Skip to main content
summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
Diffstat (limited to 'bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt')
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/BindingKey.java108
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/BufferChangedEvent.java121
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/CompletionContext.java238
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/CompletionFlags.java40
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/CompletionProposal.java2008
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/CompletionRequestor.java296
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/CorrectionEngine.java463
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ElementChangedEvent.java105
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/Flags.java230
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IAccessRule.java110
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IBuffer.java261
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IBufferChangedListener.java35
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IBufferFactory.java39
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IClassFile.java63
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ICodeAssist.java127
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ICorrectionRequestor.java137
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IElementChangedListener.java34
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IField.java64
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IFunction.java168
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IFunctionContainer.java88
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IImportContainer.java38
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IImportDeclaration.java51
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IIncludePathAttribute.java93
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IIncludePathEntry.java395
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IInitializer.java26
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJarEntryResource.java77
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJavaScriptElement.java382
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJavaScriptElementDelta.java375
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJavaScriptModel.java260
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJavaScriptModelMarker.java111
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJavaScriptModelStatus.java78
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJavaScriptModelStatusConstants.java319
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJavaScriptProject.java857
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJavaScriptUnit.java753
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJsGlobalScopeContainer.java140
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJsGlobalScopeContainerInitializer.java186
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ILocalVariable.java59
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ILookupScope.java45
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IMember.java156
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IOpenable.java193
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IPackageFragment.java202
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IPackageFragmentRoot.java432
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IParent.java45
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IProblemRequestor.java58
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IRegion.java72
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ISourceManipulation.java118
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ISourceRange.java43
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ISourceReference.java61
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IType.java722
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ITypeHierarchy.java180
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ITypeHierarchyChangedListener.java34
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ITypeRoot.java103
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/JSDScopeUtil.java86
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/JavaScriptConventions.java729
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/JavaScriptCore.java4116
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/JavaScriptModelException.java176
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/JsGlobalScopeContainerInitializer.java321
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/JsGlobalScopeVariableInitializer.java56
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/LibrarySuperType.java196
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/Messages.java34
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/NamingConventions.java949
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/Signature.java1644
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ToolFactory.java247
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/UnimplementedException.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/WorkingCopyOwner.java141
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ASTVisitor.java563
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IAND_AND_Expression.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IASTNode.java145
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IAbstractFunctionDeclaration.java79
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IAbstractVariableDeclaration.java53
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IAllocationExpression.java33
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IArgument.java33
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IArrayAllocationExpression.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IArrayInitializer.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IArrayQualifiedTypeReference.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IArrayReference.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IArrayTypeReference.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IAssignment.java54
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IBinaryExpression.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IBlock.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IBranchStatement.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IBreakStatement.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ICaseStatement.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ICombinedBinaryExpression.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ICompoundAssignment.java29
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IConditionalExpression.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IConstructorDeclaration.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IContinueStatement.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IDebuggerStatement.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IDoStatement.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IDoubleLiteral.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IEmptyExpression.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IEmptyStatement.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IEqualExpression.java29
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IExplicitConstructorCall.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IExpression.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IExtendedStringLiteral.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IFalseLiteral.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IFieldDeclaration.java26
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IFieldReference.java29
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IForInStatement.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IForStatement.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IForeachStatement.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IFunctionCall.java30
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IFunctionDeclaration.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IFunctionExpression.java33
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IIfStatement.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IImportReference.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IInitializer.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IInstanceOfExpression.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IIntLiteral.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IIntLiteralMinValue.java24
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDoc.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocAllocationExpression.java24
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocArgumentExpression.java24
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocArrayQualifiedTypeReference.java24
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocArraySingleTypeReference.java24
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocFieldReference.java23
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocImplicitTypeReference.java24
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocMessageSend.java24
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocQualifiedTypeReference.java25
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocReturnStatement.java24
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocSingleNameReference.java24
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocSingleTypeReference.java24
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ILabeledStatement.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IListExpression.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ILiteral.java29
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ILocalDeclaration.java37
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IMagicLiteral.java24
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/INameReference.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/INullLiteral.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/INumberLiteral.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IOR_OR_Expression.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IObjectLiteral.java33
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IObjectLiteralField.java30
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IOperatorExpression.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IPostfixExpression.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IPrefixExpression.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IProgramElement.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IQualifiedAllocationExpression.java24
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IQualifiedNameReference.java24
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IQualifiedThisReference.java24
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IQualifiedTypeReference.java24
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IReference.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IRegExLiteral.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IReturnStatement.java30
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IScriptFileDeclaration.java44
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ISingleNameReference.java29
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ISingleTypeReference.java26
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IStatement.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IStringLiteral.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IStringLiteralConcatenation.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ISubRoutineStatement.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ISuperReference.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ISwitchStatement.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IThisReference.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IThrowStatement.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ITrueLiteral.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ITryStatement.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ITypeDeclaration.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ITypeReference.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IUnaryExpression.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IUndefinedLiteral.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IWhileStatement.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IWithStatement.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/BuildContext.java133
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/CategorizedProblem.java153
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/CharOperation.java3433
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/IProblem.java719
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/IScanner.java154
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/ITerminalSymbols.java166
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/InvalidInputException.java43
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/ReconcileContext.java198
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/ValidationParticipant.java109
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/libraries/LibraryLocation.java49
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/libraries/SystemLibraryLocation.java212
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/AST.java2372
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ASTConverter.java4504
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ASTMatcher.java2083
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ASTNode.java2635
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ASTParser.java1161
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ASTRecoveryPropagator.java382
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ASTRequestor.java122
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ASTSyntaxErrorPropagator.java134
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ASTVisitor.java2212
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/AbstractTypeDeclaration.java242
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/AnonymousClassDeclaration.java191
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ArrayAccess.java270
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ArrayCreation.java315
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ArrayInitializer.java161
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ArrayType.java247
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Assignment.java439
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/BindingComparator.java219
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/BindingResolver.java787
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Block.java169
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/BlockComment.java130
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/BodyDeclaration.java255
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/BooleanLiteral.java178
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/BreakStatement.java188
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/CatchClause.java266
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/CharacterLiteral.java389
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ChildListPropertyDescriptor.java100
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ChildPropertyDescriptor.java116
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ClassInstanceCreation.java607
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Comment.java132
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ConditionalExpression.java332
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ConstructorInvocation.java247
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ContinueStatement.java188
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/DefaultASTVisitor.java533
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/DefaultBindingResolver.java1595
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/DefaultCommentMapper.java650
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/DoStatement.java276
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/DocCommentParser.java696
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/EmptyExpression.java91
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/EmptyStatement.java119
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/EnhancedForStatement.java331
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Expression.java143
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ExpressionStatement.java207
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FieldAccess.java316
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FieldDeclaration.java372
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ForInStatement.java331
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ForStatement.java363
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FunctionBinding.java357
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FunctionDeclaration.java871
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FunctionExpression.java206
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FunctionInvocation.java403
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FunctionRef.java320
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FunctionRefParameter.java360
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IBinding.java265
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IDocElement.java25
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IExtendedModifier.java37
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IFunctionBinding.java197
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IPackageBinding.java75
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ITypeBinding.java612
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IVariableBinding.java158
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IfStatement.java351
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ImportDeclaration.java411
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/InferredType.java97
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/InfixExpression.java546
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Initializer.java315
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/InstanceofExpression.java265
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/InternalASTRewrite.java236
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/JSdoc.java322
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/JavaScriptUnit.java1056
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/JavaScriptUnitBinding.java749
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/JavaScriptUnitResolver.java931
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/LabeledStatement.java278
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/LineComment.java129
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ListExpression.java157
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/MemberRef.java275
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Message.java137
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Modifier.java706
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/NaiveASTFlattener.java1392
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Name.java121
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/NodeEventHandler.java193
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/NodeSearcher.java107
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/NullLiteral.java120
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/NumberLiteral.java225
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ObjectLiteral.java151
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ObjectLiteralField.java261
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/PackageBinding.java162
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/PackageDeclaration.java352
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ParenthesizedExpression.java202
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/PostfixExpression.java332
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/PrefixExpression.java350
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/PrimitiveType.java316
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ProgramElement.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/QualifiedName.java284
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/QualifiedType.java288
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/RecoveredTypeBinding.java580
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/RecoveredVariableBinding.java130
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/RegularExpressionLiteral.java213
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ReturnStatement.java189
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SimpleName.java292
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SimplePropertyDescriptor.java86
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SimpleType.java201
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SingleVariableDeclaration.java641
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Statement.java213
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/StringLiteral.java347
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/StructuralPropertyDescriptor.java145
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SuperConstructorInvocation.java322
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SuperFieldAccess.java282
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SuperMethodInvocation.java401
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SwitchCase.java224
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SwitchStatement.java252
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TagElement.java403
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TextElement.java201
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ThisExpression.java191
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ThrowStatement.java203
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TryStatement.java301
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Type.java146
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TypeBinding.java824
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TypeDeclaration.java635
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TypeDeclarationStatement.java361
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TypeLiteral.java203
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/UndefinedLiteral.java120
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/VariableBinding.java283
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/VariableDeclaration.java200
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/VariableDeclarationExpression.java438
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/VariableDeclarationFragment.java337
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/VariableDeclarationStatement.java491
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/WhileStatement.java278
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/WithStatement.java278
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/rewrite/ASTRewrite.java653
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/rewrite/ITrackedNodePosition.java46
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/rewrite/ImportRewrite.java1030
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/rewrite/ListRewrite.java417
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/rewrite/TargetSourceRangeComputer.java137
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/eval/ICodeSnippetRequestor.java177
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/eval/IEvaluationContext.java385
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/eval/IGlobalVariable.java52
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/formatter/CodeFormatter.java108
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/formatter/CodeFormatterApplication.java400
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/formatter/DefaultCodeFormatterConstants.java3640
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/formatter/IndentManipulation.java429
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/formatter/messages.properties41
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/DefaultInferrenceProvider.java55
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/IInferEngine.java54
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/IInferenceFile.java38
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/ImportRewriteSupport.java56
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferEngine.java2151
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferOptions.java131
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferredAttribute.java76
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferredMember.java43
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferredMethod.java76
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferredType.java469
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferrenceManager.java190
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferrenceProvider.java73
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferrenceSupportExtension.java25
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/RefactoringSupport.java46
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/ResolutionConfiguration.java46
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/messages.properties11
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/FieldDeclarationMatch.java43
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/FieldReferenceMatch.java74
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/IJavaScriptSearchConstants.java175
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/IJavaScriptSearchScope.java96
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/LocalVariableDeclarationMatch.java44
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/LocalVariableReferenceMatch.java73
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/MethodDeclarationMatch.java44
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/MethodReferenceMatch.java113
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/PackageReferenceMatch.java46
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/SearchDocument.java143
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/SearchEngine.java631
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/SearchMatch.java380
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/SearchParticipant.java235
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/SearchPattern.java1921
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/SearchRequestor.java99
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/TypeDeclarationMatch.java45
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/TypeNameMatch.java160
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/TypeNameMatchRequestor.java52
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/TypeNameRequestor.java59
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/TypeReferenceMatch.java99
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/util/IModifierConstants.java40
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/util/JavaScriptUnitSorter.java346
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/util/SequenceReader.java100
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/CompletionEngine.java7584
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/ISearchRequestor.java67
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/ISelectionRequestor.java265
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/InternalCompletionContext.java67
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/InternalCompletionProposal.java205
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/MissingTypesGuesser.java440
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/RelevanceConstants.java42
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/SelectionEngine.java1301
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/ThrownExceptionFinder.java129
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/UnresolvedReferenceNameFinder.java552
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionJavadoc.java221
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionJavadocParser.java850
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionNodeDetector.java288
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionNodeFound.java44
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnArgumentName.java58
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnBrankStatementLabel.java52
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnClassLiteralAccess.java63
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnExplicitConstructorCall.java84
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnFieldName.java43
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnFieldType.java56
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnImportReference.java51
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnJavadoc.java37
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnJavadocAllocationExpression.java103
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnJavadocFieldReference.java142
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnJavadocMessageSend.java102
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnJavadocParamNameReference.java60
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnJavadocQualifiedTypeReference.java98
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnJavadocSingleTypeReference.java95
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnJavadocTag.java167
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnKeyword.java18
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnKeyword1.java47
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnKeyword2.java36
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnKeyword3.java43
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnLocalName.java51
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnMemberAccess.java118
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnMessageSend.java73
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnMessageSendName.java51
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnMethodName.java46
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnQualifiedAllocationExpression.java74
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnQualifiedNameReference.java89
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnQualifiedType.java69
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnQualifiedTypeReference.java104
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnSingleNameReference.java77
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnSingleTypeName.java47
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnSingleTypeReference.java140
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnStringLiteral.java62
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionParser.java3331
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionScanner.java784
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/InvalidCursorLocation.java32
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/impl/AssistOptions.java237
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/impl/AssistParser.java1314
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/impl/Engine.java364
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/impl/Keywords.java65
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionJavadoc.java142
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionJavadocParser.java192
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionNodeFound.java31
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnArgumentName.java50
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnExplicitConstructorCall.java74
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnFieldReference.java64
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnFieldType.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnImportReference.java48
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnLocalName.java45
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnMessageSend.java82
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnPackageReference.java46
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnQualifiedAllocationExpression.java79
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnQualifiedNameReference.java87
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnQualifiedType.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnQualifiedTypeReference.java64
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnSingleNameReference.java113
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnSingleType.java20
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnSingleTypeReference.java63
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnSuperReference.java58
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionParser.java690
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionScanner.java67
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ASTVisitor.java879
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/CompilationResult.java464
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/Compiler.java713
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/DefaultErrorHandlingPolicies.java75
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/DelegateASTVisitor.java866
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ICompilerRequestor.java22
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/IDebugRequestor.java42
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/IErrorHandlingPolicy.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/IProblemFactory.java42
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ISourceElementRequestor.java142
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/SourceElementParser.java1451
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/SourceJavadocParser.java94
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/AND_AND_Expression.java86
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ASTNode.java487
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/AbstractMethodDeclaration.java421
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/AbstractVariableDeclaration.java162
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/AllocationExpression.java221
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Argument.java158
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ArrayAllocationExpression.java121
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ArrayInitializer.java177
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ArrayQualifiedTypeReference.java104
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ArrayReference.java109
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ArrayTypeReference.java95
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Assignment.java258
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/BinaryExpression.java383
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Block.java125
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/BranchStatement.java39
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/BreakStatement.java101
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/CaseStatement.java117
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ClassLiteralAccess.java73
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Clinit.java126
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/CombinedBinaryExpression.java247
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/CompilationUnitDeclaration.java696
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/CompoundAssignment.java180
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ConditionalExpression.java303
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ConstructorDeclaration.java282
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ContinueStatement.java105
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/DebuggerStatement.java64
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/DoStatement.java151
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/DoubleLiteral.java105
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/EmptyExpression.java42
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/EmptyStatement.java64
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/EqualExpression.java234
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ExplicitConstructorCall.java327
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Expression.java668
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ExtendedStringLiteral.java62
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/FalseLiteral.java45
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/FieldDeclaration.java229
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/FieldReference.java578
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ForInStatement.java209
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ForStatement.java304
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ForeachStatement.java258
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/FunctionExpression.java82
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/IfStatement.java213
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ImportReference.java105
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Initializer.java107
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/InstanceOfExpression.java90
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/IntLiteral.java154
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/IntLiteralMinValue.java35
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Javadoc.java687
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocAllocationExpression.java170
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocArgumentExpression.java112
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocArrayQualifiedTypeReference.java55
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocArraySingleTypeReference.java53
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocFieldReference.java162
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocImplicitTypeReference.java119
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocMessageSend.java249
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocQualifiedTypeReference.java92
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocReturnStatement.java79
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocSingleNameReference.java98
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocSingleTypeReference.java104
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/LabeledStatement.java122
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ListExpression.java108
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Literal.java65
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/LocalDeclaration.java332
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/MagicLiteral.java36
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/MessageSend.java472
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/MethodDeclaration.java184
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/NameReference.java101
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/NullLiteral.java59
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/NumberLiteral.java43
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/OR_OR_Expression.java89
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ObjectGetterSetterField.java101
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ObjectLiteral.java106
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ObjectLiteralField.java90
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/OperatorExpression.java1733
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/OperatorIds.java50
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/PostfixExpression.java55
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/PrefixExpression.java62
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ProgramElement.java35
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/QualifiedAllocationExpression.java278
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/QualifiedNameReference.java554
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/QualifiedThisReference.java119
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/QualifiedTypeReference.java136
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Reference.java41
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/RegExLiteral.java94
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ReturnStatement.java176
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/SingleNameReference.java516
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/SingleTypeReference.java90
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Statement.java81
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/StringLiteral.java110
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/StringLiteralConcatenation.java85
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/SubRoutineStatement.java37
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/SuperReference.java74
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/SwitchStatement.java220
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ThisReference.java110
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ThrowStatement.java62
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/TrueLiteral.java45
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/TryStatement.java449
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/TypeDeclaration.java983
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/TypeReference.java179
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/UnaryExpression.java171
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/UndefinedLiteral.java57
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/WhileStatement.java160
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/WithStatement.java87
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/batch/ClasspathFile.java158
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/batch/ClasspathLocation.java68
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/batch/ClasspathMetadataFile.java127
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/batch/CompilationUnit.java109
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/batch/FileFinder.java41
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/batch/FileSystem.java384
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/batch/Main.java3892
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/batch/messages.properties290
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/classfmt/ClassFileConstants.java108
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/AccessRestriction.java50
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/AccessRule.java71
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/AccessRuleSet.java118
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/ClassSignature.java38
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/IBinaryField.java50
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/IBinaryMethod.java73
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/IBinaryNestedType.java38
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/IBinaryType.java113
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/ICompilationUnit.java49
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/IDependent.java44
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/IGenericField.java23
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/IGenericMethod.java29
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/IGenericType.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/INameEnvironment.java74
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/ISourceField.java47
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/ISourceImport.java32
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/ISourceMethod.java44
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/ISourceType.java84
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/NameEnvironmentAnswer.java138
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/ConditionalFlowInfo.java217
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/ExceptionHandlingFlowContext.java196
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/FinallyFlowContext.java282
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/FlowContext.java597
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/FlowInfo.java389
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/InitializationFlowContext.java98
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/InsideSubRoutineFlowContext.java58
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/LabelFlowContext.java51
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/LoopingFlowContext.java421
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/NullInfoRegistry.java377
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/SwitchFlowContext.java47
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/UnconditionalFlowInfo.java1713
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/BooleanConstant.java43
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/CharConstant.java56
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/CompilerOptions.java1325
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/Constant.java1336
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/DoubleConstant.java67
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/FloatConstant.java64
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/ITypeRequestor.java46
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/ITypeRequestor2.java24
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/IntConstant.java99
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/LongConstant.java58
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/ReferenceContext.java26
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/ShortConstant.java53
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/StringConstant.java46
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ArrayBinding.java270
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/BaseTypeBinding.java207
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/BinaryTypeBinding.java775
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/Binding.java84
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/BlockScope.java816
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ClassScope.java814
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/CombinedSourceTypeBinding.java182
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/CompilationUnitBinding.java167
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/CompilationUnitScope.java1180
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ExtraCompilerModifiers.java39
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/FieldBinding.java268
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/FunctionTypeBinding.java149
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/GlobalBinding.java199
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ImportBinding.java46
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ImportConflictBinding.java29
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/IndirectMethodBinding.java22
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/InnerEmulationDependency.java22
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/InvocationSite.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/LibraryAPIsBinding.java91
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/LibraryAPIsScope.java139
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/LocalFunctionBinding.java25
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/LocalTypeBinding.java185
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/LocalVariableBinding.java248
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/LookupEnvironment.java1009
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MemberTypeBinding.java35
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/Messages.java32
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MetatdataTypeBinding.java965
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MethodBinding.java628
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MethodScope.java410
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MethodVerifier.java499
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MissingBinaryTypeBinding.java57
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MultipleTypeBinding.java175
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/NestedTypeBinding.java32
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/PackageBinding.java276
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ProblemBinding.java55
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ProblemFieldBinding.java36
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ProblemMethodBinding.java42
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ProblemReasons.java25
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ProblemReferenceBinding.java50
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ReferenceBinding.java819
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/Scope.java2979
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/SignatureWrapper.java68
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/SourceTypeBinding.java1418
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/TagBits.java72
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/TypeBinding.java487
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/TypeConstants.java101
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/TypeIds.java128
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/UnresolvedReferenceBinding.java72
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/UpdatedMethodBinding.java25
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/VariableBinding.java42
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/WithScope.java24
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/messages.properties63
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/AbstractCommentParser.java1511
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/JavadocParser.java1131
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/JavadocTagConstants.java284
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/NLSTag.java30
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/Parser.java7102
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/ParserBasicInformation.java38
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredBlock.java409
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredElement.java328
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredField.java190
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredImport.java62
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredInitializer.java234
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredLocalVariable.java114
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredMethod.java455
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredStatement.java103
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredType.java510
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredUnit.java325
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveryScanner.java241
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveryScannerData.java73
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/Scanner.java4400
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/ScannerHelper.java355
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/SourceTypeConverter.java862
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/TerminalTokens.java157
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/UpdateParserFiles.java30
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/diagnose/DiagnoseParser.java2530
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/diagnose/LexStream.java291
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/diagnose/RangeUtil.java179
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser1.rscbin15180 -> 0 bytes
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser10.rscbin114 -> 0 bytes
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser11.rscbin114 -> 0 bytes
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser12.rscbin114 -> 0 bytes
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser13.rscbin114 -> 0 bytes
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser14.rscbin536 -> 0 bytes
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser15.rscbin522 -> 0 bytes
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser16.rscbin1118 -> 0 bytes
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser17.rscbin399 -> 0 bytes
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser18.rscbin6041 -> 0 bytes
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser19.rsc1
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser2.rscbin14382 -> 0 bytes
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser20.rscbin8068 -> 0 bytes
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser21.rscbin3192 -> 0 bytes
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser22.rscbin362 -> 0 bytes
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser23.rscbin62 -> 0 bytes
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser24.rscbin362 -> 0 bytes
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser25.rscbin439 -> 0 bytes
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser3.rscbin1118 -> 0 bytes
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser4.rscbin1322 -> 0 bytes
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser5.rscbin1118 -> 0 bytes
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser6.rscbin352 -> 0 bytes
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser7.rscbin242 -> 0 bytes
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser8.rscbin362 -> 0 bytes
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser9.rscbin11904 -> 0 bytes
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/part1.rscbin8192 -> 0 bytes
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/part14.rscbin8192 -> 0 bytes
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/part2.rscbin8192 -> 0 bytes
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/readableNames.properties189
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/start1.rscbin8192 -> 0 bytes
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/start2.rscbin8192 -> 0 bytes
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/AbortCompilation.java88
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/AbortCompilationUnit.java41
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/AbortMethod.java29
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/AbortType.java29
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/DefaultProblem.java289
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/DefaultProblemFactory.java206
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/ProblemHandler.java167
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/ProblemReporter.java3306
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/ProblemSeverities.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/ShouldNotImplement.java24
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/messages.properties374
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/CompoundNameVector.java71
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/FloatUtil.java421
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/GenericXMLWriter.java131
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfBinding.java105
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfInt.java98
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfIntValues.java156
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfLong.java101
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfObject.java162
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfObjectToInt.java155
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfObjectToIntArray.java155
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfPackage.java105
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfType.java105
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/Messages.java245
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/ObjectCache.java158
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/ObjectVector.java135
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/SimpleLookupTable.java167
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/SimpleNameVector.java96
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/SimpleSet.java141
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/SimpleSetOfCharArray.java143
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/SuffixConstants.java31
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/Util.java623
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ASTHolderCUInfo.java23
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BasicCompilationUnit.java162
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BatchOperation.java64
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BecomeWorkingCopyOperation.java75
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BinaryField.java124
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BinaryMember.java132
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BinaryMethod.java620
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BinaryType.java882
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BinaryTypeConverter.java236
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/Buffer.java475
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BufferCache.java76
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BufferFactoryWrapper.java55
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BufferManager.java146
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CancelableNameEnvironment.java67
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CancelableProblemFactory.java33
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ChangeClasspathOperation.java86
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ClassFile.java909
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ClassFileInfo.java171
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ClassFileWorkingCopy.java78
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ClasspathAccessRule.java56
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ClasspathAttribute.java48
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ClasspathChange.java491
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ClasspathEntry.java1688
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ClasspathValidation.java84
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CommitWorkingCopyOperation.java221
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CompilationUnit.java1404
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CompilationUnitElementInfo.java66
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CompilationUnitProblemFinder.java345
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CompilationUnitStructureRequestor.java453
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CopyElementsOperation.java262
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CopyPackageFragmentRootOperation.java274
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CopyResourceElementsOperation.java724
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreateCompilationUnitOperation.java176
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreateElementInCUOperation.java330
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreateFieldOperation.java177
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreateImportOperation.java168
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreateMethodOperation.java135
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreatePackageFragmentOperation.java157
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreateTypeHierarchyOperation.java125
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreateTypeMemberOperation.java223
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreateTypeOperation.java115
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DefaultWorkingCopyOwner.java38
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DeleteElementsOperation.java195
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DeletePackageFragmentRootOperation.java173
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DeleteResourceElementsOperation.java142
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DeltaProcessingState.java539
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DeltaProcessor.java2571
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DiscardWorkingCopyOperation.java71
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DocumentAdapter.java39
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DocumentContextFragment.java187
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DocumentContextFragmentRoot.java644
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ElementCache.java97
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ExternalJavaProject.java62
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/IJavaElementRequestor.java38
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/INamingRequestor.java18
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/IPathRequestor.java15
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/IVirtualParent.java26
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ImportContainer.java120
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ImportDeclaration.java113
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ImportDeclarationElementInfo.java22
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/Initializer.java119
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/InitializerElementInfo.java18
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/InternalNamingConventions.java423
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaCorePreferenceInitializer.java124
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaCorePreferenceModifyListener.java73
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaElement.java890
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaElementDelta.java732
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaElementDeltaBuilder.java449
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaElementInfo.java80
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaElementRequestor.java226
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaModel.java385
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaModelCache.java236
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaModelInfo.java63
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaModelManager.java4376
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaModelOperation.java899
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaModelStatus.java481
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaProject.java3227
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaProjectElementInfo.java360
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavadocConstants.java34
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/LRUCacheEnumerator.java69
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/LibraryFragmentRoot.java285
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/LibraryFragmentRootInfo.java24
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/LibraryPackageFragment.java270
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/LibraryPackageFragmentInfo.java23
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/LocalVariable.java195
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/Logger.java100
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/LookupScopeElementInfo.java219
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/Member.java396
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/MemberElementInfo.java77
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/MetadataFile.java393
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ModelUpdater.java248
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/MoveElementsOperation.java46
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/MovePackageFragmentRootOperation.java283
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/MoveResourceElementsOperation.java45
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/MultiOperation.java317
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/NameLookup.java2302
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/NamedMember.java206
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/NullBuffer.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/Openable.java484
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/OpenableElementInfo.java37
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/OverflowingLRUCache.java417
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/PackageFragment.java544
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/PackageFragmentInfo.java63
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/PackageFragmentRoot.java918
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/PackageFragmentRootInfo.java181
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ProjectReferenceChange.java103
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ReconcileWorkingCopyOperation.java283
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/Region.java150
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/RenameElementsOperation.java83
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/RenameResourceElementsOperation.java68
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ResolvedBinaryField.java60
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ResolvedBinaryMethod.java58
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ResolvedBinaryType.java66
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ResolvedSourceField.java138
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ResolvedSourceMethod.java59
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ResolvedSourceType.java66
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SearchableEnvironment.java880
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SearchableEnvironmentRequestor.java120
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SelectionRequestor.java1005
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SetClasspathOperation.java87
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SetContainerOperation.java210
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SetVariablesOperation.java193
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SimpleDelta.java124
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SingleTypeRequestor.java83
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SortElementsOperation.java342
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceConstructorInfo.java21
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceField.java170
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceFieldElementInfo.java78
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceMapper.java1305
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceMethod.java277
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceMethodElementInfo.java53
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceMethodInfo.java20
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceRange.java62
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceRefElement.java293
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceRefElementInfo.java45
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceType.java747
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceTypeElementInfo.java305
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/TypeVector.java113
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/UserLibrary.java210
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/UserLibraryJsGlobalScopeContainer.java87
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/UserLibraryJsGlobalScopeContainerInitializer.java88
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/UserLibraryManager.java276
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/VerboseElementCache.java51
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/XMLWriter.java25
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/AbortIncrementalBuildException.java26
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/AbstractImageBuilder.java667
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/AdditionalTypeCollection.java22
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/BatchImageBuilder.java137
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/BuildNotifier.java278
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ClasspathDirectory.java127
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ClasspathLibrary.java138
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ClasspathLocation.java56
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ClasspathMultiDirectory.java61
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ICompilationUnitLocator.java25
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ImageBuilderInternalException.java52
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/IncrementalImageBuilder.java752
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/JavaBuilder.java778
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/MissingSourceFileException.java24
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/NameEnvironment.java484
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/NameSet.java66
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ProblemFactory.java32
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/QualifiedNameSet.java69
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ReferenceCollection.java244
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/SourceFile.java132
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/State.java728
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/StringSet.java81
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ValidationParticipantResult.java44
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/WorkQueue.java55
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java3161
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/ASTRewriteFlattener.java1277
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/ASTRewriteFormatter.java539
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/ImportRewriteAnalyzer.java1062
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/LineCommentEndOffsets.java85
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/LineInformation.java59
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/ListRewriteEvent.java211
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/NodeInfoStore.java158
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/NodeRewriteEvent.java114
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/RewriteEvent.java79
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/RewriteEventStore.java849
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/SourceModifier.java48
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/TokenScanner.java238
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/TrackedNodePosition.java59
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/ChangeCollector.java436
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/HierarchyBinaryType.java178
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/HierarchyBuilder.java257
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/HierarchyResolver.java851
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/HierarchyType.java60
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/IndexBasedHierarchyBuilder.java530
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/RegionBasedHierarchyBuilder.java223
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/RegionBasedTypeHierarchy.java166
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/TypeHierarchy.java1220
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/index/DiskIndex.java1263
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/index/EntryResult.java79
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/index/Index.java213
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/index/MemoryIndex.java130
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/BooleanValue.java30
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/Contants.java17
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/FunctionValue.java66
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/InterpretException.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/InterpretedScript.java33
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/Interpreter.java99
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/InterpreterContext.java100
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/InterpreterEngine.java716
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/InterpreterResult.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/NativeFunction.java20
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/NativeObject.java15
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/NumberValue.java36
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/ObjectValue.java51
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/StringValue.java35
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/Value.java87
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/ValueReference.java18
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/builtin/BuiltInHelper.java22
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/builtin/BuiltInObject.java66
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/builtin/BuiltInString.java61
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/AbstractSearchScope.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/BasicSearchEngine.java1640
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/HierarchyScope.java365
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IConstructorRequestor.java40
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IRestrictedAccessBindingRequestor.java34
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IRestrictedAccessTypeRequestor.java24
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IndexQueryRequestor.java25
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IndexSelector.java223
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/JavaSearchDocument.java97
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/JavaSearchParticipant.java120
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/JavaSearchScope.java710
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/JavaSearchTypeNameMatch.java101
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/JavaWorkspaceScope.java145
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/PathCollector.java47
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/PatternSearchJob.java130
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/SubTypeSearchJob.java39
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/TypeNameMatchRequestorWrapper.java221
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/TypeNameRequestorWrapper.java47
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/AbstractIndexer.java114
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/AddFolderToIndex.java113
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/AddLibraryFileToIndex.java221
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/AddLibraryFolderToIndex.java130
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/IIndexConstants.java56
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/IndexAllProject.java259
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/IndexBinaryFolder.java199
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/IndexManager.java836
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/IndexRequest.java42
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/IndexingParser.java64
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/InternalSearchDocument.java48
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/ReadWriteMonitor.java111
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/RemoveFolderFromIndex.java78
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/RemoveFromIndex.java45
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/SaveIndex.java55
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/SourceIndexer.java116
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/SourceIndexerRequestor.java293
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/AndPattern.java86
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/ClassFileMatchLocator.java266
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/ClasspathSourceDirectory.java114
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/ConstructorDeclarationPattern.java250
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/ConstructorLocator.java358
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/ConstructorPattern.java309
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/DeclarationOfAccessedFieldsPattern.java30
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/DeclarationOfReferencedMethodsPattern.java30
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/DeclarationOfReferencedTypesPattern.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/FieldLocator.java459
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/FieldPattern.java147
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/InternalSearchPattern.java124
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/JavaSearchNameEnvironment.java202
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/JavaSearchPattern.java245
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/LocalVariableLocator.java113
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/LocalVariablePattern.java115
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MatchLocator.java2594
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MatchLocatorParser.java366
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MatchingNodeSet.java211
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MethodLocator.java634
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MethodPattern.java380
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MultiTypeDeclarationPattern.java191
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/OrLocator.java293
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/OrPattern.java109
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/PackageDeclarationLocator.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/PackageDeclarationPattern.java37
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/PackageReferenceLocator.java337
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/PackageReferencePattern.java78
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/PatternLocator.java682
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/PossibleMatch.java160
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/PossibleMatchSet.java78
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/QualifiedTypeDeclarationPattern.java123
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/SecondaryTypeDeclarationPattern.java47
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/SuperTypeNamesCollector.java304
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/SuperTypeReferenceLocator.java85
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/SuperTypeReferencePattern.java221
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/TypeDeclarationLocator.java141
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/TypeDeclarationPattern.java326
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/TypeReferenceLocator.java730
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/TypeReferencePattern.java134
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/VariableLocator.java81
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/VariablePattern.java73
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/processing/IJob.java43
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/processing/JobManager.java469
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ASTNodeFinder.java215
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/BindingKeyParser.java761
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/BindingKeyResolver.java338
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/CharArrayBuffer.java193
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/CodeSnippetParsingUtil.java204
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/CommentRecorderParser.java260
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/CommentRecorderScanner.java44
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ConvertUtility.java333
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/DOMFinder.java117
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/DefaultSourcePathProvider.java24
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/HandleFactory.java374
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/HashSetOfArray.java149
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/HashtableOfArrayToObject.java187
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ICacheEnumeration.java39
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ILRUCacheable.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/KeyKind.java105
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/KeyToSignature.java194
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/LRUCache.java525
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/MementoTokenizer.java115
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/Messages.java268
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/PublicScanner.java4245
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/RecordedParsingInformation.java39
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ReferenceInfoAdapter.java60
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ResourceCompilationUnit.java43
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/SimpleDocument.java371
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/SimpleWordSet.java68
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ToStringSorter.java75
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/Util.java2697
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/WeakHashSet.java217
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/WeakHashSetOfCharArray.java220
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/messages.properties247
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/AbortFormatting.java31
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/BinaryExpressionFragmentBuilder.java480
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/CascadingMethodInvocationFragmentBuilder.java57
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/CodeFormatterVisitor.java4783
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/DefaultCodeFormatter.java420
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/DefaultCodeFormatterOptions.java2475
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/Location.java58
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/OptimizedReplaceEdit.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/Scribe.java1800
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/align/Alignment.java417
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/align/AlignmentException.java55
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/CommentFormatterUtil.java119
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/CommentLine.java315
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/CommentRange.java262
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/CommentRegion.java573
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/HTMLEntity2JavaReader.java112
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/IBorderAttributes.java26
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/ICommentAttributes.java65
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/IHtmlTagDelimiters.java29
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/IJavaDocTagConstants.java111
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/Java2HTMLEntityReader.java56
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/JavaDocLine.java52
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/JavaDocRegion.java363
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/MultiCommentLine.java409
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/MultiCommentRegion.java245
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/SingleCommentLine.java115
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/SubstitutionTextReader.java181
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/options.properties75
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Alias.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Ancestor.java15
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Author.java35
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/ClassData.java128
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/DepreciatedOrAvailable.java19
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/DocumentedElement.java19
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Enum.java18
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Event.java32
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Exception.java32
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/IOAAMetaDataConstants.java154
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/LibraryAPIs.java78
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/MetadataReader.java880
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/MetadataSourceElementNotifier.java154
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Method.java40
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Mix.java29
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Mixin.java29
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Namespace.java29
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Option.java17
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Parameter.java32
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Property.java54
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/ReturnsData.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/VersionableElement.java18
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/AbstractVMInstall.java472
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/AbstractVMInstallType.java177
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/ExecutionArguments.java83
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IJavaLaunchConfigurationConstants.java495
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IRuntimeClasspathEntry.java332
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IRuntimeClasspathEntry2.java82
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IRuntimeClasspathEntryResolver.java101
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IRuntimeClasspathEntryResolver2.java36
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IRuntimeClasspathProvider.java87
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IVMInstall.java162
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IVMInstall2.java69
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IVMInstall3.java44
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IVMInstallChangedListener.java98
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IVMInstallType.java131
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IVMRunner.java45
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/JREContainer.java195
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/JREContainerInitializer.java301
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/JavaRuntime.java2595
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/LaunchingMessages.java61
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/LaunchingMessages.properties42
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/LibraryLocation.java164
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/ListenerList.java142
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/PropertyChangeEvent.java107
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/StandardVM.java68
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/StandardVMType.java633
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/VMRunnerConfiguration.java269
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/VMStandin.java146
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/libraries/BasicBrowserLibraryJsGlobalScopeContainerInitializer.java134
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/libraries/BasicLibraryContainer.java22
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/libraries/Messages.java37
-rw-r--r--bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/libraries/messages.properties15
1143 files changed, 0 insertions, 328812 deletions
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/BindingKey.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/BindingKey.java
deleted file mode 100644
index ef01b9c0..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/BindingKey.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core;
-
-import org.eclipse.wst.jsdt.internal.core.util.KeyToSignature;
-
-/**
- * Utility class to decode or create a binding key.
- * <p>
- * This class is not intended to be subclassed by clients.
- * </p>
- *
- * @see org.eclipse.wst.jsdt.core.dom.IBinding#getKey()
- *
- * 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 final class BindingKey {
-
- private String key;
-
- /**
- * Creates a new binding key.
- *
- * @param key the key to decode
- */
- public BindingKey(String key) {
- this.key = key;
- }
-
- /**
- * Creates a new array type binding key from the given type binding key and the given array dimension.
- * <p>
- * For example:
- * <pre>
- * <code>
- * createArrayTypeBindingKey("LObject;", 1) -> "[LObject;"
- * </code>
- * </pre>
- * </p>
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @param typeKey the binding key of the given type
- * @param arrayDimension the given array dimension
- * @return a new array type binding key
- */
- public static String createArrayTypeBindingKey(String typeKey, int arrayDimension) {
- // Note this implementation is heavily dependent on ArrayTypeBinding#computeUniqueKey()
- StringBuffer buffer = new StringBuffer();
- while (arrayDimension-- > 0)
- buffer.append('[');
- buffer.append(typeKey);
- return buffer.toString();
- }
-
- /**
- * Creates a new type binding key from the given type name.
- * <p>
- * For example:
- * <pre>
- * <code>
- * createTypeBindingKey("String") -> "LString;"
- * </code>
- * </pre>
- * </p>
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @param typeName the possibly qualified type name
- * @return a new type binding key
- */
- public static String createTypeBindingKey(String typeName) {
- // Note this implementation is heavily dependent on TypeBinding#computeUniqueKey() and its subclasses
- return Signature.createTypeSignature(typeName.replace('.', '/'), true/*resolved*/);
- }
-
- /**
- * Transforms this binding key into a resolved signature.
- * If this binding key represents a field, the returned signature is
- * the declaring type's signature.
- *
- * @return the resolved signature for this binding key
- * @see Signature
- */
- public String toSignature() {
- KeyToSignature keyToSignature = new KeyToSignature(this.key, KeyToSignature.SIGNATURE);
- keyToSignature.parse();
- return keyToSignature.signature.toString();
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return this.key;
- }
-}
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
deleted file mode 100644
index 839cbad2..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/BufferChangedEvent.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*******************************************************************************
- * 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;
-
-import java.util.EventObject;
-
-/**
- * A buffer changed event describes how a buffer has changed. These events are
- * used in <code>IBufferChangedListener</code> notifications.
- * <p>
- * For text insertions, <code>getOffset</code> is the offset
- * of the first inserted character, <code>getText</code> is the
- * inserted text, and <code>getLength</code> is 0.
- * </p>
- * <p>
- * For text removals, <code>getOffset</code> is the offset
- * of the first removed character, <code>getText</code> is <code>null</code>,
- * and <code>getLength</code> is the length of the text that was removed.
- * </p>
- * <p>
- * For replacements (including <code>IBuffer.setContents</code>),
- * <code>getOffset</code> is the offset
- * of the first replaced character, <code>getText</code> is the replacement
- * text, and <code>getLength</code> is the length of the original text
- * that was replaced.
- * </p>
- * <p>
- * When a buffer is closed, <code>getOffset</code> is 0, <code>getLength</code>
- * is 0, and <code>getText</code> is <code>null</code>.
- * </p>
- * <p>
- * This class is not intended to be instantiated or subclassed by clients.
- * Instances of this class are automatically created by the JavaScript model.
- * </p>
- *
- * @see IBuffer
- *
- * 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 BufferChangedEvent extends EventObject {
-
- /**
- * The length of text that has been modified in the buffer.
- */
- private int length;
-
- /**
- * The offset into the buffer where the modification took place.
- */
- private int offset;
-
- /**
- * The text that was modified.
- */
- private String text;
-
- private static final long serialVersionUID = 655379473891745999L; // backward compatible
-
-/**
- * Creates a new buffer changed event indicating that the given buffer has changed.
- *
- * @param buffer the given buffer
- * @param offset the given offset
- * @param length the given length
- * @param text the given text
- */
-public BufferChangedEvent(IBuffer buffer, int offset, int length, String text) {
- super(buffer);
- this.offset = offset;
- this.length = length;
- this.text = text;
-}
-/**
- * Returns the buffer which has changed.
- *
- * @return the buffer affected by the change
- */
-public IBuffer getBuffer() {
- return (IBuffer) this.source;
-}
-/**
- * Returns the length of text removed or replaced in the buffer, or
- * 0 if text has been inserted into the buffer.
- *
- * @return the length of the original text fragment modified by the
- * buffer change (<code> 0 </code> in case of insertion).
- */
-public int getLength() {
- return this.length;
-}
-/**
- * Returns the index of the first character inserted, removed, or replaced
- * in the buffer.
- *
- * @return the source offset of the textual manipulation in the buffer
- */
-public int getOffset() {
- return this.offset;
-}
-/**
- * Returns the text that was inserted, the replacement text,
- * or <code>null</code> if text has been removed.
- *
- * @return the text corresponding to the buffer change (<code> null </code>
- * in case of deletion).
- */
-public String getText() {
- return this.text;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/CompletionContext.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/CompletionContext.java
deleted file mode 100644
index 4bda7719..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/CompletionContext.java
+++ /dev/null
@@ -1,238 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core;
-
-import org.eclipse.wst.jsdt.internal.codeassist.InternalCompletionContext;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionOnJavadoc;
-
-/**
- * Completion context.
- *
- * Represent the context in which the completion occurs.
- * <p>
- * This class is not intended to be instantiated or subclassed by clients.
- * </p>
- *
- * @see CompletionRequestor#acceptContext(CompletionContext)
- *
- * 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 final class CompletionContext extends InternalCompletionContext {
-
- /**
- * The completion token is unknown.
- */
- public static final int TOKEN_KIND_UNKNOWN = 0;
-
- /**
- * The completion token is a name.
- */
- public static final int TOKEN_KIND_NAME = 1;
- /**
- * The completion token is a string literal.
- * The string literal ends quote can be not present the source.
- * <code>"foo"</code> or <code>"foo</code>.
- */
- public static final int TOKEN_KIND_STRING_LITERAL = 2;
-
- /**
- * Tell user whether completion takes place in a jsdoc comment or not.
- *
- * @return boolean true if completion takes place in a jsdoc comment, false otherwise.
- */
- public boolean isInJsdoc() {
- return this.javadoc != 0;
- }
-
- /**
- * Tell user whether completion takes place in text area of a jsdoc comment or not.
- *
- * @return boolean true if completion takes place in a text area of a jsdoc comment, false otherwise.
- */
- public boolean isInJsdocText() {
- return (this.javadoc & CompletionOnJavadoc.TEXT) != 0;
- }
-
- /**
- * Tell user whether completion takes place in a formal reference of a jsdoc tag or not.
- * Tags with formal reference are:
- * <ul>
- * <li>&#64;see</li>
- * <li>&#64;throws</li>
- * <li>&#64;exception</li>
- * <li>{&#64;link Object}</li>
- * <li>{&#64;linkplain Object}</li>
- * <li>{&#64;value} when compiler compliance is set at leats to 1.5</li>
- * </ul>
- *
- * @return boolean true if completion takes place in formal reference of a jsdoc tag, false otherwise.
- */
- public boolean isInJsdocFormalReference() {
- return (this.javadoc & CompletionOnJavadoc.FORMAL_REFERENCE) != 0;
- }
-
- /**
- * Return signatures of expected types of a potential completion proposal at the completion position.
- *
- * It's not mandatory to a completion proposal to respect this expectation.
- *
- * @return signatures expected types of a potential completion proposal at the completion position or
- * <code>null</code> if there is no expected types.
- *
- * @see Signature
- */
- public char[][] getExpectedTypesSignatures() {
- return this.expectedTypesSignatures;
- }
- /**
- * Return keys of expected types of a potential completion proposal at the completion position.
- *
- * It's not mandatory to a completion proposal to respect this expectation.
- *
- * @return keys of expected types of a potential completion proposal at the completion position or
- * <code>null</code> if there is no expected types.
- *
- * @see org.eclipse.wst.jsdt.core.dom.ASTParser#createASTs(IJavaScriptUnit[], String[], org.eclipse.wst.jsdt.core.dom.ASTRequestor, org.eclipse.core.runtime.IProgressMonitor)
- */
- public char[][] getExpectedTypesKeys() {
- return this.expectedTypesKeys;
- }
-
- /**
- * Returns the completed token.
- * This token is either the identifier or JavaScript language keyword
- * or the string literal under, immediately preceding,
- * the original request offset. If the original request offset
- * is not within or immediately after an identifier or keyword or
- * a string literal then the returned value is <code>null</code>.
- *
- * @return completed token or <code>null</code>
- */
- public char[] getToken() {
- return this.token;
- }
-
- /**
- * Returns the kind of completion token being proposed.
- * <p>
- * The set of different kinds of completion token is
- * expected to change over time. It is strongly recommended
- * that clients do <b>not</b> assume that the kind is one of the
- * ones they know about, and code defensively for the
- * possibility of unexpected future growth.
- * </p>
- *
- * @return the kind; one of the kind constants declared on
- * this class whose name starts with <code>TOKEN_KIND</code>,
- * or possibly a kind unknown to the caller
- */
- public int getTokenKind() {
- return this.tokenKind;
- }
-
- /**
- * Returns the character index of the start of the
- * subrange in the source file buffer containing the
- * relevant token being completed. This
- * token is either the identifier or JavaScript language keyword
- * under, or immediately preceding, the original request
- * offset. If the original request offset is not within
- * or immediately after an identifier or keyword, then the
- * position returned is original request offset and the
- * token range is empty.
- *
- * @return character index of token start position (inclusive)
- */
- public int getTokenStart() {
- return this.tokenStart;
- }
-
- /**
- * Returns the character index of the end (exclusive) of the subrange
- * in the source file buffer containing the
- * relevant token. When there is no relevant token, the
- * range is empty
- * (<code>getTokenEnd() == getTokenStart() - 1</code>).
- *
- * @return character index of token end position (exclusive)
- */
- public int getTokenEnd() {
- return this.tokenEnd;
- }
-
- /**
- * Returns the offset position in the source file buffer
- * after which code assist is requested.
- *
- * @return offset position in the source file buffer
- */
- public int getOffset() {
- return this.offset;
- }
-
- public String toString() {
- StringBuffer buffer = new StringBuffer();
-
- buffer.append("completion offset="); //$NON-NLS-1$
- buffer.append(this.offset);
- buffer.append('\n');
-
- buffer.append("completion range=["); //$NON-NLS-1$
- buffer.append(this.tokenStart);
- buffer.append(", "); //$NON-NLS-1$
- buffer.append(this.tokenEnd);
- buffer.append("]\n"); //$NON-NLS-1$
-
- buffer.append("completion token="); //$NON-NLS-1$
- String string = "null"; //$NON-NLS-1$
- if(token == null) {
- buffer.append(string);
- } else {
- buffer.append('\"');
- buffer.append(this.token);
- buffer.append('\"');
- }
- buffer.append('\n');
-
- buffer.append("expectedTypesSignatures="); //$NON-NLS-1$
- if(this.expectedTypesSignatures == null) {
- buffer.append(string);
- } else {
- buffer.append('{');
- for (int i = 0; i < this.expectedTypesSignatures.length; i++) {
- if(i > 0) buffer.append(',');
- buffer.append(this.expectedTypesSignatures[i]);
-
- }
- buffer.append('}');
- }
- buffer.append('\n');
-
- buffer.append("expectedTypesKeys="); //$NON-NLS-1$
- if(expectedTypesSignatures == null) {
- buffer.append(string);
- } else {
- buffer.append('{');
- for (int i = 0; i < this.expectedTypesKeys.length; i++) {
- if(i > 0) buffer.append(',');
- buffer.append(this.expectedTypesKeys[i]);
-
- }
- buffer.append('}');
- }
- buffer.append('\n');
-
- return buffer.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/CompletionFlags.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/CompletionFlags.java
deleted file mode 100644
index eda1d9ea..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/CompletionFlags.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*******************************************************************************
- * 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.core;
-
-/**
- * Utility class for decoding additional flags in completion proposal.
- * <p>
- * This class provides static methods only; it is not intended to be
- * instantiated or subclassed by clients.
- * </p>
- *
- * @see CompletionProposal#getAdditionalFlags()
- *
- *
- * 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 final class CompletionFlags {
- /**
- * Constant representing the absence of any flag
- */
- public static final int Default = 0x0000;
-
- /**
- * Not instantiable.
- */
- private CompletionFlags() {
- // Not instantiable
- }
-}
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
deleted file mode 100644
index 4b67b5a3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/CompletionProposal.java
+++ /dev/null
@@ -1,2008 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2004, 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 org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.codeassist.InternalCompletionProposal;
-
-/**
- * Completion proposal.
- * <p>
- * In typical usage, the user working in a JavaScript code editor issues
- * a code assist command. This command results in a call to
- * <code>ICodeAssist.codeComplete(position, completionRequestor)</code>
- * passing the current position in the source code. The code assist
- * engine analyzes the code in the buffer, determines what kind of
- * JavaScript language construct is at that position, and proposes ways
- * to complete that construct. These proposals are instances of
- * the class <code>CompletionProposal</code>. These proposals,
- * perhaps after sorting and filtering, are presented to the user
- * to make a choice.
- * </p>
- * <p>
- * The proposal is as follows: insert
- * the {@linkplain #getCompletion() completion string} into the
- * source file buffer, replacing the characters between
- * {@linkplain #getReplaceStart() the start}
- * and {@linkplain #getReplaceEnd() end}. The string
- * can be arbitrary; for example, it might include not only the
- * name of a function but a set of parentheses. Moreover, the source
- * range may include source positions before or after the source
- * position where <code>ICodeAssist.codeComplete</code> was invoked.
- * The rest of the information associated with the proposal is
- * to provide context that may help a user to choose from among
- * competing proposals.
- * </p>
- * <p>
- * The completion engine creates instances of this class; it is not intended
- * to be instantiated or subclassed by clients.
- * </p>
- *
- * @see ICodeAssist#codeComplete(int, CompletionRequestor)
- *
- * 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 final class CompletionProposal extends InternalCompletionProposal {
- private boolean updateCompletion = false;
-
- /**
- * Completion is a declaration of an anonymous class.
- * This kind of completion might occur in a context like
- * <code>"new List^;"</code> and complete it to
- * <code>"new List() {}"</code>.
- * <p>
- * The following additional context information is available
- * for this kind of completion proposal at little extra cost:
- * <ul>
- * <li>{@link #getDeclarationSignature()} -
- * the type signature of the type being implemented or subclassed
- * </li>
- * <li>{@link #getDeclarationKey()} -
- * the type unique key of the type being implemented or subclassed
- * </li>
- * <li>{@link #getSignature()} -
- * the method signature of the constructor that is referenced
- * </li>
- * <li>{@link #getKey()} -
- * the method unique key of the constructor that is referenced
- * if the declaring type is not an interface
- * </li>
- * <li>{@link #getFlags()} -
- * the modifiers flags of the constructor that is referenced
- * </li>
- * </ul>
- * </p>
- *
- * @see #getKind()
- */
- public static final int ANONYMOUS_CLASS_DECLARATION = 1;
-
- /**
- * Completion is a reference to a field.
- * This kind of completion might occur in a context like
- * <code>"this.ref^ = 0;"</code> and complete it to
- * <code>"this.refcount = 0;"</code>.
- * <p>
- * The following additional context information is available
- * for this kind of completion proposal at little extra cost:
- * <ul>
- * <li>{@link #getDeclarationSignature()} -
- * the type signature of the type that declares the field that is referenced
- * </li>
- * <li>{@link #getFlags()} -
- * the modifiers flags of the field that is referenced
- * </li>
- * <li>{@link #getName()} -
- * the simple name of the field that is referenced
- * </li>
- * <li>{@link #getSignature()} -
- * the type signature of the field's type (as opposed to the
- * signature of the type in which the referenced field
- * is declared)
- * </li>
- * </ul>
- * </p>
- *
- * @see #getKind()
- */
- public static final int FIELD_REF = 2;
-
- /**
- * Completion is a keyword.
- * This kind of completion might occur in a context like
- * <code>"fu Foo {}"</code> and complete it to
- * <code>"function Foo {}"</code>.
- * <p>
- * The following additional context information is available
- * for this kind of completion proposal at little extra cost:
- * <ul>
- * <li>{@link #getName()} -
- * the keyword token
- * </li>
- * <li>{@link #getFlags()} -
- * the corresponding modifier flags if the keyword is a modifier
- * </li>
- * </ul>
- * </p>
- *
- * @see #getKind()
- */
- public static final int KEYWORD = 3;
-
- /**
- * Completion is a reference to a label.
- * This kind of completion might occur in a context like
- * <code>"break lo^;"</code> and complete it to
- * <code>"break loop;"</code>.
- * <p>
- * The following additional context information is available
- * for this kind of completion proposal at little extra cost:
- * <ul>
- * <li>{@link #getName()} -
- * the simple name of the label that is referenced
- * </li>
- * </ul>
- * </p>
- *
- * @see #getKind()
- */
- public static final int LABEL_REF = 4;
-
- /**
- * Completion is a reference to a local variable.
- * This kind of completion might occur in a context like
- * <code>"ke^ = 4;"</code> and complete it to
- * <code>"keys = 4;"</code>.
- * <p>
- * The following additional context information is available
- * for this kind of completion proposal at little extra cost:
- * <ul>
- * <li>{@link #getFlags()} -
- * the modifiers flags of the local variable that is referenced
- * </li>
- * <li>{@link #getName()} -
- * the simple name of the local variable that is referenced
- * </li>
- * <li>{@link #getSignature()} -
- * the type signature of the local variable's type
- * </li>
- * </ul>
- * </p>
- *
- * @see #getKind()
- */
- public static final int LOCAL_VARIABLE_REF = 5;
-
- /**
- * Completion is a reference to a method.
- * This kind of completion might occur in a context like
- * <code>"myObject.pr^();"</code> and complete it to
- * <code>""myObject.println();"</code>.
- * <p>
- * The following additional context information is available
- * for this kind of completion proposal at little extra cost:
- * <ul>
- * <li>{@link #getDeclarationSignature()} -
- * the type signature of the type that declares the method that is referenced
- * </li>
- * <li>{@link #getFlags()} -
- * the modifiers flags of the method that is referenced
- * </li>
- * <li>{@link #getName()} -
- * the simple name of the method that is referenced
- * </li>
- * <li>{@link #getSignature()} -
- * the method signature of the method that is referenced
- * </li>
- * </ul>
- * </p>
- *
- * @see #getKind()
- */
- public static final int METHOD_REF = 6;
-
- /**
- * Completion is a declaration of a function.
- * <p>
- * The following additional context information is available
- * for this kind of completion proposal at little extra cost:
- * <ul>
- * <li>{@link #getDeclarationSignature()} -
- * the type signature of the type that declares the
- * method that is being overridden or implemented
- * </li>
- * <li>{@link #getDeclarationKey()} -
- * the unique of the type that declares the
- * method that is being overridden or implemented
- * </li>
- * <li>{@link #getName()} -
- * the simple name of the method that is being overridden
- * or implemented
- * </li>
- * <li>{@link #getSignature()} -
- * the method signature of the method that is being
- * overridden or implemented
- * </li>
- * <li>{@link #getKey()} -
- * the method unique key of the method that is being
- * overridden or implemented
- * </li>
- * <li>{@link #getFlags()} -
- * the modifiers flags of the method that is being
- * overridden or implemented
- * </li>
- * </ul>
- * </p>
- *
- * @see #getKind()
- */
- public static final int METHOD_DECLARATION = 7;
-
- /**
- * Completion is a reference to a package.
- * This kind of completion might occur in a context like
- * <code>"import java.u^.*;"</code> and complete it to
- * <code>"import java.util.*;"</code>.
- * <p>
- * The following additional context information is available
- * for this kind of completion proposal at little extra cost:
- * <ul>
- * <li>{@link #getDeclarationSignature()} -
- * the dot-based package name of the package that is referenced
- * </li>
- * </ul>
- * </p>
- *
- * <b>This completion only applies to ECMAScript 4 which is not yet supported</b>
- *
- * @see #getKind()
- */
- public static final int PACKAGE_REF = 8;
-
- /**
- * Completion is a reference to a type.
- * This kind of completion might occur in a context like
- * <code>"var c=new Str^ ;"</code> and complete it to
- * <code>"var c=new String ;"</code>.
- * <p>
- * The following additional context information is available
- * for this kind of completion proposal at little extra cost:
- * <ul>
- * <li>{@link #getDeclarationSignature()} -
- * </li>
- * <li>{@link #getSignature()} -
- * the type signature of the type that is referenced
- * </li>
- * <li>{@link #getFlags()} -
- * the modifiers flags (including Flags.AccInterface) of the type that is referenced
- * </li>
- * </ul>
- * </p>
- *
- * @see #getKind()
- */
- public static final int TYPE_REF = 9;
-
- /**
- * Completion is a declaration of a variable (locals, parameters,
- * fields, etc.).
- * <p>
- * The following additional context information is available
- * for this kind of completion proposal at little extra cost:
- * <ul>
- * <li>{@link #getName()} -
- * the simple name of the variable being declared
- * </li>
- * <li>{@link #getSignature()} -
- * the type signature of the type of the variable
- * being declared
- * </li>
- * <li>{@link #getFlags()} -
- * the modifiers flags of the variable being declared
- * </li>
- * </ul>
- * </p>
- * @see #getKind()
- */
- public static final int VARIABLE_DECLARATION = 10;
-
- /**
- * Completion is a declaration of a new potential function.
- * This kind of completion might occur in a context like
- * <p>
- * The following additional context information is available
- * for this kind of completion proposal at little extra cost:
- * <ul>
- * <li>{@link #getDeclarationSignature()} -
- * the type signature of the type that declares the
- * method that is being created
- * </li>
- * <li>{@link #getName()} -
- * the simple name of the method that is being created
- * </li>
- * <li>{@link #getSignature()} -
- * the method signature of the method that is being
- * created
- * </li>
- * <li>{@link #getFlags()} -
- * the modifiers flags of the method that is being
- * created
- * </li>
- * </ul>
- * </p>
- *
- * @see #getKind()
- */
- public static final int POTENTIAL_METHOD_DECLARATION = 11;
-
- /**
- * Completion is a reference to a function name.
- * <p>
- * The following additional context information is available
- * for this kind of completion proposal at little extra cost:
- * <ul>
- * <li>{@link #getDeclarationSignature()} -
- * the type signature of the type that declares the method that is referenced
- * </li>
- * <li>{@link #getFlags()} -
- * the modifiers flags of the method that is referenced
- * </li>
- * <li>{@link #getName()} -
- * the simple name of the method that is referenced
- * </li>
- * <li>{@link #getSignature()} -
- * the method signature of the method that is referenced
- * </li>
- * </ul>
- * </p>
- *
- * @see #getKind()
- */
- public static final int METHOD_NAME_REFERENCE = 12;
-
- /**
- * Completion is a link reference to a field in a JSdoc text.
- * This kind of completion might occur in a context like
- * <code>" * blabla System.o^ blabla"</code> and complete it to
- * <code>" * blabla {&#64;link System#out } blabla"</code>.
- * <p>
- * The following additional context information is available
- * for this kind of completion proposal at little extra cost:
- * <ul>
- * <li>{@link #getDeclarationSignature()} -
- * the type signature of the type that declares the field that is referenced
- * </li>
- * <li>{@link #getFlags()} -
- * the modifiers flags (including ACC_ENUM) of the field that is referenced
- * </li>
- * <li>{@link #getName()} -
- * the simple name of the field that is referenced
- * </li>
- * <li>{@link #getSignature()} -
- * the type signature of the field's type (as opposed to the
- * signature of the type in which the referenced field
- * is declared)
- * </li>
- * </ul>
- * </p>
- *
- * @see #getKind()
- */
- public static final int JSDOC_FIELD_REF = 14;
-
- /**
- * Completion is a link reference to a function in a JSdoc text.
- * This kind of completion might occur in a context like
- * <code>" * blabla Object#va^ blabla"</code> and complete it to
- * <code>" * blabla {&#64;link Object#valueOf() }"</code>.
- * <p>
- * The following additional context information is available
- * for this kind of completion proposal at little extra cost:
- * <ul>
- * <li>{@link #getDeclarationSignature()} -
- * the type signature of the type that declares the method that is referenced
- * </li>
- * <li>{@link #getFlags()} -
- * the modifiers flags of the method that is referenced
- * </li>
- * <li>{@link #getName()} -
- * the simple name of the method that is referenced
- * </li>
- * <li>{@link #getSignature()} -
- * the method signature of the method that is referenced
- * </li>
- * </ul>
- * </p>
- *
- * @see #getKind()
- */
- public static final int JSDOC_METHOD_REF = 15;
-
- /**
- * Completion is a link reference to a type in a JSdoc text.
- * Any kind of type is allowed, including primitive types, reference types,
- * array types, parameterized types, and type variables.
- * This kind of completion might occur in a context like
- * <code>" * blabla Str^ blabla"</code> and complete it to
- * <code>" * blabla {&#64;link String } blabla"</code>.
- * <p>
- * The following additional context information is available
- * for this kind of completion proposal at little extra cost:
- * <ul>
- * <li>{@link #getDeclarationSignature()} -
- * the dot-based package name of the package that contains
- * the type that is referenced
- * </li>
- * <li>{@link #getSignature()} -
- * the type signature of the type that is referenced
- * </li>
- * <li>{@link #getFlags()} -
- * the modifiers flags of the type that is referenced
- * </li>
- * </ul>
- * </p>
- *
- * @see #getKind()
- */
- public static final int JSDOC_TYPE_REF = 16;
-
- /**
- * Completion is a method argument or a class/method type parameter
- * in JSdoc param tag.
- * <p>
- * The following additional context information is available
- * for this kind of completion proposal at little extra cost:
- * <ul>
- * <li>{@link #getDeclarationSignature()} -
- * the type signature of the type that declares the field that is referenced
- * </li>
- * <li>{@link #getFlags()} -
- * the modifiers flags (including ACC_ENUM) of the field that is referenced
- * </li>
- * <li>{@link #getName()} -
- * the simple name of the field that is referenced
- * </li>
- * <li>{@link #getSignature()} -
- * the type signature of the field's type (as opposed to the
- * signature of the type in which the referenced field
- * is declared)
- * </li>
- * </ul>
- * </p>
- *
- * <b>This field only applies to ECMAScript 4 which is not yet supported</b>
- *
- * @see #getKind()
- */
- public static final int JSDOC_PARAM_REF = 18;
-
- /**
- * Completion is a JSdoc block tag.
- * This kind of completion might occur in a context like
- * <code>" * @s^ blabla"</code> and complete it to
- * <code>" * @see blabla"</code>.
- * <p>
- * The following additional context information is available
- * for this kind of completion proposal at little extra cost:
- * <ul>
- * <li>{@link #getDeclarationSignature()} -
- * the type signature of the type that declares the field that is referenced
- * </li>
- * <li>{@link #getFlags()} -
- * the modifiers flags of the field that is referenced
- * </li>
- * <li>{@link #getName()} -
- * the simple name of the field that is referenced
- * </li>
- * <li>{@link #getSignature()} -
- * the type signature of the field's type (as opposed to the
- * signature of the type in which the referenced field
- * is declared)
- * </li>
- * </ul>
- * </p>
- *
- * @see #getKind()
- */
- public static final int JSDOC_BLOCK_TAG = 19;
-
- /**
- * Completion is a JSdoc inline tag.
- * This kind of completion might occur in a context like
- * <code>" * Insert @l^ Object"</code> and complete it to
- * <code>" * Insert {&#64;link Object }"</code>.
- * <p>
- * The following additional context information is available
- * for this kind of completion proposal at little extra cost:
- * <ul>
- * <li>{@link #getDeclarationSignature()} -
- * the type signature of the type that declares the field that is referenced
- * </li>
- * <li>{@link #getFlags()} -
- * the modifiers flags of the field that is referenced
- * </li>
- * <li>{@link #getName()} -
- * the simple name of the field that is referenced
- * </li>
- * <li>{@link #getSignature()} -
- * the type signature of the field's type (as opposed to the
- * signature of the type in which the referenced field
- * is declared)
- * </li>
- * </ul>
- * </p>
- *
- * @see #getKind()
- */
- public static final int JSDOC_INLINE_TAG = 20;
-
- /**
- * Completion is an import of reference to a static field.
- * <p>
- * The following additional context information is available
- * for this kind of completion proposal at little extra cost:
- * <ul>
- * <li>{@link #getDeclarationSignature()} -
- * the type signature of the type that declares the field that is imported
- * </li>
- * <li>{@link #getFlags()} -
- * the modifiers flags (including ACC_ENUM) of the field that is imported
- * </li>
- * <li>{@link #getName()} -
- * the simple name of the field that is imported
- * </li>
- * <li>{@link #getSignature()} -
- * the type signature of the field's type (as opposed to the
- * signature of the type in which the referenced field
- * is declared)
- * </li>
- * <li>{@link #getAdditionalFlags()} -
- * the completion flags (including ComletionFlags.StaticImport)
- * of the proposed import
- * </li>
- * </ul>
- * </p>
- *
- * @see #getKind()
- *
- */
- public static final int FIELD_IMPORT = 21;
-
- /**
- * Completion is an import of reference to a static method.
- * <p>
- * The following additional context information is available
- * for this kind of completion proposal at little extra cost:
- * <ul>
- * <li>{@link #getDeclarationSignature()} -
- * the type signature of the type that declares the method that is imported
- * </li>
- * <li>{@link #getFlags()} -
- * the modifiers flags of the method that is imported
- * </li>
- * <li>{@link #getName()} -
- * the simple name of the method that is imported
- * </li>
- * <li>{@link #getSignature()} -
- * the method signature of the method that is imported
- * </li>
- * <li>{@link #getAdditionalFlags()} -
- * the completion flags (including ComletionFlags.StaticImport)
- * of the proposed import
- * </li>
- * </ul>
- * </p>
- *
- * @see #getKind()
- *
- */
- public static final int METHOD_IMPORT = 22;
-
- /**
- * Completion is an import of reference to a type.
- * Only reference to reference types are allowed.
- * <p>
- * The following additional context information is available
- * for this kind of completion proposal at little extra cost:
- * <ul>
- * <li>{@link #getDeclarationSignature()} -
- * the dot-based package name of the package that contains
- * the type that is imported
- * </li>
- * <li>{@link #getSignature()} -
- * the type signature of the type that is imported
- * </li>
- * <li>{@link #getFlags()} -
- * the modifiers flags (including Flags.AccInterface, AccEnum,
- * and AccAnnotation) of the type that is imported
- * </li>
- * <li>{@link #getAdditionalFlags()} -
- * the completion flags (including ComletionFlags.StaticImport)
- * of the proposed import
- * </li>
- * </ul>
- * </p>
- *
- * @see #getKind()
- *
- */
- public static final int TYPE_IMPORT = 23;
-
- /**
- * Completion is a reference to a constructor.
- * This kind of completion might occur in a context like
- * <code>"new Lis"</code> and complete it to
- * <code>"new List();"</code> if List is a class that is not abstract.
- * <p>
- * The following additional context information is available
- * for this kind of completion proposal at little extra cost:
- * <ul>
- * <li>{@link #getDeclarationSignature()} -
- * the type signature of the type that declares the constructor that is referenced
- * </li>
- * <li>{@link #getFlags()} -
- * the modifiers flags of the constructor that is referenced
- * </li>
- * <li>{@link #getName()} -
- * the simple name of the constructor that is referenced
- * </li>
- * <li>{@link #getSignature()} -
- * the method signature of the constructor that is referenced
- * </li>
- * </ul>
- * </p>
- * <p>
- * This kind of proposal could require a long computation, so they are computed only if completion operation is called with a {@link IProgressMonitor}
- * (e.g. {@link ICodeAssist#codeComplete(int, CompletionRequestor, IProgressMonitor)}).<br>
- * This kind of proposal is always is only proposals with a {@link #TYPE_REF} required proposal, so this kind of required proposal must be allowed:
- * <code>requestor.setAllowsRequiredProposals(CONSTRUCTOR_INVOCATION, TYPE_REF, true)</code>.
- * </p>
- *
- * @see #getKind()
- * @see CompletionRequestor#setAllowsRequiredProposals(int, int, boolean)
- */
- public static final int CONSTRUCTOR_INVOCATION = 26;
-
- /**
- * First valid completion kind.
- *
- */
- protected static final int FIRST_KIND = ANONYMOUS_CLASS_DECLARATION;
-
- /**
- * Last valid completion kind.
- *
- */
- protected static final int LAST_KIND = CONSTRUCTOR_INVOCATION;
-
- /**
- * Kind of completion request.
- */
- private int completionKind;
-
- /**
- * Offset in original buffer where ICodeAssist.codeComplete() was
- * requested.
- */
- private int completionLocation;
-
- /**
- * Start position (inclusive) of source range in original buffer
- * containing the relevant token
- * defaults to empty subrange at [0,0).
- */
- private int tokenStart = 0;
-
- /**
- * End position (exclusive) of source range in original buffer
- * containing the relevant token;
- * defaults to empty subrange at [0,0).
- */
- private int tokenEnd = 0;
-
- /**
- * Completion string; defaults to empty string.
- */
- private char[] completion = CharOperation.NO_CHAR;
-
- /**
- * Start position (inclusive) of source range in original buffer
- * to be replaced by completion string;
- * defaults to empty subrange at [0,0).
- */
- private int replaceStart = 0;
-
- /**
- * End position (exclusive) of source range in original buffer
- * to be replaced by completion string;
- * defaults to empty subrange at [0,0).
- */
- private int replaceEnd = 0;
-
- /**
- * Relevance rating; positive; higher means better;
- * defaults to minimum rating.
- */
- private int relevance = 1;
-
- /**
- * Signature of the relevant package or type declaration
- * in the context, or <code>null</code> if none.
- * Defaults to null.
- */
- private char[] declarationSignature = null;
-
- /**
- * Unique key of the relevant package or type declaration
- * in the context, or <code>null</code> if none.
- * Defaults to null.
- */
- private char[] declarationKey = null;
-
- /**
- * Simple name of the method, field,
- * member, or variable relevant in the context, or
- * <code>null</code> if none.
- * Defaults to null.
- */
- private char[] name = null;
-
- /**
- * Signature of the function, field type, member type,
- * relevant in the context, or <code>null</code> if none.
- * Defaults to null.
- */
- private char[] signature = null;
-
- /**
- * Unique of the function, field type, member type,
- * relevant in the context, or <code>null</code> if none.
- * Defaults to null.
- */
- private char[] key = null;
-
- /**
- * Array of required completion proposals, or <code>null</code> if none.
- * The proposal can not be applied if the required proposals aren't applied.
- * Defaults to <code>null</code>.
- */
- private CompletionProposal[] requiredProposals;
-
- /**
- * Modifier flags relevant in the context, or
- * <code>Flags.AccDefault</code> if none.
- * Defaults to <code>Flags.AccDefault</code>.
- */
- private int flags = Flags.AccDefault;
-
- /**
- * Completion flags relevant in the context, or
- * <code>CompletionFlags.Default</code> if none.
- * Defaults to <code>CompletionFlags.Default</code>.
- */
- private int additionalFlags = CompletionFlags.Default;
-
- /**
- * Parameter names (for method completions), or
- * <code>null</code> if none. Lazily computed.
- * Defaults to <code>null</code>.
- */
- private char[][] parameterNames = null;
-
- /**
- * Indicates whether parameter names have been computed.
- */
- private boolean parameterNamesComputed = false;
-
- /**
- * Creates a basic completion proposal. All instance
- * field have plausible default values unless otherwise noted.
- * <p>
- * Note that the constructors for this class are internal to the
- * JavaScript model implementation. Clients cannot directly create
- * CompletionProposal objects.
- * </p>
- *
- * @param kind one of the kind constants declared on this class
- * @param completionOffset original offset of code completion request
- * @return a new completion proposal
- */
- public static CompletionProposal create(int kind, int completionOffset) {
- return new CompletionProposal(kind, completionOffset);
- }
-
- /**
- * Creates a basic completion proposal. All instance
- * field have plausible default values unless otherwise noted.
- * <p>
- * Note that the constructors for this class are internal to the
- * JavaScript model implementation. Clients cannot directly create
- * CompletionProposal objects.
- * </p>
- *
- * @param kind one of the kind constants declared on this class
- * @param completionLocation original offset of code completion request
- */
- CompletionProposal(int kind, int completionLocation) {
- if ((kind < CompletionProposal.FIRST_KIND)
- || (kind > CompletionProposal.LAST_KIND)) {
- throw new IllegalArgumentException();
- }
- if (this.completion == null || completionLocation < 0) {
- // Work around for bug 132558 (https://bugs.eclipse.org/bugs/show_bug.cgi?id=132558).
- // completionLocation can be -1 if the completion occur at the start of a file or
- // the start of a code snippet but this API isn't design to support negative position.
- if(this.completion == null || completionLocation != -1) {
- throw new IllegalArgumentException();
- }
- completionLocation = 0;
- }
- this.completionKind = kind;
- this.completionLocation = completionLocation;
- }
-
- /**
- * Returns the completion flags relevant in the context, or
- * <code>CompletionFlags.Default</code> if none.
- * <p>
- * This field is available for the following kinds of
- * completion proposals:
- * <ul>
- * <li><code>FIELD_IMPORT</code> - completion flags
- * of the attribute that is referenced. Completion flags for
- * this proposal kind can only include <code>CompletionFlags.StaticImport</code></li>
- * <li><code>METHOD_IMPORT</code> - completion flags
- * of the attribute that is referenced. Completion flags for
- * this proposal kind can only include <code>CompletionFlags.StaticImport</code></li>
- * <li><code>TYPE_IMPORT</code> - completion flags
- * of the attribute that is referenced. Completion flags for
- * this proposal kind can only include <code>CompletionFlags.StaticImport</code></li>
- * </ul>
- * For other kinds of completion proposals, this method returns
- * <code>CompletionFlags.Default</code>.
- * </p>
- *
- * @return the completion flags, or
- * <code>CompletionFlags.Default</code> if none
- * @see CompletionFlags
- *
- */
- public int getAdditionalFlags() {
- return this.additionalFlags;
- }
-
- /**
- * Sets the completion flags relevant in the context.
- * <p>
- * If not set, defaults to none.
- * </p>
- * <p>
- * The completion engine creates instances of this class and sets
- * its properties; this method is not intended to be used by other clients.
- * </p>
- *
- * @param additionalFlags the completion flags, or
- * <code>CompletionFlags.Default</code> if none
- *
- */
- public void setAdditionalFlags(int additionalFlags) {
- this.additionalFlags = additionalFlags;
- }
-
- /**
- * Returns the kind of completion being proposed.
- * <p>
- * The set of different kinds of completion proposals is
- * expected to change over time. It is strongly recommended
- * that clients do <b>not</b> assume that the kind is one of the
- * ones they know about, and code defensively for the
- * possibility of unexpected future growth.
- * </p>
- *
- * @return the kind; one of the kind constants
- * declared on this class, or possibly a kind unknown
- * to the caller
- */
- public int getKind() {
- return this.completionKind;
- }
-
- /**
- * Returns the character index in the source file buffer
- * where source completion was requested (the
- * <code>offset</code> parameter to
- * <code>ICodeAssist.codeComplete</code> minus one).
- *
- * @return character index in source file buffer
- * @see ICodeAssist#codeComplete(int,CompletionRequestor)
- */
- // TODO (david) https://bugs.eclipse.org/bugs/show_bug.cgi?id=132558
- public int getCompletionLocation() {
- return this.completionLocation;
- }
-
- /**
- * Returns the character index of the start of the
- * subrange in the source file buffer containing the
- * relevant token being completed. This
- * token is either the identifier or JavaScript language keyword
- * under, or immediately preceding, the original request
- * offset. If the original request offset is not within
- * or immediately after an identifier or keyword, then the
- * position returned is original request offset and the
- * token range is empty.
- *
- * @return character index of token start position (inclusive)
- */
- public int getTokenStart() {
- return this.tokenStart;
- }
-
- /**
- * Returns the character index of the end (exclusive) of the subrange
- * in the source file buffer containing the
- * relevant token. When there is no relevant token, the
- * range is empty
- * (<code>getEndToken() == getStartToken()</code>).
- *
- * @return character index of token end position (exclusive)
- */
- public int getTokenEnd() {
- return this.tokenEnd;
- }
-
- /**
- * Sets the character indices of the subrange in the
- * source file buffer containing the relevant token being
- * completed. This token is either the identifier or
- * JavaScript language keyword under, or immediately preceding,
- * the original request offset. If the original request
- * offset is not within or immediately after an identifier
- * or keyword, then the source range begins at original
- * request offset and is empty.
- * <p>
- * If not set, defaults to empty subrange at [0,0).
- * </p>
- *
- * @param startIndex character index of token start position (inclusive)
- * @param endIndex character index of token end position (exclusive)
- */
- public void setTokenRange(int startIndex, int endIndex) {
- if (startIndex < 0 || endIndex < startIndex) {
- throw new IllegalArgumentException();
- }
- this.tokenStart = startIndex;
- this.tokenEnd = endIndex;
- }
-
- /**
- * Returns the proposed sequence of characters to insert into the
- * source file buffer, replacing the characters at the specified
- * source range. The string can be arbitrary; for example, it might
- * include not only the name of a method but a set of parentheses.
- * <p>
- * The client must not modify the array returned.
- * </p>
- *
- * @return the completion string
- */
- public char[] getCompletion() {
- if(this.completionKind == METHOD_DECLARATION) {
- this.findParameterNames(null);
- if(this.updateCompletion) {
- this.updateCompletion = false;
-
- if(this.parameterNames != null) {
- int length = this.parameterNames.length;
- StringBuffer completionBuffer = new StringBuffer(this.completion.length);
-
- int start = 0;
- int end = CharOperation.indexOf('%', this.completion);
-
- completionBuffer.append(this.completion, start, end - start);
-
- for(int i = 0 ; i < length ; i++){
- completionBuffer.append(this.parameterNames[i]);
- start = end + 1;
- end = CharOperation.indexOf('%', this.completion, start);
- if(end > -1){
- completionBuffer.append(this.completion, start, end - start);
- } else {
- completionBuffer.append(this.completion, start, this.completion.length - start);
- }
- }
- int nameLength = completionBuffer.length();
- this.completion = new char[nameLength];
- completionBuffer.getChars(0, nameLength, this.completion, 0);
- }
- }
- }
- return this.completion;
- }
-
- /**
- * Sets the proposed sequence of characters to insert into the
- * source file buffer, replacing the characters at the specified
- * source range. The string can be arbitrary; for example, it might
- * include not only the name of a method but a set of parentheses.
- * <p>
- * If not set, defaults to an empty character array.
- * </p>
- * <p>
- * The completion engine creates instances of this class and sets
- * its properties; this method is not intended to be used by other clients.
- * </p>
- *
- * @param completion the completion string
- */
- public void setCompletion(char[] completion) {
- this.completion = completion;
- }
-
- /**
- * Returns the character index of the start of the
- * subrange in the source file buffer to be replaced
- * by the completion string. If the subrange is empty
- * (<code>getReplaceEnd() == getReplaceStart()</code>),
- * the completion string is to be inserted at this
- * index.
- * <p>
- * Note that while the token subrange is precisely
- * specified, the replacement range is loosely
- * constrained and may not bear any direct relation
- * to the original request offset. For example,
- * it would be possible for a type completion to
- * propose inserting an import declaration at the
- * top of the compilation unit; or the completion
- * might include trailing parentheses and
- * punctuation for a method completion.
- * </p>
- *
- * @return replacement start position (inclusive)
- */
- public int getReplaceStart() {
- return this.replaceStart;
- }
-
- /**
- * Returns the character index of the end of the
- * subrange in the source file buffer to be replaced
- * by the completion string. If the subrange is empty
- * (<code>getReplaceEnd() == getReplaceStart()</code>),
- * the completion string is to be inserted at this
- * index.
- *
- * @return replacement end position (exclusive)
- */
- public int getReplaceEnd() {
- return this.replaceEnd;
- }
-
- /**
- * Sets the character indices of the subrange in the
- * source file buffer to be replaced by the completion
- * string. If the subrange is empty
- * (<code>startIndex == endIndex</code>),
- * the completion string is to be inserted at this
- * index.
- * <p>
- * If not set, defaults to empty subrange at [0,0).
- * </p>
- * <p>
- * The completion engine creates instances of this class and sets
- * its properties; this method is not intended to be used by other clients.
- * </p>
- *
- * @param startIndex character index of replacement start position (inclusive)
- * @param endIndex character index of replacement end position (exclusive)
- */
- public void setReplaceRange(int startIndex, int endIndex) {
- if (startIndex < 0 || endIndex < startIndex) {
- throw new IllegalArgumentException();
- }
- this.replaceStart = startIndex;
- this.replaceEnd = endIndex;
- }
-
- /**
- * Returns the relative relevance rating of this proposal.
- *
- * @return relevance rating of this proposal; ratings are positive; higher means better
- */
- public int getRelevance() {
- return this.relevance;
- }
-
- /**
- * Sets the relative relevance rating of this proposal.
- * <p>
- * If not set, defaults to the lowest possible rating (1).
- * </p>
- * <p>
- * The completion engine creates instances of this class and sets
- * its properties; this method is not intended to be used by other clients.
- * </p>
- *
- * @param rating relevance rating of this proposal; ratings are positive; higher means better
- */
- public void setRelevance(int rating) {
- if (rating <= 0) {
- throw new IllegalArgumentException();
- }
- this.relevance = rating;
- }
-
- /**
- * Returns the type signature of the relevant
- * declaration in the context, or <code>null</code> if none.
- * <p>
- * This field is available for the following kinds of
- * completion proposals:
- * <ul>
- * <li><code>ANNOTATION_ATTRIBUT_REF</code> - type signature
- * of the annotation that declares the attribute that is referenced</li>
- * <li><code>ANONYMOUS_CLASS_DECLARATION</code> - type signature
- * of the type that is being subclassed or implemented</li>
- * <li><code>FIELD_IMPORT</code> - type signature
- * of the type that declares the field that is imported</li>
- * <li><code>FIELD_REF</code> - type signature
- * of the type that declares the field that is referenced</li>
- * <li><code>METHOD_IMPORT</code> - type signature
- * of the type that declares the method that is imported</li>
- * <li><code>FUNCTION_REF</code> - type signature
- * of the type that declares the method that is referenced</li>
- * <li><code>FUNCTION_DECLARATION</code> - type signature
- * of the type that declares the method that is being
- * implemented or overridden</li>
- * <li><code>PACKAGE_REF</code> - dot-based package
- * name of the package that is referenced</li>
- * <li><code>TYPE_IMPORT</code> - dot-based package
- * name of the package containing the type that is imported</li>
- * <li><code>TYPE_REF</code> - dot-based package
- * name of the package containing the type that is referenced</li>
- * <li><code>POTENTIAL_METHOD_DECLARATION</code> - type signature
- * of the type that declares the method that is being created</li>
- * </ul>
- * For kinds of completion proposals, this method returns
- * <code>null</code>. Clients must not modify the array
- * returned.
- * </p>
- *
- * @return a type signature or a package name (depending
- * on the kind of completion), or <code>null</code> if none
- * @see Signature
- */
- public char[] getDeclarationSignature() {
- return this.declarationSignature;
- }
-
- /**
- * Returns the key of the relevant
- * declaration in the context, or <code>null</code> if none.
- * <p>
- * This field is available for the following kinds of
- * completion proposals:
- * <ul>
- * <li><code>ANONYMOUS_CLASS_DECLARATION</code> - key
- * of the type that is being subclassed or implemented</li>
- * <li><code>FUNCTION_DECLARATION</code> - key
- * of the type that declares the method that is being
- * implemented or overridden</li>
- * </ul>
- * For kinds of completion proposals, this method returns
- * <code>null</code>. Clients must not modify the array
- * returned.
- * </p>
- *
- * @return a key, or <code>null</code> if none
- * @see org.eclipse.wst.jsdt.core.dom.ASTParser#createASTs(IJavaScriptUnit[], String[], org.eclipse.wst.jsdt.core.dom.ASTRequestor, IProgressMonitor)
- */
- public char[] getDeclarationKey() {
- return this.declarationKey;
- }
-
- /**
- * Sets the type signature of the relevant
- * declaration in the context, or <code>null</code> if none.
- * <p>
- * If not set, defaults to none.
- * </p>
- * <p>
- * The completion engine creates instances of this class and sets
- * its properties; this method is not intended to be used by other clients.
- * </p>
- *
- * @param signature the type or package signature, or
- * <code>null</code> if none
- */
- public void setDeclarationSignature(char[] signature) {
- this.declarationSignature = signature;
- }
-
- /**
- * Sets the type key of the relevant
- * declaration in the context, or <code>null</code> if none.
- * <p>
- * If not set, defaults to none.
- * </p>
- * <p>
- * The completion engine creates instances of this class and sets
- * its properties; this method is not intended to be used by other clients.
- * </p>
- *
- * @param key the type or package key, or
- * <code>null</code> if none
- */
- public void setDeclarationKey(char[] key) {
- this.declarationKey = key;
- }
-
- /**
- * Returns the simple name of the function, field,
- * member, or variable relevant in the context, or
- * <code>null</code> if none.
- * <p>
- * This field is available for the following kinds of
- * completion proposals:
- * <ul>
- * <li><code>ANNOTATION_ATTRIBUT_REF</code> - the name of the attribute</li>
- * <li><code>FIELD_IMPORT</code> - the name of the field</li>
- * <li><code>FIELD_REF</code> - the name of the field</li>
- * <li><code>KEYWORD</code> - the keyword</li>
- * <li><code>LABEL_REF</code> - the name of the label</li>
- * <li><code>LOCAL_VARIABLE_REF</code> - the name of the local variable</li>
- * <li><code>METHOD_IMPORT</code> - the name of the method</li>
- * <li><code>FUNCTION_REF</code> - the name of the method (the type simple name for constructor)</li>
- * <li><code>FUNCTION_DECLARATION</code> - the name of the method (the type simple name for constructor)</li>
- * <li><code>VARIABLE_DECLARATION</code> - the name of the variable</li>
- * <li><code>POTENTIAL_METHOD_DECLARATION</code> - the name of the method</li>
- * </ul>
- * For kinds of completion proposals, this method returns
- * <code>null</code>. Clients must not modify the array
- * returned.
- * </p>
- *
- * @return the keyword, field, method, local variable, or member
- * name, or <code>null</code> if none
- */
- public char[] getName() {
- return this.name;
- }
-
-
- /**
- * Sets the simple name of the method (type simple name for constructor), field,
- * member, or variable relevant in the context, or
- * <code>null</code> if none.
- * <p>
- * If not set, defaults to none.
- * </p>
- * <p>
- * The completion engine creates instances of this class and sets
- * its properties; this method is not intended to be used by other clients.
- * </p>
- *
- * @param name the keyword, field, method, local variable,
- * or member name, or <code>null</code> if none
- */
- public void setName(char[] name) {
- this.name = name;
- }
-
- /**
- * Returns the signature of the method or type
- * relevant in the context, or <code>null</code> if none.
- * <p>
- * This field is available for the following kinds of
- * completion proposals:
- * <ul>
- * <li><code>ANNOTATION_ATTRIBUT_REF</code> - the type signature
- * of the referenced attribute's type</li>
- * <li><code>ANONYMOUS_CLASS_DECLARATION</code> - method signature
- * of the constructor that is being invoked</li>
- * <li><code>FIELD_IMPORT</code> - the type signature
- * of the referenced field's type</li>
- * <li><code>FIELD_REF</code> - the type signature
- * of the referenced field's type</li>
- * <li><code>LOCAL_VARIABLE_REF</code> - the type signature
- * of the referenced local variable's type</li>
- * <li><code>METHOD_IMPORT</code> - method signature
- * of the method that is imported</li>
- * <li><code>FUNCTION_REF</code> - method signature
- * of the method that is referenced</li>
- * <li><code>FUNCTION_DECLARATION</code> - method signature
- * of the method that is being implemented or overridden</li>
- * <li><code>TYPE_IMPORT</code> - type signature
- * of the type that is imported</li>
- * <li><code>TYPE_REF</code> - type signature
- * of the type that is referenced</li>
- * <li><code>VARIABLE_DECLARATION</code> - the type signature
- * of the type of the variable being declared</li>
- * <li><code>POTENTIAL_METHOD_DECLARATION</code> - method signature
- * of the method that is being created</li>
- * </ul>
- * For kinds of completion proposals, this method returns
- * <code>null</code>. Clients must not modify the array
- * returned.
- * </p>
- *
- * @return the signature, or <code>null</code> if none
- * @see Signature
- */
- public char[] getSignature() {
- return this.signature;
- }
-
- /**
- * Returns the key relevant in the context,
- * or <code>null</code> if none.
- * <p>
- * This field is available for the following kinds of
- * completion proposals:
- * <ul>
- * <li><code>ANONYMOUS_CLASS_DECLARATION</code> - method key
- * of the constructor that is being invoked, or <code>null</code> if
- * the declaring type is an interface</li>
- * <li><code>FUNCTION_DECLARATION</code> - method key
- * of the method that is being implemented or overridden</li>
- * </ul>
- * For kinds of completion proposals, this method returns
- * <code>null</code>. Clients must not modify the array
- * returned.
- * </p>
- *
- * @return the key, or <code>null</code> if none
- * @see org.eclipse.wst.jsdt.core.dom.ASTParser#createASTs(IJavaScriptUnit[], String[], org.eclipse.wst.jsdt.core.dom.ASTRequestor, IProgressMonitor)
- */
- public char[] getKey() {
- return this.key;
- }
-
-// /**
-// * Returns the package name of the relevant
-// * declaration in the context, or <code>null</code> if none.
-// * <p>
-// * This field is available for the following kinds of
-// * completion proposals:
-// * <ul>
-// * <li><code>ANONYMOUS_CLASS_DECLARATION</code> - the dot-based package name
-// * of the type that is being subclassed or implemented</li>
-// * <li><code>FIELD_REF</code> - the dot-based package name
-// * of the type that declares the field that is referenced</li>
-// * <li><code>FUNCTION_REF</code> - the dot-based package name
-// * of the type that declares the method that is referenced</li>
-// * <li><code>FUNCTION_DECLARATION</code> - the dot-based package name
-// * of the type that declares the method that is being
-// * implemented or overridden</li>
-// * </ul>
-// * For kinds of completion proposals, this method returns
-// * <code>null</code>. Clients must not modify the array
-// * returned.
-// * </p>
-// *
-// * @return the dot-based package name, or
-// * <code>null</code> 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 <code>null</code> if none.
-// * <p>
-// * This field is available for the following kinds of
-// * completion proposals:
-// * <ul>
-// * <li><code>ANONYMOUS_CLASS_DECLARATION</code> - the dot-based type name
-// * of the type that is being subclassed or implemented</li>
-// * <li><code>FIELD_REF</code> - 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</li>
-// * <li><code>FUNCTION_REF</code> - 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</li>
-// * <li><code>FUNCTION_DECLARATION</code> - the dot-based type name
-// * of the type that declares the method that is being
-// * implemented or overridden</li>
-// * </ul>
-// * For kinds of completion proposals, this method returns
-// * <code>null</code>. Clients must not modify the array
-// * returned.
-// * </p>
-// *
-// * @return the dot-based package name, or
-// * <code>null</code> 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 <code>null</code> if none.
-// * <p>
-// * This field is available for the following kinds of
-// * completion proposals:
-// * <ul>
-// * <li><code>FIELD_REF</code> - the dot-based package name
-// * of the referenced field's type</li>
-// * <li><code>LOCAL_VARIABLE_REF</code> - the dot-based package name
-// * of the referenced local variable's type</li>
-// * <li><code>FUNCTION_REF</code> - the dot-based package name
-// * of the return type of the method that is referenced</li>
-// * <li><code>FUNCTION_DECLARATION</code> - the dot-based package name
-// * of the return type of the method that is being implemented
-// * or overridden</li>
-// * <li><code>PACKAGE_REF</code> - the dot-based package name
-// * of the package that is referenced</li>
-// * <li><code>TYPE_REF</code> - the dot-based package name
-// * of the type that is referenced</li>
-// * <li><code>VARIABLE_DECLARATION</code> - the dot-based package name
-// * of the type of the variable being declared</li>
-// * </ul>
-// * For kinds of completion proposals, this method returns
-// * <code>null</code>. Clients must not modify the array
-// * returned.
-// * </p>
-// *
-// * @return the package name, or <code>null</code> 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 <code>null</code> if none.
-// * <p>
-// * This field is available for the following kinds of
-// * completion proposals:
-// * <ul>
-// * <li><code>FIELD_REF</code> - the dot-based type name
-// * of the referenced field's type</li>
-// * <li><code>LOCAL_VARIABLE_REF</code> - the dot-based type name
-// * of the referenced local variable's type</li>
-// * <li><code>FUNCTION_REF</code> - the dot-based type name
-// * of the return type of the method that is referenced</li>
-// * <li><code>FUNCTION_DECLARATION</code> - the dot-based type name
-// * of the return type of the method that is being implemented
-// * or overridden</li>
-// * <li><code>TYPE_REF</code> - the dot-based type name
-// * of the type that is referenced</li>
-// * <li><code>VARIABLE_DECLARATION</code> - the dot-based package name
-// * of the type of the variable being declared</li>
-// * </ul>
-// * For kinds of completion proposals, this method returns
-// * <code>null</code>. Clients must not modify the array
-// * returned.
-// * </p>
-// *
-// * @return the package name, or <code>null</code> 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 <code>null</code> if none.
-// * <p>
-// * This field is available for the following kinds of
-// * completion proposals:
-// * <ul>
-// * <li><code>ANONYMOUS_CLASS_DECLARATION</code> - parameter package names
-// * of the constructor that is being invoked</li>
-// * <li><code>FUNCTION_REF</code> - parameter package names
-// * of the method that is referenced</li>
-// * <li><code>FUNCTION_DECLARATION</code> - parameter package names
-// * of the method that is being implemented or overridden</li>
-// * </ul>
-// * For kinds of completion proposals, this method returns
-// * <code>null</code>. Clients must not modify the array
-// * returned.
-// * </p>
-// *
-// * @return the package name, or <code>null</code> 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 <code>null</code> if none.
-// * <p>
-// * This field is available for the following kinds of
-// * completion proposals:
-// * <ul>
-// * <li><code>ANONYMOUS_CLASS_DECLARATION</code> - parameter type names
-// * of the constructor that is being invoked</li>
-// * <li><code>FUNCTION_REF</code> - parameter type names
-// * of the method that is referenced</li>
-// * <li><code>FUNCTION_DECLARATION</code> - parameter type names
-// * of the method that is being implemented or overridden</li>
-// * </ul>
-// * For kinds of completion proposals, this method returns
-// * <code>null</code>. Clients must not modify the array
-// * returned.
-// * </p>
-// *
-// * @return the package name, or <code>null</code> if none
-// *
-// * @see #getDeclarationSignature()
-// * @see #getSignature()
-// *
-// */
-// public char[][] getParameterTypeNames() {
-// return this.parameterTypeNames;
-// }
-
- /**
- * Sets the signature of the function, method, field type, member type,
- * relevant in the context, or <code>null</code> if none.
- * <p>
- * If not set, defaults to none.
- * </p>
- * <p>
- * The completion engine creates instances of this class and sets
- * its properties; this method is not intended to be used by other clients.
- * </p>
- *
- * @param signature the signature, or <code>null</code> if none
- */
- public void setSignature(char[] signature) {
- this.signature = signature;
- }
-
- /**
- * Sets the key of the method, field type, member type,
- * relevant in the context, or <code>null</code> if none.
- * <p>
- * If not set, defaults to none.
- * </p>
- * <p>
- * The completion engine creates instances of this class and sets
- * its properties; this method is not intended to be used by other clients.
- * </p>
- *
- * @param key the key, or <code>null</code> if none
- */
- public void setKey(char[] key) {
- this.key = key;
- }
-
- /**
- * Returns the modifier flags relevant in the context, or
- * <code>Flags.AccDefault</code> if none.
- * <p>
- * This field is available for the following kinds of
- * completion proposals:
- * <ul>
- * <li><code>ANNOTATION_ATTRIBUT_REF</code> - modifier flags
- * of the attribute that is referenced;
- * <li><code>ANONYMOUS_CLASS_DECLARATION</code> - modifier flags
- * of the constructor that is referenced</li>
- * <li><code>FIELD_IMPORT</code> - modifier flags
- * of the field that is imported.</li>
- * <li><code>FIELD_REF</code> - modifier flags
- * of the field that is referenced;
- * <code>Flags.AccEnum</code> can be used to recognize
- * references to enum constants
- * </li>
- * <li><code>KEYWORD</code> - modifier flag
- * corresponding to the modifier keyword</li>
- * <li><code>LOCAL_VARIABLE_REF</code> - modifier flags
- * of the local variable that is referenced</li>
- * <li><code>METHOD_IMPORT</code> - modifier flags
- * of the method that is imported;
- * </li>
- * <li><code>FUNCTION_REF</code> - modifier flags
- * of the method that is referenced;
- * <code>Flags.AccAnnotation</code> can be used to recognize
- * references to annotation type members
- * </li>
- * <li><code>FUNCTION_DECLARATION</code> - modifier flags
- * for the method that is being implemented or overridden</li>
- * <li><code>TYPE_IMPORT</code> - modifier flags
- * of the type that is imported; <code>Flags.AccInterface</code>
- * can be used to recognize references to interfaces,
- * <code>Flags.AccEnum</code> enum types,
- * and <code>Flags.AccAnnotation</code> annotation types</li>
- * <li><code>TYPE_REF</code> - modifier flags
- * of the type that is referenced; <code>Flags.AccInterface</code>
- * can be used to recognize references to interfaces,
- * <code>Flags.AccEnum</code> enum types,
- * and <code>Flags.AccAnnotation</code> annotation types
- * </li>
- * <li><code>VARIABLE_DECLARATION</code> - modifier flags
- * for the variable being declared</li>
- * <li><code>POTENTIAL_METHOD_DECLARATION</code> - modifier flags
- * for the method that is being created</li>
- * </ul>
- * For other kinds of completion proposals, this method returns
- * <code>Flags.AccDefault</code>.
- * </p>
- *
- * @return the modifier flags, or
- * <code>Flags.AccDefault</code> if none
- * @see Flags
- */
- public int getFlags() {
- return this.flags;
- }
-
- /**
- * Sets the modifier flags relevant in the context.
- * <p>
- * If not set, defaults to none.
- * </p>
- * <p>
- * The completion engine creates instances of this class and sets
- * its properties; this method is not intended to be used by other clients.
- * </p>
- *
- * @param flags the modifier flags, or
- * <code>Flags.AccDefault</code> if none
- */
- public void setFlags(int flags) {
- this.flags = flags;
- }
-
- /**
- * Returns the required completion proposals.
- * The proposal can be apply only if these required completion proposals are also applied.
- * If the required proposal aren't applied the completion could create completion problems.
- *
- * <p>
- * This field is available for the following kinds of
- * completion proposals:
- * <ul>
- * <li><code>FIELD_REF</code> - The allowed required proposals for this kind are:
- * <ul>
- * <li><code>TYPE_REF</code></li>
- * <li><code>TYPE_IMPORT</code></li>
- * <li><code>FIELD_IMPORT</code></li>
- * </ul>
- * </li>
- * <li><code>FUNCTION_REF</code> - The allowed required proposals for this kind are:
- * <ul>
- * <li><code>TYPE_REF</code></li>
- * <li><code>TYPE_IMPORT</code></li>
- * <li><code>METHOD_IMPORT</code></li>
- * </ul>
- * </li>
- * </ul>
- * </p>
- * <p>
- * Other kinds of required proposals will be returned in the future, therefore clients of this
- * API must allow with {@link CompletionRequestor#setAllowsRequiredProposals(int, int, boolean)}
- * only kinds which are in this list to avoid unexpected results in the future.
- * </p>
- * <p>
- * A required completion proposal cannot have required completion proposals.
- * </p>
- *
- * @return the required completion proposals, or <code>null</code> if none.
- *
- * @see CompletionRequestor#setAllowsRequiredProposals(int, int,boolean)
- *
- */
- public CompletionProposal[] getRequiredProposals() {
- return this.requiredProposals;
- }
-
-
- /**
- * Sets the list of required completion proposals, or <code>null</code> if none.
- * <p>
- * If not set, defaults to none.
- * </p>
- * <p>
- * The completion engine creates instances of this class and sets
- * its properties; this method is not intended to be used by other clients.
- * </p>
- *
- * @param proposals the list of required completion proposals, or
- * <code>null</code> if none
- */
- public void setRequiredProposals(CompletionProposal[] proposals) {
- this.requiredProposals = proposals;
- }
-
- /**
- * Finds the method or function parameter names.
- * This information is relevant to method reference (and
- * method declaration proposals). Returns <code>null</code>
- * if not available or not relevant.
- * <p>
- * The client must not modify the array returned.
- * </p>
- * <p>
- * <b>Note that this is an expensive thing to compute, which may require
- * parsing JavaScript source files, etc. Use sparingly.</b>
- * </p>
- *
- * @param monitor the progress monitor, or <code>null</code> if none
- * @return the parameter names, or <code>null</code> if none
- * or not available or not relevant
- */
- public char[][] findParameterNames(IProgressMonitor monitor) {
- if (!this.parameterNamesComputed) {
- this.parameterNamesComputed = true;
-
- switch(this.completionKind) {
- case ANONYMOUS_CLASS_DECLARATION:
- try {
- this.parameterNames = this.findMethodParameterNames(
- this.declarationPackageName,
- this.declarationTypeName,
- CharOperation.lastSegment(this.declarationTypeName, '.'),
- Signature.getParameterTypes(this.originalSignature == null ? this.signature : this.originalSignature));
- } catch(IllegalArgumentException e) {
- // protection for invalid signature
- if(this.parameterTypeNames != null) {
- this.parameterNames = this.createDefaultParameterNames(this.parameterTypeNames.length);
- } else {
- this.parameterNames = null;
- }
- }
- break;
- case METHOD_REF:
- try {
- this.parameterNames = this.findMethodParameterNames(
- this.declarationPackageName,
- this.declarationTypeName,
- this.name,
- Signature.getParameterTypes(this.originalSignature == null ? this.signature : this.originalSignature));
- } catch(IllegalArgumentException e) {
- // protection for invalid signature
- if(this.parameterTypeNames != null) {
- this.parameterNames = this.createDefaultParameterNames(this.parameterTypeNames.length);
- } else {
- this.parameterNames = null;
- }
- }
- break;
- case METHOD_DECLARATION:
- try {
- this.parameterNames = this.findMethodParameterNames(
- this.declarationPackageName,
- this.declarationTypeName,
- this.name,
- Signature.getParameterTypes(this.originalSignature == null ? this.signature : this.originalSignature));
- } catch(IllegalArgumentException e) {
- // protection for invalid signature
- if(this.parameterTypeNames != null) {
- this.parameterNames = this.createDefaultParameterNames(this.parameterTypeNames.length);
- } else {
- this.parameterNames = null;
- }
- }
- if(this.parameterNames != null) {
- this.updateCompletion = true;
- }
- break;
- }
- }
- return this.parameterNames;
- }
-
- /**
- * Sets the method or function parameter names.
- * This information is relevant to method reference (and
- * method declaration proposals).
- * <p>
- * The completion engine creates instances of this class and sets
- * its properties; this method is not intended to be used by other clients.
- * </p>
- *
- * @param parameterNames the parameter names, or <code>null</code> if none
- */
- public void setParameterNames(char[][] parameterNames) {
- this.parameterNames = parameterNames;
- this.parameterNamesComputed = true;
- }
-
- /**
- * @return <code>true</code> if this proposal includes parameters,
- * <code>false</code> if it does not
- */
- public boolean hasParameters() {
- return this.parameterNames != null && this.parameterNames.length > 0;
- }
-
- /**
- * @return parameter names for this proposal, or <code>null</code> if they are not set
- *
- * @see #findParameterNames(IProgressMonitor)
- * @see #setParameterNames(char[][])
- */
- public char[][] getParamaterNames() {
- return this.parameterNames;
- }
-
- /**
- * @return type names of the parameters for this proposal, or <code>null</code> none are set
- *
- * @see org.eclipse.wst.jsdt.internal.codeassist.InternalCompletionProposal#getParameterTypeNames()
- */
- public char[][] getParameterTypeNames() {
- return this.parameterTypeNames;
- }
-
- /**
- * Returns the accessibility of the proposal.
- * <p>
- * This field is available for the following kinds of
- * completion proposals:
- * <ul>
- * <li><code>TYPE_REF</code> - accessibility of the type</li>
- * </ul>
- * For these kinds of completion proposals, this method returns
- * {@link IAccessRule#K_ACCESSIBLE} or {@link IAccessRule#K_DISCOURAGED}
- * or {@link IAccessRule#K_NON_ACCESSIBLE}.
- * By default this method return {@link IAccessRule#K_ACCESSIBLE}.
- * </p>
- *
- * @see IAccessRule
- *
- * @return the accessibility of the proposal
- *
- */
- public int getAccessibility() {
- return this.accessibility;
- }
-
- /**
- * Returns whether this proposal is a constructor.
- * <p>
- * This field is available for the following kinds of
- * completion proposals:
- * <ul>
- * <li><code>FUNCTION_REF</code> - return <code>true</code>
- * if the referenced method is a constructor</li>
- * <li><code>FUNCTION_DECLARATION</code> - return <code>true</code>
- * if the declared method is a constructor</li>
- * </ul>
- * For kinds of completion proposals, this method returns
- * <code>false</code>.
- * </p>
- *
- * @return <code>true</code> if the proposal is a constructor.
- */
- public boolean isConstructor() {
- return this.isConstructor;
- }
-
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- buffer.append('[');
- switch(this.completionKind) {
- case CompletionProposal.ANONYMOUS_CLASS_DECLARATION :
- buffer.append("ANONYMOUS_CLASS_DECLARATION"); //$NON-NLS-1$
- break;
- case CompletionProposal.FIELD_REF :
- buffer.append("FIELD_REF"); //$NON-NLS-1$
- break;
- case CompletionProposal.KEYWORD :
- buffer.append("KEYWORD"); //$NON-NLS-1$
- break;
- case CompletionProposal.LABEL_REF :
- buffer.append("LABEL_REF"); //$NON-NLS-1$
- break;
- case CompletionProposal.LOCAL_VARIABLE_REF :
- buffer.append("LOCAL_VARIABLE_REF"); //$NON-NLS-1$
- break;
- case CompletionProposal.METHOD_DECLARATION :
- buffer.append("FUNCTION_DECLARATION"); //$NON-NLS-1$
- if(this.isConstructor) {
- buffer.append("<CONSTRUCTOR>"); //$NON-NLS-1$
- }
- break;
- case CompletionProposal.METHOD_REF :
- buffer.append("FUNCTION_REF"); //$NON-NLS-1$
- if(this.isConstructor) {
- buffer.append("<CONSTRUCTOR>"); //$NON-NLS-1$
- }
- break;
- case CompletionProposal.PACKAGE_REF :
- buffer.append("PACKAGE_REF"); //$NON-NLS-1$
- break;
- case CompletionProposal.TYPE_REF :
- buffer.append("TYPE_REF"); //$NON-NLS-1$
- break;
- case CompletionProposal.VARIABLE_DECLARATION :
- buffer.append("VARIABLE_DECLARATION"); //$NON-NLS-1$
- break;
- case CompletionProposal.POTENTIAL_METHOD_DECLARATION :
- buffer.append("POTENTIAL_METHOD_DECLARATION"); //$NON-NLS-1$
- break;
- case CompletionProposal.METHOD_NAME_REFERENCE :
- buffer.append("METHOD_IMPORT"); //$NON-NLS-1$
- break;
- case CompletionProposal.JSDOC_BLOCK_TAG :
- buffer.append("JSDOC_BLOCK_TAG"); //$NON-NLS-1$
- break;
- case CompletionProposal.JSDOC_INLINE_TAG :
- buffer.append("JSDOC_INLINE_TAG"); //$NON-NLS-1$
- break;
- case CompletionProposal.JSDOC_FIELD_REF:
- buffer.append("JSDOC_FIELD_REF"); //$NON-NLS-1$
- break;
- case CompletionProposal.JSDOC_METHOD_REF :
- buffer.append("JSDOC_METHOD_REF"); //$NON-NLS-1$
- break;
- case CompletionProposal.JSDOC_TYPE_REF :
- buffer.append("JSDOC_TYPE_REF"); //$NON-NLS-1$
- break;
- case CompletionProposal.JSDOC_PARAM_REF :
- buffer.append("JSDOC_PARAM_REF"); //$NON-NLS-1$
- break;
- case CompletionProposal.FIELD_IMPORT :
- buffer.append("FIELD_IMPORT"); //$NON-NLS-1$
- break;
- case CompletionProposal.METHOD_IMPORT :
- buffer.append("METHOD_IMPORT"); //$NON-NLS-1$
- break;
- case CompletionProposal.TYPE_IMPORT :
- buffer.append("TYPE_IMPORT"); //$NON-NLS-1$
- break;
- default :
- buffer.append("PROPOSAL"); //$NON-NLS-1$
- break;
-
- }
- buffer.append("]{completion:"); //$NON-NLS-1$
- if (this.completion != null) buffer.append(this.completion);
- buffer.append(", declSign:"); //$NON-NLS-1$
- if (this.declarationSignature != null) buffer.append(this.declarationSignature);
- buffer.append(", sign:"); //$NON-NLS-1$
- if (this.signature != null) buffer.append(this.signature);
- buffer.append(", declKey:"); //$NON-NLS-1$
- if (this.declarationKey != null) buffer.append(this.declarationKey);
- buffer.append(", key:"); //$NON-NLS-1$
- if (this.key != null) buffer.append(key);
- buffer.append(", name:"); //$NON-NLS-1$
- if (this.name != null) buffer.append(this.name);
- buffer.append(", ["); //$NON-NLS-1$
- buffer.append(this.replaceStart);
- buffer.append(',');
- buffer.append(this.replaceEnd);
- buffer.append("], relevance="); //$NON-NLS-1$
- buffer.append(this.relevance);
- buffer.append('}');
- return buffer.toString();
- }
-}
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
deleted file mode 100644
index 9cfe7b54..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/CompletionRequestor.java
+++ /dev/null
@@ -1,296 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core;
-
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-
-/**
- * Abstract base class for a completion requestor which is passed completion
- * proposals as they are generated in response to a code assist request.
- * <p>
- * This class is intended to be subclassed by clients.
- * </p>
- * <p>
- * The code assist engine normally invokes methods on completion
- * requestor in the following sequence:
- * <pre>
- * requestor.beginReporting();
- * requestor.acceptContext(context);
- * requestor.accept(proposal_1);
- * requestor.accept(proposal_2);
- * ...
- * requestor.endReporting();
- * </pre>
- * If, however, the engine is unable to offer completion proposals
- * for whatever reason, <code>completionFailure</code> is called
- * with a problem object describing why completions were unavailable.
- * In this case, the sequence of calls is:
- * <pre>
- * requestor.beginReporting();
- * requestor.acceptContext(context);
- * requestor.completionFailure(problem);
- * requestor.endReporting();
- * </pre>
- * In either case, the bracketing <code>beginReporting</code>
- * <code>endReporting</code> calls are always made as well as
- * <code>acceptContext</code> call.
- * </p>
- *
- * @see ICodeAssist
- *
- * 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 CompletionRequestor {
-
- /**
- * The set of CompletionProposal kinds that this requestor
- * ignores; <code>0</code> means the set is empty.
- * 1 << completionProposalKind
- */
- private int ignoreSet = 0;
-
- private String[] favoriteReferences;
-
- /**
- * The set of CompletionProposal kinds that this requestor
- * allows for required proposals; <code>0</code> means the set is empty.
- * 1 << completionProposalKind
- */
- private int requiredProposalAllowSet[] = null;
-
- /**
- * Creates a new completion requestor.
- * The requestor is interested in all kinds of completion
- * proposals; none will be ignored.
- */
- public CompletionRequestor() {
- // do nothing
- }
-
- /**
- * Returns whether the given kind of completion proposal is ignored.
- *
- * @param completionProposalKind one of the kind constants declared
- * on <code>CompletionProposal</code>
- * @return <code>true</code> if the given kind of completion proposal
- * is ignored by this requestor, and <code>false</code> if it is of
- * interest
- * @see #setIgnored(int, boolean)
- * @see CompletionProposal#getKind()
- */
- public boolean isIgnored(int completionProposalKind) {
- if (completionProposalKind < CompletionProposal.FIRST_KIND
- || completionProposalKind > CompletionProposal.LAST_KIND) {
- throw new IllegalArgumentException("Unknown kind of completion proposal: "+completionProposalKind); //$NON-NLS-1$
- }
- return 0 != (this.ignoreSet & (1 << completionProposalKind));
- }
-
- /**
- * Sets whether the given kind of completion proposal is ignored.
- *
- * @param completionProposalKind one of the kind constants declared
- * on <code>CompletionProposal</code>
- * @param ignore <code>true</code> if the given kind of completion proposal
- * is ignored by this requestor, and <code>false</code> if it is of
- * interest
- * @see #isIgnored(int)
- * @see CompletionProposal#getKind()
- */
- public void setIgnored(int completionProposalKind, boolean ignore) {
- if (completionProposalKind < CompletionProposal.FIRST_KIND
- || completionProposalKind > CompletionProposal.LAST_KIND) {
- throw new IllegalArgumentException("Unknown kind of completion proposal: "+completionProposalKind); //$NON-NLS-1$
- }
- if (ignore) {
- this.ignoreSet |= (1 << completionProposalKind);
- } else {
- this.ignoreSet &= ~(1 << completionProposalKind);
- }
- }
-
- /**
- * Returns whether a proposal of a given kind with a required proposal
- * of the given kind is allowed.
- *
- * @param proposalKind one of the kind constants declared
- * @param requiredProposalKind one of the kind constants declared
- * on <code>CompletionProposal</code>
- * @return <code>true</code> if a proposal of a given kind with a required proposal
- * of the given kind is allowed by this requestor, and <code>false</code>
- * if it isn't of interest.
- * <p>
- * By default, all kinds of required proposals aren't allowed.
- * </p>
- * @see #setAllowsRequiredProposals(int, int, boolean)
- * @see CompletionProposal#getKind()
- * @see CompletionProposal#getRequiredProposals()
- *
- */
- public boolean isAllowingRequiredProposals(int proposalKind, int requiredProposalKind) {
- if (proposalKind < CompletionProposal.FIRST_KIND
- || proposalKind > CompletionProposal.LAST_KIND) {
- throw new IllegalArgumentException("Unknown kind of completion proposal: "+requiredProposalKind); //$NON-NLS-1$
- }
-
- if (requiredProposalKind < CompletionProposal.FIRST_KIND
- || requiredProposalKind > CompletionProposal.LAST_KIND) {
- throw new IllegalArgumentException("Unknown required kind of completion proposal: "+requiredProposalKind); //$NON-NLS-1$
- }
- if (this.requiredProposalAllowSet == null) return false;
-
- return 0 != (this.requiredProposalAllowSet[proposalKind] & (1 << requiredProposalKind));
- }
-
- /**
- * Sets whether a proposal of a given kind with a required proposal
- * of the given kind is allowed.
- *
- * Currently only a subset of kinds support required proposals. To see what combinations
- * are supported you must look at {@link CompletionProposal#getRequiredProposals()}
- * documentation.
- *
- * @param proposalKind one of the kind constants declared
- * @param requiredProposalKind one of the kind constants declared
- * on <code>CompletionProposal</code>
- * @param allow <code>true</code> if a proposal of a given kind with a required proposal
- * of the given kind is allowed by this requestor, and <code>false</code>
- * if it isn't of interest
- * @see #isAllowingRequiredProposals(int, int)
- * @see CompletionProposal#getKind()
- * @see CompletionProposal#getRequiredProposals()
- *
- */
- public void setAllowsRequiredProposals(int proposalKind, int requiredProposalKind, boolean allow) {
- if (proposalKind < CompletionProposal.FIRST_KIND
- || proposalKind > CompletionProposal.LAST_KIND) {
- throw new IllegalArgumentException("Unknown kind of completion proposal: "+requiredProposalKind); //$NON-NLS-1$
- }
- if (requiredProposalKind < CompletionProposal.FIRST_KIND
- || requiredProposalKind > CompletionProposal.LAST_KIND) {
- throw new IllegalArgumentException("Unknown required kind of completion proposal: "+requiredProposalKind); //$NON-NLS-1$
- }
-
- if (this.requiredProposalAllowSet == null) {
- this.requiredProposalAllowSet = new int[CompletionProposal.LAST_KIND + 1];
- }
-
- if (allow) {
- this.requiredProposalAllowSet[proposalKind] |= (1 << requiredProposalKind);
- } else {
- this.requiredProposalAllowSet[proposalKind] &= ~(1 << requiredProposalKind);
- }
- }
-
- /**
- * Returns the favorite references which are used to compute some completion proposals.
- * <p>
- * Currently only on demand type references (<code>"java.util.Arrays.*"</code>),
- * references to a static method or a static field are used to compute completion proposals.
- * Other kind of reference could be used in the future.
- * </p>
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @return favorite imports
- *
- */
- public String[] getFavoriteReferences() {
- return this.favoriteReferences;
- }
-
- /**
- * Set the favorite references which will be used to compute some completion proposals.
- * A favorite reference is a qualified reference as it can be seen in an import statement.<br>
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @param favoriteImports
- *
- * @see #getFavoriteReferences()
- *
- */
- public void setFavoriteReferences(String[] favoriteImports) {
- this.favoriteReferences = favoriteImports;
- }
-
- /**
- * Pro forma notification sent before reporting a batch of
- * completion proposals.
- * <p>
- * The default implementation of this method does nothing.
- * Clients may override.
- * </p>
- */
- public void beginReporting() {
- // do nothing
- }
-
- /**
- * Pro forma notification sent after reporting a batch of
- * completion proposals.
- * <p>
- * The default implementation of this method does nothing.
- * Clients may override.
- * </p>
- */
- public void endReporting() {
- // do nothing
- }
-
- /**
- * Notification of failure to produce any completions.
- * The problem object explains what prevented completing.
- * <p>
- * The default implementation of this method does nothing.
- * Clients may override to receive this kind of notice.
- * </p>
- *
- * @param problem the problem object
- */
- public void completionFailure(IProblem problem) {
- // default behavior is to ignore
- }
-
- /**
- * Proposes a completion. Has no effect if the kind of proposal
- * is being ignored by this requestor. Callers should consider
- * checking {@link #isIgnored(int)} before avoid creating proposal
- * objects that would only be ignored.
- * <p>
- * Similarly, implementers should check
- * {@link #isIgnored(int) isIgnored(proposal.getKind())}
- * and ignore proposals that have been declared as uninteresting.
- * The proposal object passed is only valid for the duration of
- * completion operation.
- *
- * @param proposal the completion proposal
- * @exception IllegalArgumentException if the proposal is null
- */
- public abstract void accept(CompletionProposal proposal);
-
- /**
- * Propose the context in which the completion occurs.
- * <p>
- * This method is called one and only one time before any call to
- * {@link #accept(CompletionProposal)}.
- * The default implementation of this method does nothing.
- * Clients may override.
- * </p>
- * @param context the completion context
- *
- */
- public void acceptContext(CompletionContext context) {
- // do nothing
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/CorrectionEngine.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/CorrectionEngine.java
deleted file mode 100644
index c2db585f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/CorrectionEngine.java
+++ /dev/null
@@ -1,463 +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.core;
-
-import java.util.Hashtable;
-import java.util.Map;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.internal.compiler.impl.CompilerOptions;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ProblemReasons;
-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.problem.ProblemReporter;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * This class is the entry point for source corrections.
- *
- * This class is not intended to be subclassed by clients. This class is intended to be instantiated 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 class CorrectionEngine implements ProblemReasons {
-
- /**
- * This field is not intended to be used by client.
- */
- protected int correctionStart;
- /**
- * This field is not intended to be used by client.
- */
- protected int correctionEnd;
- /**
- * This field is not intended to be used by client.
- */
- protected int prefixLength;
- /**
- * This field is not intended to be used by client.
- */
- protected IJavaScriptUnit compilationUnit;
- /**
- * This field is not intended to be used by client.
- */
- protected ICorrectionRequestor correctionRequestor;
- /**
- * This field is not intended to be used by client.
- */
- protected static final int CLASSES = 0x00000001;
- /**
- * This field is not intended to be used by client.
- */
- protected static final int IMPORT = 0x00000004;
- /**
- * This field is not intended to be used by client.
- */
- protected static final int METHOD = 0x00000008;
- /**
- * This field is not intended to be used by client.
- */
- protected static final int FIELD = 0x00000010;
- /**
- * This field is not intended to be used by client.
- */
- protected static final int LOCAL = 0x00000020;
- /**
- * This field is not intended to be used by client.
- */
- protected int filter;
-
- /**
- * The CorrectionEngine is responsible for computing problem corrections.
- *
- * @param setting java.util.Map
- * set of options used to configure the code correction engine.
- * CURRENTLY THERE IS NO CORRECTION SPECIFIC SETTINGS.
- */
- public CorrectionEngine(Map setting) {
- // settings ignored for now
- }
-
- /**
- * Performs code correction for the given marker,
- * reporting results to the given correction requestor.
- *
- * Correction results are answered through a requestor.
- *
- * @param marker
- * the marker which describe the problem to correct.
- * @param targetUnit
- * replace the compilation unit given by the marker. Ignored if null.
- * @param positionOffset
- * the offset of position given by the marker.
- * @param requestor
- * the given correction requestor
- * @exception IllegalArgumentException if <code>requestor</code> is <code>null</code>
- * @exception JavaScriptModelException currently this exception is never thrown, but the opportunity to thrown an exception
- * when the correction failed is kept for later.
- */
- public void computeCorrections(IMarker marker, IJavaScriptUnit targetUnit, int positionOffset, ICorrectionRequestor requestor) throws JavaScriptModelException {
-
- IJavaScriptElement element = targetUnit == null ? JavaScriptCore.create(marker.getResource()) : targetUnit;
-
- if(!(element instanceof IJavaScriptUnit))
- return;
-
- IJavaScriptUnit unit = (IJavaScriptUnit) element;
-
- int id = marker.getAttribute(IJavaScriptModelMarker.ID, -1);
- String[] args = Util.getProblemArgumentsFromMarker(marker.getAttribute(IJavaScriptModelMarker.ARGUMENTS, "")); //$NON-NLS-1$
- int start = marker.getAttribute(IMarker.CHAR_START, -1);
- int end = marker.getAttribute(IMarker.CHAR_END, -1);
-
- computeCorrections(unit, id, start + positionOffset, end + positionOffset, args, requestor);
- }
-
- /**
- * Performs code correction for the given IProblem,
- * reporting results to the given correction requestor.
- *
- * Correction results are answered through a requestor.
- *
- * @param problem
- * the problem which describe the problem to correct.
- * @param targetUnit
- * denote the compilation unit in which correction occurs. Cannot be null.
- * @param requestor
- * the given correction requestor
- * @exception IllegalArgumentException if <code>targetUnit</code> or <code>requestor</code> is <code>null</code>
- * @exception JavaScriptModelException currently this exception is never thrown, but the opportunity to thrown an exception
- * when the correction failed is kept for later.
- */
- public void computeCorrections(IProblem problem, IJavaScriptUnit targetUnit, ICorrectionRequestor requestor) throws JavaScriptModelException {
- if (requestor == null) {
- throw new IllegalArgumentException(Messages.correction_nullUnit);
- }
- this.computeCorrections(
- targetUnit, problem.getID(),
- problem.getSourceStart(),
- problem.getSourceEnd(),
- problem.getArguments(),
- requestor);
- }
-
- /**
- * Ask the engine to compute a correction for the specified problem
- * of the given compilation unit.
- * Correction results are answered through a requestor.
- *
- * @param unit org.eclipse.wst.jsdt.internal.core.ICompilationUnit
- * the compilation unit.
- *
- * @param id int
- * the id of the problem.
- *
- * @param start int
- * a position in the source where the error begin.
- *
- * @param end int
- * a position in the source where the error finish.
- *
- * @param arguments String[]
- * arguments of the problem.
- *
- * @exception IllegalArgumentException if <code>requestor</code> is <code>null</code>
- * @exception JavaScriptModelException currently this exception is never thrown, but the opportunity to thrown an exception
- * when the correction failed is kept for later.
- */
- private void computeCorrections(IJavaScriptUnit unit, int id, int start, int end, String[] arguments, ICorrectionRequestor requestor) {
-
- if(id == -1 || arguments == null || start == -1 || end == -1)
- return;
- if (requestor == null) {
- throw new IllegalArgumentException(Messages.correction_nullRequestor);
- }
-
- this.correctionRequestor = requestor;
- this.correctionStart = start;
- this.correctionEnd = end;
- this.compilationUnit = unit;
-
- String argument = null;
- try {
- switch (id) {
- // Type correction
- case IProblem.ImportNotFound :
- this.filter = IMPORT;
- argument = arguments[0];
- break;
- case IProblem.UndefinedType :
- this.filter = CLASSES;
- argument = arguments[0];
- break;
-
- // Method correction
- case IProblem.UndefinedMethod :
- case IProblem.UndefinedFunction :
- this.filter = METHOD;
- argument = arguments[1];
- break;
-
- // Field and local variable correction
- case IProblem.UndefinedField :
- this.filter = FIELD;
- argument = arguments[0];
- break;
- case IProblem.UndefinedName :
- this.filter = FIELD | LOCAL;
- argument = arguments[0];
- break;
- }
- } catch (ArrayIndexOutOfBoundsException e) {
- return;
- }
- if(argument != null) {
- correct(argument.toCharArray());
- }
- }
-
- private void correct(char[] argument) {
- try {
- String source = this.compilationUnit.getSource();
- Scanner scanner = new Scanner();
- scanner.setSource(source.toCharArray());
-
- scanner.resetTo(this.correctionStart, this.correctionEnd);
- int token = 0;
- char[] argumentSource = CharOperation.NO_CHAR;
-
- // search last segment position
- while(true) {
- token = scanner.getNextToken();
- if (token == TerminalTokens.TokenNameEOF) return;
-
- char[] tokenSource = scanner.getCurrentTokenSource();
-
- argumentSource = CharOperation.concat(argumentSource, tokenSource);
- if(!CharOperation.prefixEquals(argumentSource, argument))
- return;
-
- if(CharOperation.equals(argument, argumentSource)) {
- this.correctionStart = scanner.startPosition;
- this.correctionEnd = scanner.currentPosition;
- this.prefixLength = CharOperation.lastIndexOf('.', argument) + 1;
- break;
- }
-
- }
-
- // search completion position
- int completionPosition = this.correctionStart;
- scanner.resetTo(completionPosition, this.correctionEnd);
- int position = completionPosition;
-
- for (int i = 0; i < 4; i++) {
- if(scanner.getNextCharAsJavaIdentifierPart()) {
- completionPosition = position;
- position = scanner.currentPosition;
- } else {
- break;
- }
- }
- Hashtable oldOptions = JavaScriptCore.getOptions();
- try {
- Hashtable options = new Hashtable(oldOptions);
- options.put(JavaScriptCore.CODEASSIST_CAMEL_CASE_MATCH, JavaScriptCore.DISABLED);
- JavaScriptCore.setOptions(options);
-
- this.compilationUnit.codeComplete(
- completionPosition,
- this.completionRequestor
- );
- } finally {
- JavaScriptCore.setOptions(oldOptions);
- }
- } catch (JavaScriptModelException e) {
- return;
- } catch (InvalidInputException e) {
- return;
- }
- }
-
- /**
- * This field is not intended to be used by client.
- */
- protected CompletionRequestor completionRequestor = new CompletionRequestor() {
- public void accept(CompletionProposal proposal) {
- switch (proposal.getKind()) {
- case CompletionProposal.TYPE_REF:
- if((CorrectionEngine.this.filter & CLASSES) != 0) {
- char[] completionName = proposal.getCompletion();
- CorrectionEngine.this.correctionRequestor.acceptClass(
- proposal.getDeclarationSignature(),
- Signature.getSignatureSimpleName(proposal.getSignature()),
- CharOperation.subarray(completionName, CorrectionEngine.this.prefixLength, completionName.length),
- proposal.getFlags(),
- CorrectionEngine.this.correctionStart,
- CorrectionEngine.this.correctionEnd);
- } else if((CorrectionEngine.this.filter & IMPORT) != 0) {
- char[] packageName = proposal.getDeclarationSignature();
- char[] className = Signature.getSignatureSimpleName(proposal.getSignature());
- char[] fullName = CharOperation.concat(packageName, className, '.');
- CorrectionEngine.this.correctionRequestor.acceptClass(
- packageName,
- className,
- CharOperation.subarray(fullName, CorrectionEngine.this.prefixLength, fullName.length),
- proposal.getFlags(),
- CorrectionEngine.this.correctionStart,
- CorrectionEngine.this.correctionEnd);
- }
- break;
- case CompletionProposal.FIELD_REF:
- if((CorrectionEngine.this.filter & FIELD) != 0) {
- char[] declaringSignature = proposal.getDeclarationSignature();
- char[] signature = proposal.getSignature();
- CorrectionEngine.this.correctionRequestor.acceptField(
- Signature.getSignatureQualifier(declaringSignature),
- Signature.getSignatureSimpleName(declaringSignature),
- proposal.getName(),
- Signature.getSignatureQualifier(signature),
- Signature.getSignatureSimpleName(signature),
- proposal.getName(),
- proposal.getFlags(),
- CorrectionEngine.this.correctionStart,
- CorrectionEngine.this.correctionEnd);
- }
- break;
- case CompletionProposal.LOCAL_VARIABLE_REF:
- if((CorrectionEngine.this.filter & LOCAL) != 0) {
- char[] signature = proposal.getSignature();
- CorrectionEngine.this.correctionRequestor.acceptLocalVariable(
- proposal.getName(),
- Signature.getSignatureQualifier(signature),
- Signature.getSignatureSimpleName(signature),
- proposal.getFlags(),
- CorrectionEngine.this.correctionStart,
- CorrectionEngine.this.correctionEnd);
- }
- break;
- case CompletionProposal.METHOD_REF:
- if((CorrectionEngine.this.filter & METHOD) != 0) {
- char[] declaringSignature = proposal.getDeclarationSignature();
- char[] signature = proposal.getSignature();
- char[][] parameterTypeSignatures = Signature.getParameterTypes(signature);
- int length = parameterTypeSignatures.length;
- char[][] parameterPackageNames = new char[length][];
- char[][] parameterTypeNames = new char[length][];
- for (int i = 0; i < length; i++) {
- parameterPackageNames[i] = Signature.getSignatureQualifier(parameterTypeSignatures[i]);
- parameterTypeNames[i] = Signature.getSignatureSimpleName(parameterTypeSignatures[i]);
- }
- char[] returnTypeSignature = Signature.getReturnType(signature);
- CorrectionEngine.this.correctionRequestor.acceptMethod(
- Signature.getSignatureQualifier(declaringSignature),
- Signature.getSignatureSimpleName(declaringSignature),
- proposal.getName(),
- parameterPackageNames,
- parameterTypeNames,
- proposal.findParameterNames(null),
- Signature.getSignatureQualifier(returnTypeSignature),
- Signature.getSignatureSimpleName(returnTypeSignature),
- proposal.getName(),
- proposal.getFlags(),
- CorrectionEngine.this.correctionStart,
- CorrectionEngine.this.correctionEnd);
- }
- break;
- case CompletionProposal.PACKAGE_REF:
- if((CorrectionEngine.this.filter & (CLASSES | IMPORT)) != 0) {
- char[] packageName = proposal.getDeclarationSignature();
- CorrectionEngine.this.correctionRequestor.acceptPackage(
- packageName,
- CharOperation.subarray(packageName, CorrectionEngine.this.prefixLength, packageName.length),
- CorrectionEngine.this.correctionStart,
- CorrectionEngine.this.correctionEnd);
- }
- break;
- }
- }
- };
-
-
- /**
- * Return an array of strings which contains one entry per warning token
- * accepted by the <code>@SuppressWarnings</code> annotation. This array is
- * neither null nor empty, it contains at least the String <code>all</code>.
- * It should not be modified by the caller (please take a copy if modifications
- * are needed).<br>
- * <b>Note:</b> The tokens returned are not necessarily standardized across JavaScript
- * validators. If you were to use one of these tokens in a <code>@SuppressWarnings</code>
- * annotation in the JavaScript source code, the effects (if any) may vary from
- * validator to validator.
- *
- * @return an array of strings which contains one entry per warning token
- * accepted by the <code>@SuppressWarnings</code> annotation.
- */
- public static String[] getAllWarningTokens() {
- return CompilerOptions.warningTokens;
- }
-
- /**
- * Helper method for decoding problem marker attributes. Returns an array of String arguments
- * extracted from the problem marker "arguments" attribute, or <code>null</code> if the marker
- * "arguments" attribute is missing or ill-formed.
- *
- * @param problemMarker
- * the problem marker to decode arguments from.
- * @return an array of String arguments, or <code>null</code> if unable to extract arguments
- */
- public static String[] getProblemArguments(IMarker problemMarker){
- String argumentsString = problemMarker.getAttribute(IJavaScriptModelMarker.ARGUMENTS, null);
- return Util.getProblemArgumentsFromMarker(argumentsString);
- }
-
- /**
- * Returns a token which can be used to suppress a given warning using
- * <code>@SuppressWarnings</code> annotation, for a given problem ID
- * ({@link IProblem }). If a particular problem is not suppressable,
- * <code>null</code> will be returned.
- * <p>
- * <b>Note:</b> <code>@SuppressWarnings</code> can only suppress warnings,
- * which means that if some problems got promoted to ERROR using custom compiler
- * settings ({@link IJavaScriptProject#setOption(String, String)}), the
- * <code>@SuppressWarnings</code> annotation will be ineffective.
- * </p>
- * <p>
- * <b>Note:</b> <code>@SuppressWarnings</code> can be argumented with
- * <code>"all"</code> so as to suppress all possible warnings at once.
- * </p>
- * <p>
- * <b>Note:</b> The tokens returned are not necessarily standardized across JavaScript
- * validators. If you were to use one of these tokens in an @SuppressWarnings
- * annotation in the JavaScript source code, the effects (if any) may vary from
- * validator to validator.
- * </p>
- * @param problemID
- * the ID of a given warning to suppress
- * @return a String which can be used in <code>@SuppressWarnings</code> annotation,
- * or <code>null</code> if unable to suppress this warning.
- */
- public static String getWarningToken(int problemID){
- long irritant = ProblemReporter.getIrritant(problemID);
- if (irritant != 0) {
- return CompilerOptions.warningTokenFromIrritant(irritant);
- }
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ElementChangedEvent.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ElementChangedEvent.java
deleted file mode 100644
index d29b576c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ElementChangedEvent.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*******************************************************************************
- * 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;
-
-import java.util.EventObject;
-
-/**
- * An element changed event describes a change to the structure or contents
- * of a tree of JavaScript elements. The changes to the elements are described by
- * the associated delta object carried by this event.
- * <p>
- * This class is not intended to be instantiated or subclassed by clients.
- * Instances of this class are automatically created by the JavaScript model.
- * </p>
- *
- * @see IElementChangedListener
- * @see IJavaScriptElementDelta
- *
- * 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 ElementChangedEvent extends EventObject {
-
- /**
- * Event type constant (bit mask) indicating an after-the-fact
- * report of creations, deletions, and modifications
- * to one or more JavaScript element(s) expressed as a hierarchical
- * java element delta as returned by <code>getDelta()</code>.
- *
- * Note: this notification occurs during the corresponding POST_CHANGE
- * resource change notification, and contains a full delta accounting for
- * any JavaScriptModel operation and/or resource change.
- *
- * @see IJavaScriptElementDelta
- * @see org.eclipse.core.resources.IResourceChangeEvent
- * @see #getDelta()
- */
- public static final int POST_CHANGE = 1;
-
- /**
- * Event type constant (bit mask) indicating an after-the-fact
- * report of creations, deletions, and modifications
- * to one or more JavaScript element(s) expressed as a hierarchical
- * java element delta as returned by <code>getDelta</code>.
- *
- * Note: this notification occurs as a result of a working copy reconcile
- * operation.
- *
- * @see IJavaScriptElementDelta
- * @see org.eclipse.core.resources.IResourceChangeEvent
- * @see #getDelta()
- */
- public static final int POST_RECONCILE = 4;
-
- private static final long serialVersionUID = -8947240431612844420L; // backward compatible
-
- /*
- * Event type indicating the nature of this event.
- * It can be a combination either:
- * - POST_CHANGE
- * - PRE_AUTO_BUILD
- * - POST_RECONCILE
- */
- private int type;
-
- /**
- * Creates an new element changed event (based on a <code>IJavaScriptElementDelta</code>).
- *
- * @param delta the JavaScript element delta.
- * @param type the type of delta (ADDED, REMOVED, CHANGED) this event contains
- */
- public ElementChangedEvent(IJavaScriptElementDelta delta, int type) {
- super(delta);
- this.type = type;
- }
- /**
- * Returns the delta describing the change.
- *
- * @return the delta describing the change
- */
- public IJavaScriptElementDelta getDelta() {
- return (IJavaScriptElementDelta) this.source;
- }
-
- /**
- * Returns the type of event being reported.
- *
- * @return one of the event type constants
- * @see #POST_CHANGE
- * @see #POST_RECONCILE
- */
- public int getType() {
- return this.type;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/Flags.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/Flags.java
deleted file mode 100644
index 751e5ef6..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/Flags.java
+++ /dev/null
@@ -1,230 +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
- * IBM Corporation - added constant AccDefault
- * IBM Corporation - added constants AccBridge and AccVarargs for J2SE 1.5
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core;
-
-import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants;
-
-/**
- * Utility class for decoding modifier flags in JavaScript elements.
- * <p>
- * This class provides static methods only; it is not intended to be
- * instantiated or subclassed by clients.
- * </p>
- *
- * @see IMember#getFlags()
- *
- * 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 final class Flags {
-
- /**
- * Constant representing the absence of any flag
- */
- public static final int AccDefault = ClassFileConstants.AccDefault;
- /**
- * Public access flag.
- *
- * <b>This flag only applies to ECMAScript 4 which is not yet supported</b>
- */
- public static final int AccPublic = ClassFileConstants.AccPublic;
- /**
- * Private access flag.
- *
- * <b>This flag only applies to ECMAScript 4 which is not yet supported</b>
- */
- public static final int AccPrivate = ClassFileConstants.AccPrivate;
- /**
- * Protected access flag.
- *
- * <b>This flag only applies to ECMAScript 4 which is not yet supported</b>
- */
- public static final int AccProtected = ClassFileConstants.AccProtected;
- /**
- * Static access flag.
- */
- public static final int AccStatic = ClassFileConstants.AccStatic;
- /**
- * Abstract property flag.
- *
- * <b>This flag only applies to ECMAScript 4 which is not yet supported</b>
- */
- public static final int AccAbstract = ClassFileConstants.AccAbstract;
- /**
- * Super property flag.
- *
- * <b>This flag only applies to ECMAScript 4 which is not yet supported</b>
- */
- public static final int AccSuper = ClassFileConstants.AccSuper;
- /**
- * Deprecated property flag.
- */
- public static final int AccDeprecated = ClassFileConstants.AccDeprecated;
-
- /**=
- * Varargs method property
- * Used to flag variable arity method declarations.
- *
- * <b>This flag only applies to ECMAScript 4 which is not yet supported</b>
- */
- public static final int AccVarargs = ClassFileConstants.AccVarargs;
-
- /**
- * Not instantiable.
- */
- private Flags() {
- // Not instantiable
- }
- /**
- * Returns whether the given integer includes the <code>abstract</code> modifier.
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @param flags the flags
- * @return <code>true</code> if the <code>abstract</code> modifier is included
- */
- public static boolean isAbstract(int flags) {
- return (flags & AccAbstract) != 0;
- }
- /**
- * Returns whether the given integer includes the indication that the
- * element is deprecated (<code>@deprecated</code> tag in jsdoc comment).
- *
- * @param flags the flags
- * @return <code>true</code> if the element is marked as deprecated
- */
- public static boolean isDeprecated(int flags) {
- return (flags & AccDeprecated) != 0;
- }
- /*
- * Returns whether the given integer does not include one of the
- * <code>public</code>, <code>private</code>, or <code>protected</code> flags.
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @param flags the flags
- * @return <code>true</code> if no visibility flag is set
- */
- public static boolean isPackageDefault(int flags) {
- return (flags & (AccPublic | AccProtected | AccPrivate)) == 0;
- }
- /**
- * Returns whether the given integer includes the <code>private</code> modifier.
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @param flags the flags
- * @return <code>true</code> if the <code>private</code> modifier is included
- */
- public static boolean isPrivate(int flags) {
- return (flags & AccPrivate) != 0;
- }
- /**
- * Returns whether the given integer includes the <code>protected</code> modifier.
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @param flags the flags
- * @return <code>true</code> if the <code>protected</code> modifier is included
- */
- public static boolean isProtected(int flags) {
- return (flags & AccProtected) != 0;
- }
- /**
- * Returns whether the given integer includes the <code>public</code> modifier.
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @param flags the flags
- * @return <code>true</code> if the <code>public</code> modifier is included
- */
- public static boolean isPublic(int flags) {
- return (flags & AccPublic) != 0;
- }
- /**
- * Returns whether the given integer includes the <code>static</code> modifier.
- *
- * @param flags the flags
- * @return <code>true</code> if the <code>static</code> modifier is included
- */
- public static boolean isStatic(int flags) {
- return (flags & AccStatic) != 0;
- }
- /**
- * Returns whether the given integer includes the <code>super</code> modifier.
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @param flags the flags
- * @return <code>true</code> if the <code>super</code> modifier is included
- */
- public static boolean isSuper(int flags) {
- return (flags & AccSuper) != 0;
- }
-
- /*
- * Returns whether the given integer has the <code>AccVarargs</code>
- * bit set.
- *
- * @param flags the flags
- * @return <code>true</code> if the <code>AccVarargs</code> flag is included
- * @see #AccVarargs
- */
- public static boolean isVarargs(int flags) {
- return (flags & AccVarargs) != 0;
- }
-
- /**
- * Returns a standard string describing the given modifier flags.
- * Only modifier flags are included in the output; deprecated,
- * synthetic, bridge, etc. flags are ignored.
- * <p>
- * The flags are output in the following order:
- * <pre>
- * <code>public</code> <code>protected</code> <code>private</code>
- * <code>static</code>
- * <code>abstract</code> <code>final</code> <code>native</code> <code>synchronized</code> <code>transient</code> <code>volatile</code> <code>strictfp</code>
- * </pre>
- * </p>
- * <p>
- * Examples results:
- * <pre>
- * <code>"public static final"</code>
- * <code>"private native"</code>
- * </pre>
- * </p>
- *
- * @param flags the flags
- * @return the standard string representation of the given flags
- */
- public static String toString(int flags) {
- StringBuffer sb = new StringBuffer();
-
- if (isPublic(flags))
- sb.append("public "); //$NON-NLS-1$
- if (isPrivate(flags))
- sb.append("private "); //$NON-NLS-1$
- if (isStatic(flags))
- sb.append("static "); //$NON-NLS-1$
- if (isAbstract(flags))
- sb.append("abstract "); //$NON-NLS-1$
-
- int len = sb.length();
- if (len == 0)
- return ""; //$NON-NLS-1$
- sb.setLength(len - 1);
- return sb.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IAccessRule.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IAccessRule.java
deleted file mode 100644
index e6ff7b24..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IAccessRule.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*******************************************************************************
- * 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;
-
-import org.eclipse.core.runtime.IPath;
-
-/**
- * Describes an access rule to source and class files on a includepath entry.
- * An access rule is composed of a file pattern and a kind (accessible,
- * non accessible, or discouraged).
- * <p>
- * On a given includepath entry, the access rules are considered in the order given
- * when the entry was created. When a source matches an access
- * rule's pattern, the access rule's kind define whether the file is considered
- * accessible, non accessible, or its access is discouraged. If the source
- * file doesn't match any accessible rule, it is considered accessible. A source
- * file that is not accessible or discouraged can still be refered to but it is tagged as being not
- * accessible - the JavaScript validator will create a problem marker for example.
- * The severity of the marker created from a non accessible rule is controled through
- * the {@link JavaScriptCore#COMPILER_PB_FORBIDDEN_REFERENCE} compiler option.
- * The severity of the marker created from a discouraged rule is controled through
- * the {@link JavaScriptCore#COMPILER_PB_DISCOURAGED_REFERENCE} compiler option.
- * Note this is different from inclusion and exclusion patterns on source includepath entries,
- * where a source file that is excluded is not even validated.
- * Files patterns look like relative file paths with wildcards and are interpreted relative
- * to each entry's path.
- * File patterns are case-sensitive and they can contain '**', '*' or '?' wildcards (see
- * {@link IIncludePathEntry#getExclusionPatterns()} for the full description
- * of their syntax and semantics).
- * Note that file patterns must not include the file extension.
- * <code>com/xyz/tests/MyClass</code> is a valid file pattern, whereas
- * <code>com/xyz/tests/MyClass.class</code> is not valid.
- * </p>
- *
- *
- * 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 IAccessRule {
-
- /**
- * Constant indicating that files matching the rule's pattern are accessible.
- */
- int K_ACCESSIBLE = 0;
-
- /**
- * Constant indicating that files matching the rule's pattern are non accessible.
- */
- int K_NON_ACCESSIBLE = 1;
-
- /**
- * Constant indicating that access to the files matching the rule's pattern is discouraged.
- */
- int K_DISCOURAGED = 2;
-
- /**
- * <p>Flag indicating that whether a type matching this rule should be ignored iff a type with
- * the same qualified name can be found on a later includepath entry with a better
- * accessibility.</p>
- * <p>E.g. if a type p.X matches a rule K_NON_ACCESSIBLE | IGNORE_IF_BETTER
- * on a library entry 'lib1' and another type p.X also matches a rule
- * K_DISCOURAGED on library entry 'lib2' ('lib2' being after 'lib1' on the
- * includepath), then p.X from 'lib2' will be used and reported as
- * discouraged.</p>
- *
- */
- int IGNORE_IF_BETTER = 0x100;
-
- /**
- * Returns the file pattern for this access rule.
- *
- * @return the file pattern for this access rule
- */
- IPath getPattern();
-
- /**
- * Returns the kind of this access rule (one of {@link #K_ACCESSIBLE}, {@link #K_NON_ACCESSIBLE}
- * or {@link #K_DISCOURAGED}).
- *
- * @return the kind of this access rule
- */
- int getKind();
-
- /**
- * <p>Returns whether a type matching this rule should be ignored iff a type with
- * the same qualified name can be found on a later includepath entry with a better
- * accessibility.</p>
- * <p>E.g. if a type p.X matches a rule K_NON_ACCESSIBLE | IGNORE_IF_BETTER
- * on a library entry 'lib1' and another type p.X also matches a rule
- * K_DISCOURAGED on library entry 'lib2' ('lib2' being after 'lib1' on the
- * includepath), then p.X from 'lib2' will be used and reported as
- * discouraged.</p>
- *
- * @return whether a type matching this rule should be ignored iff a type
- * with the same qualified name can be found on a later includepath
- * entry with a better accessibility
- */
- boolean ignoreIfBetter();
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IBuffer.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IBuffer.java
deleted file mode 100644
index b46fb929..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IBuffer.java
+++ /dev/null
@@ -1,261 +0,0 @@
-/*******************************************************************************
- * 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;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IProgressMonitor;
-
-/**
- * A buffer contains the text contents of a resource. It is not language-specific.
- * The contents may be in the process of being edited, differing from the actual contents of the
- * underlying resource. A buffer has an owner, which is an <code>IOpenable</code>.
- * If a buffer does not have an underlying resource, saving the buffer has no effect.
- * Buffers can be read-only.
- * <p>
- * Note that javaScript model operations that manipulate an <code>IBuffer</code> (for example,
- * <code>IType.createMethod(...)</code>) ensures that the same line delimiter
- * (either <code>"\n"</code> or <code>"\r"</code> or <code>"\r\n"</code>) is
- * used across the whole buffer. Thus these operations may change the line delimiter(s)
- * included in the string to be append, or replaced.
- * However implementers of this interface should be aware that other clients of <code>IBuffer</code>
- * might not do such transformations beforehand.
- * <p>
- * This interface may be implemented by clients.
- * </p>
- *
- * 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 IBuffer {
-
-/**
- * Adds the given listener for changes to this buffer.
- * Has no effect if an identical listener is already registered or if the buffer
- * is closed.
- *
- * @param listener the listener of buffer changes
- */
-public void addBufferChangedListener(IBufferChangedListener listener);
-/**
- * Appends the given character array to the contents of the buffer.
- * This buffer will now have unsaved changes.
- * Any client can append to the contents of the buffer, not just the owner of the buffer.
- * Reports a buffer changed event.
- * <p>
- * Has no effect if this buffer is read-only or if the buffer is closed.
- *
- * @param text the given character array to append to contents of the buffer
- */
-public void append(char[] text);
-/**
- * Appends the given string to the contents of the buffer.
- * This buffer will now have unsaved changes.
- * Any client can append to the contents of the buffer, not just the owner of the buffer.
- * Reports a buffer changed event.
- * <p>
- * Has no effect if this buffer is read-only or if the buffer is closed.
- *
- * @param text the <code>String</code> to append to the contents of the buffer
- */
-public void append(String text);
-/**
- * Closes the buffer. Any unsaved changes are lost. Reports a buffer changed event
- * with a 0 offset and a 0 length. When this event is fired, the buffer should already
- * be closed.
- * <p>
- * Further operations on the buffer are not allowed, except for close. If an
- * attempt is made to close an already closed buffer, the second attempt has no effect.
- */
-public void close();
-/**
- * Returns the character at the given position in this buffer.
- * <p>
- * The returned value is undefined if the buffer is closed.
- *
- * @param position a zero-based source offset in this buffer
- * @return the character at the given position in this buffer
- */
-public char getChar(int position);
-/**
- * Returns the contents of this buffer as a character array, or <code>null</code> if
- * the buffer has not been initialized.
- * <p>
- * Callers should make no assumption about whether the returned character array
- * is or is not the genuine article or a copy. In other words, if the client
- * wishes to change this array, they should make a copy. Likewise, if the
- * client wishes to hang on to the array in its current state, they should
- * make a copy.
- * </p><p>
- * The returned value is undefined if the buffer is closed.
- *
- * @return the characters contained in this buffer
- */
-public char[] getCharacters();
-/**
- * Returns the contents of this buffer as a <code>String</code>. Like all strings,
- * the result is an immutable value object., It can also answer <code>null</code> if
- * the buffer has not been initialized.
- * <p>
- * The returned value is undefined if the buffer is closed.
- *
- * @return the contents of this buffer as a <code>String</code>
- */
-public String getContents();
-/**
- * Returns number of characters stored in this buffer.
- * <p>
- * The returned value is undefined if the buffer is closed.
- *
- * @return the number of characters in this buffer
- */
-public int getLength();
-/**
- * Returns the JavaScript openable element owning of this buffer.
- *
- * @return the openable element owning this buffer
- */
-public IOpenable getOwner();
-/**
- * Returns the given range of text in this buffer.
- * <p>
- * The returned value is undefined if the buffer is closed.
- *
- * @param offset the zero-based starting offset
- * @param length the number of characters to retrieve
- * @return the given range of text in this buffer
- */
-public String getText(int offset, int length);
-/**
- * Returns the underlying resource for which this buffer was opened,
- * or <code>null</code> if this buffer was not opened on a resource.
- *
- * @return the underlying resource for this buffer, or <code>null</code>
- * if none.
- */
-public IResource getUnderlyingResource();
-/**
- * Returns whether this buffer has been modified since it
- * was opened or since it was last saved.
- * If a buffer does not have an underlying resource, this method always
- * returns <code>true</code>.
- * <p>
- * NOTE: when a buffer does not have unsaved changes, the model may decide to close it
- * to claim some memory back. If the associated element needs to be reopened later on, its
- * buffer factory will be requested to create a new buffer.
- * </p>
- * @return a <code>boolean</code> indicating presence of unsaved changes (in
- * the absence of any underlying resource, it will always return <code>true</code>).
- */
-public boolean hasUnsavedChanges();
-/**
- * Returns whether this buffer has been closed.
- *
- * @return a <code>boolean</code> indicating whether this buffer is closed.
- */
-public boolean isClosed();
-/**
- * Returns whether this buffer is read-only.
- *
- * @return a <code>boolean</code> indicating whether this buffer is read-only
- */
-public boolean isReadOnly();
-/**
- * Removes the given listener from this buffer.
- * Has no affect if an identical listener is not registered or if the buffer is closed.
- *
- * @param listener the listener
- */
-public void removeBufferChangedListener(IBufferChangedListener listener);
-/**
- * Replaces the given range of characters in this buffer with the given text.
- * <code>position</code> and <code>position + length</code> must be in the range [0, getLength()].
- * <code>length</code> must not be negative.
- * <p>
- * Has no effect if this buffer is read-only or if the buffer is closed.
- *
- * @param position the zero-based starting position of the affected text range in this buffer
- * @param length the length of the affected text range in this buffer
- * @param text the replacing text as a character array
- */
-public void replace(int position, int length, char[] text);
-/**
- * Replaces the given range of characters in this buffer with the given text.
- * <code>position</code> and <code>position + length</code> must be in the range [0, getLength()].
- * <code>length</code> must not be negative.
- * <p>
- * Has no effect if this buffer is read-only or if the buffer is closed.
- *
- * @param position the zero-based starting position of the affected text range in this buffer
- * @param length the length of the affected text range in this buffer
- * @param text the replacing text as a <code>String</code>
- */
-public void replace(int position, int length, String text);
-/**
- * Saves the contents of this buffer to its underlying resource. If
- * successful, this buffer will have no unsaved changes.
- * The buffer is left open. Saving a buffer with no unsaved
- * changes has no effect - the underlying resource is not changed.
- * If the buffer does not have an underlying resource or is read-only, this
- * has no effect.
- * <p>
- * The <code>force</code> parameter controls how this method deals with
- * cases where the workbench is not completely in sync with the local file system.
- * If <code>false</code> is specified, this method will only attempt
- * to overwrite a corresponding file in the local file system provided
- * it is in sync with the workbench. This option ensures there is no
- * unintended data loss; it is the recommended setting.
- * However, if <code>true</code> is specified, an attempt will be made
- * to write a corresponding file in the local file system,
- * overwriting any existing one if need be.
- * In either case, if this method succeeds, the resource will be marked
- * as being local (even if it wasn't before).
- * <p>
- * Has no effect if this buffer is read-only or if the buffer is closed.
- *
- * @param progress the progress monitor to notify
- * @param force a <code> boolean </code> flag indicating how to deal with resource
- * inconsistencies.
- *
- * @exception JavaScriptModelException if an error occurs writing the buffer
- * to the underlying resource
- *
- * @see org.eclipse.core.resources.IFile#setContents(java.io.InputStream, boolean, boolean, org.eclipse.core.runtime.IProgressMonitor)
- */
-public void save(IProgressMonitor progress, boolean force) throws JavaScriptModelException;
-/**
- * Sets the contents of this buffer to the given character array.
- * This buffer will now have unsaved changes.
- * Any client can set the contents of the buffer, not just the owner of the buffer.
- * Reports a buffer changed event.
- * <p>
- * Equivalent to <code>replace(0,getLength(),contents)</code>.
- * </p><p>
- * Has no effect if this buffer is read-only or if the buffer is closed.
- *
- * @param contents the new contents of this buffer as a character array
- */
-public void setContents(char[] contents);
-/**
- * Sets the contents of this buffer to the given <code>String</code>.
- * This buffer will now have unsaved changes.
- * Any client can set the contents of the buffer, not just the owner of the buffer.
- * Reports a buffer changed event.
- * <p>
- * Equivalent to <code>replace(0,getLength(),contents)</code>.
- * </p><p>
- * Has no effect if this buffer is read-only or if the buffer is closed.
- *
- * @param contents the new contents of this buffer as a <code>String</code>
- */
-public void setContents(String contents);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IBufferChangedListener.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IBufferChangedListener.java
deleted file mode 100644
index ed5c6342..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IBufferChangedListener.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core;
-
-/**
- * A listener, which gets notified when the contents of a specific buffer
- * have changed, or when the buffer is closed.
- * When a buffer is closed, the listener is notified <em>after</em> the buffer has been closed.
- * A listener is not notified when a buffer is saved.
- * <p>
- * This interface may be implemented by clients.
- * </p>
- *
- * 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 IBufferChangedListener {
-
- /**
- * Notifies that the given event has occurred.
- *
- * @param event the change event
- */
- public void bufferChanged(BufferChangedEvent event);
-}
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
deleted file mode 100644
index dd41b9dc..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IBufferFactory.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*******************************************************************************
- * 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;
-
-/**
- * A factory that creates <code>IBuffer</code>s for openables.
- * <p>
- * This interface may be implemented by clients.
- * </p>
- * @deprecated Use {@link WorkingCopyOwner} instead
- *
- * 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 IBufferFactory {
-
- /**
- * Creates a buffer for the given owner.
- * The new buffer will be initialized with the contents of the owner
- * if and only if it was not already initialized by the factory (a buffer is uninitialized if
- * its content is <code>null</code>).
- *
- * @param owner the owner of the buffer
- * @return the newly created buffer
- * @see IBuffer
- */
- IBuffer createBuffer(IOpenable owner);
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IClassFile.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IClassFile.java
deleted file mode 100644
index c98e698e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IClassFile.java
+++ /dev/null
@@ -1,63 +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.core;
-
-
-/**
- * Represents an entire non-editable JavaScript file.
- * non-editable JavaScript file elements need to be opened before they can be navigated.
- * If a file cannot be parsed, its structure remains unknown. Use
- * <code>IJavaScriptElement.isStructureKnown</code> to determine whether this is the
- * case.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * 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 IClassFile extends ITypeRoot {
-
-/**
- * Returns the bytes contained in this file.
- *
- * @return the bytes contained in this file
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
-byte[] getBytes() throws JavaScriptModelException;
-
-/**
- * Returns the first type contained in this file.
- * This is a handle-only method. The type may or may not exist.
- *
- * @return the type contained in this file
- *
- */
-IType getType();
-public IType[] getTypes() throws JavaScriptModelException ;
-
-
-/*
- * Returns whether this type is edit. This is not guaranteed to be
- * instantaneous, as it may require parsing the underlying file.
- *
- * @return <code>true</code> if the file represents a class.
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
-boolean isClass() throws JavaScriptModelException;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ICodeAssist.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ICodeAssist.java
deleted file mode 100644
index f8d85da7..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ICodeAssist.java
+++ /dev/null
@@ -1,127 +0,0 @@
-/*******************************************************************************
- * 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;
-
-/**
- * Common protocol for JavaScript elements that support source code assist and code
- * resolve.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * 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 ICodeAssist {
-
- /**
- * Performs code completion at the given offset position in this javaScript unit,
- * reporting results to the given completion requestor. The <code>offset</code>
- * is the 0-based index of the character, after which code assist is desired.
- * An <code>offset</code> of -1 indicates to code assist at the beginning of this
- * javaScript unit.
- * <p>
- *
- * @param offset the given offset position
- * @param requestor the given completion requestor
- * @exception JavaScriptModelException if code assist could not be performed. Reasons include:<ul>
- * <li>This JavaScript element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> The position specified is < -1 or is greater than this javaScript unit's
- * source length (INDEX_OUT_OF_BOUNDS)
- * </ul>
- *
- * @exception IllegalArgumentException if <code>requestor</code> is <code>null</code>
- */
- void codeComplete(int offset, CompletionRequestor requestor)
- throws JavaScriptModelException;
-
- /**
- * Performs code completion at the given offset position in this javaScript unit,
- * reporting results to the given completion requestor. The <code>offset</code>
- * is the 0-based index of the character, after which code assist is desired.
- * An <code>offset</code> of -1 indicates to code assist at the beginning of this
- * javaScript unit.
- * It considers types in the working copies with the given owner first. In other words,
- * the owner's working copies will take precedence over their original javaScript units
- * in the workspace.
- * <p>
- * Note that if a working copy is empty, it will be as if the original javaScript
- * unit had been deleted.
- * </p>
- *
- * @param offset the given offset position
- * @param requestor the given completion requestor
- * @param owner the owner of working copies that take precedence over their original javaScript units
- * @exception JavaScriptModelException if code assist could not be performed. Reasons include:<ul>
- * <li>This JavaScript element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> The position specified is < -1 or is greater than this javaScript unit's
- * source length (INDEX_OUT_OF_BOUNDS)
- * </ul>
- *
- * @exception IllegalArgumentException if <code>requestor</code> is <code>null</code>
- */
- void codeComplete(int offset, CompletionRequestor requestor, WorkingCopyOwner owner)
- throws JavaScriptModelException;
-
- /**
- * Returns the JavaScript elements corresponding to the given selected text in this javaScript unit.
- * The <code>offset</code> is the 0-based index of the first selected character.
- * The <code>length</code> is the number of selected characters.
- * <p>
- * Note that if the <code>length</code> is 0 and the <code>offset</code> is inside an identifier
- * or the index just after an identifier then this identifier is considered as the selection.
- * </p>
- *
- * @param offset the given offset position
- * @param length the number of selected characters
- * @return the JavaScript elements corresponding to the given selected text
- *
- * @exception JavaScriptModelException if code resolve could not be performed. Reasons include:
- * <ul>
- * <li>This JavaScript element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> The range specified is not within this element's
- * source range (INDEX_OUT_OF_BOUNDS)
- * </ul>
- *
- */
- IJavaScriptElement[] codeSelect(int offset, int length) throws JavaScriptModelException;
- /**
- * Returns the JavaScript elements corresponding to the given selected text in this javaScript unit.
- * The <code>offset</code> is the 0-based index of the first selected character.
- * The <code>length</code> is the number of selected characters.
- * It considers types in the working copies with the given owner first. In other words,
- * the owner's working copies will take precedence over their original javaScript units
- * in the workspace.
- * <p>
- * Note that if the <code>length</code> is 0 and the <code>offset</code> is inside an identifier
- * or the index just after an identifier then this identifier is considered as the selection.
- * </p>
- * <p>
- * Note that if a working copy is empty, it will be as if the original javaScript
- * unit had been deleted.
- * </p>
- *
- * @param offset the given offset position
- * @param length the number of selected characters
- * @param owner the owner of working copies that take precedence over their original javaScript units
- * @return the JavaScript elements corresponding to the given selected text
- *
- * @exception JavaScriptModelException if code resolve could not be performed. Reasons include:
- * <ul>
- * <li>This JavaScript element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> The range specified is not within this element's
- * source range (INDEX_OUT_OF_BOUNDS)
- * </ul>
- */
- IJavaScriptElement[] codeSelect(int offset, int length, WorkingCopyOwner owner) throws JavaScriptModelException;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ICorrectionRequestor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ICorrectionRequestor.java
deleted file mode 100644
index f8a158b9..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ICorrectionRequestor.java
+++ /dev/null
@@ -1,137 +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.core;
-
-/**
- * A callback interface for receiving javaScript problem correction.
- *
- * 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 ICorrectionRequestor {
-/*
- * Notification of a class correction.
- *
- * @param packageName Declaring package name of the class.
- * @param className Name of the class.
- * @param correctionName The correction for the class.
- * @param modifiers The modifiers of the class.
- * @param correctionStart The start position of insertion of the correction of the class.
- * @param correctionEnd The end position of insertion of the correction of the class.
- *
- * NOTE - All package and type names are presented in their readable form:
- * Package names are in the form "a.b.c".
- * Nested type names are in the qualified form "A.M".
- * The default package is represented by an empty array.
- */
-void acceptClass(
- char[] packageName,
- char[] className,
- char[] correctionName,
- int modifiers,
- int correctionStart,
- int correctionEnd);
-/**
- * Notification of a field/var correction.
- *
- * @param declaringTypePackageName Name of the package in which the type that contains this field is declared.
- * @param declaringTypeName Name of the type declaring this field.
- * @param name Name of the field.
- * @param typePackageName Name of the package in which the type of this field is declared.
- * @param typeName Name of the type of this field.
- * @param correctionName The correction for the field.
- * @param modifiers The modifiers of this field.
- * @param correctionStart The start position of insertion of the correction of this field.
- * @param correctionEnd The end position of insertion of the correction of this field.
- *
- */
-void acceptField(
- char[] declaringTypePackageName,
- char[] declaringTypeName,
- char[] name,
- char[] typePackageName,
- char[] typeName,
- char[] correctionName,
- int modifiers,
- int correctionStart,
- int correctionEnd);
-/**
- * Notification of a local variable correction.
- *
- * @param name Name of the local variable.
- * @param typePackageName Name of the package in which the type of this local variable is declared.
- * @param typeName Name of the type of this local variable.
- * @param modifiers The modifiers of this local variable.
- * @param correctionStart The start position of insertion of the correction of this local variable.
- * @param correctionEnd The end position of insertion of the correction of this local variable.
- *
- */
-void acceptLocalVariable(
- char[] name,
- char[] typePackageName,
- char[] typeName,
- int modifiers,
- int correctionStart,
- int correctionEnd);
-/**
- * Notification of a method correction.
- *
- * @param declaringTypePackageName Name of the package in which the type that contains this method is declared.
- * @param declaringTypeName Name of the type declaring this method.
- * @param selector Name of the method.
- * @param parameterPackageNames Names of the packages in which the parameter types are declared.
- * Should contain as many elements as parameterTypeNames.
- * @param parameterTypeNames Names of the parameter types.
- * Should contain as many elements as parameterPackageNames.
- * @param parameterNames Names of the parameters.
- * Should contain as many elements as parameterPackageNames.
- * @param returnTypePackageName Name of the package in which the return type is declared.
- * @param returnTypeName Name of the return type of this method, should be <code>null</code> for a constructor.
- * @param correctionName The correction for the method.
- * Can include zero, one or two brackets. If the closing bracket is included, then the cursor should be placed before it.
- * @param modifiers The modifiers of this method.
- * @param correctionStart The start position of insertion of the correction of this method.
- * @param correctionEnd The end position of insertion of the correction of this method.
- *
- * NOTE: parameter names can be retrieved from the source model after the user selects a specific method.
- */
-void acceptMethod(
- char[] declaringTypePackageName,
- char[] declaringTypeName,
- char[] selector,
- char[][] parameterPackageNames,
- char[][] parameterTypeNames,
- char[][] parameterNames,
- char[] returnTypePackageName,
- char[] returnTypeName,
- char[] correctionName,
- int modifiers,
- int correctionStart,
- int correctionEnd);
-/**
- * Notification of a package correction.
- *
- * @param packageName The package name.
- * @param correctionName The correction for the package.
- * Can include '.*;' for imports.
- * @param correctionStart The start position of insertion of the correction of this package.
- * @param correctionEnd The end position of insertion of the correction of this package.
- *
- * <b>This Method only applies to ECMAScript 4 which is not yet supported</b>
- */
-void acceptPackage(
- char[] packageName,
- char[] correctionName,
- int correctionStart,
- int correctionEnd);
-}
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
deleted file mode 100644
index 5e347be3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IElementChangedListener.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*******************************************************************************
- * 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;
-
-/**
- * An element changed listener receives notification of changes to JavaScript elements
- * maintained by the JavaScript model.
- * <p>
- * This interface may be implemented by clients.
- * </p>
- *
- * 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 IElementChangedListener {
-
-/**
- * Notifies that one or more attributes of one or more JavaScript elements have changed.
- * The specific details of the change are described by the given event.
- *
- * @param event the change event
- */
-public void elementChanged(ElementChangedEvent event);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IField.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IField.java
deleted file mode 100644
index a7b58621..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IField.java
+++ /dev/null
@@ -1,64 +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
- * IBM Corporation - added J2SE 1.5 support
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core;
-
-/**
- * Represents a field declared in a type or a var declared at the file scope.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * 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 IField extends IMember {
-/**
- * Returns the simple name of this field.
- * @return the simple name of this field.
- */
-String getElementName();
-/**
- * Returns the binding key for this field. A binding key is a key that uniquely
- * identifies this field. It allows access to generic info for parameterized
- * fields.
- *
- * @return the binding key for this field
- * @see org.eclipse.wst.jsdt.core.dom.IBinding#getKey()
- * @see BindingKey
- */
-String getKey();
-/**
- * Returns the type signature of this field.
- * <p>
- * The type signature may be either unresolved (for source types)
- * or resolved (for binary types), and either basic (for basic types)
- * or rich (for parameterized types). See {@link Signature} for details.
- * </p>
- *
- * @return the type signature of this field
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- * @see Signature
- */
-String getTypeSignature() throws JavaScriptModelException;
-
-/**
- * Returns whether this field represents a resolved field.
- * If a field is resoved, its key contains resolved information.
- *
- * @return whether this field represents a resolved field.
- */
-boolean isResolved();
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IFunction.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IFunction.java
deleted file mode 100644
index beedf909..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IFunction.java
+++ /dev/null
@@ -1,168 +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
- * IBM Corporation - added J2SE 1.5 support
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core;
-
-/**
- * Represents a function or a method (or constructor) declared in a type.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * 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 IFunction extends IMember {
-/**
- * Returns the simple name of this function or method.
- * For a constructor, this returns the simple name of the declaring type.
- * Note: This holds whether the constructor appears in a source or binary type
- * This is a handle-only method.
- * @return the simple name of this method
- */
-String getElementName();
-/**
- * Returns the number of parameters of this method.
- * This is a handle-only method.
- *
- * @return the number of parameters of this method
- */
-int getNumberOfParameters();
-/**
- * Returns the binding key for this method. A binding key is a key that uniquely
- * identifies this method. It allows access to generic info for parameterized
- * methods.
- *
- * @return the binding key for this method
- * @see org.eclipse.wst.jsdt.core.dom.IBinding#getKey()
- * @see BindingKey
- */
-String getKey();
-/**
- * Returns the names of parameters in this method.
- * Returns an empty array if this method has no parameters.
- *
- * <p>For example, a method declared as <code>function foo( text, length)</code>
- * would return the array <code>{"text","length"}</code>.
- * </p>
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return the names of parameters in this method, an empty array if this method has no parameters
- */
-String[] getParameterNames() throws JavaScriptModelException;
-/**
- * Returns the type signatures for the parameters of this method.
- * Returns an empty array if this method has no parameters.
- * This is a handle-only method.
- * <p>
- * The type signatures may be either unresolved (for source types)
- * or resolved (for binary types), and either basic (for basic types)
- * or rich (for parameterized types). See {@link Signature} for details.
- * </p>
- *
- * @return the type signatures for the parameters of this method, an empty array if this method has no parameters
- * @see Signature
- */
-String[] getParameterTypes();
-/**
- * Returns the names of parameters in this method.
- * Returns an empty array if this method has no parameters.
- *
- * <p>For example, a method declared as <code>function foo( text, length)</code>
- * would return the array <code>{"text","length"}</code>. For the same method in a
- * binary, this would return <code>{"arg0", "arg1"}</code>.
- * </p>
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return the names of parameters in this method, an empty array if this method has no parameters
- */
-String[] getRawParameterNames() throws JavaScriptModelException;
-/**
- * Returns the type signature of the return value of this method.
- * For constructors, this returns the signature for void.
- * <p>
- * Until EMCAScript 4 is supported, types are inferred by analying the code, and are not necessarily accurate.
- * </p>
- * <p>
- * For example, a source method declared as <code>function getName(){return "abc"}</code>
- * would return <code>"QString;"</code>.
- * </p>
- * <p>
- * The type signature may be either unresolved (for source types)
- * or resolved (for binary types), and either basic (for basic types)
- * or rich (for parameterized types). See {@link Signature} for details.
- * </p>
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return the type signature of the return value of this method, void for constructors
- * @see Signature
- */
-String getReturnType() throws JavaScriptModelException;
-/**
- * Returns the signature of this method. This includes the signatures for the
- * parameter types and return type, but does not include the method name,
- * exception types, or type parameters.
- * <p>
- * For example, a source method declared as <code>public void foo(String text, int length)</code>
- * would return <code>"(QString;I)V"</code>.
- * </p>
- * <p>
- * The type signatures embedded in the method signature may be either unresolved
- * (for source types) or resolved (for binary types), and either basic (for
- * basic types) or rich (for parameterized types). See {@link Signature} for
- * details.
- * </p>
- *
- * @return the signature of this method
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @see Signature
- */
-String getSignature() throws JavaScriptModelException;
-/**
- * Returns whether this method is a constructor.
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- *
- * @return true if this method is a constructor, false otherwise
- */
-boolean isConstructor() throws JavaScriptModelException;
-
-/**
- * Returns whether this method represents a resolved method.
- * If a method is resoved, its key contains resolved information.
- *
- * @return whether this method represents a resolved method.
- */
-boolean isResolved();
-/**
- * Returns whether this method is similar to the given method.
- * Two methods are similar if:
- * <ul>
- * <li>their element names are equal</li>
- * <li>they have the same number of parameters</li>
- * <li>the simple names of their parameter types are equal</li>
- * </ul>
- * This is a handle-only method.
- *
- * @param method the given method
- * @return true if this method is similar to the given method.
- * @see Signature#getSimpleName(char[])
- */
-boolean isSimilar(IFunction method);
-public IFunction getFunction(String selector, String[] parameterTypeSignatures) ;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IFunctionContainer.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IFunctionContainer.java
deleted file mode 100644
index 1ea84535..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IFunctionContainer.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core;
-
-
-
-/**
- * Represents a container of methods and fields/vars (either an <code>IJavaScriptUnit</code>
- * or an <code>IType</code>).
- *
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * <p>
- * 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.
- * </p>
-
- */
-public interface IFunctionContainer {
-
-
-/**
- * Returns the field with the specified name
- * in this type (for example, <code>"bar"</code>).
- * This is a handle-only method. The field may or may not exist.
- *
- * @param name the given name
- * @return the field with the specified name in this type
- */
-IField getField(String name);
-/**
- * Returns the fields declared by this type or javascript file.
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return the fields declared by this type or file
- */
-IField[] getFields() throws JavaScriptModelException;
-
-/**
- * Returns the method with the specified name and parameter types
- * in this type (for example, <code>"foo", {"I", "QString;"}</code>).
- * To get the handle for a constructor, the name specified must be the
- * simple name of the enclosing type.
- * This is a handle-only method. The method may or may not be present.
- * <p>
- * The type signatures may be either unresolved (for source types)
- * or resolved (for binary types), and either basic (for basic types)
- * or rich (for parameterized types). See {@link Signature} for details.
- * </p>
- *
- * @param name the given name
- * @param parameterTypeSignatures the given parameter types
- * @return the method with the specified name and parameter types in this type
- */
-IFunction getFunction(String name, String[] parameterTypeSignatures);
-
-/**
- * Returns the methods and constructors declared by this type or file.
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return the methods and constructors declared by this type
- */
-IFunction[] getFunctions() throws JavaScriptModelException;
-
-/**
- * Returns the type with the specified name
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return the type with the specified name in this file
- */
-IType getType(String name);
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IImportContainer.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IImportContainer.java
deleted file mode 100644
index d89a1416..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IImportContainer.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*******************************************************************************
- * 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;
-
-/**
- * Represents an import container is a child of a JavaScript unit that contains
- * all (and only) the import declarations. If a JavaScript unit has no import
- * declarations, no import container will be present.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * <b>This Interface only applies to ECMAScript 4 which is not yet supported</b>
- *
- * 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 IImportContainer extends IJavaScriptElement, IParent, ISourceReference {
-/**
- * Returns the first import declaration in this import container with the given name.
- * This is a handle-only method. The import declaration may or may not exist.
- *
- * @param name the given name
- *
- * @return the first import declaration in this import container with the given name
- */
-IImportDeclaration getImport(String name);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IImportDeclaration.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IImportDeclaration.java
deleted file mode 100644
index 179bc32a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IImportDeclaration.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*******************************************************************************
- * 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
- * IBM Corporation - added J2SE 1.5 support
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core;
-
-/**
- * Represents an import declaration in JavaScript unit.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * <b>This Interface only applies to ECMAScript 4 which is not yet supported</b>
- *
- * 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 IImportDeclaration extends IJavaScriptElement, ISourceReference, ISourceManipulation {
-/**
- * Returns the name that has been imported.
- *
- * @return the name that has been imported
- */
-String getElementName();
-/**
- * Returns the modifier flags for this import. The flags can be examined using class
- * <code>Flags</code>. Only the static flag is meaningful for import declarations.
- *
- * @return the modifier flags for this import
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @see Flags
- */
-int getFlags() throws JavaScriptModelException;
-
-/*
- * Returns whether the import is on-demand. An import is on-demand if it ends
- * with <code>".*"</code>.
- * @return true if the import is on-demand, false otherwise
- */
-boolean isOnDemand();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IIncludePathAttribute.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IIncludePathAttribute.java
deleted file mode 100644
index d3d2b92c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IIncludePathAttribute.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core;
-
-import org.eclipse.wst.jsdt.internal.core.ClasspathAttribute;
-
-/**
- * A includepath attribute defines a name/value pair that can be persisted with a includepath entry. Such an attribute
- * can be created using the factory method {@link JavaScriptCore#newIncludepathAttribute(String, String) newClasspathAttribute(String name, String value)}.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * @see JavaScriptCore#newContainerEntry(
- * org.eclipse.core.runtime.IPath containerPath,
- * IAccessRule[] accessRules,
- * IIncludePathAttribute[] extraAttributes,
- * boolean isExported)
- * @see JavaScriptCore#newLibraryEntry(
- * org.eclipse.core.runtime.IPath path,
- * org.eclipse.core.runtime.IPath sourceAttachmentPath,
- * org.eclipse.core.runtime.IPath sourceAttachmentRootPath,
- * IAccessRule[] accessRules,
- * IIncludePathAttribute[] extraAttributes,
- * boolean isExported)
- * @see JavaScriptCore#newProjectEntry(
- * org.eclipse.core.runtime.IPath path,
- * IAccessRule[] accessRules,
- * boolean combineAccessRestrictions,
- * IIncludePathAttribute[] extraAttributes,
- * boolean isExported)
- * @see JavaScriptCore#newSourceEntry(
- * org.eclipse.core.runtime.IPath path,
- * org.eclipse.core.runtime.IPath[] inclusionPatterns,
- * org.eclipse.core.runtime.IPath[] exclusionPatterns,
- * org.eclipse.core.runtime.IPath specificOutputLocation,
- * IIncludePathAttribute[] extraAttributes)
- * @see JavaScriptCore#newVariableEntry(
- * org.eclipse.core.runtime.IPath variablePath,
- * org.eclipse.core.runtime.IPath variableSourceAttachmentPath,
- * org.eclipse.core.runtime.IPath variableSourceAttachmentRootPath,
- * IAccessRule[] accessRules,
- * IIncludePathAttribute[] extraAttributes,
- * boolean isExported)
- *
- * 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 IIncludePathAttribute {
-
- /**
- * Constant for the name of the jsdoc location attribute.
- *
- */
- String JSDOC_LOCATION_ATTRIBUTE_NAME = "javadoc_location"; //$NON-NLS-1$
-
- /**
- * Constant for the name of the optional attribute. The possible values
- * for this attribute are <code>"true"</code> or <code>"false"</code>.
- * When not present, <code>"false"</code> is assumed.
- * If the value of this attribute is <code>"true"</code>, the includepath entry
- * is optional. If the underlying resource or jar file doesn't exist, no error
- * is reported and the includepath entry is ignored.
- */
- String OPTIONAL = "optional"; //$NON-NLS-1$
-
- /**
- * Returns the name of this includepath attribute.
- *
- * @return the name of this includepath attribute.
- */
- String getName();
-
- /**
- * Returns the value of this includepath attribute.
- *
- * @return the value of this includepath attribute.
- */
- String getValue();
-
- public static final ClasspathAttribute HIDE = new ClasspathAttribute("hide","true"); //$NON-NLS-1$ //$NON-NLS-2$
-
-}
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
deleted file mode 100644
index fde5de47..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IIncludePathEntry.java
+++ /dev/null
@@ -1,395 +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.core;
-
-import org.eclipse.core.runtime.IPath;
-
-/**
- * An entry on a JavaScript project includepath identifying one or more package fragment
- * roots. A includepath entry has a content kind (either source,
- * {@link IPackageFragmentRoot#K_SOURCE}, or binary, {@link IPackageFragmentRoot#K_BINARY}), which is inherited
- * by each package fragment root and package fragment associated with the entry.
- * <p>
- * A includepath entry can refer to any of the following:<ul>
- *
- * <li>Source code in the current project. In this case, the entry identifies a
- * root folder in the current project containing package fragments and
- * source files with one of the {@link JavaScriptCore#getJavaScriptLikeExtensions()
- * JavaScript-like extensions}. The root folder itself represents a default
- * package, subfolders represent package fragments, and files with a
- * JavaScript-like extension (e.g. <code>.js</code> files)
- * represent javaScript files. All javaScript files will be compiled when
- * the project is built. The includepath entry must specify the
- * absolute path to the root folder. Entries of this kind are
- * associated with the {@link #CPE_SOURCE} constant.
- * Source includepath entries can carry inclusion and exclusion patterns for
- * selecting which source files appear as javaScript
- * units and get compiled when the project is built.
- * </li>
- *
- * <li>A binary library in the current project, in another project, or in the external
- * file system. In this case the entry identifies non-editable files. Entries
- * of this kind are associated with the {@link #CPE_LIBRARY} constant.</li>
- *
- * <li>A required project. In this case the entry identifies another project in
- * the workspace. When performing other
- * "development" operations - such as code assist, code resolve, type hierarchy
- * creation, etc. - the source code of the project is referred to. Thus, development
- * is performed against a required project's source code. The
- * includepath entry must specify the absolute path to the
- * project. Entries of this kind are associated with the {@link #CPE_PROJECT}
- * constant.
- * Note: referencing a required project with a includepath entry refers to the source
- * code or associated <code>.class</code> files located in its output location.
- * It will also automatically include any other libraries or projects that the required project's includepath
- * refers to, iff the corresponding includepath entries are tagged as being exported
- * ({@link IIncludePathEntry#isExported}).
- * Unless exporting some includepath entries, includepaths are not chained by default -
- * each project must specify its own includepath in its entirety.</li>
- *
- * <li> A path beginning in a includepath variable defined globally to the workspace.
- * Entries of this kind are associated with the {@link #CPE_VARIABLE} constant.
- * Includepath variables are created using {@link JavaScriptCore#setIncludepathVariable(String, IPath, org.eclipse.core.runtime.IProgressMonitor)},
- * and gets resolved, to either a project or library entry, using
- * {@link JavaScriptCore#getResolvedIncludepathEntry(IIncludePathEntry)}.
- * It is also possible to register an automatic initializer ({@link JsGlobalScopeVariableInitializer}),
- * which will be invoked through the extension point "org.eclipse.wst.jsdt.core.JsGlobalScopeVariableInitializer".
- * After resolution, a includepath variable entry may either correspond to a project or a library entry. </li>
- *
- * <li> A named includepath container identified by its container path.
- * A includepath container provides a way to indirectly reference a set of includepath entries through
- * a includepath entry of kind {@link #CPE_CONTAINER}. Typically, a includepath container can
- * be used to describe a complex library composed of multiple files, projects or includepath variables,
- * considering also that containers can be mapped differently on each project. Several projects can
- * reference the same generic container path, but have each of them actually bound to a different
- * container object.
- * The container path is a formed by a first ID segment followed with extra segments,
- * which can be used as additional hints for resolving this container reference. If no container was ever
- * recorded for this container path onto this project (using {@link JavaScriptCore#setJsGlobalScopeContainer},
- * then a {@link JsGlobalScopeContainerInitializer} will be activated if any was registered for this
- * container ID onto the extension point "org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer".
- * A includepath container entry can be resolved explicitly using {@link JavaScriptCore#getJsGlobalScopeContainer}
- * and the resulting container entries can contain any non-container entry. In particular, it may contain variable
- * entries, which in turn needs to be resolved before being directly used.
- * <br> Also note that the container resolution APIs include an IJavaScriptProject argument, so as to allow the same
- * container path to be interpreted in different ways for different projects. </li>
- * </ul>
- * </p>
- * The result of {@link IJavaScriptProject#getResolvedClasspath} will have all entries of type
- * {@link #CPE_VARIABLE} and {@link #CPE_CONTAINER} resolved to a set of
- * {@link #CPE_SOURCE}, {@link #CPE_LIBRARY} or {@link #CPE_PROJECT}
- * includepath entries.
- * <p>
- * Any includepath entry other than a source folder (kind {@link #CPE_SOURCE}) can
- * be marked as being exported. Exported entries are automatically contributed to
- * dependent projects, along with the project's default output folder, which is
- * implicitly exported, and any auxiliary output folders specified on source
- * includepath entries. The project's output folder(s) are always listed first,
- * followed by the any exported entries.
- * <p>
- * This interface is not intended to be implemented by clients.
- * Includepath entries can be created via methods on {@link JavaScriptCore}.
- * </p>
- *
- * @see JavaScriptCore#newLibraryEntry(org.eclipse.core.runtime.IPath, org.eclipse.core.runtime.IPath, org.eclipse.core.runtime.IPath)
- * @see JavaScriptCore#newProjectEntry(org.eclipse.core.runtime.IPath)
- * @see JavaScriptCore#newSourceEntry(org.eclipse.core.runtime.IPath)
- * @see JavaScriptCore#newVariableEntry(org.eclipse.core.runtime.IPath, org.eclipse.core.runtime.IPath, org.eclipse.core.runtime.IPath)
- * @see JavaScriptCore#newContainerEntry(org.eclipse.core.runtime.IPath)
- * @see JsGlobalScopeVariableInitializer
- * @see JsGlobalScopeContainerInitializer
- *
- * 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 IIncludePathEntry {
-
- /**
- * Entry kind constant describing a includepath entry identifying a
- * library.
- */
- int CPE_LIBRARY = 1;
-
- /**
- * Entry kind constant describing a includepath entry identifying a
- * required project.
- */
- int CPE_PROJECT = 2;
-
- /**
- * Entry kind constant describing a includepath entry identifying a
- * folder containing package fragments with source code
- * to be validated.
- */
- int CPE_SOURCE = 3;
-
- /**
- * Entry kind constant describing a includepath entry defined using
- * a path that begins with a includepath variable reference.
- */
- int CPE_VARIABLE = 4;
-
- /**
- * Entry kind constant describing a includepath entry representing
- * a name includepath container.
- */
- int CPE_CONTAINER = 5;
-
- /**
- * Returns whether the access rules of the project's exported entries should be combined with this entry's access rules.
- * Returns true for container entries.
- * Returns false otherwise.
- *
- * @return whether the access rules of the project's exported entries should be combined with this entry's access rules
- */
- boolean combineAccessRules();
-
- /**
- * Returns the possibly empty list of access rules for this entry.
- *
- * @return the possibly empty list of access rules for this entry
- */
- IAccessRule[] getAccessRules();
- /**
- * Returns the kind of files found in the package fragments identified by this
- * includepath entry.
- *
- * @return {@link IPackageFragmentRoot#K_SOURCE} for files containing
- * source code, and {@link IPackageFragmentRoot#K_BINARY} for binary
- * class files.
- * There is no specified value for an entry denoting a variable ({@link #CPE_VARIABLE})
- * or a includepath container ({@link #CPE_CONTAINER}).
- */
- int getContentKind();
-
- /**
- * Returns the kind of this includepath entry.
- *
- * @return one of:
- * <ul>
- * <li>{@link #CPE_SOURCE} - this entry describes a source root in
- its project
- * <li>{@link #CPE_LIBRARY} - this entry describes a folder
- containing non-editable files
- * <li>{@link #CPE_PROJECT} - this entry describes another project
- *
- * <li>{@link #CPE_VARIABLE} - this entry describes a project or library
- * indirectly via a includepath variable in the first segment of the path
- * *
- * <li>{@link #CPE_CONTAINER} - this entry describes set of entries
- * referenced indirectly via a includepath container
- * </ul>
- */
- int getEntryKind();
-
- /**
- * Returns the set of patterns used to exclude resources or classes associated with
- * this includepath entry.
- * <p>
- * For source includepath entries,
- * exclusion patterns allow specified portions of the resource tree rooted
- * at this source entry's path to be filtered out. If no exclusion patterns
- * are specified, this source entry includes all relevent files. Each path
- * specified must be a relative path, and will be interpreted relative
- * to this source entry's path. File patterns are case-sensitive. A file
- * matched by one or more of these patterns is excluded from the
- * corresponding package fragment root.
- * Exclusion patterns have higher precedence than inclusion patterns;
- * in other words, exclusion patterns can remove files for the ones that
- * are to be included, not the other way around.
- * </p>
- * <p>
- * The pattern mechanism is similar to Ant's. Each pattern is represented as
- * a relative path. The path segments can be regular file or folder names or simple patterns
- * involving standard wildcard characters.
- * </p>
- * <p>
- * '*' matches 0 or more characters within a segment. So
- * <code>*.js</code> matches <code>.js</code>, <code>a.js</code>
- * and <code>Foo.js</code>, but not <code>Foo.properties</code>
- * (does not end with <code>.js</code>).
- * </p>
- * <p>
- * '?' matches 1 character within a segment. So <code>?.js</code>
- * matches <code>a.js</code>, <code>A.js</code>,
- * but not <code>.js</code> or <code>xyz.js</code> (neither have
- * just one character before <code>.js</code>).
- * </p>
- * <p>
- * Combinations of *'s and ?'s are allowed.
- * </p>
- * <p>
- * The special pattern '**' matches zero or more segments. In a source entry,
- * a path like <code>tests/</code> that ends in a trailing separator is interpreted
- * as <code>tests/&#42;&#42;</code>, and would match everything under
- * the folder named <code>tests</code>.
- * </p>
- * <p>
- * Example patterns in source entries (assuming that "js" is the only {@link JavaScriptCore#getJavaScriptLikeExtensions() JavaScript-like extension}):
- * <ul>
- * <li>
- * <code>tests/&#42;&#42;</code> (or simply <code>tests/</code>)
- * matches all files under a root folder
- * named <code>tests</code>. This includes <code>tests/Foo.js</code>
- * and <code>tests/com/example/Foo.js</code>, but not
- * <code>com/example/tests/Foo.js</code> (not under a root folder named
- * <code>tests</code>).
- * </li>
- * <li>
- * <code>tests/&#42;</code> matches all files directly below a root
- * folder named <code>tests</code>. This includes <code>tests/Foo.js</code>
- * and <code>tests/FooHelp.js</code>
- * but not <code>tests/com/example/Foo.js</code> (not directly under
- * a folder named <code>tests</code>) or
- * <code>com/Foo.js</code> (not under a folder named <code>tests</code>).
- * </li>
- * <li>
- * <code>&#42;&#42;/tests/&#42;&#42;</code> matches all files under any
- * folder named <code>tests</code>. This includes <code>tests/Foo.js</code>,
- * <code>com/examples/tests/Foo.js</code>, and
- * <code>com/examples/tests/unit/Foo.js</code>, but not
- * <code>com/example/Foo.js</code> (not under a folder named
- * <code>tests</code>).
- * </li>
- * </ul>
- * </p>
- *
- * @return the possibly empty list of resource exclusion patterns
- * associated with this includepath entry, or <code>null</code> if this kind
- * of includepath entry does not support exclusion patterns
- */
- IPath[] getExclusionPatterns();
-
- /**
- * Returns the extra includepath attributes for this includepath entry. Returns an empty array if this entry
- * has no extra attributes.
- *
- * @return the possibly empty list of extra includepath attributes for this includepath entry
- */
- IIncludePathAttribute[] getExtraAttributes();
-
- /**
- * Returns the set of patterns used to explicitly define resources
- * to be included with this includepath entry.
- * <p>
- * For source includepath entries,
- * when no inclusion patterns are specified, the source entry includes all
- * relevent files in the resource tree rooted at this source entry's path.
- * Specifying one or more inclusion patterns means that only the specified
- * portions of the resource tree are to be included. Each path specified
- * must be a relative path, and will be interpreted relative to this source
- * entry's path. File patterns are case-sensitive. A file matched by one or
- * more of these patterns is included in the corresponding package fragment
- * root unless it is excluded by one or more of this entrie's exclusion
- * patterns. Exclusion patterns have higher precedence than inclusion
- * patterns; in other words, exclusion patterns can remove files for the
- * ones that are to be included, not the other way around.
- * </p>
- * <p>
- * See {@link #getExclusionPatterns()} for a discussion of the syntax and
- * semantics of path patterns. The absence of any inclusion patterns is
- * semantically equivalent to the explicit inclusion pattern
- * <code>&#42;&#42;</code>.
- * </p>
- * <p>
- * Example patterns in source entries:
- * <ul>
- * <li>
- * The inclusion pattern <code>src/&#42;&#42;</code> by itself includes all
- * files under a root folder named <code>src</code>.
- * </li>
- * <li>
- * The inclusion patterns <code>src/&#42;&#42;</code> and
- * <code>tests/&#42;&#42;</code> includes all files under the root folders
- * named <code>src</code> and <code>tests</code>.
- * </li>
- * <li>
- * The inclusion pattern <code>src/&#42;&#42;</code> together with the
- * exclusion pattern <code>src/&#42;&#42;/Foo.js</code> includes all
- * files under a root folder named <code>src</code> except for ones
- * named <code>Foo.js</code>.
- * </li>
- * </ul>
- * </p>
- *
- * @return the possibly empty list of resource inclusion patterns
- * associated with this includepath entry, or <code>null</code> if this kind
- * of includepath entry does not support inclusion patterns
- */
- IPath[] getInclusionPatterns();
-
- /**
- * Returns the path of this includepath entry.
- *
- * The meaning of the path of a includepath entry depends on its entry kind:<ul>
- * <li>Source code in the current project ({@link #CPE_SOURCE}) -
- * The path associated with this entry is the absolute path to the root folder. </li>
- * <li>A binary library in the current project ({@link #CPE_LIBRARY}) - the path
- * associated with this entry is the absolute path to the file.
- * <li>A required project ({@link #CPE_PROJECT}) - the path of the entry denotes the
- * path to the corresponding project resource.</li>
- * <li>A variable entry ({@link #CPE_VARIABLE}) - the first segment of the path
- * is the name of a includepath variable. If this includepath variable
- * is bound to the path <i>P</i>, the path of the corresponding includepath entry
- * is computed by appending to <i>P</i> the segments of the returned
- * path without the variable.</li>
- * <li> A container entry ({@link #CPE_CONTAINER}) - the path of the entry
- * is the name of the includepath container, which can be bound indirectly to a set of includepath
- * entries after resolution. The containerPath is a formed by a first ID segment followed with
- * extra segments that can be used as additional hints for resolving this container
- * reference (also see {@link IJsGlobalScopeContainer}).
- * </li>
- * </ul>
- *
- * @return the path of this includepath entry
- */
- IPath getPath();
-
- /**
- * Returns the path to the source archive or folder associated with this
- * includepath entry, or <code>null</code> if this includepath entry has no
- * source attachment.
- * <p>
- * Only library and variable includepath entries may have source attachments.
- * For library includepath entries, the result path (if present) locates a source
- * archive or folder. This archive or folder can be located in a project of the
- * workspace or outside thr workspace. For variable includepath entries, the
- * result path (if present) has an analogous form and meaning as the
- * variable path, namely the first segment is the name of a includepath variable.
- * </p>
- *
- * @return the path to the source archive or folder, or <code>null</code> if none
- */
- IPath getSourceAttachmentPath();
-
- /**
- * Returns the path within the source archive or folder where package fragments
- * are located. An empty path indicates that packages are located at
- * the root of the source archive or folder. Returns a non-<code>null</code> value
- * if and only if {@link #getSourceAttachmentPath} returns
- * a non-<code>null</code> value.
- *
- * @return the path within the source archive or folder, or <code>null</code> if
- * not applicable
- */
- IPath getSourceAttachmentRootPath();
-
- /**
- * Returns whether this entry is exported to dependent projects.
- * Always returns <code>false</code> for source entries (kind
- * {@link #CPE_SOURCE}), which cannot be exported.
- *
- * @return <code>true</code> if exported, and <code>false</code> otherwise
- */
- boolean isExported();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IInitializer.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IInitializer.java
deleted file mode 100644
index 2c27d98a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IInitializer.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core;
-
-/**
- * Represents a stand-alone instance or class (static) initializer in a type.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * 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 IInitializer extends IMember {
- // interface used as a marker: defines no member
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJarEntryResource.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJarEntryResource.java
deleted file mode 100644
index 512b386c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJarEntryResource.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core;
-
-import org.eclipse.core.resources.IStorage;
-import org.eclipse.core.runtime.IPath;
-
-/**
- * A jar entry corresponding to a non-Java resource in an archive {@link IPackageFragment} or {@link IPackageFragmentRoot}.
- * <p>
- * One can navigate the non-Java resource tree using the {@link #getChildren()} and {@link #getParent()} methods.
- * Jar entry resources are either files ({@link #isFile()} returns true) or directories ({@link #isFile()} returns false).
- * Files don't have any children and the returned array is always empty.
- * </p><p>
- * Jar entry resources that refer to the same element are guaranteed to be equal, but not necessarily identical.
- * <p>
- *
- * 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 IJarEntryResource extends IStorage {
-
- /**
- * Returns the list of children of this jar entry resource.
- * Returns an empty array if this jar entry is a file, or if this jar entry is a directory and it has no children.
- *
- * @return the children of this jar entry resource
- */
- IJarEntryResource[] getChildren();
-
- /**
- * Returns the full, absolute path of this jar entry resource relative to the archive this jar
- * entry belongs to.
- * <p>
- * A jar entry resource's full path indicates the route from the root of the archive
- * to the jar entry resource. Within an archive, there is exactly one such path
- * for any given jar entry resource. The returned path never has a trailing separator.
- * </p>
- *
- * @return the absolute path of this jar entry resource
- */
- IPath getFullPath();
-
- /**
- * Returns the parent of this jar entry resource. This is either an {@link IJarEntryResource}, an {@link IPackageFragment}
- * or an {@link IPackageFragmentRoot}.
- *
- * @return the parent of this jar entry resource
- */
- Object getParent();
-
- /**
- * Returns the package fragment root this jar entry file belongs to.
- *
- * @return the package fragment root this jar entry file belongs to.
- */
- IPackageFragmentRoot getPackageFragmentRoot();
-
- /**
- * Returns <code>true</code> if this jar entry represents a file.
- * Returns <code>false</code> if it is a directory.
- *
- * @return whether this jar entry is a file
- */
- boolean isFile();
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJavaScriptElement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJavaScriptElement.java
deleted file mode 100644
index d1a6e769..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJavaScriptElement.java
+++ /dev/null
@@ -1,382 +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.core;
-
-import java.net.URI;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.jobs.ISchedulingRule;
-
-/**
- * Common protocol for all elements provided by the JavaScript model.
- * JavaScript model elements are exposed to clients as handles to the actual underlying element.
- * The JavaScript model may hand out any number of handles for each element. Handles
- * that refer to the same element are guaranteed to be equal, but not necessarily identical.
- * <p>
- * Methods annotated as "handle-only" do not require underlying elements to exist.
- * Methods that require underlying elements to exist throw
- * a <code>JavaScriptModelException</code> when an underlying element is missing.
- * <code>JavaScriptModelException.isDoesNotExist</code> can be used to recognize
- * this common special case.
- * </p>
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * 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 IJavaScriptElement extends IAdaptable, ILookupScope{
-
- /**
- * Constant representing a JavaScript model (workspace level object).
- * A JavaScript element with this type can be safely cast to {@link IJavaScriptModel}.
- */
- int JAVASCRIPT_MODEL = 1;
-
- /**
- * Constant representing a JavaScript project.
- * A JavaScript element with this type can be safely cast to {@link IJavaScriptProject}.
- */
- int JAVASCRIPT_PROJECT = 2;
-
- /**
- * Constant representing a root source folder (package fragment root).
- * A JavaScript element with this type can be safely cast to {@link IPackageFragmentRoot}.
- */
- int PACKAGE_FRAGMENT_ROOT = 3;
-
- /**
- * Constant representing a source folder (package fragment).
- * A JavaScript element with this type can be safely cast to {@link IPackageFragment}.
- */
- int PACKAGE_FRAGMENT = 4;
-
- /**
- * Constant representing a JavaScript file.
- * A JavaScript element with this type can be safely cast to {@link IJavaScriptUnit}.
- */
- int JAVASCRIPT_UNIT = 5;
-
- /**
- * Constant representing a non-editable javaScript file.
- * A JavaScript element with this type can be safely cast to {@link IClassFile}.
- */
- int CLASS_FILE = 6;
-
- /**
- * Constant representing a type (a class or interface).
- * A JavaScript element with this type can be safely cast to {@link IType}.
- */
- int TYPE = 7;
-
- /**
- * Constant representing a field or a var with file scope.
- * A JavaScript element with this type can be safely cast to {@link IField}.
- */
- int FIELD = 8;
-
- /**
- * Constant representing a function, method or constructor.
- * A JavaScript element with this type can be safely cast to {@link IFunction}.
- */
- int METHOD = 9;
-
- /**
- * Constant representing a stand-alone instance or class initializer.
- * A JavaScript element with this type can be safely cast to {@link IInitializer}.
- */
- int INITIALIZER = 10;
-
- /**
- * Constant representing all import declarations within a compilation unit.
- * A JavaScript element with this type can be safely cast to {@link IImportContainer}.
- *
- * <b>This type only applies to ECMAScript 4 which is not yet supported</b>
- */
- int IMPORT_CONTAINER = 12;
-
- /**
- * Constant representing an import declaration within a compilation unit.
- * A JavaScript element with this type can be safely cast to {@link IImportDeclaration}.
- *
- * <b>This type only applies to ECMAScript 4 which is not yet supported</b>
- */
- int IMPORT_DECLARATION = 13;
-
- /**
- * Constant representing a local variable declaration.
- * A JavaScript element with this type can be safely cast to {@link ILocalVariable}.
- */
- int LOCAL_VARIABLE = 14;
-
- /**
- * Returns whether this JavaScript element exists in the model.
- * <p>
- * JavaScript elements are handle objects that may or may not be backed by an
- * actual element. JavaScript elements that are backed by an actual element are
- * said to "exist", and this method returns <code>true</code>. For JavaScript
- * elements that are not working copies, it is always the case that if the
- * element exists, then its parent also exists (provided it has one) and
- * includes the element as one of its children. It is therefore possible
- * to navigated to any existing JavaScript element from the root of the JavaScript model
- * along a chain of existing JavaScript elements. On the other hand, working
- * copies are said to exist until they are destroyed (with
- * <code>IWorkingCopy.destroy</code>). Unlike regular JavaScript elements, a
- * working copy never shows up among the children of its parent element
- * (which may or may not exist).
- * </p>
- *
- * @return <code>true</code> if this element exists in the JavaScript model, and
- * <code>false</code> if this element does not exist
- */
- boolean exists();
-
- /**
- * Returns the first ancestor of this JavaScript element that has the given type.
- * Returns <code>null</code> if no such an ancestor can be found.
- * This is a handle-only method.
- *
- * @param ancestorType the given type
- * @return the first ancestor of this JavaScript element that has the given type, null if no such an ancestor can be found
- */
- IJavaScriptElement getAncestor(int ancestorType);
-
- /**
- * <p>Returns the Jsdoc as an html source if this element has an attached jsdoc,
- * null otherwise.</p>
- * <p>This should be used only for binary elements. Source elements will always return null.</p>
- * <p>The encoding used to read the jsdoc is the one defined by the content type of the
- * file. If none is defined, then the project's encoding of this java element is used. If the project's
- * encoding cannot be retrieved, then the platform encoding is used.</p>
- * <p>In case of the jsdoc doesn't exist for this element, null is returned.</p>
- *
- * <p>The html is extracted from the attached jsdoc and provided as is. No
- * transformation or validation is done.</p>
- *
- * @param monitor the given progress monitor
- * @exception JavaScriptModelException if:<ul>
- * <li>this element does not exist</li>
- * <li>retrieving the attached jsdoc fails (timed-out, invalid URL, ...)</li>
- * <li>the format of the jsdoc doesn't match expected standards (different anchors,...)</li>
- * </ul>
- * @return the extracted jsdoc from the attached jsdoc, null if none
- * @see IIncludePathAttribute#JSDOC_LOCATION_ATTRIBUTE_NAME
- */
- String getAttachedJavadoc(IProgressMonitor monitor) throws JavaScriptModelException;
-
- /**
- * Returns the resource that corresponds directly to this element,
- * or <code>null</code> if there is no resource that corresponds to
- * this element.
- * <p>
- * For example, the corresponding resource for an <code>IJavaScriptUnit</code>
- * is its underlying <code>IFile</code>. The corresponding resource for
- * an <code>IPackageFragment</code> that is not contained in an archive
- * is its underlying <code>IFolder</code>. An <code>IPackageFragment</code>
- * contained in an archive has no corresponding resource. Similarly, there
- * are no corresponding resources for <code>IMethods</code>,
- * <code>IFields</code>, etc.
- * <p>
- *
- * @return the corresponding resource, or <code>null</code> if none
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
- IResource getCorrespondingResource() throws JavaScriptModelException;
-
- /**
- * Returns the name of this element. This is a handle-only method.
- *
- * @return the element name
- */
- String getElementName();
-
- /**
- * Returns this element's kind encoded as an integer.
- * This is a handle-only method.
- *
- * @return the kind of element; one of the constants declared in
- * <code>IJavaScriptElement</code>
- * @see IJavaScriptElement
- */
- int getElementType();
-
- /**
- * Returns a string representation of this element handle. The format of
- * the string is not specified; however, the identifier is stable across
- * workspace sessions, and can be used to recreate this handle via the
- * <code>JavaScriptCore.create(String)</code> method.
- *
- * @return the string handle identifier
- * @see JavaScriptCore#create(java.lang.String)
- */
- String getHandleIdentifier();
-
- /**
- * Returns the JavaScript model.
- * This is a handle-only method.
- *
- * @return the JavaScript model
- */
- IJavaScriptModel getJavaScriptModel();
-
- /**
- * Returns the JavaScript project this element is contained in,
- * or <code>null</code> if this element is not contained in any JavaScript project
- * (for instance, the <code>IJavaScriptModel</code> is not contained in any JavaScript
- * project).
- * This is a handle-only method.
- *
- * @return the containing JavaScript project, or <code>null</code> if this element is
- * not contained in a JavaScript project
- */
- IJavaScriptProject getJavaScriptProject();
-
- /**
- * Returns the first openable parent. If this element is openable, the element
- * itself is returned. Returns <code>null</code> if this element doesn't have
- * an openable parent.
- * This is a handle-only method.
- *
- * @return the first openable parent or <code>null</code> if this element doesn't have
- * an openable parent.
- */
- IOpenable getOpenable();
-
- /**
- * Returns the element directly containing this element,
- * or <code>null</code> if this element has no parent.
- * This is a handle-only method.
- *
- * @return the parent element, or <code>null</code> if this element has no parent
- */
- IJavaScriptElement getParent();
-
- /**
- * Returns the path to the innermost resource enclosing this element.
- * If this element is not included in an external archive,
- * the path returned is the full, absolute path to the underlying resource,
- * relative to the workbench.
- * If this element is included in an external archive,
- * the path returned is the absolute path to the archive in the file system.
- * This is a handle-only method.
- *
- * @return the path to the innermost resource enclosing this element
- */
- IPath getPath();
-
- /**
- * Returns the primary element (whose compilation unit is the primary compilation unit)
- * this working copy element was created from, or this element if it is a descendant of a
- * primary javaScript unit or if it is not a descendant of a working copy (e.g. it is a
- * binary member).
- * The returned element may or may not exist.
- *
- * @return the primary element this working copy element was created from, or this
- * element.
- */
- IJavaScriptElement getPrimaryElement();
-
- /**
- * Returns the innermost resource enclosing this element.
- * If this element is included in an archive and this archive is not external,
- * this is the underlying resource corresponding to the archive.
- * If this element is included in an external archive, <code>null</code>
- * is returned.
- * This is a handle-only method.
- *
- * @return the innermost resource enclosing this element, <code>null</code> if this
- * element is included in an external archive
- */
- IResource getResource();
-
- /**
- * Returns the scheduling rule associated with this JavaScript element.
- * This is a handle-only method.
- *
- * @return the scheduling rule associated with this JavaScript element
- */
- ISchedulingRule getSchedulingRule();
-
- /**
- * Returns the smallest underlying resource that contains
- * this element, or <code>null</code> if this element is not contained
- * in a resource.
- *
- * @return the underlying resource, or <code>null</code> if none
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its underlying resource
- */
- IResource getUnderlyingResource() throws JavaScriptModelException;
-
- /**
- * Returns whether this JavaScript element is read-only. An element is read-only
- * if its structure cannot be modified by the java model.
- * <p>
- * Note this is different from IResource.isReadOnly(). For example, .jar
- * files are read-only as the javaScript model doesn't know how to add/remove
- * elements in this file, but the underlying IFile can be writable.
- * <p>
- * This is a handle-only method.
- *
- * @return <code>true</code> if this element is read-only
- */
- boolean isReadOnly();
-
- /**
- * Returns whether the structure of this element is known. For example, for a
- * javaScript file that could not be parsed, <code>false</code> is returned.
- * If the structure of an element is unknown, navigations will return reasonable
- * defaults. For example, <code>getChildren</code> will return an empty collection.
- * <p>
- * Note: This does not imply anything about consistency with the
- * underlying resource/buffer contents.
- * </p>
- *
- * @return <code>true</code> if the structure of this element is known
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
- boolean isStructureKnown() throws JavaScriptModelException;
- /**
- * Returns a readable (non mangled) name. In virtual elements this is derived from a JsGlobalScopeContainerInitializer
- *
- * @return a human friendly element name.
- */
- String getDisplayName();
- /**
- * Returns if this is a virtual element (ie actually exists in the model or filesystem).
- *
- * @return if this is a virtual element.
- */
- boolean isVirtual();
-
- /**
- * If a resource is virtual, then return a real host path for the element. (Query the container initializer).
- *
- * @return if this is a virtual element.
- */
- URI getHostPath();
-
- /**
- * Returns the Super type this file is considered to be a member of. For Browser base javaScript, this would be "Window".
- *
- * @return the supertype for the javascript file.
- */
- LibrarySuperType getCommonSuperType();
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJavaScriptElementDelta.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJavaScriptElementDelta.java
deleted file mode 100644
index 28193cb4..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJavaScriptElementDelta.java
+++ /dev/null
@@ -1,375 +0,0 @@
-/*******************************************************************************
- * 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;
-
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-
-/**
- * A JavaScript element delta describes changes in JavaScript element between two discrete
- * points in time. Given a delta, clients can access the element that has
- * changed, and any children that have changed.
- * <p>
- * Deltas have a different status depending on the kind of change they represent.
- * The list below summarizes each status (as returned by {@link #getKind})
- * and its meaning (see individual constants for a more detailled description):
- * <ul>
- * <li>{@link #ADDED} - The element described by the delta has been added.</li>
- * <li>{@link #REMOVED} - The element described by the delta has been removed.</li>
- * <li>{@link #CHANGED} - The element described by the delta has been changed in some way.
- * Specification of the type of change is provided by {@link #getFlags} which returns the following values:
- * <ul>
- * <li>{@link #F_ADDED_TO_CLASSPATH} - A includepath entry corresponding to the element
- * has been added to the project's includepath. This flag is only valid if the element is an
- * {@link IPackageFragmentRoot}.</li>
- * <li>{@link #F_ARCHIVE_CONTENT_CHANGED} - The contents of an archive
- * has changed in some way. This flag is only valid if the element is an {@link IPackageFragmentRoot}
- * which is an archive.</li>
- * <li>{@link #F_CHILDREN} - A child of the element has changed in some way. This flag
- * is only valid if the element is an {@link IParent}.</li>
- * <li>{@link #F_INCLUDEPATH_REORDER} - A Includepath entry corresponding to the element
- * has changed position in the project's Includepath. This flag is only valid if the element is an
- * {@link IPackageFragmentRoot}.</li>
- * <li>{@link #F_CLOSED} - The underlying {@link org.eclipse.core.resources.IProject}
- * has been closed. This flag is only valid if the element is an {@link IJavaScriptProject}.</li>
- * <li>{@link #F_CONTENT} - The contents of the element have been altered. This flag
- * is only valid for elements which correspond to files.</li>
- *<li>{@link #F_FINE_GRAINED} - The delta is a fine-grained delta, that is, an analysis down
- * to the members level was done to determine if there were structural changes to members of the element.</li>
- * <li>{@link #F_MODIFIERS} - The modifiers on the element have changed in some way.
- * This flag is only valid if the element is an {@link IMember}.</li>
- * <li>{@link #F_OPENED} - The underlying {@link org.eclipse.core.resources.IProject}
- * has been opened. This flag is only valid if the element is an {@link IJavaScriptProject}.</li>
- * <li>{@link #F_REMOVED_FROM_CLASSPATH} - A includepath entry corresponding to the element
- * has been removed from the project's includepath. This flag is only valid if the element is an
- * {@link IPackageFragmentRoot}.</li>
- * <li>{@link #F_SOURCEATTACHED} - The source attachment path or the source attachment root path
- * of a includepath entry corresponding to the element was added. This flag is only valid if the element is an
- * {@link IPackageFragmentRoot}.</li>
- * <li>{@link #F_SOURCEDETACHED} - The source attachment path or the source attachment root path
- * of a includepath entry corresponding to the element was removed. This flag is only valid if the element is an
- * {@link IPackageFragmentRoot}.</li>
- * <li>{@link #F_SUPER_TYPES} - One of the supertypes of an {@link IType} has changed</li>.
- * </ul>
- * </li>
- * </ul>
- * </p>
- * <p>
- * Move operations are indicated by other change flags, layered on top
- * of the change flags described above. If element A is moved to become B,
- * the delta for the change in A will have status {@link #REMOVED},
- * with change flag {@link #F_MOVED_TO}. In this case,
- * {@link #getMovedToElement} on delta A will return the handle for B.
- * The delta for B will have status {@link #ADDED}, with change flag
- * {@link #F_MOVED_FROM}, and {@link #getMovedFromElement} on delta
- * B will return the handle for A. (Note, the handle to A in this case represents
- * an element that no longer exists).
- * </p>
- * <p>
- * Note that the move change flags only describe the changes to a single element, they
- * do not imply anything about the parent or children of the element.
- * </p>
- * <p>
- * The {@link #F_ADDED_TO_CLASSPATH}, {@link #F_REMOVED_FROM_CLASSPATH} and
- * {@link #F_INCLUDEPATH_REORDER} flags are triggered by changes to a project's includepath. They do not mean that
- * the underlying resource was added, removed or changed. For example, if a project P already contains a folder src, then
- * adding a includepath entry with the 'P/src' path to the project's includepath will result in an {@link IJavaScriptElementDelta}
- * with the {@link #F_ADDED_TO_CLASSPATH} flag for the {@link IPackageFragmentRoot} P/src.
- * On the contrary, if a resource is physically added, removed or changed and this resource corresponds to a includepath
- * entry of the project, then an {@link IJavaScriptElementDelta} with the {@link #ADDED},
- * {@link #REMOVED}, or {@link #CHANGED} kind will be fired.
- * </p>
- * <p>
- * Note that when a source attachment path or a source attachment root path is changed, then the flags of the delta contain
- * both {@link #F_SOURCEATTACHED} and {@link #F_SOURCEDETACHED}.
- * </p>
- * <p>
- * No assumptions should be made on whether the javaScript element delta tree is rooted at the {@link IJavaScriptModel}
- * level or not.
- * </p>
- * <p>
- * {@link IJavaScriptElementDelta} object are not valid outside the dynamic scope
- * of the notification.
- * </p>
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * 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 IJavaScriptElementDelta {
-
- /**
- * Status constant indicating that the element has been added.
- * Note that an added javaScript element delta has no children, as they are all implicitely added.
- */
- public int ADDED = 1;
-
- /**
- * Status constant indicating that the element has been removed.
- * Note that a removed javaScript element delta has no children, as they are all implicitely removed.
- */
- public int REMOVED = 2;
-
- /**
- * Status constant indicating that the element has been changed,
- * as described by the change flags.
- *
- * @see #getFlags()
- */
- public int CHANGED = 4;
-
- /**
- * Change flag indicating that the content of the element has changed.
- * This flag is only valid for elements which correspond to files.
- */
- public int F_CONTENT = 0x000001;
-
- /**
- * Change flag indicating that the modifiers of the element have changed.
- * This flag is only valid if the element is an {@link IMember}.
- */
- public int F_MODIFIERS = 0x000002;
-
- /**
- * Change flag indicating that there are changes to the children of the element.
- * This flag is only valid if the element is an {@link IParent}.
- */
- public int F_CHILDREN = 0x000008;
-
- /**
- * Change flag indicating that the element was moved from another location.
- * The location of the old element can be retrieved using {@link #getMovedFromElement}.
- */
- public int F_MOVED_FROM = 0x000010;
-
- /**
- * Change flag indicating that the element was moved to another location.
- * The location of the new element can be retrieved using {@link #getMovedToElement}.
- */
- public int F_MOVED_TO = 0x000020;
-
- /**
- * Change flag indicating that a includepath entry corresponding to the element has been added to the project's includepath.
- * This flag is only valid if the element is an {@link IPackageFragmentRoot}.
- */
- public int F_ADDED_TO_CLASSPATH = 0x000040;
-
- /**
- * Change flag indicating that a includepath entry corresponding to the element has been removed from the project's
- * includepath. This flag is only valid if the element is an {@link IPackageFragmentRoot}.
- */
- public int F_REMOVED_FROM_CLASSPATH = 0x000080;
-
- /**
- * Change flag indicating that the element has changed position relatively to its siblings.
- * If the element is an {@link IPackageFragmentRoot}, a includepath entry corresponding
- * to the element has changed position in the project's includepath.
- *
- */
- public int F_REORDER = 0x000100;
-
- /**
- * Change flag indicating that the underlying {@link org.eclipse.core.resources.IProject} has been
- * opened. This flag is only valid if the element is an {@link IJavaScriptProject}.
- */
- public int F_OPENED = 0x000200;
-
- /**
- * Change flag indicating that the underlying {@link org.eclipse.core.resources.IProject} has been
- * closed. This flag is only valid if the element is an {@link IJavaScriptProject}.
- */
- public int F_CLOSED = 0x000400;
-
- /**
- * Change flag indicating that one of the supertypes of an {@link IType}
- * has changed.
- */
- public int F_SUPER_TYPES = 0x000800;
-
- /**
- * Change flag indicating that the source attachment path or the source attachment root path of a includepath entry
- * corresponding to the element was added. This flag is only valid if the element is an
- * {@link IPackageFragmentRoot}.
- */
- public int F_SOURCEATTACHED = 0x001000;
-
- /**
- * Change flag indicating that the source attachment path or the source attachment root path of a includepath entry
- * corresponding to the element was removed. This flag is only valid if the element is an
- * {@link IPackageFragmentRoot}.
- */
- public int F_SOURCEDETACHED = 0x002000;
-
- /**
- * Change flag indicating that this is a fine-grained delta, that is, an analysis down
- * to the members level was done to determine if there were structural changes to
- * members.
- * <p>
- * Clients can use this flag to find out if a javaScript unit
- * that have a {@link #F_CONTENT} change should assume that there are
- * no finer grained changes ({@link #F_FINE_GRAINED} is set) or if
- * finer grained changes were not considered ({@link #F_FINE_GRAINED}
- * is not set).
- *
- */
- public int F_FINE_GRAINED = 0x004000;
-
- /**
- * Change flag indicating that the element's archive content on the includepath has changed.
- * This flag is only valid if the element is an {@link IPackageFragmentRoot}
- * which is an archive.
- *
- * @see IPackageFragmentRoot#isArchive()
- */
- public int F_ARCHIVE_CONTENT_CHANGED = 0x008000;
-
- /**
- * Change flag indicating that a javaScript unit has become a primary working copy, or that a
- * primary working copy has reverted to a javaScript unit.
- * This flag is only valid if the element is an {@link IJavaScriptUnit}.
- *
- */
- public int F_PRIMARY_WORKING_COPY = 0x010000;
-
- /**
- * Change flag indicating that the raw includepath (or the output folder) of a project has changed.
- * This flag is only valid if the element is an {@link IJavaScriptProject}.
- *
- */
- public int F_INCLUDEPATH_CHANGED = 0x020000;
-
- /**
- * Change flag indicating that the resource of a primary javaScript unit has changed.
- * This flag is only valid if the element is a primary {@link IJavaScriptUnit}.
- *
- */
- public int F_PRIMARY_RESOURCE = 0x040000;
-
- /**
- * Change flag indicating that a reconcile operation has affected the javaScript unit AST created in a
- * previous reconcile operation. Use {@link #getJavaScriptUnitAST()} to retrieve the AST (if any is available).
- * This flag is only valid if the element is an {@link IJavaScriptUnit} in working copy mode.
- *
- */
- public int F_AST_AFFECTED = 0x080000;
-
- /**
- * Change flag indicating that the categories of the element have changed.
- * This flag is only valid if the element is an {@link IMember}.
- *
- */
- public int F_CATEGORIES = 0x100000;
-
- /**
- * Returns deltas for the children that have been added.
- * @return deltas for the children that have been added
- */
- public IJavaScriptElementDelta[] getAddedChildren();
-
- /**
- * Returns deltas for the affected (added, removed, or changed) children.
- * @return deltas for the affected (added, removed, or changed) children
- */
- public IJavaScriptElementDelta[] getAffectedChildren();
-
- /**
- * Returns the javaScript unit AST created by the last reconcile operation on this delta's element.
- * This returns a non-null value if and only if:
- * <ul>
- * <li>the last reconcile operation on this working copy requested an AST</li>
- * <li>this delta's element is an {@link IJavaScriptUnit} in working copy mode</li>
- * <li>the delta comes from a {@link ElementChangedEvent#POST_RECONCILE} event
- * </ul>
- *
- * @return the AST created during the last reconcile operation
- * @see IJavaScriptUnit#reconcile(int, boolean, WorkingCopyOwner, org.eclipse.core.runtime.IProgressMonitor)
- * @see #F_AST_AFFECTED
- */
- public JavaScriptUnit getJavaScriptUnitAST();
-
- /**
- * Returns deltas for the children which have changed.
- * @return deltas for the children which have changed
- */
- public IJavaScriptElementDelta[] getChangedChildren();
-
- /**
- * Returns the element that this delta describes a change to.
- * @return the element that this delta describes a change to
- */
- public IJavaScriptElement getElement();
-
- /**
- * Returns flags that describe how an element has changed.
- * Such flags should be tested using the <code>&</code> operand. For example:
- * <pre>
- * if ((delta.getFlags() & IJavaScriptElementDelta.F_CONTENT) != 0) {
- * // the delta indicates a content change
- * }
- * </pre>
- *
- * @return flags that describe how an element has changed
- */
- public int getFlags();
-
- /**
- * Returns the kind of this delta - one of {@link #ADDED}, {@link #REMOVED},
- * or {@link #CHANGED}.
- *
- * @return the kind of this delta
- */
- public int getKind();
-
- /**
- * Returns an element describing this element before it was moved
- * to its current location, or <code>null</code> if the
- * {@link #F_MOVED_FROM} change flag is not set.
- *
- * @return an element describing this element before it was moved
- * to its current location, or <code>null</code> if the
- * {@link #F_MOVED_FROM} change flag is not set
- */
- public IJavaScriptElement getMovedFromElement();
-
- /**
- * Returns an element describing this element in its new location,
- * or <code>null</code> if the {@link #F_MOVED_TO} change
- * flag is not set.
- *
- * @return an element describing this element in its new location,
- * or <code>null</code> if the {@link #F_MOVED_TO} change
- * flag is not set
- */
- public IJavaScriptElement getMovedToElement();
-
- /**
- * Returns deltas for the children which have been removed.
- *
- * @return deltas for the children which have been removed
- */
- public IJavaScriptElementDelta[] getRemovedChildren();
-
- /**
- * Returns the collection of resource deltas.
- * <p>
- * Note that resource deltas, like JavaScript element deltas, are generally only valid
- * for the dynamic scope of an event notification. Clients must not hang on to
- * these objects.
- * </p>
- *
- * @return the underlying resource deltas, or <code>null</code> if none
- */
- public IResourceDelta[] getResourceDeltas();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJavaScriptModel.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJavaScriptModel.java
deleted file mode 100644
index 0b75e737..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJavaScriptModel.java
+++ /dev/null
@@ -1,260 +0,0 @@
-/*******************************************************************************
- * 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;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.runtime.IProgressMonitor;
-
-/**
- * Represent the root JavaScript element corresponding to the workspace.
- * Since there is only one such root element, it is commonly referred to as
- * <em>the</em> JavaScript model element.
- * The JavaScript model element needs to be opened before it can be navigated or manipulated.
- * The JavaScript model element has no parent (it is the root of the JavaScript element
- * hierarchy). Its children are <code>IJavaScriptProject</code>s.
- * <p>
- * This interface provides methods for performing copy, move, rename, and
- * delete operations on multiple JavaScript elements.
- * </p>
- * <p>
- * This interface is not intended to be implemented by clients. An instance
- * of one of these handles can be created via
- * <code>JavaScriptCore.create(workspace.getRoot())</code>.
- * </p>
- *
- * @see JavaScriptCore#create(org.eclipse.core.resources.IWorkspaceRoot)
- *
- * 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 IJavaScriptModel extends IJavaScriptElement, IOpenable, IParent {
-/**
- * Returns whether this JavaScript model contains an <code>IJavaScriptElement</code> whose
- * resource is the given resource or a non-JavaScript resource which is the given resource.
- * <p>
- * Note: no existency check is performed on the argument resource. If it is not accessible
- * (see <code>IResource.isAccessible()</code>) yet but would be located in JavaScript model
- * range, then it will return <code>true</code>.
- * </p><p>
- * If the resource is accessible, it can be reached by navigating the JavaScript model down using the
- * <code>getChildren()</code> and/or <code>getNonJavaResources()</code> methods.
- * </p>
- * @param resource the resource to check
- * @return true if the resource is accessible through the JavaScript model
- */
-boolean contains(IResource resource);
-/**
- * Copies the given elements to the specified container(s).
- * If one container is specified, all elements are copied to that
- * container. If more than one container is specified, the number of
- * elements and containers must match, and each element is copied to
- * its associated container.
- * <p>
- * Optionally, each copy can positioned before a sibling
- * element. If <code>null</code> is specified for a given sibling, the copy
- * is inserted as the last child of its associated container.
- * </p>
- * <p>
- * Optionally, each copy can be renamed. If
- * <code>null</code> is specified for the new name, the copy
- * is not renamed.
- * </p>
- * <p>
- * Optionally, any existing child in the destination container with
- * the same name can be replaced by specifying <code>true</code> for
- * force. Otherwise an exception is thrown in the event that a name
- * collision occurs.
- * </p>
- *
- * @param elements the elements to copy
- * @param containers the container, or list of containers
- * @param siblings the list of siblings element any of which may be
- * <code>null</code>; or <code>null</code>
- * @param renamings the list of new names any of which may be
- * <code>null</code>; or <code>null</code>
- * @param replace <code>true</code> if any existing child in a target container
- * with the target name should be replaced, and <code>false</code> to throw an
- * exception in the event of a name collision
- * @param monitor a progress monitor
- * @exception JavaScriptModelException if an element could not be copied. Reasons include:
- * <ul>
- * <li> There is no element to process (NO_ELEMENTS_TO_PROCESS). The given elements is null or empty</li>
- * <li> A specified element, container, or sibling does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while updating an underlying resource</li>
- * <li> A container is of an incompatible type (<code>INVALID_DESTINATION</code>)</li>
- * <li> A sibling is not a child of it associated container (<code>INVALID_SIBLING</code>)</li>
- * <li> A new name is invalid (<code>INVALID_NAME</code>)</li>
- * <li> A child in its associated container already exists with the same
- * name and <code>replace</code> has been specified as <code>false</code> (<code>NAME_COLLISION</code>)</li>
- * <li> A container or element is read-only (<code>READ_ONLY</code>) </li>
- * </ul>
- */
-void copy(IJavaScriptElement[] elements, IJavaScriptElement[] containers, IJavaScriptElement[] siblings, String[] renamings, boolean replace, IProgressMonitor monitor) throws JavaScriptModelException;
-/**
- * Deletes the given elements, forcing the operation if necessary and specified.
- *
- * @param elements the elements to delete
- * @param force a flag controlling whether underlying resources that are not
- * in sync with the local file system will be tolerated
- * @param monitor a progress monitor
- * @exception JavaScriptModelException if an element could not be deleted. Reasons include:
- * <ul>
- * <li> There is no element to process (NO_ELEMENTS_TO_PROCESS). The given elements is null or empty</li>
- * <li> A specified element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while updating an underlying resource</li>
- * <li> An element is read-only (<code>READ_ONLY</code>) </li>
- * </ul>
- */
-void delete(IJavaScriptElement[] elements, boolean force, IProgressMonitor monitor) throws JavaScriptModelException;
-/**
- * Returns the JavaScript project with the given name. This is a handle-only method.
- * The project may or may not exist.
- *
- * @param name the name of the JavaScript project
- * @return the JavaScript project with the given name
- */
-IJavaScriptProject getJavaScriptProject(String name);
-/**
- * Returns the JavaScript projects in this JavaScript model, or an empty array if there
- * are none.
- *
- * @return the JavaScript projects in this JavaScript model, or an empty array if there
- * are none
- * @exception JavaScriptModelException if this request fails.
- */
-IJavaScriptProject[] getJavaScriptProjects() throws JavaScriptModelException;
-/**
- * Returns an array of non-JavaScript resources (that is, non-JavaScript projects) in
- * the workspace.
- * <p>
- * Non-JavaScript projects include all projects that are closed (even if they have the
- * JavaScript nature).
- * </p>
- *
- * @return an array of non-JavaScript projects (<code>IProject</code>s) contained
- * in the workspace.
- * @throws JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
-Object[] getNonJavaScriptResources() throws JavaScriptModelException;
-/**
- * Returns the workspace associated with this JavaScript model.
- *
- * @return the workspace associated with this JavaScript model
- */
-IWorkspace getWorkspace();
-/**
- * Moves the given elements to the specified container(s).
- * If one container is specified, all elements are moved to that
- * container. If more than one container is specified, the number of
- * elements and containers must match, and each element is moved to
- * its associated container.
- * <p>
- * Optionally, each element can positioned before a sibling
- * element. If <code>null</code> is specified for sibling, the element
- * is inserted as the last child of its associated container.
- * </p>
- * <p>
- * Optionally, each element can be renamed. If
- * <code>null</code> is specified for the new name, the element
- * is not renamed.
- * </p>
- * <p>
- * Optionally, any existing child in the destination container with
- * the same name can be replaced by specifying <code>true</code> for
- * force. Otherwise an exception is thrown in the event that a name
- * collision occurs.
- * </p>
- *
- * @param elements the elements to move
- * @param containers the container, or list of containers
- * @param siblings the list of siblings element any of which may be
- * <code>null</code>; or <code>null</code>
- * @param renamings the list of new names any of which may be
- * <code>null</code>; or <code>null</code>
- * @param replace <code>true</code> if any existing child in a target container
- * with the target name should be replaced, and <code>false</code> to throw an
- * exception in the event of a name collision
- * @param monitor a progress monitor
- * @exception JavaScriptModelException if an element could not be moved. Reasons include:
- * <ul>
- * <li> There is no element to process (NO_ELEMENTS_TO_PROCESS). The given elements is null or empty</li>
- * <li> A specified element, container, or sibling does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while updating an underlying resource</li>
- * <li> A container is of an incompatible type (<code>INVALID_DESTINATION</code>)</li>
- * <li> A sibling is not a child of it associated container (<code>INVALID_SIBLING</code>)</li>
- * <li> A new name is invalid (<code>INVALID_NAME</code>)</li>
- * <li> A child in its associated container already exists with the same
- * name and <code>replace</code> has been specified as <code>false</code> (<code>NAME_COLLISION</code>)</li>
- * <li> A container or element is read-only (<code>READ_ONLY</code>) </li>
- * </ul>
- *
- * @exception IllegalArgumentException any element or container is <code>null</code>
- */
-void move(IJavaScriptElement[] elements, IJavaScriptElement[] containers, IJavaScriptElement[] siblings, String[] renamings, boolean replace, IProgressMonitor monitor) throws JavaScriptModelException;
-
-/**
- * Triggers an update of the JavaScriptModel with respect to the referenced external archives.
- * This operation will issue a JavaScriptModel delta describing the discovered changes, in term
- * of JavaScript element package fragment roots added, removed or changed.
- * Note that a collection of elements can be passed so as to narrow the set of archives
- * to refresh (passing <code>null</code> along is equivalent to refreshing the entire mode).
- * The elements can be:
- * <ul>
- * <li> package fragment roots corresponding to external archives
- * <li> JavaScript projects, which referenced external archives will be refreshed
- * <li> JavaScript model, all referenced external archives will be refreshed.
- * </ul>
- * <p> In case an archive is used by multiple projects, the delta issued will account for
- * all of them. This means that even if a project was not part of the elements scope, it
- * may still be notified of changes if it is referencing a library comprised in the scope.
- * <p>
- * @param elementsScope - a collection of elements defining the scope of the refresh
- * @param monitor - a progress monitor used to report progress
- * @exception JavaScriptModelException in one of the corresponding situation:
- * <ul>
- * <li> an exception occurs while accessing project resources </li>
- * </ul>
- *
- * @see IJavaScriptElementDelta
- */
-void refreshExternalArchives(IJavaScriptElement[] elementsScope, IProgressMonitor monitor) throws JavaScriptModelException;
-
-/**
- * Renames the given elements as specified.
- * If one container is specified, all elements are renamed within that
- * container. If more than one container is specified, the number of
- * elements and containers must match, and each element is renamed within
- * its associated container.
- *
- * @param elements the elements to rename
- * @param destinations the container, or list of containers
- * @param names the list of new names
- * @param replace <code>true</code> if an existing child in a target container
- * with the target name should be replaced, and <code>false</code> to throw an
- * exception in the event of a name collision
- * @param monitor a progress monitor
- * @exception JavaScriptModelException if an element could not be renamed. Reasons include:
- * <ul>
- * <li> There is no element to process (NO_ELEMENTS_TO_PROCESS). The given elements is null or empty</li>
- * <li> A specified element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while updating an underlying resource
- * <li> A new name is invalid (<code>INVALID_NAME</code>)
- * <li> A child already exists with the same name and <code>replace</code> has been specified as <code>false</code> (<code>NAME_COLLISION</code>)
- * <li> An element is read-only (<code>READ_ONLY</code>)
- * </ul>
- */
-void rename(IJavaScriptElement[] elements, IJavaScriptElement[] destinations, String[] names, boolean replace, IProgressMonitor monitor) throws JavaScriptModelException;
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJavaScriptModelMarker.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJavaScriptModelMarker.java
deleted file mode 100644
index 7089373c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJavaScriptModelMarker.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*******************************************************************************
- * 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;
-
-/**
- * Markers used by the JavaScript model.
- * <p>
- * This interface declares constants only; it is not intended to be implemented
- * or extended.
- * </p>
- *
- * 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 IJavaScriptModelMarker {
-
- /**
- * JavaScript model problem marker type (value
- * <code>"org.eclipse.wst.jsdt.core.problem"</code>). This can be used to
- * recognize those markers in the workspace that flag problems detected by
- * the JavaScript tooling during validation.
- */
- String JAVASCRIPT_MODEL_PROBLEM_MARKER = JavaScriptCore.PLUGIN_ID + ".problem"; //$NON-NLS-1$
-
- /**
- * JavaScript model transient problem marker type (value
- * <code>"org.eclipse.wst.jsdt.core.transient_problem"</code>). This can be
- * used to recognize those markers in the workspace that flag transient
- * problems detected by the JavaScript tooling (such as a problem detected by the
- * outliner, or a problem detected during a code completion). Since 1.0,
- * transient problems are reported as <code>IProblem</code> through
- * various API. Only the evaluation API is still producing markers for
- * transient problems.
- *
- * @see org.eclipse.wst.jsdt.core.compiler.IProblem
- * @see org.eclipse.wst.jsdt.core.eval.ICodeSnippetRequestor#acceptProblem(org.eclipse.core.resources.IMarker,String,
- * int)
- */
- String TRANSIENT_PROBLEM = JavaScriptCore.PLUGIN_ID + ".transient_problem"; //$NON-NLS-1$
-
- /**
- * JavaScript model task marker type (value
- * <code>"org.eclipse.wst.jsdt.core.task"</code>). This can be used to
- * recognize task markers in the workspace that correspond to tasks
- * specified in JavaScript source comments and detected during compilation (for
- * example, 'TO-DO: ...'). Tasks are identified by a task tag, which can be
- * customized through <code>JavaScriptCore</code> option
- * <code>"org.eclipse.wst.jsdt.core.compiler.taskTag"</code>.
- *
- */
- String TASK_MARKER = JavaScriptCore.PLUGIN_ID + ".task"; //$NON-NLS-1$
-
- /**
- * Id marker attribute (value <code>"arguments"</code>). Arguments are
- * concatenated into one String, prefixed with an argument count (followed
- * with colon separator) and separated with '#' characters. For example: {
- * "foo", "bar" } is encoded as "2:foo#bar", { } is encoded as "0: "
- *
- */
- String ARGUMENTS = "arguments"; //$NON-NLS-1$
-
- /**
- * ID marker attribute (value <code>"id"</code>).
- */
- String ID = "id"; //$NON-NLS-1$
-
- /**
- * ID category marker attribute (value <code>"categoryId"</code>)
- */
- String CATEGORY_ID = "categoryId"; //$NON-NLS-1$
-
- /**
- * Flags marker attribute (value <code>"flags"</code>). Reserved for
- * future use.
- */
- String FLAGS = "flags"; //$NON-NLS-1$
-
- /**
- * Cycle detected marker attribute (value <code>"cycleDetected"</code>).
- * Used only on buildpath problem markers. The value of this attribute is
- * either "true" or "false".
- */
- String CYCLE_DETECTED = "cycleDetected"; //$NON-NLS-1$
-
- /**
- * Include path problem marker type (value
- * <code>"org.eclipse.wst.jsdt.core.buildpath_problem"</code>). This can be
- * used to recognize those markers in the workspace that flag problems
- * detected by the JavaScript tooling during includepath setting.
- */
- String BUILDPATH_PROBLEM_MARKER = JavaScriptCore.PLUGIN_ID
- + ".buildpath_problem"; //$NON-NLS-1$
-
- /**
- * IncludePath file format marker attribute (value
- * <code>"classpathFileFormat"</code>). Used only on includepath problem
- * markers. The value of this attribute is either "true" or "false".
- *
- */
- String INCLUDEPATH_FILE_FORMAT = "classpathFileFormat"; //$NON-NLS-1$
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJavaScriptModelStatus.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJavaScriptModelStatus.java
deleted file mode 100644
index 49d7e7ca..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJavaScriptModelStatus.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*******************************************************************************
- * 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;
-
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-
-/**
- * Represents the outcome of an JavaScript model operation. Status objects are
- * used inside <code>JavaScriptModelException</code> objects to indicate what went
- * wrong.
- * <p>
- * JavaScript model status object are distinguished by their plug-in id:
- * <code>getPlugin</code> returns <code>"org.eclipse.wst.jsdt.core"</code>.
- * <code>getCode</code> returns one of the status codes declared in
- * <code>IJavaScriptModelStatusConstants</code>.
- * </p>
- * <p>
- * A JavaScript model status may also carry additional information (that is, in
- * addition to the information defined in <code>IStatus</code>):
- * <ul>
- * <li>elements - optional handles to JavaScript elements associated with the failure</li>
- * <li>string - optional string associated with the failure</li>
- * </ul>
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * @see org.eclipse.core.runtime.IStatus
- * @see IJavaScriptModelStatusConstants
- *
- * 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 IJavaScriptModelStatus extends IStatus {
-/**
- * Returns any JavaScript elements associated with the failure (see specification
- * of the status code), or an empty array if no elements are related to this
- * particular status code.
- *
- * @return the list of JavaScript element culprits
- * @see IJavaScriptModelStatusConstants
- */
-IJavaScriptElement[] getElements();
-/**
- * Returns the path associated with the failure (see specification
- * of the status code), or <code>null</code> if the failure is not
- * one of <code>DEVICE_PATH</code>, <code>INVALID_PATH</code>,
- * <code>PATH_OUTSIDE_PROJECT</code>, or <code>RELATIVE_PATH</code>.
- *
- * @return the path that caused the failure, or <code>null</code> if none
- * @see IJavaScriptModelStatusConstants#DEVICE_PATH
- * @see IJavaScriptModelStatusConstants#INVALID_PATH
- * @see IJavaScriptModelStatusConstants#PATH_OUTSIDE_PROJECT
- * @see IJavaScriptModelStatusConstants#RELATIVE_PATH
- */
-IPath getPath();
-/**
- * Returns whether this status indicates that a JavaScript model element does not exist.
- * This convenience method is equivalent to
- * <code>getCode() == IJavaScriptModelStatusConstants.ELEMENT_DOES_NOT_EXIST</code>.
- *
- * @return <code>true</code> if the status code indicates that a JavaScript model
- * element does not exist
- * @see IJavaScriptModelStatusConstants#ELEMENT_DOES_NOT_EXIST
- */
-boolean isDoesNotExist();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJavaScriptModelStatusConstants.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJavaScriptModelStatusConstants.java
deleted file mode 100644
index 39e76ac8..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJavaScriptModelStatusConstants.java
+++ /dev/null
@@ -1,319 +0,0 @@
-/*******************************************************************************
- * 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
- *
- * TODO missing 2.1 and subsequent contributions
- * VALIDATION_FAILURE
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core;
-
-/**
- * Status codes used with JavaScript model status objects.
- * <p>
- * This interface declares constants only; it is not intended to be implemented
- * or extended.
- * </p>
- *
- * @see IJavaScriptModelStatus
- * @see org.eclipse.core.runtime.IStatus#getCode()
- *
- * 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 IJavaScriptModelStatusConstants {
-
- /**
- * Status constant indicating that a container path was resolved
- * to invalid entries (null or container).
- */
- public static final int INVALID_CP_CONTAINER_ENTRY = 962;
-
- /**
- * Status constant indicating that a container path was not resolvable
- * indicating either the referred container is undefined, unbound.
- */
- public static final int CP_CONTAINER_PATH_UNBOUND = 963;
-
- /**
- * Status constant indicating that a includepath entry was invalid
- */
- public static final int INVALID_INCLUDEPATH = 964;
-
- /**
- * Status constant indicating that a variable path was not resolvable
- * indicating either the referred variable is undefined, unbound or the resolved
- * variable path does not correspond to an existing file or folder.
- */
- public static final int CP_VARIABLE_PATH_UNBOUND = 965;
-
- /**
- * Status constant indicating a core exception occurred.
- * Use <code>getException</code> to retrieve a <code>CoreException</code>.
- */
- public static final int CORE_EXCEPTION = 966;
-
- /**
- * Status constant indicating one or more of the elements
- * supplied are not of a valid type for the operation to
- * process.
- * The element(s) can be retrieved using <code>getElements</code> on the status object.
- */
- public static final int INVALID_ELEMENT_TYPES = 967;
-
- /**
- * Status constant indicating that no elements were
- * provided to the operation for processing.
- */
- public static final int NO_ELEMENTS_TO_PROCESS = 968;
-
- /**
- * Status constant indicating that one or more elements
- * supplied do not exist.
- * The element(s) can be retrieved using <code>getElements</code> on the status object.
- *
- * @see IJavaScriptModelStatus#isDoesNotExist()
- */
- public static final int ELEMENT_DOES_NOT_EXIST = 969;
-
- /**
- * Status constant indicating that a <code>null</code> path was
- * supplied to the operation.
- */
- public static final int NULL_PATH = 970;
-
- /**
- * Status constant indicating that a path outside of the
- * project was supplied to the operation. The path can be retrieved using
- * <code>getPath</code> on the status object.
- */
- public static final int PATH_OUTSIDE_PROJECT = 971;
-
- /**
- * Status constant indicating that a relative path
- * was supplied to the operation when an absolute path is
- * required. The path can be retrieved using <code>getPath</code> on the
- * status object.
- */
- public static final int RELATIVE_PATH = 972;
-
- /**
- * Status constant indicating that a path specifying a device
- * was supplied to the operation when a path with no device is
- * required. The path can be retrieved using <code>getPath</code> on the
- * status object.
- */
- public static final int DEVICE_PATH = 973;
-
- /**
- * Status constant indicating that a string
- * was supplied to the operation that was <code>null</code>.
- */
- public static final int NULL_STRING = 974;
-
- /**
- * Status constant indicating that the operation encountered
- * a read-only element.
- * The element(s) can be retrieved using <code>getElements</code> on the status object.
- */
- public static final int READ_ONLY = 976;
-
- /**
- * Status constant indicating that a naming collision would occur
- * if the operation proceeded.
- */
- public static final int NAME_COLLISION = 977;
-
- /**
- * Status constant indicating that a destination provided for a copy/move/rename operation
- * is invalid.
- * The destination element can be retrieved using <code>getElements</code> on the status object.
- */
- public static final int INVALID_DESTINATION = 978;
-
- /**
- * Status constant indicating that a path provided to an operation
- * is invalid. The path can be retrieved using <code>getPath</code> on the
- * status object.
- */
- public static final int INVALID_PATH = 979;
-
- /**
- * Status constant indicating the given source position is out of bounds.
- */
- public static final int INDEX_OUT_OF_BOUNDS = 980;
-
- /**
- * Status constant indicating there is an update conflict
- * for a working copy. The compilation unit on which the
- * working copy is based has changed since the working copy
- * was created.
- */
- public static final int UPDATE_CONFLICT = 981;
-
- /**
- * Status constant indicating that <code>null</code> was specified
- * as a name argument.
- */
- public static final int NULL_NAME = 982;
-
- /**
- * Status constant indicating that a name provided is not syntactically correct.
- * The name can be retrieved from <code>getString</code>.
- */
- public static final int INVALID_NAME = 983;
-
- /**
- * Status constant indicating that the specified contents
- * are not valid.
- */
- public static final int INVALID_CONTENTS = 984;
-
- /**
- * Status constant indicating that an <code>java.io.IOException</code>
- * occurred.
- */
- public static final int IO_EXCEPTION = 985;
-
- /**
- * Status constant indicating that a <code>DOMException</code>
- * occurred.
- */
- public static final int DOM_EXCEPTION = 986;
-
- /**
- * Status constant indicating that a <code>TargetException</code>
- * occurred.
- */
- public static final int TARGET_EXCEPTION = 987;
-
- /**
- * Status constant indicating that the JavaScript validator
- * could not be initialized.
- */
- public static final int BUILDER_INITIALIZATION_ERROR = 990;
-
- /**
- * Status constant indicating that the JavaScript validator's last built state
- * could not be serialized or deserialized.
- */
- public static final int BUILDER_SERIALIZATION_ERROR = 991;
-
- /**
- * Status constant indicating that an error was encountered while
- * trying to evaluate a code snippet, or other item.
- */
- public static final int EVALUATION_ERROR = 992;
-
- /**
- * Status constant indicating that a sibling specified is not valid.
- */
- public static final int INVALID_SIBLING = 993;
-
- /**
- * Status indicating that a JavaScript element could not be created because
- * the underlying resource is invalid.
- * @see JavaScriptCore
- */
- public static final int INVALID_RESOURCE = 995;
-
- /**
- * Status indicating that a JavaScript element could not be created because
- * the underlying resource is not of an appropriate type.
- * @see JavaScriptCore
- */
- public static final int INVALID_RESOURCE_TYPE = 996;
-
- /**
- * Status indicating that a JavaScript element could not be created because
- * the project owning underlying resource does not have the JavaScript nature.
- * @see JavaScriptCore
- */
- public static final int INVALID_PROJECT = 997;
-
- /**
- * Status indicating that the package declaration in a <code>IJavaScriptUnit</code>
- * does not correspond to the <code>IPackageFragment</code> it belongs to.
- * The <code>getString</code> method of the associated status object
- * gives the name of the package in which the <code>IJavaScriptUnit</code> is
- * declared.
- */
- public static final int INVALID_PACKAGE = 998;
-
- /**
- * Status indicating that the corresponding resource has no local contents yet.
- * This might happen when attempting to use a resource before its contents
- * has been made locally available.
- */
- public static final int NO_LOCAL_CONTENTS = 999;
-
- /**
- * Status indicating that a .jsdtScope file is ill-formed, and thus cannot
- * be read/written successfully.
- */
- public static final int INVALID_INCLUDEPATH_FILE_FORMAT = 1000;
-
- /**
- * Status indicating that a project is involved in a build path cycle.
- */
- public static final int INCLUDEPATH_CYCLE = 1001;
-
- /**
- * Status constant indicating that an inclusion or an exclusion pattern got specified
- * on a includepath source entry, though it was explicitely disabled
- * according to its project preference settings.
- * @see org.eclipse.wst.jsdt.core.IJavaScriptProject#getOptions(boolean)
- */
- public static final int DISABLED_CP_EXCLUSION_PATTERNS = 1002;
-
- /**
- * Status constant indicating that a specific output location got associated
- * with a source entry, though it was explicitely disabled according to its project
- * preference settings.
- * @see org.eclipse.wst.jsdt.core.IJavaScriptProject#getOptions(boolean)
- */
- public static final int DISABLED_CP_MULTIPLE_OUTPUT_LOCATIONS = 1003;
-
- /*
- * Status constant indicating that a project is prerequisiting some library for which the
- * classfile JDK version level is more recent than the project JDK target level setting.
- * This can indicate some binary incompatibility issues later on.
- */
- public static final int INCOMPATIBLE_JDK_LEVEL = 1004;
-
- /**
- * Status constant indicating that a validation failure occurred.
- */
- public static final int VALIDATION_FAILURE = 1005;
- /**
- * Status constant indicating that an element is not on its project's includepath.
- */
- public static final int ELEMENT_NOT_ON_CLASSPATH = 1006;
- /*
- * Status constant indicating that a compiler option is invalid.
- */
-// public static final int INVALID_COMPILER_OPTION = 1007;
- /**
- * <p>Status constant indicating that the attached jsdoc content cannot be retrieved due to multiple reasons:
- * invalid url, timed-out,...</p>
- *
- */
- public static final int CANNOT_RETRIEVE_ATTACHED_JSDOC = 1008;
- /**
- * <p>Status constant indicating that the attached jsdoc content format is unrecognized.</p>
- *
- */
- public static final int UNKNOWN_JSDOC_FORMAT = 1009;
- /**
- * <p>Status constant indicating that the variable is deprecated.</p>
- *
- */
- public static final int DEPRECATED_VARIABLE = 1010;
-}
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
deleted file mode 100644
index 8b8df17e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJavaScriptProject.java
+++ /dev/null
@@ -1,857 +0,0 @@
-/*******************************************************************************
- * 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
- * IBM Corporation - added getOption(String, boolean), getOptions(boolean) and setOptions(Map)
- * IBM Corporation - deprecated getPackageFragmentRoots(IIncludePathEntry) and
- * added findPackageFragmentRoots(IIncludePathEntry)
- * IBM Corporation - added isOnClasspath(IResource)
- * IBM Corporation - added setOption(String, String)
- * IBM Corporation - added forceClasspathReload(IProgressMonitor)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core;
-
-import java.util.Map;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.wst.jsdt.core.eval.IEvaluationContext;
-
-/**
- * A JavaScript project represents a view of a project resource in terms of JavaScript
- * elements such as package fragments, types, methods and fields.
- * A project may contain several source folders (package roots), which contain source folders (package fragments).
- * A package root corresponds to an underlying folder.
- * <p>
- * Each JavaScript project has a includepath, defining which folders contain source code and
- * where required libraries are located. A project that
- * references packages in another project can access the packages by including
- * the required project in a includepath entry. The JavaScript model will present the
- * source elements in the required project. The includepath format is a sequence of includepath entries
- * describing the location and contents of package fragment roots.
- * </p>
- * JavaScript project elements need to be opened before they can be navigated or manipulated.
- * The children of a JavaScript project are the package fragment roots that are
- * defined by the includepath and contained in this project (in other words, it
- * does not include package fragment roots for other projects).
- * </p>
- * <p>
- * This interface is not intended to be implemented by clients. An instance
- * of one of these handles can be created via
- * <code>JavaScriptCore.create(project)</code>.
- * </p>
- *
- * @see JavaScriptCore#create(org.eclipse.core.resources.IProject)
- * @see IIncludePathEntry
- *
- * 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 IJavaScriptProject extends IParent, IJavaScriptElement, IOpenable {
-
- /* returns the projects scope file */
- IFile getJSDTScopeFile();
-
- /* returns the projects scope file */
- IFile getJSDTScopeFile(boolean forceCreate);
-
- /**
- * Decodes the includepath entry that has been encoded in the given string
- * in the context of this project.
- * Returns null if the encoded entry is malformed.
- *
- * @param encodedEntry the encoded includepath entry
- * @return the decoded includepath entry, or <code>null</code> if unable to decode it
- */
- IIncludePathEntry decodeIncludepathEntry(String encodedEntry);
-
- /**
- * Encodes the given includepath entry into a string in the context of this project.
- *
- * @param includepathEntry the includepath entry to encode
- * @return the encoded includepath entry
- */
- String encodeIncludepathEntry(IIncludePathEntry includepathEntry);
-
- /**
- * Returns the <code>IJavaScriptElement</code> corresponding to the given
- * includepath-relative path, or <code>null</code> if no such
- * <code>IJavaScriptElement</code> is found. The result is one of an
- * <code>IJavaScriptUnit</code>, <code>IClassFile</code>, or
- * <code>IPackageFragment</code>.
- * <p>
- * When looking for a package fragment, there might be several potential
- * matches; only one of them is returned.
- *
- * <p>For example, the path "java/lang/Object.js", would result in the
- * <code>IJavaScriptUnit</code> or <code>IClassFile</code> corresponding to
- * "java.lang.Object". The path "java/lang" would result in the
- * <code>IPackageFragment</code> for "java.lang".
- * @param path the given includepath-relative path
- * @exception JavaScriptModelException if the given path is <code>null</code>
- * or absolute
- * @return the <code>IJavaScriptElement</code> corresponding to the given
- * includepath-relative path, or <code>null</code> if no such
- * <code>IJavaScriptElement</code> is found
- */
- IJavaScriptElement findElement(IPath path) throws JavaScriptModelException;
-
- /**
- * Returns the <code>IJavaScriptElement</code> corresponding to the given
- * includepath-relative path, or <code>null</code> if no such
- * <code>IJavaScriptElement</code> is found. The result is one of an
- * <code>IJavaScriptUnit</code>, <code>IClassFile</code>, or
- * <code>IPackageFragment</code>. If it is an <code>IJavaScriptUnit</code>,
- * its owner is the given owner.
- * <p>
- * When looking for a package fragment, there might be several potential
- * matches; only one of them is returned.
- *
- * <p>For example, the path "java/lang/Object.js", would result in the
- * <code>IJavaScriptUnit</code> or <code>IClassFile</code> corresponding to
- * "java.lang.Object". The path "java/lang" would result in the
- * <code>IPackageFragment</code> for "java.lang".
- * @param path the given includepath-relative path
- * @param owner the owner of the returned javaScript unit, ignored if it is
- * not a javaScript unit.
- * @exception JavaScriptModelException if the given path is <code>null</code>
- * or absolute
- * @return the <code>IJavaScriptElement</code> corresponding to the given
- * includepath-relative path, or <code>null</code> if no such
- * <code>IJavaScriptElement</code> is found
- */
- IJavaScriptElement findElement(IPath path, WorkingCopyOwner owner) throws JavaScriptModelException;
-
- /**
- * Returns the first existing package fragment on this project's includepath
- * whose path matches the given (absolute) path, or <code>null</code> if none
- * exist.
- * The path can be:
- * - internal to the workbench: "/Project/src"
- * - external to the workbench: "c:/jdk/classes.zip/java/lang"
- * @param path the given absolute path
- * @exception JavaScriptModelException if this project does not exist or if an
- * exception occurs while accessing its corresponding resource
- * @return the first existing package fragment on this project's includepath
- * whose path matches the given (absolute) path, or <code>null</code> if none
- * exist
- */
- IPackageFragment findPackageFragment(IPath path) throws JavaScriptModelException;
-
- /**
- * Returns the existing package fragment root on this project's includepath
- * whose path matches the given (absolute) path, or <code>null</code> if
- * one does not exist.
- * The path can be:
- * - internal to the workbench: "/Compiler/src"
- * - external to the workbench: "c:/jdk/classes.zip"
- * @param path the given absolute path
- * @exception JavaScriptModelException if this project does not exist or if an
- * exception occurs while accessing its corresponding resource
- * @return the existing package fragment root on this project's includepath
- * whose path matches the given (absolute) path, or <code>null</code> if
- * one does not exist
- */
- IPackageFragmentRoot findPackageFragmentRoot(IPath path)
- throws JavaScriptModelException;
- /**
- * Returns the existing package fragment roots identified by the given entry.
- * Note that a includepath entry that refers to another project may
- * have more than one root (if that project has more than on root
- * containing source), and includepath entries within the current
- * project identify a single root.
- * <p>
- * If the includepath entry denotes a variable, it will be resolved and return
- * the roots of the target entry (empty if not resolvable).
- * <p>
- * If the includepath entry denotes a container, it will be resolved and return
- * the roots corresponding to the set of container entries (empty if not resolvable).
- *
- * @param entry the given entry
- * @return the existing package fragment roots identified by the given entry
- * @see IJsGlobalScopeContainer
- */
- IPackageFragmentRoot[] findPackageFragmentRoots(IIncludePathEntry entry);
- /**
- * Returns the first type found following this project's includepath
- * with the given fully qualified name or <code>null</code> if none is found.
- * The fully qualified name is a dot-separated name. For example,
- * a class B defined as a member type of a class A in package x.y should have a
- * the fully qualified name "x.y.A.B".
- *
- * Note that in order to be found, a type name (or its toplevel enclosing
- * type name) must match its corresponding javaScript unit name. As a
- * consequence, secondary types cannot be found using this functionality.
- * To find secondary types use {@link #findType(String, IProgressMonitor)} instead.
- *
- * @param fullyQualifiedName the given fully qualified name
- * @exception JavaScriptModelException if this project does not exist or if an
- * exception occurs while accessing its corresponding resource
- * @return the first type found following this project's includepath
- * with the given fully qualified name or <code>null</code> if none is found
- * @see IType#getFullyQualifiedName(char)
- */
- IType findType(String fullyQualifiedName) throws JavaScriptModelException;
-
- /**
- * Returns all the types found following this project's includepath
- * with the given fully qualified name or <code>null</code> if none is found.
- * The fully qualified name is a dot-separated name. For example,
- * a class B defined as a member type of a class A in package x.y should have a
- * the fully qualified name "x.y.A.B".
- *
- * Note that in order to be found, a type name (or its toplevel enclosing
- * type name) must match its corresponding javaScript unit name. As a
- * consequence, secondary types cannot be found using this functionality.
- * To find secondary types use {@link #findType(String, IProgressMonitor)} instead.
- *
- * @param fullyQualifiedName the given fully qualified name
- * @exception JavaScriptModelException if this project does not exist or if an
- * exception occurs while accessing its corresponding resource
- * @return the first type found following this project's includepath
- * with the given fully qualified name or <code>null</code> if none is found
- * @see IType#getFullyQualifiedName(char)
- */
- IType[] findTypes(String fullyQualifiedName) throws JavaScriptModelException;
-
- /**
- * Same functionality as {@link #findType(String)} but also look for secondary
- * types if given name does not match a javaScript unit name.
- *
- * @param fullyQualifiedName the given fully qualified name
- * @param progressMonitor the progress monitor to report progress to,
- * or <code>null</code> if no progress monitor is provided
- * @exception JavaScriptModelException if this project does not exist or if an
- * exception occurs while accessing its corresponding resource
- * @return the first type found following this project's includepath
- * with the given fully qualified name or <code>null</code> if none is found
- * @see IType#getFullyQualifiedName(char)
- */
- IType findType(String fullyQualifiedName, IProgressMonitor progressMonitor) throws JavaScriptModelException;
- /**
- * Returns the first type found following this project's includepath
- * with the given fully qualified name or <code>null</code> if none is found.
- * The fully qualified name is a dot-separated name. For example,
- * a class B defined as a member type of a class A in package x.y should have a
- * the fully qualified name "x.y.A.B".
- * If the returned type is part of a javaScript unit, its owner is the given
- * owner.
- *
- * Note that in order to be found, a type name (or its toplevel enclosing
- * type name) must match its corresponding javaScript unit name. As a
- * consequence, secondary types cannot be found using this functionality.
- * To find secondary types use {@link #findType(String, WorkingCopyOwner, IProgressMonitor)}
- * instead.
- *
- * @param fullyQualifiedName the given fully qualified name
- * @param owner the owner of the returned type's javaScript unit
- * @exception JavaScriptModelException if this project does not exist or if an
- * exception occurs while accessing its corresponding resource
- * @return the first type found following this project's includepath
- * with the given fully qualified name or <code>null</code> if none is found
- * @see IType#getFullyQualifiedName(char)
- */
- IType findType(String fullyQualifiedName, WorkingCopyOwner owner) throws JavaScriptModelException;
- /**
- * Returns all the types found following this project's includepath
- * with the given fully qualified name or <code>null</code> if none is found.
- * The fully qualified name is a dot-separated name. For example,
- * a class B defined as a member type of a class A in package x.y should have a
- * the fully qualified name "x.y.A.B".
- * If the returned type is part of a javaScript unit, its owner is the given
- * owner.
- *
- * Note that in order to be found, a type name (or its toplevel enclosing
- * type name) must match its corresponding javaScript unit name. As a
- * consequence, secondary types cannot be found using this functionality.
- * To find secondary types use {@link #findType(String, WorkingCopyOwner, IProgressMonitor)}
- * instead.
- *
- * @param fullyQualifiedName the given fully qualified name
- * @param owner the owner of the returned type's javaScript unit
- * @exception JavaScriptModelException if this project does not exist or if an
- * exception occurs while accessing its corresponding resource
- * @return the first type found following this project's includepath
- * with the given fully qualified name or <code>null</code> if none is found
- * @see IType#getFullyQualifiedName(char)
- */
- IType[] findTypes(String fullyQualifiedName, WorkingCopyOwner owner) throws JavaScriptModelException;
- /**
- * Same functionality as {@link #findType(String, WorkingCopyOwner)}
- * but also look for secondary types if given name does not match
- * a javaScript unit name.
- *
- * @param fullyQualifiedName the given fully qualified name
- * @param owner the owner of the returned type's javaScript unit
- * @param progressMonitor the progress monitor to report progress to,
- * or <code>null</code> if no progress monitor is provided
- * @exception JavaScriptModelException if this project does not exist or if an
- * exception occurs while accessing its corresponding resource
- * @return the first type found following this project's includepath
- * with the given fully qualified name or <code>null</code> if none is found
- * @see IType#getFullyQualifiedName(char)
- */
- IType findType(String fullyQualifiedName, WorkingCopyOwner owner, IProgressMonitor progressMonitor) throws JavaScriptModelException;
- /**
- * Returns the first type found following this project's includepath
- * with the given package name and type qualified name
- * or <code>null</code> if none is found.
- * The package name is a dot-separated name.
- * The type qualified name is also a dot-separated name. For example,
- * a class B defined as a member type of a class A should have the
- * type qualified name "A.B".
- *
- * Note that in order to be found, a type name (or its toplevel enclosing
- * type name) must match its corresponding javaScript unit name. As a
- * consequence, secondary types cannot be found using this functionality.
- * To find secondary types use {@link #findType(String, String, IProgressMonitor)}
- * instead.
- *
- * @param packageName the given package name
- * @param typeQualifiedName the given type qualified name
- * @exception JavaScriptModelException if this project does not exist or if an
- * exception occurs while accessing its corresponding resource
- * @return the first type found following this project's includepath
- * with the given package name and type qualified name
- * or <code>null</code> if none is found
- * @see IType#getTypeQualifiedName(char)
- */
- IType findType(String packageName, String typeQualifiedName) throws JavaScriptModelException;
- /**
- * Same functionality as {@link #findType(String, String)} but also look for
- * secondary types if given name does not match a javaScript unit name.
- *
- * @param packageName the given package name
- * @param typeQualifiedName the given type qualified name
- * @param progressMonitor the progress monitor to report progress to,
- * or <code>null</code> if no progress monitor is provided
- * @exception JavaScriptModelException if this project does not exist or if an
- * exception occurs while accessing its corresponding resource
- * @return the first type found following this project's includepath
- * with the given fully qualified name or <code>null</code> if none is found
- * @see IType#getFullyQualifiedName(char)
- */
- IType findType(String packageName, String typeQualifiedName, IProgressMonitor progressMonitor) throws JavaScriptModelException;
- /**
- * Returns the first type found following this project's includepath
- * with the given package name and type qualified name
- * or <code>null</code> if none is found.
- * The package name is a dot-separated name.
- * The type qualified name is also a dot-separated name. For example,
- * a class B defined as a member type of a class A should have the
- * type qualified name "A.B".
- * If the returned type is part of a javaScript unit, its owner is the given
- * owner.
- *
- * Note that in order to be found, a type name (or its toplevel enclosing
- * type name) must match its corresponding javaScript unit name. As a
- * consequence, secondary types cannot be found using this functionality.
- * To find secondary types use {@link #findType(String, String, WorkingCopyOwner, IProgressMonitor)}
- * instead.
- *
- * @param packageName the given package name
- * @param typeQualifiedName the given type qualified name
- * @param owner the owner of the returned type's javaScript unit
- * @exception JavaScriptModelException if this project does not exist or if an
- * exception occurs while accessing its corresponding resource
- * @return the first type found following this project's includepath
- * with the given package name and type qualified name
- * or <code>null</code> if none is found
- * @see IType#getTypeQualifiedName(char)
- */
- IType findType(String packageName, String typeQualifiedName, WorkingCopyOwner owner) throws JavaScriptModelException;
- /**
- * Same functionality as {@link #findType(String, String, WorkingCopyOwner)}
- * but also look for secondary types if given name does not match a javaScript unit name.
- *
- * @param packageName the given package name
- * @param typeQualifiedName the given type qualified name
- * @param owner the owner of the returned type's javaScript unit
- * @param progressMonitor the progress monitor to report progress to,
- * or <code>null</code> if no progress monitor is provided
- * @exception JavaScriptModelException if this project does not exist or if an
- * exception occurs while accessing its corresponding resource
- * @return the first type found following this project's includepath
- * with the given fully qualified name or <code>null</code> if none is found
- * @see IType#getFullyQualifiedName(char)
- */
- IType findType(String packageName, String typeQualifiedName, WorkingCopyOwner owner, IProgressMonitor progressMonitor) throws JavaScriptModelException;
-
- /**
- * Returns all of the existing package fragment roots that exist
- * on the includepath, in the order they are defined by the includepath.
- *
- * @return all of the existing package fragment roots that exist
- * on the includepath
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
- IPackageFragmentRoot[] getAllPackageFragmentRoots() throws JavaScriptModelException;
-
- /**
- * Returns an array of non-JavaScript resources directly contained in this project.
- * It does not transitively answer non-JavaScript resources contained in folders;
- * these would have to be explicitly iterated over.
- * <p>
- * Non-JavaScript resources includes other files and folders located in the
- * project not accounted for by any of it source or binary package fragment
- * roots. If the project is a source folder itself, resources excluded from the
- * corresponding source includepath entry by one or more exclusion patterns
- * are considered non-JavaScript resources and will appear in the result
- * (possibly in a folder)
- * </p>
- *
- * @return an array of non-JavaScript resources (<code>IFile</code>s and/or
- * <code>IFolder</code>s) directly contained in this project
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
- Object[] getNonJavaScriptResources() throws JavaScriptModelException;
-
- /**
- * Helper method for returning one option value only. Equivalent to <code>(String)this.getOptions(inheritJavaCoreOptions).get(optionName)</code>
- * Note that it may answer <code>null</code> if this option does not exist, or if there is no custom value for it.
- * <p>
- * For a complete description of the configurable options, see <code>JavaScriptCore#getDefaultOptions</code>.
- * </p>
- *
- * @param optionName the name of an option
- * @param inheritJavaCoreOptions - boolean indicating whether JavaScriptCore options should be inherited as well
- * @return the String value of a given option
- * @see JavaScriptCore#getDefaultOptions()
- */
- String getOption(String optionName, boolean inheritJavaCoreOptions);
-
- /**
- * Returns the table of the current custom options for this project. Projects remember their custom options,
- * in other words, only the options different from the the JavaScriptCore global options for the workspace.
- * A boolean argument allows to directly merge the project options with global ones from <code>JavaScriptCore</code>.
- * <p>
- * For a complete description of the configurable options, see <code>JavaScriptCore#getDefaultOptions</code>.
- * </p>
- *
- * @param inheritJavaCoreOptions - boolean indicating whether JavaScriptCore options should be inherited as well
- * @return table of current settings of all options
- * (key type: <code>String</code>; value type: <code>String</code>)
- * @see JavaScriptCore#getDefaultOptions()
- */
- Map getOptions(boolean inheritJavaCoreOptions);
-
- /**
- * Returns a package fragment root for the file at the specified file system path.
- * This is a handle-only method. The underlying <code>java.io.File</code>
- * may or may not exist. No resource is associated with this local file
- * package fragment root.
- *
- * @param filePath the file system path
- * @return a package fragment root for the file at the specified file system path
- */
- IPackageFragmentRoot getPackageFragmentRoot(String filePath);
-
- /**
- * Returns a package fragment root for the given resource, which
- * must either be a folder representing the top of a package hierarchy,
- * or a javaScript file.
- * This is a handle-only method. The underlying resource may or may not exist.
- *
- * @param resource the given resource
- * @return a package fragment root for the given resource, which
- * must either be a folder representing the top of a package hierarchy,
- * or a javaScript file
- */
- IPackageFragmentRoot getPackageFragmentRoot(IResource resource);
-
- /**
- * Returns all of the package fragment roots contained in this
- * project, identified on this project's resolved includepath. The result
- * does not include package fragment roots in other projects referenced
- * on this project's includepath.
- *
- * <p>NOTE: This is equivalent to <code>getChildren()</code>.
- *
- * @return all of the package fragment roots contained in this
- * project, identified on this project's resolved includepath
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
- IPackageFragmentRoot[] getPackageFragmentRoots() throws JavaScriptModelException;
-
- /**
- * Returns all package fragments in all package fragment roots contained
- * in this project. This is a convenience method.
- *
- * Note that the package fragment roots corresponds to the resolved
- * includepath of the project.
- *
- * @return all package fragments in all package fragment roots contained
- * in this project
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
- IPackageFragment[] getPackageFragments() throws JavaScriptModelException;
-
- /**
- * Returns the <code>IProject</code> on which this <code>IJavaScriptProject</code>
- * was created. This is handle-only method.
- *
- * @return the <code>IProject</code> on which this <code>IJavaScriptProject</code>
- * was created
- */
- IProject getProject();
-
- /**
- * Returns the raw includepath for the project, as a list of includepath
- * entries. This corresponds to the exact set of entries which were assigned
- * using <code>setRawIncludepath</code>, in particular such a includepath may
- * contain includepath variable and includepath container entries. Includepath
- * variable and includepath container entries can be resolved using the
- * helper method <code>getResolvedIncludepath</code>; includepath variable
- * entries also can be resolved individually using
- * <code>JavaScriptCore#getIncludepathVariable</code>).
- * <p>
- * Both includepath containers and includepath variables provides a level of
- * indirection that can make the <code>.jsdtScope</code> file stable across
- * workspaces.
- * </p>
- * <p>
- * Note that in case the project isn't yet opened, the includepath will
- * be read directly from the associated <tt>.jsdtScope</tt> file.
- * </p>
- *
- * @return the raw includepath for the project, as a list of includepath entries
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- * @see IIncludePathEntry
- */
- IIncludePathEntry[] getRawIncludepath() throws JavaScriptModelException;
-
- /**
- * Returns the names of the projects that are directly required by this
- * project. A project is required if it is in its includepath.
- * <p>
- * The project names are returned in the order they appear on the includepath.
- *
- * @return the names of the projects that are directly required by this
- * project in includepath order
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
- String[] getRequiredProjectNames() throws JavaScriptModelException;
-
- /**
- * This is a helper method returning the resolved includepath for the project
- * as a list of simple (non-variable, non-container) includepath entries.
- * All includepath variable and includepath container entries in the project's
- * raw includepath will be replaced by the simple includepath entries they
- * resolve to.
- * <p>
- * The resulting resolved includepath is accurate for the given point in time.
- * If the project's raw includepath is later modified, or if includepath
- * variables are changed, the resolved includepath can become out of date.
- * Because of this, hanging on resolved includepath is not recommended.
- * </p>
- *
- * @param ignoreUnresolvedEntry indicates how to handle unresolvable
- * variables and containers; <code>true</code> indicates that missing
- * variables and unresolvable includepath containers should be silently
- * ignored, and that the resulting list should consist only of the
- * entries that could be successfully resolved; <code>false</code> indicates
- * that a <code>JavaScriptModelException</code> should be thrown for the first
- * unresolved variable or container
- * @return the resolved includepath for the project as a list of simple
- * includepath entries, where all includepath variable and container entries
- * have been resolved and substituted with their final target entries
- * @exception JavaScriptModelException in one of the corresponding situation:
- * <ul>
- * <li>this element does not exist</li>
- * <li>an exception occurs while accessing its corresponding resource</li>
- * <li>a includepath variable or includepath container was not resolvable
- * and <code>ignoreUnresolvedEntry</code> is <code>false</code>.</li>
- * </ul>
- * @see IIncludePathEntry
- */
- IIncludePathEntry[] getResolvedIncludepath(boolean ignoreUnresolvedEntry)
- throws JavaScriptModelException;
-
- /**
- * Returns whether this project has been built at least once and thus whether it has a build state.
- * @return true if this project has been built at least once, false otherwise
- */
- boolean hasBuildState();
-
- /**
- * Returns whether setting this project's includepath to the given includepath entries
- * would result in a cycle.
- *
- * If the set of entries contains some variables, those are resolved in order to determine
- * cycles.
- *
- * @param entries the given includepath entries
- * @return true if the given includepath entries would result in a cycle, false otherwise
- */
- boolean hasIncludepathCycle(IIncludePathEntry[] entries);
- /**
- * Returns whether the given element is on the includepath of this project,
- * that is, referenced from a includepath entry and not explicitly excluded
- * using an exclusion pattern.
- *
- * @param element the given element
- * @return <code>true</code> if the given element is on the includepath of
- * this project, <code>false</code> otherwise
- * @see IIncludePathEntry#getInclusionPatterns()
- * @see IIncludePathEntry#getExclusionPatterns()
- */
- boolean isOnIncludepath(IJavaScriptElement element);
- /**
- * Returns whether the given resource is on the includepath of this project,
- * that is, referenced from a includepath entry and not explicitly excluded
- * using an exclusion pattern.
- *
- * @param resource the given resource
- * @return <code>true</code> if the given resource is on the includepath of
- * this project, <code>false</code> otherwise
- * @see IIncludePathEntry#getInclusionPatterns()
- * @see IIncludePathEntry#getExclusionPatterns()
- */
- boolean isOnIncludepath(IResource resource);
-
- /**
- * Creates a new evaluation context.
- * @return a new evaluation context.
- */
- IEvaluationContext newEvaluationContext();
-
- /**
- * Creates and returns a type hierarchy for all types in the given
- * region, considering subtypes within that region.
- *
- * @param monitor the given progress monitor
- * @param region the given region
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- * @exception IllegalArgumentException if region is <code>null</code>
- * @return a type hierarchy for all types in the given
- * region, considering subtypes within that region
- */
- ITypeHierarchy newTypeHierarchy(IRegion region, IProgressMonitor monitor)
- throws JavaScriptModelException;
-
- /**
- * Creates and returns a type hierarchy for all types in the given
- * region, considering subtypes within that region and considering types in the
- * working copies with the given owner.
- * In other words, the owner's working copies will take
- * precedence over their original javaScript units in the workspace.
- * <p>
- * Note that if a working copy is empty, it will be as if the original javaScript
- * unit had been deleted.
- * <p>
- *
- * @param monitor the given progress monitor
- * @param region the given region
- * @param owner the owner of working copies that take precedence over their original javaScript units
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- * @exception IllegalArgumentException if region is <code>null</code>
- * @return a type hierarchy for all types in the given
- * region, considering subtypes within that region
- */
- ITypeHierarchy newTypeHierarchy(IRegion region, WorkingCopyOwner owner, IProgressMonitor monitor)
- throws JavaScriptModelException;
-
- /**
- * Creates and returns a type hierarchy for the given type considering
- * subtypes in the specified region.
- *
- * @param type the given type
- * @param region the given region
- * @param monitor the given monitor
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- *
- * @exception IllegalArgumentException if type or region is <code>null</code>
- * @return a type hierarchy for the given type considering
- * subtypes in the specified region
- */
- ITypeHierarchy newTypeHierarchy(
- IType type,
- IRegion region,
- IProgressMonitor monitor)
- throws JavaScriptModelException;
-
- /**
- * Creates and returns a type hierarchy for the given type considering
- * subtypes in the specified region and considering types in the
- * working copies with the given owner.
- * In other words, the owner's working copies will take
- * precedence over their original javaScript units in the workspace.
- * <p>
- * Note that if a working copy is empty, it will be as if the original javaScript
- * unit had been deleted.
- * <p>
- *
- * @param type the given type
- * @param region the given region
- * @param monitor the given monitor
- * @param owner the owner of working copies that take precedence over their original javaScript units
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- *
- * @exception IllegalArgumentException if type or region is <code>null</code>
- * @return a type hierarchy for the given type considering
- * subtypes in the specified region
- */
- ITypeHierarchy newTypeHierarchy(
- IType type,
- IRegion region,
- WorkingCopyOwner owner,
- IProgressMonitor monitor)
- throws JavaScriptModelException;
-
- /**
- * Returns the raw includepath for the project as defined by its
- * <code>.jsdtScope</code> file from disk, or <code>null</code>
- * if unable to read the file.
- * <p>
- * This includepath may differ from the in-memory includepath returned by
- * <code>getRawIncludepath</code>, in case the automatic reconciliation
- * mechanism has not been performed yet. Usually, any change to the
- * <code>.jsdtScope</code> file is automatically noticed and reconciled at
- * the next resource change notification event. However, if the file is
- * modified within an operation, where this change needs to be taken into
- * account before the operation ends, then the includepath from disk can be
- * read using this method, and further assigned to the project using
- * <code>setRawIncludepath(...)</code>.
- * </p>
- * <p>
- * Includepath variable and includepath container entries can be resolved using
- * the helper method <code>getResolvedIncludepath</code>; includepath variable
- * entries also can be resolved individually using
- * <code>JavaScriptCore#getIncludepathVariable</code>).
- * </p>
- * <p>
- * Note that no check is performed whether the project has the JavaScript nature
- * set, allowing an existing <code>.jsdtScope</code> file to be considered
- * independantly (unlike <code>getRawIncludepath</code> which requires the
- * JavaScript nature to be associated with the project).
- * </p>
- * <p>
- * In order to manually force a project includepath refresh, one can simply
- * assign the project includepath using the result of this method, as follows:
- * <code>proj.setRawIncludepath(proj.readRawIncludepath(), monitor)</code>
- * (note that the <code>readRawIncludepath</code> method
- * could return <code>null</code>).
- * </p>
- *
- * @return the raw includepath from disk for the project, as a list of
- * includepath entries
- * @see #getRawIncludepath()
- * @see IIncludePathEntry
- */
- IIncludePathEntry[] readRawIncludepath();
-
- /**
- * Helper method for setting one option value only. Equivalent to <code>Map options = this.getOptions(false); map.put(optionName, optionValue); this.setOptions(map)</code>
- * <p>
- * For a complete description of the configurable options, see <code>JavaScriptCore#getDefaultOptions</code>.
- * </p>
- *
- * @param optionName the name of an option
- * @param optionValue the value of the option to set
- * @see JavaScriptCore#getDefaultOptions()
- */
- void setOption(String optionName, String optionValue);
-
- /**
- * Sets the project custom options. All and only the options explicitly included in the given table
- * are remembered; all previous option settings are forgotten, including ones not explicitly
- * mentioned.
- * <p>
- * For a complete description of the configurable options, see <code>JavaScriptCore#getDefaultOptions</code>.
- * </p>
- *
- * @param newOptions the new options (key type: <code>String</code>; value type: <code>String</code>),
- * or <code>null</code> to flush all custom options (clients will automatically get the global JavaScriptCore options).
- * @see JavaScriptCore#getDefaultOptions()
- */
- void setOptions(Map newOptions);
-
- /**
- * Sets the includepath of this project using a list of includepath entries. In particular such a includepath may contain
- * includepath variable entries. Includepath variable entries can be resolved individually ({@link JavaScriptCore#getIncludepathVariable(String)}),
- * or the full includepath can be resolved at once using the helper method {@link #getResolvedIncludepath(boolean)}.
- * <p>
- * </p><p>
- * If it is specified that this operation cannot modify resources, the .jsdtScope file will not be written to disk
- * and no error marker will be generated. To synchronize the .jsdtScope with the in-memory includepath,
- * one can use <code>setRawIncludepath(readRawIncludepath(), true, monitor)</code>.
- * </p><p>
- * Setting the includepath to <code>null</code> specifies a default includepath
- * (the project root). Setting the includepath to an empty array specifies an
- * empty includepath.
- * </p><p>
- * If a cycle is detected while setting this includepath (and if resources can be modified), an error marker will be added
- * to the project closing the cycle.
- * To avoid this problem, use {@link #hasIncludepathCycle(IIncludePathEntry[])}
- * before setting the includepath.
- * <p>
- * This operation acquires a lock on the workspace's root.
- *
- * @param entries a list of includepath entries
- * @param canModifyResources whether resources should be written to disk if needed
- * @param monitor the given progress monitor
- * @exception JavaScriptModelException if the includepath could not be set. Reasons include:
- * <ul>
- * <li> This JavaScript element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> The includepath is being modified during resource change event notification (CORE_EXCEPTION)
- * <li> The includepath failed the validation check as defined by {@link JavaScriptConventions#validateIncludepath(IJavaScriptProject, IIncludePathEntry[], IPath)}
- * </ul>
- * @see IIncludePathEntry
- */
- void setRawIncludepath(IIncludePathEntry[] entries, boolean canModifyResources, IProgressMonitor monitor) throws JavaScriptModelException;
-
- /**
- * Sets the includepath of this project using a list of includepath entries. In particular such a includepath may contain
- * includepath variable entries. Includepath variable entries can be resolved individually ({@link JavaScriptCore#getIncludepathVariable(String)}),
- * or the full includepath can be resolved at once using the helper method {@link #getResolvedIncludepath(boolean)}.
- * <p>
- * <p>
- * Setting the includepath to <code>null</code> specifies a default includepath
- * (the project root). Setting the includepath to an empty array specifies an
- * empty includepath.
- * <p>
- * If a cycle is detected while setting this includepath, an error marker will be added
- * to the project closing the cycle.
- * To avoid this problem, use {@link #hasIncludepathCycle(IIncludePathEntry[])}
- * before setting the includepath.
- * <p>
- * This operation acquires a lock on the workspace's root.
- *
- * @param entries a list of includepath entries
- * @param monitor the given progress monitor
- * @exception JavaScriptModelException if the includepath could not be set. Reasons include:
- * <ul>
- * <li> This JavaScript element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> The includepath is being modified during resource change event notification (CORE_EXCEPTION)
- * <li> The includepath failed the validation check as defined by {@link JavaScriptConventions#validateIncludepath(IJavaScriptProject, IIncludePathEntry[], IPath)}
- * </ul>
- * @see IIncludePathEntry
- */
- void setRawIncludepath(IIncludePathEntry[] entries, IProgressMonitor monitor)
- throws JavaScriptModelException;
-
- ITypeRoot findTypeRoot(String fullyQualifiedName) throws JavaScriptModelException;
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJavaScriptUnit.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJavaScriptUnit.java
deleted file mode 100644
index c6fd2b5a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJavaScriptUnit.java
+++ /dev/null
@@ -1,753 +0,0 @@
-/*******************************************************************************
- * 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
- * IBM Corporation - added J2SE 1.5 support
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-
-
-/**
- * Represents an entire JavaScript file (source file with one of the
- * {@link JavaScriptCore#getJavaScriptLikeExtensions() JavaScript-like extensions}).
- * JavaScriptUnit elements need to be opened before they can be navigated or manipulated.
- * The children are of type {@link IPackageDeclaration},
- * {@link IImportContainer},{@link IFunction},{@link IField}, and {@link IType},
- * and appear in the order in which they are declared in the source.
- * If a source file cannot be parsed, its structure remains unknown.
- * Use {@link IJavaScriptElement#isStructureKnown} to determine whether this is
- * the case.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * 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 IJavaScriptUnit extends ITypeRoot, ISourceManipulation {
-/**
- * Constant indicating that a reconcile operation should not return an AST.
- */
-public static final int NO_AST = 0;
-
-/**
- * Constant indicating that a reconcile operation should recompute the problems
- * even if the source hasn't changed.
- */
-public static final int FORCE_PROBLEM_DETECTION = 0x01;
-
-/**
- * Constant indicating that a reconcile operation should enable the statements recovery.
- * @see org.eclipse.wst.jsdt.core.dom.ASTParser#setStatementsRecovery(boolean)
- */
-public static final int ENABLE_STATEMENTS_RECOVERY = 0x02;
-
-/**
- * Constant indicating that a reconcile operation should enable the bindings recovery
- * @see org.eclipse.wst.jsdt.core.dom.ASTParser#setBindingsRecovery(boolean)
- * @see org.eclipse.wst.jsdt.core.dom.IBinding#isRecovered()
- */
-public static final int ENABLE_BINDINGS_RECOVERY = 0x04;
-
-
-/**
- * Changes this javaScript file handle into a working copy. A new {@link IBuffer} is
- * created using this javaScript file handle's owner. Uses the primary owner is none was
- * specified when this javaScript file handle was created.
- * <p>
- * When switching to working copy mode, problems are reported to given
- * {@link IProblemRequestor}. Note that once in working copy mode, the given
- * {@link IProblemRequestor} is ignored. Only the original {@link IProblemRequestor}
- * is used to report subsequent problems.
- * </p>
- * <p>
- * Once in working copy mode, changes to this javaScript file or its children are done in memory.
- * Only the new buffer is affected. Using {@link #commitWorkingCopy(boolean, IProgressMonitor)}
- * will bring the underlying resource in sync with this javaScript file.
- * </p>
- * <p>
- * If this JavaScript file was already in working copy mode, an internal counter is incremented and no
- * other action is taken on this javaScript file. To bring this javaScript file back into the original mode
- * (where it reflects the underlying resource), {@link #discardWorkingCopy} must be call as many
- * times as {@link #becomeWorkingCopy(IProblemRequestor, IProgressMonitor)}.
- * </p>
- *
- * @param problemRequestor a requestor which will get notified of problems detected during
- * reconciling as they are discovered. The requestor can be set to <code>null</code> indicating
- * that the client is not interested in problems.
- * @param monitor a progress monitor used to report progress while opening this javaScript file
- * or <code>null</code> if no progress should be reported
- * @throws JavaScriptModelException if this javaScript file could not become a working copy.
- * @see #discardWorkingCopy()
- *
- * @deprecated Use {@link #becomeWorkingCopy(IProgressMonitor)} instead.
- * Note that if this deprecated method is used, problems will be reported to the given problem requestor
- * as well as the problem requestor returned by the working copy owner (if not null). While this may
- * be desired in <b>some</b> situations, by and large it is not.
-*/
-void becomeWorkingCopy(IProblemRequestor problemRequestor, IProgressMonitor monitor) throws JavaScriptModelException;
-/**
- * Changes this javaScript file handle into a working copy. A new {@link IBuffer} is
- * created using this javaScript file handle's owner. Uses the primary owner if none was
- * specified when this javaScript file handle was created.
- * <p>
- * When switching to working copy mode, problems are reported to the {@link IProblemRequestor
- * problem requestor} of the {@link WorkingCopyOwner working copy owner}.
- * </p><p>
- * Once in working copy mode, changes to this javaScript file or its children are done in memory.
- * Only the new buffer is affected. Using {@link #commitWorkingCopy(boolean, IProgressMonitor)}
- * will bring the underlying resource in sync with this javaScript file.
- * </p><p>
- * If this javaScript file was already in working copy mode, an internal counter is incremented and no
- * other action is taken on this javaScript file. To bring this javaScript file back into the original mode
- * (where it reflects the underlying resource), {@link #discardWorkingCopy} must be call as many
- * times as {@link #becomeWorkingCopy(IProblemRequestor, IProgressMonitor)}.
- * </p>
- *
- * @param monitor a progress monitor used to report progress while opening this javaScript file
- * or <code>null</code> if no progress should be reported
- * @throws JavaScriptModelException if this javaScript file could not become a working copy.
- * @see #discardWorkingCopy()
- */
-void becomeWorkingCopy(IProgressMonitor monitor) throws JavaScriptModelException;
-/**
- * Commits the contents of this working copy to its underlying resource.
- *
- * <p>It is possible that the contents of the original resource have changed
- * since this working copy was created, in which case there is an update conflict.
- * The value of the <code>force</code> parameter effects the resolution of
- * such a conflict:<ul>
- * <li> <code>true</code> - in this case the contents of this working copy are applied to
- * the underlying resource even though this working copy was created before
- * a subsequent change in the resource</li>
- * <li> <code>false</code> - in this case a {@link JavaScriptModelException} is thrown</li>
- * </ul>
- * @param force a flag to handle the cases when the contents of the original resource have changed
- * since this working copy was created
- * @param monitor the given progress monitor
- * @throws JavaScriptModelException if this working copy could not commit. Reasons include:
- * <ul>
- * <li> A {@link org.eclipse.core.runtime.CoreException} occurred while updating an underlying resource
- * <li> This element is not a working copy (INVALID_ELEMENT_TYPES)
- * <li> A update conflict (described above) (UPDATE_CONFLICT)
- * </ul>
- */
-void commitWorkingCopy(boolean force, IProgressMonitor monitor) throws JavaScriptModelException;
-/**
- * Creates and returns an non-static import declaration in this javaScript file
- * with the given name. This method is equivalent to
- * <code>createImport(name, Flags.AccDefault, sibling, monitor)</code>.
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @param name the name of the import declaration to add
- * @param sibling the existing element which the import declaration will be inserted immediately before (if
- * <code> null </code>, then this import will be inserted as the last import declaration.
- * @param monitor the progress monitor to notify
- * @return the newly inserted import declaration (or the previously existing one in case attempting to create a duplicate)
- *
- * @throws JavaScriptModelException if the element could not be created. Reasons include:
- * <ul>
- * <li> This JavaScript element does not exist or the specified sibling does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A {@link org.eclipse.core.runtime.CoreException} occurred while updating an underlying resource
- * <li> The specified sibling is not a child of this javaScript file (INVALID_SIBLING)
- * <li> The name is not a valid import name (INVALID_NAME)
- * </ul>
- * @see #createImport(String, IJavaScriptElement, int, IProgressMonitor)
- *
- */
-IImportDeclaration createImport(String name, IJavaScriptElement sibling, IProgressMonitor monitor) throws JavaScriptModelException;
-
-/**
- * Creates and returns an import declaration in this javaScript file
- * with the given name.
- * <p>
- * Optionally, the new element can be positioned before the specified
- * sibling. If no sibling is specified, the element will be inserted
- * as the last import declaration in this javaScript file.
- * <p>
- * If the javaScript file already includes the specified import declaration,
- * the import is not generated (it does not generate duplicates).
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @param name the name of the import declaration
- * @param sibling the existing element which the import declaration will be inserted immediately before (if
- * <code> null </code>, then this import will be inserted as the last import declaration.
- * @param flags {@link Flags#AccStatic} for static imports, or
- * {@link Flags#AccDefault} for regular imports; other modifier flags
- * are ignored
- * @param monitor the progress monitor to notify
- * @return the newly inserted import declaration (or the previously existing one in case attempting to create a duplicate)
- *
- * @throws JavaScriptModelException if the element could not be created. Reasons include:
- * <ul>
- * <li> This JavaScript element does not exist or the specified sibling does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A {@link org.eclipse.core.runtime.CoreException} occurred while updating an underlying resource
- * <li> The specified sibling is not a child of this javaScript file (INVALID_SIBLING)
- * <li> The name is not a valid import name (INVALID_NAME)
- * </ul>
- * @see Flags
- */
-IImportDeclaration createImport(String name, IJavaScriptElement sibling, int flags, IProgressMonitor monitor) throws JavaScriptModelException;
-
-/**
- * Creates and returns a type in this javaScript file with the
- * given contents. If this javaScript file does not exist, one
- * will be created with an appropriate package declaration.
- * <p>
- * Optionally, the new type can be positioned before the specified
- * sibling. If <code>sibling</code> is <code>null</code>, the type will be appended
- * to the end of this javaScript file.
- *
- * <p>It is possible that a type with the same name already exists in this javaScript file.
- * The value of the <code>force</code> parameter effects the resolution of
- * such a conflict:<ul>
- * <li> <code>true</code> - in this case the type is created with the new contents</li>
- * <li> <code>false</code> - in this case a {@link JavaScriptModelException} is thrown</li>
- * </ul>
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- *
- * @param contents the source contents of the type declaration to add.
- * @param sibling the existing element which the type will be inserted immediately before (if
- * <code>null</code>, then this type will be inserted as the last type declaration.
- * @param force a <code>boolean</code> flag indicating how to deal with duplicates
- * @param monitor the progress monitor to notify
- * @return the newly inserted type
- *
- * @throws JavaScriptModelException if the element could not be created. Reasons include:
- * <ul>
- * <li>The specified sibling element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A {@link org.eclipse.core.runtime.CoreException} occurred while updating an underlying resource
- * <li> The specified sibling is not a child of this javaScript file (INVALID_SIBLING)
- * <li> The contents could not be recognized as a type declaration (INVALID_CONTENTS)
- * <li> There was a naming collision with an existing type (NAME_COLLISION)
- * </ul>
- */
-IType createType(String contents, IJavaScriptElement sibling, boolean force, IProgressMonitor monitor) throws JavaScriptModelException;
-
-/**
- * Creates and returns a var in this javaScript file with the
- * given contents. If this javaScript file does not exist, one
- * will be created with an appropriate package declaration.
- * <p>
- * Optionally, the new var can be positioned before the specified
- * sibling. If <code>sibling</code> is <code>null</code>, the var will be appended
- * to the end of this javaScript file.
- *
- * <p>It is possible that a var with the same name already exists in this javaScript file.
- * The value of the <code>force</code> parameter effects the resolution of
- * such a conflict:<ul>
- * <li> <code>true</code> - in this case the var is created with the new contents</li>
- * <li> <code>false</code> - in this case a {@link JavaScriptModelException} is thrown</li>
- * </ul>
- *
- * @param contents the source contents of the var declaration to add.
- * @param sibling the existing element which the var will be inserted immediately before (if
- * <code>null</code>, then this var will be inserted as the last var declaration.
- * @param force a <code>boolean</code> flag indicating how to deal with duplicates
- * @param monitor the progress monitor to notify
- * @return the newly inserted var
- *
- * @throws JavaScriptModelException if the element could not be created. Reasons include:
- * <ul>
- * <li>The specified sibling element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A {@link org.eclipse.core.runtime.CoreException} occurred while updating an underlying resource
- * <li> The specified sibling is not a child of this javaScript file (INVALID_SIBLING)
- * <li> The contents could not be recognized as a var declaration (INVALID_CONTENTS)
- * <li> There was a naming collision with an existing var (NAME_COLLISION)
- * </ul>
- */
-IField createField(String contents, IJavaScriptElement sibling, boolean force, IProgressMonitor monitor)
-throws JavaScriptModelException;
-
-
-/**
- * Creates and returns a function in this javaScript file with the
- * given contents. If this javaScript file does not exist, one
- * will be created with an appropriate package declaration.
- * <p>
- * Optionally, the new function can be positioned before the specified
- * sibling. If <code>sibling</code> is <code>null</code>, the function will be appended
- * to the end of this javaScript file.
- *
- * <p>It is possible that a function with the same name already exists in this javaScript file.
- * The value of the <code>force</code> parameter effects the resolution of
- * such a conflict:<ul>
- * <li> <code>true</code> - in this case the function is created with the new contents</li>
- * <li> <code>false</code> - in this case a {@link JavaScriptModelException} is thrown</li>
- * </ul>
- *
- * @param contents the source contents of the function declaration to add.
- * @param sibling the existing element which the function will be inserted immediately before (if
- * <code>null</code>, then this function will be inserted as the last function declaration.
- * @param force a <code>boolean</code> flag indicating how to deal with duplicates
- * @param monitor the progress monitor to notify
- * @return the newly inserted function
- *
- * @throws JavaScriptModelException if the element could not be created. Reasons include:
- * <ul>
- * <li>The specified sibling element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A {@link org.eclipse.core.runtime.CoreException} occurred while updating an underlying resource
- * <li> The specified sibling is not a child of this javaScript file (INVALID_SIBLING)
- * <li> The contents could not be recognized as a function declaration (INVALID_CONTENTS)
- * <li> There was a naming collision with an existing function (NAME_COLLISION)
- * </ul>
- */
-IFunction createMethod(String contents, IJavaScriptElement sibling, boolean force, IProgressMonitor monitor)
-throws JavaScriptModelException;
-
-/**
- * Changes this javaScript file in working copy mode back to its original mode.
- * <p>
- * This has no effect if this javaScript file was not in working copy mode.
- * </p>
- * <p>
- * If {@link #becomeWorkingCopy} was called several times on this
- * javaScript file, {@link #discardWorkingCopy} must be called as
- * many times before it switches back to the original mode.
- * </p>
- *
- * @throws JavaScriptModelException if this working copy could not return in its original mode.
- * @see #becomeWorkingCopy(IProblemRequestor, IProgressMonitor)
- */
-void discardWorkingCopy() throws JavaScriptModelException;
-/**
- * Finds the elements in this javaScript file that correspond to
- * the given element.
- * An element A corresponds to an element B if:
- * <ul>
- * <li>A has the same element name as B.
- * <li>If A is a method, A must have the same number of arguments as
- * B and the simple names of the argument types must be equals.
- * <li>The parent of A corresponds to the parent of B recursively up to
- * their respective javaScript files.
- * <li>A exists.
- * </ul>
- * Returns <code>null</code> if no such javaScript elements can be found
- * or if the given element is not included in a javaScript file.
- *
- * @param element the given element
- * @return the found elements in this javaScript file that correspond to the given element
- */
-IJavaScriptElement[] findElements(IJavaScriptElement element);
-/**
- * Finds the working copy for this javaScript file, given a {@link WorkingCopyOwner}.
- * If no working copy has been created for this javaScript file associated with this
- * working copy owner, returns <code>null</code>.
- * <p>
- * Users of this method must not destroy the resulting working copy.
- *
- * @param owner the given {@link WorkingCopyOwner}
- * @return the found working copy for this javaScript file, <code>null</code> if none
- * @see WorkingCopyOwner
- */
-IJavaScriptUnit findWorkingCopy(WorkingCopyOwner owner);
-/**
- * Returns all types declared in this javaScript file in the order
- * in which they appear in the source.
- * This includes all top-level types and nested member types.
- * It does NOT include local types (types defined in methods).
- *
- * @return the array of top-level and member types defined in a javaScript file, in declaration order.
- * @throws JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
-IType[] getAllTypes() throws JavaScriptModelException;
-/**
- * Returns the first import declaration in this javaScript file with the given name.
- * This is a handle-only method. The import declaration may or may not exist. This
- * is a convenience method - imports can also be accessed from a javaScript file's
- * import container.
- *
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @param name the name of the import to find
- * @return a handle onto the corresponding import declaration. The import declaration may or may not exist.
- */
-IImportDeclaration getImport(String name) ;
-/**
- * Returns the import container for this javaScript file.
- * This is a handle-only method. The import container may or
- * may not exist. The import container can used to access the
- * imports.
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @return a handle onto the corresponding import container. The
- * import contain may or may not exist.
- */
-IImportContainer getImportContainer();
-/**
- * Returns the import declarations in this javaScript file
- * in the order in which they appear in the source. This is
- * a convenience method - import declarations can also be
- * accessed from a javaScript file's import container.
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @return the import declarations in this javaScript file
- * @throws JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
-IImportDeclaration[] getImports() throws JavaScriptModelException;
-/**
- * Returns the primary javaScript file (whose owner is the primary owner)
- * this working copy was created from, or this javaScript file if this a primary
- * javaScript file.
- * <p>
- * Note that the returned primary javaScript file can be in working copy mode.
- * </p>
- *
- * @return the primary javaScript file this working copy was created from,
- * or this javaScript file if it is primary
- */
-IJavaScriptUnit getPrimary();
-/**
- * Returns the working copy owner of this working copy.
- * Returns null if it is not a working copy or if it has no owner.
- *
- * @return WorkingCopyOwner the owner of this working copy or <code>null</code>
- */
-WorkingCopyOwner getOwner();
-/**
- * Returns the top-level types declared in this javaScript file
- * in the order in which they appear in the source.
- *
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @return the top-level types declared in this javaScript file
- * @throws JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
-IType[] getTypes() throws JavaScriptModelException;
-/**
- * Returns a new working copy of this javaScript file if it is a primary javaScript file,
- * or this javaScript file if it is already a non-primary working copy.
- * <p>
- * Note: if intending to share a working copy amongst several clients, then
- * {@link #getWorkingCopy(WorkingCopyOwner, IProblemRequestor, IProgressMonitor)}
- * should be used instead.
- * </p><p>
- * When the working copy instance is created, an ADDED IJavaScriptElementDelta is
- * reported on this working copy.
- * </p><p>
- * Once done with the working copy, users of this method must discard it using
- * {@link #discardWorkingCopy()}.
- * </p><p>
- * Since 2.1, a working copy can be created on a not-yet existing compilation
- * unit. In particular, such a working copy can then be committed in order to create
- * the corresponding javaScript file.
- * </p>
- * @param monitor a progress monitor used to report progress while opening this javaScript file
- * or <code>null</code> if no progress should be reported
- * @throws JavaScriptModelException if the contents of this element can
- * not be determined.
- * @return a new working copy of this element if this element is not
- * a working copy, or this element if this element is already a working copy
- */
-IJavaScriptUnit getWorkingCopy(IProgressMonitor monitor) throws JavaScriptModelException;
-/**
- * Returns a shared working copy on this javaScript file using the given working copy owner to create
- * the buffer, or this javaScript file if it is already a non-primary working copy.
- * This API can only answer an already existing working copy if it is based on the same
- * original javaScript file AND was using the same working copy owner (that is, as defined by {@link Object#equals}).
- * <p>
- * The life time of a shared working copy is as follows:
- * <ul>
- * <li>The first call to {@link #getWorkingCopy(WorkingCopyOwner, IProblemRequestor, IProgressMonitor)}
- * creates a new working copy for this element</li>
- * <li>Subsequent calls increment an internal counter.</li>
- * <li>A call to {@link #discardWorkingCopy()} decrements the internal counter.</li>
- * <li>When this counter is 0, the working copy is discarded.
- * </ul>
- * So users of this method must discard exactly once the working copy.
- * <p>
- * Note that the working copy owner will be used for the life time of this working copy, that is if the
- * working copy is closed then reopened, this owner will be used.
- * The buffer will be automatically initialized with the original's javaScript file content
- * upon creation.
- * <p>
- * When the shared working copy instance is created, an ADDED IJavaScriptElementDelta is reported on this
- * working copy.
- * </p><p>
- * Since 2.1, a working copy can be created on a not-yet existing compilation
- * unit. In particular, such a working copy can then be committed in order to create
- * the corresponding javaScript file.
- * </p>
- * @param owner the working copy owner that creates a buffer that is used to get the content
- * of the working copy
- * @param problemRequestor a requestor which will get notified of problems detected during
- * reconciling as they are discovered. The requestor can be set to <code>null</code> indicating
- * that the client is not interested in problems.
- * @param monitor a progress monitor used to report progress while opening this javaScript file
- * or <code>null</code> if no progress should be reported
- * @throws JavaScriptModelException if the contents of this element can
- * not be determined.
- * @return a new working copy of this element using the given factory to create
- * the buffer, or this element if this element is already a working copy
- * @deprecated Use {@link ITypeRoot#getWorkingCopy(WorkingCopyOwner, IProgressMonitor)} instead.
- * Note that if this deprecated method is used, problems will be reported on the passed problem requester
- * as well as on the problem requestor returned by the working copy owner (if not null).
-*/
-IJavaScriptUnit getWorkingCopy(WorkingCopyOwner owner, IProblemRequestor problemRequestor, IProgressMonitor monitor) throws JavaScriptModelException;
-/**
- * Returns whether the resource of this working copy has changed since the
- * inception of this working copy.
- * Returns <code>false</code> if this javaScript file is not in working copy mode.
- *
- * @return whether the resource has changed
- */
-public boolean hasResourceChanged();
-/**
- * Returns whether this element is a working copy.
- *
- * @return true if this element is a working copy, false otherwise
- */
-boolean isWorkingCopy();
-
-/**
- * Reconciles the contents of this working copy, sends out a JavaScript delta
- * notification indicating the nature of the change of the working copy since
- * the last time it was either reconciled or made consistent
- * ({@link IOpenable#makeConsistent(IProgressMonitor)}), and returns a
- * javaScript file AST if requested.
- * <p>
- * It performs the reconciliation by locally caching the contents of
- * the working copy, updating the contents, then creating a delta
- * over the cached contents and the new contents, and finally firing
- * this delta.
- * <p>
- * The boolean argument allows to force problem detection even if the
- * working copy is already consistent.
- * </p>
- * <p>
- * This functionality allows to specify a working copy owner which is used
- * during problem detection. All references contained in the working copy are
- * resolved against other units; for which corresponding owned working copies
- * are going to take precedence over their original javaScript files. If
- * <code>null</code> is passed in, then the primary working copy owner is used.
- * </p>
- * <p>
- * Compilation problems found in the new contents are notified through the
- * {@link IProblemRequestor} interface which was passed at
- * creation, and no longer as transient markers.
- * </p>
- * <p>
- * Note: Since 3.0, added/removed/changed inner types generate change deltas.
- * </p>
- * <p>
- * If requested, a DOM AST representing the javaScript file is returned.
- * Its bindings are computed only if the problem requestor is active, or if the
- * problem detection is forced. This method returns <code>null</code> if the
- * creation of the DOM AST was not requested, or if the requested level of AST
- * API is not supported, or if the working copy was already consistent.
- * </p>
- *
- * <p>
- * This method doesn't perform statements recovery. To recover statements with syntax
- * errors, {@link #reconcile(int, boolean, boolean, WorkingCopyOwner, IProgressMonitor)} must be use.
- * </p>
- *
- * @param astLevel either {@link #NO_AST} if no AST is wanted,
- * or the {@linkplain AST#newAST(int) AST API level} of the AST if one is wanted
- * @param forceProblemDetection boolean indicating whether problem should be
- * recomputed even if the source hasn't changed
- * @param owner the owner of working copies that take precedence over the
- * original javaScript files, or <code>null</code> if the primary working
- * copy owner should be used
- * @param monitor a progress monitor
- * @return the javaScript file AST or <code>null</code> if not requested,
- * or if the requested level of AST API is not supported,
- * or if the working copy was consistent
- * @throws JavaScriptModelException if the contents of the original element
- * cannot be accessed. Reasons include:
- * <ul>
- * <li> The original JavaScript element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * </ul>
- */
-JavaScriptUnit reconcile(int astLevel, boolean forceProblemDetection, WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaScriptModelException;
-
-/**
- * Reconciles the contents of this working copy, sends out a JavaScript delta
- * notification indicating the nature of the change of the working copy since
- * the last time it was either reconciled or made consistent
- * ({@link IOpenable#makeConsistent(IProgressMonitor)}), and returns a
- * javaScript file AST if requested.
- * <p>
- * It performs the reconciliation by locally caching the contents of
- * the working copy, updating the contents, then creating a delta
- * over the cached contents and the new contents, and finally firing
- * this delta.
- * <p>
- * The boolean argument allows to force problem detection even if the
- * working copy is already consistent.
- * </p>
- * <p>
- * This functionality allows to specify a working copy owner which is used
- * during problem detection. All references contained in the working copy are
- * resolved against other units; for which corresponding owned working copies
- * are going to take precedence over their original javaScript files. If
- * <code>null</code> is passed in, then the primary working copy owner is used.
- * </p>
- * <p>
- * Compilation problems found in the new contents are notified through the
- * {@link IProblemRequestor} interface which was passed at
- * creation, and no longer as transient markers.
- * </p>
- * <p>
- * Note: Since 3.0, added/removed/changed inner types generate change deltas.
- * </p>
- * <p>
- * If requested, a DOM AST representing the javaScript file is returned.
- * Its bindings are computed only if the problem requestor is active, or if the
- * problem detection is forced. This method returns <code>null</code> if the
- * creation of the DOM AST was not requested, or if the requested level of AST
- * API is not supported, or if the working copy was already consistent.
- * </p>
- *
- * <p>
- * If statements recovery is enabled then this method tries to rebuild statements
- * with syntax error. Otherwise statements with syntax error won't be present in
- * the returning DOM AST.
- * </p>
- *
- * @param astLevel either {@link #NO_AST} if no AST is wanted,
- * or the {@linkplain org.eclipse.wst.jsdt.core.dom.AST#newAST(int) AST API level} of the AST if one is wanted
- * @param forceProblemDetection boolean indicating whether problem should be
- * recomputed even if the source hasn't changed
- * @param enableStatementsRecovery if <code>true</code> statements recovery is enabled.
- * @param owner the owner of working copies that take precedence over the
- * original javaScript files, or <code>null</code> if the primary working
- * copy owner should be used
- * @param monitor a progress monitor
- * @return the javaScript file AST or <code>null</code> if not requested,
- * or if the requested level of AST API is not supported,
- * or if the working copy was consistent
- * @throws JavaScriptModelException if the contents of the original element
- * cannot be accessed. Reasons include:
- * <ul>
- * <li> The original JavaScript element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * </ul>
- */
-JavaScriptUnit reconcile(int astLevel, boolean forceProblemDetection, boolean enableStatementsRecovery, WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaScriptModelException;
-
-/**
- * Reconciles the contents of this working copy, sends out a JavaScript delta
- * notification indicating the nature of the change of the working copy since
- * the last time it was either reconciled or made consistent
- * ({@link IOpenable#makeConsistent(IProgressMonitor)}), and returns a
- * javaScript file AST if requested.
- *
- * <p>
- * If the problem detection is forced by passing the {@link #FORCE_PROBLEM_DETECTION} bit in the given reconcile flag,
- * problem detection is run even if the working copy is already consistent.
- * </p>
- *
- * <p>
- * It performs the reconciliation by locally caching the contents of
- * the working copy, updating the contents, then creating a delta
- * over the cached contents and the new contents, and finally firing
- * this delta.</p>
- *
- * <p>
- * This functionality allows to specify a working copy owner which is used
- * during problem detection. All references contained in the working copy are
- * resolved against other units; for which corresponding owned working copies
- * are going to take precedence over their original javaScript files. If
- * <code>null</code> is passed in, then the primary working copy owner is used.
- * </p>
- * <p>
- * Compilation problems found in the new contents are notified through the
- * {@link IProblemRequestor} interface which was passed at
- * creation, and no longer as transient markers.
- * </p>
- * <p>
- * Note: Since 3.0, added/removed/changed inner types generate change deltas.
- * </p>
- * <p>
- * If requested, a DOM AST representing the javaScript file is returned.
- * Its bindings are computed only if the problem requestor is active, or if the
- * problem detection is forced. This method returns <code>null</code> if the
- * creation of the DOM AST was not requested, or if the requested level of AST
- * API is not supported, or if the working copy was already consistent.
- * </p>
- *
- * <p>
- * If statements recovery is enabled by passing the {@link #ENABLE_STATEMENTS_RECOVERY} bit in the given reconcile flag
- * then this method tries to rebuild statements with syntax error. Otherwise statements with syntax error won't be
- * present in the returning DOM AST.</p>
- * <p>
- * If bindings recovery is enabled by passing the {@link #ENABLE_BINDINGS_RECOVERY} bit in the given reconcile flag
- * then this method tries to resolve bindings even if the type resolution contains errors.</p>
- * <p>
- * The given reconcile flags is a bit-mask of the different constants ({@link #ENABLE_BINDINGS_RECOVERY},
- * {@link #ENABLE_STATEMENTS_RECOVERY}, {@link #FORCE_PROBLEM_DETECTION}). Unspecified values are left for future use.
- * </p>
- *
- * @param astLevel either {@link #NO_AST} if no AST is wanted,
- * or the {@linkplain org.eclipse.wst.jsdt.core.dom.AST#newAST(int) AST API level} of the AST if one is wanted
- * @param reconcileFlags the given reconcile flags
- * @param owner the owner of working copies that take precedence over the
- * original javaScript files, or <code>null</code> if the primary working
- * copy owner should be used
- * @param monitor a progress monitor
- * @return the javaScript file AST or <code>null</code> if not requested,
- * or if the requested level of AST API is not supported,
- * or if the working copy was consistent
- * @throws JavaScriptModelException if the contents of the original element
- * cannot be accessed. Reasons include:
- * <ul>
- * <li> The original JavaScript element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * </ul>
- * @see #FORCE_PROBLEM_DETECTION
- * @see #ENABLE_BINDINGS_RECOVERY
- * @see #ENABLE_STATEMENTS_RECOVERY
- */
-JavaScriptUnit reconcile(int astLevel, int reconcileFlags, WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaScriptModelException;
-
-/**
- * Restores the contents of this working copy to the current contents of
- * this working copy's original element. Has no effect if this element
- * is not a working copy.
- *
- * <p>Note: This is the inverse of committing the content of the
- * working copy to the original element with {@link #commitWorkingCopy(boolean, IProgressMonitor)}.
- *
- * @throws JavaScriptModelException if the contents of the original element
- * cannot be accessed. Reasons include:
- * <ul>
- * <li> The original JavaScript element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * </ul>
- */
-void restore() throws JavaScriptModelException;
-
-/**
- * Finds the function in this javaScript file that correspond to
- * the given function.
- * Returns <code>null</code> if no such function can be found
- * or if the given element is not included in a javaScript file.
- *
- * @param function the given function
- * @return the found functions in this javaScript file that correspond to the given function
- */
-IFunction[] findFunctions(IFunction function);
-
-
-
-
-}
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
deleted file mode 100644
index 22837bf8..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJsGlobalScopeContainer.java
+++ /dev/null
@@ -1,140 +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.core;
-
-import org.eclipse.core.runtime.IPath;
-
-/**
- * Interface of a includepath container.
- * A includepath container provides a way to indirectly reference a set of includepath entries through
- * a includepath entry of kind <code>CPE_CONTAINER</code>. Typically, a includepath container can
- * be used to describe a complex library composed of filess or projects, considering also
- * that containers can map to different set of entries on each project, in other words, several
- * projects can reference the same generic container path, but have each of them actually bound
- * to a different container object.
- * <p>
- * The set of entries associated with a includepath container may contain any of the following:
- * <ul>
- * <li> library entries (<code>CPE_LIBRARY</code>) </li>
- * <li> project entries (<code>CPE_PROJECT</code>) </li>
- * </ul>
- * In particular, a includepath container can neither reference further includepath containers or includepath variables.
- * <p>
- * Classpath container values are persisted locally to the workspace, but are not preserved from a
- * session to another. It is thus highly recommended to register a <code>JsGlobalScopeContainerInitializer</code>
- * for each referenced container (through the extension point "org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer").
- * <p>
- * @see IIncludePathEntry
- *
- * 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 IJsGlobalScopeContainer {
-
- /**
- * Kind for a container mapping to an application library
- */
- int K_APPLICATION = 1;
-
- /**
- * Kind for a container mapping to a system library
- */
- int K_SYSTEM = 2;
-
- /**
- * Kind for a container mapping to a default system library, implicitly contributed by the runtime
- */
- int K_DEFAULT_SYSTEM = 3;
-
- /**
- * Answers the set of includepath entries this container is mapping to.
- * <p>
- * The set of entries associated with a includepath container may contain any of the following:
- * <ul>
- * <li> library entries (<code>CPE_LIBRARY</code>) </li>
- * <li> project entries (<code>CPE_PROJECT</code>) </li>
- * </ul>
- * A includepath container can neither reference further includepath containers
- * or includepath variables.
- * </p>
- * <p>
- * This method is called by the JavaScript model when it needs to resolve this
- * includepath container entry into a list of library and project entries.
- * The method is typically called exactly once for a given JavaScript project,
- * and the resulting list of entries cached internally by the JavaScript model.
- * This method must not be called by other clients.
- * <p>
- * There are a wide variety of conditions under which this method may be
- * invoked. To ensure that the implementation does not interfere with
- * correct functioning of the JavaScript model, the implementation should use
- * only the following JavaScript model APIs:
- * <ul>
- * <li>{@link JavaScriptCore#newLibraryEntry(IPath, IPath, IPath, boolean)} and variants</li>
- * <li>{@link JavaScriptCore#newProjectEntry(IPath, boolean)} and variants</li>
- * <li>{@link JavaScriptCore#create(org.eclipse.core.resources.IWorkspaceRoot)}</li>
- * <li>{@link JavaScriptCore#create(org.eclipse.core.resources.IProject)}</li>
- * <li>{@link IJavaScriptModel#getJavaScriptProjects()}</li>
- * <li>{@link IJavaScriptProject#getRawIncludepath()}</li>
- * <li>{@link IJavaScriptProject#readRawIncludepath()}</li>
- * <li>{@link IJavaScriptProject#getOutputLocation()}</li>
- * <li>{@link IJavaScriptProject#readOutputLocation()}</li>
- * <li>JavaScript element operations marked as "handle-only"</li>
- * </ul>
- * The effects of using other JavaScript model APIs are unspecified.
- * </p>
- *
- * @return IIncludePathEntry[] - the includepath entries this container represents
- * @see IIncludePathEntry
- */
- IIncludePathEntry[] getIncludepathEntries();
-
- /**
- * Answers a readable description of this container
- *
- * @return String - a string description of the container
- */
- String getDescription();
-
- /**
- * Answers the kind of this container. Can be either:
- * <ul>
- * <li><code>K_APPLICATION</code> if this container maps to an application library</li>
- * <li><code>K_SYSTEM</code> if this container maps to a system library</li>
- * <li><code>K_DEFAULT_SYSTEM</code> if this container maps to a default system library (library
- * implicitly contributed by the runtime).</li>
- * </ul>
- * Typically, system containers should be placed first on a build path.
- * @return the kind of this container
- */
- int getKind();
-
- /**
- * Answers the container path identifying this container.
- * A container path is formed by a first ID segment followed with extra segments, which
- * can be used as additional hints for resolving to this container.
- * <p>
- * The container ID is also used to identify a<code>JsGlobalScopeContainerInitializer</code>
- * registered on the extension point "org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer", which can
- * be invoked if needing to resolve the container before it is explicitly set.
- * <p>
- * @return IPath - the container path that is associated with this container
- */
- IPath getPath();
-
- /* 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/IJsGlobalScopeContainerInitializer.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJsGlobalScopeContainerInitializer.java
deleted file mode 100644
index 3b47c5e2..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJsGlobalScopeContainerInitializer.java
+++ /dev/null
@@ -1,186 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-/**
- *
- */
-package org.eclipse.wst.jsdt.core;
-
-import java.net.URI;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.wst.jsdt.core.compiler.libraries.LibraryLocation;
-
-/**
- *
- * 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 IJsGlobalScopeContainerInitializer {
- /**
- * Binds a includepath container to a <code>IJsGlobalScopeContainer</code> for a given project,
- * or silently fails if unable to do so.
- * <p>
- * A container is identified by a container path, which must be formed of two segments.
- * The first segment is used as a unique identifier (which this initializer did register onto), and
- * the second segment can be used as an additional hint when performing the resolution.
- * <p>
- * The initializer is invoked if a container path needs to be resolved for a given project, and no
- * value for it was recorded so far. The implementation of the initializer would typically set the
- * corresponding container using <code>JavaScriptCore#setJsGlobalScopeContainer</code>.
- * <p>
- * A container initialization can be indirectly performed while attempting to resolve a project
- * includepath using <code>IJavaScriptProject#getResolvedClasspath(</code>; or directly when using
- * <code>JavaScriptCore#getJsGlobalScopeContainer</code>. During the initialization process, any attempt
- * to further obtain the same container will simply return <code>null</code> so as to avoid an
- * infinite regression of initializations.
- * <p>
- * A container initialization may also occur indirectly when setting a project includepath, as the operation
- * needs to resolve the includepath for validation purpose. While the operation is in progress, a referenced
- * container initializer may be invoked. If the initializer further tries to access the referring project includepath,
- * it will not see the new assigned includepath until the operation has completed. Note that once the JavaScript
- * change notification occurs (at the end of the operation), the model has been updated, and the project
- * includepath can be queried normally.
- * <p>
- * This method is called by the JavaScript model to give the party that defined
- * this particular kind of includepath container the chance to install
- * includepath container objects that will be used to convert includepath
- * container entries into simpler includepath entries. The method is typically
- * called exactly once for a given JavaScript project and includepath container
- * entry. This method must not be called by other clients.
- * <p>
- * There are a wide variety of conditions under which this method may be
- * invoked. To ensure that the implementation does not interfere with
- * correct functioning of the JavaScript model, the implementation should use
- * only the following JavaScript model APIs:
- * <ul>
- * <li>{@link JavaScriptCore#setJsGlobalScopeContainer(IPath, IJavaScriptProject[], IJsGlobalScopeContainer[], org.eclipse.core.runtime.IProgressMonitor)}</li>
- * <li>{@link JavaScriptCore#getJsGlobalScopeContainer(IPath, IJavaScriptProject)}</li>
- * <li>{@link JavaScriptCore#create(org.eclipse.core.resources.IWorkspaceRoot)}</li>
- * <li>{@link JavaScriptCore#create(org.eclipse.core.resources.IProject)}</li>
- * <li>{@link IJavaScriptModel#getJavaScriptProjects()}</li>
- * <li>JavaScript element operations marked as "handle-only"</li>
- * </ul>
- * The effects of using other JavaScript model APIs are unspecified.
- * </p>
- *
- * @param containerPath a two-segment path (ID/hint) identifying the container that needs
- * to be resolved
- * @param project the JavaScript project in which context the container is to be resolved.
- * This allows generic containers to be bound with project specific values.
- * @throws CoreException if an exception occurs during the initialization
- *
- * @see JavaScriptCore#getJsGlobalScopeContainer(IPath, IJavaScriptProject)
- * @see JavaScriptCore#setJsGlobalScopeContainer(IPath, IJavaScriptProject[], IJsGlobalScopeContainer[], org.eclipse.core.runtime.IProgressMonitor)
- * @see IJsGlobalScopeContainer
- */
- public abstract void initialize(IPath containerPath, IJavaScriptProject project) throws CoreException;
-
- /**
- * Returns <code>true</code> if this container initializer can be requested to perform updates
- * on its own container values. If so, then an update request will be performed using
- * <code>JsGlobalScopeContainerInitializer#requestJsGlobalScopeContainerUpdate</code>/
- * <p>
- * @param containerPath the path of the container which requires to be updated
- * @param project the project for which the container is to be updated
- * @return returns <code>true</code> if the container can be updated
- */
- public abstract boolean canUpdateJsGlobalScopeContainer(IPath containerPath, IJavaScriptProject project);
-
- /**
- * Request a registered container definition to be updated according to a container suggestion. The container suggestion
- * only acts as a place-holder to pass along the information to update the matching container definition(s) held by the
- * container initializer. In particular, it is not expected to store the container suggestion as is, but rather adjust
- * the actual container definition based on suggested changes.
- * <p>
- * IMPORTANT: In reaction to receiving an update request, a container initializer will update the corresponding
- * container definition (after reconciling changes) at its earliest convenience, using
- * <code>JavaScriptCore#setJsGlobalScopeContainer(IPath, IJavaScriptProject[], IJsGlobalScopeContainer[], IProgressMonitor)</code>.
- * Until it does so, the update will not be reflected in the JavaScript Model.
- * <p>
- * In order to anticipate whether the container initializer allows to update its containers, the predicate
- * <code>JavaScriptCore#canUpdateJsGlobalScopeContainer</code> should be used.
- * <p>
- * @param containerPath the path of the container which requires to be updated
- * @param project the project for which the container is to be updated
- * @param containerSuggestion a suggestion to update the corresponding container definition
- * @throws CoreException when <code>JavaScriptCore#setJsGlobalScopeContainer</code> would throw any.
- * @see JavaScriptCore#setJsGlobalScopeContainer(IPath, IJavaScriptProject[], IJsGlobalScopeContainer[], org.eclipse.core.runtime.IProgressMonitor)
- * @see JsGlobalScopeContainerInitializer#canUpdateJsGlobalScopeContainer(IPath, IJavaScriptProject)
- */
- public abstract void requestJsGlobalScopeContainerUpdate(IPath containerPath, IJavaScriptProject project, IJsGlobalScopeContainer containerSuggestion)
- throws CoreException;
-
- /**
- * Returns a readable description for a container path. A readable description for a container path can be
- * used for improving the display of references to container, without actually needing to resolve them.
- * A good implementation should answer a description consistent with the description of the associated
- * target container (see <code>IJsGlobalScopeContainer.getDescription()</code>).
- *
- * @param containerPath the path of the container which requires a readable description
- * @param project the project from which the container is referenced
- * @return a string description of the container
- */
- public abstract String getDescription(IPath containerPath, IJavaScriptProject project);
-
- /**
- * Returns a includepath container that is used after this initializer failed to bind a includepath container
- * to a <code>IJsGlobalScopeContainer</code> for the given project. A non-<code>null</code>
- * failure container indicates that there will be no more request to initialize the given container
- * for the given project.
- * <p>
- * By default a non-<code>null</code> failure container with no includepath entries is returned.
- * Clients wishing to get a chance to run the initializer again should override this method
- * and return <code>null</code>.
- * </p>
- *
- * @param containerPath the path of the container which failed to initialize
- * @param project the project from which the container is referenced
- * @return the default failure container, or <code>null</code> if wishing to run the initializer again
- */
- public abstract IJsGlobalScopeContainer getFailureContainer(final IPath containerPath, IJavaScriptProject project);
-
- /**
- * Returns an object which identifies a container for comparison purpose. This allows
- * to eliminate redundant containers when accumulating includepath entries (e.g.
- * runtime includepath computation). When requesting a container comparison ID, one
- * should ensure using its corresponding container initializer. Indeed, a random container
- * initializer cannot be held responsible for determining comparison IDs for arbitrary
- * containers.
- * <p>
- * @param containerPath the path of the container which is being checked
- * @param project the project for which the container is to being checked
- * @return returns an Object identifying the container for comparison
- */
- public abstract Object getComparisonID(IPath containerPath, IJavaScriptProject project);
-
- public abstract URI getHostPath(IPath path, IJavaScriptProject project);
-
- LibraryLocation getLibraryLocation();
- /*
- * Returns if this library allows attachment of external JsDoc
- */
- boolean allowAttachJsDoc();
- /**
- * returns a String of all SuperTypes provided by this library.
- */
- String[] containerSuperTypes();
-
- /**
- * Get the id of the inference provider for this library
- * @return inference provider id
- */
- String getInferenceID();
-
- void removeFromProject(IJavaScriptProject project);
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ILocalVariable.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ILocalVariable.java
deleted file mode 100644
index 316d042a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ILocalVariable.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*******************************************************************************
- * 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;
-
-/**
- * Represents a local variable declared in a method..
- * <code>ILocalVariable</code> are pseudo-elements created as the result of a <code>ICodeAssist.codeSelect(...)</code>
- * operation. They are not part of the JavaScript model (<code>exists()</code> returns whether the parent exists rather than
- * whether the local variable exists in the parent) and they are not included in the children of an <code>IFunction</code>
- * or an <code>IInitializer</code>.
- * <p>
- * In particular such a pseudo-element should not be used as a handle. For example its name range won't be updated
- * if the underlying source changes.
- * </p><p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * 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 ILocalVariable extends IJavaScriptElement, ISourceReference {
-
- /**
- * Returns the name of this local variable.
- *
- * @return the name of this local variable.
- */
- String getElementName();
-
- /**
- * Returns the source range of this local variable's name.
- *
- * @return the source range of this local variable's name
- */
- ISourceRange getNameRange();
-
- /**
- * Returns the type signature of this local variable.
- * <p>
- * The type signature may be either unresolved (for source types)
- * or resolved (for binary types), and either basic (for basic types)
- * or rich (for parameterized types). See {@link Signature} for details.
- * </p>
- *
- * @return the type signature of this local variable.
- * @see Signature
- */
- String getTypeSignature();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ILookupScope.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ILookupScope.java
deleted file mode 100644
index 0abb85e2..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ILookupScope.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core;
-
-import org.eclipse.wst.jsdt.internal.core.NameLookup;
-import org.eclipse.wst.jsdt.internal.core.SearchableEnvironment;
-
-/**
- *
- * 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 ILookupScope {
- /*
- * Returns a new name lookup. This name lookup first looks in the given working copies.
- */
- public NameLookup newNameLookup(IJavaScriptUnit[] workingCopies) throws JavaScriptModelException;
-
- /*
- * Returns a new name lookup. This name lookup first looks in the working copies of the given owner.
- */
- public NameLookup newNameLookup(WorkingCopyOwner owner) throws JavaScriptModelException ;
-
- /*
- * Returns a new search name environment for this project. This name environment first looks in the given working copies.
- */
- public SearchableEnvironment newSearchableNameEnvironment(IJavaScriptUnit[] workingCopies) throws JavaScriptModelException ;
-
- /*
- * Returns a new search name environment for this project. This name environment first looks in the working copies
- * of the given owner.
- */
- public SearchableEnvironment newSearchableNameEnvironment(WorkingCopyOwner owner) throws JavaScriptModelException;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IMember.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IMember.java
deleted file mode 100644
index b308c528..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IMember.java
+++ /dev/null
@@ -1,156 +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.core;
-
-/**
- * Common protocol for JavaScript elements that can be members of javaScript files or types.
- * This set consists of <code>IType</code>, <code>IFunction</code>,
- * <code>IField</code>, and <code>IInitializer</code>.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * 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 IMember extends IJavaScriptElement, ISourceReference, ISourceManipulation, IParent {
-/**
- * Returns the categories defined by this member's JSDoc. A category is the identifier
- * following the tag <code>@category</code> in the member's JSDoc.
- * Returns an empty array if no category is defined in this member's JSDoc.
- *
- * @return the categories defined by this member's doc
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- */
-String[] getCategories() throws JavaScriptModelException;
-/*
- * Returns the class file in which this member is declared, or <code>null</code>
- * if this member is not declared in a class file (for example, a source type).
- * This is a handle-only method.
- *
- * @return the class file in which this member is declared, or <code>null</code>
- * if this member is not declared in a class file (for example, a source type)
- */
-IClassFile getClassFile();
-/**
- * Returns the javaScript unit in which this member is declared, or <code>null</code>
- * if this member is not declared in a javaScript unit.
- * This is a handle-only method.
- *
- * @return the javaScript unit in which this member is declared, or <code>null</code>
- * if this member is not declared in a javaScript unit (for example, a binary type)
- */
-IJavaScriptUnit getJavaScriptUnit();
-/**
- * Returns the type in which this member is declared, or <code>null</code>
- * if this member is not declared in a type (for example, a top-level type).
- * This is a handle-only method.
- *
- * @return the type in which this member is declared, or <code>null</code>
- * if this member is not declared in a type (for example, a top-level type)
- */
-IType getDeclaringType();
-/**
- * Returns the modifier flags for this member. The flags can be examined using class
- * <code>Flags</code>.
- * <p>
- * Note that only flags as indicated in the source are returned. Thus if an interface
- * defines a method <code>void myMethod();</code> the flags don't include the
- * 'public' flag.
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return the modifier flags for this member
- * @see Flags
- */
-int getFlags() throws JavaScriptModelException;
-/**
- * Returns the JSDoc range if this element is from source or if this element
- * is a binary element with an attached source, null otherwise.
- *
- * <p>If this element is from source, the jsdoc range is
- * extracted from the corresponding source.</p>
- * <p>If this element is from a binary, the jsdoc is extracted from the
- * attached source if present.</p>
- * <p>If this element's openable is not consistent, then null is returned.</p>
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return a source range corresponding to the jsdoc source or <code>null</code>
- * if no source is available, this element has no jsdoc comment or
- * this element's openable is not consistent
- * @see IOpenable#isConsistent()
- */
-ISourceRange getJSdocRange() throws JavaScriptModelException;
-/**
- * Returns the source range of this member's simple name,
- * or <code>null</code> if this member does not have a name
- * (for example, an initializer), or if this member does not have
- * associated source code (for example, a binary type).
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return the source range of this member's simple name,
- * or <code>null</code> if this member does not have a name
- * (for example, an initializer), or if this member does not have
- * associated source code (for example, a binary type)
- */
-ISourceRange getNameRange() throws JavaScriptModelException;
-/**
- * Returns the position relative to the order this member is defined in the source.
- * Numbering starts at 1 (thus the first occurrence is occurrence 1, not occurrence 0).
- * <p>
- * Two members m1 and m2 that are equal (e.g. 2 fields with the same name in
- * the same type) can be distinguished using their occurrence counts. If member
- * m1 appears first in the source, it will have an occurrence count of 1. If member
- * m2 appears right after member m1, it will have an occurrence count of 2.
- * </p><p>
- * The occurrence count can be used to distinguish initializers inside a type
- * or anonymous types inside a method.
- * </p><p>
- * This is a handle-only method. The member may or may not be present.
- * </p>
- *
- * @return the position relative to the order this member is defined in the source
- */
-int getOccurrenceCount();
-/**
- * Returns the JavaScript type root in which this member is declared.
- * This is a handle-only method.
- *
- * @return the JavaScript type root in which this member is declared.
- */
-ITypeRoot getTypeRoot();
-/**
- * Returns the local or anonymous type declared in this source member with the given simple name and/or
- * with the specified position relative to the order they are defined in the source.
- * The name is empty if it is an anonymous type.
- * Numbering starts at 1 (thus the first occurrence is occurrence 1, not occurrence 0).
- * This is a handle-only method. The type may or may not exist.
- * Throws a <code>RuntimeException</code> if this member is not a source member.
- *
- * @param name the given simple name
- * @param occurrenceCount the specified position
- * @return the type with the given name and/or with the specified position relative to the order they are defined in the source
- */
-IType getType(String name, int occurrenceCount);
-/**
- * Returns whether this member is from a non-editable file.
- * This is a handle-only method.
- *
- * @return <code>true</code> if from a non-editable file, and <code>false</code> if
- * from a javaScript unit
- */
-boolean isBinary();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IOpenable.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IOpenable.java
deleted file mode 100644
index 2b282860..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IOpenable.java
+++ /dev/null
@@ -1,193 +0,0 @@
-/*******************************************************************************
- * 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;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-
-/**
- * Common protocol for JavaScript elements that must be opened before they can be
- * navigated or modified. Opening a textual element (such as a javaScript file)
- * involves opening a buffer on its contents. While open, any changes to the buffer
- * can be reflected in the element's structure;
- * see {@link #isConsistent} and {@link #makeConsistent(IProgressMonitor)}.
- * <p>
- * To reduce complexity in clients, elements are automatically opened
- * by the JavaScript model as element properties are accessed. The JavaScript model maintains
- * an LRU cache of open elements, and automatically closes elements as they
- * are swapped out of the cache to make room for other elements. Elements with
- * unsaved changes are never removed from the cache, and thus, if the client
- * maintains many open elements with unsaved
- * changes, the LRU cache can grow in size (in this case the cache is not
- * bounded). However, as elements are saved, the cache will shrink back to its
- * original bounded size.
- * </p>
- * <p>
- * To open an element, all openable parent elements must be open.
- * The JavaScript model automatically opens parent elements, as it automatically opens elements.
- * Opening an element may provide access to direct children and other descendants,
- * but does not automatically open any descendents which are themselves {@link IOpenable}.
- * For example, opening a compilation unit provides access to all its constituent elements,
- * but opening a package fragment does not open all compilation units in the package fragment.
- * </p>
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * 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 IOpenable {
-
-/**
- * Closes this element and its buffer (if any).
- * Closing an element which is not open has no effect.
- *
- * <p>Note: although {@link #close} is exposed in the API, clients are
- * not expected to open and close elements - the JavaScript model does this automatically
- * as elements are accessed.
- *
- * @exception JavaScriptModelException if an error occurs closing this element
- */
-public void close() throws JavaScriptModelException;
-/**
- * Finds and returns the recommended line separator for this element.
- * The element's buffer is first searched and the first line separator in this buffer is returned if any.
- * Otherwise the preference {@link org.eclipse.core.runtime.Platform#PREF_LINE_SEPARATOR}
- * on this element's project or workspace is returned.
- * Finally if no such preference is set, the system line separator is returned.
- *
- * @return the recommended line separator for this element
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- */
-public String findRecommendedLineSeparator() throws JavaScriptModelException;
-/**
- * Returns the buffer opened for this element, or <code>null</code>
- * if this element does not have a buffer.
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return the buffer opened for this element, or <code>null</code>
- * if this element does not have a buffer
- */
-public IBuffer getBuffer() throws JavaScriptModelException;
-/**
- * Returns <code>true</code> if this element is open and:
- * <ul>
- * <li>its buffer has unsaved changes, or
- * <li>one of its descendants has unsaved changes, or
- * <li>a working copy has been created on one of this
- * element's children and has not yet destroyed
- * </ul>
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return <code>true</code> if this element is open and:
- * <ul>
- * <li>its buffer has unsaved changes, or
- * <li>one of its descendants has unsaved changes, or
- * <li>a working copy has been created on one of this
- * element's children and has not yet destroyed
- * </ul>
- */
-boolean hasUnsavedChanges() throws JavaScriptModelException;
-/**
- * Returns whether the element is consistent with its underlying resource or buffer.
- * The element is consistent when opened, and is consistent if the underlying resource
- * or buffer has not been modified since it was last consistent.
- *
- * <p>NOTE: Child consistency is not considered. For example, a package fragment
- * responds <code>true</code> when it knows about all of its
- * compilation units present in its underlying folder. However, one or more of
- * the compilation units could be inconsistent.
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return true if the element is consistent with its underlying resource or buffer, false otherwise.
- * @see IOpenable#makeConsistent(IProgressMonitor)
- */
-boolean isConsistent() throws JavaScriptModelException;
-/**
- * Returns whether this openable is open. This is a handle-only method.
- * @return true if this openable is open, false otherwise
- */
-boolean isOpen();
-/**
- * Makes this element consistent with its underlying resource or buffer
- * by updating the element's structure and properties as necessary.
- *<p>
- * Note: Using this functionality on a working copy will interfere with any
- * subsequent reconciling operation. Indeed, the next
- * {@link IJavaScriptUnit#reconcile(int, boolean, WorkingCopyOwner, IProgressMonitor)} or
- * {@link IJavaScriptUnit#reconcile(int, boolean, boolean, WorkingCopyOwner, IProgressMonitor)}
- * operation will not account for changes which occurred before an
- * explicit use of {@link #makeConsistent(IProgressMonitor)}
- * <p>
- * @param progress the given progress monitor
- * @exception JavaScriptModelException if the element is unable to access the contents
- * of its underlying resource. Reasons include:
- * <ul>
- * <li>This JavaScript element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * </ul>
- * @see IOpenable#isConsistent()
- * @see IJavaScriptUnit#reconcile(int, boolean, WorkingCopyOwner, IProgressMonitor)
- */
-void makeConsistent(IProgressMonitor progress) throws JavaScriptModelException;
-/**
- * Opens this element and all parent elements that are not already open.
- * For compilation units, a buffer is opened on the contents of the underlying resource.
- *
- * <p>Note: although {@link #open} is exposed in the API, clients are
- * not expected to open and close elements - the JavaScript model does this automatically
- * as elements are accessed.
- *
- * @param progress the given progress monitor
- * @exception JavaScriptModelException if an error occurs accessing the contents
- * of its underlying resource. Reasons include:
- * <ul>
- * <li>This JavaScript element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * </ul>
- */
-public void open(IProgressMonitor progress) throws JavaScriptModelException;
-/**
- * Saves any changes in this element's buffer to its underlying resource
- * via a workspace resource operation. This has no effect if the element has no underlying
- * buffer, or if there are no unsaved changed in the buffer.
- * <p>
- * The <code>force</code> parameter controls how this method deals with
- * cases where the workbench is not completely in sync with the local file system.
- * If <code>false</code> is specified, this method will only attempt
- * to overwrite a corresponding file in the local file system provided
- * it is in sync with the workbench. This option ensures there is no
- * unintended data loss; it is the recommended setting.
- * However, if <code>true</code> is specified, an attempt will be made
- * to write a corresponding file in the local file system,
- * overwriting any existing one if need be.
- * In either case, if this method succeeds, the resource will be marked
- * as being local (even if it wasn't before).
- * <p>
- * As a result of this operation, the element is consistent with its underlying
- * resource or buffer.
- *
- * @param progress the given progress monitor
- * @param force it controls how this method deals with
- * cases where the workbench is not completely in sync with the local file system
- * @exception JavaScriptModelException if an error occurs accessing the contents
- * of its underlying resource. Reasons include:
- * <ul>
- * <li>This JavaScript element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li>This JavaScript element is read-only (READ_ONLY)</li>
- * </ul>
- */
-public void save(IProgressMonitor progress, boolean force) throws JavaScriptModelException;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IPackageFragment.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IPackageFragment.java
deleted file mode 100644
index edfd33bf..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IPackageFragment.java
+++ /dev/null
@@ -1,202 +0,0 @@
-/*******************************************************************************
- * 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;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-
-/**
- * A package fragment (or source folder) is a portion of the workspace corresponding to an entire package,
- * or to a portion thereof. The distinction between a package fragment and a package
- * is that a package with some name is the union of all package fragments in the includepath
- * which have the same name.
- * <p>
- * Package fragments elements need to be opened before they can be navigated or manipulated.
- * The children are of type <code>IJavaScriptUnit</code> (representing a source file) or
- * <code>IClassFile</code> (representing a read-only file).
- * The children are listed in no particular order.
- * </p>
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * 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 IPackageFragment extends IParent, IJavaScriptElement, IOpenable, ISourceManipulation {
-
- /**
- * <p>
- * The name of package fragment for the default package (value: the empty
- * string, <code>""</code>).
- * </p>
- */
- public static final String DEFAULT_PACKAGE_NAME = ""; //$NON-NLS-1$
- /**
- * Returns whether this fragment contains at least one JavaScript resource.
- * @return true if this fragment contains at least one JavaScript resource, false otherwise
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- */
- boolean containsJavaResources() throws JavaScriptModelException;
- /**
- * Creates and returns a javaScript unit in this package fragment
- * with the specified name and contents. No verification is performed
- * on the contents.
- *
- * <p>It is possible that a javaScript unit with the same name already exists in this
- * package fragment.
- * The value of the <code>force</code> parameter effects the resolution of
- * such a conflict:<ul>
- * <li> <code>true</code> - in this case the compilation is created with the new contents</li>
- * <li> <code>false</code> - in this case a <code>JavaScriptModelException</code> is thrown</li>
- * </ul>
- *
- * @param contents the given contents
- * @param force specify how to handle conflict is the same name already exists
- * @param monitor the given progress monitor
- * @param name the given name
- * @exception JavaScriptModelException if the element could not be created. Reasons include:
- * <ul>
- * <li> This JavaScript element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while creating an underlying resource
- * <li> The name is not a valid javaScript unit name (INVALID_NAME)
- * <li> The contents are <code>null</code> (INVALID_CONTENTS)
- * </ul>
- * @return a javaScript unit in this package fragment
- * with the specified name and contents
- */
- IJavaScriptUnit createCompilationUnit(String name, String contents, boolean force, IProgressMonitor monitor) throws JavaScriptModelException;
- /**
- * Returns the non-editable file with the specified name
- * in this folder .
- * This is a handle-only method. The file may or may not be present.
- * @param name the given name
- * @return the file with the specified name in this package
- */
- IClassFile getClassFile(String name);
- /**
- * Returns all of the non-editable files in this source folder.
- *
- * <p>Note: it is possible that a package fragment contains only
- * javaScript units (in other words, its kind is <code>K_SOURCE</code>), in
- * which case this method returns an empty collection.
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return all of the files in this source folder
- */
- IClassFile[] getClassFiles() throws JavaScriptModelException;
- /**
- * Returns the javaScript unit with the specified name
- * in this package (for example, <code>"Object.js"</code>).
- * The name has to be a valid javaScript unit name.
- * This is a handle-only method. The javaScript unit may or may not be present.
- *
- * @param name the given name
- * @return the javaScript unit with the specified name in this package
- * @see JavaScriptConventions#validateCompilationUnitName(String name, String sourceLevel, String complianceLevel)
- */
- IJavaScriptUnit getJavaScriptUnit(String name);
- /**
- * Returns all of the javaScript units in this source folder.
- *
- * <p>Note: it is possible that a source folder contains only
- * read-only files (in other words, its kind is <code>K_BINARY</code>), in which
- * case this method returns an empty collection.
- * </p>
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return all of the javaScript units in this source folder
- */
- IJavaScriptUnit[] getJavaScriptUnits() throws JavaScriptModelException;
- /**
- * Returns all of the javaScript units in this source folder that are
- * in working copy mode and that have the given owner.
- * <p>
- * Only existing working copies are returned. So a javaScript unit handle that has no
- * corresponding resource on disk will be included if and only if is in working copy mode.
- * </p>
- * <p>Note: it is possible that a source folder contains only
- * read-only files (in other words, its kind is <code>K_BINARY</code>), in which
- * case this method returns an empty collection.
- * </p>
- *
- * @param owner the owner of the returned javaScript units
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return all of the javaScript units in this source folder
- */
- IJavaScriptUnit[] getJavaScriptUnits(WorkingCopyOwner owner) throws JavaScriptModelException;
- /**
- * Returns the dot-separated package name of this fragment, for example
- * <code>"java.lang"</code>, or <code>""</code> (the empty string),
- * for the default package.
- *
- * @return the dot-separated package name of this fragment
- */
- String getElementName();
- /**
- * Returns this package fragment's root kind encoded as an integer.
- * A package fragment can contain source files (i.e. files with one of
- * the {@link JavaScriptCore#getJavaScriptLikeExtensions() JavaScript-like extensions}),
- * or <code>.class</code> files. This is a convenience method.
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return this package fragment's root kind encoded as an integer
- * @see IPackageFragmentRoot#K_SOURCE
- * @see IPackageFragmentRoot#K_BINARY
- */
- int getKind() throws JavaScriptModelException;
- /**
- * Returns an array of non-JavaScript resources contained in this source folder.
- * <p>
- * Non-JavaScript resources includes other files and folders located in the same
- * directory as the javaScript units for this package
- * fragment. Source files excluded from this package by virtue of
- * inclusion/exclusion patterns on the corresponding source includepath entry
- * are considered non-JavaScript resources and will appear in the result
- * (possibly in a folder).
- * </p>
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return an array of non-JavaScript resources (<code>IFile</code>s,
- * <code>IFolder</code>s, or <code>IStorage</code>s if the
- * package fragment is in an archive) contained in this package
- * fragment
- * @see IIncludePathEntry#getInclusionPatterns()
- * @see IIncludePathEntry#getExclusionPatterns()
- */
- Object[] getNonJavaScriptResources() throws JavaScriptModelException;
- /**
- * Returns whether this package fragment's name is
- * a prefix of other package fragments in this package fragment's
- * root.
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return true if this package fragment's name is a prefix of other package fragments in this package fragment's root, false otherwise
- */
- boolean hasSubpackages() throws JavaScriptModelException;
- /**
- * Returns whether this package fragment is a default package.
- * This is a handle-only method.
- *
- * @return true if this package fragment is a default package
- */
- boolean isDefaultPackage();
-
- boolean isSource();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IPackageFragmentRoot.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IPackageFragmentRoot.java
deleted file mode 100644
index 16790491..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IPackageFragmentRoot.java
+++ /dev/null
@@ -1,432 +0,0 @@
-/*******************************************************************************
- * 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
- * IBM Corporation - specified that a source archive or a source folder can be attached to a binary
- * package fragment root.
- * IBM Corporation - added root manipulation APIs: copy, delete, move
- * IBM Corporation - added DESTINATION_PROJECT_INCLUDEPATH
- * IBM Corporation - added OTHER_REFERRING_PROJECTS_INCLUDEPATH
- * IBM Corporation - added NO_RESOURCE_MODIFICATION
- * IBM Corporation - added REPLACE
- * IBM Corporation - added ORIGINATING_PROJECT_INCLUDEPATH
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core;
-
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-
-/**
- * A package fragment root (or source folder root) contains a set of source folders (package fragments).
- * It corresponds to an underlying resource which is either folder. All descendant folders represent
- * package fragments. For a given child folder representing a package fragment,
- * the corresponding package name is composed of the folder names between the folder
- * for this root and the child folder representing the package, separated by '.'.
- * Package fragment roots need to be opened before they can be navigated or manipulated.
- * The children are of type <code>IPackageFragment</code>, and are in no particular order.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * 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 IPackageFragmentRoot
- extends IParent, IJavaScriptElement, IOpenable {
- /**
- * Kind constant for a source path root. Indicates this root
- * only contains source files.
- */
- int K_SOURCE = 1;
- /**
- * Kind constant for a binary path root. Indicates this
- * root only contains binary (non-editable) files.
- */
- int K_BINARY = 2;
- /**
- * Empty root path
- */
- String DEFAULT_PACKAGEROOT_PATH = ""; //$NON-NLS-1$
- /**
- * Update model flag constant (bit mask value 1) indicating that the operation
- * is to not copy/move/delete the package fragment root resource.
- */
- int NO_RESOURCE_MODIFICATION = 1;
- /**
- * Update model flag constant (bit mask value 2) indicating that the operation
- * is to update the includepath of the originating project.
- */
- int ORIGINATING_PROJECT_INCLUDEPATH = 2;
- /**
- * Update model flag constant (bit mask value 4) indicating that the operation
- * is to update the includepath of all referring projects except the originating project.
- */
- int OTHER_REFERRING_PROJECTS_INCLUDEPATH = 4;
- /**
- * Update model flag constant (bit mask value 8) indicating that the operation
- * is to update the includepath of the destination project.
- */
- int DESTINATION_PROJECT_INCLUDEPATH = 8;
- /**
- * Update model flag constant (bit mask value 16) indicating that the operation
- * is to replace the resource and the destination project's includepath entry.
- */
- int REPLACE = 16;
- /*
- * Attaches the source archive identified by the given absolute path to this
- * binary package fragment root. <code>rootPath</code> specifies the location
- * of the root within the archive or folder (empty specifies the default root
- * and <code>null</code> specifies the root path should be detected).
- * Once a source archive or folder is attached to the package fragment root,
- * the <code>getSource</code> and <code>getSourceRange</code>
- * methods become operational for binary types/members.
- * To detach a source archive or folder from a package fragment root, specify
- * <code>null</code> as the source path.
- *
- * @param sourcePath the given absolute path to the source archive or folder
- * @param rootPath specifies the location of the root within the archive
- * (empty specifies the default root and <code>null</code> specifies
- * automatic detection of the root path)
- * @param monitor the given progress monitor
- * @exception JavaScriptModelException if this operation fails. Reasons include:
- * <ul>
- * <li> This JavaScript element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while updating a server property
- * <li> This package fragment root is not of kind binary (INVALID_ELEMENT_TYPES)
- * <li> The path provided is not absolute (RELATIVE_PATH)
- * </ul>
- */
- void attachSource(IPath sourcePath, IPath rootPath, IProgressMonitor monitor)
- throws JavaScriptModelException;
-
- /**
- * Copies the resource of this package fragment root to the destination path
- * as specified by <code>IResource.copy(IPath, int, IProgressMonitor)</code>
- * but excluding nested source folders.
- * <p>
- * If <code>NO_RESOURCE_MODIFICATION</code> is specified in
- * <code>updateModelFlags</code> or if this package fragment root is external,
- * this operation doesn't copy the resource. <code>updateResourceFlags</code>
- * is then ignored.
- * </p><p>
- * If <code>DESTINATION_PROJECT_INCLUDEPATH</code> is specified in
- * <code>updateModelFlags</code>, updates the includepath of the
- * destination's project (if it is a JavaScript project). If a non-<code>null</code>
- * sibling is specified, a copy of this root's includepath entry is inserted before the
- * sibling on the destination project's raw includepath. If <code>null</code> is
- * specified, the includepath entry is added at the end of the raw includepath.
- * </p><p>
- * If <code>REPLACE</code> is specified in <code>updateModelFlags</code>,
- * overwrites the resource at the destination path if any.
- * If the same includepath entry already exists on the destination project's raw
- * includepath, then the sibling is ignored and the new includepath entry replaces the
- * existing one.
- * </p><p>
- * If no flags is specified in <code>updateModelFlags</code> (using
- * <code>IResource.NONE</code>), the default behavior applies: the
- * resource is copied (if this package fragment root is not external) and the
- * includepath is not updated.
- * </p>
- *
- * @param destination the destination path
- * @param updateResourceFlags bit-wise or of update resource flag constants
- * (<code>IResource.FORCE</code> and <code>IResource.SHALLOW</code>)
- * @param updateModelFlags bit-wise or of update resource flag constants
- * (<code>DESTINATION_PROJECT_INCLUDEPATH</code> and
- * <code>NO_RESOURCE_MODIFICATION</code>)
- * @param sibling the includepath entry before which a copy of the includepath
- * entry should be inserted or <code>null</code> if the includepath entry should
- * be inserted at the end
- * @param monitor a progress monitor
- *
- * @exception JavaScriptModelException if this root could not be copied. Reasons
- * include:
- * <ul>
- * <li> This root does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while copying the
- * resource or updating a includepath</li>
- * <li>
- * The destination is not inside an existing project and <code>updateModelFlags</code>
- * has been specified as <code>DESTINATION_PROJECT_INCLUDEPATH</code>
- * (INVALID_DESTINATION)</li>
- * <li> The sibling is not a includepath entry on the destination project's
- * raw includepath (INVALID_SIBLING)</li>
- * <li> The same includepath entry already exists on the destination project's
- * includepath (NAME_COLLISION) and <code>updateModelFlags</code>
- * has not been specified as <code>REPLACE</code></li>
- * </ul>
- * @see org.eclipse.core.resources.IResource#copy(IPath, boolean, IProgressMonitor)
- */
- void copy(IPath destination, int updateResourceFlags, int updateModelFlags, IIncludePathEntry sibling, IProgressMonitor monitor) throws JavaScriptModelException;
- /**
- * Creates and returns a package fragment in this root with the
- * given dot-separated package name. An empty string specifies the default package.
- * This has the side effect of creating all package
- * fragments that are a prefix of the new package fragment which
- * do not exist yet. If the package fragment already exists, this
- * has no effect.
- *
- * For a description of the <code>force</code> flag, see <code>IFolder.create</code>.
- *
- * @param name the given dot-separated package name
- * @param force a flag controlling how to deal with resources that
- * are not in sync with the local file system
- * @param monitor the given progress monitor
- * @exception JavaScriptModelException if the element could not be created. Reasons include:
- * <ul>
- * <li> This JavaScript element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while creating an underlying resource
- * <li> This package fragment root is read only (READ_ONLY)
- * <li> The name is not a valid package name (INVALID_NAME)
- * </ul>
- * @return a package fragment in this root with the given dot-separated package name
- * @see org.eclipse.core.resources.IFolder#create(boolean, boolean, IProgressMonitor)
- */
- IPackageFragment createPackageFragment(
- String name,
- boolean force,
- IProgressMonitor monitor)
- throws JavaScriptModelException;
- /**
- * Deletes the resource of this package fragment root as specified by
- * <code>IResource.delete(int, IProgressMonitor)</code> but excluding nested
- * source folders.
- * <p>
- * If <code>NO_RESOURCE_MODIFICATION</code> is specified in
- * <code>updateModelFlags</code> or if this package fragment root is external,
- * this operation doesn't delete the resource. <code>updateResourceFlags</code>
- * is then ignored.
- * </p><p>
- * If <code>ORIGINATING_PROJECT_INCLUDEPATH</code> is specified in
- * <code>updateModelFlags</code>, update the raw includepath of this package
- * fragment root's project by removing the corresponding includepath entry.
- * </p><p>
- * If <code>OTHER_REFERRING_PROJECTS_INCLUDEPATH</code> is specified in
- * <code>updateModelFlags</code>, update the raw includepaths of all other JavaScript
- * projects referring to this root's resource by removing the corresponding includepath
- * entries.
- * </p><p>
- * If no flags is specified in <code>updateModelFlags</code> (using
- * <code>IResource.NONE</code>), the default behavior applies: the
- * resource is deleted (if this package fragment root is not external) and no
- * includepaths are updated.
- * </p>
- *
- * @param updateResourceFlags bit-wise or of update resource flag constants
- * (<code>IResource.FORCE</code> and <code>IResource.KEEP_HISTORY</code>)
- * @param updateModelFlags bit-wise or of update resource flag constants
- * (<code>ORIGINATING_PROJECT_INCLUDEPATH</code>,
- * <code>OTHER_REFERRING_PROJECTS_INCLUDEPATH</code> and
- * <code>NO_RESOURCE_MODIFICATION</code>)
- * @param monitor a progress monitor
- *
- * @exception JavaScriptModelException if this root could not be deleted. Reasons
- * include:
- * <ul>
- * <li> This root does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while deleting the resource
- * or updating a includepath
- * </li>
- * </ul>
- * @see org.eclipse.core.resources.IResource#delete(boolean, IProgressMonitor)
- */
- void delete(int updateResourceFlags, int updateModelFlags, IProgressMonitor monitor) throws JavaScriptModelException;
- /**
- * Returns this package fragment root's kind encoded as an integer.
- * A package fragment root can contain source files (i.e. files with one
- * of the {@link JavaScriptCore#getJavaScriptLikeExtensions() JavaScript-like extensions},
- * or <code>.class</code> files, but not both.
- * If the underlying folder or archive contains other kinds of files, they are ignored.
- * In particular, <code>.class</code> files are ignored under a source package fragment root,
- * and source files are ignored under a binary package fragment root.
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return this package fragment root's kind encoded as an integer
- * @see IPackageFragmentRoot#K_SOURCE
- * @see IPackageFragmentRoot#K_BINARY
- */
- int getKind() throws JavaScriptModelException;
-
- /**
- * Returns an array of non-JavaScript resources contained in this package fragment root.
- * <p>
- * Non-JavaScript resources includes other files and folders located in the same
- * directories as the compilation units or class files under this package
- * fragment root. Resources excluded from this package fragment root
- * by virtue of inclusion/exclusion patterns on the corresponding source includepath
- * entry are considered non-JavaScript resources and will appear in the result
- * (possibly in a folder). Thus when a nested source folder is excluded, it will appear
- * in the non-JavaScript resources of the outer folder.
- * </p>
- * @return an array of non-JavaScript resources (<code>IFile</code>s,
- * <code>IFolder</code>s, or <code>IStorage</code>s if the
- * package fragment root is in archive) contained in this package
- * fragment root
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @see IIncludePathEntry#getInclusionPatterns()
- * @see IIncludePathEntry#getExclusionPatterns()
- */
- Object[] getNonJavaScriptResources() throws JavaScriptModelException;
-
- /**
- * Returns the package fragment with the given package name.
- * An empty string indicates the default package.
- * This is a handle-only operation. The package fragment
- * may or may not exist.
- *
- * @param packageName the given package name
- * @return the package fragment with the given package name
- */
- IPackageFragment getPackageFragment(String packageName);
-
-
- /**
- * Returns the first raw includepath entry that corresponds to this package
- * fragment root.
- * A raw includepath entry corresponds to a package fragment root if once resolved
- * this entry's path is equal to the root's path.
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return the first raw includepath entry that corresponds to this package fragment root
- */
- IIncludePathEntry getRawIncludepathEntry() throws JavaScriptModelException;
-
- /**
- * Returns the absolute path to the source archive attached to
- * this package fragment root's binary archive.
- *
- * @return the absolute path to the corresponding source archive,
- * or <code>null</code> if this package fragment root's binary archive
- * has no corresponding source archive, or if this package fragment root
- * is not a binary archive
- * @exception JavaScriptModelException if this operation fails
- */
- IPath getSourceAttachmentPath() throws JavaScriptModelException;
-
- /**
- * Returns the path within this package fragment root's source archive.
- * An empty path indicates that packages are located at the root of the
- * source archive.
- *
- * @return the path within the corresponding source archive,
- * or <code>null</code> if this package fragment root's binary archive
- * has no corresponding source archive, or if this package fragment root
- * is not a binary archive
- * @exception JavaScriptModelException if this operation fails
- */
- IPath getSourceAttachmentRootPath() throws JavaScriptModelException;
-
- /**
- * Returns whether this package fragment root's underlying
- * resource is a binary archive (a JAR or zip file).
- * <p>
- * This is a handle-only method.
- * </p>
- *
- * @return true if this package fragment root's underlying resource is a binary archive, false otherwise
- */
- public boolean isArchive();
-
- public boolean isLanguageRuntime();
- /**
- * Returns whether this package fragment root is external
- * to the workbench (that is, a local file), and has no
- * underlying resource.
- * <p>
- * This is a handle-only method.
- * </p>
- *
- * @return true if this package fragment root is external
- * to the workbench (that is, a local file), and has no
- * underlying resource, false otherwise
- */
- boolean isExternal();
-
- /**
- * Moves the resource of this package fragment root to the destination path
- * as specified by <code>IResource.move(IPath,int,IProgressMonitor)</code>
- * but excluding nested source folders.
- * <p>
- * If <code>NO_RESOURCE_MODIFICATION</code> is specified in
- * <code>updateModelFlags</code> or if this package fragment root is external,
- * this operation doesn't move the resource. <code>updateResourceFlags</code>
- * is then ignored.
- * </p><p>
- * If <code>DESTINATION_PROJECT_INCLUDEPATH</code> is specified in
- * <code>updateModelFlags</code>, updates the includepath of the
- * destination's project (if it is a JavaScript project). If a non-<code>null</code>
- * sibling is specified, a copy of this root's includepath entry is inserted before the
- * sibling on the destination project's raw includepath. If <code>null</code> is
- * specified, the includepath entry is added at the end of the raw includepath.
- * </p><p>
- * If <code>ORIGINATING_PROJECT_INCLUDEPATH</code> is specified in
- * <code>updateModelFlags</code>, update the raw includepath of this package
- * fragment root's project by removing the corresponding includepath entry.
- * </p><p>
- * If <code>OTHER_REFERRING_PROJECTS_INCLUDEPATH</code> is specified in
- * <code>updateModelFlags</code>, update the raw includepaths of all other JavaScript
- * projects referring to this root's resource by removing the corresponding includepath
- * entries.
- * </p><p>
- * If <code>REPLACE</code> is specified in <code>updateModelFlags</code>,
- * overwrites the resource at the destination path if any.
- * If the same includepath entry already exists on the destination project's raw
- * includepath, then the sibling is ignored and the new includepath entry replaces the
- * existing one.
- * </p><p>
- * If no flags is specified in <code>updateModelFlags</code> (using
- * <code>IResource.NONE</code>), the default behavior applies: the
- * resource is moved (if this package fragment root is not external) and no
- * includepaths are updated.
- * </p>
- *
- * @param destination the destination path
- * @param updateResourceFlags bit-wise or of update flag constants
- * (<code>IResource.FORCE</code>, <code>IResource.KEEP_HISTORY</code>
- * and <code>IResource.SHALLOW</code>)
- * @param updateModelFlags bit-wise or of update resource flag constants
- * (<code>DESTINATION_PROJECT_INCLUDEPATH</code>,
- * <code>ORIGINATING_PROJECT_INCLUDEPATH</code>,
- * <code>OTHER_REFERRING_PROJECTS_INCLUDEPATH</code> and
- * <code>NO_RESOURCE_MODIFICATION</code>)
- * @param sibling the includepath entry before which a copy of the includepath
- * entry should be inserted or <code>null</code> if the includepath entry should
- * be inserted at the end
- * @param monitor a progress monitor
- *
- * @exception JavaScriptModelException if this root could not be moved. Reasons
- * include:
- * <ul>
- * <li> This root does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while copying the
- * resource or updating a includepath</li>
- * <li>
- * The destination is not inside an existing project and <code>updateModelFlags</code>
- * has been specified as <code>DESTINATION_PROJECT_INCLUDEPATH</code>
- * (INVALID_DESTINATION)</li>
- * <li> The sibling is not a includepath entry on the destination project's
- * raw includepath (INVALID_SIBLING)</li>
- * <li> The same includepath entry already exists on the destination project's
- * includepath (NAME_COLLISION) and <code>updateModelFlags</code>
- * has not been specified as <code>REPLACE</code></li>
- * </ul>
- * @see org.eclipse.core.resources.IResource#move(IPath, boolean, IProgressMonitor)
- */
- void move(IPath destination, int updateResourceFlags, int updateModelFlags, IIncludePathEntry sibling, IProgressMonitor monitor) throws JavaScriptModelException;
-
- public IIncludePathAttribute[] getIncludepathAttributes();
-
- public IIncludePathEntry getResolvedIncludepathEntry() throws JavaScriptModelException;
-
- public boolean isLibrary();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IParent.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IParent.java
deleted file mode 100644
index dfd7622f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IParent.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*******************************************************************************
- * 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;
-
-/**
- * Common protocol for JavaScript elements that contain other JavaScript elements.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * 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 IParent {
-/**
- * Returns the immediate children of this element.
- * Unless otherwise specified by the implementing element,
- * the children are in no particular order.
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- * @return the immediate children of this element
- */
-IJavaScriptElement[] getChildren() throws JavaScriptModelException;
-/**
- * Returns whether this element has one or more immediate children.
- * This is a convenience method, and may be more efficient than
- * testing whether <code>getChildren</code> is an empty array.
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- * @return true if the immediate children of this element, false otherwise
- */
-boolean hasChildren() throws JavaScriptModelException;
-}
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
deleted file mode 100644
index 41ca4c91..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IProblemRequestor.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*******************************************************************************
- * 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;
-
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-
-/**
- * A callback interface for receiving javaScript problem as they are discovered
- * by some JavaScript operation.
- *
- * @see IProblem
- *
- * 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 IProblemRequestor {
-
- /**
- * Notification of a JavaScript problem.
- *
- * @param problem IProblem - The discovered JavaScript problem.
- */
- void acceptProblem(IProblem problem);
-
- /**
- * Notification sent before starting the problem detection process.
- * Typically, this would tell a problem collector to clear previously recorded problems.
- */
- void beginReporting();
-
- /**
- * Notification sent after having completed problem detection process.
- * Typically, this would tell a problem collector that no more problems should be expected in this
- * iteration.
- */
- void endReporting();
-
- /**
- * Predicate allowing the problem requestor to signal whether or not it is currently
- * interested by problem reports. When answering <code>false</code>, problem will
- * not be discovered any more until the next iteration.
- *
- * This predicate will be invoked once prior to each problem detection iteration.
- *
- * @return boolean - indicates whether the requestor is currently interested by problems.
- */
- boolean isActive();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IRegion.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IRegion.java
deleted file mode 100644
index 71646520..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IRegion.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*******************************************************************************
- * 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;
-
-/**
- * A JavaScript model region describes a hierarchical set of elements.
- * Regions are often used to describe a set of elements to be considered
- * when performing operations; for example, the set of elements to be
- * considered during a search. A region may include elements from different
- * projects.
- * <p>
- * When an element is included in a region, all of its children
- * are considered to be included. Children of an included element
- * <b>cannot</b> be selectively excluded.
- * </p>
- * <p>
- * This interface is not intended to be implemented by clients.
- * Instances can be created via the <code>JavaScriptCore.newRegion</code>.
- * </p>
- *
- * @see JavaScriptCore#newRegion()
- *
- * 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 IRegion {
- /**
- * Adds the given element and all of its descendents to this region.
- * If the specified element is already included, or one of its
- * ancestors is already included, this has no effect. If the element
- * being added is an ancestor of an element already contained in this
- * region, the ancestor subsumes the descendent.
- *
- * @param element the given element
- */
- void add(IJavaScriptElement element);
- /**
- * Returns whether the given element is contained in this region.
- *
- * @param element the given element
- * @return true if the given element is contained in this region, false otherwise
- */
- boolean contains(IJavaScriptElement element);
- /**
- * Returns the top level elements in this region.
- * All descendents of these elements are also included in this region.
- *
- * @return the top level elements in this region
- */
- IJavaScriptElement[] getElements();
- /**
- * Removes the specified element from the region and returns
- * <code>true</code> if successful, <code>false</code> if the remove
- * fails. If an ancestor of the given element is included, the
- * remove fails (in other words, it is not possible to selectively
- * exclude descendants of included ancestors).
- *
- * @param element the given element
- * @return <code>true</code> if successful, <code>false</code> if the remove fails
- */
- boolean remove(IJavaScriptElement element);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ISourceManipulation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ISourceManipulation.java
deleted file mode 100644
index 2a237bd6..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ISourceManipulation.java
+++ /dev/null
@@ -1,118 +0,0 @@
-/*******************************************************************************
- * 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;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-
-/**
- * Common protocol for JavaScript elements that support source code manipulations such
- * as copy, move, rename, and delete.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * 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 ISourceManipulation {
-/**
- * Copies this element to the given container.
- *
- * @param container the container
- * @param sibling the sibling element before which the copy should be inserted,
- * or <code>null</code> if the copy should be inserted as the last child of
- * the container
- * @param rename the new name for the element, or <code>null</code> if the copy
- * retains the name of this element
- * @param replace <code>true</code> if any existing child in the container with
- * the target name should be replaced, and <code>false</code> to throw an
- * exception in the event of a name collision
- * @param monitor a progress monitor
- * @exception JavaScriptModelException if this element could not be copied. Reasons include:
- * <ul>
- * <li> This JavaScript element, container element, or sibling does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while updating an underlying resource
- * <li> The container is of an incompatible type (INVALID_DESTINATION)
- * <li> The sibling is not a child of the given container (INVALID_SIBLING)
- * <li> The new name is invalid (INVALID_NAME)
- * <li> A child in the container already exists with the same name (NAME_COLLISION)
- * and <code>replace</code> has been specified as <code>false</code>
- * <li> The container or this element is read-only (READ_ONLY)
- * </ul>
- *
- * @exception IllegalArgumentException if container is <code>null</code>
- */
-void copy(IJavaScriptElement container, IJavaScriptElement sibling, String rename, boolean replace, IProgressMonitor monitor) throws JavaScriptModelException;
-/**
- * Deletes this element, forcing if specified and necessary.
- *
- * @param force a flag controlling whether underlying resources that are not
- * in sync with the local file system will be tolerated (same as the force flag
- * in IResource operations).
- * @param monitor a progress monitor
- * @exception JavaScriptModelException if this element could not be deleted. Reasons include:
- * <ul>
- * <li> This JavaScript element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while updating an underlying resource (CORE_EXCEPTION)</li>
- * <li> This element is read-only (READ_ONLY)</li>
- * </ul>
- */
-void delete(boolean force, IProgressMonitor monitor) throws JavaScriptModelException;
-/**
- * Moves this element to the given container.
- *
- * @param container the container
- * @param sibling the sibling element before which the element should be inserted,
- * or <code>null</code> if the element should be inserted as the last child of
- * the container
- * @param rename the new name for the element, or <code>null</code> if the
- * element retains its name
- * @param replace <code>true</code> if any existing child in the container with
- * the target name should be replaced, and <code>false</code> to throw an
- * exception in the event of a name collision
- * @param monitor a progress monitor
- * @exception JavaScriptModelException if this element could not be moved. Reasons include:
- * <ul>
- * <li> This JavaScript element, container element, or sibling does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while updating an underlying resource
- * <li> The container is of an incompatible type (INVALID_DESTINATION)
- * <li> The sibling is not a child of the given container (INVALID_SIBLING)
- * <li> The new name is invalid (INVALID_NAME)
- * <li> A child in the container already exists with the same name (NAME_COLLISION)
- * and <code>replace</code> has been specified as <code>false</code>
- * <li> The container or this element is read-only (READ_ONLY)
- * </ul>
- *
- * @exception IllegalArgumentException if container is <code>null</code>
- */
-void move(IJavaScriptElement container, IJavaScriptElement sibling, String rename, boolean replace, IProgressMonitor monitor) throws JavaScriptModelException;
-/**
- * Renames this element to the given name.
- *
- * @param name the new name for the element
- * @param replace <code>true</code> if any existing element with the target name
- * should be replaced, and <code>false</code> to throw an exception in the
- * event of a name collision
- * @param monitor a progress monitor
- * @exception JavaScriptModelException if this element could not be renamed. Reasons include:
- * <ul>
- * <li> This JavaScript element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while updating an underlying resource
- * <li> The new name is invalid (INVALID_NAME)
- * <li> A child in the container already exists with the same name (NAME_COLLISION)
- * and <code>replace</code> has been specified as <code>false</code>
- * <li> This element is read-only (READ_ONLY)
- * </ul>
- */
-void rename(String name, boolean replace, IProgressMonitor monitor) throws JavaScriptModelException;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ISourceRange.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ISourceRange.java
deleted file mode 100644
index cfe0677d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ISourceRange.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core;
-
-/**
- * A source range defines an element's source coordinates relative to
- * its source buffer.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * 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 ISourceRange {
-
-/**
- * Returns the number of characters of the source code for this element,
- * relative to the source buffer in which this element is contained.
- *
- * @return the number of characters of the source code for this element,
- * relative to the source buffer in which this element is contained
- */
-int getLength();
-/**
- * Returns the 0-based index of the first character of the source code for this element,
- * relative to the source buffer in which this element is contained.
- *
- * @return the 0-based index of the first character of the source code for this element,
- * relative to the source buffer in which this element is contained
- */
-int getOffset();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ISourceReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ISourceReference.java
deleted file mode 100644
index 7f84bad9..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ISourceReference.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*******************************************************************************
- * 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;
-
-/**
- * Common protocol for JavaScript elements that have associated source code.
- * This set consists of <code>IClassFile</code>, <code>IJavaScriptUnit</code>,
- * <code>IPackageDeclaration</code>, <code>IImportDeclaration</code>,
- * <code>IImportContainer</code>, <code>IType</code>, <code>IField</code>,
- * <code>IFunction</code>, and <code>IInitializer</code>.
- * <p>
- * Source reference elements may be working copies if they were created from
- * a compilation unit that is a working copy.
- * </p>
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * @see IPackageFragmentRoot#attachSource(org.eclipse.core.runtime.IPath, org.eclipse.core.runtime.IPath, org.eclipse.core.runtime.IProgressMonitor)
- *
- * 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 ISourceReference {
-/**
- * Returns whether this element exists in the model.
- *
- * @return <code>true</code> if this element exists in the JavaScript model
- */
-boolean exists();
-
-/**
- * Returns the source code associated with this element.
- * This extracts the substring from the source buffer containing this source
- * element. This corresponds to the source range that would be returned by
- * <code>getSourceRange</code>.
- *
- * @return the source code, or <code>null</code> if this element has no
- * associated source code
- * @exception JavaScriptModelException if an exception occurs while accessing its corresponding resource
- */
-String getSource() throws JavaScriptModelException;
-/**
- * Returns the source range associated with this element.
- *
- * @return the source range, or <code>null</code> if this element has no
- * associated source code
- * @exception JavaScriptModelException if an exception occurs while accessing its corresponding resource
- */
-ISourceRange getSourceRange() throws JavaScriptModelException;
-}
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
deleted file mode 100644
index 6668a255..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IType.java
+++ /dev/null
@@ -1,722 +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
- * IBM Corporation - added J2SE 1.5 support
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core;
-
-import java.io.InputStream;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-
-/**
- * Represents a source type in a JavaScript file (either a top-level
- * type, a member type, or a local type)
- * </p>
- * <p>
- * The children are of type <code>IMember</code>, which includes <code>IField</code>,
- * <code>IFunction</code>, <code>IInitializer</code> and <code>IType</code>.
- * The children are listed in the order in which they appear in the source file.
- * </p>
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * <p>
- * 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.
- * </p>
- *
- *
- * 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 {
-
- /**
- * Do code completion inside a code snippet in the context of the current type.
- *
- * If the type can access to his source code and the insertion position is valid,
- * then completion is performed against source. Otherwise the completion is performed
- * against type structure and given locals variables.
- *
- * @param snippet the code snippet
- * @param insertion the position with in source where the snippet
- * is inserted. This position must not be in comments.
- * A possible value is -1, if the position is not known.
- * @param position the position within snippet where the user
- * is performing code assist.
- * @param localVariableTypeNames an array (possibly empty) of fully qualified
- * type names of local variables visible at the current scope
- * @param localVariableNames an array (possibly empty) of local variable names
- * that are visible at the current scope
- * @param localVariableModifiers an array (possible empty) of modifiers for
- * local variables
- * @param isStatic whether the current scope is in a static context
- * @param requestor the completion requestor
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- */
- void codeComplete(
- char[] snippet,
- int insertion,
- int position,
- char[][] localVariableTypeNames,
- char[][] localVariableNames,
- int[] localVariableModifiers,
- boolean isStatic,
- CompletionRequestor requestor)
- throws JavaScriptModelException;
-
- /**
- * Do code completion inside a code snippet in the context of the current type.
- * It considers types in the working copies with the given owner first. In other words,
- * the owner's working copies will take precedence over their original compilation units
- * in the workspace.
- * <p>
- * Note that if a working copy is empty, it will be as if the original compilation
- * unit had been deleted.
- * </p><p>
- * If the type can access to his source code and the insertion position is valid,
- * then completion is performed against source. Otherwise the completion is performed
- * against type structure and given locals variables.
- * </p>
- *
- * @param snippet the code snippet
- * @param insertion the position with in source where the snippet
- * is inserted. This position must not be in comments.
- * A possible value is -1, if the position is not known.
- * @param position the position with in snippet where the user
- * is performing code assist.
- * @param localVariableTypeNames an array (possibly empty) of fully qualified
- * type names of local variables visible at the current scope
- * @param localVariableNames an array (possibly empty) of local variable names
- * that are visible at the current scope
- * @param localVariableModifiers an array (possible empty) of modifiers for
- * local variables
- * @param isStatic whether the current scope is in a static context
- * @param requestor the completion requestor
- * @param owner the owner of working copies that take precedence over their original compilation units
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- */
- void codeComplete(
- char[] snippet,
- int insertion,
- int position,
- char[][] localVariableTypeNames,
- char[][] localVariableNames,
- int[] localVariableModifiers,
- boolean isStatic,
- CompletionRequestor requestor,
- WorkingCopyOwner owner)
- throws JavaScriptModelException;
-
-
- /**
- * Creates and returns a field in this type with the
- * given contents.
- * <p>
- * Optionally, the new element can be positioned before the specified
- * sibling. If no sibling is specified, the element will be inserted
- * as the last field declaration in this type.</p>
- *
- * <p>It is possible that a field with the same name already exists in this type.
- * The value of the <code>force</code> parameter effects the resolution of
- * such a conflict:<ul>
- * <li> <code>true</code> - in this case the field is created with the new contents</li>
- * <li> <code>false</code> - in this case a <code>JavaScriptModelException</code> is thrown</li>
- * </ul></p>
- *
- * @param contents the given contents
- * @param sibling the given sibling
- * @param force a flag in case the same name already exists in this type
- * @param monitor the given progress monitor
- * @exception JavaScriptModelException if the element could not be created. Reasons include:
- * <ul>
- * <li> This JavaScript element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while updating an underlying resource
- * <li> The specified sibling is not a child of this type (INVALID_SIBLING)
- * <li> The contents could not be recognized as a field declaration (INVALID_CONTENTS)
- * <li> This type is read-only (binary) (READ_ONLY)
- * <li> There was a naming collision with an existing field (NAME_COLLISION)
- * </ul>
- * @return a field in this type with the given contents
- */
- IField createField(String contents, IJavaScriptElement sibling, boolean force, IProgressMonitor monitor)
- throws JavaScriptModelException;
-
-
- /**
- * Creates and returns a method or constructor in this type with the
- * given contents.
- * <p>
- * Optionally, the new element can be positioned before the specified
- * sibling. If no sibling is specified, the element will be appended
- * to this type.
- *
- * <p>It is possible that a method with the same signature already exists in this type.
- * The value of the <code>force</code> parameter effects the resolution of
- * such a conflict:<ul>
- * <li> <code>true</code> - in this case the method is created with the new contents</li>
- * <li> <code>false</code> - in this case a <code>JavaScriptModelException</code> is thrown</li>
- * </ul></p>
- *
- * @param contents the given contents
- * @param sibling the given sibling
- * @param force a flag in case the same name already exists in this type
- * @param monitor the given progress monitor
- * @exception JavaScriptModelException if the element could not be created. Reasons include:
- * <ul>
- * <li> This JavaScript element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while updating an underlying resource
- * <li> The specified sibling is not a child of this type (INVALID_SIBLING)
- * <li> The contents could not be recognized as a method or constructor
- * declaration (INVALID_CONTENTS)
- * <li> This type is read-only (binary) (READ_ONLY)
- * <li> There was a naming collision with an existing method (NAME_COLLISION)
- * </ul>
- * @return a method or constructor in this type with the given contents
- */
- IFunction createMethod(String contents, IJavaScriptElement sibling, boolean force, IProgressMonitor monitor)
- throws JavaScriptModelException;
-
- /**
- * Creates and returns a type in this type with the
- * given contents.
- * <p>
- * Optionally, the new type can be positioned before the specified
- * sibling. If no sibling is specified, the type will be appended
- * to this type.</p>
- *
- * <p>It is possible that a type with the same name already exists in this type.
- * The value of the <code>force</code> parameter effects the resolution of
- * such a conflict:<ul>
- * <li> <code>true</code> - in this case the type is created with the new contents</li>
- * <li> <code>false</code> - in this case a <code>JavaScriptModelException</code> is thrown</li>
- * </ul></p>
- *
- * @param contents the given contents
- * @param sibling the given sibling
- * @param force a flag in case the same name already exists in this type
- * @param monitor the given progress monitor
- * @exception JavaScriptModelException if the element could not be created. Reasons include:
- * <ul>
- * <li> This JavaScript element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while updating an underlying resource
- * <li> The specified sibling is not a child of this type (INVALID_SIBLING)
- * <li> The contents could not be recognized as a type declaration (INVALID_CONTENTS)
- * <li> This type is read-only (binary) (READ_ONLY)
- * <li> There was a naming collision with an existing field (NAME_COLLISION)
- * </ul>
- * @return a type in this type with the given contents
- */
- IType createType(String contents, IJavaScriptElement sibling, boolean force, IProgressMonitor monitor)
- throws JavaScriptModelException;
-
- /**
- * Finds the methods in this type that correspond to
- * the given method.
- * A method m1 corresponds to another method m2 if:
- * <ul>
- * <li>m1 has the same element name as m2.
- * <li>m1 has the same number of arguments as m2 and
- * the simple names of the argument types must be equals.
- * <li>m1 exists.
- * </ul>
- * @param method the given method
- * @return the found method or <code>null</code> if no such methods can be found.
- *
- */
- IFunction[] findMethods(IFunction method);
-
- /**
- * Returns the children of this type that have the given category as a <code>@category</code> tag.
- * Returns an empty array if no children with this category exist.
- *
- * @return the children for the given category.
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- */
- IJavaScriptElement[] getChildrenForCategory(String category) throws JavaScriptModelException;
-
- /**
- * Returns the simple name of this type, unqualified by package or enclosing type.
- * This is a handle-only method.
- *
- * @return the simple name of this type
- */
- String getElementName();
-
- /**
- * Returns the field with the specified name
- * in this type (for example, <code>"bar"</code>).
- * This is a handle-only method. The field may or may not exist.
- *
- * @param name the given name
- * @return the field with the specified name in this type
- */
- IField getField(String name);
-
- /**
- * Returns the fields declared by this type.
- * If this is a source type, the results are listed in the order
- * in which they appear in the source, otherwise, the results are
- * in no particular order. For binary types, this includes synthetic fields.
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return the fields declared by this type
- */
- IField[] getFields() throws JavaScriptModelException;
-
- /**
- * Returns the fully qualified name of this type,
- * including qualification for any containing types and packages.
- * This is the name of the package, followed by <code>'.'</code>,
- * followed by the type-qualified name.
- * This is a handle-only method.
- *
- * @see IType#getTypeQualifiedName()
- * @return the fully qualified name of this type
- */
- String getFullyQualifiedName();
-
- /**
- * Returns the fully qualified name of this type,
- * including qualification for any containing types and packages.
- * This is the name of the package, followed by <code>'.'</code>,
- * followed by the type-qualified name using the <code>enclosingTypeSeparator</code>.
- *
- *
- * This is a handle-only method.
- *
- * @param enclosingTypeSeparator the given enclosing type separator
- * @return the fully qualified name of this type, including qualification for any containing types and packages
- * @see IType#getTypeQualifiedName(char)
- */
- String getFullyQualifiedName(char enclosingTypeSeparator);
-
- /**
- * Returns this type's fully qualified name
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return the fully qualified parameterized representation of this type
- */
- String getFullyQualifiedParameterizedName() throws JavaScriptModelException;
-
- /**
- * Returns the initializer with the specified position relative to
- * the order they are defined in the source.
- * Numbering starts at 1 (thus the first occurrence is occurrence 1, not occurrence 0).
- * This is a handle-only method. The initializer may or may not be present.
- *
- * @param occurrenceCount the specified position
- * @return the initializer with the specified position relative to the order they are defined in the source
- */
- IInitializer getInitializer(int occurrenceCount);
-
- /**
- * Returns the initializers declared by this type.
- * For binary types this is an empty collection.
- * If this is a source type, the results are listed in the order
- * in which they appear in the source.
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return the initializers declared by this type
- */
- IInitializer[] getInitializers() throws JavaScriptModelException;
-
- /**
- * Returns the binding key for this type. A binding key is a key that uniquely
- * identifies this type. It allows access to generic info for parameterized
- * types.
- *
- * @return the binding key for this type
- * @see org.eclipse.wst.jsdt.core.dom.IBinding#getKey()
- * @see BindingKey
- */
- String getKey();
-
- /**
- * Returns the method with the specified name and parameter types
- * in this type (for example, <code>"foo", {"I", "QString;"}</code>).
- * To get the handle for a constructor, the name specified must be the
- * simple name of the enclosing type.
- * This is a handle-only method. The method may or may not be present.
- * <p>
- * The type signatures may be either unresolved (for source types)
- * or resolved (for binary types), and either basic (for basic types)
- * or rich (for parameterized types). See {@link Signature} for details.
- * </p>
- *
- * @param name the given name
- * @param parameterTypeSignatures the given parameter types
- * @return the method with the specified name and parameter types in this type
- */
- IFunction getFunction(String name, String[] parameterTypeSignatures);
-
- /**
- * Returns the methods and constructors declared by this type.
- * For binary types, this may include the special <code>&lt;clinit&gt;</code>; method
- * and synthetic methods.
- * If this is a source type, the results are listed in the order
- * in which they appear in the source, otherwise, the results are
- * in no particular order.
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return the methods and constructors declared by this type
- */
- IFunction[] getFunctions() throws JavaScriptModelException;
-
- /**
- * Returns the source folder (package fragment) in which this element is defined.
- * This is a handle-only method.
- *
- * @return the package fragment in which this element is defined
- */
- IPackageFragment getPackageFragment();
-
- /**
- * Returns the name of this type's superclass, or <code>null</code>
- * for source types that do not specify a superclass.
- * <p>
- * For interfaces, the superclass name is always <code>"java.lang.Object"</code>.
- * For source types, the name as declared is returned, for binary types,
- * the resolved, qualified name is returned.
- * For anonymous types, the superclass name is the name appearing after the 'new' keyword'.
- * If the superclass is a parameterized type, the string
- * may include its type arguments enclosed in "&lt;&gt;".
- * If the returned string is needed for anything other than display
- * purposes, use {@link #getSuperclassTypeSignature()} which returns
- * a structured type signature string containing more precise information.
- * </p>
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return the name of this type's superclass, or <code>null</code> for source types that do not specify a superclass
- */
- String getSuperclassName() throws JavaScriptModelException;
-
- /**
- * Returns the type signature of this type's superclass, or
- * <code>null</code> if none.
- * <p>
- * The type signature may be either unresolved (for source types)
- * or resolved (for binary types), and either basic (for basic types)
- * or rich (for parameterized types). See {@link Signature} for details.
- * </p>
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return the type signature of this type's superclass, or
- * <code>null</code> if none
- */
- String getSuperclassTypeSignature() throws JavaScriptModelException;
-
- /**
- * Returns the member type declared in this type with the given simple name.
- * This is a handle-only method. The type may or may not exist.
- *
- * @param name the given simple name
- * @return the member type declared in this type with the given simple name
- */
- IType getType(String name);
-
- /**
- * Returns the type-qualified name of this type,
- * including qualification for any enclosing types,
- * but not including package qualification.
- * This is a handle-only method.
- *
- * @return the type-qualified name of this type
- */
- String getTypeQualifiedName();
-
- /**
- * Returns the type-qualified name of this type,
- * including qualification for any enclosing types,
- * but not including package qualification.
- *
- * This is a handle-only method.
- *
- * @param enclosingTypeSeparator the specified enclosing type separator
- * @return the type-qualified name of this type
- */
- String getTypeQualifiedName(char enclosingTypeSeparator);
-
- /**
- * Returns the immediate member types declared by this type.
- * The results are listed in the order in which they appear in the source or class file.
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return the immediate member types declared by this type
- */
- IType[] getTypes() throws JavaScriptModelException;
-
- /**
- * Returns whether this type represents an anonymous type.
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return true if this type represents an anonymous type, false otherwise
- */
- boolean isAnonymous() throws JavaScriptModelException;
-
- /**
- * Returns whether this type is read-only.
- * <p>
- * Note that a class can neither be an interface, an enumeration class, nor an annotation type.
- * </p>
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return true if this type represents a class, false otherwise
- */
- boolean isClass() throws JavaScriptModelException;
-
- /**
- * Returns whether this type represents a local type.
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return true if this type represents a local type, false otherwise
- */
- boolean isLocal() throws JavaScriptModelException;
-
- /**
- * Returns whether this type represents a member type.
- *
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return true if this type represents a member type, false otherwise
- */
- boolean isMember() throws JavaScriptModelException;
- /**
- * Returns whether this type represents a resolved type.
- * If a type is resolved, its key contains resolved information.
- *
- * @return whether this type represents a resolved type.
- */
- boolean isResolved();
- /**
- * Loads a previously saved ITypeHierarchy from an input stream. A type hierarchy can
- * be stored using ITypeHierachy#store(OutputStream).
- *
- * Only hierarchies originally created by the following methods can be loaded:
- * <ul>
- * <li>IType#newSupertypeHierarchy(IProgressMonitor)</li>
- * <li>IType#newTypeHierarchy(IJavaScriptProject, IProgressMonitor)</li>
- * <li>IType#newTypeHierarchy(IProgressMonitor)</li>
- * </ul>
- *
- * @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)
- */
- ITypeHierarchy loadTypeHierachy(InputStream input, IProgressMonitor monitor) throws JavaScriptModelException;
- /**
- * Creates and returns a type hierarchy for this type containing
- * this type and all of its supertypes.
- *
- * @param monitor the given progress monitor
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return a type hierarchy for this type containing this type and all of its supertypes
- */
- ITypeHierarchy newSupertypeHierarchy(IProgressMonitor monitor) throws JavaScriptModelException;
-
- /**
- * Creates and returns a type hierarchy for this type containing
- * this type and all of its supertypes, considering types in the given
- * working copies. In other words, the list of working copies will take
- * precedence over their original compilation units in the workspace.
- * <p>
- * Note that passing an empty working copy will be as if the original compilation
- * unit had been deleted.
- * </p>
- *
- * @param workingCopies the working copies that take precedence over their original compilation units
- * @param monitor the given progress monitor
- * @return a type hierarchy for this type containing this type and all of its supertypes
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- */
- ITypeHierarchy newSupertypeHierarchy(IJavaScriptUnit[] workingCopies, IProgressMonitor monitor)
- throws JavaScriptModelException;
-
- /**
- * Creates and returns a type hierarchy for this type containing
- * this type and all of its supertypes, considering types in the
- * working copies with the given owner.
- * In other words, the owner's working copies will take
- * precedence over their original compilation units in the workspace.
- * <p>
- * Note that if a working copy is empty, it will be as if the original compilation
- * unit had been deleted.
- * <p>
- *
- * @param owner the owner of working copies that take precedence over their original compilation units
- * @param monitor the given progress monitor
- * @return a type hierarchy for this type containing this type and all of its supertypes
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- */
- ITypeHierarchy newSupertypeHierarchy(WorkingCopyOwner owner, IProgressMonitor monitor)
- throws JavaScriptModelException;
-
- /**
- * Creates and returns a type hierarchy for this type containing
- * this type, all of its supertypes, and all its subtypes
- * in the context of the given project.
- *
- * @param project the given project
- * @param monitor the given progress monitor
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return a type hierarchy for this type containing
- * this type, all of its supertypes, and all its subtypes
- * in the context of the given project
- */
- ITypeHierarchy newTypeHierarchy(IJavaScriptProject project, IProgressMonitor monitor) throws JavaScriptModelException;
-
- /**
- * Creates and returns a type hierarchy for this type containing
- * this type, all of its supertypes, and all its subtypes
- * in the context of the given project, considering types in the
- * working copies with the given owner.
- * In other words, the owner's working copies will take
- * precedence over their original compilation units in the workspace.
- * <p>
- * Note that if a working copy is empty, it will be as if the original compilation
- * unit had been deleted.
- * <p>
- *
- * @param project the given project
- * @param owner the owner of working copies that take precedence over their original compilation units
- * @param monitor the given progress monitor
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return a type hierarchy for this type containing
- * this type, all of its supertypes, and all its subtypes
- * in the context of the given project
- */
- ITypeHierarchy newTypeHierarchy(IJavaScriptProject project, WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaScriptModelException;
-
- /**
- * Creates and returns a type hierarchy for this type containing
- * this type, all of its supertypes, and all its subtypes in the workspace.
- *
- * @param monitor the given progress monitor
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return a type hierarchy for this type containing
- * this type, all of its supertypes, and all its subtypes in the workspace
- */
- ITypeHierarchy newTypeHierarchy(IProgressMonitor monitor) throws JavaScriptModelException;
-
- /**
- * Creates and returns a type hierarchy for this type containing
- * this type, all of its supertypes, and all its subtypes in the workspace,
- * considering types in the given working copies. In other words, the list of working
- * copies that will take precedence over their original compilation units in the workspace.
- * <p>
- * Note that passing an empty working copy will be as if the original compilation
- * unit had been deleted.
- *
- * @param workingCopies the working copies that take precedence over their original compilation units
- * @param monitor the given progress monitor
- * @return a type hierarchy for this type containing
- * this type, all of its supertypes, and all its subtypes in the workspace
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- */
- ITypeHierarchy newTypeHierarchy(IJavaScriptUnit[] workingCopies, IProgressMonitor monitor) throws JavaScriptModelException;
-
- /**
- * Creates and returns a type hierarchy for this type containing
- * this type, all of its supertypes, and all its subtypes in the workspace,
- * considering types in the working copies with the given owner.
- * In other words, the owner's working copies will take
- * precedence over their original compilation units in the workspace.
- * <p>
- * Note that if a working copy is empty, it will be as if the original compilation
- * unit had been deleted.
- * <p>
- *
- * @param owner the owner of working copies that take precedence over their original compilation units
- * @param monitor the given progress monitor
- * @return a type hierarchy for this type containing
- * this type, all of its supertypes, and all its subtypes in the workspace
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- */
- ITypeHierarchy newTypeHierarchy(WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaScriptModelException;
-
- /**
- * Resolves the given type name within the context of this type (depending on the type hierarchy
- * and its imports).
- * <p>
- * Multiple answers might be found in case there are ambiguous matches.
- * </p>
- * <p>
- * Each matching type name is decomposed as an array of two strings, the first denoting the package
- * name (dot-separated) and the second being the type name. The package name is empty if it is the
- * default package. The type name is the type qualified name using a '.' enclosing type separator.
- * </p>
- * <p>
- * Returns <code>null</code> if unable to find any matching type.
- * </p>
- *
- * @param typeName the given type name
- * @exception JavaScriptModelException if code resolve could not be performed.
- * @return the resolved type names or <code>null</code> if unable to find any matching type
- * @see #getTypeQualifiedName(char)
- */
- String[][] resolveType(String typeName) throws JavaScriptModelException;
-
- /**
- * Resolves the given type name within the context of this type (depending on the type hierarchy
- * and its imports) and using the given owner's working copies, considering types in the
- * working copies with the given owner. In other words, the owner's working copies will take
- * precedence over their original compilation units in the workspace.
- * <p>
- * Note that if a working copy is empty, it will be as if the original compilation
- * unit had been deleted.
- * </p>
- * <p>Multiple answers might be found in case there are ambiguous matches.
- * </p>
- * <p>
- * Each matching type name is decomposed as an array of two strings, the first denoting the package
- * name (dot-separated) and the second being the type name. The package name is empty if it is the
- * default package. The type name is the type qualified name using a '.' enclosing type separator.
- * </p>
- * <p>
- * Returns <code>null</code> if unable to find any matching type.
- *</p>
- *
- * @param typeName the given type name
- * @param owner the owner of working copies that take precedence over their original compilation units
- * @exception JavaScriptModelException if code resolve could not be performed.
- * @return the resolved type names or <code>null</code> if unable to find any matching type
- * @see #getTypeQualifiedName(char)
- */
- String[][] resolveType(String typeName, WorkingCopyOwner owner) throws JavaScriptModelException;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ITypeHierarchy.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ITypeHierarchy.java
deleted file mode 100644
index 97068265..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ITypeHierarchy.java
+++ /dev/null
@@ -1,180 +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.core;
-
-import java.io.OutputStream;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-
-/**
- * A type hierarchy provides navigations between a type and its resolved
- * supertypes and subtypes for a specific type or for all types within a region.
- * Supertypes may extend outside of the type hierarchy's region in which it was
- * created such that the root of the hierarchy is always included.
- * <p>
- * A type hierarchy is static and can become stale. Although consistent when
- * created, it does not automatically track changes in the model.
- * As changes in the model potentially invalidate the hierarchy, change notifications
- * are sent to registered <code>ITypeHierarchyChangedListener</code>s. Listeners should
- * use the <code>exists</code> method to determine if the hierarchy has become completely
- * invalid (for example, when the type or project the hierarchy was created on
- * has been removed). To refresh a hierarchy, use the <code>refresh</code> method.
- * </p>
- * <p>
- * The type hierarchy may contain cycles due to malformed supertype declarations.
- * Most type hierarchy queries are oblivious to cycles; the <code>getAll* </code>
- * methods are implemented such that they are unaffected by cycles.
- * </p>
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * 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 ITypeHierarchy {
-/**
- * Adds the given listener for changes to this type hierarchy. Listeners are
- * notified when this type hierarchy changes and needs to be refreshed.
- * Has no effect if an identical listener is already registered.
- *
- * @param listener the listener
- */
-void addTypeHierarchyChangedListener(ITypeHierarchyChangedListener listener);
-/**
- * Returns whether the given type is part of this hierarchy.
- *
- * @param type the given type
- * @return true if the given type is part of this hierarchy, false otherwise
- */
-boolean contains(IType type);
-/**
- * Returns whether the type and project this hierarchy was created on exist.
- * @return true if the type and project this hierarchy was created on exist, false otherwise
- */
-boolean exists();
-/**
- * Returns all classes in this type hierarchy's graph, in no particular
- * order. Any classes in the creation region which were not resolved to
- * have any subtypes or supertypes are not included in the result.
- *
- * @return all classes in this type hierarchy's graph
- */
-IType[] getAllClasses();
-/**
- * Returns all resolved subtypes (direct and indirect) of the
- * given type, in no particular order, limited to the
- * types in this type hierarchy's graph. An empty array
- * is returned if there are no resolved subtypes for the
- * given type.
- *
- * @param type the given type
- * @return all resolved subtypes (direct and indirect) of the given type
- */
-IType[] getAllSubtypes(IType type);
-/**
- * Returns all resolved superclasses of the
- * given class, in bottom-up order. An empty array
- * is returned if there are no resolved superclasses for the
- * given class.
- *
- * <p>NOTE: once a type hierarchy has been created, it is more efficient to
- * query the hierarchy for superclasses than to query a class recursively up
- * the superclass chain. Querying an element performs a dynamic resolution,
- * whereas the hierarchy returns a pre-computed result.
- *
- * @param type the given type
- * @return all resolved superclasses of the given class, in bottom-up order, an empty
- * array if none.
- */
-IType[] getAllSuperclasses(IType type);
-/**
- * Return the flags associated with the given type (would be equivalent to <code>IMember.getFlags()</code>),
- * or <code>-1</code> if this information wasn't cached on the hierarchy during its computation.
- *
- * @param type the given type
- * @return the modifier flags for this member
- * @see Flags
- */
-int getCachedFlags(IType type);
-/**
- * Returns all classes in the graph which have no resolved superclass,
- * in no particular order.
- *
- * @return all classes in the graph which have no resolved superclass
- */
-IType[] getRootClasses();
-/**
- * Returns the direct resolved subclasses of the given class,
- * in no particular order, limited to the classes in this
- * type hierarchy's graph.
- * Returns an empty collection if no classes were resolved to be subclasses of the given
- * class.
- *
- * @param type the given type
- * @return the direct resolved subclasses of the given class limited to the classes in this
- * type hierarchy's graph, an empty collection if none.
- */
-IType[] getSubclasses(IType type);
-/**
- * Returns the resolved superclass of the given class,
- * or <code>null</code> if the given class has no superclass or
- * the superclass could not be resolved.
- *
- * @param type the given type
- * @return the resolved superclass of the given class,
- * or <code>null</code> if the given class has no superclass or
- * the superclass could not be resolved.
- */
-IType getSuperclass(IType type);
-/**
- * Returns the type this hierarchy was computed for.
- * Returns <code>null</code> if this hierarchy was computed for a region.
- *
- * @return the type this hierarchy was computed for
- */
-IType getType();
-/**
- * Re-computes the type hierarchy reporting progress.
- *
- * @param monitor the given progress monitor
- * @exception JavaScriptModelException if unable to refresh the hierarchy
- */
-void refresh(IProgressMonitor monitor) throws JavaScriptModelException;
-/**
- * Removes the given listener from this type hierarchy.
- * Has no affect if an identical listener is not registered.
- *
- * @param listener the listener
- */
-void removeTypeHierarchyChangedListener(ITypeHierarchyChangedListener listener);
-/**
- * Stores the type hierarchy in an output stream. This stored hierarchy can be load by
- * IType#loadTypeHierachy(IJavaScriptProject, InputStream, IProgressMonitor).
- * Listeners of this hierarchy are not stored.
- *
- * Only hierarchies created by the following methods can be store:
- * <ul>
- * <li>IType#newSupertypeHierarchy(IProgressMonitor)</li>
- * <li>IType#newTypeHierarchy(IJavaScriptProject, IProgressMonitor)</li>
- * <li>IType#newTypeHierarchy(IProgressMonitor)</li>
- * </ul>
- *
- * @param outputStream output stream where the hierarchy will be stored
- * @param monitor the given progress monitor
- * @exception JavaScriptModelException if unable to store the hierarchy in the ouput stream
- * @see IType#loadTypeHierachy(java.io.InputStream, IProgressMonitor)
- * @since 2.1
- */
-void store(OutputStream outputStream, IProgressMonitor monitor) throws JavaScriptModelException;
-}
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
deleted file mode 100644
index cab5ff41..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ITypeHierarchyChangedListener.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*******************************************************************************
- * 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;
-
-/**
- * A listener which gets notified when a particular type hierarchy object
- * changes.
- * <p>
- * This interface may be implemented by clients.
- * </p>
- *
- * 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 ITypeHierarchyChangedListener {
- /**
- * Notifies that the given type hierarchy has changed in some way and should
- * be refreshed at some point to make it consistent with the current state of
- * the JavaScript model.
- *
- * @param typeHierarchy the given type hierarchy
- */
- void typeHierarchyChanged(ITypeHierarchy typeHierarchy);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ITypeRoot.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ITypeRoot.java
deleted file mode 100644
index 01a99be1..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ITypeRoot.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-
-
-/**
- * Represents an entire JavaScript type root (either an <code>IJavaScriptUnit</code>
- * or an <code>IClassFile</code>).
- *
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * @see IJavaScriptUnit Note that methods {@link #findPrimaryType()} and {@link #getElementAt(int)}
- * were already implemented in this interface respectively since version 3.0 and version 1.0.
- * @see IClassFile Note that method {@link #getWorkingCopy(WorkingCopyOwner, IProgressMonitor)}
- * was already implemented in this interface since version 3.0.
- *
- * 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 ITypeRoot extends IJavaScriptElement, IParent, IOpenable, ISourceReference, ICodeAssist, IFunctionContainer {
-
-/**
- * Finds the primary type of this JavaScript type root (that is, the type with the same name as the
- * javascript file), or <code>null</code> if no such a type exists.
- *
- * @return the found primary type of this JavaScript type root, or <code>null</code> if no such a type exists
- */
-IType findPrimaryType();
-
-/**
- * Returns the smallest element within this JavaScript type root that
- * includes the given source position (that is, a method, field, etc.), or
- * <code>null</code> if there is no element other than the JavaScript type root
- * itself at the given position, or if the given position is not
- * within the source range of the source of this JavaScript type root.
- *
- * @param position a source position inside the JavaScript type root
- * @return the innermost JavaScript element enclosing a given source position or <code>null</code>
- * if none (excluding the JavaScript type root).
- * @throws JavaScriptModelException if the JavaScript type root does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
-IJavaScriptElement getElementAt(int position) throws JavaScriptModelException;
-
-/**
- * Returns a shared working copy on this javaScirpt file using the given working copy owner to create
- * the buffer. If this is already a working copy of the given owner, the element itself is returned.
- * This API can only answer an already existing working copy if it is based on the same
- * original JavaScript type root AND was using the same working copy owner (that is, as defined by {@link Object#equals}).
- * <p>
- * The life time of a shared working copy is as follows:
- * <ul>
- * <li>The first call to {@link #getWorkingCopy(WorkingCopyOwner, IProgressMonitor)}
- * creates a new working copy for this element</li>
- * <li>Subsequent calls increment an internal counter.</li>
- * <li>A call to {@link IJavaScriptUnit#discardWorkingCopy()} decrements the internal counter.</li>
- * <li>When this counter is 0, the working copy is discarded.
- * </ul>
- * So users of this method must discard exactly once the working copy.
- * <p>
- * Note that the working copy owner will be used for the life time of the shared working copy, that is if the
- * working copy is closed then reopened, this owner will be used.
- * The buffer will be automatically initialized with the original's JavaScript type root content upon creation.
- * <p>
- * When the shared working copy instance is created, an ADDED IJavaScriptElementDelta is reported on this
- * working copy.
- * </p><p>
- * A working copy can be created on a not-yet existing compilation unit.
- * In particular, such a working copy can then be committed in order to create
- * the corresponding compilation unit.
- * </p><p>
- * Note that possible problems of this working copy are reported using this method. only
- * if the given working copy owner returns a problem requestor for this working copy
- * (see {@link WorkingCopyOwner#getProblemRequestor(IJavaScriptUnit)}).
- * </p>
- *
- * @param owner the working copy owner that creates a buffer that is used to get the content
- * of the working copy
- * @param monitor a progress monitor used to report progress while opening this compilation unit
- * or <code>null</code> if no progress should be reported
- * @throws JavaScriptModelException if the contents of this element can
- * not be determined.
- * @return a new working copy of this JavaScript type root using the given owner to create
- * the buffer, or this JavaScript type root if it is already a working copy
- */
-IJavaScriptUnit getWorkingCopy(WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaScriptModelException;
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/JSDScopeUtil.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/JSDScopeUtil.java
deleted file mode 100644
index 9fc632e0..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/JSDScopeUtil.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-/**
- *
- */
-package org.eclipse.wst.jsdt.core;
-
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.wst.jsdt.internal.core.ClassFile;
-
-/**
- * (mostly) static methods to figure out includepath entries and container initializers *
- *
- * 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 JSDScopeUtil {
-
-
-
-
-
- public static JsGlobalScopeContainerInitializer getContainerInitializer(IPath classPathEntry) {
- if(classPathEntry==null ) return null;
- JsGlobalScopeContainerInitializer initializer= JavaScriptCore.getJsGlobalScopeContainerInitializer(classPathEntry.segment(0));
- return initializer ;
- }
-
- public IIncludePathEntry[] getIncludepathEntries(IJsGlobalScopeContainer container) {
-
-
- if(container!=null) return container.getIncludepathEntries();
-
- return new IIncludePathEntry[0];
- }
-
- public IJsGlobalScopeContainer getLibraryContainer(IPath cpEntry, IJavaScriptProject javaProject) {
- IJsGlobalScopeContainer container=null;
- try {
- container = JavaScriptCore.getJsGlobalScopeContainer(cpEntry, javaProject);
- } catch (JavaScriptModelException ex) {
- // TODO Auto-generated catch block
- ex.printStackTrace();
- }
- return container;
- }
-
- public static JsGlobalScopeContainerInitializer findLibraryInitializer(IPath compUnitPath, IJavaScriptProject javaProject) {
- IPackageFragmentRoot[] roots = new IPackageFragmentRoot[0];
- try {
- roots = javaProject.getAllPackageFragmentRoots();
- } catch (JavaScriptModelException ex) {
- // TODO Auto-generated catch block
- ex.printStackTrace();
- }
- for (int i = 0;i<roots.length;i++) {
- IPackageFragment frag = roots[i].getPackageFragment(""); //$NON-NLS-1$
-
- try {
- IClassFile classfile = frag.getClassFile(compUnitPath.toString());
- if(classfile.exists()) {
- return ((ClassFile)classfile).getContainerInitializer();
- }
- } catch (Exception ex) {
- // Do nothing since CU may be invalid and thats what w're tryingto figure out.
- // TODO Auto-generated catch block
- // ex.printStackTrace();
- }
-
-
- }
-
- return null;
- }
-}
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
deleted file mode 100644
index 866eb375..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/JavaScriptConventions.java
+++ /dev/null
@@ -1,729 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core;
-
-import java.util.StringTokenizer;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-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.impl.CompilerOptions;
-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.ClasspathEntry;
-import org.eclipse.wst.jsdt.internal.core.JavaModelStatus;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-
-/**
- * Provides methods for checking JavaScript-specific conventions such as name syntax.
- * <p>
- * This class provides static methods and constants only; it is not intended to be
- * instantiated or subclassed by clients.
- * </p>
- *
- * 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 final class JavaScriptConventions {
-
- private static final char DOT= '.';
- private static final Scanner SCANNER = new Scanner(false /*comment*/, true /*whitespace*/, false /*nls*/, ClassFileConstants.JDK1_3 /*sourceLevel*/, null/*taskTag*/, null/*taskPriorities*/, true /*taskCaseSensitive*/);
-
- private JavaScriptConventions() {
- // Not instantiable
- }
-
- /*
- * Returns the current identifier extracted by the scanner (without unicode
- * escapes) from the given id and for the given source and compliance levels.
- * Returns <code>null</code> if the id was not valid
- */
- private static synchronized char[] scannedIdentifier(String id, String sourceLevel, String complianceLevel) {
- if (id == null) {
- return null;
- }
- // Set scanner for given source and compliance levels
- SCANNER.sourceLevel = sourceLevel == null ? ClassFileConstants.JDK1_3 : CompilerOptions.versionToJdkLevel(sourceLevel);
- SCANNER.complianceLevel = complianceLevel == null ? ClassFileConstants.JDK1_3 : CompilerOptions.versionToJdkLevel(complianceLevel);
-
- try {
- SCANNER.setSource(id.toCharArray());
- int token = SCANNER.scanIdentifier();
- if (token != TerminalTokens.TokenNameIdentifier) return null;
- if (SCANNER.currentPosition == SCANNER.eofPosition) { // to handle case where we had an ArrayIndexOutOfBoundsException
- try {
- return SCANNER.getCurrentIdentifierSource();
- } catch (ArrayIndexOutOfBoundsException e) {
- return null;
- }
- } else {
- return null;
- }
- }
- catch (InvalidInputException e) {
- return null;
- }
- }
-
- /**
- * Validate the given javaScript unit name.
- * <p>
- * A javaScript unit name must obey the following rules:
- * <ul>
- * <li> it must not be null
- * <li> it must be suffixed by a dot ('.') followed by one of the
- * {@link JavaScriptCore#getJavaScriptLikeExtensions() JavaScript-like extensions}
- * <li> its prefix must be a valid identifier
- * <li> it must not contain any characters or substrings that are not valid
- * on the file system on which workspace root is located.
- * </ul>
- * </p>
- * @param name the name of a javaScript unit
- * @return a status object with code <code>IStatus.OK</code> if
- * the given name is valid as a javaScript unit name, otherwise a status
- * object indicating what is wrong with the name
- * @deprecated Use {@link #validateCompilationUnitName(String id, String sourceLevel, String complianceLevel)} instead
- */
- public static IStatus validateCompilationUnitName(String name) {
- return validateCompilationUnitName(name,CompilerOptions.VERSION_1_3,CompilerOptions.VERSION_1_3);
- }
-
- /**
- * Validate the given javaScript unit name for the given source and compliance levels.
- * <p>
- * A javaScript unit name must obey the following rules:
- * <ul>
- * <li> it must not be null
- * <li> it must be suffixed by a dot ('.') followed by one of the
- * {@link JavaScriptCore#getJavaScriptLikeExtensions() JavaScript-like extensions}
- * <li> its prefix must be a valid identifier
- * <li> it must not contain any characters or substrings that are not valid
- * on the file system on which workspace root is located.
- * </ul>
- * </p>
- * @param name the name of a javaScript unit
- * @param sourceLevel the source level
- * @param complianceLevel the compliance level
- * @return a status object with code <code>IStatus.OK</code> if
- * the given name is valid as a javaScript unit name, otherwise a status
- * object indicating what is wrong with the name
- */
- public static IStatus validateCompilationUnitName(String name, String sourceLevel, String complianceLevel) {
- if (name == null) {
- return new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, -1, Messages.convention_unit_nullName, null);
- }
- if (!org.eclipse.wst.jsdt.internal.core.util.Util.isJavaLikeFileName(name)) {
- return new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, -1, Messages.convention_unit_notJavaName, null);
- }
-// String identifier;
- int index;
- index = name.lastIndexOf('.');
- if (index == -1) {
- return new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, -1, Messages.convention_unit_notJavaName, null);
- }
-// identifier = name.substring(0, index);
- // JSR-175 metadata strongly recommends "package-info.js" as the
- // file in which to store package annotations and
- // the package-level spec (replaces package.html)
-// if (!identifier.equals(PACKAGE_INFO)) {
-// IStatus status = validateIdentifier(identifier, sourceLevel, complianceLevel);
-// if (!status.isOK()) {
-// return status;
-// }
-// }
-// IStatus status = ResourcesPlugin.getWorkspace().validateName(name, IResource.FILE);
-// if (!status.isOK()) {
-// return status;
-// }
- return JavaModelStatus.VERIFIED_OK;
- }
-
- /*
- * Validate the given .class file name for the given source and compliance levels.
- * <p>
- * A .class file name must obey the following rules:
- * <ul>
- * <li> it must not be null
- * <li> it must include the <code>".class"</code> suffix
- * <li> its prefix must be a valid identifier
- * <li> it must not contain any characters or substrings that are not valid
- * on the file system on which workspace root is located.
- * </ul>
- * </p>
- * @param name the name of a .class file
- * @param sourceLevel the source level
- * @param complianceLevel the compliance level
- * @return a status object with code <code>IStatus.OK</code> if
- * the given name is valid as a .class file name, otherwise a status
- * object indicating what is wrong with the name
- */
- public static IStatus validateClassFileName(String name, String sourceLevel, String complianceLevel) {
- if (name == null) {
- return new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, -1, Messages.convention_classFile_nullName, null); }
- if (!org.eclipse.wst.jsdt.internal.compiler.util.Util.isClassFileName(name)) {
- return new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, -1, Messages.convention_classFile_notClassFileName, null);
- }
-// String identifier;
- int index;
- index = name.lastIndexOf('.');
- if (index == -1) {
- return new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, -1, Messages.convention_classFile_notClassFileName, null);
- }
-// identifier = name.substring(0, index);
- // JSR-175 metadata strongly recommends "package-info.js" as the
- // file in which to store package annotations and
- // the package-level spec (replaces package.html)
-// if (!identifier.equals(PACKAGE_INFO)) {
-// IStatus status = validateIdentifier(identifier, sourceLevel, complianceLevel);
-// if (!status.isOK()) {
-// return status;
-// }
-// }
- IStatus status = ResourcesPlugin.getWorkspace().validateName(name, IResource.FILE);
- if (!status.isOK()) {
- return status;
- }
- return JavaModelStatus.VERIFIED_OK;
- }
-
- /**
- * Validate the given var or field name.
- * <p>
- * Syntax of a field name corresponds to VariableDeclaratorId (JLS2 8.3).
- * For example, <code>"x"</code>.
- *
- * @param name the name of a field
- * @return a status object with code <code>IStatus.OK</code> if
- * the given name is valid as a field name, otherwise a status
- * object indicating what is wrong with the name
- * @deprecated Use {@link #validateFieldName(String id, String sourceLevel, String complianceLevel)} instead
- */
- public static IStatus validateFieldName(String name) {
- return validateIdentifier(name, CompilerOptions.VERSION_1_3,CompilerOptions.VERSION_1_3);
- }
-
- /**
- * Validate the given var or field name for the given source and compliance levels.
- * <p>
- * Syntax of a field name corresponds to VariableDeclaratorId (JLS2 8.3).
- * For example, <code>"x"</code>.
- *
- * @param name the name of a field
- * @param sourceLevel the source level
- * @param complianceLevel the compliance level
- * @return a status object with code <code>IStatus.OK</code> if
- * the given name is valid as a field name, otherwise a status
- * object indicating what is wrong with the name
- */
- public static IStatus validateFieldName(String name, String sourceLevel, String complianceLevel) {
- return validateIdentifier(name, sourceLevel, complianceLevel);
- }
-
- /**
- * Validate the given JavaScript identifier.
- * The identifier must not have the same spelling as a JavaScript keyword,
- * boolean literal (<code>"true"</code>, <code>"false"</code>), or null literal (<code>"null"</code>).
- * A valid identifier can act as a simple type name, method name or field name.
- *
- * @param id the JavaScript identifier
- * @return a status object with code <code>IStatus.OK</code> if
- * the given identifier is a valid JavaScript identifier, otherwise a status
- * object indicating what is wrong with the identifier
- * @deprecated Use {@link #validateIdentifier(String id, String sourceLevel, String complianceLevel)} instead
- */
- public static IStatus validateIdentifier(String id) {
- return validateIdentifier(id,CompilerOptions.VERSION_1_3,CompilerOptions.VERSION_1_3);
- }
-
- /**
- * Validate the given JavaScript identifier for the given source and compliance levels
- * The identifier must not have the same spelling as a JavaScript keyword,
- * boolean literal (<code>"true"</code>, <code>"false"</code>), or null literal (<code>"null"</code>).
- * A valid identifier can act as a simple type name, method name or field name.
- *
- * @param id the JavaScript identifier
- * @param sourceLevel the source level
- * @param complianceLevel the compliance level
- * @return a status object with code <code>IStatus.OK</code> if
- * the given identifier is a valid JavaScript identifier, otherwise a status
- * object indicating what is wrong with the identifier
- */
- public static IStatus validateIdentifier(String id, String sourceLevel, String complianceLevel) {
- if (scannedIdentifier(id, sourceLevel, complianceLevel) != null) {
- return JavaModelStatus.VERIFIED_OK;
- } else {
- return new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, -1, Messages.bind(Messages.convention_illegalIdentifier, id), null);
- }
- }
-
- /**
- * Validate the given import declaration name for the given source and compliance levels.
- * <p>
- * The name of an import corresponds to a fully qualified type name.
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @param name the import declaration
- * @param sourceLevel the source level
- * @param complianceLevel the compliance level
- * @return a status object with code <code>IStatus.OK</code> if
- * the given name is valid as an import declaration, otherwise a status
- * object indicating what is wrong with the name
- */
- public static IStatus validateImportDeclaration(String name, String sourceLevel, String complianceLevel) {
- if (name == null || name.length() == 0) {
- return new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, -1, Messages.convention_import_nullImport, null);
- }
- if (name.charAt(name.length() - 1) == '*') {
- if (name.charAt(name.length() - 2) == '.') {
- return validatePackageName(name.substring(0, name.length() - 2), sourceLevel, complianceLevel);
- } else {
- return new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, -1, Messages.convention_import_unqualifiedImport, null);
- }
- }
- return validatePackageName(name, sourceLevel, complianceLevel);
- }
-
- /**
- * Validate the given JavaScript type name, either simple or qualified.
- * <p>
- *
- * @param name the name of a type
- * @return a status object with code <code>IStatus.OK</code> if
- * the given name is valid as a JavaScript type name,
- * a status with code <code>IStatus.WARNING</code>
- * indicating why the given name is discouraged,
- * otherwise a status object indicating what is wrong with
- * the name
- * @deprecated Use {@link #validateJavaScriptTypeName(String id, String sourceLevel, String complianceLevel)} instead
- */
- public static IStatus validateJavaScriptTypeName(String name) {
- return validateJavaScriptTypeName(name, CompilerOptions.VERSION_1_3,CompilerOptions.VERSION_1_3);
- }
-
- /**
- * Validate the given JavaScript type name, either simple or qualified, for the given source and compliance levels.
- * <p>
- *
- * @param name the name of a type
- * @param sourceLevel the source level
- * @param complianceLevel the compliance level
- * @return a status object with code <code>IStatus.OK</code> if
- * the given name is valid as a JavaScript type name,
- * a status with code <code>IStatus.WARNING</code>
- * indicating why the given name is discouraged,
- * otherwise a status object indicating what is wrong with
- * the name
- */
- public static IStatus validateJavaScriptTypeName(String name, String sourceLevel, String complianceLevel) {
- if (name == null) {
- return new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, -1, Messages.convention_type_nullName, null);
- }
- String trimmed = name.trim();
- if (!name.equals(trimmed)) {
- return new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, -1, Messages.convention_type_nameWithBlanks, null);
- }
- int index = name.lastIndexOf('.');
- char[] scannedID;
- if (index == -1) {
- // simple name
- scannedID = scannedIdentifier(name, sourceLevel, complianceLevel);
- } else {
- // qualified name
- String pkg = name.substring(0, index).trim();
- IStatus status = validatePackageName(pkg, sourceLevel, complianceLevel);
- if (!status.isOK()) {
- return status;
- }
- String type = name.substring(index + 1).trim();
- scannedID = scannedIdentifier(type, sourceLevel, complianceLevel);
- }
-
- if (scannedID != null) {
- IStatus status = ResourcesPlugin.getWorkspace().validateName(new String(scannedID), IResource.FILE);
- 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);
- }
- return JavaModelStatus.VERIFIED_OK;
- } else {
- return new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, -1, Messages.bind(Messages.convention_type_invalidName, name), null);
- }
- }
-
- /**
- * Validate the given function name.
- * <p>
- *
- * @param name the name of a method
- * @return a status object with code <code>IStatus.OK</code> if
- * the given name is valid as a method name, otherwise a status
- * object indicating what is wrong with the name
- * @deprecated Use {@link #validateFunctionName(String id, String sourceLevel, String complianceLevel)} instead
- */
- public static IStatus validateFunctionName(String name) {
- return validateFunctionName(name, CompilerOptions.VERSION_1_3,CompilerOptions.VERSION_1_3);
- }
-
-
- /**
- * Validate the given function name for the given source and compliance levels.
- * <p>
- *
- * @param name the name of a method
- * @param sourceLevel the source level
- * @param complianceLevel the compliance level
- * @return a status object with code <code>IStatus.OK</code> if
- * the given name is valid as a method name, otherwise a status
- * object indicating what is wrong with the name
- */
- public static IStatus validateFunctionName(String name, String sourceLevel, String complianceLevel) {
- return validateIdentifier(name, sourceLevel,complianceLevel);
- }
-
- /**
- * Validate the given package name.
- * <p>
- * The syntax of a package name corresponds to PackageName as
- * defined by PackageDeclaration.
- * <p>
- * Note that the given name must be a non-empty package name (that is, attempting to
- * validate the default package will return an error status.)
- * Also it must not contain any characters or substrings that are not valid
- * on the file system on which workspace root is located.
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @param name the name of a package
- * @return a status object with code <code>IStatus.OK</code> if
- * the given name is valid as a package name, otherwise a status
- * object indicating what is wrong with the name
- * @deprecated Use {@link #validatePackageName(String id, String sourceLevel, String complianceLevel)} instead
- */
- public static IStatus validatePackageName(String name) {
- return validatePackageName(name, CompilerOptions.VERSION_1_3,CompilerOptions.VERSION_1_3);
- }
-
- /**
- * Validate the given package name for the given source and compliance levels.
- * <p>
- * The syntax of a package name corresponds to PackageName as
- * defined by PackageDeclaration.
- * <p>
- * Note that the given name must be a non-empty package name (that is, attempting to
- * validate the default package will return an error status.)
- * Also it must not contain any characters or substrings that are not valid
- * on the file system on which workspace root is located.
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @param name the name of a package
- * @param sourceLevel the source level
- * @param complianceLevel the compliance level
- * @return a status object with code <code>IStatus.OK</code> if
- * the given name is valid as a package name, otherwise a status
- * object indicating what is wrong with the name
- */
- public static IStatus validatePackageName(String name, String sourceLevel, String complianceLevel) {
-
- if (name == null) {
- return new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, -1, Messages.convention_package_nullName, null);
- }
- int length;
- if ((length = name.length()) == 0) {
- return new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, -1, Messages.convention_package_emptyName, null);
- }
- if (name.charAt(0) == DOT || name.charAt(length-1) == DOT) {
- return new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, -1, Messages.convention_package_dotName, null);
- }
- if (CharOperation.isWhitespace(name.charAt(0)) || CharOperation.isWhitespace(name.charAt(name.length() - 1))) {
- return new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, -1, Messages.convention_package_nameWithBlanks, null);
- }
- int dot = 0;
- while (dot != -1 && dot < length-1) {
- if ((dot = name.indexOf(DOT, dot+1)) != -1 && dot < length-1 && name.charAt(dot+1) == DOT) {
- return new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, -1, Messages.convention_package_consecutiveDotsName, null);
- }
- }
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- IStatus status = workspace.validateName(new String(name), IResource.FOLDER);
- if (!status.isOK()) {
- return status;
- }
- StringTokenizer st = new StringTokenizer(name, "."); //$NON-NLS-1$
- boolean firstToken = true;
- IStatus warningStatus = null;
- while (st.hasMoreTokens()) {
- String typeName = st.nextToken();
- typeName = typeName.trim(); // grammar allows spaces
- char[] scannedID = scannedIdentifier(typeName, sourceLevel, complianceLevel);
- if (scannedID == null) {
- return new Status(IStatus.WARNING, JavaScriptCore.PLUGIN_ID, -1, Messages.bind(Messages.convention_illegalIdentifier, typeName), null);
- }
- status = workspace.validateName(new String(name), IResource.FOLDER);
- if (!status.isOK()) {
- return status;
- }
- if (firstToken && scannedID.length > 0 && ScannerHelper.isUpperCase(scannedID[0])) {
- if (warningStatus == null) {
- warningStatus = new Status(IStatus.WARNING, JavaScriptCore.PLUGIN_ID, -1, Messages.convention_package_uppercaseName, null);
- }
- }
- firstToken = false;
- }
- if (warningStatus != null) {
- return warningStatus;
- }
- return JavaModelStatus.VERIFIED_OK;
- }
-
- /**
- * Validate a given includepath location for a project, using the following rules:
- * <ul>
- * <li> Includepath entries cannot collide with each other; that is, all entry paths must be unique.
- * <li> A project entry cannot refer to itself directly (that is, a project cannot prerequisite itself).
- * <li> Includepath entries cannot coincidate or be nested in each other, except for the following scenarii listed below:
- * <li> A source/library folder can be nested in any source folder as long as the nested folder is excluded from the enclosing one. </li>
- * </ul>
- * </ul>
- *
- * Note that the includepath entries are not validated automatically. Only bound variables or containers are considered
- * in the checking process (this allows to perform a consistency check on a includepath which has references to
- * yet non existing projects, folders, ...).
- * <p>
- * This validation is intended to anticipate includepath issues prior to assigning it to a project. In particular, it will automatically
- * be performed during the includepath setting operation (if validation fails, the includepath setting will not complete).
- * <p>
- * @param javaProject the given javaScript project
- * @param rawClasspath the given includepath
- * @return a status object with code <code>IStatus.OK</code> if
- * the given includepath are compatible, otherwise a status
- * object indicating what is wrong with the includepath
- */
- public static IJavaScriptModelStatus validateClasspath(IJavaScriptProject javaProject, IIncludePathEntry[] rawClasspath) {
-
- return ClasspathEntry.validateClasspath(javaProject, rawClasspath);
- }
-
- /**
- * Returns a JavaScript model status describing the problem related to this includepath entry if any,
- * a status object with code <code>IStatus.OK</code> if the entry is fine (that is, if the
- * given includepath entry denotes a valid element to be referenced onto a includepath).
- *
- * @param project the given javaScript project
- * @param entry the given includepath entry
- * @param checkSourceAttachment a flag to determine if source attachement should be checked
- * @return a javaScript model status describing the problem related to this includepath entry if any, a status object with code <code>IStatus.OK</code> if the entry is fine
- */
- public static IJavaScriptModelStatus validateClasspathEntry(IJavaScriptProject project, IIncludePathEntry entry, boolean checkSourceAttachment){
- IJavaScriptModelStatus status = ClasspathEntry.validateClasspathEntry(project, entry, checkSourceAttachment, true/*recurse in container*/);
- if (status.getCode() == IJavaScriptModelStatusConstants.INVALID_INCLUDEPATH && ((ClasspathEntry) entry).isOptional())
- return JavaModelStatus.VERIFIED_OK;
- return status;
- }
-
- /**
- * Validate the given type variable name.
- * <p>
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @param name the name of a type variable
- * @return a status object with code <code>IStatus.OK</code> if
- * the given name is valid as a type variable name, otherwise a status
- * object indicating what is wrong with the name
- * @deprecated Use {@link #validateTypeVariableName(String id, String sourceLevel, String complianceLevel)} instead
- */
- public static IStatus validateTypeVariableName(String name) {
- return validateIdentifier(name, CompilerOptions.VERSION_1_3,CompilerOptions.VERSION_1_3);
- }
-
- /**
- * Validate the given type variable name for the given source and compliance levels.
- * <p>
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @param name the name of a type variable
- * @param sourceLevel the source level
- * @param complianceLevel the compliance level
- * @return a status object with code <code>IStatus.OK</code> if
- * the given name is valid as a type variable name, otherwise a status
- * object indicating what is wrong with the name
- */
- public static IStatus validateTypeVariableName(String name, String sourceLevel, String complianceLevel) {
- return validateIdentifier(name, sourceLevel, complianceLevel);
- }
-
- /*
- * Validate that all compiler options of the given project match keys and values
- * described in {@link JavaScriptCore#getDefaultOptions()} method.
- *
- * @param javaProject the given javaScript project
- * @param inheritJavaCoreOptions inherit project options from JavaScriptCore or not.
- * @return a status object with code <code>IStatus.OK</code> if all project
- * compiler options are valid, otherwise a status object indicating what is wrong
- * with the keys and their value.
- */
- /*
- public static IStatus validateCompilerOptions(IJavaScriptProject javaProject, boolean inheritJavaCoreOptions) {
- return validateCompilerOptions(javaProject.getOptions(inheritJavaCoreOptions));
- }
- */
-
- /*
- * Validate that all compiler options of the given project match keys and values
- * described in {@link JavaScriptCore#getDefaultOptions()} method.
- *
- * @param compilerOptions Map of options
- * @return a status object with code <code>IStatus.OK</code> if all
- * compiler options are valid, otherwise a status object indicating what is wrong
- * with the keys and their value.
- */
- /*
- public static IStatus validateCompilerOptions(Map compilerOptions) {
-
- // Get current options
- String compliance = (String) compilerOptions.get(JavaScriptCore.COMPILER_COMPLIANCE);
- String source = (String) compilerOptions.get(JavaScriptCore.COMPILER_SOURCE);
- String target = (String) compilerOptions.get(JavaScriptCore.COMPILER_CODEGEN_TARGET_PLATFORM);
- if (compliance == null && source == null && target == null) {
- return JavaModelStatus.VERIFIED_OK; // default is OK
- }
-
- // Initialize multi-status
- List errors = new ArrayList();
-
- // Set default for compliance if necessary (not set on project and not inherited...)
- if (compliance == null) {
- compliance = JavaScriptCore.getOption(JavaScriptCore.COMPILER_COMPLIANCE);
- }
-
- // Verify compliance level value and set source and target default if necessary
- long complianceLevel = 0;
- long sourceLevel = 0;
- long targetLevel = 0;
- if (JavaScriptCore.VERSION_1_3.equals(compliance)) {
- complianceLevel = ClassFileConstants.JDK1_3;
- if (source == null) {
- source = JavaScriptCore.VERSION_1_3;
- sourceLevel = ClassFileConstants.JDK1_3;
- }
- if (target == null) {
- target = JavaScriptCore.VERSION_1_1;
- targetLevel = ClassFileConstants.JDK1_1;
- }
- } else if (JavaScriptCore.VERSION_1_4.equals(compliance)) {
- complianceLevel = ClassFileConstants.JDK1_4;
- if (source == null) {
- source = JavaScriptCore.VERSION_1_3;
- sourceLevel = ClassFileConstants.JDK1_3;
- }
- if (target == null) {
- target = JavaScriptCore.VERSION_1_2;
- targetLevel = ClassFileConstants.JDK1_2;
- }
- } else if (JavaScriptCore.VERSION_1_5.equals(compliance)) {
- complianceLevel = ClassFileConstants.JDK1_5;
- if (source == null) {
- source = JavaScriptCore.VERSION_1_5;
- sourceLevel = ClassFileConstants.JDK1_5;
- }
- if (target == null) {
- target = JavaScriptCore.VERSION_1_5;
- targetLevel = ClassFileConstants.JDK1_5;
- }
- } else {
- // compliance is not valid
- errors.add(new JavaModelStatus(IStatus.ERROR, Util.bind("convention.compiler.invalidCompilerOption", compliance==null?"":compliance, JavaScriptCore.COMPILER_COMPLIANCE))); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- // Verify source value and set default for target if necessary
- if (JavaScriptCore.VERSION_1_4.equals(source)) {
- sourceLevel = ClassFileConstants.JDK1_4;
- if (target == null) {
- target = JavaScriptCore.VERSION_1_4;
- targetLevel = ClassFileConstants.JDK1_4;
- }
- } else if (JavaScriptCore.VERSION_1_5.equals(source)) {
- sourceLevel = ClassFileConstants.JDK1_5;
- if (target == null) {
- target = JavaScriptCore.VERSION_1_5;
- targetLevel = ClassFileConstants.JDK1_5;
- }
- } else if (JavaScriptCore.VERSION_1_3.equals(source)) {
- sourceLevel = ClassFileConstants.JDK1_3;
- } else {
- // source is not valid
- errors.add(new JavaModelStatus(IStatus.ERROR, Util.bind("convention.compiler.invalidCompilerOption", source==null?"":source, JavaScriptCore.COMPILER_SOURCE))); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- // Verify target value
- if (targetLevel == 0) {
- targetLevel = CompilerOptions.versionToJdkLevel(target);
- if (targetLevel == 0) {
- // target is not valid
- errors.add(new JavaModelStatus(IStatus.ERROR, Util.bind("convention.compiler.invalidCompilerOption", target==null?"":target, JavaScriptCore.COMPILER_CODEGEN_TARGET_PLATFORM))); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
-
- // Check and set compliance/source/target compatibilities (only if they have valid values)
- if (complianceLevel != 0 && sourceLevel != 0 && targetLevel != 0) {
- // target must be 1.5 if source is 1.5
- if (sourceLevel >= ClassFileConstants.JDK1_5 && targetLevel < ClassFileConstants.JDK1_5) {
- errors.add(new JavaModelStatus(IStatus.ERROR, Util.bind("convention.compiler.incompatibleTargetForSource", target, JavaScriptCore.VERSION_1_5))); //$NON-NLS-1$
- }
- else
- // target must be 1.4 if source is 1.4
- if (sourceLevel >= ClassFileConstants.JDK1_4 && targetLevel < ClassFileConstants.JDK1_4) {
- errors.add(new JavaModelStatus(IStatus.ERROR, Util.bind("convention.compiler.incompatibleTargetForSource", target, JavaScriptCore.VERSION_1_4))); //$NON-NLS-1$
- }
- // target cannot be greater than compliance level
- if (complianceLevel < targetLevel){
- errors.add(new JavaModelStatus(IStatus.ERROR, Util.bind("convention.compiler.incompatibleComplianceForTarget", compliance, JavaScriptCore.VERSION_1_4))); //$NON-NLS-1$
- }
- // compliance must be 1.5 if source is 1.5
- if (source.equals(JavaScriptCore.VERSION_1_5) && complianceLevel < ClassFileConstants.JDK1_5) {
- errors.add(new JavaModelStatus(IStatus.ERROR, Util.bind("convention.compiler.incompatibleComplianceForSource", compliance, JavaScriptCore.VERSION_1_5))); //$NON-NLS-1$
- } else
- // compliance must be 1.4 if source is 1.4
- if (source.equals(JavaScriptCore.VERSION_1_4) && complianceLevel < ClassFileConstants.JDK1_4) {
- errors.add(new JavaModelStatus(IStatus.ERROR, Util.bind("convention.compiler.incompatibleComplianceForSource", compliance, JavaScriptCore.VERSION_1_4))); //$NON-NLS-1$
- }
- }
-
- // Return status
- int size = errors.size();
- switch (size) {
- case 0:
- return JavaModelStatus.VERIFIED_OK;
- case 1:
- return (IStatus) errors.get(0);
- default:
- IJavaScriptModelStatus[] allStatus = new IJavaScriptModelStatus[size];
- errors.toArray(allStatus);
- return JavaModelStatus.newMultiStatus(allStatus);
- }
- }
- */
-}
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
deleted file mode 100644
index a9d8be4b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/JavaScriptCore.java
+++ /dev/null
@@ -1,4116 +0,0 @@
-/*******************************************************************************
- * 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
- * IBM Corporation - added the following constants:
- * COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE
- * COMPILER_PB_STATIC_ACCESS_RECEIVER
- * COMPILER_TASK_TAGS
- * CORE_CIRCULAR_CLASSPATH
- * CORE_INCOMPLETE_CLASSPATH
- * IBM Corporation - added run(IWorkspaceRunnable, IProgressMonitor)
- * IBM Corporation - added exclusion patterns to source includepath entries
- * IBM Corporation - added specific output location to source includepath entries
- * IBM Corporation - added the following constants:
- * CORE_JAVA_BUILD_CLEAN_OUTPUT_FOLDER
- * CORE_JAVA_BUILD_RECREATE_MODIFIED_CLASS_FILES_IN_OUTPUT_FOLDER
- * CLEAN
- * IBM Corporation - added getJsGlobalScopeContainerInitializer(String)
- * IBM Corporation - added the following constants:
- * CODEASSIST_ARGUMENT_PREFIXES
- * CODEASSIST_ARGUMENT_SUFFIXES
- * CODEASSIST_FIELD_PREFIXES
- * CODEASSIST_FIELD_SUFFIXES
- * CODEASSIST_LOCAL_PREFIXES
- * CODEASSIST_LOCAL_SUFFIXES
- * CODEASSIST_STATIC_FIELD_PREFIXES
- * CODEASSIST_STATIC_FIELD_SUFFIXES
- * COMPILER_PB_CHAR_ARRAY_IN_STRING_CONCATENATION
- * IBM Corporation - added the following constants:
- * COMPILER_PB_LOCAL_VARIABLE_HIDING
- * COMPILER_PB_SPECIAL_PARAMETER_HIDING_FIELD
- * COMPILER_PB_FIELD_HIDING
- * COMPILER_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT
- * CORE_INCOMPATIBLE_JDK_LEVEL
- * VERSION_1_5
- * COMPILER_PB_EMPTY_STATEMENT
- * IBM Corporation - added the following constants:
- * COMPILER_PB_INDIRECT_STATIC_ACCESS
- * COMPILER_PB_BOOLEAN_METHOD_THROWING_EXCEPTION
- * COMPILER_PB_UNNECESSARY_CAST
- * IBM Corporation - added the following constants:
- * COMPILER_PB_INVALID_JAVADOC
- * COMPILER_PB_INVALID_JAVADOC_TAGS
- * COMPILER_PB_INVALID_JAVADOC_TAGS_VISIBILITY
- * COMPILER_PB_MISSING_JAVADOC_TAGS
- * COMPILER_PB_MISSING_JAVADOC_TAGS_VISIBILITY
- * COMPILER_PB_MISSING_JAVADOC_TAGS_OVERRIDING
- * COMPILER_PB_MISSING_JAVADOC_COMMENTS
- * COMPILER_PB_MISSING_JAVADOC_COMMENTS_VISIBILITY
- * COMPILER_PB_MISSING_JAVADOC_COMMENTS_OVERRIDING
- * COMPILER_PB_DEPRECATION_WHEN_OVERRIDING_DEPRECATED_METHOD
- * COMPILER_PB_UNUSED_DECLARED_THROWN_EXCEPTION_WHEN_OVERRIDING
- * IBM Corporation - added the following constants:
- * TIMEOUT_FOR_PARAMETER_NAME_FROM_ATTACHED_JAVADOC
- * IBM Corporation - added the following constants:
- * COMPILER_PB_FALLTHROUGH_CASE
- * COMPILER_PB_PARAMETER_ASSIGNMENT
- * COMPILER_PB_NULL_REFERENCE
- * IBM Corporation - added the following constants:
- * CODEASSIST_DEPRECATION_CHECK
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core;
-
-import java.io.File;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Hashtable;
-import java.util.Map;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IMarkerDelta;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceChangeEvent;
-import org.eclipse.core.resources.IResourceChangeListener;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.FileLocator;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IExtension;
-import org.eclipse.core.runtime.IExtensionPoint;
-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.core.runtime.Platform;
-import org.eclipse.core.runtime.Plugin;
-import org.eclipse.core.runtime.QualifiedName;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.core.runtime.jobs.ISchedulingRule;
-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.SearchPattern;
-import org.eclipse.wst.jsdt.core.search.TypeNameRequestor;
-import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants;
-import org.eclipse.wst.jsdt.internal.compiler.impl.CompilerOptions;
-import org.eclipse.wst.jsdt.internal.compiler.util.SuffixConstants;
-import org.eclipse.wst.jsdt.internal.core.BatchOperation;
-import org.eclipse.wst.jsdt.internal.core.ClasspathAccessRule;
-import org.eclipse.wst.jsdt.internal.core.ClasspathAttribute;
-import org.eclipse.wst.jsdt.internal.core.ClasspathEntry;
-import org.eclipse.wst.jsdt.internal.core.CreateTypeHierarchyOperation;
-import org.eclipse.wst.jsdt.internal.core.DefaultWorkingCopyOwner;
-import org.eclipse.wst.jsdt.internal.core.JavaModel;
-import org.eclipse.wst.jsdt.internal.core.JavaModelManager;
-import org.eclipse.wst.jsdt.internal.core.JavaProject;
-import org.eclipse.wst.jsdt.internal.core.Region;
-import org.eclipse.wst.jsdt.internal.core.SetContainerOperation;
-import org.eclipse.wst.jsdt.internal.core.SetVariablesOperation;
-import org.eclipse.wst.jsdt.internal.core.UserLibraryManager;
-import org.eclipse.wst.jsdt.internal.core.builder.JavaBuilder;
-import org.eclipse.wst.jsdt.internal.core.builder.State;
-import org.eclipse.wst.jsdt.internal.core.util.MementoTokenizer;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-import org.osgi.framework.BundleContext;
-
-/**
- * The plug-in runtime class for the JavaScript model plug-in containing the core
- * (UI-free) support for JavaScript projects.
- * <p>
- * Like all plug-in runtime classes (subclasses of <code>Plugin</code>), this
- * class is automatically instantiated by the platform when the plug-in gets
- * activated. Clients must not attempt to instantiate plug-in runtime classes
- * directly.
- * </p>
- * <p>
- * The single instance of this class can be accessed from any plug-in declaring
- * the JavaScript model plug-in as a prerequisite via
- * <code>JavaScriptCore.getJavaCore()</code>. The JavaScript model plug-in will be activated
- * automatically if not already active.
- * </p>
- *
- * 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 final class JavaScriptCore extends Plugin {
-
- public static final boolean IS_ECMASCRIPT4=false;
-
- private static final IResource[] NO_GENERATED_RESOURCES = new IResource[0];
-
-
- private static Plugin JAVA_CORE_PLUGIN = null;
- /**
- * The plug-in identifier of the JavaScript core support
- * (value <code>"org.eclipse.wst.jsdt.core"</code>).
- */
- public static final String PLUGIN_ID = "org.eclipse.wst.jsdt.core" ; //$NON-NLS-1$
-
- /**
- * The identifier for the JavaScript validator
- * (value <code>"org.eclipse.wst.jsdt.core.javascriptValidator"</code>).
- */
- public static final String BUILDER_ID = PLUGIN_ID + ".javascriptValidator" ; //$NON-NLS-1$
-
- /**
- * The identifier for the JavaScript model
- * (value <code>"org.eclipse.wst.jsdt.core.jsmodel"</code>).
- */
- public static final String MODEL_ID = PLUGIN_ID + ".jsmodel" ; //$NON-NLS-1$
-
- /**
- * The identifier for the JavaScript nature
- * (value <code>"org.eclipse.wst.jsdt.core.jsnature"</code>).
- * The presence of this nature on a project indicates that it is
- * JavaScript-capable.
- *
- * @see org.eclipse.core.resources.IProject#hasNature(java.lang.String)
- */
- public static final String NATURE_ID = PLUGIN_ID + ".jsNature" ; //$NON-NLS-1$
-
- /**
- * Name of the handle id attribute in a JavaScript marker.
- */
- protected static final String ATT_HANDLE_ID =
- "org.eclipse.wst.jsdt.internal.core.JavaModelManager.handleId" ; //$NON-NLS-1$
-
- /**
- * Name of the User Library Container id.
- */
- public static final String USER_LIBRARY_CONTAINER_ID= "org.eclipse.wst.jsdt.USER_LIBRARY"; //$NON-NLS-1$
-
- // *************** Possible IDs for configurable options. ********************
-
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_LOCAL_VARIABLE_ATTR = PLUGIN_ID + ".compiler.debug.localVariable"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_LINE_NUMBER_ATTR = PLUGIN_ID + ".compiler.debug.lineNumber"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_SOURCE_FILE_ATTR = PLUGIN_ID + ".compiler.debug.sourceFile"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_CODEGEN_UNUSED_LOCAL = PLUGIN_ID + ".compiler.codegen.unusedLocal"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_CODEGEN_TARGET_PLATFORM = PLUGIN_ID + ".compiler.codegen.targetPlatform"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_CODEGEN_INLINE_JSR_BYTECODE = PLUGIN_ID + ".compiler.codegen.inlineJsrBytecode"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_DOC_COMMENT_SUPPORT = PLUGIN_ID + ".compiler.doc.comment.support"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- * @deprecated - discontinued since turning off would violate language specs
- */
- public static final String COMPILER_PB_UNREACHABLE_CODE = PLUGIN_ID + ".compiler.problem.unreachableCode"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- * @deprecated - discontinued since turning off would violate language specs
- */
- public static final String COMPILER_PB_INVALID_IMPORT = PLUGIN_ID + ".compiler.problem.invalidImport"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_UNDEFINED_FIELD = PLUGIN_ID + ".compiler.problem.undefinedField"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_METHOD_WITH_CONSTRUCTOR_NAME = PLUGIN_ID + ".compiler.problem.methodWithConstructorName"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_DEPRECATION = PLUGIN_ID + ".compiler.problem.deprecation"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE = PLUGIN_ID + ".compiler.problem.deprecationInDeprecatedCode"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_DEPRECATION_WHEN_OVERRIDING_DEPRECATED_METHOD = "org.eclipse.wst.jsdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_HIDDEN_CATCH_BLOCK = PLUGIN_ID + ".compiler.problem.hiddenCatchBlock"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_UNUSED_LOCAL = PLUGIN_ID + ".compiler.problem.unusedLocal"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_UNUSED_PARAMETER = PLUGIN_ID + ".compiler.problem.unusedParameter"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_UNUSED_PARAMETER_WHEN_IMPLEMENTING_ABSTRACT = PLUGIN_ID + ".compiler.problem.unusedParameterWhenImplementingAbstract"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_UNUSED_PARAMETER_WHEN_OVERRIDING_CONCRETE = PLUGIN_ID + ".compiler.problem.unusedParameterWhenOverridingConcrete"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_UNUSED_PARAMETER_INCLUDE_DOC_COMMENT_REFERENCE = PLUGIN_ID + ".compiler.problem.unusedParameterIncludeDocCommentReference"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_UNUSED_IMPORT = PLUGIN_ID + ".compiler.problem.unusedImport"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_NON_NLS_STRING_LITERAL = PLUGIN_ID + ".compiler.problem.nonExternalizedStringLiteral"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_ASSERT_IDENTIFIER = PLUGIN_ID + ".compiler.problem.assertIdentifier"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_STATIC_ACCESS_RECEIVER = PLUGIN_ID + ".compiler.problem.staticAccessReceiver"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_INDIRECT_STATIC_ACCESS = PLUGIN_ID + ".compiler.problem.indirectStaticAccess"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_NO_EFFECT_ASSIGNMENT = PLUGIN_ID + ".compiler.problem.noEffectAssignment"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_UNUSED_PRIVATE_MEMBER = PLUGIN_ID + ".compiler.problem.unusedPrivateMember"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_LOCAL_VARIABLE_HIDING = PLUGIN_ID + ".compiler.problem.localVariableHiding"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_SPECIAL_PARAMETER_HIDING_FIELD = PLUGIN_ID + ".compiler.problem.specialParameterHidingField"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_FIELD_HIDING = PLUGIN_ID + ".compiler.problem.fieldHiding"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_TYPE_PARAMETER_HIDING = PLUGIN_ID + ".compiler.problem.typeParameterHiding"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT = PLUGIN_ID + ".compiler.problem.possibleAccidentalBooleanAssignment"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_FALLTHROUGH_CASE = PLUGIN_ID + ".compiler.problem.fallthroughCase"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_EMPTY_STATEMENT = PLUGIN_ID + ".compiler.problem.emptyStatement"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_BOOLEAN_METHOD_THROWING_EXCEPTION = PLUGIN_ID + ".compiler.problem.booleanMethodThrowingException"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_UNNECESSARY_TYPE_CHECK = PLUGIN_ID + ".compiler.problem.unnecessaryTypeCheck"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_UNNECESSARY_ELSE = PLUGIN_ID + ".compiler.problem.unnecessaryElse"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_UNDOCUMENTED_EMPTY_BLOCK = PLUGIN_ID + ".compiler.problem.undocumentedEmptyBlock"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_FINALLY_BLOCK_NOT_COMPLETING = PLUGIN_ID + ".compiler.problem.finallyBlockNotCompletingNormally"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_UNUSED_DECLARED_THROWN_EXCEPTION = PLUGIN_ID + ".compiler.problem.unusedDeclaredThrownException"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_UNUSED_DECLARED_THROWN_EXCEPTION_WHEN_OVERRIDING = PLUGIN_ID + ".compiler.problem.unusedDeclaredThrownExceptionWhenOverriding"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_UNQUALIFIED_FIELD_ACCESS = PLUGIN_ID + ".compiler.problem.unqualifiedFieldAccess"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- * @deprecated - got renamed into {@link #COMPILER_PB_UNCHECKED_TYPE_OPERATION}
- */
- public static final String COMPILER_PB_UNSAFE_TYPE_OPERATION = PLUGIN_ID + ".compiler.problem.uncheckedTypeOperation"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_UNCHECKED_TYPE_OPERATION = PLUGIN_ID + ".compiler.problem.uncheckedTypeOperation"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_RAW_TYPE_REFERENCE = PLUGIN_ID + ".compiler.problem.rawTypeReference"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_FINAL_PARAMETER_BOUND = PLUGIN_ID + ".compiler.problem.finalParameterBound"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_VARARGS_ARGUMENT_NEED_CAST = PLUGIN_ID + ".compiler.problem.varargsArgumentNeedCast"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_MISSING_OVERRIDE_ANNOTATION = PLUGIN_ID + ".compiler.problem.missingOverrideAnnotation"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_MISSING_DEPRECATED_ANNOTATION = PLUGIN_ID + ".compiler.problem.missingDeprecatedAnnotation"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_UNUSED_LABEL = PLUGIN_ID + ".compiler.problem.unusedLabel"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_INVALID_JAVADOC = PLUGIN_ID + ".compiler.problem.invalidJavadoc"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_INVALID_JAVADOC_TAGS = PLUGIN_ID + ".compiler.problem.invalidJavadocTags"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_INVALID_JAVADOC_TAGS__DEPRECATED_REF = PLUGIN_ID + ".compiler.problem.invalidJavadocTagsDeprecatedRef"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_INVALID_JAVADOC_TAGS__NOT_VISIBLE_REF = PLUGIN_ID + ".compiler.problem.invalidJavadocTagsNotVisibleRef"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_INVALID_JAVADOC_TAGS_VISIBILITY = PLUGIN_ID + ".compiler.problem.invalidJavadocTagsVisibility"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_MISSING_JAVADOC_TAGS = PLUGIN_ID + ".compiler.problem.missingJavadocTags"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_MISSING_JAVADOC_TAGS_VISIBILITY = PLUGIN_ID + ".compiler.problem.missingJavadocTagsVisibility"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_MISSING_JAVADOC_TAGS_OVERRIDING = PLUGIN_ID + ".compiler.problem.missingJavadocTagsOverriding"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_MISSING_JAVADOC_COMMENTS = PLUGIN_ID + ".compiler.problem.missingJavadocComments"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_MISSING_JAVADOC_COMMENTS_VISIBILITY = PLUGIN_ID + ".compiler.problem.missingJavadocCommentsVisibility"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_MISSING_JAVADOC_COMMENTS_OVERRIDING = PLUGIN_ID + ".compiler.problem.missingJavadocCommentsOverriding"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_MAX_PER_UNIT = PLUGIN_ID + ".compiler.maxProblemPerUnit"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_FATAL_OPTIONAL_ERROR = PLUGIN_ID + ".compiler.problem.fatalOptionalError"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_PARAMETER_ASSIGNMENT = PLUGIN_ID + ".compiler.problem.parameterAssignment"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_SEMANTIC_VALIDATION = "semanticValidation"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_SOURCE = PLUGIN_ID + ".compiler.source"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_COMPLIANCE = PLUGIN_ID + ".compiler.compliance"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_TASK_PRIORITIES = PLUGIN_ID + ".compiler.taskPriorities"; //$NON-NLS-1$
- /**
- * Possible configurable option value for COMPILER_TASK_PRIORITIES.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_TASK_PRIORITY_HIGH = "HIGH"; //$NON-NLS-1$
- /**
- * Possible configurable option value for COMPILER_TASK_PRIORITIES.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_TASK_PRIORITY_LOW = "LOW"; //$NON-NLS-1$
- /**
- * Possible configurable option value for COMPILER_TASK_PRIORITIES.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_TASK_PRIORITY_NORMAL = "NORMAL"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_TASK_TAGS = PLUGIN_ID + ".compiler.taskTags"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_TASK_CASE_SENSITIVE = PLUGIN_ID + ".compiler.taskCaseSensitive"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_FORBIDDEN_REFERENCE = PLUGIN_ID + ".compiler.problem.forbiddenReference"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_DISCOURAGED_REFERENCE = PLUGIN_ID + ".compiler.problem.discouragedReference"; //$NON-NLS-1$
-
- /* START -------------------------------- Bug 203292 Type/Method/Filed resolution error configuration --------------------- */
- public static final String UNRESOLVED_TYPE_REFERENCE = PLUGIN_ID + ".compiler.problem.unresolvedTypeReference"; //$NON-NLS-1$
- public static final String UNRESOLVED_FIELD_REFERENCE = PLUGIN_ID + ".compiler.problem.unresolvedFieldReference"; //$NON-NLS-1$
- public static final String UNRESOLVED_METHOD_REFERENCE = PLUGIN_ID + ".compiler.problem.unresolvedMethodReference"; //$NON-NLS-1$
- /* END -------------------------------- Bug 203292 Type/Method/Filed resolution error configuration --------------------- */
-
- /* START -------------------------------- Bug 197884 Loosly defined var (for statement) and optional semi-colon --------------------- */
- public static final String LOOSE_VAR_DECL = PLUGIN_ID + ".compiler.problem.looseVarDecleration"; //$NON-NLS-1$
- public static final String OPTIONAL_SEMICOLON = PLUGIN_ID + ".compiler.problem.optionalSemicolon"; //$NON-NLS-1$
- /* END -------------------------------- Bug 197884 Loosly defined var (for statement) and optional semi-colon --------------------- */
-
-
- /**
-
- *
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_SUPPRESS_WARNINGS = PLUGIN_ID + ".compiler.problem.suppressWarnings"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_UNHANDLED_WARNING_TOKEN = PLUGIN_ID + ".compiler.problem.unhandledWarningToken"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_NULL_REFERENCE = PLUGIN_ID + ".compiler.problem.nullReference"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_POTENTIAL_NULL_REFERENCE = PLUGIN_ID + ".compiler.problem.potentialNullReference"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_DUPLICATE_LOCAL_VARIABLES = PLUGIN_ID + ".compiler.problem.duplicateLocalVariables"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_REDUNDANT_NULL_CHECK = PLUGIN_ID + ".compiler.problem.redundantNullCheck"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_UNINITIALIZED_LOCAL_VARIABLE = PLUGIN_ID + ".compiler.problem.uninitializedLocalVariable"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_UNINITIALIZED_GLOBAL_VARIABLE = PLUGIN_ID + ".compiler.problem.uninitializedGlobalVariable"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_PB_OVERRIDING_METHOD_WITHOUT_SUPER_INVOCATION = PLUGIN_ID + ".compiler.problem.overridingMethodWithoutSuperInvocation"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String CORE_JAVA_BUILD_ORDER = PLUGIN_ID + ".computeJavaBuildOrder"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String CORE_JAVA_BUILD_RESOURCE_COPY_FILTER = PLUGIN_ID + ".builder.resourceCopyExclusionFilter"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String CORE_JAVA_BUILD_DUPLICATE_RESOURCE = PLUGIN_ID + ".builder.duplicateResourceTask"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String CORE_JAVA_BUILD_CLEAN_OUTPUT_FOLDER = PLUGIN_ID + ".builder.cleanOutputFolder"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String CORE_JAVA_BUILD_RECREATE_MODIFIED_CLASS_FILES_IN_OUTPUT_FOLDER = PLUGIN_ID + ".builder.recreateModifiedClassFileInOutputFolder"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String CORE_INCOMPLETE_CLASSPATH = PLUGIN_ID + ".incompleteClasspath"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String CORE_CIRCULAR_CLASSPATH = PLUGIN_ID + ".circularClasspath"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String CORE_INCOMPATIBLE_JDK_LEVEL = PLUGIN_ID + ".incompatibleJDKLevel"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String CORE_JAVA_BUILD_INVALID_CLASSPATH = PLUGIN_ID + ".builder.invalidClasspath"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String CORE_ENCODING = PLUGIN_ID + ".encoding"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String CORE_ENABLE_CLASSPATH_EXCLUSION_PATTERNS = PLUGIN_ID + ".classpath.exclusionPatterns"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS = PLUGIN_ID + ".classpath.multipleOutputLocations"; //$NON-NLS-1$
- /**
- * Default task tag
- * @deprecated Use {@link #DEFAULT_TASK_TAGS} instead
- */
- public static final String DEFAULT_TASK_TAG = "TODO"; //$NON-NLS-1$
- /**
- * Default task priority
- * @deprecated Use {@link #DEFAULT_TASK_PRIORITIES} instead
- */
- public static final String DEFAULT_TASK_PRIORITY = "NORMAL"; //$NON-NLS-1$
- /**
- * Default task tag
- */
- public static final String DEFAULT_TASK_TAGS = "TODO,FIXME,XXX"; //$NON-NLS-1$
- /**
- * Default task priority
- */
- public static final String DEFAULT_TASK_PRIORITIES = "NORMAL,HIGH,NORMAL"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String CODEASSIST_VISIBILITY_CHECK = PLUGIN_ID + ".codeComplete.visibilityCheck"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String CODEASSIST_DEPRECATION_CHECK = PLUGIN_ID + ".codeComplete.deprecationCheck"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String CODEASSIST_CAMEL_CASE_MATCH = PLUGIN_ID + ".codeComplete.camelCaseMatch"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String CODEASSIST_IMPLICIT_QUALIFICATION = PLUGIN_ID + ".codeComplete.forceImplicitQualification"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String CODEASSIST_FIELD_PREFIXES = PLUGIN_ID + ".codeComplete.fieldPrefixes"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String CODEASSIST_STATIC_FIELD_PREFIXES = PLUGIN_ID + ".codeComplete.staticFieldPrefixes"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String CODEASSIST_LOCAL_PREFIXES = PLUGIN_ID + ".codeComplete.localPrefixes"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String CODEASSIST_ARGUMENT_PREFIXES = PLUGIN_ID + ".codeComplete.argumentPrefixes"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String CODEASSIST_FIELD_SUFFIXES = PLUGIN_ID + ".codeComplete.fieldSuffixes"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String CODEASSIST_STATIC_FIELD_SUFFIXES = PLUGIN_ID + ".codeComplete.staticFieldSuffixes"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String CODEASSIST_LOCAL_SUFFIXES = PLUGIN_ID + ".codeComplete.localSuffixes"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String CODEASSIST_ARGUMENT_SUFFIXES = PLUGIN_ID + ".codeComplete.argumentSuffixes"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String CODEASSIST_FORBIDDEN_REFERENCE_CHECK= PLUGIN_ID + ".codeComplete.forbiddenReferenceCheck"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String CODEASSIST_DISCOURAGED_REFERENCE_CHECK= PLUGIN_ID + ".codeComplete.discouragedReferenceCheck"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String CODEASSIST_SUGGEST_STATIC_IMPORTS= PLUGIN_ID + ".codeComplete.suggestStaticImports"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String TIMEOUT_FOR_PARAMETER_NAME_FROM_ATTACHED_JAVADOC = PLUGIN_ID + ".timeoutForParameterNameFromAttachedJavadoc"; //$NON-NLS-1$
-
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions()
- */
- public static final String GENERATE = "generate"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions()
- */
- public static final String DO_NOT_GENERATE = "do not generate"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions()
- */
- public static final String PRESERVE = "preserve"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions()
- */
- public static final String OPTIMIZE_OUT = "optimize out"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions()
- */
- public static final String VERSION_1_1 = "1.1"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions()
- */
- public static final String VERSION_1_2 = "1.2"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions()
- */
- public static final String VERSION_1_3 = "1.3"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions()
- */
- public static final String VERSION_1_4 = "1.4"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions()
- */
- public static final String VERSION_1_5 = "1.5"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions()
- */
- public static final String VERSION_1_6 = "1.6"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions()
- */
- public static final String VERSION_1_7 = "1.7"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions()
- */
- public static final String ABORT = "abort"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions()
- */
- public static final String ERROR = "error"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions()
- */
- public static final String WARNING = "warning"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions()
- */
- public static final String IGNORE = "ignore"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions()
- */
- public static final String COMPUTE = "compute"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions()
- */
- public static final String INSERT = "insert"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions()
- */
- public static final String DO_NOT_INSERT = "do not insert"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions()
- */
- public static final String PRESERVE_ONE = "preserve one"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions()
- */
- public static final String CLEAR_ALL = "clear all"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions()
- */
- public static final String NORMAL = "normal"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions()
- */
- public static final String COMPACT = "compact"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions()
- */
- public static final String TAB = "tab"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions()
- */
- public static final String SPACE = "space"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions()
- */
- public static final String ENABLED = "enabled"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions()
- */
- public static final String DISABLED = "disabled"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions()
- */
- public static final String CLEAN = "clean"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions()
- */
- public static final String PUBLIC = "public"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions()
- */
- public static final String PROTECTED = "protected"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions()
- */
- public static final String DEFAULT = "default"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions()
- */
- public static final String PRIVATE = "private"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions()
- */
- public static final String NEVER = "never"; //$NON-NLS-1$
-
- /**
- * Value of the content-type for JavaScript source files. Use this value to retrieve the JavaScript content type
- * from the content type manager, and to add new JavaScript-like extensions to this content type.
- *
- * @see org.eclipse.core.runtime.content.IContentTypeManager#getContentType(String)
- * @see #getJavaScriptLikeExtensions()
- */
- public static final String JAVA_SOURCE_CONTENT_TYPE = JavaScriptCore.PLUGIN_ID+".jsSource" ; //$NON-NLS-1$
-
-
- public static final String READ_ONLY_SOURCE_PROPERTY = "readOnlyResource" ; //$NON-NLS-1$
-
- /**
- * Creates the JavaScript core plug-in.
- * <p>
- * The plug-in instance is created automatically by the
- * Eclipse platform. Clients must not call.
- * </p>
- *
- */
- public JavaScriptCore() {
- super();
- JAVA_CORE_PLUGIN = this;
- }
-
- /**
- * Adds the given listener for changes to JavaScript elements.
- * Has no effect if an identical listener is already registered.
- *
- * This listener will only be notified during the POST_CHANGE resource change notification
- * and any reconcile operation (POST_RECONCILE).
- * For finer control of the notification, use <code>addElementChangedListener(IElementChangedListener,int)</code>,
- * which allows to specify a different eventMask.
- *
- * @param listener the listener
- * @see ElementChangedEvent
- */
- public static void addElementChangedListener(IElementChangedListener listener) {
- addElementChangedListener(listener, ElementChangedEvent.POST_CHANGE | ElementChangedEvent.POST_RECONCILE);
- }
-
- /**
- * Adds the given listener for changes to JavaScript elements.
- * Has no effect if an identical listener is already registered.
- * After completion of this method, the given listener will be registered for exactly
- * the specified events. If they were previously registered for other events, they
- * will be deregistered.
- * <p>
- * Once registered, a listener starts receiving notification of changes to
- * javaScript elements in the model. The listener continues to receive
- * notifications until it is replaced or removed.
- * </p>
- * <p>
- * Listeners can listen for several types of event as defined in <code>ElementChangeEvent</code>.
- * Clients are free to register for any number of event types however if they register
- * for more than one, it is their responsibility to ensure they correctly handle the
- * case where the same javaScript element change shows up in multiple notifications.
- * Clients are guaranteed to receive only the events for which they are registered.
- * </p>
- *
- * @param listener the listener
- * @param eventMask the bit-wise OR of all event types of interest to the listener
- * @see IElementChangedListener
- * @see ElementChangedEvent
- * @see #removeElementChangedListener(IElementChangedListener)
- */
- public static void addElementChangedListener(IElementChangedListener listener, int eventMask) {
- JavaModelManager.getJavaModelManager().deltaState.addElementChangedListener(listener, eventMask);
- }
-
- /**
- * Configures the given marker attribute map for the given JavaScript element.
- * Used for markers, which denote a JavaScript element rather than a resource.
- *
- * @param attributes the mutable marker attribute map (key type: <code>String</code>,
- * value type: <code>String</code>)
- * @param element the JavaScript element for which the marker needs to be configured
- */
- public static void addJavaScriptElementMarkerAttributes(
- Map attributes,
- IJavaScriptElement element) {
- if (element instanceof IMember)
- element = ((IMember) element).getClassFile();
- if (attributes != null && element != null)
- attributes.put(ATT_HANDLE_ID, element.getHandleIdentifier());
- }
-
- /**
- * Adds the given listener for resource change events of the given types to the JavaScript core.
- * The listener is guaranteed to be notified of the resource change event before
- * the JavaScript core starts processing the resource change event itself.
- * <p>
- * If an identical listener is already registered, the given event types are added to the event types
- * of interest to the listener.
- * </p>
- * <p>
- * Supported event types are:
- * <ul>
- * <li>{@link IResourceChangeEvent#PRE_BUILD}</li>
- * <li>{@link IResourceChangeEvent#POST_BUILD}</li>
- * <li>{@link IResourceChangeEvent#POST_CHANGE}</li>
- * <li>{@link IResourceChangeEvent#PRE_DELETE}</li>
- * <li>{@link IResourceChangeEvent#PRE_CLOSE}</li>
- * </ul>
- * This list may increase in the future.
- * </p>
- *
- * @param listener the listener
- * @param eventMask the bit-wise OR of all event types of interest to the
- * listener
- * @see #removePreProcessingResourceChangedListener(IResourceChangeListener)
- * @see IResourceChangeEvent
- */
- public static void addPreProcessingResourceChangedListener(IResourceChangeListener listener, int eventMask) {
- JavaModelManager.getJavaModelManager().deltaState.addPreResourceChangedListener(listener, eventMask);
- }
-
- /**
- * Configures the given marker for the given JavaScript element.
- * Used for markers, which denote a JavaScript element rather than a resource.
- *
- * @param marker the marker to be configured
- * @param element the JavaScript element for which the marker needs to be configured
- * @exception CoreException if the <code>IMarker.setAttribute</code> on the marker fails
- */
- public void configureJavaScriptElementMarker(IMarker marker, IJavaScriptElement element)
- throws CoreException {
- if (element instanceof IMember)
- element = ((IMember) element).getClassFile();
- if (marker != null && element != null)
- marker.setAttribute(ATT_HANDLE_ID, element.getHandleIdentifier());
- }
-
- /**
- * Returns the JavaScript model element corresponding to the given handle identifier
- * generated by <code>IJavaScriptElement.getHandleIdentifier()</code>, or
- * <code>null</code> if unable to create the associated element.
- *
- * @param handleIdentifier the given handle identifier
- * @return the JavaScript element corresponding to the handle identifier
- */
- public static IJavaScriptElement create(String handleIdentifier) {
- return create(handleIdentifier, DefaultWorkingCopyOwner.PRIMARY);
- }
-
- /**
- * Returns the JavaScript model element corresponding to the given handle identifier
- * generated by <code>IJavaScriptElement.getHandleIdentifier()</code>, or
- * <code>null</code> if unable to create the associated element.
- * If the returned JavaScript element is an <code>IJavaScriptUnit</code>, its owner
- * is the given owner if such a working copy exists, otherwise the javaScript unit
- * is a primary javaScript unit.
- *
- * @param handleIdentifier the given handle identifier
- * @param owner the owner of the returned javaScript unit, ignored if the returned
- * element is not a javaScript unit
- * @return the JavaScript element corresponding to the handle identifier
- */
- public static IJavaScriptElement create(String handleIdentifier, WorkingCopyOwner owner) {
- if (handleIdentifier == null) {
- return null;
- }
- MementoTokenizer memento = new MementoTokenizer(handleIdentifier);
- JavaModel model = JavaModelManager.getJavaModelManager().getJavaModel();
- return model.getHandleFromMemento(memento, owner);
- }
-
- /**
- * Returns the JavaScript element corresponding to the given file, or
- * <code>null</code> if unable to associate the given file
- * with a JavaScript element.
- *
- * <p>The file must be one of:<ul>
- * <li>a file with one of the {@link JavaScriptCore#getJavaScriptLikeExtensions()
- * JavaScript-like extensions} - the element returned is the corresponding <code>IJavaScriptUnit</code></li>
- * <li>a <code>.class</code> file - the element returned is the corresponding <code>IClassFile</code></li>
- * <li>a <code>.jar</code> file - the element returned is the corresponding <code>IPackageFragmentRoot</code></li>
- * </ul>
- * <p>
- * Creating a JavaScript element has the side effect of creating and opening all of the
- * element's parents if they are not yet open.
- *
- * @param file the given file
- * @return the JavaScript element corresponding to the given file, or
- * <code>null</code> if unable to associate the given file
- * with a JavaScript element
- */
- public static IJavaScriptElement create(IFile file) {
- return JavaModelManager.create(file, null/*unknown javaScript project*/);
- }
- /**
- * Returns the source folder (package fragment or package fragment root) corresponding to the given folder, or
- * <code>null</code> if unable to associate the given folder with a JavaScript element.
- * <p>
- * Note that a package fragment root is returned rather than a default package.
- * <p>
- * Creating a JavaScript element has the side effect of creating and opening all of the
- * element's parents if they are not yet open.
- *
- * @param folder the given folder
- * @return the package fragment or package fragment root corresponding to the given folder, or
- * <code>null</code> if unable to associate the given folder with a JavaScript element
- */
- public static IJavaScriptElement create(IFolder folder) {
- return JavaModelManager.create(folder, null/*unknown javaScript project*/);
- }
- /**
- * Returns the JavaScript project corresponding to the given project.
- * <p>
- * Creating a JavaScript Project has the side effect of creating and opening all of the
- * project's parents if they are not yet open.
- * <p>
- * Note that no check is done at this time on the existence or the javaScript nature of this project.
- *
- * @param project the given project
- * @return the JavaScript project corresponding to the given project, null if the given project is null
- */
- public static IJavaScriptProject create(IProject project) {
- if (project == null) {
- return null;
- }
- JavaModel javaModel = JavaModelManager.getJavaModelManager().getJavaModel();
- return javaModel.getJavaProject(project);
- }
- /**
- * Returns the JavaScript element corresponding to the given resource, or
- * <code>null</code> if unable to associate the given resource
- * with a JavaScript element.
- * <p>
- * The resource must be one of:<ul>
- * <li>a project - the element returned is the corresponding <code>IJavaScriptProject</code></li>
- * <li>a file with one of the {@link JavaScriptCore#getJavaScriptLikeExtensions()
- * JavaScript-like extensions} - the element returned is the corresponding <code>IJavaScriptUnit</code></li>
- * <li>a folder - the element returned is the corresponding <code>IPackageFragmentRoot</code>
- * or <code>IPackageFragment</code></li>
- * <li>the workspace root resource - the element returned is the <code>IJavaScriptModel</code></li>
- * </ul>
- * <p>
- * Creating a JavaScript element has the side effect of creating and opening all of the
- * element's parents if they are not yet open.
- *
- * @param resource the given resource
- * @return the JavaScript element corresponding to the given resource, or
- * <code>null</code> if unable to associate the given resource
- * with a JavaScript element
- */
- public static IJavaScriptElement create(IResource resource) {
- return JavaModelManager.create(resource, null/*unknown javaScript project*/);
- }
- /**
- * Returns the JavaScript element corresponding to the given file, its project being the given
- * project. Returns <code>null</code> if unable to associate the given resource
- * with a JavaScript element.
- *<p>
- * The resource must be one of:<ul>
- * <li>a project - the element returned is the corresponding <code>IJavaScriptProject</code></li>
- * <li>a file with one of the {@link JavaScriptCore#getJavaScriptLikeExtensions()
- * JavaScript-like extensions} - the element returned is the corresponding <code>IJavaScriptUnit</code></li>
- * <li>a folder - the element returned is the corresponding <code>IPackageFragmentRoot</code>
- * or <code>IPackageFragment</code></li>
- * <li>the workspace root resource - the element returned is the <code>IJavaScriptModel</code></li>
- * </ul>
- * <p>
- * Creating a JavaScript element has the side effect of creating and opening all of the
- * element's parents if they are not yet open.
- *
- * @param resource the given resource
- * @return the JavaScript element corresponding to the given file, or
- * <code>null</code> if unable to associate the given file
- * with a JavaScript element
- */
- public static IJavaScriptElement create(IResource resource, IJavaScriptProject project) {
- return JavaModelManager.create(resource, project);
- }
- /**
- * Returns the JavaScript model.
- *
- * @param root the given root
- * @return the JavaScript model, or <code>null</code> if the root is null
- */
- public static IJavaScriptModel create(IWorkspaceRoot root) {
- if (root == null) {
- return null;
- }
- return JavaModelManager.getJavaModelManager().getJavaModel();
- }
- /*
- * Creates and returns a class file element for
- * the given <code>.class</code> file. Returns <code>null</code> if unable
- * to recognize the class file.
- *
- * @param file the given <code>.class</code> file
- * @return a class file element for the given <code>.class</code> file, or <code>null</code> if unable
- * to recognize the class file
- */
- public static IClassFile createClassFileFrom(IFile file) {
- return JavaModelManager.createClassFileFrom(file, null);
- }
- /**
- * Creates and returns a javaScript unit element for
- * the given source file (i.e. a file with one of the {@link JavaScriptCore#getJavaScriptLikeExtensions()
- * JavaScript-like extensions}). Returns <code>null</code> if unable
- * to recognize the javaScript unit.
- *
- * @param file the given source file
- * @return a javaScript unit element for the given source file, or <code>null</code> if unable
- * to recognize the javaScript unit
- */
- public static IJavaScriptUnit createCompilationUnitFrom(IFile file) {
- return JavaModelManager.createCompilationUnitFrom(file, null/*unknown javaScript project*/);
- }
- /*
- * Creates and returns a handle for the given JAR file.
- * The JavaScript model associated with the JAR's project may be
- * created as a side effect.
- *
- * @param file the given JAR file
- * @return a handle for the given JAR file, or <code>null</code> if unable to create a JAR package fragment root.
- * (for example, if the JAR file represents a non-JavaScript resource)
- */
- public static IPackageFragmentRoot createJarPackageFragmentRootFrom(IFile file) {
- return JavaModelManager.createJarPackageFragmentRootFrom(file, null/*unknown javaScript project*/);
- }
-
- /**
- * Answers the project specific value for a given includepath container.
- * In case this container path could not be resolved, then will answer <code>null</code>.
- * Both the container path and the project context are supposed to be non-null.
- * <p>
- * The containerPath is a formed by a first ID segment followed with extra segments, which can be
- * used as additional hints for resolution. If no container was ever recorded for this container path
- * onto this project (using <code>setJsGlobalScopeContainer</code>, then a
- * <code>JsGlobalScopeContainerInitializer</code> will be activated if any was registered for this container
- * ID onto the extension point "org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer".
- * <p>
- * There is no assumption that the returned container must answer the exact same containerPath
- * when requested <code>IJsGlobalScopeContainer#getPath</code>.
- * Indeed, the containerPath is just an indication for resolving it to an actual container object.
- * <p>
- * Includepath container values are persisted locally to the workspace, but
- * are not preserved from a session to another. It is thus highly recommended to register a
- * <code>JsGlobalScopeContainerInitializer</code> for each referenced container
- * (through the extension point "org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer").
- * <p>
- * @param containerPath the name of the container, which needs to be resolved
- * @param project a specific project in which the container is being resolved
- * @return the corresponding includepath container or <code>null</code> if unable to find one.
- *
- * @exception JavaScriptModelException if an exception occurred while resolving the container, or if the resolved container
- * contains illegal entries (contains CPE_CONTAINER entries or null entries).
- *
- * @see JsGlobalScopeContainerInitializer
- * @see IJsGlobalScopeContainer
- * @see #setJsGlobalScopeContainer(IPath, IJavaScriptProject[], IJsGlobalScopeContainer[], IProgressMonitor)
- */
- public static IJsGlobalScopeContainer getJsGlobalScopeContainer(IPath containerPath, IJavaScriptProject project) throws JavaScriptModelException {
-
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- IJsGlobalScopeContainer container = manager.getJsGlobalScopeContainer(containerPath, project);
- if (container == JavaModelManager.CONTAINER_INITIALIZATION_IN_PROGRESS) {
- return manager.getPreviousSessionContainer(containerPath, project);
- }
- return container;
- }
-
- /**
- * Helper method finding the includepath container initializer registered for a given includepath container ID
- * or <code>null</code> if none was found while iterating over the contributions to extension point to
- * the extension point "org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer".
- * <p>
- * A containerID is the first segment of any container path, used to identify the registered container initializer.
- * <p>
- * @param containerID - a containerID identifying a registered initializer
- * @return JsGlobalScopeContainerInitializer - the registered includepath container initializer or <code>null</code> if
- * none was found.
- */
- public static JsGlobalScopeContainerInitializer getJsGlobalScopeContainerInitializer(String containerID) {
- HashMap containerInitializersCache = JavaModelManager.getJavaModelManager().containerInitializersCache;
- JsGlobalScopeContainerInitializer initializer = (JsGlobalScopeContainerInitializer) containerInitializersCache.get(containerID);
- if (initializer == null) {
- initializer = computeJsGlobalScopeContainerInitializer(containerID);
- if (initializer == null)
- return null;
- containerInitializersCache.put(containerID, initializer);
- }
- return initializer;
- }
-
- private static JsGlobalScopeContainerInitializer computeJsGlobalScopeContainerInitializer(String containerID) {
- Plugin jdtCorePlugin = JavaScriptCore.getPlugin();
- if (jdtCorePlugin == null) return null;
-
- IExtensionPoint extension = Platform.getExtensionRegistry().getExtensionPoint(JavaScriptCore.PLUGIN_ID, JavaModelManager.CPCONTAINER_INITIALIZER_EXTPOINT_ID);
- if (extension != null) {
- IExtension[] extensions = extension.getExtensions();
- for(int i = 0; i < extensions.length; i++){
- IConfigurationElement [] configElements = extensions[i].getConfigurationElements();
- for(int j = 0; j < configElements.length; j++){
- IConfigurationElement configurationElement = configElements[j];
- String initializerID = configurationElement.getAttribute("id"); //$NON-NLS-1$
- if (initializerID != null && initializerID.equals(containerID)){
- if (JavaModelManager.CP_RESOLVE_VERBOSE_ADVANCED)
- verbose_found_container_initializer(containerID, configurationElement);
- try {
- Object execExt = configurationElement.createExecutableExtension("class"); //$NON-NLS-1$
- if (execExt instanceof JsGlobalScopeContainerInitializer){
- return (JsGlobalScopeContainerInitializer)execExt;
- }
- } catch(CoreException e) {
- // executable extension could not be created: ignore this initializer
- if (JavaModelManager.CP_RESOLVE_VERBOSE) {
- verbose_failed_to_instanciate_container_initializer(containerID, configurationElement);
- e.printStackTrace();
- }
- }
- }
- }
- }
- }
- return null;
- }
-
- private static void verbose_failed_to_instanciate_container_initializer(String containerID, IConfigurationElement configurationElement) {
- Util.verbose(
- "CPContainer INIT - failed to instanciate initializer\n" + //$NON-NLS-1$
- " container ID: " + containerID + '\n' + //$NON-NLS-1$
- " class: " + configurationElement.getAttribute("class"), //$NON-NLS-1$ //$NON-NLS-2$
- System.err);
- }
-
- private static void verbose_found_container_initializer(String containerID, IConfigurationElement configurationElement) {
- Util.verbose(
- "CPContainer INIT - found initializer\n" + //$NON-NLS-1$
- " container ID: " + containerID + '\n' + //$NON-NLS-1$
- " class: " + configurationElement.getAttribute("class")); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
-
- /**
- * Returns the path held in the given includepath variable.
- * Returns <code>null</code> if unable to bind.
- * <p>
- * Includepath variable values are persisted locally to the workspace, and
- * are preserved from session to session.
- * <p>
- * Note that includepath variables can be contributed registered initializers for,
- * using the extension point "org.eclipse.wst.jsdt.core.JsGlobalScopeVariableInitializer".
- * If an initializer is registered for a variable, its persisted value will be ignored:
- * its initializer will thus get the opportunity to rebind the variable differently on
- * each session.
- *
- * @param variableName the name of the includepath variable
- * @return the path, or <code>null</code> if none
- * @see #setClasspathVariable(String, IPath)
- */
- /**
- * Returns the path held in the given includepath variable.
- * Returns <code>null</code> if unable to bind.
- * <p>
- * Includepath variable values are persisted locally to the workspace, and
- * are preserved from session to session.
- * <p>
- * Note that includepath variables can be contributed registered initializers for,
- * using the extension point "org.eclipse.wst.jsdt.core.JsGlobalScopeVariableInitializer".
- * If an initializer is registered for a variable, its persisted value will be ignored:
- * its initializer will thus get the opportunity to rebind the variable differently on
- * each session.
- *
- * @param variableName the name of the includepath variable
- * @return the path, or <code>null</code> if none
- * @see #setIncludepathVariable(String, IPath)
- */
- public static IPath getIncludepathVariable(final String variableName) {
-
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- IPath variablePath = manager.variableGet(variableName);
- if (variablePath == JavaModelManager.VARIABLE_INITIALIZATION_IN_PROGRESS){
- return manager.getPreviousSessionVariable(variableName);
- }
-
- if (variablePath != null) {
- if (variablePath == JavaModelManager.CP_ENTRY_IGNORE_PATH)
- return null;
- return variablePath;
- }
-
- // even if persisted value exists, initializer is given priority, only if no initializer is found the persisted value is reused
- final JsGlobalScopeVariableInitializer initializer = JavaScriptCore.getJsGlobalScopeVariableInitializer(variableName);
- if (initializer != null){
- if (JavaModelManager.CP_RESOLVE_VERBOSE)
- verbose_triggering_variable_initialization(variableName, initializer);
- if (JavaModelManager.CP_RESOLVE_VERBOSE_ADVANCED)
- verbose_triggering_variable_initialization_invocation_trace();
- manager.variablePut(variableName, JavaModelManager.VARIABLE_INITIALIZATION_IN_PROGRESS); // avoid initialization cycles
- boolean ok = false;
- try {
- // let OperationCanceledException go through
- // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=59363)
- initializer.initialize(variableName);
-
- variablePath = manager.variableGet(variableName); // initializer should have performed side-effect
- if (variablePath == JavaModelManager.VARIABLE_INITIALIZATION_IN_PROGRESS) return null; // break cycle (initializer did not init or reentering call)
- if (JavaModelManager.CP_RESOLVE_VERBOSE_ADVANCED)
- verbose_variable_value_after_initialization(variableName, variablePath);
- manager.variablesWithInitializer.add(variableName);
- ok = true;
- } catch (RuntimeException e) {
- if (JavaModelManager.CP_RESOLVE_VERBOSE)
- e.printStackTrace();
- throw e;
- } catch (Error e) {
- if (JavaModelManager.CP_RESOLVE_VERBOSE)
- e.printStackTrace();
- throw e;
- } finally {
- if (!ok) JavaModelManager.getJavaModelManager().variablePut(variableName, null); // flush cache
- }
- } else {
- if (JavaModelManager.CP_RESOLVE_VERBOSE_ADVANCED)
- verbose_no_variable_initializer_found(variableName);
- }
- return variablePath;
- }
-
- private static void verbose_no_variable_initializer_found(String variableName) {
- Util.verbose(
- "CPVariable INIT - no initializer found\n" + //$NON-NLS-1$
- " variable: " + variableName); //$NON-NLS-1$
- }
-
- private static void verbose_variable_value_after_initialization(String variableName, IPath variablePath) {
- Util.verbose(
- "CPVariable INIT - after initialization\n" + //$NON-NLS-1$
- " variable: " + variableName +'\n' + //$NON-NLS-1$
- " variable path: " + variablePath); //$NON-NLS-1$
- }
-
- private static void verbose_triggering_variable_initialization(String variableName, JsGlobalScopeVariableInitializer initializer) {
- Util.verbose(
- "CPVariable INIT - triggering initialization\n" + //$NON-NLS-1$
- " variable: " + variableName + '\n' + //$NON-NLS-1$
- " initializer: " + initializer); //$NON-NLS-1$
- }
-
- private static void verbose_triggering_variable_initialization_invocation_trace() {
- Util.verbose(
- "CPVariable INIT - triggering initialization\n" + //$NON-NLS-1$
- " invocation trace:"); //$NON-NLS-1$
- new Exception("<Fake exception>").printStackTrace(System.out); //$NON-NLS-1$
- }
-
-
-
- /**
- * Returns deprecation message of a given includepath variable.
- *
- * @param variableName
- * @return A string if the includepath variable is deprecated, <code>null</code> otherwise.
- */
- public static String getIncludepathVariableDeprecationMessage(String variableName) {
- return (String) JavaModelManager.getJavaModelManager().deprecatedVariables.get(variableName);
- }
-
- /**
- * Helper method finding the includepath variable initializer registered for a given includepath variable name
- * or <code>null</code> if none was found while iterating over the contributions to extension point to
- * the extension point "org.eclipse.wst.jsdt.core.JsGlobalScopeVariableInitializer".
- * <p>
- * @param variable the given variable
- * @return JsGlobalScopeVariableInitializer - the registered includepath variable initializer or <code>null</code> if
- * none was found.
- */
- public static JsGlobalScopeVariableInitializer getJsGlobalScopeVariableInitializer(String variable){
-
- Plugin jdtCorePlugin = JavaScriptCore.getPlugin();
- if (jdtCorePlugin == null) return null;
-
- IExtensionPoint extension = Platform.getExtensionRegistry().getExtensionPoint(JavaScriptCore.PLUGIN_ID, JavaModelManager.CPVARIABLE_INITIALIZER_EXTPOINT_ID);
- if (extension != null) {
- IExtension[] extensions = extension.getExtensions();
- for(int i = 0; i < extensions.length; i++){
- IConfigurationElement [] configElements = extensions[i].getConfigurationElements();
- for(int j = 0; j < configElements.length; j++){
- IConfigurationElement configElement = configElements[j];
- try {
- String varAttribute = configElement.getAttribute("variable"); //$NON-NLS-1$
- if (variable.equals(varAttribute)) {
- if (JavaModelManager.CP_RESOLVE_VERBOSE_ADVANCED)
- verbose_found_variable_initializer(variable, configElement);
- Object execExt = configElement.createExecutableExtension("class"); //$NON-NLS-1$
- if (execExt instanceof JsGlobalScopeVariableInitializer){
- JsGlobalScopeVariableInitializer initializer = (JsGlobalScopeVariableInitializer)execExt;
- String deprecatedAttribute = configElement.getAttribute("deprecated"); //$NON-NLS-1$
- if (deprecatedAttribute != null) {
- JavaModelManager.getJavaModelManager().deprecatedVariables.put(variable, deprecatedAttribute);
- }
- String readOnlyAttribute = configElement.getAttribute("readOnly"); //$NON-NLS-1$
- if (JavaModelManager.TRUE.equals(readOnlyAttribute)) {
- JavaModelManager.getJavaModelManager().readOnlyVariables.add(variable);
- }
- return initializer;
- }
- }
- } catch(CoreException e){
- // executable extension could not be created: ignore this initializer
- if (JavaModelManager.CP_RESOLVE_VERBOSE) {
- verbose_failed_to_instanciate_variable_initializer(variable, configElement);
- e.printStackTrace();
- }
- }
- }
- }
- }
- return null;
- }
-
- private static void verbose_failed_to_instanciate_variable_initializer(String variable, IConfigurationElement configElement) {
- Util.verbose(
- "CPContainer INIT - failed to instanciate initializer\n" + //$NON-NLS-1$
- " variable: " + variable + '\n' + //$NON-NLS-1$
- " class: " + configElement.getAttribute("class"), //$NON-NLS-1$ //$NON-NLS-2$
- System.err);
- }
-
- private static void verbose_found_variable_initializer(String variable, IConfigurationElement configElement) {
- Util.verbose(
- "CPVariable INIT - found initializer\n" + //$NON-NLS-1$
- " variable: " + variable + '\n' + //$NON-NLS-1$
- " class: " + configElement.getAttribute("class")); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /**
- * Returns the names of all known includepath variables.
- * <p>
- * Includepath variable values are persisted locally to the workspace, and
- * are preserved from session to session.
- * <p>
- *
- * @return the list of includepath variable names
- * @see #setIncludepathVariable(String, IPath)
- */
- public static String[] getIncludepathVariableNames() {
- return JavaModelManager.getJavaModelManager().variableNames();
- }
-
- /**
- * Returns a table of all known configurable options with their default values.
- * These options allow to configure the behaviour of the underlying components.
- * The client may safely use the result as a template that they can modify and
- * then pass to <code>setOptions</code>.
- *
- * Helper constants have been defined on JavaScriptCore for each of the option ID and
- * their possible constant values.
- *
- * Note: more options might be added in further releases.
- * <pre>
- * RECOGNIZED OPTIONS:
- *
- * VALIDATOR / Setting Compliance Level
- * Select the compliance level for the validator. In "1.3" mode, source and target settings
- * should not go beyond "1.3" level.
- * - option id: "org.eclipse.wst.jsdt.core.compiler.compliance"
- * - possible values: { "1.3", "1.4", "1.5", "1.6", "1.7" }
- * - default: "1.4"
- *
- * VALIDATOR / Setting Source Compatibility Mode
- * Specify whether which source level compatibility is used. From 1.4 on, 'assert' is a keyword
- * reserved for assertion support. Also note, than when toggling to 1.4 mode, the target VM
- * level should be set to "1.4" and the compliance mode should be "1.4".
- * Source level 1.5 is necessary to enable generics, autoboxing, covariance, annotations, enumerations
- * enhanced for loop, static imports and varargs. Once toggled, the target VM level should be set to "1.5"
- * and the compliance mode should be "1.5".
- * Source level 1.6 is necessary to enable the computation of stack map tables. Once toggled, the target
- * VM level should be set to "1.6" and the compliance mode should be "1.6".
- * Once the source level 1.7 is toggled, the target VM level should be set to "1.7" and the compliance mode
- * should be "1.7".
- * - option id: "org.eclipse.wst.jsdt.core.compiler.source"
- * - possible values: { "1.3", "1.4", "1.5", "1.6", "1.7" }
- * - default: "1.3"
- *
- *
- * VALIDATOR / JSdoc Comment Support
- * When this support is disabled, the validator will ignore all jsdoc problems options settings
- * and will not report any jsdoc problem. It will also not find any reference in jsdoc comment and
- * DOM AST JSdoc node will be only a flat text instead of having structured tag elements.
- * - option id: "org.eclipse.wst.jsdt.core.compiler.doc.comment.support"
- * - possible values: { "enabled", "disabled" }
- * - default: "enabled"
- *
- * VALIDATOR / Reporting Deprecation
- * When enabled, the validator will signal use of deprecated API either as an
- * error or a warning.
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.deprecation"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "warning"
- *
- * VALIDATOR / Reporting Deprecation Inside Deprecated Code
- * When enabled, the validator will signal use of deprecated API inside deprecated code.
- * The severity of the problem is controlled with option "org.eclipse.wst.jsdt.core.compiler.problem.deprecation".
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.deprecationInDeprecatedCode"
- * - possible values: { "enabled", "disabled" }
- * - default: "disabled"
- *
- * VALIDATOR / Reporting Deprecation When Overriding Deprecated Method
- * When enabled, the validator will signal the declaration of a method overriding a deprecated one.
- * The severity of the problem is controlled with option "org.eclipse.wst.jsdt.core.compiler.problem.deprecation".
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod"
- * - possible values: { "enabled", "disabled" }
- * - default: "disabled"
- *
- * VALIDATOR / Reporting Unused Local
- * When enabled, the validator will issue an error or a warning for unused local
- * variables (that is, variables never read from)
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.unusedLocal"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "ignore"
- *
- * VALIDATOR / Reporting Unused Parameter
- * When enabled, the validator will issue an error or a warning for unused method
- * parameters (that is, parameters never read from)
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.unusedParameter"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "ignore"
- *
- * VALIDATOR / Reporting Unused Parameter if Implementing Abstract Method
- * When enabled, the validator will signal unused parameters in abstract method implementations.
- * The severity of the problem is controlled with option "org.eclipse.wst.jsdt.core.compiler.problem.unusedParameter".
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.unusedParameterWhenImplementingAbstract"
- * - possible values: { "enabled", "disabled" }
- * - default: "disabled"
- *
- * VALIDATOR / Reporting Unused Parameter if Overriding Concrete Method
- * When enabled, the validator will signal unused parameters in methods overriding concrete ones.
- * The severity of the problem is controlled with option "org.eclipse.wst.jsdt.core.compiler.problem.unusedParameter".
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.unusedParameterWhenOverridingConcrete"
- * - possible values: { "enabled", "disabled" }
- * - default: "disabled"
- *
- * VALIDATOR / Consider Reference in Doc Comment for Unused Parameter Check
- * When enabled, the validator will consider doc comment references to parameters (i.e. @param clauses) for the unused
- * parameter check. Thus, documented parameters will be considered as mandated as per doc contract.
- * The severity of the unused parameter problem is controlled with option "org.eclipse.wst.jsdt.core.compiler.problem.unusedParameter".
- * Note: this option has no effect until the doc comment support is enabled according to the
- * option "org.eclipse.wst.jsdt.core.compiler.doc.comment.support".
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.unusedParameterIncludeDocReference"
- * - possible values: { "enabled", "disabled" }
- * - default: "enabled"
- *
- * VALIDATOR / Reporting Unused Import
- * When enabled, the validator will issue an error or a warning for unused import
- * reference
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.unusedImport"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "warning"
- *
- * VALIDATOR / Reporting Unused Private Members
- * When enabled, the validator will issue an error or a warning whenever a private
- * method or field is declared but never used within the same unit.
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.unusedPrivateMember"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "ignore"
- *
- * VALIDATOR / Reporting Assignment with no Effect
- * When enabled, the validator will issue an error or a warning whenever an assignment
- * has no effect (e.g 'x = x').
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.noEffectAssignment"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "warning"
- *
- * VALIDATOR / Reporting Empty Statements and Unnecessary Semicolons
- * When enabled, the validator will issue an error or a warning if an empty statement or a
- * unnecessary semicolon is encountered.
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.emptyStatement"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "ignore"
- *
- * VALIDATOR / Reporting Unnecessary Type Check
- * When enabled, the validator will issue an error or a warning when a cast or an instanceof operation
- * is unnecessary.
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.unnecessaryTypeCheck"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "ignore"
- *
- * VALIDATOR / Reporting Unnecessary Else
- * When enabled, the validator will issue an error or a warning when a statement is unnecessarily
- * nested within an else clause (in situation where then clause is not completing normally).
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.unnecessaryElse"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "ignore"
- *
- * VALIDATOR / Reporting Non-Externalized String Literal
- * When enabled, the validator will issue an error or a warning for non externalized
- * String literal (that is, not tagged with //$NON-NLS-&lt;n&gt;$).
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.nonExternalizedStringLiteral"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "ignore"
- *
- * VALIDATOR / Reporting Non-Static Reference to a Static Member
- * When enabled, the validator will issue an error or a warning whenever a static field
- * or method is accessed with an expression receiver. A reference to a static member should
- * be qualified with a type name.
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.staticAccessReceiver"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "warning"
- *
- * VALIDATOR / Reporting Indirect Reference to a Static Member
- * When enabled, the validator will issue an error or a warning whenever a static field
- * or method is accessed in an indirect way. A reference to a static member should
- * preferably be qualified with its declaring type name.
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.indirectStaticAccess"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "ignore"
- *
- * VALIDATOR / Reporting Local Variable Declaration Hiding another Variable
- * When enabled, the validator will issue an error or a warning whenever a local variable
- * declaration is hiding some field or local variable (either locally, inherited or defined in enclosing type).
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.localVariableHiding"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "ignore"
- *
- * VALIDATOR / Reporting Field Declaration Hiding another Variable
- * When enabled, the validator will issue an error or a warning whenever a field
- * declaration is hiding some field or local variable (either locally, inherited or defined in enclosing type).
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.fieldHiding"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "ignore"
- *
- * VALIDATOR / Reporting Type Declaration Hiding another Type
- * When enabled, the validator will issue an error or a warning in situations where a type parameter
- * declaration is hiding some type, when a nested type is hiding some type parameter, or when
- * a nested type is hiding another nested type defined in same unit.
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.typeParameterHiding"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "warning"
- *
- * VALIDATOR / Reporting Possible Accidental Boolean Assignment
- * When enabled, the validator will issue an error or a warning if a boolean assignment is acting as the condition
- * of a control statement (where it probably was meant to be a boolean comparison).
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.possibleAccidentalBooleanAssignment"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "ignore"
- *
- * VALIDATOR / Reporting Undocumented Empty Block
- * When enabled, the validator will issue an error or a warning when an empty block is detected and it is not
- * documented with any comment.
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.undocumentedEmptyBlock"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "ignore"
- *
- * VALIDATOR / Reporting Finally Blocks Not Completing Normally
- * When enabled, the validator will issue an error or a warning when a finally block does not complete normally.
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.finallyBlockNotCompletingNormally"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "warning"
- *
- * VALIDATOR / Reporting Unused Declared Thrown Exception
- * When enabled, the validator will issue an error or a warning when a method or a constructor is declaring a
- * thrown checked exception, but never actually raises it in its body.
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.unusedDeclaredThrownException"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "ignore"
- *
- * VALIDATOR / Reporting Unused Declared Thrown Exception in Overridind Method
- * When disabled, the validator will not include overriding methods in its diagnosis for unused declared
- * thrown exceptions.
- * <br>
- * The severity of the problem is controlled with option "org.eclipse.wst.jsdt.core.compiler.problem.unusedDeclaredThrownException".
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding"
- * - possible values: { "enabled", "disabled" }
- * - default: "disabled"
- *
- * VALIDATOR / Reporting Unqualified Access to Field
- * When enabled, the validator will issue an error or a warning when a field is access without any qualification.
- * In order to improve code readability, it should be qualified, e.g. 'x' should rather be written 'this.x'.
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.unqualifiedFieldAccess"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "ignore"
- *
- * VALIDATOR / Reporting Null Dereference
- * When enabled, the validator will issue an error or a warning whenever a
- * variable that is statically known to hold a null value is used to
- * access a field or method.
- *
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.nullReference"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "ignore"
- *
- * VALIDATOR / Reporting Potential Null Dereference
- * When enabled, the validator will issue an error or a warning whenever a
- * variable that has formerly been tested against null but is not (no more)
- * statically known to hold a non-null value is used to access a field or
- * method.
- *
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.potentialNullReference"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "ignore"
- *
- * VALIDATOR / Reporting Duplicate Local Variables
- * When enabled, the validator will issue an error or a warning whenever a
- * two local variables with the same name have been declared.
- *
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.duplicateLocalVariables"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "ignore"
- *
- * VALIDATOR / Reporting Redundant Null Check
- * When enabled, the validator will issue an error or a warning whenever a
- * variable that is statically known to hold a null or a non-null value
- * is tested against null.
- *
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.redundantNullCheck"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "ignore"
- *
- * VALIDATOR / Reporting Use of Annotation Type as Super Interface
- * When enabled, the validator will issue an error or a warning whenever an annotation type is used
- * as a super-interface. Though legal, this is discouraged.
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.annotationSuperInterface"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "warning"
- *
- * VALIDATOR / Reporting Invalid Jsdoc Comment
- * This is the generic control for the severity of JSdoc problems.
- * When enabled, the validator will issue an error or a warning for a problem in JSdoc.
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.invalidJavadoc"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "ignore"
- *
- * VALIDATOR / Visibility Level For Invalid JSdoc Tags
- * Set the minimum visibility level for JSdoc tag problems. Below this level problems will be ignored.
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.invalidJavadocTagsVisibility"
- * - possible values: { "public", "protected", "default", "private" }
- * - default: "public"
- *
- * VALIDATOR / Reporting Invalid JSdoc Tags
- * When enabled, the validator will signal unbound or unexpected reference tags in JSdoc.
- * A 'throws' tag referencing an undeclared exception would be considered as unexpected.
- * <br>Note that this diagnosis can be enabled based on the visibility of the construct associated with the JSDoc;
- * also see the setting "org.eclipse.wst.jsdt.core.compiler.problem.invalidJavadocTagsVisibility".
- * <br>
- * The severity of the problem is controlled with option "org.eclipse.wst.jsdt.core.compiler.problem.invalidJavadoc".
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.invalidJavadocTags"
- * - possible values: { "disabled", "enabled" }
- * - default: "disabled"
- *
- * VALIDATOR / Reporting Invalid JSdoc Tags with Deprecated References
- * Specify whether the validator will report deprecated references used in JSdoc tags.
- * <br>Note that this diagnosis can be enabled based on the visibility of the construct associated with the JSDoc;
- * also see the setting "org.eclipse.wst.jsdt.core.compiler.problem.invalidJavadocTagsVisibility".
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.invalidJavadocTagsDeprecatedRef"
- * - possible values: { "enabled", "disabled" }
- * - default: "disabled"
- *
- * VALIDATOR / Reporting Invalid JSdoc Tags with Not Visible References
- * Specify whether the validator will report non-visible references used in JSDoc tags.
- * <br>Note that this diagnosis can be enabled based on the visibility of the construct associated with the JSDoc;
- * also see the setting "org.eclipse.wst.jsdt.core.compiler.problem.invalidJavadocTagsVisibility".
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.invalidJavadocTagsNotVisibleRef"
- * - possible values: { "enabled", "disabled" }
- * - default: "disabled"
- *
- * VALIDATOR / Reporting Missing JSDoc Tags
- * This is the generic control for the severity of JSDoc missing tag problems.
- * When enabled, the validator will issue an error or a warning when tags are missing in JSDoc comments.
- * <br>Note that this diagnosis can be enabled based on the visibility of the construct associated with the JSDoc;
- * also see the setting "org.eclipse.wst.jsdt.core.compiler.problem.missingJavadocTagsVisibility".
- * <br>
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.missingJavadocTags"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "ignore"
- *
- * VALIDATOR / Visibility Level For Missing JSDoc Tags
- * Set the minimum visibility level for JSDoc missing tag problems. Below this level problems will be ignored.
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.missingJavadocTagsVisibility"
- * - possible values: { "public", "protected", "default", "private" }
- * - default: "public"
- *
- * VALIDATOR / Reporting Missing JSDoc Tags on Overriding Methods
- * Specify whether the validator will verify overriding methods in order to report JSDoc missing tag problems.
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.missingJavadocTagsOverriding"
- * - possible values: { "enabled", "disabled" }
- * - default: "disabled"
- *
- * VALIDATOR / Reporting Missing JSDoc Comments
- * This is the generic control for the severity of missing JSDoc comment problems.
- * When enabled, the validator will issue an error or a warning when JSDoc comments are missing.
- * <br>Note that this diagnosis can be enabled based on the visibility of the construct associated with the expected JSDoc;
- * also see the setting "org.eclipse.wst.jsdt.core.compiler.problem.missingJavadocCommentsVisibility".
- * <br>
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.missingJavadocComments"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "ignore"
- *
- * VALIDATOR / Visibility Level For Missing JSDoc Comments
- * Set the minimum visibility level for missing JSDoc problems. Below this level problems will be ignored.
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.missingJavadocCommentsVisibility"
- * - possible values: { "public", "protected", "default", "private" }
- * - default: "public"
- *
- * VALIDATOR / Reporting Missing JSDoc Comments on Overriding Methods
- * Specify whether the validator will verify overriding methods in order to report missing JSDoc comment problems.
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.missingJavadocCommentsOverriding"
- * - possible values: { "enabled", "disabled" }
- * - default: "disabled"
- *
- * VALIDATOR / Maximum Number of Problems Reported per JavaScript Unit
- * Specify the maximum number of problems reported on each javaScript unit.
- * - option id: "org.eclipse.wst.jsdt.core.compiler.maxProblemPerUnit"
- * - possible values: "&lt;n&gt;" where &lt;n&gt; is zero or a positive integer (if zero then all problems are reported).
- * - default: "100"
- *
- * VALIDATOR / Treating Optional Error as Fatal
- * When enabled, optional errors (i.e. optional problems which severity is set to "error") will be treated as standard
- * validator errors, yielding problem methods/types preventing from running offending code until the issue got resolved.
- * When disabled, optional errors are only considered as warnings, still carrying an error indication to make them more
- * severe. Note that by default, errors are fatal, whether they are optional or not.
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.fatalOptionalError"
- * - possible values: { "enabled", "disabled" }
- * - default: "enabled"
- *
- * VALIDATOR / Defining the Automatic Task Tags
- * When the tag list is not empty, the validator will issue a task marker whenever it encounters
- * one of the corresponding tags inside any comment in JavaScript source code.
- * Generated task messages will start with the tag, and range until the next line separator,
- * comment ending, or tag.
- * When a given line of code bears multiple tags, each tag will be reported separately.
- * Moreover, a tag immediately followed by another tag will be reported using the contents of the
- * next non-empty tag of the line, if any.
- * Note that tasks messages are trimmed. If a tag is starting with a letter or digit, then it cannot be leaded by
- * another letter or digit to be recognized ("fooToDo" will not be recognized as a task for tag "ToDo", but "foo#ToDo"
- * will be detected for either tag "ToDo" or "#ToDo"). Respectively, a tag ending with a letter or digit cannot be followed
- * by a letter or digit to be recognized ("ToDofoo" will not be recognized as a task for tag "ToDo", but "ToDo:foo" will
- * be detected either for tag "ToDo" or "ToDo:").
- * - option id: "org.eclipse.wst.jsdt.core.compiler.taskTags"
- * - possible values: { "&lt;tag&gt;[,&lt;tag&gt;]*" } where &lt;tag&gt; is a String without any wild-card or leading/trailing spaces
- * - default: "TODO,FIXME,XXX"
- *
- * VALIDATOR / Defining the Automatic Task Priorities
- * In parallel with the Automatic Task Tags, this list defines the priorities (high, normal or low)
- * of the task markers issued by the validator.
- * If the default is specified, the priority of each task marker is "NORMAL".
- * - option id: "org.eclipse.wst.jsdt.core.compiler.taskPriorities"
- * - possible values: { "&lt;priority&gt;[,&lt;priority&gt;]*" } where &lt;priority&gt; is one of "HIGH", "NORMAL" or "LOW"
- * - default: "NORMAL,HIGH,NORMAL"
- *
- * VALIDATOR / Determining whether task tags are case-sensitive
- * When enabled, task tags are considered in a case-sensitive way.
- * - option id: "org.eclipse.wst.jsdt.core.compiler.taskCaseSensitive"
- * - possible values: { "enabled", "disabled" }
- * - default: "enabled"
- *
- * VALIDATOR / Reporting Discouraged Reference to Type with Restricted Access
- * When enabled, the validator will issue an error or a warning when referring to a type with discouraged access, as defined according
- * to the access rule specifications.
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.discouragedReference"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "warning"
- *
- * VALIDATOR / Reporting Unreferenced Label
- * When enabled, the validator will issue an error or a warning when encountering a labeled statement which label
- * is never explicitly referenced. A label is considered to be referenced if its name explicitly appears behind a break
- * or continue statement; for instance the following label would be considered unreferenced; LABEL: { break; }
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.unusedLabel"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "warning"
- *
- * VALIDATOR / Reporting Parameter Assignment
- * When enabled, the validator will issue an error or a warning if a parameter is
- * assigned to.
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.parameterAssignment"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "ignore"
- *
- * VALIDATOR / Reporting Switch Fall-Through Case
- * When enabled, the validator will issue an error or a warning if a case may be
- * entered by falling through previous case. Empty cases are allowed.
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.fallthroughCase"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "ignore"
- *
- * VALIDATOR / Reporting Overriding method that doesn't call the super method invocation
- * When enabled, the validator will issue an error or a warning if a method is overriding a method without calling
- * the super invocation.
- * - option id: "org.eclipse.wst.jsdt.core.compiler.problem.overridingMethodWithoutSuperInvocation"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "ignore"
- *
- * BUILDER / Specifying Filters for Resource Copying Control
- * Allow to specify some filters to control the resource copy process.
- * - option id: "org.eclipse.wst.jsdt.core.builder.resourceCopyExclusionFilter"
- * - possible values: { "&lt;name&gt;[,&lt;name&gt;]* } where &lt;name&gt; is a file name pattern (* and ? wild-cards allowed)
- * or the name of a folder which ends with '/'
- * - default: ""
- *
- * BUILDER / Abort if Invalid Includepath
- * Allow to toggle the builder to abort if the includepath is invalid
- * - option id: "org.eclipse.wst.jsdt.core.builder.invalidClasspath"
- * - possible values: { "abort", "ignore" }
- * - default: "abort"
- *
- * BUILDER / Reporting Duplicate Resources
- * Indicate the severity of the problem reported when more than one occurrence
- * of a resource is to be copied into the output location.
- * - option id: "org.eclipse.wst.jsdt.core.builder.duplicateResourceTask"
- * - possible values: { "error", "warning" }
- * - default: "warning"
- *
- * JAVACORE / Computing Project Build Order
- * Indicate whether JavaScriptCore should enforce the project build order to be based on
- * the includepath prerequisite chain. When requesting to compute, this takes over
- * the platform default order (based on project references).
- * - option id: "org.eclipse.wst.jsdt.core.computeJavaBuildOrder"
- * - possible values: { "compute", "ignore" }
- * - default: "ignore"
- *
- * JAVACORE / Default Source Encoding Format
- * Get the default encoding format of source files. This value is
- * immutable and preset to the result of ResourcesPlugin.getEncoding().
- * It is offered as a convenience shortcut only.
- * - option id: "org.eclipse.wst.jsdt.core.encoding"
- * - value: &lt;immutable, platform default value&gt;
- *
- * JAVACORE / Reporting Incomplete Includepath
- * Indicate the severity of the problem reported when an entry on the includepath does not exist,
- * is not legite or is not visible (for example, a referenced project is closed).
- * - option id: "org.eclipse.wst.jsdt.core.incompleteClasspath"
- * - possible values: { "error", "warning"}
- * - default: "error"
- *
- * JAVACORE / Reporting Includepath Cycle
- * Indicate the severity of the problem reported when a project is involved in a cycle.
- * - option id: "org.eclipse.wst.jsdt.core.circularClasspath"
- * - possible values: { "error", "warning" }
- * - default: "error"
- * JAVACORE / Enabling Usage of Includepath Exclusion Patterns
- * When disabled, no entry on a project includepath can be associated with
- * an exclusion pattern.
- * - option id: "org.eclipse.wst.jsdt.core.includepath.exclusionPatterns"
- * - possible values: { "enabled", "disabled" }
- * - default: "enabled"
- *
- * JAVACORE / Enabling Usage of Includepath Multiple Output Locations
- * When disabled, no entry on a project includepath can be associated with
- * a specific output location, preventing thus usage of multiple output locations.
- * - option id: "org.eclipse.wst.jsdt.core.includepath.multipleOutputLocations"
- * - possible values: { "enabled", "disabled" }
- * - default: "enabled"
- *
- * JAVACORE / Set the timeout value for retrieving the method's parameter names from jsdoc
- * Timeout in milliseconds to retrieve the method's parameter names from jsdoc.
- * If the value is 0, the parameter names are not fetched and the raw names are returned.
- * - option id: "org.eclipse.wst.jsdt.core.timeoutForParameterNameFromAttachedJavadoc"
- * - possible values: "&lt;n&gt;", where n is an integer greater than or equal to 0
- * - default: "50"
- *
- * DEPRECATED SEE DefaultCodeFormatterOptions: FORMATTER / Inserting New Line Before Opening Brace
- * When Insert, a new line is inserted before an opening brace, otherwise nothing
- * is inserted
- * - option id: "org.eclipse.wst.jsdt.core.formatter.newline.openingBrace"
- * - possible values: { "insert", "do not insert" }
- * - default: "do not insert"
- *
- * DEPRECATED SEE DefaultCodeFormatterOptions: FORMATTER / Inserting New Line Inside Control Statement
- * When Insert, a new line is inserted between } and following else, catch, finally
- * - option id: "org.eclipse.wst.jsdt.core.formatter.newline.controlStatement"
- * - possible values: { "insert", "do not insert" }
- * - default: "do not insert"
- *
- * DEPRECATED SEE DefaultCodeFormatterOptions: Clearing Blank Lines
- * When Clear all, all blank lines are removed. When Preserve one, only one is kept
- * and all others removed.
- * - option id: "org.eclipse.wst.jsdt.core.formatter.newline.clearAll"
- * - possible values: { "clear all", "preserve one" }
- * - default: "preserve one"
- *
- * DEPRECATED SEE DefaultCodeFormatterOptions: Inserting New Line Between Else/If
- * When Insert, a blank line is inserted between an else and an if when they are
- * contiguous. When choosing to not insert, else-if will be kept on the same
- * line when possible.
- * - option id: "org.eclipse.wst.jsdt.core.formatter.newline.elseIf"
- * - possible values: { "insert", "do not insert" }
- * - default: "do not insert"
- *
- * DEPRECATED SEE DefaultCodeFormatterOptions: Inserting New Line In Empty Block
- * When insert, a line break is inserted between contiguous { and }, if } is not followed
- * by a keyword.
- * - option id: "org.eclipse.wst.jsdt.core.formatter.newline.emptyBlock"
- * - possible values: { "insert", "do not insert" }
- * - default: "insert"
- *
- * DEPRECATED SEE DefaultCodeFormatterOptions: Splitting Lines Exceeding Length
- * Enable splitting of long lines (exceeding the configurable length). Length of 0 will
- * disable line splitting
- * - option id: "org.eclipse.wst.jsdt.core.formatter.lineSplit"
- * - possible values: "&lt;n&gt;", where n is zero or a positive integer
- * - default: "80"
- *
- * DEPRECATED SEE DefaultCodeFormatterOptions: Compacting Assignment
- * Assignments can be formatted asymmetrically, for example 'int x= 2;', when Normal, a space
- * is inserted before the assignment operator
- * - option id: "org.eclipse.wst.jsdt.core.formatter.style.assignment"
- * - possible values: { "compact", "normal" }
- * - default: "normal"
- *
- * DEPRECATED SEE DefaultCodeFormatterOptions: Defining Indentation Character
- * Either choose to indent with tab characters or spaces
- * - option id: "org.eclipse.wst.jsdt.core.formatter.tabulation.char"
- * - possible values: { "tab", "space" }
- * - default: "tab"
- *
- * DEPRECATED SEE DefaultCodeFormatterOptions: Defining Space Indentation Length
- * When using spaces, set the amount of space characters to use for each
- * indentation mark.
- * - option id: "org.eclipse.wst.jsdt.core.formatter.tabulation.size"
- * - possible values: "&lt;n&gt;", where n is a positive integer
- * - default: "4"
- *
- * DEPRECATED SEE DefaultCodeFormatterOptions: Inserting space in cast expression
- * When Insert, a space is added between the type and the expression in a cast expression.
- * - option id: "org.eclipse.wst.jsdt.core.formatter.space.castexpression"
- * - possible values: { "insert", "do not insert" }
- * - default: "insert"
- *
- * CODEASSIST / Activate Visibility Sensitive Completion
- * When active, completion doesn't show that you can not see
- * (for example, you can not see private methods of a super class).
- * - option id: "org.eclipse.wst.jsdt.core.codeComplete.visibilityCheck"
- * - possible values: { "enabled", "disabled" }
- * - default: "disabled"
- *
- * CODEASSIST / Activate Deprecation Sensitive Completion
- * When enabled, completion doesn't propose deprecated members and types.
- * - option id: "org.eclipse.wst.jsdt.core.codeComplete.deprecationCheck"
- * - possible values: { "enabled", "disabled" }
- * - default: "disabled"
- *
- * CODEASSIST / Automatic Qualification of Implicit Members
- * When active, completion automatically qualifies completion on implicit
- * field references and message expressions.
- * - option id: "org.eclipse.wst.jsdt.core.codeComplete.forceImplicitQualification"
- * - possible values: { "enabled", "disabled" }
- * - default: "disabled"
- *
- * CODEASSIST / Define the Prefixes for Field Name
- * When the prefixes is non empty, completion for field name will begin with
- * one of the proposed prefixes.
- * - option id: "org.eclipse.wst.jsdt.core.codeComplete.fieldPrefixes"
- * - possible values: { "&lt;prefix&gt;[,&lt;prefix&gt;]*" } where &lt;prefix&gt; is a String without any wild-card
- * - default: ""
- *
- * CODEASSIST / Define the Prefixes for Static Field Name
- * When the prefixes is non empty, completion for static field name will begin with
- * one of the proposed prefixes.
- * - option id: "org.eclipse.wst.jsdt.core.codeComplete.staticFieldPrefixes"
- * - possible values: { "&lt;prefix&gt;[,&lt;prefix&gt;]*" } where &lt;prefix&gt; is a String without any wild-card
- * - default: ""
- *
- * CODEASSIST / Define the Prefixes for Local Variable Name
- * When the prefixes is non empty, completion for local variable name will begin with
- * one of the proposed prefixes.
- * - option id: "org.eclipse.wst.jsdt.core.codeComplete.localPrefixes"
- * - possible values: { "&lt;prefix&gt;[,&lt;prefix&gt;]*" } where &lt;prefix&gt; is a String without any wild-card
- * - default: ""
- *
- * CODEASSIST / Define the Prefixes for Argument Name
- * When the prefixes is non empty, completion for argument name will begin with
- * one of the proposed prefixes.
- * - option id: "org.eclipse.wst.jsdt.core.codeComplete.argumentPrefixes"
- * - possible values: { "&lt;prefix&gt;[,&lt;prefix&gt;]*" } where &lt;prefix&gt; is a String without any wild-card
- * - default: ""
- *
- * CODEASSIST / Define the Suffixes for Field Name
- * When the suffixes is non empty, completion for field name will end with
- * one of the proposed suffixes.
- * - option id: "org.eclipse.wst.jsdt.core.codeComplete.fieldSuffixes"
- * - possible values: { "&lt;suffix&gt;[,&lt;suffix&gt;]*" } where &lt;suffix&gt; is a String without any wild-card
- * - default: ""
- *
- * CODEASSIST / Define the Suffixes for Static Field Name
- * When the suffixes is non empty, completion for static field name will end with
- * one of the proposed suffixes.
- * - option id: "org.eclipse.wst.jsdt.core.codeComplete.staticFieldSuffixes"
- * - possible values: { "&lt;suffix&gt;[,&lt;suffix&gt;]*" } where &lt;suffix&gt; is a String without any wild-card
- * - default: ""
- *
- * CODEASSIST / Define the Suffixes for Local Variable Name
- * When the suffixes is non empty, completion for local variable name will end with
- * one of the proposed suffixes.
- * - option id: "org.eclipse.wst.jsdt.core.codeComplete.localSuffixes"
- * - possible values: { "&lt;suffix&gt;[,&lt;suffix&gt;]*" } where &lt;suffix&gt; is a String without any wild-card
- * - default: ""
- *
- * CODEASSIST / Define the Suffixes for Argument Name
- * When the suffixes is non empty, completion for argument name will end with
- * one of the proposed suffixes.
- * - option id: "org.eclipse.wst.jsdt.core.codeComplete.argumentSuffixes"
- * - possible values: { "&lt;suffix&gt;[,&lt;suffix&gt;]*" } where &lt;suffix&gt; is a String without any wild-card
- * - default: ""
- *
- * CODEASSIST / Activate Forbidden Reference Sensitive Completion
- * When enabled, completion doesn't propose elements which match a
- * forbidden reference rule.
- * - option id: "org.eclipse.wst.jsdt.core.codeComplete.forbiddenReferenceCheck"
- * - possible values: { "enabled", "disabled" }
- * - default: "enabled"
- *
- * CODEASSIST / Activate Discouraged Reference Sensitive Completion
- * When enabled, completion doesn't propose elements which match a
- * discouraged reference rule.
- * - option id: "org.eclipse.wst.jsdt.core.codeComplete.discouragedReferenceCheck"
- * - possible values: { "enabled", "disabled" }
- * - default: "disabled"
- *
- * CODEASSIST / Activate Camel Case Sensitive Completion
- * When enabled, completion shows proposals whose name match the CamelCase
- * pattern.
- * - option id: "org.eclipse.wst.jsdt.core.codeComplete.camelCaseMatch"
- * - possible values: { "enabled", "disabled" }
- * - default: "enabled"
- *
- * CODEASSIST / Activate Suggestion of Static Import
- * When enabled, completion proposals can contain static import
- * pattern.
- * - option id: "org.eclipse.wst.jsdt.core.codeComplete.suggestStaticImports"
- * - possible values: { "enabled", "disabled" }
- * - default: "enabled"
- * </pre>
- */
- public static Hashtable getDefaultOptions(){
- return JavaModelManager.getJavaModelManager().getDefaultOptions();
- }
-
- /**
- * Returns the workspace root default charset encoding.
- *
- * @return the name of the default charset encoding for workspace root.
- * @see IContainer#getDefaultCharset()
- * @see ResourcesPlugin#getEncoding()
- */
- public static String getEncoding() {
- // Verify that workspace is not shutting down (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=60687)
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- if (workspace != null) {
- try {
- return workspace.getRoot().getDefaultCharset();
- } catch (CoreException e) {
- // fails silently and return plugin global encoding if core exception occurs
- }
- }
- return ResourcesPlugin.getEncoding();
- }
-
- /**
- * Returns an array that contains the resources generated by the JavaScript builder when building the
- * javaScript units contained in the given region.
- * <p>The contents of the array is accurate only if the elements of the given region have been built.</p>
- * <p>The given region can contain instances of:</p>
- * <ul>
- * <li><code>org.eclipse.wst.jsdt.core.IJavaScriptUnit</code></li>
- * <li><code>org.eclipse.wst.jsdt.core.IPackageFragment</code></li>
- * <li><code>org.eclipse.wst.jsdt.core.IPackageFragmentRoot</code></li>
- * <li><code>org.eclipse.wst.jsdt.core.IJavaScriptProject</code></li>
- * </ul>
- * <p>All other types of <code>org.eclipse.wst.jsdt.core.IJavaScriptElement</code> are ignored.</p>
- *
- * @param region the given region
- * @param includesNonJavaResources a flag that indicates if non-javaScript resources should be included
- *
- * @return an array that contains the resources generated by the JavaScript builder when building the
- * javaScript units contained in the given region, an empty array if none
- * @exception IllegalArgumentException if the given region is <code>null</code>
- */
- public static IResource[] getGeneratedResources(IRegion region, boolean includesNonJavaResources) {
- if (region == null) throw new IllegalArgumentException("region cannot be null"); //$NON-NLS-1$
- IJavaScriptElement[] elements = region.getElements();
- HashMap projectsStates = new HashMap();
- ArrayList collector = new ArrayList();
- for (int i = 0, max = elements.length; i < max; i++) {
- // collect all the javaScript project
- IJavaScriptElement element = elements[i];
- IJavaScriptProject javaProject = element.getJavaScriptProject();
- IProject project = javaProject.getProject();
- State state = null;
- State currentState = (State) projectsStates.get(project);
- if (currentState != null) {
- state = currentState;
- } else {
- state = (State) JavaModelManager.getJavaModelManager().getLastBuiltState(project, null);
- if (state != null) {
- projectsStates.put(project, state);
- }
- }
- if (state == null) continue;
- if (element.getElementType() == IJavaScriptElement.JAVASCRIPT_PROJECT) {
- IPackageFragmentRoot[] roots = null;
- try {
- roots = javaProject.getPackageFragmentRoots();
- } catch (JavaScriptModelException e) {
- // ignore
- }
- if (roots == null) continue;
- IRegion region2 = JavaScriptCore.newRegion();
- for (int j = 0; j < roots.length; j++) {
- region2.add(roots[j]);
- }
- IResource[] res = getGeneratedResources(region2, includesNonJavaResources);
- for (int j = 0, max2 = res.length; j < max2; j++) {
- collector.add(res[j]);
- }
- continue;
- }
-
- IJavaScriptElement root = element;
- while (root != null && root.getElementType() != IJavaScriptElement.PACKAGE_FRAGMENT_ROOT) {
- root = root.getParent();
- }
- if (root == null) continue;
- }
- int size = collector.size();
- if (size != 0) {
- IResource[] result = new IResource[size];
- collector.toArray(result);
- return result;
- }
- return NO_GENERATED_RESOURCES;
- }
-
- /**
- * Returns the single instance of the JavaScript core plug-in runtime class.
- * Equivalent to <code>(JavaScriptCore) getPlugin()</code>.
- *
- * @return the single instance of the JavaScript core plug-in runtime class
- */
- public static JavaScriptCore getJavaScriptCore() {
- return (JavaScriptCore) getPlugin();
- }
-
- /**
- * Returns the list of known JavaScript-like extensions.
- * JavaScript like extension are defined in the {@link org.eclipse.core.runtime.Platform#getContentTypeManager()
- * content type manager} for the {@link #JAVA_SOURCE_CONTENT_TYPE}.
- * Note that a JavaScript-like extension doesn't include the leading dot ('.').
- * Also note that the "js" extension is always defined as a JavaScript-like extension.
- *
- * @return the list of known JavaScript-like extensions.
- */
- public static String[] getJavaScriptLikeExtensions() {
- return CharOperation.toStrings(Util.getJavaLikeExtensions());
- }
-
- /**
- * Helper method for returning one option value only. Equivalent to <code>(String)JavaScriptCore.getOptions().get(optionName)</code>
- * Note that it may answer <code>null</code> if this option does not exist.
- * <p>
- * For a complete description of the configurable options, see <code>getDefaultOptions</code>.
- * </p>
- *
- * @param optionName the name of an option
- * @return the String value of a given option
- * @see JavaScriptCore#getDefaultOptions()
- * @see org.eclipse.wst.jsdt.internal.core.JavaCorePreferenceInitializer for changing default settings
- */
- public static String getOption(String optionName) {
- return JavaModelManager.getJavaModelManager().getOption(optionName);
- }
-
- /**
- * Returns the table of the current options. Initially, all options have their default values,
- * and this method returns a table that includes all known options.
- * <p>For a complete description of the configurable options, see <code>getDefaultOptions</code>.</p>
- * <p>Returns a default set of options even if the platform is not running.</p>
- *
- * @return table of current settings of all options
- * (key type: <code>String</code>; value type: <code>String</code>)
- * @see #getDefaultOptions()
- * @see org.eclipse.wst.jsdt.internal.core.JavaCorePreferenceInitializer for changing default settings
- */
- public static Hashtable getOptions() {
- return JavaModelManager.getJavaModelManager().getOptions();
- }
-
- /**
- * Returns the single instance of the JavaScript core plug-in runtime class.
- *
- * @return the single instance of the JavaScript core plug-in runtime class
- */
- public static Plugin getPlugin() {
- return JAVA_CORE_PLUGIN;
- }
-
- /**
- * This is a helper method, which returns the resolved includepath entry denoted
- * by a given entry (if it is a variable entry). It is obtained by resolving the variable
- * reference in the first segment. Returns <code>null</code> if unable to resolve using
- * the following algorithm:
- * <ul>
- * <li> if variable segment cannot be resolved, returns <code>null</code></li>
- * <li> finds a project, JAR or binary folder in the workspace at the resolved path location</li>
- * <li> if none finds an external JAR file or folder outside the workspace at the resolved path location </li>
- * <li> if none returns <code>null</code></li>
- * </ul>
- * <p>
- * Variable source attachment path and root path are also resolved and recorded in the resulting includepath entry.
- * <p>
- * NOTE: This helper method does not handle includepath containers, for which should rather be used
- * <code>JavaScriptCore#getJsGlobalScopeContainer(IPath, IJavaScriptProject)</code>.
- * <p>
- *
- * @param entry the given variable entry
- * @return the resolved library or project includepath entry, or <code>null</code>
- * if the given variable entry could not be resolved to a valid includepath entry
- */
- public static IIncludePathEntry getResolvedIncludepathEntry(IIncludePathEntry entry) {
-
- if (entry.getEntryKind() != IIncludePathEntry.CPE_VARIABLE)
- return entry;
-
- IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
- IPath resolvedPath = JavaScriptCore.getResolvedVariablePath(entry.getPath());
- if (resolvedPath == null)
- return null;
-
- Object target = JavaModel.getTarget(workspaceRoot, resolvedPath, false);
- if (target == null)
- return null;
-
- // inside the workspace
- if (target instanceof IResource) {
- IResource resolvedResource = (IResource) target;
- switch (resolvedResource.getType()) {
-
- case IResource.PROJECT :
- // internal project
- return JavaScriptCore.newProjectEntry(
- resolvedPath,
- entry.getAccessRules(),
- entry.combineAccessRules(),
- entry.getExtraAttributes(),
- entry.isExported());
- case IResource.FILE :
- if (org.eclipse.wst.jsdt.internal.compiler.util.Util.isArchiveFileName(resolvedResource.getName())) {
- // internal binary archive
- return JavaScriptCore.newLibraryEntry(
- resolvedPath,
- getResolvedVariablePath(entry.getSourceAttachmentPath()),
- getResolvedVariablePath(entry.getSourceAttachmentRootPath()),
- entry.getAccessRules(),
- entry.getExtraAttributes(),
- entry.isExported());
- }
- break;
-
- case IResource.FOLDER :
- // internal binary folder
- return JavaScriptCore.newLibraryEntry(
- resolvedPath,
- getResolvedVariablePath(entry.getSourceAttachmentPath()),
- getResolvedVariablePath(entry.getSourceAttachmentRootPath()),
- entry.getAccessRules(),
- entry.getExtraAttributes(),
- entry.isExported());
- }
- }
- // outside the workspace
- if (target instanceof File) {
- File externalFile = JavaModel.getFile(target);
- if (externalFile != null) {
- String fileName = externalFile.getName().toLowerCase();
- if (fileName.endsWith(SuffixConstants.SUFFIX_STRING_java)
- || fileName.endsWith(SuffixConstants.SUFFIX_STRING_zip)
- ) {
- // external binary archive
- return JavaScriptCore.newLibraryEntry(
- resolvedPath,
- getResolvedVariablePath(entry.getSourceAttachmentPath()),
- getResolvedVariablePath(entry.getSourceAttachmentRootPath()),
- entry.getAccessRules(),
- entry.getExtraAttributes(),
- entry.isExported());
- }
- } else { // external binary folder
- if (resolvedPath.isAbsolute()){
- return JavaScriptCore.newLibraryEntry(
- resolvedPath,
- getResolvedVariablePath(entry.getSourceAttachmentPath()),
- getResolvedVariablePath(entry.getSourceAttachmentRootPath()),
- entry.getAccessRules(),
- entry.getExtraAttributes(),
- entry.isExported());
- }
- }
- }
- return null;
- }
-
-
- /**
- * Resolve a variable path (helper method).
- *
- * @param variablePath the given variable path
- * @return the resolved variable path or <code>null</code> if none
- */
- public static IPath getResolvedVariablePath(IPath variablePath) {
-
- if (variablePath == null)
- return null;
- int count = variablePath.segmentCount();
- if (count == 0)
- return null;
-
- // lookup variable
- String variableName = variablePath.segment(0);
- IPath resolvedPath = JavaScriptCore.getIncludepathVariable(variableName);
- if (resolvedPath == null)
- return null;
-
- // append path suffix
- if (count > 1) {
- resolvedPath = resolvedPath.append(variablePath.removeFirstSegments(1));
- }
- return resolvedPath;
- }
-
- /**
- * Returns the names of all defined user libraries. The corresponding includepath container path
- * is the name appended to the USER_LIBRARY_CONTAINER_ID.
- * @return Return an array containing the names of all known user defined.
- */
- public static String[] getUserLibraryNames() {
- return UserLibraryManager.getUserLibraryNames();
- }
-
- /**
- * Returns the working copies that have the given owner.
- * Only javaScript units in working copy mode are returned.
- * If the owner is <code>null</code>, primary working copies are returned.
- *
- * @param owner the given working copy owner or <code>null</code> for primary working copy owner
- * @return the list of working copies for a given owner
- */
- public static IJavaScriptUnit[] getWorkingCopies(WorkingCopyOwner owner){
-
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- if (owner == null) owner = DefaultWorkingCopyOwner.PRIMARY;
- IJavaScriptUnit[] result = manager.getWorkingCopies(owner, false/*don't add primary WCs*/);
- if (result == null) return JavaModelManager.NO_WORKING_COPY;
- return result;
- }
-
- /**
- * Initializes JavaScriptCore internal structures to allow subsequent operations (such
- * as the ones that need a resolved classpath) to run full speed. A client may
- * choose to call this method in a background thread early after the workspace
- * has started so that the initialization is transparent to the user.
- * <p>
- * However calling this method is optional. Services will lazily perform
- * initialization when invoked. This is only a way to reduce initialization
- * overhead on user actions, if it can be performed before at some
- * appropriate moment.
- * </p><p>
- * This initialization runs accross all JavaScript projects in the workspace. Thus the
- * workspace root scheduling rule is used during this operation.
- * </p><p>
- * This method may return before the initialization is complete. The
- * initialization will then continue in a background thread.
- * </p><p>
- * This method can be called concurrently.
- * </p>
- *
- * @param monitor a progress monitor, or <code>null</code> if progress
- * reporting and cancellation are not desired
- * @exception CoreException if the initialization fails,
- * the status of the exception indicates the reason of the failure
- */
- public static void initializeAfterLoad(IProgressMonitor monitor) throws CoreException {
- try {
- if (monitor != null) monitor.beginTask(Messages.javamodel_initialization, 100);
-
- // initialize all containers and variables
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- try {
- if (monitor != null) {
- monitor.subTask(Messages.javamodel_configuring_classpath_containers);
- manager.batchContainerInitializationsProgress.set(new SubProgressMonitor(monitor, 50)); // 50% of the time is spent in initializing containers and variables
- }
-
- // all classpaths in the workspace are going to be resolved, ensure that containers are initialized in one batch
- manager.batchContainerInitializations = true;
-
- // avoid leaking source attachment properties (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=183413)
- IJavaScriptProject[] projects = manager.getJavaModel().getJavaScriptProjects();
- for (int i = 0, length = projects.length; i < length; i++) {
- IIncludePathEntry[] classpath;
- try {
- classpath = ((JavaProject) projects[i]).getResolvedClasspath();
- } catch (JavaScriptModelException e) {
- // project no longer exist: ignore
- continue;
- }
- if (classpath != null) {
- for (int j = 0, length2 = classpath.length; j < length2; j++) {
- IIncludePathEntry entry = classpath[j];
- if (entry.getSourceAttachmentPath() != null)
- Util.setSourceAttachmentProperty(entry.getPath(), null);
- // else source might have been attached by IPackageFragmentRoot#attachSource(...), we keep it
- }
- }
- }
-
- // initialize delta state
- manager.deltaState.rootsAreStale = true; // in case it was already initialized before we cleaned up the source attachment proprties
- manager.deltaState.initializeRoots();
- } finally {
- manager.batchContainerInitializationsProgress.set(null);
- }
-
- // dummy query for waiting until the indexes are ready
- SearchEngine engine = new SearchEngine();
- IJavaScriptSearchScope scope = SearchEngine.createWorkspaceScope();
- try {
- if (monitor != null)
- monitor.subTask(Messages.javamodel_configuring_searchengine);
- engine.searchAllTypeNames(
- null,
- SearchPattern.R_EXACT_MATCH,
- "!@$#!@".toCharArray(), //$NON-NLS-1$
- SearchPattern.R_PATTERN_MATCH | SearchPattern.R_CASE_SENSITIVE,
- IJavaScriptSearchConstants.CLASS,
- scope,
- new TypeNameRequestor() {
- public void acceptType(
- int modifiers,
- char[] packageName,
- char[] simpleTypeName,
- char[][] enclosingTypeNames,
- String path) {
- // no type to accept
- }
- },
- // will not activate index query caches if indexes are not ready, since it would take to long
- // to wait until indexes are fully rebuild
- IJavaScriptSearchConstants.CANCEL_IF_NOT_READY_TO_SEARCH,
- monitor == null ? null : new SubProgressMonitor(monitor, 49) // 49% of the time is spent in the dummy search
- );
- } catch (JavaScriptModelException e) {
- // /search failed: ignore
- } catch (OperationCanceledException e) {
- if (monitor != null && monitor.isCanceled())
- throw e;
- // else indexes were not ready: catch the exception so that jars are still refreshed
- }
-
- // check if the build state version number has changed since last session
- // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=98969)
- if (monitor != null)
- monitor.subTask(Messages.javamodel_getting_build_state_number);
- QualifiedName qName = new QualifiedName(JavaScriptCore.PLUGIN_ID, "stateVersionNumber"); //$NON-NLS-1$
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- String versionNumber = null;
- try {
- versionNumber = root.getPersistentProperty(qName);
- } catch (CoreException e) {
- // could not read version number: consider it is new
- }
- final JavaModel model = manager.getJavaModel();
- String newVersionNumber = Byte.toString(State.VERSION);
- if (!newVersionNumber.equals(versionNumber)) {
- // build state version number has changed: touch every projects to force a rebuild
- if (JavaBuilder.DEBUG)
- System.out.println("Build state version number has changed"); //$NON-NLS-1$
- IWorkspaceRunnable runnable = new IWorkspaceRunnable() {
- public void run(IProgressMonitor progressMonitor2) throws CoreException {
- IJavaScriptProject[] projects = null;
- try {
- projects = model.getJavaScriptProjects();
- } catch (JavaScriptModelException e) {
- // could not get JavaScript projects: ignore
- }
- if (projects != null) {
- for (int i = 0, length = projects.length; i < length; i++) {
- IJavaScriptProject project = projects[i];
- try {
- if (JavaBuilder.DEBUG)
- System.out.println("Touching " + project.getElementName()); //$NON-NLS-1$
- project.getProject().touch(progressMonitor2);
- } catch (CoreException e) {
- // could not touch this project: ignore
- }
- }
- }
- }
- };
- if (monitor != null)
- monitor.subTask(Messages.javamodel_building_after_upgrade);
- try {
- ResourcesPlugin.getWorkspace().run(runnable, monitor);
- } catch (CoreException e) {
- // could not touch all projects
- }
- try {
- root.setPersistentProperty(qName, newVersionNumber);
- } catch (CoreException e) {
- Util.log(e, "Could not persist build state version number"); //$NON-NLS-1$
- }
- }
-
- // ensure external jars are refreshed (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=93668)
- try {
- if (monitor != null)
- monitor.subTask(Messages.javamodel_refreshing_external_jars);
- model.refreshExternalArchives(
- null/*refresh all projects*/,
- monitor == null ? null : new SubProgressMonitor(monitor, 1) // 1% of the time is spent in jar refresh
- );
- } catch (JavaScriptModelException e) {
- // refreshing failed: ignore
- }
-
- } finally {
- if (monitor != null) monitor.done();
- }
- }
- /**
- * Returns whether a given includepath variable is read-only or not.
- *
- * @param variableName
- * @return <code>true</code> if the includepath variable is read-only,
- * <code>false</code> otherwise.
- */
- public static boolean isIncludepathVariableReadOnly(String variableName) {
- return JavaModelManager.getJavaModelManager().readOnlyVariables.contains(variableName);
- }
-
- /**
- * Returns whether the given file name's extension is a JavaScript-like extension.
- *
- * @return whether the given file name's extension is a JavaScript-like extension
- * @see #getJavaScriptLikeExtensions()
- */
- public static boolean isJavaScriptLikeFileName(String fileName) {
- if(fileName==null) return false;
- return Util.isJavaLikeFileName(fileName);
- }
-
- /**
- * Returns whether the given marker references the given JavaScript element.
- * Used for markers, which denote a JavaScript element rather than a resource.
- *
- * @param element the element
- * @param marker the marker
- * @return <code>true</code> if the marker references the element, false otherwise
- * @exception CoreException if the <code>IMarker.getAttribute</code> on the marker fails
- */
- public static boolean isReferencedBy(IJavaScriptElement element, IMarker marker) throws CoreException {
-
- // only match units or classfiles
- if (element instanceof IMember){
- IMember member = (IMember) element;
- if (member.isBinary()){
- element = member.getClassFile();
- } else {
- element = member.getJavaScriptUnit();
- }
- }
- if (element == null) return false;
- if (marker == null) return false;
-
- String markerHandleId = (String)marker.getAttribute(ATT_HANDLE_ID);
- if (markerHandleId == null) return false;
-
- IJavaScriptElement markerElement = JavaScriptCore.create(markerHandleId);
- while (true){
- if (element.equals(markerElement)) return true; // external elements may still be equal with different handleIDs.
-
- // cycle through enclosing types in case marker is associated with a classfile (15568)
- if (markerElement instanceof IClassFile){
- IType enclosingType = ((IClassFile)markerElement).getType().getDeclaringType();
- if (enclosingType != null){
- markerElement = enclosingType.getClassFile(); // retry with immediate enclosing classfile
- continue;
- }
- }
- break;
- }
- return false;
- }
-
- /**
- * Returns whether the given marker delta references the given JavaScript element.
- * Used for markers deltas, which denote a JavaScript element rather than a resource.
- *
- * @param element the element
- * @param markerDelta the marker delta
- * @return <code>true</code> if the marker delta references the element
- * @exception CoreException if the <code>IMarkerDelta.getAttribute</code> on the marker delta fails
- */
- public static boolean isReferencedBy(IJavaScriptElement element, IMarkerDelta markerDelta) throws CoreException {
-
- // only match units or classfiles
- if (element instanceof IMember){
- IMember member = (IMember) element;
- if (member.isBinary()){
- element = member.getClassFile();
- } else {
- element = member.getJavaScriptUnit();
- }
- }
- if (element == null) return false;
- if (markerDelta == null) return false;
-
- String markerDeltarHandleId = (String)markerDelta.getAttribute(ATT_HANDLE_ID);
- if (markerDeltarHandleId == null) return false;
-
- IJavaScriptElement markerElement = JavaScriptCore.create(markerDeltarHandleId);
- while (true){
- if (element.equals(markerElement)) return true; // external elements may still be equal with different handleIDs.
-
- // cycle through enclosing types in case marker is associated with a classfile (15568)
- if (markerElement instanceof IClassFile){
- IType enclosingType = ((IClassFile)markerElement).getType().getDeclaringType();
- if (enclosingType != null){
- markerElement = enclosingType.getClassFile(); // retry with immediate enclosing classfile
- continue;
- }
- }
- break;
- }
- return false;
- }
-
- /**
- * Creates and returns a new access rule with the given file pattern and kind.
- * <p>
- * The rule kind is one of {@link IAccessRule#K_ACCESSIBLE}, {@link IAccessRule#K_DISCOURAGED},
- * or {@link IAccessRule#K_NON_ACCESSIBLE}, optionally combined with {@link IAccessRule#IGNORE_IF_BETTER},
- * e..g. <code>IAccessRule.K_NON_ACCESSIBLE | IAccessRule.IGNORE_IF_BETTER</code>.
- * </p>
- *
- * @param filePattern the file pattern this access rule should match
- * @param kind one of {@link IAccessRule#K_ACCESSIBLE}, {@link IAccessRule#K_DISCOURAGED},
- * or {@link IAccessRule#K_NON_ACCESSIBLE}, optionally combined with
- * {@link IAccessRule#IGNORE_IF_BETTER}
- * @return a new access rule
- */
- public static IAccessRule newAccessRule(IPath filePattern, int kind) {
- return new ClasspathAccessRule(filePattern, kind);
- }
-
- /**
- * Creates and returns a new includepath attribute with the given name and the given value.
- *
- * @return a new includepath attribute
- */
- public static IIncludePathAttribute newIncludepathAttribute(String name, String value) {
- return new ClasspathAttribute(name, value);
- }
-
- /**
- * Creates and returns a new includepath entry of kind <code>CPE_CONTAINER</code>
- * for the given path. This method is fully equivalent to calling
- * {@link #newContainerEntry(IPath, IAccessRule[], IIncludePathAttribute[], boolean)
- * newContainerEntry(containerPath, new IAccessRule[0], new IIncludePathAttribute[0], false)}.
- * <p>
- * @param containerPath the path identifying the container, it must be formed of two
- * segments
- * @return a new container includepath entry
- *
- * @see JavaScriptCore#getJsGlobalScopeContainer(IPath, IJavaScriptProject)
- */
- public static IIncludePathEntry newContainerEntry(IPath containerPath) {
- return newContainerEntry(
- containerPath,
- ClasspathEntry.NO_ACCESS_RULES,
- ClasspathEntry.NO_EXTRA_ATTRIBUTES,
- false/*not exported*/);
- }
-
- /**
- * Creates and returns a new includepath entry of kind <code>CPE_CONTAINER</code>
- * for the given path. This method is fully equivalent to calling
- * {@link #newContainerEntry(IPath, IAccessRule[], IIncludePathAttribute[], boolean)
- * newContainerEntry(containerPath, new IAccessRule[0], new IIncludePathAttribute[0], isExported)}.
- *
- * @param containerPath the path identifying the container, it must be formed of at least
- * one segment (ID+hints)
- * @param isExported a boolean indicating whether this entry is contributed to dependent
- * projects in addition to the output location
- * @return a new container includepath entry
- *
- * @see JavaScriptCore#getJsGlobalScopeContainer(IPath, IJavaScriptProject)
- * @see JavaScriptCore#setJsGlobalScopeContainer(IPath, IJavaScriptProject[], IJsGlobalScopeContainer[], IProgressMonitor)
- */
- public static IIncludePathEntry newContainerEntry(IPath containerPath, boolean isExported) {
- return newContainerEntry(
- containerPath,
- ClasspathEntry.NO_ACCESS_RULES,
- ClasspathEntry.NO_EXTRA_ATTRIBUTES,
- isExported);
- }
-
- /**
- * Creates and returns a new includepath entry of kind <code>CPE_CONTAINER</code>
- * for the given path. The path of the container will be used during resolution so as to map this
- * container entry to a set of other includepath entries the container is acting for.
- * <p>
- * A container entry allows to express indirect references to a set of libraries, projects and variable entries,
- * which can be interpreted differently for each JavaScript project where it is used.
- * A includepath container entry can be resolved using <code>JavaScriptCore.getResolvedJsGlobalScopeContainer</code>,
- * and updated with <code>JavaScriptCore.JsGlobalScopeContainerChanged</code>
- * <p>
- * A container is exclusively resolved by a <code>JsGlobalScopeContainerInitializer</code> registered onto the
- * extension point "org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer".
- * <p>
- * A container path must be formed of at least one segment, where: <ul>
- * <li> the first segment is a unique ID identifying the target container, there must be a container initializer registered
- * onto this ID through the extension point "org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer". </li>
- * <li> the remaining segments will be passed onto the initializer, and can be used as additional
- * hints during the initialization phase. </li>
- * </ul>
- * <p>
- * Example of an JsGlobalScopeContainerInitializer for a includepath container denoting a default JDK container:
- * <pre>
- * containerEntry = JavaScriptCore.newContainerEntry(new Path("MyProvidedJDK/default"));
- *
- * &lt;extension
- * point="org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer"&gt;
- * &lt;containerInitializer
- * id="MyProvidedJDK"
- * class="com.example.MyInitializer"/&gt;
- * </pre>
- * <p>
- * The access rules determine the set of accessible source and class files
- * in the container. If the list of access rules is empty, then all files
- * in this container are accessible.
- * See {@link IAccessRule} for a detailed description of access
- * rules. Note that if an entry defined by the container defines access rules,
- * then these access rules are combined with the given access rules.
- * The given access rules are considered first, then the entry's access rules are
- * considered.
- * </p>
- * <p>
- * The <code>extraAttributes</code> list contains name/value pairs that must be persisted with
- * this entry. If no extra attributes are provided, an empty array must be passed in.<br>
- * Note that this list should not contain any duplicate name.
- * </p>
- * <p>
- * The <code>isExported</code> flag indicates whether this entry is contributed to dependent
- * projects. If not exported, dependent projects will not see any of the classes from this entry.
- * If exported, dependent projects will concatenate the accessible files patterns of this entry with the
- * accessible files patterns of the projects, and they will concatenate the non accessible files patterns of this entry
- * with the non accessible files patterns of the project.
- * </p>
- * <p>
- * Note that this operation does not attempt to validate includepath containers
- * or access the resources at the given paths.
- * </p>
- *
- * @param containerPath the path identifying the container, it must be formed of at least
- * one segment (ID+hints)
- * @param accessRules the possibly empty list of access rules for this entry
- * @param extraAttributes the possibly empty list of extra attributes to persist with this entry
- * @param isExported a boolean indicating whether this entry is contributed to dependent
- * projects in addition to the output location
- * @return a new container includepath entry
- *
- * @see JavaScriptCore#getJsGlobalScopeContainer(IPath, IJavaScriptProject)
- * @see JavaScriptCore#setJsGlobalScopeContainer(IPath, IJavaScriptProject[], IJsGlobalScopeContainer[], IProgressMonitor)
- * @see JavaScriptCore#newContainerEntry(IPath, boolean)
- * @see JavaScriptCore#newAccessRule(IPath, int)
- */
- public static IIncludePathEntry newContainerEntry(
- IPath containerPath,
- IAccessRule[] accessRules,
- IIncludePathAttribute[] extraAttributes,
- boolean isExported) {
-
- if (containerPath == null) {
- Assert.isTrue(false, "Container path cannot be null"); //$NON-NLS-1$
- } else if (containerPath.segmentCount() < 1) {
- Assert.isTrue(
- false,
- "Illegal classpath container path: \'" + containerPath.makeRelative().toString() + "\', must have at least one segment (containerID+hints)"); //$NON-NLS-1$//$NON-NLS-2$
- }
- return new ClasspathEntry(
- IPackageFragmentRoot.K_SOURCE,
- IIncludePathEntry.CPE_CONTAINER,
- containerPath,
- ClasspathEntry.INCLUDE_ALL, // inclusion patterns
- ClasspathEntry.EXCLUDE_NONE, // exclusion patterns
- null, // source attachment
- null, // source attachment root
- null, // specific output folder
- isExported,
- accessRules,
- true, // combine access rules
- extraAttributes);
- }
-
- /**
- * Creates and returns a type hierarchy for all types in the given
- * region, considering subtypes within that region and considering types in the
- * working copies with the given owner.
- * In other words, the owner's working copies will take
- * precedence over their original javaScript units in the workspace.
- * <p>
- * Note that if a working copy is empty, it will be as if the original compilation
- * unit had been deleted.
- * <p>
- *
- * @param monitor the given progress monitor
- * @param region the given region
- * @param owner the owner of working copies that take precedence over their original javaScript units,
- * or <code>null</code> if the primary working copy owner should be used
- * @exception JavaScriptModelException if an element in the region does not exist or if an
- * exception occurs while accessing its corresponding resource
- * @exception IllegalArgumentException if region is <code>null</code>
- * @return a type hierarchy for all types in the given
- * region, considering subtypes within that region
- */
- public static ITypeHierarchy newTypeHierarchy(IRegion region, WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaScriptModelException {
- if (region == null) {
- throw new IllegalArgumentException(Messages.hierarchy_nullRegion);
- }
- IJavaScriptUnit[] workingCopies = JavaModelManager.getJavaModelManager().getWorkingCopies(owner, true/*add primary working copies*/);
- CreateTypeHierarchyOperation op =
- new CreateTypeHierarchyOperation(region, workingCopies, null, true/*compute subtypes*/);
- op.runOperation(monitor);
- return op.getResult();
- }
-
- /**
- * Creates and returns a new non-exported includepath entry of kind <code>CPE_LIBRARY</code> for the
- * JAR or folder identified by the given absolute path. This specifies that all package fragments
- * within the root will have children of type <code>IClassFile</code>.
- * This method is fully equivalent to calling
- * {@link #newLibraryEntry(IPath, IPath, IPath, IAccessRule[], IIncludePathAttribute[], boolean)
- * newLibraryEntry(path, sourceAttachmentPath, sourceAttachmentRootPath, new IAccessRule[0], new IIncludePathAttribute[0], false)}.
- *
- * @param path the absolute path of the binary archive
- * @param sourceAttachmentPath the absolute path of the corresponding source archive or folder,
- * or <code>null</code> if none. Note, since 3.0, an empty path is allowed to denote no source attachment.
- * and will be automatically converted to <code>null</code>.
- * @param sourceAttachmentRootPath the location of the root of the source files within the source archive or folder
- * or <code>null</code> if this location should be automatically detected.
- * @return a new library includepath entry
- */
- public static IIncludePathEntry newLibraryEntry(
- IPath path,
- IPath sourceAttachmentPath,
- IPath sourceAttachmentRootPath) {
-
- return newLibraryEntry(
- path,
- sourceAttachmentPath,
- sourceAttachmentRootPath,
- ClasspathEntry.NO_ACCESS_RULES,
- ClasspathEntry.NO_EXTRA_ATTRIBUTES,
- false/*not exported*/);
- }
-
- /**
- * Creates and returns a new includepath entry of kind <code>CPE_LIBRARY</code> for the JAR or folder
- * identified by the given absolute path. This specifies that all package fragments within the root
- * will have children of type <code>IClassFile</code>.
- * This method is fully equivalent to calling
- * {@link #newLibraryEntry(IPath, IPath, IPath, IAccessRule[], IIncludePathAttribute[], boolean)
- * newLibraryEntry(path, sourceAttachmentPath, sourceAttachmentRootPath, new IAccessRule[0], new IIncludePathAttribute[0], isExported)}.
- *
- * @param path the absolute path of the binary archive
- * @param sourceAttachmentPath the absolute path of the corresponding source archive or folder,
- * or <code>null</code> if none. Note, since 3.0, an empty path is allowed to denote no source attachment.
- * and will be automatically converted to <code>null</code>.
- * @param sourceAttachmentRootPath the location of the root of the source files within the source archive or folder
- * or <code>null</code> if this location should be automatically detected.
- * @param isExported indicates whether this entry is contributed to dependent
- * projects in addition to the output location
- * @return a new library includepath entry
- */
- public static IIncludePathEntry newLibraryEntry(
- IPath path,
- IPath sourceAttachmentPath,
- IPath sourceAttachmentRootPath,
- boolean isExported) {
-
- return newLibraryEntry(
- path,
- sourceAttachmentPath,
- sourceAttachmentRootPath,
- ClasspathEntry.NO_ACCESS_RULES,
- ClasspathEntry.NO_EXTRA_ATTRIBUTES,
- isExported);
- }
-
- /**
- * Creates and returns a new includepath entry of kind <code>CPE_LIBRARY</code> for the JAR or folder
- * identified by the given absolute path. This specifies that all package fragments within the root
- * will have children of type <code>IClassFile</code>.
- * <p>
- * A library entry is used to denote a prerequisite JAR or root folder containing binaries.
- * The target JAR can either be defined internally to the workspace (absolute path relative
- * to the workspace root) or externally to the workspace (absolute path in the file system).
- * The target root folder can only be defined internally to the workspace (absolute path relative
- * to the workspace root). To use a binary folder external to the workspace, it must first be
- * linked (see IFolder#createLink(...)).
- * <p>
- * <p>
- * The <code>extraAttributes</code> list contains name/value pairs that must be persisted with
- * this entry. If no extra attributes are provided, an empty array must be passed in.<br>
- * Note that this list should not contain any duplicate name.
- * </p>
- * <p>
- * The <code>isExported</code> flag indicates whether this entry is contributed to dependent
- * projects. If not exported, dependent projects will not see any of the classes from this entry.
- * If exported, dependent projects will concatenate the accessible files patterns of this entry with the
- * accessible files patterns of the projects, and they will concatenate the non accessible files patterns of this entry
- * with the non accessible files patterns of the project.
- * </p>
- *
- * @param path the absolute path of the binary archive
- * @param sourceAttachmentPath the absolute path of the corresponding source archive or folder,
- * or <code>null</code> if none. Note, since 3.0, an empty path is allowed to denote no source attachment.
- * and will be automatically converted to <code>null</code>.
- * @param sourceAttachmentRootPath the location of the root of the source files within the source archive or folder
- * or <code>null</code> if this location should be automatically detected.
- * @param accessRules the possibly empty list of access rules for this entry
- * @param extraAttributes the possibly empty list of extra attributes to persist with this entry
- * @param isExported indicates whether this entry is contributed to dependent
- * projects in addition to the output location
- * @return a new library includepath entry
- */
- public static IIncludePathEntry newLibraryEntry(
- IPath path,
- IPath sourceAttachmentPath,
- IPath sourceAttachmentRootPath,
- IAccessRule[] accessRules,
- IIncludePathAttribute[] extraAttributes,
- 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"); //$NON-NLS-1$
- if (sourceAttachmentPath != null) {
- if (sourceAttachmentPath.isEmpty()) {
- sourceAttachmentPath = null; // treat empty path as none
- } else if (!sourceAttachmentPath.isAbsolute()) {
- Assert.isTrue(false, "Source attachment path '" //$NON-NLS-1$
- + sourceAttachmentPath
- + "' for IIncludePathEntry must be absolute"); //$NON-NLS-1$
- }
- }
- return new ClasspathEntry(
- IPackageFragmentRoot.K_BINARY,
- IIncludePathEntry.CPE_LIBRARY,
- JavaProject.canonicalizedPath(path),
- ClasspathEntry.INCLUDE_ALL, // inclusion patterns
- ClasspathEntry.EXCLUDE_NONE, // exclusion patterns
- sourceAttachmentPath,
- sourceAttachmentRootPath,
- null, // specific output folder
- isExported,
- accessRules,
- false, // no access rules to combine
- extraAttributes);
- }
-
- /**
- * Creates and returns a new includepath entry of kind <code>CPE_LIBRARY</code> for the JAR or folder
- * identified by the given absolute path. This specifies that all package fragments within the root
- * will have children of type <code>IClassFile</code>.
- * <p>
- * A library entry is used to denote a prerequisite JAR or root folder containing binaries.
- * The target JAR can either be defined internally to the workspace (absolute path relative
- * to the workspace root) or externally to the workspace (absolute path in the file system).
- * The target root folder can only be defined internally to the workspace (absolute path relative
- * to the workspace root). To use a binary folder external to the workspace, it must first be
- * linked (see IFolder#createLink(...)).
- * <p>
- * <p>
- * The <code>extraAttributes</code> list contains name/value pairs that must be persisted with
- * this entry. If no extra attributes are provided, an empty array must be passed in.<br>
- * Note that this list should not contain any duplicate name.
- * </p>
- * <p>
- * The <code>isExported</code> flag indicates whether this entry is contributed to dependent
- * projects. If not exported, dependent projects will not see any of the classes from this entry.
- * If exported, dependent projects will concatenate the accessible files patterns of this entry with the
- * accessible files patterns of the projects, and they will concatenate the non accessible files patterns of this entry
- * with the non accessible files patterns of the project.
- * </p>
- *
- * @param path the absolute path of the binary archive
- * @param sourceAttachmentPath the absolute path of the corresponding source archive or folder,
- * or <code>null</code> if none. Note, since 3.0, an empty path is allowed to denote no source attachment.
- * and will be automatically converted to <code>null</code>.
- * @param sourceAttachmentRootPath the location of the root of the source files within the source archive or folder
- * or <code>null</code> if this location should be automatically detected.
- * @param accessRules the possibly empty list of access rules for this entry
- * @param exclusionPatterns the possibly empty list of exclusion patterns
- * represented as relative paths
- * @param extraAttributes the possibly empty list of extra attributes to persist with this entry
- * @param isExported indicates whether this entry is contributed to dependent
- * projects in addition to the output location
- * @return a new library includepath entry
- */
- public static IIncludePathEntry newLibraryEntry(
- IPath path,
- IPath sourceAttachmentPath,
- IPath sourceAttachmentRootPath,
- IAccessRule[] accessRules,
- IIncludePathAttribute[] extraAttributes,
- IPath[] exclusionPatterns,
- 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"); //$NON-NLS-1$
- if (sourceAttachmentPath != null) {
- if (sourceAttachmentPath.isEmpty()) {
- sourceAttachmentPath = null; // treat empty path as none
- } else if (!sourceAttachmentPath.isAbsolute()) {
- Assert.isTrue(false, "Source attachment path '" //$NON-NLS-1$
- + sourceAttachmentPath
- + "' for IIncludePathEntry must be absolute"); //$NON-NLS-1$
- }
- }
- return new ClasspathEntry(
- IPackageFragmentRoot.K_BINARY,
- IIncludePathEntry.CPE_LIBRARY,
- JavaProject.canonicalizedPath(path),
- ClasspathEntry.INCLUDE_ALL, // inclusion patterns
- exclusionPatterns, // exclusion patterns
- sourceAttachmentPath,
- sourceAttachmentRootPath,
- null, // specific output folder
- isExported,
- accessRules,
- false, // no access rules to combine
- extraAttributes);
- }
-
- /**
- * Creates and returns a new non-exported includepath entry of kind <code>CPE_PROJECT</code>
- * for the project identified by the given absolute path.
- * This method is fully equivalent to calling
- * {@link #newProjectEntry(IPath, IAccessRule[], boolean, IIncludePathAttribute[], boolean)
- * newProjectEntry(path, new IAccessRule[0], true, new IIncludePathAttribute[0], false)}.
- *
- * @param path the absolute path of the binary archive
- * @return a new project includepath entry
- */
- public static IIncludePathEntry newProjectEntry(IPath path) {
- return newProjectEntry(path, false);
- }
-
- /**
- * Creates and returns a new includepath entry of kind <code>CPE_PROJECT</code>
- * for the project identified by the given absolute path.
- * This method is fully equivalent to calling
- * {@link #newProjectEntry(IPath, IAccessRule[], boolean, IIncludePathAttribute[], boolean)
- * newProjectEntry(path, new IAccessRule[0], true, new IIncludePathAttribute[0], isExported)}.
- *
- * @param path the absolute path of the prerequisite project
- * @param isExported indicates whether this entry is contributed to dependent
- * projects in addition to the output location
- * @return a new project includepath entry
- */
- public static IIncludePathEntry newProjectEntry(IPath path, boolean isExported) {
-
- if (!path.isAbsolute()) Assert.isTrue(false, "Path for IIncludePathEntry must be absolute"); //$NON-NLS-1$
-
- return newProjectEntry(
- path,
- ClasspathEntry.NO_ACCESS_RULES,
- true,
- ClasspathEntry.NO_EXTRA_ATTRIBUTES,
- isExported);
- }
-
- /**
- * Creates and returns a new includepath entry of kind <code>CPE_PROJECT</code>
- * for the project identified by the given absolute path.
- * <p>
- * A project entry is used to denote a prerequisite project on a includepath.
- * The referenced project will be contributed as a whole, either as sources (in the JavaScript Model, it
- * contributes all its package fragment roots) or as binaries (when building, it contributes its
- * whole output location).
- * </p>
- * <p>
- * A project reference allows to indirect through another project, independently from its internal layout.
- * </p><p>
- * The prerequisite project is referred to using an absolute path relative to the workspace root.
- * </p>
- * <p>
- * The access rules determine the set of accessible class files
- * in the project. If the list of access rules is empty then all files
- * in this project are accessible.
- * See {@link IAccessRule} for a detailed description of access rules.
- * </p>
- * <p>
- * The <code>combineAccessRules</code> flag indicates whether access rules of one (or more)
- * exported entry of the project should be combined with the given access rules. If they should
- * be combined, the given access rules are considered first, then the entry's access rules are
- * considered.
- * </p>
- * <p>
- * The <code>extraAttributes</code> list contains name/value pairs that must be persisted with
- * this entry. If no extra attributes are provided, an empty array must be passed in.<br>
- * Note that this list should not contain any duplicate name.
- * </p>
- * <p>
- * The <code>isExported</code> flag indicates whether this entry is contributed to dependent
- * projects. If not exported, dependent projects will not see any of the classes from this entry.
- * If exported, dependent projects will concatenate the accessible files patterns of this entry with the
- * accessible files patterns of the projects, and they will concatenate the non accessible files patterns of this entry
- * with the non accessible files patterns of the project.
- * </p>
- *
- * @param path the absolute path of the prerequisite project
- * @param accessRules the possibly empty list of access rules for this entry
- * @param combineAccessRules whether the access rules of the project's exported entries should be combined with the given access rules
- * @param extraAttributes the possibly empty list of extra attributes to persist with this entry
- * @param isExported indicates whether this entry is contributed to dependent
- * projects in addition to the output location
- * @return a new project includepath entry
- */
- public static IIncludePathEntry newProjectEntry(
- IPath path,
- IAccessRule[] accessRules,
- boolean combineAccessRules,
- IIncludePathAttribute[] extraAttributes,
- boolean isExported) {
-
- if (!path.isAbsolute()) Assert.isTrue(false, "Path for IIncludePathEntry must be absolute"); //$NON-NLS-1$
-
- return new ClasspathEntry(
- IPackageFragmentRoot.K_SOURCE,
- IIncludePathEntry.CPE_PROJECT,
- path,
- ClasspathEntry.INCLUDE_ALL, // inclusion patterns
- ClasspathEntry.EXCLUDE_NONE, // exclusion patterns
- null, // source attachment
- null, // source attachment root
- null, // specific output folder
- isExported,
- accessRules,
- combineAccessRules,
- extraAttributes);
- }
-
- /**
- * Returns a new empty region.
- *
- * @return a new empty region
- */
- public static IRegion newRegion() {
- return new Region();
- }
-
- /**
- * Creates and returns a new includepath entry of kind <code>CPE_SOURCE</code>
- * for all files in the project's source folder identified by the given
- * absolute workspace-relative path.
- * <p>
- * The convenience method is fully equivalent to:
- * <pre>
- * newSourceEntry(path, new IPath[] {}, new IPath[] {}, null);
- * </pre>
- * </p>
- *
- * @param path the absolute workspace-relative path of a source folder
- * @return a new source includepath entry
- * @see #newSourceEntry(IPath, IPath[], IPath[], IPath)
- */
- public static IIncludePathEntry newSourceEntry(IPath path) {
-
- return newSourceEntry(path, ClasspathEntry.INCLUDE_ALL, ClasspathEntry.EXCLUDE_NONE, null /*output location*/);
- }
-
- /**
- * Creates and returns a new includepath entry of kind <code>CPE_SOURCE</code>
- * for the project's source folder identified by the given absolute
- * workspace-relative path but excluding all source files with paths
- * matching any of the given patterns.
- * <p>
- * The convenience method is fully equivalent to:
- * <pre>
- * newSourceEntry(path, new IPath[] {}, exclusionPatterns, null);
- * </pre>
- * </p>
- *
- * @param path the absolute workspace-relative path of a source folder
- * @param exclusionPatterns the possibly empty list of exclusion patterns
- * represented as relative paths
- * @return a new source includepath entry
- * @see #newSourceEntry(IPath, IPath[], IPath[], IPath)
- */
- public static IIncludePathEntry newSourceEntry(IPath path, IPath[] exclusionPatterns) {
-
- return newSourceEntry(path, ClasspathEntry.INCLUDE_ALL, exclusionPatterns, null /*output location*/);
- }
-
- /**
- * Creates and returns a new includepath entry of kind <code>CPE_SOURCE</code>
- * for the project's source folder identified by the given absolute
- * workspace-relative path but excluding all source files with paths
- * matching any of the given patterns, and associated with a specific output location
- * (that is, ".class" files are not going to the project default output location).
- * <p>
- * The convenience method is fully equivalent to:
- * <pre>
- * newSourceEntry(path, new IPath[] {}, exclusionPatterns, specificOutputLocation);
- * </pre>
- * </p>
- *
- * @param path the absolute workspace-relative path of a source folder
- * @param exclusionPatterns the possibly empty list of exclusion patterns
- * represented as relative paths
- * @param specificOutputLocation the specific output location for this source entry (<code>null</code> if using project default ouput location)
- * @return a new source includepath entry
- * @see #newSourceEntry(IPath, IPath[], IPath[], IPath)
- */
- public static IIncludePathEntry newSourceEntry(IPath path, IPath[] exclusionPatterns, IPath specificOutputLocation) {
-
- return newSourceEntry(path, ClasspathEntry.INCLUDE_ALL, exclusionPatterns, specificOutputLocation);
- }
-
- /**
- * Creates and returns a new includepath entry of kind <code>CPE_SOURCE</code>
- * for the project's source folder identified by the given absolute
- * workspace-relative path but excluding all source files with paths
- * matching any of the given patterns, and associated with a specific output location
- * (that is, ".class" files are not going to the project default output location).
- * <p>
- * The convenience method is fully equivalent to:
- * <pre>
- * newSourceEntry(path, new IPath[] {}, exclusionPatterns, specificOutputLocation, new IIncludePathAttribute[] {});
- * </pre>
- * </p>
- *
- * @param path the absolute workspace-relative path of a source folder
- * @param inclusionPatterns the possibly empty list of inclusion patterns
- * represented as relative paths
- * @param exclusionPatterns the possibly empty list of exclusion patterns
- * represented as relative paths
- * @param specificOutputLocation the specific output location for this source entry (<code>null</code> if using project default ouput location)
- * @return a new source includepath entry
- * @see #newSourceEntry(IPath, IPath[], IPath[], IPath, IIncludePathAttribute[])
- */
- public static IIncludePathEntry newSourceEntry(IPath path, IPath[] inclusionPatterns, IPath[] exclusionPatterns, IPath specificOutputLocation) {
- return newSourceEntry(path, inclusionPatterns, exclusionPatterns, specificOutputLocation, ClasspathEntry.NO_EXTRA_ATTRIBUTES);
- }
-
- /**
- * Creates and returns a new includepath entry of kind <code>CPE_SOURCE</code>
- * for the project's source folder identified by the given absolute
- * workspace-relative path using the given inclusion and exclusion patterns
- * to determine which source files are included, and the given output path
- * to control the output location of generated files.
- * <p>
- * The source folder is referred to using an absolute path relative to the
- * workspace root, e.g. <code>/Project/src</code>. A project's source
- * folders are located with that project. That is, a source includepath
- * entry specifying the path <code>/P1/src</code> is only usable for
- * project <code>P1</code>.
- * </p>
- * <p>
- * The inclusion patterns determines the initial set of source files that
- * are to be included; the exclusion patterns are then used to reduce this
- * set. When no inclusion patterns are specified, the initial file set
- * includes all relevent files in the resource tree rooted at the source
- * entry's path. On the other hand, specifying one or more inclusion
- * patterns means that all <b>and only</b> files matching at least one of
- * the specified patterns are to be included. If exclusion patterns are
- * specified, the initial set of files is then reduced by eliminating files
- * matched by at least one of the exclusion patterns. Inclusion and
- * exclusion patterns look like relative file paths with wildcards and are
- * interpreted relative to the source entry's path. File patterns are
- * case-sensitive can contain '**', '*' or '?' wildcards (see
- * {@link IIncludePathEntry#getExclusionPatterns()} for the full description
- * of their syntax and semantics). The resulting set of files are included
- * in the corresponding package fragment root; all package fragments within
- * the root will have children of type <code>IJavaScriptUnit</code>.
- * </p>
- * <p>
- * Also note that all sources/binaries inside a project are contributed as
- * a whole through a project entry
- * (see <code>JavaScriptCore.newProjectEntry</code>). Particular source entries
- * cannot be selectively exported.
- * </p>
- * <p>
- * The <code>extraAttributes</code> list contains name/value pairs that must be persisted with
- * this entry. If no extra attributes are provided, an empty array must be passed in.<br>
- * Note that this list should not contain any duplicate name.
- * </p>
- *
- * @param path the absolute workspace-relative path of a source folder
- * @param inclusionPatterns the possibly empty list of inclusion patterns
- * represented as relative paths
- * @param exclusionPatterns the possibly empty list of exclusion patterns
- * represented as relative paths
- * @param specificOutputLocation the specific output location for this source entry (<code>null</code> if using project default ouput location)
- * @param extraAttributes the possibly empty list of extra attributes to persist with this entry
- * @return a new source includepath entry with the given exclusion patterns
- * @see IIncludePathEntry#getInclusionPatterns()
- * @see IIncludePathEntry#getExclusionPatterns()
- * @see IIncludePathEntry#getOutputLocation()
- */
- public static IIncludePathEntry newSourceEntry(IPath path, IPath[] inclusionPatterns, IPath[] exclusionPatterns, IPath specificOutputLocation, IIncludePathAttribute[] extraAttributes) {
-
- if (path == null) Assert.isTrue(false, "Source path cannot be null"); //$NON-NLS-1$
- if (!path.isAbsolute()) Assert.isTrue(false, "Path for IIncludePathEntry must be absolute"); //$NON-NLS-1$
- if (exclusionPatterns == null) Assert.isTrue(false, "Exclusion pattern set cannot be null"); //$NON-NLS-1$
- if (inclusionPatterns == null) Assert.isTrue(false, "Inclusion pattern set cannot be null"); //$NON-NLS-1$
-
- return new ClasspathEntry(
- IPackageFragmentRoot.K_SOURCE,
- IIncludePathEntry.CPE_SOURCE,
- path,
- inclusionPatterns,
- exclusionPatterns,
- null, // source attachment
- null, // source attachment root
- specificOutputLocation, // custom output location
- false,
- null,
- false, // no access rules to combine
- extraAttributes);
- }
-
- /**
- * Creates and returns a new non-exported includepath entry of kind <code>CPE_VARIABLE</code>
- * for the given path. This method is fully equivalent to calling
- * {@link #newVariableEntry(IPath, IPath, IPath, IAccessRule[], IIncludePathAttribute[], boolean)
- * newVariableEntry(variablePath, variableSourceAttachmentPath, sourceAttachmentRootPath, new IAccessRule[0], new IIncludePathAttribute[0], false)}.
- *
- * @param variablePath the path of the binary archive; first segment is the
- * name of a includepath variable
- * @param variableSourceAttachmentPath the path of the corresponding source archive,
- * or <code>null</code> if none; if present, the first segment is the
- * name of a includepath variable (not necessarily the same variable
- * as the one that begins <code>variablePath</code>)
- * @param sourceAttachmentRootPath the location of the root of the source files within the source archive
- * or <code>null</code> if <code>variableSourceAttachmentPath</code> is also <code>null</code>
- * @return a new library includepath entry
- */
- public static IIncludePathEntry newVariableEntry(
- IPath variablePath,
- IPath variableSourceAttachmentPath,
- IPath sourceAttachmentRootPath) {
-
- return newVariableEntry(variablePath, variableSourceAttachmentPath, sourceAttachmentRootPath, false);
- }
-
- /**
- * Creates and returns a new includepath entry of kind <code>CPE_VARIABLE</code>
- * for the given path. This method is fully equivalent to calling
- * {@link #newVariableEntry(IPath, IPath, IPath, IAccessRule[], IIncludePathAttribute[], boolean)
- * newVariableEntry(variablePath, variableSourceAttachmentPath, sourceAttachmentRootPath, new IAccessRule[0], new IIncludePathAttribute[0], isExported)}.
- *
- * @param variablePath the path of the binary archive; first segment is the
- * name of a includepath variable
- * @param variableSourceAttachmentPath the path of the corresponding source archive,
- * or <code>null</code> if none; if present, the first segment is the
- * name of a includepath variable (not necessarily the same variable
- * as the one that begins <code>variablePath</code>)
- * @param variableSourceAttachmentRootPath the location of the root of the source files within the source archive
- * or <code>null</code> if <code>variableSourceAttachmentPath</code> is also <code>null</code>
- * @param isExported indicates whether this entry is contributed to dependent
- * projects in addition to the output location
- * @return a new variable includepath entry
- */
- public static IIncludePathEntry newVariableEntry(
- IPath variablePath,
- IPath variableSourceAttachmentPath,
- IPath variableSourceAttachmentRootPath,
- boolean isExported) {
-
- return newVariableEntry(
- variablePath,
- variableSourceAttachmentPath,
- variableSourceAttachmentRootPath,
- ClasspathEntry.NO_ACCESS_RULES,
- ClasspathEntry.NO_EXTRA_ATTRIBUTES,
- isExported);
- }
-
- /**
- * Creates and returns a new includepath entry of kind <code>CPE_VARIABLE</code>
- * for the given path. The first segment of the path is the name of a includepath variable.
- * The trailing segments of the path will be appended to resolved variable path.
- * <p>
- * A variable entry allows to express indirect references on a includepath to other projects or libraries,
- * depending on what the includepath variable is referring.
- * <p>
- * It is possible to register an automatic initializer (<code>JsGlobalScopeVariableInitializer</code>),
- * which will be invoked through the extension point "org.eclipse.wst.jsdt.core.JsGlobalScopeVariableInitializer".
- * After resolution, a includepath variable entry may either correspond to a project or a library entry.
- * <p>
- * The <code>extraAttributes</code> list contains name/value pairs that must be persisted with
- * this entry. If no extra attributes are provided, an empty array must be passed in.<br>
- * Note that this list should not contain any duplicate name.
- * </p>
- * <p>
- * The <code>isExported</code> flag indicates whether this entry is contributed to dependent
- * projects. If not exported, dependent projects will not see any of the classes from this entry.
- * If exported, dependent projects will concatenate the accessible files patterns of this entry with the
- * accessible files patterns of the projects, and they will concatenate the non accessible files patterns of this entry
- * with the non accessible files patterns of the project.
- * </p>
- * <p>
- * Note that this operation does not attempt to validate includepath variables
- * or access the resources at the given paths.
- * </p>
- *
- * @param variablePath the path of the binary archive; first segment is the
- * name of a includepath variable
- * @param variableSourceAttachmentPath the path of the corresponding source archive,
- * or <code>null</code> if none; if present, the first segment is the
- * name of a includepath variable (not necessarily the same variable
- * as the one that begins <code>variablePath</code>)
- * @param variableSourceAttachmentRootPath the location of the root of the source files within the source archive
- * or <code>null</code> if <code>variableSourceAttachmentPath</code> is also <code>null</code>
- * @param accessRules the possibly empty list of access rules for this entry
- * @param extraAttributes the possibly empty list of extra attributes to persist with this entry
- * @param isExported indicates whether this entry is contributed to dependent
- * projects in addition to the output location
- * @return a new variable includepath entry
- */
- public static IIncludePathEntry newVariableEntry(
- IPath variablePath,
- IPath variableSourceAttachmentPath,
- IPath variableSourceAttachmentRootPath,
- IAccessRule[] accessRules,
- IIncludePathAttribute[] extraAttributes,
- boolean isExported) {
-
- if (variablePath == null) Assert.isTrue(false, "Variable path cannot be null"); //$NON-NLS-1$
- if (variablePath.segmentCount() < 1) {
- Assert.isTrue(
- false,
- "Illegal includepath variable path: \'" + variablePath.makeRelative().toString() + "\', must have at least one segment"); //$NON-NLS-1$//$NON-NLS-2$
- }
-
- return new ClasspathEntry(
- IPackageFragmentRoot.K_SOURCE,
- IIncludePathEntry.CPE_VARIABLE,
- variablePath,
- ClasspathEntry.INCLUDE_ALL, // inclusion patterns
- ClasspathEntry.EXCLUDE_NONE, // exclusion patterns
- variableSourceAttachmentPath, // source attachment
- variableSourceAttachmentRootPath, // source attachment root
- null, // specific output folder
- isExported,
- accessRules,
- false, // no access rules to combine
- extraAttributes);
- }
-
- /**
- * Removed the given includepath variable. Does nothing if no value was
- * set for this includepath variable.
- * <p>
- * This functionality cannot be used while the resource tree is locked.
- * <p>
- * Includepath variable values are persisted locally to the workspace, and
- * are preserved from session to session.
- * <p>
- *
- * @param variableName the name of the includepath variable
- * @param monitor the progress monitor to report progress
- * @see #setIncludepathVariable(String, IPath)
- */
- public static void removeIncludepathVariable(String variableName, IProgressMonitor monitor) {
- try {
- SetVariablesOperation operation = new SetVariablesOperation(new String[]{ variableName}, new IPath[]{ null }, true/*update preferences*/);
- operation.runOperation(monitor);
- } catch (JavaScriptModelException e) {
- Util.log(e, "Exception while removing variable " + variableName); //$NON-NLS-1$
- }
- }
-
- /**
- * Removes the given element changed listener.
- * Has no affect if an identical listener is not registered.
- *
- * @param listener the listener
- */
- public static void removeElementChangedListener(IElementChangedListener listener) {
- JavaModelManager.getJavaModelManager().deltaState.removeElementChangedListener(listener);
- }
-
- /**
- * Removes the file extension from the given file name, if it has a JavaScript-like file
- * extension. Otherwise the file name itself is returned.
- * Note this removes the dot ('.') before the extension as well.
- *
- * @param fileName the name of a file
- * @return the fileName without the JavaScript-like extension
- */
- public static String removeJavaScriptLikeExtension(String fileName) {
- return Util.getNameWithoutJavaLikeExtension(fileName);
- }
-
- /**
- * Removes the given pre-processing resource changed listener.
- * <p>
- * Has no affect if an identical listener is not registered.
- *
- * @param listener the listener
- */
- public static void removePreProcessingResourceChangedListener(IResourceChangeListener listener) {
- JavaModelManager.getJavaModelManager().deltaState.removePreResourceChangedListener(listener);
- }
-
-
-
- /**
- * Runs the given action as an atomic JavaScript model operation.
- * <p>
- * After running a method that modifies javaScript elements,
- * registered listeners receive after-the-fact notification of
- * what just transpired, in the form of a element changed event.
- * This method allows clients to call a number of
- * methods that modify javaScript elements and only have element
- * changed event notifications reported at the end of the entire
- * batch.
- * </p>
- * <p>
- * If this method is called outside the dynamic scope of another such
- * call, this method runs the action and then reports a single
- * element changed event describing the net effect of all changes
- * done to javaScript elements by the action.
- * </p>
- * <p>
- * If this method is called in the dynamic scope of another such
- * call, this method simply runs the action.
- * </p>
- *
- * @param action the action to perform
- * @param monitor a progress monitor, or <code>null</code> if progress
- * reporting and cancellation are not desired
- * @exception CoreException if the operation failed.
- */
- public static void run(IWorkspaceRunnable action, IProgressMonitor monitor) throws CoreException {
- run(action, ResourcesPlugin.getWorkspace().getRoot(), monitor);
- }
- /**
- * Runs the given action as an atomic JavaScript model operation.
- * <p>
- * After running a method that modifies javaScript elements,
- * registered listeners receive after-the-fact notification of
- * what just transpired, in the form of a element changed event.
- * This method allows clients to call a number of
- * methods that modify javaScript elements and only have element
- * changed event notifications reported at the end of the entire
- * batch.
- * </p>
- * <p>
- * If this method is called outside the dynamic scope of another such
- * call, this method runs the action and then reports a single
- * element changed event describing the net effect of all changes
- * done to javaScript elements by the action.
- * </p>
- * <p>
- * If this method is called in the dynamic scope of another such
- * call, this method simply runs the action.
- * </p>
- * <p>
- * The supplied scheduling rule is used to determine whether this operation can be
- * run simultaneously with workspace changes in other threads. See
- * <code>IWorkspace.run(...)</code> for more details.
- * </p>
- *
- * @param action the action to perform
- * @param rule the scheduling rule to use when running this operation, or
- * <code>null</code> if there are no scheduling restrictions for this operation.
- * @param monitor a progress monitor, or <code>null</code> if progress
- * reporting and cancellation are not desired
- * @exception CoreException if the operation failed.
- */
- public static void run(IWorkspaceRunnable action, ISchedulingRule rule, IProgressMonitor monitor) throws CoreException {
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- if (workspace.isTreeLocked()) {
- new BatchOperation(action).run(monitor);
- } else {
- // use IWorkspace.run(...) to ensure that a build will be done in autobuild mode
- workspace.run(new BatchOperation(action), rule, IWorkspace.AVOID_UPDATE, monitor);
- }
- }
- /**
- * Bind a container reference path to some actual containers (<code>IJsGlobalScopeContainer</code>).
- * This API must be invoked whenever changes in container need to be reflected onto the JavaModel.
- * Containers can have distinct values in different projects, therefore this API considers a
- * set of projects with their respective containers.
- * <p>
- * <code>containerPath</code> is the path under which these values can be referenced through
- * container includepath entries (<code>IIncludePathEntry#CPE_CONTAINER</code>). A container path
- * is formed by a first ID segment followed with extra segments, which can be used as additional hints
- * for the resolution. The container ID is used to identify a <code>JsGlobalScopeContainerInitializer</code>
- * registered on the extension point "org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer".
- * <p>
- * There is no assumption that each individual container value passed in argument
- * (<code>respectiveContainers</code>) must answer the exact same path when requested
- * <code>IJsGlobalScopeContainer#getPath</code>.
- * Indeed, the containerPath is just an indication for resolving it to an actual container object. It can be
- * delegated to a <code>JsGlobalScopeContainerInitializer</code>, which can be activated through the extension
- * point "org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer").
- * <p>
- * In reaction to changing container values, the JavaModel will be updated to reflect the new
- * state of the updated container. A combined JavaScript element delta will be notified to describe the corresponding
- * includepath changes resulting from the container update. This operation is batched, and automatically eliminates
- * unnecessary updates (new container is same as old one). This operation acquires a lock on the workspace's root.
- * <p>
- * This functionality cannot be used while the workspace is locked, since
- * it may create/remove some resource markers.
- * <p>
- * Includepath container values are persisted locally to the workspace, but
- * are not preserved from a session to another. It is thus highly recommended to register a
- * <code>JsGlobalScopeContainerInitializer</code> for each referenced container
- * (through the extension point "org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer").
- * <p>
- * Note: setting a container to <code>null</code> will cause it to be lazily resolved again whenever
- * its value is required. In particular, this will cause a registered initializer to be invoked
- * again.
- * <p>
- * @param containerPath - the name of the container reference, which is being updated
- * @param affectedProjects - the set of projects for which this container is being bound
- * @param respectiveContainers - the set of respective containers for the affected projects
- * @param monitor a monitor to report progress
- * @throws JavaScriptModelException
- * @see JsGlobalScopeContainerInitializer
- * @see #getJsGlobalScopeContainer(IPath, IJavaScriptProject)
- * @see IJsGlobalScopeContainer
- */
- public static void setJsGlobalScopeContainer(IPath containerPath, IJavaScriptProject[] affectedProjects, IJsGlobalScopeContainer[] respectiveContainers, IProgressMonitor monitor) throws JavaScriptModelException {
- if (affectedProjects.length != respectiveContainers.length)
- Assert.isTrue(false, "Projects and containers collections should have the same size"); //$NON-NLS-1$
- SetContainerOperation operation = new SetContainerOperation(containerPath, affectedProjects, respectiveContainers);
-// operation.runOperation(monitor);
-
- operation.progressMonitor=monitor;
-
- operation.execute();
-
-
-
- }
-
- /**
- * Sets the value of the given includepath variable.
- * The path must have at least one segment.
- * <p>
- * This functionality cannot be used while the resource tree is locked.
- * <p>
- * Includepath variable values are persisted locally to the workspace, and
- * are preserved from session to session.
- * <p>
- *
- * @param variableName the name of the includepath variable
- * @param path the path
- * @throws JavaScriptModelException
- * @see #getIncludepathVariable(String)
- *
- * @deprecated Use {@link #setIncludepathVariable(String, IPath, IProgressMonitor)} instead
- */
- public static void setIncludepathVariable(String variableName, IPath path)
- throws JavaScriptModelException {
-
- setIncludepathVariable(variableName, path, null);
- }
-
- /**
- * Sets the value of the given includepath variable.
- * The path must not be null.
- * <p>
- * This functionality cannot be used while the resource tree is locked.
- * <p>
- * Includepath variable values are persisted locally to the workspace, and
- * are preserved from session to session.
- * <p>
- * Updating a variable with the same value has no effect.
- *
- * @param variableName the name of the includepath variable
- * @param path the path
- * @param monitor a monitor to report progress
- * @throws JavaScriptModelException
- * @see #getIncludepathVariable(String)
- */
- public static void setIncludepathVariable(
- String variableName,
- IPath path,
- IProgressMonitor monitor)
- throws JavaScriptModelException {
-
- if (path == null) Assert.isTrue(false, "Variable path cannot be null"); //$NON-NLS-1$
- setIncludepathVariables(new String[]{variableName}, new IPath[]{ path }, monitor);
- }
-
- /**
- * Sets the values of all the given includepath variables at once.
- * Null paths can be used to request corresponding variable removal.
- * <p>
- * A combined JavaScript element delta will be notified to describe the corresponding
- * includepath changes resulting from the variables update. This operation is batched,
- * and automatically eliminates unnecessary updates (new variable is same as old one).
- * This operation acquires a lock on the workspace's root.
- * <p>
- * This functionality cannot be used while the workspace is locked, since
- * it may create/remove some resource markers.
- * <p>
- * Includepath variable values are persisted locally to the workspace, and
- * are preserved from session to session.
- * <p>
- * Updating a variable with the same value has no effect.
- *
- * @param variableNames an array of names for the updated includepath variables
- * @param paths an array of path updates for the modified includepath variables (null
- * meaning that the corresponding value will be removed
- * @param monitor a monitor to report progress
- * @throws JavaScriptModelException
- * @see #getIncludepathVariable(String)
- */
- public static void setIncludepathVariables(
- String[] variableNames,
- IPath[] paths,
- IProgressMonitor monitor)
- throws JavaScriptModelException {
-
- if (variableNames.length != paths.length) Assert.isTrue(false, "Variable names and paths collections should have the same size"); //$NON-NLS-1$
- SetVariablesOperation operation = new SetVariablesOperation(variableNames, paths, true/*update preferences*/);
- operation.runOperation(monitor);
- }
-
- /**
- * Sets the default's validator options inside the given options map according
- * to the given compliance.
- *
- * <p>The given compliance must be one of the compliance supported by the validator.
- * See {@link #getDefaultOptions()} for a list of compliance values.</p>
- *
- * <p>The list of modified options is:</p>
- * <ul>
- * <li>{@link #COMPILER_CODEGEN_TARGET_PLATFORM}</li>
- * <li>{@link #COMPILER_SOURCE}</li>
- * <li>{@link #COMPILER_COMPLIANCE}</li>
- * <li>{@link #COMPILER_PB_ASSERT_IDENTIFIER}</li>
- * <li>{@link #COMPILER_PB_ENUM_IDENTIFIER}</li>
- * </ul>
- *
- * <p>If the given compliance is unknown, the given map is unmodified.</p>
- *
- * @param compliance the given compliance
- * @param options the given options map
- */
- public static void setComplianceOptions(String compliance, Map options) {
- switch((int) (CompilerOptions.versionToJdkLevel(compliance) >>> 16)) {
- case ClassFileConstants.MAJOR_VERSION_1_3:
- options.put(JavaScriptCore.COMPILER_COMPLIANCE, JavaScriptCore.VERSION_1_3);
- options.put(JavaScriptCore.COMPILER_SOURCE, JavaScriptCore.VERSION_1_3);
- options.put(JavaScriptCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaScriptCore.VERSION_1_1);
- options.put(JavaScriptCore.COMPILER_PB_ASSERT_IDENTIFIER, JavaScriptCore.IGNORE);
- break;
- case ClassFileConstants.MAJOR_VERSION_1_4:
- options.put(JavaScriptCore.COMPILER_COMPLIANCE, JavaScriptCore.VERSION_1_4);
- options.put(JavaScriptCore.COMPILER_SOURCE, JavaScriptCore.VERSION_1_3);
- options.put(JavaScriptCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaScriptCore.VERSION_1_2);
- options.put(JavaScriptCore.COMPILER_PB_ASSERT_IDENTIFIER, JavaScriptCore.WARNING);
- break;
- case ClassFileConstants.MAJOR_VERSION_1_5:
- options.put(JavaScriptCore.COMPILER_COMPLIANCE, JavaScriptCore.VERSION_1_5);
- options.put(JavaScriptCore.COMPILER_SOURCE, JavaScriptCore.VERSION_1_5);
- options.put(JavaScriptCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaScriptCore.VERSION_1_5);
- options.put(JavaScriptCore.COMPILER_PB_ASSERT_IDENTIFIER, JavaScriptCore.ERROR);
- break;
- case ClassFileConstants.MAJOR_VERSION_1_6:
- options.put(JavaScriptCore.COMPILER_COMPLIANCE, JavaScriptCore.VERSION_1_6);
- options.put(JavaScriptCore.COMPILER_SOURCE, JavaScriptCore.VERSION_1_6);
- options.put(JavaScriptCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaScriptCore.VERSION_1_6);
- options.put(JavaScriptCore.COMPILER_PB_ASSERT_IDENTIFIER, JavaScriptCore.ERROR);
- break;
- case ClassFileConstants.MAJOR_VERSION_1_7:
- options.put(JavaScriptCore.COMPILER_COMPLIANCE, JavaScriptCore.VERSION_1_7);
- options.put(JavaScriptCore.COMPILER_SOURCE, JavaScriptCore.VERSION_1_7);
- options.put(JavaScriptCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaScriptCore.VERSION_1_7);
- options.put(JavaScriptCore.COMPILER_PB_ASSERT_IDENTIFIER, JavaScriptCore.ERROR);
- }
- }
-
- /**
- * Sets the current table of options. All and only the options explicitly
- * included in the given table are remembered; all previous option settings
- * are forgotten, including ones not explicitly mentioned.
- * <p>
- * For a complete description of the configurable options, see
- * <code>getDefaultOptions</code>.
- * </p>
- *
- * @param newOptions
- * the new options (key type: <code>String</code>; value type:
- * <code>String</code>), or <code>null</code> to reset all
- * options to their default values
- * @see JavaScriptCore#getDefaultOptions()
- * @see org.eclipse.wst.jsdt.internal.core.JavaCorePreferenceInitializer for changing default settings
- */
- public static void setOptions(Hashtable newOptions) {
- JavaModelManager.getJavaModelManager().setOptions(newOptions);
- }
-
- /* (non-Javadoc)
- * Shutdown the JavaScriptCore plug-in.
- * <p>
- * De-registers the JavaModelManager as a resource changed listener and save participant.
- * <p>
- * @see org.eclipse.core.runtime.Plugin#stop(BundleContext)
- */
- public void stop(BundleContext context) throws Exception {
- try {
- JavaModelManager.getJavaModelManager().shutdown();
- } finally {
- // ensure we call super.stop as the last thing
- super.stop(context);
- }
- }
-
- /* (non-Javadoc)
- * Startup the JavaScriptCore plug-in.
- * <p>
- * Registers the JavaModelManager as a resource changed listener and save participant.
- * Starts the background indexing, and restore saved includepath variable values.
- * <p>
- * @throws Exception
- * @see org.eclipse.core.runtime.Plugin#start(BundleContext)
- */
- public void start(BundleContext context) throws Exception {
- super.start(context);
- JavaModelManager.getJavaModelManager().startup();
- }
- public static String getSystemPath()
- {
- URL url=FileLocator.find(getJavaScriptCore().getBundle(),new Path("libraries"),null); //$NON-NLS-1$
- return url.getFile();
- }
-
-
- public static boolean isReadOnly(IResource resource)
- {
- QualifiedName qn=new QualifiedName(JavaScriptCore.PLUGIN_ID,JavaScriptCore.READ_ONLY_SOURCE_PROPERTY);
- try {
- String persistentProperty = resource.getPersistentProperty(qn);
- return "true".equals(persistentProperty);
- } catch (CoreException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return false;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/JavaScriptModelException.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/JavaScriptModelException.java
deleted file mode 100644
index daed7799..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/JavaScriptModelException.java
+++ /dev/null
@@ -1,176 +0,0 @@
-/*******************************************************************************
- * 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;
-
-import java.io.PrintStream;
-import java.io.PrintWriter;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.wst.jsdt.internal.core.JavaModelStatus;
-
-/**
- * A checked exception representing a failure in the JavaScript model.
- * JavaScript model exceptions contain a JavaScript-specific status object describing the
- * cause of the exception.
- * <p>
- * This class is not intended to be subclassed by clients. Instances of this
- * class are automatically created by the JavaScript model when problems arise, so
- * there is generally no need for clients to create instances.
- * </p>
- *
- * @see IJavaScriptModelStatus
- * @see IJavaScriptModelStatusConstants
- *
- * 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 JavaScriptModelException extends CoreException {
-
- private static final long serialVersionUID = -760398656505871287L; // backward compatible
-
- CoreException nestedCoreException;
-/**
- * Creates a JavaScript model exception that wrappers the given <code>Throwable</code>.
- * The exception contains a JavaScript-specific status object with severity
- * <code>IStatus.ERROR</code> and the given status code.
- *
- * @param e the <code>Throwable</code>
- * @param code one of the JavaScript-specific status codes declared in
- * <code>IJavaScriptModelStatusConstants</code>
- * @see IJavaScriptModelStatusConstants
- * @see org.eclipse.core.runtime.IStatus#ERROR
- */
-public JavaScriptModelException(Throwable e, int code) {
- this(new JavaModelStatus(code, e));
-}
-/**
- * Creates a JavaScript model exception for the given <code>CoreException</code>.
- * Equivalent to
- * <code>JavaScriptModelException(exception,IJavaScriptModelStatusConstants.CORE_EXCEPTION</code>.
- *
- * @param exception the <code>CoreException</code>
- */
-public JavaScriptModelException(CoreException exception) {
- super(exception.getStatus());
- this.nestedCoreException = exception;
-}
-/**
- * Creates a JavaScript model exception for the given JavaScript-specific status object.
- *
- * @param status the JavaScript-specific status object
- */
-public JavaScriptModelException(IJavaScriptModelStatus status) {
- super(status);
-}
-/**
- * Returns the underlying <code>Throwable</code> that caused the failure.
- *
- * @return the wrappered <code>Throwable</code>, or <code>null</code> if the
- * direct case of the failure was at the JavaScript model layer
- */
-public Throwable getException() {
- if (this.nestedCoreException == null) {
- return getStatus().getException();
- } else {
- return this.nestedCoreException;
- }
-}
-/**
- * Returns the JavaScript model status object for this exception.
- * Equivalent to <code>(IJavaScriptModelStatus) getStatus()</code>.
- *
- * @return a status object
- */
-public IJavaScriptModelStatus getJavaScriptModelStatus() {
- IStatus status = this.getStatus();
- if (status instanceof IJavaScriptModelStatus) {
- return (IJavaScriptModelStatus)status;
- } else {
- // A regular IStatus is created only in the case of a CoreException.
- // See bug 13492 Should handle JavaModelExceptions that contains CoreException more gracefully
- return new JavaModelStatus(this.nestedCoreException);
- }
-}
-/**
- * Returns whether this exception indicates that a JavaScript model element does not
- * exist. Such exceptions have a status with a code of
- * <code>IJavaScriptModelStatusConstants.ELEMENT_DOES_NOT_EXIST</code> or
- * <code>IJavaScriptModelStatusConstants.ELEMENT_NOT_ON_CLASSPATH</code>.
- * This is a convenience method.
- *
- * @return <code>true</code> if this exception indicates that a JavaScript model
- * element does not exist
- * @see IJavaScriptModelStatus#isDoesNotExist()
- * @see IJavaScriptModelStatusConstants#ELEMENT_DOES_NOT_EXIST
- * @see IJavaScriptModelStatusConstants#ELEMENT_NOT_ON_CLASSPATH
- */
-public boolean isDoesNotExist() {
- IJavaScriptModelStatus javaModelStatus = getJavaScriptModelStatus();
- return javaModelStatus != null && javaModelStatus.isDoesNotExist();
-}
-
-/**
- * Prints this exception's stack trace to the given print stream.
- *
- * @param output the print stream
- */
-public void printStackTrace(PrintStream output) {
- synchronized(output) {
- super.printStackTrace(output);
- Throwable throwable = getException();
- if (throwable != null) {
- output.print("Caused by: "); //$NON-NLS-1$
- throwable.printStackTrace(output);
- }
- }
-}
-
-/**
- * Prints this exception's stack trace to the given print writer.
- *
- * @param output the print writer
- */
-public void printStackTrace(PrintWriter output) {
- synchronized(output) {
- super.printStackTrace(output);
- Throwable throwable = getException();
- if (throwable != null) {
- output.print("Caused by: "); //$NON-NLS-1$
- throwable.printStackTrace(output);
- }
- }
-}
-/*
- * Returns a printable representation of this exception suitable for debugging
- * purposes only.
- */
-public String toString() {
- StringBuffer buffer= new StringBuffer();
- buffer.append("JavaScript Model Exception: "); //$NON-NLS-1$
- if (getException() != null) {
- if (getException() instanceof CoreException) {
- CoreException c= (CoreException)getException();
- buffer.append("Core Exception [code "); //$NON-NLS-1$
- buffer.append(c.getStatus().getCode());
- buffer.append("] "); //$NON-NLS-1$
- buffer.append(c.getStatus().getMessage());
- } else {
- buffer.append(getException().toString());
- }
- } else {
- buffer.append(getStatus().toString());
- }
- return buffer.toString();
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/JsGlobalScopeContainerInitializer.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/JsGlobalScopeContainerInitializer.java
deleted file mode 100644
index aa265ffb..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/JsGlobalScopeContainerInitializer.java
+++ /dev/null
@@ -1,321 +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
- * IBM Corporation - added support for requesting updates of a particular
- * container for generic container operations.
- * - canUpdateJsGlobalScopeContainer(IPath, IJavaScriptProject)
- * - requestJsGlobalScopeContainerUpdate(IPath, IJavaScriptProject, IJsGlobalScopeContainer)
- * IBM Corporation - allow initializers to provide a readable description
- * of a container reference, ahead of actual resolution.
- * - getDescription(IPath, IJavaScriptProject)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core;
-
-import java.net.URI;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.wst.jsdt.core.compiler.libraries.LibraryLocation;
-import org.eclipse.wst.jsdt.internal.core.JavaModelStatus;
-
-/**
- * Abstract base implementation of all includepath container initializer.
- * Includepath variable containers are used in conjunction with the
- * "org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer" extension point.
- * <p>
- * Clients should subclass this class to implement a specific includepath
- * container initializer. The subclass must have a public 0-argument
- * constructor and a concrete implementation of <code>initialize</code>.
- * <p>
- * Multiple includepath containers can be registered, each of them declares
- * the container ID they can handle, so as to narrow the set of containers they
- * can resolve, in other words, a container initializer is guaranteed to only be
- * activated to resolve containers which match the ID they registered onto.
- * <p>
- * In case multiple container initializers collide on the same container ID, the first
- * registered one will be invoked.
- *
- * @see IIncludePathEntry
- * @see IJsGlobalScopeContainer
- *
- * 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 JsGlobalScopeContainerInitializer implements IJsGlobalScopeContainerInitializer, IJsGlobalScopeContainer {
-
- /**
- * Status code indicating that an attribute is not supported.
- *
- * @see #getAccessRulesStatus(IPath, IJavaScriptProject)
- * @see #getAttributeStatus(IPath, IJavaScriptProject, String)
- * @see #getSourceAttachmentStatus(IPath, IJavaScriptProject)
- *
- */
- public static final int ATTRIBUTE_NOT_SUPPORTED = 1;
-
- /**
- * Status code indicating that an attribute is not modifiable.
- *
- * @see #getAccessRulesStatus(IPath, IJavaScriptProject)
- * @see #getAttributeStatus(IPath, IJavaScriptProject, String)
- * @see #getSourceAttachmentStatus(IPath, IJavaScriptProject)
- *
- */
- public static final int ATTRIBUTE_READ_ONLY = 2;
-
- /**
- * Creates a new includepath container initializer.
- */
- public JsGlobalScopeContainerInitializer() {
- // a includepath container initializer must have a public 0-argument constructor
- }
-
- public void initialize(IPath containerPath, IJavaScriptProject project) throws CoreException {
- JavaScriptCore.setJsGlobalScopeContainer(containerPath, new IJavaScriptProject[] { project }, new IJsGlobalScopeContainer[] { getContainer(containerPath, project) }, null);
- }
-
- protected IJsGlobalScopeContainer getContainer(IPath containerPath, IJavaScriptProject project) {
- return this;
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.IJsGlobalScopeContainerInitialzer#canUpdateJsGlobalScopeContainer(org.eclipse.core.runtime.IPath, org.eclipse.wst.jsdt.core.IJavaScriptProject)
- */
- public boolean canUpdateJsGlobalScopeContainer(IPath containerPath, IJavaScriptProject project) {
- if(project==null || containerPath==null) return true;
- LibrarySuperType superType = project.getCommonSuperType();
- return superType!=null && superType.getRawContainerPath().equals(getPath());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.IJsGlobalScopeContainerInitialzer#requestJsGlobalScopeContainerUpdate(org.eclipse.core.runtime.IPath, org.eclipse.wst.jsdt.core.IJavaScriptProject, org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer)
- */
- public void requestJsGlobalScopeContainerUpdate(IPath containerPath, IJavaScriptProject project, IJsGlobalScopeContainer containerSuggestion) throws CoreException {
-
- // By default, includepath container initializers do not accept updating containers
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.IJsGlobalScopeContainerInitialzer#getDescription(org.eclipse.core.runtime.IPath, org.eclipse.wst.jsdt.core.IJavaScriptProject)
- */
- public String getDescription(IPath containerPath, IJavaScriptProject project) {
-
- // By default, a container path is the only available description
- return containerPath.makeRelative().toString();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.IJsGlobalScopeContainerInitialzer#getFailureContainer(org.eclipse.core.runtime.IPath, org.eclipse.wst.jsdt.core.IJavaScriptProject)
- */
- public IJsGlobalScopeContainer getFailureContainer(final IPath containerPath, IJavaScriptProject project) {
- final String description = getDescription(containerPath, project);
- return
- new IJsGlobalScopeContainer() {
- public IIncludePathEntry[] getIncludepathEntries() {
- return new IIncludePathEntry[0];
- }
- public String getDescription() {
- return description;
- }
- public int getKind() {
- return 0;
- }
- public IPath getPath() {
- return containerPath;
- }
- public String toString() {
- return getDescription();
- }
- public String[] resolvedLibraryImport(String a) {
- return new String[] {a};
- }
- };
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.IJsGlobalScopeContainerInitialzer#getComparisonID(org.eclipse.core.runtime.IPath, org.eclipse.wst.jsdt.core.IJavaScriptProject)
- */
- public Object getComparisonID(IPath containerPath, IJavaScriptProject project) {
-
- // By default, containers are identical if they have the same containerPath first segment,
- // but this may be refined by other container initializer implementations.
- if (containerPath == null) {
- return null;
- } else {
- return containerPath.segment(0);
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.IJsGlobalScopeContainerInitialzer#getHostPath(org.eclipse.core.runtime.IPath, org.eclipse.wst.jsdt.core.IJavaScriptProject)
- */
- public URI getHostPath(IPath path, IJavaScriptProject project) {
- return null;
- }
-
- public boolean allowAttachJsDoc() { return true; }
- /*
- * returns a String of all SuperTypes provided by this library.
- */
- public String[] containerSuperTypes() {return new String[0];}
-
- /* Return a string of imports to replace the real imports for. necisary for toolkits and other t
- * things that may have a certain import best for runtime but not best for building a model
- *
- */
- public String[] resolvedLibraryImport(String realImport) {
- return new String[] {realImport};
- }
-
- 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;
- }
-
- public String getDescription() {
- return null;
- }
-
- public int getKind() {
-
- return K_APPLICATION;
- }
-
- public IPath getPath() {
-
- return null;
- }
- /**
- * Returns the access rules attribute status according to this initializer.
- * <p>
- * The returned {@link IStatus status} can have one of the following severities:
- * <ul>
- * <li>{@link IStatus#OK OK}: means that the attribute is supported
- * <strong>and</strong> is modifiable</li>
- * <li>{@link IStatus#ERROR ERROR}: means that either the attribute
- * is not supported or is not modifiable.<br>
- * In this case, the {@link IStatus#getCode() code}will have
- * respectively the {@link #ATTRIBUTE_NOT_SUPPORTED} value
- * or the {@link #ATTRIBUTE_READ_ONLY} value.</li>
- * </ul>
- * </p><p>
- * The status message can contain more information.
- * </p><p>
- * If the subclass does not override this method, then the default behavior is
- * to return {@link IStatus#OK OK} if and only if the includepath container can
- * be updated (see {@link #canUpdateJsGlobalScopeContainer(IPath, IJavaScriptProject)}).
- * </p>
- *
- * @param containerPath the path of the container which requires to be
- * updated
- * @param project the project for which the container is to be updated
- * @return returns the access rules attribute status
- *
- */
- public IStatus getAccessRulesStatus(IPath containerPath, IJavaScriptProject project) {
-
- if (canUpdateJsGlobalScopeContainer(containerPath, project)) {
- return Status.OK_STATUS;
- }
- return new JavaModelStatus(ATTRIBUTE_READ_ONLY);
- }
-
- /**
- * Returns the extra attribute status according to this initializer.
- * <p>
- * The returned {@link IStatus status} can have one of the following severities:
- * <ul>
- * <li>{@link IStatus#OK OK}: means that the attribute is supported
- * <strong>and</strong> is modifiable</li>
- * <li>{@link IStatus#ERROR ERROR}: means that either the attribute
- * is not supported or is not modifiable.<br>
- * In this case, the {@link IStatus#getCode() code}will have
- * respectively the {@link #ATTRIBUTE_NOT_SUPPORTED} value
- * or the {@link #ATTRIBUTE_READ_ONLY} value.</li>
- * </ul>
- * </p><p>
- * The status message can contain more information.
- * </p><p>
- * If the subclass does not override this method, then the default behavior is
- * to return {@link IStatus#OK OK} if and only if the includepath container can
- * be updated (see {@link #canUpdateJsGlobalScopeContainer(IPath, IJavaScriptProject)}).
- * </p>
- *
- * @param containerPath the path of the container which requires to be
- * updated
- * @param project the project for which the container is to be updated
- * @param attributeKey the key of the extra attribute
- * @return returns the extra attribute status
- * @see IIncludePathAttribute
- */
- public IStatus getAttributeStatus(IPath containerPath, IJavaScriptProject project, String attributeKey) {
-
- if (canUpdateJsGlobalScopeContainer(containerPath, project)) {
- return Status.OK_STATUS;
- }
- return new JavaModelStatus(ATTRIBUTE_READ_ONLY);
- }
-
- /**
- * Returns the source attachment attribute status according to this initializer.
- * <p>
- * The returned {@link IStatus status} can have one of the following severities:
- * <ul>
- * <li>{@link IStatus#OK OK}: means that the attribute is supported
- * <strong>and</strong> is modifiable</li>
- * <li>{@link IStatus#ERROR ERROR}: means that either the attribute
- * is not supported or is not modifiable.<br>
- * In this case, the {@link IStatus#getCode() code}will have
- * respectively the {@link #ATTRIBUTE_NOT_SUPPORTED} value
- * or the {@link #ATTRIBUTE_READ_ONLY} value.</li>
- * </ul>
- * </p><p>
- * The status message can contain more information.
- * </p><p>
- * If the subclass does not override this method, then the default behavior is
- * to return {@link IStatus#OK OK} if and only if the includepath container can
- * be updated (see {@link #canUpdateJsGlobalScopeContainer(IPath, IJavaScriptProject)}).
- * </p>
- *
- * @param containerPath the path of the container which requires to be
- * updated
- * @param project the project for which the container is to be updated
- * @return returns the source attachment attribute status
- */
- public IStatus getSourceAttachmentStatus(IPath containerPath, IJavaScriptProject project) {
-
- if (canUpdateJsGlobalScopeContainer(containerPath, project)) {
- return Status.OK_STATUS;
- }
- return new JavaModelStatus(ATTRIBUTE_READ_ONLY);
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.IJsGlobalScopeContainerInitialzer#getInferenceID()
- */
- public String getInferenceID()
- {
- return null;
- }
-
- public void removeFromProject(IJavaScriptProject project) {}
-
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/JsGlobalScopeVariableInitializer.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/JsGlobalScopeVariableInitializer.java
deleted file mode 100644
index 5d6540bc..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/JsGlobalScopeVariableInitializer.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*******************************************************************************
- * 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;
-
-/**
- * Abstract base implementation of all includepath variable initializers.
- * Includepath variable initializers are used in conjunction with the
- * "org.eclipse.wst.jsdt.core.JsGlobalScopeVariableInitializer" extension point.
- * <p>
- * Clients should subclass this class to implement a specific includepath
- * variable initializer. The subclass must have a public 0-argument
- * constructor and a concrete implementation of <code>initialize</code>.
- *
- * @see IIncludePathEntry
- *
- * 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 JsGlobalScopeVariableInitializer {
-
- /**
- * Creates a new includepath variable initializer.
- */
- public JsGlobalScopeVariableInitializer() {
- // a includepath variable initializer must have a public 0-argument constructor
- }
-
- /**
- * Binds a value to the workspace includepath variable with the given name,
- * or fails silently if this cannot be done.
- * <p>
- * A variable initializer is automatically activated whenever a variable value
- * is needed and none has been recorded so far. The implementation of
- * the initializer can set the corresponding variable using
- * <code>JavaScriptCore#setClasspathVariable</code>.
- *
- * @param variable the name of the workspace includepath variable
- * that requires a binding
- *
- * @see JavaScriptCore#getIncludepathVariable(String)
- * @see JavaScriptCore#setIncludepathVariable(String, org.eclipse.core.runtime.IPath, org.eclipse.core.runtime.IProgressMonitor)
- * @see JavaScriptCore#setIncludepathVariables(String[], org.eclipse.core.runtime.IPath[], org.eclipse.core.runtime.IProgressMonitor)
- */
- public abstract void initialize(String variable);
-}
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
deleted file mode 100644
index fba5ee7d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/LibrarySuperType.java
+++ /dev/null
@@ -1,196 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-/**
- *
- */
-package org.eclipse.wst.jsdt.core;
-
-import java.util.ArrayList;
-
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-
-
-/**
- *
- * 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 LibrarySuperType {
- IPath cpEntry;
- String superTypeName;
- String libraryName;
- IJavaScriptProject javaProject;
-
- public static final String SUPER_TYPE_CONTAINER= "org.eclipse.wst.jsdt.ui.superType.container"; //$NON-NLS-1$
- public static final String SUPER_TYPE_NAME= "org.eclipse.wst.jsdt.ui.superType.name"; //$NON-NLS-1$
-
- /* Only one superTypeName per instance so enforce that */
- public LibrarySuperType(IPath classPathEntry, IJavaScriptProject project, String superTypeName) {
- this.cpEntry = classPathEntry;
- this.superTypeName = superTypeName;
- this.javaProject = project;
- this.libraryName = initLibraryName();
-
- }
-
- public LibrarySuperType(String classPathEntry, IJavaScriptProject project, String superTypeName) {
- this(new Path(classPathEntry),project,superTypeName);
- }
- /* Construct parent */
- public LibrarySuperType(IPath classPathEntry, IJavaScriptProject project) {
- this(classPathEntry,project, null);
- }
-
- public IPath getRawContainerPath() {
- return cpEntry;
- }
-
- public boolean hasChildren() {
- /* defined super type meeans I'm a child */
- if(superTypeName!=null) return false;
- JsGlobalScopeContainerInitializer init = getContainerInitializer();
- if (init == null) return false;
- String[] availableSuperTypes = init.containerSuperTypes();
- return availableSuperTypes!=null && availableSuperTypes.length>0;
- }
-
- public LibrarySuperType[] getChildren() {
- if(superTypeName!=null) return new LibrarySuperType[0];
- return getFlatLibrarySuperTypes(cpEntry,javaProject);
- }
-
- public LibrarySuperType getParent() {
- if(superTypeName==null) return null;
- return new LibrarySuperType(cpEntry,javaProject, null);
- }
-
- public boolean isParent() {
- return getParent()==null;
- }
-
- public JsGlobalScopeContainerInitializer getContainerInitializer() {
- return getContainerInitializer(cpEntry);
- }
-
- public IIncludePathEntry[] getClasspathEntries() {
- IJsGlobalScopeContainer container=null;
- try {
- container = JavaScriptCore.getJsGlobalScopeContainer(this.cpEntry, this.javaProject);
- } catch (JavaScriptModelException ex) {
- // TODO Auto-generated catch block
- ex.printStackTrace();
- }
- if(container!=null) return container.getIncludepathEntries();
-
- return new IIncludePathEntry[0];
- }
-
- private static LibrarySuperType[] getFlatLibrarySuperTypes(IPath classPathEntry, IJavaScriptProject javaProject) {
- JsGlobalScopeContainerInitializer init = getContainerInitializer(classPathEntry);
- if (init == null) return new LibrarySuperType[0];
- String[] availableSuperTypes = init.containerSuperTypes();
- LibrarySuperType[] libSupers = new LibrarySuperType[availableSuperTypes.length];
- for (int i = 0; i < availableSuperTypes.length; i++) {
- libSupers[i] = new LibrarySuperType(classPathEntry, javaProject, availableSuperTypes[i]);
- }
- return libSupers;
- }
-
- public String getSuperTypeName() {
- return superTypeName;
- }
-
- public String getLibraryName() {
- return libraryName;
- }
-
- private String initLibraryName() {
- JsGlobalScopeContainerInitializer init = getContainerInitializer();
-
- /* parent node */
- if(superTypeName==null) {
- if(init==null) {
- return cpEntry.toString();
- }
- return init.getDescription(cpEntry, javaProject);
- }
- Object parent = getParent();
- if(!(parent instanceof LibrarySuperType)) return null;
- return ((LibrarySuperType)parent).getLibraryName();
- }
-
- public String toString() {
- //JsGlobalScopeContainerInitializer init = getContainerInitializer();
-
- /* parent node */
- if(isParent()) {
- return getLibraryName();
-
- }
-
- return Messages.getString("LibrarySuperType.0", new Object[]{superTypeName, getLibraryName()}); //$NON-NLS-1$
- }
-
- public boolean equals(Object o) {
- if(!(o instanceof LibrarySuperType)) return false;
-
- LibrarySuperType other = (LibrarySuperType)o;
-
-
-
- if(other.cpEntry!=null && !other.cpEntry.equals(cpEntry)) {
- return false;
- }
-
- if((other.superTypeName==superTypeName)) {
- return true;
- }
-
- if(other.superTypeName!=null && superTypeName!=null) {
- return other.superTypeName.equals(superTypeName);
- }
-
- return false;
- }
-
- public IPackageFragment[] getPackageFragments(){
- IIncludePathEntry[] entries = getClasspathEntries();
- ArrayList allFrags = new ArrayList();
-
- try {
- for(int i = 0;i<entries.length;i++) {
- IPath path = entries[i].getPath();
- IPackageFragmentRoot root = javaProject.findPackageFragmentRoot(path.makeAbsolute());
-
- IJavaScriptElement[] children = root.getChildren();
- for(int k = 0;k<children.length;k++) {
- if(children[k] instanceof IPackageFragment) {
- allFrags.add(children[k]);
- }
- }
- }
- } catch (JavaScriptModelException ex) {
- // TODO Auto-generated catch block
- ex.printStackTrace();
- }
- return (IPackageFragment[])allFrags.toArray(new IPackageFragment[allFrags.size()]);
- }
-
- public static JsGlobalScopeContainerInitializer getContainerInitializer(IPath classPathEntry) {
- if(classPathEntry==null ) return null;
- JsGlobalScopeContainerInitializer initializer= JavaScriptCore.getJsGlobalScopeContainerInitializer(classPathEntry.segment(0));
- return initializer ;
- }
-}
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
deleted file mode 100644
index b74bdac6..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/Messages.java
+++ /dev/null
@@ -1,34 +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.core;
-
-import java.util.MissingResourceException;
-import java.util.ResourceBundle;
-
-import com.ibm.icu.text.MessageFormat;
-
-public class Messages {
- private static final String BUNDLE_NAME = "org.eclipse.wst.jsdt.core.messages"; //$NON-NLS-1$
-
- private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
- .getBundle(BUNDLE_NAME);
-
- private Messages() {
- }
-
- public static String getString(String key, Object[] objects) {
- try {
- return MessageFormat.format( RESOURCE_BUNDLE.getString(key), objects);
- } catch (MissingResourceException e) {
- return '!' + key + '!';
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/NamingConventions.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/NamingConventions.java
deleted file mode 100644
index 83e1209b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/NamingConventions.java
+++ /dev/null
@@ -1,949 +0,0 @@
-/*******************************************************************************
- * 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;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.codeassist.impl.AssistOptions;
-import org.eclipse.wst.jsdt.internal.compiler.parser.ScannerHelper;
-import org.eclipse.wst.jsdt.internal.core.INamingRequestor;
-import org.eclipse.wst.jsdt.internal.core.InternalNamingConventions;
-
-
-/**
- * Provides methods for computing JavaScript-specific names.
- * <p>
- * The behavior of the methods is dependent of several JavaScriptCore options.
- * <p>
- * The possible options are :
- * <ul>
- * <li> {@link JavaScriptCore#CODEASSIST_FIELD_PREFIXES} : Define the Prefixes for Field Name.</li>
- * <li> {@link JavaScriptCore#CODEASSIST_STATIC_FIELD_PREFIXES} : Define the Prefixes for Static Field Name.</li>
- * <li> {@link JavaScriptCore#CODEASSIST_LOCAL_PREFIXES} : Define the Prefixes for Local Variable Name.</li>
- * <li> {@link JavaScriptCore#CODEASSIST_ARGUMENT_PREFIXES} : Define the Prefixes for Argument Name.</li>
- * <li> {@link JavaScriptCore#CODEASSIST_FIELD_SUFFIXES} : Define the Suffixes for Field Name.</li>
- * <li> {@link JavaScriptCore#CODEASSIST_STATIC_FIELD_SUFFIXES} : Define the Suffixes for Static Field Name.</li>
- * <li> {@link JavaScriptCore#CODEASSIST_LOCAL_SUFFIXES} : Define the Suffixes for Local Variable Name.</li>
- * <li> {@link JavaScriptCore#CODEASSIST_ARGUMENT_SUFFIXES} : Define the Suffixes for Argument Name.</li>
- * </ul>
- * </p>
- * <p>
- * For a complete description of the configurable options, see <code>getDefaultOptions</code>.
- * For programmaticaly change these options, see <code>JavaScriptCore#setOptions()</code>.
- * </p>
- * <p>
- * This class provides static methods and constants only; it is not intended to be
- * instantiated or subclassed by clients.
- * </p>
- *
- * @see JavaScriptCore#setOptions(java.util.Hashtable)
- * @see JavaScriptCore#getDefaultOptions()
- *
- * 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 final class NamingConventions {
- private static final char[] GETTER_BOOL_NAME = "is".toCharArray(); //$NON-NLS-1$
- private static final char[] GETTER_NAME = "get".toCharArray(); //$NON-NLS-1$
- private static final char[] SETTER_NAME = "set".toCharArray(); //$NON-NLS-1$
-
- static class NamingRequestor implements INamingRequestor {
- private final static int SIZE = 10;
-
- // for acceptNameWithPrefixAndSuffix
- private char[][] firstPrefixAndFirstSuffixResults = new char[SIZE][];
- private int firstPrefixAndFirstSuffixResultsCount = 0;
- private char[][] firstPrefixAndSuffixResults = new char[SIZE][];
- private int firstPrefixAndSuffixResultsCount = 0;
- private char[][] prefixAndFirstSuffixResults = new char[SIZE][];
- private int prefixAndFirstSuffixResultsCount = 0;
- private char[][] prefixAndSuffixResults = new char[SIZE][];
- private int prefixAndSuffixResultsCount = 0;
-
- // for acceptNameWithPrefix
- private char[][] firstPrefixResults = new char[SIZE][];
- private int firstPrefixResultsCount = 0;
- private char[][] prefixResults = new char[SIZE][];
- private int prefixResultsCount = 0;
-
- // for acceptNameWithSuffix
- private char[][] firstSuffixResults = new char[SIZE][];
- private int firstSuffixResultsCount = 0;
- private char[][] suffixResults = new char[SIZE][];
- private int suffixResultsCount = 0;
-
- // for acceptNameWithoutPrefixAndSuffix
- private char[][] otherResults = new char[SIZE][];
- private int otherResultsCount = 0;
- public void acceptNameWithPrefixAndSuffix(char[] name, boolean isFirstPrefix, boolean isFirstSuffix, int reusedCharacters) {
- if(isFirstPrefix && isFirstSuffix) {
- int length = this.firstPrefixAndFirstSuffixResults.length;
- if(length == this.firstPrefixAndFirstSuffixResultsCount) {
- System.arraycopy(
- this.firstPrefixAndFirstSuffixResults,
- 0,
- this.firstPrefixAndFirstSuffixResults = new char[length * 2][],
- 0,
- length);
- }
- this.firstPrefixAndFirstSuffixResults[this.firstPrefixAndFirstSuffixResultsCount++] = name;
- } else if (isFirstPrefix) {
- int length = this.firstPrefixAndSuffixResults.length;
- if(length == this.firstPrefixAndSuffixResultsCount) {
- System.arraycopy(
- this.firstPrefixAndSuffixResults,
- 0,
- this.firstPrefixAndSuffixResults = new char[length * 2][],
- 0,
- length);
- }
- this.firstPrefixAndSuffixResults[this.firstPrefixAndSuffixResultsCount++] = name;
- } else if(isFirstSuffix) {
- int length = this.prefixAndFirstSuffixResults.length;
- if(length == this.prefixAndFirstSuffixResultsCount) {
- System.arraycopy(
- this.prefixAndFirstSuffixResults,
- 0,
- this.prefixAndFirstSuffixResults = new char[length * 2][],
- 0,
- length);
- }
- this.prefixAndFirstSuffixResults[this.prefixAndFirstSuffixResultsCount++] = name;
- } else {
- int length = this.prefixAndSuffixResults.length;
- if(length == this.prefixAndSuffixResultsCount) {
- System.arraycopy(
- this.prefixAndSuffixResults,
- 0,
- this.prefixAndSuffixResults = new char[length * 2][],
- 0,
- length);
- }
- this.prefixAndSuffixResults[this.prefixAndSuffixResultsCount++] = name;
- }
- }
-
- public void acceptNameWithPrefix(char[] name, boolean isFirstPrefix, int reusedCharacters) {
- if(isFirstPrefix) {
- int length = this.firstPrefixResults.length;
- if(length == this.firstPrefixResultsCount) {
- System.arraycopy(
- this.firstPrefixResults,
- 0,
- this.firstPrefixResults = new char[length * 2][],
- 0,
- length);
- }
- this.firstPrefixResults[this.firstPrefixResultsCount++] = name;
- } else{
- int length = this.prefixResults.length;
- if(length == this.prefixResultsCount) {
- System.arraycopy(
- this.prefixResults,
- 0,
- this.prefixResults = new char[length * 2][],
- 0,
- length);
- }
- this.prefixResults[this.prefixResultsCount++] = name;
- }
- }
-
- public void acceptNameWithSuffix(char[] name, boolean isFirstSuffix, int reusedCharacters) {
- if(isFirstSuffix) {
- int length = this.firstSuffixResults.length;
- if(length == this.firstSuffixResultsCount) {
- System.arraycopy(
- this.firstSuffixResults,
- 0,
- this.firstSuffixResults = new char[length * 2][],
- 0,
- length);
- }
- this.firstSuffixResults[this.firstSuffixResultsCount++] = name;
- } else {
- int length = this.suffixResults.length;
- if(length == this.suffixResultsCount) {
- System.arraycopy(
- this.suffixResults,
- 0,
- this.suffixResults = new char[length * 2][],
- 0,
- length);
- }
- this.suffixResults[this.suffixResultsCount++] = name;
- }
- }
-
- public void acceptNameWithoutPrefixAndSuffix(char[] name, int reusedCharacters) {
- int length = this.otherResults.length;
- if(length == this.otherResultsCount) {
- System.arraycopy(
- this.otherResults,
- 0,
- this.otherResults = new char[length * 2][],
- 0,
- length);
- }
- this.otherResults[this.otherResultsCount++] = name;
- }
- public char[][] getResults(){
- int count =
- this.firstPrefixAndFirstSuffixResultsCount
- + this.firstPrefixAndSuffixResultsCount
- + this.prefixAndFirstSuffixResultsCount
- + this.prefixAndSuffixResultsCount
- + this.firstPrefixResultsCount
- + this.prefixResultsCount
- + this.firstSuffixResultsCount
- + this.suffixResultsCount
- + this.otherResultsCount;
-
- char[][] results = new char[count][];
-
- int index = 0;
- System.arraycopy(this.firstPrefixAndFirstSuffixResults, 0, results, index, this.firstPrefixAndFirstSuffixResultsCount);
- index += this.firstPrefixAndFirstSuffixResultsCount;
- System.arraycopy(this.firstPrefixAndSuffixResults, 0, results, index, this.firstPrefixAndSuffixResultsCount);
- index += this.firstPrefixAndSuffixResultsCount;
- System.arraycopy(this.prefixAndFirstSuffixResults, 0, results, index, this.prefixAndFirstSuffixResultsCount);
- index += this.prefixAndFirstSuffixResultsCount;
- System.arraycopy(this.prefixAndSuffixResults, 0, results, index, this.prefixAndSuffixResultsCount);
- index += this.prefixAndSuffixResultsCount;
- System.arraycopy(this.firstPrefixResults, 0, results, index, this.firstPrefixResultsCount);
- index += this.firstPrefixResultsCount;
- System.arraycopy(this.prefixResults, 0, results, index, this.prefixResultsCount);
- index += this.prefixResultsCount;
- System.arraycopy(this.firstSuffixResults, 0, results, index, this.firstSuffixResultsCount);
- index += this.firstSuffixResultsCount;
- System.arraycopy(this.suffixResults, 0, results, index, this.suffixResultsCount);
- index += this.suffixResultsCount;
- System.arraycopy(this.otherResults, 0, results, index, this.otherResultsCount);
-
- return results;
- }
- }
-
-
- private NamingConventions() {
- // Not instantiable
- }
-
- private static char[] removePrefixAndSuffix(char[] name, char[][] prefixes, char[][] suffixes) {
- // remove longer prefix
- char[] withoutPrefixName = name;
- if (prefixes != null) {
- int bestLength = 0;
- for (int i= 0; i < prefixes.length; i++) {
- char[] prefix = prefixes[i];
- if (CharOperation.prefixEquals(prefix, name)) {
- int currLen = prefix.length;
- boolean lastCharIsLetter = ScannerHelper.isLetter(prefix[currLen - 1]);
- if(!lastCharIsLetter || (lastCharIsLetter && name.length > currLen && ScannerHelper.isUpperCase(name[currLen]))) {
- if (bestLength < currLen && name.length != currLen) {
- withoutPrefixName = CharOperation.subarray(name, currLen, name.length);
- bestLength = currLen;
- }
- }
- }
- }
- }
-
- // remove longer suffix
- char[] withoutSuffixName = withoutPrefixName;
- if(suffixes != null) {
- int bestLength = 0;
- for (int i = 0; i < suffixes.length; i++) {
- char[] suffix = suffixes[i];
- if(CharOperation.endsWith(withoutPrefixName, suffix)) {
- int currLen = suffix.length;
- if(bestLength < currLen && withoutPrefixName.length != currLen) {
- withoutSuffixName = CharOperation.subarray(withoutPrefixName, 0, withoutPrefixName.length - currLen);
- bestLength = currLen;
- }
- }
- }
- }
-
- withoutSuffixName[0] = ScannerHelper.toLowerCase(withoutSuffixName[0]);
- return withoutSuffixName;
- }
-
- /**
- * Remove prefix and suffix from an argument name.
- * <p>
- * If argument name prefix is <code>pre</code> and argument name suffix is <code>suf</code>
- * then for an argument named <code>preArgsuf</code> the result of this method is <code>arg</code>.
- * If there is no prefix or suffix defined in JavaScriptCore options the result is the unchanged
- * name <code>preArgsuf</code>.
- * </p>
- * <p>
- * This method is affected by the following JavaScriptCore options : {@link JavaScriptCore#CODEASSIST_ARGUMENT_PREFIXES} and
- * {@link JavaScriptCore#CODEASSIST_ARGUMENT_SUFFIXES}.
- * </p>
- * <p>
- * For a complete description of these configurable options, see <code>getDefaultOptions</code>.
- * For programmaticaly change these options, see <code>JavaScriptCore#setOptions()</code>.
- * </p>
- *
- * @param javaProject project which contains the argument.
- * @param argumentName argument's name.
- * @return char[] the name without prefix and suffix.
- * @see JavaScriptCore#setOptions(java.util.Hashtable)
- * @see JavaScriptCore#getDefaultOptions()
- */
- public static char[] removePrefixAndSuffixForArgumentName(IJavaScriptProject javaProject, char[] argumentName) {
- AssistOptions assistOptions = new AssistOptions(javaProject.getOptions(true));
- return removePrefixAndSuffix(
- argumentName,
- assistOptions.argumentPrefixes,
- assistOptions.argumentSuffixes);
- }
-
- /**
- * Remove prefix and suffix from an argument name.
- * <p>
- * If argument name prefix is <code>pre</code> and argument name suffix is <code>suf</code>
- * then for an argument named <code>preArgsuf</code> the result of this method is <code>arg</code>.
- * If there is no prefix or suffix defined in JavaScriptCore options the result is the unchanged
- * name <code>preArgsuf</code>.
- * </p>
- * <p>
- * This method is affected by the following JavaScriptCore options : {@link JavaScriptCore#CODEASSIST_ARGUMENT_PREFIXES} and
- * {@link JavaScriptCore#CODEASSIST_ARGUMENT_SUFFIXES}.
- * </p>
- * <p>
- * For a complete description of these configurable options, see <code>getDefaultOptions</code>.
- * For programmaticaly change these options, see <code>JavaScriptCore#setOptions()</code>.
- * </p>
- *
- * @param javaProject project which contains the argument.
- * @param argumentName argument's name.
- * @return char[] the name without prefix and suffix.
- * @see JavaScriptCore#setOptions(java.util.Hashtable)
- * @see JavaScriptCore#getDefaultOptions()
- */
- public static String removePrefixAndSuffixForArgumentName(IJavaScriptProject javaProject, String argumentName) {
- return String.valueOf(removePrefixAndSuffixForArgumentName(javaProject, argumentName.toCharArray()));
- }
-
- /**
- * Remove prefix and suffix from a field name.
- * <p>
- * If field name prefix is <code>pre</code> and field name suffix is <code>suf</code>
- * then for a field named <code>preFieldsuf</code> the result of this method is <code>field</code>.
- * If there is no prefix or suffix defined in JavaScriptCore options the result is the unchanged
- * name <code>preFieldsuf</code>.
- * </p>
- * <p>
- * This method is affected by the following JavaScriptCore options : {@link JavaScriptCore#CODEASSIST_FIELD_PREFIXES} } ,
- * {@link JavaScriptCore#CODEASSIST_FIELD_SUFFIXES} for instance field and {@link JavaScriptCore#CODEASSIST_STATIC_FIELD_PREFIXES},
- * {@link JavaScriptCore#CODEASSIST_STATIC_FIELD_SUFFIXES} for static field.
- * </p>
- * <p>
- * For a complete description of these configurable options, see <code>getDefaultOptions</code>.
- * For programmaticaly change these options, see <code>JavaScriptCore#setOptions()</code>.
- * </p>
- *
- * @param javaProject project which contains the field.
- * @param fieldName field's name.
- * @param modifiers field's modifiers as defined by the class
- * <code>Flags</code>.
- * @return char[] the name without prefix and suffix.
- * @see Flags
- * @see JavaScriptCore#setOptions(java.util.Hashtable)
- * @see JavaScriptCore#getDefaultOptions()
- */
- public static char[] removePrefixAndSuffixForFieldName(IJavaScriptProject javaProject, char[] fieldName, int modifiers) {
- boolean isStatic = Flags.isStatic(modifiers);
- AssistOptions assistOptions = new AssistOptions(javaProject.getOptions(true));
- return removePrefixAndSuffix(
- fieldName,
- isStatic ? assistOptions.staticFieldPrefixes : assistOptions.fieldPrefixes,
- isStatic ? assistOptions.staticFieldSuffixes : assistOptions.fieldSuffixes);
- }
-
- /**
- * Remove prefix and suffix from a field name.
- * <p>
- * If field name prefix is <code>pre</code> and field name suffix is <code>suf</code>
- * then for a field named <code>preFieldsuf</code> the result of this method is <code>field</code>.
- * If there is no prefix or suffix defined in JavaScriptCore options the result is the unchanged
- * name <code>preFieldsuf</code>.
- * </p>
- * <p>
- * This method is affected by the following JavaScriptCore options : {@link JavaScriptCore#CODEASSIST_FIELD_PREFIXES},
- * {@link JavaScriptCore#CODEASSIST_FIELD_SUFFIXES} for instance field and {@link JavaScriptCore#CODEASSIST_STATIC_FIELD_PREFIXES},
- * {@link JavaScriptCore#CODEASSIST_STATIC_FIELD_SUFFIXES} for static field.
- * </p>
- * <p>
- * For a complete description of these configurable options, see <code>getDefaultOptions</code>.
- * For programmaticaly change these options, see <code>JavaScriptCore#setOptions()</code>.
- * </p>
- *
- * @param javaProject project which contains the field.
- * @param fieldName field's name.
- * @param modifiers field's modifiers as defined by the class
- * <code>Flags</code>.
- * @return char[] the name without prefix and suffix.
- * @see Flags
- * @see JavaScriptCore#setOptions(java.util.Hashtable)
- * @see JavaScriptCore#getDefaultOptions()
- */
- public static String removePrefixAndSuffixForFieldName(IJavaScriptProject javaProject, String fieldName, int modifiers) {
- return String.valueOf(removePrefixAndSuffixForFieldName(javaProject, fieldName.toCharArray(), modifiers));
- }
- /**
- * Remove prefix and suffix from a local variable name.
- * <p>
- * If local variable name prefix is <code>pre</code> and local variable name suffix is <code>suf</code>
- * then for a local variable named <code>preLocalsuf</code> the result of this method is <code>local</code>.
- * If there is no prefix or suffix defined in JavaScriptCore options the result is the unchanged
- * name <code>preLocalsuf</code>.
- * </p>
- * <p>
- * This method is affected by the following JavaScriptCore options : {@link JavaScriptCore#CODEASSIST_LOCAL_PREFIXES} and
- * {@link JavaScriptCore#CODEASSIST_LOCAL_SUFFIXES}.
- * </p>
- * <p>
- * For a complete description of these configurable options, see <code>getDefaultOptions</code>.
- * For programmaticaly change these options, see <code>JavaScriptCore#setOptions()</code>.
- * </p>
- *
- * @param javaProject project which contains the variable.
- * @param localName variable's name.
- * @return char[] the name without prefix and suffix.
- * @see JavaScriptCore#setOptions(java.util.Hashtable)
- * @see JavaScriptCore#getDefaultOptions()
- */
- public static char[] removePrefixAndSuffixForLocalVariableName(IJavaScriptProject javaProject, char[] localName) {
- AssistOptions assistOptions = new AssistOptions(javaProject.getOptions(true));
- return removePrefixAndSuffix(
- localName,
- assistOptions.localPrefixes,
- assistOptions.localSuffixes);
- }
-
- /**
- * Remove prefix and suffix from a local variable name.
- * <p>
- * If local variable name prefix is <code>pre</code> and local variable name suffix is <code>suf</code>
- * then for a local variable named <code>preLocalsuf</code> the result of this method is <code>local</code>.
- * If there is no prefix or suffix defined in JavaScriptCore options the result is the unchanged
- * name <code>preLocalsuf</code>.
- * </p>
- * <p>
- * This method is affected by the following JavaScriptCore options : {@link JavaScriptCore#CODEASSIST_LOCAL_PREFIXES} and
- * {@link JavaScriptCore#CODEASSIST_LOCAL_SUFFIXES}.
- * </p>
- * <p>
- * For a complete description of these configurable options, see <code>getDefaultOptions</code>.
- * For programmaticaly change these options, see <code>JavaScriptCore#setOptions()</code>.
- * </p>
- *
- * @param javaProject project which contains the variable.
- * @param localName variable's name.
- * @return char[] the name without prefix and suffix.
- * @see JavaScriptCore#setOptions(java.util.Hashtable)
- * @see JavaScriptCore#getDefaultOptions()
- */
- public static String removePrefixAndSuffixForLocalVariableName(IJavaScriptProject javaProject, String localName) {
- return String.valueOf(removePrefixAndSuffixForLocalVariableName(javaProject, localName.toCharArray()));
- }
-
- /**
- * Suggest names for an argument. The name is computed from argument's type
- * and possible prefixes or suffixes are added.
- * <p>
- * If the type of the argument is <code>TypeName</code>, the prefix for argument is <code>pre</code>
- * and the suffix for argument is <code>suf</code> then the proposed names are <code>preTypeNamesuf</code>
- * and <code>preNamesuf</code>. If there is no prefix or suffix the proposals are <code>typeName</code>
- * and <code>name</code>.
- * </p>
- * <p>
- * This method is affected by the following JavaScriptCore options : {@link JavaScriptCore#CODEASSIST_ARGUMENT_PREFIXES} and
- * {@link JavaScriptCore#CODEASSIST_ARGUMENT_SUFFIXES}.
- * </p>
- * <p>
- * For a complete description of these configurable options, see <code>getDefaultOptions</code>.
- * For programmaticaly change these options, see <code>JavaScriptCore#setOptions()</code>.
- * </p>
- *
- * @param javaProject project which contains the argument.
- * @param packageName package of the argument's type.
- * @param qualifiedTypeName argument's type.
- * @param dim argument's dimension (0 if the argument is not an array).
- * @param excludedNames a list of names which cannot be suggested (already used names).
- * Can be <code>null</code> if there is no excluded names.
- * @return char[][] an array of names.
- * @see JavaScriptCore#setOptions(java.util.Hashtable)
- * @see JavaScriptCore#getDefaultOptions()
- */
- public static char[][] suggestArgumentNames(IJavaScriptProject javaProject, char[] packageName, char[] qualifiedTypeName, int dim, char[][] excludedNames) {
- NamingRequestor requestor = new NamingRequestor();
- InternalNamingConventions.suggestArgumentNames(
- javaProject,
- packageName,
- qualifiedTypeName,
- dim,
- null,
- excludedNames,
- requestor);
-
- return requestor.getResults();
- }
-
- /**
- * Suggest names for an argument. The name is computed from argument's type
- * and possible prefixes or suffixes are added.
- * <p>
- * If the type of the argument is <code>TypeName</code>, the prefix for argument is <code>pre</code>
- * and the suffix for argument is <code>suf</code> then the proposed names are <code>preTypeNamesuf</code>
- * and <code>preNamesuf</code>. If there is no prefix or suffix the proposals are <code>typeName</code>
- * and <code>name</code>.
- * </p>
- * <p>
- * This method is affected by the following JavaScriptCore options : {@link JavaScriptCore#CODEASSIST_ARGUMENT_PREFIXES} and
- * {@link JavaScriptCore#CODEASSIST_ARGUMENT_SUFFIXES}.
- * </p>
- * <p>
- * For a complete description of these configurable options, see <code>getDefaultOptions</code>.
- * For programmaticaly change these options, see <code>JavaScriptCore#setOptions()</code>.
- * </p>
- *
- * @param javaProject project which contains the argument.
- * @param packageName package of the argument's type.
- * @param qualifiedTypeName argument's type.
- * @param dim argument's dimension (0 if the argument is not an array).
- * @param excludedNames a list of names which cannot be suggested (already used names).
- * Can be <code>null</code> if there is no excluded names.
- * @return char[][] an array of names.
- * @see JavaScriptCore#setOptions(java.util.Hashtable)
- * @see JavaScriptCore#getDefaultOptions()
- */
- public static String[] suggestArgumentNames(IJavaScriptProject javaProject, String packageName, String qualifiedTypeName, int dim, String[] excludedNames) {
- return convertCharsToString(
- suggestArgumentNames(
- javaProject,
- packageName!=null ? packageName.toCharArray() : null,
- qualifiedTypeName!=null ? qualifiedTypeName.toCharArray():null,
- dim,
- convertStringToChars(excludedNames)));
- }
- /**
- * Suggest names for a field. The name is computed from field's type
- * and possible prefixes or suffixes are added.
- * <p>
- * If the type of the field is <code>TypeName</code>, the prefix for field is <code>pre</code>
- * and the suffix for field is <code>suf</code> then the proposed names are <code>preTypeNamesuf</code>
- * and <code>preNamesuf</code>. If there is no prefix or suffix the proposals are <code>typeName</code>
- * and <code>name</code>.
- * </p>
- * <p>
- * This method is affected by the following JavaScriptCore options : {@link JavaScriptCore#CODEASSIST_FIELD_PREFIXES},
- * {@link JavaScriptCore#CODEASSIST_FIELD_SUFFIXES} and for instance field and {@link JavaScriptCore#CODEASSIST_STATIC_FIELD_PREFIXES},
- * {@link JavaScriptCore#CODEASSIST_STATIC_FIELD_SUFFIXES} for static field.
- * </p>
- * <p>
- * For a complete description of these configurable options, see <code>getDefaultOptions</code>.
- * For programmaticaly change these options, see <code>JavaScriptCore#setOptions()</code>.
- * </p>
- *
- * @param javaProject project which contains the field.
- * @param packageName package of the field's type.
- * @param qualifiedTypeName field's type.
- * @param dim field's dimension (0 if the field is not an array).
- * @param modifiers field's modifiers as defined by the class
- * <code>Flags</code>.
- * @param excludedNames a list of names which cannot be suggested (already used names).
- * Can be <code>null</code> if there is no excluded names.
- * @return char[][] an array of names.
- * @see Flags
- * @see JavaScriptCore#setOptions(java.util.Hashtable)
- * @see JavaScriptCore#getDefaultOptions()
- */
- public static char[][] suggestFieldNames(IJavaScriptProject javaProject, char[] packageName, char[] qualifiedTypeName, int dim, int modifiers, char[][] excludedNames) {
- NamingRequestor requestor = new NamingRequestor();
- InternalNamingConventions.suggestFieldNames(
- javaProject,
- packageName,
- qualifiedTypeName,
- dim,
- modifiers,
- null,
- excludedNames,
- requestor);
-
- return requestor.getResults();
- }
-
- /**
- * Suggest names for a field. The name is computed from field's type
- * and possible prefixes or suffixes are added.
- * <p>
- * If the type of the field is <code>TypeName</code>, the prefix for field is <code>pre</code>
- * and the suffix for field is <code>suf</code> then the proposed names are <code>preTypeNamesuf</code>
- * and <code>preNamesuf</code>. If there is no prefix or suffix the proposals are <code>typeName</code>
- * and <code>name</code>.
- * </p>
- * <p>
- * This method is affected by the following JavaScriptCore options : {@link JavaScriptCore#CODEASSIST_FIELD_PREFIXES},
- * {@link JavaScriptCore#CODEASSIST_FIELD_SUFFIXES} and for instance field and {@link JavaScriptCore#CODEASSIST_STATIC_FIELD_PREFIXES},
- * {@link JavaScriptCore#CODEASSIST_STATIC_FIELD_SUFFIXES} for static field.
- * </p>
- * <p>
- * For a complete description of these configurable options, see <code>getDefaultOptions</code>.
- * For programmaticaly change these options, see <code>JavaScriptCore#setOptions()</code>.
- * </p>
- *
- * @param javaProject project which contains the field.
- * @param packageName package of the field's type.
- * @param qualifiedTypeName field's type.
- * @param dim field's dimension (0 if the field is not an array).
- * @param modifiers field's modifiers as defined by the class
- * <code>Flags</code>.
- * @param excludedNames a list of names which cannot be suggested (already used names).
- * Can be <code>null</code> if there is no excluded names.
- * @return char[][] an array of names.
- * @see Flags
- * @see JavaScriptCore#setOptions(java.util.Hashtable)
- * @see JavaScriptCore#getDefaultOptions()
- */
- public static String[] suggestFieldNames(IJavaScriptProject javaProject, String packageName, String qualifiedTypeName, int dim, int modifiers, String[] excludedNames) {
- return convertCharsToString(
- suggestFieldNames(
- javaProject,
- packageName.toCharArray(),
- qualifiedTypeName.toCharArray(),
- dim,
- modifiers,
- convertStringToChars(excludedNames)));
- }
-
- /**
- * Suggest names for a local variable. The name is computed from variable's type
- * and possible prefixes or suffixes are added.
- * <p>
- * If the type of the local variable is <code>TypeName</code>, the prefix for local variable is <code>pre</code>
- * and the suffix for local variable is <code>suf</code> then the proposed names are <code>preTypeNamesuf</code>
- * and <code>preNamesuf</code>. If there is no prefix or suffix the proposals are <code>typeName</code>
- * and <code>name</code>.
- * </p>
- * <p>
- * This method is affected by the following JavaScriptCore options : {@link JavaScriptCore#CODEASSIST_LOCAL_PREFIXES} and
- * {@link JavaScriptCore#CODEASSIST_LOCAL_SUFFIXES}.
- * </p>
- * <p>
- * For a complete description of these configurable options, see <code>getDefaultOptions</code>.
- * For programmaticaly change these options, see <code>JavaScriptCore#setOptions()</code>.
- * </p>
- *
- * @param javaProject project which contains the variable.
- * @param packageName package of the variable's type.
- * @param qualifiedTypeName variable's type.
- * @param dim variable's dimension (0 if the variable is not an array).
- * @param excludedNames a list of names which cannot be suggested (already used names).
- * Can be <code>null</code> if there is no excluded names.
- * @return char[][] an array of names.
- * @see JavaScriptCore#setOptions(java.util.Hashtable)
- * @see JavaScriptCore#getDefaultOptions()
- */
- public static char[][] suggestLocalVariableNames(IJavaScriptProject javaProject, char[] packageName, char[] qualifiedTypeName, int dim, char[][] excludedNames) {
- NamingRequestor requestor = new NamingRequestor();
- InternalNamingConventions.suggestLocalVariableNames(
- javaProject,
- packageName,
- qualifiedTypeName,
- dim,
- null,
- excludedNames,
- requestor);
-
- return requestor.getResults();
- }
-
- /**
- * Suggest names for a local variable. The name is computed from variable's type
- * and possible prefixes or suffixes are added.
- * <p>
- * If the type of the local variable is <code>TypeName</code>, the prefix for local variable is <code>pre</code>
- * and the suffix for local variable is <code>suf</code> then the proposed names are <code>preTypeNamesuf</code>
- * and <code>preNamesuf</code>. If there is no prefix or suffix the proposals are <code>typeName</code>
- * and <code>name</code>.
- * </p>
- * <p>
- * This method is affected by the following JavaScriptCore options : {@link JavaScriptCore#CODEASSIST_LOCAL_PREFIXES} and
- * {@link JavaScriptCore#CODEASSIST_LOCAL_SUFFIXES}.
- * </p>
- * <p>
- * For a complete description of these configurable options, see <code>getDefaultOptions</code>.
- * For programmaticaly change these options, see <code>JavaScriptCore#setOptions()</code>.
- * </p>
- *
- * @param javaProject project which contains the variable.
- * @param packageName package of the variable's type.
- * @param qualifiedTypeName variable's type.
- * @param dim variable's dimension (0 if the variable is not an array).
- * @param excludedNames a list of names which cannot be suggested (already used names).
- * Can be <code>null</code> if there is no excluded names.
- * @return char[][] an array of names.
- * @see JavaScriptCore#setOptions(java.util.Hashtable)
- * @see JavaScriptCore#getDefaultOptions()
- */
- public static String[] suggestLocalVariableNames(IJavaScriptProject javaProject, String packageName, String qualifiedTypeName, int dim, String[] excludedNames) {
- return convertCharsToString(
- suggestLocalVariableNames(
- javaProject,
- packageName.toCharArray(),
- qualifiedTypeName.toCharArray(),
- dim,
- convertStringToChars(excludedNames)));
- }
-
- /**
- * Suggest name for a getter method. The name is computed from field's name
- * and possible prefixes or suffixes are removed.
- * <p>
- * If the field name is <code>preFieldNamesuf</code> and the prefix for field is <code>pre</code> and
- * the suffix for field is <code>suf</code> then the prosposed name is <code>isFieldName</code> for boolean field or
- * <code>getFieldName</code> for others. If there is no prefix and suffix the proposal is <code>isPreFieldNamesuf</code>
- * for boolean field or <code>getPreFieldNamesuf</code> for others.
- * </p>
- * <p>
- * This method is affected by the following JavaScriptCore options : {@link JavaScriptCore#CODEASSIST_FIELD_PREFIXES},
- * {@link JavaScriptCore#CODEASSIST_FIELD_SUFFIXES} for instance field and {@link JavaScriptCore#CODEASSIST_STATIC_FIELD_PREFIXES},
- * {@link JavaScriptCore#CODEASSIST_STATIC_FIELD_SUFFIXES} for static field.
- * </p>
- * <p>
- * For a complete description of these configurable options, see <code>getDefaultOptions</code>.
- * For programmaticaly change these options, see <code>JavaScriptCore#setOptions()</code>.
- * </p>
- *
- * @param project project which contains the field.
- * @param fieldName field's name's.
- * @param modifiers field's modifiers as defined by the class
- * <code>Flags</code>.
- * @param isBoolean <code>true</code> if the field's type is boolean
- * @param excludedNames a list of names which cannot be suggested (already used names).
- * Can be <code>null</code> if there is no excluded names.
- * @return char[] a name.
- * @see Flags
- * @see JavaScriptCore#setOptions(java.util.Hashtable)
- * @see JavaScriptCore#getDefaultOptions()
- */
- public static char[] suggestGetterName(IJavaScriptProject project, char[] fieldName, int modifiers, boolean isBoolean, char[][] excludedNames) {
- if (isBoolean) {
- char[] name = removePrefixAndSuffixForFieldName(project, fieldName, modifiers);
- int prefixLen = GETTER_BOOL_NAME.length;
- if (CharOperation.prefixEquals(GETTER_BOOL_NAME, name)
- && name.length > prefixLen && ScannerHelper.isUpperCase(name[prefixLen])) {
- return suggestNewName(name, excludedNames);
- } else {
- return suggestNewName(
- CharOperation.concat(GETTER_BOOL_NAME, suggestAccessorName(project, fieldName, modifiers)),
- excludedNames
- );
- }
- } else {
- return suggestNewName(
- CharOperation.concat(GETTER_NAME, suggestAccessorName(project, fieldName, modifiers)),
- excludedNames
- );
- }
- }
-
- /**
- * Suggest name for a getter method. The name is computed from field's name
- * and possible prefixes or suffixes are removed.
- * <p>
- * If the field name is <code>preFieldNamesuf</code> and the prefix for field is <code>pre</code> and
- * the suffix for field is <code>suf</code> then the prosposed name is <code>isFieldName</code> for boolean field or
- * <code>getFieldName</code> for others. If there is no prefix and suffix the proposal is <code>isPreFieldNamesuf</code>
- * for boolean field or <code>getPreFieldNamesuf</code> for others.
- * </p>
- * <p>
- * This method is affected by the following JavaScriptCore options : {@link JavaScriptCore#CODEASSIST_FIELD_PREFIXES},
- * {@link JavaScriptCore#CODEASSIST_FIELD_SUFFIXES} for instance field and {@link JavaScriptCore#CODEASSIST_STATIC_FIELD_PREFIXES},
- * {@link JavaScriptCore#CODEASSIST_STATIC_FIELD_SUFFIXES} for static field.
- * </p>
- * <p>
- * For a complete description of these configurable options, see <code>getDefaultOptions</code>.
- * For programmaticaly change these options, see <code>JavaScriptCore#setOptions()</code>.
- * </p>
- *
- * @param project project which contains the field.
- * @param fieldName field's name's.
- * @param modifiers field's modifiers as defined by the class
- * <code>Flags</code>.
- * @param isBoolean <code>true</code> if the field's type is boolean
- * @param excludedNames a list of names which cannot be suggested (already used names).
- * Can be <code>null</code> if there is no excluded names.
- * @return char[] a name.
- * @see Flags
- * @see JavaScriptCore#setOptions(java.util.Hashtable)
- * @see JavaScriptCore#getDefaultOptions()
- */
- public static String suggestGetterName(IJavaScriptProject project, String fieldName, int modifiers, boolean isBoolean, String[] excludedNames) {
- return String.valueOf(
- suggestGetterName(
- project,
- fieldName.toCharArray(),
- modifiers,
- isBoolean,
- convertStringToChars(excludedNames)));
- }
-
- /**
- * Suggest name for a setter method. The name is computed from field's name
- * and possible prefixes or suffixes are removed.
- * <p>
- * If the field name is <code>preFieldNamesuf</code> and the prefix for field is <code>pre</code> and
- * the suffix for field is <code>suf</code> then the proposed name is <code>setFieldName</code>.
- * If there is no prefix and suffix the proposal is <code>setPreFieldNamesuf</code>.
- * </p>
- * <p>
- * This method is affected by the following JavaScriptCore options : {@link JavaScriptCore#CODEASSIST_FIELD_PREFIXES},
- * {@link JavaScriptCore#CODEASSIST_FIELD_SUFFIXES} for instance field and {@link JavaScriptCore#CODEASSIST_STATIC_FIELD_PREFIXES},
- * {@link JavaScriptCore#CODEASSIST_STATIC_FIELD_SUFFIXES} for static field.
- * </p>
- * <p>
- * For a complete description of these configurable options, see <code>getDefaultOptions</code>.
- * For programmaticaly change these options, see <code>JavaScriptCore#setOptions()</code>.
- * </p>
- *
- * @param project project which contains the field.
- * @param fieldName field's name's.
- * @param modifiers field's modifiers as defined by the class
- * <code>Flags</code>.
- * @param isBoolean <code>true</code> if the field's type is boolean
- * @param excludedNames a list of names which cannot be suggested (already used names).
- * Can be <code>null</code> if there is no excluded names.
- * @return char[] a name.
- * @see Flags
- * @see JavaScriptCore#setOptions(java.util.Hashtable)
- * @see JavaScriptCore#getDefaultOptions()
- */
- public static char[] suggestSetterName(IJavaScriptProject project, char[] fieldName, int modifiers, boolean isBoolean, char[][] excludedNames) {
-
- if (isBoolean) {
- char[] name = removePrefixAndSuffixForFieldName(project, fieldName, modifiers);
- int prefixLen = GETTER_BOOL_NAME.length;
- if (CharOperation.prefixEquals(GETTER_BOOL_NAME, name)
- && name.length > prefixLen && ScannerHelper.isUpperCase(name[prefixLen])) {
- name = CharOperation.subarray(name, prefixLen, name.length);
- return suggestNewName(
- CharOperation.concat(SETTER_NAME, suggestAccessorName(project, name, modifiers)),
- excludedNames
- );
- } else {
- return suggestNewName(
- CharOperation.concat(SETTER_NAME, suggestAccessorName(project, fieldName, modifiers)),
- excludedNames
- );
- }
- } else {
- return suggestNewName(
- CharOperation.concat(SETTER_NAME, suggestAccessorName(project, fieldName, modifiers)),
- excludedNames
- );
- }
- }
-
- /**
- * Suggest name for a setter method. The name is computed from field's name
- * and possible prefixes or suffixes are removed.
- * <p>
- * If the field name is <code>preFieldNamesuf</code> and the prefix for field is <code>pre</code> and
- * the suffix for field is <code>suf</code> then the proposed name is <code>setFieldName</code>.
- * If there is no prefix and suffix the proposal is <code>setPreFieldNamesuf</code>.
- * </p>
- * <p>
- * This method is affected by the following JavaScriptCore options : {@link JavaScriptCore#CODEASSIST_FIELD_PREFIXES},
- * {@link JavaScriptCore#CODEASSIST_FIELD_SUFFIXES} for instance field and {@link JavaScriptCore#CODEASSIST_STATIC_FIELD_PREFIXES},
- * {@link JavaScriptCore#CODEASSIST_STATIC_FIELD_SUFFIXES} for static field.
- * </p>
- * <p>
- * For a complete description of these configurable options, see <code>getDefaultOptions</code>.
- * For programmaticaly change these options, see <code>JavaScriptCore#setOptions()</code>.
- * </p>
- *
- * @param project project which contains the field.
- * @param fieldName field's name's.
- * @param modifiers field's modifiers as defined by the class
- * <code>Flags</code>.
- * @param isBoolean <code>true</code> if the field's type is boolean
- * @param excludedNames a list of names which cannot be suggested (already used names).
- * Can be <code>null</code> if there is no excluded names.
- * @return char[] a name.
- * @see Flags
- * @see JavaScriptCore#setOptions(java.util.Hashtable)
- * @see JavaScriptCore#getDefaultOptions()
- */
- public static String suggestSetterName(IJavaScriptProject project, String fieldName, int modifiers, boolean isBoolean, String[] excludedNames) {
- return String.valueOf(
- suggestSetterName(
- project,
- fieldName.toCharArray(),
- modifiers,
- isBoolean,
- convertStringToChars(excludedNames)));
- }
-
- private static char[] suggestAccessorName(IJavaScriptProject project, char[] fieldName, int modifiers) {
- char[] name = removePrefixAndSuffixForFieldName(project, fieldName, modifiers);
- if (name.length > 0 && ScannerHelper.isLowerCase(name[0])) {
- name[0] = ScannerHelper.toUpperCase(name[0]);
- }
- return name;
- }
-
- private static char[] suggestNewName(char[] name, char[][] excludedNames){
- if(excludedNames == null) {
- return name;
- }
-
- char[] newName = name;
- int count = 2;
- int i = 0;
- while (i < excludedNames.length) {
- if(CharOperation.equals(newName, excludedNames[i], false)) {
- newName = CharOperation.concat(name, String.valueOf(count++).toCharArray());
- i = 0;
- } else {
- i++;
- }
- }
- return newName;
- }
-
- private static String[] convertCharsToString(char[][] c) {
- int length = c == null ? 0 : c.length;
- String[] s = new String[length];
- for (int i = 0; i < length; i++) {
- s[i] = String.valueOf(c[i]);
- }
- return s;
- }
-
- private static char[][] convertStringToChars(String[] s) {
- int length = s == null ? 0 : s.length;
- char[][] c = new char[length][];
- for (int i = 0; i < length; i++) {
- if(s[i] == null) {
- c[i] = CharOperation.NO_CHAR;
- } else {
- c[i] = s[i].toCharArray();
- }
- }
- return c;
- }
-}
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
deleted file mode 100644
index 07c2dbb1..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/Signature.java
+++ /dev/null
@@ -1,1644 +0,0 @@
-/*******************************************************************************
- * 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
- * IBM Corporation - added J2SE 1.5 support
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.parser.ScannerHelper;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-
-/**
- * Provides methods for encoding and decoding type and method signature strings.
- * <p>
- * This class provides static methods and constants only; it is not intended to be
- * instantiated or subclassed by clients.
- * </p>
- *
- * 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 final class Signature {
-
- /**
- * Character constant indicating the semicolon in a signature.
- * Value is <code>';'</code>.
- */
- public static final char C_SEMICOLON = ';';
-
- /**
- * Character constant indicating the colon in a signature.
- * Value is <code>':'</code>.
- * 3.0
- */
- public static final char C_COLON = ':';
-
- /**
- * Character constant indicating result type void in a signature.
- * Value is <code>'V'</code>.
- */
- public static final char C_VOID = 'V';
-
-
- /**
- * Character constant indicating any type in a signature.
- * Value is <code>'A'</code>.
- */
- public static final char C_ANY = 'A';
-
- /**
- * Character constant indicating the dot in a signature.
- * Value is <code>'.'</code>.
- */
- public static final char C_DOT = '.';
-
- /**
- * Character constant indicating the dollar in a signature.
- * Value is <code>'$'</code>.
- */
- public static final char C_DOLLAR = '$';
-
- /**
- * Character constant indicating an array type in a signature.
- * Value is <code>'['</code>.
- */
- public static final char C_ARRAY = '[';
-
- /**
- * Character constant indicating the start of a resolved, named type in a
- * signature. Value is <code>'L'</code>.
- */
- public static final char C_RESOLVED = 'L';
-
-
- /**
- * Character constant indicating a compilation unit.
- * Value is <code>'X'</code>.
- */
- public static final char C_COMPILATION_UNIT = 'X';
-
-
- /**
- * Character constant indicating the start of an unresolved, named type in a
- * signature. Value is <code>'Q'</code>.
- */
- public static final char C_UNRESOLVED = 'Q';
-
- /**
- * Character constant indicating the end of a named type in a signature.
- * Value is <code>';'</code>.
- */
- public static final char C_NAME_END = ';';
-
- /**
- * Character constant indicating the start of a parameter type list in a
- * signature. Value is <code>'('</code>.
- */
- public static final char C_PARAM_START = '(';
-
- /**
- * Character constant indicating the end of a parameter type list in a
- * signature. Value is <code>')'</code>.
- */
- public static final char C_PARAM_END = ')';
-
- /** String constant for the signature of result type void.
- * Value is <code>"V"</code>.
- */
- public static final String SIG_VOID = "V"; //$NON-NLS-1$
-
- public static final String SIG_ANY = "A"; //$NON-NLS-1$
-
- public static final String SIG_COMPILATION_UNIT = "X"; //$NON-NLS-1$
-
- /**
- * Kind constant for a class type signature.
- * @see #getTypeSignatureKind(String)
- *
- */
- public static final int CLASS_TYPE_SIGNATURE = 1;
-
- /**
- * Kind constant for a base (primitive or void) type signature.
- * @see #getTypeSignatureKind(String)
- *
- */
- public static final int BASE_TYPE_SIGNATURE = 2;
-
- /**
- * Kind constant for an array type signature.
- * @see #getTypeSignatureKind(String)
- *
- */
- public static final int ARRAY_TYPE_SIGNATURE = 4;
-
- private static final char[] VOID = "void".toCharArray(); //$NON-NLS-1$
- public static final char[] ANY = "any".toCharArray(); //$NON-NLS-1$
-
-private Signature() {
- // Not instantiable
-}
-
-private static int checkName(char[] name, char[] typeName, int pos, int length) {
- if (CharOperation.fragmentEquals(name, typeName, pos, true)) {
- pos += name.length;
- if (pos == length) return pos;
- char currentChar = typeName[pos];
- switch (currentChar) {
- case ' ' :
- case '.' :
- case '[' :
- case ',' :
- return pos;
- default:
- if (ScannerHelper.isWhitespace(currentChar))
- return pos;
-
- }
- }
- return -1;
-}
-
-/**
- * Creates a new type signature with the given amount of array nesting added
- * to the given type signature.
- *
- * @param typeSignature the type signature
- * @param arrayCount the desired number of levels of array nesting
- * @return the encoded array type signature
- *
- *
- */
-public static char[] createArraySignature(char[] typeSignature, int arrayCount) {
- if (arrayCount == 0) return typeSignature;
- int sigLength = typeSignature.length;
- char[] result = new char[arrayCount + sigLength];
- for (int i = 0; i < arrayCount; i++) {
- result[i] = C_ARRAY;
- }
- System.arraycopy(typeSignature, 0, result, arrayCount, sigLength);
- return result;
-}
-/**
- * Creates a new type signature with the given amount of array nesting added
- * to the given type signature.
- *
- * @param typeSignature the type signature
- * @param arrayCount the desired number of levels of array nesting
- * @return the encoded array type signature
- */
-public static String createArraySignature(String typeSignature, int arrayCount) {
- return new String(createArraySignature(typeSignature.toCharArray(), arrayCount));
-}
-
-/**
- * Creates a method signature from the given parameter and return type
- * signatures. The encoded method signature is dot-based.
- *
- * @param parameterTypes the list of parameter type signatures
- * @param returnType the return type signature
- * @return the encoded method signature
- *
- *
- */
-public static char[] createMethodSignature(char[][] parameterTypes, char[] returnType) {
- int parameterTypesLength = parameterTypes.length;
- int parameterLength = 0;
- for (int i = 0; i < parameterTypesLength; i++) {
- parameterLength += parameterTypes[i].length;
-
- }
- int returnTypeLength = returnType.length;
- char[] result = new char[1 + parameterLength + 1 + returnTypeLength];
- result[0] = C_PARAM_START;
- int index = 1;
- for (int i = 0; i < parameterTypesLength; i++) {
- char[] parameterType = parameterTypes[i];
- int length = parameterType.length;
- System.arraycopy(parameterType, 0, result, index, length);
- index += length;
- }
- result[index] = C_PARAM_END;
- System.arraycopy(returnType, 0, result, index+1, returnTypeLength);
- return result;
-}
-
-/**
- * Creates a method signature from the given parameter and return type
- * signatures. The encoded method signature is dot-based. This method
- * is equivalent to
- * <code>createMethodSignature(parameterTypes, returnType)</code>.
- *
- * @param parameterTypes the list of parameter type signatures
- * @param returnType the return type signature
- * @return the encoded method signature
- * @see Signature#createMethodSignature(char[][], char[])
- */
-public static String createMethodSignature(String[] parameterTypes, String returnType) {
- int parameterTypesLenth = parameterTypes.length;
- char[][] parameters = new char[parameterTypesLenth][];
- for (int i = 0; i < parameterTypesLenth; i++) {
- parameters[i] = parameterTypes[i].toCharArray();
- }
- return new String(createMethodSignature(parameters, returnType.toCharArray()));
-}
-
-/**
- * Creates a new type signature from the given type name encoded as a character
- * array. The type name may contain primitive types, array types or parameterized types.
- * This method is equivalent to
- * <code>createTypeSignature(new String(typeName),isResolved)</code>, although
- * more efficient for callers with character arrays rather than strings. If the
- * type name is qualified, then it is expected to be dot-based.
- *
- * @param typeName the possibly qualified type name
- * @param isResolved <code>true</code> if the type name is to be considered
- * resolved (for example, a type name from a binary class file), and
- * <code>false</code> if the type name is to be considered unresolved
- * (for example, a type name found in source code)
- * @return the encoded type signature
- * @see #createTypeSignature(java.lang.String,boolean)
- */
-public static String createTypeSignature(char[] typeName, boolean isResolved) {
- return new String(createCharArrayTypeSignature(typeName, isResolved));
-}
-
-/**
- * Creates a new type signature from the given type name encoded as a character
- * array. The type name may contain primitive types or array types or parameterized types.
- * This method is equivalent to
- * <code>createTypeSignature(new String(typeName),isResolved).toCharArray()</code>,
- * although more efficient for callers with character arrays rather than strings.
- * If the type name is qualified, then it is expected to be dot-based.
- *
- * @param typeName the possibly qualified type name
- * @param isResolved <code>true</code> if the type name is to be considered
- * resolved (for example, a type name from a binary class file), and
- * <code>false</code> if the type name is to be considered unresolved
- * (for example, a type name found in source code)
- * @return the encoded type signature
- * @see #createTypeSignature(java.lang.String,boolean)
- *
- *
- */
-public static char[] createCharArrayTypeSignature(char[] typeName, boolean isResolved) {
- if (typeName == null || typeName.length == 0)
- {
- return new char[]{C_ANY};
- }
-
- int length = typeName.length;
- StringBuffer buffer = new StringBuffer(5);
- int pos = encodeTypeSignature(typeName, 0, isResolved, length, buffer);
- pos = consumeWhitespace(typeName, pos, length);
- if (pos < length) throw new IllegalArgumentException(new String(typeName));
- char[] result = new char[length = buffer.length()];
- buffer.getChars(0, length, result, 0);
- return result;
-}
-private static int consumeWhitespace(char[] typeName, int pos, int length) {
- while (pos < length) {
- char currentChar = typeName[pos];
- if (currentChar != ' ' && !CharOperation.isWhitespace(currentChar)) {
- break;
- }
- pos++;
- }
- return pos;
-}
-private static int encodeQualifiedName(char[] typeName, int pos, int length, StringBuffer buffer) {
- int count = 0;
- char lastAppendedChar = 0;
- nameLoop: while (pos < length) {
- char currentChar = typeName[pos];
- switch (currentChar) {
- case '[' :
- case ',' :
- break nameLoop;
- case '.' :
- buffer.append(C_DOT);
- lastAppendedChar = C_DOT;
- count++;
- break;
- default:
- if (currentChar == ' ' || ScannerHelper.isWhitespace(currentChar)) {
- if (lastAppendedChar == C_DOT) { // allow spaces after a dot
- pos = consumeWhitespace(typeName, pos, length) - 1; // will be incremented
- break;
- }
- // allow spaces before a dot
- int checkPos = checkNextChar(typeName, '.', pos, length, true);
- if (checkPos > 0) {
- buffer.append(C_DOT); // process dot immediately to avoid one iteration
- lastAppendedChar = C_DOT;
- count++;
- pos = checkPos;
- break;
- }
- break nameLoop;
- }
- buffer.append(currentChar);
- lastAppendedChar = currentChar;
- count++;
- break;
- }
- pos++;
- }
- if (count == 0) throw new IllegalArgumentException(new String(typeName));
- return pos;
-}
-
-private static int encodeArrayDimension(char[] typeName, int pos, int length, StringBuffer buffer) {
- int checkPos;
- while (pos < length && (checkPos = checkNextChar(typeName, '[', pos, length, true)) > 0) {
- pos = checkNextChar(typeName, ']', checkPos, length, false);
- buffer.append(C_ARRAY);
- }
- return pos;
-}
-private static int checkArrayDimension(char[] typeName, int pos, int length) {
- int genericBalance = 0;
- while (pos < length) {
- switch(typeName[pos]) {
- case ',' :
- if (genericBalance == 0) return -1;
- break;
- case '[':
- if (genericBalance == 0) {
- return pos;
- }
- }
- pos++;
- }
- return -1;
-}
-private static int checkNextChar(char[] typeName, char expectedChar, int pos, int length, boolean isOptional) {
- pos = consumeWhitespace(typeName, pos, length);
- if (pos < length && typeName[pos] == expectedChar)
- return pos + 1;
- if (!isOptional) throw new IllegalArgumentException(new String(typeName));
- return -1;
-}
-
-private static int encodeTypeSignature(char[] typeName, int start, boolean isResolved, int length, StringBuffer buffer) {
- int pos = start;
- pos = consumeWhitespace(typeName, pos, length);
- if (pos >= length) throw new IllegalArgumentException(new String(typeName));
- int checkPos;
- char currentChar = typeName[pos];
- switch (currentChar) {
- // primitive type?
- case 'v':
- checkPos = checkName(VOID, typeName, pos, length);
- if (checkPos > 0) {
- pos = encodeArrayDimension(typeName, checkPos, length, buffer);
- buffer.append(C_VOID);
- return pos;
- }
- break;
- }
- // non primitive type
- checkPos = checkArrayDimension(typeName, pos, length);
- int end;
- if (checkPos > 0) {
- end = encodeArrayDimension(typeName, checkPos, length, buffer);
- } else {
- end = -1;
- }
- buffer.append(isResolved ? C_RESOLVED : C_UNRESOLVED);
- while (true) { // loop on qualifiedName[<args>][.qualifiedName[<args>]*
- pos = encodeQualifiedName(typeName, pos, length, buffer);
- checkPos = checkNextChar(typeName, '.', pos, length, true);
- if (checkPos > 0) {
- buffer.append(C_DOT);
- pos = checkPos;
- } else {
- break;
- }
- }
- buffer.append(C_NAME_END);
- if (end > 0) pos = end; // skip array dimension which were preprocessed
- return pos;
-}
-
-/**
- * Creates a new type signature from the given type name. If the type name is qualified,
- * then it is expected to be dot-based. The type name may contain primitive
- * types or array types. However, parameterized types are not supported.
- * <p>
- * For example:
- * <pre>
- * <code>
- * createTypeSignature("int", hucairz) -> "I"
- * createTypeSignature("java.lang.String", true) -> "Ljava.lang.String;"
- * createTypeSignature("String", false) -> "QString;"
- * createTypeSignature("java.lang.String", false) -> "Qjava.lang.String;"
- * createTypeSignature("int []", false) -> "[I"
- * </code>
- * </pre>
- * </p>
- *
- * @param typeName the possibly qualified type name
- * @param isResolved <code>true</code> if the type name is to be considered
- * resolved (for example, a type name from a binary class file), and
- * <code>false</code> if the type name is to be considered unresolved
- * (for example, a type name found in source code)
- * @return the encoded type signature
- */
-public static String createTypeSignature(String typeName, boolean isResolved) {
- return createTypeSignature(typeName == null ? null : typeName.toCharArray(), isResolved);
-}
-
-/**
- * Returns the array count (array nesting depth) of the given type signature.
- *
- * @param typeSignature the type signature
- * @return the array nesting depth, or 0 if not an array
- * @exception IllegalArgumentException if the signature is not syntactically
- * correct
- *
- *
- */
-public static int getArrayCount(char[] typeSignature) throws IllegalArgumentException {
- try {
- int count = 0;
- while (typeSignature[count] == C_ARRAY) {
- ++count;
- }
- return count;
- } catch (ArrayIndexOutOfBoundsException e) { // signature is syntactically incorrect if last character is C_ARRAY
- throw new IllegalArgumentException();
- }
-}
-/**
- * Returns the array count (array nesting depth) of the given type signature.
- *
- * @param typeSignature the type signature
- * @return the array nesting depth, or 0 if not an array
- * @exception IllegalArgumentException if the signature is not syntactically
- * correct
- */
-public static int getArrayCount(String typeSignature) throws IllegalArgumentException {
- return getArrayCount(typeSignature.toCharArray());
-}
-/**
- * Returns the type signature without any array nesting.
- * <p>
- * For example:
- * <pre>
- * <code>
- * getElementType({'[', '[', 'I'}) --> {'I'}.
- * </code>
- * </pre>
- * </p>
- *
- * @param typeSignature the type signature
- * @return the type signature without arrays
- * @exception IllegalArgumentException if the signature is not syntactically
- * correct
- *
- *
- */
-public static char[] getElementType(char[] typeSignature) throws IllegalArgumentException {
- int count = getArrayCount(typeSignature);
- if (count == 0) return typeSignature;
- int length = typeSignature.length;
- char[] result = new char[length-count];
- System.arraycopy(typeSignature, count, result, 0, length-count);
- return result;
-}
-/**
- * Returns the type signature without any array nesting.
- * <p>
- * For example:
- * <pre>
- * <code>
- * getElementType("[[I") --> "I".
- * </code>
- * </pre>
- * </p>
- *
- * @param typeSignature the type signature
- * @return the type signature without arrays
- * @exception IllegalArgumentException if the signature is not syntactically
- * correct
- */
-public static String getElementType(String typeSignature) throws IllegalArgumentException {
- return new String(getElementType(typeSignature.toCharArray()));
-}
-/**
- * Returns the number of parameter types in the given method signature.
- *
- * @param methodSignature the method signature
- * @return the number of parameters
- * @exception IllegalArgumentException if the signature is not syntactically
- * correct
- *
- */
-public static int getParameterCount(char[] methodSignature) throws IllegalArgumentException {
- if (methodSignature==null)
- return 0;
- try {
- int count = 0;
- int i = CharOperation.indexOf(C_PARAM_START, methodSignature);
- if (i < 0) {
- throw new IllegalArgumentException();
- } else {
- i++;
- }
- for (;;) {
- if (methodSignature[i] == C_PARAM_END) {
- return count;
- }
- int e= Util.scanTypeSignature(methodSignature, i);
- if (e < 0) {
- throw new IllegalArgumentException();
- } else {
- i = e + 1;
- }
- count++;
- }
- } catch (ArrayIndexOutOfBoundsException e) {
- throw new IllegalArgumentException();
- }
-}
-
-/**
- * Returns the kind of type signature encoded by the given string.
- *
- * @param typeSignature the type signature string
- * @return the kind of type signature; one of the kind constants:
- * {@link #ARRAY_TYPE_SIGNATURE}, {@link #CLASS_TYPE_SIGNATURE},
- * {@link #BASE_TYPE_SIGNATURE}, or {@link #TYPE_VARIABLE_SIGNATURE},
- * or {@link #CAPTURE_TYPE_SIGNATURE}
- * @exception IllegalArgumentException if this is not a type signature
- *
- */
-public static int getTypeSignatureKind(char[] typeSignature) {
- // need a minimum 1 char
- if (typeSignature.length < 1) {
- throw new IllegalArgumentException();
- }
- char c = typeSignature[0];
- switch (c) {
- case C_ARRAY :
- return ARRAY_TYPE_SIGNATURE;
- case C_RESOLVED :
- case C_UNRESOLVED :
- return CLASS_TYPE_SIGNATURE;
- case C_VOID :
- case C_ANY :
- return BASE_TYPE_SIGNATURE;
- default :
- throw new IllegalArgumentException();
- }
-}
-
-/**
- * Returns the kind of type signature encoded by the given string.
- *
- * @param typeSignature the type signature string
- * @return the kind of type signature; one of the kind constants:
- * {@link #ARRAY_TYPE_SIGNATURE}, {@link #CLASS_TYPE_SIGNATURE},
- * {@link #BASE_TYPE_SIGNATURE}, or {@link #TYPE_VARIABLE_SIGNATURE},
- * or {@link #CAPTURE_TYPE_SIGNATURE}
- * @exception IllegalArgumentException if this is not a type signature
- *
- */
-public static int getTypeSignatureKind(String typeSignature) {
- if (typeSignature.length() < 1) {
- // uknown return type
- return BASE_TYPE_SIGNATURE;
- }
- char c = typeSignature.charAt(0);
- switch (c) {
- case C_ARRAY :
- return ARRAY_TYPE_SIGNATURE;
- case C_RESOLVED :
- case C_UNRESOLVED :
- return CLASS_TYPE_SIGNATURE;
- case C_VOID :
- case C_ANY :
-
- return BASE_TYPE_SIGNATURE;
- default :
- throw new IllegalArgumentException();
- }
-}
-
-/**
- * Returns the number of parameter types in the given method signature.
- *
- * @param methodSignature the method signature
- * @return the number of parameters
- * @exception IllegalArgumentException if the signature is not syntactically
- * correct
- */
-public static int getParameterCount(String methodSignature) throws IllegalArgumentException {
- return getParameterCount(methodSignature.toCharArray());
-}
-
-/**
- * Extracts the parameter type signatures from the given method signature.
- * The method signature is expected to be dot-based.
- *
- * @param methodSignature the method signature
- * @return the list of parameter type signatures
- * @exception IllegalArgumentException if the signature is syntactically
- * incorrect
- *
- *
- */
-public static char[][] getParameterTypes(char[] methodSignature) throws IllegalArgumentException {
- try {
- int count = getParameterCount(methodSignature);
- char[][] result = new char[count][];
- if (count == 0) {
- return result;
- }
- int i = CharOperation.indexOf(C_PARAM_START, methodSignature);
- if (i < 0) {
- throw new IllegalArgumentException();
- } else {
- i++;
- }
- int t = 0;
- for (;;) {
- if (methodSignature[i] == C_PARAM_END) {
- return result;
- }
- int e = Util.scanTypeSignature(methodSignature, i);
- if (e < 0) {
- throw new IllegalArgumentException();
- }
- result[t] = CharOperation.subarray(methodSignature, i, e + 1);
- t++;
- i = e + 1;
- }
- } catch (ArrayIndexOutOfBoundsException e) {
- throw new IllegalArgumentException();
- }
-}
-
-/**
- * Extracts the parameter type signatures from the given method signature.
- * The method signature is expected to be dot-based.
- *
- * @param methodSignature the method signature
- * @return the list of parameter type signatures
- * @exception IllegalArgumentException if the signature is syntactically
- * incorrect
- */
-public static String[] getParameterTypes(String methodSignature) throws IllegalArgumentException {
- char[][] parameterTypes = getParameterTypes(methodSignature.toCharArray());
- return CharOperation.toStrings(parameterTypes);
-}
-
-/**
- * Extracts the type variable name from the given formal type parameter
- * signature. The signature is expected to be dot-based.
- *
- * @param formalTypeParameterSignature the formal type parameter signature
- * @return the name of the type variable
- * @exception IllegalArgumentException if the signature is syntactically
- * incorrect
- *
- */
-public static String getTypeVariable(String formalTypeParameterSignature) throws IllegalArgumentException {
- return new String(getTypeVariable(formalTypeParameterSignature.toCharArray()));
-}
-
-/**
- * Extracts the type variable name from the given formal type parameter
- * signature. The signature is expected to be dot-based.
- *
- * @param formalTypeParameterSignature the formal type parameter signature
- * @return the name of the type variable
- * @exception IllegalArgumentException if the signature is syntactically
- * incorrect
- *
- */
-public static char[] getTypeVariable(char[] formalTypeParameterSignature) throws IllegalArgumentException {
- int p = CharOperation.indexOf(C_COLON, formalTypeParameterSignature);
- if (p < 0) {
- // no ":" means can't be a formal type parameter signature
- throw new IllegalArgumentException();
- }
- return CharOperation.subarray(formalTypeParameterSignature, 0, p);
-}
-
-/**
- * Returns a char array containing all but the last segment of the given
- * dot-separated qualified name. Returns the empty char array if it is not qualified.
- * <p>
- * For example:
- * <pre>
- * <code>
- * getQualifier({'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'O', 'b', 'j', 'e', 'c', 't'}) -> {'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g'}
- * getQualifier({'O', 'u', 't', 'e', 'r', '.', 'I', 'n', 'n', 'e', 'r'}) -> {'O', 'u', 't', 'e', 'r'}
- * getQualifier({'j', 'a', 'v', 'a', '.', 'u', 't', 'i', 'l', '.', 'L', 'i', 's', 't', '<', 'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'S', 't', 'r', 'i', 'n', 'g', '>'}) -> {'j', 'a', 'v', 'a', '.', 'u', 't', 'i', 'l'}
- * </code>
- * </pre>
- * </p>
- *
- * @param name the name
- * @return the qualifier prefix, or the empty char array if the name contains no
- * dots
- * @exception NullPointerException if name is null
- *
- */
-public static char[] getQualifier(char[] name) {
- int lastDot = CharOperation.lastIndexOf(C_DOT, name, 0, name.length-1);
- if (lastDot == -1) {
- return CharOperation.NO_CHAR;
- }
- return CharOperation.subarray(name, 0, lastDot);
-}
-/**
- * Returns a string containing all but the last segment of the given
- * dot-separated qualified name. Returns the empty string if it is not qualified.
- * <p>
- * For example:
- * <pre>
- * <code>
- * getQualifier("java.lang.Object") -&gt; "java.lang"
- * getQualifier("Outer.Inner") -&gt; "Outer"
- * getQualifier("java.util.List&lt;java.lang.String&gt;") -&gt; "java.util"
- * </code>
- * </pre>
- * </p>
- *
- * @param name the name
- * @return the qualifier prefix, or the empty string if the name contains no
- * dots
- * @exception NullPointerException if name is null
- */
-public static String getQualifier(String name) {
- char[] qualifier = getQualifier(name.toCharArray());
- if (qualifier.length == 0) return org.eclipse.wst.jsdt.internal.compiler.util.Util.EMPTY_STRING;
- return new String(qualifier);
-}
-/**
- * Extracts the return type from the given method signature. The method signature is
- * expected to be dot-based.
- *
- * @param methodSignature the method signature
- * @return the type signature of the return type
- * @exception IllegalArgumentException if the signature is syntactically
- * incorrect
- *
- *
- */
-public static char[] getReturnType(char[] methodSignature) throws IllegalArgumentException {
- // skip type parameters
- if (methodSignature==null)
- return CharOperation.NO_CHAR;
- int paren = CharOperation.lastIndexOf(C_PARAM_END, methodSignature);
- if (paren == -1) {
- // could not be determined
- return CharOperation.NO_CHAR;
- }
- // there could be thrown exceptions behind, thus scan one type exactly
- int last = Util.scanTypeSignature(methodSignature, paren+1);
- return CharOperation.subarray(methodSignature, paren + 1, last+1);
-}
-/**
- * Extracts the return type from the given method signature. The method signature is
- * expected to be dot-based.
- *
- * @param methodSignature the method signature
- * @return the type signature of the return type
- * @exception IllegalArgumentException if the signature is syntactically
- * incorrect
- */
-public static String getReturnType(String methodSignature) throws IllegalArgumentException {
- return new String(getReturnType(methodSignature.toCharArray()));
-}
-/**
- * Returns package fragment of a type signature. The package fragment separator must be '.'
- * and the type fragment separator must be '$'.
- * <p>
- * For example:
- * <pre>
- * <code>
- * getSignatureQualifier({'L', 'j', 'a', 'v', 'a', '.', 'u', 't', 'i', 'l', '.', 'M', 'a', 'p', '$', 'E', 'n', 't', 'r', 'y', ';'}) -> {'j', 'a', 'v', 'a', '.', 'u', 't', 'i', 'l'}
- * </code>
- * </pre>
- * </p>
- *
- * @param typeSignature the type signature
- * @return the package fragment (separators are '.')
- *
- */
-public static char[] getSignatureQualifier(char[] typeSignature) {
- if(typeSignature == null) return CharOperation.NO_CHAR;
-
- char[] qualifiedType = Signature.toCharArray(typeSignature);
-
- int dotCount = 0;
- indexFound: for(int i = 0; i < typeSignature.length; i++) {
- switch(typeSignature[i]) {
- case C_DOT:
- dotCount++;
- break;
- case C_DOLLAR:
- break indexFound;
- }
- }
-
- if(dotCount > 0) {
- for(int i = 0; i < qualifiedType.length; i++) {
- if(qualifiedType[i] == '.') {
- dotCount--;
- }
- if(dotCount <= 0) {
- return CharOperation.subarray(qualifiedType, 0, i);
- }
- }
- }
- return CharOperation.NO_CHAR;
-}
-/**
- * Returns package fragment of a type signature. The package fragment separator must be '.'
- * and the type fragment separator must be '$'.
- * <p>
- * For example:
- * <pre>
- * <code>
- * getSignatureQualifier("Ljava.util.Map$Entry") -> "java.util"
- * </code>
- * </pre>
- * </p>
- *
- * @param typeSignature the type signature
- * @return the package fragment (separators are '.')
- *
- */
-public static String getSignatureQualifier(String typeSignature) {
- return new String(getSignatureQualifier(typeSignature == null ? null : typeSignature.toCharArray()));
-}
-/**
- * Returns type fragment of a type signature. The package fragment separator must be '.'
- * and the type fragment separator must be '$'.
- * <p>
- * For example:
- * <pre>
- * <code>
- * getSignatureSimpleName({'L', 'j', 'a', 'v', 'a', '.', 'u', 't', 'i', 'l', '.', 'M', 'a', 'p', '$', 'E', 'n', 't', 'r', 'y', ';'}) -> {'M', 'a', 'p', '.', 'E', 'n', 't', 'r', 'y'}
- * </code>
- * </pre>
- * </p>
- *
- * @param typeSignature the type signature
- * @return the type fragment (separators are '.')
- *
- */
-public static char[] getSignatureSimpleName(char[] typeSignature) {
- if(typeSignature == null) return CharOperation.NO_CHAR;
-
- char[] qualifiedType = Signature.toCharArray(typeSignature);
-
-// int dotCount = 0;
-// indexFound: for(int i = 0; i < typeSignature.length; i++) {
-// switch(typeSignature[i]) {
-// case C_DOT:
-// dotCount++;
-// break;
-// case C_GENERIC_START:
-// break indexFound;
-// case C_DOLLAR:
-// break indexFound;
-// }
-// }
-//
-// if(dotCount > 0) {
-// for(int i = 0; i < qualifiedType.length; i++) {
-// if(qualifiedType[i] == '.') {
-// dotCount--;
-// }
-// if(dotCount <= 0) {
-// return CharOperation.subarray(qualifiedType, i + 1, qualifiedType.length);
-// }
-// }
-// }
- return qualifiedType;
-}
-/**
- * Returns type fragment of a type signature. The package fragment separator must be '.'
- * and the type fragment separator must be '$'.
- * <p>
- * For example:
- * <pre>
- * <code>
- * getSignatureSimpleName("Ljava.util.Map$Entry") -> "Map.Entry"
- * </code>
- * </pre>
- * </p>
- *
- * @param typeSignature the type signature
- * @return the type fragment (separators are '.')
- *
- */
-public static String getSignatureSimpleName(String typeSignature) {
- return new String(getSignatureSimpleName(typeSignature == null ? null : typeSignature.toCharArray()));
-}
-
-/**
- * Returns the last segment of the given dot-separated qualified name.
- * Returns the given name if it is not qualified.
- * <p>
- * For example:
- * <pre>
- * <code>
- * getSimpleName({'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'O', 'b', 'j', 'e', 'c', 't'}) -> {'O', 'b', 'j', 'e', 'c', 't'}
- * </code>
- * </pre>
- * </p>
- *
- * @param name the name
- * @return the last segment of the qualified name
- * @exception NullPointerException if name is null
- *
- */
-public static char[] getSimpleName(char[] name) {
-
- int lastDot = -1;
- int depth = 0;
- int length = name.length;
- lastDotLookup: for (int i = length -1; i >= 0; i--) {
- switch (name[i]) {
- case '.':
- if (depth == 0) {
- lastDot = i;
- break lastDotLookup;
- }
- break;
- }
- }
-
- if (lastDot < 0) {
- return name;
- }
- return CharOperation.subarray(name, lastDot + 1, length);
-}
-/**
- * Returns the last segment of the given dot-separated qualified name.
- * Returns the given name if it is not qualified.
- * <p>
- * For example:
- * <pre>
- * <code>
- * getSimpleName("java.lang.Object") -&gt; "Object"
- * </code>
- * <code>
- * getSimpleName("java.util.Map&lt;java.lang.String, java.lang.Object&gt;") -&gt; "Map&lt;String,Object&gt;"
- * </code>
- * </pre>
- * </p>
- *
- * @param name the name
- * @return the last segment of the qualified name
- * @exception NullPointerException if name is null
- */
-public static String getSimpleName(String name) {
- int lastDot = -1;
- int depth = 0;
- int length = name.length();
- lastDotLookup: for (int i = length -1; i >= 0; i--) {
- switch (name.charAt(i)) {
- case '.':
- if (depth == 0) {
- lastDot = i;
- break lastDotLookup;
- }
- break;
- }
- }
- if (lastDot < 0) {
- return name;
- }
- return name.substring(lastDot + 1, length);
-}
-
-/**
- * Returns all segments of the given dot-separated qualified name.
- * Returns an array with only the given name if it is not qualified.
- * Returns an empty array if the name is empty.
- * <p>
- * For example:
- * <pre>
- * <code>
- * getSimpleNames({'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'O', 'b', 'j', 'e', 'c', 't'}) -> {{'j', 'a', 'v', 'a'}, {'l', 'a', 'n', 'g'}, {'O', 'b', 'j', 'e', 'c', 't'}}
- * getSimpleNames({'O', 'b', 'j', 'e', 'c', 't'}) -> {{'O', 'b', 'j', 'e', 'c', 't'}}
- * getSimpleNames({}) -> {}
- * getSimpleNames({'j', 'a', 'v', 'a', '.', 'u', 't', 'i', 'l', '.', 'L', 'i', 's', 't', '<', 'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'S', 't', 'r', 'i', 'n', 'g', '>'}) -> {{'j', 'a', 'v', 'a'}, {'l', 'a', 'n', 'g'}, {'L', 'i', 's', 't', '<', 'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'S', 't', 'r', 'i', 'n', 'g'}}
- * </code>
- * </pre>
- *
- * @param name the name
- * @return the list of simple names, possibly empty
- * @exception NullPointerException if name is null
- *
- */
-public static char[][] getSimpleNames(char[] name) {
- int length = name == null ? 0 : name.length;
- if (length == 0)
- return CharOperation.NO_CHAR_CHAR;
-
- int wordCount = 1;
- for (int i = 0; i < length; i++)
- switch(name[i]) {
- case C_DOT:
- wordCount++;
- break;
- }
- char[][] split = new char[wordCount][];
- int last = 0, currentWord = 0;
- for (int i = 0; i < length; i++) {
- if (name[i] == C_DOT) {
- split[currentWord] = new char[i - last];
- System.arraycopy(
- name,
- last,
- split[currentWord++],
- 0,
- i - last);
- last = i + 1;
- }
- }
- split[currentWord] = new char[length - last];
- System.arraycopy(name, last, split[currentWord], 0, length - last);
- return split;
-}
-/**
- * Returns all segments of the given dot-separated qualified name.
- * Returns an array with only the given name if it is not qualified.
- * Returns an empty array if the name is empty.
- * <p>
- * For example:
- * <pre>
- * <code>
- * getSimpleNames("java.lang.Object") -&gt; {"java", "lang", "Object"}
- * getSimpleNames("Object") -&gt; {"Object"}
- * getSimpleNames("") -&gt; {}
- * getSimpleNames("java.util.List&lt;java.lang.String&gt;") -&gt;
- * {"java", "util", "List&lt;java.lang.String&gt;"}
- * </code>
- * </pre>
- *
- * @param name the name
- * @return the list of simple names, possibly empty
- * @exception NullPointerException if name is null
- */
-public static String[] getSimpleNames(String name) {
- return CharOperation.toStrings(getSimpleNames(name.toCharArray()));
-}
-
-/**
- * Converts the given method signature to a readable form. The method signature is expected to
- * be dot-based.
- * <p>
- * For example:
- * <pre>
- * <code>
- * toString("([Ljava.lang.String;)V", "main", new String[] {"args"}, false, true) -> "void main(String[] args)"
- * </code>
- * </pre>
- * </p>
- *
- * @param methodSignature the method signature to convert
- * @param methodName the name of the method to insert in the result, or
- * <code>null</code> if no method name is to be included
- * @param parameterNames the parameter names to insert in the result, or
- * <code>null</code> if no parameter names are to be included; if supplied,
- * the number of parameter names must match that of the method signature
- * @param fullyQualifyTypeNames <code>true</code> if type names should be fully
- * qualified, and <code>false</code> to use only simple names
- * @param includeReturnType <code>true</code> if the return type is to be
- * included
- * @return the char array representation of the method signature
- *
- *
- */
-public static char[] toCharArray(char[] methodSignature, char[] methodName, char[][] parameterNames, boolean fullyQualifyTypeNames, boolean includeReturnType) {
- return toCharArray(methodSignature, methodName, parameterNames, fullyQualifyTypeNames, includeReturnType, false);
-}
-/**
- * Converts the given method signature to a readable form. The method signature is expected to
- * be dot-based.
- * <p>
- * For example:
- * <pre>
- * <code>
- * toString("([Ljava.lang.String;)V", "main", new String[] {"args"}, false, true) -> "void main(String[] args)"
- * </code>
- * </pre>
- * </p>
- *
- * @param methodSignature the method signature to convert
- * @param methodName the name of the method to insert in the result, or
- * <code>null</code> if no method name is to be included
- * @param parameterNames the parameter names to insert in the result, or
- * <code>null</code> if no parameter names are to be included; if supplied,
- * the number of parameter names must match that of the method signature
- * @param fullyQualifyTypeNames <code>true</code> if type names should be fully
- * qualified, and <code>false</code> to use only simple names
- * @param includeReturnType <code>true</code> if the return type is to be
- * included
- * @param isVargArgs <code>true</code> if the last argument should be displayed as a
- * variable argument, <code>false</code> otherwise.
- * @return the char array representation of the method signature
- *
- *
- */
-public static char[] toCharArray(char[] methodSignature, char[] methodName, char[][] parameterNames, boolean fullyQualifyTypeNames, boolean includeReturnType, boolean isVargArgs) {
- int firstParen = CharOperation.indexOf(C_PARAM_START, methodSignature);
- if (firstParen == -1) {
- throw new IllegalArgumentException();
- }
-
- StringBuffer buffer = new StringBuffer(methodSignature.length + 10);
-
- // return type
- if (includeReturnType) {
- char[] rts = getReturnType(methodSignature);
- appendTypeSignature(rts, 0 , fullyQualifyTypeNames, buffer);
- buffer.append(' ');
- }
-
- // selector
- if (methodName != null) {
- buffer.append(methodName);
- }
-
- // parameters
- buffer.append('(');
- char[][] pts = getParameterTypes(methodSignature);
- for (int i = 0, max = pts.length; i < max; i++) {
- if (i == max - 1) {
- appendTypeSignature(pts[i], 0 , fullyQualifyTypeNames, buffer, isVargArgs);
- } else {
- appendTypeSignature(pts[i], 0 , fullyQualifyTypeNames, buffer);
- }
- if (parameterNames != null) {
- buffer.append(' ');
- buffer.append(parameterNames[i]);
- }
- if (i != pts.length - 1) {
- buffer.append(',');
- buffer.append(' ');
- }
- }
- buffer.append(')');
- char[] result = new char[buffer.length()];
- buffer.getChars(0, buffer.length(), result, 0);
- return result;
-}
-/**
- * Converts the given type signature to a readable string. The signature is expected to
- * be dot-based.
- *
- * <p>
- * For example:
- * <pre>
- * <code>
- * toString({'[', 'L', 'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'S', 't', 'r', 'i', 'n', 'g', ';'}) -> {'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'S', 't', 'r', 'i', 'n', 'g', '[', ']'}
- * toString({'I'}) -> {'i', 'n', 't'}
- * toString({'+', 'L', 'O', 'b', 'j', 'e', 'c', 't', ';'}) -> {'?', ' ', 'e', 'x', 't', 'e', 'n', 'd', 's', ' ', 'O', 'b', 'j', 'e', 'c', 't'}
- * </code>
- * </pre>
- * </p>
- * <p>
- * Note: This method assumes that a type signature containing a <code>'$'</code>
- * is an inner type signature. While this is correct in most cases, someone could
- * define a non-inner type name containing a <code>'$'</code>. Handling this
- * correctly in all cases would have required resolving the signature, which
- * generally not feasible.
- * </p>
- *
- * @param signature the type signature
- * @return the string representation of the type
- * @exception IllegalArgumentException if the signature is not syntactically
- * correct
- *
- *
- */
-public static char[] toCharArray(char[] signature) throws IllegalArgumentException {
- int sigLength = signature.length;
- if (sigLength == 0 || signature[0] == C_PARAM_START) {
- return toCharArray(signature, CharOperation.NO_CHAR, null, true, true);
- }
-
- StringBuffer buffer = new StringBuffer(signature.length + 10);
- appendTypeSignature(signature, 0, true, buffer);
- char[] result = new char[buffer.length()];
- buffer.getChars(0, buffer.length(), result, 0);
- return result;
-}
-
-/**
- * Scans the given string for a type signature starting at the given
- * index and appends it to the given buffer, and returns the index of the last
- * character.
- *
- * @param string the signature string
- * @param start the 0-based character index of the first character
- * @param fullyQualifyTypeNames <code>true</code> if type names should be fully
- * qualified, and <code>false</code> to use only simple names
- * @param buffer the string buffer to append to
- * @return the 0-based character index of the last character
- * @exception IllegalArgumentException if this is not a type signature
- * @see Util#scanTypeSignature(char[], int)
- */
-private static int appendTypeSignature(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer) {
- return appendTypeSignature(string, start, fullyQualifyTypeNames, buffer, false);
-}
-/**
- * Scans the given string for a type signature starting at the given
- * index and appends it to the given buffer, and returns the index of the last
- * character.
- *
- * @param string the signature string
- * @param start the 0-based character index of the first character
- * @param fullyQualifyTypeNames <code>true</code> if type names should be fully
- * qualified, and <code>false</code> to use only simple names
- * @param buffer the string buffer to append to
- * @param isVarArgs <code>true</code> if the type must be displayed as a
- * variable argument, <code>false</code> otherwise. In this case, the type must be an array type
- * @return the 0-based character index of the last character
- * @exception IllegalArgumentException if this is not a type signature, or if isVarArgs is <code>true</code>,
- * and the type is not an array type signature.
- * @see Util#scanTypeSignature(char[], int)
- */
-private static int appendTypeSignature(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer, boolean isVarArgs) {
- // need a minimum 1 char
- if (start >= string.length) {
- throw new IllegalArgumentException();
- }
- char c = string[start];
- if (isVarArgs) {
- switch (c) {
- case C_ARRAY :
- return appendArrayTypeSignature(string, start, fullyQualifyTypeNames, buffer, true);
- case C_RESOLVED :
- case C_UNRESOLVED :
- case C_VOID :
- default:
- throw new IllegalArgumentException(); // a var args is an array type
- }
- } else {
- switch (c) {
- case C_ARRAY :
- return appendArrayTypeSignature(string, start, fullyQualifyTypeNames, buffer);
- case C_RESOLVED :
- case C_UNRESOLVED :
- return appendClassTypeSignature(string, start, fullyQualifyTypeNames, buffer);
- case C_COMPILATION_UNIT :
- return appendCompilationUnitSignature(string, start, fullyQualifyTypeNames, buffer);
- case C_ANY :
- buffer.append(ANY);
- return start;
- case C_VOID :
- buffer.append(VOID);
- return start;
- default :
- /* either the string is not formated as a signature, or we do not know
- * how to handle it, so just return it, this is preferable to throwing
- * an unnecessary exception
- */
- buffer.append(string);
- return start;
- }
- }
-}
-
-
-private static int appendCompilationUnitSignature(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer) {
- // need a minimum 3 chars "Lx;"
- if (start >= string.length - 2) {
- throw new IllegalArgumentException();
- }
- // must start in "L" or "Q"
- char c = string[start];
- if (c != C_COMPILATION_UNIT) {
- throw new IllegalArgumentException();
- }
- int p = start + 1;
- while (true) {
- if (p >= string.length) {
- throw new IllegalArgumentException();
- }
- c = string[p];
- switch(c) {
- case C_SEMICOLON :
- // all done
- return p;
- default :
- buffer.append(c);
- }
- p++;
- }
-}
-
-
-
-/**
- * Scans the given string for an array type signature starting at the given
- * index and appends it to the given buffer, and returns the index of the last
- * character.
- *
- * @param string the signature string
- * @param start the 0-based character index of the first character
- * @param fullyQualifyTypeNames <code>true</code> if type names should be fully
- * qualified, and <code>false</code> to use only simple names
- * @return the 0-based character index of the last character
- * @exception IllegalArgumentException if this is not an array type signature
- * @see Util#scanArrayTypeSignature(char[], int)
- */
-private static int appendArrayTypeSignature(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer) {
- return appendArrayTypeSignature(string, start, fullyQualifyTypeNames, buffer, false);
-}
-
-/**
- * Scans the given string for an array type signature starting at the given
- * index and appends it to the given buffer, and returns the index of the last
- * character.
- *
- * @param string the signature string
- * @param start the 0-based character index of the first character
- * @param fullyQualifyTypeNames <code>true</code> if type names should be fully
- * qualified, and <code>false</code> to use only simple names
- * @param isVarArgs <code>true</code> if the array type must be displayed as a
- * variable argument, <code>false</code> otherwise
- * @return the 0-based character index of the last character
- * @exception IllegalArgumentException if this is not an array type signature
- * @see Util#scanArrayTypeSignature(char[], int)
- */
-private static int appendArrayTypeSignature(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer, boolean isVarArgs) {
- int length = string.length;
- // need a minimum 2 char
- if (start >= length - 1) {
- throw new IllegalArgumentException();
- }
- char c = string[start];
- if (c != C_ARRAY) {
- throw new IllegalArgumentException();
- }
-
- int index = start;
- c = string[++index];
- while(c == C_ARRAY) {
- // need a minimum 2 char
- if (index >= length - 1) {
- throw new IllegalArgumentException();
- }
- c = string[++index];
- }
-
- int e = appendTypeSignature(string, index, fullyQualifyTypeNames, buffer);
-
- for(int i = 1, dims = index - start; i < dims; i++) {
- buffer.append('[').append(']');
- }
-
- if (isVarArgs) {
- buffer.append('.').append('.').append('.');
- } else {
- buffer.append('[').append(']');
- }
- return e;
-}
-/**
- * Scans the given string for a class type signature starting at the given
- * index and appends it to the given buffer, and returns the index of the last
- * character.
- *
- * @param string the signature string
- * @param start the 0-based character index of the first character
- * @param fullyQualifyTypeNames <code>true</code> if type names should be fully
- * qualified, and <code>false</code> to use only simple names
- * @param buffer the string buffer to append to
- * @return the 0-based character index of the last character
- * @exception IllegalArgumentException if this is not a class type signature
- * @see Util#scanClassTypeSignature(char[], int)
- */
-private static int appendClassTypeSignature(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer) {
- // need a minimum 3 chars "Lx;"
- if (start >= string.length - 2) {
- throw new IllegalArgumentException();
- }
- // must start in "L" or "Q"
- char c = string[start];
- if (c != C_RESOLVED && c != C_UNRESOLVED) {
- throw new IllegalArgumentException();
- }
- boolean resolved = (c == C_RESOLVED);
- boolean removePackageQualifiers = !fullyQualifyTypeNames;
- if (!resolved) {
- // keep everything in an unresolved name
- removePackageQualifiers = false;
- }
- int p = start + 1;
- int checkpoint = buffer.length();
- int innerTypeStart = -1;
- boolean inAnonymousType = false;
- while (true) {
- if (p >= string.length) {
- throw new IllegalArgumentException();
- }
- c = string[p];
- switch(c) {
- case C_SEMICOLON :
- // all done
- return p;
- case C_DOT :
- if (removePackageQualifiers) {
- // erase package prefix
- buffer.setLength(checkpoint);
- } else {
- buffer.append('.');
- }
- break;
- case '/' :
- if (removePackageQualifiers) {
- // erase package prefix
- buffer.setLength(checkpoint);
- } else {
- buffer.append('/');
- }
- break;
- default :
- if (innerTypeStart != -1 && !inAnonymousType && Character.isDigit(c)) {
- inAnonymousType = true;
- buffer.setLength(innerTypeStart); // remove '.'
- buffer.insert(checkpoint, "new "); //$NON-NLS-1$
- buffer.append("(){}"); //$NON-NLS-1$
- }
- if (!inAnonymousType)
- buffer.append(c);
- innerTypeStart = -1;
- }
- p++;
- }
-}
-
-/**
- * Converts the given array of qualified name segments to a qualified name.
- * <p>
- * For example:
- * <pre>
- * <code>
- * toQualifiedName({{'j', 'a', 'v', 'a'}, {'l', 'a', 'n', 'g'}, {'O', 'b', 'j', 'e', 'c', 't'}}) -> {'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'O', 'b', 'j', 'e', 'c', 't'}
- * toQualifiedName({{'O', 'b', 'j', 'e', 'c', 't'}}) -> {'O', 'b', 'j', 'e', 'c', 't'}
- * toQualifiedName({{}}) -> {}
- * </code>
- * </pre>
- * </p>
- *
- * @param segments the list of name segments, possibly empty
- * @return the dot-separated qualified name, or the empty string
- *
- *
- */
-public static char[] toQualifiedName(char[][] segments) {
- int length = segments.length;
- if (length == 0) return CharOperation.NO_CHAR;
- if (length == 1) return segments[0];
-
- int resultLength = 0;
- for (int i = 0; i < length; i++) {
- resultLength += segments[i].length+1;
- }
- resultLength--;
- char[] result = new char[resultLength];
- int index = 0;
- for (int i = 0; i < length; i++) {
- char[] segment = segments[i];
- int segmentLength = segment.length;
- System.arraycopy(segment, 0, result, index, segmentLength);
- index += segmentLength;
- if (i != length-1) {
- result[index++] = C_DOT;
- }
- }
- return result;
-}
-/**
- * Converts the given array of qualified name segments to a qualified name.
- * <p>
- * For example:
- * <pre>
- * <code>
- * toQualifiedName(new String[] {"java", "lang", "Object"}) -> "java.lang.Object"
- * toQualifiedName(new String[] {"Object"}) -> "Object"
- * toQualifiedName(new String[0]) -> ""
- * </code>
- * </pre>
- * </p>
- *
- * @param segments the list of name segments, possibly empty
- * @return the dot-separated qualified name, or the empty string
- */
-public static String toQualifiedName(String[] segments) {
- int length = segments.length;
- char[][] charArrays = new char[length][];
- for (int i = 0; i < length; i++) {
- charArrays[i] = segments[i].toCharArray();
- }
- return new String(toQualifiedName(charArrays));
-}
-/**
- * Converts the given type signature to a readable string. The signature is expected to
- * be dot-based.
- *
- * <p>
- * For example:
- * <pre>
- * <code>
- * toString("[Ljava.lang.String;") -> "java.lang.String[]"
- * toString("I") -> "int"
- * toString("+QObject;") -> "? extends Object"
- * </code>
- * </pre>
- * </p>
- * <p>
- * Note: This method assumes that a type signature containing a <code>'$'</code>
- * is an inner type signature. While this is correct in most cases, someone could
- * define a non-inner type name containing a <code>'$'</code>. Handling this
- * correctly in all cases would have required resolving the signature, which
- * generally not feasible.
- * </p>
- *
- * @param signature the type signature
- * @return the string representation of the type
- * @exception IllegalArgumentException if the signature is not syntactically
- * correct
- */
-public static String toString(String signature) throws IllegalArgumentException {
- return new String(toCharArray(signature.toCharArray()));
-}
-/**
- * Converts the given method signature to a readable string. The method signature is expected to
- * be dot-based.
- *
- * @param methodSignature the method signature to convert
- * @param methodName the name of the method to insert in the result, or
- * <code>null</code> if no method name is to be included
- * @param parameterNames the parameter names to insert in the result, or
- * <code>null</code> if no parameter names are to be included; if supplied,
- * the number of parameter names must match that of the method signature
- * @param fullyQualifyTypeNames <code>true</code> if type names should be fully
- * qualified, and <code>false</code> to use only simple names
- * @param includeReturnType <code>true</code> if the return type is to be
- * included
- * @see #toCharArray(char[], char[], char[][], boolean, boolean)
- * @return the string representation of the method signature
- */
-public static String toString(String methodSignature, String methodName, String[] parameterNames, boolean fullyQualifyTypeNames, boolean includeReturnType) {
- return toString(methodSignature, methodName, parameterNames, fullyQualifyTypeNames, includeReturnType, false);
-}
-/**
- * Converts the given method signature to a readable string. The method signature is expected to
- * be dot-based.
- *
- * @param methodSignature the method signature to convert
- * @param methodName the name of the method to insert in the result, or
- * <code>null</code> if no method name is to be included
- * @param parameterNames the parameter names to insert in the result, or
- * <code>null</code> if no parameter names are to be included; if supplied,
- * the number of parameter names must match that of the method signature
- * @param fullyQualifyTypeNames <code>true</code> if type names should be fully
- * qualified, and <code>false</code> to use only simple names
- * @param includeReturnType <code>true</code> if the return type is to be
- * included
- * @param isVarArgs <code>true</code> if the last argument should be displayed as a
- * variable argument, <code>false</code> otherwise
- * @see #toCharArray(char[], char[], char[][], boolean, boolean)
- * @return the string representation of the method signature
- *
- *
- */
-public static String toString(String methodSignature, String methodName, String[] parameterNames, boolean fullyQualifyTypeNames, boolean includeReturnType, boolean isVarArgs) {
- char[][] params;
- if (parameterNames == null) {
- params = null;
- } else {
- int paramLength = parameterNames.length;
- params = new char[paramLength][];
- for (int i = 0; i < paramLength; i++) {
- params[i] = parameterNames[i].toCharArray();
- }
- }
- return new String(toCharArray(methodSignature.toCharArray(), methodName == null ? null : methodName.toCharArray(), params, fullyQualifyTypeNames, includeReturnType, isVarArgs));
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ToolFactory.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ToolFactory.java
deleted file mode 100644
index 07224269..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ToolFactory.java
+++ /dev/null
@@ -1,247 +0,0 @@
-/*******************************************************************************
- * 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;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.wst.jsdt.core.compiler.IScanner;
-import org.eclipse.wst.jsdt.core.formatter.CodeFormatter;
-import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants;
-import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants;
-import org.eclipse.wst.jsdt.internal.compiler.impl.CompilerOptions;
-import org.eclipse.wst.jsdt.internal.core.util.PublicScanner;
-import org.eclipse.wst.jsdt.internal.formatter.DefaultCodeFormatter;
-
-/**
- * Factory for creating various compiler tools, such as scanners, parsers and compilers.
- * <p>
- * This class provides static methods only; it is not intended to be instantiated or subclassed by clients.
- * </p>
- *
- *
- * 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 ToolFactory {
-
- /**
- * This mode is used for formatting new code when some formatter options should not be used.
- * In particular, options that preserve the indentation of comments are not used.
- * In the future, newly added options may be ignored as well.
- * <p>Clients that are formatting new code are recommended to use this mode.
- * </p>
- *
- * @see DefaultCodeFormatterConstants#FORMATTER_NEVER_INDENT_BLOCK_COMMENTS_ON_FIRST_COLUMN
- * @see DefaultCodeFormatterConstants#FORMATTER_NEVER_INDENT_LINE_COMMENTS_ON_FIRST_COLUMN
- * @see #createCodeFormatter(Map, int)
- */
- public static final int M_FORMAT_NEW = new Integer(0).intValue();
-
- /**
- * This mode is used for formatting existing code when all formatter options should be used.
- * In particular, options that preserve the indentation of comments are used.
- * <p>Clients that are formatting existing code are recommended to use this mode.
- * </p>
- *
- * @see DefaultCodeFormatterConstants#FORMATTER_NEVER_INDENT_BLOCK_COMMENTS_ON_FIRST_COLUMN
- * @see DefaultCodeFormatterConstants#FORMATTER_NEVER_INDENT_LINE_COMMENTS_ON_FIRST_COLUMN
- * @see #createCodeFormatter(Map, int)
- */
- public static final int M_FORMAT_EXISTING = new Integer(1).intValue();
-
- /**
- * Create an instance of the built-in code formatter.
- * <p>The given options should at least provide the source level ({@link JavaScriptCore#COMPILER_SOURCE}),
- * the compiler compliance level ({@link JavaScriptCore#COMPILER_COMPLIANCE}) and the target platform
- * ({@link JavaScriptCore#COMPILER_CODEGEN_TARGET_PLATFORM}).
- * Without these options, it is not possible for the code formatter to know what kind of source it needs to format.
- * </p><p>
- * Note this is equivalent to <code>createCodeFormatter(options, M_FORMAT_NEW)</code>. Thus some code formatter options
- * may be ignored. See @{link {@link #M_FORMAT_NEW} for more details.
- * </p>
- * @param options - the options map to use for formatting with the default code formatter. Recognized options
- * are documented on <code>JavaScriptCore#getDefaultOptions()</code>. If set to <code>null</code>, then use
- * the current settings from <code>JavaScriptCore#getOptions</code>.
- * @return an instance of the built-in code formatter
- * @see CodeFormatter
- * @see JavaScriptCore#getOptions()
- */
- public static CodeFormatter createCodeFormatter(Map options){
- return createCodeFormatter(options, M_FORMAT_NEW);
- }
-
- /**
- * Create an instance of the built-in code formatter.
- * <p>The given options should at least provide the source level ({@link JavaScriptCore#COMPILER_SOURCE}),
- * the compiler compliance level ({@link JavaScriptCore#COMPILER_COMPLIANCE}) and the target platform
- * ({@link JavaScriptCore#COMPILER_CODEGEN_TARGET_PLATFORM}).
- * Without these options, it is not possible for the code formatter to know what kind of source it needs to format.
- * </p>
- * <p>The given mode determines what options should be enabled when formatting the code. It can have the following
- * values: {@link #M_FORMAT_NEW}, {@link #M_FORMAT_EXISTING}, but other values may be added in the future.
- * </p>
- *
- * @param options the options map to use for formatting with the default code formatter. Recognized options
- * are documented on <code>JavaScriptCore#getDefaultOptions()</code>. If set to <code>null</code>, then use
- * the current settings from <code>JavaScriptCore#getOptions</code>.
- * @param mode the given mode to modify the given options.
- *
- * @return an instance of the built-in code formatter
- * @see CodeFormatter
- * @see JavaScriptCore#getOptions()
- */
- public static CodeFormatter createCodeFormatter(Map options, int mode) {
- if (options == null) options = JavaScriptCore.getOptions();
- Map currentOptions = new HashMap(options);
- if (mode == M_FORMAT_NEW) {
- // disable the option for not indenting comments starting on first column
- currentOptions.put(DefaultCodeFormatterConstants.FORMATTER_NEVER_INDENT_BLOCK_COMMENTS_ON_FIRST_COLUMN, DefaultCodeFormatterConstants.FALSE);
- currentOptions.put(DefaultCodeFormatterConstants.FORMATTER_NEVER_INDENT_LINE_COMMENTS_ON_FIRST_COLUMN, DefaultCodeFormatterConstants.FALSE);
- }
- return new DefaultCodeFormatter(currentOptions);
- }
-
-
-
-
-
- /**
- * Create a scanner, indicating the level of detail requested for tokenizing. The scanner can then be
- * used to tokenize some source in a JavaScript aware way.
- * Here is a typical scanning loop:
- *
- * <code>
- * <pre>
- * IScanner scanner = ToolFactory.createScanner(false, false, false, false);
- * scanner.setSource("int i = 0;".toCharArray());
- * while (true) {
- * int token = scanner.getNextToken();
- * if (token == ITerminalSymbols.TokenNameEOF) break;
- * System.out.println(token + " : " + new String(scanner.getCurrentTokenSource()));
- * }
- * </pre>
- * </code>
- *
- * <p>
- * The returned scanner will tolerate unterminated line comments (missing line separator). It can be made stricter
- * by using API with extra boolean parameter (<code>strictCommentMode</code>).
- * <p>
- * @param tokenizeComments if set to <code>false</code>, comments will be silently consumed
- * @param tokenizeWhiteSpace if set to <code>false</code>, white spaces will be silently consumed,
- * @param assertMode if set to <code>false</code>, occurrences of 'assert' will be reported as identifiers
- * (<code>ITerminalSymbols#TokenNameIdentifier</code>), whereas if set to <code>true</code>, it
- * would report assert keywords (<code>ITerminalSymbols#TokenNameassert</code>).
- * @param recordLineSeparator if set to <code>true</code>, the scanner will record positions of encountered line
- * separator ends. In case of multi-character line separators, the last character position is considered. These positions
- * can then be extracted using <code>IScanner#getLineEnds</code>. Only non-unicode escape sequences are
- * considered as valid line separators.
- * @return a scanner
- * @see org.eclipse.wst.jsdt.core.compiler.IScanner
- */
- public static IScanner createScanner(boolean tokenizeComments, boolean tokenizeWhiteSpace, boolean assertMode, boolean recordLineSeparator){
-
- PublicScanner scanner = new PublicScanner(tokenizeComments, tokenizeWhiteSpace, false/*nls*/, assertMode ? ClassFileConstants.JDK1_4 : ClassFileConstants.JDK1_3/*sourceLevel*/, null/*taskTags*/, null/*taskPriorities*/, true/*taskCaseSensitive*/);
- scanner.recordLineSeparator = recordLineSeparator;
- return scanner;
- }
-
- /**
- * Create a scanner, indicating the level of detail requested for tokenizing. The scanner can then be
- * used to tokenize some source in a JavaScript aware way.
- * Here is a typical scanning loop:
- *
- * <code>
- * <pre>
- * IScanner scanner = ToolFactory.createScanner(false, false, false, false);
- * scanner.setSource("int i = 0;".toCharArray());
- * while (true) {
- * int token = scanner.getNextToken();
- * if (token == ITerminalSymbols.TokenNameEOF) break;
- * System.out.println(token + " : " + new String(scanner.getCurrentTokenSource()));
- * }
- * </pre>
- * </code>
- *
- * <p>
- * The returned scanner will tolerate unterminated line comments (missing line separator). It can be made stricter
- * by using API with extra boolean parameter (<code>strictCommentMode</code>).
- * <p>
- * @param tokenizeComments if set to <code>false</code>, comments will be silently consumed
- * @param tokenizeWhiteSpace if set to <code>false</code>, white spaces will be silently consumed,
- * @param recordLineSeparator if set to <code>true</code>, the scanner will record positions of encountered line
- * separator ends. In case of multi-character line separators, the last character position is considered. These positions
- * can then be extracted using <code>IScanner#getLineEnds</code>. Only non-unicode escape sequences are
- * considered as valid line separators.
- * @param sourceLevel if set to <code>&quot;1.3&quot;</code> or <code>null</code>, occurrences of 'assert' will be reported as identifiers
- * (<code>ITerminalSymbols#TokenNameIdentifier</code>), whereas if set to <code>&quot;1.4&quot;</code>, it
- * would report assert keywords (<code>ITerminalSymbols#TokenNameassert</code>).
- * @return a scanner
- * @see org.eclipse.wst.jsdt.core.compiler.IScanner
- */
- public static IScanner createScanner(boolean tokenizeComments, boolean tokenizeWhiteSpace, boolean recordLineSeparator, String sourceLevel) {
- PublicScanner scanner = null;
- long level = CompilerOptions.versionToJdkLevel(sourceLevel);
- if (level == 0) level = ClassFileConstants.JDK1_3; // fault-tolerance
- scanner = new PublicScanner(tokenizeComments, tokenizeWhiteSpace, false/*nls*/,level /*sourceLevel*/, null/*taskTags*/, null/*taskPriorities*/, true/*taskCaseSensitive*/);
- scanner.recordLineSeparator = recordLineSeparator;
- return scanner;
- }
-
- /**
- * Create a scanner, indicating the level of detail requested for tokenizing. The scanner can then be
- * used to tokenize some source in a JavaScript aware way.
- * Here is a typical scanning loop:
- *
- * <code>
- * <pre>
- * IScanner scanner = ToolFactory.createScanner(false, false, false, false);
- * scanner.setSource("int i = 0;".toCharArray());
- * while (true) {
- * int token = scanner.getNextToken();
- * if (token == ITerminalSymbols.TokenNameEOF) break;
- * System.out.println(token + " : " + new String(scanner.getCurrentTokenSource()));
- * }
- * </pre>
- * </code>
- *
- * <p>
- * The returned scanner will tolerate unterminated line comments (missing line separator). It can be made stricter
- * by using API with extra boolean parameter (<code>strictCommentMode</code>).
- * <p>
- * @param tokenizeComments if set to <code>false</code>, comments will be silently consumed
- * @param tokenizeWhiteSpace if set to <code>false</code>, white spaces will be silently consumed,
- * @param recordLineSeparator if set to <code>true</code>, the scanner will record positions of encountered line
- * separator ends. In case of multi-character line separators, the last character position is considered. These positions
- * can then be extracted using <code>IScanner#getLineEnds</code>. Only non-unicode escape sequences are
- * considered as valid line separators.
- * @param sourceLevel if set to <code>&quot;1.3&quot;</code> or <code>null</code>, occurrences of 'assert' will be reported as identifiers
- * (<code>ITerminalSymbols#TokenNameIdentifier</code>), whereas if set to <code>&quot;1.4&quot;</code>, it
- * would report assert keywords (<code>ITerminalSymbols#TokenNameassert</code>).
- * @param complianceLevel This is used to support the Unicode 4.0 character sets. if set to 1.5 or above,
- * the Unicode 4.0 is supporte, otherwise Unicode 3.0 is supported.
- * @return a scanner
- * @see org.eclipse.wst.jsdt.core.compiler.IScanner
- *
- */
- public static IScanner createScanner(boolean tokenizeComments, boolean tokenizeWhiteSpace, boolean recordLineSeparator, String sourceLevel, String complianceLevel) {
- PublicScanner scanner = null;
- long sourceLevelValue = CompilerOptions.versionToJdkLevel(sourceLevel);
- if (sourceLevelValue == 0) sourceLevelValue = ClassFileConstants.JDK1_3; // fault-tolerance
- long complianceLevelValue = CompilerOptions.versionToJdkLevel(complianceLevel);
- if (complianceLevelValue == 0) complianceLevelValue = ClassFileConstants.JDK1_3; // fault-tolerance
- scanner = new PublicScanner(tokenizeComments, tokenizeWhiteSpace, false/*nls*/,sourceLevelValue /*sourceLevel*/, complianceLevelValue, null/*taskTags*/, null/*taskPriorities*/, true/*taskCaseSensitive*/);
- scanner.recordLineSeparator = recordLineSeparator;
- return scanner;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/UnimplementedException.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/UnimplementedException.java
deleted file mode 100644
index e56246dd..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/UnimplementedException.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core;
-
-public class UnimplementedException extends RuntimeException {
-
- /**
- *
- */
- private static final long serialVersionUID = 1L;
-
- public UnimplementedException() {
- super();
- }
-
- public UnimplementedException(String arg0) {
- super(arg0);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/WorkingCopyOwner.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/WorkingCopyOwner.java
deleted file mode 100644
index c1c6202d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/WorkingCopyOwner.java
+++ /dev/null
@@ -1,141 +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.core;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.wst.jsdt.internal.core.BufferManager;
-import org.eclipse.wst.jsdt.internal.core.CompilationUnit;
-import org.eclipse.wst.jsdt.internal.core.DefaultWorkingCopyOwner;
-import org.eclipse.wst.jsdt.internal.core.ExternalJavaProject;
-import org.eclipse.wst.jsdt.internal.core.PackageFragment;
-
-/**
- * The owner of an {@link IJavaScriptUnit} handle in working copy mode.
- * An owner is used to identify a working copy and to create its buffer.
- * <p>
- * Clients should subclass this class to instantiate a working copy owner that is specific to their need and that
- * they can pass in to various APIs (e.g. {@link IType#resolveType(String, WorkingCopyOwner)}.
- * Clients can also override the default implementation of {@link #createBuffer(IJavaScriptUnit)}.
- * </p><p>
- * Note: even though this class has no abstract method, which means that it provides functional default behavior,
- * it is still an abstract class, as clients are intended to own their owner implementation.
- * </p>
- * @see IJavaScriptUnit#becomeWorkingCopy(org.eclipse.core.runtime.IProgressMonitor)
- * @see IJavaScriptUnit#discardWorkingCopy()
- * @see IJavaScriptUnit#getWorkingCopy(org.eclipse.core.runtime.IProgressMonitor)
- *
- * 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 WorkingCopyOwner {
-
- /**
- * Sets the buffer provider of the primary working copy owner. Note that even if the
- * buffer provider is a working copy owner, only its <code>createBuffer(IJavaScriptUnit)</code>
- * method is used by the primary working copy owner. It doesn't replace the internal primary
- * working owner.
- * <p>
- * This method is for internal use by the jsdt-related plug-ins.
- * Clients outside of the jsdt should not reference this method.
- * </p>
- *
- * @param primaryBufferProvider the primary buffer provider
- */
- public static void setPrimaryBufferProvider(WorkingCopyOwner primaryBufferProvider) {
- DefaultWorkingCopyOwner.PRIMARY.primaryBufferProvider = primaryBufferProvider;
- }
-
- /**
- * Creates a buffer for the given working copy.
- * The new buffer will be initialized with the contents of the underlying file
- * if and only if it was not already initialized by the compilation owner (a buffer is
- * uninitialized if its content is <code>null</code>).
- * <p>
- * Note: This buffer will be associated to the working copy for its entire life-cycle. Another
- * working copy on same unit but owned by a different owner would not share the same buffer
- * unless its owner decided to implement such a sharing behaviour.
- * </p>
- *
- * @param workingCopy the working copy of the buffer
- * @return IBuffer the created buffer for the given working copy
- * @see IBuffer
- */
- public IBuffer createBuffer(IJavaScriptUnit workingCopy) {
-
- return BufferManager.createBuffer(workingCopy);
- }
-
- /**
- * Returns the problem requestor used by a working copy of this working copy owner.
- * <p>
- * By default, no problem requestor is configured. Clients can override this
- * method to provide a requestor.
- * </p>
- *
- * @param workingCopy The problem requestor used for the given working copy.
- * @return the problem requestor to be used by working copies of this working
- * copy owner or <code>null</code> if no problem requestor is configured.
- *
- */
- public IProblemRequestor getProblemRequestor(IJavaScriptUnit workingCopy) {
- return null;
- }
-
- /**
- * Returns a new working copy with the given name using this working copy owner to
- * create its buffer.
- * <p>
- * This working copy always belongs to the default package in a package
- * fragment root that corresponds to its JavaScript project, and this JavaScript project never exists.
- * However this JavaScript project has the given includepath that is used when resolving names
- * in this working copy.
- * </p><p>
- * If a DOM AST is created using this working copy, then given includepath will be used
- * if bindings need to be resolved. Problems will be reported to the problem requestor
- * of the current working copy owner problem if it is not <code>null</code>.
- * <p></p>
- * Options used to create the DOM AST are got from {@link JavaScriptCore#getOptions()}
- * as it is not possible to set the options on a non-existing JavaScript project.
- * </p><p>
- * When the working copy instance is created, an {@link IJavaScriptElementDelta#ADDED added delta} is
- * reported on this working copy.
- * </p><p>
- * Once done with the working copy, users of this method must discard it using
- * {@link IJavaScriptUnit#discardWorkingCopy()}.
- * </p><p>
- * Note that when such working copy is committed, only its buffer is saved (see
- * {@link IBuffer#save(IProgressMonitor, boolean)}) but no resource is created.
- * </p><p>
- * This method is not intended to be overriden by clients.
- * </p>
- *
- * @param name the name of the working copy (e.g. "X.js")
- * @param classpath the includepath used to resolve names in this working copy
- * @param monitor a progress monitor used to report progress while opening the working copy
- * or <code>null</code> if no progress should be reported
- * @throws JavaScriptModelException if the contents of this working copy can
- * not be determined.
- * @return a new working copy
- * @see IJavaScriptUnit#becomeWorkingCopy(IProgressMonitor)
- *
- */
- public final IJavaScriptUnit newWorkingCopy(String name, IIncludePathEntry[] classpath, IProgressMonitor monitor) throws JavaScriptModelException {
- ExternalJavaProject project = new ExternalJavaProject(classpath);
- IPackageFragment parent = project.getPackageFragmentRoot(Path.EMPTY).getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME);
- CompilationUnit result = new CompilationUnit((PackageFragment) parent, name, this);
- result.becomeWorkingCopy(getProblemRequestor(result), monitor);
- return result;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ASTVisitor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ASTVisitor.java
deleted file mode 100644
index 4a808bfd..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ASTVisitor.java
+++ /dev/null
@@ -1,563 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.ast;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.core.infer.InferredAttribute;
-import org.eclipse.wst.jsdt.core.infer.InferredMethod;
-import org.eclipse.wst.jsdt.core.infer.InferredType;
-
-
-/**
- *
- * A visitor for iterating through the AST Node tree.
- *
- * 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 ASTVisitor {
-
-
- public void acceptProblem(IProblem problem) {
- // do nothing by default
- }
- public void endVisit( IAllocationExpression allocationExpression) {
- // do nothing by default
- }
- public void endVisit(IAND_AND_Expression and_and_Expression) {
- // do nothing by default
- }
- public void endVisit(IArgument argument) {
- // do nothing by default
- }
-
- public void endVisit( IArrayAllocationExpression arrayAllocationExpression) {
- // do nothing by default
- }
- public void endVisit(IArrayInitializer arrayInitializer) {
- // do nothing by default
- }
- public void endVisit(IArrayQualifiedTypeReference arrayQualifiedTypeReference) {
- // do nothing by default
- }
- public void endVisit(IArrayReference arrayReference) {
- // do nothing by default
- }
- public void endVisit(IArrayTypeReference arrayTypeReference) {
- // do nothing by default
- }
- public void endVisit(IAssignment assignment) {
- // do nothing by default
- }
- public void endVisit(IBinaryExpression binaryExpression) {
- // do nothing by default
- }
- public void endVisit(IBlock block) {
- // do nothing by default
- }
- public void endVisit(IBreakStatement breakStatement) {
- // do nothing by default
- }
- public void endVisit(ICaseStatement caseStatement) {
- // do nothing by default
- }
- public void endVisit(IScriptFileDeclaration scriptFileDeclaration) {
- // do nothing by default
- }
- public void endVisit(ICompoundAssignment compoundAssignment) {
- // do nothing by default
- }
- public void endVisit(IConditionalExpression conditionalExpression) {
- // do nothing by default
- }
- public void endVisit(IConstructorDeclaration constructorDeclaration) {
- // do nothing by default
- }
- public void endVisit(IContinueStatement continueStatement) {
- // do nothing by default
- }
- public void endVisit(IDoStatement doStatement) {
- // do nothing by default
- }
- public void endVisit(IDoubleLiteral doubleLiteral) {
- // do nothing by default
- }
- public void endVisit(IEmptyStatement emptyStatement) {
- // do nothing by default
- }
- public void endVisit(IEqualExpression equalExpression) {
- // do nothing by default
- }
- public void endVisit(IExplicitConstructorCall explicitConstructor) {
- // do nothing by default
- }
- public void endVisit(IExtendedStringLiteral extendedStringLiteral) {
- // do nothing by default
- }
- public void endVisit(IFalseLiteral falseLiteral) {
- // do nothing by default
- }
- public void endVisit(IFieldDeclaration fieldDeclaration) {
- // do nothing by default
- }
-
- public void endVisit(IFieldReference fieldDeclaration) {
- // do nothing by default
- }
-
- public void endVisit(IForeachStatement forStatement) {
- // do nothing by default
- }
- public void endVisit(IForStatement forStatement) {
- // do nothing by default
- }
- public void endVisit(IForInStatement forInStatement) {
- // do nothing by default
- }
-
- public void endVisit(IFunctionExpression functionExpression) {
- }
-
- public void endVisit(IIfStatement ifStatement) {
- // do nothing by default
- }
- public void endVisit(IImportReference importRef) {
- // do nothing by default
- }
- public void endVisit(InferredType inferredType) {
- // do nothing by default
- }
-
- public void endVisit(IInitializer initializer) {
- // do nothing by default
- }
- public void endVisit(IInstanceOfExpression instanceOfExpression) {
- // do nothing by default
- }
- public void endVisit(IIntLiteral intLiteral) {
- // do nothing by default
- }
- public void endVisit(IJsDoc javadoc) {
- // do nothing by default
- }
- public void endVisit(IJsDocAllocationExpression expression) {
- // do nothing by default
- }
- public void endVisit(IJsDocArgumentExpression expression) {
- // do nothing by default
- }
- public void endVisit(IJsDocArrayQualifiedTypeReference typeRef) {
- // do nothing by default
- }
- public void endVisit(IJsDocArraySingleTypeReference typeRef) {
- // do nothing by default
- }
- public void endVisit(IJsDocFieldReference fieldRef) {
- // do nothing by default
- }
- public void endVisit(IJsDocImplicitTypeReference implicitTypeReference) {
- // do nothing by default
- }
- public void endVisit(IJsDocMessageSend messageSend) {
- // do nothing by default
- }
- public void endVisit(IJsDocQualifiedTypeReference typeRef) {
- // do nothing by default
- }
- public void endVisit(IJsDocReturnStatement statement) {
- // do nothing by default
- }
- public void endVisit(IJsDocSingleNameReference argument) {
- // do nothing by default
- }
- public void endVisit(IJsDocSingleTypeReference typeRef) {
- // do nothing by default
- }
- public void endVisit(ILabeledStatement labeledStatement) {
- // do nothing by default
- }
- public void endVisit(ILocalDeclaration localDeclaration) {
- // do nothing by default
- }
- public void endVisit(IListExpression listDeclaration) {
- // do nothing by default
- }
- public void endVisit(IFunctionCall messageSend) {
- // do nothing by default
- }
- public void endVisit(IFunctionDeclaration methodDeclaration) {
- // do nothing by default
- }
- public void endVisit(IStringLiteralConcatenation literal) {
- // do nothing by default
- }
- public void endVisit(INullLiteral nullLiteral) {
- // do nothing by default
- }
- public void endVisit(IOR_OR_Expression or_or_Expression) {
- // do nothing by default
- }
- public void endVisit(IPostfixExpression postfixExpression) {
- // do nothing by default
- }
- public void endVisit(IPrefixExpression prefixExpression) {
- // do nothing by default
- }
- public void endVisit(IQualifiedAllocationExpression qualifiedAllocationExpression) {
- // do nothing by default
- }
- public void endVisit(IQualifiedNameReference qualifiedNameReference) {
- // do nothing by default
- }
- public void endVisit(IQualifiedThisReference qualifiedThisReference) {
- // do nothing by default
- }
- public void endVisit(IQualifiedTypeReference qualifiedTypeReference) {
- // do nothing by default
- }
-
- public void endVisit(IRegExLiteral stringLiteral) {
- // do nothing by default
- }
-
-
- public void endVisit(IReturnStatement returnStatement) {
- // do nothing by default
- }
- public void endVisit(ISingleNameReference singleNameReference) {
- // do nothing by default
- }
-
- public void endVisit(ISingleTypeReference singleTypeReference) {
- // do nothing by default
- }
- public void endVisit(IStringLiteral stringLiteral) {
- // do nothing by default
- }
- public void endVisit(ISuperReference superReference) {
- // do nothing by default
- }
- public void endVisit(ISwitchStatement switchStatement) {
- // do nothing by default
- }
-
- public void endVisit(IThisReference thisReference) {
- // do nothing by default
- }
- public void endVisit(IThrowStatement throwStatement) {
- // do nothing by default
- }
- public void endVisit(ITrueLiteral trueLiteral) {
- // do nothing by default
- }
- public void endVisit(ITryStatement tryStatement) {
- // do nothing by default
- }
- public void endVisit(ITypeDeclaration memberTypeDeclaration) {
- // do nothing by default
- }
- public void endVisit(IUnaryExpression unaryExpression) {
- // do nothing by default
- }
- public void endVisit(IUndefinedLiteral undefinedLiteral) {
- // do nothing by default
- }
-
- public void endVisit(IWhileStatement whileStatement) {
- // do nothing by default
- }
- public void endVisit(IWithStatement whileStatement) {
- // do nothing by default
- }
- public boolean visit(IAllocationExpression allocationExpression) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IAND_AND_Expression and_and_Expression) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IArgument argument) {
- return true; // do nothing by default, keep traversing
- }
-
- public boolean visit(IArrayAllocationExpression arrayAllocationExpression) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IArrayInitializer arrayInitializer) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IArrayQualifiedTypeReference arrayQualifiedTypeReference) {
- return true; // do nothing by default, keep traversing
- }
-
- public boolean visit(IArrayReference arrayReference) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IArrayTypeReference arrayTypeReference) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IAssignment assignment) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IBinaryExpression binaryExpression) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IBlock block) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IBreakStatement breakStatement) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(ICaseStatement caseStatement) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IScriptFileDeclaration compilationUnitDeclaration) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(ICompoundAssignment compoundAssignment) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IConditionalExpression conditionalExpression) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IConstructorDeclaration constructorDeclaration) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IContinueStatement continueStatement) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IDoStatement doStatement) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IDoubleLiteral doubleLiteral) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IEmptyStatement emptyStatement) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IEqualExpression equalExpression) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IExplicitConstructorCall explicitConstructor) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IExtendedStringLiteral extendedStringLiteral) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IFalseLiteral falseLiteral) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IFieldDeclaration fieldDeclaration) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IFieldReference fieldReference) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IForeachStatement forStatement) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IForInStatement forInStatement) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IForStatement forStatement) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IFunctionExpression functionExpression) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IIfStatement ifStatement) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IImportReference importRef) {
- return true; // do nothing by default, keep traversing
- }
-
- public boolean visit(InferredType inferredType) {
- return true; // do nothing by default, keep traversing
- }
-
- public boolean visit(InferredMethod inferredMethod) {
- return true; // do nothing by default, keep traversing
- }
-
- public boolean visit(InferredAttribute inferredField) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IInitializer initializer) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IInstanceOfExpression instanceOfExpression) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IIntLiteral intLiteral) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IJsDoc javadoc) {
- return true; // do nothing by default, keep traversing
- }
-
- public boolean visit(IJsDocAllocationExpression expression) {
- return true; // do nothing by default, keep traversing
- }
-
- public boolean visit(IJsDocArgumentExpression expression) {
- return true; // do nothing by default, keep traversing
- }
-
- public boolean visit(IJsDocArrayQualifiedTypeReference typeRef) {
- return true; // do nothing by default, keep traversing
- }
-
- public boolean visit(IJsDocArraySingleTypeReference typeRef) {
- return true; // do nothing by default, keep traversing
- }
-
- public boolean visit(IJsDocFieldReference fieldRef) {
- return true; // do nothing by default, keep traversing
- }
-
- public boolean visit(IJsDocImplicitTypeReference implicitTypeReference) {
- return true; // do nothing by default, keep traversing
- }
-
- public boolean visit(IJsDocMessageSend messageSend) {
- return true; // do nothing by default, keep traversing
- }
-
- public boolean visit(IJsDocQualifiedTypeReference typeRef) {
- return true; // do nothing by default, keep traversing
- }
-
- public boolean visit(IJsDocReturnStatement statement) {
- return true; // do nothing by default, keep traversing
- }
-
- public boolean visit(IJsDocSingleNameReference argument) {
- return true; // do nothing by default, keep traversing
- }
-
- public boolean visit(IJsDocSingleTypeReference typeRef) {
- return true; // do nothing by default, keep traversing
- }
-
- public boolean visit(ILabeledStatement labeledStatement) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(ILocalDeclaration localDeclaration) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IListExpression listDeclaration) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IFunctionCall functionCall) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IFunctionDeclaration functionDeclaration) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IStringLiteralConcatenation literal) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(INullLiteral nullLiteral) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IOR_OR_Expression or_or_Expression) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IPostfixExpression postfixExpression) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IPrefixExpression prefixExpression) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IQualifiedAllocationExpression qualifiedAllocationExpression) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IQualifiedNameReference qualifiedNameReference) {
- return true; // do nothing by default, keep traversing
- }
-
- public boolean visit(IQualifiedThisReference qualifiedThisReference) {
- return true; // do nothing by default, keep traversing
- }
-
- public boolean visit(IQualifiedTypeReference qualifiedTypeReference) {
- return true; // do nothing by default, keep traversing
- }
-
- public boolean visit(IRegExLiteral stringLiteral) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IReturnStatement returnStatement) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(ISingleNameReference singleNameReference) {
- return true; // do nothing by default, keep traversing
- }
-
- public boolean visit(ISingleTypeReference singleTypeReference) {
- return true; // do nothing by default, keep traversing
- }
-
- public boolean visit(IStringLiteral stringLiteral) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(ISuperReference superReference) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(ISwitchStatement switchStatement) {
- return true; // do nothing by default, keep traversing
- }
-
- public boolean visit(IThisReference thisReference) {
- return true; // do nothing by default, keep traversing
- }
-
- public boolean visit(IThrowStatement throwStatement) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(ITrueLiteral trueLiteral) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(ITryStatement tryStatement) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(ITypeDeclaration localTypeDeclaration) {
- return true; // do nothing by default, keep traversing
- }
-
- public boolean visit(IUnaryExpression unaryExpression) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IUndefinedLiteral undefined) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IWhileStatement whileStatement) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IWithStatement whileStatement) {
- return true; // do nothing by default, keep traversing
- }
-
- public boolean visit(IObjectLiteral literal) {
- return true; // do nothing by default, keep traversing
- }
- public void endVisit(IObjectLiteral literal) {
- }
- public boolean visit(IObjectLiteralField field) {
- return true; // do nothing by default, keep traversing
- }
- public void endVisit(IObjectLiteralField field) {
- }
-
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IAND_AND_Expression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IAND_AND_Expression.java
deleted file mode 100644
index 3b64692f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IAND_AND_Expression.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-
-/**
- * Representation of a && expression
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
-* 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 IAND_AND_Expression extends IBinaryExpression{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IASTNode.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IASTNode.java
deleted file mode 100644
index be19c17c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IASTNode.java
+++ /dev/null
@@ -1,145 +0,0 @@
-/*******************************************************************************
- * 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.ast;
-
-/**
- * Abstract base class for AST nodes.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IASTNode {
-
-
- //public static final int AST_FUNCTION = 1;
- //public static final int AST_ABSTRACT_METHOD_DECLARATION = 0;
- public static final int AST_NODE=0;
- public static final int ABSTRACT_FUNCTION_DECLARATION=1;
- public static final int ABSTRACT_VARIABLE_DECLARATION=2;
- public static final int ALLOCATION_EXPRESSION=3;
- public static final int AND_AND_EXPRESSION=4;
- public static final int ARGUMENT=7;
- public static final int ARRAY_ALLOCATION_EXPRESSION=8;
- public static final int ARRAY_INITIALIZER=9;
- public static final int ARRAY_QUALIFIED_TYPE_REFERENCE=10;
- public static final int ARRAY_REFERENCE=11;
- public static final int ARRAY_TYPE_REFERENCE=12;
- public static final int ASSIGNMENT=14;
- public static final int BINARY_EXPRESSION=15;
- public static final int BLOCK=16;
- public static final int BRANCH_STATEMENT=17;
- public static final int BREAK_STATEMENT=18;
- public static final int CASE_STATEMENT=19;
- public static final int CHAR_LITERAL=21;
- public static final int COMBINED_BINARY_EXPRESSION=22;
- public static final int COMPOUND_ASSIGNMENT=23;
- public static final int CONDITIONAL_EXPRESSION=24;
- public static final int CONSTRUCTOR_DECLARATION=25;
- public static final int CONTINUE_STATEMENT=26;
- public static final int DO_STATEMENT=27;
- public static final int DOUBLE_LITERAL=28;
- public static final int EMPTY_EXPRESSION=29;
- public static final int EMPTY_STATEMENT=30;
- public static final int EQUAL_EXPRESSION=31;
- public static final int EXPLICIT_CONSTRUCTOR_CALL=32;
- public static final int EXPRESSION=33;
- public static final int EXTENDED_STRING_LITERAL=34;
- public static final int FALSE_LITERAL=35;
- public static final int FIELD_DECLARATION=36;
- public static final int FIELD_REFERENCE=37;
- public static final int FLOAT_LITERAL=38;
- public static final int FOR_EACH_STATEMENT=39;
- public static final int FOR_IN_STATEMENT=40;
- public static final int FOR_STATEMENT=41;
- public static final int FUNCTION_CALL=42;
- public static final int FUNCTION_DECLARATION=43;
- public static final int FUNCTION_EXPRESSION=44;
- public static final int IF_STATEMENT=45;
- public static final int IMPORT_REFERENCE=46;
- public static final int INITIALIZER=47;
- public static final int INSTANCEOF_EXPRESSION=48;
- public static final int INT_LITERAL=49;
- public static final int INT_LITERAL_MIN_VALUE=50;
- public static final int JSDOC=51;
- public static final int JSDOC_ALLOCATION_EXPRESSION=52;
- public static final int JSDOC_ARGUMENTEXPRESSION=53;
- public static final int JSDOC_ARRAY_QUALIFIED_TYPE_REFERENCE=54;
- public static final int JSDOC_ARRAY_SINGLE_TYPE_REFERENCE=55;
- public static final int JSDOC_FIELD_REFERENCE=56;
- public static final int JSDOC_IMPLICIT_TYPE_REFERENCE=57;
- public static final int JSDOC_MESSAGE_SEND=58;
- public static final int JSDOC_QUALIFIED_TYPE_REFERENCE=59;
- public static final int JSDOC_RETURN_STATEMENT=60;
- public static final int JSDOC_SINGLE_NAME_REFERENCE=61;
- public static final int JSDOC_SINGLE_TYPE_REFERENCE=62;
- public static final int LABELED_STATEMENT=63;
- public static final int LIST_EXPRESSION=64;
- public static final int LITERAL=65;
- public static final int LOCAL_DECLARATION=66;
- public static final int LONG_LITERAL=67;
- public static final int LONG_LITERAL_MIN_VALUE=68;
- public static final int MAGIC_LITERAL=69;
- public static final int NAME_REFERENCE=72;
- public static final int NULL_LITERAL=74;
- public static final int NUMBER_LITERAL=75;
- public static final int OBJECT_LITERAL=76;
- public static final int OBJECT_LITERAL_FIELD=77;
- public static final int OPERATOR_EXPRESSION=78;
- public static final int OR_OR_EXPRESSION=79;
- public static final int PARAMETERIZED_QUALIFIED_TYPE_REFERENCE=80;
- public static final int PARAMETERIZED_SINGLE_TYPE_REFERENCE=81;
- public static final int POSTFIX_EXPRESSION=82;
- public static final int PREFIX_EXPRESSION=83;
- public static final int PROGRAM_ELEMENT=84;
- public static final int QUALIFIED_ALLOCATION_EXPRESSION=85;
- public static final int QUALIFIED_NAME_REFERENCE=86;
- public static final int QUALIFIED_SUPER_REFERENCE=87;
- public static final int QUALIFIED_THIS_REFERENCE=88;
- public static final int QUALIFIED_TYPE_REFERENCE=89;
- public static final int REFERENCE=90;
- public static final int REG_EX_LITERAL=91;
- public static final int RETURN_STATEMENT=92;
- public static final int SCRIPT_FILE_DECLARATION=93;
- public static final int SINGLE_NAME_REFERENCE=95;
- public static final int SINGLE_TYPE_REFERENCE=96;
- public static final int STATEMENT=97;
- public static final int STRING_LITERAL=98;
- public static final int STRING_LITERAL_CONCATENATION=99;
- public static final int SUB_ROUTINE_STATEMENT=100;
- public static final int SUPER_REFERENCE=101;
- public static final int SWITCH_STATEMENT=102;
- public static final int THIS_REFERENCE=103;
- public static final int THROW_STATEMENT=104;
- public static final int TRUE_LITERAL=105;
- public static final int TRY_STATEMENT=106;
- public static final int TYPE_DECLARATION=107;
- public static final int TYPE_PARAMETER=108;
- public static final int TYPE_REFERENCE=109;
- public static final int UNARY_EXPRESSION=110;
- public static final int UNDEFINED_LITERAL=111;
- public static final int WHILE_STATEMENT=112;
- public static final int WITH_STATEMENT=114;
- public static final int CLASS_LITERAL_ACCESS=115;
- public static final int CL_INIT=116;
- public static final int OBJECT_GETTER_SETTER_FIELD=117;
- public int sourceStart() ;
- public int sourceEnd();
- public int getASTType();
-
- public void traverse(ASTVisitor visitor);
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IAbstractFunctionDeclaration.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IAbstractFunctionDeclaration.java
deleted file mode 100644
index eb3cc2a4..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IAbstractFunctionDeclaration.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-import org.eclipse.wst.jsdt.core.infer.InferredMethod;
-import org.eclipse.wst.jsdt.core.infer.InferredType;
-
-/**
- * Abstract representation of a Function declaration.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IAbstractFunctionDeclaration extends IStatement{
-
- /**
- * Set the function arguments
- * @param args IArgument[]
- */
- public void setArguments( IArgument[] args);
-
- /**
- * Get the function arguments
- * @return arguments
- */
- public IArgument[] getArguments();
-
- /**
- * Get the function jsdoc
- * @return jsdoc
- */
- IJsDoc getJsDoc();
-
- /**
- * Get the function statements
- * @return statements
- */
- IProgramElement[] getStatements();
-
- /**
- * Get the function name
- *
- * @return name
- */
- char[] getName();
-
- /**
- * Set the inferred return type
- *
- * @param inferred return type
- */
- void setInferredType(InferredType type);
-
- /**
- * Get the inferred return type for the function
- * @return inferred type
- */
- InferredType getInferredType();
-
- /**
- * Get the Inferred method associated with this function
- * @return
- */
- InferredMethod getInferredMethod();
-} \ No newline at end of file
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
deleted file mode 100644
index f9ec3756..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IAbstractVariableDeclaration.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-import org.eclipse.wst.jsdt.core.infer.InferredType;
-/**
- * Abstract representation of a var.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IAbstractVariableDeclaration extends IStatement{
- /**
- * Set the inferred type of the var
- * @param inferred type
- */
- public void setInferredType(InferredType type);
- /**
- * Get the inferred type of the var
- * @return inferred type
- */
- public InferredType getInferredType();
- /**
- * get the var name
- * @return name
- */
- public char[] getName();
- /**
- * Get the initialization expression of the var
- * @return initialization expression
- */
- public IExpression getInitialization();
- /**
- * get the JSDoc for the var
- * @return jsdoc
- */
- public IJsDoc getJsDoc();
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IAllocationExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IAllocationExpression.java
deleted file mode 100644
index 058d59cd..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IAllocationExpression.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- * Representation of a new expression
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IAllocationExpression {
-
- /**
- * The expression being allocated
- * @return
- */
- IExpression getMember();
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IArgument.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IArgument.java
deleted file mode 100644
index 38487b39..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IArgument.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-/**
- * Representation of a function argument
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
-* 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 IArgument extends ILocalDeclaration{
-
- public char[] getComment();
- public abstract void bind(MethodScope scope, TypeBinding typeBinding, boolean used);
- public abstract StringBuffer print(int indent, StringBuffer output);
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IArrayAllocationExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IArrayAllocationExpression.java
deleted file mode 100644
index 983fd03f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IArrayAllocationExpression.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * 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 IArrayAllocationExpression extends IExpression{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IArrayInitializer.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IArrayInitializer.java
deleted file mode 100644
index 92dce68c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IArrayInitializer.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- * representation of an array initializer
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
-* 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 IArrayInitializer extends IExpression{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IArrayQualifiedTypeReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IArrayQualifiedTypeReference.java
deleted file mode 100644
index aa026427..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IArrayQualifiedTypeReference.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
-* 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 IArrayQualifiedTypeReference extends IQualifiedTypeReference{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IArrayReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IArrayReference.java
deleted file mode 100644
index e298f77b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IArrayReference.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- * Representation of an array reference
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
-* 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 IArrayReference extends IReference{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IArrayTypeReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IArrayTypeReference.java
deleted file mode 100644
index 75ef4a24..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IArrayTypeReference.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
-* 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 IArrayTypeReference extends ISingleTypeReference {
-
-} \ 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
deleted file mode 100644
index ee31a8d9..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IAssignment.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*******************************************************************************
- * 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.core.ast;
-
-import org.eclipse.wst.jsdt.core.infer.InferredType;
-
-/**
- * Representation of an assignment expression
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
-* 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 IAssignment extends IExpression {
-
- /**
- * get the expression being assigned
- * @return expression
- */
- IExpression getExpression();
-
- /**
- * The assignment target
- * @return
- */
- IExpression getLeftHandSide();
-
- IJsDoc getJsDoc();
-
- /**
- * Set the inferred type of the assignment
- * @param inferred type
- */
- public void setInferredType(InferredType type);
- /**
- * Get the inferred type of the assignment
- * @return inferred type
- */
- public InferredType getInferredType();
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IBinaryExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IBinaryExpression.java
deleted file mode 100644
index 47c91861..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IBinaryExpression.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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.core.ast;
-
-/**
- * Representation of binary expressions
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IBinaryExpression extends IOperatorExpression{
- public IExpression getLeft();
- public IExpression getRight();
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IBlock.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IBlock.java
deleted file mode 100644
index 59790000..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IBlock.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * 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.core.ast;
-
-/**
- * Representation of blocks of statements.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IBlock extends IStatement {
- public IStatement[] getStatements() ;
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IBranchStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IBranchStatement.java
deleted file mode 100644
index 68cd4c55..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IBranchStatement.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of a branch statement.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IBranchStatement extends IStatement {
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IBreakStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IBreakStatement.java
deleted file mode 100644
index c875f584..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IBreakStatement.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of a break statment.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IBreakStatement extends IBranchStatement{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ICaseStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ICaseStatement.java
deleted file mode 100644
index c2e6a0c5..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ICaseStatement.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of a case statement.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 ICaseStatement extends IStatement{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ICombinedBinaryExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ICombinedBinaryExpression.java
deleted file mode 100644
index 0fd006ab..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ICombinedBinaryExpression.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of binary expression.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 ICombinedBinaryExpression extends IBinaryExpression{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ICompoundAssignment.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ICompoundAssignment.java
deleted file mode 100644
index 27e70d6c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ICompoundAssignment.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-
-/**
- *
- * Representation of a compound assigment.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 ICompoundAssignment extends IAssignment {
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IConditionalExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IConditionalExpression.java
deleted file mode 100644
index 0bebc76f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IConditionalExpression.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of a conditional expression.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IConditionalExpression extends IOperatorExpression {
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IConstructorDeclaration.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IConstructorDeclaration.java
deleted file mode 100644
index 2dc86476..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IConstructorDeclaration.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of a constructor declaration.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IConstructorDeclaration extends IAbstractFunctionDeclaration{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IContinueStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IContinueStatement.java
deleted file mode 100644
index fbca0ece..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IContinueStatement.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of a continue statement.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IContinueStatement extends IBranchStatement{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IDebuggerStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IDebuggerStatement.java
deleted file mode 100644
index 94c32cdd..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IDebuggerStatement.java
+++ /dev/null
@@ -1,28 +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.core.ast;
-
-/**
- *
- * Representation of a debugger statement (debugger;).
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IDebuggerStatement extends IStatement {
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IDoStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IDoStatement.java
deleted file mode 100644
index 203d5466..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IDoStatement.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of a do statement.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IDoStatement extends IStatement{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IDoubleLiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IDoubleLiteral.java
deleted file mode 100644
index b1b9bc11..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IDoubleLiteral.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IDoubleLiteral extends INumberLiteral{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IEmptyExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IEmptyExpression.java
deleted file mode 100644
index 7786e7b0..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IEmptyExpression.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of an empty expression.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IEmptyExpression extends IExpression{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IEmptyStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IEmptyStatement.java
deleted file mode 100644
index b13abe0e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IEmptyStatement.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of an empty statement (;).
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IEmptyStatement extends IStatement {
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IEqualExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IEqualExpression.java
deleted file mode 100644
index 037bbf7d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IEqualExpression.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-
-/**
- *
- * Representation of = expression.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IEqualExpression extends IBinaryExpression{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IExplicitConstructorCall.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IExplicitConstructorCall.java
deleted file mode 100644
index c55570f7..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IExplicitConstructorCall.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of constructor call.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IExplicitConstructorCall extends IStatement{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IExpression.java
deleted file mode 100644
index d6472df8..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IExpression.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Abstract base class for expression elements.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IExpression extends IStatement{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IExtendedStringLiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IExtendedStringLiteral.java
deleted file mode 100644
index 7f028746..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IExtendedStringLiteral.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of a string literal.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IExtendedStringLiteral extends IStringLiteral{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IFalseLiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IFalseLiteral.java
deleted file mode 100644
index 47351ff5..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IFalseLiteral.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of the false literal.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IFalseLiteral extends IMagicLiteral {
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IFieldDeclaration.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IFieldDeclaration.java
deleted file mode 100644
index e994126a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IFieldDeclaration.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IFieldDeclaration extends IAbstractVariableDeclaration{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IFieldReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IFieldReference.java
deleted file mode 100644
index 96f88dc0..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IFieldReference.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*******************************************************************************
- * 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.core.ast;
-
-/**
- *
- * Representation of a field reference.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IFieldReference extends IReference{
- public IExpression getReceiver();
- char[] getToken();
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IForInStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IForInStatement.java
deleted file mode 100644
index c403d993..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IForInStatement.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of for .. in statement.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IForInStatement extends IStatement{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IForStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IForStatement.java
deleted file mode 100644
index 03bea0c9..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IForStatement.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of a for statement.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IForStatement extends IStatement{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IForeachStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IForeachStatement.java
deleted file mode 100644
index aa1fafe7..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IForeachStatement.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IForeachStatement extends IStatement{
-
-} \ 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
deleted file mode 100644
index 577a5660..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IFunctionCall.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of a function call.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IFunctionCall extends IExpression{
- public char[] getSelector();
- public IExpression[] getArguments();
- public IExpression getReceiver();
-} \ No newline at end of file
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
deleted file mode 100644
index e78489b2..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IFunctionDeclaration.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- * Representation of a function declaration.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * 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 IFunctionDeclaration extends IAbstractFunctionDeclaration{
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IFunctionExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IFunctionExpression.java
deleted file mode 100644
index 47e4b7f7..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IFunctionExpression.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration;
-
-/**
- * Representation of a function expression ( function (){}).
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * 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 IFunctionExpression extends IExpression{
-
- public void setMethodDeclaration(MethodDeclaration methodDeclaration);
- public MethodDeclaration getMethodDeclaration();
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IIfStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IIfStatement.java
deleted file mode 100644
index 4d5bdd1d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IIfStatement.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of an if statement.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IIfStatement extends IStatement{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IImportReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IImportReference.java
deleted file mode 100644
index ca7fe0e2..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IImportReference.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IImportReference extends IASTNode{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IInitializer.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IInitializer.java
deleted file mode 100644
index 14b6e84b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IInitializer.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IInitializer extends IFieldDeclaration{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IInstanceOfExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IInstanceOfExpression.java
deleted file mode 100644
index 7041185b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IInstanceOfExpression.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IInstanceOfExpression extends IOperatorExpression{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IIntLiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IIntLiteral.java
deleted file mode 100644
index ad8c50ab..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IIntLiteral.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IIntLiteral extends INumberLiteral{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IIntLiteralMinValue.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IIntLiteralMinValue.java
deleted file mode 100644
index bf53a949..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IIntLiteralMinValue.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * 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 IIntLiteralMinValue extends IIntLiteral{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDoc.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDoc.java
deleted file mode 100644
index 665ce92c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDoc.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of a jsdoc comment.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IJsDoc extends IASTNode{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocAllocationExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocAllocationExpression.java
deleted file mode 100644
index 45edb20d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocAllocationExpression.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * 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 IJsDocAllocationExpression extends IAllocationExpression{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocArgumentExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocArgumentExpression.java
deleted file mode 100644
index 2f1f3f0d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocArgumentExpression.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * 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 IJsDocArgumentExpression extends IExpression{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocArrayQualifiedTypeReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocArrayQualifiedTypeReference.java
deleted file mode 100644
index 0b1dfa47..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocArrayQualifiedTypeReference.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * 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 IJsDocArrayQualifiedTypeReference extends IArrayQualifiedTypeReference {
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocArraySingleTypeReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocArraySingleTypeReference.java
deleted file mode 100644
index c2608fbb..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocArraySingleTypeReference.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * 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 IJsDocArraySingleTypeReference extends IArrayTypeReference{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocFieldReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocFieldReference.java
deleted file mode 100644
index 59db0140..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocFieldReference.java
+++ /dev/null
@@ -1,23 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-/**
- *
- * 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 IJsDocFieldReference extends IFieldReference{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocImplicitTypeReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocImplicitTypeReference.java
deleted file mode 100644
index ce93950c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocImplicitTypeReference.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * 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 IJsDocImplicitTypeReference extends ITypeReference{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocMessageSend.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocMessageSend.java
deleted file mode 100644
index 6b6d70ab..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocMessageSend.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * 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 IJsDocMessageSend extends IFunctionCall{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocQualifiedTypeReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocQualifiedTypeReference.java
deleted file mode 100644
index 913d5294..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocQualifiedTypeReference.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-
-/**
- *
- * 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 IJsDocQualifiedTypeReference extends IQualifiedTypeReference{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocReturnStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocReturnStatement.java
deleted file mode 100644
index 71c8e03c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocReturnStatement.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * 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 IJsDocReturnStatement extends IReturnStatement{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocSingleNameReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocSingleNameReference.java
deleted file mode 100644
index 71c45ffd..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocSingleNameReference.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * 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 IJsDocSingleNameReference extends ISingleNameReference{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocSingleTypeReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocSingleTypeReference.java
deleted file mode 100644
index e1b2039f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IJsDocSingleTypeReference.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * 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 IJsDocSingleTypeReference extends ISingleTypeReference{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ILabeledStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ILabeledStatement.java
deleted file mode 100644
index a060b5ea..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ILabeledStatement.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of a labeled statement.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 ILabeledStatement extends IStatement{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IListExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IListExpression.java
deleted file mode 100644
index 4f28b288..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IListExpression.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of list expression.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IListExpression extends IExpression{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ILiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ILiteral.java
deleted file mode 100644
index 8698068d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ILiteral.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Abstract base class for literals.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 ILiteral extends IExpression {
-
- public abstract char[] source();
-} \ No newline at end of file
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
deleted file mode 100644
index 4a92fe61..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ILocalDeclaration.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*******************************************************************************
- * 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.core.ast;
-
-import org.eclipse.wst.jsdt.internal.compiler.lookup.InvocationSite;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.LocalVariableBinding;
-
-/**
- *
- * Representation of a local var declaration.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 ILocalDeclaration extends InvocationSite, IAbstractVariableDeclaration {
- public void setBinding(LocalVariableBinding binding);
- public LocalVariableBinding getBinding();
- /**
- * Get the initialization expression of the var as an assignment
- * @return initialization assignment expression or null
- */
- public IAssignment getAssignment();
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IMagicLiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IMagicLiteral.java
deleted file mode 100644
index a6e87f63..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IMagicLiteral.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * 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 IMagicLiteral extends ILiteral{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/INameReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/INameReference.java
deleted file mode 100644
index 7b289bf2..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/INameReference.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Abstract base class for references.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 INameReference extends IReference{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/INullLiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/INullLiteral.java
deleted file mode 100644
index c58d6067..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/INullLiteral.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of the null literal.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 INullLiteral extends IMagicLiteral{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/INumberLiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/INumberLiteral.java
deleted file mode 100644
index dc503871..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/INumberLiteral.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of a numeric literal.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 INumberLiteral extends ILiteral{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IOR_OR_Expression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IOR_OR_Expression.java
deleted file mode 100644
index a9d79662..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IOR_OR_Expression.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of an or or (||) expression.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IOR_OR_Expression extends IBinaryExpression{
-
-} \ 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
deleted file mode 100644
index fb220752..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IObjectLiteral.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-import org.eclipse.wst.jsdt.core.infer.InferredType;
-
-/**
- *
- * Representation of an Object literal.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IObjectLiteral extends IExpression {
- public InferredType getInferredType();
- public void setInferredType(InferredType type);
- public IObjectLiteralField[] getFields();
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IObjectLiteralField.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IObjectLiteralField.java
deleted file mode 100644
index c0ac65b7..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IObjectLiteralField.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of an object literal field.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IObjectLiteralField extends IExpression{
- public IExpression getFieldName();
- public IExpression getInitializer();
- public IJsDoc getJsDoc();
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IOperatorExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IOperatorExpression.java
deleted file mode 100644
index 37a7c786..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IOperatorExpression.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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.core.ast;
-
-/**
- *
- * Representation of an Operator expression.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IOperatorExpression extends IExpression {
- public int getOperator();
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IPostfixExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IPostfixExpression.java
deleted file mode 100644
index 1a236e5d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IPostfixExpression.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of a postfix expression.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IPostfixExpression extends ICompoundAssignment{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IPrefixExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IPrefixExpression.java
deleted file mode 100644
index e1ab94ff..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IPrefixExpression.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of a prefix expression.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IPrefixExpression extends ICompoundAssignment{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IProgramElement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IProgramElement.java
deleted file mode 100644
index 5987ba3a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IProgramElement.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Abstract base class for most AST nodes.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IProgramElement extends IASTNode{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IQualifiedAllocationExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IQualifiedAllocationExpression.java
deleted file mode 100644
index bd79de40..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IQualifiedAllocationExpression.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * 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 IQualifiedAllocationExpression extends IAllocationExpression{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IQualifiedNameReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IQualifiedNameReference.java
deleted file mode 100644
index 1bed12cf..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IQualifiedNameReference.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * 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 IQualifiedNameReference extends INameReference{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IQualifiedThisReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IQualifiedThisReference.java
deleted file mode 100644
index b7a7abce..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IQualifiedThisReference.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * 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 IQualifiedThisReference extends IThisReference{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IQualifiedTypeReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IQualifiedTypeReference.java
deleted file mode 100644
index 50df1b65..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IQualifiedTypeReference.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * 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 IQualifiedTypeReference extends ITypeReference{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IReference.java
deleted file mode 100644
index 0e37db46..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IReference.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Abstract base class for references.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IReference extends IExpression{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IRegExLiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IRegExLiteral.java
deleted file mode 100644
index 5d7001be..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IRegExLiteral.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of a regular expression literal.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IRegExLiteral extends ILiteral{
-
-} \ No newline at end of file
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
deleted file mode 100644
index 6dabd13b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IReturnStatement.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of a return statement.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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();
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IScriptFileDeclaration.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IScriptFileDeclaration.java
deleted file mode 100644
index 1abb9a02..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IScriptFileDeclaration.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of javascript file.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IScriptFileDeclaration extends IASTNode{
-
- IProgramElement []getStatements();
-
- /**
- * get the filename for the script if it can be determined
- * @return the scripts file name, this could be null
- */
- char[] getFileName();
-
- /**
- * get the inference ID for the script if it is located in a container that specified an Inference ID
- * @return the inference ID for the script, could be null
- */
- String getInferenceID();
-
- public void addImport(char [] importName, int startPosition, int endPosition, int nameStartPosition);
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ISingleNameReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ISingleNameReference.java
deleted file mode 100644
index b037d884..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ISingleNameReference.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of name reference.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 ISingleNameReference extends INameReference{
- public char[] getToken();
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ISingleTypeReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ISingleTypeReference.java
deleted file mode 100644
index b0a5bfbd..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ISingleTypeReference.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-/**
- *
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 ISingleTypeReference extends ITypeReference{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IStatement.java
deleted file mode 100644
index 3eda7cbc..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IStatement.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Abstract base for statements.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IStatement extends IProgramElement{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IStringLiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IStringLiteral.java
deleted file mode 100644
index 7dc6ab72..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IStringLiteral.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of a string literal.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IStringLiteral extends ILiteral{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IStringLiteralConcatenation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IStringLiteralConcatenation.java
deleted file mode 100644
index 447cf19b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IStringLiteralConcatenation.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of a string literal.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IStringLiteralConcatenation extends IStringLiteral{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ISubRoutineStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ISubRoutineStatement.java
deleted file mode 100644
index afca555f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ISubRoutineStatement.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 ISubRoutineStatement extends IStatement{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ISuperReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ISuperReference.java
deleted file mode 100644
index af539829..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ISuperReference.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 ISuperReference extends IThisReference{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ISwitchStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ISwitchStatement.java
deleted file mode 100644
index 389b8e9a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ISwitchStatement.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of a switch statement.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 ISwitchStatement extends IStatement{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IThisReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IThisReference.java
deleted file mode 100644
index 6d61e90c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IThisReference.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of a 'this' reference .
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IThisReference extends IReference{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IThrowStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IThrowStatement.java
deleted file mode 100644
index 2102d53d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IThrowStatement.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of a throw statement.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IThrowStatement extends IStatement{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ITrueLiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ITrueLiteral.java
deleted file mode 100644
index f6e91f8a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ITrueLiteral.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of the 'true' literal.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 ITrueLiteral extends IMagicLiteral{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ITryStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ITryStatement.java
deleted file mode 100644
index c88fef60..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ITryStatement.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of a try statement.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 ITryStatement extends ISubRoutineStatement{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ITypeDeclaration.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ITypeDeclaration.java
deleted file mode 100644
index af5943b7..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ITypeDeclaration.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 ITypeDeclaration extends IStatement{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ITypeReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ITypeReference.java
deleted file mode 100644
index ed76eb8a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ITypeReference.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 ITypeReference extends IExpression {
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IUnaryExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IUnaryExpression.java
deleted file mode 100644
index 3bbf6eba..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IUnaryExpression.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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.core.ast;
-
-/**
- *
- * Representation of a unary expression.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IUnaryExpression extends IOperatorExpression{
- public IExpression getExpression();
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IUndefinedLiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IUndefinedLiteral.java
deleted file mode 100644
index 2c75df5f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IUndefinedLiteral.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of a the 'undefined' literal.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IUndefinedLiteral extends IMagicLiteral {
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IWhileStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IWhileStatement.java
deleted file mode 100644
index 94e92760..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IWhileStatement.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of a while statement.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IWhileStatement extends IStatement{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IWithStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IWithStatement.java
deleted file mode 100644
index d9ed8f3e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IWithStatement.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.ast;
-
-/**
- *
- * Representation of the with statement.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * 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 IWithStatement extends IStatement{
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/BuildContext.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/BuildContext.java
deleted file mode 100644
index e14658c6..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/BuildContext.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 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.compiler;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.wst.jsdt.internal.core.builder.ValidationParticipantResult;
-import org.eclipse.wst.jsdt.internal.core.builder.SourceFile;
-
-/**
- * The context of a validation event that is notified to interested validation
- * participants when {@link ValidationParticipant#buildStarting(BuildContext[], boolean) a build is starting.
- * <p>
- * This class is not intended to be instanciated or subclassed by clients.
- * </p>
- *
- * 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 BuildContext extends ValidationParticipantResult {
-
-/**
- * Creates a build context for the given source file.
- * <p>
- * This constructor is not intended to be called by clients.
- * </p>
- *
- * @param sourceFile the source file being built
- */
-public BuildContext(SourceFile sourceFile) {
- super(sourceFile);
-}
-
-/**
- * Returns the contents of the javaScript unit.
- *
- * @return the contents of the javaScript unit
- */
-public char[] getContents() {
- return this.sourceFile.getContents();
-}
-
-/**
- * Returns the <code>IFile</code> representing the javaScript unit.
- *
- * @return the <code>IFile</code> representing the javaScript unit
- */
-public IFile getFile() {
- return this.sourceFile.resource;
-}
-
-/**
- * Record the added/changed generated files that need to be compiled.
- *
- * @param addedGeneratedFiles the added/changed files
- */
-public void recordAddedGeneratedFiles(IFile[] addedGeneratedFiles) {
- int length2 = addedGeneratedFiles.length;
- if (length2 == 0) return;
-
- int length1 = this.addedFiles == null ? 0 : this.addedFiles.length;
- IFile[] merged = new IFile[length1 + length2];
- if (length1 > 0) // always make a copy even if currently empty
- System.arraycopy(this.addedFiles, 0, merged, 0, length1);
- System.arraycopy(addedGeneratedFiles, 0, merged, length1, length2);
- this.addedFiles = merged;
-}
-
-/**
- * Record the generated files that need to be deleted.
- *
- * @param deletedGeneratedFiles the files that need to be deleted
- */
-public void recordDeletedGeneratedFiles(IFile[] deletedGeneratedFiles) {
- int length2 = deletedGeneratedFiles.length;
- if (length2 == 0) return;
-
- int length1 = this.deletedFiles == null ? 0 : this.deletedFiles.length;
- IFile[] merged = new IFile[length1 + length2];
- if (length1 > 0) // always make a copy even if currently empty
- System.arraycopy(this.deletedFiles, 0, merged, 0, length1);
- System.arraycopy(deletedGeneratedFiles, 0, merged, length1, length2);
- this.deletedFiles = merged;
-}
-
-/**
- * Record the fully-qualified type names of any new dependencies, each name is of the form "p1.p2.A.B".
- *
- * @param typeNameDependencies the fully-qualified type names of new dependencies
- */
-public void recordDependencies(String[] typeNameDependencies) {
- int length2 = typeNameDependencies.length;
- if (length2 == 0) return;
-
- int length1 = this.dependencies == null ? 0 : this.dependencies.length;
- String[] merged = new String[length1 + length2];
- if (length1 > 0) // always make a copy even if currently empty
- System.arraycopy(this.dependencies, 0, merged, 0, length1);
- System.arraycopy(typeNameDependencies, 0, merged, length1, length2);
- this.dependencies = merged;
-}
-
-/**
- * Record new problems to report against this compilationUnit.
- * Markers are persisted for these problems only for the declared managed marker type
- * (see the 'validationParticipant' extension point).
- *
- * @param newProblems the problems to report
- */
-public void recordNewProblems(CategorizedProblem[] newProblems) {
- int length2 = newProblems.length;
- if (length2 == 0) return;
-
- int length1 = this.problems == null ? 0 : this.problems.length;
- CategorizedProblem[] merged = new CategorizedProblem[length1 + length2];
- if (length1 > 0) // always make a copy even if currently empty
- System.arraycopy(this.problems, 0, merged, 0, length1);
- System.arraycopy(newProblems, 0, merged, length1, length2);
- this.problems = merged;
-}
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/CategorizedProblem.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/CategorizedProblem.java
deleted file mode 100644
index 9afa3ebf..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/CategorizedProblem.java
+++ /dev/null
@@ -1,153 +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.core.compiler;
-
-import org.eclipse.wst.jsdt.internal.compiler.problem.DefaultProblem;
-
-/**
- * Richer description of a JavaScript problem, as detected by the compiler or some of the underlying
- * technology reusing the compiler. With the introduction of <code>validationParticipant</code>,
- * the simpler problem interface <code>IProblem</code> did not carry enough information to better
- * separate and categorize JavaScript problems. In order to minimize impact on existing API, JavaScript problems
- * are still passed around as <code>IProblem</code>, though actual implementations should explicitly
- * extend <code>CategorizedProblem</code>. Participants can produce their own problem definitions,
- * and given these are categorized problems, they can be better handled by clients (such as user
- * interface).
- *
- * A categorized problem provides access to:
- * <ul>
- * <li> its location (originating source file name, source position, line number), </li>
- * <li> its message description and a predicate to check its severity (warning or error). </li>
- * <li> its ID : a number identifying the very nature of this problem. All possible IDs for standard JavaScript
- * problems are listed as constants on <code>IProblem</code>, </li>
- * <li> its marker type : a string identifying the problem creator. It corresponds to the marker type
- * chosen if this problem was to be persisted. Standard JavaScript problems are associated to marker
- * type "org.eclipse.wst.jsdt.core.problem"), </li>
- * <li> its category ID : a number identifying the category this problem belongs to. All possible IDs for
- * standard JavaScript problem categories are listed in this class. </li>
- * </ul>
- *
- * Note: the compiler produces IProblems internally, which are turned into markers by the validator
- * so as to persist problem descriptions. This explains why there is no API allowing to reach IProblem detected
- * when validating. However, the JavaScript problem markers carry equivalent information to IProblem, in particular
- * their ID (attribute "id") is set to one of the IDs defined on this interface.
- *
- * Note: Standard JavaScript problems produced by JavaScript default tooling will be subclasses of this class. Technically, most
- * API methods dealing with problems are referring to <code>IProblem</code> for backward compatibility reason.
- * It is intended that <code>CategorizedProblem</code> will be subclassed for custom problem implementation when
- * participating in compilation operations, so as to allow participant to contribute their own marker types, and thus
- * defining their own domain specific problem/category IDs.
- *
- * Note: standard JavaScript problems produced by JavaScript default tooling will set the
- * marker IMarker#GENERATED_BY attribute to JavaBuilder#GENERATED_BY; compiler
- * participants may specify the IMarker#GENERATED_BY attribute of their markers
- * by adding it to the extra marker attributes of the problems they generate;
- * markers resulting from compiler participants' problems that do not have the
- * IMarker#GENERATED_BY extra attribute set do not have the IMarker#GENERATED_BY
- * attribute set either.
- *
- * 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 CategorizedProblem implements IProblem {
-
- /**
- * List of standard category IDs used by JavaScript problems, more categories will be added
- * in the future.
- */
- public static final int CAT_UNSPECIFIED = 0;
- /** Category for problems related to buildpath */
- public static final int CAT_BUILDPATH = 10;
- /** Category for fatal problems related to syntax */
- public static final int CAT_SYNTAX = 20;
- /** Category for fatal problems in import statements */
- public static final int CAT_IMPORT = 30;
- /** Category for fatal problems related to types, could be addressed by some type change */
- public static final int CAT_TYPE = 40;
- /** Category for fatal problems related to type members, could be addressed by some field or method change */
- public static final int CAT_MEMBER = 50;
- /** Category for fatal problems which could not be addressed by external changes, but require an edit to be addressed */
- public static final int CAT_INTERNAL = 60;
- /** Category for optional problems in Javadoc */
- public static final int CAT_JAVADOC = 70;
- /** Category for optional problems related to coding style practices */
- public static final int CAT_CODE_STYLE = 80;
- /** Category for optional problems related to potential programming flaws */
- public static final int CAT_POTENTIAL_PROGRAMMING_PROBLEM = 90;
- /** Category for optional problems related to naming conflicts */
- public static final int CAT_NAME_SHADOWING_CONFLICT = 100;
- /** Category for optional problems related to unnecessary code */
- public static final int CAT_UNNECESSARY_CODE = 120;
- /** Category for optional problems related to access restrictions */
- public static final int CAT_RESTRICTION = 150;
-
-/**
- * Returns an integer identifying the category of this problem. Categories, like problem IDs are
- * defined in the context of some marker type. Custom implementations of <code>CategorizedProblem</code>
- * may choose arbitrary values for problem/category IDs, as long as they are associated with a different
- * marker type.
- * Standard JavaScript problem markers (i.e. marker type is "org.eclipse.wst.jsdt.core.problem") carry an
- * attribute "categoryId" persisting the originating problem category ID as defined by this method).
- * @return id - an integer identifying the category of this problem
- */
-public abstract int getCategoryID();
-
-/**
- * Returns the marker type associated to this problem, if it gets persisted into a marker by the JavaBuilder
- * Standard JavaScript problems are associated to marker type "org.eclipse.wst.jsdt.core.problem").
- * Note: problem markers are expected to extend "org.eclipse.core.resources.problemmarker" marker type.
- * @return the type of the marker which would be associated to the problem
- */
-public abstract String getMarkerType();
-
-/**
- * Returns the names of the extra marker attributes associated to this problem when persisted into a marker
- * by the JavaBuilder. Extra attributes are only optional, and are allowing client customization of generated
- * markers. By default, no EXTRA attributes is persisted, and a categorized problem only persists the following attributes:
- * <ul>
- * <li> <code>IMarker#MESSAGE</code> -&gt; {@link IProblem#getMessage()}</li>
- * <li> <code>IMarker#SEVERITY</code> -&gt; <code> IMarker#SEVERITY_ERROR</code> or
- * <code>IMarker#SEVERITY_WARNING</code> depending on {@link IProblem#isError()} or {@link IProblem#isWarning()}</li>
- * <li> <code>IJavaScriptModelMarker#ID</code> -&gt; {@link IProblem#getID()}</li>
- * <li> <code>IMarker#CHAR_START</code> -&gt; {@link IProblem#getSourceStart()}</li>
- * <li> <code>IMarker#CHAR_END</code> -&gt; {@link IProblem#getSourceEnd()}</li>
- * <li> <code>IMarker#LINE_NUMBER</code> -&gt; {@link IProblem#getSourceLineNumber()}</li>
- * <li> <code>IJavaScriptModelMarker#ARGUMENTS</code> -&gt; some <code>String[]</code> used to compute quickfixes </li>
- * <li> <code>IJavaScriptModelMarker#CATEGORY_ID</code> -&gt; {@link CategorizedProblem#getCategoryID()}</li>
- * </ul>
- * The names must be eligible for marker creation, as defined by <code>IMarker#setAttributes(String[], Object[])</code>,
- * and there must be as many names as values according to {@link #getExtraMarkerAttributeValues()}.
- * Note that extra marker attributes will be inserted after default ones (as described in {@link CategorizedProblem#getMarkerType()},
- * and thus could be used to override defaults.
- * @return the names of the corresponding marker attributes
- */
-public String[] getExtraMarkerAttributeNames() {
- return CharOperation.NO_STRINGS;
-}
-
-/**
- * Returns the respective values for the extra marker attributes associated to this problem when persisted into
- * a marker by the JavaBuilder. Each value must correspond to a matching attribute name, as defined by
- * {@link #getExtraMarkerAttributeNames()}.
- * The values must be eligible for marker creation, as defined by <code>IMarker#setAttributes(String[], Object[])</code>.
- * @return the values of the corresponding extra marker attributes
- */
-public Object[] getExtraMarkerAttributeValues() {
- return DefaultProblem.EMPTY_VALUES;
-}
-
-public void setMessage(String msg)
-{
-
-}
-}
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
deleted file mode 100644
index 4dc1e2d7..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/CharOperation.java
+++ /dev/null
@@ -1,3433 +0,0 @@
-/*******************************************************************************
- * 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
- * Luiz-Otavio Zorzella <zorzella at gmail dot com> - Improve CamelCase algorithm
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.compiler;
-
-import org.eclipse.wst.jsdt.internal.compiler.parser.ScannerHelper;
-
-/**
- * This class is a collection of helper methods to manipulate char arrays.
- * <p>
- * This class is not intended to be instantiated or subclassed by clients.
- * </p>
- *
- * 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 final class CharOperation {
-
- /**
- * Constant for an empty char array
- */
- public static final char[] NO_CHAR = new char[0];
-
- /**
- * Constant for an empty char array with two dimensions.
- */
- public static final char[][] NO_CHAR_CHAR = new char[0][];
-
- /**
- * Constant for an empty String array.
- */
- public static final String[] NO_STRINGS = new String[0];
-
-/**
- * Answers a new array with appending the suffix character at the end of the array.
- * <br>
- * <br>
- * For example:<br>
- * <ol>
- * <li><pre>
- * array = { 'a', 'b' }
- * suffix = 'c'
- * => result = { 'a', 'b' , 'c' }
- * </pre>
- * </li>
- * <li><pre>
- * array = null
- * suffix = 'c'
- * => result = { 'c' }
- * </pre></li>
- * </ol>
- *
- * @param array the array that is concanated with the suffix character
- * @param suffix the suffix character
- * @return the new array
- */
-public static final char[] append(char[] array, char suffix) {
- if (array == null)
- return new char[] { suffix };
- int length = array.length;
- System.arraycopy(array, 0, array = new char[length + 1], 0, length);
- array[length] = suffix;
- return array;
-}
-
-/**
- * Append the given subarray to the target array starting at the given index in the target array.
- * The start of the subarray is inclusive, the end is exclusive.
- * Answers a new target array if it needs to grow, otherwise answers the same target array.
- * <br>
- * For example:<br>
- * <ol>
- * <li><pre>
- * target = { 'a', 'b', '0' }
- * index = 2
- * array = { 'c', 'd' }
- * start = 0
- * end = 1
- * => result = { 'a', 'b' , 'c' }
- * </pre>
- * </li>
- * <li><pre>
- * target = { 'a', 'b' }
- * index = 2
- * array = { 'c', 'd' }
- * start = 0
- * end = 1
- * => result = { 'a', 'b' , 'c', '0', '0' , '0' } (new array)
- * </pre></li>
- * <li><pre>
- * target = { 'a', 'b', 'c' }
- * index = 1
- * array = { 'c', 'd', 'e', 'f' }
- * start = 1
- * end = 4
- * => result = { 'a', 'd' , 'e', 'f', '0', '0', '0', '0' } (new array)
- * </pre></li>
- * </ol>
- *
- * @param target the given target
- * @param index the given index
- * @param array the given array
- * @param start the given start index
- * @param end the given end index
- *
- * @return the new array
- * @throws NullPointerException if the target array is null
- */
-public static final char[] append(char[] target, int index, char[] array, int start, int end) {
- int targetLength = target.length;
- int subLength = end-start;
- int newTargetLength = subLength+index;
- if (newTargetLength > targetLength) {
- System.arraycopy(target, 0, target = new char[newTargetLength*2], 0, index);
- }
- System.arraycopy(array, start, target, index, subLength);
- return target;
-}
-
-/**
- * Answers the concatenation of the two arrays. It answers null if the two arrays are null.
- * If the first array is null, then the second array is returned.
- * If the second array is null, then the first array is returned.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * first = null
- * second = null
- * => result = null
- * </pre>
- * </li>
- * <li><pre>
- * first = { { ' a' } }
- * second = null
- * => result = { { ' a' } }
- * </pre>
- * </li>
- * <li><pre>
- * first = null
- * second = { { ' a' } }
- * => result = { { ' a' } }
- * </pre>
- * </li>
- * <li><pre>
- * first = { { ' b' } }
- * second = { { ' a' } }
- * => result = { { ' b' }, { ' a' } }
- * </pre>
- * </li>
- * </ol>
- *
- * @param first the first array to concatenate
- * @param second the second array to concatenate
- * @return the concatenation of the two arrays, or null if the two arrays are null.
- */
-public static final char[][] arrayConcat(char[][] first, char[][] second) {
- if (first == null)
- return second;
- if (second == null)
- return first;
-
- int length1 = first.length;
- int length2 = second.length;
- char[][] result = new char[length1 + length2][];
- System.arraycopy(first, 0, result, 0, length1);
- System.arraycopy(second, 0, result, length1, length2);
- return result;
-}
-
-/**
- * Answers true if the pattern matches the given name using CamelCase rules, or false otherwise.
- * char[] CamelCase matching does NOT accept explicit wild-cards '*' and '?' and is inherently case sensitive.
- * <br>
- * 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.
- * <br>
- * The pattern may contain lowercase characters, which will be match in a case sensitive way. These characters must
- * appear in sequence in the name.
- * <br><br>
- * Examples:
- * <ol>
- * <li><pre>
- * pattern = { 'N', 'P', 'E' }
- * name = { 'N', 'u','l', 'l', 'P', 'o', 'i', 'n', 't', 'e', 'r', 'E', 'x', 'c', 'e', 'p', 't', 'i', 'o', 'n' }
- * result => true
- * </pre>
- * </li>
- * <li><pre>
- * pattern = { 'N', 'P', 'E' }
- * name = { 'N', 'o', 'P', 'e', 'r', 'm', 'i', 's', 's', 'i', 'o', 'n', 'E', 'x', 'c', 'e', 'p', 't', 'i', 'o', 'n' }
- * result => true
- * </pre>
- * </li>
- * <li><pre>
- * pattern = { 'N', 'u', 'P', 'o', 'E', 'x' }
- * name = { 'N', 'u','l', 'l', 'P', 'o', 'i', 'n', 't', 'e', 'r', 'E', 'x', 'c', 'e', 'p', 't', 'i', 'o', 'n' }
- * result => true
- * </pre>
- * </li>
- * <li><pre>
- * pattern = { 'N', 'u', 'P', 'o', 'E', 'x' }
- * name = { 'N', 'o', 'P', 'e', 'r', 'm', 'i', 's', 's', 'i', 'o', 'n', 'E', 'x', 'c', 'e', 'p', 't', 'i', 'o', 'n' }
- * result => false
- * </pre>
- * </li>
- * <li><pre>
- * pattern = { 'n', p', 'e' }
- * name = { 'N', 'u','l', 'l', 'P', 'o', 'i', 'n', 't', 'e', 'r', 'E', 'x', 'c', 'e', 'p', 't', 'i', 'o', 'n' }
- * result => false
- * </pre>
- * </li>
- * </ol>
- *
- * @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(char[] pattern, char[] 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.
- * char[] 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.
- * <br>
- * 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 JavaScript, type names follow the upper CamelCase convention, whereas method or field
- * names follow the lower CamelCase convention.
- * <br>
- * 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'.
- * <br><br>
- * Examples:
- * <ol>
- * <li><pre>
- * pattern = { 'N', 'P', 'E' }
- * patternStart = 0
- * patternEnd = 3
- * name = { 'N', 'u','l', 'l', 'P', 'o', 'i', 'n', 't', 'e', 'r', 'E', 'x', 'c', 'e', 'p', 't', 'i', 'o', 'n' }
- * nameStart = 0
- * nameEnd = 20
- * result => true
- * </pre>
- * </li>
- * <li><pre>
- * pattern = { 'N', 'P', 'E' }
- * patternStart = 0
- * patternEnd = 3
- * name = { 'N', 'o', 'P', 'e', 'r', 'm', 'i', 's', 's', 'i', 'o', 'n', 'E', 'x', 'c', 'e', 'p', 't', 'i', 'o', 'n' }
- * nameStart = 0
- * nameEnd = 21
- * result => true
- * </pre>
- * </li>
- * <li><pre>
- * pattern = { 'N', 'u', 'P', 'o', 'E', 'x' }
- * patternStart = 0
- * patternEnd = 6
- * name = { 'N', 'u','l', 'l', 'P', 'o', 'i', 'n', 't', 'e', 'r', 'E', 'x', 'c', 'e', 'p', 't', 'i', 'o', 'n' }
- * nameStart = 0
- * nameEnd = 20
- * result => true
- * </pre>
- * </li>
- * <li><pre>
- * pattern = { 'N', 'u', 'P', 'o', 'E', 'x' }
- * patternStart = 0
- * patternEnd = 6
- * name = { 'N', 'o', 'P', 'e', 'r', 'm', 'i', 's', 's', 'i', 'o', 'n', 'E', 'x', 'c', 'e', 'p', 't', 'i', 'o', 'n' }
- * nameStart = 0
- * nameEnd = 21
- * result => false
- * </pre>
- * </li>
- * <li><pre>
- * pattern = { 'n', p', 'e' }
- * patternStart = 0
- * patternEnd = 3
- * name = { 'N', 'u','l', 'l', 'P', 'o', 'i', 'n', 't', 'e', 'r', 'E', 'x', 'c', 'e', 'p', 't', 'i', 'o', 'n' }
- * nameStart = 0
- * nameEnd = 20
- * result => false
- * </pre>
- * </li>
- * </ol>
- *
- * @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(char[] pattern, int patternStart, int patternEnd, char[] 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[nameStart] != pattern[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[iPattern]) == name[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[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 the char arrays as an array of Strings
- *
- * @param charArrays the char array to convert
- * @return the char arrays as an array of Strings or null if the given char arrays is null.
- */
-public static String[] charArrayToStringArray(char[][] charArrays) {
- if (charArrays == null)
- return null;
- int length = charArrays.length;
- if (length == 0)
- return NO_STRINGS;
- String[] strings= new String[length];
- for (int i= 0; i < length; i++)
- strings[i]= new String(charArrays[i]);
- return strings;
-}
-
-/**
- * Returns the char array as a String
-
- * @param charArray the char array to convert
- * @return the char array as a String or null if the given char array is null.
- */
-public static String charToString(char[] charArray) {
- if (charArray == null) return null;
- return new String(charArray);
-}
-
-/**
- * Answers a new array adding the second array at the end of first array.
- * It answers null if the first and second are null.
- * If the first array is null, then a new array char[][] is created with second.
- * If the second array is null, then the first array is returned.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * first = null
- * second = { 'a' }
- * => result = { { ' a' } }
- * </pre>
- * <li><pre>
- * first = { { ' a' } }
- * second = null
- * => result = { { ' a' } }
- * </pre>
- * </li>
- * <li><pre>
- * first = { { ' a' } }
- * second = { ' b' }
- * => result = { { ' a' } , { ' b' } }
- * </pre>
- * </li>
- * </ol>
- *
- * @param first the first array to concatenate
- * @param second the array to add at the end of the first array
- * @return a new array adding the second array at the end of first array, or null if the two arrays are null.
- */
-public static final char[][] arrayConcat(char[][] first, char[] second) {
- if (second == null)
- return first;
- if (first == null)
- return new char[][] { second };
-
- int length = first.length;
- char[][] result = new char[length + 1][];
- System.arraycopy(first, 0, result, 0, length);
- result[length] = second;
- return result;
-}
-/**
- * Compares the two char arrays lexicographically.
- *
- * Returns a negative integer if array1 lexicographically precedes the array2,
- * a positive integer if this array1 lexicographically follows the array2, or
- * zero if both arrays are equal.
- *
- * @param array1 the first given array
- * @param array2 the second given array
- * @return the returned value of the comparison between array1 and array2
- * @throws NullPointerException if one of the arrays is null
- */
-public static final int compareTo(char[] array1, char[] array2) {
- int length1 = array1.length;
- int length2 = array2.length;
- int min = Math.min(length1, length2);
- for (int i = 0; i < min; i++) {
- if (array1[i] != array2[i]) {
- return array1[i] - array2[i];
- }
- }
- return length1 - length2;
-}
-/**
- * Compares the contents of the two arrays array and prefix. Returns
- * <ul>
- * <li>zero if the array starts with the prefix contents</li>
- * <li>the difference between the first two characters that are not equal </li>
- * <li>one if array length is lower than the prefix length and that the prefix starts with the
- * array contents.</li>
- * </ul>
- * <p>
- * For example:
- * <ol>
- * <li><pre>
- * array = null
- * prefix = null
- * => result = NullPointerException
- * </pre>
- * </li>
- * <li><pre>
- * array = { 'a', 'b', 'c', 'd', 'e' }
- * prefix = { 'a', 'b', 'c'}
- * => result = 0
- * </pre>
- * </li>
- * <li><pre>
- * array = { 'a', 'b', 'c', 'd', 'e' }
- * prefix = { 'a', 'B', 'c'}
- * => result = 32
- * </pre>
- * </li>
- * <li><pre>
- * array = { 'd', 'b', 'c', 'd', 'e' }
- * prefix = { 'a', 'b', 'c'}
- * => result = 3
- * </pre>
- * </li>
- * <li><pre>
- * array = { 'a', 'b', 'c', 'd', 'e' }
- * prefix = { 'd', 'b', 'c'}
- * => result = -3
- * </pre>
- * </li>
- * <li><pre>
- * array = { 'a', 'a', 'c', 'd', 'e' }
- * prefix = { 'a', 'e', 'c'}
- * => result = -4
- * </pre>
- * </li>
- * </ol>
- * </p>
- *
- * @param array the given array
- * @param prefix the given prefix
- * @return the result of the comparison (>=0 if array>prefix)
- * @throws NullPointerException if either array or prefix is null
- */
-public static final int compareWith(char[] array, char[] prefix) {
- int arrayLength = array.length;
- int prefixLength = prefix.length;
- int min = Math.min(arrayLength, prefixLength);
- int i = 0;
- while (min-- != 0) {
- char c1 = array[i];
- char c2 = prefix[i++];
- if (c1 != c2)
- return c1 - c2;
- }
- if (prefixLength == i)
- return 0;
- return -1; // array is shorter than prefix (e.g. array:'ab' < prefix:'abc').
-}
-
-/**
- * Answers the concatenation of the two arrays. It answers null if the two arrays are null.
- * If the first array is null, then the second array is returned.
- * If the second array is null, then the first array is returned.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * first = null
- * second = { 'a' }
- * => result = { ' a' }
- * </pre>
- * </li>
- * <li><pre>
- * first = { ' a' }
- * second = null
- * => result = { ' a' }
- * </pre>
- * </li>
- * <li><pre>
- * first = { ' a' }
- * second = { ' b' }
- * => result = { ' a' , ' b' }
- * </pre>
- * </li>
- * </ol>
- *
- * @param first the first array to concatenate
- * @param second the second array to concatenate
- * @return the concatenation of the two arrays, or null if the two arrays are null.
- */
-public static final char[] concat(char[] first, char[] second) {
- if (first == null)
- return second;
- if (second == null)
- return first;
-
- int length1 = first.length;
- int length2 = second.length;
- char[] result = new char[length1 + length2];
- System.arraycopy(first, 0, result, 0, length1);
- System.arraycopy(second, 0, result, length1, length2);
- return result;
-}
-
-/**
- * Answers the concatenation of the three arrays. It answers null if the three arrays are null.
- * If first is null, it answers the concatenation of second and third.
- * If second is null, it answers the concatenation of first and third.
- * If third is null, it answers the concatenation of first and second.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * first = null
- * second = { 'a' }
- * third = { 'b' }
- * => result = { ' a', 'b' }
- * </pre>
- * </li>
- * <li><pre>
- * first = { 'a' }
- * second = null
- * third = { 'b' }
- * => result = { ' a', 'b' }
- * </pre>
- * </li>
- * <li><pre>
- * first = { 'a' }
- * second = { 'b' }
- * third = null
- * => result = { ' a', 'b' }
- * </pre>
- * </li>
- * <li><pre>
- * first = null
- * second = null
- * third = null
- * => result = null
- * </pre>
- * </li>
- * <li><pre>
- * first = { 'a' }
- * second = { 'b' }
- * third = { 'c' }
- * => result = { 'a', 'b', 'c' }
- * </pre>
- * </li>
- * </ol>
- *
- * @param first the first array to concatenate
- * @param second the second array to concatenate
- * @param third the third array to concatenate
- *
- * @return the concatenation of the three arrays, or null if the three arrays are null.
- */
-public static final char[] concat(
- char[] first,
- char[] second,
- char[] third) {
- if (first == null)
- return concat(second, third);
- if (second == null)
- return concat(first, third);
- if (third == null)
- return concat(first, second);
-
- int length1 = first.length;
- int length2 = second.length;
- int length3 = third.length;
- char[] result = new char[length1 + length2 + length3];
- System.arraycopy(first, 0, result, 0, length1);
- System.arraycopy(second, 0, result, length1, length2);
- System.arraycopy(third, 0, result, length1 + length2, length3);
- return result;
-}
-
-/**
- * Answers the concatenation of the two arrays inserting the separator character between the two arrays.
- * It answers null if the two arrays are null.
- * If the first array is null, then the second array is returned.
- * If the second array is null, then the first array is returned.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * first = null
- * second = { 'a' }
- * separator = '/'
- * => result = { ' a' }
- * </pre>
- * </li>
- * <li><pre>
- * first = { ' a' }
- * second = null
- * separator = '/'
- * => result = { ' a' }
- * </pre>
- * </li>
- * <li><pre>
- * first = { ' a' }
- * second = { ' b' }
- * separator = '/'
- * => result = { ' a' , '/', 'b' }
- * </pre>
- * </li>
- * </ol>
- *
- * @param first the first array to concatenate
- * @param second the second array to concatenate
- * @param separator the character to insert
- * @return the concatenation of the two arrays inserting the separator character
- * between the two arrays , or null if the two arrays are null.
- */
-public static final char[] concat(
- char[] first,
- char[] second,
- char separator) {
- if (first == null)
- return second;
- if (second == null)
- return first;
-
- int length1 = first.length;
- if (length1 == 0)
- return second;
- int length2 = second.length;
- if (length2 == 0)
- return first;
-
- char[] result = new char[length1 + length2 + 1];
- System.arraycopy(first, 0, result, 0, length1);
- result[length1] = separator;
- System.arraycopy(second, 0, result, length1 + 1, length2);
- return result;
-}
-
-/**
- * Answers the concatenation of the three arrays inserting the sep1 character between the
- * first two arrays and sep2 between the last two.
- * It answers null if the three arrays are null.
- * If the first array is null, then it answers the concatenation of second and third inserting
- * the sep2 character between them.
- * If the second array is null, then it answers the concatenation of first and third inserting
- * the sep1 character between them.
- * If the third array is null, then it answers the concatenation of first and second inserting
- * the sep1 character between them.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * first = null
- * sep1 = '/'
- * second = { 'a' }
- * sep2 = ':'
- * third = { 'b' }
- * => result = { ' a' , ':', 'b' }
- * </pre>
- * </li>
- * <li><pre>
- * first = { 'a' }
- * sep1 = '/'
- * second = null
- * sep2 = ':'
- * third = { 'b' }
- * => result = { ' a' , '/', 'b' }
- * </pre>
- * </li>
- * <li><pre>
- * first = { 'a' }
- * sep1 = '/'
- * second = { 'b' }
- * sep2 = ':'
- * third = null
- * => result = { ' a' , '/', 'b' }
- * </pre>
- * </li>
- * <li><pre>
- * first = { 'a' }
- * sep1 = '/'
- * second = { 'b' }
- * sep2 = ':'
- * third = { 'c' }
- * => result = { ' a' , '/', 'b' , ':', 'c' }
- * </pre>
- * </li>
- * </ol>
- *
- * @param first the first array to concatenate
- * @param sep1 the character to insert
- * @param second the second array to concatenate
- * @param sep2 the character to insert
- * @param third the second array to concatenate
- * @return the concatenation of the three arrays inserting the sep1 character between the
- * two arrays and sep2 between the last two.
- */
-public static final char[] concat(
- char[] first,
- char sep1,
- char[] second,
- char sep2,
- char[] third) {
- if (first == null)
- return concat(second, third, sep2);
- if (second == null)
- return concat(first, third, sep1);
- if (third == null)
- return concat(first, second, sep1);
-
- int length1 = first.length;
- int length2 = second.length;
- int length3 = third.length;
- char[] result = new char[length1 + length2 + length3 + 2];
- System.arraycopy(first, 0, result, 0, length1);
- result[length1] = sep1;
- System.arraycopy(second, 0, result, length1 + 1, length2);
- result[length1 + length2 + 1] = sep2;
- System.arraycopy(third, 0, result, length1 + length2 + 2, length3);
- return result;
-}
-
-/**
- * Answers a new array with prepending the prefix character and appending the suffix
- * character at the end of the array. If array is null, it answers a new array containing the
- * prefix and the suffix characters.
- * <br>
- * <br>
- * For example:<br>
- * <ol>
- * <li><pre>
- * prefix = 'a'
- * array = { 'b' }
- * suffix = 'c'
- * => result = { 'a', 'b' , 'c' }
- * </pre>
- * </li>
- * <li><pre>
- * prefix = 'a'
- * array = null
- * suffix = 'c'
- * => result = { 'a', 'c' }
- * </pre></li>
- * </ol>
- *
- * @param prefix the prefix character
- * @param array the array that is concanated with the prefix and suffix characters
- * @param suffix the suffix character
- * @return the new array
- */
-public static final char[] concat(char prefix, char[] array, char suffix) {
- if (array == null)
- return new char[] { prefix, suffix };
-
- int length = array.length;
- char[] result = new char[length + 2];
- result[0] = prefix;
- System.arraycopy(array, 0, result, 1, length);
- result[length + 1] = suffix;
- return result;
-}
-
-/**
- * Answers the concatenation of the given array parts using the given separator between each
- * part and appending the given name at the end.
- * <br>
- * <br>
- * For example:<br>
- * <ol>
- * <li><pre>
- * name = { 'c' }
- * array = { { 'a' }, { 'b' } }
- * separator = '.'
- * => result = { 'a', '.', 'b' , '.', 'c' }
- * </pre>
- * </li>
- * <li><pre>
- * name = null
- * array = { { 'a' }, { 'b' } }
- * separator = '.'
- * => result = { 'a', '.', 'b' }
- * </pre></li>
- * <li><pre>
- * name = { ' c' }
- * array = null
- * separator = '.'
- * => result = { 'c' }
- * </pre></li>
- * </ol>
- *
- * @param name the given name
- * @param array the given array
- * @param separator the given separator
- * @return the concatenation of the given array parts using the given separator between each
- * part and appending the given name at the end
- */
-public static final char[] concatWith(
- char[] name,
- char[][] array,
- char separator) {
- int nameLength = name == null ? 0 : name.length;
- if (nameLength == 0)
- return concatWith(array, separator);
-
- int length = array == null ? 0 : array.length;
- if (length == 0)
- return name;
-
- int size = nameLength;
- int index = length;
- while (--index >= 0)
- if (array[index].length > 0)
- size += array[index].length + 1;
- char[] result = new char[size];
- index = size;
- for (int i = length - 1; i >= 0; i--) {
- int subLength = array[i].length;
- if (subLength > 0) {
- index -= subLength;
- System.arraycopy(array[i], 0, result, index, subLength);
- result[--index] = separator;
- }
- }
- System.arraycopy(name, 0, result, 0, nameLength);
- return result;
-}
-
-/**
- * Answers the concatenation of the given array parts using the given separator between each
- * part and appending the given name at the end.
- * <br>
- * <br>
- * For example:<br>
- * <ol>
- * <li><pre>
- * name = { 'c' }
- * array = { { 'a' }, { 'b' } }
- * separator = '.'
- * => result = { 'a', '.', 'b' , '.', 'c' }
- * </pre>
- * </li>
- * <li><pre>
- * name = null
- * array = { { 'a' }, { 'b' } }
- * separator = '.'
- * => result = { 'a', '.', 'b' }
- * </pre></li>
- * <li><pre>
- * name = { ' c' }
- * array = null
- * separator = '.'
- * => result = { 'c' }
- * </pre></li>
- * </ol>
- *
- * @param array the given array
- * @param name the given name
- * @param separator the given separator
- * @return the concatenation of the given array parts using the given separator between each
- * part and appending the given name at the end
- */
-public static final char[] concatWith(
- char[][] array,
- char[] name,
- char separator) {
- int nameLength = name == null ? 0 : name.length;
- if (nameLength == 0)
- return concatWith(array, separator);
-
- int length = array == null ? 0 : array.length;
- if (length == 0)
- return name;
-
- int size = nameLength;
- int index = length;
- while (--index >= 0)
- if (array[index].length > 0)
- size += array[index].length + 1;
- char[] result = new char[size];
- index = 0;
- for (int i = 0; i < length; i++) {
- int subLength = array[i].length;
- if (subLength > 0) {
- System.arraycopy(array[i], 0, result, index, subLength);
- index += subLength;
- result[index++] = separator;
- }
- }
- System.arraycopy(name, 0, result, index, nameLength);
- return result;
-}
-
-public static final char[] fixLibPackageTail(char[] packageName) {
-
- if(packageName==null || packageName.length<3) return packageName;
- int length = packageName.length;
- if( packageName[length-3]=='/' && (packageName[length-2]=='j' || packageName[length-2]=='J') && (packageName[length-1]=='s' || packageName[length-1]=='S')){
- char[] newPname = packageName;
- newPname[length-3] = '.';
- return newPname;
- }
- return packageName;
-}
-
-/**
- * Answers the concatenation of the given array parts using the given separator between each part.
- * <br>
- * <br>
- * For example:<br>
- * <ol>
- * <li><pre>
- * array = { { 'a' }, { 'b' } }
- * separator = '.'
- * => result = { 'a', '.', 'b' }
- * </pre>
- * </li>
- * <li><pre>
- * array = null
- * separator = '.'
- * => result = { }
- * </pre></li>
- * </ol>
- *
- * <p><b>NOTE:</b> This implementation ignores any elements in the given array that are empty.</p>
- *
- * @param array the given array
- * @param separator the given separator
- *
- * @return the concatenation of the given array parts using the given separator between each part
- *
- * @see #concatWith(char[][], char, boolean)
- */
-public static final char[] concatWith(char[][] array, char separator) {
- return concatWith(array, separator, true);
-}
-
-/**
- * Answers the concatenation of the given array parts using the given separator between each part.
- * <br>
- * <br>
- * For example:<br>
- * <ol>
- * <li><pre>
- * array = { { 'a' }, { 'b' } }
- * separator = '.'
- * => result = { 'a', '.', 'b' }
- * </pre>
- * </li>
- * <li><pre>
- * array = null
- * separator = '.'
- * => result = { }
- * </pre></li>
- * </ol>
- *
- * <p>This implementation allows the caller to decide if empty elements in the array should be skipped or not</p>
- *
- * @param array char string array to concatenate with itself
- * @param separator the separator to use between each element of the char string array
- * @param ignoreEmptyElements <code>true</code> to skip any empty elements in the char string array,
- * <code>false</code> to include an empty element in the return char string
- *
- * @return the concatenation of the given array parts using the given separator between each part
- */
-public static final char[] concatWith(char[][] array, char separator, boolean ignoreEmptyElements) {
- int length = array == null ? 0 : array.length;
- if (length == 0)
- return CharOperation.NO_CHAR;
-
- int size = length - 1;
- int index = length;
- while (--index >= 0) {
- if (array[index].length == 0 && ignoreEmptyElements)
- size--;
- else
- size += array[index].length;
- }
- if (size <= 0)
- return CharOperation.NO_CHAR;
- char[] result = new char[size];
- index = length;
- while (--index >= 0) {
- length = array[index].length;
- if (length > 0 || (length == 0 && !ignoreEmptyElements)) {
- System.arraycopy(
- array[index],
- 0,
- result,
- (size -= length),
- length);
- if (--size >= 0)
- result[size] = separator;
- }
- }
- return result;
-}
-
-/**
- * Answers true if the array contains an occurrence of character, false otherwise.
- *
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * character = 'c'
- * array = { { ' a' }, { ' b' } }
- * result => false
- * </pre>
- * </li>
- * <li><pre>
- * character = 'a'
- * array = { { ' a' }, { ' b' } }
- * result => true
- * </pre>
- * </li>
- * </ol>
- *
- * @param character the character to search
- * @param array the array in which the search is done
- * @return true if the array contains an occurrence of character, false otherwise.
- * @throws NullPointerException if array is null.
- */
-public static final boolean contains(char character, char[][] array) {
- for (int i = array.length; --i >= 0;) {
- char[] subarray = array[i];
- for (int j = subarray.length; --j >= 0;)
- if (subarray[j] == character)
- return true;
- }
- return false;
-}
-
-/**
- * Answers true if the array contains an occurrence of character, false otherwise.
- *
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * character = 'c'
- * array = { ' b' }
- * result => false
- * </pre>
- * </li>
- * <li><pre>
- * character = 'a'
- * array = { ' a' , ' b' }
- * result => true
- * </pre>
- * </li>
- * </ol>
- *
- * @param character the character to search
- * @param array the array in which the search is done
- * @return true if the array contains an occurrence of character, false otherwise.
- * @throws NullPointerException if array is null.
- */
-public static final boolean contains(char character, char[] array) {
- for (int i = array.length; --i >= 0;)
- if (array[i] == character)
- return true;
- return false;
-}
-
-/**
- * Answers true if the array contains an occurrence of one of the characters, false otherwise.
- *
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * characters = { 'c', 'd' }
- * array = { 'a', ' b' }
- * result => false
- * </pre>
- * </li>
- * <li><pre>
- * characters = { 'c', 'd' }
- * array = { 'a', ' b', 'c' }
- * result => true
- * </pre>
- * </li>
- * </ol>
- *
- * @param characters the characters to search
- * @param array the array in which the search is done
- * @return true if the array contains an occurrence of one of the characters, false otherwise.
- * @throws NullPointerException if array is null.
- */
-public static final boolean contains(char[] characters, char[] array) {
- for (int i = array.length; --i >= 0;)
- for (int j = characters.length; --j >= 0;)
- if (array[i] == characters[j])
- return true;
- return false;
-}
-
-/**
- * Answers a deep copy of the toCopy array.
- *
- * @param toCopy the array to copy
- * @return a deep copy of the toCopy array.
- */
-
-public static final char[][] deepCopy(char[][] toCopy) {
- int toCopyLength = toCopy.length;
- char[][] result = new char[toCopyLength][];
- for (int i = 0; i < toCopyLength; i++) {
- char[] toElement = toCopy[i];
- int toElementLength = toElement.length;
- char[] resultElement = new char[toElementLength];
- System.arraycopy(toElement, 0, resultElement, 0, toElementLength);
- result[i] = resultElement;
- }
- return result;
-}
-
-/**
- * Return true if array ends with the sequence of characters contained in toBeFound,
- * otherwise false.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * array = { 'a', 'b', 'c', 'd' }
- * toBeFound = { 'b', 'c' }
- * result => false
- * </pre>
- * </li>
- * <li><pre>
- * array = { 'a', 'b', 'c' }
- * toBeFound = { 'b', 'c' }
- * result => true
- * </pre>
- * </li>
- * </ol>
- *
- * @param array the array to check
- * @param toBeFound the array to find
- * @return true if array ends with the sequence of characters contained in toBeFound,
- * otherwise false.
- * @throws NullPointerException if array is null or toBeFound is null
- */
-public static final boolean endsWith(char[] array, char[] toBeFound) {
- int i = toBeFound.length;
- int j = array.length - i;
-
- if (j < 0)
- return false;
- while (--i >= 0)
- if (toBeFound[i] != array[i + j])
- return false;
- return true;
-}
-
-/**
- * Answers true if the two arrays are identical character by character, otherwise false.
- * The equality is case sensitive.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * first = null
- * second = null
- * result => true
- * </pre>
- * </li>
- * <li><pre>
- * first = { { } }
- * second = null
- * result => false
- * </pre>
- * </li>
- * <li><pre>
- * first = { { 'a' } }
- * second = { { 'a' } }
- * result => true
- * </pre>
- * </li>
- * <li><pre>
- * first = { { 'A' } }
- * second = { { 'a' } }
- * result => false
- * </pre>
- * </li>
- * </ol>
- * @param first the first array
- * @param second the second array
- * @return true if the two arrays are identical character by character, otherwise false
- */
-public static final boolean equals(char[][] first, char[][] second) {
- if (first == second)
- return true;
- if (first == null || second == null)
- return false;
- if (first.length != second.length)
- return false;
-
- for (int i = first.length; --i >= 0;)
- if (!equals(first[i], second[i]))
- return false;
- return true;
-}
-
-/**
- * If isCaseSensite is true, answers true if the two arrays are identical character
- * by character, otherwise false.
- * If it is false, answers true if the two arrays are identical character by
- * character without checking the case, otherwise false.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * first = null
- * second = null
- * isCaseSensitive = true
- * result => true
- * </pre>
- * </li>
- * <li><pre>
- * first = { { } }
- * second = null
- * isCaseSensitive = true
- * result => false
- * </pre>
- * </li>
- * <li><pre>
- * first = { { 'A' } }
- * second = { { 'a' } }
- * isCaseSensitive = true
- * result => false
- * </pre>
- * </li>
- * <li><pre>
- * first = { { 'A' } }
- * second = { { 'a' } }
- * isCaseSensitive = false
- * result => true
- * </pre>
- * </li>
- * </ol>
- *
- * @param first the first array
- * @param second the second array
- * @param isCaseSensitive check whether or not the equality should be case sensitive
- * @return true if the two arrays are identical character by character according to the value
- * of isCaseSensitive, otherwise false
- */
-public static final boolean equals(
- char[][] first,
- char[][] second,
- boolean isCaseSensitive) {
-
- if (isCaseSensitive) {
- return equals(first, second);
- }
- if (first == second)
- return true;
- if (first == null || second == null)
- return false;
- if (first.length != second.length)
- return false;
-
- for (int i = first.length; --i >= 0;)
- if (!equals(first[i], second[i], false))
- return false;
- return true;
-}
-
-/**
- * Answers true if the two arrays are identical character by character, otherwise false.
- * The equality is case sensitive.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * first = null
- * second = null
- * result => true
- * </pre>
- * </li>
- * <li><pre>
- * first = { }
- * second = null
- * result => false
- * </pre>
- * </li>
- * <li><pre>
- * first = { 'a' }
- * second = { 'a' }
- * result => true
- * </pre>
- * </li>
- * <li><pre>
- * first = { 'a' }
- * second = { 'A' }
- * result => false
- * </pre>
- * </li>
- * </ol>
- * @param first the first array
- * @param second the second array
- * @return true if the two arrays are identical character by character, otherwise false
- */
-public static final boolean equals(char[] first, char[] second) {
- if (first == second)
- return true;
- if (first == null || second == null)
- return false;
- if (first.length != second.length)
- return false;
-
- for (int i = first.length; --i >= 0;)
- if (first[i] != second[i])
- return false;
- return true;
-}
-
-/**
- * Answers true if the first array is identical character by character to a portion of the second array
- * delimited from position secondStart (inclusive) to secondEnd(exclusive), otherwise false.
- * The equality is case sensitive.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * first = null
- * second = null
- * secondStart = 0
- * secondEnd = 0
- * result => true
- * </pre>
- * </li>
- * <li><pre>
- * first = { }
- * second = null
- * secondStart = 0
- * secondEnd = 0
- * result => false
- * </pre>
- * </li>
- * <li><pre>
- * first = { 'a' }
- * second = { 'a' }
- * secondStart = 0
- * secondEnd = 1
- * result => true
- * </pre>
- * </li>
- * <li><pre>
- * first = { 'a' }
- * second = { 'A' }
- * secondStart = 0
- * secondEnd = 1
- * result => false
- * </pre>
- * </li>
- * </ol>
- * @param first the first array
- * @param second the second array
- * @param secondStart inclusive start position in the second array to compare
- * @param secondEnd exclusive end position in the second array to compare
- * @return true if the first array is identical character by character to fragment of second array ranging from secondStart to secondEnd-1, otherwise false
- */
-public static final boolean equals(char[] first, char[] second, int secondStart, int secondEnd) {
- return equals(first, second, secondStart, secondEnd, true);
-}
-/**
- * <p>Answers true if the first array is identical character by character to a portion of the second array
- * delimited from position secondStart (inclusive) to secondEnd(exclusive), otherwise false. The equality could be either
- * case sensitive or case insensitive according to the value of the <code>isCaseSensitive</code> parameter.
- * </p>
- * <p>For example:</p>
- * <ol>
- * <li><pre>
- * first = null
- * second = null
- * secondStart = 0
- * secondEnd = 0
- * isCaseSensitive = false
- * result => true
- * </pre>
- * </li>
- * <li><pre>
- * first = { }
- * second = null
- * secondStart = 0
- * secondEnd = 0
- * isCaseSensitive = false
- * result => false
- * </pre>
- * </li>
- * <li><pre>
- * first = { 'a' }
- * second = { 'a' }
- * secondStart = 0
- * secondEnd = 1
- * isCaseSensitive = true
- * result => true
- * </pre>
- * </li>
- * <li><pre>
- * first = { 'a' }
- * second = { 'A' }
- * secondStart = 0
- * secondEnd = 1
- * isCaseSensitive = true
- * result => false
- * </pre>
- * </li>
- * <li><pre>
- * first = { 'a' }
- * second = { 'A' }
- * secondStart = 0
- * secondEnd = 1
- * isCaseSensitive = false
- * result => true
- * </pre>
- * </li>
- * </ol>
- * @param first the first array
- * @param second the second array
- * @param secondStart inclusive start position in the second array to compare
- * @param secondEnd exclusive end position in the second array to compare
- * @param isCaseSensitive check whether or not the equality should be case sensitive
- * @return true if the first array is identical character by character to fragment of second array ranging from secondStart to secondEnd-1, otherwise false
- */
-public static final boolean equals(char[] first, char[] second, int secondStart, int secondEnd, boolean isCaseSensitive) {
- if (first == second)
- return true;
- if (first == null || second == null)
- return false;
- if (first.length != secondEnd - secondStart)
- return false;
- if (isCaseSensitive) {
- for (int i = first.length; --i >= 0;)
- if (first[i] != second[i+secondStart])
- return false;
- } else {
- for (int i = first.length; --i >= 0;)
- if (ScannerHelper.toLowerCase(first[i]) != ScannerHelper.toLowerCase(second[i+secondStart]))
- return false;
- }
- return true;
-}
-
-/**
- * If isCaseSensite is true, answers true if the two arrays are identical character
- * by character, otherwise false.
- * If it is false, answers true if the two arrays are identical character by
- * character without checking the case, otherwise false.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * first = null
- * second = null
- * isCaseSensitive = true
- * result => true
- * </pre>
- * </li>
- * <li><pre>
- * first = { }
- * second = null
- * isCaseSensitive = true
- * result => false
- * </pre>
- * </li>
- * <li><pre>
- * first = { 'A' }
- * second = { 'a' }
- * isCaseSensitive = true
- * result => false
- * </pre>
- * </li>
- * <li><pre>
- * first = { 'A' }
- * second = { 'a' }
- * isCaseSensitive = false
- * result => true
- * </pre>
- * </li>
- * </ol>
- *
- * @param first the first array
- * @param second the second array
- * @param isCaseSensitive check whether or not the equality should be case sensitive
- * @return true if the two arrays are identical character by character according to the value
- * of isCaseSensitive, otherwise false
- */
-public static final boolean equals(
- char[] first,
- char[] second,
- boolean isCaseSensitive) {
-
- if (isCaseSensitive) {
- return equals(first, second);
- }
- if (first == second)
- return true;
- if (first == null || second == null)
- return false;
- if (first.length != second.length)
- return false;
-
- for (int i = first.length; --i >= 0;)
- if (ScannerHelper.toLowerCase(first[i])
- != ScannerHelper.toLowerCase(second[i]))
- return false;
- return true;
-}
-
-/**
- * If isCaseSensite is true, the equality is case sensitive, otherwise it is case insensitive.
- *
- * Answers true if the name contains the fragment at the starting index startIndex, otherwise false.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * fragment = { 'b', 'c' , 'd' }
- * name = { 'a', 'b', 'c' , 'd' }
- * startIndex = 1
- * isCaseSensitive = true
- * result => true
- * </pre>
- * </li>
- * <li><pre>
- * fragment = { 'b', 'c' , 'd' }
- * name = { 'a', 'b', 'C' , 'd' }
- * startIndex = 1
- * isCaseSensitive = true
- * result => false
- * </pre>
- * </li>
- * <li><pre>
- * fragment = { 'b', 'c' , 'd' }
- * name = { 'a', 'b', 'C' , 'd' }
- * startIndex = 0
- * isCaseSensitive = false
- * result => false
- * </pre>
- * </li>
- * <li><pre>
- * fragment = { 'b', 'c' , 'd' }
- * name = { 'a', 'b'}
- * startIndex = 0
- * isCaseSensitive = true
- * result => false
- * </pre>
- * </li>
- * </ol>
- *
- * @param fragment the fragment to check
- * @param name the array to check
- * @param startIndex the starting index
- * @param isCaseSensitive check whether or not the equality should be case sensitive
- * @return true if the name contains the fragment at the starting index startIndex according to the
- * value of isCaseSensitive, otherwise false.
- * @throws NullPointerException if fragment or name is null.
- */
-public static final boolean fragmentEquals(
- char[] fragment,
- char[] name,
- int startIndex,
- boolean isCaseSensitive) {
-
- int max = fragment.length;
- if (name.length < max + startIndex)
- return false;
- if (isCaseSensitive) {
- for (int i = max;
- --i >= 0;
- ) // assumes the prefix is not larger than the name
- if (fragment[i] != name[i + startIndex])
- return false;
- return true;
- }
- for (int i = max;
- --i >= 0;
- ) // assumes the prefix is not larger than the name
- if (ScannerHelper.toLowerCase(fragment[i])
- != ScannerHelper.toLowerCase(name[i + startIndex]))
- return false;
- return true;
-}
-
-/**
- * Answers a hashcode for the array
- *
- * @param array the array for which a hashcode is required
- * @return the hashcode
- * @throws NullPointerException if array is null
- */
-public static final int hashCode(char[] array) {
- int length = array.length;
- int hash = length == 0 ? 31 : array[0];
- if (length < 8) {
- for (int i = length; --i > 0;)
- hash = (hash * 31) + array[i];
- } else {
- // 8 characters is enough to compute a decent hash code, don't waste time examining every character
- for (int i = length - 1, last = i > 16 ? i - 16 : 0; i > last; i -= 2)
- hash = (hash * 31) + array[i];
- }
- return hash & 0x7FFFFFFF;
-}
-
-/**
- * Answers true if c is a whitespace (&#92;u000a, &#92;u000c, &#92;u000d, &#92;u0009), otherwise false.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * c = ' '
- * result => true
- * </pre>
- * </li>
- * <li><pre>
- * c = '&#92;u3000'
- * result => false
- * </pre>
- * </li>
- * </ol>
- *
- * @param c the character to check
- * @return true if c is a whitespace according to the JLS, otherwise false.
- */
-public static boolean isWhitespace(char c) {
- return c < ScannerHelper.MAX_OBVIOUS && ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_JLS_SPACE) != 0);
-}
-
-/**
- * Answers the first index in the array for which the corresponding character is
- * equal to toBeFound. Answers -1 if no occurrence of this character is found.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * toBeFound = 'c'
- * array = { ' a', 'b', 'c', 'd' }
- * result => 2
- * </pre>
- * </li>
- * <li><pre>
- * toBeFound = 'e'
- * array = { ' a', 'b', 'c', 'd' }
- * result => -1
- * </pre>
- * </li>
- * </ol>
- *
- * @param toBeFound the character to search
- * @param array the array to be searched
- * @return the first index in the array for which the corresponding character is
- * equal to toBeFound, -1 otherwise
- * @throws NullPointerException if array is null
- */
-public static final int indexOf(char toBeFound, char[] array) {
- return indexOf(toBeFound, array, 0);
-}
-
-/**
- * Answers the first index in the array for which the toBeFound array is a matching
- * subarray following the case rule. Answers -1 if no match is found.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * toBeFound = { 'c' }
- * array = { ' a', 'b', 'c', 'd' }
- * result => 2
- * </pre>
- * </li>
- * <li><pre>
- * toBeFound = { 'e' }
- * array = { ' a', 'b', 'c', 'd' }
- * result => -1
- * </pre>
- * </li>
- * </ol>
- *
- * @param toBeFound the subarray to search
- * @param array the array to be searched
- * @param isCaseSensitive flag to know if the matching should be case sensitive
- * @return the first index in the array for which the toBeFound array is a matching
- * subarray following the case rule, -1 otherwise
- * @throws NullPointerException if array is null or toBeFound is null
- */
-public static final int indexOf(char[] toBeFound, char[] array, boolean isCaseSensitive) {
- return indexOf(toBeFound, array, isCaseSensitive, 0);
-}
-
-/**
- * Answers the first index in the array for which the toBeFound array is a matching
- * subarray following the case rule starting at the index start. Answers -1 if no match is found.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * toBeFound = { 'c' }
- * array = { ' a', 'b', 'c', 'd' }
- * result => 2
- * </pre>
- * </li>
- * <li><pre>
- * toBeFound = { 'e' }
- * array = { ' a', 'b', 'c', 'd' }
- * result => -1
- * </pre>
- * </li>
- * </ol>
- *
- * @param toBeFound the subarray to search
- * @param array the array to be searched
- * @param isCaseSensitive flag to know if the matching should be case sensitive
- * @param start the starting index
- * @return the first index in the array for which the toBeFound array is a matching
- * subarray following the case rule starting at the index start, -1 otherwise
- * @throws NullPointerException if array is null or toBeFound is null
- */
-public static final int indexOf(final char[] toBeFound, final char[] array, final boolean isCaseSensitive, final int start) {
- return indexOf(toBeFound, array, isCaseSensitive, start, array.length);
-}
-
-/**
- * Answers the first index in the array for which the toBeFound array is a matching
- * subarray following the case rule starting at the index start. Answers -1 if no match is found.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * toBeFound = { 'c' }
- * array = { ' a', 'b', 'c', 'd' }
- * result => 2
- * </pre>
- * </li>
- * <li><pre>
- * toBeFound = { 'e' }
- * array = { ' a', 'b', 'c', 'd' }
- * result => -1
- * </pre>
- * </li>
- * </ol>
- *
- * @param toBeFound the subarray to search
- * @param array the array to be searched
- * @param isCaseSensitive flag to know if the matching should be case sensitive
- * @param start the starting index (inclusive)
- * @param end the end index (exclusive)
- * @return the first index in the array for which the toBeFound array is a matching
- * subarray following the case rule starting at the index start, -1 otherwise
- * @throws NullPointerException if array is null or toBeFound is null
- */
-public static final int indexOf(final char[] toBeFound, final char[] array, final boolean isCaseSensitive, final int start, final int end) {
- final int arrayLength = end;
- final int toBeFoundLength = toBeFound.length;
- if (toBeFoundLength > arrayLength) return -1;
- if (toBeFoundLength == 0) return 0;
- if (toBeFoundLength == arrayLength) {
- if (isCaseSensitive) {
- for (int i = start; i < arrayLength; i++) {
- if (array[i] != toBeFound[i]) return -1;
- }
- return 0;
- } else {
- for (int i = start; i < arrayLength; i++) {
- if (ScannerHelper.toLowerCase(array[i]) != ScannerHelper.toLowerCase(toBeFound[i])) return -1;
- }
- return 0;
- }
- }
- if (isCaseSensitive) {
- arrayLoop: for (int i = start, max = arrayLength - toBeFoundLength + 1; i < max; i++) {
- if (array[i] == toBeFound[0]) {
- for (int j = 1; j < toBeFoundLength; j++) {
- if (array[i + j] != toBeFound[j]) continue arrayLoop;
- }
- return i;
- }
- }
- } else {
- arrayLoop: for (int i = start, max = arrayLength - toBeFoundLength + 1; i < max; i++) {
- if (ScannerHelper.toLowerCase(array[i]) == ScannerHelper.toLowerCase(toBeFound[0])) {
- for (int j = 1; j < toBeFoundLength; j++) {
- if (ScannerHelper.toLowerCase(array[i + j]) != ScannerHelper.toLowerCase(toBeFound[j])) continue arrayLoop;
- }
- return i;
- }
- }
- }
- return -1;
-}
-
-/**
- * Answers the first index in the array for which the corresponding character is
- * equal to toBeFound starting the search at index start.
- * Answers -1 if no occurrence of this character is found.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * toBeFound = 'c'
- * array = { ' a', 'b', 'c', 'd' }
- * start = 2
- * result => 2
- * </pre>
- * </li>
- * <li><pre>
- * toBeFound = 'c'
- * array = { ' a', 'b', 'c', 'd' }
- * start = 3
- * result => -1
- * </pre>
- * </li>
- * <li><pre>
- * toBeFound = 'e'
- * array = { ' a', 'b', 'c', 'd' }
- * start = 1
- * result => -1
- * </pre>
- * </li>
- * </ol>
- *
- * @param toBeFound the character to search
- * @param array the array to be searched
- * @param start the starting index
- * @return the first index in the array for which the corresponding character is
- * equal to toBeFound, -1 otherwise
- * @throws NullPointerException if array is null
- * @throws ArrayIndexOutOfBoundsException if start is lower than 0
- */
-public static final int indexOf(char toBeFound, char[] array, int start) {
- for (int i = start; i < array.length; i++)
- if (toBeFound == array[i])
- return i;
- return -1;
-}
-
-/**
- * Answers the first index in the array for which the corresponding character is
- * equal to toBeFound starting the search at index start and before the ending index.
- * Answers -1 if no occurrence of this character is found.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * toBeFound = 'c'
- * array = { ' a', 'b', 'c', 'd' }
- * start = 2
- * result => 2
- * </pre>
- * </li>
- * <li><pre>
- * toBeFound = 'c'
- * array = { ' a', 'b', 'c', 'd' }
- * start = 3
- * result => -1
- * </pre>
- * </li>
- * <li><pre>
- * toBeFound = 'e'
- * array = { ' a', 'b', 'c', 'd' }
- * start = 1
- * result => -1
- * </pre>
- * </li>
- * </ol>
- *
- * @param toBeFound the character to search
- * @param array the array to be searched
- * @param start the starting index (inclusive)
- * @param end the ending index (exclusive)
- * @return the first index in the array for which the corresponding character is
- * equal to toBeFound, -1 otherwise
- * @throws NullPointerException if array is null
- * @throws ArrayIndexOutOfBoundsException if start is lower than 0 or ending greater than array length
- */
-public static final int indexOf(char toBeFound, char[] array, int start, int end) {
- for (int i = start; i < end; i++)
- if (toBeFound == array[i])
- return i;
- return -1;
-}
-
-/**
- * Answers the last index in the array for which the corresponding character is
- * equal to toBeFound starting from the end of the array.
- * Answers -1 if no occurrence of this character is found.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * toBeFound = 'c'
- * array = { ' a', 'b', 'c', 'd' , 'c', 'e' }
- * result => 4
- * </pre>
- * </li>
- * <li><pre>
- * toBeFound = 'e'
- * array = { ' a', 'b', 'c', 'd' }
- * result => -1
- * </pre>
- * </li>
- * </ol>
- *
- * @param toBeFound the character to search
- * @param array the array to be searched
- * @return the last index in the array for which the corresponding character is
- * equal to toBeFound starting from the end of the array, -1 otherwise
- * @throws NullPointerException if array is null
- */
-public static final int lastIndexOf(char toBeFound, char[] array) {
- for (int i = array.length; --i >= 0;)
- if (toBeFound == array[i])
- return i;
- return -1;
-}
-
-/**
- * Answers the last index in the array for which the corresponding character is
- * equal to toBeFound stopping at the index startIndex.
- * Answers -1 if no occurrence of this character is found.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * toBeFound = 'c'
- * array = { ' a', 'b', 'c', 'd' }
- * startIndex = 2
- * result => 2
- * </pre>
- * </li>
- * <li><pre>
- * toBeFound = 'c'
- * array = { ' a', 'b', 'c', 'd', 'e' }
- * startIndex = 3
- * result => -1
- * </pre>
- * </li>
- * <li><pre>
- * toBeFound = 'e'
- * array = { ' a', 'b', 'c', 'd' }
- * startIndex = 0
- * result => -1
- * </pre>
- * </li>
- * </ol>
- *
- * @param toBeFound the character to search
- * @param array the array to be searched
- * @param startIndex the stopping index
- * @return the last index in the array for which the corresponding character is
- * equal to toBeFound stopping at the index startIndex, -1 otherwise
- * @throws NullPointerException if array is null
- * @throws ArrayIndexOutOfBoundsException if startIndex is lower than 0
- */
-public static final int lastIndexOf(
- char toBeFound,
- char[] array,
- int startIndex) {
- for (int i = array.length; --i >= startIndex;)
- if (toBeFound == array[i])
- return i;
- return -1;
-}
-
-/**
- * Answers the last index in the array for which the corresponding character is
- * equal to toBeFound starting from endIndex to startIndex.
- * Answers -1 if no occurrence of this character is found.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * toBeFound = 'c'
- * array = { ' a', 'b', 'c', 'd' }
- * startIndex = 2
- * endIndex = 2
- * result => 2
- * </pre>
- * </li>
- * <li><pre>
- * toBeFound = 'c'
- * array = { ' a', 'b', 'c', 'd', 'e' }
- * startIndex = 3
- * endIndex = 4
- * result => -1
- * </pre>
- * </li>
- * <li><pre>
- * toBeFound = 'e'
- * array = { ' a', 'b', 'c', 'd' }
- * startIndex = 0
- * endIndex = 3
- * result => -1
- * </pre>
- * </li>
- * </ol>
- *
- * @param toBeFound the character to search
- * @param array the array to be searched
- * @param startIndex the stopping index
- * @param endIndex the starting index
- * @return the last index in the array for which the corresponding character is
- * equal to toBeFound starting from endIndex to startIndex, -1 otherwise
- * @throws NullPointerException if array is null
- * @throws ArrayIndexOutOfBoundsException if endIndex is greater or equals to array length or starting is lower than 0
- */
-public static final int lastIndexOf(
- char toBeFound,
- char[] array,
- int startIndex,
- int endIndex) {
- for (int i = endIndex; --i >= startIndex;)
- if (toBeFound == array[i])
- return i;
- return -1;
-}
-
-/**
- * Answers the last portion of a name given a separator.
- * <br>
- * <br>
- * For example,
- * <pre>
- * lastSegment("my.namespace.Object".toCharArray(),'.') --> Object
- * </pre>
- *
- * @param array the array
- * @param separator the given separator
- * @return the last portion of a name given a separator
- * @throws NullPointerException if array is null
- */
-final static public char[] lastSegment(char[] array, char separator) {
- int pos = lastIndexOf(separator, array);
- if (pos < 0)
- return array;
- return subarray(array, pos + 1, array.length);
-}
-
-/**
- * Answers true if the pattern matches the given name, false otherwise. This char[] pattern matching
- * accepts wild-cards '*' and '?'.
- *
- * When not case sensitive, the pattern is assumed to already be lowercased, the
- * name will be lowercased character per character as comparing.
- * If name is null, the answer is false.
- * If pattern is null, the answer is true if name is not null.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * pattern = { '?', 'b', '*' }
- * name = { 'a', 'b', 'c' , 'd' }
- * isCaseSensitive = true
- * result => true
- * </pre>
- * </li>
- * <li><pre>
- * pattern = { '?', 'b', '?' }
- * name = { 'a', 'b', 'c' , 'd' }
- * isCaseSensitive = true
- * result => false
- * </pre>
- * </li>
- * <li><pre>
- * pattern = { 'b', '*' }
- * name = { 'a', 'b', 'c' , 'd' }
- * isCaseSensitive = true
- * result => false
- * </pre>
- * </li>
- * </ol>
- *
- * @param pattern the given pattern
- * @param name the given name
- * @param isCaseSensitive flag to know whether or not the matching should be case sensitive
- * @return true if the pattern matches the given name, false otherwise
- */
-public static final boolean match(
- char[] pattern,
- char[] name,
- boolean isCaseSensitive) {
-
- if (name == null)
- return false; // null name cannot match
- if (pattern == null)
- return true; // null pattern is equivalent to '*'
-
- return match(
- pattern,
- 0,
- pattern.length,
- name,
- 0,
- name.length,
- isCaseSensitive);
-}
-
-/**
- * Answers true if a sub-pattern matches the subpart of the given name, false otherwise.
- * char[] pattern matching, accepting wild-cards '*' and '?'. Can match only subset of name/pattern.
- * end positions are non-inclusive.
- * The subpattern is defined by the patternStart and pattternEnd positions.
- * When not case sensitive, the pattern is assumed to already be lowercased, the
- * name will be lowercased character per character as comparing.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * pattern = { '?', 'b', '*' }
- * patternStart = 1
- * patternEnd = 3
- * name = { 'a', 'b', 'c' , 'd' }
- * nameStart = 1
- * nameEnd = 4
- * isCaseSensitive = true
- * result => true
- * </pre>
- * </li>
- * <li><pre>
- * pattern = { '?', 'b', '*' }
- * patternStart = 1
- * patternEnd = 2
- * name = { 'a', 'b', 'c' , 'd' }
- * nameStart = 1
- * nameEnd = 2
- * isCaseSensitive = true
- * result => false
- * </pre>
- * </li>
- * </ol>
- *
- * @param pattern the given pattern
- * @param patternStart the given pattern start
- * @param patternEnd the given pattern end
- * @param name the given name
- * @param nameStart the given name start
- * @param nameEnd the given name end
- * @param isCaseSensitive flag to know if the matching should be case sensitive
- * @return true if a sub-pattern matches the subpart of the given name, false otherwise
- */
-public static final boolean match(
- char[] pattern,
- int patternStart,
- int patternEnd,
- char[] name,
- int nameStart,
- int nameEnd,
- boolean isCaseSensitive) {
-
- if (name == null)
- return false; // null name cannot match
- if (pattern == null)
- return true; // null pattern is equivalent to '*'
- int iPattern = patternStart;
- int iName = nameStart;
-
- if (patternEnd < 0)
- patternEnd = pattern.length;
- if (nameEnd < 0)
- nameEnd = name.length;
-
- /* check first segment */
- char patternChar = 0;
- while ((iPattern < patternEnd)
- && (patternChar = pattern[iPattern]) != '*') {
- if (iName == nameEnd)
- return false;
- if ( (isCaseSensitive
- ? patternChar
- : ScannerHelper.toLowerCase(patternChar))
- != (isCaseSensitive
- ? name[iName]
- : ScannerHelper.toLowerCase(name[iName]))
- && patternChar != '?') {
- return false;
- }
- iName++;
- iPattern++;
- }
- /* check sequence of star+segment */
- int segmentStart;
- if (patternChar == '*') {
- segmentStart = ++iPattern; // skip star
- } else {
- segmentStart = 0; // force iName check
- }
- int prefixStart = iName;
- checkSegment : while (iName < nameEnd) {
- if (iPattern == patternEnd) {
- iPattern = segmentStart; // mismatch - restart current segment
- iName = ++prefixStart;
- continue checkSegment;
- }
- /* segment is ending */
- if ((patternChar = pattern[iPattern]) == '*') {
- segmentStart = ++iPattern; // skip start
- if (segmentStart == patternEnd) {
- return true;
- }
- prefixStart = iName;
- continue checkSegment;
- }
- /* check current name character */
- if ((isCaseSensitive ? name[iName] : ScannerHelper.toLowerCase(name[iName]))
- != patternChar
- && patternChar != '?') {
- iPattern = segmentStart; // mismatch - restart current segment
- iName = ++prefixStart;
- continue checkSegment;
- }
- iName++;
- iPattern++;
- }
-
- return (segmentStart == patternEnd)
- || (iName == nameEnd && iPattern == patternEnd)
- || (iPattern == patternEnd - 1 && pattern[iPattern] == '*');
-}
-
-/**
- * Answers true if the pattern matches the filepath using the pathSepatator, false otherwise.
- *
- * Path char[] pattern matching, accepting wild-cards '**', '*' and '?' (using Ant directory tasks
- * conventions, also see "http://jakarta.apache.org/ant/manual/dirtasks.html#defaultexcludes").
- * Path pattern matching is enhancing regular pattern matching in supporting extra rule where '**' represent
- * any folder combination.
- * Special rule:
- * - foo\ is equivalent to foo\**
- * When not case sensitive, the pattern is assumed to already be lowercased, the
- * name will be lowercased character per character as comparing.
- *
- * @param pattern the given pattern
- * @param filepath the given path
- * @param isCaseSensitive to find out whether or not the matching should be case sensitive
- * @param pathSeparator the given path separator
- * @return true if the pattern matches the filepath using the pathSepatator, false otherwise
- */
-public static final boolean pathMatch(
- char[] pattern,
- char[] filepath,
- boolean isCaseSensitive,
- char pathSeparator) {
-
- if (filepath == null)
- return false; // null name cannot match
- if (pattern == null)
- return true; // null pattern is equivalent to '*'
-
- // offsets inside pattern
- int pSegmentStart = pattern[0] == pathSeparator ? 1 : 0;
- int pLength = pattern.length;
- int pSegmentEnd = CharOperation.indexOf(pathSeparator, pattern, pSegmentStart+1);
- if (pSegmentEnd < 0) pSegmentEnd = pLength;
-
- // special case: pattern foo\ is equivalent to foo\**
- boolean freeTrailingDoubleStar = pattern[pLength - 1] == pathSeparator;
-
- // offsets inside filepath
- int fSegmentStart, fLength = filepath.length;
- if (filepath[0] != pathSeparator){
- fSegmentStart = 0;
- } else {
- fSegmentStart = 1;
- }
- if (fSegmentStart != pSegmentStart) {
- return false; // both must start with a separator or none.
- }
- int fSegmentEnd = CharOperation.indexOf(pathSeparator, filepath, fSegmentStart+1);
- if (fSegmentEnd < 0) fSegmentEnd = fLength;
-
- // first segments
- while (pSegmentStart < pLength
- && !(pSegmentEnd == pLength && freeTrailingDoubleStar
- || (pSegmentEnd == pSegmentStart + 2
- && pattern[pSegmentStart] == '*'
- && pattern[pSegmentStart + 1] == '*'))) {
-
- if (fSegmentStart >= fLength)
- return false;
- if (!CharOperation
- .match(
- pattern,
- pSegmentStart,
- pSegmentEnd,
- filepath,
- fSegmentStart,
- fSegmentEnd,
- isCaseSensitive)) {
- return false;
- }
-
- // jump to next segment
- pSegmentEnd =
- CharOperation.indexOf(
- pathSeparator,
- pattern,
- pSegmentStart = pSegmentEnd + 1);
- // skip separator
- if (pSegmentEnd < 0)
- pSegmentEnd = pLength;
-
- fSegmentEnd =
- CharOperation.indexOf(
- pathSeparator,
- filepath,
- fSegmentStart = fSegmentEnd + 1);
- // skip separator
- if (fSegmentEnd < 0) fSegmentEnd = fLength;
- }
-
- /* check sequence of doubleStar+segment */
- int pSegmentRestart;
- if ((pSegmentStart >= pLength && freeTrailingDoubleStar)
- || (pSegmentEnd == pSegmentStart + 2
- && pattern[pSegmentStart] == '*'
- && pattern[pSegmentStart + 1] == '*')) {
- pSegmentEnd =
- CharOperation.indexOf(
- pathSeparator,
- pattern,
- pSegmentStart = pSegmentEnd + 1);
- // skip separator
- if (pSegmentEnd < 0) pSegmentEnd = pLength;
- pSegmentRestart = pSegmentStart;
- } else {
- if (pSegmentStart >= pLength) return fSegmentStart >= fLength; // true if filepath is done too.
- pSegmentRestart = 0; // force fSegmentStart check
- }
- int fSegmentRestart = fSegmentStart;
- checkSegment : while (fSegmentStart < fLength) {
-
- if (pSegmentStart >= pLength) {
- if (freeTrailingDoubleStar) return true;
- // mismatch - restart current path segment
- pSegmentEnd =
- CharOperation.indexOf(pathSeparator, pattern, pSegmentStart = pSegmentRestart);
- if (pSegmentEnd < 0) pSegmentEnd = pLength;
-
- fSegmentRestart =
- CharOperation.indexOf(pathSeparator, filepath, fSegmentRestart + 1);
- // skip separator
- if (fSegmentRestart < 0) {
- fSegmentRestart = fLength;
- } else {
- fSegmentRestart++;
- }
- fSegmentEnd =
- CharOperation.indexOf(pathSeparator, filepath, fSegmentStart = fSegmentRestart);
- if (fSegmentEnd < 0) fSegmentEnd = fLength;
- continue checkSegment;
- }
-
- /* path segment is ending */
- if (pSegmentEnd == pSegmentStart + 2
- && pattern[pSegmentStart] == '*'
- && pattern[pSegmentStart + 1] == '*') {
- pSegmentEnd =
- CharOperation.indexOf(pathSeparator, pattern, pSegmentStart = pSegmentEnd + 1);
- // skip separator
- if (pSegmentEnd < 0) pSegmentEnd = pLength;
- pSegmentRestart = pSegmentStart;
- fSegmentRestart = fSegmentStart;
- if (pSegmentStart >= pLength) return true;
- continue checkSegment;
- }
- /* chech current path segment */
- if (!CharOperation.match(
- pattern,
- pSegmentStart,
- pSegmentEnd,
- filepath,
- fSegmentStart,
- fSegmentEnd,
- isCaseSensitive)) {
- // mismatch - restart current path segment
- pSegmentEnd =
- CharOperation.indexOf(pathSeparator, pattern, pSegmentStart = pSegmentRestart);
- if (pSegmentEnd < 0) pSegmentEnd = pLength;
-
- fSegmentRestart =
- CharOperation.indexOf(pathSeparator, filepath, fSegmentRestart + 1);
- // skip separator
- if (fSegmentRestart < 0) {
- fSegmentRestart = fLength;
- } else {
- fSegmentRestart++;
- }
- fSegmentEnd =
- CharOperation.indexOf(pathSeparator, filepath, fSegmentStart = fSegmentRestart);
- if (fSegmentEnd < 0) fSegmentEnd = fLength;
- continue checkSegment;
- }
- // jump to next segment
- pSegmentEnd =
- CharOperation.indexOf(
- pathSeparator,
- pattern,
- pSegmentStart = pSegmentEnd + 1);
- // skip separator
- if (pSegmentEnd < 0)
- pSegmentEnd = pLength;
-
- fSegmentEnd =
- CharOperation.indexOf(
- pathSeparator,
- filepath,
- fSegmentStart = fSegmentEnd + 1);
- // skip separator
- if (fSegmentEnd < 0)
- fSegmentEnd = fLength;
- }
-
- return (pSegmentRestart >= pSegmentEnd)
- || (fSegmentStart >= fLength && pSegmentStart >= pLength)
- || (pSegmentStart == pLength - 2
- && pattern[pSegmentStart] == '*'
- && pattern[pSegmentStart + 1] == '*')
- || (pSegmentStart == pLength && freeTrailingDoubleStar);
-}
-
-/**
- * Answers the number of occurrences of the given character in the given array, 0 if any.
- *
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * toBeFound = 'b'
- * array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
- * result => 3
- * </pre>
- * </li>
- * <li><pre>
- * toBeFound = 'c'
- * array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
- * result => 0
- * </pre>
- * </li>
- * </ol>
- *
- * @param toBeFound the given character
- * @param array the given array
- * @return the number of occurrences of the given character in the given array, 0 if any
- * @throws NullPointerException if array is null
- */
-public static final int occurencesOf(char toBeFound, char[] array) {
- int count = 0;
- for (int i = 0; i < array.length; i++)
- if (toBeFound == array[i])
- count++;
- return count;
-}
-
-/**
- * Answers the number of occurrences of the given character in the given array starting
- * at the given index, 0 if any.
- *
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * toBeFound = 'b'
- * array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
- * start = 2
- * result => 2
- * </pre>
- * </li>
- * <li><pre>
- * toBeFound = 'c'
- * array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
- * start = 0
- * result => 0
- * </pre>
- * </li>
- * </ol>
- *
- * @param toBeFound the given character
- * @param array the given array
- * @param start the given index
- * @return the number of occurrences of the given character in the given array, 0 if any
- * @throws NullPointerException if array is null
- * @throws ArrayIndexOutOfBoundsException if start is lower than 0
- */
-public static final int occurencesOf(
- char toBeFound,
- char[] array,
- int start) {
- int count = 0;
- for (int i = start; i < array.length; i++)
- if (toBeFound == array[i])
- count++;
- return count;
-}
-
-/**
- * Answers true if the given name starts with the given prefix, false otherwise.
- * The comparison is case sensitive.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * prefix = { 'a' , 'b' }
- * name = { 'a' , 'b', 'b', 'a', 'b', 'a' }
- * result => true
- * </pre>
- * </li>
- * <li><pre>
- * prefix = { 'a' , 'c' }
- * name = { 'a' , 'b', 'b', 'a', 'b', 'a' }
- * result => false
- * </pre>
- * </li>
- * </ol>
- *
- * @param prefix the given prefix
- * @param name the given name
- * @return true if the given name starts with the given prefix, false otherwise
- * @throws NullPointerException if the given name is null or if the given prefix is null
- */
-public static final boolean prefixEquals(char[] prefix, char[] name) {
-
- int max = prefix.length;
- if (name.length < max)
- return false;
- for (int i = max;
- --i >= 0;
- ) // assumes the prefix is not larger than the name
- if (prefix[i] != name[i])
- return false;
- return true;
-}
-
-/**
- * Answers true if the given name starts with the given prefix, false otherwise.
- * isCaseSensitive is used to find out whether or not the comparison should be case sensitive.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * prefix = { 'a' , 'B' }
- * name = { 'a' , 'b', 'b', 'a', 'b', 'a' }
- * isCaseSensitive = false
- * result => true
- * </pre>
- * </li>
- * <li><pre>
- * prefix = { 'a' , 'B' }
- * name = { 'a' , 'b', 'b', 'a', 'b', 'a' }
- * isCaseSensitive = true
- * result => false
- * </pre>
- * </li>
- * </ol>
- *
- * @param prefix the given prefix
- * @param name the given name
- * @param isCaseSensitive to find out whether or not the comparison should be case sensitive
- * @return true if the given name starts with the given prefix, false otherwise
- * @throws NullPointerException if the given name is null or if the given prefix is null
- */
-public static final boolean prefixEquals(
- char[] prefix,
- char[] name,
- boolean isCaseSensitive) {
-
- int max = prefix.length;
- if (name.length < max)
- return false;
- if (isCaseSensitive) {
- for (int i = max;
- --i >= 0;
- ) // assumes the prefix is not larger than the name
- if (prefix[i] != name[i])
- return false;
- return true;
- }
-
- for (int i = max;
- --i >= 0;
- ) // assumes the prefix is not larger than the name
- if (ScannerHelper.toLowerCase(prefix[i])
- != ScannerHelper.toLowerCase(name[i]))
- return false;
- return true;
-}
-
-/**
- * Answers a new array removing a given character. Answers the given array if there is
- * no occurence of the character to remove.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * array = { 'a' , 'b', 'b', 'c', 'b', 'a' }
- * toBeRemoved = 'b'
- * return { 'a' , 'c', 'a' }
- * </pre>
- * </li>
- * <li><pre>
- * array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
- * toBeRemoved = 'c'
- * return array
- * </pre>
- * </li>
- * </ol>
- *
- * @param array the given array
- * @param toBeRemoved the character to be removed
- * @return a new array removing given character
- */
-public static final char[] remove(char[] array, char toBeRemoved) {
-
- if (array == null) return null;
- int length = array.length;
- if (length == 0) return array;
- char[] result = null;
- int count = 0;
- for (int i = 0; i < length; i++) {
- char c = array[i];
- if (c == toBeRemoved) {
- if (result == null) {
- result = new char[length];
- System.arraycopy(array, 0, result, 0, i);
- count = i;
- }
- } else if (result != null) {
- result[count++] = c;
- }
- }
- if (result == null) return array;
- System.arraycopy(result, 0, result = new char[count], 0, count);
- return result;
-}
-
-/**
- * Replace all occurrence of the character to be replaced with the replacement character in the
- * given array.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
- * toBeReplaced = 'b'
- * replacementChar = 'a'
- * result => No returned value, but array is now equals to { 'a' , 'a', 'a', 'a', 'a', 'a' }
- * </pre>
- * </li>
- * <li><pre>
- * array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
- * toBeReplaced = 'c'
- * replacementChar = 'a'
- * result => No returned value, but array is now equals to { 'a' , 'b', 'b', 'a', 'b', 'a' }
- * </pre>
- * </li>
- * </ol>
- *
- * @param array the given array
- * @param toBeReplaced the character to be replaced
- * @param replacementChar the replacement character
- * @throws NullPointerException if the given array is null
- */
-public static final void replace(
- char[] array,
- char toBeReplaced,
- char replacementChar) {
- if (toBeReplaced != replacementChar) {
- for (int i = 0, max = array.length; i < max; i++) {
- if (array[i] == toBeReplaced)
- array[i] = replacementChar;
- }
- }
-}
-
-/**
- * Replace all occurrences of characters to be replaced with the replacement character in the
- * given array.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * array = { 'a' , 'b', 'b', 'c', 'a', 'b', 'c', 'a' }
- * toBeReplaced = { 'b', 'c' }
- * replacementChar = 'a'
- * result => No returned value, but array is now equals to { 'a' , 'a', 'a', 'a', 'a', 'a', 'a', 'a' }
- * </pre>
- * </li>
- * </ol>
- *
- * @param array the given array
- * @param toBeReplaced characters to be replaced
- * @param replacementChar the replacement character
- * @throws NullPointerException if arrays are null.
- */
-public static final void replace(char[] array, char[] toBeReplaced, char replacementChar) {
- replace(array, toBeReplaced, replacementChar, 0, array.length);
-}
-
-/**
- * Replace all occurrences of characters to be replaced with the replacement character in the
- * given array from the start position (inclusive) to the end position (exclusive).
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * array = { 'a' , 'b', 'b', 'c', 'a', 'b', 'c', 'a' }
- * toBeReplaced = { 'b', 'c' }
- * replacementChar = 'a'
- * start = 4
- * end = 8
- * result => No returned value, but array is now equals to { 'a' , 'b', 'b', 'c', 'a', 'a', 'a', 'a' }
- * </pre>
- * </li>
- * </ol>
- *
- * @param array the given array
- * @param toBeReplaced characters to be replaced
- * @param replacementChar the replacement character
- * @param start the given start position (inclusive)
- * @param end the given end position (exclusive)
- * @throws NullPointerException if arrays are null.
- */
-public static final void replace(char[] array, char[] toBeReplaced, char replacementChar, int start, int end) {
- for (int i = end; --i >= start;)
- for (int j = toBeReplaced.length; --j >= 0;)
- if (array[i] == toBeReplaced[j])
- array[i] = replacementChar;
-}
-/**
- * Answers a new array of characters with substitutions. No side-effect is operated on the original
- * array, in case no substitution happened, then the result is the same as the
- * original one.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
- * toBeReplaced = { 'b' }
- * replacementChar = { 'a', 'a' }
- * result => { 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a' }
- * </pre>
- * </li>
- * <li><pre>
- * array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
- * toBeReplaced = { 'c' }
- * replacementChar = { 'a' }
- * result => { 'a' , 'b', 'b', 'a', 'b', 'a' }
- * </pre>
- * </li>
- * </ol>
- *
- * @param array the given array
- * @param toBeReplaced characters to be replaced
- * @param replacementChars the replacement characters
- * @return a new array of characters with substitutions or the given array if none
- * @throws NullPointerException if the given array is null
- */
-public static final char[] replace(
- char[] array,
- char[] toBeReplaced,
- char[] replacementChars) {
-
- int max = array.length;
- int replacedLength = toBeReplaced.length;
- int replacementLength = replacementChars.length;
-
- int[] starts = new int[5];
- int occurrenceCount = 0;
-
- if (!equals(toBeReplaced, replacementChars)) {
-
- next : for (int i = 0; i < max;) {
- int index = indexOf(toBeReplaced, array, true, i);
- if (index == -1) {
- i++;
- continue next;
- }
- if (occurrenceCount == starts.length) {
- System.arraycopy(
- starts,
- 0,
- starts = new int[occurrenceCount * 2],
- 0,
- occurrenceCount);
- }
- starts[occurrenceCount++] = index;
- i = index + replacedLength;
- }
- }
- if (occurrenceCount == 0)
- return array;
- char[] result =
- new char[max
- + occurrenceCount * (replacementLength - replacedLength)];
- int inStart = 0, outStart = 0;
- for (int i = 0; i < occurrenceCount; i++) {
- int offset = starts[i] - inStart;
- System.arraycopy(array, inStart, result, outStart, offset);
- inStart += offset;
- outStart += offset;
- System.arraycopy(
- replacementChars,
- 0,
- result,
- outStart,
- replacementLength);
- inStart += replacedLength;
- outStart += replacementLength;
- }
- System.arraycopy(array, inStart, result, outStart, max - inStart);
- return result;
-}
-
-/**
- * Replace all occurrence of the character to be replaced with the replacement character
- * in a copy of the given array. Returns the given array if no occurrences of the character
- * to be replaced are found.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
- * toBeReplaced = 'b'
- * replacementChar = 'a'
- * result => A new array that is equals to { 'a' , 'a', 'a', 'a', 'a', 'a' }
- * </pre>
- * </li>
- * <li><pre>
- * array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
- * toBeReplaced = 'c'
- * replacementChar = 'a'
- * result => The original array that remains unchanged.
- * </pre>
- * </li>
- * </ol>
- *
- * @param array the given array
- * @param toBeReplaced the character to be replaced
- * @param replacementChar the replacement character
- * @throws NullPointerException if the given array is null
- */
-public static final char[] replaceOnCopy(
- char[] array,
- char toBeReplaced,
- char replacementChar) {
-
- char[] result = null;
- for (int i = 0, length = array.length; i < length; i++) {
- char c = array[i];
- if (c == toBeReplaced) {
- if (result == null) {
- result = new char[length];
- System.arraycopy(array, 0, result, 0, i);
- }
- result[i] = replacementChar;
- } else if (result != null) {
- result[i] = c;
- }
- }
- if (result == null) return array;
- return result;
-}
-
-/**
- * Return a new array which is the split of the given array using the given divider and triming each subarray to remove
- * whitespaces equals to ' '.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * divider = 'b'
- * array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
- * result => { { 'a' }, { }, { 'a' }, { 'a' } }
- * </pre>
- * </li>
- * <li><pre>
- * divider = 'c'
- * array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
- * result => { { 'a', 'b', 'b', 'a', 'b', 'a' } }
- * </pre>
- * </li>
- * <li><pre>
- * divider = 'b'
- * array = { 'a' , ' ', 'b', 'b', 'a', 'b', 'a' }
- * result => { { 'a' }, { }, { 'a' }, { 'a' } }
- * </pre>
- * </li>
- * <li><pre>
- * divider = 'c'
- * array = { ' ', ' ', 'a' , 'b', 'b', 'a', 'b', 'a', ' ' }
- * result => { { 'a', 'b', 'b', 'a', 'b', 'a' } }
- * </pre>
- * </li>
- * </ol>
- *
- * @param divider the given divider
- * @param array the given array
- * @return a new array which is the split of the given array using the given divider and triming each subarray to remove
- * whitespaces equals to ' '
- */
-public static final char[][] splitAndTrimOn(char divider, char[] array) {
- int length = array == null ? 0 : array.length;
- if (length == 0)
- return NO_CHAR_CHAR;
-
- int wordCount = 1;
- for (int i = 0; i < length; i++)
- if (array[i] == divider)
- wordCount++;
- char[][] split = new char[wordCount][];
- int last = 0, currentWord = 0;
- for (int i = 0; i < length; i++) {
- if (array[i] == divider) {
- int start = last, end = i - 1;
- while (start < i && array[start] == ' ')
- start++;
- while (end > start && array[end] == ' ')
- end--;
- split[currentWord] = new char[end - start + 1];
- System.arraycopy(
- array,
- start,
- split[currentWord++],
- 0,
- end - start + 1);
- last = i + 1;
- }
- }
- int start = last, end = length - 1;
- while (start < length && array[start] == ' ')
- start++;
- while (end > start && array[end] == ' ')
- end--;
- split[currentWord] = new char[end - start + 1];
- System.arraycopy(
- array,
- start,
- split[currentWord++],
- 0,
- end - start + 1);
- return split;
-}
-
-/**
- * Return a new array which is the split of the given array using the given divider.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * divider = 'b'
- * array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
- * result => { { 'a' }, { }, { 'a' }, { 'a' } }
- * </pre>
- * </li>
- * <li><pre>
- * divider = 'c'
- * array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
- * result => { { 'a', 'b', 'b', 'a', 'b', 'a' } }
- * </pre>
- * </li>
- * <li><pre>
- * divider = 'c'
- * array = { ' ', ' ', 'a' , 'b', 'b', 'a', 'b', 'a', ' ' }
- * result => { { ' ', 'a', 'b', 'b', 'a', 'b', 'a', ' ' } }
- * </pre>
- * </li>
- * </ol>
- *
- * @param divider the given divider
- * @param array the given array
- * @return a new array which is the split of the given array using the given divider
- */
-public static final char[][] splitOn(char divider, char[] array) {
- int length = array == null ? 0 : array.length;
- if (length == 0)
- return NO_CHAR_CHAR;
-
- int wordCount = 1;
- for (int i = 0; i < length; i++)
- if (array[i] == divider)
- wordCount++;
- char[][] split = new char[wordCount][];
- int last = 0, currentWord = 0;
- for (int i = 0; i < length; i++) {
- if (array[i] == divider) {
- split[currentWord] = new char[i - last];
- System.arraycopy(
- array,
- last,
- split[currentWord++],
- 0,
- i - last);
- last = i + 1;
- }
- }
- split[currentWord] = new char[length - last];
- System.arraycopy(array, last, split[currentWord], 0, length - last);
- return split;
-}
-
-/**
- * Return a new array which is the split of the given array using the given divider. The given end
- * is exclusive and the given start is inclusive.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * divider = 'b'
- * array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
- * start = 2
- * end = 5
- * result => { { }, { 'a' }, { } }
- * </pre>
- * </li>
- * </ol>
- *
- * @param divider the given divider
- * @param array the given array
- * @param start the given starting index
- * @param end the given ending index
- * @return a new array which is the split of the given array using the given divider
- * @throws ArrayIndexOutOfBoundsException if start is lower than 0 or end is greater than the array length
- */
-public static final char[][] splitOn(
- char divider,
- char[] array,
- int start,
- int end) {
- int length = array == null ? 0 : array.length;
- if (length == 0 || start > end)
- return NO_CHAR_CHAR;
-
- int wordCount = 1;
- for (int i = start; i < end; i++)
- if (array[i] == divider)
- wordCount++;
- char[][] split = new char[wordCount][];
- int last = start, currentWord = 0;
- for (int i = start; i < end; i++) {
- if (array[i] == divider) {
- split[currentWord] = new char[i - last];
- System.arraycopy(
- array,
- last,
- split[currentWord++],
- 0,
- i - last);
- last = i + 1;
- }
- }
- split[currentWord] = new char[end - last];
- System.arraycopy(array, last, split[currentWord], 0, end - last);
- return split;
-}
-
-/**
- * Answers a new array which is a copy of the given array starting at the given start and
- * ending at the given end. The given start is inclusive and the given end is exclusive.
- * Answers null if start is greater than end, if start is lower than 0 or if end is greater
- * than the length of the given array. If end equals -1, it is converted to the array length.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * array = { { 'a' } , { 'b' } }
- * start = 0
- * end = 1
- * result => { { 'a' } }
- * </pre>
- * </li>
- * <li><pre>
- * array = { { 'a' } , { 'b' } }
- * start = 0
- * end = -1
- * result => { { 'a' }, { 'b' } }
- * </pre>
- * </li>
- * </ol>
- *
- * @param array the given array
- * @param start the given starting index
- * @param end the given ending index
- * @return a new array which is a copy of the given array starting at the given start and
- * ending at the given end
- * @throws NullPointerException if the given array is null
- */
-public static final char[][] subarray(char[][] array, int start, int end) {
- if (end == -1)
- end = array.length;
- if (start > end)
- return null;
- if (start < 0)
- return null;
- if (end > array.length)
- return null;
-
- char[][] result = new char[end - start][];
- System.arraycopy(array, start, result, 0, end - start);
- return result;
-}
-
-/**
- * Answers a new array which is a copy of the given array starting at the given start and
- * ending at the given end. The given start is inclusive and the given end is exclusive.
- * Answers null if start is greater than end, if start is lower than 0 or if end is greater
- * than the length of the given array. If end equals -1, it is converted to the array length.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * array = { 'a' , 'b' }
- * start = 0
- * end = 1
- * result => { 'a' }
- * </pre>
- * </li>
- * <li><pre>
- * array = { 'a', 'b' }
- * start = 0
- * end = -1
- * result => { 'a' , 'b' }
- * </pre>
- * </li>
- * </ol>
- *
- * @param array the given array
- * @param start the given starting index
- * @param end the given ending index
- * @return a new array which is a copy of the given array starting at the given start and
- * ending at the given end
- * @throws NullPointerException if the given array is null
- */
-public static final char[] subarray(char[] array, int start, int end) {
- if (end == -1)
- end = array.length;
- if (start > end)
- return null;
- if (start < 0)
- return null;
- if (end > array.length)
- return null;
-
- char[] result = new char[end - start];
- System.arraycopy(array, start, result, 0, end - start);
- return result;
-}
-
-/**
- * Answers the result of a char[] conversion to lowercase. Answers null if the given chars array is null.
- * <br>
- * NOTE: If no conversion was necessary, then answers back the argument one.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * chars = { 'a' , 'b' }
- * result => { 'a' , 'b' }
- * </pre>
- * </li>
- * <li><pre>
- * array = { 'A', 'b' }
- * result => { 'a' , 'b' }
- * </pre>
- * </li>
- * </ol>
- *
- * @param chars the chars to convert
- * @return the result of a char[] conversion to lowercase
- */
-final static public char[] toLowerCase(char[] chars) {
- if (chars == null)
- return null;
- int length = chars.length;
- char[] lowerChars = null;
- for (int i = 0; i < length; i++) {
- char c = chars[i];
- char lc = ScannerHelper.toLowerCase(c);
- if ((c != lc) || (lowerChars != null)) {
- if (lowerChars == null) {
- System.arraycopy(
- chars,
- 0,
- lowerChars = new char[length],
- 0,
- i);
- }
- lowerChars[i] = lc;
- }
- }
- return lowerChars == null ? chars : lowerChars;
-}
-
-/**
- * Answers a new array removing leading and trailing spaces (' '). Answers the given array if there is no
- * space characters to remove.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * chars = { ' ', 'a' , 'b', ' ', ' ' }
- * result => { 'a' , 'b' }
- * </pre>
- * </li>
- * <li><pre>
- * array = { 'A', 'b' }
- * result => { 'A' , 'b' }
- * </pre>
- * </li>
- * </ol>
- *
- * @param chars the given array
- * @return a new array removing leading and trailing spaces (' ')
- */
-final static public char[] trim(char[] chars) {
-
- if (chars == null)
- return null;
-
- int start = 0, length = chars.length, end = length - 1;
- while (start < length && chars[start] == ' ') {
- start++;
- }
- while (end > start && chars[end] == ' ') {
- end--;
- }
- if (start != 0 || end != length - 1) {
- return subarray(chars, start, end + 1);
- }
- return chars;
-}
-
-/**
- * Answers a string which is the concatenation of the given array using the '.' as a separator.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * array = { { 'a' } , { 'b' } }
- * result => "a.b"
- * </pre>
- * </li>
- * <li><pre>
- * array = { { ' ', 'a' } , { 'b' } }
- * result => " a.b"
- * </pre>
- * </li>
- * </ol>
- *
- * @param array the given array
- * @return a string which is the concatenation of the given array using the '.' as a separator
- */
-final static public String toString(char[][] array) {
- char[] result = concatWith(array, '.');
- return new String(result);
-}
-
-/**
- * Answers an array of strings from the given array of char array.
- *
- * @param array the given array
- * @return an array of strings
- */
-final static public String[] toStrings(char[][] array) {
- if (array == null) return NO_STRINGS;
- int length = array.length;
- if (length == 0) return NO_STRINGS;
- String[] result = new String[length];
- for (int i = 0; i < length; i++)
- result[i] = new String(array[i]);
- return result;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/IProblem.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/IProblem.java
deleted file mode 100644
index 9f82ccfa..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/IProblem.java
+++ /dev/null
@@ -1,719 +0,0 @@
-/*******************************************************************************
- * 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
- * IBM Corporation - added the following constants
- * NonStaticAccessToStaticField
- * NonStaticAccessToStaticMethod
- * Task
- * ExpressionShouldBeAVariable
- * AssignmentHasNoEffect
- * IBM Corporation - added the following constants
- * TooManyArrayDimensions
- * TooManyBytesForStringConstant
- * TooManyMethods
- * TooManyFields
- * NonBlankFinalLocalAssignment
- * ObjectCannotHaveSuperTypes
- * MissingSemiColon
- * InvalidParenthesizedExpression
- * EnclosingInstanceInConstructorCall
- * BytecodeExceeds64KLimitForConstructor
- * IncompatibleReturnTypeForNonInheritedInterfaceMethod
- * UnusedPrivateMethod
- * UnusedPrivateConstructor
- * UnusedPrivateType
- * UnusedPrivateField
- * IncompatibleExceptionInThrowsClauseForNonInheritedInterfaceMethod
- * InvalidExplicitConstructorCall
- * IBM Corporation - added the following constants
- * PossibleAccidentalBooleanAssignment
- * SuperfluousSemicolon
- * IndirectAccessToStaticField
- * IndirectAccessToStaticMethod
- * IndirectAccessToStaticType
- * BooleanMethodThrowingException
- * UnnecessaryCast
- * UnnecessaryArgumentCast
- * UnnecessaryInstanceof
- * FinallyMustCompleteNormally
- * UnusedMethodDeclaredThrownException
- * UnusedConstructorDeclaredThrownException
- * InvalidCatchBlockSequence
- * UnqualifiedFieldAccess
- * IBM Corporation - added the following constants
- * Javadoc
- * JavadocUnexpectedTag
- * JavadocMissingParamTag
- * JavadocMissingParamName
- * JavadocDuplicateParamName
- * JavadocInvalidParamName
- * JavadocMissingReturnTag
- * JavadocDuplicateReturnTag
- * JavadocMissingThrowsTag
- * JavadocMissingThrowsClassName
- * JavadocInvalidThrowsClass
- * JavadocDuplicateThrowsClassName
- * JavadocInvalidThrowsClassName
- * JavadocMissingSeeReference
- * JavadocInvalidSeeReference
- * JavadocInvalidSeeHref
- * JavadocInvalidSeeArgs
- * JavadocMissing
- * JavadocInvalidTag
- * JavadocMessagePrefix
- * EmptyControlFlowStatement
- * IBM Corporation - added the following constants
- * IllegalUsageOfQualifiedTypeReference
- * InvalidDigit
- * IBM Corporation - added the following constants
- * ParameterAssignment
- * FallthroughCase
- * IBM Corporation - added the following constants
- * UnusedLabel
- * UnnecessaryNLSTag
- * LocalVariableMayBeNull
- * EnumConstantsCannotBeSurroundedByParenthesis
- * JavadocMissingIdentifier
- * JavadocNonStaticTypeFromStaticInvocation
- * RawTypeReference
- * NoAdditionalBoundAfterTypeVariable
- * UnsafeGenericArrayForVarargs
- * IllegalAccessFromTypeVariable
- * InvalidEncoding
- * CannotReadSource
- * ExternalProblemNotFixable
- * ExternalProblemFixable
- * IBM Corporation - added the following constants
- * OverridingMethodWithoutSuperInvocation
- * MethodMustOverrideOrImplement
- * TypeHidingTypeParameterFromType
- * TypeHidingTypeParameterFromMethod
- * TypeHidingType
- * IBM Corporation - added the following constants
- * NullLocalVariableReference
- * PotentialNullLocalVariableReference
- * RedundantNullCheckOnNullLocalVariable
- * NullLocalVariableComparisonYieldsFalse
- * RedundantLocalVariableNullAssignment
- * NullLocalVariableInstanceofYieldsFalse
- * RedundantNullCheckOnNonNullLocalVariable
- * NonNullLocalVariableComparisonYieldsFalse
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.compiler;
-
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ProblemReasons;
-
-/**
- * Description of a JavaScript problem, as detected by the validator
- * A problem provides access to:
- * <ul>
- * <li> its location (originating source file name, source position, line number), </li>
- * <li> its message description and a predicate to check its severity (warning or error). </li>
- * <li> its ID : a number identifying the very nature of this problem. All possible IDs are listed
- * as constants on this interface. </li>
- * </ul>
- *
- * Note: the validator produces IProblems internally, which are turned into markers by the JavaScriptBuilder
- * so as to persist problem descriptions. This explains why there is no API allowing to reach IProblem detected
- * when compiling. However, the JavaScript problem markers carry equivalent information to IProblem, in particular
- * their ID (attribute "id") is set to one of the IDs defined on this interface.
- *
- * 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 IProblem {
-
-/**
- * Answer back the original arguments recorded into the problem.
- * @return the original arguments recorded into the problem
- */
-String[] getArguments();
-
-/**
- * Returns the problem id
- *
- * @return the problem id
- */
-int getID();
-
-/**
- * Answer a localized, human-readable message string which describes the problem.
- *
- * @return a localized, human-readable message string which describes the problem
- */
-String getMessage();
-
-/**
- * Answer the file name in which the problem was found.
- *
- * @return the file name in which the problem was found
- */
-char[] getOriginatingFileName();
-
-/**
- * Answer the end position of the problem (inclusive), or -1 if unknown.
- *
- * @return the end position of the problem (inclusive), or -1 if unknown
- */
-int getSourceEnd();
-
-/**
- * Answer the line number in source where the problem begins.
- *
- * @return the line number in source where the problem begins
- */
-int getSourceLineNumber();
-
-/**
- * Answer the start position of the problem (inclusive), or -1 if unknown.
- *
- * @return the start position of the problem (inclusive), or -1 if unknown
- */
-int getSourceStart();
-
-/**
- * Checks the severity to see if the Error bit is set.
- *
- * @return true if the Error bit is set for the severity, false otherwise
- */
-boolean isError();
-
-/**
- * Checks the severity to see if the Error bit is not set.
- *
- * @return true if the Error bit is not set for the severity, false otherwise
- */
-boolean isWarning();
-
-/**
- * Set the end position of the problem (inclusive), or -1 if unknown.
- * Used for shifting problem positions.
- *
- * @param sourceEnd the given end position
- */
-void setSourceEnd(int sourceEnd);
-
-/**
- * Set the line number in source where the problem begins.
- *
- * @param lineNumber the given line number
- */
-void setSourceLineNumber(int lineNumber);
-
-/**
- * Set the start position of the problem (inclusive), or -1 if unknown.
- * Used for shifting problem positions.
- *
- * @param sourceStart the given start position
- */
-void setSourceStart(int sourceStart);
-
-
- /**
- * Problem Categories
- * The high bits of a problem ID contains information about the category of a problem.
- * For example, (problemID & TypeRelated) != 0, indicates that this problem is type related.
- *
- * A problem category can help to implement custom problem filters. Indeed, when numerous problems
- * are listed, focusing on import related problems first might be relevant.
- *
- * When a problem is tagged as Internal, it means that no change other than a local source code change
- * can fix the corresponding problem. A type related problem could be addressed by changing the type
- * involved in it.
- */
- int TypeRelated = 0x01000000;
- int FieldRelated = 0x02000000;
- int MethodRelated = 0x04000000;
- int ConstructorRelated = 0x08000000;
- int ImportRelated = 0x10000000;
- int Internal = 0x20000000;
- int Syntax = 0x40000000;
- int Javadoc = 0x80000000;
-
- /**
- * Mask to use in order to filter out the category portion of the problem ID.
- */
- int IgnoreCategoriesMask = 0xFFFFFF;
-
- /**
- * Below are listed all available problem IDs. Note that this list could be augmented in the future,
- * as new features are added to the JavaScript core implementation.
- */
-
- /**
- * ID reserved for referencing an internal error inside the JavaScriptCore implementation which
- * may be surfaced as a problem associated with the javaScript unit which caused it to occur.
- */
- int Unclassified = 0;
-
- /**
- * General type related problems
- */
- int UndefinedType = TypeRelated + 2;
- int NotVisibleType = TypeRelated + 3;
- int AmbiguousType = TypeRelated + 4;
- int UsingDeprecatedType = TypeRelated + 5;
- int InternalTypeNameProvided = TypeRelated + 6;
- int UnusedPrivateType = Internal + TypeRelated + 7;
-
- int IncompatibleTypesInEqualityOperator = TypeRelated + 15;
- int IncompatibleTypesInConditionalOperator = TypeRelated + 16;
- int TypeMismatch = TypeRelated + 17;
- int IndirectAccessToStaticType = Internal + TypeRelated + 18;
-
- /**
- * Inner types related problems
- */
- int MissingEnclosingInstanceForConstructorCall = TypeRelated + 20;
- int MissingEnclosingInstance = TypeRelated + 21;
- int IncorrectEnclosingInstanceReference = TypeRelated + 22;
- int IllegalEnclosingInstanceSpecification = TypeRelated + 23;
- int CannotDefineStaticInitializerInLocalType = Internal + 24;
- int OuterLocalMustBeFinal = Internal + 25;
- int IllegalPrimitiveOrArrayTypeForEnclosingInstance = TypeRelated + 27;
- int EnclosingInstanceInConstructorCall = Internal + 28;
- int TypeHidingType = TypeRelated + 33;
-
-
- // variables
- int UndefinedName = Internal + FieldRelated + 50;
- int UninitializedLocalVariable = Internal + 51;
- int VariableTypeCannotBeVoid = Internal + 52;
- int CannotAllocateVoidArray = Internal + 54;
- // local variables
- int RedefinedLocal = Internal + 55;
- int RedefinedArgument = Internal + 56;
- // final local variables
- int DuplicateFinalLocalInitialization = Internal + 57;
- int NonBlankFinalLocalAssignment = Internal + 58;
- int ParameterAssignment = Internal + 59;
- int FinalOuterLocalAssignment = Internal + 60;
- int LocalVariableIsNeverUsed = Internal + 61;
- int ArgumentIsNeverUsed = Internal + 62;
- int BytecodeExceeds64KLimit = Internal + 63;
- int BytecodeExceeds64KLimitForClinit = Internal + 64;
- int TooManyArgumentSlots = Internal + 65;
- int TooManyLocalVariableSlots = Internal + 66;
- int TooManyArrayDimensions = Internal + 68;
- int BytecodeExceeds64KLimitForConstructor = Internal + 69;
-
- // fields
- int UndefinedField = FieldRelated + 70;
- int NotVisibleField = FieldRelated + 71;
- int AmbiguousField = FieldRelated + 72;
- int UsingDeprecatedField = FieldRelated + 73;
- int NonStaticFieldFromStaticInvocation = FieldRelated + 74;
- int ReferenceToForwardField = FieldRelated + Internal + 75;
- int NonStaticAccessToStaticField = Internal + FieldRelated + 76;
- int UnusedPrivateField = Internal + FieldRelated + 77;
- int IndirectAccessToStaticField = Internal + FieldRelated + 78;
- int UnqualifiedFieldAccess = Internal + FieldRelated + 79;
-
- // blank final fields
- int FinalFieldAssignment = FieldRelated + 80;
- int UninitializedBlankFinalField = FieldRelated + 81;
- int DuplicateBlankFinalFieldInitialization = FieldRelated + 82;
-
- // variable hiding
- int LocalVariableHidingLocalVariable = Internal + 90;
- int LocalVariableHidingField = Internal + FieldRelated + 91;
- int FieldHidingLocalVariable = Internal + FieldRelated + 92;
- int FieldHidingField = Internal + FieldRelated + 93;
- int ArgumentHidingLocalVariable = Internal + 94;
- int ArgumentHidingField = Internal + 95;
- /* START -------------------------------- Bug 197884 Loosly defined var (for statement) and optional semi-colon --------------------- */
- int LooseVarDecl = Internal + 97;
- /* END -------------------------------- Bug 197884 Loosly defined var (for statement) and optional semi-colon --------------------- */
- int UninitializedGlobalVariable = Internal + 98;
-
- // methods
- int UndefinedMethod = MethodRelated + 100;
- int NotVisibleMethod = MethodRelated + 101;
- int AmbiguousMethod = MethodRelated + 102;
- int UsingDeprecatedMethod = MethodRelated + 103;
- int DirectInvocationOfAbstractMethod = MethodRelated + 104;
- int VoidMethodReturnsValue = MethodRelated + 105;
- int MethodReturnsVoid = MethodRelated + 106;
- int MethodRequiresBody = Internal + MethodRelated + 107;
- int ShouldReturnValue = Internal + MethodRelated + 108;
- int UndefinedFunction = MethodRelated + 109;
- int MethodButWithConstructorName = MethodRelated + 110;
- int MissingReturnType = TypeRelated + 111;
- int BodyForNativeMethod = Internal + MethodRelated + 112;
- int BodyForAbstractMethod = Internal + MethodRelated + 113;
- int NoMessageSendOnBaseType = MethodRelated + 114;
- int ParameterMismatch = MethodRelated + 115;
- int NoMessageSendOnArrayType = MethodRelated + 116;
- int NonStaticAccessToStaticMethod = Internal + MethodRelated + 117;
- int UnusedPrivateMethod = Internal + MethodRelated + 118;
- int IndirectAccessToStaticMethod = Internal + MethodRelated + 119;
- int WrongNumberOfArguments = Internal + MethodRelated + 120;
- int NotAFunction = Internal + MethodRelated + 121;
-
- // constructors
- int UndefinedConstructor = ConstructorRelated + 130;
- int NotVisibleConstructor = ConstructorRelated + 131;
- int AmbiguousConstructor = ConstructorRelated + 132;
- int UsingDeprecatedConstructor = ConstructorRelated + 133;
- int UnusedPrivateConstructor = Internal + MethodRelated + 134;
- // explicit constructor calls
- int InstanceFieldDuringConstructorInvocation = ConstructorRelated + 135;
- int InstanceMethodDuringConstructorInvocation = ConstructorRelated + 136;
- int RecursiveConstructorInvocation = ConstructorRelated + 137;
- int ThisSuperDuringConstructorInvocation = ConstructorRelated + 138;
- int InvalidExplicitConstructorCall = ConstructorRelated + Syntax + 139;
- // implicit constructor calls
- int UndefinedConstructorInDefaultConstructor = ConstructorRelated + 140;
- int NotVisibleConstructorInDefaultConstructor = ConstructorRelated + 141;
- int AmbiguousConstructorInDefaultConstructor = ConstructorRelated + 142;
- int UndefinedConstructorInImplicitConstructorCall = ConstructorRelated + 143;
- int NotVisibleConstructorInImplicitConstructorCall = ConstructorRelated + 144;
- int AmbiguousConstructorInImplicitConstructorCall = ConstructorRelated + 145;
- int UnhandledExceptionInDefaultConstructor = TypeRelated + 146;
- int UnhandledExceptionInImplicitConstructorCall = TypeRelated + 147;
-
- // expressions
- int ArrayReferenceRequired = Internal + 150;
- // constant expressions
- int StringConstantIsExceedingUtf8Limit = Internal + 152;
- int NumericValueOutOfRange = Internal + 154;
- // allocations
- int InvalidClassInstantiation = TypeRelated + 157;
- int CannotDefineDimensionExpressionsWithInit = Internal + 158;
- int MustDefineEitherDimensionExpressionsOrInitializer = Internal + 159;
- // operators
- int InvalidOperator = Internal + 160;
- // statements
- int CodeCannotBeReached = Internal + 161;
- int CannotReturnOutsideFunction = Internal + 162;
- int InitializerMustCompleteNormally = Internal + 163;
- // assert
- int InvalidVoidExpression = Internal + 164;
- // try
- int MaskedCatch = TypeRelated + 165;
- int DuplicateDefaultCase = Internal + 166;
- int UnreachableCatch = TypeRelated + MethodRelated + 167;
- int UnhandledException = TypeRelated + 168;
- // switch
- int IncorrectSwitchType = TypeRelated + 169;
- int DuplicateCase = FieldRelated + 170;
-
- // labelled
- int DuplicateLabel = Internal + 171;
- int InvalidBreak = Internal + 172;
- int InvalidContinue = Internal + 173;
- int UndefinedLabel = Internal + 174;
- //synchronized
- int InvalidTypeToSynchronized = Internal + 175;
- int InvalidNullToSynchronized = Internal + 176;
- // throw
- int CannotThrowNull = Internal + 177;
- // assignment
- int AssignmentHasNoEffect = Internal + 178;
- int PossibleAccidentalBooleanAssignment = Internal + 179;
- int SuperfluousSemicolon = Internal + 180;
- int UnnecessaryInstanceof = Internal + TypeRelated + 183;
- int FinallyMustCompleteNormally = Internal + 184;
- int UnusedMethodDeclaredThrownException = Internal + 185;
- int UnusedConstructorDeclaredThrownException = Internal + 186;
- int EmptyControlFlowStatement = Internal + TypeRelated + 188;
- int UnnecessaryElse = Internal + 189;
-
- // inner emulation
- int NeedToEmulateFieldReadAccess = FieldRelated + 190;
- int NeedToEmulateFieldWriteAccess = FieldRelated + 191;
- int NeedToEmulateMethodAccess = MethodRelated + 192;
- int NeedToEmulateConstructorAccess = MethodRelated + 193;
-
- int FallthroughCase = Internal + 194;
-
- //inherited name hides enclosing name (sort of ambiguous)
- int InheritedMethodHidesEnclosingName = MethodRelated + 195;
- int InheritedFieldHidesEnclosingName = FieldRelated + 196;
- int InheritedTypeHidesEnclosingName = TypeRelated + 197;
-
- int IllegalUsageOfQualifiedTypeReference = Internal + Syntax + 198;
-
- // miscellaneous
- int UnusedLabel = Internal + 199;
- int ThisInStaticContext = Internal + 200;
- int StaticMethodRequested = Internal + MethodRelated + 201;
- int IllegalDimension = Internal + 202;
- int ParsingError = Syntax + Internal + 204;
- int ParsingErrorNoSuggestion = Syntax + Internal + 205;
- int InvalidUnaryExpression = Syntax + Internal + 206;
-
- // syntax errors
- int ArrayConstantsOnlyInArrayInitializers = Syntax + Internal + 208;
- int ParsingErrorOnKeyword = Syntax + Internal + 209;
- int ParsingErrorOnKeywordNoSuggestion = Syntax + Internal + 210;
-
- int UnmatchedBracket = Syntax + Internal + 220;
- int NoFieldOnBaseType = FieldRelated + 221;
- int InvalidExpressionAsStatement = Syntax + Internal + 222;
- int ExpressionShouldBeAVariable = Syntax + Internal + 223;
- int MissingSemiColon = Syntax + Internal + 224;
- int InvalidParenthesizedExpression = Syntax + Internal + 225;
-
- int ParsingErrorInsertTokenBefore = Syntax + Internal + 230;
- int ParsingErrorInsertTokenAfter = Syntax + Internal + 231;
- int ParsingErrorDeleteToken = Syntax + Internal + 232;
- int ParsingErrorDeleteTokens = Syntax + Internal + 233;
- int ParsingErrorMergeTokens = Syntax + Internal + 234;
- int ParsingErrorInvalidToken = Syntax + Internal + 235;
- int ParsingErrorMisplacedConstruct = Syntax + Internal + 236;
- int ParsingErrorReplaceTokens = Syntax + Internal + 237;
- int ParsingErrorNoSuggestionForTokens = Syntax + Internal + 238;
- int ParsingErrorUnexpectedEOF = Syntax + Internal + 239;
- int ParsingErrorInsertToComplete = Syntax + Internal + 240;
- int ParsingErrorInsertToCompleteScope = Syntax + Internal + 241;
- int ParsingErrorInsertToCompletePhrase = Syntax + Internal + 242;
- /* START -------------------------------- Bug 197884 Loosly defined var (for statement) and optional semi-colon --------------------- */
- int OptionalSemiColon = Syntax + Internal + 243;
- /* END -------------------------------- Bug 197884 Loosly defined var (for statement) and optional semi-colon --------------------- */
-
-
- // scanner errors
- int EndOfSource = Syntax + Internal + 250;
- int InvalidHexa = Syntax + Internal + 251;
- int InvalidOctal = Syntax + Internal + 252;
- int InvalidCharacterConstant = Syntax + Internal + 253;
- int InvalidEscape = Syntax + Internal + 254;
- int InvalidInput = Syntax + Internal + 255;
- int InvalidUnicodeEscape = Syntax + Internal + 256;
- int InvalidFloat = Syntax + Internal + 257;
- int NullSourceString = Syntax + Internal + 258;
- int UnterminatedString = Syntax + Internal + 259;
- int UnterminatedComment = Syntax + Internal + 260;
- int NonExternalizedStringLiteral = Internal + 261;
- int InvalidDigit = Syntax + Internal + 262;
- int InvalidLowSurrogate = Syntax + Internal + 263;
- int InvalidHighSurrogate = Syntax + Internal + 264;
- int UnnecessaryNLSTag = Internal + 265;
-
- // type related problems
- int DiscouragedReference = TypeRelated + 280;
-
- int DuplicateModifierForType = TypeRelated + 301;
- int IllegalModifierForClass = TypeRelated + 302;
- int IllegalModifierForMemberClass = TypeRelated + 304;
- int IllegalModifierForLocalClass = TypeRelated + 306;
- int ForbiddenReference = TypeRelated + 307;
- int IllegalModifierCombinationFinalAbstractForClass = TypeRelated + 308;
- int IllegalVisibilityModifierCombinationForMemberType = TypeRelated + 310;
- int IllegalStaticModifierForMemberType = TypeRelated + 311;
- int SuperclassMustBeAClass = TypeRelated + 312;
- int ClassExtendFinalClass = TypeRelated + 313;
- int HierarchyCircularitySelfReference = TypeRelated + 316;
- int HierarchyCircularity = TypeRelated + 317;
- int HidingEnclosingType = TypeRelated + 318;
- int DuplicateNestedType = TypeRelated + 319;
- int CannotThrowType = TypeRelated + 320;
- int PackageCollidesWithType = TypeRelated + 321;
- int TypeCollidesWithPackage = TypeRelated + 322;
- int DuplicateTypes = TypeRelated + 323;
- int IsClassPathCorrect = TypeRelated + 324;
- int MustSpecifyPackage = Internal + 326;
- int HierarchyHasProblems = TypeRelated + 327;
- int PackageIsNotExpectedPackage = Internal + 328;
- int ObjectCannotHaveSuperTypes = Internal + 329;
- int ObjectMustBeClass = Internal + 330;
-
- // field related problems
- int DuplicateField = FieldRelated + 340;
- int DuplicateModifierForField = FieldRelated + 341;
- int IllegalModifierForField = FieldRelated + 342;
- int IllegalVisibilityModifierCombinationForField = FieldRelated + 344;
- int IllegalModifierCombinationFinalVolatileForField = FieldRelated + 345;
- int UnexpectedStaticModifierForField = FieldRelated + 346;
-
- // method related problems
- int DuplicateMethod = MethodRelated + 355;
- int DuplicateModifierForMethod = MethodRelated + 357;
- int IllegalModifierForMethod = MethodRelated + 358;
- int IllegalVisibilityModifierCombinationForMethod = MethodRelated + 360;
- int UnexpectedStaticModifierForMethod = MethodRelated + 361;
- int IllegalAbstractModifierCombinationForMethod = MethodRelated + 362;
- int AbstractMethodInAbstractClass = MethodRelated + 363;
- int ArgumentTypeCannotBeVoid = MethodRelated + 364;
- int NativeMethodsCannotBeStrictfp = MethodRelated + 367;
- int DuplicateModifierForArgument = MethodRelated + 368;
-
- // import related problems
- int ConflictingImport = ImportRelated + 385;
- int DuplicateImport = ImportRelated + 386;
- int CannotImportPackage = ImportRelated + 387;
-
- int ImportNotFound = ImportRelated + 389 + ProblemReasons.NotFound; // ImportRelated + 390
-
- // local variable related problems
- int DuplicateModifierForVariable = MethodRelated + 395;
-
- // method verifier problems
- int AbstractMethodMustBeImplemented = MethodRelated + 400;
- int IncompatibleExceptionInThrowsClause = MethodRelated + 402;
- int IncompatibleExceptionInInheritedMethodThrowsClause = MethodRelated + 403;
- int IncompatibleReturnType = MethodRelated + 404;
- int InheritedMethodReducesVisibility = MethodRelated + 405;
- int CannotOverrideAStaticMethodWithAnInstanceMethod = MethodRelated + 406;
- int CannotHideAnInstanceMethodWithAStaticMethod = MethodRelated + 407;
- int StaticInheritedMethodConflicts = MethodRelated + 408;
- int MethodReducesVisibility = MethodRelated + 409;
- int OverridingNonVisibleMethod = MethodRelated + 410;
- int AbstractMethodCannotBeOverridden = MethodRelated + 411;
- int OverridingDeprecatedMethod = MethodRelated + 412;
- int IllegalVararg = MethodRelated + 415;
- int OverridingMethodWithoutSuperInvocation = MethodRelated + 416;
-
- // code snippet support
- int CodeSnippetMissingClass = Internal + 420;
- int CodeSnippetMissingMethod = Internal + 421;
-
- //constant pool
- int TooManyConstantsInConstantPool = Internal + 430;
- int TooManyBytesForStringConstant = Internal + 431;
-
- // static constraints
- int TooManyFields = Internal + 432;
- int TooManyMethods = Internal + 433;
-
- // 1.4 features
- // assertion warning
- int UseAssertAsAnIdentifier = Internal + 440;
-
- // 1.5 features
- int UseEnumAsAnIdentifier = Internal + 441;
-
- // detected task
- int Task = Internal + 450;
-
- // local variables related problems, cont'd
- int NullLocalVariableReference = Internal + 451;
- int PotentialNullLocalVariableReference = Internal + 452;
- int RedundantNullCheckOnNullLocalVariable = Internal + 453;
- int NullLocalVariableComparisonYieldsFalse = Internal + 454;
- int RedundantLocalVariableNullAssignment = Internal + 455;
- int NullLocalVariableInstanceofYieldsFalse = Internal + 456;
- int RedundantNullCheckOnNonNullLocalVariable = Internal + 457;
- int NonNullLocalVariableComparisonYieldsFalse = Internal + 458;
-
-
- // block
- int UndocumentedEmptyBlock = Internal + 460;
-
- /*
- * Javadoc comments
- */
- /**
- * Problem signaled on an hidden reference due to a too low visibility level.
- */
- int JavadocHiddenReference = Javadoc + Internal + 465;
- /**
- * Problem signaled on an invalid qualification for member type reference.
- */
- int JavadocInvalidMemberTypeQualification = Javadoc + Internal + 466;
- int JavadocMissingIdentifier = Javadoc + Internal + 467;
- int JavadocNonStaticTypeFromStaticInvocation = Javadoc + Internal + 468;
- int JavadocUnexpectedTag = Javadoc + Internal + 470;
- int JavadocMissingParamTag = Javadoc + Internal + 471;
- int JavadocMissingParamName = Javadoc + Internal + 472;
- int JavadocDuplicateParamName = Javadoc + Internal + 473;
- int JavadocInvalidParamName = Javadoc + Internal + 474;
- int JavadocMissingReturnTag = Javadoc + Internal + 475;
- int JavadocDuplicateReturnTag = Javadoc + Internal + 476;
- int JavadocMissingThrowsTag = Javadoc + Internal + 477;
- int JavadocMissingThrowsClassName = Javadoc + Internal + 478;
- int JavadocInvalidThrowsClass = Javadoc + Internal + 479;
- int JavadocDuplicateThrowsClassName = Javadoc + Internal + 480;
- int JavadocInvalidThrowsClassName = Javadoc + Internal + 481;
- int JavadocMissingSeeReference = Javadoc + Internal + 482;
- int JavadocInvalidSeeReference = Javadoc + Internal + 483;
- int JavadocInvalidSeeHref = Javadoc + Internal + 484;
- int JavadocInvalidSeeArgs = Javadoc + Internal + 485;
- int JavadocMissing = Javadoc + Internal + 486;
- int JavadocInvalidTag = Javadoc + Internal + 487;
- /*
- * ID for field errors in Javadoc
- */
- int JavadocUndefinedField = Javadoc + Internal + 488;
- int JavadocNotVisibleField = Javadoc + Internal + 489;
- int JavadocAmbiguousField = Javadoc + Internal + 490;
- int JavadocUsingDeprecatedField = Javadoc + Internal + 491;
- /*
- * IDs for constructor errors in Javadoc
- */
- int JavadocUndefinedConstructor = Javadoc + Internal + 492;
- int JavadocNotVisibleConstructor = Javadoc + Internal + 493;
- int JavadocAmbiguousConstructor = Javadoc + Internal + 494;
- int JavadocUsingDeprecatedConstructor = Javadoc + Internal + 495;
- /*
- * IDs for method errors in Javadoc
- */
- int JavadocUndefinedMethod = Javadoc + Internal + 496;
- int JavadocNotVisibleMethod = Javadoc + Internal + 497;
- int JavadocAmbiguousMethod = Javadoc + Internal + 498;
- int JavadocUsingDeprecatedMethod = Javadoc + Internal + 499;
- int JavadocNoMessageSendOnBaseType = Javadoc + Internal + 500;
- int JavadocParameterMismatch = Javadoc + Internal + 501;
- int JavadocNoMessageSendOnArrayType = Javadoc + Internal + 502;
- /*
- * IDs for type errors in Javadoc
- */
- int JavadocUndefinedType = Javadoc + Internal + 503;
- int JavadocNotVisibleType = Javadoc + Internal + 504;
- int JavadocAmbiguousType = Javadoc + Internal + 505;
- int JavadocUsingDeprecatedType = Javadoc + Internal + 506;
- int JavadocInternalTypeNameProvided = Javadoc + Internal + 507;
- int JavadocInheritedMethodHidesEnclosingName = Javadoc + Internal + 508;
- int JavadocInheritedFieldHidesEnclosingName = Javadoc + Internal + 509;
- int JavadocInheritedNameHidesEnclosingTypeName = Javadoc + Internal + 510;
- int JavadocUnterminatedInlineTag = Javadoc + Internal + 512;
- int JavadocMalformedSeeReference = Javadoc + Internal + 513;
- int JavadocMessagePrefix = Internal + 514;
- int JavadocMissingHashCharacter = Javadoc + Internal + 515;
- int JavadocEmptyReturnTag = Javadoc + Internal + 516;
- int JavadocUnexpectedText = Javadoc + Internal + 518;
- int JavadocInvalidParamTagName = Javadoc + Internal + 519;
-
- /**
- * Foreach
- */
- int IncompatibleTypesInForeach = TypeRelated + 580;
- int InvalidTypeForCollection = Internal + 581;
-
- /**
- * 1.5 Syntax errors (when source level < 1.5)
- */
- int InvalidUsageOfForeachStatements = Syntax + Internal + 592;
-
- /**
- * Corrupted binaries
- */
- int CorruptedSignature = Internal + 700;
- /**
- * Corrupted source
- */
- int InvalidEncoding = Internal + 701;
- int CannotReadSource = Internal + 702;
-
- /**
- * External problems -- These are problems defined by other plugins
- */
-
- int ExternalProblemNotFixable = 900;
-
- // indicates an externally defined problem that has a quick-assist processor
- // associated with it
- int ExternalProblemFixable = 901;
-
- int InvalidValueForSetter = 902;
- int InvalidValueForGetter = 903;
-}
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
deleted file mode 100644
index a54502ed..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/IScanner.java
+++ /dev/null
@@ -1,154 +0,0 @@
-/*******************************************************************************
- * 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.compiler;
-
-
- /**
- * Definition of a JavaScript scanner, as returned by the <code>ToolFactory</code>.
- * The scanner is responsible for tokenizing a given source, providing information about
- * the nature of the token read, its positions and source equivalent.
- * <p>
- * When the scanner has finished tokenizing, it answers an EOF token (<code>
- * ITerminalSymbols#TokenNameEOF</code>.
- * </p><p>
- * When encountering lexical errors, an <code>InvalidInputException</code> is thrown.
- * </p><p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * @see org.eclipse.wst.jsdt.core.ToolFactory
- * @see ITerminalSymbols
- *
- * 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 IScanner {
-
- /**
- * Answers the current identifier source, after unicode escape sequences have
- * been translated into unicode characters.
- * For example, if original source was <code>\\u0061bc</code> then it will answer <code>abc</code>.
- *
- * @return the current identifier source, after unicode escape sequences have
- * been translated into unicode characters
- */
- char[] getCurrentTokenSource();
-
- /**
- * Answers the current identifier source, before unicode escape sequences have
- * been translated into unicode characters.
- * For example, if original source was <code>\\u0061bc</code> then it will answer <code>\\u0061bc</code>.
- *
- * @return the current identifier source, before unicode escape sequences have
- * been translated into unicode characters
- * @since 2.1
- */
- char[] getRawTokenSource();
-
- /**
- * Answers the starting position of the current token inside the original source.
- * This position is zero-based and inclusive. It corresponds to the position of the first character
- * which is part of this token. If this character was a unicode escape sequence, it points at the first
- * character of this sequence.
- *
- * @return the starting position of the current token inside the original source
- */
- int getCurrentTokenStartPosition();
-
- /**
- * Answers the ending position of the current token inside the original source.
- * This position is zero-based and inclusive. It corresponds to the position of the last character
- * which is part of this token. If this character was a unicode escape sequence, it points at the last
- * character of this sequence.
- *
- * @return the ending position of the current token inside the original source
- */
- int getCurrentTokenEndPosition();
-
- /**
- * Answers the starting position of a given line number. This line has to have been encountered
- * already in the tokenization process (in other words, it cannot be used to compute positions of lines beyond
- * current token). Once the entire source has been processed, it can be used without any limit.
- * Line starting positions are zero-based, and start immediately after the previous line separator (if any).
- *
- * @param lineNumber the given line number
- * @return the starting position of a given line number
- */
- int getLineStart(int lineNumber);
-
- /**
- * Answers the ending position of a given line number. This line has to have been encountered
- * already in the tokenization process (in other words, it cannot be used to compute positions of lines beyond
- * current token). Once the entire source has been processed, it can be used without any limit.
- * Line ending positions are zero-based, and correspond to the last character of the line separator
- * (in case multi-character line separators).
- *
- * @param lineNumber the given line number
- * @return the ending position of a given line number
- **/
- int getLineEnd(int lineNumber);
-
- /**
- * Answers an array of the ending positions of the lines encountered so far. Line ending positions
- * are zero-based, and correspond to the last character of the line separator (in case multi-character
- * line separators).
- *
- * @return an array of the ending positions of the lines encountered so far
- */
- int[] getLineEnds();
-
- /**
- * Answers a 1-based line number using the lines which have been encountered so far. If the position
- * is located beyond the current scanned line, then the last line number will be answered.
- *
- * @param charPosition the given character position
- * @return a 1-based line number using the lines which have been encountered so far
- */
- int getLineNumber(int charPosition);
-
- /**
- * Read the next token in the source, and answers its ID as specified by <code>ITerminalSymbols</code>.
- * Note that the actual token ID values are subject to change if new keywords were added to the language
- * (for instance, 'assert' is a keyword in 1.4).
- *
- * @throws InvalidInputException in case a lexical error was detected while reading the current token
- * @return the next token
- */
- int getNextToken() throws InvalidInputException;
-
- /**
- * Answers the original source being processed (not a copy of it).
- *
- * @return the original source being processed
- */
- char[] getSource();
-
- /**
- * Reposition the scanner on some portion of the original source. The given endPosition is the last valid position.
- * Beyond this position, the scanner will answer EOF tokens (<code>ITerminalSymbols.TokenNameEOF</code>).
- *
- * @param startPosition the given start position
- * @param endPosition the given end position
- */
- void resetTo(int startPosition, int endPosition);
-
- /**
- * Set the scanner source to process. By default, the scanner will consider starting at the beginning of the
- * source until it reaches its end.
- * If the given source is <code>null</code>, this clears the source.
- *
- * @param source the given source
- */
- void setSource(char[] source);
-}
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
deleted file mode 100644
index 4f4c91e3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/ITerminalSymbols.java
+++ /dev/null
@@ -1,166 +0,0 @@
-/*******************************************************************************
- * 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.compiler;
-
-/**
- * Maps each terminal symbol in the javaScript-grammar into a unique integer.
- * This integer is used to represent the terminal when computing a parsing action.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * @see IScanner
- *
- * 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 ITerminalSymbols {
-
- int TokenNameWHITESPACE = 1000;
- int TokenNameCOMMENT_LINE = 1001;
- int TokenNameCOMMENT_BLOCK = 1002;
- int TokenNameCOMMENT_JAVADOC = 1003;
-
- int TokenNameIdentifier = 5;
- int TokenNameabstract = 98;
-
- int TokenNameassert = 118;
- int TokenNameboolean = 18;
- int TokenNamebreak = 119;
- int TokenNamebyte = 19;
- int TokenNamecase = 211;
- int TokenNamecatch = 225;
- int TokenNamechar = 20;
- int TokenNameclass = 165;
- int TokenNamecontinue = 120;
- int TokenNamedefault = 212;
- int TokenNamedo = 121;
- int TokenNamedouble = 21;
- int TokenNameelse = 213;
- int TokenNameextends = 243;
- int TokenNamefalse = 37;
- int TokenNamefinal = 99;
- int TokenNamefinally = 226;
- int TokenNamefloat = 22;
- int TokenNamefor = 122;
- int TokenNameif = 123;
- int TokenNameimplements = 268;
- int TokenNameimport = 191;
- int TokenNameinstanceof = 65;
- int TokenNameint = 23;
- int TokenNameinterface = 180;
- int TokenNamelong = 24;
- int TokenNamenative = 100;
- int TokenNamenew = 32;
- int TokenNamenull = 38;
- int TokenNamepackage = 214;
- int TokenNameprivate = 101;
- int TokenNameprotected = 102;
- int TokenNamepublic = 103;
- int TokenNamereturn = 124;
- int TokenNameshort = 25;
- int TokenNamestatic = 94;
- int TokenNamestrictfp = 104;
- int TokenNamesuper = 33;
- int TokenNameswitch = 125;
- int TokenNamesynchronized = 85;
- int TokenNamethis = 34;
- int TokenNamethrow = 126;
- int TokenNamethrows = 227;
- int TokenNametransient = 105;
- int TokenNametrue = 39;
- int TokenNametry = 127;
- int TokenNamevoid = 26;
- int TokenNamevolatile = 106;
- int TokenNamewhile = 117;
- int TokenNameIntegerLiteral = 40;
- int TokenNameLongLiteral = 41;
- int TokenNameFloatingPointLiteral = 42;
- int TokenNameDoubleLiteral = 43;
- int TokenNameCharacterLiteral = 44;
- int TokenNameStringLiteral = 45;
- int TokenNameRegExLiteral = 46;
- int TokenNamePLUS_PLUS = 1;
- int TokenNameMINUS_MINUS = 2;
- int TokenNameEQUAL_EQUAL = 35;
- int TokenNameLESS_EQUAL = 66;
- int TokenNameGREATER_EQUAL = 67;
- int TokenNameNOT_EQUAL = 36;
- int TokenNameLEFT_SHIFT = 14;
- int TokenNameRIGHT_SHIFT = 11;
- int TokenNameUNSIGNED_RIGHT_SHIFT = 12;
- int TokenNamePLUS_EQUAL = 168;
- int TokenNameMINUS_EQUAL = 169;
- int TokenNameMULTIPLY_EQUAL = 170;
- int TokenNameDIVIDE_EQUAL = 171;
- int TokenNameAND_EQUAL = 172;
- int TokenNameOR_EQUAL = 173;
- int TokenNameXOR_EQUAL = 174;
- int TokenNameREMAINDER_EQUAL = 175;
- int TokenNameLEFT_SHIFT_EQUAL = 176;
- int TokenNameRIGHT_SHIFT_EQUAL = 177;
- int TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL = 178;
- int TokenNameOR_OR = 80;
- int TokenNameAND_AND = 79;
- int TokenNamePLUS = 3;
- int TokenNameMINUS = 4;
- int TokenNameNOT = 71;
- int TokenNameREMAINDER = 9;
- int TokenNameXOR = 63;
- int TokenNameAND = 62;
- int TokenNameMULTIPLY = 8;
- int TokenNameOR = 70;
- int TokenNameTWIDDLE = 72;
- int TokenNameDIVIDE = 10;
- int TokenNameGREATER = 68;
- int TokenNameLESS = 69;
- int TokenNameLPAREN = 7;
- int TokenNameRPAREN = 86;
- int TokenNameLBRACE = 110;
- int TokenNameRBRACE = 95;
- int TokenNameLBRACKET = 15;
- int TokenNameRBRACKET = 166;
- int TokenNameSEMICOLON = 64;
- int TokenNameQUESTION = 81;
- int TokenNameCOLON = 154;
- int TokenNameCOMMA = 90;
- int TokenNameDOT = 6;
- int TokenNameEQUAL = 167;
- int TokenNameEOF = 158;
- int TokenNameERROR = 309;
-
- int TokenNameenum = 400;
-
- int TokenNameAT = 401;
-
- int TokenNameELLIPSIS = 402;
-
- int TokenNameconst = 403;
-
- int TokenNamegoto = 404;
-
- int TokenNameNOT_EQUAL_EQUAL=450;
- int TokenNameEQUAL_EQUAL_EQUAL=451;
- int TokenNamedelete=452;
- int TokenNamedebugger=453;
- int TokenNameexport=454;
- int TokenNamefunction=455;
- int TokenNamein=456;
- int TokenNameinfinity=457;
- int TokenNametypeof=458;
- int TokenNameundefined=459;
- int TokenNamevar=460;
- int TokenNamewith=461;
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/InvalidInputException.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/InvalidInputException.java
deleted file mode 100644
index bac98f25..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/InvalidInputException.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.compiler;
-
-/**
- * Exception thrown by a scanner when encountering lexical errors.
- * <p>
- * This class is not intended to be instantiated or subclassed by clients.
- * </p>
- *
- * 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 InvalidInputException extends Exception {
-
- private static final long serialVersionUID = 2909732853499731592L; // backward compatible
-
-/**
- * Creates a new exception with no detail message.
- */
-public InvalidInputException() {
- super();
-}
-
-/**
- * Creates a new exception with the given detail message.
- * @param message the detail message
- */
-public InvalidInputException(String message) {
- super(message);
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/ReconcileContext.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/ReconcileContext.java
deleted file mode 100644
index fe4ef073..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/ReconcileContext.java
+++ /dev/null
@@ -1,198 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * mkaufman@bea.com - initial API and implementation
- * IBM - renamed from PreReconcileCompilationResult to ReconcileContext
- * IBM - rewrote spec
- *
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.compiler;
-
-import java.util.HashMap;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElementDelta;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelMarker;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.internal.core.CompilationUnit;
-import org.eclipse.wst.jsdt.internal.core.JavaProject;
-import org.eclipse.wst.jsdt.internal.core.ReconcileWorkingCopyOperation;
-
-/**
- * The context of a reconcile event that is notified to interested validation
- * participants while a reconcile operation is running.
- * <p>
- * A reconcile participant can get the AST for the reconcile-operation using
- * {@link #getAST3()}. If the participant modifies in any way the AST
- * (either by modifying the source of the working copy, or modifying another entity
- * that would result in different bindings for the AST), it is expected to reset the
- * AST in the context using {@link #resetAST()}.
- * </p><p>
- * A reconcile participant can also create and return problems using
- * {@link #putProblems(String, CategorizedProblem[])}. These problems are then reported
- * to the problem requestor of the reconcile operation.
- * </p><p>
- * This class is not intended to be instanciated or subclassed by clients.
- * </p>
- *
- * @see ValidationParticipant#reconcile(ReconcileContext)
- *
- * 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 ReconcileContext {
-
- private ReconcileWorkingCopyOperation operation;
- private CompilationUnit workingCopy;
-
-/**
- * Creates a reconcile context for the given reconcile operation.
- * <p>
- * This constructor is not intended to be called by clients.
- * </p>
- *
- * @param operation the reconcile operation
- */
-public ReconcileContext(ReconcileWorkingCopyOperation operation, CompilationUnit workingCopy) {
- this.operation = operation;
- this.workingCopy = workingCopy;
-}
-
-/**
- * Returns a resolved AST with {@link AST#JLS3 JLS3} level.
- * It is created from the current state of the working copy.
- * Creates one if none exists yet.
- * Returns <code>null</code> if the current state of the working copy
- * doesn't allow the AST to be created (e.g. if the working copy's content
- * cannot be parsed).
- * <p>
- * If the AST level requested during reconciling is not {@link AST#JLS3}
- * or if binding resolutions was not requested, then a different AST is created.
- * Note that this AST does not become the current AST and it is only valid for
- * the requestor.
- * </p>
- *
- * @return the AST created from the current state of the working copy,
- * or <code>null</code> if none could be created
- * @exception JavaScriptModelException if the contents of the working copy
- * cannot be accessed. Reasons include:
- * <ul>
- * <li> The working copy does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * </ul>
- */
-public org.eclipse.wst.jsdt.core.dom.JavaScriptUnit getAST3() throws JavaScriptModelException {
- if (this.operation.astLevel != AST.JLS3 || !this.operation.resolveBindings) {
- // create AST (optionally resolving bindings)
- ASTParser parser = ASTParser.newParser(AST.JLS3);
- parser.setCompilerOptions(workingCopy.getJavaScriptProject().getOptions(true));
- if (JavaProject.hasJavaNature(workingCopy.getJavaScriptProject().getProject()))
- parser.setResolveBindings(true);
- parser.setStatementsRecovery((this.operation.reconcileFlags & IJavaScriptUnit.ENABLE_STATEMENTS_RECOVERY) != 0);
- parser.setBindingsRecovery((this.operation.reconcileFlags & IJavaScriptUnit.ENABLE_BINDINGS_RECOVERY) != 0);
- parser.setSource(workingCopy);
- return (org.eclipse.wst.jsdt.core.dom.JavaScriptUnit) parser.createAST(this.operation.progressMonitor);
- }
- return this.operation.makeConsistent(this.workingCopy);
-}
-
-/**
- * Returns the AST level requested by the reconcile operation.
- * It is either {@link IJavaScriptUnit#NO_AST}, or one of the JLS constants defined on {@link AST}.
- *
- * @return the AST level requested by the reconcile operation
- */
-public int getASTLevel() {
- return this.operation.astLevel;
-}
-
-/**
- * Returns whether the reconcile operation is resolving bindings.
- *
- * @return whether the reconcile operation is resolving bindings
- */
-public boolean isResolvingBindings() {
- return this.operation.resolveBindings;
-}
-
-/**
- * Returns the delta describing the change to the working copy being reconciled.
- * Returns <code>null</code> if there is no change.
- * Note that the delta's AST is not yet positioned at this stage. Use {@link #getAST3()}
- * to get the current AST.
- *
- * @return the delta describing the change, or <code>null</code> if none
- */
-public IJavaScriptElementDelta getDelta() {
- return this.operation.deltaBuilder.delta;
-}
-
-/**
- * Returns the problems to be reported to the problem requester of the reconcile operation
- * for the given marker type.
- * Returns <code>null</code> if no problems need to be reported for this marker type.
- *
- * @param markerType the given marker type
- * @return problems to be reported to the problem requester
- */
-public CategorizedProblem[] getProblems(String markerType) {
- if (this.operation.problems == null) return null;
- return (CategorizedProblem[]) this.operation.problems.get(markerType);
-}
-
-/**
- * Returns the working copy this context refers to.
- *
- * @return the working copy this context refers to
- */
-public IJavaScriptUnit getWorkingCopy() {
- return this.workingCopy;
-}
-
-/**
- * Resets the AST carried by this context.
- * A validation participant that modifies the environment that would result in different
- * bindings for the AST is expected to reset the AST on this context, so that other
- * participants don't get a stale AST.
- * <p>
- * Note that resetting the AST will not restart the reconcile process. Only further
- * participants will see the new AST. Thus participants running before the one that
- * resets the AST will have a stale view of the AST and its problems. Use
- * the validation participant extension point to order the participants.
- * </p>
- */
-public void resetAST() {
- this.operation.ast = null;
- putProblems(IJavaScriptModelMarker.JAVASCRIPT_MODEL_PROBLEM_MARKER, null);
- putProblems(IJavaScriptModelMarker.TASK_MARKER, null);
-}
-
-/**
- * Sets the problems to be reported to the problem requester of the reconcile operation
- * for the given marker type.
- * <code>null</code> indicates that no problems need to be reported.
- * <p>
- * Using this functionality, a participant that resolves problems for a given marker type
- * can hide those problems since they don't exist any longer.
- * </p>
- *
- * @param markerType the marker type of the given problems
- * @param problems the problems to be reported to the problem requester of the reconcile operation,
- * or <code>null</code> if none
- */
-public void putProblems(String markerType, CategorizedProblem[] problems) {
- if (this.operation.problems == null)
- this.operation.problems = new HashMap();
- this.operation.problems.put(markerType, problems);
-}
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/ValidationParticipant.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/ValidationParticipant.java
deleted file mode 100644
index 9360a709..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/ValidationParticipant.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * mkaufman@bea.com - initial API as IvalidationParticipant
- * IBM - changed from interface IvalidationParticipant to abstract class validationParticipant
- * IBM - rewrote spec
- *
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.compiler;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-
-/**
- * A validation participant is notified of events occuring during the validation process.
- * The notified events are the result of a build action, a clean action, a reconcile operation
- * (for a working copy), etc.
- * <p>
- * Clients wishing to participate in the validation process must subclass this class, and implement
- * {@link #isActive(IJavaScriptProject)}, {@link #aboutToBuild(IJavaScriptProject)},
- * {@link #reconcile(ReconcileContext)}, etc.
-* </p><p>
- * This class is intended to be subclassed by clients.
- * </p>
- *
- * 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 ValidationParticipant {
-
-public static int READY_FOR_BUILD = 1;
-public static int NEEDS_FULL_BUILD = 2;
-
-/**
- * Notifies this participant that a validation is about to start and provides it the opportunity to
- * create missing source folders for generated source files. Additional source folders
- * should be marked as optional so the project can be built when the folders do not exist.
- * Only sent to participants interested in the project.
- * <p>
- * Default is to return <code>READY_FOR_BUILD</code>.
- * </p>
- * @param project the project about to build
- * @return READY_FOR_BUILD or NEEDS_FULL_BUILD
- */
-public int aboutToBuild(IJavaScriptProject project) {
- return READY_FOR_BUILD;
-}
-
-/**
- * Notifies this participant that a validation operation is about to start and provides it the opportunity to
- * generate source files based on the source files about to be validated.
- * When isBatchBuild is true, then files contains all source files in the project.
- * Only sent to participants interested in the current build project.
- *
- * @param files is an array of BuildContext
- * @param isBatch identifies when the build is a batch build
- */
-public void buildStarting(BuildContext[] files, boolean isBatch) {
- // do nothing by default
-}
-
-/**
- * Notifies this participant that a clean is about to start and provides it the opportunity to
- * delete generated source files.
- * Only sent to participants interested in the project.
- * @param project the project about to be cleaned
- */
-public void cleanStarting(IJavaScriptProject project) {
- // do nothing by default
-}
-
-/**
- * Returns whether this participant is active for a given project.
- * <p>
- * Default is to return <code>false</code>.
- * </p><p>
- * For efficiency, participants that are not interested in the
- * given project should return <code>false</code> for that project.
- * </p>
- * @param project the project to participate in
- * @return whether this participant is active for a given project
- */
-public boolean isActive(IJavaScriptProject project) {
- return false;
-}
-
-/**
- * Notifies this participant that a reconcile operation is happening. The participant can act on this reconcile
- * operation by using the given context. Other participant can then see the result of this participation
- * on this context.
- * <p>
- * Note that a participant should not modify the buffer of the working copy that is being reconciled.
- * </p><p>
- * Default is to do nothing.
- * </p>
- * @param context the reconcile context to act on
- */
-public void reconcile(ReconcileContext context) {
- // do nothing by default
-}
-
-}
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
deleted file mode 100644
index 7414959a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/libraries/LibraryLocation.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.compiler.libraries;
-
-import org.eclipse.core.runtime.IPath;
-/**
- *
- * 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 LibraryLocation {
-
- /**
- * @param name
- * @return path to the given library name
- */
- public String getLibraryPath(String name);
-
- /**
- * @return a list of files in the library
- */
- public char[][] getLibraryFileNames();
-
- /**
- * @return relative path within the plugin library files are stored
- */
- public IPath getLibraryPathInPlugin();
-
- /**
- * @return working location to store library files.
- */
- public IPath getWorkingLibPath();
-
- /**
- * @param name
- * @return path to the given library name
- */
- public String getLibraryPath(char[] name);
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/libraries/SystemLibraryLocation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/libraries/SystemLibraryLocation.java
deleted file mode 100644
index 9d875175..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/libraries/SystemLibraryLocation.java
+++ /dev/null
@@ -1,212 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.compiler.libraries;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Enumeration;
-import java.util.List;
-
-import org.eclipse.core.runtime.FileLocator;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-/**
- *
- * 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 SystemLibraryLocation implements LibraryLocation {
-
- public static final char[] SYSTEM_LIBARAY_NAME= {'s','y','s','t','e','m','.','j','s'};
- public static final char[] LIBRARY_RUNTIME_DIRECTORY={'l','i','b','r','a','r','i','e','s'};
- public static final char[] LIBRARY_PLUGIN_DIRECTORY={'l','i','b','r','a','r','i','e','s'};
- private static final boolean AUTO_UPDATE_LIBS=true;
-
- private static SystemLibraryLocation fInstance;
-
- public static LibraryLocation getInstance() {
- if(fInstance==null)
- fInstance = new SystemLibraryLocation();
- return fInstance;
- }
-
- public IPath getLibraryPathInPlugin() {
- return new Path("libraries"); //$NON-NLS-1$
- }
-
- public char[][] getLibraryFileNames() {
- return new char[][] {SYSTEM_LIBARAY_NAME};
- }
-
- protected String getPluginId() {
- return JavaScriptCore.PLUGIN_ID;
- }
-
- public char[][] getAllFilesInPluginDirectory(String directory){
- Enumeration entries = (Platform.getBundle(getPluginId()).getEntryPaths(directory));
- List allEntries = new ArrayList();
- while (entries.hasMoreElements()) {
- Path value = new Path((String) entries.nextElement());
- char[] filename = value.lastSegment().toCharArray();
- if (Util.isJavaLikeFileName(filename)) { //$NON-NLS-1$
- allEntries.add(filename);
- }
- }
- char[][] fileNames = new char[allEntries.size()][];
-
- for (int i = 0; i < allEntries.size(); i++) {
- fileNames[i] = (char[]) allEntries.get(i);
- }
-
- return fileNames;
- }
-
- public SystemLibraryLocation() {
- super();
-
- IPath libraryRuntimePath = Platform.getStateLocation(Platform.getBundle(JavaScriptCore.PLUGIN_ID)).append(new String(LIBRARY_RUNTIME_DIRECTORY));
- try {
- if (!libraryRuntimePath.toFile().exists()) {
- libraryRuntimePath.toFile().mkdir();
- }
- }
- catch (SecurityException e) {
- Platform.getLog(Platform.getBundle(JavaScriptCore.PLUGIN_ID)).log(new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, "Problem creating folder " + libraryRuntimePath, e));//$NON-NLS-1$
- }
-
- char[][] libFiles = getLibraryFileNames();
-
- for (int i = 0; i < libFiles.length; i++) {
- IPath workingLibLocation = libraryRuntimePath.addTrailingSeparator().append(new String(libFiles[i]));
- File library = workingLibLocation.toFile();
-
- if (!library.exists()) {
- InputStream is = null;
- try {
- is = FileLocator.openStream(Platform.getBundle(getPluginId()), getLibraryPathInPlugin().append(new String(libFiles[i])), false);
- }
- catch (IOException e) {
- Platform.getLog(Platform.getBundle(getPluginId())).log(new Status(IStatus.ERROR, getPluginId(), "Could not read " + getPluginId() + ":" + getLibraryPathInPlugin().append(new String(libFiles[i])), e));//$NON-NLS-1$ //$NON-NLS-2$
- }
- if (is != null) {
- try {
- copyFile(is, library);
- }
- catch (IOException e) {
- Platform.getLog(Platform.getBundle(getPluginId())).log(new Status(IStatus.ERROR, getPluginId(), "Problem writing to " + workingLibLocation, e));//$NON-NLS-1$
- }
- }
- }
- else if (AUTO_UPDATE_LIBS) {
- long lastModold = library.lastModified();
- URL path = null;
- URL entry = null;
- try {
- entry = Platform.getBundle(getPluginId()).getEntry(getLibraryPathInPlugin().append(new String(libFiles[i])).toString());
- path = FileLocator.toFileURL(entry);
- }
- catch (IOException e) {
- // URL conversion error
- Platform.getLog(Platform.getBundle(JavaScriptCore.PLUGIN_ID)).log(new Status(IStatus.ERROR, getPluginId(), "Problem getting file path from " + entry, e));//$NON-NLS-1$
- }
- catch (IllegalStateException e) {
- // bundle uninstalled, not really bad?
- }
-
- if (path != null) {
- File inPlugin = new File(path.getFile());
- long lastModNew = inPlugin.lastModified();
- if (lastModNew > lastModold) {
- InputStream is = null;
- try {
- is = FileLocator.openStream(Platform.getBundle(getPluginId()), getLibraryPathInPlugin().append(new String(libFiles[i])), false);
- }
- catch (IOException e) {
- Platform.getLog(Platform.getBundle(getPluginId())).log(new Status(IStatus.ERROR, getPluginId(), "Could not read " + getPluginId() + ":" + getLibraryPathInPlugin().append(new String(libFiles[i])), e));//$NON-NLS-1$ //$NON-NLS-2$
- }
-
- if (is != null) {
- // Updating old library file
- library.delete();
-
- try {
- copyFile(is, library);
- }
- catch (IOException e) {
- Platform.getLog(Platform.getBundle(getPluginId())).log(new Status(IStatus.ERROR, getPluginId(), "Problem writing to " + library, e));//$NON-NLS-1$
- }
- }
- }
- }
- }
- }
- }
-
-
- public IPath getWorkingLibPath() {
- return new Path(getLibraryPath("")); //$NON-NLS-1$
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.compiler.libraries.LibraryLocation#getLibraryPath(java.lang.String)
- */
- public String getLibraryPath(String name){
- return JavaScriptCore.getPlugin().getStateLocation().append( new String(LIBRARY_RUNTIME_DIRECTORY) ).addTrailingSeparator().append(name).toString();
- }
-
- public String getLibraryPath(char[] name){
- return getLibraryPath(new String(name));
-
- }
- protected static void copyFile(InputStream src, File dst) throws IOException {
- InputStream in = null;
- OutputStream out = null;
- try {
- in = new BufferedInputStream(src);
- out = new BufferedOutputStream(new FileOutputStream(dst));
- byte[] buffer = new byte[4096];
- int len;
- while ((len = in.read(buffer)) != -1) {
- out.write(buffer, 0, len);
- }
- }
- finally {
- if (in != null)
- try {
- in.close();
- }
- catch (IOException e) {
- // problem closing, no recovery or diagnosis possible
- }
- if (out != null)
- try {
- out.close();
- }
- catch (IOException e) {
- // problem closing, no recovery or diagnosis possible
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/AST.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/AST.java
deleted file mode 100644
index 4c8c9e64..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/AST.java
+++ /dev/null
@@ -1,2372 +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.core.dom;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.StringTokenizer;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants;
-import org.eclipse.wst.jsdt.internal.compiler.parser.Scanner;
-
-/**
- * Umbrella owner and abstract syntax tree node factory.
- * An <code>AST</code> instance serves as the common owner of any number of
- * AST nodes, and as the factory for creating new AST nodes owned by that
- * instance.
- * <p>
- * Abstract syntax trees may be hand constructed by clients, using the
- * <code>new<i>TYPE</i></code> factory methods to create new nodes, and the
- * various <code>set<i>CHILD</i></code> methods
- * (see {@link org.eclipse.wst.jsdt.core.dom.ASTNode ASTNode} and its subclasses)
- * to connect them together.
- * </p>
- * <p>
- * Each AST node belongs to a unique AST instance, called the owning AST.
- * The children of an AST node always have the same owner as their parent node.
- * If a node from one AST is to be added to a different AST, the subtree must
- * be cloned first to ensures that the added nodes have the correct owning AST.
- * </p>
- * <p>
- * There can be any number of AST nodes owned by a single AST instance that are
- * unparented. Each of these nodes is the root of a separate little tree of nodes.
- * The method <code>ASTNode.getRoot()</code> navigates from any node to the root
- * of the tree that it is contained in. Ordinarily, an AST instance has one main
- * tree (rooted at a <code>JavaScriptUnit</code>), with newly-created nodes appearing
- * as additional roots until they are parented somewhere under the main tree.
- * One can navigate from any node to its AST instance, but not conversely.
- * </p>
- * <p>
- * The class {@link ASTParser} parses a string
- * containing a JavaScript source code and returns an abstract syntax tree
- * for it. The resulting nodes carry source ranges relating the node back to
- * the original source characters.
- * </p>
- * <p>
- * JavaScript units created by <code>ASTParser</code> from a
- * source document can be serialized after arbitrary modifications
- * with minimal loss of original formatting. Here is an example:
- * <pre>
- * Document doc = new Document("var abc;\nfunction X() {}\n");
- * ASTParser parser = ASTParser.newParser(AST.JLS3);
- * parser.setSource(doc.get().toCharArray());
- * JavaScriptUnit cu = (JavaScriptUnit) parser.createAST(null);
- * cu.recordModifications();
- * AST ast = cu.getAST();
- * FunctionDeclaration id = ast.newFunctionDeclaration();
- * id.setName(ast.newName("X2");
- * cu.statements().add(id); // add declaration at end
- * TextEdit edits = cu.rewrite(document, null);
- * UndoEdit undo = edits.apply(document);
- * </pre>
- * See also {@link org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite} for
- * an alternative way to describe and serialize changes to a
- * read-only AST.
- * </p>
- * <p>
- * Clients may create instances of this class using {@link #newAST(int)},
- * but this class is not intended to be subclassed.
- * </p>
- *
- * @see ASTParser
- * @see ASTNode
- *
- * 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 final class AST {
- /**
- * Constant for indicating the AST API that handles standard Javascript.
- * This API is capable of handling all constructs
- * in the JavaScript language as described in the ECMA-262
- * Specification.
- *
- * @deprecated Clients should use the {@link #JLS3} AST API instead.
- */
- public static final int JLS2 = 2;
-
- /**
- * Internal synonym for {@link #JLS2}. Use to alleviate
- * deprecation warnings.
- */
- /*package*/ static final int JLS2_INTERNAL = JLS2;
-
- /**
- * Constant for indicating the AST API that handles ECMAScript 4.
- * This API is capable of handling all constructs in the
- * JavaScript language as described in the ECMAScript 4
- * Specification.
- * ECMAScript 4 is a superset of all earlier versions of the
- * JavaScript language.
- *
- */
- public static final int JLS3 = 3;
-
- /**
- * The binding resolver for this AST. Initially a binding resolver that
- * does not resolve names at all.
- */
- private BindingResolver resolver = new BindingResolver();
-
- /**
- * The event handler for this AST.
- * Initially an event handler that does not nothing.
- */
- private NodeEventHandler eventHandler = new NodeEventHandler();
-
- /**
- * Level of AST API supported by this AST.
- */
- int apiLevel;
-
- /**
- * Internal modification count; initially 0; increases monotonically
- * <b>by one or more</b> as the AST is successively modified.
- */
- private long modificationCount = 0;
-
- /**
- * Internal original modification count; value is equals to <code>
- * modificationCount</code> at the end of the parse (<code>ASTParser
- * </code>). If this ast is not created with a parser then value is 0.
- */
- private long originalModificationCount = 0;
-
- /**
- * When disableEvents > 0, events are not reported and
- * the modification count stays fixed.
- * <p>
- * This mechanism is used in lazy initialization of a node
- * to prevent events from being reported for the modification
- * of the node as well as for the creation of the missing child.
- * </p>
- */
- private int disableEvents = 0;
-
- /**
- * Internal object unique to the AST instance. Readers must synchronize on
- * this object when the modifying instance fields.
- */
- private final Object internalASTLock = new Object();
-
- /**
- * JavaScript Scanner used to validate preconditions for the creation of specific nodes
- * like CharacterLiteral, NumberLiteral, StringLiteral or SimpleName.
- */
- Scanner scanner;
-
- /**
- * Internal ast rewriter used to record ast modification when record mode is enabled.
- */
- InternalASTRewrite rewriter;
-
- /**
- * Default value of <code>flag<code> when a new node is created.
- */
- private int defaultNodeFlag = 0;
-
- /**
- * Creates a new JavaScript abstract syntax tree
- * (AST) following the specified set of API rules.
- *
- * @param level the API level; one of the LEVEL constants
- */
- private AST(int level) {
- if ((level != AST.JLS2)
- && (level != AST.JLS3)) {
- throw new IllegalArgumentException();
- }
- this.apiLevel = level;
- // initialize a scanner
- this.scanner = new Scanner(
- true /*comment*/,
- true /*whitespace*/,
- false /*nls*/,
- ClassFileConstants.JDK1_3 /*sourceLevel*/,
- ClassFileConstants.JDK1_5 /*complianceLevel*/,
- null/*taskTag*/,
- null/*taskPriorities*/,
- true/*taskCaseSensitive*/);
- }
-
- /**
- * Creates a new, empty abstract syntax tree using default options.
- *
- * @see JavaScriptCore#getDefaultOptions()
- * @deprecated Clients should port their code to use the new JLS3 AST API and call
- * {@link #newAST(int) AST.newAST(AST.JLS3)} instead of using this constructor.
- */
- public AST() {
- this(JavaScriptCore.getDefaultOptions());
- }
-
- /**
- * Internal method.
- * <p>
- * This method converts the given internal compiler AST for the given source string
- * into a javaScript unit. This method is not intended to be called by clients.
- * </p>
- *
- * @param level the API level; one of the LEVEL constants
- * @param compilationUnitDeclaration an internal AST node for a javaScript unit declaration
- * @param source the string of the JavaScript javaScript unit
- * @param options validator options
- * @param workingCopy the working copy that the AST is created from
- * @param monitor the progress monitor used to report progress and request cancelation,
- * or <code>null</code> if none
- * @param isResolved whether the given javaScript unit declaration is resolved
- * @return the javaScript unit node
- */
- public static JavaScriptUnit convertCompilationUnit(
- int level,
- org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration compilationUnitDeclaration,
- char[] source,
- Map options,
- boolean isResolved,
- org.eclipse.wst.jsdt.internal.core.CompilationUnit workingCopy,
- int reconcileFlags,
- IProgressMonitor monitor) {
-
- ASTConverter converter = new ASTConverter(options, isResolved, monitor);
- AST ast = AST.newAST(level);
- int savedDefaultNodeFlag = ast.getDefaultNodeFlag();
- ast.setDefaultNodeFlag(ASTNode.ORIGINAL);
- BindingResolver resolver = null;
- if (isResolved) {
- resolver = new DefaultBindingResolver(compilationUnitDeclaration.scope, workingCopy.owner, new DefaultBindingResolver.BindingTables(), false);
- ast.setFlag(AST.RESOLVED_BINDINGS);
- } else {
- resolver = new BindingResolver();
- }
- ast.setFlag(reconcileFlags);
- ast.setBindingResolver(resolver);
- converter.setAST(ast);
-
- JavaScriptUnit unit = converter.convert(compilationUnitDeclaration, source);
- unit.setLineEndTable(compilationUnitDeclaration.compilationResult.getLineSeparatorPositions());
- unit.setTypeRoot(workingCopy);
- ast.setDefaultNodeFlag(savedDefaultNodeFlag);
- return unit;
- }
-
- /**
- * Creates a new, empty abstract syntax tree using the given options.
- *
- * @param options the table of options (key type: <code>String</code>;
- * value type: <code>String</code>)
- * @see JavaScriptCore#getDefaultOptions()
- * @deprecated Clients should port their code to use the new JLS3 AST API and call
- * {@link #newAST(int) AST.newAST(AST.JLS3)} instead of using this constructor.
- */
- public AST(Map options) {
- this(JLS2);
- Object sourceLevelOption = options.get(JavaScriptCore.COMPILER_SOURCE);
- long sourceLevel = ClassFileConstants.JDK1_3;
- if (JavaScriptCore.VERSION_1_4.equals(sourceLevelOption)) {
- sourceLevel = ClassFileConstants.JDK1_4;
- } else if (JavaScriptCore.VERSION_1_5.equals(sourceLevelOption)) {
- sourceLevel = ClassFileConstants.JDK1_5;
- }
- Object complianceLevelOption = options.get(JavaScriptCore.COMPILER_COMPLIANCE);
- long complianceLevel = ClassFileConstants.JDK1_3;
- if (JavaScriptCore.VERSION_1_4.equals(complianceLevelOption)) {
- complianceLevel = ClassFileConstants.JDK1_4;
- } else if (JavaScriptCore.VERSION_1_5.equals(complianceLevelOption)) {
- complianceLevel = ClassFileConstants.JDK1_5;
- }
- // override scanner if 1.4 or 1.5 asked for
- this.scanner = new Scanner(
- true /*comment*/,
- true /*whitespace*/,
- false /*nls*/,
- sourceLevel /*sourceLevel*/,
- complianceLevel /*complianceLevel*/,
- null/*taskTag*/,
- null/*taskPriorities*/,
- true/*taskCaseSensitive*/);
- }
-
- /**
- * Creates a new JavaScript abstract syntax tree
- * (AST) following the specified set of API rules.
- *
- * @param level the API level; one of the LEVEL constants
- * @return new AST instance following the specified set of API rules.
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the API level is not one of the LEVEL constants</li>
- * </ul>
- */
- public static AST newAST(int level) {
- if ((level != AST.JLS2)
- && (level != AST.JLS3)) {
- throw new IllegalArgumentException();
- }
- return new AST(level);
- }
-
- /**
- * Returns the modification count for this AST. The modification count
- * is a non-negative value that increases (by 1 or perhaps by more) as
- * this AST or its nodes are changed. The initial value is unspecified.
- * <p>
- * The following things count as modifying an AST:
- * <ul>
- * <li>creating a new node owned by this AST,</li>
- * <li>adding a child to a node owned by this AST,</li>
- * <li>removing a child from a node owned by this AST,</li>
- * <li>setting a non-node attribute of a node owned by this AST.</li>
- * </ul>
- * </p>
- * Operations which do not entail creating or modifying existing nodes
- * do not increase the modification count.
- * <p>
- * N.B. This method may be called several times in the course
- * of a single client operation. The only promise is that the modification
- * count increases monotonically as the AST or its nodes change; there is
- * no promise that a modifying operation increases the count by exactly 1.
- * </p>
- *
- * @return the current value (non-negative) of the modification counter of
- * this AST
- */
- public long modificationCount() {
- return this.modificationCount;
- }
-
- /**
- * Return the API level supported by this AST.
- *
- * @return level the API level; one of the <code>JLS*</code>LEVEL
- * declared on <code>AST</code>; assume this set is open-ended
- */
- public int apiLevel() {
- return this.apiLevel;
- }
-
- /**
- * Indicates that this AST is about to be modified.
- * <p>
- * The following things count as modifying an AST:
- * <ul>
- * <li>creating a new node owned by this AST</li>
- * <li>adding a child to a node owned by this AST</li>
- * <li>removing a child from a node owned by this AST</li>
- * <li>setting a non-node attribute of a node owned by this AST</li>.
- * </ul>
- * </p>
- * <p>
- * N.B. This method may be called several times in the course
- * of a single client operation.
- * </p>
- */
- void modifying() {
- // when this method is called during lazy init, events are disabled
- // and the modification count will not be increased
- if (this.disableEvents > 0) {
- return;
- }
- // increase the modification count
- this.modificationCount++;
- }
-
- /**
- * Disable events.
- * This method is thread-safe for AST readers.
- *
- * @see #reenableEvents()
- */
- final void disableEvents() {
- synchronized (this.internalASTLock) {
- // guard against concurrent access by another reader
- this.disableEvents++;
- }
- // while disableEvents > 0 no events will be reported, and mod count will stay fixed
- }
-
- /**
- * Reenable events.
- * This method is thread-safe for AST readers.
- *
- * @see #disableEvents()
- */
- final void reenableEvents() {
- synchronized (this.internalASTLock) {
- // guard against concurrent access by another reader
- this.disableEvents--;
- }
- }
-
- /**
- * Reports that the given node is about to lose a child.
- *
- * @param node the node about to be modified
- * @param child the node about to be removed
- * @param property the child or child list property descriptor
- */
- void preRemoveChildEvent(ASTNode node, ASTNode child, StructuralPropertyDescriptor property) {
- // IMPORTANT: this method is called by readers during lazy init
- synchronized (this.internalASTLock) {
- // guard against concurrent access by a reader doing lazy init
- if (this.disableEvents > 0) {
- // doing lazy init OR already processing an event
- // System.out.println("[BOUNCE DEL]");
- return;
- } else {
- disableEvents();
- }
- }
- try {
- this.eventHandler.preRemoveChildEvent(node, child, property);
- // N.B. even if event handler blows up, the AST is not
- // corrupted since node has not been changed yet
- } finally {
- reenableEvents();
- }
- }
-
- /**
- * Reports that the given node just lost a child.
- *
- * @param node the node that was modified
- * @param child the child node that was removed
- * @param property the child or child list property descriptor
- */
- void postRemoveChildEvent(ASTNode node, ASTNode child, StructuralPropertyDescriptor property) {
- // IMPORTANT: this method is called by readers during lazy init
- synchronized (this.internalASTLock) {
- // guard against concurrent access by a reader doing lazy init
- if (this.disableEvents > 0) {
- // doing lazy init OR already processing an event
- // System.out.println("[BOUNCE DEL]");
- return;
- } else {
- disableEvents();
- }
- }
- try {
- this.eventHandler.postRemoveChildEvent(node, child, property);
- // N.B. even if event handler blows up, the AST is not
- // corrupted since node has not been changed yet
- } finally {
- reenableEvents();
- }
- }
-
- /**
- * Reports that the given node is about have a child replaced.
- *
- * @param node the node about to be modified
- * @param child the child node about to be removed
- * @param newChild the replacement child
- * @param property the child or child list property descriptor
- */
- void preReplaceChildEvent(ASTNode node, ASTNode child, ASTNode newChild, StructuralPropertyDescriptor property) {
- // IMPORTANT: this method is called by readers during lazy init
- synchronized (this.internalASTLock) {
- // guard against concurrent access by a reader doing lazy init
- if (this.disableEvents > 0) {
- // doing lazy init OR already processing an event
- // System.out.println("[BOUNCE REP]");
- return;
- } else {
- disableEvents();
- }
- }
- try {
- this.eventHandler.preReplaceChildEvent(node, child, newChild, property);
- // N.B. even if event handler blows up, the AST is not
- // corrupted since node has not been changed yet
- } finally {
- reenableEvents();
- }
- }
-
- /**
- * Reports that the given node has just had a child replaced.
- *
- * @param node the node modified
- * @param child the child removed
- * @param newChild the replacement child
- * @param property the child or child list property descriptor
- */
- void postReplaceChildEvent(ASTNode node, ASTNode child, ASTNode newChild, StructuralPropertyDescriptor property) {
- // IMPORTANT: this method is called by readers during lazy init
- synchronized (this.internalASTLock) {
- // guard against concurrent access by a reader doing lazy init
- if (this.disableEvents > 0) {
- // doing lazy init OR already processing an event
- // System.out.println("[BOUNCE REP]");
- return;
- } else {
- disableEvents();
- }
- }
- try {
- this.eventHandler.postReplaceChildEvent(node, child, newChild, property);
- // N.B. even if event handler blows up, the AST is not
- // corrupted since node has not been changed yet
- } finally {
- reenableEvents();
- }
- }
-
- /**
- * Reports that the given node is about to gain a child.
- *
- * @param node the node that to be modified
- * @param child the node that to be added as a child
- * @param property the child or child list property descriptor
- */
- void preAddChildEvent(ASTNode node, ASTNode child, StructuralPropertyDescriptor property) {
- // IMPORTANT: this method is called by readers during lazy init
- synchronized (this.internalASTLock) {
- // guard against concurrent access by a reader doing lazy init
- if (this.disableEvents > 0) {
- // doing lazy init OR already processing an event
- // System.out.println("[BOUNCE ADD]");
- return;
- } else {
- disableEvents();
- }
- }
- try {
- this.eventHandler.preAddChildEvent(node, child, property);
- // N.B. even if event handler blows up, the AST is not
- // corrupted since node has already been changed
- } finally {
- reenableEvents();
- }
- }
-
- /**
- * Reports that the given node has just gained a child.
- *
- * @param node the node that was modified
- * @param child the node that was added as a child
- * @param property the child or child list property descriptor
- */
- void postAddChildEvent(ASTNode node, ASTNode child, StructuralPropertyDescriptor property) {
- // IMPORTANT: this method is called by readers during lazy init
- synchronized (this.internalASTLock) {
- // guard against concurrent access by a reader doing lazy init
- if (this.disableEvents > 0) {
- // doing lazy init OR already processing an event
- // System.out.println("[BOUNCE ADD]");
- return;
- } else {
- disableEvents();
- }
- }
- try {
- this.eventHandler.postAddChildEvent(node, child, property);
- // N.B. even if event handler blows up, the AST is not
- // corrupted since node has already been changed
- } finally {
- reenableEvents();
- }
- }
-
- /**
- * Reports that the given node is about to change the value of a
- * non-child property.
- *
- * @param node the node to be modified
- * @param property the property descriptor
- */
- void preValueChangeEvent(ASTNode node, SimplePropertyDescriptor property) {
- // IMPORTANT: this method is called by readers during lazy init
- synchronized (this.internalASTLock) {
- // guard against concurrent access by a reader doing lazy init
- if (this.disableEvents > 0) {
- // doing lazy init OR already processing an event
- // System.out.println("[BOUNCE CHANGE]");
- return;
- } else {
- disableEvents();
- }
- }
- try {
- this.eventHandler.preValueChangeEvent(node, property);
- // N.B. even if event handler blows up, the AST is not
- // corrupted since node has already been changed
- } finally {
- reenableEvents();
- }
- }
-
- /**
- * Reports that the given node has just changed the value of a
- * non-child property.
- *
- * @param node the node that was modified
- * @param property the property descriptor
- */
- void postValueChangeEvent(ASTNode node, SimplePropertyDescriptor property) {
- // IMPORTANT: this method is called by readers during lazy init
- synchronized (this.internalASTLock) {
- // guard against concurrent access by a reader doing lazy init
- if (this.disableEvents > 0) {
- // doing lazy init OR already processing an event
- // System.out.println("[BOUNCE CHANGE]");
- return;
- } else {
- disableEvents();
- }
- }
- try {
- this.eventHandler.postValueChangeEvent(node, property);
- // N.B. even if event handler blows up, the AST is not
- // corrupted since node has already been changed
- } finally {
- reenableEvents();
- }
- }
-
- /**
- * Reports that the given node is about to be cloned.
- *
- * @param node the node to be cloned
- */
- void preCloneNodeEvent(ASTNode node) {
- synchronized (this.internalASTLock) {
- // guard against concurrent access by a reader doing lazy init
- if (this.disableEvents > 0) {
- // doing lazy init OR already processing an event
- // System.out.println("[BOUNCE CLONE]");
- return;
- } else {
- disableEvents();
- }
- }
- try {
- this.eventHandler.preCloneNodeEvent(node);
- // N.B. even if event handler blows up, the AST is not
- // corrupted since node has already been changed
- } finally {
- reenableEvents();
- }
- }
-
- /**
- * Reports that the given node has just been cloned.
- *
- * @param node the node that was cloned
- * @param clone the clone of <code>node</code>
- */
- void postCloneNodeEvent(ASTNode node, ASTNode clone) {
- synchronized (this.internalASTLock) {
- // guard against concurrent access by a reader doing lazy init
- if (this.disableEvents > 0) {
- // doing lazy init OR already processing an event
- // System.out.println("[BOUNCE CLONE]");
- return;
- } else {
- disableEvents();
- }
- }
- try {
- this.eventHandler.postCloneNodeEvent(node, clone);
- // N.B. even if event handler blows up, the AST is not
- // corrupted since node has already been changed
- } finally {
- reenableEvents();
- }
- }
-
- /**
- * Returns the binding resolver for this AST.
- *
- * @return the binding resolver for this AST
- */
- BindingResolver getBindingResolver() {
- return this.resolver;
- }
-
- /**
- * Returns the event handler for this AST.
- *
- * @return the event handler for this AST
- */
- NodeEventHandler getEventHandler() {
- return this.eventHandler;
- }
-
- /**
- * Sets the event handler for this AST.
- *
- * @param eventHandler the event handler for this AST
- */
- void setEventHandler(NodeEventHandler eventHandler) {
- if (this.eventHandler == null) {
- throw new IllegalArgumentException();
- }
- this.eventHandler = eventHandler;
- }
-
- /**
- * Returns default node flags of new nodes of this AST.
- *
- * @return the default node flags of new nodes of this AST
- */
- int getDefaultNodeFlag() {
- return this.defaultNodeFlag;
- }
-
- /**
- * Sets default node flags of new nodes of this AST.
- *
- * @param flag node flags of new nodes of this AST
- */
- void setDefaultNodeFlag(int flag) {
- this.defaultNodeFlag = flag;
- }
-
- /**
- * Set <code>originalModificationCount</code> to the current modification count
- *
- */
- void setOriginalModificationCount(long count) {
- this.originalModificationCount = count;
- }
-
- /**
- * Returns the type binding for a "well known" type.
- * <p>
- * Note that bindings are generally unavailable unless requested when the
- * AST is being built.
- * </p>
- *
- * @param name the name of a well known type
- * @return the corresponding type binding, or <code>null</code> if the
- * named type is not considered well known or if no binding can be found
- * for it
- */
- public ITypeBinding resolveWellKnownType(String name) {
- if (name == null) {
- return null;
- }
- return getBindingResolver().resolveWellKnownType(name);
- }
-
- /**
- * Sets the binding resolver for this AST.
- *
- * @param resolver the new binding resolver for this AST
- */
- void setBindingResolver(BindingResolver resolver) {
- if (resolver == null) {
- throw new IllegalArgumentException();
- }
- this.resolver = resolver;
- }
-
- /**
- * Checks that this AST operation is not used when
- * building level JLS2 ASTs.
-
- * @exception UnsupportedOperationException
- */
- void unsupportedIn2() {
- if (this.apiLevel == AST.JLS2) {
- throw new UnsupportedOperationException("Operation not supported in JLS2 AST"); //$NON-NLS-1$
- }
- }
-
- /**
- * Checks that this AST operation is only used when
- * building level JLS2 ASTs.
-
- * @exception UnsupportedOperationException
- */
- void supportedOnlyIn2() {
- if (this.apiLevel != AST.JLS2) {
- throw new UnsupportedOperationException("Operation not supported in JLS2 AST"); //$NON-NLS-1$
- }
- }
-
- /**
- * new Class[] {AST.class}
- */
- private static final Class[] AST_CLASS = new Class[] {AST.class};
-
- /**
- * new Object[] {this}
- */
- private final Object[] THIS_AST= new Object[] {this};
-
- /*
- * Must not collide with a value for IJavaScriptUnit constants
- */
- static final int RESOLVED_BINDINGS = 0x80000000;
-
- /**
- * Tag bit value. This represents internal state of the tree.
- */
- private int bits;
-
- /**
- * Creates an unparented node of the given node class
- * (non-abstract subclass of {@link ASTNode}).
- *
- * @param nodeClass AST node class
- * @return a new unparented node owned by this AST
- * @exception IllegalArgumentException if <code>nodeClass</code> is
- * <code>null</code> or is not a concrete node type class
- */
- public ASTNode createInstance(Class nodeClass) {
- if (nodeClass == null) {
- throw new IllegalArgumentException();
- }
- try {
- // invoke constructor with signature Foo(AST)
- Constructor c = nodeClass.getDeclaredConstructor(AST_CLASS);
- Object result = c.newInstance(this.THIS_AST);
- return (ASTNode) result;
- } catch (NoSuchMethodException e) {
- // all AST node classes have a Foo(AST) constructor
- // therefore nodeClass is not legit
- throw new IllegalArgumentException();
- } catch (InstantiationException e) {
- // all concrete AST node classes can be instantiated
- // therefore nodeClass is not legit
- throw new IllegalArgumentException();
- } catch (IllegalAccessException e) {
- // all AST node classes have an accessible Foo(AST) constructor
- // therefore nodeClass is not legit
- throw new IllegalArgumentException();
- } catch (InvocationTargetException e) {
- // concrete AST node classes do not die in the constructor
- // therefore nodeClass is not legit
- throw new IllegalArgumentException();
- }
- }
-
- /**
- * Creates an unparented node of the given node type.
- * This convenience method is equivalent to:
- * <pre>
- * createInstance(ASTNode.nodeClassForType(nodeType))
- * </pre>
- *
- * @param nodeType AST node type, one of the node type
- * constants declared on {@link ASTNode}
- * @return a new unparented node owned by this AST
- * @exception IllegalArgumentException if <code>nodeType</code> is
- * not a legal AST node type
- */
- public ASTNode createInstance(int nodeType) {
- // nodeClassForType throws IllegalArgumentException if nodeType is bogus
- Class nodeClass = ASTNode.nodeClassForType(nodeType);
- return createInstance(nodeClass);
- }
-
- //=============================== NAMES ===========================
- /**
- * Creates and returns a new unparented simple name node for the given
- * identifier. The identifier should be a legal JavaScript identifier, but not
- * a keyword, boolean literal ("true", "false") or null literal ("null").
- *
- * @param identifier the identifier
- * @return a new unparented simple name node
- * @exception IllegalArgumentException if the identifier is invalid
- */
- public SimpleName newSimpleName(String identifier) {
- if (identifier == null) {
- throw new IllegalArgumentException();
- }
- SimpleName result = new SimpleName(this);
- result.setIdentifier(identifier);
- return result;
- }
-
- /**
- * Creates and returns a new unparented qualified name node for the given
- * qualifier and simple name child node.
- *
- * @param qualifier the qualifier name node
- * @param name the simple name being qualified
- * @return a new unparented qualified name node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public QualifiedName newQualifiedName(
- Name qualifier,
- SimpleName name) {
- QualifiedName result = new QualifiedName(this);
- result.setQualifier(qualifier);
- result.setName(name);
- return result;
-
- }
-
- /**
- * Creates and returns a new unparented name node for the given name
- * segments. Returns a simple name if there is only one name segment, and
- * a qualified name if there are multiple name segments. Each of the name
- * segments should be legal JavaScript identifiers (this constraint may or may
- * not be enforced), and there must be at least one name segment.
- *
- * @param identifiers a list of 1 or more name segments, each of which
- * is a legal JavaScript identifier
- * @return a new unparented name node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the identifier is invalid</li>
- * <li>the list of identifiers is empty</li>
- * </ul>
- */
- public Name newName(String[] identifiers) {
- // update internalSetName(String[] if changed
- int count = identifiers.length;
- if (count == 0) {
- throw new IllegalArgumentException();
- }
- Name result = newSimpleName(identifiers[0]);
- for (int i = 1; i < count; i++) {
- SimpleName name = newSimpleName(identifiers[i]);
- result = newQualifiedName(result, name);
- }
- return result;
- }
-
- /* (omit jsdoc for this method)
- * This method is a copy of setName(String[]) that doesn't do any validation.
- */
- Name internalNewName(String[] identifiers) {
- int count = identifiers.length;
- if (count == 0) {
- throw new IllegalArgumentException();
- }
- final SimpleName simpleName = new SimpleName(this);
- simpleName.internalSetIdentifier(identifiers[0]);
- Name result = simpleName;
- for (int i = 1; i < count; i++) {
- SimpleName name = new SimpleName(this);
- name.internalSetIdentifier(identifiers[i]);
- result = newQualifiedName(result, name);
- }
- return result;
- }
-
- /**
- * Creates and returns a new unparented name node for the given name.
- * The name string must consist of 1 or more name segments separated
- * by single dots '.'. Returns a {@link QualifiedName} if the name has
- * dots, and a {@link SimpleName} otherwise. Each of the name
- * segments should be legal JavaScript identifiers (this constraint may or may
- * not be enforced), and there must be at least one name segment.
- * The string must not contains white space, '&lt;', '&gt;',
- * '[', ']', or other any other characters that are not
- * part of the JavaScript identifiers or separating '.'s.
- *
- * @param qualifiedName string consisting of 1 or more name segments,
- * each of which is a legal JavaScript identifier, separated by single dots '.'
- * @return a new unparented name node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the string is empty</li>
- * <li>the string begins or ends in a '.'</li>
- * <li>the string has adjacent '.'s</li>
- * <li>the segments between the '.'s are not valid JavaScript identifiers</li>
- * </ul>
- */
- public Name newName(String qualifiedName) {
- StringTokenizer t = new StringTokenizer(qualifiedName, ".", true); //$NON-NLS-1$
- Name result = null;
- // balance is # of name tokens - # of period tokens seen so far
- // initially 0; finally 1; should never drop < 0 or > 1
- int balance = 0;
- while(t.hasMoreTokens()) {
- String s = t.nextToken();
- if (s.indexOf('.') >= 0) {
- // this is a delimiter
- if (s.length() > 1) {
- // too many dots in a row
- throw new IllegalArgumentException();
- }
- balance--;
- if (balance < 0) {
- throw new IllegalArgumentException();
- }
- } else {
- // this is an identifier segment
- balance++;
- SimpleName name = newSimpleName(s);
- if (result == null) {
- result = name;
- } else {
- result = newQualifiedName(result, name);
- }
- }
- }
- if (balance != 1) {
- throw new IllegalArgumentException();
- }
- return result;
- }
-
- //=============================== TYPES ===========================
- /**
- * Creates and returns a new unparented simple type node with the given
- * type name.
- * <p>
- * This method can be used to convert a name (<code>Name</code>) into a
- * type (<code>Type</code>) by wrapping it.
- * </p>
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @param typeName the name of the class or interface
- * @return a new unparented simple type node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public SimpleType newSimpleType(Name typeName) {
- SimpleType result = new SimpleType(this);
- result.setName(typeName);
- return result;
- }
-
- /**
- * Creates and returns a new unparented array type node with the given
- * component type, which may be another array type.
- *
- * @param componentType the component type (possibly another array type)
- * @return a new unparented array type node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public ArrayType newArrayType(Type componentType) {
- ArrayType result = new ArrayType(this);
- result.setComponentType(componentType);
- return result;
- }
-
- /**
- * Creates and returns a new unparented array type node with the given
- * element type and number of dimensions.
- * <p>
- * Note that if the element type passed in is an array type, the
- * element type of the result will not be the same as what was passed in.
- * </p>
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @param elementType the element type (never an array type)
- * @param dimensions the number of dimensions, a positive number
- * @return a new unparented array type node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * <li>the element type is null</li>
- * <li>the element type is an array type</li>
- * <li>the number of dimensions is lower than 1</li>
- * <li>the number of dimensions is greater than 1000</li>
- * </ul>
- */
- public ArrayType newArrayType(Type elementType, int dimensions) {
- if (elementType == null || elementType.isArrayType()) {
- throw new IllegalArgumentException();
- }
- if (dimensions < 1 || dimensions > 1000) {
- // we would blow our stacks anyway with a 1000-D array
- throw new IllegalArgumentException();
- }
- ArrayType result = new ArrayType(this);
- result.setComponentType(elementType);
- for (int i = 2; i <= dimensions; i++) {
- result = newArrayType(result);
- }
- return result;
-
- }
-
- /**
- * Creates and returns a new unparented primitive type node with the given
- * type code.
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @param typeCode one of the primitive type code constants declared in
- * <code>PrimitiveType</code>
- * @return a new unparented primitive type node
- * @exception IllegalArgumentException if the primitive type code is invalid
- */
- public PrimitiveType newPrimitiveType(PrimitiveType.Code typeCode) {
- PrimitiveType result = new PrimitiveType(this);
- result.setPrimitiveTypeCode(typeCode);
- return result;
- }
-
- /**
- * Creates and returns a new inferred type node with the given
- * type name.
- *
- * @param typeName the name of the inferred type
- * @return a new unparented inferred type node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public InferredType newInferredType(String typeName) {
- InferredType result = new InferredType(this);
- result.setSourceRange(-1, 0);
- if (typeName!=null)
- result.type=typeName;
- return result;
- }
-
- /**
- * Creates and returns a new unparented qualified type node with
- * the given qualifier type and name.
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @param qualifier the qualifier type node
- * @param name the simple name being qualified
- * @return a new unparented qualified type node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- * @exception UnsupportedOperationException if this operation is used in
- * a JLS2 AST
- */
- public QualifiedType newQualifiedType(Type qualifier, SimpleName name) {
- QualifiedType result = new QualifiedType(this);
- result.setQualifier(qualifier);
- result.setName(name);
- return result;
- }
-
- //=============================== DECLARATIONS ===========================
- /**
- * Creates an unparented javaScript unit node owned by this AST.
- * The javaScript unit initially has no package declaration, no
- * import declarations, and no type declarations.
- *
- * @return the new unparented javaScript unit node
- */
- public JavaScriptUnit newJavaScriptUnit() {
- return new JavaScriptUnit(this);
- }
-
- /**
- * Creates an unparented package declaration node owned by this AST.
- * The package declaration initially declares a package with an
- * unspecified name.
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @return the new unparented package declaration node
- */
- public PackageDeclaration newPackageDeclaration() {
- PackageDeclaration result = new PackageDeclaration(this);
- return result;
- }
-
- /**
- * Creates an unparented import declaration node owned by this AST.
- * The import declaration initially contains a single-type import
- * of a type with an unspecified name.
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @return the new unparented import declaration node
- */
- public ImportDeclaration newImportDeclaration() {
- ImportDeclaration result = new ImportDeclaration(this);
- return result;
- }
-
- /**
- * Creates an unparented class declaration node owned by this AST.
- * The name of the class is an unspecified, but legal, name;
- * no modifiers; no doc comment; no superclass or superinterfaces;
- * and an empty class body.
- * <p>
- * To create an interface, use this method and then call
- * <code>TypeDeclaration.setInterface(true)</code>.
- * </p>
- * <p>
- * To create an enum declaration, use this method and then call
- * <code>TypeDeclaration.setEnumeration(true)</code>.
- * </p>
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @return a new unparented type declaration node
- */
- public TypeDeclaration newTypeDeclaration() {
- TypeDeclaration result = new TypeDeclaration(this);
- return result;
- }
-
- /**
- * Creates an unparented method declaration node owned by this AST.
- * By default, the declaration is for a method of an unspecified, but
- * legal, name; no modifiers; no doc comment; no parameters; return
- * type void; no extra array dimensions; no thrown exceptions; and no
- * body (as opposed to an empty body).
- * <p>
- * To create a constructor, use this method and then call
- * <code>FunctionDeclaration.setConstructor(true)</code> and
- * <code>FunctionDeclaration.setName(className)</code>.
- * </p>
- *
- * @return a new unparented method declaration node
- */
- public FunctionDeclaration newFunctionDeclaration() {
- FunctionDeclaration result = new FunctionDeclaration(this);
- result.setConstructor(false);
- return result;
- }
-
- /**
- * Creates an unparented single variable declaration node owned by this AST.
- * By default, the declaration is for a variable with an unspecified, but
- * legal, name and type; no modifiers; no array dimensions after the
- * variable; no initializer; not variable arity.
- *
- * @return a new unparented single variable declaration node
- */
- public SingleVariableDeclaration newSingleVariableDeclaration() {
- SingleVariableDeclaration result = new SingleVariableDeclaration(this);
- return result;
- }
-
- /**
- * Creates an unparented variable declaration fragment node owned by this
- * AST. By default, the fragment is for a variable with an unspecified, but
- * legal, name; no extra array dimensions; and no initializer.
- *
- * @return a new unparented variable declaration fragment node
- */
- public VariableDeclarationFragment newVariableDeclarationFragment() {
- VariableDeclarationFragment result = new VariableDeclarationFragment(this);
- return result;
- }
-
- /*
- * Creates an unparented initializer node owned by this AST, with an
- * empty block. By default, the initializer has no modifiers and
- * an empty block.
- *
- * @return a new unparented initializer node
- */
- public Initializer newInitializer() {
- Initializer result = new Initializer(this);
- return result;
- }
-
- /**
- * Creates and returns a new unparented modifier node for the given
- * modifier.
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @param keyword one of the modifier keyword constants
- * @return a new unparented modifier node
- * @exception IllegalArgumentException if the primitive type code is invalid
- * @exception UnsupportedOperationException if this operation is used in
- * a JLS2 AST
- */
- public Modifier newModifier(Modifier.ModifierKeyword keyword) {
- Modifier result = new Modifier(this);
- result.setKeyword(keyword);
- return result;
- }
-
- /**
- * Creates and returns a list of new unparented modifier nodes
- * for the given modifier flags.
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @param flags bitwise or of modifier flags declared on {@link Modifier}
- * @return a possibly empty list of new unparented modifier nodes
- * (element type <code>Modifier</code>)
- * @exception UnsupportedOperationException if this operation is used in
- * a JLS2 AST
- */
- public List newModifiers(int flags) {
- if (this.apiLevel == AST.JLS2) {
- unsupportedIn2();
- }
- List result = new ArrayList(3); // 3 modifiers is more than average
- if (Modifier.isPublic(flags)) {
- result.add(newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
- }
- if (Modifier.isProtected(flags)) {
- result.add(newModifier(Modifier.ModifierKeyword.PROTECTED_KEYWORD));
- }
- if (Modifier.isPrivate(flags)) {
- result.add(newModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD));
- }
- if (Modifier.isAbstract(flags)) {
- result.add(newModifier(Modifier.ModifierKeyword.ABSTRACT_KEYWORD));
- }
- if (Modifier.isStatic(flags)) {
- result.add(newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD));
- }
- if (Modifier.isFinal(flags)) {
- result.add(newModifier(Modifier.ModifierKeyword.FINAL_KEYWORD));
- }
- if (Modifier.isSynchronized(flags)) {
- result.add(newModifier(Modifier.ModifierKeyword.SYNCHRONIZED_KEYWORD));
- }
- if (Modifier.isNative(flags)) {
- result.add(newModifier(Modifier.ModifierKeyword.NATIVE_KEYWORD));
- }
- if (Modifier.isStrictfp(flags)) {
- result.add(newModifier(Modifier.ModifierKeyword.STRICTFP_KEYWORD));
- }
- if (Modifier.isTransient(flags)) {
- result.add(newModifier(Modifier.ModifierKeyword.TRANSIENT_KEYWORD));
- }
- if (Modifier.isVolatile(flags)) {
- result.add(newModifier(Modifier.ModifierKeyword.VOLATILE_KEYWORD));
- }
- return result;
- }
-
- //=============================== COMMENTS ===========================
-
- /**
- * Creates and returns a new block comment placeholder node.
- * <p>
- * Note that this node type is used to recording the source
- * range where a comment was found in the source string.
- * These comment nodes are normally found (only) in
- * {@linkplain JavaScriptUnit#getCommentList()
- * the comment table} for parsed javaScript units.
- * </p>
- *
- * @return a new unparented block comment node
- */
- public BlockComment newBlockComment() {
- BlockComment result = new BlockComment(this);
- return result;
- }
-
- /**
- * Creates and returns a new line comment placeholder node.
- * <p>
- * Note that this node type is used to recording the source
- * range where a comment was found in the source string.
- * These comment nodes are normally found (only) in
- * {@linkplain JavaScriptUnit#getCommentList()
- * the comment table} for parsed javaScript units.
- * </p>
- *
- * @return a new unparented line comment node
- */
- public LineComment newLineComment() {
- LineComment result = new LineComment(this);
- return result;
- }
-
- public ListExpression newListExpression() {
- ListExpression result = new ListExpression(this);
- return result;
- }
-
- /**
- * Creates and returns a new doc comment node.
- * Initially the new node has an empty list of tag elements
- * (and, for backwards compatability, an unspecified, but legal,
- * doc comment string)
- *
- * @return a new unparented doc comment node
- */
- public JSdoc newJSdoc() {
- JSdoc result = new JSdoc(this);
- return result;
- }
-
- /**
- * Creates and returns a new tag element node.
- * Initially the new node has no tag name and an empty list of fragments.
- * <p>
- * Note that this node type is used only inside doc comments
- * ({@link JSdoc}).
- * </p>
- *
- * @return a new unparented tag element node
- */
- public TagElement newTagElement() {
- TagElement result = new TagElement(this);
- return result;
- }
-
- /**
- * Creates and returns a new text element node.
- * Initially the new node has an empty text string.
- * <p>
- * Note that this node type is used only inside doc comments
- * ({@link JSdoc Javadoc}).
- * </p>
- *
- * @return a new unparented text element node
- */
- public TextElement newTextElement() {
- TextElement result = new TextElement(this);
- return result;
- }
-
- /**
- * Creates and returns a new member reference node.
- * Initially the new node has no qualifier name and
- * an unspecified, but legal, member name.
- * <p>
- * Note that this node type is used only inside doc comments
- * ({@link JSdoc}).
- * </p>
- *
- * @return a new unparented member reference node
- */
- public MemberRef newMemberRef() {
- MemberRef result = new MemberRef(this);
- return result;
- }
-
- /**
- * Creates and returns a new method reference node.
- * Initially the new node has no qualifier name,
- * an unspecified, but legal, method name, and an
- * empty parameter list.
- * <p>
- * Note that this node type is used only inside doc comments
- * ({@link JSdoc Javadoc}).
- * </p>
- *
- * @return a new unparented method reference node
- */
- public FunctionRef newFunctionRef() {
- FunctionRef result = new FunctionRef(this);
- return result;
- }
-
- /**
- * Creates and returns a new method reference node.
- * Initially the new node has an unspecified, but legal,
- * type, not variable arity, and no parameter name.
- * <p>
- * Note that this node type is used only inside doc comments
- * ({@link JSdoc}).
- * </p>
- *
- * @return a new unparented method reference parameter node
- */
- public FunctionRefParameter newFunctionRefParameter() {
- FunctionRefParameter result = new FunctionRefParameter(this);
- return result;
- }
-
- //=============================== STATEMENTS ===========================
- /**
- * Creates a new unparented local variable declaration statement node
- * owned by this AST, for the given variable declaration fragment.
- * By default, there are no modifiers and the base type is unspecified
- * (but legal).
- * <p>
- * This method can be used to convert a variable declaration fragment
- * (<code>VariableDeclarationFragment</code>) into a statement
- * (<code>Statement</code>) by wrapping it. Additional variable
- * declaration fragments can be added afterwards.
- * </p>
- *
- * @param fragment the variable declaration fragment
- * @return a new unparented variable declaration statement node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * <li>the variable declaration fragment is null</li>
- * </ul>
- */
- public VariableDeclarationStatement
- newVariableDeclarationStatement(VariableDeclarationFragment fragment) {
- if (fragment == null) {
- throw new IllegalArgumentException();
- }
- VariableDeclarationStatement result =
- new VariableDeclarationStatement(this);
- result.fragments().add(fragment);
- return result;
- }
-
- /**
- * Creates a new unparented local type declaration statement node
- * owned by this AST, for the given type declaration.
- * <p>
- * This method can be used to convert a type declaration
- * (<code>TypeDeclaration</code>) into a statement
- * (<code>Statement</code>) by wrapping it.
- * </p>
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @param decl the type declaration
- * @return a new unparented local type declaration statement node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public TypeDeclarationStatement
- newTypeDeclarationStatement(TypeDeclaration decl) {
- TypeDeclarationStatement result = new TypeDeclarationStatement(this);
- result.setDeclaration(decl);
- return result;
- }
-
- /**
- * Creates a new unparented local type declaration statement node
- * owned by this AST, for the given type declaration.
- * <p>
- * This method can be used to convert any kind of type declaration
- * (<code>AbstractTypeDeclaration</code>) into a statement
- * (<code>Statement</code>) by wrapping it.
- * </p>
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @param decl the type declaration
- * @return a new unparented local type declaration statement node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public TypeDeclarationStatement
- newTypeDeclarationStatement(AbstractTypeDeclaration decl) {
- TypeDeclarationStatement result = new TypeDeclarationStatement(this);
- if (this.apiLevel == AST.JLS2) {
- result.internalSetTypeDeclaration((TypeDeclaration) decl);
- }
- if (this.apiLevel >= AST.JLS3) {
- result.setDeclaration(decl);
- }
- return result;
- }
-
- /**
- * Creates an unparented block node owned by this AST, for an empty list
- * of statements.
- *
- * @return a new unparented, empty block node
- */
- public Block newBlock() {
- return new Block(this);
- }
-
- /**
- * Creates an unparented continue statement node owned by this AST.
- * The continue statement has no label.
- *
- * @return a new unparented continue statement node
- */
- public ContinueStatement newContinueStatement() {
- return new ContinueStatement(this);
- }
-
- /**
- * Creates an unparented break statement node owned by this AST.
- * The break statement has no label.
- *
- * @return a new unparented break statement node
- */
- public BreakStatement newBreakStatement() {
- return new BreakStatement(this);
- }
-
- /**
- * Creates a new unparented expression statement node owned by this AST,
- * for the given expression.
- * <p>
- * This method can be used to convert an expression
- * (<code>Expression</code>) into a statement (<code>Type</code>)
- * by wrapping it. Note, however, that the result is only legal for
- * limited expression types, including method invocations, assignments,
- * and increment/decrement operations.
- * </p>
- *
- * @param expression the expression
- * @return a new unparented statement node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public ExpressionStatement newExpressionStatement(Expression expression) {
- ExpressionStatement result = new ExpressionStatement(this);
- result.setExpression(expression);
- return result;
- }
-
- /**
- * Creates a new unparented if statement node owned by this AST.
- * By default, the expression is unspecified (but legal),
- * the then statement is an empty block, and there is no else statement.
- *
- * @return a new unparented if statement node
- */
- public IfStatement newIfStatement() {
- return new IfStatement(this);
- }
-
- /**
- * Creates a new unparented while statement node owned by this AST.
- * By default, the expression is unspecified (but legal), and
- * the body statement is an empty block.
- *
- * @return a new unparented while statement node
- */
- public WhileStatement newWhileStatement() {
- return new WhileStatement(this);
- }
-
- /**
- * Creates a new unparented with statement node owned by this AST.
- * By default, the expression is unspecified (but legal), and
- * the body statement is an empty block.
- *
- * @return a new unparented with statement node
- */
- public WithStatement newWithStatement() {
- return new WithStatement(this);
- }
-
- /**
- * Creates a new unparented do statement node owned by this AST.
- * By default, the expression is unspecified (but legal), and
- * the body statement is an empty block.
- *
- * @return a new unparented do statement node
- */
- public DoStatement newDoStatement() {
- return new DoStatement(this);
- }
-
- /**
- * Creates a new unparented try statement node owned by this AST.
- * By default, the try statement has an empty block, no catch
- * clauses, and no finally block.
- *
- * @return a new unparented try statement node
- */
- public TryStatement newTryStatement() {
- return new TryStatement(this);
- }
-
- /**
- * Creates a new unparented catch clause node owned by this AST.
- * By default, the catch clause declares an unspecified, but legal,
- * exception declaration and has an empty block.
- *
- * @return a new unparented catch clause node
- */
- public CatchClause newCatchClause() {
- return new CatchClause(this);
- }
-
- /**
- * Creates a new unparented return statement node owned by this AST.
- * By default, the return statement has no expression.
- *
- * @return a new unparented return statement node
- */
- public ReturnStatement newReturnStatement() {
- return new ReturnStatement(this);
- }
-
- /**
- * Creates a new unparented throw statement node owned by this AST.
- * By default, the expression is unspecified, but legal.
- *
- * @return a new unparented throw statement node
- */
- public ThrowStatement newThrowStatement() {
- return new ThrowStatement(this);
- }
-
- /**
- * Creates a new unparented empty statement node owned by this AST.
- *
- * @return a new unparented empty statement node
- */
- public EmptyStatement newEmptyStatement() {
- return new EmptyStatement(this);
- }
-
- /**
- * Creates a new unparented labeled statement node owned by this AST.
- * By default, the label and statement are both unspecified, but legal.
- *
- * @return a new unparented labeled statement node
- */
- public LabeledStatement newLabeledStatement() {
- return new LabeledStatement(this);
- }
-
- /**
- * Creates a new unparented switch statement node owned by this AST.
- * By default, the expression is unspecified, but legal, and there are
- * no statements or switch cases.
- *
- * @return a new unparented labeled statement node
- */
- public SwitchStatement newSwitchStatement() {
- return new SwitchStatement(this);
- }
-
- /**
- * Creates a new unparented switch case statement node owned by
- * this AST. By default, the expression is unspecified, but legal.
- *
- * @return a new unparented switch case node
- */
- public SwitchCase newSwitchCase() {
- return new SwitchCase(this);
- }
-
-
- /**
- * Creates a new unparented for statement node owned by this AST.
- * By default, there are no initializers, no condition expression,
- * no updaters, and the body is an empty block.
- *
- * @return a new unparented for statement node
- */
- public ForStatement newForStatement() {
- return new ForStatement(this);
- }
-
- /**
- * Creates a new unparented for..in statement node owned by this AST.
- * By default, there are no initializers, no condition expression,
- * no updaters, and the body is an empty block.
- *
- * @return a new unparented for..in statement node
- */
- public ForInStatement newForInStatement() {
- return new ForInStatement(this);
- }
-
- /*
- * Creates a new unparented enhanced for statement node owned by this AST.
- * By default, the paramter and expression are unspecified
- * but legal subtrees, and the body is an empty block.
- *
- * @return a new unparented throw statement node
- * @exception UnsupportedOperationException if this operation is used in
- * a JLS2 AST
- */
- public EnhancedForStatement newEnhancedForStatement() {
- return new EnhancedForStatement(this);
- }
-
- //=============================== EXPRESSIONS ===========================
- /**
- * Creates and returns a new unparented string literal node for
- * the empty string literal.
- *
- * @return a new unparented string literal node
- */
- public StringLiteral newStringLiteral() {
- return new StringLiteral(this);
- }
-
-
- /**
- * Creates and returns a new unparented character literal node.
- * Initially the node has an unspecified character literal.
- *
- * @return a new unparented character literal node
- */
- public CharacterLiteral newCharacterLiteral() {
- return new CharacterLiteral(this);
- }
-
-
-
- /**
- * Creates and returns a new Regular Expression literal node.
- * Initially the node has an unspecified character literal.
- *
- * @return a new unparented regular expression literal node
- */ public RegularExpressionLiteral newRegularExpressionLiteral() {
- return new RegularExpressionLiteral(this);
- }
-/**
- * Creates and returns a new unparented number literal node.
- *
- * @param literal the token for the numeric literal as it would
- * appear in JavaScript source code
- * @return a new unparented number literal node
- * @exception IllegalArgumentException if the literal is null
- */
- public NumberLiteral newNumberLiteral(String literal) {
- if (literal == null) {
- throw new IllegalArgumentException();
- }
- NumberLiteral result = new NumberLiteral(this);
- result.setToken(literal);
- return result;
- }
-
- /**
- * Creates and returns a new unparented number literal node.
- * Initially the number literal token is <code>"0"</code>.
- *
- * @return a new unparented number literal node
- */
- public NumberLiteral newNumberLiteral() {
- NumberLiteral result = new NumberLiteral(this);
- return result;
- }
-
- /**
- * Creates and returns a new unparented null literal node.
- *
- * @return a new unparented null literal node
- */
- public NullLiteral newNullLiteral() {
- return new NullLiteral(this);
- }
-
-
- /**
- * Creates and returns a new unparented 'undefined' literal node.
- *
- * @return a new unparented 'undefined' literal node
- */
- public UndefinedLiteral newUndefinedLiteral() {
- return new UndefinedLiteral(this);
- }
-
- /**
- * Creates and returns a new unparented boolean literal node.
- * <p>
- * For example, the assignment expression <code>foo = true</code>
- * is generated by the following snippet:
- * <code>
- * <pre>
- * Assignment e= ast.newAssignment();
- * e.setLeftHandSide(ast.newSimpleName("foo"));
- * e.setRightHandSide(ast.newBooleanLiteral(true));
- * </pre>
- * </code>
- * </p>
- *
- * @param value the boolean value
- * @return a new unparented boolean literal node
- */
- public BooleanLiteral newBooleanLiteral(boolean value) {
- BooleanLiteral result = new BooleanLiteral(this);
- result.setBooleanValue(value);
- return result;
- }
-
- /**
- * Creates and returns a new unparented assignment expression node
- * owned by this AST. By default, the assignment operator is "=" and
- * the left and right hand side expressions are unspecified, but
- * legal, names.
- *
- * @return a new unparented assignment expression node
- */
- public Assignment newAssignment() {
- Assignment result = new Assignment(this);
- return result;
- }
-
- /**
- * Creates an unparented method invocation expression node owned by this
- * AST. By default, the name of the method is unspecified (but legal)
- * there is no receiver expression, no type arguments, and the list of
- * arguments is empty.
- *
- * @return a new unparented method invocation expression node
- */
- public FunctionInvocation newFunctionInvocation() {
- FunctionInvocation result = new FunctionInvocation(this);
- return result;
- }
-
- /**
- * Creates an unparented "super" method invocation expression node owned by
- * this AST. By default, the name of the method is unspecified (but legal)
- * there is no qualifier, no type arguments, and the list of arguments is empty.
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @return a new unparented "super" method invocation
- * expression node
- */
- public SuperMethodInvocation newSuperMethodInvocation() {
- SuperMethodInvocation result = new SuperMethodInvocation(this);
- return result;
- }
-
- /**
- * Creates an unparented alternate constructor ("this(...);") invocation
- * statement node owned by this AST. By default, the lists of arguments
- * and type arguments are both empty.
- * <p>
- * Note that this type of node is a Statement, whereas a regular
- * method invocation is an Expression. The only valid use of these
- * statements are as the first statement of a constructor body.
- * </p>
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @return a new unparented alternate constructor invocation statement node
- */
- public ConstructorInvocation newConstructorInvocation() {
- ConstructorInvocation result = new ConstructorInvocation(this);
- return result;
- }
-
- /**
- * Creates an unparented alternate super constructor ("super(...);")
- * invocation statement node owned by this AST. By default, there is no
- * qualifier, no type arguments, and the list of arguments is empty.
- * <p>
- * Note that this type of node is a Statement, whereas a regular
- * super method invocation is an Expression. The only valid use of these
- * statements are as the first statement of a constructor body.
- * </p>
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @return a new unparented super constructor invocation statement node
- */
- public SuperConstructorInvocation newSuperConstructorInvocation() {
- SuperConstructorInvocation result =
- new SuperConstructorInvocation(this);
- return result;
- }
-
- /**
- * Creates a new unparented local variable declaration expression node
- * owned by this AST, for the given variable declaration fragment. By
- * default, there are no modifiers and the base type is unspecified
- * (but legal).
- * <p>
- * This method can be used to convert a variable declaration fragment
- * (<code>VariableDeclarationFragment</code>) into an expression
- * (<code>Expression</code>) by wrapping it. Additional variable
- * declaration fragments can be added afterwards.
- * </p>
- *
- * @param fragment the first variable declaration fragment
- * @return a new unparented variable declaration expression node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * <li>the given fragment is null</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public VariableDeclarationExpression
- newVariableDeclarationExpression(VariableDeclarationFragment fragment) {
- if (fragment == null) {
- throw new IllegalArgumentException();
- }
- VariableDeclarationExpression result =
- new VariableDeclarationExpression(this);
- result.fragments().add(fragment);
- return result;
- }
-
- /**
- * Creates a new unparented field declaration node owned by this AST,
- * for the given variable declaration fragment. By default, there are no
- * modifiers, no doc comment, and the base type is unspecified
- * (but legal).
- * <p>
- * This method can be used to wrap a variable declaration fragment
- * (<code>VariableDeclarationFragment</code>) into a field declaration
- * suitable for inclusion in the body of a type declaration
- * (<code>FieldDeclaration</code> implements <code>BodyDeclaration</code>).
- * Additional variable declaration fragments can be added afterwards.
- * </p>
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @param fragment the variable declaration fragment
- * @return a new unparented field declaration node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * <li>the given fragment is null</li>
- * </ul>
- */
- public FieldDeclaration newFieldDeclaration(VariableDeclarationFragment fragment) {
- if (fragment == null) {
- throw new IllegalArgumentException();
- }
- FieldDeclaration result = new FieldDeclaration(this);
- result.fragments().add(fragment);
- return result;
- }
-
- /**
- * Creates and returns a new unparented "this" expression node
- * owned by this AST. By default, there is no qualifier.
- *
- * @return a new unparented "this" expression node
- */
- public ThisExpression newThisExpression() {
- ThisExpression result = new ThisExpression(this);
- return result;
- }
-
- /**
- * Creates and returns a new unparented field access expression node
- * owned by this AST. By default, the expression and field are both
- * unspecified, but legal, names.
- *
- * @return a new unparented field access expression node
- */
- public FieldAccess newFieldAccess() {
- FieldAccess result = new FieldAccess(this);
- return result;
- }
-
- /**
- * Creates and returns a new unparented super field access expression node
- * owned by this AST. By default, the expression and field are both
- * unspecified, but legal, names.
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @return a new unparented super field access expression node
- */
- public SuperFieldAccess newSuperFieldAccess() {
- SuperFieldAccess result = new SuperFieldAccess(this);
- return result;
- }
-
- /**
- * Creates and returns a new unparented type literal expression node
- * owned by this AST. By default, the type is unspecified (but legal).
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @return a new unparented type literal node
- */
- public TypeLiteral newTypeLiteral() {
- TypeLiteral result = new TypeLiteral(this);
- return result;
- }
-
- /**
- * Creates and returns a new unparented function expression node
- * owned by this AST.
- *
- * @return a new unparented function expression node
- */
- public FunctionExpression newFunctionExpression() {
- FunctionExpression result = new FunctionExpression(this);
- return result;
- }
-
- /**
- * Creates and returns a new unparented object literal expression node
- * owned by this AST.
- *
- * @return a new unparented object literal expression node
- */
- public ObjectLiteral newObjectLiteral() {
- ObjectLiteral result = new ObjectLiteral(this);
- return result;
- }
-
- /**
- * Creates and returns a new unparented object literal field expression node
- * owned by this AST.
- *
- * @return a new unparented object literal field expression node
- */
- public ObjectLiteralField newObjectLiteralField() {
- ObjectLiteralField result = new ObjectLiteralField(this);
- return result;
- }
-
- /**
- * Creates and returns a new unparented parenthesized expression node
- * owned by this AST. By default, the expression is unspecified (but legal).
- *
- * @return a new unparented parenthesized expression node
- */
- public ParenthesizedExpression newParenthesizedExpression() {
- ParenthesizedExpression result = new ParenthesizedExpression(this);
- return result;
- }
-
- /**
- * Creates and returns a new unparented infix expression node
- * owned by this AST. By default, the operator and left and right
- * operand are unspecified (but legal), and there are no extended
- * operands.
- *
- * @return a new unparented infix expression node
- */
- public InfixExpression newInfixExpression() {
- InfixExpression result = new InfixExpression(this);
- return result;
- }
-
- /**
- * Creates and returns a new unparented instanceof expression node
- * owned by this AST. By default, the operator and left and right
- * operand are unspecified (but legal).
- *
- * @return a new unparented instanceof expression node
- */
- public InstanceofExpression newInstanceofExpression() {
- InstanceofExpression result = new InstanceofExpression(this);
- return result;
- }
-
- /**
- * Creates and returns a new unparented postfix expression node
- * owned by this AST. By default, the operator and operand are
- * unspecified (but legal).
- *
- * @return a new unparented postfix expression node
- */
- public PostfixExpression newPostfixExpression() {
- PostfixExpression result = new PostfixExpression(this);
- return result;
- }
-
- /**
- * Creates and returns a new unparented prefix expression node
- * owned by this AST. By default, the operator and operand are
- * unspecified (but legal).
- *
- * @return a new unparented prefix expression node
- */
- public PrefixExpression newPrefixExpression() {
- PrefixExpression result = new PrefixExpression(this);
- return result;
- }
-
- /**
- * Creates and returns a new unparented array access expression node
- * owned by this AST. By default, the array and index expression are
- * both unspecified (but legal).
- *
- * @return a new unparented array access expression node
- */
- public ArrayAccess newArrayAccess() {
- ArrayAccess result = new ArrayAccess(this);
- return result;
- }
-
- /**
- * Creates and returns a new unparented array creation expression node
- * owned by this AST. By default, the array type is an unspecified
- * 1-dimensional array, the list of dimensions is empty, and there is no
- * array initializer.
- *
- * @return a new unparented array creation expression node
- */
- public ArrayCreation newArrayCreation() {
- ArrayCreation result = new ArrayCreation(this);
- return result;
- }
-
- /**
- * Creates and returns a new unparented class instance creation
- * ("new") expression node owned by this AST. By default,
- * there is no qualifying expression, no type parameters,
- * an unspecified (but legal) type name, an empty list of
- * arguments, and does not declare an anonymous class declaration.
- *
- * @return a new unparented class instance creation expression node
- */
- public ClassInstanceCreation newClassInstanceCreation() {
- ClassInstanceCreation result = new ClassInstanceCreation(this);
- return result;
- }
-
- /**
- * Creates and returns a new unparented anonymous class declaration
- * node owned by this AST. By default, the body declaration list is empty.
- *
- * @return a new unparented anonymous class declaration node
- */
- public AnonymousClassDeclaration newAnonymousClassDeclaration() {
- AnonymousClassDeclaration result = new AnonymousClassDeclaration(this);
- return result;
- }
-
- /**
- * Creates and returns a new unparented array initializer node
- * owned by this AST. By default, the initializer has no expressions.
- *
- * @return a new unparented array initializer node
- */
- public ArrayInitializer newArrayInitializer() {
- ArrayInitializer result = new ArrayInitializer(this);
- return result;
- }
-
- /**
- * Creates and returns a new unparented conditional expression node
- * owned by this AST. By default, the condition and both expressions
- * are unspecified (but legal).
- *
- * @return a new unparented array conditional expression node
- */
- public ConditionalExpression newConditionalExpression() {
- ConditionalExpression result = new ConditionalExpression(this);
- return result;
- }
-
- /**
- * Enables the recording of changes to the given compilation
- * unit and its descendents. The javaScript unit must have
- * been created by <code>ASTParser</code> and still be in
- * its original state. Once recording is on,
- * arbitrary changes to the subtree rooted at the compilation
- * unit are recorded internally. Once the modification has
- * been completed, call <code>rewrite</code> to get an object
- * representing the corresponding edits to the original
- * source code string.
- *
- * @exception IllegalArgumentException if this javaScript unit is
- * marked as unmodifiable, or if this javaScript unit has already
- * been tampered with, or if recording has already been enabled,
- * or if <code>root</code> is not owned by this AST
- * @see JavaScriptUnit#recordModifications()
- */
- void recordModifications(JavaScriptUnit root) {
- if(this.modificationCount != this.originalModificationCount) {
- throw new IllegalArgumentException("AST is already modified"); //$NON-NLS-1$
- } else if(this.rewriter != null) {
- throw new IllegalArgumentException("AST modifications are already recorded"); //$NON-NLS-1$
- } else if((root.getFlags() & ASTNode.PROTECT) != 0) {
- throw new IllegalArgumentException("Root node is unmodifiable"); //$NON-NLS-1$
- } else if(root.getAST() != this) {
- throw new IllegalArgumentException("Root node is not owned by this ast"); //$NON-NLS-1$
- }
-
- this.rewriter = new InternalASTRewrite(root);
- this.setEventHandler(this.rewriter);
- }
-
- /**
- * Converts all modifications recorded into an object
- * representing the corresponding text edits to the
- * given document containing the original source
- * code for the javaScript unit that gave rise to
- * this AST.
- *
- * @param document original document containing source code
- * for the javaScript unit
- * @param options the table of formatter options
- * (key type: <code>String</code>; value type: <code>String</code>);
- * or <code>null</code> to use the standard global options
- * {@link JavaScriptCore#getOptions() JavaScriptCore.getOptions()}.
- * @return text edit object describing the changes to the
- * document corresponding to the recorded AST modifications
- * @exception IllegalArgumentException if the document passed is
- * <code>null</code> or does not correspond to this AST
- * @exception IllegalStateException if <code>recordModifications</code>
- * was not called to enable recording
- * @see JavaScriptUnit#rewrite(IDocument, Map)
- */
- TextEdit rewrite(IDocument document, Map options) {
- if (document == null) {
- throw new IllegalArgumentException();
- }
- if (this.rewriter == null) {
- throw new IllegalStateException("Modifications record is not enabled"); //$NON-NLS-1$
- }
- return this.rewriter.rewriteAST(document, options);
- }
- /**
- * Returns true if the ast tree was created with bindings, false otherwise
- *
- * @return true if the ast tree was created with bindings, false otherwise
- */
- public boolean hasResolvedBindings() {
- return (this.bits & RESOLVED_BINDINGS) != 0;
- }
-
- /**
- * Returns true if the ast tree was created with statements recovery, false otherwise
- *
- * @return true if the ast tree was created with statements recovery, false otherwise
- */
- public boolean hasStatementsRecovery() {
- return (this.bits & IJavaScriptUnit.ENABLE_STATEMENTS_RECOVERY) != 0;
- }
-
- /**
- * Returns true if the ast tree was created with bindings recovery, false otherwise
- *
- * @return true if the ast tree was created with bindings recovery, false otherwise
- */
- public boolean hasBindingsRecovery() {
- return (this.bits & IJavaScriptUnit.ENABLE_BINDINGS_RECOVERY) != 0;
- }
-
- void setFlag(int newValue) {
- this.bits |= newValue;
- }
-
-}
-
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
deleted file mode 100644
index 89d623fb..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ASTConverter.java
+++ /dev/null
@@ -1,4504 +0,0 @@
-/*******************************************************************************
- * 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
- * bug 227489 - Etienne Pfister <epfister@hsr.ch>
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.dom;
-
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.core.dom.Modifier.ModifierKeyword;
-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.ForeachStatement;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocArgumentExpression;
-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.OperatorIds;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ProgramElement;
-import org.eclipse.wst.jsdt.internal.compiler.ast.StringLiteralConcatenation;
-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.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ExtraCompilerModifiers;
-import org.eclipse.wst.jsdt.internal.compiler.parser.RecoveryScanner;
-import org.eclipse.wst.jsdt.internal.compiler.parser.Scanner;
-import org.eclipse.wst.jsdt.internal.compiler.parser.TerminalTokens;
-
-/**
- * Internal class for converting internal compiler ASTs into public ASTs.
- */
-class ASTConverter {
-
- protected AST ast;
- protected Comment[] commentsTable;
- char[] compilationUnitSource;
- int compilationUnitSourceLength;
- protected DocCommentParser docParser;
- // comments
- protected boolean insideComments;
- protected IProgressMonitor monitor;
- protected Set pendingNameScopeResolution;
- protected Set pendingThisExpressionScopeResolution;
- protected boolean resolveBindings;
- Scanner scanner;
- private DefaultCommentMapper commentMapper;
-
- public ASTConverter(Map options, boolean resolveBindings, IProgressMonitor monitor) {
- this.resolveBindings = resolveBindings;
- Object sourceModeSetting = options.get(JavaScriptCore.COMPILER_SOURCE);
- long sourceLevel = ClassFileConstants.JDK1_3;
- if (JavaScriptCore.VERSION_1_4.equals(sourceModeSetting)) {
- sourceLevel = ClassFileConstants.JDK1_4;
- } else if (JavaScriptCore.VERSION_1_5.equals(sourceModeSetting)) {
- sourceLevel = ClassFileConstants.JDK1_5;
- }
-
- this.scanner = new Scanner(
- true /*comment*/,
- false /*whitespace*/,
- false /*nls*/,
- sourceLevel /*sourceLevel*/,
- null /*taskTags*/,
- null/*taskPriorities*/,
- true/*taskCaseSensitive*/);
- this.monitor = monitor;
- this.insideComments = JavaScriptCore.ENABLED.equals(options.get(JavaScriptCore.COMPILER_DOC_COMMENT_SUPPORT));
- }
-
- protected void adjustSourcePositionsForParent(org.eclipse.wst.jsdt.internal.compiler.ast.Expression expression) {
- int start = expression.sourceStart;
- int end = expression.sourceEnd;
- int leftParentCount = 1;
- int rightParentCount = 0;
- this.scanner.resetTo(start, end);
- try {
- int token = this.scanner.getNextToken();
- expression.sourceStart = this.scanner.currentPosition;
- boolean stop = false;
- while (!stop && ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF)) {
- switch(token) {
- case TerminalTokens.TokenNameLPAREN:
- leftParentCount++;
- break;
- case TerminalTokens.TokenNameRPAREN:
- rightParentCount++;
- if (rightParentCount == leftParentCount) {
- // we found the matching parenthesis
- stop = true;
- }
- }
- }
- expression.sourceEnd = this.scanner.startPosition - 1;
- } catch(InvalidInputException e) {
- // ignore
- }
- }
-
- protected void buildBodyDeclarations(org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration typeDeclaration, AbstractTypeDeclaration typeDecl) {
- // add body declaration in the lexical order
- org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration[] members = typeDeclaration.memberTypes;
- org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration[] fields = typeDeclaration.fields;
- org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration[] methods = typeDeclaration.methods;
-
- int fieldsLength = fields == null? 0 : fields.length;
- int methodsLength = methods == null? 0 : methods.length;
- int membersLength = members == null ? 0 : members.length;
- int fieldsIndex = 0;
- int methodsIndex = 0;
- int membersIndex = 0;
-
- while ((fieldsIndex < fieldsLength)
- || (membersIndex < membersLength)
- || (methodsIndex < methodsLength)) {
- org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration nextFieldDeclaration = null;
- org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration nextMethodDeclaration = null;
- org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration nextMemberDeclaration = null;
-
- int position = Integer.MAX_VALUE;
- int nextDeclarationType = -1;
- if (fieldsIndex < fieldsLength) {
- nextFieldDeclaration = fields[fieldsIndex];
- if (nextFieldDeclaration.declarationSourceStart < position) {
- position = nextFieldDeclaration.declarationSourceStart;
- nextDeclarationType = 0; // FIELD
- }
- }
- if (methodsIndex < methodsLength) {
- nextMethodDeclaration = methods[methodsIndex];
- if (nextMethodDeclaration.declarationSourceStart < position) {
- position = nextMethodDeclaration.declarationSourceStart;
- nextDeclarationType = 1; // METHOD
- }
- }
- if (membersIndex < membersLength) {
- nextMemberDeclaration = members[membersIndex];
- if (nextMemberDeclaration.declarationSourceStart < position) {
- position = nextMemberDeclaration.declarationSourceStart;
- nextDeclarationType = 2; // MEMBER
- }
- }
- switch (nextDeclarationType) {
- case 0 :
- checkAndAddMultipleFieldDeclaration(fields, fieldsIndex, typeDecl.bodyDeclarations());
- fieldsIndex++;
- break;
- case 1 :
- methodsIndex++;
- if (!nextMethodDeclaration.isDefaultConstructor() && !nextMethodDeclaration.isClinit()) {
- typeDecl.bodyDeclarations().add(convert(nextMethodDeclaration));
- }
- break;
- case 2 :
- membersIndex++;
- ASTNode node = convert(nextMemberDeclaration);
- if (node == null) {
- typeDecl.setFlags(typeDecl.getFlags() | ASTNode.MALFORMED);
- } else {
- typeDecl.bodyDeclarations().add(node);
- }
- }
- }
- // Convert javadoc
- convert(typeDeclaration.javadoc, typeDecl);
- }
-
-
- protected void buildBodyDeclarations(org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration expression, AnonymousClassDeclaration anonymousClassDeclaration) {
- // add body declaration in the lexical order
- org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration[] members = expression.memberTypes;
- org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration[] fields = expression.fields;
- org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration[] methods = expression.methods;
-
- int fieldsLength = fields == null? 0 : fields.length;
- int methodsLength = methods == null? 0 : methods.length;
- int membersLength = members == null ? 0 : members.length;
- int fieldsIndex = 0;
- int methodsIndex = 0;
- int membersIndex = 0;
-
- while ((fieldsIndex < fieldsLength)
- || (membersIndex < membersLength)
- || (methodsIndex < methodsLength)) {
- org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration nextFieldDeclaration = null;
- org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration nextMethodDeclaration = null;
- org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration nextMemberDeclaration = null;
-
- int position = Integer.MAX_VALUE;
- int nextDeclarationType = -1;
- if (fieldsIndex < fieldsLength) {
- nextFieldDeclaration = fields[fieldsIndex];
- if (nextFieldDeclaration.declarationSourceStart < position) {
- position = nextFieldDeclaration.declarationSourceStart;
- nextDeclarationType = 0; // FIELD
- }
- }
- if (methodsIndex < methodsLength) {
- nextMethodDeclaration = methods[methodsIndex];
- if (nextMethodDeclaration.declarationSourceStart < position) {
- position = nextMethodDeclaration.declarationSourceStart;
- nextDeclarationType = 1; // METHOD
- }
- }
- if (membersIndex < membersLength) {
- nextMemberDeclaration = members[membersIndex];
- if (nextMemberDeclaration.declarationSourceStart < position) {
- position = nextMemberDeclaration.declarationSourceStart;
- nextDeclarationType = 2; // MEMBER
- }
- }
- switch (nextDeclarationType) {
- case 0 :
- checkAndAddMultipleFieldDeclaration(fields, fieldsIndex, anonymousClassDeclaration.bodyDeclarations());
- fieldsIndex++;
- break;
- case 1 :
- methodsIndex++;
- if (!nextMethodDeclaration.isDefaultConstructor() && !nextMethodDeclaration.isClinit()) {
- anonymousClassDeclaration.bodyDeclarations().add(convert(nextMethodDeclaration));
- }
- break;
- case 2 :
- membersIndex++;
- ASTNode node = convert(nextMemberDeclaration);
- if (node == null) {
- anonymousClassDeclaration.setFlags(anonymousClassDeclaration.getFlags() | ASTNode.MALFORMED);
- } else {
- anonymousClassDeclaration.bodyDeclarations().add(node);
- }
- }
- }
- }
-
- /**
- * @param compilationUnit
- * @param comments
- */
- void buildCommentsTable(JavaScriptUnit compilationUnit, int[][] comments) {
- // Build comment table
- this.commentsTable = new Comment[comments.length];
- int nbr = 0;
- for (int i = 0; i < comments.length; i++) {
- Comment comment = createComment(comments[i]);
- if (comment != null) {
- comment.setAlternateRoot(compilationUnit);
- this.commentsTable[nbr++] = comment;
- }
- }
- // Resize table if necessary
- if (nbr<comments.length) {
- Comment[] newCommentsTable = new Comment[nbr];
- System.arraycopy(this.commentsTable, 0, newCommentsTable, 0, nbr);
- this.commentsTable = newCommentsTable;
- }
- compilationUnit.setCommentTable(this.commentsTable);
- }
-
- protected void checkAndAddMultipleFieldDeclaration(org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration[] fields, int index, List bodyDeclarations) {
- if (fields[index] instanceof org.eclipse.wst.jsdt.internal.compiler.ast.Initializer) {
- org.eclipse.wst.jsdt.internal.compiler.ast.Initializer oldInitializer = (org.eclipse.wst.jsdt.internal.compiler.ast.Initializer) fields[index];
- Initializer initializer = new Initializer(this.ast);
- initializer.setBody(convert(oldInitializer.block));
- setModifiers(initializer, oldInitializer);
- initializer.setSourceRange(oldInitializer.declarationSourceStart, oldInitializer.sourceEnd - oldInitializer.declarationSourceStart + 1);
- // The jsdoc comment is now got from list store in javaScript unit declaration
- convert(oldInitializer.javadoc, initializer);
- bodyDeclarations.add(initializer);
- return;
- }
- if (index > 0 && fields[index - 1].declarationSourceStart == fields[index].declarationSourceStart) {
- // we have a multiple field declaration
- // We retrieve the existing fieldDeclaration to add the new VariableDeclarationFragment
- FieldDeclaration fieldDeclaration = (FieldDeclaration) bodyDeclarations.get(bodyDeclarations.size() - 1);
- fieldDeclaration.fragments().add(convertToVariableDeclarationFragment(fields[index]));
- } else {
- // we can create a new FieldDeclaration
- bodyDeclarations.add(convertToFieldDeclaration(fields[index]));
- }
- }
-
- protected void checkAndAddMultipleLocalDeclaration(org.eclipse.wst.jsdt.internal.compiler.ast.ProgramElement[] stmts, int index, List blockStatements) {
-// if (index > 0
-// && stmts[index - 1] instanceof org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration) {
-// org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration local1 = (org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration) stmts[index - 1];
-// org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration local2 = (org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration) stmts[index];
-// if (local1.declarationSourceStart == local2.declarationSourceStart) {
-// // we have a multiple local declarations
-// // We retrieve the existing VariableDeclarationStatement to add the new VariableDeclarationFragment
-// VariableDeclarationStatement variableDeclarationStatement = (VariableDeclarationStatement) blockStatements.get(blockStatements.size() - 1);
-// variableDeclarationStatement.fragments().add(convertToVariableDeclarationFragment((org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration)stmts[index]));
-// } else {
-// // we can create a new FieldDeclaration
-// blockStatements.add(convertToVariableDeclarationStatement((org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration)stmts[index]));
-// }
-// } else {
-// // we can create a new FieldDeclaration
-// blockStatements.add(convertToVariableDeclarationStatement((org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration)stmts[index]));
-// }
- VariableDeclarationStatement variableDeclarationStatement = convertToVariableDeclarationStatement((org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration)stmts[index]);
- blockStatements.add(variableDeclarationStatement);
- }
-
- protected void checkCanceled() {
- if (this.monitor != null && this.monitor.isCanceled())
- throw new OperationCanceledException();
- }
-
- protected void completeRecord(ArrayType arrayType, org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode astNode) {
- ArrayType array = arrayType;
- int dimensions = array.getDimensions();
- for (int i = 0; i < dimensions; i++) {
- Type componentType = array.getComponentType();
- this.recordNodes(componentType, astNode);
- if (componentType.isArrayType()) {
- array = (ArrayType) componentType;
- }
- }
- }
-
-
- public ASTNode convert(org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration methodDeclaration) {
- checkCanceled();
- FunctionDeclaration methodDecl = new FunctionDeclaration(this.ast);
- setModifiers(methodDecl, methodDeclaration);
- boolean isConstructor = methodDeclaration.isConstructor();
- methodDecl.setConstructor(isConstructor);
- int start = methodDeclaration.sourceStart;
- int end;
- SimpleName methodName =null;
- if (methodDeclaration.selector!=null)
- {
- methodName = new SimpleName(this.ast);
- methodName.internalSetIdentifier(new String(methodDeclaration.selector));
- end = retrieveIdentifierEndPosition(start, methodDeclaration.sourceEnd);
-
- methodName.setSourceRange(start, end - start + 1);
- methodDecl.setName(methodName);
- }
- else
- end= methodDeclaration.sourceStart;
- org.eclipse.wst.jsdt.internal.compiler.ast.Argument[] parameters = methodDeclaration.arguments;
- if (parameters != null) {
- int parametersLength = parameters.length;
- for (int i = 0; i < parametersLength; i++) {
- methodDecl.parameters().add(convert(parameters[i]));
- }
- }
- org.eclipse.wst.jsdt.internal.compiler.ast.ExplicitConstructorCall explicitConstructorCall = null;
- /* need this check because a constructor could have been made a constructor after the
- * method declaration was created, and thus it is not a ConstructorDeclaration
- */
- if (isConstructor && methodDeclaration instanceof ConstructorDeclaration) {
- ConstructorDeclaration constructorDeclaration = (ConstructorDeclaration) methodDeclaration;
- explicitConstructorCall = constructorDeclaration.constructorCall;
- switch(this.ast.apiLevel) {
- case AST.JLS2_INTERNAL :
- // set the return type to VOID
- PrimitiveType returnType = new PrimitiveType(this.ast);
- returnType.setPrimitiveTypeCode(PrimitiveType.VOID);
- returnType.setSourceRange(methodDeclaration.sourceStart, 0);
- methodDecl.internalSetReturnType(returnType);
- break;
- case AST.JLS3 :
- methodDecl.setReturnType2(null);
- }
- } else if (methodDeclaration instanceof org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration) {
- org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration method = (org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration) methodDeclaration;
- org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference typeReference = method.returnType;
- if (typeReference != null) {
- Type returnType = convertType(typeReference,method.inferredType);
- // get the positions of the right parenthesis
- int rightParenthesisPosition = retrieveEndOfRightParenthesisPosition(end, method.bodyEnd);
- int extraDimensions = retrieveExtraDimension(rightParenthesisPosition, method.bodyEnd);
- methodDecl.setExtraDimensions(extraDimensions);
- setTypeForMethodDeclaration(methodDecl, returnType, extraDimensions);
- } else {
- switch(this.ast.apiLevel) {
- case AST.JLS2_INTERNAL :
- methodDecl.setFlags(methodDecl.getFlags() | ASTNode.MALFORMED);
- break;
- case AST.JLS3 :
- methodDecl.setReturnType2(null);
- }
- }
- }
- int declarationSourceStart = methodDeclaration.declarationSourceStart;
- int declarationSourceEnd = methodDeclaration.bodyEnd;
- methodDecl.setSourceRange(declarationSourceStart, declarationSourceEnd - declarationSourceStart + 1);
- int closingPosition = retrieveRightBraceOrSemiColonPosition(methodDeclaration.bodyEnd + 1, methodDeclaration.declarationSourceEnd);
- if (closingPosition != -1) {
- int startPosition = methodDecl.getStartPosition();
- methodDecl.setSourceRange(startPosition, closingPosition - startPosition + 1);
-
- org.eclipse.wst.jsdt.internal.compiler.ast.Statement[] statements = methodDeclaration.statements;
-
- start = retrieveStartBlockPosition(methodDeclaration.sourceStart, declarationSourceEnd);
- end = retrieveEndBlockPosition(methodDeclaration.sourceStart, methodDeclaration.declarationSourceEnd);
- Block block = null;
- if (start != -1 && end != -1) {
- /*
- * start or end can be equal to -1 if we have an interface's method.
- */
- block = new Block(this.ast);
- block.setSourceRange(start, end - start + 1);
- methodDecl.setBody(block);
- }
- if (block != null && (statements != null || explicitConstructorCall != null)) {
- if (explicitConstructorCall != null && explicitConstructorCall.accessMode != org.eclipse.wst.jsdt.internal.compiler.ast.ExplicitConstructorCall.ImplicitSuper) {
- block.statements().add(convert(explicitConstructorCall));
- }
- int statementsLength = statements == null ? 0 : statements.length;
- for (int i = 0; i < statementsLength; i++) {
- if (statements[i] instanceof org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration) {
- checkAndAddMultipleLocalDeclaration(statements, i, block.statements());
- } else if (statements[i] instanceof org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration) { // fix for inner function handling, Etienne Pfister
- org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration method = (org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration) statements[i];
- block.statements().add(convert(method));
- }
- else {
- final Statement statement = convert(statements[i]);
- if (statement != null) {
- block.statements().add(statement);
- }
- }
- }
- }
- if (block != null && (Modifier.isAbstract(methodDecl.getModifiers()) || Modifier.isNative(methodDecl.getModifiers()))) {
- methodDecl.setFlags(methodDecl.getFlags() | ASTNode.MALFORMED);
- }
- } else {
- // syntax error in this method declaration
- if (!methodDeclaration.isAbstract()) {
- start = retrieveStartBlockPosition(methodDeclaration.sourceStart, declarationSourceEnd);
- end = methodDeclaration.bodyEnd;
- // try to get the best end position
- CategorizedProblem[] problems = methodDeclaration.compilationResult().problems;
- if (problems != null) {
- for (int i = 0, max = methodDeclaration.compilationResult().problemCount; i < max; i++) {
- CategorizedProblem currentProblem = problems[i];
- if (currentProblem.getSourceStart() == start && currentProblem.getID() == IProblem.ParsingErrorInsertToComplete) {
- end = currentProblem.getSourceEnd();
- break;
- }
- }
- }
- int startPosition = methodDecl.getStartPosition();
- methodDecl.setSourceRange(startPosition, end - startPosition + 1);
- if (start != -1 && end != -1) {
- /*
- * start or end can be equal to -1 if we have an interface's method.
- */
- Block block = new Block(this.ast);
- block.setSourceRange(start, end - start + 1);
- methodDecl.setBody(block);
- }
- }
- }
-
- // The jsdoc comment is now got from list store in javaScript unit declaration
- convert(methodDeclaration.javadoc, methodDecl);
- if (this.resolveBindings) {
- recordNodes(methodDecl, methodDeclaration);
- if (methodName!=null)
- recordNodes(methodName, methodDeclaration);
- methodDecl.resolveBinding();
- }
- return methodDecl;
- }
-
- public ClassInstanceCreation convert(org.eclipse.wst.jsdt.internal.compiler.ast.AllocationExpression expression) {
- ClassInstanceCreation classInstanceCreation = new ClassInstanceCreation(this.ast);
- if (this.resolveBindings) {
- recordNodes(classInstanceCreation, expression);
- }
- if (expression.type!=null) {
- switch (this.ast.apiLevel) {
- case AST.JLS2_INTERNAL:
- classInstanceCreation.internalSetName(convert(expression.type));
- break;
- case AST.JLS3:
- classInstanceCreation.setType(convertType(expression.type));
- }
- }
- classInstanceCreation.setMember(convert(expression.member));
- classInstanceCreation.setSourceRange(expression.sourceStart, expression.sourceEnd - expression.sourceStart + 1);
- org.eclipse.wst.jsdt.internal.compiler.ast.Expression[] arguments = expression.arguments;
- if (arguments != null) {
- int length = arguments.length;
- for (int i = 0; i < length; i++) {
- classInstanceCreation.arguments().add(convert(arguments[i]));
- }
- }
- removeTrailingCommentFromExpressionEndingWithAParen(classInstanceCreation);
- return classInstanceCreation;
- }
-
- public Expression convert(org.eclipse.wst.jsdt.internal.compiler.ast.AND_AND_Expression expression) {
- InfixExpression infixExpression = new InfixExpression(this.ast);
- infixExpression.setOperator(InfixExpression.Operator.CONDITIONAL_AND);
- if (this.resolveBindings) {
- this.recordNodes(infixExpression, expression);
- }
- final int expressionOperatorID = (expression.bits & org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.OperatorMASK) >> org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.OperatorSHIFT;
- if (expression.left instanceof org.eclipse.wst.jsdt.internal.compiler.ast.BinaryExpression
- && ((expression.left.bits & org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.ParenthesizedMASK) == 0)) {
- // create an extended string literal equivalent => use the extended operands list
- infixExpression.extendedOperands().add(convert(expression.right));
- org.eclipse.wst.jsdt.internal.compiler.ast.Expression leftOperand = expression.left;
- org.eclipse.wst.jsdt.internal.compiler.ast.Expression rightOperand = null;
- do {
- rightOperand = ((org.eclipse.wst.jsdt.internal.compiler.ast.BinaryExpression) leftOperand).right;
- if ((((leftOperand.bits & org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.OperatorMASK) >> org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.OperatorSHIFT) != expressionOperatorID
- && ((leftOperand.bits & org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.ParenthesizedMASK) == 0))
- || ((rightOperand instanceof org.eclipse.wst.jsdt.internal.compiler.ast.BinaryExpression
- && ((rightOperand.bits & org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.OperatorMASK) >> org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.OperatorSHIFT) != expressionOperatorID)
- && ((rightOperand.bits & org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.ParenthesizedMASK) == 0))) {
- List extendedOperands = infixExpression.extendedOperands();
- InfixExpression temp = new InfixExpression(this.ast);
- if (this.resolveBindings) {
- this.recordNodes(temp, expression);
- }
- temp.setOperator(getOperatorFor(expressionOperatorID));
- Expression leftSide = convert(leftOperand);
- temp.setLeftOperand(leftSide);
- temp.setSourceRange(leftSide.getStartPosition(), leftSide.getLength());
- int size = extendedOperands.size();
- for (int i = 0; i < size - 1; i++) {
- Expression expr = temp;
- temp = new InfixExpression(this.ast);
-
- if (this.resolveBindings) {
- this.recordNodes(temp, expression);
- }
- temp.setLeftOperand(expr);
- temp.setOperator(getOperatorFor(expressionOperatorID));
- temp.setSourceRange(expr.getStartPosition(), expr.getLength());
- }
- infixExpression = temp;
- for (int i = 0; i < size; i++) {
- Expression extendedOperand = (Expression) extendedOperands.remove(size - 1 - i);
- temp.setRightOperand(extendedOperand);
- int startPosition = temp.getLeftOperand().getStartPosition();
- temp.setSourceRange(startPosition, extendedOperand.getStartPosition() + extendedOperand.getLength() - startPosition);
- if (temp.getLeftOperand().getNodeType() == ASTNode.INFIX_EXPRESSION) {
- temp = (InfixExpression) temp.getLeftOperand();
- }
- }
- int startPosition = infixExpression.getLeftOperand().getStartPosition();
- infixExpression.setSourceRange(startPosition, expression.sourceEnd - startPosition + 1);
- if (this.resolveBindings) {
- this.recordNodes(infixExpression, expression);
- }
- return infixExpression;
- }
- infixExpression.extendedOperands().add(0, convert(rightOperand));
- leftOperand = ((org.eclipse.wst.jsdt.internal.compiler.ast.BinaryExpression) leftOperand).left;
- } while (leftOperand instanceof org.eclipse.wst.jsdt.internal.compiler.ast.BinaryExpression && ((leftOperand.bits & org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.ParenthesizedMASK) == 0));
- Expression leftExpression = convert(leftOperand);
- infixExpression.setLeftOperand(leftExpression);
- infixExpression.setRightOperand((Expression)infixExpression.extendedOperands().remove(0));
- int startPosition = leftExpression.getStartPosition();
- infixExpression.setSourceRange(startPosition, expression.sourceEnd - startPosition + 1);
- return infixExpression;
- }
- Expression leftExpression = convert(expression.left);
- infixExpression.setLeftOperand(leftExpression);
- infixExpression.setRightOperand(convert(expression.right));
- infixExpression.setOperator(InfixExpression.Operator.CONDITIONAL_AND);
- int startPosition = leftExpression.getStartPosition();
- infixExpression.setSourceRange(startPosition, expression.sourceEnd - startPosition + 1);
- return infixExpression;
- }
-
-
-
- public SingleVariableDeclaration convert(org.eclipse.wst.jsdt.internal.compiler.ast.Argument argument) {
- SingleVariableDeclaration variableDecl = new SingleVariableDeclaration(this.ast);
- setModifiers(variableDecl, argument);
- final SimpleName name = new SimpleName(this.ast);
- name.internalSetIdentifier(new String(argument.name));
- int start = argument.sourceStart;
- int nameEnd = argument.sourceEnd;
- name.setSourceRange(start, nameEnd - start + 1);
- variableDecl.setName(name);
-// final int typeSourceEnd = argument.type.sourceEnd;
- final int extraDimensions = 0;
-// final int extraDimensions = retrieveExtraDimension(nameEnd + 1, typeSourceEnd);
-// variableDecl.setExtraDimensions(extraDimensions);
-// final boolean isVarArgs = argument.isVarArgs();
-// if (isVarArgs && extraDimensions == 0) {
-// // remove the ellipsis from the type source end
-// argument.type.sourceEnd = retrieveEllipsisStartPosition(argument.type.sourceStart, typeSourceEnd);
-// }
- Type type = convertType(argument.type,argument.inferredType);
-// int typeEnd = type.getStartPosition() + type.getLength() - 1;
-// int rightEnd = Math.max(typeEnd, argument.declarationSourceEnd);
- int rightEnd = argument.declarationSourceEnd;
- /*
- * There is extra work to do to set the proper type positions
- * See PR http://bugs.eclipse.org/bugs/show_bug.cgi?id=23284
- */
-// if (isVarArgs) {
-// setTypeForSingleVariableDeclaration(variableDecl, type, extraDimensions + 1);
-// if (extraDimensions != 0) {
-// variableDecl.setFlags(variableDecl.getFlags() | ASTNode.MALFORMED);
-// }
-// } else {
- setTypeForSingleVariableDeclaration(variableDecl, type, extraDimensions);
-// }
- variableDecl.setSourceRange(argument.declarationSourceStart, rightEnd - argument.declarationSourceStart + 1);
-
-// if (isVarArgs) {
-// switch(this.ast.apiLevel) {
-// case AST.JLS2_INTERNAL :
-// variableDecl.setFlags(variableDecl.getFlags() | ASTNode.MALFORMED);
-// break;
-// case AST.JLS3 :
-// variableDecl.setVarargs(true);
-// }
-// }
- if (this.resolveBindings) {
- recordNodes(name, argument);
- recordNodes(variableDecl, argument);
- variableDecl.resolveBinding();
- }
- return variableDecl;
- }
-
-
- public ArrayCreation convert(org.eclipse.wst.jsdt.internal.compiler.ast.ArrayAllocationExpression expression) {
- ArrayCreation arrayCreation = new ArrayCreation(this.ast);
- if (this.resolveBindings) {
- recordNodes(arrayCreation, expression);
- }
- arrayCreation.setSourceRange(expression.sourceStart, expression.sourceEnd - expression.sourceStart + 1);
- org.eclipse.wst.jsdt.internal.compiler.ast.Expression[] dimensions = expression.dimensions;
-
- int dimensionsLength = dimensions.length;
- for (int i = 0; i < dimensionsLength; i++) {
- if (dimensions[i] != null) {
- Expression dimension = convert(dimensions[i]);
- if (this.resolveBindings) {
- recordNodes(dimension, dimensions[i]);
- }
- arrayCreation.dimensions().add(dimension);
- }
- }
- Type type = convertType(expression.type);
- if (this.resolveBindings) {
- recordNodes(type, expression.type);
- }
- ArrayType arrayType = null;
- if (type.isArrayType()) {
- arrayType = (ArrayType) type;
- } else {
- arrayType = this.ast.newArrayType(type, dimensionsLength);
- if (this.resolveBindings) {
- completeRecord(arrayType, expression);
- }
- int start = type.getStartPosition();
- int end = type.getStartPosition() + type.getLength();
- int previousSearchStart = end;
- ArrayType componentType = (ArrayType) type.getParent();
- for (int i = 0; i < dimensionsLength; i++) {
- previousSearchStart = retrieveRightBracketPosition(previousSearchStart + 1, this.compilationUnitSourceLength);
- componentType.setSourceRange(start, previousSearchStart - start + 1);
- componentType = (ArrayType) componentType.getParent();
- }
- }
- arrayCreation.setType(arrayType);
- if (this.resolveBindings) {
- recordNodes(arrayType, expression);
- }
- if (expression.initializer != null) {
- arrayCreation.setInitializer(convert(expression.initializer));
- }
- return arrayCreation;
- }
-
- public ArrayInitializer convert(org.eclipse.wst.jsdt.internal.compiler.ast.ArrayInitializer expression) {
- ArrayInitializer arrayInitializer = new ArrayInitializer(this.ast);
- if (this.resolveBindings) {
- recordNodes(arrayInitializer, expression);
- }
- arrayInitializer.setSourceRange(expression.sourceStart, expression.sourceEnd - expression.sourceStart + 1);
- org.eclipse.wst.jsdt.internal.compiler.ast.Expression[] expressions = expression.expressions;
- if (expressions != null) {
- int length = expressions.length;
- for (int i = 0; i < length; i++) {
- Expression expr = convert(expressions[i]);
- if (this.resolveBindings) {
- recordNodes(expr, expressions[i]);
- }
- arrayInitializer.expressions().add(expr);
- }
- }
- return arrayInitializer;
- }
-
- public ArrayAccess convert(org.eclipse.wst.jsdt.internal.compiler.ast.ArrayReference reference) {
- ArrayAccess arrayAccess = new ArrayAccess(this.ast);
- if (this.resolveBindings) {
- recordNodes(arrayAccess, reference);
- }
- arrayAccess.setSourceRange(reference.sourceStart, reference.sourceEnd - reference.sourceStart + 1);
- arrayAccess.setArray(convert(reference.receiver));
- arrayAccess.setIndex(convert(reference.position));
- return arrayAccess;
- }
-
- public Assignment convert(org.eclipse.wst.jsdt.internal.compiler.ast.Assignment expression) {
- Assignment assignment = new Assignment(this.ast);
- if (this.resolveBindings) {
- recordNodes(assignment, expression);
- }
- Expression lhs = convert(expression.lhs);
- assignment.setLeftHandSide(lhs);
- assignment.setOperator(Assignment.Operator.ASSIGN);
- assignment.setRightHandSide(convert(expression.expression));
- int start = lhs.getStartPosition();
- assignment.setSourceRange(start, expression.sourceEnd - start + 1);
- return assignment;
- }
-
- /*
- * Internal use only
- * Used to convert class body declarations
- */
- public JavaScriptUnit convert(org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode[] nodes, JavaScriptUnit compilationUnit) {
-// typeDecl.setInterface(false);
- int nodesLength = nodes.length;
- for (int i = 0; i < nodesLength; i++) {
- org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode node = nodes[i];
- if (node instanceof org.eclipse.wst.jsdt.internal.compiler.ast.Initializer) {
- org.eclipse.wst.jsdt.internal.compiler.ast.Initializer oldInitializer = (org.eclipse.wst.jsdt.internal.compiler.ast.Initializer) node;
- Initializer initializer = new Initializer(this.ast);
- initializer.setBody(convert(oldInitializer.block));
- setModifiers(initializer, oldInitializer);
- initializer.setSourceRange(oldInitializer.declarationSourceStart, oldInitializer.sourceEnd - oldInitializer.declarationSourceStart + 1);
-// setJavaDocComment(initializer);
-// initializer.setJavadoc(convert(oldInitializer.javadoc));
- convert(oldInitializer.javadoc, initializer);
- compilationUnit.statements().add(initializer);
- } else if (node instanceof org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration) {
- org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration fieldDeclaration = (org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration) node;
- if (i > 0
- && (nodes[i - 1] instanceof org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration)
- && ((org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration)nodes[i - 1]).declarationSourceStart == fieldDeclaration.declarationSourceStart) {
- // we have a multiple field declaration
- // We retrieve the existing fieldDeclaration to add the new VariableDeclarationFragment
- FieldDeclaration currentFieldDeclaration = (FieldDeclaration) compilationUnit.statements().get(compilationUnit.statements().size() - 1);
- currentFieldDeclaration.fragments().add(convertToVariableDeclarationFragment(fieldDeclaration));
- } else {
- // we can create a new FieldDeclaration
- compilationUnit.statements().add(convertToFieldDeclaration(fieldDeclaration));
- }
- } else if(node instanceof org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration) {
- AbstractMethodDeclaration nextMethodDeclaration = (AbstractMethodDeclaration) node;
- if (!nextMethodDeclaration.isDefaultConstructor() && !nextMethodDeclaration.isClinit()) {
- compilationUnit.statements().add(convert(nextMethodDeclaration));
- }
- } else if (node instanceof org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration) {
- org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration localDeclaration = (org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration) node;
- if (i > 0
- && (nodes[i - 1] instanceof org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration)
- && ((org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration)nodes[i - 1]).declarationSourceStart == localDeclaration.declarationSourceStart) {
- // we have a multiple field declaration
- // We retrieve the existing fieldDeclaration to add the new VariableDeclarationFragment
- FieldDeclaration currentFieldDeclaration = (FieldDeclaration) compilationUnit.statements().get(compilationUnit.statements().size() - 1);
- currentFieldDeclaration.fragments().add(convertToVariableDeclarationFragment(localDeclaration));
- } else {
- // we can create a new FieldDeclaration
- compilationUnit.statements().add(convertToFieldDeclaration(localDeclaration));
- }
- }
-// else if(node instanceof org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration) {
-// org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration nextMemberDeclaration = (org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration) node;
-// ASTNode nextMemberDeclarationNode = convert(nextMemberDeclaration);
-// if (nextMemberDeclarationNode == null) {
-// typeDecl.setFlags(typeDecl.getFlags() | ASTNode.MALFORMED);
-// } else {
-// typeDecl.bodyDeclarations().add(nextMemberDeclarationNode);
-// }
-// }
- }
- return compilationUnit;
- }
-
- public Expression convert(org.eclipse.wst.jsdt.internal.compiler.ast.BinaryExpression expression) {
- InfixExpression infixExpression = new InfixExpression(this.ast);
- if (this.resolveBindings) {
- this.recordNodes(infixExpression, expression);
- }
-
- int expressionOperatorID = (expression.bits & org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.OperatorMASK) >> org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.OperatorSHIFT;
- switch (expressionOperatorID) {
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.EQUAL_EQUAL :
- infixExpression.setOperator(InfixExpression.Operator.EQUALS);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.LESS_EQUAL :
- infixExpression.setOperator(InfixExpression.Operator.LESS_EQUALS);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.GREATER_EQUAL :
- infixExpression.setOperator(InfixExpression.Operator.GREATER_EQUALS);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.NOT_EQUAL :
- infixExpression.setOperator(InfixExpression.Operator.NOT_EQUALS);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.LEFT_SHIFT :
- infixExpression.setOperator(InfixExpression.Operator.LEFT_SHIFT);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.RIGHT_SHIFT :
- infixExpression.setOperator(InfixExpression.Operator.RIGHT_SHIFT_SIGNED);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.UNSIGNED_RIGHT_SHIFT :
- infixExpression.setOperator(InfixExpression.Operator.RIGHT_SHIFT_UNSIGNED);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.OR_OR :
- infixExpression.setOperator(InfixExpression.Operator.CONDITIONAL_OR);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.AND_AND :
- infixExpression.setOperator(InfixExpression.Operator.CONDITIONAL_AND);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.PLUS :
- infixExpression.setOperator(InfixExpression.Operator.PLUS);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.MINUS :
- infixExpression.setOperator(InfixExpression.Operator.MINUS);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.REMAINDER :
- infixExpression.setOperator(InfixExpression.Operator.REMAINDER);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.XOR :
- infixExpression.setOperator(InfixExpression.Operator.XOR);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.AND :
- infixExpression.setOperator(InfixExpression.Operator.AND);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.MULTIPLY :
- infixExpression.setOperator(InfixExpression.Operator.TIMES);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.OR :
- infixExpression.setOperator(InfixExpression.Operator.OR);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.DIVIDE :
- infixExpression.setOperator(InfixExpression.Operator.DIVIDE);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.GREATER :
- infixExpression.setOperator(InfixExpression.Operator.GREATER);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.LESS :
- infixExpression.setOperator(InfixExpression.Operator.LESS);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.INSTANCEOF :
- infixExpression.setOperator(InfixExpression.Operator.INSTANCEOF);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.IN:
- infixExpression.setOperator(InfixExpression.Operator.IN);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.EQUAL_EQUAL_EQUAL :
- infixExpression.setOperator(InfixExpression.Operator.EQUAL_EQUAL_EQUAL);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.NOT_EQUAL_EQUAL :
- infixExpression.setOperator(InfixExpression.Operator.NOT_EQUAL_EQUAL);
- break;
- }
-
- if (expression.left instanceof org.eclipse.wst.jsdt.internal.compiler.ast.BinaryExpression
- && ((expression.left.bits & org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.ParenthesizedMASK) == 0)) {
- // create an extended string literal equivalent => use the extended operands list
- infixExpression.extendedOperands().add(convert(expression.right));
- org.eclipse.wst.jsdt.internal.compiler.ast.Expression leftOperand = expression.left;
- org.eclipse.wst.jsdt.internal.compiler.ast.Expression rightOperand = null;
- do {
- rightOperand = ((org.eclipse.wst.jsdt.internal.compiler.ast.BinaryExpression) leftOperand).right;
- if ((((leftOperand.bits & org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.OperatorMASK) >> org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.OperatorSHIFT) != expressionOperatorID
- && ((leftOperand.bits & org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.ParenthesizedMASK) == 0))
- || ((rightOperand instanceof org.eclipse.wst.jsdt.internal.compiler.ast.BinaryExpression
- && ((rightOperand.bits & org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.OperatorMASK) >> org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.OperatorSHIFT) != expressionOperatorID)
- && ((rightOperand.bits & org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.ParenthesizedMASK) == 0))) {
- List extendedOperands = infixExpression.extendedOperands();
- InfixExpression temp = new InfixExpression(this.ast);
- if (this.resolveBindings) {
- this.recordNodes(temp, expression);
- }
- temp.setOperator(getOperatorFor(expressionOperatorID));
- Expression leftSide = convert(leftOperand);
- temp.setLeftOperand(leftSide);
- temp.setSourceRange(leftSide.getStartPosition(), leftSide.getLength());
- int size = extendedOperands.size();
- for (int i = 0; i < size - 1; i++) {
- Expression expr = temp;
- temp = new InfixExpression(this.ast);
-
- if (this.resolveBindings) {
- this.recordNodes(temp, expression);
- }
- temp.setLeftOperand(expr);
- temp.setOperator(getOperatorFor(expressionOperatorID));
- temp.setSourceRange(expr.getStartPosition(), expr.getLength());
- }
- infixExpression = temp;
- for (int i = 0; i < size; i++) {
- Expression extendedOperand = (Expression) extendedOperands.remove(size - 1 - i);
- temp.setRightOperand(extendedOperand);
- int startPosition = temp.getLeftOperand().getStartPosition();
- temp.setSourceRange(startPosition, extendedOperand.getStartPosition() + extendedOperand.getLength() - startPosition);
- if (temp.getLeftOperand().getNodeType() == ASTNode.INFIX_EXPRESSION) {
- temp = (InfixExpression) temp.getLeftOperand();
- }
- }
- int startPosition = infixExpression.getLeftOperand().getStartPosition();
- infixExpression.setSourceRange(startPosition, expression.sourceEnd - startPosition + 1);
- if (this.resolveBindings) {
- this.recordNodes(infixExpression, expression);
- }
- return infixExpression;
- }
- infixExpression.extendedOperands().add(0, convert(rightOperand));
- leftOperand = ((org.eclipse.wst.jsdt.internal.compiler.ast.BinaryExpression) leftOperand).left;
- } while (leftOperand instanceof org.eclipse.wst.jsdt.internal.compiler.ast.BinaryExpression && ((leftOperand.bits & org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.ParenthesizedMASK) == 0));
- Expression leftExpression = convert(leftOperand);
- infixExpression.setLeftOperand(leftExpression);
- infixExpression.setRightOperand((Expression)infixExpression.extendedOperands().remove(0));
- int startPosition = leftExpression.getStartPosition();
- infixExpression.setSourceRange(startPosition, expression.sourceEnd - startPosition + 1);
- return infixExpression;
- } else if (expression.left instanceof StringLiteralConcatenation
- && ((expression.left.bits & org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.ParenthesizedMASK) == 0)
- && (OperatorIds.PLUS == expressionOperatorID)) {
- StringLiteralConcatenation literal = (StringLiteralConcatenation) expression.left;
- final org.eclipse.wst.jsdt.internal.compiler.ast.Expression[] stringLiterals = literal.literals;
- infixExpression.setLeftOperand(convert(stringLiterals[0]));
- infixExpression.setRightOperand(convert(stringLiterals[1]));
- for (int i = 2; i < literal.counter; i++) {
- infixExpression.extendedOperands().add(convert(stringLiterals[i]));
- }
- infixExpression.extendedOperands().add(convert(expression.right));
- int startPosition = literal.sourceStart;
- infixExpression.setSourceRange(startPosition, expression.sourceEnd - startPosition + 1);
- return infixExpression;
- }
- Expression leftExpression = convert(expression.left);
- infixExpression.setLeftOperand(leftExpression);
- infixExpression.setRightOperand(convert(expression.right));
- int startPosition = leftExpression.getStartPosition();
- infixExpression.setSourceRange(startPosition, expression.sourceEnd - startPosition + 1);
- return infixExpression;
- }
-
- public Block convert(org.eclipse.wst.jsdt.internal.compiler.ast.Block statement) {
- Block block = new Block(this.ast);
- if (statement.sourceEnd > 0) {
- block.setSourceRange(statement.sourceStart, statement.sourceEnd - statement.sourceStart + 1);
- }
- org.eclipse.wst.jsdt.internal.compiler.ast.Statement[] statements = statement.statements;
- if (statements != null) {
- int statementsLength = statements.length;
- for (int i = 0; i < statementsLength; i++) {
- if (statements[i] instanceof org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration) {
- checkAndAddMultipleLocalDeclaration(statements, i, block.statements());
- } else {
- Statement statement2 = convert(statements[i]);
- if (statement2 != null) {
- block.statements().add(statement2);
- }
- }
- }
- }
- return block;
- }
-
- public BreakStatement convert(org.eclipse.wst.jsdt.internal.compiler.ast.BreakStatement statement) {
- BreakStatement breakStatement = new BreakStatement(this.ast);
- breakStatement.setSourceRange(statement.sourceStart, statement.sourceEnd - statement.sourceStart + 1);
- if (statement.label != null) {
- final SimpleName name = new SimpleName(this.ast);
- name.internalSetIdentifier(new String(statement.label));
- retrieveIdentifierAndSetPositions(statement.sourceStart, statement.sourceEnd, name);
- breakStatement.setLabel(name);
- }
- return breakStatement;
- }
-
-
- public SwitchCase convert(org.eclipse.wst.jsdt.internal.compiler.ast.CaseStatement statement) {
- SwitchCase switchCase = new SwitchCase(this.ast);
- org.eclipse.wst.jsdt.internal.compiler.ast.Expression constantExpression = statement.constantExpression;
- if (constantExpression == null) {
- switchCase.setExpression(null);
- } else {
- switchCase.setExpression(convert(constantExpression));
- }
- switchCase.setSourceRange(statement.sourceStart, statement.sourceEnd - statement.sourceStart + 1);
- retrieveColonPosition(switchCase);
- return switchCase;
- }
-
- public FunctionExpression convert(org.eclipse.wst.jsdt.internal.compiler.ast.FunctionExpression expression) {
- FunctionExpression functionExpression = new FunctionExpression(this.ast);
- int sourceEnd = expression.sourceEnd;
- if (sourceEnd==0)
- sourceEnd=expression.methodDeclaration.bodyEnd;
- functionExpression.setSourceRange(expression.sourceStart, sourceEnd - expression.sourceStart + 1);
-
- functionExpression.setMethod((FunctionDeclaration)convert(expression.methodDeclaration));
- if (this.resolveBindings) {
- recordNodes(functionExpression, expression);
- }
- return functionExpression;
- }
-
- public ObjectLiteral convert(org.eclipse.wst.jsdt.internal.compiler.ast.ObjectLiteral objLiteral) {
- ObjectLiteral objectLiteral = new ObjectLiteral(this.ast);
- objectLiteral.setSourceRange(objLiteral.sourceStart, objLiteral.sourceEnd - objLiteral.sourceStart + 1);
-
- org.eclipse.wst.jsdt.internal.compiler.ast.ObjectLiteralField[] fields = objLiteral.fields;
- if (fields != null) {
- int fieldsLength = fields.length;
- for (int i = 0; i < fieldsLength; i++) {
-
- ObjectLiteralField objectLiteralField =convert(fields[i]);
- objectLiteral.fields().add(objectLiteralField);
- }
- }
-
- if (this.resolveBindings) {
- recordNodes(objectLiteral, objLiteral);
- }
- return objectLiteral;
- }
-
- public ObjectLiteralField convert(org.eclipse.wst.jsdt.internal.compiler.ast.ObjectLiteralField field) {
- ObjectLiteralField objectLiteralField = new ObjectLiteralField(this.ast);
- objectLiteralField.setSourceRange(field.sourceStart, field.sourceEnd - field.sourceStart + 1);
-
- 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;
- int sourceStart = expression.sourceStart;
- RegularExpressionLiteral literal = new RegularExpressionLiteral(this.ast);
- if (this.resolveBindings) {
- this.recordNodes(literal, expression);
- }
- literal.internalSetRegularExpression(new String(this.compilationUnitSource, sourceStart, length));
- literal.setSourceRange(sourceStart, length);
- removeLeadingAndTrailingCommentsFromLiteral(literal);
- return literal;
- }
-
- public Expression convert(org.eclipse.wst.jsdt.internal.compiler.ast.ClassLiteralAccess expression) {
- TypeLiteral typeLiteral = new TypeLiteral(this.ast);
- if (this.resolveBindings) {
- this.recordNodes(typeLiteral, expression);
- }
- typeLiteral.setSourceRange(expression.sourceStart, expression.sourceEnd - expression.sourceStart + 1);
- typeLiteral.setType(convertType(expression.type));
- return typeLiteral;
- }
-
- public JavaScriptUnit convert(org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration unit, char[] source) {
- if(unit.compilationResult.recoveryScannerData != null) {
- RecoveryScanner recoveryScanner = new RecoveryScanner(this.scanner, unit.compilationResult.recoveryScannerData.removeUnused());
- this.scanner = recoveryScanner;
- this.docParser.scanner = this.scanner;
- }
- this.compilationUnitSource = source;
- this.compilationUnitSourceLength = source.length;
- this.scanner.setSource(source, unit.compilationResult);
- JavaScriptUnit compilationUnit = new JavaScriptUnit(this.ast);
-
- // Parse comments
- int[][] comments = unit.comments;
- if (comments != null) {
- buildCommentsTable(compilationUnit, comments);
- }
-
- // handle the package declaration immediately
- // There is no node corresponding to the package declaration
- if (this.resolveBindings) {
- recordNodes(compilationUnit, unit);
- }
- if (unit.currentPackage != null) {
- PackageDeclaration packageDeclaration = convertPackage(unit);
- compilationUnit.setPackage(packageDeclaration);
- }
- org.eclipse.wst.jsdt.internal.compiler.ast.ImportReference[] imports = unit.imports;
- if (imports != null) {
- int importLength = imports.length;
- for (int i = 0; i < importLength; i++) {
- compilationUnit.imports().add(convertImport(imports[i]));
- }
- }
-
-// org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration[] types = unit.types;
-// if (types != null) {
-// int typesLength = types.length;
-// for (int i = 0; i < typesLength; i++) {
-// org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration declaration = types[i];
-// if (CharOperation.equals(declaration.name, TypeConstants.PACKAGE_INFO_NAME)) {
-// continue;
-// }
-// ASTNode type = convert(declaration);
-// if (type == null) {
-// compilationUnit.setFlags(compilationUnit.getFlags() | ASTNode.MALFORMED);
-// } else {
-// compilationUnit.types().add(type);
-// }
-// }
-// }
- org.eclipse.wst.jsdt.internal.compiler.ast.ProgramElement[] statements = unit.statements;
- if (statements != null) {
- int statementsLength = statements.length;
- for (int i = 0; i < statementsLength; i++) {
-// org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration declaration = types[i];
-// if (CharOperation.equals(declaration.name, TypeConstants.PACKAGE_INFO_NAME)) {
-// continue;
-// }
- ProgramElement programElement=statements[i];
- ASTNode type = null;
- if (programElement instanceof LocalDeclaration )
- {
- checkAndAddMultipleLocalDeclaration(statements, i, compilationUnit.statements());
-
- }
- else if (programElement instanceof AbstractMethodDeclaration )
- {
- type = convert((AbstractMethodDeclaration)programElement);
- }
- else if (programElement instanceof org.eclipse.wst.jsdt.internal.compiler.ast.Statement )
- {
- type = convert((org.eclipse.wst.jsdt.internal.compiler.ast.Statement )programElement);
- }
- else
- throw new RuntimeException(""); //$NON-NLS-1$
-
-
- if (type == null) {
-// compilationUnit.setFlags(compilationUnit.getFlags() | ASTNode.MALFORMED);
- } else {
- compilationUnit.statements().add(type);
- }
- }
- }
- compilationUnit.setSourceRange(unit.sourceStart, unit.sourceEnd - unit.sourceStart + 1);
-
- int problemLength = unit.compilationResult.problemCount;
- if (problemLength != 0) {
- CategorizedProblem[] resizedProblems = null;
- final CategorizedProblem[] problems = unit.compilationResult.getProblems();
- final int realProblemLength=problems.length;
- if (realProblemLength == problemLength) {
- resizedProblems = problems;
- } else {
- System.arraycopy(problems, 0, (resizedProblems = new CategorizedProblem[realProblemLength]), 0, realProblemLength);
- }
- ASTSyntaxErrorPropagator syntaxErrorPropagator = new ASTSyntaxErrorPropagator(resizedProblems);
- compilationUnit.accept(syntaxErrorPropagator);
- ASTRecoveryPropagator recoveryPropagator =
- new ASTRecoveryPropagator(resizedProblems, unit.compilationResult.recoveryScannerData);
- compilationUnit.accept(recoveryPropagator);
- compilationUnit.setProblems(resizedProblems);
- }
- if (this.resolveBindings) {
- lookupForScopes();
- }
- compilationUnit.initCommentMapper(this.scanner);
- return compilationUnit;
- }
-
- public Assignment convert(org.eclipse.wst.jsdt.internal.compiler.ast.CompoundAssignment expression) {
- Assignment assignment = new Assignment(this.ast);
- Expression lhs = convert(expression.lhs);
- assignment.setLeftHandSide(lhs);
- int start = lhs.getStartPosition();
- assignment.setSourceRange(start, expression.sourceEnd - start + 1);
- switch (expression.operator) {
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.PLUS :
- assignment.setOperator(Assignment.Operator.PLUS_ASSIGN);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.MINUS :
- assignment.setOperator(Assignment.Operator.MINUS_ASSIGN);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.MULTIPLY :
- assignment.setOperator(Assignment.Operator.TIMES_ASSIGN);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.DIVIDE :
- assignment.setOperator(Assignment.Operator.DIVIDE_ASSIGN);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.AND :
- assignment.setOperator(Assignment.Operator.BIT_AND_ASSIGN);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.OR :
- assignment.setOperator(Assignment.Operator.BIT_OR_ASSIGN);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.XOR :
- assignment.setOperator(Assignment.Operator.BIT_XOR_ASSIGN);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.REMAINDER :
- assignment.setOperator(Assignment.Operator.REMAINDER_ASSIGN);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.LEFT_SHIFT :
- assignment.setOperator(Assignment.Operator.LEFT_SHIFT_ASSIGN);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.RIGHT_SHIFT :
- assignment.setOperator(Assignment.Operator.RIGHT_SHIFT_SIGNED_ASSIGN);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.UNSIGNED_RIGHT_SHIFT :
- assignment.setOperator(Assignment.Operator.RIGHT_SHIFT_UNSIGNED_ASSIGN);
- break;
- }
- assignment.setRightHandSide(convert(expression.expression));
- if (this.resolveBindings) {
- recordNodes(assignment, expression);
- }
- return assignment;
- }
-
- public ConditionalExpression convert(org.eclipse.wst.jsdt.internal.compiler.ast.ConditionalExpression expression) {
- ConditionalExpression conditionalExpression = new ConditionalExpression(this.ast);
- if (this.resolveBindings) {
- recordNodes(conditionalExpression, expression);
- }
- conditionalExpression.setSourceRange(expression.sourceStart, expression.sourceEnd - expression.sourceStart + 1);
- conditionalExpression.setExpression(convert(expression.condition));
- conditionalExpression.setThenExpression(convert(expression.valueIfTrue));
- conditionalExpression.setElseExpression(convert(expression.valueIfFalse));
- return conditionalExpression;
- }
-
- public ContinueStatement convert(org.eclipse.wst.jsdt.internal.compiler.ast.ContinueStatement statement) {
- ContinueStatement continueStatement = new ContinueStatement(this.ast);
- continueStatement.setSourceRange(statement.sourceStart, statement.sourceEnd - statement.sourceStart + 1);
- if (statement.label != null) {
- final SimpleName name = new SimpleName(this.ast);
- name.internalSetIdentifier(new String(statement.label));
- retrieveIdentifierAndSetPositions(statement.sourceStart, statement.sourceEnd, name);
- continueStatement.setLabel(name);
- }
- return continueStatement;
- }
-
- public DoStatement convert(org.eclipse.wst.jsdt.internal.compiler.ast.DoStatement statement) {
- DoStatement doStatement = new DoStatement(this.ast);
- doStatement.setSourceRange(statement.sourceStart, statement.sourceEnd - statement.sourceStart + 1);
- doStatement.setExpression(convert(statement.condition));
- final Statement action = convert(statement.action);
- if (action == null) return null;
- doStatement.setBody(action);
- return doStatement;
- }
-
- public NumberLiteral convert(org.eclipse.wst.jsdt.internal.compiler.ast.DoubleLiteral expression) {
- int length = expression.sourceEnd - expression.sourceStart + 1;
- int sourceStart = expression.sourceStart;
- NumberLiteral literal = new NumberLiteral(this.ast);
- literal.internalSetToken(new String(this.compilationUnitSource, sourceStart, length));
- if (this.resolveBindings) {
- this.recordNodes(literal, expression);
- }
- literal.setSourceRange(sourceStart, length);
- removeLeadingAndTrailingCommentsFromLiteral(literal);
- return literal;
- }
-
- public EmptyStatement convert(org.eclipse.wst.jsdt.internal.compiler.ast.EmptyStatement statement) {
- EmptyStatement emptyStatement = new EmptyStatement(this.ast);
- emptyStatement.setSourceRange(statement.sourceStart, statement.sourceEnd - statement.sourceStart + 1);
- return emptyStatement;
- }
-
-
- public EmptyExpression convert(org.eclipse.wst.jsdt.internal.compiler.ast.EmptyExpression expression) {
- EmptyExpression emptyExpression = new EmptyExpression(this.ast);
- emptyExpression.setSourceRange(expression.sourceStart, expression.sourceEnd - expression.sourceStart + 1);
- return emptyExpression;
- }
-
-
- public Expression convert(org.eclipse.wst.jsdt.internal.compiler.ast.EqualExpression expression) {
- InfixExpression infixExpression = new InfixExpression(this.ast);
- if (this.resolveBindings) {
- recordNodes(infixExpression, expression);
- }
- Expression leftExpression = convert(expression.left);
- infixExpression.setLeftOperand(leftExpression);
- infixExpression.setRightOperand(convert(expression.right));
- int startPosition = leftExpression.getStartPosition();
- infixExpression.setSourceRange(startPosition, expression.sourceEnd - startPosition + 1);
- switch ((expression.bits & org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.OperatorMASK) >> org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.OperatorSHIFT) {
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.EQUAL_EQUAL :
- infixExpression.setOperator(InfixExpression.Operator.EQUALS);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.NOT_EQUAL :
- infixExpression.setOperator(InfixExpression.Operator.NOT_EQUALS);
- }
- return infixExpression;
-
- }
-
- public Statement convert(org.eclipse.wst.jsdt.internal.compiler.ast.ExplicitConstructorCall statement) {
- Statement newStatement;
- int sourceStart = statement.sourceStart;
- if (statement.isSuperAccess() || statement.isSuper()) {
- SuperConstructorInvocation superConstructorInvocation = new SuperConstructorInvocation(this.ast);
- if (statement.qualification != null) {
- superConstructorInvocation.setExpression(convert(statement.qualification));
- }
- org.eclipse.wst.jsdt.internal.compiler.ast.Expression[] arguments = statement.arguments;
- if (arguments != null) {
- int length = arguments.length;
- for (int i = 0; i < length; i++) {
- superConstructorInvocation.arguments().add(convert(arguments[i]));
- }
- }
- if (statement.typeArguments != null) {
- if (sourceStart > statement.typeArgumentsSourceStart) {
- sourceStart = statement.typeArgumentsSourceStart;
- }
- switch(this.ast.apiLevel) {
- case AST.JLS2_INTERNAL :
- superConstructorInvocation.setFlags(superConstructorInvocation.getFlags() | ASTNode.MALFORMED);
- break;
- case AST.JLS3 :
- for (int i = 0, max = statement.typeArguments.length; i < max; i++) {
- superConstructorInvocation.typeArguments().add(convertType(statement.typeArguments[i]));
- }
- break;
- }
- }
- newStatement = superConstructorInvocation;
- } else {
- ConstructorInvocation constructorInvocation = new ConstructorInvocation(this.ast);
- org.eclipse.wst.jsdt.internal.compiler.ast.Expression[] arguments = statement.arguments;
- if (arguments != null) {
- int length = arguments.length;
- for (int i = 0; i < length; i++) {
- constructorInvocation.arguments().add(convert(arguments[i]));
- }
- }
- if (statement.typeArguments != null) {
- if (sourceStart > statement.typeArgumentsSourceStart) {
- sourceStart = statement.typeArgumentsSourceStart;
- }
- switch(this.ast.apiLevel) {
- case AST.JLS2_INTERNAL :
- constructorInvocation.setFlags(constructorInvocation.getFlags() | ASTNode.MALFORMED);
- break;
- case AST.JLS3 :
- for (int i = 0, max = statement.typeArguments.length; i < max; i++) {
- constructorInvocation.typeArguments().add(convertType(statement.typeArguments[i]));
- }
- break;
- }
- }
- if (statement.qualification != null) {
- // this is an error
- constructorInvocation.setFlags(constructorInvocation.getFlags() | ASTNode.MALFORMED);
- }
- newStatement = constructorInvocation;
- }
- newStatement.setSourceRange(sourceStart, statement.sourceEnd - sourceStart + 1);
- if (this.resolveBindings) {
- recordNodes(newStatement, statement);
- }
- return newStatement;
- }
-
- public Expression convert(org.eclipse.wst.jsdt.internal.compiler.ast.Expression expression) {
- if (expression==null)
- return null;
- if ((expression.bits & org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.ParenthesizedMASK) != 0) {
- return convertToParenthesizedExpression(expression);
- }
- // switch between all types of expression
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.ArrayAllocationExpression) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.ArrayAllocationExpression) expression);
- }
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedAllocationExpression) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedAllocationExpression) expression);
- }
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.AllocationExpression) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.AllocationExpression) expression);
- }
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.ArrayInitializer) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.ArrayInitializer) expression);
- }
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.PrefixExpression) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.PrefixExpression) expression);
- }
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.PostfixExpression) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.PostfixExpression) expression);
- }
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.CompoundAssignment) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.CompoundAssignment) expression);
- }
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.Assignment) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.Assignment) expression);
- }
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.ClassLiteralAccess) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.ClassLiteralAccess) expression);
- }
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.FalseLiteral) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.FalseLiteral) expression);
- }
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.TrueLiteral) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.TrueLiteral) expression);
- }
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.NullLiteral) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.NullLiteral) expression);
- }
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.DoubleLiteral) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.DoubleLiteral) expression);
- }
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.IntLiteralMinValue) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.IntLiteralMinValue) expression);
- }
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.IntLiteral) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.IntLiteral) expression);
- }
- if (expression instanceof StringLiteralConcatenation) {
- return convert((StringLiteralConcatenation) expression);
- }
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.ExtendedStringLiteral) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.ExtendedStringLiteral) expression);
- }
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.StringLiteral) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.StringLiteral) expression);
- }
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.AND_AND_Expression) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.AND_AND_Expression) expression);
- }
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.OR_OR_Expression) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.OR_OR_Expression) expression);
- }
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.EqualExpression) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.EqualExpression) expression);
- }
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.BinaryExpression) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.BinaryExpression) expression);
- }
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.InstanceOfExpression) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.InstanceOfExpression) expression);
- }
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.UnaryExpression) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.UnaryExpression) expression);
- }
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.ConditionalExpression) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.ConditionalExpression) expression);
- }
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.MessageSend) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.MessageSend) expression);
- }
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.Reference) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.Reference) expression);
- }
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference) expression);
- }
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.FunctionExpression) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.FunctionExpression) expression);
- }
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.ObjectLiteral) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.ObjectLiteral) expression);
- }
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.ObjectLiteralField) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.ObjectLiteralField) expression);
- }
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.UndefinedLiteral) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.UndefinedLiteral) expression);
- }
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.RegExLiteral) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.RegExLiteral) expression);
- }
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.ListExpression) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.ListExpression) expression);
- }
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.EmptyExpression) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.EmptyExpression) expression);
- }
- return null;
- }
-
- public StringLiteral convert(org.eclipse.wst.jsdt.internal.compiler.ast.ExtendedStringLiteral expression) {
- expression.computeConstant();
- StringLiteral literal = new StringLiteral(this.ast);
- if (this.resolveBindings) {
- this.recordNodes(literal, expression);
- }
- literal.setLiteralValue(expression.constant.stringValue());
- literal.setSourceRange(expression.sourceStart, expression.sourceEnd - expression.sourceStart + 1);
- return literal;
- }
-
- public BooleanLiteral convert(org.eclipse.wst.jsdt.internal.compiler.ast.FalseLiteral expression) {
- final BooleanLiteral literal = new BooleanLiteral(this.ast);
- literal.setBooleanValue(false);
- if (this.resolveBindings) {
- this.recordNodes(literal, expression);
- }
- literal.setSourceRange(expression.sourceStart, expression.sourceEnd - expression.sourceStart + 1);
- return literal;
- }
-
- public Expression convert(org.eclipse.wst.jsdt.internal.compiler.ast.FieldReference reference) {
- if (reference.receiver.isSuper()) {
- final SuperFieldAccess superFieldAccess = new SuperFieldAccess(this.ast);
- if (this.resolveBindings) {
- recordNodes(superFieldAccess, reference);
- }
- final SimpleName simpleName = new SimpleName(this.ast);
- simpleName.internalSetIdentifier(new String(reference.token));
- int sourceStart = (int)(reference.nameSourcePosition>>>32);
- int length = (int)(reference.nameSourcePosition & 0xFFFFFFFF) - sourceStart + 1;
- simpleName.setSourceRange(sourceStart, length);
- superFieldAccess.setName(simpleName);
- if (this.resolveBindings) {
- recordNodes(simpleName, reference);
- }
- superFieldAccess.setSourceRange(reference.receiver.sourceStart, reference.sourceEnd - reference.receiver.sourceStart + 1);
- return superFieldAccess;
- } else {
- final FieldAccess fieldAccess = new FieldAccess(this.ast);
- if (this.resolveBindings) {
- recordNodes(fieldAccess, reference);
- }
- Expression receiver = convert(reference.receiver);
- fieldAccess.setExpression(receiver);
- final SimpleName simpleName = new SimpleName(this.ast);
- simpleName.internalSetIdentifier(new String(reference.token));
- int sourceStart = (int)(reference.nameSourcePosition>>>32);
- int length = (int)(reference.nameSourcePosition & 0xFFFFFFFF) - sourceStart + 1;
- simpleName.setSourceRange(sourceStart, length);
- fieldAccess.setName(simpleName);
- if (this.resolveBindings) {
- recordNodes(simpleName, reference);
- }
- fieldAccess.setSourceRange(receiver.getStartPosition(), reference.sourceEnd - receiver.getStartPosition() + 1);
- return fieldAccess;
- }
- }
-
- public Statement convert(ForeachStatement statement) {
- switch(this.ast.apiLevel) {
- case AST.JLS2_INTERNAL :
- return createFakeEmptyStatement(statement);
- case AST.JLS3 :
- EnhancedForStatement enhancedForStatement = new EnhancedForStatement(this.ast);
- enhancedForStatement.setParameter(convertToSingleVariableDeclaration(statement.elementVariable));
- org.eclipse.wst.jsdt.internal.compiler.ast.Expression collection = statement.collection;
- if (collection == null) return null; enhancedForStatement.setExpression(convert(collection));
- final Statement action = convert(statement.action);
- if (action == null) return null;
- enhancedForStatement.setBody(action);
- int start = statement.sourceStart;
- int end = statement.sourceEnd;
- enhancedForStatement.setSourceRange(start, end - start + 1);
- return enhancedForStatement;
- default:
- return createFakeEmptyStatement(statement);
- }
- }
-
- public ForStatement convert(org.eclipse.wst.jsdt.internal.compiler.ast.ForStatement statement) {
- ForStatement forStatement = new ForStatement(this.ast);
- forStatement.setSourceRange(statement.sourceStart, statement.sourceEnd - statement.sourceStart + 1);
- org.eclipse.wst.jsdt.internal.compiler.ast.Statement[] initializations = statement.initializations;
- if (initializations != null) {
- // we know that we have at least one initialization
- if (initializations[0] instanceof org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration) {
- VariableDeclarationExpression variableDeclarationExpression = convertToVariableDeclarationExpression((org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration) initializations[0]);
- int initializationsLength = initializations.length;
- for (int i = 1; i < initializationsLength; i++) {
- variableDeclarationExpression.fragments().add(convertToVariableDeclarationFragment((org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration)initializations[i]));
- }
- if (initializationsLength != 1) {
- int start = variableDeclarationExpression.getStartPosition();
- int end = ((org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration) initializations[initializationsLength - 1]).declarationSourceEnd;
- variableDeclarationExpression.setSourceRange(start, end - start + 1);
- }
- forStatement.initializers().add(variableDeclarationExpression);
- } else {
- int initializationsLength = initializations.length;
- for (int i = 0; i < initializationsLength; i++) {
- Expression initializer = convertToExpression(initializations[i]);
- if (initializer != null) {
- forStatement.initializers().add(initializer);
- } else {
- forStatement.setFlags(forStatement.getFlags() | ASTNode.MALFORMED);
- }
- }
- }
- }
- if (statement.condition != null) {
- forStatement.setExpression(convert(statement.condition));
- }
- org.eclipse.wst.jsdt.internal.compiler.ast.Statement[] increments = statement.increments;
- if (increments != null) {
- int incrementsLength = increments.length;
- for (int i = 0; i < incrementsLength; i++) {
- forStatement.updaters().add(convertToExpression(increments[i]));
- }
- }
- final Statement action = convert(statement.action);
- if (action == null) return null;
- forStatement.setBody(action);
- return forStatement;
- }
-
-
- public ForInStatement convert(org.eclipse.wst.jsdt.internal.compiler.ast.ForInStatement statement) {
- ForInStatement forInStatement = new ForInStatement(this.ast);
- forInStatement.setSourceRange(statement.sourceStart, statement.sourceEnd - statement.sourceStart + 1);
-
- Statement iterationVariable = convert(statement.iterationVariable);
- forInStatement.setIterationVariable(iterationVariable);
-
- Expression collection = convert(statement.collection);
- forInStatement.setCollection(collection);
-
- final Statement action = convert(statement.action);
- if (action == null) return null;
- forInStatement.setBody(action);
- return forInStatement;
- }
- public IfStatement convert(org.eclipse.wst.jsdt.internal.compiler.ast.IfStatement statement) {
- IfStatement ifStatement = new IfStatement(this.ast);
- ifStatement.setSourceRange(statement.sourceStart, statement.sourceEnd - statement.sourceStart + 1);
- ifStatement.setExpression(convert(statement.condition));
- final Statement thenStatement = convert(statement.thenStatement);
- if (thenStatement == null) return null;
- ifStatement.setThenStatement(thenStatement);
- org.eclipse.wst.jsdt.internal.compiler.ast.Statement statement2 = statement.elseStatement;
- if (statement2 != null) {
- final Statement elseStatement = convert(statement2);
- if (elseStatement != null) {
- ifStatement.setElseStatement(elseStatement);
- }
- }
- return ifStatement;
- }
-
- public InstanceofExpression convert(org.eclipse.wst.jsdt.internal.compiler.ast.InstanceOfExpression expression) {
- InstanceofExpression instanceOfExpression = new InstanceofExpression(this.ast);
- if (this.resolveBindings) {
- recordNodes(instanceOfExpression, expression);
- }
- Expression leftExpression = convert(expression.expression);
- instanceOfExpression.setLeftOperand(leftExpression);
- final Type convertType = convertType(expression.type);
- instanceOfExpression.setRightOperand(convertType);
- int startPosition = leftExpression.getStartPosition();
- int sourceEnd = convertType.getStartPosition() + convertType.getLength() - 1;
- instanceOfExpression.setSourceRange(startPosition, sourceEnd - startPosition + 1);
- return instanceOfExpression;
- }
-
- public NumberLiteral convert(org.eclipse.wst.jsdt.internal.compiler.ast.IntLiteral expression) {
- int length = expression.sourceEnd - expression.sourceStart + 1;
- int sourceStart = expression.sourceStart;
- final NumberLiteral literal = new NumberLiteral(this.ast);
- literal.internalSetToken(new String(this.compilationUnitSource, sourceStart, length));
- if (this.resolveBindings) {
- this.recordNodes(literal, expression);
- }
- literal.setSourceRange(sourceStart, length);
- removeLeadingAndTrailingCommentsFromLiteral(literal);
- return literal;
- }
-
- public NumberLiteral convert(org.eclipse.wst.jsdt.internal.compiler.ast.IntLiteralMinValue expression) {
- int length = expression.sourceEnd - expression.sourceStart + 1;
- int sourceStart = expression.sourceStart;
- NumberLiteral literal = new NumberLiteral(this.ast);
- literal.internalSetToken(new String(this.compilationUnitSource, sourceStart, length));
- if (this.resolveBindings) {
- this.recordNodes(literal, expression);
- }
- literal.setSourceRange(sourceStart, length);
- removeLeadingAndTrailingCommentsFromLiteral(literal);
- return literal;
- }
-
- public void convert(org.eclipse.wst.jsdt.internal.compiler.ast.Javadoc javadoc, BodyDeclaration bodyDeclaration) {
- if (bodyDeclaration.getJavadoc() == null) {
- if (javadoc != null) {
- if (this.commentMapper == null || !this.commentMapper.hasSameTable(this.commentsTable)) {
- this.commentMapper = new DefaultCommentMapper(this.commentsTable);
- }
- Comment comment = this.commentMapper.getComment(javadoc.sourceStart);
- if (comment != null && comment.isDocComment() && comment.getParent() == null) {
- JSdoc docComment = (JSdoc) comment;
- if (this.resolveBindings) {
- recordNodes(docComment, javadoc);
- // resolve member and method references binding
- Iterator tags = docComment.tags().listIterator();
- while (tags.hasNext()) {
- recordNodes(javadoc, (TagElement) tags.next());
- }
- }
- bodyDeclaration.setJavadoc(docComment);
- }
- }
- }
- }
-
- public void convert(org.eclipse.wst.jsdt.internal.compiler.ast.Javadoc javadoc, VariableDeclarationStatement variable) {
- if (variable.getJavadoc() == null) {
- if (javadoc != null) {
- if (this.commentMapper == null || !this.commentMapper.hasSameTable(this.commentsTable)) {
- this.commentMapper = new DefaultCommentMapper(this.commentsTable);
- }
- Comment comment = this.commentMapper.getComment(javadoc.sourceStart);
- if (comment != null && comment.isDocComment() && comment.getParent() == null) {
- JSdoc docComment = (JSdoc) comment;
- if (this.resolveBindings) {
- recordNodes(docComment, javadoc);
- // resolve member and method references binding
- Iterator tags = docComment.tags().listIterator();
- while (tags.hasNext()) {
- recordNodes(javadoc, (TagElement) tags.next());
- }
- }
- variable.setJavadoc(docComment);
- }
- }
- }
- }
-
- public void convert(org.eclipse.wst.jsdt.internal.compiler.ast.Javadoc javadoc, PackageDeclaration packageDeclaration) {
- if (ast.apiLevel == AST.JLS3 && packageDeclaration.getJavadoc() == null) {
- if (javadoc != null) {
- if (this.commentMapper == null || !this.commentMapper.hasSameTable(this.commentsTable)) {
- this.commentMapper = new DefaultCommentMapper(this.commentsTable);
- }
- Comment comment = this.commentMapper.getComment(javadoc.sourceStart);
- if (comment != null && comment.isDocComment() && comment.getParent() == null) {
- JSdoc docComment = (JSdoc) comment;
- if (this.resolveBindings) {
- recordNodes(docComment, javadoc);
- // resolve member and method references binding
- Iterator tags = docComment.tags().listIterator();
- while (tags.hasNext()) {
- recordNodes(javadoc, (TagElement) tags.next());
- }
- }
- packageDeclaration.setJavadoc(docComment);
- }
- }
- }
- }
-
- public LabeledStatement convert(org.eclipse.wst.jsdt.internal.compiler.ast.LabeledStatement statement) {
- LabeledStatement labeledStatement = new LabeledStatement(this.ast);
- final int sourceStart = statement.sourceStart;
- labeledStatement.setSourceRange(sourceStart, statement.sourceEnd - sourceStart + 1);
- Statement body = convert(statement.statement);
- if (body == null) return null;
- labeledStatement.setBody(body);
- final SimpleName name = new SimpleName(this.ast);
- name.internalSetIdentifier(new String(statement.label));
- name.setSourceRange(sourceStart, statement.labelEnd - sourceStart + 1);
- labeledStatement.setLabel(name);
- return labeledStatement;
- }
-
- public ListExpression convert(org.eclipse.wst.jsdt.internal.compiler.ast.ListExpression expression) {
- ListExpression listExpression = new ListExpression(this.ast);
- if (this.resolveBindings) {
- recordNodes(listExpression, expression);
- }
- listExpression.setSourceRange(expression.sourceStart, expression.sourceEnd - expression.sourceStart + 1);
- org.eclipse.wst.jsdt.internal.compiler.ast.Expression[] expressions = expression.expressions;
- if (expressions != null) {
- int length = expressions.length;
- for (int i = 0; i < length; i++) {
- Expression expr = convert(expressions[i]);
- if (this.resolveBindings) {
- recordNodes(expr, expressions[i]);
- }
- listExpression.expressions().add(expr);
- }
- }
- return listExpression;
- }
-
- public Expression convert(MessageSend expression) {
- // will return a FunctionInvocation or a SuperMethodInvocation or
- Expression expr;
- int sourceStart = expression.sourceStart;
- if (expression.isSuperAccess()) {
- // returns a SuperMethodInvocation
- final SuperMethodInvocation superMethodInvocation = new SuperMethodInvocation(this.ast);
- if (this.resolveBindings) {
- recordNodes(superMethodInvocation, expression);
- }
- final SimpleName name = new SimpleName(this.ast);
- name.internalSetIdentifier(new String(expression.selector));
- int nameSourceStart = (int) (expression.nameSourcePosition >>> 32);
- int nameSourceLength = ((int) expression.nameSourcePosition) - nameSourceStart + 1;
- name.setSourceRange(nameSourceStart, nameSourceLength);
- if (this.resolveBindings) {
- recordNodes(name, expression);
- }
- superMethodInvocation.setName(name);
-
- org.eclipse.wst.jsdt.internal.compiler.ast.Expression[] arguments = expression.arguments;
- if (arguments != null) {
- int argumentsLength = arguments.length;
- for (int i = 0; i < argumentsLength; i++) {
- Expression expri = convert(arguments[i]);
- if (this.resolveBindings) {
- recordNodes(expri, arguments[i]);
- }
- superMethodInvocation.arguments().add(expri);
- }
- }
- expr = superMethodInvocation;
- } else {
- // returns a FunctionInvocation
- final FunctionInvocation methodInvocation = new FunctionInvocation(this.ast);
- if (this.resolveBindings) {
- recordNodes(methodInvocation, expression);
- }
- if (expression.selector!=null)
- {
- final SimpleName name = new SimpleName(this.ast);
- name.internalSetIdentifier(new String(expression.selector));
- int nameSourceStart = (int) (expression.nameSourcePosition >>> 32);
- int nameSourceLength = ((int) expression.nameSourcePosition) - nameSourceStart + 1;
- name.setSourceRange(nameSourceStart, nameSourceLength);
- methodInvocation.setName(name);
- if (this.resolveBindings) {
- recordNodes(name, expression);
- }
-
- }
- org.eclipse.wst.jsdt.internal.compiler.ast.Expression[] arguments = expression.arguments;
- if (arguments != null) {
- int argumentsLength = arguments.length;
- for (int i = 0; i < argumentsLength; i++) {
- Expression expri = convert(arguments[i]);
- if (this.resolveBindings) {
- recordNodes(expri, arguments[i]);
- }
- methodInvocation.arguments().add(expri);
- }
- }
- Expression qualifier = null;
- org.eclipse.wst.jsdt.internal.compiler.ast.Expression receiver = expression.receiver;
- if (receiver instanceof MessageSend) {
- if ((receiver.bits & org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.ParenthesizedMASK) != 0) {
- qualifier = convertToParenthesizedExpression(receiver);
- } else {
- qualifier = convert((MessageSend) receiver);
- }
- } else {
- qualifier = convert(receiver);
- }
- if (qualifier instanceof Name && this.resolveBindings) {
- recordNodes(qualifier, receiver);
- }
- methodInvocation.setExpression(qualifier);
- if (qualifier != null) {
- sourceStart = qualifier.getStartPosition();
- }
- expr = methodInvocation;
- }
- expr.setSourceRange(sourceStart, expression.sourceEnd - sourceStart + 1);
- removeTrailingCommentFromExpressionEndingWithAParen(expr);
- return expr;
- }
-
-
- public Name convert(org.eclipse.wst.jsdt.internal.compiler.ast.NameReference reference) {
- if (reference instanceof org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedNameReference) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedNameReference) reference);
- } else {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.SingleNameReference) reference);
- }
- }
-
- public InfixExpression convert(StringLiteralConcatenation expression) {
- expression.computeConstant();
- final InfixExpression infixExpression = new InfixExpression(this.ast);
- infixExpression.setOperator(InfixExpression.Operator.PLUS);
- org.eclipse.wst.jsdt.internal.compiler.ast.Expression[] stringLiterals = expression.literals;
- infixExpression.setLeftOperand(convert(stringLiterals[0]));
- infixExpression.setRightOperand(convert(stringLiterals[1]));
- for (int i = 2; i < expression.counter; i++) {
- infixExpression.extendedOperands().add(convert(stringLiterals[i]));
- }
- if (this.resolveBindings) {
- this.recordNodes(infixExpression, expression);
- }
- infixExpression.setSourceRange(expression.sourceStart, expression.sourceEnd - expression.sourceStart + 1);
- return infixExpression;
- }
-
-
- public NullLiteral convert(org.eclipse.wst.jsdt.internal.compiler.ast.NullLiteral expression) {
- final NullLiteral literal = new NullLiteral(this.ast);
- if (this.resolveBindings) {
- this.recordNodes(literal, expression);
- }
- literal.setSourceRange(expression.sourceStart, expression.sourceEnd - expression.sourceStart + 1);
- return literal;
- }
-
- public UndefinedLiteral convert(org.eclipse.wst.jsdt.internal.compiler.ast.UndefinedLiteral expression) {
- final UndefinedLiteral literal = new UndefinedLiteral(this.ast);
- if (this.resolveBindings) {
- this.recordNodes(literal, expression);
- }
- literal.setSourceRange(expression.sourceStart, expression.sourceEnd - expression.sourceStart + 1);
- return literal;
- }
-
- public Expression convert(org.eclipse.wst.jsdt.internal.compiler.ast.OR_OR_Expression expression) {
- InfixExpression infixExpression = new InfixExpression(this.ast);
- infixExpression.setOperator(InfixExpression.Operator.CONDITIONAL_OR);
- if (this.resolveBindings) {
- this.recordNodes(infixExpression, expression);
- }
- final int expressionOperatorID = (expression.bits & org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.OperatorMASK) >> org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.OperatorSHIFT;
- if (expression.left instanceof org.eclipse.wst.jsdt.internal.compiler.ast.BinaryExpression
- && ((expression.left.bits & org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.ParenthesizedMASK) == 0)) {
- // create an extended string literal equivalent => use the extended operands list
- infixExpression.extendedOperands().add(convert(expression.right));
- org.eclipse.wst.jsdt.internal.compiler.ast.Expression leftOperand = expression.left;
- org.eclipse.wst.jsdt.internal.compiler.ast.Expression rightOperand = null;
- do {
- rightOperand = ((org.eclipse.wst.jsdt.internal.compiler.ast.BinaryExpression) leftOperand).right;
- if ((((leftOperand.bits & org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.OperatorMASK) >> org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.OperatorSHIFT) != expressionOperatorID
- && ((leftOperand.bits & org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.ParenthesizedMASK) == 0))
- || ((rightOperand instanceof org.eclipse.wst.jsdt.internal.compiler.ast.BinaryExpression
- && ((rightOperand.bits & org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.OperatorMASK) >> org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.OperatorSHIFT) != expressionOperatorID)
- && ((rightOperand.bits & org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.ParenthesizedMASK) == 0))) {
- List extendedOperands = infixExpression.extendedOperands();
- InfixExpression temp = new InfixExpression(this.ast);
- if (this.resolveBindings) {
- this.recordNodes(temp, expression);
- }
- temp.setOperator(getOperatorFor(expressionOperatorID));
- Expression leftSide = convert(leftOperand);
- temp.setLeftOperand(leftSide);
- temp.setSourceRange(leftSide.getStartPosition(), leftSide.getLength());
- int size = extendedOperands.size();
- for (int i = 0; i < size - 1; i++) {
- Expression expr = temp;
- temp = new InfixExpression(this.ast);
-
- if (this.resolveBindings) {
- this.recordNodes(temp, expression);
- }
- temp.setLeftOperand(expr);
- temp.setOperator(getOperatorFor(expressionOperatorID));
- temp.setSourceRange(expr.getStartPosition(), expr.getLength());
- }
- infixExpression = temp;
- for (int i = 0; i < size; i++) {
- Expression extendedOperand = (Expression) extendedOperands.remove(size - 1 - i);
- temp.setRightOperand(extendedOperand);
- int startPosition = temp.getLeftOperand().getStartPosition();
- temp.setSourceRange(startPosition, extendedOperand.getStartPosition() + extendedOperand.getLength() - startPosition);
- if (temp.getLeftOperand().getNodeType() == ASTNode.INFIX_EXPRESSION) {
- temp = (InfixExpression) temp.getLeftOperand();
- }
- }
- int startPosition = infixExpression.getLeftOperand().getStartPosition();
- infixExpression.setSourceRange(startPosition, expression.sourceEnd - startPosition + 1);
- if (this.resolveBindings) {
- this.recordNodes(infixExpression, expression);
- }
- return infixExpression;
- }
- infixExpression.extendedOperands().add(0, convert(rightOperand));
- leftOperand = ((org.eclipse.wst.jsdt.internal.compiler.ast.BinaryExpression) leftOperand).left;
- } while (leftOperand instanceof org.eclipse.wst.jsdt.internal.compiler.ast.BinaryExpression && ((leftOperand.bits & org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.ParenthesizedMASK) == 0));
- Expression leftExpression = convert(leftOperand);
- infixExpression.setLeftOperand(leftExpression);
- infixExpression.setRightOperand((Expression)infixExpression.extendedOperands().remove(0));
- int startPosition = leftExpression.getStartPosition();
- infixExpression.setSourceRange(startPosition, expression.sourceEnd - startPosition + 1);
- return infixExpression;
- }
- Expression leftExpression = convert(expression.left);
- infixExpression.setLeftOperand(leftExpression);
- infixExpression.setRightOperand(convert(expression.right));
- infixExpression.setOperator(InfixExpression.Operator.CONDITIONAL_OR);
- int startPosition = leftExpression.getStartPosition();
- infixExpression.setSourceRange(startPosition, expression.sourceEnd - startPosition + 1);
- return infixExpression;
- }
-
- public PostfixExpression convert(org.eclipse.wst.jsdt.internal.compiler.ast.PostfixExpression expression) {
- final PostfixExpression postfixExpression = new PostfixExpression(this.ast);
- if (this.resolveBindings) {
- recordNodes(postfixExpression, expression);
- }
- postfixExpression.setSourceRange(expression.sourceStart, expression.sourceEnd - expression.sourceStart + 1);
- postfixExpression.setOperand(convert(expression.lhs));
- switch (expression.operator) {
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.PLUS :
- postfixExpression.setOperator(PostfixExpression.Operator.INCREMENT);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.MINUS :
- postfixExpression.setOperator(PostfixExpression.Operator.DECREMENT);
- break;
- }
- return postfixExpression;
- }
-
- public PrefixExpression convert(org.eclipse.wst.jsdt.internal.compiler.ast.PrefixExpression expression) {
- final PrefixExpression prefixExpression = new PrefixExpression(this.ast);
- if (this.resolveBindings) {
- recordNodes(prefixExpression, expression);
- }
- prefixExpression.setSourceRange(expression.sourceStart, expression.sourceEnd - expression.sourceStart + 1);
- prefixExpression.setOperand(convert(expression.lhs));
- switch (expression.operator) {
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.PLUS :
- prefixExpression.setOperator(PrefixExpression.Operator.INCREMENT);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.MINUS :
- prefixExpression.setOperator(PrefixExpression.Operator.DECREMENT);
- break;
- }
- return prefixExpression;
- }
-
- public Expression convert(org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedAllocationExpression allocation) {
- final ClassInstanceCreation classInstanceCreation = new ClassInstanceCreation(this.ast);
- if (allocation.enclosingInstance != null) {
- classInstanceCreation.setExpression(convert(allocation.enclosingInstance));
- }
- if (allocation.member != null) {
- classInstanceCreation.setMember(convert(allocation.member));
- }
- if (allocation.type!=null)
- {
- switch(this.ast.apiLevel) {
- case AST.JLS2_INTERNAL :
- classInstanceCreation.internalSetName(convert(allocation.type));
- break;
- case AST.JLS3 :
- classInstanceCreation.setType(convertType(allocation.type));
- }
- }
- org.eclipse.wst.jsdt.internal.compiler.ast.Expression[] arguments = allocation.arguments;
- if (arguments != null) {
- int length = arguments.length;
- for (int i = 0; i < length; i++) {
- Expression argument = convert(arguments[i]);
- if (this.resolveBindings) {
- recordNodes(argument, arguments[i]);
- }
- classInstanceCreation.arguments().add(argument);
- }
- }
- if (allocation.anonymousType != null) {
- int declarationSourceStart = allocation.sourceStart;
- classInstanceCreation.setSourceRange(declarationSourceStart, allocation.anonymousType.bodyEnd - declarationSourceStart + 1);
- final AnonymousClassDeclaration anonymousClassDeclaration = new AnonymousClassDeclaration(this.ast);
- int start = retrieveStartBlockPosition(allocation.anonymousType.sourceEnd, allocation.anonymousType.bodyEnd);
- anonymousClassDeclaration.setSourceRange(start, allocation.anonymousType.bodyEnd - start + 1);
- classInstanceCreation.setAnonymousClassDeclaration(anonymousClassDeclaration);
- buildBodyDeclarations(allocation.anonymousType, anonymousClassDeclaration);
- if (this.resolveBindings) {
- recordNodes(classInstanceCreation, allocation.anonymousType);
- recordNodes(anonymousClassDeclaration, allocation.anonymousType);
- anonymousClassDeclaration.resolveBinding();
- }
- return classInstanceCreation;
- } else {
- final int start = allocation.sourceStart;
- classInstanceCreation.setSourceRange(start, allocation.sourceEnd - start + 1);
- if (this.resolveBindings) {
- recordNodes(classInstanceCreation, allocation);
- }
- removeTrailingCommentFromExpressionEndingWithAParen(classInstanceCreation);
- return classInstanceCreation;
- }
- }
-
- public Name convert(org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedNameReference nameReference) {
- return setQualifiedNameNameAndSourceRanges(nameReference.tokens, nameReference.sourcePositions, nameReference);
- }
-
- public ThisExpression convert(org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedThisReference reference) {
- final ThisExpression thisExpression = new ThisExpression(this.ast);
- thisExpression.setSourceRange(reference.sourceStart, reference.sourceEnd - reference.sourceStart + 1);
- thisExpression.setQualifier(convert(reference.qualification));
- if (this.resolveBindings) {
- recordNodes(thisExpression, reference);
- recordPendingThisExpressionScopeResolution(thisExpression);
- }
- return thisExpression;
- }
-
- public Expression convert(org.eclipse.wst.jsdt.internal.compiler.ast.Reference reference) {
- if (reference instanceof org.eclipse.wst.jsdt.internal.compiler.ast.NameReference) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.NameReference) reference);
- }
- if (reference instanceof org.eclipse.wst.jsdt.internal.compiler.ast.ThisReference) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.ThisReference) reference);
- }
- if (reference instanceof org.eclipse.wst.jsdt.internal.compiler.ast.ArrayReference) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.ArrayReference) reference);
- }
- if (reference instanceof org.eclipse.wst.jsdt.internal.compiler.ast.FieldReference) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.FieldReference) reference);
- }
- return null; // cannot be reached
- }
-
- public ReturnStatement convert(org.eclipse.wst.jsdt.internal.compiler.ast.ReturnStatement statement) {
- final ReturnStatement returnStatement = new ReturnStatement(this.ast);
- returnStatement.setSourceRange(statement.sourceStart, statement.sourceEnd - statement.sourceStart + 1);
- if (statement.expression != null) {
- returnStatement.setExpression(convert(statement.expression));
- }
- return returnStatement;
- }
-
- public SimpleName convert(org.eclipse.wst.jsdt.internal.compiler.ast.SingleNameReference nameReference) {
- final SimpleName name = new SimpleName(this.ast);
- name.internalSetIdentifier(new String(nameReference.token));
- if (this.resolveBindings) {
- recordNodes(name, nameReference);
- }
- name.setSourceRange(nameReference.sourceStart, nameReference.sourceEnd - nameReference.sourceStart + 1);
- return name;
- }
-
- public Statement convert(org.eclipse.wst.jsdt.internal.compiler.ast.Statement statement) {
- if (statement instanceof ForeachStatement) {
- return convert((ForeachStatement) statement);
- }
- if (statement instanceof org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration) {
- return convertToVariableDeclarationStatement((org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration)statement);
- }
- if (statement instanceof org.eclipse.wst.jsdt.internal.compiler.ast.Block) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.Block) statement);
- }
- if (statement instanceof org.eclipse.wst.jsdt.internal.compiler.ast.BreakStatement) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.BreakStatement) statement);
- }
- if (statement instanceof org.eclipse.wst.jsdt.internal.compiler.ast.ContinueStatement) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.ContinueStatement) statement);
- }
- if (statement instanceof org.eclipse.wst.jsdt.internal.compiler.ast.CaseStatement) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.CaseStatement) statement);
- }
- if (statement instanceof org.eclipse.wst.jsdt.internal.compiler.ast.DoStatement) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.DoStatement) statement);
- }
- if (statement instanceof org.eclipse.wst.jsdt.internal.compiler.ast.EmptyStatement) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.EmptyStatement) statement);
- }
- if (statement instanceof org.eclipse.wst.jsdt.internal.compiler.ast.ExplicitConstructorCall) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.ExplicitConstructorCall) statement);
- }
- if (statement instanceof org.eclipse.wst.jsdt.internal.compiler.ast.ForStatement) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.ForStatement) statement);
- }
- if (statement instanceof org.eclipse.wst.jsdt.internal.compiler.ast.ForInStatement) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.ForInStatement) statement);
- }
- if (statement instanceof org.eclipse.wst.jsdt.internal.compiler.ast.IfStatement) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.IfStatement) statement);
- }
- if (statement instanceof org.eclipse.wst.jsdt.internal.compiler.ast.LabeledStatement) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.LabeledStatement) statement);
- }
- if (statement instanceof org.eclipse.wst.jsdt.internal.compiler.ast.ReturnStatement) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.ReturnStatement) statement);
- }
- if (statement instanceof org.eclipse.wst.jsdt.internal.compiler.ast.SwitchStatement) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.SwitchStatement) statement);
- }
- if (statement instanceof org.eclipse.wst.jsdt.internal.compiler.ast.ThrowStatement) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.ThrowStatement) statement);
- }
- if (statement instanceof org.eclipse.wst.jsdt.internal.compiler.ast.TryStatement) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.TryStatement) statement);
- }
- if (statement instanceof org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration) {
- ASTNode result = convert((org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration) statement);
- if (result == null) {
- return createFakeEmptyStatement(statement);
- }
- TypeDeclaration typeDeclaration = (TypeDeclaration) result;
- TypeDeclarationStatement typeDeclarationStatement = new TypeDeclarationStatement(this.ast);
- typeDeclarationStatement.setDeclaration(typeDeclaration);
- switch(this.ast.apiLevel) {
- case AST.JLS2_INTERNAL :
- TypeDeclaration typeDecl = typeDeclarationStatement.internalGetTypeDeclaration();
- typeDeclarationStatement.setSourceRange(typeDecl.getStartPosition(), typeDecl.getLength());
- break;
- case AST.JLS3 :
- AbstractTypeDeclaration typeDeclAST3 = typeDeclarationStatement.getDeclaration();
- typeDeclarationStatement.setSourceRange(typeDeclAST3.getStartPosition(), typeDeclAST3.getLength());
- break;
- }
- return typeDeclarationStatement;
-
- }
- if (statement instanceof org.eclipse.wst.jsdt.internal.compiler.ast.WhileStatement) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.WhileStatement) statement);
- }
- if (statement instanceof org.eclipse.wst.jsdt.internal.compiler.ast.WithStatement) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.WithStatement) statement);
- }
- if (statement instanceof org.eclipse.wst.jsdt.internal.compiler.ast.Expression) {
- org.eclipse.wst.jsdt.internal.compiler.ast.Expression statement2 = (org.eclipse.wst.jsdt.internal.compiler.ast.Expression) statement;
- final Expression expr = convert( statement2);
- final ExpressionStatement stmt = new ExpressionStatement(this.ast);
- stmt.setExpression(expr);
- int sourceStart = expr.getStartPosition();
- int sourceEnd = statement2.statementEnd;
- if (sourceEnd==-1)
- sourceEnd=statement2.sourceEnd;
- stmt.setSourceRange(sourceStart, sourceEnd - sourceStart + 1);
- return stmt;
- }
- return createFakeEmptyStatement(statement);
- }
-
- public Expression convert(org.eclipse.wst.jsdt.internal.compiler.ast.StringLiteral expression) {
- if (expression instanceof StringLiteralConcatenation) {
- return convert((StringLiteralConcatenation) expression);
- }
- int length = expression.sourceEnd - expression.sourceStart + 1;
- int sourceStart = expression.sourceStart;
- StringLiteral literal = new StringLiteral(this.ast);
- if (this.resolveBindings) {
- this.recordNodes(literal, expression);
- }
- literal.internalSetEscapedValue(new String(this.compilationUnitSource, sourceStart, length));
- literal.setSourceRange(expression.sourceStart, expression.sourceEnd - expression.sourceStart + 1);
- return literal;
- }
-
- public SwitchStatement convert(org.eclipse.wst.jsdt.internal.compiler.ast.SwitchStatement statement) {
- SwitchStatement switchStatement = new SwitchStatement(this.ast);
- switchStatement.setSourceRange(statement.sourceStart, statement.sourceEnd - statement.sourceStart + 1);
- switchStatement.setExpression(convert(statement.expression));
- org.eclipse.wst.jsdt.internal.compiler.ast.Statement[] statements = statement.statements;
- if (statements != null) {
- int statementsLength = statements.length;
- for (int i = 0; i < statementsLength; i++) {
- if (statements[i] instanceof org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration) {
- checkAndAddMultipleLocalDeclaration(statements, i, switchStatement.statements());
- } else {
- final Statement currentStatement = convert(statements[i]);
- if (currentStatement != null) {
- switchStatement.statements().add(currentStatement);
- }
- }
- }
- }
- return switchStatement;
- }
-
- public Expression convert(org.eclipse.wst.jsdt.internal.compiler.ast.ThisReference reference) {
- if (reference.isImplicitThis()) {
- // There is no source associated with an implicit this
- return null;
- } else if (reference instanceof org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedThisReference) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedThisReference) reference);
- } else {
- ThisExpression thisExpression = new ThisExpression(this.ast);
- thisExpression.setSourceRange(reference.sourceStart, reference.sourceEnd - reference.sourceStart + 1);
- if (this.resolveBindings) {
- recordNodes(thisExpression, reference);
- recordPendingThisExpressionScopeResolution(thisExpression);
- }
- return thisExpression;
- }
- }
-
- public ThrowStatement convert(org.eclipse.wst.jsdt.internal.compiler.ast.ThrowStatement statement) {
- final ThrowStatement throwStatement = new ThrowStatement(this.ast);
- throwStatement.setSourceRange(statement.sourceStart, statement.sourceEnd - statement.sourceStart + 1);
- throwStatement.setExpression(convert(statement.exception));
- return throwStatement;
- }
-
- public BooleanLiteral convert(org.eclipse.wst.jsdt.internal.compiler.ast.TrueLiteral expression) {
- final BooleanLiteral literal = new BooleanLiteral(this.ast);
- literal.setBooleanValue(true);
- if (this.resolveBindings) {
- this.recordNodes(literal, expression);
- }
- literal.setSourceRange(expression.sourceStart, expression.sourceEnd - expression.sourceStart + 1);
- return literal;
- }
-
- public TryStatement convert(org.eclipse.wst.jsdt.internal.compiler.ast.TryStatement statement) {
- final TryStatement tryStatement = new TryStatement(this.ast);
- tryStatement.setSourceRange(statement.sourceStart, statement.sourceEnd - statement.sourceStart + 1);
-
- tryStatement.setBody(convert(statement.tryBlock));
- org.eclipse.wst.jsdt.internal.compiler.ast.Argument[] catchArguments = statement.catchArguments;
- if (catchArguments != null) {
- int catchArgumentsLength = catchArguments.length;
- org.eclipse.wst.jsdt.internal.compiler.ast.Block[] catchBlocks = statement.catchBlocks;
- int start = statement.tryBlock.sourceEnd;
- for (int i = 0; i < catchArgumentsLength; i++) {
- CatchClause catchClause = new CatchClause(this.ast);
- int catchClauseSourceStart = retrieveStartingCatchPosition(start, catchArguments[i].sourceStart);
- catchClause.setSourceRange(catchClauseSourceStart, catchBlocks[i].sourceEnd - catchClauseSourceStart + 1);
- catchClause.setBody(convert(catchBlocks[i]));
- catchClause.setException(convert(catchArguments[i]));
- tryStatement.catchClauses().add(catchClause);
- start = catchBlocks[i].sourceEnd;
- }
- }
- if (statement.finallyBlock != null) {
- tryStatement.setFinally(convert(statement.finallyBlock));
- }
- return tryStatement;
- }
-
- public ASTNode convert(org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration typeDeclaration) {
- checkCanceled();
- TypeDeclaration typeDecl = new TypeDeclaration(this.ast);
- if (typeDeclaration.modifiersSourceStart != -1) {
- setModifiers(typeDecl, typeDeclaration);
- }
- final SimpleName typeName = new SimpleName(this.ast);
- typeName.internalSetIdentifier(new String(typeDeclaration.name));
- typeName.setSourceRange(typeDeclaration.sourceStart, typeDeclaration.sourceEnd - typeDeclaration.sourceStart + 1);
- typeDecl.setName(typeName);
- typeDecl.setSourceRange(typeDeclaration.declarationSourceStart, typeDeclaration.bodyEnd - typeDeclaration.declarationSourceStart + 1);
-
- // need to set the superclass and super interfaces here since we cannot distinguish them at
- // the type references level.
- if (typeDeclaration.superclass != null) {
- switch(this.ast.apiLevel) {
- case AST.JLS2_INTERNAL :
- typeDecl.internalSetSuperclass(convert(typeDeclaration.superclass));
- break;
- case AST.JLS3 :
- typeDecl.setSuperclassType(convertType(typeDeclaration.superclass));
- break;
- }
- }
-
- buildBodyDeclarations(typeDeclaration, typeDecl);
- if (this.resolveBindings) {
- recordNodes(typeDecl, typeDeclaration);
- recordNodes(typeName, typeDeclaration);
- typeDecl.resolveBinding();
- }
- return typeDecl;
- }
-
- public Name convert(org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference typeReference) {
- char[][] typeName = typeReference.getTypeName();
- int length = typeName.length;
- if (length > 1) {
- // QualifiedName
- org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedTypeReference qualifiedTypeReference = (org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedTypeReference) typeReference;
- final long[] positions = qualifiedTypeReference.sourcePositions;
- return setQualifiedNameNameAndSourceRanges(typeName, positions, typeReference);
- } else {
- final SimpleName name = new SimpleName(this.ast);
- name.internalSetIdentifier(new String(typeName[0]));
- name.setSourceRange(typeReference.sourceStart, typeReference.sourceEnd - typeReference.sourceStart + 1);
- name.index = 1;
- if (this.resolveBindings) {
- recordNodes(name, typeReference);
- }
- return name;
- }
- }
-
- public PrefixExpression convert(org.eclipse.wst.jsdt.internal.compiler.ast.UnaryExpression expression) {
- final PrefixExpression prefixExpression = new PrefixExpression(this.ast);
- if (this.resolveBindings) {
- this.recordNodes(prefixExpression, expression);
- }
- prefixExpression.setSourceRange(expression.sourceStart, expression.sourceEnd - expression.sourceStart + 1);
- prefixExpression.setOperand(convert(expression.expression));
- switch ((expression.bits & org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.OperatorMASK) >> org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.OperatorSHIFT) {
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.PLUS :
- prefixExpression.setOperator(PrefixExpression.Operator.PLUS);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.MINUS :
- prefixExpression.setOperator(PrefixExpression.Operator.MINUS);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.NOT :
- prefixExpression.setOperator(PrefixExpression.Operator.NOT);
- break;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.TWIDDLE :
- prefixExpression.setOperator(PrefixExpression.Operator.COMPLEMENT);
- }
- return prefixExpression;
- }
-
- public WhileStatement convert(org.eclipse.wst.jsdt.internal.compiler.ast.WhileStatement statement) {
- final WhileStatement whileStatement = new WhileStatement(this.ast);
- whileStatement.setSourceRange(statement.sourceStart, statement.sourceEnd - statement.sourceStart + 1);
- whileStatement.setExpression(convert(statement.condition));
- final Statement action = convert(statement.action);
- if (action == null) return null;
- whileStatement.setBody(action);
- return whileStatement;
- }
-
-
- public WithStatement convert(org.eclipse.wst.jsdt.internal.compiler.ast.WithStatement statement) {
- final WithStatement withStatement = new WithStatement(this.ast);
- withStatement.setSourceRange(statement.sourceStart, statement.sourceEnd - statement.sourceStart + 1);
- withStatement.setExpression(convert(statement.condition));
- final Statement action = convert(statement.action);
- if (action == null) return null;
- withStatement.setBody(action);
- return withStatement;
- }
-
- public ImportDeclaration convertImport(org.eclipse.wst.jsdt.internal.compiler.ast.ImportReference importReference) {
- final ImportDeclaration importDeclaration = new ImportDeclaration(this.ast);
- final boolean onDemand = (importReference.bits & org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.OnDemand) != 0;
- final char[][] tokens = importReference.tokens;
- int length = importReference.tokens.length;
- final long[] positions = importReference.sourcePositions;
- if (length > 1) {
- importDeclaration.setName(setQualifiedNameNameAndSourceRanges(tokens, positions, importReference));
- } else if(length == 1) {
- final SimpleName name = new SimpleName(this.ast);
- name.internalSetIdentifier(new String(tokens[0]));
- final int start = (int)(positions[0]>>>32);
- final int end = (int)(positions[0] & 0xFFFFFFFF);
- name.setSourceRange(start, end - start + 1);
- name.index = 1;
- importDeclaration.setName(name);
- if (this.resolveBindings) {
- recordNodes(name, importReference);
- }
- }
- boolean isFile=(importReference.bits&org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.IsFileImport)!=0;
- importDeclaration.setSourceRange(importReference.declarationSourceStart, importReference.declarationEnd - importReference.declarationSourceStart + 1);
- importDeclaration.setOnDemand(onDemand && !isFile);
- importDeclaration.setIsFileImport(isFile);
-
- if (this.resolveBindings) {
- recordNodes(importDeclaration, importReference);
- }
- return importDeclaration;
- }
-
- public PackageDeclaration convertPackage(org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration compilationUnitDeclaration) {
- org.eclipse.wst.jsdt.internal.compiler.ast.ImportReference importReference = compilationUnitDeclaration.currentPackage;
- final PackageDeclaration packageDeclaration = new PackageDeclaration(this.ast);
- final char[][] tokens = importReference.tokens;
- final int length = importReference.tokens.length;
- long[] positions = importReference.sourcePositions;
- if (length > 1) {
- packageDeclaration.setName(setQualifiedNameNameAndSourceRanges(tokens, positions, importReference));
- } else {
- final SimpleName name = new SimpleName(this.ast);
- name.internalSetIdentifier(new String(tokens[0]));
- int start = (int)(positions[0]>>>32);
- int end = (int)(positions[length - 1] & 0xFFFFFFFF);
- name.setSourceRange(start, end - start + 1);
- name.index = 1;
- packageDeclaration.setName(name);
- if (this.resolveBindings) {
- recordNodes(name, compilationUnitDeclaration);
- }
- }
- packageDeclaration.setSourceRange(importReference.declarationSourceStart, importReference.declarationEnd - importReference.declarationSourceStart + 1);
-
- if (this.resolveBindings) {
- recordNodes(packageDeclaration, importReference);
- }
- // Set javadoc
- convert(compilationUnitDeclaration.javadoc, packageDeclaration);
- return packageDeclaration;
- }
-
- public Expression convertToExpression(org.eclipse.wst.jsdt.internal.compiler.ast.Statement statement) {
- if (statement instanceof org.eclipse.wst.jsdt.internal.compiler.ast.Expression) {
- return convert((org.eclipse.wst.jsdt.internal.compiler.ast.Expression) statement);
- } else {
- return null;
- }
- }
-
- protected FieldDeclaration convertToFieldDeclaration(org.eclipse.wst.jsdt.internal.compiler.ast.AbstractVariableDeclaration fieldDecl) {
- VariableDeclarationFragment variableDeclarationFragment = convertToVariableDeclarationFragment(fieldDecl);
- final FieldDeclaration fieldDeclaration = new FieldDeclaration(this.ast);
- fieldDeclaration.fragments().add(variableDeclarationFragment);
- if (this.resolveBindings) {
- recordNodes(variableDeclarationFragment, fieldDecl);
- variableDeclarationFragment.resolveBinding();
- }
- fieldDeclaration.setSourceRange(fieldDecl.declarationSourceStart, fieldDecl.declarationEnd - fieldDecl.declarationSourceStart + 1);
- Type type = convertType(fieldDecl.type,fieldDecl.inferredType);
- setTypeForField(fieldDeclaration, type, variableDeclarationFragment.getExtraDimensions());
-// setModifiers(fieldDeclaration, fieldDecl);
- convert(fieldDecl.javadoc, fieldDeclaration);
- return fieldDeclaration;
- }
-
- public ParenthesizedExpression convertToParenthesizedExpression(org.eclipse.wst.jsdt.internal.compiler.ast.Expression expression) {
- final ParenthesizedExpression parenthesizedExpression = new ParenthesizedExpression(this.ast);
- if (this.resolveBindings) {
- recordNodes(parenthesizedExpression, expression);
- }
- parenthesizedExpression.setSourceRange(expression.sourceStart, expression.sourceEnd - expression.sourceStart + 1);
- adjustSourcePositionsForParent(expression);
- trimWhiteSpacesAndComments(expression);
- // decrement the number of parenthesis
- int numberOfParenthesis = (expression.bits & org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.ParenthesizedMASK) >> org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.ParenthesizedSHIFT;
- expression.bits &= ~org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.ParenthesizedMASK;
- expression.bits |= (numberOfParenthesis - 1) << org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.ParenthesizedSHIFT;
- parenthesizedExpression.setExpression(convert(expression));
- return parenthesizedExpression;
- }
-
- public Type convertToType(org.eclipse.wst.jsdt.internal.compiler.ast.NameReference reference) {
- Name name = convert(reference);
- final SimpleType type = new SimpleType(this.ast);
- type.setName(name);
- type.setSourceRange(name.getStartPosition(), name.getLength());
- if (this.resolveBindings) {
- this.recordNodes(type, reference);
- }
- return type;
- }
-
- protected VariableDeclarationExpression convertToVariableDeclarationExpression(org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration localDeclaration) {
- final VariableDeclarationFragment variableDeclarationFragment = convertToVariableDeclarationFragment(localDeclaration);
- final VariableDeclarationExpression variableDeclarationExpression = new VariableDeclarationExpression(this.ast);
- variableDeclarationExpression.fragments().add(variableDeclarationFragment);
- if (this.resolveBindings) {
- recordNodes(variableDeclarationFragment, localDeclaration);
- }
- variableDeclarationExpression.setSourceRange(localDeclaration.declarationSourceStart, localDeclaration.declarationSourceEnd - localDeclaration.declarationSourceStart + 1);
- Type type = convertType(localDeclaration.type,localDeclaration.inferredType);
- setTypeForVariableDeclarationExpression(variableDeclarationExpression, type, variableDeclarationFragment.getExtraDimensions());
- if (localDeclaration.modifiersSourceStart != -1) {
- setModifiers(variableDeclarationExpression, localDeclaration);
- }
- return variableDeclarationExpression;
- }
-
- protected SingleVariableDeclaration convertToSingleVariableDeclaration(LocalDeclaration localDeclaration) {
- final SingleVariableDeclaration variableDecl = new SingleVariableDeclaration(this.ast);
- setModifiers(variableDecl, localDeclaration);
- final SimpleName name = new SimpleName(this.ast);
- name.internalSetIdentifier(new String(localDeclaration.name));
- int start = localDeclaration.sourceStart;
- int nameEnd = localDeclaration.sourceEnd;
- name.setSourceRange(start, nameEnd - start + 1);
- variableDecl.setName(name);
- final int extraDimensions = retrieveExtraDimension(nameEnd + 1, localDeclaration.type.sourceEnd);
- variableDecl.setExtraDimensions(extraDimensions);
- Type type = convertType(localDeclaration.type,localDeclaration.inferredType);
- int typeEnd = type.getStartPosition() + type.getLength() - 1;
- int rightEnd = Math.max(typeEnd, localDeclaration.declarationSourceEnd);
- /*
- * There is extra work to do to set the proper type positions
- * See PR http://bugs.eclipse.org/bugs/show_bug.cgi?id=23284
- */
- setTypeForSingleVariableDeclaration(variableDecl, type, extraDimensions);
- variableDecl.setSourceRange(localDeclaration.declarationSourceStart, rightEnd - localDeclaration.declarationSourceStart + 1);
- if (this.resolveBindings) {
- recordNodes(name, localDeclaration);
- recordNodes(variableDecl, localDeclaration);
- variableDecl.resolveBinding();
- }
- return variableDecl;
- }
-
- protected VariableDeclarationFragment convertToVariableDeclarationFragment(org.eclipse.wst.jsdt.internal.compiler.ast.AbstractVariableDeclaration fieldDeclaration) {
- final VariableDeclarationFragment variableDeclarationFragment = new VariableDeclarationFragment(this.ast);
- final SimpleName name = new SimpleName(this.ast);
- name.internalSetIdentifier(new String(fieldDeclaration.name));
- name.setSourceRange(fieldDeclaration.sourceStart, fieldDeclaration.sourceEnd - fieldDeclaration.sourceStart + 1);
- variableDeclarationFragment.setName(name);
- int start = fieldDeclaration.sourceEnd;
- if (fieldDeclaration.initialization != null) {
- final Expression expression = convert(fieldDeclaration.initialization);
- variableDeclarationFragment.setInitializer(expression);
- start = expression.getStartPosition() + expression.getLength();
- }
- int end = retrievePositionBeforeNextCommaOrSemiColon(start, fieldDeclaration.declarationSourceEnd);
- if (end == -1) {
- variableDeclarationFragment.setSourceRange(fieldDeclaration.sourceStart, fieldDeclaration.declarationSourceEnd - fieldDeclaration.sourceStart + 1);
- variableDeclarationFragment.setFlags(variableDeclarationFragment.getFlags() | ASTNode.MALFORMED);
- } else {
- variableDeclarationFragment.setSourceRange(fieldDeclaration.sourceStart, end - fieldDeclaration.sourceStart + 1);
- }
- variableDeclarationFragment.setExtraDimensions(retrieveExtraDimension(fieldDeclaration.sourceEnd + 1, fieldDeclaration.declarationSourceEnd ));
- if (this.resolveBindings) {
- recordNodes(name, fieldDeclaration);
- recordNodes(variableDeclarationFragment, fieldDeclaration);
- variableDeclarationFragment.resolveBinding();
- }
- return variableDeclarationFragment;
- }
-
- protected VariableDeclarationFragment convertToVariableDeclarationFragment(org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration localDeclaration) {
- final VariableDeclarationFragment variableDeclarationFragment = new VariableDeclarationFragment(this.ast);
- final SimpleName name = new SimpleName(this.ast);
- name.internalSetIdentifier(new String(localDeclaration.name));
- name.setSourceRange(localDeclaration.sourceStart, localDeclaration.sourceEnd - localDeclaration.sourceStart + 1);
- variableDeclarationFragment.setName(name);
- int start = localDeclaration.sourceEnd;
- org.eclipse.wst.jsdt.internal.compiler.ast.Expression initialization = localDeclaration.initialization;
- boolean hasInitialization = initialization != null;
- if (hasInitialization) {
- final Expression expression = convert(initialization);
- variableDeclarationFragment.setInitializer(expression);
- start = expression.getStartPosition() + expression.getLength();
- }
- int end = retrievePositionBeforeNextCommaOrSemiColon(start, localDeclaration.declarationSourceEnd);
- if (end == -1) {
- if (hasInitialization) {
- // the initiazation sourceEnd is modified during convert(initialization)
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=128961
- end = start - 1;
- } else {
- end = localDeclaration.sourceEnd;
- }
- }
- variableDeclarationFragment.setSourceRange(localDeclaration.sourceStart, end - localDeclaration.sourceStart + 1);
- variableDeclarationFragment.setExtraDimensions(retrieveExtraDimension(localDeclaration.sourceEnd + 1, this.compilationUnitSourceLength));
- if (this.resolveBindings) {
- recordNodes(variableDeclarationFragment, localDeclaration);
- recordNodes(name, localDeclaration);
- variableDeclarationFragment.resolveBinding();
- }
- return variableDeclarationFragment;
- }
-
- protected VariableDeclarationStatement convertToVariableDeclarationStatement(org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration localDeclaration) {
- final VariableDeclarationFragment variableDeclarationFragment = convertToVariableDeclarationFragment(localDeclaration);
- final VariableDeclarationStatement variableDeclarationStatement = new VariableDeclarationStatement(this.ast);
- variableDeclarationStatement.fragments().add(variableDeclarationFragment);
- if (this.resolveBindings) {
- recordNodes(variableDeclarationFragment, localDeclaration);
- }
- variableDeclarationStatement.setSourceRange(localDeclaration.declarationSourceStart, localDeclaration.declarationSourceEnd - localDeclaration.declarationSourceStart + 1);
- if (localDeclaration.type!=null)
- {
- Type type = convertType(localDeclaration.type,localDeclaration.inferredType);
- setTypeForVariableDeclarationStatement(variableDeclarationStatement, type, variableDeclarationFragment.getExtraDimensions());
- }
- org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration local = localDeclaration;
- while (local.nextLocal!=null) {
- variableDeclarationStatement.fragments().add(convertToVariableDeclarationFragment(local.nextLocal));
- local=(org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration)local.nextLocal;
- }
-
- if (localDeclaration.modifiersSourceStart != -1) {
- setModifiers(variableDeclarationStatement, localDeclaration);
- }
- convert(localDeclaration.javadoc, variableDeclarationStatement);
- return variableDeclarationStatement;
- }
-
- public Type convertType(TypeReference typeReference) {
- return convertType(typeReference,null);
- }
- public Type convertType(TypeReference typeReference, org.eclipse.wst.jsdt.core.infer.InferredType inferredType) {
- if (typeReference==null)
- {
- InferredType newType=new InferredType(this.ast);
- newType.setSourceRange(-1,0);
- if (inferredType!=null)
- {
- newType.type=new String(inferredType.getName());
- if (this.resolveBindings)
- recordNodes(newType, inferredType);
- }
- return newType;
- }
- Type type = null;
- int sourceStart = -1;
- int length = 0;
- int dimensions = typeReference.dimensions();
- if (typeReference instanceof org.eclipse.wst.jsdt.internal.compiler.ast.SingleTypeReference) {
- // this is either an ArrayTypeReference or a SingleTypeReference
- char[] name = ((org.eclipse.wst.jsdt.internal.compiler.ast.SingleTypeReference) typeReference).getTypeName()[0];
- sourceStart = typeReference.sourceStart;
- length = typeReference.sourceEnd - typeReference.sourceStart + 1;
- // need to find out if this is an array type of primitive types or not
- if (isPrimitiveType(name)) {
- int end = retrieveEndOfElementTypeNamePosition(sourceStart, sourceStart + length);
- if (end == -1) {
- end = sourceStart + length - 1;
- }
- final PrimitiveType primitiveType = new PrimitiveType(this.ast);
- primitiveType.setPrimitiveTypeCode(getPrimitiveTypeCode(name));
- primitiveType.setSourceRange(sourceStart, end - sourceStart + 1);
- type = primitiveType;
- } else {
- final SimpleName simpleName = new SimpleName(this.ast);
- simpleName.internalSetIdentifier(new String(name));
- // we need to search for the starting position of the first brace in order to set the proper length
- // PR http://dev.eclipse.org/bugs/show_bug.cgi?id=10759
- int end = retrieveEndOfElementTypeNamePosition(sourceStart, sourceStart + length);
- if (end == -1) {
- end = sourceStart + length - 1;
- }
- simpleName.setSourceRange(sourceStart, end - sourceStart + 1);
- final SimpleType simpleType = new SimpleType(this.ast);
- simpleType.setName(simpleName);
- type = simpleType;
- type.setSourceRange(sourceStart, end - sourceStart + 1);
- type = simpleType;
- if (this.resolveBindings) {
- this.recordNodes(simpleName, typeReference);
- }
- }
- if (dimensions != 0) {
- type = this.ast.newArrayType(type, dimensions);
- type.setSourceRange(sourceStart, length);
- ArrayType subarrayType = (ArrayType) type;
- int index = dimensions - 1;
- while (index > 0) {
- subarrayType = (ArrayType) subarrayType.getComponentType();
- int end = retrieveProperRightBracketPosition(index, sourceStart);
- subarrayType.setSourceRange(sourceStart, end - sourceStart + 1);
- index--;
- }
- if (this.resolveBindings) {
- // store keys for inner types
- completeRecord((ArrayType) type, typeReference);
- }
- }
- } else {
- char[][] name = ((org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedTypeReference) typeReference).getTypeName();
- int nameLength = name.length;
- long[] positions = ((org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedTypeReference) typeReference).sourcePositions;
- sourceStart = (int)(positions[0]>>>32);
- length = (int)(positions[nameLength - 1] & 0xFFFFFFFF) - sourceStart + 1;
- final Name qualifiedName = this.setQualifiedNameNameAndSourceRanges(name, positions, typeReference);
- final SimpleType simpleType = new SimpleType(this.ast);
- simpleType.setName(qualifiedName);
- type = simpleType;
- type.setSourceRange(sourceStart, length);
-
- length = typeReference.sourceEnd - sourceStart + 1;
- if (dimensions != 0) {
- type = this.ast.newArrayType(type, dimensions);
- if (this.resolveBindings) {
- completeRecord((ArrayType) type, typeReference);
- }
- int end = retrieveEndOfDimensionsPosition(sourceStart+length, this.compilationUnitSourceLength);
- if (end != -1) {
- type.setSourceRange(sourceStart, end - sourceStart + 1);
- } else {
- type.setSourceRange(sourceStart, length);
- }
- ArrayType subarrayType = (ArrayType) type;
- int index = dimensions - 1;
- while (index > 0) {
- subarrayType = (ArrayType) subarrayType.getComponentType();
- end = retrieveProperRightBracketPosition(index, sourceStart);
- subarrayType.setSourceRange(sourceStart, end - sourceStart + 1);
- index--;
- }
- }
- }
- if (this.resolveBindings) {
- this.recordNodes(type, typeReference);
- }
- return type;
- }
-
- protected Comment createComment(int[] positions) {
- // Create comment node
- Comment comment = null;
- int start = positions[0];
- int end = positions[1];
- if (positions[1]>0) { // jsdoc comments have positive end position
- JSdoc docComment = this.docParser.parse(positions);
- if (docComment == null) return null;
- comment = docComment;
- } else {
- end = -end;
- if (positions[0] == 0) { // we cannot know without testing chars again
- if (this.docParser.scanner.source[1] == '/') {
- comment = new LineComment(this.ast);
- } else {
- comment = new BlockComment(this.ast);
- }
- }
- else if (positions[0]>0) { // Block comment have positive start position
- comment = new BlockComment(this.ast);
- } else { // Line comment have negative start and end position
- start = -start;
- comment = new LineComment(this.ast);
- }
- comment.setSourceRange(start, end - start);
- }
- return comment;
- }
-
- protected Statement createFakeEmptyStatement(org.eclipse.wst.jsdt.internal.compiler.ast.Statement statement) {
- if (statement == null) return null;
- EmptyStatement emptyStatement = new EmptyStatement(this.ast);
- emptyStatement.setFlags(emptyStatement.getFlags() | ASTNode.MALFORMED);
- int start = statement.sourceStart;
- int end = statement.sourceEnd;
- emptyStatement.setSourceRange(start, end - start + 1);
- return emptyStatement;
- }
- /**
- * @return a new modifier
- */
- private Modifier createModifier(ModifierKeyword keyword) {
- final Modifier modifier = new Modifier(this.ast);
- modifier.setKeyword(keyword);
- int start = this.scanner.getCurrentTokenStartPosition();
- int end = this.scanner.getCurrentTokenEndPosition();
- modifier.setSourceRange(start, end - start + 1);
- return modifier;
- }
-
- protected InfixExpression.Operator getOperatorFor(int operatorID) {
- switch (operatorID) {
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.EQUAL_EQUAL :
- return InfixExpression.Operator.EQUALS;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.LESS_EQUAL :
- return InfixExpression.Operator.LESS_EQUALS;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.GREATER_EQUAL :
- return InfixExpression.Operator.GREATER_EQUALS;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.NOT_EQUAL :
- return InfixExpression.Operator.NOT_EQUALS;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.LEFT_SHIFT :
- return InfixExpression.Operator.LEFT_SHIFT;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.RIGHT_SHIFT :
- return InfixExpression.Operator.RIGHT_SHIFT_SIGNED;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.UNSIGNED_RIGHT_SHIFT :
- return InfixExpression.Operator.RIGHT_SHIFT_UNSIGNED;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.OR_OR :
- return InfixExpression.Operator.CONDITIONAL_OR;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.AND_AND :
- return InfixExpression.Operator.CONDITIONAL_AND;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.PLUS :
- return InfixExpression.Operator.PLUS;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.MINUS :
- return InfixExpression.Operator.MINUS;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.REMAINDER :
- return InfixExpression.Operator.REMAINDER;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.XOR :
- return InfixExpression.Operator.XOR;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.AND :
- return InfixExpression.Operator.AND;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.MULTIPLY :
- return InfixExpression.Operator.TIMES;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.OR :
- return InfixExpression.Operator.OR;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.DIVIDE :
- return InfixExpression.Operator.DIVIDE;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.GREATER :
- return InfixExpression.Operator.GREATER;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.LESS :
- return InfixExpression.Operator.LESS;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.INSTANCEOF :
- return InfixExpression.Operator.INSTANCEOF;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.IN :
- return InfixExpression.Operator.IN;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.EQUAL_EQUAL_EQUAL :
- return InfixExpression.Operator.EQUAL_EQUAL_EQUAL;
- case org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds.NOT_EQUAL_EQUAL :
- return InfixExpression.Operator.NOT_EQUAL_EQUAL;
- }
- return null;
- }
-
- protected PrimitiveType.Code getPrimitiveTypeCode(char[] name) {
- switch(name[0]) {
- case 'i' :
- if (name.length == 3 && name[1] == 'n' && name[2] == 't') {
- return PrimitiveType.INT;
- }
- break;
- case 'l' :
- if (name.length == 4 && name[1] == 'o' && name[2] == 'n' && name[3] == 'g') {
- return PrimitiveType.LONG;
- }
- break;
- case 'd' :
- if (name.length == 6
- && name[1] == 'o'
- && name[2] == 'u'
- && name[3] == 'b'
- && name[4] == 'l'
- && name[5] == 'e') {
- return PrimitiveType.DOUBLE;
- }
- break;
- case 'f' :
- if (name.length == 5
- && name[1] == 'l'
- && name[2] == 'o'
- && name[3] == 'a'
- && name[4] == 't') {
- return PrimitiveType.FLOAT;
- }
- break;
- case 'b' :
- if (name.length == 4
- && name[1] == 'y'
- && name[2] == 't'
- && name[3] == 'e') {
- return PrimitiveType.BYTE;
- } else
- if (name.length == 7
- && name[1] == 'o'
- && name[2] == 'o'
- && name[3] == 'l'
- && name[4] == 'e'
- && name[5] == 'a'
- && name[6] == 'n') {
- return PrimitiveType.BOOLEAN;
- }
- break;
- case 'c' :
- if (name.length == 4
- && name[1] == 'h'
- && name[2] == 'a'
- && name[3] == 'r') {
- return PrimitiveType.CHAR;
- }
- break;
- case 's' :
- if (name.length == 5
- && name[1] == 'h'
- && name[2] == 'o'
- && name[3] == 'r'
- && name[4] == 't') {
- return PrimitiveType.SHORT;
- }
- break;
- case 'v' :
- if (name.length == 4
- && name[1] == 'o'
- && name[2] == 'i'
- && name[3] == 'd') {
- return PrimitiveType.VOID;
- }
- }
- return null; // cannot be reached
- }
-
- protected boolean isPrimitiveType(char[] name) {
- switch(name[0]) {
- case 'i' :
- if (name.length == 3 && name[1] == 'n' && name[2] == 't') {
- return true;
- }
- return false;
- case 'l' :
- if (name.length == 4 && name[1] == 'o' && name[2] == 'n' && name[3] == 'g') {
- return true;
- }
- return false;
- case 'd' :
- if (name.length == 6
- && name[1] == 'o'
- && name[2] == 'u'
- && name[3] == 'b'
- && name[4] == 'l'
- && name[5] == 'e') {
- return true;
- }
- return false;
- case 'f' :
- if (name.length == 5
- && name[1] == 'l'
- && name[2] == 'o'
- && name[3] == 'a'
- && name[4] == 't') {
- return true;
- }
- return false;
- case 'b' :
- if (name.length == 4
- && name[1] == 'y'
- && name[2] == 't'
- && name[3] == 'e') {
- return true;
- } else
- if (name.length == 7
- && name[1] == 'o'
- && name[2] == 'o'
- && name[3] == 'l'
- && name[4] == 'e'
- && name[5] == 'a'
- && name[6] == 'n') {
- return true;
- }
- return false;
- case 'c' :
- if (name.length == 4
- && name[1] == 'h'
- && name[2] == 'a'
- && name[3] == 'r') {
- return true;
- }
- return false;
- case 's' :
- if (name.length == 5
- && name[1] == 'h'
- && name[2] == 'o'
- && name[3] == 'r'
- && name[4] == 't') {
- return true;
- }
- return false;
- case 'v' :
- if (name.length == 4
- && name[1] == 'o'
- && name[2] == 'i'
- && name[3] == 'd') {
- return true;
- }
- return false;
- }
- return false;
- }
-
- private void lookupForScopes() {
- if (this.pendingNameScopeResolution != null) {
- for (Iterator iterator = this.pendingNameScopeResolution.iterator(); iterator.hasNext(); ) {
- Name name = (Name) iterator.next();
- this.ast.getBindingResolver().recordScope(name, lookupScope(name));
- }
- }
- if (this.pendingThisExpressionScopeResolution != null) {
- for (Iterator iterator = this.pendingThisExpressionScopeResolution.iterator(); iterator.hasNext(); ) {
- ThisExpression thisExpression = (ThisExpression) iterator.next();
- this.ast.getBindingResolver().recordScope(thisExpression, lookupScope(thisExpression));
- }
- }
-
- }
-
- private BlockScope lookupScope(ASTNode node) {
- ASTNode currentNode = node;
- while(currentNode != null
- &&!(currentNode instanceof FunctionDeclaration)
- && !(currentNode instanceof Initializer)
- && !(currentNode instanceof FieldDeclaration)) {
- currentNode = currentNode.getParent();
- }
- if (currentNode == null) {
- return null;
- }
- if (currentNode instanceof Initializer) {
- Initializer initializer = (Initializer) currentNode;
- while(!(currentNode instanceof AbstractTypeDeclaration)) {
- currentNode = currentNode.getParent();
- }
- if (currentNode instanceof TypeDeclaration) {
- org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration typeDecl = (org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration) this.ast.getBindingResolver().getCorrespondingNode(currentNode);
- if ((initializer.getModifiers() & Modifier.STATIC) != 0) {
- return typeDecl.staticInitializerScope;
- } else {
- return typeDecl.initializerScope;
- }
- }
- } else if (currentNode instanceof FieldDeclaration) {
- FieldDeclaration fieldDeclaration = (FieldDeclaration) currentNode;
- while(!(currentNode instanceof AbstractTypeDeclaration)) {
- currentNode = currentNode.getParent();
- }
- if (currentNode instanceof TypeDeclaration) {
- org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration typeDecl = (org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration) this.ast.getBindingResolver().getCorrespondingNode(currentNode);
- if ((fieldDeclaration.getModifiers() & Modifier.STATIC) != 0) {
- return typeDecl.staticInitializerScope;
- } else {
- return typeDecl.initializerScope;
- }
- }
- }
- AbstractMethodDeclaration abstractMethodDeclaration = (AbstractMethodDeclaration) this.ast.getBindingResolver().getCorrespondingNode(currentNode);
- return abstractMethodDeclaration.scope;
- }
-
- protected void recordName(Name name, org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode compilerNode) {
- if (compilerNode != null) {
- recordNodes(name, compilerNode);
- if (compilerNode instanceof org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference) {
- org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference typeRef = (org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference) compilerNode;
- if (name.isQualifiedName()) {
- SimpleName simpleName = null;
- while (name.isQualifiedName()) {
- simpleName = ((QualifiedName) name).getName();
- recordNodes(simpleName, typeRef);
- name = ((QualifiedName) name).getQualifier();
- recordNodes(name, typeRef);
- }
- }
- }
- }
- }
-
- protected void recordNodes(ASTNode node, org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode oldASTNode) {
- this.ast.getBindingResolver().store(node, oldASTNode);
- }
-
- protected void recordNodes(org.eclipse.wst.jsdt.internal.compiler.ast.Javadoc javadoc, TagElement tagElement) {
- Iterator fragments = tagElement.fragments().listIterator();
- while (fragments.hasNext()) {
- ASTNode node = (ASTNode) fragments.next();
- if (node.getNodeType() == ASTNode.MEMBER_REF) {
- MemberRef memberRef = (MemberRef) node;
- Name name = memberRef.getName();
- // get compiler node and record nodes
- int start = name.getStartPosition();
- org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode compilerNode = javadoc.getNodeStartingAt(start);
- if (compilerNode!= null) {
- recordNodes(name, compilerNode);
- recordNodes(node, compilerNode);
- }
- // Replace qualifier to have all nodes recorded
- if (memberRef.getQualifier() != null) {
- org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference typeRef = null;
- if (compilerNode instanceof JavadocFieldReference) {
- org.eclipse.wst.jsdt.internal.compiler.ast.Expression expression = ((JavadocFieldReference)compilerNode).receiver;
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference) {
- typeRef = (org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference) expression;
- }
- }
- else if (compilerNode instanceof JavadocMessageSend) {
- org.eclipse.wst.jsdt.internal.compiler.ast.Expression expression = ((JavadocMessageSend)compilerNode).receiver;
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference) {
- typeRef = (org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference) expression;
- }
- }
- if (typeRef != null) {
- recordName(memberRef.getQualifier(), typeRef);
- }
- }
- } else if (node.getNodeType() == ASTNode.FUNCTION_REF) {
- FunctionRef methodRef = (FunctionRef) node;
- Name name = methodRef.getName();
- // get method name start position
- int start = methodRef.getStartPosition();
- this.scanner.resetTo(start, start + name.getStartPosition()+name.getLength());
- int token;
- try {
- nextToken: while((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF && token != TerminalTokens.TokenNameLPAREN) {
- if (token == TerminalTokens.TokenNameERROR && this.scanner.currentCharacter == '#') {
- start = this.scanner.getCurrentTokenEndPosition()+1;
- break nextToken;
- }
- }
- }
- catch(InvalidInputException e) {
- // ignore
- }
- // get compiler node and record nodes
- org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode compilerNode = javadoc.getNodeStartingAt(start);
- // record nodes
- if (compilerNode != null) {
- recordNodes(methodRef, compilerNode);
- // get type ref
- org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference typeRef = null;
- if (compilerNode instanceof org.eclipse.wst.jsdt.internal.compiler.ast.JavadocAllocationExpression) {
- typeRef = ((org.eclipse.wst.jsdt.internal.compiler.ast.JavadocAllocationExpression)compilerNode).type;
- if (typeRef != null) recordNodes(name, compilerNode);
- }
- else if (compilerNode instanceof org.eclipse.wst.jsdt.internal.compiler.ast.JavadocMessageSend) {
- org.eclipse.wst.jsdt.internal.compiler.ast.Expression expression = ((org.eclipse.wst.jsdt.internal.compiler.ast.JavadocMessageSend)compilerNode).receiver;
- if (expression instanceof org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference) {
- typeRef = (org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference) expression;
- }
- recordNodes(name, compilerNode);
- }
- // record name and qualifier
- if (typeRef != null && methodRef.getQualifier() != null) {
- recordName(methodRef.getQualifier(), typeRef);
- }
- }
- // Resolve parameters
- Iterator parameters = methodRef.parameters().listIterator();
- while (parameters.hasNext()) {
- FunctionRefParameter param = (FunctionRefParameter) parameters.next();
- org.eclipse.wst.jsdt.internal.compiler.ast.Expression expression = (org.eclipse.wst.jsdt.internal.compiler.ast.Expression) javadoc.getNodeStartingAt(param.getStartPosition());
- if (expression != null) {
- recordNodes(param, expression);
- if (expression instanceof JavadocArgumentExpression) {
- JavadocArgumentExpression argExpr = (JavadocArgumentExpression) expression;
- org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference typeRef = argExpr.argument.type;
- if (this.ast.apiLevel >= AST.JLS3) param.setVarargs(argExpr.argument.isVarArgs());
- recordNodes(param.getType(), typeRef);
- if (param.getType().isSimpleType()) {
- recordName(((SimpleType)param.getType()).getName(), typeRef);
- } else if (param.getType().isArrayType()) {
- Type type = ((ArrayType) param.getType()).getElementType();
- recordNodes(type, typeRef);
- if (type.isSimpleType()) {
- recordName(((SimpleType)type).getName(), typeRef);
- }
- }
- }
- }
- }
- } else if (node.getNodeType() == ASTNode.SIMPLE_NAME ||
- node.getNodeType() == ASTNode.QUALIFIED_NAME) {
- org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode compilerNode = javadoc.getNodeStartingAt(node.getStartPosition());
- recordName((Name) node, compilerNode);
- } else if (node.getNodeType() == ASTNode.TAG_ELEMENT) {
- // resolve member and method references binding
- recordNodes(javadoc, (TagElement) node);
- }
- }
- }
- protected void recordPendingNameScopeResolution(Name name) {
- if (this.pendingNameScopeResolution == null) {
- this.pendingNameScopeResolution = new HashSet();
- }
- this.pendingNameScopeResolution.add(name);
- }
-
- protected void recordPendingThisExpressionScopeResolution(ThisExpression thisExpression) {
- if (this.pendingThisExpressionScopeResolution == null) {
- this.pendingThisExpressionScopeResolution = new HashSet();
- }
- this.pendingThisExpressionScopeResolution.add(thisExpression);
- }
-
- /**
- * Remove whitespaces and comments before and after the expression.
- */
- private void trimWhiteSpacesAndComments(org.eclipse.wst.jsdt.internal.compiler.ast.Expression expression) {
- int start = expression.sourceStart;
- int end = expression.sourceEnd;
- int token;
- int trimLeftPosition = expression.sourceStart;
- int trimRightPosition = expression.sourceEnd;
- boolean first = true;
- Scanner removeBlankScanner = this.ast.scanner;
- try {
- removeBlankScanner.setSource(this.compilationUnitSource);
- removeBlankScanner.resetTo(start, end);
- while (true) {
- token = removeBlankScanner.getNextToken();
- switch (token) {
- case TerminalTokens.TokenNameCOMMENT_JAVADOC :
- case TerminalTokens.TokenNameCOMMENT_LINE :
- case TerminalTokens.TokenNameCOMMENT_BLOCK :
- if (first) {
- trimLeftPosition = removeBlankScanner.currentPosition;
- }
- break;
- case TerminalTokens.TokenNameWHITESPACE :
- if (first) {
- trimLeftPosition = removeBlankScanner.currentPosition;
- }
- break;
- case TerminalTokens.TokenNameEOF :
- expression.sourceStart = trimLeftPosition;
- expression.sourceEnd = trimRightPosition;
- return;
- default :
- /*
- * if we find something else than a whitespace or a comment,
- * then we reset the trimRigthPosition to the expression
- * source end.
- */
- trimRightPosition = removeBlankScanner.currentPosition - 1;
- first = false;
- }
- }
- } catch (InvalidInputException e){
- // ignore
- }
- }
-
- /**
- * Remove potential trailing comment by settings the source end on the closing parenthesis
- */
- protected void removeLeadingAndTrailingCommentsFromLiteral(ASTNode node) {
- int start = node.getStartPosition();
- this.scanner.resetTo(start, start + node.getLength());
- int token;
- int startPosition = -1;
- try {
- while((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
- switch(token) {
- case TerminalTokens.TokenNameIntegerLiteral :
- case TerminalTokens.TokenNameFloatingPointLiteral :
- case TerminalTokens.TokenNameLongLiteral :
- case TerminalTokens.TokenNameDoubleLiteral :
- case TerminalTokens.TokenNameCharacterLiteral :
- case TerminalTokens.TokenNameRegExLiteral :
- if (startPosition == -1) {
- startPosition = this.scanner.startPosition;
- }
- int end = this.scanner.currentPosition;
- node.setSourceRange(startPosition, end - startPosition);
- return;
- case TerminalTokens.TokenNameMINUS :
- startPosition = this.scanner.startPosition;
- break;
- }
- }
- } catch(InvalidInputException e) {
- // ignore
- }
- }
-
- /**
- * Remove potential trailing comment by settings the source end on the closing parenthesis
- */
- protected void removeTrailingCommentFromExpressionEndingWithAParen(ASTNode node) {
- int start = node.getStartPosition();
- this.scanner.resetTo(start, start + node.getLength());
- int token;
- int parenCounter = 0;
- try {
- while((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
- switch(token) {
- case TerminalTokens.TokenNameLPAREN :
- parenCounter++;
- break;
- case TerminalTokens.TokenNameRPAREN :
- parenCounter--;
- if (parenCounter == 0) {
- int end = this.scanner.currentPosition - 1;
- node.setSourceRange(start, end - start + 1);
- }
- }
- }
- } catch(InvalidInputException e) {
- // ignore
- }
- }
-
- /**
- * This method is used to retrieve the end position of the block.
- * @return int the dimension found, -1 if none
- */
- protected int retrieveClosingAngleBracketPosition(int start) {
- this.scanner.resetTo(start, this.compilationUnitSourceLength);
- this.scanner.returnOnlyGreater = true;
- try {
- int token;
- while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
- switch(token) {
- case TerminalTokens.TokenNameGREATER:
- return this.scanner.currentPosition - 1;
- default:
- return start;
- }
- }
- } catch(InvalidInputException e) {
- // ignore
- }
- this.scanner.returnOnlyGreater = false;
- return start;
- }
-
- /**
- * This method is used to set the right end position for expression
- * statement. The actual AST nodes don't include the trailing semicolon.
- * This method fixes the length of the corresponding node.
- */
- protected void retrieveColonPosition(ASTNode node) {
- int start = node.getStartPosition();
- int length = node.getLength();
- int end = start + length;
- this.scanner.resetTo(end, this.compilationUnitSourceLength);
- try {
- int token;
- while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
- switch(token) {
- case TerminalTokens.TokenNameCOLON:
- node.setSourceRange(start, this.scanner.currentPosition - start);
- return;
- }
- }
- } catch(InvalidInputException e) {
- // ignore
- }
- }
-// /**
-// * This method is used to retrieve the start position of the Ellipsis
-// */
-// protected int retrieveEllipsisStartPosition(int start, int end) {
-// this.scanner.resetTo(start, end);
-// try {
-// int token;
-// while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
-// switch(token) {
-// case TerminalTokens.TokenNameELLIPSIS:
-// return this.scanner.startPosition - 1;
-// }
-// }
-// } catch(InvalidInputException e) {
-// // ignore
-// }
-// return -1;
-//
-// }
- /**
- * This method is used to retrieve the end position of the block.
- * @return int the dimension found, -1 if none
- */
- protected int retrieveEndBlockPosition(int start, int end) {
- this.scanner.resetTo(start, end);
- int count = 0;
- try {
- int token;
- while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
- switch(token) {
- case TerminalTokens.TokenNameLBRACE://110
- count++;
- break;
- case TerminalTokens.TokenNameRBRACE://95
- count--;
- if (count == 0) {
- return this.scanner.currentPosition - 1;
- }
- }
- }
- } catch(InvalidInputException e) {
- // ignore
- }
- return -1;
- }
-
- protected int retrieveSemiColonPosition(Expression node) {
- int start = node.getStartPosition();
- int length = node.getLength();
- int end = start + length;
- this.scanner.resetTo(end, this.compilationUnitSourceLength);
- try {
- int token;
- while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
- switch(token) {
- case TerminalTokens.TokenNameSEMICOLON:
- return this.scanner.currentPosition - 1;
- }
- }
- } catch(InvalidInputException e) {
- // ignore
- }
- return -1;
- }
-
- /**
- * This method is used to retrieve the ending position for a type declaration when the dimension is right after the type
- * name.
- * For example:
- * int[] i; => return 5, but int i[] => return -1;
- * @return int the dimension found
- */
- protected int retrieveEndOfDimensionsPosition(int start, int end) {
- this.scanner.resetTo(start, end);
- int foundPosition = -1;
- try {
- int token;
- while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
- switch(token) {
- case TerminalTokens.TokenNameLBRACKET:
- case TerminalTokens.TokenNameCOMMENT_BLOCK:
- case TerminalTokens.TokenNameCOMMENT_JAVADOC:
- case TerminalTokens.TokenNameCOMMENT_LINE:
- break;
- case TerminalTokens.TokenNameRBRACKET://166
- foundPosition = this.scanner.currentPosition - 1;
- break;
- default:
- return foundPosition;
- }
- }
- } catch(InvalidInputException e) {
- // ignore
- }
- return foundPosition;
- }
-
- /**
- * This method is used to retrieve the position just before the left bracket.
- * @return int the dimension found, -1 if none
- */
- protected int retrieveEndOfElementTypeNamePosition(int start, int end) {
- this.scanner.resetTo(start, end);
- try {
- int token;
- while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
- switch(token) {
- case TerminalTokens.TokenNameIdentifier:
- case TerminalTokens.TokenNamebyte:
- case TerminalTokens.TokenNamechar:
- case TerminalTokens.TokenNamedouble:
- case TerminalTokens.TokenNamefloat:
- case TerminalTokens.TokenNameint:
- case TerminalTokens.TokenNamelong:
- case TerminalTokens.TokenNameshort:
- case TerminalTokens.TokenNameboolean:
- return this.scanner.currentPosition - 1;
- }
- }
- } catch(InvalidInputException e) {
- // ignore
- }
- return -1;
- }
-
- /**
- * This method is used to retrieve the position after the right parenthesis.
- * @return int the position found
- */
- protected int retrieveEndOfRightParenthesisPosition(int start, int end) {
- this.scanner.resetTo(start, end);
- try {
- int token;
- while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
- switch(token) {
- case TerminalTokens.TokenNameRPAREN:
- return this.scanner.currentPosition;
- }
- }
- } catch(InvalidInputException e) {
- // ignore
- }
- return -1;
- }
-
- /**
- * This method is used to retrieve the array dimension declared after the
- * name of a local or a field declaration.
- * For example:
- * int i, j[] = null, k[][] = {{}};
- * It should return 0 for i, 1 for j and 2 for k.
- * @return int the dimension found
- */
- protected int retrieveExtraDimension(int start, int end) {
- this.scanner.resetTo(start, end);
- int dimensions = 0;
- try {
- int token;
- while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
- switch(token) {
- case TerminalTokens.TokenNameLBRACKET:
- case TerminalTokens.TokenNameCOMMENT_BLOCK:
- case TerminalTokens.TokenNameCOMMENT_JAVADOC:
- case TerminalTokens.TokenNameCOMMENT_LINE:
- break;
- case TerminalTokens.TokenNameRBRACKET://166
- dimensions++;
- break;
- default:
- return dimensions;
- }
- }
- } catch(InvalidInputException e) {
- // ignore
- }
- return dimensions;
- }
-
- protected void retrieveIdentifierAndSetPositions(int start, int end, Name name) {
- this.scanner.resetTo(start, end);
- int token;
- try {
- while((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
- if (token == TerminalTokens.TokenNameIdentifier) {
- int startName = this.scanner.startPosition;
- int endName = this.scanner.currentPosition - 1;
- name.setSourceRange(startName, endName - startName + 1);
- return;
- }
- }
- } catch(InvalidInputException e) {
- // ignore
- }
- }
-
- /**
- * This method is used to retrieve the start position of the block.
- * @return int the dimension found, -1 if none
- */
- protected int retrieveIdentifierEndPosition(int start, int end) {
- this.scanner.resetTo(start, end);
- try {
- int token;
- while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
- switch(token) {
- case TerminalTokens.TokenNameIdentifier://110
- return this.scanner.getCurrentTokenEndPosition();
- }
- }
- } catch(InvalidInputException e) {
- // ignore
- }
- return -1;
- }
-
- /**
- * This method is used to retrieve position before the next comma or semi-colon.
- * @return int the position found.
- */
- protected int retrievePositionBeforeNextCommaOrSemiColon(int start, int end) {
- this.scanner.resetTo(start, end);
- try {
- int token;
- int balance = 0;
- while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
- switch(token) {
- case TerminalTokens.TokenNameLBRACE :
- balance++;
- break;
- case TerminalTokens.TokenNameRBRACE :
- balance --;
- break;
- case TerminalTokens.TokenNameCOMMA :
- if (balance == 0) return this.scanner.startPosition - 1;
- break;
- case TerminalTokens.TokenNameSEMICOLON :
- return this.scanner.startPosition - 1;
- }
- }
- } catch(InvalidInputException e) {
- // ignore
- }
- return -1;
- }
-
- protected int retrieveProperRightBracketPosition(int bracketNumber, int start) {
- this.scanner.resetTo(start, this.compilationUnitSourceLength);
- try {
- int token, count = 0;
- while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
- switch(token) {
- case TerminalTokens.TokenNameRBRACKET:
- count++;
- if (count == bracketNumber) {
- return this.scanner.currentPosition - 1;
- }
- }
- }
- } catch(InvalidInputException e) {
- // ignore
- }
- return -1;
- }
-
- /**
- * This method is used to retrieve position before the next right brace or semi-colon.
- * @return int the position found.
- */
- protected int retrieveRightBraceOrSemiColonPosition(int start, int end) {
- this.scanner.resetTo(start, end);
- try {
- int token;
- while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
- switch(token) {
- case TerminalTokens.TokenNameRBRACE :
- return this.scanner.currentPosition - 1;
- case TerminalTokens.TokenNameSEMICOLON :
- return this.scanner.currentPosition - 1;
- }
- }
- } catch(InvalidInputException e) {
- // ignore
- }
- return -1;
- }
-
- /**
- * This method is used to retrieve position before the next right brace or semi-colon.
- * @return int the position found.
- */
- protected int retrieveRightBrace(int start, int end) {
- this.scanner.resetTo(start, end);
- try {
- int token;
- while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
- switch(token) {
- case TerminalTokens.TokenNameRBRACE :
- return this.scanner.currentPosition - 1;
- }
- }
- } catch(InvalidInputException e) {
- // ignore
- }
- return -1;
- }
-
- /**
- * This method is used to retrieve the position of the right bracket.
- * @return int the dimension found, -1 if none
- */
- protected int retrieveRightBracketPosition(int start, int end) {
- this.scanner.resetTo(start, end);
- try {
- int token;
- while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
- switch(token) {
- case TerminalTokens.TokenNameRBRACKET:
- return this.scanner.currentPosition - 1;
- }
- }
- } catch(InvalidInputException e) {
- // ignore
- }
- return -1;
- }
-
-
-
- /**
- * This method is used to retrieve the start position of the block.
- * @return int the dimension found, -1 if none
- */
- protected int retrieveStartBlockPosition(int start, int end) {
- this.scanner.resetTo(start, end);
- try {
- int token;
- while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
- switch(token) {
- case TerminalTokens.TokenNameLBRACE://110
- return this.scanner.startPosition;
- }
- }
- } catch(InvalidInputException e) {
- // ignore
- }
- return -1;
- }
-
- /**
- * This method is used to retrieve the starting position of the catch keyword.
- * @return int the dimension found, -1 if none
- */
- protected int retrieveStartingCatchPosition(int start, int end) {
- this.scanner.resetTo(start, end);
- try {
- int token;
- while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
- switch(token) {
- case TerminalTokens.TokenNamecatch://225
- return this.scanner.startPosition;
- }
- }
- } catch(InvalidInputException e) {
- // ignore
- }
- return -1;
- }
-
- public void setAST(AST ast) {
- this.ast = ast;
- this.docParser = new DocCommentParser(this.ast, this.scanner, this.insideComments);
- }
-
- /**
- * @param bodyDeclaration
- */
- protected void setModifiers(BodyDeclaration bodyDeclaration) {
- try {
- int token;
- while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
- IExtendedModifier modifier = null;
- switch(token) {
- case TerminalTokens.TokenNameabstract:
- modifier = createModifier(Modifier.ModifierKeyword.ABSTRACT_KEYWORD);
- break;
- case TerminalTokens.TokenNamepublic:
- modifier = createModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD);
- break;
- case TerminalTokens.TokenNamestatic:
- modifier = createModifier(Modifier.ModifierKeyword.STATIC_KEYWORD);
- break;
- case TerminalTokens.TokenNameprotected:
- modifier = createModifier(Modifier.ModifierKeyword.PROTECTED_KEYWORD);
- break;
- case TerminalTokens.TokenNameprivate:
- modifier = createModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD);
- break;
- case TerminalTokens.TokenNamefinal:
- modifier = createModifier(Modifier.ModifierKeyword.FINAL_KEYWORD);
- break;
- case TerminalTokens.TokenNamenative:
- modifier = createModifier(Modifier.ModifierKeyword.NATIVE_KEYWORD);
- break;
- case TerminalTokens.TokenNamesynchronized:
- modifier = createModifier(Modifier.ModifierKeyword.SYNCHRONIZED_KEYWORD);
- break;
- case TerminalTokens.TokenNametransient:
- modifier = createModifier(Modifier.ModifierKeyword.TRANSIENT_KEYWORD);
- break;
- case TerminalTokens.TokenNamevolatile:
- modifier = createModifier(Modifier.ModifierKeyword.VOLATILE_KEYWORD);
- break;
- case TerminalTokens.TokenNameCOMMENT_BLOCK :
- case TerminalTokens.TokenNameCOMMENT_LINE :
- case TerminalTokens.TokenNameCOMMENT_JAVADOC :
- break;
- default :
- return;
- }
- if (modifier != null) {
- bodyDeclaration.modifiers().add(modifier);
- }
- }
- } catch(InvalidInputException e) {
- // ignore
- }
- }
-
-
- /**
- * @param fieldDeclaration
- * @param fieldDecl
- */
- protected void setModifiers(FieldDeclaration fieldDeclaration, org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration fieldDecl) {
- switch(this.ast.apiLevel) {
- case AST.JLS2_INTERNAL :
- fieldDeclaration.internalSetModifiers(fieldDecl.modifiers & ExtraCompilerModifiers.AccJustFlag);
- break;
- case AST.JLS3 :
- this.scanner.resetTo(fieldDecl.declarationSourceStart, fieldDecl.sourceStart);
- this.setModifiers(fieldDeclaration);
- }
- }
-
- /**
- * @param initializer
- * @param oldInitializer
- */
- protected void setModifiers(Initializer initializer, org.eclipse.wst.jsdt.internal.compiler.ast.Initializer oldInitializer) {
- switch(this.ast.apiLevel) {
- case AST.JLS2_INTERNAL:
- initializer.internalSetModifiers(oldInitializer.modifiers & ExtraCompilerModifiers.AccJustFlag);
- break;
- case AST.JLS3 :
- this.scanner.resetTo(oldInitializer.declarationSourceStart, oldInitializer.bodyStart);
- this.setModifiers(initializer);
- }
- }
- /**
- * @param methodDecl
- * @param methodDeclaration
- */
- protected void setModifiers(FunctionDeclaration methodDecl, AbstractMethodDeclaration methodDeclaration) {
- switch(this.ast.apiLevel) {
- case AST.JLS2_INTERNAL :
- methodDecl.internalSetModifiers(methodDeclaration.modifiers & ExtraCompilerModifiers.AccJustFlag);
- break;
- case AST.JLS3 :
- if (methodDeclaration.sourceStart>methodDeclaration.declarationSourceStart)
- {
- this.scanner.resetTo(methodDeclaration.declarationSourceStart, methodDeclaration.sourceStart);
- this.setModifiers(methodDecl);
- }
- }
- }
-
- /**
- * @param variableDecl
- * @param argument
- */
- protected void setModifiers(SingleVariableDeclaration variableDecl, Argument argument) {
- switch(this.ast.apiLevel) {
- case AST.JLS2_INTERNAL :
- variableDecl.internalSetModifiers(argument.modifiers & ExtraCompilerModifiers.AccJustFlag);
- break;
- case AST.JLS3 :
- this.scanner.resetTo(argument.declarationSourceStart, argument.sourceStart);
- try {
- int token;
- while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
- IExtendedModifier modifier = null;
- switch(token) {
- case TerminalTokens.TokenNameabstract:
- modifier = createModifier(Modifier.ModifierKeyword.ABSTRACT_KEYWORD);
- break;
- case TerminalTokens.TokenNamepublic:
- modifier = createModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD);
- break;
- case TerminalTokens.TokenNamestatic:
- modifier = createModifier(Modifier.ModifierKeyword.STATIC_KEYWORD);
- break;
- case TerminalTokens.TokenNameprotected:
- modifier = createModifier(Modifier.ModifierKeyword.PROTECTED_KEYWORD);
- break;
- case TerminalTokens.TokenNameprivate:
- modifier = createModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD);
- break;
- case TerminalTokens.TokenNamefinal:
- modifier = createModifier(Modifier.ModifierKeyword.FINAL_KEYWORD);
- break;
- case TerminalTokens.TokenNamenative:
- modifier = createModifier(Modifier.ModifierKeyword.NATIVE_KEYWORD);
- break;
- case TerminalTokens.TokenNamesynchronized:
- modifier = createModifier(Modifier.ModifierKeyword.SYNCHRONIZED_KEYWORD);
- break;
- case TerminalTokens.TokenNametransient:
- modifier = createModifier(Modifier.ModifierKeyword.TRANSIENT_KEYWORD);
- break;
- case TerminalTokens.TokenNamevolatile:
- modifier = createModifier(Modifier.ModifierKeyword.VOLATILE_KEYWORD);
- break;
- case TerminalTokens.TokenNameCOMMENT_BLOCK :
- case TerminalTokens.TokenNameCOMMENT_LINE :
- case TerminalTokens.TokenNameCOMMENT_JAVADOC :
- break;
- default :
- return;
- }
- if (modifier != null) {
- variableDecl.modifiers().add(modifier);
- }
- }
- } catch(InvalidInputException e) {
- // ignore
- }
- }
- }
-
- protected void setModifiers(SingleVariableDeclaration variableDecl, LocalDeclaration localDeclaration) {
- switch(this.ast.apiLevel) {
- case AST.JLS2_INTERNAL :
- variableDecl.internalSetModifiers(localDeclaration.modifiers & ExtraCompilerModifiers.AccJustFlag);
- break;
- case AST.JLS3 :
- this.scanner.resetTo(localDeclaration.declarationSourceStart, localDeclaration.sourceStart);
- try {
- int token;
- while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
- IExtendedModifier modifier = null;
- switch(token) {
- case TerminalTokens.TokenNameabstract:
- modifier = createModifier(Modifier.ModifierKeyword.ABSTRACT_KEYWORD);
- break;
- case TerminalTokens.TokenNamepublic:
- modifier = createModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD);
- break;
- case TerminalTokens.TokenNamestatic:
- modifier = createModifier(Modifier.ModifierKeyword.STATIC_KEYWORD);
- break;
- case TerminalTokens.TokenNameprotected:
- modifier = createModifier(Modifier.ModifierKeyword.PROTECTED_KEYWORD);
- break;
- case TerminalTokens.TokenNameprivate:
- modifier = createModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD);
- break;
- case TerminalTokens.TokenNamefinal:
- modifier = createModifier(Modifier.ModifierKeyword.FINAL_KEYWORD);
- break;
- case TerminalTokens.TokenNamenative:
- modifier = createModifier(Modifier.ModifierKeyword.NATIVE_KEYWORD);
- break;
- case TerminalTokens.TokenNamesynchronized:
- modifier = createModifier(Modifier.ModifierKeyword.SYNCHRONIZED_KEYWORD);
- break;
- case TerminalTokens.TokenNametransient:
- modifier = createModifier(Modifier.ModifierKeyword.TRANSIENT_KEYWORD);
- break;
- case TerminalTokens.TokenNamevolatile:
- modifier = createModifier(Modifier.ModifierKeyword.VOLATILE_KEYWORD);
- break;
- case TerminalTokens.TokenNameCOMMENT_BLOCK :
- case TerminalTokens.TokenNameCOMMENT_LINE :
- case TerminalTokens.TokenNameCOMMENT_JAVADOC :
- break;
- default :
- return;
- }
- if (modifier != null) {
- variableDecl.modifiers().add(modifier);
- }
- }
- } catch(InvalidInputException e) {
- // ignore
- }
- }
- }
-
- /**
- * @param typeDecl
- * @param typeDeclaration
- */
- protected void setModifiers(TypeDeclaration typeDecl, org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration typeDeclaration) {
- switch(this.ast.apiLevel) {
- case AST.JLS2_INTERNAL :
- int modifiers = typeDeclaration.modifiers;
- modifiers &= ExtraCompilerModifiers.AccJustFlag;
- typeDecl.internalSetModifiers(modifiers);
- break;
- case AST.JLS3 :
- this.scanner.resetTo(typeDeclaration.declarationSourceStart, typeDeclaration.sourceStart);
- this.setModifiers(typeDecl);
- }
- }
-
- /**
- * @param variableDeclarationExpression
- * @param localDeclaration
- */
- protected void setModifiers(VariableDeclarationExpression variableDeclarationExpression, LocalDeclaration localDeclaration) {
- switch(this.ast.apiLevel) {
- case AST.JLS2_INTERNAL :
- int modifiers = localDeclaration.modifiers & ExtraCompilerModifiers.AccJustFlag;
- modifiers &= ~ExtraCompilerModifiers.AccBlankFinal;
- variableDeclarationExpression.internalSetModifiers(modifiers);
- break;
- case AST.JLS3 :
- this.scanner.resetTo(localDeclaration.declarationSourceStart, localDeclaration.sourceStart);
- try {
- int token;
- while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
- IExtendedModifier modifier = null;
- switch(token) {
- case TerminalTokens.TokenNameabstract:
- modifier = createModifier(Modifier.ModifierKeyword.ABSTRACT_KEYWORD);
- break;
- case TerminalTokens.TokenNamepublic:
- modifier = createModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD);
- break;
- case TerminalTokens.TokenNamestatic:
- modifier = createModifier(Modifier.ModifierKeyword.STATIC_KEYWORD);
- break;
- case TerminalTokens.TokenNameprotected:
- modifier = createModifier(Modifier.ModifierKeyword.PROTECTED_KEYWORD);
- break;
- case TerminalTokens.TokenNameprivate:
- modifier = createModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD);
- break;
- case TerminalTokens.TokenNamefinal:
- modifier = createModifier(Modifier.ModifierKeyword.FINAL_KEYWORD);
- break;
- case TerminalTokens.TokenNamenative:
- modifier = createModifier(Modifier.ModifierKeyword.NATIVE_KEYWORD);
- break;
- case TerminalTokens.TokenNamesynchronized:
- modifier = createModifier(Modifier.ModifierKeyword.SYNCHRONIZED_KEYWORD);
- break;
- case TerminalTokens.TokenNametransient:
- modifier = createModifier(Modifier.ModifierKeyword.TRANSIENT_KEYWORD);
- break;
- case TerminalTokens.TokenNamevolatile:
- modifier = createModifier(Modifier.ModifierKeyword.VOLATILE_KEYWORD);
- break;
- case TerminalTokens.TokenNameCOMMENT_BLOCK :
- case TerminalTokens.TokenNameCOMMENT_LINE :
- case TerminalTokens.TokenNameCOMMENT_JAVADOC :
- break;
- default :
- return;
- }
- if (modifier != null) {
- variableDeclarationExpression.modifiers().add(modifier);
- }
- }
- } catch(InvalidInputException e) {
- // ignore
- }
- }
- }
-
- /**
- * @param variableDeclarationStatement
- * @param localDeclaration
- */
- protected void setModifiers(VariableDeclarationStatement variableDeclarationStatement, LocalDeclaration localDeclaration) {
- switch(this.ast.apiLevel) {
- case AST.JLS2_INTERNAL :
- int modifiers = localDeclaration.modifiers & ExtraCompilerModifiers.AccJustFlag;
- modifiers &= ~ExtraCompilerModifiers.AccBlankFinal;
- variableDeclarationStatement.internalSetModifiers(modifiers);
- break;
- case AST.JLS3 :
- this.scanner.resetTo(localDeclaration.declarationSourceStart, localDeclaration.sourceStart);
- try {
- int token;
- while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
- IExtendedModifier modifier = null;
- switch(token) {
- case TerminalTokens.TokenNameabstract:
- modifier = createModifier(Modifier.ModifierKeyword.ABSTRACT_KEYWORD);
- break;
- case TerminalTokens.TokenNamepublic:
- modifier = createModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD);
- break;
- case TerminalTokens.TokenNamestatic:
- modifier = createModifier(Modifier.ModifierKeyword.STATIC_KEYWORD);
- break;
- case TerminalTokens.TokenNameprotected:
- modifier = createModifier(Modifier.ModifierKeyword.PROTECTED_KEYWORD);
- break;
- case TerminalTokens.TokenNameprivate:
- modifier = createModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD);
- break;
- case TerminalTokens.TokenNamefinal:
- modifier = createModifier(Modifier.ModifierKeyword.FINAL_KEYWORD);
- break;
- case TerminalTokens.TokenNamenative:
- modifier = createModifier(Modifier.ModifierKeyword.NATIVE_KEYWORD);
- break;
- case TerminalTokens.TokenNamesynchronized:
- modifier = createModifier(Modifier.ModifierKeyword.SYNCHRONIZED_KEYWORD);
- break;
- case TerminalTokens.TokenNametransient:
- modifier = createModifier(Modifier.ModifierKeyword.TRANSIENT_KEYWORD);
- break;
- case TerminalTokens.TokenNamevolatile:
- modifier = createModifier(Modifier.ModifierKeyword.VOLATILE_KEYWORD);
- break;
- case TerminalTokens.TokenNameCOMMENT_BLOCK :
- case TerminalTokens.TokenNameCOMMENT_LINE :
- case TerminalTokens.TokenNameCOMMENT_JAVADOC :
- break;
- default :
- return;
- }
- if (modifier != null) {
- variableDeclarationStatement.modifiers().add(modifier);
- }
- }
- } catch(InvalidInputException e) {
- // ignore
- }
- }
- }
-
- protected QualifiedName setQualifiedNameNameAndSourceRanges(char[][] typeName, long[] positions, org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode node) {
- int length = typeName.length;
- final SimpleName firstToken = new SimpleName(this.ast);
- firstToken.internalSetIdentifier(new String(typeName[0]));
- firstToken.index = 1;
- int start0 = (int)(positions[0]>>>32);
- int start = start0;
- int end = (int)(positions[0] & 0xFFFFFFFF);
- firstToken.setSourceRange(start, end - start + 1);
- final SimpleName secondToken = new SimpleName(this.ast);
- secondToken.internalSetIdentifier(new String(typeName[1]));
- secondToken.index = 2;
- start = (int)(positions[1]>>>32);
- end = (int)(positions[1] & 0xFFFFFFFF);
- secondToken.setSourceRange(start, end - start + 1);
- QualifiedName qualifiedName = new QualifiedName(this.ast);
- qualifiedName.setQualifier(firstToken);
- qualifiedName.setName(secondToken);
- if (this.resolveBindings) {
- recordNodes(qualifiedName, node);
- recordPendingNameScopeResolution(qualifiedName);
- recordNodes(firstToken, node);
- recordNodes(secondToken, node);
- recordPendingNameScopeResolution(firstToken);
- recordPendingNameScopeResolution(secondToken);
- }
- qualifiedName.index = 2;
- qualifiedName.setSourceRange(start0, end - start0 + 1);
- SimpleName newPart = null;
- for (int i = 2; i < length; i++) {
- newPart = new SimpleName(this.ast);
- newPart.internalSetIdentifier(new String(typeName[i]));
- newPart.index = i + 1;
- start = (int)(positions[i]>>>32);
- end = (int)(positions[i] & 0xFFFFFFFF);
- newPart.setSourceRange(start, end - start + 1);
- QualifiedName qualifiedName2 = new QualifiedName(this.ast);
- qualifiedName2.setQualifier(qualifiedName);
- qualifiedName2.setName(newPart);
- qualifiedName = qualifiedName2;
- qualifiedName.index = newPart.index;
- qualifiedName.setSourceRange(start0, end - start0 + 1);
- if (this.resolveBindings) {
- recordNodes(qualifiedName, node);
- recordNodes(newPart, node);
- recordPendingNameScopeResolution(qualifiedName);
- recordPendingNameScopeResolution(newPart);
- }
- }
- QualifiedName name = qualifiedName;
- if (this.resolveBindings) {
- recordNodes(name, node);
- recordPendingNameScopeResolution(name);
- }
- return name;
- }
-
- protected QualifiedName setQualifiedNameNameAndSourceRanges(char[][] typeName, long[] positions, int endingIndex, org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode node) {
- int length = endingIndex + 1;
- final SimpleName firstToken = new SimpleName(this.ast);
- firstToken.internalSetIdentifier(new String(typeName[0]));
- firstToken.index = 1;
- int start0 = (int)(positions[0]>>>32);
- int start = start0;
- int end = (int) positions[0];
- firstToken.setSourceRange(start, end - start + 1);
- final SimpleName secondToken = new SimpleName(this.ast);
- secondToken.internalSetIdentifier(new String(typeName[1]));
- secondToken.index = 2;
- start = (int)(positions[1]>>>32);
- end = (int) positions[1];
- secondToken.setSourceRange(start, end - start + 1);
- QualifiedName qualifiedName = new QualifiedName(this.ast);
- qualifiedName.setQualifier(firstToken);
- qualifiedName.setName(secondToken);
- if (this.resolveBindings) {
- recordNodes(qualifiedName, node);
- recordPendingNameScopeResolution(qualifiedName);
- recordNodes(firstToken, node);
- recordNodes(secondToken, node);
- recordPendingNameScopeResolution(firstToken);
- recordPendingNameScopeResolution(secondToken);
- }
- qualifiedName.index = 2;
- qualifiedName.setSourceRange(start0, end - start0 + 1);
- SimpleName newPart = null;
- for (int i = 2; i < length; i++) {
- newPart = new SimpleName(this.ast);
- newPart.internalSetIdentifier(new String(typeName[i]));
- newPart.index = i + 1;
- start = (int)(positions[i]>>>32);
- end = (int) positions[i];
- newPart.setSourceRange(start, end - start + 1);
- QualifiedName qualifiedName2 = new QualifiedName(this.ast);
- qualifiedName2.setQualifier(qualifiedName);
- qualifiedName2.setName(newPart);
- qualifiedName = qualifiedName2;
- qualifiedName.index = newPart.index;
- qualifiedName.setSourceRange(start0, end - start0 + 1);
- if (this.resolveBindings) {
- recordNodes(qualifiedName, node);
- recordNodes(newPart, node);
- recordPendingNameScopeResolution(qualifiedName);
- recordPendingNameScopeResolution(newPart);
- }
- }
- if (newPart == null && this.resolveBindings) {
- recordNodes(qualifiedName, node);
- recordPendingNameScopeResolution(qualifiedName);
- }
- return qualifiedName;
- }
-
-
- protected void setTypeForField(FieldDeclaration fieldDeclaration, Type type, int extraDimension) {
- if (extraDimension != 0) {
- if (type.isArrayType()) {
- ArrayType arrayType = (ArrayType) type;
- int remainingDimensions = arrayType.getDimensions() - extraDimension;
- if (remainingDimensions == 0) {
- // the dimensions are after the name so the type of the fieldDeclaration is a simpleType
- Type elementType = arrayType.getElementType();
- // cut the child loose from its parent (without creating garbage)
- elementType.setParent(null, null);
- this.ast.getBindingResolver().updateKey(type, elementType);
- fieldDeclaration.setType(elementType);
- } else {
- int start = type.getStartPosition();
- ArrayType subarrayType = arrayType;
- int index = extraDimension;
- while (index > 0) {
- subarrayType = (ArrayType) subarrayType.getComponentType();
- index--;
- }
- int end = retrieveProperRightBracketPosition(remainingDimensions, start);
- subarrayType.setSourceRange(start, end - start + 1);
- // cut the child loose from its parent (without creating garbage)
- subarrayType.setParent(null, null);
- fieldDeclaration.setType(subarrayType);
- updateInnerPositions(subarrayType, remainingDimensions);
- this.ast.getBindingResolver().updateKey(type, subarrayType);
- }
- } else {
- fieldDeclaration.setType(type);
- }
- } else {
- if (type.isArrayType()) {
- // update positions of the component types of the array type
- int dimensions = ((ArrayType) type).getDimensions();
- updateInnerPositions(type, dimensions);
- }
- fieldDeclaration.setType(type);
- }
- }
-
- protected void setTypeForMethodDeclaration(FunctionDeclaration methodDeclaration, Type type, int extraDimension) {
- if (extraDimension != 0) {
- if (type.isArrayType()) {
- ArrayType arrayType = (ArrayType) type;
- int remainingDimensions = arrayType.getDimensions() - extraDimension;
- if (remainingDimensions == 0) {
- // the dimensions are after the name so the type of the fieldDeclaration is a simpleType
- Type elementType = arrayType.getElementType();
- // cut the child loose from its parent (without creating garbage)
- elementType.setParent(null, null);
- this.ast.getBindingResolver().updateKey(type, elementType);
- switch(this.ast.apiLevel) {
- case AST.JLS2_INTERNAL :
- methodDeclaration.internalSetReturnType(elementType);
- break;
- case AST.JLS3 :
- methodDeclaration.setReturnType2(elementType);
- break;
- }
- } else {
- int start = type.getStartPosition();
- ArrayType subarrayType = arrayType;
- int index = extraDimension;
- while (index > 0) {
- subarrayType = (ArrayType) subarrayType.getComponentType();
- index--;
- }
- int end = retrieveProperRightBracketPosition(remainingDimensions, start);
- subarrayType.setSourceRange(start, end - start + 1);
- // cut the child loose from its parent (without creating garbage)
- subarrayType.setParent(null, null);
- updateInnerPositions(subarrayType, remainingDimensions);
- switch(this.ast.apiLevel) {
- case AST.JLS2_INTERNAL :
- methodDeclaration.internalSetReturnType(subarrayType);
- break;
- case AST.JLS3 :
- methodDeclaration.setReturnType2(subarrayType);
- break;
- }
- this.ast.getBindingResolver().updateKey(type, subarrayType);
- }
- } else {
- switch(this.ast.apiLevel) {
- case AST.JLS2_INTERNAL :
- methodDeclaration.internalSetReturnType(type);
- break;
- case AST.JLS3 :
- methodDeclaration.setReturnType2(type);
- break;
- }
- }
- } else {
- switch(this.ast.apiLevel) {
- case AST.JLS2_INTERNAL :
- methodDeclaration.internalSetReturnType(type);
- break;
- case AST.JLS3 :
- methodDeclaration.setReturnType2(type);
- break;
- }
- }
- }
-
- protected void setTypeForSingleVariableDeclaration(SingleVariableDeclaration singleVariableDeclaration, Type type, int extraDimension) {
- if (extraDimension != 0) {
- if (type.isArrayType()) {
- ArrayType arrayType = (ArrayType) type;
- int remainingDimensions = arrayType.getDimensions() - extraDimension;
- if (remainingDimensions == 0) {
- // the dimensions are after the name so the type of the fieldDeclaration is a simpleType
- Type elementType = arrayType.getElementType();
- // cut the child loose from its parent (without creating garbage)
- elementType.setParent(null, null);
- this.ast.getBindingResolver().updateKey(type, elementType);
- singleVariableDeclaration.setType(elementType);
- } else {
- int start = type.getStartPosition();
- ArrayType subarrayType = arrayType;
- int index = extraDimension;
- while (index > 0) {
- subarrayType = (ArrayType) subarrayType.getComponentType();
- index--;
- }
- int end = retrieveProperRightBracketPosition(remainingDimensions, start);
- subarrayType.setSourceRange(start, end - start + 1);
- // cut the child loose from its parent (without creating garbage)
- subarrayType.setParent(null, null);
- updateInnerPositions(subarrayType, remainingDimensions);
- singleVariableDeclaration.setType(subarrayType);
- this.ast.getBindingResolver().updateKey(type, subarrayType);
- }
- } else {
- singleVariableDeclaration.setType(type);
- }
- } else {
- singleVariableDeclaration.setType(type);
- }
- }
-
- protected void setTypeForVariableDeclarationExpression(VariableDeclarationExpression variableDeclarationExpression, Type type, int extraDimension) {
- if (extraDimension != 0) {
- if (type.isArrayType()) {
- ArrayType arrayType = (ArrayType) type;
- int remainingDimensions = arrayType.getDimensions() - extraDimension;
- if (remainingDimensions == 0) {
- // the dimensions are after the name so the type of the fieldDeclaration is a simpleType
- Type elementType = arrayType.getElementType();
- // cut the child loose from its parent (without creating garbage)
- elementType.setParent(null, null);
- this.ast.getBindingResolver().updateKey(type, elementType);
- variableDeclarationExpression.setType(elementType);
- } else {
- int start = type.getStartPosition();
- ArrayType subarrayType = arrayType;
- int index = extraDimension;
- while (index > 0) {
- subarrayType = (ArrayType) subarrayType.getComponentType();
- index--;
- }
- int end = retrieveProperRightBracketPosition(remainingDimensions, start);
- subarrayType.setSourceRange(start, end - start + 1);
- // cut the child loose from its parent (without creating garbage)
- subarrayType.setParent(null, null);
- updateInnerPositions(subarrayType, remainingDimensions);
- variableDeclarationExpression.setType(subarrayType);
- this.ast.getBindingResolver().updateKey(type, subarrayType);
- }
- } else {
- variableDeclarationExpression.setType(type);
- }
- } else {
- variableDeclarationExpression.setType(type);
- }
- }
-
- protected void setTypeForVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement, Type type, int extraDimension) {
- if (extraDimension != 0) {
- if (type.isArrayType()) {
- ArrayType arrayType = (ArrayType) type;
- int remainingDimensions = arrayType.getDimensions() - extraDimension;
- if (remainingDimensions == 0) {
- // the dimensions are after the name so the type of the fieldDeclaration is a simpleType
- Type elementType = arrayType.getElementType();
- // cut the child loose from its parent (without creating garbage)
- elementType.setParent(null, null);
- this.ast.getBindingResolver().updateKey(type, elementType);
- variableDeclarationStatement.setType(elementType);
- } else {
- int start = type.getStartPosition();
- ArrayType subarrayType = arrayType;
- int index = extraDimension;
- while (index > 0) {
- subarrayType = (ArrayType) subarrayType.getComponentType();
- index--;
- }
- int end = retrieveProperRightBracketPosition(remainingDimensions, start);
- subarrayType.setSourceRange(start, end - start + 1);
- // cut the child loose from its parent (without creating garbage)
- subarrayType.setParent(null, null);
- updateInnerPositions(subarrayType, remainingDimensions);
- variableDeclarationStatement.setType(subarrayType);
- this.ast.getBindingResolver().updateKey(type, subarrayType);
- }
- } else {
- variableDeclarationStatement.setType(type);
- }
- } else {
- variableDeclarationStatement.setType(type);
- }
- }
-
- protected void updateInnerPositions(Type type, int dimensions) {
- if (dimensions > 1) {
- // need to set positions for intermediate array type see 42839
- int start = type.getStartPosition();
- Type currentComponentType = ((ArrayType) type).getComponentType();
- int searchedDimension = dimensions - 1;
- int rightBracketEndPosition = start;
- while (currentComponentType.isArrayType()) {
- rightBracketEndPosition = retrieveProperRightBracketPosition(searchedDimension, start);
- currentComponentType.setSourceRange(start, rightBracketEndPosition - start + 1);
- currentComponentType = ((ArrayType) currentComponentType).getComponentType();
- searchedDimension--;
- }
- }
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ASTMatcher.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ASTMatcher.java
deleted file mode 100644
index a5de2534..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ASTMatcher.java
+++ /dev/null
@@ -1,2083 +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.core.dom;
-
-import java.util.Iterator;
-import java.util.List;
-
-/**
- * Concrete superclass and default implementation of an AST subtree matcher.
- * <p>
- * For example, to compute whether two ASTs subtrees are structurally
- * isomorphic, use <code>n1.subtreeMatch(new ASTMatcher(), n2)</code> where
- * <code>n1</code> and <code>n2</code> are the AST root nodes of the subtrees.
- * </p>
- * <p>
- * For each different concrete AST node type <i>T</i> there is a
- * <code>public boolean match(<i>T</i> node, Object other)</code> method
- * that matches the given node against another object (typically another
- * AST node, although this is not essential). The default implementations
- * provided by this class tests whether the other object is a node of the
- * same type with structurally isomorphic child subtrees. For nodes with
- * list-valued properties, the child nodes within the list are compared in
- * order. For nodes with multiple properties, the child nodes are compared
- * in the order that most closely corresponds to the lexical reading order
- * of the source program. For instance, for a type declaration node, the
- * child ordering is: name, superclass, superinterfaces, and body
- * declarations.
- * </p>
- * <p>
- * Subclasses may override (extend or reimplement) some or all of the
- * <code>match</code> methods in order to define more specialized subtree
- * matchers.
- * </p>
- *
- * @see org.eclipse.wst.jsdt.core.dom.ASTNode#subtreeMatch(ASTMatcher, Object)
- *
- * 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 ASTMatcher {
-
- /**
- * Indicates whether doc tags should be matched.
- */
- private boolean matchDocTags;
-
- /**
- * Creates a new AST matcher instance.
- * <p>
- * For backwards compatibility, the matcher ignores tag
- * elements below doc comments by default. Use
- * {@link #ASTMatcher(boolean) ASTMatcher(true)}
- * for a matcher that compares doc tags by default.
- * </p>
- */
- public ASTMatcher() {
- this(false);
- }
-
- /**
- * Creates a new AST matcher instance.
- *
- * @param matchDocTags <code>true</code> if doc comment tags are
- * to be compared by default, and <code>false</code> otherwise
- * @see #match(JSdoc,Object)
- */
- public ASTMatcher(boolean matchDocTags) {
- this.matchDocTags = matchDocTags;
- }
-
- /**
- * Returns whether the given lists of AST nodes match pair wise according
- * to <code>ASTNode.subtreeMatch</code>.
- * <p>
- * Note that this is a convenience method, useful for writing recursive
- * subtree matchers.
- * </p>
- *
- * @param list1 the first list of AST nodes
- * (element type: <code>ASTNode</code>)
- * @param list2 the second list of AST nodes
- * (element type: <code>ASTNode</code>)
- * @return <code>true</code> if the lists have the same number of elements
- * and match pair-wise according to <code>ASTNode.subtreeMatch</code>
- * @see ASTNode#subtreeMatch(ASTMatcher matcher, Object other)
- */
- public final boolean safeSubtreeListMatch(List list1, List list2) {
- int size1 = list1.size();
- int size2 = list2.size();
- if (size1 != size2) {
- return false;
- }
- for (Iterator it1 = list1.iterator(), it2 = list2.iterator(); it1.hasNext();) {
- ASTNode n1 = (ASTNode) it1.next();
- ASTNode n2 = (ASTNode) it2.next();
- if (!n1.subtreeMatch(this, n2)) {
- return false;
- }
- }
- return true;
- }
-
- /**
- * Returns whether the given nodes match according to
- * <code>AST.subtreeMatch</code>. Returns <code>false</code> if one or
- * the other of the nodes are <code>null</code>. Returns <code>true</code>
- * if both nodes are <code>null</code>.
- * <p>
- * Note that this is a convenience method, useful for writing recursive
- * subtree matchers.
- * </p>
- *
- * @param node1 the first AST node, or <code>null</code>; must be an
- * instance of <code>ASTNode</code>
- * @param node2 the second AST node, or <code>null</code>; must be an
- * instance of <code>ASTNode</code>
- * @return <code>true</code> if the nodes match according
- * to <code>AST.subtreeMatch</code> or both are <code>null</code>, and
- * <code>false</code> otherwise
- * @see ASTNode#subtreeMatch(ASTMatcher, Object)
- */
- public final boolean safeSubtreeMatch(Object node1, Object node2) {
- if (node1 == null && node2 == null) {
- return true;
- }
- if (node1 == null || node2 == null) {
- return false;
- }
- // N.B. call subtreeMatch even node1==node2!=null
- return ((ASTNode) node1).subtreeMatch(this, node2);
- }
-
- /**
- * Returns whether the given objects are equal according to
- * <code>equals</code>. Returns <code>false</code> if either
- * node is <code>null</code>.
- *
- * @param o1 the first object, or <code>null</code>
- * @param o2 the second object, or <code>null</code>
- * @return <code>true</code> if the nodes are equal according to
- * <code>equals</code> or both <code>null</code>, and
- * <code>false</code> otherwise
- */
- public static boolean safeEquals(Object o1, Object o2) {
- if (o1 == o2) {
- return true;
- }
- if (o1 == null || o2 == null) {
- return false;
- }
- return o1.equals(o2);
- }
-
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(AnonymousClassDeclaration node, Object other) {
- if (!(other instanceof AnonymousClassDeclaration)) {
- return false;
- }
- AnonymousClassDeclaration o = (AnonymousClassDeclaration) other;
- return safeSubtreeListMatch(node.bodyDeclarations(), o.bodyDeclarations());
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(ArrayAccess node, Object other) {
- if (!(other instanceof ArrayAccess)) {
- return false;
- }
- ArrayAccess o = (ArrayAccess) other;
- return (
- safeSubtreeMatch(node.getArray(), o.getArray())
- && safeSubtreeMatch(node.getIndex(), o.getIndex()));
- }
-
- /**
- * Returns whether the given node and the other object object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(ArrayCreation node, Object other) {
- if (!(other instanceof ArrayCreation)) {
- return false;
- }
- ArrayCreation o = (ArrayCreation) other;
- return (
- safeSubtreeMatch(node.getType(), o.getType())
- && safeSubtreeListMatch(node.dimensions(), o.dimensions())
- && safeSubtreeMatch(node.getInitializer(), o.getInitializer()));
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(ArrayInitializer node, Object other) {
- if (!(other instanceof ArrayInitializer)) {
- return false;
- }
- ArrayInitializer o = (ArrayInitializer) other;
- return safeSubtreeListMatch(node.expressions(), o.expressions());
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(ArrayType node, Object other) {
- if (!(other instanceof ArrayType)) {
- return false;
- }
- ArrayType o = (ArrayType) other;
- return safeSubtreeMatch(node.getComponentType(), o.getComponentType());
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(Assignment node, Object other) {
- if (!(other instanceof Assignment)) {
- return false;
- }
- Assignment o = (Assignment) other;
- return (
- node.getOperator().equals(o.getOperator())
- && safeSubtreeMatch(node.getLeftHandSide(), o.getLeftHandSide())
- && safeSubtreeMatch(node.getRightHandSide(), o.getRightHandSide()));
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(Block node, Object other) {
- if (!(other instanceof Block)) {
- return false;
- }
- Block o = (Block) other;
- return safeSubtreeListMatch(node.statements(), o.statements());
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type. Subclasses may override
- * this method as needed.
- * </p>
- * <p>Note: {@link LineComment} and {@link BlockComment} nodes are
- * not considered part of main structure of the AST. This method will
- * only be called if a client goes out of their way to visit this
- * kind of node explicitly.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(BlockComment node, Object other) {
- if (!(other instanceof BlockComment)) {
- return false;
- }
- return true;
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(BooleanLiteral node, Object other) {
- if (!(other instanceof BooleanLiteral)) {
- return false;
- }
- BooleanLiteral o = (BooleanLiteral) other;
- return node.booleanValue() == o.booleanValue();
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(BreakStatement node, Object other) {
- if (!(other instanceof BreakStatement)) {
- return false;
- }
- BreakStatement o = (BreakStatement) other;
- return safeSubtreeMatch(node.getLabel(), o.getLabel());
- }
-
- public boolean match(FunctionExpression node, Object other) {
- if (!(other instanceof FunctionExpression)) {
- return false;
- }
- FunctionExpression o = (FunctionExpression) other;
- return
- safeSubtreeMatch(node.getMethod(), o.getMethod());
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(CatchClause node, Object other) {
- if (!(other instanceof CatchClause)) {
- return false;
- }
- CatchClause o = (CatchClause) other;
- return (
- safeSubtreeMatch(node.getException(), o.getException())
- && safeSubtreeMatch(node.getBody(), o.getBody()));
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(CharacterLiteral node, Object other) {
- if (!(other instanceof CharacterLiteral)) {
- return false;
- }
- CharacterLiteral o = (CharacterLiteral) other;
- return safeEquals(node.getEscapedValue(), o.getEscapedValue());
- }
-
- public boolean match(RegularExpressionLiteral node, Object other) {
- if (!(other instanceof CharacterLiteral)) {
- return false;
- }
- RegularExpressionLiteral o = (RegularExpressionLiteral) other;
- return safeEquals(node.getRegularExpression(), o.getRegularExpression());
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(ClassInstanceCreation node, Object other) {
- if (!(other instanceof ClassInstanceCreation)) {
- return false;
- }
- ClassInstanceCreation o = (ClassInstanceCreation) other;
- int level = node.getAST().apiLevel;
- if (level == AST.JLS2_INTERNAL) {
- if (!safeSubtreeMatch(node.internalGetName(), o.internalGetName())) {
- return false;
- }
- }
- if (level >= AST.JLS3) {
- if (!safeSubtreeListMatch(node.typeArguments(), o.typeArguments())) {
- return false;
- }
- if (!safeSubtreeMatch(node.getType(), o.getType())) {
- return false;
- }
- }
- return
- safeSubtreeMatch(node.getExpression(), o.getExpression())
- && safeSubtreeMatch(node.getMember(), o.getMember())
- && safeSubtreeListMatch(node.arguments(), o.arguments())
- && safeSubtreeMatch(
- node.getAnonymousClassDeclaration(),
- o.getAnonymousClassDeclaration());
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(JavaScriptUnit node, Object other) {
- if (!(other instanceof JavaScriptUnit)) {
- return false;
- }
- JavaScriptUnit o = (JavaScriptUnit) other;
- return (
- safeSubtreeMatch(node.getPackage(), o.getPackage())
- && safeSubtreeListMatch(node.imports(), o.imports())
- && safeSubtreeListMatch(node.types(), o.types()));
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(ConditionalExpression node, Object other) {
- if (!(other instanceof ConditionalExpression)) {
- return false;
- }
- ConditionalExpression o = (ConditionalExpression) other;
- return (
- safeSubtreeMatch(node.getExpression(), o.getExpression())
- && safeSubtreeMatch(node.getThenExpression(), o.getThenExpression())
- && safeSubtreeMatch(node.getElseExpression(), o.getElseExpression()));
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(ConstructorInvocation node, Object other) {
- if (!(other instanceof ConstructorInvocation)) {
- return false;
- }
- ConstructorInvocation o = (ConstructorInvocation) other;
- if (node.getAST().apiLevel >= AST.JLS3) {
- if (!safeSubtreeListMatch(node.typeArguments(), o.typeArguments())) {
- return false;
- }
- }
- return safeSubtreeListMatch(node.arguments(), o.arguments());
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(ContinueStatement node, Object other) {
- if (!(other instanceof ContinueStatement)) {
- return false;
- }
- ContinueStatement o = (ContinueStatement) other;
- return safeSubtreeMatch(node.getLabel(), o.getLabel());
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(DoStatement node, Object other) {
- if (!(other instanceof DoStatement)) {
- return false;
- }
- DoStatement o = (DoStatement) other;
- return (
- safeSubtreeMatch(node.getExpression(), o.getExpression())
- && safeSubtreeMatch(node.getBody(), o.getBody()));
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(EmptyStatement node, Object other) {
- if (!(other instanceof EmptyStatement)) {
- return false;
- }
- return true;
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(EnhancedForStatement node, Object other) {
- if (!(other instanceof EnhancedForStatement)) {
- return false;
- }
- EnhancedForStatement o = (EnhancedForStatement) other;
- return (
- safeSubtreeMatch(node.getParameter(), o.getParameter())
- && safeSubtreeMatch(node.getExpression(), o.getExpression())
- && safeSubtreeMatch(node.getBody(), o.getBody()));
- }
-
-
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(ExpressionStatement node, Object other) {
- if (!(other instanceof ExpressionStatement)) {
- return false;
- }
- ExpressionStatement o = (ExpressionStatement) other;
- return safeSubtreeMatch(node.getExpression(), o.getExpression());
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(FieldAccess node, Object other) {
- if (!(other instanceof FieldAccess)) {
- return false;
- }
- FieldAccess o = (FieldAccess) other;
- return (
- safeSubtreeMatch(node.getExpression(), o.getExpression())
- && safeSubtreeMatch(node.getName(), o.getName()));
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(FieldDeclaration node, Object other) {
- if (!(other instanceof FieldDeclaration)) {
- return false;
- }
- FieldDeclaration o = (FieldDeclaration) other;
- int level = node.getAST().apiLevel;
- if (level == AST.JLS2_INTERNAL) {
- if (node.getModifiers() != o.getModifiers()) {
- return false;
- }
- }
- if (level >= AST.JLS3) {
- if (!safeSubtreeListMatch(node.modifiers(), o.modifiers())) {
- return false;
- }
- }
- return
- safeSubtreeMatch(node.getJavadoc(), o.getJavadoc())
- && safeSubtreeMatch(node.getType(), o.getType())
- && safeSubtreeListMatch(node.fragments(), o.fragments());
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(ForStatement node, Object other) {
- if (!(other instanceof ForStatement)) {
- return false;
- }
- ForStatement o = (ForStatement) other;
- return (
- safeSubtreeListMatch(node.initializers(), o.initializers())
- && safeSubtreeMatch(node.getExpression(), o.getExpression())
- && safeSubtreeListMatch(node.updaters(), o.updaters())
- && safeSubtreeMatch(node.getBody(), o.getBody()));
- }
-
- public boolean match(ForInStatement node, Object other) {
- if (!(other instanceof ForInStatement)) {
- return false;
- }
- ForInStatement o = (ForInStatement) other;
- return (
- safeSubtreeMatch(node.getIterationVariable(), o.getIterationVariable())
- && safeSubtreeMatch(node.getCollection(), o.getCollection())
- && safeSubtreeMatch(node.getBody(), o.getBody()));
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(IfStatement node, Object other) {
- if (!(other instanceof IfStatement)) {
- return false;
- }
- IfStatement o = (IfStatement) other;
- return (
- safeSubtreeMatch(node.getExpression(), o.getExpression())
- && safeSubtreeMatch(node.getThenStatement(), o.getThenStatement())
- && safeSubtreeMatch(node.getElseStatement(), o.getElseStatement()));
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(ImportDeclaration node, Object other) {
- if (!(other instanceof ImportDeclaration)) {
- return false;
- }
- ImportDeclaration o = (ImportDeclaration) other;
- if (node.getAST().apiLevel >= AST.JLS3) {
- if (node.isStatic() != o.isStatic()) {
- return false;
- }
- }
- if (node.isFileImport() != o.isFileImport()) {
- return false;
- }
- return (
- safeSubtreeMatch(node.getName(), o.getName())
- && node.isOnDemand() == o.isOnDemand());
- }
-
-
- public boolean match(InferredType node, Object other) {
- if (!(other instanceof InferredType)) {
- return false;
- }
- InferredType o = (InferredType) other;
- if (node.type==null || o.type==null)
- return true;
-
- return node.type.equals(o.type);
- }
-
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(InfixExpression node, Object other) {
- if (!(other instanceof InfixExpression)) {
- return false;
- }
- InfixExpression o = (InfixExpression) other;
- // be careful not to trigger lazy creation of extended operand lists
- if (node.hasExtendedOperands() && o.hasExtendedOperands()) {
- if (!safeSubtreeListMatch(node.extendedOperands(), o.extendedOperands())) {
- return false;
- }
- }
- if (node.hasExtendedOperands() != o.hasExtendedOperands()) {
- return false;
- }
- return (
- node.getOperator().equals(o.getOperator())
- && safeSubtreeMatch(node.getLeftOperand(), o.getLeftOperand())
- && safeSubtreeMatch(node.getRightOperand(), o.getRightOperand()));
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(InstanceofExpression node, Object other) {
- if (!(other instanceof InstanceofExpression)) {
- return false;
- }
- InstanceofExpression o = (InstanceofExpression) other;
- return (
- safeSubtreeMatch(node.getLeftOperand(), o.getLeftOperand())
- && safeSubtreeMatch(node.getRightOperand(), o.getRightOperand()));
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(Initializer node, Object other) {
- if (!(other instanceof Initializer)) {
- return false;
- }
- Initializer o = (Initializer) other;
- int level = node.getAST().apiLevel;
- if (level == AST.JLS2_INTERNAL) {
- if (node.getModifiers() != o.getModifiers()) {
- return false;
- }
- }
- if (level >= AST.JLS3) {
- if (!safeSubtreeListMatch(node.modifiers(), o.modifiers())) {
- return false;
- }
- }
- return (
- safeSubtreeMatch(node.getJavadoc(), o.getJavadoc())
- && safeSubtreeMatch(node.getBody(), o.getBody()));
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * Unlike other node types, the behavior of the default
- * implementation is controlled by a constructor-supplied
- * parameter {@link #ASTMatcher(boolean) ASTMatcher(boolean)}
- * which is <code>false</code> if not specified.
- * When this parameter is <code>true</code>, the implementation
- * tests whether the other object is also a <code>Javadoc</code>
- * with structurally isomorphic child subtrees; the comment string
- * (<code>Javadoc.getComment()</code>) is ignored.
- * Conversely, when the parameter is <code>false</code>, the
- * implementation tests whether the other object is also a
- * <code>Javadoc</code> with exactly the same comment string;
- * the tag elements ({@link JSdoc#tags() Javadoc.tags} are
- * ignored. Subclasses may reimplement.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- * @see #ASTMatcher()
- * @see #ASTMatcher(boolean)
- */
- public boolean match(JSdoc node, Object other) {
- if (!(other instanceof JSdoc)) {
- return false;
- }
- JSdoc o = (JSdoc) other;
- if (this.matchDocTags) {
- return safeSubtreeListMatch(node.tags(), o.tags());
- } else {
- return compareDeprecatedComment(node, o);
- }
- }
-
- /**
- * Return whether the deprecated comment strings of the given jsdoc are equals.
- * <p>
- * Note the only purpose of this method is to hide deprecated warnings.
- * @deprecated mark deprecated to hide deprecated usage
- */
- private boolean compareDeprecatedComment(JSdoc first, JSdoc second) {
- if (first.getAST().apiLevel == AST.JLS2_INTERNAL) {
- return safeEquals(first.getComment(), second.getComment());
- } else {
- return true;
- }
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(LabeledStatement node, Object other) {
- if (!(other instanceof LabeledStatement)) {
- return false;
- }
- LabeledStatement o = (LabeledStatement) other;
- return (
- safeSubtreeMatch(node.getLabel(), o.getLabel())
- && safeSubtreeMatch(node.getBody(), o.getBody()));
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type. Subclasses may override
- * this method as needed.
- * </p>
- * <p>Note: {@link LineComment} and {@link BlockComment} nodes are
- * not considered part of main structure of the AST. This method will
- * only be called if a client goes out of their way to visit this
- * kind of node explicitly.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(LineComment node, Object other) {
- if (!(other instanceof LineComment)) {
- return false;
- }
- return true;
- }
-
- public boolean match(ListExpression node, Object other) {
- if (!(other instanceof ListExpression)) {
- return false;
- }
- ListExpression o = (ListExpression) other;
- return safeSubtreeListMatch(node.expressions(), o.expressions());
- }
-
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(MemberRef node, Object other) {
- if (!(other instanceof MemberRef)) {
- return false;
- }
- MemberRef o = (MemberRef) other;
- return (
- safeSubtreeMatch(node.getQualifier(), o.getQualifier())
- && safeSubtreeMatch(node.getName(), o.getName()));
- }
-
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(FunctionRef node, Object other) {
- if (!(other instanceof FunctionRef)) {
- return false;
- }
- FunctionRef o = (FunctionRef) other;
- return (
- safeSubtreeMatch(node.getQualifier(), o.getQualifier())
- && safeSubtreeMatch(node.getName(), o.getName())
- && safeSubtreeListMatch(node.parameters(), o.parameters()));
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(FunctionRefParameter node, Object other) {
- if (!(other instanceof FunctionRefParameter)) {
- return false;
- }
- FunctionRefParameter o = (FunctionRefParameter) other;
- int level = node.getAST().apiLevel;
- if (level >= AST.JLS3) {
- if (node.isVarargs() != o.isVarargs()) {
- return false;
- }
- }
- return (
- safeSubtreeMatch(node.getType(), o.getType())
- && safeSubtreeMatch(node.getName(), o.getName()));
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- * <p>
- * Note that extra array dimensions are compared since they are an
- * important part of the method declaration.
- * </p>
- * <p>
- * Note that the method return types are compared even for constructor
- * declarations.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(FunctionDeclaration node, Object other) {
- if (!(other instanceof FunctionDeclaration)) {
- return false;
- }
- FunctionDeclaration o = (FunctionDeclaration) other;
- int level = node.getAST().apiLevel;
- if (level == AST.JLS2_INTERNAL) {
- if (node.getModifiers() != o.getModifiers()) {
- return false;
- }
- if (!safeSubtreeMatch(node.internalGetReturnType(), o.internalGetReturnType())) {
- return false;
- }
- }
- if (level >= AST.JLS3) {
- if (!safeSubtreeListMatch(node.modifiers(), o.modifiers())) {
- return false;
- }
- if (!safeSubtreeMatch(node.getReturnType2(), o.getReturnType2())) {
- return false;
- }
- }
- return ((node.isConstructor() == o.isConstructor())
- && safeSubtreeMatch(node.getJavadoc(), o.getJavadoc())
- && safeSubtreeMatch(node.getName(), o.getName())
- // n.b. compare return type even for constructors
- && safeSubtreeListMatch(node.parameters(), o.parameters())
- && node.getExtraDimensions() == o.getExtraDimensions()
- && safeSubtreeListMatch(node.thrownExceptions(), o.thrownExceptions())
- && safeSubtreeMatch(node.getBody(), o.getBody()));
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(FunctionInvocation node, Object other) {
- if (!(other instanceof FunctionInvocation)) {
- return false;
- }
- FunctionInvocation o = (FunctionInvocation) other;
- if (node.getAST().apiLevel >= AST.JLS3) {
- if (!safeSubtreeListMatch(node.typeArguments(), o.typeArguments())) {
- return false;
- }
- }
- return (
- safeSubtreeMatch(node.getExpression(), o.getExpression())
- && safeSubtreeMatch(node.getName(), o.getName())
- && safeSubtreeListMatch(node.arguments(), o.arguments()));
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(Modifier node, Object other) {
- if (!(other instanceof Modifier)) {
- return false;
- }
- Modifier o = (Modifier) other;
- return (node.getKeyword() == o.getKeyword());
- }
-
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(NullLiteral node, Object other) {
- if (!(other instanceof NullLiteral)) {
- return false;
- }
- return true;
- }
-
- public boolean match(UndefinedLiteral node, Object other) {
- if (!(other instanceof UndefinedLiteral)) {
- return false;
- }
- return true;
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(NumberLiteral node, Object other) {
- if (!(other instanceof NumberLiteral)) {
- return false;
- }
- NumberLiteral o = (NumberLiteral) other;
- return safeEquals(node.getToken(), o.getToken());
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(PackageDeclaration node, Object other) {
- if (!(other instanceof PackageDeclaration)) {
- return false;
- }
- PackageDeclaration o = (PackageDeclaration) other;
- if (node.getAST().apiLevel >= AST.JLS3) {
- if (!safeSubtreeMatch(node.getJavadoc(), o.getJavadoc())) {
- return false;
- }
- if (!safeSubtreeListMatch(node.annotations(), o.annotations())) {
- return false;
- }
- }
- return safeSubtreeMatch(node.getName(), o.getName());
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(ParenthesizedExpression node, Object other) {
- if (!(other instanceof ParenthesizedExpression)) {
- return false;
- }
- ParenthesizedExpression o = (ParenthesizedExpression) other;
- return safeSubtreeMatch(node.getExpression(), o.getExpression());
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(PostfixExpression node, Object other) {
- if (!(other instanceof PostfixExpression)) {
- return false;
- }
- PostfixExpression o = (PostfixExpression) other;
- return (
- node.getOperator().equals(o.getOperator())
- && safeSubtreeMatch(node.getOperand(), o.getOperand()));
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(PrefixExpression node, Object other) {
- if (!(other instanceof PrefixExpression)) {
- return false;
- }
- PrefixExpression o = (PrefixExpression) other;
- return (
- node.getOperator().equals(o.getOperator())
- && safeSubtreeMatch(node.getOperand(), o.getOperand()));
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(PrimitiveType node, Object other) {
- if (!(other instanceof PrimitiveType)) {
- return false;
- }
- PrimitiveType o = (PrimitiveType) other;
- return (node.getPrimitiveTypeCode() == o.getPrimitiveTypeCode());
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(QualifiedName node, Object other) {
- if (!(other instanceof QualifiedName)) {
- return false;
- }
- QualifiedName o = (QualifiedName) other;
- return (
- safeSubtreeMatch(node.getQualifier(), o.getQualifier())
- && safeSubtreeMatch(node.getName(), o.getName()));
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(QualifiedType node, Object other) {
- if (!(other instanceof QualifiedType)) {
- return false;
- }
- QualifiedType o = (QualifiedType) other;
- return (
- safeSubtreeMatch(node.getQualifier(), o.getQualifier())
- && safeSubtreeMatch(node.getName(), o.getName()));
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(ReturnStatement node, Object other) {
- if (!(other instanceof ReturnStatement)) {
- return false;
- }
- ReturnStatement o = (ReturnStatement) other;
- return safeSubtreeMatch(node.getExpression(), o.getExpression());
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(SimpleName node, Object other) {
- if (!(other instanceof SimpleName)) {
- return false;
- }
- SimpleName o = (SimpleName) other;
- return node.getIdentifier().equals(o.getIdentifier());
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(SimpleType node, Object other) {
- if (!(other instanceof SimpleType)) {
- return false;
- }
- SimpleType o = (SimpleType) other;
- return safeSubtreeMatch(node.getName(), o.getName());
- }
-
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- * <p>
- * Note that extra array dimensions and the variable arity flag
- * are compared since they are both important parts of the declaration.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(SingleVariableDeclaration node, Object other) {
- if (!(other instanceof SingleVariableDeclaration)) {
- return false;
- }
- SingleVariableDeclaration o = (SingleVariableDeclaration) other;
- int level = node.getAST().apiLevel;
- if (level == AST.JLS2_INTERNAL) {
- if (node.getModifiers() != o.getModifiers()) {
- return false;
- }
- }
- if (level >= AST.JLS3) {
- if (!safeSubtreeListMatch(node.modifiers(), o.modifiers())) {
- return false;
- }
- if (node.isVarargs() != o.isVarargs()) {
- return false;
- }
- }
- return
- safeSubtreeMatch(node.getType(), o.getType())
- && safeSubtreeMatch(node.getName(), o.getName())
- && node.getExtraDimensions() == o.getExtraDimensions()
- && safeSubtreeMatch(node.getInitializer(), o.getInitializer());
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(StringLiteral node, Object other) {
- if (!(other instanceof StringLiteral)) {
- return false;
- }
- StringLiteral o = (StringLiteral) other;
- return safeEquals(node.getEscapedValue(), o.getEscapedValue());
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(SuperConstructorInvocation node, Object other) {
- if (!(other instanceof SuperConstructorInvocation)) {
- return false;
- }
- SuperConstructorInvocation o = (SuperConstructorInvocation) other;
- if (node.getAST().apiLevel >= AST.JLS3) {
- if (!safeSubtreeListMatch(node.typeArguments(), o.typeArguments())) {
- return false;
- }
- }
- return (
- safeSubtreeMatch(node.getExpression(), o.getExpression())
- && safeSubtreeListMatch(node.arguments(), o.arguments()));
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(SuperFieldAccess node, Object other) {
- if (!(other instanceof SuperFieldAccess)) {
- return false;
- }
- SuperFieldAccess o = (SuperFieldAccess) other;
- return (
- safeSubtreeMatch(node.getName(), o.getName())
- && safeSubtreeMatch(node.getQualifier(), o.getQualifier()));
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(SuperMethodInvocation node, Object other) {
- if (!(other instanceof SuperMethodInvocation)) {
- return false;
- }
- SuperMethodInvocation o = (SuperMethodInvocation) other;
- if (node.getAST().apiLevel >= AST.JLS3) {
- if (!safeSubtreeListMatch(node.typeArguments(), o.typeArguments())) {
- return false;
- }
- }
- return (
- safeSubtreeMatch(node.getQualifier(), o.getQualifier())
- && safeSubtreeMatch(node.getName(), o.getName())
- && safeSubtreeListMatch(node.arguments(), o.arguments()));
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(SwitchCase node, Object other) {
- if (!(other instanceof SwitchCase)) {
- return false;
- }
- SwitchCase o = (SwitchCase) other;
- return safeSubtreeMatch(node.getExpression(), o.getExpression());
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(SwitchStatement node, Object other) {
- if (!(other instanceof SwitchStatement)) {
- return false;
- }
- SwitchStatement o = (SwitchStatement) other;
- return (
- safeSubtreeMatch(node.getExpression(), o.getExpression())
- && safeSubtreeListMatch(node.statements(), o.statements()));
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(TagElement node, Object other) {
- if (!(other instanceof TagElement)) {
- return false;
- }
- TagElement o = (TagElement) other;
- return (
- safeEquals(node.getTagName(), o.getTagName())
- && safeSubtreeListMatch(node.fragments(), o.fragments()));
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(TextElement node, Object other) {
- if (!(other instanceof TextElement)) {
- return false;
- }
- TextElement o = (TextElement) other;
- return safeEquals(node.getText(), o.getText());
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(ThisExpression node, Object other) {
- if (!(other instanceof ThisExpression)) {
- return false;
- }
- ThisExpression o = (ThisExpression) other;
- return safeSubtreeMatch(node.getQualifier(), o.getQualifier());
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(ThrowStatement node, Object other) {
- if (!(other instanceof ThrowStatement)) {
- return false;
- }
- ThrowStatement o = (ThrowStatement) other;
- return safeSubtreeMatch(node.getExpression(), o.getExpression());
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(TryStatement node, Object other) {
- if (!(other instanceof TryStatement)) {
- return false;
- }
- TryStatement o = (TryStatement) other;
- return (
- safeSubtreeMatch(node.getBody(), o.getBody())
- && safeSubtreeListMatch(node.catchClauses(), o.catchClauses())
- && safeSubtreeMatch(node.getFinally(), o.getFinally()));
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(TypeDeclaration node, Object other) {
- if (!(other instanceof TypeDeclaration)) {
- return false;
- }
- TypeDeclaration o = (TypeDeclaration) other;
- int level = node.getAST().apiLevel;
- if (level == AST.JLS2_INTERNAL) {
- if (node.getModifiers() != o.getModifiers()) {
- return false;
- }
- if (!safeSubtreeMatch(node.internalGetSuperclass(), o.internalGetSuperclass())) {
- return false;
- }
- }
- if (level >= AST.JLS3) {
- if (!safeSubtreeListMatch(node.modifiers(), o.modifiers())) {
- return false;
- }
- if (!safeSubtreeMatch(node.getSuperclassType(), o.getSuperclassType())) {
- return false;
- }
- }
- return (
- safeSubtreeMatch(node.getJavadoc(), o.getJavadoc())
- && safeSubtreeMatch(node.getName(), o.getName())
- && safeSubtreeListMatch(node.bodyDeclarations(), o.bodyDeclarations()));
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(TypeDeclarationStatement node, Object other) {
- if (!(other instanceof TypeDeclarationStatement)) {
- return false;
- }
- TypeDeclarationStatement o = (TypeDeclarationStatement) other;
- return safeSubtreeMatch(node.getDeclaration(), o.getDeclaration());
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(TypeLiteral node, Object other) {
- if (!(other instanceof TypeLiteral)) {
- return false;
- }
- TypeLiteral o = (TypeLiteral) other;
- return safeSubtreeMatch(node.getType(), o.getType());
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(VariableDeclarationExpression node, Object other) {
- if (!(other instanceof VariableDeclarationExpression)) {
- return false;
- }
- VariableDeclarationExpression o = (VariableDeclarationExpression) other;
- int level = node.getAST().apiLevel;
- if (level == AST.JLS2_INTERNAL) {
- if (node.getModifiers() != o.getModifiers()) {
- return false;
- }
- }
- if (level >= AST.JLS3) {
- if (!safeSubtreeListMatch(node.modifiers(), o.modifiers())) {
- return false;
- }
- }
- return safeSubtreeMatch(node.getType(), o.getType())
- && safeSubtreeListMatch(node.fragments(), o.fragments());
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- * <p>
- * Note that extra array dimensions are compared since they are an
- * important part of the type of the variable.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(VariableDeclarationFragment node, Object other) {
- if (!(other instanceof VariableDeclarationFragment)) {
- return false;
- }
- VariableDeclarationFragment o = (VariableDeclarationFragment) other;
- return safeSubtreeMatch(node.getName(), o.getName())
- && node.getExtraDimensions() == o.getExtraDimensions()
- && safeSubtreeMatch(node.getInitializer(), o.getInitializer());
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(VariableDeclarationStatement node, Object other) {
- if (!(other instanceof VariableDeclarationStatement)) {
- return false;
- }
- VariableDeclarationStatement o = (VariableDeclarationStatement) other;
- int level = node.getAST().apiLevel;
- if (level == AST.JLS2_INTERNAL) {
- if (node.getModifiers() != o.getModifiers()) {
- return false;
- }
- }
- if (level >= AST.JLS3) {
- if (!safeSubtreeListMatch(node.modifiers(), o.modifiers())) {
- return false;
- }
- }
- return safeSubtreeMatch(node.getType(), o.getType())
- && safeSubtreeListMatch(node.fragments(), o.fragments());
- }
-
- /**
- * Returns whether the given node and the other object match.
- * <p>
- * The default implementation provided by this class tests whether the
- * other object is a node of the same type with structurally isomorphic
- * child subtrees. Subclasses may override this method as needed.
- * </p>
- *
- * @param node the node
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match or the other object has a
- * different node type or is <code>null</code>
- */
- public boolean match(WhileStatement node, Object other) {
- if (!(other instanceof WhileStatement)) {
- return false;
- }
- WhileStatement o = (WhileStatement) other;
- return (
- safeSubtreeMatch(node.getExpression(), o.getExpression())
- && safeSubtreeMatch(node.getBody(), o.getBody()));
- }
-
- public boolean match(WithStatement node, Object other) {
- if (!(other instanceof WithStatement)) {
- return false;
- }
- WithStatement o = (WithStatement) other;
- return (
- safeSubtreeMatch(node.getExpression(), o.getExpression())
- && safeSubtreeMatch(node.getBody(), o.getBody()));
- }
-
- public boolean match(ObjectLiteral node, Object other) {
- if (!(other instanceof ObjectLiteral)) {
- return false;
- }
- ObjectLiteral o = (ObjectLiteral) other;
- return safeSubtreeListMatch(node.fields(), o.fields());
- }
-
- public boolean match(ObjectLiteralField node, Object other) {
- if (!(other instanceof ObjectLiteralField)) {
- return false;
- }
- ObjectLiteralField o = (ObjectLiteralField) other;
- return safeSubtreeMatch(node.getFieldName(), o.getFieldName())
- && safeSubtreeMatch(node.getInitializer(), o.getInitializer());
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ASTNode.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ASTNode.java
deleted file mode 100644
index 2c7b0b1a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ASTNode.java
+++ /dev/null
@@ -1,2635 +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
- * bug 227489 - Etienne Pfister <epfister@hsr.ch>
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.dom;
-
-import java.util.AbstractList;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Abstract superclass of all Abstract Syntax Tree (AST) node types.
- * <p>
- * An AST node represents a JavaScript source code construct, such
- * as a name, type, expression, statement, or declaration.
- * </p>
- * <p>
- * Each AST node belongs to a unique AST instance, called the owning AST.
- * The children of an AST node always have the same owner as their parent node.
- * If a node from one AST is to be added to a different AST, the subtree must
- * be cloned first to ensure that the added nodes have the correct owning AST.
- * </p>
- * <p>
- * When an AST node is part of an AST, it has a unique parent node.
- * Clients can navigate upwards, from child to parent, as well as downwards,
- * from parent to child. Newly created nodes are unparented. When an
- * unparented node is set as a child of a node (using a
- * <code>set<i>CHILD</i></code> method), its parent link is set automatically
- * and the parent link of the former child is set to <code>null</code>.
- * For nodes with properties that include a list of children (for example,
- * <code>Block</code> whose <code>statements</code> property is a list
- * of statements), adding or removing an element to/for the list property
- * automatically updates the parent links. These lists support the
- * <code>List.set</code> method; however, the constraint that the same
- * node cannot appear more than once means that this method cannot be used
- * to swap elements without first removing the node.
- * </p>
- * <p>
- * ASTs must not contain cycles. All operations that could create a cycle
- * detect this possibility and fail.
- * </p>
- * <p>
- * ASTs do not contain "holes" (missing subtrees). If a node is required to
- * have a certain property, a syntactically plausible initial value is
- * always supplied.
- * </p>
- * <p>
- * The hierarchy of AST node types has some convenient groupings marked
- * by abstract superclasses:
- * <ul>
- * <li>expressions - <code>Expression</code></li>
- * <li>names - <code>Name</code> (a sub-kind of expression)</li>
- * <li>statements - <code>Statement</code></li>
- * <li>types - <code>Type</code></li>
- * <li>type body declarations - <code>BodyDeclaration</code></li>
- * </ul>
- * </p>
- * <p>
- * Abstract syntax trees may be hand constructed by clients, using the
- * <code>new<i>TYPE</i></code> factory methods (see <code>AST</code>) to
- * create new nodes, and the various <code>set<i>CHILD</i></code> methods
- * to connect them together.
- * </p>
- * <p>
- * The class {@link ASTParser} parses a string
- * containing a JavaScript source code and returns an abstract syntax tree
- * for it. The resulting nodes carry source ranges relating the node back to
- * the original source characters. The source range covers the construct
- * as a whole.
- * </p>
- * <p>
- * Each AST node carries bit flags, which may convey additional information about
- * the node. For instance, the parser uses a flag to indicate a syntax error.
- * Newly created nodes have no flags set.
- * </p>
- * <p>
- * Each AST node is capable of carrying an open-ended collection of
- * client-defined properties. Newly created nodes have none.
- * <code>getProperty</code> and <code>setProperty</code> are used to access
- * these properties.
- * </p>
- * <p>
- * AST nodes are thread-safe for readers provided there are no active writers.
- * If one thread is modifying an AST, including creating new nodes or cloning
- * existing ones, it is <b>not</b> safe for another thread to read, visit,
- * write, create, or clone <em>any</em> of the nodes on the same AST.
- * When synchronization is required, consider using the common AST
- * object that owns the node; that is, use
- * <code>synchronize (node.getAST()) {...}</code>.
- * </p>
- * <p>
- * ASTs also support the visitor pattern; see the class <code>ASTVisitor</code>
- * for details.
- * </p>
- * <p>
- * JavaScript units created by <code>ASTParser</code> from a
- * source document can be serialized after arbitrary modifications
- * with minimal loss of original formatting. See
- * {@link JavaScriptUnit#recordModifications()} for details.
- * See also {@link org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite} for
- * an alternative way to describe and serialize changes to a
- * read-only AST.
- * </p>
- * This class is not intended to be subclassed by clients.
- *
- * @see ASTParser
- * @see ASTVisitor
- *
- * 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 ASTNode {
- /*
- * INSTRUCTIONS FOR ADDING NEW CONCRETE AST NODE TYPES
- *
- * There are several things that need to be changed when a
- * new concrete AST node type (call it "FooBar"):
- *
- * 1. Create the FooBar AST node type class.
- * The most effective way to do this is to copy a similar
- * existing concrete node class to get a template that
- * includes all the framework methods that must be implemented.
- *
- * 2. Add node type constant ASTNode.FOO_BAR.
- * Node constants are numbered consecutively. Add the
- * constant after the existing ones.
- *
- * 3. Add entry to ASTNode.nodeClassForType(int).
- *
- * 4. Add AST.newFooBar() factory method.
- *
- * 5. Add ASTVisitor.visit(FooBar) and endVisit(FooBar) methods.
- *
- * 6. Add ASTMatcher.match(FooBar,Object) method.
- *
- * 7. Ensure that SimpleName.isDeclaration() covers FooBar
- * nodes if required.
- *
- * 8. Add NaiveASTFlattener.visit(FooBar) method to illustrate
- * how these nodes should be serialized.
- *
- * 9. Update the AST test suites.
- *
- * The next steps are to update AST.parse* to start generating
- * the new type of nodes, and ASTRewrite to serialize them back out.
- */
-
- /**
- * Node type constant indicating a node of type
- * <code>AnonymousClassDeclaration</code>.
- * @see AnonymousClassDeclaration
- */
- public static final int ANONYMOUS_CLASS_DECLARATION = 1;
-
- /**
- * Node type constant indicating a node of type
- * <code>ArrayAccess</code>.
- * @see ArrayAccess
- */
- public static final int ARRAY_ACCESS = 2;
-
- /**
- * Node type constant indicating a node of type
- * <code>ArrayCreation</code>.
- * @see ArrayCreation
- */
- public static final int ARRAY_CREATION = 3;
-
- /**
- * Node type constant indicating a node of type
- * <code>ArrayInitializer</code>.
- * @see ArrayInitializer
- */
- public static final int ARRAY_INITIALIZER = 4;
-
- /**
- * Node type constant indicating a node of type
- * <code>ArrayType</code>.
- * @see ArrayType
- */
- public static final int ARRAY_TYPE = 5;
-
- /**
- * Node type constant indicating a node of type
- * <code>Assignment</code>.
- * @see Assignment
- */
- public static final int ASSIGNMENT = 7;
-
- /**
- * Node type constant indicating a node of type
- * <code>Block</code>.
- * @see Block
- */
- public static final int BLOCK = 8;
-
- /**
- * Node type constant indicating a node of type
- * <code>BooleanLiteral</code>.
- * @see BooleanLiteral
- */
- public static final int BOOLEAN_LITERAL = 9;
-
- /**
- * Node type constant indicating a node of type
- * <code>BreakStatement</code>.
- * @see BreakStatement
- */
- public static final int BREAK_STATEMENT = 10;
-
- /**
- * Node type constant indicating a node of type
- * <code>CatchClause</code>.
- * @see CatchClause
- */
- public static final int CATCH_CLAUSE = 12;
-
- /**
- * Node type constant indicating a node of type
- * <code>CharacterLiteral</code>.
- * @see CharacterLiteral
- */
- public static final int CHARACTER_LITERAL = 13;
-
- /**
- * Node type constant indicating a node of type
- * <code>ClassInstanceCreation</code>.
- * @see ClassInstanceCreation
- */
- public static final int CLASS_INSTANCE_CREATION = 14;
-
- /**
- * Node type constant indicating a node of type
- * <code>JavaScriptUnit</code>.
- * @see JavaScriptUnit
- */
- public static final int JAVASCRIPT_UNIT = 15;
-
- /**
- * Node type constant indicating a node of type
- * <code>ConditionalExpression</code>.
- * @see ConditionalExpression
- */
- public static final int CONDITIONAL_EXPRESSION = 16;
-
- /**
- * Node type constant indicating a node of type
- * <code>ConstructorInvocation</code>.
- * @see ConstructorInvocation
- */
- public static final int CONSTRUCTOR_INVOCATION = 17;
-
- /**
- * Node type constant indicating a node of type
- * <code>ContinueStatement</code>.
- * @see ContinueStatement
- */
- public static final int CONTINUE_STATEMENT = 18;
-
- /**
- * Node type constant indicating a node of type
- * <code>DoStatement</code>.
- * @see DoStatement
- */
- public static final int DO_STATEMENT = 19;
-
- /**
- * Node type constant indicating a node of type
- * <code>EmptyStatement</code>.
- * @see EmptyStatement
- */
- public static final int EMPTY_STATEMENT = 20;
-
- /**
- * Node type constant indicating a node of type
- * <code>ExpressionStatement</code>.
- * @see ExpressionStatement
- */
- public static final int EXPRESSION_STATEMENT = 21;
-
- /**
- * Node type constant indicating a node of type
- * <code>FieldAccess</code>.
- * @see FieldAccess
- */
- public static final int FIELD_ACCESS = 22;
-
- /**
- * Node type constant indicating a node of type
- * <code>FieldDeclaration</code>.
- * @see FieldDeclaration
- */
- public static final int FIELD_DECLARATION = 23;
-
- /**
- * Node type constant indicating a node of type
- * <code>ForStatement</code>.
- * @see ForStatement
- */
- public static final int FOR_STATEMENT = 24;
-
- /**
- * Node type constant indicating a node of type
- * <code>IfStatement</code>.
- * @see IfStatement
- */
- public static final int IF_STATEMENT = 25;
-
- /**
- * Node type constant indicating a node of type
- * <code>ImportDeclaration</code>.
- * @see ImportDeclaration
- */
- public static final int IMPORT_DECLARATION = 26;
-
- /**
- * Node type constant indicating a node of type
- * <code>InfixExpression</code>.
- * @see InfixExpression
- */
- public static final int INFIX_EXPRESSION = 27;
-
- /**
- * Node type constant indicating a node of type
- * <code>Initializer</code>.
- * @see Initializer
- */
- public static final int INITIALIZER = 28;
-
- /**
- * Node type constant indicating a node of type
- * <code>Javadoc</code>.
- * @see JSdoc
- */
- public static final int JSDOC = 29;
-
- /**
- * Node type constant indicating a node of type
- * <code>LabeledStatement</code>.
- * @see LabeledStatement
- */
- public static final int LABELED_STATEMENT = 30;
-
- /**
- * Node type constant indicating a node of type
- * <code>FunctionDeclaration</code>.
- * @see FunctionDeclaration
- */
- public static final int FUNCTION_DECLARATION = 31;
-
- /**
- * Node type constant indicating a node of type
- * <code>FunctionInvocation</code>.
- * @see FunctionInvocation
- */
- public static final int FUNCTION_INVOCATION = 32;
-
- /**
- * Node type constant indicating a node of type
- * <code>NullLiteral</code>.
- * @see NullLiteral
- */
- public static final int NULL_LITERAL = 33;
-
- /**
- * Node type constant indicating a node of type
- * <code>NumberLiteral</code>.
- * @see NumberLiteral
- */
- public static final int NUMBER_LITERAL = 34;
-
- /**
- * Node type constant indicating a node of type
- * <code>PackageDeclaration</code>.
- * @see PackageDeclaration
- */
- public static final int PACKAGE_DECLARATION = 35;
-
- /**
- * Node type constant indicating a node of type
- * <code>ParenthesizedExpression</code>.
- * @see ParenthesizedExpression
- */
- public static final int PARENTHESIZED_EXPRESSION = 36;
-
- /**
- * Node type constant indicating a node of type
- * <code>PostfixExpression</code>.
- * @see PostfixExpression
- */
- public static final int POSTFIX_EXPRESSION = 37;
-
- /**
- * Node type constant indicating a node of type
- * <code>PrefixExpression</code>.
- * @see PrefixExpression
- */
- public static final int PREFIX_EXPRESSION = 38;
-
- /**
- * Node type constant indicating a node of type
- * <code>PrimitiveType</code>.
- * @see PrimitiveType
- */
- public static final int PRIMITIVE_TYPE = 39;
-
- /**
- * Node type constant indicating a node of type
- * <code>QualifiedName</code>.
- * @see QualifiedName
- */
- public static final int QUALIFIED_NAME = 40;
-
- /**
- * Node type constant indicating a node of type
- * <code>ReturnStatement</code>.
- * @see ReturnStatement
- */
- public static final int RETURN_STATEMENT = 41;
-
- /**
- * Node type constant indicating a node of type
- * <code>SimpleName</code>.
- * @see SimpleName
- */
- public static final int SIMPLE_NAME = 42;
-
- /**
- * Node type constant indicating a node of type
- * <code>SimpleType</code>.
- * @see SimpleType
- */
- public static final int SIMPLE_TYPE = 43;
-
- /**
- * Node type constant indicating a node of type
- * <code>SingleVariableDeclaration</code>.
- * @see SingleVariableDeclaration
- */
- public static final int SINGLE_VARIABLE_DECLARATION = 44;
-
- /**
- * Node type constant indicating a node of type
- * <code>StringLiteral</code>.
- * @see StringLiteral
- */
- public static final int STRING_LITERAL = 45;
-
- /**
- * Node type constant indicating a node of type
- * <code>SuperConstructorInvocation</code>.
- * @see SuperConstructorInvocation
- */
- public static final int SUPER_CONSTRUCTOR_INVOCATION = 46;
-
- /**
- * Node type constant indicating a node of type
- * <code>SuperFieldAccess</code>.
- * @see SuperFieldAccess
- */
- public static final int SUPER_FIELD_ACCESS = 47;
-
- /**
- * Node type constant indicating a node of type
- * <code>SuperMethodInvocation</code>.
- * @see SuperMethodInvocation
- */
- public static final int SUPER_METHOD_INVOCATION = 48;
-
- /**
- * Node type constant indicating a node of type
- * <code>SwitchCase</code>.
- * @see SwitchCase
- */
- public static final int SWITCH_CASE = 49;
-
- /**
- * Node type constant indicating a node of type
- * <code>SwitchStatement</code>.
- * @see SwitchStatement
- */
- public static final int SWITCH_STATEMENT = 50;
-
- /**
- * Node type constant indicating a node of type
- * <code>ThisExpression</code>.
- * @see ThisExpression
- */
- public static final int THIS_EXPRESSION = 52;
-
- /**
- * Node type constant indicating a node of type
- * <code>ThrowStatement</code>.
- * @see ThrowStatement
- */
- public static final int THROW_STATEMENT = 53;
-
- /**
- * Node type constant indicating a node of type
- * <code>TryStatement</code>.
- * @see TryStatement
- */
- public static final int TRY_STATEMENT = 54;
-
- /**
- * Node type constant indicating a node of type
- * <code>TypeDeclaration</code>.
- * @see TypeDeclaration
- */
- public static final int TYPE_DECLARATION = 55;
-
- /**
- * Node type constant indicating a node of type
- * <code>TypeDeclarationStatement</code>.
- * @see TypeDeclarationStatement
- */
- public static final int TYPE_DECLARATION_STATEMENT = 56;
-
- /**
- * Node type constant indicating a node of type
- * <code>TypeLiteral</code>.
- * @see TypeLiteral
- */
- public static final int TYPE_LITERAL = 57;
-
- /**
- * Node type constant indicating a node of type
- * <code>VariableDeclarationExpression</code>.
- * @see VariableDeclarationExpression
- */
- public static final int VARIABLE_DECLARATION_EXPRESSION = 58;
-
- /**
- * Node type constant indicating a node of type
- * <code>VariableDeclarationFragment</code>.
- * @see VariableDeclarationFragment
- */
- public static final int VARIABLE_DECLARATION_FRAGMENT = 59;
-
- /**
- * Node type constant indicating a node of type
- * <code>VariableDeclarationStatement</code>.
- * @see VariableDeclarationStatement
- */
- public static final int VARIABLE_DECLARATION_STATEMENT = 60;
-
- /**
- * Node type constant indicating a node of type
- * <code>WhileStatement</code>.
- * @see WhileStatement
- */
- public static final int WHILE_STATEMENT = 61;
-
- /**
- * Node type constant indicating a node of type
- * <code>InstanceofExpression</code>.
- * @see InstanceofExpression
- */
- public static final int INSTANCEOF_EXPRESSION = 62;
-
- /**
- * Node type constant indicating a node of type
- * <code>LineComment</code>.
- * @see LineComment
- */
- public static final int LINE_COMMENT = 63;
-
- /**
- * Node type constant indicating a node of type
- * <code>BlockComment</code>.
- * @see BlockComment
- *
- */
- public static final int BLOCK_COMMENT = 64;
-
- /**
- * Node type constant indicating a node of type
- * <code>TagElement</code>.
- * @see TagElement
- *
- */
- public static final int TAG_ELEMENT = 65;
-
- /**
- * Node type constant indicating a node of type
- * <code>TextElement</code>.
- * @see TextElement
- *
- */
- public static final int TEXT_ELEMENT = 66;
-
- /**
- * Node type constant indicating a node of type
- * <code>MemberRef</code>.
- * @see MemberRef
- *
- */
- public static final int MEMBER_REF = 67;
-
- /**
- * Node type constant indicating a node of type
- * <code>FunctionRef</code>.
- * @see FunctionRef
- *
- */
- public static final int FUNCTION_REF = 68;
-
- /**
- * Node type constant indicating a node of type
- * <code>FunctionRefParameter</code>.
- * @see FunctionRefParameter
- *
- */
- public static final int FUNCTION_REF_PARAMETER = 69;
-
- /**
- * Node type constant indicating a node of type
- * <code>EnhancedForStatement</code>.
- * @see EnhancedForStatement
- *
- */
- public static final int ENHANCED_FOR_STATEMENT = 70;
-
- /**
- * Node type constant indicating a node of type
- * <code>QualifiedType</code>.
- * @see QualifiedType
- *
- */
- public static final int QUALIFIED_TYPE = 75;
-
-
- public static final int FOR_IN_STATEMENT = 83;
- public static final int FUNCTION_EXPRESSION = 84;
- public static final int OBJECT_LITERAL = 85;
- public static final int OBJECT_LITERAL_FIELD = 86;
- public static final int UNDEFINED_LITERAL = 87;
- public static final int REGULAR_EXPRESSION_LITERAL = 88;
- public static final int INFERRED_TYPE = 89;
- public static final int WITH_STATEMENT = 90;
- public static final int LIST_EXPRESSION = 91;
- public static final int EMPTY_EXPRESSION = 92;
-
-
-
-
-
- /**
- * Node type constant indicating a node of type
- * <code>Modifier</code>.
- * @see Modifier
- */
- public static final int MODIFIER = 100;
-
- /**
- * Returns the node class for the corresponding node type.
- *
- * @param nodeType AST node type
- * @return the corresponding <code>ASTNode</code> subclass
- * @exception IllegalArgumentException if <code>nodeType</code> is
- * not a legal AST node type
- * @see #getNodeType()
- */
- public static Class nodeClassForType(int nodeType) {
- switch (nodeType) {
- case ANONYMOUS_CLASS_DECLARATION :
- return AnonymousClassDeclaration.class;
- case ARRAY_ACCESS :
- return ArrayAccess.class;
- case ARRAY_CREATION :
- return ArrayCreation.class;
- case ARRAY_INITIALIZER :
- return ArrayInitializer.class;
- case ARRAY_TYPE :
- return ArrayType.class;
- case ASSIGNMENT :
- return Assignment.class;
- case BLOCK :
- return Block.class;
- case BLOCK_COMMENT :
- return BlockComment.class;
- case BOOLEAN_LITERAL :
- return BooleanLiteral.class;
- case BREAK_STATEMENT :
- return BreakStatement.class;
- case CATCH_CLAUSE :
- return CatchClause.class;
- case CHARACTER_LITERAL :
- return CharacterLiteral.class;
- case CLASS_INSTANCE_CREATION :
- return ClassInstanceCreation.class;
- case JAVASCRIPT_UNIT :
- return JavaScriptUnit.class;
- case CONDITIONAL_EXPRESSION :
- return ConditionalExpression.class;
- case CONSTRUCTOR_INVOCATION :
- return ConstructorInvocation.class;
- case CONTINUE_STATEMENT :
- return ContinueStatement.class;
- case DO_STATEMENT :
- return DoStatement.class;
- case EMPTY_STATEMENT :
- return EmptyStatement.class;
- case ENHANCED_FOR_STATEMENT :
- return EnhancedForStatement.class;
- case EXPRESSION_STATEMENT :
- return ExpressionStatement.class;
- case FIELD_ACCESS :
- return FieldAccess.class;
- case FIELD_DECLARATION :
- return FieldDeclaration.class;
- case FOR_STATEMENT :
- return ForStatement.class;
- case FOR_IN_STATEMENT:
- return ForInStatement.class;
- case IF_STATEMENT :
- return IfStatement.class;
- case IMPORT_DECLARATION :
- return ImportDeclaration.class;
- case INFIX_EXPRESSION :
- return InfixExpression.class;
- case INITIALIZER :
- return Initializer.class;
- case INSTANCEOF_EXPRESSION :
- return InstanceofExpression.class;
- case JSDOC :
- return JSdoc.class;
- case LABELED_STATEMENT :
- return LabeledStatement.class;
- case LINE_COMMENT :
- return LineComment.class;
- case MEMBER_REF :
- return MemberRef.class;
- case FUNCTION_DECLARATION :
- return FunctionDeclaration.class;
- case FUNCTION_INVOCATION :
- return FunctionInvocation.class;
- case FUNCTION_REF :
- return FunctionRef.class;
- case FUNCTION_REF_PARAMETER :
- return FunctionRefParameter.class;
- case MODIFIER :
- return Modifier.class;
- case NULL_LITERAL :
- return NullLiteral.class;
- case UNDEFINED_LITERAL :
- return UndefinedLiteral.class;
- case NUMBER_LITERAL :
- return NumberLiteral.class;
- case PACKAGE_DECLARATION :
- return PackageDeclaration.class;
- case PARENTHESIZED_EXPRESSION :
- return ParenthesizedExpression.class;
- case POSTFIX_EXPRESSION :
- return PostfixExpression.class;
- case PREFIX_EXPRESSION :
- return PrefixExpression.class;
- case PRIMITIVE_TYPE :
- return PrimitiveType.class;
- case QUALIFIED_NAME :
- return QualifiedName.class;
- case QUALIFIED_TYPE :
- return QualifiedType.class;
- case RETURN_STATEMENT :
- return ReturnStatement.class;
- case SIMPLE_NAME :
- return SimpleName.class;
- case SIMPLE_TYPE :
- return SimpleType.class;
- case SINGLE_VARIABLE_DECLARATION :
- return SingleVariableDeclaration.class;
- case STRING_LITERAL :
- return StringLiteral.class;
- case SUPER_CONSTRUCTOR_INVOCATION :
- return SuperConstructorInvocation.class;
- case SUPER_FIELD_ACCESS :
- return SuperFieldAccess.class;
- case SUPER_METHOD_INVOCATION :
- return SuperMethodInvocation.class;
- case SWITCH_CASE:
- return SwitchCase.class;
- case SWITCH_STATEMENT :
- return SwitchStatement.class;
- case TAG_ELEMENT :
- return TagElement.class;
- case TEXT_ELEMENT :
- return TextElement.class;
- case THIS_EXPRESSION :
- return ThisExpression.class;
- case THROW_STATEMENT :
- return ThrowStatement.class;
- case TRY_STATEMENT :
- return TryStatement.class;
- case TYPE_DECLARATION :
- return TypeDeclaration.class;
- case TYPE_DECLARATION_STATEMENT :
- return TypeDeclarationStatement.class;
- case TYPE_LITERAL :
- return TypeLiteral.class;
- case VARIABLE_DECLARATION_EXPRESSION :
- return VariableDeclarationExpression.class;
- case VARIABLE_DECLARATION_FRAGMENT :
- return VariableDeclarationFragment.class;
- case VARIABLE_DECLARATION_STATEMENT :
- return VariableDeclarationStatement.class;
- case WHILE_STATEMENT :
- return WhileStatement.class;
- case WITH_STATEMENT :
- return WithStatement.class;
- case OBJECT_LITERAL :
- return ObjectLiteral.class;
- case OBJECT_LITERAL_FIELD :
- return ObjectLiteralField.class;
- case FUNCTION_EXPRESSION :
- return FunctionExpression.class;
- case REGULAR_EXPRESSION_LITERAL :
- return RegularExpressionLiteral.class;
- case LIST_EXPRESSION :
- return ListExpression.class;
- }
- throw new IllegalArgumentException();
- }
-
- /**
- * Owning AST.
- * <p>
- * N.B. This ia a private field, but declared as package-visible
- * for more efficient access from inner classes.
- * </p>
- */
- final AST ast;
-
- /**
- * Parent AST node, or <code>null</code> if this node is a root.
- * Initially <code>null</code>.
- */
- private ASTNode parent = null;
-
- /**
- * An unmodifiable empty map (used to implement <code>properties()</code>).
- */
- private static final Map UNMODIFIABLE_EMPTY_MAP
- = Collections.unmodifiableMap(new HashMap(1));
-
- /**
- * Primary field used in representing node properties efficiently.
- * If <code>null</code>, this node has no properties.
- * If a <code>String</code>, this is the name of this node's sole property,
- * and <code>property2</code> contains its value.
- * If a <code>HashMap</code>, this is the table of property name-value
- * mappings; <code>property2</code>, if non-null is its unmodifiable
- * equivalent.
- * Initially <code>null</code>.
- *
- * @see #property2
- */
- private Object property1 = null;
-
- /**
- * Auxillary field used in representing node properties efficiently.
- *
- * @see #property1
- */
- private Object property2 = null;
-
- /**
- * A character index into the original source string,
- * or <code>-1</code> if no source position information is available
- * for this node; <code>-1</code> by default.
- */
- private int startPosition = -1;
-
- /**
- * A character length, or <code>0</code> if no source position
- * information is recorded for this node; <code>0</code> by default.
- */
- private int length = 0;
-
- /**
- * Flag constant (bit mask, value 1) indicating that there is something
- * not quite right with this AST node.
- * <p>
- * The standard parser (<code>ASTParser</code>) sets this
- * flag on a node to indicate a syntax error detected in the vicinity.
- * </p>
- */
- public static final int MALFORMED = 1;
-
- /**
- * Flag constant (bit mask, value 2) indicating that this is a node
- * that was created by the parser (as opposed to one created by another
- * party).
- * <p>
- * The standard parser (<code>ASTParser</code>) sets this
- * flag on the nodes it creates.
- * </p>
- *
- */
- public static final int ORIGINAL = 2;
-
- /**
- * Flag constant (bit mask, value 4) indicating that this node
- * is unmodifiable. When a node is marked unmodifiable, the
- * following operations result in a runtime exception:
- * <ul>
- * <li>Change a simple property of this node.</li>
- * <li>Add or remove a child node from this node.</li>
- * <li>Parent (or reparent) this node.</li>
- * </ul>
- * <p>
- * The standard parser (<code>ASTParser</code>) does not set
- * this flag on the nodes it creates. However, clients may set
- * this flag on a node to prevent further modification of the
- * its structural properties.
- * </p>
- */
- public static final int PROTECT = 4;
-
- /**
- * Flag constant (bit mask, value 8) indicating that this node
- * or a part of this node is recovered from source that contains
- * a syntax error detected in the vicinity.
- * <p>
- * The standard parser (<code>ASTParser</code>) sets this
- * flag on a node to indicate a recovered node.
- * </p>
- */
- public static final int RECOVERED = 8;
-
- /**
- * int containing the node type in the top 16 bits and
- * flags in the bottom 16 bits; none set by default.
- * <p>
- * N.B. This is a private field, but declared as package-visible
- * for more efficient access from inner classes.
- * </p>
- *
- * @see #MALFORMED
- */
- int typeAndFlags = 0;
-
- /**
- * Property of parent in which this node is a child, or <code>null</code>
- * if this node is a root. Initially <code>null</code>.
- *
- * @see #getLocationInParent
- */
- private StructuralPropertyDescriptor location = null;
-
- /** Internal convenience constant indicating that there is definite risk of cycles.
- */
- static final boolean CYCLE_RISK = true;
-
- /** Internal convenience constant indicating that there is no risk of cycles.
- */
- static final boolean NO_CYCLE_RISK = false;
-
- /** Internal convenience constant indicating that a structural property is mandatory.
- */
- static final boolean MANDATORY = true;
-
- /** Internal convenience constant indicating that a structural property is optional.
- */
- static final boolean OPTIONAL = false;
-
- /**
- * A specialized implementation of a list of ASTNodes. The
- * implementation is based on an ArrayList.
- */
- class NodeList extends AbstractList {
-
- /**
- * The underlying list in which the nodes of this list are
- * stored (element type: <code>ASTNode</code>).
- * <p>
- * Be stingy on storage - assume that list will be empty.
- * </p>
- * <p>
- * This field declared default visibility (rather than private)
- * so that accesses from <code>NodeList.Cursor</code> do not require
- * a synthetic accessor method.
- * </p>
- */
- ArrayList store = new ArrayList(0);
-
- /**
- * The property descriptor for this list.
- */
- ChildListPropertyDescriptor propertyDescriptor;
-
- /**
- * A cursor for iterating over the elements of the list.
- * Does not lose its position if the list is changed during
- * the iteration.
- */
- class Cursor implements Iterator {
- /**
- * The position of the cursor between elements. If the value
- * is N, then the cursor sits between the element at positions
- * N-1 and N. Initially just before the first element of the
- * list.
- */
- private int position = 0;
-
- /* (non-Javadoc)
- * Method declared on <code>Iterator</code>.
- */
- public boolean hasNext() {
- return this.position < NodeList.this.store.size();
- }
-
- /* (non-Javadoc)
- * Method declared on <code>Iterator</code>.
- */
- public Object next() {
- Object result = NodeList.this.store.get(this.position);
- this.position++;
- return result;
- }
-
- /* (non-Javadoc)
- * Method declared on <code>Iterator</code>.
- */
- public void remove() {
- throw new UnsupportedOperationException();
- }
-
- /**
- * Adjusts this cursor to accomodate an add/remove at the given
- * index.
- *
- * @param index the position at which the element was added
- * or removed
- * @param delta +1 for add, and -1 for remove
- */
- void update(int index, int delta) {
- if (this.position > index) {
- // the cursor has passed the added or removed element
- this.position += delta;
- }
- }
- }
-
- /**
- * A list of currently active cursors (element type:
- * <code>Cursor</code>), or <code>null</code> if there are no
- * active cursors.
- * <p>
- * It is important for storage considerations to maintain the
- * null-means-empty invariant; otherwise, every NodeList instance
- * will waste a lot of space. A cursor is needed only for the duration
- * of a visit to the child nodes. Under normal circumstances, only a
- * single cursor is needed; multiple cursors are only required if there
- * are multiple visits going on at the same time.
- * </p>
- */
- private List cursors = null;
-
- /**
- * Creates a new empty list of nodes owned by this node.
- * This node will be the common parent of all nodes added to
- * this list.
- *
- * @param property the property descriptor
- */
- NodeList(ChildListPropertyDescriptor property) {
- super();
- this.propertyDescriptor = property;
- }
-
- /* (non-javadoc)
- * @see java.util.AbstractCollection#size()
- */
- public int size() {
- return this.store.size();
- }
-
- /* (non-javadoc)
- * @see AbstractList#get(int)
- */
- public Object get(int index) {
- return this.store.get(index);
- }
-
- /* (non-javadoc)
- * @see List#set(int, java.lang.Object)
- */
- public Object set(int index, Object element) {
- if (element == null) {
- throw new IllegalArgumentException();
- }
- if ((ASTNode.this.typeAndFlags & PROTECT) != 0) {
- // this node is protected => cannot gain or lose children
- throw new IllegalArgumentException("AST node cannot be modified"); //$NON-NLS-1$
- }
- // delink old child from parent, and link new child to parent
- ASTNode newChild = (ASTNode) element;
- ASTNode oldChild = (ASTNode) this.store.get(index);
- if (oldChild == newChild) {
- return oldChild;
- }
- if ((oldChild.typeAndFlags & PROTECT) != 0) {
- // old child is protected => cannot be unparented
- throw new IllegalArgumentException("AST node cannot be modified"); //$NON-NLS-1$
- }
- ASTNode.checkNewChild(ASTNode.this, newChild, this.propertyDescriptor.cycleRisk, this.propertyDescriptor.elementType);
- ASTNode.this.ast.preReplaceChildEvent(ASTNode.this, oldChild, newChild, this.propertyDescriptor);
-
- Object result = this.store.set(index, newChild);
- // n.b. setParent will call ast.modifying()
- oldChild.setParent(null, null);
- newChild.setParent(ASTNode.this, this.propertyDescriptor);
- ASTNode.this.ast.postReplaceChildEvent(ASTNode.this, oldChild, newChild, this.propertyDescriptor);
- return result;
- }
-
- /* (non-javadoc)
- * @see List#add(int, java.lang.Object)
- */
- public void add(int index, Object element) {
- if (element == null) {
- // http://bugs.eclipse.org/255538 - Very frequent IllegalArgumentException in JSDT
- // XXX: Workaround until we've gotten the AST corrected, silenty return
- return;
- //throw new IllegalArgumentException();
- }
- if ((ASTNode.this.typeAndFlags & PROTECT) != 0) {
- // this node is protected => cannot gain or lose children
- throw new IllegalArgumentException("AST node cannot be modified"); //$NON-NLS-1$
- }
- // link new child to parent
- ASTNode newChild = (ASTNode) element;
- ASTNode.checkNewChild(ASTNode.this, newChild, this.propertyDescriptor.cycleRisk, this.propertyDescriptor.elementType);
- ASTNode.this.ast.preAddChildEvent(ASTNode.this, newChild, this.propertyDescriptor);
-
-
- this.store.add(index, element);
- updateCursors(index, +1);
- // n.b. setParent will call ast.modifying()
- newChild.setParent(ASTNode.this, this.propertyDescriptor);
- ASTNode.this.ast.postAddChildEvent(ASTNode.this, newChild, this.propertyDescriptor);
- }
-
- /* (non-javadoc)
- * @see List#remove(int)
- */
- public Object remove(int index) {
- if ((ASTNode.this.typeAndFlags & PROTECT) != 0) {
- // this node is protected => cannot gain or lose children
- throw new IllegalArgumentException("AST node cannot be modified"); //$NON-NLS-1$
- }
- // delink old child from parent
- ASTNode oldChild = (ASTNode) this.store.get(index);
- if ((oldChild.typeAndFlags & PROTECT) != 0) {
- // old child is protected => cannot be unparented
- throw new IllegalArgumentException("AST node cannot be modified"); //$NON-NLS-1$
- }
-
- ASTNode.this.ast.preRemoveChildEvent(ASTNode.this, oldChild, this.propertyDescriptor);
- // n.b. setParent will call ast.modifying()
- oldChild.setParent(null, null);
- Object result = this.store.remove(index);
- updateCursors(index, -1);
- ASTNode.this.ast.postRemoveChildEvent(ASTNode.this, oldChild, this.propertyDescriptor);
- return result;
-
- }
-
- /**
- * Allocate a cursor to use for a visit. The client must call
- * <code>releaseCursor</code> when done.
- * <p>
- * This method is internally synchronized on this NodeList.
- * It is thread-safe to create a cursor.
- * </p>
- *
- * @return a new cursor positioned before the first element
- * of the list
- */
- Cursor newCursor() {
- synchronized (this) {
- // serialize cursor management on this NodeList
- if (this.cursors == null) {
- // convert null to empty list
- this.cursors = new ArrayList(1);
- }
- Cursor result = new Cursor();
- this.cursors.add(result);
- return result;
- }
- }
-
- /**
- * Releases the given cursor at the end of a visit.
- * <p>
- * This method is internally synchronized on this NodeList.
- * It is thread-safe to release a cursor.
- * </p>
- *
- * @param cursor the cursor
- */
- void releaseCursor(Cursor cursor) {
- synchronized (this) {
- // serialize cursor management on this NodeList
- this.cursors.remove(cursor);
- if (this.cursors.isEmpty()) {
- // important: convert empty list back to null
- // otherwise the node will hang on to needless junk
- this.cursors = null;
- }
- }
- }
-
- /**
- * Adjusts all cursors to accomodate an add/remove at the given
- * index.
- * <p>
- * This method is only used when the list is being modified.
- * The AST is not thread-safe if any of the clients are modifying it.
- * </p>
- *
- * @param index the position at which the element was added
- * or removed
- * @param delta +1 for add, and -1 for remove
- */
- private void updateCursors(int index, int delta) {
- if (this.cursors == null) {
- // there are no cursors to worry about
- return;
- }
- for (Iterator it = this.cursors.iterator(); it.hasNext(); ) {
- Cursor c = (Cursor) it.next();
- c.update(index, delta);
- }
- }
-
- /**
- * Returns an estimate of the memory footprint of this node list
- * instance in bytes.
- * <ul>
- * <li>1 object header for the NodeList instance</li>
- * <li>5 4-byte fields of the NodeList instance</li>
- * <li>0 for cursors since null unless walk in progress</li>
- * <li>1 object header for the ArrayList instance</li>
- * <li>2 4-byte fields of the ArrayList instance</li>
- * <li>1 object header for an Object[] instance</li>
- * <li>4 bytes in array for each element</li>
- * </ul>
- *
- * @return the size of this node list in bytes
- */
- int memSize() {
- int result = HEADERS + 5 * 4;
- result += HEADERS + 2 * 4;
- result += HEADERS + 4 * size();
- return result;
- }
-
- /**
- * Returns an estimate of the memory footprint in bytes of this node
- * list and all its subtrees.
- *
- * @return the size of this list of subtrees in bytes
- */
- int listSize() {
- int result = memSize();
- for (Iterator it = iterator(); it.hasNext(); ) {
- ASTNode child = (ASTNode) it.next();
- result += child.treeSize();
- }
- return result;
- }
- }
-
- /**
- * Creates a new AST node owned by the given AST. Once established,
- * the relationship between an AST node and its owning AST does not change
- * over the lifetime of the node. The new node has no parent node,
- * and no properties.
- * <p>
- * N.B. This constructor is package-private; all subclasses my be
- * declared in the same package; clients are unable to declare
- * additional subclasses.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- ASTNode(AST ast) {
- if (ast == null) {
- throw new IllegalArgumentException();
- }
-
- this.ast = ast;
- setNodeType(getNodeType0());
- setFlags(ast.getDefaultNodeFlag());
- // setFlags calls modifying();
- }
-
- /**
- * Returns this node's AST.
- * <p>
- * Note that the relationship between an AST node and its owing AST does
- * not change over the lifetime of a node.
- * </p>
- *
- * @return the AST that owns this node
- */
- public final AST getAST() {
- return this.ast;
- }
-
- /**
- * Returns this node's parent node, or <code>null</code> if this is the
- * root node.
- * <p>
- * Note that the relationship between an AST node and its parent node
- * may change over the lifetime of a node.
- * </p>
- *
- * @return the parent of this node, or <code>null</code> if none
- */
- public final ASTNode getParent() {
- return this.parent;
- }
-
- /**
- * Returns the location of this node within its parent,
- * or <code>null</code> if this is a root node.
- * <p>
- * <pre>
- * ASTNode node = ...;
- * ASTNode parent = node.getParent();
- * StructuralPropertyDescriptor location = node.getLocationInParent();
- * assert (parent != null) == (location != null);
- * if ((location != null) && location.isChildProperty())
- * assert parent.getStructuralProperty(location) == node;
- * if ((location != null) && location.isChildListProperty())
- * assert ((List) parent.getStructuralProperty(location)).contains(node);
- * </pre>
- * </p>
- * <p>
- * Note that the relationship between an AST node and its parent node
- * may change over the lifetime of a node.
- * </p>
- *
- * @return the location of this node in its parent,
- * or <code>null</code> if this node has no parent
- */
- public final StructuralPropertyDescriptor getLocationInParent() {
- return this.location;
- }
-
- /**
- * Returns the root node at or above this node; returns this node if
- * it is a root.
- *
- * @return the root node at or above this node
- */
- public final ASTNode getRoot() {
- ASTNode candidate = this;
- while (true) {
- ASTNode p = candidate.getParent();
- if (p == null) {
- // candidate has no parent - that's the guy
- return candidate;
- }
- candidate = p;
- }
- }
-
- /**
- * Returns the value of the given structural property for this node. The value
- * returned depends on the kind of property:
- * <ul>
- * <li>{@link SimplePropertyDescriptor} - the value of the given simple property,
- * or <code>null</code> if none; primitive values are "boxed"</li>
- * <li>{@link ChildPropertyDescriptor} - the child node (type <code>ASTNode</code>),
- * or <code>null</code> if none</li>
- * <li>{@link ChildListPropertyDescriptor} - the list (element type: {@link ASTNode})</li>
- * </ul>
- *
- * @param property the property
- * @return the value, or <code>null</code> if none
- * @exception RuntimeException if this node does not have the given property
- */
- public final Object getStructuralProperty(StructuralPropertyDescriptor property) {
- if (property instanceof SimplePropertyDescriptor) {
- SimplePropertyDescriptor p = (SimplePropertyDescriptor) property;
- if (p.getValueType() == int.class) {
- int result = internalGetSetIntProperty(p, true, 0);
- return new Integer(result);
- } else if (p.getValueType() == boolean.class) {
- boolean result = internalGetSetBooleanProperty(p, true, false);
- return Boolean.valueOf(result);
- } else {
- return internalGetSetObjectProperty(p, true, null);
- }
- }
- if (property instanceof ChildPropertyDescriptor) {
- return internalGetSetChildProperty((ChildPropertyDescriptor) property, true, null);
- }
- if (property instanceof ChildListPropertyDescriptor) {
- return internalGetChildListProperty((ChildListPropertyDescriptor) property);
- }
- throw new IllegalArgumentException();
- }
-
- /**
- * Sets the value of the given structural property for this node. The value
- * passed depends on the kind of property:
- * <ul>
- * <li>{@link SimplePropertyDescriptor} - the new value of the given simple property,
- * or <code>null</code> if none; primitive values are "boxed"</li>
- * <li>{@link ChildPropertyDescriptor} - the new child node (type <code>ASTNode</code>),
- * or <code>null</code> if none</li>
- * <li>{@link ChildListPropertyDescriptor} - not allowed</li>
- * </ul>
- *
- * @param property the property
- * @param value the property value
- * @exception RuntimeException if this node does not have the
- * given property, or if the given property cannot be set
- */
- public final void setStructuralProperty(StructuralPropertyDescriptor property, Object value) {
- if (property instanceof SimplePropertyDescriptor) {
- SimplePropertyDescriptor p = (SimplePropertyDescriptor) property;
- if (p.getValueType() == int.class) {
- int arg = ((Integer) value).intValue();
- internalGetSetIntProperty(p, false, arg);
- return;
- } else if (p.getValueType() == boolean.class) {
- boolean arg = ((Boolean) value).booleanValue();
- internalGetSetBooleanProperty(p, false, arg);
- return;
- } else {
- if (value == null && p.isMandatory()) {
- throw new IllegalArgumentException();
- }
- internalGetSetObjectProperty(p, false, value);
- return;
- }
- }
- if (property instanceof ChildPropertyDescriptor) {
- ChildPropertyDescriptor p = (ChildPropertyDescriptor) property;
- ASTNode child = (ASTNode) value;
- if (child == null && p.isMandatory()) {
- throw new IllegalArgumentException();
- }
- internalGetSetChildProperty(p, false, child);
- return;
- }
- if (property instanceof ChildListPropertyDescriptor) {
- throw new IllegalArgumentException("Cannot set the list of child list property"); //$NON-NLS-1$
- }
- }
-
- /**
- * Sets the value of the given int-valued property for this node.
- * The default implementation of this method throws an exception explaining
- * that this node does not have such a property. This method should be
- * extended in subclasses that have at leasy one simple property whose value
- * type is int.
- *
- * @param property the property
- * @param get <code>true</code> for a get operation, and
- * <code>false</code> for a set operation
- * @param value the new property value; ignored for get operations
- * @return the value; always returns
- * <code>0</code> for set operations
- * @exception RuntimeException if this node does not have the
- * given property, or if the given value cannot be set as specified
- *
- */
- int internalGetSetIntProperty(SimplePropertyDescriptor property, boolean get, int value) {
- throw new RuntimeException("Node does not have this property"); //$NON-NLS-1$
- }
-
- /**
- * Sets the value of the given boolean-valued property for this node.
- * The default implementation of this method throws an exception explaining
- * that this node does not have such a property. This method should be
- * extended in subclasses that have at leasy one simple property whose value
- * type is boolean.
- *
- * @param property the property
- * @param get <code>true</code> for a get operation, and
- * <code>false</code> for a set operation
- * @param value the new property value; ignored for get operations
- * @return the value; always returns
- * <code>false</code> for set operations
- * @exception RuntimeException if this node does not have the
- * given property, or if the given value cannot be set as specified
- */
- boolean internalGetSetBooleanProperty(SimplePropertyDescriptor property, boolean get, boolean value) {
- throw new RuntimeException("Node does not have this property"); //$NON-NLS-1$
- }
-
- /**
- * Sets the value of the given property for this node.
- * The default implementation of this method throws an exception explaining
- * that this node does not have such a property. This method should be
- * extended in subclasses that have at leasy one simple property whose value
- * type is a reference type.
- *
- * @param property the property
- * @param get <code>true</code> for a get operation, and
- * <code>false</code> for a set operation
- * @param value the new property value, or <code>null</code> if none;
- * ignored for get operations
- * @return the value, or <code>null</code> if none; always returns
- * <code>null</code> for set operations
- * @exception RuntimeException if this node does not have the
- * given property, or if the given value cannot be set as specified
- */
- Object internalGetSetObjectProperty(SimplePropertyDescriptor property, boolean get, Object value) {
- throw new RuntimeException("Node does not have this property"); //$NON-NLS-1$
- }
-
- /**
- * Sets the child value of the given property for this node.
- * The default implementation of this method throws an exception explaining
- * that this node does not have such a property. This method should be
- * extended in subclasses that have at leasy one child property.
- *
- * @param property the property
- * @param get <code>true</code> for a get operation, and
- * <code>false</code> for a set operation
- * @param child the new child value, or <code>null</code> if none;
- * always <code>null</code> for get operations
- * @return the child, or <code>null</code> if none; always returns
- * <code>null</code> for set operations
- * @exception RuntimeException if this node does not have the
- * given property, or if the given child cannot be set as specified
- */
- ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- throw new RuntimeException("Node does not have this property"); //$NON-NLS-1$
- }
-
- /**
- * Returns the list value of the given property for this node.
- * The default implementation of this method throws an exception explaining
- * that this noed does not have such a property. This method should be
- * extended in subclasses that have at leasy one child list property.
- *
- * @param property the property
- * @return the list (element type: {@link ASTNode})
- * @exception RuntimeException if the given node does not have the
- * given property
- */
- List internalGetChildListProperty(ChildListPropertyDescriptor property) {
- throw new RuntimeException("Node does not have this property"); //$NON-NLS-1$
- }
-
- /**
- * Returns a list of structural property descriptors for nodes of the
- * same type as this node. Clients must not modify the result.
- * <p>
- * Note that property descriptors are a meta-level mechanism
- * for manipulating ASTNodes in a generic way. They are
- * unrelated to <code>get/setProperty</code>.
- * </p>
- *
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- */
- public final List structuralPropertiesForType() {
- return internalStructuralPropertiesForType(this.ast.apiLevel);
- }
-
- /**
- * Returns a list of property descriptors for this node type.
- * Clients must not modify the result. This abstract method
- * must be implemented in each concrete AST node type.
- * <p>
- * N.B. This method is package-private, so that the implementations
- * of this method in each of the concrete AST node types do not
- * clutter up the API doc.
- * </p>
- *
- * @param apiLevel the API level; one of the <code>AST.JLS*</code> constants
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- */
- abstract List internalStructuralPropertiesForType(int apiLevel);
-
- /**
- * Internal helper method that starts the building a list of
- * property descriptors for the given node type.
- *
- * @param nodeClass the class for a concrete node type
- * @param propertyList empty list
- */
- static void createPropertyList(Class nodeClass, List propertyList) {
- // stuff nodeClass at head of list for future ref
- propertyList.add(nodeClass);
- }
-
- /**
- * Internal helper method that adding a property descriptor.
- *
- * @param property the structural property descriptor
- * @param propertyList list beginning with the AST node class
- * followed by accumulated structural property descriptors
- */
- static void addProperty(StructuralPropertyDescriptor property, List propertyList) {
- Class nodeClass = (Class) propertyList.get(0);
- if (property.getNodeClass() != nodeClass) {
- // easily made cut-and-paste mistake
- throw new RuntimeException("Structural property descriptor has wrong node class!"); //$NON-NLS-1$
- }
- propertyList.add(property);
- }
-
- /**
- * Internal helper method that completes the building of
- * a node type's structural property descriptor list.
- *
- * @param propertyList list beginning with the AST node class
- * followed by accumulated structural property descriptors
- * @return unmodifiable list of structural property descriptors
- * (element type: <code>StructuralPropertyDescriptor</code>)
- */
- static List reapPropertyList(List propertyList) {
- propertyList.remove(0); // remove nodeClass
- // compact
- ArrayList a = new ArrayList(propertyList.size());
- a.addAll(propertyList);
- return Collections.unmodifiableList(a);
- }
-
- /**
- * Checks that this AST operation is not used when
- * building JLS2 level ASTs.
-
- * @exception UnsupportedOperationException
- */
- final void unsupportedIn2() {
- if (this.ast.apiLevel == AST.JLS2_INTERNAL) {
- throw new UnsupportedOperationException("Operation not supported in JLS2 AST"); //$NON-NLS-1$
- }
- }
-
- /**
- * Checks that this AST operation is only used when
- * building JLS2 level ASTs.
-
- * @exception UnsupportedOperationException
- */
- final void supportedOnlyIn2() {
- if (this.ast.apiLevel != AST.JLS2_INTERNAL) {
- throw new UnsupportedOperationException("Operation only supported in JLS2 AST"); //$NON-NLS-1$
- }
- }
-
- /**
- * Sets or clears this node's parent node and location.
- * <p>
- * Note that this method is package-private. The pointer from a node
- * to its parent is set implicitly as a side effect of inserting or
- * removing the node as a child of another node. This method calls
- * <code>ast.modifying()</code>.
- * </p>
- *
- * @param parent the new parent of this node, or <code>null</code> if none
- * @param property the location of this node in its parent,
- * or <code>null</code> if <code>parent</code> is <code>null</code>
- * @see #getLocationInParent
- * @see #getParent
- */
- final void setParent(ASTNode parent, StructuralPropertyDescriptor property) {
- this.ast.modifying();
- this.parent = parent;
- this.location = property;
- }
-
- /**
- * Removes this node from its parent. Has no effect if this node
- * is unparented. If this node appears as an element of a child list
- * property of its parent, then this node is removed from the
- * list using <code>List.remove</code>.
- * If this node appears as the value of a child property of its
- * parent, then this node is detached from its parent
- * by passing <code>null</code> to the appropriate setter method;
- * this operation fails if this node is in a mandatory property.
- *
- */
- public final void delete() {
- StructuralPropertyDescriptor p = getLocationInParent();
- if (p == null) {
- // node is unparented
- return;
- }
- if (p.isChildProperty()) {
- getParent().setStructuralProperty(this.location, null);
- return;
- }
- if (p.isChildListProperty()) {
- List l = (List) getParent().getStructuralProperty(this.location);
- l.remove(this);
- }
- }
-
- /**
- * Checks whether the given new child node is a node
- * in a different AST from its parent-to-be, whether it is
- * already has a parent, whether adding it to its
- * parent-to-be would create a cycle, and whether the child is of
- * the right type. The parent-to-be is the enclosing instance.
- *
- * @param node the parent-to-be node
- * @param newChild the new child of the parent
- * @param cycleCheck <code>true</code> if cycles are possible and need
- * to be checked, <code>false</code> if cycles are impossible and do
- * not need to be checked
- * @param nodeType a type constraint on child nodes, or <code>null</code>
- * if no special check is required
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the child is null</li>
- * <li>the node belongs to a different AST</li>
- * <li>the child has the incorrect node type</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- static void checkNewChild(ASTNode node, ASTNode newChild,
- boolean cycleCheck, Class nodeType) {
- if (newChild.ast != node.ast) {
- // new child is from a different AST
- throw new IllegalArgumentException();
- }
- if (newChild.getParent() != null) {
- // new child currently has a different parent
- throw new IllegalArgumentException();
- }
- if (cycleCheck && newChild == node.getRoot()) {
- // inserting new child would create a cycle
- throw new IllegalArgumentException();
- }
- Class childClass = newChild.getClass();
- if (nodeType != null && !nodeType.isAssignableFrom(childClass)) {
- // new child is not of the right type
-
- // fix for inner function handling, Etienne Pfister
- if(!(newChild instanceof org.eclipse.wst.jsdt.core.dom.FunctionDeclaration)) {
- throw new ClassCastException();
- }
- }
- if ((newChild.typeAndFlags & PROTECT) != 0) {
- // new child node is protected => cannot be parented
- throw new IllegalArgumentException("AST node cannot be modified"); //$NON-NLS-1$
- }
- }
-
- /**
- * Prelude portion of the "3 step program" for replacing the
- * old child of this node with another node.
- * Here is the code pattern found in all AST node subclasses:
- * <pre>
- * ASTNode oldChild = this.foo;
- * preReplaceChild(oldChild, newFoo, FOO_PROPERTY);
- * this.foo = newFoo;
- * postReplaceChild(oldChild, newFoo, FOO_PROPERTY);
- * </pre>
- * The first part (preReplaceChild) does all the precondition checks,
- * reports pre-delete events, and changes parent links.
- * The old child is delinked from its parent (making it a root node),
- * and the new child node is linked to its parent. The new child node
- * must be a root node in the same AST as its new parent, and must not
- * be an ancestor of this node. All three nodes must be
- * modifiable (not PROTECTED). The replace operation must fail
- * atomically; so it is crucial that all precondition checks
- * be done before any linking and delinking happens.
- * The final part (postReplaceChild )reports post-add events.
- * <p>
- * This method calls <code>ast.modifying()</code> for the nodes affected.
- * </p>
- *
- * @param oldChild the old child of this node, or <code>null</code> if
- * there was no old child to replace
- * @param newChild the new child of this node, or <code>null</code> if
- * there is no replacement child
- * @param property the property descriptor of this node describing
- * the relationship between node and child
- * @exception RuntimeException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * <li>any of the nodes involved are unmodifiable</li>
- * </ul>
- */
- final void preReplaceChild(ASTNode oldChild, ASTNode newChild, ChildPropertyDescriptor property) {
- if ((this.typeAndFlags & PROTECT) != 0) {
- // this node is protected => cannot gain or lose children
- throw new IllegalArgumentException("AST node cannot be modified"); //$NON-NLS-1$
- }
- if (newChild != null) {
- checkNewChild(this, newChild, property.cycleRisk, null);
- }
- // delink old child from parent
- if (oldChild != null) {
- if ((oldChild.typeAndFlags & PROTECT) != 0) {
- // old child node is protected => cannot be unparented
- throw new IllegalArgumentException("AST node cannot be modified"); //$NON-NLS-1$
- }
- if (newChild != null) {
- this.ast.preReplaceChildEvent(this, oldChild, newChild, property);
- } else {
- this.ast.preRemoveChildEvent(this, oldChild, property);
- }
- oldChild.setParent(null, null);
- } else {
- if(newChild != null) {
- this.ast.preAddChildEvent(this, newChild, property);
- }
- }
- // link new child to parent
- if (newChild != null) {
- newChild.setParent(this, property);
- // cannot notify postAddChildEvent until parent is linked to child too
- }
- }
-
- /**
- * Postlude portion of the "3 step program" for replacing the
- * old child of this node with another node.
- * See {@link #preReplaceChild(ASTNode, ASTNode, ChildPropertyDescriptor)}
- * for details.
- */
- final void postReplaceChild(ASTNode oldChild, ASTNode newChild, ChildPropertyDescriptor property) {
- // link new child to parent
- if (newChild != null) {
- if (oldChild != null) {
- this.ast.postReplaceChildEvent(this, oldChild, newChild, property);
- } else {
- this.ast.postAddChildEvent(this, newChild, property);
- }
- } else {
- this.ast.postRemoveChildEvent(this, oldChild, property);
- }
- }
-
- /**
- * Prelude portion of the "3 step program" for changing the
- * value of a simple property of this node.
- * Here is the code pattern found in all AST node subclasses:
- * <pre>
- * preValueChange(FOO_PROPERTY);
- * this.foo = newFoo;
- * postValueChange(FOO_PROPERTY);
- * </pre>
- * The first part (preValueChange) does the precondition check
- * to make sure the node is modifiable (not PROTECTED).
- * The change operation must fail atomically; so it is crucial
- * that the precondition checks are done before the field is
- * hammered. The final part (postValueChange)reports post-change
- * events.
- * <p>
- * This method calls <code>ast.modifying()</code> for the node affected.
- * </p>
- *
- * @param property the property descriptor of this node
- * @exception RuntimeException if:
- * <ul>
- * <li>this node is unmodifiable</li>
- * </ul>
- */
- final void preValueChange(SimplePropertyDescriptor property) {
- if ((this.typeAndFlags & PROTECT) != 0) {
- // this node is protected => cannot change valure of properties
- throw new IllegalArgumentException("AST node cannot be modified"); //$NON-NLS-1$
- }
- this.ast.preValueChangeEvent(this, property);
- this.ast.modifying();
- }
-
- /**
- * Postlude portion of the "3 step program" for replacing the
- * old child of this node with another node.
- * See {@link #preValueChange(SimplePropertyDescriptor)} for details.
- */
- final void postValueChange(SimplePropertyDescriptor property) {
- this.ast.postValueChangeEvent(this, property);
- }
-
- /**
- * Ensures that this node is modifiable (that is, not marked PROTECTED).
- * If successful, calls ast.modifying().
- * @exception RuntimeException is not modifiable
- */
- final void checkModifiable() {
- if ((this.typeAndFlags & PROTECT) != 0) {
- throw new IllegalArgumentException("AST node cannot be modified"); //$NON-NLS-1$
- }
- this.ast.modifying();
- }
-
- /**
- * Begin lazy initialization of this node.
- * Here is the code pattern found in all AST
- * node subclasses:
- * <pre>
- * if (this.foo == null) {
- * // lazy init must be thread-safe for readers
- * synchronized (this) {
- * if (this.foo == null) {
- * preLazyInit();
- * this.foo = ...; // code to create new node
- * postLazyInit(this.foo, FOO_PROPERTY);
- * }
- * }
- * }
- * </pre>
- *
- */
- final void preLazyInit() {
- // IMPORTANT: this method is called by readers
- // ASTNode.this is locked at this point
- this.ast.disableEvents();
- // will turn events back on in postLasyInit
- }
-
- /**
- * End lazy initialization of this node.
- *
- * @param newChild the new child of this node, or <code>null</code> if
- * there is no replacement child
- * @param property the property descriptor of this node describing
- * the relationship between node and child
- */
- final void postLazyInit(ASTNode newChild, ChildPropertyDescriptor property) {
- // IMPORTANT: this method is called by readers
- // ASTNode.this is locked at this point
- // newChild is brand new (so no chance of concurrent access)
- newChild.setParent(this, property);
- // turn events back on (they were turned off in corresponding preLazyInit)
- this.ast.reenableEvents();
- }
-
- /**
- * Returns the named property of this node, or <code>null</code> if none.
- *
- * @param propertyName the property name
- * @return the property value, or <code>null</code> if none
- * @see #setProperty(String,Object)
- */
- public final Object getProperty(String propertyName) {
- if (propertyName == null) {
- throw new IllegalArgumentException();
- }
- if (this.property1 == null) {
- // node has no properties at all
- return null;
- }
- if (this.property1 instanceof String) {
- // node has only a single property
- if (propertyName.equals(this.property1)) {
- return this.property2;
- } else {
- return null;
- }
- }
- // otherwise node has table of properties
- Map m = (Map) this.property1;
- return m.get(propertyName);
- }
-
- /**
- * Sets the named property of this node to the given value,
- * or to <code>null</code> to clear it.
- * <p>
- * Clients should employ property names that are sufficiently unique
- * to avoid inadvertent conflicts with other clients that might also be
- * setting properties on the same node.
- * </p>
- * <p>
- * Note that modifying a property is not considered a modification to the
- * AST itself. This is to allow clients to decorate existing nodes with
- * their own properties without jeopardizing certain things (like the
- * validity of bindings), which rely on the underlying tree remaining static.
- * </p>
- *
- * @param propertyName the property name
- * @param data the new property value, or <code>null</code> if none
- * @see #getProperty(String)
- */
- public final void setProperty(String propertyName, Object data) {
- if (propertyName == null) {
- throw new IllegalArgumentException();
- }
- // N.B. DO NOT CALL ast.modifying();
-
- if (this.property1 == null) {
- // node has no properties at all
- if (data == null) {
- // we already know this
- return;
- }
- // node gets its fist property
- this.property1 = propertyName;
- this.property2 = data;
- return;
- }
-
- if (this.property1 instanceof String) {
- // node has only a single property
- if (propertyName.equals(this.property1)) {
- // we're in luck
- this.property2 = data;
- if (data == null) {
- // just deleted last property
- this.property1 = null;
- this.property2 = null;
- }
- return;
- }
- if (data == null) {
- // we already know this
- return;
- }
- // node already has one property - getting its second
- // convert to more flexible representation
- HashMap m = new HashMap(2);
- m.put(this.property1, this.property2);
- m.put(propertyName, data);
- this.property1 = m;
- this.property2 = null;
- return;
- }
-
- // node has two or more properties
- HashMap m = (HashMap) this.property1;
- if (data == null) {
- m.remove(propertyName);
- // check for just one property left
- if (m.size() == 1) {
- // convert to more efficient representation
- Map.Entry[] entries = (Map.Entry[]) m.entrySet().toArray(new Map.Entry[1]);
- this.property1 = entries[0].getKey();
- this.property2 = entries[0].getValue();
- }
- return;
- } else {
- m.put(propertyName, data);
- // still has two or more properties
- return;
- }
- }
-
- /**
- * Returns an unmodifiable table of the properties of this node with
- * non-<code>null</code> values.
- *
- * @return the table of property values keyed by property name
- * (key type: <code>String</code>; value type: <code>Object</code>)
- */
- public final Map properties() {
- if (this.property1 == null) {
- // node has no properties at all
- return UNMODIFIABLE_EMPTY_MAP;
- }
- if (this.property1 instanceof String) {
- // node has a single property
- return Collections.singletonMap(this.property1, this.property2);
- }
-
- // node has two or more properties
- if (this.property2 == null) {
- this.property2 = Collections.unmodifiableMap((Map) this.property1);
- }
- // property2 is unmodifiable wrapper for map in property1
- return (Map) this.property2;
- }
-
- /**
- * Returns the flags associated with this node.
- * <p>
- * No flags are associated with newly created nodes.
- * </p>
- * <p>
- * The flags are the bitwise-or of individual flags.
- * The following flags are currently defined:
- * <ul>
- * <li>{@link #MALFORMED} - indicates node is syntactically
- * malformed</li>
- * <li>{@link #ORIGINAL} - indicates original node
- * created by ASTParser</li>
- * <li>{@link #PROTECT} - indicates node is protected
- * from further modification</li>
- * <li>{@link #RECOVERED} - indicates node or a part of this node
- * is recovered from source that contains a syntax error</li>
- * </ul>
- * Other bit positions are reserved for future use.
- * </p>
- *
- * @return the bitwise-or of individual flags
- * @see #setFlags(int)
- */
- public final int getFlags() {
- return this.typeAndFlags & 0xFFFF;
- }
-
- /**
- * Sets the flags associated with this node to the given value.
- * <p>
- * The flags are the bitwise-or of individual flags.
- * The following flags are currently defined:
- * <ul>
- * <li>{@link #MALFORMED} - indicates node is syntactically
- * malformed</li>
- * <li>{@link #ORIGINAL} - indicates original node
- * created by ASTParser</li>
- * <li>{@link #PROTECT} - indicates node is protected
- * from further modification</li>
- * <li>{@link #RECOVERED} - indicates node or a part of this node
- * is recovered from source that contains a syntax error</li>
- * </ul>
- * Other bit positions are reserved for future use.
- * </p>
- * <p>
- * Note that the flags are <em>not</em> considered a structural
- * property of the node, and can be changed even if the
- * node is marked as protected.
- * </p>
- *
- * @param flags the bitwise-or of individual flags
- * @see #getFlags()
- */
- public final void setFlags(int flags) {
- this.ast.modifying();
- int old = this.typeAndFlags & 0xFFFF0000;
- this.typeAndFlags = old | (flags & 0xFFFF);
- }
-
- /**
- * Returns an integer value identifying the type of this concrete AST node.
- * The values are small positive integers, suitable for use in switch statements.
- * <p>
- * For each concrete node type there is a unique node type constant (name
- * and value). The unique node type constant for a concrete node type such as
- * <code>CastExpression</code> is <code>ASTNode.CAST_EXPRESSION</code>.
- * </p>
- *
- * @return one of the node type constants
- */
- public final int getNodeType() {
- return this.typeAndFlags >>> 16;
- }
-
- /**
- * Sets the integer value identifying the type of this concrete AST node.
- * The values are small positive integers, suitable for use in switch statements.
- *
- * @param nodeType one of the node type constants
- */
- private void setNodeType(int nodeType) {
- int old = this.typeAndFlags & 0xFFFF0000;
- this.typeAndFlags = old | (nodeType << 16);
- }
-
- /**
- * Returns an integer value identifying the type of this concrete AST node.
- * <p>
- * This internal method is implemented in each of the
- * concrete node subclasses.
- * </p>
- *
- * @return one of the node type constants
- */
- abstract int getNodeType0();
-
- /**
- * The <code>ASTNode</code> implementation of this <code>Object</code>
- * method uses object identity (==). Use <code>subtreeMatch</code> to
- * compare two subtrees for equality.
- *
- * @param obj {@inheritDoc}
- * @return {@inheritDoc}
- * @see #subtreeMatch(ASTMatcher matcher, Object other)
- */
- public final boolean equals(Object obj) {
- return this == obj; // equivalent to Object.equals
- }
-
- /*
- * (non-Javadoc)
- * This makes it consistent with the fact that a equals methods has been provided.
- * @see java.lang.Object#hashCode()
- */
- public final int hashCode() {
- return super.hashCode();
- }
-
- /**
- * Returns whether the subtree rooted at the given node matches the
- * given other object as decided by the given matcher.
- *
- * @param matcher the matcher
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match
- */
- public final boolean subtreeMatch(ASTMatcher matcher, Object other) {
- return subtreeMatch0(matcher, other);
- }
-
- /**
- * Returns whether the subtree rooted at the given node matches the
- * given other object as decided by the given matcher.
- * <p>
- * This internal method is implemented in each of the
- * concrete node subclasses.
- * </p>
- *
- * @param matcher the matcher
- * @param other the other object, or <code>null</code>
- * @return <code>true</code> if the subtree matches, or
- * <code>false</code> if they do not match
- */
- abstract boolean subtreeMatch0(ASTMatcher matcher, Object other);
-
- /**
- * Returns a deep copy of the subtree of AST nodes rooted at the
- * given node. The resulting nodes are owned by the given AST,
- * which may be different from the ASTs of the given node.
- * Even if the given node has a parent, the result node will be unparented.
- * <p>
- * Source range information on the original nodes is automatically copied to the new
- * nodes. Client properties (<code>properties</code>) are not carried over.
- * </p>
- * <p>
- * The node's <code>AST</code> and the target <code>AST</code> must support
- * the same API level.
- * </p>
- *
- * @param target the AST that is to own the nodes in the result
- * @param node the node to copy, or <code>null</code> if none
- * @return the copied node, or <code>null</code> if <code>node</code>
- * is <code>null</code>
- */
- public static ASTNode copySubtree(AST target, ASTNode node) {
- if (node == null) {
- return null;
- }
- if (target == null) {
- throw new IllegalArgumentException();
- }
- if (target.apiLevel() != node.getAST().apiLevel()) {
- throw new UnsupportedOperationException();
- }
- ASTNode newNode = node.clone(target);
- return newNode;
- }
-
- /**
- * Returns a deep copy of the subtrees of AST nodes rooted at the
- * given list of nodes. The resulting nodes are owned by the given AST,
- * which may be different from the ASTs of the nodes in the list.
- * Even if the nodes in the list have parents, the nodes in the result
- * will be unparented.
- * <p>
- * Source range information on the original nodes is automatically copied to the new
- * nodes. Client properties (<code>properties</code>) are not carried over.
- * </p>
- *
- * @param target the AST that is to own the nodes in the result
- * @param nodes the list of nodes to copy
- * (element type: <code>ASTNode</code>)
- * @return the list of copied subtrees
- * (element type: <code>ASTNode</code>)
- */
- public static List copySubtrees(AST target, List nodes) {
- List result = new ArrayList(nodes.size());
- for (Iterator it = nodes.iterator(); it.hasNext(); ) {
- ASTNode oldNode = (ASTNode) it.next();
- ASTNode newNode = oldNode.clone(target);
- result.add(newNode);
- }
- return result;
- }
-
- /**
- * Returns a deep copy of the subtree of AST nodes rooted at this node.
- * The resulting nodes are owned by the given AST, which may be different
- * from the AST of this node. Even if this node has a parent, the
- * result node will be unparented.
- * <p>
- * This method reports pre- and post-clone events, and dispatches
- * to <code>clone0(AST)</code> which is reimplemented in node subclasses.
- * </p>
- *
- * @param target the AST that is to own the nodes in the result
- * @return the root node of the copies subtree
- */
- final ASTNode clone(AST target) {
- this.ast.preCloneNodeEvent(this);
- ASTNode c = this.clone0(target);
- this.ast.postCloneNodeEvent(this, c);
- return c;
- }
-
- /**
- * Returns a deep copy of the subtree of AST nodes rooted at this node.
- * The resulting nodes are owned by the given AST, which may be different
- * from the AST of this node. Even if this node has a parent, the
- * result node will be unparented.
- * <p>
- * This method must be implemented in subclasses.
- * </p>
- * <p>
- * This method does not report pre- and post-clone events.
- * All callers should instead call <code>clone(AST)</code>
- * to ensure that pre- and post-clone events are reported.
- * </p>
- * <p>
- * N.B. This method is package-private, so that the implementations
- * of this method in each of the concrete AST node types do not
- * clutter up the API doc.
- * </p>
- *
- * @param target the AST that is to own the nodes in the result
- * @return the root node of the copies subtree
- */
- abstract ASTNode clone0(AST target);
-
- /**
- * Accepts the given visitor on a visit of the current node.
- *
- * @param visitor the visitor object
- * @exception IllegalArgumentException if the visitor is null
- */
- public final void accept(ASTVisitor visitor) {
- if (visitor == null) {
- throw new IllegalArgumentException();
- }
- // begin with the generic pre-visit
- visitor.preVisit(this);
- // dynamic dispatch to internal method for type-specific visit/endVisit
- accept0(visitor);
- // end with the generic post-visit
- visitor.postVisit(this);
- }
-
- /**
- * Accepts the given visitor on a type-specific visit of the current node.
- * This method must be implemented in all concrete AST node types.
- * <p>
- * General template for implementation on each concrete ASTNode class:
- * <pre>
- * <code>
- * boolean visitChildren = visitor.visit(this);
- * if (visitChildren) {
- * // visit children in normal left to right reading order
- * acceptChild(visitor, getProperty1());
- * acceptChildren(visitor, rawListProperty);
- * acceptChild(visitor, getProperty2());
- * }
- * visitor.endVisit(this);
- * </code>
- * </pre>
- * Note that the caller (<code>accept</code>) take cares of invoking
- * <code>visitor.preVisit(this)</code> and <code>visitor.postVisit(this)</code>.
- * </p>
- *
- * @param visitor the visitor object
- */
- abstract void accept0(ASTVisitor visitor);
-
- /**
- * Accepts the given visitor on a visit of the current node.
- * <p>
- * This method should be used by the concrete implementations of
- * <code>accept0</code> to traverse optional properties. Equivalent
- * to <code>child.accept(visitor)</code> if <code>child</code>
- * is not <code>null</code>.
- * </p>
- *
- * @param visitor the visitor object
- * @param child the child AST node to dispatch too, or <code>null</code>
- * if none
- */
- final void acceptChild(ASTVisitor visitor, ASTNode child) {
- if (child == null) {
- return;
- }
- child.accept(visitor);
- }
-
- /**
- * Accepts the given visitor on a visit of the given live list of
- * child nodes.
- * <p>
- * This method must be used by the concrete implementations of
- * <code>accept</code> to traverse list-values properties; it
- * encapsulates the proper handling of on-the-fly changes to the list.
- * </p>
- *
- * @param visitor the visitor object
- * @param children the child AST node to dispatch too, or <code>null</code>
- * if none
- */
- final void acceptChildren(ASTVisitor visitor, ASTNode.NodeList children) {
- if(children == null){
- return;
- }
- // use a cursor to keep track of where we are up to
- // (the list may be changing under foot)
- NodeList.Cursor cursor = children.newCursor();
- try {
- while (cursor.hasNext()) {
- ASTNode child = (ASTNode) cursor.next();
- child.accept(visitor);
- }
- } finally {
- children.releaseCursor(cursor);
- }
- }
-
- /**
- * Returns the character index into the original source file indicating
- * where the source fragment corresponding to this node begins.
- * <p>
- * The parser supplies useful well-defined source ranges to the nodes it creates.
- * See {@link ASTParser#setKind(int)} for details
- * on precisely where source ranges begin and end.
- * </p>
- *
- * @return the 0-based character index, or <code>-1</code>
- * if no source position information is recorded for this node
- * @see #getLength()
- * @see ASTParser
- */
- public final int getStartPosition() {
- return this.startPosition;
- }
-
- /**
- * Returns the length in characters of the original source file indicating
- * where the source fragment corresponding to this node ends.
- * <p>
- * The parser supplies useful well-defined source ranges to the nodes it creates.
- * See {@link ASTParser#setKind(int)} methods for details
- * on precisely where source ranges begin and end.
- * </p>
- *
- * @return a (possibly 0) length, or <code>0</code>
- * if no source position information is recorded for this node
- * @see #getStartPosition()
- * @see ASTParser
- */
- public final int getLength() {
- return this.length;
- }
-
- /**
- * Sets the source range of the original source file where the source
- * fragment corresponding to this node was found.
- * <p>
- * See {@link ASTParser#setKind(int)} for details
- * on precisely where source ranges are supposed to begin and end.
- * </p>
- *
- * @param startPosition a 0-based character index,
- * or <code>-1</code> if no source position information is
- * available for this node
- * @param length a (possibly 0) length,
- * or <code>0</code> if no source position information is recorded
- * for this node
- * @see #getStartPosition()
- * @see #getLength()
- * @see ASTParser
- */
- public final void setSourceRange(int startPosition, int length) {
- if (startPosition >= 0 && length < 0) {
- throw new IllegalArgumentException();
- }
- if (startPosition < 0 && length != 0) {
- throw new IllegalArgumentException();
- }
- // source positions are not considered a structural property
- // but we protect them nevertheless
- checkModifiable();
- this.startPosition = startPosition;
- this.length = length;
- }
-
- /**
- * Returns a string representation of this node suitable for debugging
- * purposes only.
- *
- * @return a debug string
- */
- public final String toString() {
- StringBuffer buffer = new StringBuffer();
- int p = buffer.length();
- try {
- appendDebugString(buffer);
- } catch (RuntimeException e) {
- e.printStackTrace();
- // since debugger sometimes call toString methods, problems can easily happen when
- // toString is called on an instance that is being initialized
- buffer.setLength(p);
- buffer.append("!"); //$NON-NLS-1$
- buffer.append(standardToString());
- }
- return buffer.toString();
- }
-
- /**
- * Returns the string representation of this node produced by the standard
- * <code>Object.toString</code> method.
- *
- * @return a debug string
- */
- final String standardToString() {
- return super.toString();
- }
-
- /**
- * Appends a debug representation of this node to the given string buffer.
- * <p>
- * The <code>ASTNode</code> implementation of this method prints out the entire
- * subtree. Subclasses may override to provide a more succinct representation.
- * </p>
- *
- * @param buffer the string buffer to append to
- */
- void appendDebugString(StringBuffer buffer) {
- // print the subtree by default
- appendPrintString(buffer);
- }
-
- /**
- * Appends a standard JavaScript source code representation of this subtree to the given
- * string buffer.
- *
- * @param buffer the string buffer to append to
- */
- final void appendPrintString(StringBuffer buffer) {
- NaiveASTFlattener printer = new NaiveASTFlattener();
- this.accept(printer);
- buffer.append(printer.getResult());
- }
-
- /**
- * Estimate of size of an object header in bytes.
- */
- static final int HEADERS = 12;
-
- /**
- * Approximate base size of an AST node instance in bytes,
- * including object header and instance fields.
- * That is, HEADERS + (# instance vars in ASTNode)*4.
- */
- static final int BASE_NODE_SIZE = HEADERS + 7 * 4;
-
- /**
- * Returns an estimate of the memory footprint, in bytes,
- * of the given string.
- *
- * @param string the string to measure, or <code>null</code>
- * @return the size of this string object in bytes, or
- * 0 if the string is <code>null</code>
- */
- static int stringSize(String string) {
- int size = 0;
- if (string != null) {
- // Strings usually have 4 instance fields, one of which is a char[]
- size += HEADERS + 4 * 4;
- // char[] has 2 bytes per character
- size += HEADERS + 2 * string.length();
- }
- return size;
- }
-
- /**
- * Returns an estimate of the memory footprint in bytes of the entire
- * subtree rooted at this node.
- *
- * @return the size of this subtree in bytes
- */
- public final int subtreeBytes() {
- return treeSize();
- }
-
- /**
- * Returns an estimate of the memory footprint in bytes of the entire
- * subtree rooted at this node.
- * <p>
- * N.B. This method is package-private, so that the implementations
- * of this method in each of the concrete AST node types do not
- * clutter up the API doc.
- * </p>
- *
- * @return the size of this subtree in bytes
- */
- abstract int treeSize();
-
- /**
- * Returns an estimate of the memory footprint of this node in bytes.
- * The estimate does not include the space occupied by child nodes.
- *
- * @return the size of this node in bytes
- */
- abstract int memSize();
-
- public ASTNode getBodyChild()
- {
- ASTNode bodyChild=this;
- while (bodyChild!=null)
- {
- if (bodyChild.parent instanceof JavaScriptUnit || bodyChild.parent instanceof BodyDeclaration)
- return bodyChild;
- bodyChild=bodyChild.parent;
- }
- return null;
-
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ASTParser.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ASTParser.java
deleted file mode 100644
index 1d7e542c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ASTParser.java
+++ /dev/null
@@ -1,1161 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.dom;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-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.IJavaScriptProject;
-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.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem;
-import org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ConstructorDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.parser.RecoveryScanner;
-import org.eclipse.wst.jsdt.internal.compiler.parser.RecoveryScannerData;
-import org.eclipse.wst.jsdt.internal.compiler.parser.Scanner;
-import org.eclipse.wst.jsdt.internal.core.BasicCompilationUnit;
-import org.eclipse.wst.jsdt.internal.core.DefaultWorkingCopyOwner;
-import org.eclipse.wst.jsdt.internal.core.PackageFragment;
-import org.eclipse.wst.jsdt.internal.core.util.CodeSnippetParsingUtil;
-import org.eclipse.wst.jsdt.internal.core.util.RecordedParsingInformation;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * A JavaScript language parser for creating abstract syntax trees (ASTs).
- * <p>
- * Example: Create basic AST from source string
- * <pre>
- * char[] source = ...;
- * ASTParser parser = ASTParser.newParser(AST.JLS3);
- * parser.setSource(source);
- * JavaScriptUnit result = (JavaScriptUnit) parser.createAST(null);
- * </pre>
- * Once a configured parser instance has been used to create an AST,
- * the settings are automatically reset to their defaults,
- * ready for the parser instance to be reused.
- * </p>
- * <p>
- * There are a number of configurable features:
- * <ul>
- * <li>Source string from {@link #setSource(char[]) char[]},
- * {@link #setSource(IJavaScriptUnit) IJavaScriptUnit},
- * or {@link #setSource(IClassFile) IClassFile}, and limited
- * to a specified {@linkplain #setSourceRange(int,int) subrange}.</li>
- * <li>Whether {@linkplain #setResolveBindings(boolean) bindings} will be created.</li>
- * <li>Which {@linkplain #setWorkingCopyOwner(WorkingCopyOwner)
- * working set owner} to use when resolving bindings).</li>
- * <li>A hypothetical {@linkplain #setUnitName(String) javaScript unit file name}
- * and {@linkplain #setProject(IJavaScriptProject) JavaScript project}
- * for locating a raw source string in the JavaScript model (when
- * resolving bindings)</li>
- * <li>Which {@linkplain #setCompilerOptions(Map) validator options}
- * to use.</li>
- * <li>Whether to parse just {@linkplain #setKind(int) an expression, statements,
- * or body declarations} rather than an entire javaScript unit.</li>
- * <li>Whether to return a {@linkplain #setFocalPosition(int) abridged AST}
- * focused on the declaration containing a given source position.</li>
- * </ul>
- * </p>
- *
- * 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 ASTParser {
-
- /**
- * Kind constant used to request that the source be parsed
- * as a single expression.
- */
- public static final int K_EXPRESSION = 0x01;
-
- /**
- * Kind constant used to request that the source be parsed
- * as a sequence of statements.
- */
- public static final int K_STATEMENTS = 0x02;
-
- /**
- * Kind constant used to request that the source be parsed
- * as a sequence of class body declarations.
- */
- public static final int K_CLASS_BODY_DECLARATIONS = 0x04;
-
- /**
- * Kind constant used to request that the source be parsed
- * as a javaScript unit.
- */
- public static final int K_COMPILATION_UNIT = 0x08;
-
- /**
- * Creates a new object for creating a JavaScript abstract syntax tree
- * (AST) following the specified set of API rules.
- *
- * @param level the API level; one of the LEVEL constants
- * declared on <code>AST</code>
- * @return new ASTParser instance
- */
- public static ASTParser newParser(int level) {
- return new ASTParser(level);
- }
-
- /**
- * Level of AST API desired.
- */
- private final int apiLevel;
-
- /**
- * Kind of parse requested. Defaults to an entire javaScript unit.
- */
- private int astKind;
-
- /**
- * Compiler options. Defaults to JavaScriptCore.getOptions().
- */
- private Map compilerOptions;
-
- /**
- * Request for bindings. Defaults to <code>false</code>.
- */
- private boolean resolveBindings;
-
- /**
- * Request for a partial AST. Defaults to <code>false</code>.
- */
- private boolean partial = false;
-
- /**
- * Request for a statements recovery. Defaults to <code>false</code>.
- */
- private boolean statementsRecovery;
-
- /**
- * Request for a bindings recovery. Defaults to <code>false</code>.
- */
- private boolean bindingsRecovery;
-
-
- /**
- * The focal point for a partial AST request.
- * Only used when <code>partial</code> is <code>true</code>.
- */
- private int focalPointPosition;
-
- /**
- * Source string.
- */
- private char[] rawSource = null;
-
- /**
- * JavaScript unit supplying the source.
- */
- private ITypeRoot typeRoot = null;
-
- /**
- * Character-based offset into the source string where parsing is to
- * begin. Defaults to 0.
- */
- private int sourceOffset = 0;
-
- /**
- * Character-based length limit, or -1 if unlimited.
- * All characters in the source string between <code>offset</code>
- * and <code>offset+length-1</code> inclusive are parsed. Defaults to -1,
- * which means the rest of the source string.
- */
- private int sourceLength = -1;
-
- /**
- * Working copy owner. Defaults to primary owner.
- */
- private WorkingCopyOwner workingCopyOwner = DefaultWorkingCopyOwner.PRIMARY;
-
- /**
- * JavaScript project used to resolve names, or <code>null</code> if none.
- * Defaults to none.
- */
- private IJavaScriptProject project = null;
-
- /**
- * Name of the javaScript unit for resolving bindings, or
- * <code>null</code> if none. Defaults to none.
- */
- private String unitName = null;
-
- /**
- * Creates a new AST parser for the given API level.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param level the API level; one of the LEVEL constants
- * declared on <code>AST</code>
- */
- ASTParser(int level) {
- if ((level != AST.JLS2_INTERNAL)
- && (level != AST.JLS3)) {
- throw new IllegalArgumentException();
- }
- this.apiLevel = level;
- initializeDefaults();
- }
-
- /**
- * Sets all the setting to their default values.
- */
- private void initializeDefaults() {
- this.astKind = K_COMPILATION_UNIT;
- this.rawSource = null;
- this.typeRoot = null;
- this.resolveBindings = false;
- this.sourceLength = -1;
- this.sourceOffset = 0;
- this.workingCopyOwner = DefaultWorkingCopyOwner.PRIMARY;
- this.unitName = null;
- this.project = null;
- this.partial = false;
- Map options = JavaScriptCore.getOptions();
- options.remove(JavaScriptCore.COMPILER_TASK_TAGS); // no need to parse task tags
- this.compilerOptions = options;
- }
-
- /**
- * Requests that the validator should perform bindings recovery.
- * When bindings recovery is enabled the validator returns incomplete bindings.
- * <p>
- * Default to <code>false</code>.
- * </p>
- * <p>This should be set to true only if bindings are resolved. It has no effect if there is no binding
- * resolution.</p>
- *
- * @param enabled <code>true</code> if incomplete bindings are expected,
- * and <code>false</code> if only complete bindings are expected.
- *
- * @see IBinding#isRecovered()
- */
- public void setBindingsRecovery(boolean enabled) {
- this.bindingsRecovery = enabled;
- }
-
- /**
- * Sets the validator options to be used when parsing.
- * <p>
- * Note that {@link #setSource(IClassFile)},
- * {@link #setSource(IJavaScriptUnit)},
- * and {@link #setProject(IJavaScriptProject)} reset the validator options
- * based on the JavaScript project. In other cases, validator options default
- * to {@link JavaScriptCore#getOptions()}. In either case, and especially
- * in the latter, the caller should carefully weight the consequences of
- * allowing validator options to be defaulted as opposed to being
- * explicitly specified for the <code>ASTParser</code> instance.
- * For instance, there is a validator option called "Source Compatibility Mode"
- * which determines which JDK level the source code is expected to meet.
- * If you specify "1.4", then "assert" is treated as a keyword and disallowed
- * as an identifier; if you specify "1.3", then "assert" is allowed as an
- * identifier. So this particular setting has a major bearing on what is
- * considered syntactically legal. By explicitly specifying the setting,
- * the client control exactly how the parser works. On the other hand,
- * allowing default settings means the parsing behaves like other JDT tools.
- * </p>
- *
- * @param options the table of options (key type: <code>String</code>;
- * value type: <code>String</code>), or <code>null</code>
- * to set it back to the default
- */
- public void setCompilerOptions(Map options) {
- if (options == null) {
- options = JavaScriptCore.getOptions();
- } else {
- // copy client's options so as to not do any side effect on them
- options = new HashMap(options);
- }
- options.remove(JavaScriptCore.COMPILER_TASK_TAGS); // no need to parse task tags
- this.compilerOptions = options;
- }
-
- /**
- * Requests that the validator should provide binding information for
- * the AST nodes it creates.
- * <p>
- * Default to <code>false</code> (no bindings).
- * </p>
- * <p>
- * If <code>setResolveBindings(true)</code>, the various names
- * and types appearing in the AST can be resolved to "bindings"
- * by calling the <code>resolveBinding</code> methods. These bindings
- * draw connections between the different parts of a program, and
- * generally afford a more powerful vantage point for clients who wish to
- * analyze a program's structure more deeply. These bindings come at a
- * considerable cost in both time and space, however, and should not be
- * requested frivolously. The additional space is not reclaimed until the
- * AST, all its nodes, and all its bindings become garbage. So it is very
- * important to not retain any of these objects longer than absolutely
- * necessary. Bindings are resolved at the time the AST is created. Subsequent
- * modifications to the AST do not affect the bindings returned by
- * <code>resolveBinding</code> methods in any way; these methods return the
- * same binding as before the AST was modified (including modifications
- * that rearrange subtrees by reparenting nodes).
- * If <code>setResolveBindings(false)</code> (the default), the analysis
- * does not go beyond parsing and building the tree, and all
- * <code>resolveBinding</code> methods return <code>null</code> from the
- * outset.
- * </p>
- * <p>
- * When bindings are requested, instead of considering javaScript units on disk only
- * one can supply a <code>WorkingCopyOwner</code>. Working copies owned
- * by this owner take precedence over the underlying javaScript units when looking
- * up names and drawing the connections.
- * </p>
- * <p>
- * Binding information is obtained from the JavaScript model.
- * This means that the javaScript unit must be located relative to the
- * JavaScript model. This happens automatically when the source code comes from
- * either {@link #setSource(IJavaScriptUnit) setSource(IJavaScriptUnit)}
- * or {@link #setSource(IClassFile) setSource(IClassFile)}.
- * When source is supplied by {@link #setSource(char[]) setSource(char[])},
- * the location must be extablished explicitly by calling
- * {@link #setProject(IJavaScriptProject)} and {@link #setUnitName(String)}.
- * Note that the validator options that affect doc comment checking may also
- * affect whether any bindings are resolved for nodes within doc comments.
- * </p>
- *
- * @param bindings <code>true</code> if bindings are wanted,
- * and <code>false</code> if bindings are not of interest
- */
- public void setResolveBindings(boolean bindings) {
- this.resolveBindings = bindings;
- }
-
- /**
- * Requests an abridged abstract syntax tree.
- * By default, complete ASTs are returned.
- * <p>
- * When <code>true</code> the resulting AST does not have nodes for
- * the entire javaScript unit. Rather, the AST is only fleshed out
- * for the node that include the given source position. This kind of limited
- * AST is sufficient for certain purposes but totally unsuitable for others.
- * In places where it can be used, the limited AST offers the advantage of
- * being smaller and faster to construct.
- * </p>
- * <p>
- * The AST will include nodes for all of the javaScript unit's functions, top-level vars,
- * package, import, and top-level type declarations. It will also always contain
- * nodes for all the body declarations for those top-level types, as well
- * as body declarations for any member types. However, some of the body
- * declarations may be abridged. In particular, the statements ordinarily
- * found in the body of a method declaration node will not be included
- * (the block will be empty) unless the source position falls somewhere
- * within the source range of that method declaration node. The same is true
- * for initializer declarations; the statements ordinarily found in the body
- * of initializer node will not be included unless the source position falls
- * somewhere within the source range of that initializer declaration node.
- * Field declarations are never abridged. Note that the AST for the body of
- * that one unabridged method (or initializer) is 100% complete; it has all
- * its statements, including any local or anonymous type declarations
- * embedded within them. When the the given position is not located within
- * the source range of any body declaration of a top-level type, the AST
- * returned will be a skeleton that includes nodes for all and only the major
- * declarations; this kind of AST is still quite useful because it contains
- * all the constructs that introduce names visible to the world outside the
- * javaScript unit.
- * </p>
- *
- * @param position a position into the corresponding body declaration
- */
- public void setFocalPosition(int position) {
- this.partial = true;
- this.focalPointPosition = position;
- }
-
- /**
- * Sets the kind of constructs to be parsed from the source.
- * Defaults to an entire javaScript unit.
- * <p>
- * When the parse is successful the result returned includes the ASTs for the
- * requested source:
- * <ul>
- * <li>{@link #K_JAVASCRIPT_UNIT K_JAVASCRIPT_UNIT}: The result node
- * is a {@link JavaScriptUnit}.</li>
- * <li>{@link #K_CLASS_BODY_DECLARATIONS K_CLASS_BODY_DECLARATIONS}: The result node
- * is a {@link TypeDeclaration} whose
- * {@link TypeDeclaration#bodyDeclarations() bodyDeclarations}
- * are the new trees. Other aspects of the type declaration are unspecified.</li>
- * <li>{@link #K_STATEMENTS K_STATEMENTS}: The result node is a
- * {@link Block Block} whose {@link Block#statements() statements}
- * are the new trees. Other aspects of the block are unspecified.</li>
- * <li>{@link #K_EXPRESSION K_EXPRESSION}: The result node is a subclass of
- * {@link Expression Expression}. Other aspects of the expression are unspecified.</li>
- * </ul>
- * The resulting AST node is rooted under (possibly contrived)
- * {@link JavaScriptUnit JavaScriptUnit} node, to allow the
- * client to retrieve the following pieces of information
- * available there:
- * <ul>
- * <li>{@linkplain JavaScriptUnit#getLineNumber(int) Line number map}. Line
- * numbers start at 1 and only cover the subrange scanned
- * (<code>source[offset]</code> through <code>source[offset+length-1]</code>).</li>
- * <li>{@linkplain JavaScriptUnit#getMessages() Compiler messages}
- * and {@linkplain JavaScriptUnit#getProblems() detailed problem reports}.
- * Character positions are relative to the start of
- * <code>source</code>; line positions are for the subrange scanned.</li>
- * <li>{@linkplain JavaScriptUnit#getCommentList() Comment list}
- * for the subrange scanned.</li>
- * </ul>
- * The contrived nodes do not have source positions. Other aspects of the
- * {@link JavaScriptUnit JavaScriptUnit} node are unspecified, including
- * the exact arrangment of intervening nodes.
- * </p>
- * <p>
- * Lexical or syntax errors detected while parsing can result in
- * a result node being marked as {@link ASTNode#MALFORMED MALFORMED}.
- * In more severe failure cases where the parser is unable to
- * recognize the input, this method returns
- * a {@link JavaScriptUnit JavaScriptUnit} node with at least the
- * validator messages.
- * </p>
- * <p>Each node in the subtree (other than the contrived nodes)
- * carries source range(s) information relating back
- * to positions in the given source (the given source itself
- * is not remembered with the AST).
- * The source range usually begins at the first character of the first token
- * corresponding to the node; leading whitespace and comments are <b>not</b>
- * included. The source range usually extends through the last character of
- * the last token corresponding to the node; trailing whitespace and
- * comments are <b>not</b> included. There are a handful of exceptions
- * (including the various body declarations); the
- * specification for these node type spells out the details.
- * Source ranges nest properly: the source range for a child is always
- * within the source range of its parent, and the source ranges of sibling
- * nodes never overlap.
- * </p>
- * <p>
- * Binding information is only computed when <code>kind</code> is
- * <code>K_JAVASCRIPT_UNIT</code>.
- * </p>
- *
- * @param kind the kind of construct to parse: one of
- * {@link #K_JAVASCRIPT_UNIT},
- * {@link #K_CLASS_BODY_DECLARATIONS},
- * {@link #K_EXPRESSION},
- * {@link #K_STATEMENTS}
- */
- public void setKind(int kind) {
- if ((kind != K_COMPILATION_UNIT)
- && (kind != K_CLASS_BODY_DECLARATIONS)
- && (kind != K_EXPRESSION)
- && (kind != K_STATEMENTS)) {
- throw new IllegalArgumentException();
- }
- this.astKind = kind;
- }
-
- /**
- * Sets the source code to be parsed.
- *
- * @param source the source string to be parsed,
- * or <code>null</code> if none
- */
- public void setSource(char[] source) {
- this.rawSource = source;
- // clear the type root
- this.typeRoot = null;
- }
-
- /**
- * Sets the source code to be parsed.
- * This method automatically sets the project (and compiler
- * options) based on the given javaScript unit, in a manner
- * equivalent to <code>setProject(source.getJavaProject())</code>
- *
- * @param source the JavaScript model javaScript unit whose source code
- * is to be parsed, or <code>null</code> if none
- */
- public void setSource(IJavaScriptUnit source) {
- setSource((ITypeRoot)source);
- }
-
- /**
- * Sets the source code to be parsed.
- * <p>This method automatically sets the project (and compiler
- * options) based on the given javaScript unit, in a manner
- * equivalent to <code>setProject(source.getJavaProject())</code>.</p>
- *
- * @param source the JavaScript file whose corresponding source code
- * is to be parsed, or <code>null</code> if none
- */
- public void setSource(IClassFile source) {
- setSource((ITypeRoot)source);
- }
-
- /**
- * Sets the source code to be parsed.
- * <p>This method automatically sets the project (and compiler
- * options) based on the given javaScript unit, in a manner
- * equivalent to <code>setProject(source.getJavaProject())</code>.</p>
- *
- * @param source the JavaScript model javaScript unit whose corresponding source code
- * is to be parsed, or <code>null</code> if none
- */
- public void setSource(ITypeRoot source) {
- this.typeRoot = source;
- // clear the raw source
- this.rawSource = null;
- if (source != null) {
- this.project = source.getJavaScriptProject();
- Map options = this.project.getOptions(true);
- options.remove(JavaScriptCore.COMPILER_TASK_TAGS); // no need to parse task tags
- this.compilerOptions = options;
- }
- }
-
- /**
- * Sets the subrange of the source code to be parsed.
- * By default, the entire source string will be parsed
- * (<code>offset</code> 0 and <code>length</code> -1).
- *
- * @param offset the index of the first character to parse
- * @param length the number of characters to parse, or -1 if
- * the remainder of the source string is
- */
- public void setSourceRange(int offset, int length) {
- if (offset < 0 || length < -1) {
- throw new IllegalArgumentException();
- }
- this.sourceOffset = offset;
- this.sourceLength = length;
- }
-
- /**
- * Requests that the validator should perform statements recovery.
- * When statements recovery is enabled the validator tries to create statement nodes
- * from code containing syntax errors
- * <p>
- * Default to <code>false</code>.
- * </p>
- *
- * @param enabled <code>true</code> if statements containing syntax errors are wanted,
- * and <code>false</code> if these statements aren't wanted.
- *
- */
- public void setStatementsRecovery(boolean enabled) {
- this.statementsRecovery = enabled;
- }
-
- /**
- * Sets the working copy owner using when resolving bindings, where
- * <code>null</code> means the primary owner. Defaults to the primary owner.
- *
- * @param owner the owner of working copies that take precedence over underlying
- * javaScript units, or <code>null</code> if the primary owner should be used
- */
- public void setWorkingCopyOwner(WorkingCopyOwner owner) {
- if (owner == null) {
- this.workingCopyOwner = DefaultWorkingCopyOwner.PRIMARY;
- } else {
- this.workingCopyOwner = owner;
- }
- }
-
- /**
- * Sets the name of the javaScript unit that would hypothetically contains
- * the source string. This is used in conjunction with {@link #setSource(char[])}
- * and {@link #setProject(IJavaScriptProject) } to locate the javaScript unit relative to a JavaScript project.
- * Defaults to none (<code>null</code>).
- * <p>
- * The name of the javaScript unit must be supplied for resolving bindings.
- * This name should be suffixed by a dot ('.') followed by one of the
- * {@link JavaScriptCore#getJavaScriptLikeExtensions() JavaScript-like extensions}.
- *
- * <p>This name must represent the full path of the unit inside the given project. For example, if the source
- * declares a public class named "Foo" in a project "P", the name of the javaScript unit must be
- * "/P/Foo.js". If the source declares a public class name "Bar" in a package "p1.p2" in a project "P",
- * the name of the javaScript unit must be "/P/p1/p2/Bar.js".</p>
- *
- * @param unitName the name of the javaScript unit that would contain the source
- * string, or <code>null</code> if none
- */
- public void setUnitName(String unitName) {
- this.unitName = unitName;
- }
-
- /**
- * Sets the JavaScript project used when resolving bindings.
- * This method automatically sets the compiler
- * options based on the given project:
- * <pre>
- * setCompilerOptions(project.getOptions(true));
- * </pre>
- * See {@link #setCompilerOptions(Map)} for a discussion of
- * the pros and cons of using these options vs specifying
- * validator options explicitly.
- * This setting is used in conjunction with <code>setSource(char[])</code>.
- * For the purposes of resolving bindings, types declared in the
- * source string will hide types by the same name available
- * through the includepath of the given project.
- * Defaults to none (<code>null</code>).
- *
- * @param project the JavaScript project used to resolve names, or
- * <code>null</code> if none
- */
- public void setProject(IJavaScriptProject project) {
- this.project = project;
- if (project != null) {
- Map options = project.getOptions(true);
- options.remove(JavaScriptCore.COMPILER_TASK_TAGS); // no need to parse task tags
- this.compilerOptions = options;
- }
- }
-
- /**
- * Creates an abstract syntax tree.
- * <p>
- * A successful call to this method returns all settings to their
- * default values so the object is ready to be reused.
- * </p>
- *
- * @param monitor the progress monitor used to report progress and request cancelation,
- * or <code>null</code> if none
- * @return an AST node whose type depends on the kind of parse
- * requested, with a fallback to a <code>JavaScriptUnit</code>
- * in the case of severe parsing errors
- * @exception IllegalStateException if the settings provided
- * are insufficient, contradictory, or otherwise unsupported
- */
- public ASTNode createAST(IProgressMonitor monitor) {
- ASTNode result = null;
- if (monitor != null) monitor.beginTask("", 1); //$NON-NLS-1$
- try {
- if (this.rawSource == null && this.typeRoot == null) {
- throw new IllegalStateException("source not specified"); //$NON-NLS-1$
- }
- result = internalCreateAST(monitor);
- } finally {
- // re-init defaults to allow reuse (and avoid leaking)
- initializeDefaults();
- if (monitor != null) monitor.done();
- }
- return result;
- }
-
- /**
- * Creates ASTs for a batch of javaScript units.
- * When bindings are being resolved, processing a
- * batch of javaScript units is more efficient because much
- * of the work involved in resolving bindings can be shared.
- * <p>
- * When bindings are being resolved, all javaScript units must
- * come from the same JavaScript project, which must be set beforehand
- * with <code>setProject</code>.
- * The javaScript units are processed one at a time in no
- * specified order. For each of the javaScript units in turn,
- * <ul>
- * <li><code>ASTParser.createAST</code> is called to parse it
- * and create a corresponding AST. The calls to
- * <code>ASTParser.createAST</code> all employ the same settings.</li>
- * <li><code>ASTRequestor.acceptAST</code> is called passing
- * the javaScript unit and the corresponding AST to
- * <code>requestor</code>.
- * </li>
- * </ul>
- * Note only ASTs from the given javaScript units are reported
- * to the requestor. If additional javaScript units are required to
- * resolve the original ones, the corresponding ASTs are <b>not</b>
- * reported to the requestor.
- * </p>
- * <p>
- * Note also the following parser parameters are used, regardless of what
- * may have been specified:
- * <ul>
- * <li>The {@linkplain #setKind(int) parser kind} is <code>K_JAVASCRIPT_UNIT</code></li>
- * <li>The {@linkplain #setSourceRange(int,int) source range} is <code>(0, -1)</code></li>
- * <li>The {@linkplain #setFocalPosition(int) focal position} is not set</li>
- * </ul>
- * </p>
- * <p>
- * The <code>bindingKeys</code> parameter specifies bindings keys
- * ({@link IBinding#getKey()}) that are to be looked up. These keys may
- * be for elements either inside or outside the set of compilation
- * units being processed. When bindings are being resolved,
- * the keys and corresponding bindings (or <code>null</code> if none) are
- * passed to <code>ASTRequestor.acceptBinding</code>. Note that binding keys
- * for elements outside the set of javaScript units being processed are looked up
- * after all <code>ASTRequestor.acceptAST</code> callbacks have been made.
- * Binding keys for elements inside the set of javaScript units being processed
- * are looked up and reported right after the corresponding
- * <code>ASTRequestor.acceptAST</code> callback has been made.
- * No <code>ASTRequestor.acceptBinding</code> callbacks are made unless
- * bindings are being resolved.
- * </p>
- * <p>
- * A successful call to this method returns all settings to their
- * default values so the object is ready to be reused.
- * </p>
- *
- * @param compilationUnits the javaScript units to create ASTs for
- * @param bindingKeys the binding keys to create bindings for
- * @param requestor the AST requestor that collects abtract syntax trees and bindings
- * @param monitor the progress monitor used to report progress and request cancelation,
- * or <code>null</code> if none
- * @exception IllegalStateException if the settings provided
- * are insufficient, contradictory, or otherwise unsupported
- */
- public void createASTs(IJavaScriptUnit[] compilationUnits, String[] bindingKeys, ASTRequestor requestor, IProgressMonitor monitor) {
- try {
- int flags = 0;
- if (this.statementsRecovery) flags |= IJavaScriptUnit.ENABLE_STATEMENTS_RECOVERY;
- if (this.resolveBindings) {
- if (this.project == null)
- throw new IllegalStateException("project not specified"); //$NON-NLS-1$
- if (this.bindingsRecovery) flags |= IJavaScriptUnit.ENABLE_BINDINGS_RECOVERY;
- JavaScriptUnitResolver.resolve(compilationUnits, bindingKeys, requestor, this.apiLevel, this.compilerOptions, this.project, this.workingCopyOwner, flags, monitor);
- } else {
- JavaScriptUnitResolver.parse(compilationUnits, requestor, this.apiLevel, this.compilerOptions, flags, monitor);
- }
- } finally {
- // re-init defaults to allow reuse (and avoid leaking)
- initializeDefaults();
- }
- }
-
- /**
- * Creates bindings for a batch of JavaScript elements. These elements are either
- * enclosed in {@link IJavaScriptUnit}s or in {@link IClassFile}s.
- * <p>
- * All enclosing javaScript units must
- * come from the same JavaScript project, which must be set beforehand
- * with <code>setProject</code>.
- * </p>
- * <p>
- * All elements must exist. If one doesn't exist, an <code>IllegalStateException</code>
- * is thrown.
- * </p>
- * <p>
- * The returned array has the same size as the given elements array. At a given position
- * it contains the binding of the corresponding JavaScript element, or <code>null</code>
- * if no binding could be created.
- * </p>
- * <p>
- * Note also the following parser parameters are used, regardless of what
- * may have been specified:
- * <ul>
- * <li>The {@linkplain #setResolveBindings(boolean) binding resolution flag} is <code>true</code></li>
- * <li>The {@linkplain #setKind(int) parser kind} is <code>K_JAVASCRIPT_UNIT</code></li>
- * <li>The {@linkplain #setSourceRange(int,int) source range} is <code>(0, -1)</code></li>
- * <li>The {@linkplain #setFocalPosition(int) focal position} is not set</li>
- * </ul>
- * </p>
- * <p>
- * A successful call to this method returns all settings to their
- * default values so the object is ready to be reused.
- * </p>
- *
- * @param elements the JavaScript elements to create bindings for
- * @return the bindings for the given JavaScript elements, possibly containing <code>null</code>s
- * if some bindings could not be created
- * @exception IllegalStateException if the settings provided
- * are insufficient, contradictory, or otherwise unsupported
- */
- public IBinding[] createBindings(IJavaScriptElement[] elements, IProgressMonitor monitor) {
- try {
- if (this.project == null)
- throw new IllegalStateException("project not specified"); //$NON-NLS-1$
- int flags = 0;
- if (this.statementsRecovery) flags |= IJavaScriptUnit.ENABLE_STATEMENTS_RECOVERY;
- if (this.bindingsRecovery) flags |= IJavaScriptUnit.ENABLE_BINDINGS_RECOVERY;
- return JavaScriptUnitResolver.resolve(elements, this.apiLevel, this.compilerOptions, this.project, this.workingCopyOwner,flags, monitor);
- } finally {
- // re-init defaults to allow reuse (and avoid leaking)
- initializeDefaults();
- }
- }
-
- private ASTNode internalCreateAST(IProgressMonitor monitor) {
- boolean needToResolveBindings = this.resolveBindings;
- switch(this.astKind) {
- case K_CLASS_BODY_DECLARATIONS :
- case K_EXPRESSION :
- case K_STATEMENTS :
- if (this.rawSource != null) {
- if (this.sourceOffset + this.sourceLength > this.rawSource.length) {
- throw new IllegalStateException();
- }
- return internalCreateASTForKind();
- }
- break;
- case K_COMPILATION_UNIT :
- CompilationUnitDeclaration compilationUnitDeclaration = null;
- try {
- NodeSearcher searcher = null;
- org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit sourceUnit = null;
- WorkingCopyOwner wcOwner = this.workingCopyOwner;
- if (this.typeRoot instanceof IJavaScriptUnit) {
- /*
- * this.compilationUnitSource is an instance of org.eclipse.wst.jsdt.internal.core.CompilationUnit that implements
- * both org.eclipse.wst.jsdt.core.IJavaScriptUnit and org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit
- */
- sourceUnit = (org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit) this.typeRoot;
- /*
- * use a BasicCompilation that caches the source instead of using the compilationUnitSource directly
- * (if it is a working copy, the source can change between the parse and the AST convertion)
- * (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=75632)
- */
- sourceUnit = new BasicCompilationUnit(sourceUnit.getContents(), sourceUnit.getPackageName(), new String(sourceUnit.getFileName()), this.project);
- wcOwner = ((IJavaScriptUnit) this.typeRoot).getOwner();
- } else if (this.typeRoot instanceof IClassFile) {
- try {
- String sourceString = this.typeRoot.getSource();
- if (sourceString == null) {
- throw new IllegalStateException();
- }
- PackageFragment packageFragment = (PackageFragment) this.typeRoot.getParent();
-// BinaryType type = (BinaryType) this.typeRoot.findPrimaryType();
- char[] fileName =this.typeRoot.getElementName().toCharArray();
-// IBinaryType binaryType = (IBinaryType) type.getElementInfo();
-// // file name is used to recreate the JavaScript element, so it has to be the toplevel .class file name
-// char[] fileName = type.getElementName().toCharArray();
-// int firstDollar = CharOperation.indexOf('$', fileName);
-// if (firstDollar != -1) {
-// char[] suffix = SuffixConstants.SUFFIX_class;
-// int suffixLength = suffix.length;
-// char[] newFileName = new char[firstDollar + suffixLength];
-// System.arraycopy(fileName, 0, newFileName, 0, firstDollar);
-// System.arraycopy(suffix, 0, newFileName, firstDollar, suffixLength);
-// fileName = newFileName;
-// }
- sourceUnit = new BasicCompilationUnit(sourceString.toCharArray(), Util.toCharArrays(packageFragment.names), new String(fileName), this.project);
- } catch(JavaScriptModelException e) {
- // an error occured accessing the javaScript element
- throw new IllegalStateException();
- }
- } else if (this.rawSource != null) {
- needToResolveBindings = this.resolveBindings && this.unitName != null && this.project != null && this.compilerOptions != null;
- sourceUnit = new BasicCompilationUnit(this.rawSource, null, this.unitName == null ? "" : this.unitName, this.project); //$NON-NLS-1$
- } else {
- throw new IllegalStateException();
- }
- if (this.partial) {
- searcher = new NodeSearcher(this.focalPointPosition);
- }
- int flags = 0;
- if (this.statementsRecovery) flags |= IJavaScriptUnit.ENABLE_STATEMENTS_RECOVERY;
- if (needToResolveBindings) {
- if (this.bindingsRecovery) flags |= IJavaScriptUnit.ENABLE_BINDINGS_RECOVERY;
- try {
- // parse and resolve
- compilationUnitDeclaration =
- JavaScriptUnitResolver.resolve(
- sourceUnit,
- this.project,
- searcher,
- this.compilerOptions,
- this.workingCopyOwner,
- flags,
- monitor);
- } catch (JavaScriptModelException e) {
- flags &= ~IJavaScriptUnit.ENABLE_BINDINGS_RECOVERY;
- compilationUnitDeclaration = JavaScriptUnitResolver.parse(
- sourceUnit,
- searcher,
- this.compilerOptions,
- flags);
- needToResolveBindings = false;
- }
- } else {
- compilationUnitDeclaration = JavaScriptUnitResolver.parse(
- sourceUnit,
- searcher,
- this.compilerOptions,
- flags);
- needToResolveBindings = false;
- }
- JavaScriptUnit result = JavaScriptUnitResolver.convert(
- compilationUnitDeclaration,
- sourceUnit.getContents(),
- this.apiLevel,
- this.compilerOptions,
- needToResolveBindings,
- wcOwner,
- needToResolveBindings ? new DefaultBindingResolver.BindingTables() : null,
- flags,
- monitor);
- result.setTypeRoot(this.typeRoot);
- return result;
- } finally {
- if (compilationUnitDeclaration != null && this.resolveBindings) {
- compilationUnitDeclaration.cleanUp();
- if (compilationUnitDeclaration.scope!=null)
- compilationUnitDeclaration.scope.cleanup();
- }
- }
- }
- throw new IllegalStateException();
- }
-
- /**
- * Parses the given source between the bounds specified by the given offset (inclusive)
- * and the given length and creates and returns a corresponding abstract syntax tree.
- * <p>
- * When the parse is successful the result returned includes the ASTs for the
- * requested source:
- * <ul>
- * <li>{@link #K_CLASS_BODY_DECLARATIONS K_CLASS_BODY_DECLARATIONS}: The result node
- * is a {@link TypeDeclaration TypeDeclaration} whose
- * {@link TypeDeclaration#bodyDeclarations() bodyDeclarations}
- * are the new trees. Other aspects of the type declaration are unspecified.</li>
- * <li>{@link #K_STATEMENTS K_STATEMENTS}: The result node is a
- * {@link Block Block} whose {@link Block#statements() statements}
- * are the new trees. Other aspects of the block are unspecified.</li>
- * <li>{@link #K_EXPRESSION K_EXPRESSION}: The result node is a subclass of
- * {@link Expression Expression}. Other aspects of the expression are unspecified.</li>
- * </ul>
- * The resulting AST node is rooted under an contrived
- * {@link JavaScriptUnit JavaScriptUnit} node, to allow the
- * client to retrieve the following pieces of information
- * available there:
- * <ul>
- * <li>{@linkplain JavaScriptUnit#getLineNumber(int) Line number map}. Line
- * numbers start at 1 and only cover the subrange scanned
- * (<code>source[offset]</code> through <code>source[offset+length-1]</code>).</li>
- * <li>{@linkplain JavaScriptUnit#getMessages() Compiler messages}
- * and {@linkplain JavaScriptUnit#getProblems() detailed problem reports}.
- * Character positions are relative to the start of
- * <code>source</code>; line positions are for the subrange scanned.</li>
- * <li>{@linkplain JavaScriptUnit#getCommentList() Comment list}
- * for the subrange scanned.</li>
- * </ul>
- * The contrived nodes do not have source positions. Other aspects of the
- * {@link JavaScriptUnit JavaScriptUnit} node are unspecified, including
- * the exact arrangment of intervening nodes.
- * </p>
- * <p>
- * Lexical or syntax errors detected while parsing can result in
- * a result node being marked as {@link ASTNode#MALFORMED MALFORMED}.
- * In more severe failure cases where the parser is unable to
- * recognize the input, this method returns
- * a {@link JavaScriptUnit JavaScriptUnit} node with at least the
- * validator messages.
- * </p>
- * <p>Each node in the subtree (other than the contrived nodes)
- * carries source range(s) information relating back
- * to positions in the given source (the given source itself
- * is not remembered with the AST).
- * The source range usually begins at the first character of the first token
- * corresponding to the node; leading whitespace and comments are <b>not</b>
- * included. The source range usually extends through the last character of
- * the last token corresponding to the node; trailing whitespace and
- * comments are <b>not</b> included. There are a handful of exceptions
- * (including the various body declarations); the
- * specification for these node type spells out the details.
- * Source ranges nest properly: the source range for a child is always
- * within the source range of its parent, and the source ranges of sibling
- * nodes never overlap.
- * </p>
- * <p>
- * This method does not compute binding information; all <code>resolveBinding</code>
- * methods applied to nodes of the resulting AST return <code>null</code>.
- * </p>
- *
- * @return an AST node whose type depends on the kind of parse
- * requested, with a fallback to a <code>JavaScriptUnit</code>
- * in the case of severe parsing errors
- * @see ASTNode#getStartPosition()
- * @see ASTNode#getLength()
- */
- private ASTNode internalCreateASTForKind() {
- final ASTConverter converter = new ASTConverter(this.compilerOptions, false, null);
- converter.compilationUnitSource = this.rawSource;
- converter.compilationUnitSourceLength = this.rawSource.length;
- converter.scanner.setSource(this.rawSource);
-
- AST ast = AST.newAST(this.apiLevel);
- ast.setDefaultNodeFlag(ASTNode.ORIGINAL);
- ast.setBindingResolver(new BindingResolver());
- if (this.statementsRecovery) {
- ast.setFlag(IJavaScriptUnit.ENABLE_STATEMENTS_RECOVERY);
- }
- converter.setAST(ast);
- CodeSnippetParsingUtil codeSnippetParsingUtil = new CodeSnippetParsingUtil();
- JavaScriptUnit compilationUnit = ast.newJavaScriptUnit();
- if (this.sourceLength == -1) {
- this.sourceLength = this.rawSource.length;
- }
- switch(this.astKind) {
- case K_STATEMENTS :
- ConstructorDeclaration constructorDeclaration = codeSnippetParsingUtil.parseStatements(this.rawSource, this.sourceOffset, this.sourceLength, this.compilerOptions, true, this.statementsRecovery);
- RecoveryScannerData data = constructorDeclaration.compilationResult.recoveryScannerData;
- if(data != null) {
- Scanner scanner = converter.scanner;
- converter.scanner = new RecoveryScanner(scanner, data.removeUnused());
- converter.docParser.scanner = converter.scanner;
- converter.scanner.setSource(scanner.source);
- }
- RecordedParsingInformation recordedParsingInformation = codeSnippetParsingUtil.recordedParsingInformation;
- int[][] comments = recordedParsingInformation.commentPositions;
- if (comments != null) {
- converter.buildCommentsTable(compilationUnit, comments);
- }
- compilationUnit.setLineEndTable(recordedParsingInformation.lineEnds);
- Block block = ast.newBlock();
- block.setSourceRange(this.sourceOffset, this.sourceOffset + this.sourceLength);
- org.eclipse.wst.jsdt.internal.compiler.ast.Statement[] statements = constructorDeclaration.statements;
- if (statements != null) {
- int statementsLength = statements.length;
- for (int i = 0; i < statementsLength; i++) {
- if (statements[i] instanceof org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration) {
- converter.checkAndAddMultipleLocalDeclaration(statements, i, block.statements());
- } else {
- Statement statement = converter.convert(statements[i]);
- if (statement != null) {
- block.statements().add(statement);
- }
- }
- }
- }
- rootNodeToCompilationUnit(ast, compilationUnit, block, recordedParsingInformation, data);
- ast.setDefaultNodeFlag(0);
- ast.setOriginalModificationCount(ast.modificationCount());
- return block;
- case K_EXPRESSION :
- org.eclipse.wst.jsdt.internal.compiler.ast.Expression expression = codeSnippetParsingUtil.parseExpression(this.rawSource, this.sourceOffset, this.sourceLength, this.compilerOptions, true);
- recordedParsingInformation = codeSnippetParsingUtil.recordedParsingInformation;
- comments = recordedParsingInformation.commentPositions;
- if (comments != null) {
- converter.buildCommentsTable(compilationUnit, comments);
- }
- compilationUnit.setLineEndTable(recordedParsingInformation.lineEnds);
- if (expression != null) {
- Expression expression2 = converter.convert(expression);
- rootNodeToCompilationUnit(expression2.getAST(), compilationUnit, expression2, codeSnippetParsingUtil.recordedParsingInformation, null);
- ast.setDefaultNodeFlag(0);
- ast.setOriginalModificationCount(ast.modificationCount());
- return expression2;
- } else {
- CategorizedProblem[] problems = recordedParsingInformation.problems;
- if (problems != null) {
- compilationUnit.setProblems(problems);
- }
- ast.setDefaultNodeFlag(0);
- ast.setOriginalModificationCount(ast.modificationCount());
- return compilationUnit;
- }
- case K_CLASS_BODY_DECLARATIONS :
- final org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode[] nodes = codeSnippetParsingUtil.parseClassBodyDeclarations(this.rawSource, this.sourceOffset, this.sourceLength, this.compilerOptions, true);
- recordedParsingInformation = codeSnippetParsingUtil.recordedParsingInformation;
- comments = recordedParsingInformation.commentPositions;
- if (comments != null) {
- converter.buildCommentsTable(compilationUnit, comments);
- }
- compilationUnit.setLineEndTable(recordedParsingInformation.lineEnds);
- if (nodes != null) {
-// TypeDeclaration typeDeclaration = converter.convert(nodes);
-// typeDeclaration.setSourceRange(this.sourceOffset, this.sourceOffset + this.sourceLength);
-// rootNodeToCompilationUnit(typeDeclaration.getAST(), compilationUnit, typeDeclaration, codeSnippetParsingUtil.recordedParsingInformation, null);
- JavaScriptUnit compUnit=converter.convert(nodes, compilationUnit);
- rootNodeToCompilationUnit(compUnit.getAST(), compilationUnit, compUnit, codeSnippetParsingUtil.recordedParsingInformation, null);
- ast.setDefaultNodeFlag(0);
- ast.setOriginalModificationCount(ast.modificationCount());
- return compilationUnit;
- } else {
- CategorizedProblem[] problems = recordedParsingInformation.problems;
- if (problems != null) {
- compilationUnit.setProblems(problems);
- }
- ast.setDefaultNodeFlag(0);
- ast.setOriginalModificationCount(ast.modificationCount());
- return compilationUnit;
- }
- }
- throw new IllegalStateException();
- }
-
- private void propagateErrors(ASTNode astNode, CategorizedProblem[] problems, RecoveryScannerData data) {
- astNode.accept(new ASTSyntaxErrorPropagator(problems));
- if (data != null) {
- astNode.accept(new ASTRecoveryPropagator(problems, data));
- }
- }
-
- private void rootNodeToCompilationUnit(AST ast, JavaScriptUnit compilationUnit, ASTNode node, RecordedParsingInformation recordedParsingInformation, RecoveryScannerData data) {
- final int problemsCount = recordedParsingInformation.problemsCount;
- switch(node.getNodeType()) {
- case ASTNode.BLOCK :
- {
- Block block = (Block) node;
- if (problemsCount != 0) {
- // propagate and record problems
- final CategorizedProblem[] problems = recordedParsingInformation.problems;
- propagateErrors(block, problems, data);
- compilationUnit.setProblems(problems);
- }
- TypeDeclaration typeDeclaration = ast.newTypeDeclaration();
- Initializer initializer = ast.newInitializer();
- initializer.setBody(block);
- typeDeclaration.bodyDeclarations().add(initializer);
- compilationUnit.types().add(typeDeclaration);
- }
- break;
- case ASTNode.JAVASCRIPT_UNIT :
- {
- JavaScriptUnit compUnit = (JavaScriptUnit) node;
- if (problemsCount != 0) {
- // propagate and record problems
- final CategorizedProblem[] problems = recordedParsingInformation.problems;
- for (int i = 0, max = compUnit.statements().size(); i < max; i++) {
- propagateErrors((ASTNode) compUnit.statements().get(i), problems, data);
- }
- compilationUnit.setProblems(problems);
- }
- if (compilationUnit!=node)
- for (int i = 0, max = compUnit.statements().size(); i < max; i++)
- compilationUnit.statements().add(compUnit.statements().get(i));
- }
- break;
- case ASTNode.TYPE_DECLARATION :
- {
- TypeDeclaration typeDeclaration = (TypeDeclaration) node;
- if (problemsCount != 0) {
- // propagate and record problems
- final CategorizedProblem[] problems = recordedParsingInformation.problems;
- propagateErrors(typeDeclaration, problems, data);
- compilationUnit.setProblems(problems);
- }
- compilationUnit.types().add(typeDeclaration);
- }
- break;
- default :
- if (node instanceof Expression) {
- Expression expression = (Expression) node;
- if (problemsCount != 0) {
- // propagate and record problems
- final CategorizedProblem[] problems = recordedParsingInformation.problems;
- propagateErrors(expression, problems, data);
- compilationUnit.setProblems(problems);
- }
- ExpressionStatement expressionStatement = ast.newExpressionStatement(expression);
- Block block = ast.newBlock();
- block.statements().add(expressionStatement);
- Initializer initializer = ast.newInitializer();
- initializer.setBody(block);
- TypeDeclaration typeDeclaration = ast.newTypeDeclaration();
- typeDeclaration.bodyDeclarations().add(initializer);
- compilationUnit.types().add(typeDeclaration);
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ASTRecoveryPropagator.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ASTRecoveryPropagator.java
deleted file mode 100644
index 9853413e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ASTRecoveryPropagator.java
+++ /dev/null
@@ -1,382 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 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.dom;
-
-import java.util.List;
-import java.util.Vector;
-
-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.UndefinedLiteral;
-import org.eclipse.wst.jsdt.internal.compiler.parser.RecoveryScanner;
-import org.eclipse.wst.jsdt.internal.compiler.parser.RecoveryScannerData;
-import org.eclipse.wst.jsdt.internal.compiler.parser.TerminalTokens;
-import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfObjectToIntArray;
-
-/**
- * Internal AST visitor for propagating syntax errors.
- */
-class ASTRecoveryPropagator extends DefaultASTVisitor {
- private static final int NOTHING = -1;
- HashtableOfObjectToIntArray endingTokens = new HashtableOfObjectToIntArray();
- {
- this.endingTokens.put(AnonymousClassDeclaration.class, new int[]{TerminalTokens.TokenNameRBRACE});
- this.endingTokens.put(ArrayAccess.class, new int[]{TerminalTokens.TokenNameRBRACKET});
- this.endingTokens.put(ArrayCreation.class, new int[]{NOTHING, TerminalTokens.TokenNameRBRACKET});
- this.endingTokens.put(ArrayInitializer.class, new int[]{TerminalTokens.TokenNameRBRACKET});
- this.endingTokens.put(ArrayType.class, new int[]{TerminalTokens.TokenNameRBRACKET});
- this.endingTokens.put(Block.class, new int[]{TerminalTokens.TokenNameRBRACE});
- this.endingTokens.put(BooleanLiteral.class, new int[]{TerminalTokens.TokenNamefalse, TerminalTokens.TokenNametrue});
- this.endingTokens.put(BreakStatement.class, new int[]{TerminalTokens.TokenNameSEMICOLON});
- this.endingTokens.put(CharacterLiteral.class, new int[]{TerminalTokens.TokenNameCharacterLiteral});
- this.endingTokens.put(RegularExpressionLiteral.class, new int[]{TerminalTokens.TokenNameRegExLiteral});
- this.endingTokens.put(ClassInstanceCreation.class, new int[]{TerminalTokens.TokenNameRBRACE, TerminalTokens.TokenNameRPAREN});
- this.endingTokens.put(ConstructorInvocation.class, new int[]{TerminalTokens.TokenNameSEMICOLON});
- this.endingTokens.put(ContinueStatement.class, new int[]{TerminalTokens.TokenNameSEMICOLON});
- this.endingTokens.put(DoStatement.class, new int[]{TerminalTokens.TokenNameRPAREN});
- this.endingTokens.put(EmptyStatement.class, new int[]{TerminalTokens.TokenNameSEMICOLON});
- this.endingTokens.put(ExpressionStatement.class, new int[]{TerminalTokens.TokenNameSEMICOLON});
- this.endingTokens.put(FieldDeclaration.class, new int[]{TerminalTokens.TokenNameSEMICOLON});
- this.endingTokens.put(ImportDeclaration.class, new int[]{TerminalTokens.TokenNameSEMICOLON});
- this.endingTokens.put(Initializer.class, new int[]{TerminalTokens.TokenNameRBRACE});
- this.endingTokens.put(FunctionDeclaration.class, new int[]{NOTHING, TerminalTokens.TokenNameSEMICOLON});
- this.endingTokens.put(FunctionInvocation.class, new int[]{TerminalTokens.TokenNameRPAREN});
- this.endingTokens.put(NullLiteral.class, new int[]{TerminalTokens.TokenNamenull});
- this.endingTokens.put(UndefinedLiteral.class, new int[]{TerminalTokens.TokenNameundefined});
- this.endingTokens.put(NumberLiteral.class, new int[]{TerminalTokens.TokenNameIntegerLiteral, TerminalTokens.TokenNameLongLiteral, TerminalTokens.TokenNameFloatingPointLiteral, TerminalTokens.TokenNameDoubleLiteral});
- this.endingTokens.put(PackageDeclaration.class, new int[]{TerminalTokens.TokenNameSEMICOLON});
- this.endingTokens.put(ParenthesizedExpression.class, new int[]{TerminalTokens.TokenNameRPAREN});
- this.endingTokens.put(PostfixExpression.class, new int[]{TerminalTokens.TokenNamePLUS_PLUS, TerminalTokens.TokenNameMINUS_MINUS});
- this.endingTokens.put(PrimitiveType.class, new int[]{TerminalTokens.TokenNamebyte, TerminalTokens.TokenNameshort, TerminalTokens.TokenNamechar, TerminalTokens.TokenNameint, TerminalTokens.TokenNamelong, TerminalTokens.TokenNamefloat, TerminalTokens.TokenNameboolean, TerminalTokens.TokenNamedouble, TerminalTokens.TokenNamevoid});
- this.endingTokens.put(ReturnStatement.class, new int[]{TerminalTokens.TokenNameSEMICOLON});
- this.endingTokens.put(SimpleName.class, new int[]{TerminalTokens.TokenNameIdentifier});
- this.endingTokens.put(SingleVariableDeclaration.class, new int[]{TerminalTokens.TokenNameSEMICOLON});
- this.endingTokens.put(StringLiteral.class, new int[]{TerminalTokens.TokenNameStringLiteral});
- this.endingTokens.put(SuperConstructorInvocation.class, new int[]{TerminalTokens.TokenNameSEMICOLON});
- this.endingTokens.put(SuperMethodInvocation.class, new int[]{TerminalTokens.TokenNameRPAREN});
- this.endingTokens.put(SwitchCase.class, new int[]{TerminalTokens.TokenNameCOLON});
- this.endingTokens.put(SwitchStatement.class, new int[]{TerminalTokens.TokenNameRBRACE});
- this.endingTokens.put(ThisExpression.class, new int[]{TerminalTokens.TokenNamethis});
- this.endingTokens.put(ThrowStatement.class, new int[]{TerminalTokens.TokenNameSEMICOLON});
- this.endingTokens.put(TypeDeclaration.class, new int[]{TerminalTokens.TokenNameRBRACE});
- this.endingTokens.put(TypeLiteral.class, new int[]{TerminalTokens.TokenNameclass});
- this.endingTokens.put(VariableDeclarationStatement.class, new int[]{TerminalTokens.TokenNameSEMICOLON});
- }
-
- private CategorizedProblem[] problems;
- private boolean[] usedOrIrrelevantProblems;
-
- private RecoveryScannerData data;
- private int blockDepth = 0;
- private int lastEnd;
-
- private int[] insertedTokensKind;
- private int[] insertedTokensPosition;
- private boolean[] insertedTokensFlagged;
-
- private boolean[] removedTokensFlagged;
- private boolean[] replacedTokensFlagged;
-
- private Vector stack = new Vector();
-
- ASTRecoveryPropagator(CategorizedProblem[] problems, RecoveryScannerData data) {
- // visit Javadoc.tags() as well
- this.problems = problems;
- this.usedOrIrrelevantProblems = new boolean[problems.length];
-
- this.data = data;
-
- if(this.data != null) {
-
- int length = 0;
- for (int i = 0; i < data.insertedTokensPtr + 1; i++) {
- length += data.insertedTokens[i].length;
- }
- this.insertedTokensKind = new int[length];
- this.insertedTokensPosition = new int[length];
- this.insertedTokensFlagged = new boolean[length];
- int tokenCount = 0;
- for (int i = 0; i < data.insertedTokensPtr + 1; i++) {
- for (int j = 0; j < data.insertedTokens[i].length; j++) {
- this.insertedTokensKind[tokenCount] = data.insertedTokens[i][j];
- this.insertedTokensPosition[tokenCount] = data.insertedTokensPosition[i];
- tokenCount++;
- }
- }
-
- if(data.removedTokensPtr != -1) {
- this.removedTokensFlagged = new boolean[data.removedTokensPtr + 1];
- }
- if(data.replacedTokensPtr != -1) {
- this.replacedTokensFlagged = new boolean[data.replacedTokensPtr + 1];
- }
- }
- }
-
- public void endVisit(Block node) {
- this.blockDepth--;
- if(this.blockDepth <= 0) {
- flagNodeWithInsertedTokens();
- }
- super.endVisit(node);
- }
-
-
-
- public boolean visit(Block node) {
- boolean visitChildren = super.visit(node);
- this.blockDepth++;
- return visitChildren;
- }
-
- protected boolean visitNode(ASTNode node) {
- if(this.blockDepth > 0) {
- if (node instanceof InferredType)
- return true;
- int start = node.getStartPosition();
- int end = start + node.getLength() - 1;
-
- // continue to visit the node only if it contains tokens modifications
-
- if(this.insertedTokensFlagged != null) {
- for (int i = 0; i < this.insertedTokensFlagged.length; i++) {
- if(this.insertedTokensPosition[i] >= start &&
- this.insertedTokensPosition[i] <= end) {
- return true;
- }
- }
- }
-
- if(this.removedTokensFlagged != null) {
- for (int i = 0; i <= this.data.removedTokensPtr; i++) {
- if(this.data.removedTokensStart[i] >= start &&
- this.data.removedTokensEnd[i] <= end) {
- return true;
- }
- }
- }
-
- if(this.replacedTokensFlagged != null) {
- for (int i = 0; i <= this.data.replacedTokensPtr; i++) {
- if(this.data.replacedTokensStart[i] >= start &&
- this.data.replacedTokensEnd[i] <= end) {
- return true;
- }
- }
- }
-
- return false;
- }
- return true;
- }
-
- protected void endVisitNode(ASTNode node) {
- int start = node.getStartPosition();
- int end = start + node.getLength() - 1;
-
- // is inside diet part of the ast
- if(this.blockDepth < 1) {
- if(this.markIncludedProblems(start, end)) {
- node.setFlags(node.getFlags() | ASTNode.RECOVERED);
- }
- } else {
- this.markIncludedProblems(start, end);
-
- if(this.insertedTokensFlagged != null) {
- if(this.lastEnd != end) {
- flagNodeWithInsertedTokens();
- }
- this.stack.add(node);
- }
-
- if(this.removedTokensFlagged != null) {
- for (int i = 0; i <= this.data.removedTokensPtr; i++) {
- if(!this.removedTokensFlagged[i] &&
- this.data.removedTokensStart[i] >= start &&
- this.data.removedTokensEnd[i] <= end) {
- node.setFlags(node.getFlags() | ASTNode.RECOVERED);
- this.removedTokensFlagged[i] = true;
- }
- }
- }
-
- if(this.replacedTokensFlagged != null) {
- for (int i = 0; i <= this.data.replacedTokensPtr; i++) {
- if(!this.replacedTokensFlagged[i] &&
- this.data.replacedTokensStart[i] >= start &&
- this.data.replacedTokensEnd[i] <= end) {
- node.setFlags(node.getFlags() | ASTNode.RECOVERED);
- this.replacedTokensFlagged[i] = true;
- }
- }
- }
- }
- this.lastEnd = end;
- }
-
- private void flagNodeWithInsertedTokens() {
- if(this.insertedTokensKind != null && this.insertedTokensKind.length > 0) {
- int s = this.stack.size();
- for (int i = s - 1; i > -1; i--) {
- flagNodesWithInsertedTokensAtEnd((ASTNode)this.stack.get(i));
- }
- for (int i = 0; i < s; i++) {
- flagNodesWithInsertedTokensInside((ASTNode)this.stack.get(i));
- }
- this.stack = new Vector();
- }
- }
-
- private boolean flagNodesWithInsertedTokensAtEnd(ASTNode node) {
- int[] expectedEndingToken = this.endingTokens.get(node.getClass());
- if (expectedEndingToken != null) {
- int start = node.getStartPosition();
- int end = start + node.getLength() - 1;
-
- boolean flagParent = false;
- done : for (int i = this.insertedTokensKind.length - 1; i > -1 ; i--) {
- if(!this.insertedTokensFlagged[i] &&
- this.insertedTokensPosition[i] == end){
- this.insertedTokensFlagged[i] = true;
- for (int j = 0; j < expectedEndingToken.length; j++) {
- if(expectedEndingToken[j] == this.insertedTokensKind[i]) {
- node.setFlags(node.getFlags() | ASTNode.RECOVERED);
- break done;
- }
- }
- flagParent = true;
- }
- }
-
- if(flagParent) {
- ASTNode parent = node.getParent();
- while (parent != null) {
- parent.setFlags(node.getFlags() | ASTNode.RECOVERED);
- if((parent.getStartPosition() + parent.getLength() - 1) != end) {
- parent = null;
- } else {
- parent = parent.getParent();
- }
- }
- }
- }
- return true;
- }
-
- private boolean flagNodesWithInsertedTokensInside(ASTNode node) {
- int start = node.getStartPosition();
- int end = start + node.getLength() - 1;
- for (int i = 0; i < this.insertedTokensKind.length; i++) {
- if(!this.insertedTokensFlagged[i] &&
- start <= this.insertedTokensPosition[i] &&
- this.insertedTokensPosition[i] < end){
- node.setFlags(node.getFlags() | ASTNode.RECOVERED);
- this.insertedTokensFlagged[i] = true;
- }
- }
- return true;
- }
-
- private boolean markIncludedProblems(int start, int end) {
- boolean foundProblems = false;
- next: for (int i = 0, max = this.problems.length; i < max; i++) {
- CategorizedProblem problem = this.problems[i];
-
- if(this.usedOrIrrelevantProblems[i]) continue next;
-
- switch(problem.getID()) {
- case IProblem.ParsingErrorOnKeywordNoSuggestion :
- case IProblem.ParsingErrorOnKeyword :
- case IProblem.ParsingError :
- case IProblem.ParsingErrorNoSuggestion :
- case IProblem.ParsingErrorInsertTokenBefore :
- case IProblem.ParsingErrorInsertTokenAfter :
- case IProblem.ParsingErrorDeleteToken :
- case IProblem.ParsingErrorDeleteTokens :
- case IProblem.ParsingErrorMergeTokens :
- case IProblem.ParsingErrorInvalidToken :
- case IProblem.ParsingErrorMisplacedConstruct :
- case IProblem.ParsingErrorReplaceTokens :
- case IProblem.ParsingErrorNoSuggestionForTokens :
- case IProblem.ParsingErrorUnexpectedEOF :
- case IProblem.ParsingErrorInsertToComplete :
- case IProblem.ParsingErrorInsertToCompleteScope :
- case IProblem.ParsingErrorInsertToCompletePhrase :
- case IProblem.EndOfSource :
- case IProblem.InvalidHexa :
- case IProblem.InvalidOctal :
- case IProblem.InvalidCharacterConstant :
- case IProblem.InvalidEscape :
- case IProblem.InvalidInput :
- case IProblem.InvalidUnicodeEscape :
- case IProblem.InvalidFloat :
- case IProblem.NullSourceString :
- case IProblem.UnterminatedString :
- case IProblem.UnterminatedComment :
- case IProblem.InvalidDigit :
- break;
- default:
- this.usedOrIrrelevantProblems[i] = true;
- continue next;
-
- }
-
- int problemStart = problem.getSourceStart();
- int problemEnd = problem.getSourceEnd();
- if ((start <= problemStart) && (problemStart <= end) ||
- (start <= problemEnd) && (problemEnd <= end)) {
- this.usedOrIrrelevantProblems[i] = true;
- foundProblems = true;
- }
- }
- return foundProblems;
- }
-
- public void endVisit(ExpressionStatement node) {
- endVisitNode(node);
- if ((node.getFlags() & ASTNode.RECOVERED) == 0) return;
- Expression expression = node.getExpression();
- if (expression.getNodeType() == ASTNode.ASSIGNMENT) {
- Assignment assignment = (Assignment) expression;
- Expression rightHandSide = assignment.getRightHandSide();
- if (rightHandSide.getNodeType() == ASTNode.SIMPLE_NAME) {
- SimpleName simpleName = (SimpleName) rightHandSide;
- if (CharOperation.equals(RecoveryScanner.FAKE_IDENTIFIER, simpleName.getIdentifier().toCharArray())) {
- Expression expression2 = assignment.getLeftHandSide();
- // unparent the expression to add it in the expression stateemnt
- expression2.setParent(null, null);
- expression2.setFlags(expression2.getFlags() | ASTNode.RECOVERED);
- node.setExpression(expression2);
- }
- }
- }
- }
-
- public void endVisit(VariableDeclarationStatement node) {
- endVisitNode(node);
- List fragments = node.fragments();
- for (int i = 0, max = fragments.size(); i <max; i++) {
- VariableDeclarationFragment fragment = (VariableDeclarationFragment) fragments.get(i);
- Expression expression = fragment.getInitializer();
- if (expression == null) continue;
- if ((expression.getFlags() & ASTNode.RECOVERED) == 0) continue;
- if (expression.getNodeType() == ASTNode.SIMPLE_NAME) {
- SimpleName simpleName = (SimpleName) expression;
- if (CharOperation.equals(RecoveryScanner.FAKE_IDENTIFIER, simpleName.getIdentifier().toCharArray())) {
- fragment.setInitializer(null);
- fragment.setFlags(node.getFlags() | ASTNode.RECOVERED);
- }
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ASTRequestor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ASTRequestor.java
deleted file mode 100644
index e5bca8d8..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ASTRequestor.java
+++ /dev/null
@@ -1,122 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.dom;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-
-/**
- * An AST requestor handles ASTs for javaScript units passed to
- * <code>ASTParser.createASTs</code>.
- * <p>
- * <code>ASTRequestor.acceptAST</code> is called for each of the
- * javaScript units passed to <code>ASTParser.createASTs</code>.
- * After all the javaScript units have been processed,
- * <code>ASTRequestor.acceptBindings</code> is called for each
- * of the binding keys passed to <code>ASTParser.createASTs</code>.
- * </p>
- * <p>
- * This class is intended to be subclassed by clients.
- * AST requestors are serially reusable, but neither reentrant nor
- * thread-safe.
- * </p>
- *
- * @see ASTParser#createASTs(IJavaScriptUnit[], String[], ASTRequestor, org.eclipse.core.runtime.IProgressMonitor)
- *
- * 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 ASTRequestor {
-
- /**
- * The javaScript unit resolver used to resolve bindings, or
- * <code>null</code> if none. Note that this field is non-null
- * only within the dynamic scope of a call to
- * <code>ASTParser.createASTs</code>.
- */
- JavaScriptUnitResolver compilationUnitResolver = null;
-
- /**
- * Creates a new instance.
- */
- protected ASTRequestor() {
- // do nothing
- }
-
- /**
- * Accepts an AST corresponding to the javaScript unit.
- * That is, <code>ast</code> is an AST for <code>source</code>.
- * <p>
- * The default implementation of this method does nothing.
- * Clients should override to process the resulting AST.
- * </p>
- *
- * @param source the javaScript unit the ast is coming from
- * @param ast the requested abtract syntax tree
- */
- public void acceptAST(IJavaScriptUnit source, JavaScriptUnit ast) {
- // do nothing
- }
-
- /**
- * Accepts a binding corresponding to the binding key.
- * That is, <code>binding</code> is the binding for
- * <code>bindingKey</code>; <code>binding</code> is <code>null</code>
- * if the key cannot be resolved.
- * <p>
- * The default implementation of this method does nothing.
- * Clients should override to process the resulting binding.
- * </p>
- *
- * @param bindingKey the key of the requested binding
- * @param binding the requested binding, or <code>null</code> if none
- */
- public void acceptBinding(String bindingKey, IBinding binding) {
- // do nothing
- }
-
- /**
- * Resolves bindings for the given binding keys.
- * The given binding keys must have been obtained earlier
- * using {@link IBinding#getKey()}.
- * <p>
- * If a binding key cannot be resolved, <code>null</code> is put in the resulting array.
- * Bindings can only be resolved in the dynamic scope of a <code>ASTParser.createASTs</code>,
- * and only if <code>ASTParser.resolveBindings(true)</code> was specified.
- * </p>
- * <p>
- * Caveat: During an <code>acceptAST</code> callback, there are implementation
- * limitations concerning the look up of binding keys representing local elements.
- * In some cases, the binding is unavailable, and <code>null</code> will be returned.
- * This is only an issue during an <code>acceptAST</code> callback, and only
- * when the binding key represents a local element (e.g., local variable,
- * local class, method declared in anonymous class). There is no such limitation
- * outside of <code>acceptAST</code> callbacks, or for top-level types and their
- * members even within <code>acceptAST</code> callbacks.
- * </p>
- *
- * @param bindingKeys the binding keys to look up
- * @return a list of bindings paralleling the <code>bindingKeys</code> parameter,
- * with <code>null</code> entries for keys that could not be resolved
- */
- public final IBinding[] createBindings(String[] bindingKeys) {
- int length = bindingKeys.length;
- IBinding[] result = new IBinding[length];
- for (int i = 0; i < length; i++) {
- result[i] = null;
- if (this.compilationUnitResolver != null) {
- result[i] = this.compilationUnitResolver.createBinding(bindingKeys[i]);
- }
- }
- return result;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ASTSyntaxErrorPropagator.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ASTSyntaxErrorPropagator.java
deleted file mode 100644
index 9ed91638..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ASTSyntaxErrorPropagator.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-
-/**
- * Internal AST visitor for propagating syntax errors.
- */
-class ASTSyntaxErrorPropagator extends ASTVisitor {
-
- private CategorizedProblem[] problems;
-
- ASTSyntaxErrorPropagator(CategorizedProblem[] problems) {
- // visit Javadoc.tags() as well
- super(true);
- this.problems = problems;
- }
-
- private boolean checkAndTagAsMalformed(ASTNode node) {
- boolean tagWithErrors = false;
- search: for (int i = 0, max = this.problems.length; i < max; i++) {
- CategorizedProblem problem = this.problems[i];
- switch(problem.getID()) {
- case IProblem.ParsingErrorOnKeywordNoSuggestion :
- case IProblem.ParsingErrorOnKeyword :
- case IProblem.ParsingError :
- case IProblem.ParsingErrorNoSuggestion :
- case IProblem.ParsingErrorInsertTokenBefore :
- case IProblem.ParsingErrorInsertTokenAfter :
- case IProblem.ParsingErrorDeleteToken :
- case IProblem.ParsingErrorDeleteTokens :
- case IProblem.ParsingErrorMergeTokens :
- case IProblem.ParsingErrorInvalidToken :
- case IProblem.ParsingErrorMisplacedConstruct :
- case IProblem.ParsingErrorReplaceTokens :
- case IProblem.ParsingErrorNoSuggestionForTokens :
- case IProblem.ParsingErrorUnexpectedEOF :
- case IProblem.ParsingErrorInsertToComplete :
- case IProblem.ParsingErrorInsertToCompleteScope :
- case IProblem.ParsingErrorInsertToCompletePhrase :
- case IProblem.EndOfSource :
- case IProblem.InvalidHexa :
- case IProblem.InvalidOctal :
- case IProblem.InvalidCharacterConstant :
- case IProblem.InvalidEscape :
- case IProblem.InvalidInput :
- case IProblem.InvalidUnicodeEscape :
- case IProblem.InvalidFloat :
- case IProblem.NullSourceString :
- case IProblem.UnterminatedString :
- case IProblem.UnterminatedComment :
- case IProblem.InvalidDigit :
- break;
- default:
- continue search;
- }
- int position = problem.getSourceStart();
- int start = node.getStartPosition();
- int end = start + node.getLength();
- if ((start <= position) && (position <= end)) {
- node.setFlags(node.getFlags() | ASTNode.MALFORMED);
- // clear the bits on parent
- ASTNode currentNode = node.getParent();
- while (currentNode != null) {
- currentNode.setFlags(currentNode.getFlags() & ~ASTNode.MALFORMED);
- currentNode = currentNode.getParent();
- }
- tagWithErrors = true;
- }
- }
- return tagWithErrors;
- }
-
- /*
- * Method declared on ASTVisitor.
- */
- public boolean visit(FieldDeclaration node) {
- return checkAndTagAsMalformed(node);
- }
-
- /*
- * Method declared on ASTVisitor.
- */
- public boolean visit(FunctionDeclaration node) {
- return checkAndTagAsMalformed(node);
- }
-
- /*
- * Method declared on ASTVisitor.
- */
- public boolean visit(PackageDeclaration node) {
- return checkAndTagAsMalformed(node);
- }
-
- /*
- * Method declared on ASTVisitor.
- */
- public boolean visit(ImportDeclaration node) {
- return checkAndTagAsMalformed(node);
- }
-
- /*
- * Method declared on ASTVisitor.
- */
- public boolean visit(JavaScriptUnit node) {
- return checkAndTagAsMalformed(node);
- }
-
- /*
- * Method declared on ASTVisitor.
- */
- public boolean visit(TypeDeclaration node) {
- return checkAndTagAsMalformed(node);
- }
-
- /*
- * Method declared on ASTVisitor.
- */
- public boolean visit(Initializer node) {
- return checkAndTagAsMalformed(node);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ASTVisitor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ASTVisitor.java
deleted file mode 100644
index 6ee1df01..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ASTVisitor.java
+++ /dev/null
@@ -1,2212 +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.core.dom;
-
-/**
- * A visitor for abstract syntax trees.
- * <p>
- * For each different concrete AST node type <i>T</i> there are
- * a pair of methods:
- * <ul>
- * <li><code>public boolean visit(<i>T</i> node)</code> - Visits
- * the given node to perform some arbitrary operation. If <code>true</code>
- * is returned, the given node's child nodes will be visited next; however,
- * if <code>false</code> is returned, the given node's child nodes will
- * not be visited. The default implementation provided by this class does
- * nothing and returns <code>true</code> (with the exception of
- * {@link #visit(JSdoc) ASTVisitor.visit(Javadoc)}).
- * Subclasses may reimplement this method as needed.</li>
- * <li><code>public void endVisit(<i>T</i> node)</code> - Visits
- * the given node to perform some arbitrary operation. When used in the
- * conventional way, this method is called after all of the given node's
- * children have been visited (or immediately, if <code>visit</code> returned
- * <code>false</code>). The default implementation provided by this class does
- * nothing. Subclasses may reimplement this method as needed.</li>
- * </ul>
- * </p>
- * In addition, there are a pair of methods for visiting AST nodes in the
- * abstract, regardless of node type:
- * <ul>
- * <li><code>public void preVisit(ASTNode node)</code> - Visits
- * the given node to perform some arbitrary operation.
- * This method is invoked prior to the appropriate type-specific
- * <code>visit</code> method.
- * The default implementation of this method does nothing.
- * Subclasses may reimplement this method as needed.</li>
- * <li><code>public void postVisit(ASTNode node)</code> - Visits
- * the given node to perform some arbitrary operation.
- * This method is invoked after the appropriate type-specific
- * <code>endVisit</code> method.
- * The default implementation of this method does nothing.
- * Subclasses may reimplement this method as needed.</li>
- * </ul>
- * <p>
- * For nodes with list-valued properties, the child nodes within the list
- * are visited in order. For nodes with multiple properties, the child nodes
- * are visited in the order that most closely corresponds to the lexical
- * reading order of the source program. For instance, for a type declaration
- * node, the child ordering is: name, superclass, superinterfaces, and
- * body declarations.
- * </p>
- * <p>
- * While it is possible to modify the tree in the visitor, care is required to
- * ensure that the consequences are as expected and desirable.
- * During the course of an ordinary visit starting at a given node, every node
- * in the subtree is visited exactly twice, first with <code>visit</code> and
- * then with <code>endVisit</code>. During a traversal of a stationary tree,
- * each node is either behind (after <code>endVisit</code>), ahead (before
- * <code>visit</code>), or in progress (between <code>visit</code> and
- * the matching <code>endVisit</code>). Changes to the "behind" region of the
- * tree are of no consequence to the visit in progress. Changes to the "ahead"
- * region will be taken in stride. Changes to the "in progress" portion are
- * the more interesting cases. With a node, the various properties are arranged
- * in a linear list, with a cursor that separates the properties that have
- * been visited from the ones that are still to be visited (the cursor
- * is between the elements, rather than on an element). The cursor moves from
- * the head to the tail of this list, advancing to the next position just
- * <i>before</i> <code>visit</code> if called for that child. After the child
- * subtree has been completely visited, the visit moves on the child
- * immediately after the cursor. Removing a child while it is being visited
- * does not alter the course of the visit. But any children added at positions
- * after the cursor are considered in the "ahead" portion and will be visited.
- * </p>
- * <p>
- * Cases to watch out for:
- * <ul>
- * <li>Moving a child node further down the list. This could result in the
- * child subtree being visited multiple times; these visits are sequential.</li>
- * <li>Moving a child node up into an ancestor. If the new home for
- * the node is in the "ahead" portion, the subtree will be visited
- * a second time; again, these visits are sequential.</li>
- * <li>Moving a node down into a child. If the new home for
- * the node is in the "ahead" portion, the subtree will be visited
- * a second time; in this case, the visits will be nested. In some cases,
- * this can lead to a stack overflow or out of memory condition.</li>
- * </ul>
- * <p>Note that {@link LineComment} and {@link BlockComment} nodes are
- * not normally visited in an AST because they are not considered
- * part of main structure of the AST. Use
- * {@link JavaScriptUnit#getCommentList()} to find these additional
- * comments nodes.
- * </p>
- *
- * @see org.eclipse.wst.jsdt.core.dom.ASTNode#accept(ASTVisitor)
- *
- * 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 ASTVisitor {
-
- /**
- * Indicates whether doc tags should be visited by default.
- */
- private boolean visitDocTags;
-
- /**
- * Creates a new AST visitor instance.
- * <p>
- * For backwards compatibility, the visitor does not visit tag
- * elements below doc comments by default. Use
- * {@link #ASTVisitor(boolean) ASTVisitor(true)}
- * for an visitor that includes doc comments by default.
- * </p>
- */
- public ASTVisitor() {
- this(false);
- }
-
- /**
- * Creates a new AST visitor instance.
- *
- * @param visitDocTags <code>true</code> if doc comment tags are
- * to be visited by default, and <code>false</code> otherwise
- * @see JSdoc#tags()
- * @see #visit(JSdoc)
- */
- public ASTVisitor(boolean visitDocTags) {
- this.visitDocTags = visitDocTags;
- }
-
- /**
- * Visits the given AST node prior to the type-specific visit.
- * (before <code>visit</code>).
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void preVisit(ASTNode node) {
- // default implementation: do nothing
- }
-
- /**
- * Visits the given AST node following the type-specific visit
- * (after <code>endVisit</code>).
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void postVisit(ASTNode node) {
- // default implementation: do nothing
- }
-
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(AnonymousClassDeclaration node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(ArrayAccess node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(ArrayCreation node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(ArrayInitializer node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(ArrayType node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(Assignment node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(Block node) {
- return true;
- }
-
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- * <p>Note: {@link LineComment} and {@link BlockComment} nodes are
- * not considered part of main structure of the AST. This method will
- * only be called if a client goes out of their way to visit this
- * kind of node explicitly.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(BlockComment node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(BooleanLiteral node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(BreakStatement node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(CatchClause node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(CharacterLiteral node) {
- return true;
- }
-
- public boolean visit(RegularExpressionLiteral node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(ClassInstanceCreation node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(JavaScriptUnit node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(ConditionalExpression node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(ConstructorInvocation node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(ContinueStatement node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(DoStatement node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(EmptyStatement node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(EnhancedForStatement node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(ExpressionStatement node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(FieldAccess node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(FieldDeclaration node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(ForStatement node) {
- return true;
- }
-
- public boolean visit(ForInStatement node) {
- return true;
- }
-
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(IfStatement node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(ImportDeclaration node) {
- return true;
- }
-
-
- public boolean visit(InferredType node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(InfixExpression node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(InstanceofExpression node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(Initializer node) {
- return true;
- }
-
- /**
- * Visits the given AST node.
- * <p>
- * Unlike other node types, the boolean returned by the default
- * implementation is controlled by a constructor-supplied
- * parameter {@link #ASTVisitor(boolean) ASTVisitor(boolean)}
- * which is <code>false</code> by default.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- * @see #ASTVisitor()
- * @see #ASTVisitor(boolean)
- */
- public boolean visit(JSdoc node) {
- // visit tag elements inside doc comments only if requested
- return this.visitDocTags;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(LabeledStatement node) {
- return true;
- }
-
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- * <p>Note: {@link LineComment} and {@link BlockComment} nodes are
- * not considered part of main structure of the AST. This method will
- * only be called if a client goes out of their way to visit this
- * kind of node explicitly.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(LineComment node) {
- return true;
- }
-
-
- public boolean visit(ListExpression node) {
- return true;
- }
-
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(MemberRef node) {
- return true;
- }
-
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(FunctionRef node) {
- return true;
- }
-
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(FunctionRefParameter node) {
- return true;
- }
-
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(FunctionDeclaration node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(FunctionInvocation node) {
- return true;
- }
-
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(Modifier node) {
- return true;
- }
-
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(NullLiteral node) {
- return true;
- }
-
- public boolean visit(UndefinedLiteral node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(NumberLiteral node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(PackageDeclaration node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(ParenthesizedExpression node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(PostfixExpression node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(PrefixExpression node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(PrimitiveType node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(QualifiedName node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(QualifiedType node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(ReturnStatement node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(SimpleName node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(SimpleType node) {
- return true;
- }
-
-
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(SingleVariableDeclaration node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(StringLiteral node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(SuperConstructorInvocation node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(SuperFieldAccess node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(SuperMethodInvocation node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(SwitchCase node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(SwitchStatement node) {
- return true;
- }
-
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(TagElement node) {
- return true;
- }
-
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(TextElement node) {
- return true;
- }
-
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(ThisExpression node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(ThrowStatement node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(TryStatement node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(TypeDeclaration node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(TypeDeclarationStatement node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(TypeLiteral node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(VariableDeclarationExpression node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(VariableDeclarationStatement node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(VariableDeclarationFragment node) {
- return true;
- }
-
- /**
- * Visits the given type-specific AST node.
- * <p>
- * The default implementation does nothing and return true.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- * @return <code>true</code> if the children of this node should be
- * visited, and <code>false</code> if the children of this node should
- * be skipped
- */
- public boolean visit(WhileStatement node) {
- return true;
- }
-
- public boolean visit(WithStatement node) {
- return true;
- }
-
- public boolean visit(ObjectLiteral node) {
- return true;
- }
- public boolean visit(ObjectLiteralField node) {
- return true;
- }
- public boolean visit(FunctionExpression node) {
- return true;
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(AnonymousClassDeclaration node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(ArrayAccess node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(ArrayCreation node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(ArrayInitializer node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(ArrayType node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(Assignment node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(Block node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- * <p>Note: {@link LineComment} and {@link BlockComment} nodes are
- * not considered part of main structure of the AST. This method will
- * only be called if a client goes out of their way to visit this
- * kind of node explicitly.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(BlockComment node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(BooleanLiteral node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(BreakStatement node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(CatchClause node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(CharacterLiteral node) {
- // default implementation: do nothing
- }
- public void endVisit(RegularExpressionLiteral node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(ClassInstanceCreation node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(JavaScriptUnit node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(ConditionalExpression node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(ConstructorInvocation node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(ContinueStatement node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(DoStatement node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(EmptyStatement node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(EnhancedForStatement node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(ExpressionStatement node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(FieldAccess node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(FieldDeclaration node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(ForStatement node) {
- // default implementation: do nothing
- }
-
- public void endVisit(ForInStatement node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(IfStatement node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(ImportDeclaration node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(InfixExpression node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(InstanceofExpression node) {
- // default implementation: do nothing
- }
-
- public void endVisit(InferredType node) {
- // default implementation: do nothing
- }
-
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(Initializer node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(JSdoc node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(LabeledStatement node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- * <p>Note: {@link LineComment} and {@link BlockComment} nodes are
- * not considered part of main structure of the AST. This method will
- * only be called if a client goes out of their way to visit this
- * kind of node explicitly.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(LineComment node) {
- // default implementation: do nothing
- }
-
-
- public void endVisit(ListExpression node) {
- // default implementation: do nothing
- }
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(MemberRef node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(FunctionRef node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(FunctionRefParameter node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(FunctionDeclaration node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(FunctionInvocation node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(Modifier node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(NullLiteral node) {
- // default implementation: do nothing
- }
-
- public void endVisit(UndefinedLiteral node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(NumberLiteral node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(PackageDeclaration node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(ParenthesizedExpression node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(PostfixExpression node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(PrefixExpression node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(PrimitiveType node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(QualifiedName node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(QualifiedType node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(ReturnStatement node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(SimpleName node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(SimpleType node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(SingleVariableDeclaration node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(StringLiteral node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(SuperConstructorInvocation node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(SuperFieldAccess node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(SuperMethodInvocation node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(SwitchCase node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(SwitchStatement node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(TagElement node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(TextElement node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(ThisExpression node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(ThrowStatement node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(TryStatement node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(TypeDeclaration node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(TypeDeclarationStatement node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(TypeLiteral node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(VariableDeclarationExpression node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(VariableDeclarationStatement node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(VariableDeclarationFragment node) {
- // default implementation: do nothing
- }
-
- /**
- * End of visit the given type-specific AST node.
- * <p>
- * The default implementation does nothing. Subclasses may reimplement.
- * </p>
- *
- * @param node the node to visit
- */
- public void endVisit(WhileStatement node) {
- // default implementation: do nothing
- }
-
- public void endVisit(WithStatement node) {
- // default implementation: do nothing
- }
-
- public void endVisit(ObjectLiteral node) {
- // default implementation: do nothing
- }
-
- public void endVisit(ObjectLiteralField node) {
- // default implementation: do nothing
- }
-
- public void endVisit(FunctionExpression node) {
- // default implementation: do nothing
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/AbstractTypeDeclaration.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/AbstractTypeDeclaration.java
deleted file mode 100644
index 9fe8daae..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/AbstractTypeDeclaration.java
+++ /dev/null
@@ -1,242 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.dom;
-
-import java.util.List;
-
-/**
- * Abstract subclass for type declaration AST node types.
- *
- * 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 AbstractTypeDeclaration extends BodyDeclaration {
-
-
- /**
- * The type name; lazily initialized; defaults to a unspecified,
- * legal JavaScript class identifier.
- */
- SimpleName typeName = null;
-
- /**
- * The body declarations (element type: <code>BodyDeclaration</code>).
- * Defaults to an empty list.
- */
- ASTNode.NodeList bodyDeclarations;
-
- /**
- * Returns structural property descriptor for the "bodyDeclarations" property
- * of this node.
- *
- * @return the property descriptor
- */
- abstract ChildListPropertyDescriptor internalBodyDeclarationsProperty();
-
- /**
- * Returns structural property descriptor for the "bodyDeclarations" property
- * of this node.
- *
- * @return the property descriptor
- */
- public final ChildListPropertyDescriptor getBodyDeclarationsProperty() {
- return internalBodyDeclarationsProperty();
- }
-
- /**
- * Returns structural property descriptor for the "name" property
- * of this node.
- *
- * @return the property descriptor
- */
- abstract ChildPropertyDescriptor internalNameProperty();
-
- /**
- * Returns structural property descriptor for the "name" property
- * of this node.
- *
- * @return the property descriptor
- */
- public final ChildPropertyDescriptor getNameProperty() {
- return internalNameProperty();
- }
-
- /**
- * Creates and returns a structural property descriptor for the
- * "bodyDeclaration" property declared on the given concrete node type.
- *
- * @return the property descriptor
- */
- static final ChildListPropertyDescriptor internalBodyDeclarationPropertyFactory(Class nodeClass) {
- return new ChildListPropertyDescriptor(nodeClass, "bodyDeclarations", BodyDeclaration.class, CYCLE_RISK); //$NON-NLS-1$
- }
-
- /**
- * Creates and returns a structural property descriptor for the
- * "name" property declared on the given concrete node type.
- *
- * @return the property descriptor
- */
- static final ChildPropertyDescriptor internalNamePropertyFactory(Class nodeClass) {
- return new ChildPropertyDescriptor(nodeClass, "name", SimpleName.class, MANDATORY, NO_CYCLE_RISK); //$NON-NLS-1$
- }
-
- /**
- * Creates a new AST node for an abstract type declaration owned by the given
- * AST.
- * <p>
- * N.B. This constructor is package-private; all subclasses must be
- * declared in the same package; clients are unable to declare
- * additional subclasses.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- AbstractTypeDeclaration(AST ast) {
- super(ast);
- this.bodyDeclarations = new ASTNode.NodeList(internalBodyDeclarationsProperty());
- }
-
- /**
- * Returns the name of the type declared in this type declaration.
- *
- * @return the type name node
- */
- public SimpleName getName() {
- if (this.typeName == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.typeName == null) {
- preLazyInit();
- this.typeName = new SimpleName(this.ast);
- postLazyInit(this.typeName, internalNameProperty());
- }
- }
- }
- return this.typeName;
- }
-
- /**
- * Sets the name of the type declared in this type declaration to the
- * given name.
- *
- * @param typeName the new type name
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public void setName(SimpleName typeName) {
- if (typeName == null) {
- throw new IllegalArgumentException();
- }
- ChildPropertyDescriptor p = internalNameProperty();
- ASTNode oldChild = this.typeName;
- preReplaceChild(oldChild, typeName, p);
- this.typeName = typeName;
- postReplaceChild(oldChild, typeName, p);
- }
-
- /**
- * Returns the live ordered list of body declarations of this type
- * declaration.
- *
- * @return the live list of body declarations
- * (element type: <code>BodyDeclaration</code>)
- */
- public List bodyDeclarations() {
- return this.bodyDeclarations;
- }
-
- /**
- * Returns whether this type declaration is a package member (that is,
- * a top-level type).
- * <p>
- * Note that this is a convenience method that simply checks whether
- * this node's parent is a javaScript unit node.
- * </p>
- *
- * @return <code>true</code> if this type declaration is a child of
- * a javaScript unit node, and <code>false</code> otherwise
- */
- public boolean isPackageMemberTypeDeclaration() {
- ASTNode parent = getParent();
- return (parent instanceof JavaScriptUnit);
- }
-
- /**
- * Returns whether this type declaration is a type member.
- * <p>
- * Note that this is a convenience method that simply checks whether
- * this node's parent is a type declaration node or an anonymous
- * class declaration.
- * </p>
- *
- * @return <code>true</code> if this type declaration is a child of
- * a type declaration node or an anonymous class declaration node,
- * and <code>false</code> otherwise
- */
- public boolean isMemberTypeDeclaration() {
- ASTNode parent = getParent();
- return (parent instanceof AbstractTypeDeclaration)
- || (parent instanceof AnonymousClassDeclaration);
- }
-
- /**
- * Returns whether this type declaration is a local type.
- * <p>
- * Note that this is a convenience method that simply checks whether
- * this node's parent is a type declaration statement node.
- * </p>
- *
- * @return <code>true</code> if this type declaration is a child of
- * a type declaration statement node, and <code>false</code> otherwise
- */
- public boolean isLocalTypeDeclaration() {
- ASTNode parent = getParent();
- return (parent instanceof TypeDeclarationStatement);
- }
-
- /**
- * Resolves and returns the binding for the type declared in this type
- * declaration.
- * <p>
- * Note that bindings are generally unavailable unless requested when the
- * AST is being built.
- * </p>
- *
- * @return the binding, or <code>null</code> if the binding cannot be
- * resolved
- */
- public final ITypeBinding resolveBinding() {
- return internalResolveBinding();
- }
-
- /**
- * Resolves and returns the binding for the type declared in this type
- * declaration. This method must be implemented by subclasses.
- *
- * @return the binding, or <code>null</code> if the binding cannot be
- * resolved
- */
- abstract ITypeBinding internalResolveBinding();
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return super.memSize() + 2 * 4;
- }
-
-}
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
deleted file mode 100644
index 762b024f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/AnonymousClassDeclaration.java
+++ /dev/null
@@ -1,191 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Anonymous class declaration AST node type. For JLS2, this type of node appears
- * only as a child on a class instance creation expression.
- * For JLS3, this type of node appears may also appear as the child of
- * an enum constant declaration.
- *
- * <pre>
- * AnonymousClassDeclaration:
- * <b>{</b> ClassBodyDeclaration <b>}</b>
- * </pre>
- *
- * @see ClassInstanceCreation
- * @see EnumConstantDeclaration
- *
- * 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 AnonymousClassDeclaration extends ASTNode {
-
- /**
- * The "bodyDeclarations" structural property of this node type.
- */
- public static final ChildListPropertyDescriptor BODY_DECLARATIONS_PROPERTY =
- new ChildListPropertyDescriptor(AnonymousClassDeclaration.class, "bodyDeclarations", BodyDeclaration.class, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List properyList = new ArrayList(2);
- createPropertyList(AnonymousClassDeclaration.class, properyList);
- addProperty(BODY_DECLARATIONS_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The body declarations (element type: <code>BodyDeclaration</code>).
- * Defaults to none.
- */
- private ASTNode.NodeList bodyDeclarations =
- new ASTNode.NodeList(BODY_DECLARATIONS_PROPERTY);
-
- /**
- * Creates a new AST node for an anonymous class declaration owned
- * by the given AST. By default, the list of body declarations is empty.
- * <p>
- * N.B. This constructor is package-private; all subclasses must be
- * declared in the same package; clients are unable to declare
- * additional subclasses.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- AnonymousClassDeclaration(AST ast) {
- super(ast);
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- final List internalGetChildListProperty(ChildListPropertyDescriptor property) {
- if (property == BODY_DECLARATIONS_PROPERTY) {
- return bodyDeclarations();
- }
- // allow default implementation to flag the error
- return super.internalGetChildListProperty(property);
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return ANONYMOUS_CLASS_DECLARATION;
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- AnonymousClassDeclaration result = new AnonymousClassDeclaration(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.bodyDeclarations().addAll(
- ASTNode.copySubtrees(target, bodyDeclarations()));
- return result;
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChildren(visitor, bodyDeclarations);
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the live ordered list of body declarations of this
- * anonymous class declaration.
- *
- * @return the live list of body declarations
- * (element type: <code>BodyDeclaration</code>)
- */
- public List bodyDeclarations() {
- return this.bodyDeclarations;
- }
-
- /**
- * Resolves and returns the binding for the anonymous class declared in
- * this declaration.
- * <p>
- * Note that bindings are generally unavailable unless requested when the
- * AST is being built.
- * </p>
- *
- * @return the binding, or <code>null</code> if the binding cannot be
- * resolved
- */
- public ITypeBinding resolveBinding() {
- return this.ast.getBindingResolver().resolveType(this);
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- // treat Code as free
- return BASE_NODE_SIZE + 4;
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + this.bodyDeclarations.listSize();
- }
-}
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
deleted file mode 100644
index 4c71b069..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ArrayAccess.java
+++ /dev/null
@@ -1,270 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Array access expression AST node type.
- *
- * <pre>
- * ArrayAccess:
- * Expression <b>[</b> Expression <b>]</b>
- * </pre>
- *
- * 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 ArrayAccess extends Expression {
-
- /**
- * The "array" structural property of this node type.
- */
- public static final ChildPropertyDescriptor ARRAY_PROPERTY =
- new ChildPropertyDescriptor(ArrayAccess.class, "array", Expression.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "index" structural property of this node type.
- */
- public static final ChildPropertyDescriptor INDEX_PROPERTY =
- new ChildPropertyDescriptor(ArrayAccess.class, "index", Expression.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List properyList = new ArrayList(3);
- createPropertyList(ArrayAccess.class, properyList);
- addProperty(ARRAY_PROPERTY, properyList);
- addProperty(INDEX_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The array expression; lazily initialized; defaults to an unspecified,
- * but legal, expression.
- */
- private Expression arrayExpression = null;
-
- /**
- * The index expression; lazily initialized; defaults to an unspecified,
- * but legal, expression.
- */
- private Expression indexExpression = null;
-
- /**
- * Creates a new unparented array access expression node owned by the given
- * AST. By default, the array and index expresssions are unspecified,
- * but legal.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- ArrayAccess(AST ast) {
- super(ast);
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == ARRAY_PROPERTY) {
- if (get) {
- return getArray();
- } else {
- setArray((Expression) child);
- return null;
- }
- }
- if (property == INDEX_PROPERTY) {
- if (get) {
- return getIndex();
- } else {
- setIndex((Expression) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return ARRAY_ACCESS;
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- ArrayAccess result = new ArrayAccess(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setArray((Expression) getArray().clone(target));
- result.setIndex((Expression) getIndex().clone(target));
- return result;
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChild(visitor, getArray());
- acceptChild(visitor, getIndex());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the array expression of this array access expression.
- *
- * @return the array expression node
- */
- public Expression getArray() {
- if (this.arrayExpression == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.arrayExpression == null) {
- preLazyInit();
- this.arrayExpression = new SimpleName(this.ast);
- postLazyInit(this.arrayExpression, ARRAY_PROPERTY);
- }
- }
- }
- return this.arrayExpression;
- }
-
- /**
- * Sets the array expression of this array access expression.
- *
- * @param expression the array expression node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setArray(Expression expression) {
- if (expression == null) {
- throw new IllegalArgumentException();
- }
- // an ArrayAccess may occur inside an Expression
- // must check cycles
- ASTNode oldChild = this.arrayExpression;
- preReplaceChild(oldChild, expression, ARRAY_PROPERTY);
- this.arrayExpression = expression;
- postReplaceChild(oldChild, expression, ARRAY_PROPERTY);
- }
-
- /**
- * Returns the index expression of this array access expression.
- *
- * @return the index expression node
- */
- public Expression getIndex() {
- if (this.indexExpression == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.indexExpression == null) {
- preLazyInit();
- this.indexExpression = new SimpleName(this.ast);
- postLazyInit(this.indexExpression, INDEX_PROPERTY);
- }
- }
- }
- return this.indexExpression;
- }
-
- /**
- * Sets the index expression of this array access expression.
- *
- * @param expression the index expression node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setIndex(Expression expression) {
- if (expression == null) {
- throw new IllegalArgumentException();
- }
- // an ArrayAccess may occur inside an Expression
- // must check cycles
- ASTNode oldChild = this.indexExpression;
- preReplaceChild(oldChild, expression, INDEX_PROPERTY);
- this.indexExpression = expression;
- postReplaceChild(oldChild, expression, INDEX_PROPERTY);
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return BASE_NODE_SIZE + 2 * 4;
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.arrayExpression == null ? 0 : getArray().treeSize())
- + (this.indexExpression == null ? 0 : getIndex().treeSize());
- }
-}
-
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
deleted file mode 100644
index e075b845..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ArrayCreation.java
+++ /dev/null
@@ -1,315 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Array creation expression AST node type.
- * For JLS2:
- * <p>
- * The mapping from JavaScript language syntax to AST nodes is as follows:
- * <ul>
- * <li>the type node is the array type of the creation expression,
- * with one level of array per set of square brackets,</li>
- * <li>the dimension expressions are collected into the <code>dimensions</code>
- * list.</li>
- * </ul>
- * </p>
- * For JLS3, type arguments are added:
- * <pre>
- * ArrayCreation:
- * <b>new</b> PrimitiveType <b>[</b> Expression <b>]</b> { <b>[</b> Expression <b>]</b> } { <b>[</b> <b>]</b> }
- * <b>new</b> TypeName [ <b>&lt;</b> Type { <b>,</b> Type } <b>&gt;</b> ]
- * <b>[</b> Expression <b>]</b> { <b>[</b> Expression <b>]</b> } { <b>[</b> <b>]</b> }
- * <b>new</b> PrimitiveType <b>[</b> <b>]</b> { <b>[</b> <b>]</b> } ArrayInitializer
- * <b>new</b> TypeName [ <b>&lt;</b> Type { <b>,</b> Type } <b>&gt;</b> ]
- * <b>[</b> <b>]</b> { <b>[</b> <b>]</b> } ArrayInitializer
- * </pre>
- *
- * 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 ArrayCreation extends Expression {
-
- /**
- * The "type" structural property of this node type.
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- */
- public static final ChildPropertyDescriptor TYPE_PROPERTY =
- new ChildPropertyDescriptor(ArrayCreation.class, "type", ArrayType.class, MANDATORY, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "dimensions" structural property of this node type.
- */
- public static final ChildListPropertyDescriptor DIMENSIONS_PROPERTY =
- new ChildListPropertyDescriptor(ArrayCreation.class, "dimensions", Expression.class, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "initializer" structural property of this node type.
- */
- public static final ChildPropertyDescriptor INITIALIZER_PROPERTY =
- new ChildPropertyDescriptor(ArrayCreation.class, "initializer", ArrayInitializer.class, OPTIONAL, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List properyList = new ArrayList(4);
- createPropertyList(ArrayCreation.class, properyList);
- addProperty(TYPE_PROPERTY, properyList);
- addProperty(DIMENSIONS_PROPERTY, properyList);
- addProperty(INITIALIZER_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The array type; lazily initialized; defaults to a unspecified,
- * legal array type.
- */
- private ArrayType arrayType = null;
-
- /**
- * The list of dimension expressions (element type:
- * <code>Expression</code>). Defaults to an empty list.
- */
- private ASTNode.NodeList dimensions =
- new ASTNode.NodeList(DIMENSIONS_PROPERTY);
-
- /**
- * The optional array initializer, or <code>null</code> if none;
- * defaults to none.
- */
- private ArrayInitializer optionalInitializer = null;
-
- /**
- * Creates a new AST node for an array creation expression owned by the
- * given AST. By default, the array type is an unspecified 1-dimensional
- * array, the list of dimensions is empty, and there is no array
- * initializer.
- *
- * @param ast the AST that is to own this node
- */
- ArrayCreation(AST ast) {
- super(ast);
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == INITIALIZER_PROPERTY) {
- if (get) {
- return getInitializer();
- } else {
- setInitializer((ArrayInitializer) child);
- return null;
- }
- }
- if (property == TYPE_PROPERTY) {
- if (get) {
- return getType();
- } else {
- setType((ArrayType) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- final List internalGetChildListProperty(ChildListPropertyDescriptor property) {
- if (property == DIMENSIONS_PROPERTY) {
- return dimensions();
- }
- // allow default implementation to flag the error
- return super.internalGetChildListProperty(property);
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return ARRAY_CREATION;
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- ArrayCreation result = new ArrayCreation(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setType((ArrayType) getType().clone(target));
- result.dimensions().addAll(ASTNode.copySubtrees(target, dimensions()));
- result.setInitializer(
- (ArrayInitializer) ASTNode.copySubtree(target, getInitializer()));
- return result;
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChild(visitor, getType());
- acceptChildren(visitor, this.dimensions);
- acceptChild(visitor, getInitializer());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the array type in this array creation expression.
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @return the array type
- */
- public ArrayType getType() {
- if (this.arrayType == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.arrayType == null) {
- preLazyInit();
- this.arrayType = this.ast.newArrayType(
- this.ast.newInferredType(null));
- postLazyInit(this.arrayType, TYPE_PROPERTY);
- }
- }
- }
- return this.arrayType;
- }
-
- /**
- * Sets the array type in this array creation expression.
- *
- * @param type the new array type
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public void setType(ArrayType type) {
- if (type == null) {
- throw new IllegalArgumentException();
- }
- // an ArrayCreation cannot occur inside a ArrayType - cycles not possible
- ASTNode oldChild = this.arrayType;
- preReplaceChild(oldChild, type, TYPE_PROPERTY);
- this.arrayType = type;
- postReplaceChild(oldChild, type, TYPE_PROPERTY);
- }
-
- /**
- * Returns the live ordered list of dimension expressions in this array
- * initializer.
- *
- * @return the live list of dimension expressions
- * (element type: <code>Expression</code>)
- */
- public List dimensions() {
- return this.dimensions;
- }
-
- /**
- * Returns the array initializer of this array creation expression, or
- * <code>null</code> if there is none.
- *
- * @return the array initializer node, or <code>null</code> if
- * there is none
- */
- public ArrayInitializer getInitializer() {
- return optionalInitializer;
- }
-
- /**
- * Sets or clears the array initializer of this array creation expression.
- *
- * @param initializer the array initializer node, or <code>null</code>
- * if there is none
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setInitializer(ArrayInitializer initializer) {
- // an ArrayCreation may occur inside an ArrayInitializer
- // must check cycles
- ASTNode oldChild = this.optionalInitializer;
- preReplaceChild(oldChild, initializer, INITIALIZER_PROPERTY);
- this.optionalInitializer = initializer;
- postReplaceChild(oldChild, initializer, INITIALIZER_PROPERTY);
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return BASE_NODE_SIZE + 3 * 4;
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- int size = memSize()
- + (this.arrayType == null ? 0 : getType().treeSize())
- + (this.optionalInitializer == null ? 0 : getInitializer().treeSize())
- + this.dimensions.listSize();
- return size;
- }
-}
-
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
deleted file mode 100644
index da7e9194..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ArrayInitializer.java
+++ /dev/null
@@ -1,161 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Array initializer AST node type.
- *
- * <pre>
- * ArrayInitializer:
- * </b> { Expression { <b>,</b> Expression} { <b>,</b> }} <b>}</b>
- * </pre>
- *
- * 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 ArrayInitializer extends Expression {
-
- /**
- * The "expressions" structural property of this node type.
- */
- public static final ChildListPropertyDescriptor EXPRESSIONS_PROPERTY =
- new ChildListPropertyDescriptor(ArrayInitializer.class, "expressions", Expression.class, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List properyList = new ArrayList(2);
- createPropertyList(ArrayInitializer.class, properyList);
- addProperty(EXPRESSIONS_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The list of expressions (element type:
- * <code>Expression</code>). Defaults to an empty list.
- */
- private ASTNode.NodeList expressions =
- new ASTNode.NodeList(EXPRESSIONS_PROPERTY);
-
- /**
- * Creates a new AST node for an array initializer owned by the
- * given AST. By default, the list of expressions is empty.
- *
- * @param ast the AST that is to own this node
- */
- ArrayInitializer(AST ast) {
- super(ast);
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- final List internalGetChildListProperty(ChildListPropertyDescriptor property) {
- if (property == EXPRESSIONS_PROPERTY) {
- return expressions();
- }
- // allow default implementation to flag the error
- return super.internalGetChildListProperty(property);
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return ARRAY_INITIALIZER;
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- ArrayInitializer result = new ArrayInitializer(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.expressions().addAll(ASTNode.copySubtrees(target, expressions()));
- return result;
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- acceptChildren(visitor, this.expressions);
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the live ordered list of expressions in this array initializer.
- *
- * @return the live list of expressions
- * (element type: <code>Expression</code>)
- */
- public List expressions() {
- return this.expressions;
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return BASE_NODE_SIZE + 1 * 4;
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return memSize() + this.expressions.listSize();
- }
-}
-
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
deleted file mode 100644
index 585bca87..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ArrayType.java
+++ /dev/null
@@ -1,247 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Type node for an array type.
- * <p>
- * Array types are expressed in a recursive manner, one dimension at a time.
- * </p>
- * <pre>
- * ArrayType:
- * Type <b>[</b> <b>]</b>
- * </pre>
- *
- * 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 ArrayType extends Type {
-
- /**
- * The "componentType" structural property of this node type.
- * <p><b>Note: This Field only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- */
- public static final ChildPropertyDescriptor COMPONENT_TYPE_PROPERTY =
- new ChildPropertyDescriptor(ArrayType.class, "componentType", Type.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List properyList = new ArrayList(2);
- createPropertyList(ArrayType.class, properyList);
- addProperty(COMPONENT_TYPE_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The component type; lazily initialized; defaults to a simple type with
- * an unspecfied, but legal, name.
- */
- private Type componentType = null;
-
- /**
- * Creates a new unparented node for an array type owned by the given AST.
- * By default, a 1-dimensional array of an unspecified simple type.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- ArrayType(AST ast) {
- super(ast);
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == COMPONENT_TYPE_PROPERTY) {
- if (get) {
- return getComponentType();
- } else {
- setComponentType((Type) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return ARRAY_TYPE;
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- ArrayType result = new ArrayType(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setComponentType((Type) getComponentType().clone(target));
- return result;
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- acceptChild(visitor, getComponentType());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the component type of this array type. The component type
- * may be another array type.
- *
- * @return the component type node
- */
- public Type getComponentType() {
- if (this.componentType == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.componentType == null) {
- preLazyInit();
- this.componentType = new SimpleType(this.ast);
- postLazyInit(this.componentType, COMPONENT_TYPE_PROPERTY);
- }
- }
- }
- return this.componentType;
- }
-
- /**
- * Sets the component type of this array type. The component type
- * may be another array type.
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @param componentType the component type
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setComponentType(Type componentType) {
- if (componentType == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.componentType;
- preReplaceChild(oldChild, componentType, COMPONENT_TYPE_PROPERTY);
- this.componentType = componentType;
- postReplaceChild(oldChild, componentType, COMPONENT_TYPE_PROPERTY);
- }
-
- /**
- * Returns the element type of this array type. The element type is
- * never an array type.
- * <p>
- * This is a convenience method that descends a chain of nested array types
- * until it reaches a non-array type.
- * </p>
- *
- * <p><b>Note: This Method only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * @return the component type node
- */
- public Type getElementType() {
- Type t = getComponentType();
- while (t.isArrayType()) {
- t = ((ArrayType) t).getComponentType();
- }
- return t;
- }
-
- /**
- * Returns the number of dimensions in this array type.
- * <p>
- * This is a convenience method that descends a chain of nested array types
- * until it reaches a non-array type.
- * </p>
- *
- * @return the number of dimensions (always positive)
- */
- public int getDimensions() {
- Type t = getComponentType();
- int dimensions = 1; // always include this array type
- while (t.isArrayType()) {
- dimensions++;
- t = ((ArrayType) t).getComponentType();
- }
- return dimensions;
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return BASE_NODE_SIZE + 1 * 4;
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.componentType == null ? 0 : getComponentType().treeSize());
- }
-}
-
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
deleted file mode 100644
index 0f974470..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Assignment.java
+++ /dev/null
@@ -1,439 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Assignment expression AST node type.
- *
- * <pre>
- * Assignment:
- * Expression AssignmentOperator Expression
- * </pre>
- *
- * 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 Assignment extends Expression {
-
- /**
- * Assignment operators (typesafe enumeration).
- * <pre>
- * AssignmentOperator:<code>
- * <b>=</b> ASSIGN
- * <b>+=</b> PLUS_ASSIGN
- * <b>-=</b> MINUS_ASSIGN
- * <b>*=</b> TIMES_ASSIGN
- * <b>/=</b> DIVIDE_ASSIGN
- * <b>&amp;=</b> BIT_AND_ASSIGN
- * <b>|=</b> BIT_OR_ASSIGN
- * <b>^=</b> BIT_XOR_ASSIGN
- * <b>%=</b> REMAINDER_ASSIGN
- * <b>&lt;&lt;=</b> LEFT_SHIFT_ASSIGN
- * <b>&gt;&gt;=</b> RIGHT_SHIFT_SIGNED_ASSIGN
- * <b>&gt;&gt;&gt;=</b> RIGHT_SHIFT_UNSIGNED_ASSIGN</code>
- * </pre>
- */
- public static class Operator {
-
- /**
- * The name of the operator
- */
- private String op;
-
- /**
- * Creates a new assignment operator with the given name.
- * <p>
- * Note: this constructor is private. The only instances
- * ever created are the ones for the standard operators.
- * </p>
- *
- * @param op the character sequence for the operator
- */
- private Operator(String op) {
- this.op = op;
- }
-
- /**
- * Returns the character sequence for the operator.
- *
- * @return the character sequence for the operator
- */
- public String toString() {
- return op;
- }
-
- /** = operator. */
- public static final Operator ASSIGN = new Operator("=");//$NON-NLS-1$
- /** += operator. */
- public static final Operator PLUS_ASSIGN = new Operator("+=");//$NON-NLS-1$
- /** -= operator. */
- public static final Operator MINUS_ASSIGN = new Operator("-=");//$NON-NLS-1$
- /** *= operator. */
- public static final Operator TIMES_ASSIGN = new Operator("*=");//$NON-NLS-1$
- /** /= operator. */
- public static final Operator DIVIDE_ASSIGN = new Operator("/=");//$NON-NLS-1$
- /** &amp;= operator. */
- public static final Operator BIT_AND_ASSIGN = new Operator("&=");//$NON-NLS-1$
- /** |= operator. */
- public static final Operator BIT_OR_ASSIGN = new Operator("|=");//$NON-NLS-1$
- /** ^= operator. */
- public static final Operator BIT_XOR_ASSIGN = new Operator("^=");//$NON-NLS-1$
- /** %= operator. */
- public static final Operator REMAINDER_ASSIGN = new Operator("%=");//$NON-NLS-1$
- /** &lt;&lt;== operator. */
- public static final Operator LEFT_SHIFT_ASSIGN =
- new Operator("<<=");//$NON-NLS-1$
- /** &gt;&gt;= operator. */
- public static final Operator RIGHT_SHIFT_SIGNED_ASSIGN =
- new Operator(">>=");//$NON-NLS-1$
- /** &gt;&gt;&gt;= operator. */
- public static final Operator RIGHT_SHIFT_UNSIGNED_ASSIGN =
- new Operator(">>>=");//$NON-NLS-1$
-
- /**
- * Returns the assignment operator corresponding to the given string,
- * or <code>null</code> if none.
- * <p>
- * <code>toOperator</code> is the converse of <code>toString</code>:
- * that is, <code>Operator.toOperator(op.toString()) == op</code> for all
- * operators <code>op</code>.
- * </p>
- *
- * @param token the character sequence for the operator
- * @return the assignment operator, or <code>null</code> if none
- */
- public static Operator toOperator(String token) {
- return (Operator) CODES.get(token);
- }
-
- /**
- * Map from token to operator (key type: <code>String</code>;
- * value type: <code>Operator</code>).
- */
- private static final Map CODES;
- static {
- CODES = new HashMap(20);
- Operator[] ops = {
- ASSIGN,
- PLUS_ASSIGN,
- MINUS_ASSIGN,
- TIMES_ASSIGN,
- DIVIDE_ASSIGN,
- BIT_AND_ASSIGN,
- BIT_OR_ASSIGN,
- BIT_XOR_ASSIGN,
- REMAINDER_ASSIGN,
- LEFT_SHIFT_ASSIGN,
- RIGHT_SHIFT_SIGNED_ASSIGN,
- RIGHT_SHIFT_UNSIGNED_ASSIGN
- };
- for (int i = 0; i < ops.length; i++) {
- CODES.put(ops[i].toString(), ops[i]);
- }
- }
- }
-
- /**
- * The "leftHandSide" structural property of this node type.
- */
- public static final ChildPropertyDescriptor LEFT_HAND_SIDE_PROPERTY =
- new ChildPropertyDescriptor(Assignment.class, "leftHandSide", Expression.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "operator" structural property of this node type.
- */
- public static final SimplePropertyDescriptor OPERATOR_PROPERTY =
- new SimplePropertyDescriptor(Assignment.class, "operator", Assignment.Operator.class, MANDATORY); //$NON-NLS-1$
-
- /**
- * The "rightHandSide" structural property of this node type.
- */
- public static final ChildPropertyDescriptor RIGHT_HAND_SIDE_PROPERTY =
- new ChildPropertyDescriptor(Assignment.class, "rightHandSide", Expression.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List properyList = new ArrayList(4);
- createPropertyList(Assignment.class, properyList);
- addProperty(LEFT_HAND_SIDE_PROPERTY, properyList);
- addProperty(OPERATOR_PROPERTY, properyList);
- addProperty(RIGHT_HAND_SIDE_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The assignment operator; defaults to Assignment.Operator.ASSIGN
- */
- private Assignment.Operator assignmentOperator = Assignment.Operator.ASSIGN;
-
- /**
- * The left hand side; lazily initialized; defaults to an unspecified,
- * but legal, simple name.
- */
- private Expression leftHandSide = null;
-
- /**
- * The right hand side; lazily initialized; defaults to an unspecified,
- * but legal, simple name.
- */
- private Expression rightHandSide = null;
-
- /**
- * Creates a new AST node for an assignment expression owned by the given
- * AST. By default, the node has an assignment operator, and unspecified
- * left and right hand sides.
- *
- * @param ast the AST that is to own this node
- */
- Assignment(AST ast) {
- super(ast);
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- final Object internalGetSetObjectProperty(SimplePropertyDescriptor property, boolean get, Object value) {
- if (property == OPERATOR_PROPERTY) {
- if (get) {
- return getOperator();
- } else {
- setOperator((Operator) value);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetObjectProperty(property, get, value);
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == LEFT_HAND_SIDE_PROPERTY) {
- if (get) {
- return getLeftHandSide();
- } else {
- setLeftHandSide((Expression) child);
- return null;
- }
- }
- if (property == RIGHT_HAND_SIDE_PROPERTY) {
- if (get) {
- return getRightHandSide();
- } else {
- setRightHandSide((Expression) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return ASSIGNMENT;
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- Assignment result = new Assignment(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setOperator(getOperator());
- result.setLeftHandSide((Expression) getLeftHandSide().clone(target));
- result.setRightHandSide((Expression) getRightHandSide().clone(target));
- return result;
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChild(visitor, getLeftHandSide());
- acceptChild(visitor, getRightHandSide());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the operator of this assignment expression.
- *
- * @return the assignment operator
- */
- public Assignment.Operator getOperator() {
- return this.assignmentOperator;
- }
-
- /**
- * Sets the operator of this assignment expression.
- *
- * @param assignmentOperator the assignment operator
- * @exception IllegalArgumentException if the argument is incorrect
- */
- public void setOperator(Assignment.Operator assignmentOperator) {
- if (assignmentOperator == null) {
- throw new IllegalArgumentException();
- }
- preValueChange(OPERATOR_PROPERTY);
- this.assignmentOperator = assignmentOperator;
- postValueChange(OPERATOR_PROPERTY);
- }
-
- /**
- * Returns the left hand side of this assignment expression.
- *
- * @return the left hand side node
- */
- public Expression getLeftHandSide() {
- if (this.leftHandSide == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.leftHandSide == null) {
- preLazyInit();
- this.leftHandSide= new SimpleName(this.ast);
- postLazyInit(this.leftHandSide, LEFT_HAND_SIDE_PROPERTY);
- }
- }
- }
- return this.leftHandSide;
- }
-
- /**
- * Sets the left hand side of this assignment expression.
- *
- * @param expression the left hand side node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setLeftHandSide(Expression expression) {
- if (expression == null) {
- throw new IllegalArgumentException();
- }
- // an Assignment may occur inside a Expression - must check cycles
- ASTNode oldChild = this.leftHandSide;
- preReplaceChild(oldChild, expression, LEFT_HAND_SIDE_PROPERTY);
- this.leftHandSide = expression;
- postReplaceChild(oldChild, expression, LEFT_HAND_SIDE_PROPERTY);
- }
-
- /**
- * Returns the right hand side of this assignment expression.
- *
- * @return the right hand side node
- */
- public Expression getRightHandSide() {
- if (this.rightHandSide == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.rightHandSide == null) {
- preLazyInit();
- this.rightHandSide= new SimpleName(this.ast);
- postLazyInit(this.rightHandSide, RIGHT_HAND_SIDE_PROPERTY);
- }
- }
- }
- return this.rightHandSide;
- }
-
- /**
- * Sets the right hand side of this assignment expression.
- *
- * @param expression the right hand side node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setRightHandSide(Expression expression) {
- if (expression == null) {
- throw new IllegalArgumentException();
- }
- // an Assignment may occur inside a Expression - must check cycles
- ASTNode oldChild = this.rightHandSide;
- preReplaceChild(oldChild, expression, RIGHT_HAND_SIDE_PROPERTY);
- this.rightHandSide = expression;
- postReplaceChild(oldChild, expression, RIGHT_HAND_SIDE_PROPERTY);
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- // treat Code as free
- return BASE_NODE_SIZE + 3 * 4;
- }
-
- /* (omit jsdoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.leftHandSide == null ? 0 : getLeftHandSide().treeSize())
- + (this.rightHandSide == null ? 0 : getRightHandSide().treeSize());
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/BindingComparator.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/BindingComparator.java
deleted file mode 100644
index 42082a5d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/BindingComparator.java
+++ /dev/null
@@ -1,219 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.dom;
-
-import java.util.HashSet;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Binding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ExtraCompilerModifiers;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.FieldBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ImportBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeConstants;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.VariableBinding;
-
-/**
- * Internal helper class for comparing bindings.
- *
- */
-class BindingComparator {
-
- /**
- * @param declaringElement
- * @param declaringElement2
- * @return true if both parameters are equals, false otherwise
- */
- static boolean isEqual(Binding declaringElement, Binding declaringElement2, HashSet visitedTypes) {
- if (declaringElement instanceof org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding) {
- if (!(declaringElement2 instanceof org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding)){
- return false;
- }
- return isEqual((org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding) declaringElement,
- (org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding) declaringElement2,
- visitedTypes);
- } else if (declaringElement instanceof org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding) {
- if (!(declaringElement2 instanceof org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding)) {
- return false;
- }
- return isEqual((org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding) declaringElement,
- (org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding) declaringElement2,
- visitedTypes);
- } else if (declaringElement instanceof VariableBinding) {
- if (!(declaringElement2 instanceof VariableBinding)) {
- return false;
- }
- return isEqual((VariableBinding) declaringElement,
- (VariableBinding) declaringElement2);
- } else if (declaringElement instanceof org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding) {
- if (!(declaringElement2 instanceof org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding)) {
- return false;
- }
- org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding packageBinding = (org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding) declaringElement;
- org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding packageBinding2 = (org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding) declaringElement2;
- return CharOperation.equals(packageBinding.compoundName, packageBinding2.compoundName);
- } else if (declaringElement instanceof ImportBinding) {
- if (!(declaringElement2 instanceof ImportBinding)) {
- return false;
- }
- ImportBinding importBinding = (ImportBinding) declaringElement;
- ImportBinding importBinding2 = (ImportBinding) declaringElement2;
- return importBinding.onDemand == importBinding2.onDemand
- && CharOperation.equals(importBinding.compoundName, importBinding2.compoundName);
- }
- return false;
- }
-
- static boolean isEqual(org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding methodBinding,
- org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding methodBinding2) {
- return isEqual(methodBinding, methodBinding2, new HashSet());
- }
-
- static boolean isEqual(org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding methodBinding,
- org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding methodBinding2,
- HashSet visitedTypes) {
- if (methodBinding == null) {
- return methodBinding2 == null;
- }
- if (methodBinding2 == null) return false;
- if ( CharOperation.equals(methodBinding.selector, methodBinding2.selector)
- && isEqual(methodBinding.returnType, methodBinding2.returnType, visitedTypes)
-// && isEqual(methodBinding.thrownExceptions, methodBinding2.thrownExceptions, visitedTypes)
- && isEqual(methodBinding.declaringClass, methodBinding2.declaringClass, visitedTypes)
-// && isEqual(methodBinding.typeVariables, methodBinding2.typeVariables, visitedTypes)
- && isEqual(methodBinding.parameters, methodBinding2.parameters, visitedTypes))
- return true;
- org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding constructorBinding =null;
- org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding methBinding =null;
- if (methodBinding.selector==TypeConstants.INIT)
- {
- constructorBinding=methodBinding;
- methBinding=methodBinding2;
- }
- else if (methodBinding2.selector==TypeConstants.INIT)
- {
- constructorBinding=methodBinding2;
- methBinding=methodBinding;
-
- }
- return (constructorBinding!=null &&
- CharOperation.equals(methBinding.selector,constructorBinding.declaringClass.sourceName)
- && isEqual(methBinding.parameters, constructorBinding.parameters, visitedTypes));
-
- }
-
- static boolean isEqual(VariableBinding variableBinding, VariableBinding variableBinding2) {
- return (variableBinding.modifiers & ExtraCompilerModifiers.AccJustFlag) == (variableBinding2.modifiers & ExtraCompilerModifiers.AccJustFlag)
- && CharOperation.equals(variableBinding.name, variableBinding2.name)
- && isEqual(variableBinding.type, variableBinding2.type)
- && (variableBinding.id == variableBinding2.id);
- }
-
- static boolean isEqual(FieldBinding fieldBinding, FieldBinding fieldBinding2) {
- HashSet visitedTypes = new HashSet();
- return (fieldBinding.modifiers & ExtraCompilerModifiers.AccJustFlag) == (fieldBinding2.modifiers & ExtraCompilerModifiers.AccJustFlag)
- && CharOperation.equals(fieldBinding.name, fieldBinding2.name)
- && isEqual(fieldBinding.type, fieldBinding2.type, visitedTypes)
- && isEqual(fieldBinding.declaringClass, fieldBinding2.declaringClass, visitedTypes);
- }
-
- /**
- * @param bindings
- * @param otherBindings
- * @return true if both parameters are equals, false otherwise
- */
- static boolean isEqual(org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding[] bindings, org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding[] otherBindings) {
- return isEqual(bindings, otherBindings, new HashSet());
- }
- /**
- * @param bindings
- * @param otherBindings
- * @return true if both parameters are equals, false otherwise
- */
- static boolean isEqual(org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding[] bindings, org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding[] otherBindings, HashSet visitedTypes) {
- if (bindings == null) {
- return otherBindings == null;
- }
- if (otherBindings == null) {
- return false;
- }
- int length = bindings.length;
- int otherLength = otherBindings.length;
- if (length != otherLength) {
- return false;
- }
- for (int i = 0; i < length; i++) {
- if (!isEqual(bindings[i], otherBindings[i], visitedTypes)) {
- return false;
- }
- }
- return true;
- }
- static boolean isEqual(org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding typeBinding, org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding typeBinding2, HashSet visitedTypes) {
- if (typeBinding == typeBinding2)
- return true;
- if (typeBinding == null || typeBinding2 == null)
- return false;
-
- switch (typeBinding.kind()) {
- case Binding.BASE_TYPE :
- if (!typeBinding2.isBaseType()) {
- return false;
- }
- return typeBinding.id == typeBinding2.id;
-
- case Binding.ARRAY_TYPE :
- if (!typeBinding2.isArrayType()) {
- return false;
- }
- return typeBinding.dimensions() == typeBinding2.dimensions()
- && isEqual(typeBinding.leafComponentType(), typeBinding2.leafComponentType(), visitedTypes);
-
- default :
- if (!(typeBinding2 instanceof ReferenceBinding)) {
- return false;
- }
- ReferenceBinding referenceBinding = (ReferenceBinding) typeBinding;
- ReferenceBinding referenceBinding2 = (ReferenceBinding) typeBinding2;
- char[] constantPoolName = referenceBinding.constantPoolName();
- char[] constantPoolName2 = referenceBinding2.constantPoolName();
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=116833
- if (constantPoolName == null) {
- if (constantPoolName2 != null) {
- return false;
- }
- if (!CharOperation.equals(referenceBinding.computeUniqueKey(), referenceBinding2.computeUniqueKey())) {
- return false;
- }
- } else {
- if (constantPoolName2 == null) {
- return false;
- }
- if (!CharOperation.equals(constantPoolName, constantPoolName2)) {
- return false;
- }
- }
- return CharOperation.equals(referenceBinding.compoundName, referenceBinding2.compoundName)
- && ((referenceBinding.modifiers & ~ClassFileConstants.AccSuper) & (ExtraCompilerModifiers.AccJustFlag))
- == ((referenceBinding2.modifiers & ~ClassFileConstants.AccSuper) & (ExtraCompilerModifiers.AccJustFlag))
- && isEqual(referenceBinding.enclosingType(), referenceBinding2.enclosingType(), visitedTypes);
- }
- }
- /**
- * @param typeBinding
- * @param typeBinding2
- * @return true if both parameters are equals, false otherwise
- */
- static boolean isEqual(org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding typeBinding, org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding typeBinding2) {
- return isEqual(typeBinding, typeBinding2, new HashSet());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/BindingResolver.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/BindingResolver.java
deleted file mode 100644
index c6ee9b18..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/BindingResolver.java
+++ /dev/null
@@ -1,787 +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.core.dom;
-
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.CompilationUnitScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.LookupEnvironment;
-
-/**
- * A binding resolver is an internal mechanism for figuring out the binding
- * for a major declaration, type, or name reference.
- * <p>
- * The default implementation serves as the default binding resolver
- * that does no resolving whatsoever. Internal subclasses do all the real work.
- * </p>
- *
- * @see AST#getBindingResolver
- *
- * 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.
- */
-class BindingResolver {
-
- /**
- * Creates a binding resolver.
- */
- BindingResolver() {
- // default implementation: do nothing
- }
-
- /**
- * Finds the corresponding AST node from which the given binding originated.
- * Returns <code>null</code> if the binding does not correspond to any node
- * in the javaScript unit.
- * <p>
- * The following table indicates the expected node type for the various
- * different kinds of bindings:
- * <ul>
- * <li></li>
- * <li>var/field - a <code>VariableDeclarationFragment</code> in a
- * <code>FieldDeclaration</code> </li>
- * <li>local variable - a <code>SingleVariableDeclaration</code>, or
- * a <code>VariableDeclarationFragment</code> in a
- * <code>VariableDeclarationStatement</code> or
- * <code>VariableDeclarationExpression</code></li>
- * <li>function/method - a <code>FunctionDeclaration</code> </li>
- * </ul>
- * <ul>
- * </p>
- * <p>
- * The implementation of <code>JavaScriptUnit.findDeclaringNode</code>
- * forwards to this method.
- * </p>
- * <p>
- * The default implementation of this method returns <code>null</code>.
- * Subclasses may reimplement.
- * </p>
- *
- * @param binding the binding
- * @return the corresponding node where the bindings is declared,
- * or <code>null</code> if none
- */
- ASTNode findDeclaringNode(IBinding binding) {
- return null;
- }
-
- /**
- * Finds the corresponding AST node from which the given binding key originated.
- *
- * The default implementation of this method returns <code>null</code>.
- * Subclasses may reimplement.
- * </p>
- *
- * @param bindingKey the binding key
- * @return the corresponding node where the bindings is declared,
- * or <code>null</code> if none
- */
- ASTNode findDeclaringNode(String bindingKey) {
- return null;
- }
-
- /**
- * Allows the user to get information about the given old/new pair of
- * AST nodes.
- * <p>
- * The default implementation of this method does nothing.
- * Subclasses may reimplement.
- * </p>
- *
- * @param currentNode the new node
- * @return org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode
- */
- org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode getCorrespondingNode(ASTNode currentNode) {
- return null;
- }
-
- /**
- * Returns the new method binding corresponding to the given old method binding.
- * <p>
- * The default implementation of this method returns <code>null</code>.
- * Subclasses may reimplement.
- * </p>
- *
- * @param methodBinding the old method binding
- * @return the new method binding
- */
- IFunctionBinding getMethodBinding(org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding methodBinding) {
- return null;
- }
-
- /*
- * Returns the new package binding corresponding to the given old package binding.
- * <p>
- * The default implementation of this method returns <code>null</code>.
- * Subclasses may reimplement.
- * </p>
- *
- * @param packageBinding the old package binding
- * @return the new package binding
- */
- IPackageBinding getPackageBinding(org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding packageBinding) {
- return null;
- }
-
- /**
- * Returns the new type binding corresponding to the given old type binding.
- * <p>
- * The default implementation of this method returns <code>null</code>.
- * Subclasses may reimplement.
- * </p>
- *
- * @param referenceBinding the old type binding
- * @return the new type binding
- */
- ITypeBinding getTypeBinding(org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding referenceBinding) {
- return null;
- }
-
-
- /**
- * Returns the new type binding corresponding to the given variableDeclaration.
- * This is used for recovered binding only.
- * <p>
- * The default implementation of this method returns <code>null</code>.
- * Subclasses may reimplement.
- * </p>
- *
- * @param variableDeclaration the given variable declaration
- * @return the new type binding
- */
- ITypeBinding getTypeBinding(VariableDeclaration variableDeclaration) {
- return null;
- }
-
- /**
- * Returns the new type binding corresponding to the given type. This is used for recovered binding
- * only.
- * <p>
- * The default implementation of this method returns <code>null</code>.
- * Subclasses may reimplement.
- * </p>
- *
- * @param type the given type
- * @return the new type binding
- */
- ITypeBinding getTypeBinding(Type type) {
- return null;
- }
-
- /**
- * Returns the new type binding corresponding to the given recovered type binding.
- * <p>
- * The default implementation of this method returns <code>null</code>.
- * Subclasses may reimplement.
- * </p>
- *
- * @param recoveredTypeBinding the recovered type binding
- * @param dimensions the dimensions to add the to given type binding dimensions
- * @return the new type binding
- */
- ITypeBinding getTypeBinding(RecoveredTypeBinding recoveredTypeBinding, int dimensions) {
- return null;
- }
-
- /**
- * Returns the new variable binding corresponding to the given old variable binding.
- * <p>
- * The default implementation of this method returns <code>null</code>.
- * Subclasses may reimplement.
- * </p>
- *
- * @param binding the old variable binding
- * @return the new variable binding
- */
- IVariableBinding getVariableBinding(org.eclipse.wst.jsdt.internal.compiler.lookup.VariableBinding binding) {
- return null;
- }
-
-
- /**
- * Return the working copy owner for the receiver.
- * <p>
- * The default implementation of this method returns <code>null</code>.
- * Subclasses may reimplement.
- * </p>
- * @return the working copy owner for the receiver
- */
- public WorkingCopyOwner getWorkingCopyOwner() {
- return null;
- }
-
- boolean isResolvedTypeInferredFromExpectedType(FunctionInvocation methodInvocation) {
- return false;
- }
-
- boolean isResolvedTypeInferredFromExpectedType(SuperMethodInvocation methodInvocation) {
- return false;
- }
-
- /**
- * Returns the validator lookup environment used by this binding resolver.
- * Returns <code>null</code> if none.
- *
- * @return the lookup environment used by this resolver, or <code>null</code> if none.
- */
- LookupEnvironment lookupEnvironment() {
- return null;
- }
-
- /**
- * This method is used to record the scope and its corresponding node.
- * <p>
- * The default implementation of this method does nothing.
- * Subclasses may reimplement.
- * </p>
- * @param astNode
- */
- void recordScope(ASTNode astNode, BlockScope blockScope) {
- // default implementation: do nothing
- }
-
- /**
- * Returns whether this expression node is the site of a boxing
- * conversion (JLS3 5.1.7). This information is available only
- * when bindings are requested when the AST is being built.
- *
- * @return <code>true</code> if this expression is the site of a
- * boxing conversion, or <code>false</code> if either no boxing conversion
- * is involved or if bindings were not requested when the AST was created
- */
- boolean resolveBoxing(Expression expression) {
- return false;
- }
-
- /**
- * Returns whether this expression node is the site of an unboxing
- * conversion (JLS3 5.1.8). This information is available only
- * when bindings are requested when the AST is being built.
- *
- * @return <code>true</code> if this expression is the site of an
- * unboxing conversion, or <code>false</code> if either no unboxing
- * conversion is involved or if bindings were not requested when the
- * AST was created
- */
- boolean resolveUnboxing(Expression expression) {
- return false;
- }
-
- /**
- * Resolves and returns the compile-time constant expression value as
- * specified in JLS2 15.28, if this expression has one. Constant expression
- * values are unavailable unless bindings are requested when the AST is
- * being built. If the type of the value is a primitive type, the result
- * is the boxed equivalent (i.e., int returned as an <code>Integer</code>);
- * if the type of the value is <code>String</code>, the result is the string
- * itself. If the expression does not have a compile-time constant expression
- * value, the result is <code>null</code>.
- * <p>
- * Resolving constant expressions takes into account the value of simple
- * and qualified names that refer to constant variables (JLS2 4.12.4).
- * </p>
- * <p>
- * Note 1: enum constants are not considered constant expressions either.
- * The result is always <code>null</code> for these.
- * </p>
- * <p>
- * Note 2: Compile-time constant expressions cannot denote <code>null</code>.
- * So technically {@link NullLiteral} nodes are not constant expressions.
- * The result is <code>null</code> for these nonetheless.
- * </p>
- *
- * @return the constant expression value, or <code>null</code> if this
- * expression has no constant expression value or if bindings were not
- * requested when the AST was created
- */
- Object resolveConstantExpressionValue(Expression expression) {
- return null;
- }
-
- /**
- * Resolves and returns the binding for the constructor being invoked.
- * <p>
- * The implementation of
- * <code>ClassInstanceCreation.resolveConstructor</code>
- * forwards to this method. Which constructor is invoked is often a function
- * of the context in which the expression node is embedded as well as
- * the expression subtree itself.
- * </p>
- * <p>
- * The default implementation of this method returns <code>null</code>.
- * Subclasses may reimplement.
- * </p>
- *
- * @param expression the expression of interest
- * @return the binding for the constructor being invoked, or
- * <code>null</code> if no binding is available
- */
- IFunctionBinding resolveConstructor(ClassInstanceCreation expression) {
- return null;
- }
-
- /**
- * Resolves and returns the binding for the constructor being invoked.
- * <p>
- * The implementation of
- * <code>ConstructorInvocation.resolveConstructor</code>
- * forwards to this method. Which constructor is invoked is often a function
- * of the context in which the expression node is embedded as well as
- * the expression subtree itself.
- * </p>
- * <p>
- * The default implementation of this method returns <code>null</code>.
- * Subclasses may reimplement.
- * </p>
- *
- * @param expression the expression of interest
- * @return the binding for the constructor being invoked, or
- * <code>null</code> if no binding is available
- */
- IFunctionBinding resolveConstructor(ConstructorInvocation expression) {
- return null;
- }
-
- /**
- * Resolves and returns the binding for the constructor being invoked.
- * <p>
- * The implementation of
- * <code>SuperConstructorInvocation.resolveConstructor</code>
- * forwards to this method. Which constructor is invoked is often a function
- * of the context in which the expression node is embedded as well as
- * the expression subtree itself.
- * </p>
- * <p>
- * The default implementation of this method returns <code>null</code>.
- * Subclasses may reimplement.
- * </p>
- *
- * @param expression the expression of interest
- * @return the binding for the constructor being invoked, or
- * <code>null</code> if no binding is available
- */
- IFunctionBinding resolveConstructor(SuperConstructorInvocation expression) {
- return null;
- }
- /**
- * Resolves the type of the given expression and returns the type binding
- * for it.
- * <p>
- * The implementation of <code>Expression.resolveTypeBinding</code>
- * forwards to this method. The result is often a function of the context
- * in which the expression node is embedded as well as the expression
- * subtree itself.
- * </p>
- * <p>
- * The default implementation of this method returns <code>null</code>.
- * Subclasses may reimplement.
- * </p>
- *
- * @param expression the expression whose type is of interest
- * @return the binding for the type of the given expression, or
- * <code>null</code> if no binding is available
- */
- ITypeBinding resolveExpressionType(Expression expression) {
- return null;
- }
-
- /**
- * Resolves the given field access and returns the binding for it.
- * <p>
- * The implementation of <code>FieldAccess.resolveFieldBinding</code>
- * forwards to this method. How the field resolves is often a function of
- * the context in which the field access node is embedded as well as
- * the field access subtree itself.
- * </p>
- * <p>
- * The default implementation of this method returns <code>null</code>.
- * Subclasses may reimplement.
- * </p>
- *
- * @param fieldAccess the field access of interest
- * @return the binding for the given field access, or
- * <code>null</code> if no binding is available
- */
- IVariableBinding resolveField(FieldAccess fieldAccess) {
- return null;
- }
-
- /**
- * Resolves the given super field access and returns the binding for it.
- * <p>
- * The implementation of <code>SuperFieldAccess.resolveFieldBinding</code>
- * forwards to this method. How the field resolves is often a function of
- * the context in which the super field access node is embedded as well as
- * the super field access subtree itself.
- * </p>
- * <p>
- * The default implementation of this method returns <code>null</code>.
- * Subclasses may reimplement.
- * </p>
- *
- * @param fieldAccess the super field access of interest
- * @return the binding for the given field access, or
- * <code>null</code> if no binding is available
- */
- IVariableBinding resolveField(SuperFieldAccess fieldAccess) {
- return null;
- }
-
- /**
- * Resolves the given import declaration and returns the binding for it.
- * <p>
- * The implementation of <code>ImportDeclaration.resolveBinding</code>
- * forwards to this method.
- * </p>
- * <p>
- * The default implementation of this method returns <code>null</code>.
- * Subclasses may reimplement.
- * </p>
- *
- * @param importDeclaration the import declaration of interest
- * @return the binding for the given package declaration, or
- * the package binding (for on-demand imports) or type binding
- * (for single-type imports), or <code>null</code> if no binding is
- * available
- */
- IBinding resolveImport(ImportDeclaration importDeclaration) {
- return null;
- }
-
- /**
- * Resolves the given method declaration and returns the binding for it.
- * <p>
- * The implementation of <code>FunctionDeclaration.resolveBinding</code>
- * forwards to this method. How the method resolves is often a function of
- * the context in which the method declaration node is embedded as well as
- * the method declaration subtree itself.
- * </p>
- * <p>
- * The default implementation of this method returns <code>null</code>.
- * Subclasses may reimplement.
- * </p>
- *
- * @param method the method or constructor declaration of interest
- * @return the binding for the given method declaration, or
- * <code>null</code> if no binding is available
- */
- IFunctionBinding resolveMethod(FunctionDeclaration method) {
- return null;
- }
-
- /**
- * Resolves the given method invocation and returns the binding for it.
- * <p>
- * The implementation of <code>FunctionInvocation.resolveMethodBinding</code>
- * forwards to this method. How the method resolves is often a function of
- * the context in which the method invocation node is embedded as well as
- * the method invocation subtree itself.
- * </p>
- * <p>
- * The default implementation of this method returns <code>null</code>.
- * Subclasses may reimplement.
- * </p>
- *
- * @param method the method invocation of interest
- * @return the binding for the given method invocation, or
- * <code>null</code> if no binding is available
- */
- IFunctionBinding resolveMethod(FunctionInvocation method) {
- return null;
- }
-
- /**
- * Resolves the given method invocation and returns the binding for it.
- * <p>
- * The implementation of <code>FunctionInvocation.resolveMethodBinding</code>
- * forwards to this method. How the method resolves is often a function of
- * the context in which the method invocation node is embedded as well as
- * the method invocation subtree itself.
- * </p>
- * <p>
- * The default implementation of this method returns <code>null</code>.
- * Subclasses may reimplement.
- * </p>
- *
- * @param method the method invocation of interest
- * @return the binding for the given method invocation, or
- * <code>null</code> if no binding is available
- */
- IFunctionBinding resolveMethod(SuperMethodInvocation method) {
- return null;
- }
-
- /**
- * Resolves the given name and returns the type binding for it.
- * <p>
- * The implementation of <code>Name.resolveBinding</code> forwards to
- * this method. How the name resolves is often a function of the context
- * in which the name node is embedded as well as the name itself.
- * </p>
- * <p>
- * The default implementation of this method returns <code>null</code>.
- * Subclasses may reimplement.
- * </p>
- *
- * @param name the name of interest
- * @return the binding for the name, or <code>null</code> if no binding is
- * available
- */
- IBinding resolveName(Name name) {
- return null;
- }
-
- /**
- * Resolves the given package declaration and returns the binding for it.
- * <p>
- * The implementation of <code>PackageDeclaration.resolveBinding</code>
- * forwards to this method.
- * </p>
- * <p>
- * The default implementation of this method returns <code>null</code>.
- * Subclasses may reimplement.
- * </p>
- *
- * @param pkg the package declaration of interest
- * @return the binding for the given package declaration, or
- * <code>null</code> if no binding is available
- */
- IPackageBinding resolvePackage(PackageDeclaration pkg) {
- return null;
- }
-
- /**
- * Resolves the given reference and returns the binding for it.
- * <p>
- * The implementation of <code>MemberRef.resolveBinding</code> forwards to
- * this method. How the name resolves is often a function of the context
- * in which the name node is embedded as well as the name itself.
- * </p>
- * <p>
- * The default implementation of this method returns <code>null</code>.
- * Subclasses may reimplement.
- * </p>
- *
- * @param ref the reference of interest
- * @return the binding for the reference, or <code>null</code> if no binding is
- * available
- */
- IBinding resolveReference(MemberRef ref) {
- return null;
- }
-
- /**
- * Resolves the given reference and returns the binding for it.
- * <p>
- * The implementation of <code>FunctionRef.resolveBinding</code> forwards to
- * this method. How the name resolves is often a function of the context
- * in which the name node is embedded as well as the name itself.
- * </p>
- * <p>
- * The default implementation of this method returns <code>null</code>.
- * Subclasses may reimplement.
- * </p>
- *
- * @param ref the reference of interest
- * @return the binding for the reference, or <code>null</code> if no binding is
- * available
- */
- IBinding resolveReference(FunctionRef ref) {
- return null;
- }
-
- /**
- * Resolves the given anonymous class declaration and returns the binding
- * for it.
- * <p>
- * The implementation of <code>AnonymousClassDeclaration.resolveBinding</code>
- * forwards to this method. How the declaration resolves is often a
- * function of the context in which the declaration node is embedded as well
- * as the declaration subtree itself.
- * </p>
- * <p>
- * The default implementation of this method returns <code>null</code>.
- * Subclasses may reimplement.
- * </p>
- *
- * @param type the anonymous class declaration of interest
- * @return the binding for the given class declaration, or <code>null</code>
- * if no binding is available
- */
- ITypeBinding resolveType(AnonymousClassDeclaration type) {
- return null;
- }
-
- /**
- * Resolves the given type and returns the type binding for it.
- * <p>
- * The implementation of <code>Type.resolveBinding</code>
- * forwards to this method. How the type resolves is often a function
- * of the context in which the type node is embedded as well as the type
- * subtree itself.
- * </p>
- * <p>
- * The default implementation of this method returns <code>null</code>.
- * Subclasses may reimplement.
- * </p>
- *
- * @param type the type of interest
- * @return the binding for the given type, or <code>null</code>
- * if no binding is available
- */
- ITypeBinding resolveType(Type type) {
- return null;
- }
-
- /**
- * Resolves the given class or interface declaration and returns the binding
- * for it.
- * <p>
- * The implementation of <code>TypeDeclaration.resolveBinding</code>
- * (and <code>TypeDeclarationStatement.resolveBinding</code>) forwards
- * to this method. How the type declaration resolves is often a function of
- * the context in which the type declaration node is embedded as well as the
- * type declaration subtree itself.
- * </p>
- * <p>
- * The default implementation of this method returns <code>null</code>.
- * Subclasses may reimplement.
- * </p>
- *
- * @param type the class or interface declaration of interest
- * @return the binding for the given type declaration, or <code>null</code>
- * if no binding is available
- */
- ITypeBinding resolveType(TypeDeclaration type) {
- return null;
- }
-
-
- ITypeBinding resolveType(JavaScriptUnit compilationUnit) {
- return null;
- }
-
- /**
- * Resolves the given variable declaration and returns the binding for it.
- * <p>
- * The implementation of <code>VariableDeclaration.resolveBinding</code>
- * forwards to this method. How the variable declaration resolves is often
- * a function of the context in which the variable declaration node is
- * embedded as well as the variable declaration subtree itself. VariableDeclaration
- * declarations used as local variable, formal parameter and exception
- * variables resolve to local variable bindings; variable declarations
- * used to declare fields resolve to field bindings.
- * </p>
- * <p>
- * The default implementation of this method returns <code>null</code>.
- * Subclasses may reimplement.
- * </p>
- *
- * @param variable the variable declaration of interest
- * @return the binding for the given variable declaration, or
- * <code>null</code> if no binding is available
- */
- IVariableBinding resolveVariable(VariableDeclaration variable) {
- return null;
- }
-
- IVariableBinding resolveVariable(VariableDeclarationStatement variable) {
- return null;
- }
-
- /**
- * Resolves the given well known type by name and returns the type binding
- * for it.
- * <p>
- * The implementation of <code>AST.resolveWellKnownType</code>
- * forwards to this method.
- * </p>
- * <p>
- * The default implementation of this method returns <code>null</code>.
- * Subclasses may reimplement.
- * </p>
- *
- * @param name the name of a well known type
- * @return the corresponding type binding, or <code>null<code> if the
- * named type is not considered well known or if no binding can be found
- * for it
- */
- ITypeBinding resolveWellKnownType(String name) {
- return null;
- }
-
-
- /**
- * Answer an array type binding with the given type binding and the given
- * dimensions.
- *
- * <p>If the given type binding is an array binding, then the resulting dimensions is the given dimensions
- * plus the existing dimensions of the array binding. Otherwise the resulting dimensions is the given
- * dimensions.</p>
- *
- * <p>
- * The default implementation of this method returns <code>null</code>.
- * Subclasses may reimplement.
- * </p>
- *
- * @param typeBinding the given type binding
- * @param dimensions the given dimensions
- * @return an array type binding with the given type binding and the given
- * dimensions
- * @throws IllegalArgumentException if the type binding represents the <code>void</code> type binding
- */
- ITypeBinding resolveArrayType(ITypeBinding typeBinding, int dimensions) {
- return null;
- }
-
- /**
- * Returns the javaScript unit scope used by this binding resolver.
- * Returns <code>null</code> if none.
- *
- * @return the javaScript unit scope by this resolver, or <code>null</code> if none.
- */
- public CompilationUnitScope scope() {
- return null;
- }
-
- /**
- * Allows the user to store information about the given old/new pair of
- * AST nodes.
- * <p>
- * The default implementation of this method does nothing.
- * Subclasses may reimplement.
- * </p>
- *
- * @param newNode the new AST node
- * @param oldASTNode the old AST node
- */
- void store(ASTNode newNode, org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode oldASTNode) {
- // default implementation: do nothing
- }
-
- /**
- * Allows the user to update information about the given old/new pair of
- * AST nodes.
- * <p>
- * The default implementation of this method does nothing.
- * Subclasses may reimplement.
- * </p>
- *
- * @param node the old AST node
- * @param newNode the new AST node
- */
- void updateKey(ASTNode node, ASTNode newNode) {
- // default implementation: do nothing
- }
-}
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
deleted file mode 100644
index 59d0abf4..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Block.java
+++ /dev/null
@@ -1,169 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Block statement AST node type.
- *
- * <pre>
- * Block:
- * <b>{</b> { Statement } <b>}</b>
- * </pre>
- *
- * 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 Block extends Statement {
-
- /**
- * The "statements" structural property of this node type.
- */
- public static final ChildListPropertyDescriptor STATEMENTS_PROPERTY =
- new ChildListPropertyDescriptor(Block.class, "statements", Statement.class, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List properyList = new ArrayList(2);
- createPropertyList(Block.class, properyList);
- addProperty(STATEMENTS_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The list of statements (element type: <code>Statement</code>).
- * Defaults to an empty list.
- */
- private ASTNode.NodeList statements =
- new ASTNode.NodeList(STATEMENTS_PROPERTY);
-
- /**
- * Creates a new unparented block node owned by the given AST.
- * By default, the block is empty.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- Block(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalGetChildListProperty(ChildListPropertyDescriptor property) {
- if (property == STATEMENTS_PROPERTY) {
- return statements();
- }
- // allow default implementation to flag the error
- return super.internalGetChildListProperty(property);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return BLOCK;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- Block result = new Block(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.copyLeadingComment(this);
- result.statements().addAll(
- ASTNode.copySubtrees(target, statements()));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- acceptChildren(visitor, this.statements);
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the live list of statements in this block. Adding and
- * removing nodes from this list affects this node dynamically.
- * All nodes in this list must be <code>Statement</code>s;
- * attempts to add any other type of node will trigger an
- * exception.
- *
- * @return the live list of statements in this block
- * (element type: <code>Statement</code>)
- */
- public List statements() {
- return this.statements;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return super.memSize() + 1 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return memSize() + this.statements.listSize();
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/BlockComment.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/BlockComment.java
deleted file mode 100644
index 3f10f55b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/BlockComment.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Block comment AST node type.
- * <p>
- * Block comments (also called "traditional" comments in JLS 3.7)
- * begin with "/&#42;", may contain line breaks, and must end
- * with "&#42;/". Block comment normally exclude comments
- * that begin with "/&#42;#42;", which are instead classified as doc
- * comments ({@link JSdoc}).
- * </p>
- * <p>
- * Note that this node type is a comment placeholder, and is
- * only useful for recording the source range where a comment
- * was found in a source string. It is not useful for creating
- * comments.
- * </p>
- *
- * 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 final class BlockComment extends Comment {
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List properyList = new ArrayList(1);
- createPropertyList(BlockComment.class, properyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * Creates a new block comment node owned by the given AST.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- BlockComment(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return BLOCK_COMMENT;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- BlockComment result = new BlockComment(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- visitor.visit(this);
- visitor.endVisit(this);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return super.memSize();
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return memSize();
- }
-}
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
deleted file mode 100644
index 617b07d3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/BodyDeclaration.java
+++ /dev/null
@@ -1,255 +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.core.dom;
-
-import java.util.Iterator;
-import java.util.List;
-
-/**
- * Abstract base class of all AST nodes that represent body declarations
- * that may appear in the body of some kind of class or interface declaration,
- * including anonymous class declarations.
- * <p>
- * <pre>
- * BodyDeclaration:
- * ClassDeclaration
- * InterfaceDeclaration
- * FunctionDeclaration
- * ConstructorDeclaration
- * FieldDeclaration
- * Initializer
- * </pre>
- * </p>
- * <p>
- * All types of body declarations carry modifiers, although they differ in
- * which modifiers are allowed. Most types of body declarations can carry a
- * doc comment; Initializer is the only ones that does not. The source range
- * for body declarations always includes the doc comment if present.
- * </p>
- *
- * 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 BodyDeclaration extends ProgramElement {
-
- /**
- * The doc comment, or <code>null</code> if none.
- * Defaults to none.
- */
- JSdoc optionalDocComment = null;
-
- /**
- * The modifier flags; bit-wise or of Modifier flags.
- * Defaults to none. Not used in 3.0.
- */
- private int modifierFlags = Modifier.NONE;
-
- /**
- * The extended modifiers (element type: <code>IExtendedModifier</code>).
- * defaults to an empty list
- * (see constructor).
- *
- */
- ASTNode.NodeList modifiers = null;
-
- /**
- * Returns structural property descriptor for the "modifiers" property
- * of this node.
- *
- * @return the property descriptor
- */
- abstract SimplePropertyDescriptor internalModifiersProperty();
-
- /**
- * Returns structural property descriptor for the "modifiers" property
- * of this node.
- *
- * @return the property descriptor
- */
- abstract ChildListPropertyDescriptor internalModifiers2Property();
-
- /**
- * Returns structural property descriptor for the "modifiers" property
- * of this node.
- *
- * @return the property descriptor
- */
- public final ChildListPropertyDescriptor getModifiersProperty() {
- // important: return property for AST.JLS3
- return internalModifiers2Property();
- }
-
- /**
- * Returns structural property descriptor for the "jsdoc" property
- * of this node.
- *
- * @return the property descriptor
- */
- abstract ChildPropertyDescriptor internalJavadocProperty();
-
- /**
- * Returns structural property descriptor for the "jsdoc" property
- * of this node.
- *
- * @return the property descriptor
- */
- public final ChildPropertyDescriptor getJavadocProperty() {
- return internalJavadocProperty();
- }
-
- /**
- * Creates and returns a structural property descriptor for the
- * "jsdoc" property declared on the given concrete node type.
- *
- * @return the property descriptor
- */
- static final ChildPropertyDescriptor internalJavadocPropertyFactory(Class nodeClass) {
- return new ChildPropertyDescriptor(nodeClass, "javadoc", JSdoc.class, OPTIONAL, NO_CYCLE_RISK); //$NON-NLS-1$
- }
-
- /**
- * Creates and returns a structural property descriptor for the
- * "modifiers" property declared on the given concrete node type.
- *
- * @return the property descriptor
- */
- static final SimplePropertyDescriptor internalModifiersPropertyFactory(Class nodeClass) {
- return new SimplePropertyDescriptor(nodeClass, "modifiers", int.class, MANDATORY); //$NON-NLS-1$
- }
-
- /**
- * Creates and returns a structural property descriptor for the
- * "modifiers" property declared on the given concrete node type.
- *
- * @return the property descriptor
- */
- static final ChildListPropertyDescriptor internalModifiers2PropertyFactory(Class nodeClass) {
- return new ChildListPropertyDescriptor(nodeClass, "modifiers", IExtendedModifier.class, CYCLE_RISK); //$NON-NLS-1$
- }
-
- /**
- * Creates a new AST node for a body declaration node owned by the
- * given AST.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- BodyDeclaration(AST ast) {
- super(ast);
- if (ast.apiLevel >= AST.JLS3) {
- this.modifiers = new ASTNode.NodeList(internalModifiers2Property());
- }
- }
-
- /**
- * Returns the doc comment node.
- *
- * @return the doc comment node, or <code>null</code> if none
- */
- public JSdoc getJavadoc() {
- return this.optionalDocComment;
- }
-
- /**
- * Sets or clears the doc comment node.
- *
- * @param docComment the doc comment node, or <code>null</code> if none
- * @exception IllegalArgumentException if the doc comment string is invalid
- */
- public void setJavadoc(JSdoc docComment) {
- ChildPropertyDescriptor p = internalJavadocProperty();
- ASTNode oldChild = this.optionalDocComment;
- preReplaceChild(oldChild, docComment, p);
- this.optionalDocComment = docComment;
- postReplaceChild(oldChild, docComment, p);
- }
-
- /**
- * Returns the modifiers explicitly specified on this declaration.
- *
- * @return the bit-wise or of <code>Modifier</code> constants
- * @see Modifier
- */
- public int getModifiers() {
- // more efficient than checking getAST().API_LEVEL
- if (this.modifiers == null) {
- // JLS2 behavior - bona fide property
- return this.modifierFlags;
- } else {
- // JLS3 behavior - convenience method
- // performance could be improved by caching computed flags
- // but this would require tracking changes to this.modifiers
- int computedmodifierFlags = Modifier.NONE;
- for (Iterator it = modifiers().iterator(); it.hasNext(); ) {
- Object x = it.next();
- if (x instanceof Modifier) {
- computedmodifierFlags |= ((Modifier) x).getKeyword().toFlagValue();
- }
- }
- return computedmodifierFlags;
- }
- }
-
- /**
- * Sets the modifiers explicitly specified on this declaration (JLS2 API only).
- *
- * @param modifiers the given modifiers (bit-wise or of <code>Modifier</code> constants)
- * @see Modifier
- * @deprecated Rhis method is replaced by
- * {@link #modifiers()} which contains a list of a <code>Modifier</code> nodes.
- */
- public void setModifiers(int modifiers) {
- internalSetModifiers(modifiers);
- }
-
- /**
- * Internal synonym for deprecated method. Used to avoid
- * deprecation warnings.
- */
- /*package*/ final void internalSetModifiers(int pmodifiers) {
- // more efficient than just calling supportedOnlyIn2() to check
- if (this.modifiers != null) {
- supportedOnlyIn2();
- }
- SimplePropertyDescriptor p = internalModifiersProperty();
- preValueChange(p);
- this.modifierFlags = pmodifiers;
- postValueChange(p);
- }
-
- /**
- * Returns the live ordered list of modifiers
- * of this declaration .
- *
- * @return the live list of modifiers
- * (element type: <code>IExtendedModifier</code>)
- */
- public List modifiers() {
- // more efficient than just calling unsupportedIn2() to check
- if (this.modifiers == null) {
- unsupportedIn2();
- }
- return this.modifiers;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return BASE_NODE_SIZE + 3 * 4;
- }
-}
-
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
deleted file mode 100644
index d8385db5..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/BooleanLiteral.java
+++ /dev/null
@@ -1,178 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Boolean literal node.
- *
- * <pre>
- * BooleanLiteral:
- * <b>true</b>
- * <b>false</b>
- * </pre>
- *
- * 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 BooleanLiteral extends Expression {
-
- /**
- * The "booleanValue" structural property of this node type.
- */
- public static final SimplePropertyDescriptor BOOLEAN_VALUE_PROPERTY =
- new SimplePropertyDescriptor(BooleanLiteral.class, "booleanValue", boolean.class, MANDATORY); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List properyList = new ArrayList(2);
- createPropertyList(BooleanLiteral.class, properyList);
- addProperty(BOOLEAN_VALUE_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The boolean; defaults to the literal for <code>false</code>.
- */
- private boolean value = false;
-
- /**
- * Creates a new unparented boolean literal node owned by the given AST.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- BooleanLiteral(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean internalGetSetBooleanProperty(SimplePropertyDescriptor property, boolean get, boolean newValue) {
- if (property == BOOLEAN_VALUE_PROPERTY) {
- if (get) {
- return booleanValue();
- } else {
- setBooleanValue(newValue);
- return false;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetBooleanProperty(property, get, newValue);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return BOOLEAN_LITERAL;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- BooleanLiteral result = new BooleanLiteral(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setBooleanValue(booleanValue());
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- visitor.visit(this);
- visitor.endVisit(this);
- }
-
- /**
- * Returns the boolean value of this boolean literal node.
- *
- * @return <code>true</code> for the boolean literal spelled
- * <code>"true"</code>, and <code>false</code> for the boolean literal
- * spelled <code>"false"</code>.
- */
- public boolean booleanValue() {
- return this.value;
- }
-
- /**
- * Sets the boolean value of this boolean literal node.
- *
- * @param value <code>true</code> for the boolean literal spelled
- * <code>"true"</code>, and <code>false</code> for the boolean literal
- * spelled <code>"false"</code>.
- */
- public void setBooleanValue(boolean value) {
- preValueChange(BOOLEAN_VALUE_PROPERTY);
- this.value = value;
- postValueChange(BOOLEAN_VALUE_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return BASE_NODE_SIZE + 1 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return memSize();
- }
-}
-
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
deleted file mode 100644
index 8c000d67..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/BreakStatement.java
+++ /dev/null
@@ -1,188 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Break statement AST node type.
- *
- * <pre>
- * BreakStatement:
- * <b>break</b> [ Identifier ] <b>;</b>
- * </pre>
- *
- * 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 BreakStatement extends Statement {
-
- /**
- * The "label" structural property of this node type.
- */
- public static final ChildPropertyDescriptor LABEL_PROPERTY =
- new ChildPropertyDescriptor(BreakStatement.class, "label", SimpleName.class, OPTIONAL, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List properyList = new ArrayList(2);
- createPropertyList(BreakStatement.class, properyList);
- addProperty(LABEL_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The label, or <code>null</code> if none; none by default.
- */
- private SimpleName optionalLabel = null;
-
- /**
- * Creates a new unparented break statement node owned by the given
- * AST. By default, the break statement has no label.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- BreakStatement(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == LABEL_PROPERTY) {
- if (get) {
- return getLabel();
- } else {
- setLabel((SimpleName) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return BREAK_STATEMENT;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- BreakStatement result = new BreakStatement(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.copyLeadingComment(this);
- result.setLabel((SimpleName) ASTNode.copySubtree(target, getLabel()));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- acceptChild(visitor, getLabel());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the label of this break statement, or <code>null</code> if
- * there is none.
- *
- * @return the label, or <code>null</code> if there is none
- */
- public SimpleName getLabel() {
- return this.optionalLabel;
- }
-
- /**
- * Sets or clears the label of this break statement.
- *
- * @param label the label, or <code>null</code> if
- * there is none
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public void setLabel(SimpleName label) {
- ASTNode oldChild = this.optionalLabel;
- preReplaceChild(oldChild, label, LABEL_PROPERTY);
- this.optionalLabel = label;
- postReplaceChild(oldChild, label, LABEL_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return super.memSize() + 1 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.optionalLabel == null ? 0 : getLabel().treeSize());
- }
-}
-
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
deleted file mode 100644
index ef5ba074..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/CatchClause.java
+++ /dev/null
@@ -1,266 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Catch clause AST node type.
- *
- * <pre>
- * CatchClause:
- * <b>catch</b> <b>(</b> FormalParameter <b>)</b> Block
- * </pre>
- *
- * 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 CatchClause extends ASTNode {
-
- /**
- * The "exception" structural property of this node type.
- */
- public static final ChildPropertyDescriptor EXCEPTION_PROPERTY =
- new ChildPropertyDescriptor(CatchClause.class, "exception", SingleVariableDeclaration.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "body" structural property of this node type.
- */
- public static final ChildPropertyDescriptor BODY_PROPERTY =
- new ChildPropertyDescriptor(CatchClause.class, "body", Block.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List properyList = new ArrayList(3);
- createPropertyList(CatchClause.class, properyList);
- addProperty(EXCEPTION_PROPERTY, properyList);
- addProperty(BODY_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The body; lazily initialized; defaults to an empty block.
- */
- private Block body = null;
-
- /**
- * The exception variable declaration; lazily initialized; defaults to a
- * unspecified, but legal, variable declaration.
- */
- private SingleVariableDeclaration exceptionDecl = null;
-
- /**
- * Creates a new AST node for a catch clause owned by the given
- * AST. By default, the catch clause declares an unspecified, but legal,
- * exception declaration and has an empty block.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- CatchClause(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == EXCEPTION_PROPERTY) {
- if (get) {
- return getException();
- } else {
- setException((SingleVariableDeclaration) child);
- return null;
- }
- }
- if (property == BODY_PROPERTY) {
- if (get) {
- return getBody();
- } else {
- setBody((Block) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return CATCH_CLAUSE;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- CatchClause result = new CatchClause(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setBody((Block) getBody().clone(target));
- result.setException(
- (SingleVariableDeclaration) ASTNode.copySubtree(target, getException()));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChild(visitor, getException());
- acceptChild(visitor, getBody());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the exception variable declaration of this catch clause.
- *
- * @return the exception variable declaration node
- */
- public SingleVariableDeclaration getException() {
- if (this.exceptionDecl == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.exceptionDecl == null) {
- preLazyInit();
- this.exceptionDecl = new SingleVariableDeclaration(this.ast);
- postLazyInit(this.exceptionDecl, EXCEPTION_PROPERTY);
- }
- }
- }
- return this.exceptionDecl;
- }
-
- /**
- * Sets the variable declaration of this catch clause.
- *
- * @param exception the exception variable declaration node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setException(SingleVariableDeclaration exception) {
- if (exception == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.exceptionDecl;
- preReplaceChild(oldChild, exception, EXCEPTION_PROPERTY);
- this.exceptionDecl= exception;
- postReplaceChild(oldChild, exception, EXCEPTION_PROPERTY);
- }
-
- /**
- * Returns the body of this catch clause.
- *
- * @return the catch clause body
- */
- public Block getBody() {
- if (this.body == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.body == null) {
- preLazyInit();
- this.body = new Block(this.ast);
- postLazyInit(this.body, BODY_PROPERTY);
- }
- }
- }
- return this.body;
- }
-
- /**
- * Sets the body of this catch clause.
- *
- * @param body the catch clause block node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setBody(Block body) {
- if (body == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.body;
- preReplaceChild(oldChild, body, BODY_PROPERTY);
- this.body = body;
- postReplaceChild(oldChild, body, BODY_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- // treat Code as free
- return BASE_NODE_SIZE + 2 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.exceptionDecl == null ? 0 : getException().treeSize())
- + (this.body == null ? 0 : getBody().treeSize());
- }
-}
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
deleted file mode 100644
index 4073f203..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/CharacterLiteral.java
+++ /dev/null
@@ -1,389 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-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;
-
-/**
- * Character literal nodes.
- *
- * 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 CharacterLiteral extends Expression {
-
- /**
- * The "escapedValue" structural property of this node type.
- */
- public static final SimplePropertyDescriptor ESCAPED_VALUE_PROPERTY =
- new SimplePropertyDescriptor(CharacterLiteral.class, "escapedValue", String.class, MANDATORY); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List properyList = new ArrayList(2);
- createPropertyList(CharacterLiteral.class, properyList);
- addProperty(ESCAPED_VALUE_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The literal string, including quotes and escapes; defaults to the
- * literal for the character 'X'.
- */
- private String escapedValue = "\'X\'";//$NON-NLS-1$
-
- /**
- * Creates a new unparented character literal node owned by the given AST.
- * By default, the character literal denotes an unspecified character.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- CharacterLiteral(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final Object internalGetSetObjectProperty(SimplePropertyDescriptor property, boolean get, Object value) {
- if (property == ESCAPED_VALUE_PROPERTY) {
- if (get) {
- return getEscapedValue();
- } else {
- setEscapedValue((String) value);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetObjectProperty(property, get, value);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return CHARACTER_LITERAL;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- CharacterLiteral result = new CharacterLiteral(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setEscapedValue(getEscapedValue());
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- visitor.visit(this);
- visitor.endVisit(this);
- }
-
- /**
- * Returns the string value of this literal node. The value is the sequence
- * of characters that would appear in the source program, including
- * enclosing single quotes and embedded escapes.
- *
- * @return the escaped string value, including enclosing single quotes
- * and embedded escapes
- */
- public String getEscapedValue() {
- return this.escapedValue;
- }
-
- /**
- * Sets the string value of this literal node. The value is the sequence
- * of characters that would appear in the source program, including
- * enclosing single quotes and embedded escapes. For example,
- * <ul>
- * <li><code>'a'</code> <code>setEscapedValue("\'a\'")</code></li>
- * <li><code>'\n'</code> <code>setEscapedValue("\'\\n\'")</code></li>
- * </ul>
- *
- * @param value the string value, including enclosing single quotes
- * and embedded escapes
- * @exception IllegalArgumentException if the argument is incorrect
- */
- public void setEscapedValue(String value) {
- // check setInternalEscapedValue(String) if this method is changed
- if (value == null) {
- throw new IllegalArgumentException();
- }
- Scanner scanner = this.ast.scanner;
- char[] source = value.toCharArray();
- scanner.setSource(source);
- scanner.resetTo(0, source.length);
- try {
- int tokenType = scanner.getNextToken();
- switch(tokenType) {
- case TerminalTokens.TokenNameCharacterLiteral:
- break;
- default:
- throw new IllegalArgumentException();
- }
- } catch(InvalidInputException e) {
- throw new IllegalArgumentException();
- }
- preValueChange(ESCAPED_VALUE_PROPERTY);
- this.escapedValue = value;
- postValueChange(ESCAPED_VALUE_PROPERTY);
- }
-
-
- /* (omit javadoc for this method)
- * This method is a copy of setEscapedValue(String) that doesn't do any validation.
- */
- void internalSetEscapedValue(String value) {
- preValueChange(ESCAPED_VALUE_PROPERTY);
- this.escapedValue = value;
- postValueChange(ESCAPED_VALUE_PROPERTY);
- }
-
- /**
- * Returns the value of this literal node.
- * <p>
- * For example,
- * <pre>
- * CharacterLiteral s;
- * s.setEscapedValue("\'x\'");
- * assert s.charValue() == 'x';
- * </pre>
- * </p>
- *
- * @return the character value without enclosing quotes and embedded
- * escapes
- * @exception IllegalArgumentException if the literal value cannot be converted
- */
- public char charValue() {
- Scanner scanner = this.ast.scanner;
- char[] source = escapedValue.toCharArray();
- scanner.setSource(source);
- scanner.resetTo(0, source.length);
- int firstChar = scanner.getNextChar();
- int secondChar = scanner.getNextChar();
-
- if (firstChar == -1 || firstChar != '\'') {
- throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$
- }
- char value = (char) secondChar;
- char nextChar = (char) scanner.getNextChar();
- if (secondChar == '\\') {
- if (nextChar == -1) {
- throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$
- }
- switch(nextChar) {
- case 'b' :
- value = '\b';
- break;
- case 't' :
- value = '\t';
- break;
- case 'n' :
- value = '\n';
- break;
- case 'f' :
- value = '\f';
- break;
- case 'r' :
- value = '\r';
- break;
- case '\"':
- value = '\"';
- break;
- case '\'':
- value = '\'';
- break;
- case '\\':
- value = '\\';
- break;
- default : //octal (well-formed: ended by a ' )
- try {
- if (ScannerHelper.isDigit(nextChar)) {
- int number = ScannerHelper.getNumericValue(nextChar);
- nextChar = (char) scanner.getNextChar();
- if (nextChar == -1) {
- throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$
- }
- if (nextChar != '\'') {
- if (!ScannerHelper.isDigit(nextChar)) {
- throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$
- }
- number = (number * 8) + ScannerHelper.getNumericValue(nextChar);
- nextChar = (char) scanner.getNextChar();
- if (nextChar == -1) {
- throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$
- }
- if (nextChar != '\'') {
- if (!ScannerHelper.isDigit(nextChar)) {
- throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$
- }
- number = (number * 8) + ScannerHelper.getNumericValue(nextChar);
- }
- }
- return (char) number;
- } else {
- throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$
- }
- } catch (InvalidInputException e) {
- throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$
- }
- }
- nextChar = (char) scanner.getNextChar();
- if (nextChar == -1) {
- throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$
- }
- }
- if (nextChar == -1 || nextChar != '\'') {
- throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$
- }
- return value;
- }
- /**
- * Sets the value of this character literal node to the given character.
- * <p>
- * For example,
- * <pre>
- * CharacterLiteral s;
- * s.setCharValue('x');
- * assert s.charValue() == 'x';
- * assert s.getEscapedValue("\'x\'");
- * </pre>
- * </p>
- *
- * @param value the character value
- */
- public void setCharValue(char value) {
- StringBuffer b = new StringBuffer(3);
-
- b.append('\''); // opening delimiter
- switch(value) {
- case '\b' :
- b.append("\\b"); //$NON-NLS-1$
- break;
- case '\t' :
- b.append("\\t"); //$NON-NLS-1$
- break;
- case '\n' :
- b.append("\\n"); //$NON-NLS-1$
- break;
- case '\f' :
- b.append("\\f"); //$NON-NLS-1$
- break;
- case '\r' :
- b.append("\\r"); //$NON-NLS-1$
- break;
- case '\"':
- b.append("\\\""); //$NON-NLS-1$
- break;
- case '\'':
- b.append("\\\'"); //$NON-NLS-1$
- break;
- case '\\':
- b.append("\\\\"); //$NON-NLS-1$
- break;
- case '\0' :
- b.append("\\0"); //$NON-NLS-1$
- break;
- case '\1' :
- b.append("\\1"); //$NON-NLS-1$
- break;
- case '\2' :
- b.append("\\2"); //$NON-NLS-1$
- break;
- case '\3' :
- b.append("\\3"); //$NON-NLS-1$
- break;
- case '\4' :
- b.append("\\4"); //$NON-NLS-1$
- break;
- case '\5' :
- b.append("\\5"); //$NON-NLS-1$
- break;
- case '\6' :
- b.append("\\6"); //$NON-NLS-1$
- break;
- case '\7' :
- b.append("\\7"); //$NON-NLS-1$
- break;
- default:
- b.append(value);
- }
- b.append('\''); // closing delimiter
- setEscapedValue(b.toString());
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- int size = BASE_NODE_SIZE + 1 * 4 + stringSize(escapedValue);
- return size;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return memSize();
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ChildListPropertyDescriptor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ChildListPropertyDescriptor.java
deleted file mode 100644
index 2aa2ba7a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ChildListPropertyDescriptor.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.dom;
-
-/**
- * Descriptor for a child list property of an AST node.
- * A child list property is one whose value is a list of
- * {@link ASTNode}.
- *
- *
- * 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 final class ChildListPropertyDescriptor extends StructuralPropertyDescriptor {
-
- /**
- * Element type. For example, for a node type like
- * JavaScriptUnit, the "statements" property is Statement.class.
- * <p>
- * Field is private, but marked package-visible for fast
- * access from ASTNode.
- * </p>
- */
- final Class elementType;
-
- /**
- * Indicates whether a cycle is possible.
- * <p>
- * Field is private, but marked package-visible for fast
- * access from ASTNode.
- * </p>
- */
- final boolean cycleRisk;
-
- /**
- * Creates a new child list property descriptor with the given property id.
- * Note that this constructor is declared package-private so that
- * property descriptors can only be created by the AST
- * implementation.
- *
- * @param nodeClass concrete AST node type that owns this property
- * @param propertyId the property id
- * @param elementType the element type of this property
- * @param cycleRisk <code>true</code> if this property is at
- * risk of cycles, and <code>false</code> if there is no worry about cycles
- */
- ChildListPropertyDescriptor(Class nodeClass, String propertyId, Class elementType, boolean cycleRisk) {
- super(nodeClass, propertyId);
- if (elementType == null) {
- throw new IllegalArgumentException();
- }
- this.elementType = elementType;
- this.cycleRisk = cycleRisk;
- }
-
- /**
- * Returns the element type of this list property.
- * <p>
- * For example, for a node type like JavaScriptUnit,
- * the "imports" property returns <code>ImportDeclaration.class</code>.
- * </p>
- *
- * @return the element type of the property
- */
- public final Class getElementType() {
- return this.elementType;
- }
-
- /**
- * Returns whether this property is vulnerable to cycles.
- * <p>
- * A property is vulnerable to cycles if a node of the owning
- * type (that is, the type that owns this property) could legally
- * appear in the AST subtree below this property. For example,
- * the body property of a
- * {@link FunctionDeclaration} node
- * admits a body which might include statement that embeds
- * another {@link FunctionDeclaration} node.
- * On the other hand, the name property of a
- * FunctionDeclaration node admits only names, and thereby excludes
- * another FunctionDeclaration node.
- * </p>
- *
- * @return <code>true</code> if cycles are possible,
- * and <code>false</code> if cycles are impossible
- */
- public final boolean cycleRisk() {
- return this.cycleRisk;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ChildPropertyDescriptor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ChildPropertyDescriptor.java
deleted file mode 100644
index 8e32eb5e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ChildPropertyDescriptor.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.dom;
-
-/**
- * Descriptor for a child property of an AST node.
- * A child property is one whose value is an
- * {@link ASTNode}.
- *
- * @see org.eclipse.wst.jsdt.core.dom.ASTNode#getStructuralProperty(StructuralPropertyDescriptor)
- * @see org.eclipse.wst.jsdt.core.dom.ASTNode#setStructuralProperty(StructuralPropertyDescriptor, Object)
- *
- * 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 final class ChildPropertyDescriptor extends StructuralPropertyDescriptor {
-
- /**
- * Child type. For example, for a node type like
- * JavaScriptUnit, the "package" property is PackageDeclaration.class
- */
- private final Class childClass;
-
- /**
- * Indicates whether the child is mandatory. A child property is allowed
- * to be <code>null</code> only if it is not mandatory.
- */
- private final boolean mandatory;
-
- /**
- * Indicates whether a cycle is possible.
- * Field is private, but marked package-visible for fast
- * access from ASTNode.
- */
- final boolean cycleRisk;
-
- /**
- * Creates a new child property descriptor with the given property id.
- * Note that this constructor is declared package-private so that
- * property descriptors can only be created by the AST
- * implementation.
- *
- * @param nodeClass concrete AST node type that owns this property
- * @param propertyId the property id
- * @param childType the child type of this property
- * @param mandatory <code>true</code> if the property is mandatory,
- * and <code>false</code> if it is may be <code>null</code>
- * @param cycleRisk <code>true</code> if this property is at
- * risk of cycles, and <code>false</code> if there is no worry about cycles
- */
- ChildPropertyDescriptor(Class nodeClass, String propertyId, Class childType, boolean mandatory, boolean cycleRisk) {
- super(nodeClass, propertyId);
- if (childType == null || !ASTNode.class.isAssignableFrom(childType)) {
- throw new IllegalArgumentException();
- }
- this.childClass = childType;
- this.mandatory = mandatory;
- this.cycleRisk = cycleRisk;
- }
-
- /**
- * Returns the child type of this property.
- * <p>
- * For example, for a node type like JavaScriptUnit,
- * the "package" property returns <code>PackageDeclaration.class</code>.
- * </p>
- *
- * @return the child type of the property
- */
- public final Class getChildType() {
- return this.childClass;
- }
-
- /**
- * Returns whether this property is mandatory. A property value
- * is not allowed to be <code>null</code> if it is mandatory.
- *
- * @return <code>true</code> if the property is mandatory,
- * and <code>false</code> if it is may be <code>null</code>
- */
- public final boolean isMandatory() {
- return this.mandatory;
- }
-
- /**
- * Returns whether this property is vulnerable to cycles.
- * <p>
- * A property is vulnerable to cycles if a node of the owning
- * type (that is, the type that owns this property) could legally
- * appear in the AST subtree below this property. For example,
- * the body property of a
- * {@link FunctionDeclaration} node
- * admits a body which might include statement that embeds
- * another {@link FunctionDeclaration} node.
- * On the other hand, the name property of a
- * FunctionDeclaration node admits only names, and thereby excludes
- * another FunctionDeclaration node.
- * </p>
- *
- * @return <code>true</code> if cycles are possible,
- * and <code>false</code> if cycles are impossible
- */
- public final boolean cycleRisk() {
- return this.cycleRisk;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ClassInstanceCreation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ClassInstanceCreation.java
deleted file mode 100644
index d993b002..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ClassInstanceCreation.java
+++ /dev/null
@@ -1,607 +0,0 @@
-/*******************************************************************************
- * 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
- * Etienne Pfister <epfister@hsr.ch> - bug 231122
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Class instance creation expression AST node type.
- * For JLS2:
- * <pre>
- * ClassInstanceCreation:
- * [ Expression <b>.</b> ] <b>new</b> Name
- * <b>(</b> [ Expression { <b>,</b> Expression } ] <b>)</b>
- * [ AnonymousClassDeclaration ]
- * </pre>
- * For JLS3, type arguments are added
- * and the type name is generalized to a type so that parameterized
- * types can be instantiated:
- * <pre>
- * ClassInstanceCreation:
- * [ Expression <b>.</b> ]
- * <b>new</b> [ <b>&lt;</b> Type { <b>,</b> Type } <b>&gt;</b> ]
- * Type <b>(</b> [ Expression { <b>,</b> Expression } ] <b>)</b>
- * [ AnonymousClassDeclaration ]
- * </pre>
- * <p>
- * Not all node arragements will represent legal JavaScript constructs. In particular,
- * it is nonsense if the type is a primitive type or an array type (primitive
- * types cannot be instantiated, and array creations must be represented with
- * <code>ArrayCreation</code> nodes). The normal use is when the type is a
- * simple, qualified, or parameterized type.
- * </p>
- * <p>
- * A type like "A.B" can be represented either of two ways:
- * <ol>
- * <li>
- * <code>QualifiedType(SimpleType(SimpleName("A")),SimpleName("B"))</code>
- * </li>
- * <li>
- * <code>SimpleType(QualifiedName(SimpleName("A"),SimpleName("B")))</code>
- * </li>
- * </ol>
- * The first form is preferred when "A" is known to be a type (as opposed
- * to a package). However, a parser cannot always determine this. Clients
- * should be prepared to handle either rather than make assumptions.
- * (Note also that the first form became possible as of JLS3; only the second
- * form existed in JLS2.)
- * </p>
- *
- * 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 ClassInstanceCreation extends Expression {
-
- /**
- * The "typeArguments" structural property of this node type .
- */
- public static final ChildListPropertyDescriptor TYPE_ARGUMENTS_PROPERTY =
- new ChildListPropertyDescriptor(ClassInstanceCreation.class, "typeArguments", Type.class, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "expression" structural property of this node type.
- */
- public static final ChildPropertyDescriptor EXPRESSION_PROPERTY =
- new ChildPropertyDescriptor(ClassInstanceCreation.class, "expression", Expression.class, OPTIONAL, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "name" structural property of this node type .
- */
- public static final ChildPropertyDescriptor NAME_PROPERTY =
- new ChildPropertyDescriptor(ClassInstanceCreation.class, "name", Name.class, MANDATORY, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "type" structural property of this node type (added in JLS3 API).
- */
- public static final ChildPropertyDescriptor TYPE_PROPERTY =
- new ChildPropertyDescriptor(ClassInstanceCreation.class, "type", Type.class, MANDATORY, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "arguments" structural property of this node type.
- */
- public static final ChildListPropertyDescriptor ARGUMENTS_PROPERTY =
- new ChildListPropertyDescriptor(ClassInstanceCreation.class, "arguments", Expression.class, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "anonymousClassDeclaration" structural property of this node type.
- */
- public static final ChildPropertyDescriptor ANONYMOUS_CLASS_DECLARATION_PROPERTY =
- new ChildPropertyDescriptor(ClassInstanceCreation.class, "anonymousClassDeclaration", AnonymousClassDeclaration.class, OPTIONAL, CYCLE_RISK); //$NON-NLS-1$
-
- public static final ChildPropertyDescriptor MEMBER_PROPERTY =
- new ChildPropertyDescriptor(ClassInstanceCreation.class, "member", AnonymousClassDeclaration.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS_2_0;
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS_3_0;
-
- static {
- List properyList = new ArrayList(5);
- createPropertyList(ClassInstanceCreation.class, properyList);
- addProperty(EXPRESSION_PROPERTY, properyList);
- addProperty(NAME_PROPERTY, properyList);
- addProperty(ARGUMENTS_PROPERTY, properyList);
- addProperty(ANONYMOUS_CLASS_DECLARATION_PROPERTY, properyList);
- addProperty(MEMBER_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS_2_0 = reapPropertyList(properyList);
-
- properyList = new ArrayList(6);
- createPropertyList(ClassInstanceCreation.class, properyList);
- addProperty(EXPRESSION_PROPERTY, properyList);
- addProperty(TYPE_ARGUMENTS_PROPERTY, properyList);
- addProperty(TYPE_PROPERTY, properyList);
- addProperty(ARGUMENTS_PROPERTY, properyList);
- addProperty(ANONYMOUS_CLASS_DECLARATION_PROPERTY, properyList);
- addProperty(MEMBER_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS_3_0 = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- */
- public static List propertyDescriptors(int apiLevel) {
- if (apiLevel == AST.JLS2_INTERNAL) {
- return PROPERTY_DESCRIPTORS_2_0;
- } else {
- return PROPERTY_DESCRIPTORS_3_0;
- }
- }
-
- /**
- * The optional expression; <code>null</code> for none; defaults to none.
- */
- private Expression optionalExpression = null;
-
- private Expression member = null;
-
- /**
- * The type arguments (element type: <code>Type</code>).
- * Defaults to an empty list
- * (see constructor).
- */
- private ASTNode.NodeList typeArguments = null;
-
- /**
- * The type name; lazily initialized; defaults to a unspecified,
- * legal type name.
- */
- private Name typeName = null;
-
- /**
- * The type; lazily initialized; defaults to a unspecified type.
- */
- private Type type = null;
-
- /**
- * The list of argument expressions (element type:
- * <code>Expression</code>). Defaults to an empty list.
- */
- private ASTNode.NodeList arguments =
- new ASTNode.NodeList(ARGUMENTS_PROPERTY);
-
- /**
- * The optional anonymous class declaration; <code>null</code> for none;
- * defaults to none.
- */
- private AnonymousClassDeclaration optionalAnonymousClassDeclaration = null;
-
- /**
- * Creates a new AST node for a class instance creation expression owned
- * by the given AST. By default, there is no qualifying expression,
- * an empty list of type parameters, an unspecified type, an empty
- * list of arguments, and does not declare an anonymous class.
- * <p>
- * N.B. This constructor is package-private; all subclasses must be
- * declared in the same package; clients are unable to declare
- * additional subclasses.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- ClassInstanceCreation (AST ast) {
- super(ast);
- if (ast.apiLevel >= AST.JLS3) {
- this.typeArguments = new ASTNode.NodeList(TYPE_ARGUMENTS_PROPERTY);
- }
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == EXPRESSION_PROPERTY) {
- if (get) {
- return getExpression();
- } else {
- setExpression((Expression) child);
- return null;
- }
- }
- if (property == NAME_PROPERTY) {
- if (get) {
- return getName();
- } else {
- setName((Name) child);
- return null;
- }
- }
- if (property == MEMBER_PROPERTY) {
- if (get) {
- return getMember();
- } else {
- setMember((Expression) child);
- return null;
- }
- }
- if (property == TYPE_PROPERTY) {
- if (get) {
- return getType();
- } else {
- setType((Type) child);
- return null;
- }
- }
- if (property == ANONYMOUS_CLASS_DECLARATION_PROPERTY) {
- if (get) {
- return getAnonymousClassDeclaration();
- } else {
- setAnonymousClassDeclaration((AnonymousClassDeclaration) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalGetChildListProperty(ChildListPropertyDescriptor property) {
- if (property == ARGUMENTS_PROPERTY) {
- return arguments();
- }
- if (property == TYPE_ARGUMENTS_PROPERTY) {
- return typeArguments();
- }
- // allow default implementation to flag the error
- return super.internalGetChildListProperty(property);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return CLASS_INSTANCE_CREATION;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- ClassInstanceCreation result = new ClassInstanceCreation(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setExpression(
- (Expression) ASTNode.copySubtree(target, getExpression()));
- result.setMember(
- (Expression) ASTNode.copySubtree(target, getMember()));
- if (this.ast.apiLevel == AST.JLS2_INTERNAL) {
- result.setName((Name) getName().clone(target));
- }
- if (this.ast.apiLevel >= AST.JLS3) {
- result.typeArguments().addAll(ASTNode.copySubtrees(target, typeArguments()));
-
- Type type = getType();
- if(type != null){
- result.setType((Type) type.clone(target));
- }
- }
- result.arguments().addAll(ASTNode.copySubtrees(target, arguments()));
- result.setAnonymousClassDeclaration(
- (AnonymousClassDeclaration)
- ASTNode.copySubtree(target, getAnonymousClassDeclaration()));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChild(visitor, getExpression());
- acceptChild(visitor, getMember());
- if (this.ast.apiLevel == AST.JLS2_INTERNAL) {
- acceptChild(visitor, getName());
- }
- if (this.ast.apiLevel >= AST.JLS3) {
- acceptChildren(visitor, this.typeArguments);
- acceptChild(visitor, getType());
- }
- acceptChildren(visitor, this.arguments);
- acceptChild(visitor, getAnonymousClassDeclaration());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the expression of this class instance creation expression, or
- * <code>null</code> if there is none.
- *
- * @return the expression node, or <code>null</code> if there is none
- */
- public Expression getExpression() {
- return this.optionalExpression;
- }
-
- public Expression getMember() {
- return this.member;
- }
-
- /**
- * Sets or clears the expression of this class instance creation expression.
- *
- * @param expression the expression node, or <code>null</code> if
- * there is none
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setExpression(Expression expression) {
- // a ClassInstanceCreation may occur inside an Expression
- // must check cycles
- ASTNode oldChild = this.optionalExpression;
- preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY);
- this.optionalExpression = expression;
- postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY);
- }
-
- public void setMember(Expression expression) {
- // a ClassInstanceCreation may occur inside an Expression
- // must check cycles
- ASTNode oldChild = this.member;
- preReplaceChild(oldChild, expression, MEMBER_PROPERTY);
- this.member = expression;
- postReplaceChild(oldChild, expression, MEMBER_PROPERTY);
- }
-
- /**
- * Returns the live ordered list of type arguments of this class
- * instance creation (added in JLS3 API).
- *
- * @return the live list of type arguments
- * (element type: <code>Type</code>)
- * @exception UnsupportedOperationException if this operation is used in
- * a JLS2 AST
- */
- public List typeArguments() {
- // more efficient than just calling unsupportedIn2() to check
- if (this.typeArguments == null) {
- unsupportedIn2();
- }
- return this.typeArguments;
- }
-
- /**
- * Returns the name of the type instantiated in this class instance
- * creation expression (JLS2 API only).
- *
- * @return the type name node
- * @exception UnsupportedOperationException if this operation is used in
- * an AST later than JLS2
- * @deprecated In the JLS3 API, this method is replaced by
- * {@link #getType()}, which returns a <code>Type</code> instead of a
- * <code>Name</code>.
- */
- public Name getName() {
- return internalGetName();
- }
-
- /**
- * Internal synonym for deprecated method. Used to avoid
- * deprecation warnings.
- */
- /*package*/ Name internalGetName() {
- supportedOnlyIn2();
- if (this.typeName == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.typeName == null) {
- preLazyInit();
- this.typeName = new SimpleName(this.ast);
- postLazyInit(this.typeName, NAME_PROPERTY);
- }
- }
- }
- return typeName;
- }
-
- /**
- * Sets the name of the type instantiated in this class instance
- * creation expression (JLS2 API only).
- *
- * @param name the new type name
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>`
- * </ul>
- * @exception UnsupportedOperationException if this operation is used in
- * an AST later than JLS2
- * @deprecated In the JLS3 API, this method is replaced by
- * {@link #setType(Type)}, which expects a <code>Type</code> instead of
- * a <code>Name</code>.
- */
- public void setName(Name name) {
- internalSetName(name);
- }
-
- /**
- * Internal synonym for deprecated method. Used to avoid
- * deprecation warnings.
- */
- /*package*/ void internalSetName(Name name) {
- supportedOnlyIn2();
- if (name == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.typeName;
- preReplaceChild(oldChild, name, NAME_PROPERTY);
- this.typeName = name;
- postReplaceChild(oldChild, name, NAME_PROPERTY);
- }
-
- /**
- * Returns the type instantiated in this class instance creation
- * expression (added in JLS3 API).
- *
- * @return the type node
- * @exception UnsupportedOperationException if this operation is used in
- * a JLS2 AST
- */
- public Type getType() {
- unsupportedIn2();
-// if (this.type == null) {
-// // lazy init must be thread-safe for readers
-// synchronized (this) {
-// if (this.type == null) {
-// preLazyInit();
-// this.type = new SimpleType(this.ast);
-// postLazyInit(this.type, TYPE_PROPERTY);
-// }
-// }
-// }
- return this.type;
- }
-
- /**
- * Sets the type instantiated in this class instance creation
- * expression (added in JLS3 API).
- *
- * @param type the new type
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>`
- * </ul>
- * @exception UnsupportedOperationException if this operation is used in
- * a JLS2 AST
- */
- public void setType(Type type) {
- unsupportedIn2();
- if (type == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.type;
- preReplaceChild(oldChild, type, TYPE_PROPERTY);
- this.type = type;
- postReplaceChild(oldChild, type, TYPE_PROPERTY);
- }
-
- /**
- * Returns the live ordered list of argument expressions in this class
- * instance creation expression.
- *
- * @return the live list of argument expressions (possibly empty)
- * (element type: <code>Expression</code>)
- */
- public List arguments() {
- return this.arguments;
- }
-
- /**
- * Returns the anonymous class declaration introduced by this
- * class instance creation expression, if it has one.
- *
- * @return the anonymous class declaration, or <code>null</code> if none
- */
- public AnonymousClassDeclaration getAnonymousClassDeclaration() {
- return this.optionalAnonymousClassDeclaration;
- }
-
- /**
- * Sets whether this class instance creation expression declares
- * an anonymous class (that is, has class body declarations).
- *
- * @param decl the anonymous class declaration, or <code>null</code>
- * if none
- */
- public void setAnonymousClassDeclaration(AnonymousClassDeclaration decl) {
- ASTNode oldChild = this.optionalAnonymousClassDeclaration;
- preReplaceChild(oldChild, decl, ANONYMOUS_CLASS_DECLARATION_PROPERTY);
- this.optionalAnonymousClassDeclaration = decl;
- postReplaceChild(oldChild, decl, ANONYMOUS_CLASS_DECLARATION_PROPERTY);
- }
-
- /**
- * Resolves and returns the binding for the constructor invoked by this
- * expression. For anonymous classes, the binding is that of the anonymous
- * constructor.
- * <p>
- * Note that bindings are generally unavailable unless requested when the
- * AST is being built.
- * </p>
- *
- * @return the constructor binding, or <code>null</code> if the binding
- * cannot be resolved
- */
- public IFunctionBinding resolveConstructorBinding() {
- return this.ast.getBindingResolver().resolveConstructor(this);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- // treat Code as free
- return BASE_NODE_SIZE + 6 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- // n.b. type == null for ast.API_LEVEL == JLS2
- // n.b. typeArguments == null for ast.API_LEVEL == JLS2
- // n.b. typeName == null for ast.API_LEVEL >= JLS3
- return
- memSize()
- + (this.typeName == null ? 0 : getName().treeSize())
- + (this.type == null ? 0 : getType().treeSize())
- + (this.optionalExpression == null ? 0 : getExpression().treeSize())
- + (this.member == null ? 0 : getMember().treeSize())
- + (this.typeArguments == null ? 0 : this.typeArguments.listSize())
- + (this.arguments == null ? 0 : this.arguments.listSize())
- + (this.optionalAnonymousClassDeclaration == null ? 0 : getAnonymousClassDeclaration().treeSize());
- }
-}
-
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
deleted file mode 100644
index 087b9bc9..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Comment.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.dom;
-
-/**
- * Abstract base class for all AST nodes that represent comments.
- * There are exactly three kinds of comment:
- * line comments ({@link LineComment}),
- * block comments ({@link BlockComment}), and
- * doc comments ({@link JSdoc}).
- * <p>
- * <pre>
- * Comment:
- * LineComment
- * BlockComment
- * JSdoc
- * </pre>
- * </p>
- *
- * 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 Comment extends ASTNode {
-
- /**
- * Alternate root node, or <code>null</code> if none.
- * Initially <code>null</code>.
- */
- private ASTNode alternateRoot = null;
-
- /**
- * Creates a new AST node for a comment owned by the given AST.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- Comment(AST ast) {
- super(ast);
- }
-
- /**
- * Returns whether this comment is a block comment
- * (<code>BlockComment</code>).
- *
- * @return <code>true</code> if this is a block comment, and
- * <code>false</code> otherwise
- */
- public final boolean isBlockComment() {
- return (this instanceof BlockComment);
- }
-
- /**
- * Returns whether this comment is a line comment
- * (<code>LineComment</code>).
- *
- * @return <code>true</code> if this is a line comment, and
- * <code>false</code> otherwise
- */
- public final boolean isLineComment() {
- return (this instanceof LineComment);
- }
-
- /**
- * Returns whether this comment is a doc comment
- * (<code>JSdoc</code>).
- *
- * @return <code>true</code> if this is a doc comment, and
- * <code>false</code> otherwise
- */
- public final boolean isDocComment() {
- return (this instanceof JSdoc);
- }
-
- /**
- * Returns the root AST node that this comment occurs
- * within, or <code>null</code> if none (or not recorded).
- * <p>
- * Typically, the comment nodes created while parsing a compilation
- * unit are not considered descendents of the normal AST
- * root, namely an {@link JavaScriptUnit}. Instead, these
- * comment nodes exist outside the normal AST and each is
- * a root in its own right. This optional property provides
- * a well-known way to navigate from the comment to the
- * javaScript unit in such cases. Note that the alternate root
- * property is not one of the comment node's children. It is simply a
- * reference to a node.
- * </p>
- *
- * @return the alternate root node, or <code>null</code>
- * if none
- * @see #setAlternateRoot(ASTNode)
- */
- public final ASTNode getAlternateRoot() {
- return this.alternateRoot;
- }
-
- /**
- * Returns the root AST node that this comment occurs
- * within, or <code>null</code> if none (or not recorded).
- * <p>
- * </p>
- *
- * @param root the alternate root node, or <code>null</code>
- * if none
- * @see #getAlternateRoot()
- */
- public final void setAlternateRoot(ASTNode root) {
- // alternate root is *not* considered a structural property
- // but we protect them nevertheless
- checkModifiable();
- this.alternateRoot = root;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return BASE_NODE_SIZE + 1 * 4;
- }
-}
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
deleted file mode 100644
index 3ac84bdb..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ConditionalExpression.java
+++ /dev/null
@@ -1,332 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Conditional expression AST node type.
- *
- * <pre>
- * ConditionalExpression:
- * Expression <b>?</b> Expression <b>:</b> Expression
- * </pre>
- *
- * 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 ConditionalExpression extends Expression {
-
- /**
- * The "expression" structural property of this node type.
- */
- public static final ChildPropertyDescriptor EXPRESSION_PROPERTY =
- new ChildPropertyDescriptor(ConditionalExpression.class, "expression", Expression.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "thenExpression" structural property of this node type.
- */
- public static final ChildPropertyDescriptor THEN_EXPRESSION_PROPERTY =
- new ChildPropertyDescriptor(ConditionalExpression.class, "thenExpression", Expression.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "elseExpression" structural property of this node type.
- */
- public static final ChildPropertyDescriptor ELSE_EXPRESSION_PROPERTY =
- new ChildPropertyDescriptor(ConditionalExpression.class, "elseExpression", Expression.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List properyList = new ArrayList(4);
- createPropertyList(ConditionalExpression.class, properyList);
- addProperty(EXPRESSION_PROPERTY, properyList);
- addProperty(THEN_EXPRESSION_PROPERTY, properyList);
- addProperty(ELSE_EXPRESSION_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The condition expression; lazily initialized; defaults to an unspecified,
- * but legal, expression.
- */
- private Expression conditionExpression = null;
-
- /**
- * The "then" expression; lazily initialized; defaults to an unspecified,
- * but legal, expression.
- */
- private Expression thenExpression = null;
-
- /**
- * The "else" expression; lazily initialized; defaults to an unspecified,
- * but legal, expression.
- */
- private Expression elseExpression = null;
-
- /**
- * Creates a new unparented conditional expression node owned by the given
- * AST. By default, the condition, "then", and "else" expresssions are
- * unspecified, but legal.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- ConditionalExpression(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == EXPRESSION_PROPERTY) {
- if (get) {
- return getExpression();
- } else {
- setExpression((Expression) child);
- return null;
- }
- }
- if (property == THEN_EXPRESSION_PROPERTY) {
- if (get) {
- return getThenExpression();
- } else {
- setThenExpression((Expression) child);
- return null;
- }
- }
- if (property == ELSE_EXPRESSION_PROPERTY) {
- if (get) {
- return getElseExpression();
- } else {
- setElseExpression((Expression) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return CONDITIONAL_EXPRESSION;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- ConditionalExpression result = new ConditionalExpression(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setExpression((Expression) getExpression().clone(target));
- result.setThenExpression(
- (Expression) getThenExpression().clone(target));
- result.setElseExpression(
- (Expression) getElseExpression().clone(target));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChild(visitor, getExpression());
- acceptChild(visitor, getThenExpression());
- acceptChild(visitor, getElseExpression());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the condition of this conditional expression.
- *
- * @return the condition node
- */
- public Expression getExpression() {
- if (this.conditionExpression == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.conditionExpression == null) {
- preLazyInit();
- this.conditionExpression = new SimpleName(this.ast);
- postLazyInit(this.conditionExpression, EXPRESSION_PROPERTY);
- }
- }
- }
- return this.conditionExpression;
- }
-
- /**
- * Sets the condition of this conditional expression.
- *
- * @param expression the condition node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setExpression(Expression expression) {
- if (expression == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.conditionExpression;
- preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY);
- this.conditionExpression = expression;
- postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY);
- }
-
- /**
- * Returns the "then" part of this conditional expression.
- *
- * @return the "then" expression node
- */
- public Expression getThenExpression() {
- if (this.thenExpression == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.thenExpression == null) {
- preLazyInit();
- this.thenExpression = new SimpleName(this.ast);
- postLazyInit(this.thenExpression, THEN_EXPRESSION_PROPERTY);
- }
- }
- }
- return this.thenExpression;
- }
-
- /**
- * Sets the "then" part of this conditional expression.
- *
- * @param expression the "then" expression node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setThenExpression(Expression expression) {
- if (expression == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.thenExpression;
- preReplaceChild(oldChild, expression, THEN_EXPRESSION_PROPERTY);
- this.thenExpression = expression;
- postReplaceChild(oldChild, expression, THEN_EXPRESSION_PROPERTY);
- }
-
- /**
- * Returns the "else" part of this conditional expression.
- *
- * @return the "else" expression node
- */
- public Expression getElseExpression() {
- if (this.elseExpression == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.elseExpression == null) {
- preLazyInit();
- this.elseExpression = new SimpleName(this.ast);
- postLazyInit(this.elseExpression, ELSE_EXPRESSION_PROPERTY);
- }
- }
- }
- return this.elseExpression;
- }
-
- /**
- * Sets the "else" part of this conditional expression.
- *
- * @param expression the "else" expression node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setElseExpression(Expression expression) {
- if (expression == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.elseExpression;
- preReplaceChild(oldChild, expression, ELSE_EXPRESSION_PROPERTY);
- this.elseExpression = expression;
- postReplaceChild(oldChild, expression, ELSE_EXPRESSION_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- // treat Code as free
- return BASE_NODE_SIZE + 3 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.conditionExpression == null ? 0 : getExpression().treeSize())
- + (this.thenExpression == null ? 0 : getThenExpression().treeSize())
- + (this.elseExpression == null ? 0 : getElseExpression().treeSize());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ConstructorInvocation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ConstructorInvocation.java
deleted file mode 100644
index 747edb67..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ConstructorInvocation.java
+++ /dev/null
@@ -1,247 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Alternate constructor invocation statement AST node type.
- * For JLS2:
- * <pre>
- * ConstructorInvocation:
- * <b>this</b> <b>(</b> [ Expression { <b>,</b> Expression } ] <b>)</b> <b>;</b>
- * </pre>
- * For JLS3, type arguments are added:
- * <pre>
- * ConstructorInvocation:
- * [ <b>&lt;</b> Type { <b>,</b> Type } <b>&gt;</b> ]
- * <b>this</b> <b>(</b> [ Expression { <b>,</b> Expression } ] <b>)</b> <b>;</b>
- * </pre>
- *
- * 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 ConstructorInvocation extends Statement {
-
- /**
- * The "typeArguments" structural property of this node type (added in JLS3 API).
- */
- public static final ChildListPropertyDescriptor TYPE_ARGUMENTS_PROPERTY =
- new ChildListPropertyDescriptor(ConstructorInvocation.class, "typeArguments", Type.class, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "arguments" structural property of this node type.
- */
- public static final ChildListPropertyDescriptor ARGUMENTS_PROPERTY =
- new ChildListPropertyDescriptor(ConstructorInvocation.class, "arguments", Expression.class, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS_2_0;
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS_3_0;
-
- static {
- List properyList = new ArrayList(2);
- createPropertyList(ConstructorInvocation.class, properyList);
- addProperty(ARGUMENTS_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS_2_0 = reapPropertyList(properyList);
-
- properyList = new ArrayList(3);
- createPropertyList(ConstructorInvocation.class, properyList);
- addProperty(TYPE_ARGUMENTS_PROPERTY, properyList);
- addProperty(ARGUMENTS_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS_3_0 = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- */
- public static List propertyDescriptors(int apiLevel) {
- if (apiLevel == AST.JLS2_INTERNAL) {
- return PROPERTY_DESCRIPTORS_2_0;
- } else {
- return PROPERTY_DESCRIPTORS_3_0;
- }
- }
-
- /**
- * The type arguments (element type: <code>Type</code>).
- * Null in JLS2. Added in JLS3; defaults to an empty list
- * (see constructor).
- */
- private ASTNode.NodeList typeArguments = null;
-
- /**
- * The list of argument expressions (element type:
- * <code>Expression</code>). Defaults to an empty list.
- */
- private ASTNode.NodeList arguments =
- new ASTNode.NodeList(ARGUMENTS_PROPERTY);
-
- /**
- * Creates a new AST node for an alternate constructor invocation statement
- * owned by the given AST. By default, an empty list of arguments.
- *
- * @param ast the AST that is to own this node
- */
- ConstructorInvocation(AST ast) {
- super(ast);
- if (ast.apiLevel >= AST.JLS3) {
- this.typeArguments = new ASTNode.NodeList(TYPE_ARGUMENTS_PROPERTY);
- }
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalGetChildListProperty(ChildListPropertyDescriptor property) {
- if (property == ARGUMENTS_PROPERTY) {
- return arguments();
- }
- if (property == TYPE_ARGUMENTS_PROPERTY) {
- return typeArguments();
- }
- // allow default implementation to flag the error
- return super.internalGetChildListProperty(property);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return CONSTRUCTOR_INVOCATION;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- ConstructorInvocation result = new ConstructorInvocation(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.copyLeadingComment(this);
- if (this.ast.apiLevel >= AST.JLS3) {
- result.typeArguments().addAll(ASTNode.copySubtrees(target, typeArguments()));
- }
- result.arguments().addAll(ASTNode.copySubtrees(target, arguments()));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- if (this.ast.apiLevel >= AST.JLS3) {
- acceptChildren(visitor, this.typeArguments);
- }
- acceptChildren(visitor, this.arguments);
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the live ordered list of type arguments of this constructor
- * invocation (added in JLS3 API).
- *
- * @return the live list of type arguments
- * (element type: <code>Type</code>)
- * @exception UnsupportedOperationException if this operation is used in
- * a JLS2 AST
- */
- public List typeArguments() {
- // more efficient than just calling unsupportedIn2() to check
- if (this.typeArguments == null) {
- unsupportedIn2();
- }
- return this.typeArguments;
- }
-
- /**
- * Returns the live ordered list of argument expressions in this alternate
- * constructor invocation statement.
- *
- * @return the live list of argument expressions
- * (element type: <code>Expression</code>)
- */
- public List arguments() {
- return this.arguments;
- }
-
- /**
- * Resolves and returns the binding for the constructor invoked by this
- * expression.
- * <p>
- * Note that bindings are generally unavailable unless requested when the
- * AST is being built.
- * </p>
- *
- * @return the constructor binding, or <code>null</code> if the binding
- * cannot be resolved
- */
- public IFunctionBinding resolveConstructorBinding() {
- return this.ast.getBindingResolver().resolveConstructor(this);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- // treat Code as free
- return BASE_NODE_SIZE + 2 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.typeArguments == null ? 0 : this.typeArguments.listSize())
- + (this.arguments == null ? 0 : this.arguments.listSize());
- }
-}
-
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
deleted file mode 100644
index 1d270bac..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ContinueStatement.java
+++ /dev/null
@@ -1,188 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Continue statement AST node type.
- *
- * <pre>
- * ContinueStatement:
- * <b>continue</b> [ Identifier ] <b>;</b>
- * </pre>
- *
- * 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 ContinueStatement extends Statement {
-
- /**
- * The "label" structural property of this node type.
- */
- public static final ChildPropertyDescriptor LABEL_PROPERTY =
- new ChildPropertyDescriptor(ContinueStatement.class, "label", SimpleName.class, OPTIONAL, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List properyList = new ArrayList(2);
- createPropertyList(ContinueStatement.class, properyList);
- addProperty(LABEL_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The label, or <code>null</code> if none; none by default.
- */
- private SimpleName optionalLabel = null;
-
- /**
- * Creates a new unparented continue statement node owned by the given
- * AST. By default, the continue statement has no label.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- ContinueStatement(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == LABEL_PROPERTY) {
- if (get) {
- return getLabel();
- } else {
- setLabel((SimpleName) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return CONTINUE_STATEMENT;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- ContinueStatement result = new ContinueStatement(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.copyLeadingComment(this);
- result.setLabel((SimpleName) ASTNode.copySubtree(target, getLabel()));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- acceptChild(visitor, getLabel());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the label of this continue statement, or <code>null</code> if
- * there is none.
- *
- * @return the label, or <code>null</code> if there is none
- */
- public SimpleName getLabel() {
- return this.optionalLabel;
- }
-
- /**
- * Sets or clears the label of this continue statement.
- *
- * @param label the label, or <code>null</code> if
- * there is none
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public void setLabel(SimpleName label) {
- ASTNode oldChild = this.optionalLabel;
- preReplaceChild(oldChild, label, LABEL_PROPERTY);
- this.optionalLabel = label;
- postReplaceChild(oldChild, label, LABEL_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return super.memSize() + 1 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (optionalLabel == null ? 0 : getLabel().treeSize());
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/DefaultASTVisitor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/DefaultASTVisitor.java
deleted file mode 100644
index 590b50a3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/DefaultASTVisitor.java
+++ /dev/null
@@ -1,533 +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.core.dom;
-/**
- *
- * 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.
-*/
-class DefaultASTVisitor extends ASTVisitor {
-
-
- /**
- *
- */
- public DefaultASTVisitor() {
- super();
- }
-
- /**
- *
- */
- public DefaultASTVisitor(boolean visitDocTags) {
- super(visitDocTags);
- }
-
- public void endVisit(AnonymousClassDeclaration node) {
- endVisitNode(node);
- }
-
- public void endVisit(ArrayAccess node) {
- endVisitNode(node);
- }
-
- public void endVisit(ArrayCreation node) {
- endVisitNode(node);
- }
-
- public void endVisit(ArrayInitializer node) {
- endVisitNode(node);
- }
-
- public void endVisit(ArrayType node) {
- endVisitNode(node);
- }
-
- public void endVisit(Assignment node) {
- endVisitNode(node);
- }
-
- public void endVisit(Block node) {
- endVisitNode(node);
- }
-
- /* since 3.0 */
- public void endVisit(BlockComment node) {
- endVisitNode(node);
- }
-
- public void endVisit(BooleanLiteral node) {
- endVisitNode(node);
- }
-
- public void endVisit(BreakStatement node) {
- endVisitNode(node);
- }
- public void endVisit(CatchClause node) {
- endVisitNode(node);
- }
- public void endVisit(CharacterLiteral node) {
- endVisitNode(node);
- }
- public void endVisit(ClassInstanceCreation node) {
- endVisitNode(node);
- }
- public void endVisit(JavaScriptUnit node) {
- endVisitNode(node);
- }
- public void endVisit(ConditionalExpression node) {
- endVisitNode(node);
- }
- public void endVisit(ConstructorInvocation node) {
- endVisitNode(node);
- }
- public void endVisit(ContinueStatement node) {
- endVisitNode(node);
- }
- public void endVisit(DoStatement node) {
- endVisitNode(node);
- }
- public void endVisit(EmptyStatement node) {
- endVisitNode(node);
- }
- public void endVisit(EnhancedForStatement node) {
- endVisitNode(node);
- }
-
- public void endVisit(ExpressionStatement node) {
- endVisitNode(node);
- }
- public void endVisit(FieldAccess node) {
- endVisitNode(node);
- }
- public void endVisit(FieldDeclaration node) {
- endVisitNode(node);
- }
- public void endVisit(ForInStatement node) {
- endVisitNode(node);
- }
- public void endVisit(ForStatement node) {
- endVisitNode(node);
- }
- public void endVisit(FunctionExpression node) {
- endVisitNode(node);
- }
- public void endVisit(IfStatement node) {
- endVisitNode(node);
- }
- public void endVisit(ImportDeclaration node) {
- endVisitNode(node);
- }
- public void endVisit(InferredType node) {
- endVisitNode(node);
- }
- public void endVisit(InfixExpression node) {
- endVisitNode(node);
- }
- public void endVisit(Initializer node) {
- endVisitNode(node);
- }
- public void endVisit(InstanceofExpression node) {
- endVisitNode(node);
- }
- public void endVisit(JSdoc node) {
- endVisitNode(node);
- }
- public void endVisit(LabeledStatement node) {
- endVisitNode(node);
- }
- public void endVisit(LineComment node) {
- endVisitNode(node);
- }
- public void endVisit(ListExpression node) {
- endVisitNode(node);
- }
- public void endVisit(MemberRef node) {
- endVisitNode(node);
- }
- public void endVisit(FunctionDeclaration node) {
- endVisitNode(node);
- }
- public void endVisit(FunctionInvocation node) {
- endVisitNode(node);
- }
- public void endVisit(FunctionRef node) {
- endVisitNode(node);
- }
- public void endVisit(FunctionRefParameter node) {
- endVisitNode(node);
- }
- public void endVisit(NullLiteral node) {
- endVisitNode(node);
- }
- public void endVisit(NumberLiteral node) {
- endVisitNode(node);
- }
-
- public void endVisit(ObjectLiteral node) {
- endVisitNode(node);
- }
-
- public void endVisit(ObjectLiteralField node) {
- endVisitNode(node);
- }
- public void endVisit(PackageDeclaration node) {
- endVisitNode(node);
- }
- public void endVisit(ParenthesizedExpression node) {
- endVisitNode(node);
- }
- public void endVisit(PostfixExpression node) {
- endVisitNode(node);
- }
- public void endVisit(PrefixExpression node) {
- endVisitNode(node);
- }
- public void endVisit(PrimitiveType node) {
- endVisitNode(node);
- }
- public void endVisit(QualifiedName node) {
- endVisitNode(node);
- }
- public void endVisit(QualifiedType node) {
- endVisitNode(node);
- }
- public void endVisit(RegularExpressionLiteral node) {
- endVisitNode(node);
- }
- public void endVisit(ReturnStatement node) {
- endVisitNode(node);
- }
- public void endVisit(SimpleName node) {
- endVisitNode(node);
- }
- public void endVisit(SimpleType node) {
- endVisitNode(node);
- }
- public void endVisit(SingleVariableDeclaration node) {
- endVisitNode(node);
- }
- public void endVisit(StringLiteral node) {
- endVisitNode(node);
- }
- public void endVisit(SuperConstructorInvocation node) {
- endVisitNode(node);
- }
- public void endVisit(SuperFieldAccess node) {
- endVisitNode(node);
- }
- public void endVisit(SuperMethodInvocation node) {
- endVisitNode(node);
- }
- public void endVisit(SwitchCase node) {
- endVisitNode(node);
- }
- public void endVisit(SwitchStatement node) {
- endVisitNode(node);
- }
- public void endVisit(TagElement node) {
- endVisitNode(node);
- }
- public void endVisit(TextElement node) {
- endVisitNode(node);
- }
- public void endVisit(ThisExpression node) {
- endVisitNode(node);
- }
- public void endVisit(ThrowStatement node) {
- endVisitNode(node);
- }
- public void endVisit(TryStatement node) {
- endVisitNode(node);
- }
- public void endVisit(TypeDeclaration node) {
- endVisitNode(node);
- }
- public void endVisit(TypeDeclarationStatement node) {
- endVisitNode(node);
- }
- public void endVisit(TypeLiteral node) {
- endVisitNode(node);
- }
- public void endVisit(UndefinedLiteral node) {
- endVisitNode(node);
- }
- public void endVisit(VariableDeclarationExpression node) {
- endVisitNode(node);
- }
- public void endVisit(VariableDeclarationFragment node) {
- endVisitNode(node);
- }
- public void endVisit(VariableDeclarationStatement node) {
- endVisitNode(node);
- }
- public void endVisit(WhileStatement node) {
- endVisitNode(node);
- }
-
- public void endVisit(WithStatement node) {
- endVisitNode(node);
- }
- protected void endVisitNode(ASTNode node) {
- // do nothing
- }
- public boolean visit(AnonymousClassDeclaration node) {
- return visitNode(node);
- }
- public boolean visit(ArrayAccess node) {
- return visitNode(node);
- }
- public boolean visit(ArrayCreation node) {
- return visitNode(node);
- }
- public boolean visit(ArrayInitializer node) {
- return visitNode(node);
- }
-
- public boolean visit(ArrayType node) {
- visitNode(node);
- return false;
- }
- public boolean visit(Assignment node) {
- return visitNode(node);
- }
- public boolean visit(Block node) {
- return visitNode(node);
- }
- /* since 3.0 */
- public boolean visit(BlockComment node) {
- return visitNode(node);
- }
- public boolean visit(BooleanLiteral node) {
- return visitNode(node);
- }
- public boolean visit(BreakStatement node) {
- return visitNode(node);
- }
- public boolean visit(CatchClause node) {
- return visitNode(node);
- }
- public boolean visit(CharacterLiteral node) {
- return visitNode(node);
- }
- public boolean visit(ClassInstanceCreation node) {
- return visitNode(node);
- }
- public boolean visit(JavaScriptUnit node) {
- return visitNode(node);
- }
-
- public boolean visit(ConditionalExpression node) {
- return visitNode(node);
- }
-
- public boolean visit(ConstructorInvocation node) {
- return visitNode(node);
- }
-
- public boolean visit(ContinueStatement node) {
- return visitNode(node);
- }
- public boolean visit(DoStatement node) {
- return visitNode(node);
- }
- public boolean visit(EmptyStatement node) {
- return visitNode(node);
- }
- public boolean visit(EnhancedForStatement node) {
- return visitNode(node);
- }
- public boolean visit(ExpressionStatement node) {
- return visitNode(node);
- }
- public boolean visit(FieldAccess node) {
- return visitNode(node);
- }
- public boolean visit(FieldDeclaration node) {
- return visitNode(node);
- }
- public boolean visit(ForInStatement node) {
- return visitNode(node);
- }
- public boolean visit(ForStatement node) {
- return visitNode(node);
- }
- public boolean visit(FunctionExpression node) {
- return visitNode(node);
- }
- public boolean visit(IfStatement node) {
- return visitNode(node);
- }
- public boolean visit(ImportDeclaration node) {
- return visitNode(node);
- }
- public boolean visit(InferredType node) {
- return visitNode(node);
- }
- public boolean visit(InfixExpression node) {
- return visitNode(node);
- }
- public boolean visit(Initializer node) {
- return visitNode(node);
- }
- public boolean visit(InstanceofExpression node) {
- return visitNode(node);
- }
- public boolean visit(JSdoc node) {
- // do not visit jsdoc tags by default. Use constructor with boolean to enable.
- if (super.visit(node)) {
- return visitNode(node);
- }
- return false;
- }
- public boolean visit(LabeledStatement node) {
- return visitNode(node);
- }
- public boolean visit(LineComment node) {
- return visitNode(node);
- }
- public boolean visit(ListExpression node) {
- return visitNode(node);
- }
- public boolean visit(MemberRef node) {
- return visitNode(node);
- }
- public boolean visit(FunctionDeclaration node) {
- return visitNode(node);
- }
- public boolean visit(FunctionInvocation node) {
- return visitNode(node);
- }
- public boolean visit(FunctionRef node) {
- return visitNode(node);
- }
- public boolean visit(FunctionRefParameter node) {
- return visitNode(node);
- }
- public boolean visit(NullLiteral node) {
- return visitNode(node);
- }
- public boolean visit(NumberLiteral node) {
- return visitNode(node);
- }
- public boolean visit(ObjectLiteral node) {
- return visitNode(node);
- }
- public boolean visit(ObjectLiteralField node) {
- return visitNode(node);
- }
- public boolean visit(PackageDeclaration node) {
- return visitNode(node);
- }
- public boolean visit(ParenthesizedExpression node) {
- return visitNode(node);
- }
- public boolean visit(PostfixExpression node) {
- return visitNode(node);
- }
- public boolean visit(PrefixExpression node) {
- return visitNode(node);
- }
- public boolean visit(PrimitiveType node) {
- return visitNode(node);
- }
- public boolean visit(QualifiedName node) {
- return visitNode(node);
- }
- public boolean visit(QualifiedType node) {
- return visitNode(node);
- }
- public boolean visit(RegularExpressionLiteral node) {
- return visitNode(node);
- }
- public boolean visit(ReturnStatement node) {
- return visitNode(node);
- }
- public boolean visit(SimpleName node) {
- return visitNode(node);
- }
- public boolean visit(SimpleType node) {
- return visitNode(node);
- }
- public boolean visit(SingleVariableDeclaration node) {
- return visitNode(node);
- }
- public boolean visit(StringLiteral node) {
- return visitNode(node);
- }
- public boolean visit(SuperConstructorInvocation node) {
- return visitNode(node);
- }
- public boolean visit(SuperFieldAccess node) {
- return visitNode(node);
- }
- public boolean visit(SuperMethodInvocation node) {
- return visitNode(node);
- }
- public boolean visit(SwitchCase node) {
- return visitNode(node);
- }
- public boolean visit(SwitchStatement node) {
- return visitNode(node);
- }
- public boolean visit(TagElement node) {
- return visitNode(node);
- }
- public boolean visit(TextElement node) {
- return visitNode(node);
- }
- public boolean visit(ThisExpression node) {
- return visitNode(node);
- }
- public boolean visit(ThrowStatement node) {
- return visitNode(node);
- }
- public boolean visit(TryStatement node) {
- return visitNode(node);
- }
- public boolean visit(TypeDeclaration node) {
- return visitNode(node);
- }
-
- public boolean visit(TypeDeclarationStatement node) {
- return visitNode(node);
- }
-
- public boolean visit(TypeLiteral node) {
- return visitNode(node);
- }
- public boolean visit(UndefinedLiteral node) {
- return visitNode(node);
- }
- public boolean visit(VariableDeclarationExpression node) {
- return visitNode(node);
- }
- public boolean visit(VariableDeclarationFragment node) {
- return visitNode(node);
- }
- public boolean visit(VariableDeclarationStatement node) {
- return visitNode(node);
- }
- public boolean visit(WhileStatement node) {
- return visitNode(node);
- }
-
- public boolean visit(WithStatement node) {
- return visitNode(node);
- }
-
- protected boolean visitNode(ASTNode node) {
- return true;
- }
-
-}
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
deleted file mode 100644
index f023af3f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/DefaultBindingResolver.java
+++ /dev/null
@@ -1,1595 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.dom;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-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.ArrayAllocationExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ExplicitConstructorCall;
-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.JavadocAllocationExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocFieldReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocImplicitTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocMessageSend;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocQualifiedTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocSingleNameReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocSingleTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Literal;
-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.QualifiedNameReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedTypeReference;
-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.ThisReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.impl.Constant;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ArrayBinding;
-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.CompilationUnitBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.CompilationUnitScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.FieldBinding;
-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.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.TypeIds;
-import org.eclipse.wst.jsdt.internal.compiler.problem.AbortCompilation;
-
-/**
- * Internal class for resolving bindings using old ASTs.
- * <p>
- * IMPORTANT: The methods on this class are synchronized. This is required
- * because there may be multiple clients in separate threads concurrently
- * reading an AST and asking for bindings for its nodes. These requests all
- * end up invoking instance methods on this class. There are various internal
- * tables and caches which are built and maintained in the course of looking
- * up bindings. To ensure that they remain coherent in the presence of multiple
- * threads, the methods are synchronized on the DefaultBindingResolver instance.
- * </p>
- *
- * 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.
-*/
-class DefaultBindingResolver extends BindingResolver {
-
- /*
- * Holds on binding tables that can be shared by several ASTs.
- */
- static class BindingTables {
-
- /**
- * This map is used to get a binding from its binding key.
- */
- Map bindingKeysToBindings;
- /**
- * This map is used to keep the correspondance between new bindings and the
- * validator bindings to their internal counterpart.
- * This is an identity map. We should only create one object for one binding.
- */
- Map compilerBindingsToASTBindings;
-
- BindingTables() {
- this.compilerBindingsToASTBindings = new HashMap();
- this.bindingKeysToBindings = new HashMap();
- }
-
- }
- /**
- * This map is used to retrieve the corresponding block scope for a ast node
- */
- Map astNodesToBlockScope;
-
- /**
- * This map is used to get an ast node from its binding (new binding) or DOM
- */
- Map bindingsToAstNodes;
-
- /*
- * The shared binding tables accros ASTs.
- */
- BindingTables bindingTables;
-
- /**
- * This map is used to retrieve an old ast node using the new ast node. This is not an
- * identity map.
- */
- Map newAstToOldAst;
-
- /**
- * JavaScript unit scope
- */
- private CompilationUnitScope scope;
-
- /**
- * The working copy owner that defines the context in which this resolver is creating the bindings.
- */
- WorkingCopyOwner workingCopyOwner;
- boolean isRecoveredBinding;
-
-
- /**
- * Constructor for DefaultBindingResolver.
- */
- DefaultBindingResolver(CompilationUnitScope scope, WorkingCopyOwner workingCopyOwner, BindingTables bindingTables, boolean isRecoveredBinding) {
- this.newAstToOldAst = new HashMap();
- this.astNodesToBlockScope = new HashMap();
- this.bindingsToAstNodes = new HashMap();
- this.bindingTables = bindingTables;
- this.scope = scope;
- this.workingCopyOwner = workingCopyOwner;
- this.isRecoveredBinding = isRecoveredBinding;
- }
-
- DefaultBindingResolver(LookupEnvironment lookupEnvironment, WorkingCopyOwner workingCopyOwner, BindingTables bindingTables, boolean isRecoveredBinding) {
- this.newAstToOldAst = new HashMap();
- this.astNodesToBlockScope = new HashMap();
- this.bindingsToAstNodes = new HashMap();
- this.bindingTables = bindingTables;
- this.scope = new CompilationUnitScope(new CompilationUnitDeclaration(null, null, -1), lookupEnvironment);
- this.workingCopyOwner = workingCopyOwner;
- this.isRecoveredBinding = isRecoveredBinding;
- }
-
- /*
- * Method declared on BindingResolver.
- */
- synchronized ASTNode findDeclaringNode(IBinding binding) {
- if (binding == null) {
- return null;
- }
- if (binding instanceof IFunctionBinding) {
- IFunctionBinding methodBinding = (IFunctionBinding) binding;
- return (ASTNode) this.bindingsToAstNodes.get(methodBinding.getMethodDeclaration());
- } else if (binding instanceof ITypeBinding) {
- ITypeBinding typeBinding = (ITypeBinding) binding;
- return (ASTNode) this.bindingsToAstNodes.get(typeBinding.getTypeDeclaration());
- } else if (binding instanceof IVariableBinding) {
- IVariableBinding variableBinding = (IVariableBinding) binding;
- return (ASTNode) this.bindingsToAstNodes.get(variableBinding.getVariableDeclaration());
- }
- return (ASTNode) this.bindingsToAstNodes.get(binding);
- }
-
- synchronized ASTNode findDeclaringNode(String bindingKey) {
- if (bindingKey == null) {
- return null;
- }
- Object binding = this.bindingTables.bindingKeysToBindings.get(bindingKey);
- if (binding == null)
- return null;
- return (ASTNode) this.bindingsToAstNodes.get(binding);
- }
-
- IBinding getBinding(org.eclipse.wst.jsdt.internal.compiler.lookup.Binding binding) {
- switch (binding.kind()) {
- case Binding.PACKAGE:
- return getPackageBinding((org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding) binding);
- case Binding.TYPE:
- case Binding.BASE_TYPE:
- return getTypeBinding((org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding) binding);
- case Binding.ARRAY_TYPE:
- return new TypeBinding(this, (org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding) binding);
- case Binding.METHOD:
- return getMethodBinding((org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding) binding);
- case Binding.FIELD:
- case Binding.LOCAL:
- return getVariableBinding((org.eclipse.wst.jsdt.internal.compiler.lookup.VariableBinding) binding);
- }
- return null;
- }
-
- synchronized org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode getCorrespondingNode(ASTNode currentNode) {
- return (org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode) this.newAstToOldAst.get(currentNode);
- }
-
- /*
- * Method declared on BindingResolver.
- */
- synchronized IFunctionBinding getMethodBinding(org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding methodBinding) {
- if (methodBinding != null && !methodBinding.isValidBinding()) {
- org.eclipse.wst.jsdt.internal.compiler.lookup.ProblemMethodBinding problemMethodBinding =
- (org.eclipse.wst.jsdt.internal.compiler.lookup.ProblemMethodBinding) methodBinding;
- methodBinding = problemMethodBinding.closestMatch;
- }
-
- if (methodBinding != null) {
- IFunctionBinding binding = (IFunctionBinding) this.bindingTables.compilerBindingsToASTBindings.get(methodBinding);
- if (binding != null) {
- return binding;
- }
- binding = new FunctionBinding(this, methodBinding);
- this.bindingTables.compilerBindingsToASTBindings.put(methodBinding, binding);
- return binding;
- }
- return null;
- }
-
- /*
- * Method declared on BindingResolver.
- */
- synchronized IPackageBinding getPackageBinding(org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding packageBinding) {
- if (packageBinding == null || !packageBinding.isValidBinding()) {
- return null;
- }
- IPackageBinding binding = (IPackageBinding) this.bindingTables.compilerBindingsToASTBindings.get(packageBinding);
- if (binding != null) {
- return binding;
- }
- binding = new PackageBinding(packageBinding, this);
- this.bindingTables.compilerBindingsToASTBindings.put(packageBinding, binding);
- return binding;
- }
-
- /**
- * Returns the new type binding corresponding to the given variable declaration.
- * This is used for recovered binding only.
- * <p>
- * The default implementation of this method returns <code>null</code>.
- * Subclasses may reimplement.
- * </p>
- *
- * @param variableDeclaration the given variable declaration
- * @return the new type binding
- */
- synchronized ITypeBinding getTypeBinding(VariableDeclaration variableDeclaration) {
- ITypeBinding binding = (ITypeBinding) this.bindingTables.compilerBindingsToASTBindings.get(variableDeclaration);
- if (binding != null) {
- return binding;
- }
- binding = new RecoveredTypeBinding(this, variableDeclaration);
- this.bindingTables.compilerBindingsToASTBindings.put(variableDeclaration, binding);
- return binding;
- }
-
- /**
- * Returns the new type binding corresponding to the given type.
- * This is used for recovered binding only.
- * <p>
- * The default implementation of this method returns <code>null</code>.
- * Subclasses may reimplement.
- * </p>
- *
- * @param type the given type
- * @return the new type binding
- */
- synchronized ITypeBinding getTypeBinding(Type type) {
- ITypeBinding binding = (ITypeBinding) this.bindingTables.compilerBindingsToASTBindings.get(type);
- if (binding != null) {
- return binding;
- }
- binding = new RecoveredTypeBinding(this, type);
- this.bindingTables.compilerBindingsToASTBindings.put(type, binding);
- return binding;
- }
-
-
- /*
- * Method declared on BindingResolver.
- */
- synchronized ITypeBinding getTypeBinding(org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding referenceBinding) {
- if (referenceBinding == null) {
- return null;
- } else if (!referenceBinding.isValidBinding()) {
- switch(referenceBinding.problemId()) {
- case ProblemReasons.NotVisible :
- case ProblemReasons.NonStaticReferenceInStaticContext :
- if (referenceBinding instanceof ProblemReferenceBinding) {
- ProblemReferenceBinding problemReferenceBinding = (ProblemReferenceBinding) referenceBinding;
- ReferenceBinding binding2 = problemReferenceBinding.closestMatch();
- ITypeBinding binding = (ITypeBinding) this.bindingTables.compilerBindingsToASTBindings.get(binding2);
- if (binding != null) {
- return binding;
- }
- binding = new TypeBinding(this, binding2);
- this.bindingTables.compilerBindingsToASTBindings.put(binding2, binding);
- return binding;
- }
- break;
- case ProblemReasons.NotFound :
- if (this.isRecoveredBinding) {
- ITypeBinding binding = (ITypeBinding) this.bindingTables.compilerBindingsToASTBindings.get(referenceBinding);
- if (binding != null) {
- return binding;
- }
- binding = new RecoveredTypeBinding(this, referenceBinding);
- this.bindingTables.compilerBindingsToASTBindings.put(referenceBinding, binding);
- return binding;
- }
- }
- return null;
- } else {
- ITypeBinding binding = (ITypeBinding) this.bindingTables.compilerBindingsToASTBindings.get(referenceBinding);
- if (binding != null) {
- return binding;
- }
- if (referenceBinding instanceof CompilationUnitBinding)
- binding = new org.eclipse.wst.jsdt.core.dom.JavaScriptUnitBinding(this, referenceBinding);
- else
- binding = new TypeBinding(this, referenceBinding);
- this.bindingTables.compilerBindingsToASTBindings.put(referenceBinding, binding);
- return binding;
- }
- }
-
- synchronized ITypeBinding getTypeBinding(RecoveredTypeBinding recoveredTypeBinding, int dimensions) {
- if (recoveredTypeBinding== null) {
- return null;
- }
- return new RecoveredTypeBinding(this, recoveredTypeBinding, dimensions);
- }
-
- synchronized IVariableBinding getVariableBinding(org.eclipse.wst.jsdt.internal.compiler.lookup.VariableBinding variableBinding, VariableDeclaration variableDeclaration) {
- if (this.isRecoveredBinding) {
- if (variableBinding != null) {
- if (variableBinding.isValidBinding()) {
- IVariableBinding binding = (IVariableBinding) this.bindingTables.compilerBindingsToASTBindings.get(variableBinding);
- if (binding != null) {
- return binding;
- }
- if (variableBinding.type != null) {
- binding = new VariableBinding(this, variableBinding);
- } else {
- binding = new RecoveredVariableBinding(this, variableDeclaration);
- }
- this.bindingTables.compilerBindingsToASTBindings.put(variableBinding, binding);
- return binding;
- } else {
- /*
- * http://dev.eclipse.org/bugs/show_bug.cgi?id=24449
- */
- if (variableBinding instanceof ProblemFieldBinding) {
- ProblemFieldBinding problemFieldBinding = (ProblemFieldBinding) variableBinding;
- switch(problemFieldBinding.problemId()) {
- case ProblemReasons.NotVisible :
- case ProblemReasons.NonStaticReferenceInStaticContext :
- case ProblemReasons.NonStaticReferenceInConstructorInvocation :
- ReferenceBinding declaringClass = problemFieldBinding.declaringClass;
- FieldBinding exactBinding = declaringClass.getField(problemFieldBinding.name, true /*resolve*/);
- if (exactBinding != null) {
- IVariableBinding variableBinding2 = (IVariableBinding) this.bindingTables.compilerBindingsToASTBindings.get(exactBinding);
- if (variableBinding2 != null) {
- return variableBinding2;
- }
- variableBinding2 = new VariableBinding(this, exactBinding);
- this.bindingTables.compilerBindingsToASTBindings.put(exactBinding, variableBinding2);
- return variableBinding2;
- }
- break;
- }
- }
- }
- }
- return null;
- }
- return this.getVariableBinding(variableBinding);
- }
-
- public WorkingCopyOwner getWorkingCopyOwner() {
- return this.workingCopyOwner;
- }
-
- /*
- * Method declared on BindingResolver.
- */
- synchronized IVariableBinding getVariableBinding(org.eclipse.wst.jsdt.internal.compiler.lookup.VariableBinding variableBinding) {
- if (variableBinding != null) {
- if (variableBinding.isValidBinding()) {
- if (variableBinding.type != null) {
- IVariableBinding binding = (IVariableBinding) this.bindingTables.compilerBindingsToASTBindings.get(variableBinding);
- if (binding != null) {
- return binding;
- }
- binding = new VariableBinding(this, variableBinding);
- this.bindingTables.compilerBindingsToASTBindings.put(variableBinding, binding);
- return binding;
- }
- } else {
- /*
- * http://dev.eclipse.org/bugs/show_bug.cgi?id=24449
- */
- if (variableBinding instanceof ProblemFieldBinding) {
- ProblemFieldBinding problemFieldBinding = (ProblemFieldBinding) variableBinding;
- switch(problemFieldBinding.problemId()) {
- case ProblemReasons.NotVisible :
- case ProblemReasons.NonStaticReferenceInStaticContext :
- case ProblemReasons.NonStaticReferenceInConstructorInvocation :
- ReferenceBinding declaringClass = problemFieldBinding.declaringClass;
- FieldBinding exactBinding = declaringClass.getField(problemFieldBinding.name, true /*resolve*/);
- if (exactBinding != null) {
- IVariableBinding variableBinding2 = (IVariableBinding) this.bindingTables.compilerBindingsToASTBindings.get(exactBinding);
- if (variableBinding2 != null) {
- return variableBinding2;
- }
- variableBinding2 = new VariableBinding(this, exactBinding);
- this.bindingTables.compilerBindingsToASTBindings.put(exactBinding, variableBinding2);
- return variableBinding2;
- }
- break;
- }
- }
- }
- }
- return null;
- }
-
- boolean isResolvedTypeInferredFromExpectedType(FunctionInvocation methodInvocation) {
- Object oldNode = this.newAstToOldAst.get(methodInvocation);
- if (oldNode instanceof MessageSend) {
-// MessageSend messageSend = (MessageSend) oldNode;
-// org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding methodBinding = messageSend.binding;
-// if (methodBinding instanceof ParameterizedGenericMethodBinding) {
-// ParameterizedGenericMethodBinding genericMethodBinding = (ParameterizedGenericMethodBinding) methodBinding;
-// return genericMethodBinding.inferredReturnType;
-// }
- }
- return false;
- }
-
- boolean isResolvedTypeInferredFromExpectedType(SuperMethodInvocation superMethodInvocation) {
- Object oldNode = this.newAstToOldAst.get(superMethodInvocation);
- if (oldNode instanceof MessageSend) {
-// MessageSend messageSend = (MessageSend) oldNode;
-// org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding methodBinding = messageSend.binding;
-// if (methodBinding instanceof ParameterizedGenericMethodBinding) {
-// ParameterizedGenericMethodBinding genericMethodBinding = (ParameterizedGenericMethodBinding) methodBinding;
-// return genericMethodBinding.inferredReturnType;
-// }
- }
- return false;
- }
-
-
- /*
- * Method declared on BindingResolver.
- */
- LookupEnvironment lookupEnvironment() {
- return this.scope.environment();
- }
-
- /**
- * @see org.eclipse.wst.jsdt.core.dom.BindingResolver#recordScope(ASTNode, BlockScope)
- */
- synchronized void recordScope(ASTNode astNode, BlockScope blockScope) {
- 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)
- */
- Object resolveConstantExpressionValue(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;
- Constant constant = compilerExpression.constant;
- if (constant != null && constant != Constant.NotAConstant) {
- switch (constant.typeID()) {
- case TypeIds.T_int : return new Integer(constant.intValue());
- case TypeIds.T_short : return new Short(constant.shortValue());
- case TypeIds.T_char : return new Character(constant.charValue());
- case TypeIds.T_float : return new Float(constant.floatValue());
- case TypeIds.T_double : return new Double(constant.doubleValue());
- case TypeIds.T_boolean : return constant.booleanValue() ? Boolean.TRUE : Boolean.FALSE;
- case TypeIds.T_long : return new Long(constant.longValue());
- case TypeIds.T_JavaLangString : return constant.stringValue();
- }
- return null;
- }
- }
- return null;
- }
-
- /*
- * @see BindingResolver#resolveConstructor(ClassInstanceCreation)
- */
- synchronized IFunctionBinding resolveConstructor(ClassInstanceCreation 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.bits & org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.IsAnonymousType) != 0) {
- org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration anonymousLocalTypeDeclaration = (org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration) node;
- return this.getMethodBinding(anonymousLocalTypeDeclaration.allocation.binding);
- } else if (node instanceof AllocationExpression) {
- return this.getMethodBinding(((AllocationExpression)node).binding);
- }
- return null;
- }
-
- /*
- * @see BindingResolver#resolveConstructor(ConstructorInvocation)
- */
- synchronized IFunctionBinding resolveConstructor(ConstructorInvocation expression) {
- org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode node = (org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode) this.newAstToOldAst.get(expression);
- if (node instanceof ExplicitConstructorCall) {
- ExplicitConstructorCall explicitConstructorCall = (ExplicitConstructorCall) node;
- return this.getMethodBinding(explicitConstructorCall.binding);
- }
- return null;
- }
-
- /*
- * @see BindingResolver#resolveConstructor(SuperConstructorInvocation)
- */
- synchronized IFunctionBinding resolveConstructor(SuperConstructorInvocation expression) {
- org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode node = (org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode) this.newAstToOldAst.get(expression);
- if (node instanceof ExplicitConstructorCall) {
- ExplicitConstructorCall explicitConstructorCall = (ExplicitConstructorCall) node;
- return this.getMethodBinding(explicitConstructorCall.binding);
- }
- return null;
- }
- /*
- * Method declared on BindingResolver.
- */
- synchronized ITypeBinding resolveExpressionType(Expression expression) {
- try {
- switch(expression.getNodeType()) {
- case ASTNode.CLASS_INSTANCE_CREATION :
- org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode astNode = (org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode) this.newAstToOldAst.get(expression);
- if (astNode instanceof org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration) {
- // anonymous type case
- org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration typeDeclaration = (org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration) astNode;
- ITypeBinding typeBinding = this.getTypeBinding(typeDeclaration.binding);
- if (typeBinding != null) {
- return typeBinding;
- }
- } else {
- // should be an AllocationExpression
- AllocationExpression allocationExpression = (AllocationExpression) astNode;
- return this.getTypeBinding(allocationExpression.resolvedType);
- }
- break;
- case ASTNode.SIMPLE_NAME :
- case ASTNode.QUALIFIED_NAME :
- return this.resolveTypeBindingForName((Name) expression);
- case ASTNode.ARRAY_INITIALIZER :
- case ASTNode.ARRAY_CREATION :
- case ASTNode.ASSIGNMENT :
- case ASTNode.POSTFIX_EXPRESSION :
- case ASTNode.PREFIX_EXPRESSION :
- case ASTNode.TYPE_LITERAL :
- case ASTNode.INFIX_EXPRESSION :
- case ASTNode.INSTANCEOF_EXPRESSION :
- case ASTNode.FIELD_ACCESS :
- case ASTNode.SUPER_FIELD_ACCESS :
- case ASTNode.ARRAY_ACCESS :
- case ASTNode.FUNCTION_INVOCATION :
- case ASTNode.SUPER_METHOD_INVOCATION :
- case ASTNode.CONDITIONAL_EXPRESSION :
- case ASTNode.STRING_LITERAL :
- if (this.scope != null) {
- return this.getTypeBinding(this.scope.getJavaLangString());
- }
- break;
- case ASTNode.BOOLEAN_LITERAL :
- case ASTNode.NULL_LITERAL :
- case ASTNode.UNDEFINED_LITERAL :
- case ASTNode.CHARACTER_LITERAL :
- case ASTNode.REGULAR_EXPRESSION_LITERAL :
- case ASTNode.NUMBER_LITERAL :
- Literal literal = (Literal) this.newAstToOldAst.get(expression);
- return this.getTypeBinding(literal.literalType(this.scope));
- case ASTNode.THIS_EXPRESSION :
- ThisReference thisReference = (ThisReference) this.newAstToOldAst.get(expression);
- BlockScope blockScope = (BlockScope) this.astNodesToBlockScope.get(expression);
- if (blockScope != null) {
- return this.getTypeBinding(thisReference.resolveType(blockScope));
- }
- break;
- case ASTNode.PARENTHESIZED_EXPRESSION :
- ParenthesizedExpression parenthesizedExpression = (ParenthesizedExpression) expression;
- return this.resolveExpressionType(parenthesizedExpression.getExpression());
- case ASTNode.VARIABLE_DECLARATION_EXPRESSION :
- VariableDeclarationExpression variableDeclarationExpression = (VariableDeclarationExpression) expression;
- Type type = variableDeclarationExpression.getType();
- if (type != null) {
- return type.resolveBinding();
- }
- break;
- }
- } catch (AbortCompilation e) {
- // handle missing types
- }
- return null;
- }
-
- /*
- * @see BindingResolver#resolveField(FieldAccess)
- */
- synchronized IVariableBinding resolveField(FieldAccess fieldAccess) {
- Object oldNode = this.newAstToOldAst.get(fieldAccess);
- if (oldNode instanceof FieldReference) {
- FieldReference fieldReference = (FieldReference) oldNode;
- return this.getVariableBinding(fieldReference.binding);
- }
- return null;
- }
-
- /*
- * @see BindingResolver#resolveField(SuperFieldAccess)
- */
- synchronized IVariableBinding resolveField(SuperFieldAccess fieldAccess) {
- Object oldNode = this.newAstToOldAst.get(fieldAccess);
- if (oldNode instanceof FieldReference) {
- FieldReference fieldReference = (FieldReference) oldNode;
- return this.getVariableBinding(fieldReference.binding);
- }
- return null;
- }
-
- /*
- * @see BindingResolver#resolveImport(ImportDeclaration)
- */
- synchronized IBinding resolveImport(ImportDeclaration importDeclaration) {
- if (this.scope == null) return null;
- try {
- org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode node = (org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode) this.newAstToOldAst.get(importDeclaration);
- if (node instanceof ImportReference) {
- ImportReference importReference = (ImportReference) node;
- if ((importReference.bits & org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.OnDemand) != 0) {
- Binding binding = this.scope.getImport(CharOperation.subarray(importReference.tokens, 0, importReference.tokens.length), true);
- if (binding != null) {
- if ((binding.kind() & Binding.PACKAGE) != 0) {
- IPackageBinding packageBinding = this.getPackageBinding((org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding) binding);
- if (packageBinding == null) {
- return null;
- }
- return packageBinding;
- } else {
- // if it is not a package, it has to be a type
- ITypeBinding typeBinding = this.getTypeBinding((org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding) binding);
- if (typeBinding == null) {
- return null;
- }
- return typeBinding;
- }
- }
- } else {
- Binding binding = this.scope.getImport(importReference.tokens, false);
- if (binding != null) {
- if (binding instanceof org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding) {
- ITypeBinding typeBinding = this.getTypeBinding((org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding) binding);
- return typeBinding == null ? null : typeBinding;
- }
- }
- }
- }
- } catch(AbortCompilation e) {
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=53357
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299
- }
- return null;
- }
-
- /*
- * Method declared on BindingResolver.
- */
- synchronized IFunctionBinding resolveMethod(FunctionDeclaration method) {
- Object oldNode = this.newAstToOldAst.get(method);
- if (oldNode instanceof AbstractMethodDeclaration) {
- AbstractMethodDeclaration methodDeclaration = (AbstractMethodDeclaration) oldNode;
- IFunctionBinding methodBinding = this.getMethodBinding(methodDeclaration.binding);
- if (methodBinding == null) {
- return null;
- }
- this.bindingsToAstNodes.put(methodBinding, method);
- String key = methodBinding.getKey();
- if (key != null) {
- this.bindingTables.bindingKeysToBindings.put(key, methodBinding);
- }
- return methodBinding;
- }
- return null;
- }
- /*
- * Method declared on BindingResolver.
- */
- synchronized IFunctionBinding resolveMethod(FunctionInvocation method) {
- Object oldNode = this.newAstToOldAst.get(method);
- if (oldNode instanceof MessageSend) {
- MessageSend messageSend = (MessageSend) oldNode;
- return this.getMethodBinding(messageSend.binding);
- }
- return null;
- }
- /*
- * Method declared on BindingResolver.
- */
- synchronized IFunctionBinding resolveMethod(SuperMethodInvocation method) {
- Object oldNode = this.newAstToOldAst.get(method);
- if (oldNode instanceof MessageSend) {
- MessageSend messageSend = (MessageSend) oldNode;
- return this.getMethodBinding(messageSend.binding);
- }
- return null;
- }
-
- synchronized ITypeBinding resolveTypeBindingForName(Name name) {
- org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode node = (org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode) this.newAstToOldAst.get(name);
- int index = name.index;
- if (node instanceof QualifiedNameReference) {
- QualifiedNameReference qualifiedNameReference = (QualifiedNameReference) node;
- final char[][] tokens = qualifiedNameReference.tokens;
- if (tokens.length == index) {
- return this.getTypeBinding(qualifiedNameReference.resolvedType);
- }
- int indexOfFirstFieldBinding = qualifiedNameReference.indexOfFirstFieldBinding; // one-based
- if (index < indexOfFirstFieldBinding) {
- // an extra lookup is required
- BlockScope internalScope = (BlockScope) this.astNodesToBlockScope.get(name);
- Binding binding = null;
- try {
- if (internalScope == null) {
- if (this.scope == null) return null;
- binding = this.scope.getTypeOrPackage(CharOperation.subarray(tokens, 0, index));
- } else {
- binding = internalScope.getTypeOrPackage(CharOperation.subarray(tokens, 0, index));
- }
- } catch (AbortCompilation e) {
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=53357
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299
- }
- if (binding instanceof org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding) {
- return null;
- } else if (binding instanceof org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding) {
- // it is a type
- return this.getTypeBinding((org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding)binding);
- }
- } else if (index == indexOfFirstFieldBinding) {
- if (qualifiedNameReference.isTypeReference()) {
- return this.getTypeBinding(qualifiedNameReference.resolvedType);
- } else {
- // in this case we want to get the next field declaring's class
- if (qualifiedNameReference.otherBindings == null) {
- return null;
- }
- FieldBinding fieldBinding = qualifiedNameReference.otherBindings[0];
- if (fieldBinding == null) return null;
- org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding type = fieldBinding.declaringClass;
- if (type == null) { // array length scenario
- // use type from first binding (no capture needed for array type)
- switch (qualifiedNameReference.bits & org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.RestrictiveFlagMASK) {
- case Binding.FIELD:
- type = ((FieldBinding) qualifiedNameReference.binding).type;
- break;
- case Binding.LOCAL:
- type = ((LocalVariableBinding) qualifiedNameReference.binding).type;
- break;
- }
- }
- return this.getTypeBinding(type);
- }
- } else {
- /* This is the case for a name which is part of a qualified name that
- * cannot be resolved. See PR 13063.
- */
- if (qualifiedNameReference.otherBindings == null) return null;
- final int otherBindingsLength = qualifiedNameReference.otherBindings.length;
- if (otherBindingsLength == (index - indexOfFirstFieldBinding)) {
- return this.getTypeBinding(qualifiedNameReference.resolvedType);
- }
- FieldBinding fieldBinding = qualifiedNameReference.otherBindings[index - indexOfFirstFieldBinding];
- if (fieldBinding == null) return null;
- org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding type = fieldBinding.declaringClass;
- if (type == null) { // array length scenario
- // use type from previous binding (no capture needed for array type)
- fieldBinding = qualifiedNameReference.otherBindings[index - indexOfFirstFieldBinding - 1];
- if (fieldBinding == null) return null;
- type = fieldBinding.type;
- }
- return this.getTypeBinding(type);
- }
- } else if (node instanceof QualifiedTypeReference) {
- QualifiedTypeReference qualifiedTypeReference = (QualifiedTypeReference) node;
- if (qualifiedTypeReference.resolvedType == null) {
- return null;
- }
- if (index == qualifiedTypeReference.tokens.length) {
- if (!qualifiedTypeReference.resolvedType.isValidBinding() && qualifiedTypeReference instanceof JavadocQualifiedTypeReference) {
- JavadocQualifiedTypeReference typeRef = (JavadocQualifiedTypeReference) node;
- if (typeRef.packageBinding != null) {
- return null;
- }
- }
- return this.getTypeBinding(qualifiedTypeReference.resolvedType.leafComponentType());
- } else {
- if (index >= 0) {
- BlockScope internalScope = (BlockScope) this.astNodesToBlockScope.get(name);
- Binding binding = null;
- try {
- if (internalScope == null) {
- if (this.scope == null) return null;
- binding = this.scope.getTypeOrPackage(CharOperation.subarray(qualifiedTypeReference.tokens, 0, index));
- } else {
- binding = internalScope.getTypeOrPackage(CharOperation.subarray(qualifiedTypeReference.tokens, 0, index));
- }
- } catch (AbortCompilation e) {
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=53357
- }
- if (binding instanceof org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding) {
- return null;
- } else if (binding instanceof org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding) {
- // it is a type
- return this.getTypeBinding((org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding)binding);
- } else {
- return null;
- }
- }
- }
- } else if (node instanceof ImportReference) {
- ImportReference importReference = (ImportReference) node;
- int importReferenceLength = importReference.tokens.length;
- if (index >= 0) {
- Binding binding = null;
- if (this.scope == null) return null;
- if (importReferenceLength == index) {
- try {
- binding = this.scope.getImport(CharOperation.subarray(importReference.tokens, 0, index), (importReference.bits & org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.OnDemand) != 0);
- } catch (AbortCompilation e) {
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=53357
- }
- } else {
- try {
- binding = this.scope.getImport(CharOperation.subarray(importReference.tokens, 0, index), true);
- } catch (AbortCompilation e) {
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=53357
- }
- }
- if (binding != null) {
- if (binding instanceof org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding) {
- // it is a type
- return this.getTypeBinding((org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding)binding);
- }
- return null;
- }
- }
- } else if (node instanceof AbstractMethodDeclaration) {
- AbstractMethodDeclaration methodDeclaration = (AbstractMethodDeclaration) node;
- IFunctionBinding method = this.getMethodBinding(methodDeclaration.binding);
- if (method == null) return null;
- return method.getReturnType();
- } else if (node instanceof org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration) {
- org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration typeDeclaration = (org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration) node;
- ITypeBinding typeBinding = this.getTypeBinding(typeDeclaration.binding);
- if (typeBinding != null) {
- return typeBinding;
- }
- } if (node instanceof JavadocSingleNameReference) {
- JavadocSingleNameReference singleNameReference = (JavadocSingleNameReference) node;
- LocalVariableBinding localVariable = (LocalVariableBinding)singleNameReference.binding;
- if (localVariable != null) {
- return this.getTypeBinding(localVariable.type);
- }
- } if (node instanceof SingleNameReference) {
- SingleNameReference singleNameReference = (SingleNameReference) node;
- return this.getTypeBinding(singleNameReference.resolvedType);
- } else if (node instanceof LocalDeclaration) {
- IVariableBinding variable = this.getVariableBinding(((LocalDeclaration)node).binding);
- if (variable == null) return null;
- return variable.getType();
- } else if (node instanceof JavadocFieldReference) {
- JavadocFieldReference fieldRef = (JavadocFieldReference) node;
- if (fieldRef.methodBinding != null) {
- return getMethodBinding(fieldRef.methodBinding).getReturnType();
- }
- return getTypeBinding(fieldRef.resolvedType);
- } else if (node instanceof FieldReference) {
- return getTypeBinding(((FieldReference) node).resolvedType);
- } else if (node instanceof SingleTypeReference) {
- SingleTypeReference singleTypeReference = (SingleTypeReference) node;
- org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding binding = singleTypeReference.resolvedType;
- if (binding != null) {
- return this.getTypeBinding(binding.leafComponentType());
- }
- } else if (node instanceof org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration) {
- org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration fieldDeclaration = (org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration) node;
- IVariableBinding field = this.getVariableBinding(fieldDeclaration.binding);
- if (field == null) return null;
- return field.getType();
- } else if (node instanceof MessageSend) {
- MessageSend messageSend = (MessageSend) node;
- IFunctionBinding method = getMethodBinding(messageSend.binding);
- if (method == null) return null;
- return method.getReturnType();
- } else if (node instanceof AllocationExpression) {
- AllocationExpression allocation = (AllocationExpression) node;
- return getTypeBinding(allocation.resolvedType);
- } else if (node instanceof JavadocImplicitTypeReference) {
- JavadocImplicitTypeReference implicitRef = (JavadocImplicitTypeReference) node;
- return getTypeBinding(implicitRef.resolvedType);
- }
- return null;
- }
-
- /*
- * Method declared on BindingResolver.
- */
- synchronized IBinding resolveName(Name name) {
- org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode node = (org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode) this.newAstToOldAst.get(name);
- int index = name.index;
- if (node instanceof QualifiedNameReference) {
- QualifiedNameReference qualifiedNameReference = (QualifiedNameReference) node;
- final char[][] tokens = qualifiedNameReference.tokens;
- int indexOfFirstFieldBinding = qualifiedNameReference.indexOfFirstFieldBinding; // one-based
- if (index < indexOfFirstFieldBinding) {
- // an extra lookup is required
- BlockScope internalScope = (BlockScope) this.astNodesToBlockScope.get(name);
- Binding binding = null;
- try {
- if (internalScope == null) {
- if (this.scope == null) return null;
- binding = this.scope.getTypeOrPackage(CharOperation.subarray(tokens, 0, index));
- } else {
- binding = internalScope.getTypeOrPackage(CharOperation.subarray(tokens, 0, index));
- }
- } catch (AbortCompilation e) {
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=53357
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299
- }
- if (binding instanceof org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding) {
- return this.getPackageBinding((org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding)binding);
- } else if (binding instanceof org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding) {
- // it is a type
- return this.getTypeBinding((org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding)binding);
- }
- } else if (index == indexOfFirstFieldBinding) {
- if (qualifiedNameReference.isTypeReference()) {
- return this.getTypeBinding(qualifiedNameReference.resolvedType);
- } else {
- Binding binding = qualifiedNameReference.binding;
- if (binding != null) {
- if (binding.isValidBinding()) {
- return this.getVariableBinding((org.eclipse.wst.jsdt.internal.compiler.lookup.VariableBinding) binding);
- } else if (binding instanceof ProblemFieldBinding) {
- ProblemFieldBinding problemFieldBinding = (ProblemFieldBinding) binding;
- switch(problemFieldBinding.problemId()) {
- case ProblemReasons.NotVisible :
- case ProblemReasons.NonStaticReferenceInStaticContext :
- ReferenceBinding declaringClass = problemFieldBinding.declaringClass;
- if (declaringClass != null) {
- FieldBinding exactBinding = declaringClass.getField(tokens[tokens.length - 1], true /*resolve*/);
- if (exactBinding != null) {
- if (exactBinding.type != null) {
- IVariableBinding variableBinding = (IVariableBinding) this.bindingTables.compilerBindingsToASTBindings.get(exactBinding);
- if (variableBinding != null) {
- return variableBinding;
- }
- variableBinding = new VariableBinding(this, exactBinding);
- this.bindingTables.compilerBindingsToASTBindings.put(exactBinding, variableBinding);
- return variableBinding;
- }
- }
- }
- break;
- }
- }
- }
- }
- } else {
- /* This is the case for a name which is part of a qualified name that
- * cannot be resolved. See PR 13063.
- */
- if (qualifiedNameReference.otherBindings == null || (index - indexOfFirstFieldBinding - 1) < 0) {
- return null;
- } else {
- return this.getVariableBinding(qualifiedNameReference.otherBindings[index - indexOfFirstFieldBinding - 1]);
- }
- }
- } else if (node instanceof QualifiedTypeReference) {
- QualifiedTypeReference qualifiedTypeReference = (QualifiedTypeReference) node;
- if (qualifiedTypeReference.resolvedType == null) {
- return null;
- }
- if (index == qualifiedTypeReference.tokens.length) {
- if (!qualifiedTypeReference.resolvedType.isValidBinding() && qualifiedTypeReference instanceof JavadocQualifiedTypeReference) {
- JavadocQualifiedTypeReference typeRef = (JavadocQualifiedTypeReference) node;
- if (typeRef.packageBinding != null) {
- return getPackageBinding(typeRef.packageBinding);
- }
- }
- return this.getTypeBinding(qualifiedTypeReference.resolvedType.leafComponentType());
- } else {
- if (index >= 0) {
- BlockScope internalScope = (BlockScope) this.astNodesToBlockScope.get(name);
- Binding binding = null;
- try {
- if (internalScope == null) {
- if (this.scope == null) return null;
- binding = this.scope.getTypeOrPackage(CharOperation.subarray(qualifiedTypeReference.tokens, 0, index));
- } else {
- binding = internalScope.getTypeOrPackage(CharOperation.subarray(qualifiedTypeReference.tokens, 0, index));
- }
- } catch (AbortCompilation e) {
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=53357
- }
- if (binding instanceof org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding) {
- return this.getPackageBinding((org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding)binding);
- } else if (binding instanceof org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding) {
- // it is a type
- return this.getTypeBinding((org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding)binding);
- } else {
- return null;
- }
- }
- }
- } else if (node instanceof ImportReference) {
- ImportReference importReference = (ImportReference) node;
- int importReferenceLength = importReference.tokens.length;
- if (index >= 0) {
- Binding binding = null;
- if (this.scope == null) return null;
- if (importReferenceLength == index) {
- try {
- binding = this.scope.getImport(CharOperation.subarray(importReference.tokens, 0, index), (importReference.bits & org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.OnDemand) != 0);
- } catch (AbortCompilation e) {
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=53357
- }
- } else {
- try {
- binding = this.scope.getImport(CharOperation.subarray(importReference.tokens, 0, index), true);
- } catch (AbortCompilation e) {
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=53357
- }
- }
- if (binding != null) {
- if (binding instanceof org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding) {
- return this.getPackageBinding((org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding)binding);
- } else if (binding instanceof org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding) {
- // it is a type
- return this.getTypeBinding((org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding)binding);
- } else if (binding instanceof org.eclipse.wst.jsdt.internal.compiler.lookup.FieldBinding) {
- // it is a type
- return this.getVariableBinding((org.eclipse.wst.jsdt.internal.compiler.lookup.FieldBinding)binding);
- } else if (binding instanceof org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding) {
- // it is a type
- return this.getMethodBinding((org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding)binding);
- } else {
- return null;
- }
- }
- }
- } else if (node instanceof CompilationUnitDeclaration) {
- CompilationUnitDeclaration compilationUnitDeclaration = (CompilationUnitDeclaration) node;
- org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration[] types = compilationUnitDeclaration.types;
- if (types == null || types.length == 0) {
- return null;
- }
- org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration type = types[0];
- if (type != null) {
- ITypeBinding typeBinding = this.getTypeBinding(type.binding);
- if (typeBinding != null) {
- return typeBinding.getPackage();
- }
- }
- } else if (node instanceof AbstractMethodDeclaration) {
- AbstractMethodDeclaration methodDeclaration = (AbstractMethodDeclaration) node;
- IFunctionBinding methodBinding = this.getMethodBinding(methodDeclaration.binding);
- if (methodBinding != null) {
- return methodBinding;
- }
- } else if (node instanceof org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration) {
- org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration typeDeclaration = (org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration) node;
- ITypeBinding typeBinding = this.getTypeBinding(typeDeclaration.binding);
- if (typeBinding != null) {
- return typeBinding;
- }
- } if (node instanceof SingleNameReference) {
- SingleNameReference singleNameReference = (SingleNameReference) node;
- if (singleNameReference.isTypeReference()) {
- return this.getTypeBinding(singleNameReference.resolvedType);
- } else {
- // this is a variable or a field
- Binding binding = singleNameReference.binding;
- if (binding != null) {
- if (binding.isValidBinding()) {
- if (binding instanceof org.eclipse.wst.jsdt.internal.compiler.lookup.VariableBinding)
- return this.getVariableBinding((org.eclipse.wst.jsdt.internal.compiler.lookup.VariableBinding) binding);
- if (binding instanceof org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding)
- return this.getMethodBinding((org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding) binding);
- } else {
- /*
- * http://dev.eclipse.org/bugs/show_bug.cgi?id=24449
- */
- if (binding instanceof ProblemFieldBinding) {
- ProblemFieldBinding problemFieldBinding = (ProblemFieldBinding) binding;
- switch(problemFieldBinding.problemId()) {
- case ProblemReasons.NotVisible :
- case ProblemReasons.NonStaticReferenceInStaticContext :
- case ProblemReasons.NonStaticReferenceInConstructorInvocation :
- ReferenceBinding declaringClass = problemFieldBinding.declaringClass;
- FieldBinding exactBinding = declaringClass.getField(problemFieldBinding.name, true /*resolve*/);
- if (exactBinding != null) {
- if (exactBinding.type != null) {
- IVariableBinding variableBinding2 = (IVariableBinding) this.bindingTables.compilerBindingsToASTBindings.get(exactBinding);
- if (variableBinding2 != null) {
- return variableBinding2;
- }
- variableBinding2 = new VariableBinding(this, exactBinding);
- this.bindingTables.compilerBindingsToASTBindings.put(exactBinding, variableBinding2);
- return variableBinding2;
- }
- }
- break;
- }
- }
- }
- }
- }
- } else if (node instanceof LocalDeclaration) {
- return this.getVariableBinding(((LocalDeclaration)node).binding);
- } else if (node instanceof JavadocFieldReference) {
- JavadocFieldReference fieldRef = (JavadocFieldReference) node;
- if (fieldRef.methodBinding != null) {
- return getMethodBinding(fieldRef.methodBinding);
- }
- return getVariableBinding(fieldRef.binding);
- } else if (node instanceof FieldReference) {
- return getVariableBinding(((FieldReference) node).binding);
- } else if (node instanceof SingleTypeReference) {
- SingleTypeReference singleTypeReference = (SingleTypeReference) node;
- org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding binding = singleTypeReference.resolvedType;
- if (binding != null) {
- if (!binding.isValidBinding() && node instanceof JavadocSingleTypeReference) {
- JavadocSingleTypeReference typeRef = (JavadocSingleTypeReference) node;
- if (typeRef.packageBinding != null) {
- return getPackageBinding(typeRef.packageBinding);
- }
- }
- return this.getTypeBinding(binding.leafComponentType());
- }
- } else if (node instanceof org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration) {
- org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration fieldDeclaration = (org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration) node;
- return this.getVariableBinding(fieldDeclaration.binding);
- } else if (node instanceof MessageSend) {
- MessageSend messageSend = (MessageSend) node;
- return getMethodBinding(messageSend.binding);
- } else if (node instanceof AllocationExpression) {
- AllocationExpression allocation = (AllocationExpression) node;
- return getMethodBinding(allocation.binding);
- } else if (node instanceof JavadocImplicitTypeReference) {
- JavadocImplicitTypeReference implicitRef = (JavadocImplicitTypeReference) node;
- return getTypeBinding(implicitRef.resolvedType);
- }
- return null;
- }
-
- /*
- * @see BindingResolver#resolvePackage(PackageDeclaration)
- */
- synchronized IPackageBinding resolvePackage(PackageDeclaration pkg) {
- if (this.scope == null) return null;
- try {
- org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode node = (org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode) this.newAstToOldAst.get(pkg);
- if (node instanceof ImportReference) {
- ImportReference importReference = (ImportReference) node;
- Binding binding = this.scope.getTypeOrPackage(CharOperation.subarray(importReference.tokens, 0, importReference.tokens.length));
- if ((binding != null) && (binding.isValidBinding())) {
- IPackageBinding packageBinding = this.getPackageBinding((org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding) binding);
- if (packageBinding == null) {
- return null;
- }
- this.bindingsToAstNodes.put(packageBinding, pkg);
- String key = packageBinding.getKey();
- if (key != null) {
- this.bindingTables.bindingKeysToBindings.put(key, packageBinding);
- }
- return packageBinding;
- }
- }
- } catch (AbortCompilation e) {
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=53357
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299
- }
- return null;
- }
-
- /* (non-Javadoc)
- * @see BindingResolver#resolveReference(MemberRef)
- *
- */
- synchronized IBinding resolveReference(MemberRef ref) {
- org.eclipse.wst.jsdt.internal.compiler.ast.Expression expression = (org.eclipse.wst.jsdt.internal.compiler.ast.Expression) this.newAstToOldAst.get(ref);
- if (expression instanceof TypeReference) {
- return getTypeBinding(expression.resolvedType);
- }
- else if (expression instanceof JavadocFieldReference) {
- JavadocFieldReference fieldRef = (JavadocFieldReference) expression;
- if (fieldRef.methodBinding != null) {
- return getMethodBinding(fieldRef.methodBinding);
- }
- return getVariableBinding(fieldRef.binding);
- }
- return null;
- }
-
- /* (non-Javadoc)
- * @see BindingResolver#resolveReference(FunctionRef)
- *
- */
- synchronized IBinding resolveReference(FunctionRef ref) {
- org.eclipse.wst.jsdt.internal.compiler.ast.Expression expression = (org.eclipse.wst.jsdt.internal.compiler.ast.Expression) this.newAstToOldAst.get(ref);
- if (expression instanceof JavadocMessageSend) {
- return this.getMethodBinding(((JavadocMessageSend)expression).binding);
- }
- else if (expression instanceof JavadocAllocationExpression) {
- return this.getMethodBinding(((JavadocAllocationExpression)expression).binding);
- }
- return null;
- }
-
- /*
- * @see BindingResolver#resolveType(AnonymousClassDeclaration)
- */
- synchronized ITypeBinding resolveType(AnonymousClassDeclaration type) {
- org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode node = (org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode) this.newAstToOldAst.get(type);
- if (node != null && (node.bits & org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode.IsAnonymousType) != 0) {
- org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration anonymousLocalTypeDeclaration = (org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration) node;
- ITypeBinding typeBinding = this.getTypeBinding(anonymousLocalTypeDeclaration.binding);
- if (typeBinding == null) {
- return null;
- }
- this.bindingsToAstNodes.put(typeBinding, type);
- String key = typeBinding.getKey();
- if (key != null) {
- this.bindingTables.bindingKeysToBindings.put(key, typeBinding);
- }
- return typeBinding;
- }
- return null;
- }
-
- /*
- * Method declared on BindingResolver.
- */
- synchronized ITypeBinding resolveType(Type type) {
- // retrieve the old ast node
- org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode node = (org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode) this.newAstToOldAst.get(type);
- org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding binding = null;
- if (node != null) {
- if (node instanceof TypeReference) {
- TypeReference typeReference = (TypeReference) node;
- binding = typeReference.resolvedType;
- } else if (node instanceof SingleNameReference && ((SingleNameReference)node).isTypeReference()) {
- binding = (((SingleNameReference)node).resolvedType);
- } else if (node instanceof QualifiedNameReference && ((QualifiedNameReference)node).isTypeReference()) {
- binding = (((QualifiedNameReference)node).resolvedType);
- } else if (node instanceof ArrayAllocationExpression) {
- binding = ((ArrayAllocationExpression) node).resolvedType;
- }
- if (binding != null) {
- if (type.isArrayType()) {
- ArrayType arrayType = (ArrayType) type;
- if (this.scope == null) return null;
- if (binding.isArrayType()) {
- ArrayBinding arrayBinding = (ArrayBinding) binding;
- return getTypeBinding(this.scope.createArrayType(arrayBinding.leafComponentType, arrayType.getDimensions()));
- } else {
- return getTypeBinding(this.scope.createArrayType(binding, arrayType.getDimensions()));
- }
- } else {
- if (binding.isArrayType()) {
- ArrayBinding arrayBinding = (ArrayBinding) binding;
- return getTypeBinding(arrayBinding.leafComponentType);
- } else {
- return getTypeBinding(binding);
- }
- }
- }
- } else if (type.isPrimitiveType()) {
- /* Handle the void primitive type returned by getReturnType for a method declaration
- * that is a constructor declaration. It prevents null from being returned
- */
- if (((PrimitiveType) type).getPrimitiveTypeCode() == PrimitiveType.VOID) {
- return this.getTypeBinding(org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding.VOID);
- }
- }
- return null;
- }
-
- /*
- * Method declared on BindingResolver.
- */
- synchronized ITypeBinding resolveType(TypeDeclaration type) {
- final Object node = this.newAstToOldAst.get(type);
- if (node instanceof org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration) {
- org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration typeDeclaration = (org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration) node;
- ITypeBinding typeBinding = this.getTypeBinding(typeDeclaration.binding);
- if (typeBinding == null) {
- return null;
- }
- this.bindingsToAstNodes.put(typeBinding, type);
- String key = typeBinding.getKey();
- if (key != null) {
- this.bindingTables.bindingKeysToBindings.put(key, typeBinding);
- }
- return typeBinding;
- }
- return null;
- }
-
- ITypeBinding resolveType(JavaScriptUnit compilationUnit) {
- final Object node = this.newAstToOldAst.get(compilationUnit);
- if (node instanceof org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration) {
- org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration compilationUnitDeclaration =
- (org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration) node;
- ITypeBinding typeBinding = this.getTypeBinding(compilationUnitDeclaration.compilationUnitBinding);
- if (typeBinding == null) {
- return null;
- }
- this.bindingsToAstNodes.put(typeBinding, compilationUnit);
- String key = typeBinding.getKey();
- if (key != null) {
- this.bindingTables.bindingKeysToBindings.put(key, typeBinding);
- }
- return typeBinding;
- }
- return null;
- }
-
- /*
- * Method declared on BindingResolver.
- */
- synchronized IVariableBinding resolveVariable(VariableDeclaration variable) {
- final Object node = this.newAstToOldAst.get(variable);
- if (node instanceof AbstractVariableDeclaration) {
- AbstractVariableDeclaration abstractVariableDeclaration = (AbstractVariableDeclaration) node;
- if (abstractVariableDeclaration instanceof org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration) {
- org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration fieldDeclaration = (org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration) abstractVariableDeclaration;
- IVariableBinding variableBinding = this.getVariableBinding(fieldDeclaration.binding, variable);
- if (variableBinding == null) {
- return null;
- }
- this.bindingsToAstNodes.put(variableBinding, variable);
- String key = variableBinding.getKey();
- if (key != null) {
- this.bindingTables.bindingKeysToBindings.put(key, variableBinding);
- }
- return variableBinding;
- }
- IVariableBinding variableBinding = this.getVariableBinding(((LocalDeclaration) abstractVariableDeclaration).binding, variable);
- if (variableBinding == null) {
- return null;
- }
- this.bindingsToAstNodes.put(variableBinding, variable);
- String key = variableBinding.getKey();
- if (key != null) {
- this.bindingTables.bindingKeysToBindings.put(key, variableBinding);
- }
- return variableBinding;
- }
- return null;
- }
-
- synchronized IVariableBinding resolveVariable(VariableDeclarationStatement variable) {
- final Object node = this.newAstToOldAst.get(variable);
- if (node instanceof AbstractVariableDeclaration) {
- AbstractVariableDeclaration abstractVariableDeclaration = (AbstractVariableDeclaration) node;
- if (abstractVariableDeclaration instanceof org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration) {
- org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration fieldDeclaration = (org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration) abstractVariableDeclaration;
- IVariableBinding variableBinding = this.getVariableBinding(fieldDeclaration.binding);
- if (variableBinding == null) {
- return null;
- }
- this.bindingsToAstNodes.put(variableBinding, variable);
- String key = variableBinding.getKey();
- if (key != null) {
- this.bindingTables.bindingKeysToBindings.put(key, variableBinding);
- }
- return variableBinding;
- }
- IVariableBinding variableBinding = this.getVariableBinding(((LocalDeclaration) abstractVariableDeclaration).binding);
- if (variableBinding == null) {
- return null;
- }
- this.bindingsToAstNodes.put(variableBinding, variable);
- String key = variableBinding.getKey();
- if (key != null) {
- this.bindingTables.bindingKeysToBindings.put(key, variableBinding);
- }
- return variableBinding;
- }
- return null;
- }
-
- /*
- * Method declared on BindingResolver.
- */
- synchronized ITypeBinding resolveWellKnownType(String name) {
- if (this.scope == null) return null;
- try {
-// if (("boolean".equals(name))//$NON-NLS-1$
-// || ("char".equals(name))//$NON-NLS-1$
-// || ("byte".equals(name))//$NON-NLS-1$
-// || ("short".equals(name))//$NON-NLS-1$
-// || ("int".equals(name))//$NON-NLS-1$
-// || ("long".equals(name))//$NON-NLS-1$
-// || ("float".equals(name))//$NON-NLS-1$
-// || ("double".equals(name))//$NON-NLS-1$
-// || ("void".equals(name))) {//$NON-NLS-1$
-// return this.getTypeBinding(Scope.getBaseType(name.toCharArray()));
-// } else
- if ("Object".equals(name)) {//$NON-NLS-1$
- return this.getTypeBinding(this.scope.getJavaLangObject());
- } else if ("String".equals(name)) {//$NON-NLS-1$
- return this.getTypeBinding(this.scope.getJavaLangString());
- } else if ("Number".equals(name)) {//$NON-NLS-1$
- return this.getTypeBinding(this.scope.getJavaLangNumber());
- } else if ("Function".equals(name)) {//$NON-NLS-1$
- return this.getTypeBinding(this.scope.getJavaLangFunction());
- } else if ("Boolean".equals(name)) {//$NON-NLS-1$
- return this.getTypeBinding(this.scope.getJavaLangBoolean());
-// } else if ("java.lang.StringBuffer".equals(name)) {//$NON-NLS-1$
-// return this.getTypeBinding(this.scope.getType(TypeConstants.JAVA_LANG_STRINGBUFFER, 3));
-// } else if ("java.lang.Throwable".equals(name)) {//$NON-NLS-1$
-// return this.getTypeBinding(this.scope.getJavaLangThrowable());
-// } else if ("java.lang.Exception".equals(name)) {//$NON-NLS-1$
-// return this.getTypeBinding(this.scope.getType(TypeConstants.JAVA_LANG_EXCEPTION, 3));
-// } else if ("java.lang.RuntimeException".equals(name)) {//$NON-NLS-1$
-// return this.getTypeBinding(this.scope.getType(TypeConstants.JAVA_LANG_RUNTIMEEXCEPTION, 3));
-// } else if ("java.lang.Error".equals(name)) {//$NON-NLS-1$
-// return this.getTypeBinding(this.scope.getType(TypeConstants.JAVA_LANG_ERROR, 3));
-// } else if ("java.lang.Class".equals(name)) {//$NON-NLS-1$
-// return this.getTypeBinding(this.scope.getJavaLangClass());
-// } else if ("java.lang.Cloneable".equals(name)) {//$NON-NLS-1$
-// return this.getTypeBinding(this.scope.getJavaLangCloneable());
-// } else if ("java.io.Serializable".equals(name)) {//$NON-NLS-1$
-// return this.getTypeBinding(this.scope.getJavaIoSerializable());
-// } else if ("java.lang.Boolean".equals(name)) {//$NON-NLS-1$
-// return this.getTypeBinding(this.scope.getType(TypeConstants.JAVA_LANG_BOOLEAN, 3));
-// } else if ("java.lang.Byte".equals(name)) {//$NON-NLS-1$
-// return this.getTypeBinding(this.scope.getType(TypeConstants.JAVA_LANG_BYTE, 3));
-// } else if ("java.lang.Character".equals(name)) {//$NON-NLS-1$
-// return this.getTypeBinding(this.scope.getType(TypeConstants.JAVA_LANG_CHARACTER, 3));
-// } else if ("java.lang.Double".equals(name)) {//$NON-NLS-1$
-// return this.getTypeBinding(this.scope.getType(TypeConstants.JAVA_LANG_DOUBLE, 3));
-// } else if ("java.lang.Float".equals(name)) {//$NON-NLS-1$
-// return this.getTypeBinding(this.scope.getType(TypeConstants.JAVA_LANG_FLOAT, 3));
-// } else if ("java.lang.Integer".equals(name)) {//$NON-NLS-1$
-// return this.getTypeBinding(this.scope.getType(TypeConstants.JAVA_LANG_INTEGER, 3));
-// } else if ("java.lang.Long".equals(name)) {//$NON-NLS-1$
-// return this.getTypeBinding(this.scope.getType(TypeConstants.JAVA_LANG_LONG, 3));
-// } else if ("java.lang.Short".equals(name)) {//$NON-NLS-1$
-// return this.getTypeBinding(this.scope.getType(TypeConstants.JAVA_LANG_SHORT, 3));
-// } else if ("java.lang.Void".equals(name)) {//$NON-NLS-1$
-// return this.getTypeBinding(this.scope.getType(TypeConstants.JAVA_LANG_VOID, 3));
- }
- } catch (AbortCompilation e) {
- // ignore missing types
- }
- return null;
- }
-
-
- /*
- * Method declared on BindingResolver.
- */
- public CompilationUnitScope scope() {
- return this.scope;
- }
-
- /*
- * Method declared on BindingResolver.
- */
- synchronized void store(ASTNode node, org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode oldASTNode) {
- this.newAstToOldAst.put(node, oldASTNode);
- }
-
- /*
- * Method declared on BindingResolver.
- */
- synchronized void updateKey(ASTNode node, ASTNode newNode) {
- Object astNode = this.newAstToOldAst.remove(node);
- if (astNode != null) {
- this.newAstToOldAst.put(newNode, astNode);
- }
- }
-
- /**
- * Answer an array type binding with the given type binding and the given
- * dimensions.
- *
- * <p>If the given type binding is an array binding, then the resulting dimensions is the given dimensions
- * plus the existing dimensions of the array binding. Otherwise the resulting dimensions is the given
- * dimensions.</p>
- *
- * <p>
- * The default implementation of this method returns <code>null</code>.
- * Subclasses may reimplement.
- * </p>
- *
- * @param typeBinding the given type binding
- * @param dimensions the given dimensions
- * @return an array type binding with the given type binding and the given
- * dimensions
- * @throws IllegalArgumentException if the type binding represents the <code>void</code> type binding
- */
- ITypeBinding resolveArrayType(ITypeBinding typeBinding, int dimensions) {
- if (typeBinding.isRecovered()) throw new IllegalArgumentException("Cannot be called on a recovered type binding"); //$NON-NLS-1$
- ITypeBinding leafComponentType = typeBinding;
- int actualDimensions = dimensions;
- if (typeBinding.isArray()) {
- leafComponentType = typeBinding.getElementType();
- actualDimensions += typeBinding.getDimensions();
- }
- org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding leafTypeBinding = null;
- if (leafComponentType.isPrimitive()) {
- String name = leafComponentType.getBinaryName();
- switch(name.charAt(0)) {
- case 'I' :
- leafTypeBinding = org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding.INT;
- break;
- case 'Z' :
- leafTypeBinding = org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding.BOOLEAN;
- break;
- case 'C' :
- leafTypeBinding = org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding.CHAR;
- break;
- case 'J' :
- leafTypeBinding = org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding.LONG;
- break;
- case 'S' :
- leafTypeBinding = org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding.SHORT;
- break;
- case 'D' :
- leafTypeBinding = org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding.DOUBLE;
- break;
- case 'F' :
- leafTypeBinding = org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding.FLOAT;
- break;
- case 'V' :
- throw new IllegalArgumentException();
- }
- } else {
- leafTypeBinding = ((TypeBinding) leafComponentType).binding;
- }
- if (!(leafComponentType instanceof TypeBinding)) return null;
- return this.getTypeBinding(this.lookupEnvironment().createArrayType(leafTypeBinding, actualDimensions));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/DefaultCommentMapper.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/DefaultCommentMapper.java
deleted file mode 100644
index 7979c261..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/DefaultCommentMapper.java
+++ /dev/null
@@ -1,650 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.dom;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-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.Util;
-
-/**
- * Internal class for associating comments with AST nodes.
- *
- *
- * 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.
-*/
-class DefaultCommentMapper {
- Comment[] comments;
- Scanner scanner;
-
- // extended nodes storage
- int leadingPtr;
- ASTNode[] leadingNodes;
- long[] leadingIndexes;
- int trailingPtr, lastTrailingPtr;
- ASTNode[] trailingNodes;
- long[] trailingIndexes;
- static final int STORAGE_INCREMENT = 16;
-
- /**
- * @param table the given table of comments
- */
- DefaultCommentMapper(Comment[] table) {
- this.comments = table;
- }
-
- boolean hasSameTable(Comment[] table) {
- return this.comments == table;
- }
-
- /**
- * Get comment of the list which includes a given position
- *
- * @param position The position belonging to the looked up comment
- * @return comment which includes the given position or null if none was found
- */
- Comment getComment(int position) {
-
- if (this.comments == null) {
- return null;
- }
- int size = this.comments.length;
- if (size == 0) {
- return null;
- }
- int index = getCommentIndex(0, position, 0);
- if (index<0) {
- return null;
- }
- return this.comments[index];
- }
-
- /*
- * Get the index of comment which contains given position.
- * If there's no matching comment, then return depends on exact parameter:
- * = 0: return -1
- * < 0: return index of the comment before the given position
- * > 0: return index of the comment after the given position
- */
- private int getCommentIndex(int start, int position, int exact) {
- if (position == 0) {
- if (this.comments.length > 0 && this.comments[0].getStartPosition() == 0) {
- return 0;
- }
- return -1;
- }
- int bottom = start, top = this.comments.length - 1;
- int i = 0, index = -1;
- Comment comment = null;
- while (bottom <= top) {
- i = bottom + (top - bottom) /2;
- comment = this.comments[i];
- int commentStart = comment.getStartPosition();
- if (position < commentStart) {
- top = i-1;
- } else if (position >=(commentStart+comment.getLength())) {
- bottom = i+1;
- } else {
- index = i;
- break;
- }
- }
- if (index<0 && exact!=0) {
- comment = this.comments[i];
- if (position < comment.getStartPosition()) {
- return exact<0 ? i-1 : i;
- } else {
- return exact<0 ? i : i+1;
- }
- }
- return index;
- }
-
- /**
- * Returns the extended start position of the given node. Unlike
- * {@link ASTNode#getStartPosition()} and {@link ASTNode#getLength()},
- * the extended source range may include comments and whitespace
- * immediately before or after the normal source range for the node.
- *
- * @param node the node
- * @return the 0-based character index, or <code>-1</code>
- * if no source position information is recorded for this node
- * @see #getExtendedLength(ASTNode)
- *
- */
- public int getExtendedStartPosition(ASTNode node) {
- if (this.leadingPtr >= 0) {
- long range = -1;
- for (int i=0; range<0 && i<=this.leadingPtr; i++) {
- if (this.leadingNodes[i] == node) range = this.leadingIndexes[i];
- }
- if (range >= 0) {
- return this.comments[(int)(range>>32)].getStartPosition() ;
- }
- }
- return node.getStartPosition();
- }
-
- /*
- * Search the line number corresponding to a specific position
- * between the given line range (inclusive)
- * @param position int
- * @parem lineRange size-2 int[]
- * @return int
- */
- public final int getLineNumber(int position, int[] lineRange) {
- int[] lineEnds = this.scanner.lineEnds;
- int length = lineEnds.length;
- return Util.getLineNumber(position, lineEnds, (lineRange[0] > length ? length : lineRange[0]) -1, (lineRange[1] > length ? length : lineRange[1]) - 1);
- }
-
- /*
- * Returns the extended end position of the given node.
- */
- public int getExtendedEnd(ASTNode node) {
- int end = node.getStartPosition() + node.getLength();
- if (this.trailingPtr >= 0) {
- long range = -1;
- for (int i=0; range<0 && i<=this.trailingPtr; i++) {
- if (this.trailingNodes[i] == node) range = this.trailingIndexes[i];
- }
- if (range >= 0) {
- Comment lastComment = this.comments[(int) range];
- end = lastComment.getStartPosition() + lastComment.getLength();
- }
- }
- return end-1;
- }
-
- /**
- * Returns the extended source length of the given node. Unlike
- * {@link ASTNode#getStartPosition()} and {@link ASTNode#getLength()},
- * the extended source range may include comments and whitespace
- * immediately before or after the normal source range for the node.
- *
- * @param node the node
- * @return a (possibly 0) length, or <code>0</code>
- * if no source position information is recorded for this node
- * @see #getExtendedStartPosition(ASTNode)
- * @see #getExtendedEnd(ASTNode)
- *
- */
- public int getExtendedLength(ASTNode node) {
- return getExtendedEnd(node) - getExtendedStartPosition(node) + 1;
- }
-
- /**
- * Return index of first leading comment of a given node.
- *
- * @param node
- * @return index of first leading comment or -1 if node has no leading comment
- */
- int firstLeadingCommentIndex(ASTNode node) {
- if (this.leadingPtr >= 0) {
- for (int i=0; i<=this.leadingPtr; i++) {
- if (this.leadingNodes[i] == node) {
- return (int) (this.leadingIndexes[i]>>32);
- }
- }
- }
- return -1;
- }
-
- /**
- * Return index of last trailing comment of a given node.
- *
- * @param node
- * @return index of last trailing comment or -1 if node has no trailing comment
- */
- int lastTrailingCommentIndex(ASTNode node) {
- if (this.trailingPtr >= 0) {
- for (int i=0; i<=this.trailingPtr; i++) {
- if (this.trailingNodes[i] == node) {
- return (int) this.trailingIndexes[i];
- }
- }
- }
- return -1;
- }
-
- /*
- * Initialize leading and trailing comments tables in whole nodes hierarchy of a compilation
- * unit.
- * Scanner is necessary to scan between nodes and comments and verify if there's
- * nothing else than white spaces.
- */
- void initialize(JavaScriptUnit unit, Scanner sc) {
-
- // Init array pointers
- this.leadingPtr = -1;
- this.trailingPtr = -1;
-
- // Init comments
- this.comments = unit.optionalCommentTable;
- if (this.comments == null) {
- return;
- }
- int size = this.comments.length;
- if (size == 0) {
- return;
- }
-
- // Init scanner and start ranges computing
- this.scanner = sc;
- this.scanner.tokenizeWhiteSpace = true;
-
- // Start unit visit
- DefaultASTVisitor commentVisitor = new CommentMapperVisitor();
- unit.accept(commentVisitor);
-
- // Reduce leading arrays if necessary
- int leadingCount = this.leadingPtr + 1;
- if (leadingCount > 0 && leadingCount < this.leadingIndexes.length) {
- System.arraycopy(this.leadingNodes, 0, this.leadingNodes = new ASTNode[leadingCount], 0, leadingCount);
- System.arraycopy(this.leadingIndexes, 0, this.leadingIndexes= new long[leadingCount], 0, leadingCount);
- }
-
- // Reduce trailing arrays if necessary
- if (this.trailingPtr >= 0) {
- // remove last remaining unresolved nodes
- while (this.trailingIndexes[this.trailingPtr] == -1) {
- this.trailingPtr--;
- if (this.trailingPtr < 0) {
- this.trailingIndexes = null;
- this.trailingNodes = null;
- break;
- }
- }
-
- // reduce array size
- int trailingCount = this.trailingPtr + 1;
- if (trailingCount > 0 && trailingCount < this.trailingIndexes.length) {
- System.arraycopy(this.trailingNodes, 0, this.trailingNodes = new ASTNode[trailingCount], 0, trailingCount);
- System.arraycopy(this.trailingIndexes, 0, this.trailingIndexes= new long[trailingCount], 0, trailingCount);
- }
- }
-
- // Release scanner as it's only used during unit visit
- this.scanner = null;
- }
-
- /**
- * Search and store node leading comments. Comments are searched in position range
- * from previous extended position to node start position. If one or several comment are found,
- * returns first comment start position, otherwise returns node start position.
- * <p>
- * Starts to search for first comment before node start position and return if none was found...
- *</p><p>
- * When first comment is found before node, goes up in comment list until one of
- * following conditions becomes true:
- * <ol>
- * <li>comment end is before previous end</li>
- * <li>comment start and previous end is on the same line but not on same line of node start</li>
- * <li>there's other than white characters between current node and comment</li>
- * <li>there's more than 1 line between current node and comment</li>
- * </ol>
- * If some comment have been found, then no token should be on
- * on the same line before, so remove all comments which do not verify this assumption.
- * </p><p>
- * If finally there's leading still comments, then stores indexes of the first and last one
- * in leading comments table.
- */
- int storeLeadingComments(ASTNode node, int previousEnd, int[] parentLineRange) {
- // Init extended position
- int nodeStart = node.getStartPosition();
- int extended = nodeStart;
-
- // Get line of node start position
- int previousEndLine = getLineNumber(previousEnd, parentLineRange);
- int nodeStartLine = getLineNumber(nodeStart, parentLineRange);
-
- // Find first comment index
- int idx = getCommentIndex(0, nodeStart, -1);
- if (idx == -1) {
- return nodeStart;
- }
-
- // Look after potential comments
- int startIdx = -1;
- int endIdx = idx;
- int previousStart = nodeStart;
- while (idx >= 0 && previousStart >= previousEnd) {
- // Verify for each comment that there's only white spaces between end and start of {following comment|node}
- Comment comment = this.comments[idx];
- int commentStart = comment.getStartPosition();
- int end = commentStart+comment.getLength()-1;
- int commentLine = getLineNumber(commentStart, parentLineRange);
- if (end <= previousEnd || (commentLine == previousEndLine && commentLine != nodeStartLine)) {
- // stop search on condition 1) and 2)
- break;
- } else if ((end+1) < previousStart) { // may be equals => then no scan is necessary
- this.scanner.resetTo(end+1, previousStart);
- try {
- int token = this.scanner.getNextToken();
- if (token != TerminalTokens.TokenNameWHITESPACE || this.scanner.currentPosition != previousStart) {
- // stop search on condition 3)
- // if first comment fails, then there's no extended position in fact
- if (idx == endIdx) {
- return nodeStart;
- }
- break;
- }
- } catch (InvalidInputException e) {
- // Should not happen, but return no extended position...
- return nodeStart;
- }
- // verify that there's no more than one line between node/comments
- char[] gap = this.scanner.getCurrentIdentifierSource();
- int nbrLine = 0;
- int pos = -1;
- while ((pos=CharOperation.indexOf('\n', gap,pos+1)) >= 0) {
- nbrLine++;
- }
- if (nbrLine > 1) {
- // stop search on condition 4)
- break;
- }
- }
- // Store previous infos
- previousStart = commentStart;
- startIdx = idx--;
- }
- if (startIdx != -1) {
- // Verify that there's no token on the same line before first leading comment
- int commentStart = this.comments[startIdx].getStartPosition();
- if (previousEnd < commentStart && previousEndLine != nodeStartLine) {
- int lastTokenEnd = previousEnd;
- this.scanner.resetTo(previousEnd, commentStart);
- try {
- while (this.scanner.currentPosition < commentStart) {
- if (this.scanner.getNextToken() != TerminalTokens.TokenNameWHITESPACE) {
- lastTokenEnd = this.scanner.getCurrentTokenEndPosition();
- }
- }
- } catch (InvalidInputException e) {
- // do nothing
- }
- int lastTokenLine = getLineNumber(lastTokenEnd, parentLineRange);
- int length = this.comments.length;
- while (startIdx<length && lastTokenLine == getLineNumber(this.comments[startIdx].getStartPosition(), parentLineRange) && nodeStartLine != lastTokenLine) {
- startIdx++;
- }
- }
- // Store leading comments indexes
- if (startIdx <= endIdx) {
- if (++this.leadingPtr == 0) {
- this.leadingNodes = new ASTNode[STORAGE_INCREMENT];
- this.leadingIndexes = new long[STORAGE_INCREMENT];
- } else if (this.leadingPtr == this.leadingNodes.length) {
- int newLength = (this.leadingPtr*3/2)+STORAGE_INCREMENT;
- System.arraycopy(this.leadingNodes, 0, this.leadingNodes = new ASTNode[newLength], 0, this.leadingPtr);
- System.arraycopy(this.leadingIndexes, 0, this.leadingIndexes = new long[newLength], 0, this.leadingPtr);
- }
- this.leadingNodes[this.leadingPtr] = node;
- this.leadingIndexes[this.leadingPtr] = (((long)startIdx)<<32) + endIdx;
- extended = this.comments[endIdx].getStartPosition();
- }
- }
- return extended;
- }
-
- /**
- * Search and store node trailing comments. Comments are searched in position range
- * from node end position to specified next start. If one or several comment are found,
- * returns last comment end position, otherwise returns node end position.
- * <p>
- * Starts to search for first comment after node end position and return if none was found...
- *</p><p>
- * When first comment is found after node, goes down in comment list until one of
- * following conditions becomes true:
- * <ol>
- * <li>comment start is after next start</li>
- * <li>there's other than white characters between current node and comment</li>
- * <li>there's more than 1 line between current node and comment</li>
- *</ol>
- * If at least potential comments have been found, then all of them has to be separated
- * from following node. So, remove all comments which do not verify this assumption.
- * Note that this verification is not applicable on last node.
- * </p><p>
- * If finally there's still trailing comments, then stores indexes of the first and last one
- * in trailing comments table.
- */
- int storeTrailingComments(ASTNode node, int nextStart, boolean lastChild, int[] parentLineRange) {
-
- // Init extended position
- int nodeEnd = node.getStartPosition()+node.getLength()-1;
- if (nodeEnd == nextStart) {
- // special case for last child of its parent
- if (++this.trailingPtr == 0) {
- this.trailingNodes = new ASTNode[STORAGE_INCREMENT];
- this.trailingIndexes = new long[STORAGE_INCREMENT];
- this.lastTrailingPtr = -1;
- } else if (this.trailingPtr == this.trailingNodes.length) {
- int newLength = (this.trailingPtr*3/2)+STORAGE_INCREMENT;
- System.arraycopy(this.trailingNodes, 0, this.trailingNodes = new ASTNode[newLength], 0, this.trailingPtr);
- System.arraycopy(this.trailingIndexes, 0, this.trailingIndexes = new long[newLength], 0, this.trailingPtr);
- }
- this.trailingNodes[this.trailingPtr] = node;
- this.trailingIndexes[this.trailingPtr] = -1;
- return nodeEnd;
- }
- int extended = nodeEnd;
-
- // Get line number
- int nodeEndLine = getLineNumber(nodeEnd, parentLineRange);
-
- // Find comments range index
- int idx = getCommentIndex(0, nodeEnd, 1);
- if (idx == -1) {
- return nodeEnd;
- }
-
- // Look after potential comments
- int startIdx = idx;
- int endIdx = -1;
- int length = this.comments.length;
- int commentStart = extended+1;
- int previousEnd = nodeEnd+1;
- int sameLineIdx = -1;
- while (idx<length && commentStart < nextStart) {
- // get comment and leave if next starting position has been reached
- Comment comment = this.comments[idx];
- commentStart = comment.getStartPosition();
- // verify that there's nothing else than white spaces between node/comments
- if (commentStart >= nextStart) {
- // stop search on condition 1)
- break;
- } else if (previousEnd < commentStart) {
- this.scanner.resetTo(previousEnd, commentStart);
- try {
- int token = this.scanner.getNextToken();
- if (token != TerminalTokens.TokenNameWHITESPACE || this.scanner.currentPosition != commentStart) {
- // stop search on condition 2)
- // if first index fails, then there's no extended position in fact...
- if (idx == startIdx) {
- return nodeEnd;
- }
- // otherwise we get the last index of trailing comment => break
- break;
- }
- } catch (InvalidInputException e) {
- // Should not happen, but return no extended position...
- return nodeEnd;
- }
- // verify that there's no more than one line between node/comments
- char[] gap = this.scanner.getCurrentIdentifierSource();
- int nbrLine = 0;
- int pos = -1;
- while ((pos=CharOperation.indexOf('\n', gap,pos+1)) >= 0) {
- nbrLine++;
- }
- if (nbrLine > 1) {
- // stop search on condition 3)
- break;
- }
- }
- // Store index if we're on the same line than node end
- int commentLine = getLineNumber(commentStart, parentLineRange);
- if (commentLine == nodeEndLine) {
- sameLineIdx = idx;
- }
- // Store previous infos
- previousEnd = commentStart+comment.getLength();
- endIdx = idx++;
- }
- if (endIdx != -1) {
- // Verify that following node start is separated
- if (!lastChild) {
- int nextLine = getLineNumber(nextStart, parentLineRange);
- int previousLine = getLineNumber(previousEnd, parentLineRange);
- if((nextLine - previousLine) <= 1) {
- if (sameLineIdx == -1) return nodeEnd;
- endIdx = sameLineIdx;
- }
- }
- // Store trailing comments indexes
- if (++this.trailingPtr == 0) {
- this.trailingNodes = new ASTNode[STORAGE_INCREMENT];
- this.trailingIndexes = new long[STORAGE_INCREMENT];
- this.lastTrailingPtr = -1;
- } else if (this.trailingPtr == this.trailingNodes.length) {
- int newLength = (this.trailingPtr*3/2)+STORAGE_INCREMENT;
- System.arraycopy(this.trailingNodes, 0, this.trailingNodes = new ASTNode[newLength], 0, this.trailingPtr);
- System.arraycopy(this.trailingIndexes, 0, this.trailingIndexes = new long[newLength], 0, this.trailingPtr);
- }
- this.trailingNodes[this.trailingPtr] = node;
- long nodeRange = (((long)startIdx)<<32) + endIdx;
- this.trailingIndexes[this.trailingPtr] = nodeRange;
- // Compute new extended end
- extended = this.comments[endIdx].getStartPosition()+this.comments[endIdx].getLength()-1;
- // Look for children unresolved extended end
- ASTNode previousNode = node;
- int ptr = this.trailingPtr - 1; // children extended end were stored before
- while (ptr >= 0) {
- long range = this.trailingIndexes[ptr];
- if (range != -1) break; // there's no more unresolved nodes
- ASTNode unresolved = this.trailingNodes[ptr];
- if (previousNode != unresolved.getParent()) break; // we're no longer in node ancestor hierarchy
- this.trailingIndexes[ptr] = nodeRange;
- previousNode = unresolved;
- ptr--; // get previous node
- }
- // Remove remaining unresolved nodes
- if (ptr > this.lastTrailingPtr) {
- int offset = ptr - this.lastTrailingPtr;
- for (int i=ptr+1; i<=this.trailingPtr; i++) {
- this.trailingNodes[i-offset] = this.trailingNodes[i];
- this.trailingIndexes[i-offset] = this.trailingIndexes[i];
- }
- this.trailingPtr -= offset;
- }
- this.lastTrailingPtr = this.trailingPtr;
- }
- return extended;
- }
-
- class CommentMapperVisitor extends DefaultASTVisitor {
-
- ASTNode topSiblingParent = null;
- ASTNode[] siblings = new ASTNode[10];
- int[][] parentLineRange = new int[10][];
- int siblingPtr = -1;
-
- protected boolean visitNode(ASTNode node) {
- if (node instanceof InferredType)
- return true;
-
- // Get default previous end
- ASTNode parent = node.getParent();
- int previousEnd = parent.getStartPosition();
-
- // Look for sibling node
- ASTNode sibling = parent == this.topSiblingParent ? (ASTNode) this.siblings[this.siblingPtr] : null;
- if (sibling != null) {
- // Found one previous sibling, so compute its trailing comments using current node start position
- try {
- previousEnd = storeTrailingComments(sibling, node.getStartPosition(), false, this.parentLineRange[this.siblingPtr]);
- } catch (Exception ex) {
- // Give up extended ranges at this level if unexpected exception happens...
- }
- }
-
- // Stop visit for malformed node (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=84049)
- if ((node.typeAndFlags & ASTNode.MALFORMED) != 0) {
- return false;
- }
-
- // Compute leading comments for current node
- int[] previousLineRange = this.siblingPtr > -1 ? this.parentLineRange[this.siblingPtr] : new int[] {1, DefaultCommentMapper.this.scanner.linePtr+1};
- try {
- storeLeadingComments(node, previousEnd, previousLineRange);
- } catch (Exception ex) {
- // Give up extended ranges at this level if unexpected exception happens...
- }
-
- // Store current node as waiting sibling for its parent
- if (this.topSiblingParent != parent) {
- if (this.siblings.length == ++this.siblingPtr) {
- System.arraycopy(this.siblings, 0, this.siblings = new ASTNode[this.siblingPtr*2], 0, this.siblingPtr);
- System.arraycopy(this.parentLineRange, 0, this.parentLineRange = new int[this.siblingPtr*2][], 0, this.siblingPtr);
- }
- if (this.topSiblingParent == null) {
- // node is a JavaScriptUnit
- this.parentLineRange[this.siblingPtr] = previousLineRange;
- } else {
- int parentStart = parent.getStartPosition();
- int firstLine = getLineNumber(parentStart, previousLineRange);
- int lastLine = getLineNumber(parentStart + parent.getLength() - 1, previousLineRange);
- if (this.parentLineRange[this.siblingPtr] == null) {
- this.parentLineRange[this.siblingPtr] = new int[] {firstLine, lastLine};
- } else {
- int[] lineRange = this.parentLineRange[this.siblingPtr];
- lineRange[0] = firstLine;
- lineRange[1] = lastLine;
- }
- }
- this.topSiblingParent = parent;
- }
- this.siblings[this.siblingPtr] = node;
-
- // We're always ok to visit sub-levels
- return true;
- }
-
- protected void endVisitNode(ASTNode node) {
-
- // Look if a child node is waiting for trailing comments computing
- ASTNode sibling = this.topSiblingParent == node ? (ASTNode) this.siblings[this.siblingPtr] : null;
- if (sibling != null) {
- try {
- storeTrailingComments(sibling, node.getStartPosition()+node.getLength()-1, true, this.parentLineRange[this.siblingPtr]);
- } catch (Exception ex) {
- // Give up extended ranges at this level if unexpected exception happens...
- }
- }
- // Remove sibling if needed
- if (this.topSiblingParent != null /*not a JavaScriptUnit*/
- && this.topSiblingParent == node) {
- this.siblingPtr--;
- this.topSiblingParent = node.getParent();
- }
- }
-
- public boolean visit ( JavaScriptUnit node) {
- // do nothing special, just go down in sub-levels
- return true;
- }
- }
-}
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
deleted file mode 100644
index 5804532d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/DoStatement.java
+++ /dev/null
@@ -1,276 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Do statement AST node type.
- *
- * <pre>
- * DoStatement:
- * <b>do</b> Statement <b>while</b> <b>(</b> Expression <b>)</b> <b>;</b>
- * </pre>
- *
- * 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 DoStatement extends Statement {
-
- /**
- * The "expression" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor EXPRESSION_PROPERTY =
- new ChildPropertyDescriptor(DoStatement.class, "expression", Expression.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "body" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor BODY_PROPERTY =
- new ChildPropertyDescriptor(DoStatement.class, "body", Statement.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List properyList = new ArrayList(3);
- createPropertyList(DoStatement.class, properyList);
- addProperty(EXPRESSION_PROPERTY, properyList);
- addProperty(BODY_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The expression; lazily initialized; defaults to an unspecified, but
- * legal, expression.
- */
- private Expression expression = null;
-
- /**
- * The body statement; lazily initialized; defaults to an empty block.
- */
- private Statement body = null;
-
- /**
- * Creates a new unparented do statement node owned by the given
- * AST. By default, the expresssion is unspecified, but legal,
- * and the body statement is an empty block.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- DoStatement(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == EXPRESSION_PROPERTY) {
- if (get) {
- return getExpression();
- } else {
- setExpression((Expression) child);
- return null;
- }
- }
- if (property == BODY_PROPERTY) {
- if (get) {
- return getBody();
- } else {
- setBody((Statement) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return DO_STATEMENT;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- DoStatement result = new DoStatement(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.copyLeadingComment(this);
- result.setExpression((Expression) getExpression().clone(target));
- result.setBody((Statement) getBody().clone(target));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChild(visitor, getBody());
- acceptChild(visitor, getExpression());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the expression of this do statement.
- *
- * @return the expression node
- */
- public Expression getExpression() {
- if (this.expression == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.expression == null) {
- preLazyInit();
- this.expression = new SimpleName(this.ast);
- postLazyInit(this.expression, EXPRESSION_PROPERTY);
- }
- }
- }
- return this.expression;
- }
-
- /**
- * Sets the expression of this do statement.
- *
- * @param expression the expression node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setExpression(Expression expression) {
- if (expression == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.expression;
- preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY);
- this.expression = expression;
- postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY);
- }
-
- /**
- * Returns the body of this do statement.
- *
- * @return the body statement node
- */
- public Statement getBody() {
- if (this.body == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.body == null) {
- preLazyInit();
- this.body = new Block(this.ast);
- postLazyInit(this.body, BODY_PROPERTY);
- }
- }
- }
- return this.body;
- }
-
- /**
- * Sets the body of this do statement.
- * <p>
- * Special note: The JavaScript language does not allow a local variable declaration
- * to appear as the body of a do statement (they may only appear within a
- * block). However, the AST will allow a <code>VariableDeclarationStatement</code>
- * as the body of a <code>DoStatement</code>. To get something that will
- * compile, be sure to embed the <code>VariableDeclarationStatement</code>
- * inside a <code>Block</code>.
- * </p>
- *
- * @param statement the body statement node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setBody(Statement statement) {
- if (statement == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.body;
- preReplaceChild(oldChild, statement, BODY_PROPERTY);
- this.body = statement;
- postReplaceChild(oldChild, statement, BODY_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return super.memSize() + 2 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.expression == null ? 0 : getExpression().treeSize())
- + (this.body == null ? 0 : getBody().treeSize());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/DocCommentParser.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/DocCommentParser.java
deleted file mode 100644
index ea026b70..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/DocCommentParser.java
+++ /dev/null
@@ -1,696 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2004, 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.dom;
-
-import java.util.Iterator;
-import java.util.List;
-
-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.AbstractCommentParser;
-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;
-
-/**
- * Internal parser used for decoding doc comments.
- *
- * 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.
- */
-class DocCommentParser extends AbstractCommentParser {
-
- private JSdoc docComment;
- private AST ast;
-
- DocCommentParser(AST ast, Scanner scanner, boolean check) {
- super(null);
- this.ast = ast;
- this.scanner = scanner;
- this.sourceLevel = this.ast.apiLevel() >= AST.JLS3 ? ClassFileConstants.JDK1_5 : ClassFileConstants.JDK1_3;
- this.checkDocComment = check;
- this.kind = DOM_PARSER | TEXT_PARSE;
- }
-
- public JSdoc parse(int[] positions) {
- return parse(positions[0], positions[1]-positions[0]);
- }
- public JSdoc parse(int start, int length) {
-
- // Init
- this.source = this.scanner.source;
- this.lineEnds = this.scanner.lineEnds;
- this.docComment = new JSdoc(this.ast);
-
- // Parse
- if (this.checkDocComment) {
- this.javadocStart = start;
- this.javadocEnd = start+length-1;
- this.firstTagPosition = this.javadocStart;
- commentParse();
- }
- this.docComment.setSourceRange(start, length);
- if (this.ast.apiLevel == AST.JLS2_INTERNAL) {
- setComment(start, length); // backward compatibility
- }
- return this.docComment;
- }
-
- /**
- * Sets the comment starting at the given position and with the given length.
- * <p>
- * Note the only purpose of this method is to hide deprecated warnings.
- * @deprecated mark deprecated to hide deprecated usage
- */
- private void setComment(int start, int length) {
- this.docComment.setComment(new String(this.source, start, length));
- }
-
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- buffer.append("javadoc: ").append(this.docComment).append("\n"); //$NON-NLS-1$ //$NON-NLS-2$
- buffer.append(super.toString());
- return buffer.toString();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.parser.AbstractCommentParser#createArgumentReference(char[], java.lang.Object, int)
- */
- protected Object createArgumentReference(char[] name, int dim, boolean isVarargs, Object typeRef, long[] dimPositions, long argNamePos) throws InvalidInputException {
- try {
- FunctionRefParameter argument = this.ast.newFunctionRefParameter();
- ASTNode node = (ASTNode) typeRef;
- int argStart = node.getStartPosition();
- int argEnd = node.getStartPosition()+node.getLength()-1;
- if (dim > 0) argEnd = (int) dimPositions[dim-1];
- if (argNamePos >= 0) argEnd = (int) argNamePos;
- if (name.length != 0) {
- final SimpleName argName = new SimpleName(this.ast);
- argName.internalSetIdentifier(new String(name));
- argument.setName(argName);
- int argNameStart = (int) (argNamePos >>> 32);
- argName.setSourceRange(argNameStart, argEnd-argNameStart+1);
- }
- Type argType = null;
- if (node.getNodeType() == ASTNode.PRIMITIVE_TYPE) {
- argType = (PrimitiveType) node;
-// if (dim > 0) {
-// argType = this.ast.newArrayType(argType, dim);
-// argType.setSourceRange(argStart, ((int) dimPositions[dim-1])-argStart+1);
-// }
- } else {
- Name argTypeName = (Name) node;
- argType = this.ast.newSimpleType(argTypeName);
- argType.setSourceRange(argStart, node.getLength());
- }
- if (dim > 0 && !isVarargs) {
- for (int i=0; i<dim; i++) {
- argType = this.ast.newArrayType(argType);
- argType.setSourceRange(argStart, ((int) dimPositions[i])-argStart+1);
- }
- }
- argument.setType(argType);
- argument.setSourceRange(argStart, argEnd - argStart + 1);
- return argument;
- }
- catch (ClassCastException ex) {
- throw new InvalidInputException();
- }
- }
-/* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.parser.AbstractCommentParser#createFieldReference()
- */
- protected Object createFieldReference(Object receiver) throws InvalidInputException {
- try {
- MemberRef fieldRef = this.ast.newMemberRef();
- SimpleName fieldName = new SimpleName(this.ast);
- fieldName.internalSetIdentifier(new String(this.identifierStack[0]));
- fieldRef.setName(fieldName);
- int start = (int) (this.identifierPositionStack[0] >>> 32);
- int end = (int) this.identifierPositionStack[0];
- fieldName.setSourceRange(start, end - start + 1);
- if (receiver == null) {
- start = this.memberStart;
- fieldRef.setSourceRange(start, end - start + 1);
- } else {
- Name typeRef = (Name) receiver;
- fieldRef.setQualifier(typeRef);
- start = typeRef.getStartPosition();
- end = fieldName.getStartPosition()+fieldName.getLength()-1;
- fieldRef.setSourceRange(start, end-start+1);
- }
- return fieldRef;
- }
- catch (ClassCastException ex) {
- throw new InvalidInputException();
- }
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.parser.AbstractCommentParser#createMethodReference(java.lang.Object[])
- */
- protected Object createMethodReference(Object receiver, List arguments) throws InvalidInputException {
- try {
- // Create method ref
- FunctionRef methodRef = this.ast.newFunctionRef();
- SimpleName methodName = new SimpleName(this.ast);
- int length = this.identifierLengthStack[0] - 1; // may be > 0 for member class constructor reference
- methodName.internalSetIdentifier(new String(this.identifierStack[length]));
- methodRef.setName(methodName);
- int start = (int) (this.identifierPositionStack[length] >>> 32);
- int end = (int) this.identifierPositionStack[length];
- methodName.setSourceRange(start, end - start + 1);
- // Set qualifier
- if (receiver == null) {
- start = this.memberStart;
- methodRef.setSourceRange(start, end - start + 1);
- } else {
- Name typeRef = (Name) receiver;
- methodRef.setQualifier(typeRef);
- start = typeRef.getStartPosition();
- }
- // Add arguments
- if (arguments != null) {
- Iterator parameters = arguments.listIterator();
- while (parameters.hasNext()) {
- FunctionRefParameter param = (FunctionRefParameter) parameters.next();
- methodRef.parameters().add(param);
- }
- }
- methodRef.setSourceRange(start, this.scanner.getCurrentTokenEndPosition()-start+1);
- return methodRef;
- }
- catch (ClassCastException ex) {
- throw new InvalidInputException();
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.parser.AbstractCommentParser#createTag()
- */
- protected void createTag() {
- TagElement tagElement = this.ast.newTagElement();
- int position = this.scanner.currentPosition;
- this.scanner.resetTo(this.tagSourceStart, this.tagSourceEnd);
- StringBuffer tagName = new StringBuffer();
- int start = this.tagSourceStart;
- this.scanner.getNextChar();
- while (this.scanner.currentPosition <= (this.tagSourceEnd+1)) {
- tagName.append(this.scanner.currentCharacter);
- this.scanner.getNextChar();
- }
- tagElement.setTagName(tagName.toString());
- if (this.inlineTagStarted) {
- start = this.inlineTagStart;
- TagElement previousTag = null;
- if (this.astPtr == -1) {
- previousTag = this.ast.newTagElement();
- previousTag.setSourceRange(start, this.tagSourceEnd-start+1);
- pushOnAstStack(previousTag, true);
- } else {
- previousTag = (TagElement) this.astStack[this.astPtr];
- }
- int previousStart = previousTag.getStartPosition();
- previousTag.fragments().add(tagElement);
- previousTag.setSourceRange(previousStart, this.tagSourceEnd-previousStart+1);
- } else {
- pushOnAstStack(tagElement, true);
- }
- tagElement.setSourceRange(start, this.tagSourceEnd-start+1);
- this.scanner.resetTo(position, this.javadocEnd);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.parser.AbstractCommentParser#createTypeReference()
- */
- protected Object createTypeReference(int primitiveToken) {
- int size = this.identifierLengthStack[this.identifierLengthPtr];
- String[] identifiers = new String[size];
- int pos = this.identifierPtr - size + 1;
- for (int i = 0; i < size; i++) {
- identifiers[i] = new String(this.identifierStack[pos+i]);
- }
- ASTNode typeRef = null;
- if (primitiveToken == -1) {
- typeRef = this.ast.internalNewName(identifiers);
- } else {
- switch (primitiveToken) {
- case TerminalTokens.TokenNamevoid :
- typeRef = this.ast.newPrimitiveType(PrimitiveType.VOID);
- break;
- case TerminalTokens.TokenNameboolean :
- typeRef = this.ast.newPrimitiveType(PrimitiveType.BOOLEAN);
- break;
- case TerminalTokens.TokenNamebyte :
- typeRef = this.ast.newPrimitiveType(PrimitiveType.BYTE);
- break;
- case TerminalTokens.TokenNamechar :
- typeRef = this.ast.newPrimitiveType(PrimitiveType.CHAR);
- break;
- case TerminalTokens.TokenNamedouble :
- typeRef = this.ast.newPrimitiveType(PrimitiveType.DOUBLE);
- break;
- case TerminalTokens.TokenNamefloat :
- typeRef = this.ast.newPrimitiveType(PrimitiveType.FLOAT);
- break;
- case TerminalTokens.TokenNameint :
- typeRef = this.ast.newPrimitiveType(PrimitiveType.INT);
- break;
- case TerminalTokens.TokenNamelong :
- typeRef = this.ast.newPrimitiveType(PrimitiveType.LONG);
- break;
- case TerminalTokens.TokenNameshort :
- typeRef = this.ast.newPrimitiveType(PrimitiveType.SHORT);
- break;
- default:
- // should not happen
- return null;
- }
- }
- // Update ref for whole name
- int start = (int) (this.identifierPositionStack[pos] >>> 32);
-// int end = (int) this.identifierPositionStack[this.identifierPtr];
-// typeRef.setSourceRange(start, end-start+1);
- // Update references of each simple name
- if (size > 1) {
- Name name = (Name)typeRef;
- int nameIndex = size;
- for (int i=this.identifierPtr; i>pos; i--, nameIndex--) {
- int s = (int) (this.identifierPositionStack[i] >>> 32);
- int e = (int) this.identifierPositionStack[i];
- name.index = nameIndex;
- SimpleName simpleName = ((QualifiedName)name).getName();
- simpleName.index = nameIndex;
- simpleName.setSourceRange(s, e-s+1);
- name.setSourceRange(start, e-start+1);
- name = ((QualifiedName)name).getQualifier();
- }
- int end = (int) this.identifierPositionStack[pos];
- name.setSourceRange(start, end-start+1);
- name.index = nameIndex;
- } else {
- int end = (int) this.identifierPositionStack[pos];
- typeRef.setSourceRange(start, end-start+1);
- }
- return typeRef;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.parser.AbstractCommentParser#parseIdentifierTag(boolean)
- */
- protected boolean parseIdentifierTag(boolean report) {
- if (super.parseIdentifierTag(report)) {
- createTag();
- this.index = this.tagSourceEnd+1;
- this.scanner.resetTo(this.index, this.javadocEnd);
- return true;
- }
- return false;
- }
-
- /*
- * Parse @return tag declaration
- */
- protected boolean parseReturn() {
- createTag();
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.parser.AbstractCommentParser#parseTag(int)
- */
- protected boolean parseTag(int previousPosition) throws InvalidInputException {
-
- // Read tag name
- int currentPosition = this.index;
- int token = readTokenAndConsume();
- char[] tagName = CharOperation.NO_CHAR;
- if (currentPosition == this.scanner.startPosition) {
- this.tagSourceStart = this.scanner.getCurrentTokenStartPosition();
- this.tagSourceEnd = this.scanner.getCurrentTokenEndPosition();
- tagName = this.scanner.getCurrentIdentifierSource();
- } else {
- this.tagSourceEnd = currentPosition-1;
- }
-
- // Try to get tag name other than javaScript identifier
- // (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=51660)
- if (this.scanner.currentCharacter != ' ' && !ScannerHelper.isWhitespace(this.scanner.currentCharacter)) {
- tagNameToken: while (token != TerminalTokens.TokenNameEOF && this.index < this.scanner.eofPosition) {
- int length = tagName.length;
- // !, ", #, %, &, ', -, :, <, >, * chars and spaces are not allowed in tag names
- switch (this.scanner.currentCharacter) {
- case '}':
- case '*': // break for '*' as this is perhaps the end of comment (bug 65288)
- case '!':
- case '#':
- case '%':
- case '&':
- case '\'':
- case '"':
- case ':':
- case '<':
- case '>':
- break tagNameToken;
- case '-': // allowed in tag names as this character is often used in doclets (bug 68087)
- System.arraycopy(tagName, 0, tagName = new char[length+1], 0, length);
- tagName[length] = this.scanner.currentCharacter;
- break;
- default:
- if (this.scanner.currentCharacter == ' ' || ScannerHelper.isWhitespace(this.scanner.currentCharacter)) {
- break tagNameToken;
- }
- token = readTokenAndConsume();
- char[] ident = this.scanner.getCurrentIdentifierSource();
- System.arraycopy(tagName, 0, tagName = new char[length+ident.length], 0, length);
- System.arraycopy(ident, 0, tagName, length, ident.length);
- break;
- }
- this.tagSourceEnd = this.scanner.getCurrentTokenEndPosition();
- this.scanner.getNextChar();
- this.index = this.scanner.currentPosition;
- }
- }
- int length = tagName.length;
- this.index = this.tagSourceEnd+1;
- this.scanner.currentPosition = this.tagSourceEnd+1;
- this.tagSourceStart = previousPosition;
-
- // tage name may be empty (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=125903)
- if (tagName.length == 0) {
- return false;
- }
-
- // Decide which parse to perform depending on tag name
- this.tagValue = NO_TAG_VALUE;
- boolean valid = true;
- switch (token) {
- case TerminalTokens.TokenNameIdentifier :
- switch (tagName[0]) {
- case 'd':
- if (length == TAG_DEPRECATED_LENGTH && CharOperation.equals(TAG_DEPRECATED, tagName)) {
- this.deprecated = true;
- this.tagValue = TAG_DEPRECATED_VALUE;
- } else {
- this.tagValue = TAG_OTHERS_VALUE;
- }
- createTag();
- break;
- case 'p':
- if (length == TAG_PARAM_LENGTH && CharOperation.equals(TAG_PARAM, tagName)) {
- this.tagValue = TAG_PARAM_VALUE;
- valid = parseParam();
- } else {
- this.tagValue = TAG_OTHERS_VALUE;
- createTag();
- }
- break;
- case 'e':
- if (length == TAG_EXCEPTION_LENGTH && CharOperation.equals(TAG_EXCEPTION, tagName)) {
- this.tagValue = TAG_EXCEPTION_VALUE;
- valid = parseThrows();
- } else {
- this.tagValue = TAG_OTHERS_VALUE;
- createTag();
- }
- break;
- case 's':
- if (length == TAG_SEE_LENGTH && CharOperation.equals(TAG_SEE, tagName)) {
- this.tagValue = TAG_SEE_VALUE;
- if (this.inlineTagStarted) {
- // bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=53290
- // Cannot have @see inside inline comment
- valid = false;
- } else {
- valid = parseReference();
- }
- } else {
- this.tagValue = TAG_OTHERS_VALUE;
- createTag();
- }
- break;
- case 'l':
- if (length == TAG_LINK_LENGTH && CharOperation.equals(TAG_LINK, tagName)) {
- this.tagValue = TAG_LINK_VALUE;
- }
- if (this.tagValue != NO_TAG_VALUE) {
- if (this.inlineTagStarted) {
- valid = parseReference();
- } else {
- // bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=53290
- // Cannot have @link outside inline comment
- valid = false;
- }
- } else {
- this.tagValue = TAG_OTHERS_VALUE;
- createTag();
- }
- break;
- case 'v':
- this.tagValue = TAG_OTHERS_VALUE;
- createTag();
-
- break;
- default:
- this.tagValue = TAG_OTHERS_VALUE;
- createTag();
- }
- break;
- case TerminalTokens.TokenNamereturn :
- this.tagValue = TAG_RETURN_VALUE;
- valid = parseReturn();
- break;
- case TerminalTokens.TokenNamethrows :
- this.tagValue = TAG_THROWS_VALUE;
- valid = parseThrows();
- break;
- case TerminalTokens.TokenNameabstract:
- case TerminalTokens.TokenNameboolean:
- case TerminalTokens.TokenNamebreak:
- case TerminalTokens.TokenNamebyte:
- case TerminalTokens.TokenNamecase:
- case TerminalTokens.TokenNamecatch:
- case TerminalTokens.TokenNamechar:
- case TerminalTokens.TokenNameclass:
- case TerminalTokens.TokenNamecontinue:
- case TerminalTokens.TokenNamedefault:
- case TerminalTokens.TokenNamedo:
- case TerminalTokens.TokenNamedouble:
- case TerminalTokens.TokenNameelse:
- case TerminalTokens.TokenNameextends:
- case TerminalTokens.TokenNamefalse:
- case TerminalTokens.TokenNamefinal:
- case TerminalTokens.TokenNamefinally:
- case TerminalTokens.TokenNamefloat:
- case TerminalTokens.TokenNamefor:
- case TerminalTokens.TokenNameif:
- case TerminalTokens.TokenNameimplements:
- case TerminalTokens.TokenNameimport:
- case TerminalTokens.TokenNameinstanceof:
- case TerminalTokens.TokenNameint:
- case TerminalTokens.TokenNameinterface:
- case TerminalTokens.TokenNamelong:
- case TerminalTokens.TokenNamenative:
- case TerminalTokens.TokenNamenew:
- case TerminalTokens.TokenNamenull:
- case TerminalTokens.TokenNamepackage:
- case TerminalTokens.TokenNameprivate:
- case TerminalTokens.TokenNameprotected:
- case TerminalTokens.TokenNamepublic:
- case TerminalTokens.TokenNameshort:
- case TerminalTokens.TokenNamestatic:
- case TerminalTokens.TokenNamesuper:
- case TerminalTokens.TokenNameswitch:
- case TerminalTokens.TokenNamesynchronized:
- case TerminalTokens.TokenNamethis:
- case TerminalTokens.TokenNamethrow:
- case TerminalTokens.TokenNametransient:
- case TerminalTokens.TokenNametrue:
- case TerminalTokens.TokenNametry:
- case TerminalTokens.TokenNamevoid:
- case TerminalTokens.TokenNamevolatile:
- case TerminalTokens.TokenNamewhile:
- case TerminalTokens.TokenNameundefined:
- this.tagValue = TAG_OTHERS_VALUE;
- createTag();
- break;
- }
- this.textStart = this.index;
- return valid;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.parser.AbstractCommentParser#pushParamName(java.lang.Object)
- */
- protected boolean pushParamName(boolean isTypeParam) {
- int idIndex = isTypeParam ? 1 : 0;
- final SimpleName name = new SimpleName(this.ast);
- name.internalSetIdentifier(new String(this.identifierStack[idIndex]));
- int nameStart = (int) (this.identifierPositionStack[idIndex] >>> 32);
- int nameEnd = (int) (this.identifierPositionStack[idIndex] & 0x00000000FFFFFFFFL);
- name.setSourceRange(nameStart, nameEnd-nameStart+1);
- TagElement paramTag = this.ast.newTagElement();
- paramTag.setTagName(TagElement.TAG_PARAM);
- if (isTypeParam) { // specific storage for @param <E> (see bug 79809)
- // '<' was stored in identifiers stack
- TextElement text = this.ast.newTextElement();
- text.setText(new String(this.identifierStack[0]));
- int txtStart = (int) (this.identifierPositionStack[0] >>> 32);
- int txtEnd = (int) (this.identifierPositionStack[0] & 0x00000000FFFFFFFFL);
- text.setSourceRange(txtStart, txtEnd-txtStart+1);
- paramTag.fragments().add(text);
- // add simple name
- paramTag.fragments().add(name);
- // '>' was stored in identifiers stack
- text = this.ast.newTextElement();
- text.setText(new String(this.identifierStack[2]));
- txtStart = (int) (this.identifierPositionStack[2] >>> 32);
- txtEnd = (int) (this.identifierPositionStack[2] & 0x00000000FFFFFFFFL);
- text.setSourceRange(txtStart, txtEnd-txtStart+1);
- paramTag.fragments().add(text);
- // set param tag source range
- paramTag.setSourceRange(this.tagSourceStart, txtEnd-this.tagSourceStart+1);
- } else {
- paramTag.setSourceRange(this.tagSourceStart, nameEnd-this.tagSourceStart+1);
- paramTag.fragments().add(name);
- }
- pushOnAstStack(paramTag, true);
- return true;
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.parser.AbstractCommentParser#pushSeeRef(java.lang.Object)
- */
- protected boolean pushSeeRef(Object statement) {
- TagElement seeTag = this.ast.newTagElement();
- ASTNode node = (ASTNode) statement;
- seeTag.fragments().add(node);
- int end = node.getStartPosition()+node.getLength()-1;
- if (this.inlineTagStarted) {
- seeTag.setSourceRange(this.inlineTagStart, end-this.inlineTagStart+1);
- switch (this.tagValue) {
- case TAG_LINK_VALUE:
- seeTag.setTagName(TagElement.TAG_LINK);
- break;
- }
- TagElement previousTag = null;
- int previousStart = this.inlineTagStart;
- if (this.astPtr == -1) {
- previousTag = this.ast.newTagElement();
- pushOnAstStack(previousTag, true);
- } else {
- previousTag = (TagElement) this.astStack[this.astPtr];
- previousStart = previousTag.getStartPosition();
- }
- previousTag.fragments().add(seeTag);
- previousTag.setSourceRange(previousStart, end-previousStart+1);
- } else {
- seeTag.setTagName(TagElement.TAG_SEE);
- seeTag.setSourceRange(this.tagSourceStart, end-this.tagSourceStart+1);
- pushOnAstStack(seeTag, true);
- }
- return true;
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.parser.AbstractCommentParser#pushText(int, int)
- */
- protected void pushText(int start, int end) {
- TextElement text = this.ast.newTextElement();
- text.setText(new String( this.source, start, end-start));
- text.setSourceRange(start, end-start);
- TagElement previousTag = null;
- int previousStart = start;
- if (this.astPtr == -1) {
- previousTag = this.ast.newTagElement();
- previousTag.setSourceRange(start, end-start);
- pushOnAstStack(previousTag, true);
- } else {
- previousTag = (TagElement) this.astStack[this.astPtr];
- previousStart = previousTag.getStartPosition();
- }
- if (this.inlineTagStarted) {
- if (previousTag.fragments().size() == 0) {
- TagElement inlineTag = this.ast.newTagElement();
- previousTag.fragments().add(inlineTag);
- previousTag = inlineTag;
- } else {
- ASTNode inlineTag = (ASTNode) previousTag.fragments().get(previousTag.fragments().size()-1);
- if (inlineTag.getNodeType() == ASTNode.TAG_ELEMENT) {
- previousTag = (TagElement) inlineTag;
- previousStart = previousTag.getStartPosition();
- }
- }
- }
- previousTag.fragments().add(text);
- previousTag.setSourceRange(previousStart, end-previousStart);
- this.textStart = -1;
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.parser.AbstractCommentParser#pushText(int, int)
- */
- protected void refreshInlineTagPosition(int previousPosition) {
- if (this.astPtr != -1) {
- TagElement previousTag = (TagElement) this.astStack[this.astPtr];
- if (this.inlineTagStarted) {
- int previousStart = previousTag.getStartPosition();
- previousTag.setSourceRange(previousStart, previousPosition-previousStart+1);
- if (previousTag.fragments().size() > 0) {
- ASTNode inlineTag = (ASTNode) previousTag.fragments().get(previousTag.fragments().size()-1);
- if (inlineTag.getNodeType() == ASTNode.TAG_ELEMENT) {
- int inlineStart = inlineTag.getStartPosition();
- inlineTag.setSourceRange(inlineStart, previousPosition-inlineStart+1);
- }
- }
- }
- }
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.parser.AbstractCommentParser#pushThrowName(java.lang.Object)
- */
- protected boolean pushThrowName(Object typeRef) {
- TagElement throwsTag = this.ast.newTagElement();
- switch (this.tagValue) {
- case TAG_THROWS_VALUE:
- throwsTag.setTagName(TagElement.TAG_THROWS);
- break;
- case TAG_EXCEPTION_VALUE:
- throwsTag.setTagName(TagElement.TAG_EXCEPTION);
- break;
- }
- throwsTag.setSourceRange(this.tagSourceStart, this.scanner.getCurrentTokenEndPosition()-this.tagSourceStart+1);
- throwsTag.fragments().add(typeRef);
- pushOnAstStack(throwsTag, true);
- return true;
- }
-
- /*
- * Add stored tag elements to associated comment.
- */
- protected void updateDocComment() {
- for (int idx = 0; idx <= this.astPtr; idx++) {
- this.docComment.tags().add(this.astStack[idx]);
- }
- }
-
-
- protected void createParamType(Object[] typeReference) {
- TagElement nameRef=(TagElement)this.astStack[this.astPtr];
- Name [] refs=null;
- if (typeReference!=null)
- {
- refs = new Name[typeReference.length];
- System.arraycopy(typeReference, 0, refs, 0, typeReference.length);
- nameRef.fragments().add(refs[0]);
- }
-
- }
-}
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
deleted file mode 100644
index 338709f9..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/EmptyExpression.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-/**
- *
- * 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 EmptyExpression extends Expression {
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List properyList = new ArrayList(1);
- createPropertyList(EmptyStatement.class, properyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
-
- EmptyExpression(AST ast) {
- super(ast);
- }
-
- void accept0(ASTVisitor visitor) {
-
- }
-
- ASTNode clone0(AST target) {
- EmptyExpression result = new EmptyExpression(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- return result;
- }
-
- int getNodeType0() {
- return EMPTY_EXPRESSION;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- int memSize() {
- return BASE_NODE_SIZE + 1 * 4;
- }
-
- boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- return this.equals(other);
- }
-
- int treeSize() {
- // TODO Auto-generated method stub
- return memSize();
- }
-
-}
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
deleted file mode 100644
index ffe4d35b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/EmptyStatement.java
+++ /dev/null
@@ -1,119 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Null statement AST node type.
- *
- * <pre>
- * EmptyStatement:
- * <b>;</b>
- * </pre>
- *
- * 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 EmptyStatement extends Statement {
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List properyList = new ArrayList(1);
- createPropertyList(EmptyStatement.class, properyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * Creates a new unparented null statement node owned by the given AST.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- EmptyStatement(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return EMPTY_STATEMENT;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- EmptyStatement result = new EmptyStatement(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.copyLeadingComment(this);
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- visitor.visit(this);
- visitor.endVisit(this);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return memSize();
- }
-}
-
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
deleted file mode 100644
index 2b0de6ab..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/EnhancedForStatement.java
+++ /dev/null
@@ -1,331 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Enhanced For statement AST node type (added in JLS3 API).
- *
- * <pre>
- * EnhancedForStatement:
- * <b>for</b> <b>(</b> FormalParameter <b>:</b> Expression <b>)</b>
- * Statement
- * </pre>
- * The FormalParameter is represented by a <code>SingleVariableDeclaration</code>
- * (without an initializer).
- *
- * 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 EnhancedForStatement extends Statement {
-
- /**
- * The "parameter" structural property of this node type.
- */
- public static final ChildPropertyDescriptor PARAMETER_PROPERTY =
- new ChildPropertyDescriptor(EnhancedForStatement.class, "parameter", SingleVariableDeclaration.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "expression" structural property of this node type.
- */
- public static final ChildPropertyDescriptor EXPRESSION_PROPERTY =
- new ChildPropertyDescriptor(EnhancedForStatement.class, "expression", Expression.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "body" structural property of this node type.
- */
- public static final ChildPropertyDescriptor BODY_PROPERTY =
- new ChildPropertyDescriptor(EnhancedForStatement.class, "body", Statement.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List properyList = new ArrayList(4);
- createPropertyList(EnhancedForStatement.class, properyList);
- addProperty(PARAMETER_PROPERTY, properyList);
- addProperty(EXPRESSION_PROPERTY, properyList);
- addProperty(BODY_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The parameter; lazily initialized; defaults to a unspecified,
- * legal node.
- */
- private SingleVariableDeclaration parameter = null;
-
- /**
- * The expression; lazily initialized; defaults to a unspecified, but legal,
- * expression.
- */
- private Expression expression = null;
-
- /**
- * The body statement; lazily initialized; defaults to an empty block
- * statement.
- */
- private Statement body = null;
-
- /**
- * Creates a new AST node for an enchanced for statement owned by the
- * given AST. By default, the parameter and expression are unspecified
- * but legal subtrees, and the body is an empty block.
- *
- * @param ast the AST that is to own this node
- */
- EnhancedForStatement(AST ast) {
- super(ast);
- unsupportedIn2();
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == PARAMETER_PROPERTY) {
- if (get) {
- return getParameter();
- } else {
- setParameter((SingleVariableDeclaration) child);
- return null;
- }
- }
- if (property == EXPRESSION_PROPERTY) {
- if (get) {
- return getExpression();
- } else {
- setExpression((Expression) child);
- return null;
- }
- }
- if (property == BODY_PROPERTY) {
- if (get) {
- return getBody();
- } else {
- setBody((Statement) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return ENHANCED_FOR_STATEMENT;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- EnhancedForStatement result = new EnhancedForStatement(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.copyLeadingComment(this);
- result.setParameter((SingleVariableDeclaration) getParameter().clone(target));
- result.setExpression((Expression) getExpression().clone(target));
- result.setBody(
- (Statement) ASTNode.copySubtree(target, getBody()));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChild(visitor, getParameter());
- acceptChild(visitor, getExpression());
- acceptChild(visitor, getBody());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the formal parameter in this enhanced for statement.
- *
- * @return the parameter
- */
- public SingleVariableDeclaration getParameter() {
- if (this.parameter == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.parameter == null) {
- preLazyInit();
- this.parameter = this.ast.newSingleVariableDeclaration();
- postLazyInit(this.parameter, PARAMETER_PROPERTY);
- }
- }
- }
- return this.parameter;
- }
-
- /**
- * Sets the formal parameter in this enhanced for statement.
- *
- * @param parameter the new parameter
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public void setParameter(SingleVariableDeclaration parameter) {
- if (parameter == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.parameter;
- preReplaceChild(oldChild, parameter, PARAMETER_PROPERTY);
- this.parameter = parameter;
- postReplaceChild(oldChild, parameter, PARAMETER_PROPERTY);
- }
-
- /**
- * Returns the expression of this enhanced for statement.
- *
- * @return the expression node
- */
- public Expression getExpression() {
- if (this.expression == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.expression == null) {
- preLazyInit();
- this.expression = new SimpleName(this.ast);
- postLazyInit(this.expression, EXPRESSION_PROPERTY);
- }
- }
- }
- return this.expression;
- }
-
- /**
- * Sets the expression of this enhanced for statement.
- *
- * @param expression the new expression node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setExpression(Expression expression) {
- if (expression == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.expression;
- preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY);
- this.expression = expression;
- postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY);
- }
-
- /**
- * Returns the body of this enchanced for statement.
- *
- * @return the body statement node
- */
- public Statement getBody() {
- if (this.body == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.body == null) {
- preLazyInit();
- this.body = new Block(this.ast);
- postLazyInit(this.body, BODY_PROPERTY);
- }
- }
- }
- return this.body;
- }
-
- /**
- * Sets the body of this enhanced for statement.
- *
- * @param statement the body statement node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setBody(Statement statement) {
- if (statement == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.body;
- preReplaceChild(oldChild, statement, BODY_PROPERTY);
- this.body = statement;
- postReplaceChild(oldChild, statement, BODY_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return super.memSize() + 3 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.parameter == null ? 0 : getParameter().treeSize())
- + (this.expression == null ? 0 : getExpression().treeSize())
- + (this.body == null ? 0 : getBody().treeSize());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Expression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Expression.java
deleted file mode 100644
index dec8b37e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Expression.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-/**
- * Abstract base class of AST nodes that represent expressions.
- * There are several kinds of expressions.
- * <p>
- * <pre>
- * Expression:
- * Name
- * IntegerLiteral (includes decimal, hex, and octal forms; and long)
- * FloatingPointLiteral (includes both float and double)
- * CharacterLiteral
- * NullLiteral
- * BooleanLiteral
- * StringLiteral
- * TypeLiteral
- * ThisExpression
- * SuperFieldAccess
- * FieldAccess
- * Assignment
- * ParenthesizedExpression
- * ClassInstanceCreation
- * ArrayCreation
- * ArrayInitializer
- * FunctionInvocation
- * SuperMethodInvocation
- * ArrayAccess
- * InfixExpression
- * InstanceofExpression
- * ConditionalExpression
- * PostfixExpression
- * PrefixExpression
- * CastExpression
- * VariableDeclarationExpression
- * </pre>
- * </p>
- *
- * 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 Expression extends ASTNode {
-
- /**
- * Creates a new AST node for an expression owned by the given AST.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- Expression(AST ast) {
- super(ast);
- }
-
- /**
- * Resolves and returns the compile-time constant expression value as
- * specified in JLS2 15.28, if this expression has one. Constant expression
- * values are unavailable unless bindings are requested when the AST is
- * being built. If the type of the value is a primitive type, the result
- * is the boxed equivalent (i.e., int returned as an <code>Integer</code>);
- * if the type of the value is <code>String</code>, the result is the string
- * itself. If the expression does not have a compile-time constant expression
- * value, the result is <code>null</code>.
- * <p>
- * Resolving constant expressions takes into account the value of simple
- * and qualified names that refer to constant variables (JLS2 4.12.4).
- * </p>
- * <p>
- * Note 1: enum constants are not considered constant expressions.
- * The result is always <code>null</code> for these.
- * </p>
- * <p>
- * Note 2: Compile-time constant expressions cannot denote <code>null</code>.
- * So technically {@link NullLiteral} nodes are not constant expressions.
- * The result is <code>null</code> for these nonetheless.
- * </p>
- *
- * @return the constant expression value, or <code>null</code> if this
- * expression has no constant expression value or if bindings were not
- * requested when the AST was created
- *
- */
- public final Object resolveConstantExpressionValue() {
- return this.ast.getBindingResolver().resolveConstantExpressionValue(this);
- }
-
- /**
- * Resolves and returns the binding for the type of this expression.
- * <p>
- * Note that bindings are generally unavailable unless requested when the
- * AST is being built.
- * </p>
- *
- * @return the binding for the type of this expression, or
- * <code>null</code> if the type cannot be resolved
- */
- public final ITypeBinding resolveTypeBinding() {
- return this.ast.getBindingResolver().resolveExpressionType(this);
- }
-
- /**
- * Returns whether this expression node is the site of a boxing
- * conversion (JLS3 5.1.7). This information is available only
- * when bindings are requested when the AST is being built.
- *
- * @return <code>true</code> if this expression is the site of a
- * boxing conversion, or <code>false</code> if either no boxing conversion
- * is involved or if bindings were not requested when the AST was created
- *
- */
- public final boolean resolveBoxing() {
- return this.ast.getBindingResolver().resolveBoxing(this);
- }
-
- /**
- * Returns whether this expression node is the site of an unboxing
- * conversion (JLS3 5.1.8). This information is available only
- * when bindings are requested when the AST is being built.
- *
- * @return <code>true</code> if this expression is the site of an
- * unboxing conversion, or <code>false</code> if either no unboxing
- * conversion is involved or if bindings were not requested when the
- * AST was created
- *
- */
- public final boolean resolveUnboxing() {
- return this.ast.getBindingResolver().resolveUnboxing(this);
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ExpressionStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ExpressionStatement.java
deleted file mode 100644
index d11e4a5c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ExpressionStatement.java
+++ /dev/null
@@ -1,207 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Expression statement AST node type.
- * <p>
- * This kind of node is used to convert an expression (<code>Expression</code>)
- * into a statement (<code>Statement</code>) by wrapping it.
- * </p>
- * <pre>
- * ExpressionStatement:
- * StatementExpression <b>;</b>
- * </pre>
- *
- * 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 ExpressionStatement extends Statement {
-
- /**
- * The "expression" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor EXPRESSION_PROPERTY =
- new ChildPropertyDescriptor(ExpressionStatement.class, "expression", Expression.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List properyList = new ArrayList(2);
- createPropertyList(ExpressionStatement.class, properyList);
- addProperty(EXPRESSION_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The expression; lazily initialized; defaults to a unspecified, but legal,
- * expression.
- */
- private Expression expression = null;
-
- /**
- * Creates a new unparented expression statement node owned by the given
- * AST. By default, the expression statement is unspecified, but legal,
- * method invocation expression.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- ExpressionStatement(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == EXPRESSION_PROPERTY) {
- if (get) {
- return getExpression();
- } else {
- setExpression((Expression) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return EXPRESSION_STATEMENT;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- ExpressionStatement result = new ExpressionStatement(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.copyLeadingComment(this);
- result.setExpression((Expression) getExpression().clone(target));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- acceptChild(visitor, getExpression());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the expression of this expression statement.
- *
- * @return the expression node
- */
- public Expression getExpression() {
- if (this.expression == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.expression == null) {
- preLazyInit();
- this.expression = new FunctionInvocation(this.ast);
- postLazyInit(this.expression, EXPRESSION_PROPERTY);
- }
- }
- }
- return this.expression;
- }
-
- /**
- * Sets the expression of this expression statement.
- *
- * @param expression the new expression node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setExpression(Expression expression) {
- if (expression == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.expression;
- preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY);
- this.expression = expression;
- postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return super.memSize() + 1 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.expression == null ? 0 : getExpression().treeSize());
- }
-}
-
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
deleted file mode 100644
index 030b69ac..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FieldAccess.java
+++ /dev/null
@@ -1,316 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Field access expression AST node type.
- *
- * <pre>
- * FieldAccess:
- * Expression <b>.</b> Identifier
- * </pre>
- *
- * <p>
- * Note that there are several kinds of expressions that resemble field access
- * expressions: qualified names, this expressions, and super field access
- * expressions. The following guidelines help with correct usage:
- * <ul>
- * <li>An expression like "foo.this" can only be represented as a this
- * expression (<code>ThisExpression</code>) containing a simple name.
- * "this" is a keyword, and therefore invalid as an identifier.</li>
- * <li>An expression like "this.foo" can only be represented as a field
- * access expression (<code>FieldAccess</code>) containing a this expression
- * and a simple name. Again, this is because "this" is a keyword, and
- * therefore invalid as an identifier.</li>
- * <li>An expression with "super" can only be represented as a super field
- * access expression (<code>SuperFieldAccess</code>). "super" is a also
- * keyword, and therefore invalid as an identifier.</li>
- * <li>An expression like "foo.bar" can be represented either as a
- * qualified name (<code>QualifiedName</code>) or as a field access
- * expression (<code>FieldAccess</code>) containing simple names. Either
- * is acceptable, and there is no way to choose between them without
- * information about what the names resolve to
- * (<code>ASTParser</code> may return either).</li>
- * <li>Other expressions ending in an identifier, such as "foo().bar" can
- * only be represented as field access expressions
- * (<code>FieldAccess</code>).</li>
- * </ul>
- * </p>
- *
- * @see QualifiedName
- * @see ThisExpression
- * @see SuperFieldAccess
- *
- * 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 FieldAccess extends Expression {
-
- /**
- * The "expression" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor EXPRESSION_PROPERTY =
- new ChildPropertyDescriptor(FieldAccess.class, "expression", Expression.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "name" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor NAME_PROPERTY =
- new ChildPropertyDescriptor(FieldAccess.class, "name", SimpleName.class, MANDATORY, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List properyList = new ArrayList(3);
- createPropertyList(FieldAccess.class, properyList);
- addProperty(EXPRESSION_PROPERTY, properyList);
- addProperty(NAME_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The expression; lazily initialized; defaults to an unspecified,
- * but legal, simple name.
- */
- private Expression expression = null;
-
- /**
- * The field; lazily initialized; defaults to an unspecified,
- * but legal, simple field name.
- */
- private SimpleName fieldName = null;
-
- /**
- * Creates a new unparented node for a field access expression owned by the
- * given AST. By default, the expression and field are both unspecified,
- * but legal, names.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- FieldAccess(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == EXPRESSION_PROPERTY) {
- if (get) {
- return getExpression();
- } else {
- setExpression((Expression) child);
- return null;
- }
- }
- if (property == NAME_PROPERTY) {
- if (get) {
- return getName();
- } else {
- setName((SimpleName) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return FIELD_ACCESS;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- FieldAccess result = new FieldAccess(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setExpression((Expression) getExpression().clone(target));
- result.setName((SimpleName) getName().clone(target));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChild(visitor, getExpression());
- acceptChild(visitor, getName());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the expression of this field access expression.
- *
- * @return the expression node
- */
- public Expression getExpression() {
- if (this.expression == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.expression == null) {
- preLazyInit();
- this.expression = new SimpleName(this.ast);
- postLazyInit(this.expression, EXPRESSION_PROPERTY);
- }
- }
- }
- return this.expression;
- }
-
- /**
- * Sets the expression of this field access expression.
- *
- * @param expression the new expression
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setExpression(Expression expression) {
- if (expression == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.expression;
- preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY);
- this.expression = expression;
- postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY);
- }
-
- /**
- * Returns the name of the field accessed in this field access expression.
- *
- * @return the field name
- */
- public SimpleName getName() {
- if (this.fieldName == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.fieldName == null) {
- preLazyInit();
- this.fieldName = new SimpleName(this.ast);
- postLazyInit(this.fieldName, NAME_PROPERTY);
- }
- }
- }
- return this.fieldName;
- }
-
- /**
- * Sets the name of the field accessed in this field access expression.
- *
- * @param fieldName the field name
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public void setName(SimpleName fieldName) {
- if (fieldName == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.fieldName;
- preReplaceChild(oldChild, fieldName, NAME_PROPERTY);
- this.fieldName = fieldName;
- postReplaceChild(oldChild, fieldName, NAME_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- // treat Code as free
- return BASE_NODE_SIZE + 2 * 4;
- }
-
- /**
- * Resolves and returns the binding for the field accessed by this
- * expression.
- * <p>
- * Note that bindings are generally unavailable unless requested when the
- * AST is being built.
- * </p>
- *
- * @return the variable binding, or <code>null</code> if the binding cannot
- * be resolved
- *
- */
- public IVariableBinding resolveFieldBinding() {
- return this.ast.getBindingResolver().resolveField(this);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.expression == null ? 0 : getExpression().treeSize())
- + (this.fieldName == null ? 0 : getName().treeSize());
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FieldDeclaration.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FieldDeclaration.java
deleted file mode 100644
index 5196b647..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FieldDeclaration.java
+++ /dev/null
@@ -1,372 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Field declaration node type.
- * <p>
- * This kind of node collects several variable declaration fragments
- * (<code>VariableDeclarationFragment</code>) into a single body declaration
- * (<code>BodyDeclaration</code>), all sharing the same modifiers and base type.
- * </p>
- * <pre>
- * FieldDeclaration:
- * [Javadoc] { ExtendedModifier } Type VariableDeclarationFragment
- * { <b>,</b> VariableDeclarationFragment } <b>;</b>
- * </pre>
- * <p>
- * When a jsdoc comment is present, the source range begins with the first
- * character of the "/**" comment delimiter. When there is no jsdoc comment,
- * the source range begins with the first character of the initial modifier or
- * type. The source range extends through the last character of the final ";".
- * </p>
- *
- * <p><b>Note: This Class only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * 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 FieldDeclaration extends BodyDeclaration {
-
- /**
- * The "javadoc" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor JAVADOC_PROPERTY =
- internalJavadocPropertyFactory(FieldDeclaration.class);
-
- /**
- * The "modifiers" structural property of this node type (JLS2 API only).
- *
- */
- public static final SimplePropertyDescriptor MODIFIERS_PROPERTY =
- internalModifiersPropertyFactory(FieldDeclaration.class);
-
- /**
- * The "modifiers" structural property of this node type (added in JLS3 API).
- *
- */
- public static final ChildListPropertyDescriptor MODIFIERS2_PROPERTY =
- internalModifiers2PropertyFactory(FieldDeclaration.class);
-
- /**
- * The "type" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor TYPE_PROPERTY =
- new ChildPropertyDescriptor(FieldDeclaration.class, "type", Type.class, MANDATORY, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "fragments" structural property of this node type).
- *
- */
- public static final ChildListPropertyDescriptor FRAGMENTS_PROPERTY =
- new ChildListPropertyDescriptor(FieldDeclaration.class, "fragments", VariableDeclarationFragment.class, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS_2_0;
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS_3_0;
-
- static {
- List properyList = new ArrayList(5);
- createPropertyList(FieldDeclaration.class, properyList);
- addProperty(JAVADOC_PROPERTY, properyList);
- addProperty(MODIFIERS_PROPERTY, properyList);
- addProperty(TYPE_PROPERTY, properyList);
- addProperty(FRAGMENTS_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS_2_0 = reapPropertyList(properyList);
-
- properyList = new ArrayList(5);
- createPropertyList(FieldDeclaration.class, properyList);
- addProperty(JAVADOC_PROPERTY, properyList);
- addProperty(MODIFIERS2_PROPERTY, properyList);
- addProperty(TYPE_PROPERTY, properyList);
- addProperty(FRAGMENTS_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS_3_0 = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- if (apiLevel == AST.JLS2_INTERNAL) {
- return PROPERTY_DESCRIPTORS_2_0;
- } else {
- return PROPERTY_DESCRIPTORS_3_0;
- }
- }
-
- /**
- * The base type; lazily initialized; defaults to an unspecified,
- * legal type.
- */
- private Type baseType = null;
-
- /**
- * The list of variable declaration fragments (element type:
- * <code VariableDeclarationFragment</code>). Defaults to an empty list.
- */
- private ASTNode.NodeList variableDeclarationFragments =
- new ASTNode.NodeList(FRAGMENTS_PROPERTY);
-
- /**
- * Creates a new unparented field declaration statement node owned
- * by the given AST. By default, the field declaration has: no modifiers,
- * an unspecified (but legal) type, and an empty list of variable
- * declaration fragments (which is syntactically illegal).
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- FieldDeclaration(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- *
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int internalGetSetIntProperty(SimplePropertyDescriptor property, boolean get, int value) {
- if (property == MODIFIERS_PROPERTY) {
- if (get) {
- return getModifiers();
- } else {
- internalSetModifiers(value);
- return 0;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetIntProperty(property, get, value);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == JAVADOC_PROPERTY) {
- if (get) {
- return getJavadoc();
- } else {
- setJavadoc((JSdoc) child);
- return null;
- }
- }
- if (property == TYPE_PROPERTY) {
- if (get) {
- return getType();
- } else {
- setType((Type) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalGetChildListProperty(ChildListPropertyDescriptor property) {
- if (property == MODIFIERS2_PROPERTY) {
- return modifiers();
- }
- if (property == FRAGMENTS_PROPERTY) {
- return fragments();
- }
- // allow default implementation to flag the error
- return super.internalGetChildListProperty(property);
- }
-
- /* (omit javadoc for this method)
- * Method declared on BodyDeclaration.
- */
- final ChildPropertyDescriptor internalJavadocProperty() {
- return JAVADOC_PROPERTY;
- }
-
- /* (omit javadoc for this method)
- * Method declared on BodyDeclaration.
- */
- final SimplePropertyDescriptor internalModifiersProperty() {
- return MODIFIERS_PROPERTY;
- }
-
- /* (omit javadoc for this method)
- * Method declared on BodyDeclaration.
- */
- final ChildListPropertyDescriptor internalModifiers2Property() {
- return MODIFIERS2_PROPERTY;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return FIELD_DECLARATION;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- FieldDeclaration result = new FieldDeclaration(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setJavadoc(
- (JSdoc) ASTNode.copySubtree(target, getJavadoc()));
- if (this.ast.apiLevel == AST.JLS2_INTERNAL) {
- result.internalSetModifiers(getModifiers());
- }
- if (this.ast.apiLevel >= AST.JLS3) {
- result.modifiers().addAll(ASTNode.copySubtrees(target, modifiers()));
- }
- result.setType((Type) getType().clone(target));
- result.fragments().addAll(
- ASTNode.copySubtrees(target, fragments()));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChild(visitor, getJavadoc());
- if (this.ast.apiLevel >= AST.JLS3) {
- acceptChildren(visitor, this.modifiers);
- }
- acceptChild(visitor, getType());
- acceptChildren(visitor, this.variableDeclarationFragments);
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the base type declared in this field declaration.
- * <p>
- * N.B. The individual child variable declaration fragments may specify
- * additional array dimensions. So the type of the variable are not
- * necessarily exactly this type.
- * </p>
- *
- * @return the base type
- */
- public Type getType() {
- if (this.baseType == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.baseType == null) {
- preLazyInit();
- this.baseType = this.ast.newInferredType(null);
- postLazyInit(this.baseType, TYPE_PROPERTY);
- }
- }
- }
- return this.baseType;
- }
-
- /**
- * Sets the base type declared in this field declaration to the given type.
- *
- * @param type the new base type
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public void setType(Type type) {
- if (type == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.baseType;
- preReplaceChild(oldChild, type, TYPE_PROPERTY);
- this.baseType = type;
- postReplaceChild(oldChild, type, TYPE_PROPERTY);
- }
-
- /**
- * Returns the live list of variable declaration fragments in this field
- * declaration. Adding and removing nodes from this list affects this node
- * dynamically. All nodes in this list must be
- * <code>VariableDeclarationFragment</code>s; attempts to add any other
- * type of node will trigger an exception.
- *
- * @return the live list of variable declaration fragments in this
- * statement (element type: <code>VariableDeclarationFragment</code>)
- */
- public List fragments() {
- return this.variableDeclarationFragments;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return super.memSize() + 2 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.optionalDocComment == null ? 0 : getJavadoc().treeSize())
- + (this.modifiers == null ? 0 : this.modifiers.listSize())
- + (this.baseType == null ? 0 : getType().treeSize())
- + this.variableDeclarationFragments.listSize();
- }
-}
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
deleted file mode 100644
index 67063f7b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ForInStatement.java
+++ /dev/null
@@ -1,331 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-
-/**
- * For statement AST node type.
- *
- * <pre>
- * ForStatement:
- * <b>for</b> <b>(</b>
- * [ ForInit ]<b>;</b>
- * [ Expression ] <b>;</b>
- * [ ForUpdate ] <b>)</b>
- * Statement
- * ForInit:
- * Expression { <b>,</b> Expression }
- * ForUpdate:
- * Expression { <b>,</b> Expression }
- * </pre>
- * <p>
- * Note: When variables are declared in the initializer
- * of a for statement such as "<code>for (int a=1, b=2;;);</code>",
- * they should be represented as a single
- * <code>VariableDeclarationExpression</code>
- * with two fragments, rather than being split up into a pair
- * of expressions.
- * </p>
- *
- * 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 ForInStatement extends Statement {
-
- /**
- * The "initializers" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor ITERATION_VARIABLE_PROPERTY =
- new ChildPropertyDescriptor(ForInStatement.class, "iterationVariable", Statement.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "expression" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor COLLECTION_PROPERTY =
- new ChildPropertyDescriptor(ForInStatement.class, "collection", Expression.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
-
- /**
- * The "body" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor BODY_PROPERTY =
- new ChildPropertyDescriptor(ForInStatement.class, "body", Statement.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List properyList = new ArrayList(5);
- createPropertyList(ForInStatement.class, properyList);
- addProperty(ITERATION_VARIABLE_PROPERTY, properyList);
- addProperty(COLLECTION_PROPERTY, properyList);
- addProperty(BODY_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- private Statement iterationVariable = null;
-
- private Expression collection = null;
-
-
- /**
- * The body statement; lazily initialized; defaults to an empty block
- * statement.
- */
- private Statement body = null;
-
- /**
- * Creates a new AST node for a for statement owned by the given AST.
- * By default, there are no initializers, no condition expression,
- * no updaters, and the body is an empty block.
- *
- * @param ast the AST that is to own this node
- */
- ForInStatement(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == ITERATION_VARIABLE_PROPERTY) {
- if (get) {
- return getIterationVariable();
- } else {
- setIterationVariable((Statement) child);
- return null;
- }
- }
- if (property == COLLECTION_PROPERTY) {
- if (get) {
- return getCollection();
- } else {
- setCollection((Expression) child);
- return null;
- }
- }
- if (property == BODY_PROPERTY) {
- if (get) {
- return getBody();
- } else {
- setBody((Statement) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
-// final List internalGetChildListProperty(ChildListPropertyDescriptor property) {
-// if (property == INITIALIZERS_PROPERTY) {
-// return initializers();
-// }
-// if (property == UPDATERS_PROPERTY) {
-// return updaters();
-// }
-// // allow default implementation to flag the error
-// return super.internalGetChildListProperty(property);
-// }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return FOR_IN_STATEMENT;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- ForInStatement result = new ForInStatement(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.copyLeadingComment(this);
- result.setIterationVariable(
- (Statement) ASTNode.copySubtree(target, getIterationVariable()));
- result.setCollection(
- (Expression) ASTNode.copySubtree(target, getCollection()));
- result.setBody(
- (Statement) ASTNode.copySubtree(target, getBody()));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChild(visitor, this.iterationVariable);
- acceptChild(visitor, getCollection());
- acceptChild(visitor, getBody());
- }
- visitor.endVisit(this);
- }
-
-
- /**
- * Returns the condition expression of this for statement, or
- * <code>null</code> if there is none.
- *
- * @return the condition expression node, or <code>null</code> if
- * there is none
- */
- public Expression getCollection() {
- return this.collection;
- }
-
- public Statement getIterationVariable() {
- return this.iterationVariable;
- }
-
- /**
- * Sets or clears the condition expression of this return statement.
- *
- * @param expression the condition expression node, or <code>null</code>
- * if there is none
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setCollection(Expression expression) {
- ASTNode oldChild = this.collection;
- preReplaceChild(oldChild, expression, COLLECTION_PROPERTY);
- this.collection = expression;
- postReplaceChild(oldChild, expression, COLLECTION_PROPERTY);
- }
-
- public void setIterationVariable(Statement statement) {
- ASTNode oldChild = this.iterationVariable;
- preReplaceChild(oldChild, statement, ITERATION_VARIABLE_PROPERTY);
- this.iterationVariable = statement;
- postReplaceChild(oldChild, statement, ITERATION_VARIABLE_PROPERTY);
- }
-
-
- /**
- * Returns the body of this for statement.
- *
- * @return the body statement node
- */
- public Statement getBody() {
- if (this.body == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.body == null) {
- preLazyInit();
- this.body = new Block(this.ast);
- postLazyInit(this.body, BODY_PROPERTY);
- }
- }
- }
- return this.body;
- }
-
- /**
- * Sets the body of this for statement.
- * <p>
- * Special note: The JavaScript language does not allow a local variable declaration
- * to appear as the body of a for statement (they may only appear within a
- * block). However, the AST will allow a <code>VariableDeclarationStatement</code>
- * as the body of a <code>ForStatement</code>. To get something that will
- * compile, be sure to embed the <code>VariableDeclarationStatement</code>
- * inside a <code>Block</code>.
- * </p>
- *
- * @param statement the body statement node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setBody(Statement statement) {
- if (statement == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.body;
- preReplaceChild(oldChild, statement, BODY_PROPERTY);
- this.body = statement;
- postReplaceChild(oldChild, statement, BODY_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return super.memSize() + 4 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + getIterationVariable().treeSize()
- + getCollection().treeSize()
- + (this.body == null ? 0 : getBody().treeSize());
- }
-}
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
deleted file mode 100644
index 083387a6..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ForStatement.java
+++ /dev/null
@@ -1,363 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * For statement AST node type.
- *
- * <pre>
- * ForStatement:
- * <b>for</b> <b>(</b>
- * [ ForInit ]<b>;</b>
- * [ Expression ] <b>;</b>
- * [ ForUpdate ] <b>)</b>
- * Statement
- * ForInit:
- * Expression { <b>,</b> Expression }
- * ForUpdate:
- * Expression { <b>,</b> Expression }
- * </pre>
- * <p>
- * Note: When variables are declared in the initializer
- * of a for statement such as "<code>for (int a=1, b=2;;);</code>",
- * they should be represented as a single
- * <code>VariableDeclarationExpression</code>
- * with two fragments, rather than being split up into a pair
- * of expressions.
- * </p>
- *
- * 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 ForStatement extends Statement {
-
- /**
- * The "initializers" structural property of this node type.
- *
- */
- public static final ChildListPropertyDescriptor INITIALIZERS_PROPERTY =
- new ChildListPropertyDescriptor(ForStatement.class, "initializers", Expression.class, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "expression" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor EXPRESSION_PROPERTY =
- new ChildPropertyDescriptor(ForStatement.class, "expression", Expression.class, OPTIONAL, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "updaters" structural property of this node type.
- *
- */
- public static final ChildListPropertyDescriptor UPDATERS_PROPERTY =
- new ChildListPropertyDescriptor(ForStatement.class, "updaters", Expression.class, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "body" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor BODY_PROPERTY =
- new ChildPropertyDescriptor(ForStatement.class, "body", Statement.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List properyList = new ArrayList(5);
- createPropertyList(ForStatement.class, properyList);
- addProperty(INITIALIZERS_PROPERTY, properyList);
- addProperty(EXPRESSION_PROPERTY, properyList);
- addProperty(UPDATERS_PROPERTY, properyList);
- addProperty(BODY_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The list of initializer expressions (element type:
- * <code>Expression</code>). Defaults to an empty list.
- */
- private ASTNode.NodeList initializers =
- new ASTNode.NodeList(INITIALIZERS_PROPERTY);
-
- /**
- * The condition expression; <code>null</code> for none; defaults to none.
- */
- private Expression optionalConditionExpression = null;
-
- /**
- * The list of update expressions (element type:
- * <code>Expression</code>). Defaults to an empty list.
- */
- private ASTNode.NodeList updaters =
- new ASTNode.NodeList(UPDATERS_PROPERTY);
-
- /**
- * The body statement; lazily initialized; defaults to an empty block
- * statement.
- */
- private Statement body = null;
-
- /**
- * Creates a new AST node for a for statement owned by the given AST.
- * By default, there are no initializers, no condition expression,
- * no updaters, and the body is an empty block.
- *
- * @param ast the AST that is to own this node
- */
- ForStatement(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == EXPRESSION_PROPERTY) {
- if (get) {
- return getExpression();
- } else {
- setExpression((Expression) child);
- return null;
- }
- }
- if (property == BODY_PROPERTY) {
- if (get) {
- return getBody();
- } else {
- setBody((Statement) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalGetChildListProperty(ChildListPropertyDescriptor property) {
- if (property == INITIALIZERS_PROPERTY) {
- return initializers();
- }
- if (property == UPDATERS_PROPERTY) {
- return updaters();
- }
- // allow default implementation to flag the error
- return super.internalGetChildListProperty(property);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return FOR_STATEMENT;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- ForStatement result = new ForStatement(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.copyLeadingComment(this);
- result.initializers().addAll(ASTNode.copySubtrees(target, initializers()));
- result.setExpression(
- (Expression) ASTNode.copySubtree(target, getExpression()));
- result.updaters().addAll(ASTNode.copySubtrees(target, updaters()));
- result.setBody(
- (Statement) ASTNode.copySubtree(target, getBody()));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChildren(visitor, this.initializers);
- acceptChild(visitor, getExpression());
- acceptChildren(visitor, this.updaters);
- acceptChild(visitor, getBody());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the live ordered list of initializer expressions in this for
- * statement.
- * <p>
- * The list should consist of either a list of so called statement
- * expressions (JLS2, 14.8), or a single <code>VariableDeclarationExpression</code>.
- * Otherwise, the for statement would have no JavaScript source equivalent.
- * </p>
- *
- * @return the live list of initializer expressions
- * (element type: <code>Expression</code>)
- */
- public List initializers() {
- return this.initializers;
- }
-
- /**
- * Returns the condition expression of this for statement, or
- * <code>null</code> if there is none.
- *
- * @return the condition expression node, or <code>null</code> if
- * there is none
- */
- public Expression getExpression() {
- return this.optionalConditionExpression;
- }
-
- /**
- * Sets or clears the condition expression of this return statement.
- *
- * @param expression the condition expression node, or <code>null</code>
- * if there is none
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setExpression(Expression expression) {
- ASTNode oldChild = this.optionalConditionExpression;
- preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY);
- this.optionalConditionExpression = expression;
- postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY);
- }
-
- /**
- * Returns the live ordered list of update expressions in this for
- * statement.
- * <p>
- * The list should consist of so called statement expressions. Otherwise,
- * the for statement would have no JavaScript source equivalent.
- * </p>
- *
- * @return the live list of update expressions
- * (element type: <code>Expression</code>)
- */
- public List updaters() {
- return this.updaters;
- }
-
- /**
- * Returns the body of this for statement.
- *
- * @return the body statement node
- */
- public Statement getBody() {
- if (this.body == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.body == null) {
- preLazyInit();
- this.body = new Block(this.ast);
- postLazyInit(this.body, BODY_PROPERTY);
- }
- }
- }
- return this.body;
- }
-
- /**
- * Sets the body of this for statement.
- * <p>
- * Special note: The JavaScript language does not allow a local variable declaration
- * to appear as the body of a for statement (they may only appear within a
- * block). However, the AST will allow a <code>VariableDeclarationStatement</code>
- * as the body of a <code>ForStatement</code>. To get something that will
- * compile, be sure to embed the <code>VariableDeclarationStatement</code>
- * inside a <code>Block</code>.
- * </p>
- *
- * @param statement the body statement node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setBody(Statement statement) {
- if (statement == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.body;
- preReplaceChild(oldChild, statement, BODY_PROPERTY);
- this.body = statement;
- postReplaceChild(oldChild, statement, BODY_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return super.memSize() + 4 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + this.initializers.listSize()
- + this.updaters.listSize()
- + (this.optionalConditionExpression == null ? 0 : getExpression().treeSize())
- + (this.body == null ? 0 : getBody().treeSize());
- }
-}
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
deleted file mode 100644
index fe6b7f2d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FunctionBinding.java
+++ /dev/null
@@ -1,357 +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.core.dom;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-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.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.MethodVerifier;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-import org.eclipse.wst.jsdt.internal.compiler.problem.AbortCompilation;
-import org.eclipse.wst.jsdt.internal.core.JavaElement;
-import org.eclipse.wst.jsdt.internal.core.Member;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * Internal implementation of method bindings.
- */
-class FunctionBinding implements IFunctionBinding {
-
- private static final int VALID_MODIFIERS = Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE |
- Modifier.ABSTRACT | Modifier.STATIC | Modifier.FINAL | Modifier.SYNCHRONIZED | Modifier.NATIVE |
- Modifier.STRICTFP;
- private static final ITypeBinding[] NO_TYPE_BINDINGS = new ITypeBinding[0];
- private org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding binding;
- private BindingResolver resolver;
- private ITypeBinding[] parameterTypes;
- private String name;
- private ITypeBinding declaringClass;
- private ITypeBinding returnType;
- private String key;
-
- FunctionBinding(BindingResolver resolver, org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding binding) {
- this.resolver = resolver;
- this.binding = binding;
- }
-
- /**
- * @see IFunctionBinding#isConstructor()
- */
- public boolean isConstructor() {
- return this.binding.isConstructor();
- }
-
- /**
- * @see IFunctionBinding#isDefaultConstructor()
- *
- */
- public boolean isDefaultConstructor() {
- final ReferenceBinding declaringClassBinding = this.binding.declaringClass;
- if (declaringClassBinding.isBinaryBinding()) {
- return false;
- }
- return (this.binding.modifiers & ExtraCompilerModifiers.AccIsDefaultConstructor) != 0;
- }
-
- /**
- * @see IBinding#getName()
- */
- public String getName() {
- if (name == null) {
- if (this.binding.isConstructor()) {
- name = this.getDeclaringClass().getName();
- } else {
- name = (this.binding.selector!=null) ? new String(this.binding.selector) : "";
- }
- }
- return name;
- }
-
- /**
- * @see IFunctionBinding#getDeclaringClass()
- */
- public ITypeBinding getDeclaringClass() {
- if (this.declaringClass == null) {
- this.declaringClass = this.resolver.getTypeBinding(this.binding.declaringClass);
- }
- return declaringClass;
- }
-
- /**
- * @see IFunctionBinding#getParameterTypes()
- */
- public ITypeBinding[] getParameterTypes() {
- if (this.parameterTypes != null) {
- return parameterTypes;
- }
- org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding[] parameters = this.binding.parameters;
- int length = parameters == null ? 0 : parameters.length;
- if (length == 0) {
- return this.parameterTypes = NO_TYPE_BINDINGS;
- } else {
- ITypeBinding[] paramTypes = new ITypeBinding[length];
- for (int i = 0; i < length; i++) {
- final TypeBinding parameterBinding = parameters[i];
- if (parameterBinding != null) {
- ITypeBinding typeBinding = this.resolver.getTypeBinding(parameterBinding);
- if (typeBinding == null) {
- return this.parameterTypes = NO_TYPE_BINDINGS;
- }
- paramTypes[i] = typeBinding;
- } else {
- // log error
- StringBuffer message = new StringBuffer("Report method binding where a parameter is null:\n"); //$NON-NLS-1$
- message.append(this.toString());
- Util.log(new IllegalArgumentException(), message.toString());
- // report no binding since one or more parameter has no binding
- return this.parameterTypes = NO_TYPE_BINDINGS;
- }
- }
- return this.parameterTypes = paramTypes;
- }
- }
-
- /**
- * @see IFunctionBinding#getReturnType()
- */
- public ITypeBinding getReturnType() {
- if (this.returnType == null) {
- this.returnType = this.resolver.getTypeBinding(this.binding.returnType);
- }
- return this.returnType;
- }
-
- public Object getDefaultValue() {
- return null;
- }
-
- public IJavaScriptElement getJavaElement() {
- JavaElement element = getUnresolvedJavaElement();
- if (element == null)
- return null;
- return element.resolved(this.binding);
- }
-
- private JavaElement getUnresolvedJavaElement() {
- IJavaScriptElement declaringElement = getDeclaringClass().getJavaElement();
- if (declaringElement == null) return null;
- if (!(this.resolver instanceof DefaultBindingResolver)) return null;
- ASTNode node = (ASTNode) ((DefaultBindingResolver) this.resolver).bindingsToAstNodes.get(this);
- ITypeRoot typeRoot=null;
- IType declaringType=null;
- if (declaringElement instanceof ITypeRoot)
- {
- typeRoot=(ITypeRoot)declaringElement;
-
- }
- else if (declaringElement instanceof IType )
- declaringType=(IType)declaringElement;
-// IType declaringType=(IType)declaringElement;
- if (node != null && declaringElement.getParent().getElementType() != IJavaScriptElement.CLASS_FILE) {
- if (node instanceof FunctionDeclaration) {
- FunctionDeclaration methodDeclaration = (FunctionDeclaration) node;
- ArrayList parameterSignatures = new ArrayList();
- Iterator iterator = methodDeclaration.parameters().iterator();
- while (iterator.hasNext()) {
- SingleVariableDeclaration parameter = (SingleVariableDeclaration) iterator.next();
- Type type = parameter.getType();
- String typeSig = Util.getSignature(type);
- int arrayDim = parameter.getExtraDimensions();
- if (parameter.getAST().apiLevel() >= AST.JLS3 && parameter.isVarargs()) {
- arrayDim++;
- }
- if (arrayDim > 0) {
- typeSig = Signature.createArraySignature(typeSig, arrayDim);
- }
- parameterSignatures.add(typeSig);
- }
- int parameterCount = parameterSignatures.size();
- String[] parameters = new String[parameterCount];
- parameterSignatures.toArray(parameters);
- if (typeRoot!=null)
- return (JavaElement) typeRoot.getFunction(getName(), parameters);
- else
- return (JavaElement) declaringType.getFunction(getName(), parameters);
- }
- else {
- return null;
- }
- } 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;
- }
- IFunction[] candidates = Member.findMethods(result, methods);
- if (candidates == null || candidates.length == 0)
- return null;
- return (JavaElement) candidates[0];
- }
- }
- /**
- * @see IBinding#getKind()
- */
- public int getKind() {
- return IBinding.METHOD;
- }
-
- /**
- * @see IBinding#getModifiers()
- */
- public int getModifiers() {
- return this.binding.getAccessFlags() & VALID_MODIFIERS;
- }
-
- /**
- * @see IBinding#isDeprecated()
- */
- public boolean isDeprecated() {
- return this.binding.isDeprecated();
- }
-
- /**
- * @see IBinding#isRecovered()
- */
- public boolean isRecovered() {
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.core.dom.IFunctionBinding#isVarargs()
- *
- */
- public boolean isVarargs() {
- return this.binding.isVarargs();
- }
-
- /**
- * @see IBinding#getKey()
- */
- public String getKey() {
- if (this.key == null) {
- this.key = new String(this.binding.computeUniqueKey());
- }
- return this.key;
- }
-
- /**
- * @see IBinding#isEqualTo(IBinding)
- *
- */
- public boolean isEqualTo(IBinding other) {
- if (other == this) {
- // identical binding - equal (key or no key)
- return true;
- }
- if (other == null) {
- // other binding missing
- return false;
- }
- if (!(other instanceof FunctionBinding)) {
- return false;
- }
- org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding otherBinding = ((FunctionBinding) other).binding;
- return BindingComparator.isEqual(this.binding, otherBinding);
- }
-
- public boolean isSubsignature(IFunctionBinding otherMethod) {
- try {
- org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding other = ((FunctionBinding) otherMethod).binding;
- if (!CharOperation.equals(this.binding.selector, other.selector))
- return false;
- return this.binding.areParametersEqual(other);
- } catch (AbortCompilation e) {
- // don't surface internal exception to clients
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=143013
- return false;
- }
- }
-
- /**
- * @see org.eclipse.wst.jsdt.core.dom.IFunctionBinding#getMethodDeclaration()
- */
- public IFunctionBinding getMethodDeclaration() {
- return this.resolver.getMethodBinding(this.binding.original());
- }
-
- /**
- * @see IFunctionBinding#overrides(IFunctionBinding)
- */
- public boolean overrides(IFunctionBinding overridenMethod) {
- try {
- org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding overridenCompilerBinding = ((FunctionBinding) overridenMethod).binding;
- if (this.binding == overridenCompilerBinding)
- return false;
- char[] selector = this.binding.selector;
- if (!CharOperation.equals(selector, overridenCompilerBinding.selector))
- return false;
- TypeBinding match = this.binding.declaringClass.findSuperTypeWithSameErasure(overridenCompilerBinding.declaringClass);
- if (!(match instanceof ReferenceBinding)) return false;
-
- org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding[] superMethods = ((ReferenceBinding)match).getMethods(selector);
- for (int i = 0, length = superMethods.length; i < length; i++) {
- if (superMethods[i].original() == overridenCompilerBinding) {
- LookupEnvironment lookupEnvironment = this.resolver.lookupEnvironment();
- if (lookupEnvironment == null) return false;
- MethodVerifier methodVerifier = lookupEnvironment.methodVerifier();
- org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding superMethod = superMethods[i];
- return !superMethod.isPrivate()
- && !(superMethod.isDefault() && (superMethod.declaringClass.getPackage()) != this.binding.declaringClass.getPackage())
- && methodVerifier.doesMethodOverride(this.binding, superMethod);
- }
- }
- return false;
- } catch (AbortCompilation e) {
- // don't surface internal exception to clients
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=143013
- return false;
- }
- }
-
- /**
- * For debugging purpose only.
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return this.binding.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FunctionDeclaration.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FunctionDeclaration.java
deleted file mode 100644
index c056de95..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FunctionDeclaration.java
+++ /dev/null
@@ -1,871 +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
- * Etienne Pfister <epfister@hsr.ch> - bug 231122
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Method declaration AST node type. A method declaration
- * is the union of a method declaration and a constructor declaration.
- * For JLS2:
- * <pre>
- * FunctionDeclaration:
- * [ jsdoc ] { Modifier } ( Type | <b>void</b> ) Identifier <b>(</b>
- * [ FormalParameter
- * { <b>,</b> FormalParameter } ] <b>)</b> {<b>[</b> <b>]</b> }
- * [ <b>throws</b> TypeName { <b>,</b> TypeName } ] ( Block | <b>;</b> )
- * ConstructorDeclaration:
- * [ jsdoc ] { Modifier } Identifier <b>(</b>
- * [ FormalParameter
- * { <b>,</b> FormalParameter } ] <b>)</b>
- * [<b>throws</b> TypeName { <b>,</b> TypeName } ] Block
- * </pre>
- * For JLS3, type parameters and reified modifiers
- * were added:
- * <pre>
- * FunctionDeclaration:
- * [ jsdoc ] { ExtendedModifier }
- * [ <b>&lt;</b> TypeParameter { <b>,</b> TypeParameter } <b>&gt;</b> ]
- * ( Type | <b>void</b> ) Identifier <b>(</b>
- * [ FormalParameter
- * { <b>,</b> FormalParameter } ] <b>)</b> {<b>[</b> <b>]</b> }
- * [ <b>throws</b> TypeName { <b>,</b> TypeName } ] ( Block | <b>;</b> )
- * ConstructorDeclaration:
- * [ jsdoc ] { ExtendedModifier }
- * [ <b>&lt;</b> TypeParameter { <b>,</b> TypeParameter } <b>&gt;</b> ]
- * Identifier <b>(</b>
- * [ FormalParameter
- * { <b>,</b> FormalParameter } ] <b>)</b>
- * [<b>throws</b> TypeName { <b>,</b> TypeName } ] Block
- * </pre>
- * <p>
- * When a jsdoc comment is present, the source
- * range begins with the first character of the "/**" comment delimiter.
- * When there is no jsdoc comment, the source range begins with the first
- * character of the first modifier keyword (if modifiers), or the
- * first character of the "&lt;" token (method, no modifiers, type parameters),
- * or the first character of the return type (method, no modifiers, no type
- * parameters), or the first character of the identifier (constructor,
- * no modifiers). The source range extends through the last character of the
- * ";" token (if no body), or the last character of the block (if body).
- * </p>
- *
- * 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 FunctionDeclaration extends BodyDeclaration {
-
- /**
- * The "javadoc" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor JAVADOC_PROPERTY =
- internalJavadocPropertyFactory(FunctionDeclaration.class);
-
- /**
- * The "modifiers" structural property of this node type (JLS2 API only).
- *
- */
- public static final SimplePropertyDescriptor MODIFIERS_PROPERTY =
- internalModifiersPropertyFactory(FunctionDeclaration.class);
-
- /**
- * The "modifiers" structural property of this node type (added in JLS3 API).
- *
- */
- public static final ChildListPropertyDescriptor MODIFIERS2_PROPERTY =
- internalModifiers2PropertyFactory(FunctionDeclaration.class);
-
- /**
- * The "constructor" structural property of this node type.
- *
- */
- public static final SimplePropertyDescriptor CONSTRUCTOR_PROPERTY =
- new SimplePropertyDescriptor(FunctionDeclaration.class, "constructor", boolean.class, MANDATORY); //$NON-NLS-1$
-
- /**
- * The "name" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor NAME_PROPERTY =
- new ChildPropertyDescriptor(FunctionDeclaration.class, "name", SimpleName.class, OPTIONAL, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "returnType" structural property of this node type (JLS2 API only).
- *
- */
- public static final ChildPropertyDescriptor RETURN_TYPE_PROPERTY =
- new ChildPropertyDescriptor(FunctionDeclaration.class, "returnType", Type.class, OPTIONAL, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "returnType2" structural property of this node type (added in JLS3 API).
- *
- */
- public static final ChildPropertyDescriptor RETURN_TYPE2_PROPERTY =
- new ChildPropertyDescriptor(FunctionDeclaration.class, "returnType2", Type.class, OPTIONAL, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "extraDimensions" structural property of this node type.
- *
- */
- public static final SimplePropertyDescriptor EXTRA_DIMENSIONS_PROPERTY =
- new SimplePropertyDescriptor(FunctionDeclaration.class, "extraDimensions", int.class, MANDATORY); //$NON-NLS-1$
-
- /**
- * The "parameters" structural property of this node type).
- *
- */
- public static final ChildListPropertyDescriptor PARAMETERS_PROPERTY =
- new ChildListPropertyDescriptor(FunctionDeclaration.class, "parameters", SingleVariableDeclaration.class, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "thrownExceptions" structural property of this node type).
- *
- */
- public static final ChildListPropertyDescriptor THROWN_EXCEPTIONS_PROPERTY =
- new ChildListPropertyDescriptor(FunctionDeclaration.class, "thrownExceptions", Name.class, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "body" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor BODY_PROPERTY =
- new ChildPropertyDescriptor(FunctionDeclaration.class, "body", Block.class, OPTIONAL, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS_2_0;
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS_3_0;
-
- static {
- List propertyList = new ArrayList(10);
- createPropertyList(FunctionDeclaration.class, propertyList);
- addProperty(JAVADOC_PROPERTY, propertyList);
- addProperty(MODIFIERS_PROPERTY, propertyList);
- addProperty(CONSTRUCTOR_PROPERTY, propertyList);
- addProperty(RETURN_TYPE_PROPERTY, propertyList);
- addProperty(NAME_PROPERTY, propertyList);
- addProperty(PARAMETERS_PROPERTY, propertyList);
- addProperty(EXTRA_DIMENSIONS_PROPERTY, propertyList);
- addProperty(THROWN_EXCEPTIONS_PROPERTY, propertyList);
- addProperty(BODY_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS_2_0 = reapPropertyList(propertyList);
-
- propertyList = new ArrayList(11);
- createPropertyList(FunctionDeclaration.class, propertyList);
- addProperty(JAVADOC_PROPERTY, propertyList);
- addProperty(MODIFIERS2_PROPERTY, propertyList);
- addProperty(CONSTRUCTOR_PROPERTY, propertyList);
- addProperty(RETURN_TYPE2_PROPERTY, propertyList);
- addProperty(NAME_PROPERTY, propertyList);
- addProperty(PARAMETERS_PROPERTY, propertyList);
- addProperty(EXTRA_DIMENSIONS_PROPERTY, propertyList);
- addProperty(THROWN_EXCEPTIONS_PROPERTY, propertyList);
- addProperty(BODY_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS_3_0 = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the AST.JLS* constants
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- if (apiLevel == AST.JLS2_INTERNAL) {
- return PROPERTY_DESCRIPTORS_2_0;
- } else {
- return PROPERTY_DESCRIPTORS_3_0;
- }
- }
-
- /**
- * <code>true</code> for a constructor, <code>false</code> for a method.
- * Defaults to method.
- */
- private boolean isConstructor = false;
-
- /**
- * The method name; lazily initialized; defaults to an unspecified,
- * legal JavaScript identifier.
- */
- private SimpleName methodName = null;
-
- /**
- * The parameter declarations
- * (element type: <code>SingleVariableDeclaration</code>).
- * Defaults to an empty list.
- */
- private ASTNode.NodeList parameters =
- new ASTNode.NodeList(PARAMETERS_PROPERTY);
-
- /**
- * The return type.
- * JLS2 behevior: lazily initialized; defaults to void.
- * JLS3 behavior; lazily initialized; defaults to void; null allowed.
- * Note that this field is ignored for constructor declarations.
- */
- private Type returnType = null;
-
- /**
- * Indicated whether the return type has been initialized.
- *
- */
- private boolean returnType2Initialized = false;
-
- /**
- * The number of array dimensions that appear after the parameters, rather
- * than after the return type itself; defaults to 0.
- *
- *
- */
- private int extraArrayDimensions = 0;
-
- /**
- * The list of thrown exception names (element type: <code>Name</code>).
- * Defaults to an empty list.
- */
- private ASTNode.NodeList thrownExceptions =
- new ASTNode.NodeList(THROWN_EXCEPTIONS_PROPERTY);
-
- /**
- * The method body, or <code>null</code> if none.
- * Defaults to none.
- */
- private Block optionalBody = null;
-
- /**
- * Creates a new AST node for a method declaration owned
- * by the given AST. By default, the declaration is for a method of an
- * unspecified, but legal, name; no modifiers; no javadoc; no type
- * parameters; void return type; no parameters; no array dimensions after
- * the parameters; no thrown exceptions; and no body (as opposed to an
- * empty body).
- * <p>
- * N.B. This constructor is package-private; all subclasses must be
- * declared in the same package; clients are unable to declare
- * additional subclasses.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- FunctionDeclaration(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- *
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int internalGetSetIntProperty(SimplePropertyDescriptor property, boolean get, int value) {
- if (property == MODIFIERS_PROPERTY) {
- if (get) {
- return getModifiers();
- } else {
- internalSetModifiers(value);
- return 0;
- }
- }
- if (property == EXTRA_DIMENSIONS_PROPERTY) {
- if (get) {
- return getExtraDimensions();
- } else {
- setExtraDimensions(value);
- return 0;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetIntProperty(property, get, value);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean internalGetSetBooleanProperty(SimplePropertyDescriptor property, boolean get, boolean value) {
- if (property == CONSTRUCTOR_PROPERTY) {
- if (get) {
- return isConstructor();
- } else {
- setConstructor(value);
- return false;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetBooleanProperty(property, get, value);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == JAVADOC_PROPERTY) {
- if (get) {
- return getJavadoc();
- } else {
- setJavadoc((JSdoc) child);
- return null;
- }
- }
- if (property == NAME_PROPERTY) {
- if (get) {
- return getName();
- } else {
- setName((SimpleName) child);
- return null;
- }
- }
- if (property == RETURN_TYPE_PROPERTY) {
- if (get) {
- return getReturnType();
- } else {
- setReturnType((Type) child);
- return null;
- }
- }
- if (property == RETURN_TYPE2_PROPERTY) {
- if (get) {
- return getReturnType2();
- } else {
- setReturnType2((Type) child);
- return null;
- }
- }
- if (property == BODY_PROPERTY) {
- if (get) {
- return getBody();
- } else {
- setBody((Block) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalGetChildListProperty(ChildListPropertyDescriptor property) {
- if (property == MODIFIERS2_PROPERTY) {
- return modifiers();
- }
- if (property == PARAMETERS_PROPERTY) {
- return parameters();
- }
- if (property == THROWN_EXCEPTIONS_PROPERTY) {
- return thrownExceptions();
- }
- // allow default implementation to flag the error
- return super.internalGetChildListProperty(property);
- }
-
- /* (omit javadoc for this method)
- * Method declared on BodyDeclaration.
- */
- final ChildPropertyDescriptor internalJavadocProperty() {
- return JAVADOC_PROPERTY;
- }
-
- /* (omit javadoc for this method)
- * Method declared on BodyDeclaration.
- */
- final ChildListPropertyDescriptor internalModifiers2Property() {
- return MODIFIERS2_PROPERTY;
- }
-
- /* (omit javadoc for this method)
- * Method declared on BodyDeclaration.
- */
- final SimplePropertyDescriptor internalModifiersProperty() {
- return MODIFIERS_PROPERTY;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return FUNCTION_DECLARATION;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- FunctionDeclaration result = new FunctionDeclaration(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setJavadoc(
- (JSdoc) ASTNode.copySubtree(target, getJavadoc()));
- if (this.ast.apiLevel == AST.JLS2_INTERNAL) {
- result.internalSetModifiers(getModifiers());
- result.setReturnType(
- (Type) ASTNode.copySubtree(target, getReturnType()));
- }
- if (this.ast.apiLevel >= AST.JLS3) {
- result.modifiers().addAll(ASTNode.copySubtrees(target, modifiers()));
- result.setReturnType2(
- (Type) ASTNode.copySubtree(target, getReturnType2()));
- }
- result.setConstructor(isConstructor());
- result.setExtraDimensions(getExtraDimensions());
-
- SimpleName name = getName();
- if(name != null){
- result.setName((SimpleName) name.clone(target));
- }
-
- result.parameters().addAll(
- ASTNode.copySubtrees(target, parameters()));
- result.thrownExceptions().addAll(
- ASTNode.copySubtrees(target, thrownExceptions()));
- result.setBody(
- (Block) ASTNode.copySubtree(target, getBody()));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChild(visitor, getJavadoc());
- if (this.ast.apiLevel == AST.JLS2_INTERNAL) {
- acceptChild(visitor, getReturnType());
- } else {
- acceptChildren(visitor, this.modifiers);
- acceptChild(visitor, getReturnType2());
- }
- // n.b. visit return type even for constructors
- acceptChild(visitor, getName());
- acceptChildren(visitor, this.parameters);
- acceptChildren(visitor, this.thrownExceptions);
- acceptChild(visitor, getBody());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns whether this declaration declares a constructor or a method.
- *
- * @return <code>true</code> if this is a constructor declaration,
- * and <code>false</code> if this is a method declaration
- */
- public boolean isConstructor() {
- return this.isConstructor;
- }
-
- /**
- * Sets whether this declaration declares a constructor or a method.
- *
- * @param isConstructor <code>true</code> for a constructor declaration,
- * and <code>false</code> for a method declaration
- */
- public void setConstructor(boolean isConstructor) {
- preValueChange(CONSTRUCTOR_PROPERTY);
- this.isConstructor = isConstructor;
- postValueChange(CONSTRUCTOR_PROPERTY);
- }
-
- /**
- * Returns the name of the method declared in this method declaration.
- * For a constructor declaration, this should be the same as the name
- * of the class.
- *
- * @return the method name node
- */
- public SimpleName getName() {
-// if (this.methodName == null) {
-// // lazy init must be thread-safe for readers
-// synchronized (this) {
-// if (this.methodName == null) {
-// preLazyInit();
-// this.methodName = new SimpleName(this.ast);
-// postLazyInit(this.methodName, NAME_PROPERTY);
-// }
-// }
-// }
- return this.methodName;
- }
-
- /**
- * Sets the name of the method declared in this method declaration to the
- * given name. For a constructor declaration, this should be the same as
- * the name of the class.
- *
- * @param methodName the new method name
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public void setName(SimpleName methodName) {
- ASTNode oldChild = this.methodName;
- preReplaceChild(oldChild, methodName, NAME_PROPERTY);
- this.methodName = methodName;
- postReplaceChild(oldChild, methodName, NAME_PROPERTY);
- }
-
- /**
- * Returns the live ordered list of method parameter declarations for this
- * method declaration.
- *
- * @return the live list of method parameter declarations
- * (element type: <code>SingleVariableDeclaration</code>)
- */
- public List parameters() {
- return this.parameters;
- }
-
- /**
- * Returns whether this method declaration declares a
- * variable arity method (added in JLS3 API). The convenience method checks
- * whether the last parameter is so marked.
- *
- * @return <code>true</code> if this is a variable arity method declaration,
- * and <code>false</code> otherwise
- * @exception UnsupportedOperationException if this operation is used in
- * a JLS2 AST
- * @see SingleVariableDeclaration#isVarargs()
- *
- */
- public boolean isVarargs() {
- // more efficient than just calling unsupportedIn2() to check
- if (this.modifiers == null) {
- unsupportedIn2();
- }
- if (parameters().isEmpty()) {
- return false;
- } else {
- SingleVariableDeclaration v = (SingleVariableDeclaration) parameters().get(parameters().size() - 1);
- return v.isVarargs();
- }
- }
-
- /**
- * Returns the live ordered list of thrown exception names in this method
- * declaration.
- *
- * @return the live list of exception names
- * (element type: <code>Name</code>)
- */
- public List thrownExceptions() {
- return this.thrownExceptions;
- }
-
- /**
- * Returns the return type of the method declared in this method
- * declaration, exclusive of any extra array dimensions (JLS2 API only).
- * This is one of the few places where the void type is meaningful.
- * <p>
- * Note that this child is not relevant for constructor declarations
- * (although, it does still figure in subtree equality comparisons
- * and visits), and is devoid of the binding information ordinarily
- * available.
- * </p>
- *
- * @return the return type, possibly the void primitive type
- * @exception UnsupportedOperationException if this operation is used in
- * an AST later than JLS2
- * @deprecated In the JLS3 API, this method is replaced by {@link #getReturnType2()},
- * which may return <code>null</code>.
- */
- public Type getReturnType() {
- return internalGetReturnType();
- }
-
- /**
- * Internal synonym for deprecated method. Used to avoid
- * deprecation warnings.
- *
- */
- /*package*/ final Type internalGetReturnType() {
- supportedOnlyIn2();
- if (this.returnType == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.returnType == null) {
- preLazyInit();
- this.returnType = this.ast.newPrimitiveType(PrimitiveType.VOID);
- postLazyInit(this.returnType, RETURN_TYPE_PROPERTY);
- }
- }
- }
- return this.returnType;
- }
-
- /**
- * Sets the return type of the method declared in this method declaration
- * to the given type, exclusive of any extra array dimensions (JLS2 API only). This is one
- * of the few places where the void type is meaningful.
- * <p>
- * Note that this child is not relevant for constructor declarations
- * (although it does still figure in subtree equality comparisons and visits).
- * </p>
- *
- * @param type the new return type, possibly the void primitive type
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- * @exception UnsupportedOperationException if this operation is used in
- * an AST later than JLS2
- * @deprecated In the JLS3 API, this method is replaced by
- * {@link #setReturnType2(Type)}, which accepts <code>null</code>.
- */
- public void setReturnType(Type type) {
- internalSetReturnType(type);
- }
-
- /**
- * Internal synonym for deprecated method. Used to avoid
- * deprecation warnings.
- *
- */
- /*package*/ void internalSetReturnType(Type type) {
- supportedOnlyIn2();
- if (type == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.returnType;
- preReplaceChild(oldChild, type, RETURN_TYPE_PROPERTY);
- this.returnType = type;
- postReplaceChild(oldChild, type, RETURN_TYPE_PROPERTY);
- }
-
- /**
- * Returns the return type of the method declared in this method
- * declaration, exclusive of any extra array dimensions (added in JLS3 API).
- * This is one of the few places where the void type is meaningful.
- * <p>
- * Note that this child is not relevant for constructor declarations
- * (although, if present, it does still figure in subtree equality comparisons
- * and visits), and is devoid of the binding information ordinarily
- * available. In the JLS2 API, the return type is mandatory.
- * In the JLS3 API, the return type is optional.
- * </p>
- *
- * @return the return type, possibly the void primitive type,
- * or <code>null</code> if none
- * @exception UnsupportedOperationException if this operation is used in
- * a JLS2 AST
- *
- */
- public Type getReturnType2() {
- unsupportedIn2();
- if (this.returnType == null && !this.returnType2Initialized) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.returnType == null && !this.returnType2Initialized) {
- preLazyInit();
- this.returnType = this.ast.newPrimitiveType(PrimitiveType.VOID);
- this.returnType2Initialized = true;
- postLazyInit(this.returnType, RETURN_TYPE2_PROPERTY);
- }
- }
- }
- return this.returnType;
- }
-
- /**
- * Sets the return type of the method declared in this method declaration
- * to the given type, exclusive of any extra array dimensions (added in JLS3 API).
- * This is one of the few places where the void type is meaningful.
- * <p>
- * Note that this child is not relevant for constructor declarations
- * (although it does still figure in subtree equality comparisons and visits).
- * In the JLS2 API, the return type is mandatory.
- * In the JLS3 API, the return type is optional.
- * </p>
- *
- * @param type the new return type, possibly the void primitive type,
- * or <code>null</code> if none
- * @exception UnsupportedOperationException if this operation is used in
- * a JLS2 AST
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- *
- */
- public void setReturnType2(Type type) {
- unsupportedIn2();
- this.returnType2Initialized = true;
- ASTNode oldChild = this.returnType;
- preReplaceChild(oldChild, type, RETURN_TYPE2_PROPERTY);
- if (type instanceof InferredType && ((InferredType)type).getType()==null)
- this.returnType=null;
- else
- this.returnType = type;
- postReplaceChild(oldChild, type, RETURN_TYPE2_PROPERTY);
- }
-
- /**
- * Returns the number of extra array dimensions over and above the
- * explicitly-specified return type.
- * <p>
- * For example, <code>int foo()[][]</code> has a return type of
- * <code>int</code> and two extra array dimensions;
- * <code>int[][] foo()</code> has a return type of <code>int[][]</code>
- * and zero extra array dimensions. The two constructs have different
- * ASTs, even though there are really syntactic variants of the same
- * method declaration.
- * </p>
- *
- * @return the number of extra array dimensions
- *
- */
- public int getExtraDimensions() {
- return this.extraArrayDimensions;
- }
-
- /**
- * Sets the number of extra array dimensions over and above the
- * explicitly-specified return type.
- * <p>
- * For example, <code>int foo()[][]</code> is rendered as a return
- * type of <code>int</code> with two extra array dimensions;
- * <code>int[][] foo()</code> is rendered as a return type of
- * <code>int[][]</code> with zero extra array dimensions. The two
- * constructs have different ASTs, even though there are really syntactic
- * variants of the same method declaration.
- * </p>
- *
- * @param dimensions the number of array dimensions
- * @exception IllegalArgumentException if the number of dimensions is
- * negative
- *
- */
- public void setExtraDimensions(int dimensions) {
- if (dimensions < 0) {
- throw new IllegalArgumentException();
- }
- preValueChange(EXTRA_DIMENSIONS_PROPERTY);
- this.extraArrayDimensions = dimensions;
- postValueChange(EXTRA_DIMENSIONS_PROPERTY);
- }
-
- /**
- * Returns the body of this method declaration, or <code>null</code> if
- * this method has <b>no</b> body.
- * <p>
- * Note that there is a subtle difference between having no body and having
- * an empty body ("{}").
- * </p>
- *
- * @return the method body, or <code>null</code> if this method has no
- * body
- */
- public Block getBody() {
- return this.optionalBody;
- }
-
- /**
- * Sets or clears the body of this method declaration.
- * <p>
- * Note that there is a subtle difference between having no body
- * (as in <code>"void foo();"</code>) and having an empty body (as in
- * "void foo() {}"). Abstract methods, and methods declared in interfaces,
- * have no body. Non-abstract methods, and all constructors, have a body.
- * </p>
- *
- * @param body the block node, or <code>null</code> if
- * there is none
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setBody(Block body) {
- // a FunctionDeclaration may occur in a Block - must check cycles
- ASTNode oldChild = this.optionalBody;
- preReplaceChild(oldChild, body, BODY_PROPERTY);
- this.optionalBody = body;
- postReplaceChild(oldChild, body, BODY_PROPERTY);
- }
-
- /**
- * Resolves and returns the binding for the method or constructor declared
- * in this method or constructor declaration.
- * <p>
- * Note that bindings are generally unavailable unless requested when the
- * AST is being built.
- * </p>
- *
- * @return the binding, or <code>null</code> if the binding cannot be
- * resolved
- */
- public IFunctionBinding resolveBinding() {
- return this.ast.getBindingResolver().resolveMethod(this);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return super.memSize() + 9 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.optionalDocComment == null ? 0 : getJavadoc().treeSize())
- + (this.modifiers == null ? 0 : this.modifiers.listSize())
- + (this.methodName == null ? 0 : getName().treeSize())
- + (this.returnType == null ? 0 : this.returnType.treeSize())
- + this.parameters.listSize()
- + this.thrownExceptions.listSize()
- + (this.optionalBody == null ? 0 : getBody().treeSize());
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FunctionExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FunctionExpression.java
deleted file mode 100644
index bb3728d0..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FunctionExpression.java
+++ /dev/null
@@ -1,206 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Cast expression AST node type.
- *
- * <pre>
- * CastExpression:
- * <b>(</b> Type <b>)</b> Expression
- * </pre>
- *
- * 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 FunctionExpression extends Expression {
-
- /**
- * The "type" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor METHOD_PROPERTY =
- new ChildPropertyDescriptor(FunctionExpression.class, "method", FunctionDeclaration.class, MANDATORY, NO_CYCLE_RISK); //$NON-NLS-1$
-
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List properyList = new ArrayList(3);
- createPropertyList(FunctionExpression.class, properyList);
- addProperty(METHOD_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The type; lazily initialized; defaults to a unspecified,
- * legal type.
- */
- private FunctionDeclaration methodDeclaration = null;
-
-
- /**
- * Creates a new AST node for a cast expression owned by the given
- * AST. By default, the type and expression are unspecified (but legal).
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- FunctionExpression(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == METHOD_PROPERTY) {
- if (get) {
- return getMethod();
- } else {
- setMethod((FunctionDeclaration) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return FUNCTION_EXPRESSION;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- FunctionExpression result = new FunctionExpression(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setMethod((FunctionDeclaration) getMethod().clone(target));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChild(visitor, getMethod());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the type in this cast expression.
- *
- * @return the type
- */
- public FunctionDeclaration getMethod() {
- if (this.methodDeclaration == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.methodDeclaration == null) {
- preLazyInit();
- this.methodDeclaration = this.ast.newFunctionDeclaration();
- postLazyInit(this.methodDeclaration, METHOD_PROPERTY);
- }
- }
- }
- return this.methodDeclaration;
- }
-
- /**
- * Sets the type in this cast expression to the given type.
- *
- * @param type the new type
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public void setMethod(FunctionDeclaration method) {
- if (method == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.methodDeclaration;
- preReplaceChild(oldChild, method, METHOD_PROPERTY);
- this.methodDeclaration = method;
- postReplaceChild(oldChild, method, METHOD_PROPERTY);
- }
-
-
-
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- // treat Code as free
- return BASE_NODE_SIZE + 2 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.methodDeclaration == null ? 0 : getMethod().treeSize());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FunctionInvocation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FunctionInvocation.java
deleted file mode 100644
index a2321ead..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FunctionInvocation.java
+++ /dev/null
@@ -1,403 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Method invocation expression AST node type.
- * For JLS2:
- * <pre>
- * FunctionInvocation:
- * [ Expression <b>.</b> ] Identifier
- * <b>(</b> [ Expression { <b>,</b> Expression } ] <b>)</b>
- * </pre>
- * For JLS3, type arguments are added:
- * <pre>
- * FunctionInvocation:
- * [ Expression <b>.</b> ]
- * [ <b>&lt;</b> Type { <b>,</b> Type } <b>&gt;</b> ]
- * Identifier <b>(</b> [ Expression { <b>,</b> Expression } ] <b>)</b>
- * </pre>
- *
- * 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 FunctionInvocation extends Expression {
-
- /**
- * The "expression" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor EXPRESSION_PROPERTY =
- new ChildPropertyDescriptor(FunctionInvocation.class, "expression", Expression.class, OPTIONAL, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "typeArguments" structural property of this node type (added in JLS3 API).
- *
- */
- public static final ChildListPropertyDescriptor TYPE_ARGUMENTS_PROPERTY =
- new ChildListPropertyDescriptor(FunctionInvocation.class, "typeArguments", Type.class, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "name" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor NAME_PROPERTY =
- new ChildPropertyDescriptor(FunctionInvocation.class, "name", SimpleName.class, OPTIONAL, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "arguments" structural property of this node type.
- *
- */
- public static final ChildListPropertyDescriptor ARGUMENTS_PROPERTY =
- new ChildListPropertyDescriptor(FunctionInvocation.class, "arguments", Expression.class, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS_2_0;
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS_3_0;
-
- static {
- List properyList = new ArrayList(4);
- createPropertyList(FunctionInvocation.class, properyList);
- addProperty(EXPRESSION_PROPERTY, properyList);
- addProperty(NAME_PROPERTY, properyList);
- addProperty(ARGUMENTS_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS_2_0 = reapPropertyList(properyList);
-
- properyList = new ArrayList(5);
- createPropertyList(FunctionInvocation.class, properyList);
- addProperty(EXPRESSION_PROPERTY, properyList);
- addProperty(TYPE_ARGUMENTS_PROPERTY, properyList);
- addProperty(NAME_PROPERTY, properyList);
- addProperty(ARGUMENTS_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS_3_0 = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- if (apiLevel == AST.JLS2_INTERNAL) {
- return PROPERTY_DESCRIPTORS_2_0;
- } else {
- return PROPERTY_DESCRIPTORS_3_0;
- }
- }
-
- /**
- * The expression; <code>null</code> for none; defaults to none.
- */
- private Expression optionalExpression = null;
-
- /**
- * The type arguments (element type: <code>Type</code>).
- * Null in JLS2. Added in JLS3; defaults to an empty list
- * (see constructor).
- *
- */
- private ASTNode.NodeList typeArguments = null;
-
- /**
- * The method name; lazily initialized; defaults to a unspecified,
- * legal JavaScript method name.
- */
- private SimpleName methodName = null;
-
- /**
- * The list of argument expressions (element type:
- * <code>Expression</code>). Defaults to an empty list.
- */
- private ASTNode.NodeList arguments =
- new ASTNode.NodeList(ARGUMENTS_PROPERTY);
-
- /**
- * Creates a new AST node for a method invocation expression owned by the
- * given AST. By default, no expression, no type arguments,
- * an unspecified, but legal, method name, and an empty list of arguments.
- *
- * @param ast the AST that is to own this node
- */
- FunctionInvocation(AST ast) {
- super(ast);
- if (ast.apiLevel >= AST.JLS3) {
- this.typeArguments = new ASTNode.NodeList(TYPE_ARGUMENTS_PROPERTY);
- }
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == NAME_PROPERTY) {
- if (get) {
- return getName();
- } else {
- setName((SimpleName) child);
- return null;
- }
- }
- if (property == EXPRESSION_PROPERTY) {
- if (get) {
- return getExpression();
- } else {
- setExpression((Expression) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalGetChildListProperty(ChildListPropertyDescriptor property) {
- if (property == ARGUMENTS_PROPERTY) {
- return arguments();
- }
- if (property == TYPE_ARGUMENTS_PROPERTY) {
- return typeArguments();
- }
- // allow default implementation to flag the error
- return super.internalGetChildListProperty(property);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return FUNCTION_INVOCATION;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- FunctionInvocation result = new FunctionInvocation(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- if (getName()!=null)
- result.setName((SimpleName) getName().clone(target));
- result.setExpression(
- (Expression) ASTNode.copySubtree(target, getExpression()));
- if (this.ast.apiLevel >= AST.JLS3) {
- result.typeArguments().addAll(ASTNode.copySubtrees(target, typeArguments()));
- }
- result.arguments().addAll(ASTNode.copySubtrees(target, arguments()));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChild(visitor, getExpression());
- if (this.ast.apiLevel >= AST.JLS3) {
- acceptChildren(visitor, this.typeArguments);
- }
- if (getName()!=null)
- acceptChild(visitor, getName());
- acceptChildren(visitor, this.arguments);
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the expression of this method invocation expression, or
- * <code>null</code> if there is none.
- *
- * @return the expression node, or <code>null</code> if there is none
- */
- public Expression getExpression() {
- return this.optionalExpression;
- }
-
- /**
- * Returns <code>true</code> if the resolved return type has been inferred
- * from the assignment context (JLS3 15.12.2.8), <code>false</code> otherwise.
- * <p>
- * This information is available only when bindings are requested when the AST is being built
- * </p>.
- *
- * @return <code>true</code> if the resolved return type has been inferred
- * from the assignment context (JLS3 15.12.2.8), <code>false</code> otherwise
- *
- */
- public boolean isResolvedTypeInferredFromExpectedType() {
- return this.ast.getBindingResolver().isResolvedTypeInferredFromExpectedType(this);
- }
-
- /**
- * Sets or clears the expression of this method invocation expression.
- *
- * @param expression the expression node, or <code>null</code> if
- * there is none
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setExpression(Expression expression) {
- ASTNode oldChild = this.optionalExpression;
- preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY);
- this.optionalExpression = expression;
- postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY);
- }
-
- /**
- * Returns the live ordered list of type arguments of this method
- * invocation (added in JLS3 API).
- *
- * @return the live list of type arguments
- * (element type: <code>Type</code>)
- * @exception UnsupportedOperationException if this operation is used in
- * a JLS2 AST
- *
- */
- public List typeArguments() {
- // more efficient than just calling unsupportedIn2() to check
- if (this.typeArguments == null) {
- unsupportedIn2();
- }
- return this.typeArguments;
- }
-
- /**
- * Returns the name of the method invoked in this expression.
- *
- * @return the method name node
- */
- public SimpleName getName() {
- if (this.methodName == null) {
-// // lazy init must be thread-safe for readers
-// synchronized (this) {
-// if (this.methodName == null) {
-// preLazyInit();
-// this.methodName = new SimpleName(this.ast);
-// postLazyInit(this.methodName, NAME_PROPERTY);
-// }
-// }
- }
- return this.methodName;
- }
-
- /**
- * Sets the name of the method invoked in this expression to the
- * given name.
- *
- * @param name the new method name
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public void setName(SimpleName name) {
-// if (name == null) {
-// throw new IllegalArgumentException();
-// }
- ASTNode oldChild = this.methodName;
- preReplaceChild(oldChild, name, NAME_PROPERTY);
- this.methodName = name;
- postReplaceChild(oldChild, name, NAME_PROPERTY);
- }
-
- /**
- * Returns the live ordered list of argument expressions in this method
- * invocation expression.
- *
- * @return the live list of argument expressions
- * (element type: <code>Expression</code>)
- */
- public List arguments() {
- return this.arguments;
- }
-
- /**
- * Resolves and returns the binding for the method invoked by this
- * expression.
- * <p>
- * Note that bindings are generally unavailable unless requested when the
- * AST is being built.
- * </p>
- *
- * @return the method binding, or <code>null</code> if the binding cannot
- * be resolved
- *
- */
- public IFunctionBinding resolveMethodBinding() {
- return this.ast.getBindingResolver().resolveMethod(this);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- // treat Code as free
- return BASE_NODE_SIZE + 4 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.optionalExpression == null ? 0 : getExpression().treeSize())
- + (this.typeArguments == null ? 0 : this.typeArguments.listSize())
- + (this.methodName == null ? 0 : getName().treeSize())
- + (this.arguments == null ? 0 : this.arguments.listSize());
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FunctionRef.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FunctionRef.java
deleted file mode 100644
index 07d7f6f5..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FunctionRef.java
+++ /dev/null
@@ -1,320 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * AST node for a method or constructor reference within a doc comment
- * ({@link JSdoc}). The principal uses of these are in "@see" and "@link"
- * tag elements, for references to method and constructor members.
- * <pre>
- * FunctionRef:
- * [ Name ] <b>#</b> Identifier
- * <b>(</b> [ FunctionRefParameter | { <b>,</b> FunctionRefParameter } ] <b>)</b>
- * </pre>
- *
- * @see JSdoc
- *
- * 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 FunctionRef extends ASTNode implements IDocElement {
-
- /**
- * The "qualifier" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor QUALIFIER_PROPERTY =
- new ChildPropertyDescriptor(FunctionRef.class, "qualifier", Name.class, OPTIONAL, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "name" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor NAME_PROPERTY =
- new ChildPropertyDescriptor(FunctionRef.class, "name", SimpleName.class, MANDATORY, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "parameters" structural property of this node type.
- *
- */
- public static final ChildListPropertyDescriptor PARAMETERS_PROPERTY =
- new ChildListPropertyDescriptor(FunctionRef.class, "parameters", FunctionRefParameter.class, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List properyList = new ArrayList(4);
- createPropertyList(FunctionRef.class, properyList);
- addProperty(QUALIFIER_PROPERTY, properyList);
- addProperty(NAME_PROPERTY, properyList);
- addProperty(PARAMETERS_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the AST.JLS* constants
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The optional qualifier; <code>null</code> for none; defaults to none.
- */
- private Name optionalQualifier = null;
-
- /**
- * The method name; lazily initialized; defaults to a unspecified,
- * legal JavaScript method name.
- */
- private SimpleName methodName = null;
-
- /**
- * The parameter declarations
- * (element type: <code>FunctionRefParameter</code>).
- * Defaults to an empty list.
- */
- private ASTNode.NodeList parameters =
- new ASTNode.NodeList(PARAMETERS_PROPERTY);
-
-
- /**
- * Creates a new AST node for a method reference owned by the given
- * AST. By default, the method reference is for a method with an
- * unspecified, but legal, name; no qualifier; and an empty parameter
- * list.
- * <p>
- * N.B. This constructor is package-private; all subclasses must be
- * declared in the same package; clients are unable to declare
- * additional subclasses.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- FunctionRef(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == QUALIFIER_PROPERTY) {
- if (get) {
- return getQualifier();
- } else {
- setQualifier((Name) child);
- return null;
- }
- }
- if (property == NAME_PROPERTY) {
- if (get) {
- return getName();
- } else {
- setName((SimpleName) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalGetChildListProperty(ChildListPropertyDescriptor property) {
- if (property == PARAMETERS_PROPERTY) {
- return parameters();
- }
- // allow default implementation to flag the error
- return super.internalGetChildListProperty(property);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return FUNCTION_REF;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- FunctionRef result = new FunctionRef(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setQualifier((Name) ASTNode.copySubtree(target, getQualifier()));
- result.setName((SimpleName) ASTNode.copySubtree(target, getName()));
- result.parameters().addAll(
- ASTNode.copySubtrees(target, parameters()));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChild(visitor, getQualifier());
- acceptChild(visitor, getName());
- acceptChildren(visitor, this.parameters);
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the qualifier of this method reference, or
- * <code>null</code> if there is none.
- *
- * @return the qualifier name node, or <code>null</code> if there is none
- */
- public Name getQualifier() {
- return this.optionalQualifier;
- }
-
- /**
- * Sets or clears the qualifier of this method reference.
- *
- * @param name the qualifier name node, or <code>null</code> if
- * there is none
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public void setQualifier(Name name) {
- ASTNode oldChild = this.optionalQualifier;
- preReplaceChild(oldChild, name, QUALIFIER_PROPERTY);
- this.optionalQualifier = name;
- postReplaceChild(oldChild, name, QUALIFIER_PROPERTY);
- }
-
- /**
- * Returns the name of the referenced method or constructor.
- *
- * @return the method or constructor name node
- */
- public SimpleName getName() {
- if (this.methodName == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.methodName == null) {
- preLazyInit();
- this.methodName = new SimpleName(this.ast);
- postLazyInit(this.methodName, NAME_PROPERTY);
- }
- }
- }
- return this.methodName;
- }
-
- /**
- * Sets the name of the referenced method or constructor to the
- * given name.
- *
- * @param name the new method or constructor name node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the name is <code>null</code></li>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public void setName(SimpleName name) {
- if (name == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.methodName;
- preReplaceChild(oldChild, name, NAME_PROPERTY);
- this.methodName = name;
- postReplaceChild(oldChild, name, NAME_PROPERTY);
- }
-
- /**
- * Returns the live ordered list of method parameter references for this
- * method reference.
- *
- * @return the live list of method parameter references
- * (element type: <code>FunctionRefParameter</code>)
- */
- public List parameters() {
- return this.parameters;
- }
-
- /**
- * Resolves and returns the binding for the entity referred to by
- * this method reference.
- * <p>
- * Note that bindings are generally unavailable unless requested when the
- * AST is being built.
- * </p>
- *
- * @return the binding, or <code>null</code> if the binding cannot be
- * resolved
- */
- public final IBinding resolveBinding() {
- return this.ast.getBindingResolver().resolveReference(this);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return BASE_NODE_SIZE + 3 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.optionalQualifier == null ? 0 : getQualifier().treeSize())
- + (this.methodName == null ? 0 : getName().treeSize())
- + this.parameters.listSize();
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FunctionRefParameter.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FunctionRefParameter.java
deleted file mode 100644
index 21e0966d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FunctionRefParameter.java
+++ /dev/null
@@ -1,360 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * AST node for a parameter within a method reference ({@link FunctionRef}).
- * These nodes only occur within doc comments ({@link JSdoc}).
- * For JLS2:
- * <pre>
- * FunctionRefParameter:
- * Type [ Identifier ]
- * </pre>
- * For JLS3, the variable arity indicator was added:
- * <pre>
- * FunctionRefParameter:
- * Type [ <b>...</b> ] [ Identifier ]
- * </pre>
- * <p>
- * Note: The 1.5 spec for the jsdoc tool does not mention the possibility
- * of a variable arity indicator in method references. However, the 1.5
- * jsdoc tool itself does indeed support it. Since it makes sense to have
- * a way to explicitly refer to variable arity methods, it seems more likely
- * that the jsdoc spec is wrong in this case.
- * </p>
- *
- *
- * 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 FunctionRefParameter extends ASTNode {
-
- /**
- * The "type" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor TYPE_PROPERTY =
- new ChildPropertyDescriptor(FunctionRefParameter.class, "type", Type.class, MANDATORY, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "varargs" structural property of this node type (added in JLS3 API).
- *
- */
- public static final SimplePropertyDescriptor VARARGS_PROPERTY =
- new SimplePropertyDescriptor(FunctionRefParameter.class, "varargs", boolean.class, MANDATORY); //$NON-NLS-1$
-
- /**
- * The "name" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor NAME_PROPERTY =
- new ChildPropertyDescriptor(FunctionRefParameter.class, "name", SimpleName.class, OPTIONAL, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS_2_0;
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS_3_0;
-
- static {
- List properyList = new ArrayList(3);
- createPropertyList(FunctionRefParameter.class, properyList);
- addProperty(TYPE_PROPERTY, properyList);
- addProperty(NAME_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS_2_0 = reapPropertyList(properyList);
-
- properyList = new ArrayList(3);
- createPropertyList(FunctionRefParameter.class, properyList);
- addProperty(TYPE_PROPERTY, properyList);
- addProperty(VARARGS_PROPERTY, properyList);
- addProperty(NAME_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS_3_0 = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the AST.JLS* constants
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- if (apiLevel == AST.JLS2_INTERNAL) {
- return PROPERTY_DESCRIPTORS_2_0;
- } else {
- return PROPERTY_DESCRIPTORS_3_0;
- }
- }
-
- /**
- * The type; lazily initialized; defaults to a unspecified,
- * legal type.
- */
- private Type type = null;
-
- /**
- * Indicates the last parameter of a variable arity method;
- * defaults to false.
- *
- *
- */
- private boolean variableArity = false;
-
- /**
- * The parameter name, or <code>null</code> if none; none by
- * default.
- */
- private SimpleName optionalParameterName = null;
-
- /**
- * Creates a new AST node for a method referenece parameter owned by the given
- * AST. By default, the node has an unspecified (but legal) type,
- * not variable arity, and no parameter name.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- FunctionRefParameter(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == TYPE_PROPERTY) {
- if (get) {
- return getType();
- } else {
- setType((Type) child);
- return null;
- }
- }
- if (property == NAME_PROPERTY) {
- if (get) {
- return getName();
- } else {
- setName((SimpleName) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean internalGetSetBooleanProperty(SimplePropertyDescriptor property, boolean get, boolean value) {
- if (property == VARARGS_PROPERTY) {
- if (get) {
- return isVarargs();
- } else {
- setVarargs(value);
- return false;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetBooleanProperty(property, get, value);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return FUNCTION_REF_PARAMETER;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- FunctionRefParameter result = new FunctionRefParameter(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setType((Type) ASTNode.copySubtree(target, getType()));
- if (this.ast.apiLevel >= AST.JLS3) {
- result.setVarargs(isVarargs());
- }
- result.setName((SimpleName) ASTNode.copySubtree(target, getName()));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChild(visitor, getType());
- acceptChild(visitor, getName());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the paramter type.
- *
- * @return the parameter type
- */
- public Type getType() {
- if (this.type == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.type == null) {
- preLazyInit();
- this.type = this.ast.newInferredType(null);
- postLazyInit(this.type, TYPE_PROPERTY);
- }
- }
- }
- return this.type;
- }
-
- /**
- * Sets the paramter type to the given type.
- *
- * @param type the new type
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the type is <code>null</code></li>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public void setType(Type type) {
- if (type == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.type;
- preReplaceChild(oldChild, type, TYPE_PROPERTY);
- this.type = type;
- postReplaceChild(oldChild, type, TYPE_PROPERTY);
- }
-
- /**
- * Returns whether this method reference parameter is for
- * the last parameter of a variable arity method (added in JLS3 API).
- * <p>
- * Note that the binding for the type <code>Foo</code>in the vararg method
- * reference <code>#fun(Foo...)</code> is always for the type as
- * written; i.e., the type binding for <code>Foo</code>. However, if you
- * navigate from the FunctionRef to its method binding to the
- * type binding for its last parameter, the type binding for the vararg
- * parameter is always an array type (i.e., <code>Foo[]</code>) reflecting
- * the way vararg methods get compiled.
- * </p>
- *
- * @return <code>true</code> if this is a variable arity parameter,
- * and <code>false</code> otherwise
- * @exception UnsupportedOperationException if this operation is used in
- * a JLS2 AST
- *
- */
- public boolean isVarargs() {
- unsupportedIn2();
- return this.variableArity;
- }
-
- /**
- * Sets whether this method reference parameter is for the last parameter of
- * a variable arity method (added in JLS3 API).
- *
- * @param variableArity <code>true</code> if this is a variable arity
- * parameter, and <code>false</code> otherwise
- *
- */
- public void setVarargs(boolean variableArity) {
- unsupportedIn2();
- preValueChange(VARARGS_PROPERTY);
- this.variableArity = variableArity;
- postValueChange(VARARGS_PROPERTY);
- }
-
- /**
- * Returns the parameter name, or <code>null</code> if there is none.
- *
- * @return the parameter name node, or <code>null</code> if there is none
- */
- public SimpleName getName() {
- return this.optionalParameterName;
- }
-
- /**
- * Sets or clears the parameter name.
- *
- * @param name the parameter name node, or <code>null</code> if
- * there is none
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public void setName(SimpleName name) {
- ASTNode oldChild = this.optionalParameterName;
- preReplaceChild(oldChild, name, NAME_PROPERTY);
- this.optionalParameterName = name;
- postReplaceChild(oldChild, name, NAME_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return BASE_NODE_SIZE + 2 * 5;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.type == null ? 0 : getType().treeSize())
- + (this.optionalParameterName == null ? 0 : getName().treeSize());
- }
-}
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
deleted file mode 100644
index 141163d9..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IBinding.java
+++ /dev/null
@@ -1,265 +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.core.dom;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-
-/**
- * A binding represents a named entity in the JavaScript language. The world of
- * bindings provides an integrated picture of the structure of the program as
- * seen from the compiler's point of view. This interface declare protocol
- * common to the various different kinds of named entities in the JavaScript language:
- * packages, types, fields, methods, constructors, and local variables.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * @see IPackageBinding
- * @see ITypeBinding
- * @see IVariableBinding
- * @see IFunctionBinding
- *
- * 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 IBinding {
-
- /**
- * Kind constant (value 1) indicating a package binding.
- * Bindings of this kind can be safely cast to <code>IPackageBinding</code>.
- *
- * @see #getKind()
- * @see IPackageBinding
- */
- public static final int PACKAGE = 1;
-
- /**
- * Kind constant (value 2) indicating a type binding.
- * Bindings of this kind can be safely cast to <code>ITypeBinding</code>.
- *
- * @see #getKind()
- * @see ITypeBinding
- */
- public static final int TYPE = 2;
-
- /**
- * Kind constant (value 3) indicating a field or local variable binding.
- * Bindings of this kind can be safely cast to <code>IVariableBinding</code>.
- *
- * @see #getKind()
- * @see IVariableBinding
- */
- public static final int VARIABLE = 3;
-
- /**
- * Kind constant (value 4) indicating a method or constructor binding.
- * Bindings of this kind can be safely cast to <code>IFunctionBinding</code>.
- *
- * @see #getKind()
- * @see IFunctionBinding
- */
- public static final int METHOD = 4;
-
-
-
- /**
- * Returns the kind of bindings this is. That is one of the kind constants:
- * <code>PACKAGE</code>,
- * <code>TYPE</code>,
- * <code>VARIABLE</code>,
- * <code>METHOD</code>,
- * or <code>MEMBER_VALUE_PAIR</code>.
- * <p>
- * Note that additional kinds might be added in the
- * future, so clients should not assume this list is exhaustive and
- * should program defensively, e.g. by having a reasonable default
- * in a switch statement.
- * </p>
- * @return one of the kind constants
- */
- public int getKind();
-
- /**
- * Returns the name of this binding.
- * Details of the name are specified with each specific kind of binding.
- *
- * @return the name of this binding
- */
- public String getName();
-
- /**
- * Returns the modifiers for this binding.
- * <p>
- * Note that deprecated is not included among the modifiers.
- * Use <code>isDeprecated</code> to find out whether a binding is deprecated.
- * </p>
- *
- * @return the bit-wise or of <code>Modifier</code> constants
- * @see Modifier
- */
- public int getModifiers();
-
- /**
- * Return whether this binding is for something that is deprecated.
- * A deprecated class, interface, field, method, or constructor is one that
- * is marked with the 'deprecated' tag in its jsdoc comment.
- *
- * @return <code>true</code> if this binding is deprecated, and
- * <code>false</code> otherwise
- */
- public boolean isDeprecated();
-
- /**
- * Return whether this binding is created because the bindings recovery is enabled. This binding is considered
- * to be incomplete. Its internal state might be incomplete.
- *
- * @return <code>true</code> if this binding is a recovered binding, and
- * <code>false</code> otherwise
- *
- */
- public boolean isRecovered();
-
- /**
- * Returns the JavaScript element that corresponds to this binding.
- * Returns <code>null</code> if this binding has no corresponding
- * JavaScript element.
- * <p>
- * For array types, this method returns the JavaScript element that corresponds
- * to the array's element type. For raw and parameterized types, this method
- * returns the JavaScript element of the erasure. For annotations, this methods
- * returns the JavaScript element of the annotation type.
- * </p>
- * <p>
- * Here are the cases where a <code>null</code> should be expected:
- * <ul>
- * <li>primitive types, including void</li>
- * <li>null type</li>
- * <li>capture types</li>
- * <li>array types of any of the above</li>
- * <li>the "length" field of an array type</li>
- * <li>the default constructor of a source class</li>
- * <li>the constructor of an anonymous class</li>
- * <li>member value pairs</li>
- * </ul>
- * For all other kind of type, method, variable, annotation and package bindings,
- * this method returns non-<code>null</code>.
- * </p>
- *
- * @return the JavaScript element that corresponds to this binding,
- * or <code>null</code> if none
- *
- */
- public IJavaScriptElement getJavaElement();
-
- /**
- * Returns the key for this binding.
- * <p>
- * Within a connected cluster of bindings (for example, all bindings
- * reachable from a given AST), each binding will have a distinct keys.
- * The keys are generated in a manner that is predictable and as
- * stable as possible. This last property makes these keys useful for
- * comparing bindings between disconnected clusters of bindings (for example,
- * the bindings between the "before" and "after" ASTs of the same
- * javaScript unit).
- * </p>
- * <p>
- * The exact details of how the keys are generated is unspecified.
- * However, it is a function of the following information:
- * <ul>
- * <li>packages - the name of the package (for an unnamed package,
- * some internal id)</li>
- * <li>classes or interfaces - the VM name of the type and the key
- * of its package</li>
- * <li>array types - the key of the component type and number of
- * dimensions</li>
- * <li>primitive types - the name of the primitive type</li>
- * <li>fields - the name of the field and the key of its declaring
- * type</li>
- * <li>methods - the name of the method, the key of its declaring
- * type, and the keys of the parameter types</li>
- * <li>constructors - the key of its declaring class, and the
- * keys of the parameter types</li>
- * <li>local variables - the name of the local variable, the index of the
- * declaring block relative to its parent, the key of its method</li>
- * <li>local types - the name of the type, the index of the declaring
- * block relative to its parent, the key of its method</li>
- * <li>anonymous types - the occurence count of the anonymous
- * type relative to its declaring type, the key of its declaring type</li>
- * <li>enum types - treated like classes</li>
- * <li>annotation types - treated like interfaces</li>
- * <li>type variables - the name of the type variable and
- * the key of the generic type or generic method that declares that
- * type variable</li>
- * <li>generic type instances - the key of the generic type and the keys
- * of the type arguments used to instantiate it, and whether the
- * instance is explicit (a parameterized type reference) or
- * implicit (a raw type reference)</li>
- * <li>generic method instances - the key of the generic method and the keys
- * of the type arguments used to instantiate it, and whether the
- * instance is explicit (a parameterized method reference) or
- * implicit (a raw method reference)</li>
- * <li>members of generic type instances - the key of the generic type
- * instance and the key of the corresponding member in the generic
- * type</li>
- * </ul>
- * </p>
- * <p>Note that the key for annotation bindings and member value pair bindings is
- * not yet implemented. This returns <code>null</code> for these 2 kinds of bindings.<br>
- * Recovered bindings have a unique key.
- * </p>
- *
- * @return the key for this binding
- */
- public String getKey();
-
- /**
- * There is no special definition of equality for bindings; equality is
- * simply object identity. Within the context of a single cluster of
- * bindings, each binding is represented by a distinct object. However,
- * between different clusters of bindings, the binding objects may or may
- * not be different; in these cases, the client should compare bindings
- * using {@link #isEqualTo(IBinding)}, which checks their keys.
- *
- * @param obj {@inheritDoc}
- * @return {@inheritDoc}
- */
- public boolean equals(Object obj);
-
- /**
- * Returns whether this binding has the same key as that of the given
- * binding. Within the context of a single cluster of bindings, each
- * binding is represented by a distinct object. However, between
- * different clusters of bindings, the binding objects may or may
- * not be different objects; in these cases, the binding keys
- * are used where available.
- *
- * @param binding the other binding, or <code>null</code>
- * @return <code>true</code> if the given binding is the identical
- * object as this binding, or if the keys of both bindings are the
- * same string; <code>false</code> if the given binding is
- * <code>null</code>, or if the bindings do not have the same key,
- * or if one or both of the bindings have no key
- * @see #getKey()
- *
- */
- public boolean isEqualTo(IBinding binding);
-
- /**
- * Returns a string representation of this binding suitable for debugging
- * purposes only.
- *
- * @return a debug string
- */
- public String toString();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IDocElement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IDocElement.java
deleted file mode 100644
index 8c89defd..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IDocElement.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.dom;
-
-/**
- * Internal marker-type interface used to tag node types that can legitimately
- * be included in {@link TagElement#fragments() TagElement.fragments()}.
- *
- * 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.
- */
-interface IDocElement {
- // marker-type interfaces have no members
-}
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
deleted file mode 100644
index fe870997..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IExtendedModifier.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.dom;
-
-/**
- * Common interface for AST nodes that represent modifiers or
- * annotations.
- * <pre>
- * ExtendedModifier:
- * Modifier
- * Annotation
- * </pre>
- *
- * 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 IExtendedModifier {
-
- /**
- * Returns whether this extended modifier is a standard modifier.
- *
- * @return <code>true</code> if this is a standard modifier
- * (instance of {@link Modifier}), and <code>false</code> otherwise
- */
- public boolean isModifier();
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IFunctionBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IFunctionBinding.java
deleted file mode 100644
index 6770fc67..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IFunctionBinding.java
+++ /dev/null
@@ -1,197 +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.core.dom;
-
-/**
- * A method binding represents a method or constructor of a class or interface.
- * Method bindings usually correspond directly to method or
- * constructor declarations found in the source code.
- * However, in certain cases of references to a generic method,
- * the method binding may correspond to a copy of a generic method
- * declaration with substitutions for the method's type parameters
- * (for these, <code>getTypeArguments</code> returns a non-empty
- * list, and either <code>isParameterizedMethod</code> or
- * <code>isRawMethod</code> returns <code>true</code>).
- * And in certain cases of references to a method declared in a
- * generic type, the method binding may correspond to a copy of a
- * method declaration with substitutions for the type's type
- * parameters (for these, <code>getTypeArguments</code> returns
- * an empty list, and both <code>isParameterizedMethod</code> and
- * <code>isRawMethod</code> return <code>false</code>).
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * @see ITypeBinding#getDeclaredMethods()
- *
- * 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 IFunctionBinding extends IBinding {
-
- /**
- * Returns whether this binding is for a constructor or a method.
- *
- * @return <code>true</code> if this is the binding for a constructor,
- * and <code>false</code> if this is the binding for a method
- */
- public boolean isConstructor();
-
- /**
- * Returns whether this binding is known to be a compiler-generated
- * default constructor.
- * <p>
- * This method returns <code>false</code> for:
- * <ul>
- * <li>methods</li>
- * <li>constructors with more than one parameter</li>
- * <li>0-argument constructors where the binding information was obtained
- * from a JavaScript source file containing an explicit 0-argument constructor
- * declaration</li>
- * <li>0-argument constructors where the binding information was obtained
- * from a JavaScript class file (it is not possible to determine from a
- * class file whether a 0-argument constructor was present in the source
- * code versus generated automatically by a JavaScript compiler)</li>
- * </ul>
- *
- * @return <code>true</code> if this is known to be the binding for a
- * compiler-generated default constructor, and <code>false</code>
- * otherwise
- *
- */
- public boolean isDefaultConstructor();
-
- /**
- * Returns the name of the method declared in this binding. The method name
- * is always a simple identifier. The name of a constructor is always the
- * same as the declared name of its declaring class.
- *
- * @return the name of this method, or the declared name of this
- * constructor's declaring class
- */
- public String getName();
-
- /**
- * Returns the type binding representing the class or interface
- * that declares this method or constructor.
- *
- * @return the binding of the class or interface that declares this method
- * or constructor
- */
- public ITypeBinding getDeclaringClass();
-
- /**
- * Returns the resolved default value of an annotation type member,
- * or <code>null</code> if the member has no default value, or if this
- * is not the binding for an annotation type member.
- * <p>
- * Resolved values are represented as follows (same as for
- * {@link IMemberValuePairBinding#getValue()}):
- * <ul>
- * <li>Primitive type - the equivalent boxed object</li>
- * <li>java.lang.Class - the <code>ITypeBinding</code> for the class object</li>
- * <li>java.lang.String - the string value itself</li>
- * <li>enum type - the <code>IVariableBinding</code> for the enum constant</li>
- * <li>annotation type - an <code>IAnnotationBinding</code></li>
- * <li>array type - an <code>Object[]</code> whose elements are as per above
- * (the language only allows single dimensional arrays in annotations)</li>
- * </ul>
- *
- * @return the default value of this annotation type member, or <code>null</code>
- * if none or not applicable
- *
- */
- public Object getDefaultValue();
-
-
- /**
- * Returns a list of type bindings representing the formal parameter types,
- * in declaration order, of this method or constructor. Returns an array of
- * length 0 if this method or constructor does not takes any parameters.
- * <p>
- * Note that the binding for the last parameter type of a vararg method
- * declaration like <code>void fun(Foo... args)</code> is always for
- * an array type (i.e., <code>Foo[]</code>) reflecting the the way varargs
- * get compiled. However, the type binding obtained directly from
- * the <code>SingleVariableDeclaration</code> for the vararg parameter
- * is always for the type as written; i.e., the type binding for
- * <code>Foo</code>.
- * </p>
- * <p>
- * Note: The result does not include synthetic parameters introduced by
- * inner class emulation.
- * </p>
- *
- * @return a (possibly empty) list of type bindings for the formal
- * parameters of this method or constructor
- */
- public ITypeBinding[] getParameterTypes();
-
- /**
- * Returns the binding for the return type of this method. Returns the
- * special primitive <code>void</code> return type for constructors.
- *
- * @return the binding for the return type of this method, or the
- * <code>void</code> return type for constructors
- */
- public ITypeBinding getReturnType();
-
- /**
- * Returns the binding for the method declaration corresponding to this
- * method binding. For parameterized methods ({@link #isParameterizedMethod()})
- * and raw methods ({@link #isRawMethod()}), this method returns the binding
- * for the corresponding generic method. For other method bindings, this
- * returns the same binding.
- *
- * <p>Note: The one notable exception is the method <code>Object.getClass()</code>,
- * which is declared to return <code>Class&lt;? extends Object&gt;</code>, but
- * when invoked its return type becomes <code>Class&lt;? extends
- * </code><em>R</em><code>&gt;</code>, where <em>R</em> is the compile type of
- * the receiver of the method invocation.</p>
- *
- * @return the method binding
- *
- */
- public IFunctionBinding getMethodDeclaration();
-
- /**
- * Returns whether this method's signature is a subsignature of the given method.
- *
- * @return <code>true</code> if this method's signature is a subsignature of the given method
- *
- */
- public boolean isSubsignature(IFunctionBinding otherMethod);
-
- /**
- * Returns whether this is a variable arity method.
- * <p>
- * Note: Variable arity ("varargs") methods were added in JLS3.
- * </p>
- *
- * @return <code>true</code> if this is a variable arity method,
- * and <code>false</code> otherwise
- *
- */
- public boolean isVarargs();
-
- /**
- * Returns whether this method overrides the given method.
- *
- * @param method the method that is possibly overridden
- * @return <code>true</code> if this method overrides the given method,
- * and <code>false</code> otherwise
- *
- */
- public boolean overrides(IFunctionBinding method);
-}
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
deleted file mode 100644
index d6231350..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IPackageBinding.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-/**
- * A package binding represents a named or unnamed package.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * <p><b>Note: This Class only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * 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 IPackageBinding extends IBinding {
-
- /**
- * Returns the name of the package represented by this binding. For named
- * packages, this is the fully qualified package name (using "." for
- * separators). For unnamed packages, this is an empty string.
- *
- * @return the name of the package represented by this binding, or
- * an empty string for an unnamed package
- */
- public String getName();
-
- /**
- * Returns whether this package is an unnamed package.
- *
- * @return <code>true</code> if this is an unnamed package, and
- * <code>false</code> otherwise
- */
- public boolean isUnnamed();
-
- /**
- * Returns the list of name component making up the name of the package
- * represented by this binding. For example, for the package named
- * "com.example.tool", this method returns {"com", "example", "tool"}.
- * Returns the empty list for unnamed packages.
- *
- * @return the name of the package represented by this binding, or the
- * empty list for unnamed packages
- */
- public String[] getNameComponents();
-
-// /**
-// * Finds and returns the binding for the class or interface with the given
-// * name declared in this package.
-// * <p>
-// * For top-level classes and interfaces, the name here is just the simple
-// * name of the class or interface. For nested classes and interfaces, the
-// * name is the VM class name (in other words, a name like
-// * <code>"Outer$Inner"</code> as used to name the class file; see
-// * <code>ITypeBinding.getName</code>).
-// * </p>
-// *
-// * @param name the name of a class or interface
-// * @return the type binding for the class or interface with the
-// * given name declared in this package, or <code>null</code>
-// * if there is no such type
-// */
-// public ITypeBinding findTypeBinding(String name);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ITypeBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ITypeBinding.java
deleted file mode 100644
index b4be6bdb..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ITypeBinding.java
+++ /dev/null
@@ -1,612 +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.core.dom;
-
-/**
- * A type binding represents fully-resolved type. There are a number of
- * different kinds of type bindings:
- * <ul>
- * <li>a class - represents the class declaration;
- * possibly with type parameters</li>
- * <li>an interface - represents the class declaration;
- * possibly with type parameters</li>
- * <li>an enum - represents the enum declaration (enum types do not have
- * have type parameters)</li>
- * <li>an annotation - represents the annotation type declaration
- * (annotation types do not have have type parameters)</li>
- * <li>an array type - array types are referenced but not explicitly
- * declared</li>
- * <li>a primitive type (including the special return type <code>void</code>)
- * - primitive types are referenced but not explicitly declared</li>
- * <li>the null type - this is the special type of <code>null</code></li>
- * <li>a type variable - represents the declaration of a type variable;
- * possibly with type bounds</li>
- * <li>a raw type - represents a legacy non-parameterized reference to
- * a generic type</li>
- * <li>a parameterized type - represents an copy of a type declaration
- * with substitutions for its type parameters</li>
- * <li>a capture - represents a capture binding</li>
- * </ul>
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * @see ITypeBinding#getDeclaredTypes()
- *
- * 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 ITypeBinding extends IBinding {
-
-
- /**
- * Answer an array type binding using the receiver and the given dimension.
- *
- * <p>If the receiver is an array binding, then the resulting dimension is the given dimension
- * plus the dimension of the receiver. Otherwise the resulting dimension is the given
- * dimension.</p>
- *
- * @param dimension the given dimension
- * @return an array type binding
- * @throws IllegalArgumentException:<ul>
- * <li>if the receiver represents the void type</li>
- * <li>if the resulting dimensions is lower than one or greater than 255</li>
- * </ul>
- *
- */
- public ITypeBinding createArrayType(int dimension);
-
- /**
- * Returns the binary name of this type binding.
- * <p>
- * Note that in some cases, the binary name may be unavailable.
- * This may happen, for example, for a local type declared in
- * unreachable code.
- * </p>
- *
- * @return the binary name of this type, or <code>null</code>
- * if the binary name is unknown
- *
- */
- public String getBinaryName();
-
- /**
- * Returns the binding representing the component type of this array type,
- * or <code>null</code> if this is not an array type binding. The component
- * type of an array might be an array type.
- * <p>This is subject to change before 3.2 release.</p>
- *
- * @return the component type binding, or <code>null</code> if this is
- * not an array type
- *
- */
- public ITypeBinding getComponentType();
-
- /**
- * Returns a list of bindings representing all the fields declared
- * as members of this class, interface, or enum type.
- *
- * <p>These include public, protected, default (package-private) access,
- * and private fields declared by the class, but excludes inherited fields.
- * Synthetic fields may or may not be included. Fields from binary types that
- * reference unresolvable types may not be included.</p>
- *
- * <p>Returns an empty list if the class, interface, or enum declares no fields,
- * and for other kinds of type bindings that do not directly have members.</p>
- *
- * <p>The resulting bindings are in no particular order.</p>
- *
- * @return the list of bindings for the field members of this type,
- * or the empty list if this type does not have field members
- */
- public IVariableBinding[] getDeclaredFields();
-
- /**
- * Returns a list of method bindings representing all the methods and
- * constructors declared for this class, interface, enum, or annotation
- * type.
- * <p>These include public, protected, default (package-private) access,
- * and private methods Synthetic methods and constructors may or may not be
- * included. Returns an empty list if the class, interface, or enum,
- * type declares no methods or constructors, if the annotation type declares
- * no members, or if this type binding represents some other kind of type
- * binding. Methods from binary types that reference unresolvable types may
- * not be included.</p>
- * <p>The resulting bindings are in no particular order.</p>
- *
- * @return the list of method bindings for the methods and constructors
- * declared by this class, interface, enum type, or annotation type,
- * or the empty list if this type does not declare any methods or constructors
- */
- public IFunctionBinding[] getDeclaredMethods();
-
- /**
- * Returns the declared modifiers for this class or interface binding
- * as specified in the original source declaration of the class or
- * interface. The result may not correspond to the modifiers in the compiled
- * binary, since the validator may change them (in particular, for inner
- * class emulation). The <code>getModifiers</code> method should be used if
- * the compiled modifiers are needed. Returns -1 if this type does not
- * represent a class or interface.
- *
- * @return the bit-wise or of <code>Modifier</code> constants
- * @see #getModifiers()
- * @see Modifier
- */
- public int getDeclaredModifiers();
-
- /**
- * Returns a list of type bindings representing all the types declared as
- * members of this class, interface, or enum type.
- * These include public, protected, default (package-private) access,
- * and private classes, interfaces, enum types, and annotation types
- * declared by the type, but excludes inherited types. Returns an empty
- * list if the type declares no type members, or if this type
- * binding represents an array type, a primitive type, a type variable,
- * a capture, or the null type.
- * The resulting bindings are in no particular order.
- *
- * @return the list of type bindings for the member types of this type,
- * or the empty list if this type does not have member types
- */
- public ITypeBinding[] getDeclaredTypes();
-
- /**
- * Returns the type binding representing the class, interface, or enum
- * that declares this binding.
- * <p>
- * The declaring class of a member class, interface, enum, annotation
- * type is the class, interface, or enum type of which it is a member.
- * The declaring class of a local class or interface (including anonymous
- * classes) is the innermost class or interface containing the expression
- * or statement in which this type is declared.
- * </p>
- * <p>The declaring class of a type variable is the class in which the type
- * variable is declared if it is declared on a type. It returns
- * <code>null</code> otherwise.
- * </p>
- * <p>The declaring class of a capture binding is the innermost class or
- * interface containing the expression or statement in which this capture is
- * declared.
- * </p>
- * <p>Array types, primitive types, the null type, top-level types,
- * recovered binding have no declaring class.
- * </p>
- *
- * @return the binding of the type that declares this type, or
- * <code>null</code> if none
- */
- public ITypeBinding getDeclaringClass();
-
- /**
- * Returns the method binding representing the method that declares this binding
- * of a local type or type variable.
- * <p>
- * The declaring method of a local class or interface (including anonymous
- * classes) is the innermost method containing the expression or statement in
- * which this type is declared. Returns <code>null</code> if the type
- * is declared in an initializer.
- * </p>
- * <p>
- * The declaring method of a type variable is the method in which the type
- * variable is declared if it is declared on a method. It
- * returns <code>null</code> otherwise.
- * </p>
- * <p>Array types, primitive types, the null type, top-level types,
- * capture bindings, and recovered binding have no
- * declaring method.
- * </p>
- *
- * @return the binding of the method that declares this type, or
- * <code>null</code> if none
- *
- */
- public IFunctionBinding getDeclaringMethod();
-
- /**
- * Returns the dimensionality of this array type, or <code>0</code> if this
- * is not an array type binding.
- *
- * @return the number of dimension of this array type binding, or
- * <code>0</code> if this is not an array type
- */
- public int getDimensions();
-
- /**
- * Returns the binding representing the element type of this array type,
- * or <code>null</code> if this is not an array type binding. The element
- * type of an array is never itself an array type.
- *
- * @return the element type binding, or <code>null</code> if this is
- * not an array type
- */
- public ITypeBinding getElementType();
-
- /**
- * Returns the erasure of this type binding.
- * <ul>
- * <li>For parameterized types ({@link #isParameterizedType()})
- * - returns the binding for the corresponding generic type.</li>
- * <li>For raw types ({@link #isRawType()})
- * - returns the binding for the corresponding generic type.</li>
- * java.lang.Object in other cases.</li>
- * <li>For type variables ({@link #isTypeVariable()})
- * - returns the binding for the erasure of the leftmost bound
- * if it has bounds and java.lang.Object if it does not.</li>
- * <li>For captures ({@link #isCapture()})
- * - returns the binding for the erasure of the leftmost bound
- * if it has bounds and java.lang.Object if it does not.</li>
- * <li>For array types ({@link #isArray()}) - returns an array type of
- * the same dimension ({@link #getDimensions()}) as this type
- * binding for which the element type is the erasure of the element type
- * ({@link #getElementType()}) of this type binding.</li>
- * <li>For all other type bindings - returns the identical binding.</li>
- * </ul>
- *
- * @return the erasure type binding
- *
- */
- public ITypeBinding getErasure();
-
- /**
- * Returns the compiled modifiers for this class, interface, enum,
- * or annotation type binding.
- * The result may not correspond to the modifiers as declared in the
- * original source, since the validator may change them (in particular,
- * for inner class emulation). The <code>getDeclaredModifiers</code> method
- * should be used if the original modifiers are needed.
- * Returns 0 if this type does not represent a class, an interface, an enum, an annotation
- * type or a recovered type.
- *
- * @return the compiled modifiers for this type binding or 0
- * if this type does not represent a class, an interface, an enum, an annotation
- * type or a recovered type.
- * @see #getDeclaredModifiers()
- */
- public int getModifiers();
-
- /**
- * Returns the unqualified name of the type represented by this binding
- * if it has one.
- * <ul>
- * <li>For top-level types, member types, and local types,
- * the name is the simple name of the type.
- * Example: <code>"String"</code> or <code>"Collection"</code>.
- * Note that the type parameters of a generic type are not included.</li>
- * <li>For primitive types, the name is the keyword for the primitive type.
- * Example: <code>"int"</code>.</li>
- * <li>For the null type, the name is the string "null".</li>
- * <li>For anonymous classes, which do not have a name,
- * this method returns an empty string.</li>
- * <li>For array types, the name is the unqualified name of the component
- * type (as computed by this method) followed by "[]".
- * Example: <code>"String[]"</code>. Note that the component type is never an
- * an anonymous class.</li>
- * <li>For type variables, the name is just the simple name of the
- * type variable (type bounds are not included).
- * Example: <code>"X"</code>.</li>
- * <li>For type bindings that correspond to particular instances of a generic
- * type arising from a parameterized type reference,
- * the name is the unqualified name of the erasure type (as computed by this method)
- * followed by the names (again, as computed by this method) of the type arguments
- * surrounded by "&lt;&gt;" and separated by ",".
- * Example: <code>"Collection&lt;String&gt;"</code>.
- * </li>
- * <li>For type bindings that correspond to particular instances of a generic
- * type arising from a raw type reference, the name is the unqualified name of
- * the erasure type (as computed by this method).
- * Example: <code>"Collection"</code>.</li>
- * <li>Capture types do not have a name. For these types,
- * and array types thereof, this method returns an empty string.</li>
- * </ul>
- *
- * @return the unqualified name of the type represented by this binding,
- * or the empty string if it has none
- * @see #getQualifiedName()
- */
- public String getName();
-
- /**
- * Returns the binding for the package in which this type is declared.
- *
- * <p>The package of a recovered type reference binding is the package of the
- * enclosing type.</p>
- *
- * @return the binding for the package in which this class, interface,
- * enum, or annotation type is declared, or <code>null</code> if this type
- * binding represents a primitive type, an array type, the null type,
- * a type variable, a capture binding.
- */
- public IPackageBinding getPackage();
-
- /**
- * Returns the fully qualified name of the type represented by this
- * binding if it has one.
- * <ul>
- * <li>For top-level types, the fully qualified name is the simple name of
- * the type preceded by the package name (or unqualified if in a default package)
- * and a ".".
- * Example: <code>"java.lang.String"</code> or <code>"java.util.Collection"</code>.
- * Note that the type parameters of a generic type are not included.</li>
- * <li>For members of top-level types, the fully qualified name is the
- * simple name of the type preceded by the fully qualified name of the
- * enclosing type (as computed by this method) and a ".".
- * Example: <code>"java.io.ObjectInputStream.GetField"</code>.
- * If the binding is for a member type that corresponds to a particular instance
- * of a generic type arising from a parameterized type reference, the simple
- * name of the type is followed by the fully qualified names of the type arguments
- * (as computed by this method) surrounded by "&lt;&gt;" and separated by ",".
- * Example: <code>"pkg.Outer.Inner&lt;java.lang.String&gt;"</code>.
- * </li>
- * <li>For primitive types, the fully qualified name is the keyword for
- * the primitive type.
- * Example: <code>"int"</code>.</li>
- * <li>For the null type, the fully qualified name is the string
- * "null".</li>
- * <li>Local types (including anonymous classes) and members of local
- * types do not have a fully qualified name. For these types, and array
- * types thereof, this method returns an empty string.</li>
- * <li>For array types whose component type has a fully qualified name,
- * the fully qualified name is the fully qualified name of the component
- * type (as computed by this method) followed by "[]".
- * Example: <code>"java.lang.String[]"</code>.</li>
- * <li>For type variables, the fully qualified name is just the name of the
- * type variable (type bounds are not included).
- * Example: <code>"X"</code>.</li>
- * <li>For type bindings that correspond to particular instances of a generic
- * type arising from a parameterized type reference,
- * the fully qualified name is the fully qualified name of the erasure
- * type followed by the fully qualified names of the type arguments surrounded by "&lt;&gt;" and separated by ",".
- * Example: <code>"java.util.Collection&lt;java.lang.String&gt;"</code>.
- * </li>
- * <li>For type bindings that correspond to particular instances of a generic
- * type arising from a raw type reference,
- * the fully qualified name is the fully qualified name of the erasure type.
- * Example: <code>"java.util.Collection"</code>. Note that the
- * the type parameters are omitted.</li>
- * <li>Capture types do not have a fully qualified name. For these types,
- * and array types thereof, this method returns an empty string.</li>
- * </ul>
- *
- * @return the fully qualified name of the type represented by this
- * binding, or the empty string if it has none
- * @see #getName()
- *
- */
- public String getQualifiedName();
-
- /**
- * Returns the type binding for the superclass of the type represented
- * by this class binding.
- * <p>
- * If this type binding represents any class other than the class
- * <code>java.lang.Object</code>, then the type binding for the direct
- * superclass of this class is returned. If this type binding represents
- * the class <code>java.lang.Object</code>, then <code>null</code> is
- * returned.
- * <p>
- * Loops that ascend the class hierarchy need a suitable termination test.
- * Rather than test the superclass for <code>null</code>, it is more
- * transparent to check whether the class is <code>Object</code>, by
- * comparing whether the class binding is identical to
- * <code>ast.resolveWellKnownType("java.lang.Object")</code>.
- * </p>
- * <p>
- * If this type binding represents an interface, an array type, a
- * primitive type, the null type, a type variable, an enum type,
- * an annotation type, or a capture binding then
- * <code>null</code> is returned.
- * </p>
- *
- * @return the superclass of the class represented by this type binding,
- * or <code>null</code> if none
- * @see AST#resolveWellKnownType(String)
- */
- public ITypeBinding getSuperclass();
-
- /**
- * Returns the binding for the type declaration corresponding to this type
- * binding.
- * <p>For parameterized types ({@link #isParameterizedType()})
- * and most raw types ({@link #isRawType()}), this method returns the binding
- * for the corresponding generic type.</p>
- * <p>For raw member types ({@link #isRawType()}, {@link #isMember()})
- * of a raw declaring class, the type declaration is a generic or a non-generic
- * type.</p>
- * <p>A different non-generic binding will be returned when one of the declaring
- * types/methods was parameterized.</p>
- * <p>For other type bindings, this returns the same binding.</p>
- *
- * @return the type binding
- *
- */
- public ITypeBinding getTypeDeclaration();
-
- /**
- * Returns whether this type binding represents an anonymous class.
- * <p>
- * An anonymous class is a subspecies of local class, and therefore mutually
- * exclusive with member types. Note that anonymous classes have no name
- * (<code>getName</code> returns the empty string).
- * </p>
- *
- * @return <code>true</code> if this type binding is for an anonymous class,
- * and <code>false</code> otherwise
- */
- public boolean isAnonymous();
-
- /**
- * Returns whether this type binding represents an array type.
- *
- * @return <code>true</code> if this type binding is for an array type,
- * and <code>false</code> otherwise
- * @see #getElementType()
- * @see #getDimensions()
- */
- public boolean isArray();
-
- /**
- * Returns whether an expression of this type can be assigned to a variable
- * of the given type.
- *
- * <p>If the receiver or the argument is a recovered type, the answer is always false,
- * unless the two types are identical or the argument is <code>java.lang.Object</code>.</p>
- *
- * @param variableType the type of a variable to check compatibility against
- * @return <code>true</code> if an expression of this type can be assigned to a
- * variable of the given type, and <code>false</code> otherwise
- *
- */
- public boolean isAssignmentCompatible(ITypeBinding variableType);
-
- /**
- * Returns whether this type is cast compatible with the given type.
- * <p>
- * NOTE: The cast compatibility check performs backwards.
- * When testing whether type B can be cast to type A, one would use:
- * <code>A.isCastCompatible(B)</code>
- * </p>
- *
- * <p>If the receiver or the argument is a recovered type, the answer is always false,
- * unless the two types are identical or the argument is <code>java.lang.Object</code>.</p>
- *
- * @param type the type to check compatibility against
- * @return <code>true</code> if this type is cast compatible with the
- * given type, and <code>false</code> otherwise
- *
- */
- public boolean isCastCompatible(ITypeBinding type);
-
- /**
- * Returns whether this type binding represents a class type or a recovered binding.
- *
- * @return <code>true</code> if this object represents a class or a recovered binding,
- * and <code>false</code> otherwise
- */
- public boolean isClass();
-
- /**
- * Returns whether this type binding originated in source code.
- * Returns <code>false</code> for all primitive types, the null type,
- * array types, and for all classes, interfaces, enums, annotation
- * types, type variables, parameterized type references,
- * raw type references, and capture bindings
- * whose information came from a pre-compiled binary class file.
- *
- * @return <code>true</code> if the type is in source code,
- * and <code>false</code> otherwise
- */
- public boolean isFromSource();
-
- /**
- * Returns whether this type binding represents a local class.
- * <p>
- * A local class is any nested class or enum type not declared as a member
- * of another class or interface. A local class is a subspecies of nested
- * type, and mutually exclusive with member types. Note that anonymous
- * classes are a subspecies of local classes.
- * </p>
- * <p>
- * Also note that interfaces and annotation types cannot be local.
- * </p>
- *
- * @return <code>true</code> if this type binding is for a local class or
- * enum type, and <code>false</code> otherwise
- */
- public boolean isLocal();
-
- /**
- * Returns whether this type binding represents a member class or
- * interface.
- * <p>
- * A member type is any type declared as a member of
- * another type. A member type is a subspecies of nested
- * type, and mutually exclusive with local types.
- * </p>
- *
- * @return <code>true</code> if this type binding is for a member class,
- * interface, enum, or annotation type, and <code>false</code> otherwise
- */
- public boolean isMember();
-
- /**
- * Returns whether this type binding represents a nested class, interface,
- * enum, or annotation type.
- * <p>
- * A nested type is any type whose declaration occurs within
- * the body of another. The set of nested types is disjoint from the set of
- * top-level types. Nested types further subdivide into member types, local
- * types, and anonymous types.
- * </p>
- *
- * @return <code>true</code> if this type binding is for a nested class,
- * interface, enum, or annotation type, and <code>false</code> otherwise
- */
- public boolean isNested();
-
- /**
- * Returns whether this type binding represents the null type.
- * <p>
- * The null type is the type of a <code>NullLiteral</code> node.
- * </p>
- *
- * @return <code>true</code> if this type binding is for the null type,
- * and <code>false</code> otherwise
- */
- public boolean isNullType();
-
- /**
- * Returns whether this type binding represents a primitive type.
- * <p>
- * There are nine predefined type bindings to represent the eight primitive
- * types and <code>void</code>. These have the same names as the primitive
- * types that they represent, namely boolean, byte, char, short, int,
- * long, float, and double, and void.
- * </p>
- *
- * @return <code>true</code> if this type binding is for a primitive type,
- * and <code>false</code> otherwise
- */
- public boolean isPrimitive();
-
- /**
- * Returns whether this type is subtype compatible with the given type.
- *
- * <p>If the receiver or the argument is a recovered type, the answer is always false,
- * unless the two types are identical or the argument is <code>java.lang.Object</code>.</p>
- *
- * @param type the type to check compatibility against
- * @return <code>true</code> if this type is subtype compatible with the
- * given type, and <code>false</code> otherwise
- *
- */
- public boolean isSubTypeCompatible(ITypeBinding type);
-
- /**
- * Returns whether this type binding represents a top-level class,
- * interface, enum, or annotation type.
- * <p>
- * A top-level type is any type whose declaration does not occur within the
- * body of another type declaration. The set of top level types is disjoint
- * from the set of nested types.
- * </p>
- *
- * @return <code>true</code> if this type binding is for a top-level class,
- * interface, enum, or annotation type, and <code>false</code> otherwise
- */
- public boolean isTopLevel();
-
- public boolean isCompilationUnit();
-
-}
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
deleted file mode 100644
index 2f6e76b3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IVariableBinding.java
+++ /dev/null
@@ -1,158 +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.core.dom;
-
-/**
- * A variable binding represents either a field of a class or interface, or
- * a local variable declaration (including formal parameters, local variables,
- * and exception variables).
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * @see ITypeBinding#getDeclaredFields()
- *
- * 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 IVariableBinding extends IBinding {
-
- /**
- * Returns whether this binding is for a field.
- * Note that this method returns <code>true</code> for constants,
- * including enum constants. This method returns <code>false</code>
- * for local variables.
- *
- * @return <code>true</code> if this is the binding for a field,
- * and <code>false</code> otherwise
- */
- public boolean isField();
-
- public boolean isGlobal();
-
- /**
- * Returns whether this binding corresponds to a parameter.
- *
- * @return <code>true</code> if this is the binding for a parameter,
- * and <code>false</code> otherwise
- *
- */
- public boolean isParameter();
-
- /**
- * Returns the name of the field or local variable declared in this binding.
- * The name is always a simple identifier.
- *
- * @return the name of this field or local variable
- */
- public String getName();
-
- /**
- * Returns the type binding representing the class or interface
- * that declares this field.
- * <p>
- * The declaring class of a field is the class or interface of which it is
- * a member. Local variables have no declaring class. The field length of an
- * array type has no declaring class.
- * </p>
- *
- * @return the binding of the class or interface that declares this field,
- * or <code>null</code> if none
- */
- public ITypeBinding getDeclaringClass();
-
- /**
- * Returns the binding for the type of this field or local variable.
- *
- * @return the binding for the type of this field or local variable
- */
- public ITypeBinding getType();
-
- /**
- * Returns a small integer variable id for this variable binding.
- * <p>
- * <b>Local variables inside methods:</b> Local variables (and parameters)
- * declared within a single method are assigned ascending ids in normal
- * code reading order; var1.getVariableId()&lt;var2.getVariableId() means that var1 is
- * declared before var2.
- * </p>
- * <p>
- * <b>Local variables outside methods:</b> Local variables declared in a
- * type's static initializers (or initializer expressions of static fields)
- * are assigned ascending ids in normal code reading order. Local variables
- * declared in a type's instance initializers (or initializer expressions
- * of non-static fields) are assigned ascending ids in normal code reading
- * order. These ids are useful when checking definite assignment for
- * static initializers (JLS 16.7) and instance initializers (JLS 16.8),
- * respectively.
- * </p>
- * <p>
- * <b>Fields:</b> Fields declared as members of a type are assigned
- * ascending ids in normal code reading order;
- * field1.getVariableId()&lt;field2.getVariableId() means that field1 is declared before
- * field2.
- * </p>
- *
- * @return a small non-negative variable id
- */
- public int getVariableId();
-
- /**
- * Returns this binding's constant value if it has one.
- * Some variables may have a value computed at compile-time. If the type of
- * the value is a primitive type, the result is the boxed equivalent (i.e.,
- * int returned as an <code>Integer</code>). If the type of the value is
- * <code>String</code>, the result is the string itself. If the variable has
- * no compile-time computed value, the result is <code>null</code>.
- * (Note: compile-time constant expressions cannot denote <code>null</code>;
- * JLS2 15.28.). The result is always <code>null</code> for enum constants.
- *
- * @return the constant value, or <code>null</code> if none
- *
- */
- public Object getConstantValue();
-
- /**
- * Returns the method binding representing the method containing the scope
- * in which this local variable is declared.
- * <p>
- * The declaring method of a method formal parameter is the method itself.
- * For a local variable declared somewhere within the body of a method,
- * the declaring method is the enclosing method. When local or anonymous
- * classes are involved, the declaring method is the innermost such method.
- * There is no declaring method for a field, or for a local variable
- * declared in a static or instance initializer; this method returns
- * <code>null</code> in those cases.
- * </p>
- *
- * @return the binding of the method or constructor that declares this
- * local variable, or <code>null</code> if none
- *
- */
- public IFunctionBinding getDeclaringMethod();
-
- /**
- * Returns the binding for the variable declaration corresponding to this
- * variable binding. For a binding for a field declaration in an instance
- * of a generic type, this method returns the binding for the corresponding
- * field declaration in the generic type. For other variable bindings,
- * including all ones for local variables and parameters, this method
- * returns the same binding.
- *
- * @return the variable binding for the originating declaration
- *
- */
- public IVariableBinding getVariableDeclaration();
-
-}
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
deleted file mode 100644
index 21ee68bb..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IfStatement.java
+++ /dev/null
@@ -1,351 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * If statement AST node type.
- * <pre>
- * IfStatement:
- * <b>if</b> <b>(</b> Expression <b>)</b> Statement [ <b>else</b> Statement]
- * </pre>
- *
- *
- * 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 IfStatement extends Statement {
-
- /**
- * The "expression" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor EXPRESSION_PROPERTY =
- new ChildPropertyDescriptor(IfStatement.class, "expression", Expression.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "thenStatement" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor THEN_STATEMENT_PROPERTY =
- new ChildPropertyDescriptor(IfStatement.class, "thenStatement", Statement.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "elseStatement" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor ELSE_STATEMENT_PROPERTY =
- new ChildPropertyDescriptor(IfStatement.class, "elseStatement", Statement.class, OPTIONAL, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List properyList = new ArrayList(4);
- createPropertyList(IfStatement.class, properyList);
- addProperty(EXPRESSION_PROPERTY, properyList);
- addProperty(THEN_STATEMENT_PROPERTY, properyList);
- addProperty(ELSE_STATEMENT_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The expression; lazily initialized; defaults to an unspecified, but
- * legal, expression.
- */
- private Expression expression = null;
-
- /**
- * The then statement; lazily initialized; defaults to an unspecified, but
- * legal, statement.
- */
- private Statement thenStatement = null;
-
- /**
- * The else statement; <code>null</code> for none; defaults to none.
- */
- private Statement optionalElseStatement = null;
-
- /**
- * Creates a new unparented if statement node owned by the given
- * AST. By default, the expresssion is unspecified,
- * but legal, the then statement is an empty block, and there is no else
- * statement.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- IfStatement(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == EXPRESSION_PROPERTY) {
- if (get) {
- return getExpression();
- } else {
- setExpression((Expression) child);
- return null;
- }
- }
- if (property == THEN_STATEMENT_PROPERTY) {
- if (get) {
- return getThenStatement();
- } else {
- setThenStatement((Statement) child);
- return null;
- }
- }
- if (property == ELSE_STATEMENT_PROPERTY) {
- if (get) {
- return getElseStatement();
- } else {
- setElseStatement((Statement) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return IF_STATEMENT;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- IfStatement result = new IfStatement(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.copyLeadingComment(this);
- result.setExpression((Expression) getExpression().clone(target));
- result.setThenStatement(
- (Statement) getThenStatement().clone(target));
- result.setElseStatement(
- (Statement) ASTNode.copySubtree(target, getElseStatement()));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChild(visitor, getExpression());
- acceptChild(visitor, getThenStatement());
- acceptChild(visitor, getElseStatement());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the expression of this if statement.
- *
- * @return the expression node
- */
- public Expression getExpression() {
- if (this.expression == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.expression == null) {
- preLazyInit();
- this.expression = new SimpleName(this.ast);
- postLazyInit(this.expression, EXPRESSION_PROPERTY);
- }
- }
- }
- return this.expression;
- }
-
- /**
- * Sets the condition of this if statement.
- *
- * @param expression the expression node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setExpression(Expression expression) {
- if (expression == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.expression;
- preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY);
- this.expression = expression;
- postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY);
- }
-
- /**
- * Returns the "then" part of this if statement.
- *
- * @return the "then" statement node
- */
- public Statement getThenStatement() {
- if (this.thenStatement == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.thenStatement == null) {
- preLazyInit();
- this.thenStatement = new Block(this.ast);
- postLazyInit(this.thenStatement, THEN_STATEMENT_PROPERTY);
- }
- }
- }
- return this.thenStatement;
- }
-
- /**
- * Sets the "then" part of this if statement.
- * <p>
- * Special note: The JavaScript language does not allow a local variable declaration
- * to appear as the "then" part of an if statement (they may only appear within a
- * block). However, the AST will allow a <code>VariableDeclarationStatement</code>
- * as the thenStatement of a <code>IfStatement</code>. To get something that will
- * compile, be sure to embed the <code>VariableDeclarationStatement</code>
- * inside a <code>Block</code>.
- * </p>
- *
- * @param statement the "then" statement node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setThenStatement(Statement statement) {
- if (statement == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.thenStatement;
- preReplaceChild(oldChild, statement, THEN_STATEMENT_PROPERTY);
- this.thenStatement = statement;
- postReplaceChild(oldChild, statement, THEN_STATEMENT_PROPERTY);
- }
-
- /**
- * Returns the "else" part of this if statement, or <code>null</code> if
- * this if statement has <b>no</b> "else" part.
- * <p>
- * Note that there is a subtle difference between having no else
- * statement and having an empty statement ("{}") or null statement (";").
- * </p>
- *
- * @return the "else" statement node, or <code>null</code> if none
- */
- public Statement getElseStatement() {
- return this.optionalElseStatement;
- }
-
- /**
- * Sets or clears the "else" part of this if statement.
- * <p>
- * Note that there is a subtle difference between having no else part
- * (as in <code>"if(true){}"</code>) and having an empty block (as in
- * "if(true){}else{}") or null statement (as in "if(true){}else;").
- * </p>
- * <p>
- * Special note: The JavaScript language does not allow a local variable declaration
- * to appear as the "else" part of an if statement (they may only appear within a
- * block). However, the AST will allow a <code>VariableDeclarationStatement</code>
- * as the elseStatement of a <code>IfStatement</code>. To get something that will
- * compile, be sure to embed the <code>VariableDeclarationStatement</code>
- * inside a <code>Block</code>.
- * </p>
- *
- * @param statement the "else" statement node, or <code>null</code> if
- * there is none
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setElseStatement(Statement statement) {
- ASTNode oldChild = this.optionalElseStatement;
- preReplaceChild(oldChild, statement, ELSE_STATEMENT_PROPERTY);
- this.optionalElseStatement = statement;
- postReplaceChild(oldChild, statement, ELSE_STATEMENT_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return super.memSize() + 3 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.expression == null ? 0 : getExpression().treeSize())
- + (this.thenStatement == null ? 0 : getThenStatement().treeSize())
- + (this.optionalElseStatement == null ? 0 : getElseStatement().treeSize());
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ImportDeclaration.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ImportDeclaration.java
deleted file mode 100644
index 5e92bfb2..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ImportDeclaration.java
+++ /dev/null
@@ -1,411 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Import declaration AST node type.
- *
- * For JLS2:
- * <pre>
- * ImportDeclaration:
- * <b>import</b> Name [ <b>.</b> <b>*</b> ] <b>;</b>
- * </pre>
- * For JLS3, static was added:
- * <pre>
- * ImportDeclaration:
- * <b>import</b> [ <b>static</b> ] Name [ <b>.</b> <b>*</b> ] <b>;</b>
- * </pre>
- *
- * <p><b>Note: This Class only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * 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 ImportDeclaration extends ASTNode {
-
- /**
- * The "name" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor NAME_PROPERTY =
- new ChildPropertyDescriptor(ImportDeclaration.class, "name", Name.class, MANDATORY, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "onDemand" structural property of this node type.
- *
- */
- public static final SimplePropertyDescriptor ON_DEMAND_PROPERTY =
- new SimplePropertyDescriptor(ImportDeclaration.class, "onDemand", boolean.class, MANDATORY); //$NON-NLS-1$
-
- /**
- * The "static" structural property of this node type (added in JLS3 API).
- *
- */
- public static final SimplePropertyDescriptor STATIC_PROPERTY =
- new SimplePropertyDescriptor(ImportDeclaration.class, "static", boolean.class, MANDATORY); //$NON-NLS-1$
-
-
- public static final SimplePropertyDescriptor ISFILE_PROPERTY =
- new SimplePropertyDescriptor(ImportDeclaration.class, "isFile", boolean.class, MANDATORY); //$NON-NLS-1$
-
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS_2_0;
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS_3_0;
-
- static {
- List properyList = new ArrayList(3);
- createPropertyList(ImportDeclaration.class, properyList);
- addProperty(NAME_PROPERTY, properyList);
- addProperty(ON_DEMAND_PROPERTY, properyList);
- addProperty(ISFILE_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS_2_0 = reapPropertyList(properyList);
-
- properyList = new ArrayList(4);
- createPropertyList(ImportDeclaration.class, properyList);
- addProperty(STATIC_PROPERTY, properyList);
- addProperty(NAME_PROPERTY, properyList);
- addProperty(ON_DEMAND_PROPERTY, properyList);
- addProperty(ISFILE_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS_3_0 = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- if (apiLevel == AST.JLS2_INTERNAL) {
- return PROPERTY_DESCRIPTORS_2_0;
- } else {
- return PROPERTY_DESCRIPTORS_3_0;
- }
- }
-
- /**
- * The import name; lazily initialized; defaults to a unspecified,
- * legal JavaScript identifier.
- */
- private Name importName = null;
-
- /**
- * On demand versus single type import; defaults to single type import.
- */
- private boolean onDemand = false;
-
- /**
- * Static versus regular; defaults to regular import.
- * Added in JLS3; not used in JLS2.
- *
- */
- private boolean isStatic = false;
-
- private boolean isFile = false;
- /**
- * Creates a new AST node for an import declaration owned by the
- * given AST. The import declaration initially is a regular (non-static)
- * single type import for an unspecified, but legal, JavaScript type name.
- * <p>
- * N.B. This constructor is package-private; all subclasses must be
- * declared in the same package; clients are unable to declare
- * additional subclasses.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- ImportDeclaration(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean internalGetSetBooleanProperty(SimplePropertyDescriptor property, boolean get, boolean value) {
- if (property == ON_DEMAND_PROPERTY) {
- if (get) {
- return isOnDemand();
- } else {
- setOnDemand(value);
- return false;
- }
- }
- if (property == STATIC_PROPERTY) {
- if (get) {
- return isStatic();
- } else {
- setStatic(value);
- return false;
- }
- }
- if (property == ISFILE_PROPERTY) {
- if (get) {
- return isFileImport();
- } else {
- setIsFileImport(value);
- return false;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetBooleanProperty(property, get, value);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == NAME_PROPERTY) {
- if (get) {
- return getName();
- } else {
- setName((Name) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return IMPORT_DECLARATION;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- ImportDeclaration result = new ImportDeclaration(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setOnDemand(isOnDemand());
- result.setIsFileImport(isFileImport());
- if (this.ast.apiLevel >= AST.JLS3) {
- result.setStatic(isStatic());
- }
- result.setName((Name) getName().clone(target));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- acceptChild(visitor, getName());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the name imported by this declaration.
- * <p>
- * For a regular on-demand import, this is the name of a package.
- * For a static on-demand import, this is the qualified name of
- * a type. For a regular single-type import, this is the qualified name
- * of a type. For a static single-type import, this is the qualified name
- * of a static member of a type.
- * </p>
- *
- * @return the imported name node
- */
- public Name getName() {
- if (this.importName == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.importName == null) {
- preLazyInit();
- this.importName =this.ast.newQualifiedName(
- new SimpleName(this.ast), new SimpleName(this.ast));
- postLazyInit(this.importName, NAME_PROPERTY);
- }
- }
- }
- return importName;
- }
-
- /**
- * Sets the name of this import declaration to the given name.
- * <p>
- * For a regular on-demand import, this is the name of a package.
- * For a static on-demand import, this is the qualified name of
- * a type. For a regular single-type import, this is the qualified name
- * of a type. For a static single-type import, this is the qualified name
- * of a static member of a type.
- * </p>
- *
- * @param name the new import name
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public void setName(Name name) {
- if (name == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.importName;
- preReplaceChild(oldChild, name, NAME_PROPERTY);
- this.importName = name;
- postReplaceChild(oldChild, name, NAME_PROPERTY);
- }
-
- /**
- * Returns whether this import declaration is an on-demand or a
- * single-type import.
- *
- * @return <code>true</code> if this is an on-demand import,
- * and <code>false</code> if this is a single type import
- */
- public boolean isOnDemand() {
- return onDemand;
- }
-
- /**
- * Sets whether this import declaration is an on-demand or a
- * single-type import.
- *
- * @param onDemand <code>true</code> if this is an on-demand import,
- * and <code>false</code> if this is a single type import
- */
- public void setOnDemand(boolean onDemand) {
- preValueChange(ON_DEMAND_PROPERTY);
- this.onDemand = onDemand;
- postValueChange(ON_DEMAND_PROPERTY);
- }
-
- public void setIsFileImport(boolean isFileImport) {
- preValueChange(ISFILE_PROPERTY);
- this.isFile = isFileImport;
- postValueChange(ISFILE_PROPERTY);
- }
-
- /**
- * Returns whether this import declaration is a static import (added in JLS3 API).
- *
- * @return <code>true</code> if this is a static import,
- * and <code>false</code> if this is a regular import
- * @exception UnsupportedOperationException if this operation is used in
- * a JLS2 AST
- *
- */
- public boolean isStatic() {
- unsupportedIn2();
- return isStatic;
- }
-
- /**
- * Sets whether this import declaration is a static import (added in JLS3 API).
- *
- * @param isStatic <code>true</code> if this is a static import,
- * and <code>false</code> if this is a regular import
- * @exception UnsupportedOperationException if this operation is used in
- * a JLS2 AST
- *
- */
- public void setStatic(boolean isStatic) {
- unsupportedIn2();
- preValueChange(STATIC_PROPERTY);
- this.isStatic = isStatic;
- postValueChange(STATIC_PROPERTY);
- }
-
- /**
- * Resolves and returns the binding for the package, type, field, or
- * method named in this import declaration.
- * <p>
- * The name specified in a non-static single-type import can resolve
- * to a type (only). The name specified in a non-static on-demand
- * import can itself resolve to either a package or a type.
- * For static imports (introduced in JLS3), the name specified in a
- * static on-demand import can itself resolve to a type (only).
- * The name specified in a static single import can resolve to a
- * type, field, or method; in cases where the name could be resolved
- * to more than one element with that name (for example, two
- * methods both named "max", or a method and a field), this method
- * returns one of the plausible bindings.
- * </p>
- * <p>
- * Note that bindings are generally unavailable unless requested when the
- * AST is being built.
- * </p>
- *
- * @return a package, type, field, or method binding, or <code>null</code>
- * if the binding cannot be resolved
- */
- public IBinding resolveBinding() {
- return this.ast.getBindingResolver().resolveImport(this);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return BASE_NODE_SIZE + 3 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (importName == null ? 0 : getName().treeSize());
- }
-
- public boolean isFileImport()
- {
- return isFile;
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/InferredType.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/InferredType.java
deleted file mode 100644
index d542dd84..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/InferredType.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- *
- * 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 Type {
-
- private static final List PROPERTY_DESCRIPTORS;
-
-// public static final ChildPropertyDescriptor TYPE_PROPERTY =
-// new ChildPropertyDescriptor(InferredType.class, "type", String.class, MANDATORY, NO_CYCLE_RISK); //$NON-NLS-1$
-
- static {
- List propertyList = new ArrayList(0);
- createPropertyList(InferredType.class, propertyList);
-// addProperty(TYPE_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(propertyList);
- }
-
- String type;
-
-
- InferredType(AST ast) {
- super(ast);
- }
-
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
-
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
-// acceptChild(visitor, getName());
- }
- visitor.endVisit(this);
-
- }
-
- ASTNode clone0(AST target) {
- InferredType result = new InferredType(target);
- result.setSourceRange(-1,0);
- result.type = type;
-
- return result;
- }
-
- int getNodeType0() {
- return INFERRED_TYPE;
- }
-
- List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
-
- }
-
-
- int memSize() {
- return 0;
- }
-
- boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- return matcher.match(this, other);
- }
-
- int treeSize() {
- return 0;
- }
- public boolean isInferred()
- {
- return true;
- }
-
- public String getType() {
- return this.type;
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/InfixExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/InfixExpression.java
deleted file mode 100644
index febadf31..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/InfixExpression.java
+++ /dev/null
@@ -1,546 +0,0 @@
-/*******************************************************************************
- * 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.core.dom;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Infix expression AST node type.
- * <pre>
- * InfixExpression:
- * Expression InfixOperator Expression { InfixOperator Expression }
- * </pre>
- *
- * 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 InfixExpression extends Expression {
-
- /**
- * Infix operators (typesafe enumeration).
- * <pre>
- * InfixOperator:<code>
- * <b>*</b> TIMES
- * <b>/</b> DIVIDE
- * <b>%</b> REMAINDER
- * <b>+</b> PLUS
- * <b>-</b> MINUS
- * <b>&lt;&lt;</b> LEFT_SHIFT
- * <b>&gt;&gt;</b> RIGHT_SHIFT_SIGNED
- * <b>&gt;&gt;&gt;</b> RIGHT_SHIFT_UNSIGNED
- * <b>&lt;</b> LESS
- * <b>&gt;</b> GREATER
- * <b>&lt;=</b> LESS_EQUALS
- * <b>&gt;=</b> GREATER_EQUALS
- * <b>==</b> EQUALS
- * <b>!=</b> NOT_EQUALS
- * <b>^</b> XOR
- * <b>&amp;</b> AND
- * <b>|</b> OR
- * <b>&amp;&amp;</b> CONDITIONAL_AND
- * <b>||</b> CONDITIONAL_OR</code>
- * </pre>
- */
- public static class Operator {
-
- /**
- * The token for the operator.
- */
- private String token;
-
- /**
- * Creates a new infix operator with the given token.
- * <p>
- * Note: this constructor is private. The only instances
- * ever created are the ones for the standard operators.
- * </p>
- *
- * @param token the character sequence for the operator
- */
- private Operator(String token) {
- this.token = token;
- }
-
- /**
- * Returns the character sequence for the operator.
- *
- * @return the character sequence for the operator
- */
- public String toString() {
- return token;
- }
-
- /** Multiplication "*" operator. */
- public static final Operator TIMES = new Operator("*");//$NON-NLS-1$
- /** Division "/" operator. */
- public static final Operator DIVIDE = new Operator("/");//$NON-NLS-1$
- /** Remainder "%" operator. */
- public static final Operator REMAINDER = new Operator("%");//$NON-NLS-1$
- /** Addition (or string concatenation) "+" operator. */
- public static final Operator PLUS = new Operator("+");//$NON-NLS-1$
- /** Subtraction "-" operator. */
- public static final Operator MINUS = new Operator("-");//$NON-NLS-1$
- /** Left shift "&lt;&lt;" operator. */
- public static final Operator LEFT_SHIFT = new Operator("<<");//$NON-NLS-1$
- /** Signed right shift "&gt;&gt;" operator. */
- public static final Operator RIGHT_SHIFT_SIGNED = new Operator(">>");//$NON-NLS-1$
- /** Unsigned right shift "&gt;&gt;&gt;" operator. */
- public static final Operator RIGHT_SHIFT_UNSIGNED =
- new Operator(">>>");//$NON-NLS-1$
- /** Less than "&lt;" operator. */
- public static final Operator LESS = new Operator("<");//$NON-NLS-1$
- /** Greater than "&gt;" operator. */
- public static final Operator GREATER = new Operator(">");//$NON-NLS-1$
- /** Less than or equals "&lt;=" operator. */
- public static final Operator LESS_EQUALS = new Operator("<=");//$NON-NLS-1$
- /** Greater than or equals "&gt=;" operator. */
- public static final Operator GREATER_EQUALS = new Operator(">=");//$NON-NLS-1$
- /** Equals "==" operator. */
- public static final Operator EQUALS = new Operator("==");//$NON-NLS-1$
- /** Not equals "!=" operator. */
- public static final Operator NOT_EQUALS = new Operator("!=");//$NON-NLS-1$
- /** Exclusive OR "^" operator. */
- public static final Operator XOR = new Operator("^");//$NON-NLS-1$
- /** Inclusive OR "|" operator. */
- public static final Operator OR = new Operator("|");//$NON-NLS-1$
- /** AND "&amp;" operator. */
- public static final Operator AND = new Operator("&");//$NON-NLS-1$
- /** Conditional OR "||" operator. */
- public static final Operator CONDITIONAL_OR = new Operator("||");//$NON-NLS-1$
- /** Conditional AND "&amp;&amp;" operator. */
- public static final Operator CONDITIONAL_AND = new Operator("&&");//$NON-NLS-1$
-
- public static final Operator INSTANCEOF = new Operator("instanceof");//$NON-NLS-1$
- public static final Operator IN = new Operator("in");//$NON-NLS-1$
- public static final Operator EQUAL_EQUAL_EQUAL = new Operator("===");//$NON-NLS-1$
- public static final Operator NOT_EQUAL_EQUAL = new Operator("!==");//$NON-NLS-1$
-
-
- /**
- * Map from token to operator (key type: <code>String</code>;
- * value type: <code>Operator</code>).
- */
- private static final Map CODES;
- static {
- CODES = new HashMap(20);
- Operator[] ops = {
- TIMES,
- DIVIDE,
- REMAINDER,
- PLUS,
- MINUS,
- LEFT_SHIFT,
- RIGHT_SHIFT_SIGNED,
- RIGHT_SHIFT_UNSIGNED,
- LESS,
- GREATER,
- LESS_EQUALS,
- GREATER_EQUALS,
- EQUALS,
- NOT_EQUALS,
- XOR,
- OR,
- AND,
- CONDITIONAL_OR,
- CONDITIONAL_AND,
- };
- for (int i = 0; i < ops.length; i++) {
- CODES.put(ops[i].toString(), ops[i]);
- }
- }
-
- /**
- * Returns the infix operator corresponding to the given string,
- * or <code>null</code> if none.
- * <p>
- * <code>toOperator</code> is the converse of <code>toString</code>:
- * that is, <code>Operator.toOperator(op.toString()) == op</code> for
- * all operators <code>op</code>.
- * </p>
- *
- * @param token the character sequence for the operator
- * @return the infix operator, or <code>null</code> if none
- */
- public static Operator toOperator(String token) {
- return (Operator) CODES.get(token);
- }
-
- }
-
- /**
- * The "leftOperand" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor LEFT_OPERAND_PROPERTY =
- new ChildPropertyDescriptor(InfixExpression.class, "leftOperand", Expression.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "operator" structural property of this node type.
- *
- */
- public static final SimplePropertyDescriptor OPERATOR_PROPERTY =
- new SimplePropertyDescriptor(InfixExpression.class, "operator", InfixExpression.Operator.class, MANDATORY); //$NON-NLS-1$
-
- /**
- * The "rightOperand" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor RIGHT_OPERAND_PROPERTY =
- new ChildPropertyDescriptor(InfixExpression.class, "rightOperand", Expression.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "extendedOperands" structural property of this node type.
- *
- */
- public static final ChildListPropertyDescriptor EXTENDED_OPERANDS_PROPERTY =
- new ChildListPropertyDescriptor(InfixExpression.class, "extendedOperands", Expression.class, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List properyList = new ArrayList(5);
- createPropertyList(InfixExpression.class, properyList);
- addProperty(LEFT_OPERAND_PROPERTY, properyList);
- addProperty(OPERATOR_PROPERTY, properyList);
- addProperty(RIGHT_OPERAND_PROPERTY, properyList);
- addProperty(EXTENDED_OPERANDS_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The infix operator; defaults to InfixExpression.Operator.PLUS.
- */
- private InfixExpression.Operator operator = InfixExpression.Operator.PLUS;
-
- /**
- * The left operand; lazily initialized; defaults to an unspecified,
- * but legal, simple name.
- */
- private Expression leftOperand = null;
-
- /**
- * The right operand; lazily initialized; defaults to an unspecified,
- * but legal, simple name.
- */
- private Expression rightOperand = null;
-
- /**
- * The list of extended operand expressions (element type:
- * <code>Expression</code>). Lazily initialized; defaults to an empty list.
- */
- private ASTNode.NodeList extendedOperands = null;
-
- /**
- * Creates a new AST node for an infix expression owned by the given
- * AST. By default, the node has unspecified (but legal) operator,
- * left and right operands, and an empty list of additional operands.
- *
- * @param ast the AST that is to own this node
- */
- InfixExpression(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final Object internalGetSetObjectProperty(SimplePropertyDescriptor property, boolean get, Object value) {
- if (property == OPERATOR_PROPERTY) {
- if (get) {
- return getOperator();
- } else {
- setOperator((Operator) value);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetObjectProperty(property, get, value);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == LEFT_OPERAND_PROPERTY) {
- if (get) {
- return getLeftOperand();
- } else {
- setLeftOperand((Expression) child);
- return null;
- }
- }
- if (property == RIGHT_OPERAND_PROPERTY) {
- if (get) {
- return getRightOperand();
- } else {
- setRightOperand((Expression) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalGetChildListProperty(ChildListPropertyDescriptor property) {
- if (property == EXTENDED_OPERANDS_PROPERTY) {
- return extendedOperands();
- }
- // allow default implementation to flag the error
- return super.internalGetChildListProperty(property);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return INFIX_EXPRESSION;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- InfixExpression result = new InfixExpression(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setOperator(getOperator());
- result.setLeftOperand((Expression) getLeftOperand().clone(target));
- result.setRightOperand((Expression) getRightOperand().clone(target));
- if (this.extendedOperands != null) {
- // be careful not to trigger lazy creation of list
- result.extendedOperands().addAll(
- ASTNode.copySubtrees(target, this.extendedOperands()));
- }
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChild(visitor, getLeftOperand());
- acceptChild(visitor, getRightOperand());
- if (this.extendedOperands != null) {
- // be careful not to trigger lazy creation of list
- acceptChildren(visitor, this.extendedOperands);
- }
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the operator of this infix expression.
- *
- * @return the infix operator
- */
- public InfixExpression.Operator getOperator() {
- return this.operator;
- }
-
- /**
- * Sets the operator of this infix expression.
- *
- * @param operator the infix operator
- * @exception IllegalArgumentException if the argument is incorrect
- */
- public void setOperator(InfixExpression.Operator operator) {
- if (operator == null) {
- throw new IllegalArgumentException();
- }
- preValueChange(OPERATOR_PROPERTY);
- this.operator = operator;
- postValueChange(OPERATOR_PROPERTY);
- }
-
- /**
- * Returns the left operand of this infix expression.
- *
- * @return the left operand node
- */
- public Expression getLeftOperand() {
- if (this.leftOperand == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.leftOperand == null) {
- preLazyInit();
- this.leftOperand= new SimpleName(this.ast);
- postLazyInit(this.leftOperand, LEFT_OPERAND_PROPERTY);
- }
- }
- }
- return this.leftOperand;
- }
-
- /**
- * Sets the left operand of this infix expression.
- *
- * @param expression the left operand node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setLeftOperand(Expression expression) {
- if (expression == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.leftOperand;
- preReplaceChild(oldChild, expression, LEFT_OPERAND_PROPERTY);
- this.leftOperand = expression;
- postReplaceChild(oldChild, expression, LEFT_OPERAND_PROPERTY);
- }
-
- /**
- * Returns the right operand of this infix expression.
- *
- * @return the right operand node
- */
- public Expression getRightOperand() {
- if (this.rightOperand == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.rightOperand == null) {
- preLazyInit();
- this.rightOperand= new SimpleName(this.ast);
- postLazyInit(this.rightOperand, RIGHT_OPERAND_PROPERTY);
- }
- }
- }
- return this.rightOperand;
- }
-
- /**
- * Sets the right operand of this infix expression.
- *
- * @param expression the right operand node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setRightOperand(Expression expression) {
- if (expression == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.rightOperand;
- preReplaceChild(oldChild, expression, RIGHT_OPERAND_PROPERTY);
- this.rightOperand = expression;
- postReplaceChild(oldChild, expression, RIGHT_OPERAND_PROPERTY);
- }
-
- /**
- * Returns where there are any extended operands.
- *
- * @return <code>true</code> if there are one or more extended operands,
- * and <code>false</code> if there are no extended operands
- */
- public boolean hasExtendedOperands() {
- return
- (this.extendedOperands != null) && this.extendedOperands.size() > 0;
- }
-
- /**
- * Returns the live list of extended operands.
- * <p>
- * The extended operands is the preferred way of representing deeply nested
- * expressions of the form <code>L op R op R2 op R3...</code> where
- * the same operator appears between all the operands (the most
- * common case being lengthy string concatenation expressions). Using
- * the extended operands keeps the trees from getting too deep; this
- * decreases the risk is running out of thread stack space at runtime
- * when traversing such trees.
- * ((a + b) + c) + d would be translated to:
- * leftOperand: a
- * rightOperand: b
- * extendedOperands: {c, d}
- * operator: +
- * </p>
- *
- * @return the live list of extended operands
- * (element type: <code>Expression</code>)
- */
- public List extendedOperands() {
- if (this.extendedOperands == null) {
- // lazily initialize
- this.extendedOperands = new ASTNode.NodeList(EXTENDED_OPERANDS_PROPERTY);
- }
- return this.extendedOperands;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- // treat Operator as free
- return BASE_NODE_SIZE + 4 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.leftOperand == null ? 0 : getLeftOperand().treeSize())
- + (this.rightOperand == null ? 0 : getRightOperand().treeSize())
- + (this.extendedOperands == null ? 0 : extendedOperands.listSize());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Initializer.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Initializer.java
deleted file mode 100644
index 871f7f57..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Initializer.java
+++ /dev/null
@@ -1,315 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Static or instance initializer AST node type.
- * <pre>
- * Initializer:
- * [ <b>static</b> ] Block
- * </pre>
- *
- * 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 Initializer extends BodyDeclaration {
-
- /**
- * The "javadoc" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor JAVADOC_PROPERTY =
- internalJavadocPropertyFactory(Initializer.class);
-
- /**
- * The "modifiers" structural property of this node type (JLS2 API only).
- *
- */
- public static final SimplePropertyDescriptor MODIFIERS_PROPERTY =
- internalModifiersPropertyFactory(Initializer.class);
-
- /**
- * The "modifiers" structural property of this node type (added in JLS3 API).
- *
- */
- public static final ChildListPropertyDescriptor MODIFIERS2_PROPERTY =
- internalModifiers2PropertyFactory(Initializer.class);
-
- /**
- * The "body" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor BODY_PROPERTY =
- new ChildPropertyDescriptor(Initializer.class, "body", Block.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS_2_0;
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS_3_0;
-
- static {
- List properyList = new ArrayList(4);
- createPropertyList(Initializer.class, properyList);
- addProperty(JAVADOC_PROPERTY, properyList);
- addProperty(MODIFIERS_PROPERTY, properyList);
- addProperty(BODY_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS_2_0 = reapPropertyList(properyList);
-
- properyList = new ArrayList(4);
- createPropertyList(Initializer.class, properyList);
- addProperty(JAVADOC_PROPERTY, properyList);
- addProperty(MODIFIERS2_PROPERTY, properyList);
- addProperty(BODY_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS_3_0 = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- if (apiLevel == AST.JLS2_INTERNAL) {
- return PROPERTY_DESCRIPTORS_2_0;
- } else {
- return PROPERTY_DESCRIPTORS_3_0;
- }
- }
-
- /**
- * The initializer body; lazily initialized; defaults to an empty block.
- */
- private Block body = null;
-
- /**
- * Creates a new AST node for an initializer declaration owned by the given
- * AST. By default, the initializer has no modifiers and an empty block.
- * The jsdoc comment is not used for initializers.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- Initializer(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- *
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int internalGetSetIntProperty(SimplePropertyDescriptor property, boolean get, int value) {
- if (property == MODIFIERS_PROPERTY) {
- if (get) {
- return getModifiers();
- } else {
- internalSetModifiers(value);
- return 0;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetIntProperty(property, get, value);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == JAVADOC_PROPERTY) {
- if (get) {
- return getJavadoc();
- } else {
- setJavadoc((JSdoc) child);
- return null;
- }
- }
- if (property == BODY_PROPERTY) {
- if (get) {
- return getBody();
- } else {
- setBody((Block) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalGetChildListProperty(ChildListPropertyDescriptor property) {
- if (property == MODIFIERS2_PROPERTY) {
- return modifiers();
- }
- // allow default implementation to flag the error
- return super.internalGetChildListProperty(property);
- }
-
- /* (omit javadoc for this method)
- * Method declared on BodyDeclaration.
- */
- final ChildPropertyDescriptor internalJavadocProperty() {
- return JAVADOC_PROPERTY;
- }
-
- /* (omit javadoc for this method)
- * Method declared on BodyDeclaration.
- */
- final ChildListPropertyDescriptor internalModifiers2Property() {
- return MODIFIERS2_PROPERTY;
- }
-
- /* (omit javadoc for this method)
- * Method declared on BodyDeclaration.
- */
- final SimplePropertyDescriptor internalModifiersProperty() {
- return MODIFIERS_PROPERTY;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return INITIALIZER;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- Initializer result = new Initializer(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- if (this.ast.apiLevel == AST.JLS2_INTERNAL) {
- result.internalSetModifiers(getModifiers());
- }
- if (this.ast.apiLevel >= AST.JLS3) {
- result.modifiers().addAll(ASTNode.copySubtrees(target, modifiers()));
- }
- result.setJavadoc(
- (JSdoc) ASTNode.copySubtree(target, getJavadoc()));
- result.setBody((Block) getBody().clone(target));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- acceptChild(visitor, getJavadoc());
- if (this.ast.apiLevel >= AST.JLS3) {
- acceptChildren(visitor, this.modifiers);
- }
- acceptChild(visitor, getBody());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the body of this initializer declaration.
- *
- * @return the initializer body
- */
- public Block getBody() {
- if (this.body == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.body == null) {
- preLazyInit();
- this.body= new Block(this.ast);
- postLazyInit(this.body, BODY_PROPERTY);
- }
- }
- }
- return this.body;
- }
-
- /**
- * Sets the body of this initializer declaration.
- *
- * @param body the block node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setBody(Block body) {
- if (body == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.body;
- preReplaceChild(oldChild, body, BODY_PROPERTY);
- this.body = body;
- postReplaceChild(oldChild, body, BODY_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return super.memSize() + 1 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.optionalDocComment == null ? 0 : getJavadoc().treeSize())
- + (this.modifiers == null ? 0 : this.modifiers.listSize())
- + (this.body == null ? 0 : getBody().treeSize());
- }
-}
-
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
deleted file mode 100644
index 08f91b80..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/InstanceofExpression.java
+++ /dev/null
@@ -1,265 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Instanceof expression AST node type.
- * <pre>
- * InstanceofExpression:
- * Expression <b>instanceof</b> Type
- * </pre>
- *
- * 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 InstanceofExpression extends Expression {
-
- /**
- * The "leftOperand" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor LEFT_OPERAND_PROPERTY =
- new ChildPropertyDescriptor(InstanceofExpression.class, "leftOperand", Expression.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "rightOperand" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor RIGHT_OPERAND_PROPERTY =
- new ChildPropertyDescriptor(InstanceofExpression.class, "rightOperand", Type.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List properyList = new ArrayList(3);
- createPropertyList(InstanceofExpression.class, properyList);
- addProperty(LEFT_OPERAND_PROPERTY, properyList);
- addProperty(RIGHT_OPERAND_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The left operand; lazily initialized; defaults to an unspecified,
- * but legal, simple name.
- */
- private Expression leftOperand = null;
-
- /**
- * The right operand; lazily initialized; defaults to an unspecified,
- * but legal, simple type.
- */
- private Type rightOperand = null;
-
- /**
- * Creates a new AST node for an instanceof expression owned by the given
- * AST. By default, the node has unspecified (but legal) operator,
- * left and right operands.
- *
- * @param ast the AST that is to own this node
- */
- InstanceofExpression(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == LEFT_OPERAND_PROPERTY) {
- if (get) {
- return getLeftOperand();
- } else {
- setLeftOperand((Expression) child);
- return null;
- }
- }
- if (property == RIGHT_OPERAND_PROPERTY) {
- if (get) {
- return getRightOperand();
- } else {
- setRightOperand((Type) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return INSTANCEOF_EXPRESSION;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- InstanceofExpression result = new InstanceofExpression(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setLeftOperand((Expression) getLeftOperand().clone(target));
- result.setRightOperand((Type) getRightOperand().clone(target));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChild(visitor, getLeftOperand());
- acceptChild(visitor, getRightOperand());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the left operand of this instanceof expression.
- *
- * @return the left operand node
- */
- public Expression getLeftOperand() {
- if (this.leftOperand == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.leftOperand == null) {
- preLazyInit();
- this.leftOperand= new SimpleName(this.ast);
- postLazyInit(this.leftOperand, LEFT_OPERAND_PROPERTY);
- }
- }
- }
- return this.leftOperand;
- }
-
- /**
- * Sets the left operand of this instanceof expression.
- *
- * @param expression the left operand node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setLeftOperand(Expression expression) {
- if (expression == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.leftOperand;
- preReplaceChild(oldChild, expression, LEFT_OPERAND_PROPERTY);
- this.leftOperand = expression;
- postReplaceChild(oldChild, expression, LEFT_OPERAND_PROPERTY);
- }
-
- /**
- * Returns the right operand of this instanceof expression.
- *
- * @return the right operand node
- */
- public Type getRightOperand() {
- if (this.rightOperand == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.rightOperand == null) {
- preLazyInit();
- this.rightOperand= new SimpleType(this.ast);
- postLazyInit(this.rightOperand, RIGHT_OPERAND_PROPERTY);
- }
- }
- }
- return this.rightOperand;
- }
-
- /**
- * Sets the right operand of this instanceof expression.
- *
- * @param referenceType the right operand node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setRightOperand(Type referenceType) {
- if (referenceType == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.rightOperand;
- preReplaceChild(oldChild, referenceType, RIGHT_OPERAND_PROPERTY);
- this.rightOperand = referenceType;
- postReplaceChild(oldChild, referenceType, RIGHT_OPERAND_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- // treat Operator as free
- return BASE_NODE_SIZE + 2 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.leftOperand == null ? 0 : getLeftOperand().treeSize())
- + (this.rightOperand == null ? 0 : getRightOperand().treeSize());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/InternalASTRewrite.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/InternalASTRewrite.java
deleted file mode 100644
index e9110166..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/InternalASTRewrite.java
+++ /dev/null
@@ -1,236 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.dom;
-import java.util.Hashtable;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.dom.rewrite.TargetSourceRangeComputer;
-import org.eclipse.wst.jsdt.internal.core.dom.rewrite.ASTRewriteAnalyzer;
-import org.eclipse.wst.jsdt.internal.core.dom.rewrite.LineInformation;
-import org.eclipse.wst.jsdt.internal.core.dom.rewrite.ListRewriteEvent;
-import org.eclipse.wst.jsdt.internal.core.dom.rewrite.NodeInfoStore;
-import org.eclipse.wst.jsdt.internal.core.dom.rewrite.NodeRewriteEvent;
-import org.eclipse.wst.jsdt.internal.core.dom.rewrite.RewriteEventStore;
-import org.eclipse.wst.jsdt.internal.core.dom.rewrite.RewriteEventStore.CopySourceInfo;
-import org.eclipse.wst.jsdt.internal.core.dom.rewrite.RewriteEventStore.PropertyLocation;
-
-/**
- * Internal class: not intended to be used by client.
- * When AST modifications recording is enabled, all changes are recorded by this class.
- */
-class InternalASTRewrite extends NodeEventHandler {
-
- /** root node for the rewrite: Only nodes under this root are accepted */
- private JavaScriptUnit root;
-
- protected final RewriteEventStore eventStore;
- protected final NodeInfoStore nodeStore;
- protected final Hashtable clonedNodes;
-
- int cloneDepth = 0;
-
- /**
- * Constructor
- * @param root root node of the recorded ast.
- */
- public InternalASTRewrite(JavaScriptUnit root) {
- this.root = root;
- this.eventStore = new RewriteEventStore();
- this.nodeStore = new NodeInfoStore(root.getAST());
- this.clonedNodes = new Hashtable();
- }
-
- /**
- * Performs the rewrite: The rewrite events are translated to the corresponding in text changes.
- * @param document Document which describes the code of the AST that is passed in in the
- * constructor. This document is accessed read-only.
- * @param options options
- * @throws IllegalArgumentException if the rewrite fails
- * @return Returns the edit describing the text changes.
- */
- public TextEdit rewriteAST(IDocument document, Map options) {
- TextEdit result = new MultiTextEdit();
-
- final JavaScriptUnit rootNode = getRootNode();
- if (rootNode != null) {
- TargetSourceRangeComputer xsrComputer = new TargetSourceRangeComputer() {
- /**
- * This implementation of
- * {@link TargetSourceRangeComputer#computeSourceRange(ASTNode)}
- * is specialized to work in the case of internal AST rewriting, where the
- * original AST has been modified from its original form. This means that
- * one cannot trust that the root of the given node is the javaScript unit.
- */
- public SourceRange computeSourceRange(ASTNode node) {
- int extendedStartPosition = rootNode.getExtendedStartPosition(node);
- int extendedLength = rootNode.getExtendedLength(node);
- return new SourceRange(extendedStartPosition, extendedLength);
- }
- };
- char[] content= document.get().toCharArray();
- LineInformation lineInfo= LineInformation.create(document);
- String lineDelim= TextUtilities.getDefaultLineDelimiter(document);
- List comments= rootNode.getCommentList();
-
- ASTRewriteAnalyzer visitor = new ASTRewriteAnalyzer(content, lineInfo, lineDelim, result, this.eventStore, this.nodeStore, comments, options, xsrComputer);
- rootNode.accept(visitor);
- }
- return result;
- }
-
- private void markAsMoveOrCopyTarget(ASTNode node, ASTNode newChild) {
- ASTNode source = (ASTNode)this.clonedNodes.get(newChild);
- if(source != null) {
- if(this.cloneDepth == 0) {
- PropertyLocation propertyLocation = this.eventStore.getPropertyLocation(source, RewriteEventStore.ORIGINAL);
- CopySourceInfo sourceInfo =
- this.eventStore.markAsCopySource(
- propertyLocation.getParent(),
- propertyLocation.getProperty(),
- source,
- false);
- this.nodeStore.markAsCopyTarget(newChild, sourceInfo);
- }
- } else if((newChild.getFlags() & ASTNode.ORIGINAL) != 0) {
- PropertyLocation propertyLocation = this.eventStore.getPropertyLocation(newChild, RewriteEventStore.ORIGINAL);
- CopySourceInfo sourceInfo =
- this.eventStore.markAsCopySource(
- propertyLocation.getParent(),
- propertyLocation.getProperty(),
- newChild,
- true);
- this.nodeStore.markAsCopyTarget(newChild, sourceInfo);
- }
- }
-
- private JavaScriptUnit getRootNode() {
- return this.root;
- }
-
- public String toString() {
- StringBuffer buf = new StringBuffer();
- buf.append("Events:\n"); //$NON-NLS-1$
- buf.append(this.eventStore.toString());
- return buf.toString();
- }
-
- void preValueChangeEvent(ASTNode node, SimplePropertyDescriptor property) {
- // force event creation
- this.getNodeEvent(node, property);
- }
-
- void postValueChangeEvent(ASTNode node, SimplePropertyDescriptor property) {
- NodeRewriteEvent event = this.getNodeEvent(node, property);
- event.setNewValue(node.getStructuralProperty(property));
- }
-
- void preAddChildEvent(ASTNode node, ASTNode child, StructuralPropertyDescriptor property) {
- if(property.isChildProperty()) {
- NodeRewriteEvent event = this.getNodeEvent(node, property);
- event.setNewValue(child);
- if(child != null) {
- this.markAsMoveOrCopyTarget(node, child);
- }
- } else if(property.isChildListProperty()) {
- // force event creation
- this.getListEvent(node, property);
- }
- }
-
- void postAddChildEvent(ASTNode node, ASTNode child, StructuralPropertyDescriptor property) {
- if(property.isChildListProperty()) {
-
- ListRewriteEvent event = this.getListEvent(node, property);
- List list = (List)node.getStructuralProperty(property);
- int i = list.indexOf(child);
- int s = list.size();
- int index;
- if(i + 1 < s) {
- ASTNode nextNode = (ASTNode)list.get(i + 1);
- index = event.getIndex(nextNode, ListRewriteEvent.NEW);
- } else {
- index = -1;
- }
- event.insert(child, index);
- if(child != null) {
- this.markAsMoveOrCopyTarget(node, child);
- }
- }
- }
-
- void preRemoveChildEvent(ASTNode node, ASTNode child, StructuralPropertyDescriptor property) {
- if(property.isChildProperty()) {
- NodeRewriteEvent event = getNodeEvent(node, property);
- event.setNewValue(null);
- } else if(property.isChildListProperty()) {
- ListRewriteEvent event = this.getListEvent(node, property);
- int i = event.getIndex(child, ListRewriteEvent.NEW);
- NodeRewriteEvent nodeEvent = (NodeRewriteEvent)event.getChildren()[i];
- if(nodeEvent.getOriginalValue() == null) {
- event.revertChange(nodeEvent);
- } else {
- nodeEvent.setNewValue(null);
- }
- }
- }
-
- void preReplaceChildEvent(ASTNode node, ASTNode child, ASTNode newChild, StructuralPropertyDescriptor property) {
- if(property.isChildProperty()) {
- NodeRewriteEvent event = getNodeEvent(node, property);
- event.setNewValue(newChild);
- if(newChild != null) {
- this.markAsMoveOrCopyTarget(node, newChild);
- }
- } else if(property.isChildListProperty()) {
- ListRewriteEvent event = this.getListEvent(node, property);
- int i = event.getIndex(child, ListRewriteEvent.NEW);
- NodeRewriteEvent nodeEvent = (NodeRewriteEvent)event.getChildren()[i];
- nodeEvent.setNewValue(newChild);
- if(newChild != null) {
- this.markAsMoveOrCopyTarget(node, newChild);
- }
- }
- }
-
-
- void preCloneNodeEvent(ASTNode node) {
- this.cloneDepth++;
- }
-
-
- void postCloneNodeEvent(ASTNode node, ASTNode clone) {
- if(node.ast == root.ast && clone.ast == root.ast) {
- if((node.getFlags() & ASTNode.ORIGINAL) != 0) {
- this.clonedNodes.put(clone, node);
- } else {
- // node can be a cloned node
- Object original = this.clonedNodes.get(node);
- if(original != null) {
- this.clonedNodes.put(clone, original);
- }
- }
- }
- this.cloneDepth--;
- }
-
- private NodeRewriteEvent getNodeEvent(ASTNode node, StructuralPropertyDescriptor property) {
- return this.eventStore.getNodeEvent(node, property, true);
- }
-
- private ListRewriteEvent getListEvent(ASTNode node, StructuralPropertyDescriptor property) {
- return this.eventStore.getListEvent(node, property, true);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/JSdoc.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/JSdoc.java
deleted file mode 100644
index 7ac64e62..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/JSdoc.java
+++ /dev/null
@@ -1,322 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.internal.compiler.parser.Scanner;
-import org.eclipse.wst.jsdt.internal.compiler.parser.TerminalTokens;
-
-/**
- * AST node for a Javadoc-style doc comment.
- * <pre>
- * Javadoc:
- * <b>/** </b> { TagElement } <b>*</b><b>/</b>
- * </pre>
- *
- * 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 JSdoc extends Comment {
-
- /**
- * The "comment" structural property of this node type (JLS2 API only).
- *
- * @deprecated Replaced by {@link #TAGS_PROPERTY} in the JLS3 API.
- */
- public static final SimplePropertyDescriptor COMMENT_PROPERTY =
- new SimplePropertyDescriptor(JSdoc.class, "comment", String.class, MANDATORY); //$NON-NLS-1$
-
- /**
- * The "tags" structural property of this node type.
- *
- */
- public static final ChildListPropertyDescriptor TAGS_PROPERTY =
- new ChildListPropertyDescriptor(JSdoc.class, "tags", TagElement.class, CYCLE_RISK); //$NON-NLS-1$
-
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS_2_0;
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS_3_0;
-
- static {
- List properyList = new ArrayList(3);
- createPropertyList(JSdoc.class, properyList);
- addProperty(COMMENT_PROPERTY, properyList);
- addProperty(TAGS_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS_2_0 = reapPropertyList(properyList);
-
- properyList = new ArrayList(2);
- createPropertyList(JSdoc.class, properyList);
- addProperty(TAGS_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS_3_0 = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- if (apiLevel == AST.JLS2_INTERNAL) {
- return PROPERTY_DESCRIPTORS_2_0;
- } else {
- return PROPERTY_DESCRIPTORS_3_0;
- }
- }
-
- /**
- * Canonical minimal doc comment.
- *
- */
- private static final String MINIMAL_DOC_COMMENT = "/** */";//$NON-NLS-1$
-
- /**
- * The doc comment string, including opening and closing comment
- * delimiters; defaults to a minimal jsdoc comment.
- * @deprecated The comment string was replaced in the 3.0 release
- * by a representation of the structure of the doc comment.
- * For backwards compatibility, it is still funcational as before.
- */
- private String comment = MINIMAL_DOC_COMMENT;
-
- /**
- * The list of tag elements (element type: <code>TagElement</code>).
- * Defaults to an empty list.
- *
- */
- private ASTNode.NodeList tags =
- new ASTNode.NodeList(TAGS_PROPERTY);
-
- /**
- * Creates a new AST node for a doc comment owned by the given AST.
- * The new node has an empty list of tag elements (and, for backwards
- * compatability, an unspecified, but legal, doc comment string).
- * <p>
- * N.B. This constructor is package-private; all subclasses must be
- * declared in the same package; clients are unable to declare
- * additional subclasses.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- JSdoc(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final Object internalGetSetObjectProperty(SimplePropertyDescriptor property, boolean get, Object value) {
- if (property == COMMENT_PROPERTY) {
- if (get) {
- return getComment();
- } else {
- setComment((String) value);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetObjectProperty(property, get, value);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalGetChildListProperty(ChildListPropertyDescriptor property) {
- if (property == TAGS_PROPERTY) {
- return tags();
- }
- // allow default implementation to flag the error
- return super.internalGetChildListProperty(property);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return JSDOC;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- JSdoc result = new JSdoc(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- if (this.ast.apiLevel == AST.JLS2_INTERNAL) {
- result.setComment(getComment());
- }
- result.tags().addAll(ASTNode.copySubtrees(target, tags()));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChildren(visitor, this.tags);
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the doc comment string, including the starting
- * and ending comment delimiters, and any embedded line breaks.
- *
- * @return the doc comment string
- * @exception UnsupportedOperationException if this operation is used in
- * an AST later than JLS2
- * @deprecated The comment string was replaced in the 3.0 release
- * by a representation of the structure of the doc comment.
- * See {@link #tags() tags}.
- */
- public String getComment() {
- supportedOnlyIn2();
- return this.comment;
- }
-
- /**
- * Sets or clears the doc comment string. The documentation
- * string must include the starting and ending comment delimiters,
- * and any embedded line breaks.
- *
- * @param docComment the doc comment string
- * @exception IllegalArgumentException if the JavaScript comment string is invalid
- * @exception UnsupportedOperationException if this operation is used in
- * an AST later than JLS2
- * @deprecated The comment string was replaced in the 3.0 release
- * by a representation of the structure of the doc comment.
- * See {@link #tags() tags}.
- */
- public void setComment(String docComment) {
- supportedOnlyIn2();
- if (docComment == null) {
- throw new IllegalArgumentException();
- }
- char[] source = docComment.toCharArray();
- Scanner scanner = this.ast.scanner;
- scanner.resetTo(0, source.length);
- scanner.setSource(source);
- try {
- int token;
- boolean onlyOneComment = false;
- while ((token = scanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
- switch(token) {
- case TerminalTokens.TokenNameCOMMENT_JAVADOC :
- if (onlyOneComment) {
- throw new IllegalArgumentException();
- }
- onlyOneComment = true;
- break;
- default:
- onlyOneComment = false;
- }
- }
- if (!onlyOneComment) {
- throw new IllegalArgumentException();
- }
- } catch (InvalidInputException e) {
- throw new IllegalArgumentException();
- }
- preValueChange(COMMENT_PROPERTY);
- this.comment = docComment;
- postValueChange(COMMENT_PROPERTY);
- }
-
- /**
- * Returns the live list of tag elements that make up this doc
- * comment.
- * <p>
- * The tag elements cover everything except the starting and ending
- * comment delimiters, and generally omit leading whitespace
- * (including a leading "*") and embedded line breaks.
- * The first tag element of a typical doc comment represents
- * all the material before the first explicit doc tag; this
- * first tag element has a <code>null</code> tag name and
- * generally contains 1 or more {@link TextElement}s,
- * and possibly interspersed with tag elements for nested tags
- * like "{@link String String}".
- * Subsequent tag elements represent successive top-level doc
- * tag (e.g., "@param", "@return", "@see").
- * </p>
- * <p>
- * Adding and removing nodes from this list affects this node
- * dynamically.
- * </p>
- *
- * @return the live list of tag elements in this doc comment
- * (element type: <code>TagElement</code>)
- *
- */
- public List tags() {
- return this.tags;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- int size = super.memSize() + 2 * 4;
- if (this.comment != MINIMAL_DOC_COMMENT) {
- // anything other than the default string takes space
- size += stringSize(this.comment);
- }
- return size;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return memSize() + this.tags.listSize();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/JavaScriptUnit.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/JavaScriptUnit.java
deleted file mode 100644
index e4ca401b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/JavaScriptUnit.java
+++ /dev/null
@@ -1,1056 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.ITypeRoot;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.internal.compiler.parser.Scanner;
-import org.eclipse.wst.jsdt.internal.compiler.util.Util;
-
-/**
- * JavaScript javaScript unit AST node type. This is the type of the root of an AST.
- * <p>
- * The source range for this type of node is ordinarily the entire source file,
- * including leading and trailing whitespace and comments.
- * </p>
- * For JLS2:
- * <pre>
- * JavaScriptUnit:
- * [ PackageDeclaration ]
- * { ImportDeclaration }
- * { TypeDeclaration | <b>;</b> }
- * </pre>
- * For JLS3, the kinds of type declarations
- * grew to include enum and annotation type declarations:
- * <pre>
- * JavaScriptUnit:
- * [ PackageDeclaration ]
- * { ImportDeclaration }
- * { TypeDeclaration | EnumDeclaration | AnnotationTypeDeclaration | <b>;</b> }
- * </pre>
- *
- * 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 JavaScriptUnit extends ASTNode {
-
- /**
- * Canonical empty list of messages.
- */
- private static final Message[] EMPTY_MESSAGES = new Message[0];
-
- /**
- * Canonical empty list of problems.
- */
- private static final IProblem[] EMPTY_PROBLEMS = new IProblem[0];
-
- /**
- * The "imports" structural property of this node type.
- *
- *
- */
- public static final ChildListPropertyDescriptor IMPORTS_PROPERTY =
- new ChildListPropertyDescriptor(JavaScriptUnit.class, "imports", ImportDeclaration.class, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "package" structural property of this node type.
- *
- *
- */
- public static final ChildPropertyDescriptor PACKAGE_PROPERTY =
- new ChildPropertyDescriptor(JavaScriptUnit.class, "package", PackageDeclaration.class, OPTIONAL, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- /**
- * The "types" structural property of this node type.
- *
- *
- */
- public static final ChildListPropertyDescriptor TYPES_PROPERTY =
- new ChildListPropertyDescriptor(JavaScriptUnit.class, "types", AbstractTypeDeclaration.class, CYCLE_RISK); //$NON-NLS-1$
-
- public static final ChildListPropertyDescriptor STATEMENTS_PROPERTY =
- new ChildListPropertyDescriptor(JavaScriptUnit.class, "statements", ProgramElement.class, CYCLE_RISK); //$NON-NLS-1$
-
- static {
- List properyList = new ArrayList(4);
- createPropertyList(JavaScriptUnit.class, properyList);
- addProperty(PACKAGE_PROPERTY, properyList);
- addProperty(IMPORTS_PROPERTY, properyList);
- addProperty(TYPES_PROPERTY, properyList);
- addProperty(STATEMENTS_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The comment mapper, or <code>null</code> if none;
- * initially <code>null</code>.
- *
- */
- private DefaultCommentMapper commentMapper = null;
-
- /**
- * The JavaScript type root (an <code>org.eclipse.wst.jsdt.core.IJavaScriptUnit</code> or an <code>org.eclipse.wst.jsdt.core.IClassFile</code>)
- * this javaScript unit was created from, or <code>null</code> if it was not created from a JavaScript type root.
- */
- private ITypeRoot typeRoot = null;
-
- /**
- * The list of import declarations in textual order order;
- * initially none (elementType: <code>ImportDeclaration</code>).
- */
- private ASTNode.NodeList imports =
- new ASTNode.NodeList(IMPORTS_PROPERTY);
-
- /**
- * Line end table. If <code>lineEndTable[i] == p</code> then the
- * line number <code>i+1</code> ends at character position
- * <code>p</code>. Except for the last line, the positions are that
- * of the last character of the line delimiter.
- * For example, the source string <code>A\nB\nC</code> has
- * line end table {1, 3} (if \n is one character).
- */
- private int[] lineEndTable = Util.EMPTY_INT_ARRAY;
-
- /**
- * Messages reported by the validator during parsing or name resolution.
- */
- private Message[] messages;
-
- /**
- * The comment list (element type: <code>Comment</code>,
- * or <code>null</code> if none; initially <code>null</code>.
- *
- */
- private List optionalCommentList = null;
-
- /**
- * The comment table, or <code>null</code> if none; initially
- * <code>null</code>. This array is the storage underlying
- * the <code>optionalCommentList</code> ArrayList.
- *
- */
- Comment[] optionalCommentTable = null;
-
- /**
- * The package declaration, or <code>null</code> if none; initially
- * <code>null</code>.
- */
- private PackageDeclaration optionalPackageDeclaration = null;
-
- /**
- * Problems reported by the validator during parsing or name resolution.
- */
- private IProblem[] problems = EMPTY_PROBLEMS;
-
- /**
- * The list of type declarations in textual order order;
- * initially none (elementType: <code>AbstractTypeDeclaration</code>)
- */
- private ASTNode.NodeList types =
- new ASTNode.NodeList(TYPES_PROPERTY);
-
- private ASTNode.NodeList statements =
- new ASTNode.NodeList(STATEMENTS_PROPERTY);
-
-
- /**
- * Creates a new AST node for a compilation owned by the given AST.
- * The javaScript unit initially has no package declaration, no
- * import declarations, and no type declarations.
- * <p>
- * N.B. This constructor is package-private; all subclasses must be
- * declared in the same package; clients are unable to declare
- * additional subclasses.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- JavaScriptUnit(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChild(visitor, getPackage());
- acceptChildren(visitor, this.imports);
- acceptChildren(visitor, this.types);
- acceptChildren(visitor, this.statements);
- }
- visitor.endVisit(this);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- JavaScriptUnit result = new JavaScriptUnit(target);
- // n.b do not copy line number table or messages
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setPackage(
- (PackageDeclaration) ASTNode.copySubtree(target, getPackage()));
- result.imports().addAll(ASTNode.copySubtrees(target, imports()));
- result.types().addAll(ASTNode.copySubtrees(target, types()));
- result.statements().addAll(ASTNode.copySubtrees(target, statements()));
- return result;
- }
-
-
- /**
- * Returns the column number corresponding to the given source character
- * position in the original source string. Column number are zero-based.
- * Return <code>-1</code> if it is beyond the valid range or <code>-2</code>
- * if the column number information is unknown.
- *
- * @param position a 0-based character position, possibly
- * negative or out of range
- * @return the 0-based column number, or <code>-1</code> if the character
- * position does not correspond to a source line in the original
- * source file or <code>-2</code> if column number information is unknown for this
- * javaScript unit
- * @see ASTParser
- *
- */
- public int getColumnNumber(final int position) {
- if (this.lineEndTable == null) return -2;
- final int line = getLineNumber(position);
- if (line == -1) {
- return -1;
- }
- if (line == 1) {
- if (position >= getStartPosition() + getLength()) return -1;
- return position;
- }
- // length is different from 0
- int length = this.lineEndTable.length;
- // -1 to for one-based to zero-based conversion.
- // -1, again, to get previous line.
- final int previousLineOffset = this.lineEndTable[line - 2];
- // previousLineOffset + 1 is the first character of the current line
- final int offsetForLine = previousLineOffset + 1;
- final int currentLineEnd = line == length + 1 ? getStartPosition() + getLength() - 1 : this.lineEndTable[line - 1];
- if (offsetForLine > currentLineEnd) {
- return -1;
- } else {
- return position - offsetForLine;
- }
- }
-
- /**
- * Finds the corresponding AST node in the given javaScript unit from
- * which the given binding originated. Returns <code>null</code> if the
- * binding does not correspond to any node in this javaScript unit.
- * This method always returns <code>null</code> if bindings were not requested
- * when this AST was built.
- * <p>
- * The following table indicates the expected node type for the various
- * different kinds of bindings:
- * <ul>
- * <li>package - a <code>PackageDeclaration</code></li>
- * <li>class or interface - a <code>TypeDeclaration</code> or a
- * <code>AnonymousClassDeclaration</code> (for anonymous classes)</li>
- * <li>primitive type - none</li>
- * <li>array type - none</li>
- * <li>field - a <code>VariableDeclarationFragment</code> in a
- * <code>FieldDeclaration</code> </li>
- * <li>local variable - a <code>SingleVariableDeclaration</code>, or
- * a <code>VariableDeclarationFragment</code> in a
- * <code>VariableDeclarationStatement</code> or
- * <code>VariableDeclarationExpression</code></li>
- * <li>method - a <code>FunctionDeclaration</code> </li>
- * <li>constructor - a <code>FunctionDeclaration</code> </li>
- * <li>annotation type - an <code>AnnotationTypeDeclaration</code></li>
- * <li>annotation type member - an <code>AnnotationTypeMemberDeclaration</code></li>
- * <li>enum type - an <code>EnumDeclaration</code></li>
- * <li>enum constant - an <code>EnumConstantDeclaration</code></li>
- * <li>type variable - a <code>TypeParameter</code></li>
- * <li>capture binding - none</li>
- * <li>annotation binding - an <code>Annotation</code></li>
- * <li>member value pair binding - an <code>MemberValuePair</code>,
- * or <code>null</code> if it represents a default value or a single member value</li>
- * </ul>
- * For parameterized or raw type bindings, the declaring node is
- * that of the corresponding generic type. And for parameterized or raw
- * method bindings, the declaring node is that of the corresponding
- * generic method.
- * </p>
- * <p>
- * Each call to {@link ASTParser#createAST(org.eclipse.core.runtime.IProgressMonitor)} with a request for bindings
- * gives rise to separate universe of binding objects. This method always returns
- * <code>null</code> when the binding object comes from a different AST.
- * Use <code>findDeclaringNode(binding.getKey())</code> when the binding comes
- * from a different AST.
- * </p>
- *
- * @param binding the binding
- * @return the corresponding node where the given binding is declared,
- * or <code>null</code> if the binding does not correspond to a node in this
- * javaScript unit or if bindings were not requested when this AST was built
- * @see #findDeclaringNode(String)
- */
- public ASTNode findDeclaringNode(IBinding binding) {
- return this.ast.getBindingResolver().findDeclaringNode(binding);
- }
-
- /**
- * Finds the corresponding AST node in the given javaScript unit from
- * which the binding with the given key originated. Returns
- * <code>null</code> if the corresponding node cannot be determined.
- * This method always returns <code>null</code> if bindings were not requested
- * when this AST was built.
- * <p>
- * The following table indicates the expected node type for the various
- * different kinds of binding keys:
- * <ul>
- * <li></li>
- * <li>package - a <code>PackageDeclaration</code></li>
- * <li>class or interface - a <code>TypeDeclaration</code> or a
- * <code>AnonymousClassDeclaration</code> (for anonymous classes)</li>
- * <li>primitive type - none</li>
- * <li>array type - none</li>
- * <li>field - a <code>VariableDeclarationFragment</code> in a
- * <code>FieldDeclaration</code> </li>
- * <li>local variable - a <code>SingleVariableDeclaration</code>, or
- * a <code>VariableDeclarationFragment</code> in a
- * <code>VariableDeclarationStatement</code> or
- * <code>VariableDeclarationExpression</code></li>
- * <li>method - a <code>FunctionDeclaration</code> </li>
- * <li>constructor - a <code>FunctionDeclaration</code> </li>
- * <li>annotation type - an <code>AnnotationTypeDeclaration</code></li>
- * <li>annotation type member - an <code>AnnotationTypeMemberDeclaration</code></li>
- * <li>enum type - an <code>EnumDeclaration</code></li>
- * <li>enum constant - an <code>EnumConstantDeclaration</code></li>
- * <li>type variable - a <code>TypeParameter</code></li>
- * <li>capture binding - none</li>
- * </ul>
- * For parameterized or raw type bindings, the declaring node is
- * that of the corresponding generic type. And for parameterized or raw
- * method bindings, the declaring node is that of the corresponding
- * generic method.
- * </p>
- *
- * @param key the binding key, or <code>null</code>
- * @return the corresponding node where a binding with the given
- * key is declared, or <code>null</code> if the key is <code>null</code>
- * or if the key does not correspond to a node in this javaScript unit
- * or if bindings were not requested when this AST was built
- * @see IBinding#getKey()
- *
- */
- public ASTNode findDeclaringNode(String key) {
- return this.ast.getBindingResolver().findDeclaringNode(key);
- }
-
- /**
- * Returns a list of the comments encountered while parsing
- * this javaScript unit.
- * <p>
- * Since the JavaScript language allows comments to appear most anywhere
- * in the source text, it is problematic to locate comments in relation
- * to the structure of an AST. The one exception is doc comments
- * which, by convention, immediately precede type, field, and
- * method declarations; these comments are located in the AST
- * by {@link BodyDeclaration#getjsdoc BodyDeclaration.getJavadoc}.
- * Other comments do not show up in the AST. The table of comments
- * is provided for clients that need to find the source ranges of
- * all comments in the original source string. It includes entries
- * for comments of all kinds (line, block, and doc), arranged in order
- * of increasing source position.
- * </p>
- * <p>
- * Note on comment parenting: The {@link ASTNode#getParent() getParent()}
- * of a doc comment associated with a body declaration is the body
- * declaration node; for these comment nodes
- * {@link ASTNode#getRoot() getRoot()} will return the javaScript unit
- * (assuming an unmodified AST) reflecting the fact that these nodes
- * are property located in the AST for the javaScript unit.
- * However, for other comment nodes, {@link ASTNode#getParent() getParent()}
- * will return <code>null</code>, and {@link ASTNode#getRoot() getRoot()}
- * will return the comment node itself, indicating that these comment nodes
- * are not directly connected to the AST for the javaScript unit. The
- * {@link Comment#getAlternateRoot Comment.getAlternateRoot}
- * method provides a way to navigate from a comment to its compilation
- * unit.
- * </p>
- * <p>
- * A note on visitors: The only comment nodes that will be visited when
- * visiting a javaScript unit are the doc comments parented by body
- * declarations. To visit all comments in normal reading order, iterate
- * over the comment table and call {@link ASTNode#accept(ASTVisitor) accept}
- * on each element.
- * </p>
- * <p>
- * Clients cannot modify the resulting list.
- * </p>
- *
- * @return an unmodifiable list of comments in increasing order of source
- * start position, or <code>null</code> if comment information
- * for this javaScript unit is not available
- * @see ASTParser
- *
- */
- public List getCommentList() {
- return this.optionalCommentList;
- }
-
- /**
- * Returns the internal comment mapper.
- *
- * @return the comment mapper, or <code>null</code> if none.
- *
- */
- DefaultCommentMapper getCommentMapper() {
- return this.commentMapper;
- }
-
- /**
- * Returns the extended source length of the given node. Unlike
- * {@link ASTNode#getStartPosition()} and {@link ASTNode#getLength()},
- * the extended source range may include comments and whitespace
- * immediately before or after the normal source range for the node.
- *
- * @param node the node
- * @return a (possibly 0) length, or <code>0</code>
- * if no source position information is recorded for this node
- * @see #getExtendedStartPosition(ASTNode)
- *
- */
- public int getExtendedLength(ASTNode node) {
- if (node == null) {
- throw new IllegalArgumentException();
- }
- if (this.commentMapper == null || node.getAST() != getAST()) {
- // fall back: use best info available
- return node.getLength();
- } else {
- return this.commentMapper.getExtendedLength(node);
- }
- }
-
- /**
- * Returns the extended start position of the given node. Unlike
- * {@link ASTNode#getStartPosition()} and {@link ASTNode#getLength()},
- * the extended source range may include comments and whitespace
- * immediately before or after the normal source range for the node.
- *
- * @param node the node
- * @return the 0-based character index, or <code>-1</code>
- * if no source position information is recorded for this node
- * @see #getExtendedLength(ASTNode)
- *
- */
- public int getExtendedStartPosition(ASTNode node) {
- if (node == null) {
- throw new IllegalArgumentException();
- }
- if (this.commentMapper == null || node.getAST() != getAST()) {
- // fall back: use best info available
- return node.getStartPosition();
- } else {
- return this.commentMapper.getExtendedStartPosition(node);
- }
- }
-
- /**
- * The JavaScript element (an <code>org.eclipse.wst.jsdt.core.IJavaScriptUnit</code> or an <code>org.eclipse.wst.jsdt.core.IClassFile</code>)
- * this javaScript unit was created from, or <code>null</code> if it was not created from a JavaScript element.
- *
- * @return the JavaScript element this javaScript unit was created from, or <code>null</code> if none
- *
- * @see #getTypeRoot()
- */
- public IJavaScriptElement getJavaElement() {
- return this.typeRoot;
- }
-
- /**
- * Returns the list of messages reported by the validator during the parsing
- * or the type checking of this javaScript unit. This list might be a subset of
- * errors detected and reported by a JavaScript compiler.
- * <p>
- * This list of messages is suitable for simple clients that do little
- * more than log the messages or display them to the user. Clients that
- * need further details should call <code>getProblems</code> to get
- * validator problem objects.
- * </p>
- *
- * @return the list of messages, possibly empty
- * @see #getProblems()
- * @see ASTParser
- */
- public Message[] getMessages() {
- if (this.messages == null) {
- int problemLength = this.problems.length;
- if (problemLength == 0) {
- this.messages = EMPTY_MESSAGES;
- } else {
- this.messages = new Message[problemLength];
- for (int i = 0; i < problemLength; i++) {
- IProblem problem = this.problems[i];
- int start = problem.getSourceStart();
- int end = problem.getSourceEnd();
- messages[i] = new Message(problem.getMessage(), start, end - start + 1);
- }
- }
- }
- return this.messages;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return JAVASCRIPT_UNIT;
- }
-
- /**
- * Returns the node for the package declaration of this compilation
- * unit, or <code>null</code> if this javaScript unit is in the
- * default package.
- *
- * @return the package declaration node, or <code>null</code> if none
- */
- public PackageDeclaration getPackage() {
- return this.optionalPackageDeclaration;
- }
-
- /**
- * Given a line number and column number, returns the corresponding
- * position in the original source string.
- * Returns -2 if no line number information is available for this
- * javaScript unit.
- * Returns the total size of the source string if <code>line</code>
- * is greater than the actual number lines in the unit.
- * Returns -1 if <code>column</code> is less than 0,
- * or the position of the last character of the line if <code>column</code>
- * is beyond the legal range, or the given line number is less than one.
- *
- * @param line the one-based line number
- * @param column the zero-based column number
- * @return the 0-based character position in the source string;
- * <code>-2</code> if line/column number information is not known
- * for this javaScript unit or <code>-1</code> the inputs are not valid
- *
- */
- public int getPosition(int line, int column) {
- if (this.lineEndTable == null) return -2;
- if (line < 1 || column < 0) return -1;
- int length;
- if ((length = this.lineEndTable.length) == 0) {
- if (line != 1) return -1;
- return column >= getStartPosition() + getLength() ? -1 : column;
- }
- if (line == 1) {
- final int endOfLine = this.lineEndTable[0];
- return column > endOfLine ? -1 : column;
- } else if( line > length + 1 ) {
- // greater than the number of lines in the source string.
- return -1;
- }
- // -1 to for one-based to zero-based conversion.
- // -1, again, to get previous line.
- final int previousLineOffset = this.lineEndTable[line - 2];
- // previousLineOffset + 1 is the first character of the current line
- final int offsetForLine = previousLineOffset + 1;
- final int currentLineEnd = line == length + 1 ? getStartPosition() + getLength() - 1 : this.lineEndTable[line-1];
- if ((offsetForLine + column) > currentLineEnd) {
- return -1;
- } else {
- return offsetForLine + column;
- }
- }
-
- /**
- * Returns the list of detailed problem reports noted by the compiler
- * during the parsing or the type checking of this javaScript unit. This
- * list might be a subset of errors detected and reported by a Java
- * compiler.
- * <p>
- * Simple clients that do little more than log the messages or display
- * them to the user should probably call <code>getMessages</code> instead.
- * </p>
- *
- * @return the list of detailed problem objects, possibly empty
- * @see #getMessages()
- * @see ASTParser
- *
- */
- public IProblem[] getProblems() {
- return this.problems;
- }
-
- /**
- * The JavaScript type root (a {@link org.eclipse.wst.jsdt.core.IJavaScriptUnit javaScript unit} or a {@link org.eclipse.wst.jsdt.core.IClassFile class file})
- * this javaScript unit was created from, or <code>null</code> if it was not created from a JavaScript type root.
- *
- * @return the JavaScript type root this javaScript unit was created from, or <code>null</code> if none
- *
- */
- public ITypeRoot getTypeRoot() {
- return this.typeRoot;
- }
-
- /**
- * Returns the live list of nodes for the import declarations of this
- * javaScript unit, in order of appearance.
- *
- * @return the live list of import declaration nodes
- * (elementType: <code>ImportDeclaration</code>)
- */
- public List imports() {
- return this.imports;
- }
-
- /**
- * Return the index in the whole comments list {@link #getCommentList() }
- * of the first leading comments associated with the given node.
- *
- * @param node the node
- * @return 0-based index of first leading comment or -1 if node has no associated
- * comment before its start position.
- *
- */
- public int firstLeadingCommentIndex(ASTNode node) {
- if (node == null) {
- throw new IllegalArgumentException();
- }
- if (this.commentMapper == null || node.getAST() != getAST()) {
- return -1;
- }
- return this.commentMapper.firstLeadingCommentIndex(node);
- }
-
- /**
- * Return the index in the whole comments list {@link #getCommentList() }
- * of the last trailing comments associated with the given node.
- *
- * @param node the node
- * @return 0-based index of last trailing comment or -1 if node has no
- * associated comment after its end position.
- *
- */
- public int lastTrailingCommentIndex(ASTNode node) {
- if (node == null) {
- throw new IllegalArgumentException();
- }
- if (this.commentMapper == null || node.getAST() != getAST()) {
- return -1;
- }
- return this.commentMapper.lastTrailingCommentIndex(node);
- }
-
- /**
- * Initializes the internal comment mapper with the given
- * scanner.
- *
- * @param scanner the scanner
- *
- */
- void initCommentMapper(Scanner scanner) {
- this.commentMapper = new DefaultCommentMapper(this.optionalCommentTable);
- this.commentMapper.initialize(this, scanner);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalGetChildListProperty(ChildListPropertyDescriptor property) {
- if (property == IMPORTS_PROPERTY) {
- return imports();
- }
- if (property == TYPES_PROPERTY) {
- return types();
- }
- if (property == STATEMENTS_PROPERTY) {
- return statements();
- }
- // allow default implementation to flag the error
- return super.internalGetChildListProperty(property);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == PACKAGE_PROPERTY) {
- if (get) {
- return getPackage();
- } else {
- setPackage((PackageDeclaration) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- *
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /**
- * Returns the line number corresponding to the given source character
- * position in the original source string. The initial line of the
- * javaScript unit is numbered 1, and each line extends through the
- * last character of the end-of-line delimiter. The very last line extends
- * through the end of the source string and has no line delimiter.
- * For example, the source string <code>class A\n{\n}</code> has 3 lines
- * corresponding to inclusive character ranges [0,7], [8,9], and [10,10].
- * Returns -1 for a character position that does not correspond to any
- * source line, or -2 if no line number information is available for this
- * javaScript unit.
- *
- * @param position a 0-based character position, possibly
- * negative or out of range
- * @return the 1-based line number, or <code>-1</code> if the character
- * position does not correspond to a source line in the original
- * source file or <code>-2</code> if line number information is not known for this
- * javaScript unit
- * @see ASTParser
- *
- */
- public int getLineNumber(int position) {
- if (this.lineEndTable == null) return -2;
- int length;
- if ((length = this.lineEndTable.length) == 0) {
- if (position >= getStartPosition() + getLength()) {
- return -1;
- }
- return 1;
- }
- int low = 0;
- if (position < 0) {
- // position illegal
- return -1;
- }
- if (position <= this.lineEndTable[low]) {
- // before the first line delimiter
- return 1;
- }
- // assert position > lineEndTable[low+1] && low == 0
- int hi = length - 1;
- if (position > this.lineEndTable[hi]) {
- // position beyond the last line separator
- if (position >= getStartPosition() + getLength()) {
- // this is beyond the end of the source length
- return -1;
- } else {
- return length + 1;
- }
- }
- // assert lineEndTable[low] < position <= lineEndTable[hi]
- // && low == 0 && hi == length - 1 && low < hi
-
- // binary search line end table
- while (true) {
- // invariant lineEndTable[low] < position <= lineEndTable[hi]
- // && 0 <= low < hi <= length - 1
- // reducing measure hi - low
- if (low + 1 == hi) {
- // assert lineEndTable[low] < position <= lineEndTable[low+1]
- // position is on line low+1 (line number is low+2)
- return low + 2;
- }
- // assert hi - low >= 2, so average is truly in between
- int mid = low + (hi - low) / 2;
- // assert 0 <= low < mid < hi <= length - 1
- if (position <= this.lineEndTable[mid]) {
- // assert lineEndTable[low] < position <= lineEndTable[mid]
- // && 0 <= low < mid < hi <= length - 1
- hi = mid;
- } else {
- // position > lineEndTable[mid]
- // assert lineEndTable[mid] < position <= lineEndTable[hi]
- // && 0 <= low < mid < hi <= length - 1
- low = mid;
- }
- // in both cases, invariant reachieved with reduced measure
- }
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- int size = BASE_NODE_SIZE + 8 * 4;
- if (this.lineEndTable != null) {
- size += HEADERS + 4 * this.lineEndTable.length;
- }
- if (this.optionalCommentTable != null) {
- size += HEADERS + 4 * this.optionalCommentTable.length;
- }
- // ignore the space taken up by optionalCommentList
- return size;
- }
-
- /**
- * Enables the recording of changes to this compilation
- * unit and its descendents. The javaScript unit must have
- * been created by <code>ASTParser</code> and still be in
- * its original state. Once recording is on,
- * arbitrary changes to the subtree rooted at this compilation
- * unit are recorded internally. Once the modification has
- * been completed, call <code>rewrite</code> to get an object
- * representing the corresponding edits to the original
- * source code string.
- *
- * @exception IllegalArgumentException if this javaScript unit is
- * marked as unmodifiable, or if this javaScript unit has already
- * been tampered with, or recording has already been enabled
- *
- */
- public void recordModifications() {
- getAST().recordModifications(this);
- }
-
- /**
- * Converts all modifications recorded for this compilation
- * unit into an object representing the corresponding text
- * edits to the given document containing the original source
- * code for this javaScript unit.
- * <p>
- * The javaScript unit must have been created by
- * <code>ASTParser</code> from the source code string in the
- * given document, and recording must have been turned
- * on with a prior call to <code>recordModifications</code>
- * while the AST was still in its original state.
- * </p>
- * <p>
- * Calling this methods does not discard the modifications
- * on record. Subsequence modifications made to the AST
- * are added to the ones already on record. If this method
- * is called again later, the resulting text edit object will
- * accurately reflect the net cumulative affect of all those
- * changes.
- * </p>
- *
- * @param document original document containing source code
- * for this javaScript unit
- * @param options the table of formatter options
- * (key type: <code>String</code>; value type: <code>String</code>);
- * or <code>null</code> to use the standard global options
- * {@link org.eclipse.wst.jsdt.core.JavaScriptCore#getOptions() JavaScriptCore.getOptions()}.
- * @return text edit object describing the changes to the
- * document corresponding to the recorded AST modifications
- * @exception IllegalArgumentException if the document passed is
- * <code>null</code> or does not correspond to this AST
- * @exception IllegalStateException if <code>recordModifications</code>
- * was not called to enable recording
- * @see #recordModifications()
- *
- */
- public TextEdit rewrite(IDocument document, Map options) {
- return getAST().rewrite(document, options);
- }
-
- /**
- * Sets the list of the comments encountered while parsing
- * this javaScript unit.
- *
- * @param commentTable a list of comments in increasing order
- * of source start position, or <code>null</code> if comment
- * information for this javaScript unit is not available
- * @exception IllegalArgumentException if the comment table is
- * not in increasing order of source position
- * @see #getCommentList()
- * @see ASTParser
- *
- */
- void setCommentTable(Comment[] commentTable) {
- // double check table to ensure that all comments have
- // source positions and are in strictly increasing order
- if (commentTable == null) {
- this.optionalCommentList = null;
- this.optionalCommentTable = null;
- } else {
- int nextAvailablePosition = 0;
- for (int i = 0; i < commentTable.length; i++) {
- Comment comment = commentTable[i];
- if (comment == null) {
- throw new IllegalArgumentException();
- }
- int start = comment.getStartPosition();
- int length = comment.getLength();
- if (start < 0 || length < 0 || start < nextAvailablePosition) {
- throw new IllegalArgumentException();
- }
- nextAvailablePosition = comment.getStartPosition() + comment.getLength();
- }
- this.optionalCommentTable = commentTable;
- List commentList = Arrays.asList(commentTable);
- // protect the list from further modification
- this.optionalCommentList = Collections.unmodifiableList(commentList);
- }
- }
-
- /**
- * Sets the JavaScript type root (a {@link org.eclipse.wst.jsdt.core.IJavaScriptUnit javaScript unit} or a {@link org.eclipse.wst.jsdt.core.IClassFile class file})
- * this javaScript unit was created from, or <code>null</code> if it was not created from a JavaScript type root.
- *
- * @param typeRoot the JavaScript type root this javaScript unit was created from
- */
- void setTypeRoot(ITypeRoot typeRoot) {
- this.typeRoot = typeRoot;
- }
-
- /**
- * Sets the line end table for this javaScript unit.
- * If <code>lineEndTable[i] == p</code> then line number <code>i+1</code>
- * ends at character position <code>p</code>. Except for the last line, the
- * positions are that of (the last character of) the line delimiter.
- * For example, the source string <code>A\nB\nC</code> has
- * line end table {1, 3, 4}.
- *
- * @param lineEndTable the line end table
- */
- void setLineEndTable(int[] lineEndTable) {
- if (lineEndTable == null) {
- throw new NullPointerException();
- }
- // alternate root is *not* considered a structural property
- // but we protect them nevertheless
- checkModifiable();
- this.lineEndTable = lineEndTable;
- }
-
- /**
- * Sets or clears the package declaration of this javaScript unit
- * node to the given package declaration node.
- *
- * @param pkgDecl the new package declaration node, or
- * <code>null</code> if this javaScript unit does not have a package
- * declaration (that is in the default package)
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public void setPackage(PackageDeclaration pkgDecl) {
- ASTNode oldChild = this.optionalPackageDeclaration;
- preReplaceChild(oldChild, pkgDecl, PACKAGE_PROPERTY);
- this.optionalPackageDeclaration = pkgDecl;
- postReplaceChild(oldChild, pkgDecl, PACKAGE_PROPERTY);
- }
-
-
- /**
- * Sets the array of problems reported by the validator during the parsing or
- * name resolution of this javaScript unit.
- *
- * @param problems the list of problems
- */
- void setProblems(IProblem[] problems) {
- if (problems == null) {
- throw new IllegalArgumentException();
- }
- this.problems = problems;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- int size = memSize();
- if (this.optionalPackageDeclaration != null) {
- size += getPackage().treeSize();
- }
- size += this.imports.listSize();
- size += this.types.listSize();
- size += this.statements.listSize();
- // include disconnected comments
- if (this.optionalCommentList != null) {
- for (int i = 0; i < this.optionalCommentList.size(); i++) {
- Comment comment = (Comment) this.optionalCommentList.get(i);
- if (comment != null && comment.getParent() == null) {
- size += comment.treeSize();
- }
- }
- }
- return size;
- }
-
- /**
- * Returns the live list of nodes for the top-level type declarations of this
- * javaScript unit, in order of appearance.
- * <p>
- * Note that in JLS3, the types may include both enum declarations
- * and annotation type declarations introduced in J2SE 5.
- * For JLS2, the elements are always <code>TypeDeclaration</code>.
- * </p>
- *
- * @return the live list of top-level type declaration
- * nodes (elementType: <code>AbstractTypeDeclaration</code>)
- */
- public List types() {
- return this.types;
- }
-
- public List statements() {
- return this.statements;
- }
-
- public ITypeBinding resolveBinding() {
- return this.ast.getBindingResolver().resolveType(this);
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/JavaScriptUnitBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/JavaScriptUnitBinding.java
deleted file mode 100644
index 71823f2b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/JavaScriptUnitBinding.java
+++ /dev/null
@@ -1,749 +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.core.dom;
-
-import java.io.File;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Path;
-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.IJavaScriptProject;
-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.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants;
-import org.eclipse.wst.jsdt.internal.compiler.env.IDependent;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BaseTypeBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Binding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.FieldBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding;
-import org.eclipse.wst.jsdt.internal.core.ClassFile;
-import org.eclipse.wst.jsdt.internal.core.JavaElement;
-
-/**
- * Internal implementation of type bindings.
- */
-class JavaScriptUnitBinding implements ITypeBinding {
- private static final IFunctionBinding[] NO_METHOD_BINDINGS = new IFunctionBinding[0];
-
- private static final String NO_NAME = ""; //$NON-NLS-1$
- private static final ITypeBinding[] NO_TYPE_BINDINGS = new ITypeBinding[0];
- private static final IVariableBinding[] NO_VARIABLE_BINDINGS = new IVariableBinding[0];
-
- private static final int VALID_MODIFIERS = Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE |
- Modifier.ABSTRACT | Modifier.STATIC | Modifier.FINAL | Modifier.STRICTFP;
-
- org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding binding;
- private String key;
- private BindingResolver resolver;
-
- public JavaScriptUnitBinding(BindingResolver resolver, org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding binding) {
- this.binding = binding;
- this.resolver = resolver;
- }
-
- public ITypeBinding createArrayType(int dimension) {
-// int realDimensions = dimension;
-// realDimensions += this.getDimensions();
-// if (realDimensions < 1 || realDimensions > 255) {
-// throw new IllegalArgumentException();
-// }
-// return this.resolver.resolveArrayType(this, dimension);
- return null;
- }
-
- /*
- * @see ITypeBinding#getBinaryName()
- *
- */
- public String getBinaryName() {
- char[] constantPoolName = this.binding.constantPoolName();
- if (constantPoolName == null) return null;
- char[] dotSeparated = CharOperation.replaceOnCopy(constantPoolName, '/', '.');
- return new String(dotSeparated);
- }
-
- /*
- * Returns the class file for the given file name, or null if not found.
- * @see org.eclipse.wst.jsdt.internal.compiler.env.IDependent#getFileName()
- */
-// private IClassFile getClassFile(char[] fileName) {
-// int jarSeparator = CharOperation.indexOf(IDependent.JAR_FILE_ENTRY_SEPARATOR, fileName);
-// int pkgEnd = CharOperation.lastIndexOf('/', fileName); // pkgEnd is exclusive
-// if (pkgEnd == -1)
-// pkgEnd = CharOperation.lastIndexOf(File.separatorChar, fileName);
-// if (jarSeparator != -1 && pkgEnd < jarSeparator) // if in a jar and no slash, it is a default package -> pkgEnd should be equal to jarSeparator
-// pkgEnd = jarSeparator;
-// if (pkgEnd == -1)
-// return null;
-// IPackageFragment pkg = getPackageFragment(fileName, pkgEnd, jarSeparator);
-// if (pkg == null) return null;
-// int start;
-// return pkg.getClassFile(new String(fileName, start = pkgEnd + 1, fileName.length - start));
-// }
-
- /*
- * Returns the javaScript unit for the given file name, or null if not found.
- * @see org.eclipse.wst.jsdt.internal.compiler.env.IDependent#getFileName()
- */
- private IJavaScriptUnit getCompilationUnit(char[] fileName) {
- char[] slashSeparatedFileName = CharOperation.replaceOnCopy(fileName, File.separatorChar, '/');
- int pkgEnd = CharOperation.lastIndexOf('/', slashSeparatedFileName); // pkgEnd is exclusive
- if (pkgEnd == -1)
- return null;
- IPackageFragment pkg = getPackageFragment(slashSeparatedFileName, pkgEnd, -1/*no jar separator for .js files*/);
- if (pkg == null) return null;
- int start;
- IJavaScriptUnit cu = pkg.getJavaScriptUnit(new String(slashSeparatedFileName, start = pkgEnd+1, slashSeparatedFileName.length - start));
- if (this.resolver instanceof DefaultBindingResolver) {
- IJavaScriptUnit workingCopy = cu.findWorkingCopy(((DefaultBindingResolver) this.resolver).workingCopyOwner);
- if (workingCopy != null)
- return workingCopy;
- }
- return cu;
- }
-
- /*
- * @see ITypeBinding#getComponentType()
- */
- public ITypeBinding getComponentType() {
- return null;
- }
-
- /*
- * @see ITypeBinding#getDeclaredFields()
- */
- public IVariableBinding[] getDeclaredFields() {
- try {
- ReferenceBinding referenceBinding = (ReferenceBinding) this.binding;
- FieldBinding[] fields = referenceBinding.fields();
- int length = fields.length;
- IVariableBinding[] newFields = new IVariableBinding[length];
- for (int i = 0; i < length; i++) {
- newFields[i] = this.resolver.getVariableBinding(fields[i]);
- }
- return newFields;
- } 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
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299
- */
- }
- return NO_VARIABLE_BINDINGS;
- }
-
-
- /*
- * @see ITypeBinding#getDeclaredMethods()
- */
- public IFunctionBinding[] getDeclaredMethods() {
- try {
- ReferenceBinding referenceBinding = (ReferenceBinding) this.binding;
- org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding[] methods = referenceBinding.methods();
- int length = methods.length;
- IFunctionBinding[] newMethods = new IFunctionBinding[length];
- for (int i = 0; i < length; i++) {
- org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding methodBinding = methods[i];
-// if (!shouldBeRemoved(methodBinding)) {
- newMethods[i] = this.resolver.getMethodBinding(methodBinding);
-// }
- }
- return newMethods;
- } 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
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299
- */
- }
- return NO_METHOD_BINDINGS;
- }
-
- /*
- * @see ITypeBinding#getDeclaredModifiers()
- */
- public int getDeclaredModifiers() {
- return getModifiers();
- }
-
- /*
- * @see ITypeBinding#getDeclaredTypes()
- */
- public ITypeBinding[] getDeclaredTypes() {
-
- return NO_TYPE_BINDINGS;
- }
-
- /*
- * @see ITypeBinding#getDeclaringMethod()
- */
- public IFunctionBinding getDeclaringMethod() {
-
- return null;
- }
-
- /*
- * @see ITypeBinding#getDeclaringClass()
- */
- public ITypeBinding getDeclaringClass() {
-
- return null;
- }
-
- /*
- * @see ITypeBinding#getDimensions()
- */
- public int getDimensions() {
- return 0;
- }
-
- /*
- * @see ITypeBinding#getElementType()
- */
- public ITypeBinding getElementType() {
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#getTypeDeclaration()
- */
- public ITypeBinding getTypeDeclaration() {
- return this;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#getErasure()
- */
- public ITypeBinding getErasure() {
- return this.resolver.getTypeBinding(this.binding);
- }
-
- public ITypeBinding[] getInterfaces() {
-// if (this.binding == null)
- return NO_TYPE_BINDINGS;
-// switch (this.binding.kind()) {
-// case Binding.ARRAY_TYPE :
-// case Binding.BASE_TYPE :
-// return NO_TYPE_BINDINGS;
-// }
-// ReferenceBinding referenceBinding = (ReferenceBinding) this.binding;
-// ReferenceBinding[] interfaces = null;
-// try {
-// interfaces = referenceBinding.superInterfaces();
-// } 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
-// * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550
-// * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299
-// */
-// }
-// if (interfaces == null) {
-// return NO_TYPE_BINDINGS;
-// }
-// int length = interfaces.length;
-// if (length == 0) {
-// return NO_TYPE_BINDINGS;
-// } else {
-// ITypeBinding[] newInterfaces = new ITypeBinding[length];
-// for (int i = 0; i < length; i++) {
-// ITypeBinding typeBinding = this.resolver.getTypeBinding(interfaces[i]);
-// if (typeBinding == null) {
-// return NO_TYPE_BINDINGS;
-// }
-// newInterfaces[i] = typeBinding;
-// }
-// return newInterfaces;
-// }
- }
-
- public IJavaScriptElement getJavaElement() {
- JavaElement element = getUnresolvedJavaElement();
- if (element == null)
- return null;
- return element.resolved(this.binding);
- }
-
- private JavaElement getUnresolvedJavaElement() {
- return getUnresolvedJavaElement(this.binding);
- }
- private JavaElement getUnresolvedJavaElement(org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding typeBinding ) {
- if (typeBinding == null)
- return null;
-
- ReferenceBinding referenceBinding = (ReferenceBinding) typeBinding;
- char[] fileName = referenceBinding.getFileName();
- if (fileName == null) return null; // case of a WilCardBinding that doesn't have a corresponding JavaScript element
- // member or top level type
- ITypeBinding declaringTypeBinding = getDeclaringClass();
- if (declaringTypeBinding == null) {
- // top level type
- if (((ReferenceBinding)this.binding).isBinaryBinding()) {
- ClassFile classFile = (ClassFile) getClassFile(fileName);
- return classFile;
- }
- IJavaScriptUnit cu = getCompilationUnit(fileName);
- return (JavaElement)cu;
- } else {
- // member type
- IType declaringType = (IType) declaringTypeBinding.getJavaElement();
- if (declaringType == null) return null;
- return (JavaElement) declaringType.getType(new String(referenceBinding.sourceName()));
- }
- }
-
- /*
- * @see IBinding#getKey()
- */
- public String getKey() {
- if (this.key == null) {
- this.key = new String(this.binding.computeUniqueKey());
- }
- return this.key;
- }
-
- /*
- * @see IBinding#getKind()
- */
- public int getKind() {
- return IBinding.TYPE;
- }
-
- /*
- * @see IBinding#getModifiers()
- */
- public int getModifiers() {
- if (isClass()) {
- ReferenceBinding referenceBinding = (ReferenceBinding) this.binding;
- final int accessFlags = referenceBinding.getAccessFlags() & VALID_MODIFIERS;
- if (referenceBinding.isAnonymousType()) {
- return accessFlags & ~Modifier.FINAL;
- }
- return accessFlags;
- } else if (isAnnotation()) {
- ReferenceBinding referenceBinding = (ReferenceBinding) this.binding;
- final int accessFlags = referenceBinding.getAccessFlags() & VALID_MODIFIERS;
- // clear the AccAbstract, AccAnnotation and the AccInterface bits
- return accessFlags & ~(ClassFileConstants.AccAbstract);
- } else if (isInterface()) {
- ReferenceBinding referenceBinding = (ReferenceBinding) this.binding;
- final int accessFlags = referenceBinding.getAccessFlags() & VALID_MODIFIERS;
- // clear the AccAbstract and the AccInterface bits
- return accessFlags & ~(ClassFileConstants.AccAbstract);
- } else {
- return 0;
- }
- }
-
- public String getName() {
- return new String(this.binding.sourceName());
- }
-
- /*
- * @see ITypeBinding#getPackage()
- */
- public IPackageBinding getPackage() {
- switch (this.binding.kind()) {
- case Binding.BASE_TYPE :
- case Binding.ARRAY_TYPE :
- return null;
- }
- ReferenceBinding referenceBinding = (ReferenceBinding) this.binding;
- return this.resolver.getPackageBinding(referenceBinding.getPackage());
- }
-
- /*
- * Returns the package that includes the given file name, or null if not found.
- * pkgEnd == jarSeparator if default package in a jar
- * pkgEnd > jarSeparator if non default package in a jar
- * pkgEnd > 0 if package not in a jar
- *
- * @see org.eclipse.wst.jsdt.internal.compiler.env.IDependent#getFileName()
- */
- private IPackageFragment getPackageFragment(char[] fileName, int pkgEnd, int jarSeparator) {
- if (jarSeparator != -1) {
- String jarMemento = new String(fileName, 0, jarSeparator);
- IPackageFragmentRoot root = (IPackageFragmentRoot) JavaScriptCore.create(jarMemento);
- if (pkgEnd == jarSeparator)
- return root.getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME);
- char[] pkgName = CharOperation.subarray(fileName, jarSeparator+1, pkgEnd);
- CharOperation.replace(pkgName, '/', '.');
- return root.getPackageFragment(new String(pkgName));
- } else {
- Path path = new Path(new String(fileName, 0, pkgEnd));
- IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
- IContainer folder = path.segmentCount() == 1 ? workspaceRoot.getProject(path.lastSegment()) : (IContainer) workspaceRoot.getFolder(path);
- IJavaScriptElement element = JavaScriptCore.create(folder);
- if (element == null) return null;
- switch (element.getElementType()) {
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- return (IPackageFragment) element;
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- return ((IPackageFragmentRoot) element).getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME);
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- IPackageFragmentRoot root = ((IJavaScriptProject) element).getPackageFragmentRoot(folder);
- if (root == null) return null;
- return root.getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME);
- }
- return null;
- }
- }
-
- /**
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#getQualifiedName()
- */
- public String getQualifiedName() {
- StringBuffer buffer;
-// switch (this.binding.kind()) {
-//
-// case Binding.RAW_TYPE :
-// return getTypeDeclaration().getQualifiedName();
-//
-// case Binding.ARRAY_TYPE :
-// ITypeBinding elementType = getElementType();
-// if (elementType.isLocal() || elementType.isAnonymous() || elementType.isCapture()) {
-// return NO_NAME;
-// }
-// final int dimensions = getDimensions();
-// char[] brackets = new char[dimensions * 2];
-// for (int i = dimensions * 2 - 1; i >= 0; i -= 2) {
-// brackets[i] = ']';
-// brackets[i - 1] = '[';
-// }
-// buffer = new StringBuffer(elementType.getQualifiedName());
-// buffer.append(brackets);
-// return String.valueOf(buffer);
-//
-// case Binding.TYPE_PARAMETER :
-// if (isCapture()) {
-// return NO_NAME;
-// }
-// TypeVariableBinding typeVariableBinding = (TypeVariableBinding) this.binding;
-// return new String(typeVariableBinding.sourceName);
-//
-// case Binding.PARAMETERIZED_TYPE :
-// buffer = new StringBuffer();
-// if (isMember()) {
-// buffer
-// .append(getDeclaringClass().getQualifiedName())
-// .append('.');
-// ParameterizedTypeBinding parameterizedTypeBinding = (ParameterizedTypeBinding) this.binding;
-// buffer.append(parameterizedTypeBinding.sourceName());
-// ITypeBinding[] typeArguments = getTypeArguments();
-// final int typeArgumentsLength = typeArguments.length;
-// if (typeArgumentsLength != 0) {
-// buffer.append('<');
-// for (int i = 0, max = typeArguments.length; i < max; i++) {
-// if (i > 0) {
-// buffer.append(',');
-// }
-// buffer.append(typeArguments[i].getQualifiedName());
-// }
-// buffer.append('>');
-// }
-// return String.valueOf(buffer);
-// }
-// buffer.append(getTypeDeclaration().getQualifiedName());
-// ITypeBinding[] typeArguments = getTypeArguments();
-// final int typeArgumentsLength = typeArguments.length;
-// if (typeArgumentsLength != 0) {
-// buffer.append('<');
-// for (int i = 0, max = typeArguments.length; i < max; i++) {
-// if (i > 0) {
-// buffer.append(',');
-// }
-// buffer.append(typeArguments[i].getQualifiedName());
-// }
-// buffer.append('>');
-// }
-// return String.valueOf(buffer);
-//
-// default :
- if (isAnonymous() || isLocal()) {
- return NO_NAME;
- }
- if (isPrimitive() || isNullType()) {
- BaseTypeBinding baseTypeBinding = (BaseTypeBinding) this.binding;
- return new String(baseTypeBinding.simpleName);
- }
- if (isMember()) {
- buffer = new StringBuffer();
- buffer
- .append(getDeclaringClass().getQualifiedName())
- .append('.');
- buffer.append(getName());
- return String.valueOf(buffer);
- }
- PackageBinding packageBinding = this.binding.getPackage();
- buffer = new StringBuffer();
- if (packageBinding != null && packageBinding.compoundName != CharOperation.NO_CHAR_CHAR) {
- buffer.append(CharOperation.concatWith(packageBinding.compoundName, '.')).append('.');
- }
- buffer.append(getName());
- return String.valueOf(buffer);
-// }
- }
-
- /*
- * @see ITypeBinding#getSuperclass()
- */
- public ITypeBinding getSuperclass() {
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#getTypeArguments()
- */
- public ITypeBinding[] getTypeArguments() {
- return NO_TYPE_BINDINGS;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#getTypeBounds()
- */
- public ITypeBinding[] getTypeBounds() {
- return NO_TYPE_BINDINGS;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#getTypeParameters()
- */
- public ITypeBinding[] getTypeParameters() {
- return NO_TYPE_BINDINGS;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#isGenericType()
- *
- */
- public boolean isGenericType() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#isAnnotation()
- */
- public boolean isAnnotation() {
- return false;
- }
-
- /*
- * @see ITypeBinding#isAnonymous()
- */
- public boolean isAnonymous() {
- return false;
- }
-
- /*
- * @see ITypeBinding#isArray()
- */
- public boolean isArray() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see ITypeBinding#isAssignmentCompatible(ITypeBinding)
- */
- public boolean isAssignmentCompatible(ITypeBinding type) {
- return false;
- }
-
- /* (non-Javadoc)
- * @see ITypeBinding#isCapture()
- */
- public boolean isCapture() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see ITypeBinding#isCastCompatible(ITypeBinding)
- */
- public boolean isCastCompatible(ITypeBinding type) {
- return false;
- }
-
- /*
- * @see ITypeBinding#isClass()
- */
- public boolean isClass() {
- return this.binding.isClass();
- }
-
- /*
- * @see IBinding#isDeprecated()
- */
- public boolean isDeprecated() {
- if (isClass() || isInterface() || isEnum()) {
- ReferenceBinding referenceBinding = (ReferenceBinding) this.binding;
- return referenceBinding.isDeprecated();
- }
- return false;
- }
-
- /* (non-Javadoc)
- * @see ITypeBinding#isEnum()
- */
- public boolean isEnum() {
- return false;
- }
-
- /*
- * @see IBinding#isEqualTo(Binding)
- *
- */
- public boolean isEqualTo(IBinding other) {
- if (other == this) {
- // identical binding - equal (key or no key)
- return true;
- }
- if (other == null) {
- // other binding missing
- return false;
- }
- if (!(other instanceof JavaScriptUnitBinding)) {
- return false;
- }
- org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding otherBinding = ((JavaScriptUnitBinding) other).binding;
- // check return type
- return BindingComparator.isEqual(this.binding, otherBinding);
- }
-
- /*
- * @see ITypeBinding#isFromSource()
- */
- public boolean isFromSource() {
- return !((ReferenceBinding)this.binding).isBinaryBinding();
- }
-
- /*
- * @see ITypeBinding#isInterface()
- */
- public boolean isInterface() {
- return false;
- }
-
- /*
- * @see ITypeBinding#isLocal()
- */
- public boolean isLocal() {
- return true;
- }
-
- /*
- * @see ITypeBinding#isMember()
- */
- public boolean isMember() {
- return false;
- }
-
- /*
- * @see ITypeBinding#isNested()
- */
- public boolean isNested() {
- return false;
- }
-
- /**
- * @see ITypeBinding#isNullType()
- */
- public boolean isNullType() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#isParameterizedType()
- */
- public boolean isParameterizedType() {
- return false;
- }
-
- /*
- * @see ITypeBinding#isPrimitive()
- */
- public boolean isPrimitive() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#isRawType()
- */
- public boolean isRawType() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see ITypeBinding#isSubTypeCompatible(ITypeBinding)
- */
- public boolean isSubTypeCompatible(ITypeBinding type) {
- return false;
- }
-
- /*
- * @see ITypeBinding#isTopLevel()
- */
- public boolean isTopLevel() {
- return true;
- }
-
- /*
- * @see ITypeBinding#isTypeVariable()
- */
- public boolean isTypeVariable() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#isUpperbound()
- */
- public boolean isUpperbound() {
- return false;
- }
-
- /*
- * For debugging purpose only.
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return this.binding.toString();
- }
- public boolean isCompilationUnit()
- {
- return true;
- }
-
- private IClassFile getClassFile(char[] fileName) {
- int jarSeparator = CharOperation.indexOf(IDependent.JAR_FILE_ENTRY_SEPARATOR, fileName);
- int pkgEnd = CharOperation.lastIndexOf('/', fileName); // pkgEnd is exclusive
- if (pkgEnd == -1)
- pkgEnd = CharOperation.lastIndexOf(File.separatorChar, fileName);
- if (jarSeparator != -1 && pkgEnd < jarSeparator) // if in a jar and no slash, it is a default package -> pkgEnd should be equal to jarSeparator
- pkgEnd = jarSeparator;
- if (pkgEnd == -1)
- return null;
- IPackageFragment pkg = getPackageFragment(fileName, pkgEnd, jarSeparator);
- if (pkg == null) return null;
- int start;
- return pkg.getClassFile(new String(fileName, start = pkgEnd + 1, fileName.length - start));
- }
-
- public boolean isRecovered() {
- return false;
- }
-
-}
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
deleted file mode 100644
index 205d21c6..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/JavaScriptUnitResolver.java
+++ /dev/null
@@ -1,931 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-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;
-import org.eclipse.wst.jsdt.internal.compiler.ICompilerRequestor;
-import org.eclipse.wst.jsdt.internal.compiler.IErrorHandlingPolicy;
-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.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.lookup.Binding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ExtraCompilerModifiers;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding;
-import org.eclipse.wst.jsdt.internal.compiler.parser.Parser;
-import org.eclipse.wst.jsdt.internal.compiler.problem.AbortCompilation;
-import org.eclipse.wst.jsdt.internal.compiler.problem.DefaultProblemFactory;
-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.HashtableOfObjectToInt;
-import org.eclipse.wst.jsdt.internal.compiler.util.Messages;
-import org.eclipse.wst.jsdt.internal.core.BinaryMember;
-import org.eclipse.wst.jsdt.internal.core.CancelableNameEnvironment;
-import org.eclipse.wst.jsdt.internal.core.CancelableProblemFactory;
-import org.eclipse.wst.jsdt.internal.core.JavaProject;
-import org.eclipse.wst.jsdt.internal.core.NameLookup;
-import org.eclipse.wst.jsdt.internal.core.SourceRefElement;
-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;
-
-/**
- *
- * 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.
- */
-class JavaScriptUnitResolver extends Compiler {
-
- /* A list of int */
- static class IntArrayList {
- public int[] list = new int[5];
- public int length = 0;
- public void add(int i) {
- if (this.list.length == this.length) {
- System.arraycopy(this.list, 0, this.list = new int[this.length*2], 0, this.length);
- }
- this.list[this.length++] = i;
- }
- }
-
- /*
- * The sources that were requested.
- * Map from file name (char[]) to IJavaScriptUnit.
- */
- HashtableOfObject requestedSources;
-
- /*
- * The binding keys that were requested.
- * Map from file name (char[]) to BindingKey (or ArrayList if multiple keys in the same file).
- */
- HashtableOfObject requestedKeys;
-
- DefaultBindingResolver.BindingTables bindingTables;
-
- boolean hasCompilationAborted;
-
- private IProgressMonitor monitor;
-
- /**
- * Answer a new CompilationUnitVisitor using the given name environment and validator options.
- * The environment and options will be in effect for the lifetime of the compiler.
- * When the validator is run, compilation results are sent to the given requestor.
- *
- * @param environment org.eclipse.wst.jsdt.internal.compiler.api.env.INameEnvironment
- * Environment used by the validator in order to resolve type and package
- * names. The name environment implements the actual connection of the compiler
- * to the outside world (for example, in batch mode the name environment is performing
- * pure file accesses, reuse previous build state or connection to repositories).
- * Note: the name environment is responsible for implementing the actual includepath
- * rules.
- *
- * @param policy org.eclipse.wst.jsdt.internal.compiler.api.problem.IErrorHandlingPolicy
- * Configurable part for problem handling, allowing the validator client to
- * specify the rules for handling problems (stop on first error or accumulate
- * them all) and at the same time perform some actions such as opening a dialog
- * in UI when validating interactively.
- * @see org.eclipse.wst.jsdt.internal.compiler.DefaultErrorHandlingPolicies
- *
- * @param compilerOptions The validator options to use for the resolution.
- *
- * @param requestor org.eclipse.wst.jsdt.internal.compiler.api.ICompilerRequestor
- * Component which will receive and persist all compilation results and is intended
- * to consume them as they are produced. Typically, in a batch compiler, it is
- * responsible for writing out the actual .class files to the file system.
- * @see org.eclipse.wst.jsdt.internal.compiler.CompilationResult
- *
- * @param problemFactory org.eclipse.wst.jsdt.internal.compiler.api.problem.IProblemFactory
- * Factory used inside the validator to create problem descriptors. It allows the
- * validator client to supply its own representation of compilation problems in
- * order to avoid object conversions. Note that the factory is not supposed
- * to accumulate the created problems, the validator will gather them all and hand
- * them back as part of the javaScript unit result.
- */
- public JavaScriptUnitResolver(
- INameEnvironment environment,
- IErrorHandlingPolicy policy,
- CompilerOptions compilerOptions,
- ICompilerRequestor requestor,
- IProblemFactory problemFactory,
- IProgressMonitor monitor) {
-
- super(environment, policy, compilerOptions, requestor, problemFactory);
- this.hasCompilationAborted = false;
- this.monitor =monitor;
- }
-
- /*
- * Add additional source types
- */
- public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding, AccessRestriction accessRestriction) {
- // 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);
- }
-
- /**
- * Add the initial set of javaScript units into the loop
- * -> build javaScript unit declarations, their bindings and record their results.
- */
- protected void beginToCompile(org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit[] sourceUnits, String[] bindingKeys) {
- int sourceLength = sourceUnits.length;
- int keyLength = bindingKeys.length;
- int maxUnits = sourceLength + keyLength;
- this.totalUnits = 0;
- this.unitsToProcess = new CompilationUnitDeclaration[maxUnits];
- int index = 0;
-
- // walks the source units
- this.requestedSources = new HashtableOfObject();
- for (int i = 0; i < sourceLength; i++) {
- org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit sourceUnit = sourceUnits[i];
- CompilationUnitDeclaration parsedUnit;
- CompilationResult unitResult =
- new CompilationResult(sourceUnit, index++, maxUnits, this.options.maxProblemsPerUnit);
- try {
- if (options.verbose) {
- this.out.println(
- Messages.bind(Messages.compilation_request,
- new String[] {
- String.valueOf(index++ + 1),
- String.valueOf(maxUnits),
- new String(sourceUnit.getFileName())
- }));
- }
- // diet parsing for large collection of units
- if (this.totalUnits < this.parseThreshold) {
- parsedUnit = this.parser.parse(sourceUnit, unitResult);
- } else {
- parsedUnit = this.parser.dietParse(sourceUnit, unitResult);
- }
- // initial type binding creation
- this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/);
- addCompilationUnit(sourceUnit, parsedUnit);
- this.requestedSources.put(unitResult.getFileName(), sourceUnit);
- worked(1);
- } finally {
- sourceUnits[i] = null; // no longer hold onto the unit
- }
- }
-
- // walk the binding keys
- this.requestedKeys = new HashtableOfObject();
- for (int i = 0; i < keyLength; i++) {
- BindingKeyResolver resolver = new BindingKeyResolver(bindingKeys[i], this, this.lookupEnvironment);
- resolver.parse(true/*pause after fully qualified name*/);
- // If it doesn't have a type name, then it is either an array type, package or base type, which will definitely not have a javaScript unit.
- // Skipping it will speed up performance because the call will open jars. (theodora)
- CompilationUnitDeclaration parsedUnit = resolver.hasTypeName() ? resolver.getCompilationUnitDeclaration() : null;
- if (parsedUnit != null) {
- char[] fileName = parsedUnit.compilationResult.getFileName();
- Object existing = this.requestedKeys.get(fileName);
- if (existing == null)
- this.requestedKeys.put(fileName, resolver);
- else if (existing instanceof ArrayList)
- ((ArrayList) existing).add(resolver);
- else {
- ArrayList list = new ArrayList();
- list.add(existing);
- list.add(resolver);
- this.requestedKeys.put(fileName, list);
- }
-
- } else {
- char[] key = resolver.hasTypeName()
- ? resolver.getKey().toCharArray() // binary binding
- : CharOperation.concatWith(resolver.compoundName(), '.'); // package binding or base type binding
- this.requestedKeys.put(key, resolver);
- }
- worked(1);
- }
-
- // binding resolution
- lookupEnvironment.completeTypeBindings();
- }
-
- IBinding createBinding(String key) {
- if (this.bindingTables == null)
- throw new RuntimeException("Cannot be called outside ASTParser#createASTs(...)"); //$NON-NLS-1$
- BindingKeyResolver keyResolver = new BindingKeyResolver(key, this, this.lookupEnvironment);
- Binding compilerBinding = keyResolver.getCompilerBinding();
- if (compilerBinding == null) return null;
- DefaultBindingResolver resolver = new DefaultBindingResolver(this.lookupEnvironment, null/*no owner*/, this.bindingTables, false);
- return resolver.getBinding(compilerBinding);
- }
-
- public static JavaScriptUnit convert(CompilationUnitDeclaration compilationUnitDeclaration, char[] source, int apiLevel, Map options, boolean needToResolveBindings, WorkingCopyOwner owner, DefaultBindingResolver.BindingTables bindingTables, int flags, IProgressMonitor monitor) {
- BindingResolver resolver = null;
- AST ast = AST.newAST(apiLevel);
- ast.setDefaultNodeFlag(ASTNode.ORIGINAL);
- JavaScriptUnit compilationUnit = null;
- ASTConverter converter = new ASTConverter(options, needToResolveBindings, monitor);
- if (needToResolveBindings) {
- resolver = new DefaultBindingResolver(compilationUnitDeclaration.scope, owner, bindingTables, (flags & IJavaScriptUnit.ENABLE_BINDINGS_RECOVERY) != 0);
- ast.setFlag(flags | AST.RESOLVED_BINDINGS);
- } else {
- resolver = new BindingResolver();
- ast.setFlag(flags);
- }
- ast.setBindingResolver(resolver);
- converter.setAST(ast);
- compilationUnit = converter.convert(compilationUnitDeclaration, source);
- compilationUnit.setLineEndTable(compilationUnitDeclaration.compilationResult.getLineSeparatorPositions());
- ast.setDefaultNodeFlag(0);
- ast.setOriginalModificationCount(ast.modificationCount());
- return compilationUnit;
- }
-
- protected static CompilerOptions getCompilerOptions(Map options, boolean statementsRecovery) {
- CompilerOptions compilerOptions = new CompilerOptions(options);
- compilerOptions.performMethodsFullRecovery = statementsRecovery;
- compilerOptions.performStatementsRecovery = statementsRecovery;
- compilerOptions.parseLiteralExpressionsAsConstants = false;
- compilerOptions.storeAnnotations = true /*store annotations in the bindings*/;
- return compilerOptions;
- }
- /*
- * Low-level API performing the actual compilation
- */
- protected static IErrorHandlingPolicy getHandlingPolicy() {
-
- // passes the initial set of files to the batch oracle (to avoid finding more than once the same units when case insensitive match)
- return new IErrorHandlingPolicy() {
- public boolean stopOnFirstError() {
- return false;
- }
- public boolean proceedOnErrors() {
- return false; // stop if there are some errors
- }
- };
- }
-
- /*
- * Answer the component to which will be handed back compilation results from the compiler
- */
- protected static ICompilerRequestor getRequestor() {
- return new ICompilerRequestor() {
- public void acceptResult(CompilationResult compilationResult) {
- // do nothing
- }
- };
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.Compiler#initializeParser()
- */
- public void initializeParser() {
- this.parser = new CommentRecorderParser(this.problemReporter, false);
- }
- public void process(CompilationUnitDeclaration unit, int i) {
- // don't resolve a second time the same unit (this would create the same binding twice)
- char[] fileName = unit.compilationResult.getFileName();
- if (!this.requestedKeys.containsKey(fileName) && !this.requestedSources.containsKey(fileName))
- super.process(unit, i);
- }
- /*
- * Compiler crash recovery in case of unexpected runtime exceptions
- */
- protected void handleInternalException(
- Throwable internalException,
- CompilationUnitDeclaration unit,
- CompilationResult result) {
- super.handleInternalException(internalException, unit, result);
- if (unit != null) {
- removeUnresolvedBindings(unit);
- }
- }
-
- /*
- * Compiler recovery in case of internal AbortCompilation event
- */
- protected void handleInternalException(
- AbortCompilation abortException,
- CompilationUnitDeclaration unit) {
- super.handleInternalException(abortException, unit);
- if (unit != null) {
- removeUnresolvedBindings(unit);
- }
- this.hasCompilationAborted = true;
- }
-
- public static void parse(IJavaScriptUnit[] compilationUnits, ASTRequestor astRequestor, int apiLevel, Map options, int flags, IProgressMonitor monitor) {
- try {
- CompilerOptions compilerOptions = new CompilerOptions(options);
- Parser parser = new CommentRecorderParser(
- new ProblemReporter(
- DefaultErrorHandlingPolicies.proceedWithAllProblems(),
- compilerOptions,
- new DefaultProblemFactory()),
- false);
- int length = compilationUnits.length;
- if (monitor != null) monitor.beginTask("", length); //$NON-NLS-1$
- for (int i = 0; i < length; i++) {
- org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit sourceUnit = (org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit) compilationUnits[i];
- CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, compilerOptions.maxProblemsPerUnit);
- CompilationUnitDeclaration compilationUnitDeclaration = parser.dietParse(sourceUnit, compilationResult);
- parser.inferTypes(compilationUnitDeclaration, compilerOptions);
-
- if (compilationUnitDeclaration.ignoreMethodBodies) {
- compilationUnitDeclaration.ignoreFurtherInvestigation = true;
- // if initial diet parse did not work, no need to dig into method bodies.
- continue;
- }
-
- //fill the methods bodies in order for the code to be generated
- //real parse of the method....
- org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration[] types = compilationUnitDeclaration.types;
- if (types != null) {
- for (int j = types.length; --j >= 0;)
- types[j].parseMethod(parser, compilationUnitDeclaration);
- }
-
- // convert AST
- JavaScriptUnit node = convert(compilationUnitDeclaration, parser.scanner.getSource(), apiLevel, options, false/*don't resolve binding*/, null/*no owner needed*/, null/*no binding table needed*/, flags /* flags */, monitor);
- node.setTypeRoot(compilationUnits[i]);
-
- // accept AST
- astRequestor.acceptAST(compilationUnits[i], node);
-
- if (monitor != null) monitor.worked(1);
- }
- } finally {
- if (monitor != null) monitor.done();
- }
- }
-
- public static CompilationUnitDeclaration parse(
- org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit sourceUnit,
- NodeSearcher nodeSearcher,
- Map settings,
- int flags) {
- if (sourceUnit == null) {
- throw new IllegalStateException();
- }
- CompilerOptions compilerOptions = new CompilerOptions(settings);
- boolean statementsRecovery = (flags & IJavaScriptUnit.ENABLE_STATEMENTS_RECOVERY) != 0;
- compilerOptions.performMethodsFullRecovery = statementsRecovery;
- compilerOptions.performStatementsRecovery = statementsRecovery;
- Parser parser = new CommentRecorderParser(
- new ProblemReporter(
- DefaultErrorHandlingPolicies.proceedWithAllProblems(),
- compilerOptions,
- new DefaultProblemFactory()),
- false);
- CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, compilerOptions.maxProblemsPerUnit);
- CompilationUnitDeclaration compilationUnitDeclaration = parser.dietParse(sourceUnit, compilationResult);
-
- parser.inferTypes(compilationUnitDeclaration, compilerOptions);
- if (compilationUnitDeclaration.ignoreMethodBodies) {
- compilationUnitDeclaration.ignoreFurtherInvestigation = true;
- // if initial diet parse did not work, no need to dig into method bodies.
- return null;
- }
-
- if (nodeSearcher != null) {
- char[] source = parser.scanner.getSource();
- int searchPosition = nodeSearcher.position;
- if (searchPosition < 0 || searchPosition > source.length) {
- // the position is out of range. There is no need to search for a node.
- return compilationUnitDeclaration;
- }
-
- compilationUnitDeclaration.traverse(nodeSearcher, compilationUnitDeclaration.scope);
-
- org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode node = nodeSearcher.found;
- if (node == null) {
- return compilationUnitDeclaration;
- }
-
- org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration enclosingTypeDeclaration = nodeSearcher.enclosingType;
-
- if (node instanceof AbstractMethodDeclaration) {
- ((AbstractMethodDeclaration)node).parseStatements(parser, compilationUnitDeclaration);
- } else if (enclosingTypeDeclaration != null) {
- if (node instanceof org.eclipse.wst.jsdt.internal.compiler.ast.Initializer) {
- ((org.eclipse.wst.jsdt.internal.compiler.ast.Initializer) node).parseStatements(parser, enclosingTypeDeclaration, compilationUnitDeclaration);
- } else {
- ((org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration)node).parseMethod(parser, compilationUnitDeclaration);
- }
- }
- } else {
- //fill the methods bodies in order for the code to be generated
- //real parse of the method....
- org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration[] types = compilationUnitDeclaration.types;
- if (types != null) {
- for (int i = types.length; --i >= 0;)
- types[i].parseMethod(parser, compilationUnitDeclaration);
- }
- }
- return compilationUnitDeclaration;
- }
-
- public static void resolve(
- IJavaScriptUnit[] compilationUnits,
- String[] bindingKeys,
- ASTRequestor requestor,
- int apiLevel,
- Map options,
- IJavaScriptProject javaProject,
- WorkingCopyOwner owner,
- int flags,
- IProgressMonitor monitor) {
-
- CancelableNameEnvironment environment = null;
- CancelableProblemFactory problemFactory = null;
- try {
- if (monitor != null) {
- int amountOfWork = (compilationUnits.length + bindingKeys.length) * 2; // 1 for beginToCompile, 1 for resolve
- monitor.beginTask("", amountOfWork); //$NON-NLS-1$
- }
- environment = new CancelableNameEnvironment(((JavaProject) javaProject), owner, monitor);
- problemFactory = new CancelableProblemFactory(monitor);
- JavaScriptUnitResolver resolver =
- new JavaScriptUnitResolver(
- environment,
- getHandlingPolicy(),
- getCompilerOptions(options, (flags & IJavaScriptUnit.ENABLE_STATEMENTS_RECOVERY) != 0),
- getRequestor(),
- problemFactory,
- monitor);
-
- resolver.resolve(compilationUnits, bindingKeys, requestor, apiLevel, options, owner, flags);
- 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$
- }
- } catch (JavaScriptModelException e) {
- // project doesn't exist -> simple parse without resolving
- parse(compilationUnits, requestor, apiLevel, options, flags, monitor);
- } finally {
- if (monitor != null) monitor.done();
- if (environment != null) {
- environment.monitor = null; // don't hold a reference to this external object
- }
- if (problemFactory != null) {
- problemFactory.monitor = null; // don't hold a reference to this external object
- }
- }
- }
- public static CompilationUnitDeclaration resolve(
- org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit sourceUnit,
- IJavaScriptProject javaProject,
- NodeSearcher nodeSearcher,
- Map options,
- WorkingCopyOwner owner,
- int flags,
- IProgressMonitor monitor) throws JavaScriptModelException {
-
- CompilationUnitDeclaration unit = null;
- CancelableNameEnvironment environment = null;
- CancelableProblemFactory problemFactory = null;
- JavaScriptUnitResolver resolver = null;
- try {
- environment = new CancelableNameEnvironment(((JavaProject)javaProject), owner, monitor);
- environment.setCompilationUnit(sourceUnit);
- problemFactory = new CancelableProblemFactory(monitor);
- resolver =
- new JavaScriptUnitResolver(
- environment,
- getHandlingPolicy(),
- getCompilerOptions(options, (flags & IJavaScriptUnit.ENABLE_STATEMENTS_RECOVERY) != 0),
- getRequestor(),
- problemFactory,
- monitor);
-
- unit =
- resolver.resolve(
- null, // no existing javaScript unit declaration
- sourceUnit,
- nodeSearcher,
- true, // method verification
- true, // analyze code
- true); // generate code
- if (resolver.hasCompilationAborted) {
- // the bindings could not be resolved due to missing types in name environment
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=86541
- CompilationUnitDeclaration unitDeclaration = parse(sourceUnit, nodeSearcher, options, flags);
- final int problemCount = unit.compilationResult.problemCount;
- if (problemCount != 0) {
- unitDeclaration.compilationResult.problems = new CategorizedProblem[problemCount];
- System.arraycopy(unit.compilationResult.problems, 0, unitDeclaration.compilationResult.problems, 0, problemCount);
- unitDeclaration.compilationResult.problemCount = problemCount;
- }
- return unitDeclaration;
- }
- 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 unit;
- } finally {
- if (environment != null) {
- environment.monitor = null; // don't hold a reference to this external object
- }
- if (problemFactory != null) {
- problemFactory.monitor = null; // don't hold a reference to this external object
- }
- // first unit cleanup is done by caller, but cleanup all enqueued requested units (not processed)
-// if (resolver != null) {
-// for (int i = 1; i < resolver.totalUnits; i++) { // could be more requested units
-// CompilationUnitDeclaration parsedUnit = resolver.unitsToProcess[i];
-// if (parsedUnit.scope != null)
-// parsedUnit.scope.faultInTypes(); // force resolution of signatures, so clients can query DOM AST
-// parsedUnit.cleanUp();
-// }
-// }
- }
- }
- public static IBinding[] resolve(
- final IJavaScriptElement[] elements,
- int apiLevel,
- Map compilerOptions,
- IJavaScriptProject javaProject,
- WorkingCopyOwner owner,
- int flags,
- IProgressMonitor monitor) {
-
- final int length = elements.length;
- final HashMap sourceElementPositions = new HashMap(); // a map from IJavaScriptUnit to int[] (positions in elements)
- int cuNumber = 0;
- final HashtableOfObjectToInt binaryElementPositions = new HashtableOfObjectToInt(); // a map from String (binding key) to int (position in elements)
- for (int i = 0; i < length; i++) {
- IJavaScriptElement element = elements[i];
- if (!(element instanceof SourceRefElement))
- throw new IllegalStateException(element + " is not part of a javaScript unit or class file"); //$NON-NLS-1$
- Object cu = element.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- if (cu != null) {
- // source member
- IntArrayList intList = (IntArrayList) sourceElementPositions.get(cu);
- if (intList == null) {
- sourceElementPositions.put(cu, intList = new IntArrayList());
- cuNumber++;
- }
- intList.add(i);
- } else {
- // binary member
- try {
- String key = ((BinaryMember) element).getKey(true/*open to get resolved info*/);
- binaryElementPositions.put(key, i);
- } catch (JavaScriptModelException e) {
- throw new IllegalArgumentException(element + " does not exist"); //$NON-NLS-1$
- }
- }
- }
- IJavaScriptUnit[] cus = new IJavaScriptUnit[cuNumber];
- sourceElementPositions.keySet().toArray(cus);
-
- int bindingKeyNumber = binaryElementPositions.size();
- String[] bindingKeys = new String[bindingKeyNumber];
- binaryElementPositions.keysToArray(bindingKeys);
-
- class Requestor extends ASTRequestor {
- IBinding[] bindings = new IBinding[length];
- public void acceptAST(IJavaScriptUnit source, JavaScriptUnit ast) {
- // TODO (jerome) optimize to visit the AST only once
- IntArrayList intList = (IntArrayList) sourceElementPositions.get(source);
- for (int i = 0; i < intList.length; i++) {
- final int index = intList.list[i];
- SourceRefElement element = (SourceRefElement) elements[index];
- DOMFinder finder = new DOMFinder(ast, element, true/*resolve binding*/);
- try {
- finder.search();
- } catch (JavaScriptModelException e) {
- throw new IllegalArgumentException(element + " does not exist"); //$NON-NLS-1$
- }
- this.bindings[index] = finder.foundBinding;
- }
- }
- public void acceptBinding(String bindingKey, IBinding binding) {
- int index = binaryElementPositions.get(bindingKey);
- this.bindings[index] = binding;
- }
- }
- Requestor requestor = new Requestor();
- resolve(cus, bindingKeys, requestor, apiLevel, compilerOptions, javaProject, owner, flags, monitor);
- return requestor.bindings;
- }
- /*
- * When unit result is about to be accepted, removed back pointers
- * to unresolved bindings
- */
- public void removeUnresolvedBindings(CompilationUnitDeclaration compilationUnitDeclaration) {
- final org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration[] types = compilationUnitDeclaration.types;
- if (types != null) {
- for (int i = 0, max = types.length; i < max; i++) {
- removeUnresolvedBindings(types[i]);
- }
- }
- }
- private void removeUnresolvedBindings(org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration type) {
- final org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration[] memberTypes = type.memberTypes;
- if (memberTypes != null) {
- for (int i = 0, max = memberTypes.length; i < max; i++){
- removeUnresolvedBindings(memberTypes[i]);
- }
- }
- if (type.binding != null && (type.binding.modifiers & ExtraCompilerModifiers.AccUnresolved) != 0) {
- type.binding = null;
- }
-
- final org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration[] fields = type.fields;
- if (fields != null) {
- for (int i = 0, max = fields.length; i < max; i++){
- if (fields[i].binding != null && (fields[i].binding.modifiers & ExtraCompilerModifiers.AccUnresolved) != 0) {
- fields[i].binding = null;
- }
- }
- }
-
- 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;
- }
- }
- }
- }
-
- private void resolve(IJavaScriptUnit[] compilationUnits, String[] bindingKeys, ASTRequestor astRequestor, int apiLevel, Map compilerOptions, WorkingCopyOwner owner, int flags) {
-
- // temporararily connect ourselves to the ASTResolver - must disconnect when done
- astRequestor.compilationUnitResolver = this;
- this.bindingTables = new DefaultBindingResolver.BindingTables();
- CompilationUnitDeclaration unit = null;
- int i = 0;
- try {
- int length = compilationUnits.length;
- org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit[] sourceUnits = new org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit[length];
- System.arraycopy(compilationUnits, 0, sourceUnits, 0, length);
- beginToCompile(sourceUnits, bindingKeys);
- // process all units (some more could be injected in the loop by the lookup environment)
- for (; i < this.totalUnits; i++) {
- if (this.requestedSources.size() == 0 && this.requestedKeys.size() == 0) {
- // no need to keep resolving if no more ASTs and no more binding keys are needed
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=114935
- // cleanup remaining units
- for (; i < this.totalUnits; i++) {
- this.unitsToProcess[i].cleanUp();
- this.unitsToProcess[i] = null;
- }
- break;
- }
- unit = this.unitsToProcess[i];
- try {
- super.process(unit, i); // this.process(...) is optimized to not process already known units
-
- // requested AST
- char[] fileName = unit.compilationResult.getFileName();
- IJavaScriptUnit source = (IJavaScriptUnit) this.requestedSources.get(fileName);
- if (source != null) {
- // convert AST
- CompilationResult compilationResult = unit.compilationResult;
- org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit sourceUnit = compilationResult.compilationUnit;
- char[] contents = sourceUnit.getContents();
- AST ast = AST.newAST(apiLevel);
- ast.setFlag(flags | AST.RESOLVED_BINDINGS);
- ast.setDefaultNodeFlag(ASTNode.ORIGINAL);
- ASTConverter converter = new ASTConverter(compilerOptions, true/*need to resolve bindings*/, this.monitor);
- BindingResolver resolver = new DefaultBindingResolver(unit.scope, owner, this.bindingTables, (flags & IJavaScriptUnit.ENABLE_BINDINGS_RECOVERY) != 0);
- ast.setBindingResolver(resolver);
- converter.setAST(ast);
- JavaScriptUnit compilationUnit = converter.convert(unit, contents);
- compilationUnit.setTypeRoot(source);
- compilationUnit.setLineEndTable(compilationResult.getLineSeparatorPositions());
- ast.setDefaultNodeFlag(0);
- ast.setOriginalModificationCount(ast.modificationCount());
-
- // pass it to requestor
- astRequestor.acceptAST(source, compilationUnit);
-
- worked(1);
- }
-
- // requested binding
- Object key = this.requestedKeys.get(fileName);
- if (key instanceof BindingKeyResolver) {
- reportBinding(key, astRequestor, owner, unit);
- worked(1);
- } else if (key instanceof ArrayList) {
- Iterator iterator = ((ArrayList) key).iterator();
- while (iterator.hasNext()) {
- reportBinding(iterator.next(), astRequestor, owner, unit);
- worked(1);
- }
- }
-
- // remove at the end so that we don't resolve twice if a source and a key for the same file name have been requested
- this.requestedSources.removeKey(fileName);
- this.requestedKeys.removeKey(fileName);
- } finally {
- // cleanup javaScript unit result
- unit.cleanUp();
- }
- this.unitsToProcess[i] = null; // release reference to processed unit declaration
- this.requestor.acceptResult(unit.compilationResult.tagAsAccepted());
- }
-
- // remaining binding keys
- DefaultBindingResolver resolver = new DefaultBindingResolver(this.lookupEnvironment, owner, this.bindingTables, (flags & IJavaScriptUnit.ENABLE_BINDINGS_RECOVERY) != 0);
- Object[] keys = this.requestedKeys.valueTable;
- for (int j = 0, keysLength = keys.length; j < keysLength; j++) {
- BindingKeyResolver keyResolver = (BindingKeyResolver) keys[j];
- if (keyResolver == null) continue;
- Binding compilerBinding = keyResolver.getCompilerBinding();
- IBinding binding = compilerBinding == null ? null : resolver.getBinding(compilerBinding);
- // pass it to requestor
- astRequestor.acceptBinding(((BindingKeyResolver) this.requestedKeys.valueTable[j]).getKey(), binding);
- worked(1);
- }
- } catch (OperationCanceledException e) {
- throw e;
- } catch (AbortCompilation e) {
- this.handleInternalException(e, unit);
- } catch (Error e) {
- this.handleInternalException(e, unit, null);
- throw e; // rethrow
- } catch (RuntimeException e) {
- this.handleInternalException(e, unit, null);
- throw e; // rethrow
- } finally {
- // disconnect ourselves from ast requestor
- astRequestor.compilationUnitResolver = null;
- }
- }
-
- private void reportBinding(Object key, ASTRequestor astRequestor, WorkingCopyOwner owner, CompilationUnitDeclaration unit) {
- BindingKeyResolver keyResolver = (BindingKeyResolver) key;
- Binding compilerBinding = keyResolver.getCompilerBinding();
- if (compilerBinding != null) {
- DefaultBindingResolver resolver = new DefaultBindingResolver(unit.scope, owner, this.bindingTables, false);
- IBinding binding = resolver.getBinding(compilerBinding);
- if (binding != null)
- astRequestor.acceptBinding(keyResolver.getKey(), binding);
- }
- }
-
- private CompilationUnitDeclaration resolve(
- CompilationUnitDeclaration unit,
- org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit sourceUnit,
- NodeSearcher nodeSearcher,
- boolean verifyMethods,
- boolean analyzeCode,
- boolean generateCode) {
-
- try {
-
- if (unit == null) {
- // build and record parsed units
- this.parseThreshold = 0; // will request a full parse
- beginToCompile(new org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit[] { sourceUnit });
- // process all units (some more could be injected in the loop by the lookup environment)
- unit = this.unitsToProcess[0];
- } else {
- // initial type binding creation
- this.lookupEnvironment.buildTypeBindings(unit, null /*no access restriction*/);
-
- // binding resolution
- this.lookupEnvironment.completeTypeBindings();
- }
-
- if (nodeSearcher == null) {
- this.parser.getMethodBodies(unit); // no-op if method bodies have already been parsed
- } else {
- int searchPosition = nodeSearcher.position;
- char[] source = sourceUnit.getContents();
- int length = source.length;
- if (searchPosition >= 0 && searchPosition <= length) {
- unit.traverse(nodeSearcher, unit.scope);
-
- org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode node = nodeSearcher.found;
-
- this.parser.scanner.setSource(source, unit.compilationResult);
-
- if (node != null) {
- org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration enclosingTypeDeclaration = nodeSearcher.enclosingType;
- if (node instanceof AbstractMethodDeclaration) {
- ((AbstractMethodDeclaration)node).parseStatements(this.parser, unit);
- } else if (enclosingTypeDeclaration != null) {
- if (node instanceof org.eclipse.wst.jsdt.internal.compiler.ast.Initializer) {
- ((org.eclipse.wst.jsdt.internal.compiler.ast.Initializer) node).parseStatements(this.parser, enclosingTypeDeclaration, unit);
- } else if (node instanceof org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration) {
- ((org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration)node).parseMethod(this.parser, unit);
- }
- }
- }
- }
- }
-
- 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();
-
- // flow analysis
- if (analyzeCode) unit.analyseCode();
-
- }
- if (this.unitsToProcess != null) this.unitsToProcess[0] = null; // release reference to processed unit declaration
- this.requestor.acceptResult(unit.compilationResult.tagAsAccepted());
- return unit;
- } catch (AbortCompilation e) {
- this.handleInternalException(e, unit);
- return unit == null ? this.unitsToProcess[0] : unit;
- } catch (Error e) {
- this.handleInternalException(e, unit, null);
- throw e; // rethrow
- } catch (RuntimeException e) {
- this.handleInternalException(e, unit, null);
- throw e; // rethrow
- } finally {
- // No reset is performed there anymore since,
- // within the CodeAssist (or related tools),
- // the validator may be called *after* a call
- // to this resolve(...) method. And such a call
- // needs to have a validator with a non-empty
- // environment.
- // this.reset();
- }
- }
- /*
- * Internal API used to resolve a given javaScript unit. Can run a subset of the compilation process
- */
- public CompilationUnitDeclaration resolve(
- org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit sourceUnit,
- boolean verifyMethods,
- boolean analyzeCode,
- boolean generateCode) {
-
- return resolve(
- null, /* no existing javaScript unit declaration*/
- sourceUnit,
- null/*no node searcher*/,
- verifyMethods,
- analyzeCode,
- generateCode);
- }
-
- /*
- * Internal API used to resolve a given javaScript unit. Can run a subset of the compilation process
- */
- public CompilationUnitDeclaration resolve(
- CompilationUnitDeclaration unit,
- org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit sourceUnit,
- boolean verifyMethods,
- boolean analyzeCode,
- boolean generateCode) {
-
- return resolve(
- unit,
- sourceUnit,
- null/*no node searcher*/,
- verifyMethods,
- analyzeCode,
- generateCode);
- }
-
- private void worked(int work) {
- if (this.monitor != null) {
- if (this.monitor.isCanceled())
- throw new OperationCanceledException();
- this.monitor.worked(work);
- }
- }
-}
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
deleted file mode 100644
index 3bf948af..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/LabeledStatement.java
+++ /dev/null
@@ -1,278 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Labeled statement AST node type.
- *
- * <pre>
- * LabeledStatement:
- * Identifier <b>:</b> Statement
- * </pre>
- *
- * 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 LabeledStatement extends Statement {
-
- /**
- * The "label" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor LABEL_PROPERTY =
- new ChildPropertyDescriptor(LabeledStatement.class, "label", SimpleName.class, MANDATORY, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "body" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor BODY_PROPERTY =
- new ChildPropertyDescriptor(LabeledStatement.class, "body", Statement.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List propertyList = new ArrayList(3);
- createPropertyList(LabeledStatement.class, propertyList);
- addProperty(LABEL_PROPERTY, propertyList);
- addProperty(BODY_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The label; lazily initialized; defaults to a unspecified,
- * legal JavaScript identifier.
- */
- private SimpleName labelName = null;
-
- /**
- * The body statement; lazily initialized; defaults to an unspecified, but
- * legal, statement.
- */
- private Statement body = null;
-
- /**
- * Creates a new AST node for a labeled statement owned by the given
- * AST. By default, the statement has an unspecified (but legal) label
- * and an unspecified (but legal) statement.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- LabeledStatement(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == LABEL_PROPERTY) {
- if (get) {
- return getLabel();
- } else {
- setLabel((SimpleName) child);
- return null;
- }
- }
- if (property == BODY_PROPERTY) {
- if (get) {
- return getBody();
- } else {
- setBody((Statement) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return LABELED_STATEMENT;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- LabeledStatement result = new LabeledStatement(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setLabel(
- (SimpleName) ASTNode.copySubtree(target, getLabel()));
- result.setBody(
- (Statement) ASTNode.copySubtree(target, getBody()));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChild(visitor, getLabel());
- acceptChild(visitor, getBody());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the label of this labeled statement.
- *
- * @return the variable name node
- */
- public SimpleName getLabel() {
- if (this.labelName == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.labelName == null) {
- preLazyInit();
- this.labelName= new SimpleName(this.ast);
- postLazyInit(this.labelName, LABEL_PROPERTY);
- }
- }
- }
- return this.labelName;
- }
-
- /**
- * Sets the label of this labeled statement.
- *
- * @param label the new label
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public void setLabel(SimpleName label) {
- if (label == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.labelName;
- preReplaceChild(oldChild, label, LABEL_PROPERTY);
- this.labelName = label;
- postReplaceChild(oldChild, label, LABEL_PROPERTY);
- }
-
- /**
- * Returns the body of this labeled statement.
- *
- * @return the body statement node
- */
- public Statement getBody() {
- if (this.body == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.body == null) {
- preLazyInit();
- this.body= new EmptyStatement(this.ast);
- postLazyInit(this.body, BODY_PROPERTY);
- }
- }
- }
- return this.body;
- }
-
- /**
- * Sets the body of this labeled statement.
- * <p>
- * Special note: The JavaScript language does not allow a local variable declaration
- * to appear as the body of a labeled statement (they may only appear within a
- * block). However, the AST will allow a <code>VariableDeclarationStatement</code>
- * as the body of a <code>LabeledStatement</code>. To get something that will
- * compile, be sure to embed the <code>VariableDeclarationStatement</code>
- * inside a <code>Block</code>.
- * </p>
- *
- * @param statement the body statement node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setBody(Statement statement) {
- if (statement == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.body;
- preReplaceChild(oldChild, statement, BODY_PROPERTY);
- this.body = statement;
- postReplaceChild(oldChild, statement, BODY_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return super.memSize() + 2 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.labelName == null ? 0 : getLabel().treeSize())
- + (this.body == null ? 0 : getBody().treeSize());
- }
-}
-
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
deleted file mode 100644
index 5dffea04..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/LineComment.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * End-of-line comment AST node type.
- * <p>
- * End-of-line comments begin with "//",
- * must end with a line delimiter (as per JLS 3.7),
- * and must not contain line breaks.
- * </p>
- * <p>
- * Note that this node type is a comment placeholder, and is
- * only useful for recording the source range where a comment
- * was found in a source string. It is not useful for creating
- * comments.
- * </p>
- *
- * 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 final class LineComment extends Comment {
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List propertyList = new ArrayList(1);
- createPropertyList(LineComment.class, propertyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * Creates a new line comment node owned by the given AST.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- LineComment(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return LINE_COMMENT;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- LineComment result = new LineComment(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- visitor.visit(this);
- visitor.endVisit(this);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return super.memSize();
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return memSize();
- }
-}
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
deleted file mode 100644
index 6f1d03de..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ListExpression.java
+++ /dev/null
@@ -1,157 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- *
- * 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 ListExpression extends Expression {
-
- /**
- * The "expressions" structural property of this node type.
- *
- */
- public static final ChildListPropertyDescriptor EXPRESSIONS_PROPERTY =
- new ChildListPropertyDescriptor(ListExpression.class, "expressions", Expression.class, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List properyList = new ArrayList(2);
- createPropertyList(ListExpression.class, properyList);
- addProperty(EXPRESSIONS_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The list of expressions (element type:
- * <code>Expression</code>). Defaults to an empty list.
- */
- private ASTNode.NodeList expressions =
- new ASTNode.NodeList(EXPRESSIONS_PROPERTY);
-
- /**
- * Creates a new AST node for an array initializer owned by the
- * given AST. By default, the list of expressions is empty.
- *
- * @param ast the AST that is to own this node
- */
- ListExpression(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalGetChildListProperty(ChildListPropertyDescriptor property) {
- if (property == EXPRESSIONS_PROPERTY) {
- return expressions();
- }
- // allow default implementation to flag the error
- return super.internalGetChildListProperty(property);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return LIST_EXPRESSION;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- ListExpression result = new ListExpression(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.expressions().addAll(ASTNode.copySubtrees(target, expressions()));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- acceptChildren(visitor, this.expressions);
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the live ordered list of expressions in this array initializer.
- *
- * @return the live list of expressions
- * (element type: <code>Expression</code>)
- */
- public List expressions() {
- return this.expressions;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return BASE_NODE_SIZE + 1 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return memSize() + this.expressions.listSize();
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/MemberRef.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/MemberRef.java
deleted file mode 100644
index c2a45c58..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/MemberRef.java
+++ /dev/null
@@ -1,275 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * AST node for a member reference within a doc comment
- * ({@link JSdoc}). The principal uses of these are in "@see" and "@link"
- * tag elements, for references to field members (and occasionally to method
- * and constructor members).
- * <pre>
- * MemberRef:
- * [ Name ] <b>#</b> Identifier
- * </pre>
- *
- * @see JSdoc
- *
- * 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 MemberRef extends ASTNode implements IDocElement {
-
- /**
- * The "qualifier" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor QUALIFIER_PROPERTY =
- new ChildPropertyDescriptor(MemberRef.class, "qualifier", Name.class, OPTIONAL, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "name" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor NAME_PROPERTY =
- new ChildPropertyDescriptor(MemberRef.class, "name", SimpleName.class, MANDATORY, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List propertyList = new ArrayList(3);
- createPropertyList(MemberRef.class, propertyList);
- addProperty(QUALIFIER_PROPERTY, propertyList);
- addProperty(NAME_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the AST.JLS* constants
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The optional qualifier; <code>null</code> for none; defaults to none.
- */
- private Name optionalQualifier = null;
-
- /**
- * The member name; lazily initialized; defaults to a unspecified,
- * legal JavaScript method name.
- */
- private SimpleName memberName = null;
-
- /**
- * Creates a new AST node for a member reference owned by the given
- * AST. By default, the method reference is for a member with an
- * unspecified, but legal, name; and no qualifier.
- * <p>
- * N.B. This constructor is package-private; all subclasses must be
- * declared in the same package; clients are unable to declare
- * additional subclasses.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- MemberRef(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == QUALIFIER_PROPERTY) {
- if (get) {
- return getQualifier();
- } else {
- setQualifier((Name) child);
- return null;
- }
- }
- if (property == NAME_PROPERTY) {
- if (get) {
- return getName();
- } else {
- setName((SimpleName) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return MEMBER_REF;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- MemberRef result = new MemberRef(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setQualifier((Name) ASTNode.copySubtree(target, getQualifier()));
- result.setName((SimpleName) ASTNode.copySubtree(target, getName()));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChild(visitor, getQualifier());
- acceptChild(visitor, getName());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the qualifier of this member reference, or
- * <code>null</code> if there is none.
- *
- * @return the qualifier name node, or <code>null</code> if there is none
- */
- public Name getQualifier() {
- return this.optionalQualifier;
- }
-
- /**
- * Sets or clears the qualifier of this member reference.
- *
- * @param name the qualifier name node, or <code>null</code> if
- * there is none
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public void setQualifier(Name name) {
- ASTNode oldChild = this.optionalQualifier;
- preReplaceChild(oldChild, name, QUALIFIER_PROPERTY);
- this.optionalQualifier = name;
- postReplaceChild(oldChild, name, QUALIFIER_PROPERTY);
- }
-
- /**
- * Returns the name of the referenced member.
- *
- * @return the member name node
- */
- public SimpleName getName() {
- if (this.memberName == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.memberName == null) {
- preLazyInit();
- this.memberName = new SimpleName(this.ast);
- postLazyInit(this.memberName, NAME_PROPERTY);
- }
- }
- }
- return this.memberName;
- }
-
- /**
- * Sets the name of the referenced member to the given name.
- *
- * @param name the new member name node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the name is <code>null</code></li>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public void setName(SimpleName name) {
- if (name == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.memberName;
- preReplaceChild(oldChild, name, NAME_PROPERTY);
- this.memberName = name;
- postReplaceChild(oldChild, name, NAME_PROPERTY);
- }
-
- /**
- * Resolves and returns the binding for the entity referred to by
- * this member reference.
- * <p>
- * Note that bindings are generally unavailable unless requested when the
- * AST is being built.
- * </p>
- *
- * @return the binding, or <code>null</code> if the binding cannot be
- * resolved
- */
- public final IBinding resolveBinding() {
- return this.ast.getBindingResolver().resolveReference(this);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return BASE_NODE_SIZE + 2 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.optionalQualifier == null ? 0 : getQualifier().treeSize())
- + (this.memberName == null ? 0 : getName().treeSize());
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Message.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Message.java
deleted file mode 100644
index 2770b3d1..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Message.java
+++ /dev/null
@@ -1,137 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.dom;
-
-/**
- * Error message used to report potential errors found during the AST parsing
- * or name resolution. Instances of this class are immutable.
- *
- * 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 Message {
-
- /**
- * The message.
- */
- private String message;
-
- /**
- * The character index into the original source string, or -1 if none.
- */
- private int startPosition;
-
- /**
- * The length in characters of the original source file indicating
- * where the source fragment corresponding to this message ends.
- */
- private int length;
-
- /**
- * Creates a message.
- *
- * @param message the localized message reported by the compiler
- * @param startPosition the 0-based character index into the
- * original source file, or <code>-1</code> if no source position
- * information is to be recorded for this message
- * @throws IllegalArgumentException if the message is null
- * @throws IllegalArgumentException if the startPosition is lower than -1.
- */
- public Message(String message, int startPosition) {
- if (message == null) {
- throw new IllegalArgumentException();
- }
- if (startPosition < -1) {
- throw new IllegalArgumentException();
- }
- this.message = message;
- this.startPosition = startPosition;
- this.length = 0;
- }
-
- /**
- * Creates a message.
- *
- * @param message the localized message reported by the compiler
- * @param startPosition the 0-based character index into the
- * original source file, or <code>-1</code> if no source position
- * information is to be recorded for this message
- * @param length the length in character of the original source file indicating
- * where the source fragment corresponding to this message ends. 0 or a negative number
- * if none. A negative number will be converted to a 0-length.
- * @throws IllegalArgumentException if the message is null
- * @throws IllegalArgumentException if the startPosition is lower than -1.
- */
- public Message(String message, int startPosition, int length) {
- if (message == null) {
- throw new IllegalArgumentException();
- }
- if (startPosition < -1) {
- throw new IllegalArgumentException();
- }
- this.message = message;
- this.startPosition = startPosition;
- if (length <= 0) {
- this.length = 0;
- } else {
- this.length = length;
- }
- }
-
- /**
- * Returns the localized message.
- *
- * @return the localized message
- */
- public String getMessage() {
- return message;
- }
-
- /**
- * Returns the character index into the original source file.
- *
- * @return the 0-based character index, or <code>-1</code>
- * if no source position information is recorded for this
- * message
- * @deprecated Use {@link #getStartPosition()} instead.
- * @see #getLength()
- */
- public int getSourcePosition() {
- return getStartPosition();
- }
-
- /**
- * Returns the character index into the original source file.
- *
- * @return the 0-based character index, or <code>-1</code>
- * if no source position information is recorded for this
- * message
- * @see #getLength()
- */
- public int getStartPosition() {
- return startPosition;
- }
-
- /**
- * Returns the length in characters of the original source file indicating
- * where the source fragment corresponding to this message ends.
- *
- * @return a length, or <code>0</code>
- * if no source length information is recorded for this message
- * @see #getStartPosition()
- */
- public int getLength() {
- return length;
- }
-}
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
deleted file mode 100644
index b2d7cb68..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Modifier.java
+++ /dev/null
@@ -1,706 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Modifier node.
- * <pre>
- * Modifier:
- * <b>public</b>
- * <b>protected</b>
- * <b>private</b>
- * <b>static</b>
- * <b>abstract</b>
- * <b>final</b>
- * <b>native</b>
- * <b>synchronized</b>
- * <b>transient</b>
- * <b>volatile</b>
- * <b>strictfp</b>
- * </pre>
- * <p>
- * Note that JavaScript model class {@link org.eclipse.wst.jsdt.core.Flags} also
- * provides the same constants as this class.
- * </p>
- *
- * 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 final class Modifier extends ASTNode implements IExtendedModifier {
-
- /**
- * Modifier keywords (typesafe enumeration).
- *
- */
- public static class ModifierKeyword {
-
- /** "abstract" modifier with flag value {@link Modifier#ABSTRACT}. */
- public static final ModifierKeyword ABSTRACT_KEYWORD = new ModifierKeyword("abstract", ABSTRACT);//$NON-NLS-1$
-
- /** "final" modifier with flag value {@link Modifier#FINAL}. */
- public static final ModifierKeyword FINAL_KEYWORD = new ModifierKeyword("final", FINAL);//$NON-NLS-1$
-
- /**
- * Map from token to operator (key type: <code>String</code>;
- * value type: <code>Operator</code>).
- */
- private static final Map KEYWORDS;
-
- /** "native" modifier with flag value {@link Modifier#NATIVE}. */
- public static final ModifierKeyword NATIVE_KEYWORD = new ModifierKeyword("native", NATIVE);//$NON-NLS-1$
-
- /** "private" modifier with flag value {@link Modifier#PRIVATE}. */
- public static final ModifierKeyword PRIVATE_KEYWORD = new ModifierKeyword("private", PRIVATE);//$NON-NLS-1$
-
- /** "protected" modifier with flag value {@link Modifier#PROTECTED}. */
- public static final ModifierKeyword PROTECTED_KEYWORD = new ModifierKeyword("protected", PROTECTED);//$NON-NLS-1$
-
- /** "public" modifier with flag value {@link Modifier#PUBLIC}. */
- public static final ModifierKeyword PUBLIC_KEYWORD = new ModifierKeyword("public", PUBLIC);//$NON-NLS-1$
-
- /** "static" modifier with flag value {@link Modifier#STATIC}. */
- public static final ModifierKeyword STATIC_KEYWORD = new ModifierKeyword("static", STATIC);//$NON-NLS-1$
-
- /** "strictfp" modifier with flag value {@link Modifier#STRICTFP}. */
- public static final ModifierKeyword STRICTFP_KEYWORD = new ModifierKeyword("strictfp", STRICTFP);//$NON-NLS-1$
-
- /** "synchronized" modifier with flag value {@link Modifier#SYNCHRONIZED}. */
- public static final ModifierKeyword SYNCHRONIZED_KEYWORD = new ModifierKeyword("synchronized", SYNCHRONIZED);//$NON-NLS-1$
-
- /** "transient" modifier with flag value {@link Modifier#TRANSIENT}. */
- public static final ModifierKeyword TRANSIENT_KEYWORD = new ModifierKeyword("transient", TRANSIENT);//$NON-NLS-1$
-
- /** "volatile" modifier with flag value {@link Modifier#VOLATILE}. */
- public static final ModifierKeyword VOLATILE_KEYWORD = new ModifierKeyword("volatile", VOLATILE);//$NON-NLS-1$
- static {
- KEYWORDS = new HashMap(20);
- ModifierKeyword[] ops = {
- PUBLIC_KEYWORD,
- PROTECTED_KEYWORD,
- PRIVATE_KEYWORD,
- STATIC_KEYWORD,
- ABSTRACT_KEYWORD,
- FINAL_KEYWORD,
- NATIVE_KEYWORD,
- SYNCHRONIZED_KEYWORD,
- TRANSIENT_KEYWORD,
- VOLATILE_KEYWORD,
- STRICTFP_KEYWORD
- };
- for (int i = 0; i < ops.length; i++) {
- KEYWORDS.put(ops[i].toString(), ops[i]);
- }
- }
-
- /**
- * Returns the modifier corresponding to the given single-bit flag value,
- * or <code>null</code> if none or if more than one bit is set.
- * <p>
- * <code>fromFlagValue</code> is the converse of <code>toFlagValue</code>:
- * that is, <code>ModifierKind.fromFlagValue(k.toFlagValue()) == k</code> for
- * all modifier keywords <code>k</code>.
- * </p>
- *
- * @param flagValue the single-bit flag value for the modifier
- * @return the modifier keyword, or <code>null</code> if none
- * @see #toFlagValue()
- */
- public static ModifierKeyword fromFlagValue(int flagValue) {
- for (Iterator it = KEYWORDS.values().iterator(); it.hasNext(); ) {
- ModifierKeyword k = (ModifierKeyword) it.next();
- if (k.toFlagValue() == flagValue) {
- return k;
- }
- }
- return null;
- }
-
- /**
- * Returns the modifier corresponding to the given string,
- * or <code>null</code> if none.
- * <p>
- * <code>toKeyword</code> is the converse of <code>toString</code>:
- * that is, <code>ModifierKind.toKeyword(k.toString()) == k</code> for
- * all modifier keywords <code>k</code>.
- * </p>
- *
- * @param keyword the lowercase string name for the modifier
- * @return the modifier keyword, or <code>null</code> if none
- * @see #toString()
- */
- public static ModifierKeyword toKeyword(String keyword) {
- return (ModifierKeyword) KEYWORDS.get(keyword);
- }
-
- /**
- * The flag value for the modifier.
- */
- private int flagValue;
-
- /**
- * The keyword modifier string.
- */
- private String keyword;
-
- /**
- * Creates a new modifier with the given keyword.
- * <p>
- * Note: this constructor is private. The only instances
- * ever created are the ones for the standard modifiers.
- * </p>
- *
- * @param keyword the character sequence for the modifier
- * @param flagValue flag value
- */
- private ModifierKeyword(String keyword, int flagValue) {
- this.keyword = keyword;
- this.flagValue = flagValue;
- }
-
- /**
- * Returns the modifier flag value corresponding to this modifier keyword.
- *
- * @return one of the <code>Modifier</code> constants
- * @see #fromFlagValue(int)
- */
- public int toFlagValue() {
- return this.flagValue;
- }
-
- /**
- * Returns the keyword for the modifier.
- *
- * @return the keyword for the modifier
- * @see #toKeyword(String)
- */
- public String toString() {
- return this.keyword;
- }
- }
-
- /**
- * "abstract" modifier constant (bit mask).
- * Applicable to types and methods.
- *
- */
- public static final int ABSTRACT = 0x0400;
-
- /**
- * "final" modifier constant (bit mask).
- * Applicable to types, methods, fields, and variables.
- *
- */
- public static final int FINAL = 0x0010;
-
- /**
- * The "keyword" structural property of this node type.
- *
- */
- public static final SimplePropertyDescriptor KEYWORD_PROPERTY =
- new SimplePropertyDescriptor(Modifier.class, "keyword", Modifier.ModifierKeyword.class, MANDATORY); //$NON-NLS-1$
-
- /**
- * "native" modifier constant (bit mask).
- * Applicable only to methods.
- *
- */
- public static final int NATIVE = 0x0100;
-
- /**
- * Modifier constant (bit mask, value 0) indicating no modifiers.
- *
- */
- public static final int NONE = 0x0000;
-
- /**
- * "private" modifier constant (bit mask).
- * Applicable to types, methods, constructors, and fields.
- *
- */
- public static final int PRIVATE = 0x0002;
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- /**
- * "protected" modifier constant (bit mask).
- * Applicable to types, methods, constructors, and fields.
- *
- */
- public static final int PROTECTED = 0x0004;
-
- /**
- * "public" modifier constant (bit mask).
- * Applicable to types, methods, constructors, and fields.
- *
- */
- public static final int PUBLIC = 0x0001;
-
- /**
- * "static" modifier constant (bit mask).
- * Applicable to types, methods, fields, and initializers.
- *
- */
- public static final int STATIC = 0x0008;
-
- /**
- * "strictfp" modifier constant (bit mask).
- * Applicable to types and methods.
- *
- */
- public static final int STRICTFP = 0x0800;
-
- /**
- * "synchronized" modifier constant (bit mask).
- * Applicable only to methods.
- *
- */
- public static final int SYNCHRONIZED = 0x0020;
-
- /**
- * "transient" modifier constant (bit mask).
- * Applicable only to fields.
- *
- */
- public static final int TRANSIENT = 0x0080;
-
- /**
- * "volatile" modifier constant (bit mask).
- * Applicable only to fields.
- *
- */
- public static final int VOLATILE = 0x0040;
-
- static {
- List properyList = new ArrayList(2);
- createPropertyList(Modifier.class, properyList);
- addProperty(KEYWORD_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
- }
-
- /**
- * Returns whether the given flags includes the "abstract" modifier.
- * Applicable to types and methods.
- *
- * @param flags the modifier flags
- * @return <code>true</code> if the <code>ABSTRACT</code> bit is
- * set, and <code>false</code> otherwise
- *
- */
- public static boolean isAbstract(int flags) {
- return (flags & ABSTRACT) != 0;
- }
-
- /**
- * Returns whether the given flags includes the "final" modifier.
- * Applicable to types, methods, fields, and variables.
- *
- * @param flags the modifier flags
- * @return <code>true</code> if the <code>FINAL</code> bit is
- * set, and <code>false</code> otherwise
- *
- */
- public static boolean isFinal(int flags) {
- return (flags & FINAL) != 0;
- }
-
- /**
- * Returns whether the given flags includes the "native" modifier.
- * Applicable only to methods.
- *
- * @param flags the modifier flags
- * @return <code>true</code> if the <code>NATIVE</code> bit is
- * set, and <code>false</code> otherwise
- *
- */
- public static boolean isNative(int flags) {
- return (flags & NATIVE) != 0;
- }
-
- /**
- * Returns whether the given flags includes the "private" modifier.
- * Applicable to types, methods, constructors, and fields.
- *
- * @param flags the modifier flags
- * @return <code>true</code> if the <code>PRIVATE</code> bit is
- * set, and <code>false</code> otherwise
- *
- */
- public static boolean isPrivate(int flags) {
- return (flags & PRIVATE) != 0;
- }
-
- /**
- * Returns whether the given flags includes the "protected" modifier.
- * Applicable to types, methods, constructors, and fields.
- *
- * @param flags the modifier flags
- * @return <code>true</code> if the <code>PROTECTED</code> bit is
- * set, and <code>false</code> otherwise
- *
- */
- public static boolean isProtected(int flags) {
- return (flags & PROTECTED) != 0;
- }
-
- /**
- * Returns whether the given flags includes the "public" modifier.
- * Applicable to types, methods, constructors, and fields.
- *
- * @param flags the modifier flags
- * @return <code>true</code> if the <code>PUBLIC</code> bit is
- * set, and <code>false</code> otherwise
- *
- */
- public static boolean isPublic(int flags) {
- return (flags & PUBLIC) != 0;
- }
-
- /**
- * Returns whether the given flags includes the "static" modifier.
- * Applicable to types, methods, fields, and initializers.
- *
- * @param flags the modifier flags
- * @return <code>true</code> if the <code>STATIC</code> bit is
- * set, and <code>false</code> otherwise
- *
- */
- public static boolean isStatic(int flags) {
- return (flags & STATIC) != 0;
- }
-
- /**
- * Returns whether the given flags includes the "strictfp" modifier.
- * Applicable to types and methods.
- *
- * @param flags the modifier flags
- * @return <code>true</code> if the <code>STRICTFP</code> bit is
- * set, and <code>false</code> otherwise
- *
- */
- public static boolean isStrictfp(int flags) {
- return (flags & STRICTFP) != 0;
- }
-
- /**
- * Returns whether the given flags includes the "synchronized" modifier.
- * Applicable only to methods.
- *
- * @param flags the modifier flags
- * @return <code>true</code> if the <code>SYNCHRONIZED</code> bit is
- * set, and <code>false</code> otherwise
- *
- */
- public static boolean isSynchronized(int flags) {
- return (flags & SYNCHRONIZED) != 0;
- }
-
- /**
- * Returns whether the given flags includes the "transient" modifier.
- * Applicable only to fields.
- *
- * @param flags the modifier flags
- * @return <code>true</code> if the <code>TRANSIENT</code> bit is
- * set, and <code>false</code> otherwise
- *
- */
- public static boolean isTransient(int flags) {
- return (flags & TRANSIENT) != 0;
- }
-
- /**
- * Returns whether the given flags includes the "volatile" modifier.
- * Applicable only to fields.
- *
- * @param flags the modifier flags
- * @return <code>true</code> if the <code>VOLATILE</code> bit is
- * set, and <code>false</code> otherwise
- *
- */
- public static boolean isVolatile(int flags) {
- return (flags & VOLATILE) != 0;
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The modifier keyword; defaults to an unspecified modifier.
- *
- */
- private ModifierKeyword modifierKeyword = ModifierKeyword.PUBLIC_KEYWORD;
-
- /**
- * Creates a new unparented modifier node owned by the given AST.
- * By default, the node has unspecified (but legal) modifier.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- *
- */
- Modifier(AST ast) {
- super(ast);
- unsupportedIn2();
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- *
- */
- void accept0(ASTVisitor visitor) {
- visitor.visit(this);
- visitor.endVisit(this);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- *
- */
- ASTNode clone0(AST target) {
- Modifier result = new Modifier(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setKeyword(getKeyword());
- return result;
- }
-
- /**
- * Returns the modifier keyword of this modifier node.
- *
- * @return the modifier keyword
- *
- */
- public ModifierKeyword getKeyword() {
- return this.modifierKeyword;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- *
- */
- final int getNodeType0() {
- return MODIFIER;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final Object internalGetSetObjectProperty(SimplePropertyDescriptor property, boolean get, Object value) {
- if (property == KEYWORD_PROPERTY) {
- if (get) {
- return getKeyword();
- } else {
- setKeyword((ModifierKeyword) value);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetObjectProperty(property, get, value);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /**
- * Answer true if the receiver is the abstract modifier, false otherwise.
- *
- * @return true if the receiver is the abstract modifier, false otherwise
- *
- */
- public boolean isAbstract() {
- return this.modifierKeyword == ModifierKeyword.ABSTRACT_KEYWORD;
- }
-
- /**
- * @see IExtendedModifier#isAnnotation()
- */
- public boolean isAnnotation() {
- return false;
- }
-
- /**
- * Answer true if the receiver is the final modifier, false otherwise.
- *
- * @return true if the receiver is the final modifier, false otherwise
- *
- */
- public boolean isFinal() {
- return this.modifierKeyword == ModifierKeyword.FINAL_KEYWORD;
- }
-
- /**
- * @see IExtendedModifier#isModifier()
- */
- public boolean isModifier() {
- return true;
- }
-
- /**
- * Answer true if the receiver is the native modifier, false otherwise.
- *
- * @return true if the receiver is the native modifier, false otherwise
- *
- */
- public boolean isNative() {
- return this.modifierKeyword == ModifierKeyword.NATIVE_KEYWORD;
- }
-
- /**
- * Answer true if the receiver is the private modifier, false otherwise.
- *
- * @return true if the receiver is the private modifier, false otherwise
- *
- */
- public boolean isPrivate() {
- return this.modifierKeyword == ModifierKeyword.PRIVATE_KEYWORD;
- }
-
- /**
- * Answer true if the receiver is the protected modifier, false otherwise.
- *
- * @return true if the receiver is the protected modifier, false otherwise
- *
- */
- public boolean isProtected() {
- return this.modifierKeyword == ModifierKeyword.PROTECTED_KEYWORD;
- }
-
- /**
- * Answer true if the receiver is the public modifier, false otherwise.
- *
- * @return true if the receiver is the public modifier, false otherwise
- *
- */
- public boolean isPublic() {
- return this.modifierKeyword == ModifierKeyword.PUBLIC_KEYWORD;
- }
-
- /**
- * Answer true if the receiver is the static modifier, false otherwise.
- *
- * @return true if the receiver is the static modifier, false otherwise
- *
- */
- public boolean isStatic() {
- return this.modifierKeyword == ModifierKeyword.STATIC_KEYWORD;
- }
-
- /**
- * Answer true if the receiver is the strictfp modifier, false otherwise.
- *
- * @return true if the receiver is the strictfp modifier, false otherwise
- *
- */
- public boolean isStrictfp() {
- return this.modifierKeyword == ModifierKeyword.STRICTFP_KEYWORD;
- }
-
- /**
- * Answer true if the receiver is the synchronized modifier, false otherwise.
- *
- * @return true if the receiver is the synchronized modifier, false otherwise
- *
- */
- public boolean isSynchronized() {
- return this.modifierKeyword == ModifierKeyword.SYNCHRONIZED_KEYWORD;
- }
-
- /**
- * Answer true if the receiver is the transient modifier, false otherwise.
- *
- * @return true if the receiver is the transient modifier, false otherwise
- *
- */
- public boolean isTransient() {
- return this.modifierKeyword == ModifierKeyword.TRANSIENT_KEYWORD;
- }
-
- /**
- * Answer true if the receiver is the volatile modifier, false otherwise.
- *
- * @return true if the receiver is the volatile modifier, false otherwise
- *
- */
- public boolean isVolatile() {
- return this.modifierKeyword == ModifierKeyword.VOLATILE_KEYWORD;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- *
- */
- int memSize() {
- // treat ModifierKeyword as free
- return BASE_NODE_SIZE + 1 * 4;
- }
-
- /**
- * Sets the modifier keyword of this modifier node.
- *
- * @param modifierKeyord the modifier keyword
- * @exception IllegalArgumentException if the argument is <code>null</code>
- *
- */
- public void setKeyword(ModifierKeyword modifierKeyord) {
- if (modifierKeyord == null) {
- throw new IllegalArgumentException();
- }
- preValueChange(KEYWORD_PROPERTY);
- this.modifierKeyword = modifierKeyord;
- postValueChange(KEYWORD_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- *
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- *
- */
- int treeSize() {
- return memSize();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/NaiveASTFlattener.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/NaiveASTFlattener.java
deleted file mode 100644
index b02512f3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/NaiveASTFlattener.java
+++ /dev/null
@@ -1,1392 +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
- * bug 227489 - Etienne Pfister <epfister@hsr.ch>
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.dom;
-
-import java.util.Iterator;
-import java.util.List;
-
-/**
- * Internal AST visitor for serializing an AST in a quick and dirty fashion.
- * For various reasons the resulting string is not necessarily legal
- * JavaScript code; and even if it is legal JavaScript code, it is not necessarily the string
- * that corresponds to the given AST. Although useless for most purposes, it's
- * fine for generating debug print strings.
- * <p>
- * Example usage:
- * <code>
- * <pre>
- * NaiveASTFlattener p = new NaiveASTFlattener();
- * node.accept(p);
- * String result = p.getResult();
- * </pre>
- * </code>
- * Call the <code>reset</code> method to clear the previous result before reusing an
- * existing instance.
- * </p>
- *
- * 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.
- */
-class NaiveASTFlattener extends ASTVisitor {
-
- /**
- * The string buffer into which the serialized representation of the AST is
- * written.
- */
- private StringBuffer buffer;
-
- private int indent = 0;
-
- /**
- * Creates a new AST printer.
- */
- NaiveASTFlattener() {
- this.buffer = new StringBuffer();
- }
-
- /**
- * Returns the string accumulated in the visit.
- *
- * @return the serialized
- */
- public String getResult() {
- return this.buffer.toString();
- }
-
- /**
- * Resets this printer so that it can be used again.
- */
- public void reset() {
- this.buffer.setLength(0);
- }
-
- void printIndent() {
- for (int i = 0; i < this.indent; i++)
- this.buffer.append(" "); //$NON-NLS-1$
- }
-
- /**
- * Appends the text representation of the given modifier flags, followed by a single space.
- * Used for 3.0 modifiers and annotations.
- *
- * @param ext the list of modifier and annotation nodes
- * (element type: <code>IExtendedModifiers</code>)
- */
- void printModifiers(List ext) {
-// for (Iterator it = ext.iterator(); it.hasNext(); ) {
-// ASTNode p = (ASTNode) it.next();
-// p.accept(this);
-// this.buffer.append(" ");//$NON-NLS-1$
-// }
- }
-
- /**
- * Appends the text representation of the given modifier flags, followed by a single space.
- * Used for JLS2 modifiers.
- *
- * @param modifiers the modifier flags
- */
- void printModifiers(int modifiers) {
-// if (Modifier.isPublic(modifiers)) {
-// this.buffer.append("public ");//$NON-NLS-1$
-// }
-// if (Modifier.isProtected(modifiers)) {
-// this.buffer.append("protected ");//$NON-NLS-1$
-// }
-// if (Modifier.isPrivate(modifiers)) {
-// this.buffer.append("private ");//$NON-NLS-1$
-// }
-// if (Modifier.isStatic(modifiers)) {
-// this.buffer.append("static ");//$NON-NLS-1$
-// }
-// if (Modifier.isAbstract(modifiers)) {
-// this.buffer.append("abstract ");//$NON-NLS-1$
-// }
-// if (Modifier.isFinal(modifiers)) {
-// this.buffer.append("final ");//$NON-NLS-1$
-// }
-// if (Modifier.isSynchronized(modifiers)) {
-// this.buffer.append("synchronized ");//$NON-NLS-1$
-// }
-// if (Modifier.isVolatile(modifiers)) {
-// this.buffer.append("volatile ");//$NON-NLS-1$
-// }
-// if (Modifier.isNative(modifiers)) {
-// this.buffer.append("native ");//$NON-NLS-1$
-// }
-// if (Modifier.isStrictfp(modifiers)) {
-// this.buffer.append("strictfp ");//$NON-NLS-1$
-// }
-// if (Modifier.isTransient(modifiers)) {
-// this.buffer.append("transient ");//$NON-NLS-1$
-// }
- }
-
- /*
- * @see ASTVisitor#visit(AnonymousClassDeclaration)
- */
- public boolean visit(AnonymousClassDeclaration node) {
- this.buffer.append("{\n");//$NON-NLS-1$
- this.indent++;
- for (Iterator it = node.bodyDeclarations().iterator(); it.hasNext(); ) {
- BodyDeclaration b = (BodyDeclaration) it.next();
- b.accept(this);
- }
- this.indent--;
- printIndent();
- this.buffer.append("}\n");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ArrayAccess)
- */
- public boolean visit(ArrayAccess node) {
- node.getArray().accept(this);
- this.buffer.append("[");//$NON-NLS-1$
- node.getIndex().accept(this);
- this.buffer.append("]");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ArrayCreation)
- */
- public boolean visit(ArrayCreation node) {
- this.buffer.append("new ");//$NON-NLS-1$
- ArrayType at = node.getType();
- int dims = at.getDimensions();
- Type elementType = at.getElementType();
- elementType.accept(this);
- for (Iterator it = node.dimensions().iterator(); it.hasNext(); ) {
- this.buffer.append("[");//$NON-NLS-1$
- Expression e = (Expression) it.next();
- e.accept(this);
- this.buffer.append("]");//$NON-NLS-1$
- dims--;
- }
- // add empty "[]" for each extra array dimension
- for (int i= 0; i < dims; i++) {
- this.buffer.append("[]");//$NON-NLS-1$
- }
- if (node.getInitializer() != null) {
- node.getInitializer().accept(this);
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ArrayInitializer)
- */
- public boolean visit(ArrayInitializer node) {
- this.buffer.append("[");//$NON-NLS-1$
- for (Iterator it = node.expressions().iterator(); it.hasNext(); ) {
- Expression e = (Expression) it.next();
- e.accept(this);
- if (it.hasNext()) {
- this.buffer.append(",");//$NON-NLS-1$
- }
- }
- this.buffer.append("]");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ArrayType)
- */
- public boolean visit(ArrayType node) {
- node.getComponentType().accept(this);
- this.buffer.append("[]");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(Assignment)
- */
- public boolean visit(Assignment node) {
- node.getLeftHandSide().accept(this);
- this.buffer.append(node.getOperator().toString());
- node.getRightHandSide().accept(this);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(Block)
- */
- public boolean visit(Block node) {
- this.buffer.append("{\n");//$NON-NLS-1$
- this.indent++;
- for (Iterator it = node.statements().iterator(); it.hasNext(); ) {
- // fix for inner function handling, Etienne Pfister
- ASTNode s = (ASTNode) it.next();
- s.accept(this);
- }
- this.indent--;
- printIndent();
- this.buffer.append("}\n");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(BlockComment)
- *
- */
- public boolean visit(BlockComment node) {
- printIndent();
- this.buffer.append("/* */");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(BooleanLiteral)
- */
- public boolean visit(BooleanLiteral node) {
- if (node.booleanValue() == true) {
- this.buffer.append("true");//$NON-NLS-1$
- } else {
- this.buffer.append("false");//$NON-NLS-1$
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(BreakStatement)
- */
- public boolean visit(BreakStatement node) {
- printIndent();
- this.buffer.append("break");//$NON-NLS-1$
- if (node.getLabel() != null) {
- this.buffer.append(" ");//$NON-NLS-1$
- node.getLabel().accept(this);
- }
- this.buffer.append(";\n");//$NON-NLS-1$
- return false;
- }
-
- public boolean visit(FunctionExpression node) {
- node.getMethod().accept(this);
- return false;
- }
-
-
- /*
- * @see ASTVisitor#visit(CatchClause)
- */
- public boolean visit(CatchClause node) {
- this.buffer.append("catch (");//$NON-NLS-1$
- node.getException().accept(this);
- this.buffer.append(") ");//$NON-NLS-1$
- node.getBody().accept(this);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(CharacterLiteral)
- */
- public boolean visit(CharacterLiteral node) {
- this.buffer.append(node.getEscapedValue());
- return false;
- }
-
- public boolean visit(RegularExpressionLiteral node) {
- this.buffer.append(node.getRegularExpression());
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ClassInstanceCreation)
- */
- public boolean visit(ClassInstanceCreation node) {
- if (node.getExpression() != null) {
- node.getExpression().accept(this);
- this.buffer.append(".");//$NON-NLS-1$
- }
- this.buffer.append("new ");//$NON-NLS-1$
-// if (node.getAST().apiLevel() == AST.JLS2_INTERNAL) {
-// node.internalGetName().accept(this);
-// }
-// if (node.getAST().apiLevel() >= AST.JLS3) {
-// if (!node.typeArguments().isEmpty()) {
-// this.buffer.append("<");//$NON-NLS-1$
-// for (Iterator it = node.typeArguments().iterator(); it.hasNext(); ) {
-// Type t = (Type) it.next();
-// t.accept(this);
-// if (it.hasNext()) {
-// this.buffer.append(",");//$NON-NLS-1$
-// }
-// }
-// this.buffer.append(">");//$NON-NLS-1$
-// }
-// node.getType().accept(this);
-// }
- node.getMember().accept(this);
- this.buffer.append("(");//$NON-NLS-1$
- for (Iterator it = node.arguments().iterator(); it.hasNext(); ) {
- Expression e = (Expression) it.next();
- e.accept(this);
- if (it.hasNext()) {
- this.buffer.append(",");//$NON-NLS-1$
- }
- }
- this.buffer.append(")");//$NON-NLS-1$
- if (node.getAnonymousClassDeclaration() != null) {
- node.getAnonymousClassDeclaration().accept(this);
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(JavaScriptUnit)
- */
- public boolean visit(JavaScriptUnit node) {
- if (node.getPackage() != null) {
- node.getPackage().accept(this);
- }
- for (Iterator it = node.imports().iterator(); it.hasNext(); ) {
- ImportDeclaration d = (ImportDeclaration) it.next();
- d.accept(this);
- }
- for (Iterator it = node.types().iterator(); it.hasNext(); ) {
- AbstractTypeDeclaration d = (AbstractTypeDeclaration) it.next();
- d.accept(this);
- }
- for (Iterator it = node.statements().iterator(); it.hasNext(); ) {
- ProgramElement d = (ProgramElement) it.next();
- d.accept(this);
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ConditionalExpression)
- */
- public boolean visit(ConditionalExpression node) {
- node.getExpression().accept(this);
- this.buffer.append(" ? ");//$NON-NLS-1$
- node.getThenExpression().accept(this);
- this.buffer.append(" : ");//$NON-NLS-1$
- node.getElseExpression().accept(this);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ConstructorInvocation)
- */
- public boolean visit(ConstructorInvocation node) {
- printIndent();
- if (node.getAST().apiLevel() >= AST.JLS3) {
- if (!node.typeArguments().isEmpty()) {
- this.buffer.append("<");//$NON-NLS-1$
- for (Iterator it = node.typeArguments().iterator(); it.hasNext(); ) {
- Type t = (Type) it.next();
- t.accept(this);
- if (it.hasNext()) {
- this.buffer.append(",");//$NON-NLS-1$
- }
- }
- this.buffer.append(">");//$NON-NLS-1$
- }
- }
- this.buffer.append("this(");//$NON-NLS-1$
- for (Iterator it = node.arguments().iterator(); it.hasNext(); ) {
- Expression e = (Expression) it.next();
- e.accept(this);
- if (it.hasNext()) {
- this.buffer.append(",");//$NON-NLS-1$
- }
- }
- this.buffer.append(");\n");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ContinueStatement)
- */
- public boolean visit(ContinueStatement node) {
- printIndent();
- this.buffer.append("continue");//$NON-NLS-1$
- if (node.getLabel() != null) {
- this.buffer.append(" ");//$NON-NLS-1$
- node.getLabel().accept(this);
- }
- this.buffer.append(";\n");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(DoStatement)
- */
- public boolean visit(DoStatement node) {
- printIndent();
- this.buffer.append("do ");//$NON-NLS-1$
- node.getBody().accept(this);
- this.buffer.append(" while (");//$NON-NLS-1$
- node.getExpression().accept(this);
- this.buffer.append(");\n");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(EmptyStatement)
- */
- public boolean visit(EmptyStatement node) {
- printIndent();
- this.buffer.append(";\n");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(EnhancedForStatement)
- *
- */
- public boolean visit(EnhancedForStatement node) {
- printIndent();
- this.buffer.append("for (");//$NON-NLS-1$
- node.getParameter().accept(this);
- this.buffer.append(" : ");//$NON-NLS-1$
- node.getExpression().accept(this);
- this.buffer.append(") ");//$NON-NLS-1$
- node.getBody().accept(this);
- return false;
- }
-
-
-
- /*
- * @see ASTVisitor#visit(ExpressionStatement)
- */
- public boolean visit(ExpressionStatement node) {
- printIndent();
- node.getExpression().accept(this);
- if (node.getParent().getNodeType()!=ASTNode.FOR_IN_STATEMENT)
- this.buffer.append(";\n");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(FieldAccess)
- */
- public boolean visit(FieldAccess node) {
- node.getExpression().accept(this);
- this.buffer.append(".");//$NON-NLS-1$
- node.getName().accept(this);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(FieldDeclaration)
- */
- public boolean visit(FieldDeclaration node) {
- if (node.getJavadoc() != null) {
- node.getJavadoc().accept(this);
- }
- printIndent();
- if (node.getAST().apiLevel() == AST.JLS2_INTERNAL) {
- printModifiers(node.getModifiers());
- }
- if (node.getAST().apiLevel() >= AST.JLS3) {
- printModifiers(node.modifiers());
- }
- node.getType().accept(this);
- this.buffer.append(" ");//$NON-NLS-1$
- for (Iterator it = node.fragments().iterator(); it.hasNext(); ) {
- VariableDeclarationFragment f = (VariableDeclarationFragment) it.next();
- f.accept(this);
- if (it.hasNext()) {
- this.buffer.append(", ");//$NON-NLS-1$
- }
- }
- this.buffer.append(";\n");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ForStatement)
- */
- public boolean visit(ForStatement node) {
- printIndent();
- this.buffer.append("for (");//$NON-NLS-1$
- for (Iterator it = node.initializers().iterator(); it.hasNext(); ) {
- Expression e = (Expression) it.next();
- e.accept(this);
- if (it.hasNext()) buffer.append(", ");//$NON-NLS-1$
- }
- this.buffer.append("; ");//$NON-NLS-1$
- if (node.getExpression() != null) {
- node.getExpression().accept(this);
- }
- this.buffer.append("; ");//$NON-NLS-1$
- for (Iterator it = node.updaters().iterator(); it.hasNext(); ) {
- Expression e = (Expression) it.next();
- e.accept(this);
- if (it.hasNext()) buffer.append(", ");//$NON-NLS-1$
- }
- this.buffer.append(") ");//$NON-NLS-1$
- node.getBody().accept(this);
- return false;
- }
-
- public boolean visit(ForInStatement node) {
- printIndent();
- this.buffer.append("for (");//$NON-NLS-1$
- if (node.getIterationVariable() != null) {
- node.getIterationVariable().accept(this);
- }
- this.buffer.append(" in ");//$NON-NLS-1$
- if (node.getCollection() != null) {
- node.getCollection().accept(this);
- }
- this.buffer.append(") ");//$NON-NLS-1$
- node.getBody().accept(this);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(IfStatement)
- */
- public boolean visit(IfStatement node) {
- printIndent();
- this.buffer.append("if (");//$NON-NLS-1$
- node.getExpression().accept(this);
- this.buffer.append(") ");//$NON-NLS-1$
- node.getThenStatement().accept(this);
- if (node.getElseStatement() != null) {
- this.buffer.append(" else ");//$NON-NLS-1$
- node.getElseStatement().accept(this);
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ImportDeclaration)
- */
- public boolean visit(ImportDeclaration node) {
- printIndent();
- this.buffer.append("import ");//$NON-NLS-1$
- if (node.getAST().apiLevel() >= AST.JLS3) {
- if (node.isStatic()) {
- this.buffer.append("static ");//$NON-NLS-1$
- }
- }
- node.getName().accept(this);
- if (node.isOnDemand()) {
- this.buffer.append(".*");//$NON-NLS-1$
- }
- this.buffer.append(";\n");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(InfixExpression)
- */
- public boolean visit(InfixExpression node) {
- node.getLeftOperand().accept(this);
- this.buffer.append(' '); // for cases like x= i - -1; or x= i++ + ++i;
- this.buffer.append(node.getOperator().toString());
- this.buffer.append(' ');
- node.getRightOperand().accept(this);
- final List extendedOperands = node.extendedOperands();
- if (extendedOperands.size() != 0) {
- this.buffer.append(' ');
- for (Iterator it = extendedOperands.iterator(); it.hasNext(); ) {
- this.buffer.append(node.getOperator().toString()).append(' ');
- Expression e = (Expression) it.next();
- e.accept(this);
- }
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(InstanceofExpression)
- */
- public boolean visit(InstanceofExpression node) {
- node.getLeftOperand().accept(this);
- this.buffer.append(" instanceof ");//$NON-NLS-1$
- node.getRightOperand().accept(this);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(Initializer)
- */
- public boolean visit(Initializer node) {
- if (node.getJavadoc() != null) {
- node.getJavadoc().accept(this);
- }
- if (node.getAST().apiLevel() == AST.JLS2_INTERNAL) {
- printModifiers(node.getModifiers());
- }
- if (node.getAST().apiLevel() >= AST.JLS3) {
- printModifiers(node.modifiers());
- }
- node.getBody().accept(this);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(Javadoc)
- */
- public boolean visit(JSdoc node) {
- printIndent();
- this.buffer.append("/** ");//$NON-NLS-1$
- for (Iterator it = node.tags().iterator(); it.hasNext(); ) {
- ASTNode e = (ASTNode) it.next();
- e.accept(this);
- }
- this.buffer.append("\n */\n");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(LabeledStatement)
- */
- public boolean visit(LabeledStatement node) {
- printIndent();
- node.getLabel().accept(this);
- this.buffer.append(": ");//$NON-NLS-1$
- node.getBody().accept(this);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(LineComment)
- *
- */
- public boolean visit(LineComment node) {
- this.buffer.append("//\n");//$NON-NLS-1$
- return false;
- }
-
- public boolean visit(ListExpression node) {
- for (Iterator it = node.expressions().iterator(); it.hasNext(); ) {
- Expression e = (Expression) it.next();
- e.accept(this);
- if (it.hasNext()) {
- this.buffer.append(",");//$NON-NLS-1$
- }
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(MemberRef)
- *
- */
- public boolean visit(MemberRef node) {
- if (node.getQualifier() != null) {
- node.getQualifier().accept(this);
- }
- this.buffer.append("#");//$NON-NLS-1$
- node.getName().accept(this);
- return false;
- }
-
-
- /*
- * @see ASTVisitor#visit(FunctionRef)
- *
- */
- public boolean visit(FunctionRef node) {
- if (node.getQualifier() != null) {
- node.getQualifier().accept(this);
- }
- this.buffer.append("#");//$NON-NLS-1$
- node.getName().accept(this);
- this.buffer.append("(");//$NON-NLS-1$
- for (Iterator it = node.parameters().iterator(); it.hasNext(); ) {
- FunctionRefParameter e = (FunctionRefParameter) it.next();
- e.accept(this);
- if (it.hasNext()) {
- this.buffer.append(",");//$NON-NLS-1$
- }
- }
- this.buffer.append(")");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(FunctionRefParameter)
- *
- */
- public boolean visit(FunctionRefParameter node) {
- node.getType().accept(this);
- if (node.getAST().apiLevel() >= AST.JLS3) {
- if (node.isVarargs()) {
- this.buffer.append("...");//$NON-NLS-1$
- }
- }
- if (node.getName() != null) {
- this.buffer.append(" ");//$NON-NLS-1$
- node.getName().accept(this);
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(FunctionDeclaration)
- */
- public boolean visit(FunctionDeclaration node) {
- if (node.getJavadoc() != null) {
- node.getJavadoc().accept(this);
- }
- printIndent();
- if (node.getAST().apiLevel() == AST.JLS2_INTERNAL) {
- printModifiers(node.getModifiers());
- }
- if (node.getAST().apiLevel() >= AST.JLS3) {
- printModifiers(node.modifiers());
- }
- this.buffer.append("function ");//$NON-NLS-1$
-// if (!node.isConstructor()) {
-// if (node.getAST().apiLevel() == AST.JLS2_INTERNAL) {
-// node.internalGetReturnType().accept(this);
-// } else {
-// if (node.getReturnType2() != null) {
-// node.getReturnType2().accept(this);
-// } else {
-// // methods really ought to have a return type
-// this.buffer.append("void");//$NON-NLS-1$
-// }
-// }
-// this.buffer.append(" ");//$NON-NLS-1$
-// }
- SimpleName name = node.getName();
- if (name!=null)
- name.accept(this);
- this.buffer.append("(");//$NON-NLS-1$
- for (Iterator it = node.parameters().iterator(); it.hasNext(); ) {
- SingleVariableDeclaration v = (SingleVariableDeclaration) it.next();
- v.accept(this);
- if (it.hasNext()) {
- this.buffer.append(",");//$NON-NLS-1$
- }
- }
- this.buffer.append(")");//$NON-NLS-1$
- for (int i = 0; i < node.getExtraDimensions(); i++) {
- this.buffer.append("[]"); //$NON-NLS-1$
- }
- if (!node.thrownExceptions().isEmpty()) {
- this.buffer.append(" throws ");//$NON-NLS-1$
- for (Iterator it = node.thrownExceptions().iterator(); it.hasNext(); ) {
- Name n = (Name) it.next();
- n.accept(this);
- if (it.hasNext()) {
- this.buffer.append(", ");//$NON-NLS-1$
- }
- }
- this.buffer.append(" ");//$NON-NLS-1$
- }
- if (node.getBody() == null) {
- this.buffer.append(";\n");//$NON-NLS-1$
- } else {
- node.getBody().accept(this);
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(FunctionInvocation)
- */
- public boolean visit(FunctionInvocation node) {
- if (node.getExpression() != null) {
- node.getExpression().accept(this);
- if (node.getName()!=null)
- this.buffer.append(".");//$NON-NLS-1$
- }
- if (node.getAST().apiLevel() >= AST.JLS3) {
- if (!node.typeArguments().isEmpty()) {
- this.buffer.append("<");//$NON-NLS-1$
- for (Iterator it = node.typeArguments().iterator(); it.hasNext(); ) {
- Type t = (Type) it.next();
- t.accept(this);
- if (it.hasNext()) {
- this.buffer.append(",");//$NON-NLS-1$
- }
- }
- this.buffer.append(">");//$NON-NLS-1$
- }
- }
- if (node.getName()!=null)
- node.getName().accept(this);
- this.buffer.append("(");//$NON-NLS-1$
- for (Iterator it = node.arguments().iterator(); it.hasNext(); ) {
- Expression e = (Expression) it.next();
- e.accept(this);
- if (it.hasNext()) {
- this.buffer.append(",");//$NON-NLS-1$
- }
- }
- this.buffer.append(")");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(Modifier)
- *
- */
- public boolean visit(Modifier node) {
- this.buffer.append(node.getKeyword().toString());
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(NullLiteral)
- */
- public boolean visit(NullLiteral node) {
- this.buffer.append("null");//$NON-NLS-1$
- return false;
- }
-
- public boolean visit(UndefinedLiteral node) {
- this.buffer.append("undefined");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(NumberLiteral)
- */
- public boolean visit(NumberLiteral node) {
- this.buffer.append(node.getToken());
- return false;
- }
-
-
-
- /*
- * @see ASTVisitor#visit(PrefixExpression)
- */
- public boolean visit(ObjectLiteral node) {
- if (node.fields().isEmpty())
- this.buffer.append("{}");//$NON-NLS-1$
- else {
- this.buffer.append("{\n");//$NON-NLS-1$
- for (Iterator it = node.fields().iterator(); it.hasNext(); ) {
- ObjectLiteralField field = (ObjectLiteralField) it.next();
- field.accept(this);
- if (it.hasNext()) {
- this.buffer.append(",\n");//$NON-NLS-1$
- }
- }
- this.buffer.append("\n}");//$NON-NLS-1$
- }
- return false;
- }
-
- public boolean visit(ObjectLiteralField node) {
- node.getFieldName().accept(this);
- this.buffer.append(" : "); //$NON-NLS-1$
- node.getInitializer().accept(this);
- return false;
- }
-
-
- /*
- * @see ASTVisitor#visit(PackageDeclaration)
- */
- public boolean visit(PackageDeclaration node) {
- if (node.getAST().apiLevel() >= AST.JLS3) {
- if (node.getJavadoc() != null) {
- node.getJavadoc().accept(this);
- }
- }
- printIndent();
- this.buffer.append("package ");//$NON-NLS-1$
- node.getName().accept(this);
- this.buffer.append(";\n");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ParenthesizedExpression)
- */
- public boolean visit(ParenthesizedExpression node) {
- this.buffer.append("(");//$NON-NLS-1$
- node.getExpression().accept(this);
- this.buffer.append(")");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(PostfixExpression)
- */
- public boolean visit(PostfixExpression node) {
- node.getOperand().accept(this);
- this.buffer.append(node.getOperator().toString());
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(PrefixExpression)
- */
- public boolean visit(PrefixExpression node) {
- this.buffer.append(node.getOperator().toString());
- node.getOperand().accept(this);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(PrimitiveType)
- */
- public boolean visit(PrimitiveType node) {
- this.buffer.append(node.getPrimitiveTypeCode().toString());
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(QualifiedName)
- */
- public boolean visit(QualifiedName node) {
- node.getQualifier().accept(this);
- this.buffer.append(".");//$NON-NLS-1$
- node.getName().accept(this);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(QualifiedType)
- *
- */
- public boolean visit(QualifiedType node) {
- node.getQualifier().accept(this);
- this.buffer.append(".");//$NON-NLS-1$
- node.getName().accept(this);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ReturnStatement)
- */
- public boolean visit(ReturnStatement node) {
- printIndent();
- this.buffer.append("return");//$NON-NLS-1$
- if (node.getExpression() != null) {
- this.buffer.append(" ");//$NON-NLS-1$
- node.getExpression().accept(this);
- }
- this.buffer.append(";\n");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(SimpleName)
- */
- public boolean visit(SimpleName node) {
- this.buffer.append(node.getIdentifier());
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(SimpleType)
- */
- public boolean visit(SimpleType node) {
- return true;
- }
-
-
- /*
- * @see ASTVisitor#visit(SingleVariableDeclaration)
- */
- public boolean visit(SingleVariableDeclaration node) {
- printIndent();
- if (node.getAST().apiLevel() == AST.JLS2_INTERNAL) {
- printModifiers(node.getModifiers());
- }
- if (node.getAST().apiLevel() >= AST.JLS3) {
- printModifiers(node.modifiers());
- }
- node.getType().accept(this);
- if (node.getAST().apiLevel() >= AST.JLS3) {
- if (node.isVarargs()) {
- this.buffer.append("...");//$NON-NLS-1$
- }
- }
- this.buffer.append(" ");//$NON-NLS-1$
- node.getName().accept(this);
- for (int i = 0; i < node.getExtraDimensions(); i++) {
- this.buffer.append("[]"); //$NON-NLS-1$
- }
- if (node.getInitializer() != null) {
- this.buffer.append("=");//$NON-NLS-1$
- node.getInitializer().accept(this);
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(StringLiteral)
- */
- public boolean visit(StringLiteral node) {
- this.buffer.append(node.getEscapedValue());
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(SuperConstructorInvocation)
- */
- public boolean visit(SuperConstructorInvocation node) {
- printIndent();
- if (node.getExpression() != null) {
- node.getExpression().accept(this);
- this.buffer.append(".");//$NON-NLS-1$
- }
- if (node.getAST().apiLevel() >= AST.JLS3) {
- if (!node.typeArguments().isEmpty()) {
- this.buffer.append("<");//$NON-NLS-1$
- for (Iterator it = node.typeArguments().iterator(); it.hasNext(); ) {
- Type t = (Type) it.next();
- t.accept(this);
- if (it.hasNext()) {
- this.buffer.append(",");//$NON-NLS-1$
- }
- }
- this.buffer.append(">");//$NON-NLS-1$
- }
- }
- this.buffer.append("super(");//$NON-NLS-1$
- for (Iterator it = node.arguments().iterator(); it.hasNext(); ) {
- Expression e = (Expression) it.next();
- e.accept(this);
- if (it.hasNext()) {
- this.buffer.append(",");//$NON-NLS-1$
- }
- }
- this.buffer.append(");\n");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(SuperFieldAccess)
- */
- public boolean visit(SuperFieldAccess node) {
- if (node.getQualifier() != null) {
- node.getQualifier().accept(this);
- this.buffer.append(".");//$NON-NLS-1$
- }
- this.buffer.append("super.");//$NON-NLS-1$
- node.getName().accept(this);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(SuperMethodInvocation)
- */
- public boolean visit(SuperMethodInvocation node) {
- if (node.getQualifier() != null) {
- node.getQualifier().accept(this);
- this.buffer.append(".");//$NON-NLS-1$
- }
- this.buffer.append("super.");//$NON-NLS-1$
- if (node.getAST().apiLevel() >= AST.JLS3) {
- if (!node.typeArguments().isEmpty()) {
- this.buffer.append("<");//$NON-NLS-1$
- for (Iterator it = node.typeArguments().iterator(); it.hasNext(); ) {
- Type t = (Type) it.next();
- t.accept(this);
- if (it.hasNext()) {
- this.buffer.append(",");//$NON-NLS-1$
- }
- }
- this.buffer.append(">");//$NON-NLS-1$
- }
- }
- node.getName().accept(this);
- this.buffer.append("(");//$NON-NLS-1$
- for (Iterator it = node.arguments().iterator(); it.hasNext(); ) {
- Expression e = (Expression) it.next();
- e.accept(this);
- if (it.hasNext()) {
- this.buffer.append(",");//$NON-NLS-1$
- }
- }
- this.buffer.append(")");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(SwitchCase)
- */
- public boolean visit(SwitchCase node) {
- if (node.isDefault()) {
- this.buffer.append("default :\n");//$NON-NLS-1$
- } else {
- this.buffer.append("case ");//$NON-NLS-1$
- node.getExpression().accept(this);
- this.buffer.append(":\n");//$NON-NLS-1$
- }
- this.indent++; //decremented in visit(SwitchStatement)
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(SwitchStatement)
- */
- public boolean visit(SwitchStatement node) {
- this.buffer.append("switch (");//$NON-NLS-1$
- node.getExpression().accept(this);
- this.buffer.append(") ");//$NON-NLS-1$
- this.buffer.append("{\n");//$NON-NLS-1$
- this.indent++;
- for (Iterator it = node.statements().iterator(); it.hasNext(); ) {
- Statement s = (Statement) it.next();
- s.accept(this);
- this.indent--; // incremented in visit(SwitchCase)
- }
- this.indent--;
- printIndent();
- this.buffer.append("}\n");//$NON-NLS-1$
- return false;
- }
-
-
- /*
- * @see ASTVisitor#visit(TagElement)
- *
- */
- public boolean visit(TagElement node) {
- if (node.isNested()) {
- // nested tags are always enclosed in braces
- this.buffer.append("{");//$NON-NLS-1$
- } else {
- // top-level tags always begin on a new line
- this.buffer.append("\n * ");//$NON-NLS-1$
- }
- boolean previousRequiresWhiteSpace = false;
- if (node.getTagName() != null) {
- this.buffer.append(node.getTagName());
- previousRequiresWhiteSpace = true;
- }
- boolean previousRequiresNewLine = false;
- for (Iterator it = node.fragments().iterator(); it.hasNext(); ) {
- ASTNode e = (ASTNode) it.next();
- // assume text elements include necessary leading and trailing whitespace
- // but Name, MemberRef, FunctionRef, and nested TagElement do not include white space
- boolean currentIncludesWhiteSpace = (e instanceof TextElement);
- if (previousRequiresNewLine && currentIncludesWhiteSpace) {
- this.buffer.append("\n * ");//$NON-NLS-1$
- }
- previousRequiresNewLine = currentIncludesWhiteSpace;
- // add space if required to separate
- if (previousRequiresWhiteSpace && !currentIncludesWhiteSpace) {
- this.buffer.append(" "); //$NON-NLS-1$
- }
- e.accept(this);
- previousRequiresWhiteSpace = !currentIncludesWhiteSpace && !(e instanceof TagElement);
- }
- if (node.isNested()) {
- this.buffer.append("}");//$NON-NLS-1$
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(TextElement)
- *
- */
- public boolean visit(TextElement node) {
- this.buffer.append(node.getText());
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ThisExpression)
- */
- public boolean visit(ThisExpression node) {
- if (node.getQualifier() != null) {
- node.getQualifier().accept(this);
- this.buffer.append(".");//$NON-NLS-1$
- }
- this.buffer.append("this");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ThrowStatement)
- */
- public boolean visit(ThrowStatement node) {
- printIndent();
- this.buffer.append("throw ");//$NON-NLS-1$
- node.getExpression().accept(this);
- this.buffer.append(";\n");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(TryStatement)
- */
- public boolean visit(TryStatement node) {
- printIndent();
- this.buffer.append("try ");//$NON-NLS-1$
- node.getBody().accept(this);
- this.buffer.append(" ");//$NON-NLS-1$
- for (Iterator it = node.catchClauses().iterator(); it.hasNext(); ) {
- CatchClause cc = (CatchClause) it.next();
- cc.accept(this);
- }
- if (node.getFinally() != null) {
- this.buffer.append(" finally ");//$NON-NLS-1$
- node.getFinally().accept(this);
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(TypeDeclaration)
- */
- public boolean visit(TypeDeclaration node) {
- if (node.getJavadoc() != null) {
- node.getJavadoc().accept(this);
- }
- if (node.getAST().apiLevel() == AST.JLS2_INTERNAL) {
- printModifiers(node.getModifiers());
- }
- if (node.getAST().apiLevel() >= AST.JLS3) {
- printModifiers(node.modifiers());
- }
- this.buffer.append("class ");//$NON-NLS-1$
- node.getName().accept(this);
- this.buffer.append(" ");//$NON-NLS-1$
- if (node.getAST().apiLevel() == AST.JLS2_INTERNAL) {
- if (node.internalGetSuperclass() != null) {
- this.buffer.append("extends ");//$NON-NLS-1$
- node.internalGetSuperclass().accept(this);
- this.buffer.append(" ");//$NON-NLS-1$
- }
- }
- if (node.getAST().apiLevel() >= AST.JLS3) {
- if (node.getSuperclassType() != null) {
- this.buffer.append("extends ");//$NON-NLS-1$
- node.getSuperclassType().accept(this);
- this.buffer.append(" ");//$NON-NLS-1$
- }
- }
- this.buffer.append("{\n");//$NON-NLS-1$
- this.indent++;
- for (Iterator it = node.bodyDeclarations().iterator(); it.hasNext(); ) {
- BodyDeclaration d = (BodyDeclaration) it.next();
- d.accept(this);
- }
- this.indent--;
- printIndent();
- this.buffer.append("}\n");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(TypeDeclarationStatement)
- */
- public boolean visit(TypeDeclarationStatement node) {
- if (node.getAST().apiLevel() == AST.JLS2_INTERNAL) {
- node.internalGetTypeDeclaration().accept(this);
- }
- if (node.getAST().apiLevel() >= AST.JLS3) {
- node.getDeclaration().accept(this);
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(TypeLiteral)
- */
- public boolean visit(TypeLiteral node) {
- node.getType().accept(this);
- this.buffer.append(".class");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(VariableDeclarationExpression)
- */
- public boolean visit(VariableDeclarationExpression node) {
- if (node.getAST().apiLevel() == AST.JLS2_INTERNAL) {
- printModifiers(node.getModifiers());
- }
- if (node.getAST().apiLevel() >= AST.JLS3) {
- printModifiers(node.modifiers());
- }
- node.getType().accept(this);
- this.buffer.append(" ");//$NON-NLS-1$
- for (Iterator it = node.fragments().iterator(); it.hasNext(); ) {
- VariableDeclarationFragment f = (VariableDeclarationFragment) it.next();
- f.accept(this);
- if (it.hasNext()) {
- this.buffer.append(", ");//$NON-NLS-1$
- }
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(VariableDeclarationFragment)
- */
- public boolean visit(VariableDeclarationFragment node) {
- node.getName().accept(this);
- for (int i = 0; i < node.getExtraDimensions(); i++) {
- this.buffer.append("[]");//$NON-NLS-1$
- }
- if (node.getInitializer() != null) {
- this.buffer.append("=");//$NON-NLS-1$
- node.getInitializer().accept(this);
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(VariableDeclarationStatement)
- */
- public boolean visit(VariableDeclarationStatement node) {
- printIndent();
- if (node.getAST().apiLevel() == AST.JLS2_INTERNAL) {
- printModifiers(node.getModifiers());
- }
- if (node.getAST().apiLevel() >= AST.JLS3) {
- printModifiers(node.modifiers());
- }
-// Type type = node.getType();
-// if (type!=null)
-// type.accept(this);
- this.buffer.append("var ");//$NON-NLS-1$
- for (Iterator it = node.fragments().iterator(); it.hasNext(); ) {
- VariableDeclarationFragment f = (VariableDeclarationFragment) it.next();
- f.accept(this);
- if (it.hasNext()) {
- this.buffer.append(", ");//$NON-NLS-1$
- }
- }
- this.buffer.append(";\n");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(WhileStatement)
- */
- public boolean visit(WhileStatement node) {
- printIndent();
- this.buffer.append("while (");//$NON-NLS-1$
- node.getExpression().accept(this);
- this.buffer.append(") ");//$NON-NLS-1$
- node.getBody().accept(this);
- return false;
- }
-
- public boolean visit(WithStatement node) {
- printIndent();
- this.buffer.append("with (");//$NON-NLS-1$
- node.getExpression().accept(this);
- this.buffer.append(") ");//$NON-NLS-1$
- node.getBody().accept(this);
- return false;
- }
-
-}
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
deleted file mode 100644
index 381c03cb..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Name.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-/**
- * Abstract base class for all AST nodes that represent names.
- * There are exactly two kinds of name: simple ones
- * (<code>SimpleName</code>) and qualified ones (<code>QualifiedName</code>).
- * <p>
- * <pre>
- * Name:
- * SimpleName
- * QualifiedName
- * </pre>
- * </p>
- *
- * 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 Name extends Expression implements IDocElement {
-
- /**
- * Approximate base size of an expression node instance in bytes,
- * including object header and instance fields.
- */
- static final int BASE_NAME_NODE_SIZE = BASE_NODE_SIZE + 1 * 4;
-
- /**
- * This index represents the position inside a qualified name.
- */
- int index;
-
- /**
- * Creates a new AST node for a name owned by the given AST.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- Name(AST ast) {
- super(ast);
- }
-
- /**
- * Returns whether this name is a simple name
- * (<code>SimpleName</code>).
- *
- * @return <code>true</code> if this is a simple name, and
- * <code>false</code> otherwise
- */
- public final boolean isSimpleName() {
- return (this instanceof SimpleName);
- }
-
- /**
- * Returns whether this name is a qualified name
- * (<code>QualifiedName</code>).
- *
- * @return <code>true</code> if this is a qualified name, and
- * <code>false</code> otherwise
- */
- public final boolean isQualifiedName() {
- return (this instanceof QualifiedName);
- }
-
- /**
- * Resolves and returns the binding for the entity referred to by this name.
- * <p>
- * Note that bindings are generally unavailable unless requested when the
- * AST is being built.
- * </p>
- *
- * @return the binding, or <code>null</code> if the binding cannot be
- * resolved
- */
- public final IBinding resolveBinding() {
- return this.ast.getBindingResolver().resolveName(this);
- }
-
- /**
- * Returns the standard dot-separated representation of this name.
- * If the name is a simple name, the result is the name's identifier.
- * If the name is a qualified name, the result is the name of the qualifier
- * (as computed by this method) followed by "." followed by the name's
- * identifier.
- *
- * @return the fully qualified name
- *
- */
- public final String getFullyQualifiedName() {
- if (isSimpleName()) {
- // avoid creating garbage for common case
- return ((SimpleName) this).getIdentifier();
- } else {
- StringBuffer buffer = new StringBuffer(50);
- appendName(buffer);
- return new String(buffer);
- }
- }
-
- /**
- * Appends the standard representation of this name to the given string
- * buffer.
- *
- * @param buffer the buffer
- *
- */
- abstract void appendName(StringBuffer buffer);
-}
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
deleted file mode 100644
index d7fd718a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/NodeEventHandler.java
+++ /dev/null
@@ -1,193 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.dom;
-
-/**
- * A node event handler is an internal mechanism for receiving
- * notification of changes to nodes in an AST.
- * <p>
- * The default implementation serves as the default event handler
- * that does nothing. Internal subclasses do all the real work.
- * </p>
- *
- * @see AST#getEventHandler()
- *
- * 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.
- */
-class NodeEventHandler {
-
- /**
- * Creates a node event handler.
- */
- NodeEventHandler() {
- // default implementation: do nothing
- }
-
- /**
- * Reports that the given node is about to lose a child.
- * The first half of an event pair. The default implementation does nothing.
- *
- * @param node the node about to be modified
- * @param child the node about to be removed
- * @param property the child or child list property descriptor
- * @see #postRemoveChildEvent(ASTNode, ASTNode, StructuralPropertyDescriptor)
- *
- */
- void preRemoveChildEvent(ASTNode node, ASTNode child, StructuralPropertyDescriptor property) {
- // do nothing
- // System.out.println("DEL1 " + property);
- }
-
- /**
- * Reports that the given node has just lose a child.
- * The second half of an event pair. The default implementation does nothing.
- *
- * @param node the node that was modified
- * @param child the child that was removed; note that this node is unparented
- * @param property the child or child list property descriptor
- * @see #preRemoveChildEvent(ASTNode, ASTNode, StructuralPropertyDescriptor)
- *
- */
- void postRemoveChildEvent(ASTNode node, ASTNode child, StructuralPropertyDescriptor property) {
- // do nothing
- // System.out.println("DEL2 " + property);
- }
-
- /**
- * Reports that the given node is about to have a child replaced.
- * The first half of an event pair.
- * The default implementation does nothing.
- *
- * @param node the node about to be modified
- * @param child the node about to be replaced
- * @param newChild the replacement child; note that this node is unparented
- * @param property the child or child list property descriptor
- * @see #preReplaceChildEvent(ASTNode, ASTNode, ASTNode, StructuralPropertyDescriptor)
- *
- */
- void preReplaceChildEvent(ASTNode node, ASTNode child, ASTNode newChild, StructuralPropertyDescriptor property) {
- // do nothing
- // System.out.println("REP1 " + property);
- }
-
- /**
- * Reports that the given node has had its child replaced. The second half
- * of an event pair. The default implementation does nothing.
- *
- * @param node the node that was modified
- * @param child the node that was replaced; note that this node is unparented
- * @param newChild the replacement child
- * @param property the child or child list property descriptor
- * @see #postReplaceChildEvent(ASTNode, ASTNode, ASTNode, StructuralPropertyDescriptor)
- *
- */
- void postReplaceChildEvent(ASTNode node, ASTNode child, ASTNode newChild, StructuralPropertyDescriptor property) {
- // do nothing
- // System.out.println("REP2 " + property);
- }
-
- /**
- * Reports that the given node is about to gain a child.
- * The first half of an event pair. The default implementation does nothing.
- *
- * @param node the node that to be modified
- * @param child the node that is to be added as a child; note that this
- * node is unparented; in the case of a child list property, the exact
- * location of insertion is not supplied (but is known on the
- * corresponding <code>postAddChildEvent</code> to
- * follow)
- * @param property the child or child list property descriptor
- * @see #postAddChildEvent(ASTNode, ASTNode, StructuralPropertyDescriptor)
- *
- */
- void preAddChildEvent(ASTNode node, ASTNode child, StructuralPropertyDescriptor property) {
- // do nothing
- // System.out.println("ADD1 " + property);
- }
-
- /**
- * Reports that the given node has just gained a child.
- * The second half of an event pair. The default implementation does nothing.
- *
- * @param node the node that was modified
- * @param child the node that was added as a child
- * @param property the child or child list property descriptor
- * @see #preAddChildEvent(ASTNode, ASTNode, StructuralPropertyDescriptor)
- *
- */
- void postAddChildEvent(ASTNode node, ASTNode child, StructuralPropertyDescriptor property) {
- // do nothing
- // System.out.println("ADD2 " + property);
- }
-
- /**
- * Reports that the given node is about to change the value of a
- * non-child property. The first half of an event pair.
- * The default implementation does nothing.
- *
- * @param node the node to be modified
- * @param property the property descriptor
- * @see #postValueChangeEvent(ASTNode, SimplePropertyDescriptor)
- *
- */
- void preValueChangeEvent(ASTNode node, SimplePropertyDescriptor property) {
- // do nothing
- // System.out.println("MOD1 " + property);
- }
-
- /**
- * Reports that the given node has just changed the value of a
- * non-child property. The second half of an event pair.
- * The default implementation does nothing.
- *
- * @param node the node that was modified
- * @param property the property descriptor
- * @see #preValueChangeEvent(ASTNode, SimplePropertyDescriptor)
- *
- */
- void postValueChangeEvent(ASTNode node, SimplePropertyDescriptor property) {
- // do nothing
- // System.out.println("MOD2 " + property);
- }
-
- /**
- * Reports that the given node is about to be cloned.
- * The first half of an event pair.
- * The default implementation does nothing.
- *
- * @param node the node to be modified
- * @see #postCloneNodeEvent(ASTNode, ASTNode)
- *
- */
- void preCloneNodeEvent(ASTNode node) {
- // do nothing
- // System.out.println("CLONE1");
- }
-
- /**
- * Reports that the given node has just been cloned.
- * The second half of an event pair.
- * The default implementation does nothing.
- *
- * @param node the node that was modified
- * @param clone the clone of <code>node</code>
- * @see #preCloneNodeEvent(ASTNode)
- *
- */
- void postCloneNodeEvent(ASTNode node, ASTNode clone) {
- // do nothing
- // System.out.println("CLONE2");
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/NodeSearcher.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/NodeSearcher.java
deleted file mode 100644
index f6283bb7..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/NodeSearcher.java
+++ /dev/null
@@ -1,107 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.dom;
-
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ConstructorDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Initializer;
-import org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration;
-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.MethodScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Scope;
-
-/**
- *
- * 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.
- */
-class NodeSearcher extends ASTVisitor {
- public org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode found;
- public TypeDeclaration enclosingType;
- public int position;
-
- NodeSearcher(int position) {
- this.position = position;
- }
-
- public boolean visit(
- ConstructorDeclaration constructorDeclaration,
- ClassScope scope) {
-
- if (constructorDeclaration.declarationSourceStart <= position
- && position <= constructorDeclaration.declarationSourceEnd) {
- found = constructorDeclaration;
- return false;
- }
- return true;
- }
-
- public boolean visit(
- FieldDeclaration fieldDeclaration,
- MethodScope scope) {
- if (fieldDeclaration.declarationSourceStart <= position
- && position <= fieldDeclaration.declarationSourceEnd) {
- found = fieldDeclaration;
- return false;
- }
- return true;
- }
-
- public boolean visit(Initializer initializer, MethodScope scope) {
- if (initializer.declarationSourceStart <= position
- && position <= initializer.declarationSourceEnd) {
- found = initializer;
- return false;
- }
- return true;
- }
-
- public boolean visit(
- TypeDeclaration memberTypeDeclaration,
- ClassScope scope) {
- if (memberTypeDeclaration.declarationSourceStart <= position
- && position <= memberTypeDeclaration.declarationSourceEnd) {
- enclosingType = memberTypeDeclaration;
- return true;
-
- }
- return false;
- }
-
- public boolean visit(
- MethodDeclaration methodDeclaration,
- Scope scope) {
-
- if (methodDeclaration.declarationSourceStart <= position
- && position <= methodDeclaration.declarationSourceEnd) {
- found = methodDeclaration;
- return false;
- }
- return true;
- }
-
- public boolean visit(
- TypeDeclaration typeDeclaration,
- CompilationUnitScope scope) {
- if (typeDeclaration.declarationSourceStart <= position
- && position <= typeDeclaration.declarationSourceEnd) {
- enclosingType = typeDeclaration;
- return true;
- }
- return false;
- }
-
-}
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
deleted file mode 100644
index 41e7f6cc..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/NullLiteral.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Null literal node.
- *
- * 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 NullLiteral extends Expression {
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List propertyList = new ArrayList(1);
- createPropertyList(NullLiteral.class, propertyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * Creates a new unparented null literal node owned by the given AST.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- NullLiteral(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return NULL_LITERAL;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- NullLiteral result = new NullLiteral(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- visitor.visit(this);
- visitor.endVisit(this);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return BASE_NODE_SIZE;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return memSize();
- }
-}
-
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
deleted file mode 100644
index 5938ad6c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/NumberLiteral.java
+++ /dev/null
@@ -1,225 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.internal.compiler.parser.Scanner;
-import org.eclipse.wst.jsdt.internal.compiler.parser.TerminalTokens;
-
-/**
- * Number literal nodes.
- *
- * 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 NumberLiteral extends Expression {
-
- /**
- * The "token" structural property of this node type.
- *
- */
- public static final SimplePropertyDescriptor TOKEN_PROPERTY =
- new SimplePropertyDescriptor(NumberLiteral.class, "token", String.class, MANDATORY); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List propertyList = new ArrayList(2);
- createPropertyList(NumberLiteral.class, propertyList);
- addProperty(TOKEN_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The token string; defaults to the integer literal "0".
- */
- private String tokenValue = "0";//$NON-NLS-1$
-
- /**
- * Creates a new unparented number literal node owned by the given AST.
- * By default, the number literal is the token "<code>0</code>".
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- NumberLiteral(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final Object internalGetSetObjectProperty(SimplePropertyDescriptor property, boolean get, Object value) {
- if (property == TOKEN_PROPERTY) {
- if (get) {
- return getToken();
- } else {
- setToken((String) value);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetObjectProperty(property, get, value);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return NUMBER_LITERAL;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- NumberLiteral result = new NumberLiteral(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setToken(getToken());
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- visitor.visit(this);
- visitor.endVisit(this);
- }
-
- /**
- * Returns the token of this number literal node. The value is the sequence
- * of characters that would appear in the source program.
- *
- * @return the numeric literal token
- */
- public String getToken() {
- return this.tokenValue;
- }
-
- /**
- * Sets the token of this number literal node. The value is the sequence
- * of characters that would appear in the source program.
- *
- * @param token the numeric literal token
- * @exception IllegalArgumentException if the argument is incorrect
- */
- public void setToken(String token) {
- // update internalSetToken(String) if this is changed
- if (token == null || token.length() == 0) {
- throw new IllegalArgumentException();
- }
- Scanner scanner = this.ast.scanner;
- char[] source = token.toCharArray();
- scanner.setSource(source);
- scanner.resetTo(0, source.length);
- scanner.tokenizeComments = false;
- scanner.tokenizeWhiteSpace = false;
- try {
- int tokenType = scanner.getNextToken();
- switch(tokenType) {
- case TerminalTokens.TokenNameDoubleLiteral:
- case TerminalTokens.TokenNameIntegerLiteral:
- case TerminalTokens.TokenNameFloatingPointLiteral:
- case TerminalTokens.TokenNameLongLiteral:
- break;
- case TerminalTokens.TokenNameMINUS :
- tokenType = scanner.getNextToken();
- switch(tokenType) {
- case TerminalTokens.TokenNameDoubleLiteral:
- case TerminalTokens.TokenNameIntegerLiteral:
- case TerminalTokens.TokenNameFloatingPointLiteral:
- case TerminalTokens.TokenNameLongLiteral:
- break;
- default:
- throw new IllegalArgumentException("Invalid number literal : >" + token + "<"); //$NON-NLS-1$//$NON-NLS-2$
- }
- break;
- default:
- throw new IllegalArgumentException("Invalid number literal : >" + token + "<");//$NON-NLS-1$//$NON-NLS-2$
- }
- } catch(InvalidInputException e) {
- throw new IllegalArgumentException();
- } finally {
- scanner.tokenizeComments = true;
- scanner.tokenizeWhiteSpace = true;
- }
- preValueChange(TOKEN_PROPERTY);
- this.tokenValue = token;
- postValueChange(TOKEN_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * This method is a copy of setToken(String) that doesn't do any validation.
- */
- void internalSetToken(String token) {
- preValueChange(TOKEN_PROPERTY);
- this.tokenValue = token;
- postValueChange(TOKEN_PROPERTY);
- }
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- int size = BASE_NODE_SIZE + 1 * 4 + stringSize(tokenValue);
- return size;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return memSize();
- }
-}
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
deleted file mode 100644
index 5e874d69..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ObjectLiteral.java
+++ /dev/null
@@ -1,151 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-
-/**
- *
- * 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 ObjectLiteral extends Expression {
-
- public static final ChildListPropertyDescriptor FIELDS_PROPERTY =
- new ChildListPropertyDescriptor(ObjectLiteral.class, "fields", ObjectLiteralField.class, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List properyList = new ArrayList(3);
- createPropertyList(ObjectLiteral.class, properyList);
- addProperty(FIELDS_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- private ASTNode.NodeList fields =
- new ASTNode.NodeList(FIELDS_PROPERTY);
-
- /**
- * Creates a new AST node for a cast expression owned by the given
- * AST. By default, the type and expression are unspecified (but legal).
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- ObjectLiteral(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalGetChildListProperty(ChildListPropertyDescriptor property) {
- if (property == FIELDS_PROPERTY) {
- return fields();
- }
- // allow default implementation to flag the error
- return super.internalGetChildListProperty(property);
- }
-
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return OBJECT_LITERAL;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- ObjectLiteral result = new ObjectLiteral(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.fields().addAll(ASTNode.copySubtrees(target, fields()));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChildren(visitor, this.fields);
- }
- visitor.endVisit(this);
- }
-
- public List fields() {
- return this.fields;
- }
-
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- // treat Code as free
- return BASE_NODE_SIZE + 2 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + this.fields.listSize();
- }
-}
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
deleted file mode 100644
index fd4408ff..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ObjectLiteralField.java
+++ /dev/null
@@ -1,261 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-
-/**
- *
- * 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 ObjectLiteralField extends Expression {
-
- /**
- * The "type" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor FIELD_NAME_PROPERTY =
- new ChildPropertyDescriptor(ObjectLiteralField.class, "fieldName", Expression.class, MANDATORY, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "expression" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor INITIALIZER_PROPERTY =
- new ChildPropertyDescriptor(ObjectLiteralField.class, "initializer", Expression.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List properyList = new ArrayList(3);
- createPropertyList(ObjectLiteralField.class, properyList);
- addProperty(FIELD_NAME_PROPERTY, properyList);
- addProperty(INITIALIZER_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The type; lazily initialized; defaults to a unspecified,
- * legal type.
- */
- private Expression fieldName = null;
-
- /**
- * The expression; lazily initialized; defaults to a unspecified, but legal,
- * expression.
- */
- private Expression initializer = null;
-
- /**
- * Creates a new AST node for a cast expression owned by the given
- * AST. By default, the type and expression are unspecified (but legal).
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- ObjectLiteralField(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == INITIALIZER_PROPERTY) {
- if (get) {
- return getInitializer();
- } else {
- setInitializer((Expression) child);
- return null;
- }
- }
- if (property == FIELD_NAME_PROPERTY) {
- if (get) {
- return getFieldName();
- } else {
- setFieldName((Expression) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return OBJECT_LITERAL_FIELD;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- ObjectLiteralField result = new ObjectLiteralField(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setFieldName( (Expression) getFieldName().clone(target));
- result.setInitializer((Expression) getInitializer().clone(target));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChild(visitor, getFieldName());
- acceptChild(visitor, getInitializer());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the type in this cast expression.
- *
- * @return the type
- */
- public Expression getFieldName() {
- if (this.fieldName == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.fieldName == null) {
- preLazyInit();
- this.fieldName = new SimpleName(this.ast);
- postLazyInit(this.fieldName, FIELD_NAME_PROPERTY);
- }
- }
- }
- return this.fieldName;
- }
-
- /**
- * Sets the type in this cast expression to the given type.
- *
- * @param type the new type
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public void setFieldName(Expression name) {
- if (name == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.fieldName;
- preReplaceChild(oldChild, name, FIELD_NAME_PROPERTY);
- this.fieldName = name;
- postReplaceChild(oldChild, name, FIELD_NAME_PROPERTY);
- }
-
- /**
- * Returns the expression of this cast expression.
- *
- * @return the expression node
- */
- public Expression getInitializer() {
- if (this.initializer == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.initializer == null) {
- preLazyInit();
- this.initializer = new SimpleName(this.ast);
- postLazyInit(this.initializer, INITIALIZER_PROPERTY);
- }
- }
- }
- return this.initializer;
- }
-
- /**
- * Sets the expression of this cast expression.
- *
- * @param expression the new expression node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setInitializer(Expression expression) {
- if (expression == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.initializer;
- preReplaceChild(oldChild, expression, INITIALIZER_PROPERTY);
- this.initializer = expression;
- postReplaceChild(oldChild, expression, INITIALIZER_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- // treat Code as free
- return BASE_NODE_SIZE + 2 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.fieldName == null ? 0 : getFieldName().treeSize())
- + (this.initializer == null ? 0 : getInitializer().treeSize());
- }
-}
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
deleted file mode 100644
index b22bcb16..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/PackageBinding.java
+++ /dev/null
@@ -1,162 +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.core.dom;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.env.INameEnvironment;
-import org.eclipse.wst.jsdt.internal.compiler.util.Util;
-import org.eclipse.wst.jsdt.internal.core.NameLookup;
-import org.eclipse.wst.jsdt.internal.core.SearchableEnvironment;
-
-/**
- * Internal implementation of package bindings.
- */
-class PackageBinding implements IPackageBinding {
-
- private static final String[] NO_NAME_COMPONENTS = CharOperation.NO_STRINGS;
- private static final String UNNAMED = Util.EMPTY_STRING;
- private static final char PACKAGE_NAME_SEPARATOR = '.';
-
- private org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding binding;
- private String name;
-// private BindingResolver resolver;
- private String[] components;
-
- PackageBinding(org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding binding, BindingResolver resolver) {
- this.binding = binding;
-// this.resolver = resolver;
- }
-
-
- /*
- * @see IBinding#getName()
- */
- public String getName() {
- if (name == null) {
- computeNameAndComponents();
- }
- return name;
- }
-
- /*
- * @see IPackageBinding#isUnnamed()
- */
- public boolean isUnnamed() {
- return getName().equals(UNNAMED);
- }
-
- /*
- * @see IPackageBinding#getNameComponents()
- */
- public String[] getNameComponents() {
- if (components == null) {
- computeNameAndComponents();
- }
- return components;
- }
-
- /*
- * @see IBinding#getKind()
- */
- public int getKind() {
- return IBinding.PACKAGE;
- }
-
- /*
- * @see IBinding#getModifiers()
- */
- public int getModifiers() {
- return Modifier.NONE;
- }
-
- /*
- * @see IBinding#isDeprecated()
- */
- public boolean isDeprecated() {
- return false;
- }
-
- /**
- * @see IBinding#isRecovered()
- */
- public boolean isRecovered() {
- return false;
- }
-
- /*
- * @see IBinding#getJavaElement()
- */
- public IJavaScriptElement getJavaElement() {
- INameEnvironment nameEnvironment = this.binding.environment.nameEnvironment; // a package binding always has a LooupEnvironment set
- if (!(nameEnvironment instanceof SearchableEnvironment)) return null;
- NameLookup nameLookup = ((SearchableEnvironment) nameEnvironment).nameLookup;
- if (nameLookup == null) return null;
- IJavaScriptElement[] pkgs = nameLookup.findPackageFragments(getName(), false/*exact match*/);
- if (pkgs == null) return null;
- return pkgs[0];
- }
-
- /*
- * @see IBinding#getKey()
- */
- public String getKey() {
- return new String(this.binding.computeUniqueKey());
- }
-
- /*
- * @see IBinding#isEqualTo(Binding)
- *
- */
- public boolean isEqualTo(IBinding other) {
- if (other == this) {
- // identical binding - equal (key or no key)
- return true;
- }
- if (other == null) {
- // other binding missing
- return false;
- }
- if (!(other instanceof PackageBinding)) {
- return false;
- }
- org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding packageBinding2 = ((PackageBinding) other).binding;
- return CharOperation.equals(this.binding.compoundName, packageBinding2.compoundName);
- }
-
- private void computeNameAndComponents() {
- char[][] compoundName = this.binding.compoundName;
- if (compoundName == CharOperation.NO_CHAR_CHAR || compoundName == null) {
- name = UNNAMED;
- components = NO_NAME_COMPONENTS;
- } else {
- int length = compoundName.length;
- components = new String[length];
- StringBuffer buffer = new StringBuffer();
- for (int i = 0; i < length - 1; i++) {
- components[i] = new String(compoundName[i]);
- buffer.append(compoundName[i]).append(PACKAGE_NAME_SEPARATOR);
- }
- components[length - 1] = new String(compoundName[length - 1]);
- buffer.append(compoundName[length - 1]);
- name = buffer.toString();
- }
- }
-
- /*
- * For debugging purpose only.
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return this.binding.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/PackageDeclaration.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/PackageDeclaration.java
deleted file mode 100644
index bd677132..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/PackageDeclaration.java
+++ /dev/null
@@ -1,352 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Package declaration AST node type.
- * For JLS2:
- * <pre>
- * PackageDeclaration:
- * <b>package</b> Name <b>;</b>
- * </pre>
- * For JLS3, annotations and doc comment
- * were added:
- * <pre>
- * PackageDeclaration:
- * [ jsdoc ] { Annotation } <b>package</b> Name <b>;</b>
- * </pre>
- * Note that the standard AST parser only recognizes a jsdoc comment
- * immediately preceding the package declaration when it occurs in the
- * special <code>package-info.js</code> javaScript unit (JLS3 7.4.1.1).
- * The jsdoc comment in that file contains the package description.
- *
- * <p><b>Note: This Class only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * 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 PackageDeclaration extends ASTNode {
-
- /**
- * The "javadoc" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor JAVADOC_PROPERTY =
- new ChildPropertyDescriptor(PackageDeclaration.class, "javadoc", JSdoc.class, OPTIONAL, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "name" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor NAME_PROPERTY =
- new ChildPropertyDescriptor(PackageDeclaration.class, "name", Name.class, MANDATORY, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS_2_0;
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS_3_0;
-
- static {
- List propertyList = new ArrayList(2);
- createPropertyList(PackageDeclaration.class, propertyList);
- addProperty(NAME_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS_2_0 = reapPropertyList(propertyList);
-
- propertyList = new ArrayList(4);
- createPropertyList(PackageDeclaration.class, propertyList);
- addProperty(JAVADOC_PROPERTY, propertyList);
- addProperty(NAME_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS_3_0 = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- if (apiLevel == AST.JLS2_INTERNAL) {
- return PROPERTY_DESCRIPTORS_2_0;
- } else {
- return PROPERTY_DESCRIPTORS_3_0;
- }
- }
-
- /**
- * The doc comment, or <code>null</code> if none.
- * Defaults to none.
- *
- */
- JSdoc optionalDocComment = null;
-
- /**
- * The annotations (element type: <code>Annotation</code>).
- * Null in JLS2. Added in JLS3; defaults to an empty list
- * (see constructor).
- *
- */
- private ASTNode.NodeList annotations = null;
-
- /**
- * The package name; lazily initialized; defaults to a unspecified,
- * legal JavaScript package identifier.
- */
- private Name packageName = null;
-
- /**
- * Creates a new AST node for a package declaration owned by the
- * given AST. The package declaration initially has an unspecified,
- * but legal, JavaScript identifier; and an empty list of annotations.
- * <p>
- * N.B. This constructor is package-private; all subclasses must be
- * declared in the same package; clients are unable to declare
- * additional subclasses.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- PackageDeclaration(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == JAVADOC_PROPERTY) {
- if (get) {
- return getJavadoc();
- } else {
- setJavadoc((JSdoc) child);
- return null;
- }
- }
- if (property == NAME_PROPERTY) {
- if (get) {
- return getName();
- } else {
- setName((Name) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalGetChildListProperty(ChildListPropertyDescriptor property) {
- // allow default implementation to flag the error
- return super.internalGetChildListProperty(property);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return PACKAGE_DECLARATION;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- PackageDeclaration result = new PackageDeclaration(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- if (this.ast.apiLevel >= AST.JLS3) {
- result.setJavadoc((JSdoc) ASTNode.copySubtree(target, getJavadoc()));
- result.annotations().addAll(ASTNode.copySubtrees(target, annotations()));
- }
- result.setName((Name) getName().clone(target));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- if (this.ast.apiLevel >= AST.JLS3) {
- acceptChild(visitor, getJavadoc());
- acceptChildren(visitor, this.annotations);
- }
- acceptChild(visitor, getName());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the live ordered list of annotations of this
- * package declaration (added in JLS3 API).
- *
- * @return the live list of annotations
- * (element type: <code>Annotation</code>)
- * @exception UnsupportedOperationException if this operation is used in
- * a JLS2 AST
- *
- */
- public List annotations() {
- // more efficient than just calling unsupportedIn2() to check
- if (this.annotations == null) {
- unsupportedIn2();
- }
- return this.annotations;
- }
-
- /**
- * Returns the doc comment node.
- *
- * @return the doc comment node, or <code>null</code> if none
- * @exception UnsupportedOperationException if this operation is used in
- * a JLS2 AST
- *
- */
- public JSdoc getJavadoc() {
- // more efficient than just calling unsupportedIn2() to check
- if (this.annotations == null) {
- unsupportedIn2();
- }
- return this.optionalDocComment;
- }
-
- /**
- * Sets or clears the doc comment node.
- *
- * @param docComment the doc comment node, or <code>null</code> if none
- * @exception IllegalArgumentException if the doc comment string is invalid
- * @exception UnsupportedOperationException if this operation is used in
- * a JLS2 AST
- *
- */
- public void setJavadoc(JSdoc docComment) {
- // more efficient than just calling unsupportedIn2() to check
- if (this.annotations == null) {
- unsupportedIn2();
- }
- ASTNode oldChild = this.optionalDocComment;
- preReplaceChild(oldChild, docComment, JAVADOC_PROPERTY);
- this.optionalDocComment = docComment;
- postReplaceChild(oldChild, docComment, JAVADOC_PROPERTY);
- }
-
- /**
- * Returns the package name of this package declaration.
- *
- * @return the package name node
- */
- public Name getName() {
- if (this.packageName == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.packageName == null) {
- preLazyInit();
- this.packageName = new SimpleName(this.ast);
- postLazyInit(this.packageName, NAME_PROPERTY);
- }
- }
- }
- return this.packageName;
- }
-
- /**
- * Sets the package name of this package declaration to the given name.
- *
- * @param name the new package name
- * @exception IllegalArgumentException if`:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public void setName(Name name) {
- if (name == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.packageName;
- preReplaceChild(oldChild, name, NAME_PROPERTY);
- this.packageName = name;
- postReplaceChild(oldChild, name, NAME_PROPERTY);
- }
-
- /**
- * Resolves and returns the binding for the package declared in this package
- * declaration.
- * <p>
- * Note that bindings are generally unavailable unless requested when the
- * AST is being built.
- * </p>
- *
- * @return the binding, or <code>null</code> if the binding cannot be
- * resolved
- */
- public IPackageBinding resolveBinding() {
- return this.ast.getBindingResolver().resolvePackage(this);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return BASE_NODE_SIZE + 3 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.optionalDocComment == null ? 0 : getJavadoc().treeSize())
- + (this.annotations == null ? 0 : this.annotations.listSize())
- + (this.packageName == null ? 0 : getName().treeSize());
- }
-}
-
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
deleted file mode 100644
index dcce8647..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ParenthesizedExpression.java
+++ /dev/null
@@ -1,202 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Parenthesized expression AST node type.
- *
- * <pre>
- * ParenthesizedExpression:
- * <b>(</b> Expression <b>)</b>
- * </pre>
- *
- * 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 ParenthesizedExpression extends Expression {
-
- /**
- * The "expression" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor EXPRESSION_PROPERTY =
- new ChildPropertyDescriptor(ParenthesizedExpression.class, "expression", Expression.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List propertyList = new ArrayList(2);
- createPropertyList(ParenthesizedExpression.class, propertyList);
- addProperty(EXPRESSION_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The expression; lazily initialized; defaults to a unspecified, but legal,
- * expression.
- */
- private Expression expression = null;
-
- /**
- * Creates a new unparented parenthesized expression node owned by the given
- * AST. By default, the parenthesized expression has an unspecified, but
- * legal, expression.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- ParenthesizedExpression(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == EXPRESSION_PROPERTY) {
- if (get) {
- return getExpression();
- } else {
- setExpression((Expression) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return PARENTHESIZED_EXPRESSION;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- ParenthesizedExpression result = new ParenthesizedExpression(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setExpression((Expression) getExpression().clone(target));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- acceptChild(visitor, getExpression());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the expression of this parenthesized expression.
- *
- * @return the expression node
- */
- public Expression getExpression() {
- if (this.expression == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.expression == null) {
- preLazyInit();
- this.expression = new SimpleName(this.ast);
- postLazyInit(this.expression, EXPRESSION_PROPERTY);
- }
- }
- }
- return this.expression;
- }
-
- /**
- * Sets the expression of this parenthesized expression.
- *
- * @param expression the new expression node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setExpression(Expression expression) {
- if (expression == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.expression;
- preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY);
- this.expression = expression;
- postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return BASE_NODE_SIZE + 1 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.expression == null ? 0 : getExpression().treeSize());
- }
-}
-
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
deleted file mode 100644
index b7e366c3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/PostfixExpression.java
+++ /dev/null
@@ -1,332 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Postfix expression AST node type.
- *
- * <pre>
- * PostfixExpression:
- * Expression PostfixOperator
- * </pre>
- *
- * 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 PostfixExpression extends Expression {
-
- /**
- * Postfix operators (typesafe enumeration).
- * <pre>
- * PostfixOperator:
- * <b><code>++</code></b> <code>INCREMENT</code>
- * <b><code>--</code></b> <code>DECREMENT</code>
- * </pre>
- */
- public static class Operator {
-
- /**
- * The token for the operator.
- */
- private String token;
-
- /**
- * Creates a new postfix operator with the given token.
- * <p>
- * Note: this constructor is private. The only instances
- * ever created are the ones for the standard operators.
- * </p>
- *
- * @param token the character sequence for the operator
- */
- private Operator(String token) {
- this.token = token;
- }
-
- /**
- * Returns the character sequence for the operator.
- *
- * @return the character sequence for the operator
- */
- public String toString() {
- return token;
- }
-
- /** Postfix increment "++" operator. */
- public static final Operator INCREMENT = new Operator("++");//$NON-NLS-1$
- /** Postfix decrement "--" operator. */
- public static final Operator DECREMENT = new Operator("--");//$NON-NLS-1$
-
- /**
- * Map from token to operator (key type: <code>String</code>;
- * value type: <code>Operator</code>).
- */
- private static final Map CODES;
- static {
- CODES = new HashMap(20);
- Operator[] ops = {
- INCREMENT,
- DECREMENT,
- };
- for (int i = 0; i < ops.length; i++) {
- CODES.put(ops[i].toString(), ops[i]);
- }
- }
-
- /**
- * Returns the postfix operator corresponding to the given string,
- * or <code>null</code> if none.
- * <p>
- * <code>toOperator</code> is the converse of <code>toString</code>:
- * that is, <code>Operator.toOperator(op.toString()) == op</code> for
- * all operators <code>op</code>.
- * </p>
- *
- * @param token the character sequence for the operator
- * @return the postfix operator, or <code>null</code> if none
- */
- public static Operator toOperator(String token) {
- return (Operator) CODES.get(token);
- }
- }
-
- /**
- * The "operator" structural property of this node type.
- *
- */
- public static final SimplePropertyDescriptor OPERATOR_PROPERTY =
- new SimplePropertyDescriptor(PostfixExpression.class, "operator", PostfixExpression.Operator.class, MANDATORY); //$NON-NLS-1$
-
- /**
- * The "operand" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor OPERAND_PROPERTY =
- new ChildPropertyDescriptor(PostfixExpression.class, "operand", Expression.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List propertyList = new ArrayList(3);
- createPropertyList(PostfixExpression.class, propertyList);
- addProperty(OPERAND_PROPERTY, propertyList);
- addProperty(OPERATOR_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The operator; defaults to an unspecified postfix operator.
- */
- private PostfixExpression.Operator operator =
- PostfixExpression.Operator.INCREMENT;
-
- /**
- * The operand; lazily initialized; defaults to an unspecified,
- * but legal, simple name.
- */
- private Expression operand = null;
-
- /**
- * Creates a new AST node for an postfix expression owned by the given
- * AST. By default, the node has unspecified (but legal) operator and
- * operand.
- *
- * @param ast the AST that is to own this node
- */
- PostfixExpression(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final Object internalGetSetObjectProperty(SimplePropertyDescriptor property, boolean get, Object value) {
- if (property == OPERATOR_PROPERTY) {
- if (get) {
- return getOperator();
- } else {
- setOperator((Operator) value);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetObjectProperty(property, get, value);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == OPERAND_PROPERTY) {
- if (get) {
- return getOperand();
- } else {
- setOperand((Expression) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return POSTFIX_EXPRESSION;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- PostfixExpression result = new PostfixExpression(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setOperator(getOperator());
- result.setOperand((Expression) getOperand().clone(target));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- acceptChild(visitor, getOperand());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the operator of this postfix expression.
- *
- * @return the operator
- */
- public PostfixExpression.Operator getOperator() {
- return this.operator;
- }
-
- /**
- * Sets the operator of this postfix expression.
- *
- * @param operator the operator
- * @exception IllegalArgumentException if the argument is incorrect
- */
- public void setOperator(PostfixExpression.Operator operator) {
- if (operator == null) {
- throw new IllegalArgumentException();
- }
- preValueChange(OPERATOR_PROPERTY);
- this.operator = operator;
- postValueChange(OPERATOR_PROPERTY);
- }
-
- /**
- * Returns the operand of this postfix expression.
- *
- * @return the operand expression node
- */
- public Expression getOperand() {
- if (this.operand == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.operand == null) {
- preLazyInit();
- this.operand= new SimpleName(this.ast);
- postLazyInit(this.operand, OPERAND_PROPERTY);
- }
- }
- }
- return this.operand;
- }
-
- /**
- * Sets the operand of this postfix expression.
- *
- * @param expression the operand expression node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setOperand(Expression expression) {
- if (expression == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.operand;
- preReplaceChild(oldChild, expression, OPERAND_PROPERTY);
- this.operand = expression;
- postReplaceChild(oldChild, expression, OPERAND_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- // treat Operator as free
- return BASE_NODE_SIZE + 2 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.operand == null ? 0 : getOperand().treeSize());
- }
-}
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
deleted file mode 100644
index a7f5dd14..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/PrefixExpression.java
+++ /dev/null
@@ -1,350 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Prefix expression AST node type.
- *
- * <pre>
- * PrefixExpression:
- * PrefixOperator Expression
- * </pre>
- *
- * 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 PrefixExpression extends Expression {
-
- /**
- * Prefix operators (typesafe enumeration).
- * <pre>
- * PrefixOperator:
- * <b><code>++</code></b> <code>INCREMENT</code>
- * <b><code>--</code></b> <code>DECREMENT</code>
- * <b><code>+</code></b> <code>PLUS</code>
- * <b><code>-</code></b> <code>MINUS</code>
- * <b><code>~</code></b> <code>COMPLEMENT</code>
- * <b><code>!</code></b> <code>NOT</code>
- * </pre>
- */
- public static class Operator {
-
- /**
- * The token for the operator.
- */
- private String token;
-
- /**
- * Creates a new prefix operator with the given token.
- * <p>
- * Note: this constructor is private. The only instances
- * ever created are the ones for the standard operators.
- * </p>
- *
- * @param token the character sequence for the operator
- */
- private Operator(String token) {
- this.token = token;
- }
-
- /**
- * Returns the character sequence for the operator.
- *
- * @return the character sequence for the operator
- */
- public String toString() {
- return token;
- }
-
- /** Prefix increment "++" operator. */
- public static final Operator INCREMENT = new Operator("++");//$NON-NLS-1$
- /** Prefix decrement "--" operator. */
- public static final Operator DECREMENT = new Operator("--");//$NON-NLS-1$
- /** Unary plus "+" operator. */
- public static final Operator PLUS = new Operator("+");//$NON-NLS-1$
- /** Unary minus "-" operator. */
- public static final Operator MINUS = new Operator("-");//$NON-NLS-1$
- /** Bitwise complement "~" operator. */
- public static final Operator COMPLEMENT = new Operator("~");//$NON-NLS-1$
- /** Logical complement "!" operator. */
- public static final Operator NOT = new Operator("!");//$NON-NLS-1$
-
- /**
- * Map from token to operator (key type: <code>String</code>;
- * value type: <code>Operator</code>).
- */
- private static final Map CODES;
- static {
- CODES = new HashMap(20);
- Operator[] ops = {
- INCREMENT,
- DECREMENT,
- PLUS,
- MINUS,
- COMPLEMENT,
- NOT,
- };
- for (int i = 0; i < ops.length; i++) {
- CODES.put(ops[i].toString(), ops[i]);
- }
- }
-
- /**
- * Returns the prefix operator corresponding to the given string,
- * or <code>null</code> if none.
- * <p>
- * <code>toOperator</code> is the converse of <code>toString</code>:
- * that is, <code>Operator.toOperator(op.toString()) == op</code> for
- * all operators <code>op</code>.
- * </p>
- *
- * @param token the character sequence for the operator
- * @return the prefix operator, or <code>null</code> if none
- */
- public static Operator toOperator(String token) {
- return (Operator) CODES.get(token);
- }
- }
-
- /**
- * The "operator" structural property of this node type.
- *
- */
- public static final SimplePropertyDescriptor OPERATOR_PROPERTY =
- new SimplePropertyDescriptor(PrefixExpression.class, "operator", PrefixExpression.Operator.class, MANDATORY); //$NON-NLS-1$
-
- /**
- * The "operand" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor OPERAND_PROPERTY =
- new ChildPropertyDescriptor(PrefixExpression.class, "operand", Expression.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List propertyList = new ArrayList(3);
- createPropertyList(PrefixExpression.class, propertyList);
- addProperty(OPERATOR_PROPERTY, propertyList);
- addProperty(OPERAND_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The operator; defaults to an unspecified prefix operator.
- */
- private PrefixExpression.Operator operator =
- PrefixExpression.Operator.PLUS;
-
- /**
- * The operand; lazily initialized; defaults to an unspecified,
- * but legal, simple name.
- */
- private Expression operand = null;
-
- /**
- * Creates a new AST node for an prefix expression owned by the given
- * AST. By default, the node has unspecified (but legal) operator and
- * operand.
- *
- * @param ast the AST that is to own this node
- */
- PrefixExpression(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final Object internalGetSetObjectProperty(SimplePropertyDescriptor property, boolean get, Object value) {
- if (property == OPERATOR_PROPERTY) {
- if (get) {
- return getOperator();
- } else {
- setOperator((Operator) value);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetObjectProperty(property, get, value);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == OPERAND_PROPERTY) {
- if (get) {
- return getOperand();
- } else {
- setOperand((Expression) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return PREFIX_EXPRESSION;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- PrefixExpression result = new PrefixExpression(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setOperator(getOperator());
- result.setOperand((Expression) getOperand().clone(target));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChild(visitor, getOperand());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the operator of this prefix expression.
- *
- * @return the operator
- */
- public PrefixExpression.Operator getOperator() {
- return this.operator;
- }
-
- /**
- * Sets the operator of this prefix expression.
- *
- * @param operator the operator
- * @exception IllegalArgumentException if the argument is incorrect
- */
- public void setOperator(PrefixExpression.Operator operator) {
- if (operator == null) {
- throw new IllegalArgumentException();
- }
- preValueChange(OPERATOR_PROPERTY);
- this.operator = operator;
- postValueChange(OPERATOR_PROPERTY);
- }
-
- /**
- * Returns the operand of this prefix expression.
- *
- * @return the operand expression node
- */
- public Expression getOperand() {
- if (this.operand == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.operand == null) {
- preLazyInit();
- this.operand= new SimpleName(this.ast);
- postLazyInit(this.operand, OPERAND_PROPERTY);
- }
- }
- }
- return this.operand;
- }
-
- /**
- * Sets the operand of this prefix expression.
- *
- * @param expression the operand expression node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setOperand(Expression expression) {
- if (expression == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.operand;
- preReplaceChild(oldChild, expression, OPERAND_PROPERTY);
- this.operand = expression;
- postReplaceChild(oldChild, expression, OPERAND_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- // treat Operator as free
- return BASE_NODE_SIZE + 2 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.operand == null ? 0 : getOperand().treeSize());
- }
-}
-
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
deleted file mode 100644
index 6ea45f14..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/PrimitiveType.java
+++ /dev/null
@@ -1,316 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Primitive type nodes.
- * <pre>
- * PrimitiveType:
- * <b>byte</b>
- * <b>short</b>
- * <b>char</b>
- * <b>int</b>
- * <b>long</b>
- * <b>float</b>
- * <b>double</b>
- * <b>boolean</b>
- * <b>void</b>
- * </pre>
- * <p>
- * Note that due to the fact that AST nodes belong to a specific AST and
- * have a specific parent, there needs to multiple instances of these
- * nodes.
- * </p>
- *
- * 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 PrimitiveType extends Type {
-
- /**
- * Primitive type codes (typesafe enumeration).
- * <pre>
- * <b>byte</b> BYTE
- * <b>short</b> SHORT
- * <b>char</b> CHAR
- * <b>int</b> INT
- * <b>long</b> LONG
- * <b>float</b> FLOAT
- * <b>double</b> DOUBLE
- * <b>boolean</b> BOOLEAN
- * <b>void</b> VOID
- * </pre>
- */
- public static class Code {
-
- /**
- * The name of the type.
- */
- private String name;
-
- /**
- * Creates a new primitive type code with the given name.
- * <p>
- * Note: this constructor is package-private. The only instances
- * ever created are the ones for the standard primitive types.
- * </p>
- *
- * @param name the standard name of the primitive type
- */
- Code(String name) {
- this.name = name;
- }
-
- /**
- * Returns the standard name of the primitive type.
- *
- * @return the standard name of the primitive type
- */
- public String toString() {
- return name;
- }
- }
-
- /** Type code for the primitive type "int". */
- public static final Code INT = new Code("int");//$NON-NLS-1$
- /** Type code for the primitive type "char". */
- public static final Code CHAR = new Code("char");//$NON-NLS-1$
- /** Type code for the primitive type "boolean". */
- public static final Code BOOLEAN = new Code("boolean");//$NON-NLS-1$
- /** Type code for the primitive type "short". */
- public static final Code SHORT = new Code("short");//$NON-NLS-1$
- /** Type code for the primitive type "long". */
- public static final Code LONG = new Code("long");//$NON-NLS-1$
- /** Type code for the primitive type "float". */
- public static final Code FLOAT = new Code("float");//$NON-NLS-1$
- /** Type code for the primitive type "double". */
- public static final Code DOUBLE = new Code("double");//$NON-NLS-1$
- /** Type code for the primitive type "byte". */
- public static final Code BYTE = new Code("byte");//$NON-NLS-1$
- /** Type code for the primitive type "any". */
- public static final Code ANY_CODE = new Code("any");//$NON-NLS-1$
-
- /** Type code for the primitive type "void". Note that "void" is
- * special in that its only legitimate uses are as a method return
- * type and as a type literal.
- */
- public static final Code VOID = new Code("void");//$NON-NLS-1$
-
- /**
- * The primitive type code; one of the PrimitiveType constants; default
- * is int.
- */
- private PrimitiveType.Code typeCode = INT;
-
- /**
- * Map from token to primitive type code (key type: <code>String</code>;
- * value type: <code>PrimitiveType.Code</code>).
- */
- private static final Map CODES;
- static {
- CODES = new HashMap(20);
- Code[] ops = {
- INT,
- BYTE,
- CHAR,
- BOOLEAN,
- SHORT,
- LONG,
- FLOAT,
- DOUBLE,
- VOID,
- ANY_CODE,
- };
- for (int i = 0; i < ops.length; i++) {
- CODES.put(ops[i].toString(), ops[i]);
- }
- }
-
- /**
- * Returns the primitive type code corresponding to the given string,
- * or <code>null</code> if none.
- * <p>
- * <code>toCode</code> is the converse of <code>toString</code>:
- * that is,
- * <code>PrimitiveType.Code.toCode(code.toString()) == code</code>
- * for all type code <code>code</code>.
- * </p>
- *
- * @param token the standard name of the primitive type
- * @return the primitive type code, or <code>null</code> if none
- */
- public static PrimitiveType.Code toCode(String token) {
- return (PrimitiveType.Code) CODES.get(token);
- }
-
- /**
- * The "primitiveTypeCode" structural property of this node type.
- *
- */
- public static final SimplePropertyDescriptor PRIMITIVE_TYPE_CODE_PROPERTY =
- new SimplePropertyDescriptor(PrimitiveType.class, "primitiveTypeCode", PrimitiveType.Code.class, MANDATORY); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List propertyList = new ArrayList(2);
- createPropertyList(PrimitiveType.class, propertyList);
- addProperty(PRIMITIVE_TYPE_CODE_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
-
- public static PrimitiveType createAnyType(AST ast)
- {
- PrimitiveType type = new PrimitiveType(ast);
- type.setPrimitiveTypeCode(ANY_CODE);
- return type;
- }
-
-
- /**
- * Creates a new unparented node for a primitive type owned by the given
- * AST. By default, the node has type "int".
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- PrimitiveType(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final Object internalGetSetObjectProperty(SimplePropertyDescriptor property, boolean get, Object value) {
- if (property == PRIMITIVE_TYPE_CODE_PROPERTY) {
- if (get) {
- return getPrimitiveTypeCode();
- } else {
- setPrimitiveTypeCode((Code) value);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetObjectProperty(property, get, value);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return PRIMITIVE_TYPE;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- PrimitiveType result = new PrimitiveType(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setPrimitiveTypeCode(getPrimitiveTypeCode());
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- visitor.visit(this);
- visitor.endVisit(this);
- }
-
- /**
- * Returns the primitive type code.
- *
- * @return one of the primitive type code constants declared in this
- * class
- */
- public PrimitiveType.Code getPrimitiveTypeCode() {
- return this.typeCode;
- }
-
- /**
- * Sets the primitive type code.
- *
- * @param typeCode one of the primitive type code constants declared in
- * this class
- * @exception IllegalArgumentException if the argument is incorrect
- */
- public void setPrimitiveTypeCode(PrimitiveType.Code typeCode) {
- if (typeCode == null) {
- throw new IllegalArgumentException();
- }
- preValueChange(PRIMITIVE_TYPE_CODE_PROPERTY);
- this.typeCode = typeCode;
- postValueChange(PRIMITIVE_TYPE_CODE_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- // treat Code as free
- return BASE_NODE_SIZE + 1 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return memSize();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ProgramElement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ProgramElement.java
deleted file mode 100644
index 299c7718..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ProgramElement.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.dom;
-
-
-/**
- *
- * 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 ProgramElement extends ASTNode {
-
- ProgramElement(AST ast) {
- super(ast);
- }
-
-}
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
deleted file mode 100644
index 10e95eb3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/QualifiedName.java
+++ /dev/null
@@ -1,284 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-
-/**
- * AST node for a qualified name. A qualified name is defined recursively
- * as a simple name preceded by a name, which qualifies it. Expressing it this
- * way means that the qualifier and the simple name get their own AST nodes.
- * <pre>
- * QualifiedName:
- * Name <b>.</b> SimpleName
- * </pre>
- * <p>
- * See <code>FieldAccess</code> for guidelines on handling other expressions
- * that resemble qualified names.
- * </p>
- *
- * @see FieldAccess
- *
- * 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 QualifiedName extends Name {
-
- /**
- * The "qualifier" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor QUALIFIER_PROPERTY =
- new ChildPropertyDescriptor(QualifiedName.class, "qualifier", Name.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "name" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor NAME_PROPERTY =
- new ChildPropertyDescriptor(QualifiedName.class, "name", SimpleName.class, MANDATORY, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List propertyList = new ArrayList(3);
- createPropertyList(QualifiedName.class, propertyList);
- addProperty(QUALIFIER_PROPERTY, propertyList);
- addProperty(NAME_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The identifier; lazily initialized; defaults to a unspecified, legal
- * JavaScript identifier.
- */
- private Name qualifier = null;
-
- /**
- * The name being qualified; lazily initialized; defaults to a unspecified,
- * legal JavaScript identifier.
- */
- private SimpleName name = null;
-
- /**
- * Creates a new AST node for a qualified name owned by the given AST.
- * <p>
- * N.B. This constructor is package-private; all subclasses must be
- * declared in the same package; clients are unable to declare
- * additional subclasses.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- QualifiedName(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == QUALIFIER_PROPERTY) {
- if (get) {
- return getQualifier();
- } else {
- setQualifier((Name) child);
- return null;
- }
- }
- if (property == NAME_PROPERTY) {
- if (get) {
- return getName();
- } else {
- setName((SimpleName) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return QUALIFIED_NAME;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- QualifiedName result = new QualifiedName(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setQualifier((Name) getQualifier().clone(target));
- result.setName((SimpleName) getName().clone(target));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChild(visitor, getQualifier());
- acceptChild(visitor, getName());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the qualifier part of this qualified name.
- *
- * @return the qualifier part of this qualified name
- */
- public Name getQualifier() {
- if (this.qualifier == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.qualifier == null) {
- preLazyInit();
- this.qualifier = new SimpleName(this.ast);
- postLazyInit(this.qualifier, QUALIFIER_PROPERTY);
- }
- }
- }
- return this.qualifier;
- }
-
- /**
- * Sets the qualifier of this qualified name to the given name.
- *
- * @param qualifier the qualifier of this qualified name
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setQualifier(Name qualifier) {
- if (qualifier == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.qualifier;
- preReplaceChild(oldChild, qualifier, QUALIFIER_PROPERTY);
- this.qualifier = qualifier;
- postReplaceChild(oldChild, qualifier, QUALIFIER_PROPERTY);
- }
-
- /**
- * Returns the name part of this qualified name.
- *
- * @return the name being qualified
- */
- public SimpleName getName() {
- if (this.name == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.name == null) {
- preLazyInit();
- this.name = new SimpleName(this.ast);
- postLazyInit(this.name, NAME_PROPERTY);
- }
- }
- }
- return this.name;
- }
-
- /**
- * Sets the name part of this qualified name to the given simple name.
- *
- * @param name the identifier of this qualified name
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public void setName(SimpleName name) {
- if (name == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.name;
- preReplaceChild(oldChild, name, NAME_PROPERTY);
- this.name = name;
- postReplaceChild(oldChild, name, NAME_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on Name.
- */
- void appendName(StringBuffer buffer) {
- getQualifier().appendName(buffer);
- buffer.append('.');
- getName().appendName(buffer);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return BASE_NAME_NODE_SIZE + 3 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.name == null ? 0 : getName().treeSize())
- + (this.qualifier == null ? 0 : getQualifier().treeSize());
- }
-}
-
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
deleted file mode 100644
index c6dbe53e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/QualifiedType.java
+++ /dev/null
@@ -1,288 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Type node for a qualified type (added in JLS3 API).
- * <pre>
- * QualifiedType:
- * Type <b>.</b> SimpleName
- * </pre>
- * <p>
- * Not all node arragements will represent legal JavaScript constructs. In particular,
- * it is nonsense if the type is an array type or primitive type. The normal use
- * is when the type is a simple or parameterized type.
- * </p>
- * <p>
- * A type like "A.B" can be represented either of two ways:
- * <ol>
- * <li>
- * <code>QualifiedType(SimpleType(SimpleName("A")),SimpleName("B"))</code>
- * </li>
- * <li>
- * <code>SimpleType(QualifiedName(SimpleName("A"),SimpleName("B")))</code>
- * </li>
- * </ol>
- * The first form is preferred when "A" is known to be a type. However, a
- * parser cannot always determine this. Clients should be prepared to handle
- * either rather than make assumptions. (Note also that the first form
- * became possible as of JLS3; only the second form existed in JLS2 API.)
- * </p>
- *
- *
- * 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 QualifiedType extends Type {
- /**
- * This index represents the position inside a parameterized qualified type.
- */
- int index;
-
- /**
- * The "qualifier" structural property of this node type.
- */
- public static final ChildPropertyDescriptor QUALIFIER_PROPERTY =
- new ChildPropertyDescriptor(QualifiedType.class, "qualifier", Type.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "name" structural property of this node type.
- */
- public static final ChildPropertyDescriptor NAME_PROPERTY =
- new ChildPropertyDescriptor(QualifiedType.class, "name", SimpleName.class, MANDATORY, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List propertyList = new ArrayList(3);
- createPropertyList(QualifiedType.class, propertyList);
- addProperty(QUALIFIER_PROPERTY, propertyList);
- addProperty(NAME_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The type node; lazily initialized; defaults to a type with
- * an unspecfied, but legal, simple name.
- */
- private Type qualifier = null;
-
- /**
- * The name being qualified; lazily initialized; defaults to a unspecified,
- * legal JavaScript identifier.
- */
- private SimpleName name = null;
-
- /**
- * Creates a new unparented node for a qualified type owned by the
- * given AST. By default, an unspecified, but legal, qualifier and name.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- QualifiedType(AST ast) {
- super(ast);
- unsupportedIn2();
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == QUALIFIER_PROPERTY) {
- if (get) {
- return getQualifier();
- } else {
- setQualifier((Type) child);
- return null;
- }
- }
- if (property == NAME_PROPERTY) {
- if (get) {
- return getName();
- } else {
- setName((SimpleName) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return QUALIFIED_TYPE;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- QualifiedType result = new QualifiedType(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setQualifier((Type) ((ASTNode) getQualifier()).clone(target));
- result.setName((SimpleName) ((ASTNode) getName()).clone(target));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChild(visitor, getQualifier());
- acceptChild(visitor, getName());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the qualifier of this qualified type.
- *
- * @return the qualifier of this qualified type
- */
- public Type getQualifier() {
- if (this.qualifier == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.qualifier == null) {
- preLazyInit();
- this.qualifier = new SimpleType(this.ast);
- postLazyInit(this.qualifier, QUALIFIER_PROPERTY);
- }
- }
- }
- return this.qualifier;
- }
-
- /**
- * Sets the qualifier of this qualified type to the given type.
- *
- * @param type the new qualifier of this qualified type
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public void setQualifier(Type type) {
- if (type == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.qualifier;
- preReplaceChild(oldChild, type, QUALIFIER_PROPERTY);
- this.qualifier = type;
- postReplaceChild(oldChild, type, QUALIFIER_PROPERTY);
- }
-
- /**
- * Returns the name part of this qualified type.
- *
- * @return the name being qualified
- */
- public SimpleName getName() {
- if (this.name == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.name == null) {
- preLazyInit();
- this.name = new SimpleName(this.ast);
- postLazyInit(this.name, NAME_PROPERTY);
- }
- }
- }
- return this.name;
- }
-
- /**
- * Sets the name part of this qualified type to the given simple name.
- *
- * @param name the identifier of this qualified name
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public void setName(SimpleName name) {
- if (name == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.name;
- preReplaceChild(oldChild, name, NAME_PROPERTY);
- this.name = name;
- postReplaceChild(oldChild, name, NAME_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- // treat Code as free
- return BASE_NODE_SIZE + 3 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.qualifier == null ? 0 : getQualifier().treeSize())
- + (this.name == null ? 0 : getName().treeSize());
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/RecoveredTypeBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/RecoveredTypeBinding.java
deleted file mode 100644
index 36134a91..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/RecoveredTypeBinding.java
+++ /dev/null
@@ -1,580 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.dom;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ArrayBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.CompilationUnitScope;
-import org.eclipse.wst.jsdt.internal.compiler.util.Util;
-import org.eclipse.wst.jsdt.internal.core.CompilationUnit;
-
-/**
- * This class represents the recovered binding for a 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.
- */
-class RecoveredTypeBinding implements ITypeBinding {
-
- private VariableDeclaration variableDeclaration;
- private Type currentType;
- private BindingResolver resolver;
- private int dimensions;
- private RecoveredTypeBinding innerTypeBinding;
- private ITypeBinding[] typeArguments;
- private org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding referenceBinding;
-
- RecoveredTypeBinding(BindingResolver resolver, VariableDeclaration variableDeclaration) {
- this.variableDeclaration = variableDeclaration;
- this.resolver = resolver;
- this.currentType = getType();
- this.dimensions = variableDeclaration.getExtraDimensions();
- if (this.currentType.isArrayType()) {
- this.dimensions += ((ArrayType) this.currentType).getDimensions();
- }
- }
-
- RecoveredTypeBinding(BindingResolver resolver, org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding referenceBinding) {
- this.resolver = resolver;
- this.dimensions = referenceBinding.dimensions();
- this.referenceBinding = referenceBinding;
- }
-
- RecoveredTypeBinding(BindingResolver resolver, Type type) {
- this.currentType = type;
- this.resolver = resolver;
- this.dimensions = 0;
- if (type.isArrayType()) {
- this.dimensions += ((ArrayType) type).getDimensions();
- }
- }
-
- RecoveredTypeBinding(BindingResolver resolver, RecoveredTypeBinding typeBinding, int dimensions) {
- this.innerTypeBinding = typeBinding;
- this.dimensions = typeBinding.getDimensions() + dimensions;
- this.resolver = resolver;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#createArrayType(int)
- */
- public ITypeBinding createArrayType(int dims) {
- return this.resolver.getTypeBinding(this, dims);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#getBinaryName()
- */
- public String getBinaryName() {
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#getBound()
- */
- public ITypeBinding getBound() {
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#getComponentType()
- */
- public ITypeBinding getComponentType() {
- if (this.dimensions == 0) return null;
- return this.resolver.getTypeBinding(this, -1);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#getDeclaredFields()
- */
- public IVariableBinding[] getDeclaredFields() {
- return TypeBinding.NO_VARIABLE_BINDINGS;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#getDeclaredMethods()
- */
- public IFunctionBinding[] getDeclaredMethods() {
- return TypeBinding.NO_METHOD_BINDINGS;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#getDeclaredModifiers()
- */
- public int getDeclaredModifiers() {
- return 0;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#getDeclaredTypes()
- */
- public ITypeBinding[] getDeclaredTypes() {
- return TypeBinding.NO_TYPE_BINDINGS;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#getDeclaringClass()
- */
- public ITypeBinding getDeclaringClass() {
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#getDeclaringMethod()
- */
- public IFunctionBinding getDeclaringMethod() {
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#getDimensions()
- */
- public int getDimensions() {
- return this.dimensions;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#getElementType()
- */
- public ITypeBinding getElementType() {
- if (this.referenceBinding != null) {
- if (this.referenceBinding.isArrayType()) {
- ArrayBinding arrayBinding = (ArrayBinding) this.referenceBinding;
- return new RecoveredTypeBinding(this.resolver, arrayBinding.leafComponentType);
- } else {
- return new RecoveredTypeBinding(this.resolver, this.referenceBinding);
- }
- }
- if (this.innerTypeBinding != null) {
- return this.innerTypeBinding.getElementType();
- }
- if (this.currentType!= null && this.currentType.isArrayType()) {
- return this.resolver.getTypeBinding(((ArrayType) this.currentType).getElementType());
- }
- if (this.variableDeclaration != null && this.variableDeclaration.getExtraDimensions() != 0) {
- return this.resolver.getTypeBinding(getType());
- }
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#getErasure()
- */
- public ITypeBinding getErasure() {
- return this;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#getInterfaces()
- */
- public ITypeBinding[] getInterfaces() {
- return TypeBinding.NO_TYPE_BINDINGS;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#getModifiers()
- */
- public int getModifiers() {
- return Modifier.NONE;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#getName()
- */
- public String getName() {
- char[] brackets = new char[this.dimensions * 2];
- for (int i = this.dimensions * 2 - 1; i >= 0; i -= 2) {
- brackets[i] = ']';
- brackets[i - 1] = '[';
- }
- StringBuffer buffer = new StringBuffer(this.getInternalName());
- buffer.append(brackets);
- return String.valueOf(buffer);
- }
-
- private String getInternalName() {
- if (this.innerTypeBinding != null) {
- return this.innerTypeBinding.getInternalName();
- } else if (this.referenceBinding != null) {
- org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding typeBinding = null;
- if (this.referenceBinding.isArrayType()) {
- ArrayBinding arrayBinding = (ArrayBinding) this.referenceBinding;
- if (arrayBinding.leafComponentType instanceof org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding) {
- typeBinding = (org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding) arrayBinding.leafComponentType;
- }
- } else if (this.referenceBinding instanceof org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding) {
- typeBinding = (org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding) this.referenceBinding;
- }
- return new String(typeBinding.compoundName[typeBinding.compoundName.length - 1]);
- }
- return this.getTypeNameFrom(getType());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#getPackage()
- */
- public IPackageBinding getPackage() {
- CompilationUnitScope scope = this.resolver.scope();
- if (scope != null) {
- return this.resolver.getPackageBinding(scope.getCurrentPackage());
- }
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#getQualifiedName()
- */
- public String getQualifiedName() {
- return this.getName();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#getSuperclass()
- */
- public ITypeBinding getSuperclass() {
- return this.resolver.resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#getTypeArguments()
- */
- public ITypeBinding[] getTypeArguments() {
- if (this.referenceBinding != null) {
- return this.typeArguments = TypeBinding.NO_TYPE_BINDINGS;
- }
- if (this.typeArguments != null) {
- return typeArguments;
- }
-
- if (this.innerTypeBinding != null) {
- return this.innerTypeBinding.getTypeArguments();
- }
-
- return this.typeArguments = TypeBinding.NO_TYPE_BINDINGS;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#getTypeBounds()
- */
- public ITypeBinding[] getTypeBounds() {
- return TypeBinding.NO_TYPE_BINDINGS;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#getTypeDeclaration()
- */
- public ITypeBinding getTypeDeclaration() {
- return this;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#getTypeParameters()
- */
- public ITypeBinding[] getTypeParameters() {
- return TypeBinding.NO_TYPE_BINDINGS;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#isAnnotation()
- */
- public boolean isAnnotation() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#isAnonymous()
- */
- public boolean isAnonymous() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#isArray()
- */
- public boolean isArray() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#isAssignmentCompatible(org.eclipse.wst.jsdt.core.dom.ITypeBinding)
- */
- public boolean isAssignmentCompatible(ITypeBinding typeBinding) {
- if ("java.lang.Object".equals(typeBinding.getQualifiedName())) { //$NON-NLS-1$
- return true;
- }
- // since recovered binding are not unique isEqualTo is required
- return this.isEqualTo(typeBinding);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#isCapture()
- */
- public boolean isCapture() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#isCastCompatible(org.eclipse.wst.jsdt.core.dom.ITypeBinding)
- */
- public boolean isCastCompatible(ITypeBinding typeBinding) {
- if ("java.lang.Object".equals(typeBinding.getQualifiedName())) { //$NON-NLS-1$
- return true;
- }
- // since recovered binding are not unique isEqualTo is required
- return this.isEqualTo(typeBinding);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#isClass()
- */
- public boolean isClass() {
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#isEnum()
- */
- public boolean isEnum() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#isFromSource()
- */
- public boolean isFromSource() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#isGenericType()
- */
- public boolean isGenericType() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#isInterface()
- */
- public boolean isInterface() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#isLocal()
- */
- public boolean isLocal() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#isMember()
- */
- public boolean isMember() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#isNested()
- */
- public boolean isNested() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#isNullType()
- */
- public boolean isNullType() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#isPrimitive()
- */
- public boolean isPrimitive() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#isRawType()
- */
- public boolean isRawType() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#isSubTypeCompatible(org.eclipse.wst.jsdt.core.dom.ITypeBinding)
- */
- public boolean isSubTypeCompatible(ITypeBinding typeBinding) {
- if ("java.lang.Object".equals(typeBinding.getQualifiedName())) { //$NON-NLS-1$
- return true;
- }
- // since recovered binding are not unique isEqualTo is required
- return this.isEqualTo(typeBinding);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#isTopLevel()
- */
- public boolean isTopLevel() {
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#isTypeVariable()
- */
- public boolean isTypeVariable() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#isUpperbound()
- */
- public boolean isUpperbound() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.IBinding#getJavaElement()
- */
- public IJavaScriptElement getJavaElement() {
- try {
- return new CompilationUnit(null, this.getInternalName(), this.resolver.getWorkingCopyOwner()).getWorkingCopy(this.resolver.getWorkingCopyOwner(), null);
- } catch (JavaScriptModelException e) {
- //ignore
- }
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.IBinding#getKey()
- */
- public String getKey() {
- StringBuffer buffer = new StringBuffer();
- buffer.append("Recovered#"); //$NON-NLS-1$
- if (this.innerTypeBinding != null) {
- buffer.append("innerTypeBinding") //$NON-NLS-1$
- .append(this.innerTypeBinding.getKey());
- } else if (this.currentType != null) {
- buffer.append("currentType") //$NON-NLS-1$
- .append(this.currentType.toString());
- } else if (this.referenceBinding != null) {
- buffer.append("referenceBinding") //$NON-NLS-1$
- .append(this.referenceBinding.computeUniqueKey());
- } else if (variableDeclaration != null) {
- buffer
- .append("variableDeclaration") //$NON-NLS-1$
- .append(this.variableDeclaration.getClass())
- .append(this.variableDeclaration.getName().getIdentifier())
- .append(this.variableDeclaration.getExtraDimensions());
- }
- buffer.append(this.getDimensions());
- if (this.typeArguments != null) {
- buffer.append('<');
- for (int i = 0, max = this.typeArguments.length; i < max; i++) {
- if (i != 0) {
- buffer.append(',');
- }
- buffer.append(this.typeArguments[i].getKey());
- }
- buffer.append('>');
- }
- return String.valueOf(buffer);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.IBinding#getKind()
- */
- public int getKind() {
- return IBinding.TYPE;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.IBinding#isDeprecated()
- */
- public boolean isDeprecated() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.IBinding#isEqualTo(org.eclipse.wst.jsdt.core.dom.IBinding)
- */
- public boolean isEqualTo(IBinding other) {
- if (!other.isRecovered() || other.getKind() != IBinding.TYPE) return false;
- return this.getKey().equals(other.getKey());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.IBinding#isRecovered()
- */
- public boolean isRecovered() {
- return true;
- }
-
- private String getTypeNameFrom(Type type) {
- if (type == null) return Util.EMPTY_STRING;
- switch(type.getNodeType0()) {
- case ASTNode.ARRAY_TYPE :
- ArrayType arrayType = (ArrayType) type;
- type = arrayType.getElementType();
- return getTypeNameFrom(type);
- case ASTNode.PRIMITIVE_TYPE :
- PrimitiveType primitiveType = (PrimitiveType) type;
- return primitiveType.getPrimitiveTypeCode().toString();
- case ASTNode.QUALIFIED_TYPE :
- QualifiedType qualifiedType = (QualifiedType) type;
- return qualifiedType.getName().getIdentifier();
- case ASTNode.SIMPLE_TYPE :
- SimpleType simpleType = (SimpleType) type;
- Name name = simpleType.getName();
- if (name.isQualifiedName()) {
- QualifiedName qualifiedName = (QualifiedName) name;
- return qualifiedName.getName().getIdentifier();
- }
- return ((SimpleName) name).getIdentifier();
- }
- return Util.EMPTY_STRING;
- }
-
- private Type getType() {
- if (this.currentType != null) {
- return this.currentType;
- }
- if (this.variableDeclaration == null) return null;
- switch(this.variableDeclaration.getNodeType()) {
- case ASTNode.SINGLE_VARIABLE_DECLARATION :
- SingleVariableDeclaration singleVariableDeclaration = (SingleVariableDeclaration) this.variableDeclaration;
- return singleVariableDeclaration.getType();
- default :
- // this is a variable declaration fragment
- ASTNode parent = this.variableDeclaration.getParent();
- switch(parent.getNodeType()) {
- case ASTNode.VARIABLE_DECLARATION_EXPRESSION :
- VariableDeclarationExpression variableDeclarationExpression = (VariableDeclarationExpression) parent;
- return variableDeclarationExpression.getType();
- case ASTNode.VARIABLE_DECLARATION_STATEMENT :
- VariableDeclarationStatement statement = (VariableDeclarationStatement) parent;
- return statement.getType();
- case ASTNode.FIELD_DECLARATION :
- FieldDeclaration fieldDeclaration = (FieldDeclaration) parent;
- return fieldDeclaration.getType();
- }
- }
- return null; // should not happen
- }
-
- public boolean isCompilationUnit() {
- return false;
- }
-}
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
deleted file mode 100644
index 30abdd67..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/RecoveredVariableBinding.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.dom;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-
-/**
- * This class represents the recovered binding for a variable
- *
- * 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.
- */
-class RecoveredVariableBinding implements IVariableBinding {
-
- private VariableDeclaration variableDeclaration;
- private BindingResolver resolver;
-
- RecoveredVariableBinding(BindingResolver resolver, VariableDeclaration variableDeclaration) {
- this.resolver = resolver;
- this.variableDeclaration = variableDeclaration;
- }
- public Object getConstantValue() {
- return null;
- }
-
- public ITypeBinding getDeclaringClass() {
- ASTNode parent = this.variableDeclaration.getParent();
- while (parent != null && parent.getNodeType() != ASTNode.TYPE_DECLARATION) {
- parent = parent.getParent();
- }
- if (parent != null) {
- return ((TypeDeclaration) parent).resolveBinding();
- }
- return null;
- }
-
- public IFunctionBinding getDeclaringMethod() {
- ASTNode parent = this.variableDeclaration.getParent();
- while (parent != null && parent.getNodeType() != ASTNode.FUNCTION_DECLARATION) {
- parent = parent.getParent();
- }
- if (parent != null) {
- return ((FunctionDeclaration) parent).resolveBinding();
- }
- return null;
- }
-
- public String getName() {
- return this.variableDeclaration.getName().getIdentifier();
- }
-
- public ITypeBinding getType() {
- return this.resolver.getTypeBinding(this.variableDeclaration);
- }
-
- public IVariableBinding getVariableDeclaration() {
- return this;
- }
-
- public int getVariableId() {
- return 0;
- }
-
- public boolean isEnumConstant() {
- return false;
- }
-
- public boolean isField() {
- return this.variableDeclaration.getParent() instanceof FieldDeclaration;
- }
-
- public boolean isParameter() {
- return this.variableDeclaration instanceof SingleVariableDeclaration;
- }
-
- public IJavaScriptElement getJavaElement() {
- return null;
- }
-
- public String getKey() {
- StringBuffer buffer = new StringBuffer();
- buffer.append("Recovered#"); //$NON-NLS-1$
- if (variableDeclaration != null) {
- buffer
- .append("variableDeclaration") //$NON-NLS-1$
-// .append(this.variableDeclaration.getClass())
- .append(this.variableDeclaration.getName().getIdentifier())
- .append(this.variableDeclaration.getExtraDimensions());
- }
- return String.valueOf(buffer);
- }
-
- public int getKind() {
- return IBinding.VARIABLE;
- }
-
- public int getModifiers() {
- return 0;
- }
-
- public boolean isDeprecated() {
- return false;
- }
-
- public boolean isEqualTo(IBinding binding) {
- if (binding.isRecovered() && binding.getKind() == IBinding.VARIABLE) {
- return this.getKey().equals(binding.getKey());
- }
- return false;
- }
-
- public boolean isRecovered() {
- return true;
- }
-
- public boolean isGlobal() {
- // TODO Auto-generated method stub
- return false;
- }
-}
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
deleted file mode 100644
index 064fd9d2..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/RegularExpressionLiteral.java
+++ /dev/null
@@ -1,213 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.internal.compiler.parser.Scanner;
-import org.eclipse.wst.jsdt.internal.compiler.parser.TerminalTokens;
-
-/**
- *
- * 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 RegularExpressionLiteral extends Expression {
-
- /**
- * The "escapedValue" structural property of this node type.
- *
- */
- public static final SimplePropertyDescriptor REGULAR_EXPRESSION_PROPERTY =
- new SimplePropertyDescriptor(RegularExpressionLiteral.class, "regularExpression", String.class, MANDATORY); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List properyList = new ArrayList(2);
- createPropertyList(RegularExpressionLiteral.class, properyList);
- addProperty(REGULAR_EXPRESSION_PROPERTY, properyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
- // includes '/'
- private String regularExpression = "/&/g";//$NON-NLS-1$
-
- /**
- * Creates a new unparented character literal node owned by the given AST.
- * By default, the character literal denotes an unspecified character.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- RegularExpressionLiteral(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final Object internalGetSetObjectProperty(SimplePropertyDescriptor property, boolean get, Object value) {
- if (property == REGULAR_EXPRESSION_PROPERTY) {
- if (get) {
- return getRegularExpression();
- } else {
- setRegularExpression((String) value);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetObjectProperty(property, get, value);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return REGULAR_EXPRESSION_LITERAL;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- RegularExpressionLiteral result = new RegularExpressionLiteral(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setRegularExpression(getRegularExpression());
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- visitor.visit(this);
- visitor.endVisit(this);
- }
-
- /**
- * Returns the string value of this literal node. The value is the sequence
- * of characters that would appear in the source program, including
- * enclosing single quotes and embedded escapes.
- *
- * @return the escaped string value, including enclosing single quotes
- * and embedded escapes
- */
- public String getRegularExpression() {
- return this.regularExpression;
- }
-
- /**
- * Sets the string value of this literal node. The value is the sequence
- * of characters that would appear in the source program, including
- * enclosing single quotes and embedded escapes. For example,
- * <ul>
- * <li><code>'a'</code> <code>setEscapedValue("\'a\'")</code></li>
- * <li><code>'\n'</code> <code>setEscapedValue("\'\\n\'")</code></li>
- * </ul>
- *
- * @param value the string value, including enclosing single quotes
- * and embedded escapes
- * @exception IllegalArgumentException if the argument is incorrect
- */
- public void setRegularExpression(String value) {
- // check setInternalEscapedValue(String) if this method is changed
- if (value == null) {
- throw new IllegalArgumentException();
- }
- Scanner scanner = this.ast.scanner;
- char[] source = value.toCharArray();
- scanner.setSource(source);
- scanner.resetTo(0, source.length);
- try {
- int tokenType = scanner.getNextToken();
- switch(tokenType) {
- case TerminalTokens.TokenNameRegExLiteral:
- break;
- default:
- throw new IllegalArgumentException();
- }
- } catch(InvalidInputException e) {
- throw new IllegalArgumentException();
- }
- preValueChange(REGULAR_EXPRESSION_PROPERTY);
- this.regularExpression = value;
- postValueChange(REGULAR_EXPRESSION_PROPERTY);
- }
-
-
- /* (omit javadoc for this method)
- * This method is a copy of setEscapedValue(String) that doesn't do any validation.
- */
- void internalSetRegularExpression(String value) {
- preValueChange(REGULAR_EXPRESSION_PROPERTY);
- this.regularExpression = value;
- postValueChange(REGULAR_EXPRESSION_PROPERTY);
- }
-
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- int size = BASE_NODE_SIZE + 1 * 4 + stringSize(regularExpression);
- return size;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return memSize();
- }
-}
-
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
deleted file mode 100644
index 69442a1f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ReturnStatement.java
+++ /dev/null
@@ -1,189 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Return statement AST node type.
- *
- * <pre>
- * ReturnStatement:
- * <b>return</b> [ Expression ] <b>;</b>
- * </pre>
- *
- *
- * 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 ReturnStatement extends Statement {
-
- /**
- * The "expression" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor EXPRESSION_PROPERTY =
- new ChildPropertyDescriptor(ReturnStatement.class, "expression", Expression.class, OPTIONAL, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List propertyList = new ArrayList(2);
- createPropertyList(ReturnStatement.class, propertyList);
- addProperty(EXPRESSION_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The expression; <code>null</code> for none; defaults to none.
- */
- private Expression optionalExpression = null;
-
- /**
- * Creates a new AST node for a return statement owned by the
- * given AST. By default, the statement has no expression.
- *
- * @param ast the AST that is to own this node
- */
- ReturnStatement(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == EXPRESSION_PROPERTY) {
- if (get) {
- return getExpression();
- } else {
- setExpression((Expression) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return RETURN_STATEMENT;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- ReturnStatement result = new ReturnStatement(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.copyLeadingComment(this);
- result.setExpression(
- (Expression) ASTNode.copySubtree(target, getExpression()));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- acceptChild(visitor, getExpression());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the expression of this return statement, or
- * <code>null</code> if there is none.
- *
- * @return the expression node, or <code>null</code> if there is none
- */
- public Expression getExpression() {
- return this.optionalExpression;
- }
-
- /**
- * Sets or clears the expression of this return statement.
- *
- * @param expression the expression node, or <code>null</code> if
- * there is none
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setExpression(Expression expression) {
- ASTNode oldChild = this.optionalExpression;
- preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY);
- this.optionalExpression = expression;
- postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return super.memSize() + 1 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.optionalExpression == null ? 0 : getExpression().treeSize());
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SimpleName.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SimpleName.java
deleted file mode 100644
index 9babc645..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SimpleName.java
+++ /dev/null
@@ -1,292 +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.core.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.internal.compiler.parser.Scanner;
-import org.eclipse.wst.jsdt.internal.compiler.parser.TerminalTokens;
-
-/**
- * AST node for a simple name. A simple name is an identifier other than
- * a keyword, boolean literal ("true", "false") or null literal ("null").
- * <pre>
- * SimpleName:
- * Identifier
- * </pre>
- *
- * 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 SimpleName extends Name {
-
- /**
- * The "identifier" structural property of this node type.
- *
- *
- */
- public static final SimplePropertyDescriptor IDENTIFIER_PROPERTY =
- new SimplePropertyDescriptor(SimpleName.class, "identifier", String.class, MANDATORY); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List propertyList = new ArrayList(2);
- createPropertyList(SimpleName.class, propertyList);
- addProperty(IDENTIFIER_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the AST.JLS* constants
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * An unspecified (but externally observable) legal JavaScript identifier.
- */
- private static final String MISSING_IDENTIFIER = "MISSING";//$NON-NLS-1$
-
- /**
- * The identifier; defaults to a unspecified, legal JavaScript identifier.
- */
- private String identifier = MISSING_IDENTIFIER;
-
- /**
- * Creates a new AST node for a simple name owned by the given AST.
- * The new node has an unspecified, legal JavaScript identifier.
- * <p>
- * N.B. This constructor is package-private; all subclasses must be
- * declared in the same package; clients are unable to declare
- * additional subclasses.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- SimpleName(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- *
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final Object internalGetSetObjectProperty(SimplePropertyDescriptor property, boolean get, Object value) {
- if (property == IDENTIFIER_PROPERTY) {
- if (get) {
- return getIdentifier();
- } else {
- setIdentifier((String) value);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetObjectProperty(property, get, value);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return SIMPLE_NAME;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- SimpleName result = new SimpleName(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setIdentifier(getIdentifier());
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- visitor.visit(this);
- visitor.endVisit(this);
- }
-
- /**
- * Returns this node's identifier.
- *
- * @return the identifier of this node
- */
- public String getIdentifier() {
- return this.identifier;
- }
-
- /**
- * Sets the identifier of this node to the given value.
- * The identifier should be legal according to the rules
- * of the JavaScript language. Note that keywords are not legal
- * identifiers.
- * <p>
- * Note that the list of keywords may depend on the version of the
- * language (determined when the AST object was created).
- * </p>
- *
- * @param identifier the identifier of this node
- * @exception IllegalArgumentException if the identifier is invalid
- */
- public void setIdentifier(String identifier) {
- // update internalSetIdentifier if this is changed
- if (identifier == null) {
- throw new IllegalArgumentException();
- }
- Scanner scanner = this.ast.scanner;
- char[] source = identifier.toCharArray();
- scanner.setSource(source);
- final int length = source.length;
- scanner.resetTo(0, length - 1);
- try {
- int tokenType = scanner.scanIdentifier();
- if (tokenType != TerminalTokens.TokenNameIdentifier) {
- throw new IllegalArgumentException();
- }
- if (scanner.currentPosition != length) {
- // this is the case when there is only one identifier see 87849
- throw new IllegalArgumentException();
- }
- } catch(InvalidInputException e) {
- throw new IllegalArgumentException();
- }
- preValueChange(IDENTIFIER_PROPERTY);
- this.identifier = identifier;
- postValueChange(IDENTIFIER_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * This method is a copy of setIdentifier(String) that doesn't do any validation.
- */
- void internalSetIdentifier(String ident) {
- preValueChange(IDENTIFIER_PROPERTY);
- this.identifier = ident;
- postValueChange(IDENTIFIER_PROPERTY);
- }
-
- /**
- * Returns whether this simple name represents a name that is being defined,
- * as opposed to one being referenced. The following positions are considered
- * ones where a name is defined:
- * <ul>
- * <li>The type name in a <code>TypeDeclaration</code> node.</li>
- * <li>The method name in a <code>FunctionDeclaration</code> node
- * providing <code>isConstructor</code> is <code>false</code>.</li>
- * <li>The variable name in any type of <code>VariableDeclaration</code>
- * node.</li>
- * <li>The enum type name in a <code>EnumDeclaration</code> node.</li>
- * <li>The enum constant name in an <code>EnumConstantDeclaration</code>
- * node.</li>
- * <li>The variable name in an <code>EnhancedForStatement</code>
- * node.</li>
- * <li>The type variable name in a <code>TypeParameter</code>
- * node.</li>
- * <li>The type name in an <code>AnnotationTypeDeclaration</code> node.</li>
- * <li>The member name in an <code>AnnotationTypeMemberDeclaration</code> node.</li>
- * </ul>
- * <p>
- * Note that this is a convenience method that simply checks whether
- * this node appears in the declaration position relative to its parent.
- * It always returns <code>false</code> if this node is unparented.
- * </p>
- *
- * @return <code>true</code> if this node declares a name, and
- * <code>false</code> otherwise
- */
- public boolean isDeclaration() {
- StructuralPropertyDescriptor d = getLocationInParent();
- if (d == null) {
- // unparented node
- return false;
- }
- ASTNode parent = getParent();
- if (parent instanceof TypeDeclaration) {
- return (d == TypeDeclaration.NAME_PROPERTY);
- }
- if (parent instanceof FunctionDeclaration) {
- FunctionDeclaration p = (FunctionDeclaration) parent;
- // could be the name of the method or constructor
- return !p.isConstructor() && (d == FunctionDeclaration.NAME_PROPERTY);
- }
- if (parent instanceof SingleVariableDeclaration) {
- return (d == SingleVariableDeclaration.NAME_PROPERTY);
- }
- if (parent instanceof VariableDeclarationFragment) {
- return (d == VariableDeclarationFragment.NAME_PROPERTY);
- }
-
- return false;
- }
-
- /* (omit javadoc for this method)
- * Method declared on Name.
- */
- void appendName(StringBuffer buffer) {
- buffer.append(getIdentifier());
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- int size = BASE_NAME_NODE_SIZE + 2 * 4;
- if (identifier != MISSING_IDENTIFIER) {
- // everything but our missing id costs
- size += stringSize(identifier);
- }
- return size;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return memSize();
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SimplePropertyDescriptor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SimplePropertyDescriptor.java
deleted file mode 100644
index 82790ad9..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SimplePropertyDescriptor.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.dom;
-
-/**
- * Descriptor for a simple property of an AST node.
- * A simple property is one whose value is a
- * primitive type (such as <code>int</code> or <code>boolean</code>)
- * or some simple value type (such as <code>String</code> or
- * <code>InfixExpression.Operator</code>).
- *
- * @see org.eclipse.wst.jsdt.core.dom.ASTNode#getStructuralProperty(StructuralPropertyDescriptor)
- * @see org.eclipse.wst.jsdt.core.dom.ASTNode#setStructuralProperty(StructuralPropertyDescriptor, Object)
- *
- * 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 final class SimplePropertyDescriptor extends StructuralPropertyDescriptor {
-
- /**
- * Value type. For example, for a node type like
- * SingleVariableDeclaration, the modifiers property is int.class
- */
- private final Class valueType;
-
- /**
- * Indicates whether a value is mandatory. A property value is allowed
- * to be <code>null</code> only if it is not mandatory.
- */
- private final boolean mandatory;
-
- /**
- * Creates a new simple property descriptor with the given property id.
- * Note that this constructor is declared package-private so that
- * property descriptors can only be created by the AST
- * implementation.
- *
- * @param nodeClass concrete AST node type that owns this property
- * @param propertyId the property id
- * @param valueType the value type of this property
- * @param mandatory <code>true</code> if the property is mandatory,
- * and <code>false</code> if it is may be <code>null</code>
- */
- SimplePropertyDescriptor(Class nodeClass, String propertyId, Class valueType, boolean mandatory) {
- super(nodeClass, propertyId);
- if (valueType == null || ASTNode.class.isAssignableFrom(valueType)) {
- throw new IllegalArgumentException();
- }
- this.valueType = valueType;
- this.mandatory = mandatory;
- }
-
- /**
- * Returns the value type of this property.
- * <p>
- * For example, for a node type like SingleVariableDeclaration,
- * the "modifiers" property returns <code>int.class</code>.
- * </p>
- *
- * @return the value type of the property
- */
- public Class getValueType() {
- return this.valueType;
- }
-
- /**
- * Returns whether this property is mandatory. A property value
- * is not allowed to be <code>null</code> if it is mandatory.
- *
- * @return <code>true</code> if the property is mandatory,
- * and <code>false</code> if it is may be <code>null</code>
- */
- public boolean isMandatory() {
- return this.mandatory;
- }
-}
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
deleted file mode 100644
index 147bdfef..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SimpleType.java
+++ /dev/null
@@ -1,201 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Type node for a named class type, a named interface type, or a type variable.
- * <p>
- * This kind of node is used to convert a name (<code>Name</code>) into a type
- * (<code>Type</code>) by wrapping it.
- * </p>
- *
- *
- * 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 SimpleType extends Type {
-
- /**
- * The "name" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor NAME_PROPERTY =
- new ChildPropertyDescriptor(SimpleType.class, "name", Name.class, MANDATORY, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List propertyList = new ArrayList(2);
- createPropertyList(SimpleType.class, propertyList);
- addProperty(NAME_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The type name node; lazily initialized; defaults to a type with
- * an unspecfied, but legal, name.
- */
- private Name typeName = null;
-
- /**
- * Creates a new unparented node for a simple type owned by the given AST.
- * By default, an unspecified, but legal, name.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- SimpleType(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == NAME_PROPERTY) {
- if (get) {
- return getName();
- } else {
- setName((Name) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return SIMPLE_TYPE;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- SimpleType result = new SimpleType(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setName((Name) (getName()).clone(target));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- acceptChild(visitor, getName());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the name of this simple type.
- *
- * @return the name of this simple type
- */
- public Name getName() {
- if (this.typeName == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.typeName == null) {
- preLazyInit();
- this.typeName = new SimpleName(this.ast);
- postLazyInit(this.typeName, NAME_PROPERTY);
- }
- }
- }
- return this.typeName;
- }
-
- /**
- * Sets the name of this simple type to the given name.
- *
- * @param typeName the new name of this simple type
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public void setName(Name typeName) {
- if (typeName == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.typeName;
- preReplaceChild(oldChild, typeName, NAME_PROPERTY);
- this.typeName = typeName;
- postReplaceChild(oldChild, typeName, NAME_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- // treat Code as free
- return BASE_NODE_SIZE + 1 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.typeName == null ? 0 : getName().treeSize());
- }
-}
-
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
deleted file mode 100644
index 99e7eceb..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SingleVariableDeclaration.java
+++ /dev/null
@@ -1,641 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-/**
- * Single variable declaration AST node type. Single variable
- * declaration nodes are used in a limited number of places, including formal
- * parameter lists and catch clauses. They are not used for field declarations
- * and regular variable declaration statements.
- * For JLS2:
- * <pre>
- * SingleVariableDeclaration:
- * { Modifier } Type Identifier { <b>[</b><b>]</b> } [ <b>=</b> Expression ]
- * </pre>
- * For JLS3, the modifier flags were replaced by
- * a list of modifier nodes (intermixed with annotations), and the variable arity
- * indicator was added:
- * <pre>
- * SingleVariableDeclaration:
- * { ExtendedModifier } Type [ <b>...</b> ] Identifier { <b>[</b><b>]</b> } [ <b>=</b> Expression ]
- * </pre>
- *
- * 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 SingleVariableDeclaration extends VariableDeclaration {
-
- /**
- * The "modifiers" structural property of this node type (JLS2 API only).
- *
- */
- public static final SimplePropertyDescriptor MODIFIERS_PROPERTY =
- new SimplePropertyDescriptor(SingleVariableDeclaration.class, "modifiers", int.class, MANDATORY); //$NON-NLS-1$
-
- /**
- * The "modifiers" structural property of this node type (added in JLS3 API).
- *
- */
- public static final ChildListPropertyDescriptor MODIFIERS2_PROPERTY =
- new ChildListPropertyDescriptor(SingleVariableDeclaration.class, "modifiers", IExtendedModifier.class, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "name" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor NAME_PROPERTY =
- new ChildPropertyDescriptor(SingleVariableDeclaration.class, "name", SimpleName.class, MANDATORY, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "type" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor TYPE_PROPERTY =
- new ChildPropertyDescriptor(SingleVariableDeclaration.class, "type", Type.class, MANDATORY, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "varargs" structural property of this node type (added in JLS3 API).
- *
- */
- public static final SimplePropertyDescriptor VARARGS_PROPERTY =
- new SimplePropertyDescriptor(SingleVariableDeclaration.class, "varargs", boolean.class, MANDATORY); //$NON-NLS-1$
-
- /**
- * The "extraDimensions" structural property of this node type.
- *
- */
- public static final SimplePropertyDescriptor EXTRA_DIMENSIONS_PROPERTY =
- new SimplePropertyDescriptor(SingleVariableDeclaration.class, "extraDimensions", int.class, MANDATORY); //$NON-NLS-1$
-
- /**
- * The "initializer" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor INITIALIZER_PROPERTY =
- new ChildPropertyDescriptor(SingleVariableDeclaration.class, "initializer", Expression.class, OPTIONAL, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS_2_0;
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS_3_0;
-
- static {
- List propertyList = new ArrayList(6);
- createPropertyList(SingleVariableDeclaration.class, propertyList);
- addProperty(MODIFIERS_PROPERTY, propertyList);
- addProperty(TYPE_PROPERTY, propertyList);
- addProperty(NAME_PROPERTY, propertyList);
- addProperty(EXTRA_DIMENSIONS_PROPERTY, propertyList);
- addProperty(INITIALIZER_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS_2_0 = reapPropertyList(propertyList);
-
- propertyList = new ArrayList(7);
- createPropertyList(SingleVariableDeclaration.class, propertyList);
- addProperty(MODIFIERS2_PROPERTY, propertyList);
- addProperty(TYPE_PROPERTY, propertyList);
- addProperty(VARARGS_PROPERTY, propertyList);
- addProperty(NAME_PROPERTY, propertyList);
- addProperty(EXTRA_DIMENSIONS_PROPERTY, propertyList);
- addProperty(INITIALIZER_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS_3_0 = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- if (apiLevel == AST.JLS2_INTERNAL) {
- return PROPERTY_DESCRIPTORS_2_0;
- } else {
- return PROPERTY_DESCRIPTORS_3_0;
- }
- }
-
- /**
- * The extended modifiers (element type: <code>IExtendedModifier</code>).
- * Null in JLS2. Added in JLS3; defaults to an empty list
- * (see constructor).
- *
- *
- */
- private ASTNode.NodeList modifiers = null;
-
- /**
- * The modifiers; bit-wise or of Modifier flags.
- * Defaults to none. Not used in 3.0.
- */
- private int modifierFlags = Modifier.NONE;
-
- /**
- * The variable name; lazily initialized; defaults to a unspecified,
- * legal JavaScript identifier.
- */
- private SimpleName variableName = null;
-
- /**
- * The type; lazily initialized; defaults to a unspecified,
- * legal type.
- */
- private Type type = null;
-
- /**
- * Indicates the last parameter of a variable arity method;
- * defaults to false.
- *
- *
- */
- private boolean variableArity = false;
-
- /**
- * The number of extra array dimensions that appear after the variable;
- * defaults to 0.
- *
- *
- */
- private int extraArrayDimensions = 0;
-
- /**
- * The initializer expression, or <code>null</code> if none;
- * defaults to none.
- */
- private Expression optionalInitializer = null;
-
- /**
- * Creates a new AST node for a variable declaration owned by the given
- * AST. By default, the variable declaration has: no modifiers, an
- * unspecified (but legal) type, an unspecified (but legal) variable name,
- * 0 dimensions after the variable; no initializer; not variable arity.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- SingleVariableDeclaration(AST ast) {
- super(ast);
- if (ast.apiLevel >= AST.JLS3) {
- this.modifiers = new ASTNode.NodeList(MODIFIERS2_PROPERTY);
- }
- }
-
- /* (omit javadoc for this method)
- * Method declared on VariableDeclaration.
- *
- */
- final SimplePropertyDescriptor internalExtraDimensionsProperty() {
- return EXTRA_DIMENSIONS_PROPERTY;
- }
-
- /* (omit javadoc for this method)
- * Method declared on VariableDeclaration.
- *
- */
- final ChildPropertyDescriptor internalInitializerProperty() {
- return INITIALIZER_PROPERTY;
- }
-
- /* (omit javadoc for this method)
- * Method declared on VariableDeclaration.
- *
- */
- final ChildPropertyDescriptor internalNameProperty() {
- return NAME_PROPERTY;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int internalGetSetIntProperty(SimplePropertyDescriptor property, boolean get, int value) {
- if (property == MODIFIERS_PROPERTY) {
- if (get) {
- return getModifiers();
- } else {
- setModifiers(value);
- return 0;
- }
- }
- if (property == EXTRA_DIMENSIONS_PROPERTY) {
- if (get) {
- return getExtraDimensions();
- } else {
- setExtraDimensions(value);
- return 0;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetIntProperty(property, get, value);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean internalGetSetBooleanProperty(SimplePropertyDescriptor property, boolean get, boolean value) {
- if (property == VARARGS_PROPERTY) {
- if (get) {
- return isVarargs();
- } else {
- setVarargs(value);
- return false;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetBooleanProperty(property, get, value);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == NAME_PROPERTY) {
- if (get) {
- return getName();
- } else {
- setName((SimpleName) child);
- return null;
- }
- }
- if (property == TYPE_PROPERTY) {
- if (get) {
- return getType();
- } else {
- setType((Type) child);
- return null;
- }
- }
- if (property == INITIALIZER_PROPERTY) {
- if (get) {
- return getInitializer();
- } else {
- setInitializer((Expression) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalGetChildListProperty(ChildListPropertyDescriptor property) {
- if (property == MODIFIERS2_PROPERTY) {
- return modifiers();
- }
- // allow default implementation to flag the error
- return super.internalGetChildListProperty(property);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return SINGLE_VARIABLE_DECLARATION;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- SingleVariableDeclaration result = new SingleVariableDeclaration(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- if (this.ast.apiLevel == AST.JLS2_INTERNAL) {
- result.setModifiers(getModifiers());
- } else {
- result.modifiers().addAll(ASTNode.copySubtrees(target, modifiers()));
- result.setVarargs(isVarargs());
- }
- result.setType((Type) getType().clone(target));
- result.setExtraDimensions(getExtraDimensions());
- result.setName((SimpleName) getName().clone(target));
- result.setInitializer(
- (Expression) ASTNode.copySubtree(target, getInitializer()));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- if (this.ast.apiLevel >= AST.JLS3) {
- acceptChildren(visitor, this.modifiers);
- }
- acceptChild(visitor, getType());
- acceptChild(visitor, getName());
- acceptChild(visitor, getInitializer());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the live ordered list of modifiers and annotations
- * of this declaration (added in JLS3 API).
- * <p>
- * Note that the final modifier is the only meaningful modifier for local
- * variable and formal parameter declarations.
- * </p>
- *
- * @return the live list of modifiers and annotations
- * (element type: <code>IExtendedModifier</code>)
- * @exception UnsupportedOperationException if this operation is used in
- * a JLS2 AST
- *
- */
- public List modifiers() {
- // more efficient than just calling unsupportedIn2() to check
- if (this.modifiers == null) {
- unsupportedIn2();
- }
- return this.modifiers;
- }
-
- /**
- * Returns the modifiers explicitly specified on this declaration.
- * <p>
- * In the JLS3 API, this method is a convenience method that
- * computes these flags from <code>modifiers()</code>.
- * </p>
- *
- * @return the bit-wise or of <code>Modifier</code> constants
- * @see Modifier
- */
- public int getModifiers() {
- // more efficient than checking getAST().API_LEVEL
- if (this.modifiers == null) {
- // JLS2 behavior - bona fide property
- return this.modifierFlags;
- } else {
- // JLS3 behavior - convenient method
- // performance could be improved by caching computed flags
- // but this would require tracking changes to this.modifiers
- int computedModifierFlags = Modifier.NONE;
- for (Iterator it = modifiers().iterator(); it.hasNext(); ) {
- Object x = it.next();
- if (x instanceof Modifier) {
- computedModifierFlags |= ((Modifier) x).getKeyword().toFlagValue();
- }
- }
- return computedModifierFlags;
- }
- }
-
- /**
- * Sets the modifiers explicitly specified on this declaration (JLS2 API only).
- * <p>
- * The following modifiers are meaningful for fields: public, private, protected,
- * static, final, volatile, and transient. For local variable and formal
- * parameter declarations, the only meaningful modifier is final.
- * </p>
- *
- * @param modifiers the given modifiers (bit-wise or of <code>Modifier</code> constants)
- * @exception UnsupportedOperationException if this operation is used in
- * an AST later than JLS2
- * @see Modifier
- * @deprecated In the JLS3 API, this method is replaced by
- * {@link #modifiers()} which contains a list of a <code>Modifier</code> nodes.
- */
- public void setModifiers(int modifiers) {
- internalSetModifiers(modifiers);
- }
-
- /**
- * Internal synonym for deprecated method. Used to avoid
- * deprecation warnings.
- *
- */
- /*package*/ final void internalSetModifiers(int pmodifiers) {
- supportedOnlyIn2();
- preValueChange(MODIFIERS_PROPERTY);
- this.modifierFlags = pmodifiers;
- postValueChange(MODIFIERS_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on VariableDeclaration.
- */
- public SimpleName getName() {
- if (this.variableName == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.variableName == null) {
- preLazyInit();
- this.variableName = new SimpleName(this.ast);
- postLazyInit(this.variableName, NAME_PROPERTY);
- }
- }
- }
- return this.variableName;
- }
-
- /* (omit javadoc for this method)
- * Method declared on VariableDeclaration.
- */
- public void setName(SimpleName variableName) {
- if (variableName == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.variableName;
- preReplaceChild(oldChild, variableName, NAME_PROPERTY);
- this.variableName = variableName;
- postReplaceChild(oldChild, variableName, NAME_PROPERTY);
- }
-
- /**
- * Returns the type of the variable declared in this variable declaration,
- * exclusive of any extra array dimensions.
- *
- * @return the type
- */
- public Type getType() {
- if (this.type == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.type == null) {
- preLazyInit();
- this.type = this.ast.newInferredType(null);
- postLazyInit(this.type, TYPE_PROPERTY);
- }
- }
- }
- return this.type;
- }
-
- /**
- * Sets the type of the variable declared in this variable declaration to
- * the given type, exclusive of any extra array dimensions.
- *
- * @param type the new type
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public void setType(Type type) {
- if (type == null) {
- return;
- }
- ASTNode oldChild = this.type;
- preReplaceChild(oldChild, type, TYPE_PROPERTY);
- if (type instanceof InferredType && ((InferredType)type).getType()==null)
- this.type=null;
- else
- this.type = type;
- postReplaceChild(oldChild, type, TYPE_PROPERTY);
- }
-
- /**
- * Returns whether this declaration declares the last parameter of
- * a variable arity method (added in JLS3 API).
- * <p>
- * Note that the binding for the type <code>Foo</code>in the vararg method
- * declaration <code>void fun(Foo... args)</code> is always for the type as
- * written; i.e., the type binding for <code>Foo</code>. However, if you
- * navigate from the method declaration to its method binding to the
- * type binding for its last parameter, the type binding for the vararg
- * parameter is always an array type (i.e., <code>Foo[]</code>) reflecting
- * the way vararg methods get compiled.
- * </p>
- *
- * @return <code>true</code> if this is a variable arity parameter declaration,
- * and <code>false</code> otherwise
- * @exception UnsupportedOperationException if this operation is used in
- * a JLS2 AST
- *
- */
- public boolean isVarargs() {
- // more efficient than just calling unsupportedIn2() to check
- if (this.modifiers == null) {
- unsupportedIn2();
- }
- return this.variableArity;
- }
-
- /**
- * Sets whether this declaration declares the last parameter of
- * a variable arity method (added in JLS3 API).
- *
- * @param variableArity <code>true</code> if this is a variable arity
- * parameter declaration, and <code>false</code> otherwise
- *
- */
- public void setVarargs(boolean variableArity) {
- // more efficient than just calling unsupportedIn2() to check
- if (this.modifiers == null) {
- unsupportedIn2();
- }
- preValueChange(VARARGS_PROPERTY);
- this.variableArity = variableArity;
- postValueChange(VARARGS_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on VariableDeclaration.
- *
- */
- public int getExtraDimensions() {
- return this.extraArrayDimensions;
- }
-
- /* (omit javadoc for this method)
- * Method declared on VariableDeclaration.
- *
- */
- public void setExtraDimensions(int dimensions) {
- if (dimensions < 0) {
- throw new IllegalArgumentException();
- }
- preValueChange(EXTRA_DIMENSIONS_PROPERTY);
- this.extraArrayDimensions = dimensions;
- postValueChange(EXTRA_DIMENSIONS_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on VariableDeclaration.
- */
- public Expression getInitializer() {
- return this.optionalInitializer;
- }
-
- /* (omit javadoc for this method)
- * Method declared on VariableDeclaration.
- */
- public void setInitializer(Expression initializer) {
- // a SingleVariableDeclaration may occur inside an Expression
- // must check cycles
- ASTNode oldChild = this.optionalInitializer;
- preReplaceChild(oldChild, initializer,INITIALIZER_PROPERTY);
- this.optionalInitializer = initializer;
- postReplaceChild(oldChild, initializer,INITIALIZER_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- // treat Operator as free
- return BASE_NODE_SIZE + 7 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.modifiers == null ? 0 : this.modifiers.listSize())
- + (this.type == null ? 0 : getType().treeSize())
- + (this.variableName == null ? 0 : getName().treeSize())
- + (this.optionalInitializer == null ? 0 : getInitializer().treeSize());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Statement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Statement.java
deleted file mode 100644
index c5ecf7b0..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Statement.java
+++ /dev/null
@@ -1,213 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.internal.compiler.parser.Scanner;
-import org.eclipse.wst.jsdt.internal.compiler.parser.TerminalTokens;
-
-/**
- * Abstract base class of AST nodes that represent statements.
- * There are many kinds of statements.
- * <p>
- * The grammar combines both Statement and BlockStatement.
- * For JLS2:
- * <pre>
- * Statement:
- * Block
- * IfStatement
- * ForStatement
- * WhileStatement
- * DoStatement
- * TryStatement
- * SwitchStatement
- * SynchronizedStatement
- * ReturnStatement
- * ThrowStatement
- * BreakStatement
- * ContinueStatement
- * EmptyStatement
- * ExpressionStatement
- * LabeledStatement
- * AssertStatement
- * VariableDeclarationStatement
- * TypeDeclarationStatement
- * ConstructorInvocation
- * SuperConstructorInvocation
- * </pre>
- * For JLS3, an enhanced for node type was added:
- * <pre>
- * Statement:
- * Block
- * IfStatement
- * ForStatement
- * EnhancedForStatement
- * WhileStatement
- * DoStatement
- * TryStatement
- * SwitchStatement
- * SynchronizedStatement
- * ReturnStatement
- * ThrowStatement
- * BreakStatement
- * ContinueStatement
- * EmptyStatement
- * ExpressionStatement
- * LabeledStatement
- * AssertStatement
- * VariableDeclarationStatement
- * TypeDeclarationStatement
- * ConstructorInvocation
- * SuperConstructorInvocation
- * </pre>
- * </p>
- *
- * 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 Statement extends ProgramElement {
-
- /**
- * The leading comment, or <code>null</code> if none.
- * Defaults to none.
- *
- * @deprecated The leading comment feature was removed in 2.1.
- */
- private String optionalLeadingComment = null;
-
- /**
- * Creates a new AST node for a statement owned by the given AST.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- Statement(AST ast) {
- super(ast);
- }
-
- /**
- * Returns the leading comment string, including the starting
- * and ending comment delimiters, and any embedded line breaks.
- * <p>
- * A leading comment is a comment that appears before the statement.
- * It may be either a traditional comment or an end-of-line comment.
- * Traditional comments must begin with "/&#42;, may contain line breaks,
- * and must end with "&#42;/. End-of-line comments must begin with "//",
- * must end with a line delimiter (as per JLS 3.7), and must not contain
- * line breaks.
- * </p>
- *
- * @return the comment string, or <code>null</code> if none
- * @deprecated This feature was removed in the 2.1 release because it was
- * only a partial, and inadequate, solution to the issue of associating
- * comments with statements. Furthermore, AST.parseCompilationUnit did not
- * associate leading comments, making this moot. Clients that need to access
- * comments preceding a statement should either consult the compilation
- * unit's {@linkplain JavaScriptUnit#getCommentList() comment table}
- * or use a scanner to reanalyze the source text immediately preceding
- * the statement's source range.
- */
- public String getLeadingComment() {
- return optionalLeadingComment;
- }
-
- /**
- * Sets or clears the leading comment string. The comment
- * string must include the starting and ending comment delimiters,
- * and any embedded linebreaks.
- * <p>
- * A leading comment is a comment that appears before the statement.
- * It may be either a traditional comment or an end-of-line comment.
- * Traditional comments must begin with "/&#42;, may contain line breaks,
- * and must end with "&#42;/. End-of-line comments must begin with "//"
- * (as per JLS 3.7), and must not contain line breaks.
- * </p>
- * <p>
- * Examples:
- * <code>
- * <pre>
- * setLeadingComment("/&#42; traditional comment &#42;/"); // correct
- * setLeadingComment("missing comment delimiters"); // wrong
- * setLeadingComment("/&#42; unterminated traditional comment "); // wrong
- * setLeadingComment("/&#42; broken\n traditional comment &#42;/"); // correct
- * setLeadingComment("// end-of-line comment\n"); // correct
- * setLeadingComment("// end-of-line comment without line terminator"); // correct
- * setLeadingComment("// broken\n end-of-line comment\n"); // wrong
- * </pre>
- * </code>
- * </p>
- *
- * @param comment the comment string, or <code>null</code> if none
- * @exception IllegalArgumentException if the comment string is invalid
- * @deprecated This feature was removed in the 2.1 release because it was
- * only a partial, and inadequate, solution to the issue of associating
- * comments with statements.
- */
- public void setLeadingComment(String comment) {
- if (comment != null) {
- char[] source = comment.toCharArray();
- Scanner scanner = this.ast.scanner;
- scanner.resetTo(0, source.length);
- scanner.setSource(source);
- try {
- int token;
- boolean onlyOneComment = false;
- while ((token = scanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
- switch(token) {
- case TerminalTokens.TokenNameCOMMENT_BLOCK :
- case TerminalTokens.TokenNameCOMMENT_JAVADOC :
- case TerminalTokens.TokenNameCOMMENT_LINE :
- if (onlyOneComment) {
- throw new IllegalArgumentException();
- }
- onlyOneComment = true;
- break;
- default:
- onlyOneComment = false;
- }
- }
- if (!onlyOneComment) {
- throw new IllegalArgumentException();
- }
- } catch (InvalidInputException e) {
- throw new IllegalArgumentException();
- }
- }
- // we do not consider the obsolete comment as a structureal property
- // but we protect them nevertheless
- checkModifiable();
- this.optionalLeadingComment = comment;
- }
-
- /**
- * Copies the leading comment from the given statement.
- *
- * @param source the statement that supplies the leading comment
- *
- */
- void copyLeadingComment(Statement source) {
- setLeadingComment(source.getLeadingComment());
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- int size = BASE_NODE_SIZE + 1 * 4 + stringSize(getLeadingComment());
- return size;
- }
-}
-
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
deleted file mode 100644
index 4ab921fd..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/StringLiteral.java
+++ /dev/null
@@ -1,347 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.internal.compiler.parser.Scanner;
-import org.eclipse.wst.jsdt.internal.compiler.parser.TerminalTokens;
-
-/**
- * String literal nodes.
- *
- * 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 StringLiteral extends Expression {
-
- /**
- * The "escapedValue" structural property of this node type.
- *
- */
- public static final SimplePropertyDescriptor ESCAPED_VALUE_PROPERTY =
- new SimplePropertyDescriptor(StringLiteral.class, "escapedValue", String.class, MANDATORY); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List propertyList = new ArrayList(2);
- createPropertyList(StringLiteral.class, propertyList);
- addProperty(ESCAPED_VALUE_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The literal string, including quotes and escapes; defaults to the
- * literal for the empty string.
- */
- private String escapedValue = "\"\"";//$NON-NLS-1$
-
- /**
- * Creates a new unparented string literal node owned by the given AST.
- * By default, the string literal denotes the empty string.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- StringLiteral(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final Object internalGetSetObjectProperty(SimplePropertyDescriptor property, boolean get, Object value) {
- if (property == ESCAPED_VALUE_PROPERTY) {
- if (get) {
- return getEscapedValue();
- } else {
- setEscapedValue((String) value);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetObjectProperty(property, get, value);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return STRING_LITERAL;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- StringLiteral result = new StringLiteral(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setEscapedValue(getEscapedValue());
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- visitor.visit(this);
- visitor.endVisit(this);
- }
-
- /**
- * Returns the string value of this literal node to the given string
- * literal token. The token is the sequence of characters that would appear
- * in the source program, including enclosing double quotes and embedded
- * escapes.
- *
- * @return the string literal token, including enclosing double
- * quotes and embedded escapes
- */
- public String getEscapedValue() {
- return this.escapedValue;
- }
-
- /**
- * Sets the string value of this literal node to the given string literal
- * token. The token is the sequence of characters that would appear in the
- * source program, including enclosing double quotes and embedded escapes.
- * For example,
- * <ul>
- * <li><code>""</code> <code>setLiteral("\"\"")</code></li>
- * <li><code>"hello world"</code> <code>setLiteral("\"hello world\"")</code></li>
- * <li><code>"boo\nhoo"</code> <code>setLiteral("\"boo\\nhoo\"")</code></li>
- * </ul>
- *
- * @param token the string literal token, including enclosing double
- * quotes and embedded escapes
- * @exception IllegalArgumentException if the argument is incorrect
- */
- public void setEscapedValue(String token) {
- // update internalSetEscapedValue(String) if this is changed
- if (token == null) {
- throw new IllegalArgumentException("Token cannot be null"); //$NON-NLS-1$
- }
- Scanner scanner = this.ast.scanner;
- char[] source = token.toCharArray();
- scanner.setSource(source);
- scanner.resetTo(0, source.length);
- try {
- int tokenType = scanner.getNextToken();
- switch(tokenType) {
- case TerminalTokens.TokenNameStringLiteral:
- break;
- default:
- throw new IllegalArgumentException("Invalid string literal : >" + token + "<"); //$NON-NLS-1$//$NON-NLS-2$
- }
- } catch(InvalidInputException e) {
- throw new IllegalArgumentException("Invalid string literal : >" + token + "<");//$NON-NLS-1$//$NON-NLS-2$
- }
- preValueChange(ESCAPED_VALUE_PROPERTY);
- this.escapedValue = token;
- postValueChange(ESCAPED_VALUE_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * This method is a copy of setEscapedValue(String) that doesn't do any validation.
- */
- void internalSetEscapedValue(String token) {
- preValueChange(ESCAPED_VALUE_PROPERTY);
- this.escapedValue = token;
- postValueChange(ESCAPED_VALUE_PROPERTY);
- }
-
- /**
- * Returns the value of this literal node.
- * <p>
- * For example,
- * <pre>
- * StringLiteral s;
- * s.setEscapedValue("\"hello\\nworld\"");
- * assert s.getLiteralValue().equals("hello\nworld");
- * </pre>
- * </p>
- * <p>
- * Note that this is a convenience method that converts from the stored
- * string literal token returned by <code>getEscapedLiteral</code>.
- * </p>
- *
- * @return the string value without enclosing double quotes and embedded
- * escapes
- * @exception IllegalArgumentException if the literal value cannot be converted
- */
- public String getLiteralValue() {
- String s = getEscapedValue();
- int len = s.length();
- if (len < 2 || s.charAt(0) != '\"' || s.charAt(len-1) != '\"' ) {
- throw new IllegalArgumentException();
- }
-
- Scanner scanner = this.ast.scanner;
- char[] source = s.toCharArray();
- scanner.setSource(source);
- scanner.resetTo(0, source.length);
- try {
- int tokenType = scanner.getNextToken();
- switch(tokenType) {
- case TerminalTokens.TokenNameStringLiteral:
- return scanner.getCurrentStringLiteral();
- default:
- throw new IllegalArgumentException();
- }
- } catch(InvalidInputException e) {
- throw new IllegalArgumentException();
- }
- }
-
- /**
- * Sets the value of this literal node.
- * <p>
- * For example,
- * <pre>
- * StringLiteral s;
- * s.setLiteralValue("hello\nworld");
- * assert s.getEscapedValue("\"hello\\nworld\"");
- * assert s.getLiteralValue().equals("hello\nworld");
- * </pre>
- * </p>
- * <p>
- * Note that this is a convenience method that converts to the stored
- * string literal token acceptable to <code>setEscapedLiteral</code>.
- * </p>
- *
- * @param value the string value without enclosing double quotes and
- * embedded escapes
- * @exception IllegalArgumentException if the argument is incorrect
- */
- public void setLiteralValue(String value) {
- if (value == null) {
- throw new IllegalArgumentException();
- }
- int len = value.length();
- StringBuffer b = new StringBuffer(len + 2);
-
- b.append("\""); // opening delimiter //$NON-NLS-1$
- for (int i = 0; i < len; i++) {
- char c = value.charAt(i);
- switch(c) {
- case '\b' :
- b.append("\\b"); //$NON-NLS-1$
- break;
- case '\t' :
- b.append("\\t"); //$NON-NLS-1$
- break;
- case '\n' :
- b.append("\\n"); //$NON-NLS-1$
- break;
- case '\f' :
- b.append("\\f"); //$NON-NLS-1$
- break;
- case '\r' :
- b.append("\\r"); //$NON-NLS-1$
- break;
- case '\"':
- b.append("\\\""); //$NON-NLS-1$
- break;
- case '\'':
- b.append("\\\'"); //$NON-NLS-1$
- break;
- case '\\':
- b.append("\\\\"); //$NON-NLS-1$
- break;
- case '\0' :
- b.append("\\0"); //$NON-NLS-1$
- break;
- case '\1' :
- b.append("\\1"); //$NON-NLS-1$
- break;
- case '\2' :
- b.append("\\2"); //$NON-NLS-1$
- break;
- case '\3' :
- b.append("\\3"); //$NON-NLS-1$
- break;
- case '\4' :
- b.append("\\4"); //$NON-NLS-1$
- break;
- case '\5' :
- b.append("\\5"); //$NON-NLS-1$
- break;
- case '\6' :
- b.append("\\6"); //$NON-NLS-1$
- break;
- case '\7' :
- b.append("\\7"); //$NON-NLS-1$
- break;
- default:
- b.append(c);
- }
- }
- b.append("\""); // closing delimiter //$NON-NLS-1$
- setEscapedValue(b.toString());
- }
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- int size = BASE_NODE_SIZE + 1 * 4 + stringSize(escapedValue);
- return size;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return memSize();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/StructuralPropertyDescriptor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/StructuralPropertyDescriptor.java
deleted file mode 100644
index ebfe7f87..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/StructuralPropertyDescriptor.java
+++ /dev/null
@@ -1,145 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.dom;
-
-/**
- * Abstract base class for property descriptors of AST nodes.
- * There are three kinds of properties:
- * <ul>
- * <li>simple properties ({@link SimplePropertyDescriptor})
- * - properties where the value is a primitive (int, boolean)
- * or simple (String, InfixExprsssion.Operator) type other than an
- * AST node; for example, the identifier of a {@link SimpleName}</li>
- * <li>child properties ({@link ChildPropertyDescriptor})
- * - properties whose value is another AST node;
- * for example, the name of a {@link FunctionDeclaration}</li>
- * <li>child list properties ({@link ChildListPropertyDescriptor})
- * - properties where the value is a list of AST nodes;
- * for example, the statements of a {@link Block}</li>
- * </ul>
- *
- * 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 StructuralPropertyDescriptor {
-
- /**
- * Property id.
- */
- private final String propertyId;
-
- /**
- * The concrete AST node type that owns this property.
- */
- private final Class nodeClass;
-
- /**
- * Creates a new property descriptor for the given node type
- * with the given property id.
- * Note that this constructor is declared package-private so that
- * property descriptors can only be created by the AST
- * implementation.
- *
- * @param nodeClass concrete AST node type that owns this property
- * @param propertyId the property id
- */
- StructuralPropertyDescriptor(Class nodeClass, String propertyId) {
- if (nodeClass == null || propertyId == null) {
- throw new IllegalArgumentException();
- }
- this.propertyId = propertyId;
- this.nodeClass = nodeClass;
- }
-
- /**
- * Returns the id of this property.
- *
- * @return the property id
- */
- public final String getId() {
- return this.propertyId;
- }
-
- /**
- * Returns the AST node type that owns this property.
- * <p>
- * For example, for all properties of the node type
- * TypeDeclaration, this method returns <code>TypeDeclaration.class</code>.
- * </p>
- *
- * @return the node type that owns this property
- */
- public final Class getNodeClass() {
- return this.nodeClass;
- }
-
- /**
- * Returns whether this property is a simple property
- * (instance of {@link SimplePropertyDescriptor}.
- *
- * @return <code>true</code> if this is a simple property, and
- * <code>false</code> otherwise
- */
- public final boolean isSimpleProperty(){
- return (this instanceof SimplePropertyDescriptor);
- }
-
- /**
- * Returns whether this property is a child property
- * (instance of {@link ChildPropertyDescriptor}.
- *
- * @return <code>true</code> if this is a child property, and
- * <code>false</code> otherwise
- */
- public final boolean isChildProperty() {
- return (this instanceof ChildPropertyDescriptor);
- }
-
- /**
- * Returns whether this property is a child list property
- * (instance of {@link ChildListPropertyDescriptor}.
- *
- * @return <code>true</code> if this is a child list property, and
- * <code>false</code> otherwise
- */
- public final boolean isChildListProperty() {
- return (this instanceof ChildListPropertyDescriptor);
- }
-
- /**
- * Returns a string suitable for debug purposes.
- * @return {@inheritDoc}
- */
- public String toString() {
- StringBuffer b = new StringBuffer();
- if (isChildListProperty()) {
- b.append("ChildList"); //$NON-NLS-1$
- }
- if (isChildProperty()) {
- b.append("Child"); //$NON-NLS-1$
- }
- if (isSimpleProperty()) {
- b.append("Simple"); //$NON-NLS-1$
- }
- b.append("Property["); //$NON-NLS-1$
- if (this.nodeClass != null) {
- b.append(this.nodeClass.getName());
- }
- b.append(","); //$NON-NLS-1$
- if (this.propertyId != null) {
- b.append(this.propertyId);
- }
- b.append("]"); //$NON-NLS-1$
- return b.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SuperConstructorInvocation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SuperConstructorInvocation.java
deleted file mode 100644
index a39583ed..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SuperConstructorInvocation.java
+++ /dev/null
@@ -1,322 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Super constructor invocation statement AST node type.
- * For JLS2: * <pre>
- * SuperConstructorInvocation:
- * [ Expression <b>.</b> ] <b>super</b>
- * <b>(</b> [ Expression { <b>,</b> Expression } ] <b>)</b> <b>;</b>
- * </pre>
- * For JLS3, type arguments are added:
- * <pre>
- * SuperConstructorInvocation:
- * [ Expression <b>.</b> ]
- * [ <b>&lt;</b> Type { <b>,</b> Type } <b>&gt;</b> ]
- * <b>super</b> <b>(</b> [ Expression { <b>,</b> Expression } ] <b>)</b> <b>;</b>
- * </pre>
- *
- *
- * <p><b>Note: This Class only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * 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 SuperConstructorInvocation extends Statement {
-
- /**
- * The "expression" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor EXPRESSION_PROPERTY =
- new ChildPropertyDescriptor(SuperConstructorInvocation.class, "expression", Expression.class, OPTIONAL, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "typeArguments" structural property of this node type (added in JLS3 API).
- *
- */
- public static final ChildListPropertyDescriptor TYPE_ARGUMENTS_PROPERTY =
- new ChildListPropertyDescriptor(SuperConstructorInvocation.class, "typeArguments", Type.class, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "arguments" structural property of this node type.
- *
- */
- public static final ChildListPropertyDescriptor ARGUMENTS_PROPERTY =
- new ChildListPropertyDescriptor(SuperConstructorInvocation.class, "arguments", Expression.class, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS_2_0;
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS_3_0;
-
- static {
- List propertyList = new ArrayList(3);
- createPropertyList(SuperConstructorInvocation.class, propertyList);
- addProperty(EXPRESSION_PROPERTY, propertyList);
- addProperty(ARGUMENTS_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS_2_0 = reapPropertyList(propertyList);
-
- propertyList = new ArrayList(4);
- createPropertyList(SuperConstructorInvocation.class, propertyList);
- addProperty(EXPRESSION_PROPERTY, propertyList);
- addProperty(TYPE_ARGUMENTS_PROPERTY, propertyList);
- addProperty(ARGUMENTS_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS_3_0 = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- if (apiLevel == AST.JLS2_INTERNAL) {
- return PROPERTY_DESCRIPTORS_2_0;
- } else {
- return PROPERTY_DESCRIPTORS_3_0;
- }
- }
-
- /**
- * The expression; <code>null</code> for none; defaults to none.
- */
- private Expression optionalExpression = null;
-
- /**
- * The type arguments (element type: <code>Type</code>).
- * Null in JLS2. Added in JLS3; defaults to an empty list
- * (see constructor).
- *
- */
- private ASTNode.NodeList typeArguments = null;
-
- /**
- * The list of argument expressions (element type:
- * <code>Expression</code>). Defaults to an empty list.
- */
- private ASTNode.NodeList arguments =
- new ASTNode.NodeList(ARGUMENTS_PROPERTY);
-
- /**
- * Creates a new AST node for an super constructor invocation statement
- * owned by the given AST. By default, no type arguments, and an empty list
- * of arguments.
- *
- * @param ast the AST that is to own this node
- */
- SuperConstructorInvocation(AST ast) {
- super(ast);
- if (ast.apiLevel >= AST.JLS3) {
- this.typeArguments = new ASTNode.NodeList(TYPE_ARGUMENTS_PROPERTY);
- }
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == EXPRESSION_PROPERTY) {
- if (get) {
- return getExpression();
- } else {
- setExpression((Expression) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalGetChildListProperty(ChildListPropertyDescriptor property) {
- if (property == ARGUMENTS_PROPERTY) {
- return arguments();
- }
- if (property == TYPE_ARGUMENTS_PROPERTY) {
- return typeArguments();
- }
- // allow default implementation to flag the error
- return super.internalGetChildListProperty(property);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return SUPER_CONSTRUCTOR_INVOCATION;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- SuperConstructorInvocation result = new SuperConstructorInvocation(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.copyLeadingComment(this);
- result.setExpression(
- (Expression) ASTNode.copySubtree(target, getExpression()));
- if (this.ast.apiLevel >= AST.JLS3) {
- result.typeArguments().addAll(ASTNode.copySubtrees(target, typeArguments()));
- }
- result.arguments().addAll(ASTNode.copySubtrees(target, arguments()));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChild(visitor, getExpression());
- if (this.ast.apiLevel >= AST.JLS3) {
- acceptChildren(visitor, this.typeArguments);
- }
- acceptChildren(visitor, this.arguments);
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the expression of this super constructor invocation statement,
- * or <code>null</code> if there is none.
- *
- * @return the expression node, or <code>null</code> if there is none
- */
- public Expression getExpression() {
- return this.optionalExpression;
- }
-
- /**
- * Sets or clears the expression of this super constructor invocation
- * statement.
- *
- * @param expression the expression node, or <code>null</code> if
- * there is none
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setExpression(Expression expression) {
- ASTNode oldChild = this.optionalExpression;
- preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY);
- this.optionalExpression = expression;
- postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY);
- }
-
- /**
- * Returns the live ordered list of type arguments of this constructor
- * invocation (added in JLS3 API).
- *
- * @return the live list of type arguments
- * (element type: <code>Type</code>)
- * @exception UnsupportedOperationException if this operation is used in
- * a JLS2 AST
- *
- */
- public List typeArguments() {
- // more efficient than just calling unsupportedIn2() to check
- if (this.typeArguments == null) {
- unsupportedIn2();
- }
- return this.typeArguments;
- }
-
- /**
- * Returns the live ordered list of argument expressions in this super
- * constructor invocation statement.
- *
- * @return the live list of argument expressions
- * (element type: <code>Expression</code>)
- */
- public List arguments() {
- return this.arguments;
- }
-
- /**
- * Resolves and returns the binding for the constructor invoked by this
- * expression.
- * <p>
- * Note that bindings are generally unavailable unless requested when the
- * AST is being built.
- * </p>
- *
- * @return the constructor binding, or <code>null</code> if the binding
- * cannot be resolved
- */
- public IFunctionBinding resolveConstructorBinding() {
- return this.ast.getBindingResolver().resolveConstructor(this);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- // treat Code as free
- return BASE_NODE_SIZE + 3 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return memSize()
- + (this.optionalExpression == null ? 0 : getExpression().treeSize())
- + (this.typeArguments == null ? 0 : this.typeArguments.listSize())
- + (this.arguments == null ? 0 : this.arguments.listSize());
- }
-}
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
deleted file mode 100644
index 3a803672..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SuperFieldAccess.java
+++ /dev/null
@@ -1,282 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Simple or qualified "super" field access expression AST node type.
- *
- * <pre>
- * SuperFieldAccess:
- * [ ClassName <b>.</b> ] <b>super</b> <b>.</b> Identifier
- * </pre>
- *
- * <p>
- * See <code>FieldAccess</code> for guidelines on handling other expressions
- * that resemble qualified names.
- * </p>
- *
- * @see FieldAccess
- *
- * <p><b>Note: This Class only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * 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 SuperFieldAccess extends Expression {
-
- /**
- * The "qualifier" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor QUALIFIER_PROPERTY =
- new ChildPropertyDescriptor(SuperFieldAccess.class, "qualifier", Name.class, OPTIONAL, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "name" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor NAME_PROPERTY =
- new ChildPropertyDescriptor(SuperFieldAccess.class, "name", SimpleName.class, MANDATORY, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List propertyList = new ArrayList(3);
- createPropertyList(SuperFieldAccess.class, propertyList);
- addProperty(QUALIFIER_PROPERTY, propertyList);
- addProperty(NAME_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The optional qualifier; <code>null</code> for none; defaults to none.
- */
- private Name optionalQualifier = null;
-
- /**
- * The field; lazily initialized; defaults to an unspecified,
- * but legal, simple field name.
- */
- private SimpleName fieldName = null;
-
- /**
- * Creates a new unparented node for a super field access expression owned
- * by the given AST. By default, field name is an unspecified, but legal,
- * name, and there is no qualifier.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- SuperFieldAccess(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == QUALIFIER_PROPERTY) {
- if (get) {
- return getQualifier();
- } else {
- setQualifier((Name) child);
- return null;
- }
- }
- if (property == NAME_PROPERTY) {
- if (get) {
- return getName();
- } else {
- setName((SimpleName) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return SUPER_FIELD_ACCESS;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- SuperFieldAccess result = new SuperFieldAccess(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setName((SimpleName) ASTNode.copySubtree(target, getName()));
- result.setQualifier((Name) ASTNode.copySubtree(target, getQualifier()));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChild(visitor, getQualifier());
- acceptChild(visitor, getName());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the qualifier of this "super" field access expression, or
- * <code>null</code> if there is none.
- *
- * @return the qualifier name node, or <code>null</code> if there is none
- */
- public Name getQualifier() {
- return this.optionalQualifier;
- }
-
- /**
- * Sets or clears the qualifier of this "super" field access expression.
- *
- * @param name the qualifier name node, or <code>null</code> if
- * there is none
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public void setQualifier(Name name) {
- ASTNode oldChild = this.optionalQualifier;
- preReplaceChild(oldChild, name, QUALIFIER_PROPERTY);
- this.optionalQualifier = name;
- postReplaceChild(oldChild, name, QUALIFIER_PROPERTY);
- }
-
- /**
- * Returns the name of the field accessed in this "super" field access
- * expression.
- *
- * @return the field name
- */
- public SimpleName getName() {
- if (this.fieldName == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.fieldName == null) {
- preLazyInit();
- this.fieldName = new SimpleName(this.ast);
- postLazyInit(this.fieldName, NAME_PROPERTY);
- }
- }
- }
- return this.fieldName;
- }
-
- /**
- * Resolves and returns the binding for the field accessed by this
- * expression.
- * <p>
- * Note that bindings are generally unavailable unless requested when the
- * AST is being built.
- * </p>
- *
- * @return the variable binding, or <code>null</code> if the binding cannot
- * be resolved
- *
- */
- public IVariableBinding resolveFieldBinding() {
- return this.ast.getBindingResolver().resolveField(this);
- }
-
- /**
- * Sets the name of the field accessed in this "super" field access
- * expression.
- *
- * @param fieldName the field name
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public void setName(SimpleName fieldName) {
- if (fieldName == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.fieldName;
- preReplaceChild(oldChild, fieldName, NAME_PROPERTY);
- this.fieldName = fieldName;
- postReplaceChild(oldChild, fieldName, NAME_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- // treat Code as free
- return BASE_NODE_SIZE + 2 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.optionalQualifier == null ? 0 : getQualifier().treeSize())
- + (this.fieldName == null ? 0 : getName().treeSize());
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SuperMethodInvocation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SuperMethodInvocation.java
deleted file mode 100644
index 6d7c31e3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SuperMethodInvocation.java
+++ /dev/null
@@ -1,401 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Simple or qualified "super" method invocation expression AST node type.
- * For JLS2:
- * <pre>
- * SuperMethodInvocation:
- * [ ClassName <b>.</b> ] <b>super</b> <b>.</b> Identifier
- * <b>(</b> [ Expression { <b>,</b> Expression } ] <b>)</b>
- * </pre>
- * For JLS3, type arguments are added:
- * <pre>
- * SuperMethodInvocation:
- * [ ClassName <b>.</b> ] <b>super</b> <b>.</b>
- * [ <b>&lt;</b> Type { <b>,</b> Type } <b>&gt;</b> ]
- * Identifier <b>(</b> [ Expression { <b>,</b> Expression } ] <b>)</b>
- * </pre>
- *
- * <p><b>Note: This Class only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * 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 SuperMethodInvocation extends Expression {
-
- /**
- * The "qualifier" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor QUALIFIER_PROPERTY =
- new ChildPropertyDescriptor(SuperMethodInvocation.class, "qualifier", Name.class, OPTIONAL, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "typeArguments" structural property of this node type (added in JLS3 API).
- *
- */
- public static final ChildListPropertyDescriptor TYPE_ARGUMENTS_PROPERTY =
- new ChildListPropertyDescriptor(SuperMethodInvocation.class, "typeArguments", Type.class, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "name" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor NAME_PROPERTY =
- new ChildPropertyDescriptor(SuperMethodInvocation.class, "name", SimpleName.class, MANDATORY, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "arguments" structural property of this node type.
- *
- */
- public static final ChildListPropertyDescriptor ARGUMENTS_PROPERTY =
- new ChildListPropertyDescriptor(SuperMethodInvocation.class, "arguments", Expression.class, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS_2_0;
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS_3_0;
-
- static {
- List propertyList = new ArrayList(4);
- createPropertyList(SuperMethodInvocation.class, propertyList);
- addProperty(QUALIFIER_PROPERTY, propertyList);
- addProperty(NAME_PROPERTY, propertyList);
- addProperty(ARGUMENTS_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS_2_0 = reapPropertyList(propertyList);
-
- propertyList = new ArrayList(5);
- createPropertyList(SuperMethodInvocation.class, propertyList);
- addProperty(QUALIFIER_PROPERTY, propertyList);
- addProperty(TYPE_ARGUMENTS_PROPERTY, propertyList);
- addProperty(NAME_PROPERTY, propertyList);
- addProperty(ARGUMENTS_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS_3_0 = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- if (apiLevel == AST.JLS2_INTERNAL) {
- return PROPERTY_DESCRIPTORS_2_0;
- } else {
- return PROPERTY_DESCRIPTORS_3_0;
- }
- }
-
- /**
- * The optional qualifier; <code>null</code> for none; defaults to none.
- */
- private Name optionalQualifier = null;
-
- /**
- * The type arguments (element type: <code>Type</code>).
- * Null in JLS2. Added in JLS3; defaults to an empty list
- * (see constructor).
- *
- */
- private ASTNode.NodeList typeArguments = null;
-
- /**
- * The method name; lazily initialized; defaults to a unspecified,
- * legal JavaScript method name.
- */
- private SimpleName methodName = null;
-
- /**
- * The list of argument expressions (element type:
- * <code>Expression</code>). Defaults to an empty list.
- */
- private ASTNode.NodeList arguments =
- new ASTNode.NodeList(ARGUMENTS_PROPERTY);
-
- /**
- * Creates a new AST node for a "super" method invocation expression owned
- * by the given AST. By default, no qualifier, no type arguments,
- * an unspecified, but legal, method name, and an empty list of arguments.
- *
- * @param ast the AST that is to own this node
- */
- SuperMethodInvocation(AST ast) {
- super(ast);
- if (ast.apiLevel >= AST.JLS3) {
- this.typeArguments = new ASTNode.NodeList(TYPE_ARGUMENTS_PROPERTY);
- }
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == QUALIFIER_PROPERTY) {
- if (get) {
- return getQualifier();
- } else {
- setQualifier((Name) child);
- return null;
- }
- }
- if (property == NAME_PROPERTY) {
- if (get) {
- return getName();
- } else {
- setName((SimpleName) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalGetChildListProperty(ChildListPropertyDescriptor property) {
- if (property == ARGUMENTS_PROPERTY) {
- return arguments();
- }
- if (property == TYPE_ARGUMENTS_PROPERTY) {
- return typeArguments();
- }
- // allow default implementation to flag the error
- return super.internalGetChildListProperty(property);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return SUPER_METHOD_INVOCATION;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- SuperMethodInvocation result = new SuperMethodInvocation(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setName((SimpleName) getName().clone(target));
- result.setQualifier((Name) ASTNode.copySubtree(target, getQualifier()));
- if (this.ast.apiLevel >= AST.JLS3) {
- result.typeArguments().addAll(ASTNode.copySubtrees(target, typeArguments()));
- }
- result.arguments().addAll(ASTNode.copySubtrees(target, arguments()));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChild(visitor, getQualifier());
- if (this.ast.apiLevel >= AST.JLS3) {
- acceptChildren(visitor, this.typeArguments);
- }
- acceptChild(visitor, getName());
- acceptChildren(visitor, this.arguments);
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the qualifier of this "super" method invocation expression, or
- * <code>null</code> if there is none.
- *
- * @return the qualifier name node, or <code>null</code> if there is none
- */
- public Name getQualifier() {
- return this.optionalQualifier;
- }
-
- /**
- * Sets or clears the qualifier of this "super" method invocation expression.
- *
- * @param name the qualifier name node, or <code>null</code> if
- * there is none
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public void setQualifier(Name name) {
- ASTNode oldChild = this.optionalQualifier;
- preReplaceChild(oldChild, name, QUALIFIER_PROPERTY);
- this.optionalQualifier = name;
- postReplaceChild(oldChild, name, QUALIFIER_PROPERTY);
- }
-
-
- /**
- * Returns true if the resolved return type has been inferred from the assignment context (JLS3 15.12.2.8), false otherwise.
- * <p>
- * This information is available only when bindings are requested when the AST is being built
- * </p>.
- *
- * @return true if the resolved return type has been inferred from the assignment context (JLS3 15.12.2.8), false otherwise
- *
- */
- public boolean isResolvedTypeInferredFromExpectedType() {
- return this.ast.getBindingResolver().isResolvedTypeInferredFromExpectedType(this);
- }
-
- /**
- * Returns the live ordered list of type arguments of this method
- * invocation (added in JLS3 API).
- *
- * @return the live list of type arguments
- * (element type: <code>Type</code>)
- * @exception UnsupportedOperationException if this operation is used in
- * a JLS2 AST
- *
- */
- public List typeArguments() {
- // more efficient than just calling unsupportedIn2() to check
- if (this.typeArguments == null) {
- unsupportedIn2();
- }
- return this.typeArguments;
- }
-
- /**
- * Returns the name of the method invoked in this expression.
- *
- * @return the method name node
- */
- public SimpleName getName() {
- if (this.methodName == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.methodName == null) {
- preLazyInit();
- this.methodName = new SimpleName(this.ast);
- postLazyInit(this.methodName, NAME_PROPERTY);
- }
- }
- }
- return this.methodName;
- }
-
- /**
- * Sets the name of the method invoked in this expression to the
- * given name.
- *
- * @param name the new method name
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public void setName(SimpleName name) {
- if (name == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.methodName;
- preReplaceChild(oldChild, name, NAME_PROPERTY);
- this.methodName = name;
- postReplaceChild(oldChild, name, NAME_PROPERTY);
- }
-
- /**
- * Returns the live ordered list of argument expressions in this
- * "super" method invocation expression.
- *
- * @return the live list of argument expressions
- * (element type: <code>Expression</code>)
- */
- public List arguments() {
- return this.arguments;
- }
-
- /**
- * Resolves and returns the binding for the method invoked by this
- * expression.
- * <p>
- * Note that bindings are generally unavailable unless requested when the
- * AST is being built.
- * </p>
- *
- * @return the method binding, or <code>null</code> if the binding cannot
- * be resolved
- *
- */
- public IFunctionBinding resolveMethodBinding() {
- return this.ast.getBindingResolver().resolveMethod(this);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- // treat Code as free
- return BASE_NODE_SIZE + 4 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.optionalQualifier == null ? 0 : getQualifier().treeSize())
- + (this.typeArguments == null ? 0 : this.typeArguments.listSize())
- + (this.methodName == null ? 0 : getName().treeSize())
- + (this.arguments == null ? 0 : this.arguments.listSize());
- }
-}
-
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
deleted file mode 100644
index 2117d148..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SwitchCase.java
+++ /dev/null
@@ -1,224 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Switch case AST node type. A switch case is a special kind of node used only
- * in switch statements. It is a <code>Statement</code> in name only.
- * <p>
- * <pre>
- * SwitchCase:
- * <b>case</b> Expression <b>:</b>
- * <b>default</b> <b>:</b>
- * </pre>
- * </p>
- *
- * 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 SwitchCase extends Statement {
-
- /**
- * The "expression" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor EXPRESSION_PROPERTY =
- new ChildPropertyDescriptor(SwitchCase.class, "expression", Expression.class, OPTIONAL, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List propertyList = new ArrayList(2);
- createPropertyList(SwitchCase.class, propertyList);
- addProperty(EXPRESSION_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The expression; <code>null</code> for none; lazily initialized (but
- * does <b>not</b> default to none).
- * @see #expressionInitialized
- */
- private Expression optionalExpression = null;
-
- /**
- * Indicates whether <code>optionalExpression</code> has been initialized.
- */
- private boolean expressionInitialized = false;
-
- /**
- * Creates a new AST node for a switch case pseudo-statement owned by the
- * given AST. By default, there is an unspecified, but legal, expression.
- *
- * @param ast the AST that is to own this node
- */
- SwitchCase(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == EXPRESSION_PROPERTY) {
- if (get) {
- return getExpression();
- } else {
- setExpression((Expression) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return SWITCH_CASE;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- SwitchCase result = new SwitchCase(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.copyLeadingComment(this);
- result.setExpression(
- (Expression) ASTNode.copySubtree(target, getExpression()));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- acceptChild(visitor, getExpression());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the expression of this switch case, or
- * <code>null</code> if there is none (the "default:" case).
- *
- * @return the expression node, or <code>null</code> if there is none
- */
- public Expression getExpression() {
- if (!this.expressionInitialized) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (!this.expressionInitialized) {
- preLazyInit();
- this.optionalExpression = new SimpleName(this.ast);
- this.expressionInitialized = true;
- postLazyInit(this.optionalExpression, EXPRESSION_PROPERTY);
- }
- }
- }
- return this.optionalExpression;
- }
-
- /**
- * Sets the expression of this switch case, or clears it (turns it into
- * the "default:" case).
- *
- * @param expression the expression node, or <code>null</code> to
- * turn it into the "default:" case
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setExpression(Expression expression) {
- ASTNode oldChild = this.optionalExpression;
- preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY);
- this.optionalExpression = expression;
- this.expressionInitialized = true;
- postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY);
- }
-
- /**
- * Returns whether this switch case represents the "default:" case.
- * <p>
- * This convenience method is equivalent to
- * <code>getExpression() == null</code>.
- * </p>
- *
- * @return <code>true</code> if this is the default switch case, and
- * <code>false</code> if this is a non-default switch case
- */
- public boolean isDefault() {
- return getExpression() == null;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return super.memSize() + 2 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.optionalExpression == null ? 0 : optionalExpression.treeSize());
- }
-}
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
deleted file mode 100644
index 52f06e0c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SwitchStatement.java
+++ /dev/null
@@ -1,252 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Switch statement AST node type.
- * <p>
- * <pre>
- * SwitchStatement:
- * <b>switch</b> <b>(</b> Expression <b>)</b>
- * <b>{</b> { SwitchCase | Statement } } <b>}</b>
- * SwitchCase:
- * <b>case</b> Expression <b>:</b>
- * <b>default</b> <b>:</b>
- * </pre>
- * <code>SwitchCase</code> nodes are treated as a kind of
- * <code>Statement</code>.
- * </p>
- *
- * 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 SwitchStatement extends Statement {
-
- /**
- * The "expression" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor EXPRESSION_PROPERTY =
- new ChildPropertyDescriptor(SwitchStatement.class, "expression", Expression.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "statements" structural property of this node type.
- *
- */
- public static final ChildListPropertyDescriptor STATEMENTS_PROPERTY =
- new ChildListPropertyDescriptor(SwitchStatement.class, "statements", Statement.class, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List propertyList = new ArrayList(3);
- createPropertyList(SwitchStatement.class, propertyList);
- addProperty(EXPRESSION_PROPERTY, propertyList);
- addProperty(STATEMENTS_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The expression; lazily initialized; defaults to a unspecified, but legal,
- * expression.
- */
- private Expression expression = null;
-
- /**
- * The statements and SwitchCase nodes
- * (element type: <code>Statement</code>).
- * Defaults to an empty list.
- */
- private ASTNode.NodeList statements =
- new ASTNode.NodeList(STATEMENTS_PROPERTY);
-
- /**
- * Creates a new unparented switch statement node owned by the given
- * AST. By default, the swicth statement has an unspecified, but legal,
- * expression, and an empty list of switch groups.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- SwitchStatement(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == EXPRESSION_PROPERTY) {
- if (get) {
- return getExpression();
- } else {
- setExpression((Expression) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalGetChildListProperty(ChildListPropertyDescriptor property) {
- if (property == STATEMENTS_PROPERTY) {
- return statements();
- }
- // allow default implementation to flag the error
- return super.internalGetChildListProperty(property);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return SWITCH_STATEMENT;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- SwitchStatement result = new SwitchStatement(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.copyLeadingComment(this);
- result.setExpression((Expression) getExpression().clone(target));
- result.statements().addAll(ASTNode.copySubtrees(target, statements()));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChild(visitor, getExpression());
- acceptChildren(visitor, this.statements);
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the expression of this switch statement.
- *
- * @return the expression node
- */
- public Expression getExpression() {
- if (this.expression == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.expression == null) {
- preLazyInit();
- this.expression = new SimpleName(this.ast);
- postLazyInit(this.expression, EXPRESSION_PROPERTY);
- }
- }
- }
- return this.expression;
- }
-
- /**
- * Sets the expression of this switch statement.
- *
- * @param expression the new expression node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setExpression(Expression expression) {
- if (expression == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.expression;
- preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY);
- this.expression = expression;
- postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY);
- }
-
- /**
- * Returns the live ordered list of statements for this switch statement.
- * Within this list, <code>SwitchCase</code> nodes mark the start of
- * the switch groups.
- *
- * @return the live list of statement nodes
- * (element type: <code>Statement</code>)
- */
- public List statements() {
- return this.statements;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return super.memSize() + 2 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.expression == null ? 0 : getExpression().treeSize())
- + this.statements.listSize();
- }
-}
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
deleted file mode 100644
index 7bc18304..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TagElement.java
+++ /dev/null
@@ -1,403 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * AST node for a tag within a doc comment.
- * Tag elements nested within another tag element are called
- * inline doc tags.
- * <pre>
- * TagElement:
- * [ <b>@</b> Identifier ] { DocElement }
- * DocElement:
- * TextElement
- * Name
- * FunctionRef
- * MemberRef
- * <b>{</b> TagElement <b>}</b>
- * </pre>
- *
- * @see JSdoc
- *
- * 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 final class TagElement extends ASTNode implements IDocElement {
-
- /**
- * The "tagName" structural property of this node type.
- *
- *
- */
- public static final SimplePropertyDescriptor TAG_NAME_PROPERTY =
- new SimplePropertyDescriptor(TagElement.class, "tagName", String.class, OPTIONAL); //$NON-NLS-1$
-
- /**
- * The "fragments" structural property of this node type.
- *
- */
- public static final ChildListPropertyDescriptor FRAGMENTS_PROPERTY =
- new ChildListPropertyDescriptor(TagElement.class, "fragments", IDocElement.class, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List propertyList = new ArrayList(3);
- createPropertyList(TagElement.class, propertyList);
- addProperty(TAG_NAME_PROPERTY, propertyList);
- addProperty(FRAGMENTS_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * Standard doc tag name (value {@value}).
- */
- public static final String TAG_AUTHOR = "@author"; //$NON-NLS-1$
-
- /**
- * Standard inline doc tag name (value {@value}).
- * <p>
- * Note that this tag first appeared in J2SE 5.
- * </p>
- *
- */
- public static final String TAG_CODE = "@code"; //$NON-NLS-1$
-
- /**
- * Standard doc tag name (value {@value}).
- */
- public static final String TAG_DEPRECATED = "@deprecated"; //$NON-NLS-1$
-
- /**
- * Standard inline doc tag name (value {@value}).
- */
- public static final String TAG_DOCROOT = "@docRoot"; //$NON-NLS-1$
-
- /**
- * Standard doc tag name (value {@value}).
- */
- public static final String TAG_EXCEPTION = "@exception"; //$NON-NLS-1$
-
- /**
- * Standard inline doc tag name (value {@value}).
- */
- public static final String TAG_INHERITDOC = "@inheritDoc"; //$NON-NLS-1$
-
- /**
- * Standard inline doc tag name (value {@value}).
- */
- public static final String TAG_LINK = "@link"; //$NON-NLS-1$
-
- /**
- * Standard inline doc tag name (value {@value}).
- */
- public static final String TAG_LINKPLAIN = "@linkplain"; //$NON-NLS-1$
-
- /**
- * Standard inline doc tag name (value {@value}).
- * <p>
- * Note that this tag first appeared in J2SE 5.
- * </p>
- *
- */
- public static final String TAG_LITERAL = "@literal"; //$NON-NLS-1$
-
- /**
- * Standard doc tag name (value {@value}).
- */
- public static final String TAG_PARAM = "@param"; //$NON-NLS-1$
-
- /**
- * Standard doc tag name (value {@value}).
- */
- public static final String TAG_RETURN = "@return"; //$NON-NLS-1$
-
- /**
- * Standard doc tag name (value {@value}).
- */
- public static final String TAG_SEE = "@see"; //$NON-NLS-1$
-
- /**
- * Standard doc tag name (value {@value}).
- */
- public static final String TAG_SERIAL = "@serial"; //$NON-NLS-1$
-
- /**
- * Standard doc tag name (value {@value}).
- */
- public static final String TAG_SERIALDATA= "@serialData"; //$NON-NLS-1$
-
- /**
- * Standard doc tag name (value {@value}).
- */
- public static final String TAG_SERIALFIELD= "@serialField"; //$NON-NLS-1$
-
- /**
- * Standard doc tag name (value {@value}).
- */
- public static final String TAG_SINCE = "@since"; //$NON-NLS-1$
-
- /**
- * Standard doc tag name (value {@value}).
- */
- public static final String TAG_THROWS = "@throws"; //$NON-NLS-1$
-
- /**
- * Standard inline doc tag name (value {@value}).
- */
- public static final String TAG_VALUE= "@value"; //$NON-NLS-1$
-
- /**
- * Standard doc tag name (value {@value}).
- */
- public static final String TAG_VERSION = "@version"; //$NON-NLS-1$
-
- /**
- * The tag name, or null if none; defaults to null.
- */
- private String optionalTagName = null;
-
- /**
- * The list of doc elements (element type: <code>IDocElement</code>).
- * Defaults to an empty list.
- */
- private ASTNode.NodeList fragments =
- new ASTNode.NodeList(FRAGMENTS_PROPERTY);
-
- /**
- * Creates a new AST node for a tag element owned by the given AST.
- * The new node has no name and an empty list of fragments.
- * <p>
- * N.B. This constructor is package-private; all subclasses must be
- * declared in the same package; clients are unable to declare
- * additional subclasses.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- TagElement(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final Object internalGetSetObjectProperty(SimplePropertyDescriptor property, boolean get, Object value) {
- if (property == TAG_NAME_PROPERTY) {
- if (get) {
- return getTagName();
- } else {
- setTagName((String) value);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetObjectProperty(property, get, value);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalGetChildListProperty(ChildListPropertyDescriptor property) {
- if (property == FRAGMENTS_PROPERTY) {
- return fragments();
- }
- // allow default implementation to flag the error
- return super.internalGetChildListProperty(property);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return TAG_ELEMENT;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- TagElement result = new TagElement(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setTagName(getTagName());
- result.fragments().addAll(ASTNode.copySubtrees(target, fragments()));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- acceptChildren(visitor, this.fragments);
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns this node's tag name, or <code>null</code> if none.
- * For top level doc tags such as parameter tags, the tag name
- * includes the "@" character ("@param").
- * For inline doc tags such as link tags, the tag name
- * includes the "@" character ("@link").
- * The tag name may also be <code>null</code>; this is used to
- * represent the material at the start of a doc comment preceding
- * the first explicit tag.
- *
- * @return the tag name, or <code>null</code> if none
- */
- public String getTagName() {
- return this.optionalTagName;
- }
-
- /**
- * Sets the tag name of this node to the given value.
- * For top level doc tags such as parameter tags, the tag name
- * includes the "@" character ("@param").
- * For inline doc tags such as link tags, the tag name
- * includes the "@" character ("@link").
- * The tag name may also be <code>null</code>; this is used to
- * represent the material at the start of a doc comment preceding
- * the first explicit tag.
- *
- * @param tagName the tag name, or <code>null</code> if none
- */
- public void setTagName(String tagName) {
- preValueChange(TAG_NAME_PROPERTY);
- this.optionalTagName = tagName;
- postValueChange(TAG_NAME_PROPERTY);
- }
-
- /**
- * Returns the live list of fragments in this tag element.
- * <p>
- * The fragments cover everything following the tag name
- * (or everything if there is no tag name), and generally omit
- * embedded line breaks (and leading whitespace on new lines,
- * including any leading "*"). {@link org.eclipse.wst.jsdt.core.dom.TagElement}
- * nodes are used to represent tag elements (e.g., "@link")
- * nested within this tag element.
- * </p>
- * <p>
- * Here are some typical examples:
- * <ul>
- * <li>"@see Foo#bar()" - TagElement with tag name "@see";
- * fragments() contains a single FunctionRef node</li>
- * <li>"@param args the program arguments" -
- * TagElement with tag name "@param";
- * 2 fragments: SimpleName ("args"), TextElement
- * (" the program arguments")</li>
- * <li>"@return See {&#64;link #foo foo} instead." -
- * TagElement with tag name "@return";
- * 3 fragments: TextElement ("See "),
- * TagElement (for "&#64;link #foo foo"),
- * TextElement (" instead.")</li>
- * </ul>
- * The use of Name, FunctionRef, and MemberRef nodes within
- * tag elements allows these fragments to be queried for
- * binding information.
- * </p>
- * <p>
- * Adding and removing nodes from this list affects this node
- * dynamically. The nodes in this list may be of various
- * types, including {@link TextElement},
- * {@link org.eclipse.wst.jsdt.core.dom.TagElement}, {@link Name},
- * {@link MemberRef}, and {@link FunctionRef}.
- * Clients should assume that the list of types may grow in
- * the future, and write their code to deal with unexpected
- * nodes types. However, attempts to add a non-proscribed type
- * of node will trigger an exception.
- *
- * @return the live list of doc elements in this tag element
- * (element type: <code>ASTNode</code>)
- */
- public List fragments() {
- return this.fragments;
- }
-
- /**
- * Returns whether this tag element is nested within another
- * tag element. Nested tag elements appears enclosed in
- * "{" and "}"; certain doc tags, including "@link" and
- * "@linkplain" are only meaningful as nested tags.
- * Top-level (i.e., non-nested) doc tags begin on a new line;
- * certain doc tags, including "@param" and
- * "@see" are only meaningful as top-level tags.
- * <p>
- * This convenience methods checks to see whether the parent
- * of this node is of type {@link org.eclipse.wst.jsdt.core.dom.TagElement}.
- * </p>
- *
- * @return <code>true</code> if this node is a nested tag element,
- * and false if this node is either parented by a doc comment node
- * ({@link JSdoc}), or is unparented
- */
- public boolean isNested() {
- return (getParent() instanceof TagElement);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- int size = BASE_NODE_SIZE + 2 * 4 + stringSize(this.optionalTagName);
- return size;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return memSize() + this.fragments.listSize();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TextElement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TextElement.java
deleted file mode 100644
index 1133bf81..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TextElement.java
+++ /dev/null
@@ -1,201 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.wst.jsdt.internal.compiler.util.Util;
-
-/**
- * AST node for a text element within a doc comment.
- * <pre>
- * TextElement:
- * Sequence of characters not including a close comment delimiter <b>*</b><b>/</b>
- * </pre>
- *
- * @see JSdoc
- *
- * 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 final class TextElement extends ASTNode implements IDocElement {
-
- /**
- * The "test" structural property of this node type.
- *
- *
- */
- public static final SimplePropertyDescriptor TEXT_PROPERTY =
- new SimplePropertyDescriptor(TextElement.class, "text", String.class, MANDATORY); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List propertyList = new ArrayList(2);
- createPropertyList(TextElement.class, propertyList);
- addProperty(TEXT_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The text element; defaults to the empty string.
- */
- private String text = Util.EMPTY_STRING;
-
- /**
- * Creates a new AST node for a text element owned by the given AST.
- * The new node has an empty text string.
- * <p>
- * N.B. This constructor is package-private; all subclasses must be
- * declared in the same package; clients are unable to declare
- * additional subclasses.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- TextElement(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final Object internalGetSetObjectProperty(SimplePropertyDescriptor property, boolean get, Object value) {
- if (property == TEXT_PROPERTY) {
- if (get) {
- return getText();
- } else {
- setText((String) value);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetObjectProperty(property, get, value);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return TEXT_ELEMENT;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- TextElement result = new TextElement(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setText(getText());
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- visitor.visit(this);
- visitor.endVisit(this);
- }
-
- /**
- * Returns this node's text.
- *
- * @return the text of this node
- */
- public String getText() {
- return this.text;
- }
-
- /**
- * Sets the text of this node to the given value.
- * <p>
- * The text element typically includes leading and trailing
- * whitespace that separates it from the immediately preceding
- * or following elements. The text element must not include
- * a block comment closing delimiter "*"+"/".
- * </p>
- *
- * @param text the text of this node
- * @exception IllegalArgumentException if the text is null
- * or contains a block comment closing delimiter
- */
- public void setText(String text) {
- if (text == null) {
- throw new IllegalArgumentException();
- }
- if (text.indexOf("*/") > 0) { //$NON-NLS-1$
- throw new IllegalArgumentException();
- }
- preValueChange(TEXT_PROPERTY);
- this.text = text;
- postValueChange(TEXT_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- int size = BASE_NODE_SIZE + 1 * 4;
- if (this.text != Util.EMPTY_STRING) {
- // everything but our empty string costs
- size += stringSize(this.text);
- }
- return size;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return memSize();
- }
-}
-
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
deleted file mode 100644
index 6ef64162..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ThisExpression.java
+++ /dev/null
@@ -1,191 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Simple or qualified "this" AST node type.
- *
- * <pre>
- * ThisExpression:
- * [ ClassName <b>.</b> ] <b>this</b>
- * </pre>
- * <p>
- * See <code>FieldAccess</code> for guidelines on handling other expressions
- * that resemble qualified names.
- * </p>
- *
- * @see FieldAccess
- *
- * 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 ThisExpression extends Expression {
-
- /**
- * The "qualifier" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor QUALIFIER_PROPERTY =
- new ChildPropertyDescriptor(ThisExpression.class, "qualifier", Name.class, OPTIONAL, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List propertyList = new ArrayList(2);
- createPropertyList(ThisExpression.class, propertyList);
- addProperty(QUALIFIER_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The optional qualifier; <code>null</code> for none; defaults to none.
- */
- private Name optionalQualifier = null;
-
- /**
- * Creates a new AST node for a "this" expression owned by the
- * given AST. By default, there is no qualifier.
- *
- * @param ast the AST that is to own this node
- */
- ThisExpression(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == QUALIFIER_PROPERTY) {
- if (get) {
- return getQualifier();
- } else {
- setQualifier((Name) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return THIS_EXPRESSION;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- ThisExpression result = new ThisExpression(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setQualifier((Name) ASTNode.copySubtree(target, getQualifier()));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- acceptChild(visitor, getQualifier());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the qualifier of this "this" expression, or
- * <code>null</code> if there is none.
- *
- * @return the qualifier name node, or <code>null</code> if there is none
- */
- public Name getQualifier() {
- return this.optionalQualifier;
- }
-
- /**
- * Sets or clears the qualifier of this "this" expression.
- *
- * @param name the qualifier name node, or <code>null</code> if
- * there is none
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public void setQualifier(Name name) {
- ASTNode oldChild = this.optionalQualifier;
- preReplaceChild(oldChild, name, QUALIFIER_PROPERTY);
- this.optionalQualifier = name;
- postReplaceChild(oldChild, name, QUALIFIER_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- // treat Operator as free
- return BASE_NODE_SIZE + 1 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.optionalQualifier == null ? 0 : getQualifier().treeSize());
- }
-}
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
deleted file mode 100644
index 719a4f3e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ThrowStatement.java
+++ /dev/null
@@ -1,203 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Throw statement AST node type.
- *
- * <pre>
- * ThrowStatement:
- * <b>throw</b> Expression <b>;</b>
- * </pre>
- *
- * 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 ThrowStatement extends Statement {
-
- /**
- * The "expression" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor EXPRESSION_PROPERTY =
- new ChildPropertyDescriptor(ThrowStatement.class, "expression", Expression.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List propertyList = new ArrayList(2);
- createPropertyList(ThrowStatement.class, propertyList);
- addProperty(EXPRESSION_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The expression; lazily initialized; defaults to a unspecified, but legal,
- * expression.
- */
- private Expression expression = null;
-
- /**
- * Creates a new unparented throw statement node owned by the given
- * AST. By default, the throw statement has an unspecified, but legal,
- * expression.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- ThrowStatement(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == EXPRESSION_PROPERTY) {
- if (get) {
- return getExpression();
- } else {
- setExpression((Expression) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return THROW_STATEMENT;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- ThrowStatement result = new ThrowStatement(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.copyLeadingComment(this);
- result.setExpression((Expression) getExpression().clone(target));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- acceptChild(visitor, getExpression());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the expression of this throw statement.
- *
- * @return the expression node
- */
- public Expression getExpression() {
- if (this.expression == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.expression == null) {
- preLazyInit();
- this.expression = new SimpleName(this.ast);
- postLazyInit(this.expression, EXPRESSION_PROPERTY);
- }
- }
- }
- return this.expression;
- }
-
- /**
- * Sets the expression of this throw statement.
- *
- * @param expression the new expression node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setExpression(Expression expression) {
- if (expression == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.expression;
- preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY);
- this.expression = expression;
- postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return super.memSize() + 1 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.expression == null ? 0 : getExpression().treeSize());
- }
-}
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
deleted file mode 100644
index b3908171..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TryStatement.java
+++ /dev/null
@@ -1,301 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Try statement AST node type.
- *
- * <pre>
- * TryStatement:
- * <b>try</b> Block
- * { CatchClause }
- * [ <b>finally</b> Block ]
- * </pre>
- *
- * 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 TryStatement extends Statement {
-
- /**
- * The "body" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor BODY_PROPERTY =
- new ChildPropertyDescriptor(TryStatement.class, "body", Block.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "catchClauses" structural property of this node type.
- *
- */
- public static final ChildListPropertyDescriptor CATCH_CLAUSES_PROPERTY =
- new ChildListPropertyDescriptor(TryStatement.class, "catchClauses", CatchClause.class, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "finally" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor FINALLY_PROPERTY =
- new ChildPropertyDescriptor(TryStatement.class, "finally", Block.class, OPTIONAL, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List propertyList = new ArrayList(4);
- createPropertyList(TryStatement.class, propertyList);
- addProperty(BODY_PROPERTY, propertyList);
- addProperty(CATCH_CLAUSES_PROPERTY, propertyList);
- addProperty(FINALLY_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The body; lazily initialized; defaults to an empty block.
- */
- private Block body = null;
-
- /**
- * The catch clauses (element type: <code>CatchClause</code>).
- * Defaults to an empty list.
- */
- private ASTNode.NodeList catchClauses =
- new ASTNode.NodeList(CATCH_CLAUSES_PROPERTY);
-
- /**
- * The finally block, or <code>null</code> if none.
- * Defaults to none.
- */
- private Block optionalFinallyBody = null;
-
-
- /**
- * Creates a new AST node for a try statement owned by the given
- * AST. By default, the try statement has an empty block, no catch
- * clauses, and no finally block.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- TryStatement(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == BODY_PROPERTY) {
- if (get) {
- return getBody();
- } else {
- setBody((Block) child);
- return null;
- }
- }
- if (property == FINALLY_PROPERTY) {
- if (get) {
- return getFinally();
- } else {
- setFinally((Block) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalGetChildListProperty(ChildListPropertyDescriptor property) {
- if (property == CATCH_CLAUSES_PROPERTY) {
- return catchClauses();
- }
- // allow default implementation to flag the error
- return super.internalGetChildListProperty(property);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return TRY_STATEMENT;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- TryStatement result = new TryStatement(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.copyLeadingComment(this);
- result.setBody((Block) getBody().clone(target));
- result.catchClauses().addAll(
- ASTNode.copySubtrees(target, catchClauses()));
- result.setFinally(
- (Block) ASTNode.copySubtree(target, getFinally()));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChild(visitor, getBody());
- acceptChildren(visitor, this.catchClauses);
- acceptChild(visitor, getFinally());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the body of this try statement.
- *
- * @return the try body
- */
- public Block getBody() {
- if (this.body == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.body == null) {
- preLazyInit();
- this.body = new Block(this.ast);
- postLazyInit(this.body, BODY_PROPERTY);
- }
- }
- }
- return this.body;
- }
-
- /**
- * Sets the body of this try statement.
- *
- * @param body the block node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setBody(Block body) {
- if (body == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.body;
- preReplaceChild(oldChild, body, BODY_PROPERTY);
- this.body = body;
- postReplaceChild(oldChild, body, BODY_PROPERTY);
- }
-
- /**
- * Returns the live ordered list of catch clauses for this try statement.
- *
- * @return the live list of catch clauses
- * (element type: <code>CatchClause</code>)
- */
- public List catchClauses() {
- return this.catchClauses;
- }
-
- /**
- * Returns the finally block of this try statement, or <code>null</code> if
- * this try statement has <b>no</b> finally block.
- *
- * @return the finally block, or <code>null</code> if this try statement
- * has none
- */
- public Block getFinally() {
- return this.optionalFinallyBody;
- }
-
- /**
- * Sets or clears the finally block of this try statement.
- *
- * @param block the finally block node, or <code>null</code> if
- * there is none
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setFinally(Block block) {
- ASTNode oldChild = this.optionalFinallyBody;
- preReplaceChild(oldChild, block, FINALLY_PROPERTY);
- this.optionalFinallyBody = block;
- postReplaceChild(oldChild, block, FINALLY_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return super.memSize() + 3 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.body == null ? 0 : getBody().treeSize())
- + this.catchClauses.listSize()
- + (this.optionalFinallyBody == null ? 0 : getFinally().treeSize());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Type.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Type.java
deleted file mode 100644
index 449d17aa..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Type.java
+++ /dev/null
@@ -1,146 +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.core.dom;
-
-/**
- * Abstract base class of all type AST node types. A type node represents a
- * reference to a primitive type (including void), to an array type, or to a
- * simple named type (or type variable), to a qualified type, or to a
- * parameterized type. Note that not all of these
- * are meaningful in all contexts.
- * <p>
- * <pre>
- * Type:
- * PrimitiveType
- * ArrayType
- * SimpleType
- * QualifiedType
- * ParameterizedType
- * PrimitiveType:
- * <b>byte</b>
- * <b>short</b>
- * <b>char</b>
- * <b>int</b>
- * <b>long</b>
- * <b>float</b>
- * <b>double</b>
- * <b>boolean</b>
- * <b>void</b>
- * ArrayType:
- * Type <b>[</b> <b>]</b>
- * SimpleType:
- * TypeName
- * QualifiedType:
- * Type <b>.</b> SimpleName
- * </pre>
- * </p>
- *
- * 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 Type extends ASTNode {
-
- /**
- * Creates a new AST node for a type owned by the given AST.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- Type(AST ast) {
- super(ast);
- }
-
- /**
- * Returns whether this type is a primitive type
- * (<code>PrimitiveType</code>).
- *
- * @return <code>true</code> if this is a primitive type, and
- * <code>false</code> otherwise
- */
- public final boolean isPrimitiveType() {
- return (this instanceof PrimitiveType);
- }
-
- /**
- * Returns whether this type is a simple type
- * (<code>SimpleType</code>).
- *
- * @return <code>true</code> if this is a simple type, and
- * <code>false</code> otherwise
- */
- public final boolean isSimpleType() {
- return (this instanceof SimpleType);
- }
-
- /**
- * Returns whether this type is an array type
- * (<code>ArrayType</code>).
- *
- * @return <code>true</code> if this is an array type, and
- * <code>false</code> otherwise
- */
- public final boolean isArrayType() {
- return (this instanceof ArrayType);
- }
-
- /**
- * Returns whether this type is a qualified type
- * (<code>QualifiedType</code>).
- * <p>
- * Note that a type like "A.B" can be represented either of two ways:
- * <ol>
- * <li>
- * <code>QualifiedType(SimpleType(SimpleName("A")),SimpleName("B"))</code>
- * </li>
- * <li>
- * <code>SimpleType(QualifiedName(SimpleName("A"),SimpleName("B")))</code>
- * </li>
- * </ol>
- * The first form is preferred when "A" is known to be a type. However, a
- * parser cannot always determine this. Clients should be prepared to handle
- * either rather than make assumptions. (Note also that the first form
- * became possible as of JLS3; only the second form existed in the
- * JLS2 API.)
- * </p>
- *
- * @return <code>true</code> if this is a qualified type, and
- * <code>false</code> otherwise
- *
- */
- public final boolean isQualifiedType() {
- return (this instanceof QualifiedType);
- }
-
- /**
- * Resolves and returns the binding for this type.
- * <p>
- * Note that bindings are generally unavailable unless requested when the
- * AST is being built.
- * </p>
- *
- * @return the type binding, or <code>null</code> if the binding cannot be
- * resolved
- */
- public final ITypeBinding resolveBinding() {
- return this.ast.getBindingResolver().resolveType(this);
- }
-
- public boolean isInferred()
- {
- return false;
- }
-
-}
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
deleted file mode 100644
index 4480c424..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TypeBinding.java
+++ /dev/null
@@ -1,824 +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.core.dom;
-
-import java.io.File;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-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.IJavaScriptProject;
-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.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Expression;
-import org.eclipse.wst.jsdt.internal.compiler.env.IDependent;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ArrayBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BaseTypeBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Binding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.FieldBinding;
-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.PackageBinding;
-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.problem.AbortCompilation;
-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.ClassFile;
-import org.eclipse.wst.jsdt.internal.core.JavaElement;
-
-/**
- * Internal implementation of type bindings.
- */
-class TypeBinding implements ITypeBinding {
- protected static final IFunctionBinding[] NO_METHOD_BINDINGS = new IFunctionBinding[0];
-
- private static final String NO_NAME = ""; //$NON-NLS-1$
- protected static final ITypeBinding[] NO_TYPE_BINDINGS = new ITypeBinding[0];
- protected static final IVariableBinding[] NO_VARIABLE_BINDINGS = new IVariableBinding[0];
-
- private static final int VALID_MODIFIERS = Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE |
- Modifier.ABSTRACT | Modifier.STATIC | Modifier.FINAL | Modifier.STRICTFP;
-
- org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding binding;
- private String key;
- private BindingResolver resolver;
- private IVariableBinding[] fields;
- private IFunctionBinding[] methods;
- private ITypeBinding[] members;
-
- public TypeBinding(BindingResolver resolver, org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding binding) {
- this.binding = binding;
- this.resolver = resolver;
- }
-
- public ITypeBinding createArrayType(int dimension) {
- int realDimensions = dimension;
- realDimensions += this.getDimensions();
- if (realDimensions < 1 || realDimensions > 255) {
- throw new IllegalArgumentException();
- }
- return this.resolver.resolveArrayType(this, dimension);
- }
-
-
- /*
- * @see ITypeBinding#getBinaryName()
- *
- */
- public String getBinaryName() {
- char[] constantPoolName = this.binding.constantPoolName();
- if (constantPoolName == null) return null;
- char[] dotSeparated = CharOperation.replaceOnCopy(constantPoolName, '/', '.');
- return new String(dotSeparated);
- }
-
- /*
- * Returns the class file for the given file name, or null if not found.
- * @see org.eclipse.wst.jsdt.internal.compiler.env.IDependent#getFileName()
- */
- private IClassFile getClassFile(char[] fileName) {
- int jarSeparator = CharOperation.indexOf(IDependent.JAR_FILE_ENTRY_SEPARATOR, fileName);
- int pkgEnd = CharOperation.lastIndexOf('/', fileName); // pkgEnd is exclusive
- if (pkgEnd == -1)
- pkgEnd = CharOperation.lastIndexOf(File.separatorChar, fileName);
- if (jarSeparator != -1 && pkgEnd < jarSeparator) // if in a jar and no slash, it is a default package -> pkgEnd should be equal to jarSeparator
- pkgEnd = jarSeparator;
- if (pkgEnd == -1)
- return null;
- IPackageFragment pkg = getPackageFragment(fileName, pkgEnd, jarSeparator);
- if (pkg == null) return null;
- int start;
- return pkg.getClassFile(new String(fileName, start = pkgEnd + 1, fileName.length - start));
- }
-
- /*
- * Returns the javaScript unit for the given file name, or null if not found.
- * @see org.eclipse.wst.jsdt.internal.compiler.env.IDependent#getFileName()
- */
- private IJavaScriptUnit getCompilationUnit(char[] fileName) {
- char[] slashSeparatedFileName = CharOperation.replaceOnCopy(fileName, File.separatorChar, '/');
- int pkgEnd = CharOperation.lastIndexOf('/', slashSeparatedFileName); // pkgEnd is exclusive
- if (pkgEnd == -1)
- return null;
- IPackageFragment pkg = getPackageFragment(slashSeparatedFileName, pkgEnd, -1/*no jar separator for .js files*/);
- if (pkg == null) return null;
- int start;
- IJavaScriptUnit cu = pkg.getJavaScriptUnit(new String(slashSeparatedFileName, start = pkgEnd+1, slashSeparatedFileName.length - start));
- if (this.resolver instanceof DefaultBindingResolver) {
- IJavaScriptUnit workingCopy = cu.findWorkingCopy(((DefaultBindingResolver) this.resolver).workingCopyOwner);
- if (workingCopy != null)
- return workingCopy;
- }
- return cu;
- }
-
- /*
- * @see ITypeBinding#getComponentType()
- */
- public ITypeBinding getComponentType() {
- if (!this.isArray()) {
- return null;
- }
- ArrayBinding arrayBinding = (ArrayBinding) binding;
- return resolver.getTypeBinding(arrayBinding.elementsType());
- }
-
- /*
- * @see ITypeBinding#getDeclaredFields()
- */
- public synchronized IVariableBinding[] getDeclaredFields() {
- if (this.fields != null) {
- return this.fields;
- }
- try {
- if (isClass()) {
- ReferenceBinding referenceBinding = (ReferenceBinding) this.binding;
- FieldBinding[] fieldBindings = referenceBinding.availableFields(); // resilience
- int length = fieldBindings.length;
- if (length != 0) {
- IVariableBinding[] newFields = new IVariableBinding[length];
- for (int i = 0; i < length; i++) {
- IVariableBinding variableBinding = this.resolver.getVariableBinding(fieldBindings[i]);
- if (variableBinding == null) {
- return this.fields = NO_VARIABLE_BINDINGS;
- }
- newFields[i] = variableBinding;
- }
- return this.fields = newFields;
- }
- }
- } 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
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299
- */
- org.eclipse.wst.jsdt.internal.core.util.Util.log(e, "Could not retrieve declared fields"); //$NON-NLS-1$
- }
- return this.fields = NO_VARIABLE_BINDINGS;
- }
-
- /*
- * @see ITypeBinding#getDeclaredMethods()
- */
- public synchronized IFunctionBinding[] getDeclaredMethods() {
- if (this.methods != null) {
- return this.methods;
- }
- try {
- if (isClass()) {
- ReferenceBinding referenceBinding = (ReferenceBinding) this.binding;
- org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding[] internalMethods = referenceBinding.availableMethods(); // be resilient
- int length = internalMethods.length;
- if (length != 0) {
- int removeSyntheticsCounter = 0;
- IFunctionBinding[] newMethods = new IFunctionBinding[length];
- for (int i = 0; i < length; i++) {
- org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding methodBinding = internalMethods[i];
- if (!shouldBeRemoved(methodBinding)) {
- IFunctionBinding methodBinding2 = this.resolver.getMethodBinding(methodBinding);
- if (methodBinding2 != null) {
- newMethods[removeSyntheticsCounter++] = methodBinding2;
- }
- }
- }
- if (removeSyntheticsCounter != length) {
- System.arraycopy(newMethods, 0, (newMethods = new IFunctionBinding[removeSyntheticsCounter]), 0, removeSyntheticsCounter);
- }
- return this.methods = newMethods;
- }
- }
- } 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
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299
- */
- org.eclipse.wst.jsdt.internal.core.util.Util.log(e, "Could not retrieve declared methods"); //$NON-NLS-1$
- }
- return this.methods = NO_METHOD_BINDINGS;
- }
-
- /*
- * @see ITypeBinding#getDeclaredModifiers()
- */
- public int getDeclaredModifiers() {
- return getModifiers();
- }
-
- /*
- * @see ITypeBinding#getDeclaredTypes()
- */
- public synchronized ITypeBinding[] getDeclaredTypes() {
- if (this.members != null) {
- return this.members;
- }
- try {
- if (isClass()) {
- ReferenceBinding referenceBinding = (ReferenceBinding) this.binding;
- ReferenceBinding[] internalMembers = referenceBinding.memberTypes();
- int length = internalMembers.length;
- if (length != 0) {
- ITypeBinding[] newMembers = new ITypeBinding[length];
- for (int i = 0; i < length; i++) {
- ITypeBinding typeBinding = this.resolver.getTypeBinding(internalMembers[i]);
- if (typeBinding == null) {
- return this.members = NO_TYPE_BINDINGS;
- }
- newMembers[i] = typeBinding;
- }
- return this.members = newMembers;
- }
- }
- } 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
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299
- */
- org.eclipse.wst.jsdt.internal.core.util.Util.log(e, "Could not retrieve declared methods"); //$NON-NLS-1$
- }
- return this.members = NO_TYPE_BINDINGS;
- }
-
- /*
- * @see ITypeBinding#getDeclaringMethod()
- */
- public synchronized IFunctionBinding getDeclaringMethod() {
- if (this.binding instanceof LocalTypeBinding) {
- LocalTypeBinding localTypeBinding = (LocalTypeBinding) this.binding;
- MethodBinding methodBinding = localTypeBinding.enclosingMethod;
- if (methodBinding != null) {
- try {
- return this.resolver.getMethodBinding(localTypeBinding.enclosingMethod);
- } 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
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299
- */
- org.eclipse.wst.jsdt.internal.core.util.Util.log(e, "Could not retrieve declaring method"); //$NON-NLS-1$
- }
- }
- }
- return null;
- }
-
- /*
- * @see ITypeBinding#getDeclaringClass()
- */
- public synchronized ITypeBinding getDeclaringClass() {
- if (isClass()) {
- ReferenceBinding referenceBinding = (ReferenceBinding) this.binding;
- if (referenceBinding.isNestedType()) {
- try {
- return this.resolver.getTypeBinding(referenceBinding.enclosingType());
- } 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
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299
- */
- org.eclipse.wst.jsdt.internal.core.util.Util.log(e, "Could not retrieve declaring class"); //$NON-NLS-1$
- }
- }
- }
- return null;
- }
-
- /*
- * @see ITypeBinding#getDimensions()
- */
- public int getDimensions() {
- if (!this.isArray()) {
- return 0;
- }
- ArrayBinding arrayBinding = (ArrayBinding) binding;
- return arrayBinding.dimensions;
- }
-
- /*
- * @see ITypeBinding#getElementType()
- */
- public ITypeBinding getElementType() {
- if (!this.isArray()) {
- return null;
- }
- ArrayBinding arrayBinding = (ArrayBinding) binding;
- return resolver.getTypeBinding(arrayBinding.leafComponentType);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#getTypeDeclaration()
- */
- public ITypeBinding getTypeDeclaration() {
- return this;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#getErasure()
- */
- public ITypeBinding getErasure() {
- return this.resolver.getTypeBinding(this.binding);
- }
-
- public IJavaScriptElement getJavaElement() {
- JavaElement element = getUnresolvedJavaElement();
- if (element == null)
- return null;
- return element.resolved(this.binding);
- }
-
- private JavaElement getUnresolvedJavaElement() {
- return getUnresolvedJavaElement(this.binding);
- }
- private JavaElement getUnresolvedJavaElement(org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding typeBinding ) {
- if (typeBinding == null)
- return null;
- switch (typeBinding.kind()) {
- case Binding.ARRAY_TYPE :
- typeBinding = ((ArrayBinding) typeBinding).leafComponentType();
- return getUnresolvedJavaElement(typeBinding);
- case Binding.BASE_TYPE :
- return null;
- }
- ReferenceBinding referenceBinding = (ReferenceBinding) typeBinding;
- char[] fileName = referenceBinding.getFileName();
- if (referenceBinding.isLocalType() || referenceBinding.isAnonymousType()) {
- // local or anonymous type
- if (Util.isClassFileName(fileName)) {
- int jarSeparator = CharOperation.indexOf(IDependent.JAR_FILE_ENTRY_SEPARATOR, fileName);
- int pkgEnd = CharOperation.lastIndexOf('/', fileName); // pkgEnd is exclusive
- if (pkgEnd == -1)
- pkgEnd = CharOperation.lastIndexOf(File.separatorChar, fileName);
- if (jarSeparator != -1 && pkgEnd < jarSeparator) // if in a jar and no slash, it is a default package -> pkgEnd should be equal to jarSeparator
- pkgEnd = jarSeparator;
- if (pkgEnd == -1)
- return null;
- IPackageFragment pkg = getPackageFragment(fileName, pkgEnd, jarSeparator);
- char[] constantPoolName = referenceBinding.constantPoolName();
- if (constantPoolName == null) {
- ClassFile classFile = (ClassFile) getClassFile(fileName);
- return classFile == null ? null : (JavaElement) classFile.getType();
- }
- pkgEnd = CharOperation.lastIndexOf('/', constantPoolName);
- char[] classFileName = CharOperation.subarray(constantPoolName, pkgEnd+1, constantPoolName.length);
- ClassFile classFile = (ClassFile) pkg.getClassFile(new String(classFileName) + SuffixConstants.SUFFIX_STRING_java);
- return (JavaElement) classFile.getType();
- }
- IJavaScriptUnit cu = getCompilationUnit(fileName);
- if (cu == null) return null;
- // must use getElementAt(...) as there is no back pointer to the defining method (scope is null after resolution has ended)
- try {
- int sourceStart = ((LocalTypeBinding) referenceBinding).sourceStart;
- return (JavaElement) cu.getElementAt(sourceStart);
- } catch (JavaScriptModelException e) {
- // does not exist
- return null;
- }
- } else {
- if (fileName == null) return null; // case of a WilCardBinding that doesn't have a corresponding JavaScript element
- // member or top level type
- ITypeBinding declaringTypeBinding = null;
- if (this.isArray()) {
- declaringTypeBinding = this.getElementType().getDeclaringClass();
- } else {
- declaringTypeBinding = this.getDeclaringClass();
- }
- if (declaringTypeBinding == null) {
- // top level type
- if (Util.isClassFileName(fileName)) {
- ClassFile classFile = (ClassFile) getClassFile(fileName);
- if (classFile == null) return null;
- return (JavaElement) classFile.getType();
- }
- IJavaScriptUnit cu = getCompilationUnit(fileName);
- if (cu == null) return null;
- return (JavaElement) cu.getType(new String(referenceBinding.sourceName()));
- } else {
- // member type
- IType declaringType = (IType) declaringTypeBinding.getJavaElement();
- if (declaringType == null) return null;
- return (JavaElement) declaringType.getType(new String(referenceBinding.sourceName()));
- }
- }
- }
-
- /*
- * @see IBinding#getKey()
- */
- public String getKey() {
- if (this.key == null) {
- this.key = new String(this.binding.computeUniqueKey());
- }
- return this.key;
- }
-
- /*
- * @see IBinding#getKind()
- */
- public int getKind() {
- return IBinding.TYPE;
- }
-
- /*
- * @see IBinding#getModifiers()
- */
- public int getModifiers() {
- if (isClass()) {
- ReferenceBinding referenceBinding = (ReferenceBinding) this.binding;
- final int accessFlags = referenceBinding.getAccessFlags() & VALID_MODIFIERS;
- if (referenceBinding.isAnonymousType()) {
- return accessFlags & ~Modifier.FINAL;
- }
- return accessFlags;
- } else {
- return Modifier.NONE;
- }
- }
-
- public String getName() {
- StringBuffer buffer;
- switch (this.binding.kind()) {
-
- case Binding.ARRAY_TYPE :
- ITypeBinding elementType = getElementType();
- if (elementType.isLocal() || elementType.isAnonymous()) {
- return NO_NAME;
- }
- int dimensions = getDimensions();
- char[] brackets = new char[dimensions * 2];
- for (int i = dimensions * 2 - 1; i >= 0; i -= 2) {
- brackets[i] = ']';
- brackets[i - 1] = '[';
- }
- buffer = new StringBuffer(elementType.getName());
- buffer.append(brackets);
- return String.valueOf(buffer);
-
- default :
- if (isPrimitive() || isNullType()) {
- BaseTypeBinding baseTypeBinding = (BaseTypeBinding) this.binding;
- return new String(baseTypeBinding.simpleName);
- }
- if (isAnonymous()) {
- return NO_NAME;
- }
- return new String(this.binding.sourceName());
- }
- }
-
- /*
- * @see ITypeBinding#getPackage()
- */
- public IPackageBinding getPackage() {
- switch (this.binding.kind()) {
- case Binding.BASE_TYPE :
- case Binding.ARRAY_TYPE :
- return null;
- }
- ReferenceBinding referenceBinding = (ReferenceBinding) this.binding;
- return this.resolver.getPackageBinding(referenceBinding.getPackage());
- }
-
- /*
- * Returns the package that includes the given file name, or null if not found.
- * pkgEnd == jarSeparator if default package in a jar
- * pkgEnd > jarSeparator if non default package in a jar
- * pkgEnd > 0 if package not in a jar
- *
- * @see org.eclipse.wst.jsdt.internal.compiler.env.IDependent#getFileName()
- */
- private IPackageFragment getPackageFragment(char[] fileName, int pkgEnd, int jarSeparator) {
- if (jarSeparator != -1) {
- String jarMemento = new String(fileName, 0, jarSeparator);
- IPackageFragmentRoot root = (IPackageFragmentRoot) JavaScriptCore.create(jarMemento);
- if (pkgEnd == jarSeparator)
- return root.getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME);
- char[] pkgName = CharOperation.subarray(fileName, jarSeparator+1, pkgEnd);
- CharOperation.replace(pkgName, '/', '.');
- return root.getPackageFragment(new String(pkgName));
- } else {
- Path path = new Path(new String(fileName, 0, pkgEnd));
- IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
- IContainer folder = path.segmentCount() == 1 ? workspaceRoot.getProject(path.lastSegment()) : (IContainer) workspaceRoot.getFolder(path);
- IJavaScriptElement element = JavaScriptCore.create(folder);
- if (element == null) return null;
- switch (element.getElementType()) {
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- return (IPackageFragment) element;
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- return ((IPackageFragmentRoot) element).getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME);
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- IPackageFragmentRoot root = ((IJavaScriptProject) element).getPackageFragmentRoot(folder);
- if (root == null) return null;
- return root.getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME);
- }
- return null;
- }
- }
-
- /**
- * @see org.eclipse.wst.jsdt.core.dom.ITypeBinding#getQualifiedName()
- */
- public String getQualifiedName() {
- StringBuffer buffer;
- switch (this.binding.kind()) {
-
- case Binding.ARRAY_TYPE :
- ITypeBinding elementType = getElementType();
- if (elementType.isLocal() || elementType.isAnonymous()) {
- return NO_NAME;
- }
- final int dimensions = getDimensions();
- char[] brackets = new char[dimensions * 2];
- for (int i = dimensions * 2 - 1; i >= 0; i -= 2) {
- brackets[i] = ']';
- brackets[i - 1] = '[';
- }
- buffer = new StringBuffer(elementType.getQualifiedName());
- buffer.append(brackets);
- return String.valueOf(buffer);
-
- default :
- if (isAnonymous() || isLocal()) {
- return NO_NAME;
- }
- if (isPrimitive() || isNullType()) {
- BaseTypeBinding baseTypeBinding = (BaseTypeBinding) this.binding;
- return new String(baseTypeBinding.simpleName);
- }
- if (isMember()) {
- buffer = new StringBuffer();
- buffer
- .append(getDeclaringClass().getQualifiedName())
- .append('.');
- buffer.append(getName());
- return String.valueOf(buffer);
- }
- PackageBinding packageBinding = this.binding.getPackage();
- buffer = new StringBuffer();
- if (packageBinding != null && packageBinding.compoundName != CharOperation.NO_CHAR_CHAR) {
- buffer.append(CharOperation.concatWith(packageBinding.compoundName, '.')).append('.');
- }
- buffer.append(getName());
- return String.valueOf(buffer);
- }
- }
-
- /*
- * @see ITypeBinding#getSuperclass()
- */
- public synchronized ITypeBinding getSuperclass() {
- if (this.binding == null)
- return null;
- switch (this.binding.kind()) {
- case Binding.ARRAY_TYPE :
- case Binding.BASE_TYPE :
- return null;
- }
- ReferenceBinding superclass = null;
- try {
- superclass = ((ReferenceBinding)this.binding).superclass();
- } 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
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299
- */
- org.eclipse.wst.jsdt.internal.core.util.Util.log(e, "Could not retrieve superclass"); //$NON-NLS-1$
- return this.resolver.resolveWellKnownType("Object"); //$NON-NLS-1$
- }
- if (superclass == null) {
- return null;
- }
- return this.resolver.getTypeBinding(superclass);
- }
-
- /*
- * @see ITypeBinding#isAnonymous()
- */
- public boolean isAnonymous() {
- if (isClass()) {
- ReferenceBinding referenceBinding = (ReferenceBinding) this.binding;
- return referenceBinding.isAnonymousType();
- }
- return false;
- }
-
- /*
- * @see ITypeBinding#isArray()
- */
- public boolean isArray() {
- return binding.isArrayType();
- }
-
- /* (non-Javadoc)
- * @see ITypeBinding#isAssignmentCompatible(ITypeBinding)
- */
- public boolean isAssignmentCompatible(ITypeBinding type) {
- try {
- if (this == type) return true;
- if (!(type instanceof TypeBinding)) return false;
- TypeBinding other = (TypeBinding) type;
- Scope scope = this.resolver.scope();
- if (scope == null) return false;
- return this.binding.isCompatibleWith(other.binding) || scope.isBoxingCompatibleWith(this.binding, other.binding);
- } catch (AbortCompilation e) {
- // don't surface internal exception to clients
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=143013
- return false;
- }
- }
-
- /* (non-Javadoc)
- * @see ITypeBinding#isCastCompatible(ITypeBinding)
- */
- public boolean isCastCompatible(ITypeBinding type) {
- try {
- Expression expression = new Expression() {
- public StringBuffer printExpression(int indent,StringBuffer output) {
- return null;
- }
- };
- Scope scope = this.resolver.scope();
- if (scope == null) return false;
- if (!(type instanceof TypeBinding)) return false;
- org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding expressionType = ((TypeBinding) type).binding;
- // simulate capture in case checked binding did not properly get extracted from a reference
- return expression.checkCastTypesCompatibility(scope, this.binding, expressionType, null);
- } catch (AbortCompilation e) {
- // don't surface internal exception to clients
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=143013
- return false;
- }
- }
-
- /*
- * @see ITypeBinding#isClass()
- */
- public boolean isClass() {
- return this.binding.isClass();
- }
-
- /*
- * @see IBinding#isDeprecated()
- */
- public boolean isDeprecated() {
- if (isClass()) {
- ReferenceBinding referenceBinding = (ReferenceBinding) this.binding;
- return referenceBinding.isDeprecated();
- }
- return false;
- }
-
- /*
- * @see IBinding#isEqualTo(Binding)
- *
- */
- public boolean isEqualTo(IBinding other) {
- if (other == this) {
- // identical binding - equal (key or no key)
- return true;
- }
- if (other == null) {
- // other binding missing
- return false;
- }
- if (!(other instanceof TypeBinding)) {
- return false;
- }
- org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding otherBinding = ((TypeBinding) other).binding;
- // check return type
- return BindingComparator.isEqual(this.binding, otherBinding);
- }
-
- /*
- * @see ITypeBinding#isFromSource()
- */
- public boolean isFromSource() {
- if (isClass()) {
- ReferenceBinding referenceBinding = (ReferenceBinding) this.binding;
- return !referenceBinding.isBinaryBinding();
- }
- return false;
- }
-
- /*
- * @see ITypeBinding#isLocal()
- */
- public boolean isLocal() {
- if (isClass()) {
- ReferenceBinding referenceBinding = (ReferenceBinding) this.binding;
- return referenceBinding.isLocalType() && !referenceBinding.isMemberType();
- }
- return false;
- }
-
- /*
- * @see ITypeBinding#isMember()
- */
- public boolean isMember() {
- if (isClass()) {
- ReferenceBinding referenceBinding = (ReferenceBinding) this.binding;
- return referenceBinding.isMemberType();
- }
- return false;
- }
-
- /*
- * @see ITypeBinding#isNested()
- */
- public boolean isNested() {
- if (isClass()) {
- ReferenceBinding referenceBinding = (ReferenceBinding) this.binding;
- return referenceBinding.isNestedType();
- }
- return false;
- }
-
- /**
- * @see ITypeBinding#isNullType()
- */
- public boolean isNullType() {
- return this.binding == org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding.NULL;
- }
-
- /*
- * @see ITypeBinding#isPrimitive()
- */
- public boolean isPrimitive() {
- return !isNullType() && binding.isBaseType();
- }
-
- /* (non-Javadoc)
- * @see IBinding#isRecovered()
- */
- public boolean isRecovered() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see ITypeBinding#isSubTypeCompatible(ITypeBinding)
- */
- public boolean isSubTypeCompatible(ITypeBinding type) {
- try {
- if (this == type) return true;
- if (this.binding.isBaseType()) return false;
- if (!(type instanceof TypeBinding)) return false;
- TypeBinding other = (TypeBinding) type;
- if (other.binding.isBaseType()) return false;
- return this.binding.isCompatibleWith(other.binding);
- } catch (AbortCompilation e) {
- // don't surface internal exception to clients
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=143013
- return false;
- }
- }
-
- /*
- * @see ITypeBinding#isTopLevel()
- */
- public boolean isTopLevel() {
- if (isClass()) {
- ReferenceBinding referenceBinding = (ReferenceBinding) this.binding;
- return !referenceBinding.isNestedType();
- }
- return false;
- }
-
- private boolean shouldBeRemoved(org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding methodBinding) {
- return methodBinding.isDefaultAbstract();
- }
-
- /*
- * For debugging purpose only.
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return this.binding.toString();
- }
-
- public boolean isCompilationUnit()
- {
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TypeDeclaration.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TypeDeclaration.java
deleted file mode 100644
index 36986830..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TypeDeclaration.java
+++ /dev/null
@@ -1,635 +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.core.dom;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-/**
- * Type declaration AST node type. A type declaration
- * is the union of a class declaration and an interface declaration.
- * For JLS2:
- * <pre>
- * TypeDeclaration:
- * ClassDeclaration
- * InterfaceDeclaration
- * ClassDeclaration:
- * [ jsdoc ] { Modifier } <b>class</b> Identifier
- * [ <b>extends</b> Type]
- * [ <b>implements</b> Type { <b>,</b> Type } ]
- * <b>{</b> { ClassBodyDeclaration | <b>;</b> } <b>}</b>
- * InterfaceDeclaration:
- * [ jsdoc ] { Modifier } <b>interface</b> Identifier
- * [ <b>extends</b> Type { <b>,</b> Type } ]
- * <b>{</b> { InterfaceBodyDeclaration | <b>;</b> } <b>}</b>
- * </pre>
- * For JLS3, type parameters and reified modifiers
- * (and annotations) were added, and the superclass type name and superinterface
- * types names are generalized to type so that parameterized types can be
- * referenced:
- * <pre>
- * TypeDeclaration:
- * ClassDeclaration
- * InterfaceDeclaration
- * ClassDeclaration:
- * [ jsdoc ] { ExtendedModifier } <b>class</b> Identifier
- * [ <b>&lt;</b> TypeParameter { <b>,</b> TypeParameter } <b>&gt;</b> ]
- * [ <b>extends</b> Type ]
- * [ <b>implements</b> Type { <b>,</b> Type } ]
- * <b>{</b> { ClassBodyDeclaration | <b>;</b> } <b>}</b>
- * InterfaceDeclaration:
- * [ jsdoc ] { ExtendedModifier } <b>interface</b> Identifier
- * [ <b>&lt;</b> TypeParameter { <b>,</b> TypeParameter } <b>&gt;</b> ]
- * [ <b>extends</b> Type { <b>,</b> Type } ]
- * <b>{</b> { InterfaceBodyDeclaration | <b>;</b> } <b>}</b>
- * </pre>
- * <p>
- * When a jsdoc comment is present, the source
- * range begins with the first character of the "/**" comment delimiter.
- * When there is no jsdoc comment, the source range begins with the first
- * character of the first modifier or annotation (if any), or the
- * first character of the "class" or "interface" keyword (if no
- * modifiers or annotations). The source range extends through the last character of the "}"
- * token following the body declarations.
- * </p>
- *
- * <p><b>Note: This Class only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * 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 TypeDeclaration extends AbstractTypeDeclaration {
-
- /**
- * The "javadoc" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor JAVADOC_PROPERTY =
- internalJavadocPropertyFactory(TypeDeclaration.class);
-
- /**
- * The "modifiers" structural property of this node type (JLS2 API only).
- *
- */
- public static final SimplePropertyDescriptor MODIFIERS_PROPERTY =
- internalModifiersPropertyFactory(TypeDeclaration.class);
-
- /**
- * The "modifiers" structural property of this node type (added in JLS3 API).
- *
- */
- public static final ChildListPropertyDescriptor MODIFIERS2_PROPERTY =
- internalModifiers2PropertyFactory(TypeDeclaration.class);
-
- /**
- * The "name" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor NAME_PROPERTY =
- internalNamePropertyFactory(TypeDeclaration.class);
-
-
- /**
- * The "superclass" structural property of this node type (JLS2 API only).
- *
- */
- public static final ChildPropertyDescriptor SUPERCLASS_PROPERTY =
- new ChildPropertyDescriptor(TypeDeclaration.class, "superclass", Name.class, OPTIONAL, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "superclassType" structural property of this node type (added in JLS3 API).
- *
- */
- public static final ChildPropertyDescriptor SUPERCLASS_TYPE_PROPERTY =
- new ChildPropertyDescriptor(TypeDeclaration.class, "superclassType", Type.class, OPTIONAL, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "bodyDeclarations" structural property of this node type (added in JLS3 API).
- *
- */
- public static final ChildListPropertyDescriptor BODY_DECLARATIONS_PROPERTY =
- internalBodyDeclarationPropertyFactory(TypeDeclaration.class);
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS_2_0;
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS_3_0;
-
- static {
- List propertyList = new ArrayList(8);
- createPropertyList(TypeDeclaration.class, propertyList);
- addProperty(JAVADOC_PROPERTY, propertyList);
- addProperty(MODIFIERS_PROPERTY, propertyList);
- addProperty(NAME_PROPERTY, propertyList);
- addProperty(SUPERCLASS_PROPERTY, propertyList);
- addProperty(BODY_DECLARATIONS_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS_2_0 = reapPropertyList(propertyList);
-
- propertyList = new ArrayList(9);
- createPropertyList(TypeDeclaration.class, propertyList);
- addProperty(JAVADOC_PROPERTY, propertyList);
- addProperty(MODIFIERS2_PROPERTY, propertyList);
- addProperty(NAME_PROPERTY, propertyList);
- addProperty(SUPERCLASS_TYPE_PROPERTY, propertyList);
- addProperty(BODY_DECLARATIONS_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS_3_0 = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- if (apiLevel == AST.JLS2_INTERNAL) {
- return PROPERTY_DESCRIPTORS_2_0;
- } else {
- return PROPERTY_DESCRIPTORS_3_0;
- }
- }
-
- /**
- * The optional superclass name; <code>null</code> if none.
- * Defaults to none. Note that this field is not used for
- * interface declarations. Not used in 3.0.
- */
- private Name optionalSuperclassName = null;
-
- /**
- * The optional superclass type; <code>null</code> if none.
- * Defaults to none. Note that this field is not used for
- * interface declarations. Null in JLS2. Added in JLS3.
- *
- */
- private Type optionalSuperclassType = null;
-
- /**
- * Creates a new AST node for a type declaration owned by the given
- * AST. By default, the type declaration is for a class of an
- * unspecified, but legal, name; no modifiers; no javadoc;
- * no type parameters; no superclass or superinterfaces; and an empty list
- * of body declarations.
- * <p>
- * N.B. This constructor is package-private; all subclasses must be
- * declared in the same package; clients are unable to declare
- * additional subclasses.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- TypeDeclaration(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- *
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int internalGetSetIntProperty(SimplePropertyDescriptor property, boolean get, int value) {
- if (property == MODIFIERS_PROPERTY) {
- if (get) {
- return getModifiers();
- } else {
- internalSetModifiers(value);
- return 0;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetIntProperty(property, get, value);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean internalGetSetBooleanProperty(SimplePropertyDescriptor property, boolean get, boolean value) {
- // allow default implementation to flag the error
- return super.internalGetSetBooleanProperty(property, get, value);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == JAVADOC_PROPERTY) {
- if (get) {
- return getJavadoc();
- } else {
- setJavadoc((JSdoc) child);
- return null;
- }
- }
- if (property == NAME_PROPERTY) {
- if (get) {
- return getName();
- } else {
- setName((SimpleName) child);
- return null;
- }
- }
- if (property == SUPERCLASS_PROPERTY) {
- if (get) {
- return getSuperclass();
- } else {
- setSuperclass((Name) child);
- return null;
- }
- }
- if (property == SUPERCLASS_TYPE_PROPERTY) {
- if (get) {
- return getSuperclassType();
- } else {
- setSuperclassType((Type) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalGetChildListProperty(ChildListPropertyDescriptor property) {
- if (property == MODIFIERS2_PROPERTY) {
- return modifiers();
- }
- if (property == BODY_DECLARATIONS_PROPERTY) {
- return bodyDeclarations();
- }
- // allow default implementation to flag the error
- return super.internalGetChildListProperty(property);
- }
-
- /* (omit javadoc for this method)
- * Method declared on BodyDeclaration.
- */
- final ChildPropertyDescriptor internalJavadocProperty() {
- return JAVADOC_PROPERTY;
- }
-
- /* (omit javadoc for this method)
- * Method declared on BodyDeclaration.
- */
- final ChildListPropertyDescriptor internalModifiers2Property() {
- return MODIFIERS2_PROPERTY;
- }
-
- /* (omit javadoc for this method)
- * Method declared on BodyDeclaration.
- */
- final SimplePropertyDescriptor internalModifiersProperty() {
- return MODIFIERS_PROPERTY;
- }
-
- /* (omit javadoc for this method)
- * Method declared on AbstractTypeDeclaration.
- */
- final ChildPropertyDescriptor internalNameProperty() {
- return NAME_PROPERTY;
- }
-
- /* (omit javadoc for this method)
- * Method declared on AbstractTypeDeclaration.
- */
- final ChildListPropertyDescriptor internalBodyDeclarationsProperty() {
- return BODY_DECLARATIONS_PROPERTY;
- }
-
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return TYPE_DECLARATION;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- TypeDeclaration result = new TypeDeclaration(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setJavadoc(
- (JSdoc) ASTNode.copySubtree(target, getJavadoc()));
- if (this.ast.apiLevel == AST.JLS2_INTERNAL) {
- result.internalSetModifiers(getModifiers());
- result.setSuperclass(
- (Name) ASTNode.copySubtree(target, getSuperclass()));
- }
- result.setName((SimpleName) getName().clone(target));
- if (this.ast.apiLevel >= AST.JLS3) {
- result.modifiers().addAll(ASTNode.copySubtrees(target, modifiers()));
- result.setSuperclassType(
- (Type) ASTNode.copySubtree(target, getSuperclassType()));
- }
- result.bodyDeclarations().addAll(
- ASTNode.copySubtrees(target, bodyDeclarations()));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- if (this.ast.apiLevel == AST.JLS2_INTERNAL) {
- acceptChild(visitor, getJavadoc());
- acceptChild(visitor, getName());
- acceptChild(visitor, getSuperclass());
- acceptChildren(visitor, this.bodyDeclarations);
- }
- if (this.ast.apiLevel >= AST.JLS3) {
- acceptChild(visitor, getJavadoc());
- acceptChildren(visitor, this.modifiers);
- acceptChild(visitor, getName());
- acceptChild(visitor, getSuperclassType());
- acceptChildren(visitor, this.bodyDeclarations);
- }
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the name of the superclass declared in this type
- * declaration, or <code>null</code> if there is none (JLS2 API only).
- * <p>
- * Note that this child is not relevant for interface
- * declarations (although it does still figure in subtree
- * equality comparisons).
- * </p>
- *
- * @return the superclass name node, or <code>null</code> if
- * there is none
- * @exception UnsupportedOperationException if this operation is used in
- * an AST later than JLS2
- * @deprecated In the JLS3 API, this method is replaced by
- * {@link #getSuperclassType()}, which returns a <code>Type</code>
- * instead of a <code>Name</code>.
- */
- public Name getSuperclass() {
- return internalGetSuperclass();
- }
-
- /**
- * Internal synonym for deprecated method. Used to avoid
- * deprecation warnings.
- *
- */
- /*package*/ final Name internalGetSuperclass() {
- supportedOnlyIn2();
- return this.optionalSuperclassName;
- }
-
- /**
- * Returns the superclass declared in this type
- * declaration, or <code>null</code> if there is none (added in JLS3 API).
- * <p>
- * Note that this child is not relevant for interface
- * declarations (although it does still figure in subtree
- * equality comparisons).
- * </p>
- *
- * @return the superclass type node, or <code>null</code> if
- * there is none
- * @exception UnsupportedOperationException if this operation is used in
- * a JLS2 AST
- *
- */
- public Type getSuperclassType() {
- unsupportedIn2();
- return this.optionalSuperclassType;
- }
-
- /**
- * Sets or clears the name of the superclass declared in this type
- * declaration (JLS2 API only).
- * <p>
- * Note that this child is not relevant for interface
- * declarations (although it does still figure in subtree
- * equality comparisons).
- * </p>
- *
- * @param superclassName the superclass name node, or <code>null</code> if
- * there is none
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- * @exception UnsupportedOperationException if this operation is used in
- * an AST later than JLS2
- * @deprecated In the JLS3 API, this method is replaced by
- * {@link #setSuperclassType(Type)}, which expects a
- * <code>Type</code> instead of a <code>Name</code>.
- */
- public void setSuperclass(Name superclassName) {
- internalSetSuperclass(superclassName);
- }
-
- /**
- * Internal synonym for deprecated method. Used to avoid
- * deprecation warnings.
- *
- */
- /*package*/ final void internalSetSuperclass(Name superclassName) {
- supportedOnlyIn2();
- ASTNode oldChild = this.optionalSuperclassName;
- preReplaceChild(oldChild, superclassName, SUPERCLASS_PROPERTY);
- this.optionalSuperclassName = superclassName;
- postReplaceChild(oldChild, superclassName, SUPERCLASS_PROPERTY);
- }
-
- /**
- * Sets or clears the superclass declared in this type
- * declaration (added in JLS3 API).
- * <p>
- * Note that this child is not relevant for interface declarations
- * (although it does still figure in subtree equality comparisons).
- * </p>
- *
- * @param superclassType the superclass type node, or <code>null</code> if
- * there is none
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- * @exception UnsupportedOperationException if this operation is used in
- * a JLS2 AST
- *
- */
- public void setSuperclassType(Type superclassType) {
- unsupportedIn2();
- ASTNode oldChild = this.optionalSuperclassType;
- preReplaceChild(oldChild, superclassType, SUPERCLASS_TYPE_PROPERTY);
- this.optionalSuperclassType = superclassType;
- postReplaceChild(oldChild, superclassType, SUPERCLASS_TYPE_PROPERTY);
- }
-
- /**
- * Returns the ordered list of field declarations of this type
- * declaration. For a class declaration, these are the
- * field declarations; for an interface declaration, these are
- * the constant declarations.
- * <p>
- * This convenience method returns this node's body declarations
- * with non-fields filtered out. Unlike <code>bodyDeclarations</code>,
- * this method does not return a live result.
- * </p>
- *
- * @return the (possibly empty) list of field declarations
- */
- public FieldDeclaration[] getFields() {
- List bd = bodyDeclarations();
- int fieldCount = 0;
- for (Iterator it = bd.listIterator(); it.hasNext(); ) {
- if (it.next() instanceof FieldDeclaration) {
- fieldCount++;
- }
- }
- FieldDeclaration[] fields = new FieldDeclaration[fieldCount];
- int next = 0;
- for (Iterator it = bd.listIterator(); it.hasNext(); ) {
- Object decl = it.next();
- if (decl instanceof FieldDeclaration) {
- fields[next++] = (FieldDeclaration) decl;
- }
- }
- return fields;
- }
-
- /**
- * Returns the ordered list of method declarations of this type
- * declaration.
- * <p>
- * This convenience method returns this node's body declarations
- * with non-methods filtered out. Unlike <code>bodyDeclarations</code>,
- * this method does not return a live result.
- * </p>
- *
- * @return the (possibly empty) list of method (and constructor)
- * declarations
- */
- public FunctionDeclaration[] getMethods() {
- List bd = bodyDeclarations();
- int methodCount = 0;
- for (Iterator it = bd.listIterator(); it.hasNext(); ) {
- if (it.next() instanceof FunctionDeclaration) {
- methodCount++;
- }
- }
- FunctionDeclaration[] methods = new FunctionDeclaration[methodCount];
- int next = 0;
- for (Iterator it = bd.listIterator(); it.hasNext(); ) {
- Object decl = it.next();
- if (decl instanceof FunctionDeclaration) {
- methods[next++] = (FunctionDeclaration) decl;
- }
- }
- return methods;
- }
-
- /**
- * Returns the ordered list of member type declarations of this type
- * declaration.
- * <p>
- * This convenience method returns this node's body declarations
- * with non-types filtered out. Unlike <code>bodyDeclarations</code>,
- * this method does not return a live result.
- * </p>
- *
- * @return the (possibly empty) list of member type declarations
- */
- public TypeDeclaration[] getTypes() {
- List bd = bodyDeclarations();
- int typeCount = 0;
- for (Iterator it = bd.listIterator(); it.hasNext(); ) {
- if (it.next() instanceof TypeDeclaration) {
- typeCount++;
- }
- }
- TypeDeclaration[] memberTypes = new TypeDeclaration[typeCount];
- int next = 0;
- for (Iterator it = bd.listIterator(); it.hasNext(); ) {
- Object decl = it.next();
- if (decl instanceof TypeDeclaration) {
- memberTypes[next++] = (TypeDeclaration) decl;
- }
- }
- return memberTypes;
- }
-
- /* (omit javadoc for this method)
- * Method declared on AsbtractTypeDeclaration.
- */
- ITypeBinding internalResolveBinding() {
- return this.ast.getBindingResolver().resolveType(this);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return super.memSize() + 6 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return memSize()
- + (this.optionalDocComment == null ? 0 : getJavadoc().treeSize())
- + (this.modifiers == null ? 0 : this.modifiers.listSize())
- + (this.typeName == null ? 0 : getName().treeSize())
- + (this.optionalSuperclassName == null ? 0 : getSuperclass().treeSize())
- + (this.optionalSuperclassType == null ? 0 : getSuperclassType().treeSize())
- + this.bodyDeclarations.listSize();
- }
-}
-
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
deleted file mode 100644
index f4c5e21d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TypeDeclarationStatement.java
+++ /dev/null
@@ -1,361 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Local type declaration statement AST node type.
- * <p>
- * This kind of node is used to convert a type declaration
- * node into a statement node by wrapping it.
- * </p>
- * For JLS2:
- * <pre>
- * TypeDeclarationStatement:
- * TypeDeclaration
- * </pre>
- * For JLS3, the kinds of type declarations grew to include enum declarations:
- * <pre>
- * TypeDeclarationStatement:
- * TypeDeclaration
- * EnumDeclaration
- * </pre>
- * Although allowed at the AST, not all arrangements of AST nodes are meaningful;
- * in particular, only class and enum declarations are meaningful in the context of
- * a block.
- *
- * <p><b>Note: This Class only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * 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 TypeDeclarationStatement extends Statement {
-
- /**
- * The "typeDeclaration" structural property of this node type (JLS2 API only).
- *
- */
- public static final ChildPropertyDescriptor TYPE_DECLARATION_PROPERTY =
- new ChildPropertyDescriptor(TypeDeclarationStatement.class, "typeDeclaration", TypeDeclaration.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "declaration" structural property of this node type (added in JLS3 API).
- *
- */
- public static final ChildPropertyDescriptor DECLARATION_PROPERTY =
- new ChildPropertyDescriptor(TypeDeclarationStatement.class, "declaration", AbstractTypeDeclaration.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS_2_0;
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS_3_0;
-
- static {
- List propertyList = new ArrayList(2);
- createPropertyList(TypeDeclarationStatement.class, propertyList);
- addProperty(TYPE_DECLARATION_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS_2_0 = reapPropertyList(propertyList);
-
- propertyList = new ArrayList(2);
- createPropertyList(TypeDeclarationStatement.class, propertyList);
- addProperty(DECLARATION_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS_3_0 = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- if (apiLevel == AST.JLS2_INTERNAL) {
- return PROPERTY_DESCRIPTORS_2_0;
- } else {
- return PROPERTY_DESCRIPTORS_3_0;
- }
- }
-
- /**
- * The type declaration; lazily initialized; defaults to a unspecified,
- * but legal, type declaration. In JLS2, corresponds to TYPE_DECLARATION_PROPERTY.
- * After JLS2, corresponds to DECLARATION_PROPERTY.
- * @see #typeDeclProperty
- */
- private AbstractTypeDeclaration typeDecl = null;
-
- /**
- * The child property stored on the <code>typeDecl</code> instance variable.
- * In JLS2, corresponds to TYPE_DECLARATION_PROPERTY. After JLS2, corresponds to
- * DECLARATION_PROPERTY.
- *
- * @return the property corresponding to the <code>typeDecl</code> instance variable;
- * never <code>null</code>
- */
- private ChildPropertyDescriptor typeDeclProperty () {
- if (getAST().apiLevel() == AST.JLS2_INTERNAL) {
- return TYPE_DECLARATION_PROPERTY;
- } else {
- return DECLARATION_PROPERTY;
- }
- }
-
-
- /**
- * Creates a new unparented local type declaration statement node owned
- * by the given AST. By default, the local type declaration is an
- * unspecified, but legal, type declaration.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- TypeDeclarationStatement(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- *
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == TYPE_DECLARATION_PROPERTY) {
- if (get) {
- return getTypeDeclaration();
- } else {
- setTypeDeclaration((TypeDeclaration) child);
- return null;
- }
- }
- if (property == DECLARATION_PROPERTY) {
- if (get) {
- return getDeclaration();
- } else {
- setDeclaration((AbstractTypeDeclaration) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return TYPE_DECLARATION_STATEMENT;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- TypeDeclarationStatement result =
- new TypeDeclarationStatement(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.copyLeadingComment(this);
- result.setDeclaration(
- (AbstractTypeDeclaration) getDeclaration().clone(target));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- acceptChild(visitor, getDeclaration());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the abstract type declaration of this local type declaration
- * statement (added in JLS3 API).
- *
- * @return the type declaration node
- *
- */
- public AbstractTypeDeclaration getDeclaration() {
- if (this.typeDecl == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.typeDecl == null) {
- preLazyInit();
- this.typeDecl = new TypeDeclaration(this.ast);
- postLazyInit(this.typeDecl, typeDeclProperty());
- }
- }
- }
- return this.typeDecl;
- }
-
- /**
- * Sets the abstract type declaration of this local type declaration
- * statement (added in JLS3 API).
- *
- * @param decl the type declaration node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- *
- */
- public void setDeclaration(AbstractTypeDeclaration decl) {
- if (decl == null) {
- throw new IllegalArgumentException();
- }
- // a TypeDeclarationStatement may occur inside an
- // TypeDeclaration - must check cycles
- ASTNode oldChild = this.typeDecl;
- ChildPropertyDescriptor typeDeclProperty = typeDeclProperty();
- preReplaceChild(oldChild, decl, typeDeclProperty);
- this.typeDecl= decl;
- postReplaceChild(oldChild, decl, typeDeclProperty);
- }
-
- /**
- * Returns the type declaration of this local type declaration
- * statement (JLS2 API only).
- *
- * @return the type declaration node
- * @exception UnsupportedOperationException if this operation is used in
- * an AST later than JLS2
- * @deprecated In the JLS3 API, this method is replaced by
- * {@link #getDeclaration()}, which returns <code>AbstractTypeDeclaration</code>
- * instead of <code>TypeDeclaration</code>.
- */
- public TypeDeclaration getTypeDeclaration() {
- return internalGetTypeDeclaration();
- }
-
- /**
- * Internal synonym for deprecated method. Used to avoid
- * deprecation warnings.
- *
- */
- /*package*/ final TypeDeclaration internalGetTypeDeclaration() {
- supportedOnlyIn2();
- return (TypeDeclaration) getDeclaration();
- }
-
- /**
- * Sets the type declaration of this local type declaration
- * statement (JLS2 API only).
- *
- * @param decl the type declaration node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- * @exception UnsupportedOperationException if this operation is used in
- * an AST later than JLS2
- * @deprecated In the JLS3 API, this method is replaced by
- * {@link #setDeclaration(AbstractTypeDeclaration)} which takes
- * <code>AbstractTypeDeclaration</code> instead of
- * <code>TypeDeclaration</code>.
- */
- public void setTypeDeclaration(TypeDeclaration decl) {
- internalSetTypeDeclaration(decl);
- }
-
- /**
- * Internal synonym for deprecated method. Used to avoid
- * deprecation warnings.
- *
- */
- /*package*/ final void internalSetTypeDeclaration(TypeDeclaration decl) {
- supportedOnlyIn2();
- // forward to non-deprecated replacement method
- setDeclaration(decl);
- }
-
- /**
- * Resolves and returns the binding for the class or interface declared in
- * this type declaration statement.
- * <p>
- * Note that bindings are generally unavailable unless requested when the
- * AST is being built.
- * </p>
- *
- * @return the binding, or <code>null</code> if the binding cannot be
- * resolved
- */
- public ITypeBinding resolveBinding() {
- // forward request to the wrapped type declaration
- AbstractTypeDeclaration d = getDeclaration();
- if (d instanceof TypeDeclaration) {
- return ((TypeDeclaration) d).resolveBinding();
- } else {
- // shouldn't happen
- return null;
- }
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return super.memSize() + 1 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.typeDecl == null ? 0 : getDeclaration().treeSize());
- }
-}
-
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
deleted file mode 100644
index 3279ce7e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TypeLiteral.java
+++ /dev/null
@@ -1,203 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Type literal AST node type.
- *
- * <pre>
- * TypeLiteral:
- * ( Type | <b>void</b> ) <b>.</b> <b>class</b>
- * </pre>
- *
- * <p><b>Note: This Class only applies to ECMAScript 4 which is not yet supported</b></p>
- *
- * 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 TypeLiteral extends Expression {
-
- /**
- * The "type" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor TYPE_PROPERTY =
- new ChildPropertyDescriptor(TypeLiteral.class, "type", Type.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List propertyList = new ArrayList(2);
- createPropertyList(TypeLiteral.class, propertyList);
- addProperty(TYPE_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The type; lazily initialized; defaults to a unspecified,
- * legal type.
- */
- private Type type = null;
-
- /**
- * Creates a new AST node for a type literal owned by the given
- * AST. By default, the expression has an unspecified (but legal) type.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- TypeLiteral(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == TYPE_PROPERTY) {
- if (get) {
- return getType();
- } else {
- setType((Type) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return TYPE_LITERAL;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- TypeLiteral result = new TypeLiteral(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setType((Type) getType().clone(target));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- acceptChild(visitor, getType());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the type in this type literal expression.
- *
- * @return the type
- */
- public Type getType() {
- if (this.type == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.type == null) {
- preLazyInit();
- this.type = this.ast.newPrimitiveType(PrimitiveType.INT);
- postLazyInit(this.type, TYPE_PROPERTY);
- }
- }
- }
- return this.type;
- }
-
- /**
- * Sets the type in this type literal expression to the given type.
- *
- * @param type the new type
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public void setType(Type type) {
- if (type == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.type;
- preReplaceChild(oldChild, type, TYPE_PROPERTY);
- this.type = type;
- postReplaceChild(oldChild, type, TYPE_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- // treat Operator as free
- return BASE_NODE_SIZE + 1 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.type == null ? 0 : getType().treeSize());
- }
-}
-
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
deleted file mode 100644
index a840d76c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/UndefinedLiteral.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Null literal node.
- *
- * 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 UndefinedLiteral extends Expression {
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List propertyList = new ArrayList(1);
- createPropertyList(UndefinedLiteral.class, propertyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * Creates a new unparented null literal node owned by the given AST.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- UndefinedLiteral(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return UNDEFINED_LITERAL;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- UndefinedLiteral result = new UndefinedLiteral(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- visitor.visit(this);
- visitor.endVisit(this);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return BASE_NODE_SIZE;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return memSize();
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/VariableBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/VariableBinding.java
deleted file mode 100644
index 60405630..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/VariableBinding.java
+++ /dev/null
@@ -1,283 +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.core.dom;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.CompilationUnitScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.FieldBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.LocalVariableBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TagBits;
-import org.eclipse.wst.jsdt.internal.core.JavaElement;
-import org.eclipse.wst.jsdt.internal.core.LocalVariable;
-
-/**
- * Internal implementation of variable bindings.
- */
-class VariableBinding implements IVariableBinding {
-
- private static final int VALID_MODIFIERS = Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE |
- Modifier.STATIC | Modifier.FINAL | Modifier.TRANSIENT | Modifier.VOLATILE;
-
- private org.eclipse.wst.jsdt.internal.compiler.lookup.VariableBinding binding;
- private ITypeBinding declaringClass;
- private String key;
- private String name;
- private BindingResolver resolver;
- private ITypeBinding type;
-
- VariableBinding(BindingResolver resolver, org.eclipse.wst.jsdt.internal.compiler.lookup.VariableBinding binding) {
- this.resolver = resolver;
- this.binding = binding;
- }
-
- /* (non-Javadoc)
- * @see IVariableBinding#getConstantValue()
- *
- */
- public Object getConstantValue() {
- return null;
- }
-
- /*
- * @see IVariableBinding#getDeclaringClass()
- */
- public ITypeBinding getDeclaringClass() {
- if (isField()) {
- if (this.declaringClass == null) {
- FieldBinding fieldBinding = (FieldBinding) this.binding;
- this.declaringClass = this.resolver.getTypeBinding(fieldBinding.declaringClass);
- }
- return this.declaringClass;
- } else {
- return null;
- }
- }
-
- /*
- * @see IVariableBinding#getDeclaringMethod()
- */
- public IFunctionBinding getDeclaringMethod() {
- if (!isField()) {
- ASTNode node = this.resolver.findDeclaringNode(this);
- while (true) {
- if (node == null) break;
- switch(node.getNodeType()) {
- case ASTNode.INITIALIZER :
- return null;
- case ASTNode.FUNCTION_DECLARATION :
- FunctionDeclaration methodDeclaration = (FunctionDeclaration) node;
- return methodDeclaration.resolveBinding();
- default:
- node = node.getParent();
- }
- }
- }
- return null;
- }
-
- /*
- * @see IBinding#getJavaElement()
- */
- public IJavaScriptElement getJavaElement() {
- JavaElement element = getUnresolvedJavaElement();
- if (element == null)
- return null;
- return element.resolved(this.binding);
- }
-
- /*
- * @see IBinding#getKey()
- */
- public String getKey() {
- if (this.key == null) {
- this.key = new String(this.binding.computeUniqueKey());
- }
- return this.key;
- }
-
- /*
- * @see IBinding#getKind()
- */
- public int getKind() {
- return IBinding.VARIABLE;
- }
-
- /*
- * @see IBinding#getModifiers()
- */
- public int getModifiers() {
- if (isField()) {
- return ((FieldBinding) this.binding).getAccessFlags() & VALID_MODIFIERS;
- }
- return Modifier.NONE;
- }
-
- /*
- * @see IBinding#getName()
- */
- public String getName() {
- if (this.name == null) {
- this.name = new String(this.binding.name);
- }
- return this.name;
- }
-
- /*
- * @see IVariableBinding#getType()
- */
- public ITypeBinding getType() {
- if (this.type == null) {
- this.type = this.resolver.getTypeBinding(this.binding.type);
- }
- return this.type;
- }
-
- private JavaElement getUnresolvedJavaElement() {
- if (isField()) {
- // field
- FieldBinding fieldBinding = (FieldBinding) this.binding;
- if (fieldBinding.declaringClass == null) return null; // arraylength
- IType declaringType = (IType) getDeclaringClass().getJavaElement();
- if (declaringType == null) return null;
- return (JavaElement) declaringType.getField(getName());
- }
- // local variable
- IFunctionBinding declaringMethod = getDeclaringMethod();
- if (declaringMethod == null) return null;
- JavaElement method = (JavaElement) declaringMethod.getJavaElement();
- if (!(this.resolver instanceof DefaultBindingResolver)) return null;
- VariableDeclaration localVar = (VariableDeclaration) ((DefaultBindingResolver) this.resolver).bindingsToAstNodes.get(this);
- if (localVar == null) return null;
- int nameStart;
- int nameLength;
- int sourceStart;
- int sourceLength;
- if (localVar instanceof SingleVariableDeclaration) {
- sourceStart = localVar.getStartPosition();
- sourceLength = localVar.getLength();
- SimpleName simpleName = ((SingleVariableDeclaration) localVar).getName();
- nameStart = simpleName.getStartPosition();
- nameLength = simpleName.getLength();
- } else {
- nameStart = localVar.getStartPosition();
- nameLength = localVar.getLength();
- ASTNode node = localVar.getParent();
- sourceStart = node.getStartPosition();
- sourceLength = node.getLength();
- }
- char[] typeSig = this.binding.type.signature();
- return new LocalVariable(method, localVar.getName().getIdentifier(), sourceStart, sourceStart+sourceLength-1, nameStart, nameStart+nameLength-1, new String(typeSig));
- }
-
- /*
- * @see IVariableBinding#getVariableDeclaration()
- *
- */
- public IVariableBinding getVariableDeclaration() {
- if (this.isField()) {
- FieldBinding fieldBinding = (FieldBinding) this.binding;
- return this.resolver.getVariableBinding(fieldBinding.original());
- }
- return this;
- }
-
- /*
- * @see IVariableBinding#getVariableId()
- */
- public int getVariableId() {
- return this.binding.id;
- }
-
- /*
- * @see IVariableBinding#isParameter()
- */
- public boolean isParameter() {
- return (this.binding.tagBits & TagBits.IsArgument) != 0;
- }
- /*
- * @see IBinding#isDeprecated()
- */
- public boolean isDeprecated() {
- if (isField()) {
- return ((FieldBinding) this.binding).isDeprecated();
- }
- return false;
- }
-
- /*
- * @see IBinding#isEqualTo(Binding)
- *
- */
- public boolean isEqualTo(IBinding other) {
- if (other == this) {
- // identical binding - equal (key or no key)
- return true;
- }
- if (other == null) {
- // other binding missing
- return false;
- }
- if (!(other instanceof VariableBinding)) {
- return false;
- }
- org.eclipse.wst.jsdt.internal.compiler.lookup.VariableBinding otherBinding = ((VariableBinding) other).binding;
- if (this.binding instanceof FieldBinding) {
- if (otherBinding instanceof FieldBinding) {
- return BindingComparator.isEqual((FieldBinding) this.binding, (FieldBinding) otherBinding);
- } else {
- return false;
- }
- } else {
- if (BindingComparator.isEqual(this.binding, otherBinding)) {
- IFunctionBinding declaringMethod = this.getDeclaringMethod();
- IFunctionBinding otherDeclaringMethod = ((VariableBinding) other).getDeclaringMethod();
- if (declaringMethod == null) {
- if (otherDeclaringMethod != null) {
- return false;
- }
- return true;
- }
- return declaringMethod.isEqualTo(otherDeclaringMethod);
- }
- return false;
- }
- }
-
- /*
- * @see IVariableBinding#isField()
- */
- public boolean isField() {
- return this.binding instanceof FieldBinding;
- }
-
- public boolean isGlobal()
- {
- return this.binding instanceof LocalVariableBinding && ((LocalVariableBinding)this.binding).declaringScope instanceof CompilationUnitScope;
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.jdt.core.dom.IBinding#isRecovered()
- */
- public boolean isRecovered() {
- return false;
- }
-
- /*
- * For debugging purpose only.
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return this.binding.toString();
- }
-}
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
deleted file mode 100644
index e7b3d935..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/VariableDeclaration.java
+++ /dev/null
@@ -1,200 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-/**
- * Abstract base class of all AST node types that declare a single local
- * variable.
- * <p>
- * <pre>
- * VariableDeclaration:
- * SingleVariableDeclaration
- * VariableDeclarationFragment
- * </pre>
- * </p>
- *
- * @see SingleVariableDeclaration
- * @see VariableDeclarationFragment
- *
- * 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 VariableDeclaration extends ASTNode {
-
- /**
- * Returns structural property descriptor for the "extraDimensions" property
- * of this node.
- *
- * @return the property descriptor
- *
- */
- abstract SimplePropertyDescriptor internalExtraDimensionsProperty();
-
- /**
- * Returns structural property descriptor for the "extraDimensions" property
- * of this node.
- *
- * @return the property descriptor
- *
- */
- public final SimplePropertyDescriptor getExtraDimensionsProperty() {
- return internalExtraDimensionsProperty();
- }
-
- /**
- * Returns structural property descriptor for the "initializer" property
- * of this node.
- *
- * @return the property descriptor
- *
- */
- abstract ChildPropertyDescriptor internalInitializerProperty();
-
- /**
- * Returns structural property descriptor for the "initializer" property
- * of this node.
- *
- * @return the property descriptor
- *
- */
- public final ChildPropertyDescriptor getInitializerProperty() {
- return internalInitializerProperty();
- }
-
- /**
- * Returns structural property descriptor for the "name" property
- * of this node.
- *
- * @return the property descriptor
- *
- */
- abstract ChildPropertyDescriptor internalNameProperty();
-
- /**
- * Returns structural property descriptor for the "name" property
- * of this node.
- *
- * @return the property descriptor
- *
- */
- public final ChildPropertyDescriptor getNameProperty() {
- return internalNameProperty();
- }
-
- /**
- * Creates a new AST node for a variable declaration owned by the given AST.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- VariableDeclaration(AST ast) {
- super(ast);
- }
-
- /**
- * Returns the name of the variable declared in this variable declaration.
- *
- * @return the variable name node
- */
- public abstract SimpleName getName();
-
- /**
- * Sets the name of the variable declared in this variable declaration
- * to the given name.
- *
- * @param variableName the new variable name
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public abstract void setName(SimpleName variableName);
-
- /**
- * Returns the number of extra array dimensions over and above the
- * explicitly-specified type.
- * <p>
- * For example, <code>int x[][]</code> has a type of
- * <code>int</code> and two extra array dimensions;
- * <code>int[][] x</code> has a type of <code>int[][]</code>
- * and zero extra array dimensions. The two constructs have different
- * ASTs, even though there are really syntactic variants of the same
- * variable declaration.
- * </p>
- *
- * @return the number of extra array dimensions
- *
- */
- public abstract int getExtraDimensions();
-
- /**
- * Sets the number of extra array dimensions over and above the
- * explicitly-specified type.
- * <p>
- * For example, <code>int x[][]</code> has a type of
- * <code>int</code> and two extra array dimensions;
- * <code>int[][] x</code> has a type of <code>int[][]</code>
- * and zero extra array dimensions. The two constructs have different
- * ASTs, even though there are really syntactic variants of the same
- * variable declaration.
- * </p>
- *
- * @param dimensions the number of array dimensions
- * @exception IllegalArgumentException if the number of dimensions is
- * negative
- *
- */
- public abstract void setExtraDimensions(int dimensions);
-
- /**
- * Returns the initializer of this variable declaration, or
- * <code>null</code> if there is none.
- *
- * @return the initializer expression node, or <code>null</code> if
- * there is none
- */
- public abstract Expression getInitializer();
-
- /**
- * Sets or clears the initializer of this variable declaration.
- *
- * @param initializer the initializer expression node, or <code>null</code>
- * if there is none
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public abstract void setInitializer(Expression initializer);
-
- /**
- * Resolves and returns the binding for the variable declared in this
- * variable declaration.
- * <p>
- * Note that bindings are generally unavailable unless requested when the
- * AST is being built.
- * </p>
- *
- * @return the binding, or <code>null</code> if the binding cannot be
- * resolved
- */
- public IVariableBinding resolveBinding() {
- return this.ast.getBindingResolver().resolveVariable(this);
- }
-}
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
deleted file mode 100644
index b32858bc..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/VariableDeclarationExpression.java
+++ /dev/null
@@ -1,438 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-/**
- * Local variable declaration expression AST node type.
- * <p>
- * This kind of node collects together several variable declaration fragments
- * (<code>VariableDeclarationFragment</code>) into a single expression
- * (<code>Expression</code>), all sharing the same modifiers and base type.
- * This type of node can be used as the initializer of a
- * <code>ForStatement</code>, or wrapped in an <code>ExpressionStatement</code>
- * to form the equivalent of a <code>VariableDeclarationStatement</code>.
- * </p>
- * For JLS2:
- * <pre>
- * VariableDeclarationExpression:
- * { Modifier } Type VariableDeclarationFragment
- * { <b>,</b> VariableDeclarationFragment }
- * </pre>
- * For JLS3, the modifier flags were replaced by
- * a list of modifier nodes (intermixed with annotations):
- * <pre>
- * VariableDeclarationExpression:
- * { ExtendedModifier } Type VariableDeclarationFragment
- * { <b>,</b> VariableDeclarationFragment }
- * </pre>
- *
- *
- * 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 VariableDeclarationExpression extends Expression {
-
- /**
- * The "modifiers" structural property of this node type (JLS2 API only).
- *
- */
- public static final SimplePropertyDescriptor MODIFIERS_PROPERTY =
- new SimplePropertyDescriptor(VariableDeclarationExpression.class, "modifiers", int.class, MANDATORY); //$NON-NLS-1$
-
- /**
- * The "modifiers" structural property of this node type (added in JLS3 API).
- *
- */
- public static final ChildListPropertyDescriptor MODIFIERS2_PROPERTY =
- new ChildListPropertyDescriptor(VariableDeclarationExpression.class, "modifiers", IExtendedModifier.class, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "type" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor TYPE_PROPERTY =
- new ChildPropertyDescriptor(VariableDeclarationExpression.class, "type", Type.class, MANDATORY, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "fragments" structural property of this node type).
- *
- */
- public static final ChildListPropertyDescriptor FRAGMENTS_PROPERTY =
- new ChildListPropertyDescriptor(VariableDeclarationExpression.class, "fragments", VariableDeclarationFragment.class, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS_2_0;
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS_3_0;
-
- static {
- List propertyList = new ArrayList(4);
- createPropertyList(VariableDeclarationExpression.class, propertyList);
- addProperty(MODIFIERS_PROPERTY, propertyList);
- addProperty(TYPE_PROPERTY, propertyList);
- addProperty(FRAGMENTS_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS_2_0 = reapPropertyList(propertyList);
-
- propertyList = new ArrayList(4);
- createPropertyList(VariableDeclarationExpression.class, propertyList);
- addProperty(MODIFIERS2_PROPERTY, propertyList);
- addProperty(TYPE_PROPERTY, propertyList);
- addProperty(FRAGMENTS_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS_3_0 = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- if (apiLevel == AST.JLS2_INTERNAL) {
- return PROPERTY_DESCRIPTORS_2_0;
- } else {
- return PROPERTY_DESCRIPTORS_3_0;
- }
- }
-
- /**
- * The extended modifiers (element type: <code>IExtendedModifier</code>).
- * Null in JLS2. Added in JLS3; defaults to an empty list
- * (see constructor).
- *
- */
- private ASTNode.NodeList modifiers = null;
-
- /**
- * The modifier flags; bit-wise or of Modifier flags.
- * Defaults to none. Not used in 3.0.
- */
- private int modifierFlags = Modifier.NONE;
-
- /**
- * The base type; lazily initialized; defaults to an unspecified,
- * legal type.
- */
- private Type baseType = null;
-
- /**
- * The list of variable declaration fragments (element type:
- * <code VariableDeclarationFragment</code>). Defaults to an empty list.
- */
- private ASTNode.NodeList variableDeclarationFragments =
- new ASTNode.NodeList(FRAGMENTS_PROPERTY);
-
- /**
- * Creates a new unparented local variable declaration expression node
- * owned by the given AST. By default, the variable declaration has: no
- * modifiers, an unspecified (but legal) type, and an empty list of variable
- * declaration fragments (which is syntactically illegal).
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- VariableDeclarationExpression(AST ast) {
- super(ast);
- if (ast.apiLevel >= AST.JLS3) {
- this.modifiers = new ASTNode.NodeList(MODIFIERS2_PROPERTY);
- }
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int internalGetSetIntProperty(SimplePropertyDescriptor property, boolean get, int value) {
- if (property == MODIFIERS_PROPERTY) {
- if (get) {
- return getModifiers();
- } else {
- setModifiers(value);
- return 0;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetIntProperty(property, get, value);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == TYPE_PROPERTY) {
- if (get) {
- return getType();
- } else {
- setType((Type) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalGetChildListProperty(ChildListPropertyDescriptor property) {
- if (property == MODIFIERS2_PROPERTY) {
- return modifiers();
- }
- if (property == FRAGMENTS_PROPERTY) {
- return fragments();
- }
- // allow default implementation to flag the error
- return super.internalGetChildListProperty(property);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return VARIABLE_DECLARATION_EXPRESSION;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- VariableDeclarationExpression result =
- new VariableDeclarationExpression(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- if (this.ast.apiLevel == AST.JLS2_INTERNAL) {
- result.setModifiers(getModifiers());
- }
- if (this.ast.apiLevel >= AST.JLS3) {
- result.modifiers().addAll(ASTNode.copySubtrees(target, modifiers()));
- }
- result.setType((Type) getType().clone(target));
- result.fragments().addAll(
- ASTNode.copySubtrees(target, fragments()));
- return result;
-
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- if (this.ast.apiLevel >= AST.JLS3) {
- acceptChildren(visitor, this.modifiers);
- }
- acceptChild(visitor, getType());
- acceptChildren(visitor, variableDeclarationFragments);
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the live ordered list of modifiers and annotations
- * of this declaration (added in JLS3 API).
- * <p>
- * Note that the final modifier is the only meaningful modifier for local
- * variable declarations.
- * </p>
- *
- * @return the live list of modifiers and annotations
- * (element type: <code>IExtendedModifier</code>)
- * @exception UnsupportedOperationException if this operation is used in
- * a JLS2 AST
- *
- */
- public List modifiers() {
- // more efficient than just calling unsupportedIn2() to check
- if (this.modifiers == null) {
- unsupportedIn2();
- }
- return this.modifiers;
- }
-
- /**
- * Returns the modifiers explicitly specified on this declaration.
- * <p>
- * In the JLS3 API, this method is a convenience method that
- * computes these flags from <code>modifiers()</code>.
- * </p>
- *
- * @return the bit-wise or of <code>Modifier</code> constants
- * @see Modifier
- */
- public int getModifiers() {
- // more efficient than checking getAST().API_LEVEL
- if (this.modifiers == null) {
- // JLS2 behavior - bona fide property
- return this.modifierFlags;
- } else {
- // JLS3 behavior - convenient method
- // performance could be improved by caching computed flags
- // but this would require tracking changes to this.modifiers
- int computedModifierFlags = Modifier.NONE;
- for (Iterator it = modifiers().iterator(); it.hasNext(); ) {
- Object x = it.next();
- if (x instanceof Modifier) {
- computedModifierFlags |= ((Modifier) x).getKeyword().toFlagValue();
- }
- }
- return computedModifierFlags;
- }
- }
-
- /**
- * Sets the modifiers explicitly specified on this declaration (JLS2 API only).
- * <p>
- * Note that the final modifier is the only meaningful modifier for local
- * variable declarations.
- * </p>
- *
- * @param modifiers the given modifiers (bit-wise or of <code>Modifier</code> constants)
- * @exception UnsupportedOperationException if this operation is used in
- * an AST later than JLS2
- * @see Modifier
- * @deprecated In the JLS3 API, this method is replaced by
- * {@link #modifiers()} which contains a list of a <code>Modifier</code> nodes.
- */
- public void setModifiers(int modifiers) {
- internalSetModifiers(modifiers);
- }
-
- /**
- * Internal synonym for deprecated method. Used to avoid
- * deprecation warnings.
- *
- */
- /*package*/ final void internalSetModifiers(int pmodifiers) {
- supportedOnlyIn2();
- preValueChange(MODIFIERS_PROPERTY);
- this.modifierFlags = pmodifiers;
- postValueChange(MODIFIERS_PROPERTY);
- }
-
- /**
- * Returns the base type declared in this variable declaration.
- * <p>
- * N.B. The individual child variable declaration fragments may specify
- * additional array dimensions. So the type of the variable are not
- * necessarily exactly this type.
- * </p>
- *
- * @return the base type
- */
- public Type getType() {
- if (this.baseType == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.baseType == null) {
- preLazyInit();
- this.baseType = this.ast.newInferredType(null);
- postLazyInit(this.baseType, TYPE_PROPERTY);
- }
- }
- }
- return this.baseType;
- }
-
- /**
- * Sets the base type declared in this variable declaration to the given
- * type.
- *
- * @param type the new base type
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public void setType(Type type) {
- if (type == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.baseType;
- preReplaceChild(oldChild, type, TYPE_PROPERTY);
- this.baseType = type;
- postReplaceChild(oldChild, type, TYPE_PROPERTY);
- }
-
- /**
- * Returns the live list of variable declaration fragments in this
- * expression. Adding and removing nodes from this list affects this node
- * dynamically. All nodes in this list must be
- * <code>VariableDeclarationFragment</code>s; attempts to add any other
- * type of node will trigger an exception.
- *
- * @return the live list of variable declaration fragments in this
- * expression (element type: <code>VariableDeclarationFragment</code>)
- */
- public List fragments() {
- return this.variableDeclarationFragments;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- // treat Operator as free
- return BASE_NODE_SIZE + 4 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.modifiers == null ? 0 : this.modifiers.listSize())
- + (this.baseType == null ? 0 : getType().treeSize())
- + this.variableDeclarationFragments.listSize();
- }
-}
-
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
deleted file mode 100644
index 6763a1e0..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/VariableDeclarationFragment.java
+++ /dev/null
@@ -1,337 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Variable declaration fragment AST node type, used in field declarations,
- * local variable declarations, and <code>ForStatement</code> initializers.
- * It contrast to <code>SingleVariableDeclaration</code>, fragments are
- * missing the modifiers and the type; these are located in the fragment's
- * parent node.
- *
- * <pre>
- * VariableDeclarationFragment:
- * Identifier { <b>[</b><b>]</b> } [ <b>=</b> Expression ]
- * </pre>
- *
- *
- * 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 VariableDeclarationFragment extends VariableDeclaration {
-
- /**
- * The "name" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor NAME_PROPERTY =
- new ChildPropertyDescriptor(VariableDeclarationFragment.class, "name", SimpleName.class, MANDATORY, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "extraDimensions" structural property of this node type.
- *
- */
- public static final SimplePropertyDescriptor EXTRA_DIMENSIONS_PROPERTY =
- new SimplePropertyDescriptor(VariableDeclarationFragment.class, "extraDimensions", int.class, MANDATORY); //$NON-NLS-1$
-
- /**
- * The "initializer" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor INITIALIZER_PROPERTY =
- new ChildPropertyDescriptor(VariableDeclarationFragment.class, "initializer", Expression.class, OPTIONAL, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List propertyList = new ArrayList(4);
- createPropertyList(VariableDeclarationFragment.class, propertyList);
- addProperty(NAME_PROPERTY, propertyList);
- addProperty(EXTRA_DIMENSIONS_PROPERTY, propertyList);
- addProperty(INITIALIZER_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The variable name; lazily initialized; defaults to an unspecified,
- * legal JavaScript identifier.
- */
- private SimpleName variableName = null;
-
- /**
- * The number of extra array dimensions that this variable has;
- * defaults to 0.
- */
- private int extraArrayDimensions = 0;
-
- /**
- * The initializer expression, or <code>null</code> if none;
- * defaults to none.
- */
- private Expression optionalInitializer = null;
-
- /**
- * Creates a new AST node for a variable declaration fragment owned by the
- * given AST. By default, the variable declaration has: an unspecified
- * (but legal) variable name, no initializer, and no extra array dimensions.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- VariableDeclarationFragment(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on VariableDeclaration.
- *
- */
- final SimplePropertyDescriptor internalExtraDimensionsProperty() {
- return EXTRA_DIMENSIONS_PROPERTY;
- }
-
- /* (omit javadoc for this method)
- * Method declared on VariableDeclaration.
- *
- */
- final ChildPropertyDescriptor internalInitializerProperty() {
- return INITIALIZER_PROPERTY;
- }
-
- /* (omit javadoc for this method)
- * Method declared on VariableDeclaration.
- *
- */
- final ChildPropertyDescriptor internalNameProperty() {
- return NAME_PROPERTY;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int internalGetSetIntProperty(SimplePropertyDescriptor property, boolean get, int value) {
- if (property == EXTRA_DIMENSIONS_PROPERTY) {
- if (get) {
- return getExtraDimensions();
- } else {
- setExtraDimensions(value);
- return 0;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetIntProperty(property, get, value);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == NAME_PROPERTY) {
- if (get) {
- return getName();
- } else {
- setName((SimpleName) child);
- return null;
- }
- }
- if (property == INITIALIZER_PROPERTY) {
- if (get) {
- return getInitializer();
- } else {
- setInitializer((Expression) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return VARIABLE_DECLARATION_FRAGMENT;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- VariableDeclarationFragment result = new VariableDeclarationFragment(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.setName((SimpleName) getName().clone(target));
- result.setExtraDimensions(getExtraDimensions());
- result.setInitializer(
- (Expression) ASTNode.copySubtree(target, getInitializer()));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChild(visitor, getName());
- acceptChild(visitor, getInitializer());
- }
- visitor.endVisit(this);
- }
-
- /* (omit javadoc for this method)
- * Method declared on VariableDeclaration.
- */
- public SimpleName getName() {
- if (this.variableName == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.variableName == null) {
- preLazyInit();
- this.variableName = new SimpleName(this.ast);
- postLazyInit(this.variableName, NAME_PROPERTY);
- }
- }
- }
- return this.variableName;
- }
-
- /* (omit javadoc for this method)
- * Method declared on VariableDeclaration.
- */
- public void setName(SimpleName variableName) {
- if (variableName == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.variableName;
- preReplaceChild(oldChild, variableName, NAME_PROPERTY);
- this.variableName = variableName;
- postReplaceChild(oldChild, variableName, NAME_PROPERTY);
- }
-
- /**
- * Returns the number of extra array dimensions this variable has over
- * and above the type specified in the enclosing declaration.
- * <p>
- * For example, in the AST for <code>int[] i, j[], k[][]</code> the
- * variable declaration fragments for the variables <code>i</code>,
- * <code>j</code>, and <code>k</code>, have 0, 1, and 2 extra array
- * dimensions, respectively.
- * </p>
- *
- * @return the number of extra array dimensions this variable has over
- * and above the type specified in the enclosing declaration
- *
- */
- public int getExtraDimensions() {
- return this.extraArrayDimensions;
- }
-
- /**
- * Sets the number of extra array dimensions this variable has over
- * and above the type specified in the enclosing declaration.
- * <p>
- * For example, in the AST for <code>int[] i, j[], k[][]</code> the
- * variable declaration fragments for the variables <code>i</code>,
- * <code>j</code>, and <code>k</code>, have 0, 1, and 2 extra array
- * dimensions, respectively.
- * </p>
- *
- * @param dimensions the given dimensions
- *
- */
- public void setExtraDimensions(int dimensions) {
- if (dimensions < 0) {
- throw new IllegalArgumentException();
- }
- preValueChange(EXTRA_DIMENSIONS_PROPERTY);
- this.extraArrayDimensions = dimensions;
- postValueChange(EXTRA_DIMENSIONS_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on VariableDeclaration.
- */
- public Expression getInitializer() {
- return this.optionalInitializer;
- }
-
- /* (omit javadoc for this method)
- * Method declared on VariableDeclaration.
- */
- public void setInitializer(Expression initializer) {
- ASTNode oldChild = this.optionalInitializer;
- preReplaceChild(oldChild, initializer, INITIALIZER_PROPERTY);
- this.optionalInitializer = initializer;
- postReplaceChild(oldChild, initializer, INITIALIZER_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- // treat Operator as free
- return BASE_NODE_SIZE + 3 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.variableName == null ? 0 : getName().treeSize())
- + (this.optionalInitializer == null ? 0 : getInitializer().treeSize());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/VariableDeclarationStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/VariableDeclarationStatement.java
deleted file mode 100644
index 4dc7012a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/VariableDeclarationStatement.java
+++ /dev/null
@@ -1,491 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-/**
- * Local variable declaration statement AST node type.
- * <p>
- * This kind of node collects several variable declaration fragments
- * (<code>VariableDeclarationFragment</code>) into a statement
- * (<code>Statement</code>), all sharing the same modifiers and base type.
- * </p>
- * For JLS2:
- * <pre>
- * VariableDeclarationStatement:
- * { Modifier } Type VariableDeclarationFragment
- * { <b>,</b> VariableDeclarationFragment } <b>;</b>
- * </pre>
- * For JLS3, the modifier flags were replaced by
- * a list of modifier nodes (intermixed with annotations):
- * <pre>
- * VariableDeclarationStatement:
- * { ExtendedModifier } Type VariableDeclarationFragment
- * { <b>,</b> VariableDeclarationFragment } <b>;</b>
- * </pre>
- * <p>
- * Note: This type of node is a convenience of sorts.
- * An equivalent way to represent the same statement is to use
- * a <code>VariableDeclarationExpression</code>
- * wrapped in an <code>ExpressionStatement</code>.
- * </p>
- *
- * 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 VariableDeclarationStatement extends Statement {
-
- /**
- * The "modifiers" structural property of this node type (JLS2 API only).
- *
- */
- public static final SimplePropertyDescriptor MODIFIERS_PROPERTY =
- new SimplePropertyDescriptor(VariableDeclarationStatement.class, "modifiers", int.class, MANDATORY); //$NON-NLS-1$
-
- public static final ChildPropertyDescriptor JAVADOC_PROPERTY =
- new ChildPropertyDescriptor(VariableDeclarationStatement.class, "javadoc", JSdoc.class, OPTIONAL, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "modifiers" structural property of this node type (added in JLS3 API).
- *
- */
- public static final ChildListPropertyDescriptor MODIFIERS2_PROPERTY =
- new ChildListPropertyDescriptor(VariableDeclarationStatement.class, "modifiers", IExtendedModifier.class, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "type" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor TYPE_PROPERTY =
- new ChildPropertyDescriptor(VariableDeclarationStatement.class, "type", Type.class, MANDATORY, NO_CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "fragments" structural property of this node type).
- *
- */
- public static final ChildListPropertyDescriptor FRAGMENTS_PROPERTY =
- new ChildListPropertyDescriptor(VariableDeclarationStatement.class, "fragments", VariableDeclarationFragment.class, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS_2_0;
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- *
- */
- private static final List PROPERTY_DESCRIPTORS_3_0;
-
- static {
- List propertyList = new ArrayList(4);
- createPropertyList(VariableDeclarationStatement.class, propertyList);
- addProperty(MODIFIERS_PROPERTY, propertyList);
- addProperty(TYPE_PROPERTY, propertyList);
- addProperty(FRAGMENTS_PROPERTY, propertyList);
- addProperty(JAVADOC_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS_2_0 = reapPropertyList(propertyList);
-
- propertyList = new ArrayList(4);
- createPropertyList(VariableDeclarationStatement.class, propertyList);
- addProperty(MODIFIERS2_PROPERTY, propertyList);
- addProperty(TYPE_PROPERTY, propertyList);
- addProperty(FRAGMENTS_PROPERTY, propertyList);
- addProperty(JAVADOC_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS_3_0 = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- if (apiLevel == AST.JLS2_INTERNAL) {
- return PROPERTY_DESCRIPTORS_2_0;
- } else {
- return PROPERTY_DESCRIPTORS_3_0;
- }
- }
-
- /**
- * The extended modifiers (element type: <code>IExtendedModifier</code>).
- * Null in JLS2. Added in JLS3; defaults to an empty list
- * (see constructor).
- *
- */
- private ASTNode.NodeList modifiers = null;
-
- /**
- * The modifier flagss; bit-wise or of Modifier flags.
- * Defaults to none. Not used in JLS3.
- */
- private int modifierFlags = Modifier.NONE;
-
-
- JSdoc optionalDocComment = null;
-
- /**
- * The base type; lazily initialized; defaults to an unspecified,
- * legal type.
- */
- private Type baseType = null;
-
- /**
- * The list of variable variable declaration fragments (element type:
- * <code VariableDeclarationFragment</code>). Defaults to an empty list.
- */
- private ASTNode.NodeList variableDeclarationFragments =
- new ASTNode.NodeList(FRAGMENTS_PROPERTY);
-
- /**
- * Creates a new unparented local variable declaration statement node owned
- * by the given AST. By default, the variable declaration has: no modifiers,
- * an unspecified (but legal) type, and an empty list of variable
- * declaration fragments (which is syntactically illegal).
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- VariableDeclarationStatement(AST ast) {
- super(ast);
- if (ast.apiLevel >= AST.JLS3) {
- this.modifiers = new ASTNode.NodeList(MODIFIERS2_PROPERTY);
- }
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int internalGetSetIntProperty(SimplePropertyDescriptor property, boolean get, int value) {
- if (property == MODIFIERS_PROPERTY) {
- if (get) {
- return getModifiers();
- } else {
- setModifiers(value);
- return 0;
- }
- }
-
- // allow default implementation to flag the error
- return super.internalGetSetIntProperty(property, get, value);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == TYPE_PROPERTY) {
- if (get) {
- return getType();
- } else {
- setType((Type) child);
- return null;
- }
- }
- if (property == JAVADOC_PROPERTY) {
- if (get) {
- return getJavadoc();
- } else {
- setJavadoc((JSdoc) child);
- return null;
- }
- }
-
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalGetChildListProperty(ChildListPropertyDescriptor property) {
- if (property == MODIFIERS2_PROPERTY) {
- return modifiers();
- }
- if (property == FRAGMENTS_PROPERTY) {
- return fragments();
- }
- // allow default implementation to flag the error
- return super.internalGetChildListProperty(property);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return VARIABLE_DECLARATION_STATEMENT;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- VariableDeclarationStatement result =
- new VariableDeclarationStatement(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.copyLeadingComment(this);
- if (this.ast.apiLevel == AST.JLS2_INTERNAL) {
- result.setModifiers(getModifiers());
- }
- if (this.ast.apiLevel >= AST.JLS3) {
- result.modifiers().addAll(ASTNode.copySubtrees(target, modifiers()));
- }
- result.setType((Type) getType().clone(target));
- result.setJavadoc(
- (JSdoc) ASTNode.copySubtree(target, getJavadoc()));
- result.fragments().addAll(
- ASTNode.copySubtrees(target, fragments()));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- if (this.ast.apiLevel >= AST.JLS3) {
- acceptChildren(visitor, this.modifiers);
- }
- acceptChild(visitor, getType());
- acceptChild(visitor, getJavadoc());
- acceptChildren(visitor, this.variableDeclarationFragments);
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the live ordered list of modifiers and annotations
- * of this declaration (added in JLS3 API).
- * <p>
- * Note that the final modifier is the only meaningful modifier for local
- * variable declarations.
- * </p>
- *
- * @return the live list of modifiers and annotations
- * (element type: <code>IExtendedModifier</code>)
- * @exception UnsupportedOperationException if this operation is used in
- * a JLS2 AST
- *
- */
- public List modifiers() {
- // more efficient than just calling unsupportedIn2() to check
- if (this.modifiers == null) {
- unsupportedIn2();
- }
- return this.modifiers;
- }
-
- /**
- * Returns the modifiers explicitly specified on this declaration.
- * <p>
- * In the JLS3 API, this method is a convenience method that
- * computes these flags from <code>modifiers()</code>.
- * </p>
- *
- * @return the bit-wise or of <code>Modifier</code> constants
- * @see Modifier
- */
- public int getModifiers() {
- // more efficient than checking getAST().API_LEVEL
- if (this.modifiers == null) {
- // JLS2 behavior - bona fide property
- return this.modifierFlags;
- } else {
- // JLS3 behavior - convenience method
- // performance could be improved by caching computed flags
- // but this would require tracking changes to this.modifiers
- int computedModifierFlags = Modifier.NONE;
- for (Iterator it = modifiers().iterator(); it.hasNext(); ) {
- Object x = it.next();
- if (x instanceof Modifier) {
- computedModifierFlags |= ((Modifier) x).getKeyword().toFlagValue();
- }
- }
- return computedModifierFlags;
- }
- }
-
- /**
- * Sets the modifiers explicitly specified on this declaration (JLS2 API only).
- * <p>
- * Note that the final modifier is the only meaningful modifier for local
- * variable declarations.
- * </p>
- *
- * @param modifiers the given modifiers (bit-wise or of <code>Modifier</code> constants)
- * @exception UnsupportedOperationException if this operation is used in
- * an AST later than JLS2
- * @see Modifier
- * @deprecated In the JLS3 API, this method is replaced by
- * {@link #modifiers()} which contains a list of a <code>Modifier</code> nodes.
- */
- public void setModifiers(int modifiers) {
- internalSetModifiers(modifiers);
- }
-
- /**
- * Internal synonym for deprecated method. Used to avoid
- * deprecation warnings.
- *
- */
- /*package*/ final void internalSetModifiers(int pmodifiers) {
- supportedOnlyIn2();
- preValueChange(MODIFIERS_PROPERTY);
- this.modifierFlags = pmodifiers;
- postValueChange(MODIFIERS_PROPERTY);
- }
-
- /**
- * Returns the base type declared in this variable declaration statement.
- * <p>
- * N.B. The individual child variable declaration fragments may specify
- * additional array dimensions. So the type of the variable are not
- * necessarily exactly this type.
- * </p>
- *
- * @return the base type
- */
- public Type getType() {
- if (this.baseType == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.baseType == null) {
- preLazyInit();
- this.baseType = this.ast.newInferredType(null);
- postLazyInit(this.baseType, TYPE_PROPERTY);
- }
- }
- }
- return this.baseType;
- }
-
- /**
- * Sets the base type declared in this variable declaration statement to
- * the given type.
- *
- * @param type the new base type
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * </ul>
- */
- public void setType(Type type) {
- if (type == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.baseType;
- preReplaceChild(oldChild, type, TYPE_PROPERTY);
- this.baseType = type;
- postReplaceChild(oldChild, type, TYPE_PROPERTY);
- }
-
- /**
- * Returns the live list of variable declaration fragments in this statement.
- * Adding and removing nodes from this list affects this node dynamically.
- * All nodes in this list must be <code>VariableDeclarationFragment</code>s;
- * attempts to add any other type of node will trigger an
- * exception.
- *
- * @return the live list of variable declaration fragments in this
- * statement (element type: <code>VariableDeclarationFragment</code>)
- */
- public List fragments() {
- return this.variableDeclarationFragments;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return super.memSize() + 4 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.modifiers == null ? 0 : this.modifiers.listSize())
- + (this.baseType == null ? 0 : getType().treeSize())
- + this.variableDeclarationFragments.listSize();
- }
-
- public IVariableBinding resolveBinding() {
- return this.ast.getBindingResolver().resolveVariable(this);
- }
-
- /**
- * Returns the doc comment node.
- *
- * @return the doc comment node, or <code>null</code> if none
- */
- public JSdoc getJavadoc() {
- return this.optionalDocComment;
- }
-
- /**
- * Sets or clears the doc comment node.
- *
- * @param docComment the doc comment node, or <code>null</code> if none
- * @exception IllegalArgumentException if the doc comment string is invalid
- */
- public void setJavadoc(JSdoc docComment) {
- ChildPropertyDescriptor p = internalJavadocProperty();
- ASTNode oldChild = this.optionalDocComment;
- preReplaceChild(oldChild, docComment, p);
- this.optionalDocComment = docComment;
- postReplaceChild(oldChild, docComment, p);
- }
- final ChildPropertyDescriptor internalJavadocProperty() {
- return JAVADOC_PROPERTY;
- }
-
-}
-
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
deleted file mode 100644
index 92c12704..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/WhileStatement.java
+++ /dev/null
@@ -1,278 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * While statement AST node type.
- *
- * <pre>
- * WhileStatement:
- * <b>while</b> <b>(</b> Expression <b>)</b> Statement
- * </pre>
- *
- * 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 WhileStatement extends Statement {
-
- /**
- * The "expression" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor EXPRESSION_PROPERTY =
- new ChildPropertyDescriptor(WhileStatement.class, "expression", Expression.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "body" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor BODY_PROPERTY =
- new ChildPropertyDescriptor(WhileStatement.class, "body", Statement.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List propertyList = new ArrayList(3);
- createPropertyList(WhileStatement.class, propertyList);
- addProperty(EXPRESSION_PROPERTY, propertyList);
- addProperty(BODY_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The expression; lazily initialized; defaults to an unspecified, but
- * legal, expression.
- */
- private Expression expression = null;
-
- /**
- * The body statement; lazily initialized; defaults to an empty block
- * statement.
- */
- private Statement body = null;
-
- /**
- * Creates a new unparented while statement node owned by the given
- * AST. By default, the expresssion is unspecified, but legal, and
- * the body statement is an empty block.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- WhileStatement(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == EXPRESSION_PROPERTY) {
- if (get) {
- return getExpression();
- } else {
- setExpression((Expression) child);
- return null;
- }
- }
- if (property == BODY_PROPERTY) {
- if (get) {
- return getBody();
- } else {
- setBody((Statement) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return WHILE_STATEMENT;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- WhileStatement result = new WhileStatement(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.copyLeadingComment(this);
- result.setExpression((Expression) getExpression().clone(target));
- result.setBody((Statement) getBody().clone(target));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChild(visitor, getExpression());
- acceptChild(visitor, getBody());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the expression of this while statement.
- *
- * @return the expression node
- */
- public Expression getExpression() {
- if (this.expression == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.expression == null) {
- preLazyInit();
- this.expression = new SimpleName(this.ast);
- postLazyInit(this.expression, EXPRESSION_PROPERTY);
- }
- }
- }
- return this.expression;
- }
-
- /**
- * Sets the expression of this while statement.
- *
- * @param expression the expression node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setExpression(Expression expression) {
- if (expression == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.expression;
- preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY);
- this.expression = expression;
- postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY);
- }
-
- /**
- * Returns the body of this while statement.
- *
- * @return the body statement node
- */
- public Statement getBody() {
- if (this.body == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.body == null) {
- preLazyInit();
- this.body = new Block(this.ast);
- postLazyInit(this.body, BODY_PROPERTY);
- }
- }
- }
- return this.body;
- }
-
- /**
- * Sets the body of this while statement.
- * <p>
- * Special note: The JavaScript language does not allow a local variable declaration
- * to appear as the body of a while statement (they may only appear within a
- * block). However, the AST will allow a <code>VariableDeclarationStatement</code>
- * as the body of a <code>WhileStatement</code>. To get something that will
- * compile, be sure to embed the <code>VariableDeclarationStatement</code>
- * inside a <code>Block</code>.
- * </p>
- *
- * @param statement the body statement node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setBody(Statement statement) {
- if (statement == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.body;
- preReplaceChild(oldChild, statement, BODY_PROPERTY);
- this.body = statement;
- postReplaceChild(oldChild, statement, BODY_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return super.memSize() + 2 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.expression == null ? 0 : getExpression().treeSize())
- + (this.body == null ? 0 : getBody().treeSize());
- }
-}
-
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
deleted file mode 100644
index 5c063c32..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/WithStatement.java
+++ /dev/null
@@ -1,278 +0,0 @@
-/*******************************************************************************
- * 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.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * With statement AST node type.
- *
- * <pre>
- * WithStatement:
- * <b>with</b> <b>(</b> Expression <b>)</b> Statement
- * </pre>
- *
- * 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 WithStatement extends Statement {
-
- /**
- * The "expression" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor EXPRESSION_PROPERTY =
- new ChildPropertyDescriptor(WithStatement.class, "expression", Expression.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * The "body" structural property of this node type.
- *
- */
- public static final ChildPropertyDescriptor BODY_PROPERTY =
- new ChildPropertyDescriptor(WithStatement.class, "body", Statement.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
-
- /**
- * A list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor}),
- * or null if uninitialized.
- */
- private static final List PROPERTY_DESCRIPTORS;
-
- static {
- List propertyList = new ArrayList(3);
- createPropertyList(WithStatement.class, propertyList);
- addProperty(EXPRESSION_PROPERTY, propertyList);
- addProperty(BODY_PROPERTY, propertyList);
- PROPERTY_DESCRIPTORS = reapPropertyList(propertyList);
- }
-
- /**
- * Returns a list of structural property descriptors for this node type.
- * Clients must not modify the result.
- *
- * @param apiLevel the API level; one of the
- * <code>AST.JLS*</code> constants
-
- * @return a list of property descriptors (element type:
- * {@link StructuralPropertyDescriptor})
- *
- */
- public static List propertyDescriptors(int apiLevel) {
- return PROPERTY_DESCRIPTORS;
- }
-
- /**
- * The expression; lazily initialized; defaults to an unspecified, but
- * legal, expression.
- */
- private Expression expression = null;
-
- /**
- * The body statement; lazily initialized; defaults to an empty block
- * statement.
- */
- private Statement body = null;
-
- /**
- * Creates a new unparented with statement node owned by the given
- * AST. By default, the expresssion is unspecified, but legal, and
- * the body statement is an empty block.
- * <p>
- * N.B. This constructor is package-private.
- * </p>
- *
- * @param ast the AST that is to own this node
- */
- WithStatement(AST ast) {
- super(ast);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final List internalStructuralPropertiesForType(int apiLevel) {
- return propertyDescriptors(apiLevel);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) {
- if (property == EXPRESSION_PROPERTY) {
- if (get) {
- return getExpression();
- } else {
- setExpression((Expression) child);
- return null;
- }
- }
- if (property == BODY_PROPERTY) {
- if (get) {
- return getBody();
- } else {
- setBody((Statement) child);
- return null;
- }
- }
- // allow default implementation to flag the error
- return super.internalGetSetChildProperty(property, get, child);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final int getNodeType0() {
- return WITH_STATEMENT;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- ASTNode clone0(AST target) {
- WithStatement result = new WithStatement(target);
- result.setSourceRange(this.getStartPosition(), this.getLength());
- result.copyLeadingComment(this);
- result.setExpression((Expression) getExpression().clone(target));
- result.setBody((Statement) getBody().clone(target));
- return result;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- final boolean subtreeMatch0(ASTMatcher matcher, Object other) {
- // dispatch to correct overloaded match method
- return matcher.match(this, other);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- void accept0(ASTVisitor visitor) {
- boolean visitChildren = visitor.visit(this);
- if (visitChildren) {
- // visit children in normal left to right reading order
- acceptChild(visitor, getExpression());
- acceptChild(visitor, getBody());
- }
- visitor.endVisit(this);
- }
-
- /**
- * Returns the expression of this with statement.
- *
- * @return the expression node
- */
- public Expression getExpression() {
- if (this.expression == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.expression == null) {
- preLazyInit();
- this.expression = new SimpleName(this.ast);
- postLazyInit(this.expression, EXPRESSION_PROPERTY);
- }
- }
- }
- return this.expression;
- }
-
- /**
- * Sets the expression of this with statement.
- *
- * @param expression the expression node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setExpression(Expression expression) {
- if (expression == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.expression;
- preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY);
- this.expression = expression;
- postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY);
- }
-
- /**
- * Returns the body of this with statement.
- *
- * @return the body statement node
- */
- public Statement getBody() {
- if (this.body == null) {
- // lazy init must be thread-safe for readers
- synchronized (this) {
- if (this.body == null) {
- preLazyInit();
- this.body = new Block(this.ast);
- postLazyInit(this.body, BODY_PROPERTY);
- }
- }
- }
- return this.body;
- }
-
- /**
- * Sets the body of this with statement.
- * <p>
- * Special note: The JavaScript language does not allow a local variable declaration
- * to appear as the body of a with statement (they may only appear within a
- * block). However, the AST will allow a <code>VariableDeclarationStatement</code>
- * as the body of a <code>WithStatement</code>. To get something that will
- * compile, be sure to embed the <code>VariableDeclarationStatement</code>
- * inside a <code>Block</code>.
- * </p>
- *
- * @param statement the body statement node
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the node belongs to a different AST</li>
- * <li>the node already has a parent</li>
- * <li>a cycle in would be created</li>
- * </ul>
- */
- public void setBody(Statement statement) {
- if (statement == null) {
- throw new IllegalArgumentException();
- }
- ASTNode oldChild = this.body;
- preReplaceChild(oldChild, statement, BODY_PROPERTY);
- this.body = statement;
- postReplaceChild(oldChild, statement, BODY_PROPERTY);
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int memSize() {
- return super.memSize() + 2 * 4;
- }
-
- /* (omit javadoc for this method)
- * Method declared on ASTNode.
- */
- int treeSize() {
- return
- memSize()
- + (this.expression == null ? 0 : getExpression().treeSize())
- + (this.body == null ? 0 : getBody().treeSize());
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/rewrite/ASTRewrite.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/rewrite/ASTRewrite.java
deleted file mode 100644
index 40ef5617..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/rewrite/ASTRewrite.java
+++ /dev/null
@@ -1,653 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.dom.rewrite;
-
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.ITypeRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.ChildListPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.StructuralPropertyDescriptor;
-import org.eclipse.wst.jsdt.internal.core.dom.rewrite.ASTRewriteAnalyzer;
-import org.eclipse.wst.jsdt.internal.core.dom.rewrite.LineInformation;
-import org.eclipse.wst.jsdt.internal.core.dom.rewrite.NodeInfoStore;
-import org.eclipse.wst.jsdt.internal.core.dom.rewrite.NodeRewriteEvent;
-import org.eclipse.wst.jsdt.internal.core.dom.rewrite.RewriteEventStore;
-import org.eclipse.wst.jsdt.internal.core.dom.rewrite.TrackedNodePosition;
-import org.eclipse.wst.jsdt.internal.core.dom.rewrite.RewriteEventStore.CopySourceInfo;
-
-/**
- * Infrastructure for modifying code by describing changes to AST nodes.
- * The AST rewriter collects descriptions of modifications to nodes and
- * translates these descriptions into text edits that can then be applied to
- * the original source. The key thing is that this is all done without actually
- * modifying the original AST, which has the virtue of allowing one to entertain
- * several alternate sets of changes on the same AST (e.g., for calculating
- * quick fix proposals). The rewrite infrastructure tries to generate minimal
- * text changes, preserve existing comments and indentation, and follow code
- * formatter settings. If the freedom to explore multiple alternate changes is
- * not required, consider using the AST's built-in rewriter
- * (see {@link org.eclipse.wst.jsdt.core.dom.JavaScriptUnit#rewrite(IDocument, Map)}).
- * <p>
- * The following code snippet illustrated usage of this class:
- * </p>
- * <pre>
- * Document document = new Document("import java.util.List;\nclass X {}\n");
- * ASTParser parser = ASTParser.newParser(AST.JLS3);
- * parser.setSource(doc.get().toCharArray());
- * JavaScriptUnit cu = (JavaScriptUnit) parser.createAST(null);
- * AST ast = cu.getAST();
- * ImportDeclaration id = ast.newImportDeclaration();
- * id.setName(ast.newName(new String[] {"java", "util", "Set"}));
- * ASTRewrite rewriter = ASTRewrite.create(ast);
- * TypeDeclaration td = (TypeDeclaration) cu.types().get(0);
- * ITrackedNodePosition tdLocation = rewriter.track(td);
- * ListRewrite lrw = rewriter.getListRewrite(cu, JavaScriptUnit.IMPORTS_PROPERTY);
- * lrw.insertLast(id, null);
- * TextEdit edits = rewriter.rewriteAST(document, null);
- * UndoEdit undo = edits.apply(document);
- * assert "import java.util.List;\nimport java.util.Set;\nclass X {}".equals(doc.get().toCharArray());
- * // tdLocation.getStartPosition() and tdLocation.getLength()
- * // are new source range for "class X {}" in doc.get()
- * </pre>
- * <p>
- * This class is not intended to be subclassed.
- * </p>
- *
- * 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 ASTRewrite {
-
- /** root node for the rewrite: Only nodes under this root are accepted */
- private final AST ast;
-
- private final RewriteEventStore eventStore;
- private final NodeInfoStore nodeStore;
-
- /**
- * Target source range computer; null means uninitialized;
- * lazy initialized to <code>new TargetSourceRangeComputer()</code>.
- */
- private TargetSourceRangeComputer targetSourceRangeComputer = null;
-
- /**
- * Creates a new instance for describing manipulations of
- * the given AST.
- *
- * @param ast the AST whose nodes will be rewritten
- * @return the new rewriter instance
- */
- public static ASTRewrite create(AST ast) {
- return new ASTRewrite(ast);
- }
-
- /**
- * Internal constructor. Creates a new instance for the given AST.
- * Clients should use {@link #create(AST)} to create instances.
- *
- * @param ast the AST being rewritten
- */
- protected ASTRewrite(AST ast) {
- this.ast= ast;
- this.eventStore= new RewriteEventStore();
- this.nodeStore= new NodeInfoStore(ast);
- }
-
- /**
- * Returns the AST the rewrite was set up on.
- *
- * @return the AST the rewrite was set up on
- */
- public final AST getAST() {
- return this.ast;
- }
-
- /**
- * Internal method. Returns the internal event store.
- * Clients should not use.
- * @return Returns the internal event store. Clients should not use.
- */
- protected final RewriteEventStore getRewriteEventStore() {
- return this.eventStore;
- }
-
- /**
- * Internal method. Returns the internal node info store.
- * Clients should not use.
- * @return Returns the internal info store. Clients should not use.
- */
- protected final NodeInfoStore getNodeStore() {
- return this.nodeStore;
- }
-
- /**
- * Converts all modifications recorded by this rewriter
- * into an object representing the corresponding text
- * edits to the given document containing the original source
- * code. The document itself is not modified.
- * <p>
- * For nodes in the original that are being replaced or deleted,
- * this rewriter computes the adjusted source ranges
- * by calling <code>getTargetSourceRangeComputer().computeSourceRange(node)</code>.
- * </p>
- * <p>
- * Calling this methods does not discard the modifications
- * on record. Subsequence modifications are added to the ones
- * already on record. If this method is called again later,
- * the resulting text edit object will accurately reflect
- * the net cumulative affect of all those changes.
- * </p>
- *
- * @param document original document containing source code
- * @param options the table of formatter options
- * (key type: <code>String</code>; value type: <code>String</code>);
- * or <code>null</code> to use the standard global options
- * {@link org.eclipse.wst.jsdt.core.JavaScriptCore#getOptions() org.eclipse.wst.jsdt.core.JavaScriptCore.getOptions()}
- * @return text edit object describing the changes to the
- * document corresponding to the changes recorded by this rewriter
- * @throws IllegalArgumentException An <code>IllegalArgumentException</code>
- * is thrown if the document passed does not correspond to the AST that is rewritten.
- */
- public TextEdit rewriteAST(IDocument document, Map options) throws IllegalArgumentException {
- if (document == null) {
- throw new IllegalArgumentException();
- }
-
- ASTNode rootNode= getRootNode();
- if (rootNode == null) {
- return new MultiTextEdit(); // no changes
- }
-
- char[] content= document.get().toCharArray();
- LineInformation lineInfo= LineInformation.create(document);
- String lineDelim= TextUtilities.getDefaultLineDelimiter(document);
-
- ASTNode astRoot= rootNode.getRoot();
- List commentNodes= astRoot instanceof JavaScriptUnit ? ((JavaScriptUnit) astRoot).getCommentList() : null;
- return internalRewriteAST(content, lineInfo, lineDelim, commentNodes, options, rootNode);
- }
-
- /**
- * Converts all modifications recorded by this rewriter into an object representing the the corresponding text
- * edits to the source of a {@link ITypeRoot} from which the AST was created from.
- * The type root's source itself is not modified by this method call.
- * <p>
- * Important: This API can only be used if the modified AST has been created from a
- * {@link ITypeRoot} with source. That means {@link org.eclipse.wst.jsdt.core.dom.ASTParser#setSource(org.eclipse.wst.jsdt.core.IJavaScriptUnit)},
- * {@link org.eclipse.wst.jsdt.core.dom.ASTParser#setSource(org.eclipse.wst.jsdt.core.IClassFile)} or {@link org.eclipse.wst.jsdt.core.dom.ASTParser#setSource(ITypeRoot)}
- * has been used when initializing the {@link org.eclipse.wst.jsdt.core.dom.ASTParser}. A {@link IllegalArgumentException} is thrown
- * otherwise. An {@link IllegalArgumentException} is also thrown when the type roots buffer does not correspond
- * anymore to the AST. Use {@link #rewriteAST(IDocument, Map)} for all ASTs created from other content.
- * </p>
- * <p>
- * For nodes in the original that are being replaced or deleted,
- * this rewriter computes the adjusted source ranges
- * by calling <code>getTargetSourceRangeComputer().computeSourceRange(node)</code>.
- * </p>
- * <p>
- * Calling this methods does not discard the modifications
- * on record. Subsequence modifications are added to the ones
- * already on record. If this method is called again later,
- * the resulting text edit object will accurately reflect
- * the net cumulative affect of all those changes.
- * </p>
- *
- * @return text edit object describing the changes to the
- * document corresponding to the changes recorded by this rewriter
- * @throws JavaScriptModelException A {@link JavaScriptModelException} is thrown when
- * the underlying javaScript units buffer could not be accessed.
- * @throws IllegalArgumentException An {@link IllegalArgumentException}
- * is thrown if the document passed does not correspond to the AST that is rewritten.
- *
- */
- public TextEdit rewriteAST() throws JavaScriptModelException, IllegalArgumentException {
- ASTNode rootNode= getRootNode();
- if (rootNode == null) {
- return new MultiTextEdit(); // no changes
- }
-
- ASTNode root= rootNode.getRoot();
- if (!(root instanceof JavaScriptUnit)) {
- throw new IllegalArgumentException("This API can only be used if the AST is created from a javaScript unit or class file"); //$NON-NLS-1$
- }
- JavaScriptUnit astRoot= (JavaScriptUnit) root;
- ITypeRoot typeRoot = astRoot.getTypeRoot();
- if (typeRoot == null || typeRoot.getBuffer() == null) {
- throw new IllegalArgumentException("This API can only be used if the AST is created from a javaScript unit or class file"); //$NON-NLS-1$
- }
-
- char[] content= typeRoot.getBuffer().getCharacters();
- LineInformation lineInfo= LineInformation.create(astRoot);
- String lineDelim= typeRoot.findRecommendedLineSeparator();
- Map options= typeRoot.getJavaScriptProject().getOptions(true);
-
- return internalRewriteAST(content, lineInfo, lineDelim, astRoot.getCommentList(), options, rootNode);
- }
-
- private TextEdit internalRewriteAST(char[] content, LineInformation lineInfo, String lineDelim, List commentNodes, Map options, ASTNode rootNode) {
- TextEdit result= new MultiTextEdit();
- //validateASTNotModified(rootNode);
-
- TargetSourceRangeComputer sourceRangeComputer= getExtendedSourceRangeComputer();
- this.eventStore.prepareMovedNodes(sourceRangeComputer);
-
- ASTRewriteAnalyzer visitor= new ASTRewriteAnalyzer(content, lineInfo, lineDelim, result, this.eventStore, this.nodeStore, commentNodes, options, sourceRangeComputer);
- rootNode.accept(visitor); // throws IllegalArgumentException
-
- this.eventStore.revertMovedNodes();
- return result;
- }
-
- private ASTNode getRootNode() {
- ASTNode node= null;
- int start= -1;
- int end= -1;
-
- for (Iterator iter= getRewriteEventStore().getChangeRootIterator(); iter.hasNext();) {
- ASTNode curr= (ASTNode) iter.next();
- if (!RewriteEventStore.isNewNode(curr)) {
- int currStart= curr.getStartPosition();
- int currEnd= currStart + curr.getLength();
- if (node == null || currStart < start && currEnd > end) {
- start= currStart;
- end= currEnd;
- node= curr;
- } else if (currStart < start) {
- start= currStart;
- } else if (currEnd > end) {
- end= currEnd;
- }
- }
- }
- if (node != null) {
- int currStart= node.getStartPosition();
- int currEnd= currStart + node.getLength();
- while (start < currStart || end > currEnd) { // go up until a node covers all
- node= node.getParent();
- currStart= node.getStartPosition();
- currEnd= currStart + node.getLength();
- }
- ASTNode parent= node.getParent(); // go up until a parent has different range
- while (parent != null && parent.getStartPosition() == node.getStartPosition() && parent.getLength() == node.getLength()) {
- node= parent;
- parent= node.getParent();
- }
- }
- return node;
- }
-
- /*
- private void validateASTNotModified(ASTNode root) throws IllegalArgumentException {
- GenericVisitor isModifiedVisitor= new GenericVisitor() {
- protected boolean visitNode(ASTNode node) {
- if ((node.getFlags() & ASTNode.ORIGINAL) == 0) {
- throw new IllegalArgumentException("The AST that is rewritten must not be modified."); //$NON-NLS-1$
- }
- return true;
- }
- };
- root.accept(isModifiedVisitor);
- }
- */
-
- /**
- * Removes the given node from its parent in this rewriter. The AST itself
- * is not actually modified in any way; rather, the rewriter just records
- * a note that this node should not be there.
- *
- * @param node the node being removed
- * @param editGroup the edit group in which to collect the corresponding
- * text edits, or <code>null</code> if ungrouped
- * @throws IllegalArgumentException if the node is null, or if the node is not
- * part of this rewriter's AST, or if the described modification is invalid
- * (such as removing a required node)
- */
- public final void remove(ASTNode node, TextEditGroup editGroup) {
- if (node == null) {
- throw new IllegalArgumentException();
- }
- StructuralPropertyDescriptor property= node.getLocationInParent();
- if (property.isChildListProperty()) {
- getListRewrite(node.getParent(), (ChildListPropertyDescriptor) property).remove(node, editGroup);
- } else {
- set(node.getParent(), property, null, editGroup);
- }
- }
-
- /**
- * Replaces the given node in this rewriter. The replacement node
- * must either be brand new (not part of the original AST) or a placeholder
- * node (for example, one created by {@link #createCopyTarget(ASTNode)}
- * or {@link #createStringPlaceholder(String, int)}). The AST itself
- * is not actually modified in any way; rather, the rewriter just records
- * a note that this node has been replaced.
- *
- * @param node the node being replaced
- * @param replacement the replacement node, or <code>null</code> if no
- * replacement
- * @param editGroup the edit group in which to collect the corresponding
- * text edits, or <code>null</code> if ungrouped
- * @throws IllegalArgumentException if the node is null, or if the node is not part
- * of this rewriter's AST, or if the replacement node is not a new node (or
- * placeholder), or if the described modification is otherwise invalid
- */
- public final void replace(ASTNode node, ASTNode replacement, TextEditGroup editGroup) {
- if (node == null) {
- throw new IllegalArgumentException();
- }
- StructuralPropertyDescriptor property= node.getLocationInParent();
- if (property.isChildListProperty()) {
- getListRewrite(node.getParent(), (ChildListPropertyDescriptor) property).replace(node, replacement, editGroup);
- } else {
- set(node.getParent(), property, replacement, editGroup);
- }
- }
-
- /**
- * Sets the given property of the given node. If the given property is a child
- * property, the value must be a replacement node that is either be brand new
- * (not part of the original AST) or a placeholder node (for example, one
- * created by {@link #createCopyTarget(ASTNode)}
- * or {@link #createStringPlaceholder(String, int)}); or it must be
- * <code>null</code>, indicating that the child should be deleted.
- * If the given property is a simple property, the value must be the new
- * value (primitive types must be boxed) or <code>null</code>.
- * The AST itself is not actually modified in any way; rather, the rewriter
- * just records a note that this node has been changed in the specified way.
- *
- * @param node the node
- * @param property the node's property; either a simple property or a child property
- * @param value the replacement child or new value, or <code>null</code> if none
- * @param editGroup the edit group in which to collect the corresponding
- * text edits, or <code>null</code> if ungrouped
- * @throws IllegalArgumentException if the node or property is null, or if the node
- * is not part of this rewriter's AST, or if the property is not a node property,
- * or if the described modification is invalid
- */
- public final void set(ASTNode node, StructuralPropertyDescriptor property, Object value, TextEditGroup editGroup) {
- if (node == null || property == null) {
- throw new IllegalArgumentException();
- }
- validateIsCorrectAST(node);
- validatePropertyType(property, value);
-
- NodeRewriteEvent nodeEvent= this.eventStore.getNodeEvent(node, property, true);
- nodeEvent.setNewValue(value);
- if (editGroup != null) {
- this.eventStore.setEventEditGroup(nodeEvent, editGroup);
- }
- }
-
- /**
- * Returns the value of the given property as managed by this rewriter. If the property
- * has been removed, <code>null</code> is returned. If it has been replaced, the replacing value
- * is returned. If the property has not been changed yet, the original value is returned.
- * <p>
- * For child list properties use {@link ListRewrite#getRewrittenList()} to get access to the
- * rewritten nodes in a list. </p>
- *
- * @param node the node
- * @param property the node's property
- * @return the value of the given property as managed by this rewriter
- *
- */
- public Object get(ASTNode node, StructuralPropertyDescriptor property) {
- if (node == null || property == null) {
- throw new IllegalArgumentException();
- }
- if (property.isChildListProperty()) {
- throw new IllegalArgumentException("Use the list rewriter to access nodes in a list"); //$NON-NLS-1$
- }
- return this.eventStore.getNewValue(node, property);
- }
-
- /**
- * Creates and returns a new rewriter for describing modifications to the
- * given list property of the given node.
- *
- * @param node the node
- * @param property the node's property; the child list property
- * @return a new list rewriter object
- * @throws IllegalArgumentException if the node or property is null, or if the node
- * is not part of this rewriter's AST, or if the property is not a node property,
- * or if the described modification is invalid
- */
- public final ListRewrite getListRewrite(ASTNode node, ChildListPropertyDescriptor property) {
- if (node == null || property == null) {
- throw new IllegalArgumentException();
- }
- validateIsListProperty(property);
-
- return new ListRewrite(this, node, property);
- }
-
- /**
- * Returns an object that tracks the source range of the given node
- * across the rewrite to its AST. Upon return, the result object reflects
- * the given node's current source range in the AST. After
- * <code>rewrite</code> is called, the result object is updated to
- * reflect the given node's source range in the rewritten AST.
- *
- * @param node the node to track
- * @return an object that tracks the source range of <code>node</code>
- * @throws IllegalArgumentException if the node is null, or if the node
- * is not part of this rewriter's AST, or if the node is already being
- * tracked
- */
- public final ITrackedNodePosition track(ASTNode node) {
- if (node == null) {
- throw new IllegalArgumentException();
- }
- TextEditGroup group= this.eventStore.getTrackedNodeData(node);
- if (group == null) {
- group= new TextEditGroup("internal"); //$NON-NLS-1$
- this.eventStore.setTrackedNodeData(node, group);
- }
- return new TrackedNodePosition(group, node);
- }
-
- private void validateIsExistingNode(ASTNode node) {
- if (node.getStartPosition() == -1) {
- throw new IllegalArgumentException("Node is not an existing node"); //$NON-NLS-1$
- }
- }
-
- private void validateIsCorrectAST(ASTNode node) {
- if (node.getAST() != getAST()) {
- throw new IllegalArgumentException("Node is not inside the AST"); //$NON-NLS-1$
- }
- }
-
- private void validateIsListProperty(StructuralPropertyDescriptor property) {
- if (!property.isChildListProperty()) {
- String message= property.getId() + " is not a list property"; //$NON-NLS-1$
- throw new IllegalArgumentException(message);
- }
- }
-
- private void validatePropertyType(StructuralPropertyDescriptor prop, Object node) {
- if (prop.isChildListProperty()) {
- String message= "Can not modify a list property, use a list rewriter"; //$NON-NLS-1$
- throw new IllegalArgumentException(message);
- }
-// if (node == null) {
-// if (prop.isSimpleProperty() || (prop.isChildProperty() && ((ChildPropertyDescriptor) prop).isMandatory())) {
-// String message= "Can not remove property " + prop.getId();
-// throw new IllegalArgumentException(message);
-// }
-// } else {
-// if (!prop.getNodeClass().isInstance(node)) {
-// String message= node.getClass().getName() + " is not a valid type for property " + prop.getId();
-// throw new IllegalArgumentException(message);
-// }
-// }
- }
-
- /**
- * Creates and returns a placeholder node for a source string that is to be inserted into
- * the output document at the position corresponding to the placeholder.
- * The string will be inserted without being reformatted beyond correcting
- * the indentation level. The placeholder node can either be inserted as new or
- * used to replace an existing node.
- *
- * @param code the string to be inserted; lines should should not have extra indentation
- * @param nodeType the ASTNode type that corresponds to the passed code.
- * @return the new placeholder node
- * @throws IllegalArgumentException if the code is null, or if the node
- * type is invalid
- */
- public final ASTNode createStringPlaceholder(String code, int nodeType) {
- if (code == null) {
- throw new IllegalArgumentException();
- }
- ASTNode placeholder= getNodeStore().newPlaceholderNode(nodeType);
- if (placeholder == null) {
- throw new IllegalArgumentException("String placeholder is not supported for type" + nodeType); //$NON-NLS-1$
- }
-
- getNodeStore().markAsStringPlaceholder(placeholder, code);
- return placeholder;
- }
-
- /**
- * Creates and returns a node that represents a sequence of nodes.
- * Each of the given nodes must be either be brand new (not part of the original AST), or
- * a placeholder node (for example, one created by {@link #createCopyTarget(ASTNode)}
- * or {@link #createStringPlaceholder(String, int)}), or another group node.
- * The type of the returned node is unspecified. The returned node can be used
- * to replace an existing node (or as an element of another group node).
- * When the document is rewritten, the source code for each of the given nodes is
- * inserted, in order, into the output document at the position corresponding to the
- * group (indentation is adjusted).
- *
- * @param targetNodes the nodes to go in the group
- * @return the new group node
- * @throws IllegalArgumentException if the targetNodes is <code>null</code> or empty
- */
- public final ASTNode createGroupNode(ASTNode[] targetNodes) {
- if (targetNodes == null || targetNodes.length == 0) {
- throw new IllegalArgumentException();
- }
- Block res= getNodeStore().createCollapsePlaceholder();
- ListRewrite listRewrite= getListRewrite(res, Block.STATEMENTS_PROPERTY);
- for (int i= 0; i < targetNodes.length; i++) {
- listRewrite.insertLast(targetNodes[i], null);
- }
- return res;
- }
-
-
- private ASTNode createTargetNode(ASTNode node, boolean isMove) {
- if (node == null) {
- throw new IllegalArgumentException();
- }
- validateIsExistingNode(node);
- validateIsCorrectAST(node);
- CopySourceInfo info= getRewriteEventStore().markAsCopySource(node.getParent(), node.getLocationInParent(), node, isMove);
-
- ASTNode placeholder= getNodeStore().newPlaceholderNode(node.getNodeType());
- if (placeholder == null) {
- throw new IllegalArgumentException("Creating a target node is not supported for nodes of type" + node.getClass().getName()); //$NON-NLS-1$
- }
- getNodeStore().markAsCopyTarget(placeholder, info);
-
- return placeholder;
- }
-
- /**
- * Creates and returns a placeholder node for a true copy of the given node.
- * The placeholder node can either be inserted as new or used to replace an
- * existing node. When the document is rewritten, a copy of the source code
- * for the given node is inserted into the output document at the position
- * corresponding to the placeholder (indentation is adjusted).
- *
- * @param node the node to create a copy placeholder for
- * @return the new placeholder node
- * @throws IllegalArgumentException if the node is null, or if the node
- * is not part of this rewriter's AST
- */
- public final ASTNode createCopyTarget(ASTNode node) {
- return createTargetNode(node, false);
- }
-
- /**
- * Creates and returns a placeholder node for the new locations of the given node.
- * After obtaining a placeholder, the node should then to be removed or replaced.
- * The placeholder node can either be inserted as new or used to replace an
- * existing node. When the document is rewritten, the source code for the given
- * node is inserted into the output document at the position corresponding to the
- * placeholder (indentation is adjusted).
- *
- * @param node the node to create a move placeholder for
- * @return the new placeholder node
- * @throws IllegalArgumentException if the node is null, or if the node
- * is not part of this rewriter's AST
- */
- public final ASTNode createMoveTarget(ASTNode node) {
- return createTargetNode(node, true);
- }
-
- /**
- * Returns the extended source range computer for this AST rewriter.
- * The default value is a <code>new TargetSourceRangeComputer()</code>.
- *
- * @return an extended source range computer
- */
- public final TargetSourceRangeComputer getExtendedSourceRangeComputer() {
- if (this.targetSourceRangeComputer == null) {
- // lazy initialize
- this.targetSourceRangeComputer = new TargetSourceRangeComputer();
- }
- return this.targetSourceRangeComputer;
- }
-
- /**
- * Sets a custom target source range computer for this AST rewriter. This is advanced feature to modify how
- * comments are associated with nodes, which should be done only in special cases.
- *
- * @param computer a target source range computer,
- * or <code>null</code> to restore the default value of
- * <code>new TargetSourceRangeComputer()</code>
- */
- public final void setTargetSourceRangeComputer(TargetSourceRangeComputer computer) {
- // if computer==null, rely on lazy init code in getTargetSourceRangeComputer()
- this.targetSourceRangeComputer = computer;
- }
-
- /**
- * Returns a string suitable for debugging purposes (only).
- *
- * @return a debug string
- */
- public String toString() {
- StringBuffer buf= new StringBuffer();
- buf.append("Events:\n"); //$NON-NLS-1$
- // be extra careful of uninitialized or mangled instances
- if (this.eventStore != null) {
- buf.append(this.eventStore.toString());
- }
- return buf.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/rewrite/ITrackedNodePosition.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/rewrite/ITrackedNodePosition.java
deleted file mode 100644
index 3295eb8a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/rewrite/ITrackedNodePosition.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.dom.rewrite;
-
-/**
- * A tracked node position is returned when a rewrite change is
- * requested to be tracked.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * @see ASTRewrite#track(org.eclipse.wst.jsdt.core.dom.ASTNode)
- *
- * 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 ITrackedNodePosition {
-
- /**
- * Returns the original or modified start position of the tracked node depending if called before
- * or after the rewrite is applied. <code>-1</code> is returned for removed nodes.
- *
- * @return the original or modified start position of the tracked node
- */
- public int getStartPosition();
-
- /**
- * Returns the original or modified length of the tracked node depending if called before
- * or after the rewrite is applied. <code>-1</code> is returned for removed nodes.
- *
- * @return the original or modified length of the tracked node
- */
- public int getLength();
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/rewrite/ImportRewrite.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/rewrite/ImportRewrite.java
deleted file mode 100644
index 06525143..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/rewrite/ImportRewrite.java
+++ /dev/null
@@ -1,1030 +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.core.dom.rewrite;
-
-import java.util.ArrayList;
-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.core.runtime.SubProgressMonitor;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IImportDeclaration;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-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.core.Signature;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.ImportDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.PrimitiveType;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.infer.IInferenceFile;
-import org.eclipse.wst.jsdt.core.infer.ImportRewriteSupport;
-import org.eclipse.wst.jsdt.core.infer.InferrenceManager;
-import org.eclipse.wst.jsdt.core.infer.InferrenceProvider;
-import org.eclipse.wst.jsdt.core.infer.RefactoringSupport;
-import org.eclipse.wst.jsdt.internal.core.dom.rewrite.ImportRewriteAnalyzer;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-
-
-/**
- * The {@link ImportRewrite} helps updating imports following a import order and on-demand imports threshold as configured by a project.
- * <p>
- * The import rewrite is created on a javaScript unit and collects references to types that are added or removed. When adding imports, e.g. using
- * {@link #addImport(String)}, the import rewrite evaluates if the type can be imported and returns the a reference to the type that can be used in code.
- * This reference is either unqualified if the import could be added, or fully qualified if the import failed due to a conflict with another element of the same name.
- * </p>
- * <p>
- * On {@link #rewriteImports(IProgressMonitor)} the rewrite translates these descriptions into
- * text edits that can then be applied to the original source. The rewrite infrastructure tries to generate minimal text changes and only
- * works on the import statements. It is possible to combine the result of an import rewrite with the result of a {@link org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite}
- * as long as no import statements are modified by the AST rewrite.
- * </p>
- * <p>The options controlling the import order and on-demand thresholds are:
- * <ul><li>{@link #setImportOrder(String[])} specifies the import groups and their preferred order</li>
- * <li>{@link #setOnDemandImportThreshold(int)} specifies the number of imports in a group needed for a on-demand import statement (star import)</li>
- * <li>{@link #setStaticOnDemandImportThreshold(int)} specifies the number of static imports in a group needed for a on-demand import statement (star import)</li>
- *</ul>
- * This class is not intended to be subclassed.
- * </p>
- *
- * 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 final class ImportRewrite {
-
- /**
- * A {@link ImportRewrite.ImportRewriteContext} can optionally be used in e.g. {@link ImportRewrite#addImport(String, ImportRewrite.ImportRewriteContext)} to
- * give more information about the types visible in the scope. These types can be for example inherited inner types where it is
- * unnecessary to add import statements for.
- *
- * </p>
- * <p>
- * This class can be implemented by clients.
- * </p>
- */
- public static abstract class ImportRewriteContext {
-
- /**
- * Result constant signaling that the given element is know in the context.
- */
- public final static int RES_NAME_FOUND= 1;
-
- /**
- * Result constant signaling that the given element is not know in the context.
- */
- public final static int RES_NAME_UNKNOWN= 2;
-
- /**
- * Result constant signaling that the given element is conflicting with an other element in the context.
- */
- public final static int RES_NAME_CONFLICT= 3;
-
- /**
- * Kind constant specifying that the element is a type import.
- */
- public final static int KIND_TYPE= 1;
-
- /**
- * Kind constant specifying that the element is a static field import.
- */
- public final static int KIND_STATIC_FIELD= 2;
-
- /**
- * Kind constant specifying that the element is a static method import.
- */
- public final static int KIND_STATIC_METHOD= 3;
-
- /**
- * Searches for the given element in the context and reports if the element is known ({@link #RES_NAME_FOUND}),
- * unknown ({@link #RES_NAME_UNKNOWN}) or if its name conflicts ({@link #RES_NAME_CONFLICT}) with an other element.
- * @param qualifier The qualifier of the element, can be package or the qualified name of a type
- * @param name The simple name of the element; either a type, method or field name or * for on-demand imports.
- * @param kind The kind of the element. Can be either {@link #KIND_TYPE}, {@link #KIND_STATIC_FIELD} or
- * {@link #KIND_STATIC_METHOD}. Implementors should be prepared for new, currently unspecified kinds and return
- * {@link #RES_NAME_UNKNOWN} by default.
- * @return Returns the result of the lookup. Can be either {@link #RES_NAME_FOUND}, {@link #RES_NAME_UNKNOWN} or
- * {@link #RES_NAME_CONFLICT}.
- */
- public abstract int findInContext(String qualifier, String name, int kind);
- }
-
- private static final char STATIC_PREFIX= 's';
- private static final char NORMAL_PREFIX= 'n';
-
- private final ImportRewriteContext defaultContext;
-
- private final IJavaScriptUnit compilationUnit;
- private final JavaScriptUnit astRoot;
-
- private final boolean restoreExistingImports;
- private final List existingImports;
-
- private String[] importOrder;
- private int importOnDemandThreshold;
- private int staticImportOnDemandThreshold;
-
- private List addedImports;
- private List removedImports;
-
- private String[] createdImports;
- private String[] createdStaticImports;
-
- private boolean filterImplicitImports;
-
- private boolean writeImports=false;
-
- private ImportRewriteSupport importRewriteExtension;
- private boolean isImportMatchesType=true;
-
- /**
- * Creates a {@link ImportRewrite} from a {@link IJavaScriptUnit}. If <code>restoreExistingImports</code>
- * is <code>true</code>, all existing imports are kept, and new imports will be inserted at best matching locations. If
- * <code>restoreExistingImports</code> is <code>false</code>, the existing imports will be removed and only the
- * newly added imports will be created.
- * <p>
- * Note that {@link #create(IJavaScriptUnit, boolean)} is more efficient than this method if an AST for
- * the javaScript unit is already available.
- * </p>
- * @param cu the javaScript unit to create the imports for
- * @param restoreExistingImports specifies if the existing imports should be kept or removed.
- * @return the created import rewriter.
- * @throws JavaScriptModelException thrown when the javaScript unit could not be accessed.
- */
- public static ImportRewrite create(IJavaScriptUnit cu, boolean restoreExistingImports) throws JavaScriptModelException {
- if (cu == null) {
- throw new IllegalArgumentException("JavaScript unit must not be null"); //$NON-NLS-1$
- }
- ImportRewriteSupport importRewriteExtension=null;
- InferrenceProvider[] inferenceProviders = InferrenceManager.getInstance().getInferenceProviders( (IInferenceFile)cu);
- if (inferenceProviders.length>0 && inferenceProviders[0].getRefactoringSupport()!=null)
- {
- RefactoringSupport refactoringSupport = inferenceProviders[0].getRefactoringSupport();
- if (refactoringSupport!=null)
- importRewriteExtension=refactoringSupport.getImportRewriteSupport();
- }
- List existingImport= null;
- if (restoreExistingImports) {
- existingImport= new ArrayList();
- IImportDeclaration[] imports= cu.getImports();
- for (int i= 0; i < imports.length; i++) {
- IImportDeclaration curr= imports[i];
- char prefix= Flags.isStatic(curr.getFlags()) ? STATIC_PREFIX : NORMAL_PREFIX;
- existingImport.add(prefix + curr.getElementName());
- }
- }
- return new ImportRewrite(cu, null, existingImport,importRewriteExtension);
- }
-
- /**
- * Creates a {@link ImportRewrite} from a an AST ({@link JavaScriptUnit}). The AST has to be created from a
- * {@link IJavaScriptUnit}, that means {@link ASTParser#setSource(IJavaScriptUnit)} has been used when creating the
- * AST. If <code>restoreExistingImports</code> is <code>true</code>, all existing imports are kept, and new imports
- * will be inserted at best matching locations. If <code>restoreExistingImports</code> is <code>false</code>, the
- * existing imports will be removed and only the newly added imports will be created.
- * <p>
- * Note that this method is more efficient than using {@link #create(IJavaScriptUnit, boolean)} if an AST is already available.
- * </p>
- * @param astRoot the AST root node to create the imports for
- * @param restoreExistingImports specifies if the existing imports should be kept or removed.
- * @return the created import rewriter.
- * @throws IllegalArgumentException thrown when the passed AST is null or was not created from a javaScript unit.
- */
- public static ImportRewrite create(JavaScriptUnit astRoot, boolean restoreExistingImports) {
- if (astRoot == null) {
- throw new IllegalArgumentException("AST must not be null"); //$NON-NLS-1$
- }
- ITypeRoot typeRoot = astRoot.getTypeRoot();
- if (!(typeRoot instanceof IJavaScriptUnit)) {
- throw new IllegalArgumentException("AST must have been constructed from a JavaScript element"); //$NON-NLS-1$
- }
- ImportRewriteSupport importRewriteExtension=null;
- InferrenceProvider[] inferenceProviders = InferrenceManager.getInstance().getInferenceProviders( (IInferenceFile)typeRoot);
- if (inferenceProviders.length>0 && inferenceProviders[0].getRefactoringSupport()!=null)
- {
- RefactoringSupport refactoringSupport = inferenceProviders[0].getRefactoringSupport();
- if (refactoringSupport!=null)
- importRewriteExtension=refactoringSupport.getImportRewriteSupport();
- }
- List existingImport= null;
- if (restoreExistingImports) {
- existingImport= new ArrayList();
- List imports= astRoot.imports();
- for (int i= 0; i < imports.size(); i++) {
- ImportDeclaration curr= (ImportDeclaration) imports.get(i);
- StringBuffer buf= new StringBuffer();
- buf.append(curr.isStatic() ? STATIC_PREFIX : NORMAL_PREFIX).append(curr.getName().getFullyQualifiedName());
- if (curr.isOnDemand()) {
- if (buf.length() > 1)
- buf.append('.');
- buf.append('*');
- }
- existingImport.add(buf.toString());
- }
- }
- return new ImportRewrite((IJavaScriptUnit) typeRoot, astRoot, existingImport, importRewriteExtension);
- }
-
- private ImportRewrite(IJavaScriptUnit cu, JavaScriptUnit astRoot, List existingImports, ImportRewriteSupport importRewriteExtension) {
- this.compilationUnit= cu;
- this.astRoot= astRoot; // might be null
- this.importRewriteExtension=importRewriteExtension;
- if (this.importRewriteExtension!=null)
- {
- this.isImportMatchesType=this.importRewriteExtension.isImportMatchesType();
- this.writeImports=true;
- }
- if (existingImports != null) {
- this.existingImports= existingImports;
- this.restoreExistingImports= !existingImports.isEmpty();
- } else {
- this.existingImports= new ArrayList();
- this.restoreExistingImports= false;
- }
- this.filterImplicitImports= true;
-
- this.defaultContext= new ImportRewriteContext() {
- public int findInContext(String qualifier, String name, int kind) {
- return findInImports(qualifier, name, kind);
- }
- };
- this.addedImports= null; // Initialized on use
- this.removedImports= null; // Initialized on use
- this.createdImports= null;
- this.createdStaticImports= null;
-
- this.importOrder= CharOperation.NO_STRINGS;
- this.importOnDemandThreshold= 99;
- this.staticImportOnDemandThreshold= 99;
- }
-
-
- /**
- * Defines the import groups and order to be used by the {@link ImportRewrite}.
- * Imports are added to the group matching their qualified name most. The empty group name groups all imports not matching
- * any other group. Static imports are managed in separate groups. Static import group names are prefixed with a '#' character.
- * @param order A list of strings defining the import groups. A group name must be a valid package name or empty. If can be
- * prefixed by the '#' character for static import groups
- */
- public void setImportOrder(String[] order) {
- if (order == null)
- throw new IllegalArgumentException("Order must not be null"); //$NON-NLS-1$
- this.importOrder= order;
- }
-
- /**
- * Sets the on-demand import threshold for normal (non-static) imports.
- * This threshold defines the number of imports that need to be in a group to use
- * a on-demand (star) import declaration instead.
- *
- * @param threshold a positive number defining the on-demand import threshold
- * for normal (non-static) imports.
- * @throws IllegalArgumentException a {@link IllegalArgumentException} is thrown
- * if the number is not positive.
- */
- public void setOnDemandImportThreshold(int threshold) {
- if (threshold <= 0)
- throw new IllegalArgumentException("Threshold must be positive."); //$NON-NLS-1$
- this.importOnDemandThreshold= threshold;
- }
-
- /**
- * Sets the on-demand import threshold for static imports.
- * This threshold defines the number of imports that need to be in a group to use
- * a on-demand (star) import declaration instead.
- *
- * @param threshold a positive number defining the on-demand import threshold
- * for normal (non-static) imports.
- * @throws IllegalArgumentException a {@link IllegalArgumentException} is thrown
- * if the number is not positive.
- */
- public void setStaticOnDemandImportThreshold(int threshold) {
- if (threshold <= 0)
- throw new IllegalArgumentException("Threshold must be positive."); //$NON-NLS-1$
- this.staticImportOnDemandThreshold= threshold;
- }
-
- /**
- * The javaScript unit for which this import rewrite was created for.
- * @return the javaScript unit for which this import rewrite was created for.
- */
- public IJavaScriptUnit getCompilationUnit() {
- return this.compilationUnit;
- }
-
- /**
- * Returns the default rewrite context that only knows about the imported types. Clients
- * can write their own context and use the default context for the default behavior.
- * @return the default import rewrite context.
- */
- public ImportRewriteContext getDefaultImportRewriteContext() {
- return this.defaultContext;
- }
-
- /**
- * Specifies that implicit imports (types in default package, package <code>java.lang</code> or
- * in the same package as the rewrite javaScript unit should not be created except if necessary
- * to resolve an on-demand import conflict. The filter is enabled by default.
- * @param filterImplicitImports if set, implicit imports will be filtered.
- */
- public void setFilterImplicitImports(boolean filterImplicitImports) {
- this.filterImplicitImports= filterImplicitImports;
- }
-
- private static int compareImport(char prefix, String qualifier, String name, String curr) {
- if (curr.charAt(0) != prefix || !curr.endsWith(name)) {
- return ImportRewriteContext.RES_NAME_UNKNOWN;
- }
-
- curr= curr.substring(1); // remove the prefix
-
- if (curr.length() == name.length()) {
- if (qualifier.length() == 0) {
- return ImportRewriteContext.RES_NAME_FOUND;
- }
- return ImportRewriteContext.RES_NAME_CONFLICT;
- }
- // at this place: curr.length > name.length
-
- int dotPos= curr.length() - name.length() - 1;
- if (curr.charAt(dotPos) != '.') {
- return ImportRewriteContext.RES_NAME_UNKNOWN;
- }
- if (qualifier.length() != dotPos || !curr.startsWith(qualifier)) {
- return ImportRewriteContext.RES_NAME_CONFLICT;
- }
- return ImportRewriteContext.RES_NAME_FOUND;
- }
-
- /**
- * Not API, package visibility as accessed from an anonymous type
- */
- /* package */ final int findInImports(String qualifier, String name, int kind) {
- boolean allowAmbiguity= (kind == ImportRewriteContext.KIND_STATIC_METHOD) || (name.length() == 1 && name.charAt(0) == '*');
- List imports= this.existingImports;
- char prefix= (kind == ImportRewriteContext.KIND_TYPE) ? NORMAL_PREFIX : STATIC_PREFIX;
-
- for (int i= imports.size() - 1; i >= 0 ; i--) {
- String curr= (String) imports.get(i);
- int res= compareImport(prefix, qualifier, name, curr);
- if (res != ImportRewriteContext.RES_NAME_UNKNOWN) {
- if (!allowAmbiguity || res == ImportRewriteContext.RES_NAME_FOUND) {
- return res;
- }
- }
- }
- return ImportRewriteContext.RES_NAME_UNKNOWN;
- }
-
- /**
- * Adds a new import to the rewriter's record and returns a {@link Type} node that can be used
- * in the code as a reference to the type. The type binding can be an array binding or type variable.
- * If the binding is a generic type, the type parameters are ignored. For parameterized types, also the type
- * arguments are processed and imports added if necessary. Anonymous types inside type arguments are normalized to their base type.
- * <p>
- * No imports are added for types that are already known. If a import for a type is recorded to be removed, this record is discarded instead.
- * </p>
- * <p>
- * The content of the javaScript unit itself is actually not modified
- * in any way by this method; rather, the rewriter just records that a new import has been added.
- * </p>
- * @param typeSig the signature of the type to be added.
- * @param ast the AST to create the returned type for.
- * @return returns a type to which the type binding can be assigned to. The returned type contains is unqualified
- * when an import could be added or was already known. It is fully qualified, if an import conflict prevented the import.
- */
- public Type addImportFromSignature(String typeSig, AST ast) {
- return addImportFromSignature(typeSig, ast, this.defaultContext);
- }
-
- /**
- * Adds a new import to the rewriter's record and returns a {@link Type} node that can be used
- * in the code as a reference to the type. The type binding can be an array binding or type variable.
- * If the binding is a generic type, the type parameters are ignored. For parameterized types, also the type
- * arguments are processed and imports added if necessary. Anonymous types inside type arguments are normalized to their base type.
- * <p>
- * No imports are added for types that are already known. If a import for a type is recorded to be removed, this record is discarded instead.
- * </p>
- * <p>
- * The content of the javaScript unit itself is actually not modified
- * in any way by this method; rather, the rewriter just records that a new import has been added.
- * </p>
- * @param typeSig the signature of the type to be added.
- * @param ast the AST to create the returned type for.
- * @param context an optional context that knows about types visible in the current scope or <code>null</code>
- * to use the default context only using the available imports.
- * @return returns a type to which the type binding can be assigned to. The returned type contains is unqualified
- * when an import could be added or was already known. It is fully qualified, if an import conflict prevented the import.
- */
- public Type addImportFromSignature(String typeSig, AST ast, ImportRewriteContext context) {
- if (typeSig == null || typeSig.length() == 0) {
- throw new IllegalArgumentException("Invalid type signature: empty or null"); //$NON-NLS-1$
- }
- int sigKind= Signature.getTypeSignatureKind(typeSig);
- switch (sigKind) {
- case Signature.BASE_TYPE_SIGNATURE:
- return ast.newPrimitiveType(PrimitiveType.toCode(Signature.toString(typeSig)));
- case Signature.ARRAY_TYPE_SIGNATURE:
- Type elementType= addImportFromSignature(Signature.getElementType(typeSig), ast, context);
- return ast.newArrayType(elementType, Signature.getArrayCount(typeSig));
- case Signature.CLASS_TYPE_SIGNATURE:
- String erasureName= Signature.toString(typeSig);
- if (typeSig.charAt(0) == Signature.C_RESOLVED) {
- erasureName= internalAddImport(erasureName, erasureName, context);
- }
- Type baseType= ast.newSimpleType(ast.newName(erasureName));
- return baseType;
- default:
- throw new IllegalArgumentException("Unknown type signature kind: " + typeSig); //$NON-NLS-1$
- }
- }
-
-
-
- /**
- * Adds a new import to the rewriter's record and returns a type reference that can be used
- * in the code. The type binding can be an array binding or type variable.
- * If the binding is a generic type, the type parameters are ignored. For parameterized types, also the type
- * arguments are processed and imports added if necessary. Anonymous types inside type arguments are normalized to their base type.
- * <p>
- * No imports are added for types that are already known. If a import for a type is recorded to be removed, this record is discarded instead.
- * </p>
- * <p>
- * The content of the javaScript unit itself is actually not modified
- * in any way by this method; rather, the rewriter just records that a new import has been added.
- * </p>
- * @param binding the signature of the type to be added.
- * @return returns a type to which the type binding can be assigned to. The returned type contains is unqualified
- * when an import could be added or was already known. It is fully qualified, if an import conflict prevented the import.
- */
- public String addImport(ITypeBinding binding) {
- return addImport(binding, this.defaultContext);
- }
-
- /**
- * Adds a new import to the rewriter's record and returns a type reference that can be used
- * in the code. The type binding can be an array binding or type variable.
- * If the binding is a generic type, the type parameters are ignored. For parameterized types, also the type
- * arguments are processed and imports added if necessary. Anonymous types inside type arguments are normalized to their base type.
- * <p>
- * No imports are added for types that are already known. If a import for a type is recorded to be removed, this record is discarded instead.
- * </p>
- * <p>
- * The content of the javaScript unit itself is actually not modified
- * in any way by this method; rather, the rewriter just records that a new import has been added.
- * </p>
- * @param binding the signature of the type to be added.
- * @param context an optional context that knows about types visible in the current scope or <code>null</code>
- * to use the default context only using the available imports.
- * @return returns a type to which the type binding can be assigned to. The returned type contains is unqualified
- * when an import could be added or was already known. It is fully qualified, if an import conflict prevented the import.
- */
- public String addImport(ITypeBinding binding, ImportRewriteContext context) {
- if (binding.isPrimitive()) {
- return binding.getName();
- }
-
- ITypeBinding normalizedBinding= normalizeTypeBinding(binding);
- if (normalizedBinding == null) {
- return "invalid"; //$NON-NLS-1$
- }
-
- if (normalizedBinding.isArray()) {
- StringBuffer res= new StringBuffer(addImport(normalizedBinding.getElementType(), context));
- for (int i= normalizedBinding.getDimensions(); i > 0; i--) {
- res.append("[]"); //$NON-NLS-1$
- }
- return res.toString();
- }
-
- String qualifiedName= getRawQualifiedName(normalizedBinding);
- if (qualifiedName.length() > 0) {
- String str= internalAddImport(qualifiedName, qualifiedName, context);
- return str;
- }
- return getRawName(normalizedBinding);
- }
-
- private static ITypeBinding normalizeTypeBinding(ITypeBinding binding) {
- if (binding != null && !binding.isNullType() && !"void".equals(binding.getName())) { //$NON-NLS-1$
- if (binding.isAnonymous()) {
- return binding.getSuperclass();
- }
- return binding;
- }
- return null;
- }
-
- /**
- * Adds a new import to the rewriter's record and returns a {@link Type} that can be used
- * in the code. The type binding can be an array binding or type variable.
- * If the binding is a generic type, the type parameters are ignored. For parameterized types, also the type
- * arguments are processed and imports added if necessary. Anonymous types inside type arguments are normalized to their base type.
- * <p>
- * No imports are added for types that are already known. If a import for a type is recorded to be removed, this record is discarded instead.
- * </p>
- * <p>
- * The content of the javaScript unit itself is actually not modified
- * in any way by this method; rather, the rewriter just records that a new import has been added.
- * </p>
- * @param binding the signature of the type to be added.
- * @param ast the AST to create the returned type for.
- * @return returns a type to which the type binding can be assigned to. The returned type contains is unqualified
- * when an import could be added or was already known. It is fully qualified, if an import conflict prevented the import.
- */
- public Type addImport(ITypeBinding binding, AST ast) {
- return addImport(binding, ast, this.defaultContext);
- }
-
- /**
- * Adds a new import to the rewriter's record and returns a {@link Type} that can be used
- * in the code. The type binding can be an array binding or type variable.
- * If the binding is a generic type, the type parameters are ignored. For parameterized types, also the type
- * arguments are processed and imports added if necessary. Anonymous types inside type arguments are normalized to their base type.
- * <p>
- * No imports are added for types that are already known. If a import for a type is recorded to be removed, this record is discarded instead.
- * </p>
- * <p>
- * The content of the javaScript unit itself is actually not modified
- * in any way by this method; rather, the rewriter just records that a new import has been added.
- * </p>
- * @param binding the signature of the type to be added.
- * @param ast the AST to create the returned type for.
- * @param context an optional context that knows about types visible in the current scope or <code>null</code>
- * to use the default context only using the available imports.
- * @return returns a type to which the type binding can be assigned to. The returned type contains is unqualified
- * when an import could be added or was already known. It is fully qualified, if an import conflict prevented the import.
- */
- public Type addImport(ITypeBinding binding, AST ast, ImportRewriteContext context) {
- if (binding.isPrimitive() || binding.isRecovered()) {
- return ast.newPrimitiveType(PrimitiveType.toCode(binding.getName()));
- }
-
- ITypeBinding normalizedBinding= normalizeTypeBinding(binding);
- if (normalizedBinding == null) {
- return ast.newSimpleType(ast.newSimpleName("invalid")); //$NON-NLS-1$
- }
-
- if (normalizedBinding.isArray()) {
- Type elementType= addImport(normalizedBinding.getElementType(), ast, context);
- return ast.newArrayType(elementType, normalizedBinding.getDimensions());
- }
-
- String qualifiedName= getRawQualifiedName(normalizedBinding);
- if (qualifiedName.length() > 0) {
- String res= internalAddImport(qualifiedName, qualifiedName, context);
-
- return ast.newSimpleType(ast.newName(res));
- }
- return ast.newSimpleType(ast.newName(getRawName(normalizedBinding)));
- }
-
-
- /**
- * Adds a new import to the rewriter's record and returns a type reference that can be used
- * in the code. The type binding can only be an array or non-generic type.
- * <p>
- * No imports are added for types that are already known. If a import for a type is recorded to be removed, this record is discarded instead.
- * </p>
- * <p>
- * The content of the javaScript unit itself is actually not modified
- * in any way by this method; rather, the rewriter just records that a new import has been added.
- * </p>
- * @param qualifiedTypeName the qualified type name of the type to be added
- * @param context an optional context that knows about types visible in the current scope or <code>null</code>
- * to use the default context only using the available imports.
- * @return returns a type to which the type binding can be assigned to. The returned type contains is unqualified
- * when an import could be added or was already known. It is fully qualified, if an import conflict prevented the import.
- */
- public String addImport(String qualifiedTypeName, String packageName, ImportRewriteContext context) {
- if (packageName==null)
- packageName=qualifiedTypeName;
- if (JavaScriptCore.IS_ECMASCRIPT4) {
- int angleBracketOffset = qualifiedTypeName.indexOf('<');
- if (angleBracketOffset != -1) {
- return internalAddImport(qualifiedTypeName.substring(0,
- angleBracketOffset), packageName, context)
- + qualifiedTypeName.substring(angleBracketOffset);
- }
- int bracketOffset = qualifiedTypeName.indexOf('[');
- if (bracketOffset != -1) {
- return internalAddImport(qualifiedTypeName.substring(0,
- bracketOffset), packageName, context)
- + qualifiedTypeName.substring(bracketOffset);
- }
- }
- return internalAddImport(qualifiedTypeName, packageName, context);
- }
-
- /**
- * Adds a new import to the rewriter's record and returns a type reference that can be used
- * in the code. The type binding can only be an array or non-generic type.
- * <p>
- * No imports are added for types that are already known. If a import for a type is recorded to be removed, this record is discarded instead.
- * </p>
- * <p>
- * The content of the javaScript unit itself is actually not modified
- * in any way by this method; rather, the rewriter just records that a new import has been added.
- * </p>
- * @param qualifiedTypeName the qualified type name of the type to be added
- * @return returns a type to which the type binding can be assigned to. The returned type contains is unqualified
- * when an import could be added or was already known. It is fully qualified, if an import conflict prevented the import.
- */
- public String addImport(String qualifiedTypeName) {
- return addImport(qualifiedTypeName, qualifiedTypeName, this.defaultContext);
- }
-
- /**
- * Adds a new static import to the rewriter's record and returns a reference that can be used in the code. The reference will
- * be fully qualified if an import conflict prevented the import or unqualified if the import succeeded or was already
- * existing.
- * <p>
- * No imports are added for members that are already known. If a import for a type is recorded to be removed, this record is discarded instead.
- * </p>
- * <p>
- * The content of the javaScript unit itself is actually not modified
- * in any way by this method; rather, the rewriter just records that a new import has been added.
- * </p>
- * @param binding The binding of the static field or method to be added.
- * @return returns either the simple member name if the import was successful or else the qualified name if
- * an import conflict prevented the import.
- * @throws IllegalArgumentException an {@link IllegalArgumentException} is thrown if the binding is not a static field
- * or method.
- */
- public String addStaticImport(IBinding binding) {
- return addStaticImport(binding, this.defaultContext);
- }
-
- /**
- * Adds a new static import to the rewriter's record and returns a reference that can be used in the code. The reference will
- * be fully qualified if an import conflict prevented the import or unqualified if the import succeeded or was already
- * existing.
- * <p>
- * No imports are added for members that are already known. If a import for a type is recorded to be removed, this record is discarded instead.
- * </p>
- * <p>
- * The content of the javaScript unit itself is actually not modified
- * in any way by this method; rather, the rewriter just records that a new import has been added.
- * </p>
- * @param binding The binding of the static field or method to be added.
- * @param context an optional context that knows about members visible in the current scope or <code>null</code>
- * to use the default context only using the available imports.
- * @return returns either the simple member name if the import was successful or else the qualified name if
- * an import conflict prevented the import.
- * @throws IllegalArgumentException an {@link IllegalArgumentException} is thrown if the binding is not a static field
- * or method.
- */
- public String addStaticImport(IBinding binding, ImportRewriteContext context) {
- if (Modifier.isStatic(binding.getModifiers())) {
- if (binding instanceof IVariableBinding) {
- IVariableBinding variableBinding= (IVariableBinding) binding;
- if (variableBinding.isField()) {
- ITypeBinding declaringType= variableBinding.getDeclaringClass();
- return addStaticImport(getRawQualifiedName(declaringType), binding.getName(), true, context);
- }
- } else if (binding instanceof IFunctionBinding) {
- ITypeBinding declaringType= ((IFunctionBinding) binding).getDeclaringClass();
- return addStaticImport(getRawQualifiedName(declaringType), binding.getName(), false, context);
- }
- }
- throw new IllegalArgumentException("Binding must be a static field or method."); //$NON-NLS-1$
- }
-
- /**
- * Adds a new static import to the rewriter's record and returns a reference that can be used in the code. The reference will
- * be fully qualified if an import conflict prevented the import or unqualified if the import succeeded or was already
- * existing.
- * <p>
- * No imports are added for members that are already known. If a import for a type is recorded to be removed, this record is discarded instead.
- * </p>
- * <p>
- * The content of the javaScript unit itself is actually not modified
- * in any way by this method; rather, the rewriter just records that a new import has been added.
- * </p>
- * @param declaringTypeName The qualified name of the static's member declaring type
- * @param simpleName the simple name of the member; either a field or a method name.
- * @param isField <code>true</code> specifies that the member is a field, <code>false</code> if it is a
- * method.
- * @return returns either the simple member name if the import was successful or else the qualified name if
- * an import conflict prevented the import.
- */
- public String addStaticImport(String declaringTypeName, String simpleName, boolean isField) {
- return addStaticImport(declaringTypeName, simpleName, isField, this.defaultContext);
- }
-
- /**
- * Adds a new static import to the rewriter's record and returns a reference that can be used in the code. The reference will
- * be fully qualified if an import conflict prevented the import or unqualified if the import succeeded or was already
- * existing.
- * <p>
- * No imports are added for members that are already known. If a import for a type is recorded to be removed, this record is discarded instead.
- * </p>
- * <p>
- * The content of the javaScript unit itself is actually not modified
- * in any way by this method; rather, the rewriter just records that a new import has been added.
- * </p>
- * @param declaringTypeName The qualified name of the static's member declaring type
- * @param simpleName the simple name of the member; either a field or a method name.
- * @param isField <code>true</code> specifies that the member is a field, <code>false</code> if it is a
- * method.
- * @param context an optional context that knows about members visible in the current scope or <code>null</code>
- * to use the default context only using the available imports.
- * @return returns either the simple member name if the import was successful or else the qualified name if
- * an import conflict prevented the import.
- */
- public String addStaticImport(String declaringTypeName, String simpleName, boolean isField, ImportRewriteContext context) {
- if (declaringTypeName.indexOf('.') == -1) {
- return declaringTypeName + '.' + simpleName;
- }
- if (context == null) {
- context= this.defaultContext;
- }
- int kind= isField ? ImportRewriteContext.KIND_STATIC_FIELD : ImportRewriteContext.KIND_STATIC_METHOD;
- int res= context.findInContext(declaringTypeName, simpleName, kind);
- if (res == ImportRewriteContext.RES_NAME_CONFLICT) {
- return declaringTypeName + '.' + simpleName;
- }
- if (res == ImportRewriteContext.RES_NAME_UNKNOWN) {
- addEntry(STATIC_PREFIX + declaringTypeName + '.' + simpleName);
- }
- return simpleName;
- }
-
- private String internalAddImport(String fullTypeName, String packageName,ImportRewriteContext context) {
- String importName=(this.isImportMatchesType)? fullTypeName : packageName;
-
- int idx= importName.lastIndexOf('.');
- String typeContainerName, typeName;
- if (idx != -1) {
- typeContainerName= importName.substring(0, idx);
- typeName= importName.substring(idx + 1);
- } else {
- typeContainerName= ""; //$NON-NLS-1$
- typeName= importName;
- }
-
- if (typeContainerName.length() == 0 && PrimitiveType.toCode(typeName) != null) {
- return fullTypeName;
- }
-
- if (context == null)
- context= this.defaultContext;
-
- int res= context.findInContext(typeContainerName, typeName, ImportRewriteContext.KIND_TYPE);
- if (res == ImportRewriteContext.RES_NAME_CONFLICT) {
- return fullTypeName;
- }
- if (res == ImportRewriteContext.RES_NAME_UNKNOWN) {
- addEntry(NORMAL_PREFIX + importName);
- }
- return fullTypeName;
- }
-
- private void addEntry(String entry) {
- this.existingImports.add(entry);
-
- if (this.removedImports != null) {
- if (this.removedImports.remove(entry)) {
- return;
- }
- }
-
- if (this.addedImports == null) {
- this.addedImports= new ArrayList();
- }
- this.addedImports.add(entry);
- }
-
- private boolean removeEntry(String entry) {
- if (this.existingImports.remove(entry)) {
- if (this.addedImports != null) {
- if (this.addedImports.remove(entry)) {
- return true;
- }
- }
- if (this.removedImports == null) {
- this.removedImports= new ArrayList();
- }
- this.removedImports.add(entry);
- return true;
- }
- return false;
- }
-
- /**
- * Records to remove a import. No remove is recorded if no such import exists or if such an import is recorded
- * to be added. In that case the record of the addition is discarded.
- * <p>
- * The content of the javaScript unit itself is actually not modified
- * in any way by this method; rather, the rewriter just records that an import has been removed.
- * </p>
- * @param qualifiedName The import name to remove.
- * @return <code>true</code> is returned of an import of the given name could be found.
- */
- public boolean removeImport(String qualifiedName) {
- return removeEntry(NORMAL_PREFIX + qualifiedName);
- }
-
- /**
- * Records to remove a static import. No remove is recorded if no such import exists or if such an import is recorded
- * to be added. In that case the record of the addition is discarded.
- * <p>
- * The content of the javaScript unit itself is actually not modified
- * in any way by this method; rather, the rewriter just records that a new import has been removed.
- * </p>
- * @param qualifiedName The import name to remove.
- * @return <code>true</code> is returned of an import of the given name could be found.
- */
- public boolean removeStaticImport(String qualifiedName) {
- return removeEntry(STATIC_PREFIX + qualifiedName);
- }
-
- private static String getRawName(ITypeBinding normalizedBinding) {
- return normalizedBinding.getTypeDeclaration().getName();
- }
-
- private static String getRawQualifiedName(ITypeBinding normalizedBinding) {
- return normalizedBinding.getTypeDeclaration().getQualifiedName();
- }
-
-
- /**
- * Converts all modifications recorded by this rewriter into an object representing the corresponding text
- * edits to the source code of the rewrite's javaScript unit. The javaScript unit itself is not modified.
- * <p>
- * Calling this methods does not discard the modifications on record. Subsequence modifications are added
- * to the ones already on record. If this method is called again later, the resulting text edit object will accurately
- * reflect the net cumulative affect of all those changes.
- * </p>
- * @param monitor the progress monitor or <code>null</code>
- * @return text edit object describing the changes to the document corresponding to the changes
- * recorded by this rewriter
- * @throws CoreException the exception is thrown if the rewrite fails.
- */
- public final TextEdit rewriteImports(IProgressMonitor monitor) throws CoreException {
- if (monitor == null) {
- monitor= new NullProgressMonitor();
- }
-
- try {
- monitor.beginTask(Messages.bind(Messages.importRewrite_processDescription), 2);
- if (!hasRecordedChanges()) {
- this.createdImports= CharOperation.NO_STRINGS;
- this.createdStaticImports= CharOperation.NO_STRINGS;
- return new MultiTextEdit();
- }
-
- JavaScriptUnit usedAstRoot= this.astRoot;
- if (usedAstRoot == null) {
- ASTParser parser= ASTParser.newParser(AST.JLS3);
- parser.setSource(this.compilationUnit);
- parser.setFocalPosition(0); // reduced AST
- parser.setResolveBindings(false);
- usedAstRoot= (JavaScriptUnit) parser.createAST(new SubProgressMonitor(monitor, 1));
- }
-
- ImportRewriteAnalyzer computer= new ImportRewriteAnalyzer(this.compilationUnit, usedAstRoot, this.importOrder,
- this.importOnDemandThreshold, this.staticImportOnDemandThreshold, this.restoreExistingImports,
- this.importRewriteExtension);
- computer.setFilterImplicitImports(this.filterImplicitImports);
-
- if (this.addedImports != null) {
- for (int i= 0; i < this.addedImports.size(); i++) {
- String curr= (String) this.addedImports.get(i);
- computer.addImport(curr.substring(1), STATIC_PREFIX == curr.charAt(0));
- }
- }
-
- if (this.removedImports != null) {
- for (int i= 0; i < this.removedImports.size(); i++) {
- String curr= (String) this.removedImports.get(i);
- computer.removeImport(curr.substring(1), STATIC_PREFIX == curr.charAt(0));
- }
- }
-
- TextEdit result= computer.getResultingEdits(new SubProgressMonitor(monitor, 1));
- this.createdImports= computer.getCreatedImports();
- this.createdStaticImports= computer.getCreatedStaticImports();
- return result;
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Returns all new non-static imports created by the last invocation of {@link #rewriteImports(IProgressMonitor)}
- * or <code>null</code> if these methods have not been called yet.
- * <p>
- * Note that this list doesn't need to be the same as the added imports (see {@link #getAddedImports()}) as
- * implicit imports are not created and some imports are represented by on-demand imports instead.
- * </p>
- * @return the created imports
- */
- public String[] getCreatedImports() {
- return this.createdImports;
- }
-
- /**
- * Returns all new static imports created by the last invocation of {@link #rewriteImports(IProgressMonitor)}
- * or <code>null</code> if these methods have not been called yet.
- * <p>
- * Note that this list doesn't need to be the same as the added static imports ({@link #getAddedStaticImports()}) as
- * implicit imports are not created and some imports are represented by on-demand imports instead.
- * </p
- * @return the created imports
- */
- public String[] getCreatedStaticImports() {
- return this.createdStaticImports;
- }
-
- /**
- * Returns all non-static imports that are recorded to be added.
- *
- * @return the imports recorded to be added.
- */
- public String[] getAddedImports() {
- return filterFromList(this.addedImports, NORMAL_PREFIX);
- }
-
- /**
- * Returns all static imports that are recorded to be added.
- *
- * @return the static imports recorded to be added.
- */
- public String[] getAddedStaticImports() {
- return filterFromList(this.addedImports, STATIC_PREFIX);
- }
-
- /**
- * Returns all non-static imports that are recorded to be removed.
- *
- * @return the imports recorded to be removed.
- */
- public String[] getRemovedImports() {
- return filterFromList(this.removedImports, NORMAL_PREFIX);
- }
-
- /**
- * Returns all static imports that are recorded to be removed.
- *
- * @return the static imports recorded to be removed.
- */
- public String[] getRemovedStaticImports() {
- return filterFromList(this.removedImports, STATIC_PREFIX);
- }
-
- /**
- * Returns <code>true</code> if imports have been recorded to be added or removed.
- * @return boolean returns if any changes to imports have been recorded.
- */
- public boolean hasRecordedChanges() {
- if (!writeImports)
- return false;
- return !this.restoreExistingImports ||
- (this.addedImports != null && !this.addedImports.isEmpty()) ||
- (this.removedImports != null && !this.removedImports.isEmpty());
- }
-
-
- private static String[] filterFromList(List imports, char prefix) {
- if (imports == null) {
- return CharOperation.NO_STRINGS;
- }
- ArrayList res= new ArrayList();
- for (int i= 0; i < imports.size(); i++) {
- String curr= (String) imports.get(i);
- if (prefix == curr.charAt(0)) {
- res.add(curr.substring(1));
- }
- }
- return (String[]) res.toArray(new String[res.size()]);
- }
-
- public boolean isImportMatchesType() {
- return isImportMatchesType;
- }
-
-}
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
deleted file mode 100644
index c9d48fa6..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/rewrite/ListRewrite.java
+++ /dev/null
@@ -1,417 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.dom.rewrite;
-
-import java.util.Collections;
-import java.util.List;
-
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.core.dom.StructuralPropertyDescriptor;
-import org.eclipse.wst.jsdt.internal.core.dom.rewrite.ListRewriteEvent;
-import org.eclipse.wst.jsdt.internal.core.dom.rewrite.NodeInfoStore;
-import org.eclipse.wst.jsdt.internal.core.dom.rewrite.RewriteEvent;
-import org.eclipse.wst.jsdt.internal.core.dom.rewrite.RewriteEventStore;
-import org.eclipse.wst.jsdt.internal.core.dom.rewrite.RewriteEventStore.CopySourceInfo;
-
-/**
- * For describing manipulations to a child list property of an AST node.
- * <p>
- * This class is not intended to be subclassed.
- * </p>
- * @see ASTRewrite#getListRewrite(ASTNode, org.eclipse.wst.jsdt.core.dom.ChildListPropertyDescriptor)
- *
- * 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 final class ListRewrite {
-
- private ASTNode parent;
- private StructuralPropertyDescriptor childProperty;
- private ASTRewrite rewriter;
-
-
- /* package*/ ListRewrite(ASTRewrite rewriter, ASTNode parent, StructuralPropertyDescriptor childProperty) {
- this.rewriter= rewriter;
- this.parent= parent;
- this.childProperty= childProperty;
- }
-
- private RewriteEventStore getRewriteStore() {
- return this.rewriter.getRewriteEventStore();
- }
-
- private ListRewriteEvent getEvent() {
- return getRewriteStore().getListEvent(this.parent, this.childProperty, true);
- }
-
- /**
- * Returns the parent of the list for which this list rewriter was created.
-
- * @return the node that contains the list for which this list rewriter was created
- * @see #getLocationInParent()
- */
- public ASTNode getParent() {
- return this.parent;
- }
-
- /**
- * Returns the property of the parent node for which this list rewriter was created.
- *
- * @return the property of the parent node for which this list rewriter was created
- * @see #getParent()
- */
- public StructuralPropertyDescriptor getLocationInParent() {
- return this.childProperty;
- }
-
- /**
- * Removes the given node from its parent's list property in the rewriter.
- * The node must be contained in the list.
- * The AST itself is not actually modified in any way; rather, the rewriter
- * just records a note that this node has been removed from this list.
- *
- * @param node the node being removed
- * @param editGroup the edit group in which to collect the corresponding
- * text edits, or <code>null</code> if ungrouped
- * @throws IllegalArgumentException if the node is null, or if the node is not
- * part of this rewriter's AST, or if the described modification is invalid
- * (not a member of this node's original list)
- */
- public void remove(ASTNode node, TextEditGroup editGroup) {
- if (node == null) {
- throw new IllegalArgumentException();
- }
- RewriteEvent event= getEvent().removeEntry(node);
- if (editGroup != null) {
- getRewriteStore().setEventEditGroup(event, editGroup);
- }
- }
-
- /**
- * Returns the ASTRewrite instance from which this ListRewriter has been created from.
- * @return the parent AST Rewriter instance.
- */
- public ASTRewrite getASTRewrite() {
- return this.rewriter;
- }
-
-
- /**
- * Replaces the given node from its parent's list property in the rewriter.
- * The node must be contained in the list.
- * The replacement node must either be brand new (not part of the original AST)
- * or a placeholder node (for example, one created by
- * {@link ASTRewrite#createCopyTarget(ASTNode)},
- * {@link ASTRewrite#createMoveTarget(ASTNode)},
- * or {@link ASTRewrite#createStringPlaceholder(String, int)}). The AST itself
- * is not actually modified in any way; rather, the rewriter just records
- * a note that this node has been replaced in this list.
- *
- * @param node the node being replaced
- * @param replacement the replacement node, or <code>null</code> if no
- * replacement
- * @param editGroup the edit group in which to collect the corresponding
- * text edits, or <code>null</code> if ungrouped
- * @throws IllegalArgumentException if the node is null, or if the node is not part
- * of this rewriter's AST, or if the replacement node is not a new node (or
- * placeholder), or if the described modification is otherwise invalid
- * (not a member of this node's original list)
- */
- public void replace(ASTNode node, ASTNode replacement, TextEditGroup editGroup) {
- if (node == null) {
- throw new IllegalArgumentException();
- }
- RewriteEvent event= getEvent().replaceEntry(node, replacement);
- if (editGroup != null) {
- getRewriteStore().setEventEditGroup(event, editGroup);
- }
- }
-
- /**
- * Inserts the given node into the list after the given element.
- * The existing node must be in the list, either as an original or as a new
- * node that has been inserted.
- * The inserted node must either be brand new (not part of the original AST)
- * or a placeholder node (for example, one created by
- * {@link ASTRewrite#createCopyTarget(ASTNode)},
- * {@link ASTRewrite#createMoveTarget(ASTNode)},
- * or {@link ASTRewrite#createStringPlaceholder(String, int)}). The AST itself
- * is not actually modified in any way; rather, the rewriter just records
- * a note that this node has been inserted into the list.
- *
- * @param node the node to insert
- * @param element the element after which the given node is to be inserted
- * @param editGroup the edit group in which to collect the corresponding
- * text edits, or <code>null</code> if ungrouped
- * @throws IllegalArgumentException if the node or element is null,
- * or if the node is not part of this rewriter's AST, or if the inserted node
- * is not a new node (or placeholder), or if <code>element</code> is not a member
- * of the list (original or new), or if the described modification is
- * otherwise invalid
- */
- public void insertAfter(ASTNode node, ASTNode element, TextEditGroup editGroup) {
- if (node == null || element == null) {
- throw new IllegalArgumentException();
- }
- int index= getEvent().getIndex(element, ListRewriteEvent.BOTH);
- if (index == -1) {
- throw new IllegalArgumentException("Node does not exist"); //$NON-NLS-1$
- }
- internalInsertAt(node, index + 1, true, editGroup);
- }
-
- /**
- * Inserts the given node into the list before the given element.
- * The existing node must be in the list, either as an original or as a new
- * node that has been inserted.
- * The inserted node must either be brand new (not part of the original AST)
- * or a placeholder node (for example, one created by
- * {@link ASTRewrite#createCopyTarget(ASTNode)},
- * {@link ASTRewrite#createMoveTarget(ASTNode)},
- * or {@link ASTRewrite#createStringPlaceholder(String, int)}). The AST itself
- * is not actually modified in any way; rather, the rewriter just records
- * a note that this node has been inserted into the list.
- *
- * @param node the node to insert
- * @param element the element before which the given node is to be inserted
- * @param editGroup the edit group in which to collect the corresponding
- * text edits, or <code>null</code> if ungrouped
- * @throws IllegalArgumentException if the node or element is null,
- * or if the node is not part of this rewriter's AST, or if the inserted node
- * is not a new node (or placeholder), or if <code>element</code> is not a member
- * of the list (original or new), or if the described modification is
- * otherwise invalid
- */
- public void insertBefore(ASTNode node, ASTNode element, TextEditGroup editGroup) {
- if (node == null || element == null) {
- throw new IllegalArgumentException();
- }
- int index= getEvent().getIndex(element, ListRewriteEvent.BOTH);
- if (index == -1) {
- throw new IllegalArgumentException("Node does not exist"); //$NON-NLS-1$
- }
- internalInsertAt(node, index, false, editGroup);
- }
-
- /**
- * Inserts the given node into the list at the start of the list.
- * Equivalent to <code>insertAt(node, 0, editGroup)</code>.
- *
- * @param node the node to insert
- * @param editGroup the edit group in which to collect the corresponding
- * text edits, or <code>null</code> if ungrouped
- * @throws IllegalArgumentException if the node is null, or if the node is not part
- * of this rewriter's AST, or if the inserted node is not a new node (or
- * placeholder), or if the described modification is otherwise invalid
- * (not a member of this node's original list)
- * @see #insertAt(ASTNode, int, TextEditGroup)
- */
- public void insertFirst(ASTNode node, TextEditGroup editGroup) {
- if (node == null) {
- throw new IllegalArgumentException();
- }
- internalInsertAt(node, 0, false, editGroup);
- }
-
- /**
- * Inserts the given node into the list at the end of the list.
- * Equivalent to <code>insertAt(node, -1, editGroup)</code>.
- *
- * @param node the node to insert
- * @param editGroup the edit group in which to collect the corresponding
- * text edits, or <code>null</code> if ungrouped
- * @throws IllegalArgumentException if the node is null, or if the node is not part
- * of this rewriter's AST, or if the inserted node is not a new node (or
- * placeholder), or if the described modification is otherwise invalid
- * (not a member of this node's original list)
- * @see #insertAt(ASTNode, int, TextEditGroup)
- */
- public void insertLast(ASTNode node, TextEditGroup editGroup) {
- if (node == null) {
- throw new IllegalArgumentException();
- }
- internalInsertAt(node, -1, true, editGroup);
- }
-
- /**
- * Inserts the given node into the list at the given index.
- * The index corresponds to a combined list of original and new nodes;
- * removed or replaced nodes are still in the combined list.
- * The inserted node must either be brand new (not part of the original AST)
- * or a placeholder node (for example, one created by
- * {@link ASTRewrite#createCopyTarget(ASTNode)},
- * {@link ASTRewrite#createMoveTarget(ASTNode)},
- * or {@link ASTRewrite#createStringPlaceholder(String, int)}). The AST itself
- * is not actually modified in any way; rather, the rewriter just records
- * a note that this node has been inserted into the list.
- *
- * @param node the node to insert
- * @param index insertion index in the combined list of original and
- * inserted nodes; <code>-1</code> indicates insertion as the last element
- * @param editGroup the edit group in which to collect the corresponding
- * text edits, or <code>null</code> if ungrouped
- * @throws IllegalArgumentException if the node is null, or if the node is not part
- * of this rewriter's AST, or if the inserted node is not a new node (or
- * placeholder), or if the described modification is otherwise invalid
- * (not a member of this node's original list)
- * @throws IndexOutOfBoundsException if the index is negative and not -1,
- * or if it is larger than the size of the combined list
- */
- public void insertAt(ASTNode node, int index, TextEditGroup editGroup) {
- if (node == null) {
- throw new IllegalArgumentException();
- }
- internalInsertAt(node, index, isInsertBoundToPreviousByDefault(node), editGroup);
- }
-
- private void internalInsertAt(ASTNode node, int index, boolean boundToPrevious, TextEditGroup editGroup) {
- RewriteEvent event= getEvent().insert(node, index);
- if (boundToPrevious) {
- getRewriteStore().setInsertBoundToPrevious(node);
- }
- if (editGroup != null) {
- getRewriteStore().setEventEditGroup(event, editGroup);
- }
- }
-
-
- private ASTNode createTargetNode(ASTNode first, ASTNode last, boolean isMove, ASTNode replacingNode, TextEditGroup editGroup) {
- if (first == null || last == null) {
- throw new IllegalArgumentException();
- }
-
- NodeInfoStore nodeStore= this.rewriter.getNodeStore();
- ASTNode placeholder= nodeStore.newPlaceholderNode(first.getNodeType()); // revisit: could use list type
- if (placeholder == null) {
- throw new IllegalArgumentException("Creating a target node is not supported for nodes of type" + first.getClass().getName()); //$NON-NLS-1$
- }
-
- Block internalPlaceHolder= nodeStore.createCollapsePlaceholder();
- CopySourceInfo info= getRewriteStore().createRangeCopy(this.parent, this.childProperty, first, last, isMove, internalPlaceHolder, replacingNode, editGroup);
- nodeStore.markAsCopyTarget(placeholder, info);
-
- return placeholder;
- }
-
- /**
- * Creates and returns a placeholder node for a true copy of a range of nodes of the
- * current list.
- * The placeholder node can either be inserted as new or used to replace an
- * existing node. When the document is rewritten, a copy of the source code
- * for the given node range is inserted into the output document at the position
- * corresponding to the placeholder (indentation is adjusted).
- *
- * @param first the node that starts the range
- * @param last the node that ends the range
- * @return the new placeholder node
- * @throws IllegalArgumentException An exception is thrown if the first or last node
- * are <code>null</code>, if a node is not a child of the current list or if the first node
- * is not before the last node. An <code>IllegalArgumentException</code> is
- * also thrown if the copied range is overlapping with an other moved or copied range.
- */
- public final ASTNode createCopyTarget(ASTNode first, ASTNode last) {
- if (first == last) {
- return this.rewriter.createCopyTarget(first);
- } else {
- return createTargetNode(first, last, false, null, null);
- }
- }
-
- /**
- * Creates and returns a placeholder node for a move of a range of nodes of the
- * current list.
- * The placeholder node can either be inserted as new or used to replace an
- * existing node. When the document is rewritten, a copy of the source code
- * for the given node range is inserted into the output document at the position
- * corresponding to the placeholder (indentation is adjusted).
- *
- * @param first the node that starts the range
- * @param last the node that ends the range
- * @return the new placeholder node
- * @throws IllegalArgumentException An exception is thrown if the first or last node
- * are <code>null</code>, if a node is not a child of the current list or if the first node
- * is not before the last node. An <code>IllegalArgumentException</code> is
- * also thrown if the moved range is overlapping with an other moved or copied range.
- *
- */
- public final ASTNode createMoveTarget(ASTNode first, ASTNode last) {
- return createMoveTarget(first, last, null, null);
- }
-
- /**
- * Creates and returns a placeholder node for a move of a range of nodes of the
- * current list. The moved nodes can optionally be replaced by a specified node.
- *
- * The placeholder node can either be inserted as new or used to replace an
- * existing node. When the document is rewritten, a copy of the source code
- * for the given node range is inserted into the output document at the position
- * corresponding to the placeholder (indentation is adjusted).
- *
- * @param first the node that starts the range
- * @param last the node that ends the range
- * @param replacingNode a node that is set at the location of the moved nodes
- * or <code>null</code> to remove all nodes
- * @param editGroup the edit group in which to collect the corresponding
- * text edits fro a replace, or <code>null</code> if ungrouped
- * @return the new placeholder node
- * @throws IllegalArgumentException An exception is thrown if the first or
- * last node are <code>null</code>, if a node is not a child of the current list or
- * if the first node is not before the last node. An <code>IllegalArgumentException
- * </code> is also thrown if the moved range is overlapping with an other moved
- * or copied range.
- *
- */
- public final ASTNode createMoveTarget(ASTNode first, ASTNode last, ASTNode replacingNode, TextEditGroup editGroup) {
- if (first == last) {
- replace(first, replacingNode, editGroup);
- return this.rewriter.createMoveTarget(first);
- } else {
- return createTargetNode(first, last, true, replacingNode, editGroup);
- }
- }
-
- /*
- * Heuristic to decide if a inserted node is bound to previous or the next sibling.
- */
- private boolean isInsertBoundToPreviousByDefault(ASTNode node) {
- return (node instanceof Statement || node instanceof FieldDeclaration);
- }
-
- /**
- * Returns the original nodes in the list property managed by this
- * rewriter. The returned list is unmodifiable.
- *
- * @return a list of all original nodes in the list
- */
- public List getOriginalList() {
- List list= (List) getEvent().getOriginalValue();
- return Collections.unmodifiableList(list);
- }
-
- /**
- * Returns the nodes in the revised list property managed by this
- * rewriter. The returned list is unmodifiable.
- *
- * @return a list of all nodes in the list taking into account
- * all the described changes
- */
- public List getRewrittenList() {
- List list= (List) getEvent().getNewValue();
- return Collections.unmodifiableList(list);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/rewrite/TargetSourceRangeComputer.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/rewrite/TargetSourceRangeComputer.java
deleted file mode 100644
index 231b5d4e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/rewrite/TargetSourceRangeComputer.java
+++ /dev/null
@@ -1,137 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.dom.rewrite;
-
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-
-/**
- * An object for computing adjusted source ranges for AST nodes
- * that are being replaced or deleted.
- * <p>
- * For example, a refactoring like inline method may choose to replace
- * calls to the method but leave intact any comments immediately preceding
- * the calls. On the other hand, a refactoring like extract method may choose
- * to extract not only the nodes for the selected code but also any
- * comments preceding or following them.
- * </p>
- * <p>
- * Clients should subclass if they need to influence the
- * the source range to be affected when replacing or deleting a particular node.
- * An instance of the subclass should be registered with
- * {@link ASTRewrite#setTargetSourceRangeComputer(TargetSourceRangeComputer)}.
- * During a call to {@link ASTRewrite#rewriteAST(org.eclipse.jface.text.IDocument, java.util.Map)},
- * the {@link #computeSourceRange(ASTNode)} method on this object will be
- * used to compute the source range for a node being deleted or replaced.
- * </p>
- *
- * 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 TargetSourceRangeComputer {
-
- /**
- * Reified source range. Instances are &quot;value&quot; object
- * (cannot be modified).
- *
- */
- public static final class SourceRange {
- /**
- * 0-based character index, or <code>-1</code>
- * if no source position information is known.
- */
- private int startPosition;
-
- /**
- * (possibly 0) length, or <code>0</code>
- * if no source position information is known.
- */
- private int length;
-
- /**
- * Creates a new source range.
- *
- * @param startPosition the 0-based character index, or <code>-1</code>
- * if no source position information is known
- * @param length the (possibly 0) length, or <code>0</code>
- * if no source position information is known
- */
- public SourceRange(int startPosition, int length) {
- this.startPosition = startPosition;
- this.length = length;
- }
-
- /**
- * Returns the start position.
- *
- * @return the 0-based character index, or <code>-1</code>
- * if no source position information is known
- */
- public int getStartPosition() {
- return this.startPosition;
- }
-
- /**
- * Returns the source length.
- *
- * @return a (possibly 0) length, or <code>0</code>
- * if no source position information is known
- */
- public int getLength() {
- return this.length;
- }
- }
-
- /**
- * Creates a new target source range computer.
- */
- public TargetSourceRangeComputer() {
- // do nothing
- }
-
- /**
- * Returns the target source range of the given node. Unlike
- * {@link ASTNode#getStartPosition()} and {@link ASTNode#getLength()},
- * the extended source range may include comments and whitespace
- * immediately before or after the normal source range for the node.
- * <p>
- * The returned source ranges must satisfy the following conditions:
- * <dl>
- * <li>no two source ranges in an AST may be overlapping</li>
- * <li>a source range of a parent node must fully cover the source ranges of its children</li>
- * </dl>
- * </p>
- * <p>
- * The default implementation uses
- * {@link JavaScriptUnit#getExtendedStartPosition(ASTNode)}
- * and {@link JavaScriptUnit#getExtendedLength(ASTNode)}
- * to compute the target source range. Clients may override or
- * extend this method to expand or contract the source range of the
- * given node. The resulting source range must cover at least the
- * original source range of the node.
- * </p>
- *
- * @param node the node with a known source range in the javaScript unit
- * being rewritten
- * @return the exact source range in the javaScript unit being rewritten
- * that should be replaced (or deleted)
- */
- public SourceRange computeSourceRange(ASTNode node) {
- ASTNode root= node.getRoot();
- if (root instanceof JavaScriptUnit) {
- JavaScriptUnit cu= (JavaScriptUnit) root;
- return new SourceRange(cu.getExtendedStartPosition(node), cu.getExtendedLength(node));
- }
- return new SourceRange(node.getStartPosition(), node.getLength());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/eval/ICodeSnippetRequestor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/eval/ICodeSnippetRequestor.java
deleted file mode 100644
index ccbbf857..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/eval/ICodeSnippetRequestor.java
+++ /dev/null
@@ -1,177 +0,0 @@
-/*******************************************************************************
- * 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.eval;
-
-import org.eclipse.core.resources.IMarker;
-
-/**
- * A code snippet requestor implements a callback interface for installing
- * the class files for a code snippet on the target and running it.
- * In addition, it receives compilation problems detected during code snippet
- * compilation.
- * <p>
- * Clients may implement this interface to provide a bridge a running JavaScript VM.
- * </p>
- *
- * @see IEvaluationContext#evaluateCodeSnippet(String, ICodeSnippetRequestor, org.eclipse.core.runtime.IProgressMonitor)
- * @see IEvaluationContext#evaluateCodeSnippet(String, String[], String[], int[], org.eclipse.wst.jsdt.core.IType, boolean, boolean, ICodeSnippetRequestor, org.eclipse.core.runtime.IProgressMonitor)
- *
- * 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 ICodeSnippetRequestor {
-
- /**
- * The prefix of fields that represent the local variables in a snippet
- * class.
- */
- public static final String LOCAL_VAR_PREFIX = "val$";
-
- /**
- * The name of the field that represent 'this' in a snippet class
- * instance.
- */
- public static final String DELEGATE_THIS = "val$this";
-
- /**
- * The name of the instance method in the snippet class that runs the code
- * snippet.
- */
- public static final String RUN_METHOD = "run";
-
- /**
- * The name of the field (of type <code>java.lang.Object</code>) on the code
- * snippet instance that contains the returned value.
- */
- public static final String RESULT_VALUE_FIELD = "resultValue";
-
- /**
- * The field of type java.lang.Class on the code snippet instance that contains the type of the returned value.
- * The name of the field (of type <code>java.lang.Class</code>) on the code
- * snippet instance that contains the runtime type of the returned value.
- */
- public static final String RESULT_TYPE_FIELD = "resultType";
-
- /*
- * REPORTING A PROBLEM OF COMPILATION IN THE CODE SNIPPET
- */
-
- /**
- * Indicates a compilation problem related to a global variable.
- * <p>
- * Note: if the problem is on the type of the variable, the marker
- * source line number is -1; if the name of the variable, line number is 0;
- * otherwise, the marker source line number is relative to the initializer
- * code.
- * </p>
- *
- * @see #acceptProblem(IMarker, String, int)
- */
- public static final int VARIABLE = 1;
-
- /**
- * Indicates a compilation problem related to a code snippet.
- *
- * @see #acceptProblem(IMarker, String, int)
- */
- public static final int CODE_SNIPPET = 2;
-
- /**
- * Indicates a compilation problem related to an import declaration.
- *
- * @see #acceptProblem(IMarker, String, int)
- */
- public static final int IMPORT = 3;
-
- /**
- * Indicates a compilation problem related to a package declaration.
- *
- * @see #acceptProblem(IMarker, String, int)
- */
- public static final int PACKAGE = 4;
-
- /**
- * Indicates an internal problem.
- *
- * @see #acceptProblem(IMarker, String, int)
- */
- public static final int INTERNAL = 5;
-/**
- * Sends the given class files to the target and loads them. If the given
- * class name is not <code>null</code>, run the code snippet with this class
- * name. Returns whether the code snippet could be deployed. Note it must
- * return <code>true</code> even if running the code snippet threw an exception.
- * <p>
- * The details of sending and loading the class files are left up to
- * implementations.
- * </p>
- * <p>
- * To run a code snippet, an implementation should create a new instance of
- * the given code snippet class and call (directly or using another means) its
- * <code>RUN_METHOD</code>.
- * </p>
- * <p>
- * Also before the call, the implementation should copy the values of the local
- * variables (if any) into the corresponding fields of the code snippet instance.
- * A field name is formed of <code>LOCAL_VAR_PREFIX</code>
- * preceded the name of the local variable. For example, the field name for
- * local variable <code>"myLocal"</code> is <code>"val$myLocal"</code> (assuming the
- * value of <code>LOCAL_VAR_PREFIX</code> is "val$"). In the
- * same way, the implementation should copy the value of the 'this' object into the
- * field called <code>DELEGATE_THIS</code>.
- * </p>
- * <p>
- * After calling the <code>RUN_METHOD</code>, the values of the local
- * variables may have been modified. The implementation must copy the
- * values of the fields back into the local variables.
- * </p>
- * <p>
- * Finally, the overall value returned by the code snippet can be retrieved
- * from the special field <code>RESULT_VALUE_FIELD</code>
- * on the code snippet instance.
- * The <code>Class</code> that is the runtime type of the returned value can be
- * retrieved from the special field <code>RESULT_TYPE_FIELD</code>.
- * </p>
- *
- * @param classFileBytes the list of class file bytes
- * @param classFileCompoundNames the corresponding list of class file type
- * compound names (example of a compound name: {"java", "lang", "Object"})
- * @param codeSnippetClassName name of the actual class to instantiate and run,
- * or <code>null</code> if none
- * @return <code>true</code> if the code snippet was successfully deployed
- */
-public boolean acceptClassFiles(byte[][] classFileBytes, String[][] classFileCompoundNames, String codeSnippetClassName);
-/**
- * Notifies of an evaluation problem.
- * Problems can arise for source of the following kinds:
- * <p>
- * <ul>
- * <li>global variable (<code>VARIABLE</code>) - fragment source is name of
- * variable</li>
- * <li>code snippet (<code>CODE_SNIPPET</code>) - fragment source is code
- * snippet</li>
- * <li>import declaration (<code>IMPORT</code>) - fragment source is
- * import</li>
- * <li>package declaration (<code>PACKAGE</code>) - fragment source is
- * package declaration</li>
- * <li>other (<code>INTERNAL</code>) - no fragment source is involved, internal error occurred.</li>
- * </ul>
- * </p>
- * @param problemMarker the problem marker (cannot be null)
- * @param fragmentSource the fragment source
- * @param fragmentKind the kind of source fragment; one of:
- * <code>VARIABLE</code>, <code>CODE_SNIPPET</code>, <code>IMPORT</code>,
- * <code>PACKAGE</code>, or <code>INTERNAL</code>
- */
-public void acceptProblem(IMarker problemMarker, String fragmentSource, int fragmentKind);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/eval/IEvaluationContext.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/eval/IEvaluationContext.java
deleted file mode 100644
index e1e42549..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/eval/IEvaluationContext.java
+++ /dev/null
@@ -1,385 +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.core.eval;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.wst.jsdt.core.CompletionRequestor;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-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.WorkingCopyOwner;
-
-/**
- * An evaluation context supports evaluating code snippets.
- * <p>
- * A code snippet is pretty much any valid piece of JavaScript code that could be
- * pasted into the body of a method and compiled. However, there are two
- * areas where the rules are slightly more liberal.
- * <p>
- * First, a code snippet can return heterogeneous types. Inside the same code
- * snippet an <code>int</code> could be returned on one line, and a
- * <code>String</code> on the next, etc. For example, the following would be
- * considered a valid code snippet:
- * <pre>
- * <code>
- * char c = '3';
- * switch (c) {
- * case '1': return 1;
- * case '2': return '2';
- * case '3': return "3";
- * default: return null;
- * }
- * </code>
- * </pre>
- * </p>
- * <p>
- * Second, if the last statement is only an expression, the <code>return</code>
- * keyword is implied. For example, the following returns <code>false</code>:
- * <pre>
- * <code>
- * int i = 1;
- * i == 2
- * </code>
- * </pre>
- * </p>
- * <p>
- * Global variables are an additional feature of evaluation contexts. Within an
- * evaluation context, global variables maintain their value across evaluations.
- * These variables are particularly useful for storing the result of an
- * evaluation for use in subsequent evaluations.
- * </p>
- * <p>
- * The evaluation context remembers the name of the package in which code
- * snippets are run. The user can set this to any package, thereby gaining
- * access to types that are normally only visible within that package.
- * </p>
- * <p>
- * Finally, the evaluation context remembers a list of import declarations. The
- * user can import any packages and types so that the code snippets may refer
- * to types by their shorter simple names.
- * </p>
- * <p>
- * Example of use:
- * <pre>
- * <code>
- * IJavaScriptProject project = getJavaProject();
- * IEvaluationContext context = project.newEvaluationContext();
- * String codeSnippet = "int i= 0; i++";
- * ICodeSnippetRequestor requestor = ...;
- * context.evaluateCodeSnippet(codeSnippet, requestor, progressMonitor);
- * </code>
- * </pre>
- * </p>
- * <p>
- * This interface is not intended to be implemented by clients.
- * <code>IJavaScriptProject.newEvaluationContext</code> can be used to obtain an
- * instance.
- * </p>
- *
- * @see IJavaScriptProject#newEvaluationContext()
- *
- * 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 IEvaluationContext {
- /**
- * Returns the global variables declared in this evaluation context.
- * The variables are maintained in the order they are created in.
- *
- * @return the list of global variables
- */
- public IGlobalVariable[] allVariables();
-
- /**
- * Performs a code completion at the given position in the given code snippet,
- * reporting results to the given completion requestor.
- * <p>
- * Note that code completion does not involve evaluation.
- * <p>
- *
- * @param codeSnippet the code snippet to complete in
- * @param position the character position in the code snippet to complete at,
- * or -1 indicating the beginning of the snippet
- * @param requestor the code completion requestor capable of accepting all
- * possible types of completions
- * @exception JavaScriptModelException if code completion could not be performed. Reasons include:
- * <ul>
- * <li>The position specified is less than -1 or is greater than the snippet's
- * length (INDEX_OUT_OF_BOUNDS)</li>
- * </ul>
- *
- */
- public void codeComplete(
- String codeSnippet,
- int position,
- CompletionRequestor requestor)
- throws JavaScriptModelException;
- /**
- * Performs a code completion at the given position in the given code snippet,
- * reporting results to the given completion requestor.
- * It considers types in the working copies with the given owner first. In other words,
- * the owner's working copies will take precedence over their original javascript unit s
- * in the workspace.
- * <p>
- * Note that if a working copy is empty, it will be as if the original compilation
- * unit had been deleted.
- * </p>
- * <p>
- * Note that code completion does not involve evaluation.
- * <p>
- *
- * @param codeSnippet the code snippet to complete in
- * @param position the character position in the code snippet to complete at,
- * or -1 indicating the beginning of the snippet
- * @param requestor the code completion requestor capable of accepting all
- * possible types of completions
- * @param owner the owner of working copies that take precedence over their original javascript unit s
- * @exception JavaScriptModelException if code completion could not be performed. Reasons include:
- * <ul>
- * <li>The position specified is less than -1 or is greater than the snippet's
- * length (INDEX_OUT_OF_BOUNDS)</li>
- * </ul>
- *
- */
- public void codeComplete(
- String codeSnippet,
- int position,
- CompletionRequestor requestor,
- WorkingCopyOwner owner)
- throws JavaScriptModelException;
- /**
- * Resolves and returns a collection of JavaScript elements corresponding to the source
- * code at the given positions in the given code snippet.
- * <p>
- * Note that code select does not involve evaluation, and problems are never
- * reported.
- * <p>
- *
- * @param codeSnippet the code snippet to resolve in
- * @param offset the position in the code snippet of the first character
- * of the code to resolve
- * @param length the length of the selected code to resolve
- * @return the (possibly empty) list of selection JavaScript elements
- * @exception JavaScriptModelException if code resolve could not be performed.
- * Reasons include:
- * <ul>
- * <li>The position specified is less than -1 or is greater than the snippet's
- * length (INDEX_OUT_OF_BOUNDS)</li>
- * </ul>
- */
- public IJavaScriptElement[] codeSelect(String codeSnippet, int offset, int length)
- throws JavaScriptModelException;
- /**
- * Resolves and returns a collection of JavaScript elements corresponding to the source
- * code at the given positions in the given code snippet.
- * It considers types in the working copies with the given owner first. In other words,
- * the owner's working copies will take precedence over their original javascript unit s
- * in the workspace.
- * <p>
- * Note that if a working copy is empty, it will be as if the original compilation
- * unit had been deleted.
- * </p>
- * <p>
- * Note that code select does not involve evaluation, and problems are never
- * reported.
- * <p>
- *
- * @param codeSnippet the code snippet to resolve in
- * @param offset the position in the code snippet of the first character
- * of the code to resolve
- * @param length the length of the selected code to resolve
- * @param owner the owner of working copies that take precedence over their original javascript unit s
- * @return the (possibly empty) list of selection JavaScript elements
- * @exception JavaScriptModelException if code resolve could not be performed.
- * Reasons include:
- * <ul>
- * <li>The position specified is less than -1 or is greater than the snippet's
- * length (INDEX_OUT_OF_BOUNDS)</li>
- * </ul>
- *
- */
- public IJavaScriptElement[] codeSelect(String codeSnippet, int offset, int length, WorkingCopyOwner owner)
- throws JavaScriptModelException;
- /**
- * Deletes the given variable from this evaluation context. Does nothing if
- * the given variable has already been deleted.
- *
- * @param variable the global variable
- */
- public void deleteVariable(IGlobalVariable variable);
- /**
- * Evaluates the given code snippet in the context of a suspended thread.
- * The code snippet is compiled along with this context's package declaration,
- * imports, and global variables. The given requestor's
- * <code>acceptProblem</code> method is called for each compilation problem that
- * is detected. Then the resulting class files are handed to the given
- * requestor's <code>acceptClassFiles</code> method to deploy and run.
- * <p>
- * The requestor is expected to:
- * <ol>
- * <li>send the class files to the target VM,
- * <li>load them (starting with the code snippet class),
- * <li>create a new instance of the code snippet class,
- * <li>run the method <code>run()</code> of the code snippet,
- * <li>retrieve the values of the local variables,
- * <li>retrieve the returned value of the code snippet
- * </ol>
- * </p>
- * <p>
- * This method is long-running; progress and cancellation are provided
- * by the given progress monitor.
- * </p>
- *
- * @param codeSnippet the code snippet
- * @param localVariableTypeNames the dot-separated fully qualified names of the types of the local variables.
- * @param localVariableNames the names of the local variables as they are declared in the user's code.
- * @param localVariableModifiers the modifiers of the local variables (default modifier or final modifier).
- * @param declaringType the type in which the code snippet is evaluated.
- * @param isStatic whether the code snippet is evaluated in a static member of the declaring type.
- * @param isConstructorCall whether the code snippet is evaluated in a constructor of the declaring type.
- * @param requestor the code snippet requestor
- * @param progressMonitor a progress monitor
- * @exception JavaScriptModelException if a runtime problem occurred or if this
- * context's project has no build state
- */
- public void evaluateCodeSnippet(
- String codeSnippet,
- String[] localVariableTypeNames,
- String[] localVariableNames,
- int[] localVariableModifiers,
- IType declaringType,
- boolean isStatic,
- boolean isConstructorCall,
- ICodeSnippetRequestor requestor,
- IProgressMonitor progressMonitor)
- throws JavaScriptModelException;
- /**
- * Evaluates the given code snippet. The code snippet is
- * compiled along with this context's package declaration, imports, and
- * global variables. The given requestor's <code>acceptProblem</code> method
- * is called for each compilation problem that is detected. Then the resulting
- * class files are handed to the given requestor's <code>acceptClassFiles</code>
- * method to deploy and run. The requestor is also responsible for getting the
- * result back.
- * <p>
- * This method is long-running; progress and cancellation are provided
- * by the given progress monitor.
- * </p>
- *
- * @param codeSnippet the code snippet
- * @param requestor the code snippet requestor
- * @param progressMonitor a progress monitor
- * @exception JavaScriptModelException if a runtime problem occurred or if this
- * context's project has no build state
- */
- public void evaluateCodeSnippet(
- String codeSnippet,
- ICodeSnippetRequestor requestor,
- IProgressMonitor progressMonitor)
- throws JavaScriptModelException;
- /**
- * Evaluates the given global variable. During this operation,
- * this context's package declaration, imports, and <i>all</i> its declared
- * variables are verified. The given requestor's <code>acceptProblem</code>
- * method will be called for each problem that is detected.
- * <p>
- * This method is long-running; progress and cancellation are provided
- * by the given progress monitor.
- * </p>
- *
- * @param variable the global variable
- * @param requestor the code snippet requestor
- * @param progressMonitor a progress monitor
- * @exception JavaScriptModelException if a runtime problem occurred or if this
- * context's project has no build state
- */
- public void evaluateVariable(
- IGlobalVariable variable,
- ICodeSnippetRequestor requestor,
- IProgressMonitor progressMonitor)
- throws JavaScriptModelException;
- /**
- * Returns the import declarations for this evaluation context. Returns and empty
- * list if there are no imports (the default if the imports have never been set).
- * The syntax for the import corresponds to a fully qualified type name, or to
- * an on-demand package name as defined by ImportDeclaration (JLS2 7.5). For
- * example, <code>"java.util.Hashtable"</code> or <code>"java.util.*"</code>.
- *
- * @return the list of import names
- */
- public String[] getImports();
- /**
- * Returns the name of the package in which code snippets are to be compiled and
- * run. Returns an empty string for the default package (the default if the
- * package name has never been set). For example, <code>"com.example.myapp"</code>.
- *
- * @return the dot-separated package name, or the empty string indicating the
- * default package
- */
- public String getPackageName();
- /**
- * Returns the JavaScript project this evaluation context was created for.
- *
- * @return the JavaScript project
- */
- public IJavaScriptProject getProject();
- /**
- * Creates a new global variable with the given name, type, and initializer.
- * <p>
- * The <code>typeName</code> and <code>initializer</code> are interpreted in
- * the context of this context's package and import declarations.
- * </p>
- * <p>
- * The syntax for a type name corresponds to Type in Field Declaration (JLS2 8.3).
- * </p>
- *
- * @param typeName the type name
- * @param name the name of the global variable
- * @param initializer the initializer expression, or <code>null</code> if the
- * variable is not initialized
- * @return a new global variable with the given name, type, and initializer
- */
- public IGlobalVariable newVariable(
- String typeName,
- String name,
- String initializer);
- /**
- * Sets the import declarations for this evaluation context. An empty
- * list indicates there are no imports. The syntax for the import corresponds to a
- * fully qualified type name, or to an on-demand package name as defined by
- * ImportDeclaration (JLS2 7.5). For example, <code>"java.util.Hashtable"</code>
- * or <code>"java.util.*"</code>.
- *
- * @param imports the list of import names
- */
- public void setImports(String[] imports);
- /**
- * Sets the dot-separated name of the package in which code snippets are
- * to be compiled and run. For example, <code>"com.example.myapp"</code>.
- *
- * @param packageName the dot-separated package name, or the empty string
- * indicating the default package
- */
- public void setPackageName(String packageName);
- /**
- * Validates this evaluation context's import declarations. The given requestor's
- * <code>acceptProblem</code> method is called for each problem that is detected.
- *
- * @param requestor the code snippet requestor
- * @exception JavaScriptModelException if this context's project has no build state
- */
- public void validateImports(ICodeSnippetRequestor requestor)
- throws JavaScriptModelException;
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/eval/IGlobalVariable.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/eval/IGlobalVariable.java
deleted file mode 100644
index 53f7b927..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/eval/IGlobalVariable.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.eval;
-
-/**
- * A global variable declared in an evaluation context.
- * <p>
- * This interface is not intended to be implemented by clients.
- * <code>IEvaluationContext.newVariable</code> can be used to obtain an instance.
- * </p>
- *
- * @see IEvaluationContext#newVariable(String, String, String)
- *
- * 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 IGlobalVariable {
-/**
- * Returns the initializer of this global variable.
- * The syntax for an initializer corresponds to VariableInitializer (JLS2 8.3).
- *
- * @return the initializer expression, or <code>null</code> if this global does
- * not have an initializer
- */
-public String getInitializer();
-/**
- * Returns the name of this global variable.
- *
- * @return the name of the global variable
- */
-public String getName();
-/**
- * Returns the fully qualified name of the type of this global
- * variable, or its simple representation if it is a primitive type
- * (<code>int</code>, <code>boolean</code>, etc.).
- * <p>
- * The syntax for a type name corresponds to Type in Field Declaration (JLS2 8.3).
- * </p>
- * @return the type name
- */
-public String getTypeName();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/formatter/CodeFormatter.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/formatter/CodeFormatter.java
deleted file mode 100644
index 1889ff6d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/formatter/CodeFormatter.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*******************************************************************************
- * 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.formatter;
-
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.internal.compiler.util.Util;
-
-/**
- * Specification for a generic source code formatter.
- *
- *
- * 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 CodeFormatter {
-
- /**
- * Unknown kind
- */
- public static final int K_UNKNOWN = 0x00;
-
- /**
- * Kind used to format an expression
- */
- public static final int K_EXPRESSION = 0x01;
-
- /**
- * Kind used to format a set of statements
- */
- public static final int K_STATEMENTS = 0x02;
-
- /**
- * Kind used to format a set of class body declarations
- */
- public static final int K_CLASS_BODY_DECLARATIONS = 0x04;
-
- /**
- * Kind used to format a javascript unit
- */
- public static final int K_JAVASCRIPT_UNIT = 0x08;
-
- /**
- * Kind used to format a single-line comment
- *
- */
- public static final int K_SINGLE_LINE_COMMENT = 0x10;
- /**
- * Kind used to format a multi-line comment
- *
- */
- public static final int K_MULTI_LINE_COMMENT = 0x20;
- /**
- * Kind used to format a jsdoc comment
- *
- */
- public static final int K_JAVA_DOC = 0x40;
-
- /**
- * Format <code>source</code>,
- * and returns a text edit that correspond to the difference between the given string and the formatted string.
- * <p>It returns null if the given string cannot be formatted.</p>
- *
- * <p>If the offset position is matching a whitespace, the result can include whitespaces. It would be up to the
- * caller to get rid of preceeding whitespaces.</p>
- *
- * @param kind Use to specify the kind of the code snippet to format. It can be any of these:
- * K_EXPRESSION, K_STATEMENTS, K_CLASS_BODY_DECLARATIONS, K_JAVASCRIPT_UNIT, K_UNKNOWN,
- * K_SINGLE_LINE_COMMENT, K_MULTI_LINE_COMMENT, K_JAVA_DOC
- * @param source the source to format
- * @param offset the given offset to start recording the edits (inclusive).
- * @param length the given length to stop recording the edits (exclusive).
- * @param indentationLevel the initial indentation level, used
- * to shift left/right the entire source fragment. An initial indentation
- * level of zero or below has no effect.
- * @param lineSeparator the line separator to use in formatted source,
- * if set to <code>null</code>, then the platform default one will be used.
- * @return the text edit
- * @throws IllegalArgumentException if offset is lower than 0, length is lower than 0 or
- * length is greater than source length.
- */
- public abstract TextEdit format(int kind, String source, int offset, int length, int indentationLevel, String lineSeparator);
-
- /**
- * Answers the string that corresponds to the indentation to the given indentation level or an empty string
- * if the indentation cannot be computed.
- * <p>This method needs to be overriden in a subclass.</p>
- *
- * <p>The default implementation returns an empty string.</p>
- *
- * @param indentationLevel the given indentation level
- * @return the string corresponding to the right indentation level
- * @exception IllegalArgumentException if the given indentation level is lower than zero
- *
- */
- public String createIndentationString(int indentationLevel) {
- return Util.EMPTY_STRING;
- }
-}
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
deleted file mode 100644
index bdfea225..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/formatter/CodeFormatterApplication.java
+++ /dev/null
@@ -1,400 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2004, 2008 Ben Konrath <ben@bagu.org>
- * 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
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Ben Konrath <ben@bagu.org> - initial implementation
- * Red Hat Incorporated - improvements based on comments from JDT developers
- * IBM Corporation - Code review and integration
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.formatter;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.text.MessageFormat;
-import java.util.ArrayList;
-import java.util.Map;
-import java.util.Properties;
-
-import org.eclipse.equinox.app.IApplication;
-import org.eclipse.equinox.app.IApplicationContext;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.osgi.util.NLS;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.ToolFactory;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * Implements an Eclipse Application for org.eclipse.wst.jsdt.core.JavaCodeFormatter.
- *
- * There are a couple improvments that could be made: 1. Make a list of all the
- * files first so that a file does not get formatted twice. 2. Use a text based
- * progress monitor for output.
- * <p>
- * This class is not intended to be instantiated or subclassed by clients.
- * </p>
- *
- * @author Ben Konrath <bkonrath@redhat.com>
- *
- * 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 CodeFormatterApplication implements IApplication {
-
- /**
- * Deals with the messages in the properties file (cut n' pasted from a
- * generated class).
- */
- private final static class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.wst.jsdt.core.formatter.messages";//$NON-NLS-1$
-
- public static String CommandLineConfigFile;
-
- public static String CommandLineDone;
-
- public static String CommandLineErrorConfig;
-
- public static String CommandLineErrorFile;
-
- public static String CommandLineErrorFileDir;
-
- public static String CommandLineErrorQuietVerbose;
-
- public static String CommandLineErrorNoConfigFile;
-
- public static String CommandLineFormatting;
-
- public static String CommandLineStart;
-
- public static String CommandLineUsage;
-
- public static String ConfigFileReadingError;
-
- public static String FormatProblem;
-
- public static String CaughtException;
-
- public static String ExceptionSkip;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
-
- /**
- * Bind the given message's substitution locations with the given string
- * values.
- *
- * @param message
- * the message to be manipulated
- * @return the manipulated String
- */
- public static String bind(String message) {
- return bind(message, null);
- }
-
- /**
- * Bind the given message's substitution locations with the given string
- * values.
- *
- * @param message
- * the message to be manipulated
- * @param binding
- * the object to be inserted into the message
- * @return the manipulated String
- */
- public static String bind(String message, Object binding) {
- return bind(message, new Object[] {
- binding
- });
- }
-
- /**
- * Bind the given message's substitution locations with the given string
- * values.
- *
- * @param message
- * the message to be manipulated
- * @param binding1
- * An object to be inserted into the message
- * @param binding2
- * A second object to be inserted into the message
- * @return the manipulated String
- */
- public static String bind(String message, Object binding1, Object binding2) {
- return bind(message, new Object[] {
- binding1, binding2
- });
- }
-
- /**
- * Bind the given message's substitution locations with the given string
- * values.
- *
- * @param message
- * the message to be manipulated
- * @param bindings
- * An array of objects to be inserted into the message
- * @return the manipulated String
- */
- public static String bind(String message, Object[] bindings) {
- return MessageFormat.format(message, bindings);
- }
- }
-
- private static final String ARG_CONFIG = "-config"; //$NON-NLS-1$
-
- private static final String ARG_HELP = "-help"; //$NON-NLS-1$
-
- private static final String ARG_QUIET = "-quiet"; //$NON-NLS-1$
-
- private static final String ARG_VERBOSE = "-verbose"; //$NON-NLS-1$
-
- private String configName;
-
- private Map options = null;
-
- private static final String PDE_LAUNCH = "-pdelaunch"; //$NON-NLS-1$
-
- private boolean quiet = false;
-
- private boolean verbose = false;
-
- /**
- * Display the command line usage message.
- */
- private void displayHelp() {
- System.out.println(Messages.bind(Messages.CommandLineUsage));
- }
-
- private void displayHelp(String message) {
- System.err.println(message);
- System.out.println();
- displayHelp();
- }
-
- /**
- * Recursively format the JavaScript source code that is contained in the
- * directory rooted at dir.
- */
- private void formatDirTree(File dir, CodeFormatter codeFormatter) {
-
- File[] files = dir.listFiles();
- if (files == null)
- return;
-
- for (int i = 0; i < files.length; i++) {
- File file = files[i];
- if (file.isDirectory()) {
- formatDirTree(file, codeFormatter);
- } else if (Util.isJavaLikeFileName(file.getPath())) {
- formatFile(file, codeFormatter);
- }
- }
- }
-
- /**
- * Format the given JavaScript source file.
- */
- private void formatFile(File file, CodeFormatter codeFormatter) {
- IDocument doc = new Document();
- try {
- // read the file
- if (this.verbose) {
- System.out.println(Messages.bind(Messages.CommandLineFormatting, file.getAbsolutePath()));
- }
- String contents = new String(org.eclipse.wst.jsdt.internal.compiler.util.Util.getFileCharContent(file, null));
- // format the file (the meat and potatoes)
- doc.set(contents);
- TextEdit edit = codeFormatter.format(CodeFormatter.K_JAVASCRIPT_UNIT, contents, 0, contents.length(), 0, null);
- if (edit != null) {
- edit.apply(doc);
- } else {
- System.err.println(Messages.bind(Messages.FormatProblem, file.getAbsolutePath()));
- return;
- }
-
- // write the file
- final BufferedWriter out = new BufferedWriter(new FileWriter(file));
- try {
- out.write(doc.get());
- out.flush();
- } finally {
- try {
- out.close();
- } catch (IOException e) {
- /* ignore */
- }
- }
- } catch (IOException e) {
- String errorMessage = Messages.bind(Messages.CaughtException, "IOException", e.getLocalizedMessage()); //$NON-NLS-1$
- Util.log(e, errorMessage);
- System.err.println(Messages.bind(Messages.ExceptionSkip ,errorMessage));
- } catch (BadLocationException e) {
- String errorMessage = Messages.bind(Messages.CaughtException, "BadLocationException", e.getLocalizedMessage()); //$NON-NLS-1$
- Util.log(e, errorMessage);
- System.err.println(Messages.bind(Messages.ExceptionSkip ,errorMessage));
- }
- }
-
- private File[] processCommandLine(String[] argsArray) {
-
- ArrayList args = new ArrayList();
- for (int i = 0, max = argsArray.length; i < max; i++) {
- args.add(argsArray[i]);
- }
- int index = 0;
- final int argCount = argsArray.length;
-
- final int DEFAULT_MODE = 0;
- final int CONFIG_MODE = 1;
-
- int mode = DEFAULT_MODE;
- final int INITIAL_SIZE = 1;
- int fileCounter = 0;
-
- File[] filesToFormat = new File[INITIAL_SIZE];
-
- loop: while (index < argCount) {
- String currentArg = argsArray[index++];
-
- switch(mode) {
- case DEFAULT_MODE :
- if (PDE_LAUNCH.equals(currentArg)) {
- continue loop;
- }
- if (ARG_HELP.equals(currentArg)) {
- displayHelp();
- return null;
- }
- if (ARG_VERBOSE.equals(currentArg)) {
- this.verbose = true;
- continue loop;
- }
- if (ARG_QUIET.equals(currentArg)) {
- this.quiet = true;
- continue loop;
- }
- if (ARG_CONFIG.equals(currentArg)) {
- mode = CONFIG_MODE;
- continue loop;
- }
- // the current arg should be a file or a directory name
- File file = new File(currentArg);
- if (file.exists()) {
- if (filesToFormat.length == fileCounter) {
- System.arraycopy(filesToFormat, 0, (filesToFormat = new File[fileCounter * 2]), 0, fileCounter);
- }
- filesToFormat[fileCounter++] = file;
- } else {
- displayHelp(Messages.bind(Messages.CommandLineErrorFile, currentArg));
- return null;
- }
- break;
- case CONFIG_MODE :
- this.configName = currentArg;
- this.options = readConfig(currentArg);
- if (this.options == null) {
- displayHelp(Messages.bind(Messages.CommandLineErrorConfig, currentArg));
- return null;
- }
- mode = DEFAULT_MODE;
- continue loop;
- }
- }
-
- if (mode == CONFIG_MODE || this.options == null) {
- displayHelp(Messages.bind(Messages.CommandLineErrorNoConfigFile));
- return null;
- }
- if (this.quiet && this.verbose) {
- displayHelp(
- Messages.bind(
- Messages.CommandLineErrorQuietVerbose,
- new String[] { ARG_QUIET, ARG_VERBOSE }
- ));
- return null;
- }
- if (fileCounter == 0) {
- displayHelp(Messages.bind(Messages.CommandLineErrorFileDir));
- return null;
- }
- if (filesToFormat.length != fileCounter) {
- System.arraycopy(filesToFormat, 0, (filesToFormat = new File[fileCounter]), 0, fileCounter);
- }
- return filesToFormat;
- }
-
- /**
- * Return a JavaScript Properties file representing the options that are in the
- * specified config file.
- */
- private Properties readConfig(String filename) {
- BufferedInputStream stream = null;
- try {
- stream = new BufferedInputStream(new FileInputStream(new File(filename)));
- final Properties formatterOptions = new Properties();
- formatterOptions.load(stream);
- return formatterOptions;
- } catch (IOException e) {
- Util.log(e, Messages.bind(Messages.ConfigFileReadingError));
- } finally {
- if (stream != null) {
- try {
- stream.close();
- } catch (IOException e) {
- /* ignore */
- }
- }
- }
- return null;
- }
-
- /**
- * Runs the JavaScript code formatter application
- */
- public Object start(IApplicationContext context) throws Exception {
- File[] filesToFormat = processCommandLine((String[]) context.getArguments().get(IApplicationContext.APPLICATION_ARGS));
-
- if (filesToFormat == null) {
- return IApplication.EXIT_OK;
- }
-
- if (!this.quiet) {
- if (this.configName != null) {
- System.out.println(Messages.bind(Messages.CommandLineConfigFile, this.configName));
- }
- System.out.println(Messages.bind(Messages.CommandLineStart));
- }
-
- final CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(this.options);
- // format the list of files and/or directories
- for (int i = 0, max = filesToFormat.length; i < max; i++) {
- final File file = filesToFormat[i];
- if (file.isDirectory()) {
- formatDirTree(file, codeFormatter);
- } else if (Util.isJavaLikeFileName(file.getPath())) {
- formatFile(file, codeFormatter);
- }
- }
- if (!this.quiet) {
- System.out.println(Messages.bind(Messages.CommandLineDone));
- }
-
- return IApplication.EXIT_OK;
- }
- public void stop() {
- // do nothing
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/formatter/DefaultCodeFormatterConstants.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/formatter/DefaultCodeFormatterConstants.java
deleted file mode 100644
index 7bb65b46..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/formatter/DefaultCodeFormatterConstants.java
+++ /dev/null
@@ -1,3640 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.formatter;
-
-import java.util.Map;
-
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.formatter.DefaultCodeFormatterOptions;
-import org.eclipse.wst.jsdt.internal.formatter.align.Alignment;
-
-/**
- * Constants used to set up the options of the code formatter.
- * <p>
- * This class is not intended to be instantiated or subclassed by clients.
- * </p>
- *
- *
- * 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 DefaultCodeFormatterConstants {
-
- /**
- * <pre>
- * FORMATTER / Value to set a brace location at the end of a line.
- * </pre>
- * @see #FORMATTER_BRACE_POSITION_FOR_ANONYMOUS_TYPE_DECLARATION
- * @see #FORMATTER_BRACE_POSITION_FOR_ARRAY_INITIALIZER
- * @see #FORMATTER_BRACE_POSITION_FOR_OBJLIT_INITIALIZER
- * @see #FORMATTER_BRACE_POSITION_FOR_BLOCK
- * @see #FORMATTER_BRACE_POSITION_FOR_CONSTRUCTOR_DECLARATION
- * @see #FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION
- * @see #FORMATTER_BRACE_POSITION_FOR_SWITCH
- * @see #FORMATTER_BRACE_POSITION_FOR_TYPE_DECLARATION
- *
- */
- public static final String END_OF_LINE = "end_of_line"; //$NON-NLS-1$
-
- /**
- * <pre>
- * FORMATTER / Value to set an option to false.
- * </pre>
- *
- */
- public static final String FALSE = "false"; //$NON-NLS-1$
-
- /**
- * <pre>
- * FORMATTER / Option to align type members of a type declaration on column
- * - option id: "org.eclipse.wst.jsdt.core.formatter.formatter.align_type_members_on_columns"
- * - possible values: { TRUE, FALSE }
- * - default: FALSE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String FORMATTER_ALIGN_TYPE_MEMBERS_ON_COLUMNS = JavaScriptCore.PLUGIN_ID + ".formatter.align_type_members_on_columns"; //$NON-NLS-1$
-
- /**
- * <pre>
- * FORMATTER / Option for alignment of arguments in allocation expression
- * - option id: "org.eclipse.wst.jsdt.core.formatter.alignment_for_arguments_in_allocation_expression"
- * - possible values: values returned by <code>createAlignmentValue(boolean, int, int)</code> call
- * - default: createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
- * </pre>
- * @see #createAlignmentValue(boolean, int, int)
- *
- */
- public static final String FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_ALLOCATION_EXPRESSION = JavaScriptCore.PLUGIN_ID + ".formatter.alignment_for_arguments_in_allocation_expression"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option for alignment of arguments in enum constant
- * - option id: "org.eclipse.wst.jsdt.core.formatter.alignment_for_arguments_in_enum_constant"
- * - possible values: values returned by <code>createAlignmentValue(boolean, int, int)</code> call
- * - default: createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
- * </pre>
- * @see #createAlignmentValue(boolean, int, int)
- *
- */
- public static final String FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_ENUM_CONSTANT = JavaScriptCore.PLUGIN_ID + ".formatter.alignment_for_arguments_in_enum_constant"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option for alignment of arguments in explicit constructor call
- * - option id: "org.eclipse.wst.jsdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call"
- * - possible values: values returned by <code>createAlignmentValue(boolean, int, int)</code> call
- * - default: createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
- * </pre>
- * @see #createAlignmentValue(boolean, int, int)
- *
- */
- public static final String FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_EXPLICIT_CONSTRUCTOR_CALL = JavaScriptCore.PLUGIN_ID + ".formatter.alignment_for_arguments_in_explicit_constructor_call"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option for alignment of arguments in method invocation
- * - option id: "org.eclipse.wst.jsdt.core.formatter.alignment_for_arguments_in_method_invocation"
- * - possible values: values returned by <code>createAlignmentValue(boolean, int, int)</code> call
- * - default: createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
- * </pre>
- * @see #createAlignmentValue(boolean, int, int)
- *
- */
- public static final String FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION = JavaScriptCore.PLUGIN_ID + ".formatter.alignment_for_arguments_in_method_invocation"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option for alignment of arguments in qualified allocation expression
- * - option id: "org.eclipse.wst.jsdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression"
- * - possible values: values returned by <code>createAlignmentValue(boolean, int, int)</code> call
- * - default: createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
- * </pre>
- * @see #createAlignmentValue(boolean, int, int)
- *
- */
- public static final String FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_QUALIFIED_ALLOCATION_EXPRESSION = JavaScriptCore.PLUGIN_ID + ".formatter.alignment_for_arguments_in_qualified_allocation_expression"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option for alignment of assignment
- * - option id: "org.eclipse.wst.jsdt.core.formatter.alignment_for_assignment"
- * - possible values: values returned by <code>createAlignmentValue(boolean, int, int)</code> call
- * - default: createAlignmentValue(false, M_NO_ALIGNMENT, INDENT_DEFAULT)
- * </pre>
- * @see #createAlignmentValue(boolean, int, int)
- *
- */
- public static final String FORMATTER_ALIGNMENT_FOR_ASSIGNMENT = JavaScriptCore.PLUGIN_ID + ".formatter.alignment_for_assignment"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option for alignment of binary expression
- * - option id: "org.eclipse.wst.jsdt.core.formatter.alignment_for_binary_expression"
- * - possible values: values returned by <code>createAlignmentValue(boolean, int, int)</code> call
- * - default: createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
- * </pre>
- * @see #createAlignmentValue(boolean, int, int)
- *
- */
- public static final String FORMATTER_ALIGNMENT_FOR_BINARY_EXPRESSION = JavaScriptCore.PLUGIN_ID + ".formatter.alignment_for_binary_expression"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option for alignment of compact if
- * - option id: "org.eclipse.wst.jsdt.core.formatter.alignment_for_compact_if"
- * - possible values: values returned by <code>createAlignmentValue(boolean, int, int)</code> call
- * - default: createAlignmentValue(false, WRAP_ONE_PER_LINE, INDENT_BY_ONE)
- * </pre>
- * @see #createAlignmentValue(boolean, int, int)
- *
- */
- public static final String FORMATTER_ALIGNMENT_FOR_COMPACT_IF = JavaScriptCore.PLUGIN_ID + ".formatter.alignment_for_compact_if"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option for alignment of conditional expression
- * - option id: "org.eclipse.wst.jsdt.core.formatter.alignment_for_conditional_expression"
- * - possible values: values returned by <code>createAlignmentValue(boolean, int, int)</code> call
- * - default: createAlignmentValue(false, WRAP_ONE_PER_LINE, INDENT_DEFAULT)
- * </pre>
- * @see #createAlignmentValue(boolean, int, int)
- *
- */
- public static final String FORMATTER_ALIGNMENT_FOR_CONDITIONAL_EXPRESSION = JavaScriptCore.PLUGIN_ID + ".formatter.alignment_for_conditional_expression"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option for alignment of enum constants
- * - option id: "org.eclipse.wst.jsdt.core.formatter.alignment_for_enum_constants"
- * - possible values: values returned by <code>createAlignmentValue(boolean, int, int)</code> call
- * - default: createAlignmentValue(false, WRAP_NO_SPLIT, INDENT_DEFAULT)
- * </pre>
- * @see #createAlignmentValue(boolean, int, int)
- *
- */
- public static final String FORMATTER_ALIGNMENT_FOR_ENUM_CONSTANTS = JavaScriptCore.PLUGIN_ID + ".formatter.alignment_for_enum_constants"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option for alignment of expressions in array initializer
- * - option id: "org.eclipse.wst.jsdt.core.formatter.alignment_for_expressions_in_array_initializer"
- * - possible values: values returned by <code>createAlignmentValue(boolean, int, int)</code> call
- * - default: createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
- * </pre>
- * @see #createAlignmentValue(boolean, int, int)
- *
- */
- public static final String FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_ARRAY_INITIALIZER = JavaScriptCore.PLUGIN_ID + ".formatter.alignment_for_expressions_in_array_initializer"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option for alignment of multiple fields
- * - option id: "org.eclipse.wst.jsdt.core.formatter.alignment_for_multiple_fields"
- * - possible values: values returned by <code>createAlignmentValue(boolean, int, int)</code> call
- * - default: createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
- * </pre>
- * @see #createAlignmentValue(boolean, int, int)
- *
- */
- public static final String FORMATTER_ALIGNMENT_FOR_MULTIPLE_FIELDS = JavaScriptCore.PLUGIN_ID + ".formatter.alignment_for_multiple_fields";//$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option for alignment of parameters in constructor declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.alignment_for_parameters_in_constructor_declaration"
- * - possible values: values returned by <code>createAlignmentValue(boolean, int, int)</code> call
- * - default: createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
- * </pre>
- * @see #createAlignmentValue(boolean, int, int)
- *
- */
- public static final String FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_CONSTRUCTOR_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.alignment_for_parameters_in_constructor_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option for alignment of parameters in method declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.alignment_for_parameters_in_method_declaration"
- * - possible values: values returned by <code>createAlignmentValue(boolean, int, int)</code> call
- * - default: createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
- * </pre>
- * @see #createAlignmentValue(boolean, int, int)
- *
- */
- public static final String FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.alignment_for_parameters_in_method_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option for alignment of selector in method invocation
- * - option id: "org.eclipse.wst.jsdt.core.formatter.alignment_for_selector_in_method_invocation"
- * - possible values: values returned by <code>createAlignmentValue(boolean, int, int)</code> call
- * - default: createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
- * </pre>
- * @see #createAlignmentValue(boolean, int, int)
- *
- */
- public static final String FORMATTER_ALIGNMENT_FOR_SELECTOR_IN_METHOD_INVOCATION = JavaScriptCore.PLUGIN_ID + ".formatter.alignment_for_selector_in_method_invocation"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option for alignment of superclass in type declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.alignment_for_superclass_in_type_declaration"
- * - possible values: values returned by <code>createAlignmentValue(boolean, int, int)</code> call
- * - default: createAlignmentValue(false, WRAP_NEXT_SHIFTED, INDENT_DEFAULT)
- * </pre>
- * @see #createAlignmentValue(boolean, int, int)
- *
- */
- public static final String FORMATTER_ALIGNMENT_FOR_SUPERCLASS_IN_TYPE_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.alignment_for_superclass_in_type_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option for alignment of superinterfaces in enum declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration"
- * - possible values: values returned by <code>createAlignmentValue(boolean, int, int)</code> call
- * - default: createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
- * </pre>
- * @see #createAlignmentValue(boolean, int, int)
- *
- */
- public static final String FORMATTER_ALIGNMENT_FOR_SUPERINTERFACES_IN_ENUM_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.alignment_for_superinterfaces_in_enum_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option for alignment of superinterfaces in type declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.alignment_for_superinterfaces_in_type_declaration"
- * - possible values: values returned by <code>createAlignmentValue(boolean, int, int)</code> call
- * - default: createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
- * </pre>
- * @see #createAlignmentValue(boolean, int, int)
- *
- */
- public static final String FORMATTER_ALIGNMENT_FOR_SUPERINTERFACES_IN_TYPE_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.alignment_for_superinterfaces_in_type_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option for alignment of throws clause in constructor declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration"
- * - possible values: values returned by <code>createAlignmentValue(boolean, int, int)</code> call
- * - default: createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
- * </pre>
- * @see #createAlignmentValue(boolean, int, int)
- *
- */
- public static final String FORMATTER_ALIGNMENT_FOR_THROWS_CLAUSE_IN_CONSTRUCTOR_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.alignment_for_throws_clause_in_constructor_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option for alignment of throws clause in method declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.alignment_for_throws_clause_in_method_declaration"
- * - possible values: values returned by <code>createAlignmentValue(boolean, int, int)</code> call
- * - default: createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
- * </pre>
- * @see #createAlignmentValue(boolean, int, int)
- *
- */
- public static final String FORMATTER_ALIGNMENT_FOR_THROWS_CLAUSE_IN_METHOD_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.alignment_for_throws_clause_in_method_declaration"; //$NON-NLS-1$
-
- /**
- * <pre>
- * FORMATTER / Option to add blank lines after the imports declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.blank_lines_after_imports"
- * - possible values: "&lt;n&gt;", where n is zero or a positive integer
- * - default: "0"
- * </pre>
- *
- */
- public static final String FORMATTER_BLANK_LINES_AFTER_IMPORTS = JavaScriptCore.PLUGIN_ID + ".formatter.blank_lines_after_imports"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to add blank lines after the package declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.blank_lines_after_package"
- * - possible values: "&lt;n&gt;", where n is zero or a positive integer
- * - default: "0"
- * </pre>
- *
- */
- public static final String FORMATTER_BLANK_LINES_AFTER_PACKAGE = JavaScriptCore.PLUGIN_ID + ".formatter.blank_lines_after_package"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to add blank lines at the beginning of the method body
- * - option id: "org.eclipse.wst.jsdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body"
- * - possible values: "&lt;n&gt;", where n is zero or a positive integer
- * - default: "0"
- * </pre>
- *
- */
- public static final String FORMATTER_BLANK_LINES_AT_BEGINNING_OF_METHOD_BODY = JavaScriptCore.PLUGIN_ID + ".formatter.number_of_blank_lines_at_beginning_of_method_body"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to add blank lines before a field declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.blank_lines_before_field"
- * - possible values: "&lt;n&gt;", where n is zero or a positive integer
- * - default: "0"
- * </pre>
- *
- */
- public static final String FORMATTER_BLANK_LINES_BEFORE_FIELD = JavaScriptCore.PLUGIN_ID + ".formatter.blank_lines_before_field"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to add blank lines before the first class body declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.blank_lines_before_first_class_body_declaration"
- * - possible values: "&lt;n&gt;", where n is zero or a positive integer
- * - default: "0"
- * </pre>
- *
- */
- public static final String FORMATTER_BLANK_LINES_BEFORE_FIRST_CLASS_BODY_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.blank_lines_before_first_class_body_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to add blank lines before the imports declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.blank_lines_before_imports"
- * - possible values: "&lt;n&gt;", where n is zero or a positive integer
- * - default: "0"
- * </pre>
- *
- */
- public static final String FORMATTER_BLANK_LINES_BEFORE_IMPORTS = JavaScriptCore.PLUGIN_ID + ".formatter.blank_lines_before_imports"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to add blank lines before a member type declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.blank_lines_before_member_type"
- * - possible values: "&lt;n&gt;", where n is zero or a positive integer
- * - default: "0"
- * </pre>
- *
- */
- public static final String FORMATTER_BLANK_LINES_BEFORE_MEMBER_TYPE = JavaScriptCore.PLUGIN_ID + ".formatter.blank_lines_before_member_type"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to add blank lines before a method declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.blank_lines_before_method"
- * - possible values: "&lt;n&gt;", where n is zero or a positive integer
- * - default: "0"
- * </pre>
- *
- */
- public static final String FORMATTER_BLANK_LINES_BEFORE_METHOD = JavaScriptCore.PLUGIN_ID + ".formatter.blank_lines_before_method"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to add blank lines before a new chunk
- * - option id: "org.eclipse.wst.jsdt.core.formatter.blank_lines_before_new_chunk"
- * - possible values: "&lt;n&gt;", where n is zero or a positive integer
- * - default: "0"
- * </pre>
- *
- */
- public static final String FORMATTER_BLANK_LINES_BEFORE_NEW_CHUNK = JavaScriptCore.PLUGIN_ID + ".formatter.blank_lines_before_new_chunk"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to add blank lines before the package declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.blank_lines_before_package"
- * - possible values: "&lt;n&gt;", where n is zero or a positive integer
- * - default: "0"
- * </pre>
- *
- */
- public static final String FORMATTER_BLANK_LINES_BEFORE_PACKAGE = JavaScriptCore.PLUGIN_ID + ".formatter.blank_lines_before_package"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to add blank lines between import groups
- * - option id: "org.eclipse.wst.jsdt.core.formatter.blank_lines_between_import_groups"
- * - possible values: "&lt;n&gt;", where n is zero or a positive integer
- * - default: "1"
- * </pre>
- * Note: Import groups are defined once "Organize Import" operation has been executed. The code formatter itself
- * doesn't define the import groups.
- *
- *
- */
- public static final String FORMATTER_BLANK_LINES_BETWEEN_IMPORT_GROUPS = JavaScriptCore.PLUGIN_ID + ".formatter.blank_lines_between_import_groups"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to add blank lines between type declarations
- * - option id: "org.eclipse.wst.jsdt.core.formatter.blank_lines_between_type_declarations"
- * - possible values: "&lt;n&gt;", where n is zero or a positive integer
- * - default: "0"
- * </pre>
- *
- */
- public static final String FORMATTER_BLANK_LINES_BETWEEN_TYPE_DECLARATIONS = JavaScriptCore.PLUGIN_ID + ".formatter.blank_lines_between_type_declarations"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to position the braces of an annotation type declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.brace_position_for_annotation_type_declaration"
- * - possible values: { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
- * - default: END_OF_LINE
- * </pre>
- * @see #END_OF_LINE
- * @see #NEXT_LINE
- * @see #NEXT_LINE_SHIFTED
- * @see #NEXT_LINE_ON_WRAP
- *
- */
- public static final String FORMATTER_BRACE_POSITION_FOR_ANNOTATION_TYPE_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.brace_position_for_annotation_type_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to position the braces of an anonymous type declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.brace_position_for_anonymous_type_declaration"
- * - possible values: { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
- * - default: END_OF_LINE
- * </pre>
- * @see #END_OF_LINE
- * @see #NEXT_LINE
- * @see #NEXT_LINE_SHIFTED
- * @see #NEXT_LINE_ON_WRAP
- *
- */
- public static final String FORMATTER_BRACE_POSITION_FOR_ANONYMOUS_TYPE_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.brace_position_for_anonymous_type_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to position the braces of an array initializer
- * - option id: "org.eclipse.wst.jsdt.core.formatter.brace_position_for_array_initializer"
- * - possible values: { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
- * - default: END_OF_LINE
- * </pre>
- * @see #END_OF_LINE
- * @see #NEXT_LINE
- * @see #NEXT_LINE_SHIFTED
- * @see #NEXT_LINE_ON_WRAP
- *
- */
- public static final String FORMATTER_BRACE_POSITION_FOR_ARRAY_INITIALIZER = JavaScriptCore.PLUGIN_ID + ".formatter.brace_position_for_array_initializer"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to position the braces of an object literal initializer
- * - option id: "org.eclipse.wst.jsdt.core.formatter.brace_position_for_objlit_initializer"
- * - possible values: { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
- * - default: END_OF_LINE
- * </pre>
- * @see #END_OF_LINE
- * @see #NEXT_LINE
- * @see #NEXT_LINE_SHIFTED
- * @see #NEXT_LINE_ON_WRAP
- *
- */
- public static final String FORMATTER_BRACE_POSITION_FOR_OBJLIT_INITIALIZER = JavaScriptCore.PLUGIN_ID + ".formatter.brace_position_for_objlit_initializer"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to position the braces of a block
- * - option id: "org.eclipse.wst.jsdt.core.formatter.brace_position_for_block"
- * - possible values: { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
- * - default: END_OF_LINE
- * </pre>
- * @see #END_OF_LINE
- * @see #NEXT_LINE
- * @see #NEXT_LINE_SHIFTED
- * @see #NEXT_LINE_ON_WRAP
- *
- */
- public static final String FORMATTER_BRACE_POSITION_FOR_BLOCK = JavaScriptCore.PLUGIN_ID + ".formatter.brace_position_for_block"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to position the braces of a block in a case statement when the block is the first statement following
- * the case
- * - option id: "org.eclipse.wst.jsdt.core.formatter.brace_position_for_block_in_case"
- * - possible values: { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
- * - default: END_OF_LINE
- * </pre>
- * @see #END_OF_LINE
- * @see #NEXT_LINE
- * @see #NEXT_LINE_SHIFTED
- * @see #NEXT_LINE_ON_WRAP
- *
- */
- public static final String FORMATTER_BRACE_POSITION_FOR_BLOCK_IN_CASE = JavaScriptCore.PLUGIN_ID + ".formatter.brace_position_for_block_in_case"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to position the braces of a constructor declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.brace_position_for_constructor_declaration"
- * - possible values: { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
- * - default: END_OF_LINE
- * </pre>
- * @see #END_OF_LINE
- * @see #NEXT_LINE
- * @see #NEXT_LINE_SHIFTED
- * @see #NEXT_LINE_ON_WRAP
- *
- */
- public static final String FORMATTER_BRACE_POSITION_FOR_CONSTRUCTOR_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.brace_position_for_constructor_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to position the braces of an enum constant
- * - option id: "org.eclipse.wst.jsdt.core.formatter.brace_position_for_enum_constant"
- * - possible values: { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
- * - default: END_OF_LINE
- * </pre>
- * @see #END_OF_LINE
- * @see #NEXT_LINE
- * @see #NEXT_LINE_SHIFTED
- * @see #NEXT_LINE_ON_WRAP
- *
- */
- public static final String FORMATTER_BRACE_POSITION_FOR_ENUM_CONSTANT = JavaScriptCore.PLUGIN_ID + ".formatter.brace_position_for_enum_constant"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to position the braces of an enum declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.brace_position_for_enum_declaration"
- * - possible values: { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
- * - default: END_OF_LINE
- * </pre>
- * @see #END_OF_LINE
- * @see #NEXT_LINE
- * @see #NEXT_LINE_SHIFTED
- * @see #NEXT_LINE_ON_WRAP
- *
- */
- public static final String FORMATTER_BRACE_POSITION_FOR_ENUM_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.brace_position_for_enum_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to position the braces of a method declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.brace_position_for_method_declaration"
- * - possible values: { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
- * - default: END_OF_LINE
- * </pre>
- * @see #END_OF_LINE
- * @see #NEXT_LINE
- * @see #NEXT_LINE_SHIFTED
- * @see #NEXT_LINE_ON_WRAP
- *
- */
- public static final String FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.brace_position_for_method_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to position the braces of a switch statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.brace_position_for_switch"
- * - possible values: { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
- * - default: END_OF_LINE
- * </pre>
- * @see #END_OF_LINE
- * @see #NEXT_LINE
- * @see #NEXT_LINE_SHIFTED
- * @see #NEXT_LINE_ON_WRAP
- *
- */
- public static final String FORMATTER_BRACE_POSITION_FOR_SWITCH = JavaScriptCore.PLUGIN_ID + ".formatter.brace_position_for_switch"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to position the braces of a type declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.brace_position_for_type_declaration"
- * - possible values: { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
- * - default: END_OF_LINE
- * </pre>
- * @see #END_OF_LINE
- * @see #NEXT_LINE
- * @see #NEXT_LINE_SHIFTED
- * @see #NEXT_LINE_ON_WRAP
- *
- */
- public static final String FORMATTER_BRACE_POSITION_FOR_TYPE_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.brace_position_for_type_declaration"; //$NON-NLS-1$
-
- /**
- * <pre>
- * FORMATTER / Option to control whether blank lines are cleared inside comments
- * - option id: "org.eclipse.wst.jsdt.core.formatter.comment.clear_blank_lines"
- * - possible values: { TRUE, FALSE }
- * - default: FALSE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- *
- * @deprecated Use {@link #FORMATTER_COMMENT_CLEAR_BLANK_LINES_IN_BLOCK_COMMENT} and {@link #FORMATTER_COMMENT_CLEAR_BLANK_LINES_IN_JAVADOC_COMMENT}
- */
- public final static String FORMATTER_COMMENT_CLEAR_BLANK_LINES = "org.eclipse.wst.jsdt.core.formatter.comment.clear_blank_lines"; //$NON-NLS-1$
-
- /**
- * <pre>
- * FORMATTER / Option to control whether blank lines are cleared inside jsdoc comments
- * - option id: "org.eclipse.wst.jsdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment"
- * - possible values: { TRUE, FALSE }
- * - default: FALSE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- *
- */
- public final static String FORMATTER_COMMENT_CLEAR_BLANK_LINES_IN_JAVADOC_COMMENT = "org.eclipse.wst.jsdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment"; //$NON-NLS-1$
-
- /**
- * <pre>
- * FORMATTER / Option to control whether blank lines are cleared inside block comments
- * - option id: "org.eclipse.wst.jsdt.core.formatter.comment.clear_blank_lines_in_block_comment"
- * - possible values: { TRUE, FALSE }
- * - default: FALSE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- *
- */
- public final static String FORMATTER_COMMENT_CLEAR_BLANK_LINES_IN_BLOCK_COMMENT = "org.eclipse.wst.jsdt.core.formatter.comment.clear_blank_lines_in_block_comment"; //$NON-NLS-1$
-
- /**
- * <pre>
- * FORMATTER / Option to control whether comments are formatted
- * - option id: "org.eclipse.wst.jsdt.core.formatter.comment.format_comments"
- * - possible values: { TRUE, FALSE }
- * - default: TRUE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- *
- * @deprecated Use multiple settings for each kind of comments. See {@link #FORMATTER_COMMENT_FORMAT_BLOCK_COMMENT},
- * {@link #FORMATTER_COMMENT_FORMAT_JAVADOC_COMMENT} and {@link #FORMATTER_COMMENT_FORMAT_LINE_COMMENT}.
- */
- public final static String FORMATTER_COMMENT_FORMAT = "org.eclipse.wst.jsdt.core.formatter.comment.format_comments"; //$NON-NLS-1$
-
- /**
- * <pre>
- * FORMATTER / Option to control whether single line comments are formatted
- * - option id: "org.eclipse.wst.jsdt.core.formatter.comment.format_line_comments"
- * - possible values: { TRUE, FALSE }
- * - default: TRUE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- *
- */
- public final static String FORMATTER_COMMENT_FORMAT_LINE_COMMENT = "org.eclipse.wst.jsdt.core.formatter.comment.format_line_comments"; //$NON-NLS-1$
-
- /**
- * <pre>
- * FORMATTER / Option to control whether multiple lines comments are formatted
- * - option id: "org.eclipse.wst.jsdt.core.formatter.comment.format_block_comments"
- * - possible values: { TRUE, FALSE }
- * - default: TRUE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- *
- */
- public final static String FORMATTER_COMMENT_FORMAT_BLOCK_COMMENT = "org.eclipse.wst.jsdt.core.formatter.comment.format_block_comments"; //$NON-NLS-1$
-
- /**
- * <pre>
- * FORMATTER / Option to control whether jsdoc comments are formatted
- * - option id: "org.eclipse.wst.jsdt.core.formatter.comment.format_javadoc_comments"
- * - possible values: { TRUE, FALSE }
- * - default: TRUE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- *
- */
- public final static String FORMATTER_COMMENT_FORMAT_JAVADOC_COMMENT = "org.eclipse.wst.jsdt.core.formatter.comment.format_javadoc_comments"; //$NON-NLS-1$
-
- /**
- * <pre>
- * FORMATTER / Option to control whether the header comment of a JavaScript source file is formatted
- * - option id: "org.eclipse.wst.jsdt.core.formatter.comment.format_header"
- * - possible values: { TRUE, FALSE }
- * - default: FALSE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- *
- */
- public final static String FORMATTER_COMMENT_FORMAT_HEADER = "org.eclipse.wst.jsdt.core.formatter.comment.format_header"; //$NON-NLS-1$
-
- /**
- * <pre>
- * FORMATTER / Option to control whether HTML tags are formatted.
- * - option id: "org.eclipse.wst.jsdt.core.formatter.comment.format_html"
- * - possible values: { TRUE, FALSE }
- * - default: TRUE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- *
- */
- public final static String FORMATTER_COMMENT_FORMAT_HTML = "org.eclipse.wst.jsdt.core.formatter.comment.format_html"; //$NON-NLS-1$
-
- /**
- * <pre>
- * FORMATTER / Option to control whether code snippets are formatted in comments
- * - option id: "org.eclipse.wst.jsdt.core.formatter.comment.format_source_code"
- * - possible values: { TRUE, FALSE }
- * - default: TRUE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- *
- */
- public final static String FORMATTER_COMMENT_FORMAT_SOURCE = "org.eclipse.wst.jsdt.core.formatter.comment.format_source_code"; //$NON-NLS-1$
-
- /**
- * <pre>
- * FORMATTER / Option to control whether description of jsdoc parameters are indented
- * - option id: "org.eclipse.wst.jsdt.core.formatter.comment.indent_parameter_description"
- * - possible values: { TRUE, FALSE }
- * - default: TRUE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- *
- */
- public final static String FORMATTER_COMMENT_INDENT_PARAMETER_DESCRIPTION = "org.eclipse.wst.jsdt.core.formatter.comment.indent_parameter_description"; //$NON-NLS-1$
-
- /**
- * <pre>
- * FORMATTER / Option to control whether jsdoc root tags are indented.
- * - option id: "org.eclipse.wst.jsdt.core.formatter.comment.indent_root_tags"
- * - possible values: { TRUE, FALSE }
- * - default: TRUE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- *
- */
- public final static String FORMATTER_COMMENT_INDENT_ROOT_TAGS = "org.eclipse.wst.jsdt.core.formatter.comment.indent_root_tags"; //$NON-NLS-1$
-
- /**
- * <pre>
- * FORMATTER / Option to insert an empty line before the jsdoc root tag block
- * - option id: "org.eclipse.wst.jsdt.core.formatter.comment.insert_new_line_before_root_tags"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public final static String FORMATTER_COMMENT_INSERT_EMPTY_LINE_BEFORE_ROOT_TAGS = "org.eclipse.wst.jsdt.core.formatter.comment.insert_new_line_before_root_tags"; //$NON-NLS-1$
-
- /**
- * <pre>
- * FORMATTER / Option to insert a new line after jsdoc root tag parameters
- * - option id: "org.eclipse.wst.jsdt.core.formatter.comment.insert_new_line_for_parameter"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public final static String FORMATTER_COMMENT_INSERT_NEW_LINE_FOR_PARAMETER = "org.eclipse.wst.jsdt.core.formatter.comment.insert_new_line_for_parameter"; //$NON-NLS-1$
-
- /**
- * <pre>
- * FORMATTER / Option to specify the line length for comments.
- * - option id: "org.eclipse.wst.jsdt.core.formatter.comment.line_length"
- * - possible values: "&lt;n&gt;", where n is zero or a positive integer
- * - default: "80"
- * </pre>
- *
- */
- public final static String FORMATTER_COMMENT_LINE_LENGTH = "org.eclipse.wst.jsdt.core.formatter.comment.line_length"; //$NON-NLS-1$
-
- /**
- * <pre>
- * FORMATTER / Option to compact else/if
- * - option id: "org.eclipse.wst.jsdt.core.formatter.compact_else_if"
- * - possible values: { TRUE, FALSE }
- * - default: TRUE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String FORMATTER_COMPACT_ELSE_IF = JavaScriptCore.PLUGIN_ID + ".formatter.compact_else_if"; //$NON-NLS-1$
-
- /**
- * <pre>
- * FORMATTER / Option to set the continuation indentation
- * - option id: "org.eclipse.wst.jsdt.core.formatter.continuation_indentation"
- * - possible values: "&lt;n&gt;", where n is zero or a positive integer
- * - default: "2"
- * </pre>
- *
- */
- public static final String FORMATTER_CONTINUATION_INDENTATION = JavaScriptCore.PLUGIN_ID + ".formatter.continuation_indentation"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to set the continuation indentation inside array initializer
- * - option id: "org.eclipse.wst.jsdt.core.formatter.continuation_indentation_for_array_initializer"
- * - possible values: "&lt;n&gt;", where n is zero or a positive integer
- * - default: "2"
- * </pre>
- *
- */
- public static final String FORMATTER_CONTINUATION_INDENTATION_FOR_ARRAY_INITIALIZER = JavaScriptCore.PLUGIN_ID + ".formatter.continuation_indentation_for_array_initializer"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to set the continuation indentation inside object literals initializer
- * - option id: "org.eclipse.wst.jsdt.core.formatter.continuation_indentation_for_objlit_initializer"
- * - possible values: "&lt;n&gt;", where n is zero or a positive integer
- * - default: "1"
- * </pre>
- *
- */
- public static final String FORMATTER_CONTINUATION_INDENTATION_FOR_OBJLIT_INITIALIZER = JavaScriptCore.PLUGIN_ID + ".formatter.continuation_indentation_for_objlit_initializer"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to indent body declarations compare to its enclosing annotation declaration header
- * - option id: "org.eclipse.wst.jsdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header"
- * - possible values: { TRUE, FALSE }
- * - default: TRUE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ANNOTATION_DECLARATION_HEADER = JavaScriptCore.PLUGIN_ID + ".formatter.indent_body_declarations_compare_to_annotation_declaration_header"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to indent body declarations compare to its enclosing enum constant header
- * - option id: "org.eclipse.wst.jsdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header"
- * - possible values: { TRUE, FALSE }
- * - default: TRUE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ENUM_CONSTANT_HEADER = JavaScriptCore.PLUGIN_ID + ".formatter.indent_body_declarations_compare_to_enum_constant_header"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to indent body declarations compare to its enclosing enum declaration header
- * - option id: "org.eclipse.wst.jsdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header"
- * - possible values: { TRUE, FALSE }
- * - default: TRUE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ENUM_DECLARATION_HEADER = JavaScriptCore.PLUGIN_ID + ".formatter.indent_body_declarations_compare_to_enum_declaration_header"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to indent body declarations compare to its enclosing type header
- * - option id: "org.eclipse.wst.jsdt.core.formatter.indent_body_declarations_compare_to_type_header"
- * - possible values: { TRUE, FALSE }
- * - default: TRUE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_TYPE_HEADER = JavaScriptCore.PLUGIN_ID + ".formatter.indent_body_declarations_compare_to_type_header"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to indent breaks compare to cases
- * - option id: "org.eclipse.wst.jsdt.core.formatter.indent_breaks_compare_to_cases"
- * - possible values: { TRUE, FALSE }
- * - default: TRUE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String FORMATTER_INDENT_BREAKS_COMPARE_TO_CASES = JavaScriptCore.PLUGIN_ID + ".formatter.indent_breaks_compare_to_cases"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to indent empty lines
- * - option id: "org.eclipse.wst.jsdt.core.formatter.indent_empty_lines"
- * - possible values: { TRUE, FALSE }
- * - default: FALSE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String FORMATTER_INDENT_EMPTY_LINES = JavaScriptCore.PLUGIN_ID + ".formatter.indent_empty_lines"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to indent statements inside a block
- * - option id: "org.eclipse.wst.jsdt.core.formatter.indent_statements_compare_to_block"
- * - possible values: { TRUE, FALSE }
- * - default: TRUE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BLOCK = JavaScriptCore.PLUGIN_ID + ".formatter.indent_statements_compare_to_block"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to indent statements inside the body of a method or a constructor
- * - option id: "org.eclipse.wst.jsdt.core.formatter.indent_statements_compare_to_body"
- * - possible values: { TRUE, FALSE }
- * - default: TRUE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BODY = JavaScriptCore.PLUGIN_ID + ".formatter.indent_statements_compare_to_body"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to indent switch statements compare to cases
- * - option id: "org.eclipse.wst.jsdt.core.formatter.indent_switchstatements_compare_to_cases"
- * - possible values: { TRUE, FALSE }
- * - default: TRUE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_CASES = JavaScriptCore.PLUGIN_ID + ".formatter.indent_switchstatements_compare_to_cases"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to indent switch statements compare to switch
- * - option id: "org.eclipse.wst.jsdt.core.formatter.indent_switchstatements_compare_to_switch"
- * - possible values: { TRUE, FALSE }
- * - default: TRUE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_SWITCH = JavaScriptCore.PLUGIN_ID + ".formatter.indent_switchstatements_compare_to_switch"; //$NON-NLS-1$
-
- /**
- * <pre>
- * FORMATTER / Option to specify the equivalent number of spaces that represents one indentation
- * - option id: "org.eclipse.wst.jsdt.core.formatter.indentation.size"
- * - possible values: "&lt;n&gt;", where n is zero or a positive integer
- * - default: "4"
- * </pre>
- * <p>This option is used only if the tab char is set to MIXED.
- * </p>
- * @see #FORMATTER_TAB_CHAR
- *
- */
- public static final String FORMATTER_INDENTATION_SIZE = JavaScriptCore.PLUGIN_ID + ".formatter.indentation.size"; //$NON-NLS-1$
-
- /**
- * <pre>
- * FORMATTER / Option to insert a new line after an annotation
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_new_line_after_annotation"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_NEW_LINE_AFTER_ANNOTATION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_new_line_after_annotation";//$NON-NLS-1$
-
- /**
- * <pre>
- * FORMATTER / Option to insert a new line after the opening brace in an array initializer
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_NEW_LINE_AFTER_OPENING_BRACE_IN_ARRAY_INITIALIZER = JavaScriptCore.PLUGIN_ID + ".formatter.insert_new_line_after_opening_brace_in_array_initializer";//$NON-NLS-1$
-
- /**
- * <pre>
- * FORMATTER / Option to insert a new line after the opening brace in an object literal initializer
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_new_line_after_opening_brace_in_objlit_initializer"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_NEW_LINE_AFTER_OPENING_BRACE_IN_OBJLIT_INITIALIZER = JavaScriptCore.PLUGIN_ID + ".formatter.insert_new_line_after_opening_brace_in_objlit_initializer";//$NON-NLS-1$
-
- /**
- * <pre>
- * FORMATTER / Option to insert a new line after each comma in an object literal initializer
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_new_line_after_comma_in_objlit_initializer"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_NEW_LINE_AFTER_COMMA_IN_OBJLIT_INITIALIZER = JavaScriptCore.PLUGIN_ID + ".formatter.insert_new_line_after_comma_in_objlit_initializer";//$NON-NLS-1$
-
- /**
- * <pre>
- * FORMATTER / Option to insert a new line at the end of the current file if missing
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_new_line_at_end_of_file_if_missing"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_NEW_LINE_AT_END_OF_FILE_IF_MISSING = JavaScriptCore.PLUGIN_ID + ".formatter.insert_new_line_at_end_of_file_if_missing";//$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a new line before the catch keyword in try statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_new_line_before_catch_in_try_statement"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_NEW_LINE_BEFORE_CATCH_IN_TRY_STATEMENT = JavaScriptCore.PLUGIN_ID + ".formatter.insert_new_line_before_catch_in_try_statement"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a new line before the closing brace in an array initializer
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_NEW_LINE_BEFORE_CLOSING_BRACE_IN_ARRAY_INITIALIZER = JavaScriptCore.PLUGIN_ID + ".formatter.insert_new_line_before_closing_brace_in_array_initializer";//$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a new line before the closing brace in an object literal initializer
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_new_line_before_closing_brace_in_objlit_initializer"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_NEW_LINE_BEFORE_CLOSING_BRACE_IN_OBJLIT_INITIALIZER = JavaScriptCore.PLUGIN_ID + ".formatter.insert_new_line_before_closing_brace_in_objlit_initializer";//$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a new line before the else keyword in if statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_new_line_before_else_in_if_statement"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_NEW_LINE_BEFORE_ELSE_IN_IF_STATEMENT = JavaScriptCore.PLUGIN_ID + ".formatter.insert_new_line_before_else_in_if_statement"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a new line before the finally keyword in try statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_new_line_before_finally_in_try_statement"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_NEW_LINE_BEFORE_FINALLY_IN_TRY_STATEMENT = JavaScriptCore.PLUGIN_ID + ".formatter.insert_new_line_before_finally_in_try_statement"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a new line before while in do statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_new_line_before_while_in_do_statement"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_NEW_LINE_BEFORE_WHILE_IN_DO_STATEMENT = JavaScriptCore.PLUGIN_ID + ".formatter.insert_new_line_before_while_in_do_statement"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a new line in an empty annotation declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_new_line_in_empty_annotation_declaration"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_NEW_LINE_IN_EMPTY_ANNOTATION_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_new_line_in_empty_annotation_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a new line in an empty anonymous type declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_NEW_LINE_IN_EMPTY_ANONYMOUS_TYPE_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_new_line_in_empty_anonymous_type_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a new line in an empty block
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_new_line_in_empty_block"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_NEW_LINE_IN_EMPTY_BLOCK = JavaScriptCore.PLUGIN_ID + ".formatter.insert_new_line_in_empty_block"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a new line in an empty enum constant
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_new_line_in_empty_enum_constant"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_NEW_LINE_IN_EMPTY_ENUM_CONSTANT = JavaScriptCore.PLUGIN_ID + ".formatter.insert_new_line_in_empty_enum_constant"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a new line in an empty enum declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_new_line_in_empty_enum_declaration"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_NEW_LINE_IN_EMPTY_ENUM_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_new_line_in_empty_enum_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a new line in an empty method body
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_new_line_in_empty_method_body"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_NEW_LINE_IN_EMPTY_METHOD_BODY = JavaScriptCore.PLUGIN_ID + ".formatter.insert_new_line_in_empty_method_body"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a new line in an empty type declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_new_line_in_empty_type_declaration"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_NEW_LINE_IN_EMPTY_TYPE_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_new_line_in_empty_type_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after and in wilcard
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_and_in_type_parameter"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_AND_IN_TYPE_PARAMETER = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_and_in_type_parameter"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after an assignment operator
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_assignment_operator"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_ASSIGNMENT_OPERATOR = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_assignment_operator"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after at in annotation
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_at_in_annotation"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_AT_IN_ANNOTATION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_at_in_annotation"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after at in annotation type declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_at_in_annotation_type_declaration"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_AT_IN_ANNOTATION_TYPE_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_at_in_annotation_type_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after a binary operator
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_binary_operator"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_BINARY_OPERATOR = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_binary_operator"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the closing angle bracket in type arguments
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_CLOSING_ANGLE_BRACKET_IN_TYPE_ARGUMENTS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_closing_angle_bracket_in_type_arguments"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the closing angle bracket in type parameters
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_CLOSING_ANGLE_BRACKET_IN_TYPE_PARAMETERS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_closing_angle_bracket_in_type_parameters"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the closing brace of a block
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_closing_brace_in_block"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_CLOSING_BRACE_IN_BLOCK = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_closing_brace_in_block"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the closing parenthesis of a cast expression
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_closing_paren_in_cast"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_CLOSING_PAREN_IN_CAST = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_closing_paren_in_cast"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the colon in an assert statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_colon_in_assert"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_COLON_IN_ASSERT = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_colon_in_assert"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after colon in a case statement when a opening brace follows the colon
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_colon_in_case"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_COLON_IN_CASE = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_colon_in_case"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the colon in an object initializer expression
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_colon_in_object_initializer"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_COLON_IN_OBJECT_INITIALIZER = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_colon_in_object_initializer"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the colon in a conditional expression
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_colon_in_conditional"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_COLON_IN_CONDITIONAL = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_colon_in_conditional"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after colon in a for statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_colon_in_for"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_COLON_IN_FOR = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_colon_in_for"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the colon in a labeled statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_colon_in_labeled_statement"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_COLON_IN_LABELED_STATEMENT = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_colon_in_labeled_statement"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the comma in an allocation expression
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_comma_in_allocation_expression"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_ALLOCATION_EXPRESSION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_allocation_expression"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the comma in annotation
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_comma_in_annotation"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_ANNOTATION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_annotation"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the comma in an array initializer
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_comma_in_array_initializer"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_ARRAY_INITIALIZER = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_array_initializer"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the comma in the parameters of a constructor declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_CONSTRUCTOR_DECLARATION_PARAMETERS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_constructor_declaration_parameters"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the comma in the exception names in a throws clause of a constructor declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_CONSTRUCTOR_DECLARATION_THROWS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_constructor_declaration_throws"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the comma in the arguments of an enum constant
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_ENUM_CONSTANT_ARGUMENTS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_enum_constant_arguments"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the comma in enum declarations
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_comma_in_enum_declarations"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_ENUM_DECLARATIONS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_enum_declarations"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the comma in the arguments of an explicit constructor call
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_EXPLICIT_CONSTRUCTOR_CALL_ARGUMENTS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_explicitconstructorcall_arguments"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the comma in the increments of a for statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_comma_in_for_increments"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_FOR_INCREMENTS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_for_increments"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the comma in the initializations of a for statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_comma_in_for_inits"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_FOR_INITS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_for_inits"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the comma in the parameters of a method declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_METHOD_DECLARATION_PARAMETERS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_method_declaration_parameters"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the comma in the exception names in a throws clause of a method declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_comma_in_method_declaration_throws"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_METHOD_DECLARATION_THROWS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_method_declaration_throws"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the comma in the arguments of a method invocation
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_METHOD_INVOCATION_ARGUMENTS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_method_invocation_arguments"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the comma in multiple field declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_MULTIPLE_FIELD_DECLARATIONS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_multiple_field_declarations"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the comma in multiple local declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_MULTIPLE_LOCAL_DECLARATIONS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_multiple_local_declarations"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the comma in parameterized type reference
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_PARAMETERIZED_TYPE_REFERENCE = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_parameterized_type_reference"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the comma in superinterfaces names of a type header
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_comma_in_superinterfaces"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_SUPERINTERFACES = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_superinterfaces"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the comma in type arguments
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_comma_in_type_arguments"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_TYPE_ARGUMENTS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_type_arguments"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the comma in type parameters
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_comma_in_type_parameters"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_TYPE_PARAMETERS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_type_parameters"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after ellipsis
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_ellipsis"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_ELLIPSIS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_ellipsis"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the opening angle bracket in parameterized type reference
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_ANGLE_BRACKET_IN_PARAMETERIZED_TYPE_REFERENCE = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference";//$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the opening angle bracket in type arguments
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_ANGLE_BRACKET_IN_TYPE_ARGUMENTS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_opening_angle_bracket_in_type_arguments";//$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the opening angle bracket in type parameters
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_ANGLE_BRACKET_IN_TYPE_PARAMETERS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_opening_angle_bracket_in_type_parameters";//$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the opening brace in an array initializer
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_opening_brace_in_array_initializer"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_BRACE_IN_ARRAY_INITIALIZER = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_opening_brace_in_array_initializer"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the opening bracket inside an array allocation expression
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_BRACKET_IN_ARRAY_ALLOCATION_EXPRESSION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_opening_bracket_in_array_allocation_expression";//$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the opening bracket inside an array reference
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_opening_bracket_in_array_reference"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_BRACKET_IN_ARRAY_REFERENCE = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_opening_bracket_in_array_reference";//$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the opening parenthesis in annotation
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_opening_paren_in_annotation"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_ANNOTATION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_opening_paren_in_annotation"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the opening parenthesis in a cast expression
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_opening_paren_in_cast"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_CAST = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_opening_paren_in_cast"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the opening parenthesis in a catch
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_opening_paren_in_catch"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_CATCH = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_opening_paren_in_catch"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the opening parenthesis in a constructor declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_CONSTRUCTOR_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_opening_paren_in_constructor_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the opening parenthesis in enum constant
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_opening_paren_in_enum_constant"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_ENUM_CONSTANT = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_opening_paren_in_enum_constant"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the opening parenthesis in a for statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_opening_paren_in_for"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_FOR = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_opening_paren_in_for"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the opening parenthesis in an if statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_opening_paren_in_if"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_IF = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_opening_paren_in_if"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the opening parenthesis in a method declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_opening_paren_in_method_declaration"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_METHOD_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_opening_paren_in_method_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the opening parenthesis in a method invocation
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_opening_paren_in_method_invocation"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_METHOD_INVOCATION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_opening_paren_in_method_invocation"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the opening parenthesis in a parenthesized expression
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_PARENTHESIZED_EXPRESSION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_opening_paren_in_parenthesized_expression"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the opening parenthesis in a switch statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_opening_paren_in_switch"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_SWITCH = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_opening_paren_in_switch"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the opening parenthesis in a synchronized statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_opening_paren_in_synchronized"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_SYNCHRONIZED = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_opening_paren_in_synchronized"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after the opening parenthesis in a while statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_opening_paren_in_while"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_WHILE = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_opening_paren_in_while"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after a postfix operator
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_postfix_operator"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_POSTFIX_OPERATOR = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_postfix_operator"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after a prefix operator
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_prefix_operator"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_PREFIX_OPERATOR = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_prefix_operator"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after question mark in a conditional expression
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_question_in_conditional"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_QUESTION_IN_CONDITIONAL = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_question_in_conditional"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after semicolon in a for statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_semicolon_in_for"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_SEMICOLON_IN_FOR = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_semicolon_in_for"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space after an unary operator
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_after_unary_operator"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_AFTER_UNARY_OPERATOR = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_unary_operator"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before an assignment operator
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_assignment_operator"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_ASSIGNMENT_OPERATOR = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_assignment_operator"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before at in annotation type declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_at_in_annotation_type_declaration"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_AT_IN_ANNOTATION_TYPE_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_at_in_annotation_type_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before an binary operator
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_binary_operator"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_BINARY_OPERATOR = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_binary_operator"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the closing angle bracket in parameterized type reference
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_ANGLE_BRACKET_IN_PARAMETERIZED_TYPE_REFERENCE = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the closing angle bracket in type arguments
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_ANGLE_BRACKET_IN_TYPE_ARGUMENTS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_closing_angle_bracket_in_type_arguments"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the closing angle bracket in type parameters
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_ANGLE_BRACKET_IN_TYPE_PARAMETERS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_closing_angle_bracket_in_type_parameters"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the closing brace in an array initializer
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_closing_brace_in_array_initializer"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_BRACE_IN_ARRAY_INITIALIZER = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_closing_brace_in_array_initializer"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the closing bracket in an array allocation expression
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_BRACKET_IN_ARRAY_ALLOCATION_EXPRESSION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_closing_bracket_in_array_allocation_expression";//$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the closing bracket in an array reference
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_closing_bracket_in_array_reference"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_BRACKET_IN_ARRAY_REFERENCE = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_closing_bracket_in_array_reference";//$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the closing parenthesis in annotation
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_closing_paren_in_annotation"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_ANNOTATION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_closing_paren_in_annotation"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the closing parenthesis in a cast expression
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_closing_paren_in_cast"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_CAST = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_closing_paren_in_cast"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the closing parenthesis in a catch
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_closing_paren_in_catch"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_CATCH = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_closing_paren_in_catch"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the closing parenthesis in a constructor declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_CONSTRUCTOR_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_closing_paren_in_constructor_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the closing parenthesis in enum constant
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_closing_paren_in_enum_constant"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_ENUM_CONSTANT = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_closing_paren_in_enum_constant"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the closing parenthesis in a for statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_closing_paren_in_for"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_FOR = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_closing_paren_in_for"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the closing parenthesis in an if statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_closing_paren_in_if"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_IF = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_closing_paren_in_if"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the closing parenthesis in a method declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_closing_paren_in_method_declaration"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_METHOD_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_closing_paren_in_method_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the closing parenthesis in a method invocation
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_closing_paren_in_method_invocation"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_METHOD_INVOCATION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_closing_paren_in_method_invocation"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the closing parenthesis in a parenthesized expression
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_PARENTHESIZED_EXPRESSION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_closing_paren_in_parenthesized_expression"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the closing parenthesis in a switch statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_closing_paren_in_switch"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_SWITCH = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_closing_paren_in_switch"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the closing parenthesis in a synchronized statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_closing_paren_in_synchronized"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_SYNCHRONIZED = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_closing_paren_in_synchronized"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the closing parenthesis in a while statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_closing_paren_in_while"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_WHILE = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_closing_paren_in_while"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before colon in an assert statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_colon_in_assert"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_ASSERT = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_colon_in_assert"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before colon in a case statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_colon_in_case"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_CASE = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_colon_in_case"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before colon in an object initializer expression
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_colon_in_object_initializer"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_OBJECT_INITIALIZER = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_colon_in_object_initializer"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before colon in a conditional expression
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_colon_in_conditional"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_CONDITIONAL = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_colon_in_conditional"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before colon in a default statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_colon_in_default"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_DEFAULT = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_colon_in_default"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before colon in a for statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_colon_in_for"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_FOR = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_colon_in_for"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before colon in a labeled statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_colon_in_labeled_statement"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_LABELED_STATEMENT = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_colon_in_labeled_statement"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before comma in an allocation expression
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_comma_in_allocation_expression"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_ALLOCATION_EXPRESSION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_allocation_expression"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before comma in annotation
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_comma_in_annotation"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_ANNOTATION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_annotation"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before comma in an array initializer
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_comma_in_array_initializer"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_ARRAY_INITIALIZER = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_array_initializer"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before comma in the parameters of a constructor declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_CONSTRUCTOR_DECLARATION_PARAMETERS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_constructor_declaration_parameters"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before comma in the exception names of the throws clause of a constructor declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_CONSTRUCTOR_DECLARATION_THROWS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_constructor_declaration_throws"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before comma in the arguments of enum constant
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_ENUM_CONSTANT_ARGUMENTS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_enum_constant_arguments"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before comma in enum declarations
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_comma_in_enum_declarations"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_ENUM_DECLARATIONS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_enum_declarations"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before comma in the arguments of an explicit constructor call
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_EXPLICIT_CONSTRUCTOR_CALL_ARGUMENTS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_explicitconstructorcall_arguments"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before comma in the increments of a for statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_comma_in_for_increments"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_FOR_INCREMENTS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_for_increments"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before comma in the initializations of a for statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_comma_in_for_inits"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_FOR_INITS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_for_inits"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before comma in the parameters of a method declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_METHOD_DECLARATION_PARAMETERS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_method_declaration_parameters"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before comma in the exception names of the throws clause of a method declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_comma_in_method_declaration_throws"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_METHOD_DECLARATION_THROWS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_method_declaration_throws"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before comma in the arguments of a method invocation
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_METHOD_INVOCATION_ARGUMENTS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_method_invocation_arguments"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before comma in a multiple field declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_MULTIPLE_FIELD_DECLARATIONS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_multiple_field_declarations"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before comma in a multiple local declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_MULTIPLE_LOCAL_DECLARATIONS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_multiple_local_declarations"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before comma in parameterized type reference
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_PARAMETERIZED_TYPE_REFERENCE = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_parameterized_type_reference"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before comma in the superinterfaces names in a type header
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_comma_in_superinterfaces"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_SUPERINTERFACES = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_superinterfaces"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before comma in type arguments
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_comma_in_type_arguments"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_TYPE_ARGUMENTS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_type_arguments"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before comma in type parameters
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_comma_in_type_parameters"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_TYPE_PARAMETERS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_type_parameters"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before ellipsis
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_ellipsis"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_ELLIPSIS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_ellipsis"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the opening angle bracket in parameterized type reference
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_ANGLE_BRACKET_IN_PARAMETERIZED_TYPE_REFERENCE = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the opening angle bracket in type arguments
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_ANGLE_BRACKET_IN_TYPE_ARGUMENTS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_opening_angle_bracket_in_type_arguments"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the opening angle bracket in type parameters
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_ANGLE_BRACKET_IN_TYPE_PARAMETERS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_opening_angle_bracket_in_type_parameters"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the opening brace in an annotation type declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_ANNOTATION_TYPE_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_opening_brace_in_annotation_type_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the opening brace in an anonymous type declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_ANONYMOUS_TYPE_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_opening_brace_in_anonymous_type_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the opening brace in an array initializer
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_opening_brace_in_array_initializer"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- * @deprecated No longer used internally. Will be removed in future release.
- * Preference is overshadowed by {@link #FORMATTER_INSERT_SPACE_AFTER_ASSIGNMENT_OPERATOR}
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_ARRAY_INITIALIZER = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_opening_brace_in_array_initializer"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the opening brace in a block
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_opening_brace_in_block"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_BLOCK = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_opening_brace_in_block"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the opening brace in a constructor declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_CONSTRUCTOR_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_opening_brace_in_constructor_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the opening brace in an enum constant
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_opening_brace_in_enum_constant"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_ENUM_CONSTANT = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_opening_brace_in_enum_constant"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the opening brace in an enum declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_ENUM_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_opening_brace_in_enum_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the opening brace in a method declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_opening_brace_in_method_declaration"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_METHOD_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_opening_brace_in_method_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the opening brace in a switch statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_opening_brace_in_switch"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_SWITCH = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_opening_brace_in_switch"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the opening brace in a type declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_opening_brace_in_type_declaration"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_TYPE_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_opening_brace_in_type_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the opening bracket in an array allocation expression
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACKET_IN_ARRAY_ALLOCATION_EXPRESSION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_opening_bracket_in_array_allocation_expression";//$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the opening bracket in an array reference
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_opening_bracket_in_array_reference"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACKET_IN_ARRAY_REFERENCE = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_opening_bracket_in_array_reference";//$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the opening bracket in an array type reference
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACKET_IN_ARRAY_TYPE_REFERENCE = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_opening_bracket_in_array_type_reference"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the opening parenthesis in annotation
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_opening_paren_in_annotation"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_ANNOTATION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_opening_paren_in_annotation"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the opening parenthesis in annotation type member declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_ANNOTATION_TYPE_MEMBER_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the opening parenthesis in a catch
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_opening_paren_in_catch"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_CATCH = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_opening_paren_in_catch"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the opening parenthesis in a constructor declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_CONSTRUCTOR_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_opening_paren_in_constructor_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the opening parenthesis in enum constant
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_opening_paren_in_enum_constant"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_ENUM_CONSTANT = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_opening_paren_in_enum_constant"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the opening parenthesis in a for statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_opening_paren_in_for"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_FOR = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_opening_paren_in_for"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the opening parenthesis in an if statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_opening_paren_in_if"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_IF = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_opening_paren_in_if"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the opening parenthesis in a method declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_opening_paren_in_method_declaration"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_METHOD_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_opening_paren_in_method_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the opening parenthesis in a method invocation
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_opening_paren_in_method_invocation"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_METHOD_INVOCATION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_opening_paren_in_method_invocation"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the opening parenthesis in a parenthesized expression
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_PARENTHESIZED_EXPRESSION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_opening_paren_in_parenthesized_expression"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the opening parenthesis in a switch statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_opening_paren_in_switch"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_SWITCH = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_opening_paren_in_switch"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the opening parenthesis in a synchronized statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_opening_paren_in_synchronized"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_SYNCHRONIZED = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_opening_paren_in_synchronized"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before the opening parenthesis in a while statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_opening_paren_in_while"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_WHILE = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_opening_paren_in_while"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before parenthesized expression in return statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_parenthesized_expression_in_return"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- *
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_PARENTHESIZED_EXPRESSION_IN_RETURN = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_parenthesized_expression_in_return"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before parenthesized expression in throw statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_parenthesized_expression_in_throw"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- *
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_PARENTHESIZED_EXPRESSION_IN_THROW = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_parenthesized_expression_in_throw"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before a postfix operator
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_postfix_operator"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_POSTFIX_OPERATOR = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_postfix_operator"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before a prefix operator
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_prefix_operator"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_PREFIX_OPERATOR = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_prefix_operator"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before question mark in a conditional expression
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_question_in_conditional"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_QUESTION_IN_CONDITIONAL = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_question_in_conditional"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before semicolon
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_semicolon"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_SEMICOLON = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_semicolon"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before semicolon in for statement
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_semicolon_in_for"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_SEMICOLON_IN_FOR = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_semicolon_in_for"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space before unary operator
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_before_unary_operator"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BEFORE_UNARY_OPERATOR = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_unary_operator"; //$NON-NLS-1$
-
- /**
- * <pre>
- * FORMATTER / Option to insert a space between brackets in an array type reference
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_between_brackets_in_array_type_reference"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BETWEEN_BRACKETS_IN_ARRAY_TYPE_REFERENCE = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_between_brackets_in_array_type_reference"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space between empty braces in an array initializer
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_between_empty_braces_in_array_initializer"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_BRACES_IN_ARRAY_INITIALIZER = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_between_empty_braces_in_array_initializer"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space between empty brackets in an array allocation expression
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_BRACKETS_IN_ARRAY_ALLOCATION_EXPRESSION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_between_empty_brackets_in_array_allocation_expression"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space between empty parenthesis in an annotation type member declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_ANNOTATION_TYPE_MEMBER_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space between empty parenthesis in a constructor declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_CONSTRUCTOR_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_between_empty_parens_in_constructor_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space between empty parenthesis in enum constant
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_between_empty_parens_in_enum_constant"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_ENUM_CONSTANT = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_between_empty_parens_in_enum_constant"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space between empty parenthesis in a method declaration
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_between_empty_parens_in_method_declaration"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_METHOD_DECLARATION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_between_empty_parens_in_method_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to insert a space between empty parenthesis in a method invocation
- * - option id: "org.eclipse.wst.jsdt.core.formatter.insert_space_between_empty_parens_in_method_invocation"
- * - possible values: { INSERT, DO_NOT_INSERT }
- * - default: DO_NOT_INSERT
- * </pre>
- * @see JavaScriptCore#INSERT
- * @see JavaScriptCore#DO_NOT_INSERT
- *
- */
- public static final String FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_METHOD_INVOCATION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_between_empty_parens_in_method_invocation"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to keep else statement on the same line
- * - option id: "org.eclipse.wst.jsdt.core.formatter.keep_else_statement_on_same_line"
- * - possible values: { TRUE, FALSE }
- * - default: FALSE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String FORMATTER_KEEP_ELSE_STATEMENT_ON_SAME_LINE = JavaScriptCore.PLUGIN_ID + ".formatter.keep_else_statement_on_same_line"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to keep empty array initializer one one line
- * - option id: "org.eclipse.wst.jsdt.core.formatter.keep_empty_array_initializer_on_one_line"
- * - possible values: { TRUE, FALSE }
- * - default: FALSE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String FORMATTER_KEEP_EMPTY_ARRAY_INITIALIZER_ON_ONE_LINE = JavaScriptCore.PLUGIN_ID + ".formatter.keep_empty_array_initializer_on_one_line"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to keep empty object literal initializer one one line
- * - option id: "org.eclipse.wst.jsdt.core.formatter.keep_empty_objlit_initializer_on_one_line"
- * - possible values: { TRUE, FALSE }
- * - default: FALSE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String FORMATTER_KEEP_EMPTY_OBJLIT_INITIALIZER_ON_ONE_LINE = JavaScriptCore.PLUGIN_ID + ".formatter.keep_empty_objlit_initializer_on_one_line"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to keep guardian clause on one line
- * - option id: "org.eclipse.wst.jsdt.core.formatter.format_guardian_clause_on_one_line"
- * - possible values: { TRUE, FALSE }
- * - default: FALSE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String FORMATTER_KEEP_GUARDIAN_CLAUSE_ON_ONE_LINE = JavaScriptCore.PLUGIN_ID + ".formatter.format_guardian_clause_on_one_line"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to keep simple if statement on the one line
- * - option id: "org.eclipse.wst.jsdt.core.formatter.keep_imple_if_on_one_line"
- * - possible values: { TRUE, FALSE }
- * - default: FALSE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String FORMATTER_KEEP_SIMPLE_IF_ON_ONE_LINE = JavaScriptCore.PLUGIN_ID + ".formatter.keep_imple_if_on_one_line"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to keep then statement on the same line
- * - option id: "org.eclipse.wst.jsdt.core.formatter.keep_then_statement_on_same_line"
- * - possible values: { TRUE, FALSE }
- * - default: FALSE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String FORMATTER_KEEP_THEN_STATEMENT_ON_SAME_LINE = JavaScriptCore.PLUGIN_ID + ".formatter.keep_then_statement_on_same_line";//$NON-NLS-1$
-
- /**
- * <pre>
- * FORMATTER / Option to specify the length of the page. Beyond this length, the formatter will try to split the code
- * - option id: "org.eclipse.wst.jsdt.core.formatter.lineSplit"
- * - possible values: "&lt;n&gt;", where n is zero or a positive integer
- * - default: "80"
- * </pre>
- *
- */
- public static final String FORMATTER_LINE_SPLIT = JavaScriptCore.PLUGIN_ID + ".formatter.lineSplit"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to indent block comments that start on the first column
- * - option id: "org.eclipse.wst.jsdt.core.formatter.formatter.never_indent_block_comments_on_first_column"
- * - possible values: { TRUE, FALSE }
- * - default: FALSE
- * </pre>
- * Note that this option is ignored if the formatter is created with the mode {@link org.eclipse.wst.jsdt.core.ToolFactory#M_FORMAT_NEW}.
- * @see #TRUE
- * @see #FALSE
- * @see org.eclipse.wst.jsdt.core.ToolFactory#createCodeFormatter(Map, int)
- *
- */
- public static final String FORMATTER_NEVER_INDENT_BLOCK_COMMENTS_ON_FIRST_COLUMN = JavaScriptCore.PLUGIN_ID + ".formatter.never_indent_block_comments_on_first_column"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to indent line comments that start on the first column
- * - option id: "org.eclipse.wst.jsdt.core.formatter.formatter.never_indent_line_comments_on_first_column"
- * - possible values: { TRUE, FALSE }
- * - default: FALSE
- * </pre>
- * Note that this option is ignored if the formatter is created with the mode {@link org.eclipse.wst.jsdt.core.ToolFactory#M_FORMAT_NEW}.
- * @see #TRUE
- * @see #FALSE
- * @see org.eclipse.wst.jsdt.core.ToolFactory#createCodeFormatter(Map, int)
- *
- */
- public static final String FORMATTER_NEVER_INDENT_LINE_COMMENTS_ON_FIRST_COLUMN = JavaScriptCore.PLUGIN_ID + ".formatter.never_indent_line_comments_on_first_column"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to specify the number of empty lines to preserve
- * - option id: "org.eclipse.wst.jsdt.core.formatter.number_of_empty_lines_to_preserve"
- * - possible values: "&lt;n&gt;", where n is zero or a positive integer
- * - default: "0"
- * </pre>
- *
- */
- public static final String FORMATTER_NUMBER_OF_EMPTY_LINES_TO_PRESERVE = JavaScriptCore.PLUGIN_ID + ".formatter.number_of_empty_lines_to_preserve"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to specify whether or not empty statement should be on a new line
- * - option id: "org.eclipse.wst.jsdt.core.formatter.put_empty_statement_on_new_line"
- * - possible values: { TRUE, FALSE }
- * - default: FALSE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String FORMATTER_PUT_EMPTY_STATEMENT_ON_NEW_LINE = JavaScriptCore.PLUGIN_ID + ".formatter.put_empty_statement_on_new_line"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to specify the tabulation size
- * - option id: "org.eclipse.wst.jsdt.core.formatter.tabulation.char"
- * - possible values: { TAB, SPACE, MIXED }
- * - default: TAB
- * </pre>
- * More values may be added in the future.
- *
- * @see JavaScriptCore#TAB
- * @see JavaScriptCore#SPACE
- * @see #MIXED
- *
- */
- public static final String FORMATTER_TAB_CHAR = JavaScriptCore.PLUGIN_ID + ".formatter.tabulation.char"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to specify the equivalent number of spaces that represents one tabulation
- * - option id: "org.eclipse.wst.jsdt.core.formatter.tabulation.size"
- * - possible values: "&lt;n&gt;", where n is zero or a positive integer
- * - default: "4"
- * </pre>
- *
- */
- public static final String FORMATTER_TAB_SIZE = JavaScriptCore.PLUGIN_ID + ".formatter.tabulation.size"; //$NON-NLS-1$
-
- /**
- * <pre>
- * FORMATTER / Option to use tabulations only for leading indentations
- * - option id: "org.eclipse.wst.jsdt.core.formatter.use_tabs_only_for_leading_indentations"
- * - possible values: { TRUE, FALSE }
- * - default: FALSE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String FORMATTER_USE_TABS_ONLY_FOR_LEADING_INDENTATIONS = JavaScriptCore.PLUGIN_ID + ".formatter.use_tabs_only_for_leading_indentations"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to wrap before the binary operator
- * - option id: "org.eclipse.wst.jsdt.core.formatter.wrap_before_binary_operator"
- * - possible values: { TRUE, FALSE }
- * - default: TRUE
- * </pre>
- * This option is used only if the option {@link #FORMATTER_ALIGNMENT_FOR_BINARY_EXPRESSION} is set.
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String FORMATTER_WRAP_BEFORE_BINARY_OPERATOR = JavaScriptCore.PLUGIN_ID + ".formatter.wrap_before_binary_operator"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / The wrapping is done by indenting by one compare to the current indentation.
- * </pre>
- *
- */
- public static final int INDENT_BY_ONE= 2;
-
- /**
- * <pre>
- * FORMATTER / The wrapping is done by using the current indentation.
- * </pre>
- *
- */
- public static final int INDENT_DEFAULT= 0;
- /**
- * <pre>
- * FORMATTER / The wrapping is done by indenting on column under the splitting location.
- * </pre>
- *
- */
- public static final int INDENT_ON_COLUMN = 1;
-
- /**
- * <pre>
- * FORMATTER / Possible value for the option FORMATTER_TAB_CHAR
- * </pre>
- *
- * @see JavaScriptCore#TAB
- * @see JavaScriptCore#SPACE
- * @see #FORMATTER_TAB_CHAR
- */
- public static final String MIXED = "mixed"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Value to set a brace location at the start of the next line with
- * the right indentation.
- * </pre>
- * @see #FORMATTER_BRACE_POSITION_FOR_ANONYMOUS_TYPE_DECLARATION
- * @see #FORMATTER_BRACE_POSITION_FOR_ARRAY_INITIALIZER
- * @see #FORMATTER_BRACE_POSITION_FOR_OBJLIT_INITIALIZER
- * @see #FORMATTER_BRACE_POSITION_FOR_BLOCK
- * @see #FORMATTER_BRACE_POSITION_FOR_CONSTRUCTOR_DECLARATION
- * @see #FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION
- * @see #FORMATTER_BRACE_POSITION_FOR_SWITCH
- * @see #FORMATTER_BRACE_POSITION_FOR_TYPE_DECLARATION
- *
- */
- public static final String NEXT_LINE = "next_line"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Value to set a brace location at the start of the next line if a wrapping
- * occured.
- * </pre>
- * @see #FORMATTER_BRACE_POSITION_FOR_ANONYMOUS_TYPE_DECLARATION
- * @see #FORMATTER_BRACE_POSITION_FOR_ARRAY_INITIALIZER
- * @see #FORMATTER_BRACE_POSITION_FOR_OBJLIT_INITIALIZER
- * @see #FORMATTER_BRACE_POSITION_FOR_BLOCK
- * @see #FORMATTER_BRACE_POSITION_FOR_CONSTRUCTOR_DECLARATION
- * @see #FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION
- * @see #FORMATTER_BRACE_POSITION_FOR_SWITCH
- * @see #FORMATTER_BRACE_POSITION_FOR_TYPE_DECLARATION
- *
- */
- public static final String NEXT_LINE_ON_WRAP = "next_line_on_wrap"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Value to set a brace location at the start of the next line with
- * an extra indentation.
- * </pre>
- * @see #FORMATTER_BRACE_POSITION_FOR_ANONYMOUS_TYPE_DECLARATION
- * @see #FORMATTER_BRACE_POSITION_FOR_ARRAY_INITIALIZER
- * @see #FORMATTER_BRACE_POSITION_FOR_OBJLIT_INITIALIZER
- * @see #FORMATTER_BRACE_POSITION_FOR_BLOCK
- * @see #FORMATTER_BRACE_POSITION_FOR_CONSTRUCTOR_DECLARATION
- * @see #FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION
- * @see #FORMATTER_BRACE_POSITION_FOR_SWITCH
- * @see #FORMATTER_BRACE_POSITION_FOR_TYPE_DECLARATION
- *
- */
- public static final String NEXT_LINE_SHIFTED = "next_line_shifted"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Value to set an option to true.
- * </pre>
- *
- */
- public static final String TRUE = "true"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / The wrapping is done using as few lines as possible.
- * </pre>
- *
- */
- public static final int WRAP_COMPACT= 1;
- /**
- * <pre>
- * FORMATTER / The wrapping is done putting the first element on a new
- * line and then wrapping next elements using as few lines as possible.
- * </pre>
- *
- */
- public static final int WRAP_COMPACT_FIRST_BREAK= 2;
- /**
- * <pre>
- * FORMATTER / The wrapping is done by putting each element on its own line
- * except the first element.
- * </pre>
- *
- */
- public static final int WRAP_NEXT_PER_LINE= 5;
- /**
- * <pre>
- * FORMATTER / The wrapping is done by putting each element on its own line.
- * All elements are indented by one except the first element.
- * </pre>
- *
- */
- public static final int WRAP_NEXT_SHIFTED= 4;
-
- /**
- * <pre>
- * FORMATTER / Value to disable alignment.
- * </pre>
- *
- */
- public static final int WRAP_NO_SPLIT= 0;
- /**
- * <pre>
- * FORMATTER / The wrapping is done by putting each element on its own line.
- * </pre>
- *
- */
- public static final int WRAP_ONE_PER_LINE= 3;
-
- /*
- * Private constants. Not in javadoc
- */
- private static final IllegalArgumentException WRONG_ARGUMENT = new IllegalArgumentException();
- /**
- * Create a new alignment value according to the given values. This must be used to set up
- * the alignment options.
- *
- * @param forceSplit the given force value
- * @param wrapStyle the given wrapping style
- * @param indentStyle the given indent style
- *
- * @return the new alignement value
- */
- public static String createAlignmentValue(boolean forceSplit, int wrapStyle, int indentStyle) {
- int alignmentValue = 0;
- switch(wrapStyle) {
- case WRAP_COMPACT :
- alignmentValue |= Alignment.M_COMPACT_SPLIT;
- break;
- case WRAP_COMPACT_FIRST_BREAK :
- alignmentValue |= Alignment.M_COMPACT_FIRST_BREAK_SPLIT;
- break;
- case WRAP_NEXT_PER_LINE :
- alignmentValue |= Alignment.M_NEXT_PER_LINE_SPLIT;
- break;
- case WRAP_NEXT_SHIFTED :
- alignmentValue |= Alignment.M_NEXT_SHIFTED_SPLIT;
- break;
- case WRAP_ONE_PER_LINE :
- alignmentValue |= Alignment.M_ONE_PER_LINE_SPLIT;
- break;
- }
- if (forceSplit) {
- alignmentValue |= Alignment.M_FORCE;
- }
- switch(indentStyle) {
- case INDENT_BY_ONE :
- alignmentValue |= Alignment.M_INDENT_BY_ONE;
- break;
- case INDENT_ON_COLUMN :
- alignmentValue |= Alignment.M_INDENT_ON_COLUMN;
- }
- return String.valueOf(alignmentValue);
- }
-
- /**
- * Returns the formatter settings that most closely approximate
- * the default formatter settings of Eclipse version 2.1.
- *
- * @return the Eclipse 2.1 settings
- *
- */
- public static Map getEclipse21Settings() {
- return DefaultCodeFormatterOptions.getDefaultSettings().getMap();
- }
-
- /**
- * Returns the default Eclipse formatter settings
- *
- * @return the Eclipse default settings
- *
- */
- public static Map getEclipseDefaultSettings() {
- return DefaultCodeFormatterOptions.getEclipseDefaultSettings().getMap();
- }
-
- /**
- * <p>Return the force value of the given alignment value.
- * The given alignment value should be created using the <code>createAlignmentValue(boolean, int, int)</code>
- * API.
- * </p>
- *
- * @param value the given alignment value
- * @return the force value of the given alignment value
- * @see #createAlignmentValue(boolean, int, int)
- * @exception IllegalArgumentException if the given alignment value is null, or if it
- * doesn't have a valid format.
- */
- public static boolean getForceWrapping(String value) {
- if (value == null) {
- throw WRONG_ARGUMENT;
- }
- try {
- int existingValue = Integer.parseInt(value);
- return (existingValue & Alignment.M_FORCE) != 0;
- } catch (NumberFormatException e) {
- throw WRONG_ARGUMENT;
- }
- }
-
- /**
- * <p>Return the indentation style of the given alignment value.
- * The given alignment value should be created using the <code>createAlignmentValue(boolean, int, int)</code>
- * API.
- * </p>
- *
- * @param value the given alignment value
- * @return the indentation style of the given alignment value
- * @see #createAlignmentValue(boolean, int, int)
- * @exception IllegalArgumentException if the given alignment value is null, or if it
- * doesn't have a valid format.
- */
- public static int getIndentStyle(String value) {
- if (value == null) {
- throw WRONG_ARGUMENT;
- }
- try {
- int existingValue = Integer.parseInt(value);
- if ((existingValue & Alignment.M_INDENT_BY_ONE) != 0) {
- return INDENT_BY_ONE;
- } else if ((existingValue & Alignment.M_INDENT_ON_COLUMN) != 0) {
- return INDENT_ON_COLUMN;
- } else {
- return INDENT_DEFAULT;
- }
- } catch (NumberFormatException e) {
- throw WRONG_ARGUMENT;
- }
- }
-
- /**
- * Returns the settings according to the JavaScript conventions.
- *
- * @return the settings according to the JavaScript conventions
- *
- */
- public static Map getJavaConventionsSettings() {
- return DefaultCodeFormatterOptions.getJavaConventionsSettings().getMap();
- }
- /**
- * <p>Return the wrapping style of the given alignment value.
- * The given alignment value should be created using the <code>createAlignmentValue(boolean, int, int)</code>
- * API.
- * </p>
- *
- * @param value the given alignment value
- * @return the wrapping style of the given alignment value
- * @see #createAlignmentValue(boolean, int, int)
- * @exception IllegalArgumentException if the given alignment value is null, or if it
- * doesn't have a valid format.
- */
- public static int getWrappingStyle(String value) {
- if (value == null) {
- throw WRONG_ARGUMENT;
- }
- try {
- int existingValue = Integer.parseInt(value) & Alignment.SPLIT_MASK;
- switch(existingValue) {
- case Alignment.M_COMPACT_SPLIT :
- return WRAP_COMPACT;
- case Alignment.M_COMPACT_FIRST_BREAK_SPLIT :
- return WRAP_COMPACT_FIRST_BREAK;
- case Alignment.M_NEXT_PER_LINE_SPLIT :
- return WRAP_NEXT_PER_LINE;
- case Alignment.M_NEXT_SHIFTED_SPLIT :
- return WRAP_NEXT_SHIFTED;
- case Alignment.M_ONE_PER_LINE_SPLIT :
- return WRAP_ONE_PER_LINE;
- default:
- return WRAP_NO_SPLIT;
- }
- } catch (NumberFormatException e) {
- throw WRONG_ARGUMENT;
- }
- }
- /**
- * <p>Set the force value of the given alignment value and return the new value.
- * The given alignment value should be created using the <code>createAlignmentValue(boolean, int, int)</code>
- * API.
- * </p>
- *
- * @param value the given alignment value
- * @param force the given force value
- * @return the new alignment value
- * @see #createAlignmentValue(boolean, int, int)
- * @exception IllegalArgumentException if the given alignment value is null, or if it
- * doesn't have a valid format.
- */
- public static String setForceWrapping(String value, boolean force) {
- if (value == null) {
- throw WRONG_ARGUMENT;
- }
- try {
- int existingValue = Integer.parseInt(value);
- // clear existing force bit
- existingValue &= ~Alignment.M_FORCE;
- if (force) {
- existingValue |= Alignment.M_FORCE;
- }
- return String.valueOf(existingValue);
- } catch (NumberFormatException e) {
- throw WRONG_ARGUMENT;
- }
- }
-
- /**
- * <p>Set the indentation style of the given alignment value and return the new value.
- * The given value should be created using the <code>createAlignmentValue(boolean, int, int)</code>
- * API.
- * </p>
- *
- * @param value the given alignment value
- * @param indentStyle the given indentation style
- * @return the new alignment value
- * @see #INDENT_BY_ONE
- * @see #INDENT_DEFAULT
- * @see #INDENT_ON_COLUMN
- * @see #createAlignmentValue(boolean, int, int)
- * @exception IllegalArgumentException if the given alignment value is null, if the given
- * indentation style is not one of the possible indentation styles, or if the given
- * alignment value doesn't have a valid format.
- */
- public static String setIndentStyle(String value, int indentStyle) {
- if (value == null) {
- throw WRONG_ARGUMENT;
- }
- switch(indentStyle) {
- case INDENT_BY_ONE :
- case INDENT_DEFAULT :
- case INDENT_ON_COLUMN :
- break;
- default :
- throw WRONG_ARGUMENT;
- }
- try {
- int existingValue = Integer.parseInt(value);
- // clear existing indent bits
- existingValue &= ~(Alignment.M_INDENT_BY_ONE | Alignment.M_INDENT_ON_COLUMN);
- switch(indentStyle) {
- case INDENT_BY_ONE :
- existingValue |= Alignment.M_INDENT_BY_ONE;
- break;
- case INDENT_ON_COLUMN :
- existingValue |= Alignment.M_INDENT_ON_COLUMN;
- }
- return String.valueOf(existingValue);
- } catch (NumberFormatException e) {
- throw WRONG_ARGUMENT;
- }
- }
- /**
- * <p>Set the wrapping style of the given alignment value and return the new value.
- * The given value should be created using the <code>createAlignmentValue(boolean, int, int)</code>
- * API.
- * </p>
- *
- * @param value the given alignment value
- * @param wrappingStyle the given wrapping style
- * @return the new alignment value
- * @see #WRAP_COMPACT
- * @see #WRAP_COMPACT_FIRST_BREAK
- * @see #WRAP_NEXT_PER_LINE
- * @see #WRAP_NEXT_SHIFTED
- * @see #WRAP_NO_SPLIT
- * @see #WRAP_ONE_PER_LINE
- * @see #createAlignmentValue(boolean, int, int)
- * @exception IllegalArgumentException if the given alignment value is null, if the given
- * wrapping style is not one of the possible wrapping styles, or if the given
- * alignment value doesn't have a valid format.
- */
- public static String setWrappingStyle(String value, int wrappingStyle) {
- if (value == null) {
- throw WRONG_ARGUMENT;
- }
- switch(wrappingStyle) {
- case WRAP_COMPACT :
- case WRAP_COMPACT_FIRST_BREAK :
- case WRAP_NEXT_PER_LINE :
- case WRAP_NEXT_SHIFTED :
- case WRAP_NO_SPLIT :
- case WRAP_ONE_PER_LINE :
- break;
- default:
- throw WRONG_ARGUMENT;
- }
- try {
- int existingValue = Integer.parseInt(value);
- // clear existing split bits
- existingValue &= ~(Alignment.SPLIT_MASK);
- switch(wrappingStyle) {
- case WRAP_COMPACT :
- existingValue |= Alignment.M_COMPACT_SPLIT;
- break;
- case WRAP_COMPACT_FIRST_BREAK :
- existingValue |= Alignment.M_COMPACT_FIRST_BREAK_SPLIT;
- break;
- case WRAP_NEXT_PER_LINE :
- existingValue |= Alignment.M_NEXT_PER_LINE_SPLIT;
- break;
- case WRAP_NEXT_SHIFTED :
- existingValue |= Alignment.M_NEXT_SHIFTED_SPLIT;
- break;
- case WRAP_ONE_PER_LINE :
- existingValue |= Alignment.M_ONE_PER_LINE_SPLIT;
- break;
- }
- return String.valueOf(existingValue);
- } catch (NumberFormatException e) {
- throw WRONG_ARGUMENT;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/formatter/IndentManipulation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/formatter/IndentManipulation.java
deleted file mode 100644
index 282d6d69..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/formatter/IndentManipulation.java
+++ /dev/null
@@ -1,429 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.formatter;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Map;
-
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.DefaultLineTracker;
-import org.eclipse.jface.text.ILineTracker;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.wst.jsdt.internal.compiler.parser.ScannerHelper;
-import org.eclipse.wst.jsdt.internal.compiler.util.Util;
-
-/**
- * Helper class to provide String manipulation functions dealing with indentations.
- *
- * 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 final class IndentManipulation {
-
- private IndentManipulation() {
- // don't instantiate
- }
-
- /**
- * Returns <code>true</code> if the given character is an indentation character. Indentation character are all whitespace characters
- * except the line delimiter characters.
- *
- * @param ch the given character
- * @return Returns <code>true</code> if this the character is a indent character, <code>false</code> otherwise
- */
- public static boolean isIndentChar(char ch) {
- return ScannerHelper.isWhitespace(ch) && !isLineDelimiterChar(ch);
- }
-
- /**
- * Returns <code>true</code> if the given character is a line delimiter character.
- *
- * @param ch the given character
- * @return Returns <code>true</code> if this the character is a line delimiter character, <code>false</code> otherwise
- */
- public static boolean isLineDelimiterChar(char ch) {
- return ch == '\n' || ch == '\r';
- }
-
- /**
- * Returns the indentation of the given line in indentation units. Odd spaces are
- * not counted. This method only analyzes the content of <code>line</code> up to the first
- * non-whitespace character.
- *
- * @param line the string to measure the indent of
- * @param tabWidth the width of one tab character in space equivalents
- * @param indentWidth the width of one indentation unit in space equivalents
- * @return the number of indentation units that line is indented by
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the given <code>indentWidth</code> is lower or equals to zero</li>
- * <li>the given <code>tabWidth</code> is lower than zero</li>
- * <li>the given <code>line</code> is null</li>
- * </ul>
- */
- public static int measureIndentUnits(CharSequence line, int tabWidth, int indentWidth) {
- if (indentWidth <= 0 || tabWidth < 0 || line == null) {
- throw new IllegalArgumentException();
- }
-
- int visualLength= measureIndentInSpaces(line, tabWidth);
- return visualLength / indentWidth;
- }
-
- /**
- * Returns the indentation of the given line in space equivalents.
- *
- * <p>Tab characters are counted using the given <code>tabWidth</code> and every other indent
- * character as one. This method analyzes the content of <code>line</code> up to the first
- * non-whitespace character.</p>
- *
- * @param line the string to measure the indent of
- * @param tabWidth the width of one tab in space equivalents
- * @return the measured indent width in space equivalents
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the given <code>line</code> is null</li>
- * <li>the given <code>tabWidth</code> is lower than zero</li>
- * </ul>
- */
- public static int measureIndentInSpaces(CharSequence line, int tabWidth) {
- if (tabWidth < 0 || line == null) {
- throw new IllegalArgumentException();
- }
-
- int length= 0;
- int max= line.length();
- for (int i= 0; i < max; i++) {
- char ch= line.charAt(i);
- if (ch == '\t') {
- int reminder= length % tabWidth;
- length += tabWidth - reminder;
- } else if (isIndentChar(ch)) {
- length++;
- } else {
- return length;
- }
- }
- return length;
- }
-
- /**
- * Returns the leading indentation string of the given line. Note that the returned string
- * need not be equal to the leading whitespace as odd spaces are not considered part of the
- * indentation.
- *
- * @param line the line to scan
- * @param tabWidth the size of one tab in space equivalents
- * @param indentWidth the width of one indentation unit in space equivalents
- * @return the indent part of <code>line</code>, but no odd spaces
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the given <code>indentWidth</code> is lower or equals to zero</li>
- * <li>the given <code>tabWidth</code> is lower than zero</li>
- * <li>the given <code>line</code> is null</li>
- * </ul>
- */
- public static String extractIndentString(String line, int tabWidth, int indentWidth) {
- if (tabWidth < 0 || indentWidth <= 0 || line == null) {
- throw new IllegalArgumentException();
- }
-
- int size= line.length();
- int end= 0;
-
- int spaceEquivs= 0;
- int characters= 0;
- for (int i= 0; i < size; i++) {
- char c= line.charAt(i);
- if (c == '\t') {
- int remainder= spaceEquivs % tabWidth;
- spaceEquivs += tabWidth - remainder;
- characters++;
- } else if (isIndentChar(c)) {
- spaceEquivs++;
- characters++;
- } else {
- break;
- }
- if (spaceEquivs >= indentWidth) {
- end += characters;
- characters= 0;
- spaceEquivs= spaceEquivs % indentWidth;
- }
- }
- if (end == 0) {
- return Util.EMPTY_STRING;
- } else if (end == size) {
- return line;
- } else {
- return line.substring(0, end);
- }
- }
-
-
- /**
- * Removes the given number of indentation units from a given line. If the line
- * has less than the given indent, all the available indentation is removed.
- * If <code>indentsToRemove <= 0</code> the line is returned.
- *
- * @param line the line to trim
- * @param tabWidth the width of one tab in space equivalents
- * @param indentWidth the width of one indentation unit in space equivalents
- * @return the trimmed string
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the given <code>indentWidth</code> is lower or equals to zero</li>
- * <li>the given <code>tabWidth</code> is lower than zero</li>
- * <li>the given <code>line</code> is null</li>
- * </ul>
- */
- public static String trimIndent(String line, int indentUnitsToRemove, int tabWidth, int indentWidth) {
- if (tabWidth < 0 || indentWidth <= 0 || line == null) {
- throw new IllegalArgumentException();
- }
-
- if (indentUnitsToRemove <= 0)
- return line;
-
- final int spaceEquivalentsToRemove= indentUnitsToRemove * indentWidth;
-
- int start= 0;
- int spaceEquivalents= 0;
- int size= line.length();
- String prefix= null;
- for (int i= 0; i < size; i++) {
- char c= line.charAt(i);
- if (c == '\t') {
- int remainder= spaceEquivalents % tabWidth;
- spaceEquivalents += tabWidth - remainder;
- } else if (isIndentChar(c)) {
- spaceEquivalents++;
- } else {
- // Assert.isTrue(false, "Line does not have requested number of indents");
- start= i;
- break;
- }
- if (spaceEquivalents == spaceEquivalentsToRemove) {
- start= i + 1;
- break;
- }
- if (spaceEquivalents > spaceEquivalentsToRemove) {
- // can happen if tabSize > indentSize, e.g tabsize==8, indent==4, indentsToRemove==1, line prefixed with one tab
- // this implements the third option
- start= i + 1; // remove the tab
- // and add the missing spaces
- char[] missing= new char[spaceEquivalents - spaceEquivalentsToRemove];
- Arrays.fill(missing, ' ');
- prefix= new String(missing);
- break;
- }
- }
- String trimmed;
- if (start == size)
- trimmed= Util.EMPTY_STRING;
- else
- trimmed= line.substring(start);
-
- if (prefix == null)
- return trimmed;
- return prefix + trimmed;
- }
-
- /**
- * Change the indent of a, possible multiple line, code string. The given number of indent units is removed,
- * and a new indent string is added.
- * <p>The first line of the code will not be changed (It is considered to have no indent as it might start in
- * the middle of a line).</p>
- *
- * @param code the code to change the indent of
- * @param indentUnitsToRemove the number of indent units to remove from each line (except the first) of the given code
- * @param tabWidth the size of one tab in space equivalents
- * @param indentWidth the width of one indentation unit in space equivalents
- * @param newIndentString the new indent string to be added to all lines (except the first)
- * @param lineDelim the new line delimiter to be used. The returned code will contain only this line delimiter.
- * @return the newly indent code, containing only the given line delimiters.
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the given <code>indentWidth</code> is lower or equals to zero</li>
- * <li>the given <code>tabWidth</code> is lower than zero</li>
- * <li>the given <code>code</code> is null</li>
- * <li>the given <code>indentUnitsToRemove</code> is lower than zero</li>
- * <li>the given <code>newIndentString</code> is null</li>
- * <li>the given <code>lineDelim</code> is null</li>
- * </ul>
- */
- public static String changeIndent(String code, int indentUnitsToRemove, int tabWidth, int indentWidth, String newIndentString, String lineDelim) {
- if (tabWidth < 0 || indentWidth <= 0 || code == null || indentUnitsToRemove < 0 || newIndentString == null || lineDelim == null) {
- throw new IllegalArgumentException();
- }
-
- try {
- ILineTracker tracker= new DefaultLineTracker();
- tracker.set(code);
- int nLines= tracker.getNumberOfLines();
- if (nLines == 1) {
- return code;
- }
-
- StringBuffer buf= new StringBuffer();
-
- for (int i= 0; i < nLines; i++) {
- IRegion region= tracker.getLineInformation(i);
- int start= region.getOffset();
- int end= start + region.getLength();
- String line= code.substring(start, end);
-
- if (i == 0) { // no indent for first line (contained in the formatted string)
- buf.append(line);
- } else { // no new line after last line
- buf.append(lineDelim);
- buf.append(newIndentString);
- buf.append(trimIndent(line, indentUnitsToRemove, tabWidth, indentWidth));
- }
- }
- return buf.toString();
- } catch (BadLocationException e) {
- // can not happen
- return code;
- }
- }
-
- /**
- * Returns the text edits retrieved after changing the indentation of a, possible multi-line, code string.
- *
- * <p>The given number of indent units is removed, and a new indent string is added.</p>
- * <p>The first line of the code will not be changed (It is considered to have no indent as it might start in
- * the middle of a line).</p>
- *
- * @param source The code to change the indent of
- * @param indentUnitsToRemove the number of indent units to remove from each line (except the first) of the given code
- * @param tabWidth the size of one tab in space equivalents
- * @param indentWidth the width of one indentation unit in space equivalents
- * @param newIndentString the new indent string to be added to all lines (except the first)
- * @return returns the resulting text edits
- * @exception IllegalArgumentException if:
- * <ul>
- * <li>the given <code>indentWidth</code> is lower or equals to zero</li>
- * <li>the given <code>tabWidth</code> is lower than zero</li>
- * <li>the given <code>source</code> is null</li>
- * <li>the given <code>indentUnitsToRemove</code> is lower than zero</li>
- * <li>the given <code>newIndentString</code> is null</li>
- * </ul>
- */
- public static ReplaceEdit[] getChangeIndentEdits(String source, int indentUnitsToRemove, int tabWidth, int indentWidth, String newIndentString) {
- if (tabWidth < 0 || indentWidth <= 0 || source == null || indentUnitsToRemove < 0 || newIndentString == null) {
- throw new IllegalArgumentException();
- }
-
- ArrayList result= new ArrayList();
- try {
- ILineTracker tracker= new DefaultLineTracker();
- tracker.set(source);
- int nLines= tracker.getNumberOfLines();
- if (nLines == 1)
- return (ReplaceEdit[])result.toArray(new ReplaceEdit[result.size()]);
- for (int i= 1; i < nLines; i++) {
- IRegion region= tracker.getLineInformation(i);
- int offset= region.getOffset();
- String line= source.substring(offset, offset + region.getLength());
- int length= indexOfIndent(line, indentUnitsToRemove, tabWidth, indentWidth);
- if (length >= 0) {
- result.add(new ReplaceEdit(offset, length, newIndentString));
- } else {
- length= measureIndentUnits(line, tabWidth, indentWidth);
- result.add(new ReplaceEdit(offset, length, "")); //$NON-NLS-1$
- }
- }
- } catch (BadLocationException cannotHappen) {
- // can not happen
- }
- return (ReplaceEdit[])result.toArray(new ReplaceEdit[result.size()]);
- }
-
- /*
- * Returns the index where the indent of the given size ends.
- * Returns <code>-1<code> if the line isn't prefixed with an indent of
- * the given number of indents.
- */
- private static int indexOfIndent(CharSequence line, int numberOfIndentUnits, int tabWidth, int indentWidth) {
-
- int spaceEquivalents= numberOfIndentUnits * indentWidth;
-
- int size= line.length();
- int result= -1;
- int blanks= 0;
- for (int i= 0; i < size && blanks < spaceEquivalents; i++) {
- char c= line.charAt(i);
- if (c == '\t') {
- int remainder= blanks % tabWidth;
- blanks += tabWidth - remainder;
- } else if (isIndentChar(c)) {
- blanks++;
- } else {
- break;
- }
- result= i;
- }
- if (blanks < spaceEquivalents)
- return -1;
- return result + 1;
- }
-
- /**
- * Returns the tab width as configured in the given map.
- * <p>Use {@link org.eclipse.wst.jsdt.core.IJavaScriptProject#getOptions(boolean)} to get the most current project options.</p>
- *
- * @param options the map to get the formatter settings from.
- *
- * @return the tab width
- * @exception IllegalArgumentException if the given <code>options</code> is null
- */
- public static int getTabWidth(Map options) {
- if (options == null) {
- throw new IllegalArgumentException();
- }
- return getIntValue(options, DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, 4);
- }
-
- /**
- * Returns the tab width as configured in the given map.
- * <p>Use {@link org.eclipse.wst.jsdt.core.IJavaScriptProject#getOptions(boolean)} to get the most current project options.</p>
- *
- * @param options the map to get the formatter settings from
- *
- * @return the indent width
- * @exception IllegalArgumentException if the given <code>options</code> is null
- */
- public static int getIndentWidth(Map options) {
- if (options == null) {
- throw new IllegalArgumentException();
- }
- int tabWidth=getTabWidth(options);
- boolean isMixedMode= DefaultCodeFormatterConstants.MIXED.equals(options.get(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR));
- if (isMixedMode) {
- return getIntValue(options, DefaultCodeFormatterConstants.FORMATTER_INDENTATION_SIZE, tabWidth);
- }
- return tabWidth;
- }
-
- private static int getIntValue(Map options, String key, int def) {
- try {
- return Integer.parseInt((String) options.get(key));
- } catch (NumberFormatException e) {
- return def;
- }
- }
-}
-
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
deleted file mode 100644
index 52784179..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/formatter/messages.properties
+++ /dev/null
@@ -1,41 +0,0 @@
-###############################################################################
-# Copyright (c) 2006, 2007 Ben Konrath <ben@bagu.org>
-# All rights reserved. This program and 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:
-# Ben Konrath <ben@bagu.org> - initial implementation
-# IBM Corporation - Code review and integration
-###############################################################################
-CommandLineStart=Starting format job ...
-CommandLineDone=Done.
-CommandLineConfigFile=Configuration Name: {0}
-CommandLineFormatting=Formatting: {0}
-
-CommandLineUsage=Usage: eclipse -application org.eclipse.wst.jsdt.core.JavaCodeFormatter [ OPTIONS ] -config <configFile> <files>\n\
-\n\
-\ <files> JavaScript source files and/or directories to format.\n\
-\ Only files ending with .js will be formatted in the given directory.\n\
-\ -config <configFile> Use the formatting style from the specified properties file.\n\
-\ Refer to the help documentation to find out how to generate this file.\n\
-\n\
-\ OPTIONS:\n\
-\n\
-\ -help Display this message.\n\
-\ -quiet Only print error messages.\n\
-\ -verbose Be verbose about the formatting job.
-
-CommandLineErrorFile={0} does not exist. Please specify only valid JavaScript Source files.
-CommandLineErrorConfig=A problem occurred while reading the config file {0}.
-CommandLineErrorFileDir=You must specify at least one file or directory to format.
-CommandLineErrorQuietVerbose=You cannot use the options {0} and {1} together.
-CommandLineErrorNoConfigFile=No configuration file specified.
-
-CaughtException=Caught {0} : {1}
-ExceptionSkip= {0}\nSkipping File.
-
-ConfigFileReadingError=Error Reading config file.
-
-FormatProblem=The Eclipse formatter failed to format {0}. Skip the file. \ No newline at end of file
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
deleted file mode 100644
index 5ff53306..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/DefaultInferrenceProvider.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*******************************************************************************
- * 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.core.infer;
-
-
-/**
- * A default implementation of InferrenceProvider. It uses the default Inference engine.
- *
- * 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 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;
- }
- }
- return InferrenceProvider.MAYBE_THIS;
- }
-
- public IInferEngine getInferEngine() {
- InferEngine engine = new InferEngine();
- engine.inferenceProvider=this;
- return engine;
- }
-
- public String getID() {
- return ID;
- }
-
- public ResolutionConfiguration getResolutionConfiguration() {
- return new ResolutionConfiguration();
- }
-
- public RefactoringSupport getRefactoringSupport() {
- return null;
- }
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/IInferEngine.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/IInferEngine.java
deleted file mode 100644
index 641a3366..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/IInferEngine.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 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.core.infer;
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration;
-
-/**
- * Engine for inferring types from compilation unit.
- *
- * <p>Clients may implement this interface but should expect some breakage by future releases.</p>
- *
- * 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.
- *
- * @since 3.2
- */
-public interface IInferEngine {
-
- public final static char[] ANONYMOUS_PREFIX = {'_','_','_'};
-
- public static final char[] ANONYMOUS_CLASS_ID= {'a','n','o','n','y','m','o','u','s'};
-
- /**
- * Initializes inference engine. Always called before {@link #setCompilationUnit()}
- * to let engine prepare for next compilation unit.
- */
- void initialize();
-
- /**
- * Set compilation unit for processing.
- */
- void setCompilationUnit(CompilationUnitDeclaration parsedUnit);
-
- /**
- * Requests to perform type inference on provided compilation unit. Always called
- * after {@link #setCompilationUnit(CompilationUnitDeclaration)}
- */
- void doInfer();
-
- /**
- * Provides inference options to the engine.
- */
- void initializeOptions(InferOptions inferOptions);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/IInferenceFile.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/IInferenceFile.java
deleted file mode 100644
index 36ac9a7b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/IInferenceFile.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.infer;
-
-
-/**
- * Representation of a file which can be inferrenced.
- *
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * 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 IInferenceFile {
- /**
- * get the filename for the script if it can be determined
- * @return the scripts file name, this could be null
- */
- char[] getFileName();
-
- /**
- * get the inference ID for the script if it is located in a container that specified an Inference ID
- * @return the inference ID for the script, could be null
- */
- String getInferenceID();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/ImportRewriteSupport.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/ImportRewriteSupport.java
deleted file mode 100644
index 1f871976..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/ImportRewriteSupport.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008 IBM Corporation and others.
- * All rights reserved. This program and 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.dom.JavaScriptUnit;
-
-/**
- * Support for extending the automatic import insertion mechanisms
- *
- * 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 ImportRewriteSupport {
-
- /**
- * @return true if the import value matches a type name, false if the import value is a file path value
- */
- public boolean isImportMatchesType()
- {
- return true;
- }
-
- /**
- * @return true if existing imports should be modified if necessary
- */
- public boolean isRewriteExisting()
- {
- return true;
- }
-
- /**
- * @return the string which represents the import
- */
- public String getImportString(String importName, boolean isStatic, String lineDelim)
- {
- return null;
- }
-
- /**
- * Find the starting position of an import when none already exist
- * @return the starting position, -1 for default action
- */
- public int getImportStartPosition(JavaScriptUnit root) {
- return -1;
- }
-}
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
deleted file mode 100644
index 8f25a1f9..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferEngine.java
+++ /dev/null
@@ -1,2151 +0,0 @@
-/*******************************************************************************
- * 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.
- *
- * <p>Clients may subclass this class but should expect some breakage by future releases.</p>
- *
- * 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(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;
- }
-
-
- /**
- * <p>Creates an anonymous type name for the given {@link IASTNode}</p>
- *
- * @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;
- }
-
- /**
- * <p>Handle a local declaration who's right hand side is a function.</p>
- * <p>Use case:</p><pre>foo.bar.Test = function() { this.num = 42; }</pre>
- *
- * @param localDeclaration {@link ILocalDeclaration} to attempt to infer a type from
- * @return <code>true</code> if keep visiting, <code>false</code> 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(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;
- }
-
-}
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
deleted file mode 100644
index 700bf29b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferOptions.java
+++ /dev/null
@@ -1,131 +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.core.infer;
-
-import java.util.HashMap;
-import java.util.Map;
-
-
-/**
- *
- * Inference Options
- *
- * 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 InferOptions {
-
- public static final String OPTION_UseAssignments = "org.eclipse.wst.jsdt.core.infer.useAssignments"; //$NON-NLS-1$
- public static final String OPTION_UseInitMethod = "org.eclipse.wst.jsdt.core.infer.useInitMethod"; //$NON-NLS-1$
- public static final String OPTION_SaveArgumentComments = "org.eclipse.wst.jsdt.core.infer.saveArgumentComments"; //$NON-NLS-1$
- public static final String OPTION_DocLocation = "org.eclipse.wst.jsdt.core.infer.docLocation"; //$NON-NLS-1$
-
-
- public static final int DOC_LOCATION_BEFORE=1;
- public static final int DOC_LOCATION_AFTER=2;
-
-
- // tags used to recognize tasks in comments
- public char[][] systemClassMethod = null;
-
- /**
- * Set to true var types are inferred based on assigments
- */
- public boolean useAssignments=true;
-
- public boolean useInitMethod;
- public String engineClass;
- public boolean saveArgumentComments;
- public int docLocation=DOC_LOCATION_BEFORE;
-
-
-
-
- /**
- * Initializing the compiler options with defaults
- */
- public InferOptions(){
- // use default options
- setDefaultOptions();
- }
-
- /**
- * Initializing the compiler options with external settings
- * @param settings
- */
- public InferOptions(Map settings){
-
- if (settings == null) return;
- set(settings);
- }
-
- public void setDefaultOptions()
- {
- this.useAssignments=true;
- this.useInitMethod=true;
- this.saveArgumentComments=true;
- }
-
- public Map getMap() {
- Map optionsMap = new HashMap(30);
- optionsMap.put(OPTION_UseAssignments, this.useAssignments ? "true":"false"); //$NON-NLS-1$ //$NON-NLS-2$
- optionsMap.put(OPTION_UseInitMethod, this.useInitMethod ? "true":"false"); //$NON-NLS-1$ //$NON-NLS-2$
- optionsMap.put(OPTION_SaveArgumentComments, this.saveArgumentComments ? "true":"false"); //$NON-NLS-1$ //$NON-NLS-2$
- optionsMap.put(OPTION_DocLocation, String.valueOf(this.docLocation)); //$NON-NLS-1$ //$NON-NLS-2$
- return optionsMap;
- }
-
-
- public void set(Map optionsMap) {
-
- Object optionValue;
- if ((optionValue = optionsMap.get(OPTION_UseAssignments)) != null) {
- this.useAssignments="true".equals(optionValue) ; //$NON-NLS-1$
- }
- if ((optionValue = optionsMap.get(OPTION_UseInitMethod)) != null) {
- this.useInitMethod="true".equals(optionValue) ; //$NON-NLS-1$
- }
- if ((optionValue = optionsMap.get(OPTION_SaveArgumentComments)) != null) {
- this.saveArgumentComments="true".equals(optionValue) ; //$NON-NLS-1$
- }
- if ((optionValue = optionsMap.get(OPTION_DocLocation)) != null) {
- this.docLocation= Integer.parseInt((String)optionValue) ; //$NON-NLS-1$
- }
- }
-
- public String toString() {
-
- StringBuffer buf = new StringBuffer("InferOptions:"); //$NON-NLS-1$
- buf.append("\n\t- use assignments: ").append( this.useAssignments ? "ON" : " OFF"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- buf.append("\n\t- use initialization method : ").append( this.useInitMethod ? "ON" : " OFF"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- return buf.toString();
- }
-
-
- public InferEngine createEngine()
- {
- if (engineClass!=null)
- {
- try {
- InferEngine engine= (InferEngine) Class.forName(engineClass).newInstance();
- engine.inferOptions=this;
- return engine;
- } catch (Exception ex)
- {
- ex.printStackTrace();
- //TODO: implement something
- }
- }
- return new InferEngine(this);
- }
-}
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
deleted file mode 100644
index 1b963ca2..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferredAttribute.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*******************************************************************************
- * 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.core.infer;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.FieldBinding;
-
-
-/**
- *
- * This represents an inferred attribute.
- *
- * 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 InferredAttribute extends InferredMember{
-
- public FieldBinding binding;
- public int initializationStart=-1;
-
- /**
- * The type of this attribute
- */
- public InferredType type;
- public ASTNode node;
- public int modifiers;
-
- /**
- * Creates an attribute with this name in the given inferred type. This
- * method is <b>discouraged</b> in favor of supplying the ASTNode which declared
- * the attribute.
- */
- public InferredAttribute(char [] name, InferredType inType, int start, int end)
- {
- this.name=name;
- this.inType = inType;
- this.sourceStart=start;
- this.sourceEnd=end;
- }
-
-
- /**
- * @param name
- * @param inferredType the type to which this attribute belongs
- * @param definer
- */
- public InferredAttribute(char[] name, InferredType inferredType, IASTNode definer) {
- this(name, inferredType, definer.sourceStart(), definer.sourceEnd());
- node = (ASTNode) definer;
- }
-
-
- public StringBuffer print(int indent, StringBuffer output)
- {
- String modifier=(isStatic)? "static ":""; //$NON-NLS-1$ //$NON-NLS-2$
- printIndent(indent, output).append(modifier);
- if (type!=null)
- type.dumpReference(output);
- else
- output.append("??"); //$NON-NLS-1$
- output.append(" ").append(name); //$NON-NLS-1$
- return output;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferredMember.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferredMember.java
deleted file mode 100644
index 6efbdc57..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferredMember.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*******************************************************************************
- * 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.core.infer;
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode;
-
-
-/**
- *
- * 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 InferredMember extends ASTNode{
-
- /**
- * The name of this member
- */
- public char [] name;
- /**
- * The type to which this member belongs
- */
- public InferredType inType;
- /**
- * The source offset at which the name of this member begins
- */
- public int nameStart;
- public boolean isStatic = false;
-
- public boolean isInferred()
- {
- return true;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferredMethod.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferredMethod.java
deleted file mode 100644
index 5bfd63b9..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferredMethod.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*******************************************************************************
- * 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
- * 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.IFunctionDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding;
-
-
-/**
- *
- * This represents an inferred method
- *
- * 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 InferredMethod extends InferredMember{
-
- private MethodDeclaration methodDeclaration;
-
- public boolean isConstructor;
- public MethodBinding methodBinding;
- public InferredMethod(char [] name, IFunctionDeclaration functionDeclaration, InferredType inType )
- {
- this.methodDeclaration=(MethodDeclaration)functionDeclaration;
- this.name=name;
- this.inType = inType;
- this.sourceStart=methodDeclaration.sourceStart;
- this.sourceEnd=methodDeclaration.sourceEnd;
- }
-
- public IFunctionDeclaration getFunctionDeclaration()
- {
- return methodDeclaration;
- }
-
- public StringBuffer print(int indent, StringBuffer output)
- {
- String modifier=(isStatic)? "static ":""; //$NON-NLS-1$ //$NON-NLS-2$
- printIndent(indent, output).append(modifier);
- if (!isConstructor)
- {
- if (methodDeclaration.inferredType!=null)
- methodDeclaration.inferredType.dumpReference(output);
- else
- output.append("??"); //$NON-NLS-1$
- output.append(" "); //$NON-NLS-1$
- }
-
- output.append(name).append("("); //$NON-NLS-1$
- if (methodDeclaration.arguments!=null)
- for (int i = 0; i < methodDeclaration.arguments.length; i++) {
- if (i>0)
- output.append(", "); //$NON-NLS-1$
- InferredType argumentType = methodDeclaration.arguments[i].inferredType;
- if (argumentType!=null )
- {
- output.append(argumentType.name).append(" "); //$NON-NLS-1$
- }
- output.append(methodDeclaration.arguments[i].name);
- }
- output.append(")"); //$NON-NLS-1$
-
- return output;
- }
-}
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
deleted file mode 100644
index 90f3eae6..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferredType.java
+++ /dev/null
@@ -1,469 +0,0 @@
-/*******************************************************************************
- * 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<this.numberAttributes;i++) {
- this.attributes[i].print(indent+1,output);
- output.append(";\n"); //$NON-NLS-1$
- }
- if (methods!=null)
- for (Iterator methodIterator = methods.iterator(); methodIterator.hasNext();) {
- InferredMethod method = (InferredMethod) methodIterator.next();
- method.print(indent+1,output);
- output.append("\n"); //$NON-NLS-1$
- }
- output.append("}"); //$NON-NLS-1$
- return output;
- }
-
- public boolean isInferred()
- {
- return true;
- }
-
- public void updatePositions(int start, int end)
- {
- if (this.sourceStart==-1 ||(start>=0 && start<this.sourceStart))
- this.sourceStart=start;
- if (end>0&&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()));
- }
-
-
- /**
- * <p>Adds the name of a type to mix into this type once all of the types have
- * been inferred</p>
- *
- * @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);
- }
-
-}
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
deleted file mode 100644
index e80fe85e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferrenceManager.java
+++ /dev/null
@@ -1,190 +0,0 @@
-/*******************************************************************************
- * 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.core.infer;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IExtension;
-import org.eclipse.core.runtime.IExtensionPoint;
-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.util.Util;
-
-
-/**
- *
- * Internal
- *
- * 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 InferrenceManager {
-
- public static final String EXTENSION_POINT= "inferrenceSupport"; //$NON-NLS-1$
-
- protected static final String TAG_INFERENCE_PROVIDER = "inferenceProvider"; //$NON-NLS-1$
- protected static final String ATTR_INFERENGINE_CLASS = "class"; //$NON-NLS-1$
-
-
- private static InferrenceManager instance = null;
-
-
- private InferrenceSupportExtension [] extensions;
-
- public static InferrenceManager getInstance(){
- if( instance == null )
- instance = new InferrenceManager();
-
- return instance;
- }
-
-
-
- public InferrenceProvider [] getInferenceProviders()
- {
-
- if (extensions==null)
- {
- loadInferenceExtensions();
- }
- ArrayList extProviders=new ArrayList();
- extProviders.add(new DefaultInferrenceProvider());
- for (int i = 0; i < extensions.length; i++) {
- if (extensions[i].inferProvider!=null)
- extProviders.add(extensions[i].inferProvider);
- }
- return (InferrenceProvider [] )extProviders.toArray(new InferrenceProvider[extProviders.size()]);
- }
-
-
- public InferrenceProvider [] getInferenceProviders(IInferenceFile script)
- {
- 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;
- }
- }
- 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) {
- case InferrenceProvider.MAYBE_THIS:
- IInferEngine eng=inferenceProviders[i].getInferEngine();
- extEngines.add(eng);
- break;
-
- case InferrenceProvider.ONLY_THIS:
- return getSingleEngine(inferenceProviders[i]);
-
-
- default:
- break;
- }
- }
- return (IInferEngine [] )extEngines.toArray(new IInferEngine[extEngines.size()]);
- }
-
-
- private IInferEngine [] getSingleEngine(InferrenceProvider provider)
- {
- IInferEngine engine=provider.getInferEngine();
- IInferEngine [] thisEngine = {engine};
- return thisEngine;
- }
-
-
- protected void loadInferenceExtensions() {
- IExtensionRegistry registry = Platform.getExtensionRegistry();
- ArrayList extList = new ArrayList();
- if (registry != null) {
- IExtensionPoint point = registry.getExtensionPoint(
- JavaScriptCore.PLUGIN_ID, EXTENSION_POINT);
-
- if (point != null) {
- IExtension[] extensions = point.getExtensions();
- for (int i = 0; i < extensions.length; i++) {
- IConfigurationElement[] elements = extensions[i]
- .getConfigurationElements();
- for (int j = 0; j < elements.length; j++) {
- try {
- InferrenceProvider inferProvider = null;
- if (elements[j].getName().equals(TAG_INFERENCE_PROVIDER)) {
- inferProvider = (InferrenceProvider) elements[j]
- .createExecutableExtension(ATTR_INFERENGINE_CLASS);
- }
- InferrenceSupportExtension inferenceSupport = new InferrenceSupportExtension();
- inferenceSupport.inferProvider = inferProvider;
-
- extList.add(inferenceSupport);
- } catch (CoreException e) {
- Util.log(e, "Error in loading inference extension");
- }
- }
- }
- }
- }
-
- this.extensions = (InferrenceSupportExtension[]) extList
- .toArray(new InferrenceSupportExtension[extList.size()]);
- }
-
-
-}
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
deleted file mode 100644
index d9621bd5..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferrenceProvider.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*******************************************************************************
- * 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.core.infer;
-
-
-/**
- * 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.
- */
-public interface InferrenceProvider {
-
- /**
- * <p>Indicates that this InferrenceProvider, and its engine, are the only ones that should apply.</p>
- * <p>Its use is discouraged.</p>
- */
- public static final int ONLY_THIS = 1;
-
- /**
- * <p>Indicates that this InferrenceProvider, and its engine, do not apply.</p>
- */
- public static final int NOT_THIS = 2;
-
- /**
- * <p>Indicates that this InferrenceProvider, and its engine, should apply to a script file.</p>
- */
- 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 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 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
- */
- public ResolutionConfiguration getResolutionConfiguration();
-
- /**
- * @return the RefactoringSupport used to provide refactoring for inferred
- * types, or null if it is not offered.
- */
- public RefactoringSupport getRefactoringSupport();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferrenceSupportExtension.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferrenceSupportExtension.java
deleted file mode 100644
index faafd958..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferrenceSupportExtension.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.infer;
-
-
-/**
- *
- *
- *
- * 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 InferrenceSupportExtension {
- public InferrenceProvider inferProvider;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/RefactoringSupport.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/RefactoringSupport.java
deleted file mode 100644
index f29ea067..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/RefactoringSupport.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008 IBM Corporation and others.
- * All rights reserved. This program and 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;
-
-
-/**
- * Support for refactoring of inferred types
- *
- * 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 RefactoringSupport {
-
- /**
- * @return a ImportRewriteSupport instance if it is desired to participate in import writing
- *
- * @see ImportRewriteSupport
- */
- public ImportRewriteSupport getImportRewriteSupport()
- {
- return null;
- }
-
- /**
- * Determines if the inferred classes can safely be renamed.
- *
- * @return true if the inferred class can safely be renamed
- *
- */
-
- public boolean supportsClassRename()
- {
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/ResolutionConfiguration.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/ResolutionConfiguration.java
deleted file mode 100644
index bc48f689..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/ResolutionConfiguration.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.core.infer;
-
-/**
- * This class provides configuration information for when the inferred class
- * gets resolved
- *
- * 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 ResolutionConfiguration {
-
-
- /**
- * Get the default list of files to be looked at when resolving
- * a name
- * @return a list of file paths as strings, relative to the JavaScript project root
- */
- public String [] getContextIncludes()
- {
- return null;
- }
-
- /**
- * Determine if all files in include path should be searched to resolve a name.
- * If false, names will be resolved using only libraries, imports, and context includes
- *
- * @return true
- */
- public boolean searchAllFiles()
- {
- return true;
- }
-
-}
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
deleted file mode 100644
index 362b8498..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/messages.properties
+++ /dev/null
@@ -1,11 +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
-###############################################################################
-LibrarySuperType.0={0}() in {1}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/FieldDeclarationMatch.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/FieldDeclarationMatch.java
deleted file mode 100644
index 12ecf7a4..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/FieldDeclarationMatch.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*******************************************************************************
- * 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.resources.IResource;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-
-/**
- * A JavaScript search match that represents a field declaration.
- * The element is an <code>IField</code>.
- * <p>
- * This class is intended to be instantiated and subclassed by clients.
- * </p>
- *
- * 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 FieldDeclarationMatch extends SearchMatch {
-
- /**
- * Creates a new field declaration match.
- *
- * @param element the field declaration
- * @param accuracy one of A_ACCURATE or A_INACCURATE
- * @param offset the offset the match starts at, or -1 if unknown
- * @param length the length of the match, or -1 if unknown
- * @param participant the search participant that created the match
- * @param resource the resource of the element
- */
- public FieldDeclarationMatch(IJavaScriptElement element, int accuracy, int offset, int length, SearchParticipant participant, IResource resource) {
- super(element, accuracy, offset, length, participant, resource);
- }
-}
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
deleted file mode 100644
index 0d2dd768..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/FieldReferenceMatch.java
+++ /dev/null
@@ -1,74 +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.core.search;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-
-/**
- * A JavaScript search match that represents a field reference.
- * The element is the inner-most enclosing member that references this field.
- * <p>
- * This class is intended to be instantiated and subclassed by clients.
- * </p>
- *
- * 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 FieldReferenceMatch extends SearchMatch {
-
- private boolean isReadAccess;
- private boolean isWriteAccess;
-
- /**
- * Creates a new field reference match.
- *
- * @param enclosingElement the inner-most enclosing member that references this field
- * @param accuracy one of {@link #A_ACCURATE} or {@link #A_INACCURATE}
- * @param offset the offset the match starts at, or -1 if unknown
- * @param length the length of the match, or -1 if unknown
- * @param isReadAccess whether the match represents a read access
- * @param isWriteAccess whether the match represents a write access
- * @param insideDocComment <code>true</code> if this search match is inside a doc
- * comment, and <code>false</code> otherwise
- * @param participant the search participant that created the match
- * @param resource the resource of the element
- */
- public FieldReferenceMatch(IJavaScriptElement enclosingElement, int accuracy, int offset, int length, boolean isReadAccess, boolean isWriteAccess, boolean insideDocComment, SearchParticipant participant, IResource resource) {
- super(enclosingElement, accuracy, offset, length, participant, resource);
- this.isReadAccess = isReadAccess;
- this.isWriteAccess = isWriteAccess;
- setInsideDocComment(insideDocComment);
- }
-
- /**
- * Returns whether the field reference is a read access to the field.
- * Note that a field reference can be read and written at once in case of compound assignments (e.g. i += 0;)
- *
- * @return whether the field reference is a read access to the field.
- */
- public final boolean isReadAccess() {
- return this.isReadAccess;
- }
-
- /**
- * Returns whether the field reference is a write access to the field.
- * Note that a field reference can be read and written at once in case of compound assignments (e.g. i += 0;)
- *
- * @return whether the field reference is a write access to the field.
- */
- public final boolean isWriteAccess() {
- return this.isWriteAccess;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/IJavaScriptSearchConstants.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/IJavaScriptSearchConstants.java
deleted file mode 100644
index baf90405..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/IJavaScriptSearchConstants.java
+++ /dev/null
@@ -1,175 +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.core.search;
-
-import org.eclipse.wst.jsdt.internal.core.search.processing.IJob;
-
-/**
- * <p>
- * This interface defines the constants used by the search engine.
- * </p>
- * <p>
- * This interface declares constants only; it is not intended to be implemented.
- * </p>
- * @see org.eclipse.wst.jsdt.core.search.SearchEngine
- *
- * 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 IJavaScriptSearchConstants {
-
- /**
- * The nature of searched element or the nature
- * of match in unknown.
- */
- int UNKNOWN = -1;
-
- /* Nature of searched element */
-
- /**
- * The searched element is a type, which may include classes, interfaces,
- * enums, and annotation types.
- */
- int TYPE= 0;
-
- /**
- * The searched element is a method.
- */
- int METHOD= 1;
-
- /**
- * The searched element is a package.
- */
- int PACKAGE= 2;
-
- /**
- * The searched element is a constructor.
- */
- int CONSTRUCTOR= 3;
-
- /**
- * The searched element is a field.
- */
- int FIELD= 4;
-
- /**
- * The searched element is a class.
- * More selective than using {@link #TYPE}.
- */
- int CLASS= 5;
-
- /**
- * The searched element is an enum.
- * More selective than using {@link #TYPE}.
- *
- */
- int ENUM= 7;
-
- /**
- * The searched element is a field.
- */
- int VAR= 12;
- int FUNCTION= 13;
-
- /* Nature of match */
-
- /**
- * The search result is a declaration.
- * Can be used in conjunction with any of the nature of searched elements
- * so as to better narrow down the search.
- */
- int DECLARATIONS= 0;
-
- /**
- * The search result is a type that extends a class.
- * Used in conjunction with either TYPE or CLASS, it will
- * respectively search for any type extending a type,
- * or rather exclusively search for classes extending the type.
- */
- int IMPLEMENTORS= 1;
-
- /**
- * The search result is a reference.
- * Can be used in conjunction with any of the nature of searched elements
- * so as to better narrow down the search.
- * References can contain implementers since they are more generic kind
- * of matches.
- */
- int REFERENCES= 2;
-
- /**
- * The search result is a declaration, a reference, or an implementer
- * of an interface.
- * Can be used in conjunction with any of the nature of searched elements
- * so as to better narrow down the search.
- */
- int ALL_OCCURRENCES= 3;
-
- /**
- * When searching for field matches, it will exclusively find read accesses, as
- * opposed to write accesses. Note that some expressions are considered both
- * as field read/write accesses: for example, x++; x+= 1;
- *
- *
- */
- int READ_ACCESSES = 4;
-
- /**
- * When searching for field matches, it will exclusively find write accesses, as
- * opposed to read accesses. Note that some expressions are considered both
- * as field read/write accesses: for example, x++; x+= 1;
- *
- *
- */
- int WRITE_ACCESSES = 5;
-
- /**
- * Ignore declaring type while searching result.
- * Can be used in conjunction with any of the nature of match.
- *
- */
- int IGNORE_DECLARING_TYPE = 0x10;
-
- /**
- * Ignore return type while searching result.
- * Can be used in conjunction with any of the nature of match.
- * Note that:
- * <ul>
- * <li>for fields search, pattern will ignore field type</li>
- * <li>this flag will have no effect for types search</li>
- * </ul>
- *
- */
- int IGNORE_RETURN_TYPE = 0x20;
-
- /* Syntactic match modes */
-
- /**
- * The search operation starts immediately, even if the underlying indexer
- * has not finished indexing the workspace. Results will more likely
- * not contain all the matches.
- */
- int FORCE_IMMEDIATE_SEARCH = IJob.ForceImmediate;
- /**
- * The search operation throws an <code>org.eclipse.core.runtime.OperationCanceledException</code>
- * if the underlying indexer has not finished indexing the workspace.
- */
- int CANCEL_IF_NOT_READY_TO_SEARCH = IJob.CancelIfNotReady;
- /**
- * The search operation waits for the underlying indexer to finish indexing
- * the workspace before starting the search.
- */
- int WAIT_UNTIL_READY_TO_SEARCH = IJob.WaitUntilReady;
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/IJavaScriptSearchScope.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/IJavaScriptSearchScope.java
deleted file mode 100644
index f8fcd398..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/IJavaScriptSearchScope.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*******************************************************************************
- * 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.IPath;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-
-/**
- * An <code>IJavaScriptSearchScope</code> defines where search result should be found by a
- * <code>SearchEngine</code>. Clients must pass an instance of this interface
- * to the <code>search(...)</code> methods. Such an instance can be created using the
- * following factory methods on <code>SearchEngine</code>: <code>createHierarchyScope(IType)</code>,
- * <code>createJavaSearchScope(IResource[])</code>, <code>createWorkspaceScope()</code>, or
- * clients may choose to implement this interface.
- *
- * 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 IJavaScriptSearchScope {
-/**
- * This constant defines the separator of the resourcePath string of the <code>encloses(String)</code>
- * method. If present in the string, it separates the path to the jar file from the path
- * to the .class file in the jar.
- */
-String JAR_FILE_ENTRY_SEPARATOR = "|"; //$NON-NLS-1$
-/**
- * Include type constant (bit mask) indicating that source folders should be considered in the search scope.
- *
- */
-int SOURCES = 1;
-/**
- * Include type constant (bit mask) indicating that application libraries should be considered in the search scope.
- *
- */
-int APPLICATION_LIBRARIES = 2;
-/**
- * Include type constant (bit mask) indicating that system libraries should be considered in the search scope.
- *
- */
-int SYSTEM_LIBRARIES = 4;
-/**
- * Include type constant (bit mask) indicating that referenced projects should be considered in the search scope.
- *
- */
-int REFERENCED_PROJECTS = 8;
-/**
- * Checks whether the resource at the given path is enclosed by this scope.
- *
- * @param resourcePath if the resource is contained in
- * a JAR file, the path is composed of 2 paths separated
- * by <code>JAR_FILE_ENTRY_SEPARATOR</code>: the first path is the full OS path
- * to the JAR (if it is an external JAR), or the workspace relative <code>IPath</code>
- * to the JAR (if it is an internal JAR),
- * the second path is the path to the resource inside the JAR.
- * @return whether the resource is enclosed by this scope
- */
-public boolean encloses(String resourcePath);
-/**
- * Checks whether this scope encloses the given element.
- *
- * @param element the given element
- * @return <code>true</code> if the element is in this scope
- */
-public boolean encloses(IJavaScriptElement element);
-/**
- * Returns the paths to the enclosing projects and JARs for this search scope.
- * <ul>
- * <li> If the path is a project path, this is the full path of the project
- * (see <code>IResource.getFullPath()</code>).
- * For example, /MyProject
- * </li>
- * <li> If the path is a JAR path and this JAR is internal to the workspace,
- * this is the full path of the JAR file (see <code>IResource.getFullPath()</code>).
- * For example, /MyProject/mylib.jar
- * </li>
- * <li> If the path is a JAR path and this JAR is external to the workspace,
- * this is the full OS path to the JAR file on the file system.
- * For example, d:\libs\mylib.jar
- * </li>
- * </ul>
- *
- * @return an array of paths to the enclosing projects and JARS.
- */
-IPath[] enclosingProjectsAndJars();
-public boolean shouldExclude(String container, String resourceName);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/LocalVariableDeclarationMatch.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/LocalVariableDeclarationMatch.java
deleted file mode 100644
index 02a2c8a3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/LocalVariableDeclarationMatch.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*******************************************************************************
- * 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.resources.IResource;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-
-/**
- * A JavaScript search match that represents a local variable declaration.
- * The element is an <code>ILocalVariable</code>.
- * <p>
- * This class is intended to be instantiated and subclassed by clients.
- * </p>
- *
- * 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 LocalVariableDeclarationMatch extends SearchMatch {
-
- /**
- * Creates a new local variable declaration match.
- *
- * @param element the local variable declaration
- * @param accuracy one of A_ACCURATE or A_INACCURATE
- * @param offset the offset the match starts at, or -1 if unknown
- * @param length the length of the match, or -1 if unknown
- * @param participant the search participant that created the match
- * @param resource the resource of the element
- */
- public LocalVariableDeclarationMatch(IJavaScriptElement element, int accuracy, int offset, int length, SearchParticipant participant, IResource resource) {
- super(element, accuracy, offset, length, participant, resource);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/LocalVariableReferenceMatch.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/LocalVariableReferenceMatch.java
deleted file mode 100644
index 223348b4..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/LocalVariableReferenceMatch.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*******************************************************************************
- * 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.resources.IResource;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-
-/**
- * A JavaScript search match that represents a local variable reference.
- * The element is the inner-most enclosing member that references this local variable.
- * <p>
- * This class is intended to be instantiated and subclassed by clients.
- * </p>
- *
- * 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 LocalVariableReferenceMatch extends SearchMatch {
-
- private boolean isReadAccess;
- private boolean isWriteAccess;
-
- /**
- * Creates a new local variable reference match.
- *
- * @param enclosingElement the inner-most enclosing member that references this local variable
- * @param accuracy one of {@link #A_ACCURATE} or {@link #A_INACCURATE}
- * @param offset the offset the match starts at, or -1 if unknown
- * @param length the length of the match, or -1 if unknown
- * @param isReadAccess whether the match represents a read access
- * @param isWriteAccess whethre the match represents a write access
- * @param insideDocComment <code>true</code> if this search match is inside a doc
- * comment, and <code>false</code> otherwise
- * @param participant the search participant that created the match
- * @param resource the resource of the element
- */
- public LocalVariableReferenceMatch(IJavaScriptElement enclosingElement, int accuracy, int offset, int length, boolean isReadAccess, boolean isWriteAccess, boolean insideDocComment, SearchParticipant participant, IResource resource) {
- super(enclosingElement, accuracy, offset, length, participant, resource);
- this.isReadAccess = isReadAccess;
- this.isWriteAccess = isWriteAccess;
- setInsideDocComment(insideDocComment);
- }
-
- /**
- * Returns whether the local variable reference is a read access to the variable.
- * Note that a local variable reference can be read and written at once in case of compound assignments (e.g. i += 0;)
- *
- * @return whether the local variable reference is a read access to the variable.
- */
- public final boolean isReadAccess() {
- return this.isReadAccess;
- }
-
- /**
- * Returns whether the local variable reference is a write access to the variable.
- * Note that a local variable reference can be read and written at once in case of compound assignments (e.g. i += 0;)
- *
- * @return whether the local variable reference is a write access to the variable.
- */
- public final boolean isWriteAccess() {
- return this.isWriteAccess;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/MethodDeclarationMatch.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/MethodDeclarationMatch.java
deleted file mode 100644
index 109e00af..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/MethodDeclarationMatch.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*******************************************************************************
- * 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.resources.IResource;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-
-/**
- * A JavaScript search match that represents a method declaration.
- * The element is an <code>IFunction</code>.
- * <p>
- * This class is intended to be instantiated and subclassed by clients.
- * </p>
- *
- * 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 MethodDeclarationMatch extends SearchMatch {
-
- /**
- * Creates a new method declaration match.
- *
- * @param element the method declaration
- * @param accuracy one of A_ACCURATE or A_INACCURATE
- * @param offset the offset the match starts at, or -1 if unknown
- * @param length the length of the match, or -1 if unknown
- * @param participant the search participant that created the match
- * @param resource the resource of the element
- */
- public MethodDeclarationMatch(IJavaScriptElement element, int accuracy, int offset, int length, SearchParticipant participant, IResource resource) {
- super(element, accuracy, offset, length, participant, resource);
- }
-
-}
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
deleted file mode 100644
index f16e447e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/MethodReferenceMatch.java
+++ /dev/null
@@ -1,113 +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.core.search;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-
-/**
- * A JavaScript search match that represents a method reference.
- * The element is the inner-most enclosing member that references this method.
- * <p>
- * This class is intended to be instantiated and subclassed by clients.
- * </p>
- *
- * 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 MethodReferenceMatch extends SearchMatch {
- private boolean constructor;
- private boolean superInvocation;
-
- /**
- * Creates a new method reference match.
- *
- * @param enclosingElement the inner-most enclosing member that references this method
- * @param accuracy one of {@link #A_ACCURATE} or {@link #A_INACCURATE}
- * @param offset the offset the match starts at, or -1 if unknown
- * @param length the length of the match, or -1 if unknown
- * @param insideDocComment <code>true</code> if this search match is inside a doc
- * comment, and <code>false</code> otherwise
- * @param participant the search participant that created the match
- * @param resource the resource of the element
- */
- public MethodReferenceMatch(IJavaScriptElement enclosingElement, int accuracy, int offset, int length, boolean insideDocComment, SearchParticipant participant, IResource resource) {
- super(enclosingElement, accuracy, offset, length, participant, resource);
- setInsideDocComment(insideDocComment);
- }
-
- /**
- * Creates a new method reference match.
- *
- * @param enclosingElement the inner-most enclosing member that references this method
- * @param accuracy one of {@link #A_ACCURATE} or {@link #A_INACCURATE}
- * @param offset the offset the match starts at, or -1 if unknown
- * @param length the length of the match, or -1 if unknown
- * @param constructor <code>true</code> if this search match a constructor
- * <code>false</code> otherwise
- * @param insideDocComment <code>true</code> if this search match is inside a doc
- * comment, and <code>false</code> otherwise
- * @param participant the search participant that created the match
- * @param resource the resource of the element
- *
- */
- public MethodReferenceMatch(IJavaScriptElement enclosingElement, int accuracy, int offset, int length, boolean constructor, boolean insideDocComment, SearchParticipant participant, IResource resource) {
- this(enclosingElement, accuracy, offset, length, insideDocComment, participant, resource);
- this.constructor = constructor;
- }
-
- /**
- * Creates a new method reference match.
- *
- * @param enclosingElement the inner-most enclosing member that references this method
- * @param accuracy one of {@link #A_ACCURATE} or {@link #A_INACCURATE}
- * @param offset the offset the match starts at, or -1 if unknown
- * @param length the length of the match, or -1 if unknown
- * @param constructor <code>true</code> if this search matches a constructor
- * <code>false</code> otherwise
- * @param superInvocation <code>true</code> if this search matches a super-type invocation
- * element <code>false</code> otherwise
- * @param insideDocComment <code>true</code> if this search match is inside a doc
- * comment, and <code>false</code> otherwise
- * @param participant the search participant that created the match
- * @param resource the resource of the element
- *
- */
- public MethodReferenceMatch(IJavaScriptElement enclosingElement, int accuracy, int offset, int length, boolean constructor, boolean superInvocation, boolean insideDocComment, SearchParticipant participant, IResource resource) {
- this(enclosingElement, accuracy, offset, length, constructor, insideDocComment, participant, resource);
- this.superInvocation = superInvocation;
- }
-
- /**
- * Returns whether the reference is on a constructor.
- *
- * @return Returns whether the reference is on a constructor or not.
- *
- */
- public final boolean isConstructor() {
- return this.constructor;
- }
-
- /**
- * Returns whether the reference is on a message sent from a type
- * which is a super type of the searched method declaring type.
- * If <code>true</code>, the method called at run-time may or may not be
- * the search target, depending on the run-time type of the receiver object.
- *
- * @return <code>true</code> if the reference is on a message sent from
- * a super-type of the searched method declaring class, <code>false </code> otherwise
- */
- public boolean isSuperInvocation() {
- return this.superInvocation;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/PackageReferenceMatch.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/PackageReferenceMatch.java
deleted file mode 100644
index 959cc6b4..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/PackageReferenceMatch.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*******************************************************************************
- * 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.resources.IResource;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-
-/**
- * A JavaScript search match that represents a package reference.
- * The element is the inner-most enclosing member that references this package.
- * <p>
- * This class is intended to be instantiated and subclassed by clients.
- * </p>
- *
- * 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 PackageReferenceMatch extends SearchMatch {
-
- /**
- * Creates a new package reference match.
- *
- * @param enclosingElement the inner-most enclosing member that references this package
- * @param accuracy one of {@link #A_ACCURATE} or {@link #A_INACCURATE}
- * @param offset the offset the match starts at, or -1 if unknown
- * @param length the length of the match, or -1 if unknown
- * @param insideDocComment <code>true</code> if this search match is inside a doc
- * comment, and <code>false</code> otherwise
- * @param participant the search participant that created the match
- * @param resource the resource of the element
- */
- public PackageReferenceMatch(IJavaScriptElement enclosingElement, int accuracy, int offset, int length, boolean insideDocComment, SearchParticipant participant, IResource resource) {
- super(enclosingElement, accuracy, offset, length, participant, resource);
- setInsideDocComment(insideDocComment);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/SearchDocument.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/SearchDocument.java
deleted file mode 100644
index cf03707b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/SearchDocument.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/*******************************************************************************
- * 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.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.core.search.indexing.InternalSearchDocument;
-
-/**
- * A search document encapsulates a content to be either indexed or searched in.
- * A search particpant creates a search document.
- * <p>
- * This class is intended to be subclassed by clients.
- * </p>
- *
- * 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 SearchDocument extends InternalSearchDocument {
- private String documentPath;
- private SearchParticipant participant;
-
- /**
- * Creates a new search document. The given document path is a string that uniquely identifies the document.
- * Most of the time it is a workspace-relative path, but it can also be a file system path, or a path inside a zip file.
- *
- * @param documentPath the path to the document,
- * or <code>null</code> if none
- * @param participant the participant that creates the search document
- */
- protected SearchDocument(String documentPath, SearchParticipant participant) {
- this.documentPath = documentPath;
- this.participant = participant;
- }
-
- /**
- * Adds the given index entry (category and key) coming from this
- * document to the index. This method must be called from
- * {@link SearchParticipant#indexDocument(SearchDocument document, org.eclipse.core.runtime.IPath indexPath)}.
- *
- * @param category the category of the index entry
- * @param key the key of the index entry
- */
- public void addIndexEntry(char[] category, char[] key) {
- super.addIndexEntry(category, key);
- }
-
- /**
- * Returns the contents of this document.
- * Contents may be different from actual resource at corresponding document path,
- * in case of preprocessing.
- * <p>
- * This method must be implemented in subclasses.
- * </p><p>
- * Note: some implementation may choose to cache the contents directly on the
- * document for performance reason. However, this could induce scalability issues due
- * to the fact that collections of documents are manipulated throughout the search
- * operation, and cached contents would then consume lots of memory until they are
- * all released at once in the end.
- * </p>
- *
- * @return the contents of this document,
- * or <code>null</code> if none
- */
- public abstract byte[] getByteContents();
-
- /**
- * Returns the contents of this document.
- * Contents may be different from actual resource at corresponding document
- * path due to preprocessing.
- * <p>
- * This method must be implemented in subclasses.
- * </p><p>
- * Note: some implementation may choose to cache the contents directly on the
- * document for performance reason. However, this could induce scalability issues due
- * to the fact that collections of documents are manipulated throughout the search
- * operation, and cached contents would then consume lots of memory until they are
- * all released at once in the end.
- * </p>
- *
- * @return the contents of this document,
- * or <code>null</code> if none
- */
- public abstract char[] getCharContents();
-
- /**
- * Returns the encoding for this document.
- * <p>
- * This method must be implemented in subclasses.
- * </p>
- *
- * @return the encoding for this document,
- * or <code>null</code> if none
- */
- public abstract String getEncoding();
-
- /**
- * Returns the participant that created this document.
- *
- * @return the participant that created this document
- */
- public final SearchParticipant getParticipant() {
- return this.participant;
- }
-
- /**
- * Returns the path to the original document to publicly mention in index
- * or search results. This path is a string that uniquely identifies the document.
- * Most of the time it is a workspace-relative path, but it can also be a file system path,
- * or a path inside a zip file.
- *
- * @return the path to the document
- */
- public final String getPath() {
- return this.documentPath;
- }
- /**
- * Removes all index entries from the index for the given document.
- * This method must be called from
- * {@link SearchParticipant#indexDocument(SearchDocument document, org.eclipse.core.runtime.IPath indexPath)}.
- */
- public void removeAllIndexEntries() {
- super.removeAllIndexEntries();
- }
-
- public boolean isVirtual() {
- return false;
-
- }
- public IJavaScriptElement getJavaElement() {
- return null;
-
- }
-}
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
deleted file mode 100644
index 220ffbbd..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/SearchEngine.java
+++ /dev/null
@@ -1,631 +0,0 @@
-/*******************************************************************************
- * 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.
- * <p>
- * 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)}.
- * </p>
- * <p>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.
- * </p>
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- * 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.
- * <p>
- * Note that passing an empty working copy will be as if the original compilation
- * unit had been deleted.</p>
- * <p>
- * 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.
- * <p>
- * 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.</p>
- * <p>
- * In other words, this is equivalent to using SearchEngine.createJavaSearchScope(elements, true).</p>
- *
- * @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:
- * <ul>
- * <li>the includepath is incorrectly set</li>
- * </ul>
- *
- */
- 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 <code>null</code>, 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 <code>null</code>, then any type name is accepted.
- * @param packageMatchRule one of
- * <ul>
- * <li>{@link SearchPattern#R_EXACT_MATCH} if the package name and type name are the full names
- * of the searched types.</li>
- * <li>{@link SearchPattern#R_PREFIX_MATCH} if the package name and type name are prefixes of the names
- * of the searched types.</li>
- * <li>{@link SearchPattern#R_PATTERN_MATCH} if the package name and type name contain wild-cards.</li>
- * <li>{@link SearchPattern#R_CAMELCASE_MATCH} if type name are camel case of the names of the searched types.</li>
- * </ul>
- * 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
- * <ul>
- * <li>{@link SearchPattern#R_EXACT_MATCH} if the package name and type name are the full names
- * of the searched types.</li>
- * <li>{@link SearchPattern#R_PREFIX_MATCH} if the package name and type name are prefixes of the names
- * of the searched types.</li>
- * <li>{@link SearchPattern#R_PATTERN_MATCH} if the package name and type name contain wild-cards.</li>
- * <li>{@link SearchPattern#R_CAMELCASE_MATCH} if type name are camel case of the names of the searched types.</li>
- * </ul>
- * 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
- * <ul>
- * <li>{@link IJavaScriptSearchConstants#CLASS}: only look for classes</li>
- * <li>{@link IJavaScriptSearchConstants#INTERFACE}: only look for interfaces</li>
- * <li>{@link IJavaScriptSearchConstants#ENUM}: only look for enumeration</li>
- * <li>{@link IJavaScriptSearchConstants#ANNOTATION_TYPE}: only look for annotation type</li>
- * <li>{@link IJavaScriptSearchConstants#CLASS_AND_ENUM}: only look for classes and enumerations</li>
- * <li>{@link IJavaScriptSearchConstants#CLASS_AND_INTERFACE}: only look for classes and interfaces</li>
- * <li>{@link IJavaScriptSearchConstants#TYPE}: look for all types (ie. classes, interfaces, enum and annotation types)</li>
- * </ul>
- * @param scope the scope to search in
- * @param nameRequestor the requestor that collects the results of the search
- * @param waitingPolicy one of
- * <ul>
- * <li>{@link IJavaScriptSearchConstants#FORCE_IMMEDIATE_SEARCH} if the search should start immediately</li>
- * <li>{@link IJavaScriptSearchConstants#CANCEL_IF_NOT_READY_TO_SEARCH} if the search should be cancelled if the
- * underlying indexer has not finished indexing the workspace</li>
- * <li>{@link IJavaScriptSearchConstants#WAIT_UNTIL_READY_TO_SEARCH} if the search should wait for the
- * underlying indexer to finish indexing the workspace</li>
- * </ul>
- * @param progressMonitor the progress monitor to report progress to, or <code>null</code> if no progress
- * monitor is provided
- * @exception JavaScriptModelException if the search failed. Reasons include:
- * <ul>
- * <li>the includepath is incorrectly set</li>
- * </ul>
- *
- */
- 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).
- * <p>
- * Provided {@link TypeNameMatchRequestor} requestor will collect {@link TypeNameMatch}
- * matches found during the search.
- * </p>
- *
- * @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 <code>null</code>, then any package name is accepted.
- * @param packageMatchRule one of
- * <ul>
- * <li>{@link SearchPattern#R_EXACT_MATCH} if the package name and type name are the full names
- * of the searched types.</li>
- * <li>{@link SearchPattern#R_PREFIX_MATCH} if the package name and type name are prefixes of the names
- * of the searched types.</li>
- * <li>{@link SearchPattern#R_PATTERN_MATCH} if the package name and type name contain wild-cards.</li>
- * <li>{@link SearchPattern#R_CAMELCASE_MATCH} if type name are camel case of the names of the searched types.</li>
- * </ul>
- * 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 <code>null</code>, then any type name is accepted.
- * @param typeMatchRule one of
- * <ul>
- * <li>{@link SearchPattern#R_EXACT_MATCH} if the package name and type name are the full names
- * of the searched types.</li>
- * <li>{@link SearchPattern#R_PREFIX_MATCH} if the package name and type name are prefixes of the names
- * of the searched types.</li>
- * <li>{@link SearchPattern#R_PATTERN_MATCH} if the package name and type name contain wild-cards.</li>
- * <li>{@link SearchPattern#R_CAMELCASE_MATCH} if type name are camel case of the names of the searched types.</li>
- * </ul>
- * 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
- * <ul>
- * <li>{@link IJavaScriptSearchConstants#CLASS}: only look for classes</li>
- * <li>{@link IJavaScriptSearchConstants#INTERFACE}: only look for interfaces</li>
- * <li>{@link IJavaScriptSearchConstants#ENUM}: only look for enumeration</li>
- * <li>{@link IJavaScriptSearchConstants#ANNOTATION_TYPE}: only look for annotation type</li>
- * <li>{@link IJavaScriptSearchConstants#CLASS_AND_ENUM}: only look for classes and enumerations</li>
- * <li>{@link IJavaScriptSearchConstants#CLASS_AND_INTERFACE}: only look for classes and interfaces</li>
- * <li>{@link IJavaScriptSearchConstants#TYPE}: look for all types (ie. classes, interfaces, enum and annotation types)</li>
- * </ul>
- * @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
- * <ul>
- * <li>{@link IJavaScriptSearchConstants#FORCE_IMMEDIATE_SEARCH} if the search should start immediately</li>
- * <li>{@link IJavaScriptSearchConstants#CANCEL_IF_NOT_READY_TO_SEARCH} if the search should be cancelled if the
- * underlying indexer has not finished indexing the workspace</li>
- * <li>{@link IJavaScriptSearchConstants#WAIT_UNTIL_READY_TO_SEARCH} if the search should wait for the
- * underlying indexer to finish indexing the workspace</li>
- * </ul>
- * @param progressMonitor the progress monitor to report progress to, or <code>null</code> if no progress
- * monitor is provided
- * @exception JavaScriptModelException if the search failed. Reasons include:
- * <ul>
- * <li>the includepath is incorrectly set</li>
- * </ul>
- *
- */
- 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 <code>null</code>, then any package name is accepted.
- * @param typeNames the simple names of the searched types.
- * If this parameter is <code>null</code>, 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
- * <ul>
- * <li>{@link IJavaScriptSearchConstants#FORCE_IMMEDIATE_SEARCH} if the search should start immediately</li>
- * <li>{@link IJavaScriptSearchConstants#CANCEL_IF_NOT_READY_TO_SEARCH} if the search should be cancelled if the
- * underlying indexer has not finished indexing the workspace</li>
- * <li>{@link IJavaScriptSearchConstants#WAIT_UNTIL_READY_TO_SEARCH} if the search should wait for the
- * underlying indexer to finish indexing the workspace</li>
- * </ul>
- * @param progressMonitor the progress monitor to report progress to, or <code>null</code> if no progress
- * monitor is provided
- * @exception JavaScriptModelException if the search failed. Reasons include:
- * <ul>
- * <li>the includepath is incorrectly set</li>
- * </ul>
- *
- */
- 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.
- * <p>
- * Provided {@link TypeNameMatchRequestor} requestor will collect {@link TypeNameMatch}
- * matches found during the search.
- * </p>
- *
- * @param qualifications the qualified name of the package/enclosing type of the searched types.
- * May be <code>null</code>, then any package name is accepted.
- * @param typeNames the simple names of the searched types.
- * If this parameter is <code>null</code>, 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
- * <ul>
- * <li>{@link IJavaScriptSearchConstants#FORCE_IMMEDIATE_SEARCH} if the search should start immediately</li>
- * <li>{@link IJavaScriptSearchConstants#CANCEL_IF_NOT_READY_TO_SEARCH} if the search should be cancelled if the
- * underlying indexer has not finished indexing the workspace</li>
- * <li>{@link IJavaScriptSearchConstants#WAIT_UNTIL_READY_TO_SEARCH} if the search should wait for the
- * underlying indexer to finish indexing the workspace</li>
- * </ul>
- * @param progressMonitor the progress monitor to report progress to, or <code>null</code> if no progress
- * monitor is provided
- * @exception JavaScriptModelException if the search failed. Reasons include:
- * <ul>
- * <li>the includepath is incorrectly set</li>
- * </ul>
- *
- */
- 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.
- * <p>
- * Consider the following code:
- * <code>
- * <pre>
- * 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);
- * };
- * }
- * </pre>
- * </code>
- * then searching for declarations of accessed fields in method
- * <code>X.test()</code> would collect the fields
- * <code>B.value</code> and <code>A.field1</code>.
- * </p>
- *
- * @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:
- * <ul>
- * <li>the element doesn't exist</li>
- * <li>the includepath is incorrectly set</li>
- * </ul>
- *
- */
- 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.
- * <p>
- * Consider the following code:
- * <code>
- * <pre>
- * class A {
- * }
- * class B extends A {
- * }
- * interface I {
- * int VALUE = 0;
- * }
- * class X {
- * void test() {
- * B b = new B();
- * this.foo(b, I.VALUE);
- * };
- * }
- * </pre>
- * </code>
- * then searching for declarations of referenced types in method <code>X.test()</code>
- * would collect the class <code>B</code> and the interface <code>I</code>.
- * </p>
- *
- * @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:
- * <ul>
- * <li>the element doesn't exist</li>
- * <li>the includepath is incorrectly set</li>
- * </ul>
- *
- */
- 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.
- * <p>
- * Consider the following code:
- * <code>
- * <pre>
- * 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();
- * };
- * }
- * </pre>
- * </code>
- * then searching for declarations of sent messages in method
- * <code>X.test()</code> would collect the methods
- * <code>A.foo()</code>, <code>B.foo()</code>, and <code>A.bar()</code>.
- * </p>
- *
- * @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:
- * <ul>
- * <li>the element doesn't exist</li>
- * <li>the includepath is incorrectly set</li>
- * </ul>
- *
- */
- public void searchDeclarationsOfSentMessages(IJavaScriptElement enclosingElement, SearchRequestor requestor, IProgressMonitor monitor) throws JavaScriptModelException {
- this.basicEngine.searchDeclarationsOfSentMessages(enclosingElement, requestor, monitor);
- }
-}
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
deleted file mode 100644
index ea8c6e42..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/SearchMatch.java
+++ /dev/null
@@ -1,380 +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.core.search;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.core.JavaElement;
-
-/**
- * A search match represents the result of a search query.
- *
- * Search matches may be accurate (<code>A_ACCURATE</code>) or they might be
- * merely potential matches (<code>A_INACCURATE</code>). The latter occurs when
- * a compile-time problem prevents the search engine from completely resolving
- * the match.
- * <p>
- * This class is intended to be instantiated and subclassed by clients.
- * </p>
- *
- * @see SearchEngine#search(SearchPattern, SearchParticipant[], IJavaScriptSearchScope, SearchRequestor, org.eclipse.core.runtime.IProgressMonitor)
- *
- * 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 SearchMatch {
-
- /**
- * The search result corresponds an exact match of the search pattern.
- *
- * @see #getAccuracy()
- */
- public static final int A_ACCURATE = 0;
-
- /**
- * The search result is potentially a match for the search pattern,
- * but the search engine is unable to fully check it (for example, because
- * there are errors in the code or the includepath are not correctly set).
- *
- * @see #getAccuracy()
- */
- public static final int A_INACCURATE = 1;
-
- private Object element;
- private int length;
- private int offset;
-
- private int accuracy;
- private SearchParticipant participant;
- private IResource resource;
-
- private boolean insideDocComment = false;
-
- // store the rule used while reporting the match
- private final static int ALL_GENERIC_FLAVORS = SearchPattern.R_FULL_MATCH |
- SearchPattern.R_EQUIVALENT_MATCH |
- SearchPattern.R_ERASURE_MATCH;
- private int rule = ALL_GENERIC_FLAVORS;
-
- // store other necessary information
- private boolean raw = false;
- private boolean implicit = false;
-
- /**
- * Creates a new search match.
- * <p>
- * Note that <code>isInsideDocComment()</code> defaults to false.
- * </p>
- *
- * @param element the element that encloses or corresponds to the match,
- * or <code>null</code> if none
- * @param accuracy one of {@link #A_ACCURATE} or {@link #A_INACCURATE}
- * @param offset the offset the match starts at, or -1 if unknown
- * @param length the length of the match, or -1 if unknown
- * @param participant the search participant that created the match
- * @param resource the resource of the element, or <code>null</code> if none
- */
- public SearchMatch(
- IJavaScriptElement element,
- int accuracy,
- int offset,
- int length,
- SearchParticipant participant,
- IResource resource) {
- this.element = element;
- this.offset = offset;
- this.length = length;
- this.accuracy = accuracy & A_INACCURATE;
- if (accuracy > A_INACCURATE) {
- int genericFlavors = accuracy & ALL_GENERIC_FLAVORS;
- if (genericFlavors > 0) {
- this.rule &= ~ALL_GENERIC_FLAVORS; // reset generic flavors
- }
- this.rule |= accuracy & ~A_INACCURATE; // accuracy may have also some rule information
- }
- this.participant = participant;
- this.resource = resource;
- }
-
- /**
- * Returns the accuracy of this search match.
- *
- * @return one of {@link #A_ACCURATE} or {@link #A_INACCURATE}
- */
- public final int getAccuracy() {
- return this.accuracy;
- }
-
- /**
- * Returns the element of this search match.
- * In case of a reference match, this is the inner-most enclosing element of the reference.
- * In case of a declaration match, this is the declaration.
- *
- * @return the element of the search match, or <code>null</code> if none
- */
- public final Object getElement() {
- return this.element;
- }
-
- /**
- * Returns the length of this search match.
- *
- * @return the length of this search match, or -1 if unknown
- */
- public final int getLength() {
- return this.length;
- }
-
- /**
- * Returns the offset of this search match.
- *
- * @return the offset of this search match, or -1 if unknown
- */
- public final int getOffset() {
- return this.offset;
- }
-
- /**
- * Returns the search participant which issued this search match.
- *
- * @return the participant which issued this search match
- */
- public final SearchParticipant getParticipant() {
- return this.participant;
- }
-
- /**
- * Returns the resource containing this search match.
- *
- * @return the resource of the match, or <code>null</code> if none
- */
- public final IResource getResource() {
- return this.resource;
- }
-
- /**
- * Returns the rule used while creating the match.
- *
- * @return one of {@link SearchPattern#R_FULL_MATCH}, {@link SearchPattern#R_EQUIVALENT_MATCH}
- * or {@link SearchPattern#R_ERASURE_MATCH}
- *
- */
- public final int getRule() {
- return this.rule;
- }
-
- /**
- * Returns whether match element is compatible with searched pattern or not.
- * Note that equivalent matches are also erasure ones.
- *
- * @return <code>true</code> if match element is compatible
- * <code>false</code> otherwise
- *
- */
- public final boolean isEquivalent() {
- return isErasure() && (this.rule & SearchPattern.R_EQUIVALENT_MATCH) != 0;
- }
-
- /**
- * Returns whether match element only has same erasure than searched pattern or not.
- * Note that this is always true for both generic and non-generic element as soon
- * as the accuracy is accurate.
- *
- * @return <code>true</code> if match element has same erasure
- * <code>false</code> otherwise
- *
- */
- public final boolean isErasure() {
- return (this.rule & SearchPattern.R_ERASURE_MATCH) != 0;
- }
-
- /**
- * Returns whether element matches exactly searched pattern or not.
- * Note that exact matches are also erasure and equivalent ones.
- *
- * @return <code>true</code> if match is exact
- * <code>false</code> otherwise
- *
- */
- public final boolean isExact() {
- return isEquivalent() && (this.rule & SearchPattern.R_FULL_MATCH) != 0;
- }
-
- /**
- * Returns whether the associated element is implicit or not.
- *
- * Note that this piece of information is currently only implemented
- * for implicit member pair value in annotation.
- *
- * @return <code>true</code> if this match is associated to an implicit
- * element and <code>false</code> otherwise
- *
- */
- public final boolean isImplicit() {
- return this.implicit;
- }
-
- /**
- * Returns whether the associated element is a raw type/method or not.
- *
- * @return <code>true</code> if this match is associated to a raw
- * type or method and <code>false</code> otherwise
- *
- */
- public final boolean isRaw() {
- return this.raw;
- }
-
- /**
- * Returns whether this search match is inside a doc comment of a Java
- * source file.
- *
- * @return <code>true</code> if this search match is inside a doc
- * comment, and <code>false</code> otherwise
- */
- public final boolean isInsideDocComment() {
- // default is outside a doc comment
- return this.insideDocComment;
- }
-
- /**
- * Sets the accuracy of this match.
- *
- * @param accuracy one of {@link #A_ACCURATE} or {@link #A_INACCURATE}
- */
- public final void setAccuracy (int accuracy) {
- this.accuracy = accuracy;
- }
-
- /**
- * Sets the element of this search match.
- *
- * @param element the element that encloses or corresponds to the match,
- * or <code>null</code> if none
- */
- public final void setElement (Object element) {
- this.element = element;
- }
-
- /**
- * Sets whether this search match is inside a doc comment of a Java
- * source file.
- *
- * @param insideDoc <code>true</code> if this search match is inside a doc
- * comment, and <code>false</code> otherwise
- */
- public final void setInsideDocComment (boolean insideDoc) {
- this.insideDocComment = insideDoc;
- }
-
- /**
- * Sets whether the associated element is implicit or not.
- * Typically, this is the case when match is on an implicit constructor
- * or an implicit member pair value in annotation.
- *
- * @param implicit <code>true</code> if this match is associated to an implicit
- * element and <code>false</code> otherwise
- *
- */
- public final void setImplicit(boolean implicit) {
- this.implicit = implicit;
- }
-
- /**
- * Sets the length of this search match.
- *
- * @param length the length of the match, or -1 if unknown
- */
- public final void setLength(int length) {
- this.length = length;
- }
-
- /**
- * Sets the offset of this search match.
- *
- * @param offset the offset the match starts at, or -1 if unknown
- */
- public final void setOffset(int offset) {
- this.offset = offset;
- }
-
- /**
- * Sets the participant of this match.
- *
- * @param participant the search participant that created this match
- */
- public final void setParticipant (SearchParticipant participant) {
- this.participant = participant;
- }
-
- /**
- * Sets the resource of this match.
- *
- * @param resource the resource of the match, or <code>null</code> if none
- */
- public final void setResource (IResource resource) {
- this.resource = resource;
- }
-
- /**
- * Set the rule used while reporting the match.
- *
- * @param rule one of {@link SearchPattern#R_FULL_MATCH}, {@link SearchPattern#R_EQUIVALENT_MATCH}
- * or {@link SearchPattern#R_ERASURE_MATCH}
- *
- */
- public final void setRule(int rule) {
- this.rule = rule;
- }
-
- /**
- * Set whether the associated element is a raw type/method or not.
- *
- * @param raw <code>true</code> if this search match is associated to a raw
- * type or method and <code>false</code> otherwise
- *
- */
- public final void setRaw(boolean raw) {
- this.raw = raw;
- }
-
- /* (non-javadoc)
- * @see java.lang.Object#toString()
- */
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- buffer.append("Search match"); //$NON-NLS-1$
- buffer.append("\n accuracy="); //$NON-NLS-1$
- buffer.append(this.accuracy == A_ACCURATE ? "ACCURATE" : "INACCURATE"); //$NON-NLS-1$ //$NON-NLS-2$
- buffer.append("\n rule="); //$NON-NLS-1$
- if ((this.rule & SearchPattern.R_FULL_MATCH) != 0) {
- buffer.append("EXACT"); //$NON-NLS-1$
- } else if ((this.rule & SearchPattern.R_EQUIVALENT_MATCH) != 0) {
- buffer.append("EQUIVALENT"); //$NON-NLS-1$
- } else if ((this.rule & SearchPattern.R_ERASURE_MATCH) != 0) {
- buffer.append("ERASURE"); //$NON-NLS-1$
- }
- buffer.append("\n raw="); //$NON-NLS-1$
- buffer.append(this.raw);
- buffer.append("\n offset="); //$NON-NLS-1$
- buffer.append(this.offset);
- buffer.append("\n length="); //$NON-NLS-1$
- buffer.append(this.length);
- if (this.element != null) {
- buffer.append("\n element="); //$NON-NLS-1$
- buffer.append(((JavaElement)getElement()).toStringWithAncestors());
- }
- buffer.append("\n"); //$NON-NLS-1$
- return buffer.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/SearchParticipant.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/SearchParticipant.java
deleted file mode 100644
index 939165f6..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/SearchParticipant.java
+++ /dev/null
@@ -1,235 +0,0 @@
-/*******************************************************************************
- * 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.core.search;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-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.internal.core.JavaModel;
-import org.eclipse.wst.jsdt.internal.core.JavaModelManager;
-import org.eclipse.wst.jsdt.internal.core.search.indexing.IndexManager;
-
-/**
- * A search participant describes a particular extension to a generic search
- * mechanism, permitting combined search actions which will involve all required
- * participants.
- * <p>
- * A search participant is involved in the indexing phase and in the search phase.
- * The indexing phase consists in taking one or more search documents, parse them, and
- * add index entries in an index chosen by the participant. An index is identified by a
- * path on disk.
- * The search phase consists in selecting the indexes corresponding to a search pattern
- * and a search scope, from these indexes the search infrastructure extracts the document paths
- * that match the search pattern asking the search participant for the corresponding document,
- * finally the search participant is asked to locate the matches precisely in these search documents.
- * </p>
- * <p>
- * This class is intended to be subclassed by clients. During the indexing phase,
- * a subclass will be called with the following requests in order:
- * <ul>
- * <li>{@link #scheduleDocumentIndexing(SearchDocument, IPath)}</li>
- * <li>{@link #indexDocument(SearchDocument, IPath)}</li>
- * </ul>
- * During the search phase, a subclass will be called with the following requests in order:
- * <ul>
- * <li>{@link #selectIndexes(SearchPattern, IJavaScriptSearchScope)}</li>
- * <li>one or more {@link #getDocument(String)}</li>
- * <li>{@link #locateMatches(SearchDocument[], SearchPattern, IJavaScriptSearchScope, SearchRequestor, IProgressMonitor)}</li>
- * </ul>
- * </p>
- *
- *
- * 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 SearchParticipant {
-
- /**
- * Creates a new search participant.
- */
- protected SearchParticipant() {
- // do nothing
- }
-
- /**
- * Notification that this participant's help is needed in a search.
- * <p>
- * This method should be re-implemented in subclasses that need to do something
- * when the participant is needed in a search.
- * </p>
- */
- public void beginSearching() {
- // do nothing
- }
-
- /**
- * Notification that this participant's help is no longer needed.
- * <p>
- * This method should be re-implemented in subclasses that need to do something
- * when the participant is no longer needed in a search.
- * </p>
- */
- public void doneSearching() {
- // do nothing
- }
-
- /**
- * Returns a displayable name of this search participant.
- * <p>
- * This method should be re-implemented in subclasses that need to
- * display a meaningfull name.
- * </p>
- *
- * @return the displayable name of this search participant
- */
- public String getDescription() {
- return "Search participant"; //$NON-NLS-1$
- }
-
- /**
- * Returns a search document for the given path.
- * The given document path is a string that uniquely identifies the document.
- * Most of the time it is a workspace-relative path, but it can also be a file system path, or a path inside a zip file.
- * <p>
- * Implementors of this method can either create an instance of their own subclass of
- * {@link SearchDocument} or return an existing instance of such a subclass.
- * </p>
- *
- * @param documentPath the path of the document.
- * @return a search document
- */
- public abstract SearchDocument getDocument(String documentPath);
-
- /**
- * Indexes the given document in the given index. A search participant
- * asked to index a document should parse it and call
- * {@link SearchDocument#addIndexEntry(char[], char[])} as many times as
- * needed to add index entries to the index. If delegating to another
- * participant, it should use the original index location (and not the
- * delegatee's one). In the particular case of delegating to the default
- * search participant (see {@link SearchEngine#getDefaultSearchParticipant()}),
- * the provided document's path must be a path ending with one of the
- * {@link org.eclipse.wst.jsdt.core.JavaScriptCore#getJavaScriptLikeExtensions() Java-like extensions}
- * or with '.class'.
- * <p>
- * The given index location must represent a path in the file system to a file that
- * either already exists or is going to be created. If it exists, it must be an index file,
- * otherwise its data might be overwritten.
- * </p><p>
- * Clients are not expected to call this method.
- * </p>
- *
- * @param document the document to index
- * @param indexLocation the location in the file system to the index
- */
- public abstract void indexDocument(SearchDocument document, IPath indexLocation);
-
- /**
- * Locates the matches in the given documents using the given search pattern
- * and search scope, and reports them to the givenn search requestor. This
- * method is called by the search engine once it has search documents
- * matching the given pattern in the given search scope.
- * <p>
- * Note that a participant (e.g. a JSP participant) can pre-process the contents of the given documents,
- * create its own documents whose contents are JavaScript javascript unit s and delegate the match location
- * to the default participant (see {@link SearchEngine#getDefaultSearchParticipant()}). Passing its own
- * {@link SearchRequestor} this particpant can then map the match positions back to the original
- * contents, create its own matches and report them to the original requestor.
- * </p><p>
- * Implementors of this method should check the progress monitor
- * for cancelation when it is safe and appropriate to do so. The cancelation
- * request should be propagated to the caller by throwing
- * <code>OperationCanceledException</code>.
- * </p>
- *
- * @param documents the documents to locate matches in
- * @param pattern the search pattern to use when locating matches
- * @param scope the scope to limit the search to
- * @param requestor the requestor to report matches to
- * @param monitor the progress monitor to report progress to,
- * or <code>null</code> if no progress should be reported
- * @throws CoreException if the requestor had problem accepting one of the matches
- */
- public abstract void locateMatches(SearchDocument[] documents, SearchPattern pattern, IJavaScriptSearchScope scope, SearchRequestor requestor, IProgressMonitor monitor) throws CoreException;
-
- /**
- * Removes the index for a given path.
- * <p>
- * The given index location must represent a path in the file system to a file that
- * already exists and must be an index file, otherwise nothing will be done.
- * </p><p>
- * It is strongly recommended to use this method instead of deleting file directly
- * otherwise cached index will not be removed.
- * </p>
- *
- * @param indexLocation the location in the file system to the index
- *
- */
- public void removeIndex(IPath indexLocation){
- IndexManager manager = JavaModelManager.getJavaModelManager().getIndexManager();
- manager.removeIndexPath(indexLocation);
- }
-
- /**
- * Schedules the indexing of the given document.
- * Once the document is ready to be indexed,
- * {@link #indexDocument(SearchDocument, IPath) indexDocument(document, indexPath)}
- * will be called in a different thread than the caller's thread.
- * <p>
- * The given index location must represent a path in the file system to a file that
- * either already exists or is going to be created. If it exists, it must be an index file,
- * otherwise its data might be overwritten.
- * </p><p>
- * When the index is no longer needed, clients should use {@link #removeIndex(IPath) }
- * to discard it.
- * </p>
- *
- * @param document the document to index
- * @param indexLocation the location on the file system of the index
- */
- public final void scheduleDocumentIndexing(SearchDocument document, IPath indexLocation) {
- IPath documentPath = new Path(document.getPath());
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- Object file = JavaModel.getTarget(root, documentPath, true);
- IPath containerPath = documentPath;
- if (file instanceof IResource) {
- containerPath = ((IResource)file).getProject().getFullPath();
- } else if (file == null) {
- containerPath = documentPath.removeLastSegments(1);
- }
- IndexManager manager = JavaModelManager.getJavaModelManager().getIndexManager();
- // TODO (frederic) should not have to create index manually, should expose API that recreates index instead
- manager.ensureIndexExists(indexLocation, containerPath);
- manager.scheduleDocumentIndexing(document, containerPath, indexLocation, this);
- }
-
- /**
- * Returns the collection of index locations to consider when performing the
- * given search query in the given scope. The search engine calls this
- * method before locating matches.
- * <p>
- * An index location represents a path in the file system to a file that holds index information.
- * </p><p>
- * Clients are not expected to call this method.
- * </p>
- *
- * @param query the search pattern to consider
- * @param scope the given search scope
- * @return the collection of index paths to consider
- */
- public abstract IPath[] selectIndexes(SearchPattern query, IJavaScriptSearchScope scope);
-}
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
deleted file mode 100644
index 1b21032c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/SearchPattern.java
+++ /dev/null
@@ -1,1921 +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.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 <code>SearchPattern.createPattern</code>
- * to create a search pattern.
- * <p>
- * 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)}.
- *
- * </p><p>
- * 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.
- * </p>
- * @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.<br>
- * Type search example:
- * <ul>
- * <li>pattern: <code>List&lt;Exception&gt;</code></li>
- * <li>match: <code>List&lt;Object&gt;</code></li>
- * </ul>
- * Method search example:
- * <ul>
- * <li>declaration: <code>&lt;T&gt;foo(T t)</code></li>
- * <li>pattern: <code>&lt;Exception&gt;foo(new Exception())</code></li>
- * <li>match: <code>&lt;Object&gt;foo(new Object())</code></li>
- * </ul>
- * 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&lt;String&gt;,
- * 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.<br>
- * Type search example:
- * <ul>
- * <li>pattern: <code>List&lt;Exception&gt;</code></li>
- * <li>match:
- * <ul>
- * <li><code>List&lt;? extends Throwable&gt;</code></li>
- * <li><code>List&lt;? super RuntimeException&gt;</code></li>
- * <li><code>List&lt;?&gt;</code></li>
- * </ul>
- * </li>
- * </ul>
- * Method search example:
- * <ul>
- * <li>declaration: <code>&lt;T&gt;foo(T t)</code></li>
- * <li>pattern: <code>&lt;Exception&gt;foo(new Exception())</code></li>
- * <li>match:
- * <ul>
- * <li><code>&lt;? extends Throwable&gt;foo(new Exception())</code></li>
- * <li><code>&lt;? super RuntimeException&gt;foo(new Exception())</code></li>
- * <li><code>foo(new Exception())</code></li>
- * </ul>
- * </ul>
- * 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&lt;String&gt;,
- * 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.
- * <br>
- * Examples:
- * <ul>
- * <li><code>NPE</code> type string pattern will match
- * <code>NullPointerException</code> and <code>NpPermissionException</code> types,</li>
- * <li><code>NuPoEx</code> type string pattern will only match
- * <code>NullPointerException</code> type.</li>
- * </ul>
- * @see CharOperation#camelCaseMatch(char[], char[]) for a detailed explanation
- * of Camel Case matching.
- *<br>
- * Can be combined to {@link #R_PREFIX_MATCH} match rule. For example,
- * when prefix match rule is combined with Camel Case match rule,
- * <code>"nPE"</code> pattern will match <code>nPException</code>.
- *<br>
- * 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 <code>"NPE"</code> string pattern, search will only use
- * Camel Case match rule, but with <code>N*P*E*</code> 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.<br>
- * Note that {@link #R_ERASURE_MATCH} or {@link #R_EQUIVALENT_MATCH} have no effect
- * on non-generic types/methods search.<br>
- * 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.
- * <br>
- * 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.
- * <br>
- * 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'.
- * <br><br>
- * Examples:
- * <ol>
- * <li><pre>
- * pattern = "NPE"
- * name = NullPointerException / NoPermissionException
- * result => true
- * </pre>
- * </li>
- * <li><pre>
- * pattern = "NuPoEx"
- * name = NullPointerException
- * result => true
- * </pre>
- * </li>
- * <li><pre>
- * pattern = "npe"
- * name = NullPointerException
- * result => false
- * </pre>
- * </li>
- * </ol>
- * @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.
- * <br>
- * 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.
- * <br>
- * 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'.
- * <br><br>
- * Examples:
- * <ol>
- * <li><pre>
- * pattern = "NPE"
- * patternStart = 0
- * patternEnd = 3
- * name = NullPointerException
- * nameStart = 0
- * nameEnd = 20
- * result => true
- * </pre>
- * </li>
- * <li><pre>
- * pattern = "NPE"
- * patternStart = 0
- * patternEnd = 3
- * name = NoPermissionException
- * nameStart = 0
- * nameEnd = 21
- * result => true
- * </pre>
- * </li>
- * <li><pre>
- * pattern = "NuPoEx"
- * patternStart = 0
- * patternEnd = 6
- * name = NullPointerException
- * nameStart = 0
- * nameEnd = 20
- * result => true
- * </pre>
- * </li>
- * <li><pre>
- * pattern = "NuPoEx"
- * patternStart = 0
- * patternEnd = 6
- * name = NoPermissionException
- * nameStart = 0
- * nameEnd = 21
- * result => false
- * </pre>
- * </li>
- * <li><pre>
- * pattern = "npe"
- * patternStart = 0
- * patternEnd = 3
- * name = NullPointerException
- * nameStart = 0
- * nameEnd = 20
- * result => false
- * </pre>
- * </li>
- * </ol>
- * @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:<br>
- * [declaringType '.'] ['&lt;' typeArguments '&gt;'] selector ['(' parameterTypes ')'] [returnType]
- * <br>e.g.<ul>
- * <li>java.lang.Runnable.run() void</li>
- * <li>main(*)</li>
- * <li>&lt;String&gt;toArray(String[])</li>
- * </ul>
- * Constructor pattern are formed by:<br>
- * [declaringQualification '.'] ['&lt;' typeArguments '&gt;'] type ['(' parameterTypes ')']
- * <br>e.g.<ul>
- * <li>java.lang.Object()</li>
- * <li>Main(*)</li>
- * <li>&lt;Exception&gt;Sample(Exception)</li>
- * </ul>
- * 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.
- *
- * <br>
- * Examples:
- * <ul>
- * <li>search for case insensitive references to <code>Object</code>:
- * <code>createSearchPattern("Object", TYPE, REFERENCES, false);</code></li>
- * <li>search for case sensitive references to exact <code>Object()</code> constructor:
- * <code>createSearchPattern("java.lang.Object()", CONSTRUCTOR, REFERENCES, true);</code></li>
- * <li>search for implementers of <code>java.lang.Runnable</code>:
- * <code>createSearchPattern("java.lang.Runnable", TYPE, IMPLEMENTORS, true);</code></li>
- * </ul>
- * @param stringPattern the given pattern
- * @param searchFor determines the nature of the searched elements
- * <ul>
- * <li>{@link IJavaScriptSearchConstants#CLASS}: only look for classes</li>
- * <li>{@link IJavaScriptSearchConstants#INTERFACE}: only look for interfaces</li>
- * <li>{@link IJavaScriptSearchConstants#ENUM}: only look for enumeration</li>
- * <li>{@link IJavaScriptSearchConstants#ANNOTATION_TYPE}: only look for annotation type</li>
- * <li>{@link IJavaScriptSearchConstants#CLASS_AND_ENUM}: only look for classes and enumerations</li>
- * <li>{@link IJavaScriptSearchConstants#CLASS_AND_INTERFACE}: only look for classes and interfaces</li>
- * <li>{@link IJavaScriptSearchConstants#TYPE}: look for all types (ie. classes, interfaces, enum and annotation types)</li>
- * <li>{@link IJavaScriptSearchConstants#FIELD}: look for fields</li>
- * <li>{@link IJavaScriptSearchConstants#METHOD}: look for methods</li>
- * <li>{@link IJavaScriptSearchConstants#CONSTRUCTOR}: look for constructors</li>
- * <li>{@link IJavaScriptSearchConstants#PACKAGE}: look for packages</li>
- * </ul>
- * @param limitTo determines the nature of the expected matches
- * <ul>
- * <li>{@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.<br>
- * 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.
- * </li>
- * <li>{@link IJavaScriptSearchConstants#REFERENCES}: will search references to the given element.</li>
- * <li>{@link IJavaScriptSearchConstants#ALL_OCCURRENCES}: will search for either declarations or
- * references as specified above.
- * </li>
- * <li>{@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}.
- * </li>
- * </ul>
- * @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.<br>
- * Note that {@link #R_ERASURE_MATCH} or {@link #R_EQUIVALENT_MATCH} have no effect
- * on non-generic types/methods search.<br>
- * 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 <code>null</code> 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.
- * <br>
- * 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.
- * <br>
- * 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
- * <ul>
- * <li>{@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:
- * <ul>
- * <li>{@link IJavaScriptSearchConstants#IGNORE_DECLARING_TYPE}: declaring type will be ignored
- * during the search.<br>
- * For example using following test case:
- * <pre>
- * class A { A method() { return null; } }
- * class B extends A { B method() { return null; } }
- * class C { A method() { return null; } }
- * </pre>
- * search for <code>method</code> declaration with this flag
- * will return 2 matches: in A and in C
- * </li>
- * <li>{@link IJavaScriptSearchConstants#IGNORE_RETURN_TYPE}: return type will be ignored
- * during the search.<br>
- * Using same example, search for <code>method</code> declaration with this flag
- * will return 2 matches: in A and in B.
- * </li>
- * </ul>
- * 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 <code>method</code> declaration
- * with these 2 flags will return 3 matches: in A, in B and in C
- * </li>
- * <li>{@link IJavaScriptSearchConstants#REFERENCES}: will search references to the given element.</li>
- * <li>{@link IJavaScriptSearchConstants#ALL_OCCURRENCES}: will search for either declarations or
- * references as specified above.
- * </li>
- * <li>{@link IJavaScriptSearchConstants#IMPLEMENTORS}: for types, will find all types
- * which directly implement/extend a given interface.
- * </li>
- * </ul>
- * @return a search pattern for a JavaScript element or <code>null</code> 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
- * <ul>
- * <li>{@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:
- * <ul>
- * <li>{@link IJavaScriptSearchConstants#IGNORE_DECLARING_TYPE}: declaring type will be ignored
- * during the search.<br>
- * For example using following test case:
- * <pre>
- * class A { A method() { return null; } }
- * class B extends A { B method() { return null; } }
- * class C { A method() { return null; } }
- * </pre>
- * search for <code>method</code> declaration with this flag
- * will return 2 matches: in A and in C
- * </li>
- * <li>{@link IJavaScriptSearchConstants#IGNORE_RETURN_TYPE}: return type will be ignored
- * during the search.<br>
- * Using same example, search for <code>method</code> declaration with this flag
- * will return 2 matches: in A and in B.
- * </li>
- * </ul>
- * 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 <code>method</code> declaration
- * with these 2 flags will return 3 matches: in A, in B and in C
- * </li>
- * <li>{@link IJavaScriptSearchConstants#REFERENCES}: will search references to the given element.</li>
- * <li>{@link IJavaScriptSearchConstants#ALL_OCCURRENCES}: will search for either declarations or
- * references as specified above.
- * </li>
- * <li>{@link IJavaScriptSearchConstants#IMPLEMENTORS}: for types, will find all types
- * which directly implement/extend a given interface.
- * </li>
- * </ul>
- * @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.<br>
- * Note that {@link #R_ERASURE_MATCH} or {@link #R_EQUIVALENT_MATCH} have no effect on non-generic types
- * or methods search.<br>
- * Note also that default behavior for generic types or methods is to find exact matches.
- * @return a search pattern for a JavaScript element or <code>null</code> 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&lt;String&gt;
- */
-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.
- * <p>
- * This method should be re-implemented in subclasses that need to decode an index key.
- * </p>
- *
- * @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.
- * <p>
- * Implementors of this method should return a new search pattern that is going to be used
- * to decode index keys.
- * </p>
- *
- * @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.
- * <p>
- * This method should be re-implemented in subclasses that need to narrow down the
- * index query.
- * </p>
- *
- * @return an index key from this pattern, or <code>null</code> 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.
- * <p>
- * This method should be re-implemented in subclasses that need to narrow down the
- * index query.
- * </p>
- *
- * @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).
- * <p>
- * This method should be re-implemented in subclasses that need to narrow down the
- * index query.
- * </p>
- *
- * @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.
- * <p>
- * This method should be re-implemented in subclasses that need to define how
- * a name matches a pattern.
- * </p>
- *
- * @param pattern the given pattern, or <code>null</code> 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.
- *<br>
- * Optimized (ie. returned match rule is modified) combinations are:
- * <ul>
- * <li>{@link #R_PATTERN_MATCH} without any '*' or '?' in string pattern:
- * pattern match bit is unset,
- * </li>
- * <li>{@link #R_PATTERN_MATCH} and {@link #R_PREFIX_MATCH} bits simultaneously set:
- * prefix match bit is unset,
- * </li>
- * <li>{@link #R_PATTERN_MATCH} and {@link #R_CAMELCASE_MATCH} bits simultaneously set:
- * camel case match bit is unset,
- * </li>
- * <li>{@link #R_CAMELCASE_MATCH} with invalid combination of uppercase and lowercase characters:
- * camel case match bit is unset and replaced with prefix match pattern,
- * </li>
- * <li>{@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,
- * </li>
- * </ul>
- *<br>
- * Rejected (ie. returned match rule -1) combinations are:
- * <ul>
- * <li>{@link #R_REGEXP_MATCH} with any other match mode bit set,
- * </li>
- * </ul>
- *
- * @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<length && validCamelCase; i++) {
- char ch = stringPattern.charAt(i);
- validCamelCase = ScannerHelper.isJavaIdentifierStart(ch);
- // at least one uppercase character is need in CamelCase pattern
- // (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=136313)
- if (!uppercase) uppercase = ScannerHelper.isUpperCase(ch);
- }
- validCamelCase = validCamelCase && uppercase;
- // Verify bits compatibility
- if (validCamelCase) {
- if ((matchRule & R_PREFIX_MATCH) != 0) {
- if ((matchRule & R_CASE_SENSITIVE) != 0) {
- // This is equivalent to Camel Case match rule
- matchRule &= ~R_PREFIX_MATCH;
- matchRule &= ~R_CASE_SENSITIVE;
- }
- }
- } else {
- matchRule &= ~R_CAMELCASE_MATCH;
- if ((matchRule & R_PREFIX_MATCH) == 0) {
- matchRule |= R_PREFIX_MATCH;
- matchRule |= R_CASE_SENSITIVE;
- }
- }
- }
- return matchRule;
-}
-
-/**
- * @see java.lang.Object#toString()
- */
-public String toString() {
- return "SearchPattern"; //$NON-NLS-1$
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/SearchRequestor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/SearchRequestor.java
deleted file mode 100644
index b6c9547f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/SearchRequestor.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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;
-
-/**
- * Collects the results from a search engine query.
- * Clients implement a subclass to pass to <code>SearchEngine.search</code>
- * and implement the {@link #acceptSearchMatch(SearchMatch)} method, and
- * possibly override other life cycle methods.
- * <p>
- * The search engine calls <code>beginReporting()</code> when a search starts,
- * then calls <code>acceptSearchMatch(...)</code> for each search result, and
- * finally calls <code>endReporting()</code>. The order of the search results
- * is unspecified and may vary from request to request; when displaying results,
- * clients should not rely on the order but should instead arrange the results
- * in an order that would be more meaningful to the user.
- * </p>
- *
- * @see SearchEngine
- *
- * 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 SearchRequestor {
-
- /**
- * Accepts the given search match.
- *
- * @param match the found match
- * @throws CoreException
- */
- public abstract void acceptSearchMatch(SearchMatch match) throws CoreException;
-
- /**
- * Notification sent before starting the search action.
- * Typically, this would tell a search requestor to clear previously
- * recorded search results.
- * <p>
- * The default implementation of this method does nothing. Subclasses
- * may override.
- * </p>
- */
- public void beginReporting() {
- // do nothing
- }
-
- /**
- * Notification sent after having completed the search action.
- * Typically, this would tell a search requestor collector that no more
- * results will be forthcomping in this search.
- * <p>
- * The default implementation of this method does nothing. Subclasses
- * may override.
- * </p>
- */
- public void endReporting() {
- // do nothing
- }
-
- /**
- * Intermediate notification sent when the given participant starts to
- * contribute.
- * <p>
- * The default implementation of this method does nothing. Subclasses
- * may override.
- * </p>
- *
- * @param participant the participant that is starting to contribute
- */
- public void enterParticipant(SearchParticipant participant) {
- // do nothing
- }
-
- /**
- * Intermediate notification sent when the given participant is finished
- * contributing.
- * <p>
- * The default implementation of this method does nothing. Subclasses
- * may override.
- * </p>
- *
- * @param participant the participant that finished contributing
- */
- public void exitParticipant(SearchParticipant participant) {
- // do nothing
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/TypeDeclarationMatch.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/TypeDeclarationMatch.java
deleted file mode 100644
index 5ccf3448..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/TypeDeclarationMatch.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*******************************************************************************
- * 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.resources.IResource;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-
-/**
- * A JavaScript search match that represents a type declaration.
- * The element is an <code>IType</code>.
- * <p>
- * This class is intended to be instantiated and subclassed by clients.
- * </p>
- *
- *
- * 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 TypeDeclarationMatch extends SearchMatch {
-
- /**
- * Creates a new type declaration match.
- *
- * @param element the type declaration
- * @param accuracy one of A_ACCURATE or A_INACCURATE
- * @param offset the offset the match starts at, or -1 if unknown
- * @param length the length of the match, or -1 if unknown
- * @param participant the search participant that created the match
- * @param resource the resource of the element
- */
- public TypeDeclarationMatch(IJavaScriptElement element, int accuracy, int offset, int length, SearchParticipant participant, IResource resource) {
- super(element, accuracy, offset, length, participant, resource);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/TypeNameMatch.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/TypeNameMatch.java
deleted file mode 100644
index 78643094..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/TypeNameMatch.java
+++ /dev/null
@@ -1,160 +0,0 @@
-/*******************************************************************************
- * 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.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IType;
-
-/**
- * A match collected while {@link SearchEngine searching} for
- * all type names methods using a {@link TypeNameRequestor requestor}.
- * <p>
- * The type of this match is available from {@link #getType()}.
- * </p>
- * <p>
- * This class is not intended to be overridden by clients.
- * </p>
- *
- * @see TypeNameMatchRequestor
- * @see SearchEngine#searchAllTypeNames(char[], int, char[], int, int, IJavaScriptSearchScope, TypeNameMatchRequestor, int, org.eclipse.core.runtime.IProgressMonitor)
- * @see SearchEngine#searchAllTypeNames(char[][], char[][], IJavaScriptSearchScope, TypeNameMatchRequestor, int, org.eclipse.core.runtime.IProgressMonitor)
- *
- * 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 TypeNameMatch {
-
-/**
- * Returns the matched type's fully qualified name using '.' character
- * as separator (e.g. package name + '.' enclosing type names + '.' simple name).
- *
- * @see #getType()
- * @see IType#getFullyQualifiedName(char)
- *
- * @throws NullPointerException if matched type is <code> null</code>
- * @return Fully qualified type name of the type
- */
-public String getFullyQualifiedName() {
- return getType().getFullyQualifiedName('.');
-}
-
-/**
- * Returns the modifiers of the matched type.
- * <p>
- * This is a handle-only method as neither JavaScript Model nor includepath
- * initialization is done while calling this method.
- *
- * @return the type modifiers
- */
-public abstract int getModifiers();
-
-/**
- * Returns the package fragment root of the stored type.
- * Package fragment root cannot be null and <strong>does</strong> exist.
- *
- * @see #getType()
- * @see IJavaScriptElement#getAncestor(int)
- *
- * @throws NullPointerException if matched type is <code> null</code>
- * @return the existing javascript model package fragment root (ie. cannot be <code>null</code>
- * and will return <code>true</code> to <code>exists()</code> message).
- */
-public IPackageFragmentRoot getPackageFragmentRoot() {
- return (IPackageFragmentRoot) getType().getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
-}
-
-/**
- * Returns the package name of the stored type.
- *
- * @see #getType()
- * @see IType#getPackageFragment()
- *
- * @throws NullPointerException if matched type is <code> null</code>
- * @return the package name
- */
-public String getPackageName() {
- String name=getType().getElementName();
- int index=name.lastIndexOf(".");
- if (index>=0)
- name=name.substring(0,index);
- return "";
-}
-
-/**
- * Returns the name of the stored type.
- *
- * @see #getType()
- * @see IJavaScriptElement#getElementName()
- *
- * @throws NullPointerException if matched type is <code> null</code>
- * @return the type name
- */
-public String getSimpleTypeName() {
- String name=getType().getElementName();
- int index=name.lastIndexOf(".");
- if (index>=0)
- name=name.substring(index+1);
- return name;
-}
-
-/**
- * Returns a javascript model type handle.
- * This handle may exist or not, but is not supposed to be <code>null</code>.
- * <p>
- * This is a handle-only method as neither JavaScript Model nor includepath
- * initializations are done while calling this method.
- *
- * @see IType
- * @return the non-null handle on matched javascript model type.
- */
-public abstract IType getType();
-
-/**
- * Name of the type container using '.' character
- * as separator (e.g. package name + '.' + enclosing type names).
- *
- * @see #getType()
- * @see org.eclipse.wst.jsdt.core.IMember#getDeclaringType()
- *
- * @throws NullPointerException if matched type is <code> null</code>
- * @return name of the type container
- */
-public String getTypeContainerName() {
- IType outerType = getType().getDeclaringType();
- if (outerType != null) {
- return outerType.getFullyQualifiedName('.');
- } else {
- return getType().getPackageFragment().getElementName();
- }
-}
-
-/**
- * Returns the matched type's type qualified name using '.' character
- * as separator (e.g. enclosing type names + '.' + simple name).
- *
- * @see #getType()
- * @see IType#getTypeQualifiedName(char)
- *
- * @throws NullPointerException if matched type is <code> null</code>
- * @return fully qualified type name of the type
- */
-public String getTypeQualifiedName() {
- return getType().getTypeQualifiedName('.');
-}
-
-public String getQualifiedName() {
-return getType().getElementName();
-}
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/TypeNameMatchRequestor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/TypeNameMatchRequestor.java
deleted file mode 100644
index 953eb5b7..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/TypeNameMatchRequestor.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*******************************************************************************
- * 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;
-
-/**
- * A <code>TypeNameMatchRequestor</code> collects matches from a <code>searchAllTypeNames</code>
- * query to a <code>SearchEngine</code>. Clients must subclass this abstract class and pass an instance to the
- * {@link SearchEngine#searchAllTypeNames(
- * char[] packageName,
- * int packageMatchRule,
- * char[] typeName,
- * int typeMatchRule,
- * int searchFor,
- * IJavaScriptSearchScope scope,
- * TypeNameMatchRequestor nameMatchRequestor,
- * int waitingPolicy,
- * org.eclipse.core.runtime.IProgressMonitor monitor)} method.
- * Only top-level and member types are reported. Local types are not reported.
- * <p>
- * While {@link TypeNameRequestor} only reports type names information (e.g. package, enclosing types, simple name, modifiers, etc.),
- * this class reports {@link TypeNameMatch} objects instead, which store this information and can return
- * an {@link org.eclipse.wst.jsdt.core.IType} handle.
- * </p>
- * <p>
- * This class may be subclassed by clients.
- * </p>
- * @see TypeNameMatch
- * @see TypeNameRequestor
- *
- *
- * 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 TypeNameMatchRequestor {
- /**
- * Accepts a type name match ({@link TypeNameMatch}) which contains top-level or a member type
- * information as package name, enclosing types names, simple type name, modifiers, etc.
- *
- * @param match the match which contains all type information
- */
- public abstract void acceptTypeNameMatch(TypeNameMatch match);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/TypeNameRequestor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/TypeNameRequestor.java
deleted file mode 100644
index 71b0fb48..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/TypeNameRequestor.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*******************************************************************************
- * 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;
-
-/**
- * A <code>TypeNameRequestor</code> collects search results from a <code>searchAllTypeNames</code>
- * query to a <code>SearchEngine</code>. Clients must subclass this abstract class and pass
- * an instance to the <code>SearchEngine.searchAllTypeNames(...)</code> method. Only top-level and
- * member types are reported. Local types are not reported.
- * <p>
- * This class may be subclassed by clients.
- * </p>
- *
- * 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 TypeNameRequestor {
- /**
- * Accepts a top-level or a member type.
- * <p>
- * The default implementation of this method does nothing.
- * Subclasses should override.
- * </p>
- *
- * @param modifiers the modifier flags of the type. Note that for source type,
- * these flags may slightly differ from thoses get after resolution.
- * For example an interface defined by <code>interface A {}</code>,
- * although obviously public, will be returned false by <code>Flags.isPublic(modifiers)</code>
- * due to the fact that its declaration does not explicitely define public flag.
- * @see org.eclipse.wst.jsdt.core.Flags
- * @param packageName the dot-separated name of the package of the type
- * @param simpleTypeName the simple name of the type
- * @param enclosingTypeNames if the type is a member type,
- * the simple names of the enclosing types from the outer-most to the
- * direct parent of the type (for example, if the class is x.y.A$B$C then
- * the enclosing types are [A, B]. This is an empty array if the type
- * is a top-level type.
- * @param path the full path to the resource containing the type. If the resource is a .class file
- * or a source file, this is the full path in the workspace to this resource. If the
- * resource is an archive (that is, a .zip or .jar file), the path is composed of 2 paths separated
- * by <code>IJavaScriptSearchScope.JAR_FILE_ENTRY_SEPARATOR</code>:
- * the first path is the full OS path to the archive (if it is an external archive),
- * or the workspace relative <code>IPath</code> to the archive (if it is an internal archive),
- * the second path is the path to the resource inside the archive.
- */
- public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path) {
- // do nothing
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/TypeReferenceMatch.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/TypeReferenceMatch.java
deleted file mode 100644
index e8fc0087..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/TypeReferenceMatch.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*******************************************************************************
- * 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.resources.IResource;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-
-/**
- * A JavaScript search match that represents a type reference.
- * The element is the inner-most enclosing member that references this type.
- * <p>
- * This class is intended to be instantiated and subclassed by clients.
- * </p>
- *
- * 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 TypeReferenceMatch extends SearchMatch {
-
- private IJavaScriptElement localElement;
- private IJavaScriptElement[] otherElements;
-
- /**
- * Creates a new type reference match.
- *
- * @param enclosingElement the inner-most enclosing member that references this type
- * @param accuracy one of {@link #A_ACCURATE} or {@link #A_INACCURATE}
- * @param offset the offset the match starts at, or -1 if unknown
- * @param length the length of the match, or -1 if unknown
- * @param insideDocComment <code>true</code> if this search match is inside a doc
- * comment, and <code>false</code> otherwise
- * @param participant the search participant that created the match
- * @param resource the resource of the element
- */
- public TypeReferenceMatch(IJavaScriptElement enclosingElement, int accuracy, int offset, int length, boolean insideDocComment, SearchParticipant participant, IResource resource) {
- super(enclosingElement, accuracy, offset, length, participant, resource);
- setInsideDocComment(insideDocComment);
- }
-
- /**
- * Returns the local element of this search match.
- * This may be a local variable which declaring type is the referenced one
- * or a type parameter which extends it.
- *
- * @return the element of the search match, or <code>null</code> if none or there's
- * no more specific local element than the element itself ({@link SearchMatch#getElement()}).
- *
- */
- public final IJavaScriptElement getLocalElement() {
- return this.localElement;
- }
-
- /**
- * Returns other enclosing elements of this search match.
- *
- * If {@link #getLocalElement()} is not <code>null</code>, these may be other
- * local elements such as additional local variables of a multiple local
- * variables declaration. Otherwise, these may be other elements such as
- * additional fields of a multiple fields declaration.
- *
- * @return the other elements of the search match, or <code>null</code> if none
- *
- */
- public final IJavaScriptElement[] getOtherElements() {
- return this.otherElements;
- }
-
- /**
- * Sets the local element of this search match.
- *
- * @param localElement A more specific local element that corresponds to the match,
- * or <code>null</code> if none
- *
- */
- public final void setLocalElement(IJavaScriptElement localElement) {
- this.localElement = localElement;
- }
-
- /**
- * Sets the other elements of this search match.
- *
- * @param otherElements the other elements of the match,
- * or <code>null</code> if none
- *
- */
- public final void setOtherElements(IJavaScriptElement[] otherElements) {
- this.otherElements = otherElements;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/util/IModifierConstants.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/util/IModifierConstants.java
deleted file mode 100644
index fa3bb1a4..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/util/IModifierConstants.java
+++ /dev/null
@@ -1,40 +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.core.util;
-
-/**
- * Definition of the modifier constants.
- *
- * 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 IModifierConstants {
-
- int ACC_PUBLIC = 0x0001;
- int ACC_PRIVATE = 0x0002;
- int ACC_PROTECTED = 0x0004;
- int ACC_STATIC = 0x0008;
- int ACC_FINAL = 0x0010;
- int ACC_SUPER = 0x0020;
-
- /**
- * Indicates a variable arity method (added in J2SE 1.5).
- *
- */
- int ACC_VARARGS = 0x0080;
- int ACC_NATIVE = 0x0100;
- int ACC_ABSTRACT = 0x0400;
- int ACC_STRICT = 0x0800;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/util/JavaScriptUnitSorter.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/util/JavaScriptUnitSorter.java
deleted file mode 100644
index 42721cf3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/util/JavaScriptUnitSorter.java
+++ /dev/null
@@ -1,346 +0,0 @@
-/*******************************************************************************
- * 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
- * Alex Blewitt - alex_blewitt@yahoo.com https://bugs.eclipse.org/bugs/show_bug.cgi?id=171066
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.core.util;
-
-import java.util.Comparator;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.core.SortElementsOperation;
-
-/**
- * Operation for sorting members within a javascript unit .
- * <p>
- * This class provides all functionality via static members; it is not
- * intended to be instantiated or subclassed.
- * </p>
- *
- *
- * 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 final class JavaScriptUnitSorter {
-
- /**
- * Private constructor to prevent instantiation.
- */
- private JavaScriptUnitSorter() {
- // Not instantiable
- }
-
-
- private static void checkASTLevel(int level) {
- switch (level) {
- case AST.JLS2 :
- case AST.JLS3 :
- break;
- default :
- throw new IllegalArgumentException();
- }
- }
-
- /**
- * Name of auxillary property whose value can be used to determine the
- * original relative order of two body declarations. This allows a
- * comparator to preserve the relative positions of certain kinds of
- * body declarations when required.
- * <p>
- * All body declarations passed to the comparator's <code>compare</code>
- * method by <code>JavaScriptUnitSorter.sort</code> carry an
- * Integer-valued property. The body declaration with the lower value
- * comes before the one with the higher value. The exact numeric value
- * of these properties is unspecified.
- * </p>
- * <p>
- * Example usage:
- * <pre>
- * BodyDeclaration b1 = (BodyDeclaration) object1;
- * BodyDeclaration b2 = (BodyDeclaration) object2;
- * Integer i1 = (Integer) b1.getProperty(RELATIVE_ORDER);
- * Integer i2 = (Integer) b2.getProperty(RELATIVE_ORDER);
- * return i1.intValue() - i2.intValue(); // preserve original order
- * </pre>
- * </p>
- *
- * @see org.eclipse.wst.jsdt.core.dom.BodyDeclaration
- */
- public static final String RELATIVE_ORDER = "relativeOrder"; //$NON-NLS-1$
-
- /**
- * Reorders the declarations in the given javascript unit according to
- * the specified AST level. The caller is responsible for arranging in
- * advance that the given javascript unit is a working copy, and for
- * saving the changes afterwards.
- * <p>
- * <b>Note:</b> Reordering the members within a type declaration might be
- * more than a cosmetic change and could have potentially serious
- * repercussions. Firstly, the order in which the fields of a type are
- * initialized is significant in the JavaScript language; reordering fields
- * and initializers may result in compilation errors or change the execution
- * behavior of the code. Secondly, reordering a class's members may affect
- * how its instances are serialized. This operation should therefore be used
- * with caution and due concern for potential negative side effects.
- * </p>
- * <p>
- * The optional <code>positions</code> array contains a non-decreasing
- * ordered list of character-based source positions within the compilation
- * unit's source code string. Upon return from this method, the positions in
- * the array reflect the corresponding new locations in the modified source
- * code string. Note that this operation modifies the given array in place.
- * </p>
- * <p>
- * The <code>compare</code> method of the given comparator is passed pairs
- * of body declarations (subclasses of <code>BodyDeclaration</code>)
- * representing body declarations at the same level. The nodes are from an
- * AST of the specified level
- * ({@link org.eclipse.wst.jsdt.core.dom.ASTParser#newParser(int)}. Clients
- * will generally specify AST.JLS3 since that will cover all constructs found
- * in JavaScript 1.0, 1.1, 1.2, 1.3, 1.4, and 1.5 source code.
- * The comparator is called on body declarations of nested classes, including
- * anonymous and local classes, but always at the same level. Clients need to provide
- * a comparator implementation (there is no standard comparator). The
- * <code>RELATIVE_ORDER</code> property attached to these AST nodes afforts
- * the comparator a way to preserve the original relative order.
- * </p>
- * <p>
- * The body declarations passed as parameters to the comparator
- * always carry at least the following minimal signature information:
- * <br>
- * <table border="1" width="80%" cellpadding="5">
- * <tr>
- * <td width="20%"><code>TypeDeclaration</code></td>
- * <td width="50%"><code>modifiers, isInterface, name, superclass,
- * superInterfaces, typeParameters<br>
- * RELATIVE_ORDER property</code></td>
- * </tr>
- * <tr>
- * <td width="20%"><code>FieldDeclaration</code></td>
- * <td width="50%"><code>modifiers, type, fragments
- * (VariableDeclarationFragments
- * with name only)<br>
- * RELATIVE_ORDER property</code></td>
- * </tr>
- * <tr>
- * <td width="20%"><code>FunctionDeclaration</code></td>
- * <td width="50%"><code>modifiers, isConstructor, returnType, name,
- * typeParameters, parameters
- * (SingleVariableDeclarations with name, type, and modifiers only),
- * thrownExceptions<br>
- * RELATIVE_ORDER property</code></td>
- * </tr>
- * <tr>
- * <td width="20%"><code>Initializer</code></td>
- * <td width="50%"><code>modifiers<br>
- * RELATIVE_ORDER property</code></td>
- * </tr>
- * <tr>
- * <td width="20%"><code>AnnotationTypeDeclaration</code></td>
- * <td width="50%"><code>modifiers, name<br>
- * RELATIVE_ORDER property</code></td>
- * </tr>
- * <tr>
- * <td width="20%"><code>AnnotationTypeMemberDeclaration</code></td>
- * <td width="50%"><code>modifiers, name, type, default<br>
- * RELATIVE_ORDER property</code></td>
- * </tr>
- * <tr>
- * <td width="20%"><code>EnumDeclaration</code></td>
- * <td width="50%"><code>modifiers, name, superInterfaces<br>
- * RELATIVE_ORDER property</code></td>
- * </tr>
- * <tr>
- * <td width="20%"><code>EnumConstantDeclaration</code></td>
- * <td width="50%"><code>modifiers, name, arguments<br>
- * RELATIVE_ORDER property</code></td>
- * </tr>
- * </table>
- * Clients should not rely on the AST nodes being properly parented or on
- * having source range information. (Future releases may provide options
- * for requesting additional information like source positions, full ASTs,
- * non-recursive sorting, etc.)
- * </p>
- *
- * @param level the AST level; one of the AST LEVEL constants
- * @param compilationUnit the given javascript unit , which must be a
- * working copy
- * @param positions an array of source positions to map, or
- * <code>null</code> if none. If supplied, the positions must
- * character-based source positions within the original source code for
- * the given javascript unit , arranged in non-decreasing order.
- * The array is updated in place when this method returns to reflect the
- * corresponding source positions in the permuted source code string
- * (but not necessarily any longer in non-decreasing order).
- * @param comparator the comparator capable of ordering
- * <code>BodyDeclaration</code>s; this comparator is passed AST nodes
- * from an AST of the specified AST level
- * @param options bitwise-or of option flags; <code>0</code> for default
- * behavior (reserved for future growth)
- * @param monitor the progress monitor to notify, or <code>null</code> if
- * none
- * @exception JavaScriptModelException if the javascript unit could not be
- * sorted. Reasons include:
- * <ul>
- * <li> The given javascript unit does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> The given javascript unit is not a working copy (INVALID_ELEMENT_TYPES)</li>
- * <li> A <code>CoreException</code> occurred while accessing the underlying
- * resource
- * </ul>
- * @exception IllegalArgumentException if the given javascript unit is null
- * or if the given comparator is null, or if <code>level</code> is not one of
- * the AST JLS level constants.
- * @see org.eclipse.wst.jsdt.core.dom.BodyDeclaration
- * @see #RELATIVE_ORDER
- *
- */
- public static void sort(int level, IJavaScriptUnit compilationUnit,
- int[] positions,
- Comparator comparator,
- int options,
- IProgressMonitor monitor) throws JavaScriptModelException {
- if (compilationUnit == null || comparator == null) {
- throw new IllegalArgumentException();
- }
- checkASTLevel(level);
- IJavaScriptUnit[] compilationUnits = new IJavaScriptUnit[] { compilationUnit };
- SortElementsOperation operation = new SortElementsOperation(level, compilationUnits, positions, comparator);
- operation.runOperation(monitor);
- }
-
- /**
- * Reorders the declarations in the given javascript unit according to the
- * specified comparator. The caller is responsible for arranging in advance
- * that the given javascript unit is a working copy, and for applying the
- * returned TextEdit afterwards.
- * <p>
- * <b>Note:</b> Reordering the members within a type declaration might be
- * more than a cosmetic change and could have potentially serious
- * repercussions. Firstly, the order in which the fields of a type are
- * initialized is significant in the JavaScript language; reordering fields and
- * initializers may result in compilation errors or change the execution
- * behavior of the code. Secondly, reordering a class's members may affect
- * how its instances are serialized. This operation should therefore be used
- * with caution and due concern for potential negative side effects.
- * </p>
- * <p>
- * The <code>compare</code> method of the given comparator is passed pairs
- * of body declarations (subclasses of <code>BodyDeclaration</code>)
- * representing body declarations at the same level.
- * The comparator is called on body declarations of nested classes,
- * including anonymous and local classes, but always at the same level.
- * Clients need to provide a comparator implementation (there is no standard
- * comparator). The <code>RELATIVE_ORDER</code> property attached to these
- * AST nodes affords the comparator a way to preserve the original relative
- * order.
- * </p>
- * <p>
- * The body declarations passed as parameters to the comparator always carry
- * at least the following minimal signature information: <br>
- * <table border="1" width="80%" cellpadding="5">
- * <tr>
- * <td width="20%"><code>TypeDeclaration</code></td>
- * <td width="50%"><code>modifiers, isInterface, name, superclass,
- * superInterfaces, typeParameters<br>
- * RELATIVE_ORDER property</code></td>
- * </tr>
- * <tr>
- * <td width="20%"><code>FieldDeclaration</code></td>
- * <td width="50%"><code>modifiers, type, fragments
- * (VariableDeclarationFragments
- * with name only)<br>
- * RELATIVE_ORDER property</code></td>
- * </tr>
- * <tr>
- * <td width="20%"><code>FunctionDeclaration</code></td>
- * <td width="50%"><code>modifiers, isConstructor, returnType, name,
- * typeParameters, parameters
- * (SingleVariableDeclarations with name, type, and modifiers only),
- * thrownExceptions<br>
- * RELATIVE_ORDER property</code></td>
- * </tr>
- * <tr>
- * <td width="20%"><code>Initializer</code></td>
- * <td width="50%"><code>modifiers<br>
- * RELATIVE_ORDER property</code></td>
- * </tr>
- * <tr>
- * <td width="20%"><code>AnnotationTypeDeclaration</code></td>
- * <td width="50%"><code>modifiers, name<br>
- * RELATIVE_ORDER property</code></td>
- * </tr>
- * <tr>
- * <td width="20%"><code>AnnotationTypeMemberDeclaration</code></td>
- * <td width="50%"><code>modifiers, name, type, default<br>
- * RELATIVE_ORDER property</code></td>
- * </tr>
- * <tr>
- * <td width="20%"><code>EnumDeclaration</code></td>
- * <td width="50%"><code>modifiers, name, superInterfaces<br>
- * RELATIVE_ORDER property</code></td>
- * </tr>
- * <tr>
- * <td width="20%"><code>EnumConstantDeclaration</code></td>
- * <td width="50%"><code>modifiers, name, arguments<br>
- * RELATIVE_ORDER property</code></td>
- * </tr>
- * </table>
- * </p>
- *
- * @param unit
- * the JavaScriptUnit to sort
- * @param comparator
- * the comparator capable of ordering
- * <code>BodyDeclaration</code>s; this comparator is passed
- * AST nodes from an AST of the specified AST level
- * @param options
- * bitwise-or of option flags; <code>0</code> for default
- * behavior (reserved for future growth)
- * @param group
- * the text edit group to use when generating text edits, or <code>null</code>
- * @param monitor
- * the progress monitor to notify, or <code>null</code> if none
- * @return a TextEdit describing the required edits to do the sort, or <code>null</code>
- * if sorting is not required
- * @exception JavaScriptModelException
- * if the javascript unit could not be sorted. Reasons
- * include:
- * <ul>
- * <li> The given unit was not created from a IJavaScriptUnit (INVALID_ELEMENT_TYPES)</li>
- * </ul>
- * @exception IllegalArgumentException
- * if the given javascript unit is null or if the given
- * comparator is null, or if <code>options</code> is not one
- * of the supported levels.
- * @see org.eclipse.wst.jsdt.core.dom.BodyDeclaration
- * @see #RELATIVE_ORDER
- *
- */
- public static TextEdit sort(JavaScriptUnit unit,
- Comparator comparator,
- int options,
- TextEditGroup group,
- IProgressMonitor monitor) throws JavaScriptModelException {
- if (unit == null || comparator == null) {
- throw new IllegalArgumentException();
- }
- SortElementsOperation operation = new SortElementsOperation(AST.JLS3, new IJavaScriptElement[] { unit.getJavaElement() }, null, comparator);
- return operation.calculateEdit(unit, group);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/util/SequenceReader.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/util/SequenceReader.java
deleted file mode 100644
index c94a8151..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/util/SequenceReader.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/*******************************************************************************
- * 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.core.util;
-
-import java.io.IOException;
-import java.io.Reader;
-
-/**
- * Provides the contents of multiple Readers in sequence.
- */
-public class SequenceReader extends Reader {
- private Reader[] fReaders;
- private Reader fCurrentReader;
-
- /**
- * @param readers
- * the readers from which to read
- */
- public SequenceReader(Reader[] readers) {
- fReaders = readers;
- if (fReaders.length > 0) {
- fCurrentReader = fReaders[0];
- }
- }
-
- /*
- * (non-Javadoc)
- *
- * @see java.io.Reader#close()
- */
- public void close() throws IOException {
- if (fCurrentReader != null) {
- for (int i = 0; i <= indexOf(fCurrentReader); i++) {
- fReaders[i].close();
- }
- }
- }
-
- private int indexOf(Reader r) {
- for (int i = 0; i < fReaders.length; i++) {
- if (fReaders[i] == r) {
- return i;
- }
- }
- return -1;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see java.io.Reader#read(char[], int, int)
- */
- public int read(char[] cbuf, int off, int len) throws IOException {
- if (fCurrentReader != null) {
- int bufIndex = off;
- int read = 0;
- for (bufIndex = off; bufIndex - off < len; bufIndex++) {
- int c = primRead();
- if (c != -1) {
- read++;
- cbuf[bufIndex] = (char) c;
- }
- else if (read == 0) {
- return -1;
- }
- }
- return read;
- }
- return -1;
- }
-
- /**
- * @return
- */
- private int primRead() {
- int c = -1;
- try {
- c = fCurrentReader.read();
- }
- catch (IOException e) {
- }
- if (c == -1) {
- int index = indexOf(fCurrentReader);
- if (index > -1 && index < fReaders.length - 1) {
- fCurrentReader = fReaders[index + 1];
- c = primRead();
- }
- }
- return c;
- }
-}
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
deleted file mode 100644
index c2a7af6a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/CompletionEngine.java
+++ /dev/null
@@ -1,7584 +0,0 @@
-/*******************************************************************************
- * 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 <spektom@gmail.com> Bug 242989
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist;
-
-import java.util.ArrayList;
-import java.util.Locale;
-import java.util.Map;
-
-import org.eclipse.wst.jsdt.core.CompletionContext;
-import org.eclipse.wst.jsdt.core.CompletionFlags;
-import org.eclipse.wst.jsdt.core.CompletionProposal;
-import org.eclipse.wst.jsdt.core.CompletionRequestor;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IAccessRule;
-import org.eclipse.wst.jsdt.core.IFunction;
-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.InferredMethod;
-import org.eclipse.wst.jsdt.core.infer.InferredType;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionNodeFound;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionOnArgumentName;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionOnBrankStatementLabel;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionOnClassLiteralAccess;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionOnExplicitConstructorCall;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionOnFieldName;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionOnFieldType;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionOnImportReference;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionOnJavadoc;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionOnJavadocAllocationExpression;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionOnJavadocFieldReference;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionOnJavadocMessageSend;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionOnJavadocParamNameReference;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionOnJavadocQualifiedTypeReference;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionOnJavadocSingleTypeReference;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionOnJavadocTag;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionOnKeyword;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionOnLocalName;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionOnMemberAccess;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionOnMessageSend;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionOnMessageSendName;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionOnMethodName;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionOnQualifiedAllocationExpression;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionOnQualifiedNameReference;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionOnQualifiedType;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionOnQualifiedTypeReference;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionOnSingleNameReference;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionOnSingleTypeName;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionOnSingleTypeReference;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionOnStringLiteral;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionParser;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionScanner;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.InvalidCursorLocation;
-import org.eclipse.wst.jsdt.internal.codeassist.impl.AssistParser;
-import org.eclipse.wst.jsdt.internal.codeassist.impl.Engine;
-import org.eclipse.wst.jsdt.internal.codeassist.impl.Keywords;
-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.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.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.ConditionalExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ConstructorDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Expression;
-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.ImportReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Initializer;
-import org.eclipse.wst.jsdt.internal.compiler.ast.InstanceOfExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocImplicitTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocQualifiedTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocSingleTypeReference;
-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.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;
-import org.eclipse.wst.jsdt.internal.compiler.ast.UnaryExpression;
-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.env.ICompilationUnit;
-import org.eclipse.wst.jsdt.internal.compiler.env.ISourceType;
-import org.eclipse.wst.jsdt.internal.compiler.env.NameEnvironmentAnswer;
-import org.eclipse.wst.jsdt.internal.compiler.impl.ReferenceContext;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ArrayBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BinaryTypeBinding;
-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.CompilationUnitBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.CompilationUnitScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ExtraCompilerModifiers;
-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.LocalVariableBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.LookupEnvironment;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.MetatdataTypeBinding;
-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.PackageBinding;
-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.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.VariableBinding;
-import org.eclipse.wst.jsdt.internal.compiler.parser.JavadocTagConstants;
-import org.eclipse.wst.jsdt.internal.compiler.parser.Parser;
-import org.eclipse.wst.jsdt.internal.compiler.parser.Scanner;
-import org.eclipse.wst.jsdt.internal.compiler.parser.SourceTypeConverter;
-import org.eclipse.wst.jsdt.internal.compiler.parser.TerminalTokens;
-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.DefaultProblemFactory;
-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.HashtableOfObject;
-import org.eclipse.wst.jsdt.internal.compiler.util.ObjectVector;
-import org.eclipse.wst.jsdt.internal.compiler.util.SuffixConstants;
-import org.eclipse.wst.jsdt.internal.core.BasicCompilationUnit;
-import org.eclipse.wst.jsdt.internal.core.BinaryTypeConverter;
-import org.eclipse.wst.jsdt.internal.core.INamingRequestor;
-import org.eclipse.wst.jsdt.internal.core.InternalNamingConventions;
-import org.eclipse.wst.jsdt.internal.core.SearchableEnvironment;
-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.oaametadata.ClassData;
-import org.eclipse.wst.jsdt.internal.oaametadata.Method;
-
-/**
- * This class is the entry point for source completions.
- * It contains two public APIs used to call CodeAssist on a given source with
- * a given environment, assisting position and storage (and possibly options).
- */
-public final class CompletionEngine
- extends Engine
- implements ISearchRequestor, TypeConstants , TerminalTokens , RelevanceConstants, SuffixConstants {
-
- public class CompletionProblemFactory extends DefaultProblemFactory {
- private int lastErrorStart;
-
- private boolean checkProblems = false;
- public boolean hasForbiddenProblems = false;
- public boolean hasAllowedProblems = false;
-
- public CompletionProblemFactory(Locale loc) {
- super(loc);
- }
-
- public CategorizedProblem createProblem(
- char[] originatingFileName,
- int problemId,
- String[] problemArguments,
- String[] messageArguments,
- int severity,
- int start,
- int end,
- int lineNumber,
- int columnNumber) {
-
- CategorizedProblem pb = super.createProblem(
- originatingFileName,
- problemId,
- problemArguments,
- messageArguments,
- severity,
- start,
- end,
- lineNumber,
- columnNumber);
- int id = pb.getID();
- if (CompletionEngine.this.actualCompletionPosition > start
- && this.lastErrorStart < start
- && pb.isError()
- && (id & IProblem.Syntax) == 0
- && (CompletionEngine.this.fileName == null || CharOperation.equals(CompletionEngine.this.fileName, originatingFileName))) {
-
- CompletionEngine.this.problem = pb;
- this.lastErrorStart = start;
- }
- if (this.checkProblems && !this.hasForbiddenProblems) {
- switch (id) {
- case IProblem.UsingDeprecatedType:
- this.hasForbiddenProblems =
- CompletionEngine.this.options.checkDeprecation;
- break;
- case IProblem.NotVisibleType:
- this.hasForbiddenProblems =
- CompletionEngine.this.options.checkVisibility;
- break;
- case IProblem.ForbiddenReference:
- this.hasForbiddenProblems =
- CompletionEngine.this.options.checkForbiddenReference;
- break;
- case IProblem.DiscouragedReference:
- this.hasForbiddenProblems =
- CompletionEngine.this.options.checkDiscouragedReference;
- break;
- default:
- if ((severity & ProblemSeverities.Optional) != 0) {
- this.hasAllowedProblems = true;
- } else {
- this.hasForbiddenProblems = true;
- }
-
- break;
- }
- }
-
- return pb;
- }
-
- public void startCheckingProblems() {
- this.checkProblems = true;
- this.hasForbiddenProblems = false;
- this.hasAllowedProblems = false;
- }
-
- public void stopCheckingProblems() {
- this.checkProblems = false;
- }
- }
-
- private static class AcceptedBinding {
- public AcceptedBinding(
- char[] packageName,
- char[] simpleTypeName,
- char[][] enclosingTypeNames,
- int modifiers,
- int accessibility) {
- this.packageName = packageName;
- this.simpleTypeName = simpleTypeName;
- this.enclosingTypeNames = enclosingTypeNames;
- this.modifiers = modifiers;
- this.accessibility = accessibility;
- this.bindingType=Binding.TYPE;
- }
- public AcceptedBinding(
- int bindingType,
- char[] packageName,
- char[] simpleTypeName,
- int modifiers,
- int accessibility) {
- this.bindingType=bindingType;
- this.packageName = packageName;
- this.simpleTypeName = simpleTypeName;
- this.modifiers = modifiers;
- this.accessibility = accessibility;
- }
- public char[] packageName;
- public char[] simpleTypeName;
- public char[][] enclosingTypeNames;
- public int modifiers;
- public int accessibility;
-
- public boolean mustBeQualified = false;
- public char[] fullyQualifiedName = null;
- public char[] qualifiedTypeName = null;
- public int bindingType;
-
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- buffer.append('{');
- buffer.append(packageName);
- buffer.append(',');
- buffer.append(simpleTypeName);
- buffer.append(',');
- buffer.append(CharOperation.concatWith(enclosingTypeNames, '.'));
- buffer.append('}');
- return buffer.toString();
- }
- }
-
- public HashtableOfObject typeCache;
-
- public static boolean DEBUG = false;
- public static boolean PERF = false;
-
- // temporary constants to quickly disabled polish features if necessary
- public final static boolean NO_TYPE_COMPLETION_ON_EMPTY_TOKEN = false;
-
- private final static char[] ERROR_PATTERN = "*error*".toCharArray(); //$NON-NLS-1$
- private final static char[] EXCEPTION_PATTERN = "*exception*".toCharArray(); //$NON-NLS-1$
- private final static char[] SEMICOLON = new char[] { ';' };
-
- private final static char[] CLASS = "Class".toCharArray(); //$NON-NLS-1$
- private final static char[] VOID = "void".toCharArray(); //$NON-NLS-1$
-
- private final static char[] VARARGS = "...".toCharArray(); //$NON-NLS-1$
-
- private final static char[] IMPORT = "import".toCharArray(); //$NON-NLS-1$
- private final static char[] STATIC = "static".toCharArray(); //$NON-NLS-1$
- private final static char[] ON_DEMAND = ".*".toCharArray(); //$NON-NLS-1$
- private final static char[] IMPORT_END = ";\n".toCharArray(); //$NON-NLS-1$
-
- private final static char[] JAVA_LANG_OBJECT_SIGNATURE =
- createTypeSignature(
- new char[]{},
- OBJECT);
- private final static char[] JAVA_LANG_NAME =
- CharOperation.concatWith(JAVA_LANG, '.');
-
-
- private final static int NONE = 0;
- private final static int SUPERTYPE = 1;
- private final static int SUBTYPE = 2;
-
- private final static int FIELD = 0;
- private final static int LOCAL = 1;
- private final static int ARGUMENT = 2;
-
- int expectedTypesPtr = -1;
- TypeBinding[] expectedTypes = new TypeBinding[1];
- int expectedTypesFilter;
- boolean hasJavaLangObjectAsExpectedType = false;
- int uninterestingBindingsPtr = -1;
- Binding[] uninterestingBindings = new Binding[1];
- int forbbidenBindingsPtr = -1;
- Binding[] forbbidenBindings = new Binding[1];
- int forbbidenBindingsFilter;
-
- ImportBinding[] favoriteReferenceBindings;
-
- boolean assistNodeIsClass;
- boolean assistNodeIsException;
- boolean assistNodeIsConstructor;
- boolean assistNodeIsSuperType;
- int assistNodeInJavadoc = 0;
- boolean assistNodeCanBeSingleMemberAnnotation = false;
-
- long targetedElement;
-
- IJavaScriptProject javaProject;
- CompletionParser parser;
- CompletionRequestor requestor;
- CompletionProblemFactory problemFactory;
- ProblemReporter problemReporter;
- char[] source;
- char[] completionToken;
- char[] qualifiedCompletionToken;
- boolean resolvingImports = false;
- boolean insideQualifiedReference = false;
- boolean noProposal = true;
- CategorizedProblem problem = null;
- char[] fileName = null;
- char [][]packageName;
- int startPosition, actualCompletionPosition, endPosition, offset;
- int javadocTagPosition; // Position of previous tag while completing in javadoc
- HashtableOfObject knownPkgs = new HashtableOfObject(10);
- HashtableOfObject knownTypes = new HashtableOfObject(10);
- Scanner nameScanner;
-
- /**
- * <p>Constructors accepted by {@link #acceptConstructor(int, char[], int, char[], char[][], char[][], String, AccessRestriction)}
- * to be processed by {@link #acceptConstructors(Scope)}</p>
- */
- private ObjectVector acceptedConstructors;
-
- static final char[] classField = "class".toCharArray(); //$NON-NLS-1$
- static final char[] lengthField = "length".toCharArray(); //$NON-NLS-1$
- static final char[] cloneMethod = "clone".toCharArray(); //$NON-NLS-1$
- static final char[] THIS = "this".toCharArray(); //$NON-NLS-1$
- static final char[] THROWS = "throws".toCharArray(); //$NON-NLS-1$
-
- static InvocationSite FakeInvocationSite = new InvocationSite(){
- public boolean isSuperAccess(){ return false; }
- public boolean isTypeAccess(){ return false; }
- public void setActualReceiverType(ReferenceBinding receiverType) {/* empty */}
- public void setDepth(int depth){/* empty */}
- public void setFieldIndex(int depth){/* empty */}
- public int sourceStart() { return 0; }
- public int sourceEnd() { return 0; }
- };
-
- /**
- * When performing an index search for binding matches this is
- * where the results will be stored
- */
- private ObjectVector acceptedBindings;
-
- /**
- * The CompletionEngine is responsible for computing source completions.
- *
- * It requires a searchable name environment, which supports some
- * specific search APIs, and a requestor to feed back the results to a UI.
- *
- * @param nameEnvironment org.eclipse.wst.jsdt.internal.codeassist.ISearchableNameEnvironment
- * used to resolve type/package references and search for types/packages
- * based on partial names.
- *
- * @param requestor org.eclipse.wst.jsdt.internal.codeassist.ICompletionRequestor
- * since the engine might produce answers of various forms, the engine
- * is associated with a requestor able to accept all possible completions.
- *
- * @param settings java.util.Map
- * set of options used to configure the code assist engine.
- */
- public CompletionEngine(
- SearchableEnvironment nameEnvironment,
- CompletionRequestor requestor,
- Map settings,
- IJavaScriptProject javaProject) {
- super(settings);
- this.javaProject = javaProject;
- this.requestor = requestor;
- this.nameEnvironment = nameEnvironment;
- this.typeCache = new HashtableOfObject(5);
-
- this.problemFactory = new CompletionProblemFactory(Locale.getDefault());
- this.problemReporter = new ProblemReporter(
- DefaultErrorHandlingPolicies.proceedWithAllProblems(),
- this.compilerOptions,
- problemFactory);
- this.lookupEnvironment =
- new LookupEnvironment(this, this.compilerOptions, this.problemReporter, nameEnvironment);
- this.parser =
- new CompletionParser(this.problemReporter);
- this.nameScanner =
- new Scanner(
- false /*comment*/,
- false /*whitespace*/,
- false /*nls*/,
- this.compilerOptions.sourceLevel,
- null /*taskTags*/,
- null/*taskPriorities*/,
- true/*taskCaseSensitive*/);
- }
-
- /**
- * One result of the search consists of a new type.
- *
- * NOTE - All package and type names are presented in their readable form:
- * Package names are in the form "a.b.c".
- * Nested type names are in the qualified form "A.I".
- * The default package is represented by an empty array.
- */
- public void acceptType(
- char[] packageName,
- char[] fileName,
- char[] simpleTypeName,
- char[][] enclosingTypeNames,
- int modifiers,
- AccessRestriction accessRestriction) {
-
- if (this.options.checkDeprecation && (modifiers & ClassFileConstants.AccDeprecated) != 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;
- }
- }
-
- int accessibility = IAccessRule.K_ACCESSIBLE;
- if(accessRestriction != null) {
- switch (accessRestriction.getProblemId()) {
- case IProblem.ForbiddenReference:
- if (this.options.checkForbiddenReference) {
- return;
- }
- accessibility = IAccessRule.K_NON_ACCESSIBLE;
- break;
- case IProblem.DiscouragedReference:
- if (this.options.checkDiscouragedReference) {
- return;
- }
- accessibility = IAccessRule.K_DISCOURAGED;
- break;
- }
- }
-
- if(this.acceptedBindings == null) {
- this.acceptedBindings = new ObjectVector();
- }
- char[] fullyQualifiedName = simpleTypeName;
- if(CharOperation.indexOf('.', simpleTypeName) < 0) {
- fullyQualifiedName = CharOperation.concat(packageName, simpleTypeName, '.');
- }
- this.acceptedBindings.add(new AcceptedBinding(packageName, fullyQualifiedName, enclosingTypeNames, modifiers, accessibility));
- }
-
- public void acceptBinding(
- char[] packageName,
- char[] fileName,
- char[] simpleTypeName,
- int bindingType,
- int modifiers,
- AccessRestriction accessRestriction) {
-
- if (this.options.checkDeprecation && (modifiers & ClassFileConstants.AccDeprecated) != 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;
- }
- }
-
- int accessibility = IAccessRule.K_ACCESSIBLE;
- if(accessRestriction != null) {
- switch (accessRestriction.getProblemId()) {
- case IProblem.ForbiddenReference:
- if (this.options.checkForbiddenReference) {
- return;
- }
- accessibility = IAccessRule.K_NON_ACCESSIBLE;
- break;
- case IProblem.DiscouragedReference:
- if (this.options.checkDiscouragedReference) {
- return;
- }
- accessibility = IAccessRule.K_DISCOURAGED;
- break;
- }
- }
-
- if(acceptedBindings == null) {
- acceptedBindings = new ObjectVector();
- }
- acceptedBindings.add(new AcceptedBinding(bindingType,packageName, simpleTypeName, modifiers, accessibility));
- }
-
- private void acceptTypes(Scope scope) {
- if(this.acceptedBindings == null) return;
-
- int length = this.acceptedBindings.size();
-
- if(length == 0) return;
-
- HashtableOfObject onDemandFound = new HashtableOfObject();
-
- next : for (int i = 0; i < length; i++) {
- AcceptedBinding acceptedType = (AcceptedBinding)this.acceptedBindings.elementAt(i);
- if (acceptedType.bindingType!=Binding.TYPE)
- continue;
- char[] packageName = acceptedType.packageName;
- char[] simpleTypeName = acceptedType.simpleTypeName;
- char[][] enclosingTypeNames = acceptedType.enclosingTypeNames;
- int modifiers = acceptedType.modifiers;
- int accessibility = acceptedType.accessibility;
-
- char[] typeName;
- char[] flatEnclosingTypeNames;
- if(enclosingTypeNames == null || enclosingTypeNames.length == 0) {
- flatEnclosingTypeNames = null;
- typeName = simpleTypeName;
- } else {
- flatEnclosingTypeNames = CharOperation.concatWith(acceptedType.enclosingTypeNames, '.');
- typeName = CharOperation.concat(flatEnclosingTypeNames, simpleTypeName, '.');
- }
-
- // only need to combine package and type name if the name is not already qualified
- // in most cases, if not all, it will already be in qualified state
- char[] fullyQualifiedName = typeName;
- if(CharOperation.indexOf('.', typeName) < 0) {
- fullyQualifiedName = CharOperation.concat(packageName, typeName, '.');
- }
-
- if (this.knownTypes.containsKey(fullyQualifiedName)) continue next;
-
- this.knownTypes.put(fullyQualifiedName, this);
-
- if (this.resolvingImports) {
- char[] completionName = CharOperation.concat(fullyQualifiedName, new char[] { ';' });
-
- int relevance = computeBaseRelevance();
- relevance += computeRelevanceForResolution();
- relevance += computeRelevanceForInterestingProposal();
- relevance += computeRelevanceForRestrictions(accessibility);
- if(insideQualifiedReference) {
- relevance += computeRelevanceForCaseMatching(this.completionToken, fullyQualifiedName);
- } else {
- relevance += computeRelevanceForCaseMatching(this.completionToken, simpleTypeName);
- }
-
- this.noProposal = false;
- if(!this.requestor.isIgnored(CompletionProposal.TYPE_REF)) {
- createTypeProposal(packageName, typeName, modifiers, accessibility, completionName, relevance);
- }
- } else {
- if(!this.importCachesInitialized) {
- this.initializeImportCaches();
- }
-
- for (int j = 0; j < this.importCacheCount; j++) {
- char[][] importName = this.importsCache[j];
- if(CharOperation.equals(typeName, importName[0])) {
- proposeType(
- packageName,
- simpleTypeName,
- modifiers,
- accessibility,
- typeName,
- fullyQualifiedName,
- !CharOperation.equals(fullyQualifiedName, importName[1]),
- scope);
- continue next;
- }
- }
-
-
- //if ((enclosingTypeNames == null || enclosingTypeNames.length == 0 ) && CharOperation.equals(this.currentPackageName, packageName)) {
- proposeType(
- packageName,
- simpleTypeName,
- modifiers,
- accessibility,
- typeName,
- fullyQualifiedName,
- true,scope);
- continue next;
- }
- }
- char[][] keys = onDemandFound.keyTable;
- Object[] values = onDemandFound.valueTable;
- int max = keys.length;
- for (int i = 0; i < max; i++) {
- if(keys[i] != null) {
- AcceptedBinding value = (AcceptedBinding) values[i];
- if(value != null) {
- proposeType(
- value.packageName,
- value.simpleTypeName,
- value.modifiers,
- value.accessibility,
- value.qualifiedTypeName,
- value.fullyQualifiedName,
- value.mustBeQualified, scope);
- }
- }
- }
- this.acceptedBindings = null; // reset
- }
-
- /**
- * @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)
- */
- public void acceptConstructor(
- int modifiers,
- char[] typeName,
- int parameterCount,
- char[][] parameterTypes,
- char[][] parameterNames,
- String path,
- AccessRestriction accessRestriction) {
-
- int accessibility = IAccessRule.K_ACCESSIBLE;
- if(accessRestriction != null) {
- switch (accessRestriction.getProblemId()) {
- case IProblem.ForbiddenReference:
- if (this.options.checkForbiddenReference) {
- return;
- }
- accessibility = IAccessRule.K_NON_ACCESSIBLE;
- break;
- case IProblem.DiscouragedReference:
- if (this.options.checkDiscouragedReference) {
- return;
- }
- accessibility = IAccessRule.K_DISCOURAGED;
- break;
- }
- }
-
- if(this.acceptedConstructors == null) {
- this.acceptedConstructors = new ObjectVector();
- }
- this.acceptedConstructors.add(
- new AcceptedConstructor(
- modifiers,
- typeName,
- parameterCount,
- parameterTypes,
- parameterNames,
- accessibility));
- }
-
- /**
- * <p>Creates proposals for all of the constructors accepted by
- * {@link #acceptConstructor(int, char[], int, char[][], char[][], String, AccessRestriction)}.</p>
- *
- * @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);
- }
- }
- }
- }
-
- public void acceptUnresolvedName(char[] name) {
- int relevance = computeBaseRelevance();
- relevance += computeRelevanceForResolution(false);
- relevance += computeRelevanceForInterestingProposal();
- relevance += computeRelevanceForCaseMatching(completionToken, name);
- relevance += computeRelevanceForQualification(false);
- relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE); // no access restriction for local variable
- CompletionEngine.this.noProposal = false;
- 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.setName(name);
- proposal.setCompletion(name);
- proposal.setFlags(Flags.AccDefault);
- proposal.setReplaceRange(CompletionEngine.this.startPosition - CompletionEngine.this.offset, CompletionEngine.this.endPosition - CompletionEngine.this.offset);
- proposal.setRelevance(relevance);
- CompletionEngine.this.requestor.accept(proposal);
- if(DEBUG) {
- CompletionEngine.this.printDebug(proposal);
- }
- }
- }
-
-
- /**
- * <p>When doing an index search for bindings this is where the results end up.</p>
- *
- * @param name the name of the binding
- * @param exactMatch <code>true</code> if an exact match is needed, <code>false</code> otherwise
- * @param prefixRequired
- * @param onlyConstructors <code>true</code> if only constructors should be accepted,
- * <code>false</code> otherwise. Only applies when matching on {@link Binding#METHOD}s.
- */
- private void acceptBindings(char[] name,boolean exactMatch, boolean prefixRequired) {
-
- if(this.acceptedBindings == null) return;
-
- int length = this.acceptedBindings.size();
-
- if(length == 0) return;
-
-
- 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];
-
-
- 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;
- }
-
- 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);
- }
-
-
- 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);
- }
- }
-
- // 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);
-
- 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);
- }
- }
-
- // 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);
- }
- }
-
- }
-
- }
- break;
- case Binding.VARIABLE:
- case Binding.LOCAL:
- case Binding.FIELD:
- {
- char[] completion = bindingName;
-
- if (binding2 instanceof LocalVariableBinding && binding2.isValidBinding()) {
- LocalVariableBinding variableBinding = (LocalVariableBinding) binding2;
-
- 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);
-
- 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;
-
- 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);
- }
- }
-
- // 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);
- }
- }
- } else {
- if (binding2!=null)
- //TODO: implement
- throw new UnimplementedException();
- }
-
- }
- 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;
- }
-
- /**
- * <p>Propose a constructor based on an {@link AcceptedConstructor}.</p>
- *
- * @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);
- }
-
- /**
- * <p>Create a constructor proposal based on the given information.</p>
- *
- * @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) {
-
- 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,
- singleNameReference,
- scope,
- insideTypeAnnotation,
- singleNameReference.isInsideAnnotationAttribute);
- // can be the start of a qualified type name
- findTypesAndPackages(this.completionToken, scope, new ObjectVector());
- if (!this.requestor.isIgnored(CompletionProposal.KEYWORD)) {
- if (this.completionToken != null && this.completionToken.length != 0) {
- findKeywords(this.completionToken, singleNameReference.possibleKeywords, false, false);
- } else {
- findTrueOrFalseKeywords(singleNameReference.possibleKeywords);
- }
- }
- if (singleNameReference.canBeExplicitConstructor && !this.requestor.isIgnored(CompletionProposal.METHOD_REF)){
- if (CharOperation.prefixEquals(this.completionToken, Keywords.THIS, false)) {
- ReferenceBinding ref = scope.enclosingSourceType();
- 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);
- }
- }
-
- } else if (astNode instanceof CompletionOnSingleTypeReference) {
-
- CompletionOnSingleTypeReference singleRef = (CompletionOnSingleTypeReference) astNode;
-
- this.completionToken = singleRef.token;
-
- this.assistNodeIsClass = singleRef.isClass();
- this.assistNodeIsException = singleRef.isException();
- this.assistNodeIsConstructor = singleRef.isConstructorType;
- this.assistNodeIsSuperType = singleRef.isSuperType();
-
-
- // can be the start of a qualified type name
- if (qualifiedBinding == null) {
- ObjectVector typesFound = new ObjectVector();
- if (this.assistNodeIsException && astNodeParent instanceof TryStatement) {
- findExceptionFromTryStatement(
- this.completionToken,
- null,
- scope.enclosingSourceType(),
- (BlockScope)scope,
- typesFound);
- }
- findTypesAndPackages(this.completionToken, scope, typesFound);
-
- } else if (!this.requestor.isIgnored(CompletionProposal.TYPE_REF)) {
- findMemberTypes(
- this.completionToken,
- (ReferenceBinding) qualifiedBinding,
- scope,
- scope.enclosingSourceType(),
- false,
- false,
- false,
- false,
- !this.assistNodeIsConstructor,
- null,
- new ObjectVector());
- }
- } else if (astNode instanceof CompletionOnSingleTypeName) {
-
- CompletionOnSingleTypeName singleRef = (CompletionOnSingleTypeName) astNode;
- this.completionToken = singleRef.token;
-
- this.assistNodeIsClass = true;
- this.assistNodeIsConstructor = true;
-
- // can be the start of a qualified type name
- if (qualifiedBinding == null) {
- ObjectVector typesFound = new ObjectVector();
- findTypesAndPackages(this.completionToken, scope, typesFound);
- } else if (!this.requestor.isIgnored(CompletionProposal.TYPE_REF)) {
- findMemberTypes(
- this.completionToken,
- (ReferenceBinding) qualifiedBinding,
- scope,
- scope.enclosingSourceType(),
- false,
- false,
- false,
- false,
- !this.assistNodeIsConstructor,
- null,
- new ObjectVector());
- }
- }
- else if (astNode instanceof CompletionOnQualifiedNameReference) {
-
- this.insideQualifiedReference = true;
- CompletionOnQualifiedNameReference ref =
- (CompletionOnQualifiedNameReference) astNode;
- this.completionToken = ref.completionIdentifier;
- long completionPosition = ref.sourcePositions[ref.sourcePositions.length - 1];
-
- if (qualifiedBinding.problemId() == ProblemReasons.NotFound) {
- setSourceRange((int) (completionPosition >>> 32), (int) completionPosition);
- // complete field members with missing fields type
- // class X {
- // Missing f;
- // 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))) {
- if(ref.tokens.length == 1) {
- findFieldsAndMethodsFromMissingFieldType(ref.tokens[0], scope, ref, insideTypeAnnotation);
- }
- }
- } else if (qualifiedBinding instanceof VariableBinding) {
- setSourceRange((int) (completionPosition >>> 32), (int) completionPosition);
- TypeBinding receiverType = ((VariableBinding) qualifiedBinding).type;
- if (receiverType != null) {
- findFieldsAndMethods(this.completionToken, receiverType, scope, ref, scope,false,false,false, null, null, null, false);
- } else if (this.assistNodeInJavadoc == 0 &&
- (this.requestor.isAllowingRequiredProposals(CompletionProposal.FIELD_REF, CompletionProposal.TYPE_REF) ||
- this.requestor.isAllowingRequiredProposals(CompletionProposal.METHOD_REF, CompletionProposal.TYPE_REF))) {
- boolean proposeField = !this.requestor.isIgnored(CompletionProposal.FIELD_REF);
- boolean proposeMethod = !this.requestor.isIgnored(CompletionProposal.METHOD_REF);
- if (proposeField || proposeMethod) {
- if (qualifiedBinding instanceof LocalVariableBinding) {
- // complete local variable members with missing variables type
- // class X {
- // void foo() {
- // Missing f;
- // f.|
- // }
- // }
- LocalVariableBinding localVariableBinding = (LocalVariableBinding) qualifiedBinding;
-
- findFieldsAndMethodsFromMissingType(
- this.completionToken,
- localVariableBinding.declaration.type,
- localVariableBinding.declaringScope,
- ref,
- scope);
- }
- }
- }
-
- } else if (qualifiedBinding instanceof ReferenceBinding) {
- boolean isInsideAnnotationAttribute = ref.isInsideAnnotationAttribute;
- ReferenceBinding receiverType = (ReferenceBinding) qualifiedBinding;
- setSourceRange((int) (completionPosition >>> 32), (int) completionPosition);
-
- if (!this.requestor.isIgnored(CompletionProposal.TYPE_REF)) {
- findMemberTypes(
- this.completionToken,
- receiverType,
- scope,
- scope.enclosingSourceType(),
- false,
- true,
- new ObjectVector());
- }
- if (!this.requestor.isIgnored(CompletionProposal.FIELD_REF)) {
- findClassField(this.completionToken, (TypeBinding) qualifiedBinding, scope);
- }
-
- MethodScope methodScope = null;
- if (!isInsideAnnotationAttribute &&
- !this.requestor.isIgnored(CompletionProposal.KEYWORD) &&
- ((scope instanceof MethodScope && !((MethodScope)scope).isStatic)
- || ((methodScope = scope.enclosingMethodScope()) != null && !methodScope.isStatic))) {
- if (this.completionToken.length > 0) {
- findKeywords(this.completionToken, new char[][]{Keywords.THIS}, false, true);
- } else {
- int relevance = computeBaseRelevance();
- relevance += computeRelevanceForResolution();
- relevance += computeRelevanceForInterestingProposal();
- relevance += computeRelevanceForCaseMatching(this.completionToken, Keywords.THIS);
- relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE); // no access restriction for keywords
- relevance += R_NON_INHERITED;
-
- this.noProposal = false;
- if (!this.requestor.isIgnored(CompletionProposal.KEYWORD)) {
- CompletionProposal proposal = this.createProposal(CompletionProposal.KEYWORD, this.actualCompletionPosition);
- proposal.setName(Keywords.THIS);
- proposal.setCompletion(Keywords.THIS);
- proposal.setReplaceRange(this.startPosition - this.offset, this.endPosition - this.offset);
- proposal.setRelevance(relevance);
- this.requestor.accept(proposal);
- if (DEBUG) {
- this.printDebug(proposal);
- }
- }
- }
- }
-
- if (!this.requestor.isIgnored(CompletionProposal.FIELD_REF)) {
- findFields(
- this.completionToken,
- receiverType,
- scope,
- new ObjectVector(),
- new ObjectVector(),
- true,
- ref,
- scope,
- false,
- false,
- null,
- null,
- null,
- false);
- }
-
- if (!isInsideAnnotationAttribute && !this.requestor.isIgnored(CompletionProposal.METHOD_REF)) {
- findMethods(
- this.completionToken,
- null,
- null,
- receiverType,
- scope,
- new ObjectVector(),
- true,
- false,
- false,
- ref,
- scope,
- false,
- false,
- false,
- null,
- null,
- null,
- false);
- }
-
- } else if (qualifiedBinding instanceof PackageBinding) {
-
- setSourceRange(astNode.sourceStart, (int) completionPosition);
- // replace to the end of the completion identifier
- findTypesAndSubpackages(this.completionToken, (PackageBinding) qualifiedBinding, scope);
- }
- } else if (astNode instanceof CompletionOnQualifiedTypeReference) {
-
- this.insideQualifiedReference = true;
-
- CompletionOnQualifiedTypeReference ref =
- (CompletionOnQualifiedTypeReference) astNode;
-
- this.assistNodeIsClass = ref.isClass();
- this.assistNodeIsException = ref.isException();
- this.assistNodeIsSuperType = ref.isSuperType();
-
- this.completionToken = ref.completionIdentifier;
- long completionPosition = ref.sourcePositions[ref.tokens.length];
-
- // get the source positions of the completion identifier
- if (qualifiedBinding instanceof ReferenceBinding) {
- if (!this.requestor.isIgnored(CompletionProposal.TYPE_REF)) {
- setSourceRange((int) (completionPosition >>> 32), (int) completionPosition);
-
- ObjectVector typesFound = new ObjectVector();
-
- if (this.assistNodeIsException && astNodeParent instanceof TryStatement) {
- findExceptionFromTryStatement(
- this.completionToken,
- (ReferenceBinding)qualifiedBinding,
- scope.enclosingSourceType(),
- (BlockScope)scope,
- typesFound);
- }
-
- findMemberTypes(
- this.completionToken,
- (ReferenceBinding) qualifiedBinding,
- scope,
- scope.enclosingSourceType(),
- false,
- false,
- typesFound);
- }
- } else if (qualifiedBinding instanceof PackageBinding) {
-
- setSourceRange(astNode.sourceStart, (int) completionPosition);
- // replace to the end of the completion identifier
- findTypesAndSubpackages(this.completionToken, (PackageBinding) qualifiedBinding, scope);
- }
- } else if (astNode instanceof CompletionOnQualifiedType) {
-
- this.insideQualifiedReference = true;
-
- CompletionOnQualifiedType ref =
- (CompletionOnQualifiedType) astNode;
-
- this.assistNodeIsClass = true;
-
- this.completionToken = ref.completionIdentifier;
- long completionPosition = ref.sourcePositions[ref.tokens.length];
-
- // get the source positions of the completion identifier
- if (qualifiedBinding instanceof ReferenceBinding) {
- if (!this.requestor.isIgnored(CompletionProposal.TYPE_REF)) {
- setSourceRange((int) (completionPosition >>> 32), (int) completionPosition);
-
- ObjectVector typesFound = new ObjectVector();
-
-
- findMemberTypes(
- this.completionToken,
- (ReferenceBinding) qualifiedBinding,
- scope,
- scope.enclosingSourceType(),
- false,
- false,
- typesFound);
- }
- }
- } else if (astNode instanceof CompletionOnMemberAccess) {
- this.insideQualifiedReference = true;
- CompletionOnMemberAccess access = (CompletionOnMemberAccess) astNode;
- 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) {
-
- this.completionToken = computeToken(access);
- setSourceRange((int) (completionPosition >>> 32) - (this.completionToken.length - access.token.length), (int) completionPosition);
-
- ObjectVector typesFound = new ObjectVector();
- findTypesAndPackages(this.completionToken, scope, typesFound);
- } 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().|
- // }
- // }
- if (this.assistNodeInJavadoc == 0 &&
- (this.requestor.isAllowingRequiredProposals(CompletionProposal.FIELD_REF, CompletionProposal.TYPE_REF) ||
- this.requestor.isAllowingRequiredProposals(CompletionProposal.METHOD_REF, CompletionProposal.TYPE_REF))) {
- ProblemMethodBinding problemMethodBinding = (ProblemMethodBinding) qualifiedBinding;
- findFieldsAndMethodsFromMissingReturnType(
- problemMethodBinding.selector,
- problemMethodBinding.parameters,
- scope,
- access,
- insideTypeAnnotation);
- }
- } else {
- if (!access.isInsideAnnotation) {
- if (!this.requestor.isIgnored(CompletionProposal.KEYWORD)) {
- findKeywords(this.completionToken, new char[][]{Keywords.NEW}, false, false);
- }
-
- findFieldsAndMethods(
- this.completionToken,
- ((TypeBinding) qualifiedBinding),
- scope,
- access,
- scope,
- access.isStatic,
- false,
- access.receiver instanceof SuperReference,
- null,
- null,
- null,
- false);
- // reset completion token to find types
- this.completionToken = computeToken(access);
- setSourceRange((int) (completionPosition >>> 32) - (this.completionToken.length - access.token.length), (int) completionPosition);
- findTypesAndPackages(this.completionToken, scope, new ObjectVector());
- // after looking for types set the completion token back to original value
- this.completionToken = access.token;
- setSourceRange((int) (completionPosition >>> 32), (int) completionPosition);
- if (qualifiedBinding instanceof FunctionTypeBinding) {
- FunctionTypeBinding functionTypeBinding = (FunctionTypeBinding) qualifiedBinding;
- if (functionTypeBinding.functionBinding!=null && functionTypeBinding.functionBinding.isConstructor())
- {
- ReferenceBinding declaringClass = (ReferenceBinding)functionTypeBinding.functionBinding.returnType;
- findFieldsAndMethods(
- this.completionToken,
- declaringClass,
- scope,
- access,
- scope,
- true,
- false,
- access.receiver instanceof SuperReference,
- null,
- null,
- null,
- false);
-
- }
-
- }
- }
- }
- }
-
- } else if (astNode instanceof CompletionOnMessageSend) {
- setSourceRange(astNode.sourceStart, astNode.sourceEnd, false);
-
- CompletionOnMessageSend messageSend = (CompletionOnMessageSend) astNode;
- TypeBinding[] argTypes = computeTypes(messageSend.arguments);
- this.completionToken = messageSend.selector;
- if (qualifiedBinding == null) {
- if (!this.requestor.isIgnored(CompletionProposal.METHOD_REF)) {
- findImplicitMessageSends(this.completionToken, argTypes, scope, messageSend, scope);
- }
- } else if (!this.requestor.isIgnored(CompletionProposal.METHOD_REF)) {
- findMethods(
- this.completionToken,
- null,
- argTypes,
- (messageSend.receiver!=null)?
- (ReferenceBinding)((ReferenceBinding) qualifiedBinding)
- :null,
- scope,
- new ObjectVector(),
- false,
- false,
- false,
- messageSend,
- scope,
- false,
- messageSend.receiver instanceof SuperReference,
- false,
- null,
- null,
- null,
- false);
- }
- } else if (astNode instanceof CompletionOnExplicitConstructorCall) {
- if (!this.requestor.isIgnored(CompletionProposal.METHOD_REF)) {
- setSourceRange(astNode.sourceStart, astNode.sourceEnd, false);
-
- CompletionOnExplicitConstructorCall constructorCall =
- (CompletionOnExplicitConstructorCall) astNode;
- TypeBinding[] argTypes = computeTypes(constructorCall.arguments);
- findConstructors(
- (ReferenceBinding) qualifiedBinding,
- argTypes,
- scope,
- constructorCall,
- false);
- }
- } else if (astNode instanceof CompletionOnQualifiedAllocationExpression) {
- setSourceRange(astNode.sourceStart, astNode.sourceEnd, false);
-
- CompletionOnQualifiedAllocationExpression allocExpression =
- (CompletionOnQualifiedAllocationExpression) astNode;
- TypeBinding[] argTypes = computeTypes(allocExpression.arguments);
-
- ReferenceBinding ref = (ReferenceBinding) qualifiedBinding;
- if (!this.requestor.isIgnored(CompletionProposal.METHOD_REF)
- && ref.isClass()) {
- findConstructors(
- ref,
- argTypes,
- scope,
- allocExpression,
- false);
- }
- if (!this.requestor.isIgnored(CompletionProposal.ANONYMOUS_CLASS_DECLARATION)){
- findAnonymousType(
- ref,
- argTypes,
- scope,
- allocExpression);
- }
- } else if (astNode instanceof CompletionOnClassLiteralAccess) {
- if (!this.requestor.isIgnored(CompletionProposal.FIELD_REF)) {
- CompletionOnClassLiteralAccess access = (CompletionOnClassLiteralAccess) astNode;
- setSourceRange(access.classStart, access.sourceEnd);
-
- this.completionToken = access.completionIdentifier;
-
- findClassField(this.completionToken, (TypeBinding) qualifiedBinding, scope);
- }
- } else if (astNode instanceof CompletionOnMethodName) {
- if (!this.requestor.isIgnored(CompletionProposal.VARIABLE_DECLARATION)) {
- CompletionOnMethodName method = (CompletionOnMethodName) astNode;
-
- setSourceRange(method.sourceStart, method.selectorEnd);
-
- FieldBinding[] fields = scope.enclosingSourceType().fields();
- char[][] excludeNames = new char[fields.length][];
- for(int i = 0 ; i < fields.length ; i++){
- excludeNames[i] = fields[i].name;
- }
-
- this.completionToken = method.selector;
-
- findVariableNames(this.completionToken, method.returnType, excludeNames, null, FIELD, method.modifiers);
- }
- } else if (astNode instanceof CompletionOnFieldName) {
- if (!this.requestor.isIgnored(CompletionProposal.VARIABLE_DECLARATION)) {
- CompletionOnFieldName field = (CompletionOnFieldName) astNode;
-
- FieldBinding[] fields = scope.enclosingSourceType().fields();
- char[][] excludeNames = new char[fields.length][];
- for(int i = 0 ; i < fields.length ; i++){
- excludeNames[i] = fields[i].name;
- }
-
- this.completionToken = field.realName;
-
- findVariableNames(field.realName, field.type, excludeNames, null, FIELD, field.modifiers);
- }
- } else if (astNode instanceof CompletionOnLocalName || astNode instanceof CompletionOnArgumentName) {
- if (!this.requestor.isIgnored(CompletionProposal.VARIABLE_DECLARATION)) {
- LocalDeclaration variable = (LocalDeclaration) astNode;
-
- int kind;
- if (variable instanceof CompletionOnLocalName){
- this.completionToken = ((CompletionOnLocalName) variable).realName;
- kind = LOCAL;
- } else {
- CompletionOnArgumentName arg = (CompletionOnArgumentName) variable;
- this.completionToken = arg.realName;
- kind = arg.isCatchArgument ? LOCAL : ARGUMENT;
- }
-
- char[][] alreadyDefinedName = computeAlreadyDefinedName((BlockScope)scope, variable);
-
- char[][] forbiddenNames = findVariableFromUnresolvedReference(variable, (BlockScope)scope, alreadyDefinedName);
-
- LocalVariableBinding[] locals = ((BlockScope)scope).locals;
- char[][] discouragedNames = new char[locals.length][];
- int localCount = 0;
- for(int i = 0 ; i < locals.length ; i++){
- if (locals[i] != null) {
- discouragedNames[localCount++] = locals[i].name;
- }
- }
-
- System.arraycopy(discouragedNames, 0, discouragedNames = new char[localCount][], 0, localCount);
-
- findVariableNames(this.completionToken, variable.type, discouragedNames, forbiddenNames, kind, variable.modifiers);
- }
- } else if (astNode instanceof CompletionOnKeyword) {
- if (!this.requestor.isIgnored(CompletionProposal.KEYWORD)) {
- CompletionOnKeyword keyword = (CompletionOnKeyword)astNode;
- findKeywords(keyword.getToken(), keyword.getPossibleKeywords(), keyword.canCompleteEmptyToken(), false);
- }
- } else if(astNode instanceof CompletionOnBrankStatementLabel) {
- if (!this.requestor.isIgnored(CompletionProposal.LABEL_REF)) {
- CompletionOnBrankStatementLabel label = (CompletionOnBrankStatementLabel) astNode;
-
- this.completionToken = label.label;
-
- this.findLabels(this.completionToken, label.possibleLabels);
- }
- } else if(astNode instanceof CompletionOnMessageSendName) {
- if (!this.requestor.isIgnored(CompletionProposal.METHOD_REF)) {
- CompletionOnMessageSendName messageSend = (CompletionOnMessageSendName) astNode;
-
- 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) {
- if (astNode instanceof CompletionOnJavadocSingleTypeReference) {
-
- CompletionOnJavadocSingleTypeReference typeRef = (CompletionOnJavadocSingleTypeReference) astNode;
- this.completionToken = typeRef.token;
- this.javadocTagPosition = typeRef.tagSourceStart;
- setSourceRange(typeRef.sourceStart, typeRef.sourceEnd);
- findTypesAndPackages(this.completionToken, scope, new ObjectVector());
-
- } else if (astNode instanceof CompletionOnJavadocQualifiedTypeReference) {
-
- this.insideQualifiedReference = true;
-
- CompletionOnJavadocQualifiedTypeReference typeRef = (CompletionOnJavadocQualifiedTypeReference) astNode;
- this.completionToken = typeRef.completionIdentifier;
- long completionPosition = typeRef.sourcePositions[typeRef.tokens.length];
- this.javadocTagPosition = typeRef.tagSourceStart;
-
- // get the source positions of the completion identifier
- if (qualifiedBinding instanceof ReferenceBinding) {
- if (!this.requestor.isIgnored(CompletionProposal.TYPE_REF) ||
- ((this.assistNodeInJavadoc & CompletionOnJavadoc.TEXT) != 0 && !this.requestor.isIgnored(CompletionProposal.JSDOC_TYPE_REF))) {
- int rangeStart = typeRef.completeInText() ? typeRef.sourceStart : (int) (completionPosition >>> 32);
- setSourceRange(rangeStart, (int) completionPosition);
- findMemberTypes(this.completionToken,
- (ReferenceBinding) qualifiedBinding,
- scope,
- scope.enclosingSourceType(),
- false,
- false,
- new ObjectVector());
- }
- } else if (qualifiedBinding instanceof PackageBinding) {
-
- setSourceRange(astNode.sourceStart, (int) completionPosition);
- // replace to the end of the completion identifier
- findTypesAndSubpackages(this.completionToken, (PackageBinding) qualifiedBinding, scope);
- }
- } else if (astNode instanceof CompletionOnJavadocFieldReference) {
-
- this.insideQualifiedReference = true;
- CompletionOnJavadocFieldReference fieldRef = (CompletionOnJavadocFieldReference) astNode;
- this.completionToken = fieldRef.token;
- long completionPosition = fieldRef.nameSourcePosition;
- this.javadocTagPosition = fieldRef.tagSourceStart;
-
- if (fieldRef.receiverType != null && fieldRef.receiverType.isValidBinding()) {
- ReferenceBinding receiverType = (ReferenceBinding) fieldRef.receiverType;
- int rangeStart = (int) (completionPosition >>> 32);
- if (fieldRef.receiver.isThis()) {
- if (fieldRef.completeInText()) {
- rangeStart = fieldRef.separatorPosition;
- }
- } else if (fieldRef.completeInText()) {
- rangeStart = fieldRef.receiver.sourceStart;
- }
- setSourceRange(rangeStart, (int) completionPosition);
-
- if (!this.requestor.isIgnored(CompletionProposal.FIELD_REF)
- || !this.requestor.isIgnored(CompletionProposal.JSDOC_FIELD_REF)) {
- findFields(this.completionToken,
- receiverType,
- scope,
- new ObjectVector(),
- new ObjectVector(),
- false, /*not only static */
- fieldRef,
- scope,
- false,
- true,
- null,
- null,
- null,
- false);
- }
-
- if (!this.requestor.isIgnored(CompletionProposal.METHOD_REF)
- || !this.requestor.isIgnored(CompletionProposal.JSDOC_METHOD_REF)) {
- findMethods(this.completionToken,
- null,
- null,
- receiverType,
- scope,
- new ObjectVector(),
- false, /*not only static */
- false,
- false,
- fieldRef,
- scope,
- false,
- false,
- true,
- null,
- null,
- null,
- false);
- if (fieldRef.receiverType instanceof ReferenceBinding) {
- ReferenceBinding refBinding = (ReferenceBinding)fieldRef.receiverType;
- if (this.completionToken == null
- || CharOperation.prefixEquals(this.completionToken, refBinding.sourceName)
- || (this.options.camelCaseMatch && CharOperation.camelCaseMatch(this.completionToken, refBinding.sourceName))) {
- findConstructors(refBinding, null, scope, fieldRef, false);
- }
- }
- }
- }
- } else if (astNode instanceof CompletionOnJavadocMessageSend) {
-
- CompletionOnJavadocMessageSend messageSend = (CompletionOnJavadocMessageSend) astNode;
- TypeBinding[] argTypes = null; //computeTypes(messageSend.arguments);
- this.completionToken = messageSend.selector;
- this.javadocTagPosition = messageSend.tagSourceStart;
-
- // Set source range
- int rangeStart = astNode.sourceStart;
- if (messageSend.receiver!=null && messageSend.receiver.isThis()) {
- if (messageSend.completeInText()) {
- rangeStart = messageSend.separatorPosition;
- }
- } else if (messageSend.completeInText()) {
- rangeStart = messageSend.receiver.sourceStart;
- }
- setSourceRange(rangeStart, astNode.sourceEnd, false);
-
- if (qualifiedBinding == null) {
- if (!this.requestor.isIgnored(CompletionProposal.METHOD_REF)) {
- findImplicitMessageSends(this.completionToken, argTypes, scope, messageSend, scope);
- }
- } else if (!this.requestor.isIgnored(CompletionProposal.METHOD_REF)) {
- findMethods(
- this.completionToken,
- null,
- argTypes,
- ((ReferenceBinding) qualifiedBinding),
- scope,
- new ObjectVector(),
- false,
- false/* prefix match */,
- false,
- messageSend,
- scope,
- false,
- messageSend.receiver instanceof SuperReference,
- true,
- null,
- null,
- null,
- false);
- }
- } else if (astNode instanceof CompletionOnJavadocAllocationExpression) {
-// setSourceRange(astNode.sourceStart, astNode.sourceEnd, false);
-
- CompletionOnJavadocAllocationExpression allocExpression = (CompletionOnJavadocAllocationExpression) astNode;
- this.javadocTagPosition = allocExpression.tagSourceStart;
- int rangeStart = astNode.sourceStart;
- if (allocExpression.type.isThis()) {
- if (allocExpression.completeInText()) {
- rangeStart = allocExpression.separatorPosition;
- }
- } else if (allocExpression.completeInText()) {
- rangeStart = allocExpression.type.sourceStart;
- }
- setSourceRange(rangeStart, astNode.sourceEnd, false);
- TypeBinding[] argTypes = computeTypes(allocExpression.arguments);
-
- ReferenceBinding ref = (ReferenceBinding) qualifiedBinding;
- if (!this.requestor.isIgnored(CompletionProposal.METHOD_REF) && ref.isClass()) {
- findConstructors(ref, argTypes, scope, allocExpression, false);
- }
- } else if (astNode instanceof CompletionOnJavadocParamNameReference) {
- if (!this.requestor.isIgnored(CompletionProposal.JSDOC_PARAM_REF)) {
- CompletionOnJavadocParamNameReference paramRef = (CompletionOnJavadocParamNameReference) astNode;
- setSourceRange(paramRef.tagSourceStart, paramRef.tagSourceEnd);
- findJavadocParamNames(paramRef.token, paramRef.missingParams, false);
- }
- } else if (astNode instanceof CompletionOnJavadocTag) {
- CompletionOnJavadocTag javadocTag = (CompletionOnJavadocTag) astNode;
- setSourceRange(javadocTag.tagSourceStart, javadocTag.sourceEnd);
- findJavadocBlockTags(javadocTag);
- findJavadocInlineTags(javadocTag);
- }
- }
- return true;
- }
-
- public void complete(IType type, char[] snippet, int position, char[][] localVariableTypeNames, char[][] localVariableNames, int[] localVariableModifiers, boolean isStatic){
- if(this.requestor != null){
- this.requestor.beginReporting();
- }
- boolean contextAccepted = false;
- IType topLevelType = type;
- while(topLevelType.getDeclaringType() != null) {
- topLevelType = topLevelType.getDeclaringType();
- }
-
- this.fileName = topLevelType.getParent().getElementName().toCharArray();
- CompilationResult compilationResult = new CompilationResult(this.fileName, this.packageName, 1, 1, this.compilerOptions.maxProblemsPerUnit);
-
- CompilationUnitDeclaration compilationUnit = null;
-
- try {
- // TypeConverter is used instead of SourceTypeConverter because the type
- // to convert can be a binary type or a source type
- TypeDeclaration typeDeclaration = null;
- if (type instanceof SourceType) {
- SourceType sourceType = (SourceType) type;
- ISourceType info = (ISourceType) sourceType.getElementInfo();
- compilationUnit = SourceTypeConverter.buildCompilationUnit(
- new ISourceType[] {info},//sourceTypes[0] is always toplevel here
- SourceTypeConverter.FIELD_AND_METHOD // need field and methods
- | SourceTypeConverter.MEMBER_TYPE, // need member types
- // no need for field initialization
- this.problemReporter,
- compilationResult);
- if (compilationUnit.types != null)
- typeDeclaration = compilationUnit.types[0];
- } else {
- compilationUnit = new CompilationUnitDeclaration(this.problemReporter, compilationResult, 0);
- typeDeclaration = BinaryTypeConverter.buildTypeDeclaration(type, compilationUnit, compilationResult);
- }
-
- if(typeDeclaration != null) {
- // build AST from snippet
- Initializer fakeInitializer = parseSnippeInitializer(snippet, position, localVariableTypeNames, localVariableNames, localVariableModifiers, isStatic);
-
- // merge AST
- FieldDeclaration[] oldFields = typeDeclaration.fields;
- FieldDeclaration[] newFields = null;
- if (oldFields != null) {
- newFields = new FieldDeclaration[oldFields.length + 1];
- System.arraycopy(oldFields, 0, newFields, 0, oldFields.length);
- newFields[oldFields.length] = fakeInitializer;
- } else {
- newFields = new FieldDeclaration[] {fakeInitializer};
- }
- typeDeclaration.fields = newFields;
-
- if(DEBUG) {
- System.out.println("SNIPPET COMPLETION AST :"); //$NON-NLS-1$
- System.out.println(compilationUnit.toString());
- }
-
- if (compilationUnit.types != null) {
- try {
- this.lookupEnvironment.buildTypeBindings(compilationUnit, null /*no access restriction*/);
-
- if ((this.unitScope = compilationUnit.scope) != null) {
- this.lookupEnvironment.completeTypeBindings(compilationUnit, true);
- compilationUnit.scope.faultInTypes();
- compilationUnit.resolve();
- }
- } catch (CompletionNodeFound e) {
- // completionNodeFound = true;
- if (e.astNode != null) {
- // if null then we found a problem in the completion node
- contextAccepted = complete(e.astNode, this.parser.assistNodeParent, e.qualifiedBinding, e.scope, e.insideTypeAnnotation);
- }
- }
- }
- if(this.noProposal && this.problem != null) {
- if(!contextAccepted) {
- contextAccepted = true;
- this.requestor.acceptContext(new CompletionContext());
- }
- this.requestor.completionFailure(this.problem);
- if(DEBUG) {
- this.printDebug(this.problem);
- }
- }
- }
- } catch (IndexOutOfBoundsException e) { // work-around internal failure - 1GEMF6D (added with fix of 99629)
- if(DEBUG) {
- System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$
- e.printStackTrace(System.out);
- }
- } catch (InvalidCursorLocation e) { // may eventually report a usefull error (added to fix 99629)
- if(DEBUG) {
- System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$
- e.printStackTrace(System.out);
- }
- } catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object (added with fix of 99629)
- if(DEBUG) {
- System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$
- e.printStackTrace(System.out);
- }
- } catch (CompletionNodeFound e){ // internal failure - bugs 5618 (added with fix of 99629)
- if(DEBUG) {
- System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$
- e.printStackTrace(System.out);
- }
- } catch(JavaScriptModelException e) {
- // Do nothing
- }
- if(!contextAccepted) {
- contextAccepted = true;
- this.requestor.acceptContext(new CompletionContext());
- }
- if(this.requestor != null){
- this.requestor.endReporting();
- }
- }
-
- private Initializer parseSnippeInitializer(char[] snippet, int position, char[][] localVariableTypeNames, char[][] localVariableNames, int[] localVariableModifiers, boolean isStatic){
- StringBuffer prefix = new StringBuffer();
- prefix.append("public class FakeType {\n "); //$NON-NLS-1$
- if(isStatic) {
- prefix.append("static "); //$NON-NLS-1$
- }
- prefix.append("{\n"); //$NON-NLS-1$
- for (int i = 0; i < localVariableTypeNames.length; i++) {
- ASTNode.printModifiers(localVariableModifiers[i], prefix);
- prefix.append(' ');
- prefix.append(localVariableTypeNames[i]);
- prefix.append(' ');
- prefix.append(localVariableNames[i]);
- prefix.append(';');
- }
-
- char[] fakeSource = CharOperation.concat(prefix.toString().toCharArray(), snippet, "}}".toCharArray());//$NON-NLS-1$
- this.offset = prefix.length();
-
- String encoding = this.compilerOptions.defaultEncoding;
- BasicCompilationUnit fakeUnit = new BasicCompilationUnit(
- fakeSource,
- null,
- "FakeType.java", //$NON-NLS-1$
- encoding);
-
- this.actualCompletionPosition = prefix.length() + position - 1;
-
- CompilationResult fakeResult = new CompilationResult(fakeUnit, 1, 1, this.compilerOptions.maxProblemsPerUnit);
- CompilationUnitDeclaration fakeAST = this.parser.dietParse(fakeUnit, fakeResult, this.actualCompletionPosition);
-
- parseBlockStatements(fakeAST, this.actualCompletionPosition);
-
- return (Initializer)fakeAST.types[0].fields[0];
- }
-
- /**
- * Ask the engine to compute a completion at the specified position
- * of the given compilation unit.
- *
- * No return
- * completion results are answered through a requestor.
- *
- * @param sourceUnit org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit
- * the source of the current compilation unit.
- *
- * @param completionPosition int
- * a position in the source where the completion is taking place.
- * This position is relative to the source provided.
- */
- public void complete(ICompilationUnit sourceUnit, int completionPosition, int pos) {
-
- if(DEBUG) {
- System.out.print("COMPLETION IN "); //$NON-NLS-1$
- System.out.print(sourceUnit.getFileName());
- System.out.print(" AT POSITION "); //$NON-NLS-1$
- System.out.println(completionPosition);
- System.out.println("COMPLETION - Source :"); //$NON-NLS-1$
- System.out.println(sourceUnit.getContents());
- }
- this.requestor.beginReporting();
- boolean contextAccepted = false;
- try {
- this.fileName = sourceUnit.getFileName();
- this.packageName= CharOperation.NO_CHAR_CHAR;
- this.actualCompletionPosition = completionPosition - 1;
- this.offset = pos;
- // for now until we can change the UI.
- CompilationResult result = new CompilationResult(sourceUnit, 1, 1, this.compilerOptions.maxProblemsPerUnit);
- CompilationUnitDeclaration parsedUnit = this.parser.dietParse(sourceUnit, result, this.actualCompletionPosition);
- // boolean completionNodeFound = false;
- if (parsedUnit != null) {
- if(DEBUG) {
- System.out.println("COMPLETION - Diet AST :"); //$NON-NLS-1$
- System.out.println(parsedUnit.toString());
- }
-
- this.parser.inferTypes(parsedUnit, this.compilerOptions);
-
- ImportReference[] imports = parsedUnit.imports;
- if (imports != null) {
- for (int i = 0, length = imports.length; i < length; i++) {
- ImportReference importReference = imports[i];
- if (importReference instanceof CompletionOnImportReference) {
- this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/);
- if ((this.unitScope = parsedUnit.scope) != null) {
- contextAccepted = true;
- this.buildContext(importReference, null, null, null);
-
- setSourceRange(
- importReference.sourceStart,
- importReference.declarationSourceEnd);
-
- char[][] oldTokens = importReference.tokens;
- int tokenCount = oldTokens.length;
- if (tokenCount == 1) {
- findImports((CompletionOnImportReference)importReference, true);
- } else if(tokenCount > 1){
- this.insideQualifiedReference = true;
-
- char[] lastToken = oldTokens[tokenCount - 1];
- char[][] qualifierTokens = CharOperation.subarray(oldTokens, 0, tokenCount - 1);
-
- Binding binding = this.unitScope.getTypeOrPackage(qualifierTokens);
- if(binding != null) {
- if(binding instanceof PackageBinding) {
- findImports((CompletionOnImportReference)importReference, false);
- } else {
- ReferenceBinding ref = (ReferenceBinding) binding;
- if(!this.requestor.isIgnored(CompletionProposal.TYPE_REF)) {
- this.findImportsOfMemberTypes(lastToken, ref);
- }
- }
- }
- }
-
- if(this.noProposal && this.problem != null) {
- this.requestor.completionFailure(this.problem);
- if(DEBUG) {
- this.printDebug(this.problem);
- }
- }
- }
- return;
- } else if(importReference instanceof CompletionOnKeyword) {
- contextAccepted = true;
- this.buildContext(importReference, null, null, null);
- if(!this.requestor.isIgnored(CompletionProposal.KEYWORD)) {
- setSourceRange(importReference.sourceStart, importReference.sourceEnd);
- CompletionOnKeyword keyword = (CompletionOnKeyword)importReference;
- findKeywords(keyword.getToken(), keyword.getPossibleKeywords(), false, false);
- }
- if(this.noProposal && this.problem != null) {
- this.requestor.completionFailure(this.problem);
- if(DEBUG) {
- this.printDebug(this.problem);
- }
- }
- return;
- }
- }
- }
-
- if (parsedUnit.statements != null) {
- try {
- this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/);
-
- if ((this.unitScope = parsedUnit.scope) != null) {
- this.source = sourceUnit.getContents();
- this.lookupEnvironment.completeTypeBindings(parsedUnit, true);
- parsedUnit.scope.faultInTypes();
- if (Parser.DO_DIET_PARSE)
- parseBlockStatements(parsedUnit, this.actualCompletionPosition);
- if(DEBUG) {
- System.out.println("COMPLETION - AST :"); //$NON-NLS-1$
- System.out.println(parsedUnit.toString());
- }
- parsedUnit.resolve();
- }
- } catch (CompletionNodeFound e) {
- // completionNodeFound = true;
- if (e.astNode != null) {
- if(DEBUG) {
- System.out.print("COMPLETION - Completion node : "); //$NON-NLS-1$
- System.out.println(e.astNode.toString());
- if(this.parser.assistNodeParent != null) {
- System.out.print("COMPLETION - Parent Node : "); //$NON-NLS-1$
- System.out.println(this.parser.assistNodeParent);
- }
- }
- // if null then we found a problem in the completion node
- contextAccepted = complete(e.astNode, this.parser.assistNodeParent, e.qualifiedBinding, e.scope, e.insideTypeAnnotation);
- }
- }
- }
- parsedUnit.cleanUp();
- }
-
- if(this.noProposal && this.problem != null) {
- if(!contextAccepted) {
- contextAccepted = true;
- CompletionContext context = new CompletionContext();
- context.setOffset(completionPosition - this.offset);
- context.setTokenKind(CompletionContext.TOKEN_KIND_UNKNOWN);
- this.requestor.acceptContext(context);
- }
- this.requestor.completionFailure(this.problem);
- if(DEBUG) {
- this.printDebug(this.problem);
- }
- }
- /* Ignore package, import, class & interface keywords for now...
- if (!completionNodeFound) {
- if (parsedUnit == null || parsedUnit.types == null) {
- // this is not good enough... can still be trying to define a second type
- CompletionScanner scanner = (CompletionScanner) this.parser.scanner;
- setSourceRange(scanner.completedIdentifierStart, scanner.completedIdentifierEnd);
- findKeywords(scanner.completionIdentifier, mainDeclarations, null);
- }
- // currently have no way to know if extends/implements are possible keywords
- }
- */
- } catch (IndexOutOfBoundsException e) { // work-around internal failure - 1GEMF6D
- if(DEBUG) {
- System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$
- e.printStackTrace(System.out);
- }
- } catch (InvalidCursorLocation e) { // may eventually report a usefull error
- if(DEBUG) {
- System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$
- e.printStackTrace(System.out);
- }
- } catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object
- if(DEBUG) {
- System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$
- e.printStackTrace(System.out);
- }
- } catch (CompletionNodeFound e){ // internal failure - bugs 5618
- if(DEBUG) {
- System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$
- e.printStackTrace(System.out);
- }
- } finally {
- this.parser=null;
- reset();
- if(!contextAccepted) {
- contextAccepted = true;
- CompletionContext context = new CompletionContext();
- context.setTokenKind(CompletionContext.TOKEN_KIND_UNKNOWN);
- context.setOffset(completionPosition - this.offset);
- this.requestor.acceptContext(context);
- }
- this.requestor.endReporting();
- }
- }
-
- private TypeBinding[] computeTypes(Expression[] arguments) {
- if (arguments == null) return null;
- int argsLength = arguments.length;
- TypeBinding[] argTypes = new TypeBinding[argsLength];
- for (int a = argsLength; --a >= 0;) {
- argTypes[a] = arguments[a].resolvedType;
- }
- return argTypes;
- }
-
- private void findAnonymousType(
- ReferenceBinding currentType,
- TypeBinding[] argTypes,
- Scope scope,
- InvocationSite invocationSite) {
-
- findConstructors(
- currentType,
- argTypes,
- scope,
- invocationSite,
- true);
- }
-
- private void findClassField(char[] token, TypeBinding receiverType, Scope scope) {
-
- if (token == null) return;
-
- if (token.length <= classField.length
- && CharOperation.prefixEquals(token, classField, false /* ignore case */
- )) {
- int relevance = computeBaseRelevance();
- relevance += computeRelevanceForResolution();
- relevance += computeRelevanceForInterestingProposal();
- relevance += computeRelevanceForCaseMatching(token, classField);
- relevance += computeRelevanceForExpectingType(scope.getJavaLangClass());
- relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE); //no access restriction for class field
- relevance += R_NON_INHERITED;
-
- this.noProposal = false;
- if(!this.requestor.isIgnored(CompletionProposal.FIELD_REF)) {
- CompletionProposal proposal = this.createProposal(CompletionProposal.FIELD_REF, this.actualCompletionPosition);
- //proposal.setDeclarationSignature(null);
- char[] signature =
- createNonGenericTypeSignature(CLASS);
- if (this.compilerOptions.sourceLevel > ClassFileConstants.JDK1_4) {
- // add type argument
- char[] typeArgument = getTypeSignature(receiverType);
- int oldLength = signature.length;
- int argumentLength = typeArgument.length;
- int newLength = oldLength + argumentLength + 2;
- System.arraycopy(signature, 0, signature = new char[newLength], 0, oldLength - 1);
- signature[oldLength - 1] = '<';
- System.arraycopy(typeArgument, 0, signature, oldLength , argumentLength);
- signature[newLength - 2] = '>';
- signature[newLength - 1] = ';';
- }
- proposal.setSignature(signature);
- //proposal.setDeclarationPackageName(null);
- //proposal.setDeclarationTypeName(null);
- proposal.setPackageName(CharOperation.concatWith(JAVA_LANG, '.'));
- proposal.setTypeName(CLASS);
- proposal.setName(classField);
- proposal.setCompletion(classField);
- proposal.setFlags(Flags.AccStatic | Flags.AccPublic);
- proposal.setReplaceRange(this.startPosition - this.offset, this.endPosition - this.offset);
- proposal.setRelevance(relevance);
- this.requestor.accept(proposal);
- if(DEBUG) {
- this.printDebug(proposal);
- }
- }
- }
- }
-
- private void findExceptionFromTryStatement(
- char[] typeName,
- ReferenceBinding exceptionType,
- ReferenceBinding receiverType,
- SourceTypeBinding invocationType,
- BlockScope scope,
- ObjectVector typesFound,
- boolean searchSuperClasses) {
-
-
- if (searchSuperClasses) {
- ReferenceBinding javaLangThrowable = scope.getJavaLangThrowable();
- if (exceptionType != javaLangThrowable) {
- ReferenceBinding superClass = exceptionType.superclass();
- while(superClass != null && superClass != javaLangThrowable) {
- findExceptionFromTryStatement(typeName, superClass, receiverType, invocationType, scope, typesFound, false);
- superClass = superClass.superclass();
- }
- }
- }
-
- if (typeName.length > exceptionType.sourceName.length)
- return;
-
- if (!CharOperation.prefixEquals(typeName, exceptionType.sourceName, false/* ignore case */)
- && !(this.options.camelCaseMatch && CharOperation.camelCaseMatch(typeName, exceptionType.sourceName)))
- return;
-
- if (this.options.checkDeprecation &&
- exceptionType.isViewedAsDeprecated() &&
- !scope.isDefinedInSameUnit(exceptionType))
- return;
-
- if (this.options.checkVisibility) {
- if (invocationType != null) {
- if (receiverType != null) {
- if (!exceptionType.canBeSeenBy(receiverType, invocationType)) return;
- } else {
- if (!exceptionType.canBeSeenBy(exceptionType, invocationType)) return;
- }
- } else if(!exceptionType.canBeSeenBy(this.unitScope.getDefaultPackage())) {
- return;
- }
- }
-
- for (int j = typesFound.size; --j >= 0;) {
- ReferenceBinding otherType = (ReferenceBinding) typesFound.elementAt(j);
-
- if (exceptionType == otherType)
- return;
-
- if (CharOperation.equals(exceptionType.sourceName, otherType.sourceName, true)) {
-
- if (exceptionType.enclosingType().isSuperclassOf(otherType.enclosingType()))
- return;
-
- }
- }
-
- typesFound.add(exceptionType);
-
- char[] completionName = exceptionType.sourceName();
-
- boolean isQualified = false;
-
- if(!this.insideQualifiedReference) {
- isQualified = true;
-
- char[] memberPackageName = exceptionType.qualifiedPackageName();
- char[] memberTypeName = exceptionType.sourceName();
- char[] memberEnclosingTypeNames = null;
-
- ReferenceBinding enclosingType = exceptionType.enclosingType();
- if (enclosingType != null) {
- memberEnclosingTypeNames = exceptionType.enclosingType().qualifiedSourceName();
- }
-
- Scope currentScope = scope;
- done : while (currentScope != null) { // done when a COMPILATION_UNIT_SCOPE is found
-
- switch (currentScope.kind) {
-
- case Scope.METHOD_SCOPE :
- case Scope.BLOCK_SCOPE :
- BlockScope blockScope = (BlockScope) currentScope;
-
- for (int j = 0, length = blockScope.subscopeCount; j < length; j++) {
-
- if (blockScope.subscopes[j] instanceof ClassScope) {
- SourceTypeBinding localType =
- ((ClassScope) blockScope.subscopes[j]).referenceContext.binding;
-
- if (localType == exceptionType) {
- isQualified = false;
- break done;
- }
- }
- }
- break;
-
- case Scope.CLASS_SCOPE :
- SourceTypeBinding type = ((ClassScope)currentScope).referenceContext.binding;
- ReferenceBinding[] memberTypes = type.memberTypes();
- if (memberTypes != null) {
- for (int j = 0; j < memberTypes.length; j++) {
- if (memberTypes[j] == exceptionType) {
- isQualified = false;
- break done;
- }
- }
- }
-
-
- break;
-
- case Scope.COMPILATION_UNIT_SCOPE :
- SourceTypeBinding[] types = ((CompilationUnitScope)currentScope).topLevelTypes;
- if (types != null) {
- for (int j = 0; j < types.length; j++) {
- if (types[j] == exceptionType) {
- isQualified = false;
- break done;
- }
- }
- }
- break done;
- }
- currentScope = currentScope.parent;
- }
-
- if (isQualified && mustQualifyType(memberPackageName, memberTypeName, memberEnclosingTypeNames, exceptionType.modifiers)) {
- if (memberPackageName == null || memberPackageName.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 {
- isQualified = false;
- }
-
- if (isQualified) {
- completionName =
- CharOperation.concat(
- memberPackageName,
- CharOperation.concat(
- memberEnclosingTypeNames,
- memberTypeName,
- '.'),
- '.');
- }
- }
-
- int relevance = computeBaseRelevance();
- relevance += computeRelevanceForResolution();
- relevance += computeRelevanceForInterestingProposal();
- relevance += computeRelevanceForCaseMatching(typeName, exceptionType.sourceName);
- relevance += computeRelevanceForExpectingType(exceptionType);
- relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE);
- if(!insideQualifiedReference) {
- relevance += computeRelevanceForQualification(isQualified);
- }
- relevance += computeRelevanceForClass();
- relevance += computeRelevanceForException();
-
- this.noProposal = false;
- if(!this.requestor.isIgnored(CompletionProposal.TYPE_REF)) {
- createTypeProposal(exceptionType, exceptionType.qualifiedSourceName(), IAccessRule.K_ACCESSIBLE, completionName, relevance);
- }
- }
-
- private void findExceptionFromTryStatement(
- char[] typeName,
- ReferenceBinding receiverType,
- SourceTypeBinding invocationType,
- BlockScope scope,
- ObjectVector typesFound) {
-
- for (int i = 0; i <= this.expectedTypesPtr; i++) {
- ReferenceBinding exceptionType = (ReferenceBinding)this.expectedTypes[i];
-
- findExceptionFromTryStatement(typeName, exceptionType, receiverType, invocationType, scope, typesFound, true);
- }
- }
-
- private void findExplicitConstructors(
- char[] name,
- ReferenceBinding currentType,
- MethodScope scope,
- InvocationSite invocationSite) {
-
- ConstructorDeclaration constructorDeclaration = (ConstructorDeclaration)scope.referenceContext;
- MethodBinding enclosingConstructor = constructorDeclaration.binding;
-
- // No visibility checks can be performed without the scope & invocationSite
- MethodBinding[] methods = currentType.availableMethods();
- if(methods != null) {
- next : for (int f = methods.length; --f >= 0;) {
- MethodBinding constructor = methods[f];
- if (constructor != enclosingConstructor && constructor.isConstructor()) {
-
- if (this.options.checkDeprecation &&
- constructor.isViewedAsDeprecated() &&
- !scope.isDefinedInSameUnit(constructor.declaringClass))
- continue next;
-
- if (this.options.checkVisibility
- && !constructor.canBeSeenBy(invocationSite, scope)) continue next;
-
- 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);
-
- char[] completion = CharOperation.NO_CHAR;
- if (this.source != null
- && this.source.length > this.endPosition
- && this.source[this.endPosition] == '(')
- completion = name;
- else
- completion = CharOperation.concat(name, new char[] { '(', ')' });
-
- int relevance = computeBaseRelevance();
- relevance += computeRelevanceForResolution();
- relevance += computeRelevanceForInterestingProposal();
- relevance += computeRelevanceForCaseMatching(this.completionToken, name);
- relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE);
-
- this.noProposal = false;
- if(!this.requestor.isIgnored(CompletionProposal.METHOD_REF)) {
- CompletionProposal proposal = this.createProposal(CompletionProposal.METHOD_REF, this.actualCompletionPosition);
- proposal.setDeclarationSignature(getSignature(currentType));
- proposal.setSignature(getSignature(constructor));
- MethodBinding original = constructor.original();
- if(original != constructor) {
- proposal.setOriginalSignature(getSignature(original));
- }
- 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);
- proposal.setFlags(constructor.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);
- }
- }
- }
- }
- }
- }
-
-
- private void findConstructors(
- ReferenceBinding currentType,
- TypeBinding[] argTypes,
- Scope scope,
- InvocationSite invocationSite,
- boolean forAnonymousType) {
-
- // No visibility checks can be performed without the scope & invocationSite
- MethodBinding[] methods = currentType.availableMethods();
- if(methods != null) {
- int minArgLength = argTypes == null ? 0 : argTypes.length;
- next : for (int f = methods.length; --f >= 0;) {
- MethodBinding constructor = methods[f];
- if (constructor.isConstructor()) {
-
- if (this.options.checkDeprecation &&
- constructor.isViewedAsDeprecated() &&
- !scope.isDefinedInSameUnit(constructor.declaringClass))
- continue next;
-
- if (this.options.checkVisibility
- && !constructor.canBeSeenBy(invocationSite, scope)) {
- if(!forAnonymousType || !constructor.isProtected())
- continue next;
- }
-
- TypeBinding[] parameters = constructor.parameters;
- int paramLength = parameters.length;
- if (minArgLength > paramLength)
- continue next;
- for (int a = minArgLength; --a >= 0;)
- if (argTypes[a] != null) { // can be null if it could not be resolved properly
- if (!argTypes[a].isCompatibleWith(constructor.parameters[a]))
- 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);
-
- char[] bindingName = constructor.selector;
- char[] completion = bindingName;
- if (this.source != null
- && this.source.length > this.endPosition
- && this.source[this.endPosition] == '(') {
- completion = bindingName;
- } else {
- completion = CharOperation.concat(bindingName, new char[] { '(', ')' });
- }
-
- if(forAnonymousType){
- int relevance = computeBaseRelevance();
- relevance += computeRelevanceForResolution();
- relevance += computeRelevanceForInterestingProposal();
- relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE);
-
- this.noProposal = false;
- if(!this.requestor.isIgnored(CompletionProposal.ANONYMOUS_CLASS_DECLARATION)) {
- CompletionProposal proposal = this.createProposal(CompletionProposal.ANONYMOUS_CLASS_DECLARATION, this.actualCompletionPosition);
- proposal.setDeclarationSignature(getSignature(currentType));
- proposal.setDeclarationKey(currentType.computeUniqueKey());
- proposal.setSignature(getSignature(constructor));
- MethodBinding original = constructor.original();
- if(original != constructor) {
- proposal.setOriginalSignature(getSignature(original));
- }
- 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);
- proposal.setRelevance(relevance);
- if(parameterNames != null) proposal.setParameterNames(parameterNames);
- this.requestor.accept(proposal);
- if(DEBUG) {
- this.printDebug(proposal);
- }
- }
- } else {
- int relevance = computeBaseRelevance();
- relevance += computeRelevanceForResolution();
- relevance += computeRelevanceForInterestingProposal();
- relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE);
-
- // Special case for completion in javadoc
- if (this.assistNodeInJavadoc > 0) {
- Expression receiver = null;
- char[] selector = null;
- if (invocationSite instanceof CompletionOnJavadocAllocationExpression) {
- CompletionOnJavadocAllocationExpression alloc = (CompletionOnJavadocAllocationExpression) invocationSite;
- receiver = alloc.type;
- } else if (invocationSite instanceof CompletionOnJavadocFieldReference) {
- CompletionOnJavadocFieldReference fieldRef = (CompletionOnJavadocFieldReference) invocationSite;
- receiver = fieldRef.receiver;
- }
- if (receiver != null) {
- StringBuffer javadocCompletion = new StringBuffer();
- if (receiver.isThis()) {
- selector = (((JavadocImplicitTypeReference)receiver).token);
- if ((this.assistNodeInJavadoc & CompletionOnJavadoc.TEXT) != 0) {
- javadocCompletion.append('#');
- }
- } else if (receiver instanceof JavadocSingleTypeReference) {
- JavadocSingleTypeReference typeRef = (JavadocSingleTypeReference) receiver;
- selector = typeRef.token;
- if ((this.assistNodeInJavadoc & CompletionOnJavadoc.TEXT) != 0) {
- javadocCompletion.append(typeRef.token);
- javadocCompletion.append('#');
- }
- } else if (receiver instanceof JavadocQualifiedTypeReference) {
- JavadocQualifiedTypeReference typeRef = (JavadocQualifiedTypeReference) receiver;
- selector = typeRef.tokens[typeRef.tokens.length-1];
- if ((this.assistNodeInJavadoc & CompletionOnJavadoc.TEXT) != 0) {
- javadocCompletion.append(CharOperation.concatWith(typeRef.tokens, '.'));
- javadocCompletion.append('#');
- }
- }
- // Append parameters types
- javadocCompletion.append(selector);
- javadocCompletion.append('(');
- if (constructor.parameters != null) {
- boolean isVarargs = constructor.isVarargs();
- for (int p=0, ln=constructor.parameters.length; p<ln; p++) {
- if (p>0) javadocCompletion.append(", "); //$NON-NLS-1$
- TypeBinding argTypeBinding = constructor.parameters[p];
- if (isVarargs && p == ln - 1) {
- createVargsType(argTypeBinding, javadocCompletion);
- } else {
- createType(argTypeBinding, javadocCompletion);
- }
- }
- }
- javadocCompletion.append(')');
- completion = javadocCompletion.toString().toCharArray();
- }
- }
-
- // Create standard proposal
- this.noProposal = false;
- 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(currentType));
- proposal.setSignature(getSignature(constructor));
- MethodBinding original = constructor.original();
- if(original != constructor) {
- proposal.setOriginalSignature(getSignature(original));
- }
- proposal.setDeclarationPackageName(currentType.qualifiedPackageName());
- proposal.setDeclarationTypeName(currentType.qualifiedSourceName());
- proposal.setParameterPackageNames(parameterPackageNames);
- proposal.setParameterTypeNames(parameterTypeNames);
- proposal.setName(currentType.sourceName());
- proposal.setIsContructor(true);
- proposal.setCompletion(completion);
- proposal.setFlags(constructor.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 ((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(currentType));
- proposal.setSignature(getSignature(constructor));
- MethodBinding original = constructor.original();
- if(original != constructor) {
- proposal.setOriginalSignature(getSignature(original));
- }
- 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);
- proposal.setFlags(constructor.modifiers);
- int start = (this.assistNodeInJavadoc > 0) ? this.startPosition : this.endPosition;
- if ((this.assistNodeInJavadoc & CompletionOnJavadoc.REPLACE_TAG) != 0) start = this.javadocTagPosition;
- proposal.setReplaceRange(start - this.offset, this.endPosition - this.offset);
- proposal.setRelevance(relevance+R_INLINE_TAG);
- if(parameterNames != null) proposal.setParameterNames(parameterNames);
- this.requestor.accept(proposal);
- if(DEBUG) {
- this.printDebug(proposal);
- }
- }
- }
- }
- }
- }
- }
-
- // Helper method for findFields(char[], ReferenceBinding, Scope, ObjectVector, boolean)
- private void findFields(
- char[] fieldName,
- FieldBinding[] fields,
- Scope scope,
- ObjectVector fieldsFound,
- ObjectVector localsFound,
- boolean onlyStaticFields,
- ReferenceBinding receiverType,
- InvocationSite invocationSite,
- Scope invocationScope,
- boolean implicitCall,
- boolean canBePrefixed,
- Binding[] missingElements,
- int[] missingElementsStarts,
- int[] missingElementsEnds,
- boolean missingElementsHaveProblems) {
-
- ObjectVector newFieldsFound = new ObjectVector();
- // Inherited fields which are hidden by subclasses are filtered out
- // No visibility checks can be performed without the scope & invocationSite
-
- int fieldLength = fieldName.length;
- next : for (int f = fields.length; --f >= 0;) {
- FieldBinding field = fields[f];
-
- if (onlyStaticFields && !field.isStatic()) continue next;
-
- if (fieldLength > field.name.length) continue next;
-
- if (!CharOperation.prefixEquals(fieldName, field.name, false /* ignore case */)
- && !(this.options.camelCaseMatch && CharOperation.camelCaseMatch(fieldName, field.name))) continue next;
-
- if (this.options.checkDeprecation &&
- field.isViewedAsDeprecated() &&
- !scope.isDefinedInSameUnit(field.declaringClass))
- continue next;
-
- if (this.options.checkVisibility
- && !field.canBeSeenBy(receiverType, invocationSite, scope)) continue next;
-
- boolean prefixRequired = false;
-
- for (int i = fieldsFound.size; --i >= 0;) {
- Object[] other = (Object[])fieldsFound.elementAt(i);
- FieldBinding otherField = (FieldBinding) other[0];
- ReferenceBinding otherReceiverType = (ReferenceBinding) other[1];
- if (field == otherField && receiverType == otherReceiverType)
- continue next;
- if (CharOperation.equals(field.name, otherField.name, true)) {
- if (field.declaringClass.isSuperclassOf(otherField.declaringClass))
- continue next;
- if(canBePrefixed) {
- prefixRequired = true;
- } else {
- continue next;
- }
- }
- }
-
- for (int l = localsFound.size; --l >= 0;) {
- LocalVariableBinding local = (LocalVariableBinding) localsFound.elementAt(l);
-
- if (CharOperation.equals(field.name, local.name, true)) {
- SourceTypeBinding declarationType = scope.enclosingSourceType();
- if (declarationType.isAnonymousType() && declarationType != invocationScope.enclosingSourceType()) {
- continue next;
- }
- if(canBePrefixed) {
- prefixRequired = true;
- } else {
- continue next;
- }
- break;
- }
- }
-
- 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);
- }
- }
- }
-
- fieldsFound.addAll(newFieldsFound);
- }
-
- private void findFields(
- char[] fieldName,
- ReferenceBinding receiverType,
- Scope scope,
- ObjectVector fieldsFound,
- ObjectVector localsFound,
- boolean onlyStaticFields,
- InvocationSite invocationSite,
- Scope invocationScope,
- boolean implicitCall,
- boolean canBePrefixed,
- Binding[] missingElements,
- int[] missingElementsStarts,
- int[] missingElementsEnds,
- boolean missingElementsHaveProblems) {
-
- boolean notInJavadoc = this.assistNodeInJavadoc == 0;
- if (fieldName == null && notInJavadoc)
- return;
-
- ReferenceBinding currentType = receiverType;
- do {
-
- FieldBinding[] fields = currentType.availableFields();
- if(fields != null && fields.length > 0) {
- findFields(
- fieldName,
- fields,
- scope,
- fieldsFound,
- localsFound,
- onlyStaticFields,
- receiverType,
- invocationSite,
- invocationScope,
- implicitCall,
- canBePrefixed,
- missingElements,
- missingElementsStarts,
- missingElementsEnds,
- missingElementsHaveProblems);
- }
-
- currentType = currentType.superclass();
- } while (notInJavadoc && currentType != null);
- }
-
- protected void findFieldsAndMethods(
- char[] token,
- TypeBinding receiverType,
- Scope scope,
- InvocationSite invocationSite,
- Scope invocationScope,
- boolean staticsOnly,
- boolean implicitCall,
- boolean superCall,
- Binding[] missingElements,
- int[] missingElementsStarts,
- int[] missingElementsEnds,
- boolean missingElementsHaveProblems) {
-
- if (token == null)
- return;
-
- if (receiverType.isBaseType())
- return; // nothing else is possible with base types
-
- boolean proposeField = !this.isIgnored(CompletionProposal.FIELD_REF, missingElements != null);
- boolean proposeMethod = !this.isIgnored(CompletionProposal.METHOD_REF, missingElements != null);
-
- ObjectVector methodsFound = new ObjectVector();
- ObjectVector fieldsFound = new ObjectVector();
-
- if(proposeField) {
- findFields(
- token,
- (ReferenceBinding) receiverType,
- scope,
- fieldsFound,
- new ObjectVector(),
- staticsOnly,
- invocationSite,
- invocationScope,
- implicitCall,
- false,
- missingElements,
- missingElementsStarts,
- missingElementsEnds,
- missingElementsHaveProblems);
- }
-
- if(proposeMethod) {
- findMethods(
- token,
- null,
- null,
- (ReferenceBinding) receiverType,
- scope,
- methodsFound,
- staticsOnly,
- false,
- false,
- invocationSite,
- invocationScope,
- implicitCall,
- superCall,
- false,
- missingElements,
- missingElementsStarts,
- missingElementsEnds,
- missingElementsHaveProblems);
- }
- }
-
- private void findFieldsAndMethodsFromFavorites(
- char[] token,
- Scope scope,
- InvocationSite invocationSite,
- Scope invocationScope,
- ObjectVector localsFound,
- ObjectVector fieldsFound,
- ObjectVector methodsFound) {
-
- ImportBinding[] favoriteBindings = getFavoriteReferenceBindings(invocationScope);
-
- if (favoriteBindings != null && favoriteBindings.length > 0) {
- for (int i = 0; i < favoriteBindings.length; i++) {
- ImportBinding favoriteBinding = favoriteBindings[i];
- switch (favoriteBinding.resolvedImport.kind()) {
- case Binding.FIELD:
- FieldBinding fieldBinding = (FieldBinding) favoriteBinding.resolvedImport;
- findFieldsFromFavorites(
- token,
- new FieldBinding[]{fieldBinding},
- scope,
- fieldsFound,
- localsFound,
- fieldBinding.declaringClass,
- invocationSite,
- invocationScope);
- break;
- case Binding.METHOD:
- MethodBinding methodBinding = (MethodBinding) favoriteBinding.resolvedImport;
- MethodBinding[] methods = methodBinding.declaringClass.availableMethods();
- long range;
- if ((range = ReferenceBinding.binarySearch(methodBinding.selector, methods)) >= 0) {
- int start = (int) range, end = (int) (range >> 32);
- int length = end - start + 1;
- System.arraycopy(methods, start, methods = new MethodBinding[length], 0, length);
- } else {
- methods = Binding.NO_METHODS;
- }
- findLocalMethodsFromFavorites(
- token,
- methods,
- scope,
- methodsFound,
- methodBinding.declaringClass,
- invocationSite,
- invocationScope);
- break;
- case Binding.TYPE:
- ReferenceBinding referenceBinding = (ReferenceBinding) favoriteBinding.resolvedImport;
- if(favoriteBinding.onDemand) {
- findFieldsFromFavorites(
- token,
- referenceBinding.availableFields(),
- scope,
- fieldsFound,
- localsFound,
- referenceBinding,
- invocationSite,
- invocationScope);
-
- findLocalMethodsFromFavorites(
- token,
- referenceBinding.availableMethods(),
- scope,
- methodsFound,
- referenceBinding,
- invocationSite,
- invocationScope);
- }
- break;
- }
- }
- }
- }
-
- private void findFieldsAndMethodsFromMissingFieldType(
- char[] token,
- Scope scope,
- InvocationSite invocationSite,
- boolean insideTypeAnnotation) {
-
- boolean staticsOnly = false;
- Scope currentScope = scope;
-
- done : while (true) { // done when a COMPILATION_UNIT_SCOPE is found
-
- 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;
-
- case Scope.BLOCK_SCOPE :
- break;
-
- case Scope.CLASS_SCOPE :
- ClassScope classScope = (ClassScope) currentScope;
- SourceTypeBinding enclosingType = classScope.referenceContext.binding;
- if(!insideTypeAnnotation) {
-
- FieldDeclaration[] fields = classScope.referenceContext.fields;
-
- int fieldsCount = fields == null ? 0 : fields.length;
- for (int i = 0; i < fieldsCount; i++) {
- FieldDeclaration fieldDeclaration = fields[i];
- if (CharOperation.equals(fieldDeclaration.name, token)) {
- if (fieldDeclaration.binding == null) {
- findFieldsAndMethodsFromMissingType(
- this.completionToken,
- fieldDeclaration.type,
- currentScope,
- invocationSite,
- scope);
- }
- break done;
- }
- }
- }
- staticsOnly |= enclosingType.isStatic();
- insideTypeAnnotation = false;
- break;
- case Scope.COMPILATION_UNIT_SCOPE :
- break done;
- }
- currentScope = currentScope.parent;
- }
- }
-
- private void findFieldsAndMethodsFromMissingReturnType(
- char[] token,
- TypeBinding[] arguments,
- Scope scope,
- InvocationSite invocationSite,
- boolean insideTypeAnnotation) {
-
- boolean staticsOnly = false;
- Scope currentScope = scope;
-
- done : while (true) { // done when a COMPILATION_UNIT_SCOPE is found
-
- 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;
-
- case Scope.BLOCK_SCOPE :
- break;
-
- case Scope.CLASS_SCOPE :
- ClassScope classScope = (ClassScope) currentScope;
- SourceTypeBinding enclosingType = classScope.referenceContext.binding;
- if(!insideTypeAnnotation) {
-
- AbstractMethodDeclaration[] methods = classScope.referenceContext.methods;
-
- int methodsCount = methods == null ? 0 : methods.length;
- for (int i = 0; i < methodsCount; i++) {
- AbstractMethodDeclaration methodDeclaration = methods[i];
- if (methodDeclaration instanceof MethodDeclaration &&
- CharOperation.equals(methodDeclaration.selector, token)) {
- MethodDeclaration method = (MethodDeclaration) methodDeclaration;
- if (methodDeclaration.binding == null) {
- Argument[] parameters = method.arguments;
- int parametersLength = parameters == null ? 0 : parameters.length;
- int argumentsLength = arguments == null ? 0 : arguments.length;
-
- if (parametersLength == 0) {
- if (argumentsLength == 0) {
- findFieldsAndMethodsFromMissingType(
- this.completionToken,
- method.returnType,
- currentScope,
- invocationSite,
- scope);
- break done;
- }
- } else {
- TypeBinding[] parametersBindings = new TypeBinding[parametersLength];
- for (int j = 0; j < parametersLength; j++) {
- parametersBindings[j] = parameters[j].type.resolvedType;
- }
- if(areParametersCompatibleWith(parametersBindings, arguments, parameters[parametersLength - 1].isVarArgs())) {
- findFieldsAndMethodsFromMissingType(
- this.completionToken,
- method.returnType,
- currentScope,
- invocationSite,
- scope);
- break done;
- }
- }
- }
-
- }
- }
- }
- staticsOnly |= enclosingType.isStatic();
- insideTypeAnnotation = false;
- break;
- case Scope.COMPILATION_UNIT_SCOPE :
- break done;
- }
- currentScope = currentScope.parent;
- }
- }
-
- private void findFieldsAndMethodsFromMissingType(
- final char[] token,
- TypeReference typeRef,
- final Scope scope,
- final InvocationSite invocationSite,
- final Scope invocationScope) {
- MissingTypesGuesser missingTypesConverter = new MissingTypesGuesser(this);
- MissingTypesGuesser.GuessedTypeRequestor substitutionRequestor =
- new MissingTypesGuesser.GuessedTypeRequestor() {
- public void accept(
- TypeBinding guessedType,
- Binding[] missingElements,
- int[] missingElementsStarts,
- int[] missingElementsEnds,
- boolean hasProblems) {
- findFieldsAndMethods(
- CompletionEngine.this.completionToken,
- guessedType,
- scope,
- invocationSite,
- invocationScope,
- false,
- false,
- false,
- missingElements,
- missingElementsStarts,
- missingElementsEnds,
- hasProblems);
-
- }
- };
- missingTypesConverter.guess(typeRef, scope, substitutionRequestor);
- }
-
- private void findFieldsFromFavorites(
- char[] fieldName,
- FieldBinding[] fields,
- Scope scope,
- ObjectVector fieldsFound,
- ObjectVector localsFound,
- ReferenceBinding receiverType,
- InvocationSite invocationSite,
- Scope invocationScope) {
-
- char[] typeName = CharOperation.concatWith(receiverType.compoundName, '.');
-
- int fieldLength = fieldName.length;
- next : for (int f = fields.length; --f >= 0;) {
- FieldBinding field = fields[f];
-
- // only static fields must be proposed
- if (!field.isStatic()) continue next;
-
- if (fieldLength > field.name.length) continue next;
-
- if (!CharOperation.prefixEquals(fieldName, field.name, false /* ignore case */)
- && !(this.options.camelCaseMatch && CharOperation.camelCaseMatch(fieldName, field.name))) continue next;
-
- if (this.options.checkDeprecation &&
- field.isViewedAsDeprecated() &&
- !scope.isDefinedInSameUnit(field.declaringClass))
- continue next;
-
- if (this.options.checkVisibility
- && !field.canBeSeenBy(receiverType, invocationSite, scope)) continue next;
-
- for (int i = fieldsFound.size; --i >= 0;) {
- Object[] other = (Object[])fieldsFound.elementAt(i);
- FieldBinding otherField = (FieldBinding) other[0];
-
- if (field == otherField) continue next;
- }
-
- fieldsFound.add(new Object[]{field, receiverType});
-
- int relevance = computeBaseRelevance();
- relevance += computeRelevanceForResolution();
- relevance += computeRelevanceForInterestingProposal(field);
- if (fieldName != null) relevance += computeRelevanceForCaseMatching(fieldName, field.name);
- relevance += computeRelevanceForExpectingType(field.type);
- relevance += computeRelevanceForStatic(true, true);
- relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE);
-
- CompilationUnitDeclaration cu = this.unitScope.referenceContext;
- int importStart = cu.types[0].declarationSourceStart;
- int importEnd = importStart;
-
- this.noProposal = false;
-
- if (this.compilerOptions.complianceLevel < ClassFileConstants.JDK1_5 ||
- !this.options.suggestStaticImport) {
- if (!this.isIgnored(CompletionProposal.FIELD_REF, CompletionProposal.TYPE_IMPORT)) {
- char[] completion = CharOperation.concat(receiverType.sourceName, field.name, '.');
-
- 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);
- proposal.setCompletion(completion);
- proposal.setFlags(field.modifiers);
- proposal.setReplaceRange(this.startPosition - this.offset, this.endPosition - this.offset);
- proposal.setRelevance(relevance);
-
- char[] typeImportCompletion = createImportCharArray(typeName, false, false);
-
- CompletionProposal typeImportProposal = this.createProposal(CompletionProposal.TYPE_IMPORT, this.actualCompletionPosition);
- typeImportProposal.nameLookup = this.nameEnvironment.nameLookup;
- typeImportProposal.completionEngine = this;
- char[] packageName = receiverType.qualifiedPackageName();
- typeImportProposal.setDeclarationSignature(packageName);
- typeImportProposal.setSignature(getSignature(receiverType));
- typeImportProposal.setPackageName(packageName);
- typeImportProposal.setTypeName(receiverType.qualifiedSourceName());
- typeImportProposal.setCompletion(typeImportCompletion);
- typeImportProposal.setFlags(receiverType.modifiers);
- typeImportProposal.setAdditionalFlags(CompletionFlags.Default);
- typeImportProposal.setReplaceRange(importStart - this.offset, importEnd - this.offset);
- typeImportProposal.setRelevance(relevance);
-
- proposal.setRequiredProposals(new CompletionProposal[]{typeImportProposal});
-
- this.requestor.accept(proposal);
- if(DEBUG) {
- this.printDebug(proposal);
- }
- }
- } else {
- if (!this.isIgnored(CompletionProposal.FIELD_REF, CompletionProposal.FIELD_IMPORT)) {
- char[] completion = field.name;
-
- 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);
- proposal.setCompletion(completion);
- proposal.setFlags(field.modifiers);
- proposal.setReplaceRange(this.startPosition - this.offset, this.endPosition - this.offset);
- proposal.setRelevance(relevance);
-
- char[] fieldImportCompletion = createImportCharArray(CharOperation.concat(typeName, field.name, '.'), true, false);
-
- CompletionProposal fieldImportProposal = this.createProposal(CompletionProposal.FIELD_IMPORT, this.actualCompletionPosition);
- fieldImportProposal.setDeclarationSignature(getSignature(field.declaringClass));
- 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.setName(field.name);
- fieldImportProposal.setCompletion(fieldImportCompletion);
- fieldImportProposal.setFlags(field.modifiers);
- fieldImportProposal.setReplaceRange(importStart - this.offset, importEnd - this.offset);
- fieldImportProposal.setRelevance(relevance);
-
- proposal.setRequiredProposals(new CompletionProposal[]{fieldImportProposal});
-
- this.requestor.accept(proposal);
- if(DEBUG) {
- this.printDebug(proposal);
- }
- }
- }
- }
- }
-
- private void findImports(CompletionOnImportReference importReference, boolean findMembers) {
- char[][] tokens = importReference.tokens;
-
- char[] importName = CharOperation.concatWith(tokens, '.');
-
- if (importName.length == 0)
- return;
-
- char[] lastToken = tokens[tokens.length - 1];
- if(lastToken != null && lastToken.length == 0)
- importName = CharOperation.concat(importName, new char[]{'.'});
-
- this.resolvingImports = true;
-
- this.completionToken = importName;
- // want to replace the existing .*;
-// if(!this.requestor.isIgnored(CompletionProposal.PACKAGE_REF)) {
-// this.nameEnvironment.findPackages(importName, this);
-// }
- if(!this.requestor.isIgnored(CompletionProposal.TYPE_REF)) {
- this.nameEnvironment.findTypes(
- importName,
- findMembers,
- this.options.camelCaseMatch,
- IJavaScriptSearchConstants.TYPE,
- this);
- acceptTypes(null);
- }
- }
-
- private void findImportsOfMemberTypes(char[] typeName, ReferenceBinding ref) {
- ReferenceBinding[] memberTypes = ref.memberTypes();
-
- int typeLength = typeName.length;
- next : for (int m = memberTypes.length; --m >= 0;) {
- ReferenceBinding memberType = memberTypes[m];
- // if (!wantClasses && memberType.isClass()) continue next;
- // if (!wantInterfaces && memberType.isInterface()) continue next;
-
- if (typeLength > memberType.sourceName.length)
- continue next;
-
- if (!CharOperation.prefixEquals(typeName, memberType.sourceName, false/* ignore case */)
- && !(this.options.camelCaseMatch && CharOperation.camelCaseMatch(typeName, memberType.sourceName)))
- continue next;
-
- if (this.options.checkDeprecation && memberType.isViewedAsDeprecated()) continue next;
-
- if (this.options.checkVisibility
- && !memberType.canBeSeenBy(this.unitScope.getDefaultPackage()))
- continue next;
-
- char[] completionName = CharOperation.concat(
- memberType.qualifiedPackageName(),
- memberType.qualifiedSourceName(),
- '.');
-
- completionName = CharOperation.concat(completionName, SEMICOLON);
-
- int relevance = computeBaseRelevance();
- relevance += computeRelevanceForResolution();
- relevance += computeRelevanceForInterestingProposal();
- relevance += computeRelevanceForCaseMatching(typeName, memberType.sourceName);
- relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE);
-
- if (memberType.isClass()) {
- relevance += computeRelevanceForClass();
- }
- this.noProposal = false;
- if(!this.requestor.isIgnored(CompletionProposal.TYPE_REF)) {
- createTypeProposal(memberType, memberType.qualifiedSourceName(), IAccessRule.K_ACCESSIBLE, completionName, relevance);
- }
- }
- }
-
- /*
- * Find javadoc block tags for a given completion javadoc tag node
- */
- private void findJavadocBlockTags(CompletionOnJavadocTag javadocTag) {
- char[][] possibleTags = javadocTag.getPossibleBlockTags();
- if (possibleTags == null) return;
- int length = possibleTags.length;
- for (int i=0; i<length; i++) {
- int relevance = computeBaseRelevance();
- relevance += computeRelevanceForInterestingProposal();
- relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE); // no access restriction for keywors
-
- this.noProposal = false;
- if (!this.requestor.isIgnored(CompletionProposal.JSDOC_BLOCK_TAG)) {
- char[] possibleTag = possibleTags[i];
- CompletionProposal proposal = this.createProposal(CompletionProposal.JSDOC_BLOCK_TAG, this.actualCompletionPosition);
- proposal.setName(possibleTag);
- int tagLength = possibleTag.length;
- char[] completion = new char[1+tagLength];
- completion[0] = '@';
- System.arraycopy(possibleTag, 0, completion, 1, tagLength);
- 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);
- }
- }
- }
- }
-
- /*
- * Find javadoc inline tags for a given completion javadoc tag node
- */
- private void findJavadocInlineTags(CompletionOnJavadocTag javadocTag) {
- char[][] possibleTags = javadocTag.getPossibleInlineTags();
- if (possibleTags == null) return;
- int length = possibleTags.length;
- for (int i=0; i<length; i++) {
- int relevance = computeBaseRelevance();
- relevance += computeRelevanceForInterestingProposal();
- relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE); // no access restriction for keywors
-
- this.noProposal = false;
- if (!this.requestor.isIgnored(CompletionProposal.JSDOC_INLINE_TAG)) {
- char[] possibleTag = possibleTags[i];
- CompletionProposal proposal = this.createProposal(CompletionProposal.JSDOC_INLINE_TAG, this.actualCompletionPosition);
- proposal.setName(possibleTag);
- int tagLength = possibleTag.length;
-// boolean inlineTagStarted = javadocTag.completeInlineTagStarted();
- char[] completion = new char[2+tagLength+1];
- completion[0] = '{';
- completion[1] = '@';
- System.arraycopy(possibleTag, 0, completion, 2, tagLength);
- // do not add space at end of inline tag (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=121026)
- //completion[tagLength+2] = ' ';
- completion[tagLength+2] = '}';
- 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);
- }
- }
- }
- }
-
- // what about onDemand types? Ignore them since it does not happen!
- // import p1.p2.A.*;
- private void findKeywords(char[] keyword, char[][] choices, boolean canCompleteEmptyToken, boolean staticFieldsAndMethodOnly) {
- if(choices == null || choices.length == 0) return;
-
- int length = keyword.length;
- if (canCompleteEmptyToken || length > 0)
- for (int i = 0; i < choices.length; i++)
- if (length <= choices[i].length
- && CharOperation.prefixEquals(keyword, choices[i], false /* ignore case */
- )){
- int relevance = computeBaseRelevance();
- relevance += computeRelevanceForResolution();
- relevance += computeRelevanceForInterestingProposal();
- relevance += computeRelevanceForCaseMatching(keyword, choices[i]);
- relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE); // no access restriction for keywors
- if (staticFieldsAndMethodOnly && this.insideQualifiedReference) relevance += R_NON_INHERITED;
-
- if(CharOperation.equals(choices[i], Keywords.TRUE) || CharOperation.equals(choices[i], Keywords.FALSE)) {
- relevance += computeRelevanceForExpectingType(TypeBinding.BOOLEAN);
- relevance += computeRelevanceForQualification(false);
- }
- this.noProposal = false;
- if(!this.requestor.isIgnored(CompletionProposal.KEYWORD)) {
- CompletionProposal proposal = this.createProposal(CompletionProposal.KEYWORD, this.actualCompletionPosition);
- proposal.setName(choices[i]);
- proposal.setCompletion(choices[i]);
- proposal.setReplaceRange(this.startPosition - this.offset, this.endPosition - this.offset);
- proposal.setRelevance(relevance);
- this.requestor.accept(proposal);
- if(DEBUG) {
- this.printDebug(proposal);
- }
- }
- }
- }
- private void findTrueOrFalseKeywords(char[][] choices) {
- if(choices == null || choices.length == 0) return;
-
- if(this.expectedTypesPtr != 0 || this.expectedTypes[0] != TypeBinding.BOOLEAN) return;
-
- for (int i = 0; i < choices.length; i++) {
- if (CharOperation.equals(choices[i], Keywords.TRUE) ||
- CharOperation.equals(choices[i], Keywords.FALSE)
- ){
- int relevance = computeBaseRelevance();
- relevance += computeRelevanceForResolution();
- relevance += computeRelevanceForInterestingProposal();
- relevance += computeRelevanceForCaseMatching(CharOperation.NO_CHAR, choices[i]);
- relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE); // no access restriction for keywors
- relevance += computeRelevanceForExpectingType(TypeBinding.BOOLEAN);
- relevance += computeRelevanceForQualification(false);
- relevance += R_TRUE_OR_FALSE;
-
- this.noProposal = false;
- if(!this.requestor.isIgnored(CompletionProposal.KEYWORD)) {
- CompletionProposal proposal = this.createProposal(CompletionProposal.KEYWORD, this.actualCompletionPosition);
- proposal.setName(choices[i]);
- proposal.setCompletion(choices[i]);
- proposal.setReplaceRange(this.startPosition - this.offset, this.endPosition - this.offset);
- proposal.setRelevance(relevance);
- this.requestor.accept(proposal);
- if(DEBUG) {
- this.printDebug(proposal);
- }
- }
- }
- }
- }
-
- private void findKeywordsForMember(char[] token, int modifiers) {
- char[][] keywords = new char[Keywords.COUNT][];
- int count = 0;
-
- // visibility
- if((modifiers & ClassFileConstants.AccPrivate) == 0
- && (modifiers & ClassFileConstants.AccProtected) == 0
- && (modifiers & ClassFileConstants.AccPublic) == 0) {
- keywords[count++] = Keywords.PROTECTED;
- keywords[count++] = Keywords.PUBLIC;
- if((modifiers & ClassFileConstants.AccAbstract) == 0) {
- keywords[count++] = Keywords.PRIVATE;
- }
- }
-
- if((modifiers & ClassFileConstants.AccAbstract) == 0) {
- // abtract
- if((modifiers & ~(ExtraCompilerModifiers.AccVisibilityMASK | ClassFileConstants.AccStatic)) == 0) {
- keywords[count++] = Keywords.ABSTRACT;
- }
-
- // final
- if((modifiers & ClassFileConstants.AccFinal) == 0) {
- keywords[count++] = Keywords.FINAL;
- }
-
- // static
- if((modifiers & ClassFileConstants.AccStatic) == 0) {
- keywords[count++] = Keywords.STATIC;
- }
-
- boolean canBeField = true;
- boolean canBeMethod = true;
- boolean canBeType = true;
- if((modifiers & ClassFileConstants.AccNative) != 0
- || (modifiers & ClassFileConstants.AccStrictfp) != 0) {
- canBeField = false;
- canBeType = false;
- }
-
-
- if(canBeField) {
- // transient
- keywords[count++] = Keywords.TRANSIENT;
-
-
- // volatile
- keywords[count++] = Keywords.VOLATILE;
- }
-
- if(canBeMethod) {
- // native
- if((modifiers & ClassFileConstants.AccNative) == 0) {
- keywords[count++] = Keywords.NATIVE;
- }
-
- // strictfp
- if((modifiers & ClassFileConstants.AccStrictfp) == 0) {
- keywords[count++] = Keywords.STRICTFP;
- }
-
- // synchronized
- keywords[count++] = Keywords.SYNCHRONIZED;
-
- }
-
- if(canBeType) {
- keywords[count++] = Keywords.CLASS;
- keywords[count++] = Keywords.INTERFACE;
- }
- } else {
- // class
- keywords[count++] = Keywords.CLASS;
- keywords[count++] = Keywords.INTERFACE;
- }
- System.arraycopy(keywords, 0, keywords = new char[count][], 0, count);
-
- findKeywords(token, keywords, false, false);
- }
-
- private void findMemberTypes(
- char[] typeName,
- ReferenceBinding receiverType,
- Scope scope,
- SourceTypeBinding typeInvocation,
- boolean staticOnly,
- boolean staticFieldsAndMethodOnly,
- ObjectVector typesFound) {
- findMemberTypes(
- typeName,
- receiverType,
- scope,
- typeInvocation,
- staticOnly,
- staticFieldsAndMethodOnly,
- false,
- false,
- false,
- null,
- typesFound);
- }
- private void findMemberTypes(
- char[] typeName,
- ReferenceBinding receiverType,
- Scope scope,
- SourceTypeBinding typeInvocation,
- boolean staticOnly,
- boolean staticFieldsAndMethodOnly,
- boolean fromStaticImport,
- boolean checkQualification,
- boolean proposeAllMemberTypes,
- SourceTypeBinding typeToIgnore,
- ObjectVector typesFound) {
-
- ReferenceBinding currentType = receiverType;
- if (typeName == null)
- return;
-
- if (this.assistNodeIsSuperType && !this.insideQualifiedReference) return; // we're trying to find a supertype
-
- return; // we're trying to find a supertype
- }
-
- /*
- * Find javadoc parameter names.
- */
- private void findJavadocParamNames(char[] token, char[][] missingParams, boolean isTypeParam) {
-
- if (missingParams == null) return;
-
- // Get relevance
- int relevance = computeBaseRelevance();
- relevance += computeRelevanceForInterestingProposal();
- relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE); // no access restriction for param name
- if (!isTypeParam) relevance += R_INTERESTING;
-
- // Propose missing param
- int length = missingParams.length;
- relevance += length;
- for (int i=0; i<length; i++) {
- char[] argName = missingParams[i];
- if (token == null || CharOperation.prefixEquals(token, argName)) {
-
- this.noProposal = false;
- if (!this.requestor.isIgnored(CompletionProposal.JSDOC_PARAM_REF)) {
- CompletionProposal proposal = this.createProposal(CompletionProposal.JSDOC_PARAM_REF, this.actualCompletionPosition);
- proposal.setName(argName);
- char[] completion = isTypeParam ? CharOperation.concat('<', argName, '>') : argName;
- 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 findSubMemberTypes(
- char[] typeName,
- ReferenceBinding receiverType,
- Scope scope,
- SourceTypeBinding typeInvocation,
- boolean staticOnly,
- boolean staticFieldsAndMethodOnly,
- boolean fromStaticImport,
- ObjectVector typesFound) {
-
- ReferenceBinding currentType = receiverType;
- if (typeName == null || typeName.length == 0)
- return;
-
- return; // we're trying to find a supertype
- }
-
- private void findImplicitMessageSends(
- char[] token,
- TypeBinding[] argTypes,
- Scope scope,
- InvocationSite invocationSite,
- Scope invocationScope) {
-
- if (token == null)
- return;
-
- boolean staticsOnly = false;
- // need to know if we're in a static context (or inside a constructor)
- ObjectVector methodsFound = new ObjectVector();
-
- done : while (true) { // done when a COMPILATION_UNIT_SCOPE is found
-
- switch (scope.kind) {
-
- case Scope.METHOD_SCOPE :
- // handle the error case inside an explicit constructor call (see MethodScope>>findField)
- MethodScope methodScope = (MethodScope) scope;
- staticsOnly |= methodScope.isStatic | methodScope.isConstructorCall;
- break;
-
- case Scope.CLASS_SCOPE :
- ClassScope classScope = (ClassScope) scope;
- SourceTypeBinding enclosingType = classScope.getReferenceBinding();
- findMethods(
- token,
- null,
- argTypes,
- enclosingType,
- classScope,
- methodsFound,
- staticsOnly,
- true,
- false,
- invocationSite,
- invocationScope,
- true,
- false,
- true,
- null,
- null,
- null,
- false);
- staticsOnly |= enclosingType.isStatic();
- break;
-
- case Scope.COMPILATION_UNIT_SCOPE :
- CompilationUnitScope compScope = (CompilationUnitScope) scope;
- CompilationUnitBinding compBinding = compScope.enclosingCompilationUnit();
- findMethods(
- token,
- null,
- argTypes,
- compBinding,
- compScope,
- methodsFound,
- staticsOnly,
- false,
- false,
- invocationSite,
- invocationScope,
- true,
- false,
- true,
- null,
- null,
- null,
- false);
- break done;
- }
- scope = scope.parent;
- }
- }
-
- // 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,
- Scope scope,
- ObjectVector methodsFound,
- boolean onlyStaticMethods,
- boolean exactMatch,
- ReferenceBinding receiverType,
- InvocationSite invocationSite,
- Scope invocationScope,
- boolean implicitCall,
- boolean superCall,
- boolean canBePrefixed,
- Binding[] missingElements,
- int[] missingElementsStarts,
- int[] missingElementsEnds,
- boolean missingElementsHaveProblems) {
-
- ObjectVector newMethodsFound = new ObjectVector();
- // Inherited methods which are hidden by subclasses are filtered out
- // 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;) {
- MethodBinding method = methods[f];
-
- if (method.isDefaultAbstract()) continue next;
-
- if (method.isConstructor()) continue next;
-
- if (this.options.checkDeprecation &&
- method.isViewedAsDeprecated() &&
- !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
- && !method.canBeSeenBy(receiverType, invocationSite, scope)) continue next;
-
- if(superCall && method.isAbstract()) {
- methodsFound.add(new Object[]{method, receiverType});
- continue next;
- }
-
- if (exactMatch) {
- if (!CharOperation.equals(methodName, method.selector, false /* ignore case */)) {
- continue next;
- }
- } else {
- if (methodLength > method.selector.length) continue next;
- if (!CharOperation.prefixEquals(methodName, method.selector, false /* ignore case */)
- && !(this.options.camelCaseMatch && CharOperation.camelCaseMatch(methodName, method.selector))) {
- continue next;
- }
- }
-
- if (minTypeArgLength != 0 && minTypeArgLength != 0)
- continue next;
-
- if (minArgLength > method.parameters.length)
- continue next;
-
- for (int a = minArgLength; --a >= 0;){
- if (argTypes[a] != null) { // can be null if it could not be resolved properly
- if (!argTypes[a].isCompatibleWith(method.parameters[a])) {
- continue next;
- }
- }
- }
-
- boolean prefixRequired = false;
-
- for (int i = methodsFound.size; --i >= 0;) {
- Object[] other = (Object[]) methodsFound.elementAt(i);
- MethodBinding otherMethod = (MethodBinding) other[0];
- ReferenceBinding otherReceiverType = (ReferenceBinding) other[1];
- if (method == otherMethod && receiverType == otherReceiverType)
- 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;
- }
- }
- }
- }
- }
-
- 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();
- }
- char[][] parameterNames = findMethodParameterNames(method,parameterTypeNames);
-
- char[] completion = CharOperation.NO_CHAR;
-
- int previousStartPosition = this.startPosition;
-
- // 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; t<nt; t++) {
- if (t>0) javadocCompletion.append('.');
- javadocCompletion.append(typeRef.tokens[t]);
- }
- 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; p<ln; p++) {
- if (p>0) 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();
- }
- } 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);
- } 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));
- }
- 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);
- }
- 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);
- }
- }
-
- // 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(parameterTypeNames);
- proposal.setPackageName(method.returnType.qualifiedPackageName());
- proposal.setTypeName(method.returnType.qualifiedSourceName());
- proposal.setName(method.selector);
- proposal.setCompletion(javadocCompletion);
- proposal.setFlags(method.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);
- this.requestor.accept(proposal);
- if(DEBUG) {
- this.printDebug(proposal);
- }
- }
- this.startPosition = previousStartPosition;
- }
-
- methodsFound.addAll(newMethodsFound);
- }
-
- private void findLocalMethodsFromFavorites(
- char[] methodName,
- MethodBinding[] methods,
- Scope scope,
- ObjectVector methodsFound,
- ReferenceBinding receiverType,
- InvocationSite invocationSite,
- Scope invocationScope) {
-
- char[] typeName = CharOperation.concatWith(receiverType.compoundName, '.');
-
- int methodLength = methodName.length;
-
- next : for (int f = methods.length; --f >= 0;) {
- MethodBinding method = methods[f];
-
- if (method.isDefaultAbstract()) continue next;
-
- if (method.isConstructor()) continue next;
-
- if (this.options.checkDeprecation &&
- method.isViewedAsDeprecated() &&
- !scope.isDefinedInSameUnit(method.declaringClass))
- continue next;
-
- if (!method.isStatic()) continue next;
-
- if (this.options.checkVisibility
- && !method.canBeSeenBy(receiverType, invocationSite, scope)) continue next;
-
- if (methodLength > method.selector.length) continue next;
-
- if (!CharOperation.prefixEquals(methodName, method.selector, false /* ignore case */)
- && !(this.options.camelCaseMatch && CharOperation.camelCaseMatch(methodName, method.selector))) {
- continue next;
- }
-
- for (int i = methodsFound.size; --i >= 0;) {
- Object[] other = (Object[]) methodsFound.elementAt(i);
- MethodBinding otherMethod = (MethodBinding) other[0];
-
- if (method == otherMethod) continue next;
-
- if (CharOperation.equals(method.selector, otherMethod.selector, true)) {
- if (lookupEnvironment.methodVerifier().doesMethodOverride(otherMethod, method)) {
- continue next;
- }
- }
- }
-
- boolean proposeStaticImport = !(this.compilerOptions.complianceLevel < ClassFileConstants.JDK1_5) &&
- this.options.suggestStaticImport;
-
- boolean isAlreadyImported = false;
- if (!proposeStaticImport) {
- if(!this.importCachesInitialized) {
- this.initializeImportCaches();
- }
- for (int j = 0; j < this.importCacheCount; j++) {
- char[][] importName = this.importsCache[j];
- if(CharOperation.equals(receiverType.sourceName, importName[0])) {
- if (!CharOperation.equals(typeName, importName[1])) {
- continue next;
- } else {
- isAlreadyImported = true;
- }
- }
- }
- }
-
- methodsFound.add(new Object[]{method, receiverType});
-
- ReferenceBinding superTypeWithSameErasure = (ReferenceBinding)receiverType.findSuperTypeWithSameErasure(method.declaringClass);
- if (method.declaringClass != superTypeWithSameErasure) {
- MethodBinding[] 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();
- }
- char[][] parameterNames = findMethodParameterNames(method,parameterTypeNames);
-
- char[] completion = CharOperation.NO_CHAR;
-
- int previousStartPosition = this.startPosition;
-
- if (this.source != null
- && this.source.length > this.endPosition
- && this.source[this.endPosition] == '(') {
- completion = method.selector;
- } else {
- completion = CharOperation.concat(method.selector, new char[] { '(', ')' });
- }
-
- int relevance = computeBaseRelevance();
- relevance += computeRelevanceForResolution();
- relevance += computeRelevanceForInterestingProposal();
- if (methodName != null) relevance += computeRelevanceForCaseMatching(methodName, method.selector);
- relevance += computeRelevanceForExpectingType(method.returnType);
- relevance += computeRelevanceForStatic(true, method.isStatic());
- relevance += computeRelevanceForQualification(true);
- relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE);
-
- CompilationUnitDeclaration cu = this.unitScope.referenceContext;
- int importStart = cu.types[0].declarationSourceStart;
- int importEnd = importStart;
-
- this.noProposal = false;
-
- if (!proposeStaticImport) {
- if (isAlreadyImported) {
- if (!isIgnored(CompletionProposal.METHOD_REF)) {
- completion = CharOperation.concat(receiverType.sourceName, completion, '.');
-
- 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(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.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);
- }
- }
- } else if (!this.isIgnored(CompletionProposal.METHOD_REF, CompletionProposal.TYPE_IMPORT)) {
- completion = CharOperation.concat(receiverType.sourceName, completion, '.');
-
- 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(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.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);
-
- char[] typeImportCompletion = createImportCharArray(typeName, false, false);
-
- CompletionProposal typeImportProposal = this.createProposal(CompletionProposal.TYPE_IMPORT, this.actualCompletionPosition);
- typeImportProposal.nameLookup = this.nameEnvironment.nameLookup;
- typeImportProposal.completionEngine = this;
- char[] packageName = receiverType.qualifiedPackageName();
- typeImportProposal.setDeclarationSignature(packageName);
- typeImportProposal.setSignature(getSignature(receiverType));
- typeImportProposal.setPackageName(packageName);
- typeImportProposal.setTypeName(receiverType.qualifiedSourceName());
- typeImportProposal.setCompletion(typeImportCompletion);
- typeImportProposal.setFlags(receiverType.modifiers);
- typeImportProposal.setAdditionalFlags(CompletionFlags.Default);
- typeImportProposal.setReplaceRange(importStart - this.offset, importEnd - this.offset);
- typeImportProposal.setRelevance(relevance);
-
- proposal.setRequiredProposals(new CompletionProposal[]{typeImportProposal});
-
- this.requestor.accept(proposal);
- if(DEBUG) {
- this.printDebug(proposal);
- }
- }
- } else {
- if (!this.isIgnored(CompletionProposal.METHOD_REF, CompletionProposal.METHOD_IMPORT)) {
- 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(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.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);
-
- char[] methodImportCompletion = createImportCharArray(CharOperation.concat(typeName, method.selector, '.'), true, false);
-
- CompletionProposal methodImportProposal = this.createProposal(CompletionProposal.METHOD_IMPORT, this.actualCompletionPosition);
- methodImportProposal.setDeclarationSignature(getSignature(method.declaringClass));
- methodImportProposal.setSignature(getSignature(method));
- if(original != method) {
- proposal.setOriginalSignature(getSignature(original));
- }
- 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.setName(method.selector);
- methodImportProposal.setCompletion(methodImportCompletion);
- methodImportProposal.setFlags(method.modifiers);
- methodImportProposal.setReplaceRange(importStart - this.offset, importEnd - this.offset);
- methodImportProposal.setRelevance(relevance);
- if(parameterNames != null) methodImportProposal.setParameterNames(parameterNames);
-
- proposal.setRequiredProposals(new CompletionProposal[]{methodImportProposal});
-
- this.requestor.accept(proposal);
- if(DEBUG) {
- this.printDebug(proposal);
- }
- }
- }
-
- this.startPosition = previousStartPosition;
- }
- }
-
- private CompletionProposal createRequiredTypeProposal(Binding binding, int start, int end, int relevance) {
- CompletionProposal proposal = null;
- if (binding instanceof ReferenceBinding) {
- ReferenceBinding typeBinding = (ReferenceBinding) binding;
-
- char[] packageName = typeBinding.qualifiedPackageName();
- char[] typeName = typeBinding.qualifiedSourceName();
- char[] fullyQualifiedName = CharOperation.concat(packageName, typeName, '.');
-
- proposal = this.createProposal(CompletionProposal.TYPE_REF, this.actualCompletionPosition);
- proposal.nameLookup = this.nameEnvironment.nameLookup;
- proposal.completionEngine = this;
- proposal.setDeclarationSignature(packageName);
- proposal.setSignature(getSignature(typeBinding));
- proposal.setPackageName(packageName);
- proposal.setTypeName(typeName);
- proposal.setCompletion(fullyQualifiedName);
- proposal.setFlags(typeBinding.modifiers);
- proposal.setReplaceRange(start - this.offset, end - this.offset);
- proposal.setRelevance(relevance);
- } else if (binding instanceof PackageBinding) {
- PackageBinding packageBinding = (PackageBinding) binding;
-
- char[] packageName = CharOperation.concatWith(packageBinding.compoundName, '.');
-
- proposal = this.createProposal(CompletionProposal.PACKAGE_REF, this.actualCompletionPosition);
- proposal.setDeclarationSignature(packageName);
- proposal.setPackageName(packageName);
- proposal.setCompletion(packageName);
- proposal.setReplaceRange(start - this.offset, end - this.offset);
- proposal.setRelevance(relevance);
- }
- return proposal;
- }
-
- int computeRelevanceForCaseMatching(char[] token, char[] proposalName){
- if (this.options.camelCaseMatch) {
- if(CharOperation.equals(token, proposalName, true /* do not ignore case */)) {
- return R_CASE + R_EXACT_NAME;
- } else if (CharOperation.prefixEquals(token, proposalName, true /* do not ignore case */)) {
- return R_CASE;
- } else if (CharOperation.camelCaseMatch(token, proposalName)){
- return R_CAMEL_CASE;
- } else if(CharOperation.equals(token, proposalName, false /* ignore case */)) {
- return R_EXACT_NAME;
- }
- } else if (CharOperation.prefixEquals(token, proposalName, true /* do not ignore case */)) {
- if(CharOperation.equals(token, proposalName, true /* do not ignore case */)) {
- return R_CASE + R_EXACT_NAME;
- } else {
- return R_CASE;
- }
- } else if(CharOperation.equals(token, proposalName, false /* ignore case */)) {
- return R_EXACT_NAME;
- }
- return 0;
- }
- private int computeRelevanceForClass(){
- if(this.assistNodeIsClass) {
- return R_CLASS;
- }
- return 0;
- }
- private int computeRelevanceForMissingElements(boolean hasProblems) {
- if (!hasProblems) {
- return R_NO_PROBLEMS;
- }
- return 0;
- }
- int computeRelevanceForQualification(boolean prefixRequired) {
- if(!prefixRequired && !this.insideQualifiedReference) {
- return R_UNQUALIFIED;
- }
-
- if(prefixRequired && this.insideQualifiedReference) {
- return R_QUALIFIED;
- }
- return 0;
- }
- int computeRelevanceForRestrictions(int accessRuleKind) {
- if(accessRuleKind == IAccessRule.K_ACCESSIBLE) {
- return R_NON_RESTRICTED;
- }
- return 0;
- }
- private int computeRelevanceForStatic(boolean onlyStatic, boolean isStatic) {
- if(this.insideQualifiedReference && !onlyStatic && !isStatic) {
- return R_NON_STATIC;
- }
- return 0;
- }
- private int computeRelevanceForException(){
- if (this.assistNodeIsException) {
- return R_EXCEPTION;
- }
- return 0;
- }
- private int computeRelevanceForException(char[] proposalName){
-
- if((this.assistNodeIsException || (this.assistNodeInJavadoc & CompletionOnJavadoc.EXCEPTION) != 0 )&&
- (CharOperation.match(EXCEPTION_PATTERN, proposalName, false) ||
- CharOperation.match(ERROR_PATTERN, proposalName, false))) {
- return R_EXCEPTION;
- }
- return 0;
- }
- private int computeRelevanceForExpectingType(TypeBinding proposalType){
- if(this.expectedTypes != null && proposalType != null) {
- for (int i = 0; i <= this.expectedTypesPtr; i++) {
- int relevance = R_EXPECTED_TYPE;
- if(CharOperation.equals(this.expectedTypes[i].qualifiedPackageName(), proposalType.qualifiedPackageName()) &&
- CharOperation.equals(this.expectedTypes[i].qualifiedSourceName(), proposalType.qualifiedSourceName())) {
- relevance = R_EXACT_EXPECTED_TYPE;
- }
- if((this.expectedTypesFilter & SUBTYPE) != 0
- && proposalType.isCompatibleWith(this.expectedTypes[i])) {
- return relevance;
- }
- if((this.expectedTypesFilter & SUPERTYPE) != 0
- && this.expectedTypes[i].isCompatibleWith(proposalType)) {
- return relevance;
- }
- }
- }
- return 0;
- }
- private int computeRelevanceForExpectingType(char[] packageName, char[] typeName){
- if(this.expectedTypes != null) {
- for (int i = 0; i <= this.expectedTypesPtr; i++) {
- if(CharOperation.equals(this.expectedTypes[i].qualifiedPackageName(), packageName) &&
- CharOperation.equals(this.expectedTypes[i].qualifiedSourceName(), typeName)) {
- return R_EXACT_EXPECTED_TYPE;
- }
- }
- if(this.hasJavaLangObjectAsExpectedType) {
- return R_EXPECTED_TYPE;
- }
- }
- return 0;
- }
-
- private int computeRelevanceForInheritance(ReferenceBinding receiverType, ReferenceBinding declaringClass) {
- if (receiverType == declaringClass) return R_NON_INHERITED;
- return 0;
- }
-
- int computeRelevanceForInterestingProposal(){
- return computeRelevanceForInterestingProposal(null);
- }
- private int computeRelevanceForInterestingProposal(Binding binding){
- if(this.uninterestingBindings != null) {
- for (int i = 0; i <= this.uninterestingBindingsPtr; i++) {
- if(this.uninterestingBindings[i] == binding) {
- return 0;
- }
- }
- }
- return R_INTERESTING;
- }
- private void computeUninterestingBindings(ASTNode parent, Scope scope){
- if(parent instanceof LocalDeclaration) {
- addUninterestingBindings(((LocalDeclaration)parent).binding);
- } else if (parent instanceof FieldDeclaration) {
- addUninterestingBindings(((FieldDeclaration)parent).binding);
- }
- }
-
- private void findLabels(char[] label, char[][] choices) {
- if(choices == null || choices.length == 0) return;
-
- int length = label.length;
- for (int i = 0; i < choices.length; i++) {
- if (length <= choices[i].length
- && CharOperation.prefixEquals(label, choices[i], false /* ignore case */
- )){
- int relevance = computeBaseRelevance();
- relevance += computeRelevanceForResolution();
- relevance += computeRelevanceForInterestingProposal();
- relevance += computeRelevanceForCaseMatching(label, choices[i]);
- relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE); // no access restriction for keywors
-
- this.noProposal = false;
- if(!this.requestor.isIgnored(CompletionProposal.LABEL_REF)) {
- CompletionProposal proposal = this.createProposal(CompletionProposal.LABEL_REF, this.actualCompletionPosition);
- proposal.setName(choices[i]);
- proposal.setCompletion(choices[i]);
- proposal.setReplaceRange(this.startPosition - this.offset, this.endPosition - this.offset);
- proposal.setRelevance(relevance);
- this.requestor.accept(proposal);
- if(DEBUG) {
- this.printDebug(proposal);
- }
- }
- }
- }
- }
-
- // Helper method for findMethods(char[], FunctionBinding[], Scope, ObjectVector, boolean, boolean, boolean, TypeBinding)
- private void findLocalMethodDeclarations(
- char[] methodName,
- MethodBinding[] methods,
- Scope scope,
- ObjectVector methodsFound,
- // boolean noVoidReturnType, how do you know?
- boolean exactMatch,
- ReferenceBinding receiverType) {
-
- ObjectVector newMethodsFound = new ObjectVector();
- // Inherited methods which are hidden by subclasses are filtered out
- // No visibility checks can be performed without the scope & invocationSite
- int methodLength = methodName.length;
- next : for (int f = methods.length; --f >= 0;) {
-
- MethodBinding method = methods[f];
-
- if (method.isDefaultAbstract()) continue next;
-
- if (method.isConstructor()) continue next;
-
- if (method.isFinal()) {
- newMethodsFound.add(method);
- continue next;
- }
-
- if (this.options.checkDeprecation &&
- method.isViewedAsDeprecated() &&
- !scope.isDefinedInSameUnit(method.declaringClass))
- continue next;
-
- // if (noVoidReturnType && method.returnType == BaseTypes.VoidBinding) continue next;
- if(method.isStatic()) continue next;
-
- if (!method.canBeSeenBy(receiverType, FakeInvocationSite , scope)) continue next;
-
- if (exactMatch) {
- if (!CharOperation.equals(methodName, method.selector, false /* ignore case */
- ))
- continue next;
-
- } else {
-
- if (methodLength > method.selector.length)
- continue next;
-
- if (!CharOperation.prefixEquals(methodName, method.selector, false/* ignore case */)
- && !(this.options.camelCaseMatch && CharOperation.camelCaseMatch(methodName, method.selector)))
- continue next;
- }
-
- for (int i = methodsFound.size; --i >= 0;) {
- MethodBinding otherMethod = (MethodBinding) methodsFound.elementAt(i);
- if (method == otherMethod)
- continue next;
-
- if (CharOperation.equals(method.selector, otherMethod.selector, true)
- && lookupEnvironment.methodVerifier().doesMethodOverride(otherMethod, method)) {
- continue next;
- }
- }
-
- 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;
- 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);
- }
- }
- }
- methodsFound.addAll(newMethodsFound);
- }
-
- private void createType(TypeBinding type, StringBuffer completion) {
- if (type.isBaseType()) {
- completion.append(type.sourceName());
- } else if (type.isArrayType()) {
- createType(type.leafComponentType(), completion);
- int dim = type.dimensions();
- for (int i = 0; i < dim; i++) {
- completion.append('[');
- completion.append(']');
- }
- } else {
- char[] packageName = type.qualifiedPackageName();
- char[] typeName = type.qualifiedSourceName();
- if(mustQualifyType(
- packageName,
- type.sourceName(),
- type.isMemberType() ? type.enclosingType().qualifiedSourceName() : null,
- ((ReferenceBinding)type).modifiers)) {
- completion.append(CharOperation.concat(packageName, typeName,'.'));
- } else {
- completion.append(type.sourceName());
- }
- }
- }
-
- private void createVargsType(TypeBinding type, StringBuffer completion) {
- if (type.isArrayType()) {
- createType(type.leafComponentType(), completion);
- int dim = type.dimensions() - 1;
- for (int i = 0; i < dim; i++) {
- completion.append('[');
- completion.append(']');
- }
- completion.append(VARARGS);
- } else {
- createType(type, completion);
- }
- }
- private char[] createImportCharArray(char[] importedElement, boolean isStatic, boolean onDemand) {
- char[] result = IMPORT;
- if (isStatic) {
- result = CharOperation.concat(result, STATIC, ' ');
- }
- result = CharOperation.concat(result, importedElement, ' ');
- if (onDemand) {
- result = CharOperation.concat(result, ON_DEMAND);
- }
- return CharOperation.concat(result, IMPORT_END);
- }
- private void createMethod(MethodBinding method, char[][] parameterPackageNames, char[][] parameterTypeNames, char[][] parameterNames, StringBuffer completion) {
- //// Modifiers
- // flush uninteresting modifiers
- int insertedModifiers = method.modifiers & ~(ClassFileConstants.AccNative | ClassFileConstants.AccAbstract);
- if(insertedModifiers != ClassFileConstants.AccDefault){
- ASTNode.printModifiers(insertedModifiers, completion);
- }
-
- //// Return type
- createType(method.returnType, completion);
- completion.append(' ');
-
- //// Selector
- completion.append(method.selector);
-
- completion.append('(');
-
- ////Parameters
- TypeBinding[] parameterTypes = method.parameters;
- int length = parameterTypes.length;
- for (int i = 0; i < length; i++) {
- if(i != 0) {
- completion.append(',');
- completion.append(' ');
- }
- createType(parameterTypes[i], completion);
- completion.append(' ');
- if(parameterNames != null){
- completion.append(parameterNames[i]);
- } else {
- completion.append('%');
- }
- }
-
- completion.append(')');
- }
-
- private boolean isIgnored(int kind, boolean missingTypes) {
- return this.requestor.isIgnored(kind) ||
- (missingTypes && !this.requestor.isAllowingRequiredProposals(kind, CompletionProposal.TYPE_REF));
- }
-
- private boolean isIgnored(int kind) {
- return this.requestor.isIgnored(kind);
- }
-
- private boolean isIgnored(int kind, int requiredProposalKind) {
- return this.requestor.isIgnored(kind) ||
- !this.requestor.isAllowingRequiredProposals(kind, requiredProposalKind);
- }
-
- private void findMethods(
- char[] selector,
- TypeBinding[] typeArgTypes,
- TypeBinding[] argTypes,
- ReferenceBinding receiverType,
- Scope scope,
- ObjectVector methodsFound,
- boolean onlyStaticMethods,
- boolean exactMatch,
- boolean isCompletingDeclaration,
- InvocationSite invocationSite,
- Scope invocationScope,
- boolean implicitCall,
- boolean superCall,
- boolean canBePrefixed,
- Binding[] missingElements,
- int[] missingElementsStarts,
- int[] missingElementsEnds,
- boolean missingElementsHaveProblems) {
-
- boolean notInJavadoc = this.assistNodeInJavadoc == 0;
- if (selector == null && notInJavadoc) {
- return;
- }
-
- if(isCompletingDeclaration) {
- MethodBinding[] methods = receiverType.availableMethods();
- if (methods != null){
- for (int i = 0; i < methods.length; i++) {
- if(!methods[i].isDefaultAbstract()) {
- methodsFound.add(methods[i]);
- }
- }
- }
- }
-
- ReferenceBinding currentType = receiverType;
- if (notInJavadoc) {
- if (isCompletingDeclaration){
-
- currentType = receiverType.superclass();
- }
- }
- while (currentType != null) {
-
- MethodBinding[] methods = currentType.availableMethods();
- if (methods != null) {
- if (isCompletingDeclaration){
- findLocalMethodDeclarations(
- selector,
- methods,
- scope,
- methodsFound,
- exactMatch,
- receiverType);
- } else{
- findLocalMethods(
- selector,
- typeArgTypes,
- argTypes,
- methods,
- methods.length,
- scope,
- methodsFound,
- onlyStaticMethods,
- exactMatch,
- receiverType,
- invocationSite,
- invocationScope,
- implicitCall,
- superCall,
- canBePrefixed,
- missingElements,
- missingElementsStarts,
- missingElementsEnds,
- missingElementsHaveProblems);
- }
- }
-
- currentType = currentType.superclass();
-
- }
- }
- private char[][] findMethodParameterNames(MethodBinding method, char[][] parameterTypeNames){
- TypeBinding erasure = method.declaringClass;
- if(!(erasure instanceof ReferenceBinding)) return null;
-
- char[][] parameterNames = null;
-
- int length = parameterTypeNames.length;
-
- if (length == 0){
- return CharOperation.NO_CHAR_CHAR;
- }
- // look into the corresponding unit if it is available
- if (erasure instanceof SourceTypeBinding){
- SourceTypeBinding sourceType = (SourceTypeBinding) erasure;
-
- if (sourceType instanceof CompilationUnitBinding){
- CompilationUnitDeclaration parsedType;
-
- if ((parsedType = ((CompilationUnitScope)sourceType.scope).referenceContext) != null){
- AbstractMethodDeclaration methodDecl = parsedType.declarationOf(method.original());
-
- if(methodDecl == null && method.isConstructor()) {
- //if its a constructor we know the return type is the type the method is defined on
- InferredType type = parsedType.findInferredType(method.returnType.qualifiedSourceName());
- if(type != null) {
- InferredMethod infMethod = type.findMethod(method.selector, null);
-
- if(infMethod.getFunctionDeclaration() instanceof AbstractMethodDeclaration) {
- methodDecl = (AbstractMethodDeclaration)infMethod.getFunctionDeclaration();
- }
- }
- }
-
- if (methodDecl != null){
- Argument[] arguments = methodDecl.arguments;
- parameterNames = new char[length][];
-
- for(int i = 0 ; i < length ; i++){
- parameterNames[i] = arguments[i].name;
- }
- }
- }
- }
- else if (sourceType instanceof MetatdataTypeBinding){
- MetatdataTypeBinding metatdataTypeBinding=(MetatdataTypeBinding)sourceType;
- ClassData classData = metatdataTypeBinding.getClassData();
- Method meth = classData.getMethod(new String (method.selector));
- if (meth != null){
- int argLength=meth.parameters!=null ? meth.parameters.length : 0;
- parameterNames = new char[argLength][];
-
- for(int i = 0 ; i < argLength ; i++){
- parameterNames[i] = meth.parameters[i].name.toCharArray();
- }
- }
- }
- 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 (methodDecl != null){
- Argument[] arguments = methodDecl.arguments;
- parameterNames = new char[length][];
-
- for(int i = 0 ; i < length ; i++){
- parameterNames[i] = arguments[i].name;
- }
- }
- }
- }
- // look into the model
- if(parameterNames == null){
-
- ReferenceBinding bindingType = (ReferenceBinding)erasure;
-
- char[] compoundName = CharOperation.concatWith(bindingType.compoundName, '.');
- Object type = this.typeCache.get(compoundName);
-
- ISourceType sourceType = null;
- if(type != null) {
- if(type instanceof ISourceType) {
- sourceType = (ISourceType) type;
- }
- } else {
- NameEnvironmentAnswer answer = this.nameEnvironment.findType(bindingType.compoundName,this);
- if(answer != null && answer.isSourceType()) {
- sourceType = answer.getSourceTypes()[0];
- this.typeCache.put(compoundName, sourceType);
- }
- }
-
- if(sourceType != null) {
- IType typeHandle = ((SourceTypeElementInfo) sourceType).getHandle();
-
- String[] parameterTypeSignatures = new String[length];
- for (int i = 0; i < length; i++) {
- parameterTypeSignatures[i] = Signature.createTypeSignature(parameterTypeNames[i], false);
- }
- IFunction searchedMethod = typeHandle.getFunction(String.valueOf(method.selector), parameterTypeSignatures);
- IFunction[] foundMethods = typeHandle.findMethods(searchedMethod);
-
- if(foundMethods != null) {
- int len = foundMethods.length;
- if(len == 1) {
- try {
- SourceMethod sourceMethod = (SourceMethod) foundMethods[0];
- parameterNames = ((SourceMethodElementInfo) sourceMethod.getElementInfo()).getArgumentNames();
- } catch (JavaScriptModelException e) {
- // method doesn't exist: ignore
- }
- }
- }
- }
- }
- return parameterNames;
- }
-
- private void findNestedTypes(
- char[] typeName,
- SourceTypeBinding currentType,
- Scope scope,
- boolean proposeAllMemberTypes,
- ObjectVector typesFound) {
- if (typeName == null)
- return;
-
- int typeLength = typeName.length;
-
- SourceTypeBinding nextTypeToIgnore = null;
- while (scope != null) { // done when a COMPILATION_UNIT_SCOPE is found
-
- switch (scope.kind) {
-
- case Scope.METHOD_SCOPE :
- case Scope.BLOCK_SCOPE :
- BlockScope blockScope = (BlockScope) scope;
-
- next : for (int i = 0, length = blockScope.subscopeCount; i < length; i++) {
-
- if (blockScope.subscopes[i] instanceof ClassScope) {
- SourceTypeBinding localType =
- ((ClassScope) blockScope.subscopes[i]).getReferenceBinding();
-
- if (!localType.isAnonymousType()) {
- if (this.isForbidden(localType))
- continue next;
-
- if (typeLength > localType.sourceName.length)
- continue next;
- if (!CharOperation.prefixEquals(typeName, localType.sourceName, false/* ignore case */)
- && !(this.options.camelCaseMatch && CharOperation.camelCaseMatch(typeName, localType.sourceName)))
- continue next;
-
- for (int j = typesFound.size; --j >= 0;) {
- ReferenceBinding otherType = (ReferenceBinding) typesFound.elementAt(j);
-
- if (localType == otherType)
- continue next;
- }
-
- if(this.assistNodeIsClass) {
- if(!localType.isClass()) continue next;
- }
-
- int relevance = computeBaseRelevance();
- relevance += computeRelevanceForResolution();
- relevance += computeRelevanceForInterestingProposal();
- relevance += computeRelevanceForCaseMatching(typeName, localType.sourceName);
- relevance += computeRelevanceForExpectingType(localType);
- relevance += computeRelevanceForException(localType.sourceName);
- relevance += computeRelevanceForClass();
- relevance += computeRelevanceForQualification(false);
- relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE); // no access restriction for nested type
-
- this.noProposal = false;
- if(!this.requestor.isIgnored(CompletionProposal.TYPE_REF)) {
- createTypeProposal(localType, localType.sourceName, IAccessRule.K_ACCESSIBLE, localType.sourceName, relevance);
- }
- }
- }
- }
- break;
-
- case Scope.CLASS_SCOPE :
- SourceTypeBinding enclosingSourceType = scope.enclosingSourceType();
- findMemberTypes(typeName, enclosingSourceType, scope, currentType, false, false, false, false, proposeAllMemberTypes, nextTypeToIgnore, typesFound);
- nextTypeToIgnore = enclosingSourceType;
- if (typeLength == 0)
- return; // do not search outside the class scope if no prefix was provided
- break;
-
- case Scope.COMPILATION_UNIT_SCOPE :
- return;
- }
- scope = scope.parent;
- }
- }
-
- private void findTypesAndPackages(char[] token, Scope scope, ObjectVector typesFound) {
-
- if (token == null)
- return;
-
- boolean proposeType =
- !this.requestor.isIgnored(CompletionProposal.TYPE_REF) ||
- ((this.assistNodeInJavadoc & CompletionOnJavadoc.TEXT) != 0);
-
- boolean proposeAllMemberTypes = !this.assistNodeIsConstructor;
-
- boolean proposeConstructor =
- this.assistNodeIsConstructor &&
- (!isIgnored(CompletionProposal.CONSTRUCTOR_INVOCATION, CompletionProposal.TYPE_REF));
-
-
- if ((proposeType || proposeConstructor) && scope.enclosingSourceType() != null) {
- findNestedTypes(token, scope.enclosingSourceType(), scope, proposeAllMemberTypes, typesFound);
- }
-
- boolean isEmptyPrefix = token.length == 0;
-
- if ((proposeType || proposeConstructor) && this.unitScope != null) {
-
- ReferenceBinding outerInvocationType = scope.enclosingSourceType();
- if(outerInvocationType != null) {
- ReferenceBinding temp = outerInvocationType.enclosingType();
- while(temp != null) {
- outerInvocationType = temp;
- temp = temp.enclosingType();
- }
- }
-
- int typeLength = token.length;
- SourceTypeBinding[] types = this.unitScope.topLevelTypes;
-
- next : for (int i = 0, length = types.length; i < length; i++) {
- SourceTypeBinding sourceType = types[i];
-
- if(isForbidden(sourceType)) continue next;
-
- //hide anonymous types
- if( sourceType.isAnonymousType() ) {
- continue next;
- }
-
- if(proposeAllMemberTypes &&
- sourceType != outerInvocationType) {
- findSubMemberTypes(
- token,
- sourceType,
- scope,
- scope.enclosingSourceType(),
- false,
- false,
- false,
- typesFound);
- }
-
- if (sourceType.sourceName == CompletionParser.FAKE_TYPE_NAME) continue next;
- if (sourceType.sourceName == TypeConstants.PACKAGE_INFO_NAME) continue next;
-
- if (typeLength > sourceType.sourceName.length) continue next;
-
- int index = CharOperation.lastIndexOf('.', sourceType.sourceName);
- if (index > 0) {
-// char[] pkg = CharOperation.subarray(sourceType.sourceName, 0, index);
- char[] simpleName = CharOperation.subarray(sourceType.sourceName, index+1, sourceType.sourceName.length);
-
- if (!CharOperation.prefixEquals(token, simpleName, false) && !CharOperation.prefixEquals(token, sourceType.sourceName, false)
- && !(this.options.camelCaseMatch && CharOperation.camelCaseMatch(token, simpleName))) {
-
- continue;
- }
-
- } else if (!CharOperation.prefixEquals(token, sourceType.sourceName, false)
- && !(this.options.camelCaseMatch && CharOperation.camelCaseMatch(token, sourceType.sourceName))) {
-
- continue;
- }
-
- for (int j = typesFound.size; --j >= 0;) {
- ReferenceBinding otherType = (ReferenceBinding) typesFound.elementAt(j);
-
- if (sourceType == otherType) continue next;
- }
-
- this.knownTypes.put(CharOperation.concat(sourceType.qualifiedPackageName(), sourceType.sourceName(), '.'), this);
-
- if(this.assistNodeIsClass) {
- if(!sourceType.isClass()) continue next;
- }
-
- int relevance = computeBaseRelevance();
- relevance += computeRelevanceForResolution();
- relevance += computeRelevanceForInterestingProposal();
- relevance += computeRelevanceForCaseMatching(token, sourceType.sourceName);
- relevance += computeRelevanceForExpectingType(sourceType);
- relevance += computeRelevanceForQualification(false);
- relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE); // no access restriction for type in the current unit
-
- if(sourceType.isClass()){
- relevance += computeRelevanceForClass();
- relevance += computeRelevanceForException(sourceType.sourceName);
- }
- this.noProposal = false;
- if(proposeType && !this.assistNodeIsConstructor) {
- char[] typeName = sourceType.sourceName();
- createTypeProposal(
- sourceType,
- typeName,
- IAccessRule.K_ACCESSIBLE,
- typeName,
- relevance);
- }
-
- if (proposeConstructor) {
- findConstructors(
- sourceType,
- null,
- scope,
- FakeInvocationSite,
- false);
- }
- }
- }
-
- if (isEmptyPrefix) {
- if (!proposeConstructor) {
- findTypesFromExpectedTypes(token, scope, typesFound, proposeType, proposeConstructor);
- }
- } else {
- if (proposeConstructor) {
- //search index for constructors that match
- this.nameEnvironment.findConstructorDeclarations(
- token,
- this);
- acceptConstructors();
- } else if (proposeType) {
- int searchFor = IJavaScriptSearchConstants.TYPE;
- if(this.assistNodeIsClass) {
- searchFor = IJavaScriptSearchConstants.CLASS;
- }
-
- this.nameEnvironment.findTypes(
- token,
- proposeAllMemberTypes,
- this.options.camelCaseMatch,
- searchFor,
- this);
- acceptTypes(scope);
- }
- if(!isEmptyPrefix && !this.requestor.isIgnored(CompletionProposal.PACKAGE_REF)) {
- this.nameEnvironment.findPackages(token, this);
- }
- }
- }
-
- private void findTypesAndSubpackages(
- char[] token,
- PackageBinding packageBinding,
- Scope scope) {
-
- boolean proposeType =
- !this.requestor.isIgnored(CompletionProposal.TYPE_REF) ||
- ((this.assistNodeInJavadoc & CompletionOnJavadoc.TEXT) != 0 && !this.requestor.isIgnored(CompletionProposal.JSDOC_TYPE_REF));
-
- char[] qualifiedName =
- CharOperation.concatWith(packageBinding.compoundName, token, '.');
-
- if (token == null || token.length == 0) {
- int length = qualifiedName.length;
- System.arraycopy(
- qualifiedName,
- 0,
- qualifiedName = new char[length + 1],
- 0,
- length);
- qualifiedName[length] = '.';
- }
-
- this.qualifiedCompletionToken = qualifiedName;
-
- if (proposeType && this.unitScope != null) {
- int typeLength = qualifiedName.length;
- SourceTypeBinding[] types = this.unitScope.topLevelTypes;
-
- for (int i = 0, length = types.length; i < length; i++) {
- SourceTypeBinding sourceType = types[i];
-
- char[] qualifiedSourceTypeName = CharOperation.concatWith(sourceType.compoundName, '.');
-
- if (sourceType.sourceName == CompletionParser.FAKE_TYPE_NAME) continue;
- if (sourceType.sourceName == TypeConstants.PACKAGE_INFO_NAME) continue;
- if (typeLength > qualifiedSourceTypeName.length) continue;
- if (!(packageBinding == sourceType.getPackage())) continue;
-
- if (!CharOperation.prefixEquals(qualifiedName, qualifiedSourceTypeName, false)
- && !(this.options.camelCaseMatch && CharOperation.camelCaseMatch(token, sourceType.sourceName))) continue;
-
- if (this.options.checkDeprecation &&
- sourceType.isViewedAsDeprecated() &&
- !scope.isDefinedInSameUnit(sourceType))
- continue;
-
- int accessibility = IAccessRule.K_ACCESSIBLE;
- if(sourceType.hasRestrictedAccess()) {
- AccessRestriction accessRestriction = lookupEnvironment.getAccessRestriction(sourceType);
- if(accessRestriction != null) {
- switch (accessRestriction.getProblemId()) {
- case IProblem.ForbiddenReference:
- if (this.options.checkForbiddenReference) {
- continue;
- }
- accessibility = IAccessRule.K_NON_ACCESSIBLE;
- break;
- case IProblem.DiscouragedReference:
- if (this.options.checkDiscouragedReference) {
- continue;
- }
- accessibility = IAccessRule.K_DISCOURAGED;
- break;
- }
- }
- }
-
- this.knownTypes.put(CharOperation.concat(sourceType.qualifiedPackageName(), sourceType.sourceName(), '.'), this);
-
- int relevance = computeBaseRelevance();
- relevance += computeRelevanceForResolution();
- relevance += computeRelevanceForInterestingProposal();
- relevance += computeRelevanceForCaseMatching(qualifiedName, qualifiedSourceTypeName);
- relevance += computeRelevanceForExpectingType(sourceType);
- relevance += computeRelevanceForQualification(false);
- relevance += computeRelevanceForRestrictions(accessibility);
-
- if (sourceType.isClass()) {
- relevance += computeRelevanceForClass();
- relevance += computeRelevanceForException(sourceType.sourceName);
- }
- this.noProposal = false;
- if(proposeType) {
- char[] typeName = sourceType.sourceName();
- createTypeProposal(sourceType, typeName, IAccessRule.K_ACCESSIBLE, typeName, relevance);
- }
- }
- }
-
- if(proposeType) {
- int searchFor = IJavaScriptSearchConstants.TYPE;
- if(this.assistNodeIsClass) {
- searchFor = IJavaScriptSearchConstants.CLASS;
- }
- this.nameEnvironment.findTypes(
- qualifiedName,
- false,
- this.options.camelCaseMatch,
- searchFor,
- this);
- acceptTypes(scope);
- }
- }
-
- private void findVariablesAndMethods(
- char[] token,
- Scope scope,
- InvocationSite invocationSite,
- Scope invocationScope,
- boolean insideTypeAnnotation,
- boolean insideAnnotationAttribute) {
-
- 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
-
- boolean staticsOnly = false;
- // need to know if we're in a static context (or inside a constructor)
- int tokenLength = token.length;
-
- ObjectVector localsFound = new ObjectVector();
- ObjectVector fieldsFound = new ObjectVector();
- ObjectVector methodsFound = new ObjectVector();
-
- 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) {
-
- 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;
- }
-
- 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 (!CharOperation.prefixEquals(token, local.name, false /* ignore case */)
- && !(this.options.camelCaseMatch && CharOperation.camelCaseMatch(token, local.name)))
- continue next;
-
- if (local.isSecret())
- 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);
-
- int relevance = computeBaseRelevance();
- relevance += computeRelevanceForResolution();
- relevance += computeRelevanceForInterestingProposal(local);
- relevance += computeRelevanceForCaseMatching(token, local.name);
- relevance += computeRelevanceForExpectingType(local.type);
- 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);
- }
- }
- }
-
- if (currentScope.kind==Scope.COMPILATION_UNIT_SCOPE )
- break done1;
- else
- break;
- }
- currentScope = currentScope.parent;
- }
- }
-
- boolean proposeField = !this.requestor.isIgnored(CompletionProposal.FIELD_REF);
- boolean proposeMethod = !this.requestor.isIgnored(CompletionProposal.METHOD_REF);
-
- staticsOnly = false;
- currentScope = scope;
-
- if(proposeField || proposeMethod) {
- done2 : while (true) { // done when a COMPILATION_UNIT_SCOPE is found
-
- 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;
- if (proposeMethod && methodScope.numberMethods>0)
- {
- findLocalMethods(
- token,
- null,
- null,
- methodScope.methods,
- methodScope.numberMethods,
- currentScope,
- methodsFound,
- false,
- false,
- null,
- invocationSite,
- invocationScope,
- true,
- false,
- true,
- null,
- 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(
- token,
- enclosingType,
- compilationUnitScope,
- fieldsFound,
- localsFound,
- staticsOnly,
- invocationSite,
- invocationScope,
- true,
- true,
- null,
- null,
- null,
- false);
- }
- if(proposeMethod && !insideAnnotationAttribute) {
- findMethods(
- token,
- null,
- null,
- enclosingType,
- compilationUnitScope,
- methodsFound,
- staticsOnly,
- false,
- false,
- invocationSite,
- invocationScope,
- true,
- false,
- true,
- null,
- null,
- null,
- false);
- }
- }
- staticsOnly |= enclosingType.isStatic();
- insideTypeAnnotation = false;
- // }
-// break;
-
-// case Scope.COMPILATION_UNIT_SCOPE :
- break done2;
- }
- currentScope = currentScope.parent;
- }
-
- if (this.assistNodeInJavadoc == 0) {
- // search in favorites import
- findFieldsAndMethodsFromFavorites(
- token,
- scope,
- invocationSite,
- invocationScope,
- localsFound,
- fieldsFound,
- methodsFound);
- }
-
- //propose methods from environment if token length is not 0
- if (proposeMethod && token.length > 0)
- {
- this.nameEnvironment.findBindings(
- token,
- Binding.METHOD,
- 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(
- token,
- Binding.VARIABLE,
- this.options.camelCaseMatch,
- this);
- acceptBindings(token,false,false);
- }
- }
- }
- private char[][] findVariableFromUnresolvedReference(LocalDeclaration variable, BlockScope scope, final char[][] discouragedNames) {
- final TypeReference type = variable.type;
- if(type != null &&
- type.resolvedType != null &&
- type.resolvedType.problemId() == ProblemReasons.NoError){
-
- final ArrayList proposedNames = new ArrayList();
-
- UnresolvedReferenceNameFinder.UnresolvedReferenceNameRequestor nameRequestor =
- new UnresolvedReferenceNameFinder.UnresolvedReferenceNameRequestor() {
- public void acceptName(char[] name) {
-
- int relevance = computeBaseRelevance();
- relevance += computeRelevanceForInterestingProposal();
- relevance += computeRelevanceForCaseMatching(completionToken, name);
- relevance += R_NAME_FIRST_PREFIX;
- relevance += R_NAME_FIRST_SUFFIX;
- relevance += R_NAME_LESS_NEW_CHARACTERS;
- relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE); // no access restriction for variable name
-
- // accept result
- CompletionEngine.this.noProposal = false;
- 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.setName(name);
- proposal.setCompletion(name);
- //proposal.setFlags(Flags.AccDefault);
- proposal.setReplaceRange(CompletionEngine.this.startPosition - CompletionEngine.this.offset, CompletionEngine.this.endPosition - CompletionEngine.this.offset);
- proposal.setRelevance(relevance);
- CompletionEngine.this.requestor.accept(proposal);
- if(DEBUG) {
- CompletionEngine.this.printDebug(proposal);
- }
- }
- proposedNames.add(name);
- }
- };
-
- ReferenceContext referenceContext = scope.referenceContext();
- if (referenceContext instanceof AbstractMethodDeclaration) {
- AbstractMethodDeclaration md = (AbstractMethodDeclaration)referenceContext;
-
- UnresolvedReferenceNameFinder nameFinder = new UnresolvedReferenceNameFinder(this);
- nameFinder.find(
- completionToken,
- md,
- variable.declarationSourceEnd + 1,
- 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.bodyStart <= variable.sourceStart &&
- variable.sourceStart < initializer.bodyEnd) {
- UnresolvedReferenceNameFinder nameFinder = new UnresolvedReferenceNameFinder(this);
- nameFinder.find(
- completionToken,
- initializer,
- typeDeclaration.scope,
- variable.declarationSourceEnd + 1,
- discouragedNames,
- nameRequestor);
- break done;
- }
- }
- }
- }
- }
-
- int proposedNamesCount = proposedNames.size();
- if (proposedNamesCount > 0) {
- return (char[][])proposedNames.toArray(new char[proposedNamesCount][]);
- }
- }
-
- 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 )
- private void findVariableName(
- char[] token,
- char[] qualifiedPackageName,
- char[] qualifiedSourceName,
- char[] sourceName,
- final TypeBinding typeBinding,
- char[][] discouragedNames,
- final char[][] forbiddenNames,
- int dim,
- int kind,
- int modifiers){
-
- if(sourceName == null || sourceName.length == 0)
- return;
-
- // compute variable name for non base type
- final char[] displayName;
- if (dim > 0){
- int l = qualifiedSourceName.length;
- displayName = new char[l+(2*dim)];
- System.arraycopy(qualifiedSourceName, 0, displayName, 0, l);
- for(int i = 0; i < dim; i++){
- displayName[l+(i*2)] = '[';
- displayName[l+(i*2)+1] = ']';
- }
- } else {
- displayName = qualifiedSourceName;
- }
-
- final char[] t = token;
- final char[] q = qualifiedPackageName;
- INamingRequestor namingRequestor = new INamingRequestor() {
- public void acceptNameWithPrefixAndSuffix(char[] name, boolean isFirstPrefix, boolean isFirstSuffix, int reusedCharacters) {
- accept(
- name,
- (isFirstPrefix ? R_NAME_FIRST_PREFIX : R_NAME_PREFIX) + (isFirstSuffix ? R_NAME_FIRST_SUFFIX : R_NAME_SUFFIX),
- reusedCharacters);
- }
-
- public void acceptNameWithPrefix(char[] name, boolean isFirstPrefix, int reusedCharacters) {
- accept(name, isFirstPrefix ? R_NAME_FIRST_PREFIX : R_NAME_PREFIX, reusedCharacters);
- }
-
- public void acceptNameWithSuffix(char[] name, boolean isFirstSuffix, int reusedCharacters) {
- accept(name, isFirstSuffix ? R_NAME_FIRST_SUFFIX : R_NAME_SUFFIX, reusedCharacters);
- }
-
- public void acceptNameWithoutPrefixAndSuffix(char[] name,int reusedCharacters) {
- accept(name, 0, reusedCharacters);
- }
- void accept(char[] name, int prefixAndSuffixRelevance, int reusedCharacters){
- int l = forbiddenNames == null ? 0 : forbiddenNames.length;
- for (int i = 0; i < l; i++) {
- if (CharOperation.equals(forbiddenNames[i], name, false)) return;
- }
-
- if (CharOperation.prefixEquals(t, name, false)) {
- int relevance = computeBaseRelevance();
- relevance += computeRelevanceForInterestingProposal();
- relevance += computeRelevanceForCaseMatching(t, name);
- relevance += prefixAndSuffixRelevance;
- if(reusedCharacters > 0) relevance += R_NAME_LESS_NEW_CHARACTERS;
- relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE); // no access restriction for variable name
-
- // accept result
- CompletionEngine.this.noProposal = false;
- 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.setName(name);
- proposal.setCompletion(name);
- //proposal.setFlags(Flags.AccDefault);
- proposal.setReplaceRange(CompletionEngine.this.startPosition - CompletionEngine.this.offset, CompletionEngine.this.endPosition - CompletionEngine.this.offset);
- proposal.setRelevance(relevance);
- CompletionEngine.this.requestor.accept(proposal);
- if(DEBUG) {
- CompletionEngine.this.printDebug(proposal);
- }
- }
- }
- }
- };
-
- switch (kind) {
- case FIELD :
- InternalNamingConventions.suggestFieldNames(
- this.javaProject,
- qualifiedPackageName,
- qualifiedSourceName,
- dim,
- modifiers,
- token,
- discouragedNames,
- namingRequestor);
- break;
- case LOCAL :
- InternalNamingConventions.suggestLocalVariableNames(
- this.javaProject,
- qualifiedPackageName,
- qualifiedSourceName,
- dim,
- token,
- discouragedNames,
- namingRequestor);
- break;
- case ARGUMENT :
- InternalNamingConventions.suggestArgumentNames(
- this.javaProject,
- qualifiedPackageName,
- qualifiedSourceName,
- dim,
- token,
- discouragedNames,
- namingRequestor);
- break;
- }
- }
-
- private void findVariableNames(char[] name, TypeReference type , char[][] discouragedNames, char[][] forbiddenNames, int kind, int modifiers){
-
- if(type != null &&
- type.resolvedType != null &&
- type.resolvedType.problemId() == ProblemReasons.NoError){
- TypeBinding tb = type.resolvedType;
- findVariableName(
- name,
- tb.leafComponentType().qualifiedPackageName(),
- tb.leafComponentType().qualifiedSourceName(),
- tb.leafComponentType().sourceName(),
- tb,
- discouragedNames,
- forbiddenNames,
- type.dimensions(),
- kind,
- modifiers);
- }/* else {
- char[][] typeName = type.getTypeName();
- findVariableName(
- name,
- NoChar,
- CharOperation.concatWith(typeName, '.'),
- typeName[typeName.length - 1],
- excludeNames,
- type.dimensions());
- }*/
- }
-
- private ImportBinding[] getFavoriteReferenceBindings(Scope scope) {
- if (this.favoriteReferenceBindings != null) return this.favoriteReferenceBindings;
-
- String[] favoriteReferences = this.requestor.getFavoriteReferences();
-
- if (favoriteReferences == null || favoriteReferences.length == 0) return null;
-
- ImportBinding[] resolvedImports = new ImportBinding[favoriteReferences.length];
-
- int count = 0;
- next : for (int i = 0; i < favoriteReferences.length; i++) {
- String favoriteReference = favoriteReferences[i];
-
- int length;
- if (favoriteReference == null || (length = favoriteReference.length()) == 0) continue next;
-
- boolean onDemand = favoriteReference.charAt(length - 1) == '*';
-
- char[][] compoundName = CharOperation.splitOn('.', favoriteReference.toCharArray());
- if (onDemand) {
- compoundName = CharOperation.subarray(compoundName, 0, compoundName.length - 1);
- }
-
- // remove duplicate and conflicting
- for (int j = 0; j < count; j++) {
- ImportReference f = resolvedImports[j].reference;
-
- if (CharOperation.equals(f.tokens, compoundName)) continue next;
-
- if (!onDemand && ((f.bits & ASTNode.OnDemand) == 0)) {
- if (CharOperation.equals(f.tokens[f.tokens.length - 1], compoundName[compoundName.length - 1]))
- continue next;
- }
- }
-
- boolean isStatic = true;
-
- ImportReference importReference =
- new ImportReference(
- compoundName,
- new long[compoundName.length],
- onDemand);
-
- Binding importBinding = this.unitScope.findImport(compoundName, onDemand);
-
- if (!importBinding.isValidBinding()) {
- continue next;
- }
-
- if (importBinding instanceof PackageBinding) {
- continue next;
- }
-
- resolvedImports[count++] =
- new ImportBinding(compoundName, onDemand, importBinding, importReference);
- }
-
- if (resolvedImports.length > count)
- System.arraycopy(resolvedImports, 0, resolvedImports = new ImportBinding[count], 0, count);
-
- return this.favoriteReferenceBindings = resolvedImports;
- }
-
- public AssistParser getParser() {
-
- return this.parser;
- }
-
- protected void reset() {
-
- super.reset();
- this.knownPkgs = new HashtableOfObject(10);
- this.knownTypes = new HashtableOfObject(10);
- }
-
- private void setSourceRange(int start, int end) {
- this.setSourceRange(start, end, true);
- }
-
- private void setSourceRange(int start, int end, boolean emptyTokenAdjstment) {
- this.startPosition = start;
- if(emptyTokenAdjstment) {
- int endOfEmptyToken = ((CompletionScanner)this.parser.scanner).endOfEmptyToken;
- if (end == 0) {
- this.endPosition = 0;
- }
- else
- this.endPosition = endOfEmptyToken > end ? endOfEmptyToken + 1 : end + 1;
- }
-
- else {
- this.endPosition = end + 1;
- }
- }
- private char[][] computeAlreadyDefinedName(
- BlockScope scope,
- InvocationSite invocationSite) {
- ArrayList result = new ArrayList();
-
- boolean staticsOnly = false;
-
- Scope currentScope = scope;
-
- done1 : while (true) { // done when a COMPILATION_UNIT_SCOPE is found
-
- 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;
-
- case Scope.BLOCK_SCOPE :
- BlockScope blockScope = (BlockScope) currentScope;
-
- next : for (int i = 0, length = blockScope.locals.length; i < length; i++) {
- LocalVariableBinding local = blockScope.locals[i];
-
- if (local == null)
- break next;
-
- if (local.isSecret())
- continue next;
-
- result.add(local.name);
- }
- break;
-
- case Scope.CLASS_SCOPE :
- ClassScope classScope = (ClassScope) currentScope;
- SourceTypeBinding enclosingType = classScope.getReferenceBinding();
- computeAlreadyDefinedName(
- enclosingType,
- classScope,
- staticsOnly,
- invocationSite,
- result);
- staticsOnly |= enclosingType.isStatic();
- break;
-
- case Scope.COMPILATION_UNIT_SCOPE :
- break done1;
- }
- currentScope = currentScope.parent;
- }
-
- if (result.size() == 0) return CharOperation.NO_CHAR_CHAR;
-
- return (char[][])result.toArray(new char[result.size()][]);
- }
-
- private void computeAlreadyDefinedName(
- SourceTypeBinding receiverType,
- ClassScope scope,
- boolean onlyStaticFields,
- InvocationSite invocationSite,
- ArrayList result) {
-
- ReferenceBinding currentType = receiverType;
- do {
- FieldBinding[] fields = currentType.availableFields();
- if(fields != null && fields.length > 0) {
- computeAlreadyDefinedName(
- fields,
- scope,
- onlyStaticFields,
- receiverType,
- invocationSite,
- result);
- }
- currentType = currentType.superclass();
- } while ( currentType != null);
- }
-
- private void computeAlreadyDefinedName(
- FieldBinding[] fields,
- Scope scope,
- boolean onlyStaticFields,
- ReferenceBinding receiverType,
- InvocationSite invocationSite,
- ArrayList result) {
-
- next : for (int f = fields.length; --f >= 0;) {
- FieldBinding field = fields[f];
-
- if (onlyStaticFields && !field.isStatic()) continue next;
-
- if (!field.canBeSeenBy(receiverType, invocationSite, scope)) continue next;
-
- result.add(field.name);
- }
- }
-
- int computeBaseRelevance(){
- return R_DEFAULT;
- }
- int computeRelevanceForResolution(){
- return computeRelevanceForResolution(true);
- }
- int computeRelevanceForResolution(boolean isResolved){
- if (isResolved) {
- return R_RESOLVED;
- }
- return 0;
- }
- private void computeExpectedTypes(ASTNode parent, ASTNode node, Scope scope){
-
- // default filter
- this.expectedTypesFilter = SUBTYPE;
- this.hasJavaLangObjectAsExpectedType = false;
-
- // find types from parent
- if(parent instanceof AbstractVariableDeclaration) {
- AbstractVariableDeclaration variable = (AbstractVariableDeclaration)parent;
- TypeBinding binding = variable.getTypeBinding();
- if(binding != null) {
- if(!(variable.initialization instanceof ArrayInitializer)) {
- addExpectedType(binding, scope);
- }
- }
- } else if(parent instanceof Assignment) {
- TypeBinding binding = ((Assignment)parent).lhs.resolvedType;
- if(binding != null) {
- addExpectedType(binding, scope);
- }
- } else if(parent instanceof ReturnStatement) {
- if(scope.methodScope().referenceContext instanceof AbstractMethodDeclaration) {
- MethodBinding methodBinding = ((AbstractMethodDeclaration) scope.methodScope().referenceContext).binding;
- TypeBinding binding = methodBinding == null ? null : methodBinding.returnType;
- if(binding != null) {
- addExpectedType(binding, scope);
- }
- }
- } else if(parent instanceof MessageSend) {
- MessageSend messageSend = (MessageSend) parent;
-
- if(messageSend.actualReceiverType instanceof ReferenceBinding) {
- ReferenceBinding binding = (ReferenceBinding)messageSend.actualReceiverType;
- boolean isStatic = messageSend.receiver!=null && messageSend.receiver.isTypeReference();
-
- while(binding != null) {
- computeExpectedTypesForMessageSend(
- binding,
- messageSend.selector,
- messageSend.arguments,
- (ReferenceBinding)messageSend.actualReceiverType,
- scope,
- messageSend,
- isStatic);
- binding = binding.superclass();
- }
- }
- } else if(parent instanceof AllocationExpression) {
- AllocationExpression allocationExpression = (AllocationExpression) parent;
-
- ReferenceBinding binding =null;
- if (allocationExpression.type!=null)
- binding=(ReferenceBinding)allocationExpression.type.resolvedType;
- else
- if (allocationExpression.member.resolvedType instanceof ReferenceBinding)
- binding=(ReferenceBinding)allocationExpression.member.resolvedType;
-
-
- if(binding != null) {
- computeExpectedTypesForAllocationExpression(
- binding,
- allocationExpression.arguments,
- scope,
- allocationExpression);
- }
- } else if(parent instanceof OperatorExpression) {
- int operator = (parent.bits & ASTNode.OperatorMASK) >> ASTNode.OperatorSHIFT;
- if(parent instanceof ConditionalExpression) {
- // for future use
- } else if(parent instanceof InstanceOfExpression) {
- InstanceOfExpression e = (InstanceOfExpression) parent;
- TypeBinding binding = e.expression.resolvedType;
- if(binding != null){
- addExpectedType(binding, scope);
- this.expectedTypesFilter = SUBTYPE | SUPERTYPE;
- }
- } else if(parent instanceof BinaryExpression) {
- switch(operator) {
- case OperatorIds.PLUS :
- addExpectedType(TypeBinding.ANY, scope);
- addExpectedType(scope.getJavaLangString(), scope);
- break;
- case OperatorIds.AND_AND :
- case OperatorIds.OR_OR :
- case OperatorIds.XOR :
- addExpectedType(TypeBinding.BOOLEAN, scope);
- break;
- default :
- 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 :
- addExpectedType(TypeBinding.BOOLEAN, scope);
- break;
- case OperatorIds.TWIDDLE :
- addExpectedType(TypeBinding.SHORT, scope);
- addExpectedType(TypeBinding.INT, scope);
- addExpectedType(TypeBinding.LONG, scope);
- addExpectedType(TypeBinding.CHAR, scope);
- break;
- case OperatorIds.PLUS :
- case OperatorIds.MINUS :
- case OperatorIds.PLUS_PLUS :
- case OperatorIds.MINUS_MINUS :
- addExpectedType(TypeBinding.SHORT, scope);
- addExpectedType(TypeBinding.INT, scope);
- addExpectedType(TypeBinding.LONG, scope);
- addExpectedType(TypeBinding.FLOAT, scope);
- addExpectedType(TypeBinding.DOUBLE, scope);
- addExpectedType(TypeBinding.CHAR, scope);
- break;
- }
- }
- } else if(parent instanceof ArrayReference) {
- addExpectedType(TypeBinding.SHORT, scope);
- addExpectedType(TypeBinding.INT, scope);
- addExpectedType(TypeBinding.LONG, scope);
- } else if (parent instanceof TryStatement) {
- boolean isException = false;
- if (node instanceof CompletionOnSingleTypeReference) {
- isException = ((CompletionOnSingleTypeReference)node).isException();
- } else if (node instanceof CompletionOnQualifiedTypeReference) {
- isException = ((CompletionOnQualifiedTypeReference)node).isException();
- }
- if (isException) {
- ThrownExceptionFinder thrownExceptionFinder = new ThrownExceptionFinder();
- ReferenceBinding[] bindings = thrownExceptionFinder.find((TryStatement) parent, (BlockScope)scope);
- if (bindings != null && bindings.length > 0) {
- for (int i = 0; i < bindings.length; i++) {
- addExpectedType(bindings[i], scope);
- }
- this.expectedTypesFilter = SUPERTYPE;
- }
- }
-
- // Expected types for javadoc
- }
-
- if(this.expectedTypesPtr + 1 != this.expectedTypes.length) {
- System.arraycopy(this.expectedTypes, 0, this.expectedTypes = new TypeBinding[this.expectedTypesPtr + 1], 0, this.expectedTypesPtr + 1);
- }
- }
-
- private void computeExpectedTypesForAllocationExpression(
- ReferenceBinding binding,
- Expression[] arguments,
- Scope scope,
- InvocationSite invocationSite) {
-
- MethodBinding[] methods = binding.availableMethods();
- nextMethod : for (int i = 0; i < methods.length; i++) {
- MethodBinding method = methods[i];
-
- if (!method.isConstructor()) continue nextMethod;
-
- if (this.options.checkVisibility && !method.canBeSeenBy(invocationSite, scope)) continue nextMethod;
-
- TypeBinding[] parameters = method.parameters;
- if(parameters.length < arguments.length)
- continue nextMethod;
-
- int length = arguments.length - 1;
-
- for (int j = 0; j < length; j++) {
- Expression argument = arguments[j];
- TypeBinding argType = argument.resolvedType;
- if(argType != null && !argType.isCompatibleWith(parameters[j]))
- continue nextMethod;
- }
-
- TypeBinding expectedType = method.parameters[arguments.length - 1];
- if(expectedType != null) {
- addExpectedType(expectedType, scope);
- }
- }
- }
-
- private void computeExpectedTypesForMessageSend(
- ReferenceBinding binding,
- char[] selector,
- Expression[] arguments,
- ReferenceBinding receiverType,
- Scope scope,
- InvocationSite invocationSite,
- boolean isStatic) {
-
- MethodBinding[] methods = binding.availableMethods();
- nextMethod : for (int i = 0; i < methods.length; i++) {
- MethodBinding method = methods[i];
-
- if (method.isDefaultAbstract()) continue nextMethod;
-
- if (method.isConstructor()) continue nextMethod;
-
- if (isStatic && !method.isStatic()) continue nextMethod;
-
- if (this.options.checkVisibility && !method.canBeSeenBy(receiverType, invocationSite, scope)) continue nextMethod;
-
- if(!CharOperation.equals(method.selector, selector)) continue nextMethod;
-
- TypeBinding[] parameters = method.parameters;
- if(parameters.length < arguments.length)
- continue nextMethod;
-
- int length = arguments.length - 1;
-
- for (int j = 0; j < length; j++) {
- Expression argument = arguments[j];
- TypeBinding argType = argument.resolvedType;
- if(argType != null && !argType.isCompatibleWith(parameters[j]))
- continue nextMethod;
- }
-
- TypeBinding expectedType = method.parameters[arguments.length - 1];
- if(expectedType != null) {
- addExpectedType(expectedType, scope);
- }
- }
- }
- private void addExpectedType(TypeBinding type, Scope scope){
- if (type == null || !type.isValidBinding()) return;
-
- int length = this.expectedTypes.length;
- if (++this.expectedTypesPtr >= length)
- System.arraycopy(this.expectedTypes, 0, this.expectedTypes = new TypeBinding[length * 2], 0, length);
- this.expectedTypes[this.expectedTypesPtr] = type;
-
- if(type == scope.getJavaLangObject()) {
- this.hasJavaLangObjectAsExpectedType = true;
- }
- }
- private void addForbiddenBindings(Binding binding){
- if (binding == null) return;
-
- int length = this.forbbidenBindings.length;
- if (++this.forbbidenBindingsPtr >= length)
- System.arraycopy(this.forbbidenBindings, 0, this.forbbidenBindings = new Binding[length * 2], 0, length);
- this.forbbidenBindings[this.forbbidenBindingsPtr] = binding;
- }
- private void addUninterestingBindings(Binding binding){
- if (binding == null) return;
-
- int length = this.uninterestingBindings.length;
- if (++this.uninterestingBindingsPtr >= length)
- System.arraycopy(this.uninterestingBindings, 0, this.uninterestingBindings = new Binding[length * 2], 0, length);
- this.uninterestingBindings[this.uninterestingBindingsPtr] = binding;
- }
-
- private Scope computeForbiddenBindings(ASTNode astNode, ASTNode astNodeParent, Scope scope) {
- this.forbbidenBindingsFilter = NONE;
- if(scope instanceof ClassScope) {
- TypeDeclaration typeDeclaration = ((ClassScope)scope).referenceContext;
- if(typeDeclaration.superclass == astNode) {
- this.addForbiddenBindings(typeDeclaration.binding);
- return scope.parent;
- }
- } else {
- if (astNodeParent != null && astNodeParent instanceof TryStatement) {
- boolean isException = false;
- if (astNode instanceof CompletionOnSingleTypeReference) {
- isException = ((CompletionOnSingleTypeReference)astNode).isException();
- } else if (astNode instanceof CompletionOnQualifiedTypeReference) {
- isException = ((CompletionOnQualifiedTypeReference)astNode).isException();
- }
- if (isException) {
- Argument[] catchArguments = ((TryStatement) astNodeParent).catchArguments;
- int length = catchArguments == null ? 0 : catchArguments.length;
- for (int i = 0; i < length; i++) {
- TypeBinding caughtException = catchArguments[i].type.resolvedType;
- if (caughtException != null) {
- this.addForbiddenBindings(caughtException);
- this.knownTypes.put(CharOperation.concat(caughtException.qualifiedPackageName(), caughtException.qualifiedSourceName(), '.'), this);
- }
- }
- this.forbbidenBindingsFilter = SUBTYPE;
- }
- }
- }
-// else if(scope instanceof MethodScope) {
-// MethodScope methodScope = (MethodScope) scope;
-// if(methodScope.insideTypeAnnotation) {
-// return methodScope.parent.parent;
-// }
-// }
- return scope;
- }
- private char[] computePrefix(SourceTypeBinding declarationType, SourceTypeBinding invocationType, boolean isStatic){
-
- StringBuffer completion = new StringBuffer(10);
-
- if (isStatic) {
- completion.append(declarationType.sourceName());
-
- } else if (declarationType == invocationType) {
- completion.append(THIS);
-
- } else {
-
- if (!declarationType.isNestedType()) {
-
- completion.append(declarationType.sourceName());
- completion.append('.');
- completion.append(THIS);
-
- } else if (!declarationType.isAnonymousType()) {
-
- completion.append(declarationType.sourceName());
- completion.append('.');
- completion.append(THIS);
-
- }
- }
-
- return completion.toString().toCharArray();
- }
-
- private void proposeNewMethod(char[] token, ReferenceBinding reference) {
- if(!this.requestor.isIgnored(CompletionProposal.POTENTIAL_METHOD_DECLARATION)) {
- int relevance = computeBaseRelevance();
- relevance += computeRelevanceForResolution();
- relevance += computeRelevanceForInterestingProposal();
- relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE); // no access restriction for new method
-
- CompletionProposal proposal = this.createProposal(CompletionProposal.POTENTIAL_METHOD_DECLARATION, this.actualCompletionPosition);
- proposal.setDeclarationSignature(getSignature(reference));
- proposal.setSignature(
- createMethodSignature(
- CharOperation.NO_CHAR_CHAR,
- CharOperation.NO_CHAR_CHAR,
- CharOperation.NO_CHAR,
- VOID));
- proposal.setDeclarationPackageName(reference.qualifiedPackageName());
- proposal.setDeclarationTypeName(reference.qualifiedSourceName());
-
- //proposal.setPackageName(null);
- proposal.setTypeName(VOID);
- proposal.setName(token);
- //proposal.setParameterPackageNames(null);
- //proposal.setParameterTypeNames(null);
- //proposal.setPackageName(null);
- proposal.setCompletion(token);
- proposal.setFlags(Flags.AccPublic);
- proposal.setReplaceRange(this.startPosition - this.offset, this.endPosition - this.offset);
- proposal.setRelevance(relevance);
- this.requestor.accept(proposal);
- if(DEBUG) {
- this.printDebug(proposal);
- }
- }
- }
- private boolean isForbidden(Binding binding) {
- for (int i = 0; i <= this.forbbidenBindingsPtr; i++) {
- if(this.forbbidenBindings[i] == binding) {
- return true;
- }
- if((this.forbbidenBindingsFilter & SUBTYPE) != 0) {
- if (binding instanceof TypeBinding &&
- this.forbbidenBindings[i] instanceof TypeBinding &&
- ((TypeBinding)binding).isCompatibleWith((TypeBinding)this.forbbidenBindings[i])) {
- return true;
- }
- }
- }
- return false;
- }
- private boolean isValidParent(ASTNode parent, ASTNode node, Scope scope){
- return true;
- }
-
- public static char[] createNonGenericTypeSignature(char[] qualifiedTypeName) {
- return Signature.createCharArrayTypeSignature(qualifiedTypeName, true);
- }
- public static char[] createTypeSignature(char[] qualifiedPackageName, char[] qualifiedTypeName) {
- char[] name = new char[qualifiedTypeName.length];
- System.arraycopy(qualifiedTypeName, 0, name, 0, qualifiedTypeName.length);
-
- int depth = 0;
- 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;
- case '>':
- depth++;
- break;
- }
- }
- return Signature.createCharArrayTypeSignature(
- CharOperation.concat(
- qualifiedPackageName,
- name, '.'), true);
- }
-
- public static char[] createMethodSignature(char[][] parameterPackageNames, char[][] parameterTypeNames, char[] returnPackagename, char[] returnTypeName) {
- char[] returnTypeSignature =
- returnTypeName == null || returnTypeName.length == 0
- ? Signature.createCharArrayTypeSignature(VOID, true)
- : Signature.createCharArrayTypeSignature(
- CharOperation.concat(
- returnPackagename,
- CharOperation.replaceOnCopy(returnTypeName, '.', '$'), '.'), true);
-
- return createMethodSignature(
- parameterPackageNames,
- parameterTypeNames,
- returnTypeSignature);
- }
-
- public static char[] createMethodSignature(char[][] parameterPackageNames, char[][] parameterTypeNames, char[] returnTypeSignature) {
- char[][] parameterTypeSignature = new char[parameterTypeNames.length][];
- for (int i = 0; i < parameterTypeSignature.length; i++) {
- parameterTypeSignature[i] =
- Signature.createCharArrayTypeSignature(
- CharOperation.concat(
- parameterPackageNames[i],
- CharOperation.replaceOnCopy(parameterTypeNames[i], '.', '$'), '.'), true);
- }
-
- return Signature.createMethodSignature(
- parameterTypeSignature,
- returnTypeSignature);
- }
-
- protected CompletionProposal createProposal(int kind, int completionOffset) {
- CompletionProposal proposal = CompletionProposal.create(kind, completionOffset - this.offset);
- proposal.nameLookup = this.nameEnvironment.nameLookup;
- proposal.completionEngine = this;
- return proposal;
- }
-
- /*
- * Create a completion proposal for a type.
- */
- private void createTypeProposal(char[] packageName, char[] typeName, int modifiers, int accessibility, char[] completionName, int relevance) {
-
- // Create standard type proposal
- if(!this.requestor.isIgnored(CompletionProposal.TYPE_REF) && (this.assistNodeInJavadoc & CompletionOnJavadoc.ONLY_INLINE_TAG) == 0) {
- CompletionProposal proposal = CompletionProposal.create(CompletionProposal.TYPE_REF, this.actualCompletionPosition - this.offset);
- proposal.nameLookup = this.nameEnvironment.nameLookup;
- proposal.completionEngine = this;
- proposal.setDeclarationSignature(packageName);
- proposal.setSignature(createNonGenericTypeSignature(typeName));
- proposal.setPackageName(packageName);
- proposal.setTypeName(typeName);
- proposal.setCompletion(completionName);
- proposal.setFlags(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);
- }
- }
-
- // Create javadoc text proposal if necessary
- if ((this.assistNodeInJavadoc & CompletionOnJavadoc.TEXT) != 0 && !this.requestor.isIgnored(CompletionProposal.JSDOC_TYPE_REF)) {
- char[] javadocCompletion= inlineTagCompletion(completionName, JavadocTagConstants.TAG_LINK);
- CompletionProposal proposal = CompletionProposal.create(CompletionProposal.JSDOC_TYPE_REF, this.actualCompletionPosition - this.offset);
- proposal.nameLookup = this.nameEnvironment.nameLookup;
- proposal.completionEngine = this;
- proposal.setDeclarationSignature(packageName);
- proposal.setSignature(createNonGenericTypeSignature(typeName));
- proposal.setPackageName(packageName);
- proposal.setTypeName(typeName);
- 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);
- proposal.setAccessibility(accessibility);
- this.requestor.accept(proposal);
- if(DEBUG) {
- this.printDebug(proposal);
- }
- }
- }
-
- /*
- * Create a completion proposal for a member type.
- */
- private void createTypeProposal(ReferenceBinding refBinding, char[] typeName, int accessibility, char[] completionName, int relevance) {
-
- // Create standard type proposal
- if(!this.requestor.isIgnored(CompletionProposal.TYPE_REF) && (this.assistNodeInJavadoc & CompletionOnJavadoc.ONLY_INLINE_TAG) == 0) {
- CompletionProposal proposal = CompletionProposal.create(CompletionProposal.TYPE_REF, this.actualCompletionPosition - this.offset);
- proposal.nameLookup = this.nameEnvironment.nameLookup;
- proposal.completionEngine = this;
- proposal.setDeclarationSignature(refBinding.qualifiedPackageName());
- proposal.setSignature(getSignature(refBinding));
- proposal.setPackageName(refBinding.qualifiedPackageName());
- proposal.setTypeName(typeName);
- proposal.setCompletion(completionName);
- proposal.setFlags(refBinding.modifiers);
- proposal.setReplaceRange(this.startPosition - this.offset, this.endPosition - this.offset);
- proposal.setRelevance(relevance);
- this.requestor.accept(proposal);
- if(DEBUG) {
- this.printDebug(proposal);
- }
- }
-
- // Create javadoc text proposal if necessary
- if ((this.assistNodeInJavadoc & CompletionOnJavadoc.TEXT) != 0 && !this.requestor.isIgnored(CompletionProposal.JSDOC_TYPE_REF)) {
- char[] javadocCompletion= inlineTagCompletion(completionName, JavadocTagConstants.TAG_LINK);
- CompletionProposal proposal = CompletionProposal.create(CompletionProposal.JSDOC_TYPE_REF, this.actualCompletionPosition - this.offset);
- proposal.nameLookup = this.nameEnvironment.nameLookup;
- proposal.completionEngine = this;
- proposal.setDeclarationSignature(refBinding.qualifiedPackageName());
- proposal.setSignature(getSignature(refBinding));
- proposal.setPackageName(refBinding.qualifiedPackageName());
- proposal.setTypeName(typeName);
- proposal.setCompletion(javadocCompletion);
- proposal.setFlags(refBinding.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);
- }
- }
- }
-
- /**
- * Returns completion string inserted inside a specified inline tag.
- * @param completionName
- * @return char[] Completion text inclunding specified inline tag
- */
- private char[] inlineTagCompletion(char[] completionName, char[] inlineTag) {
- int tagLength= inlineTag.length;
- int completionLength = completionName.length;
- int inlineLength = 2+tagLength+1+completionLength+1;
- char[] inlineCompletion = new char[inlineLength];
- inlineCompletion[0] = '{';
- inlineCompletion[1] = '@';
- System.arraycopy(inlineTag, 0, inlineCompletion, 2, tagLength);
- inlineCompletion[tagLength+2] = ' ';
- System.arraycopy(completionName, 0, inlineCompletion, tagLength+3, completionLength);
- // do not add space at end of inline tag (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=121026)
- //inlineCompletion[inlineLength-2] = ' ';
- inlineCompletion[inlineLength-1] = '}';
- return inlineCompletion;
- }
-
- protected void printDebug(CategorizedProblem error) {
- if(CompletionEngine.DEBUG) {
- System.out.print("COMPLETION - completionFailure("); //$NON-NLS-1$
- System.out.print(error);
- System.out.println(")"); //$NON-NLS-1$
- }
- }
-
- private void printDebugTab(int tab, StringBuffer buffer) {
- for (int i = 0; i < tab; i++) {
- buffer.append('\t');
- }
- }
-
- protected void printDebug(CompletionProposal proposal){
- StringBuffer buffer = new StringBuffer();
- printDebug(proposal, 0, buffer);
- System.out.println(buffer.toString());
- }
- private void printDebug(CompletionProposal proposal, int tab, StringBuffer buffer){
- printDebugTab(tab, buffer);
- buffer.append("COMPLETION - "); //$NON-NLS-1$
- switch(proposal.getKind()) {
- case CompletionProposal.ANONYMOUS_CLASS_DECLARATION :
- buffer.append("ANONYMOUS_CLASS_DECLARATION"); //$NON-NLS-1$
- break;
- case CompletionProposal.FIELD_REF :
- buffer.append("FIELD_REF"); //$NON-NLS-1$
- break;
- case CompletionProposal.KEYWORD :
- buffer.append("KEYWORD"); //$NON-NLS-1$
- break;
- case CompletionProposal.LABEL_REF :
- buffer.append("LABEL_REF"); //$NON-NLS-1$
- break;
- case CompletionProposal.LOCAL_VARIABLE_REF :
- buffer.append("LOCAL_VARIABLE_REF"); //$NON-NLS-1$
- break;
- case CompletionProposal.METHOD_DECLARATION :
- buffer.append("FUNCTION_DECLARATION"); //$NON-NLS-1$
- break;
- case CompletionProposal.METHOD_REF :
- buffer.append("FUNCTION_REF"); //$NON-NLS-1$
- break;
- case CompletionProposal.PACKAGE_REF :
- buffer.append("PACKAGE_REF"); //$NON-NLS-1$
- break;
- case CompletionProposal.TYPE_REF :
- buffer.append("TYPE_REF"); //$NON-NLS-1$
- break;
- case CompletionProposal.VARIABLE_DECLARATION :
- buffer.append("VARIABLE_DECLARATION"); //$NON-NLS-1$
- break;
- case CompletionProposal.POTENTIAL_METHOD_DECLARATION :
- buffer.append("POTENTIAL_METHOD_DECLARATION"); //$NON-NLS-1$
- break;
- case CompletionProposal.METHOD_NAME_REFERENCE :
- buffer.append("METHOD_NAME_REFERENCE"); //$NON-NLS-1$
- break;
- case CompletionProposal.FIELD_IMPORT :
- buffer.append("FIELD_IMPORT"); //$NON-NLS-1$
- break;
- case CompletionProposal.METHOD_IMPORT :
- buffer.append("METHOD_IMPORT"); //$NON-NLS-1$
- break;
- case CompletionProposal.TYPE_IMPORT :
- buffer.append("TYPE_IMPORT"); //$NON-NLS-1$
- break;
- default :
- buffer.append("PROPOSAL"); //$NON-NLS-1$
- break;
-
- }
-
- buffer.append("{\n");//$NON-NLS-1$
- printDebugTab(tab, buffer);
- buffer.append("\tCompletion[").append(proposal.getCompletion() == null ? "null".toCharArray() : proposal.getCompletion()).append("]\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- printDebugTab(tab, buffer);
- buffer.append("\tDeclarationSignature[").append(proposal.getDeclarationSignature() == null ? "null".toCharArray() : proposal.getDeclarationSignature()).append("]\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- printDebugTab(tab, buffer);
- buffer.append("\tDeclarationKey[").append(proposal.getDeclarationKey() == null ? "null".toCharArray() : proposal.getDeclarationKey()).append("]\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- printDebugTab(tab, buffer);
- buffer.append("\tSignature[").append(proposal.getSignature() == null ? "null".toCharArray() : proposal.getSignature()).append("]\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- printDebugTab(tab, buffer);
- buffer.append("\tKey[").append(proposal.getKey() == null ? "null".toCharArray() : proposal.getKey()).append("]\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- printDebugTab(tab, buffer);
- buffer.append("\tName[").append(proposal.getName() == null ? "null".toCharArray() : proposal.getName()).append("]\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
- printDebugTab(tab, buffer);
- buffer.append("\tFlags[");//$NON-NLS-1$
- int flags = proposal.getFlags();
- buffer.append(Flags.toString(flags));
- buffer.append("]\n"); //$NON-NLS-1$
-
- CompletionProposal[] proposals = proposal.getRequiredProposals();
- if(proposals != null) {
- printDebugTab(tab, buffer);
- buffer.append("\tRequiredProposals[");//$NON-NLS-1$
- for (int i = 0; i < proposals.length; i++) {
- buffer.append("\n"); //$NON-NLS-1$
- printDebug(proposals[i], tab + 2, buffer);
- }
- printDebugTab(tab, buffer);
- buffer.append("\n\t]\n"); //$NON-NLS-1$
- }
-
- printDebugTab(tab, buffer);
- buffer.append("\tCompletionLocation[").append(proposal.getCompletionLocation()).append("]\n"); //$NON-NLS-1$ //$NON-NLS-2$
- int start = proposal.getReplaceStart();
- int end = proposal.getReplaceEnd();
- printDebugTab(tab, buffer);
- buffer.append("\tReplaceStart[").append(start).append("]"); //$NON-NLS-1$ //$NON-NLS-2$
- buffer.append("-ReplaceEnd[").append(end).append("]\n"); //$NON-NLS-1$ //$NON-NLS-2$
- if (this.source != null) {
- printDebugTab(tab, buffer);
- buffer.append("\tReplacedText[").append(this.source, start, end-start).append("]\n"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- printDebugTab(tab, buffer);
- buffer.append("\tTokenStart[").append(proposal.getTokenStart()).append("]"); //$NON-NLS-1$ //$NON-NLS-2$
- buffer.append("-TokenEnd[").append(proposal.getTokenEnd()).append("]\n"); //$NON-NLS-1$ //$NON-NLS-2$
- printDebugTab(tab, buffer);
- buffer.append("\tRelevance[").append(proposal.getRelevance()).append("]\n"); //$NON-NLS-1$ //$NON-NLS-2$
-
- printDebugTab(tab, buffer);
- buffer.append("}\n");//$NON-NLS-1$
- }
-
- public CompilationUnitDeclaration doParse(ICompilationUnit unit, AccessRestriction accessRestriction) {
- CompilationResult unitResult =
- new CompilationResult(unit, 1, 1, this.compilerOptions.maxProblemsPerUnit);
- try {
- Parser localParser = new Parser(this.problemReporter, this.compilerOptions.parseLiteralExpressionsAsConstants);
- // fix for 309133
- localParser.scanner.taskTags = null;
-
- CompilationUnitDeclaration parsedUnit = localParser.parse(unit, unitResult);
- 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
-// }
- }
-
- }
-
- public static char[] getSignature(Binding binding) {
- char[] result = null;
- if ((binding.kind() & Binding.TYPE) != 0 || (binding.kind() & Binding.COMPILATION_UNIT) != 0) {
- TypeBinding typeBinding = (TypeBinding)binding;
- result = typeBinding.signature();
- // walk the supertypes if the type is anonymous to get a useful name
- while (typeBinding != null && typeBinding.isAnonymousType()) {
- // why not just use ReferenceBinding here?
- if (typeBinding instanceof SourceTypeBinding)
- typeBinding = ((SourceTypeBinding) typeBinding).superclass();
- else if (typeBinding instanceof BinaryTypeBinding)
- typeBinding = ((BinaryTypeBinding) typeBinding).superclass();
- // must avoid endless loop
- else
- typeBinding = null;
- }
- if (typeBinding != null && typeBinding != binding)
- result = typeBinding.signature();
-
- if (result != null) {
- if ( (binding.kind() & Binding.TYPE) != 0 )
- result = CharOperation.replaceOnCopy(result, '/', '.');
- }
- } else {
- result = Engine.getSignature(binding);
- }
-
- return result;
- }
-
- private char[] computeToken(FieldReference field) {
- char[] currentToken = field.token;
- boolean addDot = false;
- if(currentToken != null && currentToken.length == 0)
- addDot = true;
- if(field.receiver != null) {
- if(field.receiver instanceof SingleNameReference) {
- currentToken = CharOperation.concat(((SingleNameReference)field.receiver).token, currentToken, '.');
- } else if(field.receiver instanceof FieldReference) {
- currentToken = CharOperation.concat(computeToken((FieldReference) field.receiver), currentToken, '.');
- }
- }
- if(addDot)
- currentToken = CharOperation.append(currentToken, '.');
- return currentToken;
- }
-
-
- private void findTypesFromExpectedTypes(char[] token, Scope scope, ObjectVector typesFound, boolean proposeType, boolean proposeConstructor) {
- if(this.expectedTypesPtr > -1) {
- int typeLength = token == null ? 0 : token.length;
-
- next : for (int i = 0; i <= this.expectedTypesPtr; i++) {
-
- if(this.expectedTypes[i] instanceof ReferenceBinding) {
- ReferenceBinding refBinding = (ReferenceBinding)this.expectedTypes[i];
-
- if (typeLength > 0) {
- if (typeLength > refBinding.sourceName.length) continue next;
-
- if (!CharOperation.prefixEquals(token, refBinding.sourceName, false)
- && !(this.options.camelCaseMatch && CharOperation.camelCaseMatch(token, refBinding.sourceName))) continue next;
- }
-
- if (this.options.checkDeprecation &&
- refBinding.isViewedAsDeprecated() &&
- !scope.isDefinedInSameUnit(refBinding))
- continue next;
-
- int accessibility = IAccessRule.K_ACCESSIBLE;
- if(refBinding.hasRestrictedAccess()) {
- AccessRestriction accessRestriction = this.lookupEnvironment.getAccessRestriction(refBinding);
- if(accessRestriction != null) {
- switch (accessRestriction.getProblemId()) {
- case IProblem.ForbiddenReference:
- if (this.options.checkForbiddenReference) {
- continue next;
- }
- accessibility = IAccessRule.K_NON_ACCESSIBLE;
- break;
- case IProblem.DiscouragedReference:
- if (this.options.checkDiscouragedReference) {
- continue next;
- }
- accessibility = IAccessRule.K_DISCOURAGED;
- break;
- }
- }
- }
-
- for (int j = 0; j < typesFound.size(); j++) {
- ReferenceBinding typeFound = (ReferenceBinding)typesFound.elementAt(j);
- if (typeFound == refBinding) {
- continue next;
- }
- }
-
- 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);
- }
- }
- }
- }
- }
- }
-
- 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);
- } else {
- ref = new QualifiedTypeReference(cn,new long[cn.length]);
- }
-
- 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;
- }
-
-
- if (guessedType != null && guessedType.isValidBinding()) {
- if (guessedType instanceof SourceTypeBinding) {
- SourceTypeBinding refBinding = (SourceTypeBinding) guessedType;
-
- if (refBinding.scope == null || refBinding.classScope.referenceContext == null) return null;
-
- TypeDeclaration typeDeclaration = refBinding.classScope.referenceContext;
- AbstractMethodDeclaration[] methods = typeDeclaration.methods;
-
- 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);
- }
- }
- }
-
- 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] = ']';
- }
- }
-
- return typeName;
- }
-
- /**
- * <p>Represents a constructor accepted from the index.</p>
- */
- private static class AcceptedConstructor {
- /**
- * <p>Modifiers to the constructor such as public/private</p>
- *
- * @see Flags
- */
- public int modifiers;
-
- /** <p>Name of the type the constructor is for</p> */
- public char[] typeName;
-
- /** <p>Number of parameters for the constructor, or -1 for a default constructor</p> */
- public int parameterCount;
-
- /** <p>Type names of the parameters, should be same length as <code>parameterCount</code></p> */
- public char[][] parameterTypes;
-
- /** <p>Names of the parameters, should be same length as <code>parameterCount</code></p> */
- public char[][] parameterNames;
-
- /**
- * <p>Accessibility of the constructor</p>
- *
- * @see IAccessRule
- */
- public int accessibility;
-
- /**
- * <p>Constructor</p>
- *
- * @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 <code>parameterCount</code>
- * @param parameterNames Names of the parameters, should be same length as <code>parameterCount</code>
- * @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;
- }
-
- /**
- * @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();
- }
- }
-}
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
deleted file mode 100644
index d9a0c987..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/ISearchRequestor.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*******************************************************************************
- * 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.codeassist;
-
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IAccessRule;
-import org.eclipse.wst.jsdt.internal.compiler.env.AccessRestriction;
-
-/**
- * This is the internal requestor passed to the searchable name environment
- * so as to process the multiple search results as they are discovered.
- *
- * It is used to allow the code assist engine to add some more information
- * to the raw name environment results before answering them to the UI.
- */
-public interface ISearchRequestor {
- /**
- * One result of the search consists of a new type.
- *
- * NOTE - All package and type names are presented in their readable form:
- * Package names are in the form "a.b.c".
- * Nested type names are in the qualified form "A.I".
- * The default package is represented by an empty array.
- */
- public void acceptType(char[] packageName, char [] fileName, char[] typeName, char[][] enclosingTypeNames, int modifiers, AccessRestriction accessRestriction);
- public void acceptBinding(char[] packageName, char [] fileName, char[] bindingName, int bindingType, int modifiers, AccessRestriction accessRestriction);
-
- /**
- * 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);
-
- /**
- * <p>Accepts a constructor found during an index search.</p>
- *
- * @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 <code>parameterCount</code>
- * @param parameterNames Names of the parameters, should be same length as <code>parameterCount</code>
- * @param path to the document containing the constructor match
- * @param access Accessibility of the constructor
- *
- * @see Flags
- * @see IAccessRule
- */
- public void acceptConstructor(
- int modifiers,
- char[] typeName,
- int parameterCount,
- char[][] parameterTypes,
- char[][] parameterNames,
- String path,
- AccessRestriction access);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/ISelectionRequestor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/ISelectionRequestor.java
deleted file mode 100644
index 79b87aa4..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/ISelectionRequestor.java
+++ /dev/null
@@ -1,265 +0,0 @@
-/*******************************************************************************
- * 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.codeassist;
-
-import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem;
-
-/**
- * A selection requestor accepts results from the selection engine.
- */
-public interface ISelectionRequestor {
- /**
- * Code assist notification of a enum selection.
- * @param packageName char[]
- * Declaring package name of the type.
- *
- * @param annotationName char[]
- * Name of the type.
- *
- * @param isDeclaration boolean
- * Answer if the selected type is a declaration
- *
- * @param genericTypeSignature
- * genric type signature of the selected type if it is a
- * parameterized type
- *
- * @param start
- * Start of the selection
- *
- * @param end
- * End of the selection
- *
- * NOTE - All package and type names are presented in their readable form:
- * Package names are in the form "a.b.c".
- * Nested type names are in the qualified form "A.M".
- * The default package is represented by an empty array.
- */
- void acceptType(
- char[] packageName,
- char[] fileName,
- char[] annotationName,
- int modifiers,
- boolean isDeclaration,
- char[] genericTypeSignature,
- int start,
- int end);
-
- /**
- * Code assist notification of a compilation error detected during selection.
- * @param error CategorizedProblem
- * Only problems which are categorized as errors are notified to the requestor,
- * warnings are silently ignored.
- * In case an error got signaled, no other completions might be available,
- * therefore the problem message should be presented to the user.
- * The source positions of the problem are related to the source where it was
- * detected (might be in another compilation unit, if it was indirectly requested
- * during the code assist process).
- * Note: the problem knows its originating file name.
- */
- void acceptError(CategorizedProblem error);
-
- /**
- * Code assist notification of a field selection.
- * @param declaringTypePackageName char[]
- * Name of the package in which the type that contains this field is declared.
- *
- * @param declaringTypeName char[]
- * Name of the type declaring this new field.
- *
- * @param name char[]
- * Name of the field.
- *
- * @param isDeclaration boolean
- * Answer if the selected field is a declaration
- *
- * @param uniqueKey
- * unique key of this field
- *
- * @param start
- * Start of the selection
- *
- * @param end
- * End of the selection
- *
- * NOTE - All package and type names are presented in their readable form:
- * Package names are in the form "a.b.c".
- * Nested type names are in the qualified form "A.M".
- * The default package is represented by an empty array.
- */
- void acceptField(
- char[] declaringTypePackageName,
- char[] fileName,
- char[] declaringTypeName,
- char[] name,
- boolean isDeclaration,
- char[] uniqueKey,
- int start,
- int end);
-
- /**
- * Code assist notification of a method selection.
- * @param declaringTypePackageName char[]
- * Name of the package in which the type that contains this new method is declared.
- *
- * @param declaringTypeName char[]
- * Name of the type declaring this new method.
- *
- * @param enclosingDeclaringTypeSignature String
- * Type signature of the declaring type of the declaring type or <code>null</code>
- * if declaring type is a top level type.
- *
- * @param selector char[]
- * Name of the new method.
- *
- * @param parameterPackageNames char[][]
- * Names of the packages in which the parameter types are declared.
- * Should contain as many elements as parameterTypeNames.
- *
- * @param parameterTypeNames char[][]
- * Names of the parameters types.
- * Should contain as many elements as parameterPackageNames.
- *
- * @param parameterSignatures String[]
- * Signature of the parameters types.
- * Should contain as many elements as parameterPackageNames.
- *
- * @param isConstructor boolean
- * Answer if the method is a constructor.
- *
- * @param isDeclaration boolean
- * Answer if the selected method is a declaration
- *
- * @param uniqueKey
- * unique key of the method
- *
- * @param start
- * Start of the selection
- *
- * @param end
- * End of the selection
- *
- * NOTE - All package and type names are presented in their readable form:
- * Package names are in the form "a.b.c".
- * Base types are in the form "int" or "boolean".
- * Array types are in the qualified form "M[]" or "int[]".
- * Nested type names are in the qualified form "A.M".
- * The default package is represented by an empty array.
- */
- // parameters 'isDeclaration', 'start' and 'end' are use to distinguish duplicate methods declarations
- 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);
-
- /**
- * Code assist notification of a package selection.
- * @param packageName char[]
- * The package name.
- *
- * 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.
- */
- void acceptPackage(char[] packageName);
- /**
- * Code assist notification of a type parameter selection.
- *
- * @param declaringTypePackageName char[]
- * Name of the package in which the type that contains this new method is declared.
- *
- * @param declaringTypeName char[]
- * Name of the type declaring this new method.
- *
- * @param typeParameterName char[]
- * Name of the type parameter.
- *
- * @param isDeclaration boolean
- * Answer if the selected type parameter is a declaration
- *
- * @param start
- * Start of the selection
- *
- * @param end
- * End of the selection
- *
- * NOTE - All package and type names are presented in their readable form:
- * Package names are in the form "a.b.c".
- * Nested type names are in the qualified form "A.M".
- * The default package is represented by an empty array.
- */
- void acceptTypeParameter(
- char[] declaringTypePackageName,
- char[] fileName,
- char[] declaringTypeName,
- char[] typeParameterName,
- boolean isDeclaration,
- int start,
- int end);
-
- /**
- * Code assist notification of a type parameter selection.
- *
- * @param declaringTypePackageName char[]
- * Name of the package in which the type that contains this new method is declared.
- *
- * @param declaringTypeName char[]
- * Name of the type declaring this new method.
- *
- * @param selector char[]
- * Name of the declaring method.
- *
- * @param selectorStart int
- * Start of the selector.
- *
- * @param selectorEnd int
- * End of the selector.
- *
- * @param typeParameterName char[]
- * Name of the type parameter.
- *
- * @param isDeclaration boolean
- * Answer if the selected type parameter is a declaration
- *
- * @param start
- * Start of the selection
- *
- * @param end
- * End of the selection
- *
- * NOTE - All package and type names are presented in their readable form:
- * Package names are in the form "a.b.c".
- * Nested type names are in the qualified form "A.M".
- * The default package is represented by an empty array.
- */
- void acceptMethodTypeParameter(
- char[] declaringTypePackageName,
- char[] fileName,
- char[] declaringTypeName,
- char[] selector,
- int selectorStart,
- int selectorEnd,
- char[] typeParameterName,
- boolean isDeclaration,
- int start,
- int end);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/InternalCompletionContext.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/InternalCompletionContext.java
deleted file mode 100644
index 9f5a5722..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/InternalCompletionContext.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist;
-
-
-/**
- * Internal completion context
- * @since 3.1
- */
-public class InternalCompletionContext {
- protected char[][] expectedTypesSignatures;
- protected char[][] expectedTypesKeys;
- protected int javadoc;
-
- protected int offset = -1;
- protected int tokenStart = -1;
- protected int tokenEnd = -1;
- protected char[] token = null;
- protected int tokenKind;
-
- protected void setExpectedTypesSignatures(char[][] expectedTypesSignatures) {
- this.expectedTypesSignatures = expectedTypesSignatures;
- }
-
- protected void setExpectedTypesKeys(char[][] expectedTypesKeys) {
- this.expectedTypesKeys = expectedTypesKeys;
- }
-
- protected void setJavadoc(int javadoc) {
- this.javadoc = javadoc;
- }
-
- protected void setOffset(int offset) {
- this.offset = offset;
- }
-
- protected void setTokenRange(int start, int end) {
- this.setTokenRange(start, end, -1);
- }
- protected void setTokenRange(int start, int end, int endOfEmptyToken) {
- this.tokenStart = start;
- this.tokenEnd = endOfEmptyToken > end ? endOfEmptyToken : end;
-
- // Work around for bug 132558 (https://bugs.eclipse.org/bugs/show_bug.cgi?id=132558).
- // completionLocation can be -1 if the completion occur at the start of a file or
- // the start of a code snippet but this API isn't design to support negative position.
- if(this.tokenEnd == -1) {
- this.tokenEnd = 0;
- }
- }
-
- protected void setToken(char[] token) {
- this.token = token;
- }
-
- protected void setTokenKind(int tokenKind) {
- this.tokenKind = tokenKind;
- }
-}
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
deleted file mode 100644
index da06fc4b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/InternalCompletionProposal.java
+++ /dev/null
@@ -1,205 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist;
-
-import org.eclipse.wst.jsdt.core.IAccessRule;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-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.internal.core.BinaryType;
-import org.eclipse.wst.jsdt.internal.core.NameLookup;
-
-/**
- * Internal completion proposal
- * @since 3.1
- */
-public class InternalCompletionProposal {
- private static Object NO_ATTACHED_SOURCE = new Object();
-
- static final char[] ARG = "arg".toCharArray(); //$NON-NLS-1$
- static final char[] ARG0 = "arg0".toCharArray(); //$NON-NLS-1$
- static final char[] ARG1 = "arg1".toCharArray(); //$NON-NLS-1$
- static final char[] ARG2 = "arg2".toCharArray(); //$NON-NLS-1$
- static final char[] ARG3 = "arg3".toCharArray(); //$NON-NLS-1$
- static final char[][] ARGS1 = new char[][]{ARG0};
- static final char[][] ARGS2 = new char[][]{ARG0, ARG1};
- static final char[][] ARGS3 = new char[][]{ARG0, ARG1, ARG2};
- static final char[][] ARGS4 = new char[][]{ARG0, ARG1, ARG2, ARG3};
-
- protected CompletionEngine completionEngine;
- protected NameLookup nameLookup;
-
- protected char[] declarationPackageName;
- protected char[] declarationTypeName;
- protected char[] packageName;
- protected char[] typeName;
- protected char[][] parameterPackageNames;
- protected char[][] parameterTypeNames;
-
- protected char[] originalSignature;
-
- protected int accessibility = IAccessRule.K_ACCESSIBLE;
-
- protected boolean isConstructor = false;
-
- protected char[][] createDefaultParameterNames(int length) {
- char[][] parameterNames;
- switch (length) {
- case 0 :
- parameterNames = new char[length][];
- break;
- case 1 :
- parameterNames = ARGS1;
- break;
- case 2 :
- parameterNames = ARGS2;
- break;
- case 3 :
- parameterNames = ARGS3;
- break;
- case 4 :
- parameterNames = ARGS4;
- break;
- default :
- parameterNames = new char[length][];
- for (int i = 0; i < length; i++) {
- parameterNames[i] = CharOperation.concat(ARG, String.valueOf(i).toCharArray());
- }
- break;
- }
- return parameterNames;
- }
- protected char[][] findMethodParameterNames(char[] declaringTypePackageName, char[] declaringTypeName, char[] selector, char[][] paramTypeNames){
- if(paramTypeNames == null || declaringTypeName == null) return null;
-
- char[][] parameterNames = null;
- int length = paramTypeNames.length;
-
- char[] tName = CharOperation.concat(declaringTypePackageName,declaringTypeName,'.');
- Object cachedType = this.completionEngine.typeCache.get(tName);
-
- IType type = null;
- if(cachedType != null) {
- if(cachedType != NO_ATTACHED_SOURCE && cachedType instanceof BinaryType) {
- type = (BinaryType)cachedType;
- }
- } else {
- // TODO (david) shouldn't it be NameLookup.ACCEPT_ALL ?
- NameLookup.Answer answer = this.nameLookup.findType(new String(tName),
- false,
- NameLookup.ACCEPT_CLASSES & NameLookup.ACCEPT_INTERFACES,
- true/* consider secondary types */,
- false/* do NOT wait for indexes */,
- false/*don't check restrictions*/,
- null);
- type = answer == null ? null : answer.type;
- if(type instanceof BinaryType){
- this.completionEngine.typeCache.put(tName, type);
- } else {
- type = null;
- }
- }
-
- if(type != null) {
- String[] args = new String[length];
- for(int i = 0; i< length ; i++){
- args[i] = new String(paramTypeNames[i]);
- }
- IFunction method = type.getFunction(new String(selector),args);
- try{
- parameterNames = new char[length][];
- String[] params = method.getParameterNames();
- for(int i = 0; i< length ; i++){
- parameterNames[i] = params[i].toCharArray();
- }
- } catch(JavaScriptModelException e){
- parameterNames = null;
- }
- }
-
- // default parameters name
- if(parameterNames == null) {
- parameterNames = createDefaultParameterNames(length);
- }
-
- return parameterNames;
- }
-
- protected char[] getDeclarationPackageName() {
- return this.declarationPackageName;
- }
-
- protected char[] getDeclarationTypeName() {
- return this.declarationTypeName;
- }
-
- protected char[] getPackageName() {
- return this.packageName;
- }
-
- protected char[] getTypeName() {
- return this.typeName;
- }
-
- protected char[][] getParameterPackageNames() {
- return this.parameterPackageNames;
- }
-
-
- protected char[][] getParameterTypeNames() {
- return this.parameterTypeNames;
- }
-
- protected void setDeclarationPackageName(char[] declarationPackageName) {
- this.declarationPackageName = declarationPackageName;
- }
-
- protected void setDeclarationTypeName(char[] declarationTypeName) {
- this.declarationTypeName = declarationTypeName;
- }
-
- protected void setPackageName(char[] packageName) {
- this.packageName = packageName;
- }
-
- protected void setTypeName(char[] typeName) {
- this.typeName = typeName;
- }
-
- protected void setParameterPackageNames(char[][] parameterPackageNames) {
- this.parameterPackageNames = parameterPackageNames;
- }
-
- protected void setParameterTypeNames(char[][] parameterTypeNames) {
- this.parameterTypeNames = parameterTypeNames;
- }
-
- protected void setAccessibility(int kind) {
- this.accessibility = kind;
- }
-
- protected void setIsContructor(boolean isConstructor) {
- this.isConstructor = isConstructor;
- }
- public void setOriginalSignature(char[] originalSignature) {
- this.originalSignature = originalSignature;
- }
-
- public IJavaScriptProject getJavaProject() {
- return completionEngine.javaProject;
- }
-
- public NameLookup getNameLookup() {
- return nameLookup;
- }
-}
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
deleted file mode 100644
index b38679cd..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/MissingTypesGuesser.java
+++ /dev/null
@@ -1,440 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Set;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ArrayQualifiedTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ArrayTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.SingleTypeReference;
-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.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.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.util.HashtableOfObjectToInt;
-import org.eclipse.wst.jsdt.internal.core.SearchableEnvironment;
-
-public class MissingTypesGuesser extends ASTVisitor {
- public static interface GuessedTypeRequestor {
- public void accept(
- TypeBinding guessedType,
- Binding[] missingElements,
- int[] missingElementsStarts,
- int[] missingElementsEnds,
- boolean hasProblems);
-
- }
-
- private static class ResolutionCleaner extends ASTVisitor {
- private HashtableOfObjectToInt bitsMap = new HashtableOfObjectToInt();
- private boolean firstCall = true;
-
- public ResolutionCleaner(){
- super();
- }
-
- private void cleanUp(TypeReference typeReference) {
- if (this.firstCall) {
- this.bitsMap.put(typeReference, typeReference.bits);
- } else {
- typeReference.bits = this.bitsMap.get(typeReference);
- }
- typeReference.resolvedType = null;
- }
-
- public void cleanUp(TypeReference convertedType, BlockScope scope) {
- convertedType.traverse(this, scope);
- this.firstCall = false;
- }
-
- public void cleanUp(TypeReference convertedType, ClassScope scope) {
- convertedType.traverse(this, scope);
- this.firstCall = false;
- }
-
- public boolean visit(SingleTypeReference singleTypeReference, BlockScope scope) {
- this.cleanUp(singleTypeReference);
- return true;
- }
-
- public boolean visit(SingleTypeReference singleTypeReference, ClassScope scope) {
- this.cleanUp(singleTypeReference);
- return true;
- }
-
- public boolean visit(ArrayTypeReference arrayTypeReference, BlockScope scope) {
- this.cleanUp(arrayTypeReference);
- return true;
- }
-
- public boolean visit(ArrayTypeReference arrayTypeReference, ClassScope scope) {
- this.cleanUp(arrayTypeReference);
- return true;
- }
-
- public boolean visit(QualifiedTypeReference qualifiedTypeReference, BlockScope scope) {
- this.cleanUp(qualifiedTypeReference);
- return true;
- }
-
- public boolean visit(QualifiedTypeReference qualifiedTypeReference, ClassScope scope) {
- this.cleanUp(qualifiedTypeReference);
- return true;
- }
-
- public boolean visit(ArrayQualifiedTypeReference arrayQualifiedTypeReference, BlockScope scope) {
- this.cleanUp(arrayQualifiedTypeReference);
- return true;
- }
-
- public boolean visit(ArrayQualifiedTypeReference arrayQualifiedTypeReference, ClassScope scope) {
- this.cleanUp(arrayQualifiedTypeReference);
- return true;
- }
- }
-
- private CompletionEngine.CompletionProblemFactory problemFactory ;
- private SearchableEnvironment nameEnvironment;
-
- private HashMap substituedTypes;
- private HashMap originalTypes;
- private int combinationsCount;
-
- public MissingTypesGuesser(CompletionEngine completionEngine) {
- this.problemFactory = completionEngine.problemFactory;
- this.nameEnvironment = completionEngine.nameEnvironment;
- }
-
- private boolean computeMissingElements(
- QualifiedTypeReference[] substituedTypeNodes,
- char[][][] originalTypeNames,
- Binding[] missingElements,
- int[] missingElementsStarts,
- int[] missingElementsEnds) {
- int length = substituedTypeNodes.length;
-
- for (int i = 0; i < length; i++) {
- TypeReference substituedType = substituedTypeNodes[i];
- if (substituedType.resolvedType == null) return false;
- ReferenceBinding erasure = (ReferenceBinding)substituedType.resolvedType.leafComponentType();
- Binding missingElement;
- int depthToRemove = originalTypeNames[i].length - 1 ;
- if (depthToRemove == 0) {
- missingElement = erasure;
- } else {
- int depth = erasure.depth() + 1;
-
- if (depth > depthToRemove) {
- missingElement = erasure.enclosingTypeAt(depthToRemove);
- } else {
- return false;
- ///////////////////////////////////////////////////////////
- //// Uncomment the following code to return missing package
- ///////////////////////////////////////////////////////////
- //depthToRemove -= depth;
- //PackageBinding packageBinding = erasure.getPackage();
- //while(depthToRemove > 0) {
- // packageBinding = packageBinding.parent;
- // depthToRemove--;
- //}
- //missingElement = packageBinding;
- }
- }
-
- missingElements[i] = missingElement;
- missingElementsStarts[i] = substituedType.sourceStart;
- missingElementsEnds[i] = substituedType.sourceEnd + 1;
-
- }
-
- return true;
- }
-
- private TypeReference convert(ArrayQualifiedTypeReference typeRef) {
- if (typeRef.resolvedType != null) {
- if (typeRef.resolvedType.isValidBinding()) {
- ArrayQualifiedTypeReference convertedType =
- new ArrayQualifiedTypeReference(
- typeRef.tokens,
- typeRef.dimensions(),
- typeRef.sourcePositions);
- convertedType.sourceStart = typeRef.sourceStart;
- convertedType.sourceEnd = typeRef.sourceEnd;
- return convertedType;
- } else if((typeRef.resolvedType.problemId() & ProblemReasons.NotFound) != 0) {
- // only the first token must be resolved
- if(((ReferenceBinding)typeRef.resolvedType.leafComponentType()).compoundName.length != 1) return null;
-
- char[][] typeName = typeRef.getTypeName();
- char[][][] typeNames = findTypeNames(typeName);
- if(typeNames == null || typeNames.length == 0) return null;
- ArrayQualifiedTypeReference convertedType =
- new ArrayQualifiedTypeReference(
- typeNames[0],
- typeRef.dimensions(),
- new long[typeNames[0].length]);
- convertedType.sourceStart = typeRef.sourceStart;
- convertedType.sourceEnd = (int)(typeRef.sourcePositions[0] & 0x00000000FFFFFFFFL);
- this.substituedTypes.put(convertedType, typeNames);
- this.originalTypes.put(convertedType, typeName);
- this.combinationsCount *= typeNames.length;
- return convertedType;
- }
- }
- return null;
- }
-
- private TypeReference convert(ArrayTypeReference typeRef) {
- if (typeRef.resolvedType != null) {
- if (typeRef.resolvedType.isValidBinding()) {
- ArrayTypeReference convertedType =
- new ArrayTypeReference(
- typeRef.token,
- typeRef.dimensions,
- 0);
- convertedType.sourceStart = typeRef.sourceStart;
- convertedType.sourceEnd = typeRef.originalSourceEnd;
- return convertedType;
- } else if((typeRef.resolvedType.problemId() & ProblemReasons.NotFound) != 0) {
- char[][] typeName = typeRef.getTypeName();
- char[][][] typeNames = findTypeNames(typeName);
- if(typeNames == null || typeNames.length == 0) return null;
- ArrayQualifiedTypeReference convertedType =
- new ArrayQualifiedTypeReference(
- typeNames[0],
- typeRef.dimensions,
- new long[typeNames[0].length]);
- convertedType.sourceStart = typeRef.sourceStart;
- convertedType.sourceEnd = typeRef.originalSourceEnd;
- this.substituedTypes.put(convertedType, typeNames);
- this.originalTypes.put(convertedType, typeName);
- this.combinationsCount *= typeNames.length;
- return convertedType;
- }
- }
- return null;
- }
-
- private TypeReference convert(QualifiedTypeReference typeRef) {
- if (typeRef.resolvedType != null) {
- if (typeRef.resolvedType.isValidBinding()) {
- QualifiedTypeReference convertedType = new QualifiedTypeReference(typeRef.tokens, typeRef.sourcePositions);
- convertedType.sourceStart = typeRef.sourceStart;
- convertedType.sourceEnd = typeRef.sourceEnd;
- return convertedType;
- } else if((typeRef.resolvedType.problemId() & ProblemReasons.NotFound) != 0) {
- // only the first token must be resolved
- if(((ReferenceBinding)typeRef.resolvedType).compoundName.length != 1) return null;
-
- char[][] typeName = typeRef.getTypeName();
- char[][][] typeNames = findTypeNames(typeName);
- if(typeNames == null || typeNames.length == 0) return null;
- QualifiedTypeReference convertedType = new QualifiedTypeReference(typeNames[0], new long[typeNames[0].length]);
- convertedType.sourceStart = typeRef.sourceStart;
- convertedType.sourceEnd = (int)(typeRef.sourcePositions[0] & 0x00000000FFFFFFFFL);
- this.substituedTypes.put(convertedType, typeNames);
- this.originalTypes.put(convertedType, typeName);
- this.combinationsCount *= typeNames.length;
- return convertedType;
- }
- }
- return null;
- }
-
- private TypeReference convert(SingleTypeReference typeRef) {
- if (typeRef.resolvedType != null) {
- if (typeRef.resolvedType.isValidBinding()) {
- SingleTypeReference convertedType = new SingleTypeReference(typeRef.token, 0);
- convertedType.sourceStart = typeRef.sourceStart;
- convertedType.sourceEnd = typeRef.sourceEnd;
- return convertedType;
- } else if((typeRef.resolvedType.problemId() & ProblemReasons.NotFound) != 0) {
- char[][] typeName = typeRef.getTypeName();
- char[][][] typeNames = findTypeNames(typeName);
- if(typeNames == null || typeNames.length == 0) return null;
- QualifiedTypeReference convertedType = new QualifiedTypeReference(typeNames[0], new long[typeNames[0].length]);
- convertedType.sourceStart = typeRef.sourceStart;
- convertedType.sourceEnd = typeRef.sourceEnd;
- this.substituedTypes.put(convertedType, typeNames);
- this.originalTypes.put(convertedType, typeName);
- this.combinationsCount *= typeNames.length;
- return convertedType;
- }
- }
- return null;
- }
-
- private TypeReference convert(TypeReference typeRef) {
- if (typeRef instanceof ArrayTypeReference) {
- return convert((ArrayTypeReference)typeRef);
- } else if(typeRef instanceof ArrayQualifiedTypeReference) {
- return convert((ArrayQualifiedTypeReference)typeRef);
- } else if (typeRef instanceof SingleTypeReference) {
- return convert((SingleTypeReference)typeRef);
- } else if (typeRef instanceof QualifiedTypeReference) {
- return convert((QualifiedTypeReference)typeRef);
- }
- return null;
- }
-
- private char[][][] findTypeNames(char[][] missingTypeName) {
- char[] missingSimpleName = missingTypeName[missingTypeName.length - 1];
- final boolean isQualified = missingTypeName.length > 1;
- final char[] missingFullyQualifiedName =
- isQualified ? CharOperation.concatWith(missingTypeName, '.') : null;
- final ArrayList results = new ArrayList();
- ISearchRequestor storage = new ISearchRequestor() {
-
- public void acceptPackage(char[] packageName) {
- // package aren't searched
- }
- public void acceptType(
- char[] packageName,
- char[] fileName,
- char[] typeName,
- char[][] enclosingTypeNames,
- int modifiers,
- AccessRestriction accessRestriction) {
- char[] fullyQualifiedName = CharOperation.concat(packageName, CharOperation.concat(CharOperation.concatWith(enclosingTypeNames, '.'), typeName, '.'), '.');
- if (isQualified && !CharOperation.endsWith(fullyQualifiedName, missingFullyQualifiedName)) return;
- char[][] compoundName = CharOperation.splitOn('.', fullyQualifiedName);
- results.add(compoundName);
- }
- public void acceptBinding(char[] packageName, char[] fileName, char[] bindingName, int bindingType, int modifiers, AccessRestriction accessRestriction) {
- //do nothing
- }
-
- /**
- * @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)
- */
- public void acceptConstructor(int modifiers, char[] typeName,
- int parameterCount, char[][] parameterTypes, char[][] parameterNames,
- String path, AccessRestriction access) {
-
- //do nothing
- }
-
- };
- nameEnvironment.findExactTypes(missingSimpleName, true, IJavaScriptSearchConstants.TYPE, storage);
- if(results.size() == 0) return null;
- return (char[][][])results.toArray(new char[results.size()][0][0]);
- }
-
- private char[][] getOriginal(TypeReference typeRef) {
- return (char[][])this.originalTypes.get(typeRef);
- }
-
- private QualifiedTypeReference[] getSubstituedTypes() {
- Set types = this.substituedTypes.keySet();
- return (QualifiedTypeReference[]) types.toArray(new QualifiedTypeReference[types.size()]);
- }
-
- private char[][][] getSubstitution(TypeReference typeRef) {
- return (char[][][])this.substituedTypes.get(typeRef);
- }
-
- public void guess(TypeReference typeRef, Scope scope, GuessedTypeRequestor requestor) {
- this.substituedTypes = new HashMap();
- this.originalTypes = new HashMap();
- this.combinationsCount = 1;
-
- TypeReference convertedType = convert(typeRef);
-
- if(convertedType == null) return;
-
- QualifiedTypeReference[] substituedTypeNodes = this.getSubstituedTypes();
- int length = substituedTypeNodes.length;
-
- int[] substitutionsIndexes = new int[substituedTypeNodes.length];
- char[][][][] subtitutions = new char[substituedTypeNodes.length][][][];
- char[][][] originalTypeNames = new char[substituedTypeNodes.length][][];
- for (int i = 0; i < substituedTypeNodes.length; i++) {
- subtitutions[i] = this.getSubstitution(substituedTypeNodes[i]);
- originalTypeNames[i] = this.getOriginal(substituedTypeNodes[i]);
- }
-
- ResolutionCleaner resolutionCleaner = new ResolutionCleaner();
- for (int i = 0; i < this.combinationsCount; i++) {
-
- nextSubstitution(substituedTypeNodes, subtitutions, substitutionsIndexes);
-
-
- this.problemFactory.startCheckingProblems();
- TypeBinding guessedType = null;
- switch (scope.kind) {
- case Scope.METHOD_SCOPE :
- case Scope.BLOCK_SCOPE :
- resolutionCleaner.cleanUp(convertedType, (BlockScope)scope);
- guessedType = convertedType.resolveType((BlockScope)scope);
- break;
- case Scope.CLASS_SCOPE :
- resolutionCleaner.cleanUp(convertedType, (ClassScope)scope);
- guessedType = convertedType.resolveType((ClassScope)scope);
- break;
- }
- this.problemFactory.stopCheckingProblems();
- if (!this.problemFactory.hasForbiddenProblems) {
- if (guessedType != null) {
- Binding[] missingElements = new Binding[length];
- int[] missingElementsStarts = new int[length];
- int[] missingElementsEnds = new int[length];
-
- if(computeMissingElements(
- substituedTypeNodes,
- originalTypeNames,
- missingElements,
- missingElementsStarts,
- missingElementsEnds)) {
- requestor.accept(
- guessedType,
- missingElements,
- missingElementsStarts,
- missingElementsEnds,
- this.problemFactory.hasAllowedProblems);
- }
- }
- }
- }
- }
- private void nextSubstitution(
- QualifiedTypeReference[] substituedTypeNodes,
- char[][][][] subtitutions,
- int[] substitutionsIndexes) {
- int length = substituedTypeNodes.length;
-
- done : for (int i = 0; i < length; i++) {
- if(substitutionsIndexes[i] < subtitutions[i].length - 1) {
- substitutionsIndexes[i]++;
- break done;
- } else {
- substitutionsIndexes[i] = 0;
- }
- }
-
- for (int i = 0; i < length; i++) {
- QualifiedTypeReference qualifiedTypeReference = substituedTypeNodes[i];
- qualifiedTypeReference.tokens = subtitutions[i][substitutionsIndexes[i]];
- qualifiedTypeReference.sourcePositions = new long[qualifiedTypeReference.tokens.length];
- }
- }
-}
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
deleted file mode 100644
index ce267f1c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/RelevanceConstants.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist;
-
-public interface RelevanceConstants {
-
- int R_DEFAULT = 0;
- int R_INTERESTING = 5;
- int R_CASE = 10;
- int R_CAMEL_CASE = 5;
- int R_EXACT_NAME = 4;
- int R_EXPECTED_TYPE = 20;
- int R_EXACT_EXPECTED_TYPE = 30;
- int R_CLASS = 20;
- int R_EXCEPTION = 20;
- int R_ABSTRACT_METHOD = 20;
- int R_NON_STATIC = 11;
- int R_UNQUALIFIED = 3;
- int R_QUALIFIED = 2;
- int R_NAME_FIRST_PREFIX = 6;
- int R_NAME_PREFIX = 5;
- int R_NAME_FIRST_SUFFIX = 4;
- int R_NAME_SUFFIX = 3;
- int R_NAME_LESS_NEW_CHARACTERS = 15;
- int R_METHOD_OVERIDE = 3;
- int R_NON_RESTRICTED = 3;
- int R_TRUE_OR_FALSE = 1;
- int R_INLINE_TAG = 31;
- int R_VALUE_TAG = 31;
- int R_NON_INHERITED = 2;
- int R_NO_PROBLEMS = 1;
- int R_RESOLVED = 1;
- int R_TARGET = 5;
-}
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
deleted file mode 100644
index 69577239..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/SelectionEngine.java
+++ /dev/null
@@ -1,1301 +0,0 @@
-/*******************************************************************************
- * 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.codeassist;
-
-import java.util.Locale;
-import java.util.Map;
-
-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.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.internal.codeassist.impl.AssistParser;
-import org.eclipse.wst.jsdt.internal.codeassist.impl.Engine;
-import org.eclipse.wst.jsdt.internal.codeassist.select.SelectionNodeFound;
-import org.eclipse.wst.jsdt.internal.codeassist.select.SelectionOnImportReference;
-import org.eclipse.wst.jsdt.internal.codeassist.select.SelectionOnPackageReference;
-import org.eclipse.wst.jsdt.internal.codeassist.select.SelectionOnQualifiedTypeReference;
-import org.eclipse.wst.jsdt.internal.codeassist.select.SelectionOnSingleTypeReference;
-import org.eclipse.wst.jsdt.internal.codeassist.select.SelectionParser;
-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.AbstractMethodDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ConstructorDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ImportReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ProgramElement;
-import org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.env.AccessRestriction;
-import org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit;
-import org.eclipse.wst.jsdt.internal.compiler.env.ISourceType;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ArrayBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BaseTypeBinding;
-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.FieldBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.LocalFunctionBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.LocalTypeBinding;
-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.MemberTypeBinding;
-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.PackageBinding;
-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.parser.Parser;
-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.SourceTypeConverter;
-import org.eclipse.wst.jsdt.internal.compiler.parser.TerminalTokens;
-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.DefaultProblemFactory;
-import org.eclipse.wst.jsdt.internal.compiler.problem.ProblemReporter;
-import org.eclipse.wst.jsdt.internal.core.SearchableEnvironment;
-import org.eclipse.wst.jsdt.internal.core.SelectionRequestor;
-import org.eclipse.wst.jsdt.internal.core.SourceType;
-import org.eclipse.wst.jsdt.internal.core.SourceTypeElementInfo;
-import org.eclipse.wst.jsdt.internal.core.util.ASTNodeFinder;
-
-/**
- * The selection engine is intended to infer the nature of a selected name in some
- * source code. This name can be qualified.
- *
- * Selection is resolving context using a name environment (no need to search), assuming
- * the source where selection occurred is correct and will not perform any completion
- * attempt. If this was the desired behavior, a call to the CompletionEngine should be
- * performed instead.
- */
-public final class SelectionEngine extends Engine implements ISearchRequestor {
-
- public static boolean DEBUG = false;
- public static boolean PERF = false;
-
- SelectionParser parser;
- ISelectionRequestor requestor;
-
- boolean acceptedAnswer;
-
- private int actualSelectionStart;
- private int actualSelectionEnd;
- private char[] selectedIdentifier;
-
- private char[][][] acceptedClasses;
- private int[] acceptedClassesModifiers;
- private char[][][] acceptedInterfaces;
- private int[] acceptedInterfacesModifiers;
- private char[][][] acceptedEnums;
- private int[] acceptedEnumsModifiers;
- private char[][][] acceptedAnnotations;
- private int[] acceptedAnnotationsModifiers;
- int acceptedClassesCount;
- int acceptedInterfacesCount;
- int acceptedEnumsCount;
- int acceptedAnnotationsCount;
-
- boolean noProposal = true;
- CategorizedProblem problem = null;
-
- /**
- * The SelectionEngine is responsible for computing the selected object.
- *
- * It requires a searchable name environment, which supports some
- * specific search APIs, and a requestor to feed back the results to a UI.
- *
- * @param nameEnvironment org.eclipse.wst.jsdt.internal.core.SearchableEnvironment
- * used to resolve type/package references and search for types/packages
- * based on partial names.
- *
- * @param requestor org.eclipse.wst.jsdt.internal.codeassist.ISelectionRequestor
- * since the engine might produce answers of various forms, the engine
- * is associated with a requestor able to accept all possible completions.
- *
- * @param settings java.util.Map
- * set of options used to configure the code assist engine.
- */
- public SelectionEngine(
- SearchableEnvironment nameEnvironment,
- ISelectionRequestor requestor,
- Map settings) {
-
- super(settings);
-
- this.requestor = requestor;
- this.nameEnvironment = nameEnvironment;
-
- ProblemReporter problemReporter =
- new ProblemReporter(
- DefaultErrorHandlingPolicies.proceedWithAllProblems(),
- this.compilerOptions,
- new DefaultProblemFactory(Locale.getDefault())) {
-
- public CategorizedProblem createProblem(
- char[] fileName,
- int problemId,
- String[] problemArguments,
- String[] messageArguments,
- int severity,
- int problemStartPosition,
- int problemEndPosition,
- int lineNumber,
- int columnNumber) {
- CategorizedProblem pb = super.createProblem(
- fileName,
- problemId,
- problemArguments,
- messageArguments,
- severity,
- problemStartPosition,
- problemEndPosition,
- lineNumber,
- columnNumber);
- if(SelectionEngine.this.problem == null && pb.isError() && (pb.getID() & IProblem.Syntax) == 0) {
- SelectionEngine.this.problem = pb;
- }
-
- return pb;
- }
- };
- this.lookupEnvironment =
- new LookupEnvironment(this, this.compilerOptions, problemReporter, nameEnvironment);
- this.parser = new SelectionParser(problemReporter);
- }
-
- public void acceptType(char[] packageName, char [] fileName, char[] simpleTypeName, char[][] enclosingTypeNames, int modifiers, AccessRestriction accessRestriction) {
- char[] typeName = enclosingTypeNames == null ?
- simpleTypeName :
- CharOperation.concat(
- CharOperation.concatWith(enclosingTypeNames, '.'),
- simpleTypeName,
- '.');
-
- if (CharOperation.equals(simpleTypeName, this.selectedIdentifier)) {
- char[] flatEnclosingTypeNames =
- enclosingTypeNames == null || enclosingTypeNames.length == 0 ?
- null :
- CharOperation.concatWith(enclosingTypeNames, '.');
- if(mustQualifyType(packageName, simpleTypeName, flatEnclosingTypeNames, modifiers)) {
- int length = 0;
- int kind = 0;
- switch (kind) {
- default:
- char[][] acceptedClass = new char[3][];
- acceptedClass[0] = packageName;
- acceptedClass[1] = typeName;
- acceptedClass[2] = fileName;
-
- if(this.acceptedClasses == null) {
- this.acceptedClasses = new char[10][][];
- this.acceptedClassesModifiers = new int[10];
- this.acceptedClassesCount = 0;
- }
- length = this.acceptedClasses.length;
- if(length == this.acceptedClassesCount) {
- int newLength = (length + 1)* 2;
- System.arraycopy(this.acceptedClasses, 0, this.acceptedClasses = new char[newLength][][], 0, length);
- System.arraycopy(this.acceptedClassesModifiers, 0, this.acceptedClassesModifiers = new int[newLength], 0, length);
- }
- this.acceptedClassesModifiers[this.acceptedClassesCount] = modifiers;
- this.acceptedClasses[this.acceptedClassesCount++] = acceptedClass;
- break;
- }
- } else {
- this.noProposal = false;
- this.requestor.acceptType(
- packageName,
- fileName,
- typeName,
- modifiers,
- false,
- null,
- this.actualSelectionStart,
- this.actualSelectionEnd);
- this.acceptedAnswer = true;
- }
- }
- }
-
- public void acceptBinding(char[] packageName, char [] filename, char[] simpleTypeName, int bindingType, int modifiers, AccessRestriction accessRestriction) {
- char[] typeName = simpleTypeName ;
-
- if (CharOperation.equals(simpleTypeName, this.selectedIdentifier)) {
- char[] flatEnclosingTypeNames = null;
- if(mustQualifyType(packageName, simpleTypeName, flatEnclosingTypeNames, modifiers)) {
- int length = 0;
- int kind = 0;
- switch (kind) {
- default:
- char[][] acceptedClass = new char[2][];
- acceptedClass[0] = packageName;
- acceptedClass[1] = typeName;
-
- if(this.acceptedClasses == null) {
- this.acceptedClasses = new char[10][][];
- this.acceptedClassesModifiers = new int[10];
- this.acceptedClassesCount = 0;
- }
- length = this.acceptedClasses.length;
- if(length == this.acceptedClassesCount) {
- int newLength = (length + 1)* 2;
- System.arraycopy(this.acceptedClasses, 0, this.acceptedClasses = new char[newLength][][], 0, length);
- System.arraycopy(this.acceptedClassesModifiers, 0, this.acceptedClassesModifiers = new int[newLength], 0, length);
- }
- this.acceptedClassesModifiers[this.acceptedClassesCount] = modifiers;
- this.acceptedClasses[this.acceptedClassesCount++] = acceptedClass;
- break;
- }
- } else {
- this.noProposal = false;
- this.requestor.acceptType(
- packageName,
- filename,
- typeName,
- modifiers,
- false,
- null,
- this.actualSelectionStart,
- this.actualSelectionEnd);
- this.acceptedAnswer = true;
- }
- }
- }
-
- /**
- * One result of the search consists of a new package.
- * @param packageName char[]
- *
- * 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) {
- // implementation of interface method
- }
-
- /**
- * @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)
- */
- public void acceptConstructor(int modifiers, char[] typeName,
- int parameterCount, char[][] parameterTypes,
- char[][] parameterNames, String path,
- AccessRestriction access) {
-
- // do nothing
- }
-
- private void acceptQualifiedTypes() {
- if(this.acceptedClasses != null){
- this.acceptedAnswer = true;
- for (int i = 0; i < this.acceptedClassesCount; i++) {
- this.noProposal = false;
- this.requestor.acceptType(
- this.acceptedClasses[i][0],
- this.acceptedClasses[i][2],
- this.acceptedClasses[i][1],
- this.acceptedClassesModifiers[i],
- false,
- null,
- this.actualSelectionStart,
- this.actualSelectionEnd);
- }
- this.acceptedClasses = null;
- this.acceptedClassesModifiers = null;
- this.acceptedClassesCount = 0;
- }
- if(this.acceptedInterfaces != null){
- this.acceptedAnswer = true;
- for (int i = 0; i < this.acceptedInterfacesCount; i++) {
- this.noProposal = false;
- this.requestor.acceptType(
- this.acceptedInterfaces[i][0],
- null,
- this.acceptedInterfaces[i][1],
- this.acceptedInterfacesModifiers[i],
- false,
- null,
- this.actualSelectionStart,
- this.actualSelectionEnd);
- }
- this.acceptedInterfaces = null;
- this.acceptedInterfacesModifiers = null;
- this.acceptedInterfacesCount = 0;
- }
- if(this.acceptedAnnotations != null){
- this.acceptedAnswer = true;
- for (int i = 0; i < this.acceptedAnnotationsCount; i++) {
- this.noProposal = false;
- this.requestor.acceptType(
- this.acceptedAnnotations[i][0],
- null,
- this.acceptedAnnotations[i][1],
- this.acceptedAnnotationsModifiers[i],
- false,
- null,
- this.actualSelectionStart,
- this.actualSelectionEnd);
- }
- this.acceptedAnnotations = null;
- this.acceptedAnnotationsModifiers = null;
- this.acceptedAnnotationsCount = 0;
- }
- if(this.acceptedEnums != null){
- this.acceptedAnswer = true;
- for (int i = 0; i < this.acceptedEnumsCount; i++) {
- this.noProposal = false;
- this.requestor.acceptType(
- this.acceptedEnums[i][0],
- null,
- this.acceptedEnums[i][1],
- this.acceptedEnumsModifiers[i],
- false,
- null,
- this.actualSelectionStart,
- this.actualSelectionEnd);
- }
- this.acceptedEnums = null;
- this.acceptedEnumsModifiers = null;
- this.acceptedEnumsCount = 0;
- }
- }
- private boolean checkSelection(
- char[] source,
- int selectionStart,
- int selectionEnd) {
-
- Scanner scanner = new Scanner();
- scanner.setSource(source);
-
- int lastIdentifierStart = -1;
- int lastIdentifierEnd = -1;
- char[] lastIdentifier = null;
- int token;
-
- if(selectionStart > selectionEnd){
-
- // compute end position of the selection
- int end = selectionEnd + 1 == source.length ? selectionEnd : selectionEnd + 1;
- // compute start position of current line
- int currentPosition = selectionStart - 1;
- int nextCharacterPosition = selectionStart;
- char currentCharacter = ' ';
- boolean brokeLoop=false;
- try {
- lineLoop: while(currentPosition > 0){
-
- if(source[currentPosition] == '\\' && source[currentPosition+1] == 'u') {
- int pos = currentPosition + 2;
- int c1 = 0, c2 = 0, c3 = 0, c4 = 0;
- while (source[pos] == 'u') {
- pos++;
- }
- int endOfUnicode = pos + 3;
- if (end < endOfUnicode) {
- if (endOfUnicode < source.length) {
- end = endOfUnicode;
- } else {
- return false; // not enough characters to decode an unicode
- }
- }
-
- if ((c1 = ScannerHelper.getNumericValue(source[pos++])) > 15
- || c1 < 0
- || (c2 = ScannerHelper.getNumericValue(source[pos++])) > 15
- || c2 < 0
- || (c3 = ScannerHelper.getNumericValue(source[pos++])) > 15
- || c3 < 0
- || (c4 = ScannerHelper.getNumericValue(source[pos++])) > 15
- || c4 < 0) {
- return false;
- } else {
- currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4);
- nextCharacterPosition = pos;
- }
- } else {
- currentCharacter = source[currentPosition];
- nextCharacterPosition = currentPosition+1;
- }
-
- switch(currentCharacter) {
- case '\r':
- case '\n':
- case '/':
- case '"':
- case '\'':
- brokeLoop=true;
- break lineLoop;
- }
- currentPosition--;
- }
- } catch (ArrayIndexOutOfBoundsException e) {
- return false;
- }
- if (!brokeLoop)
- nextCharacterPosition=currentPosition;
-
- // compute start and end of the last token
- scanner.resetTo(nextCharacterPosition, end);
- do {
- try {
- token = scanner.getNextToken();
- } catch (InvalidInputException e) {
- return false;
- }
- switch (token) {
- case TerminalTokens.TokenNamethis:
- case TerminalTokens.TokenNamesuper:
- case TerminalTokens.TokenNameIdentifier:
- if (scanner.startPosition <= selectionStart && selectionStart <= scanner.currentPosition) {
- if (scanner.currentPosition == scanner.eofPosition) {
- int temp = scanner.eofPosition;
- scanner.eofPosition = scanner.source.length;
- while(scanner.getNextCharAsJavaIdentifierPart()){/*empty*/}
- scanner.eofPosition = temp;
- }
- lastIdentifierStart = scanner.startPosition;
- lastIdentifierEnd = scanner.currentPosition - 1;
- lastIdentifier = scanner.getCurrentTokenSource();
- }
- break;
- }
- } while (token != TerminalTokens.TokenNameEOF);
- } else {
- scanner.resetTo(selectionStart, selectionEnd);
-
- boolean expectingIdentifier = true;
- try {
- do {
- token = scanner.getNextToken();
-
- switch (token) {
- case TerminalTokens.TokenNamethis :
- case TerminalTokens.TokenNamesuper :
- case TerminalTokens.TokenNameIdentifier :
- if (!expectingIdentifier)
- return false;
- lastIdentifier = scanner.getCurrentTokenSource();
- lastIdentifierStart = scanner.startPosition;
- lastIdentifierEnd = scanner.currentPosition - 1;
- if(lastIdentifierEnd > selectionEnd) {
- lastIdentifierEnd = selectionEnd;
- lastIdentifier = CharOperation.subarray(lastIdentifier, 0,lastIdentifierEnd - lastIdentifierStart + 1);
- }
-
- expectingIdentifier = false;
- break;
- case TerminalTokens.TokenNameDOT :
- if (expectingIdentifier)
- return false;
- expectingIdentifier = true;
- break;
- case TerminalTokens.TokenNameEOF :
- if (expectingIdentifier)
- return false;
- break;
- case TerminalTokens.TokenNameLESS :
- if(!checkTypeArgument(scanner))
- return false;
- break;
- default :
- return false;
- }
- } while (token != TerminalTokens.TokenNameEOF);
- } catch (InvalidInputException e) {
- return false;
- }
- }
- if (lastIdentifierStart >= 0) {
- this.actualSelectionStart = lastIdentifierStart;
- this.actualSelectionEnd = lastIdentifierEnd;
- this.selectedIdentifier = lastIdentifier;
- return true;
- }
- return false;
- }
- private boolean checkTypeArgument(Scanner scanner) throws InvalidInputException {
- int depth = 1;
- int token;
- StringBuffer buffer = new StringBuffer();
- do {
- token = scanner.getNextToken();
-
- switch(token) {
- case TerminalTokens.TokenNameLESS :
- depth++;
- buffer.append(scanner.getCurrentTokenSource());
- break;
- case TerminalTokens.TokenNameGREATER :
- depth--;
- buffer.append(scanner.getCurrentTokenSource());
- break;
- case TerminalTokens.TokenNameRIGHT_SHIFT :
- depth-=2;
- buffer.append(scanner.getCurrentTokenSource());
- break;
- case TerminalTokens.TokenNameUNSIGNED_RIGHT_SHIFT :
- depth-=3;
- buffer.append(scanner.getCurrentTokenSource());
- break;
- case TerminalTokens.TokenNameextends :
- case TerminalTokens.TokenNamesuper :
- buffer.append(' ');
- buffer.append(scanner.getCurrentTokenSource());
- buffer.append(' ');
- break;
- case TerminalTokens.TokenNameCOMMA :
- if(depth == 1) {
- int length = buffer.length();
- char[] typeRef = new char[length];
- buffer.getChars(0, length, typeRef, 0);
- try {
- Signature.createTypeSignature(typeRef, true);
- buffer = new StringBuffer();
- } catch(IllegalArgumentException e) {
- return false;
- }
- }
- break;
- default :
- buffer.append(scanner.getCurrentTokenSource());
- break;
-
- }
- if(depth < 0) {
- return false;
- }
- } while (depth != 0 && token != TerminalTokens.TokenNameEOF);
-
- if(depth == 0) {
- int length = buffer.length() - 1;
- char[] typeRef = new char[length];
- buffer.getChars(0, length, typeRef, 0);
- try {
- Signature.createTypeSignature(typeRef, true);
- return true;
- } catch(IllegalArgumentException e) {
- return false;
- }
- }
-
- return false;
- }
-
- public AssistParser getParser() {
- return this.parser;
- }
-
- /*
- * Returns whether the given binding is a local/anonymous reference binding, or if its declaring class is
- * local.
- */
- private boolean isLocal(ReferenceBinding binding) {
- if (!(binding instanceof SourceTypeBinding)) return false;
- if (binding instanceof LocalTypeBinding) return true;
- if (binding instanceof MemberTypeBinding) {
- return isLocal(((MemberTypeBinding)binding).enclosingType);
- }
- return false;
- }
-
- /**
- * Ask the engine to compute the selection at the specified position
- * of the given compilation unit.
-
- * @param sourceUnit org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit
- * the source of the current compilation unit.
- *
- * @param selectionSourceStart int
- * @param selectionSourceEnd int
- * a range in the source where the selection is.
- */
- public void select(
- ICompilationUnit sourceUnit,
- int selectionSourceStart,
- int selectionSourceEnd) {
-
- char[] source = sourceUnit.getContents();
-
- if(DEBUG) {
- System.out.print("SELECTION IN "); //$NON-NLS-1$
- System.out.print(sourceUnit.getFileName());
- System.out.print(" FROM "); //$NON-NLS-1$
- System.out.print(selectionSourceStart);
- System.out.print(" TO "); //$NON-NLS-1$
- System.out.println(selectionSourceEnd);
- System.out.println("SELECTION - Source :"); //$NON-NLS-1$
- System.out.println(source);
- }
- if (!checkSelection(source, selectionSourceStart, selectionSourceEnd)) {
- return;
- }
- if (DEBUG) {
- System.out.print("SELECTION - Checked : \""); //$NON-NLS-1$
- System.out.print(new String(source, actualSelectionStart, actualSelectionEnd-actualSelectionStart+1));
- System.out.println('"');
- }
- try {
- this.acceptedAnswer = false;
- CompilationResult result = new CompilationResult(sourceUnit, 1, 1, this.compilerOptions.maxProblemsPerUnit);
- CompilationUnitDeclaration parsedUnit =
- this.parser.dietParse(sourceUnit, result, this.actualSelectionStart, this.actualSelectionEnd);
-
- if (parsedUnit != null) {
- if(DEBUG) {
- System.out.println("SELECTION - Diet AST :"); //$NON-NLS-1$
- System.out.println(parsedUnit.toString());
- }
-
- // 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);
- }
- }
- // scan the package & import statements first
- if (parsedUnit.currentPackage instanceof SelectionOnPackageReference) {
- char[][] tokens =
- ((SelectionOnPackageReference) parsedUnit.currentPackage).tokens;
- this.noProposal = false;
- this.requestor.acceptPackage(CharOperation.concatWith(tokens, '.'));
- return;
- }
- ImportReference[] imports = parsedUnit.imports;
- if (imports != null) {
- for (int i = 0, length = imports.length; i < length; i++) {
- ImportReference importReference = imports[i];
- if (importReference instanceof SelectionOnImportReference) {
- char[][] tokens = ((SelectionOnImportReference) importReference).tokens;
- this.noProposal = false;
- this.requestor.acceptPackage(CharOperation.concatWith(tokens, '.'));
- this.nameEnvironment.findTypes(CharOperation.concatWith(tokens, '.'), false, false, IJavaScriptSearchConstants.TYPE, this);
-
- this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/);
- if ((this.unitScope = parsedUnit.scope) != null) {
- int tokenCount = tokens.length;
- char[] lastToken = tokens[tokenCount - 1];
- char[][] qualifierTokens = CharOperation.subarray(tokens, 0, tokenCount - 1);
-
- if(qualifierTokens != null && qualifierTokens.length > 0) {
- Binding binding = this.unitScope.getTypeOrPackage(qualifierTokens);
- if(binding != null && binding instanceof ReferenceBinding) {
- ReferenceBinding ref = (ReferenceBinding) binding;
- selectMemberTypeFromImport(parsedUnit, lastToken, ref);
- }
- }
- }
-
- // accept qualified types only if no unqualified type was accepted
- if(!this.acceptedAnswer) {
- acceptQualifiedTypes();
- if (!this.acceptedAnswer) {
- this.nameEnvironment.findTypes(this.selectedIdentifier, false, false, IJavaScriptSearchConstants.TYPE, this);
- // try with simple type name
- if(!this.acceptedAnswer) {
- acceptQualifiedTypes();
- }
- }
- }
- if(this.noProposal && this.problem != null) {
- this.requestor.acceptError(this.problem);
- }
- return;
- }
- }
- }
- 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 {
- this.lookupEnvironment.completeTypeBindings(parsedUnit, true);
- parsedUnit.scope.faultInTypes();
- ASTNode node = null;
- if (parsedUnit.types != null)
- node = parseBlockStatements(parsedUnit, selectionSourceStart);
- if(DEBUG) {
- System.out.println("SELECTION - AST :"); //$NON-NLS-1$
- System.out.println(parsedUnit.toString());
- }
- parsedUnit.resolve();
- 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);
- }
- }
- }
- }
- }
- // only reaches here if no selection could be derived from the parsed tree
- // thus use the selected source and perform a textual type search
- if (!this.acceptedAnswer) {
- this.nameEnvironment.findTypes(this.selectedIdentifier, false, false, IJavaScriptSearchConstants.TYPE, this);
-
- // accept qualified types only if no unqualified type was accepted
- if(!this.acceptedAnswer) {
- acceptQualifiedTypes();
- }
- }
- if(this.noProposal && this.problem != null) {
- this.requestor.acceptError(this.problem);
- }
- } catch (IndexOutOfBoundsException e) { // work-around internal failure - 1GEMF6D
- if(DEBUG) {
- System.out.println("Exception caught by SelectionEngine:"); //$NON-NLS-1$
- e.printStackTrace(System.out);
- }
- } catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object
- if(DEBUG) {
- System.out.println("Exception caught by SelectionEngine:"); //$NON-NLS-1$
- e.printStackTrace(System.out);
- }
- } finally {
- reset();
- }
- }
-
- private void selectMemberTypeFromImport(CompilationUnitDeclaration parsedUnit, char[] lastToken, ReferenceBinding ref) {
- int fieldLength = lastToken.length;
- ReferenceBinding[] memberTypes = ref.memberTypes();
- next : for (int j = 0; j < memberTypes.length; j++) {
- ReferenceBinding memberType = memberTypes[j];
-
- if (fieldLength > memberType.sourceName.length)
- continue next;
-
- if (!CharOperation.equals(lastToken, memberType.sourceName, true))
- continue next;
-
- this.selectFrom(memberType, parsedUnit, false);
- }
- }
-
- private void selectFrom(Binding binding, CompilationUnitDeclaration parsedUnit, boolean isDeclaration) {
- if (binding instanceof ReferenceBinding) {
- ReferenceBinding typeBinding = (ReferenceBinding) binding;
- if(typeBinding instanceof ProblemReferenceBinding) {
- typeBinding = typeBinding.closestMatch();
- }
- if (typeBinding == null) return;
- if (isLocal(typeBinding) && this.requestor instanceof SelectionRequestor) {
- this.noProposal = false;
- ((SelectionRequestor)this.requestor).acceptLocalType(typeBinding);
- } else {
- this.noProposal = false;
-
- this.requestor.acceptType(
- typeBinding.qualifiedPackageName(),
- typeBinding.getFileName(),
- typeBinding.qualifiedSourceName(),
- typeBinding.modifiers,
- false,
- typeBinding.computeUniqueKey(),
- this.actualSelectionStart,
- this.actualSelectionEnd);
- }
- this.acceptedAnswer = true;
- } else
- if (binding instanceof MethodBinding) {
- MethodBinding methodBinding = (MethodBinding) binding;
- this.noProposal = false;
-
- boolean isValuesOrValueOf = false;
-
- if(!isValuesOrValueOf) {
- TypeBinding[] parameterTypes = methodBinding.original().parameters;
- int length = parameterTypes.length;
- char[][] parameterPackageNames = new char[length][];
- char[][] parameterTypeNames = new char[length][];
- String[] parameterSignatures = new String[length];
- for (int i = 0; i < length; i++) {
- parameterPackageNames[i] = parameterTypes[i].qualifiedPackageName();
- parameterTypeNames[i] = parameterTypes[i].qualifiedSourceName();
- parameterSignatures[i] = new String(getSignature(parameterTypes[i])).replace('/', '.');
- }
-
- char[][] typeParameterNames = new char[length][];
- char[][][] typeParameterBoundNames = new char[length][][];
-
- ReferenceBinding declaringClass = methodBinding.declaringClass;
- if ( ( ( methodBinding instanceof LocalFunctionBinding || isLocal(declaringClass))
- && this.requestor instanceof SelectionRequestor)
- || declaringClass.qualifiedSourceName()==null) {
- ((SelectionRequestor)this.requestor).acceptLocalMethod(methodBinding);
- } else {
- this.requestor.acceptMethod(
- /*declaringClass.qualifiedPackageName()*/ new char[0],
- declaringClass.getFileName(),
- declaringClass.qualifiedSourceName(),
- declaringClass.enclosingType() == null ? null : new String(getSignature(declaringClass.enclosingType())),
- methodBinding.isConstructor()
- ? declaringClass.sourceName()
- : methodBinding.selector,
- parameterPackageNames,
- parameterTypeNames,
- parameterSignatures,
- typeParameterNames,
- typeParameterBoundNames,
- methodBinding.isConstructor(),
- isDeclaration,
- methodBinding.computeUniqueKey(),
- this.actualSelectionStart,
- this.actualSelectionEnd);
- }
- }
- this.acceptedAnswer = true;
- } else
- if (binding instanceof FieldBinding) {
- FieldBinding fieldBinding = (FieldBinding) binding;
- ReferenceBinding declaringClass = fieldBinding.declaringClass;
- if (declaringClass != null) { // arraylength
- this.noProposal = false;
- if (isLocal(declaringClass) && this.requestor instanceof SelectionRequestor) {
- ((SelectionRequestor)this.requestor).acceptLocalField(fieldBinding);
- } else {
- this.requestor.acceptField(
- declaringClass.qualifiedPackageName(),
- declaringClass.getFileName(),
- declaringClass.qualifiedSourceName(),
- fieldBinding.name,
- false,
- fieldBinding.computeUniqueKey(),
- this.actualSelectionStart,
- this.actualSelectionEnd);
- }
- this.acceptedAnswer = true;
- }
- } else
- if (binding instanceof LocalVariableBinding) {
- this.noProposal = false;
- if (this.requestor instanceof SelectionRequestor) {
- ((SelectionRequestor)this.requestor).acceptLocalVariable((LocalVariableBinding)binding);
- this.acceptedAnswer = true;
- } else {
- // open on the type of the variable
- selectFrom(((LocalVariableBinding) binding).type, parsedUnit, false);
- }
- } else
- if (binding instanceof ArrayBinding) {
- selectFrom(((ArrayBinding) binding).leafComponentType, parsedUnit, false);
- // open on the type of the array
- } else
- if (binding instanceof PackageBinding) {
- PackageBinding packageBinding = (PackageBinding) binding;
- this.noProposal = false;
- this.requestor.acceptPackage(packageBinding.readableName());
- this.acceptedAnswer = true;
- } else
- if(binding instanceof BaseTypeBinding) {
- this.acceptedAnswer = true;
- }
- }
-
- /*
- * Checks if a local declaration got selected in this method/initializer/field.
- */
- private void selectLocalDeclaration(ASTNode node) {
- // the selected identifier is not identical to the parser one (equals but not identical),
- // for traversing the parse tree, the parser assist identifier is necessary for identitiy checks
- final char[] assistIdentifier = this.getParser().assistIdentifier();
- if (assistIdentifier == null) return;
-
- class Visitor extends ASTVisitor {
- public boolean visit(ConstructorDeclaration constructorDeclaration, ClassScope scope) {
- if (constructorDeclaration.selector == assistIdentifier){
- if (constructorDeclaration.binding != null) {
- throw new SelectionNodeFound(constructorDeclaration.binding);
- } else {
- if (constructorDeclaration.scope != null) {
- throw new SelectionNodeFound(new MethodBinding(constructorDeclaration.modifiers, constructorDeclaration.selector, null, null, constructorDeclaration.scope.referenceType().binding));
- }
- }
- }
- return true;
- }
- public boolean visit(FieldDeclaration fieldDeclaration, MethodScope scope) {
- if (fieldDeclaration.name == assistIdentifier){
- throw new SelectionNodeFound(fieldDeclaration.binding);
- }
- return true;
- }
- public boolean visit(TypeDeclaration localTypeDeclaration, BlockScope scope) {
- if (localTypeDeclaration.name == assistIdentifier) {
- throw new SelectionNodeFound(localTypeDeclaration.binding);
- }
- return true;
- }
- public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope scope) {
- if (memberTypeDeclaration.name == assistIdentifier) {
- throw new SelectionNodeFound(memberTypeDeclaration.binding);
- }
- return true;
- }
- public boolean visit(MethodDeclaration methodDeclaration, Scope scope) {
- if (methodDeclaration.selector == assistIdentifier){
- if (methodDeclaration.binding != null) {
- throw new SelectionNodeFound(methodDeclaration.binding);
- } else {
- if (methodDeclaration.scope != null) {
- throw new SelectionNodeFound(new MethodBinding(methodDeclaration.modifiers, methodDeclaration.selector, null, null, methodDeclaration.scope.referenceType().binding));
- }
- }
- }
- return true;
- }
- public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) {
- if (typeDeclaration.name == assistIdentifier) {
- throw new SelectionNodeFound(typeDeclaration.binding);
- }
- return true;
- }
- }
-
- if (node instanceof AbstractMethodDeclaration) {
- ((AbstractMethodDeclaration)node).traverse(new Visitor(), (ClassScope)null);
- } else {
- ((FieldDeclaration)node).traverse(new Visitor(), (MethodScope)null);
- }
- }
-
- /**
- * Asks the engine to compute the selection of the given type
- * from the source type.
- *
- * @param sourceType org.eclipse.wst.jsdt.internal.compiler.env.ISourceType
- * a source form of the current type in which code assist is invoked.
- *
- * @param typeName char[]
- * a type name which is to be resolved in the context of a compilation unit.
- * NOTE: the type name is supposed to be correctly reduced (no whitespaces, no unicodes left)
- *
- * @param topLevelTypes SourceTypeElementInfo[]
- * a source form of the top level types of the compilation unit in which code assist is invoked.
-
- * @param searchInEnvironment
- * if <code>true</code> and no selection could be found in context then search type in environment.
- */
- public void selectType(ISourceType sourceType, char[] typeName, SourceTypeElementInfo[] topLevelTypes, boolean searchInEnvironment) {
- try {
- this.acceptedAnswer = false;
-
- // only the type erasure are returned by IType.resolvedType(...)
- if (CharOperation.indexOf('<', typeName) != -1) {
- char[] typeSig = Signature.createCharArrayTypeSignature(typeName, false/*not resolved*/);
- typeName = Signature.toCharArray(typeSig);
- }
-
- // find the outer most type
- ISourceType outerType = sourceType;
- ISourceType parent = sourceType.getEnclosingType();
- while (parent != null) {
- outerType = parent;
- parent = parent.getEnclosingType();
- }
- // compute parse tree for this most outer type
- CompilationResult result = new CompilationResult(outerType.getFileName(), outerType.getPackageName(), 1, 1, this.compilerOptions.maxProblemsPerUnit);
- if (!(sourceType instanceof SourceTypeElementInfo)) return;
- SourceType typeHandle = (SourceType) ((SourceTypeElementInfo)sourceType).getHandle();
- int flags = SourceTypeConverter.FIELD_AND_METHOD | SourceTypeConverter.MEMBER_TYPE;
- if (typeHandle.isAnonymous() || typeHandle.isLocal())
- flags |= SourceTypeConverter.LOCAL_TYPE;
- CompilationUnitDeclaration parsedUnit =
- SourceTypeConverter.buildCompilationUnit(
- topLevelTypes,
- flags,
- this.parser.problemReporter(),
- result);
-
- if (parsedUnit != null && parsedUnit.types != null) {
- if(DEBUG) {
- System.out.println("SELECTION - Diet AST :"); //$NON-NLS-1$
- System.out.println(parsedUnit.toString());
- }
- // find the type declaration that corresponds to the original source type
- TypeDeclaration typeDecl = new ASTNodeFinder(parsedUnit).findType(typeHandle);
-
- if (typeDecl != null) {
-
- // add fake field with the type we're looking for
- // note: since we didn't ask for fields above, there is no field defined yet
- FieldDeclaration field = new FieldDeclaration();
- int dot;
- if ((dot = CharOperation.lastIndexOf('.', typeName)) == -1) {
- this.selectedIdentifier = typeName;
- field.type = new SelectionOnSingleTypeReference(typeName, -1);
- // position not used
- } else {
- char[][] previousIdentifiers = CharOperation.splitOn('.', typeName, 0, dot);
- char[] selectionIdentifier =
- CharOperation.subarray(typeName, dot + 1, typeName.length);
- this.selectedIdentifier = selectionIdentifier;
- field.type =
- new SelectionOnQualifiedTypeReference(
- previousIdentifiers,
- selectionIdentifier,
- new long[previousIdentifiers.length + 1]);
- }
- field.name = "<fakeField>".toCharArray(); //$NON-NLS-1$
- typeDecl.fields = new FieldDeclaration[] { field };
-
- // build bindings
- this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/);
- if ((this.unitScope = parsedUnit.scope) != null) {
- try {
- // build fields
- // note: this builds fields only in the parsed unit (the buildFieldsAndMethods flag is not passed along)
- this.lookupEnvironment.completeTypeBindings(parsedUnit, true);
-
- // resolve
- parsedUnit.scope.faultInTypes();
- parsedUnit.resolve();
- } 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);
- }
- }
- }
- }
- }
- // only reaches here if no selection could be derived from the parsed tree
- // thus use the selected source and perform a textual type search
- if (!this.acceptedAnswer && searchInEnvironment) {
- if (this.selectedIdentifier != null) {
- this.nameEnvironment.findTypes(typeName, false, false, IJavaScriptSearchConstants.TYPE, this);
-
- // accept qualified types only if no unqualified type was accepted
- if(!this.acceptedAnswer) {
- acceptQualifiedTypes();
- }
- }
- }
- if(this.noProposal && this.problem != null) {
- this.requestor.acceptError(this.problem);
- }
- } catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object
- } finally {
- reset();
- }
- }
-
- // Check if a declaration got selected in this unit
- private boolean selectDeclaration(CompilationUnitDeclaration compilationUnit){
-
- // the selected identifier is not identical to the parser one (equals but not identical),
- // for traversing the parse tree, the parser assist identifier is necessary for identity checks
- char[] assistIdentifier = this.getParser().assistIdentifier();
- if (assistIdentifier == null) return false;
-
- ImportReference currentPackage = compilationUnit.currentPackage;
- char[] packageName = currentPackage == null ? CharOperation.NO_CHAR : CharOperation.concatWith(currentPackage.tokens, '.');
- // iterate over the types
- TypeDeclaration[] types = compilationUnit.types;
- for (int i = 0, length = types == null ? 0 : types.length; i < length; i++){
- if(selectDeclaration(types[i], assistIdentifier, packageName))
- return true;
- }
- ProgramElement[] statements = compilationUnit.statements;
- for (int i = 0, length = statements == null ? 0 : statements.length; i < length; i++){
- if (statements[i] instanceof FieldDeclaration)
- {
- FieldDeclaration field = (FieldDeclaration)statements[i];
-
- if (field.name == assistIdentifier){
- char[] qualifiedSourceName = null;
-
- this.requestor.acceptField(
- packageName,
- compilationUnit.getFileName(),
- qualifiedSourceName,
- field.name,
- true,
- field.binding != null ? field.binding.computeUniqueKey() : null,
- this.actualSelectionStart,
- this.actualSelectionEnd);
-
- this.noProposal = false;
- return true;
- }
- }
- else if (statements[i] instanceof AbstractMethodDeclaration)
- {
- AbstractMethodDeclaration method = (AbstractMethodDeclaration)statements[i];
-
- if (method.selector == assistIdentifier){
- char[] qualifiedSourceName = compilationUnit.getFileName();
-
- this.requestor.acceptMethod(
- packageName,
- compilationUnit.getFileName(),
- qualifiedSourceName,
- null, // SelectionRequestor does not need of declaring type signature for method declaration
- method.selector,
- 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,
- this.actualSelectionStart,
- this.actualSelectionEnd);
-
- this.noProposal = false;
- return true;
- }
-
- }
-
- }
- return false;
- }
-
- // Check if a declaration got selected in this type
- private boolean selectDeclaration(TypeDeclaration typeDeclaration, char[] assistIdentifier, char[] packageName){
-
- if (typeDeclaration.name == assistIdentifier){
- char[] qualifiedSourceName = null;
-
- TypeDeclaration enclosingType = typeDeclaration;
- while(enclosingType != null) {
- qualifiedSourceName = CharOperation.concat(enclosingType.name, qualifiedSourceName, '.');
- enclosingType = enclosingType.enclosingType;
- }
- char[] uniqueKey = typeDeclaration.binding != null ? typeDeclaration.binding.computeUniqueKey() : null;
-
- this.requestor.acceptType(
- packageName,
- null,
- qualifiedSourceName,
- typeDeclaration.modifiers,
- true,
- uniqueKey,
- this.actualSelectionStart,
- this.actualSelectionEnd);
-
- this.noProposal = false;
- return true;
- }
- TypeDeclaration[] memberTypes = typeDeclaration.memberTypes;
- for (int i = 0, length = memberTypes == null ? 0 : memberTypes.length; i < length; i++){
- if(selectDeclaration(memberTypes[i], assistIdentifier, packageName))
- return true;
- }
- FieldDeclaration[] fields = typeDeclaration.fields;
- for (int i = 0, length = fields == null ? 0 : fields.length; i < length; i++){
- if (fields[i].name == assistIdentifier){
- char[] qualifiedSourceName = null;
-
- TypeDeclaration enclosingType = typeDeclaration;
- while(enclosingType != null) {
- qualifiedSourceName = CharOperation.concat(enclosingType.name, qualifiedSourceName, '.');
- enclosingType = enclosingType.enclosingType;
- }
- FieldDeclaration field = fields[i];
- this.requestor.acceptField(
- packageName,
- null,
- qualifiedSourceName,
- field.name,
- true,
- field.binding != null ? field.binding.computeUniqueKey() : null,
- this.actualSelectionStart,
- this.actualSelectionEnd);
-
- this.noProposal = false;
- return true;
- }
- }
- AbstractMethodDeclaration[] methods = typeDeclaration.methods;
- for (int i = 0, length = methods == null ? 0 : methods.length; i < length; i++){
- AbstractMethodDeclaration method = methods[i];
-
- if (method.selector == assistIdentifier){
- char[] qualifiedSourceName = null;
-
- TypeDeclaration enclosingType = typeDeclaration;
- while(enclosingType != null) {
- qualifiedSourceName = CharOperation.concat(enclosingType.name, qualifiedSourceName, '.');
- enclosingType = enclosingType.enclosingType;
- }
-
- this.requestor.acceptMethod(
- packageName,
- null,
- qualifiedSourceName,
- null, // SelectionRequestor does not need of declaring type signature for method declaration
- method.selector,
- 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, // SelectionRequestor does not need of type parameters name for method declaration
- null, // SelectionRequestor does not need of type parameters bounds for method declaration
- method.isConstructor(),
- true,
- method.binding != null ? method.binding.computeUniqueKey() : null,
- this.actualSelectionStart,
- this.actualSelectionEnd);
-
- this.noProposal = false;
- return true;
- }
-
- }
-
- return false;
- }
- public CompilationUnitDeclaration doParse(ICompilationUnit unit, AccessRestriction accessRestriction) {
- CompilationResult unitResult =
- new CompilationResult(unit, 1, 1, this.compilerOptions.maxProblemsPerUnit);
- try {
- Parser localParser = new Parser(this.parser.problemReporter(), this.compilerOptions.parseLiteralExpressionsAsConstants);
-
- CompilationUnitDeclaration parsedUnit = localParser.parse(unit, unitResult);
- 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
-// }
- }
-
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/ThrownExceptionFinder.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/ThrownExceptionFinder.java
deleted file mode 100644
index 28f2bbd0..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/ThrownExceptionFinder.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist;
-
-import java.util.Stack;
-
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-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.Block;
-import org.eclipse.wst.jsdt.internal.compiler.ast.MessageSend;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ThrowStatement;
-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.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.ReferenceBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-import org.eclipse.wst.jsdt.internal.compiler.util.SimpleSet;
-
-public class ThrownExceptionFinder extends ASTVisitor {
-
- private SimpleSet thrownExceptions;
- private Stack exceptionsStack;
-
- public ReferenceBinding[] find(TryStatement tryStatement, BlockScope scope) {
- this.thrownExceptions = new SimpleSet();
- this.exceptionsStack = new Stack();
- tryStatement.traverse(this, scope);
- removeCaughtExceptions(tryStatement);
-
- ReferenceBinding[] result = new ReferenceBinding[this.thrownExceptions.elementSize];
- this.thrownExceptions.asArray(result);
- return result;
- }
-
- private void acceptException(ReferenceBinding binding) {
- if (binding != null && binding.isValidBinding()) {
- this.thrownExceptions.add(binding);
- }
- }
-
- public void endVisit(MessageSend messageSend, BlockScope scope) {
- super.endVisit(messageSend, scope);
- }
-
- public void endVisit(AllocationExpression allocationExpression, BlockScope scope) {
- super.endVisit(allocationExpression, scope);
- }
-
- public void endVisit(ThrowStatement throwStatement, BlockScope scope) {
- this.acceptException((ReferenceBinding)throwStatement.exception.resolvedType);
- super.endVisit(throwStatement, scope);
- }
-
- public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) {
- return this.visitType(typeDeclaration);
- }
-
- public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope scope) {
- return this.visitType(memberTypeDeclaration);
- }
-
- public boolean visit(TypeDeclaration localTypeDeclaration, BlockScope scope) {
- return this.visitType(localTypeDeclaration);
- }
-
- private boolean visitType(TypeDeclaration typeDeclaration) {
- return false;
- }
-
- public boolean visit(TryStatement tryStatement, BlockScope scope) {
- this.exceptionsStack.push(this.thrownExceptions);
- SimpleSet exceptionSet = new SimpleSet();
- this.thrownExceptions = exceptionSet;
- tryStatement.tryBlock.traverse(this, scope);
-
- this.removeCaughtExceptions(tryStatement);
-
- this.thrownExceptions = (SimpleSet)this.exceptionsStack.pop();
-
- Object[] values = exceptionSet.values;
- for (int i = 0; i < values.length; i++) {
- if (values[i] != null) {
- this.thrownExceptions.add(values[i]);
- }
- }
-
- Block[] catchBlocks = tryStatement.catchBlocks;
- int length = catchBlocks == null ? 0 : catchBlocks.length;
- for (int i = 0; i < length; i++) {
- catchBlocks[i].traverse(this, scope);
- }
- return false;
- }
-
- private void removeCaughtExceptions(TryStatement tryStatement) {
- Argument[] catchArguments = tryStatement.catchArguments;
- int length = catchArguments == null ? 0 : catchArguments.length;
- for (int i = 0; i < length; i++) {
- TypeBinding exception = catchArguments[i].type.resolvedType;
- if (exception != null && exception.isValidBinding()) {
- this.removeCaughtException((ReferenceBinding)exception);
-
- }
- }
- }
-
- private void removeCaughtException(ReferenceBinding caughtException) {
- Object[] exceptions = this.thrownExceptions.values;
- for (int i = 0; i < exceptions.length; i++) {
- ReferenceBinding exception = (ReferenceBinding)exceptions[i];
- if (exception != null) {
- if (exception == caughtException || caughtException.isSuperclassOf(exception)) {
- this.thrownExceptions.remove(exception);
- }
- }
- }
- }
-}
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
deleted file mode 100644
index c7c3744f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/UnresolvedReferenceNameFinder.java
+++ /dev/null
@@ -1,552 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionParser;
-import org.eclipse.wst.jsdt.internal.codeassist.complete.CompletionScanner;
-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.AbstractMethodDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Argument;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Block;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ConstructorDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Initializer;
-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.Statement;
-import org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration;
-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.MethodScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Scope;
-import org.eclipse.wst.jsdt.internal.compiler.util.SimpleSetOfCharArray;
-import org.eclipse.wst.jsdt.internal.compiler.util.Util;
-
-public class UnresolvedReferenceNameFinder extends ASTVisitor {
- private static final int MAX_LINE_COUNT = 100;
- private static final int FAKE_BLOCKS_COUNT = 20;
-
- public static interface UnresolvedReferenceNameRequestor {
- public void acceptName(char[] name);
- }
-
- private UnresolvedReferenceNameRequestor requestor;
-
- private CompletionEngine completionEngine;
- private CompletionParser parser;
- private CompletionScanner completionScanner;
-
- private int parentsPtr;
- private ASTNode[] parents;
-
- private int potentialVariableNamesPtr;
- private char[][] potentialVariableNames;
- private int[] potentialVariableNameStarts;
-
- private SimpleSetOfCharArray acceptedNames = new SimpleSetOfCharArray();
-
- public UnresolvedReferenceNameFinder(CompletionEngine completionEngine) {
- this.completionEngine = completionEngine;
- this.parser = completionEngine.parser;
- this.completionScanner = (CompletionScanner) parser.scanner;
- }
-
- private void acceptName(char[] name) {
- // the null check is added to fix bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=166570
- if (name == null) return;
-
- if (!CharOperation.prefixEquals(this.completionEngine.completionToken, name, false /* ignore case */)
- && !(this.completionEngine.options.camelCaseMatch && CharOperation.camelCaseMatch(this.completionEngine.completionToken, name))) return;
-
- if (acceptedNames.includes(name)) return;
-
- this.acceptedNames.add(name);
-
- // accept result
- this.requestor.acceptName(name);
- }
-
- public void find(
- char[] startWith,
- Initializer initializer,
- ClassScope scope,
- int from,
- char[][] discouragedNames,
- UnresolvedReferenceNameRequestor nameRequestor) {
- MethodDeclaration fakeMethod =
- this.findAfter(startWith, scope, from, initializer.bodyEnd, MAX_LINE_COUNT, false, discouragedNames, nameRequestor);
- if (fakeMethod != null) fakeMethod.traverse(this, scope);
- }
-
- public void find(
- char[] startWith,
- AbstractMethodDeclaration methodDeclaration,
- int from,
- 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());
- }
-
- public void findAfter(
- char[] startWith,
- Scope scope,
- ClassScope classScope,
- int from,
- int to,
- char[][] discouragedNames,
- UnresolvedReferenceNameRequestor nameRequestor) {
- MethodDeclaration fakeMethod =
- this.findAfter(startWith, scope, from, to, MAX_LINE_COUNT / 2, true, discouragedNames, nameRequestor);
- if (fakeMethod != null) fakeMethod.traverse(this, classScope);
- }
-
- private MethodDeclaration findAfter(
- char[] startWith,
- Scope s,
- int from,
- int to,
- int maxLineCount,
- boolean outsideEnclosingBlock,
- char[][] discouragedNames,
- UnresolvedReferenceNameRequestor nameRequestor) {
- this.requestor = nameRequestor;
-
- // reinitialize completion scanner to be usable as a normal scanner
- this.completionScanner.cursorLocation = 0;
-
- if (!outsideEnclosingBlock) {
- // compute location of the end of the current block
- this.completionScanner.resetTo(from + 1, to);
- this.completionScanner.jumpOverBlock();
-
- to = this.completionScanner.startPosition - 1;
- }
-
- int maxEnd =
- this.completionScanner.getLineEnd(
- Util.getLineNumber(from, this.completionScanner.lineEnds, 0, this.completionScanner.linePtr) + maxLineCount);
-
- int end;
- if (maxEnd < 0) {
- end = to;
- } else {
- end = maxEnd < to ? maxEnd : to;
- }
-
- this.parser.startRecordingIdentifiers(from, end);
-
- MethodDeclaration fakeMethod = this.parser.parseSomeStatements(
- from,
- end,
- outsideEnclosingBlock ? FAKE_BLOCKS_COUNT : 0,
- s.compilationUnitScope().referenceContext);
-
- this.parser.stopRecordingIdentifiers();
-
- if(!this.initPotentialNamesTables(discouragedNames)) return null;
-
- this.parentsPtr = -1;
- this.parents = new ASTNode[10];
-
- return fakeMethod;
- }
-
- public void findBefore(
- char[] startWith,
- Scope scope,
- ClassScope classScope,
- int from,
- int recordTo,
- int parseTo,
- char[][] discouragedNames,
- UnresolvedReferenceNameRequestor nameRequestor) {
- MethodDeclaration fakeMethod =
- this.findBefore(startWith, scope, from, recordTo, parseTo, MAX_LINE_COUNT / 2, discouragedNames, nameRequestor);
- if (fakeMethod != null) fakeMethod.traverse(this, classScope);
- }
-
- private MethodDeclaration findBefore(
- char[] startWith,
- Scope s,
- int from,
- int recordTo,
- int parseTo,
- int maxLineCount,
- char[][] discouragedNames,
- UnresolvedReferenceNameRequestor nameRequestor) {
- this.requestor = nameRequestor;
-
- // reinitialize completion scanner to be usable as a normal scanner
- this.completionScanner.cursorLocation = 0;
-
- int minStart =
- this.completionScanner.getLineStart(
- Util.getLineNumber(recordTo, this.completionScanner.lineEnds, 0, this.completionScanner.linePtr) - maxLineCount);
-
- int start;
- int fakeBlocksCount;
- if (minStart <= from) {
- start = from;
- fakeBlocksCount = 0;
- } else {
- start = minStart;
- fakeBlocksCount = FAKE_BLOCKS_COUNT;
- }
-
- this.parser.startRecordingIdentifiers(start, recordTo);
-
- MethodDeclaration fakeMethod = this.parser.parseSomeStatements(
- start,
- parseTo,
- fakeBlocksCount,
- s.compilationUnitScope().referenceContext);
-
- this.parser.stopRecordingIdentifiers();
-
- if(!this.initPotentialNamesTables(discouragedNames)) return null;
-
- this.parentsPtr = -1;
- this.parents = new ASTNode[10];
-
- return fakeMethod;
- }
-
- private boolean initPotentialNamesTables(char[][] discouragedNames) {
- char[][] pvns = this.parser.potentialVariableNames;
- int[] pvnss = this.parser.potentialVariableNameStarts;
- int pvnsPtr = this.parser.potentialVariableNamesPtr;
-
- if (pvnsPtr < 0) return false; // there is no potential names
-
- // remove null and discouragedNames
- int discouragedNamesCount = discouragedNames == null ? 0 : discouragedNames.length;
- int j = -1;
- next : for (int i = 0; i <= pvnsPtr; i++) {
- char[] temp = pvns[i];
-
- if (temp == null) continue next;
-
- for (int k = 0; k < discouragedNamesCount; k++) {
- if (CharOperation.equals(temp, discouragedNames[k], false)) {
- continue next;
- }
- }
-
- pvns[i] = null;
- pvns[++j] = temp;
- pvnss[j] = pvnss[i];
- }
- pvnsPtr = j;
-
- if (pvnsPtr < 0) return false; // there is no potential names
-
- this.potentialVariableNames = pvns;
- this.potentialVariableNameStarts = pvnss;
- this.potentialVariableNamesPtr = pvnsPtr;
-
- return true;
- }
-
- private void popParent() {
- this.parentsPtr--;
- }
- private void pushParent(ASTNode parent) {
- int length = this.parents.length;
- if (this.parentsPtr >= length - 1) {
- System.arraycopy(this.parents, 0, this.parents = new ASTNode[length * 2], 0, length);
- }
- this.parents[++this.parentsPtr] = parent;
- }
-
- private ASTNode getEnclosingDeclaration() {
- int i = this.parentsPtr;
- while (i > -1) {
- ASTNode parent = parents[i];
- if (parent instanceof AbstractMethodDeclaration) {
- return parent;
- } else if (parent instanceof Initializer) {
- return parent;
- } else if (parent instanceof FieldDeclaration) {
- return parent;
- } else if (parent instanceof TypeDeclaration) {
- return parent;
- }
- i--;
- }
- return null;
- }
-
- public boolean visit(Block block, BlockScope blockScope) {
- ASTNode enclosingDeclaration = getEnclosingDeclaration();
- removeLocals(block.statements, enclosingDeclaration.sourceStart, block.sourceEnd);
- pushParent(block);
- return true;
- }
-
- public boolean visit(ConstructorDeclaration constructorDeclaration, ClassScope classScope) {
- if (((constructorDeclaration.bits & ASTNode.IsDefaultConstructor) == 0) && !constructorDeclaration.isClinit()) {
- removeLocals(
- constructorDeclaration.arguments,
- constructorDeclaration.declarationSourceStart,
- constructorDeclaration.declarationSourceEnd);
- removeLocals(
- constructorDeclaration.statements,
- constructorDeclaration.declarationSourceStart,
- constructorDeclaration.declarationSourceEnd);
- }
- pushParent(constructorDeclaration);
- return true;
- }
-
- public boolean visit(FieldDeclaration fieldDeclaration, MethodScope methodScope) {
- pushParent(fieldDeclaration);
- return true;
- }
-
- public boolean visit(Initializer initializer, MethodScope methodScope) {
- pushParent(initializer);
- return true;
- }
-
- public boolean visit(MethodDeclaration methodDeclaration, Scope classScope) {
- removeLocals(
- methodDeclaration.arguments,
- methodDeclaration.declarationSourceStart,
- methodDeclaration.declarationSourceEnd);
- removeLocals(
- methodDeclaration.statements,
- methodDeclaration.declarationSourceStart,
- methodDeclaration.declarationSourceEnd);
- pushParent(methodDeclaration);
- return true;
- }
-
- public boolean visit(TypeDeclaration localTypeDeclaration, BlockScope blockScope) {
- removeFields(localTypeDeclaration);
- pushParent(localTypeDeclaration);
- return true;
- }
-
- public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope classScope) {
- removeFields(memberTypeDeclaration);
- pushParent(memberTypeDeclaration);
- return true;
- }
-
- public void endVisit(Block block, BlockScope blockScope) {
- popParent();
- }
-
- public void endVisit(Argument argument, BlockScope blockScope) {
- endVisitRemoved(argument.declarationSourceStart, argument.sourceEnd);
- }
-
- public void endVisit(Argument argument, ClassScope classScope) {
- endVisitRemoved(argument.declarationSourceStart, argument.sourceEnd);
- }
-
- public void endVisit(ConstructorDeclaration constructorDeclaration, ClassScope classScope) {
- if (((constructorDeclaration.bits & ASTNode.IsDefaultConstructor) == 0) && !constructorDeclaration.isClinit()) {
- endVisitPreserved(constructorDeclaration.bodyStart, constructorDeclaration.bodyEnd);
- }
- popParent();
- }
-
- public void endVisit(FieldDeclaration fieldDeclaration, MethodScope methodScope) {
- endVisitRemoved(fieldDeclaration.declarationSourceStart, fieldDeclaration.sourceEnd);
- endVisitPreserved(fieldDeclaration.sourceEnd, fieldDeclaration.declarationEnd);
- popParent();
- }
-
- public void endVisit(Initializer initializer, MethodScope methodScope) {
- endVisitPreserved(initializer.bodyStart, initializer.bodyEnd);
- popParent();
- }
-
- public void endVisit(LocalDeclaration localDeclaration, BlockScope blockScope) {
- endVisitRemoved(localDeclaration.declarationSourceStart, localDeclaration.sourceEnd);
- }
-
- public void endVisit(MethodDeclaration methodDeclaration, Scope classScope) {
- endVisitPreserved(
- methodDeclaration.bodyStart,
- methodDeclaration.bodyEnd);
- popParent();
- }
-
- public void endVisit(TypeDeclaration typeDeclaration, BlockScope blockScope) {
- endVisitRemoved(typeDeclaration.sourceStart, typeDeclaration.declarationSourceEnd);
- popParent();
- }
-
- public void endVisit(TypeDeclaration typeDeclaration, ClassScope classScope) {
- endVisitRemoved(typeDeclaration.sourceStart, typeDeclaration.declarationSourceEnd);
- popParent();
- }
-
- private int indexOfFisrtNameAfter(int position) {
- int left = 0;
- int right = this.potentialVariableNamesPtr;
-
- next : while (true) {
- if (right < left) return -1;
-
- int mid = left + (right - left) / 2;
- int midPosition = this.potentialVariableNameStarts[mid];
- if (midPosition < 0) {
- int nextMid = indexOfNextName(mid);
- if (nextMid < 0 || right < nextMid) { // no next index or next index is after 'right'
- right = mid - 1;
- continue next;
- }
- mid = nextMid;
- midPosition = this.potentialVariableNameStarts[nextMid];
-
- if (mid == right) { // mid and right are at the same index, we must move 'left'
- int leftPosition = this.potentialVariableNameStarts[left];
- if (leftPosition < 0 || leftPosition < position) { // 'left' is empty or 'left' is before the position
- int nextLeft = indexOfNextName(left);
- if (nextLeft < 0) return - 1;
-
- left = nextLeft;
- continue next;
- }
-
- return left;
- }
- }
-
- if (left != right) {
- if (midPosition < position) {
- left = mid + 1;
- } else {
- right = mid;
- }
- } else {
- if (midPosition < position) {
- return -1;
- }
- return mid;
- }
- }
- }
-
- private int indexOfNextName(int index) {
- int nextIndex = index + 1;
- while (nextIndex <= this.potentialVariableNamesPtr &&
- this.potentialVariableNames[nextIndex] == null) {
- int jumpIndex = -this.potentialVariableNameStarts[nextIndex];
- if (jumpIndex > 0) {
- nextIndex = jumpIndex;
- } else {
- nextIndex++;
- }
- }
-
- if (this.potentialVariableNamesPtr < nextIndex) {
- if (index < this.potentialVariableNamesPtr) {
- this.potentialVariableNamesPtr = index;
- }
- return -1;
- }
- if (index + 1 < nextIndex) {
- this.potentialVariableNameStarts[index + 1] = -nextIndex;
- }
- return nextIndex;
- }
-
- private void removeNameAt(int index) {
- this.potentialVariableNames[index] = null;
- int nextIndex = indexOfNextName(index);
- if (nextIndex != -1) {
- this.potentialVariableNameStarts[index] = -nextIndex;
- } else {
- this.potentialVariableNamesPtr = index - 1;
- }
- }
-
- private void endVisitPreserved(int start, int end) {
- int i = indexOfFisrtNameAfter(start);
- done : while (i != -1) {
- int nameStart = this.potentialVariableNameStarts[i];
- if (start < nameStart && nameStart < end) {
- this.acceptName(this.potentialVariableNames[i]);
- this.removeNameAt(i);
- }
-
- if (end < nameStart) break done;
- i = indexOfNextName(i);
- }
- }
-
- private void endVisitRemoved(int start, int end) {
- int i = indexOfFisrtNameAfter(start);
- done : while (i != -1) {
- int nameStart = this.potentialVariableNameStarts[i];
- if (start < nameStart && nameStart < end) {
- this.removeNameAt(i);
- }
-
- if (end < nameStart) break done;
- i = indexOfNextName(i);
- }
- }
-
- private void removeLocals(Statement[] statements, int start, int end) {
- if (statements != null) {
- for (int i = 0; i < statements.length; i++) {
- if (statements[i] instanceof LocalDeclaration) {
- LocalDeclaration localDeclaration = (LocalDeclaration) statements[i];
- int j = indexOfFisrtNameAfter(start);
- done : while (j != -1) {
- int nameStart = this.potentialVariableNameStarts[j];
- if (start <= nameStart && nameStart <= end) {
- if (CharOperation.equals(this.potentialVariableNames[j], localDeclaration.name, false)) {
- this.removeNameAt(j);
- }
- }
-
- if (end < nameStart) break done;
- j = indexOfNextName(j);
- }
- }
- }
-
- }
- }
-
- private void removeFields(TypeDeclaration typeDeclaration) {
- int start = typeDeclaration.declarationSourceStart;
- int end = typeDeclaration.declarationSourceEnd;
-
- FieldDeclaration[] fieldDeclarations = typeDeclaration.fields;
- if (fieldDeclarations != null) {
- for (int i = 0; i < fieldDeclarations.length; i++) {
- int j = indexOfFisrtNameAfter(start);
- done : while (j != -1) {
- int nameStart = this.potentialVariableNameStarts[j];
- if (start <= nameStart && nameStart <= end) {
- if (CharOperation.equals(this.potentialVariableNames[j], fieldDeclarations[i].name, false)) {
- this.removeNameAt(j);
- }
- }
-
- if (end < nameStart) break done;
- j = indexOfNextName(j);
- }
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionJavadoc.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionJavadoc.java
deleted file mode 100644
index 0acd1418..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionJavadoc.java
+++ /dev/null
@@ -1,221 +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.codeassist.complete;
-
-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.Expression;
-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.lookup.Binding;
-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.MethodScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Scope;
-
-/**
- * Node representing a Javadoc comment including code selection.
- */
-public class CompletionJavadoc extends Javadoc {
-
- Expression completionNode;
-
- public CompletionJavadoc(int sourceStart, int sourceEnd) {
- super(sourceStart, sourceEnd);
- }
-
- /**
- * @return Returns the completionNode.
- */
- public Expression getCompletionNode() {
- return this.completionNode;
- }
-
- /**
- * Resolve selected node if not null and throw exception to let clients know
- * that it has been found.
- *
- * @throws CompletionNodeFound
- */
- private void internalResolve(Scope scope) {
- if (this.completionNode != null) {
- if (this.completionNode instanceof CompletionOnJavadocTag) {
- ((CompletionOnJavadocTag)this.completionNode).filterPossibleTags(scope);
- } else {
- boolean resolve = true;
- if (this.completionNode instanceof CompletionOnJavadocParamNameReference) {
- resolve = ((CompletionOnJavadocParamNameReference)this.completionNode).token != null;
- }
- if (resolve) {
- switch (scope.kind) {
- case Scope.CLASS_SCOPE:
- this.completionNode.resolveType((ClassScope)scope);
- break;
- case Scope.METHOD_SCOPE:
- this.completionNode.resolveType((MethodScope) scope);
- break;
- }
- }
- if (this.completionNode instanceof CompletionOnJavadocParamNameReference) {
- CompletionOnJavadocParamNameReference paramNameReference = (CompletionOnJavadocParamNameReference) this.completionNode;
- if (scope.kind == Scope.METHOD_SCOPE) {
- paramNameReference.missingParams = missingParamTags(paramNameReference.binding, (MethodScope)scope);
- }
- }
- }
- Binding qualifiedBinding = null;
- if (this.completionNode instanceof CompletionOnJavadocQualifiedTypeReference) {
- CompletionOnJavadocQualifiedTypeReference typeRef = (CompletionOnJavadocQualifiedTypeReference) this.completionNode;
- if (typeRef.packageBinding == null) {
- qualifiedBinding = typeRef.resolvedType;
- } else {
- qualifiedBinding = typeRef.packageBinding;
- }
- } else if (this.completionNode instanceof CompletionOnJavadocMessageSend) {
- CompletionOnJavadocMessageSend msg = (CompletionOnJavadocMessageSend) this.completionNode;
- if (msg.receiver!=null && !msg.receiver.isThis()) qualifiedBinding = msg.receiver.resolvedType;
- } else if (this.completionNode instanceof CompletionOnJavadocAllocationExpression) {
- CompletionOnJavadocAllocationExpression alloc = (CompletionOnJavadocAllocationExpression) this.completionNode;
- qualifiedBinding = alloc.type.resolvedType;
- }
- throw new CompletionNodeFound(this.completionNode, qualifiedBinding, scope);
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode#print(int, java.lang.StringBuffer)
- */
- public StringBuffer print(int indent, StringBuffer output) {
- printIndent(indent, output).append("/**\n"); //$NON-NLS-1$
- boolean nodePrinted = false;
- if (this.paramReferences != null) {
- for (int i = 0, length = this.paramReferences.length; i < length; i++) {
- printIndent(indent, output).append(" * @param "); //$NON-NLS-1$
- this.paramReferences[i].print(indent, output).append('\n');
- if (!nodePrinted && this.completionNode != null) {
- nodePrinted = this.completionNode == this.paramReferences[i];
- }
- }
- }
- if (this.returnStatement != null) {
- printIndent(indent, output).append(" * @"); //$NON-NLS-1$
- this.returnStatement.print(indent, output).append('\n');
- }
- if (this.exceptionReferences != null) {
- for (int i = 0, length = this.exceptionReferences.length; i < length; i++) {
- printIndent(indent, output).append(" * @throws "); //$NON-NLS-1$
- this.exceptionReferences[i].print(indent, output).append('\n');
- if (!nodePrinted && this.completionNode != null) {
- nodePrinted = this.completionNode == this.exceptionReferences[i];
- }
- }
- }
- if (this.seeReferences != null) {
- for (int i = 0, length = this.seeReferences.length; i < length; i++) {
- printIndent(indent, output).append(" * @see "); //$NON-NLS-1$
- this.seeReferences[i].print(indent, output).append('\n');
- if (!nodePrinted && this.completionNode != null) {
- nodePrinted = this.completionNode == this.seeReferences[i];
- }
- }
- }
- if (!nodePrinted && this.completionNode != null) {
- printIndent(indent, output).append(" * "); //$NON-NLS-1$
- this.completionNode.print(indent, output).append('\n');
- }
- printIndent(indent, output).append(" */\n"); //$NON-NLS-1$
- return output;
- }
-
- /**
- * Resolve completion node if not null and throw exception to let clients know
- * that it has been found.
- *
- * @throws CompletionNodeFound
- */
- public void resolve(ClassScope scope) {
- super.resolve(scope);
- internalResolve(scope);
- }
-
- /**
- * Resolve completion node if not null and throw exception to let clients know
- * that it has been found.
- *
- * @throws CompletionNodeFound
- */
- public void resolve(CompilationUnitScope scope) {
- internalResolve(scope);
- }
-
- /**
- * Resolve completion node if not null and throw exception to let clients know
- * that it has been found.
- *
- * @throws CompletionNodeFound
- */
- public void resolve(MethodScope scope) {
- super.resolve(scope);
- internalResolve(scope);
- }
-
- /*
- * Look for missing method @param tags
- */
- private char[][] missingParamTags(Binding paramNameRefBinding, MethodScope methScope) {
-
- // Verify if there's some possible param tag
- AbstractMethodDeclaration md = methScope.referenceMethod();
- int paramTagsSize = this.paramReferences == null ? 0 : this.paramReferences.length;
- if (md == null) return null;
- int argumentsSize = md.arguments == null ? 0 : md.arguments.length;
- if (argumentsSize == 0) return null;
-
- // Store all method arguments if there's no @param in javadoc
- if (paramTagsSize == 0) {
- char[][] missingParams = new char[argumentsSize][];
- for (int i = 0; i < argumentsSize; i++) {
- missingParams[i] = md.arguments[i].name;
- }
- return missingParams;
- }
-
- // Look for missing arguments
- char[][] missingParams = new char[argumentsSize][];
- int size = 0;
- for (int i = 0; i < argumentsSize; i++) {
- Argument arg = md.arguments[i];
- boolean found = false;
- int paramNameRefCount = 0;
- for (int j = 0; j < paramTagsSize && !found; j++) {
- JavadocSingleNameReference param = this.paramReferences[j];
- if (arg.binding == param.binding) {
- if (param.binding == paramNameRefBinding) { // do not count first occurence of param name reference
- paramNameRefCount++;
- found = paramNameRefCount > 1;
- } else {
- found = true;
- }
- }
- }
- if (!found) {
- missingParams[size++] = arg.name;
- }
- }
- if (size > 0) {
- if (size != argumentsSize) {
- System.arraycopy(missingParams, 0, missingParams = new char[size][], 0, size);
- }
- return missingParams;
- }
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionJavadocParser.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionJavadocParser.java
deleted file mode 100644
index a49d75b9..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionJavadocParser.java
+++ /dev/null
@@ -1,850 +0,0 @@
-/*******************************************************************************
- * 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.codeassist.complete;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.internal.codeassist.CompletionEngine;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Expression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocAllocationExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocArgumentExpression;
-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.JavadocQualifiedTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocSingleNameReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocSingleTypeReference;
-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.classfmt.ClassFileConstants;
-import org.eclipse.wst.jsdt.internal.compiler.parser.JavadocParser;
-import org.eclipse.wst.jsdt.internal.compiler.parser.ScannerHelper;
-import org.eclipse.wst.jsdt.internal.compiler.parser.TerminalTokens;
-
-/**
- * Parser specialized for decoding javadoc comments which includes cursor location for code completion.
- */
-public class CompletionJavadocParser extends JavadocParser {
-
- // Initialize lengthes for block and inline tags tables
- public final static int INLINE_ALL_TAGS_LENGTH;
- public final static int BLOCK_ALL_TAGS_LENGTH;
- static {
- int length = 0;
- for (int i=0; i<INLINE_TAGS_LENGTH; i++) {
- length += INLINE_TAGS[i].length;
- }
- INLINE_ALL_TAGS_LENGTH = length;
- length = 0;
- for (int i=0; i<BLOCK_TAGS_LENGTH; i++) {
- length += BLOCK_TAGS[i].length;
- }
- BLOCK_ALL_TAGS_LENGTH = length;
- }
-
- // Level tags are array of inline/block tags depending on compilation source level
- char[][][] levelTags = new char[2][][];
- int[] levelTagsLength = new int[2];
-
- // Completion specific info
- int cursorLocation;
- CompletionOnJavadoc completionNode = null;
- boolean pushText = false;
- boolean allPossibleTags = false;
-
- public CompletionJavadocParser(CompletionParser sourceParser) {
- super(sourceParser);
- this.scanner = new CompletionScanner(ClassFileConstants.JDK1_3);
- this.kind = COMPLETION_PARSER | TEXT_PARSE;
- this.reportProblems = false;
- initLevelTags();
- }
-
-// /*
-// * Do not parse comment if completion location is not included.
-// */
- public boolean checkDeprecation(int commentPtr) {
- this.cursorLocation = ((CompletionParser)sourceParser).cursorLocation;
- CompletionScanner completionScanner = (CompletionScanner)this.scanner;
- completionScanner.cursorLocation = this.cursorLocation;
- this.javadocStart = this.sourceParser.scanner.commentStarts[commentPtr];
- this.javadocEnd = this.sourceParser.scanner.commentStops[commentPtr];
- if (this.javadocStart <= this.cursorLocation && this.cursorLocation <= this.javadocEnd) {
- if (CompletionEngine.DEBUG) {
- System.out.println("COMPLETION in Javadoc:"); //$NON-NLS-1$
- }
- completionScanner.completionIdentifier = null;
- this.firstTagPosition = 1;
- super.checkDeprecation(commentPtr);
- } else {
- super.checkDeprecation(commentPtr);
-// this.docComment = null;
- }
- return false;
- }
-
- /*
- * Replace stored Javadoc node with specific completion one.
- */
- protected boolean commentParse() {
- this.docComment = new CompletionJavadoc(this.javadocStart, this.javadocEnd);
- return super.commentParse();
- }
-
- /*
- * Create argument expression. If it includes completion location, create and store completion node.
- */
- protected Object createArgumentReference(char[] name, int dim, boolean isVarargs, Object typeRef, long[] dimPositions, long argNamePos) throws InvalidInputException {
- // Create argument as we may need it after
- char[] argName = name==null ? CharOperation.NO_CHAR : name;
- Expression expression = (Expression) super.createArgumentReference(argName, dim, isVarargs, typeRef, dimPositions, argNamePos);
- // See if completion location is in argument
- int refStart = ((TypeReference)typeRef).sourceStart;
- int refEnd = ((TypeReference)typeRef).sourceEnd;
- boolean inCompletion = (refStart <= this.cursorLocation && this.cursorLocation <= refEnd) // completion cursor is between first and last stacked identifiers
- || ((refStart == (refEnd+1) && refEnd == this.cursorLocation)); // or it's a completion on empty token
- if (this.completionNode == null && inCompletion) {
- JavadocArgumentExpression javadocArgument = (JavadocArgumentExpression) expression;
- TypeReference expressionType = javadocArgument.argument.type;
- if (expressionType instanceof JavadocSingleTypeReference) {
- this.completionNode = new CompletionOnJavadocSingleTypeReference((JavadocSingleTypeReference) expressionType);
- } else if (expressionType instanceof JavadocQualifiedTypeReference) {
- this.completionNode = new CompletionOnJavadocQualifiedTypeReference((JavadocQualifiedTypeReference) expressionType);
- }
- if (CompletionEngine.DEBUG) {
- System.out.println(" completion argument="+completionNode); //$NON-NLS-1$
- }
- return this.completionNode;
- }
- return expression;
- }
-
- /*
- * Create field reference. If it includes completion location, create and store completion node.
- */
- protected Object createFieldReference(Object receiver) throws InvalidInputException {
- int refStart = (int) (this.identifierPositionStack[0] >>> 32);
- int refEnd = (int) this.identifierPositionStack[0];
- boolean inCompletion = (refStart <= (this.cursorLocation+1) && this.cursorLocation <= refEnd) // completion cursor is between first and last stacked identifiers
- || ((refStart == (refEnd+1) && refEnd == this.cursorLocation)) // or it's a completion on empty token
- || (this.memberStart == this.cursorLocation); // or it's a completion just after the member separator with an identifier after the cursor
- if (inCompletion) {
- JavadocFieldReference fieldRef = (JavadocFieldReference) super.createFieldReference(receiver);
- char[] name = this.sourceParser.compilationUnit.getMainTypeName();
- TypeDeclaration typeDecl = getParsedTypeDeclaration();
- if (typeDecl != null) {
- name = typeDecl.name;
- }
- this.completionNode = new CompletionOnJavadocFieldReference(fieldRef, this.memberStart, name);
- if (CompletionEngine.DEBUG) {
- System.out.println(" completion field="+completionNode); //$NON-NLS-1$
- }
- return this.completionNode;
- }
- return super.createFieldReference(receiver);
- }
-
- /*
- * Verify if method identifier positions include completion location.
- * If so, create method reference and store it.
- * Otherwise return null as we do not need this reference.
- */
- protected Object createMethodReference(Object receiver, List arguments) throws InvalidInputException {
- int memberPtr = this.identifierLengthStack[0] - 1; // may be > 0 for inner class constructor reference
- int refStart = (int) (this.identifierPositionStack[memberPtr] >>> 32);
- int refEnd = (int) this.identifierPositionStack[memberPtr];
- boolean inCompletion = (refStart <= (this.cursorLocation+1) && this.cursorLocation <= refEnd) // completion cursor is between first and last stacked identifiers
- || ((refStart == (refEnd+1) && refEnd == this.cursorLocation)) // or it's a completion on empty token
- || (this.memberStart == this.cursorLocation); // or it's a completion just after the member separator with an identifier after the cursor
- if (inCompletion) {
- ASTNode node = (ASTNode) super.createMethodReference(receiver, arguments);
- if (node instanceof JavadocMessageSend) {
- JavadocMessageSend messageSend = (JavadocMessageSend) node;
- int nameStart = (int) (messageSend.nameSourcePosition >>> 32);
- int nameEnd = (int) messageSend.nameSourcePosition;
- if ((nameStart <= (this.cursorLocation+1) && this.cursorLocation <= nameEnd)) {
- this.completionNode = new CompletionOnJavadocFieldReference(messageSend, this.memberStart);
- } else {
- this.completionNode = new CompletionOnJavadocMessageSend(messageSend, this.memberStart);
- }
- } else if (node instanceof JavadocAllocationExpression) {
- this.completionNode = new CompletionOnJavadocAllocationExpression((JavadocAllocationExpression)node, this.memberStart);
- }
- if (CompletionEngine.DEBUG) {
- System.out.println(" completion method="+completionNode); //$NON-NLS-1$
- }
- return this.completionNode;
- }
- return super.createMethodReference(receiver, arguments);
- }
-
- /*
- * Create type reference. If it includes completion location, create and store completion node.
- */
- protected Object createTypeReference(int primitiveToken) {
- // Need to create type ref in case it was needed by members
- int nbIdentifiers = this.identifierLengthStack[this.identifierLengthPtr];
- int startPtr = this.identifierPtr - (nbIdentifiers-1);
- int refStart = (int) (this.identifierPositionStack[startPtr] >>> 32);
- int refEnd = (int) this.identifierPositionStack[this.identifierPtr];
- boolean inCompletion = (refStart <= (this.cursorLocation+1) && this.cursorLocation <= refEnd) // completion cursor is between first and last stacked identifiers
- || ((refStart == (refEnd+1) && refEnd == this.cursorLocation)); // or it's a completion on empty token
- if (!inCompletion) {
- return super.createTypeReference(primitiveToken);
- }
- this.identifierLengthPtr--;
- if (nbIdentifiers == 1) { // Single Type ref
- this.completionNode = new CompletionOnJavadocSingleTypeReference(
- this.identifierStack[this.identifierPtr],
- this.identifierPositionStack[this.identifierPtr],
- this.tagSourceStart,
- this.tagSourceEnd);
- } else if (nbIdentifiers > 1) { // Qualified Type ref
- for (int i=startPtr; i<this.identifierPtr; i++) {
- int start = (int) (this.identifierPositionStack[i] >>> 32);
- int end = (int) this.identifierPositionStack[i];
- if (start <= this.cursorLocation && this.cursorLocation <= end) {
- if (i == startPtr) {
- this.completionNode = new CompletionOnJavadocSingleTypeReference(
- this.identifierStack[startPtr],
- this.identifierPositionStack[startPtr],
- this.tagSourceStart,
- this.tagSourceEnd);
- } else {
- char[][] tokens = new char[i][];
- System.arraycopy(this.identifierStack, startPtr, tokens, 0, i);
- long[] positions = new long[i+1];
- System.arraycopy(this.identifierPositionStack, startPtr, positions, 0, i+1);
- this.completionNode = new CompletionOnJavadocQualifiedTypeReference(tokens, this.identifierStack[i], positions, this.tagSourceStart, this.tagSourceEnd);
- }
- break;
- }
- }
- if (this.completionNode == null) {
- char[][] tokens = new char[nbIdentifiers-1][];
- System.arraycopy(this.identifierStack, startPtr, tokens, 0, nbIdentifiers-1);
- long[] positions = new long[nbIdentifiers];
- System.arraycopy(this.identifierPositionStack, startPtr, positions, 0, nbIdentifiers);
- this.completionNode = new CompletionOnJavadocQualifiedTypeReference(tokens, this.identifierStack[this.identifierPtr], positions, this.tagSourceStart, this.tagSourceEnd);
- }
- }
-
- if (CompletionEngine.DEBUG) {
- System.out.println(" completion partial qualified type="+completionNode); //$NON-NLS-1$
- }
- return this.completionNode;
- }
-
- /*
- * Get possible tags for a given prefix.
- */
- private char[][][] possibleTags(char[] prefix, boolean newLine) {
- char[][][] possibleTags = new char[2][][];
- if (newLine) {
- System.arraycopy(this.levelTags[BLOCK_IDX], 0, possibleTags[BLOCK_IDX] = new char[this.levelTagsLength[BLOCK_IDX]][], 0, this.levelTagsLength[BLOCK_IDX]);
- } else {
- possibleTags[BLOCK_IDX] = CharOperation.NO_CHAR_CHAR;
- }
- System.arraycopy(this.levelTags[INLINE_IDX], 0, possibleTags[INLINE_IDX] = new char[this.levelTagsLength[INLINE_IDX]][], 0, this.levelTagsLength[INLINE_IDX]);
- if (prefix == null || prefix.length == 0) return possibleTags;
- int kinds = levelTags.length;
- for (int k=0; k<kinds; k++) {
- int length = possibleTags[k].length, size = 0;
- int indexes[] = new int[length];
- for (int i=0; i<length; i++) {
- if (CharOperation.prefixEquals(prefix, possibleTags[k][i], false)) {
- indexes[size++] = i;
- }
- }
- char[][] tags = new char[size][];
- for (int i=0; i<size; i++) {
- tags[i] = possibleTags[k][indexes[i]];
- }
- possibleTags[k] = tags;
- }
- return possibleTags;
- }
-
- private CompletionJavadoc getCompletionJavadoc() {
- return (CompletionJavadoc)this.docComment;
- }
-
- private CompletionParser getCompletionParser() {
- return (CompletionParser)this.sourceParser;
- }
-
- /*
- * Init tags arrays for current source level.
- */
- private void initLevelTags() {
- int level = ((int)(this.complianceLevel >>> 16)) - ClassFileConstants.MAJOR_VERSION_1_1 + 1;
- // Init block tags
- this.levelTags[BLOCK_IDX] = new char[BLOCK_ALL_TAGS_LENGTH][];
- this.levelTagsLength[BLOCK_IDX] = 0;
- for (int i=0; i<=level; i++) {
- int length = BLOCK_TAGS[i].length;
- System.arraycopy(BLOCK_TAGS[i], 0, this.levelTags[BLOCK_IDX], this.levelTagsLength[BLOCK_IDX], length);
- this.levelTagsLength[BLOCK_IDX] += length;
- }
- if (this.levelTagsLength[BLOCK_IDX] < BLOCK_ALL_TAGS_LENGTH) {
- System.arraycopy(this.levelTags[BLOCK_IDX], 0, this.levelTags[BLOCK_IDX] = new char[this.levelTagsLength[BLOCK_IDX]][], 0, this.levelTagsLength[BLOCK_IDX]);
- }
- // Init inline tags
- this.levelTags[INLINE_IDX] = new char[INLINE_ALL_TAGS_LENGTH][];
- this.levelTagsLength[INLINE_IDX]= 0;
- for (int i=0; i<=level; i++) {
- int length = INLINE_TAGS[i].length;
- System.arraycopy(INLINE_TAGS[i], 0, this.levelTags[INLINE_IDX], this.levelTagsLength[INLINE_IDX], length);
- this.levelTagsLength[INLINE_IDX] += length;
- }
- if (this.levelTagsLength[INLINE_IDX] < INLINE_ALL_TAGS_LENGTH) {
- System.arraycopy(this.levelTags[INLINE_IDX], 0, this.levelTags[INLINE_IDX] = new char[this.levelTagsLength[INLINE_IDX]][], 0, this.levelTagsLength[INLINE_IDX]);
- }
- }
- /*
- * Parse argument in @see tag method reference
- */
- protected Object parseArguments(Object receiver) throws InvalidInputException {
-
- if (this.tagSourceStart>this.cursorLocation) {
- return super.parseArguments(receiver);
- }
-
- // Init
- int modulo = 0; // should be 2 for (Type,Type,...) or 3 for (Type arg,Type arg,...)
- int iToken = 0;
- char[] argName = null;
- List arguments = new ArrayList(10);
- Object typeRef = null;
- int dim = 0;
- boolean isVarargs = false;
- long[] dimPositions = new long[20]; // assume that there won't be more than 20 dimensions...
- char[] name = null;
- long argNamePos = -1;
-
- // Parse arguments declaration if method reference
- nextArg : while (this.index < this.scanner.eofPosition) {
-
- // Read argument type reference
- try {
- typeRef = parseQualifiedName(false);
- if (this.abort) return null; // May be aborted by specialized parser
- } catch (InvalidInputException e) {
- break nextArg;
- }
- boolean firstArg = modulo == 0;
- if (firstArg) { // verify position
- if (iToken != 0)
- break nextArg;
- } else if ((iToken % modulo) != 0) {
- break nextArg;
- }
- if (typeRef == null) {
- if (firstArg && getCurrentTokenType() == TerminalTokens.TokenNameRPAREN) {
- this.lineStarted = true;
- return createMethodReference(receiver, null);
- }
- Object methodRef = createMethodReference(receiver, arguments);
- return syntaxRecoverEmptyArgumentType(methodRef);
- }
- if (this.index >= this.scanner.eofPosition) {
- int argumentStart = ((ASTNode)typeRef).sourceStart;
- Object argument = createArgumentReference(this.scanner.getCurrentIdentifierSource(), 0, false, typeRef, null, (((long)argumentStart)<<32)+this.tokenPreviousPosition-1);
- return syntaxRecoverArgumentType(receiver, arguments, argument);
- }
- if (this.index >= this.cursorLocation) {
- if (this.completionNode instanceof CompletionOnJavadocSingleTypeReference) {
- CompletionOnJavadocSingleTypeReference singleTypeReference = (CompletionOnJavadocSingleTypeReference) this.completionNode;
- if (singleTypeReference.token == null || singleTypeReference.token.length == 0) {
- Object methodRef = createMethodReference(receiver, arguments);
- return syntaxRecoverEmptyArgumentType(methodRef);
- }
- }
- if (this.completionNode instanceof CompletionOnJavadocQualifiedTypeReference) {
- CompletionOnJavadocQualifiedTypeReference qualifiedTypeReference = (CompletionOnJavadocQualifiedTypeReference) this.completionNode;
- if (qualifiedTypeReference.tokens == null || qualifiedTypeReference.tokens.length < qualifiedTypeReference.sourcePositions.length) {
- Object methodRef = createMethodReference(receiver, arguments);
- return syntaxRecoverEmptyArgumentType(methodRef);
- }
- }
- }
- iToken++;
-
- // Read possible additional type info
- dim = 0;
- isVarargs = false;
- if (readToken() == TerminalTokens.TokenNameLBRACKET) {
- // array declaration
- int dimStart = this.scanner.getCurrentTokenStartPosition();
- while (readToken() == TerminalTokens.TokenNameLBRACKET) {
- consumeToken();
- if (readToken() != TerminalTokens.TokenNameRBRACKET) {
- break nextArg;
- }
- consumeToken();
- dimPositions[dim++] = (((long) dimStart) << 32) + this.scanner.getCurrentTokenEndPosition();
- }
- }
-// else if (readToken() == TerminalTokens.TokenNameELLIPSIS) {
-// // ellipsis declaration
-// int dimStart = this.scanner.getCurrentTokenStartPosition();
-// dimPositions[dim++] = (((long) dimStart) << 32) + this.scanner.getCurrentTokenEndPosition();
-// consumeToken();
-// isVarargs = true;
-// }
-
- // Read argument name
- argNamePos = -1;
- if (readToken() == TerminalTokens.TokenNameIdentifier) {
- consumeToken();
- if (firstArg) { // verify position
- if (iToken != 1)
- break nextArg;
- } else if ((iToken % modulo) != 1) {
- break nextArg;
- }
- if (argName == null) { // verify that all arguments name are declared
- if (!firstArg) {
- break nextArg;
- }
- }
- argName = this.scanner.getCurrentIdentifierSource();
- argNamePos = (((long)this.scanner.getCurrentTokenStartPosition())<<32)+this.scanner.getCurrentTokenEndPosition();
- iToken++;
- } else if (argName != null) { // verify that no argument name is declared
- break nextArg;
- }
-
- // Verify token position
- if (firstArg) {
- modulo = iToken + 1;
- } else {
- if ((iToken % modulo) != (modulo - 1)) {
- break nextArg;
- }
- }
-
- // Read separator or end arguments declaration
- int token = readToken();
- name = argName == null ? CharOperation.NO_CHAR : argName;
- if (token == TerminalTokens.TokenNameCOMMA) {
- // Create new argument
- Object argument = createArgumentReference(name, dim, isVarargs, typeRef, dimPositions, argNamePos);
- if (this.abort) return null; // May be aborted by specialized parser
- arguments.add(argument);
- consumeToken();
- iToken++;
- } else if (token == TerminalTokens.TokenNameRPAREN) {
- // Create new argument
- Object argument = createArgumentReference(name, dim, isVarargs, typeRef, dimPositions, argNamePos);
- if (this.abort) return null; // May be aborted by specialized parser
- arguments.add(argument);
- consumeToken();
- return createMethodReference(receiver, arguments);
- } else {
- Object argument = createArgumentReference(name, dim, isVarargs, typeRef, dimPositions, argNamePos);
- return syntaxRecoverArgumentType(receiver, arguments, argument);
- }
- }
-
- // Something wrong happened => Invalid input
- throw new InvalidInputException();
- }
-
- protected boolean parseParam() throws InvalidInputException {
- int startPosition = this.index;
- int endPosition = this.index;
- long namePosition = (((long)startPosition)<<32) + endPosition;
- this.identifierPtr = -1;
- boolean valid = super.parseParam();
- if (this.identifierPtr > 2) return valid;
- // See if expression is concerned by completion
- char[] name = null;
-
-//TODO: implement types
- TypeReference[]types=null;
- CompletionScanner completionScanner = (CompletionScanner) this.scanner;
- boolean isTypeParam = false;
- if (this.identifierPtr >= 0) {
- char[] identifier = null;
- switch (this.identifierPtr) {
- case 2:
- if (!valid && completionScanner.completionIdentifier != null && completionScanner.completionIdentifier.length == 0) {
- valid = pushParamName(true);
- }
- case 1:
- isTypeParam = this.identifierStack[0][0] == '<';
- identifier = this.identifierStack[1];
- namePosition = this.identifierPositionStack[1];
- break;
- case 0:
- identifier = this.identifierStack[0];
- namePosition = this.identifierPositionStack[0];
- isTypeParam = identifier.length > 0 && identifier[0] == '<';
- break;
- }
- if (identifier != null && identifier.length > 0 && ScannerHelper.isJavaIdentifierPart(identifier[0])) {
- name = identifier;
- }
- startPosition = (int)(this.identifierPositionStack[0]>>32);
- endPosition = (int)this.identifierPositionStack[this.identifierPtr];
- }
- boolean inCompletion = (startPosition <= (this.cursorLocation+1) && this.cursorLocation <= endPosition) // completion cursor is between first and last stacked identifiers
- || ((startPosition == (endPosition+1) && endPosition == this.cursorLocation)); // or it's a completion on empty token
- if (inCompletion) {
- if (this.completionNode == null) {
-
- this.completionNode = new CompletionOnJavadocParamNameReference(name, namePosition, startPosition, endPosition);
-
- if (CompletionEngine.DEBUG) {
- System.out.println(" completion param="+completionNode); //$NON-NLS-1$
- }
- } else if (this.completionNode instanceof CompletionOnJavadocParamNameReference) {
- CompletionOnJavadocParamNameReference paramNameRef = (CompletionOnJavadocParamNameReference)this.completionNode;
- int nameStart = (int) (namePosition>>32);
- paramNameRef.sourceStart = nameStart;
- int nameEnd = (int) namePosition;
- if (nameStart<this.cursorLocation && this.cursorLocation<nameEnd) {
- paramNameRef.sourceEnd = this.cursorLocation + 1;
- } else {
- paramNameRef.sourceEnd = nameEnd;
- }
- paramNameRef.tagSourceStart = startPosition;
- paramNameRef.tagSourceEnd = endPosition;
- }
- }
- return valid;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.parser.AbstractCommentParser#parseReference()
- */
- protected boolean parseReference() throws InvalidInputException {
- boolean completed = this.completionNode != null;
- boolean valid = super.parseReference();
- if (!completed && this.completionNode != null) {
- this.completionNode.addCompletionFlags(CompletionOnJavadoc.FORMAL_REFERENCE);
- }
- return valid;
- }
-
- /*(non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.parser.AbstractCommentParser#parseTag(int)
- */
- protected boolean parseTag(int previousPosition) throws InvalidInputException {
- int startPosition = this.inlineTagStarted ? this.inlineTagStart : previousPosition;
- boolean newLine = !this.lineStarted;
- boolean valid = super.parseTag(previousPosition);
- boolean inCompletion = (this.tagSourceStart <= (this.cursorLocation+1) && this.cursorLocation <= this.tagSourceEnd) // completion cursor is between first and last stacked identifiers
- || ((this.tagSourceStart == (this.tagSourceEnd+1) && this.tagSourceEnd == this.cursorLocation)); // or it's a completion on empty token
- if (inCompletion) {
- int end = this.tagSourceEnd;
- if (this.inlineTagStarted && this.scanner.currentCharacter == '}') {
- end = this.scanner.currentPosition;
- }
- long position = (((long)startPosition)<<32) + end;
- int length = this.cursorLocation+1-tagSourceStart;
- char[] tag = new char[length];
- System.arraycopy(this.source, this.tagSourceStart, tag, 0, length);
- char[][][] tags = possibleTags(tag, newLine);
- if (tags != null) {
- this.completionNode = new CompletionOnJavadocTag(tag, position, startPosition, end, tags, this.allPossibleTags);
- }
- }
- return valid;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.parser.AbstractCommentParser#parseThrows()
- */
- protected boolean parseThrows() {
- try {
- Object typeRef = parseQualifiedName(true);
- if (this.completionNode != null) {
- this.completionNode.addCompletionFlags(CompletionOnJavadoc.EXCEPTION);
- }
- return pushThrowName(typeRef);
- } catch (InvalidInputException ex) {
- // ignore
- }
- return false;
- }
-
- /*
- * Push param name reference. If it includes completion location, create and store completion node.
- */
- protected boolean pushParamName(boolean isTypeParam) {
- if (super.pushParamName(isTypeParam)) {
- Expression expression = (Expression) astStack[astPtr];
- // See if expression is concerned by completion
- if (expression.sourceStart <= (this.cursorLocation+1) && this.cursorLocation <= expression.sourceEnd) {
-
- this.completionNode = new CompletionOnJavadocParamNameReference((JavadocSingleNameReference)expression);
-
- if (CompletionEngine.DEBUG) {
- System.out.println(" completion param="+completionNode); //$NON-NLS-1$
- }
- }
- return true;
- }
- return false;
- }
-
- /**
- * Push text. If it includes completion location, then rescan line to see if there's a possible
- * reference under the cursor location.
- *
- * @see org.eclipse.wst.jsdt.internal.compiler.parser.AbstractCommentParser#pushText(int, int)
- */
- protected void pushText(int start, int end) {
- if (start <= this.cursorLocation && this.cursorLocation <= end) {
- this.scanner.resetTo(start, end);
- boolean tokenizeWhiteSpace = this.scanner.tokenizeWhiteSpace;
- this.scanner.tokenizeWhiteSpace = true;
- try {
- Object typeRef = null;
- this.pushText = true;
-
- // Get reference tokens
- int previousToken = TerminalTokens.TokenNameWHITESPACE;
- while (!this.scanner.atEnd() && this.completionNode == null && !this.abort) {
- int token = readTokenSafely();
- switch (token) {
- case TerminalTokens.TokenNameStringLiteral :
- int strStart = 0, strEnd = 0;
- if ((strStart=this.scanner.getCurrentTokenStartPosition()+1) <= this.cursorLocation &&
- this.cursorLocation <= (strEnd=this.scanner.getCurrentTokenEndPosition()-1))
- {
- this.scanner.resetTo(strStart, strEnd);
- }
- consumeToken();
- break;
- case TerminalTokens.TokenNameERROR :
- consumeToken();
- if (this.scanner.currentCharacter == '#') { // @see ...#member
- Object member = null;
- try {
- this.scanner.tokenizeWhiteSpace = false;
- member = parseMember(typeRef);
- } catch (InvalidInputException e) {
- consumeToken();
- }
- this.scanner.tokenizeWhiteSpace = true;
- if (this.completionNode != null) {
- int flags = this.inlineTagStarted ? 0 : CompletionOnJavadoc.TEXT|CompletionOnJavadoc.ONLY_INLINE_TAG;
- if (member instanceof JavadocMessageSend) {
- JavadocMessageSend msgSend = (JavadocMessageSend) member;
- this.completionNode = new CompletionOnJavadocMessageSend(msgSend, this.memberStart, flags);
- if (CompletionEngine.DEBUG) {
- System.out.println(" new completion method="+completionNode); //$NON-NLS-1$
- }
- } else if (member instanceof JavadocAllocationExpression) {
- JavadocAllocationExpression alloc = (JavadocAllocationExpression) member;
- this.completionNode = new CompletionOnJavadocAllocationExpression(alloc, this.memberStart, flags);
- if (CompletionEngine.DEBUG) {
- System.out.println(" new completion method="+completionNode); //$NON-NLS-1$
- }
- } else {
- this.completionNode.addCompletionFlags(flags);
- }
- }
- }
- break;
- case TerminalTokens.TokenNameIdentifier :
- try {
- this.scanner.tokenizeWhiteSpace = false;
- typeRef = parseQualifiedName(true);
- if (this.completionNode == null) {
- consumeToken();
- this.scanner.resetTo(this.tokenPreviousPosition, end);
- this.index = this.tokenPreviousPosition;
- }
- }
- catch (InvalidInputException e) {
- consumeToken();
- }
- finally {
- this.scanner.tokenizeWhiteSpace = true;
- }
- if (previousToken != TerminalTokens.TokenNameWHITESPACE) {
- typeRef = null;
- this.completionNode = null;
- }
- break;
- default :
- consumeToken();
- typeRef = null;
- break;
- }
- previousToken = token;
- }
- }
- finally {
- this.scanner.tokenizeWhiteSpace = tokenizeWhiteSpace;
- this.pushText = false;
- }
-
- // Reset position to avoid missing tokens when new line was encountered
- this.index = end;
- this.scanner.currentPosition = end;
- consumeToken();
-
- if (this.completionNode != null) {
- if (this.inlineTagStarted) {
- this.completionNode.addCompletionFlags(CompletionOnJavadoc.FORMAL_REFERENCE);
- } else {
- this.completionNode.addCompletionFlags(CompletionOnJavadoc.TEXT);
- }
- }
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.parser.AbstractCommentParser#readToken()
- */
- protected int readToken() throws InvalidInputException {
- int token = super.readToken();
- if (token == TerminalTokens.TokenNameIdentifier && this.scanner.currentPosition == this.scanner.startPosition) {
- // Scanner is looping on empty token => read it...
- this.scanner.getCurrentIdentifierSource();
- }
- return token;
- }
-
- /*
- * Recover syntax on invalid qualified name.
- */
- protected Object syntaxRecoverQualifiedName(int primitiveToken) throws InvalidInputException {
- if (this.cursorLocation == ((int)this.identifierPositionStack[this.identifierPtr])) {
- // special case of completion just before the dot.
- return createTypeReference(primitiveToken);
- }
- int idLength = this.identifierLengthStack[this.identifierLengthPtr];
- char[][] tokens = new char[idLength][];
- int startPtr = this.identifierPtr-idLength+1;
- System.arraycopy(this.identifierStack, startPtr, tokens, 0, idLength);
- long[] positions = new long[idLength+1];
- System.arraycopy(this.identifierPositionStack, startPtr, positions, 0, idLength);
- positions[idLength] = (((long)this.tokenPreviousPosition)<<32) + this.tokenPreviousPosition;
- this.completionNode = new CompletionOnJavadocQualifiedTypeReference(tokens, CharOperation.NO_CHAR, positions, this.tagSourceStart, this.tagSourceEnd);
-
- if (CompletionEngine.DEBUG) {
- System.out.println(" completion partial qualified type="+completionNode); //$NON-NLS-1$
- }
- return this.completionNode;
- }
-
- /*
- * Recover syntax on type argument in invalid method/constructor reference
- */
- protected Object syntaxRecoverArgumentType(Object receiver, List arguments, Object argument) throws InvalidInputException {
- if (this.completionNode != null && !this.pushText) {
- this.completionNode.addCompletionFlags(CompletionOnJavadoc.BASE_TYPES);
- if (this.completionNode instanceof CompletionOnJavadocSingleTypeReference) {
- char[] token = ((CompletionOnJavadocSingleTypeReference)this.completionNode).token;
- if (token != null && token.length > 0) {
- return this.completionNode;
- }
- } else {
- return this.completionNode;
- }
- }
- // Filter empty token
- if (this.completionNode instanceof CompletionOnJavadocSingleTypeReference) {
- CompletionOnJavadocSingleTypeReference singleTypeReference = (CompletionOnJavadocSingleTypeReference) this.completionNode;
- if (singleTypeReference.token != null && singleTypeReference.token.length > 0) {
- arguments.add(argument);
- }
- } else if (this.completionNode instanceof CompletionOnJavadocQualifiedTypeReference) {
- CompletionOnJavadocQualifiedTypeReference qualifiedTypeReference = (CompletionOnJavadocQualifiedTypeReference) this.completionNode;
- if (qualifiedTypeReference.tokens != null && qualifiedTypeReference.tokens.length == qualifiedTypeReference.sourcePositions.length) {
- arguments.add(argument);
- }
- } else {
- arguments.add(argument);
- }
- Object methodRef = super.createMethodReference(receiver, arguments);
- if (methodRef instanceof JavadocMessageSend) {
- JavadocMessageSend msgSend = (JavadocMessageSend) methodRef;
- if (this.index > this.cursorLocation) {
- msgSend.sourceEnd = this.tokenPreviousPosition-1;
- }
- int nameStart = (int) (msgSend.nameSourcePosition >>> 32);
- int nameEnd = (int) msgSend.nameSourcePosition;
- if ((nameStart <= (this.cursorLocation+1) && this.cursorLocation <= nameEnd)) {
- this.completionNode = new CompletionOnJavadocFieldReference(msgSend, this.memberStart);
- } else {
- this.completionNode = new CompletionOnJavadocMessageSend(msgSend, this.memberStart);
- }
- } else if (methodRef instanceof JavadocAllocationExpression) {
- JavadocAllocationExpression allocExp = (JavadocAllocationExpression) methodRef;
- if (this.index > this.cursorLocation) {
- allocExp.sourceEnd = this.tokenPreviousPosition-1;
- }
- this.completionNode = new CompletionOnJavadocAllocationExpression(allocExp, this.memberStart);
- }
- if (CompletionEngine.DEBUG) {
- System.out.println(" completion method="+completionNode); //$NON-NLS-1$
- }
- return this.completionNode;
- }
-
- /*
- * Recover syntax on empty type argument in invalid method/constructor reference
- */
- protected Object syntaxRecoverEmptyArgumentType(Object methodRef) throws InvalidInputException {
- if (methodRef instanceof JavadocMessageSend) {
- JavadocMessageSend msgSend = (JavadocMessageSend) methodRef;
- if (this.index > this.cursorLocation) {
- msgSend.sourceEnd = this.tokenPreviousPosition-1;
- }
- this.completionNode = new CompletionOnJavadocMessageSend(msgSend, this.memberStart);
- } else if (methodRef instanceof JavadocAllocationExpression) {
- JavadocAllocationExpression allocExp = (JavadocAllocationExpression) methodRef;
- if (this.index > this.cursorLocation) {
- allocExp.sourceEnd = this.tokenPreviousPosition-1;
- }
- this.completionNode = new CompletionOnJavadocAllocationExpression(allocExp, this.memberStart);
- }
- if (CompletionEngine.DEBUG) {
- System.out.println(" completion method="+completionNode); //$NON-NLS-1$
- }
- return this.completionNode;
- }
-
- /*
- * Store completion node into doc comment.
- */
- protected void updateDocComment() {
- super.updateDocComment();
- if (completionNode instanceof Expression) {
- getCompletionParser().assistNodeParent = this.docComment;
- getCompletionParser().assistNode = (ASTNode) this.completionNode;
- getCompletionJavadoc().completionNode = (Expression) completionNode;
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.parser.AbstractCommentParser#verifySpaceOrEndComment()
- */
- protected boolean verifySpaceOrEndComment() {
- CompletionScanner completionScanner = (CompletionScanner) this.scanner;
- if (completionScanner.completionIdentifier != null && completionScanner.completedIdentifierStart <= this.cursorLocation && this.cursorLocation <= completionScanner.completedIdentifierEnd) {
- // if we're on completion location do not verify end...
- return true;
- }
- return super.verifySpaceOrEndComment();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionNodeDetector.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionNodeDetector.java
deleted file mode 100644
index d9f49bb9..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionNodeDetector.java
+++ /dev/null
@@ -1,288 +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.codeassist.complete;
-
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-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.AllocationExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ArrayAllocationExpression;
-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.CompoundAssignment;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ConditionalExpression;
-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.FieldReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.InstanceOfExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ListExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.MessageSend;
-import org.eclipse.wst.jsdt.internal.compiler.ast.OR_OR_Expression;
-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.QualifiedAllocationExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedNameReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedThisReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedTypeReference;
-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.StringLiteral;
-import org.eclipse.wst.jsdt.internal.compiler.ast.SuperReference;
-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.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ClassScope;
-
-/**
- * Detect the presence of a node in expression
- */
-public class CompletionNodeDetector extends ASTVisitor {
- private ASTNode searchedNode;
- private ASTNode parent;
- private boolean result;
-
- public CompletionNodeDetector(ASTNode searchedNode, ASTNode visitedAst){
- this.searchedNode = searchedNode;
- this.result = false;
-
- if(searchedNode != null && visitedAst != null) {
- visitedAst.traverse(this, null);
- }
- }
-
- public boolean containsCompletionNode() {
- return this.result;
- }
-
- public ASTNode getCompletionNodeParent() {
- return this.parent;
- }
- public void endVisit(AllocationExpression allocationExpression, BlockScope scope) {
- endVisit(allocationExpression);
- }
- public void endVisit(AND_AND_Expression and_and_Expression, BlockScope scope) {
- endVisit(and_and_Expression);
- }
- public void endVisit(ArrayAllocationExpression arrayAllocationExpression, BlockScope scope) {
- endVisit(arrayAllocationExpression);
- }
- public void endVisit(ArrayInitializer arrayInitializer, BlockScope scope) {
- endVisit(arrayInitializer);
- }
- public void endVisit(ArrayQualifiedTypeReference arrayQualifiedTypeReference, BlockScope scope) {
- endVisit(arrayQualifiedTypeReference);
- }
- public void endVisit(ArrayQualifiedTypeReference arrayQualifiedTypeReference, ClassScope scope) {
- endVisit(arrayQualifiedTypeReference);
- }
- public void endVisit(ArrayReference arrayReference, BlockScope scope) {
- endVisit(arrayReference);
- }
- public void endVisit(ArrayTypeReference arrayTypeReference, BlockScope scope) {
- endVisit(arrayTypeReference);
- }
- public void endVisit(ArrayTypeReference arrayTypeReference, ClassScope scope) {
- endVisit(arrayTypeReference);
- }
- public void endVisit(Assignment assignment, BlockScope scope) {
- endVisit(assignment);
- }
- public void endVisit(BinaryExpression binaryExpression, BlockScope scope) {
- endVisit(binaryExpression);
- }
- public void endVisit(CompoundAssignment compoundAssignment, BlockScope scope) {
- endVisit(compoundAssignment);
- }
- public void endVisit(ConditionalExpression conditionalExpression, BlockScope scope) {
- endVisit(conditionalExpression);
- }
- public void endVisit(EqualExpression equalExpression, BlockScope scope) {
- endVisit(equalExpression);
- }
- public void endVisit(ExplicitConstructorCall explicitConstructor, BlockScope scope) {
- endVisit(explicitConstructor);
- }
- public void endVisit(FieldReference fieldReference, BlockScope scope) {
- endVisit(fieldReference);
- }
- public void endVisit(InstanceOfExpression instanceOfExpression, BlockScope scope) {
- endVisit(instanceOfExpression);
- }
- public void endVisit(MessageSend messageSend, BlockScope scope) {
- endVisit(messageSend);
- }
- public void endVisit(ListExpression listExpression, BlockScope scope) {
- endVisit(listExpression);
- }
- public void endVisit(OR_OR_Expression or_or_Expression, BlockScope scope) {
- endVisit(or_or_Expression);
- }
- public void endVisit(PostfixExpression postfixExpression, BlockScope scope) {
- endVisit(postfixExpression);
- }
- public void endVisit(PrefixExpression prefixExpression, BlockScope scope) {
- endVisit(prefixExpression);
- }
- public void endVisit(QualifiedAllocationExpression qualifiedAllocationExpression, BlockScope scope) {
- endVisit(qualifiedAllocationExpression);
- }
- public void endVisit(QualifiedNameReference qualifiedNameReference, BlockScope scope) {
- endVisit(qualifiedNameReference);
- }
- public void endVisit(QualifiedThisReference qualifiedThisReference, BlockScope scope) {
- endVisit(qualifiedThisReference);
- }
- public void endVisit(QualifiedTypeReference qualifiedTypeReference, BlockScope scope) {
- endVisit(qualifiedTypeReference);
- }
- public void endVisit(QualifiedTypeReference qualifiedTypeReference, ClassScope scope) {
- endVisit(qualifiedTypeReference);
- }
- public void endVisit(SingleNameReference singleNameReference, BlockScope scope) {
- endVisit(singleNameReference);
- }
- public void endVisit(SingleTypeReference singleTypeReference, BlockScope scope) {
- endVisit(singleTypeReference);
- }
- public void endVisit(SingleTypeReference singleTypeReference, ClassScope scope) {
- endVisit(singleTypeReference);
- }
- public void endVisit(SuperReference superReference, BlockScope scope) {
- endVisit(superReference);
- }
- public void endVisit(ThisReference thisReference, BlockScope scope) {
- endVisit(thisReference);
- }
- public void endVisit(UnaryExpression unaryExpression, BlockScope scope) {
- endVisit(unaryExpression);
- }
- public boolean visit(AllocationExpression allocationExpression, BlockScope scope) {
- return this.visit(allocationExpression);
- }
- public boolean visit(AND_AND_Expression and_and_Expression, BlockScope scope) {
- return this.visit(and_and_Expression);
- }
- public boolean visit(ArrayAllocationExpression arrayAllocationExpression, BlockScope scope) {
- return this.visit(arrayAllocationExpression);
- }
- public boolean visit(ArrayInitializer arrayInitializer, BlockScope scope) {
- return this.visit(arrayInitializer);
- }
- public boolean visit(ArrayQualifiedTypeReference arrayQualifiedTypeReference, BlockScope scope) {
- return this.visit(arrayQualifiedTypeReference);
- }
- public boolean visit(ArrayQualifiedTypeReference arrayQualifiedTypeReference, ClassScope scope) {
- return this.visit(arrayQualifiedTypeReference);
- }
- public boolean visit(ArrayReference arrayReference, BlockScope scope) {
- return this.visit(arrayReference);
- }
- public boolean visit(ArrayTypeReference arrayTypeReference, BlockScope scope) {
- return this.visit(arrayTypeReference);
- }
- public boolean visit(ArrayTypeReference arrayTypeReference, ClassScope scope) {
- return this.visit(arrayTypeReference);
- }
- public boolean visit(Assignment assignment, BlockScope scope) {
- return this.visit(assignment);
- }
- public boolean visit(BinaryExpression binaryExpression, BlockScope scope) {
- return this.visit(binaryExpression);
- }
- public boolean visit(CompoundAssignment compoundAssignment, BlockScope scope) {
- return this.visit(compoundAssignment);
- }
- public boolean visit(ConditionalExpression conditionalExpression, BlockScope scope) {
- return this.visit(conditionalExpression);
- }
- public boolean visit(EqualExpression equalExpression, BlockScope scope) {
- return this.visit(equalExpression);
- }
- public boolean visit(ExplicitConstructorCall explicitConstructor, BlockScope scope) {
- return this.visit(explicitConstructor);
- }
- public boolean visit(FieldReference fieldReference, BlockScope scope) {
- return this.visit(fieldReference);
- }
- public boolean visit(ListExpression listExpression, BlockScope scope) {
- return this.visit(listExpression);
- }
- public boolean visit(InstanceOfExpression instanceOfExpression, BlockScope scope) {
- return this.visit(instanceOfExpression);
- }
- public boolean visit(MessageSend messageSend, BlockScope scope) {
- return this.visit(messageSend);
- }
- public boolean visit(OR_OR_Expression or_or_Expression, BlockScope scope) {
- return this.visit(or_or_Expression);
- }
- public boolean visit(PostfixExpression postfixExpression, BlockScope scope) {
- return this.visit(postfixExpression);
- }
- public boolean visit(PrefixExpression prefixExpression, BlockScope scope) {
- return this.visit(prefixExpression);
- }
- public boolean visit(QualifiedAllocationExpression qualifiedAllocationExpression, BlockScope scope) {
- return this.visit(qualifiedAllocationExpression);
- }
- public boolean visit(QualifiedNameReference qualifiedNameReference, BlockScope scope) {
- return this.visit(qualifiedNameReference);
- }
- public boolean visit(QualifiedThisReference qualifiedThisReference, BlockScope scope) {
- return this.visit(qualifiedThisReference);
- }
- public boolean visit(QualifiedTypeReference qualifiedTypeReference, BlockScope scope) {
- return this.visit(qualifiedTypeReference);
- }
- public boolean visit(QualifiedTypeReference qualifiedTypeReference, ClassScope scope) {
- return this.visit(qualifiedTypeReference);
- }
- public boolean visit(SingleNameReference singleNameReference, BlockScope scope) {
- return this.visit(singleNameReference);
- }
- public boolean visit(SingleTypeReference singleTypeReference, BlockScope scope) {
- return this.visit(singleTypeReference);
- }
- public boolean visit(SingleTypeReference singleTypeReference, ClassScope scope) {
- return this.visit(singleTypeReference);
- }
- public boolean visit(StringLiteral stringLiteral, BlockScope scope) {
- return this.visit(stringLiteral);
- }
- public boolean visit(SuperReference superReference, BlockScope scope) {
- return this.visit(superReference);
- }
- public boolean visit(ThisReference thisReference, BlockScope scope) {
- return this.visit(thisReference);
- }
- public boolean visit(UnaryExpression unaryExpression, BlockScope scope) {
- return this.visit(unaryExpression);
- }
- private void endVisit(ASTNode astNode) {
- if(this.result && this.parent == null && astNode != this.searchedNode) {
- if(!(astNode instanceof AllocationExpression && ((AllocationExpression) astNode).type == this.searchedNode)
- && !(astNode instanceof ConditionalExpression && ((ConditionalExpression) astNode).valueIfTrue == this.searchedNode)
- && !(astNode instanceof ConditionalExpression && ((ConditionalExpression) astNode).valueIfFalse == this.searchedNode)) {
- this.parent = astNode;
- }
- }
- }
- private boolean visit(ASTNode astNode) {
- if(astNode == this.searchedNode) {
- this.result = true;
- }
- return !this.result;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionNodeFound.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionNodeFound.java
deleted file mode 100644
index 088eb428..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionNodeFound.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.complete;
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Binding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Scope;
-
-public class CompletionNodeFound extends RuntimeException {
-
- public ASTNode astNode;
- public Binding qualifiedBinding;
- public Scope scope;
- public boolean insideTypeAnnotation = false;
-
- private static final long serialVersionUID = 6981437684184091462L; // backward compatible
-
-public CompletionNodeFound() {
- this(null, null, null, false); // we found a problem in the completion node
-}
-public CompletionNodeFound(ASTNode astNode, Binding qualifiedBinding, Scope scope) {
- this(astNode, qualifiedBinding, scope, false);
-}
-public CompletionNodeFound(ASTNode astNode, Binding qualifiedBinding, Scope scope, boolean insideTypeAnnotation) {
- this.astNode = astNode;
- this.qualifiedBinding = qualifiedBinding;
- this.scope = scope;
- this.insideTypeAnnotation = insideTypeAnnotation;
-}
-public CompletionNodeFound(ASTNode astNode, Scope scope) {
- this(astNode, null, scope, false);
-}
-public CompletionNodeFound(ASTNode astNode, Scope scope, boolean insideTypeAnnotation) {
- this(astNode, null, scope, insideTypeAnnotation);
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnArgumentName.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnArgumentName.java
deleted file mode 100644
index 98416b09..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnArgumentName.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.complete;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Argument;
-import org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-
-public class CompletionOnArgumentName extends Argument {
-
- private static final char[] FAKENAMESUFFIX = " ".toCharArray(); //$NON-NLS-1$
- public char[] realName;
- public boolean isCatchArgument = false;
-
- public CompletionOnArgumentName(char[] name , long posNom , TypeReference tr , int modifiers){
-
- super(CharOperation.concat(name, FAKENAMESUFFIX), posNom, tr, modifiers);
- this.realName = name;
- }
-
- public void bind(MethodScope scope, TypeBinding typeBinding, boolean used) {
-
- super.bind(scope, typeBinding, used);
- throw new CompletionNodeFound(this, scope);
- }
-
- public StringBuffer print(int indent, StringBuffer output) {
-
- printIndent(indent, output);
- output.append("<CompleteOnArgumentName:"); //$NON-NLS-1$
- if (this.type != null) this.type.print(0, output).append(' ');
- output.append(this.realName);
- if (this.initialization != null) {
- output.append(" = "); //$NON-NLS-1$
- this.initialization.printExpression(0, output);
- }
- return output.append('>');
- }
-
- public void resolve(BlockScope scope) {
-
- super.resolve(scope);
- throw new CompletionNodeFound(this, scope);
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnBrankStatementLabel.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnBrankStatementLabel.java
deleted file mode 100644
index 01611c45..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnBrankStatementLabel.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.complete;
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.BranchStatement;
-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.lookup.BlockScope;
-
-public class CompletionOnBrankStatementLabel extends BranchStatement {
- public static final int BREAK = 1;
- public static final int CONTINUE = 2;
-
- private int kind;
- public char[][] possibleLabels;
-
- public CompletionOnBrankStatementLabel(int kind, char[] l, int s, int e, char[][] possibleLabels) {
- super(l, s, e);
- this.kind = kind;
- this.possibleLabels = possibleLabels;
- }
-
- public FlowInfo analyseCode(BlockScope currentScope,
- FlowContext flowContext, FlowInfo flowInfo) {
- // Is never called
- return null;
- }
-
- public void resolve(BlockScope scope) {
- throw new CompletionNodeFound(this, scope);
- }
- public StringBuffer printStatement(int indent, StringBuffer output) {
- printIndent(indent, output);
- if(kind == CONTINUE) {
- output.append("continue "); //$NON-NLS-1$
- } else {
- output.append("break "); //$NON-NLS-1$
- }
- output.append("<CompleteOnLabel:"); //$NON-NLS-1$
- output.append(label);
- return output.append(">;"); //$NON-NLS-1$
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnClassLiteralAccess.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnClassLiteralAccess.java
deleted file mode 100644
index 548e34d4..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnClassLiteralAccess.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.complete;
-
-/*
- * Completion node build by the parser in any case it was intending to
- * reduce an access to the literal 'class' containing the cursor.
- * e.g.
- *
- * class X {
- * void foo() {
- * String[].[cursor]
- * }
- * }
- *
- * ---> class X {
- * void foo() {
- * <CompleteOnClassLiteralAccess:String[].>
- * }
- * }
- *
- * The source range of the completion node denotes the source range
- * which should be replaced by the completion.
- */
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.ClassLiteralAccess;
-import org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class CompletionOnClassLiteralAccess extends ClassLiteralAccess {
-
- public char[] completionIdentifier;
- public int classStart;
-
- public CompletionOnClassLiteralAccess(long pos, TypeReference t) {
-
- super((int)pos, t);
- this.classStart = (int) (pos >>> 32);
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output) {
-
- output.append("<CompleteOnClassLiteralAccess:"); //$NON-NLS-1$
- return this.type.print(0, output).append('.').append(this.completionIdentifier).append('>');
- }
-
- public TypeBinding resolveType(BlockScope scope) {
-
- if (super.resolveType(scope) == null)
- throw new CompletionNodeFound();
- else
- throw new CompletionNodeFound(this, this.targetType, scope);
- }
-}
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
deleted file mode 100644
index 51dbdaad..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnExplicitConstructorCall.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.complete;
-
-/*
- * Completion node build by the parser in any case it was intending to
- * reduce a explicit constructor call containing the cursor.
- * e.g.
- *
- * class X {
- * X() {
- * this(1, 2, [cursor]
- * }
- * }
- *
- * ---> class X {
- * X() {
- * <CompleteOnExplicitConstructorCall:this(1, 2)>
- * }
- * }
- *
- * The source range is always of length 0.
- * The arguments of the constructor call are all the arguments defined
- * before the cursor.
- */
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.ExplicitConstructorCall;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding;
-
-public class CompletionOnExplicitConstructorCall extends ExplicitConstructorCall {
-
- public CompletionOnExplicitConstructorCall(int accessMode) {
- super(accessMode);
- }
-
- public StringBuffer printStatement(int tab, StringBuffer output) {
-
- printIndent(tab, output);
- output.append("<CompleteOnExplicitConstructorCall:"); //$NON-NLS-1$
- if (this.qualification != null) this.qualification.printExpression(0, output).append('.');
- if (this.accessMode == This) {
- output.append("this("); //$NON-NLS-1$
- } else {
- output.append("super("); //$NON-NLS-1$
- }
- if (this.arguments != null) {
- for (int i = 0; i < this.arguments.length; i++) {
- if (i > 0) output.append(", "); //$NON-NLS-1$
- this.arguments[i].printExpression(0, output);
- }
- }
- return output.append(")>;"); //$NON-NLS-1$
- }
-
- public void resolve(BlockScope scope) {
-
- ReferenceBinding receiverType = scope.enclosingSourceType();
-
- if (this.arguments != null) {
- int argsLength = this.arguments.length;
- for (int a = argsLength; --a >= 0;)
- this.arguments[a].resolveType(scope);
- }
-
- if (this.accessMode != This && receiverType != null) {
- if (receiverType.isHierarchyInconsistent())
- throw new CompletionNodeFound();
- receiverType = receiverType.superclass();
- }
- if (receiverType == null)
- throw new CompletionNodeFound();
- else
- throw new CompletionNodeFound(this, receiverType, scope);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnFieldName.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnFieldName.java
deleted file mode 100644
index 1aa9040e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnFieldName.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.complete;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodScope;
-
-public class CompletionOnFieldName extends FieldDeclaration {
- private static final char[] FAKENAMESUFFIX = " ".toCharArray(); //$NON-NLS-1$
- public char[] realName;
- public CompletionOnFieldName(char[] name, int sourceStart, int sourceEnd) {
- super(CharOperation.concat(name, FAKENAMESUFFIX), sourceStart, sourceEnd);
- this.realName = name;
- }
-
- public StringBuffer printStatement(int tab, StringBuffer output) {
-
- printIndent(tab, output).append("<CompleteOnFieldName:"); //$NON-NLS-1$
- if (type != null) type.print(0, output).append(' ');
- output.append(realName);
- if (initialization != null) {
- output.append(" = "); //$NON-NLS-1$
- initialization.printExpression(0, output);
- }
- return output.append(">;"); //$NON-NLS-1$
- }
-
- public void resolve(MethodScope initializationScope) {
- super.resolve(initializationScope);
-
- throw new CompletionNodeFound(this, initializationScope);
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnFieldType.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnFieldType.java
deleted file mode 100644
index a16170f5..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnFieldType.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.complete;
-
-/*
- * Completion node build by the parser in any case it was intending to
- * reduce an type reference located as a potential return type for a class
- * member, containing the cursor location.
- * This node is only a fake-field wrapper of the actual completion node
- * which is accessible as the fake-field type.
- * e.g.
- *
- * class X {
- * Obj[cursor]
- * }
- *
- * ---> class X {
- * <CompleteOnType:Obj>;
- * }
- *
- * The source range is always of length 0.
- * The arguments of the allocation expression are all the arguments defined
- * before the cursor.
- */
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference;
-
-public class CompletionOnFieldType extends FieldDeclaration {
- public boolean isLocalVariable;
-
-public CompletionOnFieldType(TypeReference type, boolean isLocalVariable){
- super();
- this.sourceStart = type.sourceStart;
- this.sourceEnd = type.sourceEnd;
- this.type = type;
- this.name = CharOperation.NO_CHAR;
- this.isLocalVariable = isLocalVariable;
- if (type instanceof CompletionOnSingleTypeReference) {
- ((CompletionOnSingleTypeReference) type).fieldTypeCompletionNode = this;
- }
-}
-
-public StringBuffer printStatement(int tab, StringBuffer output) {
- return type.print(tab, output).append(';');
-}
-}
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
deleted file mode 100644
index 4faae947..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnImportReference.java
+++ /dev/null
@@ -1,51 +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.codeassist.complete;
-
-/*
- * Completion node build by the parser in any case it was intending to
- * reduce an import reference containing the cursor location.
- * e.g.
- *
- * import java.io[cursor];
- * class X {
- * void foo() {
- * }
- * }
- *
- * ---> <CompleteOnImport:java.io>
- * class X {
- * void foo() {
- * }
- * }
- *
- * The source range is always of length 0.
- * The arguments of the allocation expression are all the arguments defined
- * before the cursor.
- */
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.ImportReference;
-
-public class CompletionOnImportReference extends ImportReference {
-
-public CompletionOnImportReference(char[][] tokens , long[] positions) {
- super(tokens, positions, false);
-}
-public StringBuffer print(int indent, StringBuffer output, boolean withOnDemand) {
-
- printIndent(indent, output).append("<CompleteOnImport:"); //$NON-NLS-1$
- for (int i = 0; i < tokens.length; i++) {
- if (i > 0) output.append('.');
- output.append(tokens[i]);
- }
- return output.append('>');
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnJavadoc.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnJavadoc.java
deleted file mode 100644
index 1db51f4f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnJavadoc.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.complete;
-
-public interface CompletionOnJavadoc {
-
- // Bit pattern for javadoc completion flags
- int JAVADOC = 0x0001;
- int EXCEPTION = 0x0002;
- int TEXT = 0x0004;
- int BASE_TYPES = 0x0008;
- int ONLY_INLINE_TAG = 0x0010;
- int REPLACE_TAG = 0x0020;
- int FORMAL_REFERENCE = 0x0040;
- int ALL_POSSIBLE_TAGS = 0x0080;
-
- /**
- * Get completion node flags.
- *
- * @return int Flags of the javadoc completion node.
- */
- public int getCompletionFlags();
-
- /**
- * @param flags The completionFlags to add.
- */
- public void addCompletionFlags(int flags);
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnJavadocAllocationExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnJavadocAllocationExpression.java
deleted file mode 100644
index 0f615090..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnJavadocAllocationExpression.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.complete;
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocAllocationExpression;
-
-public class CompletionOnJavadocAllocationExpression extends JavadocAllocationExpression implements CompletionOnJavadoc {
- public int completionFlags = JAVADOC;
- public int separatorPosition;
-
- public CompletionOnJavadocAllocationExpression(JavadocAllocationExpression allocation, int position) {
- super(allocation.sourceStart, allocation.sourceEnd);
- this.arguments = allocation.arguments;
- this.type = allocation.type;
- this.tagValue = allocation.tagValue;
- this.sourceEnd = allocation.sourceEnd;
- this.separatorPosition = position;
- this.qualification = allocation.qualification;
- }
-
- public CompletionOnJavadocAllocationExpression(JavadocAllocationExpression allocation, int position, int flags) {
- this(allocation, position);
- this.completionFlags |= flags;
- }
-
- /**
- * @param flags The completionFlags to set.
- */
- public void addCompletionFlags(int flags) {
- this.completionFlags |= flags;
- }
-
- public boolean completeAnException() {
- return (this.completionFlags & EXCEPTION) != 0;
- }
-
- public boolean completeInText() {
- return (this.completionFlags & TEXT) != 0;
- }
-
- public boolean completeBaseTypes() {
- return (this.completionFlags & BASE_TYPES) != 0;
- }
-
- public boolean completeFormalReference() {
- return (this.completionFlags & FORMAL_REFERENCE) != 0;
- }
-
- /**
- * Get completion node flags.
- *
- * @return int Flags of the javadoc completion node.
- */
- public int getCompletionFlags() {
- return this.completionFlags;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.AllocationExpression#printExpression(int, java.lang.StringBuffer)
- */
- public StringBuffer printExpression(int indent, StringBuffer output) {
- output.append("<CompleteOnJavadocAllocationExpression:"); //$NON-NLS-1$
- super.printExpression(indent, output);
- indent++;
- if (this.completionFlags > 0) {
- output.append('\n');
- for (int i=0; i<indent; i++) output.append('\t');
- output.append("infos:"); //$NON-NLS-1$
- char separator = 0;
- if (completeAnException()) {
- output.append("exception"); //$NON-NLS-1$
- separator = ',';
- }
- if (completeInText()) {
- if (separator != 0) output.append(separator);
- output.append("text"); //$NON-NLS-1$
- separator = ',';
- }
- if (completeBaseTypes()) {
- if (separator != 0) output.append(separator);
- output.append("base types"); //$NON-NLS-1$
- separator = ',';
- }
- if (completeFormalReference()) {
- if (separator != 0) output.append(separator);
- output.append("formal reference"); //$NON-NLS-1$
- separator = ',';
- }
- output.append('\n');
- }
- indent--;
- for (int i=0; i<indent; i++) output.append('\t');
- return output.append('>');
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnJavadocFieldReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnJavadocFieldReference.java
deleted file mode 100644
index a63a1147..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnJavadocFieldReference.java
+++ /dev/null
@@ -1,142 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.complete;
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.Expression;
-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.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ClassScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Scope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class CompletionOnJavadocFieldReference extends JavadocFieldReference implements CompletionOnJavadoc {
-// public boolean completionInText;
- public int completionFlags = JAVADOC;
- public int separatorPosition;
-
- public CompletionOnJavadocFieldReference(Expression receiver, int tag, int position, int separatorPos, char[] name) {
- super(null, (((long)position)<<32)+position-1);
- this.receiver = receiver;
- this.tagSourceStart = position;
- this.tagSourceEnd = position;
- this.tagValue = tag;
- this.separatorPosition = separatorPos;
- }
-
- public CompletionOnJavadocFieldReference(JavadocFieldReference fieldRef, int position, char[] name) {
- super(fieldRef.token, fieldRef.nameSourcePosition);
- this.receiver = fieldRef.receiver;
- this.separatorPosition = position;
- this.tagSourceStart = fieldRef.tagSourceStart;
- this.tagSourceEnd = fieldRef.tagSourceEnd;
- this.tagValue = fieldRef.tagValue;
- }
-
- public CompletionOnJavadocFieldReference(JavadocMessageSend msgSend, int position) {
- super(msgSend.selector, ((msgSend.nameSourcePosition>>32)<<32)+msgSend.sourceEnd);
- this.receiver = msgSend.receiver;
- this.separatorPosition = position;
- this.tagSourceStart = msgSend.tagSourceStart;
- this.tagSourceEnd = msgSend.tagSourceEnd;
- this.tagValue = msgSend.tagValue;
- }
-
- /**
- * @param flags The completionFlags to set.
- */
- public void addCompletionFlags(int flags) {
- this.completionFlags |= flags;
- }
-
- public boolean completeAnException() {
- return (this.completionFlags & EXCEPTION) != 0;
- }
-
- public boolean completeInText() {
- return (this.completionFlags & TEXT) != 0;
- }
-
- public boolean completeBaseTypes() {
- return (this.completionFlags & BASE_TYPES) != 0;
- }
-
- public boolean completeFormalReference() {
- return (this.completionFlags & FORMAL_REFERENCE) != 0;
- }
-
- /**
- * Get completion node flags.
- *
- * @return int Flags of the javadoc completion node.
- */
- public int getCompletionFlags() {
- return this.completionFlags;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.JavadocFieldReference#internalResolveType(org.eclipse.wst.jsdt.internal.compiler.lookup.Scope)
- */
- protected TypeBinding internalResolveType(Scope scope) {
-
- if (this.token != null) {
- return super.internalResolveType(scope);
- }
-
- // Resolve only receiver
- if (this.receiver == null) {
- this.receiverType = scope.enclosingSourceType();
- } else if (scope.kind == Scope.CLASS_SCOPE) {
- this.receiverType = this.receiver.resolveType((ClassScope) scope);
- } else {
- this.receiverType = this.receiver.resolveType((BlockScope)scope);
- }
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.JavadocFieldReference#printExpression(int, java.lang.StringBuffer)
- */
- public StringBuffer printExpression(int indent, StringBuffer output) {
- output.append("<CompleteOnJavadocFieldReference:"); //$NON-NLS-1$
- super.printExpression(indent, output);
- indent++;
- if (this.completionFlags > 0) {
- output.append('\n');
- for (int i=0; i<indent; i++) output.append('\t');
- output.append("infos:"); //$NON-NLS-1$
- char separator = 0;
- if (completeAnException()) {
- output.append("exception"); //$NON-NLS-1$
- separator = ',';
- }
- if (completeInText()) {
- if (separator != 0) output.append(separator);
- output.append("text"); //$NON-NLS-1$
- separator = ',';
- }
- if (completeBaseTypes()) {
- if (separator != 0) output.append(separator);
- output.append("base types"); //$NON-NLS-1$
- separator = ',';
- }
- if (completeFormalReference()) {
- if (separator != 0) output.append(separator);
- output.append("formal reference"); //$NON-NLS-1$
- separator = ',';
- }
- output.append('\n');
- }
- indent--;
- for (int i=0; i<indent; i++) output.append('\t');
- return output.append('>');
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnJavadocMessageSend.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnJavadocMessageSend.java
deleted file mode 100644
index a88bcd9d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnJavadocMessageSend.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.complete;
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocMessageSend;
-
-public class CompletionOnJavadocMessageSend extends JavadocMessageSend implements CompletionOnJavadoc {
- public int completionFlags = JAVADOC;
- public int separatorPosition;
-
- public CompletionOnJavadocMessageSend(JavadocMessageSend method, int position) {
- super(method.selector, method.nameSourcePosition);
- this.arguments = method.arguments;
- this.receiver = method.receiver;
- this.sourceEnd = method.sourceEnd;
- this.tagValue = method.tagValue;
- this.separatorPosition = position;
- }
-
- public CompletionOnJavadocMessageSend(JavadocMessageSend method, int position, int flags) {
- this(method, position);
- this.completionFlags |= flags;
- }
-
- /**
- * @param flags The completionFlags to set.
- */
- public void addCompletionFlags(int flags) {
- this.completionFlags |= flags;
- }
-
- public boolean completeAnException() {
- return (this.completionFlags & EXCEPTION) != 0;
- }
-
- public boolean completeInText() {
- return (this.completionFlags & TEXT) != 0;
- }
-
- public boolean completeBaseTypes() {
- return (this.completionFlags & BASE_TYPES) != 0;
- }
-
- public boolean completeFormalReference() {
- return (this.completionFlags & FORMAL_REFERENCE) != 0;
- }
-
- /**
- * Get completion node flags.
- *
- * @return int Flags of the javadoc completion node.
- */
- public int getCompletionFlags() {
- return this.completionFlags;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.JavadocMessageSend#printExpression(int, java.lang.StringBuffer)
- */
- public StringBuffer printExpression(int indent, StringBuffer output) {
- output.append("<CompleteOnJavadocMessageSend:"); //$NON-NLS-1$
- super.printExpression(indent, output);
- indent++;
- if (this.completionFlags > 0) {
- output.append('\n');
- for (int i=0; i<indent; i++) output.append('\t');
- output.append("infos:"); //$NON-NLS-1$
- char separator = 0;
- if (completeAnException()) {
- output.append("exception"); //$NON-NLS-1$
- separator = ',';
- }
- if (completeInText()) {
- if (separator != 0) output.append(separator);
- output.append("text"); //$NON-NLS-1$
- separator = ',';
- }
- if (completeBaseTypes()) {
- if (separator != 0) output.append(separator);
- output.append("base types"); //$NON-NLS-1$
- separator = ',';
- }
- if (completeFormalReference()) {
- if (separator != 0) output.append(separator);
- output.append("formal reference"); //$NON-NLS-1$
- separator = ',';
- }
- output.append('\n');
- }
- indent--;
- for (int i=0; i<indent; i++) output.append('\t');
- return output.append('>');
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnJavadocParamNameReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnJavadocParamNameReference.java
deleted file mode 100644
index f107b69b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnJavadocParamNameReference.java
+++ /dev/null
@@ -1,60 +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.codeassist.complete;
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocSingleNameReference;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class CompletionOnJavadocParamNameReference extends JavadocSingleNameReference implements CompletionOnJavadoc {
- public int completionFlags = JAVADOC;
- public char[][] missingParams;
-
- public CompletionOnJavadocParamNameReference(char[] name, long pos, int start, int end) {
- super(name, pos, start, end);
- }
-
- public CompletionOnJavadocParamNameReference(JavadocSingleNameReference nameRef) {
- super(nameRef.token, (((long)nameRef.sourceStart)<<32)+nameRef.sourceEnd, nameRef.tagSourceStart, nameRef.tagSourceStart);
- }
-
- /**
- * @param flags The completionFlags to set.
- */
- public void addCompletionFlags(int flags) {
- this.completionFlags |= flags;
- }
-
- /**
- * Get completion node flags.
- *
- * @return int Flags of the javadoc completion node.
- */
- public int getCompletionFlags() {
- return this.completionFlags;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.AllocationExpression#printExpression(int, java.lang.StringBuffer)
- */
- public StringBuffer printExpression(int indent, StringBuffer output) {
- output.append("<CompletionOnJavadocParamNameReference:"); //$NON-NLS-1$
- if (this.token != null) super.printExpression(indent, output);
- return output.append('>');
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.SingleNameReference#reportError(org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public TypeBinding reportError(BlockScope scope) {
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnJavadocQualifiedTypeReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnJavadocQualifiedTypeReference.java
deleted file mode 100644
index b736dff7..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnJavadocQualifiedTypeReference.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.complete;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocQualifiedTypeReference;
-
-public class CompletionOnJavadocQualifiedTypeReference extends JavadocQualifiedTypeReference implements CompletionOnJavadoc {
- public int completionFlags = JAVADOC;
- public char[] completionIdentifier;
-
- public CompletionOnJavadocQualifiedTypeReference(char[][] sources, char[] identifier, long[] pos, int tagStart, int tagEnd) {
- super(sources, pos, tagStart, tagEnd);
- this.completionIdentifier = identifier;
- }
-
- public CompletionOnJavadocQualifiedTypeReference(JavadocQualifiedTypeReference typeRef) {
- super(typeRef.tokens, typeRef.sourcePositions, typeRef.tagSourceStart, typeRef.tagSourceStart);
- this.completionIdentifier = CharOperation.NO_CHAR;
- }
-
- /**
- * @param flags The completionFlags to set.
- */
- public void addCompletionFlags(int flags) {
- this.completionFlags |= flags;
- }
-
- public boolean completeAnException() {
- return (this.completionFlags & EXCEPTION) != 0;
- }
-
- public boolean completeInText() {
- return (this.completionFlags & TEXT) != 0;
- }
-
- public boolean completeBaseTypes() {
- return (this.completionFlags & BASE_TYPES) != 0;
- }
-
- public boolean completeFormalReference() {
- return (this.completionFlags & FORMAL_REFERENCE) != 0;
- }
-
- /**
- * Get completion node flags.
- *
- * @return int Flags of the javadoc completion node.
- */
- public int getCompletionFlags() {
- return this.completionFlags;
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedTypeReference#printExpression(int, java.lang.StringBuffer)
- */
- public StringBuffer printExpression(int indent, StringBuffer output) {
- output.append("<CompletionOnJavadocQualifiedTypeReference:"); //$NON-NLS-1$
- super.printExpression(indent, output);
- indent++;
- if (this.completionFlags > 0) {
- output.append('\n');
- for (int i=0; i<indent; i++) output.append('\t');
- output.append("infos:"); //$NON-NLS-1$
- char separator = 0;
- if (completeAnException()) {
- output.append("exception"); //$NON-NLS-1$
- separator = ',';
- }
- if (completeInText()) {
- if (separator != 0) output.append(separator);
- output.append("text"); //$NON-NLS-1$
- separator = ',';
- }
- if (completeBaseTypes()) {
- if (separator != 0) output.append(separator);
- output.append("base types"); //$NON-NLS-1$
- separator = ',';
- }
- if (completeFormalReference()) {
- if (separator != 0) output.append(separator);
- output.append("formal reference"); //$NON-NLS-1$
- separator = ',';
- }
- output.append('\n');
- }
- indent--;
- for (int i=0; i<indent; i++) output.append('\t');
- return output.append('>');
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnJavadocSingleTypeReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnJavadocSingleTypeReference.java
deleted file mode 100644
index 6add1e8e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnJavadocSingleTypeReference.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.complete;
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocSingleTypeReference;
-
-public class CompletionOnJavadocSingleTypeReference extends JavadocSingleTypeReference implements CompletionOnJavadoc {
- public int completionFlags = JAVADOC;
-
- public CompletionOnJavadocSingleTypeReference(char[] source, long pos, int tagStart, int tagEnd) {
- super(source, pos, tagStart, tagEnd);
- }
-
- public CompletionOnJavadocSingleTypeReference(JavadocSingleTypeReference typeRef) {
- super(typeRef.token, (((long)typeRef.sourceStart)<<32)+typeRef.sourceEnd, typeRef.tagSourceStart, typeRef.tagSourceStart);
- }
-
- /**
- * @param flags The completionFlags to set.
- */
- public void addCompletionFlags(int flags) {
- this.completionFlags |= flags;
- }
-
- public boolean completeAnException() {
- return (this.completionFlags & EXCEPTION) != 0;
- }
-
- public boolean completeInText() {
- return (this.completionFlags & TEXT) != 0;
- }
-
- public boolean completeBaseTypes() {
- return (this.completionFlags & BASE_TYPES) != 0;
- }
-
- public boolean completeFormalReference() {
- return (this.completionFlags & FORMAL_REFERENCE) != 0;
- }
-
- /**
- * Get completion node flags.
- *
- * @return int Flags of the javadoc completion node.
- */
- public int getCompletionFlags() {
- return this.completionFlags;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.SingleTypeReference#printExpression(int, java.lang.StringBuffer)
- */
- public StringBuffer printExpression(int indent, StringBuffer output) {
- output.append("<CompletionOnJavadocSingleTypeReference:"); //$NON-NLS-1$
- super.printExpression(indent, output);
- indent++;
- if (this.completionFlags > 0) {
- output.append('\n');
- for (int i=0; i<indent; i++) output.append('\t');
- output.append("infos:"); //$NON-NLS-1$
- char separator = 0;
- if (completeAnException()) {
- output.append("exception"); //$NON-NLS-1$
- separator = ',';
- }
- if (completeInText()) {
- if (separator != 0) output.append(separator);
- output.append("text"); //$NON-NLS-1$
- separator = ',';
- }
- if (completeBaseTypes()) {
- if (separator != 0) output.append(separator);
- output.append("base types"); //$NON-NLS-1$
- separator = ',';
- }
- if (completeFormalReference()) {
- if (separator != 0) output.append(separator);
- output.append("formal reference"); //$NON-NLS-1$
- separator = ',';
- }
- output.append('\n');
- }
- indent--;
- for (int i=0; i<indent; i++) output.append('\t');
- return output.append('>');
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnJavadocTag.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnJavadocTag.java
deleted file mode 100644
index 92fd1f9b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnJavadocTag.java
+++ /dev/null
@@ -1,167 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.complete;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocSingleNameReference;
-import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants;
-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.parser.JavadocTagConstants;
-
-public class CompletionOnJavadocTag extends JavadocSingleNameReference implements JavadocTagConstants, CompletionOnJavadoc {
- public int completionFlags = JAVADOC;
- public final static char[][][] NO_CHAR_CHAR_CHAR = new char[0][][];
- private char[][][] possibleTags = NO_CHAR_CHAR_CHAR;
-
- public CompletionOnJavadocTag(char[] source, long pos, int tagStart, int tagEnd, char[][][] possibleTags, boolean orphan) {
- super(source, pos, tagStart, tagEnd);
- this.possibleTags = possibleTags;
- if (orphan) this.completionFlags |= ALL_POSSIBLE_TAGS;
- }
-
- /**
- * @param flags The completionFlags to set.
- */
- public void addCompletionFlags(int flags) {
- this.completionFlags |= flags;
- }
-
- /**
- * Get completion node flags.
- *
- * @return int Flags of the javadoc completion node.
- */
- public int getCompletionFlags() {
- return this.completionFlags;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.AllocationExpression#printExpression(int, java.lang.StringBuffer)
- */
- public StringBuffer printExpression(int indent, StringBuffer output) {
- output.append("<CompleteOnJavadocTag:"); //$NON-NLS-1$
- output.append('@');
- if (this.token != null) super.printExpression(indent, output);
- // Print block tags
- char[][] blockTags = this.possibleTags[BLOCK_IDX];
- if (blockTags != null) {
- int length=blockTags.length;
- if (length > 0) {
- output.append("\npossible block tags:"); //$NON-NLS-1$
- for (int i=0; i<length; i++) {
- output.append("\n - "); //$NON-NLS-1$
- output.append(blockTags[i]);
- }
- output.append('\n');
- }
- }
- // Print inline tags
- char[][] inlineTags = this.possibleTags[INLINE_IDX];
- if (inlineTags != null) {
- int length=inlineTags.length;
- if (length > 0) {
- output.append("\npossible inline tags:"); //$NON-NLS-1$
- for (int i=0; i<length; i++) {
- output.append("\n - "); //$NON-NLS-1$
- output.append(inlineTags[i]);
- }
- output.append('\n');
- }
- }
- return output.append('>');
- }
-
- public void filterPossibleTags(Scope scope) {
- if (this.possibleTags == null || this.possibleTags.length == 0 || (this.completionFlags & ALL_POSSIBLE_TAGS) != 0) {
- return;
- }
- int kind = scope.kind;
- char[][] specifiedTags = null;
- switch (kind) {
- case Scope.COMPILATION_UNIT_SCOPE:
- case Scope.CLASS_SCOPE:
- specifiedTags = CLASS_TAGS;
- break;
- case Scope.METHOD_SCOPE:
- MethodScope methodScope = (MethodScope) scope;
- if (methodScope.referenceMethod() == null) {
- if (methodScope.initializedField == null) {
- specifiedTags = PACKAGE_TAGS;
- } else {
- specifiedTags = FIELD_TAGS;
- }
- } else {
- specifiedTags = METHOD_TAGS;
- }
- break;
- default:
- return;
- }
- int kinds = this.possibleTags.length;
- for (int k=0; k<kinds; k++) {
- int length = this.possibleTags[k].length;
- int specLenth = specifiedTags.length;
- char[][] filteredTags = new char[length][];
- int size = 0;
- for (int i=0; i<length; i++) {
- char[] possibleTag = this.possibleTags[k][i];
- for (int j=0; j<specLenth; j++) {
- if (possibleTag[0] == specifiedTags[j][0] && CharOperation.equals(possibleTag, specifiedTags[j])) {
- if (possibleTag == TAG_PARAM) {
- switch (scope.kind) {
- case Scope.CLASS_SCOPE:
- if (scope.compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5) {
-// if (((ClassScope)scope).referenceContext.binding.isGenericType()) {
-// filteredTags[size++] = possibleTag;
-// }
- }
- break;
- case Scope.COMPILATION_UNIT_SCOPE:
- if (scope.compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5) {
- filteredTags[size++] = possibleTag;
- }
- break;
- default:
- filteredTags[size++] = possibleTag;
- break;
- }
- } else {
- filteredTags[size++] = possibleTag;
- }
- break;
- }
- }
- }
- if (size<length) {
- System.arraycopy(filteredTags, 0, this.possibleTags[k] = new char[size][], 0, size);
- }
- }
- }
-
- /**
- * Return possible block tags
- *
- * @return char[][]
- */
- public char[][] getPossibleBlockTags() {
- return this.possibleTags[BLOCK_IDX];
- }
-
- /**
- * Return possible inline tags
- *
- * @return char[][]
- */
- public char[][] getPossibleInlineTags() {
- return this.possibleTags[INLINE_IDX];
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnKeyword.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnKeyword.java
deleted file mode 100644
index 0a9c3d9e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnKeyword.java
+++ /dev/null
@@ -1,18 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.complete;
-
-public interface CompletionOnKeyword {
-
- char[] getToken();
- char[][] getPossibleKeywords();
- boolean canCompleteEmptyToken();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnKeyword1.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnKeyword1.java
deleted file mode 100644
index 634c08cf..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnKeyword1.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.complete;
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.SingleTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Scope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class CompletionOnKeyword1 extends SingleTypeReference implements CompletionOnKeyword {
- private char[][] possibleKeywords;
- public boolean canCompleteEmptyToken;
-
- public CompletionOnKeyword1(char[] token, long pos, char[] possibleKeyword) {
- this(token, pos, new char[][]{possibleKeyword});
- }
- public CompletionOnKeyword1(char[] token, long pos, char[][] possibleKeywords) {
- super(token, pos);
- this.possibleKeywords = possibleKeywords;
- }
- public boolean canCompleteEmptyToken() {
- return this.canCompleteEmptyToken;
- }
- public char[] getToken() {
- return token;
- }
- public char[][] getPossibleKeywords() {
- return possibleKeywords;
- }
- public void aboutToResolve(Scope scope) {
- getTypeBinding(scope);
- }
- protected TypeBinding getTypeBinding(Scope scope) {
- throw new CompletionNodeFound(this, scope);
- }
- public StringBuffer printExpression(int indent, StringBuffer output){
-
- return output.append("<CompleteOnKeyword:").append(token).append('>'); //$NON-NLS-1$
- }
-}
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
deleted file mode 100644
index 0750b020..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnKeyword2.java
+++ /dev/null
@@ -1,36 +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.codeassist.complete;
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.ImportReference;
-
-public class CompletionOnKeyword2 extends ImportReference implements CompletionOnKeyword {
- private char[] token;
- private char[][] possibleKeywords;
- public CompletionOnKeyword2(char[] token, long pos, char[][] possibleKeywords) {
- super(new char[][]{token}, new long[]{pos}, false);
- this.token = token;
- this.possibleKeywords = possibleKeywords;
- }
- public boolean canCompleteEmptyToken() {
- return false;
- }
- public char[] getToken() {
- return token;
- }
- public char[][] getPossibleKeywords() {
- return possibleKeywords;
- }
- public StringBuffer print(int indent, StringBuffer output, boolean withOnDemand) {
-
- return printIndent(indent, output).append("<CompleteOnKeyword:").append(token).append('>'); //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnKeyword3.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnKeyword3.java
deleted file mode 100644
index 2ffa8915..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnKeyword3.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.complete;
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.SingleNameReference;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class CompletionOnKeyword3 extends SingleNameReference implements CompletionOnKeyword{
- private char[][] possibleKeywords;
- public CompletionOnKeyword3(char[] token, long pos, char[] possibleKeyword) {
- this(token, pos, new char[][]{possibleKeyword});
- }
- public CompletionOnKeyword3(char[] token, long pos, char[][] possibleKeywords) {
- super(token, pos);
- this.token = token;
- this.possibleKeywords = possibleKeywords;
- }
- public boolean canCompleteEmptyToken() {
- return false;
- }
- public char[] getToken() {
- return token;
- }
- public char[][] getPossibleKeywords() {
- return possibleKeywords;
- }
- public StringBuffer printExpression(int indent, StringBuffer output) {
-
- return output.append("<CompleteOnKeyword:").append(token).append('>'); //$NON-NLS-1$
- }
- public TypeBinding resolveType(BlockScope scope) {
- throw new CompletionNodeFound(this, scope);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnLocalName.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnLocalName.java
deleted file mode 100644
index 0a3816d4..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnLocalName.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.complete;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-
-
-public class CompletionOnLocalName extends LocalDeclaration {
- private static final char[] FAKENAMESUFFIX = " ".toCharArray(); //$NON-NLS-1$
- public char[] realName;
-
- public CompletionOnLocalName(char[] name, int sourceStart, int sourceEnd){
-
- super(CharOperation.concat(name, FAKENAMESUFFIX), sourceStart, sourceEnd);
- this.realName = name;
- }
-
- public void resolve(BlockScope scope) {
-
- super.resolve(scope);
- throw new CompletionNodeFound(this, scope);
- }
-
- public StringBuffer printAsExpression(int indent, StringBuffer output) {
- printIndent(indent, output);
- output.append("<CompleteOnLocalName:"); //$NON-NLS-1$
- if (type != null) type.print(0, output).append(' ');
- output.append(this.realName);
- if (initialization != null) {
- output.append(" = "); //$NON-NLS-1$
- initialization.printExpression(0, output);
- }
- return output.append('>');
- }
-
- public StringBuffer printStatement(int indent, StringBuffer output) {
- this.printAsExpression(indent, output);
- return output.append(';');
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnMemberAccess.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnMemberAccess.java
deleted file mode 100644
index 17cf18ce..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnMemberAccess.java
+++ /dev/null
@@ -1,118 +0,0 @@
-/*******************************************************************************
- * 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.codeassist.complete;
-
-/*
- * Completion node build by the parser in any case it was intending to
- * reduce an access to a member (field reference or message send)
- * containing the completion identifier.
- * e.g.
- *
- * class X {
- * void foo() {
- * bar().fred[cursor]
- * }
- * }
- *
- * ---> class X {
- * void foo() {
- * <CompleteOnMemberAccess:bar().fred>
- * }
- * }
- *
- * The source range of the completion node denotes the source range
- * which should be replaced by the completion.
- */
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode;
-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.MessageSend;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ThisReference;
-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.ProblemMethodBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ProblemReasons;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class CompletionOnMemberAccess extends FieldReference {
-
- public boolean isInsideAnnotation;
- public boolean isStatic;
-
- public CompletionOnMemberAccess(char[] source, long pos, boolean isInsideAnnotation) {
-
- super(source, pos);
- this.isInsideAnnotation = isInsideAnnotation;
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output) {
-
- output.append("<CompleteOnMemberAccess:"); //$NON-NLS-1$
- return super.printExpression(0, output).append('>');
- }
-
- public TypeBinding resolveType(BlockScope scope) {
-
- this.receiverType = receiver.resolveType(scope);
- if (scope.getJavaLangFunction().equals(this.receiverType))
- {
- Binding typeBinding = receiver.alternateBinding();
- if (typeBinding instanceof TypeBinding)
- {
- this.receiverType=(TypeBinding)typeBinding;
- isStatic=true;
- }
- }
- if ((receiver.bits&Binding.TYPE)!=0)
- isStatic=true;
- if(this.receiverType != null && this.receiverType.isAnonymousType())
- isStatic=false;
-
- if (this.receiverType == null && receiver instanceof MessageSend) {
- MessageSend messageSend = (MessageSend) receiver;
- if(messageSend.receiver instanceof ThisReference) {
- Expression[] arguments = messageSend.arguments;
- int length = arguments == null ? 0 : arguments.length;
- TypeBinding[] argBindings = new TypeBinding[length];
- for (int i = 0; i < length; i++) {
- argBindings[i] = arguments[i].resolvedType;
- if(argBindings[i] == null || !argBindings[i].isValidBinding()) {
- throw new CompletionNodeFound();
- }
- }
-
- ProblemMethodBinding problemMethodBinding = new ProblemMethodBinding(messageSend.selector, argBindings, ProblemReasons.NotFound);
- throw new CompletionNodeFound(this, problemMethodBinding, scope);
- }
- }
-
- if (this.receiverType == null || this.receiverType.isBaseType())
- throw new CompletionNodeFound(this, scope);
- else
- throw new CompletionNodeFound(this, this.receiverType, scope);
- // array types are passed along to find the length field
- }
-
- public TypeBinding resolveForAllocation(BlockScope scope, ASTNode location) {
- throw new CompletionNodeFound(this, scope);
- }
-
- /**
- *
- * @return <code>true</code> because this node is special because it is a completion node
- *
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.Expression#isSpecialNode()
- */
- public boolean isSpecialNode() {
- return true;
- }
-}
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
deleted file mode 100644
index 04c3da6d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnMessageSend.java
+++ /dev/null
@@ -1,73 +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.codeassist.complete;
-
-/*
- * Completion node build by the parser in any case it was intending to
- * reduce a message send containing the cursor.
- * e.g.
- *
- * class X {
- * void foo() {
- * this.bar(1, 2, [cursor]
- * }
- * }
- *
- * ---> class X {
- * void foo() {
- * <CompleteOnMessageSend:this.bar(1, 2)>
- * }
- * }
- *
- * The source range is always of length 0.
- * The arguments of the message send are all the arguments defined
- * before the cursor.
- */
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.MessageSend;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class CompletionOnMessageSend extends MessageSend {
-
- public TypeBinding resolveType(BlockScope scope) {
- if (arguments != null) {
- int argsLength = arguments.length;
- for (int a = argsLength; --a >= 0;)
- arguments[a].resolveType(scope);
- }
-
- if (receiver==null || receiver.isImplicitThis())
- throw new CompletionNodeFound(this, null, scope);
-
- this.actualReceiverType = receiver.resolveType(scope);
- if (this.actualReceiverType == null || this.actualReceiverType.isBaseType())
- throw new CompletionNodeFound();
-
- if (this.actualReceiverType.isArrayType())
- this.actualReceiverType = scope.getJavaLangObject();
- throw new CompletionNodeFound(this, this.actualReceiverType, scope);
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output) {
-
- output.append("<CompleteOnMessageSend:"); //$NON-NLS-1$
- if (receiver!=null && !receiver.isImplicitThis()) receiver.printExpression(0, output).append('.');
- output.append(selector).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(")>"); //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnMessageSendName.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnMessageSendName.java
deleted file mode 100644
index 2b0be381..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnMessageSendName.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 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.complete;
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.MessageSend;
-import org.eclipse.wst.jsdt.internal.compiler.ast.NameReference;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class CompletionOnMessageSendName extends MessageSend {
- public CompletionOnMessageSendName(char[] selector, int start, int end) {
- super();
- this.selector = selector;
- this.sourceStart = start;
- this.sourceEnd = end;
- this.nameSourcePosition = end;
- }
-
- public TypeBinding resolveType(BlockScope scope) {
-
- if (receiver==null || receiver.isImplicitThis())
- throw new CompletionNodeFound();
-
- this.actualReceiverType = receiver.resolveType(scope);
- if (this.actualReceiverType == null || this.actualReceiverType.isBaseType() || this.actualReceiverType.isArrayType())
- throw new CompletionNodeFound();
-
- if(this.receiver instanceof NameReference) {
- throw new CompletionNodeFound(this, ((NameReference)this.receiver).binding, scope);
- } else if(this.receiver instanceof MessageSend) {
- throw new CompletionNodeFound(this, ((MessageSend)this.receiver).binding, scope);
- }
- throw new CompletionNodeFound(this, this.actualReceiverType, scope);
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output) {
-
- output.append("<CompleteOnMessageSendName:"); //$NON-NLS-1$
- if (receiver!=null && receiver.isImplicitThis()) receiver.printExpression(0, output).append('.');
- output.append(selector).append('(');
- return output.append(")>"); //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnMethodName.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnMethodName.java
deleted file mode 100644
index 1150b17e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnMethodName.java
+++ /dev/null
@@ -1,46 +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.codeassist.complete;
-
-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.ClassScope;
-
-public class CompletionOnMethodName extends MethodDeclaration {
- public int selectorEnd;
-
- public CompletionOnMethodName(CompilationResult compilationResult){
- super(compilationResult);
- }
-
- public StringBuffer print(int indent, StringBuffer output) {
-
- printIndent(indent, output);
- output.append("<CompletionOnMethodName:"); //$NON-NLS-1$
- printModifiers(this.modifiers, output);
- printReturnType(0, output);
- output.append(selector).append('(');
- if (arguments != null) {
- for (int i = 0; i < arguments.length; i++) {
- if (i > 0) output.append(", "); //$NON-NLS-1$
- arguments[i].print(0, output);
- }
- }
- output.append(')');
- return output.append('>');
- }
-
- public void resolve(ClassScope upperScope) {
-
- super.resolve(upperScope);
- throw new CompletionNodeFound(this, upperScope);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnQualifiedAllocationExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnQualifiedAllocationExpression.java
deleted file mode 100644
index cd6576d0..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnQualifiedAllocationExpression.java
+++ /dev/null
@@ -1,74 +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.codeassist.complete;
-
-/*
- * Completion node build by the parser in any case it was intending to
- * reduce an allocation expression containing the cursor.
- * If the allocation expression is not qualified, the enclosingInstance field
- * is null.
- * e.g.
- *
- * class X {
- * void foo() {
- * new Bar(1, 2, [cursor]
- * }
- * }
- *
- * ---> class X {
- * void foo() {
- * <CompleteOnAllocationExpression:new Bar(1, 2)>
- * }
- * }
- *
- * The source range is always of length 0.
- * The arguments of the allocation expression are all the arguments defined
- * before the cursor.
- */
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedAllocationExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.SingleTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class CompletionOnQualifiedAllocationExpression extends QualifiedAllocationExpression {
-public TypeBinding resolveType(BlockScope scope) {
- if (arguments != null) {
- int argsLength = arguments.length;
- for (int a = argsLength; --a >= 0;)
- arguments[a].resolveType(scope);
- }
-
- if (enclosingInstance != null) {
- TypeBinding enclosingType = enclosingInstance.resolveType(scope);
- if (enclosingType == null || !(enclosingType instanceof ReferenceBinding)) {
- throw new CompletionNodeFound();
- }
- this.resolvedType = ((SingleTypeReference) type).resolveTypeEnclosing(scope, (ReferenceBinding) enclosingType);
- if (!(this.resolvedType instanceof ReferenceBinding))
- throw new CompletionNodeFound(); // no need to continue if its an array or base type
- } else {
- this.resolvedType = type.resolveType(scope, true /* check bounds*/);
- if (!(this.resolvedType instanceof ReferenceBinding))
- throw new CompletionNodeFound(); // no need to continue if its an array or base type
- }
-
- throw new CompletionNodeFound(this, this.resolvedType, scope);
-}
-public StringBuffer printExpression(int indent, StringBuffer output) {
- if (this.enclosingInstance == null)
- output.append("<CompleteOnAllocationExpression:" ); //$NON-NLS-1$
- else
- output.append("<CompleteOnQualifiedAllocationExpression:"); //$NON-NLS-1$
- return super.printExpression(indent, output).append('>');
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnQualifiedNameReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnQualifiedNameReference.java
deleted file mode 100644
index 984700bf..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnQualifiedNameReference.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.complete;
-
-/*
- * Completion node build by the parser in any case it was intending to
- * reduce a qualified name reference containing the completion identifier.
- * e.g.
- *
- * class X {
- * Y y;
- * void foo() {
- * y.fred.ba[cursor]
- * }
- * }
- *
- * ---> class X {
- * Y y;
- * void foo() {
- * <CompleteOnName:y.fred.ba>
- * }
- * }
- *
- * The source range of the completion node denotes the source range
- * which should be replaced by the completion.
- */
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedNameReference;
-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.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.TypeBinding;
-
-public class CompletionOnQualifiedNameReference extends QualifiedNameReference {
- public char[] completionIdentifier;
- public boolean isInsideAnnotationAttribute;
-public CompletionOnQualifiedNameReference(char[][] previousIdentifiers, char[] completionIdentifier, long[] positions, boolean isInsideAnnotationAttribute) {
- super(previousIdentifiers, positions, (int) (positions[0] >>> 32), (int) positions[positions.length - 1]);
- this.completionIdentifier = completionIdentifier;
- this.isInsideAnnotationAttribute = isInsideAnnotationAttribute;
-}
-public StringBuffer printExpression(int indent, StringBuffer output) {
-
- output.append("<CompleteOnName:"); //$NON-NLS-1$
- for (int i = 0; i < tokens.length; i++) {
- output.append(tokens[i]);
- output.append('.');
- }
- output.append(completionIdentifier).append('>');
- return output;
-}
-public TypeBinding resolveType(BlockScope scope) {
- // it can be a package, type, member type, local variable or field
- binding = scope.getBinding(tokens, this);
- if (!binding.isValidBinding()) {
- if (binding instanceof ProblemFieldBinding) {
- scope.problemReporter().invalidField(this, (FieldBinding) binding);
- } else if (binding instanceof ProblemReferenceBinding) {
- scope.problemReporter().invalidType(this, (TypeBinding) binding);
- } else {
- scope.problemReporter().unresolvableReference(this, binding);
- }
-
- if (binding.problemId() == ProblemReasons.NotFound) {
- throw new CompletionNodeFound(this, binding, scope);
- }
-
- throw new CompletionNodeFound();
- }
-
- throw new CompletionNodeFound(this, binding, scope);
-}
-
-
-public boolean isSpecialNode()
-{
- return true;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnQualifiedType.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnQualifiedType.java
deleted file mode 100644
index fbdd9428..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnQualifiedType.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.complete;
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedNameReference;
-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.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.TypeBinding;
-
-public class CompletionOnQualifiedType extends
-QualifiedNameReference {
-
-
- public char[] completionIdentifier;
-public CompletionOnQualifiedType(char[][] previousIdentifiers, char[] completionIdentifier, long[] positions) {
- super(previousIdentifiers, positions, (int) (positions[0] >>> 32), (int) positions[positions.length - 1]);
- this.completionIdentifier = completionIdentifier;
-}
-public StringBuffer printExpression(int indent, StringBuffer output) {
-
- output.append("<CompleteOnName:"); //$NON-NLS-1$
- for (int i = 0; i < tokens.length; i++) {
- output.append(tokens[i]);
- output.append('.');
- }
- output.append(completionIdentifier).append('>');
- return output;
-}
-
-public TypeBinding resolveType(BlockScope scope) {
- // it can be a package, type, member type, local variable or field
- binding = scope.getBinding(tokens, this);
- if (!binding.isValidBinding()) {
- if (binding instanceof ProblemFieldBinding) {
- scope.problemReporter().invalidField(this, (FieldBinding) binding);
- } else if (binding instanceof ProblemReferenceBinding) {
- scope.problemReporter().invalidType(this, (TypeBinding) binding);
- } else {
- scope.problemReporter().unresolvableReference(this, binding);
- }
-
- if (binding.problemId() == ProblemReasons.NotFound) {
- throw new CompletionNodeFound(this, binding, scope);
- }
-
- throw new CompletionNodeFound();
- }
-
- throw new CompletionNodeFound(this, binding, scope);
-}
-
-
-public boolean isSpecialNode()
-{
- return true;
-}
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnQualifiedTypeReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnQualifiedTypeReference.java
deleted file mode 100644
index c6f5ada9..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnQualifiedTypeReference.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.complete;
-
-/*
- * Completion node build by the parser in any case it was intending to
- * reduce a type reference containing the completion identifier as part
- * of a qualified name.
- * e.g.
- *
- * class X extends java.lang.Obj[cursor]
- *
- * ---> class X extends <CompleteOnType:java.lang.Obj>
- *
- * The source range of the completion node denotes the source range
- * which should be replaced by the completion.
- */
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedTypeReference;
-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.Scope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class CompletionOnQualifiedTypeReference extends QualifiedTypeReference {
- public static final int K_TYPE = 0;
- public static final int K_CLASS = 1;
- public static final int K_INTERFACE = 2;
- public static final int K_EXCEPTION = 3;
-
- private int kind = K_TYPE;
- public char[] completionIdentifier;
-public CompletionOnQualifiedTypeReference(char[][] previousIdentifiers, char[] completionIdentifier, long[] positions) {
- this(previousIdentifiers, completionIdentifier, positions, K_TYPE);
-}
-public CompletionOnQualifiedTypeReference(char[][] previousIdentifiers, char[] completionIdentifier, long[] positions, int kind) {
- super(previousIdentifiers, positions);
- this.completionIdentifier = completionIdentifier;
- this.kind = kind;
-}
-public void aboutToResolve(Scope scope) {
- getTypeBinding(scope);
-}
-/*
- * No expansion of the completion reference into an array one
- */
-public TypeReference copyDims(int dim){
- return this;
-}
-protected TypeBinding getTypeBinding(Scope scope) {
- // it can be a package, type or member type
- Binding binding = scope.parent.getTypeOrPackage(tokens); // step up from the ClassScope
- if (!binding.isValidBinding()) {
- scope.problemReporter().invalidType(this, (TypeBinding) binding);
- throw new CompletionNodeFound();
- }
-
- throw new CompletionNodeFound(this, binding, scope);
-}
-public boolean isClass(){
- return this.kind == K_CLASS;
-}
-
-public boolean isInterface(){
- return this.kind == K_INTERFACE;
-}
-
-public boolean isException(){
- return this.kind == K_EXCEPTION;
-}
-public boolean isSuperType(){
- return this.kind == K_CLASS || this.kind == K_INTERFACE;
-}
-public StringBuffer printExpression(int indent, StringBuffer output) {
- switch (this.kind) {
- case K_CLASS :
- output.append("<CompleteOnClass:");//$NON-NLS-1$
- break;
- case K_INTERFACE :
- output.append("<CompleteOnInterface:");//$NON-NLS-1$
- break;
- case K_EXCEPTION :
- output.append("<CompleteOnException:");//$NON-NLS-1$
- break;
- default :
- output.append("<CompleteOnType:");//$NON-NLS-1$
- break;
- }
- for (int i = 0; i < tokens.length; i++) {
- output.append(tokens[i]);
- output.append('.');
- }
- output.append(completionIdentifier).append('>');
- return output;
-}
-}
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
deleted file mode 100644
index 60380cbf..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnSingleNameReference.java
+++ /dev/null
@@ -1,77 +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.codeassist.complete;
-
-/*
- * Completion node build by the parser in any case it was intending to
- * reduce a single name reference containing the completion identifier.
- * e.g.
- *
- * class X {
- * void foo() {
- * ba[cursor]
- * }
- * }
- *
- * ---> class X {
- * void foo() {
- * <CompleteOnName:ba>
- * }
- * }
- *
- * The source range of the completion node denotes the source range
- * which should be replaced by the completion.
- */
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode;
-import org.eclipse.wst.jsdt.internal.compiler.ast.SingleNameReference;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class CompletionOnSingleNameReference extends SingleNameReference {
-
- public char[][] possibleKeywords;
- public boolean canBeExplicitConstructor;
- public boolean isInsideAnnotationAttribute;
-
- public CompletionOnSingleNameReference(char[] source, long pos, boolean isInsideAnnotationAttribute) {
- this(source, pos, null, false, isInsideAnnotationAttribute);
- }
-
- public CompletionOnSingleNameReference(char[] source, long pos, char[][] possibleKeywords, boolean canBeExplicitConstructor, boolean isInsideAnnotationAttribute) {
- super(source, (pos>=0)?pos : 0);
- this.possibleKeywords = possibleKeywords;
- this.canBeExplicitConstructor = canBeExplicitConstructor;
- this.isInsideAnnotationAttribute = isInsideAnnotationAttribute;
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output) {
-
- output.append("<CompleteOnName:"); //$NON-NLS-1$
- return super.printExpression(0, output).append('>');
- }
-
- public TypeBinding resolveType(BlockScope scope) {
- if(scope instanceof MethodScope) {
- throw new CompletionNodeFound(this, scope, false);
- }
- throw new CompletionNodeFound(this, scope);
- }
-
- public TypeBinding resolveForAllocation(BlockScope scope, ASTNode location) {
- throw new CompletionNodeFound(this, scope);
- }
- public boolean isSpecialNode()
- {
- return true;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnSingleTypeName.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnSingleTypeName.java
deleted file mode 100644
index c906006f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnSingleTypeName.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.complete;
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode;
-import org.eclipse.wst.jsdt.internal.compiler.ast.SingleNameReference;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Scope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class CompletionOnSingleTypeName extends SingleNameReference {
-
- public CompletionOnSingleTypeName(char[] source, long pos) {
- super(source, pos);
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output) {
-
- output.append("<CompleteOnType:"); //$NON-NLS-1$
- return output.append(token).append('>');
- }
- public void aboutToResolve(Scope scope) {
- throw new CompletionNodeFound(this, scope);
- }
-
- public boolean isSpecialNode()
- {
- return true;
- }
-
- public TypeBinding resolveType(BlockScope scope) {
- throw new CompletionNodeFound(this, scope);
- }
-
- public TypeBinding resolveForAllocation(BlockScope scope, ASTNode location)
- {
- throw new CompletionNodeFound(this, scope);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnSingleTypeReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnSingleTypeReference.java
deleted file mode 100644
index e8d7eb5e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnSingleTypeReference.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*******************************************************************************
- * 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.codeassist.complete;
-
-/*
- * Completion node build by the parser in any case it was intending to
- * reduce a type reference containing the completion identifier as a single
- * name reference.
- * e.g.
- *
- * class X extends Obj[cursor]
- *
- * ---> class X extends <CompleteOnType:Obj>
- *
- * The source range of the completion node denotes the source range
- * which should be replaced by the completion.
- */
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode;
-import org.eclipse.wst.jsdt.internal.compiler.ast.SingleTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-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;
-
-public class CompletionOnSingleTypeReference extends SingleTypeReference {
- public static final int K_TYPE = 0;
- public static final int K_CLASS = 1;
- public static final int K_INTERFACE = 2;
- public static final int K_EXCEPTION = 3;
-
- private int kind = K_TYPE;
- public boolean isCompletionNode;
- public boolean isConstructorType;
- public CompletionOnFieldType fieldTypeCompletionNode;
-
- public CompletionOnSingleTypeReference(char[] source, long pos) {
- this(source, pos, K_TYPE);
- }
- public CompletionOnSingleTypeReference(char[] source, long pos, int kind) {
- super(source, pos);
- isCompletionNode = true;
- this.kind = kind;
- }
- public void aboutToResolve(Scope scope) {
- getTypeBinding(scope);
- }
- /*
- * No expansion of the completion reference into an array one
- */
- public TypeReference copyDims(int dim){
- return this;
- }
- protected TypeBinding getTypeBinding(Scope scope) {
- if (this.fieldTypeCompletionNode != null) {
- throw new CompletionNodeFound(this.fieldTypeCompletionNode, scope);
- }
- if(isCompletionNode) {
- throw new CompletionNodeFound(this, scope);
- } else {
- return super.getTypeBinding(scope);
- }
- }
- public boolean isClass(){
- return this.kind == K_CLASS;
- }
- public boolean isInterface(){
- return this.kind == K_INTERFACE;
- }
- public boolean isException(){
- return this.kind == K_EXCEPTION;
- }
- public boolean isSuperType(){
- return this.kind == K_CLASS || this.kind == K_INTERFACE;
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output){
- switch (this.kind) {
- case K_CLASS :
- output.append("<CompleteOnClass:");//$NON-NLS-1$
- break;
- case K_INTERFACE :
- output.append("<CompleteOnInterface:");//$NON-NLS-1$
- break;
- case K_EXCEPTION :
- output.append("<CompleteOnException:");//$NON-NLS-1$
- break;
- default :
- output.append("<CompleteOnType:");//$NON-NLS-1$
- break;
- }
- return output.append(token).append('>');
- }
-
- public TypeBinding resolveTypeEnclosing(BlockScope scope, ReferenceBinding enclosingType) {
- if (this.fieldTypeCompletionNode != null) {
- throw new CompletionNodeFound(this.fieldTypeCompletionNode, scope);
- }
- if(isCompletionNode) {
- throw new CompletionNodeFound(this, enclosingType, scope);
- } else {
- return super.resolveTypeEnclosing(scope, enclosingType);
- }
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.Expression#resolve(org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public void resolve(BlockScope scope) {
- super.resolve(scope);
-
- throw new CompletionNodeFound(this, scope);
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference#resolveType(org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope, boolean)
- */
- public TypeBinding resolveType(BlockScope scope, boolean checkBounds) {
- super.resolveType(scope, checkBounds);
-
- throw new CompletionNodeFound(this, scope);
- }
-
- /**
- *
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.Expression#resolveForAllocation(org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope, org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode)
- */
- public TypeBinding resolveForAllocation(BlockScope scope, ASTNode location) {
- return this.resolveType(scope);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnStringLiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnStringLiteral.java
deleted file mode 100644
index 552648a3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnStringLiteral.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.complete;
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.StringLiteral;
-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.TypeBinding;
-
-/*
- * Completion node build by the parser in any case it was intending to
- * reduce a string literal.
- * e.g.
- *
- * class X {
- * void foo() {
- * String s = "a[cursor]"
- * }
- * }
- *
- * ---> class X {
- * void foo() {
- * String s = <CompleteOnStringLiteral:a>
- * }
- * }
- */
-
-public class CompletionOnStringLiteral extends StringLiteral {
- public int contentStart;
- public int contentEnd;
- public CompletionOnStringLiteral(char[] token, int s, int e, int cs, int ce, int lineNumber) {
- super(token, s, e, lineNumber);
- this.contentStart = cs;
- this.contentEnd = ce;
- }
-
- public CompletionOnStringLiteral(int s, int e, int cs, int ce) {
- super(s,e);
- this.contentStart = cs;
- this.contentEnd = ce;
- }
- public TypeBinding resolveType(ClassScope scope) {
- throw new CompletionNodeFound(this, null, scope);
- }
- public TypeBinding resolveType(BlockScope scope) {
- throw new CompletionNodeFound(this, null, scope);
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output) {
- output.append("<CompletionOnString:"); //$NON-NLS-1$
- output = super.printExpression(indent, output);
- return output.append('>');
- }
-}
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
deleted file mode 100644
index ad21bd1a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionParser.java
+++ /dev/null
@@ -1,3331 +0,0 @@
-/*******************************************************************************
- * 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.codeassist.complete;
-
-/*
- * Parser able to build specific completion parse nodes, given a cursorLocation.
- *
- * Cursor location denotes the position of the last character behind which completion
- * got requested:
- * -1 means completion at the very beginning of the source
- * 0 means completion behind the first character
- * n means completion behind the n-th character
- */
-
-import org.eclipse.wst.jsdt.core.ast.IExpression;
-import org.eclipse.wst.jsdt.core.ast.IFieldReference;
-import org.eclipse.wst.jsdt.core.ast.ISingleNameReference;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.codeassist.impl.AssistParser;
-import org.eclipse.wst.jsdt.internal.codeassist.impl.Keywords;
-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.ArrayAllocationExpression;
-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.Block;
-import org.eclipse.wst.jsdt.internal.compiler.ast.CaseStatement;
-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.ConstructorDeclaration;
-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.FieldDeclaration;
-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.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.OR_OR_Expression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.PrefixExpression;
-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.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.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.classfmt.ClassFileConstants;
-import org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit;
-import org.eclipse.wst.jsdt.internal.compiler.parser.JavadocParser;
-import org.eclipse.wst.jsdt.internal.compiler.parser.RecoveredBlock;
-import org.eclipse.wst.jsdt.internal.compiler.parser.RecoveredElement;
-import org.eclipse.wst.jsdt.internal.compiler.parser.RecoveredField;
-import org.eclipse.wst.jsdt.internal.compiler.parser.RecoveredInitializer;
-import org.eclipse.wst.jsdt.internal.compiler.parser.RecoveredLocalVariable;
-import org.eclipse.wst.jsdt.internal.compiler.parser.RecoveredMethod;
-import org.eclipse.wst.jsdt.internal.compiler.parser.RecoveredType;
-import org.eclipse.wst.jsdt.internal.compiler.parser.RecoveredUnit;
-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.Util;
-
-public class CompletionParser extends AssistParser {
- // OWNER
- protected static final int COMPLETION_PARSER = 1024;
- protected static final int COMPLETION_OR_ASSIST_PARSER = ASSIST_PARSER + COMPLETION_PARSER;
-
- // KIND : all values known by CompletionParser are between 1025 and 1549
- protected static final int K_BLOCK_DELIMITER = COMPLETION_PARSER + 1; // whether we are inside a block
- protected static final int K_SELECTOR_INVOCATION_TYPE = COMPLETION_PARSER + 2; // whether we are inside a message send
- protected static final int K_SELECTOR_QUALIFIER = COMPLETION_PARSER + 3; // whether we are inside a message send
- protected static final int K_BETWEEN_CATCH_AND_RIGHT_PAREN = COMPLETION_PARSER + 4; // whether we are between the keyword 'catch' and the following ')'
- protected static final int K_NEXT_TYPEREF_IS_CLASS = COMPLETION_PARSER + 5; // whether the next type reference is a class
- protected static final int K_NEXT_TYPEREF_IS_INTERFACE = COMPLETION_PARSER + 6; // whether the next type reference is an interface
- protected static final int K_NEXT_TYPEREF_IS_EXCEPTION = COMPLETION_PARSER + 7; // whether the next type reference is an exception
- protected static final int K_BETWEEN_NEW_AND_LEFT_BRACKET = COMPLETION_PARSER + 8; // whether we are between the keyword 'new' and the following left braket, ie. '[', '(' or '{'
- protected static final int K_INSIDE_THROW_STATEMENT = COMPLETION_PARSER + 9; // whether we are between the keyword 'throw' and the end of a throw statement
- protected static final int K_INSIDE_RETURN_STATEMENT = COMPLETION_PARSER + 10; // whether we are between the keyword 'return' and the end of a return statement
- protected static final int K_CAST_STATEMENT = COMPLETION_PARSER + 11; // whether we are between ')' and the end of a cast statement
- protected static final int K_LOCAL_INITIALIZER_DELIMITER = COMPLETION_PARSER + 12;
- protected static final int K_ARRAY_INITIALIZER = COMPLETION_PARSER + 13;
- protected static final int K_ARRAY_CREATION = COMPLETION_PARSER + 14;
- protected static final int K_UNARY_OPERATOR = COMPLETION_PARSER + 15;
- protected static final int K_BINARY_OPERATOR = COMPLETION_PARSER + 16;
- protected static final int K_ASSISGNMENT_OPERATOR = COMPLETION_PARSER + 17;
- protected static final int K_CONDITIONAL_OPERATOR = COMPLETION_PARSER + 18;
- protected static final int K_BETWEEN_IF_AND_RIGHT_PAREN = COMPLETION_PARSER + 19;
- protected static final int K_BETWEEN_WHILE_AND_RIGHT_PAREN = COMPLETION_PARSER + 20;
- protected static final int K_BETWEEN_FOR_AND_RIGHT_PAREN = COMPLETION_PARSER + 21;
- protected static final int K_BETWEEN_SWITCH_AND_RIGHT_PAREN = COMPLETION_PARSER + 22;
- protected static final int K_BETWEEN_SYNCHRONIZED_AND_RIGHT_PAREN = COMPLETION_PARSER + 23;
- protected static final int K_INSIDE_ASSERT_STATEMENT = COMPLETION_PARSER + 24;
- protected static final int K_SWITCH_LABEL= COMPLETION_PARSER + 25;
- protected static final int K_BETWEEN_CASE_AND_COLON = COMPLETION_PARSER + 26;
- protected static final int K_BETWEEN_DEFAULT_AND_COLON = COMPLETION_PARSER + 27;
- protected static final int K_BETWEEN_LEFT_AND_RIGHT_BRACKET = COMPLETION_PARSER + 28;
- protected static final int K_EXTENDS_KEYWORD = COMPLETION_PARSER + 29;
- protected static final int K_PARAMETERIZED_METHOD_INVOCATION = COMPLETION_PARSER + 30;
- protected static final int K_PARAMETERIZED_ALLOCATION = COMPLETION_PARSER + 31;
- protected static final int K_PARAMETERIZED_CAST = COMPLETION_PARSER + 32;
- protected static final int K_BETWEEN_ANNOTATION_NAME_AND_RPAREN = COMPLETION_PARSER + 33;
- protected static final int K_INSIDE_BREAK_STATEMENT = COMPLETION_PARSER + 34;
- protected static final int K_INSIDE_CONTINUE_STATEMENT = COMPLETION_PARSER + 35;
- protected static final int K_LABEL = COMPLETION_PARSER + 36;
- protected static final int K_MEMBER_VALUE_ARRAY_INITIALIZER = COMPLETION_PARSER + 37;
-
- public final static char[] FAKE_TYPE_NAME = new char[]{' '};
- public final static char[] FAKE_METHOD_NAME = new char[]{' '};
- public final static char[] FAKE_ARGUMENT_NAME = new char[]{' '};
- public final static char[] VALUE = new char[]{'v', 'a', 'l', 'u', 'e'};
-
- /* public fields */
-
- public int cursorLocation;
- public ASTNode assistNodeParent; // the parent node of assist node
- /* the following fields are internal flags */
-
- // block kind
- static final int IF = 1;
- static final int TRY = 2;
- static final int CATCH = 3;
- static final int WHILE = 4;
- static final int SWITCH = 5;
- static final int FOR = 6;
- static final int DO = 7;
- static final int SYNCHRONIZED = 8;
-
- // label kind
- static final int DEFAULT = 1;
-
- // invocation type constants
- static final int EXPLICIT_RECEIVER = 0;
- static final int NO_RECEIVER = -1;
- static final int SUPER_RECEIVER = -2;
- static final int NAME_RECEIVER = -3;
- static final int ALLOCATION = -4;
- static final int QUALIFIED_ALLOCATION = -5;
-
- static final int QUESTION = 1;
- static final int COLON = 2;
-
- // K_BETWEEN_ANNOTATION_NAME_AND_RPAREN arguments
- static final int LPAREN_NOT_CONSUMED = 1;
- static final int LPAREN_CONSUMED = 2;
- static final int ANNOTATION_NAME_COMPLETION = 4;
-
- // K_PARAMETERIZED_METHOD_INVOCATION arguments
- static final int INSIDE_NAME = 1;
-
- // the type of the current invocation (one of the invocation type constants)
- int invocationType;
-
- // a pointer in the expression stack to the qualifier of a invocation
- int qualifier;
-
- // last modifiers info
- int lastModifiers = ClassFileConstants.AccDefault;
- int lastModifiersStart = -1;
-
- // depth of '(', '{' and '[]'
- int bracketDepth;
-
- // show if the current token can be an explicit constructor
- int canBeExplicitConstructor = NO;
- static final int NO = 0;
- static final int NEXTTOKEN = 1;
- static final int YES = 2;
-
- protected static final int LabelStackIncrement = 10;
- char[][] labelStack = new char[LabelStackIncrement][];
- int labelPtr = -1;
-
- boolean isAlreadyAttached;
- public boolean record = false;
- public boolean skipRecord = false;
- public int recordFrom;
- public int recordTo;
- public int potentialVariableNamesPtr;
- public char[][] potentialVariableNames;
- public int[] potentialVariableNameStarts;
- public int[] potentialVariableNameEnds;
-
-public CompletionParser(ProblemReporter problemReporter) {
- super(problemReporter);
- this.reportSyntaxErrorIsRequired = false;
- this.javadocParser.checkDocComment = true;
-}
-private void addPotentialName(char[] potentialVariableName, int start, int end) {
- int length = this.potentialVariableNames.length;
- if (this.potentialVariableNamesPtr >= length - 1) {
- System.arraycopy(
- this.potentialVariableNames,
- 0,
- this.potentialVariableNames = new char[length * 2][],
- 0,
- length);
- System.arraycopy(
- this.potentialVariableNameStarts,
- 0,
- this.potentialVariableNameStarts = new int[length * 2],
- 0,
- length);
- System.arraycopy(
- this.potentialVariableNameEnds,
- 0,
- this.potentialVariableNameEnds = new int[length * 2],
- 0,
- length);
- }
- this.potentialVariableNames[++this.potentialVariableNamesPtr] = potentialVariableName;
- this.potentialVariableNameStarts[this.potentialVariableNamesPtr] = start;
- this.potentialVariableNameEnds[this.potentialVariableNamesPtr] = end;
-}
-public void startRecordingIdentifiers(int from, int to) {
- this.record = true;
- this.skipRecord = false;
- this.recordFrom = from;
- this.recordTo = to;
-
- this.potentialVariableNamesPtr = -1;
- this.potentialVariableNames = new char[10][];
- this.potentialVariableNameStarts = new int[10];
- this.potentialVariableNameEnds = new int[10];
-}
-public void stopRecordingIdentifiers() {
- this.record = true;
- this.skipRecord = false;
-}
-
-public char[] assistIdentifier(){
- return ((CompletionScanner)scanner).completionIdentifier;
-}
-protected void attachOrphanCompletionNode(){
- if(assistNode == null || this.isAlreadyAttached) return;
-
-
- if (STOP_AT_CURSOR)
- this.isAlreadyAttached = true;
- if (this.isOrphanCompletionNode) {
- if (!STOP_AT_CURSOR)
- this.isAlreadyAttached = true;
- ASTNode orphan = this.assistNode;
- this.isOrphanCompletionNode = false;
-
- if (currentElement instanceof RecoveredUnit){
- if (orphan instanceof ImportReference){
- currentElement.add((ImportReference)orphan, 0);
- }
- }
-
- /* if in context of a type, then persists the identifier into a fake field return type */
- if (currentElement instanceof RecoveredType){
- RecoveredType recoveredType = (RecoveredType)currentElement;
- /* filter out cases where scanner is still inside type header */
- if (recoveredType.foundOpeningBrace) {
- /* generate a pseudo field with a completion on type reference */
- if (orphan instanceof TypeReference){
- TypeReference fieldType;
-
- int kind = topKnownElementKind(COMPLETION_OR_ASSIST_PARSER);
- int info = topKnownElementInfo(COMPLETION_OR_ASSIST_PARSER);
- if(kind == K_BINARY_OPERATOR && info == LESS && this.identifierPtr > -1) {
- this.pushOnGenericsStack(orphan);
- fieldType = getTypeReference(0);
- this.assistNodeParent = fieldType;
- } else {
- fieldType = (TypeReference)orphan;
- }
-
- CompletionOnFieldType fieldDeclaration = new CompletionOnFieldType(fieldType, false);
-
- // retrieve available modifiers if any
- if (intPtr >= 2 && intStack[intPtr-1] == this.lastModifiersStart && intStack[intPtr-2] == this.lastModifiers){
- fieldDeclaration.modifiersSourceStart = intStack[intPtr-1];
- fieldDeclaration.modifiers = intStack[intPtr-2];
- }
-
- currentElement = currentElement.add(fieldDeclaration, 0);
- return;
- }
- }
- }
- /* if in context of a method, persists if inside arguments as a type */
- if (currentElement instanceof RecoveredMethod){
- RecoveredMethod recoveredMethod = (RecoveredMethod)currentElement;
- /* only consider if inside method header */
- if (!recoveredMethod.foundOpeningBrace) {
- //if (rParenPos < lParenPos){ // inside arguments
- if (orphan instanceof TypeReference){
- currentElement = currentElement.parent.add(
- new CompletionOnFieldType((TypeReference)orphan, true), 0);
- return;
- }
- }
- }
-
- if ((topKnownElementKind(COMPLETION_OR_ASSIST_PARSER) == K_BETWEEN_CATCH_AND_RIGHT_PAREN)) {
- if (this.assistNode instanceof CompletionOnSingleTypeReference &&
- ((CompletionOnSingleTypeReference)this.assistNode).isException()) {
- buildMoreTryStatementCompletionContext((TypeReference)this.assistNode);
- return;
- } else if (this.assistNode instanceof CompletionOnQualifiedTypeReference &&
- ((CompletionOnQualifiedTypeReference)this.assistNode).isException()) {
- buildMoreTryStatementCompletionContext((TypeReference)this.assistNode);
- return;
- }
- } // add the completion node to the method declaration or constructor declaration
- if (orphan instanceof Statement) {
- /* check for completion at the beginning of method body
- behind an invalid signature
- */
- RecoveredMethod method = currentElement.enclosingMethod();
- if (method != null){
- AbstractMethodDeclaration methodDecl = method.methodDeclaration;
- if ((methodDecl.bodyStart == methodDecl.sourceEnd+1) // was missing opening brace
- && (Util.getLineNumber(orphan.sourceStart, scanner.lineEnds, 0, scanner.linePtr)
- == Util.getLineNumber(methodDecl.sourceEnd, scanner.lineEnds, 0, scanner.linePtr))){
- return;
- }
- }
- // add the completion node as a statement to the list of block statements
- currentElement = currentElement.add((Statement)orphan, 0);
- return;
- }
- }
-
- if (this.isInsideAnnotation()) {
- // push top expression on ast stack if it contains the completion node
- Expression expression;
- if (this.expressionPtr > -1) {
- expression = this.expressionStack[this.expressionPtr];
- if(expression == assistNode) {
- if (this.topKnownElementKind(COMPLETION_OR_ASSIST_PARSER) == K_MEMBER_VALUE_ARRAY_INITIALIZER ) {
- ArrayInitializer arrayInitializer = new ArrayInitializer();
- arrayInitializer.expressions = new Expression[]{expression};
- } else if(this.topKnownElementKind(COMPLETION_OR_ASSIST_PARSER) == K_BETWEEN_ANNOTATION_NAME_AND_RPAREN) {
- if (expression instanceof SingleNameReference) {
- SingleNameReference nameReference = (SingleNameReference) expression;
- return;
- } else if (expression instanceof QualifiedNameReference) {
- }
- } else {
- int index;
- if((index = lastIndexOfElement(K_ATTRIBUTE_VALUE_DELIMITER)) != -1) {
- int attributeIndentifierPtr = this.elementInfoStack[index];
- int identLengthPtr = this.identifierLengthPtr;
- int identPtr = this.identifierPtr;
- while (attributeIndentifierPtr < identPtr) {
- identPtr -= this.identifierLengthStack[identLengthPtr--];
- }
-
- if(attributeIndentifierPtr != identPtr) return;
-
- this.identifierLengthPtr = identLengthPtr;
- this.identifierPtr = identPtr;
-
- this.identifierLengthPtr--;
- this.identifierPtr--;
-
- return;
- }
- }
- } else {
- CompletionNodeDetector detector = new CompletionNodeDetector(this.assistNode, expression);
- if(detector.containsCompletionNode()) {
- }
- }
- }
- }
-
- if(this.currentElement instanceof RecoveredType || this.currentElement instanceof RecoveredMethod) {
- if(this.currentElement instanceof RecoveredType) {
- RecoveredType recoveredType = (RecoveredType)this.currentElement;
- }
-
- if ((!isInsideMethod() && !isInsideFieldInitialization())) {
- if(this.genericsPtr > -1 && this.genericsLengthPtr > -1 && this.genericsIdentifiersLengthPtr > -1) {
- int kind = topKnownElementKind(COMPLETION_OR_ASSIST_PARSER);
- int info = topKnownElementInfo(COMPLETION_OR_ASSIST_PARSER);
- int numberOfIdentifiers = this.genericsIdentifiersLengthStack[this.genericsIdentifiersLengthPtr];
- int genPtr = this.genericsPtr;
- done : for(int i = 0; i <= this.identifierLengthPtr && numberOfIdentifiers > 0; i++){
- int identifierLength = this.identifierLengthStack[this.identifierLengthPtr - i];
- int length = this.genericsLengthStack[this.genericsLengthPtr - i];
- for(int j = 0; j < length; j++) {
- ASTNode node = this.genericsStack[genPtr - j];
- CompletionNodeDetector detector = new CompletionNodeDetector(this.assistNode, node);
- if(detector.containsCompletionNode()) {
- if(node == this.assistNode){
- if(this.identifierLengthPtr > -1 && this.identifierLengthStack[this.identifierLengthPtr]!= 0) {
- TypeReference ref = this.getTypeReference(0);
- this.assistNodeParent = ref;
- }
- } else {
- this.assistNodeParent = detector.getCompletionNodeParent();
- }
- break done;
- }
- }
- genPtr -= length;
- numberOfIdentifiers -= identifierLength;
- }
- if(this.assistNodeParent != null && this.assistNodeParent instanceof TypeReference) {
- if(this.currentElement instanceof RecoveredType) {
- this.currentElement = this.currentElement.add(new CompletionOnFieldType((TypeReference)this.assistNodeParent, false), 0);
- } else {
- this.currentElement = this.currentElement.add((TypeReference)this.assistNodeParent, 0);
- }
- }
- }
- }
- }
-
- // the following code applies only in methods, constructors or initializers
- if ((!isInsideMethod() && !isInsideFieldInitialization() && !isInsideAttributeValue())) {
- return;
- }
-
- if(this.genericsPtr > -1) {
- ASTNode node = this.genericsStack[this.genericsPtr];
- CompletionNodeDetector detector = new CompletionNodeDetector(this.assistNode, node);
- if(detector.containsCompletionNode()) {
- /* check for completion at the beginning of method body
- behind an invalid signature
- */
- RecoveredMethod method = this.currentElement.enclosingMethod();
- if (method != null){
- AbstractMethodDeclaration methodDecl = method.methodDeclaration;
- if ((methodDecl.bodyStart == methodDecl.sourceEnd+1) // was missing opening brace
- && (Util.getLineNumber(node.sourceStart, this.scanner.lineEnds, 0, this.scanner.linePtr)
- == Util.getLineNumber(methodDecl.sourceEnd, this.scanner.lineEnds, 0, this.scanner.linePtr))){
- return;
- }
- }
- if(node == this.assistNode){
- buildMoreGenericsCompletionContext(node,true);
- }
- }
- }
-
- // push top expression on ast stack if it contains the completion node
- Expression expression;
- if (this.expressionPtr > -1) {
- expression = this.expressionStack[this.expressionPtr];
- CompletionNodeDetector detector = new CompletionNodeDetector(assistNode, expression);
- if(detector.containsCompletionNode()) {
- /* check for completion at the beginning of method body
- behind an invalid signature
- */
- RecoveredMethod method = currentElement.enclosingMethod();
- if (method != null){
- AbstractMethodDeclaration methodDecl = method.methodDeclaration;
- if ((methodDecl.bodyStart == methodDecl.sourceEnd+1) // was missing opening brace
- && (Util.getLineNumber(expression.sourceStart, scanner.lineEnds, 0, scanner.linePtr)
- == Util.getLineNumber(methodDecl.sourceEnd, scanner.lineEnds, 0, scanner.linePtr))){
- return;
- }
- }
- if(expression == assistNode
- || (expression instanceof AllocationExpression
- && ((AllocationExpression)expression).type == assistNode)){
- buildMoreCompletionContext(expression);
- } else {
- assistNodeParent = detector.getCompletionNodeParent();
- if(assistNodeParent != null) {
- currentElement = currentElement.add((Statement)assistNodeParent, 0);
- } else {
- currentElement = currentElement.add(expression, 0);
- }
- }
- }
- }
-}
-
-private void buildMoreCompletionContext(Expression expression) {
- Statement statement = expression;
- int kind = topKnownElementKind(COMPLETION_OR_ASSIST_PARSER);
- if(kind != 0) {
- int info = topKnownElementInfo(COMPLETION_OR_ASSIST_PARSER);
- nextElement : switch (kind) {
- case K_SELECTOR_QUALIFIER :
- int selector = topKnownElementInfo(COMPLETION_OR_ASSIST_PARSER, 2);
- if(false){// Not Possible selector == THIS_CONSTRUCTOR || selector == SUPER_CONSTRUCTOR) {
- ExplicitConstructorCall call = new ExplicitConstructorCall(ExplicitConstructorCall.This);
- call.arguments = new Expression[] {expression};
- call.sourceStart = expression.sourceStart;
- call.sourceEnd = expression.sourceEnd;
- assistNodeParent = call;
- } else {
- int invocType = topKnownElementInfo(COMPLETION_OR_ASSIST_PARSER,1);
- int qualifierExprPtr = info;
-
- // find arguments
- int length = expressionLengthStack[expressionLengthPtr];
-
- // search previous arguments if missing
- if(this.expressionPtr > 0 && this.expressionLengthPtr > 0 && length == 1) {
- int start = 0;
- if (invocType != ALLOCATION && invocType != QUALIFIED_ALLOCATION)
- start=(int) (identifierPositionStack[selector] >>> 32);
- else
- start=expressionStack[info].sourceStart;
-
- if(this.expressionStack[expressionPtr-1] != null && this.expressionStack[expressionPtr-1].sourceStart > start) {
- length += expressionLengthStack[expressionLengthPtr-1];
- }
-
- }
-
- Expression[] arguments = null;
- if (length != 0) {
- arguments = new Expression[length];
- expressionPtr -= length;
- System.arraycopy(expressionStack, expressionPtr + 1, arguments, 0, length-1);
- arguments[length-1] = expression;
- }
-
- if(invocType != ALLOCATION && invocType != QUALIFIED_ALLOCATION) {
- MessageSend messageSend = new MessageSend();
- messageSend.selector = identifierStack[selector];
- messageSend.arguments = arguments;
-
- // find receiver
- switch (invocType) {
- case NO_RECEIVER:
- messageSend.receiver = ThisReference.implicitThis();
- break;
- case NAME_RECEIVER:
- // remove special flags for primitive types
- while (this.identifierLengthPtr >= 0 && this.identifierLengthStack[this.identifierLengthPtr] < 0) {
- this.identifierLengthPtr--;
- }
-
- // remove selector
- this.identifierPtr--;
- if(this.genericsPtr > -1 && this.genericsLengthPtr > -1 && this.genericsLengthStack[this.genericsLengthPtr] > 0) {
- // is inside a paremeterized method: bar.<X>.foo
- this.identifierLengthPtr--;
- } else {
- this.identifierLengthStack[this.identifierLengthPtr]--;
- }
- // consume the receiver
- int identifierLength = this.identifierLengthStack[this.identifierLengthPtr];
- if(this.identifierPtr > -1 && identifierLength > 0 && this.identifierPtr + 1 >= identifierLength) {
- messageSend.receiver = this.getUnspecifiedReference();
- } else {
- messageSend = null;
- }
- break;
- case SUPER_RECEIVER:
- messageSend.receiver = new SuperReference(0, 0);
- break;
- case EXPLICIT_RECEIVER:
- messageSend.receiver = this.expressionStack[qualifierExprPtr];
- break;
- default :
- messageSend.receiver = ThisReference.implicitThis();
- break;
- }
- assistNodeParent = messageSend;
- } else {
- if(invocType == ALLOCATION) {
- AllocationExpression allocationExpr = new AllocationExpression();
- allocationExpr.arguments = arguments;
-// pushOnGenericsIdentifiersLengthStack(identifierLengthStack[identifierLengthPtr]);
-// pushOnGenericsLengthStack(0);
-// allocationExpr.type = getTypeReference(0);
- allocationExpr.member=expressionStack[info];
- assistNodeParent = allocationExpr;
- } else {
- QualifiedAllocationExpression allocationExpr = new QualifiedAllocationExpression();
- allocationExpr.enclosingInstance = this.expressionStack[qualifierExprPtr];
- allocationExpr.arguments = arguments;
- pushOnGenericsIdentifiersLengthStack(identifierLengthStack[identifierLengthPtr]);
- pushOnGenericsLengthStack(0);
-
- allocationExpr.type = getTypeReference(0);
- assistNodeParent = allocationExpr;
- }
- }
- }
- break nextElement;
- case K_INSIDE_RETURN_STATEMENT :
- if(info == bracketDepth) {
- ReturnStatement returnStatement = new ReturnStatement(expression, expression.sourceStart, expression.sourceEnd);
- assistNodeParent = returnStatement;
- }
- break nextElement;
- case K_UNARY_OPERATOR :
- if(expressionPtr > -1) {
- Expression operatorExpression = null;
- switch (info) {
- case PLUS_PLUS :
- operatorExpression = new PrefixExpression(expression,IntLiteral.getOne(), PLUS, expression.sourceStart);
- break;
- case MINUS_MINUS :
- operatorExpression = new PrefixExpression(expression,IntLiteral.getOne(), MINUS, expression.sourceStart);
- break;
- default :
- operatorExpression = new UnaryExpression(expression, info);
- break;
- }
- assistNodeParent = operatorExpression;
- }
- break nextElement;
- case K_BINARY_OPERATOR :
- if(expressionPtr > -1) {
- Expression operatorExpression = null;
- Expression left = null;
- if(expressionPtr == 0) {
- // it is a ***_NotName rule
- if(this.identifierPtr > -1) {
- left = getUnspecifiedReferenceOptimized();
- }
- } else {
- left = this.expressionStack[expressionPtr-1];
- // is it a ***_NotName rule ?
- if(this.identifierPtr > -1) {
- int start = (int) (identifierPositionStack[this.identifierPtr] >>> 32);
- if(left.sourceStart < start) {
- left = getUnspecifiedReferenceOptimized();
- }
- }
- }
-
- if(left != null) {
- switch (info) {
- case AND_AND :
- operatorExpression = new AND_AND_Expression(left, expression, info);
- break;
- case OR_OR :
- operatorExpression = new OR_OR_Expression(left, expression, info);
- break;
- case EQUAL_EQUAL :
- case NOT_EQUAL :
- operatorExpression = new EqualExpression(left, expression, info);
- break;
- default :
- operatorExpression = new BinaryExpression(left, expression, info);
- break;
- }
- }
- if(operatorExpression != null) {
- assistNodeParent = operatorExpression;
- }
- }
- break nextElement;
- case K_ARRAY_INITIALIZER :
- ArrayInitializer arrayInitializer = new ArrayInitializer();
- arrayInitializer.expressions = new Expression[]{expression};
- expressionPtr -= expressionLengthStack[expressionLengthPtr--];
-
- if(expressionLengthPtr > -1
- && expressionPtr > -1
- && this.expressionStack[expressionPtr] != null
- && this.expressionStack[expressionPtr].sourceStart > info) {
- expressionLengthPtr--;
- }
-
- lastCheckPoint = scanner.currentPosition;
-
- if(topKnownElementKind(COMPLETION_OR_ASSIST_PARSER, 1) == K_ARRAY_CREATION) {
- ArrayAllocationExpression allocationExpression = new ArrayAllocationExpression();
- pushOnGenericsLengthStack(0);
- pushOnGenericsIdentifiersLengthStack(identifierLengthStack[identifierLengthPtr]);
- allocationExpression.type = getTypeReference(0);
- allocationExpression.type.bits |= ASTNode.IgnoreRawTypeCheck; // no need to worry about raw type usage
- int length = expressionLengthStack[expressionLengthPtr];
- allocationExpression.dimensions = new Expression[length];
-
- allocationExpression.initializer = arrayInitializer;
- assistNodeParent = allocationExpression;
- } else if(currentElement instanceof RecoveredField && !(currentElement instanceof RecoveredInitializer)) {
- RecoveredField recoveredField = (RecoveredField) currentElement;
- if(recoveredField.fieldDeclaration.type.dimensions() == 0) {
- Block block = new Block(0);
- block.sourceStart = info;
- currentElement = currentElement.add(block, 1);
- } else {
- statement = arrayInitializer;
- }
- } else if(currentElement instanceof RecoveredLocalVariable) {
- RecoveredLocalVariable recoveredLocalVariable = (RecoveredLocalVariable) currentElement;
- if(recoveredLocalVariable.localDeclaration.type.dimensions() == 0) {
- Block block = new Block(0);
- block.sourceStart = info;
- currentElement = currentElement.add(block, 1);
- } else {
- statement = arrayInitializer;
- }
- } else {
- statement = arrayInitializer;
- }
- break nextElement;
- case K_ARRAY_CREATION :
- ArrayAllocationExpression allocationExpression = new ArrayAllocationExpression();
- allocationExpression.type = getTypeReference(0);
- allocationExpression.dimensions = new Expression[]{expression};
-
- assistNodeParent = allocationExpression;
- break nextElement;
- case K_ASSISGNMENT_OPERATOR :
- if(expressionPtr > 0 && expressionStack[expressionPtr - 1] != null) {
- Assignment assignment;
- if(info == EQUAL) {
- assignment = new Assignment(
- expressionStack[expressionPtr - 1],
- expression,
- expression.sourceEnd
- );
- } else {
- assignment = new CompoundAssignment(
- expressionStack[expressionPtr - 1],
- expression,
- info,
- expression.sourceEnd
- );
- }
- assistNodeParent = assignment;
- }
- break nextElement;
- case K_CONDITIONAL_OPERATOR :
- if(info == QUESTION) {
- if(expressionPtr > 0) {
- expressionPtr--;
- expressionLengthPtr--;
- expressionStack[expressionPtr] = expressionStack[expressionPtr+1];
- popElement(K_CONDITIONAL_OPERATOR);
- buildMoreCompletionContext(expression);
- return;
- }
- } else {
- if(expressionPtr > 1) {
- expressionPtr = expressionPtr - 2;
- expressionLengthPtr = expressionLengthPtr - 2;
- expressionStack[expressionPtr] = expressionStack[expressionPtr+2];
- popElement(K_CONDITIONAL_OPERATOR);
- buildMoreCompletionContext(expression);
- return;
- }
- }
- break nextElement;
- case K_BETWEEN_LEFT_AND_RIGHT_BRACKET :
- ArrayReference arrayReference;
- if(identifierPtr < 0 && expressionPtr > 0 && expressionStack[expressionPtr] == expression) {
- arrayReference =
- new ArrayReference(
- expressionStack[expressionPtr-1],
- expression);
- } else {
- arrayReference =
- new ArrayReference(
- getUnspecifiedReferenceOptimized(),
- expression);
- }
- assistNodeParent = arrayReference;
- break;
- case K_BETWEEN_CASE_AND_COLON :
- if(this.expressionPtr > 0) {
- SwitchStatement switchStatement = new SwitchStatement();
- switchStatement.expression = this.expressionStack[this.expressionPtr - 1];
- if(this.astLengthPtr > -1 && this.astPtr > -1) {
- int length = this.astLengthStack[this.astLengthPtr];
- int newAstPtr = this.astPtr - length;
- ASTNode firstNode = this.astStack[newAstPtr + 1];
- if(length != 0 && firstNode.sourceStart > switchStatement.expression.sourceEnd) {
- switchStatement.statements = new Statement[length + 1];
- System.arraycopy(
- this.astStack,
- newAstPtr + 1,
- switchStatement.statements,
- 0,
- length);
- }
- }
- CaseStatement caseStatement = new CaseStatement(expression, expression.sourceStart, expression.sourceEnd);
- if(switchStatement.statements == null) {
- switchStatement.statements = new Statement[]{caseStatement};
- } else {
- switchStatement.statements[switchStatement.statements.length - 1] = caseStatement;
- }
- assistNodeParent = switchStatement;
- }
- break;
- }
- }
- if(assistNodeParent != null) {
- currentElement = currentElement.add((Statement)assistNodeParent, 0);
- } else {
- if(currentElement instanceof RecoveredField && !(currentElement instanceof RecoveredInitializer)
- && ((RecoveredField) currentElement).fieldDeclaration.initialization == null) {
-
- assistNodeParent = ((RecoveredField) currentElement).fieldDeclaration;
- currentElement = currentElement.add(statement, 0);
- } else if(currentElement instanceof RecoveredLocalVariable
- && ((RecoveredLocalVariable) currentElement).localDeclaration.initialization == null) {
-
- assistNodeParent = ((RecoveredLocalVariable) currentElement).localDeclaration;
- currentElement = currentElement.add(statement, 0);
- } else {
- currentElement = currentElement.add(expression, 0);
- }
- }
-}
-private void buildMoreGenericsCompletionContext(ASTNode node, boolean consumeTypeArguments) {
- int kind = topKnownElementKind(COMPLETION_OR_ASSIST_PARSER);
- if(kind != 0) {
- int info = topKnownElementInfo(COMPLETION_OR_ASSIST_PARSER);
- nextElement : switch (kind) {
- case K_BINARY_OPERATOR :
- int prevKind = topKnownElementKind(COMPLETION_OR_ASSIST_PARSER, 1);
- switch (prevKind) {
- case K_PARAMETERIZED_ALLOCATION :
- if(this.invocationType == ALLOCATION || this.invocationType == QUALIFIED_ALLOCATION) {
- currentElement = currentElement.add((TypeReference)node, 0);
- }
- break nextElement;
- case K_PARAMETERIZED_METHOD_INVOCATION :
- if(topKnownElementInfo(COMPLETION_OR_ASSIST_PARSER, 1) == 0) {
- currentElement = currentElement.add((TypeReference)node, 0);
- break nextElement;
- }
- }
- if(info == LESS && node instanceof TypeReference) {
- if(this.identifierLengthPtr > -1 && this.identifierLengthStack[this.identifierLengthPtr]!= 0) {
- TypeReference ref = this.getTypeReference(0);
- if(currentElement instanceof RecoveredType) {
- currentElement = currentElement.add(new CompletionOnFieldType(ref, false), 0);
- } else {
- currentElement = currentElement.add(ref, 0);
- }
- } else if (currentElement.enclosingMethod().methodDeclaration.isConstructor()) {
- currentElement = currentElement.add((TypeReference)node, 0);
- }
- }
- break;
- }
- }
-}
-private void buildMoreTryStatementCompletionContext(TypeReference exceptionRef) {
- if (this.astLengthPtr > -1 &&
- this.astPtr > 1 &&
- this.astStack[this.astPtr] instanceof Block &&
- this.astStack[this.astPtr - 1] instanceof Argument) {
- TryStatement tryStatement = new TryStatement();
-
- int newAstPtr = this.astPtr;
-
- int length = this.astLengthStack[this.astLengthPtr];
- Block[] bks = (tryStatement.catchBlocks = new Block[length + 1]);
- Argument[] args = (tryStatement.catchArguments = new Argument[length + 1]);
- if (length != 0) {
- while (length-- > 0) {
- bks[length] = (Block) this.astStack[newAstPtr--];
- bks[length].statements = null; // statements of catch block won't be used
- args[length] = (Argument) this.astStack[newAstPtr--];
- }
- }
-
- bks[bks.length - 1] = new Block(0);
- args[args.length - 1] = new Argument(FAKE_ARGUMENT_NAME,0,exceptionRef,0);
-
- tryStatement.tryBlock = (Block) this.astStack[newAstPtr--];
-
- assistNodeParent = tryStatement;
-
- currentElement.add(tryStatement, 0);
- } else if (this.astLengthPtr > -1 &&
- this.astPtr > -1 &&
- this.astStack[this.astPtr] instanceof Block) {
- TryStatement tryStatement = new TryStatement();
-
- int newAstPtr = this.astPtr;
-
- Block[] bks = (tryStatement.catchBlocks = new Block[1]);
- Argument[] args = (tryStatement.catchArguments = new Argument[1]);
-
- bks[0] = new Block(0);
- args[0] = new Argument(FAKE_ARGUMENT_NAME,0,exceptionRef,0);
-
- tryStatement.tryBlock = (Block) this.astStack[newAstPtr--];
-
- assistNodeParent = tryStatement;
-
- currentElement.add(tryStatement, 0);
- }else {
- currentElement = currentElement.add(exceptionRef, 0);
- }
-}
-
-public int bodyEnd(AbstractMethodDeclaration method){
- return cursorLocation;
-}
-public int bodyEnd(Initializer initializer){
- return cursorLocation;
-}
-/**
- * Checks if the completion is on the exception type of a catch clause.
- * Returns whether we found a completion node.
- */
-private boolean checkCatchClause() {
- if ((topKnownElementKind(COMPLETION_OR_ASSIST_PARSER) == K_BETWEEN_CATCH_AND_RIGHT_PAREN) && this.identifierPtr > -1) {
- // NB: if the cursor is on the variable, then it has been reduced (so identifierPtr is -1),
- // thus this can only be a completion on the type of the catch clause
- pushOnElementStack(K_NEXT_TYPEREF_IS_EXCEPTION);
- this.assistNode = getTypeReference(0);
- popElement(K_NEXT_TYPEREF_IS_EXCEPTION);
- this.lastCheckPoint = this.assistNode.sourceEnd + 1;
- this.isOrphanCompletionNode = true;
- return true;
- }
- return false;
-}
-/**
- * Checks if the completion is on the type following a 'new'.
- * Returns whether we found a completion node.
- */
-private boolean checkClassInstanceCreation() {
- if (topKnownElementKind(COMPLETION_OR_ASSIST_PARSER) == K_BETWEEN_NEW_AND_LEFT_BRACKET) {
- int length = identifierLengthStack[identifierLengthPtr];
- int numberOfIdentifiers = this.genericsIdentifiersLengthStack[this.genericsIdentifiersLengthPtr];
- if (length != numberOfIdentifiers || this.genericsLengthStack[this.genericsLengthPtr] != 0) {
- // no class instance creation with a parameterized type
- return true;
- }
-
- // completion on type inside an allocation expression
-
- TypeReference type;
- if (this.invocationType == ALLOCATION) {
- // non qualified allocation expression
- AllocationExpression allocExpr = new AllocationExpression();
- if (topKnownElementKind(COMPLETION_OR_ASSIST_PARSER, 1) == K_INSIDE_THROW_STATEMENT
- && topKnownElementInfo(COMPLETION_OR_ASSIST_PARSER, 1) == this.bracketDepth) {
- pushOnElementStack(K_NEXT_TYPEREF_IS_EXCEPTION);
- type = getTypeReference(0);
- popElement(K_NEXT_TYPEREF_IS_EXCEPTION);
- } else {
- type = getTypeReference(0);
- }
- if(type instanceof CompletionOnSingleTypeReference) {
- ((CompletionOnSingleTypeReference)type).isConstructorType = true;
- }
- allocExpr.type = type;
- allocExpr.sourceStart = type.sourceStart;
- allocExpr.sourceEnd = type.sourceEnd;
- pushOnExpressionStack(allocExpr);
- this.isOrphanCompletionNode = false;
- } else {
- // qualified allocation expression
- QualifiedAllocationExpression allocExpr = new QualifiedAllocationExpression();
- pushOnGenericsIdentifiersLengthStack(identifierLengthStack[identifierLengthPtr]);
- pushOnGenericsLengthStack(0);
- if (topKnownElementKind(COMPLETION_OR_ASSIST_PARSER, 1) == K_INSIDE_THROW_STATEMENT
- && topKnownElementInfo(COMPLETION_OR_ASSIST_PARSER, 1) == this.bracketDepth) {
- pushOnElementStack(K_NEXT_TYPEREF_IS_EXCEPTION);
- type = getTypeReference(0);
- popElement(K_NEXT_TYPEREF_IS_EXCEPTION);
- } else {
- type = getTypeReference(0);
- }
- allocExpr.type = type;
- allocExpr.enclosingInstance = this.expressionStack[this.qualifier];
- allocExpr.sourceStart = this.intStack[this.intPtr--];
- allocExpr.sourceEnd = type.sourceEnd;
- this.expressionStack[this.qualifier] = allocExpr; // attach it now (it replaces the qualifier expression)
- this.isOrphanCompletionNode = false;
- }
- this.assistNode = type;
- this.lastCheckPoint = type.sourceEnd + 1;
-
- popElement(K_BETWEEN_NEW_AND_LEFT_BRACKET);
- return true;
- }
- return false;
-}
-/**
- * Checks if the completion is on the dot following an array type,
- * a primitive type or an primitive array type.
- * Returns whether we found a completion node.
- */
-private boolean checkClassLiteralAccess() {
- if (this.identifierLengthPtr >= 1 && this.previousToken == TokenNameDOT) { // (NB: the top id length is 1 and it is for the completion identifier)
- int length;
- // if the penultimate id length is negative,
- // the completion is after a primitive type or a primitive array type
- if ((length = this.identifierLengthStack[this.identifierLengthPtr-1]) < 0) {
- // build the primitive type node
- int dim = this.isAfterArrayType() ? this.intStack[this.intPtr--] : 0;
- SingleTypeReference typeRef = (SingleTypeReference)TypeReference.baseTypeReference(-length, dim);
- typeRef.sourceStart = this.intStack[this.intPtr--];
- if (dim == 0) {
- typeRef.sourceEnd = this.intStack[this.intPtr--];
- } else {
- this.intPtr--;
- typeRef.sourceEnd = this.endPosition;
- }
- //typeRef.sourceEnd = typeRef.sourceStart + typeRef.token.length; // NB: It's ok to use the length of the token since it doesn't contain any unicode
-
- // find the completion identifier and its source positions
- char[] source = identifierStack[identifierPtr];
- long pos = this.identifierPositionStack[this.identifierPtr--];
- this.identifierLengthPtr--; // it can only be a simple identifier (so its length is one)
-
- // build the completion on class literal access node
- CompletionOnClassLiteralAccess access = new CompletionOnClassLiteralAccess(pos, typeRef);
- access.completionIdentifier = source;
- this.identifierLengthPtr--; // pop the length that was used to say it is a primitive type
- this.assistNode = access;
- this.isOrphanCompletionNode = true;
- return true;
- }
-
- // if the completion is after a regular array type
- if (isAfterArrayType()) {
- // find the completion identifier and its source positions
- char[] source = identifierStack[identifierPtr];
- long pos = this.identifierPositionStack[this.identifierPtr--];
- this.identifierLengthPtr--; // it can only be a simple identifier (so its length is one)
-
- // get the type reference
- pushOnGenericsIdentifiersLengthStack(identifierLengthStack[identifierLengthPtr]);
- pushOnGenericsLengthStack(0);
-
- TypeReference typeRef = getTypeReference(this.intStack[this.intPtr--]);
-
- // build the completion on class literal access node
- CompletionOnClassLiteralAccess access = new CompletionOnClassLiteralAccess(pos, typeRef);
- access.completionIdentifier = source;
- this.assistNode = access;
- this.isOrphanCompletionNode = true;
- return true;
- }
-
- }
- return false;
-}
-private boolean checkKeyword() {
- if (currentElement instanceof RecoveredUnit) {
-// RecoveredUnit unit = (RecoveredUnit) currentElement;
- int index = -1;
- if ((index = this.indexOfAssistIdentifier()) > -1) {
- int ptr = this.identifierPtr - this.identifierLengthStack[this.identifierLengthPtr] + index + 1;
-
- char[] ident = identifierStack[ptr];
- long pos = identifierPositionStack[ptr];
-
- char[][] keywords = new char[Keywords.COUNT][];
- int count = 0;
-// if(unit.typeCount == 0
-// && lastModifiers == ClassFileConstants.AccDefault) {
-// keywords[count++] = Keywords.IMPORT;
-// }
-// if(unit.typeCount == 0
-// && unit.importCount == 0
-// && lastModifiers == ClassFileConstants.AccDefault
-// && compilationUnit.currentPackage == null) {
-// keywords[count++] = Keywords.PACKAGE;
-// }
-// if((lastModifiers & ClassFileConstants.AccPublic) == 0) {
-// boolean hasNoPublicType = true;
-// for (int i = 0; i < unit.typeCount; i++) {
-// if((unit.types[i].typeDeclaration.modifiers & ClassFileConstants.AccPublic) != 0) {
-// hasNoPublicType = false;
-// }
-// }
-// if(hasNoPublicType) {
-// keywords[count++] = Keywords.PUBLIC;
-// }
-// }
-// if((lastModifiers & ClassFileConstants.AccAbstract) == 0
-// && (lastModifiers & ClassFileConstants.AccFinal) == 0) {
-// keywords[count++] = Keywords.ABSTRACT;
-// }
-// if((lastModifiers & ClassFileConstants.AccAbstract) == 0
-// && (lastModifiers & ClassFileConstants.AccFinal) == 0) {
-// keywords[count++] = Keywords.FINAL;
-// }
-//
-// keywords[count++] = Keywords.CLASS;
-//
-// if((lastModifiers & ClassFileConstants.AccFinal) == 0) {
-// keywords[count++] = Keywords.INTERFACE;
-// }
- if(count != 0) {
- System.arraycopy(keywords, 0, keywords = new char[count][], 0, count);
-
- this.assistNode = new CompletionOnKeyword2(ident, pos, keywords);
- this.lastCheckPoint = assistNode.sourceEnd + 1;
- this.isOrphanCompletionNode = true;
- return true;
- }
- }
- }
- return false;
-}
-private boolean checkInstanceofKeyword() {
- if(isInsideMethod()) {
- int kind = topKnownElementKind(COMPLETION_OR_ASSIST_PARSER);
- int index;
- if(kind != K_BLOCK_DELIMITER
- && (index = indexOfAssistIdentifier()) > -1
- && expressionPtr > -1
- && expressionLengthStack[expressionPtr] == 1) {
-
- int ptr = this.identifierPtr - this.identifierLengthStack[this.identifierLengthPtr] + index + 1;
- if(identifierStack[ptr].length > 0 && CharOperation.prefixEquals(identifierStack[ptr], Keywords.INSTANCEOF)) {
- this.assistNode = new CompletionOnKeyword3(
- identifierStack[ptr],
- identifierPositionStack[ptr],
- Keywords.INSTANCEOF);
- this.lastCheckPoint = assistNode.sourceEnd + 1;
- this.isOrphanCompletionNode = true;
- return true;
- }
- if(identifierStack[ptr].length > 0 && CharOperation.prefixEquals(identifierStack[ptr], Keywords.TYPEOF)) {
- this.assistNode = new CompletionOnKeyword3(
- identifierStack[ptr],
- identifierPositionStack[ptr],
- Keywords.TYPEOF);
- this.lastCheckPoint = assistNode.sourceEnd + 1;
- this.isOrphanCompletionNode = true;
- return true;
- }
- }
- }
- return false;
-}
-/**
- * Checks if the completion is inside a method invocation or a constructor invocation.
- * Returns whether we found a completion node.
- */
-private boolean checkInvocation() {
- Expression topExpression = this.expressionPtr >= 0 ?
- this.expressionStack[this.expressionPtr] :
- null;
- boolean isEmptyNameCompletion = false;
- boolean isEmptyAssistIdentifier = false;
- if (topKnownElementKind(COMPLETION_OR_ASSIST_PARSER) == K_SELECTOR_QUALIFIER
- && ((isEmptyNameCompletion = topExpression == this.assistNode && this.isEmptyNameCompletion()) // eg. it is something like "this.fred([cursor]" but it is not something like "this.fred(1 + [cursor]"
- || (isEmptyAssistIdentifier = this.indexOfAssistIdentifier() >= 0 && this.identifierStack[this.identifierPtr].length == 0))) { // eg. it is something like "this.fred(1 [cursor]"
-
- // pop empty name completion
- if (isEmptyNameCompletion) {
- this.expressionPtr--;
- this.expressionLengthStack[this.expressionLengthPtr]--;
- } else if (isEmptyAssistIdentifier) {
- this.identifierPtr--;
- this.identifierLengthPtr--;
- }
-
- // find receiver and qualifier
- int invocType = topKnownElementInfo(COMPLETION_OR_ASSIST_PARSER, 1);
- int qualifierExprPtr = topKnownElementInfo(COMPLETION_OR_ASSIST_PARSER);
-
- // find arguments
- int numArgs = this.expressionPtr - qualifierExprPtr;
- int argStart = qualifierExprPtr + 1;
- Expression[] arguments = null;
- if (numArgs > 0) {
- // remember the arguments
- arguments = new Expression[numArgs];
- System.arraycopy(this.expressionStack, argStart, arguments, 0, numArgs);
-
- // consume the expression arguments
- this.expressionPtr -= numArgs;
- int count = numArgs;
- while (count > 0) {
- count -= this.expressionLengthStack[this.expressionLengthPtr--];
- }
- }
-
- // build ast node
- if (invocType != ALLOCATION && invocType != QUALIFIED_ALLOCATION) {
- // creates completion on message send
- CompletionOnMessageSend messageSend = new CompletionOnMessageSend();
- messageSend.arguments = arguments;
- switch (invocType) {
- case NO_RECEIVER:
- // implicit this
- messageSend.receiver = ThisReference.implicitThis();
- break;
- case NAME_RECEIVER:
- // remove special flags for primitive types
- while (this.identifierLengthPtr >= 0 && this.identifierLengthStack[this.identifierLengthPtr] < 0) {
- this.identifierLengthPtr--;
- }
-
- // remove selector
- this.identifierPtr--;
- if(this.genericsPtr > -1 && this.genericsLengthPtr > -1 && this.genericsLengthStack[this.genericsLengthPtr] > 0) {
- // is inside a paremeterized method: bar.<X>.foo
- this.identifierLengthPtr--;
- } else {
- this.identifierLengthStack[this.identifierLengthPtr]--;
- }
- // consume the receiver
- messageSend.receiver = this.getUnspecifiedReference();
- break;
- case SUPER_RECEIVER:
- messageSend.receiver = new SuperReference(0, 0);
- break;
- case EXPLICIT_RECEIVER:
- messageSend.receiver = this.expressionStack[qualifierExprPtr];
- }
-
- // set selector
- int selectorPtr = topKnownElementInfo(COMPLETION_OR_ASSIST_PARSER, 2);
- messageSend.selector = this.identifierStack[selectorPtr];
- // remove selector
- if (this.identifierLengthPtr >=0 && this.identifierLengthStack[this.identifierLengthPtr] == 1) {
- this.identifierPtr--;
- this.identifierLengthPtr--;
- }
-
- // the entire message may be replaced in case qualification is needed
- messageSend.sourceStart = (int)(this.identifierPositionStack[selectorPtr] >> 32); //this.cursorLocation + 1;
- messageSend.sourceEnd = this.cursorLocation;
-
- // remember the message send as an orphan completion node
- this.assistNode = messageSend;
- this.lastCheckPoint = messageSend.sourceEnd + 1;
- this.isOrphanCompletionNode = true;
- return true;
- } else {
- int selectorPtr = topKnownElementInfo(COMPLETION_OR_ASSIST_PARSER, 2);
- if (selectorPtr == THIS_CONSTRUCTOR || selectorPtr == SUPER_CONSTRUCTOR) {
- // creates an explicit constructor call
- CompletionOnExplicitConstructorCall call = new CompletionOnExplicitConstructorCall(ExplicitConstructorCall.This);
- call.arguments = arguments;
- if (invocType == QUALIFIED_ALLOCATION) {
- call.qualification = this.expressionStack[qualifierExprPtr];
- }
-
- // no source is going to be replaced
- call.sourceStart = this.cursorLocation + 1;
- call.sourceEnd = this.cursorLocation;
-
- // remember the explicit constructor call as an orphan completion node
- this.assistNode = call;
- this.lastCheckPoint = call.sourceEnd + 1;
- this.isOrphanCompletionNode = true;
- return true;
- } else {
- // creates an allocation expression
- CompletionOnQualifiedAllocationExpression allocExpr = new CompletionOnQualifiedAllocationExpression();
- allocExpr.arguments = arguments;
- if(this.genericsLengthPtr < 0) {
- pushOnGenericsLengthStack(0);
- pushOnGenericsIdentifiersLengthStack(identifierLengthStack[identifierLengthPtr]);
- }
- allocExpr.type = super.getTypeReference(0); // we don't want a completion node here, so call super
- if (invocType == QUALIFIED_ALLOCATION) {
- allocExpr.enclosingInstance = this.expressionStack[qualifierExprPtr];
- }
- // no source is going to be replaced
- allocExpr.sourceStart = this.cursorLocation + 1;
- allocExpr.sourceEnd = this.cursorLocation;
-
- // remember the allocation expression as an orphan completion node
- this.assistNode = allocExpr;
- this.lastCheckPoint = allocExpr.sourceEnd + 1;
- this.isOrphanCompletionNode = true;
- return true;
- }
- }
- }
- return false;
-}
-private boolean checkLabelStatement() {
- if(isInsideMethod() || isInsideFieldInitialization()) {
-
- int kind = this.topKnownElementKind(COMPLETION_OR_ASSIST_PARSER);
- if(kind != K_INSIDE_BREAK_STATEMENT && kind != K_INSIDE_CONTINUE_STATEMENT) return false;
-
- if (indexOfAssistIdentifier() != 0) return false;
-
- char[][] labels = new char[this.labelPtr + 1][];
- int labelCount = 0;
-
- int labelKind = kind;
- int index = 1;
- while(labelKind != 0 && labelKind != K_METHOD_DELIMITER) {
- labelKind = this.topKnownElementKind(COMPLETION_OR_ASSIST_PARSER, index);
- if(labelKind == K_LABEL) {
- int ptr = this.topKnownElementInfo(COMPLETION_OR_ASSIST_PARSER, index);
- labels[labelCount++] = this.labelStack[ptr];
- }
- index++;
- }
- System.arraycopy(labels, 0, labels = new char[labelCount][], 0, labelCount);
-
- long position = this.identifierPositionStack[this.identifierPtr];
- CompletionOnBrankStatementLabel statementLabel =
- new CompletionOnBrankStatementLabel(
- kind == K_INSIDE_BREAK_STATEMENT ? CompletionOnBrankStatementLabel.BREAK : CompletionOnBrankStatementLabel.CONTINUE,
- this.identifierStack[this.identifierPtr--],
- (int) (position >>> 32),
- (int)position,
- labels);
-
- this.assistNode = statementLabel;
- this.lastCheckPoint = this.assistNode.sourceEnd + 1;
- this.isOrphanCompletionNode = true;
- return true;
- }
- return false;
-}
-/**
- * Checks if the completion is on a member access (ie. in an identifier following a dot).
- * Returns whether we found a completion node.
- */
-private boolean checkMemberAccess() {
- if (this.previousToken == TokenNameDOT && this.qualifier > -1 && this.expressionPtr == this.qualifier) {
- if (this.identifierLengthPtr > 1 && this.identifierLengthStack[this.identifierLengthPtr - 1] < 0) {
- // its not a member access because the receiver is a base type
- // fix for bug: https://bugs.eclipse.org/bugs/show_bug.cgi?id=137623
- return false;
- }
- // the receiver is an expression
- pushCompletionOnMemberAccessOnExpressionStack(false);
- return true;
- }
- return false;
-}
-/**
- * Checks if the completion is on a name reference.
- * Returns whether we found a completion node.
- */
-private boolean checkNameCompletion() {
- /*
- We didn't find any other completion, but the completion identifier is on the identifier stack,
- so it can only be a completion on name.
- Note that we allow the completion on a name even if nothing is expected (eg. foo() b[cursor] would
- be a completion on 'b'). This policy gives more to the user than he/she would expect, but this
- simplifies the problem. To fix this, the recovery must be changed to work at a 'statement' granularity
- instead of at the 'expression' granularity as it does right now.
- */
-
- // NB: at this point the completion identifier is on the identifier stack
- this.assistNode = getUnspecifiedReferenceOptimized();
- this.lastCheckPoint = this.assistNode.sourceEnd + 1;
- this.isOrphanCompletionNode = true;
- return true;
-}
-/**
- * Checks if the completion is in the context of a method and on the type of one of its arguments
- * Returns whether we found a completion node.
- */
-private boolean checkRecoveredMethod() {
- if (currentElement instanceof RecoveredMethod){
- /* check if current awaiting identifier is the completion identifier */
- if (this.indexOfAssistIdentifier() < 0) return false;
-
- /* check if on line with an error already - to avoid completing inside
- illegal type names e.g. int[<cursor> */
- if (lastErrorEndPosition <= cursorLocation+1
- && Util.getLineNumber(lastErrorEndPosition, scanner.lineEnds, 0, scanner.linePtr)
- == Util.getLineNumber(((CompletionScanner)scanner).completedIdentifierStart, scanner.lineEnds, 0, scanner.linePtr)){
- return false;
- }
- RecoveredMethod recoveredMethod = (RecoveredMethod)currentElement;
- /* only consider if inside method header */
- if (!recoveredMethod.foundOpeningBrace
- && lastIgnoredToken == -1) {
- //if (rParenPos < lParenPos){ // inside arguments
- this.assistNode = this.getTypeReference(0);
- this.lastCheckPoint = this.assistNode.sourceEnd + 1;
- this.isOrphanCompletionNode = true;
- return true;
- }
- }
- return false;
-}
-/**
- * Checks if the completion is in the context of a type and on a type reference in this type.
- * Persists the identifier into a fake field return type
- * Returns whether we found a completion node.
- */
-private boolean checkRecoveredType() {
- if (currentElement instanceof RecoveredType){
- /* check if current awaiting identifier is the completion identifier */
- if (this.indexOfAssistIdentifier() < 0) return false;
-
- /* check if on line with an error already - to avoid completing inside
- illegal type names e.g. int[<cursor> */
- if ((lastErrorEndPosition <= cursorLocation+1)
- && Util.getLineNumber(lastErrorEndPosition, scanner.lineEnds, 0, scanner.linePtr)
- == Util.getLineNumber(((CompletionScanner)scanner).completedIdentifierStart, scanner.lineEnds, 0, scanner.linePtr)){
- return false;
- }
- RecoveredType recoveredType = (RecoveredType)currentElement;
- /* filter out cases where scanner is still inside type header */
- if (recoveredType.foundOpeningBrace) {
- // complete generics stack if necessary
- if((this.genericsIdentifiersLengthPtr < 0 && this.identifierPtr > -1)
- || (this.genericsIdentifiersLengthStack[this.genericsIdentifiersLengthPtr] <= this.identifierPtr)) {
- pushOnGenericsIdentifiersLengthStack(this.identifierLengthStack[this.identifierLengthPtr]);
- pushOnGenericsLengthStack(0); // handle type arguments
- }
- this.assistNode = this.getTypeReference(0);
- this.lastCheckPoint = this.assistNode.sourceEnd + 1;
- this.isOrphanCompletionNode = true;
- return true;
- } else {
- if(recoveredType.typeDeclaration.superclass == null &&
- this.topKnownElementKind(COMPLETION_OR_ASSIST_PARSER) == K_EXTENDS_KEYWORD) {
- this.consumeClassOrInterfaceName();
- this.pushOnElementStack(K_NEXT_TYPEREF_IS_CLASS);
- this.assistNode = this.getTypeReference(0);
- this.popElement(K_NEXT_TYPEREF_IS_CLASS);
- this.lastCheckPoint = this.assistNode.sourceEnd + 1;
- this.isOrphanCompletionNode = true;
- return true;
- }
- }
- }
- return false;
-}
-private void classHeaderExtendsOrImplements(boolean isInterface) {
- if (currentElement != null
- && currentToken == TokenNameIdentifier
- && this.cursorLocation+1 >= scanner.startPosition
- && this.cursorLocation < scanner.currentPosition){
- this.pushIdentifier();
- int index = -1;
- /* check if current awaiting identifier is the completion identifier */
- if ((index = this.indexOfAssistIdentifier()) > -1) {
- int ptr = this.identifierPtr - this.identifierLengthStack[this.identifierLengthPtr] + index + 1;
- RecoveredType recoveredType = (RecoveredType)currentElement;
- /* filter out cases where scanner is still inside type header */
- if (!recoveredType.foundOpeningBrace) {
- TypeDeclaration type = recoveredType.typeDeclaration;
- if(!isInterface) {
- char[][] keywords = new char[Keywords.COUNT][];
- int count = 0;
-
-
- if(type.superclass == null) {
- keywords[count++] = Keywords.EXTENDS;
- }
- keywords[count++] = Keywords.IMPLEMENTS;
-
- System.arraycopy(keywords, 0, keywords = new char[count][], 0, count);
-
- if(count > 0) {
- CompletionOnKeyword1 completionOnKeyword = new CompletionOnKeyword1(
- identifierStack[ptr],
- identifierPositionStack[ptr],
- keywords);
- completionOnKeyword.canCompleteEmptyToken = true;
- type.superclass = completionOnKeyword;
- type.superclass.bits |= ASTNode.IsSuperType;
- this.assistNode = completionOnKeyword;
- this.lastCheckPoint = completionOnKeyword.sourceEnd + 1;
- }
- } else {
- CompletionOnKeyword1 completionOnKeyword = new CompletionOnKeyword1(
- identifierStack[ptr],
- identifierPositionStack[ptr],
- Keywords.EXTENDS);
- completionOnKeyword.canCompleteEmptyToken = true;
- this.assistNode = completionOnKeyword;
- this.lastCheckPoint = completionOnKeyword.sourceEnd + 1;
- }
- }
- }
- }
-}
-/*
- * Check whether about to shift beyond the completion token.
- * If so, depending on the context, a special node might need to be created
- * and attached to the existing recovered structure so as to be remember in the
- * resulting parsed structure.
- */
-public void completionIdentifierCheck(){
- //if (assistNode != null) return;
-
- if (checkKeyword()) return;
- if (checkRecoveredType()) return;
- if (checkRecoveredMethod()) return;
-
- // if not in a method in non diet mode and if not inside a field initializer, only record references attached to types
-// if (!(isInsideMethod() && !this.diet)
-// && !isIndirectlyInsideFieldInitialization()
-// && !isInsideAttributeValue()) return;
-
- /*
- In some cases, the completion identifier may not have yet been consumed,
- e.g. int.[cursor]
- This is because the grammar does not allow any (empty) identifier to follow
- a base type. We thus have to manually force the identifier to be consumed
- (that is, pushed).
- */
- if (assistIdentifier() == null && this.currentToken == TokenNameIdentifier) { // Test below copied from CompletionScanner.getCurrentIdentifierSource()
- if (cursorLocation < this.scanner.startPosition && this.scanner.currentPosition == this.scanner.startPosition){ // fake empty identifier got issued
- this.pushIdentifier();
- } else if (cursorLocation+1 >= this.scanner.startPosition && cursorLocation < this.scanner.currentPosition){
- this.pushIdentifier();
- }
- }
-
- // check for different scenarii
- // no need to go further if we found a non empty completion node
- // (we still need to store labels though)
- if (this.assistNode != null) {
- // however inside an invocation, the completion identifier may already have been consumed into an empty name
- // completion, so this check should be before we check that we are at the cursor location
- if (!isEmptyNameCompletion() || checkInvocation()) return;
- }
-
- // no need to check further if we are not at the cursor location
- if (this.indexOfAssistIdentifier() < 0) return;
-
- if (checkClassInstanceCreation()) return;
- if (checkCatchClause()) return;
- if (checkMemberAccess()) return;
- if (checkClassLiteralAccess()) return;
- if (checkInstanceofKeyword()) return;
-
- // if the completion was not on an empty name, it can still be inside an invocation (eg. this.fred("abc"[cursor])
- // (NB: Put this check before checkNameCompletion() because the selector of the invocation can be on the identifier stack)
- if (checkInvocation()) return;
-
- if (checkLabelStatement()) return;
- if (checkNameCompletion()) return;
-}
-protected void consumeArrayCreationHeader() {
- // nothing to do
-}
-protected void consumeAssignment() {
- popElement(K_ASSISGNMENT_OPERATOR);
- super.consumeAssignment();
-}
-protected void consumeAssignmentOperator(int pos) {
- super.consumeAssignmentOperator(pos);
- pushOnElementStack(K_ASSISGNMENT_OPERATOR, pos);
-}
-protected void consumeBinaryExpression(int op) {
- super.consumeBinaryExpression(op);
- popElement(K_BINARY_OPERATOR);
-
- if(expressionStack[expressionPtr] instanceof BinaryExpression) {
- BinaryExpression exp = (BinaryExpression) expressionStack[expressionPtr];
- if(assistNode != null && exp.right == assistNode) {
- assistNodeParent = exp;
- }
- }
-}
-protected void consumeCaseLabel() {
- super.consumeCaseLabel();
- if(topKnownElementKind(COMPLETION_OR_ASSIST_PARSER) != K_SWITCH_LABEL) {
- pushOnElementStack(K_SWITCH_LABEL);
- }
-}
-
-/* (non-Javadoc)
- * @see org.eclipse.jdt.internal.compiler.parser.Parser#consumeCompilationUnit()
- */
-protected void consumeCompilationUnit() {
- this.javadoc = null;
- checkComment();
- if (this.javadoc != null && this.cursorLocation > this.javadoc.sourceStart && this.cursorLocation < this.javadoc.sourceEnd) {
- // completion is in an orphan javadoc comment => replace compilation unit one to allow completion resolution
- compilationUnit.javadoc = this.javadoc;
- // create a fake interface declaration to allow resolution
- if (this.compilationUnit.types == null) {
- this.compilationUnit.types = new TypeDeclaration[1];
- TypeDeclaration declaration = new TypeDeclaration(compilationUnit.compilationResult);
- declaration.name = FAKE_TYPE_NAME;
- declaration.modifiers = ClassFileConstants.AccDefault;
- this.compilationUnit.types[0] = declaration;
- }
- }
- super.consumeCompilationUnit();
-}
-
-protected void consumeConditionalExpression(int op) {
- popElement(K_CONDITIONAL_OPERATOR);
- super.consumeConditionalExpression(op);
-}
-protected void consumeDefaultLabel() {
- super.consumeDefaultLabel();
- if(topKnownElementKind(COMPLETION_OR_ASSIST_PARSER) == K_SWITCH_LABEL) {
- popElement(K_SWITCH_LABEL);
- }
- pushOnElementStack(K_SWITCH_LABEL, DEFAULT);
-}
-protected void consumeDimWithOrWithOutExpr() {
- // DimWithOrWithOutExpr ::= '[' ']'
- pushOnExpressionStack(null);
-}
-protected void consumeEnterVariable() {
- identifierPtr--;
- identifierLengthPtr--;
-
- boolean isLocalDeclaration = true;//nestedMethod[nestedType] != 0;
- int variableIndex = variablesCounter[nestedType];
- int extendedDimension = intStack[intPtr + 1];
-
- if(isLocalDeclaration || indexOfAssistIdentifier() < 0 || variableIndex != 0 || extendedDimension != 0) {
- identifierPtr++;
- identifierLengthPtr++;
- super.consumeEnterVariable();
- } else {
- restartRecovery = AssistParser.STOP_AT_CURSOR;
-
- // recovery
- if (currentElement != null) {
- if(!checkKeyword() && !(currentElement instanceof RecoveredUnit && ((RecoveredUnit)currentElement).statementCount == 0)) {
- int nameSourceStart = (int)(identifierPositionStack[identifierPtr] >>> 32);
- intPtr--;
-// pushOnGenericsIdentifiersLengthStack(identifierLengthStack[identifierLengthPtr]);
-// pushOnGenericsLengthStack(0);
- TypeReference type = getTypeReference(intStack[intPtr--]);
- intPtr--;
-
- if (!(currentElement instanceof RecoveredType)
- && (currentToken == TokenNameDOT
- || (Util.getLineNumber(type.sourceStart, scanner.lineEnds, 0, scanner.linePtr)
- != Util.getLineNumber(nameSourceStart, scanner.lineEnds, 0, scanner.linePtr)))){
- lastCheckPoint = nameSourceStart;
- restartRecovery = true;
- return;
- }
-
- FieldDeclaration completionFieldDecl = new CompletionOnFieldType(type, false);
- completionFieldDecl.modifiers = intStack[intPtr--];
- assistNode = completionFieldDecl;
- lastCheckPoint = type.sourceEnd + 1;
- currentElement = currentElement.add(completionFieldDecl, 0);
- lastIgnoredToken = -1;
- }
- }
- }
-}
-protected void consumeEqualityExpression(int op) {
- super.consumeEqualityExpression(op);
- popElement(K_BINARY_OPERATOR);
-
- BinaryExpression exp = (BinaryExpression) expressionStack[expressionPtr];
- if(assistNode != null && exp.right == assistNode) {
- assistNodeParent = exp;
- }
-}
-protected void consumeExitVariableWithInitialization() {
- super.consumeExitVariableWithInitialization();
-
- // does not keep the initialization if completion is not inside
- AbstractVariableDeclaration variable = (AbstractVariableDeclaration) astStack[astPtr];
- if (cursorLocation + 1 < variable.initialization.sourceStart ||
- cursorLocation > variable.initialization.sourceEnd) {
- if (STOP_AT_CURSOR)
- variable.initialization = null;
- } else if (assistNode != null && assistNode == variable.initialization) {
- assistNodeParent = variable;
- }
-}
-protected void consumeCallExpressionWithSimpleName() {
- this.invocationType = NO_RECEIVER;
- this.qualifier = -1;
-
- if (this.indexOfAssistIdentifier() < 0) {
- super.consumeCallExpressionWithSimpleName();
- } else {
- this.pushCompletionOnMemberAccessOnExpressionStack(false);
- }
-}
-protected void consumeMemberExpressionWithSimpleName() {
- this.invocationType = NO_RECEIVER;
- this.qualifier = -1;
-
- if (this.indexOfAssistIdentifier() < 0) {
- super.consumeMemberExpressionWithSimpleName();
- } else {
- this.pushCompletionOnMemberAccessOnExpressionStack(false);
- }
-}
-protected void consumeForceNoDiet() {
- super.consumeForceNoDiet();
- if (isInsideMethod()) {
- pushOnElementStack(K_LOCAL_INITIALIZER_DELIMITER);
- }
-}
-protected void consumeFormalParameter(boolean isVarArgs) {
- if (this.indexOfAssistIdentifier() < 0) {
- super.consumeFormalParameter(isVarArgs);
- } else {
-
- identifierLengthPtr--;
- char[] identifierName = identifierStack[identifierPtr];
- long namePositions = identifierPositionStack[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
-// }
- intPtr -= 2;
- CompletionOnArgumentName arg =
- new CompletionOnArgumentName(
- identifierName,
- namePositions,
- null,
- intStack[intPtr + 1] & ~ClassFileConstants.AccDeprecated); // modifiers
- // 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);
-// }
-
- arg.isCatchArgument = topKnownElementKind(COMPLETION_OR_ASSIST_PARSER) == K_BETWEEN_CATCH_AND_RIGHT_PAREN;
- pushOnAstStack(arg);
-
- assistNode = arg;
- this.lastCheckPoint = (int) namePositions;
- isOrphanCompletionNode = true;
-
- /* if incomplete method header, listLength counter will not have been reset,
- indicating that some arguments are available on the stack */
- listLength++;
- }
-}
-protected void consumeInsideCastExpression() {
- int end = intStack[intPtr--];
- boolean isParameterized =(topKnownElementKind(COMPLETION_OR_ASSIST_PARSER) == K_PARAMETERIZED_CAST);
- if(isParameterized) {
- popElement(K_PARAMETERIZED_CAST);
-
- if(this.identifierLengthStack[this.identifierLengthPtr] > 0) {
- pushOnGenericsIdentifiersLengthStack(this.identifierLengthStack[this.identifierLengthPtr]);
- }
- } else {
- if(this.identifierLengthStack[this.identifierLengthPtr] > 0) {
- pushOnGenericsIdentifiersLengthStack(this.identifierLengthStack[this.identifierLengthPtr]);
- pushOnGenericsLengthStack(0);
- }
- }
- Expression castType = getTypeReference(intStack[intPtr--]);
- if(isParameterized) {
- intPtr--;
- }
- castType.sourceEnd = end - 1;
- castType.sourceStart = intStack[intPtr--] + 1;
- pushOnExpressionStack(castType);
-
- pushOnElementStack(K_CAST_STATEMENT);
-}
-protected void consumeCallExpressionWithArguments() {
- popElement(K_SELECTOR_QUALIFIER);
- popElement(K_SELECTOR_INVOCATION_TYPE);
- super.consumeCallExpressionWithArguments();
-}
-protected void consumeMethodHeaderName(boolean isAnnotationMethod) {
- if(this.indexOfAssistIdentifier() < 0) {
- identifierPtr--;
- identifierLengthPtr--;
- if(this.indexOfAssistIdentifier() != 0 ||
- this.identifierLengthStack[this.identifierLengthPtr] != this.genericsIdentifiersLengthStack[this.genericsIdentifiersLengthPtr]) {
- identifierPtr++;
- identifierLengthPtr++;
- super.consumeMethodHeaderName(isAnnotationMethod);
- } else {
- restartRecovery = AssistParser.STOP_AT_CURSOR;
-
- // recovery
- if (currentElement != null) {
- //name
-// char[] selector = identifierStack[identifierPtr + 1];
-// long selectorSource = identifierPositionStack[identifierPtr + 1];
-
-// //type
-// TypeReference type = getTypeReference(intStack[intPtr--]);
-// ((CompletionOnSingleTypeReference)type).isCompletionNode = false;
-// //modifiers
-// int declarationSourceStart = intStack[intPtr--];
-// int mod = intStack[intPtr--];
-
-// if(Util.getLineNumber(type.sourceStart, scanner.lineEnds, 0, scanner.linePtr)
-// != Util.getLineNumber((int) (selectorSource >>> 32), scanner.lineEnds, 0, scanner.linePtr)) {
-// FieldDeclaration completionFieldDecl = new CompletionOnFieldType(type, false);
-// // consume annotations
-// int length;
-// if ((length = this.expressionLengthStack[this.expressionLengthPtr--]) != 0) {
-// System.arraycopy(
-// this.expressionStack,
-// (this.expressionPtr -= length) + 1,
-// completionFieldDecl.annotations = new Annotation[length],
-// 0,
-// length);
-// }
-// completionFieldDecl.modifiers = mod;
-// assistNode = completionFieldDecl;
-// lastCheckPoint = type.sourceEnd + 1;
-// currentElement = currentElement.add(completionFieldDecl, 0);
-// lastIgnoredToken = -1;
-// } else {
-// CompletionOnMethodReturnType md = new CompletionOnMethodReturnType(type, this.compilationUnit.compilationResult);
-// // 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);
-// }
-// md.selector = selector;
-// md.declarationSourceStart = declarationSourceStart;
-// md.modifiers = mod;
-// md.bodyStart = lParenPos+1;
-// listLength = 0; // initialize listLength before reading parameters/throws
-// assistNode = md;
-// this.lastCheckPoint = md.bodyStart;
-// currentElement = currentElement.add(md, 0);
-// lastIgnoredToken = -1;
-// // javadoc
-// md.javadoc = this.javadoc;
-// this.javadoc = null;
-// }
- }
- }
- } else {
- // MethodHeaderName ::= Modifiersopt Type 'Identifier' '('
- CompletionOnMethodName md = new CompletionOnMethodName(this.compilationUnit.compilationResult);
-
- //name
- md.selector = identifierStack[identifierPtr];
- long selectorSource = identifierPositionStack[identifierPtr--];
- identifierLengthPtr--;
- //type
- md.returnType = getTypeReference(intStack[intPtr--]);
- //modifiers
- md.declarationSourceStart = intStack[intPtr--];
- md.modifiers = intStack[intPtr--];
- this.expressionLengthPtr--;
- // javadoc
- md.javadoc = this.javadoc;
- this.javadoc = null;
-
- //highlight starts at selector start
- md.sourceStart = (int) (selectorSource >>> 32);
- md.selectorEnd = (int) selectorSource;
- pushOnAstStack(md);
- md.sourceEnd = lParenPos;
- md.bodyStart = lParenPos+1;
- listLength = 0; // initialize listLength before reading parameters/throws
-
- this.assistNode = md;
- this.lastCheckPoint = md.sourceEnd;
- // recovery
- if (currentElement != null){
- if (currentElement instanceof RecoveredType
- //|| md.modifiers != 0
- || (Util.getLineNumber(md.returnType.sourceStart, scanner.lineEnds, 0, scanner.linePtr)
- == Util.getLineNumber(md.sourceStart, scanner.lineEnds, 0, scanner.linePtr))){
- lastCheckPoint = md.bodyStart;
- currentElement = currentElement.add(md, 0);
- lastIgnoredToken = -1;
- } else {
- lastCheckPoint = md.sourceStart;
- restartRecovery = AssistParser.STOP_AT_CURSOR;
- }
- }
- }
-}
-protected void consumeMethodHeaderRightParen() {
- super.consumeMethodHeaderRightParen();
-
- if (currentElement != null
- && currentToken == TokenNameIdentifier
- && this.cursorLocation+1 >= scanner.startPosition
- && this.cursorLocation < scanner.currentPosition){
- this.pushIdentifier();
-
- int index = -1;
- /* check if current awaiting identifier is the completion identifier */
- if ((index = this.indexOfAssistIdentifier()) > -1) {
- int ptr = this.identifierPtr - this.identifierLengthStack[this.identifierLengthPtr] + index + 1;
- if (currentElement instanceof RecoveredMethod){
- RecoveredMethod recoveredMethod = (RecoveredMethod)currentElement;
- /* filter out cases where scanner is still inside type header */
- if (!recoveredMethod.foundOpeningBrace) {
- CompletionOnKeyword1 completionOnKeyword = new CompletionOnKeyword1(
- identifierStack[ptr],
- identifierPositionStack[ptr],
- Keywords.THROWS);
- recoveredMethod.foundOpeningBrace = true;
- this.assistNode = completionOnKeyword;
- this.lastCheckPoint = completionOnKeyword.sourceEnd + 1;
- }
- }
- }
- }
-}
-protected void consumeLabel() {
- super.consumeLabel();
- this.pushOnLabelStack(this.identifierStack[this.identifierPtr]);
- this.pushOnElementStack(K_LABEL, this.labelPtr);
-}
-protected void consumeMethodBody() {
- popElement(K_BLOCK_DELIMITER);
- super.consumeMethodBody();
-}
-protected void consumeMethodHeader() {
- super.consumeMethodHeader();
- pushOnElementStack(K_BLOCK_DELIMITER);
-}
-protected void consumeRestoreDiet() {
- super.consumeRestoreDiet();
- if (isInsideMethod()) {
- popElement(K_LOCAL_INITIALIZER_DELIMITER);
- }
-}
-protected void consumeStatementBreakWithLabel() {
- super.consumeStatementBreakWithLabel();
- if (this.record) {
- ASTNode breakStatement = this.astStack[this.astPtr];
- if (!isAlreadyPotentialName(breakStatement.sourceStart)) {
- this.addPotentialName(null, breakStatement.sourceStart, breakStatement.sourceEnd);
- }
- }
-
-}
-
-protected void consumeStatementLabel() {
- this.popElement(K_LABEL);
- super.consumeStatementLabel();
-}
-protected void consumeStatementSwitch() {
- super.consumeStatementSwitch();
- if(topKnownElementKind(COMPLETION_OR_ASSIST_PARSER) == K_SWITCH_LABEL) {
- popElement(K_SWITCH_LABEL);
- popElement(K_BLOCK_DELIMITER);
- }
-}
-protected void consumeNestedMethod() {
- super.consumeNestedMethod();
- if(!(topKnownElementKind(COMPLETION_OR_ASSIST_PARSER) == K_BLOCK_DELIMITER)) pushOnElementStack(K_BLOCK_DELIMITER);
-}
-protected void consumePushPosition() {
- super.consumePushPosition();
- if(topKnownElementKind(COMPLETION_OR_ASSIST_PARSER) == K_BINARY_OPERATOR) {
- int info = topKnownElementInfo(COMPLETION_OR_ASSIST_PARSER);
- popElement(K_BINARY_OPERATOR);
- pushOnElementStack(K_UNARY_OPERATOR, info);
- }
-}
-protected void consumeToken(int token) {
- if(isFirst) {
- super.consumeToken(token);
- return;
- }
- if(canBeExplicitConstructor == NEXTTOKEN) {
- canBeExplicitConstructor = YES;
- } else {
- canBeExplicitConstructor = NO;
- }
-
- int previous = this.previousToken;
- int prevIdentifierPtr = this.previousIdentifierPtr;
-
- if (isInsideMethod() || isInsideFieldInitialization() || isInsideAnnotation()) {
- switch(token) {
- case TokenNameLPAREN:
- if(previous == TokenNameIdentifier &&
- topKnownElementKind(COMPLETION_OR_ASSIST_PARSER) == K_PARAMETERIZED_METHOD_INVOCATION) {
- popElement(K_PARAMETERIZED_METHOD_INVOCATION);
- } else {
- popElement(K_BETWEEN_NEW_AND_LEFT_BRACKET);
- }
- break;
- case TokenNameLBRACE:
- popElement(K_BETWEEN_NEW_AND_LEFT_BRACKET);
- break;
- case TokenNameLBRACKET:
- if(topKnownElementKind(COMPLETION_OR_ASSIST_PARSER) == K_BETWEEN_NEW_AND_LEFT_BRACKET) {
- popElement(K_BETWEEN_NEW_AND_LEFT_BRACKET);
- pushOnElementStack(K_ARRAY_CREATION);
- }
- break;
- case TokenNameRBRACE:
- int kind = topKnownElementKind(COMPLETION_OR_ASSIST_PARSER);
- switch (kind) {
- case K_BLOCK_DELIMITER:
- popElement(K_BLOCK_DELIMITER);
- break;
- case K_MEMBER_VALUE_ARRAY_INITIALIZER:
- popElement(K_MEMBER_VALUE_ARRAY_INITIALIZER);
- break;
- default:
- popElement(K_ARRAY_INITIALIZER);
- break;
- }
- break;
- case TokenNameRBRACKET:
- if(topKnownElementKind(COMPLETION_OR_ASSIST_PARSER) == K_BETWEEN_LEFT_AND_RIGHT_BRACKET) {
- popElement(K_BETWEEN_LEFT_AND_RIGHT_BRACKET);
- }
- break;
-
- }
- }
- super.consumeToken(token);
-
- // if in field initializer (directly or not), on the completion identifier and not in recovery mode yet
- // then position end of file at cursor location (so that we have the same behavior as
- // in method bodies)
- if (token == TokenNameIdentifier
- && this.identifierStack[this.identifierPtr] == assistIdentifier()
- && this.currentElement == null
- && this.isIndirectlyInsideFieldInitialization()) {
-// this.scanner.eofPosition = cursorLocation < Integer.MAX_VALUE ? cursorLocation+1 : cursorLocation;
- }
-
- // if in a method or if in a field initializer
- if (isInsideMethod() || isInsideFieldInitialization() || isInsideAttributeValue()) {
- switch (token) {
- case TokenNameDOT:
- switch (previous) {
- case TokenNamethis: // eg. this[.]fred()
- this.invocationType = EXPLICIT_RECEIVER;
- break;
- case TokenNamesuper: // eg. super[.]fred()
- this.invocationType = SUPER_RECEIVER;
- break;
- case TokenNameIdentifier: // eg. bar[.]fred()
- if (topKnownElementKind(COMPLETION_OR_ASSIST_PARSER) != K_BETWEEN_NEW_AND_LEFT_BRACKET) {
- if (this.identifierPtr != prevIdentifierPtr) { // if identifier has been consumed, eg. this.x[.]fred()
- this.invocationType = EXPLICIT_RECEIVER;
- } else {
- this.invocationType = NAME_RECEIVER;
- }
- }
- break;
- }
- break;
- case TokenNameIdentifier:
- if (previous == TokenNameDOT) { // eg. foo().[fred]()
- if (this.invocationType != SUPER_RECEIVER // eg. not super.[fred]()
- && this.invocationType != NAME_RECEIVER // eg. not bar.[fred]()
- && this.invocationType != ALLOCATION // eg. not new foo.[Bar]()
- && this.invocationType != QUALIFIED_ALLOCATION) { // eg. not fred().new foo.[Bar]()
-
- this.invocationType = EXPLICIT_RECEIVER;
- this.qualifier = this.expressionPtr;
- }
- }
- break;
- case TokenNamenew:
- pushOnElementStack(K_BETWEEN_NEW_AND_LEFT_BRACKET);
- this.qualifier = this.expressionPtr; // NB: even if there is no qualification, set it to the expression ptr so that the number of arguments are correctly computed
- if (previous == TokenNameDOT) { // eg. fred().[new] X()
- this.invocationType = QUALIFIED_ALLOCATION;
- } else { // eg. [new] X()
- this.invocationType = ALLOCATION;
- }
- break;
- case TokenNamethis:
- if (previous == TokenNameDOT) { // eg. fred().[this]()
- this.invocationType = QUALIFIED_ALLOCATION;
- this.qualifier = this.expressionPtr;
- }
- break;
- case TokenNamesuper:
- if (previous == TokenNameDOT) { // eg. fred().[super]()
- this.invocationType = QUALIFIED_ALLOCATION;
- this.qualifier = this.expressionPtr;
- }
- break;
- case TokenNamecatch:
- pushOnElementStack(K_BETWEEN_CATCH_AND_RIGHT_PAREN);
- break;
- case TokenNameLPAREN:
- if (this.invocationType == NO_RECEIVER || this.invocationType == NAME_RECEIVER || this.invocationType == SUPER_RECEIVER) {
- this.qualifier = this.expressionPtr; // remenber the last expression so that arguments are correctly computed
- }
- switch (previous) {
- case TokenNameIdentifier: // eg. fred[(]) or foo.fred[(])
- if (topKnownElementKind(COMPLETION_OR_ASSIST_PARSER) == K_SELECTOR) {
- int info = 0;
- if(topKnownElementKind(COMPLETION_OR_ASSIST_PARSER,1) == K_BETWEEN_ANNOTATION_NAME_AND_RPAREN &&
- (info=topKnownElementInfo(COMPLETION_OR_ASSIST_PARSER,1) & LPAREN_NOT_CONSUMED) != 0) {
- this.popElement(K_SELECTOR);
- this.popElement(K_BETWEEN_ANNOTATION_NAME_AND_RPAREN);
- if ((info & ANNOTATION_NAME_COMPLETION) != 0) {
- this.pushOnElementStack(K_BETWEEN_ANNOTATION_NAME_AND_RPAREN, LPAREN_CONSUMED | ANNOTATION_NAME_COMPLETION);
- } else {
- this.pushOnElementStack(K_BETWEEN_ANNOTATION_NAME_AND_RPAREN, LPAREN_CONSUMED);
- } } else {
- this.pushOnElementStack(K_SELECTOR_INVOCATION_TYPE, this.invocationType);
- int selectorQualifier=(this.invocationType==ALLOCATION)?this.expressionPtr:this.qualifier;
- this.pushOnElementStack(K_SELECTOR_QUALIFIER, selectorQualifier);
- }
- }
- this.qualifier = -1;
- this.invocationType = NO_RECEIVER;
- break;
- case TokenNamethis: // explicit constructor invocation, eg. this[(]1, 2)
- if (topKnownElementKind(COMPLETION_OR_ASSIST_PARSER) == K_SELECTOR) {
- this.pushOnElementStack(K_SELECTOR_INVOCATION_TYPE, (this.invocationType == QUALIFIED_ALLOCATION) ? QUALIFIED_ALLOCATION : ALLOCATION);
- this.pushOnElementStack(K_SELECTOR_QUALIFIER, this.qualifier);
- }
- this.qualifier = -1;
- this.invocationType = NO_RECEIVER;
- break;
- case TokenNamesuper: // explicit constructor invocation, eg. super[(]1, 2)
- if (topKnownElementKind(COMPLETION_OR_ASSIST_PARSER) == K_SELECTOR) {
- this.pushOnElementStack(K_SELECTOR_INVOCATION_TYPE, (this.invocationType == QUALIFIED_ALLOCATION) ? QUALIFIED_ALLOCATION : ALLOCATION);
- this.pushOnElementStack(K_SELECTOR_QUALIFIER, this.qualifier);
- }
- this.qualifier = -1;
- this.invocationType = NO_RECEIVER;
- break;
- case TokenNameGREATER: // explicit constructor invocation, eg. Fred<X>[(]1, 2)
- case TokenNameRIGHT_SHIFT: // or fred<X<X>>[(]1, 2)
- case TokenNameUNSIGNED_RIGHT_SHIFT: //or Fred<X<X<X>>>[(]1, 2)
- if (topKnownElementKind(COMPLETION_OR_ASSIST_PARSER) == K_SELECTOR) {
- if (topKnownElementKind(COMPLETION_OR_ASSIST_PARSER, 1) == K_BINARY_OPERATOR &&
- topKnownElementInfo(COMPLETION_OR_ASSIST_PARSER, 1) == GREATER) {
- // it's not a selector invocation
- popElement(K_SELECTOR);
- } else {
- this.pushOnElementStack(K_SELECTOR_INVOCATION_TYPE, (this.invocationType == QUALIFIED_ALLOCATION) ? QUALIFIED_ALLOCATION : ALLOCATION);
- this.pushOnElementStack(K_SELECTOR_QUALIFIER, this.qualifier);
- }
- }
- this.qualifier = -1;
- this.invocationType = NO_RECEIVER;
- break;
- }
- break;
- case TokenNameLBRACE:
- this.bracketDepth++;
- int kind = topKnownElementKind(COMPLETION_OR_ASSIST_PARSER);
- if(kind == K_FIELD_INITIALIZER_DELIMITER
- || kind == K_LOCAL_INITIALIZER_DELIMITER
- || kind == K_ARRAY_CREATION) {
- pushOnElementStack(K_ARRAY_INITIALIZER, endPosition);
- } else if (kind == K_BETWEEN_ANNOTATION_NAME_AND_RPAREN) {
- pushOnElementStack(K_MEMBER_VALUE_ARRAY_INITIALIZER, endPosition);
- } else {
- switch(previous) {
- case TokenNameRPAREN :
- switch(previousKind) {
- case K_BETWEEN_IF_AND_RIGHT_PAREN :
- pushOnElementStack(K_BLOCK_DELIMITER, IF);
- break;
- case K_BETWEEN_CATCH_AND_RIGHT_PAREN :
- pushOnElementStack(K_BLOCK_DELIMITER, CATCH);
- break;
- case K_BETWEEN_WHILE_AND_RIGHT_PAREN :
- pushOnElementStack(K_BLOCK_DELIMITER, WHILE);
- break;
- case K_BETWEEN_SWITCH_AND_RIGHT_PAREN :
- pushOnElementStack(K_BLOCK_DELIMITER, SWITCH);
- break;
- case K_BETWEEN_FOR_AND_RIGHT_PAREN :
- pushOnElementStack(K_BLOCK_DELIMITER, FOR);
- break;
- case K_BETWEEN_SYNCHRONIZED_AND_RIGHT_PAREN :
- pushOnElementStack(K_BLOCK_DELIMITER, SYNCHRONIZED);
- break;
- default :
- pushOnElementStack(K_BLOCK_DELIMITER);
- break;
- }
- break;
- case TokenNametry :
- pushOnElementStack(K_BLOCK_DELIMITER, TRY);
- break;
- case TokenNamedo:
- pushOnElementStack(K_BLOCK_DELIMITER, DO);
- break;
- default :
- pushOnElementStack(K_BLOCK_DELIMITER);
- break;
- }
- }
- break;
- case TokenNameLBRACKET:
- if(topKnownElementKind(COMPLETION_OR_ASSIST_PARSER) != K_ARRAY_CREATION) {
- pushOnElementStack(K_BETWEEN_LEFT_AND_RIGHT_BRACKET);
- } else {
- if(previous == TokenNameIdentifier) {
- invocationType = NO_RECEIVER;
- qualifier = -1;
- }
- }
- this.bracketDepth++;
- break;
- case TokenNameRBRACE:
- this.bracketDepth--;
- break;
- case TokenNameRBRACKET:
- this.bracketDepth--;
- break;
- case TokenNameRPAREN:
- switch(topKnownElementKind(COMPLETION_OR_ASSIST_PARSER)) {
- case K_BETWEEN_CATCH_AND_RIGHT_PAREN :
- popElement(K_BETWEEN_CATCH_AND_RIGHT_PAREN);
- break;
- case K_BETWEEN_IF_AND_RIGHT_PAREN :
- if(topKnownElementInfo(COMPLETION_OR_ASSIST_PARSER) == bracketDepth) {
- popElement(K_BETWEEN_IF_AND_RIGHT_PAREN);
- }
- break;
- case K_BETWEEN_WHILE_AND_RIGHT_PAREN :
- if(topKnownElementInfo(COMPLETION_OR_ASSIST_PARSER) == bracketDepth) {
- popElement(K_BETWEEN_WHILE_AND_RIGHT_PAREN);
- }
- break;
- case K_BETWEEN_FOR_AND_RIGHT_PAREN :
- if(topKnownElementInfo(COMPLETION_OR_ASSIST_PARSER) == bracketDepth) {
- popElement(K_BETWEEN_FOR_AND_RIGHT_PAREN);
- }
- break;
- case K_BETWEEN_SWITCH_AND_RIGHT_PAREN :
- if(topKnownElementInfo(COMPLETION_OR_ASSIST_PARSER) == bracketDepth) {
- popElement(K_BETWEEN_SWITCH_AND_RIGHT_PAREN);
- }
- break;
- case K_BETWEEN_SYNCHRONIZED_AND_RIGHT_PAREN :
- if(topKnownElementInfo(COMPLETION_OR_ASSIST_PARSER) == bracketDepth) {
- popElement(K_BETWEEN_SYNCHRONIZED_AND_RIGHT_PAREN);
- }
- break;
- }
- break;
- case TokenNamethrow:
- pushOnElementStack(K_INSIDE_THROW_STATEMENT, bracketDepth);
- break;
- case TokenNameSEMICOLON:
- switch(topKnownElementKind(COMPLETION_OR_ASSIST_PARSER)) {
- case K_INSIDE_THROW_STATEMENT :
- if(topKnownElementInfo(COMPLETION_OR_ASSIST_PARSER) == this.bracketDepth) {
- popElement(K_INSIDE_THROW_STATEMENT);
- }
- break;
- case K_INSIDE_RETURN_STATEMENT :
- if(topKnownElementInfo(COMPLETION_OR_ASSIST_PARSER) == this.bracketDepth) {
- popElement(K_INSIDE_RETURN_STATEMENT);
- }
- break;
- case K_INSIDE_ASSERT_STATEMENT :
- if(topKnownElementInfo(COMPLETION_OR_ASSIST_PARSER) == this.bracketDepth) {
- popElement(K_INSIDE_ASSERT_STATEMENT);
- }
- break;
- case K_INSIDE_BREAK_STATEMENT:
- if(topKnownElementInfo(COMPLETION_OR_ASSIST_PARSER) == this.bracketDepth) {
- popElement(K_INSIDE_BREAK_STATEMENT);
- }
- break;
- case K_INSIDE_CONTINUE_STATEMENT:
- if(topKnownElementInfo(COMPLETION_OR_ASSIST_PARSER) == this.bracketDepth) {
- popElement(K_INSIDE_CONTINUE_STATEMENT);
- }
- break;
- }
- break;
- case TokenNamereturn:
- pushOnElementStack(K_INSIDE_RETURN_STATEMENT, this.bracketDepth);
- break;
- case TokenNameMULTIPLY:
- pushOnElementStack(K_BINARY_OPERATOR, MULTIPLY);
- break;
- case TokenNameDIVIDE:
- pushOnElementStack(K_BINARY_OPERATOR, DIVIDE);
- break;
- case TokenNameREMAINDER:
- pushOnElementStack(K_BINARY_OPERATOR, REMAINDER);
- break;
- case TokenNamePLUS:
- pushOnElementStack(K_BINARY_OPERATOR, PLUS);
- break;
- case TokenNameMINUS:
- pushOnElementStack(K_BINARY_OPERATOR, MINUS);
- break;
- case TokenNameLEFT_SHIFT:
- pushOnElementStack(K_BINARY_OPERATOR, LEFT_SHIFT);
- break;
- case TokenNameRIGHT_SHIFT:
- pushOnElementStack(K_BINARY_OPERATOR, RIGHT_SHIFT);
- break;
- case TokenNameUNSIGNED_RIGHT_SHIFT:
- pushOnElementStack(K_BINARY_OPERATOR, UNSIGNED_RIGHT_SHIFT);
- break;
- case TokenNameLESS:
- switch(previous) {
- case TokenNameDOT :
- pushOnElementStack(K_PARAMETERIZED_METHOD_INVOCATION);
- break;
- case TokenNamenew :
- pushOnElementStack(K_PARAMETERIZED_ALLOCATION);
- break;
- }
- pushOnElementStack(K_BINARY_OPERATOR, LESS);
- break;
- case TokenNameGREATER:
- pushOnElementStack(K_BINARY_OPERATOR, GREATER);
- break;
- case TokenNameLESS_EQUAL:
- pushOnElementStack(K_BINARY_OPERATOR, LESS_EQUAL);
- break;
- case TokenNameGREATER_EQUAL:
- pushOnElementStack(K_BINARY_OPERATOR, GREATER_EQUAL);
- break;
- case TokenNameAND:
- pushOnElementStack(K_BINARY_OPERATOR, AND);
- break;
- case TokenNameXOR:
- pushOnElementStack(K_BINARY_OPERATOR, XOR);
- break;
- case TokenNameOR:
- pushOnElementStack(K_BINARY_OPERATOR, OR);
- break;
- case TokenNameAND_AND:
- pushOnElementStack(K_BINARY_OPERATOR, AND_AND);
- break;
- case TokenNameOR_OR:
- pushOnElementStack(K_BINARY_OPERATOR, OR_OR);
- break;
- case TokenNamePLUS_PLUS:
- pushOnElementStack(K_UNARY_OPERATOR, PLUS_PLUS);
- break;
- case TokenNameMINUS_MINUS:
- pushOnElementStack(K_UNARY_OPERATOR, MINUS_MINUS);
- break;
- case TokenNameTWIDDLE:
- pushOnElementStack(K_UNARY_OPERATOR, TWIDDLE);
- break;
- case TokenNameNOT:
- pushOnElementStack(K_UNARY_OPERATOR, NOT);
- break;
- case TokenNameEQUAL_EQUAL:
- pushOnElementStack(K_BINARY_OPERATOR, EQUAL_EQUAL);
- break;
- case TokenNameNOT_EQUAL:
- pushOnElementStack(K_BINARY_OPERATOR, NOT_EQUAL);
- break;
- case TokenNameinstanceof:
- pushOnElementStack(K_BINARY_OPERATOR, INSTANCEOF);
- break;
- case TokenNameQUESTION:
- if(previous != TokenNameLESS) {
- pushOnElementStack(K_CONDITIONAL_OPERATOR, QUESTION);
- }
- break;
- case TokenNameCOLON:
- if(topKnownElementKind(COMPLETION_OR_ASSIST_PARSER) == K_CONDITIONAL_OPERATOR
- && topKnownElementInfo(COMPLETION_OR_ASSIST_PARSER) == QUESTION) {
- popElement(K_CONDITIONAL_OPERATOR);
- pushOnElementStack(K_CONDITIONAL_OPERATOR, COLON);
- } else {
- if(topKnownElementKind(COMPLETION_OR_ASSIST_PARSER) == K_BETWEEN_CASE_AND_COLON) {
- popElement(K_BETWEEN_CASE_AND_COLON);
- } else {
- popElement(K_BETWEEN_DEFAULT_AND_COLON);
- }
- }
- break;
- case TokenNameif:
- pushOnElementStack(K_BETWEEN_IF_AND_RIGHT_PAREN, bracketDepth);
- break;
- case TokenNamewhile:
- pushOnElementStack(K_BETWEEN_WHILE_AND_RIGHT_PAREN, bracketDepth);
- break;
- case TokenNamefor:
- pushOnElementStack(K_BETWEEN_FOR_AND_RIGHT_PAREN, bracketDepth);
- break;
- case TokenNameswitch:
- pushOnElementStack(K_BETWEEN_SWITCH_AND_RIGHT_PAREN, bracketDepth);
- break;
- case TokenNamesynchronized:
- pushOnElementStack(K_BETWEEN_SYNCHRONIZED_AND_RIGHT_PAREN, bracketDepth);
- break;
-// case TokenNameassert:
-// pushOnElementStack(K_INSIDE_ASSERT_STATEMENT, this.bracketDepth);
-// break;
- case TokenNamecase :
- pushOnElementStack(K_BETWEEN_CASE_AND_COLON);
- break;
- case TokenNamedefault :
- pushOnElementStack(K_BETWEEN_DEFAULT_AND_COLON);
- break;
- case TokenNameextends:
- pushOnElementStack(K_EXTENDS_KEYWORD);
- break;
- case TokenNamebreak:
- pushOnElementStack(K_INSIDE_BREAK_STATEMENT, bracketDepth);
- break;
- case TokenNamecontinue:
- pushOnElementStack(K_INSIDE_CONTINUE_STATEMENT, bracketDepth);
- break;
- }
- } else {
- switch(token) {
- case TokenNameextends:
- pushOnElementStack(K_EXTENDS_KEYWORD);
- break;
- case TokenNameLESS:
- pushOnElementStack(K_BINARY_OPERATOR, LESS);
- break;
- case TokenNameGREATER:
- pushOnElementStack(K_BINARY_OPERATOR, GREATER);
- break;
- case TokenNameRIGHT_SHIFT:
- pushOnElementStack(K_BINARY_OPERATOR, RIGHT_SHIFT);
- break;
- case TokenNameUNSIGNED_RIGHT_SHIFT:
- pushOnElementStack(K_BINARY_OPERATOR, UNSIGNED_RIGHT_SHIFT);
- break;
-
- }
- }
-}
-protected void consumeRightParen() {
- super.consumeRightParen();
-}
-protected void consumeUnaryExpression(int op) {
- super.consumeUnaryExpression(op);
- popElement(K_UNARY_OPERATOR);
-
- if(expressionStack[expressionPtr] instanceof UnaryExpression) {
- UnaryExpression exp = (UnaryExpression) expressionStack[expressionPtr];
- if(assistNode != null && exp.expression == assistNode) {
- assistNodeParent = exp;
- }
- }
-}
-protected void consumeUnaryExpression(int op, boolean post) {
- super.consumeUnaryExpression(op, post);
- popElement(K_UNARY_OPERATOR);
-
- if(expressionStack[expressionPtr] instanceof UnaryExpression) {
- UnaryExpression exp = (UnaryExpression) expressionStack[expressionPtr];
- if(assistNode != null && exp.expression == assistNode) {
- assistNodeParent = exp;
- }
- }
-}
-
-public ImportReference createAssistImportReference(char[][] tokens, long[] positions){
- return new CompletionOnImportReference(tokens, positions);
-}
-public NameReference createQualifiedAssistNameReference(char[][] previousIdentifiers, char[] assistName, long[] positions){
- return new CompletionOnQualifiedNameReference(
- previousIdentifiers,
- assistName,
- positions,
- isInsideAttributeValue());
-}
-public TypeReference createQualifiedAssistTypeReference(char[][] previousIdentifiers, char[] assistName, long[] positions){
- switch (topKnownElementKind(COMPLETION_OR_ASSIST_PARSER)) {
- case K_NEXT_TYPEREF_IS_EXCEPTION :
- return new CompletionOnQualifiedTypeReference(
- previousIdentifiers,
- assistName,
- positions,
- CompletionOnQualifiedTypeReference.K_EXCEPTION);
- case K_NEXT_TYPEREF_IS_CLASS :
- return new CompletionOnQualifiedTypeReference(
- previousIdentifiers,
- assistName,
- positions,
- CompletionOnQualifiedTypeReference.K_CLASS);
- case K_NEXT_TYPEREF_IS_INTERFACE :
- return new CompletionOnQualifiedTypeReference(
- previousIdentifiers,
- assistName,
- positions,
- CompletionOnQualifiedTypeReference.K_INTERFACE);
- default :
- return new CompletionOnQualifiedTypeReference(
- previousIdentifiers,
- assistName,
- positions);
- }
-}
-public NameReference createSingleAssistNameReference(char[] assistName, long position) {
- int kind = topKnownElementKind(COMPLETION_OR_ASSIST_PARSER);
- if(false){//!isInsideMethod()) {
- if (isInsideFieldInitialization()) {
- return new CompletionOnSingleNameReference(
- assistName,
- position,
- new char[][]{Keywords.FALSE, Keywords.TRUE},
- false,
- isInsideAttributeValue());
- }
- return new CompletionOnSingleNameReference(assistName, position, isInsideAttributeValue());
- } else {
- boolean canBeExplicitConstructorCall = false;
- if(kind == K_BLOCK_DELIMITER
- && previousKind == K_BLOCK_DELIMITER
- && previousInfo == DO) {
- return new CompletionOnKeyword3(assistName, position, Keywords.WHILE);
- } else if(kind == K_BLOCK_DELIMITER
- && previousKind == K_BLOCK_DELIMITER
- && previousInfo == TRY) {
- return new CompletionOnKeyword3(assistName, position, new char[][]{Keywords.CATCH, Keywords.FINALLY});
- } else if(kind == K_BLOCK_DELIMITER
- && topKnownElementInfo(COMPLETION_OR_ASSIST_PARSER) == SWITCH) {
- return new CompletionOnKeyword3(assistName, position, new char[][]{Keywords.CASE, Keywords.DEFAULT});
- } else {
- char[][] keywords = new char[Keywords.COUNT][];
- int count = 0;
-
-// if((lastModifiers & ClassFileConstants.AccStatic) == 0) {
-// keywords[count++]= Keywords.SUPER;
- keywords[count++]= Keywords.THIS;
-// }
- keywords[count++]= Keywords.NEW;
-
- if(kind == K_BLOCK_DELIMITER || kind==0) {
- if(canBeExplicitConstructor == YES) {
- canBeExplicitConstructorCall = true;
- }
-
-// keywords[count++]= Keywords.ASSERT;
- keywords[count++]= Keywords.DO;
- keywords[count++]= Keywords.FOR;
- keywords[count++]= Keywords.IF;
- keywords[count++]= Keywords.RETURN;
- keywords[count++]= Keywords.SWITCH;
-// keywords[count++]= Keywords.SYNCHRONIZED;
- keywords[count++]= Keywords.THROW;
- keywords[count++]= Keywords.TRY;
- keywords[count++]= Keywords.WHILE;
- keywords[count++]= Keywords.VAR;
- keywords[count++]= Keywords.FUNCTION;
- keywords[count++]= Keywords.DELETE;
- keywords[count++]= Keywords.TYPEOF;
-
-// keywords[count++]= Keywords.FINAL;
-// keywords[count++]= Keywords.CLASS;
-
- if(previousKind == K_BLOCK_DELIMITER) {
- switch (previousInfo) {
- case IF :
- keywords[count++]= Keywords.ELSE;
- break;
- case CATCH :
- keywords[count++]= Keywords.CATCH;
- keywords[count++]= Keywords.FINALLY;
- break;
- }
- }
- if(isInsideLoop()) {
- keywords[count++]= Keywords.CONTINUE;
- }
- if(isInsideBreakable()) {
- keywords[count++]= Keywords.BREAK;
- }
- } else if(kind != K_BETWEEN_CASE_AND_COLON && kind != K_BETWEEN_DEFAULT_AND_COLON) {
- keywords[count++]= Keywords.TRUE;
- keywords[count++]= Keywords.FALSE;
- keywords[count++]= Keywords.NULL;
- keywords[count++]= Keywords.UNDEFINED;
- keywords[count++]= Keywords.FUNCTION;
-
- if(kind == K_SWITCH_LABEL) {
- if(topKnownElementInfo(COMPLETION_OR_ASSIST_PARSER) != DEFAULT) {
- keywords[count++]= Keywords.DEFAULT;
- }
- keywords[count++]= Keywords.BREAK;
- keywords[count++]= Keywords.CASE;
- keywords[count++]= Keywords.DO;
- keywords[count++]= Keywords.FOR;
- keywords[count++]= Keywords.IF;
- keywords[count++]= Keywords.RETURN;
- keywords[count++]= Keywords.SWITCH;
-// keywords[count++]= Keywords.SYNCHRONIZED;
- keywords[count++]= Keywords.THROW;
- keywords[count++]= Keywords.TRY;
- keywords[count++]= Keywords.WHILE;
- keywords[count++]= Keywords.VAR;
- keywords[count++]= Keywords.FUNCTION;
- keywords[count++]= Keywords.DELETE;
- keywords[count++]= Keywords.TYPEOF;
- if(isInsideLoop()) {
- keywords[count++]= Keywords.CONTINUE;
- } }
- }
- System.arraycopy(keywords, 0 , keywords = new char[count][], 0, count);
-
- return new CompletionOnSingleNameReference(assistName, position, keywords, canBeExplicitConstructorCall, isInsideAttributeValue());
- }
- }
-}
-public TypeReference createSingleAssistTypeReference(char[] assistName, long position) {
- switch (topKnownElementKind(COMPLETION_OR_ASSIST_PARSER)) {
- case K_NEXT_TYPEREF_IS_EXCEPTION :
- return new CompletionOnSingleTypeReference(assistName, position, CompletionOnSingleTypeReference.K_EXCEPTION) ;
- case K_NEXT_TYPEREF_IS_CLASS :
- return new CompletionOnSingleTypeReference(assistName, position, CompletionOnSingleTypeReference.K_CLASS);
- case K_NEXT_TYPEREF_IS_INTERFACE :
- return new CompletionOnSingleTypeReference(assistName, position, CompletionOnSingleTypeReference.K_INTERFACE);
- default :
- return new CompletionOnSingleTypeReference(assistName, position);
- }
-}
-public TypeReference createParameterizedSingleAssistTypeReference(TypeReference[] typeArguments, char[] assistName, long position) {
- return this.createSingleAssistTypeReference(assistName, position);
-}
-protected StringLiteral createStringLiteral(char[] token, int start, int end, int lineNumber) {
- if (start <= this.cursorLocation && this.cursorLocation <= end){
- char[] source = this.scanner.source;
-
- int contentStart = start;
- int contentEnd = end;
-
- // " could be as unicode \u0022
- int pos = contentStart;
- if(source[pos] == '\"') {
- contentStart = pos + 1;
- } else if(source[pos] == '\\' && source[pos+1] == 'u') {
- pos += 2;
- while (source[pos] == 'u') {
- pos++;
- }
- if(source[pos] == 0 && source[pos + 1] == 0 && source[pos + 2] == 2 && source[pos + 3] == 2) {
- contentStart = pos + 4;
- }
- }
-
- pos = contentEnd;
- if(source[pos] == '\"') {
- contentEnd = pos - 1;
- } else if(source.length > 5 && source[pos-4] == 'u') {
- if(source[pos - 3] == 0 && source[pos - 2] == 0 && source[pos - 1] == 2 && source[pos] == 2) {
- pos -= 5;
- while (pos > -1 && source[pos] == 'u') {
- pos--;
- }
- if(pos > -1 && source[pos] == '\\') {
- contentEnd = pos - 1;
- }
- }
- }
-
- if(contentEnd < start) {
- contentEnd = end;
- }
-
- if(this.cursorLocation != end || end == contentEnd) {
- CompletionOnStringLiteral stringLiteral = new CompletionOnStringLiteral(
- token,
- start,
- end,
- contentStart,
- contentEnd,
- lineNumber);
-
- this.assistNode = stringLiteral;
- this.restartRecovery = AssistParser.STOP_AT_CURSOR;
- this.lastCheckPoint = end;
-
- return stringLiteral;
- }
- }
- return super.createStringLiteral(token, start, end, lineNumber);
-}
-protected TypeReference copyDims(TypeReference typeRef, int dim) {
- if (this.assistNode == typeRef) {
- return typeRef;
- }
- TypeReference result = super.copyDims(typeRef, dim);
- if (this.assistNodeParent == typeRef) {
- this.assistNodeParent = result;
- }
- return result;
-}
-public CompilationUnitDeclaration dietParse(ICompilationUnit sourceUnit, CompilationResult compilationResult, int cursorLoc) {
-
- this.cursorLocation = cursorLoc;
- CompletionScanner completionScanner = (CompletionScanner)this.scanner;
- completionScanner.completionIdentifier = null;
- completionScanner.cursorLocation = cursorLoc;
- return this.dietParse(sourceUnit, compilationResult);
-}
-/*
- * Flush parser/scanner state regarding to code assist
- */
-public void flushAssistState() {
-
- super.flushAssistState();
- this.isOrphanCompletionNode = false;
- this.isAlreadyAttached = false;
- assistNodeParent = null;
- CompletionScanner completionScanner = (CompletionScanner)this.scanner;
- completionScanner.completedIdentifierStart = 0;
- completionScanner.completedIdentifierEnd = -1;
-}
-protected NameReference getUnspecifiedReference() {
- NameReference nameReference = super.getUnspecifiedReference();
- if (this.record) {
- recordReference(nameReference);
- }
- return nameReference;
-}
-protected NameReference getUnspecifiedReferenceOptimized() {
- if (this.identifierLengthStack[this.identifierLengthPtr] > 1) { // reducing a qualified name
- // potential receiver is being poped, so reset potential receiver
- this.invocationType = NO_RECEIVER;
- this.qualifier = -1;
- }
- NameReference nameReference = super.getUnspecifiedReferenceOptimized();
- if (this.record) {
- recordReference(nameReference);
- }
- return nameReference;
-}
-private boolean isAlreadyPotentialName(int identifierStart) {
- if (this.potentialVariableNamesPtr < 0) return false;
-
- return identifierStart <= this.potentialVariableNameEnds[this.potentialVariableNamesPtr];
-}
-protected int indexOfAssistIdentifier(boolean useGenericsStack) {
- if (this.record) return -1; // when names are recorded there is no assist identifier
- return super.indexOfAssistIdentifier(useGenericsStack);
-}
-public void initialize() {
- super.initialize();
- this.labelPtr = -1;
- this.initializeForBlockStatements();
-}
-public void initialize(boolean initializeNLS) {
- super.initialize(initializeNLS);
- this.labelPtr = -1;
- this.initializeForBlockStatements();
-}
-/*
- * Initializes the state of the parser that is about to go for BlockStatements.
- */
-private void initializeForBlockStatements() {
- this.previousToken = -1;
- this.previousIdentifierPtr = -1;
- this.bracketDepth = 0;
- this.invocationType = NO_RECEIVER;
- this.qualifier = -1;
- popUntilElement(K_SWITCH_LABEL);
- if(topKnownElementKind(COMPLETION_OR_ASSIST_PARSER) != K_SWITCH_LABEL) {
- this.popUntilElement(K_BLOCK_DELIMITER);
- }
-}
-public void initializeScanner(){
- this.scanner = new CompletionScanner(this.options.sourceLevel);
-}
-/**
- * Returns whether the completion is just after an array type
- * eg. String[].[cursor]
- */
-private boolean isAfterArrayType() {
- // TBD: The following relies on the fact that array dimensions are small: it says that if the
- // top of the intStack is less than 11, then it must be a dimension
- // (smallest position of array type in a compilation unit is 11 as in "class X{Y[]")
- if ((this.intPtr > -1) && (this.intStack[this.intPtr] < 11)) {
- return true;
- }
- return false;
-}
-private boolean isEmptyNameCompletion() {
- return
- this.assistNode != null &&
- this.assistNode instanceof CompletionOnSingleNameReference &&
- (((CompletionOnSingleNameReference)this.assistNode).token.length == 0);
-}
-protected boolean isInsideAnnotation() {
- int i = elementPtr;
- while(i > -1) {
- if(elementKindStack[i] == K_BETWEEN_ANNOTATION_NAME_AND_RPAREN)
- return true;
- i--;
- }
- return false;
-}
-protected boolean isIndirectlyInsideBlock(){
- int i = elementPtr;
- while(i > -1) {
- if(elementKindStack[i] == K_BLOCK_DELIMITER)
- return true;
- i--;
- }
- return false;
-}
-
-protected boolean isInsideBlock(){
- int i = elementPtr;
- while(i > -1) {
- switch (elementKindStack[i]) {
- case K_TYPE_DELIMITER : return false;
- case K_METHOD_DELIMITER : return false;
- case K_FIELD_INITIALIZER_DELIMITER : return false;
- case K_BLOCK_DELIMITER : return true;
- }
- i--;
- }
- return false;
-}
-protected boolean isInsideBreakable(){
- int i = elementPtr;
- while(i > -1) {
- switch (elementKindStack[i]) {
- case K_TYPE_DELIMITER : return false;
- case K_METHOD_DELIMITER : return false;
- case K_FIELD_INITIALIZER_DELIMITER : return false;
- case K_SWITCH_LABEL : return true;
- case K_BLOCK_DELIMITER :
- switch(elementInfoStack[i]) {
- case FOR :
- case DO :
- case WHILE :
- return true;
- }
- }
- i--;
- }
- return false;
-}
-protected boolean isInsideLoop(){
- int i = elementPtr;
- while(i > -1) {
- switch (elementKindStack[i]) {
- case K_TYPE_DELIMITER : return false;
- case K_METHOD_DELIMITER : return false;
- case K_FIELD_INITIALIZER_DELIMITER : return false;
- case K_BLOCK_DELIMITER :
- switch(elementInfoStack[i]) {
- case FOR :
- case DO :
- case WHILE :
- return true;
- }
- }
- i--;
- }
- return false;
-}
-protected boolean isInsideReturn(){
- int i = elementPtr;
- while(i > -1) {
- switch (elementKindStack[i]) {
- case K_TYPE_DELIMITER : return false;
- case K_METHOD_DELIMITER : return false;
- case K_FIELD_INITIALIZER_DELIMITER : return false;
- case K_BLOCK_DELIMITER : return false;
- case K_INSIDE_RETURN_STATEMENT : return true;
- }
- i--;
- }
- return false;
-}
-public CompilationUnitDeclaration parse(ICompilationUnit sourceUnit, CompilationResult compilationResult, int cursorLoc) {
-
- this.cursorLocation = cursorLoc;
- CompletionScanner completionScanner = (CompletionScanner)this.scanner;
- completionScanner.completionIdentifier = null;
- completionScanner.cursorLocation = cursorLoc;
- return this.parse(sourceUnit, compilationResult);
-}
-public void parseBlockStatements(
- ConstructorDeclaration cd,
- CompilationUnitDeclaration unit) {
- canBeExplicitConstructor = 1;
- super.parseBlockStatements(cd, unit);
-}
-public MethodDeclaration parseSomeStatements(int start, int end, int fakeBlocksCount, CompilationUnitDeclaration unit) {
- this.methodRecoveryActivated = true;
-
- initialize();
-
- // simulate goForMethodBody except that we don't want to balance brackets because they are not going to be balanced
- goForBlockStatementsopt();
-
- MethodDeclaration fakeMethod = new MethodDeclaration(unit.compilationResult());
- fakeMethod.selector = FAKE_METHOD_NAME;
- fakeMethod.bodyStart = start;
- fakeMethod.bodyEnd = end;
- fakeMethod.declarationSourceStart = start;
- fakeMethod.declarationSourceEnd = end;
- fakeMethod.sourceStart = start;
- fakeMethod.sourceEnd = start; //fake method must ignore the method header
-
- referenceContext = fakeMethod;
- compilationUnit = unit;
- this.diet = false;
- this.restartRecovery = true;
-
-
- scanner.resetTo(start, end);
- consumeNestedMethod();
- for (int i = 0; i < fakeBlocksCount; i++) {
- consumeOpenFakeBlock();
- }
- try {
- parse();
- } catch (AbortCompilation ex) {
- lastAct = ERROR_ACTION;
- } finally {
- nestedMethod[nestedType]--;
- }
- if (!this.hasError) {
- int length;
- if (astLengthPtr > -1 && (length = this.astLengthStack[this.astLengthPtr--]) != 0) {
- System.arraycopy(
- this.astStack,
- (this.astPtr -= length) + 1,
- fakeMethod.statements = new Statement[length],
- 0,
- length);
- }
- }
-
- return fakeMethod;
-}
-protected void popUntilCompletedAnnotationIfNecessary() {
- if(elementPtr < 0) return;
-
- int i = elementPtr;
- while(i > -1 &&
- (elementKindStack[i] != K_BETWEEN_ANNOTATION_NAME_AND_RPAREN ||
- (elementInfoStack[i] & ANNOTATION_NAME_COMPLETION) == 0)) {
- i--;
- }
-
- if(i >= 0) {
- previousKind = elementKindStack[i];
- previousInfo = elementInfoStack[i];
- elementPtr = i - 1;
- }
-}
-
-/*
- * 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;
-
- this.initializeForBlockStatements();
-}
-protected void pushOnLabelStack(char[] label){
- if (this.labelPtr < -1) return;
-
- int stackLength = this.labelStack.length;
- if (++this.labelPtr >= stackLength) {
- System.arraycopy(
- this.labelStack, 0,
- this.labelStack = new char[stackLength + LabelStackIncrement][], 0,
- stackLength);
- }
- this.labelStack[this.labelPtr] = label;
-}
-/**
- * Creates a completion on member access node and push it
- * on the expression stack.
- */
-private void pushCompletionOnMemberAccessOnExpressionStack(boolean isSuperAccess) {
- char[] source = identifierStack[identifierPtr];
- long pos = identifierPositionStack[identifierPtr--];
- CompletionOnMemberAccess fr = new CompletionOnMemberAccess(source, pos, isInsideAnnotation());
- this.assistNode = fr;
- this.lastCheckPoint = fr.sourceEnd + 1;
- identifierLengthPtr--;
- if (isSuperAccess) { //considerates the fieldReference beginning at the 'super' ....
- fr.sourceStart = intStack[intPtr--];
- fr.receiver = new SuperReference(fr.sourceStart, endPosition);
- pushOnExpressionStack(fr);
- } else { //optimize push/pop
- if ((fr.receiver = expressionStack[expressionPtr]).isThis()) { //fieldreference begins at the this
- fr.sourceStart = fr.receiver.sourceStart;
- }
- expressionStack[expressionPtr] = fr;
- }
-}
-public void recordCompletionOnReference(){
-
- if (currentElement instanceof RecoveredType){
- RecoveredType recoveredType = (RecoveredType)currentElement;
-
- /* filter out cases where scanner is still inside type header */
- if (!recoveredType.foundOpeningBrace) return;
-
- /* generate a pseudo field with a completion on type reference */
- currentElement.add(
- new CompletionOnFieldType(this.getTypeReference(0), false), 0);
- return;
- }
- if (!diet) return; // only record references attached to types
-
-}
-private void recordReference(NameReference nameReference) {
- if (!this.skipRecord &&
- this.recordFrom <= nameReference.sourceStart &&
- nameReference.sourceEnd <= this.recordTo &&
- !isAlreadyPotentialName(nameReference.sourceStart)) {
- char[] token;
- if (nameReference instanceof SingleNameReference) {
- token = ((SingleNameReference) nameReference).token;
- } else {
- token = ((QualifiedNameReference) nameReference).tokens[0];
- }
-
- // Most of the time a name which start with an uppercase is a type name.
- // As we don't want to resolve names to avoid to slow down performances then this name will be ignored
- if (Character.isUpperCase(token[0])) return;
-
- addPotentialName(token, nameReference.sourceStart, nameReference.sourceEnd);
- }
-}
-public void recoveryExitFromVariable() {
- if(currentElement != null && currentElement instanceof RecoveredLocalVariable) {
- RecoveredElement oldElement = currentElement;
- super.recoveryExitFromVariable();
- if(oldElement != currentElement) {
- popElement(K_LOCAL_INITIALIZER_DELIMITER);
- }
- } else {
- super.recoveryExitFromVariable();
- }
-}
-public void recoveryTokenCheck() {
- RecoveredElement oldElement = currentElement;
- switch (currentToken) {
- case TokenNameLBRACE :
- super.recoveryTokenCheck();
- break;
- case TokenNameRBRACE :
- super.recoveryTokenCheck();
- if(currentElement != oldElement && oldElement instanceof RecoveredBlock) {
- popElement(K_BLOCK_DELIMITER);
- }
- break;
- case TokenNamecase :
- super.recoveryTokenCheck();
- if(topKnownElementKind(COMPLETION_OR_ASSIST_PARSER) == K_BLOCK_DELIMITER
- && topKnownElementInfo(COMPLETION_OR_ASSIST_PARSER) == SWITCH) {
- pushOnElementStack(K_SWITCH_LABEL);
- }
- break;
- case TokenNamedefault :
- super.recoveryTokenCheck();
- if(topKnownElementKind(COMPLETION_OR_ASSIST_PARSER) == K_BLOCK_DELIMITER
- && topKnownElementInfo(COMPLETION_OR_ASSIST_PARSER) == SWITCH) {
- pushOnElementStack(K_SWITCH_LABEL, DEFAULT);
- } else if(topKnownElementKind(COMPLETION_OR_ASSIST_PARSER) == K_SWITCH_LABEL) {
- popElement(K_SWITCH_LABEL);
- pushOnElementStack(K_SWITCH_LABEL, DEFAULT);
- }
- break;
- default :
- super.recoveryTokenCheck();
- break;
- }
-}
-/*
- * Reset internal state after completion is over
- */
-
-public void reset() {
- super.reset();
- this.cursorLocation = 0;
-}
-/*
- * Reset internal state after completion is over
- */
-
-public void resetAfterCompletion() {
- this.cursorLocation = 0;
- this.flushAssistState();
-}
-/*
- * 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.assistNode != null) {
- /* if reached [eof] inside method body, but still inside nested type,
- or inside a field initializer, should continue in diet mode until
- the end of the method body or compilation unit */
- if ((scanner.eofPosition == cursorLocation+1)
- && (!(referenceContext instanceof CompilationUnitDeclaration)
- || isIndirectlyInsideFieldInitialization()
- || assistNodeParent instanceof FieldDeclaration && !(assistNodeParent instanceof Initializer))) {
-
- /* disabled since does not handle possible field/message refs, that is, Obj[ASSIST HERE]ect.registerNatives()
- // consume extra tokens which were part of the qualified reference
- // so that the replaced source comprises them as well
- if (this.assistNode instanceof NameReference){
- int oldEof = scanner.eofPosition;
- scanner.eofPosition = currentElement.topElement().sourceEnd()+1;
- scanner.currentPosition = this.cursorLocation+1;
- int token = -1;
- try {
- do {
- // first token might not have to be a dot
- if (token >= 0 || !this.completionBehindDot){
- if ((token = scanner.getNextToken()) != TokenNameDOT) break;
- }
- if ((token = scanner.getNextToken()) != TokenNameIdentifier) break;
- this.assistNode.sourceEnd = scanner.currentPosition - 1;
- } while (token != TokenNameEOF);
- } catch (InvalidInputException e){
- } finally {
- scanner.eofPosition = oldEof;
- }
- }
- */
- /* restart in diet mode for finding sibling constructs */
- if (currentElement instanceof RecoveredType
- || currentElement.enclosingType() != null){
-
- if(lastCheckPoint <= this.assistNode.sourceEnd) {
- lastCheckPoint = this.assistNode.sourceEnd+1;
- }
- int end = currentElement.topElement().sourceEnd();
- scanner.eofPosition = end < Integer.MAX_VALUE ? end + 1 : end;
- } else {
- this.resetStacks();
- return false;
- }
- }
- }
- return super.resumeAfterRecovery();
-}
-public void setAssistIdentifier(char[] assistIdent){
- ((CompletionScanner)scanner).completionIdentifier = assistIdent;
-}
-public String toString() {
- StringBuffer buffer = new StringBuffer();
- buffer.append("elementKindStack : int[] = {"); //$NON-NLS-1$
- for (int i = 0; i <= elementPtr; i++) {
- buffer.append(String.valueOf(elementKindStack[i])).append(',');
- }
- buffer.append("}\n"); //$NON-NLS-1$
- buffer.append("elementInfoStack : int[] = {"); //$NON-NLS-1$
- for (int i = 0; i <= elementPtr; i++) {
- buffer.append(String.valueOf(elementInfoStack[i])).append(',');
- }
- buffer.append("}\n"); //$NON-NLS-1$
- buffer.append(super.toString());
- return String.valueOf(buffer);
-}
-
-/*
- * Update recovery state based on current parser/scanner state
- */
-protected void updateRecoveryState() {
-
- /* expose parser state to recovery state */
- currentElement.updateFromParserState();
-
- /* may be able to retrieve completionNode as an orphan, and then attach it */
- this.completionIdentifierCheck();
- this.attachOrphanCompletionNode();
-
- // if an assist node has been found and a recovered element exists,
- // mark enclosing blocks as to be preserved
- if (this.assistNode != null && this.currentElement != null) {
- currentElement.preserveEnclosingBlocks();
- }
-
- /* check and update recovered state based on current token,
- this action is also performed when shifting token after recovery
- got activated once.
- */
- this.recoveryTokenCheck();
-
- this.recoveryExitFromVariable();
-}
-
-protected LocalDeclaration createLocalDeclaration(char[] assistName, int sourceStart, int sourceEnd) {
- if (this.indexOfAssistIdentifier() < 0) {
- return super.createLocalDeclaration(assistName, sourceStart, sourceEnd);
- } else {
- CompletionOnLocalName local = new CompletionOnLocalName(assistName, sourceStart, sourceEnd);
- this.assistNode = local;
- this.lastCheckPoint = sourceEnd + 1;
- return local;
- }
-}
-
-protected FieldDeclaration createFieldDeclaration(char[] assistName, int sourceStart, int sourceEnd) {
- if (this.indexOfAssistIdentifier() < 0 || (currentElement instanceof RecoveredUnit && ((RecoveredUnit)currentElement).statementCount == 0)) {
- return super.createFieldDeclaration(assistName, sourceStart, sourceEnd);
- } else {
- CompletionOnFieldName field = new CompletionOnFieldName(assistName, sourceStart, sourceEnd);
- this.assistNode = field;
- this.lastCheckPoint = sourceEnd + 1;
- return field;
- }
-}
-protected void classInstanceCreation(boolean isQualified, boolean isShort) {
- popElement(K_SELECTOR_QUALIFIER);
- popElement(K_SELECTOR_INVOCATION_TYPE);
- super.classInstanceCreation(isQualified, isShort);
-}
-public int getCursorLocation() {
- return this.cursorLocation;
-}
-
-
-protected MessageSend newMessageSend() {
- if (AssistParser.STOP_AT_CURSOR)
- return super.newMessageSend();
- // '(' ArgumentListopt ')'
- // the arguments are on the expression stack
-
- int numArgs=expressionLengthStack[expressionLengthPtr];
- Expression receiver = expressionStack[expressionPtr-numArgs];
-
-// char[] selector = identifierStack[identifierPtr];
-// if (selector != this.assistIdentifier()){
- if (!(receiver instanceof CompletionOnMemberAccess || receiver instanceof CompletionOnSingleNameReference))
- {
- return super.newMessageSend();
- }
- MessageSend messageSend = new CompletionOnMessageSend();
- int length;
- if ((length = expressionLengthStack[expressionLengthPtr--]) != 0) {
- expressionPtr -= length;
- System.arraycopy(
- expressionStack,
- expressionPtr + 1,
- messageSend.arguments = new Expression[length],
- 0,
- length);
- }
- assistNode = messageSend;
- if (!diet){
- this.restartRecovery = AssistParser.STOP_AT_CURSOR; // force to restart in recovery mode
- this.lastIgnoredToken = -1;
- }
-
- this.isOrphanCompletionNode = true;
- return messageSend;
-}
-
-protected JavadocParser createJavadocParser() {
- return new CompletionJavadocParser(this);
-}
-
- /**
- * @see org.eclipse.wst.jsdt.internal.codeassist.impl.AssistParser#createAssistTypeForAllocation(org.eclipse.wst.jsdt.internal.compiler.ast.AllocationExpression)
- */
- public void createAssistTypeForAllocation(AllocationExpression expression) {
- Expression member = expression.member;
-
- /* create a CompletionOnSingleTypeReference from the existing
- * member expression for the given allocation expression
- */
- if (member instanceof SingleNameReference) {
- SingleNameReference snr = (SingleNameReference) member;
- long position = (((long)snr.sourceStart)<<32)+snr.sourceEnd;
- expression.member= new CompletionOnSingleTypeReference(snr.token,position);
- ((CompletionOnSingleTypeReference)expression.member).isConstructorType = true;
- }
- else if(member instanceof CompletionOnMemberAccess) {
- CompletionOnMemberAccess memberAccess = (CompletionOnMemberAccess) member;
-
- //iterate over the receivers to build the token and find the start of the expression
- IExpression receiver = memberAccess.getReceiver();
- String token = new String(memberAccess.getToken());
- int start = memberAccess.sourceStart();
- while(receiver != null) {
- start = receiver.sourceStart();
- if(receiver instanceof IFieldReference) {
- IFieldReference ref = (IFieldReference)receiver;
- token = new String(ref.getToken()) + "." + token;
- receiver = ref.getReceiver();
- } else if(receiver instanceof ISingleNameReference) {
- ISingleNameReference ref = (ISingleNameReference)receiver;
- token = new String(ref.getToken()) + "." + token;
- receiver = null;
- }
- }
-
- //create and set the CompletionOnSingleTypeReference
- long position = (((long)start)<<32)+memberAccess.sourceEnd;
- expression.member = new CompletionOnSingleTypeReference(token.toCharArray(), position);
- ((CompletionOnSingleTypeReference)expression.member).isConstructorType = true;
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionScanner.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionScanner.java
deleted file mode 100644
index 20033cf1..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionScanner.java
+++ /dev/null
@@ -1,784 +0,0 @@
-/*******************************************************************************
- * 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.codeassist.complete;
-
-/*
- * Scanner aware of a cursor location so as to discard trailing portions of identifiers
- * containing the cursor location.
- *
- * Cursor location denotes the position of the last character behind which completion
- * got requested:
- * -1 means completion at the very beginning of the source
- * 0 means completion behind the first character
- * n means completion behind the n-th character
- */
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.internal.codeassist.impl.AssistParser;
-import org.eclipse.wst.jsdt.internal.compiler.parser.Parser;
-import org.eclipse.wst.jsdt.internal.compiler.parser.Scanner;
-import org.eclipse.wst.jsdt.internal.compiler.parser.ScannerHelper;
-
-public class CompletionScanner extends Scanner {
-
-
- public char[] completionIdentifier;
- public int cursorLocation;
- public int endOfEmptyToken = -1;
-
- /* Source positions of the completedIdentifier
- * if inside actual identifier, end goes to the actual identifier
- * end, in other words, beyond cursor location
- */
- public int completedIdentifierStart = 0;
- public int completedIdentifierEnd = -1;
- public int unicodeCharSize;
-
-
- public static final char[] EmptyCompletionIdentifier = {};
-
-public CompletionScanner(long sourceLevel) {
- super(
- false /*comment*/,
- false /*whitespace*/,
- false /*nls*/,
- sourceLevel,
- null /*taskTags*/,
- null/*taskPriorities*/,
- true/*taskCaseSensitive*/);
-}
-
-/*
- * Truncate the current identifier if it is containing the cursor location. Since completion is performed
- * on an identifier prefix.
- *
- */
-public char[] getCurrentIdentifierSource() {
-
- if (this.completionIdentifier == null){
- if (this.cursorLocation < this.startPosition && this.currentPosition == this.startPosition){ // fake empty identifier got issued
- // remember actual identifier positions
- this.completedIdentifierStart = this.startPosition;
- this.completedIdentifierEnd = this.completedIdentifierStart - 1;
- return this.completionIdentifier = EmptyCompletionIdentifier;
- }
- if (this.cursorLocation+1 >= this.startPosition && this.cursorLocation < this.currentPosition){
- // remember actual identifier positions
- this.completedIdentifierStart = this.startPosition;
- this.completedIdentifierEnd = this.currentPosition - 1;
- if (this.withoutUnicodePtr != 0){ // check unicode scenario
- int length = this.cursorLocation + 1 - this.startPosition - this.unicodeCharSize;
- System.arraycopy(this.withoutUnicodeBuffer, 1, this.completionIdentifier = new char[length], 0, length);
- } else {
- // no char[] sharing around completionIdentifier, we want it to be unique so as to use identity checks
- int length = this.cursorLocation + 1 - this.startPosition;
- System.arraycopy(this.source, this.startPosition, (this.completionIdentifier = new char[length]), 0, length);
- }
- return this.completionIdentifier;
- }
- }
- return super.getCurrentIdentifierSource();
-}
-
-public char[] getCurrentTokenSourceString() {
- if (this.completionIdentifier == null){
- if (this.cursorLocation+1 >= this.startPosition && this.cursorLocation < this.currentPosition){
- // remember actual identifier positions
- this.completedIdentifierStart = this.startPosition;
- this.completedIdentifierEnd = this.currentPosition - 1;
- if (this.withoutUnicodePtr != 0){ // check unicode scenario
- int length = this.cursorLocation - this.startPosition - this.unicodeCharSize;
- System.arraycopy(this.withoutUnicodeBuffer, 2, this.completionIdentifier = new char[length], 0, length);
- } else {
- // no char[] sharing around completionIdentifier, we want it to be unique so as to use identity checks
- int length = this.cursorLocation - this.startPosition;
- System.arraycopy(this.source, this.startPosition + 1, (this.completionIdentifier = new char[length]), 0, length);
- }
- return this.completionIdentifier;
- }
- }
- return super.getCurrentTokenSourceString();
-}
-public int getNextToken() throws InvalidInputException {
- if ( pushedBack ) {
- pushedBack = false;
- return currentToken;
- }
- int previousToken = this.currentToken;
- this.wasAcr = false;
- this.unicodeCharSize = 0;
- if (this.diet) {
- jumpOverMethodBody();
- this.diet = false;
- return (currentToken=this.currentPosition > this.eofPosition ? TokenNameEOF : TokenNameRBRACE);
- }
- int whiteStart = 0;
- try {
- while (true) { //loop for jumping over comments
- this.withoutUnicodePtr = 0;
- //start with a new token (even comment written with unicode )
-
- // ---------Consume white space and handles start position---------
- whiteStart = this.currentPosition;
- boolean isWhiteSpace, hasWhiteSpaces = false;
- int offset = 0;
- do {
- this.startPosition = this.currentPosition;
- boolean checkIfUnicode = false;
- try {
- checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u');
- } catch(IndexOutOfBoundsException e) {
- if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) {
- // reposition scanner in case we are interested by spaces as tokens
- this.currentPosition--;
- this.startPosition = whiteStart;
- return (currentToken=TokenNameWHITESPACE);
- }
- if (this.currentPosition > this.eofPosition) {
- /* might be completing at eof (e.g. behind a dot) */
- if (this.completionIdentifier == null &&
- this.startPosition == this.cursorLocation + 1){
- this.currentPosition = this.startPosition; // for being detected as empty free identifier
- return TokenNameIdentifier;
- }
- return (currentToken=TokenNameEOF);
- }
- }
- if (checkIfUnicode) {
- isWhiteSpace = jumpOverUnicodeWhiteSpace();
- offset = 6;
- } else {
- offset = 1;
- if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) {
- //checkNonExternalizedString();
- if (this.recordLineSeparator) {
- pushLineSeparator();
- }
- }
- isWhiteSpace =
- (this.currentCharacter == ' ') || CharOperation.isWhitespace(this.currentCharacter);
- }
- if (isWhiteSpace) {
- hasWhiteSpaces = true;
- }
- /* completion requesting strictly inside blanks */
- if ((whiteStart != this.currentPosition)
- //&& (previousToken == TokenNameDOT)
- && (/* !AssistParser.STOP_AT_CURSOR || */ this.completionIdentifier == null)
- && (whiteStart <= this.cursorLocation+1)
- && (this.cursorLocation < this.startPosition)
- && !ScannerHelper.isJavaIdentifierStart(this.currentCharacter)){
-// if (AssistParser.STOP_AT_CURSOR)
- this.currentPosition = this.startPosition; // for next token read
- return (currentToken=TokenNameIdentifier);
- }
- } while (isWhiteSpace);
- if (this.tokenizeWhiteSpace && hasWhiteSpaces) {
- // reposition scanner in case we are interested by spaces as tokens
- this.currentPosition-=offset;
- this.startPosition = whiteStart;
- return (currentToken=TokenNameWHITESPACE);
- }
- //little trick to get out in the middle of a source computation
- if (this.currentPosition > this.eofPosition ||(!AssistParser.STOP_AT_CURSOR && this.currentPosition > this.cursorLocation)){
- /* might be completing at eof (e.g. behind a dot) */
- if (this.completionIdentifier == null &&
- this.startPosition == this.cursorLocation + 1){
- // compute end of empty identifier.
- // if the empty identifier is at the start of a next token the end of
- // empty identifier is the end of the next token (eg. "<empty token>next").
- int temp = this.eofPosition;
- this.eofPosition = this.source.length;
- while(getNextCharAsJavaIdentifierPart()){/*empty*/}
- this.eofPosition = temp;
- this.endOfEmptyToken = this.currentPosition - 1;
-// this.currentPosition = this.startPosition; // for being detected as empty free identifier
- return (currentToken=TokenNameIdentifier);
- }
- if (AssistParser.STOP_AT_CURSOR)
- return (currentToken=TokenNameEOF);
- }
-
- // ---------Identify the next token-------------
-
- switch (this.currentCharacter) {
- case '(' :
- return (currentToken=TokenNameLPAREN);
- case ')' :
- return (currentToken=TokenNameRPAREN);
- case '{' :
- return (currentToken=TokenNameLBRACE);
- case '}' :
- return (currentToken=TokenNameRBRACE);
- case '[' :
- return (currentToken=TokenNameLBRACKET);
- case ']' :
- return (currentToken=TokenNameRBRACKET);
- case ';' :
- return (currentToken=TokenNameSEMICOLON);
- case ',' :
- return (currentToken=TokenNameCOMMA);
- case '.' :
- if (this.startPosition <= this.cursorLocation
- && this.cursorLocation < this.currentPosition){
- return (currentToken=TokenNameDOT); // completion inside .<|>12
- }
- if (getNextCharAsDigit()) {
- return (currentToken=scanNumber(true));
- }
- int temp = this.currentPosition;
- if (getNextChar('.')) {
-// if (getNextChar('.')) {
-// return (currentToken=TokenNameELLIPSIS);
-// } else {
- this.currentPosition = temp;
- return (currentToken=TokenNameDOT);
-// }
- } else {
- this.currentPosition = temp;
- return (currentToken=TokenNameDOT);
- }
- case '+' :
- {
- int test;
- if ((test = getNextChar('+', '=')) == 0)
- return (currentToken=TokenNamePLUS_PLUS);
- if (test > 0)
- return (currentToken=TokenNamePLUS_EQUAL);
- return (currentToken=TokenNamePLUS);
- }
- case '-' :
- {
- int test;
- if ((test = getNextChar('-', '=')) == 0)
- return (currentToken=TokenNameMINUS_MINUS);
- if (test > 0)
- return (currentToken=TokenNameMINUS_EQUAL);
- return (currentToken=TokenNameMINUS);
- }
- case '~' :
- return (currentToken=TokenNameTWIDDLE);
- case '!' :
- if (getNextChar('='))
- {
- if (getNextChar('='))
- {
- currentToken=TokenNameNOT_EQUAL_EQUAL;
- return currentToken;
- }
- currentToken=TokenNameNOT_EQUAL;
- return currentToken;
- }
- currentToken=TokenNameNOT;
- return currentToken;
- case '*' :
- if (getNextChar('='))
- return (currentToken=TokenNameMULTIPLY_EQUAL);
- return (currentToken=TokenNameMULTIPLY);
- case '%' :
- if (getNextChar('='))
- return (currentToken=TokenNameREMAINDER_EQUAL);
- return (currentToken=TokenNameREMAINDER);
- case '<' :
- {
- int test;
- if ((test = getNextChar('=', '<')) == 0)
- return (currentToken=TokenNameLESS_EQUAL);
- if (test > 0) {
- if (getNextChar('='))
- return (currentToken=TokenNameLEFT_SHIFT_EQUAL);
- return (currentToken=TokenNameLEFT_SHIFT);
- }
- return (currentToken=TokenNameLESS);
- }
- case '>' :
- {
- int test;
- if (this.returnOnlyGreater) {
- return (currentToken=TokenNameGREATER);
- }
- if ((test = getNextChar('=', '>')) == 0)
- return (currentToken=TokenNameGREATER_EQUAL);
- if (test > 0) {
- if ((test = getNextChar('=', '>')) == 0)
- return (currentToken=TokenNameRIGHT_SHIFT_EQUAL);
- if (test > 0) {
- if (getNextChar('='))
- return (currentToken=TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL);
- return (currentToken=TokenNameUNSIGNED_RIGHT_SHIFT);
- }
- return (currentToken=TokenNameRIGHT_SHIFT);
- }
- return (currentToken=TokenNameGREATER);
- }
- case '=' :
- if (getNextChar('='))
- {
- if (getNextChar('='))
- {
- currentToken=TokenNameEQUAL_EQUAL_EQUAL;
- return currentToken;
- }
- currentToken=TokenNameEQUAL_EQUAL;
- return currentToken;
- }
- currentToken=TokenNameEQUAL;
- return currentToken;
- case '&' :
- {
- int test;
- if ((test = getNextChar('&', '=')) == 0)
- return (currentToken=TokenNameAND_AND);
- if (test > 0)
- return (currentToken=TokenNameAND_EQUAL);
- return (currentToken=TokenNameAND);
- }
- case '|' :
- {
- int test;
- if ((test = getNextChar('|', '=')) == 0)
- return (currentToken=TokenNameOR_OR);
- if (test > 0)
- return (currentToken=TokenNameOR_EQUAL);
- return (currentToken=TokenNameOR);
- }
- case '^' :
- if (getNextChar('='))
- return (currentToken=TokenNameXOR_EQUAL);
- return (currentToken=TokenNameXOR);
- case '?' :
- return (currentToken=TokenNameQUESTION);
- case ':' :
- return (currentToken=TokenNameCOLON);
-/* case '\'' :
- {
- int test;
- if ((test = getNextChar('\n', '\r')) == 0) {
- throw new InvalidInputException(INVALID_CHARACTER_CONSTANT);
- }
- if (test > 0) {
- // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed
- for (int lookAhead = 0; lookAhead < 3; lookAhead++) {
- if (this.currentPosition + lookAhead == this.eofPosition)
- break;
- if (this.source[this.currentPosition + lookAhead] == '\n')
- break;
- if (this.source[this.currentPosition + lookAhead] == '\'') {
- this.currentPosition += lookAhead + 1;
- break;
- }
- }
- throw new InvalidInputException(INVALID_CHARACTER_CONSTANT);
- }
- }
- if (getNextChar('\'')) {
- // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed
- for (int lookAhead = 0; lookAhead < 3; lookAhead++) {
- if (this.currentPosition + lookAhead == this.eofPosition)
- break;
- if (this.source[this.currentPosition + lookAhead] == '\n')
- break;
- if (this.source[this.currentPosition + lookAhead] == '\'') {
- this.currentPosition += lookAhead + 1;
- break;
- }
- }
- throw new InvalidInputException(INVALID_CHARACTER_CONSTANT);
- }
- if (getNextChar('\\')) {
- if (this.unicodeAsBackSlash) {
- // consume next character
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- } else {
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
- } else {
- this.currentCharacter = this.source[this.currentPosition++];
- }
- scanEscapeCharacter();
- } else { // consume next character
- this.unicodeAsBackSlash = false;
- boolean checkIfUnicode = false;
- try {
- checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u');
- } catch(IndexOutOfBoundsException e) {
- this.currentPosition--;
- throw new InvalidInputException(INVALID_CHARACTER_CONSTANT);
- }
- if (checkIfUnicode) {
- getNextUnicodeChar();
- } else {
- if (this.withoutUnicodePtr != 0) {
- this.unicodeStore();
- }
- }
- }
- if (getNextChar('\''))
- return (currentToken=TokenNameCharacterLiteral);
- // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed
- for (int lookAhead = 0; lookAhead < 20; lookAhead++) {
- if (this.currentPosition + lookAhead == this.eofPosition)
- break;
- if (this.source[this.currentPosition + lookAhead] == '\n')
- break;
- if (this.source[this.currentPosition + lookAhead] == '\'') {
- this.currentPosition += lookAhead + 1;
- break;
- }
- }
- throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); */
- case '\'' :
- case '"' :
- char character = this.currentCharacter;
- try {
- // consume next character
- this.unicodeAsBackSlash = false;
- boolean isUnicode = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- isUnicode = true;
- } else {
- if (this.withoutUnicodePtr != 0) {
- this.unicodeStore();
- }
- }
-
- while ((this.currentCharacter != character) || ((this.currentCharacter == character) && (isUnicode == true))) {
- if ((this.currentCharacter == '\n' && !isUnicode) || (this.currentCharacter == '\r' && !isUnicode)) {
- this.currentPosition--; // set current position on new line character
- if(this.startPosition <= this.cursorLocation
- && this.cursorLocation <= this.currentPosition-1) {
- // complete inside a string literal
- return (currentToken=TokenNameStringLiteral);
- }
- throw new InvalidInputException(INVALID_CHAR_IN_STRING);
- }
- if (this.currentCharacter == '\\') {
- if (this.unicodeAsBackSlash) {
- this.withoutUnicodePtr--;
- // consume next character
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- isUnicode = true;
- this.withoutUnicodePtr--;
- } else {
- isUnicode = false;
- }
- } else {
- if (this.withoutUnicodePtr == 0) {
- unicodeInitializeBuffer(this.currentPosition - this.startPosition);
- }
- this.withoutUnicodePtr --;
- this.currentCharacter = this.source[this.currentPosition++];
- }
- // we need to compute the escape character in a separate buffer
- if (scanEscapeCharacter() && this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
- // consume next character
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- isUnicode = true;
- } else {
- isUnicode = false;
- if (this.withoutUnicodePtr != 0) {
- this.unicodeStore();
- }
- }
-
- }
- } catch (IndexOutOfBoundsException e) {
- this.currentPosition--;
- if(this.startPosition <= this.cursorLocation
- && this.cursorLocation < this.currentPosition) {
- // complete inside a string literal
- return (currentToken=TokenNameStringLiteral);
- }
- throw new InvalidInputException(UNTERMINATED_STRING);
- } catch (InvalidInputException e) {
- if (e.getMessage().equals(INVALID_ESCAPE)) {
- // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed
- for (int lookAhead = 0; lookAhead < 50; lookAhead++) {
- if (this.currentPosition + lookAhead == this.eofPosition)
- break;
- if (this.source[this.currentPosition + lookAhead] == '\n')
- break;
- if (this.source[this.currentPosition + lookAhead] == character) {
- this.currentPosition += lookAhead + 1;
- break;
- }
- }
-
- }
- throw e; // rethrow
- }
- if (character == '\'') {
- return (currentToken=TokenNameCharacterLiteral);
- } else {
- return (currentToken=TokenNameStringLiteral);
- }
-
-
- case '/' :
- {
- int test;
- if ((test = getNextChar('/', '*')) == 0) { //line comment
- this.lastCommentLinePosition = this.currentPosition;
- try { //get the next char
- this.currentCharacter = this.source[this.currentPosition++];
- while (this.currentCharacter != '\r' && this.currentCharacter != '\n') {
- this.currentCharacter = this.source[this.currentPosition++];
- }
- /*
- * We need to completely consume the line break
- */
- boolean isUnicode = false;
- if (this.currentCharacter == '\r'
- && this.eofPosition > this.currentPosition) {
- if (this.source[this.currentPosition] == '\n') {
- this.currentPosition++;
- this.currentCharacter = '\n';
- } else if ((this.source[this.currentPosition] == '\\')
- && (this.source[this.currentPosition + 1] == 'u')) {
- isUnicode = true;
- char unicodeChar;
- int index = this.currentPosition + 1;
- index++;
- while (this.source[index] == 'u') {
- index++;
- }
- //-------------unicode traitement ------------
- int c1 = 0, c2 = 0, c3 = 0, c4 = 0;
- if ((c1 = ScannerHelper.getNumericValue(this.source[index++])) > 15
- || c1 < 0
- || (c2 = ScannerHelper.getNumericValue(this.source[index++])) > 15
- || c2 < 0
- || (c3 = ScannerHelper.getNumericValue(this.source[index++])) > 15
- || c3 < 0
- || (c4 = ScannerHelper.getNumericValue(this.source[index++])) > 15
- || c4 < 0) {
- this.currentPosition = index;
- throw new InvalidInputException(INVALID_UNICODE_ESCAPE);
- } else {
- unicodeChar = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4);
- }
- if (unicodeChar == '\n') {
- this.currentPosition = index;
- this.currentCharacter = '\n';
- }
- }
- }
- recordComment(TokenNameCOMMENT_LINE);
- if (this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition-1){
- throw new InvalidCursorLocation(InvalidCursorLocation.NO_COMPLETION_INSIDE_COMMENT);
- }
- if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition);
- if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) {
- //checkNonExternalizedString();
- if (this.recordLineSeparator) {
- if (isUnicode) {
- pushUnicodeLineSeparator();
- } else {
- pushLineSeparator();
- }
- }
- }
- if (this.tokenizeComments) {
- return (currentToken=TokenNameCOMMENT_LINE);
- }
- } catch (IndexOutOfBoundsException e) {
- this.currentPosition--;
- recordComment(TokenNameCOMMENT_LINE);
- if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition);
- if (this.tokenizeComments) {
- return (currentToken=TokenNameCOMMENT_LINE);
- } else {
- this.currentPosition++;
- }
- }
- break;
- }
- if (test > 0) { //traditional and javadoc comment
- try { //get the next char
- boolean isJavadoc = false, star = false;
- boolean isUnicode = false;
- // consume next character
- this.currentCharacter = this.source[this.currentPosition++];
-
- if (this.currentCharacter == '*') {
- isJavadoc = true;
- star = true;
- }
- if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) {
- //checkNonExternalizedString();
- if (this.recordLineSeparator) {
- if (!isUnicode) {
- pushLineSeparator();
- }
- }
- }
- isUnicode = false;
- this.currentCharacter = this.source[this.currentPosition++];
- // empty comment is not a javadoc /**/
- if (this.currentCharacter == '/') {
- isJavadoc = false;
- }
- //loop until end of comment */
- while ((this.currentCharacter != '/') || (!star)) {
- if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) {
- //checkNonExternalizedString();
- if (this.recordLineSeparator) {
- if (!isUnicode) {
- pushLineSeparator();
- }
- }
- }
- star = this.currentCharacter == '*';
- //get next char
- this.currentCharacter = this.source[this.currentPosition++];
- }
- int token = isJavadoc ? TokenNameCOMMENT_JAVADOC : TokenNameCOMMENT_BLOCK;
- recordComment(token);
- if (!isJavadoc && this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition-1){
- throw new InvalidCursorLocation(InvalidCursorLocation.NO_COMPLETION_INSIDE_COMMENT);
- }
- if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition);
- if (this.tokenizeComments) {
- /*
- if (isJavadoc)
- return TokenNameCOMMENT_JAVADOC;
- return TokenNameCOMMENT_BLOCK;
- */
- return (currentToken=token);
- }
- } catch (IndexOutOfBoundsException e) {
- this.currentPosition--;
- throw new InvalidInputException(UNTERMINATED_COMMENT);
- }
- break;
- }
- if (checkIfDivide(previousToken)){
- if (getNextChar('='))
- {
- currentToken=TokenNameDIVIDE_EQUAL;
- return currentToken;
- }
- currentToken=TokenNameDIVIDE;
- return currentToken;
- }
-
- // check if regular expression
- if (checkIfRegExp()) {
- currentToken = TokenNameRegExLiteral;
- return currentToken;
- }
- }
- case '\u001a' :
- if (atEnd())
- return (currentToken=TokenNameEOF);
- //the atEnd may not be <this.currentPosition == this.eofPosition> if source is only some part of a real (external) stream
- throw new InvalidInputException("Ctrl-Z"); //$NON-NLS-1$
-
- default :
- if (ScannerHelper.isJavaIdentifierStart(this.currentCharacter))
- return (currentToken=scanIdentifierOrKeyword());
- if (ScannerHelper.isDigit(this.currentCharacter)) {
- return (currentToken=scanNumber(false));
- }
- return (currentToken=TokenNameERROR);
- }
- }
- } //-----------------end switch while try--------------------
- catch (IndexOutOfBoundsException e) {
- if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) {
- // reposition scanner in case we are interested by spaces as tokens
- this.currentPosition--;
- this.startPosition = whiteStart;
- return (currentToken=TokenNameWHITESPACE);
- }
- }
- /* might be completing at very end of file (e.g. behind a dot) */
- if (this.completionIdentifier == null &&
- this.startPosition == this.cursorLocation + 1){
- this.currentPosition = this.startPosition; // for being detected as empty free identifier
- return (currentToken=TokenNameIdentifier);
- }
- return (currentToken=TokenNameEOF);
-}
-public final void getNextUnicodeChar() throws InvalidInputException {
- int temp = this.currentPosition; // the \ is already read
- super.getNextUnicodeChar();
- if(this.cursorLocation > temp) {
- this.unicodeCharSize += (this.currentPosition - temp);
- }
- if (temp < this.cursorLocation && this.cursorLocation < this.currentPosition-1){
- throw new InvalidCursorLocation(InvalidCursorLocation.NO_COMPLETION_INSIDE_UNICODE);
- }
-}
-public final void jumpOverBlock() {
- this.jumpOverMethodBody();
-}
-
-
-///*
-// * In case we actually read a keyword, but the cursor is located inside,
-// * we pretend we read an identifier.
-// */
-public int scanIdentifierOrKeyword() {
-
- int id = super.scanIdentifierOrKeyword();
-
- if (this.startPosition <= this.cursorLocation+1
- && this.cursorLocation < this.currentPosition){
-
- // extends the end of the completion token even if the end is after eofPosition
- if (this.cursorLocation+1 == this.eofPosition) {
- int temp = this.eofPosition;
- this.eofPosition = this.source.length;
- while(getNextCharAsJavaIdentifierPart()){/*empty*/}
- this.eofPosition = temp;
- }
- // convert completed keyword into an identifier
- return TokenNameIdentifier;
- }
- return id;
-}
-
-
-public int scanNumber(boolean dotPrefix) throws InvalidInputException {
-
- int token = super.scanNumber(dotPrefix);
-
- // consider completion just before a number to be ok, will insert before it
- if (this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition){
- throw new InvalidCursorLocation(InvalidCursorLocation.NO_COMPLETION_INSIDE_NUMBER);
- }
- return token;
-}
-
-public void setSource(char[] sourceString) {
- super.setSource(sourceString);
- if (!Parser.DO_DIET_PARSE && AssistParser.STOP_AT_CURSOR)
- this.eofPosition=this.cursorLocation+1;
-}
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/InvalidCursorLocation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/InvalidCursorLocation.java
deleted file mode 100644
index cbc901d7..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/InvalidCursorLocation.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.complete;
-
-/**
- * Thrown whenever cursor location is not inside a consistent token
- * for example: inside a string, number, unicode, comments etc...
- */
-public class InvalidCursorLocation extends RuntimeException {
-
- public String irritant;
-
- /* Possible irritants */
- public static final String NO_COMPLETION_INSIDE_UNICODE = "No Completion Inside Unicode"; //$NON-NLS-1$
- public static final String NO_COMPLETION_INSIDE_COMMENT = "No Completion Inside Comment"; //$NON-NLS-1$
- public static final String NO_COMPLETION_INSIDE_STRING = "No Completion Inside String"; //$NON-NLS-1$
- public static final String NO_COMPLETION_INSIDE_NUMBER = "No Completion Inside Number"; //$NON-NLS-1$
-
- private static final long serialVersionUID = -3443160725735779590L; // backward compatible
-
-public InvalidCursorLocation(String irritant){
- this.irritant = irritant;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/impl/AssistOptions.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/impl/AssistOptions.java
deleted file mode 100644
index 4009b59e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/impl/AssistOptions.java
+++ /dev/null
@@ -1,237 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.impl;
-
-import java.util.Map;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-
-public class AssistOptions {
- /**
- * Option IDs
- */
- public static final String OPTION_PerformVisibilityCheck =
- "org.eclipse.wst.jsdt.core.codeComplete.visibilityCheck"; //$NON-NLS-1$
- public static final String OPTION_PerformDeprecationCheck =
- "org.eclipse.wst.jsdt.core.codeComplete.deprecationCheck"; //$NON-NLS-1$
- public static final String OPTION_ForceImplicitQualification =
- "org.eclipse.wst.jsdt.core.codeComplete.forceImplicitQualification"; //$NON-NLS-1$
- public static final String OPTION_FieldPrefixes =
- "org.eclipse.wst.jsdt.core.codeComplete.fieldPrefixes"; //$NON-NLS-1$
- public static final String OPTION_StaticFieldPrefixes =
- "org.eclipse.wst.jsdt.core.codeComplete.staticFieldPrefixes"; //$NON-NLS-1$
- public static final String OPTION_LocalPrefixes =
- "org.eclipse.wst.jsdt.core.codeComplete.localPrefixes"; //$NON-NLS-1$
- public static final String OPTION_ArgumentPrefixes =
- "org.eclipse.wst.jsdt.core.codeComplete.argumentPrefixes"; //$NON-NLS-1$
- public static final String OPTION_FieldSuffixes =
- "org.eclipse.wst.jsdt.core.codeComplete.fieldSuffixes"; //$NON-NLS-1$
- public static final String OPTION_StaticFieldSuffixes =
- "org.eclipse.wst.jsdt.core.codeComplete.staticFieldSuffixes"; //$NON-NLS-1$
- public static final String OPTION_LocalSuffixes =
- "org.eclipse.wst.jsdt.core.codeComplete.localSuffixes"; //$NON-NLS-1$
- public static final String OPTION_ArgumentSuffixes =
- "org.eclipse.wst.jsdt.core.codeComplete.argumentSuffixes"; //$NON-NLS-1$
- public static final String OPTION_PerformForbiddenReferenceCheck =
- "org.eclipse.wst.jsdt.core.codeComplete.forbiddenReferenceCheck"; //$NON-NLS-1$
- public static final String OPTION_PerformDiscouragedReferenceCheck =
- "org.eclipse.wst.jsdt.core.codeComplete.discouragedReferenceCheck"; //$NON-NLS-1$
- public static final String OPTION_CamelCaseMatch =
- "org.eclipse.wst.jsdt.core.codeComplete.camelCaseMatch"; //$NON-NLS-1$
- public static final String OPTION_SuggestStaticImports =
- "org.eclipse.wst.jsdt.core.codeComplete.suggestStaticImports"; //$NON-NLS-1$
-
- public static final String ENABLED = "enabled"; //$NON-NLS-1$
- public static final String DISABLED = "disabled"; //$NON-NLS-1$
-
- public boolean checkVisibility = false;
- public boolean checkDeprecation = false;
- public boolean checkForbiddenReference = false;
- public boolean checkDiscouragedReference = false;
- public boolean forceImplicitQualification = false;
- public boolean camelCaseMatch = true;
- public boolean suggestStaticImport = true;
- public char[][] fieldPrefixes = null;
- public char[][] staticFieldPrefixes = null;
- public char[][] localPrefixes = null;
- public char[][] argumentPrefixes = null;
- public char[][] fieldSuffixes = null;
- public char[][] staticFieldSuffixes = null;
- public char[][] localSuffixes = null;
- public char[][] argumentSuffixes = null;
-
- /**
- * Initializing the assist options with default settings
- */
- public AssistOptions() {
- // Initializing the assist options with default settings
- }
-
- /**
- * Initializing the assist options with external settings
- */
- public AssistOptions(Map settings) {
- if (settings == null)
- return;
-
- set(settings);
- }
- public void set(Map optionsMap) {
-
- Object optionValue;
- if ((optionValue = optionsMap.get(OPTION_PerformVisibilityCheck)) != null) {
- if (ENABLED.equals(optionValue)) {
- this.checkVisibility = true;
- } else if (DISABLED.equals(optionValue)) {
- this.checkVisibility = false;
- }
- }
- if ((optionValue = optionsMap.get(OPTION_ForceImplicitQualification)) != null) {
- if (ENABLED.equals(optionValue)) {
- this.forceImplicitQualification = true;
- } else if (DISABLED.equals(optionValue)) {
- this.forceImplicitQualification = false;
- }
- }
- if ((optionValue = optionsMap.get(OPTION_FieldPrefixes)) != null) {
- if (optionValue instanceof String) {
- String stringValue = (String) optionValue;
- if (stringValue.length() > 0){
- this.fieldPrefixes = this.splitAndTrimOn(',', stringValue.toCharArray());
- } else {
- this.fieldPrefixes = null;
- }
- }
- }
- if ((optionValue = optionsMap.get(OPTION_StaticFieldPrefixes)) != null) {
- if (optionValue instanceof String) {
- String stringValue = (String) optionValue;
- if (stringValue.length() > 0){
- this.staticFieldPrefixes = this.splitAndTrimOn(',', stringValue.toCharArray());
- } else {
- this.staticFieldPrefixes = null;
- }
- }
- }
- if ((optionValue = optionsMap.get(OPTION_LocalPrefixes)) != null) {
- if (optionValue instanceof String) {
- String stringValue = (String) optionValue;
- if (stringValue.length() > 0){
- this.localPrefixes = this.splitAndTrimOn(',', stringValue.toCharArray());
- } else {
- this.localPrefixes = null;
- }
- }
- }
- if ((optionValue = optionsMap.get(OPTION_ArgumentPrefixes)) != null) {
- if (optionValue instanceof String) {
- String stringValue = (String) optionValue;
- if (stringValue.length() > 0){
- this.argumentPrefixes = this.splitAndTrimOn(',', stringValue.toCharArray());
- } else {
- this.argumentPrefixes = null;
- }
- }
- }
- if ((optionValue = optionsMap.get(OPTION_FieldSuffixes)) != null) {
- if (optionValue instanceof String) {
- String stringValue = (String) optionValue;
- if (stringValue.length() > 0){
- this.fieldSuffixes = this.splitAndTrimOn(',', stringValue.toCharArray());
- } else {
- this.fieldSuffixes = null;
- }
- }
- }
- if ((optionValue = optionsMap.get(OPTION_StaticFieldSuffixes)) != null) {
- if (optionValue instanceof String) {
- String stringValue = (String) optionValue;
- if (stringValue.length() > 0){
- this.staticFieldSuffixes = this.splitAndTrimOn(',', stringValue.toCharArray());
- } else {
- this.staticFieldSuffixes = null;
- }
- }
- }
- if ((optionValue = optionsMap.get(OPTION_LocalSuffixes)) != null) {
- if (optionValue instanceof String) {
- String stringValue = (String) optionValue;
- if (stringValue.length() > 0){
- this.localSuffixes = this.splitAndTrimOn(',', stringValue.toCharArray());
- } else {
- this.localSuffixes = null;
- }
- }
- }
- if ((optionValue = optionsMap.get(OPTION_ArgumentSuffixes)) != null) {
- if (optionValue instanceof String) {
- String stringValue = (String) optionValue;
- if (stringValue.length() > 0){
- this.argumentSuffixes = this.splitAndTrimOn(',', stringValue.toCharArray());
- } else {
- this.argumentSuffixes = null;
- }
- }
- }
- if ((optionValue = optionsMap.get(OPTION_PerformForbiddenReferenceCheck)) != null) {
- if (ENABLED.equals(optionValue)) {
- this.checkForbiddenReference = true;
- } else if (DISABLED.equals(optionValue)) {
- this.checkForbiddenReference = false;
- }
- }
- if ((optionValue = optionsMap.get(OPTION_PerformDiscouragedReferenceCheck)) != null) {
- if (ENABLED.equals(optionValue)) {
- this.checkDiscouragedReference = true;
- } else if (DISABLED.equals(optionValue)) {
- this.checkDiscouragedReference = false;
- }
- }
- if ((optionValue = optionsMap.get(OPTION_CamelCaseMatch)) != null) {
- if (ENABLED.equals(optionValue)) {
- this.camelCaseMatch = true;
- } else if (DISABLED.equals(optionValue)) {
- this.camelCaseMatch = false;
- }
- }
- if ((optionValue = optionsMap.get(OPTION_PerformDeprecationCheck)) != null) {
- if (ENABLED.equals(optionValue)) {
- this.checkDeprecation = true;
- } else if (DISABLED.equals(optionValue)) {
- this.checkDeprecation = false;
- }
- }
- if ((optionValue = optionsMap.get(OPTION_SuggestStaticImports)) != null) {
- if (ENABLED.equals(optionValue)) {
- this.suggestStaticImport = true;
- } else if (DISABLED.equals(optionValue)) {
- this.suggestStaticImport = false;
- }
- }
- }
-
- private char[][] splitAndTrimOn(char divider, char[] arrayToSplit) {
- char[][] result = CharOperation.splitAndTrimOn(',', arrayToSplit);
-
- int length = result.length;
-
- int resultCount = 0;
- for (int i = 0; i < length; i++) {
- if(result[i].length != 0) {
- result[resultCount++] = result[i];
- }
- }
- if(resultCount != length) {
- System.arraycopy(result, 0, result = new char[resultCount][], 0, resultCount);
- }
- return result;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/impl/AssistParser.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/impl/AssistParser.java
deleted file mode 100644
index 76daa138..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/impl/AssistParser.java
+++ /dev/null
@@ -1,1314 +0,0 @@
-/*******************************************************************************
- * 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.codeassist.impl;
-
-/*
- * Parser extension for code assist task
- *
- */
-
-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.Block;
-import org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ConstructorDeclaration;
-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.FieldDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ForeachStatement;
-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.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.SingleNameReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Statement;
-import org.eclipse.wst.jsdt.internal.compiler.ast.SuperReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ThisReference;
-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.classfmt.ClassFileConstants;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Binding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ExtraCompilerModifiers;
-import org.eclipse.wst.jsdt.internal.compiler.parser.Parser;
-import org.eclipse.wst.jsdt.internal.compiler.parser.RecoveredBlock;
-import org.eclipse.wst.jsdt.internal.compiler.parser.RecoveredElement;
-import org.eclipse.wst.jsdt.internal.compiler.parser.RecoveredField;
-import org.eclipse.wst.jsdt.internal.compiler.parser.RecoveredInitializer;
-import org.eclipse.wst.jsdt.internal.compiler.parser.RecoveredMethod;
-import org.eclipse.wst.jsdt.internal.compiler.parser.RecoveredType;
-import org.eclipse.wst.jsdt.internal.compiler.parser.RecoveredUnit;
-import org.eclipse.wst.jsdt.internal.compiler.problem.AbortCompilation;
-import org.eclipse.wst.jsdt.internal.compiler.problem.ProblemReporter;
-
-public abstract class AssistParser extends Parser {
-
- // Default behavior is to stop parsing at the cursor position, but
- // we need to parse fully so that types can be inferred
- public static final boolean STOP_AT_CURSOR=false;
-
- public ASTNode assistNode;
- public boolean isOrphanCompletionNode;
-
- /* recovery */
- int[] blockStarts = new int[30];
-
- // the previous token read by the scanner
- protected int previousToken;
-
- // the index in the identifier stack of the previous identifier
- protected int previousIdentifierPtr;
-
- // element stack
- protected static final int ElementStackIncrement = 100;
- protected int elementPtr;
- protected int[] elementKindStack = new int[ElementStackIncrement];
- protected int[] elementInfoStack = new int[ElementStackIncrement];
- protected int previousKind;
- protected int previousInfo;
-
- // OWNER
- protected static final int ASSIST_PARSER = 512;
-
- // KIND : all values known by AssistParser are between 513 and 1023
- protected static final int K_SELECTOR = ASSIST_PARSER + 1; // whether we are inside a message send
- protected static final int K_TYPE_DELIMITER = ASSIST_PARSER + 2; // whether we are inside a type declaration
- protected static final int K_METHOD_DELIMITER = ASSIST_PARSER + 3; // whether we are inside a method declaration
- protected static final int K_FIELD_INITIALIZER_DELIMITER = ASSIST_PARSER + 4; // whether we are inside a field initializer
- protected static final int K_ATTRIBUTE_VALUE_DELIMITER = ASSIST_PARSER + 5; // whether we are inside a annotation attribute valuer
- protected static final int K_ENUM_CONSTANT_DELIMITER = ASSIST_PARSER + 6; // whether we are inside a field initializer
-
- // selector constants
- protected static final int THIS_CONSTRUCTOR = -1;
- protected static final int SUPER_CONSTRUCTOR = -2;
-
- // enum constant constants
- protected static final int NO_BODY = 0;
- protected static final int WITH_BODY = 1;
-
- protected boolean isFirst = false;
-
-public AssistParser(ProblemReporter problemReporter) {
- super(problemReporter, true);
- this.javadocParser.checkDocComment = false;
-
- this.setMethodsFullRecovery(false);
- this.setStatementsRecovery(false);
-}
-public abstract char[] assistIdentifier();
-public int bodyEnd(AbstractMethodDeclaration method){
- return method.bodyEnd;
-}
-public int bodyEnd(Initializer initializer){
- return initializer.declarationSourceEnd;
-}
-/*
- * Build initial recovery state.
- * Recovery state is inferred from the current state of the parser (reduced node stack).
- */
-public RecoveredElement buildInitialRecoveryState(){
- /* recovery in unit structure */
- if (referenceContext instanceof CompilationUnitDeclaration){
- boolean oldStatementRecoveryActivated = this.statementRecoveryActivated;
- if (!DO_DIET_PARSE)
- this.statementRecoveryActivated=true;
- RecoveredElement element = super.buildInitialRecoveryState();
- this.statementRecoveryActivated=oldStatementRecoveryActivated;
- flushAssistState();
- flushElementStack();
- if (element instanceof RecoveredMethod)
- pushOnElementStack(K_METHOD_DELIMITER);
- return element;
- }
-
- /* recovery in method body */
- lastCheckPoint = 0;
-
- RecoveredElement element = null;
- if (referenceContext instanceof AbstractMethodDeclaration){
- element = new RecoveredMethod((AbstractMethodDeclaration) referenceContext, null, 0, this);
- lastCheckPoint = ((AbstractMethodDeclaration) referenceContext).bodyStart;
- } else {
- /* Initializer bodies are parsed in the context of the type declaration, we must thus search it inside */
- if (referenceContext instanceof TypeDeclaration){
- TypeDeclaration type = (TypeDeclaration) referenceContext;
- for (int i = 0; i < type.fields.length; i++){
- FieldDeclaration field = type.fields[i];
- if (field != null
- && field.getKind() == AbstractVariableDeclaration.INITIALIZER
- && field.declarationSourceStart <= scanner.initialPosition
- && scanner.initialPosition <= field.declarationSourceEnd
- && scanner.eofPosition <= field.declarationSourceEnd+1){
- element = new RecoveredInitializer(field, null, 1, this);
- lastCheckPoint = field.declarationSourceStart;
- break;
- }
- }
- }
- }
-
- if (element == null) return element;
-
- /* add initial block */
- Block block = new Block(0);
- int lastStart = blockStarts[0];
- block.sourceStart = lastStart;
- element = element.add(block, 1);
- int blockIndex = 1; // ignore first block start, since manually rebuilt here
-
- for(int i = 0; i <= astPtr; i++){
- ASTNode node = astStack[i];
-
- if(node instanceof ForeachStatement && ((ForeachStatement)node).action == null) {
- node = ((ForeachStatement)node).elementVariable;
- }
-
- /* check for intermediate block creation, so recovery can properly close them afterwards */
- int nodeStart = node.sourceStart;
- for (int j = blockIndex; j <= realBlockPtr; j++) {
- if (blockStarts[j] >= 0) {
- if (blockStarts[j] > nodeStart) {
- blockIndex = j; // shift the index to the new block
- break;
- }
- if (blockStarts[j] != lastStart) { // avoid multiple block
- // if at same position
- block = new Block(0);
- block.sourceStart = lastStart = blockStarts[j];
- element = element.add(block, 1);
- }
- blockIndex = j + 1; // shift the index to the new block
- } else {
- if (-blockStarts[j] > nodeStart) {
- blockIndex = j; // shift the index to the new block
- break;
- }
- block = new Block(0);
- block.sourceStart = lastStart = -blockStarts[j];
- element = element.add(block, 1);
- }
- }
- if (node instanceof LocalDeclaration){
- LocalDeclaration local = (LocalDeclaration) node;
- if (local.declarationSourceEnd == 0){
- element = element.add(local, 0);
- if (local.initialization == null){
- lastCheckPoint = local.sourceEnd + 1;
- } else {
- lastCheckPoint = local.initialization.sourceEnd + 1;
- }
- } else {
- element = element.add(local, 0);
- lastCheckPoint = local.declarationSourceEnd + 1;
- }
- continue;
- }
- if (node instanceof AbstractMethodDeclaration){
- AbstractMethodDeclaration method = (AbstractMethodDeclaration) node;
- if (method.declarationSourceEnd == 0){
- element = element.add(method, 0);
- lastCheckPoint = method.bodyStart;
- } else {
- element = element.add(method, 0);
- lastCheckPoint = method.declarationSourceEnd + 1;
- }
- continue;
- }
- if (node instanceof Initializer){
- Initializer initializer = (Initializer) node;
- if (initializer.declarationSourceEnd == 0){
- element = element.add(initializer, 1);
- lastCheckPoint = initializer.sourceStart;
- } else {
- element = element.add(initializer, 0);
- lastCheckPoint = initializer.declarationSourceEnd + 1;
- }
- continue;
- }
- if (node instanceof FieldDeclaration){
- FieldDeclaration field = (FieldDeclaration) node;
- if (field.declarationSourceEnd == 0){
- element = element.add(field, 0);
- if (field.initialization == null){
- lastCheckPoint = field.sourceEnd + 1;
- } else {
- lastCheckPoint = field.initialization.sourceEnd + 1;
- }
- } else {
- element = element.add(field, 0);
- lastCheckPoint = field.declarationSourceEnd + 1;
- }
- continue;
- }
- if (node instanceof TypeDeclaration){
- TypeDeclaration type = (TypeDeclaration) node;
- if (type.declarationSourceEnd == 0){
- element = element.add(type, 0);
- lastCheckPoint = type.bodyStart;
- } else {
- element = element.add(type, 0);
- lastCheckPoint = type.declarationSourceEnd + 1;
- }
- continue;
- }
- if (node instanceof ImportReference){
- ImportReference importRef = (ImportReference) node;
- element = element.add(importRef, 0);
- lastCheckPoint = importRef.declarationSourceEnd + 1;
- }
- }
- if (this.currentToken == TokenNameRBRACE) {
- this.currentToken = 0; // closing brace has already been taken care of
- }
-
- /* might need some extra block (after the last reduced node) */
- int pos = this.assistNode == null ? lastCheckPoint : this.assistNode.sourceStart;
- for (int j = blockIndex; j <= realBlockPtr; j++){
- if (blockStarts[j] >= 0) {
- if ((blockStarts[j] < pos) && (blockStarts[j] != lastStart)){ // avoid multiple block if at same position
- block = new Block(0);
- block.sourceStart = lastStart = blockStarts[j];
- element = element.add(block, 1);
- }
- } else {
- if ((blockStarts[j] < pos)){ // avoid multiple block if at same position
- block = new Block(0);
- block.sourceStart = lastStart = -blockStarts[j];
- element = element.add(block, 1);
- }
- }
- }
-
- return element;
-}
-protected void consumeForceNoDiet() {
- super.consumeForceNoDiet();
- // if we are not in a method (ie. we are not in a local variable initializer)
- // then we are entering a field initializer
- if (!isInsideMethod()) {
- if(topKnownElementKind(ASSIST_PARSER) != K_ENUM_CONSTANT_DELIMITER) {
- if(topKnownElementKind(ASSIST_PARSER, 2) != K_ENUM_CONSTANT_DELIMITER) {
- pushOnElementStack(K_FIELD_INITIALIZER_DELIMITER);
- }
- } else {
- int info = topKnownElementInfo(ASSIST_PARSER);
- if(info != NO_BODY) {
- pushOnElementStack(K_FIELD_INITIALIZER_DELIMITER);
- }
- }
-
- }
-}
-protected void consumeMethodBody() {
- super.consumeMethodBody();
- popElement(K_METHOD_DELIMITER);
-}
-protected void consumeMethodHeader() {
- super.consumeMethodHeader();
- pushOnElementStack(K_METHOD_DELIMITER);
-}
-protected void consumeCallExpressionWithArguments() {
- super.consumeCallExpressionWithArguments();
- popElement(K_SELECTOR);
- MessageSend messageSend = (MessageSend)expressionStack[expressionPtr];
- if (messageSend == assistNode){
- this.lastCheckPoint = messageSend.sourceEnd + 1;
- }
-}
-protected void consumeNestedMethod() {
- super.consumeNestedMethod();
- if(!isInsideMethod()) pushOnElementStack(K_METHOD_DELIMITER);
-}
-protected void consumeOpenBlock() {
- // OpenBlock ::= $empty
-
- super.consumeOpenBlock();
- int stackLength = this.blockStarts.length;
- if (this.realBlockPtr >= stackLength) {
- System.arraycopy(
- this.blockStarts, 0,
- this.blockStarts = new int[stackLength + StackIncrement], 0,
- stackLength);
- }
- this.blockStarts[this.realBlockPtr] = scanner.startPosition;
-}
-protected void consumeOpenFakeBlock() {
- // OpenBlock ::= $empty
-
- super.consumeOpenBlock();
- int stackLength = this.blockStarts.length;
- if (this.realBlockPtr >= stackLength) {
- System.arraycopy(
- this.blockStarts, 0,
- this.blockStarts = new int[stackLength + StackIncrement], 0,
- stackLength);
- }
- this.blockStarts[this.realBlockPtr] = -scanner.startPosition;
-}
-
-protected void consumeRestoreDiet() {
- super.consumeRestoreDiet();
- // if we are not in a method (ie. we were not in a local variable initializer)
- // then we are exiting a field initializer
- if (!isInsideMethod()) {
- popElement(K_FIELD_INITIALIZER_DELIMITER);
- }
-}
-
-protected void consumeToken(int token) {
- super.consumeToken(token);
-
- if(isFirst) {
- isFirst = false;
- return;
- }
- // register message send selector only if inside a method or if looking at a field initializer
- // and if the current token is an open parenthesis
- if (isInsideMethod() || isInsideFieldInitialization() || isInsideAttributeValue()) {
- switch (token) {
- case TokenNameLPAREN :
- switch (this.previousToken) {
- case TokenNameIdentifier:
- this.pushOnElementStack(K_SELECTOR, this.previousIdentifierPtr);
- break;
- case TokenNamethis: // explicit constructor invocation, eg. this(1, 2)
- this.pushOnElementStack(K_SELECTOR, THIS_CONSTRUCTOR);
- break;
- case TokenNamesuper: // explicit constructor invocation, eg. super(1, 2)
- this.pushOnElementStack(K_SELECTOR, SUPER_CONSTRUCTOR);
- break;
- case TokenNameGREATER: // explicit constructor invocation, eg. Fred<X>[(]1, 2)
- case TokenNameRIGHT_SHIFT: // or fred<X<X>>[(]1, 2)
- case TokenNameUNSIGNED_RIGHT_SHIFT: //or Fred<X<X<X>>>[(]1, 2)
- if(this.identifierPtr > -1) {
- this.pushOnElementStack(K_SELECTOR, this.previousIdentifierPtr);
- }
- break;
- }
- break;
- }
- } else {
- switch (token) {
- case TokenNameRBRACE :
- if(topKnownElementKind(ASSIST_PARSER) == K_TYPE_DELIMITER) {
- popElement(K_TYPE_DELIMITER);
- }
- break;
- }
- }
- this.previousToken = token;
- if (token == TokenNameIdentifier) {
- this.previousIdentifierPtr = this.identifierPtr;
- }
-}
-public abstract ImportReference createAssistImportReference(char[][] tokens, long[] positions);
-public abstract NameReference createQualifiedAssistNameReference(char[][] previousIdentifiers, char[] assistName, long[] positions);
-public abstract TypeReference createQualifiedAssistTypeReference(char[][] previousIdentifiers, char[] assistName, long[] positions);
-public abstract NameReference createSingleAssistNameReference(char[] assistName, long position);
-public abstract TypeReference createSingleAssistTypeReference(char[] assistName, long position);
-public abstract void createAssistTypeForAllocation(AllocationExpression expression);
-/*
- * Flush parser/scanner state regarding to code assist
- */
-
-public abstract int getCursorLocation();
-
-public void flushAssistState(){
- if (STOP_AT_CURSOR || this.lastCheckPoint<this.getCursorLocation())
- {
- this.assistNode = null;
- this.setAssistIdentifier(null);
- }
- this.isOrphanCompletionNode = false;
-}
-protected void flushElementStack() {
- this.elementPtr = -1;
- this.previousKind = 0;
- this.previousInfo = 0;
-}
-/*
- * Build specific type reference nodes in case the cursor is located inside the type reference
- */
-protected TypeReference getTypeReference(int dim) {
-
- int index;
-
- /* no need to take action if not inside completed identifiers */
- if ((index = indexOfAssistIdentifier(true)) < 0) {
- return super.getTypeReference(dim);
- }
- int length = identifierLengthStack[identifierLengthPtr];
- TypeReference reference;
- int numberOfIdentifiers = this.genericsIdentifiersLengthStack[this.genericsIdentifiersLengthPtr--];
- if (length != numberOfIdentifiers || this.genericsLengthStack[this.genericsLengthPtr] != 0) {
- identifierLengthPtr--;
- // generic type
- reference = null;
- } else {
- /* retrieve identifiers subset and whole positions, the assist node positions
- should include the entire replaced source. */
-
- char[][] subset = identifierSubSet(index);
- identifierLengthPtr--;
- identifierPtr -= length;
- long[] positions = new long[length];
- System.arraycopy(
- identifierPositionStack,
- identifierPtr + 1,
- positions,
- 0,
- length);
-
- /* build specific assist on type reference */
-
- if (index == 0) {
-// genericsIdentifiersLengthPtr--;
- genericsLengthPtr--;
- /* assist inside first identifier */
- reference = this.createSingleAssistTypeReference(
- assistIdentifier(),
- positions[0]);
- } else {
-// genericsIdentifiersLengthPtr--;
- genericsLengthPtr--;
- /* assist inside subsequent identifier */
- reference = this.createQualifiedAssistTypeReference(
- subset,
- assistIdentifier(),
- positions);
- }
- assistNode = reference;
- this.lastCheckPoint = reference.sourceEnd + 1;
- }
- return reference;
-}
-/*
- * Copy of code from superclass with the following change:
- * In the case of qualified name reference if the cursor location is on the
- * qualified name reference, then create a CompletionOnQualifiedNameReference
- * instead.
- */
-protected NameReference getUnspecifiedReferenceOptimized() {
-
- int completionIndex;
-
- /* no need to take action if not inside completed identifiers */
- if ((completionIndex = indexOfAssistIdentifier()) < 0) {
- return super.getUnspecifiedReferenceOptimized();
- }
-
- /* retrieve identifiers subset and whole positions, the completion node positions
- should include the entire replaced source. */
- int length = identifierLengthStack[identifierLengthPtr];
- char[][] subset = identifierSubSet(completionIndex);
- identifierLengthPtr--;
- identifierPtr -= length;
- long[] positions = new long[length];
- System.arraycopy(
- identifierPositionStack,
- identifierPtr + 1,
- positions,
- 0,
- length);
-
- /* build specific completion on name reference */
- NameReference reference;
- if (completionIndex == 0) {
- /* completion inside first identifier */
- reference = this.createSingleAssistNameReference(assistIdentifier(), positions[0]);
- } else {
- /* completion inside subsequent identifier */
- reference = this.createQualifiedAssistNameReference(subset, assistIdentifier(), positions);
- }
- reference.bits &= ~ASTNode.RestrictiveFlagMASK;
- reference.bits |= Binding.LOCAL | Binding.FIELD;
-
- assistNode = reference;
- lastCheckPoint = reference.sourceEnd + 1;
- return reference;
-}
-public void goForBlockStatementsopt() {
- super.goForBlockStatementsopt();
- isFirst = true;
-}
-public void goForHeaders(){
- super.goForHeaders();
- isFirst = true;
-}
-public void goForCompilationUnit(){
- super.goForCompilationUnit();
- isFirst = true;
-}
-public void goForBlockStatementsOrCatchHeader() {
- super.goForBlockStatementsOrCatchHeader();
- isFirst = true;
-}
-
-public void goForProgramElements() {
- super.goForProgramElements();
- isFirst = true;
-}
-
-/*
- * Retrieve a partial subset of a qualified name reference up to the completion point.
- * It does not pop the actual awaiting identifiers, so as to be able to retrieve position
- * information afterwards.
- */
-protected char[][] identifierSubSet(int subsetLength){
-
- if (subsetLength == 0) return null;
-
- char[][] subset;
- System.arraycopy(
- identifierStack,
- identifierPtr - identifierLengthStack[identifierLengthPtr] + 1,
- (subset = new char[subsetLength][]),
- 0,
- subsetLength);
- return subset;
-}
-
-protected int indexOfAssistIdentifier(){
- return this.indexOfAssistIdentifier(false);
-}
-/*
- * Iterate the most recent group of awaiting identifiers (grouped for qualified name reference (eg. aa.bb.cc)
- * so as to check whether one of them is the assist identifier.
- * If so, then answer the index of the assist identifier (0 being the first identifier of the set).
- * eg. aa(0).bb(1).cc(2)
- * If no assist identifier was found, answers -1.
- */
-protected int indexOfAssistIdentifier(boolean useGenericsStack){
-
- if (identifierLengthPtr < 0){
- return -1; // no awaiting identifier
- }
-
- char[] assistIdentifier ;
- if ((assistIdentifier = this.assistIdentifier()) == null){
- return -1; // no assist identifier found yet
- }
-
- // iterate awaiting identifiers backwards
- int length = identifierLengthStack[identifierLengthPtr];
- if(useGenericsStack && length > 0 && this.genericsIdentifiersLengthPtr > -1 ) {
- length = this.genericsIdentifiersLengthStack[this.genericsIdentifiersLengthPtr];
- }
- for (int i = 0; i < length; i++){
- if (identifierStack[identifierPtr - i] == assistIdentifier){
- return length - i - 1;
- }
- }
- // none of the awaiting identifiers is the completion one
- return -1;
-}
-public void initialize() {
- super.initialize();
- this.flushAssistState();
- this.flushElementStack();
- this.previousIdentifierPtr = -1;
-}
-public void initialize(boolean initializeNLS) {
- super.initialize(initializeNLS);
- this.flushAssistState();
- this.flushElementStack();
- this.previousIdentifierPtr = -1;
-}
-public abstract void initializeScanner();
-protected boolean isIndirectlyInsideFieldInitialization(){
- int i = elementPtr;
- while(i > -1) {
- if(elementKindStack[i] == K_FIELD_INITIALIZER_DELIMITER)
- return true;
- i--;
- }
- return false;
-}
-protected boolean isIndirectlyInsideMethod(){
- int i = elementPtr;
- while(i > -1) {
- if(elementKindStack[i] == K_METHOD_DELIMITER)
- return true;
- i--;
- }
- return false;
-}
-protected boolean isIndirectlyInsideType(){
- int i = elementPtr;
- while(i > -1) {
- if(elementKindStack[i] == K_TYPE_DELIMITER)
- return true;
- i--;
- }
- return false;
-}
-protected boolean isInsideAttributeValue(){
- int i = elementPtr;
- while(i > -1) {
- switch (elementKindStack[i]) {
- case K_TYPE_DELIMITER : return false;
- case K_METHOD_DELIMITER : return false;
- case K_FIELD_INITIALIZER_DELIMITER : return false;
- case K_ATTRIBUTE_VALUE_DELIMITER : return true;
- }
- i--;
- }
- return false;
-}
-protected boolean isInsideFieldInitialization(){
- int i = elementPtr;
- while(i > -1) {
- switch (elementKindStack[i]) {
- case K_TYPE_DELIMITER : return false;
- case K_METHOD_DELIMITER : return false;
- case K_FIELD_INITIALIZER_DELIMITER : return true;
- }
- i--;
- }
- return false;
-}
-protected boolean isInsideMethod(){
- int i = elementPtr;
- while(i > -1) {
- switch (elementKindStack[i]) {
- case K_TYPE_DELIMITER : return false;
- case K_METHOD_DELIMITER : return true;
- case K_FIELD_INITIALIZER_DELIMITER : return false;
- }
- i--;
- }
- return false;
-}
-protected boolean isInsideType(){
- int i = elementPtr;
- while(i > -1) {
- switch (elementKindStack[i]) {
- case K_TYPE_DELIMITER : return true;
- case K_METHOD_DELIMITER : return false;
- case K_FIELD_INITIALIZER_DELIMITER : return false;
- }
- i--;
- }
- return false;
-}
-protected int lastIndexOfElement(int kind) {
- int i = elementPtr;
- while(i > -1) {
- if(elementKindStack[i] == kind) return i;
- i--;
- }
- return -1;
-}
-/**
- * Parse the block statements inside the given method declaration and try to complete at the
- * cursor location.
- */
-public void parseBlockStatements(AbstractMethodDeclaration md, CompilationUnitDeclaration unit) {
- if (md instanceof MethodDeclaration) {
- parseBlockStatements((MethodDeclaration) md, unit);
- } else if (md instanceof ConstructorDeclaration) {
- parseBlockStatements((ConstructorDeclaration) md, unit);
- }
-}
-/**
- * Parse the block statements inside the given constructor declaration and try to complete at the
- * cursor location.
- */
-public void parseBlockStatements(ConstructorDeclaration cd, CompilationUnitDeclaration unit) {
- //only parse the method body of cd
- //fill out its statements
-
- //convert bugs into parse error
-
- initialize();
-
- // simulate goForConstructorBody except that we don't want to balance brackets because they are not going to be balanced
- goForBlockStatementsopt();
-
- referenceContext = cd;
- compilationUnit = unit;
-
- scanner.resetTo(cd.bodyStart, bodyEnd(cd));
- consumeNestedMethod();
- try {
- parse();
- } catch (AbortCompilation ex) {
- lastAct = ERROR_ACTION;
- }
-
- if (lastAct == ERROR_ACTION) {
- return;
- }
-
- // attach the statements as we might be searching for a reference to a local type
- cd.explicitDeclarations = realBlockStack[realBlockPtr--];
- int length;
- if ((length = astLengthStack[astLengthPtr--]) != 0) {
- astPtr -= length;
- if (astStack[astPtr + 1] instanceof ExplicitConstructorCall)
- //avoid a isSomeThing that would only be used here BUT what is faster between two alternatives ?
- {
- System.arraycopy(
- astStack,
- astPtr + 2,
- cd.statements = new Statement[length - 1],
- 0,
- length - 1);
- cd.constructorCall = (ExplicitConstructorCall) astStack[astPtr + 1];
- } else { //need to add explicitly the super();
- System.arraycopy(
- astStack,
- 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;
- }
-}
-/**
- * Parse the block statements inside the given initializer and try to complete at the
- * cursor location.
- */
-public void parseBlockStatements(
- Initializer initializer,
- TypeDeclaration type,
- CompilationUnitDeclaration unit) {
-
- initialize();
-
- // simulate goForInitializer except that we don't want to balance brackets because they are not going to be balanced
- goForBlockStatementsopt();
-
- referenceContext = type;
- compilationUnit = unit;
-
- scanner.resetTo(initializer.sourceStart, bodyEnd(initializer)); // just after the beginning {
- consumeNestedMethod();
- try {
- parse();
- } catch (AbortCompilation ex) {
- lastAct = ERROR_ACTION;
- } finally {
- nestedMethod[nestedType]--;
- }
-
- if (lastAct == ERROR_ACTION) {
- return;
- }
-
- // attach the statements as we might be searching for a reference to a local type
- initializer.block.explicitDeclarations = realBlockStack[realBlockPtr--];
- int length;
- if ((length = astLengthStack[astLengthPtr--]) > 0) {
- System.arraycopy(astStack, (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;
- }
-}
-/**
- * Parse the block statements inside the given method declaration and try to complete at the
- * cursor location.
- */
-public void parseBlockStatements(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;
-
- initialize();
-
- // simulate goForMethodBody except that we don't want to balance brackets because they are not going to be balanced
- goForBlockStatementsopt();
-
- referenceContext = md;
- compilationUnit = unit;
-
- scanner.resetTo(md.bodyStart, bodyEnd(md)); // reset the scanner to parser from { down to the cursor location
- consumeNestedMethod();
- try {
- parse();
- } catch (AbortCompilation ex) {
- lastAct = ERROR_ACTION;
- } finally {
- nestedMethod[nestedType]--;
- }
-
- if (lastAct == ERROR_ACTION) {
- return;
- }
-
- // attach the statements as we might be searching for a reference to a local type
- md.explicitDeclarations = realBlockStack[realBlockPtr--];
- int length;
- if ((length = astLengthStack[astLengthPtr--]) != 0) {
- System.arraycopy(
- astStack,
- (astPtr -= length) + 1,
- md.statements = new Statement[length],
- 0,
- length);
- } else {
- if (!containsComment(md.bodyStart, md.bodyEnd)) {
- md.bits |= ASTNode.UndocumentedEmptyBlock;
- }
- }
-
-}
-protected void popElement(int kind){
- if(elementPtr < 0 || elementKindStack[elementPtr] != kind) return;
-
- previousKind = elementKindStack[elementPtr];
- previousInfo = elementInfoStack[elementPtr];
-
- switch (kind) {
- default :
- elementPtr--;
- break;
- }
-}
-protected void popUntilElement(int kind){
- if(elementPtr < 0) return;
- int i = elementPtr;
- while (i >= 0 && elementKindStack[i] != kind) {
- i--;
- }
- if(i >= 0) {
- if(i < elementPtr) {
- previousKind = elementKindStack[i+1];
- previousInfo = elementInfoStack[i+1];
- }
- elementPtr = i;
- }
-}
-/*
- * 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;
-
- // initialize element stack
- int fieldInitializerIndex = lastIndexOfElement(K_FIELD_INITIALIZER_DELIMITER);
- int methodIndex = lastIndexOfElement(K_METHOD_DELIMITER);
- if(methodIndex == fieldInitializerIndex) {
- // there is no method and no field initializer
- flushElementStack();
- } else if(methodIndex > fieldInitializerIndex) {
- popUntilElement(K_METHOD_DELIMITER);
- } else {
- popUntilElement(K_FIELD_INITIALIZER_DELIMITER);
- }
-}
-/*
- * Prepares the state of the parser to go for Headers.
- */
-protected void prepareForHeaders() {
- nestedMethod[nestedType = 0] = 0;
- variablesCounter[nestedType] = 0;
- realBlockStack[realBlockPtr = 0] = 0;
-
-// popUntilElement(K_TYPE_DELIMITER);
-//
-// if(this.topKnownElementKind(ASSIST_PARSER) != K_TYPE_DELIMITER) {
-// // is outside a type and inside a compilation unit.
-// // remove all elements.
-// this.flushElementStack();
-// }
-}
-protected void pushOnElementStack(int kind){
- this.pushOnElementStack(kind, 0);
-}
-protected void pushOnElementStack(int kind, int info){
- if (this.elementPtr < -1) return;
-
- this.previousKind = 0;
- this.previousInfo = 0;
-
- int stackLength = this.elementKindStack.length;
- if (++this.elementPtr >= stackLength) {
- System.arraycopy(
- this.elementKindStack, 0,
- this.elementKindStack = new int[stackLength + StackIncrement], 0,
- stackLength);
- System.arraycopy(
- this.elementInfoStack, 0,
- this.elementInfoStack = new int[stackLength + StackIncrement], 0,
- stackLength);
- }
- this.elementKindStack[this.elementPtr] = kind;
- this.elementInfoStack[this.elementPtr] = info;
-}
-public void recoveryExitFromVariable() {
- if(currentElement != null && currentElement instanceof RecoveredField
- && !(currentElement instanceof RecoveredInitializer)) {
- RecoveredElement oldElement = currentElement;
- super.recoveryExitFromVariable();
- if(oldElement != currentElement) {
- popElement(K_FIELD_INITIALIZER_DELIMITER);
- }
- } else {
- super.recoveryExitFromVariable();
- }
-}
-public void recoveryTokenCheck() {
- RecoveredElement oldElement = currentElement;
- switch (currentToken) {
- case TokenNameLBRACE :
- super.recoveryTokenCheck();
- if(currentElement instanceof RecoveredInitializer) {
- if(oldElement instanceof RecoveredField) {
- popUntilElement(K_FIELD_INITIALIZER_DELIMITER);
- popElement(K_FIELD_INITIALIZER_DELIMITER);
- }
- if(currentElement != oldElement
- && topKnownElementKind(ASSIST_PARSER) != K_METHOD_DELIMITER) {
- pushOnElementStack(K_METHOD_DELIMITER);
- }
- }
- break;
- case TokenNameRBRACE :
- super.recoveryTokenCheck();
- if(currentElement != oldElement && !isInsideAttributeValue()) {
- if(oldElement instanceof RecoveredInitializer
- || oldElement instanceof RecoveredMethod
- || (oldElement instanceof RecoveredBlock && oldElement.parent instanceof RecoveredInitializer)
- || (oldElement instanceof RecoveredBlock && oldElement.parent instanceof RecoveredMethod)) {
- popUntilElement(K_METHOD_DELIMITER);
- popElement(K_METHOD_DELIMITER);
- } else if(oldElement instanceof RecoveredType) {
- popUntilElement(K_TYPE_DELIMITER);
- if(!(referenceContext instanceof CompilationUnitDeclaration)
- || isIndirectlyInsideFieldInitialization()
- || currentElement instanceof RecoveredUnit) {
- popElement(K_TYPE_DELIMITER);
- }
- }
- }
- break;
- default :
- super.recoveryTokenCheck();
- break;
- }
-}
-public void reset(){
- this.flushAssistState();
-}
-/*
- * 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() {
-
- // reset internal stacks
- this.astPtr = -1;
- this.astLengthPtr = -1;
- this.expressionPtr = -1;
- this.expressionLengthPtr = -1;
- this.identifierPtr = -1;
- this.identifierLengthPtr = -1;
- this.intPtr = -1;
- this.dimensions = 0 ;
- this.recoveredStaticInitializerStart = 0;
-
- this.genericsIdentifiersLengthPtr = -1;
- this.genericsLengthPtr = -1;
- this.genericsPtr = -1;
-
- this.modifiers = ClassFileConstants.AccDefault;
- this.modifiersSourceStart = -1;
-
- // if in diet mode, reset the diet counter because we're going to restart outside an initializer.
- if (diet) dietInt = 0;
-
- /* attempt to move checkpoint location */
- if (!this.moveRecoveryCheckpoint()) return false;
-
- // only look for headers
- if (referenceContext instanceof CompilationUnitDeclaration
- || this.assistNode != null){
- if(isInsideMethod() &&
- isIndirectlyInsideFieldInitialization() &&
- this.assistNode == null
- ){
- this.prepareForBlockStatements();
- goForBlockStatementsOrCatchHeader();
- } else {
- this.prepareForHeaders();
- if (DO_DIET_PARSE)
- {
- goForHeaders();
- this.diet = true; // passed this point, will not consider method bodies
- }
- else
- goForProgramElements();
- }
- return true;
- }
- if (referenceContext instanceof AbstractMethodDeclaration
- || referenceContext instanceof TypeDeclaration){
-
- if (currentElement instanceof RecoveredType){
- this.prepareForHeaders();
- goForHeaders();
- } else {
- this.prepareForBlockStatements();
- goForBlockStatementsOrCatchHeader();
- }
- return true;
- }
- // does not know how to restart
- return false;
-}
-public abstract void setAssistIdentifier(char[] assistIdent);
-protected int topKnownElementInfo(int owner) {
- return topKnownElementInfo(owner, 0);
-}
-protected int topKnownElementInfo(int owner, int offSet) {
- int i = elementPtr;
- while(i > -1) {
- if((elementKindStack[i] & owner) != 0) {
- if(offSet <= 0) return elementInfoStack[i];
- offSet--;
- }
- i--;
- }
- return 0;
-}
-protected int topKnownElementKind(int owner) {
- return topKnownElementKind(owner, 0);
-}
-protected int topKnownElementKind(int owner, int offSet) {
- int i = elementPtr;
- while(i > -1) {
- if((elementKindStack[i] & owner) != 0) {
- if(offSet <= 0) return elementKindStack[i];
- offSet--;
- }
- i--;
- }
- return 0;
-}
-/**
- * If the given ast node is inside an explicit constructor call
- * then wrap it with a fake constructor call.
- * Returns the wrapped completion node or the completion node itself.
- */
-protected ASTNode wrapWithExplicitConstructorCallIfNeeded(ASTNode ast) {
- int selector;
- if (ast != null && topKnownElementKind(ASSIST_PARSER) == K_SELECTOR && ast instanceof Expression &&
- (((selector = topKnownElementInfo(ASSIST_PARSER)) == THIS_CONSTRUCTOR) ||
- (selector == SUPER_CONSTRUCTOR))) {
- ExplicitConstructorCall call = new ExplicitConstructorCall(ExplicitConstructorCall.This);
- call.arguments = new Expression[] {(Expression)ast};
- call.sourceStart = ast.sourceStart;
- call.sourceEnd = ast.sourceEnd;
- return call;
- } else {
- return ast;
- }
-}
-protected void consumeCallExpressionWithSimpleName() {
- int completionIndex;
-
- /* no need to take action if not inside completed identifiers */
- if ((completionIndex = indexOfAssistIdentifier()) < 0) {
- super.consumeCallExpressionWithSimpleName();
- return;
- }
-
-
- int length = identifierLengthStack[identifierLengthPtr];
- char[][] subset = identifierSubSet(completionIndex);
- identifierLengthPtr--;
- identifierPtr -= length;
-
- Expression receiver = this.expressionStack[this.expressionPtr];
- int subsetLength=0;
- long []subsetPositions=null;
- if (receiver instanceof SingleNameReference) {
- SingleNameReference snr = (SingleNameReference) receiver;
- subsetLength=1;
- subset=new char[][]{snr.token};
- subsetPositions=new long[]{(((long)snr.sourceStart)<<32)+snr.sourceEnd};
- }
- else if (receiver instanceof ThisReference)
- {
- ThisReference thisReference = (ThisReference) receiver;
-
- subsetLength=1;
- subsetLength=1;
- subset=new char[][]{{'t','h','i','s'}};
- subsetPositions=new long[]{ (((long)thisReference.sourceStart)<<32)+thisReference.sourceEnd};
-
- }
- else
- //TODO: implement
- throw new org.eclipse.wst.jsdt.core.UnimplementedException();
-
- long[] positions = new long[length+subsetLength];
- if (subsetLength>0)
- {
- System.arraycopy(
- subsetPositions,
- 0,
- positions,
- 0,
- subsetLength);
-
- }
- System.arraycopy(
- identifierPositionStack,
- identifierPtr + 1,
- positions,
- subsetLength,
- length);
-
-
-
- /* build specific completion on name reference */
- NameReference reference;
- if (completionIndex == 0 && subsetLength==0) {
- /* completion inside first identifier */
- reference = this.createSingleAssistNameReference(assistIdentifier(), positions[0]);
- } else {
- /* completion inside subsequent identifier */
- reference = this.createQualifiedAssistNameReference(subset, assistIdentifier(), positions);
- }
- reference.bits &= ~ASTNode.RestrictiveFlagMASK;
- reference.bits |= Binding.LOCAL | Binding.FIELD;
-
- assistNode = reference;
- lastCheckPoint = reference.sourceEnd + 1;
- this.expressionStack[this.expressionPtr] =reference ;
- this.isOrphanCompletionNode = true;
-
-
-}
-protected void consumeMemberExpressionWithSimpleName() {
- int completionIndex;
-
- /* no need to take action if not inside completed identifiers */
- if ((completionIndex = indexOfAssistIdentifier()) < 0) {
- super.consumeMemberExpressionWithSimpleName();
- return;
- }
-
-
- int length = identifierLengthStack[identifierLengthPtr];
- char[][] subset = identifierSubSet(completionIndex);
- identifierLengthPtr--;
- identifierPtr -= length;
-
- Expression receiver = this.expressionStack[this.expressionPtr];
- int subsetLength=0;
- long []subsetPositions=null;
- if (receiver instanceof SingleNameReference) {
- SingleNameReference snr = (SingleNameReference) receiver;
- subsetLength=1;
- subset=new char[][]{snr.token};
- subsetPositions=new long[]{(((long)snr.sourceStart)<<32)+snr.sourceEnd};
- }
- else if (receiver instanceof ThisReference)
- {
- ThisReference thisReference = (ThisReference) receiver;
-
- subsetLength=1;
- subsetLength=1;
- subset=new char[][]{{'t','h','i','s'}};
- subsetPositions=new long[]{ (((long)thisReference.sourceStart)<<32)+thisReference.sourceEnd};
-
- }
- else
- //TODO: implement
- throw new org.eclipse.wst.jsdt.core.UnimplementedException();
-
- long[] positions = new long[length+subsetLength];
- if (subsetLength>0)
- {
- System.arraycopy(
- subsetPositions,
- 0,
- positions,
- 0,
- subsetLength);
-
- }
- System.arraycopy(
- identifierPositionStack,
- identifierPtr + 1,
- positions,
- subsetLength,
- length);
-
-
-
- /* build specific completion on name reference */
- NameReference reference;
- if (completionIndex == 0 && subsetLength==0) {
- /* completion inside first identifier */
- reference = this.createSingleAssistNameReference(assistIdentifier(), positions[0]);
- } else {
- /* completion inside subsequent identifier */
- reference = this.createQualifiedAssistNameReference(subset, assistIdentifier(), positions);
- }
- reference.bits &= ~ASTNode.RestrictiveFlagMASK;
- reference.bits |= Binding.LOCAL | Binding.FIELD;
-
- assistNode = reference;
- lastCheckPoint = reference.sourceEnd + 1;
- this.expressionStack[this.expressionPtr] =reference ;
- this.isOrphanCompletionNode = true;
-
-
-}
-protected void classInstanceCreation(boolean isQualified, boolean isShort) {
- popElement(K_SELECTOR);
- super.classInstanceCreation(isQualified, isShort);
- AllocationExpression expression = (AllocationExpression)this.expressionStack[this.expressionPtr];
- Expression member = expression.member;
- if (member.isSpecialNode())
- {
- this.createAssistTypeForAllocation(expression);
- }
-}
-
-}
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
deleted file mode 100644
index 445d7299..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/impl/Engine.java
+++ /dev/null
@@ -1,364 +0,0 @@
-/*******************************************************************************
- * 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.codeassist.impl;
-
-import java.util.Map;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.CompilationResult;
-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.CompilationUnitDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Initializer;
-import org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration;
-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.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.Binding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.CompilationUnitScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ImportBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ImportConflictBinding;
-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.PackageBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-import org.eclipse.wst.jsdt.internal.compiler.parser.SourceTypeConverter;
-import org.eclipse.wst.jsdt.internal.compiler.problem.ProblemSeverities;
-import org.eclipse.wst.jsdt.internal.core.NameLookup;
-import org.eclipse.wst.jsdt.internal.core.SearchableEnvironment;
-import org.eclipse.wst.jsdt.internal.oaametadata.LibraryAPIs;
-
-public abstract class Engine implements ITypeRequestor, ITypeRequestor2 {
-
- public LookupEnvironment lookupEnvironment;
-
- protected CompilationUnitScope unitScope;
- public SearchableEnvironment nameEnvironment;
-
- public AssistOptions options;
- public CompilerOptions compilerOptions;
- public boolean forbiddenReferenceIsError;
- public boolean discouragedReferenceIsError;
-
- public boolean importCachesInitialized = false;
- public char[][][] importsCache;
- public ImportBinding[] onDemandImportsCache;
- public int importCacheCount = 0;
- public int onDemandImportCacheCount = 0;
- public char[] currentPackageName = null;
-
- public Engine(Map settings){
- this.options = new AssistOptions(settings);
- this.compilerOptions = new CompilerOptions(settings);
- this.forbiddenReferenceIsError =
- (this.compilerOptions.getSeverity(CompilerOptions.ForbiddenReference) & ProblemSeverities.Error) != 0;
- this.discouragedReferenceIsError =
- (this.compilerOptions.getSeverity(CompilerOptions.DiscouragedReference) & ProblemSeverities.Error) != 0;
- }
-
- /**
- * Add an additional binary type
- */
- public void accept(IBinaryType binaryType, PackageBinding packageBinding, AccessRestriction accessRestriction) {
-// lookupEnvironment.createBinaryTypeFrom(binaryType, packageBinding, accessRestriction);
- }
-
- public abstract CompilationUnitDeclaration doParse(ICompilationUnit unit, AccessRestriction accessRestriction) ;
- /**
- * Add an additional compilation unit.
- */
- public void accept(ICompilationUnit sourceUnit, AccessRestriction accessRestriction) {
- CompilationUnitDeclaration parsedUnit = doParse(sourceUnit,accessRestriction);
-
- lookupEnvironment.buildTypeBindings(parsedUnit, accessRestriction);
- lookupEnvironment.completeTypeBindings(parsedUnit, true);
- }
- public void accept(ICompilationUnit unit, char[][] typeNames, AccessRestriction accessRestriction) {
- CompilationUnitDeclaration parsedUnit = doParse(unit,accessRestriction);
-
- lookupEnvironment.buildTypeBindings(parsedUnit, typeNames, accessRestriction);
- lookupEnvironment.completeTypeBindings(parsedUnit, typeNames, true);
- }
-
- /**
- * Add additional source types (the first one is the requested type, the rest is formed by the
- * secondary types defined in the same compilation unit).
- */
- public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding, AccessRestriction accessRestriction) {
- CompilationResult result =
- new CompilationResult(sourceTypes[0].getFileName(), sourceTypes[0].getPackageName(), 1, 1, this.compilerOptions.maxProblemsPerUnit);
- CompilationUnitDeclaration unit =
- SourceTypeConverter.buildCompilationUnit(
- sourceTypes,//sourceTypes[0] is always toplevel here
- SourceTypeConverter.FIELD_AND_METHOD // need field and methods
- | SourceTypeConverter.MEMBER_TYPE, // need member types
- // no need for field initialization
- lookupEnvironment.problemReporter,
- result);
-
- if (unit != null) {
- lookupEnvironment.buildTypeBindings(unit, accessRestriction);
- lookupEnvironment.completeTypeBindings(unit, true);
- }
- }
-
- public void accept(LibraryAPIs libraryMetaData) {
- lookupEnvironment.buildTypeBindings(libraryMetaData);
- }
-
- public abstract AssistParser getParser();
-
- public void initializeImportCaches() {
- ImportBinding[] importBindings = this.unitScope.imports;
- int length = importBindings == null ? 0 : importBindings.length;
-
- this.currentPackageName = CharOperation.concatWith(new char[][] {}, '.');
-
- for (int i = 0; i < length; i++) {
- ImportBinding importBinding = importBindings[i];
- if(importBinding.onDemand) {
- if(this.onDemandImportsCache == null) {
- this.onDemandImportsCache = new ImportBinding[length - i];
- }
- this.onDemandImportsCache[this.onDemandImportCacheCount++] =
- importBinding;
- } else {
- if(!(importBinding.resolvedImport instanceof MethodBinding) ||
- importBinding instanceof ImportConflictBinding) {
- if(this.importsCache == null) {
- this.importsCache = new char[length - i][][];
- }
- this.importsCache[this.importCacheCount++] = new char[][]{
- importBinding.compoundName[importBinding.compoundName.length - 1],
- CharOperation.concatWith(importBinding.compoundName, '.')
- };
- }
- }
- }
-
- this.importCachesInitialized = true;
- }
-
- protected boolean mustQualifyType(
- char[] packageName,
- char[] typeName,
- char[] enclosingTypeNames,
- int modifiers) {
-
- // If there are no types defined into the current CU yet.
- if (unitScope == null)
- return true;
-
- if(!this.importCachesInitialized) {
- this.initializeImportCaches();
- }
-
-
- for (int i = 0; i < this.importCacheCount; i++) {
- char[][] importName = this.importsCache[i];
- if(CharOperation.equals(typeName, importName[0])) {
- char[] fullyQualifiedTypeName =
- enclosingTypeNames == null || enclosingTypeNames.length == 0
- ? CharOperation.concat(
- packageName,
- typeName,
- '.')
- : CharOperation.concat(
- CharOperation.concat(
- packageName,
- enclosingTypeNames,
- '.'),
- typeName,
- '.');
- return !CharOperation.equals(fullyQualifiedTypeName, importName[1]);
- }
- }
-
- if ((enclosingTypeNames == null || enclosingTypeNames.length == 0 ) && CharOperation.equals(this.currentPackageName, packageName))
- return false;
-
- char[] fullyQualifiedEnclosingTypeName = null;
-
- for (int i = 0; i < this.onDemandImportCacheCount; i++) {
- ImportBinding importBinding = this.onDemandImportsCache[i];
- Binding resolvedImport = importBinding.resolvedImport;
-
- char[][] importName = importBinding.compoundName;
- char[] importFlatName = CharOperation.concatWith(importName, '.');
-
- boolean isFound = false;
- // resolvedImport is a ReferenceBindng or a PackageBinding
- if(resolvedImport instanceof ReferenceBinding) {
- if(enclosingTypeNames != null && enclosingTypeNames.length != 0) {
- if(fullyQualifiedEnclosingTypeName == null) {
- fullyQualifiedEnclosingTypeName =
- CharOperation.concat(
- packageName,
- enclosingTypeNames,
- '.');
- }
- if(CharOperation.equals(fullyQualifiedEnclosingTypeName, importFlatName)) {
- isFound = true;
- }
- }
- } else {
- if(enclosingTypeNames == null || enclosingTypeNames.length == 0) {
- if(CharOperation.equals(packageName, importFlatName)) {
- isFound = true;
- }
- }
- }
-
- // find potential conflict with another import
- if(isFound) {
- for (int j = 0; j < this.onDemandImportCacheCount; j++) {
- if(i != j) {
- ImportBinding conflictingImportBinding = this.onDemandImportsCache[j];
- if(conflictingImportBinding.resolvedImport instanceof ReferenceBinding) {
- ReferenceBinding refBinding =
- (ReferenceBinding) conflictingImportBinding.resolvedImport;
- if (refBinding.getMemberType(typeName) != null) {
- return true;
- }
- } else {
- char[] conflictingImportName =
- CharOperation.concatWith(conflictingImportBinding.compoundName, '.');
-
- if (this.nameEnvironment.nameLookup.findType(
- String.valueOf(typeName),
- String.valueOf(conflictingImportName),
- false,
- NameLookup.ACCEPT_ALL,
- false/*don't check restrictions*/) != null) {
- return true;
- }
- }
- }
- }
- return false;
- }
- }
- return true;
- }
-
- /*
- * Find the node (a field, a method or an initializer) at the given position
- * and parse its block statements if it is a method or an initializer.
- * Returns the node or null if not found
- */
- protected ASTNode parseBlockStatements(CompilationUnitDeclaration unit, int position) {
- int length = unit.types.length;
- for (int i = 0; i < length; i++) {
- TypeDeclaration type = unit.types[i];
- if (type.declarationSourceStart < position
- && type.declarationSourceEnd >= position) {
- getParser().scanner.setSource(unit.compilationResult);
- return parseBlockStatements(type, unit, position);
- }
- }
- return null;
- }
-
- private ASTNode parseBlockStatements(
- TypeDeclaration type,
- CompilationUnitDeclaration unit,
- int position) {
- //members
- TypeDeclaration[] memberTypes = type.memberTypes;
- if (memberTypes != null) {
- int length = memberTypes.length;
- for (int i = 0; i < length; i++) {
- TypeDeclaration memberType = memberTypes[i];
- if (memberType.bodyStart > position)
- continue;
- if (memberType.declarationSourceEnd >= position) {
- return parseBlockStatements(memberType, unit, position);
- }
- }
- }
- //methods
- AbstractMethodDeclaration[] methods = type.methods;
- if (methods != null) {
- int length = methods.length;
- for (int i = 0; i < length; i++) {
- AbstractMethodDeclaration method = methods[i];
- if (method.bodyStart > position)
- continue;
-
- if(method.isDefaultConstructor())
- continue;
-
- if (method.declarationSourceEnd >= position) {
-
- getParser().parseBlockStatements(method, unit);
- return method;
- }
- }
- }
- //initializers
- FieldDeclaration[] fields = type.fields;
- if (fields != null) {
- int length = fields.length;
- for (int i = 0; i < length; i++) {
- FieldDeclaration field = fields[i];
- if (field.sourceStart > position)
- continue;
- if (field.declarationSourceEnd >= position) {
- if (field instanceof Initializer) {
- getParser().parseBlockStatements((Initializer)field, type, unit);
- }
- return field;
- }
- }
- }
- return null;
- }
-
- protected void reset() {
- lookupEnvironment.reset();
- }
-
- public static char[] getTypeSignature(TypeBinding typeBinding) {
- return typeBinding.signature();
- }
- public static char[] getSignature(Binding binding) {
- char[] result = null;
- if ((binding.kind() & Binding.TYPE) != 0 || (binding.kind() & Binding.COMPILATION_UNIT) != 0) {
- TypeBinding typeBinding = (TypeBinding)binding;
- result = typeBinding.signature();
- } else if ((binding.kind() & Binding.METHOD) != 0) {
- MethodBinding methodBinding = (MethodBinding)binding;
- int oldMod = methodBinding.modifiers;
- result = methodBinding.signature();
- methodBinding.modifiers = oldMod;
- }
- if (result != null) {
- if ( (binding.kind() & Binding.TYPE) != 0 )
- result = CharOperation.replaceOnCopy(result, '/', '.');
- }
- return result;
- }
-
- public static char[][] getSignatures(Binding[] bindings) {
- int length = bindings == null ? 0 : bindings.length;
- char[][] signatures = new char[length][];
- for (int i = 0; i < length; i++) {
- signatures[i] = getSignature(bindings[i]);
- }
- return signatures;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/impl/Keywords.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/impl/Keywords.java
deleted file mode 100644
index 055312e5..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/impl/Keywords.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.impl;
-
-public interface Keywords {
- int COUNT = 48;
-
- char[] ABSTRACT = "abstract".toCharArray(); //$NON-NLS-1$
- char[] ASSERT = "assert".toCharArray(); //$NON-NLS-1$
- char[] BREAK = "break".toCharArray(); //$NON-NLS-1$
- char[] CASE = "case".toCharArray(); //$NON-NLS-1$
- char[] CATCH = "catch".toCharArray(); //$NON-NLS-1$
- char[] CLASS = "class".toCharArray(); //$NON-NLS-1$
- char[] CONTINUE = "continue".toCharArray(); //$NON-NLS-1$
- char[] DEFAULT = "default".toCharArray(); //$NON-NLS-1$
- char[] DO = "do".toCharArray(); //$NON-NLS-1$
- char[] ELSE = "else".toCharArray(); //$NON-NLS-1$
- char[] EXTENDS = "extends".toCharArray(); //$NON-NLS-1$
- char[] FINAL = "final".toCharArray(); //$NON-NLS-1$
- char[] FINALLY = "finally".toCharArray(); //$NON-NLS-1$
- char[] FOR = "for".toCharArray(); //$NON-NLS-1$
- char[] IF = "if".toCharArray(); //$NON-NLS-1$
- char[] IMPLEMENTS = "implements".toCharArray(); //$NON-NLS-1$
- char[] IMPORT = "import".toCharArray(); //$NON-NLS-1$
- char[] INSTANCEOF = "instanceof".toCharArray(); //$NON-NLS-1$
- char[] INTERFACE = "interface".toCharArray(); //$NON-NLS-1$
- char[] NATIVE = "native".toCharArray(); //$NON-NLS-1$
- char[] NEW = "new".toCharArray(); //$NON-NLS-1$
- char[] PACKAGE = "package".toCharArray(); //$NON-NLS-1$
- char[] PRIVATE = "private".toCharArray(); //$NON-NLS-1$
- char[] PROTECTED = "protected".toCharArray(); //$NON-NLS-1$
- char[] PUBLIC = "public".toCharArray(); //$NON-NLS-1$
- char[] RETURN = "return".toCharArray(); //$NON-NLS-1$
- char[] STATIC = "static".toCharArray(); //$NON-NLS-1$
- char[] STRICTFP = "strictfp".toCharArray(); //$NON-NLS-1$
- char[] SUPER = "super".toCharArray(); //$NON-NLS-1$
- char[] SWITCH = "switch".toCharArray(); //$NON-NLS-1$
- char[] SYNCHRONIZED = "synchronized".toCharArray(); //$NON-NLS-1$
- char[] THIS = "this".toCharArray(); //$NON-NLS-1$
- char[] THROW = "throw".toCharArray(); //$NON-NLS-1$
- char[] THROWS = "throws".toCharArray(); //$NON-NLS-1$
- char[] TRANSIENT = "transient".toCharArray(); //$NON-NLS-1$
- char[] TRY = "try".toCharArray(); //$NON-NLS-1$
- char[] VOLATILE = "volatile".toCharArray(); //$NON-NLS-1$
- char[] WHILE = "while".toCharArray(); //$NON-NLS-1$
- char[] TRUE = "true".toCharArray(); //$NON-NLS-1$
- char[] FALSE = "false".toCharArray(); //$NON-NLS-1$
- char[] NULL = "null".toCharArray(); //$NON-NLS-1$
- char[] VAR = "var".toCharArray(); //$NON-NLS-1$
- char[] FUNCTION = "function".toCharArray(); //$NON-NLS-1$
- char[] UNDEFINED = "undefined".toCharArray(); //$NON-NLS-1$
- char[] DELETE = "delete".toCharArray(); //$NON-NLS-1$
- char[] TYPEOF = "typeof".toCharArray(); //$NON-NLS-1$
- char[] WITH = "with".toCharArray(); //$NON-NLS-1$
- char[] IN = "in".toCharArray(); //$NON-NLS-1$
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionJavadoc.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionJavadoc.java
deleted file mode 100644
index ca2e1ec8..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionJavadoc.java
+++ /dev/null
@@ -1,142 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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.ast.Expression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Javadoc;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocAllocationExpression;
-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.JavadocQualifiedTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocSingleNameReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocSingleTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Binding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ClassScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Scope;
-
-/**
- * Node representing a Javadoc comment including code selection.
- */
-public class SelectionJavadoc extends Javadoc {
-
- Expression selectedNode;
-
- public SelectionJavadoc(int sourceStart, int sourceEnd) {
- super(sourceStart, sourceEnd);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.Javadoc#print(int, java.lang.StringBuffer)
- */
- public StringBuffer print(int indent, StringBuffer output) {
- super.print(indent, output);
- if (this.selectedNode != null) {
- String selectedString = null;
- if (this.selectedNode instanceof JavadocFieldReference) {
- JavadocFieldReference fieldRef = (JavadocFieldReference) this.selectedNode;
- if (fieldRef.methodBinding != null) {
- selectedString = "<SelectOnMethod:"; //$NON-NLS-1$
- } else {
- selectedString = "<SelectOnField:"; //$NON-NLS-1$
- }
- } else if (this.selectedNode instanceof JavadocMessageSend) {
- selectedString = "<SelectOnMethod:"; //$NON-NLS-1$
- } else if (this.selectedNode instanceof JavadocAllocationExpression) {
- selectedString = "<SelectOnConstructor:"; //$NON-NLS-1$
- } else if (this.selectedNode instanceof JavadocSingleNameReference) {
- selectedString = "<SelectOnLocalVariable:"; //$NON-NLS-1$
- } else if (this.selectedNode instanceof JavadocSingleTypeReference) {
- JavadocSingleTypeReference typeRef = (JavadocSingleTypeReference) this.selectedNode;
- if (typeRef.packageBinding == null) {
- selectedString = "<SelectOnType:"; //$NON-NLS-1$
- }
- } else if (this.selectedNode instanceof JavadocQualifiedTypeReference) {
- JavadocQualifiedTypeReference typeRef = (JavadocQualifiedTypeReference) this.selectedNode;
- if (typeRef.packageBinding == null) {
- selectedString = "<SelectOnType:"; //$NON-NLS-1$
- }
- } else {
- selectedString = "<SelectOnType:"; //$NON-NLS-1$
- }
- int pos = output.length()-3;
- output.replace(pos-2,pos, selectedString+selectedNode+'>');
- }
- return output;
- }
-
- /**
- * Resolve selected node if not null and throw exception to let clients know
- * that it has been found.
- *
- * @throws SelectionNodeFound
- */
- private void internalResolve(Scope scope) {
- if (this.selectedNode != null) {
- switch (scope.kind) {
- case Scope.CLASS_SCOPE:
- this.selectedNode.resolveType((ClassScope)scope);
- break;
- case Scope.METHOD_SCOPE:
- this.selectedNode.resolveType((MethodScope)scope);
- break;
- }
- Binding binding = null;
- if (this.selectedNode instanceof JavadocFieldReference) {
- JavadocFieldReference fieldRef = (JavadocFieldReference) this.selectedNode;
- binding = fieldRef.binding;
- if (binding == null && fieldRef.methodBinding != null) {
- binding = fieldRef.methodBinding;
- }
- } else if (this.selectedNode instanceof JavadocMessageSend) {
- binding = ((JavadocMessageSend) this.selectedNode).binding;
- } else if (this.selectedNode instanceof JavadocAllocationExpression) {
- binding = ((JavadocAllocationExpression) this.selectedNode).binding;
- } else if (this.selectedNode instanceof JavadocSingleNameReference) {
- binding = ((JavadocSingleNameReference) this.selectedNode).binding;
- } else if (this.selectedNode instanceof JavadocSingleTypeReference) {
- JavadocSingleTypeReference typeRef = (JavadocSingleTypeReference) this.selectedNode;
- if (typeRef.packageBinding == null) {
- binding = typeRef.resolvedType;
- }
- } else if (this.selectedNode instanceof JavadocQualifiedTypeReference) {
- JavadocQualifiedTypeReference typeRef = (JavadocQualifiedTypeReference) this.selectedNode;
- if (typeRef.packageBinding == null) {
- binding = typeRef.resolvedType;
- }
- } else {
- binding = this.selectedNode.resolvedType;
- }
- throw new SelectionNodeFound(binding);
- }
- }
-
- /**
- * Resolve selected node if not null and throw exception to let clients know
- * that it has been found.
- *
- * @throws SelectionNodeFound
- */
- public void resolve(ClassScope scope) {
- internalResolve(scope);
- }
-
- /**
- * Resolve selected node if not null and throw exception to let clients know
- * that it has been found.
- *
- * @throws SelectionNodeFound
- */
- public void resolve(MethodScope scope) {
- internalResolve(scope);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionJavadocParser.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionJavadocParser.java
deleted file mode 100644
index 6bc32ef9..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionJavadocParser.java
+++ /dev/null
@@ -1,192 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.select;
-
-import java.util.List;
-
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.internal.codeassist.SelectionEngine;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Expression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocQualifiedTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.parser.JavadocParser;
-
-/**
- * Parser specialized for decoding javadoc comments which includes code selection.
- */
-public class SelectionJavadocParser extends JavadocParser {
-
- int selectionStart;
- int selectionEnd;
- ASTNode selectedNode;
-
- public SelectionJavadocParser(SelectionParser sourceParser) {
- super(sourceParser);
- this.kind = SELECTION_PARSER | TEXT_PARSE;
- }
-
- /*
- * Do not parse comment if selection is not included.
- */
- public boolean checkDeprecation(int commentPtr) {
- this.selectionStart = ((SelectionParser)sourceParser).selectionStart;
- this.selectionEnd = ((SelectionParser)sourceParser).selectionEnd;
- this.javadocStart = this.sourceParser.scanner.commentStarts[commentPtr];
- this.javadocEnd = this.sourceParser.scanner.commentStops[commentPtr];
- if (this.javadocStart <= this.selectionStart && this.selectionEnd <= this.javadocEnd) {
- if (SelectionEngine.DEBUG) {
- System.out.println("SELECTION in Javadoc:"); //$NON-NLS-1$
- }
- super.checkDeprecation(commentPtr);
- } else {
- this.docComment = null;
- }
- return false;
- }
-
- /*
- * Replace stored Javadoc node with specific selection one.
- */
- protected boolean commentParse() {
- this.docComment = new SelectionJavadoc(this.javadocStart, this.javadocEnd);
- return super.commentParse();
- }
-
- /*
- * Create argument expression and store it if it includes selection.
- */
- protected Object createArgumentReference(char[] name, int dim, boolean isVarargs, Object typeRef, long[] dimPositions, long argNamePos) throws InvalidInputException {
- // Create argument as we may need it after
- Expression expression = (Expression) super.createArgumentReference(name, dim, isVarargs, typeRef, dimPositions, argNamePos);
- // See if selection is in argument
- int start = ((TypeReference)typeRef).sourceStart;
- int end = ((TypeReference)typeRef).sourceEnd;
- if (start <= this.selectionStart && this.selectionEnd <= end) {
- selectedNode = expression;
- this.abort = true;
- if (SelectionEngine.DEBUG) {
- System.out.println(" selected argument="+selectedNode); //$NON-NLS-1$
- }
- }
- return expression;
- }
-
- /*
- * Verify if field identifier positions include selection.
- * If so, create field reference, store it and abort comment parse.
- * Otherwise return null as we do not need this reference.
- */
- protected Object createFieldReference(Object receiver) throws InvalidInputException {
- int start = (int) (this.identifierPositionStack[0] >>> 32);
- int end = (int) this.identifierPositionStack[0];
- if (start <= this.selectionStart && this.selectionEnd <= end) {
- selectedNode = (ASTNode) super.createFieldReference(receiver);
- this.abort = true;
- if (SelectionEngine.DEBUG) {
- System.out.println(" selected field="+selectedNode); //$NON-NLS-1$
- }
- }
- return null;
- }
-
- /*
- * Verify if method identifier positions include selection.
- * If so, create field reference, store it and abort comment parse.
- * Otherwise return null as we do not need this reference.
- */
- protected Object createMethodReference(Object receiver, List arguments) throws InvalidInputException {
- int memberPtr = this.identifierLengthStack[0] - 1; // may be > 0 for inner class constructor reference
- int start = (int) (this.identifierPositionStack[memberPtr] >>> 32);
- int end = (int) this.identifierPositionStack[memberPtr];
- if (start <= this.selectionStart && this.selectionEnd <= end) {
- selectedNode = (ASTNode) super.createMethodReference(receiver, arguments);
- this.abort = true;
- if (SelectionEngine.DEBUG) {
- System.out.println(" selected method="+selectedNode); //$NON-NLS-1$
- }
- }
- return null;
- }
-
- /*
- * Create type reference and verify if it includes selection.
- * If so, store it and abort comment parse.
- * Otherwise return null as we do not need this reference.
- */
- protected Object createTypeReference(int primitiveToken) {
- // Need to create type ref in case it was needed by members
- TypeReference typeRef = (TypeReference) super.createTypeReference(primitiveToken);
-
- // See if node is concerned by selection
- if (typeRef.sourceStart <= this.selectionStart && this.selectionEnd <= typeRef.sourceEnd) {
- // See if selection is in one of tokens of qualification
- if (typeRef instanceof JavadocQualifiedTypeReference) {
- JavadocQualifiedTypeReference qualifiedTypeRef = (JavadocQualifiedTypeReference) typeRef;
- int size = qualifiedTypeRef.tokens.length - 1;
- for (int i=0; i<size; i++) {
- int start = (int) (qualifiedTypeRef.sourcePositions[i] >>> 32);
- int end = (int) qualifiedTypeRef.sourcePositions[i];
- if (start <= this.selectionStart && this.selectionEnd <= end) {
- int pos = i + 1;
- char[][] tokens = new char[pos][];
- int ptr = this.identifierPtr - size;
- System.arraycopy(this.identifierStack, ptr, tokens, 0, pos);
- long[] positions = new long[pos];
- System.arraycopy(this.identifierPositionStack, ptr, positions, 0, pos);
- selectedNode = new JavadocQualifiedTypeReference(tokens, positions, this.tagSourceStart, this.tagSourceEnd);
- this.abort = true; // we got selected node => cancel parse
- if (SelectionEngine.DEBUG) {
- System.out.println(" selected partial qualified type="+selectedNode); //$NON-NLS-1$
- }
- return typeRef;
- }
- }
- // Selection is in last token => we'll store type ref as this
- }
- // Store type ref as selected node
- selectedNode = typeRef;
- this.abort = true; // we got selected node => cancel parse
- if (SelectionEngine.DEBUG) {
- System.out.println(" selected type="+selectedNode); //$NON-NLS-1$
- }
- }
- return typeRef;
- }
-
- /*
- * Push param reference and verify if it includes selection.
- * If so, store it and abort comment parse.
- */
- protected boolean pushParamName(boolean isTypeParam) {
- if (super.pushParamName(isTypeParam)) {
- Expression expression = (Expression) astStack[astPtr--];
- // See if expression is concerned by selection
- if (expression.sourceStart <= this.selectionStart && this.selectionEnd <= expression.sourceEnd) {
- selectedNode = expression;
- this.abort = true; // we got selected node => cancel parse
- if (SelectionEngine.DEBUG) {
- System.out.println(" selected param="+selectedNode); //$NON-NLS-1$
- }
- }
- }
- return false;
- }
-
- /*
- * Store selected node into doc comment.
- */
- protected void updateDocComment() {
- if (selectedNode instanceof Expression) {
- ((SelectionJavadoc) this.docComment).selectedNode = (Expression) selectedNode;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionNodeFound.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionNodeFound.java
deleted file mode 100644
index f535e8aa..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionNodeFound.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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.lookup.Binding;
-
-public class SelectionNodeFound extends RuntimeException {
-
- public Binding binding;
- public boolean isDeclaration;
- private static final long serialVersionUID = -7335444736618092295L; // backward compatible
-
-public SelectionNodeFound() {
- this(null, false); // we found a problem in the selection node
-}
-public SelectionNodeFound(Binding binding) {
- this(binding, false);
-}
-public SelectionNodeFound(Binding binding, boolean isDeclaration) {
- this.binding = binding;
- this.isDeclaration = isDeclaration;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnArgumentName.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnArgumentName.java
deleted file mode 100644
index f3f6e827..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnArgumentName.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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.ast.Argument;
-import org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class SelectionOnArgumentName extends Argument {
-
- public SelectionOnArgumentName(char[] name , long posNom , TypeReference tr , int modifiers){
-
- super(name, posNom, tr, modifiers);
- }
-
- public void bind(MethodScope scope, TypeBinding typeBinding, boolean used) {
-
- super.bind(scope, typeBinding, used);
- throw new SelectionNodeFound(binding);
- }
-
- public StringBuffer print(int indent, StringBuffer output) {
-
- printIndent(indent, output);
- output.append("<SelectionOnArgumentName:"); //$NON-NLS-1$
- if (type != null) type.print(0, output).append(' ');
- output.append(name);
- if (initialization != null) {
- output.append(" = ");//$NON-NLS-1$
- initialization.printExpression(0, output);
- }
- return output.append('>');
- }
-
- public void resolve(BlockScope scope) {
-
- super.resolve(scope);
- throw new SelectionNodeFound(binding);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnExplicitConstructorCall.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnExplicitConstructorCall.java
deleted file mode 100644
index b785defc..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnExplicitConstructorCall.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.select;
-
-/*
- * Selection node build by the parser in any case it was intending to
- * reduce an explicit constructor call containing the cursor.
- * e.g.
- *
- * class X {
- * void foo() {
- * Y.[start]super[end](1, 2)
- * }
- * }
- *
- * ---> class X {
- * void foo() {
- * <SelectOnExplicitConstructorCall:Y.super(1, 2)>
- * }
- * }
- *
- */
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.ExplicitConstructorCall;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ProblemReasons;
-
-public class SelectionOnExplicitConstructorCall extends ExplicitConstructorCall {
-
- public SelectionOnExplicitConstructorCall(int accessMode) {
-
- super(accessMode);
- }
-
- public StringBuffer printStatement(int tab, StringBuffer output) {
-
- printIndent(tab, output);
- output.append("<SelectOnExplicitConstructorCall:"); //$NON-NLS-1$
- if (qualification != null) qualification.printExpression(0, output).append('.');
- if (accessMode == This) {
- output.append("this("); //$NON-NLS-1$
- } else {
- output.append("super("); //$NON-NLS-1$
- }
- 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(")>;"); //$NON-NLS-1$
- }
-
- public void resolve(BlockScope scope) {
-
- super.resolve(scope);
-
- // tolerate some error cases
- if (binding == null ||
- !(binding.isValidBinding() ||
- binding.problemId() == ProblemReasons.NotVisible))
- throw new SelectionNodeFound();
- else
- throw new SelectionNodeFound(binding);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnFieldReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnFieldReference.java
deleted file mode 100644
index 185e19c2..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnFieldReference.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.select;
-
-/*
- * Selection node build by the parser in any case it was intending to
- * reduce a field reference containing the cursor.
- * e.g.
- *
- * class X {
- * void foo() {
- * bar().[start]fred[end]
- * }
- * }
- *
- * ---> class X {
- * void foo() {
- * <SelectOnFieldReference:bar().fred>
- * }
- * }
- *
- */
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.FieldReference;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ProblemReasons;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class SelectionOnFieldReference extends FieldReference {
-
- public SelectionOnFieldReference(char[] source , long pos) {
-
- super(source, pos);
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output){
-
- output.append("<SelectionOnFieldReference:"); //$NON-NLS-1$
- return super.printExpression(0, output).append('>');
- }
-
- public TypeBinding resolveType(BlockScope scope) {
-
- super.resolveType(scope);
- // tolerate some error cases
- if (binding == null ||
- !(binding.isValidBinding() ||
- binding.problemId() == ProblemReasons.NotVisible
- || binding.problemId() == ProblemReasons.InheritedNameHidesEnclosingName
- || binding.problemId() == ProblemReasons.NonStaticReferenceInConstructorInvocation
- || binding.problemId() == ProblemReasons.NonStaticReferenceInStaticContext))
- throw new SelectionNodeFound();
- else
- throw new SelectionNodeFound(binding);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnFieldType.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnFieldType.java
deleted file mode 100644
index a2447651..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnFieldType.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference;
-
-public class SelectionOnFieldType extends FieldDeclaration {
- public SelectionOnFieldType(TypeReference type) {
- super();
- this.sourceStart = type.sourceStart;
- this.sourceEnd = type.sourceEnd;
- this.type = type;
- this.name = CharOperation.NO_CHAR;
- }
- public StringBuffer printStatement(int tab, StringBuffer output) {
- return type.print(tab, output).append(';');
- }
-}
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
deleted file mode 100644
index 08c559a1..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnImportReference.java
+++ /dev/null
@@ -1,48 +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.codeassist.select;
-
-/*
- * Selection node build by the parser in any case it was intending to
- * reduce an import reference containing the assist identifier.
- * e.g.
- *
- * import java.[start]io[end].*;
- * class X {
- * void foo() {
- * }
- * }
- *
- * ---> <SelectOnImport:java.io>
- * class X {
- * void foo() {
- * }
- * }
- *
- */
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.ImportReference;
-
-public class SelectionOnImportReference extends ImportReference {
-
-public SelectionOnImportReference(char[][] tokens , long[] positions) {
- super(tokens, positions, false);
-}
-public StringBuffer print(int indent, StringBuffer output, boolean withOnDemand) {
-
- printIndent(indent, output).append("<SelectOnImport:"); //$NON-NLS-1$
- for (int i = 0; i < tokens.length; i++) {
- if (i > 0) output.append('.');
- output.append(tokens[i]);
- }
- return output.append('>');
-}
-}
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
deleted file mode 100644
index 76fdd834..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnLocalName.java
+++ /dev/null
@@ -1,45 +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.codeassist.select;
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-
-public class SelectionOnLocalName extends LocalDeclaration{
-
- public SelectionOnLocalName(char[] name, int sourceStart, int sourceEnd) {
-
- super(name, sourceStart, sourceEnd);
- }
-
- public void resolve(BlockScope scope) {
-
- super.resolve(scope);
- throw new SelectionNodeFound(binding);
- }
-
- public StringBuffer printAsExpression(int indent, StringBuffer output) {
- printIndent(indent, output);
- output.append("<SelectionOnLocalName:"); //$NON-NLS-1$
- printModifiers(this.modifiers, output);
- output.append(this.name);
- if (initialization != null) {
- output.append(" = "); //$NON-NLS-1$
- initialization.printExpression(0, output);
- }
- return output.append('>');
- }
-
- public StringBuffer printStatement(int indent, StringBuffer output) {
- this.printAsExpression(indent, output);
- return output.append(';');
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnMessageSend.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnMessageSend.java
deleted file mode 100644
index b4d14b15..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnMessageSend.java
+++ /dev/null
@@ -1,82 +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.codeassist.select;
-
-/*
- * Selection node build by the parser in any case it was intending to
- * reduce a message send containing the cursor.
- * e.g.
- *
- * class X {
- * void foo() {
- * this.[start]bar[end](1, 2)
- * }
- * }
- *
- * ---> class X {
- * void foo() {
- * <SelectOnMessageSend:this.bar(1, 2)>
- * }
- * }
- *
- */
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.MessageSend;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ProblemReasons;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class SelectionOnMessageSend extends MessageSend {
-
- /*
- * Cannot answer default abstract match, iterate in superinterfaces of declaring class
- * for a better match (default abstract match came from scope lookups).
- */
- private MethodBinding findNonDefaultAbstractMethod(MethodBinding methodBinding) {
- return methodBinding;
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output) {
-
- output.append("<SelectOnMessageSend:"); //$NON-NLS-1$
- if (receiver!=null && !receiver.isImplicitThis()) receiver.printExpression(0, output).append('.');
- output.append(this.selector).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(")>"); //$NON-NLS-1$
- }
-
- public TypeBinding resolveType(BlockScope scope) {
-
- super.resolveType(scope);
-
- // tolerate some error cases
- if(binding == null ||
- !(binding.isValidBinding() ||
- binding.problemId() == ProblemReasons.NotVisible
- || binding.problemId() == ProblemReasons.InheritedNameHidesEnclosingName
- || binding.problemId() == ProblemReasons.NonStaticReferenceInConstructorInvocation
- || binding.problemId() == ProblemReasons.NonStaticReferenceInStaticContext)) {
- throw new SelectionNodeFound();
- } else {
- if(binding.isDefaultAbstract()) {
- throw new SelectionNodeFound(findNonDefaultAbstractMethod(binding)); // 23594
- } else {
- 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
deleted file mode 100644
index bd5407a1..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnPackageReference.java
+++ /dev/null
@@ -1,46 +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.codeassist.select;
-
-/*
- * Selection node build by the parser in any case it was intending to
- * reduce an package statement containing the assist identifier.
- * e.g.
- *
- * package java.[start]io[end];
- * class X {
- * void foo() {
- * }
- * }
- *
- * ---> <SelectOnPackage:java.io>
- * class X {
- * void foo() {
- * }
- * }
- *
- */
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.ImportReference;
-
-public class SelectionOnPackageReference extends ImportReference {
-public SelectionOnPackageReference(char[][] tokens , long[] positions) {
- super(tokens, positions, true);
-}
-public StringBuffer print(int tab, StringBuffer output, boolean withOnDemand) {
- printIndent(tab, output).append("<SelectOnPackage:"); //$NON-NLS-1$
- for (int i = 0; i < tokens.length; i++) {
- if (i > 0) output.append('.');
- output.append(tokens[i]);
- }
- return output.append('>');
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnQualifiedAllocationExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnQualifiedAllocationExpression.java
deleted file mode 100644
index e063dbb1..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnQualifiedAllocationExpression.java
+++ /dev/null
@@ -1,79 +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.codeassist.select;
-
-/*
- * Selection node build by the parser in any case it was intending to
- * reduce an allocation expression containing the cursor.
- * If the allocation expression is not qualified, the enclosingInstance field
- * is null.
- * e.g.
- *
- * class X {
- * void foo() {
- * new [start]Bar[end](1, 2)
- * }
- * }
- *
- * ---> class X {
- * void foo() {
- * <SelectOnAllocationExpression:new Bar(1, 2)>
- * }
- * }
- *
- */
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.ConstructorDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedAllocationExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ProblemReasons;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class SelectionOnQualifiedAllocationExpression extends QualifiedAllocationExpression {
-
- public SelectionOnQualifiedAllocationExpression() {
- // constructor without argument
- }
-
- public SelectionOnQualifiedAllocationExpression(TypeDeclaration anonymous) {
- super(anonymous);
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output) {
- if (this.enclosingInstance == null)
- output.append("<SelectOnAllocationExpression:"); //$NON-NLS-1$
- else
- output.append("<SelectOnQualifiedAllocationExpression:"); //$NON-NLS-1$
-
- return super.printExpression(indent, output).append('>');
- }
-
- public TypeBinding resolveType(BlockScope scope) {
- super.resolveType(scope);
-
- // tolerate some error cases
- if (binding == null ||
- !(binding.isValidBinding() ||
- binding.problemId() == ProblemReasons.NotVisible))
- throw new SelectionNodeFound();
- if (anonymousType == null)
- throw new SelectionNodeFound(binding);
-
- // if selecting a type for an anonymous type creation, we have to
- // find its target super constructor (if extending a class) or its target
- // super interface (if extending an interface)
- // find the constructor binding inside the super constructor call
- ConstructorDeclaration constructor = (ConstructorDeclaration) anonymousType.declarationOf(binding.original());
- throw new SelectionNodeFound(constructor.constructorCall.binding);
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnQualifiedNameReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnQualifiedNameReference.java
deleted file mode 100644
index 9c013632..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnQualifiedNameReference.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.select;
-
-/*
- * Selection node build by the parser in any case it was intending to
- * reduce a qualified name reference containing the assist identifier.
- * e.g.
- *
- * class X {
- * Y y;
- * void foo() {
- * y.fred.[start]ba[end]
- * }
- * }
- *
- * ---> class X {
- * Y y;
- * void foo() {
- * <SelectOnName:y.fred.ba>
- * }
- * }
- *
- */
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedNameReference;
-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.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.TypeBinding;
-
-public class SelectionOnQualifiedNameReference extends QualifiedNameReference {
-
-public SelectionOnQualifiedNameReference(char[][] previousIdentifiers, char[] selectionIdentifier, long[] positions) {
- super(
- CharOperation.arrayConcat(previousIdentifiers, selectionIdentifier),
- positions,
- (int) (positions[0] >>> 32),
- (int) positions[positions.length - 1]);
-}
-public StringBuffer printExpression(int indent, StringBuffer output) {
-
- output.append("<SelectOnName:"); //$NON-NLS-1$
- for (int i = 0, length = tokens.length; i < length; i++) {
- if (i > 0) output.append('.');
- output.append(tokens[i]);
- }
- return output.append('>');
-}
-public TypeBinding resolveType(BlockScope scope) {
- // it can be a package, type, member type, local variable or field
- binding = scope.getBinding(tokens, this);
- if (!binding.isValidBinding()) {
- if (binding instanceof ProblemFieldBinding) {
- // tolerate some error cases
- if (binding.problemId() == ProblemReasons.NotVisible
- || binding.problemId() == ProblemReasons.InheritedNameHidesEnclosingName
- || binding.problemId() == ProblemReasons.NonStaticReferenceInConstructorInvocation
- || binding.problemId() == ProblemReasons.NonStaticReferenceInStaticContext) {
- throw new SelectionNodeFound(binding);
- }
- scope.problemReporter().invalidField(this, (FieldBinding) binding);
- } else if (binding instanceof ProblemReferenceBinding) {
- // tolerate some error cases
- if (binding.problemId() == ProblemReasons.NotVisible){
- throw new SelectionNodeFound(binding);
- }
- scope.problemReporter().invalidType(this, (TypeBinding) binding);
- } else {
- scope.problemReporter().unresolvableReference(this, binding);
- }
- throw new SelectionNodeFound();
- }
- throw new SelectionNodeFound(binding);
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnQualifiedType.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnQualifiedType.java
deleted file mode 100644
index 6e2cc3b5..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnQualifiedType.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.select;
-
-public class SelectionOnQualifiedType extends SelectionOnQualifiedNameReference {
-
- public SelectionOnQualifiedType(char[][] previousIdentifiers, char[] selectionIdentifier, long[] positions) {
- super(previousIdentifiers, selectionIdentifier, positions);
- }
- public StringBuffer printExpression(int indent, StringBuffer output) {
-
- output.append("<SelectOnType:"); //$NON-NLS-1$
- for (int i = 0, length = tokens.length; i < length; i++) {
- if (i > 0) output.append('.');
- output.append(tokens[i]);
- }
- return output.append('>');
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnQualifiedTypeReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnQualifiedTypeReference.java
deleted file mode 100644
index 89bf5d92..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnQualifiedTypeReference.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.select;
-
-/*
- * Selection node build by the parser in any case it was intending to
- * reduce a type reference containing the completion identifier as part
- * of a qualified name.
- * e.g.
- *
- * class X extends java.lang.[start]Object[end]
- *
- * ---> class X extends <SelectOnType:java.lang.Object>
- *
- */
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Binding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ProblemReasons;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Scope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class SelectionOnQualifiedTypeReference extends QualifiedTypeReference {
-public SelectionOnQualifiedTypeReference(char[][] previousIdentifiers, char[] selectionIdentifier, long[] positions) {
- super(
- CharOperation.arrayConcat(previousIdentifiers, selectionIdentifier),
- positions);
-}
-public void aboutToResolve(Scope scope) {
- getTypeBinding(scope.parent); // step up from the ClassScope
-}
-protected TypeBinding getTypeBinding(Scope scope) {
- // it can be a package, type or member type
- Binding binding = scope.getTypeOrPackage(tokens);
- if (!binding.isValidBinding()) {
- // tolerate some error cases
- if (binding.problemId() == ProblemReasons.NotVisible){
- throw new SelectionNodeFound(binding);
- }
- scope.problemReporter().invalidType(this, (TypeBinding) binding);
- throw new SelectionNodeFound();
- }
-
- throw new SelectionNodeFound(binding);
-}
-public StringBuffer printExpression(int indent, StringBuffer output) {
-
- output.append("<SelectOnType:"); //$NON-NLS-1$
- for (int i = 0, length = tokens.length; i < length; i++) {
- if (i > 0) output.append('.');
- output.append(tokens[i]);
- }
- return output.append('>');
-}
-}
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
deleted file mode 100644
index de19843e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnSingleNameReference.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*******************************************************************************
- * 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.codeassist.select;
-
-/*
- * Selection node build by the parser in any case it was intending to
- * reduce a single name reference containing the assist identifier.
- * e.g.
- *
- * class X {
- * void foo() {
- * [start]ba[end]
- * }
- * }
- *
- * ---> class X {
- * void foo() {
- * <SelectOnName:ba>
- * }
- * }
- *
- */
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode;
-import org.eclipse.wst.jsdt.internal.compiler.ast.SingleNameReference;
-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.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.TypeBinding;
-
-public class SelectionOnSingleNameReference extends SingleNameReference {
-public SelectionOnSingleNameReference(char[] source, long pos) {
- super(source, pos);
-}
-public TypeBinding resolveType(BlockScope scope) {
- if (this.actualReceiverType != null) {
- this.binding = scope.getField(this.actualReceiverType, token, this);
- if (this.binding != null && this.binding.isValidBinding()) {
- throw new SelectionNodeFound(binding);
- }
- }
- // it can be a package, type, member type, local variable or field
- binding = scope.getBinding(token, Binding.VARIABLE | Binding.METHOD, this, true /*resolve*/);
- if (!binding.isValidBinding()) {
- if (binding instanceof ProblemFieldBinding) {
- // tolerate some error cases
- if (binding.problemId() == ProblemReasons.NotVisible
- || binding.problemId() == ProblemReasons.InheritedNameHidesEnclosingName
- || binding.problemId() == ProblemReasons.NonStaticReferenceInConstructorInvocation
- || binding.problemId() == ProblemReasons.NonStaticReferenceInStaticContext){
- throw new SelectionNodeFound(binding);
- }
- scope.problemReporter().invalidField(this, (FieldBinding) binding);
- } else if (binding instanceof ProblemReferenceBinding) {
- // tolerate some error cases
- if (binding.problemId() == ProblemReasons.NotVisible){
- throw new SelectionNodeFound(binding);
- }
- scope.problemReporter().invalidType(this, (TypeBinding) binding);
- } else {
- scope.problemReporter().unresolvableReference(this, binding);
- }
- throw new SelectionNodeFound();
- }
-
- throw new SelectionNodeFound(binding);
-}
-
-public TypeBinding resolveForAllocation(BlockScope scope, ASTNode location) {
- TypeBinding typeBinding=null;
- this.binding=
- scope.getBinding(this.token, (Binding.TYPE|Binding.METHOD | bits) & RestrictiveFlagMASK, this, true /*resolve*/);
- if (binding instanceof TypeBinding)
- typeBinding=(TypeBinding)binding;
- else if (binding instanceof MethodBinding)
- typeBinding=((MethodBinding)binding).returnType;
- else
- if (typeBinding==null || binding==null)
- throw new SelectionNodeFound();
- else if (!binding.isValidBinding()){
- switch (binding.problemId() ) {
- case ProblemReasons.NotVisible:
- case ProblemReasons.InheritedNameHidesEnclosingName:
- case ProblemReasons.NonStaticReferenceInConstructorInvocation:
- case ProblemReasons.NonStaticReferenceInStaticContext:
- throw new SelectionNodeFound(typeBinding);
-
- default:
- throw new SelectionNodeFound();
- }
-// !binding.isValidBinding())
- }
-
- throw new SelectionNodeFound(typeBinding);
-}
-
-public StringBuffer printExpression(int indent, StringBuffer output) {
- output.append("<SelectOnName:"); //$NON-NLS-1$
- return super.printExpression(0, output).append('>');
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnSingleType.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnSingleType.java
deleted file mode 100644
index 7b619550..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnSingleType.java
+++ /dev/null
@@ -1,20 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.select;
-
-public class SelectionOnSingleType extends SelectionOnSingleNameReference {
-
- public SelectionOnSingleType(char[] source, long pos) {
- super(source, pos);
- // TODO Auto-generated constructor stub
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnSingleTypeReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnSingleTypeReference.java
deleted file mode 100644
index ed6e7cb3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnSingleTypeReference.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.select;
-
-/*
- * Selection node build by the parser in any case it was intending to
- * reduce a type reference containing the selection identifier as a single
- * name reference.
- * e.g.
- *
- * class X extends [start]Object[end]
- *
- * ---> class X extends <SelectOnType:Object>
- *
- */
-import org.eclipse.wst.jsdt.internal.compiler.ast.SingleTypeReference;
-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.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;
-
-public class SelectionOnSingleTypeReference extends SingleTypeReference {
-public SelectionOnSingleTypeReference(char[] source, long pos) {
- super(source, pos);
-}
-public void aboutToResolve(Scope scope) {
- getTypeBinding(scope.parent); // step up from the ClassScope
-}
-protected TypeBinding getTypeBinding(Scope scope) {
- // it can be a package, type or member type
- Binding binding = scope.getTypeOrPackage(new char[][] {token});
- if (!binding.isValidBinding()) {
- scope.problemReporter().invalidType(this, (TypeBinding) binding);
- throw new SelectionNodeFound();
- }
- throw new SelectionNodeFound(binding);
-}
-public StringBuffer printExpression(int indent, StringBuffer output) {
-
- return output.append("<SelectOnType:").append(token).append('>');//$NON-NLS-1$
-}
-public TypeBinding resolveTypeEnclosing(BlockScope scope, ReferenceBinding enclosingType) {
- super.resolveTypeEnclosing(scope, enclosingType);
-
- // tolerate some error cases
- if (this.resolvedType == null ||
- !(this.resolvedType.isValidBinding() ||
- this.resolvedType.problemId() == ProblemReasons.NotVisible))
- throw new SelectionNodeFound();
- else
- throw new SelectionNodeFound(this.resolvedType);
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnSuperReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnSuperReference.java
deleted file mode 100644
index 6d007a93..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnSuperReference.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.select;
-
-/*
- * Selection node build by the parser in any case it was intending to
- * reduce a super reference containing the assist identifier.
- * e.g.
- *
- * class X extends Z {
- * class Y {
- * void foo() {
- * [start]super[end].bar();
- * }
- * }
- * }
- *
- * ---> class X {
- * class Y {
- * void foo() {
- * <SelectOnQualifiedSuper:super>
- * }
- * }
- * }
- *
- */
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.SuperReference;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class SelectionOnSuperReference extends SuperReference {
-
-public SelectionOnSuperReference(int pos, int sourceEnd) {
- super(pos, sourceEnd);
-}
-public StringBuffer printExpression(int indent, StringBuffer output){
-
- output.append("<SelectOnSuper:"); //$NON-NLS-1$
- return super.printExpression(0, output).append('>');
-}
-public TypeBinding resolveType(BlockScope scope) {
- TypeBinding binding = super.resolveType(scope);
-
- if (binding == null || !binding.isValidBinding())
- throw new SelectionNodeFound();
- else
- throw new SelectionNodeFound(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
deleted file mode 100644
index 94ed1e94..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionParser.java
+++ /dev/null
@@ -1,690 +0,0 @@
-/*******************************************************************************
- * 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.codeassist.select;
-
-/*
- * Parser able to build specific completion parse nodes, given a cursorLocation.
- *
- * Cursor location denotes the position of the last character behind which completion
- * got requested:
- * -1 means completion at the very beginning of the source
- * 0 means completion behind the first character
- * n means completion behind the n-th character
- */
-
-
-import org.eclipse.wst.jsdt.internal.codeassist.impl.AssistParser;
-import org.eclipse.wst.jsdt.internal.compiler.CompilationResult;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode;
-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.CaseStatement;
-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.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.NameReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedAllocationExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Statement;
-import org.eclipse.wst.jsdt.internal.compiler.ast.SwitchStatement;
-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.env.ICompilationUnit;
-import org.eclipse.wst.jsdt.internal.compiler.parser.JavadocParser;
-import org.eclipse.wst.jsdt.internal.compiler.parser.RecoveredType;
-import org.eclipse.wst.jsdt.internal.compiler.problem.ProblemReporter;
-import org.eclipse.wst.jsdt.internal.compiler.util.Util;
-
-public class SelectionParser extends AssistParser {
- // OWNER
- protected static final int SELECTION_PARSER = 1024;
- protected static final int SELECTION_OR_ASSIST_PARSER = ASSIST_PARSER + SELECTION_PARSER;
-
- // KIND : all values known by SelectionParser are between 1025 and 1549
- protected static final int K_BETWEEN_CASE_AND_COLON = SELECTION_PARSER + 1; // whether we are inside a block
-
- public ASTNode assistNodeParent; // the parent node of assist node
-
- /* public fields */
-
- public int selectionStart, selectionEnd;
-
- public static final char[] THIS = "this".toCharArray(); //$NON-NLS-1$
-
-public SelectionParser(ProblemReporter problemReporter) {
- super(problemReporter);
- this.javadocParser.checkDocComment = true;
-}
-public char[] assistIdentifier(){
- return ((SelectionScanner)scanner).selectionIdentifier;
-}
-protected void attachOrphanCompletionNode(){
- if (isOrphanCompletionNode){
- ASTNode orphan = this.assistNode;
- isOrphanCompletionNode = false;
-
-
- /* if in context of a type, then persists the identifier into a fake field return type */
- if (currentElement instanceof RecoveredType){
- RecoveredType recoveredType = (RecoveredType)currentElement;
- /* filter out cases where scanner is still inside type header */
- if (recoveredType.foundOpeningBrace) {
- /* generate a pseudo field with a completion on type reference */
- if (orphan instanceof TypeReference){
- currentElement = currentElement.add(new SelectionOnFieldType((TypeReference)orphan), 0);
- return;
- }
- }
- }
-
- if (orphan instanceof Expression) {
- buildMoreCompletionContext((Expression)orphan);
- } else {
- Statement statement = (Statement) orphan;
- currentElement = currentElement.add(statement, 0);
- }
- currentToken = 0; // given we are not on an eof, we do not want side effects caused by looked-ahead token
- }
-}
-private void buildMoreCompletionContext(Expression expression) {
- ASTNode parentNode = null;
-
- int kind = topKnownElementKind(SELECTION_OR_ASSIST_PARSER);
- if(kind != 0) {
-// int info = topKnownElementInfo(SELECTION_OR_ASSIST_PARSER);
- switch (kind) {
- case K_BETWEEN_CASE_AND_COLON :
- if(this.expressionPtr > 0) {
- SwitchStatement switchStatement = new SwitchStatement();
- switchStatement.expression = this.expressionStack[this.expressionPtr - 1];
- if(this.astLengthPtr > -1 && this.astPtr > -1) {
- int length = this.astLengthStack[this.astLengthPtr];
- int newAstPtr = this.astPtr - length;
- ASTNode firstNode = this.astStack[newAstPtr + 1];
- if(length != 0 && firstNode.sourceStart > switchStatement.expression.sourceEnd) {
- switchStatement.statements = new Statement[length + 1];
- System.arraycopy(
- this.astStack,
- newAstPtr + 1,
- switchStatement.statements,
- 0,
- length);
- }
- }
- CaseStatement caseStatement = new CaseStatement(expression, expression.sourceStart, expression.sourceEnd);
- if(switchStatement.statements == null) {
- switchStatement.statements = new Statement[]{caseStatement};
- } else {
- switchStatement.statements[switchStatement.statements.length - 1] = caseStatement;
- }
- parentNode = switchStatement;
- this.assistNodeParent = parentNode;
- }
- break;
- }
- }
- if(parentNode != null) {
- currentElement = currentElement.add((Statement)parentNode, 0);
- } else {
- currentElement = currentElement.add((Statement)wrapWithExplicitConstructorCallIfNeeded(expression), 0);
- if(lastCheckPoint < expression.sourceEnd) {
- lastCheckPoint = expression.sourceEnd + 1;
- }
- }
-}
-private boolean checkRecoveredType() {
- if (currentElement instanceof RecoveredType){
- /* check if current awaiting identifier is the completion identifier */
- if (this.indexOfAssistIdentifier() < 0) return false;
-
- if ((lastErrorEndPosition >= selectionStart)
- && (lastErrorEndPosition <= selectionEnd+1)){
- return false;
- }
- RecoveredType recoveredType = (RecoveredType)currentElement;
- /* filter out cases where scanner is still inside type header */
- if (recoveredType.foundOpeningBrace) {
- this.assistNode = this.getTypeReference(0);
- this.lastCheckPoint = this.assistNode.sourceEnd + 1;
- this.isOrphanCompletionNode = true;
- return true;
- }
- }
- return false;
-}
-protected void classInstanceCreation(boolean hasClassBody, 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.....
-
-
-// if ((astLengthStack[astLengthPtr] == 1)
-// && (astStack[astPtr] == null)) {
-
-
-// int index;
- int argsLength= isShort ? 0 : expressionLengthStack[expressionLengthPtr];
- if (!(this.expressionStack[this.expressionPtr-argsLength] instanceof SelectionOnSingleNameReference))
- {
-//
-//
-// if ((index = this.indexOfAssistIdentifier()) < 0) {
-// super.classInstanceCreation(hasClassBody, isShort);
-// return;
-// } else if(this.identifierLengthPtr > -1 &&
-// (this.identifierLengthStack[this.identifierLengthPtr] - 1) != index) {
- super.classInstanceCreation(hasClassBody, isShort);
- return;
- }
- QualifiedAllocationExpression alloc;
-// astPtr--;
-// astLengthPtr--;
- alloc = new SelectionOnQualifiedAllocationExpression();
- alloc.sourceEnd = endPosition; //the position has been stored explicitly
-
- if (!isShort)
- {
- int length;
- if ((length = expressionLengthStack[expressionLengthPtr--]) != 0) {
- expressionPtr -= length;
- System.arraycopy(
- expressionStack,
- expressionPtr + 1,
- alloc.arguments = new Expression[length],
- 0,
- length);
- }
- }
- else
- alloc.arguments=new Expression[0];
- // trick to avoid creating a selection on type reference
- char [] oldIdent = this.assistIdentifier();
- this.setAssistIdentifier(null);
-// alloc.type = getTypeReference(0);
- alloc.member = this.expressionStack[this.expressionPtr--];
- this.expressionLengthPtr--;
-
- this.setAssistIdentifier(oldIdent);
-
- //the default constructor with the correct number of argument
- //will be created and added by the TC (see createsInternalConstructorWithBinding)
- alloc.sourceStart = intStack[intPtr--];
- pushOnExpressionStack(alloc);
-
- this.assistNode = alloc;
- this.lastCheckPoint = alloc.sourceEnd + 1;
- if (!diet){
- this.restartRecovery = AssistParser.STOP_AT_CURSOR; // force to restart in recovery mode
- this.lastIgnoredToken = -1;
- }
- this.isOrphanCompletionNode = true;
-// } else {
-// super.classInstanceCreation(hasClassBody, isShort);
-// }
-}
-protected void consumeEnterVariable() {
- // EnterVariable ::= $empty
- // do nothing by default
-
- super.consumeEnterVariable();
-
-// AbstractVariableDeclaration variable = (AbstractVariableDeclaration) astStack[astPtr];
-// if (variable.type == assistNode){
-// if (!diet){
-// this.restartRecovery = true; // force to restart in recovery mode
-// this.lastIgnoredToken = -1;
-// }
-// isOrphanCompletionNode = false; // already attached inside variable decl
-// }
-}
-
-protected void consumeExitVariableWithInitialization() {
- super.consumeExitVariableWithInitialization();
-
- // does not keep the initialization if selection is not inside
- AbstractVariableDeclaration variable = (AbstractVariableDeclaration) astStack[astPtr];
- int start = variable.initialization.sourceStart;
- int end = variable.initialization.sourceEnd;
- if ((selectionStart < start) && (selectionEnd < start) ||
- (selectionStart > end) && (selectionEnd > end)) {
- if (STOP_AT_CURSOR)
- variable.initialization = null;
- }
-
-}
-protected void consumeCallExpressionWithSimpleName() {
- if (this.indexOfAssistIdentifier() < 0) {
- super.consumeCallExpressionWithSimpleName();
- return;
- }
- FieldReference fieldReference =
- new SelectionOnFieldReference(
- identifierStack[identifierPtr],
- identifierPositionStack[identifierPtr--]);
- identifierLengthPtr--;
- if ((fieldReference.receiver = expressionStack[expressionPtr]).isThis()) { //fieldReferenceerence begins at the this
- fieldReference.sourceStart = fieldReference.receiver.sourceStart;
- }
- expressionStack[expressionPtr] = fieldReference;
- assistNode = fieldReference;
- this.lastCheckPoint = fieldReference.sourceEnd + 1;
- if (!diet){
- this.restartRecovery = AssistParser.STOP_AT_CURSOR; // force to restart in recovery mode
- this.lastIgnoredToken = -1;
- }
- this.isOrphanCompletionNode = true;
-
-}
-protected void consumeMemberExpressionWithSimpleName() {
- if (this.indexOfAssistIdentifier() < 0) {
- super.consumeMemberExpressionWithSimpleName();
- return;
- }
- FieldReference fieldReference =
- new SelectionOnFieldReference(
- identifierStack[identifierPtr],
- identifierPositionStack[identifierPtr--]);
- identifierLengthPtr--;
- if ((fieldReference.receiver = expressionStack[expressionPtr]).isThis()) { //fieldReferenceerence begins at the this
- fieldReference.sourceStart = fieldReference.receiver.sourceStart;
- }
- expressionStack[expressionPtr] = fieldReference;
- assistNode = fieldReference;
- this.lastCheckPoint = fieldReference.sourceEnd + 1;
- if (!diet){
- this.restartRecovery = AssistParser.STOP_AT_CURSOR; // force to restart in recovery mode
- this.lastIgnoredToken = -1;
- }
- this.isOrphanCompletionNode = true;
-
-}
-protected void consumeFormalParameter(boolean isVarArgs) {
- if (this.indexOfAssistIdentifier() < 0) {
- super.consumeFormalParameter(isVarArgs);
-// if((!diet || dietInt != 0) && astPtr > -1) {
-// Argument argument = (Argument) astStack[astPtr];
-// if(argument.type == assistNode) {
-// isOrphanCompletionNode = true;
-// this.restartRecovery = true; // force to restart in recovery mode
-// this.lastIgnoredToken = -1;
-// }
-// }
- } else {
- identifierLengthPtr--;
- char[] identifierName = identifierStack[identifierPtr];
- long namePositions = identifierPositionStack[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 = intStack[intPtr--];
-// intPtr--;
- int modifierPositions=(int) (namePositions >>> 32);
- Argument arg =
- new SelectionOnArgumentName(
- identifierName,
- namePositions,
- null,
- ClassFileConstants.AccDefault);
-// intStack[intPtr + 1] & ~ClassFileConstants.AccDeprecated); // modifiers
- arg.declarationSourceStart = modifierPositions;
- pushOnAstStack(arg);
-
- assistNode = arg;
- this.lastCheckPoint = (int) namePositions;
- isOrphanCompletionNode = true;
-
- if (!diet){
- this.restartRecovery = AssistParser.STOP_AT_CURSOR; // force to restart in recovery mode
- this.lastIgnoredToken = -1;
- }
-
- /* if incomplete method header, listLength counter will not have been reset,
- indicating that some arguments are available on the stack */
- listLength++;
- }
-}
-protected void consumeLocalVariableDeclarationStatement() {
- super.consumeLocalVariableDeclarationStatement();
-
- // force to restart in recovery mode if the declaration contains the selection
- if (!this.diet) {
- LocalDeclaration localDeclaration = (LocalDeclaration) this.astStack[this.astPtr];
- if ((this.selectionStart >= localDeclaration.sourceStart)
- && (this.selectionEnd <= localDeclaration.sourceEnd)) {
- this.restartRecovery = AssistParser.STOP_AT_CURSOR;
- this.lastIgnoredToken = -1;
- }
- }
-}
-
-// Nothing here applicable to javascript
-//protected void consumeMethodInvocationPrimary() {
-// //optimize the push/pop
-// //FunctionInvocation ::= Primary '.' 'Identifier' '(' ArgumentListopt ')'
-//
-// char[] selector = identifierStack[identifierPtr];
-// int accessMode;
-// if(selector == this.assistIdentifier()) {
-// if(CharOperation.equals(selector, SUPER)) {
-// accessMode = ExplicitConstructorCall.Super;
-// } else if(CharOperation.equals(selector, THIS)) {
-// accessMode = ExplicitConstructorCall.This;
-// } else {
-// super.consumeMethodInvocationPrimary();
-// return;
-// }
-// } else {
-// super.consumeMethodInvocationPrimary();
-// return;
-// }
-//
-// final ExplicitConstructorCall constructorCall = new SelectionOnExplicitConstructorCall(accessMode);
-// constructorCall.sourceEnd = rParenPos;
-// int length;
-// if ((length = expressionLengthStack[expressionLengthPtr--]) != 0) {
-// expressionPtr -= length;
-// System.arraycopy(expressionStack, expressionPtr + 1, constructorCall.arguments = new Expression[length], 0, length);
-// }
-// constructorCall.qualification = expressionStack[expressionPtr--];
-// constructorCall.sourceStart = constructorCall.qualification.sourceStart;
-//
-// if (!diet){
-// pushOnAstStack(constructorCall);
-// this.restartRecovery = AssistParser.STOP_AT_CURSOR; // force to restart in recovery mode
-// this.lastIgnoredToken = -1;
-// } else {
-// pushOnExpressionStack(new Expression(){
-// public TypeBinding resolveType(BlockScope scope) {
-// constructorCall.resolve(scope);
-// return null;
-// }
-// public StringBuffer printExpression(int indent, StringBuffer output) {
-// return output;
-// }
-// });
-// }
-//
-// this.assistNode = constructorCall;
-// this.lastCheckPoint = constructorCall.sourceEnd + 1;
-// this.isOrphanCompletionNode = true;
-//}
-protected void consumeToken(int token) {
- super.consumeToken(token);
-
- // if in a method or if in a field initializer
- if (isInsideMethod() || isInsideFieldInitialization()) {
- switch (token) {
- case TokenNamecase :
- pushOnElementStack(K_BETWEEN_CASE_AND_COLON);
- break;
- case TokenNameCOLON:
- if(topKnownElementKind(SELECTION_OR_ASSIST_PARSER) == K_BETWEEN_CASE_AND_COLON) {
- popElement(K_BETWEEN_CASE_AND_COLON);
- }
- break;
- }
- }
-}
-public ImportReference createAssistImportReference(char[][] tokens, long[] positions){
- return new SelectionOnImportReference(tokens, positions);
-}
-protected JavadocParser createJavadocParser() {
- return new SelectionJavadocParser(this);
-}
-protected LocalDeclaration createLocalDeclaration(char[] assistName,int sourceStart,int sourceEnd) {
- if (this.indexOfAssistIdentifier() < 0) {
- return super.createLocalDeclaration(assistName, sourceStart, sourceEnd);
- } else {
- SelectionOnLocalName local = new SelectionOnLocalName(assistName, sourceStart, sourceEnd);
- this.assistNode = local;
- this.lastCheckPoint = sourceEnd + 1;
- return local;
- }
-}
-public NameReference createQualifiedAssistNameReference(char[][] previousIdentifiers, char[] assistName, long[] positions){
- return new SelectionOnQualifiedNameReference(
- previousIdentifiers,
- assistName,
- positions);
-}
-public TypeReference createQualifiedAssistTypeReference(char[][] previousIdentifiers, char[] assistName, long[] positions){
- return new SelectionOnQualifiedTypeReference(
- previousIdentifiers,
- assistName,
- positions);
-}
-public NameReference createSingleAssistNameReference(char[] assistName, long position) {
- return new SelectionOnSingleNameReference(assistName, position);
-}
-public TypeReference createSingleAssistTypeReference(char[] assistName, long position) {
- return new SelectionOnSingleTypeReference(assistName, position);
-}
-public CompilationUnitDeclaration dietParse(ICompilationUnit sourceUnit, CompilationResult compilationResult, int start, int end) {
-
- this.selectionStart = start;
- this.selectionEnd = end;
- SelectionScanner selectionScanner = (SelectionScanner)this.scanner;
- selectionScanner.selectionIdentifier = null;
- selectionScanner.selectionStart = start;
- selectionScanner.selectionEnd = end;
- return this.dietParse(sourceUnit, compilationResult);
-}
-protected NameReference getUnspecifiedReference() {
- /* build a (unspecified) NameReference which may be qualified*/
-
- int completionIndex;
-
- /* no need to take action if not inside completed identifiers */
- if ((completionIndex = indexOfAssistIdentifier()) < 0) {
- return super.getUnspecifiedReference();
- }
-
- int length = identifierLengthStack[identifierLengthPtr];
- NameReference nameReference;
- /* retrieve identifiers subset and whole positions, the completion node positions
- should include the entire replaced source. */
- char[][] subset = identifierSubSet(completionIndex);
- identifierLengthPtr--;
- identifierPtr -= length;
- long[] positions = new long[length];
- System.arraycopy(
- identifierPositionStack,
- identifierPtr + 1,
- positions,
- 0,
- length);
- /* build specific completion on name reference */
- if (completionIndex == 0) {
- /* completion inside first identifier */
- nameReference = this.createSingleAssistNameReference(assistIdentifier(), positions[0]);
- } else {
- /* completion inside subsequent identifier */
- nameReference = this.createQualifiedAssistNameReference(subset, assistIdentifier(), positions);
- }
- assistNode = nameReference;
- this.lastCheckPoint = nameReference.sourceEnd + 1;
- if (!diet){
- this.restartRecovery = true; // force to restart in recovery mode
- this.lastIgnoredToken = -1;
- }
- this.isOrphanCompletionNode = true;
- return nameReference;
-}
-/*
- * Copy of code from superclass with the following change:
- * In the case of qualified name reference if the cursor location is on the
- * qualified name reference, then create a CompletionOnQualifiedNameReference
- * instead.
- */
-protected NameReference getUnspecifiedReferenceOptimized() {
-
- int index = indexOfAssistIdentifier();
- NameReference reference = super.getUnspecifiedReferenceOptimized();
-
- if (index >= 0){
- if (!diet){
- this.restartRecovery = AssistParser.STOP_AT_CURSOR; // force to restart in recovery mode
- this.lastIgnoredToken = -1;
- }
- this.isOrphanCompletionNode = true;
- }
- return reference;
-}
-public void initializeScanner(){
- this.scanner = new SelectionScanner(this.options.sourceLevel);
-}
-protected MessageSend newMessageSend() {
- // '(' ArgumentListopt ')'
- // the arguments are on the expression stack
-
-
-
- int numArgs=expressionLengthStack[expressionLengthPtr];
- Expression receiver = expressionStack[expressionPtr-numArgs];
-// char[] selector = identifierStack[identifierPtr];
-// if (selector != this.assistIdentifier()){
-
- if (!(receiver instanceof SelectionOnSingleNameReference || receiver instanceof SelectionOnFieldReference))
- {
- return super.newMessageSend();
- }
- MessageSend messageSend = new SelectionOnMessageSend();
- int length;
- if ((length = expressionLengthStack[expressionLengthPtr--]) != 0) {
- expressionPtr -= length;
- System.arraycopy(
- expressionStack,
- expressionPtr + 1,
- messageSend.arguments = new Expression[length],
- 0,
- length);
- }
- assistNode = messageSend;
- if (!diet){
- this.restartRecovery = AssistParser.STOP_AT_CURSOR; // force to restart in recovery mode
- this.lastIgnoredToken = -1;
- }
-
- this.isOrphanCompletionNode = true;
- return messageSend;
-}
-public CompilationUnitDeclaration parse(ICompilationUnit sourceUnit, CompilationResult compilationResult, int start, int end) {
-
- if (end == -1) return super.parse(sourceUnit, compilationResult, start, end);
-
- this.selectionStart = start;
- this.selectionEnd = end;
- SelectionScanner selectionScanner = (SelectionScanner)this.scanner;
- selectionScanner.selectionIdentifier = null;
- selectionScanner.selectionStart = start;
- selectionScanner.selectionEnd = end;
- return super.parse(sourceUnit, compilationResult, -1, -1/*parse without reseting the scanner*/);
-}
-/*
- * 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 reached assist node inside method body, but still inside nested type,
- should continue in diet mode until the end of the method body */
- if (this.assistNode != null
- && !(referenceContext instanceof CompilationUnitDeclaration)){
- currentElement.preserveEnclosingBlocks();
- if (currentElement.enclosingType() == null) {
- if(!(currentElement instanceof RecoveredType)) {
- this.resetStacks();
- return false;
- }
-
- RecoveredType recoveredType = (RecoveredType)currentElement;
- if(recoveredType.typeDeclaration != null && recoveredType.typeDeclaration.allocation == this.assistNode){
- this.resetStacks();
- return false;
- }
- }
- }
- return super.resumeAfterRecovery();
-}
-
-public void selectionIdentifierCheck(){
- if (checkRecoveredType()) return;
-}
-public void setAssistIdentifier(char[] assistIdent){
- ((SelectionScanner)scanner).selectionIdentifier = assistIdent;
-}
-/*
- * Update recovery state based on current parser/scanner state
- */
-protected void updateRecoveryState() {
-
- /* expose parser state to recovery state */
- currentElement.updateFromParserState();
-
- /* may be able to retrieve completionNode as an orphan, and then attach it */
- this.selectionIdentifierCheck();
- this.attachOrphanCompletionNode();
-
- // if an assist node has been found and a recovered element exists,
- // mark enclosing blocks as to be preserved
- if (this.assistNode != null && this.currentElement != null) {
- currentElement.preserveEnclosingBlocks();
- }
-
- /* check and update recovered state based on current token,
- this action is also performed when shifting token after recovery
- got activated once.
- */
- this.recoveryTokenCheck();
-}
-
-public String toString() {
- String s = Util.EMPTY_STRING;
- s = s + "elementKindStack : int[] = {"; //$NON-NLS-1$
- for (int i = 0; i <= elementPtr; i++) {
- s = s + String.valueOf(elementKindStack[i]) + ","; //$NON-NLS-1$
- }
- s = s + "}\n"; //$NON-NLS-1$
- s = s + "elementInfoStack : int[] = {"; //$NON-NLS-1$
- for (int i = 0; i <= elementPtr; i++) {
- s = s + String.valueOf(elementInfoStack[i]) + ","; //$NON-NLS-1$
- }
- s = s + "}\n"; //$NON-NLS-1$
- return s + super.toString();
-}
-public int getCursorLocation() {
- return this.selectionStart;
-}
-
-public void createAssistTypeForAllocation(AllocationExpression expression) {
-
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionScanner.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionScanner.java
deleted file mode 100644
index a11b391b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionScanner.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.codeassist.select;
-
-/*
- * Scanner aware of a selection range. If finding an identifier which source range is exactly
- * the same, then will record it so that the parser can make use of it.
- *
- * Source positions are zero-based and inclusive.
- */
-import org.eclipse.wst.jsdt.internal.compiler.parser.Scanner;
-
-public class SelectionScanner extends Scanner {
-
- public char[] selectionIdentifier;
- public int selectionStart, selectionEnd;
-/*
- * Truncate the current identifier if it is containing the cursor location. Since completion is performed
- * on an identifier prefix.
- *
- */
-
-public SelectionScanner(long sourceLevel) {
- super(false /*comment*/, false /*whitespace*/, false /*nls*/, sourceLevel, null /*taskTags*/, null/*taskPriorities*/, true/*taskCaseSensitive*/);
-}
-
-public char[] getCurrentIdentifierSource() {
-
- if (selectionIdentifier == null){
- if (selectionStart == startPosition && selectionEnd == currentPosition-1){
- if (withoutUnicodePtr != 0){ // check unicode scenario
- System.arraycopy(withoutUnicodeBuffer, 1, selectionIdentifier = new char[withoutUnicodePtr], 0, withoutUnicodePtr);
- } else {
- int length = currentPosition - startPosition;
- // no char[] sharing around completionIdentifier, we want it to be unique so as to use identity checks
- System.arraycopy(source, startPosition, (selectionIdentifier = new char[length]), 0, length);
- }
- return selectionIdentifier;
- }
- }
- return super.getCurrentIdentifierSource();
-}
-/*
- * In case we actually read a keyword which corresponds to the selected
- * range, we pretend we read an identifier.
- */
-public int scanIdentifierOrKeyword() {
-
- int id = super.scanIdentifierOrKeyword();
-
- // convert completed keyword into an identifier
- if (id != TokenNameIdentifier
- && startPosition == selectionStart
- && currentPosition == selectionEnd+1){
- return TokenNameIdentifier;
- }
- return id;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ASTVisitor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ASTVisitor.java
deleted file mode 100644
index a4198af6..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ASTVisitor.java
+++ /dev/null
@@ -1,879 +0,0 @@
-/*******************************************************************************
- * 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.compiler;
-
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-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.AND_AND_Expression;
-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.ArrayAllocationExpression;
-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.ClassLiteralAccess;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Clinit;
-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.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.ExtendedStringLiteral;
-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.ForeachStatement;
-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.InstanceOfExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.IntLiteral;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Javadoc;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocAllocationExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocArgumentExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocArrayQualifiedTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocArraySingleTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocFieldReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocImplicitTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocMessageSend;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocQualifiedTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocReturnStatement;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocSingleNameReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocSingleTypeReference;
-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.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.PostfixExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.PrefixExpression;
-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.QualifiedThisReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedTypeReference;
-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.StringLiteral;
-import org.eclipse.wst.jsdt.internal.compiler.ast.StringLiteralConcatenation;
-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.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.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.MethodScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Scope;
-
-/**
- * A visitor for iterating through the parse tree.
- */
-public abstract class ASTVisitor {
- public void acceptProblem(IProblem problem) {
- // do nothing by default
- }
- public void endVisit(
- AllocationExpression allocationExpression,
- BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(AND_AND_Expression and_and_Expression, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(Argument argument, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(Argument argument,ClassScope scope) {
- // do nothing by default
- }
- public void endVisit(
- ArrayAllocationExpression arrayAllocationExpression,
- BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(ArrayInitializer arrayInitializer, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(
- ArrayQualifiedTypeReference arrayQualifiedTypeReference,
- BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(
- ArrayQualifiedTypeReference arrayQualifiedTypeReference,
- ClassScope scope) {
- // do nothing by default
- }
- public void endVisit(ArrayReference arrayReference, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(ArrayTypeReference arrayTypeReference, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(ArrayTypeReference arrayTypeReference, ClassScope scope) {
- // do nothing by default
- }
- public void endVisit(Assignment assignment, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(BinaryExpression binaryExpression, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(Block block, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(BreakStatement breakStatement, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(CaseStatement caseStatement, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(ClassLiteralAccess classLiteral, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(Clinit clinit, ClassScope scope) {
- // do nothing by default
- }
- public void endVisit(
- CompilationUnitDeclaration compilationUnitDeclaration,
- CompilationUnitScope scope) {
- // do nothing by default
- }
- public void endVisit(CompoundAssignment compoundAssignment, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(
- ConditionalExpression conditionalExpression,
- BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(
- ConstructorDeclaration constructorDeclaration,
- ClassScope scope) {
- // do nothing by default
- }
- public void endVisit(ContinueStatement continueStatement, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(DoStatement doStatement, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(DoubleLiteral doubleLiteral, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(EmptyStatement emptyStatement, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(EqualExpression equalExpression, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(
- ExplicitConstructorCall explicitConstructor,
- BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(
- ExtendedStringLiteral extendedStringLiteral,
- BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(FalseLiteral falseLiteral, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(FieldDeclaration fieldDeclaration, MethodScope scope) {
- // do nothing by default
- }
- public void endVisit(FieldReference fieldReference, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(FieldReference fieldReference, ClassScope scope) {
- // do nothing by default
- }
- public void endVisit(ForeachStatement forStatement, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(ForStatement forStatement, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(ForInStatement forInStatement, BlockScope scope) {
- // do nothing by default
- }
-
- public void endVisit(FunctionExpression functionExpression, BlockScope scope) {
- }
-
- public void endVisit(IfStatement ifStatement, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(ImportReference importRef, CompilationUnitScope scope) {
- // do nothing by default
- }
- public void endVisit(InferredType inferredType, BlockScope scope) {
- // do nothing by default
- }
-
- public void endVisit(Initializer initializer, MethodScope scope) {
- // do nothing by default
- }
- public void endVisit(
- InstanceOfExpression instanceOfExpression,
- BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(IntLiteral intLiteral, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(Javadoc javadoc, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(Javadoc javadoc, ClassScope scope) {
- // do nothing by default
- }
- public void endVisit(JavadocAllocationExpression expression, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(JavadocAllocationExpression expression, ClassScope scope) {
- // do nothing by default
- }
- public void endVisit(JavadocArgumentExpression expression, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(JavadocArgumentExpression expression, ClassScope scope) {
- // do nothing by default
- }
- public void endVisit(JavadocArrayQualifiedTypeReference typeRef, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(JavadocArrayQualifiedTypeReference typeRef, ClassScope scope) {
- // do nothing by default
- }
- public void endVisit(JavadocArraySingleTypeReference typeRef, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(JavadocArraySingleTypeReference typeRef, ClassScope scope) {
- // do nothing by default
- }
- public void endVisit(JavadocFieldReference fieldRef, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(JavadocFieldReference fieldRef, ClassScope scope) {
- // do nothing by default
- }
- public void endVisit(JavadocImplicitTypeReference implicitTypeReference, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(JavadocImplicitTypeReference implicitTypeReference, ClassScope scope) {
- // do nothing by default
- }
- public void endVisit(JavadocMessageSend messageSend, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(JavadocMessageSend messageSend, ClassScope scope) {
- // do nothing by default
- }
- public void endVisit(JavadocQualifiedTypeReference typeRef, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(JavadocQualifiedTypeReference typeRef, ClassScope scope) {
- // do nothing by default
- }
- public void endVisit(JavadocReturnStatement statement, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(JavadocReturnStatement statement, ClassScope scope) {
- // do nothing by default
- }
- public void endVisit(JavadocSingleNameReference argument, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(JavadocSingleNameReference argument, ClassScope scope) {
- // do nothing by default
- }
- public void endVisit(JavadocSingleTypeReference typeRef, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(JavadocSingleTypeReference typeRef, ClassScope scope) {
- // do nothing by default
- }
- public void endVisit(LabeledStatement labeledStatement, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(LocalDeclaration localDeclaration, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(ListExpression listDeclaration, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(MessageSend messageSend, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(MethodDeclaration methodDeclaration, Scope scope) {
- // do nothing by default
- }
- public void endVisit(StringLiteralConcatenation literal, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(NullLiteral nullLiteral, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(OR_OR_Expression or_or_Expression, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(PostfixExpression postfixExpression, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(PrefixExpression prefixExpression, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(
- QualifiedAllocationExpression qualifiedAllocationExpression,
- BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(
- QualifiedNameReference qualifiedNameReference,
- BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(
- QualifiedNameReference qualifiedNameReference,
- ClassScope scope) {
- // do nothing by default
- }
- public void endVisit(
- QualifiedThisReference qualifiedThisReference,
- BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(
- QualifiedThisReference qualifiedThisReference,
- ClassScope scope) {
- // do nothing by default
- }
- public void endVisit(
- QualifiedTypeReference qualifiedTypeReference,
- BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(
- QualifiedTypeReference qualifiedTypeReference,
- ClassScope scope) {
- // do nothing by default
- }
-
- public void endVisit(RegExLiteral stringLiteral, BlockScope scope) {
- // do nothing by default
- }
-
-
- public void endVisit(ReturnStatement returnStatement, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(
- SingleNameReference singleNameReference,
- BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(
- SingleNameReference singleNameReference,
- ClassScope scope) {
- // do nothing by default
- }
- public void endVisit(
- SingleTypeReference singleTypeReference,
- BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(
- SingleTypeReference singleTypeReference,
- ClassScope scope) {
- // do nothing by default
- }
- public void endVisit(StringLiteral stringLiteral, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(SuperReference superReference, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(SwitchStatement switchStatement, BlockScope scope) {
- // do nothing by default
- }
-
- public void endVisit(ThisReference thisReference, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(ThisReference thisReference, ClassScope scope) {
- // do nothing by default
- }
- public void endVisit(ThrowStatement throwStatement, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(TrueLiteral trueLiteral, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(TryStatement tryStatement, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(
- TypeDeclaration localTypeDeclaration,
- BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(
- TypeDeclaration memberTypeDeclaration,
- ClassScope scope) {
- // do nothing by default
- }
- public void endVisit(
- TypeDeclaration typeDeclaration,
- CompilationUnitScope scope) {
- // do nothing by default
- }
- public void endVisit(UnaryExpression unaryExpression, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(UndefinedLiteral undefinedLiteral, BlockScope scope) {
- // do nothing by default
- }
-
- public void endVisit(WhileStatement whileStatement, BlockScope scope) {
- // do nothing by default
- }
- public void endVisit(WithStatement whileStatement, BlockScope scope) {
- // do nothing by default
- }
- public boolean visit(
- AllocationExpression allocationExpression,
- BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(AND_AND_Expression and_and_Expression, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(Argument argument, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(Argument argument, ClassScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(
- ArrayAllocationExpression arrayAllocationExpression,
- BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(ArrayInitializer arrayInitializer, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(
- ArrayQualifiedTypeReference arrayQualifiedTypeReference,
- BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(
- ArrayQualifiedTypeReference arrayQualifiedTypeReference,
- ClassScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(ArrayReference arrayReference, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(ArrayTypeReference arrayTypeReference, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(ArrayTypeReference arrayTypeReference, ClassScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(Assignment assignment, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(BinaryExpression binaryExpression, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(Block block, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(BreakStatement breakStatement, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(CaseStatement caseStatement, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(ClassLiteralAccess classLiteral, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(Clinit clinit, ClassScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(
- CompilationUnitDeclaration compilationUnitDeclaration,
- CompilationUnitScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(CompoundAssignment compoundAssignment, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(
- ConditionalExpression conditionalExpression,
- BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(
- ConstructorDeclaration constructorDeclaration,
- ClassScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(ContinueStatement continueStatement, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(DoStatement doStatement, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(DoubleLiteral doubleLiteral, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(EmptyStatement emptyStatement, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(EqualExpression equalExpression, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(
- ExplicitConstructorCall explicitConstructor,
- BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(
- ExtendedStringLiteral extendedStringLiteral,
- BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(FalseLiteral falseLiteral, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(FieldDeclaration fieldDeclaration, MethodScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(FieldReference fieldReference, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(FieldReference fieldReference, ClassScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(ForeachStatement forStatement, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(ForInStatement forInStatement, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(ForStatement forStatement, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(FunctionExpression functionExpression, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IfStatement ifStatement, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(ImportReference importRef, CompilationUnitScope scope) {
- return true; // do nothing by default, keep traversing
- }
-
- public boolean visit(InferredType inferredType, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
-
- public boolean visit(InferredMethod inferredMethod, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
-
- public boolean visit(InferredAttribute inferredField, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(Initializer initializer, MethodScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(
- InstanceOfExpression instanceOfExpression,
- BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(IntLiteral intLiteral, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(Javadoc javadoc, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(Javadoc javadoc, ClassScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(JavadocAllocationExpression expression, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(JavadocAllocationExpression expression, ClassScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(JavadocArgumentExpression expression, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(JavadocArgumentExpression expression, ClassScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(JavadocArrayQualifiedTypeReference typeRef, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(JavadocArrayQualifiedTypeReference typeRef, ClassScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(JavadocArraySingleTypeReference typeRef, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(JavadocArraySingleTypeReference typeRef, ClassScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(JavadocFieldReference fieldRef, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(JavadocFieldReference fieldRef, ClassScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(JavadocImplicitTypeReference implicitTypeReference, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(JavadocImplicitTypeReference implicitTypeReference, ClassScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(JavadocMessageSend messageSend, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(JavadocMessageSend messageSend, ClassScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(JavadocQualifiedTypeReference typeRef, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(JavadocQualifiedTypeReference typeRef, ClassScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(JavadocReturnStatement statement, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(JavadocReturnStatement statement, ClassScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(JavadocSingleNameReference argument, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(JavadocSingleNameReference argument, ClassScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(JavadocSingleTypeReference typeRef, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(JavadocSingleTypeReference typeRef, ClassScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(LabeledStatement labeledStatement, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(LocalDeclaration localDeclaration, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(ListExpression listDeclaration, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(MessageSend messageSend, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(MethodDeclaration methodDeclaration, Scope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(
- StringLiteralConcatenation literal,
- BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(NullLiteral nullLiteral, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(OR_OR_Expression or_or_Expression, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(PostfixExpression postfixExpression, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(PrefixExpression prefixExpression, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(
- QualifiedAllocationExpression qualifiedAllocationExpression,
- BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(
- QualifiedNameReference qualifiedNameReference,
- BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(
- QualifiedNameReference qualifiedNameReference,
- ClassScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(
- QualifiedThisReference qualifiedThisReference,
- BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(
- QualifiedThisReference qualifiedThisReference,
- ClassScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(
- QualifiedTypeReference qualifiedTypeReference,
- BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(
- QualifiedTypeReference qualifiedTypeReference,
- ClassScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(RegExLiteral stringLiteral, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(ReturnStatement returnStatement, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(
- SingleNameReference singleNameReference,
- BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(
- SingleNameReference singleNameReference,
- ClassScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(
- SingleTypeReference singleTypeReference,
- BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(
- SingleTypeReference singleTypeReference,
- ClassScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(StringLiteral stringLiteral, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(SuperReference superReference, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(SwitchStatement switchStatement, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
-
- public boolean visit(ThisReference thisReference, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(ThisReference thisReference, ClassScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(ThrowStatement throwStatement, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(TrueLiteral trueLiteral, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(TryStatement tryStatement, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(
- TypeDeclaration localTypeDeclaration,
- BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(
- TypeDeclaration memberTypeDeclaration,
- ClassScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(
- TypeDeclaration typeDeclaration,
- CompilationUnitScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(UnaryExpression unaryExpression, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(UndefinedLiteral undefined, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(WhileStatement whileStatement, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(WithStatement whileStatement, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public boolean visit(ObjectLiteral literal, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public void endVisit(ObjectLiteral literal, BlockScope scope) {
- }
- public boolean visit(ObjectLiteralField field, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public void endVisit(ObjectLiteralField field, BlockScope scope) {
- }
- public boolean visit(ObjectGetterSetterField field, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public void endVisit(ObjectGetterSetterField field, BlockScope scope) {
- }
- public boolean visit(DebuggerStatement statement, BlockScope scope) {
- return true; // do nothing by default, keep traversing
- }
- public void endVisit(DebuggerStatement statement, BlockScope scope) {
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/CompilationResult.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/CompilationResult.java
deleted file mode 100644
index f6cc2969..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/CompilationResult.java
+++ /dev/null
@@ -1,464 +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.compiler;
-
-/**
- * A compilation result consists of all information returned by the compiler for
- * a single compiled compilation source unit. This includes:
- * <ul>
- * <li> the compilation unit that was compiled
- * <li> for each type produced by compiling the compilation unit, its binary and optionally its principal structure
- * <li> any problems (errors or warnings) produced
- * <li> dependency info
- * </ul>
- *
- * The principle structure and binary may be null if the compiler could not produce them.
- * If neither could be produced, there is no corresponding entry for the type.
- *
- * The dependency info includes type references such as supertypes, field types, method
- * parameter and return types, local variable types, types of intermediate expressions, etc.
- * It also includes the namespaces (packages) in which names were looked up.
- * It does <em>not</em> include finer grained dependencies such as information about
- * specific fields and methods which were referenced, but does contain their
- * declaring types and any other types used to locate such fields or methods.
- */
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit;
-import org.eclipse.wst.jsdt.internal.compiler.impl.ReferenceContext;
-import org.eclipse.wst.jsdt.internal.compiler.parser.RecoveryScannerData;
-import org.eclipse.wst.jsdt.internal.compiler.problem.ProblemReporter;
-import org.eclipse.wst.jsdt.internal.compiler.util.Util;
-
-public class CompilationResult {
-
- public CategorizedProblem problems[];
- public CategorizedProblem tasks[];
- public int problemCount;
- public int taskCount;
- public ICompilationUnit compilationUnit;
- private Map problemsMap;
- private Set firstErrors;
- private int maxProblemPerUnit;
- public char[][][] qualifiedReferences;
- public char[][] simpleNameReferences;
- public int lineSeparatorPositions[];
- public RecoveryScannerData recoveryScannerData;
- public Map compiledTypes = new Hashtable(11);
- public int unitIndex, totalUnitsKnown;
- public boolean hasBeenAccepted = false;
- public char[] fileName;
- public boolean hasInconsistentToplevelHierarchies = false; // record the fact some toplevel types have inconsistent hierarchies
- public boolean hasSyntaxError = false;
- long[] suppressWarningIrritants; // irritant for suppressed warnings
- long[] suppressWarningScopePositions; // (start << 32) + end
- int suppressWarningsCount;
- public char[][] packageName;
-
-private static final int[] EMPTY_LINE_ENDS = Util.EMPTY_INT_ARRAY;
-private static final Comparator PROBLEM_COMPARATOR = new Comparator() {
- public int compare(Object o1, Object o2) {
- return ((CategorizedProblem) o1).getSourceStart() - ((CategorizedProblem) o2).getSourceStart();
- }
-};
-
-public CompilationResult(
- char[] fileName,
- char[][] packageName,
- int unitIndex,
- int totalUnitsKnown, int maxProblemPerUnit){
-
- this.fileName = fileName;
- this.unitIndex = unitIndex;
- this.totalUnitsKnown = totalUnitsKnown;
- this.maxProblemPerUnit = maxProblemPerUnit;
-}
-
-public CompilationResult(
- ICompilationUnit compilationUnit,
- int unitIndex,
- int totalUnitsKnown,
- int maxProblemPerUnit){
-
- this.fileName = compilationUnit.getFileName();
- this.compilationUnit = compilationUnit;
- this.unitIndex = unitIndex;
- this.totalUnitsKnown = totalUnitsKnown;
- this.maxProblemPerUnit = maxProblemPerUnit;
-}
-
-private int computePriority(CategorizedProblem problem){
- final int P_STATIC = 10000;
- final int P_OUTSIDE_METHOD = 40000;
- final int P_FIRST_ERROR = 20000;
- final int P_ERROR = 100000;
-
- int priority = 10000 - problem.getSourceLineNumber(); // early problems first
- if (priority < 0) priority = 0;
- if (problem.isError()){
- priority += P_ERROR;
- }
- ReferenceContext context = this.problemsMap == null ? null : (ReferenceContext) this.problemsMap.get(problem);
- if (context != null){
- if (context instanceof AbstractMethodDeclaration){
- AbstractMethodDeclaration method = (AbstractMethodDeclaration) context;
- if (method.isStatic()) {
- priority += P_STATIC;
- }
- } else {
- priority += P_OUTSIDE_METHOD;
- }
- if (this.firstErrors.contains(problem)){ // if context is null, firstErrors is null too
- priority += P_FIRST_ERROR;
- }
- } else {
- priority += P_OUTSIDE_METHOD;
- }
- return priority;
-}
-
-public void discardSuppressedWarnings() {
- if (this.suppressWarningsCount == 0) return;
- int removed = 0;
- nextProblem: for (int i = 0, length = this.problemCount; i < length; i++) {
- CategorizedProblem problem = this.problems[i];
- int problemID = problem.getID();
- if (!problem.isWarning()) {
- continue nextProblem;
- }
- int start = problem.getSourceStart();
- int end = problem.getSourceEnd();
- nextSuppress: for (int j = 0, max = this.suppressWarningsCount; j < max; j++) {
- long position = this.suppressWarningScopePositions[j];
- int startSuppress = (int) (position >>> 32);
- int endSuppress = (int) position;
- if (start < startSuppress) continue nextSuppress;
- if (end > endSuppress) continue nextSuppress;
- if ((ProblemReporter.getIrritant(problemID) & this.suppressWarningIrritants[j]) == 0)
- continue nextSuppress;
- // discard suppressed warning
- removed++;
- this.problems[i] = null;
- if (this.problemsMap != null) this.problemsMap.remove(problem);
- if (this.firstErrors != null) this.firstErrors.remove(problem);
- continue nextProblem;
- }
- }
- if (removed > 0) {
- for (int i = 0, index = 0; i < this.problemCount; i++) {
- CategorizedProblem problem;
- if ((problem = this.problems[i]) != null) {
- if (i > index) {
- this.problems[index++] = problem;
- } else {
- index++;
- }
- }
- }
- this.problemCount -= removed;
- }
-}
-
-public CategorizedProblem[] getAllProblems() {
- CategorizedProblem[] onlyProblems = this.getProblems();
- int onlyProblemCount = onlyProblems != null ? onlyProblems.length : 0;
- CategorizedProblem[] onlyTasks = this.getTasks();
- int onlyTaskCount = onlyTasks != null ? onlyTasks.length : 0;
- if (onlyTaskCount == 0) {
- return onlyProblems;
- }
- if (onlyProblemCount == 0) {
- return onlyTasks;
- }
-
- int totalNumberOfProblem = onlyProblemCount + onlyTaskCount;
- CategorizedProblem[] allProblems = new CategorizedProblem[totalNumberOfProblem];
- int allProblemIndex = 0;
- int taskIndex = 0;
- int problemIndex = 0;
- while (taskIndex + problemIndex < totalNumberOfProblem) {
- CategorizedProblem nextTask = null;
- CategorizedProblem nextProblem = null;
- if (taskIndex < onlyTaskCount) {
- nextTask = onlyTasks[taskIndex];
- }
- if (problemIndex < onlyProblemCount) {
- nextProblem = onlyProblems[problemIndex];
- }
- // select the next problem
- CategorizedProblem currentProblem = null;
- if (nextProblem != null) {
- if (nextTask != null) {
- if (nextProblem.getSourceStart() < nextTask.getSourceStart()) {
- currentProblem = nextProblem;
- problemIndex++;
- } else {
- currentProblem = nextTask;
- taskIndex++;
- }
- } else {
- currentProblem = nextProblem;
- problemIndex++;
- }
- } else {
- if (nextTask != null) {
- currentProblem = nextTask;
- taskIndex++;
- }
- }
- allProblems[allProblemIndex++] = currentProblem;
- }
- return allProblems;
-}
-
-
-/**
- * Answer the initial compilation unit corresponding to the present compilation result
- */
-public ICompilationUnit getCompilationUnit(){
- return this.compilationUnit;
-}
-
-/**
- * Answer the errors encountered during compilation.
- */
-public CategorizedProblem[] getErrors() {
- CategorizedProblem[] reportedProblems = getProblems();
- int errorCount = 0;
- for (int i = 0; i < this.problemCount; i++) {
- if (reportedProblems[i].isError()) errorCount++;
- }
- if (errorCount == this.problemCount) return reportedProblems;
- CategorizedProblem[] errors = new CategorizedProblem[errorCount];
- int index = 0;
- for (int i = 0; i < this.problemCount; i++) {
- if (reportedProblems[i].isError()) errors[index++] = reportedProblems[i];
- }
- return errors;
-}
-
-
-/**
- * Answer the initial file name
- */
-public char[] getFileName(){
- return this.fileName;
-}
-
-public char [][] getPackageName()
-{
- if (this.compilationUnit!=null)
- return this.compilationUnit.getPackageName();
- return this.packageName;
-}
-
-public int[] getLineSeparatorPositions() {
- return this.lineSeparatorPositions == null ? CompilationResult.EMPTY_LINE_ENDS : this.lineSeparatorPositions;
-}
-
-/**
- * Answer the problems (errors and warnings) encountered during compilation.
- *
- * This is not a compiler internal API - it has side-effects !
- * It is intended to be used only once all problems have been detected,
- * and makes sure the problems slot as the exact size of the number of
- * problems.
- */
-public CategorizedProblem[] getProblems() {
- // Re-adjust the size of the problems if necessary.
- if (this.problems != null) {
- discardSuppressedWarnings();
-
- if (this.problemCount != this.problems.length) {
- System.arraycopy(this.problems, 0, (this.problems = new CategorizedProblem[this.problemCount]), 0, this.problemCount);
- }
-
- if (this.maxProblemPerUnit > 0 && this.problemCount > this.maxProblemPerUnit){
- quickPrioritize(this.problems, 0, this.problemCount - 1);
- this.problemCount = this.maxProblemPerUnit;
- System.arraycopy(this.problems, 0, (this.problems = new CategorizedProblem[this.problemCount]), 0, this.problemCount);
- }
-
- // Stable sort problems per source positions.
- Arrays.sort(this.problems, 0, this.problems.length, CompilationResult.PROBLEM_COMPARATOR);
- //quickSort(problems, 0, problems.length-1);
- }
- return this.problems;
-}
-
-/**
- * Answer the tasks (TO-DO, ...) encountered during compilation.
- *
- * This is not a compiler internal API - it has side-effects !
- * It is intended to be used only once all problems have been detected,
- * and makes sure the problems slot as the exact size of the number of
- * problems.
- */
-public CategorizedProblem[] getTasks() {
- // Re-adjust the size of the tasks if necessary.
- if (this.tasks != null) {
-
- if (this.taskCount != this.tasks.length) {
- System.arraycopy(this.tasks, 0, (this.tasks = new CategorizedProblem[this.taskCount]), 0, this.taskCount);
- }
- // Stable sort problems per source positions.
- Arrays.sort(this.tasks, 0, this.tasks.length, CompilationResult.PROBLEM_COMPARATOR);
- //quickSort(tasks, 0, tasks.length-1);
- }
- return this.tasks;
-}
-
-public boolean hasErrors() {
- if (this.problems != null)
- for (int i = 0; i < this.problemCount; i++) {
- if (this.problems[i].isError())
- return true;
- }
- return false;
-}
-
-public boolean hasProblems() {
- return this.problemCount != 0;
-}
-
-public boolean hasTasks() {
- return this.taskCount != 0;
-}
-
-public boolean hasWarnings() {
- if (this.problems != null)
- for (int i = 0; i < this.problemCount; i++) {
- if (this.problems[i].isWarning())
- return true;
- }
- return false;
-}
-
-private void quickPrioritize(CategorizedProblem[] problemList, int left, int right) {
- if (left >= right) return;
-
- // sort the problems by their priority... starting with the highest priority
- int original_left = left;
- int original_right = right;
- int mid = computePriority(problemList[left + (right - left) / 2]);
- do {
- while (computePriority(problemList[right]) < mid)
- right--;
- while (mid < computePriority(problemList[left]))
- left++;
- if (left <= right) {
- CategorizedProblem tmp = problemList[left];
- problemList[left] = problemList[right];
- problemList[right] = tmp;
- left++;
- right--;
- }
- } while (left <= right);
- if (original_left < right)
- quickPrioritize(problemList, original_left, right);
- if (left < original_right)
- quickPrioritize(problemList, left, original_right);
-}
-/*
- * Record the compilation unit result's package name
- */
-public void recordPackageName(char[][] packName) {
- this.packageName = packName;
-}
-public void record(CategorizedProblem newProblem, ReferenceContext referenceContext) {
- //new Exception("VERBOSE PROBLEM REPORTING").printStackTrace();
- if(newProblem.getID() == IProblem.Task) {
- recordTask(newProblem);
- return;
- }
- if (this.problemCount == 0) {
- this.problems = new CategorizedProblem[5];
- } else if (this.problemCount == this.problems.length) {
- System.arraycopy(this.problems, 0, (this.problems = new CategorizedProblem[this.problemCount * 2]), 0, this.problemCount);
- }
- this.problems[this.problemCount++] = newProblem;
- if (referenceContext != null){
- if (this.problemsMap == null) this.problemsMap = new HashMap(5);
- if (this.firstErrors == null) this.firstErrors = new HashSet(5);
- if (newProblem.isError() && !referenceContext.hasErrors()) this.firstErrors.add(newProblem);
- this.problemsMap.put(newProblem, referenceContext);
- }
- if ((newProblem.getID() & IProblem.Syntax) != 0 && newProblem.isError())
- this.hasSyntaxError = true;
-}
-
-
-
-public void recordSuppressWarnings(long irritant, int scopeStart, int scopeEnd) {
- if (this.suppressWarningIrritants == null) {
- this.suppressWarningIrritants = new long[3];
- this.suppressWarningScopePositions = new long[3];
- } else if (this.suppressWarningIrritants.length == this.suppressWarningsCount) {
- System.arraycopy(this.suppressWarningIrritants, 0,this.suppressWarningIrritants = new long[2*this.suppressWarningsCount], 0, this.suppressWarningsCount);
- System.arraycopy(this.suppressWarningScopePositions, 0,this.suppressWarningScopePositions = new long[2*this.suppressWarningsCount], 0, this.suppressWarningsCount);
- }
- this.suppressWarningIrritants[this.suppressWarningsCount] = irritant;
- this.suppressWarningScopePositions[this.suppressWarningsCount++] = ((long)scopeStart<<32) + scopeEnd;
-}
-
-private void recordTask(CategorizedProblem newProblem) {
- if (this.taskCount == 0) {
- this.tasks = new CategorizedProblem[5];
- } else if (this.taskCount == this.tasks.length) {
- System.arraycopy(this.tasks, 0, (this.tasks = new CategorizedProblem[this.taskCount * 2]), 0, this.taskCount);
- }
- this.tasks[this.taskCount++] = newProblem;
-}
-
-public CompilationResult tagAsAccepted(){
- this.hasBeenAccepted = true;
- this.problemsMap = null; // flush
- this.firstErrors = null; // flush
- return this;
-}
-
-public String toString(){
- StringBuffer buffer = new StringBuffer();
- if (this.fileName != null){
- buffer.append("Filename : ").append(this.fileName).append('\n'); //$NON-NLS-1$
- }
- if (this.compiledTypes != null){
- buffer.append("COMPILED type(s) \n"); //$NON-NLS-1$
- Iterator keys = this.compiledTypes.keySet().iterator();
- while (keys.hasNext()) {
- char[] typeName = (char[]) keys.next();
- buffer.append("\t - ").append(typeName).append('\n'); //$NON-NLS-1$
-
- }
- } else {
- buffer.append("No COMPILED type\n"); //$NON-NLS-1$
- }
- if (this.problems != null){
- buffer.append(this.problemCount).append(" PROBLEM(s) detected \n"); //$NON-NLS-1$
- for (int i = 0; i < this.problemCount; i++){
- buffer.append("\t - ").append(this.problems[i]).append('\n'); //$NON-NLS-1$
- }
- } else {
- buffer.append("No PROBLEM\n"); //$NON-NLS-1$
- }
- return buffer.toString();
-}
-}
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
deleted file mode 100644
index 0b816132..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/Compiler.java
+++ /dev/null
@@ -1,713 +0,0 @@
-/*******************************************************************************
- * 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 <spektom@gmail.com> - Bug 243886
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler;
-
-import java.io.PrintWriter;
-import java.io.StringWriter;
-
-import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem;
-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;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ImportReference;
-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;
-import org.eclipse.wst.jsdt.internal.compiler.impl.ITypeRequestor;
-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;
-import org.eclipse.wst.jsdt.internal.compiler.parser.Parser;
-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.DefaultProblem;
-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.HashtableOfObject;
-import org.eclipse.wst.jsdt.internal.compiler.util.Messages;
-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 Parser parser;
- public ICompilerRequestor requestor;
- public CompilerOptions options;
- public ProblemReporter problemReporter;
- protected PrintWriter out; // output for messages that are not sent to problemReporter
-
- // management of unit to be processed
- public CompilationUnitDeclaration[] unitsToProcess;
- public int totalUnits; // (totalUnits-1) gives the last unit in unitToProcess
-
- // name lookup
- public LookupEnvironment lookupEnvironment;
-
- // ONCE STABILIZED, THESE SHOULD RETURN TO A FINAL FIELD
- public static boolean DEBUG = false;
- public int parseThreshold = -1;
-
- public ReferenceBinding[] referenceBindings;
- protected HashtableOfObject parsedUnits;
-
-
- // number of initial units parsed at once (-1: none)
-
- /*
- * Static requestor reserved to listening compilation results in debug mode,
- * so as for example to monitor compiler activity independantly from a particular
- * builder implementation. It is reset at the end of compilation, and should not
- * persist any information after having been reset.
- */
- public static IDebugRequestor DebugRequestor = null;
-
- /**
- * Answer a new compiler using the given name environment and compiler options.
- * The environment and options will be in effect for the lifetime of the compiler.
- * When the compiler is run, compilation results are sent to the given requestor.
- *
- * @param environment org.eclipse.wst.jsdt.internal.compiler.api.env.INameEnvironment
- * Environment used by the compiler in order to resolve type and package
- * names. The name environment implements the actual connection of the compiler
- * to the outside world (e.g. in batch mode the name environment is performing
- * pure file accesses, reuse previous build state or connection to repositories).
- * Note: the name environment is responsible for implementing the actual classpath
- * rules.
- *
- * @param policy org.eclipse.wst.jsdt.internal.compiler.api.problem.IErrorHandlingPolicy
- * Configurable part for problem handling, allowing the compiler client to
- * specify the rules for handling problems (stop on first error or accumulate
- * them all) and at the same time perform some actions such as opening a dialog
- * in UI when compiling interactively.
- * @see org.eclipse.wst.jsdt.internal.compiler.DefaultErrorHandlingPolicies
- *
- * @param options org.eclipse.wst.jsdt.internal.compiler.impl.CompilerOptions
- * The options that control the compiler behavior.
- *
- * @param requestor org.eclipse.wst.jsdt.internal.compiler.api.ICompilerRequestor
- * Component which will receive and persist all compilation results and is intended
- * to consume them as they are produced. Typically, in a batch compiler, it is
- * responsible for writing out the actual .class files to the file system.
- * @see org.eclipse.wst.jsdt.internal.compiler.CompilationResult
- *
- * @param problemFactory org.eclipse.wst.jsdt.internal.compiler.api.problem.IProblemFactory
- * Factory used inside the compiler to create problem descriptors. It allows the
- * compiler client to supply its own representation of compilation problems in
- * order to avoid object conversions. Note that the factory is not supposed
- * to accumulate the created problems, the compiler will gather them all and hand
- * them back as part of the compilation unit result.
- */
- public Compiler(
- INameEnvironment environment,
- IErrorHandlingPolicy policy,
- CompilerOptions options,
- final ICompilerRequestor requestor,
- IProblemFactory problemFactory) {
- this(environment, policy, options, requestor, problemFactory, null);
- }
-
- /**
- * Answer a new compiler using the given name environment and compiler options.
- * The environment and options will be in effect for the lifetime of the compiler.
- * When the compiler is run, compilation results are sent to the given requestor.
- *
- * @param environment org.eclipse.wst.jsdt.internal.compiler.api.env.INameEnvironment
- * Environment used by the compiler in order to resolve type and package
- * names. The name environment implements the actual connection of the compiler
- * to the outside world (e.g. in batch mode the name environment is performing
- * pure file accesses, reuse previous build state or connection to repositories).
- * Note: the name environment is responsible for implementing the actual classpath
- * rules.
- *
- * @param policy org.eclipse.wst.jsdt.internal.compiler.api.problem.IErrorHandlingPolicy
- * Configurable part for problem handling, allowing the compiler client to
- * specify the rules for handling problems (stop on first error or accumulate
- * them all) and at the same time perform some actions such as opening a dialog
- * in UI when compiling interactively.
- * @see org.eclipse.wst.jsdt.internal.compiler.DefaultErrorHandlingPolicies
- *
- * @param options org.eclipse.wst.jsdt.internal.compiler.impl.CompilerOptions
- * The options that control the compiler behavior.
- *
- * @param requestor org.eclipse.wst.jsdt.internal.compiler.api.ICompilerRequestor
- * Component which will receive and persist all compilation results and is intended
- * to consume them as they are produced. Typically, in a batch compiler, it is
- * responsible for writing out the actual .class files to the file system.
- * @see org.eclipse.wst.jsdt.internal.compiler.CompilationResult
- *
- * @param problemFactory org.eclipse.wst.jsdt.internal.compiler.api.problem.IProblemFactory
- * Factory used inside the compiler to create problem descriptors. It allows the
- * compiler client to supply its own representation of compilation problems in
- * order to avoid object conversions. Note that the factory is not supposed
- * to accumulate the created problems, the compiler will gather them all and hand
- * them back as part of the compilation unit result.
- */
- public Compiler(
- INameEnvironment environment,
- IErrorHandlingPolicy policy,
- CompilerOptions options,
- final ICompilerRequestor requestor,
- IProblemFactory problemFactory,
- PrintWriter out) {
-
- this.options = options;
-
- // wrap requestor in DebugRequestor if one is specified
- if(DebugRequestor == null) {
- this.requestor = requestor;
- } else {
- this.requestor = new ICompilerRequestor(){
- public void acceptResult(CompilationResult result){
- if (DebugRequestor.isActive()){
- DebugRequestor.acceptDebugResult(result);
- }
- requestor.acceptResult(result);
- }
- };
- }
- this.problemReporter = new ProblemReporter(policy, this.options, problemFactory);
- this.lookupEnvironment = new LookupEnvironment(this, this.options, problemReporter, environment);
- this.out = out == null ? new PrintWriter(System.out, true) : out;
- initializeParser();
- }
-
- /**
- * Add an additional binary type
- */
- public void accept(IBinaryType binaryType, PackageBinding packageBinding, AccessRestriction accessRestriction) {
-// if (this.options.verbose) {
-// this.out.println(
-// Messages.bind(Messages.compilation_loadBinary, new String(binaryType.getName())));
-//// new Exception("TRACE BINARY").printStackTrace(System.out);
-//// System.out.println();
-// }
-// lookupEnvironment.createBinaryTypeFrom(binaryType, packageBinding, accessRestriction);
- }
-
- /**
- * Add an additional compilation unit into the loop
- * -> build compilation unit declarations, their bindings and record their results.
- */
- public void accept(ICompilationUnit sourceUnit, 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);
- if (sourceUnit instanceof SourceFile)
- this.addCompilationUnit(sourceUnit, parsedUnit);
- }
- // initial type binding creation
- lookupEnvironment.buildTypeBindings(parsedUnit, accessRestriction);
-
- // binding resolution
- lookupEnvironment.completeTypeBindings(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
- }
- }
- }
-
- public void accept(LibraryAPIs libraryMetaData)
- {
- lookupEnvironment.buildTypeBindings(libraryMetaData);
-
- }
-
-
- public CompilationUnitDeclaration doParse(ICompilationUnit sourceUnit, AccessRestriction accessRestriction) {
- CompilationResult unitResult =
- new CompilationResult(sourceUnit, totalUnits, totalUnits, this.options.maxProblemsPerUnit);
- 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())
- }));
- }
- // diet parsing for large collection of unit
- CompilationUnitDeclaration parsedUnit;
- if (totalUnits < parseThreshold) {
- parsedUnit = parser.parse(sourceUnit, unitResult);
- } else {
- parsedUnit = parser.dietParse(sourceUnit, unitResult);
- }
- parser.inferTypes(parsedUnit,this.options);
- 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
-// }
- }
- }
-
-
- /**
- * Add additional source types
- */
- public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding, AccessRestriction accessRestriction) {
- problemReporter.abortDueToInternalError(
- Messages.bind(Messages.abort_againstSourceModel, new String[] { String.valueOf(sourceTypes[0].getName()), String.valueOf(sourceTypes[0].getFileName()) }));
- }
-
- protected void addCompilationUnit(
- ICompilationUnit sourceUnit,
- CompilationUnitDeclaration parsedUnit) {
-
- // append the unit to the list of ones to process later on
- int size = unitsToProcess.length;
- if (totalUnits == size)
- // when growing reposition units starting at position 0
- System.arraycopy(
- unitsToProcess,
- 0,
- (unitsToProcess = new CompilationUnitDeclaration[size * 2]),
- 0,
- totalUnits);
- unitsToProcess[totalUnits++] = parsedUnit;
- }
-
- /**
- * Add the initial set of compilation units into the loop
- * -> build compilation unit declarations, their bindings and record their results.
- */
- protected void beginToCompile(ICompilationUnit[] sourceUnits) {
- int maxUnits = sourceUnits.length;
- this.totalUnits = 0;
- this.unitsToProcess = new CompilationUnitDeclaration[maxUnits];
-
- internalBeginToCompile(sourceUnits, maxUnits);
- }
-
- /**
- * General API
- * -> compile each of supplied files
- * -> recompile any required types for which we have an incomplete principle structure
- */
- public void compile(ICompilationUnit[] sourceUnits) {
- CompilationUnitDeclaration unit = null;
- int i = 0;
- try {
- // build and record parsed units
-
- beginToCompile(sourceUnits);
-
- // process all units (some more could be injected in the loop by the lookup environment)
- for (; 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 {
- // cleanup compilation unit result
- unit.cleanUp();
- }
- unitsToProcess[i] = null; // release reference to processed unit declaration
- requestor.acceptResult(unit.compilationResult.tagAsAccepted());
- if (options.verbose)
- this.out.println(
- Messages.bind(Messages.compilation_done,
- new String[] {
- String.valueOf(i + 1),
- String.valueOf(this.totalUnits),
- new String(unit.getFileName())
- }));
- }
- } catch (AbortCompilation e) {
- this.handleInternalException(e, unit);
- } catch (Error e) {
- this.handleInternalException(e, unit, null);
- throw e; // rethrow
- } catch (RuntimeException e) {
- this.handleInternalException(e, unit, null);
- throw e; // rethrow
- } finally {
- this.reset();
- }
- if (options.verbose) {
- if (this.totalUnits > 1) {
- this.out.println(
- Messages.bind(Messages.compilation_units, String.valueOf(this.totalUnits)));
- } else {
- this.out.println(
- Messages.bind(Messages.compilation_unit, String.valueOf(this.totalUnits)));
- }
- }
- }
- /*
- * Compiler crash recovery in case of unexpected runtime exceptions
- */
- protected void handleInternalException(
- Throwable internalException,
- CompilationUnitDeclaration unit,
- CompilationResult result) {
-
- if (!this.options.enableSemanticValidation)
- return;
-
- if ((result == null) && (unit != null)) {
- result = unit.compilationResult; // current unit being processed ?
- }
- // Lookup environment may be in middle of connecting types
- if ((result == null) && lookupEnvironment.unitBeingCompleted != null) {
- result = lookupEnvironment.unitBeingCompleted.compilationResult;
- }
- // Lookup environment may be in middle of connecting types
- if ((result == null) && lookupEnvironment.unitBeingCompleted != null) {
- result = lookupEnvironment.unitBeingCompleted.compilationResult;
- }
- if ((result == null) && (unitsToProcess != null) && (totalUnits > 0))
- result = unitsToProcess[totalUnits - 1].compilationResult;
- // last unit in beginToCompile ?
-
- boolean needToPrint = true;
- if (result != null) {
- /* create and record a compilation problem */
- StringWriter stringWriter = new StringWriter();
- PrintWriter writer = new PrintWriter(stringWriter);
- internalException.printStackTrace(writer);
- StringBuffer buffer = stringWriter.getBuffer();
-
- String[] pbArguments = new String[] {
- Messages.compilation_internalError
- + "\n" //$NON-NLS-1$
- + buffer.toString()};
-
- result
- .record(
- problemReporter
- .createProblem(
- result.getFileName(),
- IProblem.Unclassified,
- pbArguments,
- pbArguments,
- Error, // severity
- 0, // source start
- 0, // source end
- 0, // line number
- 0),// column number
- unit);
-
- /* hand back the compilation result */
- if (!result.hasBeenAccepted) {
- requestor.acceptResult(result.tagAsAccepted());
- needToPrint = false;
- }
- }
- if (needToPrint) {
- /* dump a stack trace to the console */
- internalException.printStackTrace();
- }
- }
-
- public void setBinaryTypes(ReferenceBinding[] binaryTypes) {
- this.referenceBindings = binaryTypes;
- }
- /*
- * Compiler recovery in case of internal AbortCompilation event
- */
- protected void handleInternalException(
- AbortCompilation abortException,
- CompilationUnitDeclaration unit) {
-
- if (!this.options.enableSemanticValidation)
- return;
-
- /* special treatment for SilentAbort: silently cancelling the compilation process */
- if (abortException.isSilent) {
- if (abortException.silentException == null) {
- return;
- }
- throw abortException.silentException;
- }
-
- /* uncomment following line to see where the abort came from */
- // abortException.printStackTrace();
-
- // Exception may tell which compilation result it is related, and which problem caused it
- CompilationResult result = abortException.compilationResult;
- if ((result == null) && (unit != null)) {
- result = unit.compilationResult; // current unit being processed ?
- }
- // Lookup environment may be in middle of connecting types
- if ((result == null) && lookupEnvironment.unitBeingCompleted != null) {
- result = lookupEnvironment.unitBeingCompleted.compilationResult;
- }
- if ((result == null) && (unitsToProcess != null) && (totalUnits > 0))
- result = unitsToProcess[totalUnits - 1].compilationResult;
- // last unit in beginToCompile ?
- if (result != null && !result.hasBeenAccepted) {
- /* distant problem which could not be reported back there? */
- if (abortException.problem != null) {
- recordDistantProblem: {
- CategorizedProblem distantProblem = abortException.problem;
- CategorizedProblem[] knownProblems = result.problems;
- for (int i = 0; i < result.problemCount; i++) {
- if (knownProblems[i] == distantProblem) { // already recorded
- break recordDistantProblem;
- }
- }
- if (distantProblem instanceof DefaultProblem) { // fixup filename TODO (philippe) should improve API to make this official
- ((DefaultProblem) distantProblem).setOriginatingFileName(result.getFileName());
- }
- result.record(distantProblem, unit);
- }
- } else {
- /* distant internal exception which could not be reported back there */
- if (abortException.exception != null) {
- this.handleInternalException(abortException.exception, null, result);
- return;
- }
- }
- /* hand back the compilation result */
- if (!result.hasBeenAccepted) {
- requestor.acceptResult(result.tagAsAccepted());
- }
- } else {
- abortException.printStackTrace();
- }
- }
-
- public void initializeParser() {
-
- this.parser = new Parser(this.problemReporter, this.options.parseLiteralExpressionsAsConstants);
- this.parser.javadocParser=new SourceJavadocParser(this.parser);
- this.parser.javadocParser.checkDocComment=true;
- }
-
- /**
- * Add the initial set of compilation units into the loop
- * -> build compilation unit declarations, their bindings and record their results.
- */
- protected void internalBeginToCompile(ICompilationUnit[] sourceUnits, int maxUnits) {
- SimpleSetOfCharArray allDefinedTypes = new SimpleSetOfCharArray();
- // Switch the current policy and compilation result for this unit to the requested one.
- for (int i = 0; i < maxUnits; i++) {
- CompilationUnitDeclaration parsedUnit;
- CompilationResult unitResult =
- new CompilationResult(sourceUnits[i], i, maxUnits, this.options.maxProblemsPerUnit);
- try {
- if (options.verbose) {
- this.out.println(
- Messages.bind(Messages.compilation_request,
- new String[] {
- String.valueOf(i + 1),
- String.valueOf(maxUnits),
- new String(sourceUnits[i].getFileName())
- }));
- }
- // diet parsing for large collection of units
- if (totalUnits < parseThreshold) {
- parsedUnit = parser.parse(sourceUnits[i], unitResult);
- } else {
- parsedUnit = parser.dietParse(sourceUnits[i], unitResult);
- }
- parser.inferTypes(parsedUnit,this.options);
-
- SimpleSetOfCharArray defined = new SimpleSetOfCharArray();
- for (int j = 0; j < parsedUnit.numberInferredTypes; j++) {
- if (parsedUnit.inferredTypes[j].isDefinition && !parsedUnit.inferredTypes[j].isEmptyGlobal()) {
- defined.add(parsedUnit.inferredTypes[j].getName());
- allDefinedTypes.add(parsedUnit.inferredTypes[j].getName());
- }
- }
- // initial type binding creation
- this.addCompilationUnit(sourceUnits[i], parsedUnit);
- lookupEnvironment.buildTypeBindings(parsedUnit, defined.values, null /*no access restriction*/);
- ImportReference currentPackage = parsedUnit.currentPackage;
- if (currentPackage != null) {
- unitResult.recordPackageName(currentPackage.tokens);
- }
- //} catch (AbortCompilationUnit e) {
- // requestor.acceptResult(unitResult.tagAsAccepted());
- } finally {
- sourceUnits[i] = null; // no longer hold onto the unit
- }
- }
- // binding resolution
- lookupEnvironment.completeTypeBindings(allDefinedTypes.values);
- }
-
- /**
- * Process a compilation unit already parsed and build.
- */
- public void process(CompilationUnitDeclaration unit, int i) {
- this.lookupEnvironment.unitBeingCompleted = unit;
-
- this.parser.getMethodBodies(unit);
-
- // fault in fields & methods
- if (unit.scope != null)
- unit.scope.faultInTypes();
-
- // verify inherited methods
- if (unit.scope != null)
- unit.scope.verifyMethods(lookupEnvironment.methodVerifier());
-
- // type checking
- unit.resolve();
-
- unit.analyseCode();
-
-
- // reference info
- if (options.produceReferenceInfo && unit.scope != null)
- unit.scope.storeDependencyInfo();
-
- // refresh the total number of units known at this stage
- unit.compilationResult.totalUnitsKnown = totalUnits;
-
- this.lookupEnvironment.unitBeingCompleted = null;
- }
-
- public void reset() {
- lookupEnvironment.reset();
- parser.scanner.source = null;
- unitsToProcess = null;
- if(parsedUnits != null)
- parsedUnits.clear();
- if (DebugRequestor != null) DebugRequestor.reset();
- this.problemReporter.reset();
- }
-
- /**
- * Internal API used to resolve a given compilation unit. Can run a subset of the compilation process
- */
- public CompilationUnitDeclaration resolve(
- CompilationUnitDeclaration unit,
- ICompilationUnit sourceUnit,
- boolean verifyMethods,
- boolean analyzeCode,
- boolean generateCode) {
-
- try {
- if (unit == null) {
- // build and record parsed units
- parseThreshold = 0; // will request a full parse
- beginToCompile(new ICompilationUnit[] { sourceUnit });
- // process all units (some more could be injected in the loop by the lookup environment)
- unit = unitsToProcess[0];
- } else {
- // initial type binding creation
- lookupEnvironment.buildTypeBindings(unit, null /*no access restriction*/);
-
- // binding resolution
- lookupEnvironment.completeTypeBindings();
- }
- this.lookupEnvironment.unitBeingCompleted = unit;
- this.parser.getMethodBodies(unit);
- 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();
-
- // flow analysis
- if (analyzeCode) unit.analyseCode();
-
- // code generation
-// if (generateCode) unit.generateCode();
- }
- if (unitsToProcess != null) unitsToProcess[0] = null; // release reference to processed unit declaration
- requestor.acceptResult(unit.compilationResult.tagAsAccepted());
- return unit;
- } catch (AbortCompilation e) {
- this.handleInternalException(e, unit);
- return unit == null ? unitsToProcess[0] : unit;
- } catch (Error e) {
- this.handleInternalException(e, unit, null);
- throw e; // rethrow
- } catch (RuntimeException e) {
- this.handleInternalException(e, unit, null);
- throw e; // rethrow
- } finally {
-// this.lookupEnvironment.unitBeingCompleted = null;
- // leave this.lookupEnvironment.unitBeingCompleted set to the unit, until another unit is resolved
- // other calls to dom can cause classpath errors to be detected, resulting in AbortCompilation exceptions // No reset is performed there anymore since,
-
- // within the CodeAssist (or related tools),
- // the compiler may be called *after* a call
- // to this resolve(...) method. And such a call
- // needs to have a compiler with a non-empty
- // environment.
- // this.reset();
- }
- }
- /**
- * Internal API used to resolve a given compilation unit. Can run a subset of the compilation process
- */
- public CompilationUnitDeclaration resolve(
- ICompilationUnit sourceUnit,
- boolean verifyMethods,
- boolean analyzeCode,
- boolean generateCode) {
-
- return resolve(
- null,
- sourceUnit,
- verifyMethods,
- analyzeCode,
- generateCode);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/DefaultErrorHandlingPolicies.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/DefaultErrorHandlingPolicies.java
deleted file mode 100644
index cf6eb82e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/DefaultErrorHandlingPolicies.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler;
-
-public class DefaultErrorHandlingPolicies {
-
-/*
- * Accumulate all problems, then exit without proceeding.
- *
- * Typically, the #proceedWithProblems(Problem[]) should
- * show the problems.
- *
- */
-public static IErrorHandlingPolicy exitAfterAllProblems() {
- return new IErrorHandlingPolicy() {
- public boolean stopOnFirstError() {
- return false;
- }
- public boolean proceedOnErrors(){
- return false;
- }
- };
-}
-/*
- * Exit without proceeding on the first problem wich appears
- * to be an error.
- *
- */
-public static IErrorHandlingPolicy exitOnFirstError() {
- return new IErrorHandlingPolicy() {
- public boolean stopOnFirstError() {
- return true;
- }
- public boolean proceedOnErrors(){
- return false;
- }
- };
-}
-/*
- * Proceed on the first error met.
- *
- */
-public static IErrorHandlingPolicy proceedOnFirstError() {
- return new IErrorHandlingPolicy() {
- public boolean stopOnFirstError() {
- return true;
- }
- public boolean proceedOnErrors(){
- return true;
- }
- };
-}
-/*
- * Accumulate all problems, then proceed with them.
- *
- */
-public static IErrorHandlingPolicy proceedWithAllProblems() {
- return new IErrorHandlingPolicy() {
- public boolean stopOnFirstError() {
- return false;
- }
- public boolean proceedOnErrors(){
- return true;
- }
- };
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/DelegateASTVisitor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/DelegateASTVisitor.java
deleted file mode 100644
index 828bc8ca..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/DelegateASTVisitor.java
+++ /dev/null
@@ -1,866 +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.compiler;
-
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-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.AND_AND_Expression;
-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.ArrayAllocationExpression;
-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.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.DoStatement;
-import org.eclipse.wst.jsdt.internal.compiler.ast.DoubleLiteral;
-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.ExtendedStringLiteral;
-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.ForeachStatement;
-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.InstanceOfExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.IntLiteral;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Javadoc;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocAllocationExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocArgumentExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocArrayQualifiedTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocArraySingleTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocFieldReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocImplicitTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocMessageSend;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocQualifiedTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocReturnStatement;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocSingleNameReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocSingleTypeReference;
-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.NullLiteral;
-import org.eclipse.wst.jsdt.internal.compiler.ast.OR_OR_Expression;
-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.PostfixExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.PrefixExpression;
-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.QualifiedThisReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedTypeReference;
-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.StringLiteral;
-import org.eclipse.wst.jsdt.internal.compiler.ast.StringLiteralConcatenation;
-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.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.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.MethodScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Scope;
-
-
-/**
- * A visitor for iterating through the parse tree.
- */
-public class DelegateASTVisitor extends ASTVisitor {
- org.eclipse.wst.jsdt.core.ast.ASTVisitor visitor;
- public DelegateASTVisitor(org.eclipse.wst.jsdt.core.ast.ASTVisitor visitor)
- {
- this.visitor=visitor;
- }
-
-
- public void acceptProblem(IProblem problem) {
- visitor.acceptProblem(problem);
- }
- public void endVisit(
- AllocationExpression allocationExpression,
- BlockScope scope) {
- visitor.endVisit(allocationExpression);
- }
- public void endVisit(AND_AND_Expression and_and_Expression, BlockScope scope) {
- visitor.endVisit(and_and_Expression);
- }
- public void endVisit(Argument argument, BlockScope scope) {
- visitor.endVisit(argument);
- }
- public void endVisit(Argument argument,ClassScope scope) {
- visitor.endVisit(argument);
- }
- public void endVisit(
- ArrayAllocationExpression arrayAllocationExpression,
- BlockScope scope) {
- visitor.endVisit(arrayAllocationExpression);
- }
- public void endVisit(ArrayInitializer arrayInitializer, BlockScope scope) {
- visitor.endVisit(arrayInitializer);
- }
- public void endVisit(
- ArrayQualifiedTypeReference arrayQualifiedTypeReference,
- BlockScope scope) {
- visitor.endVisit(arrayQualifiedTypeReference);
- }
- public void endVisit(
- ArrayQualifiedTypeReference arrayQualifiedTypeReference,
- ClassScope scope) {
- visitor.endVisit(arrayQualifiedTypeReference);
- }
- public void endVisit(ArrayReference arrayReference, BlockScope scope) {
- visitor.endVisit(arrayReference);
- }
- public void endVisit(ArrayTypeReference arrayTypeReference, BlockScope scope) {
- visitor.endVisit(arrayTypeReference);
- }
- public void endVisit(ArrayTypeReference arrayTypeReference, ClassScope scope) {
- visitor.endVisit(arrayTypeReference);
- }
- public void endVisit(Assignment assignment, BlockScope scope) {
- visitor.endVisit(assignment);
- }
- public void endVisit(BinaryExpression binaryExpression, BlockScope scope) {
- visitor.endVisit(binaryExpression);
- }
- public void endVisit(Block block, BlockScope scope) {
- visitor.endVisit(block);
- }
- public void endVisit(BreakStatement breakStatement, BlockScope scope) {
- visitor.endVisit(breakStatement);
- }
- public void endVisit(CaseStatement caseStatement, BlockScope scope) {
- visitor.endVisit(caseStatement);
- }
-
- public void endVisit(
- CompilationUnitDeclaration compilationUnitDeclaration,
- CompilationUnitScope scope) {
- visitor.endVisit(compilationUnitDeclaration);
- }
- public void endVisit(CompoundAssignment compoundAssignment, BlockScope scope) {
- visitor.endVisit(compoundAssignment);
- }
- public void endVisit(
- ConditionalExpression conditionalExpression,
- BlockScope scope) {
- visitor.endVisit(conditionalExpression);
- }
- public void endVisit(
- ConstructorDeclaration constructorDeclaration,
- ClassScope scope) {
- visitor.endVisit(constructorDeclaration);
- }
- public void endVisit(ContinueStatement continueStatement, BlockScope scope) {
- visitor.endVisit(continueStatement);
- }
- public void endVisit(DoStatement doStatement, BlockScope scope) {
- visitor.endVisit(doStatement);
- }
- public void endVisit(DoubleLiteral doubleLiteral, BlockScope scope) {
- visitor.endVisit(doubleLiteral);
- }
- public void endVisit(EmptyStatement emptyStatement, BlockScope scope) {
- visitor.endVisit(emptyStatement);
- }
- public void endVisit(EqualExpression equalExpression, BlockScope scope) {
- visitor.endVisit(equalExpression);
- }
- public void endVisit(
- ExplicitConstructorCall explicitConstructor,
- BlockScope scope) {
- visitor.endVisit(explicitConstructor);
- }
- public void endVisit(
- ExtendedStringLiteral extendedStringLiteral,
- BlockScope scope) {
- visitor.endVisit(extendedStringLiteral);
- }
- public void endVisit(FalseLiteral falseLiteral, BlockScope scope) {
- visitor.endVisit(falseLiteral);
- }
- public void endVisit(FieldDeclaration fieldDeclaration, MethodScope scope) {
- visitor.endVisit( fieldDeclaration);
- }
- public void endVisit(FieldReference fieldReference, BlockScope scope) {
- visitor.endVisit( fieldReference);
- }
- public void endVisit(FieldReference fieldReference, ClassScope scope) {
- visitor.endVisit(fieldReference);
- }
- public void endVisit(ForeachStatement forStatement, BlockScope scope) {
- visitor.endVisit(forStatement);
- }
- public void endVisit(ForStatement forStatement, BlockScope scope) {
- visitor.endVisit(forStatement);
- }
- public void endVisit(ForInStatement forInStatement, BlockScope scope) {
- visitor.endVisit(forInStatement);
- }
-
- public void endVisit(FunctionExpression functionExpression, BlockScope scope) {
- visitor.endVisit(functionExpression);
- }
-
- public void endVisit(IfStatement ifStatement, BlockScope scope) {
- visitor.endVisit(ifStatement);
- }
- public void endVisit(ImportReference importRef, CompilationUnitScope scope) {
- visitor.endVisit(importRef);
- }
- public void endVisit(InferredType inferredType, BlockScope scope) {
- visitor.endVisit(inferredType);
- }
-
- public void endVisit(Initializer initializer, MethodScope scope) {
- visitor.endVisit(initializer);
- }
- public void endVisit(
- InstanceOfExpression instanceOfExpression,
- BlockScope scope) {
- visitor.endVisit(instanceOfExpression);
- }
- public void endVisit(IntLiteral intLiteral, BlockScope scope) {
- visitor.endVisit(intLiteral);
- }
- public void endVisit(Javadoc javadoc, BlockScope scope) {
- visitor.endVisit(javadoc);
- }
- public void endVisit(Javadoc javadoc, ClassScope scope) {
- visitor.endVisit(javadoc);
- }
- public void endVisit(JavadocAllocationExpression expression, BlockScope scope) {
- visitor.endVisit(expression);
- }
- public void endVisit(JavadocAllocationExpression expression, ClassScope scope) {
- visitor.endVisit(expression);
- }
- public void endVisit(JavadocArgumentExpression expression, BlockScope scope) {
- visitor.endVisit(expression);
- }
- public void endVisit(JavadocArgumentExpression expression, ClassScope scope) {
- visitor.endVisit(expression);
- }
- public void endVisit(JavadocArrayQualifiedTypeReference typeRef, BlockScope scope) {
- visitor.endVisit(typeRef);
- }
- public void endVisit(JavadocArrayQualifiedTypeReference typeRef, ClassScope scope) {
- visitor.endVisit(typeRef);
- }
- public void endVisit(JavadocArraySingleTypeReference typeRef, BlockScope scope) {
- visitor.endVisit(typeRef);
- }
- public void endVisit(JavadocArraySingleTypeReference typeRef, ClassScope scope) {
- visitor.endVisit(typeRef);
- }
- public void endVisit(JavadocFieldReference fieldRef, BlockScope scope) {
- visitor.endVisit(fieldRef);
- }
- public void endVisit(JavadocFieldReference fieldRef, ClassScope scope) {
- visitor.endVisit(fieldRef);
- }
- public void endVisit(JavadocImplicitTypeReference implicitTypeReference, BlockScope scope) {
- visitor.endVisit(implicitTypeReference);
- }
- public void endVisit(JavadocImplicitTypeReference implicitTypeReference, ClassScope scope) {
- visitor.endVisit(implicitTypeReference);
- }
- public void endVisit(JavadocMessageSend messageSend, BlockScope scope) {
- visitor.endVisit(messageSend);
- }
- public void endVisit(JavadocMessageSend messageSend, ClassScope scope) {
- visitor.endVisit(messageSend);
- }
- public void endVisit(JavadocQualifiedTypeReference typeRef, BlockScope scope) {
- visitor.endVisit(typeRef);
- }
- public void endVisit(JavadocQualifiedTypeReference typeRef, ClassScope scope) {
- visitor.endVisit(typeRef);
- }
- public void endVisit(JavadocReturnStatement statement, BlockScope scope) {
- visitor.endVisit(statement);
- }
- public void endVisit(JavadocReturnStatement statement, ClassScope scope) {
- visitor.endVisit(statement);
- }
- public void endVisit(JavadocSingleNameReference argument, BlockScope scope) {
- visitor.endVisit(argument);
- }
- public void endVisit(JavadocSingleNameReference argument, ClassScope scope) {
- visitor.endVisit(argument);
- }
- public void endVisit(JavadocSingleTypeReference typeRef, BlockScope scope) {
- visitor.endVisit(typeRef);
- }
- public void endVisit(JavadocSingleTypeReference typeRef, ClassScope scope) {
- visitor.endVisit(typeRef);
- }
- public void endVisit(LabeledStatement labeledStatement, BlockScope scope) {
- visitor.endVisit(labeledStatement);
- }
- public void endVisit(LocalDeclaration localDeclaration, BlockScope scope) {
- visitor.endVisit(localDeclaration);
- }
- public void endVisit(ListExpression listDeclaration, BlockScope scope) {
- visitor.endVisit(listDeclaration);
- }
- public void endVisit(MessageSend messageSend, BlockScope scope) {
- visitor.endVisit(messageSend);
- }
- public void endVisit(MethodDeclaration methodDeclaration, Scope scope) {
- visitor.endVisit(methodDeclaration);
- }
- public void endVisit(StringLiteralConcatenation literal, BlockScope scope) {
- visitor.endVisit(literal);
- }
- public void endVisit(NullLiteral nullLiteral, BlockScope scope) {
- visitor.endVisit(nullLiteral);
- }
- public void endVisit(OR_OR_Expression or_or_Expression, BlockScope scope) {
- visitor.endVisit(or_or_Expression);
- }
- public void endVisit(PostfixExpression postfixExpression, BlockScope scope) {
- visitor.endVisit(postfixExpression);
- }
- public void endVisit(PrefixExpression prefixExpression, BlockScope scope) {
- visitor.endVisit(prefixExpression);
- }
- public void endVisit(
- QualifiedAllocationExpression qualifiedAllocationExpression,
- BlockScope scope) {
- visitor.endVisit(qualifiedAllocationExpression);
- }
- public void endVisit(
- QualifiedNameReference qualifiedNameReference,
- BlockScope scope) {
- visitor.endVisit(qualifiedNameReference);
- }
- public void endVisit(
- QualifiedNameReference qualifiedNameReference,
- ClassScope scope) {
- visitor.endVisit(qualifiedNameReference);
- }
- public void endVisit(
- QualifiedThisReference qualifiedThisReference,
- BlockScope scope) {
- visitor.endVisit(qualifiedThisReference);
- }
- public void endVisit(
- QualifiedThisReference qualifiedThisReference,
- ClassScope scope) {
- visitor.endVisit(qualifiedThisReference);
- }
- public void endVisit(
- QualifiedTypeReference qualifiedTypeReference,
- BlockScope scope) {
- visitor.endVisit(qualifiedTypeReference);
- }
- public void endVisit(
- QualifiedTypeReference qualifiedTypeReference,
- ClassScope scope) {
- visitor.endVisit(qualifiedTypeReference);
- }
-
- public void endVisit(RegExLiteral stringLiteral, BlockScope scope) {
- visitor.endVisit(stringLiteral);
- }
-
-
- public void endVisit(ReturnStatement returnStatement, BlockScope scope) {
- visitor.endVisit(returnStatement);
- }
- public void endVisit(
- SingleNameReference singleNameReference,
- BlockScope scope) {
- visitor.endVisit(singleNameReference);
- }
- public void endVisit(
- SingleNameReference singleNameReference,
- ClassScope scope) {
- visitor.endVisit(singleNameReference);
- }
- public void endVisit(
- SingleTypeReference singleTypeReference,
- BlockScope scope) {
- visitor.endVisit(singleTypeReference);
- }
- public void endVisit(
- SingleTypeReference singleTypeReference,
- ClassScope scope) {
- visitor.endVisit(singleTypeReference);
- }
- public void endVisit(StringLiteral stringLiteral, BlockScope scope) {
- visitor.endVisit(stringLiteral);
- }
- public void endVisit(SuperReference superReference, BlockScope scope) {
- visitor.endVisit(superReference);
- }
- public void endVisit(SwitchStatement switchStatement, BlockScope scope) {
- visitor.endVisit(switchStatement);
- }
-
- public void endVisit(ThisReference thisReference, BlockScope scope) {
- visitor.endVisit(thisReference);
- }
- public void endVisit(ThisReference thisReference, ClassScope scope) {
- visitor.endVisit(thisReference);
- }
- public void endVisit(ThrowStatement throwStatement, BlockScope scope) {
- visitor.endVisit(throwStatement);
- }
- public void endVisit(TrueLiteral trueLiteral, BlockScope scope) {
- visitor.endVisit(trueLiteral);
- }
- public void endVisit(TryStatement tryStatement, BlockScope scope) {
- visitor.endVisit(tryStatement);
- }
- public void endVisit(
- TypeDeclaration localTypeDeclaration,
- BlockScope scope) {
- visitor.endVisit(localTypeDeclaration);
- }
- public void endVisit(
- TypeDeclaration memberTypeDeclaration,
- ClassScope scope) {
- visitor.endVisit(memberTypeDeclaration);
- }
- public void endVisit(
- TypeDeclaration typeDeclaration,
- CompilationUnitScope scope) {
- visitor.endVisit(typeDeclaration);
- }
- public void endVisit(UnaryExpression unaryExpression, BlockScope scope) {
- visitor.endVisit(unaryExpression);
- }
- public void endVisit(UndefinedLiteral undefinedLiteral, BlockScope scope) {
- visitor.endVisit(undefinedLiteral);
- }
-
- public void endVisit(WhileStatement whileStatement, BlockScope scope) {
- visitor.endVisit(whileStatement);
- }
- public void endVisit(WithStatement whileStatement, BlockScope scope) {
- visitor.endVisit(whileStatement);
- }
- public boolean visit(
- AllocationExpression allocationExpression,
- BlockScope scope) {
- return visitor.visit(allocationExpression);
- }
- public boolean visit(AND_AND_Expression and_and_Expression, BlockScope scope) {
- return visitor.visit(and_and_Expression);
- }
- public boolean visit(Argument argument, BlockScope scope) {
- return visitor.visit(argument);
- }
- public boolean visit(Argument argument, ClassScope scope) {
- return visitor.visit(argument);
- }
- public boolean visit(
- ArrayAllocationExpression arrayAllocationExpression,
- BlockScope scope) {
- return visitor.visit(arrayAllocationExpression);
- }
- public boolean visit(ArrayInitializer arrayInitializer, BlockScope scope) {
- return visitor.visit(arrayInitializer);
- }
- public boolean visit(
- ArrayQualifiedTypeReference arrayQualifiedTypeReference,
- BlockScope scope) {
- return visitor.visit(arrayQualifiedTypeReference);
- }
- public boolean visit(
- ArrayQualifiedTypeReference arrayQualifiedTypeReference,
- ClassScope scope) {
- return visitor.visit(arrayQualifiedTypeReference);
- }
- public boolean visit(ArrayReference arrayReference, BlockScope scope) {
- return visitor.visit(arrayReference);
- }
- public boolean visit(ArrayTypeReference arrayTypeReference, BlockScope scope) {
- return visitor.visit(arrayTypeReference);
- }
- public boolean visit(ArrayTypeReference arrayTypeReference, ClassScope scope) {
- return visitor.visit(arrayTypeReference);
- }
- public boolean visit(Assignment assignment, BlockScope scope) {
- return visitor.visit(assignment);
- }
- public boolean visit(BinaryExpression binaryExpression, BlockScope scope) {
- return visitor.visit(binaryExpression);
- }
- public boolean visit(Block block, BlockScope scope) {
- return visitor.visit(block);
- }
- public boolean visit(BreakStatement breakStatement, BlockScope scope) {
- return visitor.visit(breakStatement);
- }
- public boolean visit(CaseStatement caseStatement, BlockScope scope) {
- return visitor.visit(caseStatement);
- }
-
- public boolean visit(
- CompilationUnitDeclaration compilationUnitDeclaration,
- CompilationUnitScope scope) {
- return visitor.visit(compilationUnitDeclaration);
- }
- public boolean visit(CompoundAssignment compoundAssignment, BlockScope scope) {
- return visitor.visit(compoundAssignment);
- }
- public boolean visit(
- ConditionalExpression conditionalExpression,
- BlockScope scope) {
- return visitor.visit(conditionalExpression);
- }
- public boolean visit(
- ConstructorDeclaration constructorDeclaration,
- ClassScope scope) {
- return visitor.visit(constructorDeclaration);
- }
- public boolean visit(ContinueStatement continueStatement, BlockScope scope) {
- return visitor.visit(continueStatement);
- }
- public boolean visit(DoStatement doStatement, BlockScope scope) {
- return visitor.visit(doStatement);
- }
- public boolean visit(DoubleLiteral doubleLiteral, BlockScope scope) {
- return visitor.visit(doubleLiteral);
- }
- public boolean visit(EmptyStatement emptyStatement, BlockScope scope) {
- return visitor.visit(emptyStatement);
- }
- public boolean visit(EqualExpression equalExpression, BlockScope scope) {
- return visitor.visit(equalExpression);
- }
- public boolean visit(
- ExplicitConstructorCall explicitConstructor,
- BlockScope scope) {
- return visitor.visit(explicitConstructor);
- }
- public boolean visit(
- ExtendedStringLiteral extendedStringLiteral,
- BlockScope scope) {
- return visitor.visit(extendedStringLiteral);
- }
- public boolean visit(FalseLiteral falseLiteral, BlockScope scope) {
- return visitor.visit(falseLiteral);
- }
- public boolean visit(FieldDeclaration fieldDeclaration, MethodScope scope) {
- return visitor.visit(fieldDeclaration);
- }
- public boolean visit(FieldReference fieldReference, BlockScope scope) {
- return visitor.visit(fieldReference);
- }
- public boolean visit(FieldReference fieldReference, ClassScope scope) {
- return visitor.visit(fieldReference);
- }
- public boolean visit(ForeachStatement forStatement, BlockScope scope) {
- return visitor.visit(forStatement);
- }
- public boolean visit(ForInStatement forInStatement, BlockScope scope) {
- return visitor.visit(forInStatement);
- }
- public boolean visit(ForStatement forStatement, BlockScope scope) {
- return visitor.visit(forStatement);
- }
- public boolean visit(FunctionExpression functionExpression, BlockScope scope) {
- return visitor.visit(functionExpression);
- }
- public boolean visit(IfStatement ifStatement, BlockScope scope) {
- return visitor.visit(ifStatement);
- }
- public boolean visit(ImportReference importRef, CompilationUnitScope scope) {
- return visitor.visit(importRef);
- }
-
- public boolean visit(InferredType inferredType, BlockScope scope) {
- return visitor.visit(inferredType);
- }
-
- public boolean visit(InferredMethod inferredMethod, BlockScope scope) {
- return visitor.visit(inferredMethod);
- }
-
- public boolean visit(InferredAttribute inferredField, BlockScope scope) {
- return visitor.visit(inferredField);
- }
- public boolean visit(Initializer initializer, MethodScope scope) {
- return visitor.visit(initializer);
- }
- public boolean visit(
- InstanceOfExpression instanceOfExpression,
- BlockScope scope) {
- return visitor.visit(instanceOfExpression);
- }
- public boolean visit(IntLiteral intLiteral, BlockScope scope) {
- return visitor.visit(intLiteral);
- }
- public boolean visit(Javadoc javadoc, BlockScope scope) {
- return visitor.visit(javadoc);
- }
- public boolean visit(Javadoc javadoc, ClassScope scope) {
- return visitor.visit(javadoc);
- }
- public boolean visit(JavadocAllocationExpression expression, BlockScope scope) {
- return visitor.visit(expression);
- }
- public boolean visit(JavadocAllocationExpression expression, ClassScope scope) {
- return visitor.visit(expression);
- }
- public boolean visit(JavadocArgumentExpression expression, BlockScope scope) {
- return visitor.visit(expression);
- }
- public boolean visit(JavadocArgumentExpression expression, ClassScope scope) {
- return visitor.visit(expression);
- }
- public boolean visit(JavadocArrayQualifiedTypeReference typeRef, BlockScope scope) {
- return visitor.visit(typeRef);
- }
- public boolean visit(JavadocArrayQualifiedTypeReference typeRef, ClassScope scope) {
- return visitor.visit(typeRef);
- }
- public boolean visit(JavadocArraySingleTypeReference typeRef, BlockScope scope) {
- return visitor.visit(typeRef);
- }
- public boolean visit(JavadocArraySingleTypeReference typeRef, ClassScope scope) {
- return visitor.visit(typeRef);
- }
- public boolean visit(JavadocFieldReference fieldRef, BlockScope scope) {
- return visitor.visit(fieldRef);
- }
- public boolean visit(JavadocFieldReference fieldRef, ClassScope scope) {
- return visitor.visit(fieldRef);
- }
- public boolean visit(JavadocImplicitTypeReference implicitTypeReference, BlockScope scope) {
- return visitor.visit(implicitTypeReference);
- }
- public boolean visit(JavadocImplicitTypeReference implicitTypeReference, ClassScope scope) {
- return visitor.visit(implicitTypeReference);
- }
- public boolean visit(JavadocMessageSend messageSend, BlockScope scope) {
- return visitor.visit(messageSend);
- }
- public boolean visit(JavadocMessageSend messageSend, ClassScope scope) {
- return visitor.visit(messageSend);
- }
- public boolean visit(JavadocQualifiedTypeReference typeRef, BlockScope scope) {
- return visitor.visit(typeRef);
- }
- public boolean visit(JavadocQualifiedTypeReference typeRef, ClassScope scope) {
- return visitor.visit(typeRef);
- }
- public boolean visit(JavadocReturnStatement statement, BlockScope scope) {
- return visitor.visit(statement);
- }
- public boolean visit(JavadocReturnStatement statement, ClassScope scope) {
- return visitor.visit(statement);
- }
- public boolean visit(JavadocSingleNameReference argument, BlockScope scope) {
- return visitor.visit(argument);
- }
- public boolean visit(JavadocSingleNameReference argument, ClassScope scope) {
- return visitor.visit(argument);
- }
- public boolean visit(JavadocSingleTypeReference typeRef, BlockScope scope) {
- return visitor.visit(typeRef);
- }
- public boolean visit(JavadocSingleTypeReference typeRef, ClassScope scope) {
- return visitor.visit(typeRef);
- }
- public boolean visit(LabeledStatement labeledStatement, BlockScope scope) {
- return visitor.visit(labeledStatement);
- }
- public boolean visit(LocalDeclaration localDeclaration, BlockScope scope) {
- return visitor.visit(localDeclaration);
- }
- public boolean visit(ListExpression listDeclaration, BlockScope scope) {
- return visitor.visit(listDeclaration);
- }
- public boolean visit(MessageSend messageSend, BlockScope scope) {
- return visitor.visit(messageSend);
- }
- public boolean visit(MethodDeclaration methodDeclaration, Scope scope) {
- return visitor.visit(methodDeclaration);
- }
- public boolean visit(
- StringLiteralConcatenation literal,
- BlockScope scope) {
- return visitor.visit(literal);
- }
- public boolean visit(NullLiteral nullLiteral, BlockScope scope) {
- return visitor.visit(nullLiteral);
- }
- public boolean visit(OR_OR_Expression or_or_Expression, BlockScope scope) {
- return visitor.visit(or_or_Expression);
- }
- public boolean visit(PostfixExpression postfixExpression, BlockScope scope) {
- return visitor.visit(postfixExpression);
- }
- public boolean visit(PrefixExpression prefixExpression, BlockScope scope) {
- return visitor.visit(prefixExpression);
- }
- public boolean visit(
- QualifiedAllocationExpression qualifiedAllocationExpression,
- BlockScope scope) {
- return visitor.visit(qualifiedAllocationExpression);
- }
- public boolean visit(
- QualifiedNameReference qualifiedNameReference,
- BlockScope scope) {
- return visitor.visit(qualifiedNameReference);
- }
- public boolean visit(
- QualifiedNameReference qualifiedNameReference,
- ClassScope scope) {
- return visitor.visit(qualifiedNameReference);
- }
- public boolean visit(
- QualifiedThisReference qualifiedThisReference,
- BlockScope scope) {
- return visitor.visit(qualifiedThisReference);
- }
- public boolean visit(
- QualifiedThisReference qualifiedThisReference,
- ClassScope scope) {
- return visitor.visit(qualifiedThisReference);
- }
- public boolean visit(
- QualifiedTypeReference qualifiedTypeReference,
- BlockScope scope) {
- return visitor.visit(qualifiedTypeReference);
- }
- public boolean visit(
- QualifiedTypeReference qualifiedTypeReference,
- ClassScope scope) {
- return visitor.visit(qualifiedTypeReference);
- }
- public boolean visit(RegExLiteral stringLiteral, BlockScope scope) {
- return visitor.visit(stringLiteral);
- }
- public boolean visit(ReturnStatement returnStatement, BlockScope scope) {
- return visitor.visit(returnStatement);
- }
- public boolean visit(
- SingleNameReference singleNameReference,
- BlockScope scope) {
- return visitor.visit(singleNameReference);
- }
- public boolean visit(
- SingleNameReference singleNameReference,
- ClassScope scope) {
- return visitor.visit(singleNameReference);
- }
- public boolean visit(
- SingleTypeReference singleTypeReference,
- BlockScope scope) {
- return visitor.visit(singleTypeReference);
- }
- public boolean visit(
- SingleTypeReference singleTypeReference,
- ClassScope scope) {
- return visitor.visit(singleTypeReference);
- }
- public boolean visit(StringLiteral stringLiteral, BlockScope scope) {
- return visitor.visit(stringLiteral);
- }
- public boolean visit(SuperReference superReference, BlockScope scope) {
- return visitor.visit(superReference);
- }
- public boolean visit(SwitchStatement switchStatement, BlockScope scope) {
- return visitor.visit(switchStatement);
- }
-
- public boolean visit(ThisReference thisReference, BlockScope scope) {
- return visitor.visit(thisReference);
- }
- public boolean visit(ThisReference thisReference, ClassScope scope) {
- return visitor.visit(thisReference);
- }
- public boolean visit(ThrowStatement throwStatement, BlockScope scope) {
- return visitor.visit(throwStatement);
- }
- public boolean visit(TrueLiteral trueLiteral, BlockScope scope) {
- return visitor.visit(trueLiteral);
- }
- public boolean visit(TryStatement tryStatement, BlockScope scope) {
- return visitor.visit(tryStatement);
- }
- public boolean visit(
- TypeDeclaration localTypeDeclaration,
- BlockScope scope) {
- return visitor.visit(localTypeDeclaration);
- }
- public boolean visit(
- TypeDeclaration memberTypeDeclaration,
- ClassScope scope) {
- return visitor.visit(memberTypeDeclaration);
- }
- public boolean visit(
- TypeDeclaration typeDeclaration,
- CompilationUnitScope scope) {
- return visitor.visit(typeDeclaration);
- }
- public boolean visit(UnaryExpression unaryExpression, BlockScope scope) {
- return visitor.visit(unaryExpression);
- }
- public boolean visit(UndefinedLiteral undefined, BlockScope scope) {
- return visitor.visit(undefined);
- }
- public boolean visit(WhileStatement whileStatement, BlockScope scope) {
- return visitor.visit(whileStatement);
- }
- public boolean visit(WithStatement whileStatement, BlockScope scope) {
- return visitor.visit(whileStatement);
- }
- public boolean visit(ObjectLiteral literal, BlockScope scope) {
- return visitor.visit(literal);
- }
- public void endVisit(ObjectLiteral literal, BlockScope scope) {
- visitor.endVisit(literal);
- }
- public boolean visit(ObjectLiteralField field, BlockScope scope) {
- return visitor.visit(field);
- }
- public void endVisit(ObjectLiteralField field, BlockScope scope) {
- visitor.endVisit(field);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ICompilerRequestor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ICompilerRequestor.java
deleted file mode 100644
index 629d077f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ICompilerRequestor.java
+++ /dev/null
@@ -1,22 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler;
-
-/**
- * A callback interface for receiving compilation results.
- */
-public interface ICompilerRequestor {
-
- /**
- * Accept a compilation result.
- */
- public void acceptResult(CompilationResult result);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/IDebugRequestor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/IDebugRequestor.java
deleted file mode 100644
index dd75ed38..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/IDebugRequestor.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler;
-
-public interface IDebugRequestor {
-
- /*
- * Debug callback method allowing to take into account a new compilation result.
- * Any side-effect performed on the actual result might interfere with the
- * original compiler requestor, and should be prohibited.
- */
- void acceptDebugResult(CompilationResult result);
-
- /*
- * Answers true when in active mode
- */
- boolean isActive();
-
- /*
- * Activate debug callbacks
- */
- void activate();
-
- /*
- * Deactivate debug callbacks
- */
- void deactivate();
-
- /*
- * Reset debug requestor after compilation has finished
- */
- void reset();
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/IErrorHandlingPolicy.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/IErrorHandlingPolicy.java
deleted file mode 100644
index cdc19e6b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/IErrorHandlingPolicy.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler;
-
-/*
- * Handler policy is responsible to answer the 2 following
- * questions:
- * 1. should the handler stop on first problem which appears
- * to be a real error (that is, not a warning),
- * 2. should it proceed once it has gathered all problems
- *
- * The intent is that one can supply its own policy to implement
- * some interactive error handling strategy where some UI would
- * display problems and ask user if he wants to proceed or not.
- */
-
-public interface IErrorHandlingPolicy {
- boolean proceedOnErrors();
- boolean stopOnFirstError();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/IProblemFactory.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/IProblemFactory.java
deleted file mode 100644
index e185e6a7..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/IProblemFactory.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler;
-
-import java.util.Locale;
-
-import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem;
-
-/*
- * Factory used from inside the compiler to build the actual problems
- * which are handed back in the compilation result.
- *
- * This allows sharing the internal problem representation with the environment.
- *
- * Note: The factory is responsible for computing and storing a localized error message.
- */
-
-public interface IProblemFactory {
-
- CategorizedProblem createProblem(
- char[] originatingFileName,
- int problemId,
- String[] problemArguments,
- String[] messageArguments, // shorter versions of the problemArguments
- int severity,
- int startPosition,
- int endPosition,
- int lineNumber,
- int columnNumber);
-
- Locale getLocale();
-
- String getLocalizedMessage(int problemId, String[] messageArguments);
-}
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
deleted file mode 100644
index d2bf417c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ISourceElementRequestor.java
+++ /dev/null
@@ -1,142 +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.compiler;
-
-import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem;
-
-/*
- * Part of the source element parser responsible for building the output. It
- * gets notified of structural information as they are detected, relying on the
- * requestor to assemble them together, based on the notifications it got.
- *
- * The structural investigation includes: - package statement - import
- * statements - top-level types: package member, member types (member types of
- * member types...) - fields - methods
- *
- * If reference information is requested, then all source constructs are
- * investigated and type, field & method references are provided as well.
- *
- * Any (parsing) problem encountered is also provided.
- *
- * All positions are relative to the exact source fed to the parser.
- *
- * Elements which are complex are notified in two steps: - enter <Element> :
- * once the element header has been identified - exit <Element> : once the
- * element has been fully consumed
- *
- * other simpler elements (package, import) are read all at once: - accept
- * <Element>
- */
-
-public interface ISourceElementRequestor {
-
- public static class TypeInfo {
- public int declarationStart;
- public int modifiers;
- public char[] name;
- public int nameSourceStart;
- public int nameSourceEnd;
- public char[] superclass;
- public char[][] categories;
- public boolean secondary;
- public boolean anonymousMember;
- }
-
- public static class MethodInfo {
- public boolean isConstructor;
- public int declarationStart;
- public int modifiers;
- public char[] returnType;
- public char[] name;
- public int nameSourceStart;
- public int nameSourceEnd;
- public char[][] parameterTypes;
- public char[][] parameterNames;
- public char[][] categories;
- }
-
- public static class FieldInfo {
- public int declarationStart;
- public int modifiers;
- public char[] type;
- public char[] name;
- public int nameSourceStart;
- public int nameSourceEnd;
- public char[][] categories;
- }
-
- void acceptConstructorReference(char[] typeName, int argCount, int sourcePosition);
-
- void acceptFieldReference(char[] fieldName, int sourcePosition);
- /**
- * @param declarationStart
- * This is the position of the first character of the import
- * keyword.
- * @param declarationEnd
- * This is the position of the ';' ending the import statement or
- * the end of the comment following the import.
- * @param tokens
- * This are the tokens of the import like specified in the source.
- * @param onDemand
- * set to true if the import is an import on demand (e.g. import
- * java.io.*). False otherwise.
- */
- void acceptImport(int declarationStart, int declarationEnd, char[][] tokens, boolean onDemand);
-
- /*
- * Table of line separator position. This table is passed once at the end of
- * the parse action, so as to allow computation of normalized ranges.
- *
- * A line separator might corresponds to several characters in the source,
- *
- */
- void acceptLineSeparatorPositions(int[] positions);
-
- void acceptMethodReference(char[] methodName, int argCount, int sourcePosition);
-
- void acceptProblem(CategorizedProblem problem);
-
- void acceptTypeReference(char[][] typeName, int sourceStart, int sourceEnd);
-
- void acceptTypeReference(char[] typeName, int sourcePosition);
-
- void acceptUnknownReference(char[][] name, int sourceStart, int sourceEnd);
-
- void acceptUnknownReference(char[] name, int sourcePosition);
-
- void enterCompilationUnit();
-
- void enterConstructor(MethodInfo methodInfo);
-
- void enterField(FieldInfo fieldInfo);
-
- void enterInitializer(int declarationStart, int modifiers);
-
- void enterMethod(MethodInfo methodInfo);
-
- void enterType(TypeInfo typeInfo);
-
- void exitCompilationUnit(int declarationEnd);
-
- void exitConstructor(int declarationEnd);
-
- /*
- * initializationStart denotes the source start of the expression used for
- * initializing the field if any (-1 if no initialization).
- */
- void exitField(int initializationStart, int declarationEnd, int declarationSourceEnd);
-
- void exitInitializer(int declarationEnd);
-
- void exitMethod(int declarationEnd, int defaultValueStart, int defaultValueEnd);
-
- void exitType(int declarationEnd);
-}
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
deleted file mode 100644
index bf235395..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/SourceElementParser.java
+++ /dev/null
@@ -1,1451 +0,0 @@
-/*******************************************************************************
- * 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
- * bug 242694 - Michael Spector <spektom@gmail.com>
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler;
-
-import java.util.ArrayList;
-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;
-import org.eclipse.wst.jsdt.core.infer.InferredMethod;
-import org.eclipse.wst.jsdt.core.infer.InferredType;
-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.ArrayAllocationExpression;
-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.ClassLiteralAccess;
-import org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ConstructorDeclaration;
-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.FieldDeclaration;
-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.ImportReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Initializer;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocAllocationExpression;
-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.JavadocQualifiedTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocSingleTypeReference;
-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.ObjectLiteral;
-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;
-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.ThisReference;
-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.classfmt.ClassFileConstants;
-import org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit;
-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.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.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.compiler.util.HashtableOfObjectToInt;
-import org.eclipse.wst.jsdt.internal.compiler.util.Util;
-import org.eclipse.wst.jsdt.internal.core.util.CommentRecorderParser;
-
-/**
- * A source element parser extracts structural and reference information
- * from a piece of source.
- *
- * also see @ISourceElementRequestor
- *
- * The structural investigation includes:
- * - the package statement
- * - import statements
- * - top-level types: package member, member types (member types of member types...)
- * - fields
- * - methods
- *
- * If reference information is requested, then all source constructs are
- * investigated and type, field & method references are provided as well.
- *
- * Any (parsing) problem encountered is also provided.
- */
-public class SourceElementParser extends CommentRecorderParser {
-
- ISourceElementRequestor requestor;
- ISourceType sourceType;
- boolean reportReferenceInfo;
- char[][] typeNames;
- char[][] superTypeNames;
- int nestedTypeIndex;
- int nestedMethodIndex;
- LocalDeclarationVisitor localDeclarationVisitor = null;
- CompilerOptions options;
- HashtableOfObjectToInt sourceEnds = new HashtableOfObjectToInt();
- HashMap nodesToCategories = new HashMap(); // a map from ASTNode to char[][]
- boolean useSourceJavadocParser = true;
- HashtableOfObject notifiedTypes=new HashtableOfObject();
-
-
- public static final boolean NOTIFY_LOCALS=false;
-/**
- * An ast visitor that visits local type declarations.
- */
-public class LocalDeclarationVisitor extends ASTVisitor {
- ArrayList declaringTypes;
- public void pushDeclaringType(TypeDeclaration declaringType) {
- if (this.declaringTypes == null) {
- this.declaringTypes = new ArrayList();
- }
- this.declaringTypes.add(declaringType);
- }
- public void popDeclaringType() {
- this.declaringTypes.remove(this.declaringTypes.size()-1);
- }
- public TypeDeclaration peekDeclaringType() {
- if (this.declaringTypes == null) return null;
- int size = this.declaringTypes.size();
- if (size == 0) return null;
- return (TypeDeclaration) this.declaringTypes.get(size-1);
- }
- public boolean visit(TypeDeclaration typeDeclaration, BlockScope scope) {
- notifySourceElementRequestor(typeDeclaration, sourceType == null, peekDeclaringType());
- return false; // don't visit members as this was done during notifySourceElementRequestor(...)
- }
- public boolean visit(TypeDeclaration typeDeclaration, ClassScope scope) {
- notifySourceElementRequestor(typeDeclaration, sourceType == null, peekDeclaringType());
- return false; // don't visit members as this was done during notifySourceElementRequestor(...)
- }
-
- public boolean visit(MethodDeclaration methodDeclaration, Scope scope) {
- notifySourceElementRequestor(methodDeclaration);
- return false;
- }
-}
-
-
- /*
- * Visitor for current context declaration.
- *
- * A context is defined by either the top level or a closure (function)
- */
- protected ASTVisitor contextDeclarationNotifier = new ASTVisitor(){
-
- public boolean visit(LocalDeclaration localDeclaration, BlockScope scope) {
- if (NOTIFY_LOCALS || nestedMethodIndex==0)
- notifySourceElementRequestor( localDeclaration, null );
- 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 )
- notifySourceElementRequestor( methodDeclaration );
- return false;
- }
-
- /**
- * <p>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.</p>
- *
- * @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();
-
- char[] selector = Util.getTypeName(leftHandSide);
- MethodDeclaration methodDecl = ((IFunctionExpression) righHandSide).getMethodDeclaration();
- if(selector != null && methodDecl.isConstructor()) {
- notifySourceElementRequestor(methodDecl,
- selector);
- }
-
- }
- return keepVisiting;
- }
-
- public void endVisit(MethodDeclaration methodDeclaration, Scope scope) {
- nestedMethodIndex--;
-
- }
-
- };
-
-public SourceElementParser(
- final ISourceElementRequestor requestor,
- IProblemFactory problemFactory,
- CompilerOptions options,
- boolean reportLocalDeclarations,
- boolean optimizeStringLiterals) {
- this(requestor, problemFactory, options, reportLocalDeclarations, optimizeStringLiterals, true/* use SourceJavadocParser */);
-}
-
-public SourceElementParser(
- ISourceElementRequestor requestor,
- IProblemFactory problemFactory,
- CompilerOptions options,
- boolean reportLocalDeclarations,
- boolean optimizeStringLiterals,
- boolean useSourceJavadocParser) {
-
- super(
- new ProblemReporter(
- DefaultErrorHandlingPolicies.exitAfterAllProblems(),
- options,
- problemFactory),
- optimizeStringLiterals);
-
- // we want to notify all syntax error with the acceptProblem API
- // To do so, we define the record method of the ProblemReporter
- this.problemReporter = new ProblemReporter(
- DefaultErrorHandlingPolicies.exitAfterAllProblems(),
- options,
- problemFactory) {
- public void record(CategorizedProblem problem, CompilationResult unitResult, ReferenceContext context) {
- unitResult.record(problem, context); // TODO (jerome) clients are trapping problems either through factory or requestor... is result storing needed?
- SourceElementParser.this.requestor.acceptProblem(problem);
- }
- };
- this.requestor = requestor;
- typeNames = new char[4][];
- superTypeNames = new char[4][];
- nestedTypeIndex = 0;
- this.options = options;
- if (reportLocalDeclarations) {
- this.localDeclarationVisitor = new LocalDeclarationVisitor();
- }
- // set specific javadoc parser
- this.useSourceJavadocParser = useSourceJavadocParser;
- if (useSourceJavadocParser) {
- this.javadocParser = new SourceJavadocParser(this);
- }
-}
-
-public void setRequestor(ISourceElementRequestor requestor) {
- this.requestor = requestor;
- notifiedTypes.clear();
-}
-
-private void acceptJavadocTypeReference(Expression expression) {
- if (expression instanceof JavadocSingleTypeReference) {
- JavadocSingleTypeReference singleRef = (JavadocSingleTypeReference) expression;
- this.requestor.acceptTypeReference(singleRef.token, singleRef.sourceStart);
- } else if (expression instanceof JavadocQualifiedTypeReference) {
- JavadocQualifiedTypeReference qualifiedRef = (JavadocQualifiedTypeReference) expression;
- this.requestor.acceptTypeReference(qualifiedRef.tokens, qualifiedRef.sourceStart, qualifiedRef.sourceEnd);
- }
-}
-public void addUnknownRef(NameReference nameRef) {
- // Note that:
- // - the only requestor interested in references is the SourceIndexerRequestor
- // - a name reference can become a type reference only during the cast case, it is then tagged later with the Binding.TYPE bit
- // However since the indexer doesn't make the distinction between name reference and type reference, there is no need
- // to report a type reference in the SourceElementParser.
- // This gained 3.7% in the indexing performance test.
- if (nameRef instanceof SingleNameReference) {
- requestor.acceptUnknownReference(((SingleNameReference) nameRef).token, nameRef.sourceStart);
- } else {
- //QualifiedNameReference
- requestor.acceptUnknownReference(((QualifiedNameReference) nameRef).tokens, nameRef.sourceStart, nameRef.sourceEnd);
- }
-}
-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 && Math.abs(this.scanner.commentStarts[lastComment]) > this.modifiersSourceStart) lastComment--;
- }
- if (lastComment >= 0) {
- // consider all remaining leading comments to be part of current declaration
- this.modifiersSourceStart = Math.abs(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;
- }
- }
-
- if (this.reportReferenceInfo && this.javadocParser.checkDocComment && this.javadoc != null) {
- // Report reference info in javadoc comment @throws/@exception tags
- TypeReference[] thrownExceptions = this.javadoc.exceptionReferences;
- if (thrownExceptions != null) {
- for (int i = 0, max=thrownExceptions.length; i < max; i++) {
- TypeReference typeRef = thrownExceptions[i];
- if (typeRef instanceof JavadocSingleTypeReference) {
- JavadocSingleTypeReference singleRef = (JavadocSingleTypeReference) typeRef;
- this.requestor.acceptTypeReference(singleRef.token, singleRef.sourceStart);
- } else if (typeRef instanceof JavadocQualifiedTypeReference) {
- JavadocQualifiedTypeReference qualifiedRef = (JavadocQualifiedTypeReference) typeRef;
- this.requestor.acceptTypeReference(qualifiedRef.tokens, qualifiedRef.sourceStart, qualifiedRef.sourceEnd);
- }
- }
- }
-
- // Report reference info in javadoc comment @see tags
- Expression[] references = this.javadoc.seeReferences;
- if (references != null) {
- for (int i = 0, max=references.length; i < max; i++) {
- Expression reference = references[i];
- acceptJavadocTypeReference(reference);
- if (reference instanceof JavadocFieldReference) {
- JavadocFieldReference fieldRef = (JavadocFieldReference) reference;
- this.requestor.acceptFieldReference(fieldRef.token, fieldRef.sourceStart);
- if (fieldRef.receiver != null && !fieldRef.receiver.isThis()) {
- acceptJavadocTypeReference(fieldRef.receiver);
- }
- } 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.acceptConstructorReference(messageSend.selector, argCount, messageSend.sourceStart);
- if (messageSend.receiver != null && !messageSend.receiver.isThis()) {
- acceptJavadocTypeReference(messageSend.receiver);
- }
- } else if (reference instanceof JavadocAllocationExpression) {
- JavadocAllocationExpression constructor = (JavadocAllocationExpression) reference;
- int argCount = constructor.arguments == null ? 0 : constructor.arguments.length;
- if (constructor.type != null) {
- char[][] compoundName = constructor.type.getTypeName();
- this.requestor.acceptConstructorReference(compoundName[compoundName.length-1], argCount, constructor.sourceStart);
- if (!constructor.type.isThis()) {
- acceptJavadocTypeReference(constructor.type);
- }
- }
- }
- }
- }
- }
-}
-protected void classInstanceCreation(boolean alwaysQualified, boolean isShort) {
-
- boolean previousFlag = reportReferenceInfo;
- reportReferenceInfo = false; // not to see the type reference reported in super call to getTypeReference(...)
- super.classInstanceCreation(alwaysQualified, isShort);
- reportReferenceInfo = previousFlag;
- if (reportReferenceInfo){
- AllocationExpression alloc = (AllocationExpression)expressionStack[expressionPtr];
-// TypeReference typeRef = alloc.type;
- char [] name={};
- if (alloc.member !=null)
- {
- name=Util.getTypeName(alloc.member);
- }
- else if (alloc.type!=null)
- name= CharOperation.concatWith(alloc.type.getTypeName(), '.');
-
- if (name!=null && name.length>0)
- requestor.acceptConstructorReference(name,
-// typeRef instanceof SingleTypeReference
-// ? ((SingleTypeReference) typeRef).token
-// : CharOperation.concatWith(alloc.type.getParameterizedTypeName(), '.'),
- alloc.arguments == null ? 0 : alloc.arguments.length,
- alloc.sourceStart);
- }
-}
-
-protected void consumeExitVariableWithInitialization() {
- // ExitVariableWithInitialization ::= $empty
- // the scanner is located after the comma or the semi-colon.
- // we want to include the comma or the semi-colon
- super.consumeExitVariableWithInitialization();
- if ((currentToken == TokenNameCOMMA || currentToken == TokenNameSEMICOLON)
- && this.astStack[this.astPtr] instanceof FieldDeclaration) {
- this.sourceEnds.put(this.astStack[this.astPtr], this.scanner.currentPosition - 1);
- rememberCategories();
- }
-}
-protected void consumeExitVariableWithoutInitialization() {
- // ExitVariableWithoutInitialization ::= $empty
- // do nothing by default
- super.consumeExitVariableWithoutInitialization();
- if ((currentToken == TokenNameCOMMA || currentToken == TokenNameSEMICOLON)
- && astStack[astPtr] instanceof FieldDeclaration) {
- this.sourceEnds.put(this.astStack[this.astPtr], this.scanner.currentPosition - 1);
- rememberCategories();
- }
-}
-protected void consumeCallExpressionWithSimpleName() {
- super.consumeCallExpressionWithSimpleName();
- FieldReference fr = (FieldReference) expressionStack[expressionPtr];
- if (reportReferenceInfo) {
- requestor.acceptFieldReference(fr.token, fr.sourceStart);
- }
-
-}
-protected void consumeMemberExpressionWithSimpleName() {
- super.consumeMemberExpressionWithSimpleName();
- FieldReference fr = (FieldReference) expressionStack[expressionPtr];
- if (reportReferenceInfo) {
- requestor.acceptFieldReference(fr.token, fr.sourceStart);
- }
-
-}
-protected void consumeFormalParameter(boolean isVarArgs) {
- super.consumeFormalParameter(isVarArgs);
-
- // Flush comments prior to this formal parameter so the declarationSourceStart of the following parameter
- // is correctly set (see bug 80904)
- // Note that this could be done in the Parser itself, but this would slow down all parsers, when they don't need
- // the declarationSourceStart to be set
- flushCommentsDefinedPriorTo(this.scanner.currentPosition);
-}
-protected void consumeMethodHeaderName(boolean isAnonymousMethod) {
- long selectorSourcePositions = (isAnonymousMethod) ? this.lParenPos
- :this.identifierPositionStack[this.identifierPtr];
- int selectorSourceEnd = (int) selectorSourcePositions;
- int currentAstPtr = this.astPtr;
- super.consumeMethodHeaderName(isAnonymousMethod);
- if (this.astPtr > currentAstPtr) { // if ast node was pushed on the ast stack
- this.sourceEnds.put(this.astStack[this.astPtr], selectorSourceEnd);
- rememberCategories();
- }
-}
-protected void consumeCallExpressionWithArguments() {
- super.consumeCallExpressionWithArguments();
- MessageSend messageSend = (MessageSend) expressionStack[expressionPtr];
- Expression[] args = messageSend.arguments;
- if (reportReferenceInfo) {
- requestor.acceptMethodReference(
- messageSend.selector,
- args == null ? 0 : args.length,
- (int)(messageSend.nameSourcePosition >>> 32));
- }
-}
-public MethodDeclaration convertToMethodDeclaration(ConstructorDeclaration c, CompilationResult compilationResult) {
- MethodDeclaration methodDeclaration = super.convertToMethodDeclaration(c, compilationResult);
- int selectorSourceEnd = this.sourceEnds.removeKey(c);
- if (selectorSourceEnd != -1)
- this.sourceEnds.put(methodDeclaration, selectorSourceEnd);
- char[][] categories = (char[][]) this.nodesToCategories.remove(c);
- if (categories != null)
- this.nodesToCategories.put(methodDeclaration, categories);
-
- return methodDeclaration;
-}
-protected CompilationUnitDeclaration endParse(int act) {
- if (compilationUnit != null) {
- CompilationUnitDeclaration result = super.endParse(act);
- return result;
- } else {
- return null;
- }
-}
-public 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
- */
- int length = identifierLengthStack[identifierLengthPtr--];
- if (length < 0) { //flag for precompiled type reference on base types
- TypeReference ref = TypeReference.baseTypeReference(-length, dim);
- ref.sourceStart = intStack[intPtr--];
- if (dim == 0) {
- ref.sourceEnd = intStack[intPtr--];
- } else {
- intPtr--; // no need to use this position as it is an array
- ref.sourceEnd = endPosition;
- }
- if (reportReferenceInfo){
- requestor.acceptTypeReference(ref.getTypeName(), ref.sourceStart, ref.sourceEnd);
- }
- return ref;
- } else {
- int numberOfIdentifiers = this.genericsIdentifiersLengthStack[this.genericsIdentifiersLengthPtr--];
- if (length != numberOfIdentifiers || this.genericsLengthStack[this.genericsLengthPtr] != 0) {
- // generic type
- TypeReference ref = null;
- return ref;
- } else if (length == 1) {
- // single variable reference
- this.genericsLengthPtr--; // pop the 0
- if (dim == 0) {
- SingleTypeReference ref =
- new SingleTypeReference(
- identifierStack[identifierPtr],
- identifierPositionStack[identifierPtr--]);
- if (reportReferenceInfo) {
- requestor.acceptTypeReference(ref.token, ref.sourceStart);
- }
- return ref;
- } else {
- ArrayTypeReference ref =
- new ArrayTypeReference(
- identifierStack[identifierPtr],
- dim,
- identifierPositionStack[identifierPtr--]);
- ref.sourceEnd = endPosition;
- if (reportReferenceInfo) {
- requestor.acceptTypeReference(ref.token, ref.sourceStart);
- }
- return ref;
- }
- } else {//Qualified variable reference
- this.genericsLengthPtr--;
- char[][] tokens = new char[length][];
- identifierPtr -= length;
- long[] positions = new long[length];
- System.arraycopy(identifierStack, identifierPtr + 1, tokens, 0, length);
- System.arraycopy(
- identifierPositionStack,
- identifierPtr + 1,
- positions,
- 0,
- length);
- if (dim == 0) {
- QualifiedTypeReference ref = new QualifiedTypeReference(tokens, positions);
- if (reportReferenceInfo) {
- requestor.acceptTypeReference(ref.tokens, ref.sourceStart, ref.sourceEnd);
- }
- return ref;
- } else {
- ArrayQualifiedTypeReference ref =
- new ArrayQualifiedTypeReference(tokens, dim, positions);
- ref.sourceEnd = endPosition;
- if (reportReferenceInfo) {
- requestor.acceptTypeReference(ref.tokens, ref.sourceStart, ref.sourceEnd);
- }
- return ref;
- }
- }
- }
-}
-public NameReference getUnspecifiedReference() {
- /* build a (unspecified) NameReference which may be qualified*/
-
- int length;
- if ((length = identifierLengthStack[identifierLengthPtr--]) == 1) {
- // single variable reference
- SingleNameReference ref =
- newSingleNameReference(
- identifierStack[identifierPtr],
- identifierPositionStack[identifierPtr--]);
- if (reportReferenceInfo) {
- this.addUnknownRef(ref);
- }
- return ref;
- } else {
- //Qualified variable reference
- char[][] tokens = new char[length][];
- identifierPtr -= length;
- System.arraycopy(identifierStack, identifierPtr + 1, tokens, 0, length);
- long[] positions = new long[length];
- System.arraycopy(identifierPositionStack, identifierPtr + 1, positions, 0, length);
- QualifiedNameReference ref =
- newQualifiedNameReference(
- tokens,
- positions,
- (int) (identifierPositionStack[identifierPtr + 1] >> 32), // sourceStart
- (int) identifierPositionStack[identifierPtr + length]); // sourceEnd
- if (reportReferenceInfo) {
- this.addUnknownRef(ref);
- }
- return ref;
- }
-}
-public 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;
- if ((length = identifierLengthStack[identifierLengthPtr--]) == 1) {
- // single variable reference
- SingleNameReference ref =
- newSingleNameReference(
- identifierStack[identifierPtr],
- identifierPositionStack[identifierPtr--]);
- ref.bits &= ~ASTNode.RestrictiveFlagMASK;
- ref.bits |= Binding.LOCAL | Binding.FIELD;
- if (reportReferenceInfo) {
- this.addUnknownRef(ref);
- }
- 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][];
- identifierPtr -= length;
- System.arraycopy(identifierStack, identifierPtr + 1, tokens, 0, length);
- long[] positions = new long[length];
- System.arraycopy(identifierPositionStack, identifierPtr + 1, positions, 0, length);
- QualifiedNameReference ref =
- newQualifiedNameReference(
- tokens,
- positions,
- (int) (identifierPositionStack[identifierPtr + 1] >> 32),
- // sourceStart
- (int) identifierPositionStack[identifierPtr + length]); // sourceEnd
- ref.bits &= ~ASTNode.RestrictiveFlagMASK;
- ref.bits |= Binding.LOCAL | Binding.FIELD;
- if (reportReferenceInfo) {
- this.addUnknownRef(ref);
- }
- return ref;
-}
-
-protected ImportReference newImportReference(char[][] tokens, long[] positions, boolean onDemand) {
- return new ImportReference(tokens, positions, onDemand);
-}
-protected QualifiedNameReference newQualifiedNameReference(char[][] tokens, long[] positions, int sourceStart, int sourceEnd) {
- return new QualifiedNameReference(tokens, positions, sourceStart, sourceEnd);
-}
-protected SingleNameReference newSingleNameReference(char[] source, long positions) {
- return new SingleNameReference(source, positions);
-}
-
-
-
-/*
- * Update the bodyStart of the corresponding parse node
- */
-public void notifySourceElementRequestor(CompilationUnitDeclaration parsedUnit) {
- if (parsedUnit == null) {
- // when we parse a single type member declaration the compilation unit is null, but we still
- // want to be able to notify the requestor on the created ast node
- if (astStack[0] instanceof AbstractMethodDeclaration) {
- notifySourceElementRequestor((AbstractMethodDeclaration) astStack[0]);
- return;
- }
- return;
- }
-
- inferTypes(parsedUnit,this.options);
-
- // range check
- boolean isInRange =
- scanner.initialPosition <= parsedUnit.sourceStart
- && scanner.eofPosition >= parsedUnit.sourceEnd;
-
- // collect the top level ast nodes
- if (sourceType == null){
- if (isInRange) {
- requestor.enterCompilationUnit();
- }
- }
-
- //visit each statement to notify context declarations
- if( parsedUnit.statements != null ){
-
- for( int i=0; i<parsedUnit.statements.length; i++ ){
- parsedUnit.statements[i].traverse( contextDeclarationNotifier, parsedUnit.scope );
- }
-
- }
-
- for (int inx=0;inx<parsedUnit.numberInferredTypes;inx++) {
- InferredType type = parsedUnit.inferredTypes[inx];
-
- notifySourceElementRequestor(type);
- }
-
- if (sourceType == null){
- if (isInRange) {
- requestor.exitCompilationUnit(parsedUnit.sourceEnd);
- }
- }
-}
-
-public void notifySourceElementRequestor( InferredType type ) {
-
- if ( !type.isDefinition || type.isEmptyGlobal())
- return;
-
- if (type.isAnonymous && !type.isNamed() && !type.isObjectLiteral)
- return;
- // prevent possible recurrsion
- if (notifiedTypes.containsKey(type.getName()))
- return;
- notifiedTypes.put(type.getName(), null);
-
-
- ISourceElementRequestor.TypeInfo typeInfo = new ISourceElementRequestor.TypeInfo();
- typeInfo.declarationStart = type.sourceStart;
- typeInfo.modifiers = 0;
-
- typeInfo.name = type.getName();
-
- typeInfo.nameSourceStart = type.getNameStart();
- if(type.isObjectLiteral) {
- typeInfo.nameSourceEnd = type.sourceEnd;
- } else {
- typeInfo.nameSourceEnd = typeInfo.nameSourceStart+typeInfo.name.length-1;
- }
- typeInfo.superclass = type.getSuperClassName();
- typeInfo.secondary = false;
-
- typeInfo.anonymousMember = type.isAnonymous;
-
- requestor.enterType(typeInfo);
-
- for (int attributeInx=0; attributeInx<type.numberAttributes; attributeInx++) {
- InferredAttribute field = type.attributes[attributeInx];
- ISourceElementRequestor.FieldInfo fieldInfo = new ISourceElementRequestor.FieldInfo();
- fieldInfo.declarationStart = field.sourceStart();
- fieldInfo.name = field.name;
- fieldInfo.modifiers = field.modifiers;
-
- if (field.isStatic)
- fieldInfo.modifiers |= ClassFileConstants.AccStatic;
- fieldInfo.nameSourceStart = field.nameStart;
- fieldInfo.nameSourceEnd = field.nameStart+field.name.length-1;
-
- fieldInfo.type = field.type!=null ? field.type.getName():null;
- requestor.enterField(fieldInfo);
-
- //If this field is of an anonymous type, need to notify so that it shows as a child
- if( field.type != null && field.type.isAnonymous && !field.type.isNamed() ){
- notifySourceElementRequestor( field.type );
- }
-
- int initializationStart=field.initializationStart;
- requestor.exitField(initializationStart,field.sourceEnd(),field.sourceEnd());
- }
-
- if (type.methods!=null)
- for (Iterator iterator = type.methods.iterator(); iterator.hasNext();) {
- InferredMethod method = (InferredMethod) iterator.next();
-
- ISourceElementRequestor.MethodInfo methodInfo = new ISourceElementRequestor.MethodInfo();
- methodInfo.isConstructor = method.isConstructor;
- MethodDeclaration methodDeclaration=(MethodDeclaration)method.getFunctionDeclaration();
-
- char[][] argumentTypes = null;
- char[][] argumentNames = null;
- Argument[] arguments = methodDeclaration.arguments;
- if (arguments != null) {
- int argumentLength = arguments.length;
- argumentTypes = new char[argumentLength][];
- argumentNames = new char[argumentLength][];
- for (int i = 0; i < argumentLength; i++) {
- if (arguments[i].type!=null) {
- argumentTypes[i] = CharOperation.concatWith(arguments[i].type.getTypeName(), '.');
- } else if(arguments[i].inferredType != null) {
- argumentTypes[i] = arguments[i].inferredType.getName();
- }
- argumentNames[i] = arguments[i].name;
- }
- }
- methodInfo.declarationStart = methodDeclaration.declarationSourceStart;
- methodInfo.modifiers = methodDeclaration.modifiers;
- if (method.isStatic) {
- methodInfo.modifiers |= ClassFileConstants.AccStatic;
- }
- methodInfo.returnType = methodDeclaration.inferredType == null ?
- null : methodDeclaration.inferredType.getName();
- methodInfo.name =method.name;
- methodInfo.nameSourceStart = method.nameStart;
- methodInfo.nameSourceEnd = method.nameStart+method.name.length-1;
- methodInfo.parameterTypes = argumentTypes;
- methodInfo.parameterNames = argumentNames;
- methodInfo.categories = (char[][]) this.nodesToCategories.get(methodDeclaration);
-
- //enter either constructor or method where appropriate
- if(methodInfo.isConstructor) {
- requestor.enterConstructor(methodInfo);
- } else {
- requestor.enterMethod(methodInfo);
- }
-
- visitIfNeeded( (MethodDeclaration)method.getFunctionDeclaration() );
-
- requestor.exitMethod(methodDeclaration.declarationSourceEnd, -1, -1);
-
- }
-
-
- requestor.exitType(type.sourceEnd);
-
-}
-
-/**
- * <p>Notifies the requester of a method declaration using the {@link AbstractMethodDeclaration#selector} as the
- * selector to notify with.</p>
- *
- * @param methodDeclaration to notify the requester of
- *
- * @see #notifySourceElementRequestor(AbstractMethodDeclaration, char[])
- */
-public void notifySourceElementRequestor(AbstractMethodDeclaration methodDeclaration) {
- this.notifySourceElementRequestor(methodDeclaration, methodDeclaration.selector);
-}
-
-/**
- * <p>Notifies the requester of a method declaration using the given selector rather then the selector set
- * on the declaration itself.</p>
- *
- * <p>This is useful when the selector on the declaration is not set but it can be pre-determined some other way.</p>
- *
- * @param methodDeclaration to notify the requester of
- * @param selector to use when notifying the requester of the given <code>methodDeclaration</code>
- */
-public void notifySourceElementRequestor(AbstractMethodDeclaration methodDeclaration, char[] selector) {
-
- this.nestedMethodIndex++;
- // range check
- boolean isInRange =
- scanner.initialPosition <= methodDeclaration.declarationSourceStart
- && scanner.eofPosition >= methodDeclaration.declarationSourceEnd;
-
- if (methodDeclaration.isClinit()) {
- this.visitIfNeeded(methodDeclaration);
- this.nestedMethodIndex--;
- return;
- }
-
- if (methodDeclaration.isDefaultConstructor()) {
- if (reportReferenceInfo) {
- ConstructorDeclaration constructorDeclaration = (ConstructorDeclaration) methodDeclaration;
- ExplicitConstructorCall constructorCall = constructorDeclaration.constructorCall;
- if (constructorCall != null) {
- switch(constructorCall.accessMode) {
- case ExplicitConstructorCall.This :
- requestor.acceptConstructorReference(
- typeNames[nestedTypeIndex-1],
- constructorCall.arguments == null ? 0 : constructorCall.arguments.length,
- constructorCall.sourceStart);
- break;
- case ExplicitConstructorCall.ImplicitSuper :
- requestor.acceptConstructorReference(
- superTypeNames[nestedTypeIndex-1],
- constructorCall.arguments == null ? 0 : constructorCall.arguments.length,
- constructorCall.sourceStart);
- break;
- }
- }
- }
- this.nestedMethodIndex--;
- return;
- }
- char[][] argumentTypes = null;
- char[][] argumentNames = null;
- boolean isVarArgs = false;
- Argument[] arguments = methodDeclaration.arguments;
- if (arguments != null) {
- int argumentLength = arguments.length;
- argumentTypes = new char[argumentLength][];
- argumentNames = new char[argumentLength][];
- for (int i = 0; i < argumentLength; i++) {
- if (arguments[i].type!=null) {
- argumentTypes[i] = CharOperation.concatWith(arguments[i].type.getTypeName(), '.');
- } else if(arguments[i].inferredType != null) {
- argumentTypes[i] = arguments[i].inferredType.getName();
- }
- argumentNames[i] = arguments[i].name;
- }
- isVarArgs = arguments[argumentLength-1].isVarArgs();
- }
- // by default no selector end position
- int selectorSourceEnd = -1;
- if (methodDeclaration.isConstructor()) {
- selectorSourceEnd = this.sourceEnds.get(methodDeclaration);
- if (isInRange){
- int currentModifiers = methodDeclaration.modifiers;
- if (isVarArgs)
- currentModifiers |= ClassFileConstants.AccVarargs;
-
- // remember deprecation so as to not lose it below
- boolean deprecated = (currentModifiers & ClassFileConstants.AccDeprecated) != 0;
-
- ISourceElementRequestor.MethodInfo methodInfo = new ISourceElementRequestor.MethodInfo();
- methodInfo.isConstructor = true;
- methodInfo.declarationStart = methodDeclaration.declarationSourceStart;
- methodInfo.modifiers = deprecated ? (currentModifiers & ExtraCompilerModifiers.AccJustFlag) | ClassFileConstants.AccDeprecated : currentModifiers & ExtraCompilerModifiers.AccJustFlag;
- methodInfo.name = selector;
- methodInfo.nameSourceStart = methodDeclaration.sourceStart;
- methodInfo.nameSourceEnd = selectorSourceEnd;
- methodInfo.parameterTypes = argumentTypes;
- methodInfo.parameterNames = argumentNames;
- methodInfo.categories = (char[][]) this.nodesToCategories.get(methodDeclaration);
- requestor.enterConstructor(methodInfo);
- }
- /* need this check because a constructor could have been made a constructor after the
- * method declaration was created, and thus it is not a ConstructorDeclaration
- */
- if (reportReferenceInfo && methodDeclaration instanceof ConstructorDeclaration) {
- ConstructorDeclaration constructorDeclaration = (ConstructorDeclaration) methodDeclaration;
- ExplicitConstructorCall constructorCall = constructorDeclaration.constructorCall;
- if (constructorCall != null) {
- switch(constructorCall.accessMode) {
- case ExplicitConstructorCall.This :
- requestor.acceptConstructorReference(
- typeNames[nestedTypeIndex-1],
- constructorCall.arguments == null ? 0 : constructorCall.arguments.length,
- constructorCall.sourceStart);
- break;
- case ExplicitConstructorCall.ImplicitSuper :
- requestor.acceptConstructorReference(
- superTypeNames[nestedTypeIndex-1],
- constructorCall.arguments == null ? 0 : constructorCall.arguments.length,
- constructorCall.sourceStart);
- break;
- }
- }
- }
- this.visitIfNeeded(methodDeclaration);
- if (isInRange){
- requestor.exitConstructor(methodDeclaration.declarationSourceEnd);
- }
- this.nestedMethodIndex--;
- return;
- }
- selectorSourceEnd = this.sourceEnds.get(methodDeclaration);
- if (isInRange) {
- int currentModifiers = methodDeclaration.modifiers;
- if (isVarArgs)
- currentModifiers |= ClassFileConstants.AccVarargs;
-
- // remember deprecation so as to not lose it below
- boolean deprecated = (currentModifiers & ClassFileConstants.AccDeprecated) != 0;
-
- InferredType returnType = methodDeclaration instanceof MethodDeclaration
- ? ((MethodDeclaration) methodDeclaration).inferredType
- : null;
- ISourceElementRequestor.MethodInfo methodInfo = new ISourceElementRequestor.MethodInfo();
- methodInfo.declarationStart = methodDeclaration.declarationSourceStart;
- methodInfo.modifiers = deprecated ? (currentModifiers & ExtraCompilerModifiers.AccJustFlag) | ClassFileConstants.AccDeprecated : currentModifiers & ExtraCompilerModifiers.AccJustFlag;
- methodInfo.returnType = returnType == null ? null : returnType.getName();
- methodInfo.name = selector;
- methodInfo.nameSourceStart = methodDeclaration.sourceStart;
- methodInfo.nameSourceEnd = selectorSourceEnd;
- methodInfo.parameterTypes = argumentTypes;
- methodInfo.parameterNames = argumentNames;
- methodInfo.categories = (char[][]) this.nodesToCategories.get(methodDeclaration);
- requestor.enterMethod(methodInfo);
- }
-
- this.visitIfNeeded(methodDeclaration);
-
- if (isInRange) {
- requestor.exitMethod(methodDeclaration.declarationSourceEnd, -1, -1);
- }
- this.nestedMethodIndex--;
-}
-
-/*
-* Update the bodyStart of the corresponding parse node
-*/
-public void notifySourceElementRequestor(AbstractVariableDeclaration fieldDeclaration, TypeDeclaration declaringType) {
-
- // range check
- boolean isInRange =
- scanner.initialPosition <= fieldDeclaration.declarationSourceStart
- && scanner.eofPosition >= fieldDeclaration.declarationSourceEnd;
-
- switch(fieldDeclaration.getKind()) {
- case AbstractVariableDeclaration.FIELD:
- case AbstractVariableDeclaration.LOCAL_VARIABLE:
- int fieldEndPosition = this.sourceEnds.get(fieldDeclaration);
- if (fieldEndPosition == -1) {
- // use the declaration source end by default
- fieldEndPosition = fieldDeclaration.declarationSourceEnd;
- }
- MethodDeclaration methodDeclaration = null;
- if (isInRange) {
- int currentModifiers = fieldDeclaration.modifiers;
-
- // remember deprecation so as to not lose it below
- boolean deprecated = (currentModifiers & ClassFileConstants.AccDeprecated) != 0;
-
- if (fieldDeclaration.initialization instanceof FunctionExpression) {
- methodDeclaration=((FunctionExpression)fieldDeclaration.initialization).methodDeclaration;
- } else if (fieldDeclaration.initialization instanceof Assignment &&
- ((Assignment)fieldDeclaration.initialization).getExpression() instanceof FunctionExpression) {
-
- methodDeclaration=((FunctionExpression)((Assignment)fieldDeclaration.initialization).getExpression()).methodDeclaration;
- }
-
- /* if the variable declaration has a method declaration on the right hand side notify of the declaration using the variable name as the method selector
- * else notify of a field declaration
- */
- if (methodDeclaration!=null) {
- this.notifySourceElementRequestor(methodDeclaration, fieldDeclaration.getName());
- }
- else
- {
- ISourceElementRequestor.FieldInfo fieldInfo = new ISourceElementRequestor.FieldInfo();
- fieldInfo.declarationStart = fieldDeclaration.declarationSourceStart;
- fieldInfo.name = fieldDeclaration.name;
- fieldInfo.modifiers = deprecated ? (currentModifiers & ExtraCompilerModifiers.AccJustFlag)
- | ClassFileConstants.AccDeprecated
- : currentModifiers & ExtraCompilerModifiers.AccJustFlag;
- fieldInfo.type = fieldDeclaration.inferredType != null ? fieldDeclaration.inferredType
- .getName()
- : null;
- fieldInfo.nameSourceStart = fieldDeclaration.sourceStart;
- fieldInfo.nameSourceEnd = fieldDeclaration.sourceEnd;
- fieldInfo.categories = (char[][]) this.nodesToCategories
- .get(fieldDeclaration);
- requestor.enterField(fieldInfo);
- //If this field is of an anonymous type, need to notify so that it shows as a child
- if (fieldDeclaration.inferredType != null
- && fieldDeclaration.inferredType.isAnonymous) {
- notifySourceElementRequestor(fieldDeclaration.inferredType);
- }
- }
- }
- this.visitIfNeeded(fieldDeclaration, declaringType);
- if (isInRange){
- if (methodDeclaration == null) {
- requestor.exitField(
- // filter out initializations that are not a constant (simple check)
- (fieldDeclaration.initialization == null
- || fieldDeclaration.initialization instanceof ArrayInitializer
- || fieldDeclaration.initialization instanceof AllocationExpression
- || fieldDeclaration.initialization instanceof ArrayAllocationExpression
- || fieldDeclaration.initialization instanceof Assignment
- || fieldDeclaration.initialization instanceof ClassLiteralAccess
- || fieldDeclaration.initialization instanceof MessageSend
- || fieldDeclaration.initialization instanceof ArrayReference
- || fieldDeclaration.initialization instanceof ThisReference) ?
- -1 :
- fieldDeclaration.initialization.sourceStart,
- fieldEndPosition,
- fieldDeclaration.declarationSourceEnd);
-
- }
- }
- break;
- case AbstractVariableDeclaration.INITIALIZER:
- if (isInRange){
- requestor.enterInitializer(
- fieldDeclaration.declarationSourceStart,
- fieldDeclaration.modifiers);
- }
- this.visitIfNeeded((Initializer)fieldDeclaration);
- if (isInRange){
- requestor.exitInitializer(fieldDeclaration.declarationSourceEnd);
- }
- break;
- }
-}
-public void notifySourceElementRequestor(
- ImportReference importReference,
- boolean isPackage) {
-
- requestor.acceptImport(
- importReference.declarationSourceStart,
- importReference.declarationSourceEnd,
- importReference.tokens,
- (importReference.bits & ASTNode.OnDemand) != 0);
-
-}
-public void notifySourceElementRequestor(TypeDeclaration typeDeclaration, boolean notifyTypePresence, TypeDeclaration declaringType) {
-
- if (CharOperation.equals(TypeConstants.PACKAGE_INFO_NAME, typeDeclaration.name)) return;
-
- // range check
- boolean isInRange =
- scanner.initialPosition <= typeDeclaration.declarationSourceStart
- && scanner.eofPosition >= typeDeclaration.declarationSourceEnd;
-
- FieldDeclaration[] fields = typeDeclaration.fields;
- AbstractMethodDeclaration[] methods = typeDeclaration.methods;
- TypeDeclaration[] memberTypes = typeDeclaration.memberTypes;
- int fieldCounter = fields == null ? 0 : fields.length;
- int methodCounter = methods == null ? 0 : methods.length;
- int memberTypeCounter = memberTypes == null ? 0 : memberTypes.length;
- int fieldIndex = 0;
- int methodIndex = 0;
- int memberTypeIndex = 0;
-
- if (notifyTypePresence){
-
- int kind = TypeDeclaration.kind(typeDeclaration.modifiers);
- char[] implicitSuperclassName = TypeConstants.CharArray_JAVA_LANG_OBJECT;
- if (isInRange) {
- int currentModifiers = typeDeclaration.modifiers;
-
- // remember deprecation so as to not lose it below
- boolean deprecated = (currentModifiers & ClassFileConstants.AccDeprecated) != 0;
-
- char[] superclassName;
-
- TypeReference superclass = typeDeclaration.superclass;
- superclassName = superclass != null ? CharOperation.concatWith(superclass.getTypeName(), '.') : null;
-
- ISourceElementRequestor.TypeInfo typeInfo = new ISourceElementRequestor.TypeInfo();
- typeInfo.declarationStart = typeDeclaration.declarationSourceStart;
- typeInfo.modifiers = deprecated ? (currentModifiers & ExtraCompilerModifiers.AccJustFlag) | ClassFileConstants.AccDeprecated : currentModifiers & ExtraCompilerModifiers.AccJustFlag;
- typeInfo.name = typeDeclaration.name;
- typeInfo.nameSourceStart = typeDeclaration.sourceStart;
- typeInfo.nameSourceEnd = sourceEnd(typeDeclaration);
- typeInfo.superclass = superclassName;
- typeInfo.categories = (char[][]) this.nodesToCategories.get(typeDeclaration);
- typeInfo.secondary = typeDeclaration.isSecondary();
- typeInfo.anonymousMember = typeDeclaration.allocation != null && typeDeclaration.allocation.enclosingInstance != null;
- requestor.enterType(typeInfo);
- switch (kind) {
- case TypeDeclaration.CLASS_DECL :
- if (superclassName != null)
- implicitSuperclassName = superclassName;
- break;
- }
- }
- if (this.nestedTypeIndex == this.typeNames.length) {
- // need a resize
- System.arraycopy(this.typeNames, 0, (this.typeNames = new char[this.nestedTypeIndex * 2][]), 0, this.nestedTypeIndex);
- System.arraycopy(this.superTypeNames, 0, (this.superTypeNames = new char[this.nestedTypeIndex * 2][]), 0, this.nestedTypeIndex);
- }
- this.typeNames[this.nestedTypeIndex] = typeDeclaration.name;
- this.superTypeNames[this.nestedTypeIndex++] = implicitSuperclassName;
- }
- while ((fieldIndex < fieldCounter)
- || (memberTypeIndex < memberTypeCounter)
- || (methodIndex < methodCounter)) {
- FieldDeclaration nextFieldDeclaration = null;
- AbstractMethodDeclaration nextMethodDeclaration = null;
- TypeDeclaration nextMemberDeclaration = null;
-
- int position = Integer.MAX_VALUE;
- int nextDeclarationType = -1;
- if (fieldIndex < fieldCounter) {
- nextFieldDeclaration = fields[fieldIndex];
- if (nextFieldDeclaration.declarationSourceStart < position) {
- position = nextFieldDeclaration.declarationSourceStart;
- nextDeclarationType = 0; // FIELD
- }
- }
- if (methodIndex < methodCounter) {
- nextMethodDeclaration = methods[methodIndex];
- if (nextMethodDeclaration.declarationSourceStart < position) {
- position = nextMethodDeclaration.declarationSourceStart;
- nextDeclarationType = 1; // METHOD
- }
- }
- if (memberTypeIndex < memberTypeCounter) {
- nextMemberDeclaration = memberTypes[memberTypeIndex];
- if (nextMemberDeclaration.declarationSourceStart < position) {
- position = nextMemberDeclaration.declarationSourceStart;
- nextDeclarationType = 2; // MEMBER
- }
- }
- switch (nextDeclarationType) {
- case 0 :
- fieldIndex++;
- notifySourceElementRequestor(nextFieldDeclaration, typeDeclaration);
- break;
- case 1 :
- methodIndex++;
- notifySourceElementRequestor(nextMethodDeclaration);
- break;
- case 2 :
- memberTypeIndex++;
- notifySourceElementRequestor(nextMemberDeclaration, true, null);
- }
- }
- if (notifyTypePresence){
- if (isInRange){
- requestor.exitType(typeDeclaration.declarationSourceEnd);
- }
- nestedTypeIndex--;
- }
-}
-public void parseCompilationUnit(
- ICompilationUnit unit,
- int start,
- int end,
- boolean fullParse) {
-
- this.reportReferenceInfo = fullParse;
- boolean old = diet;
-
- try {
- diet = true;
- CompilationResult compilationUnitResult = new CompilationResult(unit, 0, 0, this.options.maxProblemsPerUnit);
- CompilationUnitDeclaration parsedUnit = parse(unit, compilationUnitResult, start, end);
- if (scanner.recordLineSeparator) {
- requestor.acceptLineSeparatorPositions(compilationUnitResult.getLineSeparatorPositions());
- }
- if (this.localDeclarationVisitor != null || fullParse){
- diet = false;
- this.getMethodBodies(parsedUnit);
- }
- this.scanner.resetTo(start, end);
- notifySourceElementRequestor(parsedUnit);
- } catch (AbortCompilation e) {
- // ignore this exception
- } finally {
- diet = old;
- reset();
- }
-}
-public CompilationUnitDeclaration parseCompilationUnit(
- ICompilationUnit unit,
- boolean fullParse) {
-
- boolean old = diet;
-
- try {
- diet = DO_DIET_PARSE;
- this.reportReferenceInfo = fullParse;
- CompilationResult compilationUnitResult = new CompilationResult(unit, 0, 0, this.options.maxProblemsPerUnit);
- CompilationUnitDeclaration parsedUnit = parse(unit, compilationUnitResult);
- if (scanner.recordLineSeparator) {
- requestor.acceptLineSeparatorPositions(compilationUnitResult.getLineSeparatorPositions());
- }
- int initialStart = this.scanner.initialPosition;
- int initialEnd = this.scanner.eofPosition;
- if (this.localDeclarationVisitor != null || fullParse){
- diet = false;
- this.getMethodBodies(parsedUnit);
- }
- this.scanner.resetTo(initialStart, initialEnd);
-
- notifySourceElementRequestor(parsedUnit);
- return parsedUnit;
- } catch (AbortCompilation e) {
- // ignore this exception
- } finally {
- diet = old;
- reset();
- }
- return null;
-}
-public void parseTypeMemberDeclarations(
- ISourceType type,
- ICompilationUnit sourceUnit,
- int start,
- int end,
- boolean needReferenceInfo) {
- boolean old = diet;
-
- CompilationResult compilationUnitResult =
- new CompilationResult(sourceUnit, 0, 0, this.options.maxProblemsPerUnit);
- try {
- diet = !needReferenceInfo;
- reportReferenceInfo = needReferenceInfo;
- CompilationUnitDeclaration unit =
- SourceTypeConverter.buildCompilationUnit(
- new ISourceType[]{type},
- // no need for field and methods
- // no need for member types
- // no need for field initialization
- SourceTypeConverter.NONE,
- problemReporter(),
- compilationUnitResult);
- if ((unit == null) || (unit.types == null) || (unit.types.length != 1))
- return;
- this.sourceType = type;
- try {
- /* automaton initialization */
- initialize();
- goForClassBodyDeclarations();
- /* scanner initialization */
- scanner.setSource(sourceUnit.getContents());
- scanner.resetTo(start, end);
- /* unit creation */
- referenceContext = compilationUnit = unit;
- /* initialize the astStacl */
- // the compilationUnitDeclaration should contain exactly one type
- pushOnAstStack(unit.types[0]);
- /* run automaton */
- parse();
- notifySourceElementRequestor(unit);
- } finally {
- unit = compilationUnit;
- compilationUnit = null; // reset parser
- }
- } catch (AbortCompilation e) {
- // ignore this exception
- } finally {
- if (scanner.recordLineSeparator) {
- requestor.acceptLineSeparatorPositions(compilationUnitResult.getLineSeparatorPositions());
- }
- diet = old;
- reset();
- }
-}
-
-public void parseTypeMemberDeclarations(
- char[] contents,
- int start,
- int end) {
-
- boolean old = diet;
-
- try {
- diet = true;
-
- /* automaton initialization */
- initialize();
- goForClassBodyDeclarations();
- /* scanner initialization */
- scanner.setSource(contents);
- scanner.recordLineSeparator = false;
- scanner.taskTags = null;
- scanner.taskPriorities = null;
- scanner.resetTo(start, end);
-
- /* unit creation */
- referenceContext = null;
-
- /* initialize the astStacl */
- // the compilationUnitDeclaration should contain exactly one type
- /* run automaton */
- parse();
- notifySourceElementRequestor((CompilationUnitDeclaration)null);
- } catch (AbortCompilation e) {
- // ignore this exception
- } finally {
- diet = old;
- reset();
- }
-}
-/*
- * Sort the given ast nodes by their positions.
- */
-//private static void quickSort(ASTNode[] sortedCollection, int left, int right) {
-// int original_left = left;
-// int original_right = right;
-// ASTNode mid = sortedCollection[ left + (right - left) / 2];
-// do {
-// while (sortedCollection[left].sourceStart < mid.sourceStart) {
-// left++;
-// }
-// while (mid.sourceStart < sortedCollection[right].sourceStart) {
-// right--;
-// }
-// if (left <= right) {
-// ASTNode tmp = sortedCollection[left];
-// sortedCollection[left] = sortedCollection[right];
-// sortedCollection[right] = tmp;
-// left++;
-// right--;
-// }
-// } while (left <= right);
-// if (original_left < right) {
-// quickSort(sortedCollection, original_left, right);
-// }
-// if (left < original_right) {
-// quickSort(sortedCollection, left, original_right);
-// }
-//}
-private void rememberCategories() {
- if (this.useSourceJavadocParser) {
- SourceJavadocParser sourceJavadocParser = (SourceJavadocParser) this.javadocParser;
- char[][] categories = sourceJavadocParser.categories;
- if (categories.length > 0) {
- this.nodesToCategories.put(this.astStack[this.astPtr], categories);
- sourceJavadocParser.categories = CharOperation.NO_CHAR_CHAR;
- }
- }
-}
-private void reset() {
- this.sourceEnds = new HashtableOfObjectToInt();
- this.nodesToCategories = new HashMap();
- typeNames = new char[4][];
- superTypeNames = new char[4][];
- nestedTypeIndex = 0;
-}
-private int sourceEnd(TypeDeclaration typeDeclaration) {
- if ((typeDeclaration.bits & ASTNode.IsAnonymousType) != 0) {
- QualifiedAllocationExpression allocation = typeDeclaration.allocation;
- if (allocation.type == null) // case of enum constant body
- return typeDeclaration.sourceEnd;
- return allocation.type.sourceEnd;
- } else {
- return typeDeclaration.sourceEnd;
- }
-}
-private void visitIfNeeded(AbstractMethodDeclaration method) {
- if (this.localDeclarationVisitor != null
- //&& (method.bits & ASTNode.HasLocalType) != 0) {
- ){
- if (method instanceof ConstructorDeclaration) {
- ConstructorDeclaration constructorDeclaration = (ConstructorDeclaration) method;
- if (constructorDeclaration.constructorCall != null) {
- constructorDeclaration.constructorCall.traverse(this.localDeclarationVisitor, method.scope);
- }
- }
- 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 );
- }
- }
-}
-
-private void visitIfNeeded(AbstractVariableDeclaration field, TypeDeclaration declaringType) {
- if (this.localDeclarationVisitor != null
- && (field.bits & ASTNode.HasLocalType) != 0) {
- if (field.initialization != null) {
- try {
- this.localDeclarationVisitor.pushDeclaringType(declaringType);
- field.initialization.traverse(this.localDeclarationVisitor, (MethodScope) null);
- } finally {
- this.localDeclarationVisitor.popDeclaringType();
- }
- }
- }
-}
-
-private void visitIfNeeded(Initializer initializer) {
- if (this.localDeclarationVisitor != null
- && (initializer.bits & ASTNode.HasLocalType) != 0) {
- if (initializer.block != null) {
- initializer.block.traverse(this.localDeclarationVisitor, null);
- }
- }
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/SourceJavadocParser.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/SourceJavadocParser.java
deleted file mode 100644
index 314e8330..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/SourceJavadocParser.java
+++ /dev/null
@@ -1,94 +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.compiler;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.parser.JavadocParser;
-import org.eclipse.wst.jsdt.internal.compiler.parser.Parser;
-import org.eclipse.wst.jsdt.internal.compiler.parser.ScannerHelper;
-
-public class SourceJavadocParser extends JavadocParser {
-
- // Store categories identifiers parsed in javadoc
- int categoriesPtr = -1;
- char[][] categories = CharOperation.NO_CHAR_CHAR;
-
-public SourceJavadocParser(Parser sourceParser) {
- super(sourceParser);
- this.kind = SOURCE_PARSER | TEXT_VERIF;
-}
-
-public boolean checkDeprecation(int commentPtr) {
- this.categoriesPtr = -1;
- boolean result = super.checkDeprecation(commentPtr);
- if (this.categoriesPtr > -1) {
- System.arraycopy(this.categories, 0, this.categories = new char[this.categoriesPtr+1][], 0, this.categoriesPtr+1);
- } else {
- this.categories = CharOperation.NO_CHAR_CHAR;
- }
- return result;
-}
-
-/* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.parser.AbstractCommentParser#parseIdentifierTag()
- */
-protected boolean parseIdentifierTag(boolean report) {
- int end = this.lineEnd+1;
- if (super.parseIdentifierTag(report) && this.index <= end) {
- return true;
- }
- return false;
-}
-
-/* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.parser.JavadocParser#parseSimpleTag()
- */
-protected void parseSimpleTag() {
-
- // Read first char
- // readChar() code is inlined to balance additional method call in checkDeprectation(int)
- char first = this.source[this.index++];
- if (first == '\\' && this.source[this.index] == 'u') {
- int c1, c2, c3, c4;
- int pos = this.index;
- this.index++;
- while (this.source[this.index] == 'u')
- this.index++;
- if (!(((c1 = ScannerHelper.getNumericValue(this.source[this.index++])) > 15 || c1 < 0)
- || ((c2 = ScannerHelper.getNumericValue(this.source[this.index++])) > 15 || c2 < 0)
- || ((c3 = ScannerHelper.getNumericValue(this.source[this.index++])) > 15 || c3 < 0)
- || ((c4 = ScannerHelper.getNumericValue(this.source[this.index++])) > 15 || c4 < 0))) {
- first = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4);
- } else {
- this.index = pos;
- }
- }
-
- // switch on first tag char
- switch (first) {
- case 'd': // perhaps @deprecated tag?
- if ((readChar() == 'e') &&
- (readChar() == 'p') && (readChar() == 'r') &&
- (readChar() == 'e') && (readChar() == 'c') &&
- (readChar() == 'a') && (readChar() == 't') &&
- (readChar() == 'e') && (readChar() == 'd')) {
- // ensure the tag is properly ended: either followed by a space, a tab, line end or asterisk.
- char c = readChar();
- if (ScannerHelper.isWhitespace(c) || c == '*') {
- this.tagValue = TAG_DEPRECATED_VALUE;
- this.deprecated = true;
- }
- }
- break;
- }
-}
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/AND_AND_Expression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/AND_AND_Expression.java
deleted file mode 100644
index 1e0fae6b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/AND_AND_Expression.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IAND_AND_Expression;
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-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;
-import org.eclipse.wst.jsdt.internal.compiler.impl.Constant;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-
-//dedicated treatment for the &&
-public class AND_AND_Expression extends BinaryExpression implements IAND_AND_Expression {
-
- int rightInitStateIndex = -1;
- int mergedInitStateIndex = -1;
-
- public AND_AND_Expression(Expression left, Expression right, int operator) {
- super(left, right, operator);
- }
-
- public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {
-
- Constant cst = this.left.optimizedBooleanConstant();
- boolean isLeftOptimizedTrue = cst != Constant.NotAConstant && cst.booleanValue() == true;
- boolean isLeftOptimizedFalse = cst != Constant.NotAConstant && cst.booleanValue() == false;
-
- if (isLeftOptimizedTrue) {
- // TRUE && anything
- // need to be careful of scenario:
- // (x && y) && !z, if passing the left info to the right, it would
- // be swapped by the !
- FlowInfo mergedInfo = left.analyseCode(currentScope, flowContext, flowInfo)
- .unconditionalInits();
- mergedInfo = right.analyseCode(currentScope, flowContext, mergedInfo);
-// mergedInitStateIndex = currentScope.methodScope()
-// .recordInitializationStates(mergedInfo);
- return mergedInfo;
- }
-
- FlowInfo leftInfo = left.analyseCode(currentScope, flowContext, flowInfo);
- // need to be careful of scenario:
- // (x && y) && !z, if passing the left info to the right, it would be
- // swapped by the !
- FlowInfo rightInfo = leftInfo.initsWhenTrue().unconditionalCopy();
-// rightInitStateIndex = currentScope.methodScope().recordInitializationStates(rightInfo);
-
- int previousMode = rightInfo.reachMode();
- if (isLeftOptimizedFalse) {
- rightInfo.setReachMode(FlowInfo.UNREACHABLE);
- }
- rightInfo = right.analyseCode(currentScope, flowContext, rightInfo);
- FlowInfo mergedInfo = FlowInfo.conditional(
- rightInfo.safeInitsWhenTrue(),
- leftInfo.initsWhenFalse().unconditionalInits().mergedWith(
- rightInfo.initsWhenFalse().setReachMode(previousMode).unconditionalInits()));
- // reset after trueMergedInfo got extracted
-// mergedInitStateIndex = currentScope.methodScope().recordInitializationStates(mergedInfo);
- return mergedInfo;
- }
-
- public boolean isCompactableOperation() {
- return false;
- }
-
- public void traverse(ASTVisitor visitor, BlockScope scope) {
- if (visitor.visit(this, scope)) {
- left.traverse(visitor, scope);
- right.traverse(visitor, scope);
- }
- visitor.endVisit(this, scope);
- }
- public int getASTType() {
- return IASTNode.AND_AND_EXPRESSION;
-
- }
-}
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
deleted file mode 100644
index da894d15..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ASTNode.java
+++ /dev/null
@@ -1,487 +0,0 @@
-/*******************************************************************************
- * 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
- * Matt McCutchen
- * Partial fix for https://bugs.eclipse.org/bugs/show_bug.cgi?id=122995.
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-import org.eclipse.wst.jsdt.internal.compiler.DelegateASTVisitor;
-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.lookup.ArrayBinding;
-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.FieldBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.InvocationSite;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding;
-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.lookup.TypeConstants;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeIds;
-
-public abstract class ASTNode implements TypeConstants, TypeIds, IASTNode {
-
- public int sourceStart, sourceEnd;
-
- // storage for internal flags (32 bits) BIT USAGE
- public final static int Bit1 = 0x1; // return type (operator) | name reference kind (name ref) | add assertion (type decl) | useful empty statement (empty statement)
- public final static int Bit2 = 0x2; // return type (operator) | name reference kind (name ref) | has local type (type, method, field decl)
- public final static int Bit3 = 0x4; // return type (operator) | name reference kind (name ref)
- public final static int Bit4 = 0x8; // return type (operator) | first assignment to local (name ref,local decl) | undocumented empty block (block, type and method decl)
- public final static int Bit5 = 0x10; // value for return (expression) | has all method bodies (unit) | supertype ref (type ref) | resolved (field decl)
- public final static int Bit6 = 0x20; // depth (name ref, msg) | ignore need cast check (cast expression) | error in signature (method declaration/ initializer)
- public final static int Bit7 = 0x40; // depth (name ref, msg) | operator (operator) | need runtime checkcast (cast expression) | label used (labelStatement) | needFreeReturn (AbstractMethodDeclaration)
- public final static int Bit8 = 0x80; // depth (name ref, msg) | operator (operator) | unsafe cast (cast expression) | is default constructor (constructor declaration)
- public final static int Bit9 = 0x100; // depth (name ref, msg) | operator (operator) | is local type (type decl)
- public final static int Bit10= 0x200; // depth (name ref, msg) | operator (operator) | is anonymous type (type decl)
- public final static int Bit11 = 0x400; // depth (name ref, msg) | operator (operator) | is member type (type decl)
- public final static int Bit12 = 0x800; // depth (name ref, msg) | operator (operator) | has abstract methods (type decl)
- public final static int Bit13 = 0x1000; // depth (name ref, msg) | is secondary type (type decl)
- public final static int Bit14 = 0x2000; // strictly assigned (reference lhs) | discard enclosing instance (explicit constr call) | hasBeenGenerated (type decl)
- public final static int Bit15 = 0x4000; // is unnecessary cast (expression) | implicit this (this ref) | is varargs (type ref) | isSubRoutineEscaping (try statement) | superAccess (javadoc allocation expression/javadoc message send/javadoc return statement)
- public final static int Bit16 = 0x8000; // in javadoc comment (name ref, type ref, msg)
- public final static int Bit17 = 0x10000; // compound assigned (reference lhs)
- public final static int Bit18 = 0x20000; // non null (expression) | onDemand (import reference)
- public final static int Bit19 = 0x40000; // didResolve (parameterized qualified type ref/parameterized single type ref) | empty (javadoc return statement)
- public final static int Bit20 = 0x80000;
- public final static int Bit21 = 0x100000;
- public final static int Bit22 = 0x200000; // parenthesis count (expression) | used (import reference)
- public final static int Bit23 = 0x400000; // parenthesis count (expression)
- public final static int Bit24 = 0x800000; // parenthesis count (expression)
- public final static int Bit25 = 0x1000000; // parenthesis count (expression)
- public final static int Bit26 = 0x2000000; // parenthesis count (expression)
- public final static int Bit27 = 0x4000000; // parenthesis count (expression)
- public final static int Bit28 = 0x8000000; // parenthesis count (expression)
- public final static int Bit29 = 0x10000000; // parenthesis count (expression)
- public final static int Bit30 = 0x20000000; // elseif (if statement) | try block exit (try statement) | fall-through (case statement) | ignore no effect assign (expression ref) | needScope (for statement) | isAnySubRoutineEscaping (return statement) | blockExit (synchronized statement)
- public final static int Bit31 = 0x40000000; // local declaration reachable (local decl) | ignore raw type check (type ref) | discard entire assignment (assignment) | isSynchronized (return statement) | thenExit (if statement)
- public final static int Bit32 = 0x80000000; // reachable (statement)
-
- public final static long Bit32L = 0x80000000L;
- public final static long Bit33L = 0x100000000L;
- public final static long Bit34L = 0x200000000L;
- public final static long Bit35L = 0x400000000L;
- public final static long Bit36L = 0x800000000L;
- public final static long Bit37L = 0x1000000000L;
- public final static long Bit38L = 0x2000000000L;
- public final static long Bit39L = 0x4000000000L;
- public final static long Bit40L = 0x8000000000L;
- public final static long Bit41L = 0x10000000000L;
- public final static long Bit42L = 0x20000000000L;
- public final static long Bit43L = 0x40000000000L;
- public final static long Bit44L = 0x80000000000L;
- public final static long Bit45L = 0x100000000000L;
- public final static long Bit46L = 0x200000000000L;
- public final static long Bit47L = 0x400000000000L;
- public final static long Bit48L = 0x800000000000L;
- public final static long Bit49L = 0x1000000000000L;
- public final static long Bit50L = 0x2000000000000L;
- public final static long Bit51L = 0x4000000000000L;
- public final static long Bit52L = 0x8000000000000L;
- public final static long Bit53L = 0x10000000000000L;
- public final static long Bit54L = 0x20000000000000L;
- public final static long Bit55L = 0x40000000000000L;
- public final static long Bit56L = 0x80000000000000L;
- public final static long Bit57L = 0x100000000000000L;
- public final static long Bit58L = 0x200000000000000L;
- public final static long Bit59L = 0x400000000000000L;
- public final static long Bit60L = 0x800000000000000L;
- public final static long Bit61L = 0x1000000000000000L;
- public final static long Bit62L = 0x2000000000000000L;
- public final static long Bit63L = 0x4000000000000000L;
- public final static long Bit64L = 0x8000000000000000L;
-
- public int bits = IsReachable; // reachable by default
-
- // for operators
- public static final int ReturnTypeIDMASK = Bit1|Bit2|Bit3|Bit4;
- public static final int OperatorSHIFT = 6; // Bit7 -> Bit12
- public static final int OperatorMASK = Bit7|Bit8|Bit9|Bit10|Bit11|Bit12; // 6 bits for operator ID
-
- // for binary expressions
- public static final int IsReturnedValue = Bit5;
-
- // for name references
- public static final int RestrictiveFlagMASK = Bit1|Bit2|Bit3|Bit4;
-
- // for name refs or local decls
- public static final int FirstAssignmentToLocal = Bit4;
-
- // for this reference
- public static final int IsImplicitThis = Bit15;
-
- // for single name references
- public static final int DepthSHIFT = 5; // Bit6 -> Bit13
- public static final int DepthMASK = Bit6|Bit7|Bit8|Bit9|Bit10|Bit11|Bit12|Bit13; // 8 bits for actual depth value (max. 255)
-
- // for statements
- public static final int IsReachable = Bit32;
- public static final int LabelUsed = Bit7;
- public static final int DocumentedFallthrough = Bit30;
-
- // local decls
- public static final int IsLocalDeclarationReachable = Bit31;
-
- // try statements
- public static final int IsSubRoutineEscaping = Bit15;
- public static final int IsTryBlockExiting = Bit30;
-
- // for type declaration
- public static final int ContainsAssertion = Bit1;
- public static final int IsLocalType = Bit9;
- public static final int IsAnonymousType = Bit10; // used to test for anonymous
- public static final int IsMemberType = Bit11; // local member do not know it is local at parse time (need to look at binding)
- public static final int HasAbstractMethods = Bit12; // used to promote abstract enums
- public static final int IsSecondaryType = Bit13; // used to test for secondary
- public static final int HasBeenGenerated = Bit14;
-
- // for type, method and field declarations
- public static final int HasLocalType = Bit2; // cannot conflict with AddAssertionMASK
- public static final int HasBeenResolved = Bit5; // field decl only (to handle forward references)
-
- // for expression
- public static final int ParenthesizedSHIFT = 21; // Bit22 -> Bit29
- public static final int ParenthesizedMASK = Bit22|Bit23|Bit24|Bit25|Bit26|Bit27|Bit28|Bit29; // 8 bits for parenthesis count value (max. 255)
- public static final int IgnoreNoEffectAssignCheck = Bit30;
-
- // for references on lhs of assignment
- public static final int IsStrictlyAssigned = Bit14; // set only for true assignments, as opposed to compound ones
- public static final int IsCompoundAssigned = Bit17; // set only for compound assignments, as opposed to other ones
-
- // for explicit constructor call
- public static final int DiscardEnclosingInstance = Bit14; // used for codegen
-
- // for empty statement
- public static final int IsUsefulEmptyStatement = Bit1;
-
- // for block and method declaration
- public static final int UndocumentedEmptyBlock = Bit4;
- public static final int OverridingMethodWithSupercall = Bit5;
-
- // for initializer and method declaration
- public static final int ErrorInSignature = Bit6;
-
- // for abstract method declaration
- public static final int NeedFreeReturn = Bit7; // abstract method declaration
-
- // for constructor declaration
- public static final int IsDefaultConstructor = Bit8;
-
- // for compilation unit
- public static final int HasAllMethodBodies = Bit5;
- public static final int IsImplicitUnit = Bit1;
-
- // for references in Javadoc comments
- public static final int InsideJavadoc = Bit16;
-
- // for javadoc allocation expression/javadoc message send/javadoc return statement
- public static final int SuperAccess = Bit15;
-
- // for javadoc return statement
- public static final int Empty = Bit19;
-
- // for if statement
- public static final int IsElseIfStatement = Bit30;
- public static final int ThenExit = Bit31;
-
- // for type reference
- public static final int IsSuperType = Bit5;
- 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;
-
- // for for statement
- public static final int NeededScope = Bit30;
-
- // for import reference
- public static final int OnDemand = Bit18;
- public static final int Used = Bit2;
- public static final int IsFileImport = Bit5;
-
- // for parameterized qualified/single type ref
- public static final int DidResolve = Bit19;
-
- // for return statement
- public static final int IsAnySubRoutineEscaping = Bit30;
-
- // for synchronized statement
- public static final int BlockExit = Bit30;
-
- // for method decls and var decls
- public static final int IsInferredType = Bit14;
- public static final int IsInferredJsDocType = Bit15;
-
- // 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() {
-
- super();
- }
- private static int checkInvocationArgument(BlockScope scope, Expression argument, TypeBinding parameterType, TypeBinding argumentType, TypeBinding originalParameterType) {
- TypeBinding checkedParameterType = originalParameterType == null ? parameterType : originalParameterType;
- if (argumentType != checkedParameterType && argumentType.needsUncheckedConversion(checkedParameterType)) {
- return INVOCATION_ARGUMENT_UNCHECKED;
- }
- return INVOCATION_ARGUMENT_OK;
- }
- public static void checkInvocationArguments(BlockScope scope, Expression receiver, TypeBinding receiverType, MethodBinding method, Expression[] arguments, TypeBinding[] argumentTypes, boolean argsContainCast, InvocationSite invocationSite) {
- TypeBinding[] params = method.parameters;
- int paramLength = params.length;
-
- int invocationStatus = INVOCATION_ARGUMENT_OK;
- if (arguments != null) {
- if (method.isVarargs()) {
- // 4 possibilities exist for a call to the vararg method foo(int i, long ... value) : foo(1), foo(1, 2), foo(1, 2, 3, 4) & foo(1, new long[] {1, 2})
- int lastIndex = paramLength - 1;
- for (int i = 0; i < lastIndex; i++) {
- TypeBinding originalRawParam = null;
- invocationStatus |= checkInvocationArgument(scope, arguments[i], params[i] , argumentTypes[i], originalRawParam);
- }
- int argLength = arguments.length;
- if (lastIndex < argLength) { // vararg argument was provided
- TypeBinding parameterType = params[lastIndex];
- TypeBinding originalRawParam = null;
-
- if (paramLength != argLength || parameterType.dimensions() != argumentTypes[lastIndex].dimensions()) {
- parameterType = ((ArrayBinding) parameterType).elementsType(); // single element was provided for vararg parameter
- }
- for (int i = lastIndex; i < argLength; i++) {
- invocationStatus |= checkInvocationArgument(scope, arguments[i], parameterType, argumentTypes[i], originalRawParam);
- }
- }
-
- if (paramLength == argumentTypes.length) { // 70056
- int varargsIndex = paramLength - 1;
- ArrayBinding varargsType = (ArrayBinding) params[varargsIndex];
- TypeBinding lastArgType = argumentTypes[varargsIndex];
- int dimensions;
- if (lastArgType != TypeBinding.NULL && (varargsType.dimensions <= (dimensions = lastArgType.dimensions()))) {
- if (lastArgType.leafComponentType().isBaseType()) {
- dimensions--;
- }
- }
- }
- } else {
- int length = (paramLength<arguments.length) ? paramLength : arguments.length;
- for (int i = 0; i < length; i++) {
- TypeBinding originalRawParam = null;
- invocationStatus |= checkInvocationArgument(scope, arguments[i], params[i], argumentTypes[i], originalRawParam);
- }
- }
- }
-// if ((invocationStatus & INVOCATION_ARGUMENT_WILDCARD) != 0) {
-// scope.problemReporter().wildcardInvocation((ASTNode)invocationSite, receiverType, method, argumentTypes);
-// } else if (!method.isStatic() && !receiverType.isUnboundWildcard() && method.declaringClass.isRawType() && method.hasSubstitutedParameters()) {
-// scope.problemReporter().unsafeRawInvocation((ASTNode)invocationSite, method);
-// } else if (rawOriginalGenericMethod != null) {
-// scope.problemReporter().unsafeRawGenericMethodInvocation((ASTNode)invocationSite, method);
-// }
- }
- public ASTNode concreteStatement() {
- return this;
- }
-
- public final boolean isFieldUseDeprecated(FieldBinding field, Scope scope, boolean isStrictlyAssigned) {
-
- if (!isStrictlyAssigned && (field.isPrivate() || (field.declaringClass != null && field.declaringClass.isLocalType())) && !scope.isDefinedInField(field)) {
- // ignore cases where field is used from within inside itself
- field.original().modifiers |= ExtraCompilerModifiers.AccLocallyUsed;
- }
-
- if ((field.modifiers & ExtraCompilerModifiers.AccRestrictedAccess) != 0) {
- AccessRestriction restriction =
- scope.environment().getAccessRestriction(field.declaringClass);
- if (restriction != null) {
- scope.problemReporter().forbiddenReference(field, this,
- restriction.getFieldAccessMessageTemplate(), restriction.getProblemId());
- }
- }
-
- if (!field.isViewedAsDeprecated()) return false;
-
- // inside same unit - no report
- if (scope.isDefinedInSameUnit(field.declaringClass)) return false;
-
- // if context is deprecated, may avoid reporting
- if (!scope.compilerOptions().reportDeprecationInsideDeprecatedCode && scope.isInsideDeprecatedCode()) return false;
- return true;
- }
-
- public boolean isImplicitThis() {
-
- return false;
- }
-
- /* Answer true if the method use is considered deprecated.
- * An access in the same compilation unit is allowed.
- */
- public final boolean isMethodUseDeprecated(MethodBinding method, Scope scope,
- boolean isExplicitUse) {
- if ((method.isPrivate() /*|| method.declaringClass.isLocalType()*/) && !scope.isDefinedInMethod(method)) {
- // ignore cases where method is used from within inside itself (e.g. direct recursions)
- method.original().modifiers |= ExtraCompilerModifiers.AccLocallyUsed;
- }
-
- // TODO (maxime) consider separating concerns between deprecation and access restriction.
- // Caveat: this was not the case when access restriction funtion was added.
- if (isExplicitUse && (method.modifiers & ExtraCompilerModifiers.AccRestrictedAccess) != 0) {
- // note: explicit constructors calls warnings are kept despite the 'new C1()' case (two
- // warnings, one on type, the other on constructor), because of the 'super()' case.
- AccessRestriction restriction =
- scope.environment().getAccessRestriction(method.declaringClass);
- if (restriction != null) {
- if (method.isConstructor()) {
- scope.problemReporter().forbiddenReference(method, this,
- restriction.getConstructorAccessMessageTemplate(),
- restriction.getProblemId());
- }
- else {
- scope.problemReporter().forbiddenReference(method, this,
- restriction.getMethodAccessMessageTemplate(),
- restriction.getProblemId());
- }
- }
- }
-
- if (!method.isViewedAsDeprecated()) return false;
-
- // inside same unit - no report
- if (scope.isDefinedInSameUnit(method.declaringClass)) return false;
-
- // non explicit use and non explicitly deprecated - no report
- if (!isExplicitUse &&
- (method.modifiers & ClassFileConstants.AccDeprecated) == 0) {
- return false;
- }
-
- // if context is deprecated, may avoid reporting
- if (!scope.compilerOptions().reportDeprecationInsideDeprecatedCode && scope.isInsideDeprecatedCode()) return false;
- return true;
- }
-
- public boolean isSuper() {
-
- return false;
- }
-
- public boolean isThis() {
-
- return false;
- }
-
- /* Answer true if the type use is considered deprecated.
- * An access in the same compilation unit is allowed.
- */
- public final boolean isTypeUseDeprecated(TypeBinding type, Scope scope) {
-
- if (type.isArrayType())
- return isTypeUseDeprecated(((ArrayBinding) type).leafComponentType, scope);
- if (type.isBaseType())
- return false;
-
-
- /* BC - threw an exception-- temp fix */
- ReferenceBinding refType=null;
- try {
- refType = (ReferenceBinding) type;
- } catch (Exception ex) {
- // TODO Auto-generated catch block
- ex.printStackTrace();
- }
-
- if ((refType.isPrivate() || refType.isLocalType()) && !scope.isDefinedInType(refType)) {
- // ignore cases where type is used from within inside itself
- refType.modifiers |= ExtraCompilerModifiers.AccLocallyUsed;
- }
-
- if (refType.hasRestrictedAccess()) {
- AccessRestriction restriction = scope.environment().getAccessRestriction(type);
- if (restriction != null) {
- scope.problemReporter().forbiddenReference(type, this, restriction.getMessageTemplate(), restriction.getProblemId());
- }
- }
-
- if (!refType.isViewedAsDeprecated()) return false;
-
- // inside same unit - no report
- if (scope.isDefinedInSameUnit(refType)) return false;
-
- // if context is deprecated, may avoid reporting
- if (!scope.compilerOptions().reportDeprecationInsideDeprecatedCode && scope.isInsideDeprecatedCode()) return false;
- return true;
- }
-
- public abstract StringBuffer print(int indent, StringBuffer output);
-
- public static StringBuffer printIndent(int indent, StringBuffer output) {
-
- for (int i = indent; i > 0; i--) output.append(" "); //$NON-NLS-1$
- return output;
- }
-
- public static StringBuffer printModifiers(int modifiers, StringBuffer output) {
-
- if ((modifiers & ClassFileConstants.AccPublic) != 0)
- output.append("public "); //$NON-NLS-1$
- if ((modifiers & ClassFileConstants.AccPrivate) != 0)
- output.append("private "); //$NON-NLS-1$
- if ((modifiers & ClassFileConstants.AccProtected) != 0)
- output.append("protected "); //$NON-NLS-1$
- if ((modifiers & ClassFileConstants.AccStatic) != 0)
- output.append("static "); //$NON-NLS-1$
- if ((modifiers & ClassFileConstants.AccFinal) != 0)
- output.append("final "); //$NON-NLS-1$
- if ((modifiers & ClassFileConstants.AccNative) != 0)
- output.append("native "); //$NON-NLS-1$
- if ((modifiers & ClassFileConstants.AccAbstract) != 0)
- output.append("abstract "); //$NON-NLS-1$
- return output;
- }
-
- public int sourceStart() {
- return this.sourceStart;
- }
- public int sourceEnd() {
- return this.sourceEnd;
- }
- public void setSourceEnd(int pos) {
- this.sourceEnd = pos;
- }
- public String toString() {
- return print(0, new StringBuffer(30)).toString();
- }
-
- public void traverse(ASTVisitor visitor, BlockScope scope) {
- // do nothing by default
- }
-
- public boolean isInferred() {
- return false;
- }
- public int getASTType() {
- return IASTNode.AST_NODE;
-
- }
-
- public void traverse(org.eclipse.wst.jsdt.core.ast.ASTVisitor visitor) {
- this.traverse(new DelegateASTVisitor(visitor), null);
- }
-}
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
deleted file mode 100644
index 0af6e515..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/AbstractMethodDeclaration.java
+++ /dev/null
@@ -1,421 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import java.util.ArrayList;
-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.IJsDoc;
-import org.eclipse.wst.jsdt.core.ast.IProgramElement;
-import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem;
-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.CompilationResult;
-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.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.MethodBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodScope;
-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.parser.Parser;
-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.AbortMethod;
-import org.eclipse.wst.jsdt.internal.compiler.problem.AbortType;
-import org.eclipse.wst.jsdt.internal.compiler.problem.ProblemSeverities;
-
-
-public abstract class AbstractMethodDeclaration extends Statement
- implements IAbstractFunctionDeclaration, ProblemSeverities, ReferenceContext {
-
- public MethodScope scope;
- 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;
- public int declarationSourceStart;
- public int declarationSourceEnd;
- public int modifiers;
- public Argument[] arguments;
- public Statement[] statements;
- public int explicitDeclarations;
- public MethodBinding binding;
- public boolean ignoreFurtherInvestigation = false;
- public boolean needFreeReturn = false;
- public boolean resolveChildStatments = true;
-
- public Javadoc javadoc;
-
- public int bodyStart;
- public int bodyEnd = -1;
- public CompilationResult compilationResult;
-
- public InferredType inferredType;
- public InferredMethod inferredMethod;
-
- public boolean errorInSignature = false;
- public int exprStackPtr;
-
- AbstractMethodDeclaration(CompilationResult compilationResult){
- this.compilationResult = compilationResult;
- this.prevScope = null;
- }
-
- public void setArguments( IArgument[] args) {
- if(args instanceof Argument[]) this.arguments = (Argument[])args;
- }
-
- public IArgument[] getArguments() {
- return this.arguments;
- }
-
- /*
- * We cause the compilation task to abort to a given extent.
- */
- public void abort(int abortLevel, CategorizedProblem problem) {
-
- switch (abortLevel) {
- case AbortCompilation :
- throw new AbortCompilation(this.compilationResult, problem);
- case AbortCompilationUnit :
- throw new AbortCompilationUnit(this.compilationResult, problem);
- case AbortType :
- throw new AbortType(this.compilationResult, problem);
- default :
- throw new AbortMethod(this.compilationResult, problem);
- }
- }
-
- public FlowInfo analyseCode(BlockScope classScope, FlowContext initializationContext, FlowInfo info)
- {
- return this.analyseCode((Scope)classScope, initializationContext, info);
- }
-
- public abstract FlowInfo analyseCode(Scope classScope, FlowContext initializationContext, FlowInfo info);
-
- /**
- * Bind and add argument's binding into the scope of the method
- */
- 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;
-
- // 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);
- }
- return;
- }
- if (this.arguments.length>0 && this.binding.parameters.length==0) // types not set yet
- {
- ReferenceBinding declaringClass = this.binding.declaringClass;
- if (declaringClass instanceof SourceTypeBinding) {
- SourceTypeBinding binding = (SourceTypeBinding) declaringClass;
- binding.resolveTypesFor(this.binding,this);
- }
- }
- 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);
- }
- }
- }
-
- public CompilationResult compilationResult() {
-
- return this.compilationResult;
- }
-
- public boolean hasErrors() {
- return this.ignoreFurtherInvestigation;
- }
-
- public boolean isAbstract() {
-
- if (this.binding != null)
- return this.binding.isAbstract();
- return (this.modifiers & ClassFileConstants.AccAbstract) != 0;
- }
-
- public boolean isClinit() {
-
- return false;
- }
-
-
- /**
- * @return If the {@link #inferredMethod} is set then use that to determine if
- * this declaration is a constructor, else <code>false</code>
- */
- public boolean isConstructor() {
- boolean isConstructor = false;
- if(this.inferredMethod != null) {
- isConstructor = this.inferredMethod.isConstructor;
- }
- return isConstructor;
- }
-
- public boolean isDefaultConstructor() {
-
- return false;
- }
-
- public boolean isInitializationMethod() {
-
- return false;
- }
-
- public boolean isMethod() {
-
- return false;
- }
-
- public boolean isStatic() {
-
- if (this.binding != null)
- return this.binding.isStatic();
- return (this.modifiers & ClassFileConstants.AccStatic) != 0;
- }
-
- public boolean isInferredJsDocType() {
- return (this.bits & ASTNode.IsInferredJsDocType) != 0;
- }
-
- /**
- * Fill up the method body with statement
- * @param parser
- * @param unit
- */
- public abstract void parseStatements(
- Parser parser,
- CompilationUnitDeclaration unit);
-
- public StringBuffer printStatement(int indent, StringBuffer output)
- {
- return print(indent,output);
- }
-
- public StringBuffer print(int tab, StringBuffer output) {
-
- if (this.javadoc != null) {
- this.javadoc.print(tab, output);
- }
- printIndent(tab, output);
-
- output.append("function "); //$NON-NLS-1$
- if (this.selector!=null)
- output.append(this.selector);
- output.append('(');
- if (this.arguments != null) {
- for (int i = 0; i < this.arguments.length; i++) {
- if (i > 0) output.append(", "); //$NON-NLS-1$
- this.arguments[i].print(0, output);
- }
- }
- output.append(')');
- printBody(tab + 1, output);
- return output;
- }
-
- public StringBuffer printBody(int indent, StringBuffer output) {
-
- if (isAbstract() || (this.modifiers & ExtraCompilerModifiers.AccSemicolonBody) != 0)
- return output.append(';');
-
- output.append(" {"); //$NON-NLS-1$
- if (this.statements != null) {
- for (int i = 0; i < this.statements.length; i++) {
- output.append('\n');
- this.statements[i].printStatement(indent, output);
- }
- }
- output.append('\n');
- printIndent(indent == 0 ? 0 : indent - 1, output).append('}');
- return output;
- }
-
- 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);
- }
- }
- }
- }
-
- }
-
- if (this.binding == null) {
-
-
- this.ignoreFurtherInvestigation = true;
- }
-
- try {
- if(resolveChildStatments) {
- bindArguments();
- resolveJavadoc();
- resolveStatements();
- }
- } catch (AbortMethod e) { // ========= abort on fatal error =============
- this.ignoreFurtherInvestigation = true;
- }
- }
-
- public void resolveJavadoc() {
-
- if (this.binding == null) return;
- if (this.javadoc != null) {
- this.javadoc.resolve(this.scope);
- return;
- }
- if (this.binding.declaringClass != null && !this.binding.declaringClass.isLocalType()) {
- this.scope.problemReporter().javadocMissing(this.sourceStart, this.sourceEnd, this.binding.modifiers);
- }
- }
-
- // made some changes here to fix https://bugs.eclipse.org/bugs/show_bug.cgi?id=262728
- public void resolveStatements() {
- if (this.statements != null) {
- 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)
- 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
- if(nonFunctions != null) {
- for(int j = 0; j < nonFunctions.size(); j++) {
- ((Statement)nonFunctions.get(j)).resolve(this.scope);
- }
- }
- // now its time to reslove the children statements of the function
- if(functions != null) {
- for(int f = 0; f < functions.size(); f++) {
- ((Statement)functions.get(f)).resolve(this.scope);
- }
- }
- } else if ((this.bits & UndocumentedEmptyBlock) != 0) {
- this.scope.problemReporter().undocumentedEmptyBlock(this.bodyStart-1, this.bodyEnd+1);
- }
- }
-
- public void tagAsHavingErrors() {
- this.ignoreFurtherInvestigation = true;
- }
-
- public void traverse(
- ASTVisitor visitor,
- Scope classScope) {
- // default implementation: subclass will define it
- }
-
- public void resolve(BlockScope scope) {
- this.resolve((Scope)scope);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode#isInferred()
- */
- public boolean isInferred() {
- return this.inferredMethod != null;
- }
-
- public int getASTType() {
- return IASTNode.ABSTRACT_FUNCTION_DECLARATION;
-
- }
-
- public IJsDoc getJsDoc() {
- return this.javadoc;
- }
-
- public IProgramElement[] getStatements() {
- return this.statements;
- }
-
- public char[] getName() {
- return this.selector != null ? this.selector : this.potentialName;
- }
-
- public void setInferredType(InferredType type) {
- this.inferredType=type;
- }
-
- public InferredMethod getInferredMethod() {
- return this.inferredMethod;
- }
-
- public InferredType getInferredType() {
- 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 []{};
- }
-}
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
deleted file mode 100644
index 90d657f2..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/AbstractVariableDeclaration.java
+++ /dev/null
@@ -1,162 +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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IAbstractVariableDeclaration;
-import org.eclipse.wst.jsdt.core.ast.IExpression;
-import org.eclipse.wst.jsdt.core.ast.IJsDoc;
-import org.eclipse.wst.jsdt.core.infer.InferredType;
-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.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.InvocationSite;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public abstract class AbstractVariableDeclaration extends Statement implements IAbstractVariableDeclaration, InvocationSite {
- public int declarationEnd;
- public int declarationSourceEnd;
- public int declarationSourceStart;
- public int hiddenVariableDepth; // used to diagnose hiding scenarii
- public Expression initialization;
- public int modifiers;
- public int modifiersSourceStart;
- public Javadoc javadoc;
-
-
- public InferredType inferredType;
- public char[] name;
-
- public TypeReference type;
-
- public AbstractVariableDeclaration nextLocal;
-
- public InferredType getInferredType() {
- return this.inferredType;
- }
-
- public void setInferredType(InferredType type) {
- this.inferredType = type;
- }
-
- public char[] getName() {
- return this.name;
- }
- public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {
- return flowInfo;
- }
-
- public static final int FIELD = 1;
- public static final int INITIALIZER = 2;
- public static final int LOCAL_VARIABLE = 4;
- public static final int PARAMETER = 5;
-
- /**
- * Returns the constant kind of this variable declaration
- */
- public abstract int getKind();
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.lookup.InvocationSite#isSuperAccess()
- */
- public boolean isSuperAccess() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.lookup.InvocationSite#isTypeAccess()
- */
- public boolean isTypeAccess() {
- return false;
- }
-
- public StringBuffer printStatement(int indent, StringBuffer output) {
- printAsExpression(indent, output);
- return output.append(';');
- }
-
- public StringBuffer printAsExpression(int indent, StringBuffer output) {
- printIndent(indent, output);
- printModifiers(this.modifiers, output);
- output.append("var "); //$NON-NLS-1$
-
- printFragment(indent, output);
- if (this.nextLocal!=null)
- {
- output.append(", "); //$NON-NLS-1$
- this.nextLocal.printFragment(indent, output);
- }
- return output;
- }
-
- protected void printFragment(int indent, StringBuffer output) {
- if (type != null) {
- type.print(0, output).append(' ');
- }
- output.append(this.name);
-
- if (initialization != null) {
- output.append(" = "); //$NON-NLS-1$
- initialization.printExpression(indent, output);
- }
- }
-
- public void resolve(BlockScope scope) {
- // do nothing by default (redefined for local variables)
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.lookup.InvocationSite#setActualReceiverType(org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding)
- */
- public void setActualReceiverType(ReferenceBinding receiverType) {
- // do nothing by default
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.lookup.InvocationSite#setDepth(int)
- */
- public void setDepth(int depth) {
-
- this.hiddenVariableDepth = depth;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.lookup.InvocationSite#setFieldIndex(int)
- */
- public void setFieldIndex(int depth) {
- // do nothing by default
- }
-
- public TypeBinding getTypeBinding()
- {
- if (type!=null)
- return type.resolvedType;
- else if (inferredType!=null)
- return inferredType.binding;
- return null;
-
- }
- public int getASTType() {
- return IASTNode.ABSTRACT_VARIABLE_DECLARATION;
-
- }
-
- public IJsDoc getJsDoc()
- {
- return this.javadoc;
- }
-
- public IExpression getInitialization()
- {
- return this.initialization;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/AllocationExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/AllocationExpression.java
deleted file mode 100644
index 07aba58e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/AllocationExpression.java
+++ /dev/null
@@ -1,221 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IAllocationExpression;
-import org.eclipse.wst.jsdt.core.ast.IExpression;
-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;
-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.InvocationSite;
-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.ProblemMethodBinding;
-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.TypeBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeConstants;
-
-public class AllocationExpression extends Expression implements InvocationSite, IAllocationExpression {
-
- public TypeReference type;
- public Expression[] arguments;
- public MethodBinding binding; // exact binding resulting from lookup
- protected MethodBinding codegenBinding; // actual binding used for code generation (if no synthetic accessor)
- public Expression member;
- public boolean isShort;
-
-
- public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {
- if (this.member!=null)
- flowInfo =
- this.member
- .analyseCode(currentScope, flowContext, flowInfo)
- .unconditionalInits();
- // process arguments
- if (arguments != null) {
- for (int i = 0, count = arguments.length; i < count; i++) {
- flowInfo =
- arguments[i]
- .analyseCode(currentScope, flowContext, flowInfo)
- .unconditionalInits();
- }
- }
-
- return flowInfo;
- }
-
- public Expression enclosingInstance() {
- return null;
- }
-
- public boolean isSuperAccess() {
- return false;
- }
-
- public boolean isTypeAccess() {
- return true;
- }
-
- /* Inner emulation consists in either recording a dependency
- * link only, or performing one level of propagation.
- *
- * Dependency mechanism is used whenever dealing with source target
- * types, since by the time we reach them, we might not yet know their
- * exact need.
- */
- public void manageEnclosingInstanceAccessIfNecessary(BlockScope currentScope, FlowInfo flowInfo) {
- if ((flowInfo.tagBits & FlowInfo.UNREACHABLE) != 0) return;
- ReferenceBinding allocatedTypeErasure = binding.declaringClass;
-
- // perform some emulation work in case there is some and we are inside a local type only
- if (allocatedTypeErasure.isNestedType()
- && currentScope.enclosingSourceType().isLocalType()) {
-
- if (allocatedTypeErasure.isLocalType()) {
- ((LocalTypeBinding) allocatedTypeErasure).addInnerEmulationDependent(currentScope, false);
- // request cascade of accesses
- }
- }
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output) {
- output.append("new "); //$NON-NLS-1$
- member.print(indent, output);
-
- if (type != null) { // type null for enum constant initializations
- type.printExpression(0, output);
- }
- if (!isShort)
- {
- 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);
- }
- }
- output.append(')');
- }
- return output;
- }
-
- public TypeBinding resolveType(BlockScope scope) {
- // Propagate the type checking to the arguments, and check if the constructor is defined.
- constant = Constant.NotAConstant;
- if (this.member!=null) {
- this.resolvedType=this.member.resolveForAllocation(scope, this);
- if (this.resolvedType!=null && !this.resolvedType.isValidBinding()) {
- scope.problemReporter().invalidType(this, this.resolvedType);
- }
- }
- else if (this.type == null) {
- // initialization of an enum constant
- this.resolvedType = scope.enclosingReceiverType();
- }
- else {
- this.resolvedType = this.type.resolveType(scope, true /* check bounds*/);
- }
- // will check for null after args are resolved
- // buffering the arguments' types
- boolean argsContainCast = false;
- TypeBinding[] argumentTypes = Binding.NO_PARAMETERS;
- if (arguments != null) {
- boolean argHasError = false;
- int length = arguments.length;
- argumentTypes = new TypeBinding[length];
- for (int i = 0; i < length; i++) {
- Expression argument = this.arguments[i];
- if ((argumentTypes[i] = argument.resolveType(scope)) == null) {
- argHasError = true;
- argumentTypes[i]=TypeBinding.UNKNOWN;
- }
- }
- }
- if (this.resolvedType == null || this.resolvedType.isAnyType()|| this.resolvedType instanceof ProblemReferenceBinding)
- {
- this.binding= new ProblemMethodBinding(
- TypeConstants.INIT,
- Binding.NO_PARAMETERS,
- ProblemReasons.NotFound);
- this.resolvedType=TypeBinding.UNKNOWN;
- return this.resolvedType;
-
- }
-
- if (!this.resolvedType.isValidBinding())
- return null;
- if (this.resolvedType instanceof ReferenceBinding )
- {
- ReferenceBinding allocationType = (ReferenceBinding) this.resolvedType;
- if (!(binding = scope.getConstructor(allocationType, argumentTypes, this)).isValidBinding()) {
- if (binding.declaringClass == null)
- binding.declaringClass = allocationType;
- scope.problemReporter().invalidConstructor(this, binding);
- return this.resolvedType;
- }
- if (argumentTypes.length!=binding.parameters.length)
- scope.problemReporter().wrongNumberOfArguments(this, binding);
- if (isMethodUseDeprecated(binding, scope, true))
- scope.problemReporter().deprecatedMethod(binding, this);
- checkInvocationArguments(scope, null, allocationType, this.binding, this.arguments, argumentTypes, argsContainCast, this);
- }
-
- return this.resolvedType;
- }
-
- public void setActualReceiverType(ReferenceBinding receiverType) {
- // ignored
- }
-
- public void setDepth(int i) {
- // ignored
- }
-
- public void setFieldIndex(int i) {
- // ignored
- }
-
- public void traverse(ASTVisitor visitor, BlockScope scope) {
- if (visitor.visit(this, scope)) {
- if (this.member!=null)
- this.member.traverse(visitor, scope);
- else if (this.type != null) { // enum constant scenario
- this.type.traverse(visitor, scope);
- }
- if (this.arguments != null) {
- for (int i = 0, argumentsLength = this.arguments.length; i < argumentsLength; i++)
- this.arguments[i].traverse(visitor, scope);
- }
- }
- visitor.endVisit(this, scope);
- }
- public int getASTType() {
- return IASTNode.ALLOCATION_EXPRESSION;
-
- }
-
- public IExpression getMember() {
- return this.member;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.Expression#resolveForAllocation(org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope, org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode)
- */
- public TypeBinding resolveForAllocation(BlockScope scope, ASTNode location) {
- return this.resolveType(scope);
- }
-}
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
deleted file mode 100644
index 707b418c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Argument.java
+++ /dev/null
@@ -1,158 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IArgument;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-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.LocalVariableBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class Argument extends LocalDeclaration implements IArgument {
-
- public char [] comment;
-
- public Argument(char[] name, long posNom, TypeReference tr, int modifiers) {
-
- super(name, (int) (posNom >>> 32), (int) posNom);
- this.declarationSourceEnd = (int) posNom;
- this.modifiers = modifiers;
- type = tr;
- this.bits |= IsLocalDeclarationReachable;
- }
-
- public char[] getComment() {
- return this.comment;
- }
-
- 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 ){
- 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())
- 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);
- //true stand for argument instead of just local
- this.binding.declaration = this;
- this.binding.useFlag = used ? LocalVariableBinding.USED : LocalVariableBinding.UNUSED;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.AbstractVariableDeclaration#getKind()
- */
- public int getKind() {
- return PARAMETER;
- }
-
- public boolean isVarArgs() {
- return this.type != null && (this.type.bits & IsVarArgs) != 0;
- }
-
- public StringBuffer print(int indent, StringBuffer output) {
-
- printIndent(indent, output);
- printModifiers(this.modifiers, output);
-// if (this.annotations != null) printAnnotations(this.annotations, output);
-
-// if (type == null) {
-// output.append("<no type> "); //$NON-NLS-1$
-// } else {
-// type.print(0, output).append(' ');
-// }
- return output.append(this.name);
- }
-
- public StringBuffer printStatement(int indent, StringBuffer output) {
-
- return print(indent, output).append(';');
- }
-
- public TypeBinding resolveForCatch(BlockScope scope) {
-
- // resolution on an argument of a catch clause
- // provide the scope with a side effect : insertion of a LOCAL
- // that represents the argument. The type must be from JavaThrowable
-
- ReferenceBinding javaLangError = scope.getJavaLangError();
- TypeBinding exceptionType = this.type!=null ?
- this.type.resolveType(scope, true /* check bounds*/) : javaLangError;
- if (exceptionType == null) return null;
- boolean hasError = false;
-
- Binding existingVariable = scope.getBinding(name, Binding.VARIABLE, this, false /*do not resolve hidden field*/);
- if (existingVariable != null && existingVariable.isValidBinding()){
-// if (existingVariable instanceof LocalVariableBinding && this.hiddenVariableDepth == 0) {
-// scope.problemReporter().redefineArgument(this);
-// } else {
- scope.problemReporter().localVariableHiding(this, existingVariable, false);
-// }
- }
-
- this.binding = new LocalVariableBinding(this, exceptionType, modifiers, false); // argument decl, but local var (where isArgument = false)
-// resolveAnnotations(scope, this.annotations, this.binding);
-
- scope.addLocalVariable(binding);
- if (hasError) return null;
- return exceptionType;
- }
-
- public void traverse(ASTVisitor visitor, BlockScope scope) {
-
- if (visitor.visit(this, scope)) {
- if (type != null)
- type.traverse(visitor, scope);
- }
- visitor.endVisit(this, scope);
- }
-
- public void traverse(ASTVisitor visitor, ClassScope scope) {
-
- if (visitor.visit(this, scope)) {
- if (type != null)
- type.traverse(visitor, scope);
- }
- visitor.endVisit(this, scope);
- }
-
- public int getASTType() {
- return IASTNode.ARGUMENT;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ArrayAllocationExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ArrayAllocationExpression.java
deleted file mode 100644
index f1ab0615..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ArrayAllocationExpression.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IArrayAllocationExpression;
-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;
-import org.eclipse.wst.jsdt.internal.compiler.impl.Constant;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ArrayBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class ArrayAllocationExpression extends Expression implements IArrayAllocationExpression {
-
- public TypeReference type;
-
- //dimensions.length gives the number of dimensions, but the
- // last ones may be nulled as in new int[4][5][][]
- public Expression[] dimensions;
- public ArrayInitializer initializer;
-
- public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {
- for (int i = 0, max = this.dimensions.length; i < max; i++) {
- Expression dim;
- if ((dim = this.dimensions[i]) != null) {
- flowInfo = dim.analyseCode(currentScope, flowContext, flowInfo);
- }
- }
- if (this.initializer != null) {
- return this.initializer.analyseCode(currentScope, flowContext, flowInfo);
- }
- return flowInfo;
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output) {
- output.append("new "); //$NON-NLS-1$
- this.type.print(0, output);
- for (int i = 0; i < this.dimensions.length; i++) {
- if (this.dimensions[i] == null)
- output.append("[]"); //$NON-NLS-1$
- else {
- output.append('[');
- this.dimensions[i].printExpression(0, output);
- output.append(']');
- }
- }
- if (this.initializer != null) this.initializer.printExpression(0, output);
- return output;
- }
-
- public TypeBinding resolveType(BlockScope scope) {
- // Build an array type reference using the current dimensions
- // The parser does not check for the fact that dimension may be null
- // only at the -end- like new int [4][][]. The parser allows new int[][4][]
- // so this must be checked here......(this comes from a reduction to LL1 grammar)
-
- TypeBinding referenceType = this.type.resolveType(scope, true /* check bounds*/);
-
- // will check for null after dimensions are checked
- this.constant = Constant.NotAConstant;
-
- // check the validity of the dimension syntax (and test for all null dimensions)
- int explicitDimIndex = -1;
- loop: for (int i = this.dimensions.length; --i >= 0;) {
- if (this.dimensions[i] != null) {
- if (explicitDimIndex < 0) explicitDimIndex = i;
- } else if (explicitDimIndex > 0) {
- break loop;
- }
- }
-
- // dimensions resolution
- for (int i = 0; i <= explicitDimIndex; i++) {
- Expression dimExpression;
- if ((dimExpression = this.dimensions[i]) != null) {
- TypeBinding dimensionType = dimExpression.resolveTypeExpecting(scope, TypeBinding.INT);
- }
- }
-
- // building the array binding
- if (referenceType != null) {
- this.resolvedType = scope.createArrayType(referenceType, this.dimensions.length);
-
- // check the initializer
- if (this.initializer != null) {
- if ((this.initializer.resolveTypeExpecting(scope, this.resolvedType)) != null)
- this.initializer.binding = (ArrayBinding)this.resolvedType;
- }
- }
- return this.resolvedType;
- }
-
-
- public void traverse(ASTVisitor visitor, BlockScope scope) {
- if (visitor.visit(this, scope)) {
- int dimensionsLength = this.dimensions.length;
- this.type.traverse(visitor, scope);
- for (int i = 0; i < dimensionsLength; i++) {
- if (this.dimensions[i] != null)
- this.dimensions[i].traverse(visitor, scope);
- }
- if (this.initializer != null)
- this.initializer.traverse(visitor, scope);
- }
- visitor.endVisit(this, scope);
- }
- public int getASTType() {
- return IASTNode.ARRAY_ALLOCATION_EXPRESSION;
-
- }
-}
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
deleted file mode 100644
index 7b5f95fc..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ArrayInitializer.java
+++ /dev/null
@@ -1,177 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IArrayInitializer;
-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.ArrayBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BaseTypeBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class ArrayInitializer extends Expression implements IArrayInitializer {
-
- public Expression[] expressions;
- public ArrayBinding binding; //the type of the { , , , }
-
- /**
- * ArrayInitializer constructor comment.
- */
- public ArrayInitializer() {
-
- super();
- }
-
- public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {
-
- if (expressions != null) {
- for (int i = 0, max = expressions.length; i < max; i++) {
- flowInfo = expressions[i].analyseCode(currentScope, flowContext, flowInfo).unconditionalInits();
- }
- }
- return flowInfo;
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output) {
-
- output.append('[');
- if (expressions != null) {
- int j = 20 ;
- for (int i = 0 ; i < expressions.length ; i++) {
- if (i > 0) output.append(", "); //$NON-NLS-1$
- if (expressions[i]!=null)
- expressions[i].printExpression(0, output);
- j -- ;
- if (j == 0) {
- output.append('\n');
- printIndent(indent+1, output);
- j = 20;
- }
- }
- }
- return output.append(']');
- }
-
- public TypeBinding resolveType(BlockScope scope) {
- this.constant = Constant.NotAConstant;
- this.resolvedType = this.binding = new ArrayBinding(TypeBinding.UNKNOWN,1,scope.environment());
- if (this.expressions!=null)
- for (int i = 0, length = this.expressions.length; i < length; i++) {
- Expression expression = this.expressions[i];
- expression.resolveType(scope);
- }
- return this.resolvedType;
- }
-
- public TypeBinding resolveTypeExpecting(BlockScope scope, TypeBinding expectedType) {
- // Array initializers can only occur on the right hand side of an assignment
- // expression, therefore the expected type contains the valid information
- // concerning the type that must be enforced by the elements of the array initializer.
-
- // this method is recursive... (the test on isArrayType is the stop case)
-
- 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;
- TypeBinding elementType = this.binding.elementsType();
- for (int i = 0, length = this.expressions.length; i < length; i++) {
- Expression expression = this.expressions[i];
- expression.setExpectedType(elementType);
- TypeBinding exprType = expression instanceof ArrayInitializer
- ? expression.resolveTypeExpecting(scope, elementType)
- : expression.resolveType(scope);
- if (exprType == null)
- continue;
-
- // Compile-time conversion required?
- if (elementType != exprType) // must call before computeConversion() and typeMismatchError()
- scope.compilationUnitScope().recordTypeConversion(elementType, exprType);
-
- if ((expression.isConstantValueOfTypeAssignableToType(exprType, elementType)
- || (elementType.isBaseType() && BaseTypeBinding.isWidening(elementType.id, exprType.id)))
- || exprType.isCompatibleWith(elementType)) {
- } else if (scope.isBoxingCompatibleWith(exprType, elementType)
- || (exprType.isBaseType() // narrowing then boxing ?
- && scope.compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5 // autoboxing
- && !elementType.isBaseType()
- && expression.isConstantValueOfTypeAssignableToType(exprType, scope.environment().computeBoxingType(elementType)))) {
- } else {
- scope.problemReporter().typeMismatchError(exprType, elementType, expression);
-// return null;
- }
- }
- return this.binding;
- }
-
- // infer initializer type for error reporting based on first element
- TypeBinding leafElementType = null;
- int dim = 1;
- if (this.expressions == null) {
- leafElementType = TypeBinding.UNKNOWN;
- } else {
- Expression expression = this.expressions[0];
- while(expression != null && expression instanceof ArrayInitializer) {
- dim++;
- Expression[] subExprs = ((ArrayInitializer) expression).expressions;
- if (subExprs == null){
- leafElementType = scope.getJavaLangObject();
- expression = null;
- break;
- }
- expression = ((ArrayInitializer) expression).expressions[0];
- }
- if (expression != null) {
- leafElementType = expression.resolveType(scope);
- }
- // fault-tolerance - resolve other expressions as well
- for (int i = 1, length = this.expressions.length; i < length; i++) {
- expression = this.expressions[i];
- if (expression != null) {
- expression.resolveType(scope) ;
- }
- } }
- if (leafElementType != null) {
- this.resolvedType = scope.createArrayType(leafElementType, dim);
- if (expectedType != null )
- scope.problemReporter().typeMismatchError(this.resolvedType, expectedType, this);
- }
- return null;
- }
-
- public void traverse(ASTVisitor visitor, BlockScope scope) {
-
- if (visitor.visit(this, scope)) {
- if (this.expressions != null) {
- int expressionsLength = this.expressions.length;
- for (int i = 0; i < expressionsLength; i++)
- if (this.expressions[i]!=null)
- this.expressions[i].traverse(visitor, scope);
- }
- }
- visitor.endVisit(this, scope);
- }
- public int getASTType() {
- return IASTNode.ARRAY_INITIALIZER;
-
- }
-}
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
deleted file mode 100644
index 32ef489a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ArrayQualifiedTypeReference.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IArrayQualifiedTypeReference;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-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.LookupEnvironment;
-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.AbortCompilation;
-
-public class ArrayQualifiedTypeReference extends QualifiedTypeReference implements IArrayQualifiedTypeReference {
- int dimensions;
-
- public ArrayQualifiedTypeReference(char[][] sources , int dim, long[] poss) {
-
- super( sources , poss);
- dimensions = dim ;
- }
-
- public int dimensions() {
-
- return dimensions;
- }
-
- /**
- * @return char[][]
- */
- public char [][] getParameterizedTypeName(){
- int dim = this.dimensions;
- char[] dimChars = new char[dim*2];
- for (int i = 0; i < dim; i++) {
- int index = i*2;
- dimChars[index] = '[';
- dimChars[index+1] = ']';
- }
- int length = this.tokens.length;
- char[][] qParamName = new char[length][];
- System.arraycopy(this.tokens, 0, qParamName, 0, length-1);
- qParamName[length-1] = CharOperation.concat(this.tokens[length-1], dimChars);
- return qParamName;
- }
-
- protected TypeBinding getTypeBinding(Scope scope) {
-
- if (this.resolvedType != null)
- return this.resolvedType;
- LookupEnvironment env = scope.environment();
- try {
- env.missingClassFileLocation = this;
- TypeBinding leafComponentType = super.getTypeBinding(scope);
- return this.resolvedType = scope.createArrayType(leafComponentType, dimensions);
- } catch (AbortCompilation e) {
- e.updateContext(this, scope.referenceCompilationUnit().compilationResult);
- throw e;
- } finally {
- env.missingClassFileLocation = null;
- }
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output){
-
- super.printExpression(indent, output);
- if ((this.bits & IsVarArgs) != 0) {
- for (int i= 0 ; i < dimensions - 1; i++) {
- output.append("[]"); //$NON-NLS-1$
- }
- output.append("..."); //$NON-NLS-1$
- } else {
- for (int i= 0 ; i < dimensions; i++) {
- output.append("[]"); //$NON-NLS-1$
- }
- }
- return output;
- }
-
- public void traverse(ASTVisitor visitor, BlockScope scope) {
-
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
- }
-
- public void traverse(ASTVisitor visitor, ClassScope scope) {
-
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
- }
- public int getASTType() {
- return IASTNode.ARRAY_QUALIFIED_TYPE_REFERENCE;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ArrayReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ArrayReference.java
deleted file mode 100644
index f18bba61..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ArrayReference.java
+++ /dev/null
@@ -1,109 +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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IArrayReference;
-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;
-import org.eclipse.wst.jsdt.internal.compiler.impl.Constant;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ArrayBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class ArrayReference extends Reference implements IArrayReference {
-
- public Expression receiver;
- public Expression position;
-
- public ArrayReference(Expression rec, Expression pos) {
- this.receiver = rec;
- this.position = pos;
- sourceStart = rec.sourceStart;
- }
-
-public FlowInfo analyseAssignment(
- BlockScope currentScope,
- FlowContext flowContext,
- FlowInfo flowInfo,
- Assignment assignment,
- boolean compoundAssignment) {
- // TODO (maxime) optimization: unconditionalInits is applied to all existing calls
- if (assignment.expression == null) {
- return analyseCode(currentScope, flowContext, flowInfo);
- }
- return assignment
- .expression
- .analyseCode(
- currentScope,
- flowContext,
- analyseCode(currentScope, flowContext, flowInfo).unconditionalInits());
-}
-
-public FlowInfo analyseCode(
- BlockScope currentScope,
- FlowContext flowContext,
- FlowInfo flowInfo) {
- receiver.checkNPE(currentScope, flowContext, flowInfo);
- flowInfo = receiver.analyseCode(currentScope, flowContext, flowInfo);
- return position.analyseCode(currentScope, flowContext, flowInfo);
-}
-
- public int nullStatus(FlowInfo flowInfo) {
- return FlowInfo.UNKNOWN;
-}
-
- public StringBuffer printExpression(int indent, StringBuffer output) {
-
- receiver.printExpression(0, output).append('[');
- return position.printExpression(0, output).append(']');
- }
-
- public TypeBinding resolveType(BlockScope scope) {
-
- constant = Constant.NotAConstant;
-// if (receiver instanceof CastExpression // no cast check for ((type[])null)[0]
-// && ((CastExpression)receiver).innermostCastedExpression() instanceof NullLiteral) {
-// this.receiver.bits |= DisableUnnecessaryCastCheck; // will check later on
-// }
- TypeBinding arrayType = receiver.resolveType(scope);
- if (arrayType != null) {
- if (arrayType.isArrayType()) {
- TypeBinding elementType = ((ArrayBinding) arrayType).elementsType();
- this.resolvedType = elementType;
- } else {
-// scope.problemReporter().referenceMustBeArrayTypeAt(arrayType, this);
- this.resolvedType=TypeBinding.UNKNOWN;
- }
- }
- else
- this.resolvedType=TypeBinding.UNKNOWN;
- position.resolveTypeExpecting(scope, new TypeBinding[] {scope.getJavaLangNumber(),scope.getJavaLangString(),TypeBinding.ANY});
-// if (positionType != null) {
-// position.computeConversion(scope, TypeBinding.INT, positionType);
-// }
- return this.resolvedType;
- }
-
- public void traverse(ASTVisitor visitor, BlockScope scope) {
-
- if (visitor.visit(this, scope)) {
- receiver.traverse(visitor, scope);
- position.traverse(visitor, scope);
- }
- visitor.endVisit(this, scope);
- }
- public int getASTType() {
- return IASTNode.ARRAY_REFERENCE;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ArrayTypeReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ArrayTypeReference.java
deleted file mode 100644
index 55e173c3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ArrayTypeReference.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IArrayTypeReference;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-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.Scope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class ArrayTypeReference extends SingleTypeReference implements IArrayTypeReference {
- public int dimensions;
- public int originalSourceEnd;
-
- /**
- * ArrayTypeReference constructor comment.
- * @param source char[]
- * @param dimensions int
- * @param pos int
- */
- public ArrayTypeReference(char[] source, int dimensions, long pos) {
-
- super(source, pos);
- this.originalSourceEnd = this.sourceEnd;
- this.dimensions = dimensions ;
- }
-
- public int dimensions() {
-
- return dimensions;
- }
- /**
- * @return char[][]
- */
- public char [][] getParameterizedTypeName(){
- int dim = this.dimensions;
- char[] dimChars = new char[dim*2];
- for (int i = 0; i < dim; i++) {
- int index = i*2;
- dimChars[index] = '[';
- dimChars[index+1] = ']';
- }
- return new char[][]{ CharOperation.concat(token, dimChars) };
- }
- protected TypeBinding getTypeBinding(Scope scope) {
-
- if (this.resolvedType != null) return this.resolvedType;
- TypeBinding leafComponentType = scope.getType(token);
- return scope.createArrayType(leafComponentType, dimensions);
-
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output){
-
- super.printExpression(indent, output);
- if ((this.bits & IsVarArgs) != 0) {
- for (int i= 0 ; i < dimensions - 1; i++) {
- output.append("[]"); //$NON-NLS-1$
- }
- output.append("..."); //$NON-NLS-1$
- } else {
- for (int i= 0 ; i < dimensions; i++) {
- output.append("[]"); //$NON-NLS-1$
- }
- }
- return output;
- }
-
- public void traverse(ASTVisitor visitor, BlockScope scope) {
-
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
- }
-
- public void traverse(ASTVisitor visitor, ClassScope scope) {
-
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
- }
- public int getASTType() {
- return IASTNode.ARRAY_TYPE_REFERENCE;
-
- }
-}
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
deleted file mode 100644
index 97942cf5..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Assignment.java
+++ /dev/null
@@ -1,258 +0,0 @@
-/*******************************************************************************
- * 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
- * Genady Beriozkin - added support for reporting assignment with no effect
- *******************************************************************************/
-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.IJsDoc;
-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.BaseTypeBinding;
-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.LocalVariableBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TagBits;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class Assignment extends Expression implements IAssignment {
-
- public Expression lhs;
- public Expression expression;
- 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);
- }
- }
- 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);
- }
- 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;
-}
-
-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) {
- 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);
- }
- }
-// } 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;
-}
-
-
-
-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;
- }
- 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;
- }
-
- //check if the lhs is prototype, in which case we are done
- if( lhs instanceof FieldReference && ((FieldReference)lhs).isPrototype() )
- return this.resolvedType;
-
- // check for assignment with no effect
- Binding left = getDirectBinding(this.lhs);
- if (left != null && left == getDirectBinding(this.expression)) {
- scope.problemReporter().assignmentHasNoEffect(this, left.shortReadableName());
- }
-
- // 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;
- }
- 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);
- }
- 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);
- }
- visitor.endVisit(this, scope);
-}
-public LocalVariableBinding localVariableBinding() {
- return lhs.localVariableBinding();
-}
-public int getASTType() {
- return IASTNode.ASSIGNMENT;
-
-}
-
-public IExpression getExpression() {
- return this.expression;
-}
-
-public IExpression getLeftHandSide() {
- return this.lhs;
-}
-
-public IJsDoc getJsDoc() {
- return javadoc;
-}
-
-public void setInferredType(InferredType type) {
- this.inferredType = type;
-
-}
-
-public InferredType getInferredType() {
- return this.inferredType;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/BinaryExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/BinaryExpression.java
deleted file mode 100644
index 8e0c81eb..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/BinaryExpression.java
+++ /dev/null
@@ -1,383 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IBinaryExpression;
-import org.eclipse.wst.jsdt.core.ast.IExpression;
-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.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeIds;
-
-public class BinaryExpression extends OperatorExpression implements IBinaryExpression {
-
-/* Tracking helpers
- * The following are used to elaborate realistic statistics about binary
- * expressions. This must be neutralized in the released code.
- * Search the keyword BE_INSTRUMENTATION to reenable.
- * An external device must install a suitable probe so as to monitor the
- * emission of events and publish the results.
- public interface Probe {
- public void ping(int depth);
- }
- public int depthTracker;
- public static Probe probe;
- */
-
- public Expression left, right;
- public Constant optimizedBooleanConstant;
-
-public BinaryExpression(Expression left, Expression right, int operator) {
- this.left = left;
- this.right = right;
- this.bits |= operator << ASTNode.OperatorSHIFT; // encode operator
- this.sourceStart = left.sourceStart;
- this.sourceEnd = right.sourceEnd;
- // BE_INSTRUMENTATION: neutralized in the released code
-// if (left instanceof BinaryExpression &&
-// ((left.bits & OperatorMASK) ^ (this.bits & OperatorMASK)) == 0) {
-// this.depthTracker = ((BinaryExpression)left).depthTracker + 1;
-// } else {
-// this.depthTracker = 1;
-// }
-}
-
-public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext,
- FlowInfo flowInfo) {
- // keep implementation in sync with CombinedBinaryExpression#analyseCode
- if (this.resolvedType.id == TypeIds.T_JavaLangString) {
- return this.right.analyseCode(
- currentScope, flowContext,
- this.left.analyseCode(currentScope, flowContext, flowInfo).unconditionalInits())
- .unconditionalInits();
- } else {
- this.left.checkNPE(currentScope, flowContext, flowInfo);
- flowInfo = this.left.analyseCode(currentScope, flowContext, flowInfo).unconditionalInits();
- this.right.checkNPE(currentScope, flowContext, flowInfo);
- return this.right.analyseCode(currentScope, flowContext, flowInfo).unconditionalInits();
- }
-}
-
-public void computeConstant(BlockScope scope, int leftId, int rightId) {
- //compute the constant when valid
-
- /* bchilds - Not sure about this change but left side was null (variable) and causing NPE further down */
-
- if(this.left.constant==null) this.left.constant= Constant.NotAConstant;
- if(this.right.constant==null) this.left.constant= Constant.NotAConstant;
-
- if ((this.left.constant != Constant.NotAConstant)
- && (this.right.constant != Constant.NotAConstant)) {
- try {
- this.constant =
- Constant.computeConstantOperation(
- this.left.constant,
- leftId,
- (this.bits & ASTNode.OperatorMASK) >> ASTNode.OperatorSHIFT,
- this.right.constant,
- rightId);
- } catch (Exception e) {
- this.constant = Constant.NotAConstant;
- // 1.2 no longer throws an exception at compile-time
- //scope.problemReporter().compileTimeConstantThrowsArithmeticException(this);
- }
- } else {
- this.constant = Constant.NotAConstant;
- //add some work for the boolean operators & |
- this.optimizedBooleanConstant(
- leftId,
- (this.bits & ASTNode.OperatorMASK) >> ASTNode.OperatorSHIFT,
- rightId);
- }
-}
-
-public Constant optimizedBooleanConstant() {
- return this.optimizedBooleanConstant == null ? this.constant : this.optimizedBooleanConstant;
-}
-
-public boolean isCompactableOperation() {
- return true;
-}
-
-/**
- * Separates into a reusable method the subpart of {@link
- * #resolveType(BlockScope)} that needs to be executed while climbing up the
- * chain of expressions of this' leftmost branch. For use by {@link
- * CombinedBinaryExpression#resolveType(BlockScope)}.
- * @param scope the scope within which the resolution occurs
- */
-void nonRecursiveResolveTypeUpwards(BlockScope scope) {
- // keep implementation in sync with BinaryExpression#resolveType
- TypeBinding leftType = this.left.resolvedType;
-
- TypeBinding rightType = this.right.resolveType(scope);
-
- // use the id of the type to navigate into the table
- if (leftType == null || rightType == null) {
- this.constant = Constant.NotAConstant;
- return;
- }
-
- int leftTypeID = leftType.id;
- int rightTypeID = rightType.id;
-
- // autoboxing support
- boolean use15specifics = scope.compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5;
- if (use15specifics) {
- if (!leftType.isBaseType() && rightTypeID != TypeIds.T_JavaLangString && rightTypeID != TypeIds.T_null) {
- leftTypeID = scope.environment().computeBoxingType(leftType).id;
- }
- if (!rightType.isBaseType() && leftTypeID != TypeIds.T_JavaLangString && leftTypeID != TypeIds.T_null) {
- rightTypeID = scope.environment().computeBoxingType(rightType).id;
- }
- }
- if (leftTypeID > 15
- || rightTypeID > 15) { // must convert String + Object || Object + String
- if (leftTypeID == TypeIds.T_JavaLangString) {
- rightTypeID = TypeIds.T_JavaLangObject;
- } else if (rightTypeID == TypeIds.T_JavaLangString) {
- leftTypeID = TypeIds.T_JavaLangObject;
- } else {
- this.constant = Constant.NotAConstant;
- scope.problemReporter().invalidOperator(this, leftType, rightType);
- return;
- }
- }
-
- // the code is an int
- // (cast) left Op (cast) right --> result
- // 0000 0000 0000 0000 0000
- // <<16 <<12 <<8 <<4 <<0
-
- // Don't test for result = 0. If it is zero, some more work is done.
- // On the one hand when it is not zero (correct code) we avoid doing the test
- int operator = (this.bits & ASTNode.OperatorMASK) >> ASTNode.OperatorSHIFT;
- int operatorSignature = OperatorExpression.OperatorSignatures[operator][(leftTypeID << 4) + rightTypeID];
-
- this.bits |= operatorSignature & 0xF;
- switch (operatorSignature & 0xF) { // record the current ReturnTypeID
- // only switch on possible result type.....
- case T_boolean :
- this.resolvedType = TypeBinding.BOOLEAN;
- break;
- case T_char :
- this.resolvedType = TypeBinding.CHAR;
- break;
- case T_double :
- this.resolvedType = TypeBinding.DOUBLE;
- break;
- case T_float :
- this.resolvedType = TypeBinding.FLOAT;
- break;
- case T_int :
- this.resolvedType = TypeBinding.INT;
- break;
- case T_long :
- this.resolvedType = TypeBinding.LONG;
- break;
- case T_JavaLangString :
- this.resolvedType = scope.getJavaLangString();
- break;
- default : //error........
- this.constant = Constant.NotAConstant;
- scope.problemReporter().invalidOperator(this, leftType, rightType);
- return;
- }
-
- // compute the constant when valid
- computeConstant(scope, leftTypeID, rightTypeID);
-}
-
-public void optimizedBooleanConstant(int leftId, int operator, int rightId) {
- switch (operator) {
- case AND :
- if ((leftId != TypeIds.T_boolean) || (rightId != TypeIds.T_boolean))
- return;
- case AND_AND :
- Constant cst;
- if ((cst = this.left.optimizedBooleanConstant()) != Constant.NotAConstant) {
- if (cst.booleanValue() == false) { // left is equivalent to false
- this.optimizedBooleanConstant = cst; // constant(false)
- return;
- } else { //left is equivalent to true
- if ((cst = this.right.optimizedBooleanConstant()) != Constant.NotAConstant) {
- this.optimizedBooleanConstant = cst;
- // the conditional result is equivalent to the right conditional value
- }
- return;
- }
- }
- if ((cst = this.right.optimizedBooleanConstant()) != Constant.NotAConstant) {
- if (cst.booleanValue() == false) { // right is equivalent to false
- this.optimizedBooleanConstant = cst; // constant(false)
- }
- }
- return;
- case OR :
- if ((leftId != TypeIds.T_boolean) || (rightId != TypeIds.T_boolean))
- return;
- case OR_OR :
- if ((cst = this.left.optimizedBooleanConstant()) != Constant.NotAConstant) {
- if (cst.booleanValue() == true) { // left is equivalent to true
- this.optimizedBooleanConstant = cst; // constant(true)
- return;
- } else { //left is equivalent to false
- if ((cst = this.right.optimizedBooleanConstant()) != Constant.NotAConstant) {
- this.optimizedBooleanConstant = cst;
- }
- return;
- }
- }
- if ((cst = this.right.optimizedBooleanConstant()) != Constant.NotAConstant) {
- if (cst.booleanValue() == true) { // right is equivalent to true
- this.optimizedBooleanConstant = cst; // constant(true)
- }
- }
- }
-}
-
-public StringBuffer printExpressionNoParenthesis(int indent, StringBuffer output) {
- // keep implementation in sync with
- // CombinedBinaryExpression#printExpressionNoParenthesis
- this.left.printExpression(indent, output).append(' ').append(operatorToString()).append(' ');
- return this.right.printExpression(0, output);
-}
-
-public TypeBinding resolveType(BlockScope scope) {
- // keep implementation in sync with CombinedBinaryExpression#resolveType
- // and nonRecursiveResolveTypeUpwards
- TypeBinding leftType = this.left.resolveType(scope);
- TypeBinding rightType = this.right.resolveType(scope);
-
- // use the id of the type to navigate into the table
- if (leftType == null || rightType == null) {
- this.constant = Constant.NotAConstant;
- this.resolvedType=TypeBinding.ANY;
- return null;
- }
- int operator = (this.bits & ASTNode.OperatorMASK) >> ASTNode.OperatorSHIFT;
-
- int leftTypeID = leftType.id;
- int rightTypeID = rightType.id;
-
- if(operator==OperatorIds.INSTANCEOF || operator==OperatorIds.IN || operator==OperatorIds.OR_OR) {
- if ( rightTypeID>15)
- rightTypeID= TypeIds.T_JavaLangObject;
- if ( leftTypeID>15)
- leftTypeID= TypeIds.T_JavaLangObject;
- }
-
- // autoboxing support
- boolean use15specifics = scope.compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5;
- if (use15specifics) {
- if (!leftType.isBaseType() && rightTypeID != TypeIds.T_JavaLangString && rightTypeID != TypeIds.T_null) {
- leftTypeID = scope.environment().computeBoxingType(leftType).id;
- }
- if (!rightType.isBaseType() && leftTypeID != TypeIds.T_JavaLangString && leftTypeID != TypeIds.T_null) {
- rightTypeID = scope.environment().computeBoxingType(rightType).id;
- }
- }
- if (rightType.isArrayType())
- {
- rightType=rightType.leafComponentType();
- rightTypeID=rightType.id;
- }
- if (leftTypeID > 15
- || rightTypeID > 15) { // must convert String + Object || Object + String
-
- if (leftTypeID == TypeIds.T_JavaLangString) {
- rightTypeID = TypeIds.T_JavaLangObject;
- } else if (rightTypeID == TypeIds.T_JavaLangString) {
- leftTypeID = TypeIds.T_JavaLangObject;
- } else {
-
- this.constant = Constant.NotAConstant;
- scope.problemReporter().invalidOperator(this, leftType, rightType);
- return null;
- }
- }
-
- // the code is an int
- // (cast) left Op (cast) right --> result
- // 0000 0000 0000 0000 0000
- // <<16 <<12 <<8 <<4 <<0
-
- // Don't test for result = 0. If it is zero, some more work is done.
- // On the one hand when it is not zero (correct code) we avoid doing the test
- int operatorSignature = OperatorExpression.OperatorSignatures[operator][(leftTypeID << 4) + rightTypeID];
-
- this.bits |= operatorSignature & 0xF;
- switch (operatorSignature & 0xF) { // record the current ReturnTypeID
- // only switch on possible result type.....
- case T_boolean :
- this.resolvedType = TypeBinding.BOOLEAN;
- break;
- case T_char :
- this.resolvedType = TypeBinding.CHAR;
- break;
- case T_double :
- this.resolvedType = TypeBinding.DOUBLE;
- break;
- case T_float :
- this.resolvedType = TypeBinding.FLOAT;
- break;
- case T_int :
- this.resolvedType = scope.getJavaLangNumber();
- break;
- case T_long :
- this.resolvedType = TypeBinding.LONG;
- break;
- case T_JavaLangString :
- this.resolvedType = scope.getJavaLangString();
- break;
- case T_any:
- this.resolvedType = TypeBinding.UNKNOWN;
- break;
- case T_function:
- this.resolvedType = scope.getJavaLangFunction();
- break;
- case T_JavaLangObject:
- this.resolvedType = scope.getJavaLangObject();
- break;
- default : //error........
- this.constant = Constant.NotAConstant;
- scope.problemReporter().invalidOperator(this, leftType, rightType);
- return null;
- }
-
- // compute the constant when valid
- computeConstant(scope, leftTypeID, rightTypeID);
- return this.resolvedType;
-}
-
-public void traverse(ASTVisitor visitor, BlockScope scope) {
- if (visitor.visit(this, scope)) {
- this.left.traverse(visitor, scope);
- this.right.traverse(visitor, scope);
- }
- visitor.endVisit(this, scope);
-}
-public int getASTType() {
- return IASTNode.BINARY_EXPRESSION;
-
-}
-public IExpression getLeft() {
- return left;
-}
-public IExpression getRight() {
- return right;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Block.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Block.java
deleted file mode 100644
index 29f68b48..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Block.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IBlock;
-import org.eclipse.wst.jsdt.core.ast.IStatement;
-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;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-
-public class Block extends Statement implements IBlock {
-
- public Statement[] statements;
- public int explicitDeclarations;
- // the number of explicit declaration , used to create scope
- public BlockScope scope;
-
- public Block(int explicitDeclarations) {
- this.explicitDeclarations = explicitDeclarations;
- }
-
- public IStatement[] getStatements() {
- return statements;
- }
-
- public FlowInfo analyseCode(
- BlockScope currentScope,
- FlowContext flowContext,
- FlowInfo flowInfo) {
-
- // empty block
- if (statements == null) return flowInfo;
- boolean didAlreadyComplain = false;
- for (int i = 0, max = statements.length; i < max; i++) {
- Statement stat = statements[i];
- if (!stat.complainIfUnreachable(flowInfo, scope, didAlreadyComplain)) {
- flowInfo = stat.analyseCode(scope, flowContext, flowInfo);
- } else {
- didAlreadyComplain = true;
- }
- }
- return flowInfo;
- }
- public boolean isEmptyBlock() {
-
- return statements == null;
- }
-
- public StringBuffer printBody(int indent, StringBuffer output) {
-
- if (this.statements == null) return output;
- for (int i = 0; i < statements.length; i++) {
- statements[i].printStatement(indent + 1, output);
- output.append('\n');
- }
- return output;
- }
-
- public StringBuffer printStatement(int indent, StringBuffer output) {
-
- printIndent(indent, output);
- output.append("{\n"); //$NON-NLS-1$
- printBody(indent, output);
- return printIndent(indent, output).append('}');
- }
-
- public void resolve(BlockScope upperScope) {
-
- if ((this.bits & UndocumentedEmptyBlock) != 0) {
- upperScope.problemReporter().undocumentedEmptyBlock(this.sourceStart, this.sourceEnd);
- }
- if (statements != null) {
- scope =
- (!JavaScriptCore.IS_ECMASCRIPT4 || explicitDeclarations == 0)
- ? upperScope
- : new BlockScope(upperScope, explicitDeclarations);
- for (int i = 0, length = statements.length; i < length; i++) {
- statements[i].resolve(scope);
- }
- }
- }
-
- public void resolveUsing(BlockScope givenScope) {
-
- if ((this.bits & UndocumentedEmptyBlock) != 0) {
- givenScope.problemReporter().undocumentedEmptyBlock(this.sourceStart, this.sourceEnd);
- }
- // this optimized resolve(...) is sent only on none empty blocks
- scope = givenScope;
- if (statements != null) {
- for (int i = 0, length = statements.length; i < length; i++) {
- statements[i].resolve(scope);
- }
- }
- }
-
- public void traverse(
- ASTVisitor visitor,
- BlockScope blockScope) {
-
- BlockScope visitScope=(scope!=null) ? scope:blockScope;
- if (visitor.visit(this, blockScope)) {
- if (statements != null) {
- for (int i = 0, length = statements.length; i < length; i++)
- statements[i].traverse(visitor, visitScope);
- }
- }
- visitor.endVisit(this, blockScope);
- }
- public int getASTType() {
- return IASTNode.BLOCK;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/BranchStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/BranchStatement.java
deleted file mode 100644
index 48279efc..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/BranchStatement.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IBranchStatement;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-
-public abstract class BranchStatement extends Statement implements IBranchStatement {
-
- public char[] label;
- public SubRoutineStatement[] subroutines;
- public int initStateIndex = -1;
-
-/**
- * BranchStatement constructor comment.
- */
-public BranchStatement(char[] label, int sourceStart,int sourceEnd) {
- this.label = label ;
- this.sourceStart = sourceStart;
- this.sourceEnd = sourceEnd;
-}
-
-public void resolve(BlockScope scope) {
- // nothing to do during name resolution
-}
-public int getASTType() {
- return IASTNode.BRANCH_STATEMENT;
-
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/BreakStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/BreakStatement.java
deleted file mode 100644
index d3f462b4..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/BreakStatement.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IBreakStatement;
-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;
-import org.eclipse.wst.jsdt.internal.compiler.flow.InsideSubRoutineFlowContext;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-
-public class BreakStatement extends BranchStatement implements IBreakStatement {
-
-public BreakStatement(char[] label, int sourceStart, int e) {
- super(label, sourceStart, e);
-}
-
-public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {
-
- // here requires to generate a sequence of finally blocks invocations depending corresponding
- // to each of the traversed try statements, so that execution will terminate properly.
-
- // lookup the label, this should answer the returnContext
- FlowContext targetContext = (this.label == null)
- ? flowContext.getTargetContextForDefaultBreak()
- : flowContext.getTargetContextForBreakLabel(this.label);
-
- if (targetContext == null) {
- if (this.label == null) {
- currentScope.problemReporter().invalidBreak(this);
- } else {
- currentScope.problemReporter().undefinedLabel(this);
- }
- return flowInfo; // pretend it did not break since no actual target
- }
-
-// this.initStateIndex =
-// currentScope.methodScope().recordInitializationStates(flowInfo);
-//
- FlowContext traversedContext = flowContext;
- int subCount = 0;
- this.subroutines = new SubRoutineStatement[5];
-
- do {
- SubRoutineStatement sub;
- if ((sub = traversedContext.subroutine()) != null) {
- 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()) {
- break;
- }
- }
- traversedContext.recordReturnFrom(flowInfo.unconditionalInits());
- traversedContext.recordBreakTo(targetContext);
-
- if (traversedContext instanceof InsideSubRoutineFlowContext) {
- ASTNode node = traversedContext.associatedNode;
- if (node instanceof TryStatement) {
- TryStatement tryStatement = (TryStatement) node;
- flowInfo.addInitializationsFrom(tryStatement.subRoutineInits); // collect inits
- }
- } else if (traversedContext == targetContext) {
- // only record break info once accumulated through subroutines, and only against target context
- targetContext.recordBreakFrom(flowInfo);
- break;
- }
- } while ((traversedContext = traversedContext.parent) != null);
-
- // resize subroutines
- if (subCount != this.subroutines.length) {
- System.arraycopy(this.subroutines, 0, (this.subroutines = new SubRoutineStatement[subCount]), 0, subCount);
- }
- return FlowInfo.DEAD_END;
-}
-
-public StringBuffer printStatement(int tab, StringBuffer output) {
- printIndent(tab, output).append("break "); //$NON-NLS-1$
- if (this.label != null) output.append(this.label);
- return output.append(';');
-}
-
-public void traverse(ASTVisitor visitor, BlockScope blockscope) {
- visitor.visit(this, blockscope);
- visitor.endVisit(this, blockscope);
-}
-public int getASTType() {
- return IASTNode.BREAK_STATEMENT;
-
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/CaseStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/CaseStatement.java
deleted file mode 100644
index 973f438d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/CaseStatement.java
+++ /dev/null
@@ -1,117 +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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.ICaseStatement;
-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.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class CaseStatement extends Statement implements ICaseStatement {
-
- public Expression constantExpression;
-
- public CaseStatement(Expression constantExpression, int sourceEnd, int sourceStart) {
- this.constantExpression = constantExpression;
- this.sourceEnd = sourceEnd;
- this.sourceStart = sourceStart;
- }
-
- public FlowInfo analyseCode(
- BlockScope currentScope,
- FlowContext flowContext,
- FlowInfo flowInfo) {
-
- if (constantExpression != null) {
- this.constantExpression.analyseCode(currentScope, flowContext, flowInfo);
- }
- return flowInfo;
- }
-
- public StringBuffer printStatement(int tab, StringBuffer output) {
-
- printIndent(tab, output);
- if (constantExpression == null) {
- output.append("default : "); //$NON-NLS-1$
- } else {
- output.append("case "); //$NON-NLS-1$
- constantExpression.printExpression(0, output).append(" : "); //$NON-NLS-1$
- }
- return output.append(';');
- }
-
-
- /**
- * No-op : should use resolveCase(...) instead.
- */
- public void resolve(BlockScope scope) {
- // no-op : should use resolveCase(...) instead.
- }
-
- /**
- * Returns the constant intValue or ordinal for enum constants. If constant is NotAConstant, then answers Float.MIN_VALUE
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.Statement#resolveCase(org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope, org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding, org.eclipse.wst.jsdt.internal.compiler.ast.SwitchStatement)
- */
- public Constant resolveCase(BlockScope scope, TypeBinding switchExpressionType, SwitchStatement switchStatement) {
- // switchExpressionType maybe null in error case
- scope.enclosingCase = this; // record entering in a switch case block
-
- if (constantExpression == null) {
- // remember the default case into the associated switch statement
- if (switchStatement.defaultCase != null)
- scope.problemReporter().duplicateDefaultCase(this);
-
- // on error the last default will be the selected one ...
- switchStatement.defaultCase = this;
- return Constant.NotAConstant;
- }
- // add into the collection of cases of the associated switch statement
- switchStatement.cases[switchStatement.caseCount++] = this;
-
- TypeBinding caseType = constantExpression.resolveType(scope);
- if (caseType == null || switchExpressionType == null) return Constant.NotAConstant;
- if (constantExpression.isConstantValueOfTypeAssignableToType(caseType, switchExpressionType)
- || caseType.isCompatibleWith(switchExpressionType)) {
-
- return constantExpression.constant;
-
- } else if (scope.isBoxingCompatibleWith(caseType, switchExpressionType)
- || (caseType.isBaseType() // narrowing then boxing ?
- && scope.compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5 // autoboxing
- && !switchExpressionType.isBaseType()
- && constantExpression.isConstantValueOfTypeAssignableToType(caseType, scope.environment().computeBoxingType(switchExpressionType)))) {
- // constantExpression.computeConversion(scope, caseType, switchExpressionType); - do not report boxing/unboxing conversion
- return constantExpression.constant;
- }
- scope.problemReporter().typeMismatchError(caseType, switchExpressionType, constantExpression);
- return Constant.NotAConstant;
- }
-
-
- public void traverse(
- ASTVisitor visitor,
- BlockScope blockScope) {
-
- if (visitor.visit(this, blockScope)) {
- if (constantExpression != null) constantExpression.traverse(visitor, blockScope);
- }
- visitor.endVisit(this, blockScope);
- }
- public int getASTType() {
- return IASTNode.CASE_STATEMENT;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ClassLiteralAccess.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ClassLiteralAccess.java
deleted file mode 100644
index 6d8cb628..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ClassLiteralAccess.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-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;
-import org.eclipse.wst.jsdt.internal.compiler.impl.Constant;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class ClassLiteralAccess extends Expression {
-
- public TypeReference type;
- public TypeBinding targetType;
-
- public ClassLiteralAccess(int sourceEnd, TypeReference type) {
- this.type = type;
- type.bits |= IgnoreRawTypeCheck; // no need to worry about raw type usage
- this.sourceStart = type.sourceStart;
- this.sourceEnd = sourceEnd;
- }
-
- public FlowInfo analyseCode(
- BlockScope currentScope,
- FlowContext flowContext,
- FlowInfo flowInfo) {
-
- return flowInfo;
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output) {
-
- return type.print(0, output).append(".class"); //$NON-NLS-1$
- }
-
- public TypeBinding resolveType(BlockScope scope) {
-
- constant = Constant.NotAConstant;
- if ((targetType = type.resolveType(scope, true /* check bounds*/)) == null)
- return null;
-
- ReferenceBinding classType = scope.getJavaLangClass();
- this.resolvedType = classType;
-
- return this.resolvedType;
- }
-
- public void traverse(
- ASTVisitor visitor,
- BlockScope blockScope) {
-
- if (visitor.visit(this, blockScope)) {
- type.traverse(visitor, blockScope);
- }
- visitor.endVisit(this, blockScope);
- }
- public int getASTType() {
- return IASTNode.CLASS_LITERAL_ACCESS;
-
- }
-}
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
deleted file mode 100644
index 3e4aa63c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Clinit.java
+++ /dev/null
@@ -1,126 +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.compiler.ast;
-
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-import org.eclipse.wst.jsdt.internal.compiler.CompilationResult;
-import org.eclipse.wst.jsdt.internal.compiler.flow.ExceptionHandlingFlowContext;
-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.flow.InitializationFlowContext;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Binding;
-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.MethodScope;
-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.TypeConstants;
-import org.eclipse.wst.jsdt.internal.compiler.parser.Parser;
-import org.eclipse.wst.jsdt.internal.compiler.problem.AbortMethod;
-
-public class Clinit extends AbstractMethodDeclaration {
-
- public Clinit(CompilationResult compilationResult) {
- super(compilationResult);
- modifiers = 0;
- selector = TypeConstants.CLINIT;
- }
-
- public FlowInfo analyseCode(
- Scope classScope,
- FlowContext flowContext,
- FlowInfo flowInfo) {
-
- InitializationFlowContext staticInitializerFlowContext =(InitializationFlowContext)flowContext;
- if (ignoreFurtherInvestigation)
- return flowInfo;
- try {
- ExceptionHandlingFlowContext clinitContext =
- new ExceptionHandlingFlowContext(
- staticInitializerFlowContext.parent,
- this,
- Binding.NO_EXCEPTIONS,
- scope,
- FlowInfo.DEAD_END);
-
- // check for missing returning path
- this.needFreeReturn = (flowInfo.tagBits & FlowInfo.UNREACHABLE) == 0;
-
-
- // check missing blank final field initializations
- flowInfo = flowInfo.mergedWith(staticInitializerFlowContext.initsOnReturn);
-
- // check static initializers thrown exceptions
- staticInitializerFlowContext.checkInitializerExceptions(
- scope,
- clinitContext,
- flowInfo);
- } catch (AbortMethod e) {
- this.ignoreFurtherInvestigation = true;
- }
- return flowInfo;
- }
-
- public boolean isClinit() {
-
- return true;
- }
-
- public boolean isInitializationMethod() {
-
- return true;
- }
-
- public boolean isStatic() {
-
- return true;
- }
-
- public void parseStatements(Parser parser, CompilationUnitDeclaration unit) {
- //the clinit is filled by hand ....
- }
-
- public StringBuffer print(int tab, StringBuffer output) {
-
- printIndent(tab, output).append("<clinit>()"); //$NON-NLS-1$
- printBody(tab + 1, output);
- return output;
- }
-
- public void resolve(ClassScope classScope) {
-
- this.scope = new MethodScope(classScope, classScope.referenceContext, true);
- }
-
- public void traverse(
- ASTVisitor visitor,
- ClassScope classScope) {
-
- visitor.visit(this, classScope);
- visitor.endVisit(this, classScope);
- }
-
- public void setAssertionSupport(FieldBinding assertionSyntheticFieldBinding, boolean needClassLiteralField) {
-
- // 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();
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=22334
- }
- }
- public int getASTType() {
- return IASTNode.CL_INIT;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/CombinedBinaryExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/CombinedBinaryExpression.java
deleted file mode 100644
index 67b5e181..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/CombinedBinaryExpression.java
+++ /dev/null
@@ -1,247 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 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
- * Michael Spector <spektom@gmail.com> Bug 242754
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.ICombinedBinaryExpression;
-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;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeIds;
-
-/**
- * CombinedBinaryExpression is an implementation of BinaryExpression that
- * specifically attempts to mitigate the issues raised by expressions which
- * have a very deep leftmost branch. It does so by maintaining a table of
- * direct references to its subexpressions, and implementing non-recursive
- * variants of the most significant recursive algorithms of its ancestors.
- * The subexpressions table only holds intermediate binary expressions. Its
- * role is to provide the reversed navigation through the left relationship
- * of BinaryExpression to Expression. To cope with potentially very deep
- * left branches, an instance of CombinedBinaryExpression is created once in
- * a while, using variable thresholds held by {@link #arityMax}.
- * As a specific case, the topmost node of all binary expressions that are
- * deeper than one is a CombinedBinaryExpression, but it has no references
- * table.<br>
- * Notes:
- * <ul>
- * <li>CombinedBinaryExpression is not meant to behave in other ways than
- * BinaryExpression in any observable respect;</li>
- * <li>visitors that implement their own traversal upon binary expressions
- * should consider taking advantage of combined binary expressions, or
- * else face a risk of StackOverflowError upon deep instances;</li>
- * <li>callers that need to change the operator should rebuild the expression
- * from scratch, or else amend the references table as needed to cope with
- * the resulting, separated expressions.</li>
- * </ul>
- */
-public class CombinedBinaryExpression extends BinaryExpression implements ICombinedBinaryExpression {
-
- /**
- * The number of consecutive binary expressions of this' left branch that
- * bear the same operator as this.<br>
- * Notes:
- * <ul><li>the presence of a CombinedBinaryExpression instance resets
- * arity, even when its operator is compatible;</li>
- * <li>this property is maintained by the parser.</li>
- * </ul>
- */
- public int arity;
-
- /**
- * The threshold that will trigger the creation of the next full-fledged
- * CombinedBinaryExpression. This field is only maintained for the
- * topmost binary expression (it is 0 otherwise). It enables a variable
- * policy, which scales better with very large expressions.
- */
- public int arityMax;
-
- /**
- * Upper limit for {@link #arityMax}.
- */
- public static final int ARITY_MAX_MAX = 160;
-
- /**
- * Default lower limit for {@link #arityMax}.
- */
- public static final int ARITY_MAX_MIN = 20;
-
- /**
- * Default value for the first term of the series of {@link #arityMax}
- * values. Changing this allows for experimentation. Not meant to be
- * changed during a parse operation.
- */
- public static int defaultArityMaxStartingValue = ARITY_MAX_MIN;
-
- /**
- * A table of references to the binary expressions of this' left branch.
- * Instances of CombinedBinaryExpression are not repeated here. Instead,
- * the left subexpression of referencesTable[0] may be a combined binary
- * expression, if appropriate. Null when this only cares about tracking
- * the expression's arity.
- */
- public BinaryExpression referencesTable[];
-
-/**
- * Make a new CombinedBinaryExpression. If arity is strictly greater than one,
- * a references table is built and initialized with the reverse relationship of
- * the one defined by {@link BinaryExpression#left}. arity and left must be
- * compatible with each other (that is, there must be at least arity - 1
- * consecutive compatible binary expressions into the leftmost branch of left,
- * the topmost of which being left's immediate left expression).
- * @param left the left branch expression
- * @param right the right branch expression
- * @param operator the operator for this binary expression - only PLUS for now
- * @param arity the number of binary expressions of a compatible operator that
- * already exist into the leftmost branch of left (including left); must
- * be strictly greater than 0
- */
-public CombinedBinaryExpression(Expression left, Expression right, int operator,
- int arity) {
- super(left, right, operator);
- this.arity = arity;
- if (arity > 1) {
- this.referencesTable = new BinaryExpression[arity];
- this.referencesTable[arity - 1] = (BinaryExpression) left;
- for (int i = arity - 1; i > 0; i--) {
- this.referencesTable[i - 1] =
- (BinaryExpression) this.referencesTable[i].left;
- }
- } else {
- this.arityMax = defaultArityMaxStartingValue;
- }
-}
-
-public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext,
- FlowInfo flowInfo) {
- // keep implementation in sync with BinaryExpression#analyseCode
- if (this.referencesTable == null) {
- return super.analyseCode(currentScope, flowContext, flowInfo);
- }
- if (this.referencesTable[0] != null && this.referencesTable[0].resolvedType != null) {
- BinaryExpression cursor;
- if ((cursor = this.referencesTable[0]).resolvedType.id !=
- TypeIds.T_JavaLangString) {
- cursor.left.checkNPE(currentScope, flowContext, flowInfo);
- }
- flowInfo = cursor.left.analyseCode(currentScope, flowContext, flowInfo).
- unconditionalInits();
- for (int i = 0, end = this.arity; i < end; i ++) {
- if ((cursor = this.referencesTable[i]).resolvedType.id !=
- TypeIds.T_JavaLangString) {
- cursor.right.checkNPE(currentScope, flowContext, flowInfo);
- }
- flowInfo = cursor.right.
- analyseCode(currentScope, flowContext, flowInfo).
- unconditionalInits();
- }
- }
- if (this.resolvedType.id != TypeIds.T_JavaLangString) {
- this.right.checkNPE(currentScope, flowContext, flowInfo);
- }
- return this.right.analyseCode(currentScope, flowContext, flowInfo).
- unconditionalInits();
-}
-
-public StringBuffer printExpressionNoParenthesis(int indent,
- StringBuffer output) {
- // keep implementation in sync with
- // BinaryExpression#printExpressionNoParenthesis and
- // OperatorExpression#printExpression
- if (this.referencesTable == null) {
- return super.printExpressionNoParenthesis(indent, output);
- }
- String operatorString = operatorToString();
- for (int i = this.arity - 1; i >= 0; i--) {
- output.append('(');
- }
- output = this.referencesTable[0].left.
- printExpression(indent, output);
- for (int i = 0, end = this.arity;
- i < end; i++) {
- output.append(' ').append(operatorString).append(' ');
- output = this.referencesTable[i].right.
- printExpression(0, output);
- output.append(')');
- }
- output.append(' ').append(operatorString).append(' ');
- return this.right.printExpression(0, output);
-}
-
-public TypeBinding resolveType(BlockScope scope) {
- // keep implementation in sync with BinaryExpression#resolveType
- if (this.referencesTable == null) {
- return super.resolveType(scope);
- }
- BinaryExpression cursor = this.referencesTable[0];
- cursor.left.resolveType(scope);
- for (int i = 0, end = this.arity; i < end; i ++) {
- this.referencesTable[i].nonRecursiveResolveTypeUpwards(scope);
- }
- nonRecursiveResolveTypeUpwards(scope);
- return this.resolvedType;
-}
-
-public void traverse(ASTVisitor visitor, BlockScope scope) {
- if (this.referencesTable == null) {
- super.traverse(visitor, scope);
- } else {
- if (visitor.visit(this, scope)) {
- int restart;
- for (restart = this.arity - 1;
- restart >= 0;
- restart--) {
- if (!visitor.visit(
- this.referencesTable[restart], scope)) {
- visitor.endVisit(
- this.referencesTable[restart], scope);
- break;
- }
- }
- restart++;
- // restart now points to the deepest BE for which
- // visit returned true, if any
- if (restart == 0) {
- this.referencesTable[0].left.traverse(visitor, scope);
- }
- for (int i = restart, end = this.arity;
- i < end; i++) {
- this.referencesTable[i].right.traverse(visitor, scope);
- visitor.endVisit(this.referencesTable[i], scope);
- }
- this.right.traverse(visitor, scope);
- }
- visitor.endVisit(this, scope);
- }
-}
-
-/**
- * Change {@link #arityMax} if and as needed. The current policy is to double
- * arityMax each time this method is called, until it reaches
- * {@link #ARITY_MAX_MAX}. Other policies may consider incrementing it less
- * agressively. Call only after an appropriate value has been assigned to
- * {@link #left}.
- */
-// more sophisticate increment policies would leverage the leftmost expression
-// to hold an indication of the number of uses of a given arityMax in a row
-public void tuneArityMax() {
- if (this.arityMax < ARITY_MAX_MAX) {
- this.arityMax *= 2;
- }
-}
-public int getASTType() {
- return IASTNode.COMBINED_BINARY_EXPRESSION;
-
-}
-}
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
deleted file mode 100644
index f3d6f011..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/CompilationUnitDeclaration.java
+++ /dev/null
@@ -1,696 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.ast;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IProgramElement;
-import org.eclipse.wst.jsdt.core.ast.IScriptFileDeclaration;
-import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.infer.IInferenceFile;
-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.CompilationResult;
-import org.eclipse.wst.jsdt.internal.compiler.DelegateASTVisitor;
-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.ReferenceContext;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-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;
-import org.eclipse.wst.jsdt.internal.compiler.problem.AbortCompilationUnit;
-import org.eclipse.wst.jsdt.internal.compiler.problem.AbortMethod;
-import org.eclipse.wst.jsdt.internal.compiler.problem.AbortType;
-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.HashtableOfObject;
-
-public class CompilationUnitDeclaration
- extends ASTNode
- implements ProblemSeverities, ReferenceContext, IScriptFileDeclaration, IInferenceFile {
-
- private static final Comparator STRING_LITERAL_COMPARATOR = new Comparator() {
- public int compare(Object o1, Object o2) {
- StringLiteral literal1 = (StringLiteral) o1;
- StringLiteral literal2 = (StringLiteral) o2;
- return literal1.sourceStart - literal2.sourceStart;
- }
- };
- private static final int STRING_LITERALS_INCREMENT = 10;
-
- public ImportReference currentPackage;
- public ImportReference[] imports;
- public TypeDeclaration[] types;
- public ProgramElement[] statements;
- public int[][] comments;
-
-
- public InferredType [] inferredTypes = new InferredType[10];
- public int numberInferredTypes=0;
- public HashtableOfObject inferredTypesHash=new HashtableOfObject();
- public boolean typesHaveBeenInferred=false;
-
- public boolean ignoreFurtherInvestigation = false; // once pointless to investigate due to errors
- public boolean ignoreMethodBodies = false;
- public CompilationUnitScope scope;
- public ProblemReporter problemReporter;
- public CompilationResult compilationResult;
-
-
- public LocalTypeBinding[] localTypes;
- public int localTypeCount = 0;
-
- public CompilationUnitBinding compilationUnitBinding;
-
-
- public boolean isPropagatingInnerClassEmulation;
-
- public Javadoc javadoc; // 1.5 addition for package-info.js
-
- public NLSTag[] nlsTags;
- private StringLiteral[] stringLiterals;
- private int stringLiteralsPtr;
-
-
-
- public CompilationUnitDeclaration(
- ProblemReporter problemReporter,
- CompilationResult compilationResult,
- int sourceLength) {
-
- this.problemReporter = problemReporter;
- this.compilationResult = compilationResult;
-
- //by definition of a compilation unit....
- sourceStart = 0;
- sourceEnd = sourceLength - 1;
-// System.out.println("create "+hashCode());
- }
-
- /*
- * We cause the compilation task to abort to a given extent.
- */
- public void abort(int abortLevel, CategorizedProblem problem) {
-
- switch (abortLevel) {
- case AbortType :
- throw new AbortType(this.compilationResult, problem);
- case AbortMethod :
- throw new AbortMethod(this.compilationResult, problem);
- default :
- throw new AbortCompilationUnit(this.compilationResult, problem);
- }
- }
-
- /*
- * Dispatch code analysis AND request saturation of inner emulation
- */
- public void analyseCode() {
-
- if (ignoreFurtherInvestigation )
- return;
- try {
- if (types != null) {
- for (int i = 0, count = types.length; i < count; i++) {
- types[i].analyseCode(scope);
- }
- }
-
- this.scope.temporaryAnalysisIndex=0;
- int maxVars=this.scope.localIndex;
- for (Iterator iter = this.scope.externalCompilationUnits.iterator(); iter.hasNext();) {
- CompilationUnitScope externalScope = (CompilationUnitScope) iter.next();
- externalScope.temporaryAnalysisIndex=maxVars;
- maxVars+=externalScope.localIndex;
- }
- FlowInfo flowInfo=FlowInfo.initial(maxVars);
- FlowContext flowContext = new FlowContext(null, this);
-
- if (statements != null) {
- List functions = null;
- for (int i = 0, length = this.statements.length; i < length; i++) {
- // if this is not a function then analyse it
- if(!(this.statements[i] instanceof AbstractMethodDeclaration)) {
- flowInfo=((Statement)statements[i]).analyseCode(scope,flowContext,flowInfo);
- } else {
- // if this is a function then store it until all non functions are finished
- if(functions == null)
- functions = new ArrayList();
- functions.add(statements[i]);
- }
- }
- if(functions != null) {
- for(int f = 0; f < functions.size(); f++) {
- ((Statement)functions.get(f)).analyseCode(this.scope, null, flowInfo.copy());
- }
- }
-
-// for (int i = 0, count = statements.length; i < count; i++) {
-// if (statements[i] instanceof AbstractMethodDeclaration)
-// {
-// ((AbstractMethodDeclaration)statements[i]).analyseCode(this.scope, null, flowInfo.copy());
-// }
-// else
-// flowInfo=((Statement)statements[i]).analyseCode(scope,flowContext,flowInfo);
-// }
- }
- } catch (AbortCompilationUnit e) {
- this.ignoreFurtherInvestigation = true;
- return;
- }
- }
-
- /*
- * When unit result is about to be accepted, removed back pointers
- * to compiler structures.
- */
- public void cleanUp() {
- if (this.compilationUnitBinding!=null)
-
- this.compilationUnitBinding.cleanup();
- if (this.types != null) {
- for (int i = 0, max = this.types.length; i < max; i++) {
- cleanUp(this.types[i]);
- }
- for (int i = 0, max = this.localTypeCount; i < max; i++) {
- LocalTypeBinding localType = localTypes[i];
- // null out the type's scope backpointers
- localType.scope = null; // local members are already in the list
- localType.enclosingCase = null;
- }
- }
-
- for (int i = 0; i < this.numberInferredTypes; i++) {
- SourceTypeBinding binding = this.inferredTypes[i].binding;
- if (binding!=null)
- binding.cleanup();
- }
- compilationResult.recoveryScannerData = null; // recovery is already done
-
-
- }
- private void cleanUp(TypeDeclaration type) {
- if (type.memberTypes != null) {
- for (int i = 0, max = type.memberTypes.length; i < max; i++){
- cleanUp(type.memberTypes[i]);
- }
- }
- if (type.binding != null) {
- // null out the type's scope backpointers
- type.binding.scope = null;
- }
- }
-
- public CompilationResult compilationResult() {
- return this.compilationResult;
- }
-
- /*
- * Finds the matching type amoung this compilation unit types.
- * Returns null if no type with this name is found.
- * The type name is a compound name
- * eg. if we're looking for X.A.B then a type name would be {X, A, B}
- */
- public TypeDeclaration declarationOfType(char[][] typeName) {
-
- for (int i = 0; i < this.types.length; i++) {
- TypeDeclaration typeDecl = this.types[i].declarationOfType(typeName);
- if (typeDecl != null) {
- return typeDecl;
- }
- }
- return null;
- }
-
-
- 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 null;
- }
-
-
- public char[] getFileName() {
-
- return compilationResult.getFileName();
- }
-
- public char[] getMainTypeName() {
-
- if (compilationResult.compilationUnit == null) {
- char[] fileName = compilationResult.getFileName();
-
- int start = CharOperation.lastIndexOf('/', fileName) + 1;
- if (start == 0 || start < CharOperation.lastIndexOf('\\', fileName))
- start = CharOperation.lastIndexOf('\\', fileName) + 1;
-
- int end = CharOperation.lastIndexOf('.', fileName);
- if (end == -1)
- end = fileName.length;
-
- return CharOperation.subarray(fileName, start, end);
- } else {
- return compilationResult.compilationUnit.getMainTypeName();
- }
- }
-
- public boolean isEmpty() {
-
- return (currentPackage == null) && (imports == null) && (types == null) && (statements==null);
- }
-
- public boolean isPackageInfo() {
- return CharOperation.equals(this.getMainTypeName(), TypeConstants.PACKAGE_INFO_NAME);
- }
-
- public boolean hasErrors() {
- return this.ignoreFurtherInvestigation;
- }
-
- public StringBuffer print(int indent, StringBuffer output) {
-
- if (currentPackage != null) {
- printIndent(indent, output).append("package "); //$NON-NLS-1$
- currentPackage.print(0, output, false).append(";\n"); //$NON-NLS-1$
- }
- if (imports != null)
- for (int i = 0; i < imports.length; i++) {
- if (imports[i].isInternal())
- continue;
- printIndent(indent, output).append("import "); //$NON-NLS-1$
- ImportReference currentImport = imports[i];
- currentImport.print(0, output).append(";\n"); //$NON-NLS-1$
- }
-
- if (types != null) {
- for (int i = 0; i < types.length; i++) {
- types[i].print(indent, output).append("\n"); //$NON-NLS-1$
- }
- }
- if (statements != null) {
- for (int i = 0; i < statements.length; i++) {
- statements[i].printStatement(indent, output).append("\n"); //$NON-NLS-1$
- }
- }
- return output;
- }
-
- public void recordStringLiteral(StringLiteral literal) {
- if (this.stringLiterals == null) {
- this.stringLiterals = new StringLiteral[STRING_LITERALS_INCREMENT];
- this.stringLiteralsPtr = 0;
- } else {
- int stackLength = this.stringLiterals.length;
- if (this.stringLiteralsPtr == stackLength) {
- System.arraycopy(
- this.stringLiterals,
- 0,
- this.stringLiterals = new StringLiteral[stackLength + STRING_LITERALS_INCREMENT],
- 0,
- stackLength);
- }
- }
- this.stringLiterals[this.stringLiteralsPtr++] = literal;
- }
-
- /*
- * Keep track of all local types, so as to update their innerclass
- * emulation later on.
- */
- public void record(LocalTypeBinding localType) {
-
- if (this.localTypeCount == 0) {
- this.localTypes = new LocalTypeBinding[5];
- } else if (this.localTypeCount == this.localTypes.length) {
- System.arraycopy(this.localTypes, 0, (this.localTypes = new LocalTypeBinding[this.localTypeCount * 2]), 0, this.localTypeCount);
- }
- this.localTypes[this.localTypeCount++] = localType;
- }
-
- public void resolve() {
- int startingTypeIndex = 0;
- boolean isPackageInfo = false;//isPackageInfo();
- if (this.types != null && isPackageInfo) {
- // resolve synthetic type declaration
- final TypeDeclaration syntheticTypeDeclaration = types[0];
- // set empty javadoc to avoid missing warning (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=95286)
- if (syntheticTypeDeclaration.javadoc == null) {
- syntheticTypeDeclaration.javadoc = new Javadoc(syntheticTypeDeclaration.declarationSourceStart, syntheticTypeDeclaration.declarationSourceStart);
- }
- syntheticTypeDeclaration.resolve(this.scope);
- // resolve annotations if any
-// if (this.currentPackage!= null && this.currentPackage.annotations != null) {
-// resolveAnnotations(syntheticTypeDeclaration.staticInitializerScope, this.currentPackage.annotations, this.scope.getDefaultPackage());
-// }
- // resolve javadoc package if any
- if (this.javadoc != null) {
- this.javadoc.resolve(syntheticTypeDeclaration.staticInitializerScope);
- }
- startingTypeIndex = 1;
- } else {
- // resolve compilation unit javadoc package if any
- if (this.javadoc != null) {
- this.javadoc.resolve(this.scope);
- }
- }
-
- try {
- if (types != null) {
- for (int i = startingTypeIndex, count = types.length; i < count; i++) {
- types[i].resolve(scope);
- }
- }
- if (statements != null) {
- for (int i = 0, count = statements.length; i < count; i++) {
- statements[i].resolve(scope);
- }
- }
- reportNLSProblems();
- } catch (AbortCompilationUnit e) {
- this.ignoreFurtherInvestigation = true;
- return;
- }
- }
-
- public void resolve(int start, int end) {
- try {
- int startingTypeIndex = 0;
- // resolve compilation unit javadoc package if any
- if (this.javadoc != null && this.javadoc.sourceStart<=start && this.javadoc.sourceEnd>= end) {
- this.javadoc.resolve(this.scope);
- }
- if (types != null) {
- for (int i = startingTypeIndex, count = types.length; i < count; i++) {
- TypeDeclaration typeDeclaration = types[i];
- if (typeDeclaration.sourceStart<=start && typeDeclaration.sourceEnd>=end)
- typeDeclaration.resolve(scope);
- }
- }
- if (statements != null) {
- for (int i = 0, count = statements.length; i < count; i++) {
- ProgramElement programElement = statements[i];
- if (programElement.sourceStart<=start && programElement.sourceEnd>=end)
- programElement.resolve(scope);
- }
- }
- reportNLSProblems();
- } catch (AbortCompilationUnit e) {
- this.ignoreFurtherInvestigation = true;
- return;
- }
- }
-
-
- private void reportNLSProblems() {
- if (this.nlsTags != null || this.stringLiterals != null) {
- final int stringLiteralsLength = this.stringLiteralsPtr;
- final int nlsTagsLength = this.nlsTags == null ? 0 : this.nlsTags.length;
- if (stringLiteralsLength == 0) {
- if (nlsTagsLength != 0) {
- for (int i = 0; i < nlsTagsLength; i++) {
- NLSTag tag = this.nlsTags[i];
- if (tag != null) {
- scope.problemReporter().unnecessaryNLSTags(tag.start, tag.end);
- }
- }
- }
- } else if (nlsTagsLength == 0) {
- // resize string literals
- if (this.stringLiterals.length != stringLiteralsLength) {
- System.arraycopy(this.stringLiterals, 0, (stringLiterals = new StringLiteral[stringLiteralsLength]), 0, stringLiteralsLength);
- }
- Arrays.sort(this.stringLiterals, STRING_LITERAL_COMPARATOR);
- for (int i = 0; i < stringLiteralsLength; i++) {
- scope.problemReporter().nonExternalizedStringLiteral(this.stringLiterals[i]);
- }
- } else {
- // need to iterate both arrays to find non matching elements
- if (this.stringLiterals.length != stringLiteralsLength) {
- System.arraycopy(this.stringLiterals, 0, (stringLiterals = new StringLiteral[stringLiteralsLength]), 0, stringLiteralsLength);
- }
- Arrays.sort(this.stringLiterals, STRING_LITERAL_COMPARATOR);
- int indexInLine = 1;
- int lastLineNumber = -1;
- StringLiteral literal = null;
- int index = 0;
- int i = 0;
- stringLiteralsLoop: for (; i < stringLiteralsLength; i++) {
- literal = this.stringLiterals[i];
- final int literalLineNumber = literal.lineNumber;
- if (lastLineNumber != literalLineNumber) {
- indexInLine = 1;
- lastLineNumber = literalLineNumber;
- } else {
- indexInLine++;
- }
- if (index < nlsTagsLength) {
- nlsTagsLoop: for (; index < nlsTagsLength; index++) {
- NLSTag tag = this.nlsTags[index];
- if (tag == null) continue nlsTagsLoop;
- int tagLineNumber = tag.lineNumber;
- if (literalLineNumber < tagLineNumber) {
- scope.problemReporter().nonExternalizedStringLiteral(literal);
- continue stringLiteralsLoop;
- } else if (literalLineNumber == tagLineNumber) {
- if (tag.index == indexInLine) {
- this.nlsTags[index] = null;
- index++;
- continue stringLiteralsLoop;
- } else {
- nlsTagsLoop2: for (int index2 = index + 1; index2 < nlsTagsLength; index2++) {
- NLSTag tag2 = this.nlsTags[index2];
- if (tag2 == null) continue nlsTagsLoop2;
- int tagLineNumber2 = tag2.lineNumber;
- if (literalLineNumber == tagLineNumber2) {
- if (tag2.index == indexInLine) {
- this.nlsTags[index2] = null;
- continue stringLiteralsLoop;
- } else {
- continue nlsTagsLoop2;
- }
- } else {
- scope.problemReporter().nonExternalizedStringLiteral(literal);
- continue stringLiteralsLoop;
- }
- }
- scope.problemReporter().nonExternalizedStringLiteral(literal);
- continue stringLiteralsLoop;
- }
- } else {
- scope.problemReporter().unnecessaryNLSTags(tag.start, tag.end);
- continue nlsTagsLoop;
- }
- }
- }
- // all nls tags have been processed, so remaining string literals are not externalized
- break stringLiteralsLoop;
- }
- for (; i < stringLiteralsLength; i++) {
- scope.problemReporter().nonExternalizedStringLiteral(this.stringLiterals[i]);
- }
- if (index < nlsTagsLength) {
- for (; index < nlsTagsLength; index++) {
- NLSTag tag = this.nlsTags[index];
- if (tag != null) {
- scope.problemReporter().unnecessaryNLSTags(tag.start, tag.end);
- }
- }
- }
- }
- }
- }
-
- public void tagAsHavingErrors() {
- ignoreFurtherInvestigation = true;
- }
-
-
- public void traverse(org.eclipse.wst.jsdt.core.ast.ASTVisitor visitor)
- {
- this.traverse(new DelegateASTVisitor(visitor), null,false);
- }
-
- public void traverse(
- ASTVisitor visitor,
- CompilationUnitScope unitScope) {
- traverse(visitor, scope,false);
- }
-
- public void traverse(
- ASTVisitor visitor,
- CompilationUnitScope unitScope, boolean ignoreErrors) {
-
- if (ignoreFurtherInvestigation && !ignoreErrors)
- 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++) {
- statements[i].traverse(visitor, this.scope);
- }
- }
- traverseInferredTypes(visitor,unitScope);
- }
- visitor.endVisit(this, this.scope);
- } catch (AbortCompilationUnit e) {
- // ignore
- }
- }
-
- public void traverseInferredTypes(ASTVisitor visitor,BlockScope unitScope) {
- boolean continueVisiting=true;
- for (int i=0;i<this.numberInferredTypes;i++) {
- InferredType inferredType = this.inferredTypes[i];
- continueVisiting=visitor.visit(inferredType, scope);
- for (int attributeInx=0; attributeInx<inferredType.numberAttributes; attributeInx++) {
- visitor.visit(inferredType.attributes[attributeInx], scope);
- }
- if (inferredType.methods!=null)
- for (Iterator iterator = inferredType.methods.iterator(); continueVisiting && iterator
- .hasNext();) {
- InferredMethod inferredMethod = (InferredMethod) iterator.next();
- visitor.visit(inferredMethod, scope);
- }
- visitor.endVisit(inferredType, scope);
- }
- }
-
- public InferredType findInferredType(char [] name)
- {
- return (InferredType)inferredTypesHash.get(name);
-// for (int i=0;i<this.numberInferredTypes;i++) {
-// InferredType inferredType = this.inferredTypes[i];
-// if (CharOperation.equals(name,inferredType.getName()))
-// return inferredType;
-// }
-// return null;
- }
-
-
-
- public void printInferredTypes(StringBuffer sb)
- {
- for (int i=0;i<this.numberInferredTypes;i++) {
- InferredType inferredType = this.inferredTypes[i];
- if (inferredType.isDefinition)
- {
- inferredType.print(0,sb);
- sb.append("\n"); //$NON-NLS-1$
- }
- }
-
- }
- public int getASTType() {
- return IASTNode.SCRIPT_FILE_DECLARATION;
-
- }
-
- public IProgramElement[] getStatements() {
- return this.statements;
- }
-
- public String getInferenceID() {
- if (this.compilationResult.compilationUnit!=null)
- return this.compilationResult.compilationUnit.getInferenceID();
- return null;
- }
-
- public void addImport(char [] importName, int startPosition, int endPosition, int nameStartPosition)
- {
- ImportReference importReference=new ImportReference(importName, startPosition, endPosition, nameStartPosition);
- if (imports==null)
- {
- imports=new ImportReference[]{importReference};
- }
- else
- {
- ImportReference[] newImports=new ImportReference[imports.length+1];
- System.arraycopy(this.imports, 0, newImports, 0, this.imports.length);
- newImports[this.imports.length]=importReference;
- this.imports=newImports;
- }
- }
-
- public InferredType addType(char[] className, boolean isDefinition, String providerId) {
- InferredType type = findInferredType(className);
-
- if (type==null && className.length > 0)
- {
- if (numberInferredTypes == inferredTypes.length)
- {
- System.arraycopy(
- inferredTypes,
- 0,
- (inferredTypes = new InferredType[numberInferredTypes * 2]),
- 0,
- numberInferredTypes );
- }
-
- type=inferredTypes[numberInferredTypes ++] = new InferredType(className);
- type.inferenceProviderID = providerId;
- if (className.length > 2 && className[className.length - 2] == '[' && className[className.length - 1] == ']') {
- type.isArray = true;
- }
-
- inferredTypesHash.put(className,type);
- }
- if (isDefinition && type != null)
- type.isDefinition=isDefinition;
- return type;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/CompoundAssignment.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/CompoundAssignment.java
deleted file mode 100644
index fc9711e6..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/CompoundAssignment.java
+++ /dev/null
@@ -1,180 +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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.ICompoundAssignment;
-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.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.LookupEnvironment;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class CompoundAssignment extends Assignment implements OperatorIds, ICompoundAssignment {
- public int operator;
- public int preAssignImplicitConversion;
-
- // var op exp is equivalent to var = (varType) var op exp
- // assignmentImplicitConversion stores the cast needed for the assignment
-
- public CompoundAssignment(Expression lhs, Expression expression,int operator, int sourceEnd) {
- //lhs is always a reference by construction ,
- //but is build as an expression ==> the checkcast cannot fail
-
- super(lhs, expression, sourceEnd);
- lhs.bits &= ~IsStrictlyAssigned; // tag lhs as NON assigned - it is also a read access
- lhs.bits |= IsCompoundAssigned; // tag lhs as assigned by compound
- this.operator = operator ;
- }
-
-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.
- if (this.resolvedType.id != T_JavaLangString) {
- lhs.checkNPE(currentScope, flowContext, flowInfo);
- }
- return ((Reference) lhs).analyseAssignment(currentScope, flowContext, flowInfo, this, true).unconditionalInits();
-}
-
- public int nullStatus(FlowInfo flowInfo) {
- return FlowInfo.NON_NULL;
- // we may have complained on checkNPE, but we avoid duplicate error
-}
-
- public String operatorToString() {
- switch (operator) {
- case PLUS :
- return "+="; //$NON-NLS-1$
- case MINUS :
- return "-="; //$NON-NLS-1$
- case MULTIPLY :
- return "*="; //$NON-NLS-1$
- case DIVIDE :
- return "/="; //$NON-NLS-1$
- case AND :
- return "&="; //$NON-NLS-1$
- case OR :
- return "|="; //$NON-NLS-1$
- case XOR :
- return "^="; //$NON-NLS-1$
- case REMAINDER :
- return "%="; //$NON-NLS-1$
- case LEFT_SHIFT :
- return "<<="; //$NON-NLS-1$
- case RIGHT_SHIFT :
- return ">>="; //$NON-NLS-1$
- case UNSIGNED_RIGHT_SHIFT :
- return ">>>="; //$NON-NLS-1$
- }
- return "unknown operator"; //$NON-NLS-1$
- }
-
- public StringBuffer printExpressionNoParenthesis(int indent, StringBuffer output) {
-
- lhs.printExpression(indent, output).append(' ').append(operatorToString()).append(' ');
- return expression.printExpression(0, output) ;
- }
-
- public TypeBinding resolveType(BlockScope scope) {
- constant = Constant.NotAConstant;
- if (!(this.lhs instanceof Reference) || this.lhs.isThis()) {
- scope.problemReporter().expressionShouldBeAVariable(this.lhs);
- return null;
- }
- TypeBinding originalLhsType = lhs.resolveType(scope);
- TypeBinding originalExpressionType = expression.resolveType(scope);
- this.resolvedType=TypeBinding.ANY;
- if (originalLhsType == null || originalExpressionType == null)
- {
- return null;
- }
-
- // autoboxing support
- LookupEnvironment env = scope.environment();
- TypeBinding lhsType = originalLhsType, expressionType = originalExpressionType;
- boolean use15specifics = scope.compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5;
- boolean unboxedLhs = false;
- if (use15specifics) {
- if (!lhsType.isBaseType() && expressionType.id != T_JavaLangString && expressionType.id != T_null) {
- TypeBinding unboxedType = env.computeBoxingType(lhsType);
- if (unboxedType != lhsType) {
- lhsType = unboxedType;
- unboxedLhs = true;
- }
- }
- if (!expressionType.isBaseType() && lhsType.id != T_JavaLangString && lhsType.id != T_null) {
- expressionType = env.computeBoxingType(expressionType);
- }
- }
-
- if (restrainUsageToNumericTypes() && !lhsType.isNumericType() && !lhsType.isAnyType()) {
- scope.problemReporter().operatorOnlyValidOnNumericType(this, lhsType, expressionType);
- return null;
- }
- int lhsID = lhsType.id;
- int expressionID = expressionType.id;
- if (lhsID > 15 || expressionID > 15) {
- if (lhsID != T_JavaLangString) { // String += Thread is valid whereas Thread += String is not
- scope.problemReporter().invalidOperator(this, lhsType, expressionType);
- return null;
- }
- expressionID = T_JavaLangObject; // use the Object has tag table
- }
-
- // the code is an int
- // (cast) left Op (cast) rigth --> result
- // 0000 0000 0000 0000 0000
- // <<16 <<12 <<8 <<4 <<0
-
- // the conversion is stored INTO the reference (info needed for the code gen)
- int result = OperatorExpression.OperatorSignatures[operator][ (lhsID << 4) + expressionID];
- if (result == T_undefined) {
- scope.problemReporter().invalidOperator(this, lhsType, expressionType);
- return null;
- }
-// if (operator == PLUS){
-// if(lhsID == T_JavaLangObject) {
-// // <Object> += <String> is illegal (39248)
-// scope.problemReporter().invalidOperator(this, lhsType, expressionType);
-// return null;
-// } else {
-// // <int | boolean> += <String> is illegal
-// if ((lhsType.isNumericType() || lhsID == T_boolean) && !expressionType.isNumericType()){
-// scope.problemReporter().invalidOperator(this, lhsType, expressionType);
-// return null;
-// }
-// }
-// }
- this.preAssignImplicitConversion = (unboxedLhs ? BOXING : 0) | (lhsID << 4) | (result & 0x0000F);
- return this.resolvedType = originalLhsType;
- }
-
- public boolean restrainUsageToNumericTypes(){
- return false ;
- }
-
- public void traverse(ASTVisitor visitor, BlockScope scope) {
- if (visitor.visit(this, scope)) {
- lhs.traverse(visitor, scope);
- expression.traverse(visitor, scope);
- }
- visitor.endVisit(this, scope);
- }
- public int getASTType() {
- return IASTNode.COMPOUND_ASSIGNMENT;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ConditionalExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ConditionalExpression.java
deleted file mode 100644
index 3ef9b68a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ConditionalExpression.java
+++ /dev/null
@@ -1,303 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IConditionalExpression;
-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;
-import org.eclipse.wst.jsdt.internal.compiler.flow.UnconditionalFlowInfo;
-import org.eclipse.wst.jsdt.internal.compiler.impl.Constant;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BaseTypeBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class ConditionalExpression extends OperatorExpression implements IConditionalExpression {
-
- public Expression condition, valueIfTrue, valueIfFalse;
- public Constant optimizedBooleanConstant;
- public Constant optimizedIfTrueConstant;
- public Constant optimizedIfFalseConstant;
-
- // for local variables table attributes
- int trueInitStateIndex = -1;
- int falseInitStateIndex = -1;
- int mergedInitStateIndex = -1;
-
- public ConditionalExpression(
- Expression condition,
- Expression valueIfTrue,
- Expression valueIfFalse) {
- this.condition = condition;
- this.valueIfTrue = valueIfTrue;
- this.valueIfFalse = valueIfFalse;
- sourceStart = condition.sourceStart;
- sourceEnd = valueIfFalse.sourceEnd;
- }
-
-public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext,
- FlowInfo flowInfo) {
- Constant cst = this.condition.optimizedBooleanConstant();
- boolean isConditionOptimizedTrue = cst != Constant.NotAConstant && cst.booleanValue() == true;
- boolean isConditionOptimizedFalse = cst != Constant.NotAConstant && cst.booleanValue() == false;
-
- int mode = flowInfo.reachMode();
- flowInfo = condition.analyseCode(currentScope, flowContext, flowInfo, cst == Constant.NotAConstant);
-
- // process the if-true part
- FlowInfo trueFlowInfo = flowInfo.initsWhenTrue().copy();
- if (isConditionOptimizedFalse) {
- trueFlowInfo.setReachMode(FlowInfo.UNREACHABLE);
- }
-// trueInitStateIndex = currentScope.methodScope().recordInitializationStates(trueFlowInfo);
- trueFlowInfo = valueIfTrue.analyseCode(currentScope, flowContext, trueFlowInfo);
-
- // process the if-false part
- FlowInfo falseFlowInfo = flowInfo.initsWhenFalse().copy();
- if (isConditionOptimizedTrue) {
- falseFlowInfo.setReachMode(FlowInfo.UNREACHABLE);
- }
-// falseInitStateIndex = currentScope.methodScope().recordInitializationStates(falseFlowInfo);
- falseFlowInfo = valueIfFalse.analyseCode(currentScope, flowContext, falseFlowInfo);
-
- // merge if-true & if-false initializations
- FlowInfo mergedInfo;
- if (isConditionOptimizedTrue){
- mergedInfo = trueFlowInfo.addPotentialInitializationsFrom(falseFlowInfo);
- } else if (isConditionOptimizedFalse) {
- mergedInfo = falseFlowInfo.addPotentialInitializationsFrom(trueFlowInfo);
- } else {
- // if ((t && (v = t)) ? t : t && (v = f)) r = v; -- ok
- cst = this.optimizedIfTrueConstant;
- boolean isValueIfTrueOptimizedTrue = cst != null && cst != Constant.NotAConstant && cst.booleanValue() == true;
- boolean isValueIfTrueOptimizedFalse = cst != null && cst != Constant.NotAConstant && cst.booleanValue() == false;
-
- cst = this.optimizedIfFalseConstant;
- boolean isValueIfFalseOptimizedTrue = cst != null && cst != Constant.NotAConstant && cst.booleanValue() == true;
- boolean isValueIfFalseOptimizedFalse = cst != null && cst != Constant.NotAConstant && cst.booleanValue() == false;
-
- UnconditionalFlowInfo trueInfoWhenTrue = trueFlowInfo.initsWhenTrue().unconditionalCopy();
- UnconditionalFlowInfo falseInfoWhenTrue = falseFlowInfo.initsWhenTrue().unconditionalCopy();
- UnconditionalFlowInfo trueInfoWhenFalse = trueFlowInfo.initsWhenFalse().unconditionalInits();
- UnconditionalFlowInfo falseInfoWhenFalse = falseFlowInfo.initsWhenFalse().unconditionalInits();
- if (isValueIfTrueOptimizedFalse) trueInfoWhenTrue.setReachMode(FlowInfo.UNREACHABLE);
- if (isValueIfFalseOptimizedFalse) falseInfoWhenTrue.setReachMode(FlowInfo.UNREACHABLE);
- if (isValueIfTrueOptimizedTrue) trueInfoWhenFalse.setReachMode(FlowInfo.UNREACHABLE);
- if (isValueIfFalseOptimizedTrue) falseInfoWhenFalse.setReachMode(FlowInfo.UNREACHABLE);
-
- mergedInfo =
- FlowInfo.conditional(
- trueInfoWhenTrue.mergedWith(falseInfoWhenTrue),
- trueInfoWhenFalse.mergedWith(falseInfoWhenFalse));
- }
-// mergedInitStateIndex =
-// currentScope.methodScope().recordInitializationStates(mergedInfo);
- mergedInfo.setReachMode(mode);
- return mergedInfo;
- }
-
- public int nullStatus(FlowInfo flowInfo) {
- Constant cst = this.condition.optimizedBooleanConstant();
- if (cst != Constant.NotAConstant) {
- if (cst.booleanValue()) {
- return valueIfTrue.nullStatus(flowInfo);
- }
- return valueIfFalse.nullStatus(flowInfo);
- }
- int ifTrueNullStatus = valueIfTrue.nullStatus(flowInfo),
- ifFalseNullStatus = valueIfFalse.nullStatus(flowInfo);
- if (ifTrueNullStatus == ifFalseNullStatus) {
- return ifTrueNullStatus;
- }
- return FlowInfo.UNKNOWN;
- // cannot decide which branch to take, and they disagree
-}
-
- public Constant optimizedBooleanConstant() {
-
- return this.optimizedBooleanConstant == null ? this.constant : this.optimizedBooleanConstant;
- }
-
- public StringBuffer printExpressionNoParenthesis(int indent, StringBuffer output) {
-
- condition.printExpression(indent, output).append(" ? "); //$NON-NLS-1$
- valueIfTrue.printExpression(0, output).append(" : "); //$NON-NLS-1$
- return valueIfFalse.printExpression(0, output);
- }
-
- public TypeBinding resolveType(BlockScope scope) {
- // JLS3 15.25
- constant = Constant.NotAConstant;
-// LookupEnvironment env = scope.environment();
-// boolean use15specifics = scope.compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5;
- TypeBinding conditionType = condition.resolveTypeExpecting(scope, TypeBinding.BOOLEAN);
-
- TypeBinding originalValueIfTrueType = valueIfTrue.resolveType(scope);
- TypeBinding originalValueIfFalseType = valueIfFalse.resolveType(scope);
-
- if (conditionType == null || originalValueIfTrueType == null || originalValueIfFalseType == null)
- return null;
-
- TypeBinding valueIfTrueType = originalValueIfTrueType;
- TypeBinding valueIfFalseType = originalValueIfFalseType;
-// if (use15specifics && valueIfTrueType != valueIfFalseType) {
-// if (valueIfTrueType.isBaseType()) {
-// if (valueIfFalseType.isBaseType()) {
-// // bool ? baseType : baseType
-// if (valueIfTrueType == TypeBinding.NULL) { // bool ? null : 12 --> Integer
-// valueIfFalseType = env.computeBoxingType(valueIfFalseType); // boxing
-// } else if (valueIfFalseType == TypeBinding.NULL) { // bool ? 12 : null --> Integer
-// valueIfTrueType = env.computeBoxingType(valueIfTrueType); // boxing
-// }
-// } else {
-// // bool ? baseType : nonBaseType
-// TypeBinding unboxedIfFalseType = valueIfFalseType.isBaseType() ? valueIfFalseType : env.computeBoxingType(valueIfFalseType);
-// if (valueIfTrueType.isNumericType() && unboxedIfFalseType.isNumericType()) {
-// valueIfFalseType = unboxedIfFalseType; // unboxing
-// } else if (valueIfTrueType != TypeBinding.NULL) { // bool ? 12 : new Integer(12) --> int
-// valueIfFalseType = env.computeBoxingType(valueIfFalseType); // unboxing
-// }
-// }
-// } else if (valueIfFalseType.isBaseType()) {
-// // bool ? nonBaseType : baseType
-// TypeBinding unboxedIfTrueType = valueIfTrueType.isBaseType() ? valueIfTrueType : env.computeBoxingType(valueIfTrueType);
-// if (unboxedIfTrueType.isNumericType() && valueIfFalseType.isNumericType()) {
-// valueIfTrueType = unboxedIfTrueType; // unboxing
-// } else if (valueIfFalseType != TypeBinding.NULL) { // bool ? new Integer(12) : 12 --> int
-// valueIfTrueType = env.computeBoxingType(valueIfTrueType); // unboxing
-// }
-// } else {
-// // bool ? nonBaseType : nonBaseType
-// TypeBinding unboxedIfTrueType = env.computeBoxingType(valueIfTrueType);
-// TypeBinding unboxedIfFalseType = env.computeBoxingType(valueIfFalseType);
-// if (unboxedIfTrueType.isNumericType() && unboxedIfFalseType.isNumericType()) {
-// valueIfTrueType = unboxedIfTrueType;
-// valueIfFalseType = unboxedIfFalseType;
-// }
-// }
-// }
- // Propagate the constant value from the valueIfTrue and valueIFFalse expression if it is possible
- Constant condConstant, trueConstant, falseConstant;
- if ((condConstant = condition.constant) != Constant.NotAConstant
- && (trueConstant = valueIfTrue.constant) != Constant.NotAConstant
- && (falseConstant = valueIfFalse.constant) != Constant.NotAConstant) {
- // all terms are constant expression so we can propagate the constant
- // from valueIFTrue or valueIfFalse to the receiver constant
- constant = condConstant.booleanValue() ? trueConstant : falseConstant;
- }
- if (valueIfTrueType == valueIfFalseType) { // harmed the implicit conversion
- if (valueIfTrueType == TypeBinding.BOOLEAN) {
- this.optimizedIfTrueConstant = valueIfTrue.optimizedBooleanConstant();
- this.optimizedIfFalseConstant = valueIfFalse.optimizedBooleanConstant();
- if (this.optimizedIfTrueConstant != Constant.NotAConstant
- && this.optimizedIfFalseConstant != Constant.NotAConstant
- && this.optimizedIfTrueConstant.booleanValue() == this.optimizedIfFalseConstant.booleanValue()) {
- // a ? true : true / a ? false : false
- this.optimizedBooleanConstant = optimizedIfTrueConstant;
- } else if ((condConstant = condition.optimizedBooleanConstant()) != Constant.NotAConstant) { // Propagate the optimized boolean constant if possible
- this.optimizedBooleanConstant = condConstant.booleanValue()
- ? this.optimizedIfTrueConstant
- : this.optimizedIfFalseConstant;
- }
- }
- return this.resolvedType = valueIfTrueType;
- }
- // Determine the return type depending on argument types
- // Numeric types
- if (valueIfTrueType.isNumericType() && valueIfFalseType.isNumericType()) {
- // <Byte|Short|Char> x constant(Int) ---> <Byte|Short|Char> and reciprocally
- if ((valueIfTrueType == TypeBinding.SHORT || valueIfTrueType == TypeBinding.CHAR)
- && (valueIfFalseType == TypeBinding.INT
- && valueIfFalse.isConstantValueOfTypeAssignableToType(valueIfFalseType, valueIfTrueType))) {
- return this.resolvedType = valueIfTrueType;
- }
- if ((valueIfFalseType == TypeBinding.SHORT
- || valueIfFalseType == TypeBinding.CHAR)
- && (valueIfTrueType == TypeBinding.INT
- && valueIfTrue.isConstantValueOfTypeAssignableToType(valueIfTrueType, valueIfFalseType))) {
- return this.resolvedType = valueIfFalseType;
- }
- // Manual binary numeric promotion
- // int
- if (BaseTypeBinding.isNarrowing(valueIfTrueType.id, T_int)
- && BaseTypeBinding.isNarrowing(valueIfFalseType.id, T_int)) {
- return this.resolvedType = TypeBinding.INT;
- }
- // long
- if (BaseTypeBinding.isNarrowing(valueIfTrueType.id, T_long)
- && BaseTypeBinding.isNarrowing(valueIfFalseType.id, T_long)) {
- return this.resolvedType = TypeBinding.LONG;
- }
- // float
- if (BaseTypeBinding.isNarrowing(valueIfTrueType.id, T_float)
- && BaseTypeBinding.isNarrowing(valueIfFalseType.id, T_float)) {
- return this.resolvedType = TypeBinding.FLOAT;
- }
- // double
- return this.resolvedType = TypeBinding.DOUBLE;
- }
- // Type references (null null is already tested)
-// if (valueIfTrueType.isBaseType() && valueIfTrueType != TypeBinding.NULL) {
-// if (use15specifics) {
-// valueIfTrueType = env.computeBoxingType(valueIfTrueType);
-// } else {
-// scope.problemReporter().conditionalArgumentsIncompatibleTypes(this, valueIfTrueType, valueIfFalseType);
-// return null;
-// }
-// }
-// if (valueIfFalseType.isBaseType() && valueIfFalseType != TypeBinding.NULL) {
-// if (use15specifics) {
-// valueIfFalseType = env.computeBoxingType(valueIfFalseType);
-// } else {
-// scope.problemReporter().conditionalArgumentsIncompatibleTypes(this, valueIfTrueType, valueIfFalseType);
-// return null;
-// }
-// }
-// if (use15specifics) {
-// // >= 1.5 : LUB(operand types) must exist
-// TypeBinding commonType = null;
-// if (valueIfTrueType == TypeBinding.NULL) {
-// commonType = valueIfFalseType;
-// } else if (valueIfFalseType == TypeBinding.NULL) {
-// commonType = valueIfTrueType;
-// } else {
-// commonType = scope.lowerUpperBound(new TypeBinding[] { valueIfTrueType, valueIfFalseType });
-// }
-// if (commonType != null) {
-// valueIfTrue.computeConversion(scope, commonType, originalValueIfTrueType);
-// valueIfFalse.computeConversion(scope, commonType, originalValueIfFalseType);
-// return this.resolvedType = commonType.capture(scope, this.sourceEnd);
-// }
-// } else {
- // < 1.5 : one operand must be convertible to the other
- if (valueIfFalseType.isCompatibleWith(valueIfTrueType)) {
- return this.resolvedType = (valueIfTrueType != TypeBinding.NULL)? valueIfTrueType : valueIfFalseType;
- } else if (valueIfTrueType.isCompatibleWith(valueIfFalseType)) {
- return this.resolvedType = (valueIfFalseType != TypeBinding.NULL)? valueIfFalseType : valueIfTrueType;
- }
-// }
- return null;
- }
-
- public void traverse(ASTVisitor visitor, BlockScope scope) {
- if (visitor.visit(this, scope)) {
- condition.traverse(visitor, scope);
- valueIfTrue.traverse(visitor, scope);
- valueIfFalse.traverse(visitor, scope);
- }
- visitor.endVisit(this, scope);
- }
- public int getASTType() {
- return IASTNode.CONDITIONAL_EXPRESSION;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ConstructorDeclaration.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ConstructorDeclaration.java
deleted file mode 100644
index 3674163e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ConstructorDeclaration.java
+++ /dev/null
@@ -1,282 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import java.util.ArrayList;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IConstructorDeclaration;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-import org.eclipse.wst.jsdt.internal.compiler.CompilationResult;
-import org.eclipse.wst.jsdt.internal.compiler.flow.ExceptionHandlingFlowContext;
-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.flow.InitializationFlowContext;
-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.MethodBinding;
-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.TypeIds;
-import org.eclipse.wst.jsdt.internal.compiler.parser.Parser;
-import org.eclipse.wst.jsdt.internal.compiler.problem.AbortMethod;
-
-public class ConstructorDeclaration extends AbstractMethodDeclaration implements IConstructorDeclaration {
-
- public ExplicitConstructorCall constructorCall;
-
- public boolean isDefaultConstructor = false;
-
-public ConstructorDeclaration(CompilationResult compilationResult){
- super(compilationResult);
-}
-
-public FlowInfo analyseCode(Scope classScope, FlowContext initializationContext, FlowInfo flowInfo) {
- analyseCode((ClassScope)classScope, (InitializationFlowContext)initializationContext, flowInfo, FlowInfo.REACHABLE);
- return flowInfo;
-}
-/**
- * The flowInfo corresponds to non-static field initialization infos. It may be unreachable (155423), but still the explicit constructor call must be
- * analysed as reachable, since it will be generated in the end.
- */
-public void analyseCode(ClassScope classScope, InitializationFlowContext initializerFlowContext, FlowInfo flowInfo, int initialReachMode) {
- if (this.ignoreFurtherInvestigation)
- return;
-
- int nonStaticFieldInfoReachMode = flowInfo.reachMode();
- flowInfo.setReachMode(initialReachMode);
-
- checkUnused: {
- MethodBinding constructorBinding;
- if ((constructorBinding = this.binding) == null) break checkUnused;
- if (this.isDefaultConstructor) break checkUnused;
- if (constructorBinding.isUsed()) break checkUnused;
- if (constructorBinding.isPrivate()) {
- if ((this.binding.declaringClass.tagBits & TagBits.HasNonPrivateConstructor) == 0)
- break checkUnused; // tolerate as known pattern to block instantiation
- } else if ((this.binding.declaringClass.tagBits & (TagBits.IsAnonymousType|TagBits.IsLocalType)) != TagBits.IsLocalType) {
- break checkUnused;
- }
- }
-
- try {
- ExceptionHandlingFlowContext constructorContext =
- new ExceptionHandlingFlowContext(
- initializerFlowContext.parent,
- this,
- null,
- this.scope,
- FlowInfo.DEAD_END);
- initializerFlowContext.checkInitializerExceptions(
- this.scope,
- constructorContext,
- flowInfo);
-
- // anonymous constructor can gain extra thrown exceptions from unhandled ones
- if (this.binding.declaringClass.isAnonymousType()) {
- ArrayList computedExceptions = constructorContext.extendedExceptions;
- if (computedExceptions != null){
- int size;
- if ((size = computedExceptions.size()) > 0){
- ReferenceBinding[] actuallyThrownExceptions;
- computedExceptions.toArray(actuallyThrownExceptions = new ReferenceBinding[size]);
- }
- }
- }
-
- // tag parameters as being set
- if (this.arguments != null) {
- for (int i = 0, count = this.arguments.length; i < count; i++) {
- flowInfo.markAsDefinitelyAssigned(this.arguments[i].binding);
- }
- }
-
- // propagate to constructor call
- if (this.constructorCall != null) {
- // if calling 'this(...)', then flag all non-static fields as definitely
- // set since they are supposed to be set inside other local constructor
- if (this.constructorCall.accessMode == ExplicitConstructorCall.This) {
- FieldBinding[] fields = this.binding.declaringClass.fields();
- for (int i = 0, count = fields.length; i < count; i++) {
- FieldBinding field;
- if (!(field = fields[i]).isStatic()) {
- flowInfo.markAsDefinitelyAssigned(field);
- }
- }
- }
- flowInfo = this.constructorCall.analyseCode(this.scope, constructorContext, flowInfo);
- }
-
- // reuse the reachMode from non static field info
- flowInfo.setReachMode(nonStaticFieldInfoReachMode);
-
- // propagate to statements
- if (this.statements != null) {
- boolean didAlreadyComplain = false;
- for (int i = 0, count = this.statements.length; i < count; i++) {
- Statement stat = this.statements[i];
- if (!stat.complainIfUnreachable(flowInfo, this.scope, didAlreadyComplain)) {
- flowInfo = stat.analyseCode(this.scope, constructorContext, flowInfo);
- } else {
- didAlreadyComplain = true;
- }
- }
- }
- // check for missing returning path
- this.needFreeReturn = (flowInfo.tagBits & FlowInfo.UNREACHABLE) == 0;
-
- // reuse the initial reach mode for diagnosing missing blank finals
- flowInfo.setReachMode(initialReachMode);
-
- // check missing blank final field initializations
- if ((this.constructorCall != null)
- && (this.constructorCall.accessMode != ExplicitConstructorCall.This)) {
- flowInfo = flowInfo.mergedWith(constructorContext.initsOnReturn);
- }
- // check unreachable catch blocks
- constructorContext.complainIfUnusedExceptionHandlers(this);
- } catch (AbortMethod e) {
- this.ignoreFurtherInvestigation = true;
- }
-}
-
-public boolean isConstructor() {
- return true;
-}
-
-public boolean isDefaultConstructor() {
- return this.isDefaultConstructor;
-}
-
-public boolean isInitializationMethod() {
- return true;
-}
-
-/*
- * Returns true if the constructor is directly involved in a cycle.
- * Given most constructors aren't, we only allocate the visited list
- * lazily.
- */
-public boolean isRecursive(ArrayList visited) {
- if (this.binding == null
- || this.constructorCall == null
- || this.constructorCall.binding == null
- || this.constructorCall.isSuperAccess()
- || !this.constructorCall.binding.isValidBinding()) {
- return false;
- }
-
- ConstructorDeclaration targetConstructor =
- ((ConstructorDeclaration)this.scope.referenceType().declarationOf(this.constructorCall.binding.original()));
- if (this == targetConstructor) return true; // direct case
-
- if (visited == null) { // lazy allocation
- visited = new ArrayList(1);
- } else {
- int index = visited.indexOf(this);
- if (index >= 0) return index == 0; // only blame if directly part of the cycle
- }
- visited.add(this);
-
- return targetConstructor.isRecursive(visited);
-}
-
-public void parseStatements(Parser parser, CompilationUnitDeclaration unit) {
- //fill up the constructor body with its statements
- if (this.ignoreFurtherInvestigation)
- return;
- if (this.isDefaultConstructor && this.constructorCall == null){
- this.constructorCall = SuperReference.implicitSuperConstructorCall();
- this.constructorCall.sourceStart = this.sourceStart;
- this.constructorCall.sourceEnd = this.sourceEnd;
- return;
- }
- parser.parse(this, unit);
-
-}
-
-public StringBuffer printBody(int indent, StringBuffer output) {
- output.append(" {"); //$NON-NLS-1$
- if (this.constructorCall != null) {
- output.append('\n');
- this.constructorCall.printStatement(indent, output);
- }
- if (this.statements != null) {
- for (int i = 0; i < this.statements.length; i++) {
- output.append('\n');
- this.statements[i].printStatement(indent, output);
- }
- }
- output.append('\n');
- printIndent(indent == 0 ? 0 : indent - 1, output).append('}');
- return output;
-}
-
-public void resolveJavadoc() {
- if (this.binding == null || this.javadoc != null) {
- super.resolveJavadoc();
- } else if (!this.isDefaultConstructor) {
- this.scope.problemReporter().javadocMissing(this.sourceStart, this.sourceEnd, this.binding.modifiers);
- }
-}
-
-/*
- * Type checking for constructor, just another method, except for special check
- * for recursive constructor invocations.
- */
-public void resolveStatements() {
- SourceTypeBinding sourceType = this.scope.enclosingSourceType();
- if (!CharOperation.equals(sourceType.sourceName, this.selector)){
- this.scope.problemReporter().missingReturnType(this);
- }
- if (this.binding != null && !this.binding.isPrivate()) {
- sourceType.tagBits |= TagBits.HasNonPrivateConstructor;
- }
- // if null ==> an error has occurs at parsing time ....
- if (this.constructorCall != null) {
- if (sourceType.id == TypeIds.T_JavaLangObject
- && this.constructorCall.accessMode != ExplicitConstructorCall.This) {
- this.constructorCall = null;
- } else {
- this.constructorCall.resolve(this.scope);
- }
- }
- super.resolveStatements();
-}
-
-public void traverse(ASTVisitor visitor, ClassScope classScope) {
- if (visitor.visit(this, classScope)) {
- if (this.javadoc != null) {
- this.javadoc.traverse(visitor, this.scope);
- }
- if (this.arguments != null) {
- int argumentLength = this.arguments.length;
- for (int i = 0; i < argumentLength; i++)
- this.arguments[i].traverse(visitor, this.scope);
- }
- if (this.constructorCall != null)
- this.constructorCall.traverse(visitor, this.scope);
- if (this.statements != null) {
- int statementsLength = this.statements.length;
- for (int i = 0; i < statementsLength; i++)
- this.statements[i].traverse(visitor, this.scope);
- }
- }
- visitor.endVisit(this, classScope);
-}
-public int getASTType() {
- return IASTNode.CONSTRUCTOR_DECLARATION;
-
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ContinueStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ContinueStatement.java
deleted file mode 100644
index 36c42321..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ContinueStatement.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IContinueStatement;
-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;
-import org.eclipse.wst.jsdt.internal.compiler.flow.InsideSubRoutineFlowContext;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-
-public class ContinueStatement extends BranchStatement implements IContinueStatement {
-
-public ContinueStatement(char[] label, int sourceStart, int sourceEnd) {
- super(label, sourceStart, sourceEnd);
-}
-
-public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {
-
- // here requires to generate a sequence of finally blocks invocations depending corresponding
- // to each of the traversed try statements, so that execution will terminate properly.
-
- // lookup the label, this should answer the returnContext
- FlowContext targetContext = (label == null)
- ? flowContext.getTargetContextForDefaultContinue()
- : flowContext.getTargetContextForContinueLabel(label);
-
- if (targetContext == null) {
- if (label == null) {
- currentScope.problemReporter().invalidContinue(this);
- } else {
- currentScope.problemReporter().undefinedLabel(this);
- }
- return flowInfo; // pretend it did not continue since no actual target
- }
-
- if (targetContext == FlowContext.NotContinuableContext) {
- currentScope.problemReporter().invalidContinue(this);
- return flowInfo; // pretend it did not continue since no actual target
- }
-// this.initStateIndex =
-// currentScope.methodScope().recordInitializationStates(flowInfo);
-
-// targetLabel = targetContext.continueLabel();
- FlowContext traversedContext = flowContext;
- int subCount = 0;
- subroutines = new SubRoutineStatement[5];
-
- do {
- SubRoutineStatement sub;
- if ((sub = traversedContext.subroutine()) != null) {
- if (subCount == subroutines.length) {
- System.arraycopy(subroutines, 0, subroutines = new SubRoutineStatement[subCount*2], 0, subCount); // grow
- }
- subroutines[subCount++] = sub;
- if (sub.isSubRoutineEscaping()) {
- 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
- }
- } else if (traversedContext == targetContext) {
- // only record continue info once accumulated through subroutines, and only against target context
- targetContext.recordContinueFrom(flowContext, flowInfo);
- break;
- }
- } while ((traversedContext = traversedContext.parent) != null);
-
- // resize subroutines
- if (subCount != subroutines.length) {
- System.arraycopy(subroutines, 0, subroutines = new SubRoutineStatement[subCount], 0, subCount);
- }
- return FlowInfo.DEAD_END;
-}
-
-public StringBuffer printStatement(int tab, StringBuffer output) {
- printIndent(tab, output).append("continue "); //$NON-NLS-1$
- if (label != null) output.append(label);
- return output.append(';');
-}
-
-public void traverse(ASTVisitor visitor, BlockScope blockScope) {
- visitor.visit(this, blockScope);
- visitor.endVisit(this, blockScope);
-}
-public int getASTType() {
- return IASTNode.CONTINUE_STATEMENT;
-
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/DebuggerStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/DebuggerStatement.java
deleted file mode 100644
index 19409114..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/DebuggerStatement.java
+++ /dev/null
@@ -1,64 +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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IDebuggerStatement;
-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.lookup.BlockScope;
-
-public class DebuggerStatement extends Statement implements IDebuggerStatement {
-
- public DebuggerStatement(int startPosition, int endPosition) {
- this.sourceStart = startPosition;
- this.sourceEnd = endPosition;
- }
-
- public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {
- return flowInfo;
- }
-
- // Report an error if necessary
- public boolean complainIfUnreachable(FlowInfo flowInfo, BlockScope scope, boolean didAlreadyComplain) {
-
- // before 1.4, empty statements are tolerated anywhere
- if (scope.compilerOptions().complianceLevel < ClassFileConstants.JDK1_4) {
- return false;
- }
- return super.complainIfUnreachable(flowInfo, scope, didAlreadyComplain);
- }
-
- public StringBuffer printStatement(int tab, StringBuffer output) {
- return printIndent(tab, output).append("debugger;");
- }
-
- public void resolve(BlockScope scope) {
- if ((bits & IsUsefulEmptyStatement) == 0) {
- scope.problemReporter().superfluousSemicolon(this.sourceStart, this.sourceEnd);
- } else {
- scope.problemReporter().emptyControlFlowStatement(this.sourceStart, this.sourceEnd);
- }
- }
-
- public void traverse(ASTVisitor visitor, BlockScope scope) {
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
- }
- public int getASTType() {
- return IASTNode.EMPTY_STATEMENT;
-
- }
-
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/DoStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/DoStatement.java
deleted file mode 100644
index 19897203..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/DoStatement.java
+++ /dev/null
@@ -1,151 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IDoStatement;
-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;
-import org.eclipse.wst.jsdt.internal.compiler.flow.LoopingFlowContext;
-import org.eclipse.wst.jsdt.internal.compiler.flow.UnconditionalFlowInfo;
-import org.eclipse.wst.jsdt.internal.compiler.impl.Constant;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class DoStatement extends Statement implements IDoStatement {
-
- public Expression condition;
- public Statement action;
-
-
- // for local variables table attributes
- int mergedInitStateIndex = -1;
-
-public DoStatement(Expression condition, Statement action, int s, int e) {
-
- this.sourceStart = s;
- this.sourceEnd = e;
- this.condition = condition;
- this.action = action;
- // remember useful empty statement
- if (action instanceof EmptyStatement) action.bits |= ASTNode.IsUsefulEmptyStatement;
-}
-
-public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {
- LoopingFlowContext loopingContext =
- new LoopingFlowContext(
- flowContext,
- flowInfo,
- this,
- currentScope);
-
- Constant cst = this.condition.constant;
- boolean isConditionTrue = cst != Constant.NotAConstant && cst.booleanValue() == true;
- cst = this.condition.optimizedBooleanConstant();
- boolean isConditionOptimizedTrue = cst != Constant.NotAConstant && cst.booleanValue() == true;
- boolean isConditionOptimizedFalse = cst != Constant.NotAConstant && cst.booleanValue() == false;
-
- int previousMode = flowInfo.reachMode();
-
- boolean isContinue=true;
-
-
- UnconditionalFlowInfo actionInfo = flowInfo.nullInfoLessUnconditionalCopy();
- // we need to collect the contribution to nulls of the coming paths through the
- // loop, be they falling through normally or branched to break, continue labels
- // or catch blocks
- if ((this.action != null) && !this.action.isEmptyBlock()) {
- actionInfo = this.action.
- analyseCode(currentScope, loopingContext, actionInfo).
- unconditionalInits();
-
- // code generation can be optimized when no need to continue in the loop
- if ((actionInfo.tagBits &
- loopingContext.initsOnContinue.tagBits &
- FlowInfo.UNREACHABLE) != 0) {
- isContinue = false;
- }
- }
- /* Reset reach mode, to address following scenario.
- * final blank;
- * do { if (true) break; else blank = 0; } while(false);
- * blank = 1; // may be initialized already
- */
- actionInfo.setReachMode(previousMode);
-
- LoopingFlowContext condLoopContext;
- FlowInfo condInfo =
- this.condition.analyseCode(
- currentScope,
- (condLoopContext =
- new LoopingFlowContext(flowContext, flowInfo, this, currentScope)),
- (this.action == null
- ? actionInfo
- : (actionInfo.mergedWith(loopingContext.initsOnContinue))).copy());
- if (!isConditionOptimizedFalse && isContinue) {
- loopingContext.complainOnDeferredNullChecks(currentScope,
- flowInfo.unconditionalCopy().addPotentialNullInfoFrom(
- condInfo.initsWhenTrue().unconditionalInits()));
- condLoopContext.complainOnDeferredNullChecks(currentScope,
- actionInfo.addPotentialNullInfoFrom(
- condInfo.initsWhenTrue().unconditionalInits()));
- }
-
- // end of loop
- FlowInfo mergedInfo = FlowInfo.mergedOptimizedBranches(
- (loopingContext.initsOnBreak.tagBits &
- FlowInfo.UNREACHABLE) != 0 ?
- loopingContext.initsOnBreak :
- flowInfo.unconditionalCopy().addInitializationsFrom(loopingContext.initsOnBreak),
- // recover upstream null info
- isConditionOptimizedTrue,
- (condInfo.tagBits & FlowInfo.UNREACHABLE) == 0 ?
- flowInfo.addInitializationsFrom(condInfo.initsWhenFalse()) : condInfo,
- // recover null inits from before condition analysis
- false, // never consider opt false case for DO loop, since break can always occur (47776)
- !isConditionTrue /*do{}while(true); unreachable(); */);
-// this.mergedInitStateIndex = currentScope.methodScope().recordInitializationStates(mergedInfo);
- return mergedInfo;
-}
-
-public StringBuffer printStatement(int indent, StringBuffer output) {
- printIndent(indent, output).append("do"); //$NON-NLS-1$
- if (this.action == null)
- output.append(" ;\n"); //$NON-NLS-1$
- else {
- output.append('\n');
- this.action.printStatement(indent + 1, output).append('\n');
- }
- output.append("while ("); //$NON-NLS-1$
- return this.condition.printExpression(0, output).append(");"); //$NON-NLS-1$
-}
-
-public void resolve(BlockScope scope) {
- TypeBinding type = this.condition.resolveTypeExpecting(scope, TypeBinding.BOOLEAN);
- if (this.action != null)
- this.action.resolve(scope);
-}
-
-public void traverse(ASTVisitor visitor, BlockScope scope) {
- if (visitor.visit(this, scope)) {
- if (this.action != null) {
- this.action.traverse(visitor, scope);
- }
- this.condition.traverse(visitor, scope);
- }
- visitor.endVisit(this, scope);
-}
-public int getASTType() {
- return IASTNode.DOUBLE_LITERAL;
-
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/DoubleLiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/DoubleLiteral.java
deleted file mode 100644
index 1212e93e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/DoubleLiteral.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IDoubleLiteral;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-import org.eclipse.wst.jsdt.internal.compiler.impl.DoubleConstant;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-import org.eclipse.wst.jsdt.internal.compiler.util.FloatUtil;
-
-public class DoubleLiteral extends NumberLiteral implements IDoubleLiteral {
- double value;
- public DoubleLiteral(char[] token, int s, int e) {
- super(token, s, e);
- }
- public void computeConstant() {
- Double computedValue;
- try {
- computedValue = Double.valueOf(String.valueOf(source));
- } catch (NumberFormatException e) {
- // hex floating point literal
- // being rejected by 1.4 libraries where Double.valueOf(...) doesn't handle hex decimal floats
- try {
- double v = FloatUtil.valueOfHexDoubleLiteral(source);
- if (v == Double.POSITIVE_INFINITY) {
- // error: the number is too large to represent
- return;
- }
- if (Double.isNaN(v)) {
- // error: the number is too small to represent
- return;
- }
- value = v;
- constant = DoubleConstant.fromValue(v);
- } catch (NumberFormatException e1) {
- // if the computation of the constant fails
- }
- return;
- }
-
- final double doubleValue = computedValue.doubleValue();
- if (doubleValue > Double.MAX_VALUE) {
- // error: the number is too large to represent
- return;
- }
- if (doubleValue < Double.MIN_VALUE) {
- // see 1F6IGUU
- // a true 0 only has '0' and '.' in mantissa
- // 1.0e-5000d is non-zero, but underflows to 0
- boolean isHexaDecimal = false;
- label : for (int i = 0; i < source.length; i++) { //it is welled formated so just test against '0' and potential . D d
- switch (source[i]) {
- case '0' :
- case '.' :
- break;
- case 'x' :
- case 'X' :
- isHexaDecimal = true;
- break;
- case 'e' :
- case 'E' :
- case 'f' :
- case 'F' :
- case 'd' :
- case 'D' :
- if (isHexaDecimal) {
- return;
- }
- // starting the exponent - mantissa is all zero
- // no exponent - mantissa is all zero
- break label;
- case 'p' :
- case 'P' :
- break label;
- default :
- // error: the number is too small to represent
- return;
- }
- }
- }
- value = doubleValue;
- constant = DoubleConstant.fromValue(value);
- }
- public TypeBinding literalType(BlockScope scope) {
- return TypeBinding.DOUBLE;
- }
- public void traverse(ASTVisitor visitor, BlockScope scope) {
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
- }
- public int getASTType() {
- return IASTNode.DOUBLE_LITERAL;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/EmptyExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/EmptyExpression.java
deleted file mode 100644
index a2937d60..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/EmptyExpression.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IEmptyExpression;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class EmptyExpression extends Expression implements IEmptyExpression {
-
-
-
- public EmptyExpression(int startPosition, int endPosition) {
- this.sourceStart = startPosition;
- this.sourceEnd = endPosition;
- }
-
-
- public StringBuffer printExpression(int indent, StringBuffer output) {
- return output;
- }
-
- public void resolve(BlockScope scope) {
- }
-
- public TypeBinding resolveType(BlockScope scope) {
- return TypeBinding.ANY;
- }
- public int getASTType() {
- return IASTNode.EMPTY_EXPRESSION;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/EmptyStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/EmptyStatement.java
deleted file mode 100644
index 51b4c0f9..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/EmptyStatement.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IEmptyStatement;
-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.lookup.BlockScope;
-
-public class EmptyStatement extends Statement implements IEmptyStatement {
-
- public EmptyStatement(int startPosition, int endPosition) {
- this.sourceStart = startPosition;
- this.sourceEnd = endPosition;
- }
-
- public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {
- return flowInfo;
- }
-
- // Report an error if necessary
- public boolean complainIfUnreachable(FlowInfo flowInfo, BlockScope scope, boolean didAlreadyComplain) {
-
- // before 1.4, empty statements are tolerated anywhere
- if (scope.compilerOptions().complianceLevel < ClassFileConstants.JDK1_4) {
- return false;
- }
- return super.complainIfUnreachable(flowInfo, scope, didAlreadyComplain);
- }
-
- public StringBuffer printStatement(int tab, StringBuffer output) {
- return printIndent(tab, output).append(';');
- }
-
- public void resolve(BlockScope scope) {
- if ((bits & IsUsefulEmptyStatement) == 0) {
- scope.problemReporter().superfluousSemicolon(this.sourceStart, this.sourceEnd);
- } else {
- scope.problemReporter().emptyControlFlowStatement(this.sourceStart, this.sourceEnd);
- }
- }
-
- public void traverse(ASTVisitor visitor, BlockScope scope) {
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
- }
- public int getASTType() {
- return IASTNode.EMPTY_STATEMENT;
-
- }
-
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/EqualExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/EqualExpression.java
deleted file mode 100644
index 06ebbba9..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/EqualExpression.java
+++ /dev/null
@@ -1,234 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IEqualExpression;
-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.flow.UnconditionalFlowInfo;
-import org.eclipse.wst.jsdt.internal.compiler.impl.BooleanConstant;
-import org.eclipse.wst.jsdt.internal.compiler.impl.Constant;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.LocalVariableBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TagBits;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class EqualExpression extends BinaryExpression implements IEqualExpression {
-
- public EqualExpression(Expression left, Expression right,int operator) {
- super(left,right,operator);
- }
- private void checkNullComparison(BlockScope scope, FlowContext flowContext, FlowInfo flowInfo, FlowInfo initsWhenTrue, FlowInfo initsWhenFalse) {
-
- LocalVariableBinding local = this.left.localVariableBinding();
- if (local != null && (local.type.tagBits & TagBits.IsBaseType) == 0) {
- checkVariableComparison(scope, flowContext, flowInfo, initsWhenTrue, initsWhenFalse, local, right.nullStatus(flowInfo), this.left);
- }
- local = this.right.localVariableBinding();
- if (local != null && (local.type.tagBits & TagBits.IsBaseType) == 0) {
- checkVariableComparison(scope, flowContext, flowInfo, initsWhenTrue, initsWhenFalse, local, left.nullStatus(flowInfo), this.right);
- }
- }
- private void checkVariableComparison(BlockScope scope, FlowContext flowContext, FlowInfo flowInfo, FlowInfo initsWhenTrue, FlowInfo initsWhenFalse, LocalVariableBinding local, int nullStatus, Expression reference) {
- switch (nullStatus) {
- case FlowInfo.NULL :
- if (((this.bits & OperatorMASK) >> OperatorSHIFT) == EQUAL_EQUAL) {
- flowContext.recordUsingNullReference(scope, local, reference,
- FlowContext.CAN_ONLY_NULL_NON_NULL | FlowContext.IN_COMPARISON_NULL, flowInfo);
- initsWhenTrue.markAsComparedEqualToNull(local); // from thereon it is set
- initsWhenFalse.markAsComparedEqualToNonNull(local); // from thereon it is set
- } else {
- flowContext.recordUsingNullReference(scope, local, reference,
- FlowContext.CAN_ONLY_NULL_NON_NULL | FlowContext.IN_COMPARISON_NON_NULL, flowInfo);
- initsWhenTrue.markAsComparedEqualToNonNull(local); // from thereon it is set
- initsWhenFalse.markAsComparedEqualToNull(local); // from thereon it is set
- }
- break;
- case FlowInfo.NON_NULL :
- if (((this.bits & OperatorMASK) >> OperatorSHIFT) == EQUAL_EQUAL) {
- flowContext.recordUsingNullReference(scope, local, reference,
- FlowContext.CAN_ONLY_NULL | FlowContext.IN_COMPARISON_NON_NULL, flowInfo);
- initsWhenTrue.markAsComparedEqualToNonNull(local); // from thereon it is set
- } else {
- flowContext.recordUsingNullReference(scope, local, reference,
- FlowContext.CAN_ONLY_NULL | FlowContext.IN_COMPARISON_NULL, flowInfo);
- }
- break;
- }
- // we do not impact enclosing try context because this kind of protection
- // does not preclude the variable from being null in an enclosing scope
- }
-
- public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {
- FlowInfo result;
- if (((bits & OperatorMASK) >> OperatorSHIFT) == EQUAL_EQUAL) {
- if ((left.constant != Constant.NotAConstant) && (left.constant.typeID() == T_boolean)) {
- if (left.constant.booleanValue()) { // true == anything
- // this is equivalent to the right argument inits
- result = right.analyseCode(currentScope, flowContext, flowInfo);
- } else { // false == anything
- // this is equivalent to the right argument inits negated
- result = right.analyseCode(currentScope, flowContext, flowInfo).asNegatedCondition();
- }
- }
- else if (right.constant != null && (right.constant != Constant.NotAConstant) && (right.constant.typeID() == T_boolean)) {
- if (right.constant.booleanValue()) { // anything == true
- // this is equivalent to the left argument inits
- result = left.analyseCode(currentScope, flowContext, flowInfo);
- } else { // anything == false
- // this is equivalent to the right argument inits negated
- result = left.analyseCode(currentScope, flowContext, flowInfo).asNegatedCondition();
- }
- }
- else {
- result = right.analyseCode(
- currentScope, flowContext,
- left.analyseCode(currentScope, flowContext, flowInfo).unconditionalInits()).unconditionalInits();
- }
- } else { //NOT_EQUAL :
- if ((left.constant != Constant.NotAConstant) && (left.constant.typeID() == T_boolean)) {
- if (!left.constant.booleanValue()) { // false != anything
- // this is equivalent to the right argument inits
- result = right.analyseCode(currentScope, flowContext, flowInfo);
- } else { // true != anything
- // this is equivalent to the right argument inits negated
- result = right.analyseCode(currentScope, flowContext, flowInfo).asNegatedCondition();
- }
- }
- else if ((right.constant != Constant.NotAConstant) && (right.constant.typeID() == T_boolean)) {
- if (!right.constant.booleanValue()) { // anything != false
- // this is equivalent to the right argument inits
- result = left.analyseCode(currentScope, flowContext, flowInfo);
- } else { // anything != true
- // this is equivalent to the right argument inits negated
- result = left.analyseCode(currentScope, flowContext, flowInfo).asNegatedCondition();
- }
- }
- else {
- result = right.analyseCode(
- currentScope, flowContext,
- left.analyseCode(currentScope, flowContext, flowInfo).unconditionalInits()).
- /* unneeded since we flatten it: asNegatedCondition(). */
- unconditionalInits();
- }
- }
- if (result instanceof UnconditionalFlowInfo &&
- (result.tagBits & FlowInfo.UNREACHABLE) == 0) { // the flow info is flat
- result = FlowInfo.conditional(result.copy(), result.copy());
- // TODO (maxime) check, reintroduced copy
- }
- checkNullComparison(currentScope, flowContext, result, result.initsWhenTrue(), result.initsWhenFalse());
- return result;
- }
-
- public final void computeConstant(TypeBinding leftType, TypeBinding rightType) {
- if ((this.left.constant != Constant.NotAConstant) && (this.right.constant != Constant.NotAConstant)) {
- this.constant =
- Constant.computeConstantOperationEQUAL_EQUAL(
- left.constant,
- leftType.id,
- right.constant,
- rightType.id);
- if (((this.bits & OperatorMASK) >> OperatorSHIFT) == NOT_EQUAL)
- constant = BooleanConstant.fromValue(!constant.booleanValue());
- } else {
- this.constant = Constant.NotAConstant;
- // no optimization for null == null
- }
- }
- public boolean isCompactableOperation() {
- return false;
- }
- public TypeBinding resolveType(BlockScope scope) {
-
- constant = Constant.NotAConstant;
- TypeBinding originalLeftType = left.resolveType(scope);
- TypeBinding originalRightType = right.resolveType(scope);
-
- // always return BooleanBinding
- if (originalLeftType == null || originalRightType == null){
- constant = Constant.NotAConstant;
- return TypeBinding.BOOLEAN;
- }
-
- // autoboxing support
- boolean use15specifics = scope.compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5;
- TypeBinding leftType = originalLeftType, rightType = originalRightType;
- if (use15specifics) {
- if (leftType != TypeBinding.NULL && leftType.isBaseType()) {
- if (!rightType.isBaseType()) {
- rightType = scope.environment().computeBoxingType(rightType);
- }
- } else {
- if (rightType != TypeBinding.NULL && rightType.isBaseType()) {
- leftType = scope.environment().computeBoxingType(leftType);
- }
- }
- }
- // both base type
- if (leftType.isAnyType() || rightType.isAnyType())
- {
- return TypeBinding.BOOLEAN;
- }
- if ( leftType.isBasicType() && rightType.isBasicType()) {
- int leftTypeID = leftType.id;
- int rightTypeID = rightType.id;
-
- // the code is an int
- // (cast) left == (cast) right --> result
- // 0000 0000 0000 0000 0000
- // <<16 <<12 <<8 <<4 <<0
- int operatorSignature = OperatorSignatures[EQUAL_EQUAL][ (leftTypeID << 4) + rightTypeID];
- bits |= operatorSignature & 0xF;
- // fix for https://bugs.eclipse.org/bugs/show_bug.cgi?id=283663
- if ((operatorSignature & 0x0000F) == T_undefined) {
- constant = Constant.NotAConstant;
- //scope.problemReporter().invalidOperator(this, leftType, rightType);
- return TypeBinding.BOOLEAN;
- }
-
- computeConstant(leftType, rightType);
- return this.resolvedType = TypeBinding.BOOLEAN;
- }
-
- // Object references
- // spec 15.20.3
- if ((!leftType.isBaseType() || leftType == TypeBinding.NULL) // cannot compare: Object == (int)0
- && (!rightType.isBaseType() || rightType == TypeBinding.NULL)
- && (this.checkCastTypesCompatibility(scope, leftType, rightType, null)
- || this.checkCastTypesCompatibility(scope, rightType, leftType, null))) {
-
- // (special case for String)
- if ((rightType.id == T_JavaLangString) && (leftType.id == T_JavaLangString)) {
- computeConstant(leftType, rightType);
- } else {
- constant = Constant.NotAConstant;
- }
- return this.resolvedType = TypeBinding.BOOLEAN;
- }
- constant = Constant.NotAConstant;
- return null;
- }
- public void traverse(ASTVisitor visitor, BlockScope scope) {
- if (visitor.visit(this, scope)) {
- left.traverse(visitor, scope);
- right.traverse(visitor, scope);
- }
- visitor.endVisit(this, scope);
- }
- public int getASTType() {
- return IASTNode.EQUAL_EXPRESSION;
-
- }
-}
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
deleted file mode 100644
index b0d63f13..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ExplicitConstructorCall.java
+++ /dev/null
@@ -1,327 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IExplicitConstructorCall;
-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.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.InvocationSite;
-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.ProblemMethodBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding;
-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.VariableBinding;
-
-public class ExplicitConstructorCall extends Statement implements InvocationSite, IExplicitConstructorCall {
-
- public Expression[] arguments;
- public Expression qualification;
- public MethodBinding binding; // exact binding resulting from lookup
- protected MethodBinding codegenBinding; // actual binding used for code generation (if no synthetic accessor)
- public int accessMode;
- public TypeReference[] typeArguments;
- public TypeBinding[] genericTypeArguments;
-
- public final static int ImplicitSuper = 1;
- public final static int This = 3;
-
- public VariableBinding[][] implicitArguments;
-
- // TODO Remove once DOMParser is activated
- public int typeArgumentsSourceStart;
-
- public ExplicitConstructorCall(int accessMode) {
- this.accessMode = accessMode;
- }
-
- public FlowInfo analyseCode(
- BlockScope currentScope,
- FlowContext flowContext,
- FlowInfo flowInfo) {
-
- // must verify that exceptions potentially thrown by this expression are caught in the method.
-
- try {
- ((MethodScope) currentScope).isConstructorCall = true;
-
- // process enclosing instance
- if (qualification != null) {
- flowInfo =
- qualification
- .analyseCode(currentScope, flowContext, flowInfo)
- .unconditionalInits();
- }
- // process arguments
- if (arguments != null) {
- for (int i = 0, max = arguments.length; i < max; i++) {
- flowInfo =
- arguments[i]
- .analyseCode(currentScope, flowContext, flowInfo)
- .unconditionalInits();
- }
- }
- manageEnclosingInstanceAccessIfNecessary(currentScope, flowInfo);
- manageSyntheticAccessIfNecessary(currentScope, flowInfo);
- return flowInfo;
- } finally {
- ((MethodScope) currentScope).isConstructorCall = false;
- }
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.lookup.InvocationSite#genericTypeArguments()
- */
- public TypeBinding[] genericTypeArguments() {
- return this.genericTypeArguments;
- }
- public boolean isImplicitSuper() {
- //return true if I'm of these compiler added statement super();
-
- return (accessMode == ImplicitSuper);
- }
-
- public boolean isSuperAccess() {
-
- return accessMode != This;
- }
-
- public boolean isTypeAccess() {
-
- return true;
- }
-
- /* Inner emulation consists in either recording a dependency
- * link only, or performing one level of propagation.
- *
- * Dependency mechanism is used whenever dealing with source target
- * types, since by the time we reach them, we might not yet know their
- * exact need.
- */
- void manageEnclosingInstanceAccessIfNecessary(BlockScope currentScope, FlowInfo flowInfo) {
- ReferenceBinding superTypeErasure = binding.declaringClass;
-
- if ((flowInfo.tagBits & FlowInfo.UNREACHABLE) == 0) {
- // perform some emulation work in case there is some and we are inside a local type only
- if (superTypeErasure.isNestedType()
- && currentScope.enclosingSourceType().isLocalType()) {
-
- if (superTypeErasure.isLocalType()) {
- ((LocalTypeBinding) superTypeErasure).addInnerEmulationDependent(currentScope, qualification != null);
- }
- }
- }
- }
-
- public void manageSyntheticAccessIfNecessary(BlockScope currentScope, FlowInfo flowInfo) {
-
- if ((flowInfo.tagBits & FlowInfo.UNREACHABLE) == 0) {
- // if constructor from parameterized type got found, use the original constructor at codegen time
- this.codegenBinding = this.binding.original();
-
- // perform some emulation work in case there is some and we are inside a local type only
- if (binding.isPrivate() && accessMode != This) {
- ReferenceBinding declaringClass = this.codegenBinding.declaringClass;
- // from 1.4 on, local type constructor can lose their private flag to ease emulation
- if ((declaringClass.tagBits & TagBits.IsLocalType) != 0 && currentScope.compilerOptions().complianceLevel >= ClassFileConstants.JDK1_4) {
- // constructor will not be dumped as private, no emulation required thus
- this.codegenBinding.tagBits |= TagBits.ClearPrivateModifier;
- }
- }
- }
- }
-
- public StringBuffer printStatement(int indent, StringBuffer output) {
-
- printIndent(indent, output);
- if (qualification != null) qualification.printExpression(0, output).append('.');
- if (typeArguments != null) {
- output.append('<');
- int max = typeArguments.length - 1;
- for (int j = 0; j < max; j++) {
- typeArguments[j].print(0, output);
- output.append(", ");//$NON-NLS-1$
- }
- typeArguments[max].print(0, output);
- output.append('>');
- }
- if (accessMode == This) {
- output.append("this("); //$NON-NLS-1$
- } else {
- output.append("super("); //$NON-NLS-1$
- }
- 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(");"); //$NON-NLS-1$
- }
-
- public void resolve(BlockScope scope) {
- // the return type should be void for a constructor.
- // the test is made into getConstructor
-
- // mark the fact that we are in a constructor call.....
- // unmark at all returns
- MethodScope methodScope = scope.methodScope();
- try {
- AbstractMethodDeclaration methodDeclaration = methodScope.referenceMethod();
- if (methodDeclaration == null
- || !methodDeclaration.isConstructor()
- || ((ConstructorDeclaration) methodDeclaration).constructorCall != this) {
- // fault-tolerance
- if (this.qualification != null) {
- this.qualification.resolveType(scope);
- }
- if (this.typeArguments != null) {
- for (int i = 0, max = this.typeArguments.length; i < max; i++) {
- this.typeArguments[i].resolveType(scope, true /* check bounds*/);
- }
- }
- if (this.arguments != null) {
- for (int i = 0, max = this.arguments.length; i < max; i++) {
- this.arguments[i].resolveType(scope);
- }
- }
- return;
- }
- methodScope.isConstructorCall = true;
- ReferenceBinding receiverType = scope.enclosingReceiverType();
- if (accessMode != This)
- receiverType = receiverType.superclass();
-
- if (receiverType == null) {
- return;
- }
- // qualification should be from the type of the enclosingType
- if (qualification != null) {
-
- ReferenceBinding enclosingType = receiverType.enclosingType();
- if (enclosingType == null) {
- this.bits |= ASTNode.DiscardEnclosingInstance;
- } else {
- qualification.resolveTypeExpecting(scope, enclosingType);
- }
- }
- // resolve type arguments (for generic constructor call)
- if (this.typeArguments != null) {
- int length = this.typeArguments.length;
- boolean argHasError = false; // typeChecks all arguments
- this.genericTypeArguments = new TypeBinding[length];
- for (int i = 0; i < length; i++) {
- TypeReference typeReference = this.typeArguments[i];
- if ((this.genericTypeArguments[i] = typeReference.resolveType(scope, true /* check bounds*/)) == null) {
- argHasError = true;
- }
- }
- if (argHasError) {
- return;
- }
- }
-
- // arguments buffering for the method lookup
- TypeBinding[] argumentTypes = Binding.NO_PARAMETERS;
- boolean argsContainCast = false;
- 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 = this.arguments[i];
- if ((argumentTypes[i] = argument.resolveType(scope)) == null) {
- argHasError = true;
- }
- }
- if (argHasError) {
- // record a best guess, for clients who need hint about possible contructor 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 null type
- }
- this.binding = scope.findMethod(receiverType, TypeConstants.INIT, pseudoArgs, this);
- if (this.binding != null && !this.binding.isValidBinding()) {
- MethodBinding closestMatch = ((ProblemMethodBinding)this.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.modifiers |= ExtraCompilerModifiers.AccLocallyUsed;
- }
- }
- }
- return;
- }
- }
- if ((binding = scope.getConstructor(receiverType, argumentTypes, this)).isValidBinding()) {
- if (isMethodUseDeprecated(this.binding, scope, this.accessMode != ImplicitSuper))
- scope.problemReporter().deprecatedMethod(binding, this);
- checkInvocationArguments(scope, null, receiverType, binding, this.arguments, argumentTypes, argsContainCast, this);
- if (binding.isPrivate() || receiverType.isLocalType()) {
- binding.original().modifiers |= ExtraCompilerModifiers.AccLocallyUsed;
- }
- } else {
- if (binding.declaringClass == null)
- binding.declaringClass = receiverType;
- scope.problemReporter().invalidConstructor(this, binding);
- }
- } finally {
- methodScope.isConstructorCall = false;
- }
- }
-
- public void setActualReceiverType(ReferenceBinding receiverType) {
- // ignored
- }
-
- public void setDepth(int depth) {
- // ignore for here
- }
-
- public void setFieldIndex(int depth) {
- // ignore for here
- }
-
- public void traverse(ASTVisitor visitor, BlockScope scope) {
-
- if (visitor.visit(this, scope)) {
- if (this.qualification != null) {
- this.qualification.traverse(visitor, scope);
- }
- if (this.typeArguments != null) {
- for (int i = 0, typeArgumentsLength = this.typeArguments.length; i < typeArgumentsLength; i++) {
- this.typeArguments[i].traverse(visitor, scope);
- }
- }
- if (this.arguments != null) {
- for (int i = 0, argumentLength = this.arguments.length; i < argumentLength; i++)
- this.arguments[i].traverse(visitor, scope);
- }
- }
- visitor.endVisit(this, scope);
- }
- public int getASTType() {
- return IASTNode.EXPLICIT_CONSTRUCTOR_CALL;
-
- }
-}
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
deleted file mode 100644
index dc1c8aac..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Expression.java
+++ /dev/null
@@ -1,668 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IExpression;
-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.ArrayBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BaseTypeBinding;
-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.LocalVariableBinding;
-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.lookup.TypeIds;
-
-public abstract class Expression extends Statement implements IExpression {
-
- public Constant constant;
-
- public int statementEnd = -1;
-
- //Some expression may not be used - from a java semantic point
- //of view only - as statements. Other may. In order to avoid the creation
- //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) {
- //true if there is no loss of precision while casting.
- // constantTypeID == constant.typeID
- if (targetTypeID == constantTypeID || constantTypeID==T_any)
- return true;
- switch (targetTypeID) {
- case T_char :
- switch (constantTypeID) {
- case T_char :
- return true;
- case T_double :
- return constant.doubleValue() == constant.charValue();
- case T_float :
- return constant.floatValue() == constant.charValue();
- case T_int :
- return constant.intValue() == constant.charValue();
- case T_short :
- return constant.shortValue() == constant.charValue();
- case T_long :
- return constant.longValue() == constant.charValue();
- default :
- return false;//boolean
- }
-
- case T_float :
- switch (constantTypeID) {
- case T_char :
- return constant.charValue() == constant.floatValue();
- case T_double :
- return constant.doubleValue() == constant.floatValue();
- case T_float :
- return true;
- case T_int :
- return constant.intValue() == constant.floatValue();
- case T_short :
- return constant.shortValue() == constant.floatValue();
- case T_long :
- return constant.longValue() == constant.floatValue();
- default :
- return false;//boolean
- }
-
- case T_double :
- switch (constantTypeID) {
- case T_char :
- return constant.charValue() == constant.doubleValue();
- case T_double :
- return true;
- case T_float :
- return constant.floatValue() == constant.doubleValue();
- case T_int :
- return constant.intValue() == constant.doubleValue();
- case T_short :
- return constant.shortValue() == constant.doubleValue();
- case T_long :
- return constant.longValue() == constant.doubleValue();
- default :
- return false; //boolean
- }
-
- case T_short :
- switch (constantTypeID) {
- case T_char :
- return constant.charValue() == constant.shortValue();
- case T_double :
- return constant.doubleValue() == constant.shortValue();
- case T_float :
- return constant.floatValue() == constant.shortValue();
- case T_int :
- return constant.intValue() == constant.shortValue();
- case T_short :
- return true;
- case T_long :
- return constant.longValue() == constant.shortValue();
- default :
- return false; //boolean
- }
-
- case T_int :
- switch (constantTypeID) {
- case T_char :
- return constant.charValue() == constant.intValue();
- case T_double :
- return constant.doubleValue() == constant.intValue();
- case T_float :
- return constant.floatValue() == constant.intValue();
- case T_int :
- return true;
- case T_short :
- return constant.shortValue() == constant.intValue();
- case T_long :
- return constant.longValue() == constant.intValue();
- default :
- return false; //boolean
- }
-
- case T_long :
- switch (constantTypeID) {
- case T_char :
- return constant.charValue() == constant.longValue();
- case T_double :
- return constant.doubleValue() == constant.longValue();
- case T_float :
- return constant.floatValue() == constant.longValue();
- case T_int :
- return constant.intValue() == constant.longValue();
- case T_short :
- return constant.shortValue() == constant.longValue();
- case T_long :
- return true;
- default :
- return false; //boolean
- }
-
- default :
- return false; //boolean
- }
-}
-
-public Expression() {
- super();
-}
-
-public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {
- return flowInfo;
-}
-
-/**
- * More sophisticated for of the flow analysis used for analyzing expressions, and be able to optimize out
- * portions of expressions where no actual value is required.
- *
- * @param currentScope
- * @param flowContext
- * @param flowInfo
- * @param valueRequired
- * @return The state of initialization after the analysis of the current expression
- */
-public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo, boolean valueRequired) {
-
- return analyseCode(currentScope, flowContext, flowInfo);
-}
-
-/**
- * Returns false if cast is not legal.
- */
-public final boolean checkCastTypesCompatibility(Scope scope, TypeBinding castType, TypeBinding expressionType, Expression expression) {
-
- // see specifications 5.5
- // handle errors and process constant when needed
-
- // if either one of the type is null ==>
- // some error has been already reported some where ==>
- // we then do not report an obvious-cascade-error.
-
- if (castType == null || expressionType == null) return true;
- if (castType==expressionType || castType.id==expressionType.id)
- return true;
-
- // identity conversion cannot be performed upfront, due to side-effects
- // like constant propagation
- boolean use15specifics = scope.compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5;
- if (castType.isBaseType()) {
- if (expressionType.isBaseType()) {
- if (expressionType == castType) {
- if (expression != null) {
- this.constant = expression.constant; //use the same constant
- }
- tagAsUnnecessaryCast(scope, castType);
- return true;
- }
- 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;
-
- }
- } else if (use15specifics
- && scope.environment().computeBoxingType(expressionType).isCompatibleWith(castType)) { // unboxing - only widening match is allowed
- tagAsUnnecessaryCast(scope, castType);
- return true;
- }
- return false;
- } else if (use15specifics
- && expressionType.isBaseType()
- && scope.environment().computeBoxingType(expressionType).isCompatibleWith(castType)) { // boxing - only widening match is allowed
- tagAsUnnecessaryCast(scope, castType);
- return true;
- }
-
- switch(expressionType.kind()) {
- case Binding.BASE_TYPE :
- //-----------cast to something which is NOT a base type--------------------------
- if (expressionType == TypeBinding.NULL) {
- tagAsUnnecessaryCast(scope, castType);
- return true; //null is compatible with every thing
- }
- return false;
-
- case Binding.ARRAY_TYPE :
- if (castType == expressionType) {
- tagAsUnnecessaryCast(scope, castType);
- return true; // identity conversion
- }
- switch (castType.kind()) {
- case Binding.ARRAY_TYPE :
- // ( ARRAY ) ARRAY
- TypeBinding castElementType = ((ArrayBinding) castType).elementsType();
- TypeBinding exprElementType = ((ArrayBinding) expressionType).elementsType();
- if (exprElementType.isBaseType() || castElementType.isBaseType()) {
- if (castElementType == exprElementType) {
- tagAsNeedCheckCast();
- return true;
- }
- return false;
- }
- // recurse on array type elements
- return checkCastTypesCompatibility(scope, castElementType, exprElementType, expression);
-
- default:
- // ( CLASS/INTERFACE ) ARRAY
- switch (castType.id) {
- case T_JavaLangObject :
- tagAsUnnecessaryCast(scope, castType);
- return true;
- default :
- return false;
- }
- }
-
- default:
- switch (castType.kind()) {
- case Binding.ARRAY_TYPE :
- // ( ARRAY ) CLASS
- if (expressionType.id == TypeIds.T_JavaLangObject) { // potential runtime error
- if (use15specifics) checkUnsafeCast(scope, castType, expressionType, expressionType, true);
- tagAsNeedCheckCast();
- return true;
- }
- return false;
-
- default :
- // ( CLASS ) CLASS
- TypeBinding match = expressionType.findSuperTypeWithSameErasure(castType);
- if (match != null) {
- if (expression != null && castType.id == TypeIds.T_JavaLangString) this.constant = expression.constant; // (String) cst is still a constant
- return checkUnsafeCast(scope, castType, expressionType, match, false);
- }
- match = castType.findSuperTypeWithSameErasure(expressionType);
- if (match != null) {
- tagAsNeedCheckCast();
- return checkUnsafeCast(scope, castType, expressionType, match, true);
- }
- return false;
- }
-
- }
-}
-
-/**
- * Check the local variable of this expression, if any, against potential NPEs
- * given a flow context and an upstream flow info. If so, report the risk to
- * the context. Marks the local as checked, which affects the flow info.
- * @param scope the scope of the analysis
- * @param flowContext the current flow context
- * @param flowInfo the upstream flow info; caveat: may get modified
- */
-public void checkNPE(BlockScope scope, FlowContext flowContext,
- FlowInfo flowInfo) {
- LocalVariableBinding local = this.localVariableBinding();
- if (local != null /*&&
- (local.type.tagBits & TagBits.IsBaseType) == 0*/) {
- if ((this.bits & ASTNode.IsNonNull) == 0) {
- flowContext.recordUsingNullReference(scope, local, this,
- FlowContext.MAY_NULL, flowInfo);
- }
- flowInfo.markAsComparedEqualToNonNull(local);
- // from thereon it is set
- if (flowContext.initsOnFinally != null) {
- flowContext.initsOnFinally.markAsComparedEqualToNonNull(local);
- }
- }
-}
-
-public boolean checkUnsafeCast(Scope scope, TypeBinding castType, TypeBinding expressionType, TypeBinding match, boolean isNarrowing) {
- if (match == castType) {
- if (!isNarrowing) tagAsUnnecessaryCast(scope, castType);
- return true;
- }
- if (!isNarrowing) tagAsUnnecessaryCast(scope, castType);
- return true;
- }
-
- public boolean isCompactableOperation() {
-
- return false;
- }
-
- //Return true if the conversion is done AUTOMATICALLY by the vm
- //while the javaVM is an int based-machine, thus for example pushing
- //a byte onto the stack , will automatically create an int on the stack
- //(this request some work d be done by the VM on signed numbers)
- public boolean isConstantValueOfTypeAssignableToType(TypeBinding constantType, TypeBinding targetType) {
-
- if (this.constant == Constant.NotAConstant)
- return false;
- if (constantType == targetType)
- return true;
- if (constantType.id==targetType.id)
- return true;
- if (constantType.isBaseType() && targetType.isBaseType()) {
- //No free assignment conversion from anything but to integral ones.
- if ((constantType == TypeBinding.INT
- || BaseTypeBinding.isWidening(TypeIds.T_int, constantType.id))
- && (BaseTypeBinding.isNarrowing(targetType.id, TypeIds.T_int))) {
- //use current explicit conversion in order to get some new value to compare with current one
- return isConstantValueRepresentable(this.constant, constantType.id, targetType.id);
- }
- }
- return false;
- }
-
- public boolean isTypeReference() {
- return false;
- }
-
- /**
- * Returns the local variable referenced by this node. Can be a direct reference (SingleNameReference)
- * or thru a cast expression etc...
- */
- public LocalVariableBinding localVariableBinding() {
- return null;
- }
-
-/**
- * Mark this expression as being non null, per a specific tag in the
- * source code.
- */
-// this is no more called for now, waiting for inter procedural null reference analysis
-public void markAsNonNull() {
- this.bits |= ASTNode.IsNonNull;
-}
-
- public int nullStatus(FlowInfo flowInfo) {
-
- if (/* (this.bits & IsNonNull) != 0 || */
- this.constant != null && this.constant != Constant.NotAConstant)
- return FlowInfo.NON_NULL; // constant expression cannot be null
-
- LocalVariableBinding local = localVariableBinding();
- 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;
- }
-
- /**
- * Constant usable for bytecode pattern optimizations, but cannot be inlined
- * since it is not strictly equivalent to the definition of constant expressions.
- * In particular, some side-effects may be required to occur (only the end value
- * is known).
- * @return Constant known to be of boolean type
- */
- public Constant optimizedBooleanConstant() {
- if(this.constant != null)
- 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);
- }
-
- public abstract StringBuffer printExpression(int indent, StringBuffer output);
-
- public StringBuffer printStatement(int indent, StringBuffer output) {
- return print(indent, output).append(";"); //$NON-NLS-1$
- }
-
- public void resolve(BlockScope scope) {
- // drops the returning expression's type whatever the type is.
-
- this.resolveType(scope);
- return;
- }
-
- /**
- * Resolve the type of this expression in the context of a blockScope
- *
- * @param scope
- * @return
- * Return the actual type of this expression after resolution
- */
- public TypeBinding resolveType(BlockScope scope) {
- // by default... subclasses should implement a better TB if required.
- return null;
- }
-
-
- public TypeBinding resolveType(BlockScope scope, boolean define, TypeBinding useType) {
- return resolveType(scope);
- }
-
- /**
- * Resolve the type of this expression in the context of a classScope
- *
- * @param scope
- * @return
- * Return the actual type of this expression after resolution
- */
- public TypeBinding resolveType(ClassScope scope) {
- // by default... subclasses should implement a better TB if required.
- return null;
- }
-
-
- public TypeBinding resolveTypeExpecting(
- BlockScope scope,
- TypeBinding [] expectedTypes) {
-
- this.setExpectedType(expectedTypes[0]); // needed in case of generic method invocation
- TypeBinding expressionType = this.resolveType(scope);
- if (expressionType == null) return null;
-
- for (int i = 0; i < expectedTypes.length; i++) {
- if (expressionType == expectedTypes[i]) return expressionType;
-
- if (expressionType.isCompatibleWith(expectedTypes[i])) {
-// if (scope.isBoxingCompatibleWith(expressionType, expectedType)) {
-// this.computeConversion(scope, expectedType, expressionType);
-// } else {
-// }
- return expressionType;
- }
- }
- scope.problemReporter().typeMismatchError(expressionType, expectedTypes[0], this);
- return null;
- }
-
-
- public TypeBinding resolveTypeExpecting(
- BlockScope scope,
- TypeBinding expectedType) {
-
- this.setExpectedType(expectedType); // needed in case of generic method invocation
- TypeBinding expressionType = this.resolveType(scope);
- if (expressionType == null) return null;
- if (expressionType == expectedType) return expressionType;
-
- if (!expressionType.isCompatibleWith(expectedType)) {
- if (scope.isBoxingCompatibleWith(expressionType, expectedType)) {
- } else {
- if (expectedType!=TypeBinding.BOOLEAN || expressionType==TypeBinding.VOID)
- {
- scope.problemReporter().typeMismatchError(expressionType, expectedType, this);
- return null;
- }
- }
- }
- return expressionType;
- }
-
- /**
- * Returns an object which can be used to identify identical JSR sequence targets
- * (see TryStatement subroutine codegen)
- * or <code>null</null> if not reusable
- */
- public Object reusableJSRTarget() {
- if (this.constant != Constant.NotAConstant)
- return this.constant;
- return null;
- }
-
- /**
- * Record the type expectation before this expression is typechecked.
- * e.g. String s = foo();, foo() will be tagged as being expected of type String
- * Used to trigger proper inference of generic method invocations.
- *
- * @param expectedType
- * The type denoting an expectation in the context of an assignment conversion
- */
- public void setExpectedType(TypeBinding expectedType) {
- // do nothing by default
- }
-
- public void tagAsNeedCheckCast() {
- // do nothing by default
- }
-
- /**
- * Record the fact a cast expression got detected as being unnecessary.
- *
- * @param scope
- * @param castType
- */
- public void tagAsUnnecessaryCast(Scope scope, TypeBinding castType) {
- // do nothing by default
- }
-
- public Expression toTypeReference() {
- //by default undefined
-
- //this method is meanly used by the parser in order to transform
- //an expression that is used as a type reference in a cast ....
- //--appreciate the fact that castExpression and ExpressionWithParenthesis
- //--starts with the same pattern.....
-
- return this;
- }
-
- /**
- * Traverse an expression in the context of a blockScope
- * @param visitor
- * @param scope
- */
- public void traverse(ASTVisitor visitor, BlockScope scope) {
- // nothing to do
- }
-
- /**
- * Traverse an expression in the context of a classScope
- * @param visitor
- * @param scope
- */
- public void traverse(ASTVisitor visitor, ClassScope scope) {
- // nothing to do
- }
-
- public void traverse(ASTVisitor visitior, Scope scope)
- {
- if (scope instanceof BlockScope)
- traverse(visitior,(BlockScope)scope);
- else if (scope instanceof ClassScope)
- traverse(visitior,(ClassScope)scope);
- else if (scope instanceof CompilationUnitScope)
- traverse(visitior,(CompilationUnitScope)scope);
- }
-
- public boolean isPrototype()
- {
- return false;
- }
-
- // is completion or selection node
- public boolean isSpecialNode()
- {
- return false;
- }
-
- public Binding alternateBinding()
- { return null;}
-
- public TypeBinding resolveForAllocation(BlockScope scope, ASTNode location)
- {
- switch (getASTType()) {
- case IASTNode.STRING_LITERAL:
- case IASTNode.CHAR_LITERAL:
- case IASTNode.ARRAY_REFERENCE:
- case IASTNode.FUNCTION_CALL:
-
- break;
-
- default:
- System.out.println("IMPLEMENT resolveForAllocation for "+this.getClass());
- break;
- }
- return this.resolveType(scope);
- }
-
- public int getASTType() {
- return IASTNode.EXPRESSION;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ExtendedStringLiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ExtendedStringLiteral.java
deleted file mode 100644
index f7a04058..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ExtendedStringLiteral.java
+++ /dev/null
@@ -1,62 +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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IExtendedStringLiteral;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-
-public class ExtendedStringLiteral extends StringLiteral implements IExtendedStringLiteral {
-
- /**
- * Build a two-strings literal
- * */
- public ExtendedStringLiteral(StringLiteral str1, StringLiteral str2) {
-
- super(str1.source, str1.sourceStart, str1.sourceEnd, str1.lineNumber);
- extendWith(str2);
- }
-
- /**
- * Add the lit source to mine, just as if it was mine
- */
- public ExtendedStringLiteral extendWith(StringLiteral lit) {
-
- //uddate the source
- int length = source.length;
- System.arraycopy(
- source,
- 0,
- source = new char[length + lit.source.length],
- 0,
- length);
- System.arraycopy(lit.source, 0, source, length, lit.source.length);
- //position at the end of all literals
- sourceEnd = lit.sourceEnd;
- return this;
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output) {
-
- return output.append("ExtendedStringLiteral{").append(source).append('}'); //$NON-NLS-1$
- }
-
- public void traverse(ASTVisitor visitor, BlockScope scope) {
-
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
- }
- public int getASTType() {
- return IASTNode.EXTENDED_STRING_LITERAL;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/FalseLiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/FalseLiteral.java
deleted file mode 100644
index da1ead49..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/FalseLiteral.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IFalseLiteral;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-import org.eclipse.wst.jsdt.internal.compiler.impl.BooleanConstant;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class FalseLiteral extends MagicLiteral implements IFalseLiteral {
- static final char[] source = {'f', 'a', 'l', 's', 'e'};
-public FalseLiteral(int s , int e) {
- super(s,e);
-}
-public void computeConstant() {
- constant = BooleanConstant.fromValue(false);
-}
-public TypeBinding literalType(BlockScope scope) {
- return scope.getJavaLangBoolean();
-}
-/**
- *
- */
-public char[] source() {
- return source;
-}
-public void traverse(ASTVisitor visitor, BlockScope scope) {
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
-}
-public int getASTType() {
- return IASTNode.FALSE_LITERAL;
-
-}
-}
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
deleted file mode 100644
index 57f886bc..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/FieldDeclaration.java
+++ /dev/null
@@ -1,229 +0,0 @@
-/*******************************************************************************
- * 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.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.IFieldDeclaration;
-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.lookup.ArrayBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BaseTypeBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Binding;
-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.MethodScope;
-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;
-
-public class FieldDeclaration extends AbstractVariableDeclaration implements IFieldDeclaration {
-
- public FieldBinding binding;
-// 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
- // - 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);
- }
- }
- }
-
- if (this.initialization != null) {
- flowInfo =
- this.initialization
- .analyseCode(initializationScope, flowContext, flowInfo)
- .unconditionalInits();
- flowInfo.markAsDefinitelyAssigned(this.binding);
- }
- 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);
- }
- return super.printStatement(indent, output);
-}
-
-public void resolve(MethodScope initializationScope) {
- // the two <constant = Constant.NotAConstant> 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
- if (existingVariable instanceof FieldBinding) {
- FieldBinding existingField = (FieldBinding) existingVariable;
- if (existingField.original() == this.binding) break checkHidingSuperField; // keep checking outer scenario
- }
- // 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 /*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;
-
-// resolveAnnotations(initializationScope, this.annotations, this.binding);
- // the resolution of the initialization hasn't been done
- if (this.initialization != null) {
-
- TypeBinding fieldType = this.binding.type;
- TypeBinding initializationType;
- this.initialization.setExpectedType(fieldType); // needed in case of generic method invocation
- 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);
- }
- }
- // 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) {
- /*
- if (classScope != null) {
- this.javadoc.resolve(classScope);
- }
- */
- 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;
- }
-}
-
-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);
- }
- visitor.endVisit(this, scope);
-}
-public int getASTType() {
- return IASTNode.FIELD_DECLARATION;
-
-}
-public IExpression getInitialization()
-{
- return this.initialization;
-}
-}
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
deleted file mode 100644
index 0b00db60..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/FieldReference.java
+++ /dev/null
@@ -1,578 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.ast;
-
-import java.util.ArrayList;
-
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-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.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.InvocationSite;
-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.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.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
-
- public long nameSourcePosition; //(start<<32)+end
- 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);
- }
- flowInfo =
- receiver
- .analyseCode(currentScope, flowContext, flowInfo, binding==null || !binding.isStatic())
- .unconditionalInits();
- if (assignment.expression != null) {
- flowInfo =
- assignment
- .expression
- .analyseCode(currentScope, flowContext, flowInfo)
- .unconditionalInits();
- }
- 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, boolean valueRequired) {
- boolean nonStatic = binding==null || !binding.isStatic();
- receiver.analyseCode(currentScope, flowContext, flowInfo, nonStatic);
- if (nonStatic) {
- receiver.checkNPE(currentScope, flowContext, flowInfo);
- }
-
- if (valueRequired || currentScope.compilerOptions().complianceLevel >= ClassFileConstants.JDK1_4) {
- manageSyntheticAccessIfNecessary(currentScope, flowInfo, true /*read-access*/);
- }
- 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();
- }
-}
-
-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;
- }
-}
-
-/**
- * @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 :
- }
- if ((this.implicitConversion & BOXING) != 0) {
- convertedType = scope.environment().computeBoxingType(convertedType);
- }
- return convertedType;
-}
-
-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
-
- //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;
-// }
-
-
- /*
- * 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;
- }
- 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*/);
- 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;
- return this.typeBinding;
- }
- else
- {
- this.binding=new ProblemFieldBinding(null,this.token,ProblemReasons.NotFound);
- constant = Constant.NotAConstant;
- 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;
- 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;
- }
- 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 (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 (!isImplicitThisRcv
- && fieldBinding.declaringClass != receiverType
- && fieldBinding.declaringClass.canBeSeenBy(scope)) {
- scope.problemReporter().indirectAccessToStaticField(this, fieldBinding);
- }
- } else {
- if(receiverIsType)
- scope.problemReporter().staticFieldAccessToNonStaticVariable(this, fieldBinding);
- }
- // perform capture conversion if read access
- return this.resolvedType = fieldBinding.type;
- }
- else if( memberBinding instanceof MethodBinding ){
- MethodBinding methodBinding=(MethodBinding) memberBinding;
-
- 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= 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 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 traverse(ASTVisitor visitor, BlockScope scope) {
- if (visitor.visit(this, scope)) {
- receiver.traverse(visitor, 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, '.'));
- }
- 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;
-}
-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);
- }
- else
- return null;
- }
- return (char [][])list.toArray(new char[list.size()][]);
-}
-
-public IExpression getReceiver() {
- return receiver;
-}
-
-public char[] getToken() {
- return token;
-}
-
-public boolean isTypeReference() {
- return (this.bits & Binding.TYPE) ==Binding.TYPE;
-}
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ForInStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ForInStatement.java
deleted file mode 100644
index 68338685..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ForInStatement.java
+++ /dev/null
@@ -1,209 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IForInStatement;
-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.flow.LoopingFlowContext;
-import org.eclipse.wst.jsdt.internal.compiler.flow.UnconditionalFlowInfo;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.LocalVariableBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class ForInStatement extends Statement implements IForInStatement {
-
- public Statement iterationVariable;
- public Expression collection;
- public Statement action;
-
- //when there is no local declaration, there is no need of a new scope
- //scope is positionned either to a new scope, or to the "upper"scope (see resolveType)
- public boolean neededScope;
- public BlockScope scope;
-
-
- // for local variables table attributes
- int preCondInitStateIndex = -1;
- int condIfTrueInitStateIndex = -1;
- int mergedInitStateIndex = -1;
-
- public ForInStatement(
- Statement iterationVariable,
- Expression collection,
- Statement action,
- boolean neededScope,
- int s,
- int e) {
-
- this.sourceStart = s;
- this.sourceEnd = e;
- this.iterationVariable = iterationVariable;
- this.collection = collection;
- this.action = action;
- // remember useful empty statement
- if (action instanceof EmptyStatement) action.bits |= IsUsefulEmptyStatement;
- this.neededScope = neededScope;
- }
-
- public FlowInfo analyseCode(
- BlockScope currentScope,
- FlowContext flowContext,
- FlowInfo flowInfo) {
-
-
- // process the element variable and collection
- this.collection.checkNPE(currentScope, flowContext, flowInfo);
- flowInfo = this.iterationVariable.analyseCode(scope, flowContext, flowInfo);
- FlowInfo condInfo = this.collection.analyseCode(scope, flowContext, flowInfo.copy());
-
- LocalVariableBinding iterationVariableBinding=null;
- if (this.iterationVariable instanceof LocalDeclaration)
- iterationVariableBinding=((LocalDeclaration)this.iterationVariable).binding;
- else if (this.iterationVariable instanceof SingleNameReference)
- {
- SingleNameReference singleNameReference =(SingleNameReference)this.iterationVariable;
- if (singleNameReference.binding instanceof LocalVariableBinding)
- iterationVariableBinding=(LocalVariableBinding)singleNameReference.binding;
- }
-
-
- // element variable will be assigned when iterating
- if (iterationVariableBinding!=null)
- condInfo.markAsDefinitelyAssigned(iterationVariableBinding);
-
-// this.postCollectionInitStateIndex = currentScope.methodScope().recordInitializationStates(condInfo);
-
- // process the action
- LoopingFlowContext loopingContext =
- new LoopingFlowContext(flowContext, flowInfo, this, scope);
- UnconditionalFlowInfo actionInfo =
- condInfo.nullInfoLessUnconditionalCopy();
- if (iterationVariableBinding!=null)
- actionInfo.markAsDefinitelyUnknown(iterationVariableBinding);
- FlowInfo exitBranch;
- if (!(action == null || (action.isEmptyBlock()
- && currentScope.compilerOptions().complianceLevel <= ClassFileConstants.JDK1_3))) {
-
- if (!this.action.complainIfUnreachable(actionInfo, scope, false)) {
- actionInfo = action.
- analyseCode(scope, loopingContext, actionInfo).
- unconditionalCopy();
- }
-
- // code generation can be optimized when no need to continue in the loop
- exitBranch = flowInfo.unconditionalCopy().
- addInitializationsFrom(condInfo.initsWhenFalse());
- // TODO (maxime) no need to test when false: can optimize (same for action being unreachable above)
- if ((actionInfo.tagBits & loopingContext.initsOnContinue.tagBits &
- FlowInfo.UNREACHABLE) != 0) {
- } else {
- actionInfo = actionInfo.mergedWith(loopingContext.initsOnContinue);
- exitBranch.addPotentialInitializationsFrom(actionInfo);
- }
- } else {
- exitBranch = condInfo.initsWhenFalse();
- }
-
- // we need the variable to iterate the collection even if the
- // element variable is not used
-// final boolean hasEmptyAction = this.action == null
-// || this.action.isEmptyBlock()
-// || ((this.action.bits & IsUsefulEmptyStatement) != 0);
-
-
- //end of loop
- loopingContext.complainOnDeferredNullChecks(currentScope, actionInfo);
-
- FlowInfo mergedInfo = FlowInfo.mergedOptimizedBranches(
- (loopingContext.initsOnBreak.tagBits &
- FlowInfo.UNREACHABLE) != 0 ?
- loopingContext.initsOnBreak :
- flowInfo.addInitializationsFrom(loopingContext.initsOnBreak), // recover upstream null info
- false,
- exitBranch,
- false,
- true /*for(;;){}while(true); unreachable(); */);
-// mergedInitStateIndex = currentScope.methodScope().recordInitializationStates(mergedInfo);
- return mergedInfo;
- }
-
- public StringBuffer printStatement(int tab, StringBuffer output) {
-
- printIndent(tab, output).append("for ("); //$NON-NLS-1$
- //inits
- if (iterationVariable != null) {
- if (iterationVariable instanceof AbstractVariableDeclaration) {
- AbstractVariableDeclaration variable = (AbstractVariableDeclaration) iterationVariable;
- variable.printAsExpression(0, output);
- }
- else
- iterationVariable.print(0, output);
- }
- output.append(" in "); //$NON-NLS-1$
- //cond
- if (collection != null) collection.printExpression(0, output);
- output.append(") "); //$NON-NLS-1$
- //block
- if (action == null)
- output.append(';');
- else {
- output.append('\n');
- action.printStatement(tab + 1, output);
- }
- return output;
- }
-
- public void resolve(BlockScope upperScope) {
-
- // use the scope that will hold the init declarations
- scope = neededScope ? new BlockScope(upperScope) : upperScope;
- if (iterationVariable != null)
- {
- if (iterationVariable instanceof Expression) {
- Expression expression = (Expression) iterationVariable;
- expression.resolveType(scope, true, null);
-// TODO: show a warning message here saying this var is at global scope
- }
- else
- iterationVariable.resolve(scope);
- }
- if (collection != null) {
- TypeBinding type = collection.resolveTypeExpecting(scope, TypeBinding.BOOLEAN);
- }
- if (action != null)
- action.resolve(scope);
- }
-
- public void traverse(ASTVisitor visitor, BlockScope blockScope) {
- BlockScope visitScope = (this.scope != null) ? this.scope : blockScope;
- if (visitor.visit(this, blockScope)) {
- if (iterationVariable != null) {
- iterationVariable.traverse(visitor, visitScope);
- }
-
- if (collection != null)
- collection.traverse(visitor, visitScope);
-
- if (action != null)
- action.traverse(visitor, visitScope);
- }
- visitor.endVisit(this, blockScope);
- }
-
- public int getASTType() {
- return IASTNode.FOR_IN_STATEMENT;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ForStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ForStatement.java
deleted file mode 100644
index cac0bf81..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ForStatement.java
+++ /dev/null
@@ -1,304 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IForStatement;
-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.flow.LoopingFlowContext;
-import org.eclipse.wst.jsdt.internal.compiler.flow.UnconditionalFlowInfo;
-import org.eclipse.wst.jsdt.internal.compiler.impl.Constant;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.CompilationUnitScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.LocalVariableBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class ForStatement extends Statement implements IForStatement {
-
- public Statement[] initializations;
- public Expression condition;
- public Statement[] increments;
- public Statement action;
-
- //when there is no local declaration, there is no need of a new scope
- //scope is positionned either to a new scope, or to the "upper"scope (see resolveType)
- public boolean neededScope;
- public BlockScope scope;
-
-
- // for local variables table attributes
- int preCondInitStateIndex = -1;
- int preIncrementsInitStateIndex = -1;
- int condIfTrueInitStateIndex = -1;
- int mergedInitStateIndex = -1;
-
- public ForStatement(
- Statement[] initializations,
- Expression condition,
- Statement[] increments,
- Statement action,
- boolean neededScope,
- int s,
- int e) {
-
- this.sourceStart = s;
- this.sourceEnd = e;
- this.initializations = initializations;
- this.condition = condition;
- this.increments = increments;
- this.action = action;
- // remember useful empty statement
- if (action instanceof EmptyStatement) action.bits |= IsUsefulEmptyStatement;
- this.neededScope = neededScope;
- }
-
- public FlowInfo analyseCode(
- BlockScope currentScope,
- FlowContext flowContext,
- FlowInfo flowInfo) {
-
-
-
- boolean isContinue=true;
-
- // process the initializations
- if (initializations != null) {
- for (int i = 0, count = initializations.length; i < count; i++) {
- flowInfo = initializations[i].analyseCode(scope, flowContext, flowInfo);
- }
- }
-// preCondInitStateIndex =
-// currentScope.methodScope().recordInitializationStates(flowInfo);
-
- Constant cst = this.condition == null ? null : this.condition.constant;
- boolean isConditionTrue = cst == null || (cst != Constant.NotAConstant && cst.booleanValue() == true);
- boolean isConditionFalse = cst != null && (cst != Constant.NotAConstant && cst.booleanValue() == false);
-
- cst = this.condition == null ? null : this.condition.optimizedBooleanConstant();
- boolean isConditionOptimizedTrue = cst == null || (cst != Constant.NotAConstant && cst.booleanValue() == true);
- boolean isConditionOptimizedFalse = cst != null && (cst != Constant.NotAConstant && cst.booleanValue() == false);
-
-
-
- // process the condition
- LoopingFlowContext condLoopContext = null;
- FlowInfo condInfo = flowInfo.nullInfoLessUnconditionalCopy();
- if (condition != null) {
- if (!isConditionTrue) {
- condInfo =
- condition.analyseCode(
- scope,
- (condLoopContext =
- new LoopingFlowContext(flowContext, flowInfo, this, scope)),
- condInfo);
- }
- }
-
- // process the action
- LoopingFlowContext loopingContext;
- UnconditionalFlowInfo actionInfo;
- if (action == null
- || (action.isEmptyBlock() && currentScope.compilerOptions().complianceLevel <= ClassFileConstants.JDK1_3)) {
- if (isConditionTrue) {
- if (condLoopContext != null) {
- condLoopContext.complainOnDeferredNullChecks(currentScope,
- condInfo);
- }
- return FlowInfo.DEAD_END;
- } else {
- if (isConditionFalse){
- isContinue=false; // for(;false;p());
- }
- actionInfo = condInfo.initsWhenTrue().unconditionalCopy();
- loopingContext =
- new LoopingFlowContext(flowContext, flowInfo, this, scope);
- }
- }
- else {
- loopingContext =
- new LoopingFlowContext(flowContext, flowInfo, this, scope);
- FlowInfo initsWhenTrue = condInfo.initsWhenTrue();
-// condIfTrueInitStateIndex =
-// currentScope.methodScope().recordInitializationStates(initsWhenTrue);
-
- if (isConditionFalse) {
- actionInfo = FlowInfo.DEAD_END;
- } else {
- actionInfo = initsWhenTrue.unconditionalCopy();
- if (isConditionOptimizedFalse){
- actionInfo.setReachMode(FlowInfo.UNREACHABLE);
- }
- }
- if (!this.action.complainIfUnreachable(actionInfo, scope, false)) {
- actionInfo = action.analyseCode(scope, loopingContext, actionInfo).
- unconditionalInits();
- }
-
- // code generation can be optimized when no need to continue in the loop
- if ((actionInfo.tagBits &
- loopingContext.initsOnContinue.tagBits &
- FlowInfo.UNREACHABLE) != 0) {
- isContinue=false;
- }
- else {
- actionInfo = actionInfo.mergedWith(loopingContext.initsOnContinue);
- }
- }
- // for increments
- FlowInfo exitBranch = flowInfo.copy();
- // recover null inits from before condition analysis
- LoopingFlowContext incrementContext = null;
- if (isContinue) {
- if (increments != null) {
- incrementContext =
- new LoopingFlowContext(flowContext, flowInfo, this, scope);
- FlowInfo incrementInfo = actionInfo;
-// this.preIncrementsInitStateIndex =
-// currentScope.methodScope().recordInitializationStates(incrementInfo);
- for (int i = 0, count = increments.length; i < count; i++) {
- incrementInfo = increments[i].
- analyseCode(scope, incrementContext, incrementInfo);
- }
- actionInfo = incrementInfo.unconditionalInits();
- }
- exitBranch.addPotentialInitializationsFrom(actionInfo).
- addInitializationsFrom(condInfo.initsWhenFalse());
- }
- else {
- exitBranch.addInitializationsFrom(condInfo.initsWhenFalse());
- }
- // nulls checks
- if (condLoopContext != null) {
- condLoopContext.complainOnDeferredNullChecks(currentScope,
- actionInfo);
- }
- loopingContext.complainOnDeferredNullChecks(currentScope,
- actionInfo);
- if (incrementContext != null) {
- incrementContext.complainOnDeferredNullChecks(currentScope,
- actionInfo);
- }
-
- //end of loop
- FlowInfo mergedInfo = FlowInfo.mergedOptimizedBranches(
- (loopingContext.initsOnBreak.tagBits &
- FlowInfo.UNREACHABLE) != 0 ?
- loopingContext.initsOnBreak :
- flowInfo.addInitializationsFrom(loopingContext.initsOnBreak), // recover upstream null info
- isConditionOptimizedTrue,
- exitBranch,
- isConditionOptimizedFalse,
- !isConditionTrue /*for(;;){}while(true); unreachable(); */);
-// mergedInitStateIndex = currentScope.methodScope().recordInitializationStates(mergedInfo);
- return mergedInfo;
- }
-
- public StringBuffer printStatement(int tab, StringBuffer output) {
-
- printIndent(tab, output).append("for ("); //$NON-NLS-1$
- //inits
- if (initializations != null) {
- for (int i = 0; i < initializations.length; i++) {
- //nice only with expressions
- if (i > 0) output.append(", "); //$NON-NLS-1$
- initializations[i].print(0, output);
- }
- }
- output.append("; "); //$NON-NLS-1$
- //cond
- if (condition != null) condition.printExpression(0, output);
- output.append("; "); //$NON-NLS-1$
- //updates
- if (increments != null) {
- for (int i = 0; i < increments.length; i++) {
- if (i > 0) output.append(", "); //$NON-NLS-1$
- increments[i].print(0, output);
- }
- }
- output.append(") "); //$NON-NLS-1$
- //block
- if (action == null)
- output.append(';');
- else {
- output.append('\n');
- action.printStatement(tab + 1, output);
- }
- return output;
- }
-
- public void resolve(BlockScope upperScope) {
-
- // use the scope that will hold the init declarations
- scope = neededScope ? new BlockScope(upperScope) : upperScope;
- if (initializations != null)
- for (int i = 0, length = initializations.length; i < length; i++) {
- initializations[i].resolve(scope);
- /* START -------------------------------- Bug 197884 Loosly defined var (for statement) and optional semi-colon --------------------- */
- /* check where for variable exists in scope chain, report error if not local */
- if(initializations[i] instanceof Assignment ) {
- Assignment as = ((Assignment)initializations[i]);
- if (as.getLeftHandSide() instanceof SingleNameReference)
- {
- LocalVariableBinding bind1 = as.localVariableBinding();
- if(bind1==null || bind1.declaringScope instanceof CompilationUnitScope){
- upperScope.problemReporter().looseVariableDecleration(this, as);
- }
- }
- }
-
-
- }
- /* END -------------------------------- Bug 197884 Loosly defined var (for statement) and optional semi-colon --------------------- */
-
- if (condition != null) {
- TypeBinding type = condition.resolveTypeExpecting(scope, TypeBinding.BOOLEAN);
- }
- if (increments != null)
- for (int i = 0, length = increments.length; i < length; i++)
- increments[i].resolve(scope);
- if (action != null)
- action.resolve(scope);
- }
-
- public void traverse(
- ASTVisitor visitor,
- BlockScope blockScope) {
-
- BlockScope visitScope= (this.scope!=null)?this.scope :blockScope;
- if (visitor.visit(this, blockScope)) {
- if (initializations != null) {
- int initializationsLength = initializations.length;
- for (int i = 0; i < initializationsLength; i++)
- initializations[i].traverse(visitor, visitScope);
- }
-
- if (condition != null)
- condition.traverse(visitor, visitScope);
-
- if (increments != null) {
- int incrementsLength = increments.length;
- for (int i = 0; i < incrementsLength; i++)
- increments[i].traverse(visitor, visitScope);
- }
-
- if (action != null)
- action.traverse(visitor, visitScope);
- }
- visitor.endVisit(this, blockScope);
- }
- public int getASTType() {
- return IASTNode.FOR_STATEMENT;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ForeachStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ForeachStatement.java
deleted file mode 100644
index c952e0fa..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ForeachStatement.java
+++ /dev/null
@@ -1,258 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IForeachStatement;
-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.flow.LoopingFlowContext;
-import org.eclipse.wst.jsdt.internal.compiler.flow.UnconditionalFlowInfo;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ArrayBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.LocalVariableBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class ForeachStatement extends Statement implements IForeachStatement {
-
- public LocalDeclaration elementVariable;
- public int elementVariableImplicitWidening = -1;
- public Expression collection;
- public Statement action;
-
- // set the kind of foreach
- private int kind;
- // possible kinds of iterating behavior
- private static final int ARRAY = 0;
- private static final int RAW_ITERABLE = 1;
- private static final int GENERIC_ITERABLE = 2;
-
- private TypeBinding iteratorReceiverType;
- private TypeBinding collectionElementType;
-
-
- public BlockScope scope;
-
- // secret variables for codegen
- public LocalVariableBinding indexVariable;
- public LocalVariableBinding collectionVariable; // to store the collection expression value
- public LocalVariableBinding maxVariable;
- // secret variable names
- private static final char[] SecretIndexVariableName = " index".toCharArray(); //$NON-NLS-1$
- private static final char[] SecretCollectionVariableName = " collection".toCharArray(); //$NON-NLS-1$
- private static final char[] SecretMaxVariableName = " max".toCharArray(); //$NON-NLS-1$
-
- int postCollectionInitStateIndex = -1;
- int mergedInitStateIndex = -1;
-
- public ForeachStatement(
- LocalDeclaration elementVariable,
- int start) {
-
- this.elementVariable = elementVariable;
- this.sourceStart = start;
- this.kind = -1;
- }
-
- public FlowInfo analyseCode(
- BlockScope currentScope,
- FlowContext flowContext,
- FlowInfo flowInfo) {
- // initialize break and continue labels
- boolean isContinue=true;
-
- // process the element variable and collection
- this.collection.checkNPE(currentScope, flowContext, flowInfo);
- flowInfo = this.elementVariable.analyseCode(scope, flowContext, flowInfo);
- FlowInfo condInfo = this.collection.analyseCode(scope, flowContext, flowInfo.copy());
-
- // element variable will be assigned when iterating
- condInfo.markAsDefinitelyAssigned(this.elementVariable.binding);
-
-// this.postCollectionInitStateIndex = currentScope.methodScope().recordInitializationStates(condInfo);
-
- // process the action
- LoopingFlowContext loopingContext =
- new LoopingFlowContext(flowContext, flowInfo, this, scope);
- UnconditionalFlowInfo actionInfo =
- condInfo.nullInfoLessUnconditionalCopy();
- actionInfo.markAsDefinitelyUnknown(this.elementVariable.binding);
- FlowInfo exitBranch;
- if (!(action == null || (action.isEmptyBlock()
- && currentScope.compilerOptions().complianceLevel <= ClassFileConstants.JDK1_3))) {
-
- if (!this.action.complainIfUnreachable(actionInfo, scope, false)) {
- actionInfo = action.
- analyseCode(scope, loopingContext, actionInfo).
- unconditionalCopy();
- }
-
- // code generation can be optimized when no need to continue in the loop
- exitBranch = flowInfo.unconditionalCopy().
- addInitializationsFrom(condInfo.initsWhenFalse());
- // TODO (maxime) no need to test when false: can optimize (same for action being unreachable above)
- if ((actionInfo.tagBits & loopingContext.initsOnContinue.tagBits &
- FlowInfo.UNREACHABLE) != 0) {
- isContinue = false;
- } else {
- actionInfo = actionInfo.mergedWith(loopingContext.initsOnContinue);
- exitBranch.addPotentialInitializationsFrom(actionInfo);
- }
- } else {
- exitBranch = condInfo.initsWhenFalse();
- }
-
- // we need the variable to iterate the collection even if the
- // element variable is not used
- final boolean hasEmptyAction = this.action == null
- || this.action.isEmptyBlock()
- || ((this.action.bits & IsUsefulEmptyStatement) != 0);
-
- switch(this.kind) {
- case ARRAY :
- if (!hasEmptyAction
- || this.elementVariable.binding.resolvedPosition != -1) {
- this.collectionVariable.useFlag = LocalVariableBinding.USED;
- if (isContinue) {
- this.indexVariable.useFlag = LocalVariableBinding.USED;
- this.maxVariable.useFlag = LocalVariableBinding.USED;
- }
- }
- break;
- case RAW_ITERABLE :
- case GENERIC_ITERABLE :
- this.indexVariable.useFlag = LocalVariableBinding.USED;
- break;
- }
- //end of loop
- loopingContext.complainOnDeferredNullChecks(currentScope, actionInfo);
-
- FlowInfo mergedInfo = FlowInfo.mergedOptimizedBranches(
- (loopingContext.initsOnBreak.tagBits &
- FlowInfo.UNREACHABLE) != 0 ?
- loopingContext.initsOnBreak :
- flowInfo.addInitializationsFrom(loopingContext.initsOnBreak), // recover upstream null info
- false,
- exitBranch,
- false,
- true /*for(;;){}while(true); unreachable(); */);
-// mergedInitStateIndex = currentScope.methodScope().recordInitializationStates(mergedInfo);
- return mergedInfo;
- }
-
- public StringBuffer printStatement(int indent, StringBuffer output) {
-
- printIndent(indent, output).append("for ("); //$NON-NLS-1$
- this.elementVariable.printAsExpression(0, output);
- output.append(" : ");//$NON-NLS-1$
- this.collection.print(0, output).append(") "); //$NON-NLS-1$
- //block
- if (this.action == null) {
- output.append(';');
- } else {
- output.append('\n');
- this.action.printStatement(indent + 1, output);
- }
- return output;
- }
-
- public void resolve(BlockScope upperScope) {
- // use the scope that will hold the init declarations
- scope = new BlockScope(upperScope);
- this.elementVariable.resolve(scope); // collection expression can see itemVariable
- TypeBinding elementType = this.elementVariable.type.resolvedType;
- TypeBinding collectionType = this.collection == null ? null : this.collection.resolveType(scope);
-
- if (elementType != null && collectionType != null) {
- if (collectionType.isArrayType()) { // for(E e : E[])
- this.kind = ARRAY;
- this.collectionElementType = ((ArrayBinding) collectionType).elementsType();
- // in case we need to do a conversion
- int compileTimeTypeID = collectionElementType.id;
- if (elementType.isBaseType()) {
- if (!collectionElementType.isBaseType()) {
- compileTimeTypeID = scope.environment().computeBoxingType(collectionElementType).id;
- this.elementVariableImplicitWidening = UNBOXING;
- if (elementType.isBaseType()) {
- this.elementVariableImplicitWidening |= (elementType.id << 4) + compileTimeTypeID;
- }
- } else {
- this.elementVariableImplicitWidening = (elementType.id << 4) + compileTimeTypeID;
- }
- } else {
- if (collectionElementType.isBaseType()) {
- int boxedID = scope.environment().computeBoxingType(collectionElementType).id;
- this.elementVariableImplicitWidening = BOXING | (compileTimeTypeID << 4) | compileTimeTypeID; // use primitive type in implicit conversion
- compileTimeTypeID = boxedID;
- }
- }
- } else if (collectionType instanceof ReferenceBinding) {
- ReferenceBinding iterableType = ((ReferenceBinding)collectionType).findSuperTypeErasingTo(T_JavaLangIterable, false /*Iterable is not a class*/);
- checkIterable: {
- if (iterableType == null) break checkIterable;
-
- this.iteratorReceiverType = collectionType;
- if (((ReferenceBinding)iteratorReceiverType).findSuperTypeErasingTo(T_JavaLangIterable, false) == null) {
- this.iteratorReceiverType = iterableType; // handle indirect inheritance thru variable secondary bound
- }
-
-
- break checkIterable;
- }
- }
- switch(this.kind) {
- case ARRAY :
- // allocate #index secret variable (of type int)
- this.indexVariable = new LocalVariableBinding(SecretIndexVariableName, TypeBinding.INT, ClassFileConstants.AccDefault, false);
- scope.addLocalVariable(this.indexVariable);
-
- // allocate #max secret variable
- this.maxVariable = new LocalVariableBinding(SecretMaxVariableName, TypeBinding.INT, ClassFileConstants.AccDefault, false);
- scope.addLocalVariable(this.maxVariable);
- // add #array secret variable (of collection type)
- this.collectionVariable = new LocalVariableBinding(SecretCollectionVariableName, collectionType, ClassFileConstants.AccDefault, false);
- scope.addLocalVariable(this.collectionVariable);
- break;
- case RAW_ITERABLE :
- case GENERIC_ITERABLE :
-// // allocate #index secret variable (of type Iterator)
-// this.indexVariable = new LocalVariableBinding(SecretIndexVariableName, scope.getJavaUtilIterator(), ClassFileConstants.AccDefault, false);
-// scope.addLocalVariable(this.indexVariable);
-// this.indexVariable.setConstant(Constant.NotAConstant); // not inlinable
- break;
- }
- }
- if (action != null) {
- action.resolve(scope);
- }
- }
-
- public void traverse(
- ASTVisitor visitor,
- BlockScope blockScope) {
-
- if (visitor.visit(this, blockScope)) {
- this.elementVariable.traverse(visitor, scope);
- this.collection.traverse(visitor, scope);
- if (action != null) {
- action.traverse(visitor, scope);
- }
- }
- visitor.endVisit(this, blockScope);
- }
- public int getASTType() {
- return IASTNode.FOR_EACH_STATEMENT;
-
- }
-}
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
deleted file mode 100644
index 66ddc9bc..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/FunctionExpression.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*******************************************************************************
- * 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.internal.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IFunctionExpression;
-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;
-import org.eclipse.wst.jsdt.internal.compiler.impl.Constant;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class FunctionExpression extends Expression implements IFunctionExpression {
-
-
- public MethodDeclaration methodDeclaration;
-
- public void setMethodDeclaration(MethodDeclaration methodDeclaration) {
- this.methodDeclaration = methodDeclaration;
- }
-
- public MethodDeclaration getMethodDeclaration() {
- return this.methodDeclaration;
- }
-
-
- public FunctionExpression(MethodDeclaration methodDeclaration)
- {
- this.methodDeclaration=methodDeclaration;
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output) {
- return methodDeclaration.print(indent, output);
- }
-
- public void traverse(ASTVisitor visitor, BlockScope scope) {
- if (visitor.visit(this, scope))
- methodDeclaration.traverse(visitor, scope);
- }
-
-
- 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.resolve(scope);
- return this.methodDeclaration.binding.functionTypeBinding;
- }
-
- public TypeBinding resolveForAllocation(BlockScope scope, ASTNode location) {
- return this.resolveType(scope);
- }
-
- public int nullStatus(FlowInfo flowInfo) {
- return FlowInfo.NON_NULL; // constant expression cannot be null
- }
-
- public FlowInfo analyseCode(
- BlockScope classScope,
- FlowContext initializationContext,
- FlowInfo flowInfo) {
- this.methodDeclaration.analyseCode(classScope, initializationContext, flowInfo.copy());
- return flowInfo;
- }
- public int getASTType() {
- return IASTNode.FUNCTION_EXPRESSION;
-
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/IfStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/IfStatement.java
deleted file mode 100644
index b228f847..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/IfStatement.java
+++ /dev/null
@@ -1,213 +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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IIfStatement;
-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;
-import org.eclipse.wst.jsdt.internal.compiler.impl.Constant;
-import org.eclipse.wst.jsdt.internal.compiler.impl.StringConstant;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.LocalVariableBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class IfStatement extends Statement implements IIfStatement {
-
- //this class represents the case of only one statement in
- //either else and/or then branches.
-
- public Expression condition;
- public Statement thenStatement;
- public Statement elseStatement;
-
- boolean thenExit;
-
- // for local variables table attributes
- int thenInitStateIndex = -1;
- int elseInitStateIndex = -1;
- int mergedInitStateIndex = -1;
-
- public IfStatement(Expression condition, Statement thenStatement, int sourceStart, int sourceEnd) {
-
- this.condition = condition;
- this.thenStatement = thenStatement;
- // remember useful empty statement
- if (thenStatement instanceof EmptyStatement) thenStatement.bits |= IsUsefulEmptyStatement;
- this.sourceStart = sourceStart;
- this.sourceEnd = sourceEnd;
- }
-
- public IfStatement(Expression condition, Statement thenStatement, Statement elseStatement, int sourceStart, int sourceEnd) {
-
- this.condition = condition;
- this.thenStatement = thenStatement;
- // remember useful empty statement
- if (thenStatement instanceof EmptyStatement) thenStatement.bits |= IsUsefulEmptyStatement;
- this.elseStatement = elseStatement;
- if (elseStatement instanceof IfStatement) elseStatement.bits |= IsElseIfStatement;
- if (elseStatement instanceof EmptyStatement) elseStatement.bits |= IsUsefulEmptyStatement;
- this.sourceStart = sourceStart;
- this.sourceEnd = sourceEnd;
- }
-
- public FlowInfo analyseCode(
- BlockScope currentScope,
- FlowContext flowContext,
- FlowInfo flowInfo) {
-
- // process the condition
- FlowInfo conditionFlowInfo =
- condition.analyseCode(currentScope, flowContext, flowInfo);
-
- Constant cst = this.condition.optimizedBooleanConstant();
- boolean isConditionOptimizedTrue = cst != Constant.NotAConstant && cst.booleanValue() == true;
- boolean isConditionOptimizedFalse = cst != Constant.NotAConstant && cst.booleanValue() == false;
-
- // process the THEN part
- FlowInfo thenFlowInfo = conditionFlowInfo.safeInitsWhenTrue();
- if (isConditionOptimizedFalse) {
- thenFlowInfo.setReachMode(FlowInfo.UNREACHABLE);
- }
- FlowInfo elseFlowInfo = conditionFlowInfo.initsWhenFalse();
- if (isConditionOptimizedTrue) {
- elseFlowInfo.setReachMode(FlowInfo.UNREACHABLE);
- }
- if (this.thenStatement != null) {
- // Save info for code gen
-// thenInitStateIndex =
-// currentScope.methodScope().recordInitializationStates(thenFlowInfo);
- if (!thenStatement.complainIfUnreachable(thenFlowInfo, currentScope, false)) {
- thenFlowInfo =
- thenStatement.analyseCode(currentScope, flowContext, thenFlowInfo);
- }
- }
- // code gen: optimizing the jump around the ELSE part
- this.thenExit = (thenFlowInfo.tagBits & FlowInfo.UNREACHABLE) != 0;
-
- // process the ELSE part
- if (this.elseStatement != null) {
- // signal else clause unnecessarily nested, tolerate else-if code pattern
- if (thenFlowInfo == FlowInfo.DEAD_END
- && (this.bits & IsElseIfStatement) == 0 // else of an else-if
- && !(this.elseStatement instanceof IfStatement)) {
- currentScope.problemReporter().unnecessaryElse(this.elseStatement);
- }
- // Save info for code gen
-// elseInitStateIndex =
-// currentScope.methodScope().recordInitializationStates(elseFlowInfo);
- if (!elseStatement.complainIfUnreachable(elseFlowInfo, currentScope, false)) {
- elseFlowInfo =
- elseStatement.analyseCode(currentScope, flowContext, elseFlowInfo);
- }
- }
-
- // handle cases where condition is "typeof something== ''", set inits accordingly
- if (this.condition instanceof EqualExpression)
- {
- EqualExpression equalExpression =(EqualExpression) this.condition;
- int operator=(equalExpression.bits & OperatorMASK) >> OperatorSHIFT;
- if (operator==OperatorIds.EQUAL_EQUAL || operator==OperatorIds.NOT_EQUAL)
- {
-
- boolean isDefined[]={false};
- SingleNameReference snr=getTypeofExpressionVar(equalExpression.left,equalExpression.right,isDefined);
- if (snr==null)
- snr=getTypeofExpressionVar(equalExpression.right, equalExpression.left,isDefined);
- if (snr!=null)
- {
- LocalVariableBinding local = snr.localVariableBinding();
- if (local==null)
- snr.resolveType(currentScope, true,null);
- local = snr.localVariableBinding();
- if (local!=null)
- {
- if (isDefined[0])
- thenFlowInfo.markAsDefinitelyAssigned(local);
- else
- elseFlowInfo.markAsDefinitelyAssigned(local);
- }
- }
-
-
- }
- }
-
- // merge THEN & ELSE initializations
- FlowInfo mergedInfo = FlowInfo.mergedOptimizedBranches(
- thenFlowInfo,
- isConditionOptimizedTrue,
- elseFlowInfo,
- isConditionOptimizedFalse,
- true /*if(true){ return; } fake-reachable(); */);
-// mergedInitStateIndex = currentScope.methodScope().recordInitializationStates(mergedInfo);
- return mergedInfo;
- }
-
- private SingleNameReference getTypeofExpressionVar(Expression expression1,Expression expression2,boolean isDefined[])
- {
- if (expression1 instanceof UnaryExpression && expression2.constant instanceof StringConstant)
- {
- UnaryExpression unaryExpression = (UnaryExpression)expression1;
- if ( unaryExpression.expression instanceof SingleNameReference &&
- (((unaryExpression.bits & OperatorMASK) >> OperatorSHIFT)==OperatorIds.TYPEOF)
- )
- {
- isDefined[0]=!((StringConstant)expression2.constant).stringValue().equals("undefined"); //$NON-NLS-1$
- return (SingleNameReference)unaryExpression.expression ;
-
- }
- }
- return null;
- }
-
- public StringBuffer printStatement(int indent, StringBuffer output) {
-
- printIndent(indent, output).append("if ("); //$NON-NLS-1$
- condition.printExpression(0, output).append(")\n"); //$NON-NLS-1$
- thenStatement.printStatement(indent + 2, output);
- if (elseStatement != null) {
- output.append('\n');
- printIndent(indent, output);
- output.append("else\n"); //$NON-NLS-1$
- elseStatement.printStatement(indent + 2, output);
- }
- return output;
- }
-
- public void resolve(BlockScope scope) {
-
- TypeBinding type = condition.resolveTypeExpecting(scope, TypeBinding.BOOLEAN);
- if (thenStatement != null)
- thenStatement.resolve(scope);
- if (elseStatement != null)
- elseStatement.resolve(scope);
- }
-
- public void traverse(
- ASTVisitor visitor,
- BlockScope blockScope) {
-
- if (visitor.visit(this, blockScope)) {
- condition.traverse(visitor, blockScope);
- if (thenStatement != null)
- thenStatement.traverse(visitor, blockScope);
- if (elseStatement != null)
- elseStatement.traverse(visitor, blockScope);
- }
- visitor.endVisit(this, blockScope);
- }
- public int getASTType() {
- return IASTNode.IF_STATEMENT;
-
- }
-}
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
deleted file mode 100644
index d62048c8..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ImportReference.java
+++ /dev/null
@@ -1,105 +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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IImportReference;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.CompilationUnitScope;
-
-public class ImportReference extends ASTNode implements IImportReference {
-
- public char[][] tokens;
- public long[] sourcePositions; //each entry is using the code : (start<<32) + end
- public int declarationEnd; // doesn't include an potential trailing comment
- public int declarationSourceStart;
- public int declarationSourceEnd;
-
- public ImportReference(
- char[][] tokens, long[] sourcePositions, boolean onDemand) {
-
- this.tokens = tokens;
- this.sourcePositions = sourcePositions;
- if (onDemand) {
- this.bits |= ASTNode.OnDemand;
- }
-
- this.sourceEnd = (int) (sourcePositions[sourcePositions.length-1] & 0x00000000FFFFFFFF);
- this.sourceStart = (int) (sourcePositions[0] >>> 32);
- }
-
- public ImportReference( // for internal imports
- char[] name, int startPosition, int endPosition, int nameStartPosition) {
-
- this.tokens = CharOperation.splitOn('.', name);
- this.sourcePositions = new long[tokens.length];
- for (int i = 0; i < tokens.length; i++) {
- this.sourcePositions[i] =
- (((long) nameStartPosition) << 32) + (nameStartPosition+tokens[i].length - 1);
- nameStartPosition+=tokens[i].length + 1;
- }
- this.bits |= ASTNode.IsFileImport;
- this.bits |= ASTNode.OnDemand;
- this.declarationSourceStart=this.sourceStart = startPosition;
- this.declarationSourceEnd=this.declarationEnd=this.sourceEnd = endPosition;
- }
-
- /**
- * @return char[][]
- */
- public char[][] getImportName() {
- return tokens;
- }
-
- public StringBuffer print(int indent, StringBuffer output) {
- return print(indent, output, true);
- }
-
- public StringBuffer print(int tab, StringBuffer output, boolean withOnDemand) {
-
- /* when withOnDemand is false, only the name is printed */
- for (int i = 0; i < tokens.length; i++) {
- if (i > 0) output.append('.');
- output.append(tokens[i]);
- }
- if (withOnDemand && ((this.bits & ASTNode.OnDemand) != 0)) {
- output.append(".*"); //$NON-NLS-1$
- }
- return output;
- }
-
- /**
- * Traverse the node
- * @param visitor
- * @param scope
- */
- public void traverse(ASTVisitor visitor, CompilationUnitScope scope) {
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
- }
-
- /**
- * Returns true if this is an internal import.
- * @return true if an internal import.
- */
- public boolean isInternal() {
- return (this.bits & ASTNode.IsFileImport) != 0;
- }
-
- /**
- * Returns true if this is a file import.
- * @return true if a file import.
- */
- public boolean isFileImport() {
- return (this.bits & ASTNode.IsFileImport) != 0;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Initializer.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Initializer.java
deleted file mode 100644
index a3278744..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Initializer.java
+++ /dev/null
@@ -1,107 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IInitializer;
-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.lookup.FieldBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodScope;
-import org.eclipse.wst.jsdt.internal.compiler.parser.Parser;
-
-public class Initializer extends FieldDeclaration implements IInitializer {
-
- public Block block;
- public int lastVisibleFieldID;
- public int bodyStart;
- public int bodyEnd;
-
- public boolean errorInSignature = false;
-
- public Initializer(Block block, int modifiers) {
- this.block = block;
- this.modifiers = modifiers;
-
- declarationSourceStart = sourceStart = block.sourceStart;
- }
-
- public FlowInfo analyseCode(
- MethodScope currentScope,
- FlowContext flowContext,
- FlowInfo flowInfo) {
-
- return block.analyseCode(currentScope, flowContext, flowInfo);
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.AbstractVariableDeclaration#getKind()
- */
- public int getKind() {
- return AbstractVariableDeclaration.INITIALIZER;
- }
-
- public boolean isStatic() {
-
- return (this.modifiers & ClassFileConstants.AccStatic) != 0;
- }
-
- public void parseStatements(
- Parser parser,
- TypeDeclaration typeDeclaration,
- CompilationUnitDeclaration unit) {
-
- //fill up the method body with statement
- parser.parse(this, typeDeclaration, unit);
- }
-
- public StringBuffer printStatement(int indent, StringBuffer output) {
-
- if (modifiers != 0) {
- printIndent(indent, output);
- printModifiers(modifiers, output);
- output.append("{\n"); //$NON-NLS-1$
- block.printBody(indent, output);
- printIndent(indent, output).append('}');
- return output;
- } else {
- return block.printStatement(indent, output);
- }
- }
-
- public void resolve(MethodScope scope) {
-
- FieldBinding previousField = scope.initializedField;
- int previousFieldID = scope.lastVisibleFieldID;
- try {
- scope.initializedField = null;
- scope.lastVisibleFieldID = lastVisibleFieldID;
- block.resolve(scope);
- } finally {
- scope.initializedField = previousField;
- scope.lastVisibleFieldID = previousFieldID;
- }
- }
-
- public void traverse(ASTVisitor visitor, MethodScope scope) {
-
- if (visitor.visit(this, scope)) {
- block.traverse(visitor, scope);
- }
- visitor.endVisit(this, scope);
- }
- public int getASTType() {
- return IASTNode.INITIALIZER;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/InstanceOfExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/InstanceOfExpression.java
deleted file mode 100644
index 0f45bbba..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/InstanceOfExpression.java
+++ /dev/null
@@ -1,90 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IInstanceOfExpression;
-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;
-import org.eclipse.wst.jsdt.internal.compiler.impl.Constant;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.LocalVariableBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TagBits;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class InstanceOfExpression extends OperatorExpression implements IInstanceOfExpression {
-
- public Expression expression;
- public TypeReference type;
-
- public InstanceOfExpression(Expression expression, TypeReference type) {
-
- this.expression = expression;
- this.type = type;
- type.bits |= IgnoreRawTypeCheck; // no need to worry about raw type usage
- this.bits |= INSTANCEOF << OperatorSHIFT;
- this.sourceStart = expression.sourceStart;
- this.sourceEnd = type.sourceEnd;
- }
-
-public FlowInfo analyseCode(
- BlockScope currentScope,
- FlowContext flowContext,
- FlowInfo flowInfo) {
- LocalVariableBinding local = this.expression.localVariableBinding();
- if (local != null && (local.type.tagBits & TagBits.IsBaseType) == 0) {
- flowContext.recordUsingNullReference(currentScope, local,
- this.expression, FlowContext.CAN_ONLY_NULL, flowInfo);
- flowInfo = expression.analyseCode(currentScope, flowContext, flowInfo).
- unconditionalInits();
- FlowInfo initsWhenTrue = flowInfo.copy();
- initsWhenTrue.markAsComparedEqualToNonNull(local);
- // no impact upon enclosing try context
- return FlowInfo.conditional(initsWhenTrue, flowInfo.copy());
- }
- return expression.analyseCode(currentScope, flowContext, flowInfo).
- unconditionalInits();
-}
-
- public StringBuffer printExpressionNoParenthesis(int indent, StringBuffer output) {
-
- expression.printExpression(indent, output).append(" instanceof "); //$NON-NLS-1$
- return type.print(0, output);
- }
-
- public TypeBinding resolveType(BlockScope scope) {
-
- constant = Constant.NotAConstant;
- TypeBinding expressionType = expression.resolveType(scope);
- TypeBinding checkedType = type.resolveType(scope, true /* check bounds*/);
- if (expressionType == null || checkedType == null)
- return null;
-
- if ((expressionType != TypeBinding.NULL && expressionType.isBaseType()) // disallow autoboxing
- || !checkCastTypesCompatibility(scope, checkedType, expressionType, null)) {
- scope.problemReporter().notCompatibleTypesError(this, expressionType, checkedType);
- }
- return this.resolvedType = TypeBinding.BOOLEAN;
- }
- public void traverse(ASTVisitor visitor, BlockScope scope) {
-
- if (visitor.visit(this, scope)) {
- expression.traverse(visitor, scope);
- type.traverse(visitor, scope);
- }
- visitor.endVisit(this, scope);
- }
- public int getASTType() {
- return IASTNode.INSTANCEOF_EXPRESSION;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/IntLiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/IntLiteral.java
deleted file mode 100644
index dfc190d1..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/IntLiteral.java
+++ /dev/null
@@ -1,154 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IIntLiteral;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-import org.eclipse.wst.jsdt.internal.compiler.impl.Constant;
-import org.eclipse.wst.jsdt.internal.compiler.impl.DoubleConstant;
-import org.eclipse.wst.jsdt.internal.compiler.impl.IntConstant;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-import org.eclipse.wst.jsdt.internal.compiler.parser.ScannerHelper;
-
-public class IntLiteral extends NumberLiteral implements IIntLiteral {
- public int value;
-
-
- static final Constant FORMAT_ERROR = DoubleConstant.fromValue(1.0/0.0); // NaN;
-public IntLiteral(char[] token, int s, int e) {
- super(token, s,e);
-}
-public IntLiteral(char[] token, int s,int e, int value) {
- this(token, s,e);
- this.value = value;
-}
-public IntLiteral(int intValue) {
- //special optimized constructor : the cst is the argument
-
- //value that should not be used
- // tokens = null ;
- // sourceStart = 0;
- // sourceEnd = 0;
- super(null,0,0);
- constant = IntConstant.fromValue(intValue);
- value = intValue;
-
-}
-public void computeConstant() {
- //a special constant is use for the potential Integer.MAX_VALUE+1
- //which is legal if used with a - as prefix....cool....
- //notice that Integer.MIN_VALUE == -2147483648
-
-
- int length = source.length;
- long computedValue = 0L;
- if (source[0] == '0')
- { if (length == 1) { constant = IntConstant.fromValue(0); return ;}
- final int shift,radix;
- int maxDigit=16;
- int j ;
- if ( (source[1] == 'x') || (source[1] == 'X') )
- { shift = 4 ; j = 2; radix = 16; maxDigit=18;}
- else
- { shift = 3 ; j = 1; radix = 8;}
- if (length>maxDigit)
- return ;
- while (source[j]=='0')
- { j++; //jump over redondant zero
- if (j == length)
- { //watch for 000000000000000000
- constant = IntConstant.fromValue(value = (int)computedValue);
- return ;}}
-
- while (j<length)
- { int digitValue ;
- if ((digitValue = ScannerHelper.digit(source[j++],radix)) < 0 )
- { constant = FORMAT_ERROR; return ;}
- computedValue = (computedValue<<shift) | digitValue ;
-// if (computedValue > MAX) return /*constant stays null*/ ;
- } }
- else
- { //-----------regular case : radix = 10-----------
- for (int i = 0 ; i < length;i++)
- { int digitValue ;
- if ((digitValue = ScannerHelper.digit(source[i],10)) < 0 )
- { constant = FORMAT_ERROR; return ;}
- computedValue = 10*computedValue + digitValue;
-// if (computedValue > MAX) return /*constant stays null*/ ;
- }}
-
- constant = IntConstant.fromValue(value = (int)computedValue);
-
-}
-public TypeBinding literalType(BlockScope scope) {
- if(scope == null)
- return TypeBinding.INT;
- return scope.getJavaLangNumber();
-
-}
-public final boolean mayRepresentMIN_VALUE(){
- //a special autorized int literral is 2147483648
- //which is ONE over the limit. This special case
- //only is used in combinaison with - to denote
- //the minimal value of int -2147483648
-
- return ((source.length == 10) &&
- (source[0] == '2') &&
- (source[1] == '1') &&
- (source[2] == '4') &&
- (source[3] == '7') &&
- (source[4] == '4') &&
- (source[5] == '8') &&
- (source[6] == '3') &&
- (source[7] == '6') &&
- (source[8] == '4') &&
- (source[9] == '8') &&
- (((this.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT) == 0));
-}
-public TypeBinding resolveType(BlockScope scope) {
- // the format may be incorrect while the scanner could detect
- // such an error only on painfull tests...easier and faster here
-
- TypeBinding tb = super.resolveType(scope);
- if (constant == FORMAT_ERROR) {
- constant = Constant.NotAConstant;
- scope.problemReporter().constantOutOfFormat(this);
- this.resolvedType = null;
- return null;
- }
- return tb;
-}
-public StringBuffer printExpression(int indent, StringBuffer output){
-
- if (source == null) {
- /* special optimized IntLiteral that are created by the compiler */
- return output.append(String.valueOf(value));
- }
- return super.printExpression(indent, output);
-}
-
-public void traverse(ASTVisitor visitor, BlockScope scope) {
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
-}
-public int getASTType() {
- return IASTNode.INT_LITERAL;
-
-}
-
-public static IntLiteral getOne()
-{
- return new IntLiteral(new char[]{'1'},0,0,1);//used for ++ and --
-}
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/IntLiteralMinValue.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/IntLiteralMinValue.java
deleted file mode 100644
index f6631864..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/IntLiteralMinValue.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IIntLiteralMinValue;
-import org.eclipse.wst.jsdt.internal.compiler.impl.Constant;
-import org.eclipse.wst.jsdt.internal.compiler.impl.IntConstant;
-
-public class IntLiteralMinValue extends IntLiteral implements IIntLiteralMinValue {
-
- final static char[] CharValue = new char[]{'-','2','1','4','7','4','8','3','6','4','8'};
- final static Constant MIN_VALUE = IntConstant.fromValue(Integer.MIN_VALUE) ;
-
-public IntLiteralMinValue() {
- super(CharValue,0,0,Integer.MIN_VALUE);
- constant = MIN_VALUE;
-}
-public void computeConstant(){
-
- /*precomputed at creation time*/
-}
-public int getASTType() {
- return IASTNode.INT_LITERAL_MIN_VALUE;
-
-}
-}
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
deleted file mode 100644
index ba3422c4..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Javadoc.java
+++ /dev/null
@@ -1,687 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IJsDoc;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants;
-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.ExtraCompilerModifiers;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ImportBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.LocalVariableBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodScope;
-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;
-
-/**
- * Node representing a structured Javadoc comment
- */
-public class Javadoc extends ASTNode implements IJsDoc {
-
- public JavadocSingleNameReference[] paramReferences; // @param
- public TypeReference[] exceptionReferences; // @throws, @exception
- public JavadocReturnStatement returnStatement; // @return, @returns
- public Expression[] seeReferences; // @see
- public long inheritedPositions = -1;
- // bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=51600
- // Store param references for tag with invalid syntax
- public JavadocSingleNameReference[] invalidParameters; // @param
- // bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=153399
- // Store value tag positions
- public long valuePositions = -1;
- public int modifiers=0;
-
- public TypeReference namespace=null;
- public TypeReference memberOf=null;
- public TypeReference returnType=null;
- public TypeReference extendsType=null;
-
- public TypeReference classDef=null;
- public TypeReference methodDef=null;
- public JavadocSingleNameReference property=null;
- public boolean isConstructor;
-
-
- public Javadoc(int sourceStart, int sourceEnd) {
- this.sourceStart = sourceStart;
- this.sourceEnd = sourceEnd;
- }
- /**
- * Returns whether a type can be seen at a given visibility level or not.
- *
- * @param visibility Level of visiblity allowed to see references
- * @param modifiers modifiers of java element to be seen
- * @return true if the type can be seen, false otherwise
- */
- boolean canBeSeen(int visibility, int modifiers) {
- if (modifiers < 0) return true;
- switch (modifiers & ExtraCompilerModifiers.AccVisibilityMASK) {
- case ClassFileConstants.AccPublic :
- return true;
- case ClassFileConstants.AccProtected:
- return (visibility != ClassFileConstants.AccPublic);
- case ClassFileConstants.AccDefault:
- return (visibility == ClassFileConstants.AccDefault || visibility == ClassFileConstants.AccPrivate);
- case ClassFileConstants.AccPrivate:
- return (visibility == ClassFileConstants.AccPrivate);
- }
- return true;
- }
-
- /*
- * Search node with a given staring position in javadoc objects arrays.
- */
- public ASTNode getNodeStartingAt(int start) {
- int length = 0;
- // parameters array
- if (this.paramReferences != null) {
- length = this.paramReferences.length;
- for (int i=0; i<length; i++) {
- JavadocSingleNameReference param = this.paramReferences[i];
- if (param.sourceStart==start) {
- return param;
- }
- }
- }
- // array of invalid syntax tags parameters
- if (this.invalidParameters != null) {
- length = this.invalidParameters.length;
- for (int i=0; i<length; i++) {
- JavadocSingleNameReference param = this.invalidParameters[i];
- if (param.sourceStart==start) {
- return param;
- }
- }
- }
-
- // thrown exception array
- if (this.exceptionReferences != null) {
- length = this.exceptionReferences.length;
- for (int i=0; i<length; i++) {
- TypeReference typeRef = this.exceptionReferences[i];
- if (typeRef.sourceStart==start) {
- return typeRef;
- }
- }
- }
- // references array
- if (this.seeReferences != null) {
- length = this.seeReferences.length;
- for (int i=0; i<length; i++) {
- org.eclipse.wst.jsdt.internal.compiler.ast.Expression expression = this.seeReferences[i];
- if (expression.sourceStart==start) {
- return expression;
- } else if (expression instanceof JavadocAllocationExpression) {
- JavadocAllocationExpression allocationExpr = (JavadocAllocationExpression) this.seeReferences[i];
- // if binding is valid then look at arguments
- if (allocationExpr.binding != null && allocationExpr.binding.isValidBinding()) {
- if (allocationExpr.arguments != null) {
- for (int j=0, l=allocationExpr.arguments.length; j<l; j++) {
- if (allocationExpr.arguments[j].sourceStart == start) {
- return allocationExpr.arguments[j];
- }
- }
- }
- }
- } else if (expression instanceof JavadocMessageSend) {
- JavadocMessageSend messageSend = (JavadocMessageSend) this.seeReferences[i];
- // if binding is valid then look at arguments
- if (messageSend.binding != null && messageSend.binding.isValidBinding()) {
- if (messageSend.arguments != null) {
- for (int j=0, l=messageSend.arguments.length; j<l; j++) {
- if (messageSend.arguments[j].sourceStart == start) {
- return messageSend.arguments[j];
- }
- }
- }
- }
- }
- }
- }
- return null;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode#print(int, java.lang.StringBuffer)
- */
- public StringBuffer print(int indent, StringBuffer output) {
- printIndent(indent, output).append("/**\n"); //$NON-NLS-1$
- if (this.paramReferences != null) {
- for (int i = 0, length = this.paramReferences.length; i < length; i++) {
- printIndent(indent + 1, output).append(" * @param "); //$NON-NLS-1$
- this.paramReferences[i].print(indent, output).append('\n');
- }
- }
- if (this.returnStatement != null) {
- printIndent(indent + 1, output).append(" * @"); //$NON-NLS-1$
- this.returnStatement.print(indent, output).append('\n');
- }
- if (this.exceptionReferences != null) {
- for (int i = 0, length = this.exceptionReferences.length; i < length; i++) {
- printIndent(indent + 1, output).append(" * @throws "); //$NON-NLS-1$
- this.exceptionReferences[i].print(indent, output).append('\n');
- }
- }
- if (this.seeReferences != null) {
- for (int i = 0, length = this.seeReferences.length; i < length; i++) {
- printIndent(indent + 1, output).append(" * @see "); //$NON-NLS-1$
- this.seeReferences[i].print(indent, output).append('\n');
- }
- }
-
- if (this.returnType!=null)
- {
- printIndent(indent + 1, output).append(" * @type "); //$NON-NLS-1$
- this.returnType.print(indent, output).append('\n');
-
- }
- if (this.memberOf!=null)
- {
- printIndent(indent + 1, output).append(" * @member "); //$NON-NLS-1$
- this.memberOf.print(indent, output).append('\n');
-
- }
- if (this.extendsType!=null)
- {
- printIndent(indent + 1, output).append(" * @extends "); //$NON-NLS-1$
- this.extendsType.print(indent, output).append('\n');
-
- }
- if (this.isConstructor)
- printIndent(indent + 1, output).append(" * @constructor\n"); //$NON-NLS-1$
- if ((this.modifiers & ClassFileConstants.AccPrivate) != 0)
- printIndent(indent + 1, output).append(" * @private\n"); //$NON-NLS-1$
- if ((this.modifiers & ClassFileConstants.AccFinal) != 0)
- printIndent(indent + 1, output).append(" * @final\n"); //$NON-NLS-1$
-
-
- printIndent(indent, output).append(" */\n"); //$NON-NLS-1$
- return output;
- }
-
- /*
- * Resolve type javadoc
- */
- public void resolve(ClassScope scope) {
-
- // @param tags
- int paramTagsSize = this.paramReferences == null ? 0 : this.paramReferences.length;
- for (int i = 0; i < paramTagsSize; i++) {
- JavadocSingleNameReference param = this.paramReferences[i];
- scope.problemReporter().javadocUnexpectedTag(param.tagSourceStart, param.tagSourceEnd);
- }
-
- // @return tags
- if (this.returnStatement != null) {
- scope.problemReporter().javadocUnexpectedTag(this.returnStatement.sourceStart, this.returnStatement.sourceEnd);
- }
-
- // @throws/@exception tags
- int throwsTagsLength = this.exceptionReferences == null ? 0 : this.exceptionReferences.length;
- for (int i = 0; i < throwsTagsLength; i++) {
- TypeReference typeRef = this.exceptionReferences[i];
- int start, end;
- if (typeRef instanceof JavadocSingleTypeReference) {
- JavadocSingleTypeReference singleRef = (JavadocSingleTypeReference) typeRef;
- start = singleRef.tagSourceStart;
- end = singleRef.tagSourceEnd;
- } else if (typeRef instanceof JavadocQualifiedTypeReference) {
- JavadocQualifiedTypeReference qualifiedRef = (JavadocQualifiedTypeReference) typeRef;
- start = qualifiedRef.tagSourceStart;
- end = qualifiedRef.tagSourceEnd;
- } else {
- start = typeRef.sourceStart;
- end = typeRef.sourceEnd;
- }
- scope.problemReporter().javadocUnexpectedTag(start, end);
- }
-
- // @see tags
- int seeTagsLength = this.seeReferences == null ? 0 : this.seeReferences.length;
- for (int i = 0; i < seeTagsLength; i++) {
- resolveReference(this.seeReferences[i], scope);
- }
-
- // @value tag
- boolean source15 = scope.compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5;
- if (!source15 && this.valuePositions != -1) {
- scope.problemReporter().javadocUnexpectedTag((int)(this.valuePositions>>>32), (int) this.valuePositions);
- }
- }
-
- /*
- * Resolve compilation unit javadoc
- */
- public void resolve(CompilationUnitScope unitScope) {
- // do nothing
- }
-
- /*
- * Resolve method javadoc
- */
- public void resolve(MethodScope methScope) {
-
- // get method declaration
- AbstractMethodDeclaration methDecl = methScope.referenceMethod();
- boolean overriding = methDecl == null /* field declaration */ || methDecl.binding == null /* compiler error */
- ? false :
- !methDecl.binding.isStatic() && ((methDecl.binding.modifiers & (ExtraCompilerModifiers.AccImplementing | ExtraCompilerModifiers.AccOverriding)) != 0);
-
- // @see tags
- int seeTagsLength = this.seeReferences == null ? 0 : this.seeReferences.length;
- boolean superRef = false;
- for (int i = 0; i < seeTagsLength; i++) {
-
- // Resolve reference
- resolveReference(this.seeReferences[i], methScope);
-
- if (methDecl != null && (methDecl.isConstructor() || overriding) && !superRef) {
- if (this.seeReferences[i] instanceof JavadocMessageSend) {
- JavadocMessageSend messageSend = (JavadocMessageSend) this.seeReferences[i];
- // if binding is valid then look if we have a reference to an overriden method/constructor
- 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) &&
- (methDecl.binding.returnType.isCompatibleWith(messageSend.binding.returnType))) {
- if (messageSend.arguments == null && methDecl.arguments == null) {
- superRef = true;
- }
- else if (messageSend.arguments != null && methDecl.arguments != null) {
- superRef = methDecl.binding.areParametersEqual(messageSend.binding);
- }
- }
- }
- }
- else if (this.seeReferences[i] instanceof JavadocAllocationExpression) {
- JavadocAllocationExpression allocationExpr = (JavadocAllocationExpression) this.seeReferences[i];
- // if binding is valid then look if we have a reference to an overriden method/constructor
- if (allocationExpr.binding != null && allocationExpr.binding.isValidBinding()) {
- if (methDecl.binding.declaringClass.isCompatibleWith(allocationExpr.resolvedType)) {
- if (allocationExpr.arguments == null && methDecl.arguments == null) {
- superRef = true;
- }
- else if (allocationExpr.arguments != null && methDecl.arguments != null) {
- superRef = methDecl.binding.areParametersCompatibleWith(allocationExpr.binding.parameters);
- }
- }
- }
- }
- }
- }
-
- // Store if a reference exists to an overriden method/constructor or the method is in a local type,
- boolean reportMissing = methDecl == null || !((overriding && this.inheritedPositions != -1) || superRef || (methDecl.binding != null && methDecl.binding.declaringClass != null && methDecl.binding.declaringClass.isLocalType()));
- if (!overriding && this.inheritedPositions != -1) {
- int start = (int) (this.inheritedPositions >>> 32);
- int end = (int) this.inheritedPositions;
- methScope.problemReporter().javadocUnexpectedTag(start, end);
- }
-
- // @param tags
- boolean considerParamRefAsUsage = methScope.compilerOptions().reportUnusedParameterIncludeDocCommentReference;
- resolveParamTags(methScope, reportMissing,considerParamRefAsUsage);
-
- // @return tags
- if (this.returnStatement == null) {
- if (reportMissing && methDecl != null) {
- if (methDecl.isMethod()) {
- MethodDeclaration meth = (MethodDeclaration) methDecl;
- if (meth.binding != null && meth.binding.returnType != TypeBinding.VOID && !meth.binding.isConstructor()) {
- // method with return should have @return tag
- methScope.problemReporter().javadocMissingReturnTag(meth.declarationSourceStart, meth.declarationSourceEnd, methDecl.binding.modifiers);
- }
- }
- }
- } else {
- this.returnStatement.resolve(methScope);
- }
-
- // @throws/@exception tags
- resolveThrowsTags(methScope, reportMissing);
-
- // @value tag
- boolean source15 = methScope.compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5;
- if (!source15 && methDecl != null && this.valuePositions != -1) {
- methScope.problemReporter().javadocUnexpectedTag((int)(this.valuePositions>>>32), (int) this.valuePositions);
- }
-
- // Resolve param tags with invalid syntax
- int length = this.invalidParameters == null ? 0 : this.invalidParameters.length;
- for (int i = 0; i < length; i++) {
- this.invalidParameters[i].resolve(methScope, false, false);
- }
- }
-
- private void resolveReference(Expression reference, Scope scope) {
-
- // Perform resolve
- int problemCount = scope.referenceContext().compilationResult().problemCount;
- switch (scope.kind) {
- case Scope.METHOD_SCOPE:
- reference.resolveType((MethodScope)scope);
- break;
- case Scope.CLASS_SCOPE:
- reference.resolveType((ClassScope)scope);
- break;
- }
- boolean hasProblems = scope.referenceContext().compilationResult().problemCount > problemCount;
-
- // Verify field references
- boolean source15 = scope.compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5;
- int scopeModifiers = -1;
- if (reference instanceof JavadocFieldReference) {
- JavadocFieldReference fieldRef = (JavadocFieldReference) reference;
-
- // Verify if this is a method reference
- // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=51911
- if (fieldRef.methodBinding != null) {
- if (fieldRef.receiverType != null) {
- if (scope.enclosingSourceType().isCompatibleWith(fieldRef.receiverType)) {
- fieldRef.bits |= ASTNode.SuperAccess;
- }
- fieldRef.methodBinding = scope.findMethod((ReferenceBinding)fieldRef.receiverType, fieldRef.token, new TypeBinding[0], fieldRef);
- }
- }
-
- // Verify type references
- if (!hasProblems && fieldRef.binding != null && fieldRef.binding.isValidBinding() && fieldRef.receiverType instanceof ReferenceBinding) {
- ReferenceBinding resolvedType = (ReferenceBinding) fieldRef.receiverType;
- verifyTypeReference(fieldRef, fieldRef.receiver, scope, source15, resolvedType, fieldRef.binding.modifiers);
- }
-
- // That's it for field references
- return;
- }
-
- // Verify type references
- if (!hasProblems && (reference instanceof JavadocSingleTypeReference || reference instanceof JavadocQualifiedTypeReference) && reference.resolvedType instanceof ReferenceBinding) {
- ReferenceBinding resolvedType = (ReferenceBinding) reference.resolvedType;
- verifyTypeReference(reference, reference, scope, source15, resolvedType, resolvedType.modifiers);
- }
-
- // Verify that message reference are not used for @value tags
- if (reference instanceof JavadocMessageSend) {
- JavadocMessageSend msgSend = (JavadocMessageSend) reference;
-
- // Verify type references
- if (!hasProblems && msgSend.binding != null && msgSend.binding.isValidBinding() && msgSend.actualReceiverType instanceof ReferenceBinding) {
- ReferenceBinding resolvedType = (ReferenceBinding) msgSend.actualReceiverType;
- verifyTypeReference(msgSend, msgSend.receiver, scope, source15, resolvedType, msgSend.binding.modifiers);
- }
- }
-
- // Verify that constructor reference are not used for @value tags
- else if (reference instanceof JavadocAllocationExpression) {
- JavadocAllocationExpression alloc = (JavadocAllocationExpression) reference;
-
- // Verify type references
- if (!hasProblems && alloc.binding != null && alloc.binding.isValidBinding() && alloc.resolvedType instanceof ReferenceBinding) {
- ReferenceBinding resolvedType = (ReferenceBinding) alloc.resolvedType;
- verifyTypeReference(alloc, alloc.type, scope, source15, resolvedType, alloc.binding.modifiers);
- }
- }
- }
-
- /*
- * Resolve @param tags while method scope
- */
- private void resolveParamTags(MethodScope scope, boolean reportMissing, boolean considerParamRefAsUsage) {
- AbstractMethodDeclaration methodDecl = scope.referenceMethod();
- int paramTagsSize = this.paramReferences == null ? 0 : this.paramReferences.length;
-
- // If no referenced method (field initializer for example) then report a problem for each param tag
- if (methodDecl == null) {
- for (int i = 0; i < paramTagsSize; i++) {
- JavadocSingleNameReference param = this.paramReferences[i];
- scope.problemReporter().javadocUnexpectedTag(param.tagSourceStart, param.tagSourceEnd);
- }
- return;
- }
-
- // If no param tags then report a problem for each method argument
- int argumentsSize = methodDecl.arguments == null ? 0 : methodDecl.arguments.length;
- if (paramTagsSize == 0) {
- if (reportMissing) {
- for (int i = 0; i < argumentsSize; i++) {
- Argument arg = methodDecl.arguments[i];
- scope.problemReporter().javadocMissingParamTag(arg.name, arg.sourceStart, arg.sourceEnd, methodDecl.binding == null ? 0 : methodDecl.binding.modifiers);
- }
- }
- } else {
- LocalVariableBinding[] bindings = new LocalVariableBinding[paramTagsSize];
- int maxBindings = 0;
-
- // Scan all @param tags
- for (int i = 0; i < paramTagsSize; i++) {
- JavadocSingleNameReference param = this.paramReferences[i];
- param.resolve(scope, true, considerParamRefAsUsage);
- if (param.binding != null && param.binding.isValidBinding()) {
- // Verify duplicated tags
- boolean found = false;
- for (int j = 0; j < maxBindings && !found; j++) {
- if (bindings[j] == param.binding) {
- scope.problemReporter().javadocDuplicatedParamTag(param.token, param.sourceStart, param.sourceEnd, methodDecl.binding.modifiers);
- found = true;
- }
- }
- if (!found) {
- bindings[maxBindings++] = (LocalVariableBinding) param.binding;
- }
- }
- }
-
- // Look for undocumented arguments
- if (reportMissing) {
- for (int i = 0; i < argumentsSize; i++) {
- Argument arg = methodDecl.arguments[i];
- boolean found = false;
- for (int j = 0; j < maxBindings && !found; j++) {
- LocalVariableBinding binding = bindings[j];
- if (arg.binding == binding) {
- found = true;
- }
- }
- if (!found) {
- scope.problemReporter().javadocMissingParamTag(arg.name, arg.sourceStart, arg.sourceEnd, methodDecl.binding.modifiers);
- }
- }
- }
- }
- }
-
- /*
- * Resolve @throws/@exception tags while method scope
- */
- private void resolveThrowsTags(MethodScope methScope, boolean reportMissing) {
- AbstractMethodDeclaration md = methScope.referenceMethod();
- int throwsTagsLength = this.exceptionReferences == null ? 0 : this.exceptionReferences.length;
-
- // If no referenced method (field initializer for example) then report a problem for each throws tag
- if (md == null) {
- for (int i = 0; i < throwsTagsLength; i++) {
- TypeReference typeRef = this.exceptionReferences[i];
- int start = typeRef.sourceStart;
- int end = typeRef.sourceEnd;
- if (typeRef instanceof JavadocQualifiedTypeReference) {
- start = ((JavadocQualifiedTypeReference) typeRef).tagSourceStart;
- end = ((JavadocQualifiedTypeReference) typeRef).tagSourceEnd;
- } else if (typeRef instanceof JavadocSingleTypeReference) {
- start = ((JavadocSingleTypeReference) typeRef).tagSourceStart;
- end = ((JavadocSingleTypeReference) typeRef).tagSourceEnd;
- }
- methScope.problemReporter().javadocUnexpectedTag(start, end);
- }
- return;
- }
-
- // If no throws tags then report a problem for each method thrown exception
- if (throwsTagsLength == 0) {
- } else {
- int maxRef = 0;
- TypeReference[] typeReferences = new TypeReference[throwsTagsLength];
-
- // Scan all @throws tags
- for (int i = 0; i < throwsTagsLength; i++) {
- TypeReference typeRef = this.exceptionReferences[i];
- typeRef.resolve(methScope);
- TypeBinding typeBinding = typeRef.resolvedType;
-
- if (typeBinding != null && typeBinding.isValidBinding() && typeBinding.isClass()) {
- // accept only valid class binding
- typeReferences[maxRef++] = typeRef;
- }
- }
- }
- }
-
- private void verifyTypeReference(Expression reference, Expression typeReference, Scope scope, boolean source15, ReferenceBinding resolvedType, int modifiers) {
- if (resolvedType.isValidBinding()) {
- int scopeModifiers = -1;
-
- // reference must have enough visibility to be used
- if (!canBeSeen(scope.problemReporter().options.reportInvalidJavadocTagsVisibility, modifiers)) {
- scope.problemReporter().javadocHiddenReference(typeReference.sourceStart, reference.sourceEnd, scope, modifiers);
- return;
- }
-
- // type reference must have enough visibility to be used
- if (reference != typeReference) {
- if (!canBeSeen(scope.problemReporter().options.reportInvalidJavadocTagsVisibility, resolvedType.modifiers)) {
- scope.problemReporter().javadocHiddenReference(typeReference.sourceStart, typeReference.sourceEnd, scope, resolvedType.modifiers);
- return;
- }
- }
-
- // member types
- if (resolvedType.isMemberType()) {
- ReferenceBinding topLevelType = resolvedType;
- // rebuild and store (in reverse order) compound name to handle embedded inner class
- int packageLength = topLevelType.fPackage.compoundName.length;
- int depth = resolvedType.depth();
- int idx = depth + packageLength;
- char[][] computedCompoundName = new char[idx+1][];
- computedCompoundName[idx] = topLevelType.sourceName;
- while (topLevelType.enclosingType() != null) {
- topLevelType = topLevelType.enclosingType();
- computedCompoundName[--idx] = topLevelType.sourceName;
- }
-
- // add package information
- for (int i = packageLength; --i >= 0;) {
- computedCompoundName[--idx] = topLevelType.fPackage.compoundName[i];
- }
-
- ClassScope topLevelScope = scope.classScope();
- // when scope is not on compilation unit type, then inner class may not be visible...
- if (topLevelScope.parent.kind != Scope.COMPILATION_UNIT_SCOPE ||
- !CharOperation.equals(topLevelType.sourceName, topLevelScope.referenceContext.name)) {
- topLevelScope = topLevelScope.outerMostClassScope();
- if (typeReference instanceof JavadocSingleTypeReference) {
- // inner class single reference can only be done in same unit
- if ((!source15 && depth == 1) || topLevelType != topLevelScope.referenceContext.binding) {
- // search for corresponding import
- boolean hasValidImport = false;
- if (source15) {
- CompilationUnitScope unitScope = topLevelScope.compilationUnitScope();
- ImportBinding[] imports = unitScope.imports;
- int length = imports == null ? 0 : imports.length;
- mainLoop: for (int i=0; i<length; i++) {
- char[][] compoundName = imports[i].compoundName;
- int compoundNameLength = compoundName.length;
- if ((imports[i].onDemand && compoundNameLength == computedCompoundName.length-1) ||
- (compoundNameLength == computedCompoundName.length))
- {
- for (int j = compoundNameLength; --j >= 0;) {
- if (CharOperation.equals(imports[i].compoundName[j], computedCompoundName[j])) {
- if (j == 0) {
- hasValidImport = true;
- break mainLoop;
- }
- } else {
- break;
- }
- }
- }
- }
- }
- }
- }
- }
- }
- }
- }
- public void traverse(ASTVisitor visitor, BlockScope scope) {
- if (visitor.visit(this, scope)) {
- if (this.paramReferences != null) {
- for (int i = 0, length = this.paramReferences.length; i < length; i++) {
- this.paramReferences[i].traverse(visitor, scope);
- }
- }
- if (this.returnStatement != null) {
- this.returnStatement.traverse(visitor, scope);
- }
- if (this.exceptionReferences != null) {
- for (int i = 0, length = this.exceptionReferences.length; i < length; i++) {
- this.exceptionReferences[i].traverse(visitor, scope);
- }
- }
- if (this.seeReferences != null) {
- for (int i = 0, length = this.seeReferences.length; i < length; i++) {
- this.seeReferences[i].traverse(visitor, scope);
- }
- }
- }
- visitor.endVisit(this, scope);
- }
- public void traverse(ASTVisitor visitor, ClassScope scope) {
- if (visitor.visit(this, scope)) {
- if (this.paramReferences != null) {
- for (int i = 0, length = this.paramReferences.length; i < length; i++) {
- this.paramReferences[i].traverse(visitor, scope);
- }
- }
- if (this.returnStatement != null) {
- this.returnStatement.traverse(visitor, scope);
- }
- if (this.exceptionReferences != null) {
- for (int i = 0, length = this.exceptionReferences.length; i < length; i++) {
- this.exceptionReferences[i].traverse(visitor, scope);
- }
- }
- if (this.seeReferences != null) {
- for (int i = 0, length = this.seeReferences.length; i < length; i++) {
- this.seeReferences[i].traverse(visitor, scope);
- }
- }
- }
- visitor.endVisit(this, scope);
- }
-
- public JavadocSingleNameReference findParam(char [] name)
- {
- if (this.paramReferences!=null)
- for (int i = 0; i < this.paramReferences.length; i++) {
- if (CharOperation.equals(name, this.paramReferences[i].token))
- return this.paramReferences[i];
- }
- return null;
- }
- public int getASTType() {
- return IASTNode.JSDOC;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocAllocationExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocAllocationExpression.java
deleted file mode 100644
index e7b87b51..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocAllocationExpression.java
+++ /dev/null
@@ -1,170 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IJsDocAllocationExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-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.ClassScope;
-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.SourceTypeBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class JavadocAllocationExpression extends AllocationExpression implements IJsDocAllocationExpression {
-
- public int tagSourceStart, tagSourceEnd;
- public int tagValue, memberStart;
- public char[][] qualification;
-
- public JavadocAllocationExpression(int start, int end) {
- this.sourceStart = start;
- this.sourceEnd = end;
- this.bits |= InsideJavadoc;
- }
- public JavadocAllocationExpression(long pos) {
- this((int) (pos >>> 32), (int) pos);
- }
-
- TypeBinding internalResolveType(Scope scope) {
-
- // Propagate the type checking to the arguments, and check if the constructor is defined.
- this.constant = Constant.NotAConstant;
- if (this.type == null) {
- this.resolvedType = scope.enclosingSourceType();
- } else if (scope.kind == Scope.CLASS_SCOPE) {
- this.resolvedType = this.type.resolveType((ClassScope)scope);
- } else {
- this.resolvedType = this.type.resolveType((BlockScope)scope, true /* check bounds*/);
- }
-
- // buffering the arguments' types
- TypeBinding[] argumentTypes = Binding.NO_PARAMETERS;
- boolean hasTypeVarArgs = false;
- if (this.arguments != null) {
- boolean argHasError = false;
- int length = this.arguments.length;
- argumentTypes = new TypeBinding[length];
- for (int i = 0; i < length; i++) {
- Expression argument = this.arguments[i];
- if (scope.kind == Scope.CLASS_SCOPE) {
- argumentTypes[i] = argument.resolveType((ClassScope)scope);
- } else {
- argumentTypes[i] = argument.resolveType((BlockScope)scope);
- }
- if (argumentTypes[i] == null) {
- argHasError = true;
- } else if (!hasTypeVarArgs) {
- hasTypeVarArgs = false;
- }
- }
- if (argHasError) {
- return null;
- }
- }
-
- // check resolved type
- if (this.resolvedType == null) {
- return null;
- }
- this.resolvedType = this.type.resolvedType;
- SourceTypeBinding enclosingType = scope.enclosingSourceType();
- if (enclosingType == null ? false : enclosingType.isCompatibleWith(this.resolvedType)) {
- this.bits |= ASTNode.SuperAccess;
- }
-
- ReferenceBinding allocationType = (ReferenceBinding) this.resolvedType;
- this.binding = scope.getConstructor(allocationType, argumentTypes, this);
- if (!this.binding.isValidBinding()) {
- ReferenceBinding enclosingTypeBinding = allocationType;
- MethodBinding contructorBinding = this.binding;
- while (!contructorBinding.isValidBinding() && (enclosingTypeBinding.isMemberType() || enclosingTypeBinding.isLocalType())) {
- enclosingTypeBinding = enclosingTypeBinding.enclosingType();
- contructorBinding = scope.getConstructor(enclosingTypeBinding, argumentTypes, this);
- }
- if (contructorBinding.isValidBinding()) {
- this.binding = contructorBinding;
- }
- }
- if (!this.binding.isValidBinding()) {
- // First try to search a method instead
- MethodBinding methodBinding = scope.getMethod(this.resolvedType, this.resolvedType.sourceName(), argumentTypes, this);
- if (methodBinding.isValidBinding()) {
- this.binding = methodBinding;
- } else {
- if (this.binding.declaringClass == null) {
- this.binding.declaringClass = allocationType;
- }
- scope.problemReporter().javadocInvalidConstructor(this, this.binding, scope.getDeclarationModifiers());
- }
- return this.resolvedType;
- } else if (binding.isVarargs()) {
- int length = argumentTypes.length;
- if (!(binding.parameters.length == length && argumentTypes[length-1].isArrayType())) {
- MethodBinding problem = new ProblemMethodBinding(this.binding, this.binding.selector, argumentTypes, ProblemReasons.NotFound);
- scope.problemReporter().javadocInvalidConstructor(this, problem, scope.getDeclarationModifiers());
- }
- } else if (hasTypeVarArgs) {
- MethodBinding problem = new ProblemMethodBinding(this.binding, this.binding.selector, argumentTypes, ProblemReasons.NotFound);
- scope.problemReporter().javadocInvalidConstructor(this, problem, scope.getDeclarationModifiers());
- }
- if (isMethodUseDeprecated(this.binding, scope, true)) {
- scope.problemReporter().javadocDeprecatedMethod(this.binding, this, scope.getDeclarationModifiers());
- }
- return allocationType;
- }
-
- public boolean isSuperAccess() {
- return (this.bits & ASTNode.SuperAccess) != 0;
- }
-
- public TypeBinding resolveType(BlockScope scope) {
- return internalResolveType(scope);
- }
-
- public TypeBinding resolveType(ClassScope scope) {
- return internalResolveType(scope);
- }
- public void traverse(ASTVisitor visitor, BlockScope scope) {
- if (visitor.visit(this, scope)) {
- if (this.type != null) { // enum constant scenario
- this.type.traverse(visitor, scope);
- }
- if (this.arguments != null) {
- for (int i = 0, argumentsLength = this.arguments.length; i < argumentsLength; i++)
- this.arguments[i].traverse(visitor, scope);
- }
- }
- visitor.endVisit(this, scope);
- }
- public void traverse(ASTVisitor visitor, ClassScope scope) {
- if (visitor.visit(this, scope)) {
- if (this.type != null) { // enum constant scenario
- this.type.traverse(visitor, scope);
- }
- if (this.arguments != null) {
- for (int i = 0, argumentsLength = this.arguments.length; i < argumentsLength; i++)
- this.arguments[i].traverse(visitor, scope);
- }
- }
- visitor.endVisit(this, scope);
- }
- public int getASTType() {
- return IASTNode.JSDOC_ALLOCATION_EXPRESSION;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocArgumentExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocArgumentExpression.java
deleted file mode 100644
index 9d1ad783..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocArgumentExpression.java
+++ /dev/null
@@ -1,112 +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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IJsDocArgumentExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants;
-import org.eclipse.wst.jsdt.internal.compiler.impl.Constant;
-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.Scope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class JavadocArgumentExpression extends Expression implements IJsDocArgumentExpression {
- public char[] token;
- public Argument argument;
-
- public JavadocArgumentExpression(char[] name, int startPos, int endPos, TypeReference typeRef) {
- this.token = name;
- this.sourceStart = startPos;
- this.sourceEnd = endPos;
- long pos = (((long) startPos) << 32) + endPos;
- this.argument = new Argument(name, pos, typeRef, ClassFileConstants.AccDefault);
- this.bits |= InsideJavadoc;
- }
-
- /*
- * Resolves type on a Block or Class scope.
- */
- private TypeBinding internalResolveType(Scope scope) {
- this.constant = Constant.NotAConstant;
- if (this.resolvedType != null) // is a shared type reference which was already resolved
- return this.resolvedType.isValidBinding() ? this.resolvedType : null; // already reported error
-
- if (this.argument != null) {
- TypeReference typeRef = this.argument.type;
- if (typeRef != null) {
- this.resolvedType = typeRef.getTypeBinding(scope);
- typeRef.resolvedType = this.resolvedType;
- if (!this.resolvedType.isValidBinding()) {
- scope.problemReporter().javadocInvalidType(typeRef, this.resolvedType, scope.getDeclarationModifiers());
- return null;
- }
- if (isTypeUseDeprecated(this.resolvedType, scope)) {
- scope.problemReporter().javadocDeprecatedType(this.resolvedType, typeRef, scope.getDeclarationModifiers());
- }
- return this.resolvedType;
- }
- }
- return null;
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output) {
- if (this.argument == null) {
- if (this.token != null) {
- output.append(this.token);
- }
- }
- else {
- this.argument.print(indent, output);
- }
- return output;
- }
-
- public void resolve(BlockScope scope) {
- if (this.argument != null) {
- this.argument.resolve(scope);
- }
- }
-
- public TypeBinding resolveType(BlockScope scope) {
- return internalResolveType(scope);
- }
-
- public TypeBinding resolveType(ClassScope scope) {
- return internalResolveType(scope);
- }
-
- /* (non-Javadoc)
- * Redefine to capture javadoc specific signatures
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode#traverse(org.eclipse.wst.jsdt.internal.compiler.ASTVisitor, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public void traverse(ASTVisitor visitor, BlockScope blockScope) {
- if (visitor.visit(this, blockScope)) {
- if (this.argument != null) {
- this.argument.traverse(visitor, blockScope);
- }
- }
- visitor.endVisit(this, blockScope);
- }
- public void traverse(ASTVisitor visitor, ClassScope blockScope) {
- if (visitor.visit(this, blockScope)) {
- if (this.argument != null) {
- this.argument.traverse(visitor, blockScope);
- }
- }
- visitor.endVisit(this, blockScope);
- }
- public int getASTType() {
- return IASTNode.JSDOC_ARGUMENTEXPRESSION;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocArrayQualifiedTypeReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocArrayQualifiedTypeReference.java
deleted file mode 100644
index 9917e0ce..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocArrayQualifiedTypeReference.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IJsDocArrayQualifiedTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-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.Scope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-
-
-public class JavadocArrayQualifiedTypeReference extends ArrayQualifiedTypeReference implements IJsDocArrayQualifiedTypeReference {
-
- public int tagSourceStart, tagSourceEnd;
-
- public JavadocArrayQualifiedTypeReference(JavadocQualifiedTypeReference typeRef, int dim) {
- super(typeRef.tokens, dim, typeRef.sourcePositions);
- }
-
- protected void reportInvalidType(Scope scope) {
- scope.problemReporter().javadocInvalidType(this, this.resolvedType, scope.getDeclarationModifiers());
- }
- protected void reportDeprecatedType(TypeBinding type, Scope scope) {
- scope.problemReporter().javadocDeprecatedType(type, this, scope.getDeclarationModifiers());
- }
-
- /* (non-Javadoc)
- * Redefine to capture javadoc specific signatures
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode#traverse(org.eclipse.wst.jsdt.internal.compiler.ASTVisitor, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public void traverse(ASTVisitor visitor, BlockScope scope) {
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
- }
-
- public void traverse(ASTVisitor visitor, ClassScope scope) {
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
- }
- public int getASTType() {
- return IASTNode.JSDOC_ARRAY_QUALIFIED_TYPE_REFERENCE;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocArraySingleTypeReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocArraySingleTypeReference.java
deleted file mode 100644
index c300074f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocArraySingleTypeReference.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IJsDocArraySingleTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-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.Scope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-
-public class JavadocArraySingleTypeReference extends ArrayTypeReference implements IJsDocArraySingleTypeReference {
-
- public JavadocArraySingleTypeReference(char[] name, int dim, long pos) {
- super(name, dim, pos);
- this.bits |= InsideJavadoc;
- }
-
- protected void reportInvalidType(Scope scope) {
- scope.problemReporter().javadocInvalidType(this, this.resolvedType, scope.getDeclarationModifiers());
- }
- protected void reportDeprecatedType(TypeBinding type, Scope scope) {
- scope.problemReporter().javadocDeprecatedType(type, this, scope.getDeclarationModifiers());
- }
-
- /* (non-Javadoc)
- * Redefine to capture javadoc specific signatures
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode#traverse(org.eclipse.wst.jsdt.internal.compiler.ASTVisitor, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public void traverse(ASTVisitor visitor, BlockScope scope) {
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
- }
-
- public void traverse(ASTVisitor visitor, ClassScope scope) {
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
- }
- public int getASTType() {
- return IASTNode.JSDOC_ARRAY_SINGLE_TYPE_REFERENCE;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocFieldReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocFieldReference.java
deleted file mode 100644
index b69d4e75..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocFieldReference.java
+++ /dev/null
@@ -1,162 +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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IJsDocFieldReference;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-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.ClassScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.FieldBinding;
-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.ReferenceBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Scope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class JavadocFieldReference extends FieldReference implements IJsDocFieldReference {
-
- public int tagSourceStart, tagSourceEnd;
- public int tagValue;
- public MethodBinding methodBinding;
-
- public JavadocFieldReference(char[] source, long pos) {
- super(source, pos);
- this.bits |= InsideJavadoc;
- }
-
- /*
- public Binding getBinding() {
- if (this.methodBinding != null) {
- return this.methodBinding;
- }
- return this.binding;
- }
- */
-
- /*
- * Resolves type on a Block or Class scope.
- */
- protected TypeBinding internalResolveType(Scope scope) {
-
- this.constant = Constant.NotAConstant;
- if (this.receiver == null) {
- this.receiverType = scope.enclosingSourceType();
- } else if (scope.kind == Scope.CLASS_SCOPE) {
- this.receiverType = this.receiver.resolveType((ClassScope) scope);
- } else {
- this.receiverType = this.receiver.resolveType((BlockScope)scope);
- }
- if (this.receiverType == null) {
- return null;
- }
-
- //temp fix for 267053 - I don't think these javadoc classes have ever been updated to work well with javascript - cmj
- if(this.receiver != null && this.receiver.isThis() && scope.classScope() == null) {
- return null;
- }
-
- Binding fieldBinding = (this.receiver != null && this.receiver.isThis())
- ? scope.classScope().getBinding(this.token, this.bits & RestrictiveFlagMASK, this, true /*resolve*/)
- : scope.getField(this.receiverType, this.token, this);
- if (!fieldBinding.isValidBinding()) {
- // implicit lookup may discover issues due to static/constructor contexts. javadoc must be resilient
- switch (fieldBinding.problemId()) {
- case ProblemReasons.NonStaticReferenceInConstructorInvocation:
- case ProblemReasons.NonStaticReferenceInStaticContext:
- case ProblemReasons.InheritedNameHidesEnclosingName :
- FieldBinding closestMatch = ((ProblemFieldBinding)fieldBinding).closestMatch;
- if (closestMatch != null) {
- fieldBinding = closestMatch; // ignore problem if can reach target field through it
- }
- }
- }
- // When there's no valid field binding, try to resolve possible method reference without parenthesis
- if (!fieldBinding.isValidBinding() || !(fieldBinding instanceof FieldBinding)) {
- if (this.receiverType instanceof ReferenceBinding) {
- ReferenceBinding refBinding = (ReferenceBinding) this.receiverType;
- MethodBinding[] methodBindings = refBinding.getMethods(this.token);
- if (methodBindings == null) {
- scope.problemReporter().javadocInvalidField(this.sourceStart, this.sourceEnd, fieldBinding, this.receiverType, scope.getDeclarationModifiers());
- } else {
- switch (methodBindings.length) {
- case 0:
- // no method was found: report problem
- scope.problemReporter().javadocInvalidField(this.sourceStart, this.sourceEnd, fieldBinding, this.receiverType, scope.getDeclarationModifiers());
- break;
- case 1:
- // one method binding was found: store binding in specific field
- this.methodBinding = methodBindings[0];
- break;
- }
- }
- }
- return null;
- }
- this.binding = (FieldBinding) fieldBinding;
-
- if (isFieldUseDeprecated(this.binding, scope, (this.bits & IsStrictlyAssigned) != 0)) {
- scope.problemReporter().javadocDeprecatedField(this.binding, this, scope.getDeclarationModifiers());
- }
- return this.resolvedType = this.binding.type;
- }
-
- public boolean isSuperAccess() {
- return (this.bits & ASTNode.SuperAccess) != 0;
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output) {
-
- if (this.receiver != null) {
- this.receiver.printExpression(0, output);
- }
- output.append('#').append(this.token);
- return output;
- }
-
- public TypeBinding resolveType(BlockScope scope) {
- return internalResolveType(scope);
- }
-
- public TypeBinding resolveType(ClassScope scope) {
- return internalResolveType(scope);
- }
-
- /* (non-Javadoc)
- * Redefine to capture javadoc specific signatures
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode#traverse(org.eclipse.wst.jsdt.internal.compiler.ASTVisitor, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public void traverse(ASTVisitor visitor, BlockScope scope) {
-
- if (visitor.visit(this, scope)) {
- if (this.receiver != null) {
- this.receiver.traverse(visitor, scope);
- }
- }
- visitor.endVisit(this, scope);
- }
- public void traverse(ASTVisitor visitor, ClassScope scope) {
-
- if (visitor.visit(this, scope)) {
- if (this.receiver != null) {
- this.receiver.traverse(visitor, scope);
- }
- }
- visitor.endVisit(this, scope);
- }
- public int getASTType() {
- return IASTNode.JSDOC_FIELD_REFERENCE;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocImplicitTypeReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocImplicitTypeReference.java
deleted file mode 100644
index a2c68a3d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocImplicitTypeReference.java
+++ /dev/null
@@ -1,119 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IJsDocImplicitTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-import org.eclipse.wst.jsdt.internal.compiler.impl.Constant;
-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.Scope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class JavadocImplicitTypeReference extends TypeReference implements IJsDocImplicitTypeReference {
-
- public char[] token;
-
- public JavadocImplicitTypeReference(char[] name, int pos) {
- super();
- this.token = name;
- this.sourceStart = pos;
- this.sourceEnd = pos;
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference#copyDims(int)
- */
- public TypeReference copyDims(int dim) {
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference#getTypeBinding(org.eclipse.wst.jsdt.internal.compiler.lookup.Scope)
- */
- protected TypeBinding getTypeBinding(Scope scope) {
- this.constant = Constant.NotAConstant;
- return this.resolvedType = scope.enclosingSourceType();
- }
-
- public char[] getLastToken() {
- return this.token;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference#getTypeName()
- */
- public char[][] getTypeName() {
- if (this.token != null) {
- char[][] tokens = { this.token };
- return tokens;
- }
- return null;
- }
- public boolean isThis() {
- return true;
- }
-
- /*
- * Resolves type on a Block, Class or JavaScriptUnit scope.
- * We need to modify resoling behavior to avoid raw type creation.
- */
- private TypeBinding internalResolveType(Scope scope) {
- // handle the error here
- this.constant = Constant.NotAConstant;
- if (this.resolvedType != null) // is a shared type reference which was already resolved
- return this.resolvedType.isValidBinding() ? this.resolvedType : null; // already reported error
-
- this.resolvedType = scope.enclosingSourceType();
- if (this.resolvedType == null)
- return null; // detected cycle while resolving hierarchy
- if (!this.resolvedType.isValidBinding()) {
- reportInvalidType(scope);
- return null;
- }
- if (isTypeUseDeprecated(this.resolvedType, scope))
- reportDeprecatedType(this.resolvedType, scope);
- return this.resolvedType;
- }
-
- protected void reportInvalidType(Scope scope) {
- scope.problemReporter().javadocInvalidType(this, this.resolvedType, scope.getDeclarationModifiers());
- }
- protected void reportDeprecatedType(TypeBinding type, Scope scope) {
- scope.problemReporter().javadocDeprecatedType(type, this, scope.getDeclarationModifiers());
- }
-
- public TypeBinding resolveType(BlockScope blockScope, boolean checkBounds) {
- return internalResolveType(blockScope);
- }
-
- public TypeBinding resolveType(ClassScope classScope) {
- return internalResolveType(classScope);
- }
-
- public void traverse(ASTVisitor visitor, BlockScope scope) {
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
- }
-
- public void traverse(ASTVisitor visitor, ClassScope scope) {
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output) {
- return new StringBuffer();
- }
- public int getASTType() {
- return IASTNode.JSDOC_IMPLICIT_TYPE_REFERENCE;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocMessageSend.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocMessageSend.java
deleted file mode 100644
index 8af84f24..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocMessageSend.java
+++ /dev/null
@@ -1,249 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IJsDocMessageSend;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-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.ClassScope;
-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.SourceTypeBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-
-public class JavadocMessageSend extends MessageSend implements IJsDocMessageSend {
-
- public int tagSourceStart, tagSourceEnd;
- public int tagValue;
-
- public JavadocMessageSend(char[] name, long pos) {
- this.selector = name;
- this.nameSourcePosition = pos;
- this.sourceStart = (int) (this.nameSourcePosition >>> 32);
- this.sourceEnd = (int) this.nameSourcePosition;
- this.bits |= InsideJavadoc;
- }
- public JavadocMessageSend(char[] name, long pos, JavadocArgumentExpression[] arguments) {
- this(name, pos);
- this.arguments = arguments;
- }
-
- /*
- * Resolves type on a Block or Class scope.
- */
- private TypeBinding internalResolveType(Scope scope) {
- // Answer the signature return type
- // Base type promotion
- this.constant = Constant.NotAConstant;
- if (this.receiver == null) {
- this.actualReceiverType = scope.enclosingSourceType();
- } else if (scope.kind == Scope.CLASS_SCOPE) {
- this.actualReceiverType = this.receiver.resolveType((ClassScope) scope);
- } else {
- this.actualReceiverType = this.receiver.resolveType((BlockScope) scope);
- }
-
- // will check for null after args are resolved
-
- TypeBinding[] argumentTypes = Binding.NO_PARAMETERS;
- boolean hasArgsTypeVar = false;
- if (this.arguments != null) {
- boolean argHasError = false; // typeChecks all arguments
- int length = this.arguments.length;
- argumentTypes = new TypeBinding[length];
- for (int i = 0; i < length; i++){
- Expression argument = this.arguments[i];
- if (scope.kind == Scope.CLASS_SCOPE) {
- argumentTypes[i] = argument.resolveType((ClassScope)scope);
- } else {
- argumentTypes[i] = argument.resolveType((BlockScope)scope);
- }
- if (argumentTypes[i] == null) {
- argHasError = true;
- } else if (!hasArgsTypeVar) {
- hasArgsTypeVar = false;
- }
- }
- if (argHasError) {
- return null;
- }
- }
-
- // check receiver type
- if (this.actualReceiverType == null) {
- return null;
- }
- this.actualReceiverType =(this.receiver!=null)? this.receiver.resolvedType:null;
- SourceTypeBinding enclosingType = scope.enclosingSourceType();
- if (enclosingType==null ? false : enclosingType.isCompatibleWith(this.actualReceiverType)) {
- this.bits |= ASTNode.SuperAccess;
- }
- // base type cannot receive any message
- if (this.actualReceiverType.isBaseType()) {
- return null;
- }
- this.binding = scope.getMethod(this.actualReceiverType, this.selector, argumentTypes, this);
- if (!this.binding.isValidBinding()) {
- // Try method in enclosing types
- TypeBinding enclosingTypeBinding = this.actualReceiverType;
- MethodBinding methodBinding = this.binding;
- while (!methodBinding.isValidBinding() && (enclosingTypeBinding.isMemberType() || enclosingTypeBinding.isLocalType())) {
- enclosingTypeBinding = enclosingTypeBinding.enclosingType();
- methodBinding = scope.getMethod(enclosingTypeBinding, this.selector, argumentTypes, this);
- }
- if (methodBinding.isValidBinding()) {
- this.binding = methodBinding;
- } else {
- // Try to search a constructor instead
- enclosingTypeBinding = this.actualReceiverType;
- MethodBinding contructorBinding = this.binding;
- while (!contructorBinding.isValidBinding() && (enclosingTypeBinding.isMemberType() || enclosingTypeBinding.isLocalType())) {
- enclosingTypeBinding = enclosingTypeBinding.enclosingType();
- if (CharOperation.equals(this.selector, enclosingTypeBinding.shortReadableName())) {
- contructorBinding = scope.getConstructor((ReferenceBinding)enclosingTypeBinding, argumentTypes, this);
- }
- }
- if (contructorBinding.isValidBinding()) {
- this.binding = contructorBinding;
- }
- }
- }
- if (!this.binding.isValidBinding()) {
- // implicit lookup may discover issues due to static/constructor contexts. javadoc must be resilient
- switch (this.binding.problemId()) {
- case ProblemReasons.NonStaticReferenceInConstructorInvocation:
- case ProblemReasons.NonStaticReferenceInStaticContext:
- case ProblemReasons.InheritedNameHidesEnclosingName :
- case ProblemReasons.Ambiguous:
- MethodBinding closestMatch = ((ProblemMethodBinding)this.binding).closestMatch;
- if (closestMatch != null) {
- this.binding = closestMatch; // ignore problem if can reach target method through it
- }
- }
- }
- if (!this.binding.isValidBinding()) {
- if (this.binding.declaringClass == null) {
- if (this.actualReceiverType instanceof ReferenceBinding) {
- this.binding.declaringClass = (ReferenceBinding) this.actualReceiverType;
- } else {
- return null;
- }
- }
- scope.problemReporter().javadocInvalidMethod(this, this.binding, scope.getDeclarationModifiers());
- // record the closest match, for clients who may still need hint about possible method match
- if (this.binding instanceof ProblemMethodBinding) {
- MethodBinding closestMatch = ((ProblemMethodBinding)this.binding).closestMatch;
- if (closestMatch != null) this.binding = closestMatch;
- }
- return this.resolvedType = this.binding == null ? null : this.binding.returnType;
- } else if (hasArgsTypeVar) {
- MethodBinding problem = new ProblemMethodBinding(this.binding, this.selector, argumentTypes, ProblemReasons.NotFound);
- scope.problemReporter().javadocInvalidMethod(this, problem, scope.getDeclarationModifiers());
- } else if (binding.isVarargs()) {
- int length = argumentTypes.length;
- if (!(binding.parameters.length == length && argumentTypes[length-1].isArrayType())) {
- MethodBinding problem = new ProblemMethodBinding(this.binding, this.selector, argumentTypes, ProblemReasons.NotFound);
- scope.problemReporter().javadocInvalidMethod(this, problem, scope.getDeclarationModifiers());
- }
- } else {
- int length = argumentTypes.length;
- for (int i=0; i<length; i++) {
- if (this.binding.parameters[i] != argumentTypes[i]) {
- MethodBinding problem = new ProblemMethodBinding(this.binding, this.selector, argumentTypes, ProblemReasons.NotFound);
- scope.problemReporter().javadocInvalidMethod(this, problem, scope.getDeclarationModifiers());
- break;
- }
- }
- }
- if (isMethodUseDeprecated(this.binding, scope, true)) {
- scope.problemReporter().javadocDeprecatedMethod(this.binding, this, scope.getDeclarationModifiers());
- }
-
- return this.resolvedType = this.binding.returnType;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.lookup.InvocationSite#isSuperAccess()
- */
- public boolean isSuperAccess() {
- return (this.bits & ASTNode.SuperAccess) != 0;
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output){
-
- if (this.receiver != null) {
- this.receiver.printExpression(0, output);
- }
- output.append('#').append(this.selector).append('(');
- if (this.arguments != null) {
- for (int i = 0; i < this.arguments.length ; i ++) {
- if (i > 0) output.append(", "); //$NON-NLS-1$
- this.arguments[i].printExpression(0, output);
- }
- }
- return output.append(')');
- }
-
- public TypeBinding resolveType(BlockScope scope) {
- return internalResolveType(scope);
- }
-
- public TypeBinding resolveType(ClassScope scope) {
- return internalResolveType(scope);
- }
-
- /* (non-Javadoc)
- * Redefine to capture javadoc specific signatures
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode#traverse(org.eclipse.wst.jsdt.internal.compiler.ASTVisitor, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public void traverse(ASTVisitor visitor, BlockScope blockScope) {
- if (visitor.visit(this, blockScope)) {
- if (this.receiver != null) {
- this.receiver.traverse(visitor, blockScope);
- }
- if (this.arguments != null) {
- int argumentsLength = this.arguments.length;
- for (int i = 0; i < argumentsLength; i++)
- this.arguments[i].traverse(visitor, blockScope);
- }
- }
- visitor.endVisit(this, blockScope);
- }
- /* (non-Javadoc)
- * Redefine to capture javadoc specific signatures
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode#traverse(org.eclipse.wst.jsdt.internal.compiler.ASTVisitor, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public void traverse(ASTVisitor visitor, ClassScope scope) {
- if (visitor.visit(this, scope)) {
- if (this.receiver != null) {
- this.receiver.traverse(visitor, scope);
- }
- if (this.arguments != null) {
- int argumentsLength = this.arguments.length;
- for (int i = 0; i < argumentsLength; i++)
- this.arguments[i].traverse(visitor, scope);
- }
- }
- visitor.endVisit(this, scope);
- }
- public int getASTType() {
- return IASTNode.JSDOC_MESSAGE_SEND;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocQualifiedTypeReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocQualifiedTypeReference.java
deleted file mode 100644
index f66b1970..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocQualifiedTypeReference.java
+++ /dev/null
@@ -1,92 +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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IJsDocQualifiedTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-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.ClassScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Scope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-
-public class JavadocQualifiedTypeReference extends QualifiedTypeReference implements IJsDocQualifiedTypeReference {
-
- public int tagSourceStart, tagSourceEnd;
- public PackageBinding packageBinding;
-
- public JavadocQualifiedTypeReference(char[][] sources, long[] pos, int tagStart, int tagEnd) {
- super(sources, pos);
- this.tagSourceStart = tagStart;
- this.tagSourceEnd = tagEnd;
- this.bits |= ASTNode.InsideJavadoc;
- }
-
- protected void reportInvalidType(Scope scope) {
- scope.problemReporter().javadocInvalidType(this, this.resolvedType, scope.getDeclarationModifiers());
- }
- protected void reportDeprecatedType(TypeBinding type, Scope scope) {
- scope.problemReporter().javadocDeprecatedType(type, this, scope.getDeclarationModifiers());
- }
-
- /* (non-Javadoc)
- * Redefine to capture javadoc specific signatures
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode#traverse(org.eclipse.wst.jsdt.internal.compiler.ASTVisitor, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public void traverse(ASTVisitor visitor, BlockScope scope) {
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
- }
- public void traverse(ASTVisitor visitor, ClassScope scope) {
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
- }
-
- /*
- * We need to modify resolving behavior to handle package references
- */
- private TypeBinding internalResolveType(Scope scope, boolean checkBounds) {
- // handle the error here
- this.constant = Constant.NotAConstant;
- if (this.resolvedType != null) // is a shared type reference which was already resolved
- return this.resolvedType.isValidBinding() ? this.resolvedType : null; // already reported error
-
- this.resolvedType = getTypeBinding(scope);
- if (!this.resolvedType.isValidBinding()) {
- Binding binding = scope.getTypeOrPackage(this.tokens);
- if (binding instanceof PackageBinding) {
- this.packageBinding = (PackageBinding) binding;
- } else {
- reportInvalidType(scope);
- }
- return null;
- }
- if (isTypeUseDeprecated(this.resolvedType, scope))
- reportDeprecatedType(this.resolvedType, scope);
- return this.resolvedType;
- }
-
- public TypeBinding resolveType(BlockScope blockScope, boolean checkBounds) {
- return internalResolveType(blockScope, checkBounds);
- }
-
- public TypeBinding resolveType(ClassScope classScope) {
- return internalResolveType(classScope, false);
- }
- public int getASTType() {
- return IASTNode.JSDOC_QUALIFIED_TYPE_REFERENCE;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocReturnStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocReturnStatement.java
deleted file mode 100644
index c117e036..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocReturnStatement.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IJsDocReturnStatement;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-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.MethodBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-
-public class JavadocReturnStatement extends ReturnStatement implements IJsDocReturnStatement {
-
- public JavadocReturnStatement(int s, int e) {
- super(null, s, e);
- this.bits |= (ASTNode.InsideJavadoc | ASTNode.Empty);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.Statement#resolve(org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public void resolve(BlockScope scope) {
- MethodScope methodScope = scope.methodScope();
- MethodBinding methodBinding = null;
- TypeBinding methodType =
- (methodScope.referenceContext instanceof AbstractMethodDeclaration)
- ? ((methodBinding = ((AbstractMethodDeclaration) methodScope.referenceContext).binding) == null
- ? null
- : methodBinding.returnType)
- : TypeBinding.VOID;
- if (methodType == null || methodType == TypeBinding.VOID) {
- scope.problemReporter().javadocUnexpectedTag(this.sourceStart, this.sourceEnd);
- } else if ((this.bits & ASTNode.Empty) != 0) {
- scope.problemReporter().javadocEmptyReturnTag(this.sourceStart, this.sourceEnd, scope.getDeclarationModifiers());
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.Statement#printStatement(int, java.lang.StringBuffer)
- */
- public StringBuffer printStatement(int tab, StringBuffer output) {
- printIndent(tab, output).append("return"); //$NON-NLS-1$
- if ((this.bits & ASTNode.Empty) == 0)
- output.append(' ').append(" <not empty>"); //$NON-NLS-1$
- return output;
- }
-
- /* (non-Javadoc)
- * Redefine to capture javadoc specific signatures
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode#traverse(org.eclipse.wst.jsdt.internal.compiler.ASTVisitor, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public void traverse(ASTVisitor visitor, BlockScope scope) {
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
- }
- /* (non-Javadoc)
- * Redefine to capture javadoc specific signatures
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode#traverse(org.eclipse.wst.jsdt.internal.compiler.ASTVisitor, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public void traverse(ASTVisitor visitor, ClassScope scope) {
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
- }
- public int getASTType() {
- return IASTNode.JSDOC_RETURN_STATEMENT;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocSingleNameReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocSingleNameReference.java
deleted file mode 100644
index f20beafb..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocSingleNameReference.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IJsDocSingleNameReference;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-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.LocalVariableBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TagBits;
-
-public class JavadocSingleNameReference extends SingleNameReference implements IJsDocSingleNameReference {
-
- public int tagSourceStart, tagSourceEnd;
- public TypeReference []types;
-
- public JavadocSingleNameReference(char[] source, long pos, int tagStart, int tagEnd) {
- super(source, pos);
- this.tagSourceStart = tagStart;
- this.tagSourceEnd = tagEnd;
- this.bits |= InsideJavadoc;
- }
-
- public void resolve(BlockScope scope) {
- resolve(scope, true, scope.compilerOptions().reportUnusedParameterIncludeDocCommentReference);
- }
-
- /**
- * Resolve without warnings
- */
- public void resolve(BlockScope scope, boolean warn, boolean considerParamRefAsUsage) {
-
- LocalVariableBinding variableBinding = scope.findVariable(this.token);
- if (variableBinding != null && variableBinding.isValidBinding() && ((variableBinding.tagBits & TagBits.IsArgument) != 0)) {
- this.binding = variableBinding;
- if (considerParamRefAsUsage) {
- variableBinding.useFlag = LocalVariableBinding.USED;
- }
- return;
- }
- if (warn) {
- try {
- MethodScope methScope = (MethodScope) scope;
- scope.problemReporter().javadocUndeclaredParamTagName(this.token, this.sourceStart, this.sourceEnd, methScope.referenceMethod().modifiers);
- }
- catch (Exception e) {
- scope.problemReporter().javadocUndeclaredParamTagName(this.token, this.sourceStart, this.sourceEnd, -1);
- }
- }
- }
-
- /* (non-Javadoc)
- * Redefine to capture javadoc specific signatures
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode#traverse(org.eclipse.wst.jsdt.internal.compiler.ASTVisitor, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public void traverse(ASTVisitor visitor, BlockScope scope) {
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
- }
- /* (non-Javadoc)
- * Redefine to capture javadoc specific signatures
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode#traverse(org.eclipse.wst.jsdt.internal.compiler.ASTVisitor, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public void traverse(ASTVisitor visitor, ClassScope scope) {
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output){
-
- if (types!=null && types.length>0)
- {
- output.append("{"); //$NON-NLS-1$
- for (int i = 0; i < types.length; i++) {
- if (i>0)
- output.append('|');
- types[i].printExpression(indent, output);
- }
- output.append("} "); //$NON-NLS-1$
- }
- output=super.printExpression(indent, output);
- return output;
- }
- public int getASTType() {
- return IASTNode.JSDOC_SINGLE_NAME_REFERENCE;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocSingleTypeReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocSingleTypeReference.java
deleted file mode 100644
index 50cb7138..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/JavadocSingleTypeReference.java
+++ /dev/null
@@ -1,104 +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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IJsDocSingleTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-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.ClassScope;
-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.Scope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-
-public class JavadocSingleTypeReference extends SingleTypeReference implements IJsDocSingleTypeReference {
-
- public int tagSourceStart, tagSourceEnd;
- public PackageBinding packageBinding;
-
- public JavadocSingleTypeReference(char[] source, long pos, int tagStart, int tagEnd) {
- super(source, pos);
- this.tagSourceStart = tagStart;
- this.tagSourceEnd = tagEnd;
- this.bits |= ASTNode.InsideJavadoc;
- }
-
- protected void reportInvalidType(Scope scope) {
- scope.problemReporter().javadocInvalidType(this, this.resolvedType, scope.getDeclarationModifiers());
- }
- protected void reportDeprecatedType(TypeBinding type, Scope scope) {
- scope.problemReporter().javadocDeprecatedType(type, this, scope.getDeclarationModifiers());
- }
-
- /* (non-Javadoc)
- * Redefine to capture javadoc specific signatures
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode#traverse(org.eclipse.wst.jsdt.internal.compiler.ASTVisitor, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public void traverse(ASTVisitor visitor, BlockScope scope) {
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
- }
-
- public void traverse(ASTVisitor visitor, ClassScope scope) {
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
- }
-
- /*
- * We need to modify resolving behavior to handle package references
- */
- TypeBinding internalResolveType(Scope scope) {
- // handle the error here
- this.constant = Constant.NotAConstant;
- if (this.resolvedType != null)// is a shared type reference which was already resolved
- return this.resolvedType.isValidBinding() ? this.resolvedType : null; // already reported error
-
- this.resolvedType = getTypeBinding(scope);
- if (!this.resolvedType.isValidBinding()) {
- char[][] tokens = { this.token };
- Binding binding = scope.getTypeOrPackage(tokens);
- if (binding instanceof PackageBinding) {
- this.packageBinding = (PackageBinding) binding;
- } else {
- if (this.resolvedType.problemId() == ProblemReasons.NonStaticReferenceInStaticContext) {
- ReferenceBinding closestMatch = ((ProblemReferenceBinding)this.resolvedType).closestMatch();
- }
- reportInvalidType(scope);
- }
- return null;
- }
- if (isTypeUseDeprecated(this.resolvedType, scope))
- reportDeprecatedType(this.resolvedType, scope);
- return this.resolvedType;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.Expression#resolveType(org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- * We need to override to handle package references
- */
- public TypeBinding resolveType(BlockScope blockScope, boolean checkBounds) {
- return internalResolveType(blockScope);
- }
-
- public TypeBinding resolveType(ClassScope classScope) {
- return internalResolveType(classScope);
- }
- public int getASTType() {
- return IASTNode.JSDOC_SINGLE_TYPE_REFERENCE;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/LabeledStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/LabeledStatement.java
deleted file mode 100644
index f57aa518..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/LabeledStatement.java
+++ /dev/null
@@ -1,122 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.ILabeledStatement;
-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;
-import org.eclipse.wst.jsdt.internal.compiler.flow.LabelFlowContext;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-
-public class LabeledStatement extends Statement implements ILabeledStatement {
-
- public Statement statement;
- public char[] label;
- public int labelEnd;
-
- // for local variables table attributes
- int mergedInitStateIndex = -1;
-
- /**
- * LabeledStatement constructor comment.
- */
- public LabeledStatement(char[] label, Statement statement, long labelPosition, int sourceEnd) {
-
- this.statement = statement;
- // remember useful empty statement
- if (statement instanceof EmptyStatement) statement.bits |= IsUsefulEmptyStatement;
- this.label = label;
- this.sourceStart = (int)(labelPosition >>> 32);
- this.labelEnd = (int) labelPosition;
- this.sourceEnd = sourceEnd;
- }
-
- public FlowInfo analyseCode(
- BlockScope currentScope,
- FlowContext flowContext,
- FlowInfo flowInfo) {
-
- // need to stack a context to store explicit label, answer inits in case of normal completion merged
- // with those relative to the exit path from break statement occurring inside the labeled statement.
- if (statement == null) {
- return flowInfo;
- } else {
- LabelFlowContext labelContext;
- FlowInfo statementInfo, mergedInfo;
- if (((statementInfo = statement
- .analyseCode(
- currentScope,
- (labelContext =
- new LabelFlowContext(
- flowContext,
- this,
- label,
- currentScope)),
- flowInfo)).tagBits & FlowInfo.UNREACHABLE) != 0) {
- if ((labelContext.initsOnBreak.tagBits & FlowInfo.UNREACHABLE) == 0) {
- // an embedded loop has had no chance to reinject forgotten null info
- mergedInfo = flowInfo.unconditionalCopy().
- addInitializationsFrom(labelContext.initsOnBreak);
- } else {
- mergedInfo = labelContext.initsOnBreak;
- }
- } else {
- mergedInfo = statementInfo.mergedWith(labelContext.initsOnBreak);
- }
-// mergedInitStateIndex =
-// currentScope.methodScope().recordInitializationStates(mergedInfo);
- if ((this.bits & ASTNode.LabelUsed) == 0) {
- currentScope.problemReporter().unusedLabel(this);
- }
- return mergedInfo;
- }
- }
-
- public ASTNode concreteStatement() {
-
- // return statement.concreteStatement(); // for supporting nested labels: a:b:c: someStatement (see 21912)
- return statement;
- }
-
- public StringBuffer printStatement(int tab, StringBuffer output) {
-
- printIndent(tab, output).append(label).append(": "); //$NON-NLS-1$
- if (this.statement == null)
- output.append(';');
- else
- this.statement.printStatement(0, output);
- return output;
- }
-
- public void resolve(BlockScope scope) {
-
- if (this.statement != null) {
- this.statement.resolve(scope);
- }
- }
-
-
- public void traverse(
- ASTVisitor visitor,
- BlockScope blockScope) {
-
- if (visitor.visit(this, blockScope)) {
- if (this.statement != null) this.statement.traverse(visitor, blockScope);
- }
- visitor.endVisit(this, blockScope);
- }
- public int getASTType() {
- return IASTNode.LABELED_STATEMENT;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ListExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ListExpression.java
deleted file mode 100644
index 731c810a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ListExpression.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IListExpression;
-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;
-import org.eclipse.wst.jsdt.internal.compiler.impl.Constant;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class ListExpression extends Expression implements IListExpression {
-
-/* Tracking helpers
- * The following are used to elaborate realistic statistics about binary
- * expressions. This must be neutralized in the released code.
- * Search the keyword BE_INSTRUMENTATION to reenable.
- * An external device must install a suitable probe so as to monitor the
- * emission of events and publish the results.
- public interface Probe {
- public void ping(int depth);
- }
- public int depthTracker;
- public static Probe probe;
- */
-
- public Expression []expressions;
- public Constant optimizedBooleanConstant;
-
-public ListExpression(Expression expression1, Expression expression2) {
- if (expression1 instanceof ListExpression)
- {
- ListExpression expr1=(ListExpression)expression1;
- this.expressions=new Expression[expr1.expressions.length+1];
- System.arraycopy(expr1.expressions, 0, this.expressions, 0, expr1.expressions.length);
- this.expressions[this.expressions.length-1]=expression2;
- }
- else
- this.expressions=new Expression[]{expression1,expression2};
- this.sourceStart = expressions[0].sourceStart;
- this.sourceEnd = expressions[expressions.length-1].sourceEnd;
-}
-
-public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext,
- FlowInfo flowInfo) {
- // keep implementation in sync with CombinedBinaryExpression#analyseCode
- for (int i=0; i<this.expressions.length; i++)
- {
- this.expressions[i].checkNPE(currentScope, flowContext, flowInfo);
- flowInfo = this.expressions[i].analyseCode(currentScope, flowContext, flowInfo).unconditionalInits();
- }
- return flowInfo;
-}
-
-
-public boolean isCompactableOperation() {
- return true;
-}
-
-
-
-public TypeBinding resolveType(BlockScope scope) {
- // keep implementation in sync with CombinedBinaryExpression#resolveType
- // and nonRecursiveResolveTypeUpwards
-
- this.constant = Constant.NotAConstant;
-
- for (int i = 0; i < this.expressions.length; i++) {
- this.resolvedType=this.expressions[i].resolveType(scope);
- this.constant = this.expressions[i].constant;
- }
-
- return this.resolvedType;
-}
-
-public void traverse(ASTVisitor visitor, BlockScope scope) {
- if (visitor.visit(this, scope)) {
- for (int i = 0; i < this.expressions.length; i++)
- this.expressions[i].traverse(visitor, scope);
- }
- visitor.endVisit(this, scope);
-}
-
-public StringBuffer printExpression(int indent, StringBuffer output) {
- output.append('(');
- for (int i = 0; i < this.expressions.length; i++) {
- if (i>0)
- output.append(", "); //$NON-NLS-1$
- this.expressions[i].printExpression(indent, output);
- }
- output.append(')');
- return output;
-}
-public int getASTType() {
- return IASTNode.LIST_EXPRESSION;
-
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Literal.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Literal.java
deleted file mode 100644
index e8f2c7d7..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Literal.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.ILiteral;
-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.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public abstract class Literal extends Expression implements ILiteral {
-
- public Literal(int s, int e) {
-
- sourceStart = s;
- sourceEnd = e;
- }
-
- public FlowInfo analyseCode(
- BlockScope currentScope,
- FlowContext flowContext,
- FlowInfo flowInfo) {
-
- return flowInfo;
- }
-
- public abstract void computeConstant();
-
- public abstract TypeBinding literalType(BlockScope scope);
-
- public StringBuffer printExpression(int indent, StringBuffer output){
-
- return output.append(source());
- }
-
- public TypeBinding resolveType(BlockScope scope) {
- // compute the real value, which must range its type's range
- this.resolvedType = literalType(scope);
-
- // in case of error, constant did remain null
- computeConstant();
- if (constant == null) {
- scope.problemReporter().constantOutOfRange(this, this.resolvedType);
- constant = Constant.NotAConstant;
- }
- return this.resolvedType;
- }
-
- public abstract char[] source();
-
- public int getASTType() {
- return IASTNode.LITERAL;
-
- }
-}
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
deleted file mode 100644
index 1657e7dd..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/LocalDeclaration.java
+++ /dev/null
@@ -1,332 +0,0 @@
-/*******************************************************************************
- * 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.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.ILocalDeclaration;
-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.lookup.ArrayBinding;
-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.CompilationUnitScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ExtraCompilerModifiers;
-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.TypeBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.VariableBinding;
-
-public class LocalDeclaration extends AbstractVariableDeclaration implements ILocalDeclaration {
-
- public LocalVariableBinding binding;
-
- public LocalDeclaration(
- char[] name,
- int sourceStart,
- int sourceEnd) {
-
- this.name = name;
- this.sourceStart = sourceStart;
- this.sourceEnd = sourceEnd;
- this.declarationEnd = sourceEnd;
- }
-
- public IAssignment getAssignment() {
- if (this.initialization == null)
- return null;
- if (initialization instanceof FunctionExpression && ((FunctionExpression) initialization).getMethodDeclaration().getName() == null) {
- 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
- }
- 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);
- }
- flowInfo.markAsDefinitelyAssigned(binding);
- if ( true){//(this.binding.type.tagBits & TagBits.IsBaseType) == 0) {
- switch(nullStatus) {
- case FlowInfo.NULL :
- flowInfo.markAsDefinitelyNull(this.binding);
- break;
- case FlowInfo.NON_NULL :
- flowInfo.markAsDefinitelyNonNull(this.binding);
- break;
- 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;
-}
-
- public void checkModifiers() {
-
- //only potential valid modifier is <<final>>
- 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;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ast.AbstractVariableDeclaration#getKind()
- */
- public int getKind() {
- return LOCAL_VARIABLE;
- }
-
- public TypeBinding resolveVarType(BlockScope scope)
- {
- TypeBinding variableType = null;
-
- if (type!=null)
- variableType=type.resolveType(scope, true /* check bounds*/);
- else {
- if (inferredType!=null)
- variableType=inferredType.resolveType(scope,this);
- else
- variableType=TypeBinding.UNKNOWN;
- }
-
-
- checkModifiers();
- return variableType;
-
- }
-
- public void resolve(BlockScope scope) {
- resolve0(scope);
- if (this.nextLocal!=null)
- this.nextLocal.resolve(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);
- }
- 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;
- }
- 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);
- }
- }
- }
-
- if ((modifiers & ClassFileConstants.AccFinal)!= 0 && this.initialization == null) {
- modifiers |= ExtraCompilerModifiers.AccBlankFinal;
- }
- if (!(this.binding!=null && alreadyDefined))
- {
- this.binding = new LocalVariableBinding(this, variableType, modifiers, false);
- MethodScope methodScope = scope.enclosingMethodScope();
- if (methodScope!=null)
- methodScope.addLocalVariable(binding);
- 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
- return;
- }
-
- // store the constant for final locals
- if (initialization != null) {
- if (initialization instanceof ArrayInitializer) {
- TypeBinding initializationType = initialization.resolveTypeExpecting(scope, variableType);
- if (initializationType != null) {
- ((ArrayInitializer) initialization).binding = (ArrayBinding) initializationType;
- }
- } 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;
- existingMethod.updateFrom(functionBinding);
- }
- }
- 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);
- }
- }
- }
- }
- // 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);
- }
- return super.printStatement(indent, output);
- }
-
- public void traverse(ASTVisitor visitor, BlockScope scope) {
-
- if (visitor.visit(this, scope)) {
- if (type!=null)
- type.traverse(visitor, scope);
- IAssignment assignment = getAssignment();
- if (assignment != null) {
- ((Assignment) assignment).traverse(visitor, scope);
- }
- else if (initialization != null)
- initialization.traverse(visitor, scope);
- }
- visitor.endVisit(this, scope);
- if (this.nextLocal!=null)
- this.nextLocal.traverse(visitor, scope);
- }
-
- public String getTypeName()
- {
- if (type!=null)
- return type.toString();
- if (inferredType!=null)
- return new String(inferredType.getName());
- return null;
- }
- public int getASTType() {
- return IASTNode.LOCAL_DECLARATION;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/MagicLiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/MagicLiteral.java
deleted file mode 100644
index f58a6a97..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/MagicLiteral.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IMagicLiteral;
-
-public abstract class MagicLiteral extends Literal implements IMagicLiteral {
-
- public MagicLiteral(int start , int end) {
-
- super(start,end);
- }
-
- public boolean isValidJavaStatement(){
-
- return false ;
- }
-
- public char[] source() {
-
- return null;
- }
- public int getASTType() {
- return IASTNode.MAGIC_LITERAL;
-
- }
-}
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
deleted file mode 100644
index 6b0c4fac..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/MessageSend.java
+++ /dev/null
@@ -1,472 +0,0 @@
-/*******************************************************************************
- * 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
- * Nick Teryaev - fix for bug (https://bugs.eclipse.org/bugs/show_bug.cgi?id=40752)
- *******************************************************************************/
-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.IFunctionCall;
-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;
-import org.eclipse.wst.jsdt.internal.compiler.impl.CompilerOptions;
-import org.eclipse.wst.jsdt.internal.compiler.impl.Constant;
-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.IndirectMethodBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.InvocationSite;
-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.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;
-
-public class MessageSend extends Expression implements InvocationSite, IFunctionCall {
-
- 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)
-
- public long nameSourcePosition ; //(start<<32)+end
-
- 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);
- }
- }
- 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 (arguments != null) {
- int length = arguments.length;
- for (int i = 0; i < length; i++) {
- flowInfo = arguments[i].analyseCode(currentScope, flowContext, flowInfo).unconditionalInits();
- }
- }
- 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;
-// }
- }
-
- // 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 :
- }
- 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('.');
- }
- 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(')');
-}
-
-public TypeBinding resolveType(BlockScope scope) {
- // Answer the signature return type
- // Base type promotion
-
- 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 (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;
- }
- }
- 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;
- }
- }
- }
- }
- 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 (!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;
- }
- 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);
- }
- } 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);
- }
- }
- }
-// checkInvocationArguments(scope, this.receiver, actualReceiverType, binding, this.arguments, argumentTypes, argsContainCast, this);
-
- if (isMethodUseDeprecated(binding, scope, true))
- scope.problemReporter().deprecatedMethod(binding, this);
-
-
- 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;
-}
-
-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;
-}
-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);
- }
- }
- visitor.endVisit(this, blockScope);
-}
-public int getASTType() {
- return IASTNode.FUNCTION_CALL;
-
-}
-
-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
deleted file mode 100644
index 7d34022f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/MethodDeclaration.java
+++ /dev/null
@@ -1,184 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IFunctionDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-import org.eclipse.wst.jsdt.internal.compiler.CompilationResult;
-import org.eclipse.wst.jsdt.internal.compiler.flow.ExceptionHandlingFlowContext;
-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.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ExtraCompilerModifiers;
-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.parser.Parser;
-import org.eclipse.wst.jsdt.internal.compiler.problem.AbortMethod;
-
-public class MethodDeclaration extends AbstractMethodDeclaration implements IFunctionDeclaration {
-
- public TypeReference returnType;
-
- /**
- * FunctionDeclaration constructor comment.
- */
- public MethodDeclaration(CompilationResult compilationResult) {
- super(compilationResult);
- }
-
- public FlowInfo analyseCode(
- Scope classScope,
- FlowContext initializationContext,
- FlowInfo flowInfo) {
-
- // starting of the code analysis for methods
- if (ignoreFurtherInvestigation)
- return flowInfo;
- try {
- if (binding == null)
- return flowInfo;
-
- if (!this.binding.isUsed() &&
- (this.binding.isPrivate()
- || (((this.binding.modifiers & (ExtraCompilerModifiers.AccOverriding|ExtraCompilerModifiers.AccImplementing)) == 0) && this.binding.declaringClass.isLocalType()))) {
- if (!classScope.referenceCompilationUnit().compilationResult.hasSyntaxError) {
- scope.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 <clinit> for innerclass with static final constant fields
- if (binding.isAbstract())
- return flowInfo;
-
- ExceptionHandlingFlowContext methodContext =
- new ExceptionHandlingFlowContext(
- initializationContext,
- this,
- null,
- scope,
- FlowInfo.DEAD_END);
-
- // tag parameters as being set
- if (this.arguments != null) {
- for (int i = 0, count = this.arguments.length; i < count; i++) {
- flowInfo.markAsDefinitelyAssigned(this.arguments[i].getBinding());
- }
- }
- // propagate to statements
- if (statements != null) {
- 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 instanceof AbstractMethodDeclaration) {
- ((AbstractMethodDeclaration)stat).analyseCode(this.scope, null, flowInfo.copy());
- } else
- flowInfo = stat.analyseCode(scope, methodContext, flowInfo);
- } else {
- didAlreadyComplain = true;
- }
- }
- }
- // check for missing returning path
- TypeBinding returnTypeBinding = binding.returnType;
- boolean isJsDocInferredReturn = (binding.tagBits&TagBits.IsInferredJsDocType)!=0;
- if ((returnTypeBinding == TypeBinding.VOID || returnTypeBinding == TypeBinding.UNKNOWN) || isAbstract()) {
- this.needFreeReturn =
- (flowInfo.tagBits & FlowInfo.UNREACHABLE) == 0;
- } else {
- if (flowInfo != FlowInfo.DEAD_END) {
- if ((this.inferredMethod==null || !this.inferredMethod.isConstructor) &&
- !isJsDocInferredReturn)
- scope.problemReporter().shouldReturn(returnTypeBinding, this);
- }
- }
- this.scope.reportUnusedDeclarations();
- // check unreachable catch blocks
- if (JavaScriptCore.IS_ECMASCRIPT4)
- methodContext.complainIfUnusedExceptionHandlers(this);
- } catch (AbortMethod e) {
- this.ignoreFurtherInvestigation = true;
- }
- return flowInfo;
- }
-
- public boolean isMethod() {
-
- return true;
- }
-
- public void parseStatements(Parser parser, CompilationUnitDeclaration unit) {
-
- //fill up the method body with statement
- if (ignoreFurtherInvestigation)
- return;
- parser.parse(this, unit);
- }
-
- public void resolveStatements() {
-
- // ========= abort on fatal error =============
-
- super.resolveStatements();
- }
-
- public void traverse(
- ASTVisitor visitor,
- Scope classScope) {
-
- if (visitor.visit(this, classScope)) {
- if (this.javadoc != null) {
- this.javadoc.traverse(visitor, scope);
- }
- 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);
- }
- }
- 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);
- }
- }
- 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/NameReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/NameReference.java
deleted file mode 100644
index 93a3ff48..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/NameReference.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.INameReference;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Binding;
-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.LocalVariableBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public abstract class NameReference extends Reference implements INameReference, InvocationSite {
-
- public Binding binding;//, codegenBinding; //may be aTypeBinding-aFieldBinding-aLocalVariableBinding
-
- public TypeBinding actualReceiverType; // modified receiver type - actual one according to namelookup
-
- //the error printing
- //some name reference are build as name reference but
- //only used as type reference. When it happens, instead of
- //creating a new objet (aTypeReference) we just flag a boolean
- //This concesion is valuable while their are cases when the NameReference
- //will be a TypeReference (static message sends.....) and there is
- //no changeClass in java.
-public NameReference() {
- super();
- bits |= Binding.TYPE | Binding.VARIABLE; // restrictiveFlag
-
-}
-public FieldBinding fieldBinding() {
- //this method should be sent ONLY after a check against isFieldReference()
- //check its use doing senders.........
-
- return (FieldBinding) binding ;
-}
-public boolean isSuperAccess() {
- return false;
-}
-public boolean isTypeAccess() {
- // null is acceptable when we are resolving the first part of a reference
- return binding == null || binding instanceof ReferenceBinding;
-}
-public boolean isTypeReference() {
- return binding instanceof ReferenceBinding;
-}
-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
- }
-}
-public void setFieldIndex(int index){
- // ignored
-}
-
-public abstract String unboundReferenceErrorName();
-
-public Binding alternateBinding()
-{
- Binding alternateBinding = binding;
- if (alternateBinding instanceof MethodBinding && ((MethodBinding)alternateBinding).isConstructor())
- {
- MethodBinding constructorBinding=(MethodBinding)alternateBinding;
- alternateBinding=constructorBinding.returnType;
- } else if(alternateBinding instanceof LocalVariableBinding) {
- if(((LocalVariableBinding)alternateBinding).type instanceof FunctionTypeBinding) {
- FunctionTypeBinding functionBinding = (FunctionTypeBinding)((LocalVariableBinding)alternateBinding).type;
- if(functionBinding.functionBinding.isConstructor()) {
- alternateBinding = functionBinding.functionBinding.returnType;
- }
- }
- }
-
- return alternateBinding;
-
-
-}
-public int getASTType() {
- return IASTNode.NAME_REFERENCE;
-
-}
-}
-
-
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/NullLiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/NullLiteral.java
deleted file mode 100644
index c1fda774..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/NullLiteral.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.INullLiteral;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-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.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class NullLiteral extends MagicLiteral implements INullLiteral {
-
- static final char[] source = {'n' , 'u' , 'l' , 'l'};
-
- public NullLiteral(int s , int e) {
-
- super(s,e);
- }
-
- public void computeConstant() {
-
- constant = Constant.NotAConstant;
- }
-
- public TypeBinding literalType(BlockScope scope) {
- return TypeBinding.NULL;
- }
-
- public int nullStatus(FlowInfo flowInfo) {
- return FlowInfo.NULL;
- }
-
- public Object reusableJSRTarget() {
- return TypeBinding.NULL;
- }
-
- public char[] source() {
- return source;
- }
-
- public void traverse(ASTVisitor visitor, BlockScope scope) {
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
- }
- public int getASTType() {
- return IASTNode.NULL_LITERAL;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/NumberLiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/NumberLiteral.java
deleted file mode 100644
index 2ae32ea7..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/NumberLiteral.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.INumberLiteral;
-
-public abstract class NumberLiteral extends Literal implements INumberLiteral {
-
- public char[] source;
-
- public NumberLiteral(char[] token, int s, int e) {
-
- this(s,e) ;
- source = token ;
- }
-
- public NumberLiteral(int s, int e) {
- super (s,e) ;
- }
-
- public boolean isValidJavaStatement(){
-
- return false ;
- }
-
- public char[] source(){
-
- return source;
- }
- public int getASTType() {
- return IASTNode.NUMBER_LITERAL;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/OR_OR_Expression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/OR_OR_Expression.java
deleted file mode 100644
index 2c4204f9..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/OR_OR_Expression.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IOR_OR_Expression;
-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;
-import org.eclipse.wst.jsdt.internal.compiler.impl.Constant;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-
-//dedicated treatment for the ||
-public class OR_OR_Expression extends BinaryExpression implements IOR_OR_Expression {
-
- int rightInitStateIndex = -1;
- int mergedInitStateIndex = -1;
-
- public OR_OR_Expression(Expression left, Expression right, int operator) {
- super(left, right, operator);
- }
-
- public FlowInfo analyseCode(
- BlockScope currentScope,
- FlowContext flowContext,
- FlowInfo flowInfo) {
-
- Constant cst = this.left.optimizedBooleanConstant();
- boolean isLeftOptimizedTrue = cst != Constant.NotAConstant && cst.booleanValue() == true;
- boolean isLeftOptimizedFalse = cst != Constant.NotAConstant && cst.booleanValue() == false;
-
- if (isLeftOptimizedFalse) {
- // FALSE || anything
- // need to be careful of scenario:
- // (x || y) || !z, if passing the left info to the right, it would be swapped by the !
- FlowInfo mergedInfo = left.analyseCode(currentScope, flowContext, flowInfo).unconditionalInits();
- mergedInfo = right.analyseCode(currentScope, flowContext, mergedInfo);
-// mergedInitStateIndex =
-// currentScope.methodScope().recordInitializationStates(mergedInfo);
- return mergedInfo;
- }
-
- FlowInfo leftInfo = left.analyseCode(currentScope, flowContext, flowInfo);
-
- // need to be careful of scenario:
- // (x || y) || !z, if passing the left info to the right, it would be swapped by the !
- FlowInfo rightInfo = leftInfo.initsWhenFalse().unconditionalCopy();
-// rightInitStateIndex =
-// currentScope.methodScope().recordInitializationStates(rightInfo);
-
- int previousMode = rightInfo.reachMode();
- if (isLeftOptimizedTrue){
- rightInfo.setReachMode(FlowInfo.UNREACHABLE);
- }
- rightInfo = right.analyseCode(currentScope, flowContext, rightInfo);
- FlowInfo mergedInfo = FlowInfo.conditional(
- // merging two true initInfos for such a negative case: if ((t && (b = t)) || f) r = b; // b may not have been initialized
- leftInfo.initsWhenTrue().unconditionalInits().mergedWith(
- rightInfo.safeInitsWhenTrue().setReachMode(previousMode).unconditionalInits()),
- rightInfo.initsWhenFalse());
-// mergedInitStateIndex =
-// currentScope.methodScope().recordInitializationStates(mergedInfo);
- return mergedInfo;
- }
-
- public boolean isCompactableOperation() {
- return false;
- }
-
- public void traverse(ASTVisitor visitor, BlockScope scope) {
- if (visitor.visit(this, scope)) {
- left.traverse(visitor, scope);
- right.traverse(visitor, scope);
- }
- visitor.endVisit(this, scope);
- }
- public int getASTType() {
- return IASTNode.OR_OR_EXPRESSION;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ObjectGetterSetterField.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ObjectGetterSetterField.java
deleted file mode 100644
index 8caed4a5..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ObjectGetterSetterField.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*******************************************************************************
- * 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.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.IJsDoc;
-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;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class ObjectGetterSetterField extends ObjectLiteralField implements IExpression {
-
- public Statement[] statements;
- public Javadoc javaDoc;
- public boolean isSetter;
- public Expression varName;
-
- public ObjectGetterSetterField(Expression field, Statement[] statements, Expression varName, int start, int end) {
- super(field, null, start, end);
- this.statements = statements;
- this.isSetter = varName != null;
- this.varName = varName;
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output) {
- if (this.javaDoc!=null) {
- this.javaDoc.print(indent, output);
- }
- printIndent(indent, output);
- if (this.isSetter) {
- output.append("set "); //$NON-NLS-1$
- } else {
- output.append("get "); //$NON-NLS-1$
- }
- this.fieldName.printExpression(indent, output);
- output.append("("); //$NON-NLS-1$
- if (this.isSetter) {
- this.varName.printExpression(indent, output);
- }
- output.append(") {\n"); //$NON-NLS-1$
- for (int i = 0, max = this.statements.length; i < max; i++) {
- printIndent(indent + 1, output);
- this.statements[i].printStatement(indent + 1, output);
- output.append("\n"); //$NON-NLS-1$
- }
- printIndent(indent + 1, output);
- output.append("}"); //$NON-NLS-1$
- return output;
- }
-
- public void traverse(ASTVisitor visitor, BlockScope scope) {
- if (visitor.visit(this, scope)) {
- if (javaDoc!=null)
- javaDoc.traverse(visitor, scope);
- if (fieldName!=null)
- fieldName.traverse(visitor, scope);
- if (this.varName != null) {
- this.varName.traverse(visitor, scope);
- }
- for (int i = 0, max = this.statements.length; i < max; i++) {
- this.statements[i].traverse(visitor, scope);
- }
- }
- visitor.endVisit(this, scope);
- }
-
-
- public TypeBinding resolveType(BlockScope scope) {
- // TODO to be completed
- return null;
- }
-
-
- public FlowInfo analyseCode(
- BlockScope classScope,
- FlowContext initializationContext,
- FlowInfo flowInfo) {
- // TODO to be completed
-
- return flowInfo;
- }
- public int getASTType() {
- return IASTNode.OBJECT_GETTER_SETTER_FIELD;
-
- }
-
- public IJsDoc getJsDoc() {
- return this.javaDoc;
- }
-}
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
deleted file mode 100644
index 4b034e2f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ObjectLiteral.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IObjectLiteral;
-import org.eclipse.wst.jsdt.core.ast.IObjectLiteralField;
-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;
-import org.eclipse.wst.jsdt.internal.compiler.impl.Constant;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-
-public class ObjectLiteral extends Expression implements IObjectLiteral {
-
- public ObjectLiteralField [] fields;
- public InferredType inferredType;
-
- public StringBuffer printExpression(int indent, StringBuffer output) {
- if (fields==null || fields.length==0)
- {
- output.append("{}"); //$NON-NLS-1$
- }
- else
- {
- output.append("{\n"); //$NON-NLS-1$
- printIndent(indent+1, output);
- for (int i = 0; i < fields.length; i++) {
- if (i>0)
- {
- output.append(",\n"); //$NON-NLS-1$
- printIndent(indent+1, output);
- }
- fields[i].printExpression(indent, output);
- }
- output.append("\n"); //$NON-NLS-1$
- printIndent(indent, output);
- output.append("}"); //$NON-NLS-1$
- }
- return output;
- }
-
- public InferredType getInferredType() {
- return this.inferredType;
- }
-
- public void setInferredType(InferredType type) {
- this.inferredType=type;
- }
-
- public IObjectLiteralField[] getFields() {
- return this.fields;
- }
- public void traverse(ASTVisitor visitor, BlockScope scope) {
- if (visitor.visit(this, scope)) {
- if (fields!=null)
- for (int i = 0; i < fields.length; i++) {
- fields[i].traverse(visitor, scope);
- }
- }
- visitor.endVisit(this, scope);
- }
-
-
- public TypeBinding resolveType(BlockScope scope) {
- this.constant=Constant.NotAConstant;
- 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;
- return TypeBinding.ANY;
- }
-
- public int nullStatus(FlowInfo flowInfo) {
- return FlowInfo.NON_NULL; // constant expression cannot be null
- }
-
- public FlowInfo analyseCode(
- BlockScope classScope,
- FlowContext initializationContext,
- FlowInfo flowInfo) {
- if (this.fields!=null)
- for (int i = 0; i < this.fields.length; i++) {
- flowInfo=this.fields[i].analyseCode(classScope,initializationContext, flowInfo);
- }
-
- return flowInfo;
- }
- public int getASTType() {
- return IASTNode.OBJECT_LITERAL;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ObjectLiteralField.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ObjectLiteralField.java
deleted file mode 100644
index c6cee9b9..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ObjectLiteralField.java
+++ /dev/null
@@ -1,90 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-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.IJsDoc;
-import org.eclipse.wst.jsdt.core.ast.IObjectLiteralField;
-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;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class ObjectLiteralField extends Expression implements IObjectLiteralField {
-
- public Expression fieldName;
- public Expression initializer;
- public Javadoc javaDoc;
-
- public ObjectLiteralField(Expression field, Expression value, int start, int end) {
-
- this.fieldName=field;
- this.initializer=value;
- this.sourceEnd=end;
- this.sourceStart=start;
- }
-
- public IExpression getFieldName() {
- return fieldName;
- }
-
- public IExpression getInitializer() {
- return initializer;
- }
-
-
- public StringBuffer printExpression(int indent, StringBuffer output) {
- if (this.javaDoc!=null)
- this.javaDoc.print(indent, output);
- fieldName.printExpression(indent, output);
- output.append(" : "); //$NON-NLS-1$
- initializer.printExpression(indent, output) ;
- return output;
- }
-
- public void traverse(ASTVisitor visitor, BlockScope scope) {
- if (visitor.visit(this, scope)) {
-
- if (javaDoc!=null)
- javaDoc.traverse(visitor, scope);
- if (fieldName!=null)
- fieldName.traverse(visitor, scope);
- if (initializer!=null)
- initializer.traverse(visitor, scope);
- }
- visitor.endVisit(this, scope);
- }
-
-
- public TypeBinding resolveType(BlockScope scope) {
- return initializer.resolveType(scope);
- }
-
-
- public FlowInfo analyseCode(
- BlockScope classScope,
- FlowContext initializationContext,
- FlowInfo flowInfo) {
- flowInfo=initializer.analyseCode(classScope,initializationContext, flowInfo);
-
- return flowInfo;
- }
- public int getASTType() {
- return IASTNode.OBJECT_LITERAL_FIELD;
-
- }
-
- public IJsDoc getJsDoc() {
- return this.javaDoc;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/OperatorExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/OperatorExpression.java
deleted file mode 100644
index 0154deeb..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/OperatorExpression.java
+++ /dev/null
@@ -1,1733 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IOperatorExpression;
-import org.eclipse.wst.jsdt.internal.compiler.flow.FlowInfo;
-import org.eclipse.wst.jsdt.internal.compiler.util.Util;
-
-public abstract class OperatorExpression extends Expression implements OperatorIds, IOperatorExpression {
-
- public static int[][] OperatorSignatures = new int[NumberOfTables][];
-
- static {classInitialize();}
-
- /**
- * OperatorExpression constructor comment.
- */
- public OperatorExpression() {
- super();
- }
- public static final void classInitialize() {
- OperatorSignatures[AND] = get_AND();
- OperatorSignatures[AND_AND] = get_AND_AND();
- OperatorSignatures[DIVIDE] = get_DIVIDE();
- OperatorSignatures[EQUAL_EQUAL] = get_EQUAL_EQUAL();
- OperatorSignatures[GREATER] = get_GREATER();
- OperatorSignatures[GREATER_EQUAL] = get_GREATER_EQUAL();
- OperatorSignatures[LEFT_SHIFT] = get_LEFT_SHIFT();
- OperatorSignatures[LESS] = get_LESS();
- OperatorSignatures[LESS_EQUAL] = get_LESS_EQUAL();
- OperatorSignatures[MINUS] = get_MINUS();
- OperatorSignatures[MULTIPLY] = get_MULTIPLY();
- OperatorSignatures[OR] = get_OR();
- OperatorSignatures[OR_OR] = get_OR_OR();
- OperatorSignatures[PLUS] = get_PLUS();
- OperatorSignatures[REMAINDER] = get_REMAINDER();
- OperatorSignatures[RIGHT_SHIFT] = get_RIGHT_SHIFT();
- OperatorSignatures[UNSIGNED_RIGHT_SHIFT] = get_UNSIGNED_RIGHT_SHIFT();
- OperatorSignatures[XOR] = get_XOR();
- OperatorSignatures[IN] = get_EQUAL_EQUAL();
- OperatorSignatures[EQUAL_EQUAL_EQUAL] = get_EQUAL_EQUAL();
- OperatorSignatures[NOT_EQUAL_EQUAL] = get_EQUAL_EQUAL();
- OperatorSignatures[INSTANCEOF] = get_INSTANCEOF();
- }
-
- public static final String generateTableTestCase(){
- //return a String which is a java method allowing to test
- //the non zero entries of all tables
-
- /*
- org.eclipse.wst.jsdt.internal.compiler.ast.
- OperatorExpression.generateTableTestCase();
- */
-
- int[] operators = new int[]{AND,AND_AND,DIVIDE,GREATER,GREATER_EQUAL,
- LEFT_SHIFT,LESS,LESS_EQUAL,MINUS,MULTIPLY,OR,OR_OR,PLUS,REMAINDER,
- RIGHT_SHIFT,UNSIGNED_RIGHT_SHIFT,XOR};
-
- class Decode {
- public final String constant(int code){
- switch(code){
- case T_boolean : return "true"; //$NON-NLS-1$
- case T_char : return "'A'"; //$NON-NLS-1$
- case T_double : return "300.0d"; //$NON-NLS-1$
- case T_float : return "100.0f"; //$NON-NLS-1$
- case T_int : return "1"; //$NON-NLS-1$
- case T_long : return "7L"; //$NON-NLS-1$
- case T_JavaLangString : return "\"hello-world\""; //$NON-NLS-1$
- case T_null : return "null"; //$NON-NLS-1$
- case T_short : return "((short) 5)"; //$NON-NLS-1$
- case T_JavaLangObject : return "null";} //$NON-NLS-1$
- return Util.EMPTY_STRING;}
-
- public final String type(int code){
- switch(code){
- case T_boolean : return "z"; //$NON-NLS-1$
- case T_char : return "c"; //$NON-NLS-1$
- case T_double : return "d"; //$NON-NLS-1$
- case T_float : return "f"; //$NON-NLS-1$
- case T_int : return "i"; //$NON-NLS-1$
- case T_long : return "l"; //$NON-NLS-1$
- case T_JavaLangString : return "str"; //$NON-NLS-1$
- case T_null : return "null"; //$NON-NLS-1$
- case T_short : return "s"; //$NON-NLS-1$
- case T_JavaLangObject : return "obj";} //$NON-NLS-1$
- return "xxx";} //$NON-NLS-1$
-
- public final String operator(int operator){
- switch (operator) {
- case EQUAL_EQUAL : return "=="; //$NON-NLS-1$
- case LESS_EQUAL : return "<="; //$NON-NLS-1$
- case GREATER_EQUAL :return ">="; //$NON-NLS-1$
- case LEFT_SHIFT : return "<<"; //$NON-NLS-1$
- case RIGHT_SHIFT : return ">>"; //$NON-NLS-1$
- case UNSIGNED_RIGHT_SHIFT : return ">>>"; //$NON-NLS-1$
- case OR_OR :return "||"; //$NON-NLS-1$
- case AND_AND : return "&&"; //$NON-NLS-1$
- case PLUS : return "+"; //$NON-NLS-1$
- case MINUS : return "-"; //$NON-NLS-1$
- case NOT : return "!"; //$NON-NLS-1$
- case REMAINDER : return "%"; //$NON-NLS-1$
- case XOR : return "^"; //$NON-NLS-1$
- case AND : return "&"; //$NON-NLS-1$
- case MULTIPLY : return "*"; //$NON-NLS-1$
- case OR : return "|"; //$NON-NLS-1$
- case TWIDDLE : return "~"; //$NON-NLS-1$
- case DIVIDE : return "/"; //$NON-NLS-1$
- case GREATER : return ">"; //$NON-NLS-1$
- case LESS : return "<"; } //$NON-NLS-1$
- return "????";} //$NON-NLS-1$
- }
-
-
- Decode decode = new Decode();
- String s;
-
- s = "\tpublic static void binaryOperationTablesTestCase(){\n" + //$NON-NLS-1$
-
- "\t\t//TC test : all binary operation (described in tables)\n"+ //$NON-NLS-1$
- "\t\t//method automatically generated by\n"+ //$NON-NLS-1$
- "\t\t//org.eclipse.wst.jsdt.internal.compiler.ast.OperatorExpression.generateTableTestCase();\n"+ //$NON-NLS-1$
-
- "\t\tString str0;\t String str\t= "+decode.constant(T_JavaLangString)+";\n"+ //$NON-NLS-1$ //$NON-NLS-2$
- "\t\tint i0;\t int i\t= "+decode.constant(T_int)+";\n"+ //$NON-NLS-1$ //$NON-NLS-2$
- "\t\tboolean z0;\t boolean z\t= "+decode.constant(T_boolean)+";\n"+ //$NON-NLS-1$ //$NON-NLS-2$
- "\t\tchar c0; \t char c\t= "+decode.constant(T_char)+";\n"+ //$NON-NLS-1$ //$NON-NLS-2$
- "\t\tfloat f0; \t float f\t= "+decode.constant(T_float)+";\n"+ //$NON-NLS-1$ //$NON-NLS-2$
- "\t\tshort s0; \t short s\t= "+decode.constant(T_short)+";\n"+ //$NON-NLS-1$ //$NON-NLS-2$
- "\t\tlong l0; \t long l\t= "+decode.constant(T_long)+";\n"+ //$NON-NLS-1$ //$NON-NLS-2$
- "\t\tObject obj0; \t Object obj\t= "+decode.constant(T_JavaLangObject)+";\n"+ //$NON-NLS-1$ //$NON-NLS-2$
- "\n"; //$NON-NLS-1$
-
- int error = 0;
- for (int i=0; i < operators.length; i++)
- { int operator = operators[i];
- for (int left=0; left<16;left++)
- for (int right=0; right<16;right++)
- { int result = (OperatorSignatures[operator][(left<<4)+right]) & 0x0000F;
- if (result != T_undefined)
-
- //1/ First regular computation then 2/ comparaison
- //with a compile time constant (generated by the compiler)
- // z0 = s >= s;
- // if ( z0 != (((short) 5) >= ((short) 5)))
- // System.out.println(155);
-
- { s += "\t\t"+decode.type(result)+"0"+" = "+decode.type(left); //$NON-NLS-1$ //$NON-NLS-3$ //$NON-NLS-2$
- s += " "+decode.operator(operator)+" "+decode.type(right)+";\n"; //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-3$
- String begin = result == T_JavaLangString ? "\t\tif (! " : "\t\tif ( "; //$NON-NLS-2$ //$NON-NLS-1$
- String test = result == T_JavaLangString ? ".equals(" : " != ("; //$NON-NLS-2$ //$NON-NLS-1$
- s += begin +decode.type(result)+"0"+test //$NON-NLS-1$
- +decode.constant(left)+" " //$NON-NLS-1$
- +decode.operator(operator)+" " //$NON-NLS-1$
- +decode.constant(right)+"))\n"; //$NON-NLS-1$
- s += "\t\t\tSystem.out.println("+ (++error) +");\n"; //$NON-NLS-1$ //$NON-NLS-2$
-
- }
- }
- }
-
- return s += "\n\t\tSystem.out.println(\"binary tables test : done\");}"; //$NON-NLS-1$
- }
-
- public static final int[] get_AND(){
-
- //the code is an int, only 20 bits are used, see below.
- // (cast) left Op (cast) rigth --> result
- // 0000 0000 0000 0000 0000
- // <<16 <<12 <<8 <<4
-
- int[] table = new int[16*16];
-
- // table[(T_undefined<<4)+T_undefined] = T_undefined;
- // table[(T_undefined<<4)+T_byte] = T_undefined;
- // table[(T_undefined<<4)+T_long] = T_undefined;
- // table[(T_undefined<<4)+T_short] = T_undefined;
- // table[(T_undefined<<4)+T_void] = T_undefined;
- // table[(T_undefined<<4)+T_JavaLangString] = T_undefined;
- // table[(T_undefined<<4)+T_Object] = T_undefined;
- // table[(T_undefined<<4)+T_double] = T_undefined;
- // table[(T_undefined<<4)+T_float] = T_undefined;
- // table[(T_undefined<<4)+T_boolean] = T_undefined;
- // table[(T_undefined<<4)+T_char] = T_undefined;
- // table[(T_undefined<<4)+T_int] = T_undefined;
- // table[(T_undefined<<4)+T_null] = T_undefined;
-
- // table[(T_long<<4)+T_undefined] = T_undefined;
- table[(T_long<<4)+T_long] = (Long2Long<<12)+(Long2Long<<4)+T_long;
- table[(T_long<<4)+T_short] = (Long2Long<<12)+(Short2Long<<4)+T_long;
- // table[(T_long<<4)+T_void] = T_undefined;
- // table[(T_long<<4)+T_JavaLangString] = T_undefined;
- // table[(T_long<<4)+T_Object] = T_undefined;
- // table[(T_long<<4)+T_double] = T_undefined;
- // table[(T_long<<4)+T_float] = T_undefined;
- // table[(T_long<<4)+T_boolean] = T_undefined;
- table[(T_long<<4)+T_char] = (Long2Long<<12)+(Char2Long<<4)+T_long;
- table[(T_long<<4)+T_int] = (Long2Long<<12)+(Int2Long<<4)+T_long;
- // table[(T_long<<4)+T_null] = T_undefined;
- table[(T_long<<4)+T_any] = T_any;
-
- // table[(T_short<<4)+T_undefined] = T_undefined;
- table[(T_short<<4)+T_long] = (Short2Long<<12)+(Long2Long<<4)+T_long;
- table[(T_short<<4)+T_short] = (Short2Int<<12)+(Short2Int<<4)+T_int;
- // table[(T_short<<4)+T_void] = T_undefined;
- // table[(T_short<<4)+T_JavaLangString] = T_undefined;
- // table[(T_short<<4)+T_Object] = T_undefined;
- // table[(T_short<<4)+T_double] = T_undefined;
- // table[(T_short<<4)+T_float] = T_undefined;
- // table[(T_short<<4)+T_boolean] = T_undefined;
- table[(T_short<<4)+T_char] = (Short2Int<<12)+(Char2Int<<4)+T_int;
- table[(T_short<<4)+T_int] = (Short2Int<<12)+(Int2Int<<4)+T_int;
- // table[(T_short<<4)+T_null] = T_undefined;
- table[(T_short<<4)+T_any] = T_any;
-
- // table[(T_void<<4)+T_undefined] = T_undefined;
- // table[(T_void<<4)+T_byte] = T_undefined;
- // table[(T_void<<4)+T_long] = T_undefined;
- // table[(T_void<<4)+T_short] = T_undefined;
- // table[(T_void<<4)+T_void] = T_undefined;
- // table[(T_void<<4)+T_JavaLangString] = T_undefined;
- // table[(T_void<<4)+T_Object] = T_undefined;
- // table[(T_void<<4)+T_double] = T_undefined;
- // table[(T_void<<4)+T_float] = T_undefined;
- // table[(T_void<<4)+T_boolean] = T_undefined;
- // table[(T_void<<4)+T_char] = T_undefined;
- // table[(T_void<<4)+T_int] = T_undefined;
- // table[(T_void<<4)+T_null] = T_undefined;
- table[(T_void<<4)+T_any] = T_any;
-
- // table[(T_JavaLangString<<4)+T_undefined] = T_undefined;
- // table[(T_JavaLangString<<4)+T_byte] = T_undefined;
- // table[(T_JavaLangString<<4)+T_long] = T_undefined;
- // table[(T_JavaLangString<<4)+T_short] = T_undefined;
- // table[(T_JavaLangString<<4)+T_void] = T_undefined;
- // table[(T_JavaLangString<<4)+T_JavaLangString] = T_undefined;
- // table[(T_JavaLangString<<4)+T_Object] = T_undefined;
- // table[(T_JavaLangString<<4)+T_double] = T_undefined;
- // table[(T_JavaLangString<<4)+T_float] = T_undefined;
- // table[(T_JavaLangString<<4)+T_boolean] = T_undefined;
- // table[(T_JavaLangString<<4)+T_char] = T_undefined;
- // table[(T_JavaLangString<<4)+T_int] = T_undefined;
- // table[(T_JavaLangString<<4)+T_null] = T_undefined;
- table[(T_JavaLangString<<4)+T_any] = T_any;
-
- // table[(T_Object<<4)+T_undefined] = T_undefined;
- // table[(T_Object<<4)+T_byte] = T_undefined;
- // table[(T_Object<<4)+T_long] = T_undefined;
- // table[(T_Object<<4)+T_short] = T_undefined;
- // table[(T_Object<<4)+T_void] = T_undefined;
- // table[(T_Object<<4)+T_JavaLangString] = T_undefined;
- // table[(T_Object<<4)+T_Object] = T_undefined;
- // table[(T_Object<<4)+T_double] = T_undefined;
- // table[(T_Object<<4)+T_float] = T_undefined;
- // table[(T_Object<<4)+T_boolean] = T_undefined;
- // table[(T_Object<<4)+T_char] = T_undefined;
- // table[(T_Object<<4)+T_int] = T_undefined;
- // table[(T_Object<<4)+T_null] = T_undefined;
- table[(T_JavaLangObject<<4)+T_any] = T_any;
-
- // table[(T_double<<4)+T_undefined] = T_undefined;
- // table[(T_double<<4)+T_byte] = T_undefined;
- // table[(T_double<<4)+T_long] = T_undefined;
- // table[(T_double<<4)+T_short] = T_undefined;
- // table[(T_double<<4)+T_void] = T_undefined;
- // table[(T_double<<4)+T_JavaLangString] = T_undefined;
- // table[(T_double<<4)+T_Object] = T_undefined;
- // table[(T_double<<4)+T_double] = T_undefined;
- // table[(T_double<<4)+T_float] = T_undefined;
- // table[(T_double<<4)+T_boolean] = T_undefined;
- // table[(T_double<<4)+T_char] = T_undefined;
- // table[(T_double<<4)+T_int] = T_undefined;
- // table[(T_double<<4)+T_null] = T_undefined;
- table[(T_double<<4)+T_any] = T_any;
-
- // table[(T_float<<4)+T_undefined] = T_undefined;
- // table[(T_float<<4)+T_byte] = T_undefined;
- // table[(T_float<<4)+T_long] = T_undefined;
- // table[(T_float<<4)+T_short] = T_undefined;
- // table[(T_float<<4)+T_void] = T_undefined;
- // table[(T_float<<4)+T_JavaLangString] = T_undefined;
- // table[(T_float<<4)+T_Object] = T_undefined;
- // table[(T_float<<4)+T_double] = T_undefined;
- // table[(T_float<<4)+T_float] = T_undefined;
- // table[(T_float<<4)+T_boolean] = T_undefined;
- // table[(T_float<<4)+T_char] = T_undefined;
- // table[(T_float<<4)+T_int] = T_undefined;
- // table[(T_float<<4)+T_null] = T_undefined;
- table[(T_float<<4)+T_any] = T_any;
-
- // table[(T_boolean<<4)+T_undefined] = T_undefined;
- // table[(T_boolean<<4)+T_byte] = T_undefined;
- // table[(T_boolean<<4)+T_long] = T_undefined;
- // table[(T_boolean<<4)+T_short] = T_undefined;
- // table[(T_boolean<<4)+T_void] = T_undefined;
- // table[(T_boolean<<4)+T_JavaLangString] = T_undefined;
- // table[(T_boolean<<4)+T_Object] = T_undefined;
- // table[(T_boolean<<4)+T_double] = T_undefined;
- // table[(T_boolean<<4)+T_float] = T_undefined;
- table[(T_boolean<<4)+T_boolean] = (Boolean2Boolean << 12)+(Boolean2Boolean << 4)+T_boolean;
- // table[(T_boolean<<4)+T_char] = T_undefined;
- // table[(T_boolean<<4)+T_int] = T_undefined;
- // table[(T_boolean<<4)+T_null] = T_undefined;
- table[(T_boolean<<4)+T_any] = T_any;
-
- // table[(T_char<<4)+T_undefined] = T_undefined;
- table[(T_char<<4)+T_long] = (Char2Long<<12)+(Long2Long<<4)+T_long;
- table[(T_char<<4)+T_short] = (Char2Int<<12)+(Short2Int<<4)+T_int;
- // table[(T_char<<4)+T_void] = T_undefined;
- // table[(T_char<<4)+T_JavaLangString] = T_undefined;
- // table[(T_char<<4)+T_Object] = T_undefined;
- // table[(T_char<<4)+T_double] = T_undefined;
- // table[(T_char<<4)+T_float] = T_undefined;
- // table[(T_char<<4)+T_boolean] = T_undefined;
- table[(T_char<<4)+T_char] = (Char2Int<<12)+(Char2Int<<4)+T_int;
- table[(T_char<<4)+T_int] = (Char2Int<<12)+(Int2Int<<4)+T_int;
- // table[(T_char<<4)+T_null] = T_undefined;
- table[(T_char<<4)+T_any] = T_any;
-
- // table[(T_int<<4)+T_undefined] = T_undefined;
- table[(T_int<<4)+T_long] = (Int2Long<<12)+(Long2Long<<4)+T_long;
- table[(T_int<<4)+T_short] = (Int2Int<<12)+(Short2Int<<4)+T_int;
- // table[(T_int<<4)+T_void] = T_undefined;
- // table[(T_int<<4)+T_JavaLangString] = T_undefined;
- // table[(T_int<<4)+T_Object] = T_undefined;
- // table[(T_int<<4)+T_double] = T_undefined;
- // table[(T_int<<4)+T_float] = T_undefined;
- // table[(T_int<<4)+T_boolean] = T_undefined;
- table[(T_int<<4)+T_char] = (Int2Int<<12)+(Char2Int<<4)+T_int;
- table[(T_int<<4)+T_int] = (Int2Int<<12)+(Int2Int<<4)+T_int;
- // table[(T_int<<4)+T_null] = T_undefined;
- table[(T_int<<4)+T_any] = T_any;
-
- // table[(T_null<<4)+T_undefined] = T_undefined;
- // table[(T_null<<4)+T_byte] = T_undefined;
- // table[(T_null<<4)+T_long] = T_undefined;
- // table[(T_null<<4)+T_short] = T_undefined;
- // table[(T_null<<4)+T_void] = T_undefined;
- // table[(T_null<<4)+T_JavaLangString] = T_undefined;
- // table[(T_null<<4)+T_Object] = T_undefined;
- // table[(T_null<<4)+T_double] = T_undefined;
- // table[(T_null<<4)+T_float] = T_undefined;
- // table[(T_null<<4)+T_boolean] = T_undefined;
- // table[(T_null<<4)+T_char] = T_undefined;
- // table[(T_null<<4)+T_int] = T_undefined;
- // table[(T_null<<4)+T_null] = T_undefined;
- table[(T_null<<4)+T_any] = T_any;
-
- table[(T_any<<4)+T_undefined] = T_any;
- table[(T_any<<4)+T_long] = T_any;
- table[(T_any<<4)+T_short] = T_any;
- table[(T_any<<4)+T_void] = T_any;
- table[(T_any<<4)+T_JavaLangString] = T_any;
- table[(T_any<<4)+T_JavaLangObject] = T_any;
- table[(T_any<<4)+T_double] = T_any;
- table[(T_any<<4)+T_float] = T_any;
- table[(T_any<<4)+T_boolean] = T_any;
- table[(T_any<<4)+T_char] = T_any;
- table[(T_any<<4)+T_int] = T_any;
- table[(T_any<<4)+T_null] = T_any;
- table[(T_any<<4)+T_any] = T_any;
-
- return table;
- }
-
- public static final int[] get_AND_AND(){
-
- int[] table = new int[16*16];
- // table[(T_undefined<<4)+T_undefined] = T_undefined;
- // table[(T_undefined<<4)+T_byte] = T_undefined;
- // table[(T_undefined<<4)+T_long] = T_undefined;
- // table[(T_undefined<<4)+T_short] = T_undefined;
- // table[(T_undefined<<4)+T_void] = T_undefined;
- table[(T_undefined<<4)+T_JavaLangString] = T_JavaLangString;
- // table[(T_undefined<<4)+T_Object] = T_undefined;
- // table[(T_undefined<<4)+T_double] = T_undefined;
- // table[(T_undefined<<4)+T_float] = T_undefined;
- table[(T_undefined<<4)+T_boolean] = T_boolean;
- table[(T_undefined<<4)+T_char] = T_JavaLangString;
- table[(T_undefined<<4)+T_int] = T_int;
- // table[(T_undefined<<4)+T_null] = T_undefined;
-
- // table[(T_byte<<4)+T_undefined] = T_undefined;
- // table[(T_byte<<4)+T_byte] = T_undefined;
- // table[(T_byte<<4)+T_long] = T_undefined;
- // table[(T_byte<<4)+T_short] = T_undefined;
- // table[(T_byte<<4)+T_void] = T_undefined;
- // table[(T_byte<<4)+T_JavaLangString] = T_undefined;
- // table[(T_byte<<4)+T_Object] = T_undefined;
- // table[(T_byte<<4)+T_double] = T_undefined;
- // table[(T_byte<<4)+T_float] = T_undefined;
- // table[(T_byte<<4)+T_boolean] = T_undefined;
- // table[(T_byte<<4)+T_char] = T_undefined;
- // table[(T_byte<<4)+T_int] = T_undefined;
- // table[(T_byte<<4)+T_null] = T_undefined;
-
- // table[(T_long<<4)+T_undefined] = T_undefined;
- // table[(T_long<<4)+T_byte] = T_undefined;
- // table[(T_long<<4)+T_long] = T_undefined;
- // table[(T_long<<4)+T_short] = T_undefined;
- // table[(T_long<<4)+T_void] = T_undefined;
- // table[(T_long<<4)+T_JavaLangString] = T_undefined;
- // table[(T_long<<4)+T_Object] = T_undefined;
- // table[(T_long<<4)+T_double] = T_undefined;
- // table[(T_long<<4)+T_float] = T_undefined;
- // table[(T_long<<4)+T_boolean] = T_undefined;
- // table[(T_long<<4)+T_char] = T_undefined;
- // table[(T_long<<4)+T_int] = T_undefined;
- // table[(T_long<<4)+T_null] = T_undefined;
- table[(T_long<<4)+T_any] = T_boolean;
-
- // table[(T_short<<4)+T_undefined] = T_undefined;
- // table[(T_short<<4)+T_byte] = T_undefined;
- // table[(T_short<<4)+T_long] = T_undefined;
- // table[(T_short<<4)+T_short] = T_undefined;
- // table[(T_short<<4)+T_void] = T_undefined;
- // table[(T_short<<4)+T_JavaLangString] = T_undefined;
- // table[(T_short<<4)+T_Object] = T_undefined;
- // table[(T_short<<4)+T_double] = T_undefined;
- // table[(T_short<<4)+T_float] = T_undefined;
- // table[(T_short<<4)+T_boolean] = T_undefined;
- // table[(T_short<<4)+T_char] = T_undefined;
- // table[(T_short<<4)+T_int] = T_undefined;
- // table[(T_short<<4)+T_null] = T_undefined;
- table[(T_short<<4)+T_any] = T_boolean;
-
- // table[(T_void<<4)+T_undefined] = T_undefined;
- // table[(T_void<<4)+T_byte] = T_undefined;
- // table[(T_void<<4)+T_long] = T_undefined;
- // table[(T_void<<4)+T_short] = T_undefined;
- // table[(T_void<<4)+T_void] = T_undefined;
- // table[(T_void<<4)+T_JavaLangString] = T_undefined;
- // table[(T_void<<4)+T_Object] = T_undefined;
- // table[(T_void<<4)+T_double] = T_undefined;
- // table[(T_void<<4)+T_float] = T_undefined;
- // table[(T_void<<4)+T_boolean] = T_undefined;
- // table[(T_void<<4)+T_char] = T_undefined;
- // table[(T_void<<4)+T_int] = T_undefined;
- // table[(T_void<<4)+T_null] = T_undefined;
- table[(T_short<<4)+T_any] = T_boolean;
-
- table[(T_JavaLangString<<4)+T_undefined] = T_JavaLangString;
- // table[(T_JavaLangString<<4)+T_byte] = T_undefined;
- // table[(T_JavaLangString<<4)+T_long] = T_undefined;
- // table[(T_JavaLangString<<4)+T_short] = T_undefined;
- // table[(T_JavaLangString<<4)+T_void] = T_undefined;
- table[(T_JavaLangString<<4)+T_JavaLangString] = T_JavaLangString;
- // table[(T_JavaLangString<<4)+T_Object] = T_undefined;
- // table[(T_JavaLangString<<4)+T_double] = T_undefined;
- // table[(T_JavaLangString<<4)+T_float] = T_undefined;
- table[(T_JavaLangString<<4)+T_boolean] = T_boolean;
- // table[(T_JavaLangString<<4)+T_char] = T_undefined;
- table[(T_JavaLangString<<4)+T_int] = T_any;
- // table[(T_JavaLangString<<4)+T_null] = T_undefined;
- table[(T_JavaLangString<<4)+T_any] = T_boolean;
-
- // table[(T_Object<<4)+T_undefined] = T_undefined;
- // table[(T_Object<<4)+T_byte] = T_undefined;
- // table[(T_Object<<4)+T_long] = T_undefined;
- // table[(T_Object<<4)+T_short] = T_undefined;
- // table[(T_Object<<4)+T_void] = T_undefined;
- table[(T_JavaLangObject<<4)+T_JavaLangString] = T_boolean;
- // table[(T_Object<<4)+T_Object] = T_undefined;
- // table[(T_Object<<4)+T_double] = T_undefined;
- // table[(T_Object<<4)+T_float] = T_undefined;
- table[(T_JavaLangObject<<4)+T_boolean] = T_boolean;
- // table[(T_Object<<4)+T_char] = T_undefined;
- table[(T_JavaLangObject<<4)+T_int] = T_int;
- // table[(T_Object<<4)+T_null] = T_undefined;
- table[(T_JavaLangObject<<4)+T_any] = T_boolean;
-
- // table[(T_double<<4)+T_undefined] = T_undefined;
- // table[(T_double<<4)+T_byte] = T_undefined;
- // table[(T_double<<4)+T_long] = T_undefined;
- // table[(T_double<<4)+T_short] = T_undefined;
- // table[(T_double<<4)+T_void] = T_undefined;
- // table[(T_double<<4)+T_JavaLangString] = T_undefined;
- // table[(T_double<<4)+T_Object] = T_undefined;
- // table[(T_double<<4)+T_double] = T_undefined;
- // table[(T_double<<4)+T_float] = T_undefined;
- // table[(T_double<<4)+T_boolean] = T_undefined;
- // table[(T_double<<4)+T_char] = T_undefined;
- // table[(T_double<<4)+T_int] = T_undefined;
- // table[(T_double<<4)+T_null] = T_undefined;
- table[(T_double<<4)+T_any] = T_boolean;
-
- // table[(T_float<<4)+T_undefined] = T_undefined;
- // table[(T_float<<4)+T_byte] = T_undefined;
- // table[(T_float<<4)+T_long] = T_undefined;
- // table[(T_float<<4)+T_short] = T_undefined;
- // table[(T_float<<4)+T_void] = T_undefined;
- // table[(T_float<<4)+T_JavaLangString] = T_undefined;
- // table[(T_float<<4)+T_Object] = T_undefined;
- // table[(T_float<<4)+T_double] = T_undefined;
- // table[(T_float<<4)+T_float] = T_undefined;
- // table[(T_float<<4)+T_boolean] = T_undefined;
- // table[(T_float<<4)+T_char] = T_undefined;
- // table[(T_float<<4)+T_int] = T_undefined;
- // table[(T_float<<4)+T_null] = T_undefined;
- table[(T_float<<4)+T_any] = T_boolean;
-
- // table[(T_boolean<<4)+T_undefined] = T_undefined;
- // table[(T_boolean<<4)+T_byte] = T_undefined;
- // table[(T_boolean<<4)+T_long] = T_undefined;
- // table[(T_boolean<<4)+T_short] = T_undefined;
- // table[(T_boolean<<4)+T_void] = T_undefined;
- table[(T_boolean<<4)+T_JavaLangString] = T_JavaLangString;
- table[(T_boolean<<4)+T_JavaLangObject] = T_JavaLangObject;
- // table[(T_boolean<<4)+T_double] = T_undefined;
- // table[(T_boolean<<4)+T_float] = T_undefined;
- table[(T_boolean<<4)+T_boolean] = (Boolean2Boolean<<12)+(Boolean2Boolean<<4)+T_boolean;
- // table[(T_boolean<<4)+T_char] = T_undefined;
- table[(T_boolean<<4)+T_int] = T_boolean;
- // table[(T_boolean<<4)+T_null] = T_undefined;
- table[(T_boolean<<4)+T_any] = T_boolean;
-
- // table[(T_char<<4)+T_undefined] = T_undefined;
- // table[(T_char<<4)+T_byte] = T_undefined;
- // table[(T_char<<4)+T_long] = T_undefined;
- // table[(T_char<<4)+T_short] = T_undefined;
- // table[(T_char<<4)+T_void] = T_undefined;
- table[(T_char<<4)+T_JavaLangString] = T_JavaLangString;
- // table[(T_char<<4)+T_Object] = T_undefined;
- // table[(T_char<<4)+T_double] = T_undefined;
- // table[(T_char<<4)+T_float] = T_undefined;
- // table[(T_char<<4)+T_boolean] = T_undefined;
- table[(T_char<<4)+T_char] = T_JavaLangString;
- // table[(T_char<<4)+T_int] = T_undefined;
- // table[(T_char<<4)+T_null] = T_undefined;
- table[(T_char<<4)+T_any] = T_boolean;
-
- // table[(T_int<<4)+T_undefined] = T_undefined;
- // table[(T_int<<4)+T_byte] = T_undefined;
- // table[(T_int<<4)+T_long] = T_undefined;
- // table[(T_int<<4)+T_short] = T_undefined;
- // table[(T_int<<4)+T_void] = T_undefined;
- table[(T_int<<4)+T_JavaLangString] = T_any;
- // table[(T_int<<4)+T_Object] = T_undefined;
- // table[(T_int<<4)+T_double] = T_undefined;
- // table[(T_int<<4)+T_float] = T_undefined;
- table[(T_int<<4)+T_boolean] = T_boolean;
- // table[(T_int<<4)+T_char] = T_undefined;
- table[(T_int<<4)+T_int] = T_int;
- // table[(T_int<<4)+T_null] = T_undefined;
- table[(T_int<<4)+T_function] = T_boolean;
- table[(T_int<<4)+T_any] = T_boolean;
-
- // table[(T_null<<4)+T_undefined] = T_undefined;
- // table[(T_null<<4)+T_byte] = T_undefined;
- // table[(T_null<<4)+T_long] = T_undefined;
- // table[(T_null<<4)+T_short] = T_undefined;
- // table[(T_null<<4)+T_void] = T_undefined;
- // table[(T_null<<4)+T_JavaLangString] = T_undefined;
- // table[(T_null<<4)+T_Object] = T_undefined;
- // table[(T_null<<4)+T_double] = T_undefined;
- // table[(T_null<<4)+T_float] = T_undefined;
- // table[(T_null<<4)+T_boolean] = T_undefined;
- // table[(T_null<<4)+T_char] = T_undefined;
- // table[(T_null<<4)+T_int] = T_undefined;
- // table[(T_null<<4)+T_null] = T_undefined;
- table[(T_null<<4)+T_any] = T_boolean;
-
- table[(T_any<<4)+T_undefined] = T_boolean;
-
- table[(T_function<<4)+T_undefined] = T_boolean;
- table[(T_function<<4)+T_any] = T_boolean;
- table[(T_function<<4)+T_int] = T_boolean;
- table[(T_function<<4)+T_function] = T_function;
-
-
- table[(T_any<<4)+T_long] = T_boolean;
- table[(T_any<<4)+T_short] = T_boolean;
- table[(T_any<<4)+T_void] = T_boolean;
- table[(T_any<<4)+T_JavaLangString] = T_JavaLangString;
- table[(T_any<<4)+T_JavaLangObject] = T_JavaLangObject;
- table[(T_any<<4)+T_double] = T_boolean;
- table[(T_any<<4)+T_float] = T_boolean;
- table[(T_any<<4)+T_boolean] = T_boolean;
- table[(T_any<<4)+T_char] = T_boolean;
- table[(T_any<<4)+T_int] = T_int;
- table[(T_any<<4)+T_null] = T_boolean;
- table[(T_any<<4)+T_any] = T_any;
- table[(T_any<<4)+T_function] = T_function;
-
- table[(T_function<<4)+T_any] = T_function;
-
- return table;
- }
-
- public static final int[] get_DIVIDE(){
-
- //the code is an int
- // (cast) left Op (cast) rigth --> result
- // 0000 0000 0000 0000 0000
- // <<16 <<12 <<8 <<4
-
-
- // int[] table = new int[16*16];
-
- return get_MINUS();
- }
- public static final int[] get_INSTANCEOF(){
-
-
- //the code is an int
- // (cast) left Op (cast) rigth --> result
- // 0000 0000 0000 0000 0000
- // <<16 <<12 <<8 <<4
-
- int[] table = new int[16*16];
-
-
- table[(T_any<<4)+T_JavaLangString] = T_boolean;
- table[(T_any<<4)+T_JavaLangObject] = T_boolean;
- table[(T_any<<4)+T_function] = T_boolean;
- table[(T_any<<4)+T_boolean] = T_boolean;
- table[(T_any<<4)+T_int] = T_boolean;
- table[(T_any<<4)+T_any] = T_boolean;
-
- table[(T_null<<4)+T_JavaLangObject] = T_boolean;
- table[(T_null<<4)+T_JavaLangString] = T_boolean;
- table[(T_null<<4)+T_function] = T_boolean;
- table[(T_null<<4)+T_boolean] = T_boolean;
- table[(T_null<<4)+T_int] = T_boolean;
- table[(T_null<<4)+T_any] = T_boolean;
-
- table[(T_JavaLangString<<4)+T_JavaLangObject] = T_boolean;
- table[(T_JavaLangString<<4)+T_JavaLangString] = T_boolean;
- table[(T_JavaLangString<<4)+T_function] = T_boolean;
- table[(T_JavaLangString<<4)+T_boolean] = T_boolean;
- table[(T_JavaLangString<<4)+T_int] = T_boolean;
- table[(T_JavaLangString<<4)+T_any] = T_boolean;
-
- table[(T_JavaLangObject<<4)+T_JavaLangObject] = T_boolean;
- table[(T_JavaLangObject<<4)+T_JavaLangString] = T_boolean;
- table[(T_JavaLangObject<<4)+T_function] = T_boolean;
- table[(T_JavaLangObject<<4)+T_boolean] = T_boolean;
- table[(T_JavaLangObject<<4)+T_int] = T_boolean;
- table[(T_JavaLangObject<<4)+T_any] = T_boolean;
-
- table[(T_function<<4)+T_int] = T_boolean;
- table[(T_function<<4)+T_JavaLangObject] = T_boolean;
- table[(T_function<<4)+T_JavaLangString] = T_boolean;
- table[(T_function<<4)+T_function] = T_boolean;
- table[(T_function<<4)+T_boolean] = T_boolean;
- table[(T_function<<4)+T_any] = T_boolean;
-
- table[(T_boolean<<4)+T_int] = T_boolean;
- table[(T_boolean<<4)+T_JavaLangObject] = T_boolean;
- table[(T_boolean<<4)+T_JavaLangString] = T_boolean;
- table[(T_boolean<<4)+T_function] = T_boolean;
- table[(T_boolean<<4)+T_boolean] = T_boolean;
- table[(T_boolean<<4)+T_any] = T_boolean;
-
- table[(T_int<<4)+T_int] = T_boolean;
- table[(T_int<<4)+T_JavaLangObject] = T_boolean;
- table[(T_int<<4)+T_JavaLangString] = T_boolean;
- table[(T_int<<4)+T_function] = T_boolean;
- table[(T_int<<4)+T_boolean] = T_boolean;
- table[(T_int<<4)+T_any] = T_boolean;
-
-
-
- return table;
- }
- public static final int[] get_EQUAL_EQUAL(){
-
- //the code is an int
- // (cast) left Op (cast) rigth --> result
- // 0000 0000 0000 0000 0000
- // <<16 <<12 <<8 <<4
-
- int[] table = new int[16*16];
-
- // table[(T_undefined<<4)+T_undefined] = T_undefined;
- // table[(T_undefined<<4)+T_byte] = T_undefined;
- // table[(T_undefined<<4)+T_long] = T_undefined;
- // table[(T_undefined<<4)+T_short] = T_undefined;
- // table[(T_undefined<<4)+T_void] = T_undefined;
- // table[(T_undefined<<4)+T_JavaLangString] = T_undefined;
- // table[(T_undefined<<4)+T_Object] = T_undefined;
- // table[(T_undefined<<4)+T_double] = T_undefined;
- // table[(T_undefined<<4)+T_float] = T_undefined;
- // table[(T_undefined<<4)+T_boolean] = T_undefined;
- // table[(T_undefined<<4)+T_char] = T_undefined;
- // table[(T_undefined<<4)+T_int] = T_undefined;
- // table[(T_undefined<<4)+T_null] = T_undefined;
-
- // table[(T_long<<4)+T_undefined] = T_undefined;
- table[(T_long<<4)+T_long] = (Long2Long<<12)+(Long2Long<<4)+T_boolean;
- table[(T_long<<4)+T_short] = (Long2Long<<12)+(Short2Long<<4)+T_boolean;
- // table[(T_long<<4)+T_void] = T_undefined;
- // table[(T_long<<4)+T_JavaLangString] = T_undefined;
- // table[(T_long<<4)+T_Object] = T_undefined;
- table[(T_long<<4)+T_double] = (Long2Double<<12)+(Double2Double<<4)+T_boolean;
- table[(T_long<<4)+T_float] = (Long2Float<<12)+(Float2Float<<4)+T_boolean;
- // table[(T_long<<4)+T_boolean] = T_undefined;
- table[(T_long<<4)+T_char] = (Long2Long<<12)+(Char2Long<<4)+T_boolean;
- table[(T_long<<4)+T_int] = (Long2Long<<12)+(Int2Long<<4)+T_boolean;
- // table[(T_long<<4)+T_null] = T_undefined;
- table[(T_long<<4)+T_any] = (Long2Long<<12)+(Int2Long<<4)+T_boolean;
-
- // table[(T_short<<4)+T_undefined] = T_undefined;
- table[(T_short<<4)+T_long] = (Short2Long<<12)+(Long2Long<<4)+T_boolean;
- table[(T_short<<4)+T_short] = (Short2Int<<12)+(Short2Int<<4)+T_boolean;
- // table[(T_short<<4)+T_void] = T_undefined;
- // table[(T_short<<4)+T_JavaLangString] = T_undefined;
- // table[(T_short<<4)+T_Object] = T_undefined;
- table[(T_short<<4)+T_double] = (Short2Double<<12)+(Double2Double<<4)+T_boolean;
- table[(T_short<<4)+T_float] = (Short2Float<<12)+(Float2Float<<4)+T_boolean;
- // table[(T_short<<4)+T_boolean] = T_undefined;
- table[(T_short<<4)+T_char] = (Short2Int<<12)+(Char2Int<<4)+T_boolean;
- table[(T_short<<4)+T_int] = (Short2Int<<12)+(Int2Int<<4)+T_boolean;
- // table[(T_short<<4)+T_null] = T_undefined;
- table[(T_short<<4)+T_any] = (Short2Int<<12)+(Int2Int<<4)+T_boolean;
-
- // table[(T_void<<4)+T_undefined] = T_undefined;
- // table[(T_void<<4)+T_byte] = T_undefined;
- // table[(T_void<<4)+T_long] = T_undefined;
- // table[(T_void<<4)+T_short] = T_undefined;
- // table[(T_void<<4)+T_void] = T_undefined;
- // table[(T_void<<4)+T_JavaLangString] = T_undefined;
- // table[(T_void<<4)+T_Object] = T_undefined;
- // table[(T_void<<4)+T_double] = T_undefined;
- // table[(T_void<<4)+T_float] = T_undefined;
- // table[(T_void<<4)+T_boolean] = T_undefined;
- // table[(T_void<<4)+T_char] = T_undefined;
- // table[(T_void<<4)+T_int] = T_undefined;
- // table[(T_void<<4)+T_null] = T_undefined;
- table[(T_void<<4)+T_any] = T_undefined;
-
- // table[(T_JavaLangString<<4)+T_undefined] = T_undefined;
- // table[(T_JavaLangString<<4)+T_byte] = T_undefined;
- // table[(T_JavaLangString<<4)+T_long] = T_undefined;
- // table[(T_JavaLangString<<4)+T_short] = T_undefined;
- // table[(T_JavaLangString<<4)+T_void] = T_undefined;
- table[(T_JavaLangString<<4)+T_JavaLangString] = /*String2Object String2Object*/
- (T_JavaLangObject<<16)+(T_JavaLangString<<12)+(T_JavaLangObject<<8)+(T_JavaLangString<<4)+T_boolean;
- table[(T_JavaLangString<<4)+T_JavaLangObject] = /*String2Object Object2Object*/
- (T_JavaLangObject<<16)+(T_JavaLangString<<12)+(T_JavaLangObject<<8)+(T_JavaLangObject<<4)+T_boolean;
- // table[(T_JavaLangString<<4)+T_double] = T_undefined;
- // table[(T_JavaLangString<<4)+T_float] = T_undefined;
- // table[(T_JavaLangString<<4)+T_boolean] = T_undefined;
- table[(T_JavaLangString<<4)+T_char] = T_boolean;
- // table[(T_JavaLangString<<4)+T_int] = T_undefined;
- table[(T_JavaLangString<<4)+T_null] = /*Object2String null2Object */
- (T_JavaLangObject<<16)+(T_JavaLangString<<12)+(T_JavaLangObject<<8)+(T_null<<4)+T_boolean;
- table[(T_JavaLangString<<4)+T_any] = T_any;
-
- // table[(T_Object<<4)+T_undefined] = T_undefined;
- // table[(T_Object<<4)+T_byte] = T_undefined;
- // table[(T_Object<<4)+T_long] = T_undefined;
- // table[(T_Object<<4)+T_short] = T_undefined;
- // table[(T_Object<<4)+T_void] = T_undefined;
- table[(T_JavaLangObject<<4)+T_JavaLangString] = /*Object2Object String2Object*/
- (T_JavaLangObject<<16)+(T_JavaLangObject<<12)+(T_JavaLangObject<<8)+(T_JavaLangString<<4)+T_boolean;
- table[(T_JavaLangObject<<4)+T_JavaLangObject] = /*Object2Object Object2Object*/
- (T_JavaLangObject<<16)+(T_JavaLangObject<<12)+(T_JavaLangObject<<8)+(T_JavaLangObject<<4)+T_boolean;
- // table[(T_Object<<4)+T_double] = T_undefined;
- // table[(T_Object<<4)+T_float] = T_undefined;
- // table[(T_Object<<4)+T_boolean] = T_undefined;
- // table[(T_Object<<4)+T_char] = T_undefined;
- // table[(T_Object<<4)+T_int] = T_undefined;
- table[(T_JavaLangObject<<4)+T_null] = /*Object2Object null2Object*/
- (T_JavaLangObject<<16)+(T_JavaLangObject<<12)+(T_JavaLangObject<<8)+(T_null<<4)+T_boolean;
- table[(T_JavaLangObject<<4)+T_any] = T_boolean;
-
- // table[(T_double<<4)+T_undefined] = T_undefined;
- table[(T_double<<4)+T_long] = (Double2Double<<12)+(Long2Double<<4)+T_boolean;
- table[(T_double<<4)+T_short] = (Double2Double<<12)+(Short2Double<<4)+T_boolean;
- // table[(T_double<<4)+T_void] = T_undefined;
- // table[(T_double<<4)+T_JavaLangString] = T_undefined;
- // table[(T_double<<4)+T_Object] = T_undefined;
- table[(T_double<<4)+T_double] = (Double2Double<<12)+(Double2Double<<4)+T_boolean;
- table[(T_double<<4)+T_float] = (Double2Double<<12)+(Float2Double<<4)+T_boolean;
- // table[(T_double<<4)+T_boolean] = T_undefined;
- table[(T_double<<4)+T_char] = (Double2Double<<12)+(Char2Double<<4)+T_boolean;
- table[(T_double<<4)+T_int] = (Double2Double<<12)+(Int2Double<<4)+T_boolean;
- // table[(T_double<<4)+T_null] = T_undefined;
- table[(T_double<<4)+T_any] = T_boolean;
-
- // table[(T_float<<4)+T_undefined] = T_undefined;
- table[(T_float<<4)+T_long] = (Float2Float<<12)+(Long2Float<<4)+T_boolean;
- table[(T_float<<4)+T_short] = (Float2Float<<12)+(Short2Float<<4)+T_boolean;
- // table[(T_float<<4)+T_void] = T_undefined;
- // table[(T_float<<4)+T_JavaLangString] = T_undefined;
- // table[(T_float<<4)+T_Object] = T_undefined;
- table[(T_float<<4)+T_double] = (Float2Double<<12)+(Double2Double<<4)+T_boolean;
- table[(T_float<<4)+T_float] = (Float2Float<<12)+(Float2Float<<4)+T_boolean;
- // table[(T_float<<4)+T_boolean] = T_undefined;
- table[(T_float<<4)+T_char] = (Float2Float<<12)+(Char2Float<<4)+T_boolean;
- table[(T_float<<4)+T_int] = (Float2Float<<12)+(Int2Float<<4)+T_boolean;
- // table[(T_float<<4)+T_null] = T_undefined;
- table[(T_float<<4)+T_any] = T_boolean;
-
- // table[(T_boolean<<4)+T_undefined] = T_undefined;
- // table[(T_boolean<<4)+T_byte] = T_undefined;
- // table[(T_boolean<<4)+T_long] = T_undefined;
- // table[(T_boolean<<4)+T_short] = T_undefined;
- // table[(T_boolean<<4)+T_void] = T_undefined;
- // table[(T_boolean<<4)+T_JavaLangString] = T_undefined;
- // table[(T_boolean<<4)+T_Object] = T_undefined;
- // table[(T_boolean<<4)+T_double] = T_undefined;
- // table[(T_boolean<<4)+T_float] = T_undefined;
- table[(T_boolean<<4)+T_boolean] = (Boolean2Boolean<<12)+(Boolean2Boolean<<4)+T_boolean;
- // table[(T_boolean<<4)+T_char] = T_undefined;
- // table[(T_boolean<<4)+T_int] = T_undefined;
- // table[(T_boolean<<4)+T_null] = T_undefined;
- table[(T_boolean<<4)+T_any] = T_boolean;
-
- // table[(T_char<<4)+T_undefined] = T_undefined;
- table[(T_char<<4)+T_long] = (Char2Long<<12)+(Long2Long<<4)+T_boolean;
- table[(T_char<<4)+T_short] = (Char2Int<<12)+(Short2Int<<4)+T_boolean;
- // table[(T_char<<4)+T_void] = T_undefined;
- table[(T_char<<4)+T_JavaLangString] = T_boolean;
- // table[(T_char<<4)+T_Object] = T_undefined;
- table[(T_char<<4)+T_double] = (Char2Double<<12)+(Double2Double<<4)+T_boolean;
- table[(T_char<<4)+T_float] = (Char2Float<<12)+(Float2Float<<4)+T_boolean;
- // table[(T_char<<4)+T_boolean] = T_undefined;
- table[(T_char<<4)+T_char] = (Char2Int<<12)+(Char2Int<<4)+T_boolean;
- table[(T_char<<4)+T_int] = (Char2Int<<12)+(Int2Int<<4)+T_boolean;
- // table[(T_char<<4)+T_null] = T_undefined;
- table[(T_char<<4)+T_any] = T_boolean;
-
- // table[(T_int<<4)+T_undefined] = T_undefined;
- table[(T_int<<4)+T_long] = (Int2Long<<12)+(Long2Long<<4)+T_boolean;
- table[(T_int<<4)+T_short] = (Int2Int<<12)+(Short2Int<<4)+T_boolean;
- // table[(T_int<<4)+T_void] = T_undefined;
- // table[(T_int<<4)+T_JavaLangString] = T_undefined;
- // table[(T_int<<4)+T_Object] = T_undefined;
- table[(T_int<<4)+T_double] = (Int2Double<<12)+(Double2Double<<4)+T_boolean;
- table[(T_int<<4)+T_float] = (Int2Float<<12)+(Float2Float<<4)+T_boolean;
- // table[(T_int<<4)+T_boolean] = T_undefined;
- table[(T_int<<4)+T_char] = (Int2Int<<12)+(Char2Int<<4)+T_boolean;
- table[(T_int<<4)+T_int] = (Int2Int<<12)+(Int2Int<<4)+T_boolean;
- // table[(T_int<<4)+T_null] = T_undefined;
- table[(T_int<<4)+T_any] = T_boolean;
-
- // table[(T_null<<4)+T_undefined] = T_undefined;
- // table[(T_null<<4)+T_byte] = T_undefined;
- // table[(T_null<<4)+T_long] = T_undefined;
- // table[(T_null<<4)+T_short] = T_undefined;
- // table[(T_null<<4)+T_void] = T_undefined;
- table[(T_null<<4)+T_JavaLangString] = /*null2Object String2Object*/
- (T_JavaLangObject<<16)+(T_null<<12)+(T_JavaLangObject<<8)+(T_JavaLangString<<4)+T_boolean;
- table[(T_null<<4)+T_JavaLangObject] = /*null2Object Object2Object*/
- (T_JavaLangObject<<16)+(T_null<<12)+(T_JavaLangObject<<8)+(T_JavaLangObject<<4)+T_boolean;
- // table[(T_null<<4)+T_double] = T_undefined;
- // table[(T_null<<4)+T_float] = T_undefined;
- // table[(T_null<<4)+T_boolean] = T_undefined;
- // table[(T_null<<4)+T_char] = T_undefined;
- // table[(T_null<<4)+T_int] = T_undefined;
- table[(T_null<<4)+T_null] = /*null2Object null2Object*/
- (T_JavaLangObject<<16)+(T_null<<12)+(T_JavaLangObject<<8)+(T_null<<4)+T_boolean;
- table[(T_null<<4)+T_function] = T_boolean;
- table[(T_null<<4)+T_any] = T_boolean;
-
- table[(T_any<<4)+T_undefined] = T_undefined;
- table[(T_any<<4)+T_long] = T_boolean;
- table[(T_any<<4)+T_short] = T_boolean;
- table[(T_any<<4)+T_void] = T_undefined;
- table[(T_any<<4)+T_JavaLangString] = T_boolean;
- table[(T_any<<4)+T_JavaLangObject] = T_boolean;
- table[(T_any<<4)+T_double] = T_boolean;
- table[(T_any<<4)+T_float] = T_boolean;
- table[(T_any<<4)+T_boolean] = T_boolean;
- table[(T_any<<4)+T_char] = T_boolean;
- table[(T_any<<4)+T_int] = T_boolean;
- table[(T_any<<4)+T_null] = T_boolean;
- table[(T_any<<4)+T_any] = T_boolean;
- table[(T_any<<4)+T_function] = T_boolean;
-
- table[(T_function<<4)+T_undefined] = T_boolean;
- table[(T_function<<4)+T_JavaLangString] = T_boolean;
- table[(T_function<<4)+T_JavaLangObject] = T_boolean;
- table[(T_function<<4)+T_null] = T_boolean;
- table[(T_function<<4)+T_any] = T_boolean;
- table[(T_function<<4)+T_function] = T_boolean;
-
-
- return table;
- }
-
- public static final int[] get_GREATER(){
-
- //the code is an int
- // (cast) left Op (cast) rigth --> result
- // 0000 0000 0000 0000 0000
- // <<16 <<12 <<8 <<4
-
- // int[] table = new int[16*16];
- return get_LESS();
- }
-
- public static final int[] get_GREATER_EQUAL(){
-
- //the code is an int
- // (cast) left Op (cast) rigth --> result
- // 0000 0000 0000 0000 0000
- // <<16 <<12 <<8 <<4
-
- // int[] table = new int[16*16];
- return get_LESS();
- }
-
- public static final int[] get_LEFT_SHIFT(){
-
- //the code is an int
- // (cast) left Op (cast) rigth --> result
- // 0000 0000 0000 0000 0000
- // <<16 <<12 <<8 <<4
-
- int[] table = new int[16*16];
-
- // table[(T_undefined<<4)+T_undefined] = T_undefined;
- // table[(T_undefined<<4)+T_byte] = T_undefined;
- // table[(T_undefined<<4)+T_long] = T_undefined;
- // table[(T_undefined<<4)+T_short] = T_undefined;
- // table[(T_undefined<<4)+T_void] = T_undefined;
- // table[(T_undefined<<4)+T_JavaLangString] = T_undefined;
- // table[(T_undefined<<4)+T_Object] = T_undefined;
- // table[(T_undefined<<4)+T_double] = T_undefined;
- // table[(T_undefined<<4)+T_float] = T_undefined;
- // table[(T_undefined<<4)+T_boolean] = T_undefined;
- // table[(T_undefined<<4)+T_char] = T_undefined;
- // table[(T_undefined<<4)+T_int] = T_undefined;
- // table[(T_undefined<<4)+T_null] = T_undefined;
-
- // table[(T_long<<4)+T_undefined] = T_undefined;
- table[(T_long<<4)+T_long] = (Long2Long<<12)+(Long2Int<<4)+T_long;
- table[(T_long<<4)+T_short] = (Long2Long<<12)+(Short2Int<<4)+T_long;
- // table[(T_long<<4)+T_void] = T_undefined;
- // table[(T_long<<4)+T_JavaLangString] = T_undefined;
- // table[(T_long<<4)+T_Object] = T_undefined;
- // table[(T_long<<4)+T_double] = T_undefined;
- // table[(T_long<<4)+T_float] = T_undefined;
- // table[(T_long<<4)+T_boolean] = T_undefined;
- table[(T_long<<4)+T_char] = (Long2Long<<12)+(Char2Int<<4)+T_long;
- table[(T_long<<4)+T_int] = (Long2Long<<12)+(Int2Int<<4)+T_long;
- // table[(T_long<<4)+T_null] = T_undefined;
- table[(T_long<<4)+T_any] = T_any;
-
- // table[(T_short<<4)+T_undefined] = T_undefined;
- table[(T_short<<4)+T_long] = (Short2Int<<12)+(Long2Int<<4)+T_int;
- table[(T_short<<4)+T_short] = (Short2Int<<12)+(Short2Int<<4)+T_int;
- // table[(T_short<<4)+T_void] = T_undefined;
- // table[(T_short<<4)+T_JavaLangString] = T_undefined;
- // table[(T_short<<4)+T_Object] = T_undefined;
- // table[(T_short<<4)+T_double] = T_undefined;
- // table[(T_short<<4)+T_float] = T_undefined;
- // table[(T_short<<4)+T_boolean] = T_undefined;
- table[(T_short<<4)+T_char] = (Short2Int<<12)+(Char2Int<<4)+T_int;
- table[(T_short<<4)+T_int] = (Short2Int<<12)+(Int2Int<<4)+T_int;
- // table[(T_short<<4)+T_null] = T_undefined;
- table[(T_void<<4)+T_any] = T_any;
-
- // table[(T_void<<4)+T_undefined] = T_undefined;
- // table[(T_void<<4)+T_byte] = T_undefined;
- // table[(T_void<<4)+T_long] = T_undefined;
- // table[(T_void<<4)+T_short] = T_undefined;
- // table[(T_void<<4)+T_void] = T_undefined;
- // table[(T_void<<4)+T_JavaLangString] = T_undefined;
- // table[(T_void<<4)+T_Object] = T_undefined;
- // table[(T_void<<4)+T_double] = T_undefined;
- // table[(T_void<<4)+T_float] = T_undefined;
- // table[(T_void<<4)+T_boolean] = T_undefined;
- // table[(T_void<<4)+T_char] = T_undefined;
- // table[(T_void<<4)+T_int] = T_undefined;
- // table[(T_void<<4)+T_null] = T_undefined;
- table[(T_void<<4)+T_any] = T_any;
-
- // table[(T_JavaLangString<<4)+T_undefined] = T_undefined;
- // table[(T_JavaLangString<<4)+T_byte] = T_undefined;
- // table[(T_JavaLangString<<4)+T_long] = T_undefined;
- // table[(T_JavaLangString<<4)+T_short] = T_undefined;
- // table[(T_JavaLangString<<4)+T_void] = T_undefined;
- // table[(T_JavaLangString<<4)+T_JavaLangString] = T_undefined;
- // table[(T_JavaLangString<<4)+T_Object] = T_undefined;
- // table[(T_JavaLangString<<4)+T_double] = T_undefined;
- // table[(T_JavaLangString<<4)+T_float] = T_undefined;
- // table[(T_JavaLangString<<4)+T_boolean] = T_undefined;
- // table[(T_JavaLangString<<4)+T_char] = T_undefined;
- // table[(T_JavaLangString<<4)+T_int] = T_undefined;
- // table[(T_JavaLangString<<4)+T_null] = T_undefined;
- table[(T_JavaLangString<<4)+T_any] = T_any;
-
- // table[(T_Object<<4)+T_undefined] = T_undefined;
- // table[(T_Object<<4)+T_byte] = T_undefined;
- // table[(T_Object<<4)+T_long] = T_undefined;
- // table[(T_Object<<4)+T_short] = T_undefined;
- // table[(T_Object<<4)+T_void] = T_undefined;
- // table[(T_Object<<4)+T_JavaLangString] = T_undefined;
- // table[(T_Object<<4)+T_Object] = T_undefined;
- // table[(T_Object<<4)+T_double] = T_undefined;
- // table[(T_Object<<4)+T_float] = T_undefined;
- // table[(T_Object<<4)+T_boolean] = T_undefined;
- // table[(T_Object<<4)+T_char] = T_undefined;
- // table[(T_Object<<4)+T_int] = T_undefined;
- // table[(T_Object<<4)+T_null] = T_undefined;
- table[(T_JavaLangObject<<4)+T_any] = T_any;
-
- // table[(T_double<<4)+T_undefined] = T_undefined;
- // table[(T_double<<4)+T_byte] = T_undefined;
- // table[(T_double<<4)+T_long] = T_undefined;
- // table[(T_double<<4)+T_short] = T_undefined;
- // table[(T_double<<4)+T_void] = T_undefined;
- // table[(T_double<<4)+T_JavaLangString] = T_undefined;
- // table[(T_double<<4)+T_Object] = T_undefined;
- // table[(T_double<<4)+T_double] = T_undefined;
- // table[(T_double<<4)+T_float] = T_undefined;
- // table[(T_double<<4)+T_boolean] = T_undefined;
- // table[(T_double<<4)+T_char] = T_undefined;
- // table[(T_double<<4)+T_int] = T_undefined;
- // table[(T_double<<4)+T_null] = T_undefined;
- table[(T_double<<4)+T_any] = T_any;
-
- // table[(T_float<<4)+T_undefined] = T_undefined;
- // table[(T_float<<4)+T_byte] = T_undefined;
- // table[(T_float<<4)+T_long] = T_undefined;
- // table[(T_float<<4)+T_short] = T_undefined;
- // table[(T_float<<4)+T_void] = T_undefined;
- // table[(T_float<<4)+T_JavaLangString] = T_undefined;
- // table[(T_float<<4)+T_Object] = T_undefined;
- // table[(T_float<<4)+T_double] = T_undefined;
- // table[(T_float<<4)+T_float] = T_undefined;
- // table[(T_float<<4)+T_boolean] = T_undefined;
- // table[(T_float<<4)+T_char] = T_undefined;
- // table[(T_float<<4)+T_int] = T_undefined;
- // table[(T_float<<4)+T_null] = T_undefined;
- table[(T_float<<4)+T_any] = T_any;
-
- // table[(T_boolean<<4)+T_undefined] = T_undefined;
- // table[(T_boolean<<4)+T_byte] = T_undefined;
- // table[(T_boolean<<4)+T_long] = T_undefined;
- // table[(T_boolean<<4)+T_short] = T_undefined;
- // table[(T_boolean<<4)+T_void] = T_undefined;
- // table[(T_boolean<<4)+T_JavaLangString] = T_undefined;
- // table[(T_boolean<<4)+T_Object] = T_undefined;
- // table[(T_boolean<<4)+T_double] = T_undefined;
- // table[(T_boolean<<4)+T_float] = T_undefined;
- // table[(T_boolean<<4)+T_boolean] = T_undefined;
- // table[(T_boolean<<4)+T_char] = T_undefined;
- // table[(T_boolean<<4)+T_int] = T_undefined;
- // table[(T_boolean<<4)+T_null] = T_undefined;
- table[(T_boolean<<4)+T_any] = T_any;
-
- // table[(T_char<<4)+T_undefined] = T_undefined;
- table[(T_char<<4)+T_long] = (Char2Int<<12)+(Long2Int<<4)+T_int;
- table[(T_char<<4)+T_short] = (Char2Int<<12)+(Short2Int<<4)+T_int;
- // table[(T_char<<4)+T_void] = T_undefined;
- // table[(T_char<<4)+T_JavaLangString] = T_undefined;
- // table[(T_char<<4)+T_Object] = T_undefined;
- // table[(T_char<<4)+T_double] = T_undefined;
- // table[(T_char<<4)+T_float] = T_undefined;
- // table[(T_char<<4)+T_boolean] = T_undefined;
- table[(T_char<<4)+T_char] = (Char2Int<<12)+(Char2Int<<4)+T_int;
- table[(T_char<<4)+T_int] = (Char2Int<<12)+(Int2Int<<4)+T_int;
- // table[(T_char<<4)+T_null] = T_undefined;
- table[(T_char<<4)+T_any] = T_any;
-
- // table[(T_int<<4)+T_undefined] = T_undefined;
- table[(T_int<<4)+T_long] = (Int2Int<<12)+(Long2Int<<4)+T_int;
- table[(T_int<<4)+T_short] = (Int2Int<<12)+(Short2Int<<4)+T_int;
- // table[(T_int<<4)+T_void] = T_undefined;
- // table[(T_int<<4)+T_JavaLangString] = T_undefined;
- // table[(T_int<<4)+T_Object] = T_undefined;
- // table[(T_int<<4)+T_double] = T_undefined;
- // table[(T_int<<4)+T_float] = T_undefined;
- // table[(T_int<<4)+T_boolean] = T_undefined;
- table[(T_int<<4)+T_char] = (Int2Int<<12)+(Char2Int<<4)+T_int;
- table[(T_int<<4)+T_int] = (Int2Int<<12)+(Int2Int<<4)+T_int;
- // table[(T_int<<4)+T_null] = T_undefined;
- table[(T_int<<4)+T_any] = T_any;
-
- // table[(T_null<<4)+T_undefined] = T_undefined;
- // table[(T_null<<4)+T_byte] = T_undefined;
- // table[(T_null<<4)+T_long] = T_undefined;
- // table[(T_null<<4)+T_short] = T_undefined;
- // table[(T_null<<4)+T_void] = T_undefined;
- // table[(T_null<<4)+T_JavaLangString] = T_undefined;
- // table[(T_null<<4)+T_Object] = T_undefined;
- // table[(T_null<<4)+T_double] = T_undefined;
- // table[(T_null<<4)+T_float] = T_undefined;
- // table[(T_null<<4)+T_boolean] = T_undefined;
- // table[(T_null<<4)+T_char] = T_undefined;
- // table[(T_null<<4)+T_int] = T_undefined;
- // table[(T_null<<4)+T_null] = T_undefined;
- table[(T_null<<4)+T_any] = T_any;
-
-
- table[(T_any<<4)+T_undefined] = T_any;
- table[(T_any<<4)+T_long] = T_any;
- table[(T_any<<4)+T_short] = T_any;
- table[(T_any<<4)+T_void] = T_any;
- table[(T_any<<4)+T_JavaLangString] = T_any;
- table[(T_any<<4)+T_JavaLangObject] = T_any;
- table[(T_any<<4)+T_double] = T_any;
- table[(T_any<<4)+T_float] = T_any;
- table[(T_any<<4)+T_boolean] = T_any;
- table[(T_any<<4)+T_char] = T_any;
- table[(T_any<<4)+T_int] = T_any;
- table[(T_any<<4)+T_null] = T_any;
- table[(T_any<<4)+T_any] = T_any;
-
- return table;
- }
-
- public static final int[] get_LESS(){
-
- //the code is an int
- // (cast) left Op (cast) rigth --> result
- // 0000 0000 0000 0000 0000
- // <<16 <<12 <<8 <<4
-
- int[] table = new int[16*16];
-
- // table[(T_undefined<<4)+T_undefined] = T_undefined;
- // table[(T_undefined<<4)+T_byte] = T_undefined;
- // table[(T_undefined<<4)+T_long] = T_undefined;
- // table[(T_undefined<<4)+T_short] = T_undefined;
- // table[(T_undefined<<4)+T_void] = T_undefined;
- // table[(T_undefined<<4)+T_JavaLangString] = T_undefined;
- // table[(T_undefined<<4)+T_Object] = T_undefined;
- // table[(T_undefined<<4)+T_double] = T_undefined;
- // table[(T_undefined<<4)+T_float] = T_undefined;
- // table[(T_undefined<<4)+T_boolean] = T_undefined;
- // table[(T_undefined<<4)+T_char] = T_undefined;
- // table[(T_undefined<<4)+T_int] = T_undefined;
- // table[(T_undefined<<4)+T_null] = T_undefined;
-
- // table[(T_long<<4)+T_undefined] = T_undefined;
- table[(T_long<<4)+T_long] = (Long2Long<<12)+(Long2Long<<4)+T_boolean;
- table[(T_long<<4)+T_short] = (Long2Long<<12)+(Short2Long<<4)+T_boolean;
- // table[(T_long<<4)+T_void] = T_undefined;
- // table[(T_long<<4)+T_JavaLangString] = T_undefined;
- // table[(T_long<<4)+T_Object] = T_undefined;
- table[(T_long<<4)+T_double] = (Long2Double<<12)+(Double2Double<<4)+T_boolean;
- table[(T_long<<4)+T_float] = (Long2Float<<12)+(Float2Float<<4)+T_boolean;
- // table[(T_long<<4)+T_boolean] = T_undefined;
- table[(T_long<<4)+T_char] = (Long2Long<<12)+(Char2Long<<4)+T_boolean;
- table[(T_long<<4)+T_int] = (Long2Long<<12)+(Int2Long<<4)+T_boolean;
- // table[(T_long<<4)+T_null] = T_undefined;
- table[(T_long<<4)+T_any] = T_boolean;
-
- // table[(T_short<<4)+T_undefined] = T_undefined;
- table[(T_short<<4)+T_long] = (Short2Long<<12)+(Long2Long<<4)+T_boolean;
- table[(T_short<<4)+T_short] = (Short2Int<<12)+(Short2Int<<4)+T_boolean;
- // table[(T_short<<4)+T_void] = T_undefined;
- // table[(T_short<<4)+T_JavaLangString] = T_undefined;
- // table[(T_short<<4)+T_Object] = T_undefined;
- table[(T_short<<4)+T_double] = (Short2Double<<12)+(Double2Double<<4)+T_boolean;
- table[(T_short<<4)+T_float] = (Short2Float<<12)+(Float2Float<<4)+T_boolean;
- // table[(T_short<<4)+T_boolean] = T_undefined;
- table[(T_short<<4)+T_char] = (Short2Int<<12)+(Char2Int<<4)+T_boolean;
- table[(T_short<<4)+T_int] = (Short2Int<<12)+(Int2Int<<4)+T_boolean;
- // table[(T_short<<4)+T_null] = T_undefined;
- table[(T_short<<4)+T_any] = T_boolean;
-
- // table[(T_void<<4)+T_undefined] = T_undefined;
- // table[(T_void<<4)+T_byte] = T_undefined;
- // table[(T_void<<4)+T_long] = T_undefined;
- // table[(T_void<<4)+T_short] = T_undefined;
- // table[(T_void<<4)+T_void] = T_undefined;
- // table[(T_void<<4)+T_JavaLangString] = T_undefined;
- // table[(T_void<<4)+T_Object] = T_undefined;
- // table[(T_void<<4)+T_double] = T_undefined;
- // table[(T_void<<4)+T_float] = T_undefined;
- // table[(T_void<<4)+T_boolean] = T_undefined;
- // table[(T_void<<4)+T_char] = T_undefined;
- // table[(T_void<<4)+T_int] = T_undefined;
- // table[(T_void<<4)+T_null] = T_undefined;
- table[(T_void<<4)+T_any] = T_undefined;
-
- // table[(T_JavaLangString<<4)+T_undefined] = T_undefined;
- // table[(T_JavaLangString<<4)+T_byte] = T_undefined;
- // table[(T_JavaLangString<<4)+T_long] = T_undefined;
- // table[(T_JavaLangString<<4)+T_short] = T_undefined;
- // table[(T_JavaLangString<<4)+T_void] = T_undefined;
- table[(T_JavaLangString<<4)+T_JavaLangString] = T_boolean;
- // table[(T_JavaLangString<<4)+T_Object] = T_undefined;
- // table[(T_JavaLangString<<4)+T_double] = T_undefined;
- // table[(T_JavaLangString<<4)+T_float] = T_undefined;
- // table[(T_JavaLangString<<4)+T_boolean] = T_undefined;
- table[(T_JavaLangString<<4)+T_char] = T_boolean;
- table[(T_JavaLangString<<4)+T_int] = T_boolean;
- // table[(T_JavaLangString<<4)+T_null] = T_undefined;
- table[(T_JavaLangString<<4)+T_any] = T_boolean;
-
- // table[(T_Object<<4)+T_undefined] = T_undefined;
- // table[(T_Object<<4)+T_byte] = T_undefined;
- // table[(T_Object<<4)+T_long] = T_undefined;
- // table[(T_Object<<4)+T_short] = T_undefined;
- // table[(T_Object<<4)+T_void] = T_undefined;
- // table[(T_Object<<4)+T_JavaLangString] = T_undefined;
- // table[(T_Object<<4)+T_Object] = T_undefined;
- // table[(T_Object<<4)+T_double] = T_undefined;
- // table[(T_Object<<4)+T_float] = T_undefined;
- // table[(T_Object<<4)+T_boolean] = T_undefined;
- // table[(T_Object<<4)+T_char] = T_undefined;
- // table[(T_Object<<4)+T_int] = T_undefined;
- // table[(T_Object<<4)+T_null] = T_undefined;
- table[(T_JavaLangObject<<4)+T_any] = T_boolean;
-
- // table[(T_double<<4)+T_undefined] = T_undefined;
- table[(T_double<<4)+T_long] = (Double2Double<<12)+(Long2Double<<4)+T_boolean;
- table[(T_double<<4)+T_short] = (Double2Double<<12)+(Short2Double<<4)+T_boolean;
- // table[(T_double<<4)+T_void] = T_undefined;
- // table[(T_double<<4)+T_JavaLangString] = T_undefined;
- // table[(T_double<<4)+T_Object] = T_undefined;
- table[(T_double<<4)+T_double] = (Double2Double<<12)+(Double2Double<<4)+T_boolean;
- table[(T_double<<4)+T_float] = (Double2Double<<12)+(Float2Double<<4)+T_boolean;
- // table[(T_double<<4)+T_boolean] = T_undefined;
- table[(T_double<<4)+T_char] = (Double2Double<<12)+(Char2Double<<4)+T_boolean;
- table[(T_double<<4)+T_int] = (Double2Double<<12)+(Int2Double<<4)+T_boolean;
- // table[(T_double<<4)+T_null] = T_undefined;
- table[(T_double<<4)+T_any] = T_boolean;
-
- // table[(T_float<<4)+T_undefined] = T_undefined;
- table[(T_float<<4)+T_long] = (Float2Float<<12)+(Long2Float<<4)+T_boolean;
- table[(T_float<<4)+T_short] = (Float2Float<<12)+(Short2Float<<4)+T_boolean;
- // table[(T_float<<4)+T_void] = T_undefined;
- // table[(T_float<<4)+T_JavaLangString] = T_undefined;
- // table[(T_float<<4)+T_Object] = T_undefined;
- table[(T_float<<4)+T_double] = (Float2Double<<12)+(Double2Double<<4)+T_boolean;
- table[(T_float<<4)+T_float] = (Float2Float<<12)+(Float2Float<<4)+T_boolean;
- // table[(T_float<<4)+T_boolean] = T_undefined;
- table[(T_float<<4)+T_char] = (Float2Float<<12)+(Char2Float<<4)+T_boolean;
- table[(T_float<<4)+T_int] = (Float2Float<<12)+(Int2Float<<4)+T_boolean;
- // table[(T_float<<4)+T_null] = T_undefined;
- table[(T_float<<4)+T_any] = T_boolean;
-
- // table[(T_boolean<<4)+T_undefined] = T_undefined;
- // table[(T_boolean<<4)+T_byte] = T_undefined;
- // table[(T_boolean<<4)+T_long] = T_undefined;
- // table[(T_boolean<<4)+T_short] = T_undefined;
- // table[(T_boolean<<4)+T_void] = T_undefined;
- // table[(T_boolean<<4)+T_JavaLangString] = T_undefined;
- // table[(T_boolean<<4)+T_Object] = T_undefined;
- // table[(T_boolean<<4)+T_double] = T_undefined;
- // table[(T_boolean<<4)+T_float] = T_undefined;
- // table[(T_boolean<<4)+T_boolean] = T_undefined;
- // table[(T_boolean<<4)+T_char] = T_undefined;
- // table[(T_boolean<<4)+T_int] = T_undefined;
- // table[(T_boolean<<4)+T_null] = T_undefined;
- table[(T_boolean<<4)+T_any] = T_undefined;
-
- // table[(T_char<<4)+T_undefined] = T_undefined;
- table[(T_char<<4)+T_long] = (Char2Long<<12)+(Long2Long<<4)+T_boolean;
- table[(T_char<<4)+T_short] = (Char2Int<<12)+(Short2Int<<4)+T_boolean;
- // table[(T_char<<4)+T_void] = T_undefined;
- table[(T_char<<4)+T_JavaLangString] = T_undefined;
- // table[(T_char<<4)+T_Object] = T_undefined;
- table[(T_char<<4)+T_double] = (Char2Double<<12)+(Double2Double<<4)+T_boolean;
- table[(T_char<<4)+T_float] = (Char2Float<<12)+(Float2Float<<4)+T_boolean;
- // table[(T_char<<4)+T_boolean] = T_undefined;
- table[(T_char<<4)+T_JavaLangString] = (Char2Int<<12)+(Char2Int<<4)+T_boolean;
- table[(T_char<<4)+T_int] = (Char2Int<<12)+(Int2Int<<4)+T_boolean;
- // table[(T_char<<4)+T_null] = T_undefined;
- table[(T_char<<4)+T_any] = T_boolean;
-
- // table[(T_int<<4)+T_undefined] = T_undefined;
- table[(T_int<<4)+T_long] = (Int2Long<<12)+(Long2Long<<4)+T_boolean;
- table[(T_int<<4)+T_short] = (Int2Int<<12)+(Short2Int<<4)+T_boolean;
- // table[(T_int<<4)+T_void] = T_undefined;
- table[(T_int<<4)+T_JavaLangString] = T_boolean;
- // table[(T_int<<4)+T_Object] = T_undefined;
- table[(T_int<<4)+T_double] = (Int2Double<<12)+(Double2Double<<4)+T_boolean;
- table[(T_int<<4)+T_float] = (Int2Float<<12)+(Float2Float<<4)+T_boolean;
- // table[(T_int<<4)+T_boolean] = T_undefined;
- table[(T_int<<4)+T_char] = (Int2Int<<12)+(Char2Int<<4)+T_boolean;
- table[(T_int<<4)+T_int] = (Int2Int<<12)+(Int2Int<<4)+T_boolean;
- // table[(T_int<<4)+T_null] = T_undefined;
- table[(T_int<<4)+T_any] = T_boolean;
-
- // table[(T_null<<4)+T_undefined] = T_undefined;
- // table[(T_null<<4)+T_byte] = T_undefined;
- // table[(T_null<<4)+T_long] = T_undefined;
- // table[(T_null<<4)+T_short] = T_undefined;
- // table[(T_null<<4)+T_void] = T_undefined;
- // table[(T_null<<4)+T_JavaLangString] = T_undefined;
- // table[(T_null<<4)+T_Object] = T_undefined;
- // table[(T_null<<4)+T_double] = T_undefined;
- // table[(T_null<<4)+T_float] = T_undefined;
- // table[(T_null<<4)+T_boolean] = T_undefined;
- // table[(T_null<<4)+T_char] = T_undefined;
- // table[(T_null<<4)+T_int] = T_undefined;
- // table[(T_null<<4)+T_null] = T_undefined;
-
- table[(T_any<<4)+T_undefined] = T_boolean;
- table[(T_any<<4)+T_long] = T_boolean;
- table[(T_any<<4)+T_short] = T_boolean;
- table[(T_any<<4)+T_void] = T_boolean;
- table[(T_any<<4)+T_JavaLangString] = T_boolean;
- table[(T_any<<4)+T_JavaLangObject] = T_boolean;
- table[(T_any<<4)+T_double] = T_boolean;
- table[(T_any<<4)+T_float] = T_boolean;
- table[(T_any<<4)+T_boolean] = T_boolean;
- table[(T_any<<4)+T_char] = T_boolean;
- table[(T_any<<4)+T_int] = T_boolean;
- table[(T_any<<4)+T_null] = T_boolean;
- table[(T_any<<4)+T_any] = T_boolean;
-
- return table;
- }
-
- public static final int[] get_LESS_EQUAL(){
-
- //the code is an int
- // (cast) left Op (cast) rigth --> result
- // 0000 0000 0000 0000 0000
- // <<16 <<12 <<8 <<4
-
- // int[] table = new int[16*16];
- return get_LESS();
- }
-
- public static final int[] get_MINUS(){
-
- //the code is an int
- // (cast) left Op (cast) rigth --> result
- // 0000 0000 0000 0000 0000
- // <<16 <<12 <<8 <<4
-
- int[] table = (int[]) get_PLUS().clone();
-
- // customization
- table[(T_JavaLangString<<4)+T_long] = T_undefined;
- table[(T_JavaLangString<<4)+T_short] = T_undefined;
- table[(T_JavaLangString<<4)+T_void] = T_undefined;
- table[(T_JavaLangString<<4)+T_JavaLangString] = T_int;
- table[(T_JavaLangString<<4)+T_JavaLangObject] = T_undefined;
- table[(T_JavaLangString<<4)+T_double] = T_undefined;
- table[(T_JavaLangString<<4)+T_float] = T_undefined;
- table[(T_JavaLangString<<4)+T_boolean] = T_undefined;
- table[(T_JavaLangString<<4)+T_char] = T_undefined;
- table[(T_JavaLangString<<4)+T_int] = T_int;
- table[(T_JavaLangString<<4)+T_null] = T_undefined;
- table[(T_JavaLangString<<4)+T_any] = T_int;
-
- table[(T_long<<4) +T_JavaLangString] = T_undefined;
- table[(T_short<<4) +T_JavaLangString] = T_undefined;
- table[(T_void<<4) +T_JavaLangString] = T_undefined;
- table[(T_JavaLangObject<<4) +T_JavaLangString] = T_undefined;
- table[(T_double<<4) +T_JavaLangString] = T_undefined;
- table[(T_float<<4) +T_JavaLangString] = T_undefined;
- table[(T_boolean<<4)+T_JavaLangString] = T_undefined;
- table[(T_char<<4) +T_JavaLangString] = T_undefined;
- table[(T_int<<4) +T_JavaLangString] = T_int;
- table[(T_null<<4) +T_JavaLangString] = T_undefined;
-
- table[(T_null<<4) +T_null] = T_undefined;
-
- table[(T_any<<4)+T_undefined] = T_any;
- table[(T_any<<4)+T_long] = T_any;
- table[(T_any<<4)+T_short] = T_any;
- table[(T_any<<4)+T_void] = T_any;
- table[(T_any<<4)+T_JavaLangString] = T_any;
- table[(T_any<<4)+T_JavaLangObject] = T_any;
- table[(T_any<<4)+T_double] = T_any;
- table[(T_any<<4)+T_float] = T_any;
- table[(T_any<<4)+T_boolean] = T_any;
- table[(T_any<<4)+T_char] = T_any;
- table[(T_any<<4)+T_int] = T_any;
- table[(T_any<<4)+T_null] = T_any;
- table[(T_any<<4)+T_any] = T_any;
-
- return table;
- }
-
- public static final int[] get_MULTIPLY(){
-
- //the code is an int
- // (cast) left Op (cast) rigth --> result
- // 0000 0000 0000 0000 0000
- // <<16 <<12 <<8 <<4
-
- // int[] table = new int[16*16];
- return get_MINUS();
- }
-
- public static final int[] get_OR(){
-
- //the code is an int
- // (cast) left Op (cast) rigth --> result
- // 0000 0000 0000 0000 0000
- // <<16 <<12 <<8 <<4
-
-
- // int[] table = new int[16*16];
- return get_AND();
- }
-
- public static final int[] get_OR_OR(){
-
- return get_AND_AND();
- }
-
- public static final int[] get_PLUS(){
-
- //the code is an int
- // (cast) left Op (cast) rigth --> result
- // 0000 0000 0000 0000 0000
- // <<16 <<12 <<8 <<4
-
- int[] table = new int[16*16];
-
- // table[(T_undefined<<4)+T_undefined] = T_undefined;
- // table[(T_undefined<<4)+T_byte] = T_undefined;
- // table[(T_undefined<<4)+T_long] = T_undefined;
- // table[(T_undefined<<4)+T_short] = T_undefined;
- // table[(T_undefined<<4)+T_void] = T_undefined;
- // table[(T_undefined<<4)+T_JavaLangString] = T_undefined;
- // table[(T_undefined<<4)+T_Object] = T_undefined;
- // table[(T_undefined<<4)+T_double] = T_undefined;
- // table[(T_undefined<<4)+T_float] = T_undefined;
- // table[(T_undefined<<4)+T_boolean] = T_undefined;
- // table[(T_undefined<<4)+T_char] = T_undefined;
- // table[(T_undefined<<4)+T_int] = T_undefined;
- // table[(T_undefined<<4)+T_null] = T_undefined;
-
- // table[(T_long<<4)+T_undefined] = T_undefined;
- table[(T_long<<4)+T_long] = (Long2Long<<12)+(Long2Long<<4)+T_long;
- table[(T_long<<4)+T_short] = (Long2Long<<12)+(Short2Long<<4)+T_long;
- // table[(T_long<<4)+T_void] = T_undefined;
- table[(T_long<<4)+T_JavaLangString] = (Long2Long<<12)+(String2String<<4)+T_JavaLangString;
- // table[(T_long<<4)+T_Object] = T_undefined;
- table[(T_long<<4)+T_double] = (Long2Double<<12)+(Double2Double<<4)+T_double;
- table[(T_long<<4)+T_float] = (Long2Float<<12)+(Float2Float<<4)+T_float;
- // table[(T_long<<4)+T_boolean] = T_undefined;
- table[(T_long<<4)+T_char] = (Long2Long<<12)+(Char2Long<<4)+T_long;
- table[(T_long<<4)+T_int] = (Long2Long<<12)+(Int2Long<<4)+T_long;
- // table[(T_long<<4)+T_null] = T_undefined;
- table[(T_long<<4)+T_any] = T_any;
-
- // table[(T_short<<4)+T_undefined] = T_undefined;
- table[(T_short<<4)+T_long] = (Short2Long<<12)+(Long2Long<<4)+T_long;
- table[(T_short<<4)+T_short] = (Short2Int<<12)+(Short2Int<<4)+T_int;
- // table[(T_short<<4)+T_void] = T_undefined;
- table[(T_short<<4)+T_JavaLangString] = (Short2Short<<12)+(String2String<<4)+T_JavaLangString;
- // table[(T_short<<4)+T_Object] = T_undefined;
- table[(T_short<<4)+T_double] = (Short2Double<<12)+(Double2Double<<4)+T_double;
- table[(T_short<<4)+T_float] = (Short2Float<<12)+(Float2Float<<4)+T_float;
- // table[(T_short<<4)+T_boolean] = T_undefined;
- table[(T_short<<4)+T_char] = (Short2Int<<12)+(Char2Int<<4)+T_int;
- table[(T_short<<4)+T_int] = (Short2Int<<12)+(Int2Int<<4)+T_int;
- // table[(T_short<<4)+T_null] = T_undefined;
- table[(T_short<<4)+T_any] = T_any;
-
- // table[(T_void<<4)+T_undefined] = T_undefined;
- // table[(T_void<<4)+T_byte] = T_undefined;
- // table[(T_void<<4)+T_long] = T_undefined;
- // table[(T_void<<4)+T_short] = T_undefined;
- // table[(T_void<<4)+T_void] = T_undefined;
- // table[(T_void<<4)+T_JavaLangString] = T_undefined;
- // table[(T_void<<4)+T_Object] = T_undefined;
- // table[(T_void<<4)+T_double] = T_undefined;
- // table[(T_void<<4)+T_float] = T_undefined;
- // table[(T_void<<4)+T_boolean] = T_undefined;
- // table[(T_void<<4)+T_char] = T_undefined;
- // table[(T_void<<4)+T_int] = T_undefined;
- // table[(T_void<<4)+T_null] = T_undefined;
- table[(T_void<<4)+T_any] = T_any;
-
- // table[(T_JavaLangString<<4)+T_undefined] = T_undefined;
- table[(T_JavaLangString<<4)+T_long] = (String2String<<12)+(Long2Long<<4)+T_JavaLangString;
- table[(T_JavaLangString<<4)+T_short] = (String2String<<12)+(Short2Short<<4)+T_JavaLangString;
- table[(T_JavaLangString<<4)+T_void] = T_JavaLangString;
- table[(T_JavaLangString<<4)+T_JavaLangString] = (String2String<<12)+(String2String<<4)+T_JavaLangString;
- table[(T_JavaLangString<<4)+T_JavaLangObject] = (String2String<<12)+(Object2Object<<4)+T_JavaLangString;
- table[(T_JavaLangString<<4)+T_double] = (String2String<<12)+(Double2Double<<4)+T_JavaLangString;
- table[(T_JavaLangString<<4)+T_float] = (String2String<<12)+(Float2Float<<4)+T_JavaLangString;
- table[(T_JavaLangString<<4)+T_boolean] = (String2String<<12)+(Boolean2Boolean<<4)+T_JavaLangString;
- table[(T_JavaLangString<<4)+T_char] = (String2String<<12)+(Char2Char<<4)+T_JavaLangString;
- table[(T_JavaLangString<<4)+T_int] = (String2String<<12)+(Int2Int<<4)+T_JavaLangString;
- table[(T_JavaLangString<<4)+T_null] = (String2String<<12)+(T_null<<8)+(T_null<<4)+T_JavaLangString;
- table[(T_JavaLangString<<4)+T_any] = T_JavaLangString;
- table[(T_JavaLangString<<4)+T_function] = T_any;
-
- // table[(T_Object<<4)+T_undefined] = T_undefined;
- // table[(T_Object<<4)+T_byte] = T_undefined;
- // table[(T_Object<<4)+T_long] = T_undefined;
- // table[(T_Object<<4)+T_short] = T_undefined;
- // table[(T_Object<<4)+T_void] = T_undefined;
- table[(T_JavaLangObject<<4)+T_JavaLangString] = (Object2Object<<12)+(String2String<<4)+T_JavaLangString;
- // table[(T_Object<<4)+T_Object] = T_undefined;
- // table[(T_Object<<4)+T_double] = T_undefined;
- // table[(T_Object<<4)+T_float] = T_undefined;
- // table[(T_Object<<4)+T_boolean] = T_undefined;
- // table[(T_Object<<4)+T_char] = T_undefined;
- table[(T_JavaLangObject<<4)+T_int] = T_int;
- // table[(T_Object<<4)+T_null] = T_undefined;
- table[(T_JavaLangObject<<4)+T_any] = T_any;
-
- // table[(T_double<<4)+T_undefined] = T_undefined;
- table[(T_double<<4)+T_long] = (Double2Double<<12)+(Long2Double<<4)+T_double;
- table[(T_double<<4)+T_short] = (Double2Double<<12)+(Short2Double<<4)+T_double;
- // table[(T_double<<4)+T_void] = T_undefined;
- table[(T_double<<4)+T_JavaLangString] = (Double2Double<<12)+(String2String<<4)+T_JavaLangString;
- // table[(T_double<<4)+T_Object] = T_undefined;
- table[(T_double<<4)+T_double] = (Double2Double<<12)+(Double2Double<<4)+T_double;
- table[(T_double<<4)+T_float] = (Double2Double<<12)+(Float2Double<<4)+T_double;
- // table[(T_double<<4)+T_boolean] = T_undefined;
- table[(T_double<<4)+T_char] = (Double2Double<<12)+(Char2Double<<4)+T_double;
- table[(T_double<<4)+T_int] = (Double2Double<<12)+(Int2Double<<4)+T_double;
- // table[(T_double<<4)+T_null] = T_undefined;
- table[(T_double<<4)+T_any] = T_any;
-
- // table[(T_float<<4)+T_undefined] = T_undefined;
- table[(T_float<<4)+T_long] = (Float2Float<<12)+(Long2Float<<4)+T_float;
- table[(T_float<<4)+T_short] = (Float2Float<<12)+(Short2Float<<4)+T_float;
- // table[(T_float<<4)+T_void] = T_undefined;
- table[(T_float<<4)+T_JavaLangString] = (Float2Float<<12)+(String2String<<4)+T_JavaLangString;
- // table[(T_float<<4)+T_Object] = T_undefined;
- table[(T_float<<4)+T_double] = (Float2Double<<12)+(Double2Double<<4)+T_double;
- table[(T_float<<4)+T_float] = (Float2Float<<12)+(Float2Float<<4)+T_float;
- // table[(T_float<<4)+T_boolean] = T_undefined;
- table[(T_float<<4)+T_char] = (Float2Float<<12)+(Char2Float<<4)+T_float;
- table[(T_float<<4)+T_int] = (Float2Float<<12)+(Int2Float<<4)+T_float;
- // table[(T_float<<4)+T_null] = T_undefined;
- table[(T_float<<4)+T_any] = T_any;
-
- // table[(T_boolean<<4)+T_undefined] = T_undefined;
- // table[(T_boolean<<4)+T_byte] = T_undefined;
- // table[(T_boolean<<4)+T_long] = T_undefined;
- // table[(T_boolean<<4)+T_short] = T_undefined;
- // table[(T_boolean<<4)+T_void] = T_undefined;
- table[(T_boolean<<4)+T_JavaLangString] = (Boolean2Boolean<<12)+(String2String<<4)+T_JavaLangString;
- // table[(T_boolean<<4)+T_Object] = T_undefined;
- // table[(T_boolean<<4)+T_double] = T_undefined;
- // table[(T_boolean<<4)+T_float] = T_undefined;
- // table[(T_boolean<<4)+T_boolean] = T_undefined;
- // table[(T_boolean<<4)+T_char] = T_undefined;
- // table[(T_boolean<<4)+T_int] = T_undefined;
- // table[(T_boolean<<4)+T_null] = T_undefined;
- table[(T_boolean<<4)+T_any] = T_any;
-
- table[(T_char<<4)+T_undefined] = T_JavaLangString;
- table[(T_char<<4)+T_long] = (Char2Long<<12)+(Long2Long<<4)+T_JavaLangString;
- table[(T_char<<4)+T_short] = (Char2Int<<12)+(Short2Int<<4)+T_JavaLangString;
- // table[(T_char<<4)+T_void] = T_undefined;
- table[(T_char<<4)+T_JavaLangString] = (Char2Char<<12)+(String2String<<4)+T_JavaLangString;
-// table[(T_char<<4)+T_Object] = T_JavaLangString;
- table[(T_char<<4)+T_double] = (Char2Double<<12)+(Double2Double<<4)+T_JavaLangString;
- table[(T_char<<4)+T_float] = (Char2Float<<12)+(Float2Float<<4)+T_JavaLangString;
- table[(T_char<<4)+T_boolean] = T_JavaLangString;
- table[(T_char<<4)+T_char] = (Char2Int<<12)+(Char2Int<<4)+T_JavaLangString;
- table[(T_char<<4)+T_int] = (Char2Int<<12)+(Int2Int<<4)+T_JavaLangString;
- // table[(T_char<<4)+T_null] = T_undefined;
- table[(T_char<<4)+T_any] = T_JavaLangString;
-
- // table[(T_int<<4)+T_undefined] = T_undefined;
- table[(T_int<<4)+T_long] = (Int2Long<<12)+(Long2Long<<4)+T_long;
- table[(T_int<<4)+T_short] = (Int2Int<<12)+(Short2Int<<4)+T_int;
- // table[(T_int<<4)+T_void] = T_undefined;
- table[(T_int<<4)+T_JavaLangString] = (Int2Int<<12)+(String2String<<4)+T_JavaLangString;
- // table[(T_int<<4)+T_Object] = T_undefined;
- table[(T_int<<4)+T_double] = (Int2Double<<12)+(Double2Double<<4)+T_double;
- table[(T_int<<4)+T_float] = (Int2Float<<12)+(Float2Float<<4)+T_float;
- // table[(T_int<<4)+T_boolean] = T_undefined;
- table[(T_int<<4)+T_char] = (Int2Int<<12)+(Char2Int<<4)+T_int;
- table[(T_int<<4)+T_int] = (Int2Int<<12)+(Int2Int<<4)+T_int;
- // table[(T_int<<4)+T_null] = T_undefined;
- table[(T_int<<4)+T_any] = T_any;
-
- // table[(T_null<<4)+T_undefined] = T_undefined;
- // table[(T_null<<4)+T_byte] = T_undefined;
- // table[(T_null<<4)+T_long] = T_undefined;
- // table[(T_null<<4)+T_short] = T_undefined;
- // table[(T_null<<4)+T_void] = T_undefined;
- table[(T_null<<4)+T_JavaLangString] = (T_null<<16)+(T_null<<12)+(String2String<<4)+T_JavaLangString;
- // table[(T_null<<4)+T_Object] = T_undefined;
- // table[(T_null<<4)+T_double] = T_undefined;
- // table[(T_null<<4)+T_float] = T_undefined;
- // table[(T_null<<4)+T_boolean] = T_undefined;
- // table[(T_null<<4)+T_char] = T_undefined;
- table[(T_null<<4)+T_int] = T_int;
- // table[(T_null<<4)+T_null] = (Null2String<<12)+(Null2String<<4)+T_JavaLangString;;
- table[(T_null<<4)+T_any] = T_any;
-
- table[(T_any<<4)+T_undefined] = T_any;
- table[(T_any<<4)+T_long] = T_any;
- table[(T_any<<4)+T_short] = T_any;
- table[(T_any<<4)+T_void] = T_any;
- table[(T_any<<4)+T_JavaLangString] = T_any;
- table[(T_any<<4)+T_JavaLangObject] = T_any;
- table[(T_any<<4)+T_double] = T_any;
- table[(T_any<<4)+T_float] = T_any;
- table[(T_any<<4)+T_boolean] = T_any;
- table[(T_any<<4)+T_char] = T_any;
- table[(T_any<<4)+T_int] = T_any;
- table[(T_any<<4)+T_null] = T_any;
- table[(T_any<<4)+T_any] = T_any;
-
- return table;
- }
-
- public static final int[] get_REMAINDER(){
-
- //the code is an int
- // (cast) left Op (cast) rigth --> result
- // 0000 0000 0000 0000 0000
- // <<16 <<12 <<8 <<4
-
- // int[] table = new int[16*16];
- return get_MINUS();
- }
-
- public static final int[] get_RIGHT_SHIFT(){
-
- //the code is an int
- // (cast) left Op (cast) rigth --> result
- // 0000 0000 0000 0000 0000
- // <<16 <<12 <<8 <<4
-
- // int[] table = new int[16*16];
- return get_LEFT_SHIFT();
- }
-
- public static final int[] get_UNSIGNED_RIGHT_SHIFT(){
-
- //the code is an int
- // (cast) left Op (cast) rigth --> result
- // 0000 0000 0000 0000 0000
- // <<16 <<12 <<8 <<4
-
- // int[] table = new int[16*16];
- return get_LEFT_SHIFT();
- }
-
- public static final int[] get_XOR(){
-
- //the code is an int
- // (cast) left Op (cast) rigth --> result
- // 0000 0000 0000 0000 0000
- // <<16 <<12 <<8 <<4
-
- // int[] table = new int[16*16];
- return get_AND();
- }
-
- public String operatorToString() {
- switch ((bits & OperatorMASK) >> OperatorSHIFT) {
- case EQUAL_EQUAL :
- return "=="; //$NON-NLS-1$
- case LESS_EQUAL :
- return "<="; //$NON-NLS-1$
- case GREATER_EQUAL :
- return ">="; //$NON-NLS-1$
- case NOT_EQUAL :
- return "!="; //$NON-NLS-1$
- case LEFT_SHIFT :
- return "<<"; //$NON-NLS-1$
- case RIGHT_SHIFT :
- return ">>"; //$NON-NLS-1$
- case UNSIGNED_RIGHT_SHIFT :
- return ">>>"; //$NON-NLS-1$
- case OR_OR :
- return "||"; //$NON-NLS-1$
- case AND_AND :
- return "&&"; //$NON-NLS-1$
- case PLUS :
- return "+"; //$NON-NLS-1$
- case MINUS :
- return "-"; //$NON-NLS-1$
- case NOT :
- return "!"; //$NON-NLS-1$
- case REMAINDER :
- return "%"; //$NON-NLS-1$
- case XOR :
- return "^"; //$NON-NLS-1$
- case AND :
- return "&"; //$NON-NLS-1$
- case MULTIPLY :
- return "*"; //$NON-NLS-1$
- case OR :
- return "|"; //$NON-NLS-1$
- case TWIDDLE :
- return "~"; //$NON-NLS-1$
- case DIVIDE :
- return "/"; //$NON-NLS-1$
- case GREATER :
- return ">"; //$NON-NLS-1$
- case LESS :
- return "<"; //$NON-NLS-1$
- case QUESTIONCOLON :
- return "?:"; //$NON-NLS-1$
- case EQUAL :
- return "="; //$NON-NLS-1$
- case TYPEOF :
- return "typeof"; //$NON-NLS-1$
- case DELETE :
- return "delete"; //$NON-NLS-1$
- case OperatorIds.VOID :
- return "void"; //$NON-NLS-1$
- case OperatorIds.INSTANCEOF :
- return "instanceof"; //$NON-NLS-1$
- case OperatorIds.IN :
- return "in"; //$NON-NLS-1$
- case OperatorIds.EQUAL_EQUAL_EQUAL :
- return "==="; //$NON-NLS-1$
- case OperatorIds.NOT_EQUAL_EQUAL :
- return "!=="; //$NON-NLS-1$
- }
- return "unknown operator"; //$NON-NLS-1$
- }
-
- public int nullStatus(FlowInfo flowInfo) {
- return FlowInfo.NON_NULL;
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output){
-
- output.append('(');
- return printExpressionNoParenthesis(0, output).append(')');
- }
-
- public abstract StringBuffer printExpressionNoParenthesis(int indent, StringBuffer output);
- public int getASTType() {
- return IASTNode.OPERATOR_EXPRESSION;
-
- }
- public int getOperator() {
- return (bits & OperatorMASK) >> OperatorSHIFT;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/OperatorIds.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/OperatorIds.java
deleted file mode 100644
index 09033094..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/OperatorIds.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.ast;
-
-public interface OperatorIds {
- public static final int AND_AND = 0;
- public static final int OR_OR = 1;
- public static final int AND = 2;
- public static final int OR = 3;
- public static final int LESS = 4;
- public static final int LESS_EQUAL = 5;
- public static final int GREATER = 6;
- public static final int GREATER_EQUAL = 7;
- public static final int XOR = 8;
- public static final int DIVIDE = 9;
- public static final int LEFT_SHIFT = 10;
- public static final int NOT = 11;
- public static final int TWIDDLE = 12;
- public static final int MINUS = 13;
- public static final int PLUS = 14;
- public static final int MULTIPLY = 15;
- public static final int REMAINDER = 16;
- public static final int RIGHT_SHIFT = 17;
- public static final int EQUAL_EQUAL = 18;
- public static final int UNSIGNED_RIGHT_SHIFT= 19;
- public static final int DELETE = 20;
- public static final int VOID = 21;
- public static final int TYPEOF = 22;
- public static final int IN = 23;
- public static final int EQUAL_EQUAL_EQUAL = 24;
- public static final int NOT_EQUAL_EQUAL = 25;
- public static final int INSTANCEOF = 26;
-
- public static final int NumberOfTables = 27;
-
- public static final int QUESTIONCOLON = 31;
-
- public static final int NOT_EQUAL = 29;
- public static final int EQUAL = 30;
- public static final int PLUS_PLUS = 32;
- public static final int MINUS_MINUS = 33;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/PostfixExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/PostfixExpression.java
deleted file mode 100644
index 30c2b12d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/PostfixExpression.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IPostfixExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-
-public class PostfixExpression extends CompoundAssignment implements IPostfixExpression {
-
-public PostfixExpression(Expression lhs, Expression expression, int operator, int pos) {
- super(lhs, expression, operator, pos);
- this.sourceStart = lhs.sourceStart;
- this.sourceEnd = pos;
-}
-
-public String operatorToString() {
- switch (this.operator) {
- case PLUS :
- return "++"; //$NON-NLS-1$
- case MINUS :
- return "--"; //$NON-NLS-1$
- }
- return "unknown operator"; //$NON-NLS-1$
-}
-
-public StringBuffer printExpressionNoParenthesis(int indent, StringBuffer output) {
- return this.lhs.printExpression(indent, output).append(' ').append(operatorToString());
-}
-
-public boolean restrainUsageToNumericTypes() {
- return true;
-}
-
-public void traverse(ASTVisitor visitor, BlockScope scope) {
-
- if (visitor.visit(this, scope)) {
- this.lhs.traverse(visitor, scope);
- }
- visitor.endVisit(this, scope);
-}
-public int getASTType() {
- return IASTNode.POSTFIX_EXPRESSION;
-
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/PrefixExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/PrefixExpression.java
deleted file mode 100644
index 1f971e0f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/PrefixExpression.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IPrefixExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-
-public class PrefixExpression extends CompoundAssignment implements IPrefixExpression {
-
-/**
- * PrefixExpression constructor comment.
- * @param lhs org.eclipse.wst.jsdt.internal.compiler.ast.Expression
- * @param expression org.eclipse.wst.jsdt.internal.compiler.ast.Expression
- * @param operator int
- */
-public PrefixExpression(Expression lhs, Expression expression, int operator, int pos) {
- super(lhs, expression, operator, lhs.sourceEnd);
- this.sourceStart = pos;
- this.sourceEnd = lhs.sourceEnd;
-}
-
-public String operatorToString() {
- switch (this.operator) {
- case PLUS :
- return "++"; //$NON-NLS-1$
- case MINUS :
- return "--"; //$NON-NLS-1$
- }
- return "unknown operator"; //$NON-NLS-1$
-}
-
-public StringBuffer printExpressionNoParenthesis(int indent, StringBuffer output) {
-
- output.append(operatorToString()).append(' ');
- return this.lhs.printExpression(0, output);
-}
-
-public boolean restrainUsageToNumericTypes() {
- return true;
-}
-
-public void traverse(ASTVisitor visitor, BlockScope scope) {
- if (visitor.visit(this, scope)) {
- this.lhs.traverse(visitor, scope);
- }
- visitor.endVisit(this, scope);
-}
-public int getASTType() {
- return IASTNode.PREFIX_EXPRESSION;
-
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ProgramElement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ProgramElement.java
deleted file mode 100644
index 2012212b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ProgramElement.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IProgramElement;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Scope;
-
-public abstract class ProgramElement extends ASTNode implements IProgramElement {
-
- public abstract StringBuffer printStatement(int indent, StringBuffer output);
-
- public void resolve(BlockScope scope)
- {
- if (this instanceof AbstractMethodDeclaration)
- ((AbstractMethodDeclaration)this).resolve((Scope)scope);
- else
- //TODO: implement
- throw new org.eclipse.wst.jsdt.core.UnimplementedException();
- }
- public int getASTType() {
- return IASTNode.PROGRAM_ELEMENT;
-
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/QualifiedAllocationExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/QualifiedAllocationExpression.java
deleted file mode 100644
index 4574a555..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/QualifiedAllocationExpression.java
+++ /dev/null
@@ -1,278 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IQualifiedAllocationExpression;
-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;
-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.ExtraCompilerModifiers;
-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.ProblemMethodBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeConstants;
-
-/**
- * Variation on allocation, where can optionally be specified any of:
- * - leading enclosing instance
- * - trailing anonymous type
- * - generic type arguments for generic constructor invocation
- */
-public class QualifiedAllocationExpression extends AllocationExpression implements IQualifiedAllocationExpression {
-
- //qualification may be on both side
- public Expression enclosingInstance;
- public TypeDeclaration anonymousType;
- public ReferenceBinding superTypeBinding;
-
- public QualifiedAllocationExpression() {
- // for subtypes
- }
-
- public QualifiedAllocationExpression(TypeDeclaration anonymousType) {
- this.anonymousType = anonymousType;
- anonymousType.allocation = this;
- }
-
- public FlowInfo analyseCode(
- BlockScope currentScope,
- FlowContext flowContext,
- FlowInfo flowInfo) {
-
- // analyse the enclosing instance
- if (this.enclosingInstance != null) {
- flowInfo = this.enclosingInstance.analyseCode(currentScope, flowContext, flowInfo);
- }
-
- // process arguments
- if (this.arguments != null) {
- for (int i = 0, count = this.arguments.length; i < count; i++) {
- flowInfo = this.arguments[i].analyseCode(currentScope, flowContext, flowInfo);
- }
- }
-
- // analyse the anonymous nested type
- if (this.anonymousType != null) {
- flowInfo = this.anonymousType.analyseCode(currentScope, flowContext, flowInfo);
- }
-
- manageEnclosingInstanceAccessIfNecessary(currentScope, flowInfo);
- return flowInfo;
- }
-
- public Expression enclosingInstance() {
-
- return this.enclosingInstance;
- }
-
- public boolean isSuperAccess() {
-
- // necessary to lookup super constructor of anonymous type
- return this.anonymousType != null;
- }
-
- /* Inner emulation consists in either recording a dependency
- * link only, or performing one level of propagation.
- *
- * Dependency mechanism is used whenever dealing with source target
- * types, since by the time we reach them, we might not yet know their
- * exact need.
- */
- public void manageEnclosingInstanceAccessIfNecessary(BlockScope currentScope, FlowInfo flowInfo) {
-
- if ((flowInfo.tagBits & FlowInfo.UNREACHABLE) == 0) {
- ReferenceBinding allocatedTypeErasure = this.binding.declaringClass;
-
- // perform some extra emulation work in case there is some and we are inside a local type only
- if (allocatedTypeErasure.isNestedType()
- && currentScope.enclosingSourceType().isLocalType()) {
-
- if (allocatedTypeErasure.isLocalType()) {
- ((LocalTypeBinding) allocatedTypeErasure).addInnerEmulationDependent(currentScope, this.enclosingInstance != null);
- }
- }
- }
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output) {
-
- if (this.enclosingInstance != null)
- this.enclosingInstance.printExpression(0, output).append('.');
- super.printExpression(0, output);
- if (this.anonymousType != null) {
- this.anonymousType.print(indent, output);
- }
- return output;
- }
-
- public TypeBinding resolveType(BlockScope scope) {
-
- // added for code assist...cannot occur with 'normal' code
- if (this.anonymousType == null && this.enclosingInstance == null) {
- return super.resolveType(scope);
- }
-
- // Propagate the type checking to the arguments, and checks if the constructor is defined.
- // ClassInstanceCreationExpression ::= Primary '.' 'new' SimpleName '(' ArgumentListopt ')' ClassBodyopt
- // ClassInstanceCreationExpression ::= Name '.' 'new' SimpleName '(' ArgumentListopt ')' ClassBodyopt
-
- this.constant = Constant.NotAConstant;
- TypeBinding enclosingInstanceType = null;
- TypeBinding receiverType = null;
- boolean hasError = false;
- boolean argsContainCast = false;
-
- if (this.enclosingInstance != null) {
- if ((enclosingInstanceType = this.enclosingInstance.resolveType(scope)) == null){
- hasError = true;
- } else {
- receiverType = ((SingleTypeReference) this.type).resolveTypeEnclosing(scope, (ReferenceBinding) enclosingInstanceType);
- }
- } else {
- if (this.type == null) {
- // initialization of an enum constant
- receiverType = scope.enclosingSourceType();
- } else {
- receiverType = this.type.resolveType(scope, true /* check bounds*/);
- checkParameterizedAllocation: {
- if (receiverType == null) break checkParameterizedAllocation;
- }
- }
- }
- if (receiverType == null) {
- hasError = true;
- }
-
- // will check for null after args are resolved
- TypeBinding[] argumentTypes = Binding.NO_PARAMETERS;
- if (this.arguments != null) {
- int length = this.arguments.length;
- argumentTypes = new TypeBinding[length];
- for (int i = 0; i < length; i++) {
- Expression argument = this.arguments[i];
- if ((argumentTypes[i] = argument.resolveType(scope)) == null){
- hasError = true;
- }
- }
- }
- // limit of fault-tolerance
- if (hasError) {
- if (receiverType instanceof ReferenceBinding) {
- // record a best guess, for clients who need hint about possible contructor match
- int length = this.arguments == null ? 0 : this.arguments.length;
- 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 null type
- }
- this.binding = scope.findMethod((ReferenceBinding) receiverType, TypeConstants.INIT, pseudoArgs, this);
- if (this.binding != null && !this.binding.isValidBinding()) {
- MethodBinding closestMatch = ((ProblemMethodBinding)this.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.modifiers |= ExtraCompilerModifiers.AccLocallyUsed;
- }
- }
- }
-
- }
- return this.resolvedType = receiverType;
- }
- if (this.anonymousType == null) {
- ReferenceBinding allocationType = (ReferenceBinding) receiverType;
- if ((this.binding = scope.getConstructor(allocationType, argumentTypes, this)).isValidBinding()) {
- if (isMethodUseDeprecated(this.binding, scope, true)) {
- scope.problemReporter().deprecatedMethod(this.binding, this);
- }
- checkInvocationArguments(scope, null, allocationType, this.binding, this.arguments, argumentTypes, argsContainCast, this);
- } else {
- if (this.binding.declaringClass == null) {
- this.binding.declaringClass = allocationType;
- }
- scope.problemReporter().invalidConstructor(this, this.binding);
- return this.resolvedType = receiverType;
- }
-
- // The enclosing instance must be compatible with the innermost enclosing type
- ReferenceBinding expectedType = this.binding.declaringClass.enclosingType();
- if (expectedType != enclosingInstanceType) // must call before computeConversion() and typeMismatchError()
- scope.compilationUnitScope().recordTypeConversion(expectedType, enclosingInstanceType);
- if (enclosingInstanceType.isCompatibleWith(expectedType) || scope.isBoxingCompatibleWith(enclosingInstanceType, expectedType)) {
- return this.resolvedType = receiverType;
- }
- scope.problemReporter().typeMismatchError(enclosingInstanceType, expectedType, this.enclosingInstance);
- return this.resolvedType = receiverType;
- }
-
- // anonymous type scenario
- // an anonymous class inherits from java.lang.Object when declared "after" an interface
- this.superTypeBinding = (ReferenceBinding) receiverType;
- // insert anonymous type in scope
- scope.addAnonymousType(this.anonymousType, (ReferenceBinding) receiverType);
- this.anonymousType.resolve(scope);
-
- // find anonymous super constructor
- MethodBinding inheritedBinding = scope.getConstructor(this.superTypeBinding, argumentTypes, this);
- if (!inheritedBinding.isValidBinding()) {
- if (inheritedBinding.declaringClass == null) {
- inheritedBinding.declaringClass = this.superTypeBinding;
- }
- scope.problemReporter().invalidConstructor(this, inheritedBinding);
- return this.resolvedType = this.anonymousType.binding;
- }
- if (this.enclosingInstance != null) {
- ReferenceBinding targetEnclosing = inheritedBinding.declaringClass.enclosingType();
- if (targetEnclosing == null) {
- return this.resolvedType = this.anonymousType.binding;
- } else if (!enclosingInstanceType.isCompatibleWith(targetEnclosing) && !scope.isBoxingCompatibleWith(enclosingInstanceType, targetEnclosing)) {
- scope.problemReporter().typeMismatchError(enclosingInstanceType, targetEnclosing, this.enclosingInstance);
- return this.resolvedType = this.anonymousType.binding;
- }
- }
- if (this.arguments != null)
- checkInvocationArguments(scope, null, this.superTypeBinding, inheritedBinding, this.arguments, argumentTypes, argsContainCast, this);
-
- // Update the anonymous inner class : superclass, interface
- this.binding = this.anonymousType.createDefaultConstructorWithBinding(inheritedBinding);
- return this.resolvedType = this.anonymousType.binding; // 1.2 change
- }
-
- public void traverse(ASTVisitor visitor, BlockScope scope) {
-
- if (visitor.visit(this, scope)) {
- if (this.enclosingInstance != null)
- this.enclosingInstance.traverse(visitor, scope);
- if (this.type != null) // case of enum constant
- this.type.traverse(visitor, scope);
- if (this.arguments != null) {
- int argumentsLength = this.arguments.length;
- for (int i = 0; i < argumentsLength; i++)
- this.arguments[i].traverse(visitor, scope);
- }
- if (this.anonymousType != null)
- this.anonymousType.traverse(visitor, scope);
- }
- visitor.endVisit(this, scope);
- }
- public int getASTType() {
- return IASTNode.QUALIFIED_ALLOCATION_EXPRESSION;
-
- }
-}
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
deleted file mode 100644
index 37c5a256..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/QualifiedNameReference.java
+++ /dev/null
@@ -1,554 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IQualifiedNameReference;
-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.ClassScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.CompilationUnitScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.FieldBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.LocalVariableBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodScope;
-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.ReferenceBinding;
-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.TypeIds;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.VariableBinding;
-
-public class QualifiedNameReference extends NameReference implements IQualifiedNameReference {
-
- public char[][] tokens;
- public long[] sourcePositions;
- public FieldBinding[] otherBindings, otherCodegenBindings;
- int[] otherDepths;
- public int indexOfFirstFieldBinding;//points (into tokens) for the first token that corresponds to first FieldBinding
- public TypeBinding genericCast;
- public TypeBinding[] otherGenericCasts;
-
-public QualifiedNameReference( char[][] tokens, long[] positions, int sourceStart, int sourceEnd) {
- this.tokens = tokens;
- this.sourcePositions = positions;
- this.sourceStart = sourceStart;
- this.sourceEnd = sourceEnd;
-}
-
-public FlowInfo analyseAssignment(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo, Assignment assignment, boolean isCompound) {
- // determine the rank until which we now we do not need any actual value for the field access
- int otherBindingsCount = this.otherBindings == null ? 0 : this.otherBindings.length;
- boolean needValue = otherBindingsCount == 0 || !this.otherBindings[0].isStatic();
- boolean complyTo14 = currentScope.compilerOptions().complianceLevel >= ClassFileConstants.JDK1_4;
- FieldBinding lastFieldBinding = null;
- switch (this.bits & ASTNode.RestrictiveFlagMASK) {
- case Binding.FIELD : // reading a field
- lastFieldBinding = (FieldBinding) this.binding;
- break;
- case Binding.LOCAL :
- // first binding is a local variable
- LocalVariableBinding localBinding;
- if (!flowInfo
- .isDefinitelyAssigned(localBinding = (LocalVariableBinding) this.binding)) {
- currentScope.problemReporter().uninitializedLocalVariable(localBinding, this);
- }
- if ((flowInfo.tagBits & FlowInfo.UNREACHABLE) == 0) {
- localBinding.useFlag = LocalVariableBinding.USED;
- } else if (localBinding.useFlag == LocalVariableBinding.UNUSED) {
- localBinding.useFlag = LocalVariableBinding.FAKE_USED;
- }
- checkNPE(currentScope, flowContext, flowInfo, true);
- }
-
- if (needValue) {
- manageEnclosingInstanceAccessIfNecessary(currentScope, flowInfo);
- // only for first binding
- }
- // all intermediate field accesses are read accesses
- if (this.otherBindings != null) {
- for (int i = 0; i < otherBindingsCount-1; i++) {
- lastFieldBinding = this.otherBindings[i];
- needValue = !this.otherBindings[i+1].isStatic();
- }
- lastFieldBinding = this.otherBindings[otherBindingsCount-1];
- }
-
- if (isCompound) {
- TypeBinding lastReceiverType;
- switch (otherBindingsCount) {
- case 0 :
- lastReceiverType = this.actualReceiverType;
- break;
- case 1 :
- lastReceiverType = ((VariableBinding)this.binding).type;
- break;
- default:
- lastReceiverType = this.otherBindings[otherBindingsCount-2].type;
- break;
- }
- }
-
- if (assignment.expression != null) {
- flowInfo =
- assignment
- .expression
- .analyseCode(currentScope, flowContext, flowInfo)
- .unconditionalInits();
- }
-
- // equivalent to valuesRequired[maxOtherBindings]
- TypeBinding lastReceiverType;
- switch (otherBindingsCount) {
- case 0 :
- lastReceiverType = this.actualReceiverType;
- break;
- case 1 :
- lastReceiverType = ((VariableBinding)this.binding).type;
- break;
- default :
- lastReceiverType = this.otherBindings[otherBindingsCount-2].type;
- break;
- }
-
- 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, boolean valueRequired) {
- // determine the rank until which we now we do not need any actual value for the field access
- int otherBindingsCount = this.otherBindings == null ? 0 : this.otherBindings.length;
-
- boolean needValue = otherBindingsCount == 0 ? valueRequired : !this.otherBindings[0].isStatic();
- boolean complyTo14 = currentScope.compilerOptions().complianceLevel >= ClassFileConstants.JDK1_4;
- switch (this.bits & ASTNode.RestrictiveFlagMASK) {
- case Binding.FIELD : // reading a field
- break;
- case Binding.LOCAL : // reading a local variable
- LocalVariableBinding localBinding;
- if (!flowInfo
- .isDefinitelyAssigned(localBinding = (LocalVariableBinding) this.binding)) {
- if(localBinding.declaringScope instanceof CompilationUnitScope)
- currentScope.problemReporter().uninitializedGlobalVariable(localBinding, this);
- else
- currentScope.problemReporter().uninitializedLocalVariable(localBinding, this);
- }
- if ((flowInfo.tagBits & FlowInfo.UNREACHABLE) == 0) {
- localBinding.useFlag = LocalVariableBinding.USED;
- } else if (localBinding.useFlag == LocalVariableBinding.UNUSED) {
- localBinding.useFlag = LocalVariableBinding.FAKE_USED;
- }
- checkNPE(currentScope, flowContext, flowInfo, true);
- }
- if (needValue) {
- manageEnclosingInstanceAccessIfNecessary(currentScope, flowInfo);
- // only for first binding (if value needed only)
- }
- if (this.otherBindings != null) {
- for (int i = 0; i < otherBindingsCount; i++) {
- needValue = i < otherBindingsCount-1 ? !this.otherBindings[i+1].isStatic() : valueRequired;
- if (needValue || complyTo14) {
- TypeBinding lastReceiverType = getGenericCast(i);
- if (lastReceiverType == null) {
- if (i == 0) {
- lastReceiverType = ((VariableBinding)this.binding).type;
- } else {
- lastReceiverType = this.otherBindings[i-1].type;
- }
- }
- }
- }
- }
- return flowInfo;
-}
-
-/**
- * Check and/or redirect the field access to the delegate receiver if any
- */
-public TypeBinding checkFieldAccess(BlockScope scope) {
- FieldBinding fieldBinding = (FieldBinding) this.binding;
- MethodScope methodScope = scope.methodScope();
- // check for forward references
- if (this.indexOfFirstFieldBinding == 1
- && 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.RestrictiveFlagMASK; // clear bits
- this.bits |= Binding.FIELD;
- return getOtherFieldBindings(scope);
-}
-
-public void checkNPE(BlockScope scope, FlowContext flowContext, FlowInfo flowInfo, boolean checkString) {
- // cannot override localVariableBinding because this would project o.m onto o when
- // analysing assignments
- if ((this.bits & ASTNode.RestrictiveFlagMASK) == Binding.LOCAL) {
- LocalVariableBinding local = (LocalVariableBinding) this.binding;
- if (local != null &&
- (local.type.tagBits & TagBits.IsBaseType) == 0 &&
- (checkString || local.type.id != TypeIds.T_JavaLangString)) {
- if ((this.bits & ASTNode.IsNonNull) == 0) {
- flowContext.recordUsingNullReference(scope, local, this,
- FlowContext.MAY_NULL, flowInfo);
- }
- flowInfo.markAsComparedEqualToNonNull(local);
- // from thereon it is set
- if (flowContext.initsOnFinally != null) {
- flowContext.initsOnFinally.markAsComparedEqualToNonNull(local);
- }
- }
- }
-}
-
-/**
- * @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)
- FieldBinding field = null;
- int length = this.otherBindings == null ? 0 : this.otherBindings.length;
- if (length == 0) {
- if ((this.bits & Binding.FIELD) != 0 && this.binding != null && this.binding.isValidBinding()) {
- field = (FieldBinding) this.binding;
- }
- } else {
- field = this.otherBindings[length-1];
- }
- if (field != null) {
- FieldBinding originalBinding = field.original();
- }
-}
-
-/**
- * @see org.eclipse.wst.jsdt.internal.compiler.lookup.InvocationSite#genericTypeArguments()
- */
-public TypeBinding[] genericTypeArguments() {
- return null;
-}
-
-// get the matching codegenBinding
-protected FieldBinding getCodegenBinding(int index) {
-// if (index == 0){
-// return (FieldBinding)this.codegenBinding;
-// } else {
-// return this.otherCodegenBindings[index-1];
-// }
- return (FieldBinding)this.binding;
-}
-
-// get the matching generic cast
-protected TypeBinding getGenericCast(int index) {
- if (index == 0){
- return this.genericCast;
- } else {
- if (this.otherGenericCasts == null) return null;
- return this.otherGenericCasts[index-1];
- }
-}
-
-public TypeBinding getOtherFieldBindings(BlockScope scope) {
- // At this point restrictiveFlag may ONLY have two potential value : FIELD LOCAL (i.e cast <<(VariableBinding) binding>> is valid)
- int length = this.tokens.length;
- FieldBinding field;
- if ((this.bits & Binding.FIELD) != 0) {
- field = (FieldBinding) this.binding;
- if (!field.isStatic()) {
- //must check for the static status....
- if (this.indexOfFirstFieldBinding > 1 //accessing to a field using a type as "receiver" is allowed only with static field
- || scope.methodScope().isStatic) { // the field is the first token of the qualified reference....
- scope.problemReporter().staticFieldAccessToNonStaticVariable(this, field);
- return null;
- }
- } else {
- // indirect static reference ?
- if (this.indexOfFirstFieldBinding > 1
- && field.declaringClass != this.actualReceiverType
- && field.declaringClass.canBeSeenBy(scope)) {
- scope.problemReporter().indirectAccessToStaticField(this, field);
- }
- }
- // only last field is actually a write access if any
- if (isFieldUseDeprecated(field, scope, (this.bits & ASTNode.IsStrictlyAssigned) != 0 && this.indexOfFirstFieldBinding == length))
- scope.problemReporter().deprecatedField(field, this);
- } else {
- field = null;
- }
- TypeBinding type = ((VariableBinding) this.binding).type;
- int index = this.indexOfFirstFieldBinding;
- if (index == length) { // restrictiveFlag == FIELD
- // perform capture conversion if read access
- return type;
- }
- // allocation of the fieldBindings array and its respective constants
- int otherBindingsLength = length - index;
- this.otherCodegenBindings = this.otherBindings = new FieldBinding[otherBindingsLength];
- this.otherDepths = new int[otherBindingsLength];
-
- // save first depth, since will be updated by visibility checks of other bindings
- int firstDepth = (this.bits & ASTNode.DepthMASK) >> ASTNode.DepthSHIFT;
- // iteration on each field
- while (index < length) {
- char[] token = this.tokens[index];
- if (type == null)
- return null; // could not resolve type prior to this point
-
- this.bits &= ~ASTNode.DepthMASK; // flush previous depth if any
- FieldBinding previousField = field;
- field = scope.getField(type, token, this);
- int place = index - this.indexOfFirstFieldBinding;
- this.otherBindings[place] = field;
- this.otherDepths[place] = (this.bits & ASTNode.DepthMASK) >> ASTNode.DepthSHIFT;
- if (field.isValidBinding()) {
- // set generic cast of for previous field (if any)
- if (previousField != null) {
- TypeBinding fieldReceiverType = type;
- TypeBinding receiverErasure = type;
- if (receiverErasure instanceof ReferenceBinding) {
- if (receiverErasure.findSuperTypeWithSameErasure(field.declaringClass) == null) {
- fieldReceiverType = field.declaringClass; // handle indirect inheritance thru variable secondary bound
- }
- }
- FieldBinding originalBinding = previousField.original();
- }
- // only last field is actually a write access if any
- if (isFieldUseDeprecated(field, scope, (this.bits & ASTNode.IsStrictlyAssigned) !=0 && index+1 == length)) {
- scope.problemReporter().deprecatedField(field, this);
- }
-
- if (field.isStatic()) {
- // static field accessed through receiver? legal but unoptimal (optional warning)
- scope.problemReporter().nonStaticAccessToStaticField(this, field);
- // indirect static reference ?
- if (field.declaringClass != type) {
- scope.problemReporter().indirectAccessToStaticField(this, field);
- }
- }
- type = field.type;
- index++;
- } else {
- this.constant = Constant.NotAConstant; //don't fill other constants slots...
- scope.problemReporter().invalidField(this, field, index, type);
- setDepth(firstDepth);
- return null;
- }
- }
- setDepth(firstDepth);
- type = (this.otherBindings[otherBindingsLength - 1]).type;
- // perform capture conversion if read access
- return type;
-}
-
-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 (((this.bits & ASTNode.DepthMASK) == 0) || (this.constant != Constant.NotAConstant)) {
- return;
- }
- if ((this.bits & ASTNode.RestrictiveFlagMASK) == Binding.LOCAL) {
- currentScope.emulateOuterAccess((LocalVariableBinding) this.binding);
- }
- }
-}
-
-public int nullStatus(FlowInfo flowInfo) {
- return FlowInfo.UNKNOWN;
-}
-
-public Constant optimizedBooleanConstant() {
- switch (this.resolvedType.id) {
- case T_boolean :
- case T_JavaLangBoolean :
- if (this.constant != Constant.NotAConstant) return this.constant;
- switch (this.bits & ASTNode.RestrictiveFlagMASK) {
- case Binding.FIELD : // reading a field
- if (this.otherBindings == null)
- return Constant.NotAConstant;
- // fall thru
- case Binding.LOCAL : // reading a local variable
- return Constant.NotAConstant;
- }
- }
- 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('.');
- output.append(this.tokens[i]);
- }
- return output;
-}
-
-/**
- * Normal field binding did not work, try to bind to a field of the delegate receiver.
- */
-public TypeBinding reportError(BlockScope scope) {
- if (this.binding instanceof ProblemFieldBinding) {
- scope.problemReporter().invalidField(this, (FieldBinding) this.binding);
- } else if (this.binding instanceof ProblemReferenceBinding) {
- scope.problemReporter().invalidType(this, (TypeBinding) this.binding);
- } else {
- scope.problemReporter().unresolvableReference(this, this.binding);
- }
- return null;
-}
-
-public TypeBinding resolveType(BlockScope scope) {
- // field and/or local are done before type lookups
- // the only available value for the restrictiveFlag BEFORE
- // the TC is Flag_Type Flag_LocalField and Flag_TypeLocalField
- this.actualReceiverType = scope.enclosingReceiverType();
- this.constant = Constant.NotAConstant;
- if ((/*this.codegenBinding =*/ this.binding = scope.getBinding(this.tokens, this.bits & ASTNode.RestrictiveFlagMASK, this, true /*resolve*/)).isValidBinding()) {
- switch (this.bits & ASTNode.RestrictiveFlagMASK) {
- case Binding.VARIABLE : //============only variable===========
- case Binding.TYPE | Binding.VARIABLE :
- if (this.binding instanceof LocalVariableBinding) {
- this.bits &= ~ASTNode.RestrictiveFlagMASK; // clear bits
- this.bits |= Binding.LOCAL;
- return this.resolvedType = getOtherFieldBindings(scope);
- }
- if (this.binding instanceof FieldBinding) {
- FieldBinding fieldBinding = (FieldBinding) this.binding;
- MethodScope methodScope = scope.methodScope();
- // check for forward references
- if (this.indexOfFirstFieldBinding == 1
- && 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.RestrictiveFlagMASK; // clear bits
- this.bits |= Binding.FIELD;
-
-// // check for deprecated receiver type
-// // deprecation check for receiver type if not first token
-// if (indexOfFirstFieldBinding > 1) {
-// if (isTypeUseDeprecated(this.actualReceiverType, scope))
-// scope.problemReporter().deprecatedType(this.actualReceiverType, this);
-// }
-
- return this.resolvedType = getOtherFieldBindings(scope);
- }
- // thus it was a type
- this.bits &= ~ASTNode.RestrictiveFlagMASK; // clear bits
- this.bits |= Binding.TYPE;
- case Binding.TYPE : //=============only type ==============
- TypeBinding type = (TypeBinding) this.binding;
-// if (isTypeUseDeprecated(type, scope))
-// scope.problemReporter().deprecatedType(type, this);
- return this.resolvedType = type;
- }
- }
- //========error cases===============
- return this.resolvedType = this.reportError(scope);
-}
-
-// set the matching codegenBinding and generic cast
-protected void setCodegenBinding(int index, FieldBinding someCodegenBinding) {
-// if (index == 0){
-// this.codegenBinding = someCodegenBinding;
-// } else {
-// int length = this.otherBindings.length;
-// if (this.otherCodegenBindings == this.otherBindings){
-// System.arraycopy(this.otherBindings, 0, this.otherCodegenBindings = new FieldBinding[length], 0, length);
-// }
-// this.otherCodegenBindings[index-1] = someCodegenBinding;
-// }
-}
-
-public void setFieldIndex(int index) {
- this.indexOfFirstFieldBinding = index;
-}
-
-// set the matching codegenBinding and generic cast
-protected void setGenericCast(int index, TypeBinding someGenericCast) {
- if (index == 0){
- this.genericCast = someGenericCast;
- } else {
- if (this.otherGenericCasts == null) {
- this.otherGenericCasts = new TypeBinding[this.otherBindings.length];
- }
- this.otherGenericCasts[index-1] = someGenericCast;
- }
-}
-
-public void traverse(ASTVisitor visitor, BlockScope scope) {
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
-}
-
-public void traverse(ASTVisitor visitor, ClassScope scope) {
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
-}
-
-public String unboundReferenceErrorName() {
- return new String(this.tokens[0]);
-}
-public int getASTType() {
- return IASTNode.QUALIFIED_NAME_REFERENCE;
-
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/QualifiedThisReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/QualifiedThisReference.java
deleted file mode 100644
index 9e0e24b1..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/QualifiedThisReference.java
+++ /dev/null
@@ -1,119 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IQualifiedThisReference;
-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;
-import org.eclipse.wst.jsdt.internal.compiler.impl.Constant;
-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.ReferenceBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class QualifiedThisReference extends ThisReference implements IQualifiedThisReference {
-
- public TypeReference qualification;
- ReferenceBinding currentCompatibleType;
-
- public QualifiedThisReference(TypeReference name, int sourceStart, int sourceEnd) {
- super(sourceStart, sourceEnd);
- qualification = name;
- name.bits |= IgnoreRawTypeCheck; // no need to worry about raw type usage
- this.sourceStart = name.sourceStart;
- }
-
- public FlowInfo analyseCode(
- BlockScope currentScope,
- FlowContext flowContext,
- FlowInfo flowInfo) {
-
- return flowInfo;
- }
-
- public FlowInfo analyseCode(
- BlockScope currentScope,
- FlowContext flowContext,
- FlowInfo flowInfo,
- boolean valueRequired) {
-
- return flowInfo;
- }
-
- public TypeBinding resolveType(BlockScope scope) {
-
- constant = Constant.NotAConstant;
- // X.this is not a param/raw type as denoting enclosing instance
- TypeBinding type = this.qualification.resolveType(scope, true /* check bounds*/);
- if (type == null) return null;
-
- // resolvedType needs to be converted to parameterized
- if (type instanceof ReferenceBinding) {
- this.resolvedType = type;
- } else {
- // error case
- this.resolvedType = type;
- }
-
- // the qualification MUST exactly match some enclosing type name
- // It is possible to qualify 'this' by the name of the current class
- int depth = 0;
- this.currentCompatibleType = scope.referenceType().binding;
- while (this.currentCompatibleType != null && this.currentCompatibleType != type) {
- depth++;
- this.currentCompatibleType = this.currentCompatibleType.isStatic() ? null : this.currentCompatibleType.enclosingType();
- }
- bits &= ~DepthMASK; // flush previous depth if any
- bits |= (depth & 0xFF) << DepthSHIFT; // encoded depth into 8 bits
-
- if (this.currentCompatibleType == null) {
- return this.resolvedType;
- }
-
- // Ensure one cannot write code like: B() { super(B.this); }
- if (depth == 0) {
- checkAccess(scope.methodScope());
- } // if depth>0, path emulation will diagnose bad scenarii
-
- return this.resolvedType;
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output) {
-
- return qualification.print(0, output).append(".this"); //$NON-NLS-1$
- }
-
- public void traverse(
- ASTVisitor visitor,
- BlockScope blockScope) {
-
- if (visitor.visit(this, blockScope)) {
- qualification.traverse(visitor, blockScope);
- }
- visitor.endVisit(this, blockScope);
- }
-
- public void traverse(
- ASTVisitor visitor,
- ClassScope blockScope) {
-
- if (visitor.visit(this, blockScope)) {
- qualification.traverse(visitor, blockScope);
- }
- visitor.endVisit(this, blockScope);
- }
- public int getASTType() {
- return IASTNode.QUALIFIED_THIS_REFERENCE;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/QualifiedTypeReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/QualifiedTypeReference.java
deleted file mode 100644
index 505c0eb1..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/QualifiedTypeReference.java
+++ /dev/null
@@ -1,136 +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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IQualifiedTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-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.LookupEnvironment;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding;
-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.TypeBinding;
-import org.eclipse.wst.jsdt.internal.compiler.problem.AbortCompilation;
-
-public class QualifiedTypeReference extends TypeReference implements IQualifiedTypeReference {
-
- public char[][] tokens;
- public long[] sourcePositions;
-
- public QualifiedTypeReference(char[][] sources , long[] poss) {
-
- tokens = sources ;
- sourcePositions = poss ;
- sourceStart = (int) (sourcePositions[0]>>>32) ;
- sourceEnd = (int)(sourcePositions[sourcePositions.length-1] & 0x00000000FFFFFFFFL ) ;
- }
-
- public TypeReference copyDims(int dim){
- //return a type reference copy of me with some dimensions
- //warning : the new type ref has a null binding
- return new ArrayQualifiedTypeReference(tokens, dim, sourcePositions);
- }
-
- protected TypeBinding findNextTypeBinding(int tokenIndex, Scope scope, PackageBinding packageBinding) {
- LookupEnvironment env = scope.environment();
- try {
- env.missingClassFileLocation = this;
- if (this.resolvedType == null) {
- this.resolvedType = scope.getType(this.tokens[tokenIndex], packageBinding);
- } else {
- this.resolvedType = scope.getMemberType(this.tokens[tokenIndex], (ReferenceBinding) this.resolvedType);
- if (this.resolvedType instanceof ProblemReferenceBinding) {
- ProblemReferenceBinding problemBinding = (ProblemReferenceBinding) this.resolvedType;
- this.resolvedType = new ProblemReferenceBinding(
- org.eclipse.wst.jsdt.core.compiler.CharOperation.subarray(this.tokens, 0, tokenIndex + 1),
- problemBinding.closestMatch(),
- this.resolvedType.problemId());
- }
- }
- return this.resolvedType;
- } catch (AbortCompilation e) {
- e.updateContext(this, scope.referenceCompilationUnit().compilationResult);
- throw e;
- } finally {
- env.missingClassFileLocation = null;
- }
- }
-
- public char[] getLastToken() {
- return this.tokens[this.tokens.length-1];
- }
- protected TypeBinding getTypeBinding(Scope scope) {
-
- if (this.resolvedType != null)
- return this.resolvedType;
-
- Binding binding = scope.getPackage(this.tokens);
- if (binding != null && !binding.isValidBinding())
- return (ReferenceBinding) binding; // not found
-
- PackageBinding packageBinding = binding == null ? null : (PackageBinding) binding;
- boolean isClassScope = scope.kind == Scope.CLASS_SCOPE;
- ReferenceBinding qualifiedType = null;
- for (int i = packageBinding == null ? 0 : packageBinding.compoundName.length, max = this.tokens.length, last = max-1; i < max; i++) {
- findNextTypeBinding(i, scope, packageBinding);
- if (!this.resolvedType.isValidBinding())
- return this.resolvedType;
- if (i < last && isTypeUseDeprecated(this.resolvedType, scope)) {
- reportDeprecatedType(this.resolvedType, scope);
- }
- if (isClassScope)
- if (((ClassScope) scope).detectHierarchyCycle(this.resolvedType, this)) // must connect hierarchy to find inherited member types
- return null;
- ReferenceBinding currentType = (ReferenceBinding) this.resolvedType;
- if (qualifiedType != null) {
- qualifiedType = currentType;
- } else {
- qualifiedType = currentType;
- }
- }
- this.resolvedType = qualifiedType;
- return this.resolvedType;
- }
-
- public char[][] getTypeName(){
-
- return tokens;
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output) {
-
- for (int i = 0; i < tokens.length; i++) {
- if (i > 0) output.append('.');
- output.append(tokens[i]);
- }
- return output;
- }
-
- public void traverse(ASTVisitor visitor, BlockScope scope) {
-
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
- }
-
- public void traverse(ASTVisitor visitor, ClassScope scope) {
-
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
- }
- public int getASTType() {
- return IASTNode.QUALIFIED_TYPE_REFERENCE;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Reference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Reference.java
deleted file mode 100644
index 9cbf0636..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Reference.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IReference;
-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.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.FieldBinding;
-
-public abstract class Reference extends Expression implements IReference {
-/**
- * BaseLevelReference constructor comment.
- */
-public Reference() {
- super();
-}
-public abstract FlowInfo analyseAssignment(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo, Assignment assignment, boolean isCompound);
-
-public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {
- return flowInfo;
-}
-public FieldBinding fieldBinding() {
- //this method should be sent one FIELD-tagged references
- // (ref.bits & BindingIds.FIELD != 0)()
- return null ;
-}
-public int getASTType() {
- return IASTNode.REFERENCE;
-
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/RegExLiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/RegExLiteral.java
deleted file mode 100644
index df016653..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/RegExLiteral.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IRegExLiteral;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-import org.eclipse.wst.jsdt.internal.compiler.impl.StringConstant;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class RegExLiteral extends Literal implements IRegExLiteral {
-
- char[] source;
-
- public RegExLiteral(char[] token, int start, int end) {
-
- this(start,end);
- this.source = token;
- }
-
- public RegExLiteral(int s, int e) {
-
- super(s,e);
- }
-
- public void computeConstant() {
-
- constant = StringConstant.fromValue(String.valueOf(source));
- }
-
- public TypeBinding literalType(BlockScope scope) {
-
- return scope.getJavaLangRegExp();
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output) {
-
- // handle some special char.....
- for (int i = 0; i < source.length; i++) {
- switch (source[i]) {
-// case '\b' :
-// output.append("\\b"); //$NON-NLS-1$
-// break;
-// case '\t' :
-// output.append("\\t"); //$NON-NLS-1$
-// break;
-// case '\n' :
-// output.append("\\n"); //$NON-NLS-1$
-// break;
-// case '\f' :
-// output.append("\\f"); //$NON-NLS-1$
-// break;
-// case '\r' :
-// output.append("\\r"); //$NON-NLS-1$
-// break;
-// case '\"' :
-// output.append("\\\""); //$NON-NLS-1$
-// break;
-// case '\'' :
-// output.append("\\'"); //$NON-NLS-1$
-// break;
-// case '\\' : //take care not to display the escape as a potential real char
-// output.append("\\\\"); //$NON-NLS-1$
-// break;
- default :
- output.append(source[i]);
- }
- }
- return output;
- }
-
- public char[] source() {
-
- return source;
- }
-
- public void traverse(ASTVisitor visitor, BlockScope scope) {
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
- }
- public int getASTType() {
- return IASTNode.REG_EX_LITERAL;
-
- }
-}
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
deleted file mode 100644
index 515cbb1b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ReturnStatement.java
+++ /dev/null
@@ -1,176 +0,0 @@
-/*******************************************************************************
- * 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.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.internal.compiler.ASTVisitor;
-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.flow.InitializationFlowContext;
-import org.eclipse.wst.jsdt.internal.compiler.flow.InsideSubRoutineFlowContext;
-import org.eclipse.wst.jsdt.internal.compiler.impl.Constant;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-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.TypeBinding;
-
-public class ReturnStatement extends Statement implements IReturnStatement {
-
- public Expression expression;
- 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);
- }
-
- // 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;
- }
- }
- } 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);
- }
-
- // 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;
-}
-
-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;
- }
- 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);
-}
-
-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);
-}
-public int getASTType() {
- return IASTNode.RETURN_STATEMENT;
-
-}
-
-public IExpression getExpression() {
- return this.expression;
-}
-}
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
deleted file mode 100644
index daf541a8..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/SingleNameReference.java
+++ /dev/null
@@ -1,516 +0,0 @@
-/*******************************************************************************
- * 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.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.internal.compiler.ASTVisitor;
-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.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);
- }
-
- public SingleNameReference(char[] source, int sourceStart, int sourceEnd) {
- super();
- token = source;
- this.sourceStart = sourceStart;
- this.sourceEnd = sourceEnd;
- }
-
- public char[] getToken() {
- return this.token;
- }
- public FlowInfo analyseAssignment(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo, Assignment assignment, boolean isCompound) {
-
- boolean isReachable = (flowInfo.tagBits & FlowInfo.UNREACHABLE) == 0;
- // compound assignment extra work
- 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)) {
- 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 (assignment.expression != null) {
- flowInfo = assignment.expression.analyseCode(currentScope, flowContext, flowInfo).unconditionalInits();
- }
- 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);
- }
- flowInfo.markAsDefinitelyAssigned(localBinding);
- }
- manageEnclosingInstanceAccessIfNecessary(currentScope, flowInfo);
- 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, boolean valueRequired) {
-
- 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 :
- case Binding.VARIABLE:
- if(binding instanceof LocalVariableBinding) {
- LocalVariableBinding localBinding= (LocalVariableBinding) binding;
-
- // ignore the arguments variable inside a function
- if(!(CharOperation.equals(localBinding.name, new char[]{'a','r','g','u','m','e','n','t','s'}) && (localBinding.declaringScope instanceof MethodScope))) {
- if(!flowInfo.isDefinitelyAssigned(localBinding)) {
- if (localBinding.declaringScope instanceof MethodScope) {
- currentScope.problemReporter().uninitializedLocalVariable(localBinding, this);
- } else if(localBinding.isSameCompilationUnit(currentScope)) {
- currentScope.problemReporter().uninitializedGlobalVariable(localBinding, this);
- }
- }
- }
-
- if ((flowInfo.tagBits & FlowInfo.UNREACHABLE) == 0) {
- localBinding.useFlag = LocalVariableBinding.USED;
- } else if (localBinding.useFlag == LocalVariableBinding.UNUSED) {
- localBinding.useFlag = LocalVariableBinding.FAKE_USED;
- }
- }
-
- }
- if (valueRequired) {
- manageEnclosingInstanceAccessIfNecessary(currentScope, flowInfo);
- }
- return flowInfo;
- }
-
- public TypeBinding checkFieldAccess(BlockScope scope) {
-
- FieldBinding fieldBinding = (FieldBinding) binding;
-
- bits &= ~RestrictiveFlagMASK; // clear bits
- bits |= Binding.FIELD;
- MethodScope methodScope = scope.methodScope();
- boolean isStatic = fieldBinding.isStatic();
- if (!isStatic) {
- // must check for the static status....
- if (methodScope!=null && methodScope.isStatic) {
- // reference is ok if coming from compilation unit superclass
- if (fieldBinding.declaringClass==null || !fieldBinding.declaringClass.equals(scope.compilationUnitScope().superBinding))
- {
- scope.problemReporter().staticFieldAccessToNonStaticVariable(this, fieldBinding);
- this.constant = Constant.NotAConstant;
- return fieldBinding.type;
- }
- }
- }
-
- 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()
- */
- public TypeBinding[] genericTypeArguments() {
- return null;
- }
-
- /**
- * Returns the local variable referenced by this node. Can be a direct reference (SingleNameReference)
- * or thru a cast expression etc...
- */
- public LocalVariableBinding localVariableBinding() {
- switch (bits & RestrictiveFlagMASK) {
- case Binding.FIELD : // reading a field
- break;
- case Binding.LOCAL : // reading a local variable
- 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);
- }
- }
- }
- 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 :
- }
- if ((this.implicitConversion & BOXING) != 0) {
- convertedType = scope.environment().computeBoxingType(convertedType);
- }
- return convertedType;
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output){
-
- return output.append(token);
- }
- public TypeBinding reportError(BlockScope scope) {
-
- //=====error cases=======
- constant = Constant.NotAConstant;
- if (binding instanceof ProblemFieldBinding) {
- scope.problemReporter().invalidField(this, (FieldBinding) binding);
- } else if (binding instanceof ProblemReferenceBinding) {
- scope.problemReporter().invalidType(this, (TypeBinding) binding);
- } else {
- scope.problemReporter().unresolvableReference(this, binding);
- }
- return null;
- }
-
- public TypeBinding resolveType(BlockScope scope) {
- return resolveType(scope,false,null);
- }
-
- 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);
- LocalVariableBinding localBinding=new LocalVariableBinding(localDeclaration,TypeBinding.UNKNOWN,0,false);
- scope.compilationUnitScope().addLocalVariable(localBinding);
- this.binding=localBinding;
- }
-// this.codegenBinding = this.binding;
- if (this.binding.isValidBinding()) {
- switch (bits & RestrictiveFlagMASK) {
- case Binding.FIELD:
- case Binding.LOCAL : // =========only variable============
- case Binding.VARIABLE : // =========only variable============
- case Binding.LOCAL | Binding.TYPE : //====both variable and type============
- case Binding.VARIABLE | Binding.TYPE : //====both variable and type============
- if (binding instanceof VariableBinding) {
- VariableBinding variable = (VariableBinding) binding;
- 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
- {
- if (fieldType==TypeBinding.UNKNOWN)
- fieldType=variable.type=useType;
- else if (!fieldType.isCompatibleWith(useType))
- fieldType=variable.type=TypeBinding.ANY;
- }
- }
-
- constant = Constant.NotAConstant;
-
-
- return this.resolvedType = fieldType;
- }
- // perform capture conversion if read access
- TypeBinding fieldType = checkFieldAccess(scope);
- if (fieldType.isAnonymousType())
- bits |= Binding.TYPE;
-
- return this.resolvedType = fieldType;
- }
-
- if (binding instanceof MethodBinding)
- {
- return ((MethodBinding)binding).functionTypeBinding;
- }
- else
- {
- // thus it was a type
- bits &= ~RestrictiveFlagMASK; // clear bits
- bits |= Binding.TYPE;
- }
-
- 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;
- }
- }
-
- // error scenarii
- return this.resolvedType = this.reportError(scope);
- }
-
- 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*/);
- }
-
- public void traverse(ASTVisitor visitor, BlockScope scope) {
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
- }
-
- public void traverse(ASTVisitor visitor, ClassScope scope) {
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
- }
-
- public String unboundReferenceErrorName(){
-
- return new String(token);
- }
-
- public TypeBinding resolveForAllocation(BlockScope scope, ASTNode location)
- {
- char[] memberName = this.token;
- TypeBinding typeBinding=null;
- this.binding=
- scope.getBinding(memberName, (Binding.TYPE|Binding.METHOD | bits) & RestrictiveFlagMASK, this, true /*resolve*/);
- if (binding instanceof TypeBinding)
- typeBinding=(TypeBinding)binding;
- else if (binding instanceof MethodBinding)
- typeBinding=((MethodBinding)binding).returnType;
- else if (binding!=null && !binding.isValidBinding())
- {
- typeBinding=new ProblemReferenceBinding(memberName,null,binding.problemId());
- }
- return typeBinding;
- }
- public int getASTType() {
- return IASTNode.SINGLE_NAME_REFERENCE;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/SingleTypeReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/SingleTypeReference.java
deleted file mode 100644
index 9fbca5c5..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/SingleTypeReference.java
+++ /dev/null
@@ -1,90 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.ISingleTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-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.ReferenceBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Scope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class SingleTypeReference extends TypeReference implements ISingleTypeReference {
-
- public char[] token;
-
- public SingleTypeReference(char[] source, long pos) {
-
- token = source;
- sourceStart = (int) (pos>>>32) ;
- sourceEnd = (int) (pos & 0x00000000FFFFFFFFL) ;
-
- }
-
- public TypeReference copyDims(int dim){
- //return a type reference copy of me with some dimensions
- //warning : the new type ref has a null binding
-
- return new ArrayTypeReference(token, dim,(((long)sourceStart)<<32)+sourceEnd);
- }
-
- public char[] getLastToken() {
- return this.token;
- }
- protected TypeBinding getTypeBinding(Scope scope) {
- if (this.resolvedType != null)
- return this.resolvedType;
-
- this.resolvedType = scope.getType(token);
-
- if (scope.kind == Scope.CLASS_SCOPE && this.resolvedType.isValidBinding())
- if (((ClassScope) scope).detectHierarchyCycle(this.resolvedType, this))
- return null;
- return this.resolvedType;
- }
-
- public char [][] getTypeName() {
- return new char[][] { token };
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output){
-
- return output.append(token);
- }
-
- public TypeBinding resolveTypeEnclosing(BlockScope scope, ReferenceBinding enclosingType) {
-
- TypeBinding memberType = scope.getMemberType(token, enclosingType);
- if (!memberType.isValidBinding()) {
- this.resolvedType = memberType;
- return null;
- }
- if (isTypeUseDeprecated(memberType, scope))
- scope.problemReporter().deprecatedType(memberType, this);
- return this.resolvedType = memberType;
- }
-
- public void traverse(ASTVisitor visitor, BlockScope scope) {
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
- }
-
- public void traverse(ASTVisitor visitor, ClassScope scope) {
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
- }
- public int getASTType() {
- return IASTNode.SINGLE_TYPE_REFERENCE;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Statement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Statement.java
deleted file mode 100644
index 5393c236..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Statement.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IStatement;
-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.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public abstract class Statement extends ProgramElement implements IStatement {
-
- public abstract FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo);
-
-
- // Report an error if necessary
- public boolean complainIfUnreachable(FlowInfo flowInfo, BlockScope scope, boolean didAlreadyComplain) {
-
- if ((flowInfo.reachMode() & FlowInfo.UNREACHABLE) != 0) {
- this.bits &= ~ASTNode.IsReachable;
- boolean reported = flowInfo == FlowInfo.DEAD_END;
- if (!didAlreadyComplain && reported) {
- scope.problemReporter().unreachableCode(this);
- }
- return reported; // keep going for fake reachable
- }
- return false;
- }
-
-
- public boolean isEmptyBlock() {
- return false;
- }
-
- public boolean isValidJavaStatement() {
- //the use of this method should be avoid in most cases
- //and is here mostly for documentation purpose.....
- //while the parser is responsable for creating
- //welled formed expression statement, which results
- //in the fact that java-non-semantic-expression-used-as-statement
- //should not be parsable...thus not being built.
- //It sounds like the java grammar as help the compiler job in removing
- //-by construction- some statement that would have no effect....
- //(for example all expression that may do side-effects are valid statement
- // -this is an appromative idea.....-)
-
- return true;
- }
-
- public StringBuffer print(int indent, StringBuffer output) {
- return printStatement(indent, output);
- }
-// public abstract StringBuffer printStatement(int indent, StringBuffer output);
-
- public abstract void resolve(BlockScope scope);
-
- /**
- * Returns case constant associated to this statement (NotAConstant if none)
- */
- public Constant resolveCase(BlockScope scope, TypeBinding testType, SwitchStatement switchStatement) {
- // statement within a switch that are not case are treated as normal statement....
-
- resolve(scope);
- return Constant.NotAConstant;
- }
- public int getASTType() {
- return IASTNode.STATEMENT;
-
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/StringLiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/StringLiteral.java
deleted file mode 100644
index 422a101d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/StringLiteral.java
+++ /dev/null
@@ -1,110 +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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IStringLiteral;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-import org.eclipse.wst.jsdt.internal.compiler.impl.StringConstant;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class StringLiteral extends Literal implements IStringLiteral {
-
- char[] source;
- int lineNumber;
-
- public StringLiteral(char[] token, int start, int end, int lineNumber) {
-
- this(start,end);
- this.source = token;
- this.lineNumber = lineNumber - 1; // line number is 1 based
- }
-
- public StringLiteral(int s, int e) {
-
- super(s,e);
- }
-
- public void computeConstant() {
-
- constant = StringConstant.fromValue(String.valueOf(source));
- }
-
- public ExtendedStringLiteral extendWith(StringLiteral lit){
-
- //add the lit source to mine, just as if it was mine
- return new ExtendedStringLiteral(this,lit);
- }
-
- /**
- * Add the lit source to mine, just as if it was mine
- */
- public StringLiteralConcatenation extendsWith(StringLiteral lit) {
- return new StringLiteralConcatenation(this, lit);
- }
- public TypeBinding literalType(BlockScope scope) {
-
- return scope.getJavaLangString();
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output) {
-
- // handle some special char.....
- output.append('\"');
- for (int i = 0; i < source.length; i++) {
- switch (source[i]) {
- case '\b' :
- output.append("\\b"); //$NON-NLS-1$
- break;
- case '\t' :
- output.append("\\t"); //$NON-NLS-1$
- break;
- case '\n' :
- output.append("\\n"); //$NON-NLS-1$
- break;
- case '\f' :
- output.append("\\f"); //$NON-NLS-1$
- break;
- case '\r' :
- output.append("\\r"); //$NON-NLS-1$
- break;
- case '\"' :
- output.append("\\\""); //$NON-NLS-1$
- break;
- case '\'' :
- output.append("\\'"); //$NON-NLS-1$
- break;
- case '\\' : //take care not to display the escape as a potential real char
- output.append("\\\\"); //$NON-NLS-1$
- break;
- default :
- output.append(source[i]);
- }
- }
- output.append('\"');
- return output;
- }
-
- public char[] source() {
-
- return source;
- }
-
- public void traverse(ASTVisitor visitor, BlockScope scope) {
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
- }
- public int getASTType() {
- return IASTNode.STRING_LITERAL;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/StringLiteralConcatenation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/StringLiteralConcatenation.java
deleted file mode 100644
index 969f97ae..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/StringLiteralConcatenation.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IStringLiteralConcatenation;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-
-/**
- * Flatten string literal
- */
-public class StringLiteralConcatenation extends StringLiteral implements IStringLiteralConcatenation {
- private static final int INITIAL_SIZE = 5;
- public Expression[] literals;
- public int counter;
- /**
- * Build a two-strings literal
- * */
- public StringLiteralConcatenation(StringLiteral str1, StringLiteral str2) {
- super(str1.sourceStart, str1.sourceEnd);
- this.source = str1.source;
- this.literals = new StringLiteral[INITIAL_SIZE];
- this.counter = 0;
- this.literals[this.counter++] = str1;
- extendsWith(str2);
- }
-
- /**
- * Add the lit source to mine, just as if it was mine
- */
- public StringLiteralConcatenation extendsWith(StringLiteral lit) {
- this.sourceEnd = lit.sourceEnd;
- final int literalsLength = this.literals.length;
- if (this.counter == literalsLength) {
- // resize
- System.arraycopy(this.literals, 0, this.literals = new StringLiteral[literalsLength + INITIAL_SIZE], 0, literalsLength);
- }
- //uddate the source
- int length = source.length;
- System.arraycopy(
- source,
- 0,
- source = new char[length + lit.source.length],
- 0,
- length);
- System.arraycopy(lit.source, 0, source, length, lit.source.length);
- this.literals[this.counter++] = lit;
- return this;
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output) {
- output.append("StringLiteralConcatenation{"); //$NON-NLS-1$
- for (int i = 0, max = this.counter; i < max; i++) {
- this.literals[i].printExpression(indent, output);
- output.append("+\n");//$NON-NLS-1$
- }
- return output.append('}');
- }
-
- public char[] source() {
- return source;
- }
-
- public void traverse(ASTVisitor visitor, BlockScope scope) {
- if (visitor.visit(this, scope)) {
- for (int i = 0, max = this.counter; i < max; i++) {
- this.literals[i].traverse(visitor, scope);
- }
- }
- visitor.endVisit(this, scope);
- }
- public int getASTType() {
- return IASTNode.STRING_LITERAL_CONCATENATION;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/SubRoutineStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/SubRoutineStatement.java
deleted file mode 100644
index 2cbeed05..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/SubRoutineStatement.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.ISubRoutineStatement;
-
-
-/**
- * Extra behavior for statements which are generating subroutines
- */
-public abstract class SubRoutineStatement extends Statement implements ISubRoutineStatement {
-
-
-
-
-
-
-
-
-
-
- public abstract boolean isSubRoutineEscaping();
-
- public int getASTType() {
- return IASTNode.SUB_ROUTINE_STATEMENT;
-
- }
-}
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
deleted file mode 100644
index 2cfd9e33..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/SuperReference.java
+++ /dev/null
@@ -1,74 +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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.ISuperReference;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-import org.eclipse.wst.jsdt.internal.compiler.impl.Constant;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class SuperReference extends ThisReference implements ISuperReference {
-
- public SuperReference(int sourceStart, int sourceEnd) {
-
- super(sourceStart, sourceEnd);
- }
-
- public static ExplicitConstructorCall implicitSuperConstructorCall() {
-
- return new ExplicitConstructorCall(ExplicitConstructorCall.ImplicitSuper);
- }
-
- public boolean isImplicitThis() {
-
- return false;
- }
-
- public boolean isSuper() {
-
- return true;
- }
-
- public boolean isThis() {
-
- return false ;
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output){
-
- return output.append("super"); //$NON-NLS-1$
-
- }
-
- public TypeBinding resolveType(BlockScope scope) {
-
- constant = Constant.NotAConstant;
- if (!checkAccess(scope.methodScope()))
- return null;
- ReferenceBinding enclosingReceiverType = scope.enclosingReceiverType();
- if (enclosingReceiverType.id == T_JavaLangObject) {
- return null;
- }
- return this.resolvedType = enclosingReceiverType.superclass();
- }
-
- public void traverse(ASTVisitor visitor, BlockScope blockScope) {
- visitor.visit(this, blockScope);
- visitor.endVisit(this, blockScope);
- }
- public int getASTType() {
- return IASTNode.SUPER_REFERENCE;
-
- }
-}
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
deleted file mode 100644
index 2d4bc12e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/SwitchStatement.java
+++ /dev/null
@@ -1,220 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.ISwitchStatement;
-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;
-import org.eclipse.wst.jsdt.internal.compiler.flow.SwitchFlowContext;
-import org.eclipse.wst.jsdt.internal.compiler.impl.Constant;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class SwitchStatement extends Statement implements ISwitchStatement{
-
- public Expression expression;
- public Statement[] statements;
- public BlockScope scope;
- public int explicitDeclarations;
- public CaseStatement[] cases;
- public CaseStatement defaultCase;
- public int blockStart;
- public int caseCount;
- Constant[] constants;
-
- // fallthrough
- public final static int CASE = 0;
- public final static int FALLTHROUGH = 1;
- public final static int ESCAPING = 2;
-
- // for local variables table attributes
- int preSwitchInitStateIndex = -1;
- int mergedInitStateIndex = -1;
-
- public FlowInfo analyseCode(
- BlockScope currentScope,
- FlowContext flowContext,
- FlowInfo flowInfo) {
-
- try {
- flowInfo = expression.analyseCode(currentScope, flowContext, flowInfo);
- SwitchFlowContext switchContext =
- new SwitchFlowContext(flowContext, this);
-
- // analyse the block by considering specially the case/default statements (need to bind them
- // to the entry point)
- FlowInfo caseInits = FlowInfo.DEAD_END;
- // in case of statements before the first case
-// preSwitchInitStateIndex =
-// currentScope.methodScope().recordInitializationStates(flowInfo);
- int caseIndex = 0;
- if (statements != null) {
- boolean didAlreadyComplain = false;
- int fallThroughState = CASE;
- for (int i = 0, max = statements.length; i < max; i++) {
- Statement statement = statements[i];
- if ((caseIndex < caseCount) && (statement == cases[caseIndex])) { // statement is a case
- this.scope.enclosingCase = cases[caseIndex]; // record entering in a switch case block
- caseIndex++;
- if (fallThroughState == FALLTHROUGH
- && (statement.bits & ASTNode.DocumentedFallthrough) == 0) { // the case is not fall-through protected by a line comment
- scope.problemReporter().possibleFallThroughCase(this.scope.enclosingCase);
- }
- caseInits = caseInits.mergedWith(flowInfo.unconditionalInits());
- didAlreadyComplain = false; // reset complaint
- fallThroughState = CASE;
- } else if (statement == defaultCase) { // statement is the default case
- this.scope.enclosingCase = defaultCase; // record entering in a switch case block
- if (fallThroughState == FALLTHROUGH
- && (statement.bits & ASTNode.DocumentedFallthrough) == 0) {
- scope.problemReporter().possibleFallThroughCase(this.scope.enclosingCase);
- }
- caseInits = caseInits.mergedWith(flowInfo.unconditionalInits());
- didAlreadyComplain = false; // reset complaint
- fallThroughState = CASE;
- } else {
- fallThroughState = FALLTHROUGH; // reset below if needed
- }
- if (!statement.complainIfUnreachable(caseInits, scope, didAlreadyComplain)) {
- caseInits = statement.analyseCode(scope, switchContext, caseInits);
- if (caseInits == FlowInfo.DEAD_END) {
- fallThroughState = ESCAPING;
- }
- } else {
- didAlreadyComplain = true;
- }
- }
- }
-
- final TypeBinding resolvedTypeBinding = this.expression.resolvedType;
- // if no default case, then record it may jump over the block directly to the end
- if (defaultCase == null) {
- // only retain the potential initializations
- flowInfo.addPotentialInitializationsFrom(
- caseInits.mergedWith(switchContext.initsOnBreak));
-// mergedInitStateIndex =
-// currentScope.methodScope().recordInitializationStates(flowInfo);
- return flowInfo;
- }
-
- // merge all branches inits
- FlowInfo mergedInfo = caseInits.mergedWith(switchContext.initsOnBreak);
-// mergedInitStateIndex =
-// currentScope.methodScope().recordInitializationStates(mergedInfo);
- return mergedInfo;
- } finally {
- if (this.scope != null) this.scope.enclosingCase = null; // no longer inside switch case block
- }
- }
-
- public StringBuffer printStatement(int indent, StringBuffer output) {
-
- printIndent(indent, output).append("switch ("); //$NON-NLS-1$
- expression.printExpression(0, output).append(") {"); //$NON-NLS-1$
- if (statements != null) {
- for (int i = 0; i < statements.length; i++) {
- output.append('\n');
- if (statements[i] instanceof CaseStatement) {
- statements[i].printStatement(indent, output);
- } else {
- statements[i].printStatement(indent+2, output);
- }
- }
- }
- output.append("\n"); //$NON-NLS-1$
- return printIndent(indent, output).append('}');
- }
-
- 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);
- int length;
- // collection of cases is too big but we will only iterate until caseCount
- cases = new CaseStatement[length = statements.length];
- this.constants = new Constant[length];
- CaseStatement[] duplicateCaseStatements = null;
- int duplicateCaseStatementsCounter = 0;
- int counter = 0;
- for (int i = 0; i < length; i++) {
- Constant constant;
- final Statement statement = statements[i];
- if ((constant = statement.resolveCase(scope, expressionType, this)) != Constant.NotAConstant) {
- Constant key = constant;
- if (constant==null)
- continue;
- //----check for duplicate case statement------------
- for (int j = 0; j < counter; j++) {
- if (this.constants[j].equals(key)) {
- final CaseStatement currentCaseStatement = (CaseStatement) statement;
- if (duplicateCaseStatements == null) {
- scope.problemReporter().duplicateCase(cases[j]);
- scope.problemReporter().duplicateCase(currentCaseStatement);
- duplicateCaseStatements = new CaseStatement[length];
- duplicateCaseStatements[duplicateCaseStatementsCounter++] = cases[j];
- duplicateCaseStatements[duplicateCaseStatementsCounter++] = currentCaseStatement;
- } else {
- boolean found = false;
- searchReportedDuplicate: for (int k = 2; k < duplicateCaseStatementsCounter; k++) {
- if (duplicateCaseStatements[k] == statement) {
- found = true;
- break searchReportedDuplicate;
- }
- }
- if (!found) {
- scope.problemReporter().duplicateCase(currentCaseStatement);
- duplicateCaseStatements[duplicateCaseStatementsCounter++] = currentCaseStatement;
- }
- }
- }
- }
- this.constants[counter++] = key;
- }
- }
- if (length != counter) { // resize constants array
- System.arraycopy(this.constants, 0, this.constants = new Constant[counter], 0, counter);
- }
- } else {
- if ((this.bits & UndocumentedEmptyBlock) != 0) {
- upperScope.problemReporter().undocumentedEmptyBlock(this.blockStart, this.sourceEnd);
- }
- }
- } finally {
- if (this.scope != null) this.scope.enclosingCase = null; // no longer inside switch case block
- }
- }
-
- public void traverse(
- ASTVisitor visitor,
- BlockScope blockScope) {
-
- if (visitor.visit(this, blockScope)) {
- expression.traverse(visitor, scope);
- if (statements != null) {
- int statementsLength = statements.length;
- for (int i = 0; i < statementsLength; i++)
- statements[i].traverse(visitor, scope);
- }
- }
- visitor.endVisit(this, blockScope);
- }
- public int getASTType() {
- return IASTNode.SWITCH_STATEMENT;
-
- }
-
-}
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
deleted file mode 100644
index c15f5f99..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ThisReference.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IThisReference;
-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;
-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.ClassScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class ThisReference extends Reference implements IThisReference {
-
- public static ThisReference implicitThis(){
-
- ThisReference implicitThis = new ThisReference(0, 0);
- implicitThis.bits |= IsImplicitThis;
- return implicitThis;
- }
-
- public ThisReference(int sourceStart, int sourceEnd) {
-
- this.sourceStart = sourceStart;
- this.sourceEnd = sourceEnd;
- }
-
- /*
- * @see Reference#analyseAssignment(...)
- */
- public FlowInfo analyseAssignment(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo, Assignment assignment, boolean isCompound) {
-
- return flowInfo; // this cannot be assigned
- }
-
- public boolean checkAccess(MethodScope methodScope) {
-
- // this/super cannot be used in constructor call
-// if (methodScope!=null && methodScope.isConstructorCall) {
-// methodScope.problemReporter().fieldsOrThisBeforeConstructorInvocation(this);
-// return false;
-// }
-
- // static may not refer to this/super
-// if (methodScope!=null && methodScope.isStatic) {
-// methodScope.problemReporter().errorThisSuperInStatic(this);
-// return false;
-// }
- return true;
- }
-
- public boolean isImplicitThis() {
-
- return (this.bits & IsImplicitThis) != 0;
- }
-
- public boolean isThis() {
-
- return true ;
- }
-
- public int nullStatus(FlowInfo flowInfo) {
- return FlowInfo.NON_NULL;
- }
-
- public StringBuffer printExpression(int indent, StringBuffer output){
-
- if (this.isImplicitThis()) return output;
- return output.append("this"); //$NON-NLS-1$
- }
-
- public TypeBinding resolveType(BlockScope scope) {
-
- constant = Constant.NotAConstant;
- if (!this.isImplicitThis() &&!checkAccess(scope.methodScope())) {
- return null;
- }
- MethodScope methodScope = scope.methodScope();
- if (methodScope!=null && methodScope.isStatic)
- bits |= Binding.TYPE;
- return this.resolvedType = scope.enclosingReceiverType();
- }
-
- public void traverse(ASTVisitor visitor, BlockScope blockScope) {
-
- visitor.visit(this, blockScope);
- visitor.endVisit(this, blockScope);
- }
- public void traverse(ASTVisitor visitor, ClassScope blockScope) {
-
- visitor.visit(this, blockScope);
- visitor.endVisit(this, blockScope);
- }
- public int getASTType() {
- return IASTNode.THIS_REFERENCE;
-
- }
-}
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
deleted file mode 100644
index 547ad8de..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ThrowStatement.java
+++ /dev/null
@@ -1,62 +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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IThrowStatement;
-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;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ProblemReferenceBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class ThrowStatement extends Statement implements IThrowStatement {
-
- public Expression exception;
- public TypeBinding exceptionType;
-
-public ThrowStatement(Expression exception, int sourceStart, int sourceEnd) {
- this.exception = exception;
- this.sourceStart = sourceStart;
- this.sourceEnd = sourceEnd;
-}
-
-public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {
- this.exception.analyseCode(currentScope, flowContext, flowInfo);
- // need to check that exception thrown is actually caught somewhere
- //flowContext.checkExceptionHandlers(this.exceptionType, this, flowInfo, currentScope);
- return FlowInfo.DEAD_END;
-}
-
-public StringBuffer printStatement(int indent, StringBuffer output) {
- printIndent(indent, output).append("throw "); //$NON-NLS-1$
- this.exception.printExpression(0, output);
- return output.append(';');
-}
-
-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);
- }
-}
-
-public void traverse(ASTVisitor visitor, BlockScope blockScope) {
- if (visitor.visit(this, blockScope))
- this.exception.traverse(visitor, blockScope);
- visitor.endVisit(this, blockScope);
-}
-public int getASTType() {
- return IASTNode.THROW_STATEMENT;
-
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/TrueLiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/TrueLiteral.java
deleted file mode 100644
index b846bae5..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/TrueLiteral.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.ITrueLiteral;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-import org.eclipse.wst.jsdt.internal.compiler.impl.BooleanConstant;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class TrueLiteral extends MagicLiteral implements ITrueLiteral {
- static final char[] source = {'t' , 'r' , 'u' , 'e'};
-public TrueLiteral(int s , int e) {
- super(s,e);
-}
-public void computeConstant() {
- this.constant = BooleanConstant.fromValue(true);
-}
-public TypeBinding literalType(BlockScope scope) {
- return scope.getJavaLangBoolean();
-}
-/**
- *
- */
-public char[] source() {
- return source;
-}
-public void traverse(ASTVisitor visitor, BlockScope scope) {
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
-}
-public int getASTType() {
- return IASTNode.TRUE_LITERAL;
-
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/TryStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/TryStatement.java
deleted file mode 100644
index 47a64acb..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/TryStatement.java
+++ /dev/null
@@ -1,449 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.ITryStatement;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-import org.eclipse.wst.jsdt.internal.compiler.flow.ExceptionHandlingFlowContext;
-import org.eclipse.wst.jsdt.internal.compiler.flow.FinallyFlowContext;
-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.flow.InsideSubRoutineFlowContext;
-import org.eclipse.wst.jsdt.internal.compiler.flow.NullInfoRegistry;
-import org.eclipse.wst.jsdt.internal.compiler.flow.UnconditionalFlowInfo;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-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.ReferenceBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeIds;
-
-public class TryStatement extends SubRoutineStatement implements ITryStatement {
-
- public Block tryBlock;
- public Block[] catchBlocks;
-
- public Argument[] catchArguments;
-
- // should rename into subRoutineComplete to be set to false by default
-
- public Block finallyBlock;
- BlockScope scope;
-
- public UnconditionalFlowInfo subRoutineInits;
- ReferenceBinding[] caughtExceptionTypes;
- boolean[] catchExits;
-
- boolean isSubRoutineStartLabel;
- public LocalVariableBinding anyExceptionVariable,
- returnAddressVariable,
- secretReturnValue;
-
-
-
- // for local variables table attributes
- int mergedInitStateIndex = -1;
- int preTryInitStateIndex = -1;
- int naturalExitMergeInitStateIndex = -1;
- int[] catchExitInitStateIndexes;
-
-public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {
-
- // Consider the try block and catch block so as to compute the intersection of initializations and
- // the minimum exit relative depth amongst all of them. Then consider the subroutine, and append its
- // initialization to the try/catch ones, if the subroutine completes normally. If the subroutine does not
- // complete, then only keep this result for the rest of the analysis
-
- // process the finally block (subroutine) - create a context for the subroutine
-
- if (this.anyExceptionVariable != null) {
- this.anyExceptionVariable.useFlag = LocalVariableBinding.USED;
- }
- if (this.returnAddressVariable != null) { // TODO (philippe) if subroutine is escaping, unused
- this.returnAddressVariable.useFlag = LocalVariableBinding.USED;
- }
- if (!isSubRoutineStartLabel) {
- // no finally block -- this is a simplified copy of the else part
- // process the try block in a context handling the local exceptions.
- ExceptionHandlingFlowContext handlingContext =
- new ExceptionHandlingFlowContext(
- flowContext,
- this,
- this.caughtExceptionTypes,
- this.scope,
- flowInfo.unconditionalInits());
- handlingContext.initsOnFinally =
- new NullInfoRegistry(flowInfo.unconditionalInits());
- // only try blocks initialize that member - may consider creating a
- // separate class if needed
-
- FlowInfo tryInfo;
- if (this.tryBlock.isEmptyBlock()) {
- tryInfo = flowInfo;
- } else {
- tryInfo = this.tryBlock.analyseCode(currentScope, handlingContext, flowInfo.copy());
- if ((tryInfo.tagBits & FlowInfo.UNREACHABLE) != 0)
- this.bits |= ASTNode.IsTryBlockExiting;
- }
-
- // process the catch blocks - computing the minimal exit depth amongst try/catch
- if (this.catchArguments != null) {
- int catchCount;
- this.catchExits = new boolean[catchCount = this.catchBlocks.length];
- this.catchExitInitStateIndexes = new int[catchCount];
- for (int i = 0; i < catchCount; i++) {
- // keep track of the inits that could potentially have led to this exception handler (for final assignments diagnosis)
- FlowInfo catchInfo;
- if (this.caughtExceptionTypes[i].isUncheckedException(true)) {
- catchInfo =
- handlingContext.initsOnFinally.mitigateNullInfoOf(
- flowInfo.unconditionalCopy().
- addPotentialInitializationsFrom(
- handlingContext.initsOnException(
- this.caughtExceptionTypes[i])).
- addPotentialInitializationsFrom(tryInfo).
- addPotentialInitializationsFrom(
- handlingContext.initsOnReturn));
- } else {
- catchInfo =
- flowInfo.unconditionalCopy().
- addPotentialInitializationsFrom(
- handlingContext.initsOnException(
- this.caughtExceptionTypes[i]))
- .addPotentialInitializationsFrom(
- tryInfo.nullInfoLessUnconditionalCopy())
- // remove null info to protect point of
- // exception null info
- .addPotentialInitializationsFrom(
- handlingContext.initsOnReturn.
- nullInfoLessUnconditionalCopy());
- }
-
- // catch var is always set
- LocalVariableBinding catchArg = this.catchArguments[i].binding;
- catchInfo.markAsDefinitelyAssigned(catchArg);
- catchInfo.markAsDefinitelyNonNull(catchArg);
- /*
- "If we are about to consider an unchecked exception handler, potential inits may have occured inside
- the try block that need to be detected , e.g.
- try { x = 1; throwSomething();} catch(Exception e){ x = 2} "
- "(uncheckedExceptionTypes notNil and: [uncheckedExceptionTypes at: index])
- ifTrue: [catchInits addPotentialInitializationsFrom: tryInits]."
- */
- if (this.tryBlock.statements == null) {
- catchInfo.setReachMode(FlowInfo.UNREACHABLE);
- }
- catchInfo =
- this.catchBlocks[i].analyseCode(
- currentScope,
- flowContext,
- catchInfo);
-// this.catchExitInitStateIndexes[i] = currentScope.methodScope().recordInitializationStates(catchInfo);
- this.catchExits[i] =
- (catchInfo.tagBits & FlowInfo.UNREACHABLE) != 0;
- tryInfo = tryInfo.mergedWith(catchInfo.unconditionalInits());
- }
- }
-// this.mergedInitStateIndex =
-// currentScope.methodScope().recordInitializationStates(tryInfo);
-
- // chain up null info registry
- if (flowContext.initsOnFinally != null) {
- flowContext.initsOnFinally.add(handlingContext.initsOnFinally);
- }
-
- return tryInfo;
- } else {
- InsideSubRoutineFlowContext insideSubContext;
- FinallyFlowContext finallyContext;
- UnconditionalFlowInfo subInfo;
- // analyse finally block first
- insideSubContext = new InsideSubRoutineFlowContext(flowContext, this);
-
- subInfo =
- this.finallyBlock
- .analyseCode(
- currentScope,
- finallyContext = new FinallyFlowContext(flowContext, this.finallyBlock),
- flowInfo.nullInfoLessUnconditionalCopy())
- .unconditionalInits();
- if (subInfo == FlowInfo.DEAD_END) {
- this.bits |= ASTNode.IsSubRoutineEscaping;
- this.scope.problemReporter().finallyMustCompleteNormally(this.finallyBlock);
- }
- this.subRoutineInits = subInfo;
- // process the try block in a context handling the local exceptions.
- ExceptionHandlingFlowContext handlingContext =
- new ExceptionHandlingFlowContext(
- insideSubContext,
- this,
- this.caughtExceptionTypes,
- this.scope,
- flowInfo.unconditionalInits());
- handlingContext.initsOnFinally =
- new NullInfoRegistry(flowInfo.unconditionalInits());
- // only try blocks initialize that member - may consider creating a
- // separate class if needed
-
- FlowInfo tryInfo;
- if (this.tryBlock.isEmptyBlock()) {
- tryInfo = flowInfo;
- } else {
- tryInfo = this.tryBlock.analyseCode(currentScope, handlingContext, flowInfo.copy());
- if ((tryInfo.tagBits & FlowInfo.UNREACHABLE) != 0)
- this.bits |= ASTNode.IsTryBlockExiting;
- }
-
- // process the catch blocks - computing the minimal exit depth amongst try/catch
- if (this.catchArguments != null) {
- int catchCount;
- this.catchExits = new boolean[catchCount = this.catchBlocks.length];
- this.catchExitInitStateIndexes = new int[catchCount];
- for (int i = 0; i < catchCount; i++) {
- // keep track of the inits that could potentially have led to this exception handler (for final assignments diagnosis)
- FlowInfo catchInfo;
- if (this.caughtExceptionTypes[i].isUncheckedException(true)) {
- catchInfo =
- handlingContext.initsOnFinally.mitigateNullInfoOf(
- flowInfo.unconditionalCopy().
- addPotentialInitializationsFrom(
- handlingContext.initsOnException(
- this.caughtExceptionTypes[i])).
- addPotentialInitializationsFrom(tryInfo).
- addPotentialInitializationsFrom(
- handlingContext.initsOnReturn));
- }else {
- catchInfo =
- flowInfo.unconditionalCopy()
- .addPotentialInitializationsFrom(
- handlingContext.initsOnException(
- this.caughtExceptionTypes[i]))
- .addPotentialInitializationsFrom(
- tryInfo.nullInfoLessUnconditionalCopy())
- // remove null info to protect point of
- // exception null info
- .addPotentialInitializationsFrom(
- handlingContext.initsOnReturn.
- nullInfoLessUnconditionalCopy());
- }
-
- // catch var is always set
- LocalVariableBinding catchArg = this.catchArguments[i].binding;
- catchInfo.markAsDefinitelyAssigned(catchArg);
- catchInfo.markAsDefinitelyNonNull(catchArg);
- /*
- "If we are about to consider an unchecked exception handler, potential inits may have occured inside
- the try block that need to be detected , e.g.
- try { x = 1; throwSomething();} catch(Exception e){ x = 2} "
- "(uncheckedExceptionTypes notNil and: [uncheckedExceptionTypes at: index])
- ifTrue: [catchInits addPotentialInitializationsFrom: tryInits]."
- */
- if (this.tryBlock.statements == null) {
- catchInfo.setReachMode(FlowInfo.UNREACHABLE);
- }
- catchInfo =
- this.catchBlocks[i].analyseCode(
- currentScope,
- insideSubContext,
- catchInfo);
-// this.catchExitInitStateIndexes[i] = currentScope.methodScope().recordInitializationStates(catchInfo);
- this.catchExits[i] =
- (catchInfo.tagBits & FlowInfo.UNREACHABLE) != 0;
- tryInfo = tryInfo.mergedWith(catchInfo.unconditionalInits());
- }
- }
- // we also need to check potential multiple assignments of final variables inside the finally block
- // need to include potential inits from returns inside the try/catch parts - 1GK2AOF
- finallyContext.complainOnDeferredChecks(
- handlingContext.initsOnFinally.mitigateNullInfoOf(
- (tryInfo.tagBits & FlowInfo.UNREACHABLE) == 0 ?
- flowInfo.unconditionalCopy().
- addPotentialInitializationsFrom(tryInfo).
- // lighten the influence of the try block, which may have
- // exited at any point
- addPotentialInitializationsFrom(insideSubContext.initsOnReturn) :
- insideSubContext.initsOnReturn),
- currentScope);
-
- // chain up null info registry
- if (flowContext.initsOnFinally != null) {
- flowContext.initsOnFinally.add(handlingContext.initsOnFinally);
- }
-
-// this.naturalExitMergeInitStateIndex =
-// currentScope.methodScope().recordInitializationStates(tryInfo);
- if (subInfo == FlowInfo.DEAD_END) {
-// this.mergedInitStateIndex =
-// currentScope.methodScope().recordInitializationStates(subInfo);
- return subInfo;
- } else {
- FlowInfo mergedInfo = tryInfo.addInitializationsFrom(subInfo);
-// this.mergedInitStateIndex =
-// currentScope.methodScope().recordInitializationStates(mergedInfo);
- return mergedInfo;
- }
- }
-}
-
-
-
-
-
-public boolean isSubRoutineEscaping() {
- return (this.bits & ASTNode.IsSubRoutineEscaping) != 0;
-}
-
-public StringBuffer printStatement(int indent, StringBuffer output) {
- printIndent(indent, output).append("try \n"); //$NON-NLS-1$
- this.tryBlock.printStatement(indent + 1, output);
-
- //catches
- if (this.catchBlocks != null)
- for (int i = 0; i < this.catchBlocks.length; i++) {
- output.append('\n');
- printIndent(indent, output).append("catch ("); //$NON-NLS-1$
- this.catchArguments[i].print(0, output).append(") "); //$NON-NLS-1$
- this.catchBlocks[i].printStatement(indent + 1, output);
- }
- //finally
- if (this.finallyBlock != null) {
- output.append('\n');
- printIndent(indent, output).append("finally\n"); //$NON-NLS-1$
- this.finallyBlock.printStatement(indent + 1, output);
- }
- return output;
-}
-
-public void resolve(BlockScope upperScope) {
- // special scope for secret locals optimization.
- this.scope = new BlockScope(upperScope);
-
- BlockScope tryScope = new BlockScope(this.scope);
- BlockScope finallyScope = null;
-
- if (this.finallyBlock != null) {
- if (this.finallyBlock.isEmptyBlock()) {
- if ((this.finallyBlock.bits & ASTNode.UndocumentedEmptyBlock) != 0) {
- this.scope.problemReporter().undocumentedEmptyBlock(this.finallyBlock.sourceStart, this.finallyBlock.sourceEnd);
- }
- } else {
- finallyScope = JavaScriptCore.IS_ECMASCRIPT4 ? new BlockScope(this.scope, false) : this.scope; // don't add it yet to parent scope
-
- // provision for returning and forcing the finally block to run
- MethodScope methodScope = this.scope.methodScope();
-
- // the type does not matter as long as it is not a base type
-// if (!upperScope.compilerOptions().inlineJsrBytecode) {
-// this.returnAddressVariable =
-// new LocalVariableBinding(TryStatement.SECRET_RETURN_ADDRESS_NAME, upperScope.getJavaLangObject(), ClassFileConstants.AccDefault, false);
-// finallyScope.addLocalVariable(this.returnAddressVariable);
-// this.returnAddressVariable.setConstant(Constant.NotAConstant); // not inlinable
-// }
- this.isSubRoutineStartLabel = true;
-
-// this.anyExceptionVariable =
-// new LocalVariableBinding(TryStatement.SECRET_ANY_HANDLER_NAME, this.scope.getJavaLangThrowable(), ClassFileConstants.AccDefault, false);
-// finallyScope.addLocalVariable(this.anyExceptionVariable);
-// this.anyExceptionVariable.setConstant(Constant.NotAConstant); // not inlinable
-
- if (methodScope != null && !methodScope.isInsideInitializer()) {
- MethodBinding methodBinding =
- ((AbstractMethodDeclaration) methodScope.referenceContext).binding;
- if (methodBinding != null) {
- TypeBinding methodReturnType = methodBinding.returnType;
- if (methodReturnType.id != TypeIds.T_void) {
-// this.secretReturnValue =
-// new LocalVariableBinding(
-// TryStatement.SECRET_RETURN_VALUE_NAME,
-// methodReturnType,
-// ClassFileConstants.AccDefault,
-// false);
-// finallyScope.addLocalVariable(this.secretReturnValue);
-// this.secretReturnValue.setConstant(Constant.NotAConstant); // not inlinable
- }
- }
- }
- this.finallyBlock.resolveUsing(finallyScope);
- if (JavaScriptCore.IS_ECMASCRIPT4) {
- // force the finally scope to have variable positions shifted after its try scope and catch ones
- finallyScope.shiftScopes = new BlockScope[this.catchArguments == null ? 1
- : this.catchArguments.length + 1];
- finallyScope.shiftScopes[0] = tryScope;
- }
- }
- }
- this.tryBlock.resolveUsing(tryScope);
-
- // arguments type are checked against JavaLangThrowable in resolveForCatch(..)
- if (this.catchBlocks != null) {
- int length = this.catchArguments.length;
- TypeBinding[] argumentTypes = new TypeBinding[length];
- boolean catchHasError = false;
- for (int i = 0; i < length; i++) {
- BlockScope catchScope = new BlockScope(this.scope);
- if (JavaScriptCore.IS_ECMASCRIPT4 && finallyScope != null){
- finallyScope.shiftScopes[i+1] = catchScope;
- }
- // side effect on catchScope in resolveForCatch(..)
- if ((argumentTypes[i] = this.catchArguments[i].resolveForCatch(catchScope)) == null) {
- catchHasError = true;
- }
- this.catchBlocks[i].resolveUsing(catchScope);
- }
- if (catchHasError) {
- return;
- }
- // Verify that the catch clause are ordered in the right way:
- // more specialized first.
- this.caughtExceptionTypes = new ReferenceBinding[length];
- for (int i = 0; i < length; i++) {
- this.caughtExceptionTypes[i] = (ReferenceBinding) argumentTypes[i];
-// for (int j = 0; j < i; j++) {
-// if (this.caughtExceptionTypes[i].isCompatibleWith(argumentTypes[j])) {
-// this.scope.problemReporter().wrongSequenceOfExceptionTypesError(this, this.caughtExceptionTypes[i], i, argumentTypes[j]);
-// }
-// }
- }
- } else {
- this.caughtExceptionTypes = new ReferenceBinding[0];
- }
-
- if (JavaScriptCore.IS_ECMASCRIPT4 && finallyScope != null){
- // add finallyScope as last subscope, so it can be shifted behind try/catch subscopes.
- // the shifting is necessary to achieve no overlay in between the finally scope and its
- // sibling in term of local variable positions.
- this.scope.addSubscope(finallyScope);
- }
-}
-
-public void traverse(ASTVisitor visitor, BlockScope blockScope) {
- if (visitor.visit(this, blockScope)) {
- if(this.scope==null) this.scope=blockScope;
- this.tryBlock.traverse(visitor, this.scope);
- if (this.catchArguments != null) {
- for (int i = 0, max = this.catchBlocks.length; i < max; i++) {
- this.catchArguments[i].traverse(visitor, this.scope);
- this.catchBlocks[i].traverse(visitor, this.scope);
- }
- }
- if (this.finallyBlock != null)
- this.finallyBlock.traverse(visitor, this.scope);
- }
- visitor.endVisit(this, blockScope);
-}
-public int getASTType() {
- return IASTNode.TRY_STATEMENT;
-
-}
-}
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
deleted file mode 100644
index 94fd96b6..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/TypeDeclaration.java
+++ /dev/null
@@ -1,983 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.ITypeDeclaration;
-import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-import org.eclipse.wst.jsdt.internal.compiler.CompilationResult;
-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.flow.InitializationFlowContext;
-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.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.ExtraCompilerModifiers;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.FieldBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.LocalTypeBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.MemberTypeBinding;
-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.NestedTypeBinding;
-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.problem.AbortCompilation;
-import org.eclipse.wst.jsdt.internal.compiler.problem.AbortCompilationUnit;
-import org.eclipse.wst.jsdt.internal.compiler.problem.AbortMethod;
-import org.eclipse.wst.jsdt.internal.compiler.problem.AbortType;
-import org.eclipse.wst.jsdt.internal.compiler.problem.ProblemSeverities;
-
-public class TypeDeclaration extends Statement implements ProblemSeverities, ReferenceContext, ITypeDeclaration {
- // Type decl kinds
- public static final int CLASS_DECL = 1;
-
- public int modifiers = ClassFileConstants.AccDefault;
- public int modifiersSourceStart;
- public char[] name;
- public TypeReference superclass;
- public FieldDeclaration[] fields;
- public AbstractMethodDeclaration[] methods;
- public TypeDeclaration[] memberTypes;
- public SourceTypeBinding binding= new SourceTypeBinding(null,null,null);
- public ClassScope scope;
- public MethodScope initializerScope;
- public MethodScope staticInitializerScope;
- public boolean ignoreFurtherInvestigation = false;
- public int maxFieldCount;
- public int declarationSourceStart;
- public int declarationSourceEnd;
- public int bodyStart;
- public int bodyEnd; // doesn't include the trailing comment if any.
- public CompilationResult compilationResult;
- public MethodDeclaration[] missingAbstractMethods;
- public Javadoc javadoc;
-
- public QualifiedAllocationExpression allocation; // for anonymous only
- public TypeDeclaration enclosingType; // for member types only
-
-public TypeDeclaration(CompilationResult compilationResult){
- this.compilationResult = compilationResult;
-}
-
-/*
- * We cause the compilation task to abort to a given extent.
- */
-public void abort(int abortLevel, CategorizedProblem problem) {
- switch (abortLevel) {
- case AbortCompilation :
- throw new AbortCompilation(this.compilationResult, problem);
- case AbortCompilationUnit :
- throw new AbortCompilationUnit(this.compilationResult, problem);
- case AbortMethod :
- throw new AbortMethod(this.compilationResult, problem);
- default :
- throw new AbortType(this.compilationResult, problem);
- }
-}
-
-/**
- * This method is responsible for adding a <clinit> method declaration to the type method collections.
- * Note that this implementation is inserting it in first place (as VAJ or javac), and that this
- * impacts the behavior of the method ConstantPool.resetForClinit(int. int), in so far as
- * the latter will have to reset the constant pool state accordingly (if it was added first, it does
- * not need to preserve some of the method specific cached entries since this will be the first method).
- * inserts the clinit method declaration in the first position.
- *
- * @see org.eclipse.wst.jsdt.internal.compiler.codegen.ConstantPool#resetForClinit(int, int)
- */
-public final void addClinit() {
- //see comment on needClassInitMethod
- if (needClassInitMethod()) {
- int length;
- AbstractMethodDeclaration[] methodDeclarations;
- if ((methodDeclarations = this.methods) == null) {
- length = 0;
- methodDeclarations = new AbstractMethodDeclaration[1];
- } else {
- length = methodDeclarations.length;
- System.arraycopy(
- methodDeclarations,
- 0,
- (methodDeclarations = new AbstractMethodDeclaration[length + 1]),
- 1,
- length);
- }
- Clinit clinit = new Clinit(this.compilationResult);
- methodDeclarations[0] = clinit;
- // clinit is added in first location, so as to minimize the use of ldcw (big consumer of constant inits)
- clinit.declarationSourceStart = clinit.sourceStart = this.sourceStart;
- clinit.declarationSourceEnd = clinit.sourceEnd = this.sourceEnd;
- clinit.bodyEnd = this.sourceEnd;
- this.methods = methodDeclarations;
- }
-}
-
-/*
- * INTERNAL USE ONLY - Creates a fake method declaration for the corresponding binding.
- * It is used to report errors for missing abstract methods.
- */
-public MethodDeclaration addMissingAbstractMethodFor(MethodBinding methodBinding) {
- TypeBinding[] argumentTypes = methodBinding.parameters;
- int argumentsLength = argumentTypes.length;
- //the constructor
- MethodDeclaration methodDeclaration = new MethodDeclaration(this.compilationResult);
- methodDeclaration.selector = methodBinding.selector;
- methodDeclaration.sourceStart = this.sourceStart;
- methodDeclaration.sourceEnd = this.sourceEnd;
- methodDeclaration.modifiers = methodBinding.getAccessFlags() & ~ClassFileConstants.AccAbstract;
-
- if (argumentsLength > 0) {
- String baseName = "arg";//$NON-NLS-1$
- Argument[] arguments = (methodDeclaration.arguments = new Argument[argumentsLength]);
- for (int i = argumentsLength; --i >= 0;) {
- arguments[i] = new Argument((baseName + i).toCharArray(), 0L, null /*type ref*/, ClassFileConstants.AccDefault);
- }
- }
-
- //adding the constructor in the methods list
- if (this.missingAbstractMethods == null) {
- this.missingAbstractMethods = new MethodDeclaration[] { methodDeclaration };
- } else {
- MethodDeclaration[] newMethods;
- System.arraycopy(
- this.missingAbstractMethods,
- 0,
- newMethods = new MethodDeclaration[this.missingAbstractMethods.length + 1],
- 1,
- this.missingAbstractMethods.length);
- newMethods[0] = methodDeclaration;
- this.missingAbstractMethods = newMethods;
- }
-
- //============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;
- }*/
- //===================================================
-
- return methodDeclaration;
-}
-
-/**
- * Flow analysis for a local innertype
- *
- */
-public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {
- if (this.ignoreFurtherInvestigation)
- return flowInfo;
- try {
- if ((flowInfo.tagBits & FlowInfo.UNREACHABLE) == 0) {
- this.bits |= ASTNode.IsReachable;
- LocalTypeBinding localType = (LocalTypeBinding) this.binding;
- localType.setConstantPoolName(currentScope.compilationUnitScope().computeConstantPoolName(localType));
- }
- updateMaxFieldCount(); // propagate down the max field count
- internalAnalyseCode(flowContext, flowInfo);
- } catch (AbortType e) {
- this.ignoreFurtherInvestigation = true;
- }
- return flowInfo;
-}
-
-/**
- * Flow analysis for a member innertype
- *
- */
-public void analyseCode(ClassScope enclosingClassScope) {
- if (this.ignoreFurtherInvestigation)
- return;
- try {
- // propagate down the max field count
- updateMaxFieldCount();
- internalAnalyseCode(null, FlowInfo.initial(this.maxFieldCount));
- } catch (AbortType e) {
- this.ignoreFurtherInvestigation = true;
- }
-}
-
-/**
- * Flow analysis for a local member innertype
- *
- */
-public void analyseCode(ClassScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {
- if (this.ignoreFurtherInvestigation)
- return;
- try {
- if ((flowInfo.tagBits & FlowInfo.UNREACHABLE) == 0) {
- this.bits |= ASTNode.IsReachable;
- LocalTypeBinding localType = (LocalTypeBinding) this.binding;
- localType.setConstantPoolName(currentScope.compilationUnitScope().computeConstantPoolName(localType));
- }
- updateMaxFieldCount(); // propagate down the max field count
- internalAnalyseCode(flowContext, flowInfo);
- } catch (AbortType e) {
- this.ignoreFurtherInvestigation = true;
- }
-}
-
-/**
- * Flow analysis for a package member type
- *
- */
-public void analyseCode(CompilationUnitScope unitScope) {
- if (this.ignoreFurtherInvestigation)
- return;
- try {
- internalAnalyseCode(null, FlowInfo.initial(this.maxFieldCount));
- } catch (AbortType e) {
- this.ignoreFurtherInvestigation = true;
- }
-}
-
-/**
- * Check for constructor vs. method with no return type.
- * Answers true if at least one constructor is defined
- */
-public boolean checkConstructors(Parser parser) {
- //if a constructor has not the name of the type,
- //convert it into a method with 'null' as its return type
- boolean hasConstructor = false;
- if (this.methods != null) {
- for (int i = this.methods.length; --i >= 0;) {
- AbstractMethodDeclaration am;
- if ((am = this.methods[i]).isConstructor()) {
- if (!CharOperation.equals(am.selector, this.name)) {
- // the constructor was in fact a method with no return type
- // unless an explicit constructor call was supplied
- ConstructorDeclaration c = (ConstructorDeclaration) am;
- if (c.constructorCall == null || c.constructorCall.isImplicitSuper()) { //changed to a method
- MethodDeclaration m = parser.convertToMethodDeclaration(c, this.compilationResult);
- this.methods[i] = m;
- }
- } else {
- hasConstructor = true;
- }
- }
- }
- }
- return hasConstructor;
-}
-
-public CompilationResult compilationResult() {
- return this.compilationResult;
-}
-
-public ConstructorDeclaration createDefaultConstructor( boolean needExplicitConstructorCall, boolean needToInsert) {
- //Add to method'set, the default constuctor that just recall the
- //super constructor with no arguments
- //The arguments' type will be positionned by the TC so just use
- //the default int instead of just null (consistency purpose)
-
- //the constructor
- ConstructorDeclaration constructor = new ConstructorDeclaration(this.compilationResult);
- constructor.bits |= ASTNode.IsDefaultConstructor;
- constructor.selector = this.name;
- constructor.modifiers = this.modifiers & ExtraCompilerModifiers.AccVisibilityMASK;
-
- //if you change this setting, please update the
- //SourceIndexer2.buildTypeDeclaration(TypeDeclaration,char[]) method
- constructor.declarationSourceStart = constructor.sourceStart = this.sourceStart;
- constructor.declarationSourceEnd =
- constructor.sourceEnd = constructor.bodyEnd = this.sourceEnd;
-
- //the super call inside the constructor
- if (needExplicitConstructorCall) {
- constructor.constructorCall = SuperReference.implicitSuperConstructorCall();
- constructor.constructorCall.sourceStart = this.sourceStart;
- constructor.constructorCall.sourceEnd = this.sourceEnd;
- }
-
- //adding the constructor in the methods list: rank is not critical since bindings will be sorted
- if (needToInsert) {
- if (this.methods == null) {
- this.methods = new AbstractMethodDeclaration[] { constructor };
- } else {
- AbstractMethodDeclaration[] newMethods;
- System.arraycopy(
- this.methods,
- 0,
- newMethods = new AbstractMethodDeclaration[this.methods.length + 1],
- 1,
- this.methods.length);
- newMethods[0] = constructor;
- this.methods = newMethods;
- }
- }
- return constructor;
-}
-
-// anonymous type constructor creation: rank is important since bindings already got sorted
-public MethodBinding createDefaultConstructorWithBinding(MethodBinding inheritedConstructorBinding) {
- //Add to method'set, the default constuctor that just recall the
- //super constructor with the same arguments
- String baseName = "$anonymous"; //$NON-NLS-1$
- TypeBinding[] argumentTypes = inheritedConstructorBinding.parameters;
- int argumentsLength = argumentTypes.length;
- //the constructor
- ConstructorDeclaration constructor = new ConstructorDeclaration(this.compilationResult);
- constructor.selector = new char[] { 'x' }; //no maining
- constructor.sourceStart = this.sourceStart;
- constructor.sourceEnd = this.sourceEnd;
- int newModifiers = this.modifiers & ExtraCompilerModifiers.AccVisibilityMASK;
- if (inheritedConstructorBinding.isVarargs()) {
- newModifiers |= ClassFileConstants.AccVarargs;
- }
- constructor.modifiers = newModifiers;
- constructor.bits |= ASTNode.IsDefaultConstructor;
-
- if (argumentsLength > 0) {
- Argument[] arguments = (constructor.arguments = new Argument[argumentsLength]);
- for (int i = argumentsLength; --i >= 0;) {
- arguments[i] = new Argument((baseName + i).toCharArray(), 0L, null /*type ref*/, ClassFileConstants.AccDefault);
- }
- }
- //the super call inside the constructor
- constructor.constructorCall = SuperReference.implicitSuperConstructorCall();
- constructor.constructorCall.sourceStart = this.sourceStart;
- constructor.constructorCall.sourceEnd = this.sourceEnd;
-
- if (argumentsLength > 0) {
- Expression[] args;
- args = constructor.constructorCall.arguments = new Expression[argumentsLength];
- for (int i = argumentsLength; --i >= 0;) {
- args[i] = new SingleNameReference((baseName + i).toCharArray(), 0L);
- }
- }
-
- //adding the constructor in the methods list
- if (this.methods == null) {
- this.methods = new AbstractMethodDeclaration[] { constructor };
- } else {
- AbstractMethodDeclaration[] newMethods;
- System.arraycopy(this.methods, 0, newMethods = new AbstractMethodDeclaration[this.methods.length + 1], 1, this.methods.length);
- newMethods[0] = constructor;
- this.methods = newMethods;
- }
-
- //============BINDING UPDATE==========================
- SourceTypeBinding sourceType = this.binding;
- constructor.binding = new MethodBinding(
- constructor.modifiers, //methodDeclaration
- argumentsLength == 0 ? Binding.NO_PARAMETERS : argumentTypes, //arguments bindings
- sourceType); //declaringClass
-
- constructor.binding.modifiers |= ExtraCompilerModifiers.AccIsDefaultConstructor;
-
- constructor.scope = new MethodScope(this.scope, constructor, true);
- constructor.bindArguments();
- constructor.constructorCall.resolve(constructor.scope);
-
- 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;
- 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;
-}
-
-/**
- * Find the matching parse node, answers null if nothing found
- */
-public FieldDeclaration declarationOf(FieldBinding fieldBinding) {
- if (fieldBinding != null && this.fields != null) {
- for (int i = 0, max = this.fields.length; i < max; i++) {
- FieldDeclaration fieldDecl;
- if ((fieldDecl = this.fields[i]).binding == fieldBinding)
- return fieldDecl;
- }
- }
- return null;
-}
-
-/**
- * Find the matching parse node, answers null if nothing found
- */
-public TypeDeclaration declarationOf(MemberTypeBinding memberTypeBinding) {
- if (memberTypeBinding != null && this.memberTypes != null) {
- for (int i = 0, max = this.memberTypes.length; i < max; i++) {
- TypeDeclaration memberTypeDecl;
- if ((memberTypeDecl = this.memberTypes[i]).binding == memberTypeBinding)
- return memberTypeDecl;
- }
- }
- return null;
-}
-
-/**
- * Find the matching parse node, answers null if nothing found
- */
-public AbstractMethodDeclaration declarationOf(MethodBinding methodBinding) {
- if (methodBinding != null && this.methods != null) {
- for (int i = 0, max = this.methods.length; i < max; i++) {
- AbstractMethodDeclaration methodDecl;
-
- if ((methodDecl = this.methods[i]).binding == methodBinding)
- return methodDecl;
- }
- }
- return null;
-}
-
-/**
- * Finds the matching type amoung this type's member types.
- * Returns null if no type with this name is found.
- * The type name is a compound name relative to this type
- * eg. if this type is X and we're looking for Y.X.A.B
- * then a type name would be {X, A, B}
- */
-public TypeDeclaration declarationOfType(char[][] typeName) {
- int typeNameLength = typeName.length;
- if (typeNameLength < 1 || !CharOperation.equals(typeName[0], this.name)) {
- return null;
- }
- if (typeNameLength == 1) {
- return this;
- }
- char[][] subTypeName = new char[typeNameLength - 1][];
- System.arraycopy(typeName, 1, subTypeName, 0, typeNameLength - 1);
- for (int i = 0; i < this.memberTypes.length; i++) {
- TypeDeclaration typeDecl = this.memberTypes[i].declarationOfType(subTypeName);
- if (typeDecl != null) {
- return typeDecl;
- }
- }
- return null;
-}
-
-public boolean hasErrors() {
- return this.ignoreFurtherInvestigation;
-}
-
-/**
- * Common flow analysis for all types
- */
-private void internalAnalyseCode(FlowContext flowContext, FlowInfo flowInfo) {
- if ((this.binding.isPrivate() || (this.binding.tagBits & (TagBits.IsAnonymousType|TagBits.IsLocalType)) == TagBits.IsLocalType) && !this.binding.isUsed()) {
- if (!this.scope.referenceCompilationUnit().compilationResult.hasSyntaxError) {
- this.scope.problemReporter().unusedPrivateType(this);
- }
- }
- InitializationFlowContext initializerContext = new InitializationFlowContext(null, this, this.initializerScope);
- InitializationFlowContext staticInitializerContext = new InitializationFlowContext(null, this, this.staticInitializerScope);
- FlowInfo nonStaticFieldInfo = flowInfo.unconditionalFieldLessCopy();
- FlowInfo staticFieldInfo = flowInfo.unconditionalFieldLessCopy();
- if (this.fields != null) {
- for (int i = 0, count = this.fields.length; i < count; i++) {
- FieldDeclaration field = this.fields[i];
- if (field.isStatic()) {
- if ((staticFieldInfo.tagBits & FlowInfo.UNREACHABLE) != 0)
- field.bits &= ~ASTNode.IsReachable;
-
- /*if (field.isField()){
- staticInitializerContext.handledExceptions = NoExceptions; // no exception is allowed jls8.3.2
- } else {*/
- staticInitializerContext.handledExceptions = Binding.ANY_EXCEPTION; // tolerate them all, and record them
- /*}*/
- staticFieldInfo =
- field.analyseCode(
- this.staticInitializerScope,
- staticInitializerContext,
- staticFieldInfo);
- // in case the initializer is not reachable, use a reinitialized flowInfo and enter a fake reachable
- // branch, since the previous initializer already got the blame.
- if (staticFieldInfo == FlowInfo.DEAD_END) {
- staticFieldInfo = FlowInfo.initial(this.maxFieldCount).setReachMode(FlowInfo.UNREACHABLE);
- }
- } else {
- if ((nonStaticFieldInfo.tagBits & FlowInfo.UNREACHABLE) != 0)
- field.bits &= ~ASTNode.IsReachable;
-
- /*if (field.isField()){
- initializerContext.handledExceptions = NoExceptions; // no exception is allowed jls8.3.2
- } else {*/
- initializerContext.handledExceptions = Binding.ANY_EXCEPTION; // tolerate them all, and record them
- /*}*/
- nonStaticFieldInfo =
- field.analyseCode(this.initializerScope, initializerContext, nonStaticFieldInfo);
- // in case the initializer is not reachable, use a reinitialized flowInfo and enter a fake reachable
- // branch, since the previous initializer already got the blame.
- if (nonStaticFieldInfo == FlowInfo.DEAD_END) {
- nonStaticFieldInfo = FlowInfo.initial(this.maxFieldCount).setReachMode(FlowInfo.UNREACHABLE);
- }
- }
- }
- }
- if (this.memberTypes != null) {
- for (int i = 0, count = this.memberTypes.length; i < count; i++) {
- if (flowContext != null){ // local type
- this.memberTypes[i].analyseCode(this.scope, flowContext, nonStaticFieldInfo.copy().setReachMode(flowInfo.reachMode())); // reset reach mode in case initializers did abrupt completely
- } else {
- this.memberTypes[i].analyseCode(this.scope);
- }
- }
- }
- if (this.methods != null) {
- UnconditionalFlowInfo outerInfo = flowInfo.unconditionalFieldLessCopy();
- FlowInfo constructorInfo = nonStaticFieldInfo.unconditionalInits().discardNonFieldInitializations().addInitializationsFrom(outerInfo);
- for (int i = 0, count = this.methods.length; i < count; i++) {
- AbstractMethodDeclaration method = this.methods[i];
- if (method.ignoreFurtherInvestigation)
- continue;
- if (method.isInitializationMethod()) {
- if (method.isStatic()) { // <clinit>
- method.analyseCode(
- this.scope,
- staticInitializerContext,
- staticFieldInfo.unconditionalInits().discardNonFieldInitializations().addInitializationsFrom(outerInfo));
- } else { // constructor
- ((ConstructorDeclaration)method).analyseCode(this.scope, initializerContext, constructorInfo.copy(), flowInfo.reachMode());
- }
- } else { // regular method
- method.analyseCode(this.scope, null, flowInfo.copy());
- }
- }
- }
-}
-
-public final static int kind(int flags) {
- return TypeDeclaration.CLASS_DECL;
-}
-
-/**
- * A <clinit> will be requested as soon as static fields or assertions are present. It will be eliminated during
- * classfile creation if no bytecode was actually produced based on some optimizations/compiler settings.
- */
-public final boolean needClassInitMethod() {
- // always need a <clinit> when assertions are present
- if ((this.bits & ASTNode.ContainsAssertion) != 0)
- return true;
-
- if (this.fields != null) {
- for (int i = this.fields.length; --i >= 0;) {
- FieldDeclaration field = this.fields[i];
- //need to test the modifier directly while there is no binding yet
- if ((field.modifiers & ClassFileConstants.AccStatic) != 0)
- return true; // TODO (philippe) shouldn't it check whether field is initializer or has some initial value ?
- }
- }
- return false;
-}
-
-public void parseMethod(Parser parser, CompilationUnitDeclaration unit) {
- //connect method bodies
- if (unit.ignoreMethodBodies)
- return;
-
- //members
- if (this.memberTypes != null) {
- int length = this.memberTypes.length;
- for (int i = 0; i < length; i++)
- this.memberTypes[i].parseMethod(parser, unit);
- }
-
- //methods
- if (this.methods != null) {
- int length = this.methods.length;
- for (int i = 0; i < length; i++) {
- this.methods[i].parseStatements(parser, unit);
- }
- }
-
- //initializers
- if (this.fields != null) {
- int length = this.fields.length;
- for (int i = 0; i < length; i++) {
- final FieldDeclaration fieldDeclaration = this.fields[i];
- switch(fieldDeclaration.getKind()) {
- case AbstractVariableDeclaration.INITIALIZER:
- ((Initializer) fieldDeclaration).parseStatements(parser, this, unit);
- break;
- }
- }
- }
-}
-
-public StringBuffer print(int indent, StringBuffer output) {
- if (this.javadoc != null) {
- this.javadoc.print(indent, output);
- }
- if ((this.bits & ASTNode.IsAnonymousType) == 0) {
- printIndent(indent, output);
- printHeader(0, output);
- }
- return printBody(indent, output);
-}
-
-public StringBuffer printBody(int indent, StringBuffer output) {
- output.append(" {"); //$NON-NLS-1$
- if (this.memberTypes != null) {
- for (int i = 0; i < this.memberTypes.length; i++) {
- if (this.memberTypes[i] != null) {
- output.append('\n');
- this.memberTypes[i].print(indent + 1, output);
- }
- }
- }
- if (this.fields != null) {
- for (int fieldI = 0; fieldI < this.fields.length; fieldI++) {
- if (this.fields[fieldI] != null) {
- output.append('\n');
- this.fields[fieldI].print(indent + 1, output);
- }
- }
- }
- if (this.methods != null) {
- for (int i = 0; i < this.methods.length; i++) {
- if (this.methods[i] != null) {
- output.append('\n');
- this.methods[i].print(indent + 1, output);
- }
- }
- }
- output.append('\n');
- return printIndent(indent, output).append('}');
-}
-
-public StringBuffer printHeader(int indent, StringBuffer output) {
- printModifiers(this.modifiers, output);
-
- switch (kind(this.modifiers)) {
- case TypeDeclaration.CLASS_DECL :
- output.append("class "); //$NON-NLS-1$
- break;
- }
- output.append(this.name);
-
- if (this.superclass != null) {
- output.append(" extends "); //$NON-NLS-1$
- this.superclass.print(0, output);
- }
- return output;
-}
-
-public StringBuffer printStatement(int tab, StringBuffer output) {
- return print(tab, output);
-}
-
-
-
-public void resolve() {
- SourceTypeBinding sourceType = this.binding;
- if (sourceType == null) {
- this.ignoreFurtherInvestigation = true;
- return;
- }
- try {
- if ((this.bits & ASTNode.UndocumentedEmptyBlock) != 0) {
- this.scope.problemReporter().undocumentedEmptyBlock(this.bodyStart-1, this.bodyEnd);
- }
-
- // generics (and non static generic members) cannot extend Throwable
- if (sourceType.findSuperTypeErasingTo(TypeIds.T_JavaLangThrowable, true) != null) {
- ReferenceBinding current = sourceType;
- checkEnclosedInGeneric : do {
- if (current.isStatic()) break checkEnclosedInGeneric;
- if (current.isLocalType()) {
- NestedTypeBinding nestedType = (NestedTypeBinding) current;
- if (nestedType.scope.methodScope().isStatic) break checkEnclosedInGeneric;
- }
- } while ((current = current.enclosingType()) != null);
- }
- this.maxFieldCount = 0;
- int lastVisibleFieldID = -1;
-
- if (this.memberTypes != null) {
- for (int i = 0, count = this.memberTypes.length; i < count; i++) {
- this.memberTypes[i].resolve(this.scope);
- }
- }
- if (this.fields != null) {
- for (int i = 0, count = this.fields.length; i < count; i++) {
- FieldDeclaration field = this.fields[i];
- switch(field.getKind()) {
- case AbstractVariableDeclaration.FIELD:
- FieldBinding fieldBinding = field.binding;
- if (fieldBinding == null) {
- // still discover secondary errors
- if (field.initialization != null) field.initialization.resolve(field.isStatic() ? this.staticInitializerScope : this.initializerScope);
- this.ignoreFurtherInvestigation = true;
- continue;
- }
- this.maxFieldCount++;
- lastVisibleFieldID = field.binding.id;
- break;
-
- case AbstractVariableDeclaration.INITIALIZER:
- ((Initializer) field).lastVisibleFieldID = lastVisibleFieldID + 1;
- break;
- }
- field.resolve(field.isStatic() ? this.staticInitializerScope : this.initializerScope);
- }
- }
-
- if (this.methods != null) {
- for (int i = 0, count = this.methods.length; i < count; i++) {
- this.methods[i].resolve(this.scope);
- }
- }
- // Resolve javadoc
- if (this.javadoc != null) {
- if (this.scope != null && (this.name != TypeConstants.PACKAGE_INFO_NAME)) {
- // if the type is package-info, the javadoc was resolved as part of the compilation unit javadoc
- this.javadoc.resolve(this.scope);
- }
- } else if (sourceType != null && !sourceType.isLocalType()) {
- this.scope.problemReporter().javadocMissing(this.sourceStart, this.sourceEnd, sourceType.modifiers);
- }
-
- } catch (AbortType e) {
- this.ignoreFurtherInvestigation = true;
- return;
- }
-}
-
-/**
- * Resolve a local type declaration
- */
-public void resolve(BlockScope blockScope) {
-
- // need to build its scope first and proceed with binding's creation
- if ((this.bits & ASTNode.IsAnonymousType) == 0) {
- // check collision scenarii
- blockScope.addLocalType(this);
- }
-
- if (this.binding != null) {
- // remember local types binding for innerclass emulation propagation
- blockScope.referenceCompilationUnit().record((LocalTypeBinding)this.binding);
-
- // binding is not set if the receiver could not be created
- resolve();
- updateMaxFieldCount();
- }
-}
-
-/**
- * Resolve a member type declaration (can be a local member)
- */
-public void resolve(ClassScope upperScope) {
- // member scopes are already created
- // request the construction of a binding if local member type
-
- if (this.binding != null && this.binding instanceof LocalTypeBinding) {
- // remember local types binding for innerclass emulation propagation
- upperScope.referenceCompilationUnit().record((LocalTypeBinding)this.binding);
- }
- resolve();
- updateMaxFieldCount();
-}
-
-/**
- * Resolve a top level type declaration
- */
-public void resolve(CompilationUnitScope upperScope) {
- // top level : scope are already created
- resolve();
- updateMaxFieldCount();
-}
-
-public void tagAsHavingErrors() {
- this.ignoreFurtherInvestigation = true;
-}
-
-/**
- * Iteration for a package member type
- *
- */
-public void traverse(ASTVisitor visitor, CompilationUnitScope unitScope) {
-
- if (this.ignoreFurtherInvestigation)
- return;
- try {
- if (visitor.visit(this, unitScope)) {
- if (this.javadoc != null) {
- this.javadoc.traverse(visitor, this.scope);
- }
- if (this.superclass != null)
- this.superclass.traverse(visitor, this.scope);
- if (this.memberTypes != null) {
- int length = this.memberTypes.length;
- for (int i = 0; i < length; i++)
- this.memberTypes[i].traverse(visitor, this.scope);
- }
- if (this.fields != null) {
- int length = this.fields.length;
- for (int i = 0; i < length; i++) {
- FieldDeclaration field;
- if ((field = this.fields[i]).isStatic()) {
- field.traverse(visitor, this.staticInitializerScope);
- } else {
- field.traverse(visitor, this.initializerScope);
- }
- }
- }
- if (this.methods != null) {
- int length = this.methods.length;
- for (int i = 0; i < length; i++)
- this.methods[i].traverse(visitor, this.scope);
- }
- }
- visitor.endVisit(this, unitScope);
- } catch (AbortType e) {
- // silent abort
- }
-}
-
-/**
- * Iteration for a local innertype
- */
-public void traverse(ASTVisitor visitor, BlockScope blockScope) {
- if (this.ignoreFurtherInvestigation)
- return;
- try {
- if (visitor.visit(this, blockScope)) {
- if (this.javadoc != null) {
- this.javadoc.traverse(visitor, this.scope);
- }
- if (this.superclass != null)
- this.superclass.traverse(visitor, this.scope);
- if (this.memberTypes != null) {
- int length = this.memberTypes.length;
- for (int i = 0; i < length; i++)
- this.memberTypes[i].traverse(visitor, this.scope);
- }
- if (this.fields != null) {
- int length = this.fields.length;
- for (int i = 0; i < length; i++) {
- FieldDeclaration field;
- if ((field = this.fields[i]).isStatic()) {
- // local type cannot have static fields
- } else {
- field.traverse(visitor, this.initializerScope);
- }
- }
- }
- if (this.methods != null) {
- int length = this.methods.length;
- for (int i = 0; i < length; i++)
- this.methods[i].traverse(visitor, this.scope);
- }
- }
- visitor.endVisit(this, blockScope);
- } catch (AbortType e) {
- // silent abort
- }
-}
-
-/**
- * Iteration for a member innertype
- *
- */
-public void traverse(ASTVisitor visitor, ClassScope classScope) {
- if (this.ignoreFurtherInvestigation)
- return;
- try {
- if (visitor.visit(this, classScope)) {
- if (this.javadoc != null) {
- this.javadoc.traverse(visitor, scope);
- }
- if (this.superclass != null)
- this.superclass.traverse(visitor, this.scope);
- if (this.memberTypes != null) {
- int length = this.memberTypes.length;
- for (int i = 0; i < length; i++)
- this.memberTypes[i].traverse(visitor, this.scope);
- }
- if (this.fields != null) {
- int length = this.fields.length;
- for (int i = 0; i < length; i++) {
- FieldDeclaration field;
- if ((field = this.fields[i]).isStatic()) {
- field.traverse(visitor, this.staticInitializerScope);
- } else {
- field.traverse(visitor, this.initializerScope);
- }
- }
- }
- if (this.methods != null) {
- int length = this.methods.length;
- for (int i = 0; i < length; i++)
- this.methods[i].traverse(visitor, this.scope);
- }
- }
- visitor.endVisit(this, classScope);
- } catch (AbortType e) {
- // silent abort
- }
-}
-
-/**
- * MaxFieldCount's computation is necessary so as to reserve space for
- * the flow info field portions. It corresponds to the maximum amount of
- * fields this class or one of its innertypes have.
- *
- * During name resolution, types are traversed, and the max field count is recorded
- * on the outermost type. It is then propagated down during the flow analysis.
- *
- * This method is doing either up/down propagation.
- */
-void updateMaxFieldCount() {
- if (this.binding == null)
- return; // error scenario
- TypeDeclaration outerMostType = this.scope.outerMostClassScope().referenceType();
- if (this.maxFieldCount > outerMostType.maxFieldCount) {
- outerMostType.maxFieldCount = this.maxFieldCount; // up
- } else {
- this.maxFieldCount = outerMostType.maxFieldCount; // down
- }
-}
-
-/**
- * Returns whether the type is a secondary one or not.
- */
-public boolean isSecondary() {
- return (this.bits & ASTNode.IsSecondaryType) != 0;
-}
-public int getASTType() {
- return IASTNode.TYPE_DECLARATION;
-
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/TypeReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/TypeReference.java
deleted file mode 100644
index ef7b259a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/TypeReference.java
+++ /dev/null
@@ -1,179 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.ITypeReference;
-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;
-import org.eclipse.wst.jsdt.internal.compiler.impl.Constant;
-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.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.lookup.TypeIds;
-
-public abstract class TypeReference extends Expression implements ITypeReference {
-
-public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {
- return flowInfo;
-}
-
-// allows us to trap completion & selection nodes
-public void aboutToResolve(Scope scope) {
- // default implementation: do nothing
-}
-/*
- * Answer a base type reference (can be an array of base type).
- */
-public static final TypeReference baseTypeReference(int baseType, int dim) {
-
- if (dim == 0) {
- switch (baseType) {
- case (TypeIds.T_void) :
- return new SingleTypeReference(TypeBinding.VOID.simpleName, 0);
- case (TypeIds.T_boolean) :
- return new SingleTypeReference(TypeBinding.BOOLEAN.simpleName, 0);
- case (TypeIds.T_char) :
- return new SingleTypeReference(TypeBinding.CHAR.simpleName, 0);
- case (TypeIds.T_float) :
- return new SingleTypeReference(TypeBinding.FLOAT.simpleName, 0);
- case (TypeIds.T_double) :
- return new SingleTypeReference(TypeBinding.DOUBLE.simpleName, 0);
- case (TypeIds.T_short) :
- return new SingleTypeReference(TypeBinding.SHORT.simpleName, 0);
- case (TypeIds.T_int) :
- return new SingleTypeReference(TypeBinding.INT.simpleName, 0);
- default : //T_long
- return new SingleTypeReference(TypeBinding.LONG.simpleName, 0);
- }
- }
- switch (baseType) {
- case (TypeIds.T_void) :
- return new ArrayTypeReference(TypeBinding.VOID.simpleName, dim, 0);
- case (TypeIds.T_boolean) :
- return new ArrayTypeReference(TypeBinding.BOOLEAN.simpleName, dim, 0);
- case (TypeIds.T_char) :
- return new ArrayTypeReference(TypeBinding.CHAR.simpleName, dim, 0);
- case (TypeIds.T_float) :
- return new ArrayTypeReference(TypeBinding.FLOAT.simpleName, dim, 0);
- case (TypeIds.T_double) :
- return new ArrayTypeReference(TypeBinding.DOUBLE.simpleName, dim, 0);
- case (TypeIds.T_short) :
- return new ArrayTypeReference(TypeBinding.SHORT.simpleName, dim, 0);
- case (TypeIds.T_int) :
- return new ArrayTypeReference(TypeBinding.INT.simpleName, dim, 0);
- default : //T_long
- return new ArrayTypeReference(TypeBinding.LONG.simpleName, dim, 0);
- }
-}
-
-public abstract TypeReference copyDims(int dim);
-public int dimensions() {
- return 0;
-}
-
-public abstract char[] getLastToken();
-
-protected abstract TypeBinding getTypeBinding(Scope scope);
-/**
- * @return char[][]
- */
-public abstract char [][] getTypeName() ;
-
-public char[] getSimpleTypeName()
-{
- char[][] typeName = getTypeName();
- return typeName[typeName.length-1];
-}
-
-public char[] getFullTypeName() {
- char[][] typeName = getTypeName();
- return CharOperation.concatWith(typeName, '.');
-}
-
-public boolean isTypeReference() {
- return true;
-}
-public TypeBinding resolveSuperType(ClassScope scope) {
- // assumes the implementation of resolveType(ClassScope) will call back to detect cycles
- if (resolveType(scope) == null) return null;
-
- return this.resolvedType;
-}
-
-public final TypeBinding resolveType(BlockScope blockScope) {
- return resolveType(blockScope, true /* checkbounds if any */);
-}
-
-public TypeBinding resolveType(BlockScope scope, boolean checkBounds) {
- // handle the error here
- this.constant = Constant.NotAConstant;
- if (this.resolvedType != null) // is a shared type reference which was already resolved
- return this.resolvedType.isValidBinding() ? this.resolvedType : null; // already reported error
-
- TypeBinding type = this.resolvedType = getTypeBinding(scope);
- if (type == null)
- return null; // detected cycle while resolving hierarchy
- if (!type.isValidBinding()) {
- reportInvalidType(scope);
- return null;
- }
-
- if (isTypeUseDeprecated(type, scope))
- reportDeprecatedType(type, scope);
-
- return this.resolvedType = type;
-}
-public TypeBinding resolveType(ClassScope scope) {
- // handle the error here
- this.constant = Constant.NotAConstant;
- if (this.resolvedType != null) // is a shared type reference which was already resolved
- return this.resolvedType.isValidBinding() ? this.resolvedType : null; // already reported error
-
- TypeBinding type = this.resolvedType = getTypeBinding(scope);
- if (type == null)
- return null; // detected cycle while resolving hierarchy
- if (!type.isValidBinding()) {
- reportInvalidType(scope);
- return null;
- }
- if (isTypeUseDeprecated(type, scope))
- reportDeprecatedType(type, scope);
-
- return this.resolvedType = type;
-}
-
-public TypeBinding resolveTypeArgument(BlockScope blockScope, ReferenceBinding genericType, int rank) {
- return resolveType(blockScope, true /* check bounds*/);
-}
-
-public TypeBinding resolveTypeArgument(ClassScope classScope, ReferenceBinding genericType, int rank) {
- return resolveType(classScope);
-}
-
-protected void reportInvalidType(Scope scope) {
- scope.problemReporter().invalidType(this, this.resolvedType);
-}
-protected void reportDeprecatedType(TypeBinding type, Scope scope) {
- scope.problemReporter().deprecatedType(type, this);
-}
-public abstract void traverse(ASTVisitor visitor, BlockScope scope);
-public abstract void traverse(ASTVisitor visitor, ClassScope scope);
-
-public int getASTType() {
- return IASTNode.TYPE_REFERENCE;
-
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/UnaryExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/UnaryExpression.java
deleted file mode 100644
index 8c780e27..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/UnaryExpression.java
+++ /dev/null
@@ -1,171 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-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.IUnaryExpression;
-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;
-import org.eclipse.wst.jsdt.internal.compiler.impl.BooleanConstant;
-import org.eclipse.wst.jsdt.internal.compiler.impl.Constant;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class UnaryExpression extends OperatorExpression implements IUnaryExpression {
-
- public Expression expression;
- public Constant optimizedBooleanConstant;
-
- public UnaryExpression(Expression expression, int operator) {
- this.expression = expression;
- this.bits |= operator << OperatorSHIFT; // encode operator
- }
-
- public FlowInfo analyseCode( BlockScope currentScope, FlowContext flowContext,
- FlowInfo flowInfo) {
- this.expression.checkNPE(currentScope, flowContext, flowInfo);
- if (((bits & OperatorMASK) >> OperatorSHIFT) == NOT) {
- return this.expression.analyseCode(currentScope, flowContext, flowInfo).
- asNegatedCondition();
- } else {
- return this.expression.analyseCode(currentScope, flowContext, flowInfo);
- }
- }
-
- public Constant optimizedBooleanConstant() {
- return this.optimizedBooleanConstant == null
- ? this.constant == null ? Constant.NotAConstant : this.constant
- : this.optimizedBooleanConstant;
- }
-
- public StringBuffer printExpressionNoParenthesis(int indent, StringBuffer output) {
-
- output.append(operatorToString()).append(' ');
- return this.expression.printExpression(0, output);
- }
-
- public final int getOperator() {
- return (bits & OperatorMASK) >> OperatorSHIFT;
- }
-
- public TypeBinding resolveType(BlockScope scope) {
- TypeBinding expressionType = null;
- if (getOperator()==TYPEOF && (this.expression instanceof SingleNameReference))
- expressionType=TypeBinding.UNKNOWN;
- else
- expressionType = this.expression.resolveType(scope);
- if (expressionType == null) {
- this.constant = Constant.NotAConstant;
- return null;
- }
- int expressionTypeID = expressionType.id;
-
- if (expressionTypeID > 15) {
- expressionTypeID=T_JavaLangObject;
-// this.constant = Constant.NotAConstant;
-// scope.problemReporter().invalidOperator(this, expressionType);
-// return null;
- }
-
- int tableId=-1;
- int operator = (bits & OperatorMASK) >> OperatorSHIFT;
- switch (operator) {
- case NOT :
- this.resolvedType= TypeBinding.BOOLEAN;
- break;
- case TWIDDLE :
- tableId = LEFT_SHIFT;
- break;
- case TYPEOF :
- this.resolvedType= scope.getJavaLangString();
- break;
- case OperatorIds.VOID :
- this.resolvedType= TypeBinding.VOID;
- break;
- default :
- tableId = MINUS;
- } //+ and - cases
-
- // the code is an int
- // (cast) left Op (cast) rigth --> result
- // 0000 0000 0000 0000 0000
- // <<16 <<12 <<8 <<4 <<0
- if (tableId>-1) // not already determined
- {
- int operatorSignature = OperatorSignatures[tableId][(expressionTypeID << 4) + expressionTypeID];
- this.bits |= operatorSignature & 0xF;
- switch (operatorSignature & 0xF) { // only switch on possible result type.....
- case T_boolean :
- this.resolvedType = TypeBinding.BOOLEAN;
- break;
- case T_char :
- this.resolvedType = TypeBinding.CHAR;
- break;
- case T_double :
- this.resolvedType = TypeBinding.DOUBLE;
- break;
- case T_float :
- this.resolvedType = TypeBinding.FLOAT;
- break;
- case T_int :
- this.resolvedType = scope.getJavaLangNumber();
- break;
- case T_long :
- this.resolvedType = TypeBinding.LONG;
- break;
- case T_any :
- this.resolvedType = TypeBinding.UNKNOWN;
- break;
- default : //error........
- this.constant = Constant.NotAConstant;
- if (expressionTypeID != T_undefined)
- scope.problemReporter().invalidOperator(this, expressionType);
- return null;
- }
- }
- // compute the constant when valid
- if (this.expression.constant != Constant.NotAConstant) {
- this.constant =
- Constant.computeConstantOperation(
- this.expression.constant,
- expressionTypeID,
- operator);
- } else {
- this.constant = Constant.NotAConstant;
- if (operator == NOT) {
- Constant cst = expression.optimizedBooleanConstant();
- if (cst != Constant.NotAConstant)
- this.optimizedBooleanConstant = BooleanConstant.fromValue(!cst.booleanValue());
- }
- }
- return this.resolvedType;
- }
-
- public void traverse(
- ASTVisitor visitor,
- BlockScope blockScope) {
-
- if (visitor.visit(this, blockScope)) {
- this.expression.traverse(visitor, blockScope);
- }
- visitor.endVisit(this, blockScope);
- }
-
- public int getASTType() {
- return IASTNode.UNARY_EXPRESSION;
- }
-
- public IExpression getExpression() {
- return expression;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/UndefinedLiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/UndefinedLiteral.java
deleted file mode 100644
index e7f66b23..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/UndefinedLiteral.java
+++ /dev/null
@@ -1,57 +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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IUndefinedLiteral;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-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.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class UndefinedLiteral extends MagicLiteral implements IUndefinedLiteral {
-
- static final char[] source = {'u' , 'n' , 'd' , 'e', 'f', 'i', 'n', 'e', 'd'};
-
- public UndefinedLiteral(int s , int e) {
- super(s,e);
- }
-
- public void computeConstant() {
- constant = Constant.NotAConstant;
- }
-
- public TypeBinding literalType(BlockScope scope) {
- return TypeBinding.UNDEFINED;
- }
-
- public int nullStatus(FlowInfo flowInfo) {
- return FlowInfo.NULL;
- }
-
- public Object reusableJSRTarget() {
- return TypeBinding.UNDEFINED;
- }
-
- public char[] source() {
- return source;
- }
-
- public void traverse(ASTVisitor visitor, BlockScope scope) {
- visitor.visit(this, scope);
- visitor.endVisit(this, scope);
- }
-
- public int getASTType() {
- return IASTNode.UNDEFINED_LITERAL;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/WhileStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/WhileStatement.java
deleted file mode 100644
index 4d1de1d5..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/WhileStatement.java
+++ /dev/null
@@ -1,160 +0,0 @@
-/*******************************************************************************
- * 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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IWhileStatement;
-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.flow.LoopingFlowContext;
-import org.eclipse.wst.jsdt.internal.compiler.impl.Constant;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class WhileStatement extends Statement implements IWhileStatement {
-
- public Expression condition;
- public Statement action;
-
- public WhileStatement(Expression condition, Statement action, int s, int e) {
- this.condition = condition;
- this.action = action;
- // remember useful empty statement
- if (action instanceof EmptyStatement) action.bits |= IsUsefulEmptyStatement;
- sourceStart = s;
- sourceEnd = e;
- }
-
- public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext,
- FlowInfo flowInfo) {
-
- Constant cst = this.condition.constant;
- boolean isConditionTrue = cst == null ? false : cst != Constant.NotAConstant && cst.booleanValue() == true;
- boolean isConditionFalse = cst == null ? false : cst != Constant.NotAConstant && cst.booleanValue() == false;
-
- cst = this.condition.optimizedBooleanConstant();
- boolean isConditionOptimizedTrue = cst == null ? false : cst != Constant.NotAConstant && cst.booleanValue() == true;
- boolean isConditionOptimizedFalse = cst == null ? false : cst != Constant.NotAConstant && cst.booleanValue() == false;
-
- LoopingFlowContext condLoopContext;
- FlowInfo condInfo = flowInfo.nullInfoLessUnconditionalCopy();
- // we need to collect the contribution to nulls of the coming paths through the
- // loop, be they falling through normally or branched to break, continue labels
- // or catch blocks
- condInfo = this.condition.analyseCode(
- currentScope,
- (condLoopContext =
- new LoopingFlowContext(flowContext, flowInfo, this, currentScope)),
- condInfo);
-
- LoopingFlowContext loopingContext;
- FlowInfo actionInfo;
- FlowInfo exitBranch;
- if (action == null
- || (action.isEmptyBlock() && currentScope.compilerOptions().complianceLevel <= ClassFileConstants.JDK1_3)) {
- condLoopContext.complainOnDeferredNullChecks(currentScope,
- condInfo.unconditionalInits());
- if (isConditionTrue) {
- return FlowInfo.DEAD_END;
- } else {
- FlowInfo mergedInfo = flowInfo.copy().addInitializationsFrom(condInfo.initsWhenFalse());
- if (isConditionOptimizedTrue){
- mergedInfo.setReachMode(FlowInfo.UNREACHABLE);
- }
- return mergedInfo;
- }
- } else {
- // in case the condition was inlined to false, record the fact that there is no way to reach any
- // statement inside the looping action
- loopingContext =
- new LoopingFlowContext(
- flowContext,
- flowInfo,
- this,
- currentScope);
- if (isConditionFalse) {
- actionInfo = FlowInfo.DEAD_END;
- } else {
- actionInfo = condInfo.initsWhenTrue().copy();
- if (isConditionOptimizedFalse){
- actionInfo.setReachMode(FlowInfo.UNREACHABLE);
- }
- }
-
- if (!this.action.complainIfUnreachable(actionInfo, currentScope, false)) {
- actionInfo = this.action.analyseCode(currentScope, loopingContext, actionInfo);
- }
-
- // code generation can be optimized when no need to continue in the loop
- exitBranch = flowInfo.copy();
- // need to start over from flowInfo so as to get null inits
-
- if ((actionInfo.tagBits &
- loopingContext.initsOnContinue.tagBits &
- FlowInfo.UNREACHABLE) != 0) {
- exitBranch.addInitializationsFrom(condInfo.initsWhenFalse());
- } else {
- actionInfo = actionInfo.mergedWith(loopingContext.initsOnContinue.unconditionalInits());
- condLoopContext.complainOnDeferredNullChecks(currentScope,
- actionInfo);
- loopingContext.complainOnDeferredNullChecks(currentScope,
- actionInfo);
- exitBranch.
- addPotentialInitializationsFrom(
- actionInfo.unconditionalInits()).
- addInitializationsFrom(condInfo.initsWhenFalse());
- }
- }
-
- // end of loop
- FlowInfo mergedInfo = FlowInfo.mergedOptimizedBranches(
- (loopingContext.initsOnBreak.tagBits &
- FlowInfo.UNREACHABLE) != 0 ?
- loopingContext.initsOnBreak :
- flowInfo.addInitializationsFrom(loopingContext.initsOnBreak), // recover upstream null info
- isConditionOptimizedTrue,
- exitBranch,
- isConditionOptimizedFalse,
- !isConditionTrue /*while(true); unreachable(); */);
- return mergedInfo;
- }
-
- public void resolve(BlockScope scope) {
- condition.resolveTypeExpecting(scope, TypeBinding.BOOLEAN);
- if (action != null)
- action.resolve(scope);
- }
-
- public StringBuffer printStatement(int tab, StringBuffer output) {
- printIndent(tab, output).append("while ("); //$NON-NLS-1$
- condition.printExpression(0, output).append(')');
- if (action == null)
- output.append(';');
- else
- action.printStatement(tab + 1, output);
- return output;
- }
-
- public void traverse( ASTVisitor visitor, BlockScope blockScope) {
- if (visitor.visit(this, blockScope)) {
- condition.traverse(visitor, blockScope);
- if (action != null)
- action.traverse(visitor, blockScope);
- }
- visitor.endVisit(this, blockScope);
- }
-
- public int getASTType() {
- return IASTNode.WHILE_STATEMENT;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/WithStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/WithStatement.java
deleted file mode 100644
index f69cd6d5..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/WithStatement.java
+++ /dev/null
@@ -1,87 +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.compiler.ast;
-
-import org.eclipse.wst.jsdt.core.ast.IASTNode;
-import org.eclipse.wst.jsdt.core.ast.IWithStatement;
-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;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.WithScope;
-
-public class WithStatement extends Statement implements IWithStatement {
-
- public Expression condition;
- public Statement action;
-
- public WithStatement(Expression condition, Statement action, int s, int e) {
- this.condition = condition;
- this.action = action;
- // remember useful empty statement
- if (action instanceof EmptyStatement) action.bits |= IsUsefulEmptyStatement;
- sourceStart = s;
- sourceEnd = e;
- }
-
- public FlowInfo analyseCode( BlockScope currentScope, FlowContext flowContext,
- FlowInfo flowInfo) {
-
- flowInfo =
- condition.analyseCode(currentScope, flowContext, flowInfo);
-
- if (this.action != null) {
- if (!action.complainIfUnreachable(flowInfo, currentScope, false)) {
- flowInfo =
- this.action.analyseCode(currentScope, flowContext, flowInfo);
- }
- }
- return flowInfo;
- }
-
- public void resolve(BlockScope parentScope) {
-
- TypeBinding type = condition.resolveTypeExpecting(parentScope, TypeBinding.ANY);
- BlockScope scope = (type instanceof ReferenceBinding)?
- new WithScope(parentScope,(ReferenceBinding)type) : parentScope;
- if (action != null)
- action.resolve(scope);
- }
-
- public StringBuffer printStatement(int tab, StringBuffer output) {
-
- printIndent(tab, output).append("with ("); //$NON-NLS-1$
- condition.printExpression(0, output).append(")\n"); //$NON-NLS-1$
- if (action == null)
- output.append(';');
- else
- action.printStatement(tab + 1, output);
- return output;
- }
-
- public void traverse(
- ASTVisitor visitor,
- BlockScope blockScope) {
-
- if (visitor.visit(this, blockScope)) {
- condition.traverse(visitor, blockScope);
- if (action != null)
- action.traverse(visitor, blockScope);
- }
- visitor.endVisit(this, blockScope);
- }
-
- public int getASTType() {
- return IASTNode.WITH_STATEMENT;
- }
-}
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
deleted file mode 100644
index e1080b4f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/batch/ClasspathFile.java
+++ /dev/null
@@ -1,158 +0,0 @@
-/*******************************************************************************
- * 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.compiler.batch;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.Hashtable;
-
-import org.eclipse.wst.jsdt.core.UnimplementedException;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-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;
-import org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.env.AccessRuleSet;
-import org.eclipse.wst.jsdt.internal.compiler.env.NameEnvironmentAnswer;
-import org.eclipse.wst.jsdt.internal.compiler.impl.ITypeRequestor;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Binding;
-import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfObject;
-
-public class ClasspathFile extends ClasspathLocation {
-
-protected File file;
-protected Hashtable packageCache;
-String packageName;
-protected char[] normalizedPath;
-String encoding;
-HashtableOfObject definedItems[] = new HashtableOfObject[Binding.NUMBER_BASIC_BINDING];
-
-NameEnvironmentAnswer foundAnswer;
-
-public ClasspathFile(File file, String encoding,
- AccessRuleSet accessRuleSet, String destinationPath) {
- super(accessRuleSet,destinationPath);
- this.file = file;
- this.packageName=file.getName();
- this.encoding=encoding;
-}
-
-public NameEnvironmentAnswer findBinding(char[] typeName, String qualifiedPackageName, int type, ITypeRequestor requestor) {
-// if (!qualifiedPackageName.equals(this.packageName))
- // return null;
- if (foundAnswer==null)
- {
- parseFile(requestor);
- }
- NameEnvironmentAnswer answer=null;
- if ((type&(Binding.VARIABLE|Binding.FIELD))!=0)
- {
- answer= (NameEnvironmentAnswer)definedItems[Binding.VARIABLE|Binding.FIELD].get(typeName);
- if (answer!=null)
- return answer;
- }
- if ((type&Binding.TYPE)!=0)
- {
- answer= (NameEnvironmentAnswer)definedItems[Binding.TYPE].get(typeName);
- if (answer!=null)
- return answer;
- }
- if ((type&Binding.METHOD)!=0)
- {
- answer= (NameEnvironmentAnswer)definedItems[Binding.METHOD].get(typeName);
- if (answer!=null)
- return answer;
- }
- return null;
- }
-
-private void parseFile(ITypeRequestor requestor) {
- CompilationUnit compilationUnit = new CompilationUnit(null,
- file.getAbsolutePath(), this.encoding);
- compilationUnit.packageName=new char [][]{packageName.toCharArray()};
- for (int i = 0; i < definedItems.length; i++) {
- definedItems[i]=new HashtableOfObject();
- }
-
-
- foundAnswer =
- new NameEnvironmentAnswer(compilationUnit,
- fetchAccessRestriction(file.getAbsolutePath()));
-
- if (requestor!=null)
- {
- CompilationUnitDeclaration declaration = requestor.doParse(compilationUnit,null);
- 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);
- }
- else if (declaration.statements[i] instanceof AbstractVariableDeclaration) {
- AbstractVariableDeclaration var = (AbstractVariableDeclaration) declaration.statements[i];
- definedItems[Binding.VARIABLE].put(var.name, foundAnswer);
-
- }
- }
- for (int inx=0;inx<declaration.numberInferredTypes;inx++) {
- InferredType inferredType = declaration.inferredTypes[inx];
- if (inferredType.isDefinition && !inferredType.isEmptyGlobal())
- definedItems[Binding.TYPE].put(inferredType.getName(), foundAnswer);
- }
-
- }
- else
- //TODO: implement
- throw new org.eclipse.wst.jsdt.core.UnimplementedException();
-
-}
-
-public NameEnvironmentAnswer findClass(char[] typeName, String qualifiedPackageName, String qualifiedBinaryFileName) {
- return findClass(typeName,qualifiedPackageName,qualifiedBinaryFileName,false);
-}
-public NameEnvironmentAnswer findClass(char[] typeName,
- String qualifiedPackageName, String qualifiedBinaryFileName,
- boolean asBinaryOnly) {
- if (!isPackage(qualifiedPackageName))
- return null; // most common case
- throw new org.eclipse.wst.jsdt.core.UnimplementedException();
-
-// return null;
-}
-public void initialize() throws IOException {
-}
-public boolean isPackage(String qualifiedPackageName) {
- return packageName.equals(qualifiedPackageName);
-}
-public void reset() {
-
- this.packageCache = null;
-}
-public String toString() {
- return "Classpath for file " + this.file.getPath(); //$NON-NLS-1$
-}
-public char[] normalizedPath() {
- if (this.normalizedPath == null) {
- char[] rawName = this.file.getPath().toCharArray();
- if (File.separatorChar == '\\') {
- CharOperation.replace(rawName, '\\', '/');
- }
- this.normalizedPath = CharOperation.subarray(rawName, 0, CharOperation.lastIndexOf('.', rawName));
- }
- return this.normalizedPath;
-}
-public String getPath(){
- return this.file.getPath();
-}
-
-public char[][][] findTypeNames(String qualifiedPackageName) {
- throw new UnimplementedException("implement"); //$NON-NLS-1$
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/batch/ClasspathLocation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/batch/ClasspathLocation.java
deleted file mode 100644
index c7c2f8b5..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/batch/ClasspathLocation.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*******************************************************************************
- * 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.compiler.batch;
-
-import java.io.File;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-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.util.SuffixConstants;
-
-public abstract class ClasspathLocation implements FileSystem.Classpath,
- SuffixConstants {
-
- public static final int SOURCE = 1;
- public static final int BINARY = 2;
-
- public AccessRuleSet accessRuleSet;
-
- public String destinationPath;
- // destination path for compilation units that are reached through this
- // classpath location; the coding is consistent with the one of
- // Main.destinationPath:
- // == null: unspecified, use whatever value is set by the enclosing
- // context, id est Main;
- // == Main.NONE: absorbent element, do not output class files;
- // else: use as the path of the directory into which class files must
- // be written.
- // potentially carried by any entry that contains to be compiled files
-
- protected ClasspathLocation(AccessRuleSet accessRuleSet,
- String destinationPath) {
- this.accessRuleSet = accessRuleSet;
- this.destinationPath = destinationPath;
- }
-
- /**
- * Return the first access rule which is violated when accessing a given
- * type, or null if no 'non accessible' access rule applies.
- *
- * @param qualifiedBinaryFileName
- * tested type specification, formed as:
- * "org/eclipse/jdt/core/JavaScriptCore.class"; on systems that
- * use \ as File.separator, the
- * "org\eclipse\jdt\core\JavaScriptCore.class" is accepted as well
- * @return the first access rule which is violated when accessing a given
- * type, or null if none applies
- */
- protected AccessRestriction fetchAccessRestriction(String qualifiedBinaryFileName) {
- if (this.accessRuleSet == null)
- return null;
- char [] qualifiedTypeName = qualifiedBinaryFileName.
- substring(0, qualifiedBinaryFileName.length() - SUFFIX_java.length)
- .toCharArray();
- if (File.separatorChar == '\\') {
- CharOperation.replace(qualifiedTypeName, File.separatorChar, '/');
- }
- return this.accessRuleSet.getViolatedRestriction(qualifiedTypeName);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/batch/ClasspathMetadataFile.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/batch/ClasspathMetadataFile.java
deleted file mode 100644
index d9bd4de8..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/batch/ClasspathMetadataFile.java
+++ /dev/null
@@ -1,127 +0,0 @@
-/*******************************************************************************
- * 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.compiler.batch;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.Hashtable;
-
-import org.eclipse.wst.jsdt.core.UnimplementedException;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.env.AccessRuleSet;
-import org.eclipse.wst.jsdt.internal.compiler.env.NameEnvironmentAnswer;
-import org.eclipse.wst.jsdt.internal.compiler.impl.ITypeRequestor;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Binding;
-import org.eclipse.wst.jsdt.internal.oaametadata.LibraryAPIs;
-import org.eclipse.wst.jsdt.internal.oaametadata.MetadataReader;
-
-public class ClasspathMetadataFile extends ClasspathLocation {
-
-protected File file;
-protected Hashtable packageCache;
-String packageName;
-protected char[] normalizedPath;
-String encoding;
-LibraryAPIs apis;
-
-NameEnvironmentAnswer foundAnswer;
-
-public ClasspathMetadataFile(File file, String encoding,
- AccessRuleSet accessRuleSet, String destinationPath) {
- super(accessRuleSet,destinationPath);
- this.file = file;
- this.packageName=file.getName();
- this.encoding=encoding;
-}
-
-public NameEnvironmentAnswer findBinding(char[] typeName, String qualifiedPackageName, int type, ITypeRequestor requestor) {
-// if (!qualifiedPackageName.equals(this.packageName))
- // return null;
- if (foundAnswer==null)
- {
- parseFile(requestor);
- }
- if (this.apis==null)
- return null;
- String name = new String(typeName);
- if ((type&(Binding.VARIABLE|Binding.FIELD))!=0)
- {
- if (this.apis.getGlobalVar(name)!=null)
- return foundAnswer;
- }
- if ((type&Binding.TYPE)!=0)
- {
- if (this.apis.getClass(name)!=null)
- return foundAnswer;
- }
- if ((type&Binding.METHOD)!=0)
- {
- if (this.apis.getGlobalMethod(name)!=null)
- return foundAnswer;
- }
- return null;
- }
-
-private void parseFile(ITypeRequestor requestor) {
- CompilationUnit compilationUnit = new CompilationUnit(null,
- file.getAbsolutePath(), this.encoding);
- compilationUnit.packageName=new char [][]{packageName.toCharArray()};
-
-
-
- apis=MetadataReader.readAPIsFromFile(this.file.getAbsolutePath());
- foundAnswer =
- new NameEnvironmentAnswer(apis);
-
-}
-
-public NameEnvironmentAnswer findClass(char[] typeName, String qualifiedPackageName, String qualifiedBinaryFileName) {
- return findClass(typeName,qualifiedPackageName,qualifiedBinaryFileName,false);
-}
-public NameEnvironmentAnswer findClass(char[] typeName,
- String qualifiedPackageName, String qualifiedBinaryFileName,
- boolean asBinaryOnly) {
- if (!isPackage(qualifiedPackageName))
- return null; // most common case
- throw new org.eclipse.wst.jsdt.core.UnimplementedException();
-
-// return null;
-}
-public void initialize() throws IOException {
-}
-public boolean isPackage(String qualifiedPackageName) {
- return packageName.equals(qualifiedPackageName);
-}
-public void reset() {
-
- this.packageCache = null;
-}
-public String toString() {
- return "Classpath for file " + this.file.getPath(); //$NON-NLS-1$
-}
-public char[] normalizedPath() {
- if (this.normalizedPath == null) {
- char[] rawName = this.file.getPath().toCharArray();
- if (File.separatorChar == '\\') {
- CharOperation.replace(rawName, '\\', '/');
- }
- this.normalizedPath = CharOperation.subarray(rawName, 0, CharOperation.lastIndexOf('.', rawName));
- }
- return this.normalizedPath;
-}
-public String getPath(){
- return this.file.getPath();
-}
-
-public char[][][] findTypeNames(String qualifiedPackageName) {
- throw new UnimplementedException("implement"); //$NON-NLS-1$
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/batch/CompilationUnit.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/batch/CompilationUnit.java
deleted file mode 100644
index 667ba8d8..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/batch/CompilationUnit.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.batch;
-
-import java.io.File;
-import java.io.IOException;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.LibrarySuperType;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit;
-import org.eclipse.wst.jsdt.internal.compiler.problem.AbortCompilationUnit;
-import org.eclipse.wst.jsdt.internal.compiler.util.Util;
-
-public class CompilationUnit implements ICompilationUnit {
- public char[] contents;
- public char[] fileName;
- public char[] mainTypeName;
- String encoding;
- public char[][] packageName;
- public String destinationPath;
- // a specific destination path for this compilation unit; coding is
- // aligned with Main.destinationPath:
- // == null: unspecified, use whatever value is set by the enclosing
- // context, id est Main;
- // == Main.NONE: absorbent element, do not output class files;
- // else: use as the path of the directory into which class files must
- // be written.
-
-public CompilationUnit(char[] contents, String fileName, String encoding) {
- this(contents, fileName, encoding, null);
-}
-public CompilationUnit(char[] contents, String fileName, String encoding,
- String destinationPath) {
- this.contents = contents;
- char[] fileNameCharArray = fileName.toCharArray();
- switch(File.separatorChar) {
- case '/' :
- if (CharOperation.indexOf('\\', fileNameCharArray) != -1) {
- CharOperation.replace(fileNameCharArray, '\\', '/');
- }
- break;
- case '\\' :
- if (CharOperation.indexOf('/', fileNameCharArray) != -1) {
- CharOperation.replace(fileNameCharArray, '/', '\\');
- }
- }
- this.fileName = fileNameCharArray;
- int start = CharOperation.lastIndexOf(File.separatorChar, fileNameCharArray) + 1;
-
- int end = CharOperation.lastIndexOf('.', fileNameCharArray);
- if (end == -1) {
- end = fileNameCharArray.length;
- }
-
- this.mainTypeName = CharOperation.subarray(fileNameCharArray, start, end);
- this.encoding = encoding;
- this.destinationPath = destinationPath;
-}
-public char[] getContents() {
- if (this.contents != null)
- return this.contents; // answer the cached source
-
- // otherwise retrieve it
- try {
- return Util.getFileCharContent(new File(new String(this.fileName)), this.encoding);
- } catch (IOException e) {
- this.contents = CharOperation.NO_CHAR; // assume no source if asked again
- throw new AbortCompilationUnit(null, e, this.encoding);
- }
-}
-/**
- * @see org.eclipse.wst.jsdt.internal.compiler.env.IDependent#getFileName()
- */
-public char[] getFileName() {
- return this.fileName;
-}
-public char[] getMainTypeName() {
- return this.mainTypeName;
-}
-public char[][] getPackageName() {
- return packageName;
-}
-public String toString() {
- return "JavaScriptUnit[" + new String(this.fileName) + "]"; //$NON-NLS-2$ //$NON-NLS-1$
-}
-/* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit#getCommonSuperType()
- */
-public LibrarySuperType getCommonSuperType() {
- // TODO Auto-generated method stub
-// System.out.println("Unimplemented method:JavaScriptUnit.getCommonSuperType"); //$NON-NLS-1$
- // need to set the name of the super type or else we can't resolve global variables
- return new LibrarySuperType("batch", (IJavaScriptProject) null, "Global");
- //return null;
-}
-public String getInferenceID() {
- return null;
-}
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/batch/FileFinder.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/batch/FileFinder.java
deleted file mode 100644
index 302f2021..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/batch/FileFinder.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.batch;
-
-import java.io.File;
-import java.util.ArrayList;
-
-public class FileFinder {
-
-public static String[] find(File f, String pattern) {
- ArrayList files = new ArrayList();
- find0(f, pattern, files);
- String[] result = new String[files.size()];
- files.toArray(result);
- return result;
-}
-private static void find0(File f, String pattern, ArrayList collector) {
- if (f.isDirectory()) {
- String[] files = f.list();
- if (files == null) return;
- for (int i = 0, max = files.length; i < max; i++) {
- File current = new File(f, files[i]);
- if (current.isDirectory()) {
- find0(current, pattern, collector);
- } else {
- if (current.getName().toUpperCase().endsWith(pattern)) {
- collector.add(current.getAbsolutePath());
- }
- }
- }
- }
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/batch/FileSystem.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/batch/FileSystem.java
deleted file mode 100644
index a16c7545..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/batch/FileSystem.java
+++ /dev/null
@@ -1,384 +0,0 @@
-/*******************************************************************************
- * 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.compiler.batch;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.env.AccessRuleSet;
-import org.eclipse.wst.jsdt.internal.compiler.env.INameEnvironment;
-import org.eclipse.wst.jsdt.internal.compiler.env.NameEnvironmentAnswer;
-import org.eclipse.wst.jsdt.internal.compiler.impl.ITypeRequestor;
-import org.eclipse.wst.jsdt.internal.compiler.util.SuffixConstants;
-import org.eclipse.wst.jsdt.internal.compiler.util.Util;
-import org.eclipse.wst.jsdt.internal.oaametadata.IOAAMetaDataConstants;
-
-public class FileSystem implements INameEnvironment, SuffixConstants {
-
- public interface Classpath {
- char[][][] findTypeNames(String qualifiedPackageName);
- NameEnvironmentAnswer findClass(char[] typeName, String qualifiedPackageName, String qualifiedBinaryFileName);
- boolean isPackage(String qualifiedPackageName);
- NameEnvironmentAnswer findBinding(char[] typeName, String qualifiedPackageName, int type, ITypeRequestor requestor);
- NameEnvironmentAnswer findClass(char[] typeName, String qualifiedPackageName, String qualifiedBinaryFileName, boolean asBinaryOnly);
- /**
- * This method resets the environment. The resulting state is equivalent to
- * a new name environment without creating a new object.
- */
- void reset();
- /**
- * Return a normalized path for file based classpath entries. This is an absolute path
- * ending with a file separator for directories, an absolute path deprived from the '.jar'
- * (resp. '.zip') extension for jar (resp. zip) files.
- * @return a normalized path for file based classpath entries
- */
- char[] normalizedPath();
- /**
- * Return the path for file based classpath entries. This is an absolute path
- * ending with a file separator for directories, an absolute path including the '.jar'
- * (resp. '.zip') extension for jar (resp. zip) files.
- * @return the path for file based classpath entries
- */
- String getPath();
- /**
- * Initialize the entry
- */
- void initialize() throws IOException;
- }
- /**
- * This class is defined how to normalize the classpath entries.
- * It removes duplicate entries.
- */
- public static class ClasspathNormalizer {
- /**
- * Returns the normalized classpath entries (no duplicate).
- * <p>The given classpath entries are FileSystem.Classpath. We check the getPath() in order to find
- * duplicate entries.</p>
- *
- * @param classpaths the given classpath entries
- * @return the normalized classpath entries
- */
- public static ArrayList normalize(ArrayList classpaths) {
- ArrayList normalizedClasspath = new ArrayList();
- HashSet cache = new HashSet();
- for (Iterator iterator = classpaths.iterator(); iterator.hasNext(); ) {
- FileSystem.Classpath classpath = (FileSystem.Classpath) iterator.next();
- String path = classpath.getPath();
- if (!cache.contains(path)) {
- normalizedClasspath.add(classpath);
- cache.add(path);
- }
- }
- return normalizedClasspath;
- }
- }
-
- Classpath[] classpaths;
- Set knownFileNames;
-
-/*
- classPathNames is a collection is Strings representing the full path of each class path
- initialFileNames is a collection is Strings, the trailing '.js' will be removed if its not already.
-*/
-public FileSystem(String[] classpathNames, String[] initialFileNames, String encoding) {
- final int classpathSize = classpathNames.length;
- this.classpaths = new Classpath[classpathSize];
- int counter = 0;
- for (int i = 0; i < classpathSize; i++) {
- Classpath classpath = getClasspath(classpathNames[i], encoding, null);
- if (classpath!=null) {
- try {
- classpath.initialize();
- this.classpaths[counter++] = classpath;
- } catch (IOException e) {
- // ignore
- }
- }
- }
- if (counter != classpathSize) {
- System.arraycopy(this.classpaths, 0, (this.classpaths = new Classpath[counter]), 0, counter);
- }
- initializeKnownFileNames(initialFileNames);
-}
-FileSystem(Classpath[] paths, String[] initialFileNames) {
- final int length = paths.length;
- int counter = 0;
- this.classpaths = new FileSystem.Classpath[length];
- for (int i = 0; i < length; i++) {
- final Classpath classpath = paths[i];
- try {
- classpath.initialize();
- this.classpaths[counter++] = classpath;
- } catch(IOException exception) {
- // ignore
- }
- }
- if (counter != length) {
- // should not happen
- System.arraycopy(this.classpaths, 0, (this.classpaths = new FileSystem.Classpath[counter]), 0, counter);
- }
- initializeKnownFileNames(initialFileNames);
-}
-public static Classpath getClasspath(String classpathName, String encoding, AccessRuleSet accessRuleSet) {
- return getClasspath(classpathName, encoding, false, accessRuleSet, null);
-}
-static Classpath getClasspath(String classpathName, String encoding,
- boolean isSourceOnly, AccessRuleSet accessRuleSet,
- String destinationPath) {
- Classpath result = null;
- File file = new File(convertPathSeparators(classpathName));
- if (file.isDirectory()) {
- if (file.exists()) {
-// result = new ClasspathDirectory(file, encoding,
-// isSourceOnly ? ClasspathLocation.SOURCE :
-// ClasspathLocation.SOURCE | ClasspathLocation.BINARY,
-// accessRuleSet,
-// destinationPath == null || destinationPath == Main.NONE ?
-// destinationPath : // keep == comparison valid
-// convertPathSeparators(destinationPath));
- }
- } else {
- String lowercaseClasspathName = classpathName.toLowerCase();
-// if (lowercaseClasspathName.endsWith(SUFFIX_STRING_jar)
-// || lowercaseClasspathName.endsWith(SUFFIX_STRING_zip)) {
-// if (isSourceOnly) {
-// // source only mode
-// result = new ClasspathSourceJar(file, true, accessRuleSet,
-// encoding,
-// destinationPath == null || destinationPath == Main.NONE ?
-// destinationPath : // keep == comparison valid
-// convertPathSeparators(destinationPath));
-// } else {
-// // class file only mode
-// if (destinationPath == null) {
-// result = new ClasspathJar(file, true, accessRuleSet, null);
-// }
-// }
-// }
-// else
- if (lowercaseClasspathName.endsWith(SUFFIX_STRING_java))
- {
- result=new ClasspathFile(file, encoding,accessRuleSet,destinationPath == null || destinationPath == Main.NONE ?
- destinationPath : // keep == comparison valid
- convertPathSeparators(destinationPath));
- }
- else if (lowercaseClasspathName.endsWith(IOAAMetaDataConstants.METADATA_FILE.toLowerCase()))
- {
- result=new ClasspathMetadataFile(file, encoding,accessRuleSet,destinationPath == null || destinationPath == Main.NONE ?
- destinationPath : // keep == comparison valid
- convertPathSeparators(destinationPath));
-
- }
- }
- return result;
-}
-private void initializeKnownFileNames(String[] initialFileNames) {
- if (initialFileNames == null) {
- this.knownFileNames = new HashSet(0);
- return;
- }
- this.knownFileNames = new HashSet(initialFileNames.length * 2);
- for (int i = initialFileNames.length; --i >= 0;) {
- char[] fileName = initialFileNames[i].toCharArray();
- char[] matchingPathName = null;
- final int lastIndexOf = CharOperation.lastIndexOf('.', fileName);
- if (lastIndexOf != -1) {
- fileName = CharOperation.subarray(fileName, 0, lastIndexOf);
- }
- CharOperation.replace(fileName, '\\', '/');
-// for (int j = 0; j < classpaths.length; j++){
-// char[] matchCandidate = this.classpaths[j].normalizedPath();
-// if (this.classpaths[j] instanceof ClasspathDirectory &&
-// CharOperation.prefixEquals(matchCandidate, fileName) &&
-// (matchingPathName == null ||
-// matchCandidate.length < matchingPathName.length))
-// matchingPathName = matchCandidate;
-// }
- if (matchingPathName == null) {
- this.knownFileNames.add(new String(fileName)); // leave as is...
- }
- else {
- this.knownFileNames.add(new String(CharOperation.subarray(fileName, matchingPathName.length, fileName.length)));
- }
- matchingPathName = null;
- }
-}
-public void cleanup() {
- for (int i = 0, max = this.classpaths.length; i < max; i++)
- this.classpaths[i].reset();
-}
-private static String convertPathSeparators(String path) {
- return File.separatorChar == '/'
- ? path.replace('\\', '/')
- : path.replace('/', '\\');
-}
-private NameEnvironmentAnswer findClass(String qualifiedTypeName, char[] typeName, boolean asBinaryOnly){
- if (this.knownFileNames.contains(qualifiedTypeName)) return null; // looking for a file which we know was provided at the beginning of the compilation
-
- String qualifiedBinaryFileName = qualifiedTypeName + SUFFIX_STRING_java;
- String qualifiedPackageName =
- qualifiedTypeName.length() == typeName.length
- ? Util.EMPTY_STRING
- : qualifiedBinaryFileName.substring(0, qualifiedTypeName.length() - typeName.length - 1);
- String qp2 = File.separatorChar == '/' ? qualifiedPackageName : qualifiedPackageName.replace('/', File.separatorChar);
- NameEnvironmentAnswer suggestedAnswer = null;
- if (qualifiedPackageName == qp2) {
- for (int i = 0, length = this.classpaths.length; i < length; i++) {
- NameEnvironmentAnswer answer = this.classpaths[i].findClass(typeName, qualifiedPackageName, qualifiedBinaryFileName, asBinaryOnly);
- if (answer != null) {
- if (!answer.ignoreIfBetter()) {
- if (answer.isBetter(suggestedAnswer))
- return answer;
- } else if (answer.isBetter(suggestedAnswer))
- // remember suggestion and keep looking
- suggestedAnswer = answer;
- }
- }
- } else {
- String qb2 = qualifiedBinaryFileName.replace('/', File.separatorChar);
- for (int i = 0, length = this.classpaths.length; i < length; i++) {
- Classpath p = this.classpaths[i];
- NameEnvironmentAnswer answer = p.findClass(typeName, qp2, qb2, asBinaryOnly);
- if (answer != null) {
- if (!answer.ignoreIfBetter()) {
- if (answer.isBetter(suggestedAnswer))
- return answer;
- } else if (answer.isBetter(suggestedAnswer))
- // remember suggestion and keep looking
- suggestedAnswer = answer;
- }
- }
- }
- if (suggestedAnswer != null)
- // no better answer was found
- return suggestedAnswer;
- return null;
-}
-
-private NameEnvironmentAnswer findBinding(String qualifiedTypeName, char[] typeName, int type, ITypeRequestor requestor){
- if (this.knownFileNames.contains(qualifiedTypeName)) return null; // looking for a file which we know was provided at the beginning of the compilation
-
- String qualifiedPackageName =
- qualifiedTypeName.length() == typeName.length
- ? "" //$NON-NLS-1$
- : qualifiedTypeName.substring(0, qualifiedTypeName.length() - typeName.length - 1);
- NameEnvironmentAnswer suggestedAnswer = null;
- for (int i = 0, length = this.classpaths.length; i < length; i++) {
- NameEnvironmentAnswer answer = this.classpaths[i].findBinding(typeName, qualifiedPackageName, type,requestor);
- if (answer != null) {
- if (!answer.ignoreIfBetter()) {
- if (answer.isBetter(suggestedAnswer))
- return answer;
- } else if (answer.isBetter(suggestedAnswer))
- // remember suggestion and keep looking
- suggestedAnswer = answer;
- }
- }
- if (suggestedAnswer != null)
- // no better answer was found
- return suggestedAnswer;
- return null;
-}
-
-public NameEnvironmentAnswer findBinding(char[] typeName, char[][] packageName, int type, ITypeRequestor requestor, boolean returnMultiple, String excludePath) {
- if (typeName != null)
- return findBinding(
- new String(CharOperation.concatWith(packageName, typeName, '/')),
- typeName,type,requestor);
- return null;
-}
-
-
-public NameEnvironmentAnswer findType(char[][] compoundName, ITypeRequestor requestor) {
- if (compoundName != null)
- return findClass(
- new String(CharOperation.concatWith(compoundName, '/')),
- compoundName[compoundName.length - 1],false);
- return null;
-}
-public char[][][] findTypeNames(char[][] packageName) {
- char[][][] result = null;
- if (packageName != null) {
- String qualifiedPackageName = new String(CharOperation.concatWith(packageName, '/'));
- String qualifiedPackageName2 = File.separatorChar == '/' ? qualifiedPackageName : qualifiedPackageName.replace('/', File.separatorChar);
- if (qualifiedPackageName == qualifiedPackageName2) {
- for (int i = 0, length = this.classpaths.length; i < length; i++) {
- char[][][] answers = this.classpaths[i].findTypeNames(qualifiedPackageName);
- if (answers != null) {
- // concat with previous answers
- if (result == null) {
- result = answers;
- } else {
- int resultLength = result.length;
- int answersLength = answers.length;
- System.arraycopy(result, 0, (result = new char[answersLength + resultLength][][]), 0, resultLength);
- System.arraycopy(answers, 0, result, resultLength, answersLength);
- }
- }
- }
- } else {
- for (int i = 0, length = this.classpaths.length; i < length; i++) {
- Classpath p = this.classpaths[i];
- char[][][] answers =p.findTypeNames(qualifiedPackageName2);
- if (answers != null) {
- // concat with previous answers
- if (result == null) {
- result = answers;
- } else {
- int resultLength = result.length;
- int answersLength = answers.length;
- System.arraycopy(result, 0, (result = new char[answersLength + resultLength][][]), 0, resultLength);
- System.arraycopy(answers, 0, result, resultLength, answersLength);
- }
- }
- }
- }
- }
- return result;
-}
-public NameEnvironmentAnswer findType(char[][] compoundName, boolean asBinaryOnly) {
- if (compoundName != null)
- return findClass(
- new String(CharOperation.concatWith(compoundName, '/')),
- compoundName[compoundName.length - 1],
- asBinaryOnly);
- return null;
-}
-
-public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName, ITypeRequestor requestor) {
- if (typeName != null)
- return findClass(
- new String(CharOperation.concatWith(packageName, typeName, '/')),
- typeName,false);
- return null;
-}
-public boolean isPackage(char[][] compoundName, char[] packageName) {
- String qualifiedPackageName = new String(CharOperation.concatWith(compoundName, packageName, '/'));
- String qp2 = File.separatorChar == '/' ? qualifiedPackageName : qualifiedPackageName.replace('/', File.separatorChar);
- if (qualifiedPackageName == qp2) {
- for (int i = 0, length = this.classpaths.length; i < length; i++)
- if (this.classpaths[i].isPackage(qualifiedPackageName))
- return true;
- } else {
- for (int i = 0, length = this.classpaths.length; i < length; i++) {
- Classpath p = this.classpaths[i];
- if ( p.isPackage(qp2))
- return true;
- }
- }
- return false;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/batch/Main.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/batch/Main.java
deleted file mode 100644
index a0cafde1..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/batch/Main.java
+++ /dev/null
@@ -1,3892 +0,0 @@
-/*******************************************************************************
- * 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
- * Tom Tromey - Contribution for bug 125961
- * Tom Tromey - Contribution for bug 159641
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.batch;
-
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.FilenameFilter;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.LineNumberReader;
-import java.io.PrintWriter;
-import java.io.StringReader;
-import java.io.StringWriter;
-import java.io.UnsupportedEncodingException;
-import java.lang.reflect.Field;
-import java.text.DateFormat;
-import java.text.MessageFormat;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Locale;
-import java.util.Map;
-import java.util.MissingResourceException;
-import java.util.ResourceBundle;
-import java.util.Set;
-import java.util.StringTokenizer;
-
-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.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.core.compiler.libraries.SystemLibraryLocation;
-import org.eclipse.wst.jsdt.internal.compiler.CompilationResult;
-import org.eclipse.wst.jsdt.internal.compiler.Compiler;
-import org.eclipse.wst.jsdt.internal.compiler.ICompilerRequestor;
-import org.eclipse.wst.jsdt.internal.compiler.IErrorHandlingPolicy;
-import org.eclipse.wst.jsdt.internal.compiler.IProblemFactory;
-import org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants;
-import org.eclipse.wst.jsdt.internal.compiler.env.AccessRule;
-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.impl.CompilerOptions;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.LookupEnvironment;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding;
-import org.eclipse.wst.jsdt.internal.compiler.problem.DefaultProblemFactory;
-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.GenericXMLWriter;
-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.Messages;
-import org.eclipse.wst.jsdt.internal.compiler.util.SuffixConstants;
-import org.eclipse.wst.jsdt.internal.compiler.util.Util;
-
-public class Main implements ProblemSeverities, SuffixConstants {
- /**
- * Resource bundle factory to share bundles for the same locale
- */
- public static class ResourceBundleFactory {
- private static HashMap Cache = new HashMap();
- public static synchronized ResourceBundle getBundle(Locale locale) {
- ResourceBundle bundle = (ResourceBundle) Cache.get(locale);
- if (bundle == null) {
- bundle = ResourceBundle.getBundle(Main.bundleName, locale);
- Cache.put(locale, bundle);
- }
- return bundle;
- }
- }
-
- public static class Logger {
- private static final String CLASS = "class"; //$NON-NLS-1$
- private static final String CLASS_FILE = "classfile"; //$NON-NLS-1$
- private static final String CLASSPATH = "classpath"; //$NON-NLS-1$
- private static final String CLASSPATH_FILE = "FILE"; //$NON-NLS-1$
- private static final String CLASSPATH_FOLDER = "FOLDER"; //$NON-NLS-1$
- private static final String CLASSPATH_ID = "id"; //$NON-NLS-1$
- private static final String CLASSPATH_JAR = "JAR"; //$NON-NLS-1$
- private static final String CLASSPATHS = "classpaths"; //$NON-NLS-1$
- private static final String COMMAND_LINE_ARGUMENT = "argument"; //$NON-NLS-1$
- private static final String COMMAND_LINE_ARGUMENTS = "command_line"; //$NON-NLS-1$
- private static final String COMPILER = "compiler"; //$NON-NLS-1$
- private static final String COMPILER_COPYRIGHT = "copyright"; //$NON-NLS-1$
- private static final String COMPILER_NAME = "name"; //$NON-NLS-1$
- private static final String COMPILER_VERSION = "version"; //$NON-NLS-1$
- public static final int EMACS = 2;
- private static final String ERROR = "ERROR"; //$NON-NLS-1$
- private static final String ERROR_TAG = "error"; //$NON-NLS-1$
- private static final String EXCEPTION = "exception"; //$NON-NLS-1$
- private static final String EXTRA_PROBLEM_TAG = "extra_problem"; //$NON-NLS-1$
- private static final String EXTRA_PROBLEMS = "extra_problems"; //$NON-NLS-1$
- private static final HashtableOfInt FIELD_TABLE = new HashtableOfInt();
- private static final String KEY = "key"; //$NON-NLS-1$
- private static final String MESSAGE = "message"; //$NON-NLS-1$
- private static final String NUMBER_OF_CLASSFILES = "number_of_classfiles"; //$NON-NLS-1$
- private static final String NUMBER_OF_ERRORS = "errors"; //$NON-NLS-1$
- private static final String NUMBER_OF_LINES = "number_of_lines"; //$NON-NLS-1$
- private static final String NUMBER_OF_PROBLEMS = "problems"; //$NON-NLS-1$
- private static final String NUMBER_OF_TASKS = "tasks"; //$NON-NLS-1$
- private static final String NUMBER_OF_WARNINGS = "warnings"; //$NON-NLS-1$
- private static final String OPTION = "option"; //$NON-NLS-1$
- private static final String OPTIONS = "options"; //$NON-NLS-1$
- private static final String OUTPUT = "output"; //$NON-NLS-1$
- private static final String PACKAGE = "package"; //$NON-NLS-1$
- private static final String PATH = "path"; //$NON-NLS-1$
- private static final String PROBLEM_ARGUMENT = "argument"; //$NON-NLS-1$
- private static final String PROBLEM_ARGUMENT_VALUE = "value"; //$NON-NLS-1$
- private static final String PROBLEM_ARGUMENTS = "arguments"; //$NON-NLS-1$
- private static final String PROBLEM_CATEGORY_ID = "categoryID"; //$NON-NLS-1$
- private static final String ID = "id"; //$NON-NLS-1$
- private static final String PROBLEM_ID = "problemID"; //$NON-NLS-1$
- private static final String PROBLEM_LINE = "line"; //$NON-NLS-1$
- private static final String PROBLEM_OPTION_KEY = "optionKey"; //$NON-NLS-1$
- private static final String PROBLEM_MESSAGE = "message"; //$NON-NLS-1$
- private static final String PROBLEM_SEVERITY = "severity"; //$NON-NLS-1$
- private static final String PROBLEM_SOURCE_END = "charEnd"; //$NON-NLS-1$
- private static final String PROBLEM_SOURCE_START = "charStart"; //$NON-NLS-1$
- private static final String PROBLEM_SUMMARY = "problem_summary"; //$NON-NLS-1$
- private static final String PROBLEM_TAG = "problem"; //$NON-NLS-1$
- private static final String PROBLEMS = "problems"; //$NON-NLS-1$
- private static final String SOURCE = "source"; //$NON-NLS-1$
- private static final String SOURCE_CONTEXT = "source_context"; //$NON-NLS-1$
- private static final String SOURCE_END = "sourceEnd"; //$NON-NLS-1$
- private static final String SOURCE_START = "sourceStart"; //$NON-NLS-1$
- private static final String SOURCES = "sources"; //$NON-NLS-1$
- private static final String STATS = "stats"; //$NON-NLS-1$
- private static final String TASK = "task"; //$NON-NLS-1$
- private static final String TASKS = "tasks"; //$NON-NLS-1$
- private static final String TIME = "time"; //$NON-NLS-1$
- private static final String VALUE = "value"; //$NON-NLS-1$
- private static final String WARNING = "WARNING"; //$NON-NLS-1$
-
- public static final int XML = 1;
-
- private static final String XML_DTD_DECLARATION = "<!DOCTYPE compiler PUBLIC \"-//Eclipse.org//DTD Eclipse JDT 3.2.003 Compiler//EN\" \"http://www.eclipse.org/jdt/core/compiler_32_003.dtd\">"; //$NON-NLS-1$
- static {
- try {
- Class c = IProblem.class;
- Field[] fields = c.getFields();
- for (int i = 0, max = fields.length; i < max; i++) {
- Field field = fields[i];
- if (field.getType().equals(Integer.TYPE)) {
- Integer value = (Integer) field.get(null);
- Logger.FIELD_TABLE.put(value.intValue() & IProblem.IgnoreCategoriesMask, field.getName());
- }
- }
- } catch (SecurityException e) {
- e.printStackTrace();
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- }
- }
- private PrintWriter err;
- private PrintWriter log;
- private Main main;
- private PrintWriter out;
- private HashMap parameters;
- int tagBits;
- public Logger(Main main, PrintWriter out, PrintWriter err) {
- this.out = out;
- this.err = err;
- this.parameters = new HashMap();
- this.main = main;
- }
-
- public String buildFileName(
- String outputPath,
- String relativeFileName) {
- char fileSeparatorChar = File.separatorChar;
- String fileSeparator = File.separator;
-
- outputPath = outputPath.replace('/', fileSeparatorChar);
- // To be able to pass the mkdirs() method we need to remove the extra file separator at the end of the outDir name
- StringBuffer outDir = new StringBuffer(outputPath);
- if (!outputPath.endsWith(fileSeparator)) {
- outDir.append(fileSeparator);
- }
- StringTokenizer tokenizer =
- new StringTokenizer(relativeFileName, fileSeparator);
- String token = tokenizer.nextToken();
- while (tokenizer.hasMoreTokens()) {
- outDir.append(token).append(fileSeparator);
- token = tokenizer.nextToken();
- }
- // token contains the last one
- return outDir.append(token).toString();
- }
-
- public void close() {
- if (this.log != null) {
- if ((this.tagBits & Logger.XML) != 0) {
- this.endTag(Logger.COMPILER);
- this.flush();
- }
- this.log.close();
- }
- }
-
- /**
- *
- */
- public void compiling() {
- this.printlnOut(this.main.bind("progress.compiling")); //$NON-NLS-1$
- }
-
- /**
- * Used to stop logging problems.
- * Only use in xml mode.
- */
- private void endLoggingProblems() {
- this.endTag(Logger.PROBLEMS);
- }
- private void endLoggingExtraProblems() {
- this.endTag(Logger.EXTRA_PROBLEMS);
- }
- public void endLoggingSource() {
- if ((this.tagBits & Logger.XML) != 0) {
- this.endTag(Logger.SOURCE);
- }
- }
-
- public void endLoggingSources() {
- if ((this.tagBits & Logger.XML) != 0) {
- this.endTag(Logger.SOURCES);
- }
- }
-
- public void endLoggingTasks() {
- if ((this.tagBits & Logger.XML) != 0) {
- this.endTag(Logger.TASKS);
- }
- }
- private void endTag(String name) {
- ((GenericXMLWriter) this.log).endTag(name, true, true);
- }
- private void extractContext(CategorizedProblem problem, char[] unitSource) {
- //sanity .....
- int startPosition = problem.getSourceStart();
- int endPosition = problem.getSourceEnd();
- if (unitSource == null) {
- if (problem.getOriginatingFileName() != null) {
- try {
- unitSource = Util.getFileCharContent(new File(new String(problem.getOriginatingFileName())), null);
- } catch(IOException e) {
- // ignore
- }
- }
- }
- int length = unitSource== null ? 0 : unitSource.length;
- if ((startPosition > endPosition)
- || ((startPosition < 0) && (endPosition < 0))
- || (length <= 0)
- || (endPosition > length)) {
- this.parameters.put(Logger.VALUE, Messages.problem_noSourceInformation);
- this.parameters.put(Logger.SOURCE_START, "-1"); //$NON-NLS-1$
- this.parameters.put(Logger.SOURCE_END, "-1"); //$NON-NLS-1$
- this.printTag(Logger.SOURCE_CONTEXT, this.parameters, true, true);
- return;
- }
-
- char c;
- //the next code tries to underline the token.....
- //it assumes (for a good display) that token source does not
- //contain any \r \n. This is false on statements !
- //(the code still works but the display is not optimal !)
-
- // expand to line limits
- int begin, end;
- for (begin = startPosition >= length ? length - 1 : startPosition; begin > 0; begin--) {
- if ((c = unitSource[begin - 1]) == '\n' || c == '\r') break;
- }
- for (end = endPosition >= length ? length - 1 : endPosition ; end+1 < length; end++) {
- if ((c = unitSource[end + 1]) == '\r' || c == '\n') break;
- }
-
- // trim left and right spaces/tabs
- while ((c = unitSource[begin]) == ' ' || c == '\t') begin++;
- while ((c = unitSource[end]) == ' ' || c == '\t') end--;
-
- // copy source
- StringBuffer buffer = new StringBuffer();
- buffer.append(unitSource, begin, end - begin + 1);
-
- this.parameters.put(Logger.VALUE, String.valueOf(buffer));
- this.parameters.put(Logger.SOURCE_START, Integer.toString(startPosition - begin));
- this.parameters.put(Logger.SOURCE_END, Integer.toString(endPosition - begin));
- this.printTag(Logger.SOURCE_CONTEXT, this.parameters, true, true);
- }
-
- public void flush() {
- this.out.flush();
- this.err.flush();
- if (this.log != null) {
- this.log.flush();
- }
- }
- private String getFieldName(int id) {
- return (String) Logger.FIELD_TABLE.get(id & IProblem.IgnoreCategoriesMask);
- }
-
- // find out an option name controlling a given problemID
- private String getProblemOptionKey(int problemID) {
- long irritant = ProblemReporter.getIrritant(problemID);
- return CompilerOptions.optionKeyFromIrritant(irritant);
- }
-
- public void logAverage(long[] times, long lineCount) {
- Arrays.sort(times);
- final int length = times.length;
- long sum = 0;
- for (int i = 1, max = length - 1; i < max; i++) {
- sum += times[i];
- }
- long time = sum / (length - 2);
- this.printlnOut(this.main.bind(
- "compile.averageTime", //$NON-NLS-1$
- new String[] {
- String.valueOf(lineCount),
- String.valueOf(time),
- String.valueOf(((int) (lineCount * 10000.0 / time)) / 10.0) }));
- }
-
- public void logClassFile(boolean generatePackagesStructure, String outputPath, String relativeFileName) {
- if ((this.tagBits & Logger.XML) != 0) {
- String fileName = null;
- if (generatePackagesStructure) {
- fileName = buildFileName(outputPath, relativeFileName);
- } else {
- char fileSeparatorChar = File.separatorChar;
- String fileSeparator = File.separator;
- // First we ensure that the outputPath exists
- outputPath = outputPath.replace('/', fileSeparatorChar);
- // To be able to pass the mkdirs() method we need to remove the extra file separator at the end of the outDir name
- int indexOfPackageSeparator = relativeFileName.lastIndexOf(fileSeparatorChar);
- if (indexOfPackageSeparator == -1) {
- if (outputPath.endsWith(fileSeparator)) {
- fileName = outputPath + relativeFileName;
- } else {
- fileName = outputPath + fileSeparator + relativeFileName;
- }
- } else {
- int length = relativeFileName.length();
- if (outputPath.endsWith(fileSeparator)) {
- fileName = outputPath + relativeFileName.substring(indexOfPackageSeparator + 1, length);
- } else {
- fileName = outputPath + fileSeparator + relativeFileName.substring(indexOfPackageSeparator + 1, length);
- }
- }
- }
- File f = new File(fileName);
- try {
- this.parameters.put(Logger.PATH, f.getCanonicalPath());
- this.printTag(Logger.CLASS_FILE, this.parameters, true, true);
- } catch (IOException e) {
- this.logNoClassFileCreated(outputPath, relativeFileName, e);
- }
- }
- }
- public void logClasspath(FileSystem.Classpath[] classpaths) {
- if (classpaths == null) return;
- if ((this.tagBits & Logger.XML) != 0) {
- final int length = classpaths.length;
- if (length != 0) {
- // generate xml output
- this.printTag(Logger.CLASSPATHS, null, true, false);
- for (int i = 0; i < length; i++) {
- String classpath = classpaths[i].getPath();
- this.parameters.put(Logger.PATH, classpath);
- File f = new File(classpath);
- String id = null;
- if (f.isFile()) {
- if (Util.isArchiveFileName(classpath)) {
- id = Logger.CLASSPATH_JAR;
- } else {
- id = Logger.CLASSPATH_FILE;
- }
- } else if (f.isDirectory()) {
- id = Logger.CLASSPATH_FOLDER;
- }
- if (id != null) {
- this.parameters.put(Logger.CLASSPATH_ID, id);
- this.printTag(Logger.CLASSPATH, this.parameters, true, true);
- }
- }
- this.endTag(Logger.CLASSPATHS);
- }
- }
-
- }
- public void logCommandLineArguments(String[] commandLineArguments) {
- if (commandLineArguments == null) return;
- if ((this.tagBits & Logger.XML) != 0) {
- final int length = commandLineArguments.length;
- if (length != 0) {
- // generate xml output
- this.printTag(Logger.COMMAND_LINE_ARGUMENTS, null, true, false);
- for (int i = 0; i < length; i++) {
- this.parameters.put(Logger.VALUE, commandLineArguments[i]);
- this.printTag(Logger.COMMAND_LINE_ARGUMENT, this.parameters, true, true);
- }
- this.endTag(Logger.COMMAND_LINE_ARGUMENTS);
- }
- }
- }
-
- /**
- * @param e the given exception to log
- */
- public void logException(Exception e) {
- StringWriter writer = new StringWriter();
- PrintWriter printWriter = new PrintWriter(writer);
- e.printStackTrace(printWriter);
- printWriter.flush();
- printWriter.close();
- final String stackTrace = writer.getBuffer().toString();
- if ((this.tagBits & Logger.XML) != 0) {
- LineNumberReader reader = new LineNumberReader(new StringReader(stackTrace));
- String line;
- int i = 0;
- StringBuffer buffer = new StringBuffer();
- String message = e.getMessage();
- if (message != null) {
- buffer.append(message).append(Util.LINE_SEPARATOR);
- }
- try {
- while ((line = reader.readLine()) != null && i < 4) {
- buffer.append(line).append(Util.LINE_SEPARATOR);
- i++;
- }
- reader.close();
- } catch (IOException e1) {
- // ignore
- }
- message = buffer.toString();
- this.parameters.put(Logger.MESSAGE, message);
- this.parameters.put(Logger.CLASS, e.getClass());
- this.printTag(Logger.EXCEPTION, this.parameters, true, true);
- }
- String message = e.getMessage();
- if (message == null) {
- this.printlnErr(stackTrace);
- } else {
- this.printlnErr(message);
- }
- }
-
- /**
- * @param wrongClasspath
- * the given wrong classpath entry
- */
- public void logIncorrectClasspath(String wrongClasspath) {
- if ((this.tagBits & Logger.XML) != 0) {
- this.parameters.put(Logger.MESSAGE, this.main.bind("configure.incorrectClasspath", wrongClasspath)); //$NON-NLS-1$
- this.printTag(Logger.ERROR_TAG, this.parameters, true, true);
- }
- this.printlnErr(this.main.bind(
- "configure.incorrectClasspath", wrongClasspath)); //$NON-NLS-1$
- }
-
- /**
- * @param wrongPath
- * the given wrong path entry
- */
- public void logIncorrectEndorsedDirsEntry(String wrongPath) {
- if ((this.tagBits & Logger.XML) != 0) {
- this.parameters.put(Logger.MESSAGE, this.main.bind("configure.incorrectEndorsedDirsEntry", wrongPath)); //$NON-NLS-1$
- this.printTag(Logger.ERROR_TAG, this.parameters, true, true);
- }
- this.printlnErr(this.main.bind(
- "configure.incorrectEndorsedDirsEntry", wrongPath)); //$NON-NLS-1$
- }
-
- /**
- * @param wrongPath
- * the given wrong path entry
- */
- public void logIncorrectExtDirsEntry(String wrongPath) {
- if ((this.tagBits & Logger.XML) != 0) {
- this.parameters.put(Logger.MESSAGE, this.main.bind("configure.incorrectExtDirsEntry", wrongPath)); //$NON-NLS-1$
- this.printTag(Logger.ERROR_TAG, this.parameters, true, true);
- }
- this.printlnErr(this.main.bind(
- "configure.incorrectExtDirsEntry", wrongPath)); //$NON-NLS-1$
- }
-
- public void logIncorrectVMVersionForAnnotationProcessing() {
- if ((this.tagBits & Logger.XML) != 0) {
- this.parameters.put(Logger.MESSAGE, this.main.bind("configure.incorrectVMVersionforAPT")); //$NON-NLS-1$
- this.printTag(Logger.ERROR_TAG, this.parameters, true, true);
- }
- this.printlnErr(this.main.bind("configure.incorrectVMVersionforAPT")); //$NON-NLS-1$
- }
-
- /**
- *
- */
- public void logNoClassFileCreated(String outputDir, String relativeFileName, IOException e) {
- if ((this.tagBits & Logger.XML) != 0) {
- this.parameters.put(Logger.MESSAGE, this.main.bind("output.noClassFileCreated", //$NON-NLS-1$
- new String[] {
- outputDir,
- relativeFileName,
- e.getMessage()
- }));
- this.printTag(Logger.ERROR_TAG, this.parameters, true, true);
- }
- this.printlnErr(this.main.bind("output.noClassFileCreated", //$NON-NLS-1$
- new String[] {
- outputDir,
- relativeFileName,
- e.getMessage()
- }));
- }
-
- public void logNoClasspath() {
- if ((this.tagBits & Logger.XML) != 0) {
- this.parameters.put(Logger.MESSAGE, this.main.bind("configure.noClasspath")); //$NON-NLS-1$
- this.printTag(Logger.ERROR_TAG, this.parameters, true, true);
- }
- this.printlnErr(this.main.bind("configure.noClasspath")); //$NON-NLS-1$
- }
-
- /**
- * @param exportedClassFilesCounter
- */
- public void logNumberOfClassFilesGenerated(int exportedClassFilesCounter) {
- if ((this.tagBits & Logger.XML) != 0) {
- this.parameters.put(Logger.VALUE, new Integer(exportedClassFilesCounter));
- this.printTag(Logger.NUMBER_OF_CLASSFILES, this.parameters, true, true);
- }
- if (exportedClassFilesCounter == 1) {
- this.printlnOut(this.main.bind("compile.oneClassFileGenerated")); //$NON-NLS-1$
- } else {
- this.printlnOut(this.main.bind("compile.severalClassFilesGenerated", //$NON-NLS-1$
- String.valueOf(exportedClassFilesCounter)));
- }
- }
-
- /**
- * @param options the given compiler options
- */
- public void logOptions(Map options) {
- if ((this.tagBits & Logger.XML) != 0) {
- this.printTag(Logger.OPTIONS, null, true, false);
- final Set entriesSet = options.entrySet();
- Object[] entries = entriesSet.toArray();
- Arrays.sort(entries, new Comparator() {
- public int compare(Object o1, Object o2) {
- Map.Entry entry1 = (Map.Entry) o1;
- Map.Entry entry2 = (Map.Entry) o2;
- return ((String) entry1.getKey()).compareTo((String) entry2.getKey());
- }
- });
- for (int i = 0, max = entries.length; i < max; i++) {
- Map.Entry entry = (Map.Entry) entries[i];
- String key = (String) entry.getKey();
- this.parameters.put(Logger.KEY, key);
- this.parameters.put(Logger.VALUE, entry.getValue());
- this.printTag(Logger.OPTION, this.parameters, true, true);
- }
- this.endTag(Logger.OPTIONS);
- }
- }
-
- private void logProblem(CategorizedProblem problem, int localErrorCount,
- int globalErrorCount, char[] unitSource) {
- if ((this.tagBits & Logger.EMACS) != 0) {
- String result = (new String(problem.getOriginatingFileName())
- + ":" //$NON-NLS-1$
- + problem.getSourceLineNumber()
- + ": " //$NON-NLS-1$
- + (problem.isError() ? this.main.bind("output.emacs.error") : this.main.bind("output.emacs.warning")) //$NON-NLS-1$ //$NON-NLS-2$
- + ": " //$NON-NLS-1$
- + problem.getMessage());
- this.printlnErr(result);
- final String errorReportSource = errorReportSource(problem, unitSource, this.tagBits);
- if (errorReportSource.length() != 0) this.printlnErr(errorReportSource);
- } else {
- if (localErrorCount == 0) {
- this.printlnErr("----------"); //$NON-NLS-1$
- }
- this.printErr(problem.isError() ?
- this.main.bind(
- "requestor.error", //$NON-NLS-1$
- Integer.toString(globalErrorCount),
- new String(problem.getOriginatingFileName()))
- : this.main.bind(
- "requestor.warning", //$NON-NLS-1$
- Integer.toString(globalErrorCount),
- new String(problem.getOriginatingFileName())));
- try {
- final String errorReportSource = errorReportSource(problem, unitSource, 0);
- this.printlnErr(errorReportSource);
- this.printlnErr(problem.getMessage());
- } catch (Exception e) {
- this.printlnErr(this.main.bind(
- "requestor.notRetrieveErrorMessage", problem.toString())); //$NON-NLS-1$
- }
- this.printlnErr("----------"); //$NON-NLS-1$
- }
- }
-
- public int logProblems(CategorizedProblem[] problems, char[] unitSource, Main currentMain) {
- final int count = problems.length;
- int localErrorCount = 0;
- int localProblemCount = 0;
- if (count != 0) {
- int errors = 0;
- int warnings = 0;
- int tasks = 0;
- for (int i = 0; i < count; i++) {
- CategorizedProblem problem = problems[i];
- if (problem != null) {
- currentMain.globalProblemsCount++;
- this.logProblem(problem, localProblemCount, currentMain.globalProblemsCount, unitSource);
- localProblemCount++;
- if (problem.isError()) {
- localErrorCount++;
- errors++;
- currentMain.globalErrorsCount++;
- } else if (problem.getID() == IProblem.Task) {
- currentMain.globalTasksCount++;
- tasks++;
- } else {
- currentMain.globalWarningsCount++;
- warnings++;
- }
- }
- }
- if ((this.tagBits & Logger.XML) != 0) {
- if ((errors + warnings) != 0) {
- this.startLoggingProblems(errors, warnings);
- for (int i = 0; i < count; i++) {
- CategorizedProblem problem = problems[i];
- if (problem!= null) {
- if (problem.getID() != IProblem.Task) {
- this.logXmlProblem(problem, unitSource);
- }
- }
- }
- this.endLoggingProblems();
- }
- if (tasks != 0) {
- this.startLoggingTasks(tasks);
- for (int i = 0; i < count; i++) {
- CategorizedProblem problem = problems[i];
- if (problem!= null) {
- if (problem.getID() == IProblem.Task) {
- this.logXmlTask(problem, unitSource);
- }
- }
- }
- this.endLoggingTasks();
- }
- }
- }
- return localErrorCount;
- }
-
- /**
- * @param globalProblemsCount
- * @param globalErrorsCount
- * @param globalWarningsCount
- */
- public void logProblemsSummary(int globalProblemsCount,
- int globalErrorsCount, int globalWarningsCount, int globalTasksCount) {
- if ((this.tagBits & Logger.XML) != 0) {
- // generate xml
- this.parameters.put(Logger.NUMBER_OF_PROBLEMS, new Integer(globalProblemsCount));
- this.parameters.put(Logger.NUMBER_OF_ERRORS, new Integer(globalErrorsCount));
- this.parameters.put(Logger.NUMBER_OF_WARNINGS, new Integer(globalWarningsCount));
- this.parameters.put(Logger.NUMBER_OF_TASKS, new Integer(globalTasksCount));
- this.printTag(Logger.PROBLEM_SUMMARY, this.parameters, true, true);
- }
- if (globalProblemsCount == 1) {
- String message = null;
- if (globalErrorsCount == 1) {
- message = this.main.bind("compile.oneError"); //$NON-NLS-1$
- } else {
- message = this.main.bind("compile.oneWarning"); //$NON-NLS-1$
- }
- this.printErr(this.main.bind("compile.oneProblem", message)); //$NON-NLS-1$
- } else {
- String errorMessage = null;
- String warningMessage = null;
- if (globalErrorsCount > 0) {
- if (globalErrorsCount == 1) {
- errorMessage = this.main.bind("compile.oneError"); //$NON-NLS-1$
- } else {
- errorMessage = this.main.bind("compile.severalErrors", String.valueOf(globalErrorsCount)); //$NON-NLS-1$
- }
- }
- int warningsNumber = globalWarningsCount + globalTasksCount;
- if (warningsNumber > 0) {
- if (warningsNumber == 1) {
- warningMessage = this.main.bind("compile.oneWarning"); //$NON-NLS-1$
- } else {
- warningMessage = this.main.bind("compile.severalWarnings", String.valueOf(warningsNumber)); //$NON-NLS-1$
- }
- }
- if (errorMessage == null || warningMessage == null) {
- if (errorMessage == null) {
- this.printErr(this.main.bind(
- "compile.severalProblemsErrorsOrWarnings", //$NON-NLS-1$
- String.valueOf(globalProblemsCount),
- warningMessage));
- } else {
- this.printErr(this.main.bind(
- "compile.severalProblemsErrorsOrWarnings", //$NON-NLS-1$
- String.valueOf(globalProblemsCount),
- errorMessage));
- }
- } else {
- this.printErr(this.main.bind(
- "compile.severalProblemsErrorsAndWarnings", //$NON-NLS-1$
- new String[] {
- String.valueOf(globalProblemsCount),
- errorMessage,
- warningMessage
- }));
- }
- }
- if ((this.tagBits & Logger.EMACS) != 0) {
- this.printlnErr();
- }
- }
-
- /**
- *
- */
- public void logProgress() {
- this.printOut('.');
- }
-
- /**
- * @param i
- * the current repetition number
- * @param repetitions
- * the given number of repetitions
- */
- public void logRepetition(int i, int repetitions) {
- this.printlnOut(this.main.bind("compile.repetition", //$NON-NLS-1$
- String.valueOf(i + 1), String.valueOf(repetitions)));
- }
-
- /**
- * @param time
- * @param lineCount
- */
- public void logTiming(long time, long lineCount) {
- if ((this.tagBits & Logger.XML) != 0) {
- this.parameters.put(Logger.VALUE, new Long(time));
- this.printTag(Logger.TIME, this.parameters, true, true);
- this.parameters.put(Logger.VALUE, new Long(lineCount));
- this.printTag(Logger.NUMBER_OF_LINES, this.parameters, true, true);
- }
- if (lineCount != 0) {
- this.printlnOut(this.main.bind(
- "compile.instantTime", //$NON-NLS-1$
- new String[] {
- String.valueOf(lineCount),
- String.valueOf(time),
- String.valueOf(((int) (lineCount * 10000.0 / time)) / 10.0) }));
- } else {
- this.printlnOut(this.main.bind("compile.totalTime", String.valueOf(time))); //$NON-NLS-1$
- }
- }
-
- /**
- * Print the usage of the compiler
- * @param usage
- */
- public void logUsage(String usage) {
- this.printlnOut(usage);
- }
-
- /**
- * Print the version of the compiler in the log and/or the out field
- */
- public void logVersion(final boolean printToOut) {
- if (this.log != null && (this.tagBits & Logger.XML) == 0) {
- final String version = this.main.bind("misc.version", //$NON-NLS-1$
- new String[] {
- this.main.bind("compiler.name"), //$NON-NLS-1$
- this.main.bind("compiler.version"), //$NON-NLS-1$
- this.main.bind("compiler.copyright") //$NON-NLS-1$
- }
- );
- this.log.println("# " + version); //$NON-NLS-1$
- if (printToOut) {
- this.out.println(version);
- this.out.flush();
- }
- } else if (printToOut) {
- final String version = this.main.bind("misc.version", //$NON-NLS-1$
- new String[] {
- this.main.bind("compiler.name"), //$NON-NLS-1$
- this.main.bind("compiler.version"), //$NON-NLS-1$
- this.main.bind("compiler.copyright") //$NON-NLS-1$
- }
- );
- this.out.println(version);
- this.out.flush();
- }
- }
- /**
- * Print the usage of wrong JDK
- */
- public void logWrongJDK() {
- if ((this.tagBits & Logger.XML) != 0) {
- this.parameters.put(Logger.MESSAGE, this.main.bind("configure.requiresJDK1.2orAbove")); //$NON-NLS-1$
- this.printTag(Logger.ERROR, this.parameters, true, true);
- }
- this.printlnErr(this.main.bind("configure.requiresJDK1.2orAbove")); //$NON-NLS-1$
- }
-
- /**
- * @param problem
- * the given problem to log
- * @param unitSource
- * the given unit source
- */
- private void logXmlProblem(CategorizedProblem problem, char[] unitSource) {
- final int sourceStart = problem.getSourceStart();
- final int sourceEnd = problem.getSourceEnd();
- final int id = problem.getID();
- this.parameters.put(Logger.ID, getFieldName(id)); // ID as field name
- this.parameters.put(Logger.PROBLEM_ID, new Integer(id)); // ID as numeric value
- boolean isError = problem.isError();
- int severity = isError ? ProblemSeverities.Error : ProblemSeverities.Warning;
- this.parameters.put(Logger.PROBLEM_SEVERITY, isError ? Logger.ERROR : Logger.WARNING);
- this.parameters.put(Logger.PROBLEM_LINE, new Integer(problem.getSourceLineNumber()));
- this.parameters.put(Logger.PROBLEM_SOURCE_START, new Integer(sourceStart));
- this.parameters.put(Logger.PROBLEM_SOURCE_END, new Integer(sourceEnd));
- String problemOptionKey = getProblemOptionKey(id);
- if (problemOptionKey != null) {
- this.parameters.put(Logger.PROBLEM_OPTION_KEY, problemOptionKey);
- }
- int categoryID = ProblemReporter.getProblemCategory(severity, id);
- this.parameters.put(Logger.PROBLEM_CATEGORY_ID, new Integer(categoryID));
- this.printTag(Logger.PROBLEM_TAG, this.parameters, true, false);
- this.parameters.put(Logger.VALUE, problem.getMessage());
- this.printTag(Logger.PROBLEM_MESSAGE, this.parameters, true, true);
- extractContext(problem, unitSource);
- String[] arguments = problem.getArguments();
- final int length = arguments.length;
- if (length != 0) {
- this.printTag(Logger.PROBLEM_ARGUMENTS, null, true, false);
- for (int i = 0; i < length; i++) {
- this.parameters.put(Logger.PROBLEM_ARGUMENT_VALUE, arguments[i]);
- this.printTag(Logger.PROBLEM_ARGUMENT, this.parameters, true, true);
- }
- this.endTag(Logger.PROBLEM_ARGUMENTS);
- }
- this.endTag(Logger.PROBLEM_TAG);
- }
-
- /**
- * @param problem
- * the given problem to log
- * @param unitSource
- * the given unit source
- */
- private void logXmlTask(CategorizedProblem problem, char[] unitSource) {
- this.parameters.put(Logger.PROBLEM_LINE, new Integer(problem.getSourceLineNumber()));
- this.parameters.put(Logger.PROBLEM_SOURCE_START, new Integer(problem.getSourceStart()));
- this.parameters.put(Logger.PROBLEM_SOURCE_END, new Integer(problem.getSourceEnd()));
- String problemOptionKey = getProblemOptionKey(problem.getID());
- if (problemOptionKey != null) {
- this.parameters.put(Logger.PROBLEM_OPTION_KEY, problemOptionKey);
- }
- this.printTag(Logger.TASK, this.parameters, true, false);
- this.parameters.put(Logger.VALUE, problem.getMessage());
- this.printTag(Logger.PROBLEM_MESSAGE, this.parameters, true, true);
- extractContext(problem, unitSource);
- this.endTag(Logger.TASK);
- }
-
- private void printErr(String s) {
- this.err.print(s);
- if ((this.tagBits & Logger.XML) == 0 && this.log != null) {
- this.log.print(s);
- }
- }
-
- private void printlnErr() {
- this.err.println();
- if ((this.tagBits & Logger.XML) == 0 && this.log != null) {
- this.log.println();
- }
- }
- private void printlnErr(String s) {
- this.err.println(s);
- if ((this.tagBits & Logger.XML) == 0 && this.log != null) {
- this.log.println(s);
- }
- }
- private void printlnOut(String s) {
- this.out.println(s);
- if ((this.tagBits & Logger.XML) == 0 && this.log != null) {
- this.log.println(s);
- }
- }
-
- /**
- *
- */
- public void printNewLine() {
- this.out.println();
- }
-
- private void printOut(char c) {
- this.out.print(c);
- }
-
- public void printStats() {
- final boolean isTimed = this.main.timing;
- if ((this.tagBits & Logger.XML) != 0) {
- this.printTag(Logger.STATS, null, true, false);
- }
- if (isTimed) {
- long time = System.currentTimeMillis() - this.main.startTime;
- this.logTiming(time, this.main.lineCount);
- if (this.main.times != null) {
- this.main.times[this.main.timesCounter++] = time;
- }
- }
- if (this.main.globalProblemsCount > 0) {
- this.logProblemsSummary(this.main.globalProblemsCount, this.main.globalErrorsCount, this.main.globalWarningsCount, main.globalTasksCount);
- }
- if (this.main.exportedClassFilesCounter != 0
- && (this.main.showProgress || isTimed || this.main.verbose)) {
- this.logNumberOfClassFilesGenerated(this.main.exportedClassFilesCounter);
- }
- if ((this.tagBits & Logger.XML) != 0) {
- this.endTag(Logger.STATS);
- }
- }
-
- private void printTag(String name, HashMap params, boolean insertNewLine, boolean closeTag) {
- ((GenericXMLWriter) this.log).printTag(name, parameters, true, insertNewLine, closeTag);
- this.parameters.clear();
- }
-
- public void setEmacs() {
- this.tagBits |= Logger.EMACS;
- }
-
- public void setLog(String logFileName) throws InvalidInputException {
- final Date date = new Date();
- final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG, Locale.getDefault());
- try {
- int index = logFileName.lastIndexOf('.');
- if (index != -1) {
- if (logFileName.substring(index).toLowerCase().equals(".xml")) { //$NON-NLS-1$
- this.log = new GenericXMLWriter(new FileOutputStream(logFileName, false), Util.LINE_SEPARATOR, true);
- this.tagBits |= Logger.XML;
- // insert time stamp as comment
- try {
- this.log.println("<!-- " + new String(dateFormat.format(date).getBytes(), "UTF-8") + " -->");//$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- this.log.println(Logger.XML_DTD_DECLARATION);
- this.parameters.put(Logger.COMPILER_NAME, this.main.bind("compiler.name")); //$NON-NLS-1$
- this.parameters.put(Logger.COMPILER_VERSION, this.main.bind("compiler.version")); //$NON-NLS-1$
- this.parameters.put(Logger.COMPILER_COPYRIGHT, this.main.bind("compiler.copyright")); //$NON-NLS-1$
- this.printTag(Logger.COMPILER, this.parameters, true, false);
- } else {
- this.log = new PrintWriter(new FileOutputStream(logFileName, false));
- this.log.println("# " + dateFormat.format(date));//$NON-NLS-1$
- }
- } else {
- if (logFileName.equals("con")) //$NON-NLS-1$
- this.log=new PrintWriter(System.out);
- else
- this.log = new PrintWriter(new FileOutputStream(logFileName, false));
- this.log.println("# " + dateFormat.format(date));//$NON-NLS-1$
- }
- } catch (FileNotFoundException e) {
- throw new InvalidInputException(this.main.bind("configure.cannotOpenLog", logFileName)); //$NON-NLS-1$
- }
- }
-
- /**
- * Used to start logging problems.
- * Only use in xml mode.
- */
- private void startLoggingProblems(int errors, int warnings) {
- this.parameters.put(Logger.NUMBER_OF_PROBLEMS, new Integer(errors + warnings));
- this.parameters.put(Logger.NUMBER_OF_ERRORS, new Integer(errors));
- this.parameters.put(Logger.NUMBER_OF_WARNINGS, new Integer(warnings));
- this.printTag(Logger.PROBLEMS, this.parameters, true, false);
- }
-
- private void startLoggingExtraProblems(int count) {
- this.parameters.put(Logger.NUMBER_OF_PROBLEMS, new Integer(count));
- this.printTag(Logger.EXTRA_PROBLEMS, this.parameters, true, false);
- }
-
- public void startLoggingSource(CompilationResult compilationResult) {
- if ((this.tagBits & Logger.XML) != 0) {
- ICompilationUnit compilationUnit = compilationResult.compilationUnit;
- if (compilationUnit != null) {
- char[] fileName = compilationUnit.getFileName();
- File f = new File(new String(fileName));
- if (fileName != null) {
- this.parameters.put(Logger.PATH, f.getAbsolutePath());
- }
- char[][] packageName = compilationResult.packageName;
- if (packageName != null) {
- this.parameters.put(
- Logger.PACKAGE,
- new String(CharOperation.concatWith(packageName, File.separatorChar)));
- }
- CompilationUnit unit = (CompilationUnit) compilationUnit;
- String destinationPath = unit.destinationPath;
- if (destinationPath == null) {
- destinationPath = this.main.destinationPath;
- }
- if (destinationPath != null && destinationPath != NONE) {
- if (File.separatorChar == '/') {
- this.parameters.put(Logger.OUTPUT, destinationPath);
- } else {
- this.parameters.put(Logger.OUTPUT, destinationPath.replace('/', File.separatorChar));
- }
- }
- }
- this.printTag(Logger.SOURCE, this.parameters, true, false);
- }
- }
- public void startLoggingSources() {
- if ((this.tagBits & Logger.XML) != 0) {
- this.printTag(Logger.SOURCES, null, true, false);
- }
- }
- public void startLoggingTasks(int tasks) {
- if ((this.tagBits & Logger.XML) != 0) {
- this.parameters.put(Logger.NUMBER_OF_TASKS, new Integer(tasks));
- this.printTag(Logger.TASKS, this.parameters, true, false);
- }
- }
-
- public void loggingExtraProblems(Main currentMain) {
- ArrayList problems = currentMain.extraProblems;
- final int count = problems.size();
- int localErrorCount = 0;
- int localProblemCount = 0;
- if (count != 0) {
- int errors = 0;
- int warnings = 0;
- for (int i = 0; i < count; i++) {
- CategorizedProblem problem = (CategorizedProblem) problems.get(i);
- if (problem != null) {
- currentMain.globalProblemsCount++;
- this.logExtraProblem(problem, localProblemCount, currentMain.globalProblemsCount);
- localProblemCount++;
- if (problem.isError()) {
- localErrorCount++;
- errors++;
- currentMain.globalErrorsCount++;
- } else if (problem.isWarning()) {
- currentMain.globalWarningsCount++;
- warnings++;
- }
- }
- }
- if ((this.tagBits & Logger.XML) != 0) {
- if ((errors + warnings) != 0) {
- this.startLoggingExtraProblems(count);
- for (int i = 0; i < count; i++) {
- CategorizedProblem problem = (CategorizedProblem) problems.get(i);
- if (problem!= null) {
- if (problem.getID() != IProblem.Task) {
- this.logXmlExtraProblem(problem, localProblemCount, currentMain.globalProblemsCount);
- }
- }
- }
- this.endLoggingExtraProblems();
- }
- }
- }
- }
-
- private void logXmlExtraProblem(CategorizedProblem problem, int globalErrorCount, int localErrorCount) {
- final int sourceStart = problem.getSourceStart();
- final int sourceEnd = problem.getSourceEnd();
- boolean isError = problem.isError();
- this.parameters.put(Logger.PROBLEM_SEVERITY, isError ? Logger.ERROR : Logger.WARNING);
- this.parameters.put(Logger.PROBLEM_LINE, new Integer(problem.getSourceLineNumber()));
- this.parameters.put(Logger.PROBLEM_SOURCE_START, new Integer(sourceStart));
- this.parameters.put(Logger.PROBLEM_SOURCE_END, new Integer(sourceEnd));
- this.printTag(Logger.EXTRA_PROBLEM_TAG, this.parameters, true, false);
- this.parameters.put(Logger.VALUE, problem.getMessage());
- this.printTag(Logger.PROBLEM_MESSAGE, this.parameters, true, true);
- extractContext(problem, null);
- this.endTag(Logger.EXTRA_PROBLEM_TAG);
- }
-
- private void logExtraProblem(CategorizedProblem problem, int localErrorCount, int globalErrorCount) {
- char[] originatingFileName = problem.getOriginatingFileName();
- String fileName =
- originatingFileName == null
- ? this.main.bind("requestor.noFileNameSpecified")//$NON-NLS-1$
- : new String(originatingFileName);
- if ((this.tagBits & Logger.EMACS) != 0) {
- String result = fileName
- + ":" //$NON-NLS-1$
- + problem.getSourceLineNumber()
- + ": " //$NON-NLS-1$
- + (problem.isError() ? this.main.bind("output.emacs.error") : this.main.bind("output.emacs.warning")) //$NON-NLS-1$ //$NON-NLS-2$
- + ": " //$NON-NLS-1$
- + problem.getMessage();
- this.printlnErr(result);
- final String errorReportSource = errorReportSource(problem, null, this.tagBits);
- this.printlnErr(errorReportSource);
- } else {
- if (localErrorCount == 0) {
- this.printlnErr("----------"); //$NON-NLS-1$
- }
- this.printErr(problem.isError() ?
- this.main.bind(
- "requestor.error", //$NON-NLS-1$
- Integer.toString(globalErrorCount),
- new String(fileName))
- : this.main.bind(
- "requestor.warning", //$NON-NLS-1$
- Integer.toString(globalErrorCount),
- new String(fileName)));
- final String errorReportSource = errorReportSource(problem, null, 0);
- this.printlnErr(errorReportSource);
- this.printlnErr(problem.getMessage());
- this.printlnErr("----------"); //$NON-NLS-1$
- }
- }
-
- private String errorReportSource(CategorizedProblem problem, char[] unitSource, int bits) {
- //extra from the source the innacurate token
- //and "highlight" it using some underneath ^^^^^
- //put some context around too.
-
- //this code assumes that the font used in the console is fixed size
-
- //sanity .....
- int startPosition = problem.getSourceStart();
- int endPosition = problem.getSourceEnd();
- if (unitSource == null) {
- if (problem.getOriginatingFileName() != null) {
- try {
- unitSource = Util.getFileCharContent(new File(new String(problem.getOriginatingFileName())), null);
- } catch (IOException e) {
- // ignore;
- }
- }
- }
- int length = unitSource == null ? 0 : unitSource.length;
- if ((startPosition > endPosition)
- || ((startPosition < 0) && (endPosition < 0))
- || length == 0)
- return Messages.problem_noSourceInformation;
-
- StringBuffer errorBuffer = new StringBuffer();
- if ((bits & Main.Logger.EMACS) == 0) {
- errorBuffer.append(' ').append(Messages.bind(Messages.problem_atLine, String.valueOf(problem.getSourceLineNumber())));
- errorBuffer.append(Util.LINE_SEPARATOR);
- }
- errorBuffer.append('\t');
-
- char c;
- final char SPACE = '\u0020';
- final char MARK = '^';
- final char TAB = '\t';
- //the next code tries to underline the token.....
- //it assumes (for a good display) that token source does not
- //contain any \r \n. This is false on statements !
- //(the code still works but the display is not optimal !)
-
- // expand to line limits
- int begin;
- int end;
- for (begin = startPosition >= length ? length - 1 : startPosition; begin > 0; begin--) {
- if ((c = unitSource[begin - 1]) == '\n' || c == '\r') break;
- }
- for (end = endPosition >= length ? length - 1 : endPosition ; end+1 < length; end++) {
- if ((c = unitSource[end + 1]) == '\r' || c == '\n') break;
- }
-
- // trim left and right spaces/tabs
- while ((c = unitSource[begin]) == ' ' || c == '\t') begin++;
- //while ((c = unitSource[end]) == ' ' || c == '\t') end--; TODO (philippe) should also trim right, but all tests are to be updated
-
- // copy source
- errorBuffer.append(unitSource, begin, end-begin+1);
- errorBuffer.append(Util.LINE_SEPARATOR).append("\t"); //$NON-NLS-1$
-
- // compute underline
- for (int i = begin; i <startPosition; i++) {
- errorBuffer.append((unitSource[i] == TAB) ? TAB : SPACE);
- }
- for (int i = startPosition; i <= (endPosition >= length ? length - 1 : endPosition); i++) {
- errorBuffer.append(MARK);
- }
- return errorBuffer.toString();
- }
- }
- public final static String bundleName = "org.eclipse.wst.jsdt.internal.compiler.batch.messages"; //$NON-NLS-1$
-
- // two uses: recognize 'none' in options; code the singleton none
- // for the '-d none' option (wherever it may be found)
- public static final int DEFAULT_SIZE_CLASSPATH = 4;
- public static final String NONE = "none"; //$NON-NLS-1$
-
- /*
- * Internal IDE API
- */
- public static boolean compile(String commandLine) {
-
- return compile(commandLine, new PrintWriter(System.out), new PrintWriter(System.err));
- }
- /*
- * Internal IDE API for test harness purpose
- */
- public static boolean compile(String commandLine, PrintWriter outWriter, PrintWriter errWriter) {
-
- return new Main(outWriter, errWriter, false).compile(tokenize(commandLine));
- }
- public static File[][] getLibrariesFiles(File[] files) {
- FilenameFilter filter = new FilenameFilter() {
- public boolean accept(File dir, String name) {
- String lowerCaseName = name.toLowerCase();
- if (lowerCaseName.endsWith(SuffixConstants.SUFFIX_STRING_zip)) {
- return true;
- }
- return false;
- }
- };
- final int filesLength = files.length;
- File[][] result = new File[filesLength][];
- for (int i = 0; i < filesLength; i++) {
- File currentFile = files[i];
- if (currentFile.exists() && currentFile.isDirectory()) {
- result[i] = currentFile.listFiles(filter);
- }
- }
- return result;
- }
- public static void main(String[] argv) {
- new Main(new PrintWriter(System.out), new PrintWriter(System.err), true).compile(argv);
- }
- public static String[] tokenize(String commandLine) {
-
- int count = 0;
- String[] arguments = new String[10];
- StringTokenizer tokenizer = new StringTokenizer(commandLine, " \"", true); //$NON-NLS-1$
- String token = Util.EMPTY_STRING;
- boolean insideQuotes = false;
- boolean startNewToken = true;
-
- // take care to quotes on the command line
- // 'xxx "aaa bbb";ccc yyy' ---> {"xxx", "aaa bbb;ccc", "yyy" }
- // 'xxx "aaa bbb;ccc" yyy' ---> {"xxx", "aaa bbb;ccc", "yyy" }
- // 'xxx "aaa bbb";"ccc" yyy' ---> {"xxx", "aaa bbb;ccc", "yyy" }
- // 'xxx/"aaa bbb";"ccc" yyy' ---> {"xxx/aaa bbb;ccc", "yyy" }
- while (tokenizer.hasMoreTokens()) {
- token = tokenizer.nextToken();
-
- if (token.equals(" ")) { //$NON-NLS-1$
- if (insideQuotes) {
- arguments[count - 1] += token;
- startNewToken = false;
- } else {
- startNewToken = true;
- }
- } else if (token.equals("\"")) { //$NON-NLS-1$
- if (!insideQuotes && startNewToken) {
- if (count == arguments.length)
- System.arraycopy(arguments, 0, (arguments = new String[count * 2]), 0, count);
- arguments[count++] = Util.EMPTY_STRING;
- }
- insideQuotes = !insideQuotes;
- startNewToken = false;
- } else {
- if (insideQuotes) {
- arguments[count - 1] += token;
- } else {
- if (token.length() > 0 && !startNewToken) {
- arguments[count - 1] += token;
- } else {
- if (count == arguments.length)
- System.arraycopy(arguments, 0, (arguments = new String[count * 2]), 0, count);
- String trimmedToken = token.trim();
- if (trimmedToken.length() != 0) {
- arguments[count++] = trimmedToken;
- }
- }
- }
- startNewToken = false;
- }
- }
- System.arraycopy(arguments, 0, arguments = new String[count], 0, count);
- return arguments;
- }
- public Compiler batchCompiler;
- /* Bundle containing messages */
- public ResourceBundle bundle;
- protected FileSystem.Classpath[] checkedClasspaths;
- public Locale compilerLocale;
- public CompilerOptions compilerOptions; // read-only
- public String destinationPath;
- public String[] destinationPaths;
- // destination path for compilation units that get no more specific
- // one (through directory arguments or various classpath options);
- // coding is:
- // == null: unspecified, write class files close to their respective
- // source files;
- // == Main.NONE: absorbent element, do not output class files;
- // else: use as the path of the directory into which class files must
- // be written.
- private boolean didSpecifySource;
- private boolean didSpecifyTarget;
-
- public String[] encodings;
-
- public int exportedClassFilesCounter;
- public String[] filenames;
-
- public String[] classNames;
-
- // overrides of destinationPath on a directory argument basis
- public int globalErrorsCount;
- public int globalProblemsCount;
- public int globalTasksCount;
- public int globalWarningsCount;
- private File javaHomeCache;
- private boolean javaHomeChecked = false;
- public long lineCount;
- public String log;
- public Logger logger;
- public int maxProblems;
- public boolean noWarn = false;
- public Map options;
- protected PrintWriter out;
- public boolean proceed = true;
- public boolean proceedOnError = false;
- public boolean produceRefInfo = false;
- public int repetitions;
-
- public boolean showProgress = false;
- public long startTime;
-
- public boolean showError=true;
-
-public boolean systemExitWhenFinished = true;
-
-public long[] times;
-
-public int timesCounter;
-
-public boolean timing = false;
-
-public boolean verbose = false;
-
-private String[] expandedCommandLine;
-
-private PrintWriter err;
-
-protected ArrayList extraProblems;
-
-public Main(PrintWriter outWriter, PrintWriter errWriter, boolean systemExitWhenFinished) {
- this(outWriter, errWriter, systemExitWhenFinished, null);
-}
-
-public Main(PrintWriter outWriter, PrintWriter errWriter, boolean systemExitWhenFinished, Map customDefaultOptions) {
- this.initialize(outWriter, errWriter, systemExitWhenFinished, customDefaultOptions);
- this.relocalize();
-}
-public void addExtraProblems(CategorizedProblem problem) {
- if (this.extraProblems == null) {
- this.extraProblems = new ArrayList();
- }
- this.extraProblems.add(problem);
-}
-protected void addNewEntry(ArrayList paths, String currentClasspathName,
- ArrayList currentRuleSpecs, String customEncoding,
- String destPath, boolean isSourceOnly,
- boolean rejectDestinationPathOnJars) throws InvalidInputException {
-
- int rulesSpecsSize = currentRuleSpecs.size();
- AccessRuleSet accessRuleSet = null;
- if (rulesSpecsSize != 0) {
- AccessRule[] accessRules = new AccessRule[currentRuleSpecs.size()];
- boolean rulesOK = true;
- Iterator i = currentRuleSpecs.iterator();
- int j = 0;
- while (i.hasNext()) {
- String ruleSpec = (String) i.next();
- char key = ruleSpec.charAt(0);
- String pattern = ruleSpec.substring(1);
- if (pattern.length() > 0) {
- switch (key) {
- case '+':
- accessRules[j++] = new AccessRule(pattern
- .toCharArray(), 0);
- break;
- case '~':
- accessRules[j++] = new AccessRule(pattern
- .toCharArray(),
- IProblem.DiscouragedReference);
- break;
- case '-':
- accessRules[j++] = new AccessRule(pattern
- .toCharArray(),
- IProblem.ForbiddenReference);
- break;
- case '?':
- accessRules[j++] = new AccessRule(pattern
- .toCharArray(),
- IProblem.ForbiddenReference, true/*keep looking for accessible type*/);
- break;
- default:
- rulesOK = false;
- }
- } else {
- rulesOK = false;
- }
- }
- if (rulesOK) {
- String templates[] = new String[AccessRuleSet.MESSAGE_TEMPLATES_LENGTH];
- templates[0] = this.bind(
- "template.restrictedAccess.type", //$NON-NLS-1$
- new String[] {"{0}", currentClasspathName}); //$NON-NLS-1$
- templates[1] = this.bind(
- "template.restrictedAccess.constructor", //$NON-NLS-1$
- new String[] {"{0}", currentClasspathName}); //$NON-NLS-1$
- templates[2] = this.bind(
- "template.restrictedAccess.method", //$NON-NLS-1$
- new String[] {"{0}", "{1}", currentClasspathName}); //$NON-NLS-1$ //$NON-NLS-2$
- templates[3] = this.bind(
- "template.restrictedAccess.field", //$NON-NLS-1$
- new String[] {"{0}", "{1}", currentClasspathName}); //$NON-NLS-1$ //$NON-NLS-2$
- accessRuleSet = new AccessRuleSet(accessRules, templates);
- } else {
- if (currentClasspathName.length() != 0) {
- // we go on anyway
- this.logger.logIncorrectClasspath(currentClasspathName);
- }
- return;
- }
- }
- if (NONE.equals(destPath)) {
- destPath = NONE; // keep == comparison valid
- }
- if (rejectDestinationPathOnJars && destPath != null &&
- (currentClasspathName.endsWith(".jar") || //$NON-NLS-1$
- currentClasspathName.endsWith(".zip"))) { //$NON-NLS-1$
- throw new InvalidInputException(
- this.bind("configure.unexpectedDestinationPathEntryFile", //$NON-NLS-1$
- currentClasspathName));
- }
- FileSystem.Classpath currentClasspath = FileSystem.getClasspath(
- currentClasspathName,
- customEncoding,
- isSourceOnly,
- accessRuleSet,
- destPath);
- if (currentClasspath != null) {
- paths.add(currentClasspath);
- } else if (currentClasspathName.length() != 0) {
- // we go on anyway
- this.logger.logIncorrectClasspath(currentClasspathName);
- }
-}
-/*
- * Lookup the message with the given ID in this catalog
- */
-public String bind(String id) {
- return bind(id, (String[]) null);
-}
-/*
- * Lookup the message with the given ID in this catalog and bind its
- * substitution locations with the given string.
- */
-public String bind(String id, String binding) {
- return bind(id, new String[] { binding });
-}
-
-/*
- * Lookup the message with the given ID in this catalog and bind its
- * substitution locations with the given strings.
- */
-public String bind(String id, String binding1, String binding2) {
- return bind(id, new String[] { binding1, binding2 });
-}
-
-/*
- * Lookup the message with the given ID in this catalog and bind its
- * substitution locations with the given string values.
- */
-public String bind(String id, String[] arguments) {
- if (id == null)
- return "No message available"; //$NON-NLS-1$
- String message = null;
- try {
- message = this.bundle.getString(id);
- } catch (MissingResourceException e) {
- // If we got an exception looking for the message, fail gracefully by just returning
- // the id we were looking for. In most cases this is semi-informative so is not too bad.
- return "Missing message: " + id + " in: " + Main.bundleName; //$NON-NLS-2$ //$NON-NLS-1$
- }
- return MessageFormat.format(message, arguments);
-}
-/**
- * Return true if and only if the running VM supports the given minimal version.
- *
- * <p>This only checks the major version, since the minor version is always 0 (at least for the useful cases).</p>
- * <p>The given minimalSupportedVersion is one of the constants:</p>
- * <ul>
- * <li><code>org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants.JDK1_1</code></li>
- * <li><code>org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants.JDK1_2</code></li>
- * <li><code>org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants.JDK1_3</code></li>
- * <li><code>org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants.JDK1_4</code></li>
- * <li><code>org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants.JDK1_5</code></li>
- * <li><code>org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants.JDK1_6</code></li>
- * <li><code>org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants.JDK1_7</code></li>
- * </ul>
- * @param minimalSupportedVersion the given minimal version
- * @return true if and only if the running VM supports the given minimal version, false otherwise
- */
-protected boolean checkVMVersion(long minimalSupportedVersion) {
- // the format of this property is supposed to be xx.x where x are digits.
- String classFileVersion = System.getProperty("java.class.version"); //$NON-NLS-1$
- if (classFileVersion == null) {
- // by default we don't support a class file version we cannot recognize
- return false;
- }
- int index = classFileVersion.indexOf('.');
- if (index == -1) {
- // by default we don't support a class file version we cannot recognize
- return false;
- }
- int majorVersion;
- try {
- majorVersion = Integer.parseInt(classFileVersion.substring(0, index));
- } catch (NumberFormatException e) {
- // by default we don't support a class file version we cannot recognize
- return false;
- }
- switch(majorVersion) {
- case 45 : // 1.0 and 1.1
- return ClassFileConstants.JDK1_1 >= minimalSupportedVersion;
- case 46 : // 1.2
- return ClassFileConstants.JDK1_2 >= minimalSupportedVersion;
- case 47 : // 1.3
- return ClassFileConstants.JDK1_3 >= minimalSupportedVersion;
- case 48 : // 1.4
- return ClassFileConstants.JDK1_4 >= minimalSupportedVersion;
- case 49 : // 1.5
- return ClassFileConstants.JDK1_5 >= minimalSupportedVersion;
- case 50 : // 1.6
- return ClassFileConstants.JDK1_6 >= minimalSupportedVersion;
- case 51 : // 1.7
- return ClassFileConstants.JDK1_7 >= minimalSupportedVersion;
- }
- // unknown version
- return false;
-}
-/*
- * Low-level API performing the actual compilation
- */
-public boolean compile(String[] argv) {
-
- // decode command line arguments
- try {
- configure(argv);
- if (this.proceed) {
-// if (this.verbose) {
-// System.out.println(new CompilerOptions(this.options));
-// }
- if (this.showProgress) this.logger.compiling();
- for (int i = 0; i < this.repetitions; i++) {
- this.globalProblemsCount = 0;
- this.globalErrorsCount = 0;
- this.globalWarningsCount = 0;
- this.globalTasksCount = 0;
- this.lineCount = 0;
- this.exportedClassFilesCounter = 0;
-
- if (this.repetitions > 1) {
- this.logger.flush();
- this.logger.logRepetition(i, this.repetitions);
- }
- // request compilation
- performCompilation();
- }
- if (this.times != null) {
- this.logger.logAverage(this.times, this.lineCount);
- }
- if (this.showProgress) this.logger.printNewLine();
- }
- if (this.systemExitWhenFinished) {
- this.logger.flush();
- this.logger.close();
- System.exit(this.globalErrorsCount > 0 ? -1 : 0);
- }
- } catch (InvalidInputException e) {
- this.logger.logException(e);
- if (this.systemExitWhenFinished) {
- this.logger.flush();
- this.logger.close();
- System.exit(-1);
- }
- return false;
- } catch (RuntimeException e) { // internal compiler failure
- this.logger.logException(e);
- if (this.systemExitWhenFinished) {
- this.logger.flush();
- this.logger.close();
- System.exit(-1);
- }
- return false;
- } finally {
- this.logger.flush();
- this.logger.close();
- }
- if (this.globalErrorsCount == 0)
- return true;
- return false;
-}
-
-/*
- * External API
- * Handle a single warning token.
-*/
-protected void handleWarningToken(String token, boolean isEnabling, boolean useEnableJavadoc) throws InvalidInputException {
- if (token.equals("constructorName")) { //$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_ReportMethodWithConstructorName,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
-// } else if (token.equals("pkgDefaultMethod") || token.equals("packageDefaultMethod")/*backward compatible*/ ) { //$NON-NLS-1$ //$NON-NLS-2$
-// this.options.put(
-// CompilerOptions.OPTION_ReportOverridingPackageDefaultMethod,
-// isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("maskedCatchBlock") || token.equals("maskedCatchBlocks")/*backward compatible*/) { //$NON-NLS-1$ //$NON-NLS-2$
- this.options.put(
- CompilerOptions.OPTION_ReportHiddenCatchBlock,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("deprecation")) { //$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_ReportDeprecation,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- this.options.put(
- CompilerOptions.OPTION_ReportDeprecationInDeprecatedCode,
- CompilerOptions.DISABLED);
- this.options.put(
- CompilerOptions.OPTION_ReportDeprecationWhenOverridingDeprecatedMethod,
- CompilerOptions.DISABLED);
- } else if (token.equals("allDeprecation")) { //$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_ReportDeprecation,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- this.options.put(
- CompilerOptions.OPTION_ReportDeprecationInDeprecatedCode,
- isEnabling ? CompilerOptions.ENABLED : CompilerOptions.DISABLED);
- this.options.put(
- CompilerOptions.OPTION_ReportDeprecationWhenOverridingDeprecatedMethod,
- isEnabling ? CompilerOptions.ENABLED : CompilerOptions.DISABLED);
- } else if (token.equals("unusedLocal") || token.equals("unusedLocals")/*backward compatible*/) { //$NON-NLS-1$ //$NON-NLS-2$
- this.options.put(
- CompilerOptions.OPTION_ReportUnusedLocal,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("unusedArgument") || token.equals("unusedArguments")/*backward compatible*/) { //$NON-NLS-1$ //$NON-NLS-2$
- this.options.put(
- CompilerOptions.OPTION_ReportUnusedParameter,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("unusedPrivate")) { //$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_ReportUnusedPrivateMember,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("unusedLabel")) { //$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_ReportUnusedLabel,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("localHiding")) { //$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_ReportLocalVariableHiding,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("fieldHiding")) { //$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_ReportFieldHiding,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("specialParamHiding")) { //$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_ReportSpecialParameterHidingField,
- isEnabling ? CompilerOptions.ENABLED : CompilerOptions.DISABLED);
- } else if (token.equals("conditionAssign")) { //$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_ReportPossibleAccidentalBooleanAssignment,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("syntheticAccess") //$NON-NLS-1$
- || token.equals("synthetic-access")) { //$NON-NLS-1$
-// this.options.put(
-// CompilerOptions.OPTION_ReportSyntheticAccessEmulation,
-// isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("nls")) { //$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_ReportNonExternalizedStringLiteral,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("staticReceiver")) { //$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_ReportNonStaticAccessToStatic,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("indirectStatic")) { //$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_ReportIndirectStaticAccess,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("noEffectAssign")) { //$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_ReportNoEffectAssignment,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("semicolon")) {//$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_ReportEmptyStatement,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("serial")) {//$NON-NLS-1$
-// this.options.put(
-// CompilerOptions.OPTION_ReportMissingSerialVersion,
-// isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("emptyBlock")) {//$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_ReportUndocumentedEmptyBlock,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("uselessTypeCheck")) {//$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_ReportUnnecessaryTypeCheck,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("unchecked") || token.equals("unsafe")) {//$NON-NLS-1$ //$NON-NLS-2$
- this.options.put(
- CompilerOptions.OPTION_ReportUncheckedTypeOperation,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("raw")) {//$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_ReportRawTypeReference,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("finalBound")) {//$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_ReportFinalParameterBound,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("suppress")) {//$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_SuppressWarnings,
- isEnabling ? CompilerOptions.ENABLED : CompilerOptions.DISABLED);
- } else if (token.equals("unnecessaryElse")) {//$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_ReportUnnecessaryElse,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("javadoc")) {//$NON-NLS-1$
- if (!useEnableJavadoc) {
- this.options.put(
- CompilerOptions.OPTION_DocCommentSupport,
- isEnabling ? CompilerOptions.ENABLED: CompilerOptions.DISABLED);
- }
- // if disabling then it's not necessary to set other javadoc options
- if (isEnabling) {
- this.options.put(
- CompilerOptions.OPTION_ReportInvalidJavadoc,
- CompilerOptions.WARNING);
- this.options.put(
- CompilerOptions.OPTION_ReportInvalidJavadocTags,
- CompilerOptions.ENABLED);
- this.options.put(
- CompilerOptions.OPTION_ReportInvalidJavadocTagsDeprecatedRef,
- CompilerOptions.DISABLED);
- this.options.put(
- CompilerOptions.OPTION_ReportInvalidJavadocTagsNotVisibleRef,
- CompilerOptions.DISABLED);
- this.options.put(
- CompilerOptions.OPTION_ReportInvalidJavadocTagsVisibility,
- CompilerOptions.PRIVATE);
- this.options.put(
- CompilerOptions.OPTION_ReportMissingJavadocTags,
- CompilerOptions.WARNING);
- this.options.put(
- CompilerOptions.OPTION_ReportMissingJavadocTagsVisibility,
- CompilerOptions.PRIVATE);
- }
- } else if (token.equals("allJavadoc")) { //$NON-NLS-1$
- if (!useEnableJavadoc) {
- this.options.put(
- CompilerOptions.OPTION_DocCommentSupport,
- isEnabling ? CompilerOptions.ENABLED: CompilerOptions.DISABLED);
- }
- // if disabling then it's not necessary to set other javadoc options
- if (isEnabling) {
- this.options.put(
- CompilerOptions.OPTION_ReportInvalidJavadoc,
- CompilerOptions.WARNING);
- this.options.put(
- CompilerOptions.OPTION_ReportInvalidJavadocTags,
- CompilerOptions.ENABLED);
- this.options.put(
- CompilerOptions.OPTION_ReportInvalidJavadocTagsVisibility,
- CompilerOptions.PRIVATE);
- this.options.put(
- CompilerOptions.OPTION_ReportMissingJavadocTags,
- CompilerOptions.WARNING);
- this.options.put(
- CompilerOptions.OPTION_ReportMissingJavadocTagsVisibility,
- CompilerOptions.PRIVATE);
- this.options.put(
- CompilerOptions.OPTION_ReportMissingJavadocComments,
- CompilerOptions.WARNING);
- }
- } else if (token.startsWith("tasks")) { //$NON-NLS-1$
- String taskTags = Util.EMPTY_STRING;
- int start = token.indexOf('(');
- int end = token.indexOf(')');
- if (start >= 0 && end >= 0 && start < end){
- taskTags = token.substring(start+1, end).trim();
- taskTags = taskTags.replace('|',',');
- }
- if (taskTags.length() == 0){
- throw new InvalidInputException(this.bind("configure.invalidTaskTag", token)); //$NON-NLS-1$
- }
- this.options.put(
- CompilerOptions.OPTION_TaskTags,
- isEnabling ? taskTags : Util.EMPTY_STRING);
- } else if (token.equals("assertIdentifier")) { //$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_ReportAssertIdentifier,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("enumIdentifier")) { //$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_ReportEnumIdentifier,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("finally")) { //$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_ReportFinallyBlockNotCompletingNormally,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("unusedThrown")) { //$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_ReportUnusedDeclaredThrownException,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("unqualifiedField") //$NON-NLS-1$
- || token.equals("unqualified-field-access")) { //$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_ReportUnqualifiedFieldAccess,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("typeHiding")) { //$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_ReportTypeParameterHiding,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("null")) { //$NON-NLS-1$
- if (isEnabling) {
- this.options.put(CompilerOptions.OPTION_ReportNullReference,
- CompilerOptions.WARNING);
- this.options.put(CompilerOptions.OPTION_ReportPotentialNullReference,
- CompilerOptions.WARNING);
- this.options.put(CompilerOptions.OPTION_ReportRedundantNullCheck,
- CompilerOptions.WARNING);
- } else {
- this.options.put(CompilerOptions.OPTION_ReportNullReference,
- CompilerOptions.IGNORE);
- this.options.put(CompilerOptions.OPTION_ReportPotentialNullReference,
- CompilerOptions.IGNORE);
- this.options.put(CompilerOptions.OPTION_ReportRedundantNullCheck,
- CompilerOptions.IGNORE);
- }
- } else if (token.equals("nullDereference")) { //$NON-NLS-1$
- if (isEnabling) {
- this.options.put(CompilerOptions.OPTION_ReportNullReference,
- CompilerOptions.WARNING);
- } else {
- this.options.put(CompilerOptions.OPTION_ReportNullReference,
- CompilerOptions.IGNORE);
- this.options.put(CompilerOptions.OPTION_ReportPotentialNullReference,
- CompilerOptions.IGNORE);
- this.options.put(CompilerOptions.OPTION_ReportRedundantNullCheck,
- CompilerOptions.IGNORE);
- }
- } else if (token.equals("hiding")) { //$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_ReportHiddenCatchBlock,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- this.options.put(
- CompilerOptions.OPTION_ReportLocalVariableHiding,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- this.options.put(
- CompilerOptions.OPTION_ReportFieldHiding,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- this.options.put(
- CompilerOptions.OPTION_ReportTypeParameterHiding,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("static-access")) { //$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_ReportNonStaticAccessToStatic,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- this.options.put(
- CompilerOptions.OPTION_ReportIndirectStaticAccess,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("unused")) { //$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_ReportUnusedLocal,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- this.options.put(
- CompilerOptions.OPTION_ReportUnusedParameter,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- this.options.put(
- CompilerOptions.OPTION_ReportUnusedPrivateMember,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- this.options.put(
- CompilerOptions.OPTION_ReportUnusedDeclaredThrownException,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- this.options.put(
- CompilerOptions.OPTION_ReportUnusedLabel,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("paramAssign")) { //$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_ReportParameterAssignment,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("discouraged")) { //$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_ReportDiscouragedReference,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("forbidden")) { //$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_ReportForbiddenReference,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("fallthrough")) { //$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_ReportFallthroughCase,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else if (token.equals("super")) { //$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_ReportOverridingMethodWithoutSuperInvocation,
- isEnabling ? CompilerOptions.WARNING : CompilerOptions.IGNORE);
- } else {
- throw new InvalidInputException(this.bind("configure.invalidWarning", token)); //$NON-NLS-1$
- }
-}
-/*
- * External API
- */
-protected ArrayList handleBootclasspath(ArrayList bootclasspaths, String customEncoding) throws InvalidInputException {
- final int bootclasspathsSize = bootclasspaths == null ? 0 : bootclasspaths.size();
- if (bootclasspathsSize != 0) {
- String[] paths = new String[bootclasspathsSize];
- bootclasspaths.toArray(paths);
- bootclasspaths.clear();
- for (int i = 0; i < bootclasspathsSize; i++) {
- processPathEntries(DEFAULT_SIZE_CLASSPATH, bootclasspaths,
- paths[i], customEncoding, false, true);
- }
- } else {
- bootclasspaths = new ArrayList(DEFAULT_SIZE_CLASSPATH);
- /* no bootclasspath specified
- * we can try to retrieve the default librairies of the VM used to run
- * the batch compiler
- */
- String javaversion = System.getProperty("java.version");//$NON-NLS-1$
- if (javaversion != null && javaversion.equalsIgnoreCase("1.1.8")) { //$NON-NLS-1$
- this.logger.logWrongJDK();
- this.proceed = false;
- return null;
- }
-
- /*
- * Handle >= JDK 1.2.2 settings: retrieve the bootclasspath
- */
- // check bootclasspath properties for Sun, JRockit and Harmony VMs
-// String bootclasspathProperty = System.getProperty("sun.boot.class.path"); //$NON-NLS-1$
-// if ((bootclasspathProperty == null) || (bootclasspathProperty.length() == 0)) {
-// // IBM J9 VMs
-// bootclasspathProperty = System.getProperty("vm.boot.class.path"); //$NON-NLS-1$
-// if ((bootclasspathProperty == null) || (bootclasspathProperty.length() == 0)) {
-// // Harmony using IBM VME
-// bootclasspathProperty = System.getProperty("org.apache.harmony.boot.class.path"); //$NON-NLS-1$
-// }
-// }
-// if ((bootclasspathProperty != null) && (bootclasspathProperty.length() != 0)) {
-// StringTokenizer tokenizer = new StringTokenizer(bootclasspathProperty, File.pathSeparator);
-// String token;
-// while (tokenizer.hasMoreTokens()) {
-// token = tokenizer.nextToken();
-// FileSystem.Classpath currentClasspath = FileSystem
-// .getClasspath(token, customEncoding, null);
-// if (currentClasspath != null) {
-// bootclasspaths.add(currentClasspath);
-// }
-// }
-// } else
- {
- String libraryPath = SystemLibraryLocation.getInstance().getLibraryPath(new String(SystemLibraryLocation.SYSTEM_LIBARAY_NAME));
- if (libraryPath!=null)
- bootclasspaths.add(FileSystem.getClasspath(libraryPath, null, null));
-
- // try to get all jars inside the lib folder of the java home
-// final File javaHome = getJavaHome();
-// if (javaHome != null) {
-// File[] directoriesToCheck = null;
-// if (System.getProperty("os.name").startsWith("Mac")) {//$NON-NLS-1$//$NON-NLS-2$
-// directoriesToCheck = new File[] {
-// new File(javaHome, "../Classes"), //$NON-NLS-1$
-// };
-// } else {
-// // fall back to try to retrieve them out of the lib directory
-// directoriesToCheck = new File[] {
-// new File(javaHome, "lib") //$NON-NLS-1$
-// };
-// }
-// File[][] systemLibrariesJars = getLibrariesFiles(directoriesToCheck);
-// if (systemLibrariesJars != null) {
-// for (int i = 0, max = systemLibrariesJars.length; i < max; i++) {
-// File[] current = systemLibrariesJars[i];
-// if (current != null) {
-// for (int j = 0, max2 = current.length; j < max2; j++) {
-// FileSystem.Classpath classpath =
-// FileSystem.getClasspath(current[j].getAbsolutePath(),
-// null, false, null, null);
-// if (classpath != null) {
-// bootclasspaths.add(classpath);
-// }
-// }
-// }
-// }
-// }
-// }
- }
- }
- return bootclasspaths;
-}
-/*
- * External API
- */
-protected ArrayList handleClasspath(ArrayList classpaths, String customEncoding) throws InvalidInputException {
- final int classpathsSize = classpaths == null ? 0 : classpaths.size();
- if (classpathsSize != 0) {
- String[] paths = new String[classpathsSize];
- classpaths.toArray(paths);
- classpaths.clear();
- for (int i = 0; i < classpathsSize; i++) {
- processPathEntries(DEFAULT_SIZE_CLASSPATH, classpaths, paths[i],
- customEncoding, false, true);
- }
- } else {
- // no user classpath specified.
-// classpaths = new ArrayList(DEFAULT_SIZE_CLASSPATH);
-// String classProp = System.getProperty("java.class.path"); //$NON-NLS-1$
-// if ((classProp == null) || (classProp.length() == 0)) {
-// this.logger.logNoClasspath();
-// classpaths.add(FileSystem.getClasspath(System.getProperty("user.dir"), customEncoding, null));//$NON-NLS-1$
-// } else {
-// StringTokenizer tokenizer = new StringTokenizer(classProp, File.pathSeparator);
-// String token;
-// while (tokenizer.hasMoreTokens()) {
-// token = tokenizer.nextToken();
-// FileSystem.Classpath currentClasspath = FileSystem
-// .getClasspath(token, customEncoding, null);
-// if (currentClasspath != null) {
-// classpaths.add(currentClasspath);
-// } else if (token.length() != 0) {
-// this.logger.logIncorrectClasspath(token);
-// }
-// }
-// }
- }
- return classpaths;
-}
-/*
- * External API
- * Handle extdirs processing
- */
-protected ArrayList handleExtdirs(ArrayList extdirsClasspaths) {
-// final File javaHome = getJavaHome();
-//
-// /*
-// * Feed extDirClasspath according to:
-// * - -extdirs first if present;
-// * - else java.ext.dirs if defined;
-// * - else default extensions directory for the platform.
-// */
-// if (extdirsClasspaths == null) {
-// extdirsClasspaths = new ArrayList(DEFAULT_SIZE_CLASSPATH);
-// String extdirsStr = System.getProperty("java.ext.dirs"); //$NON-NLS-1$
-// if (extdirsStr == null) {
-// extdirsClasspaths.add(javaHome.getAbsolutePath() + "/lib/ext"); //$NON-NLS-1$
-// } else {
-// StringTokenizer tokenizer = new StringTokenizer(extdirsStr, File.pathSeparator);
-// while (tokenizer.hasMoreTokens())
-// extdirsClasspaths.add(tokenizer.nextToken());
-// }
-// }
-//
-// /*
-// * Feed extdirsClasspath with the entries found into the directories listed by
-// * extdirsNames.
-// */
-// if (extdirsClasspaths.size() != 0) {
-// File[] directoriesToCheck = new File[extdirsClasspaths.size()];
-// for (int i = 0; i < directoriesToCheck.length; i++)
-// directoriesToCheck[i] = new File((String) extdirsClasspaths.get(i));
-// extdirsClasspaths.clear();
-// File[][] extdirsJars = getLibrariesFiles(directoriesToCheck);
-// if (extdirsJars != null) {
-// for (int i = 0, max = extdirsJars.length; i < max; i++) {
-// File[] current = extdirsJars[i];
-// if (current != null) {
-// for (int j = 0, max2 = current.length; j < max2; j++) {
-// FileSystem.Classpath classpath =
-// FileSystem.getClasspath(
-// current[j].getAbsolutePath(),
-// null, null);
-// if (classpath != null) {
-// extdirsClasspaths.add(classpath);
-// }
-// }
-// } else if (directoriesToCheck[i].isFile()) {
-// this.logger.logIncorrectExtDirsEntry(directoriesToCheck[i].getAbsolutePath());
-// }
-// }
-// }
-// }
-
- return extdirsClasspaths;
-}
-/*
- * External API
- */
-protected ArrayList handleEndorseddirs(ArrayList endorsedDirClasspaths) {
-// final File javaHome = getJavaHome();
-// /*
-// * Feed endorsedDirClasspath according to:
-// * - -endorseddirs first if present;
-// * - else java.endorsed.dirs if defined;
-// * - else default extensions directory for the platform. (/lib/endorsed)
-// */
-// if (endorsedDirClasspaths == null) {
-// endorsedDirClasspaths = new ArrayList(DEFAULT_SIZE_CLASSPATH);
-// String endorsedDirsStr = System.getProperty("java.endorsed.dirs"); //$NON-NLS-1$
-// if (endorsedDirsStr == null) {
-// if (javaHome != null) {
-// endorsedDirClasspaths.add(javaHome.getAbsolutePath() + "/lib/endorsed"); //$NON-NLS-1$
-// }
-// } else {
-// StringTokenizer tokenizer = new StringTokenizer(endorsedDirsStr, File.pathSeparator);
-// while (tokenizer.hasMoreTokens()) {
-// endorsedDirClasspaths.add(tokenizer.nextToken());
-// }
-// }
-// }
-//
-// /*
-// * Feed extdirsClasspath with the entries found into the directories listed by
-// * extdirsNames.
-// */
-// if (endorsedDirClasspaths.size() != 0) {
-// File[] directoriesToCheck = new File[endorsedDirClasspaths.size()];
-// for (int i = 0; i < directoriesToCheck.length; i++)
-// directoriesToCheck[i] = new File((String) endorsedDirClasspaths.get(i));
-// endorsedDirClasspaths.clear();
-// File[][] endorsedDirsJars = getLibrariesFiles(directoriesToCheck);
-// if (endorsedDirsJars != null) {
-// for (int i = 0, max = endorsedDirsJars.length; i < max; i++) {
-// File[] current = endorsedDirsJars[i];
-// if (current != null) {
-// for (int j = 0, max2 = current.length; j < max2; j++) {
-// FileSystem.Classpath classpath =
-// FileSystem.getClasspath(
-// current[j].getAbsolutePath(),
-// null, null);
-// if (classpath != null) {
-// endorsedDirClasspaths.add(classpath);
-// }
-// }
-// } else if (directoriesToCheck[i].isFile()) {
-// this.logger.logIncorrectEndorsedDirsEntry(directoriesToCheck[i].getAbsolutePath());
-// }
-// }
-// }
-// }
- return endorsedDirClasspaths;
-}
-
-/*
-Decode the command line arguments
- */
-public void configure(String[] argv) throws InvalidInputException {
-
- if ((argv == null) || (argv.length == 0)) {
- printUsage();
- return;
- }
-
- final int INSIDE_CLASSPATH_start = 1;
- final int INSIDE_DESTINATION_PATH = 3;
- final int INSIDE_TARGET = 4;
- final int INSIDE_LOG = 5;
- final int INSIDE_REPETITION = 6;
- final int INSIDE_SOURCE = 7;
- final int INSIDE_DEFAULT_ENCODING = 8;
- final int INSIDE_BOOTCLASSPATH_start = 9;
- final int INSIDE_MAX_PROBLEMS = 11;
- final int INSIDE_EXT_DIRS = 12;
- final int INSIDE_SOURCE_PATH_start = 13;
- final int INSIDE_ENDORSED_DIRS = 15;
- final int INSIDE_SOURCE_DIRECTORY_DESTINATION_PATH = 16;
- final int INSIDE_PROCESSOR_PATH_start = 17;
- final int INSIDE_PROCESSOR_start = 18;
- final int INSIDE_S_start = 19;
- final int INSIDE_CLASS_NAMES = 20;
-
- final int DEFAULT = 0;
- ArrayList bootclasspaths = new ArrayList(DEFAULT_SIZE_CLASSPATH);
- String sourcepathClasspathArg = null;
- ArrayList sourcepathClasspaths = new ArrayList(DEFAULT_SIZE_CLASSPATH);
- ArrayList classpaths = new ArrayList(DEFAULT_SIZE_CLASSPATH);
- ArrayList extdirsClasspaths = null;
- ArrayList endorsedDirClasspaths = null;
-
- int index = -1;
- int filesCount = 0;
- int classCount = 0;
- int argCount = argv.length;
- int mode = DEFAULT;
- this.repetitions = 0;
- boolean printUsageRequired = false;
- String usageSection = null;
- boolean printVersionRequired = false;
-
- boolean didSpecifyDefaultEncoding = false;
- boolean didSpecifyDeprecation = false;
- boolean didSpecifyWarnings = false;
- boolean useEnableJavadoc = false;
- boolean didSpecifyCompliance = false;
- boolean didSpecifyDisabledAnnotationProcessing = false;
-
- String customEncoding = null;
- String customDestinationPath = null;
- String currentSourceDirectory = null;
- String currentArg = Util.EMPTY_STRING;
-
- // expand the command line if necessary
- boolean needExpansion = false;
- loop: for (int i = 0; i < argCount; i++) {
- if (argv[i].startsWith("@")) { //$NON-NLS-1$
- needExpansion = true;
- break loop;
- }
- }
-
- String[] newCommandLineArgs = null;
- if (needExpansion) {
- newCommandLineArgs = new String[argCount];
- index = 0;
- for (int i = 0; i < argCount; i++) {
- String[] newArgs = null;
- String arg = argv[i].trim();
- if (arg.startsWith("@")) { //$NON-NLS-1$
- try {
- LineNumberReader reader = new LineNumberReader(new StringReader(new String(Util.getFileCharContent(new File(arg.substring(1)), null))));
- StringBuffer buffer = new StringBuffer();
- String line;
- while((line = reader.readLine()) != null) {
- line = line.trim();
- if (!line.startsWith("#")) { //$NON-NLS-1$
- buffer.append(line).append(" "); //$NON-NLS-1$
- }
- }
- newArgs = tokenize(buffer.toString());
- } catch(IOException e) {
- throw new InvalidInputException(
- this.bind("configure.invalidexpansionargumentname", arg)); //$NON-NLS-1$
- }
- }
- if (newArgs != null) {
- int newCommandLineArgsLength = newCommandLineArgs.length;
- int newArgsLength = newArgs.length;
- System.arraycopy(newCommandLineArgs, 0, (newCommandLineArgs = new String[newCommandLineArgsLength + newArgsLength - 1]), 0, index);
- System.arraycopy(newArgs, 0, newCommandLineArgs, index, newArgsLength);
- index += newArgsLength;
- } else {
- newCommandLineArgs[index++] = arg;
- }
- }
- index = -1;
- } else {
- newCommandLineArgs = argv;
- for (int i = 0; i < argCount; i++) {
- newCommandLineArgs[i] = newCommandLineArgs[i].trim();
- }
- }
- argCount = newCommandLineArgs.length;
- this.expandedCommandLine = newCommandLineArgs;
- while (++index < argCount) {
-
- if (customEncoding != null) {
- throw new InvalidInputException(
- this.bind("configure.unexpectedCustomEncoding", currentArg, customEncoding)); //$NON-NLS-1$
- }
-
- currentArg = newCommandLineArgs[index];
-
- switch(mode) {
- case DEFAULT :
- if (currentArg.startsWith("[")) { //$NON-NLS-1$
- throw new InvalidInputException(
- this.bind("configure.unexpectedBracket", //$NON-NLS-1$
- currentArg));
- }
-
- if (currentArg.endsWith("]")) { //$NON-NLS-1$
- // look for encoding specification
- int encodingStart = currentArg.indexOf('[') + 1;
- if (encodingStart <= 1) {
- throw new InvalidInputException(
- this.bind("configure.unexpectedBracket", currentArg)); //$NON-NLS-1$
- }
- int encodingEnd = currentArg.length() - 1;
- if (encodingStart >= 1) {
- if (encodingStart < encodingEnd) {
- customEncoding = currentArg.substring(encodingStart, encodingEnd);
- try { // ensure encoding is supported
- new InputStreamReader(new ByteArrayInputStream(new byte[0]), customEncoding);
- } catch (UnsupportedEncodingException e) {
- throw new InvalidInputException(
- this.bind("configure.unsupportedEncoding", customEncoding)); //$NON-NLS-1$
- }
- }
- currentArg = currentArg.substring(0, encodingStart - 1);
- }
- }
-
- if (currentArg.endsWith(SuffixConstants.SUFFIX_STRING_java)) {
- if (this.filenames == null) {
- this.filenames = new String[argCount - index];
- this.encodings = new String[argCount - index];
- this.destinationPaths = new String[argCount - index];
- } else if (filesCount == this.filenames.length) {
- int length = this.filenames.length;
- System.arraycopy(
- this.filenames,
- 0,
- (this.filenames = new String[length + argCount - index]),
- 0,
- length);
- System.arraycopy(
- this.encodings,
- 0,
- (this.encodings = new String[length + argCount - index]),
- 0,
- length);
- System.arraycopy(
- this.destinationPaths,
- 0,
- (this.destinationPaths = new String[length + argCount - index]),
- 0,
- length);
- }
- this.filenames[filesCount] = currentArg;
- this.encodings[filesCount++] = customEncoding;
- // destination path cannot be specified upon an individual file
- customEncoding = null;
- mode = DEFAULT;
- continue;
- }
- if (currentArg.equals("-log")) { //$NON-NLS-1$
- if (this.log != null)
- throw new InvalidInputException(
- this.bind("configure.duplicateLog", currentArg)); //$NON-NLS-1$
- mode = INSIDE_LOG;
- continue;
- }
- if (currentArg.equals("-repeat")) { //$NON-NLS-1$
- if (this.repetitions > 0)
- throw new InvalidInputException(
- this.bind("configure.duplicateRepeat", currentArg)); //$NON-NLS-1$
- mode = INSIDE_REPETITION;
- continue;
- }
- if (currentArg.equals("-maxProblems")) { //$NON-NLS-1$
- if (this.maxProblems > 0)
- throw new InvalidInputException(
- this.bind("configure.duplicateMaxProblems", currentArg)); //$NON-NLS-1$
- mode = INSIDE_MAX_PROBLEMS;
- continue;
- }
- if (currentArg.equals("-source")) { //$NON-NLS-1$
- mode = INSIDE_SOURCE;
- continue;
- }
- if (currentArg.equals("-encoding")) { //$NON-NLS-1$
- mode = INSIDE_DEFAULT_ENCODING;
- continue;
- }
- if (currentArg.equals("-1.3")) { //$NON-NLS-1$
- if (didSpecifyCompliance) {
- throw new InvalidInputException(
- this.bind("configure.duplicateCompliance", currentArg));//$NON-NLS-1$
- }
- didSpecifyCompliance = true;
- this.options.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_3);
- mode = DEFAULT;
- continue;
- }
- if (currentArg.equals("-1.4")) { //$NON-NLS-1$
- if (didSpecifyCompliance) {
- throw new InvalidInputException(
- this.bind("configure.duplicateCompliance", currentArg)); //$NON-NLS-1$
- }
- didSpecifyCompliance = true;
- this.options.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_4);
- mode = DEFAULT;
- continue;
- }
- if (currentArg.equals("-1.5") || currentArg.equals("-5") || currentArg.equals("-5.0")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- if (didSpecifyCompliance) {
- throw new InvalidInputException(
- this.bind("configure.duplicateCompliance", currentArg)); //$NON-NLS-1$
- }
- didSpecifyCompliance = true;
- this.options.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5);
- mode = DEFAULT;
- continue;
- }
- if (currentArg.equals("-1.6") || currentArg.equals("-6") || currentArg.equals("-6.0")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- if (didSpecifyCompliance) {
- throw new InvalidInputException(
- this.bind("configure.duplicateCompliance", currentArg)); //$NON-NLS-1$
- }
- didSpecifyCompliance = true;
- this.options.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_6);
- mode = DEFAULT;
- continue;
- }
- if (currentArg.equals("-1.7") || currentArg.equals("-7") || currentArg.equals("-7.0")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- if (didSpecifyCompliance) {
- throw new InvalidInputException(
- this.bind("configure.duplicateCompliance", currentArg)); //$NON-NLS-1$
- }
- didSpecifyCompliance = true;
- this.options.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_7);
- mode = DEFAULT;
- continue;
- }
- if (currentArg.equals("-d")) { //$NON-NLS-1$
- if (this.destinationPath != null) {
- StringBuffer errorMessage = new StringBuffer();
- errorMessage.append(currentArg);
- if ((index + 1) < argCount) {
- errorMessage.append(' ');
- errorMessage.append(newCommandLineArgs[index + 1]);
- }
- throw new InvalidInputException(
- this.bind("configure.duplicateOutputPath", errorMessage.toString())); //$NON-NLS-1$
- }
- mode = INSIDE_DESTINATION_PATH;
- continue;
- }
- if (currentArg.equals("-classpath") //$NON-NLS-1$
- || currentArg.equals("-cp")) { //$NON-NLS-1$
- mode = INSIDE_CLASSPATH_start;
- continue;
- }
- if (currentArg.equals("-bootclasspath")) {//$NON-NLS-1$
- if (bootclasspaths.size() > 0) {
- StringBuffer errorMessage = new StringBuffer();
- errorMessage.append(currentArg);
- if ((index + 1) < argCount) {
- errorMessage.append(' ');
- errorMessage.append(newCommandLineArgs[index + 1]);
- }
- throw new InvalidInputException(
- this.bind("configure.duplicateBootClasspath", errorMessage.toString())); //$NON-NLS-1$
- }
- mode = INSIDE_BOOTCLASSPATH_start;
- continue;
- }
- if (currentArg.equals("-sourcepath")) {//$NON-NLS-1$
- if (sourcepathClasspathArg != null) {
- StringBuffer errorMessage = new StringBuffer();
- errorMessage.append(currentArg);
- if ((index + 1) < argCount) {
- errorMessage.append(' ');
- errorMessage.append(newCommandLineArgs[index + 1]);
- }
- throw new InvalidInputException(
- this.bind("configure.duplicateSourcepath", errorMessage.toString())); //$NON-NLS-1$
- }
- mode = INSIDE_SOURCE_PATH_start;
- continue;
- }
- if (currentArg.equals("-extdirs")) {//$NON-NLS-1$
- if (extdirsClasspaths != null) {
- StringBuffer errorMessage = new StringBuffer();
- errorMessage.append(currentArg);
- if ((index + 1) < argCount) {
- errorMessage.append(' ');
- errorMessage.append(newCommandLineArgs[index + 1]);
- }
- throw new InvalidInputException(
- this.bind("configure.duplicateExtDirs", errorMessage.toString())); //$NON-NLS-1$
- }
- mode = INSIDE_EXT_DIRS;
- continue;
- }
- if (currentArg.equals("-endorseddirs")) { //$NON-NLS-1$
- if (endorsedDirClasspaths != null) {
- StringBuffer errorMessage = new StringBuffer();
- errorMessage.append(currentArg);
- if ((index + 1) < argCount) {
- errorMessage.append(' ');
- errorMessage.append(newCommandLineArgs[index + 1]);
- }
- throw new InvalidInputException(
- this.bind("configure.duplicateEndorsedDirs", errorMessage.toString())); //$NON-NLS-1$
- }
- mode = INSIDE_ENDORSED_DIRS;
- continue;
- }
- if (currentArg.equals("-progress")) { //$NON-NLS-1$
- mode = DEFAULT;
- this.showProgress = true;
- continue;
- }
- if (currentArg.equals("-proceedOnError")) { //$NON-NLS-1$
- mode = DEFAULT;
- this.proceedOnError = true;
- continue;
- }
- if (currentArg.equals("-time")) { //$NON-NLS-1$
- mode = DEFAULT;
- this.timing = true;
- continue;
- }
- if (currentArg.equals("-noErrors")) { //$NON-NLS-1$
- mode = DEFAULT;
- this.showError = false;
- continue;
- }
- if (currentArg.equals("-version") //$NON-NLS-1$
- || currentArg.equals("-v")) { //$NON-NLS-1$
- this.logger.logVersion(true);
- this.proceed = false;
- return;
- }
- if (currentArg.equals("-showversion")) { //$NON-NLS-1$
- printVersionRequired = true;
- mode = DEFAULT;
- continue;
- }
- if ("-deprecation".equals(currentArg)) { //$NON-NLS-1$
- didSpecifyDeprecation = true;
- this.options.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.WARNING);
- mode = DEFAULT;
- continue;
- }
- if (currentArg.equals("-help") || currentArg.equals("-?")) { //$NON-NLS-1$ //$NON-NLS-2$
- printUsageRequired = true;
- mode = DEFAULT;
- continue;
- }
- if (currentArg.equals("-help:warn") || //$NON-NLS-1$
- currentArg.equals("-?:warn")) { //$NON-NLS-1$
- printUsageRequired = true;
- usageSection = "misc.usage.warn"; //$NON-NLS-1$
- continue;
- }
- if (currentArg.equals("-noExit")) { //$NON-NLS-1$
- this.systemExitWhenFinished = false;
- mode = DEFAULT;
- continue;
- }
- if (currentArg.equals("-verbose")) { //$NON-NLS-1$
- this.verbose = true;
- mode = DEFAULT;
- continue;
- }
- if (currentArg.equals("-referenceInfo")) { //$NON-NLS-1$
- this.produceRefInfo = true;
- mode = DEFAULT;
- continue;
- }
- if (currentArg.equals("-inlineJSR")) { //$NON-NLS-1$
- mode = DEFAULT;
- this.options.put(
- CompilerOptions.OPTION_InlineJsr,
- CompilerOptions.ENABLED);
- continue;
- }
- if (currentArg.startsWith("-g")) { //$NON-NLS-1$
- mode = DEFAULT;
- String debugOption = currentArg;
- int length = currentArg.length();
- if (length == 2) {
- this.options.put(
- CompilerOptions.OPTION_LocalVariableAttribute,
- CompilerOptions.GENERATE);
- this.options.put(
- CompilerOptions.OPTION_LineNumberAttribute,
- CompilerOptions.GENERATE);
- this.options.put(
- CompilerOptions.OPTION_SourceFileAttribute,
- CompilerOptions.GENERATE);
- continue;
- }
- if (length > 3) {
- this.options.put(
- CompilerOptions.OPTION_LocalVariableAttribute,
- CompilerOptions.DO_NOT_GENERATE);
- this.options.put(
- CompilerOptions.OPTION_LineNumberAttribute,
- CompilerOptions.DO_NOT_GENERATE);
- this.options.put(
- CompilerOptions.OPTION_SourceFileAttribute,
- CompilerOptions.DO_NOT_GENERATE);
- if (length == 7 && debugOption.equals("-g:" + NONE)) //$NON-NLS-1$
- continue;
- StringTokenizer tokenizer =
- new StringTokenizer(debugOption.substring(3, debugOption.length()), ","); //$NON-NLS-1$
- while (tokenizer.hasMoreTokens()) {
- String token = tokenizer.nextToken();
- if (token.equals("vars")) { //$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_LocalVariableAttribute,
- CompilerOptions.GENERATE);
- } else if (token.equals("lines")) { //$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_LineNumberAttribute,
- CompilerOptions.GENERATE);
- } else if (token.equals("source")) { //$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_SourceFileAttribute,
- CompilerOptions.GENERATE);
- } else {
- throw new InvalidInputException(
- this.bind("configure.invalidDebugOption", debugOption)); //$NON-NLS-1$
- }
- }
- continue;
- }
- throw new InvalidInputException(
- this.bind("configure.invalidDebugOption", debugOption)); //$NON-NLS-1$
- }
- if (currentArg.startsWith("-nowarn")) { //$NON-NLS-1$
- disableWarnings();
- mode = DEFAULT;
- continue;
- }
- if (currentArg.startsWith("-warn")) { //$NON-NLS-1$
- mode = DEFAULT;
- String warningOption = currentArg;
- int length = currentArg.length();
- if (length == 10 && warningOption.equals("-warn:" + NONE)) { //$NON-NLS-1$
- disableWarnings();
- continue;
- }
- if (length <= 6) {
- throw new InvalidInputException(
- this.bind("configure.invalidWarningConfiguration", warningOption)); //$NON-NLS-1$
- }
- int warnTokenStart;
- boolean isEnabling;
- switch (warningOption.charAt(6)) {
- case '+' :
- warnTokenStart = 7;
- isEnabling = true;
- break;
- case '-' :
- warnTokenStart = 7;
- isEnabling = false; // mentionned warnings are disabled
- break;
- default:
- warnTokenStart = 6;
- // clear default warning level
- // but allow multiple warning option on the command line
- if (!didSpecifyWarnings) disableWarnings();
- isEnabling = true;
- }
-
- StringTokenizer tokenizer =
- new StringTokenizer(warningOption.substring(warnTokenStart, warningOption.length()), ","); //$NON-NLS-1$
- int tokenCounter = 0;
-
- if (didSpecifyDeprecation) { // deprecation could have also been set through -deprecation option
- this.options.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.WARNING);
- }
-
- while (tokenizer.hasMoreTokens()) {
- String token = tokenizer.nextToken();
- tokenCounter++;
- handleWarningToken(token, isEnabling, useEnableJavadoc);
- }
- if (tokenCounter == 0)
- throw new InvalidInputException(
- this.bind("configure.invalidWarningOption", currentArg)); //$NON-NLS-1$
- didSpecifyWarnings = true;
- continue;
- }
- if (currentArg.equals("-target")) { //$NON-NLS-1$
- mode = INSIDE_TARGET;
- continue;
- }
- if (currentArg.equals("-preserveAllLocals")) { //$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_PreserveUnusedLocal,
- CompilerOptions.PRESERVE);
- mode = DEFAULT;
- continue;
- }
- if (currentArg.equals("-enableJavadoc")) {//$NON-NLS-1$
- mode = DEFAULT;
- this.options.put(
- CompilerOptions.OPTION_DocCommentSupport,
- CompilerOptions.ENABLED);
- useEnableJavadoc = true;
- continue;
- }
- if (currentArg.equals("-Xemacs")) { //$NON-NLS-1$
- mode = DEFAULT;
- this.logger.setEmacs();
- continue;
- }
- // annotation processing
- if (currentArg.startsWith("-A")) { //$NON-NLS-1$
- mode = DEFAULT;
- continue;
- }
- if (currentArg.equals("-processorpath")) { //$NON-NLS-1$
- mode = INSIDE_PROCESSOR_PATH_start;
- continue;
- }
- if (currentArg.equals("-processor")) { //$NON-NLS-1$
- mode = INSIDE_PROCESSOR_start;
- continue;
- }
- if (currentArg.equals("-proc:only")) { //$NON-NLS-1$
- this.options.put(
- CompilerOptions.OPTION_GenerateClassFiles,
- CompilerOptions.DISABLED);
- mode = DEFAULT;
- continue;
- }
- if (currentArg.equals("-proc:none")) { //$NON-NLS-1$
- didSpecifyDisabledAnnotationProcessing = true;
- this.options.put(
- CompilerOptions.OPTION_Process_Annotations,
- CompilerOptions.DISABLED);
- mode = DEFAULT;
- continue;
- }
- if (currentArg.equals("-s")) { //$NON-NLS-1$
- mode = INSIDE_S_start;
- continue;
- }
- if (currentArg.equals("-XprintProcessorInfo") //$NON-NLS-1$
- || currentArg.equals("-XprintRounds")) { //$NON-NLS-1$
- mode = DEFAULT;
- continue;
- }
- // tolerated javac options - quietly filtered out
- if (currentArg.startsWith("-X")) { //$NON-NLS-1$
- mode = DEFAULT;
- continue;
- }
- if (currentArg.startsWith("-J")) { //$NON-NLS-1$
- mode = DEFAULT;
- continue;
- }
- if (currentArg.equals("-O")) { //$NON-NLS-1$
- mode = DEFAULT;
- continue;
- }
- if (currentArg.equals("-classNames")) { //$NON-NLS-1$
- mode = INSIDE_CLASS_NAMES;
- continue;
- }
- break;
- case INSIDE_TARGET :
- if (this.didSpecifyTarget) {
- throw new InvalidInputException(
- this.bind("configure.duplicateTarget", currentArg));//$NON-NLS-1$
- }
- this.didSpecifyTarget = true;
- if (currentArg.equals("1.1")) { //$NON-NLS-1$
- this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
- } else if (currentArg.equals("1.2")) { //$NON-NLS-1$
- this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_2);
- } else if (currentArg.equals("1.3")) { //$NON-NLS-1$
- this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_3);
- } else if (currentArg.equals("1.4")) { //$NON-NLS-1$
- this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4);
- } else if (currentArg.equals("1.5") || currentArg.equals("5") || currentArg.equals("5.0")) { //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
- this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5);
- } else if (currentArg.equals("1.6") || currentArg.equals("6") || currentArg.equals("6.0")) { //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
- this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_6);
- } else if (currentArg.equals("1.7") || currentArg.equals("7") || currentArg.equals("7.0")) { //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
- this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_7);
- } else if (currentArg.equals("jsr14")) { //$NON-NLS-1$
- this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_JSR14);
- } else {
- throw new InvalidInputException(this.bind("configure.targetJDK", currentArg)); //$NON-NLS-1$
- }
- mode = DEFAULT;
- continue;
- case INSIDE_LOG :
- this.log = currentArg;
- mode = DEFAULT;
- continue;
- case INSIDE_REPETITION :
- try {
- this.repetitions = Integer.parseInt(currentArg);
- if (this.repetitions <= 0) {
- throw new InvalidInputException(this.bind("configure.repetition", currentArg)); //$NON-NLS-1$
- }
- } catch (NumberFormatException e) {
- throw new InvalidInputException(this.bind("configure.repetition", currentArg)); //$NON-NLS-1$
- }
- mode = DEFAULT;
- continue;
- case INSIDE_MAX_PROBLEMS :
- try {
- this.maxProblems = Integer.parseInt(currentArg);
- if (this.maxProblems <= 0) {
- throw new InvalidInputException(this.bind("configure.maxProblems", currentArg)); //$NON-NLS-1$
- }
- this.options.put(CompilerOptions.OPTION_MaxProblemPerUnit, currentArg);
- } catch (NumberFormatException e) {
- throw new InvalidInputException(this.bind("configure.maxProblems", currentArg)); //$NON-NLS-1$
- }
- mode = DEFAULT;
- continue;
- case INSIDE_SOURCE :
- if (this.didSpecifySource) {
- throw new InvalidInputException(
- this.bind("configure.duplicateSource", currentArg));//$NON-NLS-1$
- }
- this.didSpecifySource = true;
- if (currentArg.equals("1.3")) { //$NON-NLS-1$
- this.options.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
- } else if (currentArg.equals("1.4")) { //$NON-NLS-1$
- this.options.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_4);
- } else if (currentArg.equals("1.5") || currentArg.equals("5") || currentArg.equals("5.0")) { //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
- this.options.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
- } else if (currentArg.equals("1.6") || currentArg.equals("6") || currentArg.equals("6.0")) { //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
- this.options.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_6);
- } else if (currentArg.equals("1.7") || currentArg.equals("7") || currentArg.equals("7.0")) { //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
- this.options.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_7);
- } else {
- throw new InvalidInputException(this.bind("configure.source", currentArg)); //$NON-NLS-1$
- }
- mode = DEFAULT;
- continue;
- case INSIDE_DEFAULT_ENCODING :
- if (didSpecifyDefaultEncoding) {
- throw new InvalidInputException(
- this.bind("configure.duplicateDefaultEncoding", currentArg)); //$NON-NLS-1$
- }
- try { // ensure encoding is supported
- new InputStreamReader(new ByteArrayInputStream(new byte[0]), currentArg);
- } catch (UnsupportedEncodingException e) {
- throw new InvalidInputException(
- this.bind("configure.unsupportedEncoding", currentArg)); //$NON-NLS-1$
- }
- this.options.put(CompilerOptions.OPTION_Encoding, currentArg);
- didSpecifyDefaultEncoding = true;
- mode = DEFAULT;
- continue;
- case INSIDE_DESTINATION_PATH :
- this.setDestinationPath(currentArg.equals(NONE) ? NONE : currentArg);
- mode = DEFAULT;
- continue;
- case INSIDE_CLASSPATH_start:
- mode = DEFAULT;
- index += processPaths(newCommandLineArgs, index, currentArg, classpaths);
- continue;
- case INSIDE_BOOTCLASSPATH_start:
- mode = DEFAULT;
- index += processPaths(newCommandLineArgs, index, currentArg, bootclasspaths);
- continue;
- case INSIDE_SOURCE_PATH_start:
- mode = DEFAULT;
- String[] sourcePaths = new String[1];
- index += processPaths(newCommandLineArgs, index, currentArg, sourcePaths);
- sourcepathClasspathArg = sourcePaths[0];
- continue;
- case INSIDE_EXT_DIRS:
- if (currentArg.indexOf("[-d") != -1) { //$NON-NLS-1$
- throw new InvalidInputException(
- this.bind("configure.unexpectedDestinationPathEntry", //$NON-NLS-1$
- "-extdir")); //$NON-NLS-1$
- }
- StringTokenizer tokenizer = new StringTokenizer(currentArg, File.pathSeparator, false);
- extdirsClasspaths = new ArrayList(DEFAULT_SIZE_CLASSPATH);
- while (tokenizer.hasMoreTokens())
- extdirsClasspaths.add(tokenizer.nextToken());
- mode = DEFAULT;
- continue;
- case INSIDE_ENDORSED_DIRS:
- if (currentArg.indexOf("[-d") != -1) { //$NON-NLS-1$
- throw new InvalidInputException(
- this.bind("configure.unexpectedDestinationPathEntry", //$NON-NLS-1$
- "-endorseddirs")); //$NON-NLS-1$
- } tokenizer = new StringTokenizer(currentArg, File.pathSeparator, false);
- endorsedDirClasspaths = new ArrayList(DEFAULT_SIZE_CLASSPATH);
- while (tokenizer.hasMoreTokens())
- endorsedDirClasspaths.add(tokenizer.nextToken());
- mode = DEFAULT;
- continue;
- case INSIDE_SOURCE_DIRECTORY_DESTINATION_PATH:
- if (currentArg.endsWith("]")) { //$NON-NLS-1$
- customDestinationPath = currentArg.substring(0,
- currentArg.length() - 1);
- } else {
- throw new InvalidInputException(
- this.bind("configure.incorrectDestinationPathEntry", //$NON-NLS-1$
- "[-d " + currentArg)); //$NON-NLS-1$
- }
- break;
- case INSIDE_PROCESSOR_PATH_start :
- // nothing to do here. This is consumed again by the AnnotationProcessorManager
- mode = DEFAULT;
- continue;
- case INSIDE_PROCESSOR_start :
- // nothing to do here. This is consumed again by the AnnotationProcessorManager
- mode = DEFAULT;
- continue;
- case INSIDE_S_start :
- // nothing to do here. This is consumed again by the AnnotationProcessorManager
- mode = DEFAULT;
- continue;
- case INSIDE_CLASS_NAMES :
- tokenizer = new StringTokenizer(currentArg, ","); //$NON-NLS-1$
- if (this.classNames == null) {
- this.classNames = new String[DEFAULT_SIZE_CLASSPATH];
- }
- while (tokenizer.hasMoreTokens()) {
- if (this.classNames.length == classCount) {
- // resize
- System.arraycopy(
- this.classNames,
- 0,
- (this.classNames = new String[classCount * 2]),
- 0,
- classCount);
- }
- this.classNames[classCount++] = tokenizer.nextToken();
- }
- mode = DEFAULT;
- continue;
- }
-
- // default is input directory, if no custom destination path exists
- if (customDestinationPath == null) {
- if (File.separatorChar != '/') {
- currentArg = currentArg.replace('/', File.separatorChar);
- }
- if (currentArg.endsWith("[-d")) { //$NON-NLS-1$
- currentSourceDirectory = currentArg.substring(0,
- currentArg.length() - 3);
- mode = INSIDE_SOURCE_DIRECTORY_DESTINATION_PATH;
- continue;
- } else {
- currentSourceDirectory = currentArg;
- }
- }
- File dir = new File(currentSourceDirectory);
- if (!dir.isDirectory()) {
- throw new InvalidInputException(
- this.bind("configure.unrecognizedOption", currentSourceDirectory)); //$NON-NLS-1$
- }
- String[] result = FileFinder.find(dir, SuffixConstants.SUFFIX_STRING_JAVA);
- if (NONE.equals(customDestinationPath)) {
- customDestinationPath = NONE; // ensure == comparison
- }
- if (this.filenames != null) {
- // some source files were specified explicitly
- int length = result.length;
- System.arraycopy(
- this.filenames,
- 0,
- (this.filenames = new String[length + filesCount]),
- 0,
- filesCount);
- System.arraycopy(
- this.encodings,
- 0,
- (this.encodings = new String[length + filesCount]),
- 0,
- filesCount);
- System.arraycopy(
- this.destinationPaths,
- 0,
- (this.destinationPaths = new String[length + filesCount]),
- 0,
- filesCount);
- System.arraycopy(result, 0, this.filenames, filesCount, length);
- for (int i = 0; i < length; i++) {
- this.encodings[filesCount + i] = customEncoding;
- this.destinationPaths[filesCount + i] = customDestinationPath;
- }
- filesCount += length;
- customEncoding = null;
- customDestinationPath = null;
- currentSourceDirectory = null;
- } else {
- this.filenames = result;
- filesCount = this.filenames.length;
- this.encodings = new String[filesCount];
- this.destinationPaths = new String[filesCount];
- for (int i = 0; i < filesCount; i++) {
- this.encodings[i] = customEncoding;
- this.destinationPaths[i] = customDestinationPath;
- }
- customEncoding = null;
- customDestinationPath = null;
- currentSourceDirectory = null;
- }
- mode = DEFAULT;
- continue;
- }
-
- if (printUsageRequired || (filesCount == 0 && classCount == 0)) {
- if (usageSection == null) {
- printUsage(); // default
- } else {
- printUsage(usageSection);
- }
- this.proceed = false;
- return;
- }
-
- if (this.log != null) {
- this.logger.setLog(this.log);
- } else {
- this.showProgress = false;
- }
- this.logger.logVersion(printVersionRequired);
-
- validateOptions(didSpecifyCompliance);
-
- // Enable annotation processing by default in batch mode when compliance is at least 1.6
- // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=185768
- if (!didSpecifyDisabledAnnotationProcessing
- && CompilerOptions.versionToJdkLevel(this.options.get(CompilerOptions.OPTION_Compliance)) >= ClassFileConstants.JDK1_6) {
- this.options.put(CompilerOptions.OPTION_Process_Annotations, CompilerOptions.ENABLED);
- }
-
- this.logger.logCommandLineArguments(newCommandLineArgs);
- this.logger.logOptions(this.options);
- if (this.repetitions == 0) {
- this.repetitions = 1;
- }
- if (this.repetitions >= 3 && this.timing) {
- this.times = new long[this.repetitions];
- this.timesCounter = 0;
- }
-
- if (filesCount != 0) {
- System.arraycopy(
- this.filenames,
- 0,
- (this.filenames = new String[filesCount]),
- 0,
- filesCount);
- }
-
- if (classCount != 0) {
- System.arraycopy(
- this.classNames,
- 0,
- (this.classNames = new String[classCount]),
- 0,
- classCount);
- }
-
- setPaths(bootclasspaths,
- sourcepathClasspathArg,
- sourcepathClasspaths,
- classpaths,
- extdirsClasspaths,
- endorsedDirClasspaths,
- customEncoding);
-}
-
-protected void disableWarnings() {
- Object[] entries = this.options.entrySet().toArray();
- for (int i = 0, max = entries.length; i < max; i++) {
- Map.Entry entry = (Map.Entry) entries[i];
- if (!(entry.getKey() instanceof String))
- continue;
- if (!(entry.getValue() instanceof String))
- continue;
- if (((String) entry.getValue()).equals(CompilerOptions.WARNING)) {
- this.options.put(entry.getKey(), CompilerOptions.IGNORE);
- }
- }
- this.options.put(CompilerOptions.OPTION_TaskTags, Util.EMPTY_STRING);
-}
-
-public String extractDestinationPathFromSourceFile(CompilationResult result) {
- ICompilationUnit compilationUnit = result.compilationUnit;
- if (compilationUnit != null) {
- char[] fileName = compilationUnit.getFileName();
- int lastIndex = CharOperation.lastIndexOf(java.io.File.separatorChar, fileName);
- if (lastIndex != -1) {
- final String outputPathName = new String(fileName, 0, lastIndex);
- final File output = new File(outputPathName);
- if (output.exists() && output.isDirectory()) {
- return outputPathName;
- }
- }
- }
- return System.getProperty("user.dir"); //$NON-NLS-1$
-}
-
-/*
- * Answer the component to which will be handed back compilation results from the compiler
- */
-public ICompilerRequestor getBatchRequestor() {
- return new ICompilerRequestor() {
- int lineDelta = 0;
- public void acceptResult(CompilationResult compilationResult) {
- if (compilationResult.lineSeparatorPositions != null) {
- int unitLineCount = compilationResult.lineSeparatorPositions.length;
- Main.this.lineCount += unitLineCount;
- this.lineDelta += unitLineCount;
- if (Main.this.showProgress && this.lineDelta > 2000) {
- // in -log mode, dump a dot every 2000 lines compiled
- Main.this.logger.logProgress();
- this.lineDelta = 0;
- }
- }
- Main.this.logger.startLoggingSource(compilationResult);
- if (Main.this.showError && (compilationResult.hasProblems() || compilationResult.hasTasks())) {
- int localErrorCount = Main.this.logger.logProblems(compilationResult.getAllProblems(), compilationResult.compilationUnit.getContents(), Main.this);
- // exit?
- if (Main.this.systemExitWhenFinished && !Main.this.proceedOnError && (localErrorCount > 0)) {
- // ensure dumping problems for enqueued units as well, since may contain primary errors (123476)
- CompilationUnitDeclaration[] queuedUnits = Main.this.batchCompiler.unitsToProcess;
- for (int i = 0, length = Main.this.batchCompiler.totalUnits; i < length; i++) {
- CompilationUnitDeclaration queuedUnit = queuedUnits[i];
- if (queuedUnit == null) continue;
- CompilationResult result = queuedUnit.compilationResult;
- if (result.hasProblems() && !result.hasBeenAccepted) {
- Main.this.logger.logProblems(result.getAllProblems(), result.compilationUnit.getContents(), Main.this);
- }
- }
- Main.this.logger.endLoggingSource();
- Main.this.logger.endLoggingSources();
- Main.this.logger.printStats();
- Main.this.logger.flush();
- Main.this.logger.close();
- System.exit(-1);
- }
- }
-// outputClassFiles(compilationResult);
- Main.this.logger.endLoggingSource();
- }
- };
-}
-
-/*
- * Build the set of compilation source units
- */
-public CompilationUnit[] getCompilationUnits()
- throws InvalidInputException {
- int fileCount = this.filenames.length;
- CompilationUnit[] units = new CompilationUnit[fileCount];
- HashtableOfObject knownFileNames = new HashtableOfObject(fileCount);
-
- String defaultEncoding = (String) this.options.get(CompilerOptions.OPTION_Encoding);
- if (Util.EMPTY_STRING.equals(defaultEncoding))
- defaultEncoding = null;
-
- for (int i = 0; i < fileCount; i++) {
- char[] charName = this.filenames[i].toCharArray();
- if (knownFileNames.get(charName) != null)
- throw new InvalidInputException(this.bind("unit.more", this.filenames[i])); //$NON-NLS-1$
- knownFileNames.put(charName, charName);
- File file = new File(this.filenames[i]);
- if (!file.exists())
- throw new InvalidInputException(this.bind("unit.missing", this.filenames[i])); //$NON-NLS-1$
- String encoding = this.encodings[i];
- if (encoding == null)
- encoding = defaultEncoding;
- units[i] = new CompilationUnit(null, this.filenames[i], encoding,
- this.destinationPaths[i]);
- }
- return units;
-}
-
-/*
- * Low-level API performing the actual compilation
- */
-public IErrorHandlingPolicy getHandlingPolicy() {
-
- // passes the initial set of files to the batch oracle (to avoid finding more than once the same units when case insensitive match)
- return new IErrorHandlingPolicy() {
- public boolean proceedOnErrors() {
- return Main.this.proceedOnError; // stop if there are some errors
- }
- public boolean stopOnFirstError() {
- return false;
- }
- };
-}
-/*
- * External API
- */
-public File getJavaHome() {
- if (!javaHomeChecked) {
- javaHomeChecked = true;
- String javaHome = System.getProperty("java.home");//$NON-NLS-1$
- if (javaHome != null) {
- this.javaHomeCache = new File(javaHome);
- if (!this.javaHomeCache.exists())
- this.javaHomeCache = null;
- }
- }
- return this.javaHomeCache;
-}
-
-public FileSystem getLibraryAccess() {
- return new FileSystem(this.checkedClasspaths, this.filenames);
-}
-
-/*
- * Low-level API performing the actual compilation
- */
-public IProblemFactory getProblemFactory() {
- return new DefaultProblemFactory(this.compilerLocale);
-}
-/*
- * External API
- */
-protected void initialize(PrintWriter outWriter,
- PrintWriter errWriter,
- boolean systemExit) {
- this.initialize(outWriter, errWriter, systemExit, null);
-}
-protected void initialize(PrintWriter outWriter,
- PrintWriter errWriter,
- boolean systemExit,
- Map customDefaultOptions) {
- this.logger = new Logger(this, outWriter, errWriter);
- this.proceed = true;
- this.out = outWriter;
- this.err = errWriter;
- this.systemExitWhenFinished = systemExit;
- this.options = new CompilerOptions().getMap();
- if (customDefaultOptions != null) {
- this.didSpecifySource = customDefaultOptions.get(CompilerOptions.OPTION_Source) != null;
- this.didSpecifyTarget = customDefaultOptions.get(CompilerOptions.OPTION_TargetPlatform) != null;
- for (Iterator iter = customDefaultOptions.entrySet().iterator(); iter.hasNext();) {
- Map.Entry entry = (Map.Entry) iter.next();
- this.options.put(entry.getKey(), entry.getValue());
- }
- } else {
- this.didSpecifySource = false;
- this.didSpecifyTarget = false;
- }
- this.classNames = null;
-}
-
-/*
- * Low-level API performing the actual compilation
- */
-public void performCompilation() throws InvalidInputException {
-
- this.startTime = System.currentTimeMillis();
-
- FileSystem environment = getLibraryAccess();
- this.compilerOptions = new CompilerOptions(this.options);
- this.compilerOptions.performMethodsFullRecovery = false;
- this.compilerOptions.performStatementsRecovery = false;
- this.batchCompiler =
- new Compiler(
- environment,
- getHandlingPolicy(),
- this.compilerOptions,
- getBatchRequestor(),
- getProblemFactory(),
- this.out);
-
- if (this.compilerOptions.complianceLevel >= ClassFileConstants.JDK1_6
- && this.compilerOptions.processAnnotations) {
- if (checkVMVersion(ClassFileConstants.JDK1_6)) {
- if (this.classNames != null) {
- this.batchCompiler.setBinaryTypes(processClassNames(this.batchCompiler.lookupEnvironment));
- }
- } else {
- // report a warning
- this.logger.logIncorrectVMVersionForAnnotationProcessing();
- }
- }
-
- // set the non-externally configurable options.
- this.compilerOptions.verbose = this.verbose;
- this.compilerOptions.produceReferenceInfo = this.produceRefInfo;
- try {
- this.logger.startLoggingSources();
- this.batchCompiler.compile(getCompilationUnits());
- } finally {
- this.logger.endLoggingSources();
- }
-
- if (this.extraProblems != null) {
- this.logger.loggingExtraProblems(this);
- this.extraProblems = null;
- }
- this.logger.printStats();
-
- // cleanup
- environment.cleanup();
-}
-protected ReferenceBinding[] processClassNames(LookupEnvironment environment) throws InvalidInputException {
- // check for .class file presence in case of apt processing
- int length = this.classNames.length;
- ReferenceBinding[] referenceBindings = new ReferenceBinding[length];
- for (int i = 0; i < length; i++) {
- String currentName = this.classNames[i];
- char[][] compoundName = null;
- if (currentName.indexOf('.') != -1) {
- // consider names with '.' as fully qualified names
- char[] typeName = currentName.toCharArray();
- compoundName = CharOperation.splitOn('.', typeName);
- } else {
- compoundName = new char[][] { currentName.toCharArray() };
- }
- ReferenceBinding type = environment.getType(compoundName);
- if (type != null && type.isValidBinding()) {
- if (type.isBinaryBinding()) {
- referenceBindings[i] = type;
- }
- } else {
- throw new InvalidInputException(
- this.bind("configure.invalidClassName", currentName));//$NON-NLS-1$
- }
- }
- return referenceBindings;
-}
-
-public void printUsage() {
- printUsage("misc.usage"); //$NON-NLS-1$
-}
-private void printUsage(String sectionID) {
- this.logger.logUsage(
- this.bind(
- sectionID,
- new String[] {
- System.getProperty("path.separator"), //$NON-NLS-1$
- this.bind("compiler.name"), //$NON-NLS-1$
- this.bind("compiler.version"), //$NON-NLS-1$
- this.bind("compiler.copyright") //$NON-NLS-1$
- }));
- this.logger.flush();
-}
-/*
- * External API
- */
-public void processPathEntries(final int defaultSize, final ArrayList paths,
- final String currentPath, String customEncoding, boolean isSourceOnly,
- boolean rejectDestinationPathOnJars)
- throws InvalidInputException {
- String currentClasspathName = null;
- String currentDestinationPath = null;
- ArrayList currentRuleSpecs = new ArrayList(defaultSize);
- StringTokenizer tokenizer = new StringTokenizer(currentPath,
- File.pathSeparator + "[]", true); //$NON-NLS-1$
- ArrayList tokens = new ArrayList();
- while (tokenizer.hasMoreTokens()) {
- tokens.add(tokenizer.nextToken());
- }
- // state machine
- final int start = 0;
- final int readyToClose = 1;
- // 'path' 'path1[rule];path2'
- final int readyToCloseEndingWithRules = 2;
- // 'path[rule]' 'path1;path2[rule]'
- final int readyToCloseOrOtherEntry = 3;
- // 'path[rule];' 'path;' 'path1;path2;'
- final int rulesNeedAnotherRule = 4;
- // 'path[rule1;'
- final int rulesStart = 5;
- // 'path[' 'path1;path2['
- final int rulesReadyToClose = 6;
- // 'path[rule' 'path[rule1;rule2'
- final int destinationPathReadyToClose = 7;
- // 'path[-d bin'
- final int readyToCloseEndingWithDestinationPath = 8;
- // 'path[-d bin]' 'path[rule][-d bin]'
- final int destinationPathStart = 9;
- // 'path[rule]['
- final int bracketOpened = 10;
- // '.*[.*'
- final int bracketClosed = 11;
- // '.*([.*])+'
-
- final int error = 99;
- int state = start;
- String token = null;
- int cursor = 0, tokensNb = tokens.size(), bracket = -1;
- while (cursor < tokensNb && state != error) {
- token = (String) tokens.get(cursor++);
- if (token.equals(File.pathSeparator)) {
- switch (state) {
- case start:
- case readyToCloseOrOtherEntry:
- case bracketOpened:
- break;
- case readyToClose:
- case readyToCloseEndingWithRules:
- case readyToCloseEndingWithDestinationPath:
- state = readyToCloseOrOtherEntry;
- addNewEntry(paths, currentClasspathName, currentRuleSpecs,
- customEncoding, currentDestinationPath, isSourceOnly,
- rejectDestinationPathOnJars);
- currentRuleSpecs.clear();
- break;
- case rulesReadyToClose:
- state = rulesNeedAnotherRule;
- break;
- case destinationPathReadyToClose:
- throw new InvalidInputException(
- this.bind("configure.incorrectDestinationPathEntry", //$NON-NLS-1$
- currentPath));
- case bracketClosed:
- cursor = bracket + 1;
- state = rulesStart;
- break;
- default:
- state = error;
- }
- } else if (token.equals("[")) { //$NON-NLS-1$
- switch (state) {
- case start:
- currentClasspathName = ""; //$NON-NLS-1$
- case readyToClose:
- bracket = cursor - 1;
- case bracketClosed:
- state = bracketOpened;
- break;
- case readyToCloseEndingWithRules:
- state = destinationPathStart;
- break;
- case readyToCloseEndingWithDestinationPath:
- state = rulesStart;
- break;
- case bracketOpened:
- default:
- state = error;
- }
- } else if (token.equals("]")) { //$NON-NLS-1$
- switch (state) {
- case rulesReadyToClose:
- state = readyToCloseEndingWithRules;
- break;
- case destinationPathReadyToClose:
- state = readyToCloseEndingWithDestinationPath;
- break;
- case bracketOpened:
- state = bracketClosed;
- break;
- case bracketClosed:
- default:
- state = error;
- }
- } else {
- // regular word
- switch (state) {
- case start:
- case readyToCloseOrOtherEntry:
- state = readyToClose;
- currentClasspathName = token;
- break;
- case rulesStart:
- if (token.startsWith("-d ")) { //$NON-NLS-1$
- if (currentDestinationPath != null) {
- throw new InvalidInputException(
- this.bind("configure.duplicateDestinationPathEntry", //$NON-NLS-1$
- currentPath));
- }
- currentDestinationPath = token.substring(3).trim();
- state = destinationPathReadyToClose;
- break;
- } // else we proceed with a rule
- case rulesNeedAnotherRule:
- if (currentDestinationPath != null) {
- throw new InvalidInputException(
- this.bind("configure.accessRuleAfterDestinationPath", //$NON-NLS-1$
- currentPath));
- }
- state = rulesReadyToClose;
- currentRuleSpecs.add(token);
- break;
- case destinationPathStart:
- if (!token.startsWith("-d ")) { //$NON-NLS-1$
- state = error;
- } else {
- currentDestinationPath = token.substring(3).trim();
- state = destinationPathReadyToClose;
- }
- break;
- case bracketClosed:
- for (int i = bracket; i < cursor ; i++) {
- currentClasspathName += (String) tokens.get(i);
- }
- state = readyToClose;
- break;
- case bracketOpened:
- break;
- default:
- state = error;
- }
- }
- if (state == bracketClosed && cursor == tokensNb) {
- cursor = bracket + 1;
- state = rulesStart;
- }
- }
- switch(state) {
- case readyToCloseOrOtherEntry:
- break;
- case readyToClose:
- case readyToCloseEndingWithRules:
- case readyToCloseEndingWithDestinationPath:
- addNewEntry(paths, currentClasspathName, currentRuleSpecs,
- customEncoding, currentDestinationPath, isSourceOnly,
- rejectDestinationPathOnJars);
- break;
- case bracketOpened:
- case bracketClosed:
- default :
- // we go on anyway
- if (currentPath.length() != 0) {
- this.logger.logIncorrectClasspath(currentPath);
- }
- }
-}
-
-private int processPaths(String[] args, int index, String currentArg, ArrayList paths) throws InvalidInputException {
- int localIndex = index;
- int count = 0;
- for (int i = 0, max = currentArg.length(); i < max; i++) {
- switch(currentArg.charAt(i)) {
- case '[' :
- count++;
- break;
- case ']' :
- count--;
- break;
- }
- }
- if (count == 0) {
- paths.add(currentArg);
- } else if (count > 1) {
- throw new InvalidInputException(
- this.bind("configure.unexpectedBracket", //$NON-NLS-1$
- currentArg));
- } else {
- StringBuffer currentPath = new StringBuffer(currentArg);
- while (true) {
- if (localIndex >= args.length) {
- throw new InvalidInputException(
- this.bind("configure.unexpectedBracket", //$NON-NLS-1$
- currentArg));
- }
- localIndex++;
- String nextArg = args[localIndex];
- for (int i = 0, max = nextArg.length(); i < max; i++) {
- switch(nextArg.charAt(i)) {
- case '[' :
- if (count > 1) {
- throw new InvalidInputException(
- this.bind("configure.unexpectedBracket", //$NON-NLS-1$
- nextArg));
- }
- count++;
- break;
- case ']' :
- count--;
- break;
- }
- }
- if (count == 0) {
- currentPath.append(' ');
- currentPath.append(nextArg);
- paths.add(currentPath.toString());
- return localIndex - index;
- } else if (count < 0) {
- throw new InvalidInputException(
- this.bind("configure.unexpectedBracket", //$NON-NLS-1$
- nextArg));
- } else {
- currentPath.append(' ');
- currentPath.append(nextArg);
- }
- }
-
- }
- return localIndex - index;
-}
-private int processPaths(String[] args, int index, String currentArg, String[] paths) throws InvalidInputException {
- int localIndex = index;
- int count = 0;
- for (int i = 0, max = currentArg.length(); i < max; i++) {
- switch(currentArg.charAt(i)) {
- case '[' :
- count++;
- break;
- case ']' :
- count--;
- break;
- }
- }
- if (count == 0) {
- paths[0] = currentArg;
- } else {
- StringBuffer currentPath = new StringBuffer(currentArg);
- while (true) {
- localIndex++;
- if (localIndex >= args.length) {
- throw new InvalidInputException(
- this.bind("configure.unexpectedBracket", //$NON-NLS-1$
- currentArg));
- }
- String nextArg = args[localIndex];
- for (int i = 0, max = nextArg.length(); i < max; i++) {
- switch(nextArg.charAt(i)) {
- case '[' :
- if (count > 1) {
- throw new InvalidInputException(
- this.bind("configure.unexpectedBracket", //$NON-NLS-1$
- currentArg));
- }
- count++;
- break;
- case ']' :
- count--;
- break;
- }
- }
- if (count == 0) {
- currentPath.append(' ');
- currentPath.append(nextArg);
- paths[0] = currentPath.toString();
- return localIndex - index;
- } else if (count < 0) {
- throw new InvalidInputException(
- this.bind("configure.unexpectedBracket", //$NON-NLS-1$
- currentArg));
- } else {
- currentPath.append(' ');
- currentPath.append(nextArg);
- }
- }
-
- }
- return localIndex - index;
-}
-/**
- * Creates a NLS catalog for the given locale.
- */
-public void relocalize() {
- relocalize(Locale.getDefault());
-}
-
-private void relocalize(Locale locale) {
- this.compilerLocale = locale;
- try {
- this.bundle = ResourceBundleFactory.getBundle(locale);
- } catch(MissingResourceException e) {
- System.out.println("Missing resource : " + Main.bundleName.replace('.', '/') + ".properties for locale " + locale); //$NON-NLS-1$//$NON-NLS-2$
- throw e;
- }
-}
-/*
- * External API
- */
-public void setLocale(Locale locale) {
- relocalize(locale);
-}
-/*
- * External API
- */
-protected void setDestinationPath(String dest) {
- this.destinationPath = dest;
-}
-/*
- * External API
- */
-protected void setPaths(ArrayList bootclasspaths,
- String sourcepathClasspathArg,
- ArrayList sourcepathClasspaths,
- ArrayList classpaths,
- ArrayList extdirsClasspaths,
- ArrayList endorsedDirClasspaths,
- String customEncoding) throws InvalidInputException {
-
- // process bootclasspath, classpath and sourcepaths
- bootclasspaths = handleBootclasspath(bootclasspaths, customEncoding);
-
- classpaths = handleClasspath(classpaths, customEncoding);
-
- if (sourcepathClasspathArg != null) {
- processPathEntries(DEFAULT_SIZE_CLASSPATH, sourcepathClasspaths,
- sourcepathClasspathArg, customEncoding, true, false);
- }
-
- /*
- * Feed endorsedDirClasspath according to:
- * - -extdirs first if present;
- * - else java.ext.dirs if defined;
- * - else default extensions directory for the platform.
- */
- extdirsClasspaths = handleExtdirs(extdirsClasspaths);
-
- endorsedDirClasspaths = handleEndorseddirs(endorsedDirClasspaths);
-
- /*
- * Concatenate classpath entries
- * We put the bootclasspath at the beginning of the classpath
- * entries, followed by the extension libraries, followed by
- * the sourcepath followed by the classpath. All classpath
- * entries are searched for both sources and binaries except
- * the sourcepath entries which are searched for sources only.
- */
-// bootclasspaths.addAll(endorsedDirClasspaths);
-// bootclasspaths.addAll(extdirsClasspaths);
- bootclasspaths.addAll(sourcepathClasspaths);
- bootclasspaths.addAll(classpaths);
- classpaths = bootclasspaths;
- classpaths = FileSystem.ClasspathNormalizer.normalize(classpaths);
- this.checkedClasspaths = new FileSystem.Classpath[classpaths.size()];
- classpaths.toArray(this.checkedClasspaths);
- this.logger.logClasspath(this.checkedClasspaths);
-}
-protected void validateOptions(boolean didSpecifyCompliance) throws InvalidInputException {
- if (didSpecifyCompliance) {
- Object version = this.options.get(CompilerOptions.OPTION_Compliance);
- if (CompilerOptions.VERSION_1_3.equals(version)) {
- if (!this.didSpecifySource) this.options.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
- if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
- } else if (CompilerOptions.VERSION_1_4.equals(version)) {
- if (this.didSpecifySource) {
- Object source = this.options.get(CompilerOptions.OPTION_Source);
- if (CompilerOptions.VERSION_1_3.equals(source)) {
- if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_2);
- } else if (CompilerOptions.VERSION_1_4.equals(source)) {
- if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4);
- }
- } else {
- this.options.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
- if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_2);
- }
- } else if (CompilerOptions.VERSION_1_5.equals(version)) {
- if (this.didSpecifySource) {
- Object source = this.options.get(CompilerOptions.OPTION_Source);
- if (CompilerOptions.VERSION_1_3.equals(source)
- || CompilerOptions.VERSION_1_4.equals(source)) {
- if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4);
- } else if (CompilerOptions.VERSION_1_5.equals(source)) {
- if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5);
- }
- } else {
- this.options.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
- if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5);
- }
- } else if (CompilerOptions.VERSION_1_6.equals(version)) {
- if (this.didSpecifySource) {
- Object source = this.options.get(CompilerOptions.OPTION_Source);
- if (CompilerOptions.VERSION_1_3.equals(source)
- || CompilerOptions.VERSION_1_4.equals(source)) {
- if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4);
- } else if (CompilerOptions.VERSION_1_5.equals(source)
- || CompilerOptions.VERSION_1_6.equals(source)) {
- if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_6);
- }
- } else {
- this.options.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_6);
- if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_6);
- }
- } else if (CompilerOptions.VERSION_1_7.equals(version)) {
- if (this.didSpecifySource) {
- Object source = this.options.get(CompilerOptions.OPTION_Source);
- if (CompilerOptions.VERSION_1_3.equals(source)
- || CompilerOptions.VERSION_1_4.equals(source)) {
- if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4);
- } else if (CompilerOptions.VERSION_1_5.equals(source)
- || CompilerOptions.VERSION_1_6.equals(source)) {
- if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_6);
- } else if (CompilerOptions.VERSION_1_7.equals(source)) {
- if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_7);
- }
- } else {
- this.options.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_7);
- if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_7);
- }
- }
- } else if (this.didSpecifySource) {
- Object version = this.options.get(CompilerOptions.OPTION_Source);
- // default is source 1.3 target 1.2 and compliance 1.4
- if (CompilerOptions.VERSION_1_4.equals(version)) {
- if (!didSpecifyCompliance) this.options.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_4);
- if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4);
- } else if (CompilerOptions.VERSION_1_5.equals(version)) {
- if (!didSpecifyCompliance) this.options.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5);
- if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5);
- } else if (CompilerOptions.VERSION_1_6.equals(version)) {
- if (!didSpecifyCompliance) this.options.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_6);
- if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_6);
- } else if (CompilerOptions.VERSION_1_7.equals(version)) {
- if (!didSpecifyCompliance) this.options.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_7);
- if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_7);
- }
- }
-
- final Object sourceVersion = this.options.get(CompilerOptions.OPTION_Source);
- final Object compliance = this.options.get(CompilerOptions.OPTION_Compliance);
- if (sourceVersion.equals(CompilerOptions.VERSION_1_7)
- && CompilerOptions.versionToJdkLevel(compliance) < ClassFileConstants.JDK1_7) {
- // compliance must be 1.7 if source is 1.7
- throw new InvalidInputException(this.bind("configure.incompatibleComplianceForSource", (String)this.options.get(CompilerOptions.OPTION_Compliance), CompilerOptions.VERSION_1_7)); //$NON-NLS-1$
- } else if (sourceVersion.equals(CompilerOptions.VERSION_1_6)
- && CompilerOptions.versionToJdkLevel(compliance) < ClassFileConstants.JDK1_6) {
- // compliance must be 1.6 if source is 1.6
- throw new InvalidInputException(this.bind("configure.incompatibleComplianceForSource", (String)this.options.get(CompilerOptions.OPTION_Compliance), CompilerOptions.VERSION_1_6)); //$NON-NLS-1$
- } else if (sourceVersion.equals(CompilerOptions.VERSION_1_5)
- && CompilerOptions.versionToJdkLevel(compliance) < ClassFileConstants.JDK1_5) {
- // compliance must be 1.5 if source is 1.5
- throw new InvalidInputException(this.bind("configure.incompatibleComplianceForSource", (String)this.options.get(CompilerOptions.OPTION_Compliance), CompilerOptions.VERSION_1_5)); //$NON-NLS-1$
- } else if (sourceVersion.equals(CompilerOptions.VERSION_1_4)
- && CompilerOptions.versionToJdkLevel(compliance) < ClassFileConstants.JDK1_4) {
- // compliance must be 1.4 if source is 1.4
- throw new InvalidInputException(this.bind("configure.incompatibleComplianceForSource", (String)this.options.get(CompilerOptions.OPTION_Compliance), CompilerOptions.VERSION_1_4)); //$NON-NLS-1$
- }
-
- // check and set compliance/source/target compatibilities
- if (this.didSpecifyTarget) {
- final Object targetVersion = this.options.get(CompilerOptions.OPTION_TargetPlatform);
- // tolerate jsr14 target
- if (CompilerOptions.VERSION_JSR14.equals(targetVersion)) {
- // expecting source >= 1.5
- if (CompilerOptions.versionToJdkLevel(sourceVersion) < ClassFileConstants.JDK1_5) {
- throw new InvalidInputException(this.bind("configure.incompatibleTargetForGenericSource", (String) targetVersion, (String) sourceVersion)); //$NON-NLS-1$
- }
- } else {
- // target must be 1.7 if source is 1.7
- if (CompilerOptions.versionToJdkLevel(sourceVersion) >= ClassFileConstants.JDK1_7
- && CompilerOptions.versionToJdkLevel(targetVersion) < ClassFileConstants.JDK1_7){
- throw new InvalidInputException(this.bind("configure.incompatibleTargetForSource", (String) targetVersion, CompilerOptions.VERSION_1_7)); //$NON-NLS-1$
- }
- // target must be 1.6 if source is 1.6
- if (CompilerOptions.versionToJdkLevel(sourceVersion) >= ClassFileConstants.JDK1_6
- && CompilerOptions.versionToJdkLevel(targetVersion) < ClassFileConstants.JDK1_6){
- throw new InvalidInputException(this.bind("configure.incompatibleTargetForSource", (String) targetVersion, CompilerOptions.VERSION_1_6)); //$NON-NLS-1$
- }
- // target must be 1.5 if source is 1.5
- if (CompilerOptions.versionToJdkLevel(sourceVersion) >= ClassFileConstants.JDK1_5
- && CompilerOptions.versionToJdkLevel(targetVersion) < ClassFileConstants.JDK1_5){
- throw new InvalidInputException(this.bind("configure.incompatibleTargetForSource", (String) targetVersion, CompilerOptions.VERSION_1_5)); //$NON-NLS-1$
- }
- // target must be 1.4 if source is 1.4
- if (CompilerOptions.versionToJdkLevel(sourceVersion) >= ClassFileConstants.JDK1_4
- && CompilerOptions.versionToJdkLevel(targetVersion) < ClassFileConstants.JDK1_4){
- throw new InvalidInputException(this.bind("configure.incompatibleTargetForSource", (String) targetVersion, CompilerOptions.VERSION_1_4)); //$NON-NLS-1$
- }
- // target cannot be greater than compliance level
- if (CompilerOptions.versionToJdkLevel(compliance) < CompilerOptions.versionToJdkLevel(targetVersion)){
- throw new InvalidInputException(this.bind("configure.incompatibleComplianceForTarget", (String)this.options.get(CompilerOptions.OPTION_Compliance), (String) targetVersion)); //$NON-NLS-1$
- }
- }
- }
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/batch/messages.properties b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/batch/messages.properties
deleted file mode 100644
index f34d88dc..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/batch/messages.properties
+++ /dev/null
@@ -1,290 +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
-###############################################################################
-### JavaBatchCompiler messages.
-
-### compiler
-#Format: compiler.name = word1 word2 word3
-compiler.name = Eclipse JavaScript Validator
-#Format: compiler.version = 0.XXX[, other words (don't forget the comma if adding other words)]
-compiler.version = 0.735, 3.3.0 milestone-5
-compiler.copyright = Copyright IBM Corp 2000, 2008. All rights reserved.
-
-### progress
-progress.compiling = Compiling
-
-### compile
-compile.repetition = [repetition {0}/{1}]
-compile.instantTime = [validated {0} lines in {1} ms: {2} lines/s]
-compile.averageTime = [average, excluding min-max {0} lines in {1} ms: {2} lines/s]
-compile.totalTime = [total validation time: {0}]
-compile.oneProblem = 1 problem ({0})
-compile.severalProblemsErrorsOrWarnings = {0} problems ({1})
-compile.severalProblemsErrorsAndWarnings = {0} problems ({1}, {2})
-compile.oneError = 1 error
-compile.severalErrors = {0} errors
-compile.oneWarning = 1 warning
-compile.severalWarnings = {0} warnings
-compile.oneClassFileGenerated = [1 .class file generated]
-compile.severalClassFilesGenerated = [{0} .class files generated]
-
-### configure
-configure.requiresJDK1.2orAbove = Need to use a JVM >= 1.2
-configure.duplicateLog = duplicate log specification: {0}
-configure.duplicateRepeat = duplicate repeat specification: {0}
-configure.duplicateMaxProblems = duplicate max problems specification: {0}
-configure.duplicateCompliance = duplicate compliance setting specification: {0}
-configure.duplicateSource = duplicate source compliance setting specification: {0}
-configure.duplicateTarget = duplicate target compliance setting specification: {0}
-configure.source = source level should be comprised in between ''1.3'' and ''1.6'' (or ''5'', ''5.0'', ..., ''7'' or ''7.0''): {0}
-configure.duplicateOutputPath = duplicate output path specification: {0}
-configure.duplicateBootClasspath = duplicate bootclasspath specification: {0}
-configure.duplicateExtDirs = duplicate extdirs specification: {0}
-configure.duplicateSourcepath = duplicate sourcepath specification: {0}
-configure.invalidDebugOption = invalid debug option: {0}
-configure.invalidWarningConfiguration = invalid warning configuration: {0}
-configure.invalidWarning = invalid warning: {0}
-configure.invalidWarningOption = invalid warning option: {0}
-configure.targetJDK = target level should be comprised in between ''1.1'' and ''1.7'' (or ''5'', ''5.0'', ..., ''7'' or ''7.0''): {0}
-configure.incompatibleTargetForSource = Target level ''{0}'' is incompatible with source level ''{1}''. A target level ''{1}'' or better is required
-configure.incompatibleTargetForGenericSource = Target level ''{0}'' is incompatible with source level ''{1}''. A source level ''1.5'' or better is required
-configure.incompatibleComplianceForSource = Compliance level ''{0}'' is incompatible with source level ''{1}''. A compliance level ''{1}'' or better is required
-configure.incompatibleComplianceForTarget = Compliance level ''{0}'' is incompatible with target level ''{1}''. A compliance level ''{1}'' or better is required
-configure.repetition = repetition must be a positive integer: {0}
-configure.maxProblems = max problems must be a positive integer: {0}
-configure.directoryNotExist = directory does not exist: {0}
-configure.noClasspath = no classpath defined, using default directory instead
-configure.incorrectClasspath = incorrect classpath: {0}
-configure.invalidexpansionargumentname = expansion argument file {0} does not exist or cannot be read
-configure.cannotOpenLog = cannot open .log file: {0}
-configure.unexpectedCustomEncoding = unexpected custom encoding specification: {0}[{1}]
-configure.unsupportedEncoding = unsupported encoding format: {0}
-configure.duplicateDefaultEncoding = duplicate default encoding format specification: {0}
-configure.invalidTaskTag ={0} is an invalid task tag
-configure.incorrectExtDirsEntry = incorrect ext dir entry; {0} must be a directory
-configure.incorrectEndorsedDirsEntry = incorrect endorsed dir entry; {0} must be a directory
-configure.duplicateEndorsedDirs = duplicate endorseddirs specification: {0}
-configure.incorrectDestinationPathEntry = incorrect destination path entry: {0}
-configure.unexpectedBracket = unexpected bracket: {0}
-configure.unexpectedDestinationPathEntry = unexpected destination path entry in {0} option
-configure.unexpectedDestinationPathEntryFile = unexpected destination path entry for file: {0}
-configure.accessRuleAfterDestinationPath = access rules cannot follow destination path entries: {0}
-configure.duplicateDestinationPathEntry = duplicate destination path entry in {0} option
-
-### requestor
-requestor.error = {0}. ERROR in {1}
-requestor.warning = {0}. WARNING in {1}
-requestor.notRetrieveErrorMessage = Cannot retrieve the error message for {0}
-
-### EMACS STYLE
-output.emacs.error=error
-output.emacs.warning=warning
-
-### unit
-unit.more = File {0} is specified more than once
-unit.missing = File {0} is missing
-
-### output
-output.noClassFileCreated = No .class file created for file {1} in {0} because of an IOException: {2}
-
-### miscellaneous
-misc.version = {0} {1}, {2}
-misc.usage = {1} {2}\n\
-{3}\n\
-\ \n\
-\ Usage: <options> <source files | directories>\n\
-\ If directories are specified, then their source contents are compiled.\n\
-\ Possible options are listed below. Options enabled by default are prefixed\n\
-\ with ''+''.\n\
-\ \n\
-\ Classpath options:\n\
-\ -cp -classpath <directories and zip/jar files separated by {0}>\n\
-\ specify location for application classes and sources.\n\
-\ Each directory or file can specify access rules for\n\
-\ types between ''['' and '']'' (e.g. [-X] to forbid\n\
-\ access to type X, [~X] to discourage access to type X,\n\
-\ [+p/X:-p/*] to forbid access to all types in package p\n\
-\ but allow access to p/X)\n\
-\ -bootclasspath <directories and zip/jar files separated by {0}>\n\
-\ specify location for system classes. Each directory or\n\
-\ file can specify access rules for types between ''[''\n\
-\ and '']''\n\
-\ -sourcepath <directories and zip/jar files separated by {0}>\n\
-\ specify location for application sources. Each directory\n\
-\ or file can specify access rules for types between ''[''\n\
-\ and '']''. Each directory can further specify a specific\n\
-\ destination directory using a ''-d'' option between ''[''\n\
-\ and '']''; this overrides the general ''-d'' option.\n\
-\ .class files created from source files contained in a\n\
-\ jar file are put in the user.dir folder in case no\n\
-\ general ''-d'' option is specified. zip/jar files cannot\n\
-\ override the general ''-d'' option\n\
-\ -extdirs <directories separated by {0}>\n\
-\ specify location for extension zip/jar files\n\
-\ -endorseddirs <directories separated by {0}>\n\
-\ specify location for endorsed zip/jar files\n\
-\ -d <dir> destination directory (if omitted, no directory is\n\
-\ created); this option can be overridden per source\n\
-\ directory\n\
-\ -d none generate no .class files\n\
-\ -encoding <enc> specify custom encoding for all sources. Each\n\
-\ file/directory can override it when suffixed with\n\
-\ ''[''<enc>'']'' (e.g. X.js[utf8])\n\
-\ \n\
-\ Compliance options:\n\
-\ -1.3 use 1.3 compliance (-source 1.3 -target 1.1)\n\
-\ -1.4 + use 1.4 compliance (-source 1.3 -target 1.2)\n\
-\ -1.5 -5 -5.0 use 1.5 compliance (-source 1.5 -target 1.5)\n\
-\ -1.6 -6 -6.0 use 1.6 compliance (-source 1.6 -target 1.6)\n\
-\ -1.7 -7 -7.0 use 1.7 compliance (-source 1.7 -target 1.7)\n\
-\ -source <version> set source level: 1.3 to 1.7 (or 5, 5.0, etc)\n\
-\ -target <version> set classfile target: 1.1 to 1.7 (or 5, 5.0, etc)\n\
-\ \n\
-\ Warning options:\n\
-\ -deprecation + deprecation outside deprecated code (equivalent to\n\
-\ -warn:+deprecation)\n\
-\ -nowarn -warn:none disable all warnings\n\
-\ -?:warn -help:warn display advanced warning options\n\
-\ \n\
-\ Debug options:\n\
-\ -g[:lines,vars,source] custom debug info\n\
-\ -g:lines,source + both lines table and source debug info\n\
-\ -g all debug info\n\
-\ -g:none no debug info\n\
-\ -preserveAllLocals preserve unused local vars for debug purpose\n\
-\ \n\
-\ Annotation processing options:\n\
-\ These options are meaningful only in a 1.6 environment.\n\
-\ -Akey[=value] annotation processors options that are made to\n\
-\ annotation processors. key are identifiers separated\n\
-\ by ''.''.\n\
-\ -processorpath <directories and zip/jar files separated by {0}>\n\
-\ specify locations where to find annotation processors\n\
-\ If this option is not used, the classpath will be\n\
-\ searched for processors.\n\
-\ -processor <class1[,class2,...]>\n\
-\ Qualified names of the annotation processors to run.\n\
-\ This bypasses the default annotation discovery process\n\
-\ -proc:only run annotation processors, but do not compile\n\
-\ -proc:none perform compilation but do not run annotation\n\
-\ processors\n\
-\ -s <dir> specify a directory where to put the generated source\n\
-\ files\n\
-\ -XprintProcessorInfo print information about which annotations and which\n\
-\ elements a processor is asked to process\n\
-\ -XprintRounds print information about annotation processing rounds.\n\
-\ \n\
-\ Advanced options:\n\
-\ @<file> read command line arguments from file\n\
-\ -maxProblems <n> max number of problems per JavaScript file (100 by\n\
-\ default)\n\
-\ -log <file> log to a file. If the file extension is ''.xml'', then\n\
-\ the log will be a xml file.\n\
-\ -proceedOnError do not stop at first error, dumping class files with\n\
-\ problem methods\n\
-\ -verbose enable verbose output\n\
-\ -referenceInfo compute reference info\n\
-\ -progress show progress (only in -log mode)\n\
-\ -time display speed information \n\
-\ -noExit do not call System.exit(n) at end of compilation (n==0\n\
-\ if no error)\n\
-\ -repeat <n> repeat compilation process <n> times for perf analysis\n\
-\ -inlineJSR inline JSR bytecode (implicit if target >= 1.5)\n\
-\ -enablejsDoc consider references in jsDoc\n\
-\ -Xemacs used to enable emacs-style output in the console.\n\
-\ It does not affect the xml log output\n\
-\ \n\
-\ -? -help print this help message\n\
-\ -v -version print compiler version\n\
-\ -showversion print compiler version and continue\n\
-\ \n\
-\ Ignored options:\n\
-\ -J<option> pass option to virtual machine (ignored)\n\
-\ -X<option> specify non-standard option (ignored\n\
-\ except for listed -X options)\n\
-\ -X print non-standard options and exit (ignored)\n\
-\ -O optimize for execution time (ignored)\n
-misc.usage.warn = {1} {2}\n\
-{3}\n\
-\ \n\
-\ Warning options:\n\
-\ -deprecation + deprecation outside deprecated code\n\
-\ -nowarn -warn:none disable all warnings\n\
-\ -warn:<warnings separated by ,> enable exactly the listed warnings\n\
-\ -warn:+<warnings separated by ,> enable additional warnings\n\
-\ -warn:-<warnings separated by ,> disable specific warnings\n\
-\ allDeprecation deprecation including inside deprecated code\n\
-\ alljsDoc invalid or missing jsDoc\n\
-\ assertIdentifier + ''assert'' used as identifier\n\
-\ boxing autoboxing conversion\n\
-\ charConcat + char[] in String concat\n\
-\ conditionAssign possible accidental boolean assignment\n\
-\ constructorName + method with constructor name\n\
-\ dep-ann missing @Deprecated annotation\n\
-\ deprecation + deprecation outside deprecated code\n\
-\ discouraged + use of types matching a discouraged access rule\n\
-\ emptyBlock undocumented empty block\n\
-\ enumSwitch incomplete enum switch\n\
-\ fallthrough possible fall-through case\n\
-\ fieldHiding field hiding another variable\n\
-\ finalBound type parameter with final bound\n\
-\ finally + finally block not completing normally\n\
-\ forbidden + use of types matching a forbidden access rule\n\
-\ hiding macro for fieldHiding, localHiding, typeHiding and\n\
-\ maskedCatchBlock\n\
-\ incomplete-switch same as enumSwitch\n\
-\ indirectStatic indirect reference to static member\n\
-\ intfAnnotation + annotation type used as super interface\n\
-\ intfNonInherited + interface non-inherited method compatibility\n\
-\ jsDoc invalid jsDoc\n\
-\ localHiding local variable hiding another variable\n\
-\ maskedCatchBlock + hidden catch block\n\
-\ nls string literal lacking non-nls tag //$NON-NLS-<n>$\n\
-\ noEffectAssign + assignment without effect\n\
-\ null missing or redundant null check\n\
-\ over-ann missing @Override annotation\n\
-\ paramAssign assignment to a parameter\n\
-\ pkgDefaultMethod + attempt to override package-default method\n\
-\ raw + usage of raw type\n\
-\ semicolon unnecessary semicolon, empty statement\n\
-\ serial + missing serialVersionUID\n\
-\ specialParamHiding constructor or setter parameter hiding another field\n\
-\ static-access macro for indirectStatic and staticReceiver\n\
-\ staticReceiver + non-static reference to static member\n\
-\ super overriding a method without making a super invocation\n\
-\ suppress + enable @SuppressWarnings\n\
-\ synthetic-access same as syntheticAccess\n\
-\ syntheticAccess synthetic access for innerclass\n\
-\ tasks(<tags separated by |>) tasks identified by tags inside comments\n\
-\ typeHiding + type parameter hiding another type\n\
-\ unchecked + unchecked type operation\n\
-\ unnecessaryElse unnecessary else clause\n\
-\ unqualified-field-access same as unqualifiedField\n\
-\ unqualifiedField unqualified reference to field\n\
-\ unused macro for unusedArgument, unusedImport, unusedLabel,\n\
-\ unusedLocal, unusedPrivate and unusedThrown\n\
-\ unusedArgument unread method parameter\n\
-\ unusedImport + unused import declaration\n\
-\ unusedLabel + unused label\n\
-\ unusedLocal + unread local variable\n\
-\ unusedPrivate + unused private member declaration\n\
-\ unusedThrown unused declared thrown exception\n\
-\ uselessTypeCheck unnecessary cast/instanceof operation\n\
-\ warningToken + unhandled warning token in @SuppressWarnings\n\
-\ \n\
-\ Advanced options:\n\
-\ -? -help print the help message\n\
-
-# templates
-### access restrictions
-template.restrictedAccess.type = The type {0} is not accessible due to restriction on classpath entry {1}
-template.restrictedAccess.constructor = The constructor {0} is not accessible due to restriction on classpath entry {1}
-template.restrictedAccess.field = The field {0} from the type {1} is not accessible due to restriction on classpath entry {2}
-template.restrictedAccess.method = The method {0} from the type {1} is not accessible due to restriction on classpath entry {2}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/classfmt/ClassFileConstants.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/classfmt/ClassFileConstants.java
deleted file mode 100644
index 8e02bc29..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/classfmt/ClassFileConstants.java
+++ /dev/null
@@ -1,108 +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.compiler.classfmt;
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode;
-
-public interface ClassFileConstants {
-
- int AccDefault = 0;
- /*
- * Modifiers
- */
- int AccPublic = 0x0001;
- int AccPrivate = 0x0002;
- int AccProtected = 0x0004;
- int AccStatic = 0x0008;
- int AccFinal = 0x0010;
- int AccBridge = 0x0040;
- int AccVarargs = 0x0080;
- int AccNative = 0x0100;
- int AccAbstract = 0x0400;
- int AccStrictfp = 0x0800;
-
- /**
- * Other VM flags.
- */
- int AccSuper = 0x0020;
-
- /**
- * Extra flags for types and members attributes.
- */
- int AccAnnotationDefault = ASTNode.Bit18; // indicate presence of an attribute "DefaultValue" (annotation method)
- int AccDeprecated = ASTNode.Bit21; // indicate presence of an attribute "Deprecated"
-
- int Utf8Tag = 1;
- int IntegerTag = 3;
- int FloatTag = 4;
- int LongTag = 5;
- int DoubleTag = 6;
- int ClassTag = 7;
- int StringTag = 8;
- int FieldRefTag = 9;
- int MethodRefTag = 10;
- int InterfaceMethodRefTag = 11;
- int NameAndTypeTag = 12;
-
- int ConstantMethodRefFixedSize = 5;
- int ConstantClassFixedSize = 3;
- int ConstantDoubleFixedSize = 9;
- int ConstantFieldRefFixedSize = 5;
- int ConstantFloatFixedSize = 5;
- int ConstantIntegerFixedSize = 5;
- int ConstantInterfaceMethodRefFixedSize = 5;
- int ConstantLongFixedSize = 9;
- int ConstantStringFixedSize = 3;
- int ConstantUtf8FixedSize = 3;
- int ConstantNameAndTypeFixedSize = 5;
-
- int MAJOR_VERSION_1_1 = 45;
- int MAJOR_VERSION_1_2 = 46;
- int MAJOR_VERSION_1_3 = 47;
- int MAJOR_VERSION_1_4 = 48;
- int MAJOR_VERSION_1_5 = 49;
- int MAJOR_VERSION_1_6 = 50;
- int MAJOR_VERSION_1_7 = 51;
-
- int MINOR_VERSION_0 = 0;
- int MINOR_VERSION_1 = 1;
- int MINOR_VERSION_2 = 2;
- int MINOR_VERSION_3 = 3;
-
- // JDK 1.1 -> 1.7, comparable value allowing to check both major/minor version at once 1.4.1 > 1.4.0
- // 16 unsigned bits for major, then 16 bits for minor
- long JDK1_1 = ((long)ClassFileConstants.MAJOR_VERSION_1_1 << 16) + ClassFileConstants.MINOR_VERSION_3; // 1.1. is 45.3
- long JDK1_2 = ((long)ClassFileConstants.MAJOR_VERSION_1_2 << 16) + ClassFileConstants.MINOR_VERSION_0;
- long JDK1_3 = ((long)ClassFileConstants.MAJOR_VERSION_1_3 << 16) + ClassFileConstants.MINOR_VERSION_0;
- long JDK1_4 = ((long)ClassFileConstants.MAJOR_VERSION_1_4 << 16) + ClassFileConstants.MINOR_VERSION_0;
- long JDK1_5 = ((long)ClassFileConstants.MAJOR_VERSION_1_5 << 16) + ClassFileConstants.MINOR_VERSION_0;
- long JDK1_6 = ((long)ClassFileConstants.MAJOR_VERSION_1_6 << 16) + ClassFileConstants.MINOR_VERSION_0;
- long JDK1_7 = ((long)ClassFileConstants.MAJOR_VERSION_1_7 << 16) + ClassFileConstants.MINOR_VERSION_0;
-
- // jdk level used to denote future releases: optional behavior is not enabled for now, but may become so. In order to enable these,
- // search for references to this constant, and change it to one of the official JDT constants above.
- long JDK_DEFERRED = Long.MAX_VALUE;
-
- int INT_ARRAY = 10;
- int BYTE_ARRAY = 8;
- int BOOLEAN_ARRAY = 4;
- int SHORT_ARRAY = 9;
- int CHAR_ARRAY = 5;
- int LONG_ARRAY = 11;
- int FLOAT_ARRAY = 6;
- int DOUBLE_ARRAY = 7;
-
- // Debug attributes
- int ATTR_SOURCE = 1; // SourceFileAttribute
- int ATTR_LINES = 2; // LineNumberAttribute
- int ATTR_VARS = 4; // LocalVariableTableAttribute
- int ATTR_STACK_MAP = 8; // Stack map table attribute
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/AccessRestriction.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/AccessRestriction.java
deleted file mode 100644
index 2a7d546d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/AccessRestriction.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.env;
-
-public class AccessRestriction {
-
- private AccessRule accessRule;
- private String[] messageTemplates;
- public AccessRestriction(AccessRule accessRule, String [] messageTemplates) {
- this.accessRule = accessRule;
- this.messageTemplates = messageTemplates;
- }
-
- /**
- * Returns readable description for problem reporting,
- * message is expected to contain room for restricted type name
- * e.g. "{0} has restricted access"
- */
- public String getMessageTemplate() {
- return this.messageTemplates[0];
- }
-
- public String getConstructorAccessMessageTemplate() {
- return this.messageTemplates[1];
- }
-
- public String getMethodAccessMessageTemplate() {
- return this.messageTemplates[2];
- }
-
- public String getFieldAccessMessageTemplate() {
- return this.messageTemplates[3];
- }
-
- public int getProblemId() {
- return this.accessRule.getProblemId();
- }
-
- public boolean ignoreIfBetter() {
- return this.accessRule.ignoreIfBetter();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/AccessRule.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/AccessRule.java
deleted file mode 100644
index 464d83f0..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/AccessRule.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.env;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-
-public class AccessRule {
-
- public static final int IgnoreIfBetter = 0x02000000; // value must be greater than IProblem#ForbiddenReference and DiscouragedReference
-
- public char[] pattern;
- public int problemId;
-
- public AccessRule(char[] pattern, int problemId) {
- this(pattern, problemId, false);
- }
-
- public AccessRule(char[] pattern, int problemId, boolean keepLooking) {
- this.pattern = pattern;
- this.problemId = keepLooking ? problemId | IgnoreIfBetter : problemId;
- }
-
- public int hashCode() {
- return this.problemId * 17 + CharOperation.hashCode(this.pattern);
- }
-
- public boolean equals(Object obj) {
- if (!(obj instanceof AccessRule)) return false;
- AccessRule other = (AccessRule) obj;
- if (this.problemId != other.problemId) return false;
- return CharOperation.equals(this.pattern, other.pattern);
- }
-
- public int getProblemId() {
- return this.problemId & ~IgnoreIfBetter;
- }
-
- public boolean ignoreIfBetter() {
- return (this.problemId & IgnoreIfBetter) != 0;
- }
-
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- buffer.append("pattern="); //$NON-NLS-1$
- buffer.append(this.pattern);
- switch (getProblemId()) {
- case IProblem.ForbiddenReference:
- buffer.append(" (NON ACCESSIBLE"); //$NON-NLS-1$
- break;
- case IProblem.DiscouragedReference:
- buffer.append(" (DISCOURAGED"); //$NON-NLS-1$
- break;
- default:
- buffer.append(" (ACCESSIBLE"); //$NON-NLS-1$
- break;
- }
- if (ignoreIfBetter())
- buffer.append(" | IGNORE IF BETTER"); //$NON-NLS-1$
- buffer.append(')');
- return buffer.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/AccessRuleSet.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/AccessRuleSet.java
deleted file mode 100644
index 8748ca1b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/AccessRuleSet.java
+++ /dev/null
@@ -1,118 +0,0 @@
-/*******************************************************************************
- * 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.compiler.env;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-
-/**
- * Definition of a set of access rules used to flag forbidden references to non API code.
- */
-public class AccessRuleSet {
-
- private AccessRule[] accessRules;
- public String[] messageTemplates;
- public static final int MESSAGE_TEMPLATES_LENGTH = 4;
-
- /**
- * Make a new set of access rules.
- * @param accessRules the access rules to be contained by the new set
- * @param messageTemplates a Sting[4] array specifying the messages for type,
- * constructor, method and field access violation; each should contain as many
- * placeholders as expected by the respective access violation message (that is,
- * one for type and constructor, two for method and field); replaced by a
- * default value if null.
- */
- public AccessRuleSet(AccessRule[] accessRules, String[] messageTemplates) {
- this.accessRules = accessRules;
- if (messageTemplates != null && messageTemplates.length == MESSAGE_TEMPLATES_LENGTH)
- this.messageTemplates = messageTemplates;
- else
- this.messageTemplates = new String[] {"{0}", "{0}", "{0} {1}", "{0} {1}"}; //$NON-NLS-1$ //$NON-NLS-2$//$NON-NLS-3$ //$NON-NLS-4$
- }
-
- /**
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public boolean equals(Object object) {
- if (this == object)
- return true;
- if (!(object instanceof AccessRuleSet))
- return false;
- AccessRuleSet otherRuleSet = (AccessRuleSet) object;
- if (this.messageTemplates.length != MESSAGE_TEMPLATES_LENGTH ||
- otherRuleSet.messageTemplates.length != MESSAGE_TEMPLATES_LENGTH)
- return false; // guard
- for (int i = 0; i < MESSAGE_TEMPLATES_LENGTH; i++)
- if (!this.messageTemplates[i].equals(otherRuleSet.messageTemplates[i]))
- return false;
- int rulesLength = this.accessRules.length;
- if (rulesLength != otherRuleSet.accessRules.length) return false;
- for (int i = 0; i < rulesLength; i++)
- if (!this.accessRules[i].equals(otherRuleSet.accessRules[i]))
- return false;
- return true;
- }
-
- public AccessRule[] getAccessRules() {
- return this.accessRules;
- }
-
-/**
- * Select the first access rule which is violated when accessing a given type,
- * or null if no 'non accessible' access rule applies.
- * @param targetTypeFilePath the target type file path, formed as:
- * "org/eclipse/jdt/core/JavaScriptCore"
- * @return the first access restriction that applies if any, null else
- */
-public AccessRestriction getViolatedRestriction(char[] targetTypeFilePath) {
- for (int i = 0, length = this.accessRules.length; i < length; i++) {
- AccessRule accessRule = this.accessRules[i];
- if (CharOperation.pathMatch(accessRule.pattern, targetTypeFilePath,
- true/*case sensitive*/, '/')) {
- switch (accessRule.getProblemId()) {
- case IProblem.ForbiddenReference:
- case IProblem.DiscouragedReference:
- return new AccessRestriction(accessRule, this.messageTemplates);
- default:
- return null;
- }
- }
- }
- return null;
-}
-
- public String toString() {
- return toString(true/*wrap lines*/);
- }
-
- public String toString(boolean wrap) {
- StringBuffer buffer = new StringBuffer(200);
- buffer.append("AccessRuleSet {"); //$NON-NLS-1$
- if (wrap)
- buffer.append('\n');
- for (int i = 0, length = this.accessRules.length; i < length; i++) {
- if (wrap)
- buffer.append('\t');
- AccessRule accessRule = this.accessRules[i];
- buffer.append(accessRule);
- if (wrap)
- buffer.append('\n');
- else if (i < length-1)
- buffer.append(", "); //$NON-NLS-1$
- }
- buffer.append("} [templates:\""); //$NON-NLS-1$
- for (int i = 0; i < messageTemplates.length; i++)
- buffer.append(this.messageTemplates[i]);
- buffer.append("\"]"); //$NON-NLS-1$
- return buffer.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/ClassSignature.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/ClassSignature.java
deleted file mode 100644
index 9e6f2776..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/ClassSignature.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * tyeung@bea.com - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.env;
-
-/**
- * Represents a class reference in the class file.
- * One of the possible results for the default value of an annotation method or an element value pair.
- */
-public class ClassSignature {
-
- char[] className;
-
-public ClassSignature(final char[] className) {
- this.className = className;
-}
-
-/**
- * @return name of the type in the class file format
- */
-public char[] getTypeName() {
- return this.className;
-}
-
-public String toString() {
- StringBuffer buffer = new StringBuffer();
- buffer.append(this.className);
- buffer.append(".class"); //$NON-NLS-1$
- return buffer.toString();
-}
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/IBinaryField.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/IBinaryField.java
deleted file mode 100644
index c6751842..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/IBinaryField.java
+++ /dev/null
@@ -1,50 +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.compiler.env;
-
-import org.eclipse.wst.jsdt.internal.compiler.impl.Constant;
-
-public interface IBinaryField extends IGenericField {
-
-/**
- *
- * @return org.eclipse.wst.jsdt.internal.compiler.Constant
- */
-Constant getConstant();
-
-/**
- * Answer the receiver's signature which describes the parameter &
- * return types as specified in section 4.4.4 of the Java 2 VM spec.
- */
-char[] getGenericSignature();
-
-/**
- * Answer the name of the field.
- */
-char[] getName();
-
-/**
- * Answer the tagbits set according to the bits for annotations.
- */
-long getTagBits();
-
-/**
- * Answer the resolved name of the receiver's type in the
- * class file format as specified in section 4.3.2 of the Java 2 VM spec.
- *
- * For example:
- * - java.lang.String is Ljava/lang/String;
- * - an int is I
- * - a 2 dimensional array of strings is [[Ljava/lang/String;
- * - an array of floats is [F
- */
-char[] getTypeName();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/IBinaryMethod.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/IBinaryMethod.java
deleted file mode 100644
index 48ea0be2..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/IBinaryMethod.java
+++ /dev/null
@@ -1,73 +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.compiler.env;
-
-// clinit methods (synthetics too?) can be returned from IBinaryType>>getMethods()
-// BUT do not have to be... the compiler will ignore them when building the binding.
-// The synthetic argument of a member type's constructor (ie. the first arg of a non-static
-// member type) is also ignored by the compiler, BUT in this case it must be included
-// in the constructor's signature.
-
-public interface IBinaryMethod extends IGenericMethod {
-
-/**
- * Return {@link ClassSignature} for a Class {@link java.lang.Class}.
- * Return {@link org.eclipse.wst.jsdt.internal.compiler.impl.Constant} for compile-time constant of primitive type, as well as String literals.
- * Return {@link EnumConstantSignature} if value is an enum constant.
- * Return {@link IBinaryAnnotation} for annotation type.
- * Return {@link Object}[] for array type.
- *
- * @return default value of this annotation method
- */
-Object getDefaultValue();
-
-/**
- * Answer the resolved names of the exception types in the
- * class file format as specified in section 4.2 of the Java 2 VM spec
- * or null if the array is empty.
- *
- * For example, java.lang.String is java/lang/String.
- */
-char[][] getExceptionTypeNames();
-
-/**
- * Answer the receiver's signature which describes the parameter &
- * return types as specified in section 4.4.4 of the Java 2 VM spec.
- */
-char[] getGenericSignature();
-
-/**
- * Answer the receiver's method descriptor which describes the parameter &
- * return types as specified in section 4.4.3 of the Java 2 VM spec.
- *
- * For example:
- * - int foo(String) is (Ljava/lang/String;)I
- * - Object[] foo(int) is (I)[Ljava/lang/Object;
- */
-char[] getMethodDescriptor();
-
-/**
- * Answer the name of the method.
- *
- * For a constructor, answer <init> & <clinit> for a clinit method.
- */
-char[] getSelector();
-
-/**
- * Answer the tagbits set according to the bits for annotations.
- */
-long getTagBits();
-
-/**
- * Answer whether the receiver represents a class initializer method.
- */
-boolean isClinit();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/IBinaryNestedType.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/IBinaryNestedType.java
deleted file mode 100644
index dbd1abc3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/IBinaryNestedType.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.env;
-
-public interface IBinaryNestedType {
-/**
- * Answer the resolved name of the enclosing type in the
- * class file format as specified in section 4.2 of the Java 2 VM spec.
- *
- * For example, java.lang.String is java/lang/String.
- */
-
-char[] getEnclosingTypeName();
-/**
- * Answer an int whose bits are set according the access constants
- * defined by the VM spec.
- */
-
-// We have added AccDeprecated & AccSynthetic.
-
-int getModifiers();
-/**
- * Answer the resolved name of the member type in the
- * class file format as specified in section 4.2 of the Java 2 VM spec.
- *
- * For example, p1.p2.A.M is p1/p2/A$M.
- */
-
-char[] getName();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/IBinaryType.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/IBinaryType.java
deleted file mode 100644
index 96fc1f4d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/IBinaryType.java
+++ /dev/null
@@ -1,113 +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.compiler.env;
-
-
-public interface IBinaryType extends IGenericType {
-
- IBinaryNestedType[] NoNestedType = new IBinaryNestedType[0];
- IBinaryField[] NoField = new IBinaryField[0];
- IBinaryMethod[] NoMethod = new IBinaryMethod[0];
-
-/**
- * Answer the resolved name of the enclosing type in the
- * class file format as specified in section 4.2 of the Java 2 VM spec
- * or null if the receiver is a top level type.
- *
- * For example, java.lang.String is java/lang/String.
- */
-
-char[] getEnclosingTypeName();
-/**
- * Answer the receiver's fields or null if the array is empty.
- */
-
-IBinaryField[] getFields();
-/**
- * Answer the receiver's signature which describes the parameter &
- * return types as specified in section 4.4.4 of the Java 2 VM spec 3rd edition.
- * Returns null if none.
- *
- * @return the receiver's signature, null if none
- */
-char[] getGenericSignature();
-/**
- * Answer the receiver's nested types or null if the array is empty.
- *
- * This nested type info is extracted from the inner class attributes.
- * Ask the name environment to find a member type using its compound name.
- */
-
-// NOTE: The compiler examines the nested type info & ignores the local types
-// so the local types do not have to be included.
-
-IBinaryNestedType[] getMemberTypes();
-/**
- * Answer the receiver's methods or null if the array is empty.
- */
-
-IBinaryMethod[] getMethods();
-
-/**
- * Answer the resolved name of the type in the
- * class file format as specified in section 4.2 of the Java 2 VM spec.
- *
- * For example, java.lang.String is java/lang/String.
- */
-char[] getName();
-
-/**
- * Answer the simple name of the type in the class file.
- * For member A$B, will answer B.
- * For anonymous will answer null.
- */
-char[] getSourceName();
-
-/**
- * Answer the resolved name of the receiver's superclass in the
- * class file format as specified in section 4.2 of the Java 2 VM spec
- * or null if it does not have one.
- *
- * For example, java.lang.String is java/lang/String.
- */
-
-char[] getSuperclassName();
-/**
- * Answer the tagbits set according to the bits for annotations.
- */
-long getTagBits();
-/**
- * Answer true if the receiver is an anonymous class.
- * false otherwise
- */
-boolean isAnonymous();
-
-/**
- * Answer true if the receiver is a local class.
- * false otherwise
- */
-boolean isLocal();
-
-/**
- * Answer true if the receiver is a member class.
- * false otherwise
- */
-boolean isMember();
-
-/**
- * Answer the source file attribute, or null if none.
- *
- * For example, "String.js"
- */
-
-char[] sourceFileName();
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/ICompilationUnit.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/ICompilationUnit.java
deleted file mode 100644
index 05acd82b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/ICompilationUnit.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*******************************************************************************
- * 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.compiler.env;
-
-import org.eclipse.wst.jsdt.core.LibrarySuperType;
-import org.eclipse.wst.jsdt.core.infer.IInferenceFile;
-
-/**
- * This interface denotes a compilation unit, providing its name and content.
- */
-public interface ICompilationUnit extends IDependent, IInferenceFile {
-/**
- * Answer the contents of the compilation unit.
- *
- * In normal use, the contents are requested twice.
- * Once during the initial lite parsing step, then again for the
- * more detailed parsing step.
- * Implementors must never return null - return an empty char[] instead,
- * CharOperation.NO_CHAR being the candidate of choice.
- */
-char[] getContents();
-/**
- * Answer the name of the top level public type.
- * For example, {Hashtable}.
- */
-char[] getMainTypeName();
-/**
- * Answer the name of the package according to the directory structure
- * or null if package consistency checks should be ignored.
- * For example, {java, lang}.
- */
-char[][] getPackageName();
-LibrarySuperType getCommonSuperType();
-
-
-/**
- * Get the id of the inference provider for this Compilation Unit
- * @return inference provider id
- */
-String getInferenceID();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/IDependent.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/IDependent.java
deleted file mode 100644
index 55346359..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/IDependent.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.env;
-
-/**
- * This represents the target file of a type dependency.
- *
- * All implementors of this interface are containers for types or types
- * themselves which must be able to identify their source file name
- * when file dependencies are collected.
- */
-public interface IDependent {
- char JAR_FILE_ENTRY_SEPARATOR = '|';
-/**
- * Answer the file name which defines the type.
- *
- * The path part (optional) must be separated from the actual
- * file proper name by a separator suitable for the type (java.io.File.separator for example),
- * e.g.
- * "c:\\source\\com\\p\\X.js" or
- * "/com/p/Y.js".
- *
- * The path to the zip or jar file (optional) must be separated
- * from the actual path part by JAR_FILE_ENTRY_SEPARATOR,
- * e.g.
- * "c:\\lib\\some.jar|/com/p/X.class" or
- * "/lib/some.zip|/com/q/Y.class".
- *
- * The proper file name includes the suffix extension (e.g.&nbsp;".js")
- * e.g.&nbsp;"c:/org/eclipse/jdt/internal/compileri/env/IDependent.js"
- *
- * Return null if no file defines the type.
- */
-
-char[] getFileName();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/IGenericField.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/IGenericField.java
deleted file mode 100644
index a466302d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/IGenericField.java
+++ /dev/null
@@ -1,23 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.env;
-
-public interface IGenericField {
-/**
- * Answer an int whose bits are set according the access constants
- * defined by the VM spec.
- */
-
-// We have added AccDeprecated & AccSynthetic.
-
-int getModifiers();
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/IGenericMethod.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/IGenericMethod.java
deleted file mode 100644
index 2f103437..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/IGenericMethod.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.env;
-
-public interface IGenericMethod {
-/**
- * Answer an int whose bits are set according the access constants
- * defined by the VM spec.
- */
-// We have added AccDeprecated
-int getModifiers();
-
-boolean isConstructor();
-
-/**
- * Answer the names of the argument
- * or null if the argument names are not available.
- */
-
-char[][] getArgumentNames();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/IGenericType.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/IGenericType.java
deleted file mode 100644
index b679775e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/IGenericType.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.env;
-
-public interface IGenericType extends IDependent {
-
-/**
- * Answer an int whose bits are set according the access constants
- * defined by the VM spec.
- * NOTE 1: We have added AccDeprecated & AccSynthetic.
- * NOTE 2: If the receiver represents a member type, the modifiers are extracted from its inner class attributes.
- */
-int getModifiers();
-/**
- * Answer whether the receiver contains the resolved binary form
- * or the unresolved source form of the type.
- */
-
-boolean isBinaryType();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/INameEnvironment.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/INameEnvironment.java
deleted file mode 100644
index 3006d553..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/INameEnvironment.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.env;
-
-import org.eclipse.wst.jsdt.internal.compiler.impl.ITypeRequestor;
-
-/**
- * The name environment provides a callback API that the compiler
- * can use to look up types, compilation units, and packages in the
- * current environment. The name environment is passed to the compiler
- * on creation.
- */
-public interface INameEnvironment {
-/**
- * Find a type with the given compound name.
- * Answer the binary form of the type if it is known to be consistent.
- * Otherwise, answer the compilation unit which defines the type
- * or null if the type does not exist.
- * Types in the default package are specified as {{typeName}}.
- *
- * It is unknown whether the package containing the type actually exists.
- *
- * NOTE: This method can be used to find a member type using its
- * internal name A$B, but the source file for A is answered if the binary
- * file is inconsistent.
- */
-
-NameEnvironmentAnswer findType(char[][] compoundTypeName, ITypeRequestor requestor);
-/**
- * Find a type named <typeName> in the package <packageName>.
- * Answer the binary form of the type if it is known to be consistent.
- * Otherwise, answer the compilation unit which defines the type
- * or null if the type does not exist.
- * The default package is indicated by char[0][].
- *
- * It is known that the package containing the type exists.
- *
- * NOTE: This method can be used to find a member type using its
- * internal name A$B, but the source file for A is answered if the binary
- * file is inconsistent.
- */
-
-NameEnvironmentAnswer findType(char[] typeName, char[][] packageName, ITypeRequestor requestor);
-/**
- * Answer whether packageName is the name of a known subpackage inside
- * the package parentPackageName. A top level package is found relative to null.
- * The default package is always assumed to exist.
- *
- * For example:
- * isPackage({{java}, {awt}}, {event});
- * isPackage(null, {java});
- */
-
-boolean isPackage(char[][] parentPackageName, char[] packageName);
-NameEnvironmentAnswer findBinding(char[] typeName, char[][] packageName, int type, ITypeRequestor requestor, boolean returnMultiple, String excludePath);
-
-/**
- * This method cleans the environment uo. It is responsible for releasing the memory
- * and freeing resources. Passed that point, the name environment is no longer usable.
- *
- * A name environment can have a long life cycle, therefore it is the responsibility of
- * the code which created it to decide when it is a good time to clean it up.
- */
-void cleanup();
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/ISourceField.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/ISourceField.java
deleted file mode 100644
index 1ec98d53..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/ISourceField.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.env;
-
-public interface ISourceField extends IGenericField {
-/**
- * Answer the source end position of the field's declaration.
- */
-int getDeclarationSourceEnd();
-
-/**
- * Answer the source start position of the field's declaration.
- */
-int getDeclarationSourceStart();
-
-/**
- * Answer the initialization source for this constant field.
- * Answer null if the field is not a constant or if it has no initialization.
- */
-char[] getInitializationSource();
-
-/**
- * Answer the source end position of the field's name.
- */
-int getNameSourceEnd();
-
-/**
- * Answer the source start position of the field's name.
- */
-int getNameSourceStart();
-
-/**
- * Answer the type name of the field.
- *
- * The name is a simple name or a qualified, dot separated name.
- * For example, Hashtable or java.util.Hashtable.
- */
-char[] getTypeName();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/ISourceImport.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/ISourceImport.java
deleted file mode 100644
index 78e8ad0a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/ISourceImport.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.env;
-
-public interface ISourceImport {
-
-/**
- * Answer the source end position of the import declaration.
- */
-
-int getDeclarationSourceEnd();
-/**
- * Answer the source start position of the import declaration.
- */
-
-int getDeclarationSourceStart();
-
-/**
- * Answer an int whose bits are set according the access constants
- * defined by the VM spec.
- * Since Java 1.5, static imports can be defined.
- */
-int getModifiers();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/ISourceMethod.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/ISourceMethod.java
deleted file mode 100644
index f0417c6d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/ISourceMethod.java
+++ /dev/null
@@ -1,44 +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.compiler.env;
-
-public interface ISourceMethod extends IGenericMethod {
-
-/**
- * Answer the source end position of the method's declaration.
- */
-
-int getDeclarationSourceEnd();
-/**
- * Answer the source start position of the method's declaration.
- */
-
-int getDeclarationSourceStart();
-
-/**
- * Answer the source end position of the method's selector.
- */
-int getNameSourceEnd();
-/**
- * Answer the source start position of the method's selector.
- */
-
-int getNameSourceStart();
-/**
- * Answer the unresolved name of the return type
- * or null if receiver is a constructor or clinit.
- *
- * The name is a simple name or a qualified, dot separated name.
- * For example, Hashtable or java.util.Hashtable.
- */
-
-char[] getReturnTypeName();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/ISourceType.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/ISourceType.java
deleted file mode 100644
index b644e0f4..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/ISourceType.java
+++ /dev/null
@@ -1,84 +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.compiler.env;
-
-public interface ISourceType extends IGenericType {
-
-/**
- * Answer the source end position of the type's declaration.
- */
-int getDeclarationSourceEnd();
-
-/**
- * Answer the source start position of the type's declaration.
- */
-int getDeclarationSourceStart();
-
-/**
- * Answer the enclosing type
- * or null if the receiver is a top level type.
- */
-ISourceType getEnclosingType();
-
-/**
- * Answer the receiver's fields.
- *
- * NOTE: Multiple fields with the same name can exist in the result.
- */
-ISourceField[] getFields();
-
-/**
- * Answer the unresolved names of the receiver's interfaces
- * or null if the array is empty.
- *
- * A name is a simple name or a qualified, dot separated name.
- * For example, Hashtable or java.util.Hashtable.
- */
-char[][] getInterfaceNames();
-
-/**
- * Answer the receiver's member types.
- */
-ISourceType[] getMemberTypes();
-
-/**
- * Answer the receiver's methods.
- *
- * NOTE: Multiple methods with the same name & parameter types can exist in the result.
- */
-ISourceMethod[] getMethods();
-
-/**
- * Answer the simple source name of the receiver.
- */
-char[] getName();
-
-/**
- * Answer the source end position of the type's name.
- */
-int getNameSourceEnd();
-
-/**
- * Answer the source start position of the type's name.
- */
-int getNameSourceStart();
-
-/**
- * Answer the unresolved name of the receiver's superclass
- * or null if it does not have one.
- *
- * The name is a simple name or a qualified, dot separated name.
- * For example, Hashtable or java.util.Hashtable.
- */
-char[] getSuperclassName();
-
-char [][]getPackageName();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/NameEnvironmentAnswer.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/NameEnvironmentAnswer.java
deleted file mode 100644
index 4b4c374f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/env/NameEnvironmentAnswer.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/*******************************************************************************
- * 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.compiler.env;
-
-import org.eclipse.wst.jsdt.internal.oaametadata.LibraryAPIs;
-
-public class NameEnvironmentAnswer {
-
- // only one of the three can be set
- IBinaryType binaryType;
- ICompilationUnit compilationUnit;
- ICompilationUnit[] compilationUnits;
- ISourceType[] sourceTypes;
- AccessRestriction accessRestriction;
- LibraryAPIs libraryMetaData;
-
- public NameEnvironmentAnswer(IBinaryType binaryType, AccessRestriction accessRestriction) {
- this.binaryType = binaryType;
- this.accessRestriction = accessRestriction;
- }
-
-
- public NameEnvironmentAnswer(LibraryAPIs metaData) {
- this.libraryMetaData = metaData;
- }
-
- public NameEnvironmentAnswer(ICompilationUnit compilationUnit, AccessRestriction accessRestriction) {
- this.compilationUnit = compilationUnit;
- this.accessRestriction = accessRestriction;
- }
-
-
- public NameEnvironmentAnswer(ICompilationUnit[] compilationUnits, AccessRestriction accessRestriction) {
- this.compilationUnits = compilationUnits;
- this.accessRestriction = accessRestriction;
- }
-
-
- public NameEnvironmentAnswer(ISourceType[] sourceTypes, AccessRestriction accessRestriction) {
- this.sourceTypes = sourceTypes;
- this.accessRestriction = accessRestriction;
- }
- /**
- * Returns the associated access restriction, or null if none.
- */
- public AccessRestriction getAccessRestriction() {
- return this.accessRestriction;
- }
- /**
- * Answer the resolved binary form for the type or null if the
- * receiver represents a compilation unit or source type.
- */
- public IBinaryType getBinaryType() {
- return this.binaryType;
- }
-
- /**
- * Answer the compilation unit or null if the
- * receiver represents a binary or source type.
- */
- public ICompilationUnit getCompilationUnit() {
- return this.compilationUnit;
- }
-
- public ICompilationUnit[] getCompilationUnits() {
- return this.compilationUnits;
- }
- /**
- * Answer the unresolved source forms for the type or null if the
- * receiver represents a compilation unit or binary type.
- *
- * Multiple source forms can be answered in case the originating compilation unit did contain
- * several type at once. Then the first type is guaranteed to be the requested type.
- */
- public ISourceType[] getSourceTypes() {
- return this.sourceTypes;
- }
-
- /**
- * Answer whether the receiver contains the resolved binary form of the type.
- */
- public boolean isBinaryType() {
- return this.binaryType != null;
- }
-
- /**
- * Answer whether the receiver contains the compilation unit which defines the type.
- */
- public boolean isCompilationUnit() {
- return this.compilationUnit != null;
- }
-
- public boolean isCompilationUnits() {
- return this.compilationUnits != null;
- }
-
- /**
- * Answer whether the receiver contains the unresolved source form of the type.
- */
- public boolean isSourceType() {
- return this.sourceTypes != null;
- }
-
-
- public boolean isMetaData() {
- return this.libraryMetaData != null;
- }
-
-
- public boolean ignoreIfBetter() {
- return this.accessRestriction != null && this.accessRestriction.ignoreIfBetter();
- }
-
- /*
- * Returns whether this answer is better than the other awswer.
- * (accessible is better than discouraged, which is better than
- * non-accessible)
- */
- public boolean isBetter(NameEnvironmentAnswer otherAnswer) {
- if (otherAnswer == null) return true;
- if (this.accessRestriction == null) return true;
- return otherAnswer.accessRestriction != null
- && this.accessRestriction.getProblemId() < otherAnswer.accessRestriction.getProblemId();
- }
-
- public LibraryAPIs getLibraryMetadata()
- {
- return this.libraryMetaData;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/ConditionalFlowInfo.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/ConditionalFlowInfo.java
deleted file mode 100644
index 11a90f11..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/ConditionalFlowInfo.java
+++ /dev/null
@@ -1,217 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.flow;
-
-import org.eclipse.wst.jsdt.internal.compiler.lookup.FieldBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.LocalVariableBinding;
-
-/**
- * Record conditional initialization status during definite assignment analysis
- *
- */
-public class ConditionalFlowInfo extends FlowInfo {
-
- public FlowInfo initsWhenTrue;
- public FlowInfo initsWhenFalse;
-
-ConditionalFlowInfo(FlowInfo initsWhenTrue, FlowInfo initsWhenFalse){
-
- this.initsWhenTrue = initsWhenTrue;
- this.initsWhenFalse = initsWhenFalse;
-}
-
-public FlowInfo addInitializationsFrom(FlowInfo otherInits) {
-
- this.initsWhenTrue.addInitializationsFrom(otherInits);
- this.initsWhenFalse.addInitializationsFrom(otherInits);
- return this;
-}
-
-public FlowInfo addPotentialInitializationsFrom(FlowInfo otherInits) {
-
- this.initsWhenTrue.addPotentialInitializationsFrom(otherInits);
- this.initsWhenFalse.addPotentialInitializationsFrom(otherInits);
- return this;
-}
-
-public FlowInfo asNegatedCondition() {
-
- FlowInfo extra = initsWhenTrue;
- initsWhenTrue = initsWhenFalse;
- initsWhenFalse = extra;
- return this;
-}
-
-public FlowInfo copy() {
-
- return new ConditionalFlowInfo(initsWhenTrue.copy(), initsWhenFalse.copy());
-}
-
-public FlowInfo initsWhenFalse() {
-
- return initsWhenFalse;
-}
-
-public FlowInfo initsWhenTrue() {
-
- return initsWhenTrue;
-}
-
-public boolean isDefinitelyAssigned(FieldBinding field) {
-
- return initsWhenTrue.isDefinitelyAssigned(field)
- && initsWhenFalse.isDefinitelyAssigned(field);
-}
-
-public boolean isDefinitelyAssigned(LocalVariableBinding local) {
-
- return initsWhenTrue.isDefinitelyAssigned(local)
- && initsWhenFalse.isDefinitelyAssigned(local);
-}
-
-public boolean isDefinitelyNonNull(LocalVariableBinding local) {
- return initsWhenTrue.isDefinitelyNonNull(local)
- && initsWhenFalse.isDefinitelyNonNull(local);
-}
-
-public boolean isDefinitelyNull(LocalVariableBinding local) {
- return initsWhenTrue.isDefinitelyNull(local)
- && initsWhenFalse.isDefinitelyNull(local);
-}
-
-public boolean isDefinitelyUnknown(LocalVariableBinding local) {
- return initsWhenTrue.isDefinitelyUnknown(local)
- && initsWhenFalse.isDefinitelyUnknown(local);
-}
-
-public boolean isPotentiallyAssigned(FieldBinding field) {
- return initsWhenTrue.isPotentiallyAssigned(field)
- || initsWhenFalse.isPotentiallyAssigned(field);
-}
-
-public boolean isPotentiallyAssigned(LocalVariableBinding local) {
- return initsWhenTrue.isPotentiallyAssigned(local)
- || initsWhenFalse.isPotentiallyAssigned(local);
-}
-
-public boolean isPotentiallyNonNull(LocalVariableBinding local) {
- return initsWhenTrue.isPotentiallyNonNull(local)
- || initsWhenFalse.isPotentiallyNonNull(local);
-}
-
-public boolean isPotentiallyNull(LocalVariableBinding local) {
- return initsWhenTrue.isPotentiallyNull(local)
- || initsWhenFalse.isPotentiallyNull(local);
-}
-
-public boolean isPotentiallyUnknown(LocalVariableBinding local) {
- return initsWhenTrue.isPotentiallyUnknown(local)
- || initsWhenFalse.isPotentiallyUnknown(local);
-}
-
-public boolean isProtectedNonNull(LocalVariableBinding local) {
- return initsWhenTrue.isProtectedNonNull(local)
- && initsWhenFalse.isProtectedNonNull(local);
-}
-
-public boolean isProtectedNull(LocalVariableBinding local) {
- return initsWhenTrue.isProtectedNull(local)
- && initsWhenFalse.isProtectedNull(local);
-}
-
-public void markAsComparedEqualToNonNull(LocalVariableBinding local) {
- initsWhenTrue.markAsComparedEqualToNonNull(local);
- initsWhenFalse.markAsComparedEqualToNonNull(local);
-}
-
-public void markAsComparedEqualToNull(LocalVariableBinding local) {
- initsWhenTrue.markAsComparedEqualToNull(local);
- initsWhenFalse.markAsComparedEqualToNull(local);
-}
-
-public void markAsDefinitelyAssigned(FieldBinding field) {
- initsWhenTrue.markAsDefinitelyAssigned(field);
- initsWhenFalse.markAsDefinitelyAssigned(field);
-}
-
-public void markAsDefinitelyAssigned(LocalVariableBinding local) {
- initsWhenTrue.markAsDefinitelyAssigned(local);
- initsWhenFalse.markAsDefinitelyAssigned(local);
-}
-
-public void markAsDefinitelyNonNull(LocalVariableBinding local) {
- initsWhenTrue.markAsDefinitelyNonNull(local);
- initsWhenFalse.markAsDefinitelyNonNull(local);
-}
-
-public void markAsDefinitelyNull(LocalVariableBinding local) {
- initsWhenTrue.markAsDefinitelyNull(local);
- initsWhenFalse.markAsDefinitelyNull(local);
-}
-
-public void markAsDefinitelyUnknown(LocalVariableBinding local) {
- initsWhenTrue.markAsDefinitelyUnknown(local);
- initsWhenFalse.markAsDefinitelyUnknown(local);
-}
-
-public FlowInfo setReachMode(int reachMode) {
- if (reachMode == REACHABLE) {
- this.tagBits &= ~UNREACHABLE;
- }
- else {
- this.tagBits |= UNREACHABLE;
- }
- initsWhenTrue.setReachMode(reachMode);
- initsWhenFalse.setReachMode(reachMode);
- return this;
-}
-
-public UnconditionalFlowInfo mergedWith(UnconditionalFlowInfo otherInits) {
- return unconditionalInits().mergedWith(otherInits);
-}
-
-public UnconditionalFlowInfo nullInfoLessUnconditionalCopy() {
- return unconditionalInitsWithoutSideEffect().
- nullInfoLessUnconditionalCopy();
-}
-
-public String toString() {
-
- return "FlowInfo<true: " + initsWhenTrue.toString() + ", false: " + initsWhenFalse.toString() + ">"; //$NON-NLS-1$ //$NON-NLS-3$ //$NON-NLS-2$
-}
-
-public FlowInfo safeInitsWhenTrue() {
- return initsWhenTrue;
-}
-
-public UnconditionalFlowInfo unconditionalCopy() {
- return initsWhenTrue.unconditionalCopy().
- mergedWith(initsWhenFalse.unconditionalInits());
-}
-
-public UnconditionalFlowInfo unconditionalFieldLessCopy() {
- return initsWhenTrue.unconditionalFieldLessCopy().
- mergedWith(initsWhenFalse.unconditionalFieldLessCopy());
- // should never happen, hence suboptimal does not hurt
-}
-
-public UnconditionalFlowInfo unconditionalInits() {
- return initsWhenTrue.unconditionalInits().
- mergedWith(initsWhenFalse.unconditionalInits());
-}
-
-public UnconditionalFlowInfo unconditionalInitsWithoutSideEffect() {
- // cannot do better here than unconditionalCopy - but still a different
- // operation for UnconditionalFlowInfo
- return initsWhenTrue.unconditionalCopy().
- mergedWith(initsWhenFalse.unconditionalInits());
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/ExceptionHandlingFlowContext.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/ExceptionHandlingFlowContext.java
deleted file mode 100644
index 99d650af..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/ExceptionHandlingFlowContext.java
+++ /dev/null
@@ -1,196 +0,0 @@
-/*******************************************************************************
- * 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.compiler.flow;
-
-import java.util.ArrayList;
-
-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.SubRoutineStatement;
-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.MethodScope;
-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.util.ObjectCache;
-
-/**
- * Reflects the context of code analysis, keeping track of enclosing
- * try statements, exception handlers, etc...
- */
-public class ExceptionHandlingFlowContext extends FlowContext {
-
- public final static int BitCacheSize = 32; // 32 bits per int
-
- public ReferenceBinding[] handledExceptions;
- int[] isReached;
- int[] isNeeded;
- UnconditionalFlowInfo[] initsOnExceptions;
- ObjectCache indexes = new ObjectCache();
- boolean isMethodContext;
-
- public UnconditionalFlowInfo initsOnReturn;
-
- // for dealing with anonymous constructor thrown exceptions
- public ArrayList extendedExceptions;
-
-public ExceptionHandlingFlowContext(
- FlowContext parent,
- ASTNode associatedNode,
- ReferenceBinding[] handledExceptions,
- BlockScope scope,
- UnconditionalFlowInfo flowInfo) {
-
- super(parent, associatedNode);
- this.isMethodContext = scope == scope.methodScope();
- this.handledExceptions = handledExceptions;
- int count = handledExceptions != null ? handledExceptions.length : 0, cacheSize = (count / ExceptionHandlingFlowContext.BitCacheSize) + 1;
- this.isReached = new int[cacheSize]; // none is reached by default
- this.isNeeded = new int[cacheSize]; // none is needed by default
- this.initsOnExceptions = new UnconditionalFlowInfo[count];
- for (int i = 0; i < count; i++) {
- this.indexes.put(handledExceptions[i], i); // key type -> value index
- int cacheIndex = i / ExceptionHandlingFlowContext.BitCacheSize, bitMask = 1 << (i % ExceptionHandlingFlowContext.BitCacheSize);
- if (handledExceptions[i].isUncheckedException(true)) {
- this.isReached[cacheIndex] |= bitMask;
- this.initsOnExceptions[i] = flowInfo.unconditionalCopy();
- } else {
- this.initsOnExceptions[i] = FlowInfo.DEAD_END;
- }
- }
- System.arraycopy(this.isReached, 0, this.isNeeded, 0, cacheSize);
- this.initsOnReturn = FlowInfo.DEAD_END;
-}
-
-public void complainIfUnusedExceptionHandlers(AbstractMethodDeclaration method) {
- MethodScope scope = method.scope;
- // can optionally skip overriding methods
- if ((method.binding.modifiers & (ExtraCompilerModifiers.AccOverriding | ExtraCompilerModifiers.AccImplementing)) != 0
- && !scope.compilerOptions().reportUnusedDeclaredThrownExceptionWhenOverriding) {
- return;
- }
-}
-
-public String individualToString() {
- StringBuffer buffer = new StringBuffer("Exception flow context"); //$NON-NLS-1$
- int length = this.handledExceptions.length;
- for (int i = 0; i < length; i++) {
- int cacheIndex = i / ExceptionHandlingFlowContext.BitCacheSize;
- int bitMask = 1 << (i % ExceptionHandlingFlowContext.BitCacheSize);
- buffer.append('[').append(this.handledExceptions[i].readableName());
- if ((this.isReached[cacheIndex] & bitMask) != 0) {
- if ((this.isNeeded[cacheIndex] & bitMask) == 0) {
- buffer.append("-masked"); //$NON-NLS-1$
- } else {
- buffer.append("-reached"); //$NON-NLS-1$
- }
- } else {
- buffer.append("-not reached"); //$NON-NLS-1$
- }
- buffer.append('-').append(this.initsOnExceptions[i].toString()).append(']');
- }
- buffer.append("[initsOnReturn -").append(this.initsOnReturn.toString()).append(']'); //$NON-NLS-1$
- return buffer.toString();
-}
-
-public UnconditionalFlowInfo initsOnException(ReferenceBinding exceptionType) {
- int index;
- if ((index = this.indexes.get(exceptionType)) < 0) {
- return FlowInfo.DEAD_END;
- }
- return this.initsOnExceptions[index];
-}
-
-public UnconditionalFlowInfo initsOnReturn(){
- return this.initsOnReturn;
-}
-
-/*
- * Compute a merged list of unhandled exception types (keeping only the most generic ones).
- * This is necessary to add synthetic thrown exceptions for anonymous type constructors (JLS 8.6).
- */
-public void mergeUnhandledException(TypeBinding newException){
- if (this.extendedExceptions == null){
- this.extendedExceptions = new ArrayList(5);
- for (int i = 0; i < this.handledExceptions.length; i++){
- this.extendedExceptions.add(this.handledExceptions[i]);
- }
- }
- boolean isRedundant = false;
-
- for(int i = this.extendedExceptions.size()-1; i >= 0; i--){
- switch(Scope.compareTypes(newException, (TypeBinding)this.extendedExceptions.get(i))){
- case Scope.MORE_GENERIC :
- this.extendedExceptions.remove(i);
- break;
- case Scope.EQUAL_OR_MORE_SPECIFIC :
- isRedundant = true;
- break;
- case Scope.NOT_RELATED :
- break;
- }
- }
- if (!isRedundant){
- this.extendedExceptions.add(newException);
- }
-}
-
-public void recordHandlingException(
- ReferenceBinding exceptionType,
- UnconditionalFlowInfo flowInfo,
- TypeBinding raisedException,
- ASTNode invocationSite,
- boolean wasAlreadyDefinitelyCaught) {
-
- int index = this.indexes.get(exceptionType);
- // if already flagged as being reached (unchecked exception handler)
- int cacheIndex = index / ExceptionHandlingFlowContext.BitCacheSize;
- int bitMask = 1 << (index % ExceptionHandlingFlowContext.BitCacheSize);
- if (!wasAlreadyDefinitelyCaught) {
- this.isNeeded[cacheIndex] |= bitMask;
- }
- this.isReached[cacheIndex] |= bitMask;
-
- this.initsOnExceptions[index] =
- (this.initsOnExceptions[index].tagBits & FlowInfo.UNREACHABLE) == 0 ?
- this.initsOnExceptions[index].mergedWith(flowInfo):
- flowInfo.unconditionalCopy();
-}
-
-public void recordReturnFrom(UnconditionalFlowInfo flowInfo) {
- if ((flowInfo.tagBits & FlowInfo.UNREACHABLE) == 0) {
- if ((this.initsOnReturn.tagBits & FlowInfo.UNREACHABLE) == 0) {
- this.initsOnReturn = this.initsOnReturn.mergedWith(flowInfo);
- }
- else {
- this.initsOnReturn = (UnconditionalFlowInfo) flowInfo.copy();
- }
- }
-}
-
-/**
- * Exception handlers (with no finally block) are also included with subroutine
- * only once (in case parented with true InsideSubRoutineFlowContext).
- * Standard management of subroutines need to also operate on intermediate
- * exception handlers.
- * @see org.eclipse.wst.jsdt.internal.compiler.flow.FlowContext#subroutine()
- */
-public SubRoutineStatement subroutine() {
- if (this.associatedNode instanceof SubRoutineStatement) {
- // exception handler context may be child of InsideSubRoutineFlowContext, which maps to same handler
- if (this.parent.subroutine() == this.associatedNode)
- return null;
- return (SubRoutineStatement) this.associatedNode;
- }
- return null;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/FinallyFlowContext.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/FinallyFlowContext.java
deleted file mode 100644
index 6e1d5ad8..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/FinallyFlowContext.java
+++ /dev/null
@@ -1,282 +0,0 @@
-/*******************************************************************************
- * 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.compiler.flow;
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Expression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Reference;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.LocalVariableBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Scope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.VariableBinding;
-
-/**
- * Reflects the context of code analysis, keeping track of enclosing
- * try statements, exception handlers, etc...
- */
-public class FinallyFlowContext extends FlowContext {
-
- Reference[] finalAssignments;
- VariableBinding[] finalVariables;
- int assignCount;
-
- LocalVariableBinding[] nullLocals;
- Expression[] nullReferences;
- int[] nullCheckTypes;
- int nullCount;
-
- public FinallyFlowContext(FlowContext parent, ASTNode associatedNode) {
- super(parent, associatedNode);
- }
-
-/**
- * Given some contextual initialization info (derived from a try block or a catch block), this
- * code will check that the subroutine context does not also initialize a final variable potentially set
- * redundantly.
- */
-public void complainOnDeferredChecks(FlowInfo flowInfo, BlockScope scope) {
-
- // check inconsistent null checks
- if (this.deferNullDiagnostic) { // within an enclosing loop, be conservative
- for (int i = 0; i < this.nullCount; i++) {
- this.parent.recordUsingNullReference(scope, this.nullLocals[i],
- this.nullReferences[i], this.nullCheckTypes[i], flowInfo);
- }
- }
- else { // no enclosing loop, be as precise as possible right now
- for (int i = 0; i < this.nullCount; i++) {
- Expression expression = this.nullReferences[i];
- // final local variable
- LocalVariableBinding local = this.nullLocals[i];
- switch (this.nullCheckTypes[i]) {
- case CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NULL:
- case CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NON_NULL:
- if (flowInfo.isDefinitelyNonNull(local)) {
- if (this.nullCheckTypes[i] == (CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NON_NULL)) {
- scope.problemReporter().localVariableRedundantCheckOnNonNull(local, expression);
- } else {
- scope.problemReporter().localVariableNonNullComparedToNull(local, expression);
- }
- continue;
- }
- case CAN_ONLY_NULL | IN_COMPARISON_NULL:
- case CAN_ONLY_NULL | IN_COMPARISON_NON_NULL:
- case CAN_ONLY_NULL | IN_ASSIGNMENT:
- case CAN_ONLY_NULL | IN_INSTANCEOF:
- if (flowInfo.isDefinitelyNull(local)) {
- switch(this.nullCheckTypes[i] & CONTEXT_MASK) {
- case FlowContext.IN_COMPARISON_NULL:
- scope.problemReporter().localVariableRedundantCheckOnNull(local, expression);
- continue;
- case FlowContext.IN_COMPARISON_NON_NULL:
- scope.problemReporter().localVariableNullComparedToNonNull(local, expression);
- continue;
- case FlowContext.IN_ASSIGNMENT:
- scope.problemReporter().localVariableRedundantNullAssignment(local, expression);
- continue;
- case FlowContext.IN_INSTANCEOF:
- scope.problemReporter().localVariableNullInstanceof(local, expression);
- continue;
- }
- }
- break;
- case MAY_NULL:
- if (flowInfo.isDefinitelyNull(local)) {
- scope.problemReporter().localVariableNullReference(local, expression);
- continue;
- }
- if (flowInfo.isPotentiallyNull(local)) {
- scope.problemReporter().localVariablePotentialNullReference(local, expression);
- }
- break;
- default:
- // should not happen
- }
- }
- }
-}
-
- public String individualToString() {
-
- StringBuffer buffer = new StringBuffer("Finally flow context"); //$NON-NLS-1$
- buffer.append("[finalAssignments count - ").append(assignCount).append(']'); //$NON-NLS-1$
- buffer.append("[nullReferences count - ").append(nullCount).append(']'); //$NON-NLS-1$
- return buffer.toString();
- }
-
- public boolean isSubRoutine() {
- return true;
- }
-
- protected boolean recordFinalAssignment(
- VariableBinding binding,
- Reference finalAssignment) {
- if (assignCount == 0) {
- finalAssignments = new Reference[5];
- finalVariables = new VariableBinding[5];
- } else {
- if (assignCount == finalAssignments.length)
- System.arraycopy(
- finalAssignments,
- 0,
- (finalAssignments = new Reference[assignCount * 2]),
- 0,
- assignCount);
- System.arraycopy(
- finalVariables,
- 0,
- (finalVariables = new VariableBinding[assignCount * 2]),
- 0,
- assignCount);
- }
- finalAssignments[assignCount] = finalAssignment;
- finalVariables[assignCount++] = binding;
- return true;
- }
-
- public void recordUsingNullReference(Scope scope, LocalVariableBinding local,
- Expression reference, int checkType, FlowInfo flowInfo) {
- if ((flowInfo.tagBits & FlowInfo.UNREACHABLE) == 0 && !flowInfo.isDefinitelyUnknown(local)) {
- if (deferNullDiagnostic) { // within an enclosing loop, be conservative
- switch (checkType) {
- case CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NULL:
- case CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NON_NULL:
- case CAN_ONLY_NULL | IN_COMPARISON_NULL:
- case CAN_ONLY_NULL | IN_COMPARISON_NON_NULL:
- case CAN_ONLY_NULL | IN_ASSIGNMENT:
- case CAN_ONLY_NULL | IN_INSTANCEOF:
- if (flowInfo.cannotBeNull(local)) {
- if (checkType == (CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NON_NULL)) {
- scope.problemReporter().localVariableRedundantCheckOnNonNull(local, reference);
- } else {
- scope.problemReporter().localVariableNonNullComparedToNull(local, reference);
- }
- return;
- }
- if (flowInfo.canOnlyBeNull(local)) {
- switch(checkType & CONTEXT_MASK) {
- case FlowContext.IN_COMPARISON_NULL:
- scope.problemReporter().localVariableRedundantCheckOnNull(local, reference);
- return;
- case FlowContext.IN_COMPARISON_NON_NULL:
- scope.problemReporter().localVariableNullComparedToNonNull(local, reference);
- return;
- case FlowContext.IN_ASSIGNMENT:
- scope.problemReporter().localVariableRedundantNullAssignment(local, reference);
- return;
- case FlowContext.IN_INSTANCEOF:
- scope.problemReporter().localVariableNullInstanceof(local, reference);
- return;
- }
- }
- break;
- case MAY_NULL :
- if (flowInfo.cannotBeNull(local)) {
- return;
- }
- if (flowInfo.canOnlyBeNull(local)) {
- scope.problemReporter().localVariableNullReference(local, reference);
- return;
- }
- break;
- default:
- // never happens
- }
- }
- else { // no enclosing loop, be as precise as possible right now
- switch (checkType) {
- case CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NULL:
- case CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NON_NULL:
- if (flowInfo.isDefinitelyNonNull(local)) {
- if (checkType == (CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NON_NULL)) {
- scope.problemReporter().localVariableRedundantCheckOnNonNull(local, reference);
- } else {
- scope.problemReporter().localVariableNonNullComparedToNull(local, reference);
- }
- return;
- }
- case CAN_ONLY_NULL | IN_COMPARISON_NULL:
- case CAN_ONLY_NULL | IN_COMPARISON_NON_NULL:
- case CAN_ONLY_NULL | IN_ASSIGNMENT:
- case CAN_ONLY_NULL | IN_INSTANCEOF:
- if (flowInfo.isDefinitelyNull(local)) {
- switch(checkType & CONTEXT_MASK) {
- case FlowContext.IN_COMPARISON_NULL:
- scope.problemReporter().localVariableRedundantCheckOnNull(local, reference);
- return;
- case FlowContext.IN_COMPARISON_NON_NULL:
- scope.problemReporter().localVariableNullComparedToNonNull(local, reference);
- return;
- case FlowContext.IN_ASSIGNMENT:
- scope.problemReporter().localVariableRedundantNullAssignment(local, reference);
- return;
- case FlowContext.IN_INSTANCEOF:
- scope.problemReporter().localVariableNullInstanceof(local, reference);
- return;
- }
- }
- break;
- case MAY_NULL :
- if (flowInfo.isDefinitelyNull(local)) {
- scope.problemReporter().localVariableNullReference(local, reference);
- return;
- }
- if (flowInfo.isPotentiallyNull(local)) {
- scope.problemReporter().localVariablePotentialNullReference(local, reference);
- return;
- }
- if (flowInfo.isDefinitelyNonNull(local)) {
- return; // shortcut: cannot be null
- }
- break;
- default:
- // never happens
- }
- }
- recordNullReference(local, reference, checkType);
- // prepare to re-check with try/catch flow info
- }
- }
-
- void removeFinalAssignmentIfAny(Reference reference) {
- for (int i = 0; i < assignCount; i++) {
- if (finalAssignments[i] == reference) {
- finalAssignments[i] = null;
- finalVariables[i] = null;
- return;
- }
- }
- }
-
-protected void recordNullReference(LocalVariableBinding local,
- Expression expression, int status) {
- if (this.nullCount == 0) {
- this.nullLocals = new LocalVariableBinding[5];
- this.nullReferences = new Expression[5];
- this.nullCheckTypes = new int[5];
- }
- else if (this.nullCount == this.nullLocals.length) {
- int newLength = this.nullCount * 2;
- System.arraycopy(this.nullLocals, 0,
- this.nullLocals = new LocalVariableBinding[newLength], 0,
- this.nullCount);
- System.arraycopy(this.nullReferences, 0,
- this.nullReferences = new Expression[newLength], 0,
- this.nullCount);
- System.arraycopy(this.nullCheckTypes, 0,
- this.nullCheckTypes = new int[newLength], 0,
- this.nullCount);
- }
- this.nullLocals[this.nullCount] = local;
- this.nullReferences[this.nullCount] = expression;
- this.nullCheckTypes[this.nullCount++] = status;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/FlowContext.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/FlowContext.java
deleted file mode 100644
index 91dd5c26..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/FlowContext.java
+++ /dev/null
@@ -1,597 +0,0 @@
-/*******************************************************************************
- * 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.compiler.flow;
-
-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.Expression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.LabeledStatement;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Reference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.SubRoutineStatement;
-import org.eclipse.wst.jsdt.internal.compiler.ast.TryStatement;
-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.LocalVariableBinding;
-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.lookup.TypeConstants;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.VariableBinding;
-
-/**
- * Reflects the context of code analysis, keeping track of enclosing
- * try statements, exception handlers, etc...
- */
-public class FlowContext implements TypeConstants {
-
- // preempt marks looping contexts
- public final static FlowContext NotContinuableContext = new FlowContext(null, null);
- public ASTNode associatedNode;
- public FlowContext parent;
- public NullInfoRegistry initsOnFinally;
- // only used within try blocks; remembers upstream flow info mergedWith
- // any null related operation happening within the try block
-
-boolean deferNullDiagnostic, preemptNullDiagnostic;
-
-public FlowContext(FlowContext parent, ASTNode associatedNode) {
- this.parent = parent;
- this.associatedNode = associatedNode;
- if (parent != null) {
- this.deferNullDiagnostic =
- parent.deferNullDiagnostic || parent.preemptNullDiagnostic;
- this.initsOnFinally = parent.initsOnFinally;
- }
-}
-
-
-
-public void checkExceptionHandlers(TypeBinding raisedException, ASTNode location, FlowInfo flowInfo, BlockScope scope) {
- // LIGHT-VERSION OF THE EQUIVALENT WITH AN ARRAY OF EXCEPTIONS
- // check that all the argument exception types are handled
- // JDK Compatible implementation - when an exception type is thrown,
- // all related catch blocks are marked as reachable... instead of those only
- // until the point where it is safely handled (Smarter - see comment at the end)
- FlowContext traversedContext = this;
- while (traversedContext != null) {
- SubRoutineStatement sub;
- if (((sub = traversedContext.subroutine()) != null) && sub.isSubRoutineEscaping()) {
- // traversing a non-returning subroutine means that all unhandled
- // exceptions will actually never get sent...
- return;
- }
-
- // filter exceptions that are locally caught from the innermost enclosing
- // try statement to the outermost ones.
- if (traversedContext instanceof ExceptionHandlingFlowContext) {
- ExceptionHandlingFlowContext exceptionContext =
- (ExceptionHandlingFlowContext) traversedContext;
- ReferenceBinding[] caughtExceptions;
- if ((caughtExceptions = exceptionContext.handledExceptions) != Binding.NO_EXCEPTIONS) {
- boolean definitelyCaught = false;
- for (int caughtIndex = 0, caughtCount = caughtExceptions.length;
- caughtIndex < caughtCount;
- caughtIndex++) {
- ReferenceBinding caughtException = caughtExceptions[caughtIndex];
- int state = caughtException == null
- ? Scope.EQUAL_OR_MORE_SPECIFIC /* any exception */
- : Scope.compareTypes(raisedException, caughtException);
- switch (state) {
- case Scope.EQUAL_OR_MORE_SPECIFIC :
- exceptionContext.recordHandlingException(
- caughtException,
- flowInfo.unconditionalInits(),
- raisedException,
- location,
- definitelyCaught);
- // was it already definitely caught ?
- definitelyCaught = true;
- break;
- case Scope.MORE_GENERIC :
- exceptionContext.recordHandlingException(
- caughtException,
- flowInfo.unconditionalInits(),
- raisedException,
- location,
- false);
- // was not caught already per construction
- }
- }
- if (definitelyCaught)
- return;
- }
- // method treatment for unchecked exceptions
- if (exceptionContext.isMethodContext) {
- if (raisedException.isUncheckedException(false))
- return;
-
- // anonymous constructors are allowed to throw any exceptions (their thrown exceptions
- // clause will be fixed up later as per JLS 8.6).
- if (exceptionContext.associatedNode instanceof AbstractMethodDeclaration){
- AbstractMethodDeclaration method = (AbstractMethodDeclaration)exceptionContext.associatedNode;
- if (method.isConstructor() && method.binding.declaringClass.isAnonymousType()){
-
- exceptionContext.mergeUnhandledException(raisedException);
- return; // no need to complain, will fix up constructor exceptions
- }
- }
- break; // not handled anywhere, thus jump to error handling
- }
- }
-
- 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
- }
- }
- traversedContext = traversedContext.parent;
- }
-}
-
-public void checkExceptionHandlers(TypeBinding[] raisedExceptions, ASTNode location, FlowInfo flowInfo, BlockScope scope) {
- // check that all the argument exception types are handled
- // JDK Compatible implementation - when an exception type is thrown,
- // all related catch blocks are marked as reachable... instead of those only
- // until the point where it is safely handled (Smarter - see comment at the end)
- int remainingCount; // counting the number of remaining unhandled exceptions
- int raisedCount; // total number of exceptions raised
- if ((raisedExceptions == null)
- || ((raisedCount = raisedExceptions.length) == 0))
- return;
- remainingCount = raisedCount;
-
- // duplicate the array of raised exceptions since it will be updated
- // (null replaces any handled exception)
- System.arraycopy(
- raisedExceptions,
- 0,
- (raisedExceptions = new TypeBinding[raisedCount]),
- 0,
- raisedCount);
- FlowContext traversedContext = this;
-
- while (traversedContext != null) {
- SubRoutineStatement sub;
- if (((sub = traversedContext.subroutine()) != null) && sub.isSubRoutineEscaping()) {
- // traversing a non-returning subroutine means that all unhandled
- // exceptions will actually never get sent...
- return;
- }
- // filter exceptions that are locally caught from the innermost enclosing
- // try statement to the outermost ones.
- if (traversedContext instanceof ExceptionHandlingFlowContext) {
- ExceptionHandlingFlowContext exceptionContext =
- (ExceptionHandlingFlowContext) traversedContext;
- ReferenceBinding[] caughtExceptions;
- if ((caughtExceptions = exceptionContext.handledExceptions) != Binding.NO_EXCEPTIONS) {
- int caughtCount = caughtExceptions.length;
- boolean[] locallyCaught = new boolean[raisedCount]; // at most
-
- for (int caughtIndex = 0; caughtIndex < caughtCount; caughtIndex++) {
- ReferenceBinding caughtException = caughtExceptions[caughtIndex];
- for (int raisedIndex = 0; raisedIndex < raisedCount; raisedIndex++) {
- TypeBinding raisedException;
- if ((raisedException = raisedExceptions[raisedIndex]) != null) {
- int state = caughtException == null
- ? Scope.EQUAL_OR_MORE_SPECIFIC /* any exception */
- : Scope.compareTypes(raisedException, caughtException);
- switch (state) {
- case Scope.EQUAL_OR_MORE_SPECIFIC :
- exceptionContext.recordHandlingException(
- caughtException,
- flowInfo.unconditionalInits(),
- raisedException,
- location,
- locallyCaught[raisedIndex]);
- // was already definitely caught ?
- if (!locallyCaught[raisedIndex]) {
- locallyCaught[raisedIndex] = true;
- // remember that this exception has been definitely caught
- remainingCount--;
- }
- break;
- case Scope.MORE_GENERIC :
- exceptionContext.recordHandlingException(
- caughtException,
- flowInfo.unconditionalInits(),
- raisedException,
- location,
- false);
- // was not caught already per construction
- }
- }
- }
- }
- // remove locally caught exceptions from the remaining ones
- for (int i = 0; i < raisedCount; i++) {
- if (locallyCaught[i]) {
- raisedExceptions[i] = null; // removed from the remaining ones.
- }
- }
- }
- // method treatment for unchecked exceptions
- if (exceptionContext.isMethodContext) {
- for (int i = 0; i < raisedCount; i++) {
- TypeBinding raisedException;
- if ((raisedException = raisedExceptions[i]) != null) {
- if (raisedException.isUncheckedException(false)) {
- remainingCount--;
- raisedExceptions[i] = null;
- }
- }
- }
- // anonymous constructors are allowed to throw any exceptions (their thrown exceptions
- // clause will be fixed up later as per JLS 8.6).
- if (exceptionContext.associatedNode instanceof AbstractMethodDeclaration){
- AbstractMethodDeclaration method = (AbstractMethodDeclaration)exceptionContext.associatedNode;
- if (method.isConstructor() && method.binding.declaringClass.isAnonymousType()){
-
- for (int i = 0; i < raisedCount; i++) {
- TypeBinding raisedException;
- if ((raisedException = raisedExceptions[i]) != null) {
- exceptionContext.mergeUnhandledException(raisedException);
- }
- }
- return; // no need to complain, will fix up constructor exceptions
- }
- }
- break; // not handled anywhere, thus jump to error handling
- }
- }
- if (remainingCount == 0)
- return;
-
- 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
- }
- }
- traversedContext = traversedContext.parent;
- }
- // if reaches this point, then there are some remaining unhandled exception types.
- nextReport: for (int i = 0; i < raisedCount; i++) {
- TypeBinding exception;
- if ((exception = raisedExceptions[i]) != null) {
- // only one complaint if same exception declared to be thrown more than once
- for (int j = 0; j < i; j++) {
- if (raisedExceptions[j] == exception) continue nextReport; // already reported
- }
- }
- }
-}
-
-
-/*
- * lookup through break labels
- */
-public FlowContext getTargetContextForBreakLabel(char[] labelName) {
- FlowContext current = this, lastNonReturningSubRoutine = null;
- while (current != null) {
- if (current.isNonReturningContext()) {
- lastNonReturningSubRoutine = current;
- }
- char[] currentLabelName;
- if (((currentLabelName = current.labelName()) != null)
- && CharOperation.equals(currentLabelName, labelName)) {
- ((LabeledStatement)current.associatedNode).bits |= ASTNode.LabelUsed;
- if (lastNonReturningSubRoutine == null)
- return current;
- return lastNonReturningSubRoutine;
- }
- current = current.parent;
- }
- // not found
- return null;
-}
-
-/*
- * lookup through continue labels
- */
-public FlowContext getTargetContextForContinueLabel(char[] labelName) {
- FlowContext current = this;
- FlowContext lastContinuable = null;
- FlowContext lastNonReturningSubRoutine = null;
-
- while (current != null) {
- if (current.isNonReturningContext()) {
- lastNonReturningSubRoutine = current;
- } else {
- if (current.isContinuable()) {
- lastContinuable = current;
- }
- }
-
- char[] currentLabelName;
- if ((currentLabelName = current.labelName()) != null && CharOperation.equals(currentLabelName, labelName)) {
- ((LabeledStatement)current.associatedNode).bits |= ASTNode.LabelUsed;
-
- // matching label found
- if ((lastContinuable != null)
- && (current.associatedNode.concreteStatement() == lastContinuable.associatedNode)) {
-
- if (lastNonReturningSubRoutine == null) return lastContinuable;
- return lastNonReturningSubRoutine;
- }
- // label is found, but not a continuable location
- return FlowContext.NotContinuableContext;
- }
- current = current.parent;
- }
- // not found
- return null;
-}
-
-/*
- * lookup a default break through breakable locations
- */
-public FlowContext getTargetContextForDefaultBreak() {
- FlowContext current = this, lastNonReturningSubRoutine = null;
- while (current != null) {
- if (current.isNonReturningContext()) {
- lastNonReturningSubRoutine = current;
- }
- if (current.isBreakable() && current.labelName() == null) {
- if (lastNonReturningSubRoutine == null) return current;
- return lastNonReturningSubRoutine;
- }
- current = current.parent;
- }
- // not found
- return null;
-}
-
-/*
- * lookup a default continue amongst continuable locations
- */
-public FlowContext getTargetContextForDefaultContinue() {
- FlowContext current = this, lastNonReturningSubRoutine = null;
- while (current != null) {
- if (current.isNonReturningContext()) {
- lastNonReturningSubRoutine = current;
- }
- if (current.isContinuable()) {
- if (lastNonReturningSubRoutine == null)
- return current;
- return lastNonReturningSubRoutine;
- }
- current = current.parent;
- }
- // not found
- return null;
-}
-
-public String individualToString() {
- return "Flow context"; //$NON-NLS-1$
-}
-
-public FlowInfo initsOnBreak() {
- return FlowInfo.DEAD_END;
-}
-
-public UnconditionalFlowInfo initsOnReturn() {
- return FlowInfo.DEAD_END;
-}
-
-public boolean isBreakable() {
- return false;
-}
-
-public boolean isContinuable() {
- return false;
-}
-
-public boolean isNonReturningContext() {
- return false;
-}
-
-public boolean isSubRoutine() {
- return false;
-}
-
-public char[] labelName() {
- return null;
-}
-
-public void recordBreakFrom(FlowInfo flowInfo) {
- // default implementation: do nothing
-}
-
-public void recordBreakTo(FlowContext targetContext) {
- // default implementation: do nothing
-}
-
-public void recordContinueFrom(FlowContext innerFlowContext, FlowInfo flowInfo) {
- // default implementation: do nothing
-}
-
-protected boolean recordFinalAssignment(VariableBinding variable, Reference finalReference) {
- return true; // keep going
-}
-
-/**
- * Record a null reference for use by deferred checks. Only looping or
- * finally contexts really record that information.
- * @param local the local variable involved in the check
- * @param expression the expression within which local lays
- * @param status the status against which the check must be performed; one of
- * {@link #CAN_ONLY_NULL CAN_ONLY_NULL}, {@link #CAN_ONLY_NULL_NON_NULL
- * CAN_ONLY_NULL_NON_NULL}, {@link #MAY_NULL MAY_NULL},
- * {@link #CAN_ONLY_NON_NULL CAN_ONLY_NON_NULL}, potentially
- * combined with a context indicator (one of {@link #IN_COMPARISON_NULL},
- * {@link #IN_COMPARISON_NON_NULL}, {@link #IN_ASSIGNMENT} or {@link #IN_INSTANCEOF})
- */
-protected void recordNullReference(LocalVariableBinding local,
- Expression expression, int status) {
- // default implementation: do nothing
-}
-
-public void recordReturnFrom(UnconditionalFlowInfo flowInfo) {
- // default implementation: do nothing
-}
-
-public void recordSettingFinal(VariableBinding variable, Reference finalReference, FlowInfo flowInfo) {
- if ((flowInfo.tagBits & FlowInfo.UNREACHABLE) == 0) {
- // for initialization inside looping statement that effectively loops
- FlowContext context = this;
- while (context != null) {
- if (!context.recordFinalAssignment(variable, finalReference)) {
- break; // no need to keep going
- }
- context = context.parent;
- }
- }
-}
-
-public static final int
- CAN_ONLY_NULL_NON_NULL = 0x0000,
- // check against null and non null, with definite values -- comparisons
- CAN_ONLY_NULL = 0x0001,
- // check against null, with definite values -- comparisons
- CAN_ONLY_NON_NULL = 0x0002,
- // check against non null, with definite values -- comparisons
- MAY_NULL = 0x0003,
- // check against null, with potential values -- NPE guard
- CHECK_MASK = 0x00FF,
- IN_COMPARISON_NULL = 0x0100,
- IN_COMPARISON_NON_NULL = 0x0200,
- // check happened in a comparison
- IN_ASSIGNMENT = 0x0300,
- // check happened in an assignment
- IN_INSTANCEOF = 0x0400,
- // check happened in an instanceof expression
- CONTEXT_MASK = ~CHECK_MASK;
-
-/**
- * Record a null reference for use by deferred checks. Only looping or
- * finally contexts really record that information. The context may
- * emit an error immediately depending on the status of local against
- * flowInfo and its nature (only looping of finally contexts defer part
- * of the checks; nonetheless, contexts that are nested into a looping or a
- * finally context get affected and delegate some checks to their enclosing
- * context).
- * @param scope the scope into which the check is performed
- * @param local the local variable involved in the check
- * @param reference the expression within which local lies
- * @param checkType the status against which the check must be performed; one
- * of {@link #CAN_ONLY_NULL CAN_ONLY_NULL}, {@link #CAN_ONLY_NULL_NON_NULL
- * CAN_ONLY_NULL_NON_NULL}, {@link #MAY_NULL MAY_NULL}, potentially
- * combined with a context indicator (one of {@link #IN_COMPARISON_NULL},
- * {@link #IN_COMPARISON_NON_NULL}, {@link #IN_ASSIGNMENT} or {@link #IN_INSTANCEOF})
- * @param flowInfo the flow info at the check point; deferring contexts will
- * perform supplementary checks against flow info instances that cannot
- * be known at the time of calling this method (they are influenced by
- * code that follows the current point)
- */
-public void recordUsingNullReference(Scope scope, LocalVariableBinding local,
- Expression reference, int checkType, FlowInfo flowInfo) {
- if ((flowInfo.tagBits & FlowInfo.UNREACHABLE) != 0 ||
- flowInfo.isDefinitelyUnknown(local)) {
- return;
- }
- switch (checkType) {
- case CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NULL:
- case CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NON_NULL:
- if (flowInfo.isDefinitelyNonNull(local)) {
- if (checkType == (CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NON_NULL)) {
- scope.problemReporter().localVariableRedundantCheckOnNonNull(local, reference);
- } else {
- scope.problemReporter().localVariableNonNullComparedToNull(local, reference);
- }
- return;
- }
- else if (flowInfo.cannotBeDefinitelyNullOrNonNull(local)) {
- return;
- }
- case CAN_ONLY_NULL | IN_COMPARISON_NULL:
- case CAN_ONLY_NULL | IN_COMPARISON_NON_NULL:
- case CAN_ONLY_NULL | IN_ASSIGNMENT:
- case CAN_ONLY_NULL | IN_INSTANCEOF:
- if (flowInfo.isDefinitelyNull(local)) {
- switch(checkType & CONTEXT_MASK) {
- case FlowContext.IN_COMPARISON_NULL:
- scope.problemReporter().localVariableRedundantCheckOnNull(local, reference);
- return;
- case FlowContext.IN_COMPARISON_NON_NULL:
- scope.problemReporter().localVariableNullComparedToNonNull(local, reference);
- return;
- case FlowContext.IN_ASSIGNMENT:
- scope.problemReporter().localVariableRedundantNullAssignment(local, reference);
- return;
- case FlowContext.IN_INSTANCEOF:
- scope.problemReporter().localVariableNullInstanceof(local, reference);
- return;
- }
- } else if (flowInfo.cannotBeDefinitelyNullOrNonNull(local)) {
- return;
- }
- break;
- case MAY_NULL :
- if (flowInfo.isDefinitelyNull(local)) {
- scope.problemReporter().localVariableNullReference(local, reference);
- return;
- }
- if (flowInfo.isPotentiallyNull(local)) {
- scope.problemReporter().localVariablePotentialNullReference(local, reference);
- return;
- }
- break;
- default:
- // never happens
- }
- if (this.parent != null) {
- this.parent.recordUsingNullReference(scope, local, reference, checkType,
- flowInfo);
- }
-}
-
-void removeFinalAssignmentIfAny(Reference reference) {
- // default implementation: do nothing
-}
-
-public SubRoutineStatement subroutine() {
- return null;
-}
-
-public String toString() {
- StringBuffer buffer = new StringBuffer();
- FlowContext current = this;
- int parentsCount = 0;
- while ((current = current.parent) != null) {
- parentsCount++;
- }
- FlowContext[] parents = new FlowContext[parentsCount + 1];
- current = this;
- int index = parentsCount;
- while (index >= 0) {
- parents[index--] = current;
- current = current.parent;
- }
- for (int i = 0; i < parentsCount; i++) {
- for (int j = 0; j < i; j++)
- buffer.append('\t');
- buffer.append(parents[i].individualToString()).append('\n');
- }
- buffer.append('*');
- for (int j = 0; j < parentsCount + 1; j++)
- buffer.append('\t');
- buffer.append(individualToString()).append('\n');
- return buffer.toString();
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/FlowInfo.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/FlowInfo.java
deleted file mode 100644
index 0ebf95c0..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/FlowInfo.java
+++ /dev/null
@@ -1,389 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.flow;
-
-import org.eclipse.wst.jsdt.internal.compiler.lookup.FieldBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.LocalVariableBinding;
-
-public abstract class FlowInfo {
-
- public int tagBits; // REACHABLE by default
- public final static int REACHABLE = 0;
- public final static int UNREACHABLE = 1;
- public final static int NULL_FLAG_MASK = 2;
-
- public final static int UNKNOWN = 0;
- public final static int NULL = 1;
- public final static int NON_NULL = -1;
-
- public static final UnconditionalFlowInfo DEAD_END; // Represents a dead branch status of initialization
- static {
- DEAD_END = new UnconditionalFlowInfo();
- DEAD_END.tagBits = UNREACHABLE;
- }
-
-/**
- * Add other inits to this flow info, then return this. The operation semantics
- * are to match as closely as possible the application to this flow info of all
- * the operations that resulted into otherInits.
- * @param otherInits other inits to add to this
- * @return this, modified according to otherInits information
- */
-abstract public FlowInfo addInitializationsFrom(FlowInfo otherInits);
-
-
-/**
- * Compose other inits over this flow info, then return this. The operation
- * semantics are to wave into this flow info the consequences of a possible
- * path into the operations that resulted into otherInits. The fact that this
- * path may be left unexecuted under peculiar conditions results into less
- * specific results than {@link #addInitializationsFrom(FlowInfo)
- * addInitializationsFrom}.
- * @param otherInits other inits to compose over this
- * @return this, modified according to otherInits information
- */
-abstract public FlowInfo addPotentialInitializationsFrom(FlowInfo otherInits);
-
- public FlowInfo asNegatedCondition() {
-
- return this;
- }
-
- public static FlowInfo conditional(FlowInfo initsWhenTrue, FlowInfo initsWhenFalse){
-
- // if (initsWhenTrue.equals(initsWhenFalse)) return initsWhenTrue; -- could optimize if #equals is defined
- return new ConditionalFlowInfo(initsWhenTrue, initsWhenFalse);
- }
-
-/**
- * Check whether a given local variable is known to be unable to gain a definite
- * non null or definite null status by the use of an enclosing flow info. The
- * semantics are that if the current flow info marks the variable as potentially
- * unknown or else as being both potentially null and potentially non null,
- * then it won't ever be promoted as definitely null or definitely non null. (It
- * could still get promoted to definite unknown).
- * @param local the variable to ckeck
- * @return true iff this flow info prevents local from being promoted to
- * definite non null or definite null against an enclosing flow info
- */
-public boolean cannotBeDefinitelyNullOrNonNull(LocalVariableBinding local) {
- return isPotentiallyUnknown(local) ||
- isPotentiallyNonNull(local) && isPotentiallyNull(local);
-}
-
-/**
- * Check whether a given local variable is known to be non null, either because
- * it is definitely non null, or because is has been tested against non null.
- * @param local the variable to ckeck
- * @return true iff local cannot be null for this flow info
- */
-public boolean cannotBeNull(LocalVariableBinding local) {
- return isDefinitelyNonNull(local) || isProtectedNonNull(local);
-}
-
-/**
- * Check whether a given local variable is known to be null, either because it
- * is definitely null, or because is has been tested against null.
- * @param local the variable to ckeck
- * @return true iff local can only be null for this flow info
- */
-public boolean canOnlyBeNull(LocalVariableBinding local) {
- return isDefinitelyNull(local) || isProtectedNull(local);
-}
-
-/**
- * Return a deep copy of the current instance.
- * @return a deep copy of this flow info
- */
- abstract public FlowInfo copy();
-
- public static UnconditionalFlowInfo initial(int maxFieldCount) {
- UnconditionalFlowInfo info = new UnconditionalFlowInfo();
- info.maxFieldCount = maxFieldCount;
- return info;
- }
-
-/**
- * Return the flow info that would result from the path associated to the
- * value false for the condition expression that generated this flow info.
- * May be this flow info if it is not an instance of {@link
- * ConditionalFlowInfo}. May have a side effect on subparts of this flow
- * info (subtrees get merged).
- * @return the flow info associated to the false branch of the condition
- * that generated this flow info
- */
-abstract public FlowInfo initsWhenFalse();
-
-/**
- * Return the flow info that would result from the path associated to the
- * value true for the condition expression that generated this flow info.
- * May be this flow info if it is not an instance of {@link
- * ConditionalFlowInfo}. May have a side effect on subparts of this flow
- * info (subtrees get merged).
- * @return the flow info associated to the true branch of the condition
- * that generated this flow info
- */
- abstract public FlowInfo initsWhenTrue();
-
- /**
- * Check status of definite assignment for a field.
- */
- abstract public boolean isDefinitelyAssigned(FieldBinding field);
-
- /**
- * Check status of definite assignment for a local.
- */
- public abstract boolean isDefinitelyAssigned(LocalVariableBinding local);
-
-/**
- * Check status of definite non-null value for a given local variable.
- * @param local the variable to ckeck
- * @return true iff local is definitely non null for this flow info
- */
- public abstract boolean isDefinitelyNonNull(LocalVariableBinding local);
-
-/**
- * Check status of definite null value for a given local variable.
- * @param local the variable to ckeck
- * @return true iff local is definitely null for this flow info
- */
-public abstract boolean isDefinitelyNull(LocalVariableBinding local);
-
-/**
- * Check status of definite unknown value for a given local variable.
- * @param local the variable to ckeck
- * @return true iff local is definitely unknown for this flow info
- */
-public abstract boolean isDefinitelyUnknown(LocalVariableBinding local);
-
- /**
- * Check status of potential assignment for a field.
- */
- abstract public boolean isPotentiallyAssigned(FieldBinding field);
-
- /**
- * Check status of potential assignment for a local variable.
- */
-
- abstract public boolean isPotentiallyAssigned(LocalVariableBinding field);
-
-/**
- * Check status of potential null assignment for a local. Return true if there
- * is a reasonable expectation that the variable be non null at this point.
- * @param local LocalVariableBinding - the binding for the checked local
- * @return true if there is a reasonable expectation that local be non null at
- * this point
- */
-public abstract boolean isPotentiallyNonNull(LocalVariableBinding local);
-
-/**
- * Check status of potential null assignment for a local. Return true if there
- * is a reasonable expectation that the variable be null at this point. This
- * includes the protected null case, so as to augment diagnostics, but does not
- * really check that someone deliberately assigned to null on any specific
- * path
- * @param local LocalVariableBinding - the binding for the checked local
- * @return true if there is a reasonable expectation that local be null at
- * this point
- */
-public abstract boolean isPotentiallyNull(LocalVariableBinding local);
-
-/**
- * Return true if the given local may have been assigned to an unknown value.
- * @param local the local to check
- * @return true if the given local may have been assigned to an unknown value
- */
-public abstract boolean isPotentiallyUnknown(LocalVariableBinding local);
-
-/**
- * Return true if the given local is protected by a test against a non null
- * value.
- * @param local the local to check
- * @return true if the given local is protected by a test against a non null
- */
-public abstract boolean isProtectedNonNull(LocalVariableBinding local);
-
-/**
- * Return true if the given local is protected by a test against null.
- * @param local the local to check
- * @return true if the given local is protected by a test against null
- */
-public abstract boolean isProtectedNull(LocalVariableBinding local);
-
-/**
- * Record that a local variable got checked to be non null.
- * @param local the checked local variable
- */
-abstract public void markAsComparedEqualToNonNull(LocalVariableBinding local);
-
-/**
- * Record that a local variable got checked to be null.
- * @param local the checked local variable
- */
-abstract public void markAsComparedEqualToNull(LocalVariableBinding local);
-
- /**
- * Record a field got definitely assigned.
- */
- abstract public void markAsDefinitelyAssigned(FieldBinding field);
-
- /**
- * Record a local got definitely assigned to a non-null value.
- */
- abstract public void markAsDefinitelyNonNull(LocalVariableBinding local);
-
- /**
- * Record a local got definitely assigned to null.
- */
- abstract public void markAsDefinitelyNull(LocalVariableBinding local);
-
- /**
- * Record a local got definitely assigned.
- */
- abstract public void markAsDefinitelyAssigned(LocalVariableBinding local);
-
-/**
- * Record a local got definitely assigned to an unknown value.
- */
-abstract public void markAsDefinitelyUnknown(LocalVariableBinding local);
-
-/**
- * Merge branches using optimized boolean conditions
- */
-public static UnconditionalFlowInfo mergedOptimizedBranches(
- FlowInfo initsWhenTrue, boolean isOptimizedTrue,
- FlowInfo initsWhenFalse, boolean isOptimizedFalse,
- boolean allowFakeDeadBranch) {
- UnconditionalFlowInfo mergedInfo;
- if (isOptimizedTrue){
- if (initsWhenTrue == FlowInfo.DEAD_END && allowFakeDeadBranch) {
- mergedInfo = initsWhenFalse.setReachMode(FlowInfo.UNREACHABLE).
- unconditionalInits();
- }
- else {
- mergedInfo =
- initsWhenTrue.addPotentialInitializationsFrom(initsWhenFalse.
- nullInfoLessUnconditionalCopy()).
- unconditionalInits();
- }
- }
- else if (isOptimizedFalse) {
- if (initsWhenFalse == FlowInfo.DEAD_END && allowFakeDeadBranch) {
- mergedInfo = initsWhenTrue.setReachMode(FlowInfo.UNREACHABLE).
- unconditionalInits();
- }
- else {
- mergedInfo =
- initsWhenFalse.addPotentialInitializationsFrom(initsWhenTrue.
- nullInfoLessUnconditionalCopy()).
- unconditionalInits();
- }
- }
- else {
- mergedInfo = initsWhenTrue.
- mergedWith(initsWhenFalse.unconditionalInits());
- }
- return mergedInfo;
-}
-
-/**
- * Return REACHABLE if this flow info is reachable, UNREACHABLE
- * else.
- * @return REACHABLE if this flow info is reachable, UNREACHABLE
- * else
- */
-public int reachMode() {
- return this.tagBits & UNREACHABLE;
-}
-
-/**
- * Return a flow info that carries the same information as the result of
- * {@link #initsWhenTrue() initsWhenTrue}, but warrantied to be different
- * from this.<br>
- * Caveat: side effects on the result may affect components of this.
- * @return the result of initsWhenTrue or a copy of it
- */
-abstract public FlowInfo safeInitsWhenTrue();
-
-/**
- * Set this flow info reach mode and return this.
- * @param reachMode one of {@link #REACHABLE REACHABLE} or {@link #UNREACHABLE UNREACHABLE}
- * @return this, with the reach mode set to reachMode
- */
-abstract public FlowInfo setReachMode(int reachMode);
-
-/**
- * Return the intersection of this and otherInits, that is
- * one of:<ul>
- * <li>the receiver updated in the following way:<ul>
- * <li>intersection of definitely assigned variables,
- * <li>union of potentially assigned variables,
- * <li>similar operations for null,</ul>
- * <li>or the receiver or otherInits if the other one is non
- * reachable.</ul>
- * otherInits is not affected, and is not returned either (no
- * need to protect the result).
- * @param otherInits the flow info to merge with this
- * @return the intersection of this and otherInits.
- */
-abstract public UnconditionalFlowInfo mergedWith(
- UnconditionalFlowInfo otherInits);
-
-/**
- * Return a copy of this unconditional flow info, deprived from its null
- * info. {@link #DEAD_END DEAD_END} is returned unmodified.
- * @return a copy of this unconditional flow info deprived from its null info
- */
-abstract public UnconditionalFlowInfo nullInfoLessUnconditionalCopy();
-
- public String toString(){
-
- if (this == DEAD_END){
- return "FlowInfo.DEAD_END"; //$NON-NLS-1$
- }
- return super.toString();
- }
-
-/**
- * Return a new flow info that holds the same information as this would after
- * a call to unconditionalInits, but leaving this info unaffected. Moreover,
- * the result can be modified without affecting this.
- * @return a new flow info carrying this unconditional flow info
- */
-abstract public UnconditionalFlowInfo unconditionalCopy();
-
-/**
- * Return a new flow info that holds the same information as this would after
- * a call to {@link #unconditionalInits() unconditionalInits} followed by the
- * erasure of fields specific information, but leaving this flow info unaffected.
- * @return a new flow info carrying the unconditional flow info for local variables
- */
-abstract public UnconditionalFlowInfo unconditionalFieldLessCopy();
-
-/**
- * Return a flow info that merges the possible paths of execution described by
- * this flow info. In case of an unconditional flow info, return this. In case
- * of a conditional flow info, merge branches recursively. Caveat: this may
- * be affected, and modifying the result may affect this.
- * @return a flow info that merges the possible paths of execution described by
- * this
- */
-abstract public UnconditionalFlowInfo unconditionalInits();
-
-/**
- * Return a new flow info that holds the same information as this would after
- * a call to {@link #unconditionalInits() unconditionalInits}, but leaving
- * this info unaffected. Side effects on the result might affect this though
- * (consider it as read only).
- * @return a flow info carrying this unconditional flow info
- */
-abstract public UnconditionalFlowInfo unconditionalInitsWithoutSideEffect();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/InitializationFlowContext.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/InitializationFlowContext.java
deleted file mode 100644
index 8c846c0b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/InitializationFlowContext.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.flow;
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode;
-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.ReferenceBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-/**
- * Reflects the context of code analysis, keeping track of enclosing
- * try statements, exception handlers, etc...
- */
-public class InitializationFlowContext extends ExceptionHandlingFlowContext {
-
- public int exceptionCount;
- public TypeBinding[] thrownExceptions = new TypeBinding[5];
- public ASTNode[] exceptionThrowers = new ASTNode[5];
- public FlowInfo[] exceptionThrowerFlowInfos = new FlowInfo[5];
-
- public InitializationFlowContext(
- FlowContext parent,
- ASTNode associatedNode,
- BlockScope scope) {
- super(
- parent,
- associatedNode,
- Binding.NO_EXCEPTIONS, // no exception allowed by default
- scope,
- FlowInfo.DEAD_END);
- }
-
- public void checkInitializerExceptions(
- BlockScope currentScope,
- FlowContext initializerContext,
- FlowInfo flowInfo) {
- for (int i = 0; i < exceptionCount; i++) {
- initializerContext.checkExceptionHandlers(
- thrownExceptions[i],
- exceptionThrowers[i],
- exceptionThrowerFlowInfos[i],
- currentScope);
- }
- }
-
- public String individualToString() {
-
- StringBuffer buffer = new StringBuffer("Initialization flow context"); //$NON-NLS-1$
- for (int i = 0; i < exceptionCount; i++) {
- buffer.append('[').append(thrownExceptions[i].readableName());
- buffer.append('-').append(exceptionThrowerFlowInfos[i].toString()).append(']');
- }
- return buffer.toString();
- }
-
- public void recordHandlingException(
- ReferenceBinding exceptionType,
- UnconditionalFlowInfo flowInfo,
- TypeBinding raisedException,
- ASTNode invocationSite,
- boolean wasMasked) {
-
- // even if unreachable code, need to perform unhandled exception diagnosis
- int size = thrownExceptions.length;
- if (exceptionCount == size) {
- System.arraycopy(
- thrownExceptions,
- 0,
- (thrownExceptions = new TypeBinding[size * 2]),
- 0,
- size);
- System.arraycopy(
- exceptionThrowers,
- 0,
- (exceptionThrowers = new ASTNode[size * 2]),
- 0,
- size);
- System.arraycopy(
- exceptionThrowerFlowInfos,
- 0,
- (exceptionThrowerFlowInfos = new FlowInfo[size * 2]),
- 0,
- size);
- }
- thrownExceptions[exceptionCount] = raisedException;
- exceptionThrowers[exceptionCount] = invocationSite;
- exceptionThrowerFlowInfos[exceptionCount++] = flowInfo.copy();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/InsideSubRoutineFlowContext.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/InsideSubRoutineFlowContext.java
deleted file mode 100644
index d8fa1ada..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/InsideSubRoutineFlowContext.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.flow;
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode;
-import org.eclipse.wst.jsdt.internal.compiler.ast.SubRoutineStatement;
-
-/**
- * Reflects the context of code analysis, keeping track of enclosing
- * try statements, exception handlers, etc...
- */
-public class InsideSubRoutineFlowContext extends FlowContext {
-
- public UnconditionalFlowInfo initsOnReturn;
-
-public InsideSubRoutineFlowContext(
- FlowContext parent,
- ASTNode associatedNode) {
- super(parent, associatedNode);
- this.initsOnReturn = FlowInfo.DEAD_END;
-}
-
-public String individualToString() {
- StringBuffer buffer = new StringBuffer("Inside SubRoutine flow context"); //$NON-NLS-1$
- buffer.append("[initsOnReturn -").append(this.initsOnReturn.toString()).append(']'); //$NON-NLS-1$
- return buffer.toString();
-}
-
-public UnconditionalFlowInfo initsOnReturn(){
- return this.initsOnReturn;
-}
-
-public boolean isNonReturningContext() {
- return ((SubRoutineStatement) this.associatedNode).isSubRoutineEscaping();
-}
-
-public void recordReturnFrom(UnconditionalFlowInfo flowInfo) {
- if ((flowInfo.tagBits & FlowInfo.UNREACHABLE) == 0) {
- if (this.initsOnReturn == FlowInfo.DEAD_END) {
- this.initsOnReturn = (UnconditionalFlowInfo) flowInfo.copy();
- } else {
- this.initsOnReturn = this.initsOnReturn.mergedWith(flowInfo);
- }
- }
-}
-
-public SubRoutineStatement subroutine() {
- return (SubRoutineStatement) this.associatedNode;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/LabelFlowContext.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/LabelFlowContext.java
deleted file mode 100644
index 82545c18..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/LabelFlowContext.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*******************************************************************************
- * 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.compiler.flow;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-
-/**
- * Reflects the context of code analysis, keeping track of enclosing
- * try statements, exception handlers, etc...
- */
-public class LabelFlowContext extends SwitchFlowContext {
-
- public char[] labelName;
-
-public LabelFlowContext(FlowContext parent, ASTNode associatedNode, char[] labelName, BlockScope scope) {
- super(parent, associatedNode);
- this.labelName = labelName;
- checkLabelValidity(scope);
-}
-
-void checkLabelValidity(BlockScope scope) {
- // check if label was already defined above
- FlowContext current = parent;
- while (current != null) {
- char[] currentLabelName;
- if (((currentLabelName = current.labelName()) != null)
- && CharOperation.equals(currentLabelName, labelName)) {
- scope.problemReporter().alreadyDefinedLabel(labelName, associatedNode);
- }
- current = current.parent;
- }
-}
-
-public String individualToString() {
- return "Label flow context [label:" + String.valueOf(labelName) + "]"; //$NON-NLS-2$ //$NON-NLS-1$
-}
-
-public char[] labelName() {
- return labelName;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/LoopingFlowContext.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/LoopingFlowContext.java
deleted file mode 100644
index bd0a6afd..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/LoopingFlowContext.java
+++ /dev/null
@@ -1,421 +0,0 @@
-/*******************************************************************************
- * 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.compiler.flow;
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Expression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Reference;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.LocalVariableBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Scope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.VariableBinding;
-
-/**
- * Reflects the context of code analysis, keeping track of enclosing
- * try statements, exception handlers, etc...
- */
-public class LoopingFlowContext extends SwitchFlowContext {
-
- public UnconditionalFlowInfo initsOnContinue = FlowInfo.DEAD_END;
- private UnconditionalFlowInfo upstreamNullFlowInfo;
- private LoopingFlowContext innerFlowContexts[] = null;
- private UnconditionalFlowInfo innerFlowInfos[] = null;
- private int innerFlowContextsCount = 0;
- private LabelFlowContext breakTargetContexts[] = null;
- private int breakTargetsCount = 0;
-
- Reference finalAssignments[];
- VariableBinding finalVariables[];
- int assignCount = 0;
-
- LocalVariableBinding[] nullLocals;
- Expression[] nullReferences;
- int[] nullCheckTypes;
- int nullCount;
-
- Scope associatedScope;
-
- public LoopingFlowContext(
- FlowContext parent,
- FlowInfo upstreamNullFlowInfo,
- ASTNode associatedNode,
- Scope associatedScope) {
- super(parent, associatedNode);
- preemptNullDiagnostic = true;
- // children will defer to this, which may defer to its own parent
- this.associatedScope = associatedScope;
- this.upstreamNullFlowInfo = upstreamNullFlowInfo.unconditionalCopy();
- }
-
-/**
- * Perform deferred checks relative to the null status of local variables.
- * @param scope the scope to which this context is associated
- * @param callerFlowInfo the flow info against which checks must be performed
- */
-public void complainOnDeferredNullChecks(BlockScope scope, FlowInfo callerFlowInfo) {
- for (int i = 0 ; i < this.innerFlowContextsCount ; i++) {
- this.upstreamNullFlowInfo.
- addPotentialNullInfoFrom(
- this.innerFlowContexts[i].upstreamNullFlowInfo).
- addPotentialNullInfoFrom(this.innerFlowInfos[i]);
- }
- this.innerFlowContextsCount = 0;
- UnconditionalFlowInfo flowInfo = this.upstreamNullFlowInfo.
- addPotentialNullInfoFrom(callerFlowInfo.unconditionalInitsWithoutSideEffect());
- if (this.deferNullDiagnostic) {
- // check only immutable null checks on innermost looping context
- for (int i = 0; i < this.nullCount; i++) {
- LocalVariableBinding local = this.nullLocals[i];
- Expression expression = this.nullReferences[i];
- // final local variable
- switch (this.nullCheckTypes[i]) {
- case CAN_ONLY_NON_NULL | IN_COMPARISON_NULL:
- case CAN_ONLY_NON_NULL | IN_COMPARISON_NON_NULL:
- if (flowInfo.isDefinitelyNonNull(local)) {
- this.nullReferences[i] = null;
- if (this.nullCheckTypes[i] == (CAN_ONLY_NON_NULL | IN_COMPARISON_NON_NULL)) {
- scope.problemReporter().localVariableRedundantCheckOnNonNull(local, expression);
- } else {
- scope.problemReporter().localVariableNonNullComparedToNull(local, expression);
- }
- continue;
- }
- break;
- case CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NULL:
- case CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NON_NULL:
- if (flowInfo.isDefinitelyNonNull(local)) {
- this.nullReferences[i] = null;
- if (this.nullCheckTypes[i] == (CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NON_NULL)) {
- scope.problemReporter().localVariableRedundantCheckOnNonNull(local, expression);
- } else {
- scope.problemReporter().localVariableNonNullComparedToNull(local, expression);
- }
- continue;
- }
- if (flowInfo.isDefinitelyNull(local)) {
- this.nullReferences[i] = null;
- if (this.nullCheckTypes[i] == (CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NULL)) {
- scope.problemReporter().localVariableRedundantCheckOnNull(local, expression);
- } else {
- scope.problemReporter().localVariableNullComparedToNonNull(local, expression);
- }
- continue;
- }
- break;
- case CAN_ONLY_NULL | IN_COMPARISON_NULL:
- case CAN_ONLY_NULL | IN_COMPARISON_NON_NULL:
- case CAN_ONLY_NULL | IN_ASSIGNMENT:
- case CAN_ONLY_NULL | IN_INSTANCEOF:
- if (flowInfo.isDefinitelyNull(local)) {
- this.nullReferences[i] = null;
- switch(this.nullCheckTypes[i] & CONTEXT_MASK) {
- case FlowContext.IN_COMPARISON_NULL:
- scope.problemReporter().localVariableRedundantCheckOnNull(local, expression);
- continue;
- case FlowContext.IN_COMPARISON_NON_NULL:
- scope.problemReporter().localVariableNullComparedToNonNull(local, expression);
- continue;
- case FlowContext.IN_ASSIGNMENT:
- scope.problemReporter().localVariableRedundantNullAssignment(local, expression);
- continue;
- case FlowContext.IN_INSTANCEOF:
- scope.problemReporter().localVariableNullInstanceof(local, expression);
- continue;
- }
- }
- break;
- case MAY_NULL:
- if (flowInfo.isDefinitelyNull(local)) {
- this.nullReferences[i] = null;
- scope.problemReporter().localVariableNullReference(local, expression);
- continue;
- }
- break;
- default:
- // never happens
- }
- this.parent.recordUsingNullReference(scope, local, expression,
- this.nullCheckTypes[i], flowInfo);
- }
- }
- else {
- // check inconsistent null checks on outermost looping context
- for (int i = 0; i < this.nullCount; i++) {
- Expression expression = this.nullReferences[i];
- // final local variable
- LocalVariableBinding local = this.nullLocals[i];
- switch (this.nullCheckTypes[i]) {
- case CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NULL:
- case CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NON_NULL:
- if (flowInfo.isDefinitelyNonNull(local)) {
- this.nullReferences[i] = null;
- if (this.nullCheckTypes[i] == (CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NON_NULL)) {
- scope.problemReporter().localVariableRedundantCheckOnNonNull(local, expression);
- } else {
- scope.problemReporter().localVariableNonNullComparedToNull(local, expression);
- }
- continue;
- }
- case CAN_ONLY_NULL | IN_COMPARISON_NULL:
- case CAN_ONLY_NULL | IN_COMPARISON_NON_NULL:
- case CAN_ONLY_NULL | IN_ASSIGNMENT:
- case CAN_ONLY_NULL | IN_INSTANCEOF:
- if (flowInfo.isDefinitelyNull(local)) {
- this.nullReferences[i] = null;
- switch(this.nullCheckTypes[i] & CONTEXT_MASK) {
- case FlowContext.IN_COMPARISON_NULL:
- scope.problemReporter().localVariableRedundantCheckOnNull(local, expression);
- continue;
- case FlowContext.IN_COMPARISON_NON_NULL:
- scope.problemReporter().localVariableNullComparedToNonNull(local, expression);
- continue;
- case FlowContext.IN_ASSIGNMENT:
- scope.problemReporter().localVariableRedundantNullAssignment(local, expression);
- continue;
- case FlowContext.IN_INSTANCEOF:
- scope.problemReporter().localVariableNullInstanceof(local, expression);
- continue;
- }
- }
- break;
- case MAY_NULL:
- if (flowInfo.isDefinitelyNull(local)) {
- this.nullReferences[i] = null;
- scope.problemReporter().localVariableNullReference(local, expression);
- continue;
- }
- if (flowInfo.isPotentiallyNull(local)) {
- this.nullReferences[i] = null;
- scope.problemReporter().localVariablePotentialNullReference(local, expression);
- continue;
- }
- break;
- default:
- // never happens
- }
- }
- }
- // propagate breaks
- for (int i = 0; i < this.breakTargetsCount; i++) {
- this.breakTargetContexts[i].initsOnBreak.addPotentialNullInfoFrom(flowInfo);
- }
-}
-
-
-
- public String individualToString() {
- StringBuffer buffer = new StringBuffer("Looping flow context"); //$NON-NLS-1$
- buffer.append("[initsOnBreak - ").append(initsOnBreak.toString()).append(']'); //$NON-NLS-1$
- buffer.append("[initsOnContinue - ").append(initsOnContinue.toString()).append(']'); //$NON-NLS-1$
- buffer.append("[finalAssignments count - ").append(assignCount).append(']'); //$NON-NLS-1$
- buffer.append("[nullReferences count - ").append(nullCount).append(']'); //$NON-NLS-1$
- return buffer.toString();
- }
-
- public boolean isContinuable() {
- return true;
- }
-
- public boolean isContinuedTo() {
- return initsOnContinue != FlowInfo.DEAD_END;
- }
-
-public void recordBreakTo(FlowContext targetContext) {
- if (targetContext instanceof LabelFlowContext) {
- int current;
- if ((current = this.breakTargetsCount++) == 0) {
- this.breakTargetContexts = new LabelFlowContext[2];
- } else if (current == this.breakTargetContexts.length) {
- System.arraycopy(this.breakTargetContexts, 0, this.breakTargetContexts = new LabelFlowContext[current + 2], 0, current);
- }
- this.breakTargetContexts[current] = (LabelFlowContext) targetContext;
- }
-}
-
-public void recordContinueFrom(FlowContext innerFlowContext, FlowInfo flowInfo) {
- if ((flowInfo.tagBits & FlowInfo.UNREACHABLE) == 0) {
- if ((initsOnContinue.tagBits & FlowInfo.UNREACHABLE) == 0) {
- initsOnContinue = initsOnContinue.
- mergedWith(flowInfo.unconditionalInitsWithoutSideEffect());
- }
- else {
- initsOnContinue = flowInfo.unconditionalCopy();
- }
- FlowContext inner = innerFlowContext;
- while (inner != this && !(inner instanceof LoopingFlowContext)) {
- inner = inner.parent;
- }
- if (inner == this) {
- this.upstreamNullFlowInfo.
- addPotentialNullInfoFrom(
- flowInfo.unconditionalInitsWithoutSideEffect());
- }
- else {
- int length = 0;
- if (this.innerFlowContexts == null) {
- this.innerFlowContexts = new LoopingFlowContext[5];
- this.innerFlowInfos = new UnconditionalFlowInfo[5];
- }
- else if (this.innerFlowContextsCount ==
- (length = this.innerFlowContexts.length) - 1) {
- System.arraycopy(this.innerFlowContexts, 0,
- (this.innerFlowContexts = new LoopingFlowContext[length + 5]),
- 0, length);
- System.arraycopy(this.innerFlowInfos, 0,
- (this.innerFlowInfos= new UnconditionalFlowInfo[length + 5]),
- 0, length);
- }
- this.innerFlowContexts[this.innerFlowContextsCount] = (LoopingFlowContext) inner;
- this.innerFlowInfos[this.innerFlowContextsCount++] =
- flowInfo.unconditionalInitsWithoutSideEffect();
- }
- }
-}
-
- protected boolean recordFinalAssignment(
- VariableBinding binding,
- Reference finalAssignment) {
-
- // do not consider variables which are defined inside this loop
- if (binding instanceof LocalVariableBinding) {
- Scope scope = ((LocalVariableBinding) binding).declaringScope;
- while ((scope = scope.parent) != null) {
- if (scope == associatedScope)
- return false;
- }
- }
- if (assignCount == 0) {
- finalAssignments = new Reference[5];
- finalVariables = new VariableBinding[5];
- } else {
- if (assignCount == finalAssignments.length)
- System.arraycopy(
- finalAssignments,
- 0,
- (finalAssignments = new Reference[assignCount * 2]),
- 0,
- assignCount);
- System.arraycopy(
- finalVariables,
- 0,
- (finalVariables = new VariableBinding[assignCount * 2]),
- 0,
- assignCount);
- }
- finalAssignments[assignCount] = finalAssignment;
- finalVariables[assignCount++] = binding;
- return true;
- }
-
-protected void recordNullReference(LocalVariableBinding local,
- Expression expression, int status) {
- if (nullCount == 0) {
- nullLocals = new LocalVariableBinding[5];
- nullReferences = new Expression[5];
- nullCheckTypes = new int[5];
- }
- else if (nullCount == nullLocals.length) {
- System.arraycopy(nullLocals, 0,
- nullLocals = new LocalVariableBinding[nullCount * 2], 0, nullCount);
- System.arraycopy(nullReferences, 0,
- nullReferences = new Expression[nullCount * 2], 0, nullCount);
- System.arraycopy(nullCheckTypes, 0,
- nullCheckTypes = new int[nullCount * 2], 0, nullCount);
- }
- nullLocals[nullCount] = local;
- nullReferences[nullCount] = expression;
- nullCheckTypes[nullCount++] = status;
-}
-
-public void recordUsingNullReference(Scope scope, LocalVariableBinding local,
- Expression reference, int checkType, FlowInfo flowInfo) {
- if ((flowInfo.tagBits & FlowInfo.UNREACHABLE) != 0 ||
- flowInfo.isDefinitelyUnknown(local)) {
- return;
- }
- switch (checkType) {
- case CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NULL:
- case CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NON_NULL:
- if (flowInfo.isDefinitelyNonNull(local)) {
- if (checkType == (CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NON_NULL)) {
- scope.problemReporter().localVariableRedundantCheckOnNonNull(local, reference);
- } else {
- scope.problemReporter().localVariableNonNullComparedToNull(local, reference);
- }
- } else if (flowInfo.isDefinitelyNull(local)) {
- if (checkType == (CAN_ONLY_NULL_NON_NULL | IN_COMPARISON_NULL)) {
- scope.problemReporter().localVariableRedundantCheckOnNull(local, reference);
- } else {
- scope.problemReporter().localVariableNullComparedToNonNull(local, reference);
- }
- } else if (! flowInfo.cannotBeDefinitelyNullOrNonNull(local)) {
- if (flowInfo.isPotentiallyNonNull(local)) {
- recordNullReference(local, reference, CAN_ONLY_NON_NULL | checkType & CONTEXT_MASK);
- } else {
- recordNullReference(local, reference, checkType);
- }
- }
- return;
- case CAN_ONLY_NULL | IN_COMPARISON_NULL:
- case CAN_ONLY_NULL | IN_COMPARISON_NON_NULL:
- case CAN_ONLY_NULL | IN_ASSIGNMENT:
- case CAN_ONLY_NULL | IN_INSTANCEOF:
- if (flowInfo.isPotentiallyNonNull(local)
- || flowInfo.isPotentiallyUnknown(local)) {
- return;
- }
- if (flowInfo.isDefinitelyNull(local)) {
- switch(checkType & CONTEXT_MASK) {
- case FlowContext.IN_COMPARISON_NULL:
- scope.problemReporter().localVariableRedundantCheckOnNull(local, reference);
- return;
- case FlowContext.IN_COMPARISON_NON_NULL:
- scope.problemReporter().localVariableNullComparedToNonNull(local, reference);
- return;
- case FlowContext.IN_ASSIGNMENT:
- scope.problemReporter().localVariableRedundantNullAssignment(local, reference);
- return;
- case FlowContext.IN_INSTANCEOF:
- scope.problemReporter().localVariableNullInstanceof(local, reference);
- return;
- }
- }
- recordNullReference(local, reference, checkType);
- return;
- case MAY_NULL :
- if (flowInfo.isDefinitelyNonNull(local)) {
- return;
- }
- if (flowInfo.isDefinitelyNull(local)) {
- scope.problemReporter().localVariableNullReference(local, reference);
- return;
- }
- if (flowInfo.isPotentiallyNull(local)) {
- scope.problemReporter().localVariablePotentialNullReference(local, reference);
- return;
- }
- recordNullReference(local, reference, checkType);
- return;
- default:
- // never happens
- }
-}
-
- void removeFinalAssignmentIfAny(Reference reference) {
- for (int i = 0; i < assignCount; i++) {
- if (finalAssignments[i] == reference) {
- finalAssignments[i] = null;
- finalVariables[i] = null;
- return;
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/NullInfoRegistry.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/NullInfoRegistry.java
deleted file mode 100644
index bfb4b7d3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/NullInfoRegistry.java
+++ /dev/null
@@ -1,377 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.flow;
-
-import org.eclipse.wst.jsdt.internal.compiler.lookup.LocalVariableBinding;
-
-/**
- * A degenerate form of UnconditionalFlowInfo explicitly meant to capture
- * the effects of null related operations within try blocks. Given the fact
- * that a try block might exit at any time, a null related operation that
- * occurs within such a block mitigates whatever we know about the previous
- * null status of involved variables. NullInfoRegistry handles that
- * by negating upstream definite information that clashes with what a given
- * statement contends about the same variable. It also implements
- * {@link #mitigateNullInfoOf(FlowInfo) mitigateNullInfo} so as to elaborate the
- * flow info presented in input of finally blocks.
- */
-public class NullInfoRegistry extends UnconditionalFlowInfo {
- // significant states at this level:
- // def. non null, def. null, def. unknown, prot. non null
-
-// PREMATURE implement coverage and low level tests
-
-/**
- * Make a new null info registry, using an upstream flow info. All definite
- * assignments of the upstream are carried forward, since a try block may
- * exit before its first statement.
- * @param upstream - UnconditionalFlowInfo: the flow info before we enter the
- * try block; only definite assignments are considered; this parameter is
- * not modified by this constructor
- */
-public NullInfoRegistry(UnconditionalFlowInfo upstream) {
- this.maxFieldCount = upstream.maxFieldCount;
- if ((upstream.tagBits & NULL_FLAG_MASK) != 0) {
- long u1, u2, u3, u4, nu2, nu3, nu4;
- this.nullBit2 = (u1 = upstream.nullBit1)
- & (u2 = upstream.nullBit2)
- & (nu3 = ~(u3 = upstream.nullBit3))
- & (nu4 = ~(u4 = upstream.nullBit4));
- this.nullBit3 = u1 & (nu2 = ~u2) & u3 & nu4;
- this.nullBit4 = u1 & nu2 &nu3 & u4;
- if ((this.nullBit2 | this.nullBit3 | this.nullBit4) != 0) {
- this.tagBits |= NULL_FLAG_MASK;
- }
- if (upstream.extra != null) {
- this.extra = new long[extraLength][];
- int length = upstream.extra[2].length;
- for (int i = 2; i < extraLength; i++) {
- this.extra[i] = new long[length];
- }
- for (int i = 0; i < length; i++) {
- this.extra[2 + 1][i] = (u1 = upstream.extra[1 + 1][i])
- & (u2 = upstream.extra[2 + 1][i])
- & (nu3 = ~(u3 = upstream.extra[3 + 1][i]))
- & (nu4 = ~(u4 = upstream.extra[4 + 1][i]));
- this.extra[3 + 1][i] = u1 & (nu2 = ~u2) & u3 & nu4;
- this.extra[4 + 1][i] = u1 & nu2 &nu3 & u4;
- if ((this.extra[2 + 1][i] | this.extra[3 + 1][i] | this.extra[4 + 1][i]) != 0) {
- this.tagBits |= NULL_FLAG_MASK;
- }
- }
- }
- }
-}
-
-/**
- * Add the information held by another NullInfoRegistry instance to this,
- * then return this.
- * @param other - NullInfoRegistry: the information to add to this
- * @return this, modified to carry the information held by other
- */
-public NullInfoRegistry add(NullInfoRegistry other) {
- if ((other.tagBits & NULL_FLAG_MASK) == 0) {
- return this;
- }
- this.tagBits |= NULL_FLAG_MASK;
- this.nullBit1 |= other.nullBit1;
- this.nullBit2 |= other.nullBit2;
- this.nullBit3 |= other.nullBit3;
- this.nullBit4 |= other.nullBit4;
- if (other.extra != null) {
- if (this.extra == null) {
- this.extra = new long[extraLength][];
- for (int i = 2, length = other.extra[2].length; i < extraLength; i++) {
- System.arraycopy(other.extra[i], 0,
- (this.extra[i] = new long[length]), 0, length);
- }
- } else {
- int length = this.extra[2].length, otherLength = other.extra[2].length;
- if (otherLength > length) {
- for (int i = 2; i < extraLength; i++) {
- System.arraycopy(this.extra[i], 0,
- (this.extra[i] = new long[otherLength]), 0, length);
- System.arraycopy(other.extra[i], length,
- this.extra[i], length, otherLength - length);
- }
- } else if (otherLength < length) {
- length = otherLength;
- }
- for (int i = 2; i < extraLength; i++) {
- for (int j = 0; j < length; j++) {
- this.extra[i][j] |= other.extra[i][j];
- }
- }
- }
- }
- return this;
-}
-
-public void markAsComparedEqualToNonNull(LocalVariableBinding local) {
- // protected from non-object locals in calling methods
- if (this != DEAD_END) {
- this.tagBits |= NULL_FLAG_MASK;
- int position;
- // position is zero-based
- if ((position = getLocalID(local)) < BitCacheSize) { // use bits
- // set protected non null
- this.nullBit1 |= (1L << position);
- if (coverageTestFlag && coverageTestId == 290) {
- this.nullBit1 = 0;
- }
- }
- else {
- // use extra vector
- int vectorIndex = (position / BitCacheSize) - 1;
- if (this.extra == null) {
- int length = vectorIndex + 1;
- this.extra = new long[extraLength][];
- for (int j = 2; j < extraLength; j++) {
- this.extra[j] = new long[length];
- }
- }
- else {
- int oldLength; // might need to grow the arrays
- if (vectorIndex >= (oldLength = this.extra[2].length)) {
- for (int j = 2; j < extraLength; j++) {
- System.arraycopy(this.extra[j], 0,
- (this.extra[j] = new long[vectorIndex + 1]), 0,
- oldLength);
- }
- }
- }
- this.extra[2][vectorIndex] |= (1L << (position % BitCacheSize));
- if (coverageTestFlag && coverageTestId == 300) {
- this.extra[5][vectorIndex] = ~0;
- }
- }
- }
-}
-
-public void markAsDefinitelyNonNull(LocalVariableBinding local) {
- // protected from non-object locals in calling methods
- if (this != DEAD_END) {
- this.tagBits |= NULL_FLAG_MASK;
- int position;
- // position is zero-based
- if ((position = getLocalID(local)) < BitCacheSize) { // use bits
- // set assigned non null
- this.nullBit3 |= (1L << position);
- if (coverageTestFlag && coverageTestId == 290) {
- this.nullBit1 = 0;
- }
- }
- else {
- // use extra vector
- int vectorIndex = (position / BitCacheSize) - 1;
- if (this.extra == null) {
- int length = vectorIndex + 1;
- this.extra = new long[extraLength][];
- for (int j = 2; j < extraLength; j++) {
- this.extra[j] = new long[length];
- }
- }
- else {
- int oldLength; // might need to grow the arrays
- if (vectorIndex >= (oldLength = this.extra[2].length)) {
- for (int j = 2; j < extraLength; j++) {
- System.arraycopy(this.extra[j], 0,
- (this.extra[j] = new long[vectorIndex + 1]), 0,
- oldLength);
- }
- }
- }
- this.extra[4][vectorIndex] |= (1L << (position % BitCacheSize));
- if (coverageTestFlag && coverageTestId == 300) {
- this.extra[5][vectorIndex] = ~0;
- }
- }
- }
-}
-// PREMATURE consider ignoring extra 0 to 2 included - means a1 should not be used either
-// PREMATURE project protected non null onto something else
-public void markAsDefinitelyNull(LocalVariableBinding local) {
- // protected from non-object locals in calling methods
- if (this != DEAD_END) {
- this.tagBits |= NULL_FLAG_MASK;
- int position;
- // position is zero-based
- if ((position = getLocalID(local)) < BitCacheSize) { // use bits
- // set assigned null
- this.nullBit2 |= (1L << position);
- if (coverageTestFlag && coverageTestId == 290) {
- this.nullBit1 = 0;
- }
- }
- else {
- // use extra vector
- int vectorIndex = (position / BitCacheSize) - 1;
- if (this.extra == null) {
- int length = vectorIndex + 1;
- this.extra = new long[extraLength][];
- for (int j = 2; j < extraLength; j++) {
- this.extra[j] = new long[length];
- }
- }
- else {
- int oldLength; // might need to grow the arrays
- if (vectorIndex >= (oldLength = this.extra[2].length)) {
- for (int j = 2; j < extraLength; j++) {
- System.arraycopy(this.extra[j], 0,
- (this.extra[j] = new long[vectorIndex + 1]), 0,
- oldLength);
- }
- }
- }
- this.extra[3][vectorIndex] |= (1L << (position % BitCacheSize));
- if (coverageTestFlag && coverageTestId == 300) {
- this.extra[5][vectorIndex] = ~0;
- }
- }
- }
-}
-
-public void markAsDefinitelyUnknown(LocalVariableBinding local) {
- // protected from non-object locals in calling methods
- if (this != DEAD_END) {
- this.tagBits |= NULL_FLAG_MASK;
- int position;
- // position is zero-based
- if ((position = getLocalID(local)) < BitCacheSize) { // use bits
- // set assigned unknown
- this.nullBit4 |= (1L << position);
- if (coverageTestFlag && coverageTestId == 290) {
- this.nullBit1 = 0;
- }
- }
- else {
- // use extra vector
- int vectorIndex = (position / BitCacheSize) - 1;
- if (this.extra == null) {
- int length = vectorIndex + 1;
- this.extra = new long[extraLength][];
- for (int j = 2; j < extraLength; j++) {
- this.extra[j] = new long[length];
- }
- }
- else {
- int oldLength; // might need to grow the arrays
- if (vectorIndex >= (oldLength = this.extra[2].length)) {
- for (int j = 2; j < extraLength; j++) {
- System.arraycopy(this.extra[j], 0,
- (this.extra[j] = new long[vectorIndex + 1]), 0,
- oldLength);
- }
- }
- }
- this.extra[5][vectorIndex] |= (1L << (position % BitCacheSize));
- if (coverageTestFlag && coverageTestId == 300) {
- this.extra[5][vectorIndex] = ~0;
- }
- }
- }
-}
-
-/**
- * Mitigate the definite and protected info of flowInfo, depending on what
- * this null info registry knows about potential assignments and messages
- * sends involving locals. May return flowInfo unchanged, or a modified,
- * fresh copy of flowInfo.
- * @param flowInfo - FlowInfo: the flow information that this null info
- * registry may mitigate
- * @return a copy of flowInfo carrying mitigated information, or else
- * flowInfo unchanged
- */
-public UnconditionalFlowInfo mitigateNullInfoOf(FlowInfo flowInfo) {
- if ((this.tagBits & NULL_FLAG_MASK) == 0) {
- return flowInfo.unconditionalInits();
- }
- long m, m1, nm1, m2, nm2, m3, a2, a3, a4, s1, s2, ns2, s3, ns3, s4, ns4;
- boolean newCopy = false;
- UnconditionalFlowInfo source = flowInfo.unconditionalInits();
- // clear incompatible protections
- m1 = (s1 = source.nullBit1) & (s3 = source.nullBit3)
- & (s4 = source.nullBit4)
- // prot. non null
- & ((a2 = this.nullBit2) | (a4 = this.nullBit4));
- // null or unknown
- m2 = s1 & (s2 = this.nullBit2) & (s3 ^ s4)
- // prot. null
- & ((a3 = this.nullBit3) | a4);
- // non null or unknown
- // clear incompatible assignments
- // PREMATURE check effect of protected non null (no NPE on call)
- // TODO (maxime) code extensive implementation tests
- m3 = s1 & (s2 & (ns3 = ~s3) & (ns4 = ~s4) & (a3 | a4)
- | (ns2 = ~s2) & s3 & ns4 & (a2 | a4)
- | ns2 & ns3 & s4 & (a2 | a3));
- if ((m = (m1 | m2 | m3)) != 0) {
- newCopy = true;
- source = source.unconditionalCopy();
- source.nullBit1 &= ~m;
- source.nullBit2 &= (nm1 = ~m1) & ((nm2 = ~m2) | a4);
- source.nullBit3 &= (nm1 | a2) & nm2;
- source.nullBit4 &= nm1 & nm2;
- }
- if (this.extra != null && source.extra != null) {
- int length = this.extra[2].length, sourceLength = source.extra[0].length;
- if (sourceLength < length) {
- length = sourceLength;
- }
- for (int i = 0; i < length; i++) {
- m1 = (s1 = source.extra[1 + 1][i]) & (s3 = source.extra[3 + 1][i])
- & (s4 = source.extra[4 + 1][i])
- & ((a2 = this.extra[2 + 1][i]) | (a4 = this.extra[4 + 1][i]));
- m2 = s1 & (s2 = this.extra[2 + 1][i]) & (s3 ^ s4)
- & ((a3 = this.extra[3 + 1][i]) | a4);
- m3 = s1 & (s2 & (ns3 = ~s3) & (ns4 = ~s4) & (a3 | a4)
- | (ns2 = ~s2) & s3 & ns4 & (a2 | a4)
- | ns2 & ns3 & s4 & (a2 | a3));
- if ((m = (m1 | m2 | m3)) != 0) {
- if (! newCopy) {
- newCopy = true;
- source = source.unconditionalCopy();
- }
- source.extra[1 + 1][i] &= ~m;
- source.extra[2 + 1][i] &= (nm1 = ~m1) & ((nm2 = ~m2) | a4);
- source.extra[3 + 1][i] &= (nm1 | a2) & nm2;
- source.extra[4 + 1][i] &= nm1 & nm2;
- }
- }
- }
- return source;
-}
-
-public String toString(){
- if (this.extra == null) {
- return "NullInfoRegistry<" + this.nullBit1 //$NON-NLS-1$
- + this.nullBit2 + this.nullBit3 + this.nullBit4
- + ">"; //$NON-NLS-1$
- }
- else {
- String nullS = "NullInfoRegistry<[" + this.nullBit1 //$NON-NLS-1$
- + this.nullBit2 + this.nullBit3 + this.nullBit4;
- int i, ceil;
- for (i = 0, ceil = this.extra[0].length > 3 ?
- 3 :
- this.extra[0].length;
- i < ceil; i++) {
- nullS += "," + this.extra[2][i] //$NON-NLS-1$
- + this.extra[3][i] + this.extra[4][i] + this.extra[5][i];
- }
- if (ceil < this.extra[0].length) {
- nullS += ",..."; //$NON-NLS-1$
- }
- return nullS + "]>"; //$NON-NLS-1$
- }
-}
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/SwitchFlowContext.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/SwitchFlowContext.java
deleted file mode 100644
index de5f5e2e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/SwitchFlowContext.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*******************************************************************************
- * 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.compiler.flow;
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode;
-
-/**
- * Reflects the context of code analysis, keeping track of enclosing
- * try statements, exception handlers, etc...
- */
-public class SwitchFlowContext extends FlowContext {
-
- public UnconditionalFlowInfo initsOnBreak = FlowInfo.DEAD_END;
-
-public SwitchFlowContext(FlowContext parent, ASTNode associatedNode ) {
- super(parent, associatedNode);
-}
-
-
-
-public String individualToString() {
- StringBuffer buffer = new StringBuffer("Switch flow context"); //$NON-NLS-1$
- buffer.append("[initsOnBreak -").append(initsOnBreak.toString()).append(']'); //$NON-NLS-1$
- return buffer.toString();
-}
-
-public boolean isBreakable() {
- return true;
-}
-
-public void recordBreakFrom(FlowInfo flowInfo) {
- if ((initsOnBreak.tagBits & FlowInfo.UNREACHABLE) == 0) {
- initsOnBreak = initsOnBreak.mergedWith(flowInfo.unconditionalInits());
- }
- else {
- initsOnBreak = flowInfo.unconditionalCopy();
- }
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/UnconditionalFlowInfo.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/UnconditionalFlowInfo.java
deleted file mode 100644
index 8aef848c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/flow/UnconditionalFlowInfo.java
+++ /dev/null
@@ -1,1713 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.flow;
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.FieldBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.LocalVariableBinding;
-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.TagBits;
-
-/**
- * Record initialization status during definite assignment analysis
- *
- * No caching of pre-allocated instances.
- */
-public class UnconditionalFlowInfo extends FlowInfo {
- // Coverage tests
- /**
- * Exception raised when unexpected behavior is detected during coverage
- * tests.
- */
- public static class AssertionFailedException extends RuntimeException {
- private static final long serialVersionUID = 1827352841030089703L;
-
- public AssertionFailedException(String message) {
- super(message);
- }
- }
-
- // Coverage tests need that the code be instrumented. The following flag
- // controls whether the instrumented code is compiled in or not, and whether
- // the coverage tests methods run or not.
- public final static boolean coverageTestFlag = false;
- // never release with the coverageTestFlag set to true
- public static int coverageTestId;
-
- // assignment bits - first segment
- public long definiteInits;
- public long potentialInits;
-
- // null bits - first segment
- public long
- nullBit1,
- nullBit2,
- nullBit3,
- nullBit4;
-/*
- nullBit1
- nullBit2...
- 0000 start
- 0001 pot. unknown
- 0010 pot. non null
- 0011 pot. nn & pot. un
- 0100 pot. null
- 0101 pot. n & pot. un
- 0110 pot. n & pot. nn
- 1001 def. unknown
- 1010 def. non null
- 1011 pot. nn & prot. nn
- 1100 def. null
- 1101 pot. n & prot. n
- 1110 prot. null
- 1111 prot. non null
- */
-
- // extra segments
- public static final int extraLength = 6;
- public long extra[][];
- // extra bit fields for larger numbers of fields/variables
- // extra[0] holds definiteInits values, extra[1] potentialInits, etc.
- // lifecycle is extra == null or else all extra[]'s are allocated
- // arrays which have the same size
-
- public int maxFieldCount; // limit between fields and locals
-
- // Constants
- public static final int BitCacheSize = 64; // 64 bits in a long.
-
-
-public FlowInfo addInitializationsFrom(FlowInfo inits) {
- if (this == DEAD_END)
- return this;
- if (inits == DEAD_END)
- return this;
- UnconditionalFlowInfo otherInits = inits.unconditionalInits();
-
- // union of definitely assigned variables,
- this.definiteInits |= otherInits.definiteInits;
- // union of potentially set ones
- this.potentialInits |= otherInits.potentialInits;
- // combine null information
- boolean thisHadNulls = (this.tagBits & NULL_FLAG_MASK) != 0,
- otherHasNulls = (otherInits.tagBits & NULL_FLAG_MASK) != 0;
- long
- a1, a2, a3, a4,
- na1, na2, na3, na4,
- b1, b2, b3, b4,
- nb1, nb2, nb3, nb4;
- if (otherHasNulls) {
- if (!thisHadNulls) {
- this.nullBit1 = otherInits.nullBit1;
- this.nullBit2 = otherInits.nullBit2;
- this.nullBit3 = otherInits.nullBit3;
- this.nullBit4 = otherInits.nullBit4;
- if (coverageTestFlag && coverageTestId == 1) {
- this.nullBit4 = ~0;
- }
- }
- else {
- this.nullBit1 = (b1 = otherInits.nullBit1)
- | (a1 = this.nullBit1) & ((a3 = this.nullBit3)
- & (a4 = this.nullBit4) & (nb2 = ~(b2 = otherInits.nullBit2))
- & (nb4 = ~(b4 = otherInits.nullBit4))
- | ((na4 = ~a4) | (na3 = ~a3))
- & ((na2 = ~(a2 = this.nullBit2)) & nb2
- | a2 & (nb3 = ~(b3 = otherInits.nullBit3)) & nb4));
- this.nullBit2 = b2 & (nb4 | nb3)
- | na3 & na4 & b2
- | a2 & (nb3 & nb4
- | (nb1 = ~b1) & (na3 | (na1 = ~a1))
- | a1 & b2);
- this.nullBit3 = b3 & (nb1 & (b2 | a2 | na1)
- | b1 & (b4 | nb2 | a1 & a3)
- | na1 & na2 & na4)
- | a3 & nb2 & nb4
- | nb1 & ((na2 & a4 | na1) & a3
- | a1 & na2 & na4 & b2);
- this.nullBit4 = nb1 & (a4 & (na3 & nb3 | (a3 | na2) & nb2)
- | a1 & (a3 & nb2 & b4
- | a2 & b2 & (b4 | a3 & na4 & nb3)))
- | b1 & (a3 & a4 & b4
- | na2 & na4 & nb3 & b4
- | a2 & ((b3 | a4) & b4
- | na3 & a4 & b2 & b3)
- | na1 & (b4 | (a4 | a2) & b2 & b3))
- | (na1 & (na3 & nb3 | na2 & nb2)
- | a1 & (nb2 & nb3 | a2 & a3)) & b4;
- if (coverageTestFlag && coverageTestId == 2) {
- this.nullBit4 = ~0;
- }
- }
- this.tagBits |= NULL_FLAG_MASK; // in all cases - avoid forgetting extras
- }
- // treating extra storage
- if (this.extra != null || otherInits.extra != null) {
- int mergeLimit = 0, copyLimit = 0;
- if (this.extra != null) {
- if (otherInits.extra != null) {
- // both sides have extra storage
- int length, otherLength;
- if ((length = this.extra[0].length) <
- (otherLength = otherInits.extra[0].length)) {
- // current storage is shorter -> grow current
- for (int j = 0; j < extraLength; j++) {
- System.arraycopy(this.extra[j], 0,
- (this.extra[j] = new long[otherLength]), 0, length);
- }
- mergeLimit = length;
- copyLimit = otherLength;
- if (coverageTestFlag && coverageTestId == 3) {
- throw new AssertionFailedException("COVERAGE 3"); //$NON-NLS-1$
- }
- } else {
- // current storage is longer
- mergeLimit = otherLength;
- if (coverageTestFlag && coverageTestId == 4) {
- throw new AssertionFailedException("COVERAGE 4"); //$NON-NLS-1$
- }
- }
- }
- } else if (otherInits.extra != null) {
- // no storage here, but other has extra storage.
- // shortcut regular copy because array copy is better
- int otherLength;
- this.extra = new long[extraLength][];
- System.arraycopy(otherInits.extra[0], 0,
- (this.extra[0] = new long[otherLength =
- otherInits.extra[0].length]), 0, otherLength);
- System.arraycopy(otherInits.extra[1], 0,
- (this.extra[1] = new long[otherLength]), 0, otherLength);
- if (otherHasNulls) {
- for (int j = 2; j < extraLength; j++) {
- System.arraycopy(otherInits.extra[j], 0,
- (this.extra[j] = new long[otherLength]), 0, otherLength);
- }
- if (coverageTestFlag && coverageTestId == 5) {
- this.extra[5][otherLength - 1] = ~0;
- }
- }
- else {
- for (int j = 2; j < extraLength; j++) {
- this.extra[j] = new long[otherLength];
- }
- if (coverageTestFlag && coverageTestId == 6) {
- throw new AssertionFailedException("COVERAGE 6"); //$NON-NLS-1$
- }
- }
- }
- int i;
- // manage definite assignment info
- for (i = 0; i < mergeLimit; i++) {
- this.extra[0][i] |= otherInits.extra[0][i];
- this.extra[1][i] |= otherInits.extra[1][i];
- }
- for (; i < copyLimit; i++) {
- this.extra[0][i] = otherInits.extra[0][i];
- this.extra[1][i] = otherInits.extra[1][i];
- }
- // tweak limits for nulls
- if (!thisHadNulls) {
- if (copyLimit < mergeLimit) {
- copyLimit = mergeLimit;
- }
- mergeLimit = 0;
- }
- if (!otherHasNulls) {
- copyLimit = 0;
- mergeLimit = 0;
- }
- for (i = 0; i < mergeLimit; i++) {
- this.extra[1 + 1][i] = (b1 = otherInits.extra[1 + 1][i])
- | (a1 = this.extra[1 + 1][i]) & ((a3 = this.extra[3 + 1][i])
- & (a4 = this.extra[4 + 1][i]) & (nb2 = ~(b2 = otherInits.extra[2 + 1][i]))
- & (nb4 = ~(b4 = otherInits.extra[4 + 1][i]))
- | ((na4 = ~a4) | (na3 = ~a3))
- & ((na2 = ~(a2 = this.extra[2 + 1][i])) & nb2
- | a2 & (nb3 = ~(b3 = otherInits.extra[3 + 1][i])) & nb4));
- this.extra[2 + 1][i] = b2 & (nb4 | nb3)
- | na3 & na4 & b2
- | a2 & (nb3 & nb4
- | (nb1 = ~b1) & (na3 | (na1 = ~a1))
- | a1 & b2);
- this.extra[3 + 1][i] = b3 & (nb1 & (b2 | a2 | na1)
- | b1 & (b4 | nb2 | a1 & a3)
- | na1 & na2 & na4)
- | a3 & nb2 & nb4
- | nb1 & ((na2 & a4 | na1) & a3
- | a1 & na2 & na4 & b2);
- this.extra[4 + 1][i] = nb1 & (a4 & (na3 & nb3 | (a3 | na2) & nb2)
- | a1 & (a3 & nb2 & b4
- | a2 & b2 & (b4 | a3 & na4 & nb3)))
- | b1 & (a3 & a4 & b4
- | na2 & na4 & nb3 & b4
- | a2 & ((b3 | a4) & b4
- | na3 & a4 & b2 & b3)
- | na1 & (b4 | (a4 | a2) & b2 & b3))
- | (na1 & (na3 & nb3 | na2 & nb2)
- | a1 & (nb2 & nb3 | a2 & a3)) & b4;
- if (coverageTestFlag && coverageTestId == 7) {
- this.extra[5][i] = ~0;
- }
- }
- for (; i < copyLimit; i++) {
- for (int j = 2; j < extraLength; j++) {
- this.extra[j][i] = otherInits.extra[j][i];
- }
- if (coverageTestFlag && coverageTestId == 8) {
- this.extra[5][i] = ~0;
- }
- }
- }
- return this;
-}
-
-public FlowInfo addPotentialInitializationsFrom(FlowInfo inits) {
- if (this == DEAD_END){
- return this;
- }
- if (inits == DEAD_END){
- return this;
- }
- UnconditionalFlowInfo otherInits = inits.unconditionalInits();
- // union of potentially set ones
- this.potentialInits |= otherInits.potentialInits;
- // treating extra storage
- if (this.extra != null) {
- if (otherInits.extra != null) {
- // both sides have extra storage
- int i = 0, length, otherLength;
- if ((length = this.extra[0].length) < (otherLength = otherInits.extra[0].length)) {
- // current storage is shorter -> grow current
- for (int j = 0; j < extraLength; j++) {
- System.arraycopy(this.extra[j], 0,
- (this.extra[j] = new long[otherLength]), 0, length);
- }
- for (; i < length; i++) {
- this.extra[1][i] |= otherInits.extra[1][i];
- }
- for (; i < otherLength; i++) {
- this.extra[1][i] = otherInits.extra[1][i];
- }
- }
- else {
- // current storage is longer
- for (; i < otherLength; i++) {
- this.extra[1][i] |= otherInits.extra[1][i];
- }
- }
- }
- }
- else if (otherInits.extra != null) {
- // no storage here, but other has extra storage.
- int otherLength = otherInits.extra[0].length;
- this.extra = new long[extraLength][];
- for (int j = 0; j < extraLength; j++) {
- this.extra[j] = new long[otherLength];
- }
- System.arraycopy(otherInits.extra[1], 0, this.extra[1], 0,
- otherLength);
- }
- this.addPotentialNullInfoFrom(otherInits);
- return this;
-}
-
-/**
- * Compose other inits over this flow info, then return this. The operation
- * semantics are to wave into this flow info the consequences upon null
- * information of a possible path into the operations that resulted into
- * otherInits. The fact that this path may be left unexecuted under peculiar
- * conditions results into less specific results than
- * {@link #addInitializationsFrom(FlowInfo) addInitializationsFrom}; moreover,
- * only the null information is affected.
- * @param otherInits other null inits to compose over this
- * @return this, modified according to otherInits information
- */
-public UnconditionalFlowInfo addPotentialNullInfoFrom(
- UnconditionalFlowInfo otherInits) {
- if ((this.tagBits & UNREACHABLE) != 0 ||
- (otherInits.tagBits & UNREACHABLE) != 0 ||
- (otherInits.tagBits & NULL_FLAG_MASK) == 0) {
- return this;
- }
- // if we get here, otherInits has some null info
- boolean thisHadNulls = (this.tagBits & NULL_FLAG_MASK) != 0,
- thisHasNulls = false;
- long a1, a2, a3, a4,
- na1, na2, na3, na4,
- b1, b2, b3, b4,
- nb1, nb2, nb3, nb4;
- if (thisHadNulls) {
- this.nullBit1 = (a1 = this.nullBit1)
- & ((a3 = this.nullBit3) & (a4 = this.nullBit4)
- & ((nb2 = ~(b2 = otherInits.nullBit2))
- & (nb4 = ~(b4 = otherInits.nullBit4))
- | (b1 = otherInits.nullBit1) & (b3 = otherInits.nullBit3))
- | (na2 = ~(a2 = this.nullBit2))
- & (b1 & b3 | ((na4 = ~a4) | (na3 = ~a3)) & nb2)
- | a2 & ((na4 | na3) & ((nb3 = ~b3) & nb4 | b1 & b2)));
- this.nullBit2 = b2 & (nb3 | (nb1 = ~b1))
- | a2 & (nb3 & nb4 | b2 | na3 | (na1 = ~a1));
- this.nullBit3 = b3 & (nb1 & b2
- | a2 & (nb2 | a3)
- | na1 & nb2
- | a1 & na2 & na4 & b1)
- | a3 & (nb2 & nb4 | na2 & a4 | na1)
- | a1 & na2 & na4 & b2;
- this.nullBit4 = na3 & (nb1 & nb3 & b4
- | a4 & (nb3 | b1 & b2))
- | nb2 & (na3 & b1 & nb3 | na2 & (nb1 & b4 | b1 & nb3 | a4))
- | a3 & (a4 & (nb2 | b1 & b3)
- | a1 & a2 & (nb1 & b4 | na4 & (b2 | b1) & nb3));
- if (coverageTestFlag && coverageTestId == 9) {
- this.nullBit4 = ~0;
- }
- if ((this.nullBit2 | this.nullBit3 | this.nullBit4) != 0) { // bit1 is redundant
- thisHasNulls = true;
- }
- } else {
- this.nullBit1 = 0;
- this.nullBit2 = (b2 = otherInits.nullBit2)
- & ((nb3 = ~(b3 = otherInits.nullBit3)) |
- (nb1 = ~(b1 = otherInits.nullBit1)));
- this.nullBit3 = b3 & (nb1 | (nb2 = ~b2));
- this.nullBit4 = ~b1 & ~b3 & (b4 = otherInits.nullBit4) | ~b2 & (b1 & ~b3 | ~b1 & b4);
- if (coverageTestFlag && coverageTestId == 10) {
- this.nullBit4 = ~0;
- }
- if ((this.nullBit2 | this.nullBit3 | this.nullBit4) != 0) { // bit1 is redundant
- thisHasNulls = true;
- }
- }
- // extra storage management
- if (otherInits.extra != null) {
- int mergeLimit = 0, copyLimit = otherInits.extra[0].length;
- if (this.extra == null) {
- this.extra = new long[extraLength][];
- for (int j = 0; j < extraLength; j++) {
- this.extra[j] = new long[copyLimit];
- }
- if (coverageTestFlag && coverageTestId == 11) {
- throw new AssertionFailedException("COVERAGE 11"); //$NON-NLS-1$
- }
- } else {
- mergeLimit = copyLimit;
- if (mergeLimit > this.extra[0].length) {
- mergeLimit = this.extra[0].length;
- for (int j = 0; j < extraLength; j++) {
- System.arraycopy(this.extra[j], 0,
- this.extra[j] = new long[copyLimit], 0,
- mergeLimit);
- }
- if (! thisHadNulls) {
- mergeLimit = 0;
- // will do with a copy -- caveat: only valid because definite assignment bits copied above
- if (coverageTestFlag && coverageTestId == 12) {
- throw new AssertionFailedException("COVERAGE 12"); //$NON-NLS-1$
- }
- }
- }
- }
- // PREMATURE skip operations for fields
- int i;
- for (i = 0 ; i < mergeLimit ; i++) {
- this.extra[1 + 1][i] = (a1 = this.extra[1 + 1][i])
- & ((a3 = this.extra[3 + 1][i]) & (a4 = this.extra[4 + 1][i])
- & ((nb2 = ~(b2 = otherInits.extra[2 + 1][i]))
- & (nb4 = ~(b4 = otherInits.extra[4 + 1][i]))
- | (b1 = otherInits.extra[1 + 1][i]) & (b3 = otherInits.extra[3 + 1][i]))
- | (na2 = ~(a2 = this.extra[2 + 1][i]))
- & (b1 & b3 | ((na4 = ~a4) | (na3 = ~a3)) & nb2)
- | a2 & ((na4 | na3) & ((nb3 = ~b3) & nb4 | b1 & b2)));
- this.extra[2 + 1][i] = b2 & (nb3 | (nb1 = ~b1))
- | a2 & (nb3 & nb4 | b2 | na3 | (na1 = ~a1));
- this.extra[3 + 1][i] = b3 & (nb1 & b2
- | a2 & (nb2 | a3)
- | na1 & nb2
- | a1 & na2 & na4 & b1)
- | a3 & (nb2 & nb4 | na2 & a4 | na1)
- | a1 & na2 & na4 & b2;
- this.extra[4 + 1][i] = na3 & (nb1 & nb3 & b4
- | a4 & (nb3 | b1 & b2))
- | nb2 & (na3 & b1 & nb3 | na2 & (nb1 & b4 | b1 & nb3 | a4))
- | a3 & (a4 & (nb2 | b1 & b3)
- | a1 & a2 & (nb1 & b4 | na4 & (b2 | b1) & nb3));
- if ((this.extra[2 + 1][i] | this.extra[3 + 1][i] | this.extra[4 + 1][i]) != 0) { // bit1 is redundant
- thisHasNulls = true;
- }
- if (coverageTestFlag && coverageTestId == 13) {
- this.nullBit4 = ~0;
- }
- }
- for (; i < copyLimit; i++) {
- this.extra[1 + 1][i] = 0;
- this.extra[2 + 1][i] = (b2 = otherInits.extra[2 + 1][i])
- & ((nb3 = ~(b3 = otherInits.extra[3 + 1][i])) |
- (nb1 = ~(b1 = otherInits.extra[1 + 1][i])));
- this.extra[3 + 1][i] = b3 & (nb1 | (nb2 = ~b2));
- this.extra[4 + 1][i] = ~b1 & ~b3 & (b4 = otherInits.extra[4 + 1][i]) | ~b2 & (b1 & ~b3 | ~b1 & b4);
- if ((this.extra[2 + 1][i] | this.extra[3 + 1][i] | this.extra[4 + 1][i]) != 0) { // bit1 is redundant
- thisHasNulls = true;
- }
- if (coverageTestFlag && coverageTestId == 14) {
- this.extra[5][i] = ~0;
- }
- }
- }
- if (thisHasNulls) {
- this.tagBits |= NULL_FLAG_MASK;
- }
- else {
- this.tagBits &= NULL_FLAG_MASK;
- }
- return this;
-}
-
-final public boolean cannotBeDefinitelyNullOrNonNull(LocalVariableBinding local) {
- if ((this.tagBits & NULL_FLAG_MASK) == 0 ||
- (local.type.tagBits & TagBits.IsBaseType) != 0) {
- return false;
- }
- int position;
- if ((position = local.id + this.maxFieldCount) < BitCacheSize) {
- // use bits
- return (
- (~this.nullBit1
- & (this.nullBit2 & this.nullBit3 | this.nullBit4)
- | ~this.nullBit2 & ~this.nullBit3 & this.nullBit4)
- & (1L << position)) != 0;
- }
- // use extra vector
- if (this.extra == null) {
- return false; // if vector not yet allocated, then not initialized
- }
- int vectorIndex;
- if ((vectorIndex = (position / BitCacheSize) - 1) >=
- this.extra[0].length) {
- return false; // if not enough room in vector, then not initialized
- }
- long a2, a3, a4;
- return (
- (~this.extra[2][vectorIndex]
- & ((a2 = this.extra[3][vectorIndex]) & (a3 = this.extra[4][vectorIndex]) | (a4 = this.extra[5][vectorIndex]))
- | ~a2 & ~a3 & a4)
- & (1L << (position % BitCacheSize))) != 0;
-}
-
-final public boolean cannotBeNull(LocalVariableBinding local) {
- if ((this.tagBits & NULL_FLAG_MASK) == 0 ||
- (local.type.tagBits & TagBits.IsBaseType) != 0) {
- return false;
- }
- int position;
- if ((position = getLocalID(local)) < BitCacheSize) {
- // use bits
- return (this.nullBit1 & this.nullBit3
- & ((this.nullBit2 & this.nullBit4) | ~this.nullBit2)
- & (1L << position)) != 0;
- }
- // use extra vector
- if (this.extra == null) {
- return false; // if vector not yet allocated, then not initialized
- }
- int vectorIndex;
- if ((vectorIndex = (position / BitCacheSize) - 1) >=
- this.extra[0].length) {
- return false; // if not enough room in vector, then not initialized
- }
- return (this.extra[2][vectorIndex] & this.extra[4][vectorIndex]
- & ((this.extra[3][vectorIndex] & this.extra[5][vectorIndex]) |
- ~this.extra[3][vectorIndex])
- & (1L << (position % BitCacheSize))) != 0;
-}
-
-final public boolean canOnlyBeNull(LocalVariableBinding local) {
- if ((this.tagBits & NULL_FLAG_MASK) == 0 ||
- (local.type.tagBits & TagBits.IsBaseType) != 0) {
- return false;
- }
- int position;
- if ((position = getLocalID(local)) < BitCacheSize) {
- // use bits
- return (this.nullBit1 & this.nullBit2
- & (~this.nullBit3 | ~this.nullBit4)
- & (1L << position)) != 0;
- }
- // use extra vector
- if (this.extra == null) {
- return false; // if vector not yet allocated, then not initialized
- }
- int vectorIndex;
- if ((vectorIndex = (position / BitCacheSize) - 1) >=
- this.extra[0].length) {
- return false; // if not enough room in vector, then not initialized
- }
- return (this.extra[2][vectorIndex] & this.extra[3][vectorIndex]
- & (~this.extra[4][vectorIndex] | ~this.extra[5][vectorIndex])
- & (1L << (position % BitCacheSize))) != 0;
-}
-
-public FlowInfo copy() {
- // do not clone the DeadEnd
- if (this == DEAD_END) {
- return this;
- }
- UnconditionalFlowInfo copy = new UnconditionalFlowInfo();
- // copy slots
- copy.definiteInits = this.definiteInits;
- copy.potentialInits = this.potentialInits;
- boolean hasNullInfo = (this.tagBits & NULL_FLAG_MASK) != 0;
- if (hasNullInfo) {
- copy.nullBit1 = this.nullBit1;
- copy.nullBit2 = this.nullBit2;
- copy.nullBit3 = this.nullBit3;
- copy.nullBit4 = this.nullBit4;
- }
- copy.tagBits = this.tagBits;
- copy.maxFieldCount = this.maxFieldCount;
- if (this.extra != null) {
- int length;
- copy.extra = new long[extraLength][];
- System.arraycopy(this.extra[0], 0,
- (copy.extra[0] = new long[length = this.extra[0].length]), 0,
- length);
- System.arraycopy(this.extra[1], 0,
- (copy.extra[1] = new long[length]), 0, length);
- if (hasNullInfo) {
- for (int j = 2; j < extraLength; j++) {
- System.arraycopy(this.extra[j], 0,
- (copy.extra[j] = new long[length]), 0, length);
- }
- }
- else {
- for (int j = 2; j < extraLength; j++) {
- copy.extra[j] = new long[length];
- }
- }
- }
- return copy;
-}
-
-/**
- * Discard definite inits and potential inits from this, then return this.
- * The returned flow info only holds null related information.
- * @return this flow info, minus definite inits and potential inits
- */
-public UnconditionalFlowInfo discardInitializationInfo() {
- if (this == DEAD_END) {
- return this;
- }
- this.definiteInits =
- this.potentialInits = 0;
- if (this.extra != null) {
- for (int i = 0, length = this.extra[0].length; i < length; i++) {
- this.extra[0][i] = this.extra[1][i] = 0;
- }
- }
- return this;
-}
-
-/**
- * Remove local variables information from this flow info and return this.
- * @return this, deprived from any local variable information
- */
-public UnconditionalFlowInfo discardNonFieldInitializations() {
- int limit = this.maxFieldCount;
- if (limit < BitCacheSize) {
- long mask = (1L << limit)-1;
- this.definiteInits &= mask;
- this.potentialInits &= mask;
- this.nullBit1 &= mask;
- this.nullBit2 &= mask;
- this.nullBit3 &= mask;
- this.nullBit4 &= mask;
- }
- // use extra vector
- if (this.extra == null) {
- return this; // if vector not yet allocated, then not initialized
- }
- int vectorIndex, length = this.extra[0].length;
- if ((vectorIndex = (limit / BitCacheSize) - 1) >= length) {
- return this; // not enough room yet
- }
- if (vectorIndex >= 0) {
- // else we only have complete non field array items left
- long mask = (1L << (limit % BitCacheSize))-1;
- for (int j = 0; j < extraLength; j++) {
- this.extra[j][vectorIndex] &= mask;
- }
- }
- for (int i = vectorIndex + 1; i < length; i++) {
- for (int j = 0; j < extraLength; j++) {
- this.extra[j][i] = 0;
- }
- }
- return this;
-}
-
-public FlowInfo initsWhenFalse() {
- return this;
-}
-
-public FlowInfo initsWhenTrue() {
- return this;
-}
-
-/**
- * Check status of definite assignment at a given position.
- * It deals with the dual representation of the InitializationInfo2:
- * bits for the first 64 entries, then an array of booleans.
- */
-final private boolean isDefinitelyAssigned(int position) {
- if (position < BitCacheSize) {
- // use bits
- return (this.definiteInits & (1L << position)) != 0;
- }
- // use extra vector
- if (this.extra == null)
- return false; // if vector not yet allocated, then not initialized
- int vectorIndex;
- if ((vectorIndex = (position / BitCacheSize) - 1)
- >= this.extra[0].length) {
- return false; // if not enough room in vector, then not initialized
- }
- return ((this.extra[0][vectorIndex]) &
- (1L << (position % BitCacheSize))) != 0;
-}
-
-final public boolean isDefinitelyAssigned(FieldBinding field) {
- // Mirrored in CodeStream.isDefinitelyAssigned(..)
- // do not want to complain in unreachable code
- if ((this.tagBits & UNREACHABLE) != 0) {
- return true;
- }
- return isDefinitelyAssigned(field.id);
-}
-
-final public boolean isDefinitelyAssigned(LocalVariableBinding local) {
- // do not want to complain in unreachable code if local declared in reachable code
- if ((this.tagBits & UNREACHABLE) != 0 && (local.declaration.bits & ASTNode.IsLocalDeclarationReachable) != 0) {
- return true;
- }
- return isDefinitelyAssigned( getLocalID(local));
-}
-
-final public boolean isDefinitelyNonNull(LocalVariableBinding local) {
- // do not want to complain in unreachable code
- if ((this.tagBits & UNREACHABLE) != 0 ||
- (this.tagBits & NULL_FLAG_MASK) == 0) {
- return false;
- }
- if ((local.type.tagBits & TagBits.IsBaseType) != 0) { // String instances
- return true;
- }
- int position = getLocalID(local);
- if (position < BitCacheSize) { // use bits
- return ((this.nullBit1 & this.nullBit3 & (~this.nullBit2 | this.nullBit4))
- & (1L << position)) != 0;
- }
- // use extra vector
- if (this.extra == null) {
- return false; // if vector not yet allocated, then not initialized
- }
- int vectorIndex;
- if ((vectorIndex = (position / BitCacheSize) - 1)
- >= this.extra[0].length) {
- return false; // if not enough room in vector, then not initialized
- }
- return ((this.extra[2][vectorIndex] & this.extra[4][vectorIndex]
- & (~this.extra[3][vectorIndex] | this.extra[5][vectorIndex]))
- & (1L << (position % BitCacheSize))) != 0;
-}
-
-final public boolean isDefinitelyNull(LocalVariableBinding local) {
- // do not want to complain in unreachable code
- if ((this.tagBits & UNREACHABLE) != 0 ||
- (this.tagBits & NULL_FLAG_MASK) == 0 /*||
- (local.type.tagBits & TagBits.IsBaseType) != 0 */) {
- return false;
- }
- int position = getLocalID(local);
- if (position < BitCacheSize) { // use bits
- return ((this.nullBit1 & this.nullBit2
- & (~this.nullBit3 | ~this.nullBit4))
- & (1L << position)) != 0;
- }
- // use extra vector
- if (this.extra == null) {
- return false; // if vector not yet allocated, then not initialized
- }
- int vectorIndex;
- if ((vectorIndex = (position / BitCacheSize) - 1) >=
- this.extra[0].length) {
- return false; // if not enough room in vector, then not initialized
- }
- return ((this.extra[2][vectorIndex] & this.extra[3][vectorIndex]
- & (~this.extra[4][vectorIndex] | ~this.extra[5][vectorIndex]))
- & (1L << (position % BitCacheSize))) != 0;
-}
-
-final public boolean isDefinitelyUnknown(LocalVariableBinding local) {
- // do not want to complain in unreachable code
- if ((this.tagBits & UNREACHABLE) != 0 ||
- (this.tagBits & NULL_FLAG_MASK) == 0) {
- return false;
- }
- int position = getLocalID(local);
- if (position < BitCacheSize) { // use bits
- return ((this.nullBit1 & this.nullBit4
- & ~this.nullBit2 & ~this.nullBit3) & (1L << position)) != 0;
- }
- // use extra vector
- if (this.extra == null) {
- return false; // if vector not yet allocated, then not initialized
- }
- int vectorIndex;
- if ((vectorIndex = (position / BitCacheSize) - 1) >=
- this.extra[0].length) {
- return false; // if not enough room in vector, then not initialized
- }
- return ((this.extra[2][vectorIndex] & this.extra[5][vectorIndex]
- & ~this.extra[3][vectorIndex] & ~this.extra[4][vectorIndex])
- & (1L << (position % BitCacheSize))) != 0;
-}
-
-/**
- * Check status of potential assignment at a given position.
- */
-final private boolean isPotentiallyAssigned(int position) {
- // id is zero-based
- if (position < BitCacheSize) {
- // use bits
- return (this.potentialInits & (1L << position)) != 0;
- }
- // use extra vector
- if (this.extra == null) {
- return false; // if vector not yet allocated, then not initialized
- }
- int vectorIndex;
- if ((vectorIndex = (position / BitCacheSize) - 1)
- >= this.extra[0].length) {
- return false; // if not enough room in vector, then not initialized
- }
- return ((this.extra[1][vectorIndex]) &
- (1L << (position % BitCacheSize))) != 0;
-}
-
-final public boolean isPotentiallyAssigned(FieldBinding field) {
- return isPotentiallyAssigned(field.id);
-}
-
-final public boolean isPotentiallyAssigned(LocalVariableBinding local) {
- return isPotentiallyAssigned( getLocalID(local));
-}
-
-final public boolean isPotentiallyNonNull(LocalVariableBinding local) {
- if ((this.tagBits & NULL_FLAG_MASK) == 0 ||
- (local.type.tagBits & TagBits.IsBaseType) != 0) {
- return false;
- }
- int position;
- if ((position = getLocalID(local)) < BitCacheSize) {
- // use bits
- return ((this.nullBit3 & (~this.nullBit1 | ~this.nullBit2))
- & (1L << position)) != 0;
- }
- // use extra vector
- if (this.extra == null) {
- return false; // if vector not yet allocated, then not initialized
- }
- int vectorIndex;
- if ((vectorIndex = (position / BitCacheSize) - 1) >=
- this.extra[0].length) {
- return false; // if not enough room in vector, then not initialized
- }
- return ((this.extra[4][vectorIndex]
- & (~this.extra[2][vectorIndex] | ~this.extra[3][vectorIndex]))
- & (1L << (position % BitCacheSize))) != 0;
-}
-
-final public boolean isPotentiallyNull(LocalVariableBinding local) {
- if ((this.tagBits & NULL_FLAG_MASK) == 0 ||
- (local.type.tagBits & TagBits.IsBaseType) != 0) {
- return false;
- }
- int position;
- if ((position = getLocalID(local)) < BitCacheSize) {
- // use bits
- return ((this.nullBit2 & (~this.nullBit1 | ~this.nullBit3))
- & (1L << position)) != 0;
- }
- // use extra vector
- if (this.extra == null) {
- return false; // if vector not yet allocated, then not initialized
- }
- int vectorIndex;
- if ((vectorIndex = (position / BitCacheSize) - 1) >=
- this.extra[0].length) {
- return false; // if not enough room in vector, then not initialized
- }
- return ((this.extra[3][vectorIndex]
- & (~this.extra[2][vectorIndex] | ~this.extra[4][vectorIndex]))
- & (1L << (position % BitCacheSize))) != 0;
-}
-
-final public boolean isPotentiallyUnknown(LocalVariableBinding local) {
- // do not want to complain in unreachable code
- if ((this.tagBits & UNREACHABLE) != 0 ||
- (this.tagBits & NULL_FLAG_MASK) == 0) {
- return false;
- }
- int position = getLocalID(local);
- if (position < BitCacheSize) { // use bits
- return (this.nullBit4
- & (~this.nullBit1 | ~this.nullBit2 & ~this.nullBit3)
- & (1L << position)) != 0;
- }
- // use extra vector
- if (this.extra == null) {
- return false; // if vector not yet allocated, then not initialized
- }
- int vectorIndex;
- if ((vectorIndex = (position / BitCacheSize) - 1) >=
- this.extra[0].length) {
- return false; // if not enough room in vector, then not initialized
- }
- return (this.extra[5][vectorIndex]
- & (~this.extra[2][vectorIndex]
- | ~this.extra[3][vectorIndex] & ~this.extra[4][vectorIndex])
- & (1L << (position % BitCacheSize))) != 0;
-}
-
-final public boolean isProtectedNonNull(LocalVariableBinding local) {
- if ((this.tagBits & NULL_FLAG_MASK) == 0 ||
- (local.type.tagBits & TagBits.IsBaseType) != 0) {
- return false;
- }
- int position;
- if ((position = getLocalID(local)) < BitCacheSize) {
- // use bits
- return (this.nullBit1 & this.nullBit3 & this.nullBit4 & (1L << position)) != 0;
- }
- // use extra vector
- if (this.extra == null) {
- return false; // if vector not yet allocated, then not initialized
- }
- int vectorIndex;
- if ((vectorIndex = (position / BitCacheSize) - 1) >=
- this.extra[0].length) {
- return false; // if not enough room in vector, then not initialized
- }
- return (this.extra[2][vectorIndex]
- & this.extra[4][vectorIndex]
- & this.extra[5][vectorIndex]
- & (1L << (position % BitCacheSize))) != 0;
-}
-
-final public boolean isProtectedNull(LocalVariableBinding local) {
- if ((this.tagBits & NULL_FLAG_MASK) == 0 ||
- (local.type.tagBits & TagBits.IsBaseType) != 0) {
- return false;
- }
- int position;
- if ((position = getLocalID(local)) < BitCacheSize) {
- // use bits
- return (this.nullBit1 & this.nullBit2
- & (this.nullBit3 ^ this.nullBit4)
- & (1L << position)) != 0;
- }
- // use extra vector
- if (this.extra == null) {
- return false; // if vector not yet allocated, then not initialized
- }
- int vectorIndex;
- if ((vectorIndex = (position / BitCacheSize) - 1) >=
- this.extra[0].length) {
- return false; // if not enough room in vector, then not initialized
- }
- return (this.extra[2][vectorIndex] & this.extra[3][vectorIndex]
- & (this.extra[4][vectorIndex] ^ this.extra[5][vectorIndex])
- & (1L << (position % BitCacheSize))) != 0;
-}
-
-public void markAsComparedEqualToNonNull(LocalVariableBinding local) {
- // protected from non-object locals in calling methods
- if (this != DEAD_END) {
- this.tagBits |= NULL_FLAG_MASK;
- int position;
- long mask;
- long a1, a2, a3, a4, na2;
- // position is zero-based
- if ((position = getLocalID(local)) < BitCacheSize) {
- // use bits
- if (((mask = 1L << position)
- & (a1 = this.nullBit1)
- & (na2 = ~(a2 = this.nullBit2))
- & ~(a3 = this.nullBit3)
- & (a4 = this.nullBit4))
- != 0) {
- this.nullBit4 &= ~mask;
- } else if ((mask & a1 & na2 & a3) == 0) {
- this.nullBit4 |= mask;
- if ((mask & a1) == 0) {
- if ((mask & a2 & (a3 ^ a4)) != 0) {
- this.nullBit2 &= ~mask;
- }
- else if ((mask & (a2 | a3 | a4)) == 0) {
- this.nullBit2 |= mask;
- }
- }
- }
- this.nullBit1 |= mask;
- this.nullBit3 |= mask;
- if (coverageTestFlag && coverageTestId == 15) {
- this.nullBit4 = ~0;
- }
- }
- else {
- // use extra vector
- int vectorIndex = (position / BitCacheSize) - 1;
- if (this.extra == null) {
- int length = vectorIndex + 1;
- this.extra = new long[extraLength][];
- for (int j = 0; j < extraLength; j++) {
- this.extra[j] = new long[length];
- }
- if (coverageTestFlag && coverageTestId == 16) {
- throw new AssertionFailedException("COVERAGE 16"); //$NON-NLS-1$
- }
- }
- else {
- int oldLength;
- if (vectorIndex >= (oldLength = this.extra[0].length)) {
- int newLength = vectorIndex + 1;
- for (int j = 0; j < extraLength; j++) {
- System.arraycopy(this.extra[j], 0,
- (this.extra[j] = new long[newLength]), 0,
- oldLength);
- }
- if (coverageTestFlag && coverageTestId == 17) {
- throw new AssertionFailedException("COVERAGE 17"); //$NON-NLS-1$
- }
- }
- }
- // MACRO :'b,'es/nullBit\(.\)/extra[\1 + 1][vectorIndex]/gc
- if (((mask = 1L << (position % BitCacheSize))
- & (a1 = this.extra[1 + 1][vectorIndex])
- & (na2 = ~(a2 = this.extra[2 + 1][vectorIndex]))
- & ~(a3 = this.extra[3 + 1][vectorIndex])
- & (a4 = this.extra[4 + 1][vectorIndex]))
- != 0) {
- this.extra[4 + 1][vectorIndex] &= ~mask;
- } else if ((mask & a1 & na2 & a3) == 0) {
- this.extra[4 + 1][vectorIndex] |= mask;
- if ((mask & a1) == 0) {
- if ((mask & a2 & (a3 ^ a4)) != 0) {
- this.extra[2 + 1][vectorIndex] &= ~mask;
- }
- else if ((mask & (a2 | a3 | a4)) == 0) {
- this.extra[2 + 1][vectorIndex] |= mask;
- }
- }
- }
- this.extra[1 + 1][vectorIndex] |= mask;
- this.extra[3 + 1][vectorIndex] |= mask;
- if (coverageTestFlag && coverageTestId == 18) {
- this.extra[5][vectorIndex] = ~0;
- }
- }
- }
-}
-
-public void markAsComparedEqualToNull(LocalVariableBinding local) {
- // protected from non-object locals in calling methods
- if (this != DEAD_END) {
- this.tagBits |= NULL_FLAG_MASK;
- int position;
- long mask;
- // position is zero-based
- if ((position = getLocalID(local)) < BitCacheSize) {
- // use bits
- if (((mask = 1L << position) & this.nullBit1) != 0) {
- if ((mask
- & (~this.nullBit2 | this.nullBit3
- | ~this.nullBit4)) != 0) {
- this.nullBit4 &= ~mask;
- }
- } else if ((mask & this.nullBit4) != 0) {
- this.nullBit3 &= ~mask;
- } else {
- if ((mask & this.nullBit2) != 0) {
- this.nullBit3 &= ~mask;
- this.nullBit4 |= mask;
- } else {
- this.nullBit3 |= mask;
- }
- }
- this.nullBit1 |= mask;
- this.nullBit2 |= mask;
- if (coverageTestFlag && coverageTestId == 19) {
- this.nullBit4 = ~0;
- }
- }
- else {
- // use extra vector
- int vectorIndex = (position / BitCacheSize) - 1;
- mask = 1L << (position % BitCacheSize);
- if (this.extra == null) {
- int length = vectorIndex + 1;
- this.extra = new long[extraLength][];
- for (int j = 0; j < extraLength; j++) {
- this.extra[j] = new long[length ];
- }
- if (coverageTestFlag && coverageTestId == 20) {
- throw new AssertionFailedException("COVERAGE 20"); //$NON-NLS-1$
- }
- }
- else {
- int oldLength;
- if (vectorIndex >= (oldLength = this.extra[0].length)) {
- int newLength = vectorIndex + 1;
- for (int j = 0; j < extraLength; j++) {
- System.arraycopy(this.extra[j], 0,
- (this.extra[j] = new long[newLength]), 0,
- oldLength);
- }
- if (coverageTestFlag && coverageTestId == 21) {
- throw new AssertionFailedException("COVERAGE 21"); //$NON-NLS-1$
- }
- }
- }
- if ((mask & this.extra[1 + 1][vectorIndex]) != 0) {
- if ((mask
- & (~this.extra[2 + 1][vectorIndex] | this.extra[3 + 1][vectorIndex]
- | ~this.extra[4 + 1][vectorIndex])) != 0) {
- this.extra[4 + 1][vectorIndex] &= ~mask;
- }
- } else if ((mask & this.extra[4 + 1][vectorIndex]) != 0) {
- this.extra[3 + 1][vectorIndex] &= ~mask;
- } else {
- if ((mask & this.extra[2 + 1][vectorIndex]) != 0) {
- this.extra[3 + 1][vectorIndex] &= ~mask;
- this.extra[4 + 1][vectorIndex] |= mask;
- } else {
- this.extra[3 + 1][vectorIndex] |= mask;
- }
- }
- this.extra[1 + 1][vectorIndex] |= mask;
- this.extra[2 + 1][vectorIndex] |= mask;
- }
- }
-}
-
-/**
- * Record a definite assignment at a given position.
- */
-final private void markAsDefinitelyAssigned(int position) {
-
- if (this != DEAD_END) {
- // position is zero-based
- if (position < BitCacheSize) {
- // use bits
- long mask;
- this.definiteInits |= (mask = 1L << position);
- this.potentialInits |= mask;
- }
- else {
- // use extra vector
- int vectorIndex = (position / BitCacheSize) - 1;
- if (this.extra == null) {
- int length = vectorIndex + 1;
- this.extra = new long[extraLength][];
- for (int j = 0; j < extraLength; j++) {
- this.extra[j] = new long[length];
- }
- }
- else {
- int oldLength; // might need to grow the arrays
- if (vectorIndex >= (oldLength = this.extra[0].length)) {
- for (int j = 0; j < extraLength; j++) {
- System.arraycopy(this.extra[j], 0,
- (this.extra[j] = new long[vectorIndex + 1]), 0,
- oldLength);
- }
- }
- }
- long mask;
- this.extra[0][vectorIndex] |=
- (mask = 1L << (position % BitCacheSize));
- this.extra[1][vectorIndex] |= mask;
- }
- }
-}
-
-public void markAsDefinitelyAssigned(FieldBinding field) {
- if (this != DEAD_END)
- markAsDefinitelyAssigned(field.id);
-}
-
-public void markAsDefinitelyAssigned(LocalVariableBinding local) {
- if (this != DEAD_END && local != null)
- {
- markAsDefinitelyAssigned(getLocalID(local));
- }
-}
-
-public void markAsDefinitelyNonNull(LocalVariableBinding local) {
- // protected from non-object locals in calling methods
- if (this != DEAD_END) {
- this.tagBits |= NULL_FLAG_MASK;
- long mask;
- int position;
- // position is zero-based
- if ((position = getLocalID(local)) < BitCacheSize) { // use bits
- // set assigned non null
- this.nullBit1 |= (mask = 1L << position);
- this.nullBit3 |= mask;
- // clear others
- this.nullBit2 &= (mask = ~mask);
- this.nullBit4 &= mask;
- if (coverageTestFlag && coverageTestId == 22) {
- this.nullBit1 = 0;
- }
- }
- else {
- // use extra vector
- int vectorIndex = (position / BitCacheSize) - 1;
- if (this.extra == null) {
- int length = vectorIndex + 1;
- this.extra = new long[extraLength][];
- for (int j = 0; j < extraLength; j++) {
- this.extra[j] = new long[length];
- }
- }
- this.extra[2][vectorIndex]
- |= (mask = 1L << (position % BitCacheSize));
- this.extra[4][vectorIndex] |= mask;
- this.extra[3][vectorIndex] &= (mask = ~mask);
- this.extra[5][vectorIndex] &= mask;
- if (coverageTestFlag && coverageTestId == 23) {
- this.extra[2][vectorIndex] = 0;
- }
- }
- }
-}
-
-public void markAsDefinitelyNull(LocalVariableBinding local) {
- // protected from non-object locals in calling methods
- if (this != DEAD_END) {
- this.tagBits |= NULL_FLAG_MASK;
- long mask;
- int position;
- // position is zero-based
- if ((position = getLocalID(local)) < BitCacheSize) { // use bits
- // mark assigned null
- this.nullBit1 |= (mask = 1L << position);
- this.nullBit2 |= mask;
- // clear others
- this.nullBit3 &= (mask = ~mask);
- this.nullBit4 &= mask;
- if (coverageTestFlag && coverageTestId == 24) {
- this.nullBit4 = ~0;
- }
- }
- else {
- // use extra vector
- int vectorIndex ;
- this.extra[2][vectorIndex = (position / BitCacheSize) - 1]
- |= (mask = 1L << (position % BitCacheSize));
- this.extra[3][vectorIndex] |= mask;
- this.extra[4][vectorIndex] &= (mask = ~mask);
- this.extra[5][vectorIndex] &= mask;
- if (coverageTestFlag && coverageTestId == 25) {
- this.extra[5][vectorIndex] = ~0;
- }
- }
- }
-}
-
-/**
- * Mark a local as having been assigned to an unknown value.
- * @param local the local to mark
- */
-// PREMATURE may try to get closer to markAsDefinitelyAssigned, but not
-// obvious
-public void markAsDefinitelyUnknown(LocalVariableBinding local) {
- // protected from non-object locals in calling methods
- if (this != DEAD_END) {
- this.tagBits |= NULL_FLAG_MASK;
- long mask;
- int position;
- // position is zero-based
- if ((position = getLocalID(local)) < BitCacheSize) {
- // use bits
- // mark assigned null
- this.nullBit1 |= (mask = 1L << position);
- this.nullBit4 |= mask;
- // clear others
- this.nullBit2 &= (mask = ~mask);
- this.nullBit3 &= mask;
- if (coverageTestFlag && coverageTestId == 26) {
- this.nullBit4 = 0;
- }
- }
- else {
- // use extra vector
- int vectorIndex ;
- this.extra[2][vectorIndex = (position / BitCacheSize) - 1]
- |= (mask = 1L << (position % BitCacheSize));
- this.extra[5][vectorIndex] |= mask;
- this.extra[3][vectorIndex] &= (mask = ~mask);
- this.extra[4][vectorIndex] &= mask;
- if (coverageTestFlag && coverageTestId == 27) {
- this.extra[5][vectorIndex] = 0;
- }
- }
- }
-}
-
-public UnconditionalFlowInfo mergedWith(UnconditionalFlowInfo otherInits) {
- if ((otherInits.tagBits & UNREACHABLE) != 0 && this != DEAD_END) {
- if (coverageTestFlag && coverageTestId == 28) {
- throw new AssertionFailedException("COVERAGE 28"); //$NON-NLS-1$
- }
- return this;
- }
- if ((this.tagBits & UNREACHABLE) != 0) {
- if (coverageTestFlag && coverageTestId == 29) {
- throw new AssertionFailedException("COVERAGE 29"); //$NON-NLS-1$
- }
- return (UnconditionalFlowInfo) otherInits.copy(); // make sure otherInits won't be affected
- }
-
- // intersection of definitely assigned variables,
- this.definiteInits &= otherInits.definiteInits;
- // union of potentially set ones
- this.potentialInits |= otherInits.potentialInits;
-
- // null combinations
- boolean
- thisHasNulls = (this.tagBits & NULL_FLAG_MASK) != 0,
- otherHasNulls = (otherInits.tagBits & NULL_FLAG_MASK) != 0,
- thisHadNulls = thisHasNulls;
- long
- a1, a2, a3, a4,
- na1, na2, na3, na4,
- nb1, nb2, nb3, nb4,
- b1, b2, b3, b4;
- if (thisHadNulls) {
- if (otherHasNulls) {
- this.nullBit1 = (a2 = this.nullBit2) & (a3 = this.nullBit3)
- & (a4 = this.nullBit4) & (b1 = otherInits.nullBit1)
- & (nb2 = ~(b2 = otherInits.nullBit2))
- | (a1 = this.nullBit1) & (b1 & (a3 & a4 & (b3 = otherInits.nullBit3)
- & (b4 = otherInits.nullBit4)
- | (na2 = ~a2) & nb2
- & ((nb4 = ~b4) | (na4 = ~a4)
- | (na3 = ~a3) & (nb3 = ~b3))
- | a2 & b2 & ((na4 | na3) & (nb4 | nb3)))
- | na2 & b2 & b3 & b4);
- this.nullBit2 = b2 & (nb3 | (nb1 = ~b1) | a3 & (a4 | (na1 = ~a1)) & nb4)
- | a2 & (b2 | na4 & b3 & (b4 | nb1) | na3 | na1);
- this.nullBit3 = b3 & (nb2 & b4 | nb1 | a3 & (na4 & nb4 | a4 & b4))
- | a3 & (na2 & a4 | na1)
- | (a2 | na1) & b1 & nb2 & nb4
- | a1 & na2 & na4 & (b2 | nb1);
- this.nullBit4 = na3 & (nb1 & nb3 & b4
- | b1 & (nb2 & nb3 | a4 & b2 & nb4)
- | na1 & a4 & (nb3 | b1 & b2))
- | a3 & a4 & (b3 & b4 | b1 & nb2)
- | na2 & (nb1 & b4 | b1 & nb3 | na1 & a4) & nb2
- | a1 & (na3 & (nb3 & b4
- | b1 & b2 & b3 & nb4
- | na2 & (nb3 | nb2))
- | na2 & b3 & b4
- | a2 & (nb1 & b4 | a3 & na4 & b1) & nb3);
- if (coverageTestFlag && coverageTestId == 30) {
- this.nullBit4 = ~0;
- }
- } else { // other has no null info
- a1 = this.nullBit1;
- this.nullBit1 = 0;
- this.nullBit2 = (a2 = this.nullBit2) & (na3 = ~(a3 = this.nullBit3) | (na1 = ~a1));
- this.nullBit3 = a3 & ((na2 = ~a2) & (a4 = this.nullBit4) | na1) | a1 & na2 & ~a4;
- this.nullBit4 = (na3 | na2) & na1 & a4 | a1 & na3 & na2;
- if (coverageTestFlag && coverageTestId == 31) {
- this.nullBit4 = ~0;
- }
- }
- } else if (otherHasNulls) { // only other had nulls
- this.nullBit1 = 0;
- this.nullBit2 = (b2 = otherInits.nullBit2) & (nb3 = ~(b3 = otherInits.nullBit3) | (nb1 = ~(b1 = otherInits.nullBit1)));
- this.nullBit3 = b3 & ((nb2 = ~b2) & (b4 = otherInits.nullBit4) | nb1) | b1 & nb2 & ~b4;
- this.nullBit4 = (nb3 | nb2) & nb1 & b4 | b1 & nb3 & nb2;
- if (coverageTestFlag && coverageTestId == 32) {
- this.nullBit4 = ~0;
- }
- thisHasNulls =
- // redundant with the three following ones
- this.nullBit2 != 0 ||
- this.nullBit3 != 0 ||
- this.nullBit4 != 0;
- }
-
- // treating extra storage
- if (this.extra != null || otherInits.extra != null) {
- int mergeLimit = 0, copyLimit = 0, resetLimit = 0;
- int i;
- if (this.extra != null) {
- if (otherInits.extra != null) {
- // both sides have extra storage
- int length, otherLength;
- if ((length = this.extra[0].length) <
- (otherLength = otherInits.extra[0].length)) {
- // current storage is shorter -> grow current
- for (int j = 0; j < extraLength; j++) {
- System.arraycopy(this.extra[j], 0,
- (this.extra[j] = new long[otherLength]), 0, length);
- }
- mergeLimit = length;
- copyLimit = otherLength;
- if (coverageTestFlag && coverageTestId == 33) {
- throw new AssertionFailedException("COVERAGE 33"); //$NON-NLS-1$
- }
- }
- else {
- // current storage is longer
- mergeLimit = otherLength;
- resetLimit = length;
- if (coverageTestFlag && coverageTestId == 34) {
- throw new AssertionFailedException("COVERAGE 34"); //$NON-NLS-1$
- }
- }
- }
- else {
- resetLimit = this.extra[0].length;
- if (coverageTestFlag && coverageTestId == 35) {
- throw new AssertionFailedException("COVERAGE 35"); //$NON-NLS-1$
- }
- }
- }
- else if (otherInits.extra != null) {
- // no storage here, but other has extra storage.
- int otherLength = otherInits.extra[0].length;
- this.extra = new long[extraLength][];
- for (int j = 0; j < extraLength; j++) {
- this.extra[j] = new long[otherLength];
- }
- System.arraycopy(otherInits.extra[1], 0,
- this.extra[1], 0, otherLength);
- copyLimit = otherLength;
- if (coverageTestFlag && coverageTestId == 36) {
- throw new AssertionFailedException("COVERAGE 36"); //$NON-NLS-1$
- }
- }
- // MACRO :'b,'es/nullBit\(.\)/extra[\1 + 1][i]/g
- // manage definite assignment
- for (i = 0; i < mergeLimit; i++) {
- this.extra[0][i] &= otherInits.extra[0][i];
- this.extra[1][i] |= otherInits.extra[1][i];
- }
- for (; i < copyLimit; i++) {
- this.extra[1][i] = otherInits.extra[1][i];
- }
- for (; i < resetLimit; i++) {
- this.extra[0][i] = 0;
- }
- // refine null bits requirements
- if (!otherHasNulls) {
- if (resetLimit < mergeLimit) {
- resetLimit = mergeLimit;
- }
- copyLimit = 0; // no need to carry inexisting nulls
- mergeLimit = 0;
- }
- if (!thisHadNulls) {
- resetLimit = 0; // no need to reset anything
- }
- // compose nulls
- for (i = 0; i < mergeLimit; i++) {
- this.extra[1 + 1][i] = (a2 = this.extra[2 + 1][i]) & (a3 = this.extra[3 + 1][i])
- & (a4 = this.extra[4 + 1][i]) & (b1 = otherInits.extra[1 + 1][i])
- & (nb2 = ~(b2 = otherInits.extra[2 + 1][i]))
- | (a1 = this.extra[1 + 1][i]) & (b1 & (a3 & a4 & (b3 = otherInits.extra[3 + 1][i])
- & (b4 = otherInits.extra[4 + 1][i])
- | (na2 = ~a2) & nb2
- & ((nb4 = ~b4) | (na4 = ~a4)
- | (na3 = ~a3) & (nb3 = ~b3))
- | a2 & b2 & ((na4 | na3) & (nb4 | nb3)))
- | na2 & b2 & b3 & b4);
- this.extra[2 + 1][i] = b2 & (nb3 | (nb1 = ~b1) | a3 & (a4 | (na1 = ~a1)) & nb4)
- | a2 & (b2 | na4 & b3 & (b4 | nb1) | na3 | na1);
- this.extra[3 + 1][i] = b3 & (nb2 & b4 | nb1 | a3 & (na4 & nb4 | a4 & b4))
- | a3 & (na2 & a4 | na1)
- | (a2 | na1) & b1 & nb2 & nb4
- | a1 & na2 & na4 & (b2 | nb1);
- this.extra[4 + 1][i] = na3 & (nb1 & nb3 & b4
- | b1 & (nb2 & nb3 | a4 & b2 & nb4)
- | na1 & a4 & (nb3 | b1 & b2))
- | a3 & a4 & (b3 & b4 | b1 & nb2)
- | na2 & (nb1 & b4 | b1 & nb3 | na1 & a4) & nb2
- | a1 & (na3 & (nb3 & b4
- | b1 & b2 & b3 & nb4
- | na2 & (nb3 | nb2))
- | na2 & b3 & b4
- | a2 & (nb1 & b4 | a3 & na4 & b1) & nb3);
- thisHasNulls = thisHasNulls ||
- this.extra[3][i] != 0 ||
- this.extra[4][i] != 0 ||
- this.extra[5][i] != 0 ;
- if (coverageTestFlag && coverageTestId == 37) {
- this.extra[5][i] = ~0;
- }
- }
- for (; i < copyLimit; i++) {
- this.extra[1 + 1][i] = 0;
- this.extra[2 + 1][i] = (b2 = otherInits.extra[2 + 1][i]) & (nb3 = ~(b3 = otherInits.extra[3 + 1][i]) | (nb1 = ~(b1 = otherInits.extra[1 + 1][i])));
- this.extra[3 + 1][i] = b3 & ((nb2 = ~b2) & (b4 = otherInits.extra[4 + 1][i]) | nb1) | b1 & nb2 & ~b4;
- this.extra[4 + 1][i] = (nb3 | nb2) & nb1 & b4 | b1 & nb3 & nb2;
- thisHasNulls = thisHasNulls ||
- this.extra[3][i] != 0 ||
- this.extra[4][i] != 0 ||
- this.extra[5][i] != 0;
- if (coverageTestFlag && coverageTestId == 38) {
- this.extra[5][i] = ~0;
- }
- }
- for (; i < resetLimit; i++) {
- a1 = this.extra[1 + 1][i];
- this.extra[1 + 1][i] = 0;
- this.extra[2 + 1][i] = (a2 = this.extra[2 + 1][i]) & (na3 = ~(a3 = this.extra[3 + 1][i]) | (na1 = ~a1));
- this.extra[3 + 1][i] = a3 & ((na2 = ~a2) & (a4 = this.extra[4 + 1][i]) | na1) | a1 & na2 & ~a4;
- this.extra[4 + 1][i] = (na3 | na2) & na1 & a4 | a1 & na3 & na2;
- thisHasNulls = thisHasNulls ||
- this.extra[3][i] != 0 ||
- this.extra[4][i] != 0 ||
- this.extra[5][i] != 0;
- if (coverageTestFlag && coverageTestId == 39) {
- this.extra[5][i] = ~0;
- }
- }
- }
- if (thisHasNulls) {
- this.tagBits |= NULL_FLAG_MASK;
- }
- else {
- this.tagBits &= ~NULL_FLAG_MASK;
- }
- return this;
-}
-
-/*
- * Answer the total number of fields in enclosing types of a given type
- */
-static int numberOfEnclosingFields(ReferenceBinding type){
- int count = 0;
- type = type.enclosingType();
- while(type != null) {
- count += type.fieldCount();
- type = type.enclosingType();
- }
- return count;
-}
-
-public UnconditionalFlowInfo nullInfoLessUnconditionalCopy() {
- if (this == DEAD_END) {
- return this;
- }
- UnconditionalFlowInfo copy = new UnconditionalFlowInfo();
- copy.definiteInits = this.definiteInits;
- copy.potentialInits = this.potentialInits;
- copy.tagBits = this.tagBits & ~NULL_FLAG_MASK;
- copy.maxFieldCount = this.maxFieldCount;
- if (this.extra != null) {
- int length;
- copy.extra = new long[extraLength][];
- System.arraycopy(this.extra[0], 0,
- (copy.extra[0] =
- new long[length = this.extra[0].length]), 0, length);
- System.arraycopy(this.extra[1], 0,
- (copy.extra[1] = new long[length]), 0, length);
- for (int j = 2; j < extraLength; j++) {
- copy.extra[j] = new long[length];
- }
- }
- return copy;
-}
-
-public FlowInfo safeInitsWhenTrue() {
- return copy();
-}
-
-public FlowInfo setReachMode(int reachMode) {
- if (reachMode == REACHABLE && this != DEAD_END) { // cannot modify DEAD_END
- this.tagBits &= ~UNREACHABLE;
- }
- else {
- if ((this.tagBits & UNREACHABLE) == 0) {
- // reset optional inits when becoming unreachable
- // see InitializationTest#test090 (and others)
- this.potentialInits = 0;
- if (this.extra != null) {
- for (int i = 0, length = this.extra[0].length;
- i < length; i++) {
- this.extra[1][i] = 0;
- }
- }
- }
- this.tagBits |= UNREACHABLE;
- }
- return this;
-}
-
-public String toString(){
- // PREMATURE consider printing bit fields as 0001 0001 1000 0001...
- if (this == DEAD_END){
- return "FlowInfo.DEAD_END"; //$NON-NLS-1$
- }
- if ((this.tagBits & NULL_FLAG_MASK) != 0) {
- if (this.extra == null) {
- return "FlowInfo<def: " + this.definiteInits //$NON-NLS-1$
- +", pot: " + this.potentialInits //$NON-NLS-1$
- + ", reachable:" + ((this.tagBits & UNREACHABLE) == 0) //$NON-NLS-1$
- +", null: " + this.nullBit1 //$NON-NLS-1$
- + this.nullBit2 + this.nullBit3 + this.nullBit4
- +">"; //$NON-NLS-1$
- }
- else {
- String def = "FlowInfo<def:[" + this.definiteInits, //$NON-NLS-1$
- pot = "], pot:[" + this.potentialInits, //$NON-NLS-1$
- nullS = ", null:[" + this.nullBit1 //$NON-NLS-1$
- + this.nullBit2 + this.nullBit3 + this.nullBit4;
- int i, ceil;
- for (i = 0, ceil = this.extra[0].length > 3 ?
- 3 :
- this.extra[0].length;
- i < ceil; i++) {
- def += "," + this.extra[0][i]; //$NON-NLS-1$
- pot += "," + this.extra[1][i]; //$NON-NLS-1$
- nullS += "," + this.extra[2][i] //$NON-NLS-1$
- + this.extra[3][i] + this.extra[4][i] + this.extra[5][i];
- }
- if (ceil < this.extra[0].length) {
- def += ",..."; //$NON-NLS-1$
- pot += ",..."; //$NON-NLS-1$
- nullS += ",..."; //$NON-NLS-1$
- }
- return def + pot
- + "], reachable:" + ((this.tagBits & UNREACHABLE) == 0) //$NON-NLS-1$
- + nullS
- + "]>"; //$NON-NLS-1$
- }
- }
- else {
- if (this.extra == null) {
- return "FlowInfo<def: " + this.definiteInits //$NON-NLS-1$
- +", pot: " + this.potentialInits //$NON-NLS-1$
- + ", reachable:" + ((this.tagBits & UNREACHABLE) == 0) //$NON-NLS-1$
- +", no null info>"; //$NON-NLS-1$
- }
- else {
- String def = "FlowInfo<def:[" + this.definiteInits, //$NON-NLS-1$
- pot = "], pot:[" + this.potentialInits; //$NON-NLS-1$
- int i, ceil;
- for (i = 0, ceil = this.extra[0].length > 3 ?
- 3 :
- this.extra[0].length;
- i < ceil; i++) {
- def += "," + this.extra[0][i]; //$NON-NLS-1$
- pot += "," + this.extra[1][i]; //$NON-NLS-1$
- }
- if (ceil < this.extra[0].length) {
- def += ",..."; //$NON-NLS-1$
- pot += ",..."; //$NON-NLS-1$
- }
- return def + pot
- + "], reachable:" + ((this.tagBits & UNREACHABLE) == 0) //$NON-NLS-1$
- + ", no null info>"; //$NON-NLS-1$
- }
- }
-}
-
-public UnconditionalFlowInfo unconditionalCopy() {
- return (UnconditionalFlowInfo) copy();
-}
-
-public UnconditionalFlowInfo unconditionalFieldLessCopy() {
- // TODO (maxime) may consider leveraging null contribution verification as it is done in copy
- UnconditionalFlowInfo copy = new UnconditionalFlowInfo();
- copy.tagBits = this.tagBits;
- copy.maxFieldCount = this.maxFieldCount;
- int limit = this.maxFieldCount;
- if (limit < BitCacheSize) {
- long mask;
- copy.definiteInits = this.definiteInits & (mask = ~((1L << limit)-1));
- copy.potentialInits = this.potentialInits & mask;
- copy.nullBit1 = this.nullBit1 & mask;
- copy.nullBit2 = this.nullBit2 & mask;
- copy.nullBit3 = this.nullBit3 & mask;
- copy.nullBit4 = this.nullBit4 & mask;
- }
- // use extra vector
- if (this.extra == null) {
- return copy; // if vector not yet allocated, then not initialized
- }
- int vectorIndex, length, copyStart;
- if ((vectorIndex = (limit / BitCacheSize) - 1) >=
- (length = this.extra[0].length)) {
- return copy; // not enough room yet
- }
- long mask;
- copy.extra = new long[extraLength][];
- if ((copyStart = vectorIndex + 1) < length) {
- int copyLength = length - copyStart;
- for (int j = 0; j < extraLength; j++) {
- System.arraycopy(this.extra[j], copyStart,
- (copy.extra[j] = new long[length]), copyStart,
- copyLength);
- }
- }
- else if (vectorIndex >= 0) {
- for (int j = 0; j < extraLength; j++) {
- copy.extra[j] = new long[length];
- }
- }
- if (vectorIndex >= 0) {
- mask = ~((1L << (limit % BitCacheSize))-1);
- for (int j = 0; j < extraLength; j++) {
- copy.extra[j][vectorIndex] =
- this.extra[j][vectorIndex] & mask;
- }
- }
- return copy;
-}
-
-public UnconditionalFlowInfo unconditionalInits() {
- // also see conditional inits, where it requests them to merge
- return this;
-}
-
-public UnconditionalFlowInfo unconditionalInitsWithoutSideEffect() {
- return this;
-}
-
-protected final int getLocalID(LocalVariableBinding local)
-{
- int id=local.id;
- if (local.declaringScope.kind==Scope.METHOD_SCOPE)
- id+=this.maxFieldCount;
- else
- id+=local.declaringScope.compilationUnitScope().temporaryAnalysisIndex;
- return id;
-}
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/BooleanConstant.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/BooleanConstant.java
deleted file mode 100644
index 0c2e448c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/BooleanConstant.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.impl;
-
-public class BooleanConstant extends Constant {
-
-private boolean value;
-
-private static final BooleanConstant TRUE = new BooleanConstant(true);
-private static final BooleanConstant FALSE = new BooleanConstant(false);
-
-public static BooleanConstant fromValue(boolean value) {
- return value ? BooleanConstant.TRUE : BooleanConstant.FALSE;
-}
-private BooleanConstant(boolean value) {
- this.value = value;
-}
-
-public boolean booleanValue() {
- return value;
-}
-
-public String stringValue() {
- //spec 15.17.11
- return String.valueOf(this.value);
-}
-
-public String toString(){
- return "(boolean)" + value ; //$NON-NLS-1$
-}
-
-public int typeID() {
- return T_boolean;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/CharConstant.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/CharConstant.java
deleted file mode 100644
index ba1b7076..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/CharConstant.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.impl;
-
-public class CharConstant extends Constant {
-
- private char value;
-
- public static Constant fromValue(char value) {
- return new CharConstant(value);
- }
-
- private CharConstant(char value) {
- this.value = value;
- }
- public byte byteValue() {
- return (byte) value;
- }
- public char charValue() {
- return this.value;
- }
- public double doubleValue() {
- return value; // implicit cast to return type
- }
- public float floatValue() {
- return value; // implicit cast to return type
- }
- public int intValue() {
- return value; // implicit cast to return type
- }
- public long longValue() {
- return value; // implicit cast to return type
- }
- public short shortValue() {
- return (short) value;
- }
- public String stringValue() {
- //spec 15.17.11
- return String.valueOf(this.value);
- }
- public String toString(){
-
- return "(char)" + value; //$NON-NLS-1$
- }
- public int typeID() {
- return T_char;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/CompilerOptions.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/CompilerOptions.java
deleted file mode 100644
index 6b46a7e3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/CompilerOptions.java
+++ /dev/null
@@ -1,1325 +0,0 @@
-/*******************************************************************************
- * 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.compiler.impl;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStreamReader;
-import java.io.UnsupportedEncodingException;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.infer.InferOptions;
-import org.eclipse.wst.jsdt.internal.compiler.Compiler;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode;
-import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ExtraCompilerModifiers;
-import org.eclipse.wst.jsdt.internal.compiler.problem.ProblemSeverities;
-import org.eclipse.wst.jsdt.internal.compiler.util.Util;
-
-public class CompilerOptions {
-
- /**
- * Option IDs
- */
- public static final String OPTION_SemanticValidation = "semanticValidation"; //$NON-NLS-1$
- public static final String OPTION_LocalVariableAttribute = "org.eclipse.wst.jsdt.core.compiler.debug.localVariable"; //$NON-NLS-1$
- public static final String OPTION_LineNumberAttribute = "org.eclipse.wst.jsdt.core.compiler.debug.lineNumber"; //$NON-NLS-1$
- public static final String OPTION_SourceFileAttribute = "org.eclipse.wst.jsdt.core.compiler.debug.sourceFile"; //$NON-NLS-1$
- public static final String OPTION_PreserveUnusedLocal = "org.eclipse.wst.jsdt.core.compiler.codegen.unusedLocal"; //$NON-NLS-1$
- public static final String OPTION_DocCommentSupport= "org.eclipse.wst.jsdt.core.compiler.doc.comment.support"; //$NON-NLS-1$
- public static final String OPTION_ReportMethodWithConstructorName = "org.eclipse.wst.jsdt.core.compiler.problem.methodWithConstructorName"; //$NON-NLS-1$
- public static final String OPTION_ReportUndefinedField = "org.eclipse.wst.jsdt.core.compiler.problem.undefinedField"; //$NON-NLS-1$
- public static final String OPTION_ReportDeprecation = "org.eclipse.wst.jsdt.core.compiler.problem.deprecation"; //$NON-NLS-1$
- public static final String OPTION_ReportDeprecationInDeprecatedCode = "org.eclipse.wst.jsdt.core.compiler.problem.deprecationInDeprecatedCode"; //$NON-NLS-1$
- public static final String OPTION_ReportDeprecationWhenOverridingDeprecatedMethod = "org.eclipse.wst.jsdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod"; //$NON-NLS-1$
- public static final String OPTION_ReportHiddenCatchBlock = "org.eclipse.wst.jsdt.core.compiler.problem.hiddenCatchBlock"; //$NON-NLS-1$
- public static final String OPTION_ReportUnusedLocal = "org.eclipse.wst.jsdt.core.compiler.problem.unusedLocal"; //$NON-NLS-1$
- public static final String OPTION_ReportUnusedParameter = "org.eclipse.wst.jsdt.core.compiler.problem.unusedParameter"; //$NON-NLS-1$
- public static final String OPTION_ReportUnusedParameterWhenImplementingAbstract = "org.eclipse.wst.jsdt.core.compiler.problem.unusedParameterWhenImplementingAbstract"; //$NON-NLS-1$
- public static final String OPTION_ReportUnusedParameterWhenOverridingConcrete = "org.eclipse.wst.jsdt.core.compiler.problem.unusedParameterWhenOverridingConcrete"; //$NON-NLS-1$
- public static final String OPTION_ReportUnusedParameterIncludeDocCommentReference = "org.eclipse.wst.jsdt.core.compiler.problem.unusedParameterIncludeDocCommentReference"; //$NON-NLS-1$
- public static final String OPTION_ReportWrongNumberOfArguments = "org.eclipse.wst.jsdt.core.compiler.problem.wrongNumberOfArguments"; //$NON-NLS-1$
- public static final String OPTION_ReportNoEffectAssignment = "org.eclipse.wst.jsdt.core.compiler.problem.noEffectAssignment"; //$NON-NLS-1$
- public static final String OPTION_ReportLocalVariableHiding = "org.eclipse.wst.jsdt.core.compiler.problem.localVariableHiding"; //$NON-NLS-1$
- public static final String OPTION_ReportSpecialParameterHidingField = "org.eclipse.wst.jsdt.core.compiler.problem.specialParameterHidingField"; //$NON-NLS-1$
- public static final String OPTION_ReportFieldHiding = "org.eclipse.wst.jsdt.core.compiler.problem.fieldHiding"; //$NON-NLS-1$
- public static final String OPTION_ReportTypeParameterHiding = "org.eclipse.wst.jsdt.core.compiler.problem.typeParameterHiding"; //$NON-NLS-1$
- public static final String OPTION_ReportPossibleAccidentalBooleanAssignment = "org.eclipse.wst.jsdt.core.compiler.problem.possibleAccidentalBooleanAssignment"; //$NON-NLS-1$
- public static final String OPTION_ReportNonExternalizedStringLiteral = "org.eclipse.wst.jsdt.core.compiler.problem.nonExternalizedStringLiteral"; //$NON-NLS-1$
- public static final String OPTION_ReportUnusedPrivateMember = "org.eclipse.wst.jsdt.core.compiler.problem.unusedPrivateMember"; //$NON-NLS-1$
- public static final String OPTION_ReportAssertIdentifier = "org.eclipse.wst.jsdt.core.compiler.problem.assertIdentifier"; //$NON-NLS-1$
- public static final String OPTION_ReportEnumIdentifier = "org.eclipse.wst.jsdt.core.compiler.problem.enumIdentifier"; //$NON-NLS-1$
- public static final String OPTION_ReportNonStaticAccessToStatic = "org.eclipse.wst.jsdt.core.compiler.problem.staticAccessReceiver"; //$NON-NLS-1$
- public static final String OPTION_ReportIndirectStaticAccess = "org.eclipse.wst.jsdt.core.compiler.problem.indirectStaticAccess"; //$NON-NLS-1$
- public static final String OPTION_ReportEmptyStatement = "org.eclipse.wst.jsdt.core.compiler.problem.emptyStatement"; //$NON-NLS-1$
- public static final String OPTION_ReportUnnecessaryTypeCheck = "org.eclipse.wst.jsdt.core.compiler.problem.unnecessaryTypeCheck"; //$NON-NLS-1$
- public static final String OPTION_ReportUnnecessaryElse = "org.eclipse.wst.jsdt.core.compiler.problem.unnecessaryElse"; //$NON-NLS-1$
- public static final String OPTION_ReportUndocumentedEmptyBlock = "org.eclipse.wst.jsdt.core.compiler.problem.undocumentedEmptyBlock"; //$NON-NLS-1$
- public static final String OPTION_ReportInvalidJavadoc = "org.eclipse.wst.jsdt.core.compiler.problem.invalidJavadoc"; //$NON-NLS-1$
- public static final String OPTION_ReportInvalidJavadocTags = "org.eclipse.wst.jsdt.core.compiler.problem.invalidJavadocTags"; //$NON-NLS-1$
- public static final String OPTION_ReportInvalidJavadocTagsDeprecatedRef = "org.eclipse.wst.jsdt.core.compiler.problem.invalidJavadocTagsDeprecatedRef"; //$NON-NLS-1$
- public static final String OPTION_ReportInvalidJavadocTagsNotVisibleRef = "org.eclipse.wst.jsdt.core.compiler.problem.invalidJavadocTagsNotVisibleRef"; //$NON-NLS-1$
- public static final String OPTION_ReportInvalidJavadocTagsVisibility = "org.eclipse.wst.jsdt.core.compiler.problem.invalidJavadocTagsVisibility"; //$NON-NLS-1$
- public static final String OPTION_ReportMissingJavadocTags = "org.eclipse.wst.jsdt.core.compiler.problem.missingJavadocTags"; //$NON-NLS-1$
- public static final String OPTION_ReportMissingJavadocTagsVisibility = "org.eclipse.wst.jsdt.core.compiler.problem.missingJavadocTagsVisibility"; //$NON-NLS-1$
- public static final String OPTION_ReportMissingJavadocTagsOverriding = "org.eclipse.wst.jsdt.core.compiler.problem.missingJavadocTagsOverriding"; //$NON-NLS-1$
- public static final String OPTION_ReportMissingJavadocComments = "org.eclipse.wst.jsdt.core.compiler.problem.missingJavadocComments"; //$NON-NLS-1$
- public static final String OPTION_ReportMissingJavadocCommentsVisibility = "org.eclipse.wst.jsdt.core.compiler.problem.missingJavadocCommentsVisibility"; //$NON-NLS-1$
- public static final String OPTION_ReportMissingJavadocCommentsOverriding = "org.eclipse.wst.jsdt.core.compiler.problem.missingJavadocCommentsOverriding"; //$NON-NLS-1$
- public static final String OPTION_ReportFinallyBlockNotCompletingNormally = "org.eclipse.wst.jsdt.core.compiler.problem.finallyBlockNotCompletingNormally"; //$NON-NLS-1$
- public static final String OPTION_ReportUnusedDeclaredThrownException = "org.eclipse.wst.jsdt.core.compiler.problem.unusedDeclaredThrownException"; //$NON-NLS-1$
- public static final String OPTION_ReportUnusedDeclaredThrownExceptionWhenOverriding = "org.eclipse.wst.jsdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding"; //$NON-NLS-1$
- public static final String OPTION_ReportUnqualifiedFieldAccess = "org.eclipse.wst.jsdt.core.compiler.problem.unqualifiedFieldAccess"; //$NON-NLS-1$
- public static final String OPTION_ReportUncheckedTypeOperation = "org.eclipse.wst.jsdt.core.compiler.problem.uncheckedTypeOperation"; //$NON-NLS-1$
- public static final String OPTION_ReportRawTypeReference = "org.eclipse.wst.jsdt.core.compiler.problem.rawTypeReference"; //$NON-NLS-1$
- public static final String OPTION_ReportFinalParameterBound = "org.eclipse.wst.jsdt.core.compiler.problem.finalParameterBound"; //$NON-NLS-1$
- public static final String OPTION_Source = "org.eclipse.wst.jsdt.core.compiler.source"; //$NON-NLS-1$
- public static final String OPTION_TargetPlatform = "org.eclipse.wst.jsdt.core.compiler.codegen.targetPlatform"; //$NON-NLS-1$
- public static final String OPTION_Compliance = "org.eclipse.wst.jsdt.core.compiler.compliance"; //$NON-NLS-1$
- public static final String OPTION_Encoding = "org.eclipse.wst.jsdt.core.encoding"; //$NON-NLS-1$
- public static final String OPTION_MaxProblemPerUnit = "org.eclipse.wst.jsdt.core.compiler.maxProblemPerUnit"; //$NON-NLS-1$
- public static final String OPTION_TaskTags = "org.eclipse.wst.jsdt.core.compiler.taskTags"; //$NON-NLS-1$
- public static final String OPTION_TaskPriorities = "org.eclipse.wst.jsdt.core.compiler.taskPriorities"; //$NON-NLS-1$
- public static final String OPTION_TaskCaseSensitive = "org.eclipse.wst.jsdt.core.compiler.taskCaseSensitive"; //$NON-NLS-1$
- public static final String OPTION_InlineJsr = "org.eclipse.wst.jsdt.core.compiler.codegen.inlineJsrBytecode"; //$NON-NLS-1$
- public static final String OPTION_ReportNullReference = "org.eclipse.wst.jsdt.core.compiler.problem.nullReference"; //$NON-NLS-1$
- public static final String OPTION_ReportPotentialNullReference = "org.eclipse.wst.jsdt.core.compiler.problem.potentialNullReference"; //$NON-NLS-1$
- public static final String OPTION_ReportDuplicateLocalVariables = "org.eclipse.wst.jsdt.core.compiler.problem.duplicateLocalVariables"; //$NON-NLS-1$
- public static final String OPTION_ReportRedundantNullCheck = "org.eclipse.wst.jsdt.core.compiler.problem.redundantNullCheck"; //$NON-NLS-1$
- public static final String OPTION_ReportUninitializedLocalVariable = "org.eclipse.wst.jsdt.core.compiler.problem.uninitializedLocalVariable"; //$NON-NLS-1$
- public static final String OPTION_ReportUninitializedGlobalVariable = "org.eclipse.wst.jsdt.core.compiler.problem.uninitializedGlobalVariable"; //$NON-NLS-1$
- public static final String OPTION_ReportForbiddenReference = "org.eclipse.wst.jsdt.core.compiler.problem.forbiddenReference"; //$NON-NLS-1$
- public static final String OPTION_ReportDiscouragedReference = "org.eclipse.wst.jsdt.core.compiler.problem.discouragedReference"; //$NON-NLS-1$
- public static final String OPTION_SuppressWarnings = "org.eclipse.wst.jsdt.core.compiler.problem.suppressWarnings"; //$NON-NLS-1$
- public static final String OPTION_ReportUnusedLabel = "org.eclipse.wst.jsdt.core.compiler.problem.unusedLabel"; //$NON-NLS-1$
- public static final String OPTION_FatalOptionalError = "org.eclipse.wst.jsdt.core.compiler.problem.fatalOptionalError"; //$NON-NLS-1$
- public static final String OPTION_ReportParameterAssignment = "org.eclipse.wst.jsdt.core.compiler.problem.parameterAssignment"; //$NON-NLS-1$
- public static final String OPTION_ReportFallthroughCase = "org.eclipse.wst.jsdt.core.compiler.problem.fallthroughCase"; //$NON-NLS-1$
- public static final String OPTION_ReportOverridingMethodWithoutSuperInvocation = "org.eclipse.wst.jsdt.core.compiler.problem.overridingMethodWithoutSuperInvocation"; //$NON-NLS-1$
- public static final String OPTION_GenerateClassFiles = "org.eclipse.wst.jsdt.core.compiler.generateClassFiles"; //$NON-NLS-1$
- public static final String OPTION_Process_Annotations = "org.eclipse.wst.jsdt.core.compiler.processAnnotations"; //$NON-NLS-1$
-
- /* START -------------------------------- Bug 203292 Type/Method/Filed resolution error configuration --------------------- */
- public static final String OPTION_Unresolved_Type = JavaScriptCore.UNRESOLVED_TYPE_REFERENCE;
- public static final String OPTION_Unresolved_Field = JavaScriptCore.UNRESOLVED_FIELD_REFERENCE;
- public static final String OPTION_Unresolved_Method = JavaScriptCore.UNRESOLVED_METHOD_REFERENCE;
- /* END -------------------------------- Bug 203292 Type/Method/Filed resolution error configuration --------------------- */
-
- /* START -------------------------------- Bug 197884 Loosly defined var (for statement) and optional semi-colon --------------------- */
- public static final String OPTION_LOOSE_VAR_DECL = JavaScriptCore.LOOSE_VAR_DECL;
- public static final String OPTION_OPTIONAL_SEMICOLON = JavaScriptCore.OPTIONAL_SEMICOLON;
- /* END -------------------------------- Bug 197884 Loosly defined var (for statement) and optional semi-colon --------------------- */
-
-
-
- // Backward compatibility
- public static final String OPTION_ReportInvalidAnnotation = "org.eclipse.wst.jsdt.core.compiler.problem.invalidAnnotation"; //$NON-NLS-1$
- public static final String OPTION_ReportMissingAnnotation = "org.eclipse.wst.jsdt.core.compiler.problem.missingAnnotation"; //$NON-NLS-1$
- public static final String OPTION_ReportMissingJavadoc = "org.eclipse.wst.jsdt.core.compiler.problem.missingJavadoc"; //$NON-NLS-1$
-
- /**
- * Possible values for configurable options
- */
- public static final String GENERATE = "generate";//$NON-NLS-1$
- public static final String DO_NOT_GENERATE = "do not generate"; //$NON-NLS-1$
- public static final String PRESERVE = "preserve"; //$NON-NLS-1$
- public static final String OPTIMIZE_OUT = "optimize out"; //$NON-NLS-1$
- public static final String VERSION_1_1 = "1.1"; //$NON-NLS-1$
- public static final String VERSION_1_2 = "1.2"; //$NON-NLS-1$
- public static final String VERSION_1_3 = "1.3"; //$NON-NLS-1$
- public static final String VERSION_1_4 = "1.4"; //$NON-NLS-1$
- public static final String VERSION_JSR14 = "jsr14"; //$NON-NLS-1$
- public static final String VERSION_1_5 = "1.5"; //$NON-NLS-1$
- public static final String VERSION_1_6 = "1.6"; //$NON-NLS-1$
- public static final String VERSION_1_7 = "1.7"; //$NON-NLS-1$
- public static final String ERROR = "error"; //$NON-NLS-1$
- public static final String WARNING = "warning"; //$NON-NLS-1$
- public static final String IGNORE = "ignore"; //$NON-NLS-1$
- public static final String ENABLED = "enabled"; //$NON-NLS-1$
- public static final String DISABLED = "disabled"; //$NON-NLS-1$
- public static final String PUBLIC = "public"; //$NON-NLS-1$
- public static final String PROTECTED = "protected"; //$NON-NLS-1$
- public static final String DEFAULT = "default"; //$NON-NLS-1$
- public static final String PRIVATE = "private"; //$NON-NLS-1$
-
- /**
- * Bit mask for configurable problems (error/warning threshold)
- */
- public static final long MethodWithConstructorName = ASTNode.Bit1;
- public static final long UndefinedField = ASTNode.Bit2;
- public static final long UsingDeprecatedAPI = ASTNode.Bit3;
- public static final long MaskedCatchBlock = ASTNode.Bit4;
- public static final long UnusedLocalVariable = ASTNode.Bit5;
- public static final long UnusedArgument = ASTNode.Bit6;
-//TODO: remove AccessEmulation
- public static final long AccessEmulation = ASTNode.Bit8;
- public static final long WrongNumberOfArguments = ASTNode.Bit8;
- public static final long NonExternalizedString = ASTNode.Bit9;
- public static final long AssertUsedAsAnIdentifier = ASTNode.Bit10;
- public static final long NonStaticAccessToStatic = ASTNode.Bit12;
- public static final long Task = ASTNode.Bit13;
- public static final long NoEffectAssignment = ASTNode.Bit14;
- public static final long UnusedPrivateMember = ASTNode.Bit16;
- public static final long LocalVariableHiding = ASTNode.Bit17;
- public static final long FieldHiding = ASTNode.Bit18;
- public static final long AccidentalBooleanAssign = ASTNode.Bit19;
- public static final long EmptyStatement = ASTNode.Bit20;
- public static final long MissingJavadocComments = ASTNode.Bit21;
- public static final long MissingJavadocTags = ASTNode.Bit22;
- public static final long UnqualifiedFieldAccess = ASTNode.Bit23;
- public static final long UnusedDeclaredThrownException = ASTNode.Bit24;
- public static final long FinallyBlockNotCompleting = ASTNode.Bit25;
- public static final long InvalidJavadoc = ASTNode.Bit26;
- public static final long UnnecessaryTypeCheck = ASTNode.Bit27;
- public static final long UndocumentedEmptyBlock = ASTNode.Bit28;
- public static final long IndirectStaticAccess = ASTNode.Bit29;
- public static final long UnnecessaryElse = ASTNode.Bit30;
- public static final long UncheckedTypeOperation = ASTNode.Bit31;
- public static final long FinalParameterBound = ASTNode.Bit32L;
- public static final long EnumUsedAsAnIdentifier = ASTNode.Bit34L;
- public static final long ForbiddenReference = ASTNode.Bit35L;
- public static final long NullReference = ASTNode.Bit37L;
- public static final long TypeHiding = ASTNode.Bit40L;
- public static final long DiscouragedReference = ASTNode.Bit44L;
- public static final long RawTypeReference = ASTNode.Bit46L;
- public static final long UnusedLabel = ASTNode.Bit47L;
- public static final long ParameterAssignment = ASTNode.Bit48L;
- public static final long FallthroughCase = ASTNode.Bit49L;
- public static final long OverridingMethodWithoutSuperInvocation = ASTNode.Bit50L;
- public static final long PotentialNullReference = ASTNode.Bit51L;
- public static final long DuplicateLocalVariables = ASTNode.Bit58L;
- public static final long RedundantNullCheck = ASTNode.Bit52L;
-
-
- /* START -------------------------------- Bug 203292 Type/Method/Filed resolution error configuration --------------------- */
- public static final long UnresolvedType = ASTNode.Bit53L;
- public static final long UnresolvedMethod = ASTNode.Bit54L;
- public static final long UnresolvedField = ASTNode.Bit55L;
-
- /* END -------------------------------- Bug 203292 Type/Method/Filed resolution error configuration --------------------- */
-
- /* START -------------------------------- Bug 197884 Loosly defined var (for statement) and optional semi-colon --------------------- */
- public static final long LooseVariableDecl = ASTNode.Bit56L;
- public static final long OptionalSemicolon = ASTNode.Bit57L;
-
- /* END -------------------------------- Bug 197884 Loosly defined var (for statement) and optional semi-colon --------------------- */
-
- public static final long UninitializedLocalVariable = ASTNode.Bit59L;
- public static final long UninitializedGlobalVariable = ASTNode.Bit60L;
-
- // Map: String optionKey --> Long irritant>
- private static Map OptionToIrritants;
-
- // Default severity level for handlers
- public long errorThreshold = 0;
-
- public long warningThreshold =
- MethodWithConstructorName
- | UsingDeprecatedAPI
- | MaskedCatchBlock
- | UndefinedField
- | NonStaticAccessToStatic
- | NoEffectAssignment
- | FinallyBlockNotCompleting
- | AssertUsedAsAnIdentifier
- | EnumUsedAsAnIdentifier
- | UncheckedTypeOperation
- | RawTypeReference
- | ForbiddenReference
- | DiscouragedReference
- | TypeHiding
- | FinalParameterBound
- | UnusedLocalVariable
- | UnusedPrivateMember
- | UnusedLabel
- /*| NullReference -- keep JavaScriptCore#getDefaultOptions comment in sync */;
-
- // By default only lines and source attributes are generated.
- public int produceDebugAttributes = ClassFileConstants.ATTR_SOURCE | ClassFileConstants.ATTR_LINES;
-
- public long complianceLevel = ClassFileConstants.JDK1_4; // by default be compliant with 1.4
- public long sourceLevel = ClassFileConstants.JDK1_3; //1.3 source behavior by default
- public long targetJDK = ClassFileConstants.JDK1_2; // default generates for JVM1.2
-
- // source encoding format
- public String defaultEncoding = null; // will use the platform default encoding
-
- // print what unit is being processed
- public boolean verbose = Compiler.DEBUG;
-
- // indicates if reference info is desired
- public boolean produceReferenceInfo = false;
-
- // indicates if unused/optimizable local variables need to be preserved (debugging purpose)
- public boolean preserveAllLocalVariables = false;
-
- // indicates whether literal expressions are inlined at parse-time or not
- public boolean parseLiteralExpressionsAsConstants = true;
-
- // max problems per compilation unit
- public int maxProblemsPerUnit = 100; // no more than 100 problems per default
-
- // tags used to recognize tasks in comments
- public char[][] taskTags = null;
- public char[][] taskPriorites = null;
- public boolean isTaskCaseSensitive = true;
-
- // deprecation report
- public boolean reportDeprecationInsideDeprecatedCode = false;
- public boolean reportDeprecationWhenOverridingDeprecatedMethod = false;
-
- // unused parameters report
- public boolean reportUnusedParameterWhenImplementingAbstract = false;
- public boolean reportUnusedParameterWhenOverridingConcrete = false;
- public boolean reportUnusedParameterIncludeDocCommentReference = true;
-
- // unused declaration of thrown exception
- public boolean reportUnusedDeclaredThrownExceptionWhenOverriding = false;
-
- // constructor/setter parameter hiding
- public boolean reportSpecialParameterHidingField = false;
-
- // check javadoc comments tags
- public int reportInvalidJavadocTagsVisibility = ClassFileConstants.AccDefault;
- public boolean reportInvalidJavadocTags = false;
- public boolean reportInvalidJavadocTagsDeprecatedRef = false;
- public boolean reportInvalidJavadocTagsNotVisibleRef = false;
-
- // check missing javadoc tags
- public int reportMissingJavadocTagsVisibility = ClassFileConstants.AccDefault;
- public boolean reportMissingJavadocTagsOverriding = false;
-
- // check missing javadoc comments
- public int reportMissingJavadocCommentsVisibility = ClassFileConstants.AccDefault;
- public boolean reportMissingJavadocCommentsOverriding = false;
-
- // JSR bytecode inlining
- public boolean inlineJsrBytecode = false;
-
- // javadoc comment support
- public boolean docCommentSupport = false;
-
- // suppress warning annotation
- public boolean suppressWarnings = true;
-
- // treat optional error as fatal or just like warning?
- public boolean treatOptionalErrorAsFatal = true;
-
- // parser perform statements recovery
- public boolean performMethodsFullRecovery = true;
-
- // parser perform statements recovery
- public boolean performStatementsRecovery = true;
-
- // store annotations
- public boolean storeAnnotations = false;
-
- // annotation processing
- public boolean generateClassFiles = true;
-
- // Enable annotation processing by default only in batch mode
- public boolean processAnnotations = false;
-
-
- public InferOptions inferOptions=new InferOptions();
-
-
- public boolean enableSemanticValidation=false;
-
-
- /**
- * Initializing the compiler options with defaults
- */
- public CompilerOptions() {
- // use default options
- }
-
- /**
- * Initializing the compiler options with external settings
- * @param settings
- */
- public CompilerOptions(Map settings){
- if (settings == null) return;
- set(settings);
- }
-
- /**
- * @deprecated used to preserve 3.1 and 3.2M4 compatibility of some Compiler constructors
- */
- public CompilerOptions(Map settings, boolean parseLiteralExpressionsAsConstants){
- this(settings);
- this.parseLiteralExpressionsAsConstants = parseLiteralExpressionsAsConstants;
- }
-
- public Map getMap() {
- HashMap optionsMap = new HashMap(30);
- optionsMap.put(OPTION_SemanticValidation, this.enableSemanticValidation ? ENABLED : DISABLED);
- optionsMap.put(OPTION_LocalVariableAttribute, (this.produceDebugAttributes & ClassFileConstants.ATTR_VARS) != 0 ? GENERATE : DO_NOT_GENERATE);
- optionsMap.put(OPTION_LineNumberAttribute, (this.produceDebugAttributes & ClassFileConstants.ATTR_LINES) != 0 ? GENERATE : DO_NOT_GENERATE);
- optionsMap.put(OPTION_SourceFileAttribute, (this.produceDebugAttributes & ClassFileConstants.ATTR_SOURCE) != 0 ? GENERATE : DO_NOT_GENERATE);
- optionsMap.put(OPTION_PreserveUnusedLocal, this.preserveAllLocalVariables ? PRESERVE : OPTIMIZE_OUT);
- optionsMap.put(OPTION_DocCommentSupport, this.docCommentSupport ? ENABLED : DISABLED);
- optionsMap.put(OPTION_ReportMethodWithConstructorName, getSeverityString(MethodWithConstructorName));
- optionsMap.put(OPTION_ReportUndefinedField, getSeverityString(UndefinedField));
- optionsMap.put(OPTION_ReportDeprecation, getSeverityString(UsingDeprecatedAPI));
- optionsMap.put(OPTION_ReportDeprecationInDeprecatedCode, this.reportDeprecationInsideDeprecatedCode ? ENABLED : DISABLED);
- optionsMap.put(OPTION_ReportDeprecationWhenOverridingDeprecatedMethod, this.reportDeprecationWhenOverridingDeprecatedMethod ? ENABLED : DISABLED);
- optionsMap.put(OPTION_ReportHiddenCatchBlock, getSeverityString(MaskedCatchBlock));
- optionsMap.put(OPTION_ReportUnusedLocal, getSeverityString(UnusedLocalVariable));
- optionsMap.put(OPTION_ReportUnusedParameter, getSeverityString(UnusedArgument));
- optionsMap.put(OPTION_ReportWrongNumberOfArguments, getSeverityString(WrongNumberOfArguments));
- optionsMap.put(OPTION_ReportNoEffectAssignment, getSeverityString(NoEffectAssignment));
- optionsMap.put(OPTION_ReportNonExternalizedStringLiteral, getSeverityString(NonExternalizedString));
- optionsMap.put(OPTION_ReportNonStaticAccessToStatic, getSeverityString(NonStaticAccessToStatic));
- optionsMap.put(OPTION_ReportIndirectStaticAccess, getSeverityString(IndirectStaticAccess));
- optionsMap.put(OPTION_ReportUnusedPrivateMember, getSeverityString(UnusedPrivateMember));
- optionsMap.put(OPTION_ReportLocalVariableHiding, getSeverityString(LocalVariableHiding));
- optionsMap.put(OPTION_ReportFieldHiding, getSeverityString(FieldHiding));
- optionsMap.put(OPTION_ReportTypeParameterHiding, getSeverityString(TypeHiding));
- optionsMap.put(OPTION_ReportPossibleAccidentalBooleanAssignment, getSeverityString(AccidentalBooleanAssign));
- optionsMap.put(OPTION_ReportEmptyStatement, getSeverityString(EmptyStatement));
- optionsMap.put(OPTION_ReportAssertIdentifier, getSeverityString(AssertUsedAsAnIdentifier));
- optionsMap.put(OPTION_ReportEnumIdentifier, getSeverityString(EnumUsedAsAnIdentifier));
- optionsMap.put(OPTION_ReportUndocumentedEmptyBlock, getSeverityString(UndocumentedEmptyBlock));
- optionsMap.put(OPTION_ReportUnnecessaryTypeCheck, getSeverityString(UnnecessaryTypeCheck));
- optionsMap.put(OPTION_ReportUnnecessaryElse, getSeverityString(UnnecessaryElse));
- optionsMap.put(OPTION_ReportInvalidJavadoc, getSeverityString(InvalidJavadoc));
- optionsMap.put(OPTION_ReportInvalidJavadocTagsVisibility, getVisibilityString(this.reportInvalidJavadocTagsVisibility));
- optionsMap.put(OPTION_ReportInvalidJavadocTags, this.reportInvalidJavadocTags ? ENABLED : DISABLED);
- optionsMap.put(OPTION_ReportInvalidJavadocTagsDeprecatedRef, this.reportInvalidJavadocTagsDeprecatedRef ? ENABLED : DISABLED);
- optionsMap.put(OPTION_ReportInvalidJavadocTagsNotVisibleRef, this.reportInvalidJavadocTagsNotVisibleRef ? ENABLED : DISABLED);
- optionsMap.put(OPTION_ReportMissingJavadocTags, getSeverityString(MissingJavadocTags));
- optionsMap.put(OPTION_ReportMissingJavadocTagsVisibility, getVisibilityString(this.reportMissingJavadocTagsVisibility));
- optionsMap.put(OPTION_ReportMissingJavadocTagsOverriding, this.reportMissingJavadocTagsOverriding ? ENABLED : DISABLED);
- optionsMap.put(OPTION_ReportMissingJavadocComments, getSeverityString(MissingJavadocComments));
- optionsMap.put(OPTION_ReportMissingJavadocCommentsVisibility, getVisibilityString(this.reportMissingJavadocCommentsVisibility));
- optionsMap.put(OPTION_ReportMissingJavadocCommentsOverriding, this.reportMissingJavadocCommentsOverriding ? ENABLED : DISABLED);
- optionsMap.put(OPTION_ReportFinallyBlockNotCompletingNormally, getSeverityString(FinallyBlockNotCompleting));
- optionsMap.put(OPTION_ReportUnusedDeclaredThrownException, getSeverityString(UnusedDeclaredThrownException));
- optionsMap.put(OPTION_ReportUnusedDeclaredThrownExceptionWhenOverriding, this.reportUnusedDeclaredThrownExceptionWhenOverriding ? ENABLED : DISABLED);
- optionsMap.put(OPTION_ReportUnqualifiedFieldAccess, getSeverityString(UnqualifiedFieldAccess));
- optionsMap.put(OPTION_ReportUncheckedTypeOperation, getSeverityString(UncheckedTypeOperation));
- optionsMap.put(OPTION_ReportRawTypeReference, getSeverityString(RawTypeReference));
- optionsMap.put(OPTION_ReportFinalParameterBound, getSeverityString(FinalParameterBound));
- optionsMap.put(OPTION_ReportForbiddenReference, getSeverityString(ForbiddenReference));
- optionsMap.put(OPTION_ReportDiscouragedReference, getSeverityString(DiscouragedReference));
- optionsMap.put(OPTION_ReportUnusedLabel, getSeverityString(UnusedLabel));
- optionsMap.put(OPTION_Compliance, versionFromJdkLevel(this.complianceLevel));
- optionsMap.put(OPTION_Source, versionFromJdkLevel(this.sourceLevel));
- optionsMap.put(OPTION_TargetPlatform, versionFromJdkLevel(this.targetJDK));
- optionsMap.put(OPTION_FatalOptionalError, this.treatOptionalErrorAsFatal ? ENABLED : DISABLED);
- if (this.defaultEncoding != null) {
- optionsMap.put(OPTION_Encoding, this.defaultEncoding);
- }
- optionsMap.put(OPTION_TaskTags, this.taskTags == null ? Util.EMPTY_STRING : new String(CharOperation.concatWith(this.taskTags,',')));
- optionsMap.put(OPTION_TaskPriorities, this.taskPriorites == null ? Util.EMPTY_STRING : new String(CharOperation.concatWith(this.taskPriorites,',')));
- optionsMap.put(OPTION_TaskCaseSensitive, this.isTaskCaseSensitive ? ENABLED : DISABLED);
- optionsMap.put(OPTION_ReportUnusedParameterWhenImplementingAbstract, this.reportUnusedParameterWhenImplementingAbstract ? ENABLED : DISABLED);
- optionsMap.put(OPTION_ReportUnusedParameterWhenOverridingConcrete, this.reportUnusedParameterWhenOverridingConcrete ? ENABLED : DISABLED);
- optionsMap.put(OPTION_ReportUnusedParameterIncludeDocCommentReference, this.reportUnusedParameterIncludeDocCommentReference ? ENABLED : DISABLED);
- optionsMap.put(OPTION_ReportSpecialParameterHidingField, this.reportSpecialParameterHidingField ? ENABLED : DISABLED);
- optionsMap.put(OPTION_MaxProblemPerUnit, String.valueOf(this.maxProblemsPerUnit));
- optionsMap.put(OPTION_InlineJsr, this.inlineJsrBytecode ? ENABLED : DISABLED);
- optionsMap.put(OPTION_ReportNullReference, getSeverityString(NullReference));
- optionsMap.put(OPTION_ReportPotentialNullReference, getSeverityString(PotentialNullReference));
- optionsMap.put(OPTION_ReportDuplicateLocalVariables, getSeverityString(DuplicateLocalVariables));
- optionsMap.put(OPTION_ReportRedundantNullCheck, getSeverityString(RedundantNullCheck));
- optionsMap.put(OPTION_ReportUninitializedLocalVariable, getSeverityString(UninitializedLocalVariable));
- optionsMap.put(OPTION_ReportUninitializedGlobalVariable, getSeverityString(UninitializedGlobalVariable));
- optionsMap.put(OPTION_SuppressWarnings, this.suppressWarnings ? ENABLED : DISABLED);
- optionsMap.put(OPTION_ReportParameterAssignment, getSeverityString(ParameterAssignment));
- optionsMap.put(OPTION_ReportFallthroughCase, getSeverityString(FallthroughCase));
- optionsMap.put(OPTION_ReportOverridingMethodWithoutSuperInvocation, getSeverityString(OverridingMethodWithoutSuperInvocation));
- optionsMap.put(OPTION_GenerateClassFiles, this.generateClassFiles ? ENABLED : DISABLED);
- optionsMap.put(OPTION_Process_Annotations, this.processAnnotations ? ENABLED : DISABLED);
-
- /* START -------------------------------- Bug 203292 Type/Method/Filed resolution error configuration --------------------- */
- optionsMap.put(OPTION_Unresolved_Type, getSeverityString(UnresolvedType));
- optionsMap.put(OPTION_Unresolved_Field, getSeverityString(UnresolvedField));
- optionsMap.put(OPTION_Unresolved_Method, getSeverityString(UnresolvedMethod));
- /* END -------------------------------- Bug 203292 Type/Method/Filed resolution error configuration --------------------- */
- /* START -------------------------------- Bug 197884 Loosly defined var (for statement) and optional semi-colon --------------------- */
- optionsMap.put(OPTION_LOOSE_VAR_DECL, getSeverityString(LooseVariableDecl));
- optionsMap.put(OPTION_OPTIONAL_SEMICOLON, getSeverityString(OptionalSemicolon));
-
- /* END -------------------------------- Bug 197884 Loosly defined var (for statement) and optional semi-colon --------------------- */
-
-
- Map inferOptionsMap = inferOptions.getMap();
- optionsMap.putAll(inferOptionsMap);
-
- return optionsMap;
- }
-
- /**
- * Return the most specific option key controlling this irritant. Note that in some case, some irritant is controlled by
- * other master options (e.g. javadoc, deprecation, etc.).
- * This information is intended for grouping purpose (several problems governed by a rule)
- */
- public static String optionKeyFromIrritant(long irritant) {
- // keep in sync with warningTokens and warningTokenToIrritant
- int irritantInt = (int) irritant;
- if (irritantInt == irritant) {
- switch (irritantInt) {
- case (int) MethodWithConstructorName :
- return OPTION_ReportMethodWithConstructorName;
- case (int) UndefinedField :
- return OPTION_ReportUndefinedField;
- case (int) UsingDeprecatedAPI :
- case (int) (InvalidJavadoc | UsingDeprecatedAPI) :
- return OPTION_ReportDeprecation;
- case (int) MaskedCatchBlock :
- return OPTION_ReportHiddenCatchBlock;
- case (int) UnusedLocalVariable :
- return OPTION_ReportUnusedLocal;
- case (int) UnusedArgument :
- return OPTION_ReportUnusedParameter;
- case (int) WrongNumberOfArguments :
- return OPTION_ReportWrongNumberOfArguments;
- case (int) NonExternalizedString :
- return OPTION_ReportNonExternalizedStringLiteral;
- case (int) AssertUsedAsAnIdentifier :
- return OPTION_ReportAssertIdentifier;
- case (int) NonStaticAccessToStatic :
- return OPTION_ReportNonStaticAccessToStatic;
- case (int) Task :
- return OPTION_TaskTags;
- case (int) NoEffectAssignment :
- return OPTION_ReportNoEffectAssignment;
- case (int) UnusedPrivateMember :
- return OPTION_ReportUnusedPrivateMember;
- case (int) LocalVariableHiding :
- return OPTION_ReportLocalVariableHiding;
- case (int) FieldHiding :
- return OPTION_ReportFieldHiding;
- case (int) AccidentalBooleanAssign :
- return OPTION_ReportPossibleAccidentalBooleanAssignment;
- case (int) EmptyStatement :
- return OPTION_ReportEmptyStatement;
- case (int) MissingJavadocComments :
- return OPTION_ReportMissingJavadocComments;
- case (int) MissingJavadocTags :
- return OPTION_ReportMissingJavadocTags;
- case (int) UnqualifiedFieldAccess :
- return OPTION_ReportUnqualifiedFieldAccess;
- case (int) UnusedDeclaredThrownException :
- return OPTION_ReportUnusedDeclaredThrownExceptionWhenOverriding;
- case (int) FinallyBlockNotCompleting :
- return OPTION_ReportFinallyBlockNotCompletingNormally;
- case (int) InvalidJavadoc :
- return OPTION_ReportInvalidJavadoc;
- case (int) UnnecessaryTypeCheck :
- return OPTION_ReportUnnecessaryTypeCheck;
- case (int) UndocumentedEmptyBlock :
- return OPTION_ReportUndocumentedEmptyBlock;
- case (int) IndirectStaticAccess :
- return OPTION_ReportIndirectStaticAccess;
- case (int) UnnecessaryElse :
- return OPTION_ReportUnnecessaryElse;
- case (int) UncheckedTypeOperation :
- return OPTION_ReportUncheckedTypeOperation;
- case (int) FinalParameterBound :
- return OPTION_ReportFinalParameterBound;
- }
- } else {
- irritantInt = (int)(irritant >>> 32);
- switch (irritantInt) {
- case (int)(EnumUsedAsAnIdentifier >>> 32) :
- return OPTION_ReportEnumIdentifier;
- case (int)(ForbiddenReference >>> 32) :
- return OPTION_ReportForbiddenReference;
- case (int)(NullReference >>> 32) :
- return OPTION_ReportNullReference;
- case (int)(PotentialNullReference >>> 32) :
- return OPTION_ReportPotentialNullReference;
- case (int)(DuplicateLocalVariables >>> 32) :
- return OPTION_ReportDuplicateLocalVariables;
- case (int)(RedundantNullCheck >>> 32) :
- return OPTION_ReportRedundantNullCheck;
- case (int)(UninitializedLocalVariable >>> 32) :
- return OPTION_ReportUninitializedLocalVariable;
- case (int)(UninitializedGlobalVariable >>> 32) :
- return OPTION_ReportUninitializedGlobalVariable;
- case (int)(TypeHiding >>> 32) :
- return OPTION_ReportTypeParameterHiding;
- case (int)(DiscouragedReference >>> 32) :
- return OPTION_ReportDiscouragedReference;
- case (int)(RawTypeReference >>> 32) :
- return OPTION_ReportRawTypeReference;
- case (int)(UnusedLabel >>> 32) :
- return OPTION_ReportUnusedLabel;
- case (int)(ParameterAssignment>>> 32) :
- return OPTION_ReportParameterAssignment;
- case (int)(FallthroughCase >>> 32) :
- return OPTION_ReportFallthroughCase;
- case (int)(OverridingMethodWithoutSuperInvocation >>> 32) :
- return OPTION_ReportOverridingMethodWithoutSuperInvocation;
-
-
- /* START -------------------------------- Bug 203292 Type/Method/Filed resolution error configuration --------------------- */
-
- case (int)(UnresolvedType >>> 32) :
- return OPTION_Unresolved_Type;
- case (int)(UnresolvedMethod >>> 32) :
- return OPTION_Unresolved_Method;
- case (int)(UnresolvedField >>> 32) :
- return OPTION_Unresolved_Field;
-
- /* END -------------------------------- Bug 203292 Type/Method/Filed resolution error configuration --------------------- */
-
- /* START -------------------------------- Bug 197884 Loosly defined var (for statement) and optional semi-colon --------------------- */
- case (int)(LooseVariableDecl >>> 32) :
- return OPTION_LOOSE_VAR_DECL;
- case (int)( OptionalSemicolon >>> 32) :
- return OPTION_OPTIONAL_SEMICOLON;
-
- /* END -------------------------------- Bug 197884 Loosly defined var (for statement) and optional semi-colon --------------------- */
-
-
-
- }
- }
- return null;
- }
-
- public static long optionKeyToIrritant(String optionName) {
- if (OptionToIrritants == null) {
- long irritant = 0;
- for (int i = 0; i < 64; i++) {
- irritant <<= 1;
- String optionKey = optionKeyFromIrritant(irritant);
- if (optionKey == null) continue;
- OptionToIrritants.put(optionKey, new Long(irritant));
- }
- }
- Long irritant = (Long)OptionToIrritants.get(optionName);
- return irritant == null ? 0 : irritant.longValue();
- }
-
- public int getSeverity(long irritant) {
- if((this.errorThreshold & irritant) != 0) {
- return this.treatOptionalErrorAsFatal
- ? ProblemSeverities.Error | ProblemSeverities.Optional | ProblemSeverities.Fatal
- : ProblemSeverities.Error | ProblemSeverities.Optional;
- }
- if((this.warningThreshold & irritant) != 0)
- return ProblemSeverities.Warning | ProblemSeverities.Optional;
- return ProblemSeverities.Ignore;
- }
-
- public String getSeverityString(long irritant) {
- if((this.warningThreshold & irritant) != 0)
- return WARNING;
- if((this.errorThreshold & irritant) != 0)
- return ERROR;
- return IGNORE;
- }
-
- public String getVisibilityString(int level) {
- switch (level & ExtraCompilerModifiers.AccVisibilityMASK) {
- case ClassFileConstants.AccPublic:
- return PUBLIC;
- case ClassFileConstants.AccProtected:
- return PROTECTED;
- case ClassFileConstants.AccPrivate:
- return PRIVATE;
- default:
- return DEFAULT;
- }
- }
-
- public void set(Map optionsMap) {
- Object optionValue;
- if ((optionValue = optionsMap.get(OPTION_SemanticValidation)) != null) {
- if (ENABLED.equals(optionValue)) {
- this.enableSemanticValidation = true;
- } else if (DISABLED.equals(optionValue)) {
- this.enableSemanticValidation = false;
- }
- }
- if ((optionValue = optionsMap.get(OPTION_LocalVariableAttribute)) != null) {
- if (GENERATE.equals(optionValue)) {
- this.produceDebugAttributes |= ClassFileConstants.ATTR_VARS;
- } else if (DO_NOT_GENERATE.equals(optionValue)) {
- this.produceDebugAttributes &= ~ClassFileConstants.ATTR_VARS;
- }
- }
- if ((optionValue = optionsMap.get(OPTION_LineNumberAttribute)) != null) {
- if (GENERATE.equals(optionValue)) {
- this.produceDebugAttributes |= ClassFileConstants.ATTR_LINES;
- } else if (DO_NOT_GENERATE.equals(optionValue)) {
- this.produceDebugAttributes &= ~ClassFileConstants.ATTR_LINES;
- }
- }
- if ((optionValue = optionsMap.get(OPTION_SourceFileAttribute)) != null) {
- if (GENERATE.equals(optionValue)) {
- this.produceDebugAttributes |= ClassFileConstants.ATTR_SOURCE;
- } else if (DO_NOT_GENERATE.equals(optionValue)) {
- this.produceDebugAttributes &= ~ClassFileConstants.ATTR_SOURCE;
- }
- }
- if ((optionValue = optionsMap.get(OPTION_PreserveUnusedLocal)) != null) {
- if (PRESERVE.equals(optionValue)) {
- this.preserveAllLocalVariables = true;
- } else if (OPTIMIZE_OUT.equals(optionValue)) {
- this.preserveAllLocalVariables = false;
- }
- }
- if ((optionValue = optionsMap.get(OPTION_ReportDeprecationInDeprecatedCode)) != null) {
- if (ENABLED.equals(optionValue)) {
- this.reportDeprecationInsideDeprecatedCode = true;
- } else if (DISABLED.equals(optionValue)) {
- this.reportDeprecationInsideDeprecatedCode = false;
- }
- }
- if ((optionValue = optionsMap.get(OPTION_ReportDeprecationWhenOverridingDeprecatedMethod)) != null) {
- if (ENABLED.equals(optionValue)) {
- this.reportDeprecationWhenOverridingDeprecatedMethod = true;
- } else if (DISABLED.equals(optionValue)) {
- this.reportDeprecationWhenOverridingDeprecatedMethod = false;
- }
- }
- if ((optionValue = optionsMap.get(OPTION_ReportUnusedDeclaredThrownExceptionWhenOverriding)) != null) {
- if (ENABLED.equals(optionValue)) {
- this.reportUnusedDeclaredThrownExceptionWhenOverriding = true;
- } else if (DISABLED.equals(optionValue)) {
- this.reportUnusedDeclaredThrownExceptionWhenOverriding = false;
- }
- }
- if ((optionValue = optionsMap.get(OPTION_Compliance)) != null) {
- long level = versionToJdkLevel(optionValue);
- if (level != 0) this.complianceLevel = level;
- }
- if ((optionValue = optionsMap.get(OPTION_Source)) != null) {
- long level = versionToJdkLevel(optionValue);
- if (level != 0) this.sourceLevel = level;
- }
- if ((optionValue = optionsMap.get(OPTION_TargetPlatform)) != null) {
- long level = versionToJdkLevel(optionValue);
- if (level != 0) this.targetJDK = level;
- if (this.targetJDK >= ClassFileConstants.JDK1_5) this.inlineJsrBytecode = true; // forced from 1.5 mode on
- }
- if ((optionValue = optionsMap.get(OPTION_Encoding)) != null) {
- if (optionValue instanceof String) {
- this.defaultEncoding = null;
- String stringValue = (String) optionValue;
- if (stringValue.length() > 0){
- try {
- new InputStreamReader(new ByteArrayInputStream(new byte[0]), stringValue);
- this.defaultEncoding = stringValue;
- } catch(UnsupportedEncodingException e){
- // ignore unsupported encoding
- }
- }
- }
- }
- if ((optionValue = optionsMap.get(OPTION_ReportUnusedParameterWhenImplementingAbstract)) != null) {
- if (ENABLED.equals(optionValue)) {
- this.reportUnusedParameterWhenImplementingAbstract = true;
- } else if (DISABLED.equals(optionValue)) {
- this.reportUnusedParameterWhenImplementingAbstract = false;
- }
- }
- if ((optionValue = optionsMap.get(OPTION_ReportUnusedParameterWhenOverridingConcrete)) != null) {
- if (ENABLED.equals(optionValue)) {
- this.reportUnusedParameterWhenOverridingConcrete = true;
- } else if (DISABLED.equals(optionValue)) {
- this.reportUnusedParameterWhenOverridingConcrete = false;
- }
- }
- if ((optionValue = optionsMap.get(OPTION_ReportUnusedParameterIncludeDocCommentReference)) != null) {
- if (ENABLED.equals(optionValue)) {
- this.reportUnusedParameterIncludeDocCommentReference = true;
- } else if (DISABLED.equals(optionValue)) {
- this.reportUnusedParameterIncludeDocCommentReference = false;
- }
- }
- if ((optionValue = optionsMap.get(OPTION_ReportSpecialParameterHidingField)) != null) {
- if (ENABLED.equals(optionValue)) {
- this.reportSpecialParameterHidingField = true;
- } else if (DISABLED.equals(optionValue)) {
- this.reportSpecialParameterHidingField = false;
- }
- }
- if ((optionValue = optionsMap.get(OPTION_MaxProblemPerUnit)) != null) {
- if (optionValue instanceof String) {
- String stringValue = (String) optionValue;
- try {
- int val = Integer.parseInt(stringValue);
- if (val >= 0) this.maxProblemsPerUnit = val;
- } catch(NumberFormatException e){
- // ignore ill-formatted limit
- }
- }
- }
- if ((optionValue = optionsMap.get(OPTION_TaskTags)) != null) {
- if (optionValue instanceof String) {
- String stringValue = (String) optionValue;
- if (stringValue.length() == 0) {
- this.taskTags = null;
- } else {
- this.taskTags = CharOperation.splitAndTrimOn(',', stringValue.toCharArray());
- }
- }
- }
- if ((optionValue = optionsMap.get(OPTION_TaskPriorities)) != null) {
- if (optionValue instanceof String) {
- String stringValue = (String) optionValue;
- if (stringValue.length() == 0) {
- this.taskPriorites = null;
- } else {
- this.taskPriorites = CharOperation.splitAndTrimOn(',', stringValue.toCharArray());
- }
- }
- }
- if ((optionValue = optionsMap.get(OPTION_TaskCaseSensitive)) != null) {
- if (ENABLED.equals(optionValue)) {
- this.isTaskCaseSensitive = true;
- } else if (DISABLED.equals(optionValue)) {
- this.isTaskCaseSensitive = false;
- }
- }
- if ((optionValue = optionsMap.get(OPTION_InlineJsr)) != null) {
- if (this.targetJDK < ClassFileConstants.JDK1_5) { // only optional if target < 1.5 (inlining on from 1.5 on)
- if (ENABLED.equals(optionValue)) {
- this.inlineJsrBytecode = true;
- } else if (DISABLED.equals(optionValue)) {
- this.inlineJsrBytecode = false;
- }
- }
- }
- if ((optionValue = optionsMap.get(OPTION_SuppressWarnings)) != null) {
- if (ENABLED.equals(optionValue)) {
- this.suppressWarnings = true;
- } else if (DISABLED.equals(optionValue)) {
- this.suppressWarnings = false;
- }
- }
- if ((optionValue = optionsMap.get(OPTION_FatalOptionalError)) != null) {
- if (ENABLED.equals(optionValue)) {
- this.treatOptionalErrorAsFatal = true;
- } else if (DISABLED.equals(optionValue)) {
- this.treatOptionalErrorAsFatal = false;
- }
- }
- if ((optionValue = optionsMap.get(OPTION_ReportMethodWithConstructorName)) != null) updateSeverity(MethodWithConstructorName, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportUndefinedField)) != null) updateSeverity(UndefinedField, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportDeprecation)) != null) updateSeverity(UsingDeprecatedAPI, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportHiddenCatchBlock)) != null) updateSeverity(MaskedCatchBlock, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportUnusedLocal)) != null) updateSeverity(UnusedLocalVariable, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportUnusedParameter)) != null) updateSeverity(UnusedArgument, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportUnusedPrivateMember)) != null) updateSeverity(UnusedPrivateMember, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportUnusedDeclaredThrownException)) != null) updateSeverity(UnusedDeclaredThrownException, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportWrongNumberOfArguments)) != null) updateSeverity(WrongNumberOfArguments, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportLocalVariableHiding)) != null) updateSeverity(LocalVariableHiding, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportFieldHiding)) != null) updateSeverity(FieldHiding, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportTypeParameterHiding)) != null) updateSeverity(TypeHiding, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportPossibleAccidentalBooleanAssignment)) != null) updateSeverity(AccidentalBooleanAssign, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportEmptyStatement)) != null) updateSeverity(EmptyStatement, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportNonExternalizedStringLiteral)) != null) updateSeverity(NonExternalizedString, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportAssertIdentifier)) != null) updateSeverity(AssertUsedAsAnIdentifier, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportEnumIdentifier)) != null) updateSeverity(EnumUsedAsAnIdentifier, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportNonStaticAccessToStatic)) != null) updateSeverity(NonStaticAccessToStatic, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportIndirectStaticAccess)) != null) updateSeverity(IndirectStaticAccess, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportUndocumentedEmptyBlock)) != null) updateSeverity(UndocumentedEmptyBlock, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportUnnecessaryTypeCheck)) != null) updateSeverity(UnnecessaryTypeCheck, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportUnnecessaryElse)) != null) updateSeverity(UnnecessaryElse, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportFinallyBlockNotCompletingNormally)) != null) updateSeverity(FinallyBlockNotCompleting, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportUnqualifiedFieldAccess)) != null) updateSeverity(UnqualifiedFieldAccess, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportNoEffectAssignment)) != null) updateSeverity(NoEffectAssignment, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportUncheckedTypeOperation)) != null) updateSeverity(UncheckedTypeOperation, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportRawTypeReference)) != null) updateSeverity(RawTypeReference, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportFinalParameterBound)) != null) updateSeverity(FinalParameterBound, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportForbiddenReference)) != null) updateSeverity(ForbiddenReference, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportDiscouragedReference)) != null) updateSeverity(DiscouragedReference, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportNullReference)) != null) updateSeverity(NullReference, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportPotentialNullReference)) != null) updateSeverity(PotentialNullReference, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportDuplicateLocalVariables)) != null) updateSeverity(DuplicateLocalVariables, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportRedundantNullCheck)) != null) updateSeverity(RedundantNullCheck, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportUninitializedLocalVariable)) != null) updateSeverity(UninitializedLocalVariable, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportUninitializedGlobalVariable)) != null) updateSeverity(UninitializedGlobalVariable, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportUnusedLabel)) != null) updateSeverity(UnusedLabel, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportParameterAssignment)) != null) updateSeverity(ParameterAssignment, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportFallthroughCase)) != null) updateSeverity(FallthroughCase, optionValue);
- if ((optionValue = optionsMap.get(OPTION_ReportOverridingMethodWithoutSuperInvocation)) != null) updateSeverity(OverridingMethodWithoutSuperInvocation, optionValue);
-
- /* START -------------------------------- Bug 203292 Type/Method/Filed resolution error configuration --------------------- */
- if ((optionValue = optionsMap.get(OPTION_Unresolved_Type)) != null) updateSeverity(UnresolvedType, optionValue);
- if ((optionValue = optionsMap.get(OPTION_Unresolved_Field)) != null) updateSeverity(UnresolvedField, optionValue);
- if ((optionValue = optionsMap.get(OPTION_Unresolved_Method)) != null) updateSeverity(UnresolvedMethod, optionValue);
-
- /* END -------------------------------- Bug 203292 Type/Method/Filed resolution error configuration --------------------- */
-
-
- /* START -------------------------------- Bug 197884 Loosly defined var (for statement) and optional semi-colon --------------------- */
- if ((optionValue = optionsMap.get(OPTION_OPTIONAL_SEMICOLON)) != null)
- updateSeverity(OptionalSemicolon, optionValue);
- if ((optionValue = optionsMap.get(OPTION_LOOSE_VAR_DECL)) != null)
- updateSeverity(LooseVariableDecl, optionValue);
- /* END -------------------------------- Bug 197884 Loosly defined var (for statement) and optional semi-colon --------------------- */
-
-
- // Javadoc options
- if ((optionValue = optionsMap.get(OPTION_DocCommentSupport)) != null) {
- if (ENABLED.equals(optionValue)) {
- this.docCommentSupport = true;
- } else if (DISABLED.equals(optionValue)) {
- this.docCommentSupport = false;
- }
- }
- if ((optionValue = optionsMap.get(OPTION_ReportInvalidJavadoc)) != null) {
- updateSeverity(InvalidJavadoc, optionValue);
- }
- if ( (optionValue = optionsMap.get(OPTION_ReportInvalidJavadocTagsVisibility)) != null) {
- if (PUBLIC.equals(optionValue)) {
- this.reportInvalidJavadocTagsVisibility = ClassFileConstants.AccPublic;
- } else if (PROTECTED.equals(optionValue)) {
- this.reportInvalidJavadocTagsVisibility = ClassFileConstants.AccProtected;
- } else if (DEFAULT.equals(optionValue)) {
- this.reportInvalidJavadocTagsVisibility = ClassFileConstants.AccDefault;
- } else if (PRIVATE.equals(optionValue)) {
- this.reportInvalidJavadocTagsVisibility = ClassFileConstants.AccPrivate;
- }
- }
- if ((optionValue = optionsMap.get(OPTION_ReportInvalidJavadocTags)) != null) {
- if (ENABLED.equals(optionValue)) {
- this.reportInvalidJavadocTags = true;
- } else if (DISABLED.equals(optionValue)) {
- this.reportInvalidJavadocTags = false;
- }
- }
- if ((optionValue = optionsMap.get(OPTION_ReportInvalidJavadocTagsDeprecatedRef)) != null) {
- if (ENABLED.equals(optionValue)) {
- this.reportInvalidJavadocTagsDeprecatedRef = true;
- } else if (DISABLED.equals(optionValue)) {
- this.reportInvalidJavadocTagsDeprecatedRef = false;
- }
- }
- if ((optionValue = optionsMap.get(OPTION_ReportInvalidJavadocTagsNotVisibleRef)) != null) {
- if (ENABLED.equals(optionValue)) {
- this.reportInvalidJavadocTagsNotVisibleRef = true;
- } else if (DISABLED.equals(optionValue)) {
- this.reportInvalidJavadocTagsNotVisibleRef = false;
- }
- }
- if ((optionValue = optionsMap.get(OPTION_ReportMissingJavadocTags)) != null) {
- updateSeverity(MissingJavadocTags, optionValue);
- }
- if ((optionValue = optionsMap.get(OPTION_ReportMissingJavadocTagsVisibility)) != null) {
- if (PUBLIC.equals(optionValue)) {
- this.reportMissingJavadocTagsVisibility = ClassFileConstants.AccPublic;
- } else if (PROTECTED.equals(optionValue)) {
- this.reportMissingJavadocTagsVisibility = ClassFileConstants.AccProtected;
- } else if (DEFAULT.equals(optionValue)) {
- this.reportMissingJavadocTagsVisibility = ClassFileConstants.AccDefault;
- } else if (PRIVATE.equals(optionValue)) {
- this.reportMissingJavadocTagsVisibility = ClassFileConstants.AccPrivate;
- }
- }
- if ((optionValue = optionsMap.get(OPTION_ReportMissingJavadocTagsOverriding)) != null) {
- if (ENABLED.equals(optionValue)) {
- this.reportMissingJavadocTagsOverriding = true;
- } else if (DISABLED.equals(optionValue)) {
- this.reportMissingJavadocTagsOverriding = false;
- }
- }
- if ((optionValue = optionsMap.get(OPTION_ReportMissingJavadocComments)) != null) {
- updateSeverity(MissingJavadocComments, optionValue);
- }
- if ((optionValue = optionsMap.get(OPTION_ReportMissingJavadocCommentsVisibility)) != null) {
- if (PUBLIC.equals(optionValue)) {
- this.reportMissingJavadocCommentsVisibility = ClassFileConstants.AccPublic;
- } else if (PROTECTED.equals(optionValue)) {
- this.reportMissingJavadocCommentsVisibility = ClassFileConstants.AccProtected;
- } else if (DEFAULT.equals(optionValue)) {
- this.reportMissingJavadocCommentsVisibility = ClassFileConstants.AccDefault;
- } else if (PRIVATE.equals(optionValue)) {
- this.reportMissingJavadocCommentsVisibility = ClassFileConstants.AccPrivate;
- }
- }
- if ((optionValue = optionsMap.get(OPTION_ReportMissingJavadocCommentsOverriding)) != null) {
- if (ENABLED.equals(optionValue)) {
- this.reportMissingJavadocCommentsOverriding = true;
- } else if (DISABLED.equals(optionValue)) {
- this.reportMissingJavadocCommentsOverriding = false;
- }
- }
- if ((optionValue = optionsMap.get(OPTION_GenerateClassFiles)) != null) {
- if (ENABLED.equals(optionValue)) {
- this.generateClassFiles = true;
- } else if (DISABLED.equals(optionValue)) {
- this.generateClassFiles = false;
- }
- }
- if ((optionValue = optionsMap.get(OPTION_Process_Annotations)) != null) {
- if (ENABLED.equals(optionValue)) {
- this.processAnnotations = true;
- this.storeAnnotations = true; // annotation processing requires annotation to be stored
- this.docCommentSupport = true; // annotation processing requires javadoc processing
- } else if (DISABLED.equals(optionValue)) {
- this.processAnnotations = false;
- this.storeAnnotations = false;
- }
- }
- inferOptions.set(optionsMap);
-
- }
-
- public String toString() {
-
- StringBuffer buf = new StringBuffer("CompilerOptions:"); //$NON-NLS-1$
- buf.append("\n\t- local variables debug attributes: ").append((this.produceDebugAttributes & ClassFileConstants.ATTR_VARS) != 0 ? "ON" : " OFF"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- buf.append("\n\t- line number debug attributes: ").append((this.produceDebugAttributes & ClassFileConstants.ATTR_LINES) != 0 ? "ON" : " OFF"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- buf.append("\n\t- source debug attributes: ").append((this.produceDebugAttributes & ClassFileConstants.ATTR_SOURCE) != 0 ? "ON" : " OFF"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- buf.append("\n\t- preserve all local variables: ").append(this.preserveAllLocalVariables ? "ON" : " OFF"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- buf.append("\n\t- method with constructor name: ").append(getSeverityString(MethodWithConstructorName)); //$NON-NLS-1$
- buf.append("\n\t- undefined field: ").append(getSeverityString(UndefinedField)); //$NON-NLS-1$
- buf.append("\n\t- deprecation: ").append(getSeverityString(UsingDeprecatedAPI)); //$NON-NLS-1$
- buf.append("\n\t- masked catch block: ").append(getSeverityString(MaskedCatchBlock)); //$NON-NLS-1$
- buf.append("\n\t- unused local variable: ").append(getSeverityString(UnusedLocalVariable)); //$NON-NLS-1$
- buf.append("\n\t- unused parameter: ").append(getSeverityString(UnusedArgument)); //$NON-NLS-1$
- buf.append("\n\t- synthetic access emulation: ").append(getSeverityString(AccessEmulation)); //$NON-NLS-1$
- buf.append("\n\t- assignment with no effect: ").append(getSeverityString(NoEffectAssignment)); //$NON-NLS-1$
- buf.append("\n\t- non externalized string: ").append(getSeverityString(NonExternalizedString)); //$NON-NLS-1$
- buf.append("\n\t- static access receiver: ").append(getSeverityString(NonStaticAccessToStatic)); //$NON-NLS-1$
- buf.append("\n\t- indirect static access: ").append(getSeverityString(IndirectStaticAccess)); //$NON-NLS-1$
- buf.append("\n\t- unused private member: ").append(getSeverityString(UnusedPrivateMember)); //$NON-NLS-1$
- buf.append("\n\t- local variable hiding another variable: ").append(getSeverityString(LocalVariableHiding)); //$NON-NLS-1$
- buf.append("\n\t- field hiding another variable: ").append(getSeverityString(FieldHiding)); //$NON-NLS-1$
- buf.append("\n\t- type hiding another type: ").append(getSeverityString(TypeHiding)); //$NON-NLS-1$
- buf.append("\n\t- possible accidental boolean assignment: ").append(getSeverityString(AccidentalBooleanAssign)); //$NON-NLS-1$
- buf.append("\n\t- superfluous semicolon: ").append(getSeverityString(EmptyStatement)); //$NON-NLS-1$
- buf.append("\n\t- uncommented empty block: ").append(getSeverityString(UndocumentedEmptyBlock)); //$NON-NLS-1$
- buf.append("\n\t- unnecessary type check: ").append(getSeverityString(UnnecessaryTypeCheck)); //$NON-NLS-1$
- buf.append("\n\t- javadoc comment support: ").append(this.docCommentSupport ? "ON" : " OFF"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- buf.append("\n\t\t+ invalid javadoc: ").append(getSeverityString(InvalidJavadoc)); //$NON-NLS-1$
- buf.append("\n\t\t+ report invalid javadoc tags: ").append(this.reportInvalidJavadocTags ? ENABLED : DISABLED); //$NON-NLS-1$
- buf.append("\n\t\t\t* deprecated references: ").append(this.reportInvalidJavadocTagsDeprecatedRef ? ENABLED : DISABLED); //$NON-NLS-1$
- buf.append("\n\t\t\t* not visible references: ").append(this.reportInvalidJavadocTagsNotVisibleRef ? ENABLED : DISABLED); //$NON-NLS-1$
- buf.append("\n\t\t+ visibility level to report invalid javadoc tags: ").append(getVisibilityString(this.reportInvalidJavadocTagsVisibility)); //$NON-NLS-1$
- buf.append("\n\t\t+ missing javadoc tags: ").append(getSeverityString(MissingJavadocTags)); //$NON-NLS-1$
- buf.append("\n\t\t+ visibility level to report missing javadoc tags: ").append(getVisibilityString(this.reportMissingJavadocTagsVisibility)); //$NON-NLS-1$
- buf.append("\n\t\t+ report missing javadoc tags in overriding methods: ").append(this.reportMissingJavadocTagsOverriding ? ENABLED : DISABLED); //$NON-NLS-1$
- buf.append("\n\t\t+ missing javadoc comments: ").append(getSeverityString(MissingJavadocComments)); //$NON-NLS-1$
- buf.append("\n\t\t+ visibility level to report missing javadoc comments: ").append(getVisibilityString(this.reportMissingJavadocCommentsVisibility)); //$NON-NLS-1$
- buf.append("\n\t\t+ report missing javadoc comments in overriding methods: ").append(this.reportMissingJavadocCommentsOverriding ? ENABLED : DISABLED); //$NON-NLS-1$
- buf.append("\n\t- finally block not completing normally: ").append(getSeverityString(FinallyBlockNotCompleting)); //$NON-NLS-1$
- buf.append("\n\t- unused declared thrown exception: ").append(getSeverityString(UnusedDeclaredThrownException)); //$NON-NLS-1$
- buf.append("\n\t- unused declared thrown exception when overriding: ").append(this.reportUnusedDeclaredThrownExceptionWhenOverriding ? ENABLED : DISABLED); //$NON-NLS-1$
- buf.append("\n\t- unnecessary else: ").append(getSeverityString(UnnecessaryElse)); //$NON-NLS-1$
- buf.append("\n\t- JDK compliance level: "+ versionFromJdkLevel(this.complianceLevel)); //$NON-NLS-1$
- buf.append("\n\t- JDK source level: "+ versionFromJdkLevel(this.sourceLevel)); //$NON-NLS-1$
- buf.append("\n\t- JDK target level: "+ versionFromJdkLevel(this.targetJDK)); //$NON-NLS-1$
- buf.append("\n\t- verbose : ").append(this.verbose ? "ON" : "OFF"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- buf.append("\n\t- produce reference info : ").append(this.produceReferenceInfo ? "ON" : "OFF"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- buf.append("\n\t- parse literal expressions as constants : ").append(this.parseLiteralExpressionsAsConstants ? "ON" : "OFF"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- buf.append("\n\t- encoding : ").append(this.defaultEncoding == null ? "<default>" : this.defaultEncoding); //$NON-NLS-1$ //$NON-NLS-2$
- buf.append("\n\t- task tags: ").append(this.taskTags == null ? Util.EMPTY_STRING : new String(CharOperation.concatWith(this.taskTags,','))); //$NON-NLS-1$
- buf.append("\n\t- task priorities : ").append(this.taskPriorites == null ? Util.EMPTY_STRING : new String(CharOperation.concatWith(this.taskPriorites,','))); //$NON-NLS-1$
- buf.append("\n\t- report deprecation inside deprecated code : ").append(this.reportDeprecationInsideDeprecatedCode ? ENABLED : DISABLED); //$NON-NLS-1$
- buf.append("\n\t- report deprecation when overriding deprecated method : ").append(this.reportDeprecationWhenOverridingDeprecatedMethod ? ENABLED : DISABLED); //$NON-NLS-1$
- buf.append("\n\t- report unused parameter when implementing abstract method : ").append(this.reportUnusedParameterWhenImplementingAbstract ? ENABLED : DISABLED); //$NON-NLS-1$
- buf.append("\n\t- report unused parameter when overriding concrete method : ").append(this.reportUnusedParameterWhenOverridingConcrete ? ENABLED : DISABLED); //$NON-NLS-1$
- buf.append("\n\t- report unused parameter include doc comment reference : ").append(this.reportUnusedParameterIncludeDocCommentReference ? ENABLED : DISABLED); //$NON-NLS-1$
- buf.append("\n\t- report constructor/setter parameter hiding existing field : ").append(this.reportSpecialParameterHidingField ? ENABLED : DISABLED); //$NON-NLS-1$
- buf.append("\n\t- inline JSR bytecode : ").append(this.inlineJsrBytecode ? ENABLED : DISABLED); //$NON-NLS-1$
- buf.append("\n\t- unsafe type operation: ").append(getSeverityString(UncheckedTypeOperation)); //$NON-NLS-1$
- buf.append("\n\t- unsafe raw type: ").append(getSeverityString(RawTypeReference)); //$NON-NLS-1$
- buf.append("\n\t- final bound for type parameter: ").append(getSeverityString(FinalParameterBound)); //$NON-NLS-1$
- buf.append("\n\t- forbidden reference to type with access restriction: ").append(getSeverityString(ForbiddenReference)); //$NON-NLS-1$
- buf.append("\n\t- discouraged reference to type with access restriction: ").append(getSeverityString(DiscouragedReference)); //$NON-NLS-1$
- buf.append("\n\t- null reference: ").append(getSeverityString(NullReference)); //$NON-NLS-1$
- buf.append("\n\t- potential null reference: ").append(getSeverityString(PotentialNullReference)); //$NON-NLS-1$
- buf.append("\n\t- duplicate local variables: ").append(getSeverityString(DuplicateLocalVariables)); //$NON-NLS-1%
- buf.append("\n\t- redundant null check: ").append(getSeverityString(RedundantNullCheck)); //$NON-NLS-1$
- buf.append("\n\t- uninitialized local variable: ").append(getSeverityString(UninitializedLocalVariable)); //$NON-NLS-1$
- buf.append("\n\t- uninitialized global variable: ").append(getSeverityString(UninitializedGlobalVariable)); //$NON-NLS-1$
- buf.append("\n\t- suppress warnings: ").append(this.suppressWarnings ? ENABLED : DISABLED); //$NON-NLS-1$
- buf.append("\n\t- unused label: ").append(getSeverityString(UnusedLabel)); //$NON-NLS-1$
- buf.append("\n\t- treat optional error as fatal: ").append(this.treatOptionalErrorAsFatal ? ENABLED : DISABLED); //$NON-NLS-1$
- buf.append("\n\t- parameter assignment: ").append(getSeverityString(ParameterAssignment)); //$NON-NLS-1$
- buf.append("\n\t- generate class files: ").append(this.generateClassFiles ? ENABLED : DISABLED); //$NON-NLS-1$
- buf.append("\n\t- process annotations: ").append(this.processAnnotations ? ENABLED : DISABLED); //$NON-NLS-1$
- return buf.toString();
- }
-
- void updateSeverity(long irritant, Object severityString) {
- if (ERROR.equals(severityString)) {
- this.errorThreshold |= irritant;
- this.warningThreshold &= ~irritant;
- } else if (WARNING.equals(severityString)) {
- this.errorThreshold &= ~irritant;
- this.warningThreshold |= irritant;
- } else if (IGNORE.equals(severityString)) {
- this.errorThreshold &= ~irritant;
- this.warningThreshold &= ~irritant;
- }
- }
- public static long versionToJdkLevel(Object versionID) {
- if (versionID instanceof String) {
- String version = (String) versionID;
- // verification is optimized for all versions with same length and same "1." prefix
- if (version.length() == 3 && version.charAt(0) == '1' && version.charAt(1) == '.') {
- switch (version.charAt(2)) {
- case '1':
- return ClassFileConstants.JDK1_1;
- case '2':
- return ClassFileConstants.JDK1_2;
- case '3':
- return ClassFileConstants.JDK1_3;
- case '4':
- return ClassFileConstants.JDK1_4;
- case '5':
- return ClassFileConstants.JDK1_5;
- case '6':
- return ClassFileConstants.JDK1_6;
- case '7':
- return ClassFileConstants.JDK1_7;
- default:
- return 0; // unknown
- }
- }
- if (VERSION_JSR14.equals(versionID)) {
- return ClassFileConstants.JDK1_4;
- }
- }
- return 0; // unknown
- }
-
- public static String versionFromJdkLevel(long jdkLevel) {
- switch ((int)(jdkLevel>>16)) {
- case ClassFileConstants.MAJOR_VERSION_1_1 :
- if (jdkLevel == ClassFileConstants.JDK1_1)
- return VERSION_1_1;
- break;
- case ClassFileConstants.MAJOR_VERSION_1_2 :
- if (jdkLevel == ClassFileConstants.JDK1_2)
- return VERSION_1_2;
- break;
- case ClassFileConstants.MAJOR_VERSION_1_3 :
- if (jdkLevel == ClassFileConstants.JDK1_3)
- return VERSION_1_3;
- break;
- case ClassFileConstants.MAJOR_VERSION_1_4 :
- if (jdkLevel == ClassFileConstants.JDK1_4)
- return VERSION_1_4;
- break;
- case ClassFileConstants.MAJOR_VERSION_1_5 :
- if (jdkLevel == ClassFileConstants.JDK1_5)
- return VERSION_1_5;
- break;
- case ClassFileConstants.MAJOR_VERSION_1_6 :
- if (jdkLevel == ClassFileConstants.JDK1_6)
- return VERSION_1_6;
- break;
- case ClassFileConstants.MAJOR_VERSION_1_7 :
- if (jdkLevel == ClassFileConstants.JDK1_7)
- return VERSION_1_7;
- break;
- }
- return Util.EMPTY_STRING; // unknown version
- }
-
- /**
- * Return all warning option names for use as keys in compiler options maps.
- * @return all warning option names
- * TODO (maxime) revise for ensuring completeness
- */
- public static String[] warningOptionNames() {
- String[] result = {
- OPTION_ReportAssertIdentifier,
- OPTION_ReportDeprecation,
- OPTION_ReportDiscouragedReference,
- OPTION_ReportEmptyStatement,
- OPTION_ReportEnumIdentifier,
- OPTION_ReportFallthroughCase,
- OPTION_ReportFieldHiding,
- OPTION_ReportFinalParameterBound,
- OPTION_ReportFinallyBlockNotCompletingNormally,
- OPTION_ReportForbiddenReference,
- OPTION_ReportHiddenCatchBlock,
- OPTION_ReportIndirectStaticAccess,
- OPTION_ReportInvalidJavadoc,
- OPTION_ReportLocalVariableHiding,
- OPTION_ReportMethodWithConstructorName,
- OPTION_ReportMissingJavadocComments,
- OPTION_ReportMissingJavadocTags,
- OPTION_ReportNoEffectAssignment,
- OPTION_ReportNonExternalizedStringLiteral,
- OPTION_ReportNonStaticAccessToStatic,
- OPTION_ReportNullReference,
- OPTION_ReportPotentialNullReference,
- OPTION_ReportDuplicateLocalVariables,
- OPTION_ReportRedundantNullCheck,
- OPTION_ReportUninitializedLocalVariable,
- OPTION_ReportUninitializedGlobalVariable,
- OPTION_ReportUndefinedField,
- OPTION_ReportParameterAssignment,
- OPTION_ReportPossibleAccidentalBooleanAssignment,
- OPTION_ReportWrongNumberOfArguments,
- OPTION_ReportTypeParameterHiding,
- OPTION_ReportUncheckedTypeOperation,
- OPTION_ReportUndocumentedEmptyBlock,
- OPTION_ReportUnnecessaryElse,
- OPTION_ReportUnnecessaryTypeCheck,
- OPTION_ReportUnqualifiedFieldAccess,
- OPTION_ReportUnusedDeclaredThrownException,
- OPTION_ReportUnusedLocal,
- OPTION_ReportUnusedParameter,
- OPTION_ReportUnusedPrivateMember,
- OPTION_ReportOverridingMethodWithoutSuperInvocation
- };
- return result;
- }
-
- public static String warningTokenFromIrritant(long irritant) {
- // keep in sync with warningTokens and warningTokenToIrritant
- int irritantInt = (int) irritant;
- if (irritantInt == irritant) {
- switch (irritantInt) {
- case (int) (InvalidJavadoc | UsingDeprecatedAPI) :
- case (int) UsingDeprecatedAPI :
- return "deprecation"; //$NON-NLS-1$
- case (int) FinallyBlockNotCompleting :
- return "finally"; //$NON-NLS-1$
- case (int) FieldHiding :
- case (int) LocalVariableHiding :
- case (int) MaskedCatchBlock :
- return "hiding"; //$NON-NLS-1$
- case (int) NonExternalizedString :
- return "nls"; //$NON-NLS-1$
- case (int) UnnecessaryTypeCheck :
- return "cast"; //$NON-NLS-1$
- case (int) UnusedLocalVariable :
- case (int) UnusedArgument :
- case (int) UnusedPrivateMember:
- case (int) UnusedDeclaredThrownException:
- return "unused"; //$NON-NLS-1$
- case (int) IndirectStaticAccess :
- case (int) NonStaticAccessToStatic :
- return "static-access"; //$NON-NLS-1$
- case (int) AccessEmulation :
- return "synthetic-access"; //$NON-NLS-1$
- case (int) UnqualifiedFieldAccess :
- return "unqualified-field-access"; //$NON-NLS-1$
- case (int) UncheckedTypeOperation :
- return "unchecked"; //$NON-NLS-1$
- }
- } else {
- irritantInt = (int)(irritant >>> 32);
- switch (irritantInt) {
- case (int)(TypeHiding >>> 32) :
- return "hiding"; //$NON-NLS-1$
- case (int)(RawTypeReference >>> 32):
- return "unchecked"; //$NON-NLS-1$
- case (int) (UnusedLabel >>> 32):
- return "unused"; //$NON-NLS-1$
- case (int) (DiscouragedReference >>> 32) :
- case (int) (ForbiddenReference >>> 32) :
- return "restriction"; //$NON-NLS-1$
- case (int) (NullReference >>> 32) :
- case (int) (PotentialNullReference >>> 32) :
- case (int) (RedundantNullCheck >>> 32) :
- return "null"; //$NON-NLS-1$
- case (int) (FallthroughCase >>> 32) :
- return "fallthrough"; //$NON-NLS-1$
- case (int) (OverridingMethodWithoutSuperInvocation >>> 32) :
- return "super"; //$NON-NLS-1$
- case (int) (UninitializedLocalVariable >>> 32) :
- return "uninitializedLocalVariable";
- case (int) (UninitializedGlobalVariable >>> 32) :
- return "uninitializedGlobalVariable";
- }
- }
- return null;
- }
- // 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$
- "finally", //$NON-NLS-1$
- "hiding", //$NON-NLS-1$
- "nls", //$NON-NLS-1$
- "null", //$NON-NLS-1$
- "restriction", //$NON-NLS-1$
- "static-access", //$NON-NLS-1$
- "super", //$NON-NLS-1$
- "synthetic-access", //$NON-NLS-1$
- "unchecked", //$NON-NLS-1$
- "unqualified-field-access", //$NON-NLS-1$
- "unused", //$NON-NLS-1$
- };
- public static long warningTokenToIrritant(String warningToken) {
- // keep in sync with warningTokens and warningTokenFromIrritant
- if (warningToken == null || warningToken.length() == 0) return 0;
- switch (warningToken.charAt(0)) {
- case 'a' :
- if ("all".equals(warningToken)) //$NON-NLS-1$
- return 0xFFFFFFFFFFFFFFFFl; // suppress all warnings
- break;
- case 'c' :
- if ("cast".equals(warningToken)) //$NON-NLS-1$
- return UnnecessaryTypeCheck;
- break;
- case 'd' :
- if ("deprecation".equals(warningToken)) //$NON-NLS-1$
- return UsingDeprecatedAPI;
- break;
- case 'f' :
- if ("fallthrough".equals(warningToken)) //$NON-NLS-1$
- return FallthroughCase;
- if ("finally".equals(warningToken)) //$NON-NLS-1$
- return FinallyBlockNotCompleting;
- break;
- case 'h' :
- if ("hiding".equals(warningToken)) //$NON-NLS-1$
- return FieldHiding | LocalVariableHiding | MaskedCatchBlock | TypeHiding;
- break;
- case 'n' :
- if ("nls".equals(warningToken)) //$NON-NLS-1$
- return NonExternalizedString;
- if ("null".equals(warningToken)) //$NON-NLS-1$
- return NullReference | PotentialNullReference | RedundantNullCheck;
- break;
- case 'r' :
- if ("restriction".equals(warningToken)) //$NON-NLS-1$
- return DiscouragedReference | ForbiddenReference;
- break;
- case 's' :
- if ("static-access".equals(warningToken)) //$NON-NLS-1$
- return IndirectStaticAccess | NonStaticAccessToStatic;
- if ("synthetic-access".equals(warningToken)) //$NON-NLS-1$
- return AccessEmulation;
- if ("super".equals(warningToken)) { //$NON-NLS-1$
- return OverridingMethodWithoutSuperInvocation;
- }
- break;
- case 'u' :
- if ("unused".equals(warningToken)) //$NON-NLS-1$
- return UnusedLocalVariable | UnusedArgument | UnusedPrivateMember | UnusedDeclaredThrownException | UnusedLabel;
- if ("unchecked".equals(warningToken)) //$NON-NLS-1$
- return UncheckedTypeOperation | RawTypeReference;
- if ("unqualified-field-access".equals(warningToken)) //$NON-NLS-1$
- return UnqualifiedFieldAccess;
- if("uninitializedLocalVariable".equals(warningToken)) //$NON-NLS-1$
- return UninitializedLocalVariable;
- if("uninitializedGlobalVariable".equals(warningToken)) //$NON-NLS-1$
- return UninitializedGlobalVariable;
- break;
- }
- return 0;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/Constant.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/Constant.java
deleted file mode 100644
index 9a14e699..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/Constant.java
+++ /dev/null
@@ -1,1336 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.impl;
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeIds;
-import org.eclipse.wst.jsdt.internal.compiler.problem.ShouldNotImplement;
-import org.eclipse.wst.jsdt.internal.compiler.util.Messages;
-
-public abstract class Constant implements TypeIds, OperatorIds {
-
- public static final Constant NotAConstant = DoubleConstant.fromValue(Double.NaN);
-
- public boolean booleanValue() {
-
- return false;
-// throw new ShouldNotImplement(Messages.bind(Messages.constant_cannotCastedInto, new String[] { typeName(), "boolean" })); //$NON-NLS-1$
- }
-
- public final Constant castTo(int conversionToTargetType){
- //the cast is an int of the form
- // (castId<<4)+typeId (in order to follow the
- //user written style (cast)expression ....
-
- if (this == NotAConstant) return NotAConstant;
- switch(conversionToTargetType){
- case T_undefined : return this;
- // TARGET TYPE <- FROM TYPE
- // case (T_undefined<<4)+T_undefined : return NotAConstant;
- // case (T_undefined<<4)+T_byte : return NotAConstant;
- // case (T_undefined<<4)+T_long : return NotAConstant;
- // case (T_undefined<<4)+T_short : return NotAConstant;
- // case (T_undefined<<4)+T_void : return NotAConstant;
- // case (T_undefined<<4)+T_String : return NotAConstant;
- // case (T_undefined<<4)+T_Object : return NotAConstant;
- // case (T_undefined<<4)+T_double : return NotAConstant;
- // case (T_undefined<<4)+T_float : return NotAConstant;
- // case (T_undefined<<4)+T_boolean : return NotAConstant;
- // case (T_undefined<<4)+T_char : return NotAConstant;
- // case (T_undefined<<4)+T_int : return NotAConstant;
-
- // case (T_long<<4)+T_undefined : return NotAConstant;
- case (T_long<<4)+T_long : return this;
- case (T_long<<4)+T_short : return LongConstant.fromValue(this.shortValue());
- // case (T_long<<4)+T_void : return NotAConstant;
- // case (T_long<<4)+T_String : return NotAConstant;
- // case (T_long<<4)+T_Object : return NotAConstant;
- case (T_long<<4)+T_double : return LongConstant.fromValue((long)this.doubleValue());
- case (T_long<<4)+T_float : return LongConstant.fromValue((long)this.floatValue());
- // case (T_long<<4)+T_boolean : return NotAConstant;
- case (T_long<<4)+T_char : return LongConstant.fromValue(this.charValue());
- case (T_long<<4)+T_int : return LongConstant.fromValue(this.intValue());
-
- // case (T_short<<4)+T_undefined : return NotAConstant;
- case (T_short<<4)+T_long : return ShortConstant.fromValue((short)this.longValue());
- case (T_short<<4)+T_short : return this;
- // case (T_short<<4)+T_void : return NotAConstant;
- // case (T_short<<4)+T_String : return NotAConstant;
- // case (T_short<<4)+T_Object : return NotAConstant;
- case (T_short<<4)+T_double : return ShortConstant.fromValue((short)this.doubleValue());
- case (T_short<<4)+T_float : return ShortConstant.fromValue((short)this.floatValue());
- // case (T_short<<4)+T_boolean : return NotAConstant;
- case (T_short<<4)+T_char : return ShortConstant.fromValue((short)this.charValue());
- case (T_short<<4)+T_int : return ShortConstant.fromValue((short)this.intValue());
-
- // case (T_void<<4)+T_undefined : return NotAConstant;
- // case (T_void<<4)+T_byte : return NotAConstant;
- // case (T_void<<4)+T_long : return NotAConstant;
- // case (T_void<<4)+T_short : return NotAConstant;
- // case (T_void<<4)+T_void : return NotAConstant;
- // case (T_void<<4)+T_String : return NotAConstant;
- // case (T_void<<4)+T_Object : return NotAConstant;
- // case (T_void<<4)+T_double : return NotAConstant;
- // case (T_void<<4)+T_float : return NotAConstant;
- // case (T_void<<4)+T_boolean : return NotAConstant;
- // case (T_void<<4)+T_char : return NotAConstant;
- // case (T_void<<4)+T_int : return NotAConstant;
-
- // case (T_String<<4)+T_undefined : return NotAConstant;
- // case (T_String<<4)+T_byte : return NotAConstant;
- // case (T_String<<4)+T_long : return NotAConstant;
- // case (T_String<<4)+T_short : return NotAConstant;
- // case (T_String<<4)+T_void : return NotAConstant;
- case (T_JavaLangString<<4)+T_JavaLangString : return this;
- // case (T_String<<4)+T_Object : return NotAConstant;
- // case (T_String<<4)+T_double : return NotAConstant;
- // case (T_String<<4)+T_float : return NotAConstant;
- // case (T_String<<4)+T_boolean : return NotAConstant;
- // case (T_String<<4)+T_char : return NotAConstant;
- // case (T_String<<4)+T_int : return NotAConstant;
-
- // case (T_Object<<4)+T_undefined : return NotAConstant;
- // case (T_Object<<4)+T_byte : return NotAConstant;
- // case (T_Object<<4)+T_long : return NotAConstant;
- // case (T_Object<<4)+T_short : return NotAConstant;
- // case (T_Object<<4)+T_void : return NotAConstant;
- // case (T_Object<<4)+T_String : return NotAConstant;
- // case (T_Object<<4)+T_Object : return NotAConstant;
- // case (T_Object<<4)+T_double : return NotAConstant;
- // case (T_Object<<4)+T_float : return NotAConstant;
- // case (T_Object<<4)+T_boolean : return NotAConstant;
- // case (T_Object<<4)+T_char : return NotAConstant;
- // case (T_Object<<4)+T_int : return NotAConstant;
-
- // case (T_double<<4)+T_undefined : return NotAConstant;
- case (T_double<<4)+T_long : return DoubleConstant.fromValue(this.longValue());
- case (T_double<<4)+T_short : return DoubleConstant.fromValue(this.shortValue());
- // case (T_double<<4)+T_void : return NotAConstant;
- // case (T_double<<4)+T_String : return NotAConstant;
- // case (T_double<<4)+T_Object : return NotAConstant;
- case (T_double<<4)+T_double : return this;
- case (T_double<<4)+T_float : return DoubleConstant.fromValue(this.floatValue());
- // case (T_double<<4)+T_boolean : return NotAConstant;
- case (T_double<<4)+T_char : return DoubleConstant.fromValue(this.charValue());
- case (T_double<<4)+T_int : return DoubleConstant.fromValue(this.intValue());
-
- // case (T_float<<4)+T_undefined : return NotAConstant;
- case (T_float<<4)+T_long : return FloatConstant.fromValue(this.longValue());
- case (T_float<<4)+T_short : return FloatConstant.fromValue(this.shortValue());
- // case (T_float<<4)+T_void : return NotAConstant;
- // case (T_float<<4)+T_String : return NotAConstant;
- // case (T_float<<4)+T_Object : return NotAConstant;
- case (T_float<<4)+T_double : return FloatConstant.fromValue((float)this.doubleValue());
- case (T_float<<4)+T_float : return this;
- // case (T_float<<4)+T_boolean : return NotAConstant;
- case (T_float<<4)+T_char : return FloatConstant.fromValue(this.charValue());
- case (T_float<<4)+T_int : return FloatConstant.fromValue(this.intValue());
-
- // case (T_boolean<<4)+T_undefined : return NotAConstant;
- // case (T_boolean<<4)+T_byte : return NotAConstant;
- // case (T_boolean<<4)+T_long : return NotAConstant;
- // case (T_boolean<<4)+T_short : return NotAConstant;
- // case (T_boolean<<4)+T_void : return NotAConstant;
- // case (T_boolean<<4)+T_String : return NotAConstant;
- // case (T_boolean<<4)+T_Object : return NotAConstant;
- // case (T_boolean<<4)+T_double : return NotAConstant;
- // case (T_boolean<<4)+T_float : return NotAConstant;
- case (T_boolean<<4)+T_boolean : return this;
- // case (T_boolean<<4)+T_char : return NotAConstant;
- // case (T_boolean<<4)+T_int : return NotAConstant;
-
- // case (T_char<<4)+T_undefined : return NotAConstant;
- case (T_char<<4)+T_long : return CharConstant.fromValue((char)this.longValue());
- case (T_char<<4)+T_short : return CharConstant.fromValue((char)this.shortValue());
- // case (T_char<<4)+T_void : return NotAConstant;
- // case (T_char<<4)+T_String : return NotAConstant;
- // case (T_char<<4)+T_Object : return NotAConstant;
- case (T_char<<4)+T_double : return CharConstant.fromValue((char)this.doubleValue());
- case (T_char<<4)+T_float : return CharConstant.fromValue((char)this.floatValue());
- // case (T_char<<4)+T_boolean : return NotAConstant;
- case (T_char<<4)+T_char : return this;
- case (T_char<<4)+T_int : return CharConstant.fromValue((char)this.intValue());
-
- // case (T_int<<4)+T_undefined : return NotAConstant;
- case (T_int<<4)+T_long : return IntConstant.fromValue((int) this.longValue());
- case (T_int<<4)+T_short : return IntConstant.fromValue(this.shortValue());
- // case (T_int<<4)+T_void : return NotAConstant;
- // case (T_int<<4)+T_String : return NotAConstant;
- // case (T_int<<4)+T_Object : return NotAConstant;
- case (T_int<<4)+T_double : return IntConstant.fromValue((int) this.doubleValue());
- case (T_int<<4)+T_float : return IntConstant.fromValue((int) this.floatValue());
- // case (T_int<<4)+T_boolean : return NotAConstant;
- case (T_int<<4)+T_char : return IntConstant.fromValue(this.charValue());
- case (T_int<<4)+T_int : return this;
-
- }
-
- return NotAConstant;
- }
-
- public char charValue() {
-
- throw new ShouldNotImplement(Messages.bind(Messages.constant_cannotCastedInto, new String[] { typeName(), "char" })); //$NON-NLS-1$
- }
-
- public static final Constant computeConstantOperation(Constant cst, int id, int operator) {
-
- switch (operator) {
- case NOT :
- if(cst == null)
- return NotAConstant;
- return BooleanConstant.fromValue(!cst.booleanValue());
- case PLUS :
- return computeConstantOperationPLUS(IntConstant.fromValue(0),T_int,cst,id);
- case MINUS : //the two special -9223372036854775808L and -2147483648 are inlined at parseTime
- switch (id){
- case T_float : float f;
- if ( (f= cst.floatValue()) == 0.0f)
- { //positive and negative 0....
- if (Float.floatToIntBits(f) == 0)
- return FloatConstant.fromValue(-0.0f);
- else
- return FloatConstant.fromValue(0.0f);}
- break; //default case
- case T_double : double d;
- if ( (d= cst.doubleValue()) == 0.0d)
- { //positive and negative 0....
- if (Double.doubleToLongBits(d) == 0)
- return DoubleConstant.fromValue(-0.0d);
- else
- return DoubleConstant.fromValue(0.0d);}
- break; //default case
- }
- return computeConstantOperationMINUS(IntConstant.fromValue(0),T_int,cst,id);
- case TWIDDLE:
- switch (id){
- case T_char : return IntConstant.fromValue(~ cst.charValue());
- case T_short: return IntConstant.fromValue(~ cst.shortValue());
- case T_int: return IntConstant.fromValue(~ cst.intValue());
- case T_long: return LongConstant.fromValue(~ cst.longValue());
- default : return NotAConstant;
- }
- default : return NotAConstant;
- }
- }
-
- public static final Constant computeConstantOperation(Constant left, int leftId, int operator, Constant right, int rightId) {
-
- switch (operator) {
- case AND : return computeConstantOperationAND (left,leftId,right,rightId);
- case AND_AND : return computeConstantOperationAND_AND (left,leftId,right,rightId);
- case DIVIDE : return computeConstantOperationDIVIDE (left,leftId,right,rightId);
- case GREATER : return computeConstantOperationGREATER (left,leftId,right,rightId);
- case GREATER_EQUAL : return computeConstantOperationGREATER_EQUAL(left,leftId,right,rightId);
- case LEFT_SHIFT : return computeConstantOperationLEFT_SHIFT (left,leftId,right,rightId);
- case LESS : return computeConstantOperationLESS (left,leftId,right,rightId);
- case LESS_EQUAL : return computeConstantOperationLESS_EQUAL (left,leftId,right,rightId);
- case MINUS : return computeConstantOperationMINUS (left,leftId,right,rightId);
- case MULTIPLY : return computeConstantOperationMULTIPLY (left,leftId,right,rightId);
- case OR : return computeConstantOperationOR (left,leftId,right,rightId);
- case OR_OR : return computeConstantOperationOR_OR (left,leftId,right,rightId);
- case PLUS : return computeConstantOperationPLUS (left,leftId,right,rightId);
- case REMAINDER : return computeConstantOperationREMAINDER (left,leftId,right,rightId);
- case RIGHT_SHIFT: return computeConstantOperationRIGHT_SHIFT(left,leftId,right,rightId);
- case UNSIGNED_RIGHT_SHIFT: return computeConstantOperationUNSIGNED_RIGHT_SHIFT(left,leftId,right,rightId);
- case XOR : return computeConstantOperationXOR (left,leftId,right,rightId);
-
- default : return NotAConstant;
- }
- }
-
- public static final Constant computeConstantOperationAND(Constant left, int leftId, Constant right, int rightId) {
-
- switch (leftId){
- case T_boolean : return BooleanConstant.fromValue(left.booleanValue() & right.booleanValue());
- case T_char :
- switch (rightId){
- case T_char : return IntConstant.fromValue(left.charValue() & right.charValue());
- case T_short: return IntConstant.fromValue(left.charValue() & right.shortValue());
- case T_int: return IntConstant.fromValue(left.charValue() & right.intValue());
- case T_long: return LongConstant.fromValue(left.charValue() & right.longValue());
- }
- break;
- case T_short :
- switch (rightId){
- case T_char : return IntConstant.fromValue(left.shortValue() & right.charValue());
- case T_short: return IntConstant.fromValue(left.shortValue() & right.shortValue());
- case T_int: return IntConstant.fromValue(left.shortValue() & right.intValue());
- case T_long: return LongConstant.fromValue(left.shortValue() & right.longValue());
- }
- break;
- case T_int :
- switch (rightId){
- case T_char : return IntConstant.fromValue(left.intValue() & right.charValue());
- case T_short: return IntConstant.fromValue(left.intValue() & right.shortValue());
- case T_int: return IntConstant.fromValue(left.intValue() & right.intValue());
- case T_long: return LongConstant.fromValue(left.intValue() & right.longValue());
- }
- break;
- case T_long :
- switch (rightId){
- case T_char : return LongConstant.fromValue(left.longValue() & right.charValue());
- case T_short: return LongConstant.fromValue(left.longValue() & right.shortValue());
- case T_int: return LongConstant.fromValue(left.longValue() & right.intValue());
- case T_long: return LongConstant.fromValue(left.longValue() & right.longValue());
- }
- }
-
- return NotAConstant;
- }
-
- public static final Constant computeConstantOperationAND_AND(Constant left, int leftId, Constant right, int rightId) {
-
- return BooleanConstant.fromValue(left.booleanValue() && right.booleanValue());
- }
-
- public static final Constant computeConstantOperationDIVIDE(Constant left, int leftId, Constant right, int rightId) {
- // division by zero must be handled outside this method (error reporting)
-
- switch (leftId){
- case T_char :
- switch (rightId){
- case T_char : return IntConstant.fromValue(left.charValue() / right.charValue());
- case T_float: return FloatConstant.fromValue(left.charValue() / right.floatValue());
- case T_double: return DoubleConstant.fromValue(left.charValue() / right.doubleValue());
- case T_short: return IntConstant.fromValue(left.charValue() / right.shortValue());
- case T_int: return IntConstant.fromValue(left.charValue() / right.intValue());
- case T_long: return LongConstant.fromValue(left.charValue() / right.longValue());
- }
- break;
- case T_float :
- switch (rightId){
- case T_char : return FloatConstant.fromValue(left.floatValue() / right.charValue());
- case T_float: return FloatConstant.fromValue(left.floatValue() / right.floatValue());
- case T_double: return DoubleConstant.fromValue(left.floatValue() / right.doubleValue());
- case T_short: return FloatConstant.fromValue(left.floatValue() / right.shortValue());
- case T_int: return FloatConstant.fromValue(left.floatValue() / right.intValue());
- case T_long: return FloatConstant.fromValue(left.floatValue() / right.longValue());
- }
- break;
- case T_double :
- switch (rightId){
- case T_char : return DoubleConstant.fromValue(left.doubleValue() / right.charValue());
- case T_float: return DoubleConstant.fromValue(left.doubleValue() / right.floatValue());
- case T_double: return DoubleConstant.fromValue(left.doubleValue() / right.doubleValue());
- case T_short: return DoubleConstant.fromValue(left.doubleValue() / right.shortValue());
- case T_int: return DoubleConstant.fromValue(left.doubleValue() / right.intValue());
- case T_long: return DoubleConstant.fromValue(left.doubleValue() / right.longValue());
- }
- break;
- case T_short :
- switch (rightId){
- case T_char : return IntConstant.fromValue(left.shortValue() / right.charValue());
- case T_float: return FloatConstant.fromValue(left.shortValue() / right.floatValue());
- case T_double: return DoubleConstant.fromValue(left.shortValue() / right.doubleValue());
- case T_short: return IntConstant.fromValue(left.shortValue() / right.shortValue());
- case T_int: return IntConstant.fromValue(left.shortValue() / right.intValue());
- case T_long: return LongConstant.fromValue(left.shortValue() / right.longValue());
- }
- break;
- case T_int :
- switch (rightId){
- case T_char : return IntConstant.fromValue(left.intValue() / right.charValue());
- case T_float: return FloatConstant.fromValue(left.intValue() / right.floatValue());
- case T_double: return DoubleConstant.fromValue(left.intValue() / right.doubleValue());
- case T_short: return IntConstant.fromValue(left.intValue() / right.shortValue());
- case T_int: return IntConstant.fromValue(left.intValue() / right.intValue());
- case T_long: return LongConstant.fromValue(left.intValue() / right.longValue());
- }
- break;
- case T_long :
- switch (rightId){
- case T_char : return LongConstant.fromValue(left.longValue() / right.charValue());
- case T_float: return FloatConstant.fromValue(left.longValue() / right.floatValue());
- case T_double: return DoubleConstant.fromValue(left.longValue() / right.doubleValue());
- case T_short: return LongConstant.fromValue(left.longValue() / right.shortValue());
- case T_int: return LongConstant.fromValue(left.longValue() / right.intValue());
- case T_long: return LongConstant.fromValue(left.longValue() / right.longValue());
- }
-
- }
-
- return NotAConstant;
- }
-
- public static final Constant computeConstantOperationEQUAL_EQUAL(Constant left, int leftId, Constant right, int rightId) {
-
- switch (leftId){
- case T_boolean :
- if (rightId == T_boolean) {
- return BooleanConstant.fromValue(left.booleanValue() == right.booleanValue());
- }
- break;
- case T_char :
- switch (rightId){
- case T_char : return BooleanConstant.fromValue(left.charValue() == right.charValue());
- case T_float: return BooleanConstant.fromValue(left.charValue() == right.floatValue());
- case T_double: return BooleanConstant.fromValue(left.charValue() == right.doubleValue());
- case T_short: return BooleanConstant.fromValue(left.charValue() == right.shortValue());
- case T_int: return BooleanConstant.fromValue(left.charValue() == right.intValue());
- case T_long: return BooleanConstant.fromValue(left.charValue() == right.longValue());}
- break;
- case T_float :
- switch (rightId){
- case T_char : return BooleanConstant.fromValue(left.floatValue() == right.charValue());
- case T_float: return BooleanConstant.fromValue(left.floatValue() == right.floatValue());
- case T_double: return BooleanConstant.fromValue(left.floatValue() == right.doubleValue());
- case T_short: return BooleanConstant.fromValue(left.floatValue() == right.shortValue());
- case T_int: return BooleanConstant.fromValue(left.floatValue() == right.intValue());
- case T_long: return BooleanConstant.fromValue(left.floatValue() == right.longValue());
- }
- break;
- case T_double :
- switch (rightId){
- case T_char : return BooleanConstant.fromValue(left.doubleValue() == right.charValue());
- case T_float: return BooleanConstant.fromValue(left.doubleValue() == right.floatValue());
- case T_double: return BooleanConstant.fromValue(left.doubleValue() == right.doubleValue());
- case T_short: return BooleanConstant.fromValue(left.doubleValue() == right.shortValue());
- case T_int: return BooleanConstant.fromValue(left.doubleValue() == right.intValue());
- case T_long: return BooleanConstant.fromValue(left.doubleValue() == right.longValue());
- }
- break;
- case T_short :
- switch (rightId){
- case T_char : return BooleanConstant.fromValue(left.shortValue() == right.charValue());
- case T_float: return BooleanConstant.fromValue(left.shortValue() == right.floatValue());
- case T_double: return BooleanConstant.fromValue(left.shortValue() == right.doubleValue());
- case T_short: return BooleanConstant.fromValue(left.shortValue() == right.shortValue());
- case T_int: return BooleanConstant.fromValue(left.shortValue() == right.intValue());
- case T_long: return BooleanConstant.fromValue(left.shortValue() == right.longValue());
- }
- break;
- case T_int :
- switch (rightId){
- case T_char : return BooleanConstant.fromValue(left.intValue() == right.charValue());
- case T_float: return BooleanConstant.fromValue(left.intValue() == right.floatValue());
- case T_double: return BooleanConstant.fromValue(left.intValue() == right.doubleValue());
- case T_short: return BooleanConstant.fromValue(left.intValue() == right.shortValue());
- case T_int: return BooleanConstant.fromValue(left.intValue() == right.intValue());
- case T_long: return BooleanConstant.fromValue(left.intValue() == right.longValue());
- }
- break;
- case T_long :
- switch (rightId){
- case T_char : return BooleanConstant.fromValue(left.longValue() == right.charValue());
- case T_float: return BooleanConstant.fromValue(left.longValue() == right.floatValue());
- case T_double: return BooleanConstant.fromValue(left.longValue() == right.doubleValue());
- case T_short: return BooleanConstant.fromValue(left.longValue() == right.shortValue());
- case T_int: return BooleanConstant.fromValue(left.longValue() == right.intValue());
- case T_long: return BooleanConstant.fromValue(left.longValue() == right.longValue());
- }
- break;
- case T_JavaLangString :
- if (rightId == T_JavaLangString) {
- //String are interned in th compiler==>thus if two string constant
- //get to be compared, it is an equal on the vale which is done
- return BooleanConstant.fromValue(((StringConstant)left).hasSameValue(right));
- }
- break;
- case T_null :
- if (rightId == T_JavaLangString) {
- return BooleanConstant.fromValue(false);
- } else {
- if (rightId == T_null) {
- return BooleanConstant.fromValue(true);
- }
- }
- }
-
- return BooleanConstant.fromValue(false);
- }
-
- public static final Constant computeConstantOperationGREATER(Constant left, int leftId, Constant right, int rightId) {
-
- switch (leftId){
- case T_char :
- switch (rightId){
- case T_char : return BooleanConstant.fromValue(left.charValue() > right.charValue());
- case T_float: return BooleanConstant.fromValue(left.charValue() > right.floatValue());
- case T_double: return BooleanConstant.fromValue(left.charValue() > right.doubleValue());
- case T_short: return BooleanConstant.fromValue(left.charValue() > right.shortValue());
- case T_int: return BooleanConstant.fromValue(left.charValue() > right.intValue());
- case T_long: return BooleanConstant.fromValue(left.charValue() > right.longValue());
- }
- break;
- case T_float :
- switch (rightId){
- case T_char : return BooleanConstant.fromValue(left.floatValue() > right.charValue());
- case T_float: return BooleanConstant.fromValue(left.floatValue() > right.floatValue());
- case T_double: return BooleanConstant.fromValue(left.floatValue() > right.doubleValue());
- case T_short: return BooleanConstant.fromValue(left.floatValue() > right.shortValue());
- case T_int: return BooleanConstant.fromValue(left.floatValue() > right.intValue());
- case T_long: return BooleanConstant.fromValue(left.floatValue() > right.longValue());
- }
- break;
- case T_double :
- switch (rightId){
- case T_char : return BooleanConstant.fromValue(left.doubleValue() > right.charValue());
- case T_float: return BooleanConstant.fromValue(left.doubleValue() > right.floatValue());
- case T_double: return BooleanConstant.fromValue(left.doubleValue() > right.doubleValue());
- case T_short: return BooleanConstant.fromValue(left.doubleValue() > right.shortValue());
- case T_int: return BooleanConstant.fromValue(left.doubleValue() > right.intValue());
- case T_long: return BooleanConstant.fromValue(left.doubleValue() > right.longValue());
- }
- break;
- case T_short :
- switch (rightId){
- case T_char : return BooleanConstant.fromValue(left.shortValue() > right.charValue());
- case T_float: return BooleanConstant.fromValue(left.shortValue() > right.floatValue());
- case T_double: return BooleanConstant.fromValue(left.shortValue() > right.doubleValue());
- case T_short: return BooleanConstant.fromValue(left.shortValue() > right.shortValue());
- case T_int: return BooleanConstant.fromValue(left.shortValue() > right.intValue());
- case T_long: return BooleanConstant.fromValue(left.shortValue() > right.longValue());
- }
- break;
- case T_int :
- switch (rightId){
- case T_char : return BooleanConstant.fromValue(left.intValue() > right.charValue());
- case T_float: return BooleanConstant.fromValue(left.intValue() > right.floatValue());
- case T_double: return BooleanConstant.fromValue(left.intValue() > right.doubleValue());
- case T_short: return BooleanConstant.fromValue(left.intValue() > right.shortValue());
- case T_int: return BooleanConstant.fromValue(left.intValue() > right.intValue());
- case T_long: return BooleanConstant.fromValue(left.intValue() > right.longValue());
- }
- break;
- case T_long :
- switch (rightId){
- case T_char : return BooleanConstant.fromValue(left.longValue() > right.charValue());
- case T_float: return BooleanConstant.fromValue(left.longValue() > right.floatValue());
- case T_double: return BooleanConstant.fromValue(left.longValue() > right.doubleValue());
- case T_short: return BooleanConstant.fromValue(left.longValue() > right.shortValue());
- case T_int: return BooleanConstant.fromValue(left.longValue() > right.intValue());
- case T_long: return BooleanConstant.fromValue(left.longValue() > right.longValue());
- }
-
- }
-
- return NotAConstant;
- }
-
- public static final Constant computeConstantOperationGREATER_EQUAL(Constant left, int leftId, Constant right, int rightId) {
-
- switch (leftId){
- case T_char :
- switch (rightId){
- case T_char : return BooleanConstant.fromValue(left.charValue() >= right.charValue());
- case T_float: return BooleanConstant.fromValue(left.charValue() >= right.floatValue());
- case T_double: return BooleanConstant.fromValue(left.charValue() >= right.doubleValue());
- case T_short: return BooleanConstant.fromValue(left.charValue() >= right.shortValue());
- case T_int: return BooleanConstant.fromValue(left.charValue() >= right.intValue());
- case T_long: return BooleanConstant.fromValue(left.charValue() >= right.longValue());
- }
- break;
- case T_float :
- switch (rightId){
- case T_char : return BooleanConstant.fromValue(left.floatValue() >= right.charValue());
- case T_float: return BooleanConstant.fromValue(left.floatValue() >= right.floatValue());
- case T_double: return BooleanConstant.fromValue(left.floatValue() >= right.doubleValue());
- case T_short: return BooleanConstant.fromValue(left.floatValue() >= right.shortValue());
- case T_int: return BooleanConstant.fromValue(left.floatValue() >= right.intValue());
- case T_long: return BooleanConstant.fromValue(left.floatValue() >= right.longValue());
- }
- break;
- case T_double :
- switch (rightId){
- case T_char : return BooleanConstant.fromValue(left.doubleValue() >= right.charValue());
- case T_float: return BooleanConstant.fromValue(left.doubleValue() >= right.floatValue());
- case T_double: return BooleanConstant.fromValue(left.doubleValue() >= right.doubleValue());
- case T_short: return BooleanConstant.fromValue(left.doubleValue() >= right.shortValue());
- case T_int: return BooleanConstant.fromValue(left.doubleValue() >= right.intValue());
- case T_long: return BooleanConstant.fromValue(left.doubleValue() >= right.longValue());
- }
- break;
- case T_short :
- switch (rightId){
- case T_char : return BooleanConstant.fromValue(left.shortValue() >= right.charValue());
- case T_float: return BooleanConstant.fromValue(left.shortValue() >= right.floatValue());
- case T_double: return BooleanConstant.fromValue(left.shortValue() >= right.doubleValue());
- case T_short: return BooleanConstant.fromValue(left.shortValue() >= right.shortValue());
- case T_int: return BooleanConstant.fromValue(left.shortValue() >= right.intValue());
- case T_long: return BooleanConstant.fromValue(left.shortValue() >= right.longValue());
- }
- break;
- case T_int :
- switch (rightId){
- case T_char : return BooleanConstant.fromValue(left.intValue() >= right.charValue());
- case T_float: return BooleanConstant.fromValue(left.intValue() >= right.floatValue());
- case T_double: return BooleanConstant.fromValue(left.intValue() >= right.doubleValue());
- case T_short: return BooleanConstant.fromValue(left.intValue() >= right.shortValue());
- case T_int: return BooleanConstant.fromValue(left.intValue() >= right.intValue());
- case T_long: return BooleanConstant.fromValue(left.intValue() >= right.longValue());
- }
- break;
- case T_long :
- switch (rightId){
- case T_char : return BooleanConstant.fromValue(left.longValue() >= right.charValue());
- case T_float: return BooleanConstant.fromValue(left.longValue() >= right.floatValue());
- case T_double: return BooleanConstant.fromValue(left.longValue() >= right.doubleValue());
- case T_short: return BooleanConstant.fromValue(left.longValue() >= right.shortValue());
- case T_int: return BooleanConstant.fromValue(left.longValue() >= right.intValue());
- case T_long: return BooleanConstant.fromValue(left.longValue() >= right.longValue());
- }
-
- }
-
- return NotAConstant;
- }
-
- public static final Constant computeConstantOperationLEFT_SHIFT(Constant left, int leftId, Constant right, int rightId) {
-
- switch (leftId){
- case T_char :
- switch (rightId){
- case T_char : return IntConstant.fromValue(left.charValue() << right.charValue());
- case T_short: return IntConstant.fromValue(left.charValue() << right.shortValue());
- case T_int: return IntConstant.fromValue(left.charValue() << right.intValue());
- case T_long: return IntConstant.fromValue(left.charValue() << right.longValue());
- }
- break;
- case T_short :
- switch (rightId){
- case T_char : return IntConstant.fromValue(left.shortValue() << right.charValue());
- case T_short: return IntConstant.fromValue(left.shortValue() << right.shortValue());
- case T_int: return IntConstant.fromValue(left.shortValue() << right.intValue());
- case T_long: return IntConstant.fromValue(left.shortValue() << right.longValue());
- }
- break;
- case T_int :
- switch (rightId){
- case T_char : return IntConstant.fromValue(left.intValue() << right.charValue());
- case T_short: return IntConstant.fromValue(left.intValue() << right.shortValue());
- case T_int: return IntConstant.fromValue(left.intValue() << right.intValue());
- case T_long: return IntConstant.fromValue(left.intValue() << right.longValue());
- }
- break;
- case T_long :
- switch (rightId){
- case T_char : return LongConstant.fromValue(left.longValue() << right.charValue());
- case T_short: return LongConstant.fromValue(left.longValue() << right.shortValue());
- case T_int: return LongConstant.fromValue(left.longValue() << right.intValue());
- case T_long: return LongConstant.fromValue(left.longValue() << right.longValue());
- }
-
- }
-
- return NotAConstant;
- }
-
- public static final Constant computeConstantOperationLESS(Constant left, int leftId, Constant right, int rightId) {
-
- switch (leftId){
- case T_char :
- switch (rightId){
- case T_char : return BooleanConstant.fromValue(left.charValue() < right.charValue());
- case T_float: return BooleanConstant.fromValue(left.charValue() < right.floatValue());
- case T_double: return BooleanConstant.fromValue(left.charValue() < right.doubleValue());
- case T_short: return BooleanConstant.fromValue(left.charValue() < right.shortValue());
- case T_int: return BooleanConstant.fromValue(left.charValue() < right.intValue());
- case T_long: return BooleanConstant.fromValue(left.charValue() < right.longValue());
- }
- break;
- case T_float :
- switch (rightId){
- case T_char : return BooleanConstant.fromValue(left.floatValue() < right.charValue());
- case T_float: return BooleanConstant.fromValue(left.floatValue() < right.floatValue());
- case T_double: return BooleanConstant.fromValue(left.floatValue() < right.doubleValue());
- case T_short: return BooleanConstant.fromValue(left.floatValue() < right.shortValue());
- case T_int: return BooleanConstant.fromValue(left.floatValue() < right.intValue());
- case T_long: return BooleanConstant.fromValue(left.floatValue() < right.longValue());
- }
- break;
- case T_double :
- switch (rightId){
- case T_char : return BooleanConstant.fromValue(left.doubleValue() < right.charValue());
- case T_float: return BooleanConstant.fromValue(left.doubleValue() < right.floatValue());
- case T_double: return BooleanConstant.fromValue(left.doubleValue() < right.doubleValue());
- case T_short: return BooleanConstant.fromValue(left.doubleValue() < right.shortValue());
- case T_int: return BooleanConstant.fromValue(left.doubleValue() < right.intValue());
- case T_long: return BooleanConstant.fromValue(left.doubleValue() < right.longValue());
- }
- break;
- case T_short :
- switch (rightId){
- case T_char : return BooleanConstant.fromValue(left.shortValue() < right.charValue());
- case T_float: return BooleanConstant.fromValue(left.shortValue() < right.floatValue());
- case T_double: return BooleanConstant.fromValue(left.shortValue() < right.doubleValue());
- case T_short: return BooleanConstant.fromValue(left.shortValue() < right.shortValue());
- case T_int: return BooleanConstant.fromValue(left.shortValue() < right.intValue());
- case T_long: return BooleanConstant.fromValue(left.shortValue() < right.longValue());
- }
- break;
- case T_int :
- switch (rightId){
- case T_char : return BooleanConstant.fromValue(left.intValue() < right.charValue());
- case T_float: return BooleanConstant.fromValue(left.intValue() < right.floatValue());
- case T_double: return BooleanConstant.fromValue(left.intValue() < right.doubleValue());
- case T_short: return BooleanConstant.fromValue(left.intValue() < right.shortValue());
- case T_int: return BooleanConstant.fromValue(left.intValue() < right.intValue());
- case T_long: return BooleanConstant.fromValue(left.intValue() < right.longValue());
- }
- break;
- case T_long :
- switch (rightId){
- case T_char : return BooleanConstant.fromValue(left.longValue() < right.charValue());
- case T_float: return BooleanConstant.fromValue(left.longValue() < right.floatValue());
- case T_double: return BooleanConstant.fromValue(left.longValue() < right.doubleValue());
- case T_short: return BooleanConstant.fromValue(left.longValue() < right.shortValue());
- case T_int: return BooleanConstant.fromValue(left.longValue() < right.intValue());
- case T_long: return BooleanConstant.fromValue(left.longValue() < right.longValue());
- }
-
- }
-
- return NotAConstant;
- }
-
- public static final Constant computeConstantOperationLESS_EQUAL(Constant left, int leftId, Constant right, int rightId) {
-
- switch (leftId){
- case T_char :
- switch (rightId){
- case T_char : return BooleanConstant.fromValue(left.charValue() <= right.charValue());
- case T_float: return BooleanConstant.fromValue(left.charValue() <= right.floatValue());
- case T_double: return BooleanConstant.fromValue(left.charValue() <= right.doubleValue());
- case T_short: return BooleanConstant.fromValue(left.charValue() <= right.shortValue());
- case T_int: return BooleanConstant.fromValue(left.charValue() <= right.intValue());
- case T_long: return BooleanConstant.fromValue(left.charValue() <= right.longValue());
- }
- break;
- case T_float :
- switch (rightId){
- case T_char : return BooleanConstant.fromValue(left.floatValue() <= right.charValue());
- case T_float: return BooleanConstant.fromValue(left.floatValue() <= right.floatValue());
- case T_double: return BooleanConstant.fromValue(left.floatValue() <= right.doubleValue());
- case T_short: return BooleanConstant.fromValue(left.floatValue() <= right.shortValue());
- case T_int: return BooleanConstant.fromValue(left.floatValue() <= right.intValue());
- case T_long: return BooleanConstant.fromValue(left.floatValue() <= right.longValue());
- }
- break;
- case T_double :
- switch (rightId){
- case T_char : return BooleanConstant.fromValue(left.doubleValue() <= right.charValue());
- case T_float: return BooleanConstant.fromValue(left.doubleValue() <= right.floatValue());
- case T_double: return BooleanConstant.fromValue(left.doubleValue() <= right.doubleValue());
- case T_short: return BooleanConstant.fromValue(left.doubleValue() <= right.shortValue());
- case T_int: return BooleanConstant.fromValue(left.doubleValue() <= right.intValue());
- case T_long: return BooleanConstant.fromValue(left.doubleValue() <= right.longValue());
- }
- break;
- case T_short :
- switch (rightId){
- case T_char : return BooleanConstant.fromValue(left.shortValue() <= right.charValue());
- case T_float: return BooleanConstant.fromValue(left.shortValue() <= right.floatValue());
- case T_double: return BooleanConstant.fromValue(left.shortValue() <= right.doubleValue());
- case T_short: return BooleanConstant.fromValue(left.shortValue() <= right.shortValue());
- case T_int: return BooleanConstant.fromValue(left.shortValue() <= right.intValue());
- case T_long: return BooleanConstant.fromValue(left.shortValue() <= right.longValue());
- }
- break;
- case T_int :
- switch (rightId){
- case T_char : return BooleanConstant.fromValue(left.intValue() <= right.charValue());
- case T_float: return BooleanConstant.fromValue(left.intValue() <= right.floatValue());
- case T_double: return BooleanConstant.fromValue(left.intValue() <= right.doubleValue());
- case T_short: return BooleanConstant.fromValue(left.intValue() <= right.shortValue());
- case T_int: return BooleanConstant.fromValue(left.intValue() <= right.intValue());
- case T_long: return BooleanConstant.fromValue(left.intValue() <= right.longValue());
- }
- break;
- case T_long :
- switch (rightId){
- case T_char : return BooleanConstant.fromValue(left.longValue() <= right.charValue());
- case T_float: return BooleanConstant.fromValue(left.longValue() <= right.floatValue());
- case T_double: return BooleanConstant.fromValue(left.longValue() <= right.doubleValue());
- case T_short: return BooleanConstant.fromValue(left.longValue() <= right.shortValue());
- case T_int: return BooleanConstant.fromValue(left.longValue() <= right.intValue());
- case T_long: return BooleanConstant.fromValue(left.longValue() <= right.longValue());
- }
- }
-
- return NotAConstant;
- }
-
- public static final Constant computeConstantOperationMINUS(Constant left, int leftId, Constant right, int rightId) {
-
- switch (leftId){
- case T_char :
- switch (rightId){
- case T_char : return IntConstant.fromValue(left.charValue() - right.charValue());
- case T_float: return FloatConstant.fromValue(left.charValue() - right.floatValue());
- case T_double: return DoubleConstant.fromValue(left.charValue() - right.doubleValue());
- case T_short: return IntConstant.fromValue(left.charValue() - right.shortValue());
- case T_int: return IntConstant.fromValue(left.charValue() - right.intValue());
- case T_long: return LongConstant.fromValue(left.charValue() - right.longValue());
- }
- break;
- case T_float :
- switch (rightId){
- case T_char : return FloatConstant.fromValue(left.floatValue() - right.charValue());
- case T_float: return FloatConstant.fromValue(left.floatValue() - right.floatValue());
- case T_double: return DoubleConstant.fromValue(left.floatValue() - right.doubleValue());
- case T_short: return FloatConstant.fromValue(left.floatValue() - right.shortValue());
- case T_int: return FloatConstant.fromValue(left.floatValue() - right.intValue());
- case T_long: return FloatConstant.fromValue(left.floatValue() - right.longValue());
- }
- break;
- case T_double :
- switch (rightId){
- case T_char : return DoubleConstant.fromValue(left.doubleValue() - right.charValue());
- case T_float: return DoubleConstant.fromValue(left.doubleValue() - right.floatValue());
- case T_double: return DoubleConstant.fromValue(left.doubleValue() - right.doubleValue());
- case T_short: return DoubleConstant.fromValue(left.doubleValue() - right.shortValue());
- case T_int: return DoubleConstant.fromValue(left.doubleValue() - right.intValue());
- case T_long: return DoubleConstant.fromValue(left.doubleValue() - right.longValue());
- }
- break;
- case T_short :
- switch (rightId){
- case T_char : return IntConstant.fromValue(left.shortValue() - right.charValue());
- case T_float: return FloatConstant.fromValue(left.shortValue() - right.floatValue());
- case T_double: return DoubleConstant.fromValue(left.shortValue() - right.doubleValue());
- case T_short: return IntConstant.fromValue(left.shortValue() - right.shortValue());
- case T_int: return IntConstant.fromValue(left.shortValue() - right.intValue());
- case T_long: return LongConstant.fromValue(left.shortValue() - right.longValue());
- }
- break;
- case T_int :
- switch (rightId){
- case T_char : return IntConstant.fromValue(left.intValue() - right.charValue());
- case T_float: return FloatConstant.fromValue(left.intValue() - right.floatValue());
- case T_double: return DoubleConstant.fromValue(left.intValue() - right.doubleValue());
- case T_short: return IntConstant.fromValue(left.intValue() - right.shortValue());
- case T_int: return IntConstant.fromValue(left.intValue() - right.intValue());
- case T_long: return LongConstant.fromValue(left.intValue() - right.longValue());
- }
- break;
- case T_long :
- switch (rightId){
- case T_char : return LongConstant.fromValue(left.longValue() - right.charValue());
- case T_float: return FloatConstant.fromValue(left.longValue() - right.floatValue());
- case T_double: return DoubleConstant.fromValue(left.longValue() - right.doubleValue());
- case T_short: return LongConstant.fromValue(left.longValue() - right.shortValue());
- case T_int: return LongConstant.fromValue(left.longValue() - right.intValue());
- case T_long: return LongConstant.fromValue(left.longValue() - right.longValue());
- }
-
- }
-
- return NotAConstant;
- }
-
- public static final Constant computeConstantOperationMULTIPLY(Constant left, int leftId, Constant right, int rightId) {
-
- switch (leftId){
- case T_char :
- switch (rightId){
- case T_char : return IntConstant.fromValue(left.charValue() * right.charValue());
- case T_float: return FloatConstant.fromValue(left.charValue() * right.floatValue());
- case T_double: return DoubleConstant.fromValue(left.charValue() * right.doubleValue());
- case T_short: return IntConstant.fromValue(left.charValue() * right.shortValue());
- case T_int: return IntConstant.fromValue(left.charValue() * right.intValue());
- case T_long: return LongConstant.fromValue(left.charValue() * right.longValue());
- }
- break;
- case T_float :
- switch (rightId){
- case T_char : return FloatConstant.fromValue(left.floatValue() * right.charValue());
- case T_float: return FloatConstant.fromValue(left.floatValue() * right.floatValue());
- case T_double: return DoubleConstant.fromValue(left.floatValue() * right.doubleValue());
- case T_short: return FloatConstant.fromValue(left.floatValue() * right.shortValue());
- case T_int: return FloatConstant.fromValue(left.floatValue() * right.intValue());
- case T_long: return FloatConstant.fromValue(left.floatValue() * right.longValue());
- }
- break;
- case T_double :
- switch (rightId){
- case T_char : return DoubleConstant.fromValue(left.doubleValue() * right.charValue());
- case T_float: return DoubleConstant.fromValue(left.doubleValue() * right.floatValue());
- case T_double: return DoubleConstant.fromValue(left.doubleValue() * right.doubleValue());
- case T_short: return DoubleConstant.fromValue(left.doubleValue() * right.shortValue());
- case T_int: return DoubleConstant.fromValue(left.doubleValue() * right.intValue());
- case T_long: return DoubleConstant.fromValue(left.doubleValue() * right.longValue());
- }
- break;
- case T_short :
- switch (rightId){
- case T_char : return IntConstant.fromValue(left.shortValue() * right.charValue());
- case T_float: return FloatConstant.fromValue(left.shortValue() * right.floatValue());
- case T_double: return DoubleConstant.fromValue(left.shortValue() * right.doubleValue());
- case T_short: return IntConstant.fromValue(left.shortValue() * right.shortValue());
- case T_int: return IntConstant.fromValue(left.shortValue() * right.intValue());
- case T_long: return LongConstant.fromValue(left.shortValue() * right.longValue());
- }
- break;
- case T_int :
- switch (rightId){
- case T_char : return IntConstant.fromValue(left.intValue() * right.charValue());
- case T_float: return FloatConstant.fromValue(left.intValue() * right.floatValue());
- case T_double: return DoubleConstant.fromValue(left.intValue() * right.doubleValue());
- case T_short: return IntConstant.fromValue(left.intValue() * right.shortValue());
- case T_int: return IntConstant.fromValue(left.intValue() * right.intValue());
- case T_long: return LongConstant.fromValue(left.intValue() * right.longValue());
- }
- break;
- case T_long :
- switch (rightId){
- case T_char : return LongConstant.fromValue(left.longValue() * right.charValue());
- case T_float: return FloatConstant.fromValue(left.longValue() * right.floatValue());
- case T_double: return DoubleConstant.fromValue(left.longValue() * right.doubleValue());
- case T_short: return LongConstant.fromValue(left.longValue() * right.shortValue());
- case T_int: return LongConstant.fromValue(left.longValue() * right.intValue());
- case T_long: return LongConstant.fromValue(left.longValue() * right.longValue());
- }
- }
-
- return NotAConstant;
- }
-
- public static final Constant computeConstantOperationOR(Constant left, int leftId, Constant right, int rightId) {
-
- switch (leftId){
- case T_boolean : return BooleanConstant.fromValue(left.booleanValue() | right.booleanValue());
- case T_char :
- switch (rightId){
- case T_char : return IntConstant.fromValue(left.charValue() | right.charValue());
- case T_short: return IntConstant.fromValue(left.charValue() | right.shortValue());
- case T_int: return IntConstant.fromValue(left.charValue() | right.intValue());
- case T_long: return LongConstant.fromValue(left.charValue() | right.longValue());
- }
- break;
- case T_short :
- switch (rightId){
- case T_char : return IntConstant.fromValue(left.shortValue() | right.charValue());
- case T_short: return IntConstant.fromValue(left.shortValue() | right.shortValue());
- case T_int: return IntConstant.fromValue(left.shortValue() | right.intValue());
- case T_long: return LongConstant.fromValue(left.shortValue() | right.longValue());
- }
- break;
- case T_int :
- switch (rightId){
- case T_char : return IntConstant.fromValue(left.intValue() | right.charValue());
- case T_short: return IntConstant.fromValue(left.intValue() | right.shortValue());
- case T_int: return IntConstant.fromValue(left.intValue() | right.intValue());
- case T_long: return LongConstant.fromValue(left.intValue() | right.longValue());
- }
- break;
- case T_long :
- switch (rightId){
- case T_char : return LongConstant.fromValue(left.longValue() | right.charValue());
- case T_short: return LongConstant.fromValue(left.longValue() | right.shortValue());
- case T_int: return LongConstant.fromValue(left.longValue() | right.intValue());
- case T_long: return LongConstant.fromValue(left.longValue() | right.longValue());
- }
-
- }
-
- return NotAConstant;
- }
-
- public static final Constant computeConstantOperationOR_OR(Constant left, int leftId, Constant right, int rightId) {
-
- return BooleanConstant.fromValue(left.booleanValue() || right.booleanValue());
- }
-
- public static final Constant computeConstantOperationPLUS(Constant left, int leftId, Constant right, int rightId) {
-
- switch (leftId){
- case T_JavaLangObject :
- if (rightId == T_JavaLangString) {
- return StringConstant.fromValue(left.stringValue() + right.stringValue());
- }
- case T_boolean :
- if (rightId == T_JavaLangString) {
- return StringConstant.fromValue(left.stringValue() + right.stringValue());
- }
- break;
- case T_char :
- switch (rightId){
- case T_char : return IntConstant.fromValue(left.charValue() + right.charValue());
- case T_float: return FloatConstant.fromValue(left.charValue() + right.floatValue());
- case T_double: return DoubleConstant.fromValue(left.charValue() + right.doubleValue());
- case T_short: return IntConstant.fromValue(left.charValue() + right.shortValue());
- case T_int: return IntConstant.fromValue(left.charValue() + right.intValue());
- case T_long: return LongConstant.fromValue(left.charValue() + right.longValue());
- case T_JavaLangString: return StringConstant.fromValue(left.stringValue() + right.stringValue());
- }
- break;
- case T_float :
- switch (rightId){
- case T_char : return FloatConstant.fromValue(left.floatValue() + right.charValue());
- case T_float: return FloatConstant.fromValue(left.floatValue() + right.floatValue());
- case T_double: return DoubleConstant.fromValue(left.floatValue() + right.doubleValue());
- case T_short: return FloatConstant.fromValue(left.floatValue() + right.shortValue());
- case T_int: return FloatConstant.fromValue(left.floatValue() + right.intValue());
- case T_long: return FloatConstant.fromValue(left.floatValue() + right.longValue());
- case T_JavaLangString: return StringConstant.fromValue(left.stringValue() + right.stringValue());
- }
- break;
- case T_double :
- switch (rightId){
- case T_char : return DoubleConstant.fromValue(left.doubleValue() + right.charValue());
- case T_float: return DoubleConstant.fromValue(left.doubleValue() + right.floatValue());
- case T_double: return DoubleConstant.fromValue(left.doubleValue() + right.doubleValue());
- case T_short: return DoubleConstant.fromValue(left.doubleValue() + right.shortValue());
- case T_int: return DoubleConstant.fromValue(left.doubleValue() + right.intValue());
- case T_long: return DoubleConstant.fromValue(left.doubleValue() + right.longValue());
- case T_JavaLangString: return StringConstant.fromValue(left.stringValue() + right.stringValue());
- }
- break;
- case T_short :
- switch (rightId){
- case T_char : return IntConstant.fromValue(left.shortValue() + right.charValue());
- case T_float: return FloatConstant.fromValue(left.shortValue() + right.floatValue());
- case T_double: return DoubleConstant.fromValue(left.shortValue() + right.doubleValue());
- case T_short: return IntConstant.fromValue(left.shortValue() + right.shortValue());
- case T_int: return IntConstant.fromValue(left.shortValue() + right.intValue());
- case T_long: return LongConstant.fromValue(left.shortValue() + right.longValue());
- case T_JavaLangString: return StringConstant.fromValue(left.stringValue() + right.stringValue());
- }
- break;
- case T_int :
- switch (rightId){
- case T_char : return IntConstant.fromValue(left.intValue() + right.charValue());
- case T_float: return FloatConstant.fromValue(left.intValue() + right.floatValue());
- case T_double: return DoubleConstant.fromValue(left.intValue() + right.doubleValue());
- case T_short: return IntConstant.fromValue(left.intValue() + right.shortValue());
- case T_int: return IntConstant.fromValue(left.intValue() + right.intValue());
- case T_long: return LongConstant.fromValue(left.intValue() + right.longValue());
- case T_JavaLangString: return StringConstant.fromValue(left.stringValue() + right.stringValue());
- }
- break;
- case T_long :
- switch (rightId){
- case T_char : return LongConstant.fromValue(left.longValue() + right.charValue());
- case T_float: return FloatConstant.fromValue(left.longValue() + right.floatValue());
- case T_double: return DoubleConstant.fromValue(left.longValue() + right.doubleValue());
- case T_short: return LongConstant.fromValue(left.longValue() + right.shortValue());
- case T_int: return LongConstant.fromValue(left.longValue() + right.intValue());
- case T_long: return LongConstant.fromValue(left.longValue() + right.longValue());
- case T_JavaLangString: return StringConstant.fromValue(left.stringValue() + right.stringValue());
- }
- break;
- case T_JavaLangString :
- switch (rightId){
- case T_char : return StringConstant.fromValue(left.stringValue() + String.valueOf(right.charValue()));
- case T_float: return StringConstant.fromValue(left.stringValue() + String.valueOf(right.floatValue()));
- case T_double: return StringConstant.fromValue(left.stringValue() + String.valueOf(right.doubleValue()));
- case T_short: return StringConstant.fromValue(left.stringValue() + String.valueOf(right.shortValue()));
- case T_int: return StringConstant.fromValue(left.stringValue() + String.valueOf(right.intValue()));
- case T_long: return StringConstant.fromValue(left.stringValue() + String.valueOf(right.longValue()));
- case T_JavaLangString: return StringConstant.fromValue(left.stringValue() + right.stringValue());
- case T_boolean: return StringConstant.fromValue(left.stringValue() + right.booleanValue());
- }
- break;
-// case T_null :
-// switch (rightId){
-// case T_char : return Constant.fromValue(left.stringValue() + String.valueOf(right.charValue()));
-// case T_float: return Constant.fromValue(left.stringValue() + String.valueOf(right.floatValue()));
-// case T_double: return Constant.fromValue(left.stringValue() + String.valueOf(right.doubleValue()));
-// case T_byte: return Constant.fromValue(left.stringValue() + String.valueOf(right.byteValue()));
-// case T_short: return Constant.fromValue(left.stringValue() + String.valueOf(right.shortValue()));
-// case T_int: return Constant.fromValue(left.stringValue() + String.valueOf(right.intValue()));
-// case T_long: return Constant.fromValue(left.stringValue() + String.valueOf(right.longValue()));
-// case T_JavaLangString: return Constant.fromValue(left.stringValue() + right.stringValue());
-// case T_boolean: return Constant.fromValue(left.stringValue() + right.booleanValue());
-// }
- }
-
- return NotAConstant;
- }
-
- public static final Constant computeConstantOperationREMAINDER(Constant left, int leftId, Constant right, int rightId) {
-
- switch (leftId){
- case T_char :
- switch (rightId){
- case T_char : return IntConstant.fromValue(left.charValue() % right.charValue());
- case T_float: return FloatConstant.fromValue(left.charValue() % right.floatValue());
- case T_double: return DoubleConstant.fromValue(left.charValue() % right.doubleValue());
- case T_short: return IntConstant.fromValue(left.charValue() % right.shortValue());
- case T_int: return IntConstant.fromValue(left.charValue() % right.intValue());
- case T_long: return LongConstant.fromValue(left.charValue() % right.longValue());
- }
- break;
- case T_float :
- switch (rightId){
- case T_char : return FloatConstant.fromValue(left.floatValue() % right.charValue());
- case T_float: return FloatConstant.fromValue(left.floatValue() % right.floatValue());
- case T_double: return DoubleConstant.fromValue(left.floatValue() % right.doubleValue());
- case T_short: return FloatConstant.fromValue(left.floatValue() % right.shortValue());
- case T_int: return FloatConstant.fromValue(left.floatValue() % right.intValue());
- case T_long: return FloatConstant.fromValue(left.floatValue() % right.longValue());
- }
- break;
- case T_double :
- switch (rightId){
- case T_char : return DoubleConstant.fromValue(left.doubleValue() % right.charValue());
- case T_float: return DoubleConstant.fromValue(left.doubleValue() % right.floatValue());
- case T_double: return DoubleConstant.fromValue(left.doubleValue() % right.doubleValue());
- case T_short: return DoubleConstant.fromValue(left.doubleValue() % right.shortValue());
- case T_int: return DoubleConstant.fromValue(left.doubleValue() % right.intValue());
- case T_long: return DoubleConstant.fromValue(left.doubleValue() % right.longValue());
- }
- break;
- case T_short :
- switch (rightId){
- case T_char : return IntConstant.fromValue(left.shortValue() % right.charValue());
- case T_float: return FloatConstant.fromValue(left.shortValue() % right.floatValue());
- case T_double: return DoubleConstant.fromValue(left.shortValue() % right.doubleValue());
- case T_short: return IntConstant.fromValue(left.shortValue() % right.shortValue());
- case T_int: return IntConstant.fromValue(left.shortValue() % right.intValue());
- case T_long: return LongConstant.fromValue(left.shortValue() % right.longValue());
- }
- break;
- case T_int :
- switch (rightId){
- case T_char : return IntConstant.fromValue(left.intValue() % right.charValue());
- case T_float: return FloatConstant.fromValue(left.intValue() % right.floatValue());
- case T_double: return DoubleConstant.fromValue(left.intValue() % right.doubleValue());
- case T_short: return IntConstant.fromValue(left.intValue() % right.shortValue());
- case T_int: return IntConstant.fromValue(left.intValue() % right.intValue());
- case T_long: return LongConstant.fromValue(left.intValue() % right.longValue());
- }
- break;
- case T_long :
- switch (rightId){
- case T_char : return LongConstant.fromValue(left.longValue() % right.charValue());
- case T_float: return FloatConstant.fromValue(left.longValue() % right.floatValue());
- case T_double: return DoubleConstant.fromValue(left.longValue() % right.doubleValue());
- case T_short: return LongConstant.fromValue(left.longValue() % right.shortValue());
- case T_int: return LongConstant.fromValue(left.longValue() % right.intValue());
- case T_long: return LongConstant.fromValue(left.longValue() % right.longValue());
- }
-
- }
-
- return NotAConstant;
- }
-
- public static final Constant computeConstantOperationRIGHT_SHIFT(Constant left, int leftId, Constant right, int rightId) {
-
- switch (leftId){
- case T_char :
- switch (rightId){
- case T_char : return IntConstant.fromValue(left.charValue() >> right.charValue());
- case T_short: return IntConstant.fromValue(left.charValue() >> right.shortValue());
- case T_int: return IntConstant.fromValue(left.charValue() >> right.intValue());
- case T_long: return IntConstant.fromValue(left.charValue() >> right.longValue());
- }
- break;
- case T_short :
- switch (rightId){
- case T_char : return IntConstant.fromValue(left.shortValue() >> right.charValue());
- case T_short: return IntConstant.fromValue(left.shortValue() >> right.shortValue());
- case T_int: return IntConstant.fromValue(left.shortValue() >> right.intValue());
- case T_long: return IntConstant.fromValue(left.shortValue() >> right.longValue());
- }
- break;
- case T_int :
- switch (rightId){
- case T_char : return IntConstant.fromValue(left.intValue() >> right.charValue());
- case T_short: return IntConstant.fromValue(left.intValue() >> right.shortValue());
- case T_int: return IntConstant.fromValue(left.intValue() >> right.intValue());
- case T_long: return IntConstant.fromValue(left.intValue() >> right.longValue());
- }
- break;
- case T_long :
- switch (rightId){
- case T_char : return LongConstant.fromValue(left.longValue() >> right.charValue());
- case T_short: return LongConstant.fromValue(left.longValue() >> right.shortValue());
- case T_int: return LongConstant.fromValue(left.longValue() >> right.intValue());
- case T_long: return LongConstant.fromValue(left.longValue() >> right.longValue());
- }
-
- }
-
- return NotAConstant;
- }
-
- public static final Constant computeConstantOperationUNSIGNED_RIGHT_SHIFT(Constant left, int leftId, Constant right, int rightId) {
-
- switch (leftId){
- case T_char :
- switch (rightId){
- case T_char : return IntConstant.fromValue(left.charValue() >>> right.charValue());
- case T_short: return IntConstant.fromValue(left.charValue() >>> right.shortValue());
- case T_int: return IntConstant.fromValue(left.charValue() >>> right.intValue());
- case T_long: return IntConstant.fromValue(left.charValue() >>> right.longValue());
- }
- break;
- case T_short :
- switch (rightId){
- case T_char : return IntConstant.fromValue(left.shortValue() >>> right.charValue());
- case T_short: return IntConstant.fromValue(left.shortValue() >>> right.shortValue());
- case T_int: return IntConstant.fromValue(left.shortValue() >>> right.intValue());
- case T_long: return IntConstant.fromValue(left.shortValue() >>> right.longValue());
- }
- break;
- case T_int :
- switch (rightId){
- case T_char : return IntConstant.fromValue(left.intValue() >>> right.charValue());
- case T_short: return IntConstant.fromValue(left.intValue() >>> right.shortValue());
- case T_int: return IntConstant.fromValue(left.intValue() >>> right.intValue());
- case T_long: return IntConstant.fromValue(left.intValue() >>> right.longValue());
- }
- break;
- case T_long :
- switch (rightId){
- case T_char : return LongConstant.fromValue(left.longValue() >>> right.charValue());
- case T_short: return LongConstant.fromValue(left.longValue() >>> right.shortValue());
- case T_int: return LongConstant.fromValue(left.longValue() >>> right.intValue());
- case T_long: return LongConstant.fromValue(left.longValue() >>> right.longValue());
- }
-
- }
-
- return NotAConstant;
- }
-
- public static final Constant computeConstantOperationXOR(Constant left, int leftId, Constant right, int rightId) {
-
- switch (leftId){
- case T_boolean : return BooleanConstant.fromValue(left.booleanValue() ^ right.booleanValue());
- case T_char :
- switch (rightId){
- case T_char : return IntConstant.fromValue(left.charValue() ^ right.charValue());
- case T_short: return IntConstant.fromValue(left.charValue() ^ right.shortValue());
- case T_int: return IntConstant.fromValue(left.charValue() ^ right.intValue());
- case T_long: return LongConstant.fromValue(left.charValue() ^ right.longValue());
- }
- break;
- case T_short :
- switch (rightId){
- case T_char : return IntConstant.fromValue(left.shortValue() ^ right.charValue());
- case T_short: return IntConstant.fromValue(left.shortValue() ^ right.shortValue());
- case T_int: return IntConstant.fromValue(left.shortValue() ^ right.intValue());
- case T_long: return LongConstant.fromValue(left.shortValue() ^ right.longValue());
- }
- break;
- case T_int :
- switch (rightId){
- case T_char : return IntConstant.fromValue(left.intValue() ^ right.charValue());
- case T_short: return IntConstant.fromValue(left.intValue() ^ right.shortValue());
- case T_int: return IntConstant.fromValue(left.intValue() ^ right.intValue());
- case T_long: return LongConstant.fromValue(left.intValue() ^ right.longValue());
- }
- break;
- case T_long :
- switch (rightId){
- case T_char : return LongConstant.fromValue(left.longValue() ^ right.charValue());
- case T_short: return LongConstant.fromValue(left.longValue() ^ right.shortValue());
- case T_int: return LongConstant.fromValue(left.longValue() ^ right.intValue());
- case T_long: return LongConstant.fromValue(left.longValue() ^ right.longValue());
- }
- }
-
- return NotAConstant;
- }
-
- public double doubleValue() {
-
- throw new ShouldNotImplement(Messages.bind(Messages.constant_cannotCastedInto, new String[] { typeName(), "double" })); //$NON-NLS-1$
- }
-
- public float floatValue() {
-
- throw new ShouldNotImplement(Messages.bind(Messages.constant_cannotCastedInto, new String[] { typeName(), "float" })); //$NON-NLS-1$
- }
- /**
- * Returns true if both constants have the same type and the same actual value
- * @param otherConstant
- */
- public boolean hasSameValue(Constant otherConstant) {
- if (this == otherConstant)
- return true;
- int typeID;
- if ((typeID = typeID()) != otherConstant.typeID())
- return false;
- switch (typeID) {
- case TypeIds.T_boolean:
- return booleanValue() == otherConstant.booleanValue();
- case TypeIds.T_char:
- return charValue() == otherConstant.charValue();
- case TypeIds.T_double:
- return doubleValue() == otherConstant.doubleValue();
- case TypeIds.T_float:
- return floatValue() == otherConstant.floatValue();
- case TypeIds.T_int:
- return intValue() == otherConstant.intValue();
- case TypeIds.T_short:
- return shortValue() == otherConstant.shortValue();
- case TypeIds.T_long:
- return longValue() == otherConstant.longValue();
- case TypeIds.T_JavaLangString:
- String value = stringValue();
- return value == null
- ? otherConstant.stringValue() == null
- : value.equals(otherConstant.stringValue());
- }
- return false;
- }
-
- public int intValue() {
-
- throw new ShouldNotImplement(Messages.bind(Messages.constant_cannotCastedInto, new String[] { typeName(), "int" })); //$NON-NLS-1$
- }
-
- public long longValue() {
-
- throw new ShouldNotImplement(Messages.bind(Messages.constant_cannotCastedInto, new String[] { typeName(), "long" })); //$NON-NLS-1$
- }
-
- public short shortValue() {
-
- throw new ShouldNotImplement(Messages.bind(Messages.constant_cannotConvertedTo, new String[] { typeName(), "short" })); //$NON-NLS-1$
- }
-
- public String stringValue() {
-
- throw new ShouldNotImplement(Messages.bind(Messages.constant_cannotConvertedTo, new String[] { typeName(), "String" })); //$NON-NLS-1$
- }
-
- public String toString(){
-
- if (this == NotAConstant) return "(Constant) NotAConstant"; //$NON-NLS-1$
- return super.toString(); }
-
- public abstract int typeID();
-
- public String typeName() {
- switch (typeID()) {
- case T_int : return "int"; //$NON-NLS-1$
- case T_short : return "short"; //$NON-NLS-1$
- case T_char : return "char"; //$NON-NLS-1$
- case T_float : return "float"; //$NON-NLS-1$
- case T_double : return "double"; //$NON-NLS-1$
- case T_boolean : return "boolean"; //$NON-NLS-1$
- case T_long : return "long";//$NON-NLS-1$
- case T_JavaLangString : return "java.lang.String"; //$NON-NLS-1$
- case T_null : return "null"; //$NON-NLS-1$
- default: return "unknown"; //$NON-NLS-1$
- }
- }
-
- public boolean equals(Object obj) {
- if (obj instanceof Constant)
- {
- Constant other = (Constant)obj;
- if ( typeID()==other.typeID())
- {
- return stringValue().equals(other.stringValue());
- }
- }
- return false;
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/DoubleConstant.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/DoubleConstant.java
deleted file mode 100644
index f9928d13..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/DoubleConstant.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.impl;
-
-public class DoubleConstant extends Constant {
-
- private double value;
-
- public static Constant fromValue(double value) {
-
- return new DoubleConstant(value);
- }
-
- private DoubleConstant(double value) {
- this.value = value;
- }
-
- public byte byteValue() {
- return (byte) value;
- }
-
- public char charValue() {
- return (char) value;
- }
-
- public double doubleValue() {
- return this.value;
- }
-
- public float floatValue() {
- return (float) value;
- }
-
- public int intValue() {
- return (int) value;
- }
-
- public long longValue() {
- return (long) value;
- }
-
- public short shortValue() {
- return (short) value;
- }
-
- public String stringValue() {
- return String.valueOf(this.value);
- }
-
- public String toString() {
- if (this == NotAConstant)
- return "(Constant) NotAConstant"; //$NON-NLS-1$
- return "(double)" + value; //$NON-NLS-1$
- }
-
- public int typeID() {
- return T_double;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/FloatConstant.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/FloatConstant.java
deleted file mode 100644
index b835abbb..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/FloatConstant.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.impl;
-
-public class FloatConstant extends Constant {
-
- float value;
-
- public static Constant fromValue(float value) {
- return new FloatConstant(value);
- }
-
- private FloatConstant(float value) {
- this.value = value;
- }
-
- public byte byteValue() {
- return (byte) value;
- }
-
- public char charValue() {
- return (char) value;
- }
-
- public double doubleValue() {
- return value; // implicit cast to return type
- }
-
- public float floatValue() {
- return this.value;
- }
-
- public int intValue() {
- return (int) value;
- }
-
- public long longValue() {
- return (long) value;
- }
-
- public short shortValue() {
- return (short) value;
- }
-
- public String stringValue() {
- return String.valueOf(this.value);
- }
-
- public String toString() {
- return "(float)" + value; //$NON-NLS-1$
- }
-
- public int typeID() {
- return T_float;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/ITypeRequestor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/ITypeRequestor.java
deleted file mode 100644
index 418e22fe..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/ITypeRequestor.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*******************************************************************************
- * 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.compiler.impl;
-
-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.ISourceType;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding;
-import org.eclipse.wst.jsdt.internal.oaametadata.LibraryAPIs;
-
-public interface ITypeRequestor {
-
- /**
- * Accept the resolved binary form for the requested type.
- */
- void accept(IBinaryType binaryType, PackageBinding packageBinding, AccessRestriction accessRestriction);
-
- /**
- * Accept the requested type's compilation unit.
- */
- void accept(ICompilationUnit unit, AccessRestriction accessRestriction);
-
- /**
- * Accept the unresolved source forms for the requested type.
- * Note that the multiple source forms can be answered, in case the target compilation unit
- * contains multiple types. The first one is then guaranteed to be the one corresponding to the
- * requested type.
- */
- void accept(ISourceType[] sourceType, PackageBinding packageBinding, AccessRestriction accessRestriction);
-
- void accept(LibraryAPIs libraryMetaData);
-
-
- CompilationUnitDeclaration doParse(ICompilationUnit unit, AccessRestriction accessRestriction);
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/ITypeRequestor2.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/ITypeRequestor2.java
deleted file mode 100644
index 2eb46da5..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/ITypeRequestor2.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*******************************************************************************
- * 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.compiler.impl;
-
-import org.eclipse.wst.jsdt.internal.compiler.env.AccessRestriction;
-import org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit;
-
-public interface ITypeRequestor2 extends ITypeRequestor {
-
- /**
- * Accept the requested type's compilation unit, building and
- * completing type bindings only for the given type names.
- */
- void accept(ICompilationUnit unit, char[][] typeNames, AccessRestriction accessRestriction);
-
-}
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
deleted file mode 100644
index c7bf90e6..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/IntConstant.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*******************************************************************************
- * 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.compiler.impl;
-
-public class IntConstant extends Constant {
-
- long value;
-
- private static final IntConstant MINUS_FOUR = new IntConstant(-4);
- private static final IntConstant MINUS_THREE = new IntConstant(-3);
- private static final IntConstant MINUS_TWO = new IntConstant(-2);
- private static final IntConstant MINUS_ONE = new IntConstant(-1);
- private static final IntConstant ZERO = new IntConstant(0);
- private static final IntConstant ONE = new IntConstant(1);
- private static final IntConstant TWO = new IntConstant(2);
- private static final IntConstant THREE = new IntConstant(3);
- private static final IntConstant FOUR = new IntConstant(4);
- private static final IntConstant FIVE = new IntConstant(5);
- private static final IntConstant SIX = new IntConstant(6);
- private static final IntConstant SEVEN = new IntConstant(7);
- private static final IntConstant EIGHT= new IntConstant(8);
- private static final IntConstant NINE = new IntConstant(9);
- private static final IntConstant TEN = new IntConstant(10);
-
- public static Constant fromValue(int value) {
-
- switch (value) {
- case -4 : return IntConstant.MINUS_FOUR;
- case -3 : return IntConstant.MINUS_THREE;
- case -2 : return IntConstant.MINUS_TWO;
- case -1 : return IntConstant.MINUS_ONE;
- case 0 : return IntConstant.ZERO;
- case 1 : return IntConstant.ONE;
- case 2 : return IntConstant.TWO;
- case 3 : return IntConstant.THREE;
- case 4 : return IntConstant.FOUR;
- case 5 : return IntConstant.FIVE;
- case 6 : return IntConstant.SIX;
- case 7 : return IntConstant.SEVEN;
- case 8 : return IntConstant.EIGHT;
- case 9 : return IntConstant.NINE;
- case 10 : return IntConstant.TEN;
- }
- return new IntConstant(value);
- }
-
- private IntConstant(int value) {
- this.value = value;
- }
-
- public byte byteValue() {
- return (byte) value;
- }
-
- public char charValue() {
- return (char) value;
- }
-
- public double doubleValue() {
- return value; // implicit cast to return type
- }
-
- public float floatValue() {
- return value; // implicit cast to return type
- }
-
- public int intValue() {
- return (int)value;
- }
-
- public long longValue() {
- return value; // implicit cast to return type
- }
-
- public short shortValue() {
- return (short) value;
- }
-
- public String stringValue() {
- //spec 15.17.11
- return String.valueOf(this.value);
- }
-
- public String toString() {
- return "(int)" + value; //$NON-NLS-1$
- }
-
- public int typeID() {
- return T_int;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/LongConstant.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/LongConstant.java
deleted file mode 100644
index 7f5d31a6..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/LongConstant.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.impl;
-
-public class LongConstant extends Constant {
-private static final LongConstant ZERO = new LongConstant(0L);
-
-private long value;
-
-public static Constant fromValue(long value) {
- if (value == 0L) {
- return ZERO;
- }
- return new LongConstant(value);
-}
-private LongConstant(long value) {
- this.value = value;
-}
-public byte byteValue() {
- return (byte) value;
-}
-public char charValue() {
- return (char) value;
-}
-public double doubleValue() {
- return value; // implicit cast to return type
-}
-public float floatValue() {
- return value; // implicit cast to return type
-}
-public int intValue() {
- return (int) value;
-}
-public long longValue() {
- return value;
-}
-public short shortValue() {
- return (short) value;
-}
-public String stringValue() {
- //spec 15.17.11
- return String.valueOf(this.value);
-}
-public String toString(){
-
- return "(long)" + value ; } //$NON-NLS-1$
-public int typeID() {
- return T_long;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/ReferenceContext.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/ReferenceContext.java
deleted file mode 100644
index 4a0ff9cc..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/ReferenceContext.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.impl;
-/*
- * Implementors are valid compilation contexts from which we can
- * escape in case of error:
- * For example: method, type or compilation unit.
- */
-
-import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem;
-import org.eclipse.wst.jsdt.internal.compiler.CompilationResult;
-
-public interface ReferenceContext {
- void abort(int abortLevel, CategorizedProblem problem);
- CompilationResult compilationResult();
- boolean hasErrors();
- void tagAsHavingErrors();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/ShortConstant.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/ShortConstant.java
deleted file mode 100644
index 3c09f15f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/ShortConstant.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.impl;
-
-public class ShortConstant extends Constant {
-private short value;
-
-public static Constant fromValue(short value) {
- return new ShortConstant(value);
-}
-private ShortConstant(short value) {
- this.value = value;
-}
-public byte byteValue() {
- return (byte) value;
-}
-public char charValue() {
- return (char) value;
-}
-public double doubleValue() {
- return value; // implicit cast to return type
-}
-public float floatValue() {
- return value; // implicit cast to return type
-}
-public int intValue() {
- return value; // implicit cast to return type
-}
-public long longValue() {
- return value; // implicit cast to return type
-}
-public short shortValue() {
- return value;
-}
-public String stringValue() {
- //spec 15.17.11
- return String.valueOf(this.value);
-}
-public String toString(){
-
- return "(short)" + value ; } //$NON-NLS-1$
-public int typeID() {
- return T_short;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/StringConstant.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/StringConstant.java
deleted file mode 100644
index a2d59286..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/StringConstant.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.impl;
-
-public class StringConstant extends Constant {
-private String value;
-
-
-public static Constant fromValue(String value) {
- return new StringConstant(value);
-}
-
-private StringConstant(String value) {
- this.value = value ;
-}
-
-public String stringValue() {
- //spec 15.17.11
-
- //the next line do not go into the toString() send....!
- return value ;
-
- /*
- String s = value.toString() ;
- if (s == null)
- return "null";
- else
- return s;
- */
-
-}
-public String toString(){
-
- return "(String)\"" + value +"\""; } //$NON-NLS-2$ //$NON-NLS-1$
-public int typeID() {
- return T_JavaLangString;
-}
-}
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
deleted file mode 100644
index da4eed25..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ArrayBinding.java
+++ /dev/null
@@ -1,270 +0,0 @@
-/*******************************************************************************
- * 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.compiler.lookup;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.infer.InferredType;
-import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants;
-
-public final class ArrayBinding extends ReferenceBinding {
- // creation and initialization of the length field
- // the declaringClass of this field is intentionally set to null so it can be distinguished.
- public static final FieldBinding ArrayLength = new FieldBinding(TypeConstants.LENGTH, TypeBinding.INT, ClassFileConstants.AccPublic | ClassFileConstants.AccFinal, null);
-
- public TypeBinding leafComponentType;
- public int dimensions;
- LookupEnvironment environment;
- char[] constantPoolName;
- char[] genericTypeSignature;
- ReferenceBinding referenceBinding;
-
-public ArrayBinding(TypeBinding type, int dimensions, LookupEnvironment environment) {
- this.tagBits |= TagBits.IsArrayType;
- this.leafComponentType = type;
- this.dimensions = dimensions;
- this.environment = environment;
- if (type instanceof UnresolvedReferenceBinding)
- ((UnresolvedReferenceBinding) type).addWrapper(this, environment);
-
- referenceBinding = environment.getResolvedType(TypeConstants.ARRAY,null);
- this.fPackage=environment.defaultPackage;
-}
-
-/*
- * brakets leafUniqueKey
- * p.X[][] --> [[Lp/X;
- */
-public char[] computeUniqueKey(boolean isLeaf) {
- char[] brackets = new char[dimensions];
- for (int i = dimensions - 1; i >= 0; i--) brackets[i] = '[';
- return CharOperation.concat(brackets, this.leafComponentType.computeUniqueKey(isLeaf));
- }
-
-/**
- * Answer the receiver's constant pool name.
- * NOTE: This method should only be used during/after code gen.
- * e.g. '[Ljava/lang/Object;'
- */
-public char[] constantPoolName() {
- if (constantPoolName != null)
- return constantPoolName;
-
- char[] brackets = new char[dimensions];
- for (int i = dimensions - 1; i >= 0; i--) brackets[i] = '[';
- return constantPoolName = CharOperation.concat(brackets, leafComponentType.signature());
-}
-
-public char[] signature() {
- return this.signature = CharOperation.concat('L', InferredType.ARRAY_NAME, ';');
-}
-
-public String debugName() {
- StringBuffer brackets = new StringBuffer(dimensions * 2);
- for (int i = dimensions; --i >= 0;)
- brackets.append("[]"); //$NON-NLS-1$
- return leafComponentType.debugName() + brackets.toString();
-}
-public int dimensions() {
- return this.dimensions;
-}
-
-/* Answer an array whose dimension size is one less than the receiver.
-*
-* When the receiver's dimension size is one then answer the leaf component type.
-*/
-
-public TypeBinding elementsType() {
- if (this.dimensions == 1) return this.leafComponentType;
- return this.environment.createArrayType(this.leafComponentType, this.dimensions - 1);
-}
-
-public LookupEnvironment environment() {
- return this.environment;
-}
-
-public char[] genericTypeSignature() {
-
- if (this.genericTypeSignature == null) {
- char[] brackets = new char[dimensions];
- for (int i = dimensions - 1; i >= 0; i--) brackets[i] = '[';
- this.genericTypeSignature = CharOperation.concat(brackets, leafComponentType.signature());
- }
- return this.genericTypeSignature;
-}
-
-public PackageBinding getPackage() {
- return leafComponentType.getPackage();
-}
-
-public int hashCode() {
- return this.leafComponentType == null ? super.hashCode() : this.leafComponentType.hashCode();
-}
-
-/* Answer true if the receiver type can be assigned to the argument type (right)
-*/
-public boolean isCompatibleWith(TypeBinding otherType) {
- if (this == otherType)
- return true;
-
- switch (otherType.kind()) {
- case Binding.ARRAY_TYPE :
- ArrayBinding otherArray = (ArrayBinding) otherType;
-// if (otherArray.leafComponentType.isBaseType())
-// return false; // relying on the fact that all equal arrays are identical
-// if (dimensions == otherArray.dimensions)
- return leafComponentType.isCompatibleWith(otherArray.leafComponentType);
-// if (dimensions < otherArray.dimensions)
-// return false; // cannot assign 'String[]' into 'Object[][]' but can assign 'byte[][]' into 'Object[]'
-// break;
- case Binding.BASE_TYPE :
- return otherType.isAnyType();
-
- case Binding.TYPE :
- return otherType==this.referenceBinding;
-
- }
- //Check dimensions - Java does not support explicitly sized dimensions for types.
- //However, if it did, the type checking support would go here.
- switch (otherType.leafComponentType().id) {
- case TypeIds.T_JavaLangObject :
- return true;
- }
- return false;
-}
-
-public int kind() {
- return ARRAY_TYPE;
-}
-
-public TypeBinding leafComponentType(){
- return leafComponentType;
-}
-
-/* API
-* Answer the problem id associated with the receiver.
-* NoError if the receiver is a valid binding.
-*/
-public int problemId() {
- return leafComponentType.problemId();
-}
-/**
-* Answer the source name for the type.
-* In the case of member types, as the qualified name from its top level type.
-* For example, for a member type N defined inside M & A: "A.M.N".
-*/
-
-public char[] qualifiedSourceName() {
- char[] brackets = new char[dimensions * 2];
- for (int i = dimensions * 2 - 1; i >= 0; i -= 2) {
- brackets[i] = ']';
- brackets[i - 1] = '[';
- }
- return CharOperation.concat(leafComponentType.qualifiedSourceName(), brackets);
-}
-public char[] readableName() /* java.lang.Object[] */ {
- char[] brackets = new char[dimensions * 2];
- for (int i = dimensions * 2 - 1; i >= 0; i -= 2) {
- brackets[i] = ']';
- brackets[i - 1] = '[';
- }
- return CharOperation.concat(leafComponentType.readableName(), brackets);
-}
-public char[] shortReadableName(){
- char[] brackets = new char[dimensions * 2];
- for (int i = dimensions * 2 - 1; i >= 0; i -= 2) {
- brackets[i] = ']';
- brackets[i - 1] = '[';
- }
- return CharOperation.concat(leafComponentType.shortReadableName(), brackets);
-}
-public char[] sourceName() {
- char[] brackets = new char[dimensions * 2];
- for (int i = dimensions * 2 - 1; i >= 0; i -= 2) {
- brackets[i] = ']';
- brackets[i - 1] = '[';
- }
- return CharOperation.concat(leafComponentType.sourceName(), brackets);
-}
-public ReferenceBinding superclass() {
- if(referenceBinding != null)
- return referenceBinding.superclass();
- return null;
-}
-public void swapUnresolved(UnresolvedReferenceBinding unresolvedType, ReferenceBinding resolvedType, LookupEnvironment env) {
- if (this.leafComponentType == unresolvedType) {
- this.leafComponentType = resolvedType;
- this.tagBits |= this.leafComponentType.tagBits;
- }
-}
-public String toString() {
- return leafComponentType != null ? debugName() : "NULL TYPE ARRAY"; //$NON-NLS-1$
-}
-
-public FieldBinding[] availableFields() {
- if(referenceBinding != null)
- return referenceBinding.availableFields();
- return new FieldBinding[0];
-}
-
-public MethodBinding[] availableMethods() {
- if(referenceBinding != null)
- return referenceBinding.availableMethods();
- return new MethodBinding[0];
-}
-
-public int fieldCount() {
- if(referenceBinding != null)
- return referenceBinding.fieldCount();
- return 0;
-}
-
-public FieldBinding[] fields() {
- if(referenceBinding != null)
- return referenceBinding.fields();
- return new FieldBinding[0];
-}
-
-public InferredType getInferredType() {
- if(referenceBinding != null)
- return referenceBinding.getInferredType();
- return null;
-}
-
-public MethodBinding[] getMethods(char[] selector) {
- if(referenceBinding != null)
- return referenceBinding.getMethods(selector);
- return new MethodBinding[0];
-}
-
-boolean implementsMethod(MethodBinding method) {
- if(referenceBinding != null)
- return referenceBinding.implementsMethod(method);
- return false;
-}
-
-public MethodBinding[] methods() {
- if(referenceBinding != null)
- return referenceBinding.methods();
- return new MethodBinding[0];
-}
-public MethodBinding getExactMethod(char[] selector, TypeBinding[] argumentTypes, CompilationUnitScope refScope) {
- if(referenceBinding != null)
- return referenceBinding.getExactMethod(selector, argumentTypes, refScope);
- return null;
-}
-
-public FieldBinding getField(char[] fieldName, boolean needResolve) {
- if(referenceBinding != null)
- return referenceBinding.getField(fieldName, needResolve);
- return null;
-}
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/BaseTypeBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/BaseTypeBinding.java
deleted file mode 100644
index 08c4a5ec..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/BaseTypeBinding.java
+++ /dev/null
@@ -1,207 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.lookup;
-
-public final class BaseTypeBinding extends TypeBinding {
-
- public char[] simpleName;
- private char[] constantPoolName;
-
- BaseTypeBinding(int id, char[] name, char[] constantPoolName) {
-
- this.tagBits |= TagBits.IsBaseType;
- this.id = id;
- this.simpleName = name;
- this.constantPoolName = constantPoolName;
- }
-
- /**
- * int -> I
- */
- public char[] computeUniqueKey(boolean isLeaf) {
- return constantPoolName();
- }
-
- /* Answer the receiver's constant pool name.
- */
- public char[] constantPoolName() {
-
- return constantPoolName;
- }
-
- public PackageBinding getPackage() {
-
- return null;
- }
-
- /* Answer true if the receiver type can be assigned to the argument type (right)
- */
- public final boolean isCompatibleWith(TypeBinding right) {
-
- if (this == right)
- return true;
- if (this.id==TypeIds.T_any)
- return true;
- if (!right.isBasicType())
- return this == TypeBinding.NULL;
-
- switch (right.id) {
- case TypeIds.T_boolean :
- if(id == TypeIds.T_boolean)
- return true;
- break;
- case TypeIds.T_char :
- return false;
- case TypeIds.T_double :
- switch (id) {
- case TypeIds.T_char :
- case TypeIds.T_short :
- case TypeIds.T_int :
- case TypeIds.T_long :
- case TypeIds.T_float :
- return true;
- default :
- return false;
- }
- case TypeIds.T_float :
- switch (id) {
- case TypeIds.T_char :
- case TypeIds.T_short :
- case TypeIds.T_int :
- case TypeIds.T_long :
- return true;
- default :
- return false;
- }
- case TypeIds.T_long :
- switch (id) {
- case TypeIds.T_char :
- case TypeIds.T_short :
- case TypeIds.T_int :
- return true;
- default :
- return false;
- }
- case TypeIds.T_int :
- switch (id) {
- case TypeIds.T_char :
- case TypeIds.T_short :
- case TypeIds.T_double :
- return true;
- default :
- return false;
- }
- case TypeIds.T_any :
- return true;
- case TypeIds.T_JavaLangString:
- case TypeIds.T_JavaLangObject:
- case TypeIds.T_function:
- return (id==TypeIds.T_null);
- }
- return false;
- }
-
- public static final boolean isNarrowing(int left, int right) {
-
- //can "left" store a "right" using some narrowing conversion
- //(is left smaller than right)
- if (right==TypeIds.T_any)
- return true;
- switch (left) {
- case TypeIds.T_boolean :
- return right == TypeIds.T_boolean;
- case TypeIds.T_char :
- case TypeIds.T_short :
- if (right == TypeIds.T_short)
- return true;
- if (right == TypeIds.T_char)
- return true;
- case TypeIds.T_int :
- if (right == TypeIds.T_int)
- return true;
- case TypeIds.T_long :
- if (right == TypeIds.T_long)
- return true;
- case TypeIds.T_float :
- if (right == TypeIds.T_float)
- return true;
- case TypeIds.T_double :
- if (right == TypeIds.T_double)
- return true;
- case TypeIds.T_any :
- return true;
- default :
- return false;
- }
- }
- /**
- * T_null is acting as an unchecked exception
- * @see org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding#isUncheckedException(boolean)
- */
- public boolean isUncheckedException(boolean includeSupertype) {
- return this == TypeBinding.NULL;
- }
- public static final boolean isWidening(int left, int right) {
-
- //can "left" store a "right" using some widening conversion
- //(is left "bigger" than right)
- switch (left) {
- case TypeIds.T_boolean :
- return right == TypeIds.T_boolean;
- case TypeIds.T_char :
- return right == TypeIds.T_char;
- case TypeIds.T_double :
- if (right == TypeIds.T_double)
- return true;
- case TypeIds.T_float :
- if (right == TypeIds.T_float)
- return true;
- case TypeIds.T_long :
- if (right == TypeIds.T_long)
- return true;
- case TypeIds.T_int :
- if (right == TypeIds.T_int)
- return true;
- if (right == TypeIds.T_char)
- return true;
- case TypeIds.T_short :
- if (right == TypeIds.T_short)
- return true;
- default :
- return false;
- }
- }
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.lookup.Binding#kind()
- */
- public int kind() {
- return Binding.BASE_TYPE;
- }
- public char[] qualifiedSourceName() {
- return simpleName;
- }
-
- public char[] readableName() {
- return simpleName;
- }
-
- public char[] shortReadableName() {
- return simpleName;
- }
-
- public char[] sourceName() {
- return simpleName;
- }
-
- public String toString() {
- return new String(constantPoolName) + " (id=" + id + ")"; //$NON-NLS-1$ //$NON-NLS-2$
- }
-}
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
deleted file mode 100644
index 9b38f5ce..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/BinaryTypeBinding.java
+++ /dev/null
@@ -1,775 +0,0 @@
-/*******************************************************************************
- * 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.compiler.lookup;
-
-import org.eclipse.wst.jsdt.core.UnimplementedException;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants;
-import org.eclipse.wst.jsdt.internal.compiler.env.ClassSignature;
-import org.eclipse.wst.jsdt.internal.compiler.env.ISourceField;
-import org.eclipse.wst.jsdt.internal.compiler.env.ISourceMethod;
-import org.eclipse.wst.jsdt.internal.compiler.env.ISourceType;
-import org.eclipse.wst.jsdt.internal.compiler.impl.Constant;
-import org.eclipse.wst.jsdt.internal.compiler.problem.AbortCompilation;
-import org.eclipse.wst.jsdt.internal.core.SourceField;
-import org.eclipse.wst.jsdt.internal.core.SourceMethod;
-
-/*
-Not all fields defined by this type are initialized when it is created.
-Some are initialized only when needed.
-
-Accessors have been provided for some public fields so all TypeBindings have the same API...
-but access public fields directly whenever possible.
-Non-public fields have accessors which should be used everywhere you expect the field to be initialized.
-
-null is NOT a valid value for a non-public field... it just means the field is not initialized.
-*/
-
-public class BinaryTypeBinding extends ReferenceBinding {
-
- // all of these fields are ONLY guaranteed to be initialized if accessed using their public accessor method
- protected ReferenceBinding superclass;
- protected ReferenceBinding enclosingType;
- protected FieldBinding[] fields;
- protected MethodBinding[] methods;
- protected ReferenceBinding[] memberTypes;
-
- // For the link with the principle structure
- protected LookupEnvironment environment;
-
-static Object convertMemberValue(Object binaryValue, LookupEnvironment env) {
- if (binaryValue == null) return null;
- if (binaryValue instanceof Constant)
- return binaryValue;
- if (binaryValue instanceof ClassSignature)
- return env.getTypeFromSignature(((ClassSignature) binaryValue).getTypeName(), 0, -1, false, null);
- if (binaryValue instanceof Object[]) {
- Object[] objects = (Object[]) binaryValue;
- int length = objects.length;
- if (length == 0) return objects;
- Object[] values = new Object[length];
- for (int i = 0; i < length; i++)
- values[i] = convertMemberValue(objects[i], env);
- return values;
- }
-
- // should never reach here.
- throw new IllegalStateException();
-}
-public static ReferenceBinding resolveType(ReferenceBinding type, LookupEnvironment environment, boolean convertGenericToRawType) {
- if (type instanceof UnresolvedReferenceBinding)
- return ((UnresolvedReferenceBinding) type).resolve(environment, convertGenericToRawType);
-
- return type;
-}
-public static TypeBinding resolveType(TypeBinding type, LookupEnvironment environment, int rank) {
- switch (type.kind()) {
-
- case Binding.ARRAY_TYPE :
- resolveType(((ArrayBinding) type).leafComponentType, environment, rank);
- break;
-
- default:
- if (type instanceof UnresolvedReferenceBinding)
- return ((UnresolvedReferenceBinding) type).resolve(environment, true);
- }
- return type;
-}
-
-/**
- * Default empty constructor for subclasses only.
- */
-protected BinaryTypeBinding() {
- // only for subclasses
-}
-
-/**
- * Standard constructor for creating binary type bindings from binary models (classfiles)
- * @param packageBinding
- * @param binaryType
- * @param environment
- */
-public BinaryTypeBinding(PackageBinding packageBinding, ISourceType binaryType, LookupEnvironment environment) {
- this.compoundName = CharOperation.splitOn('/', binaryType.getName());
- this.fileName = binaryType.getFileName();
- computeId();
-
- this.tagBits |= TagBits.IsBinaryBinding;
- this.environment = environment;
- this.fPackage = packageBinding;
-
-// char[] typeSignature = environment.globalOptions.sourceLevel >= ClassFileConstants.JDK1_5 ? binaryType.getGenericSignature() : null;
-// this.typeVariables = typeSignature != null && typeSignature.length > 0 && typeSignature[0] == '<'
-// ? null // is initialized in cachePartsFrom (called from LookupEnvironment.createBinaryTypeFrom())... must set to null so isGenericType() answers true
-// : Binding.NO_TYPE_VARIABLES;
-
- this.sourceName = binaryType.getFileName();
- this.modifiers = binaryType.getModifiers();
-
-// if ((binaryType.getTagBits() & TagBits.HasInconsistentHierarchy) != 0)
-// this.tagBits |= TagBits.HierarchyHasProblems;
-// if (binaryType.isAnonymous()) {
-// this.tagBits |= TagBits.AnonymousTypeMask;
-// } else if (binaryType.isLocal()) {
-// this.tagBits |= TagBits.LocalTypeMask;
-// } else if (binaryType.isMember()) {
-// this.tagBits |= TagBits.MemberTypeMask;
-// }
-// // need enclosing type to access type variables
-// char[] enclosingTypeName = binaryType.getEnclosingTypeName();
-// if (enclosingTypeName != null) {
-// // attempt to find the enclosing type if it exists in the cache (otherwise - resolve it when requested)
-// this.enclosingType = environment.getTypeFromConstantPoolName(enclosingTypeName, 0, -1, true); // pretend parameterized to avoid raw
-// this.tagBits |= TagBits.MemberTypeMask; // must be a member type not a top-level or local type
-// this.tagBits |= TagBits.HasUnresolvedEnclosingType;
-// if (this.enclosingType().isStrictfp())
-// this.modifiers |= ClassFileConstants.AccStrictfp;
-// if (this.enclosingType().isDeprecated())
-// this.modifiers |= ExtraCompilerModifiers.AccDeprecatedImplicitly;
-// }
-}
-
-public FieldBinding[] availableFields() {
- if ((this.tagBits & TagBits.AreFieldsComplete) != 0)
- return fields;
-
- // 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;
- }
- FieldBinding[] availableFields = new FieldBinding[fields.length];
- int count = 0;
- for (int i = 0; i < fields.length; i++) {
- try {
- availableFields[count] = resolveTypeFor(fields[i]);
- count++;
- } catch (AbortCompilation a){
- // silent abort
- }
- }
- if (count < availableFields.length)
- System.arraycopy(availableFields, 0, availableFields = new FieldBinding[count], 0, count);
- return availableFields;
-}
-public MethodBinding[] availableMethods() {
- if ((this.tagBits & TagBits.AreMethodsComplete) != 0)
- return 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[] availableMethods = new MethodBinding[methods.length];
- int count = 0;
- for (int i = 0; i < methods.length; i++) {
- try {
- availableMethods[count] = resolveTypesFor(methods[i]);
- count++;
- } catch (AbortCompilation a){
- // silent abort
- }
- }
- if (count < availableMethods.length)
- System.arraycopy(availableMethods, 0, availableMethods = new MethodBinding[count], 0, count);
- return availableMethods;
-}
-void cachePartsFrom(ISourceType binaryType, boolean needFieldsAndMethods) {
- // must retrieve member types in case superclass/interfaces need them
- this.memberTypes = Binding.NO_MEMBER_TYPES;
- ISourceType[] memberTypeStructures = binaryType.getMemberTypes();
- if (memberTypeStructures != null) {
- int size = memberTypeStructures.length;
- if (size > 0) {
- this.memberTypes = new ReferenceBinding[size];
- for (int i = 0; i < size; i++)
- // attempt to find each member type if it exists in the cache (otherwise - resolve it when requested)
- this.memberTypes[i] = environment.getTypeFromConstantPoolName(memberTypeStructures[i].getName(), 0, -1, false);
- this.tagBits |= TagBits.HasUnresolvedMemberTypes;
- }
- }
-
- long sourceLevel = environment.globalOptions.sourceLevel;
- char[] typeSignature = null;
-// if (sourceLevel >= ClassFileConstants.JDK1_5) {
-// typeSignature = binaryType.getGenericSignature();
-// this.tagBits |= binaryType.getTagBits();
-// }
- if (typeSignature == null) {
- char[] superclassName = binaryType.getSuperclassName();
- if (superclassName != null) {
- // attempt to find the superclass if it exists in the cache (otherwise - resolve it when requested)
- this.superclass = environment.getTypeFromConstantPoolName(superclassName, 0, -1, false);
- this.tagBits |= TagBits.HasUnresolvedSuperclass;
- }
- } else {
- // ClassSignature = ParameterPart(optional) super_TypeSignature interface_signature
- SignatureWrapper wrapper = new SignatureWrapper(typeSignature);
- if (wrapper.signature[wrapper.start] == '<') {
- // ParameterPart = '<' ParameterSignature(s) '>'
- wrapper.start++; // skip '<'
- wrapper.start++; // skip '>'
- this.tagBits |= TagBits.HasUnresolvedTypeVariables;
- }
-
- // attempt to find the superclass if it exists in the cache (otherwise - resolve it when requested)
- this.superclass = (ReferenceBinding) environment.getTypeFromTypeSignature(wrapper, this);
- this.tagBits |= TagBits.HasUnresolvedSuperclass;
- }
-
- if (needFieldsAndMethods) {
- createFields(binaryType.getFields(), sourceLevel);
- createMethods(binaryType.getMethods(), sourceLevel);
- } else { // protect against incorrect use of the needFieldsAndMethods flag, see 48459
- this.fields = Binding.NO_FIELDS;
- this.methods = Binding.NO_METHODS;
- }
-// if (this.environment.globalOptions.storeAnnotations)
-// setAnnotations(createAnnotations(binaryType.getAnnotations(), this.environment));
-}
-private void createFields(ISourceField[] iFields, long sourceLevel) {
- this.fields = Binding.NO_FIELDS;
- if (iFields != null) {
- int size = iFields.length;
- if (size > 0) {
- this.fields = new FieldBinding[size];
-// boolean use15specifics = sourceLevel >= ClassFileConstants.JDK1_5;
- boolean isViewedAsDeprecated = isViewedAsDeprecated();
- boolean hasRestrictedAccess = hasRestrictedAccess();
-// int firstAnnotatedFieldIndex = -1;
- for (int i = 0; i < size; i++) {
- ISourceField binaryField = iFields[i];
- char[] fieldSignature = null;//use15specifics ? binaryField.getGenericSignature() : null;
- TypeBinding type = fieldSignature == null
- ? environment.getTypeFromSignature(binaryField.getTypeName(), 0, -1, false, this)
- : environment.getTypeFromTypeSignature(new SignatureWrapper(fieldSignature), this);
- FieldBinding field =
- new FieldBinding(
-// binaryField.getName(),
- ((SourceField)binaryField).getElementName ().toCharArray(),
- type,
- binaryField.getModifiers() | ExtraCompilerModifiers.AccUnresolved,
- this);
-// if (firstAnnotatedFieldIndex < 0
-// && this.environment.globalOptions.storeAnnotations
-// && binaryField.getAnnotations() != null) {
-// firstAnnotatedFieldIndex = i;
-// }
- field.id = i; // ordinal
-// if (use15specifics)
-// field.tagBits |= binaryField.getTagBits();
- if (isViewedAsDeprecated && !field.isDeprecated())
- field.modifiers |= ExtraCompilerModifiers.AccDeprecatedImplicitly;
- if (hasRestrictedAccess)
- field.modifiers |= ExtraCompilerModifiers.AccRestrictedAccess;
- this.fields[i] = field;
- }
- // second pass for reifying annotations, since may refer to fields being constructed (147875)
-// if (firstAnnotatedFieldIndex >= 0) {
-// for (int i = firstAnnotatedFieldIndex; i <size; i++) {
-// this.fields[i].setAnnotations(createAnnotations(iFields[i].getAnnotations(), this.environment));
-// }
-// }
- }
- }
-}
-private MethodBinding createMethod(ISourceMethod method, long sourceLevel) {
- int methodModifiers = method.getModifiers() | ExtraCompilerModifiers.AccUnresolved;
- if (sourceLevel < ClassFileConstants.JDK1_5)
- methodModifiers &= ~ClassFileConstants.AccVarargs; // vararg methods are not recognized until 1.5
-// ReferenceBinding[] exceptions = Binding.NO_EXCEPTIONS;
-// TypeBinding[] parameters = Binding.NO_PARAMETERS;
-// TypeVariableBinding[] typeVars = Binding.NO_TYPE_VARIABLES;
-// AnnotationBinding[][] paramAnnotations = null;
-// TypeBinding returnType = null;
-
- throw new UnimplementedException("fix compile errors for this code"); //$NON-NLS-1$
-// final boolean use15specifics = sourceLevel >= ClassFileConstants.JDK1_5;
-// char[] methodSignature = use15specifics ? method.getGenericSignature() : null;
-// if (methodSignature == null) { // no generics
-// char[] methodDescriptor = method.getMethodDescriptor(); // of the form (I[Ljava/jang/String;)V
-// int numOfParams = 0;
-// char nextChar;
-// int index = 0; // first character is always '(' so skip it
-// while ((nextChar = methodDescriptor[++index]) != ')') {
-// if (nextChar != '[') {
-// numOfParams++;
-// if (nextChar == 'L')
-// while ((nextChar = methodDescriptor[++index]) != ';'){/*empty*/}
-// }
-// }
-//
-// // Ignore synthetic argument for member types.
-// int startIndex = (method.isConstructor() && isMemberType() && !isStatic()) ? 1 : 0;
-// int size = numOfParams - startIndex;
-// if (size > 0) {
-// parameters = new TypeBinding[size];
-// if (this.environment.globalOptions.storeAnnotations)
-// paramAnnotations = new AnnotationBinding[size][];
-// index = 1;
-// int end = 0; // first character is always '(' so skip it
-// for (int i = 0; i < numOfParams; i++) {
-// while ((nextChar = methodDescriptor[++end]) == '['){/*empty*/}
-// if (nextChar == 'L')
-// while ((nextChar = methodDescriptor[++end]) != ';'){/*empty*/}
-//
-// if (i >= startIndex) { // skip the synthetic arg if necessary
-// parameters[i - startIndex] = environment.getTypeFromSignature(methodDescriptor, index, end, false, this);
-// // 'paramAnnotations' line up with 'parameters'
-// // int parameter to method.getParameterAnnotations() include the synthetic arg
-// if (paramAnnotations != null)
-// paramAnnotations[i - startIndex] = createAnnotations(method.getParameterAnnotations(i), this.environment);
-// }
-// index = end + 1;
-// }
-// }
-//
-// char[][] exceptionTypes = method.getExceptionTypeNames();
-// if (exceptionTypes != null) {
-// size = exceptionTypes.length;
-// if (size > 0) {
-// exceptions = new ReferenceBinding[size];
-// for (int i = 0; i < size; i++)
-// exceptions[i] = environment.getTypeFromConstantPoolName(exceptionTypes[i], 0, -1, false);
-// }
-// }
-//
-// if (!method.isConstructor())
-// returnType = environment.getTypeFromSignature(methodDescriptor, index + 1, -1, false, this); // index is currently pointing at the ')'
-// } else {
-// methodModifiers |= ExtraCompilerModifiers.AccGenericSignature;
-// // MethodTypeSignature = ParameterPart(optional) '(' TypeSignatures ')' return_typeSignature ['^' TypeSignature (optional)]
-// SignatureWrapper wrapper = new SignatureWrapper(methodSignature);
-// if (wrapper.signature[wrapper.start] == '<') {
-// // <A::Ljava/lang/annotation/Annotation;>(Ljava/lang/Class<TA;>;)TA;
-// // ParameterPart = '<' ParameterSignature(s) '>'
-// wrapper.start++; // skip '<'
-// typeVars = createTypeVariables(wrapper, false);
-// wrapper.start++; // skip '>'
-// }
-//
-// if (wrapper.signature[wrapper.start] == '(') {
-// wrapper.start++; // skip '('
-// if (wrapper.signature[wrapper.start] == ')') {
-// wrapper.start++; // skip ')'
-// } else {
-// java.util.ArrayList types = new java.util.ArrayList(2);
-// while (wrapper.signature[wrapper.start] != ')')
-// types.add(environment.getTypeFromTypeSignature(wrapper, typeVars, this));
-// wrapper.start++; // skip ')'
-// int numParam = types.size();
-// parameters = new TypeBinding[numParam];
-// types.toArray(parameters);
-// if (this.environment.globalOptions.storeAnnotations) {
-// paramAnnotations = new AnnotationBinding[numParam][];
-// for (int i = 0; i < numParam; i++)
-// paramAnnotations[i] = createAnnotations(method.getParameterAnnotations(i), this.environment);
-// }
-// }
-// }
-//
-// if (!method.isConstructor())
-// returnType = environment.getTypeFromTypeSignature(wrapper, typeVars, this);
-//
-// if (!wrapper.atEnd() && wrapper.signature[wrapper.start] == '^') {
-// // attempt to find each superinterface if it exists in the cache (otherwise - resolve it when requested)
-// java.util.ArrayList types = new java.util.ArrayList(2);
-// do {
-// wrapper.start++; // skip '^'
-// types.add(environment.getTypeFromTypeSignature(wrapper, typeVars, this));
-// } while (!wrapper.atEnd() && wrapper.signature[wrapper.start] == '^');
-// exceptions = new ReferenceBinding[types.size()];
-// types.toArray(exceptions);
-// } else { // get the exceptions the old way
-// char[][] exceptionTypes = method.getExceptionTypeNames();
-// if (exceptionTypes != null) {
-// int size = exceptionTypes.length;
-// if (size > 0) {
-// exceptions = new ReferenceBinding[size];
-// for (int i = 0; i < size; i++)
-// exceptions[i] = environment.getTypeFromConstantPoolName(exceptionTypes[i], 0, -1, false);
-// }
-// }
-// }
-// }
-//
-// FunctionBinding result = method.isConstructor()
-// ? new FunctionBinding(methodModifiers, parameters, exceptions, this)
-// : new FunctionBinding(methodModifiers, method.getSelector(), returnType, parameters, exceptions, this);
-// if (this.environment.globalOptions.storeAnnotations)
-// result.setAnnotations(
-// createAnnotations(method.getAnnotations(), this.environment),
-// paramAnnotations,
-// isAnnotationType() ? convertMemberValue(method.getDefaultValue(), this.environment) : null);
-//
-// if (use15specifics)
-// result.tagBits |= method.getTagBits();
-// result.typeVariables = typeVars;
-// // fixup the declaring element of the type variable
-// for (int i = 0, length = typeVars.length; i < length; i++)
-// typeVars[i].declaringElement = result;
-// return result;
-}
-/**
- * Create method bindings for binary type, filtering out <clinit> and synthetics
- */
-private void createMethods(ISourceMethod[] iMethods, long sourceLevel) {
- int total = 0, initialTotal = 0, iClinit = -1;
- int[] toSkip = null;
- if (iMethods != null) {
- total = initialTotal = iMethods.length;
- boolean keepBridgeMethods = sourceLevel < ClassFileConstants.JDK1_5
- && this.environment.globalOptions.complianceLevel >= ClassFileConstants.JDK1_5;
- for (int i = total; --i >= 0;) {
- ISourceMethod method = iMethods[i];
- if (iClinit == -1) {
- char[] methodName =((SourceMethod)method).getElementName().toCharArray();
- if (methodName.length == 8 && methodName[0] == '<') {
- // discard <clinit>
- iClinit = i;
- total--;
- }
- }
- }
- }
- if (total == 0) {
- this.methods = Binding.NO_METHODS;
- return;
- }
-
- boolean isViewedAsDeprecated = isViewedAsDeprecated();
- boolean hasRestrictedAccess = hasRestrictedAccess();
- this.methods = new MethodBinding[total];
- if (total == initialTotal) {
- for (int i = 0; i < initialTotal; i++) {
- MethodBinding method = createMethod(iMethods[i], sourceLevel);
- if (isViewedAsDeprecated && !method.isDeprecated())
- method.modifiers |= ExtraCompilerModifiers.AccDeprecatedImplicitly;
- if (hasRestrictedAccess)
- method.modifiers |= ExtraCompilerModifiers.AccRestrictedAccess;
- this.methods[i] = method;
- }
- } else {
- for (int i = 0, index = 0; i < initialTotal; i++) {
- if (iClinit != i && (toSkip == null || toSkip[i] != -1)) {
- MethodBinding method = createMethod(iMethods[i], sourceLevel);
- if (isViewedAsDeprecated && !method.isDeprecated())
- method.modifiers |= ExtraCompilerModifiers.AccDeprecatedImplicitly;
- if (hasRestrictedAccess)
- method.modifiers |= ExtraCompilerModifiers.AccRestrictedAccess;
- this.methods[index++] = method;
- }
- }
- }
-}
-/* Answer the receiver's enclosing type... null if the receiver is a top level type.
-*
-* NOTE: enclosingType of a binary type is resolved when needed
-*/
-public ReferenceBinding enclosingType() {
- if ((this.tagBits & TagBits.HasUnresolvedEnclosingType) == 0)
- return this.enclosingType;
-
- // finish resolving the type
- this.enclosingType = resolveType(this.enclosingType, this.environment, false);
- this.tagBits &= ~TagBits.HasUnresolvedEnclosingType;
- return this.enclosingType;
-}
-// NOTE: the type of each field of a binary type is resolved when needed
-public FieldBinding[] fields() {
- if ((this.tagBits & TagBits.AreFieldsComplete) != 0)
- return fields;
-
- // 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 = fields.length; --i >= 0;)
- resolveTypeFor(fields[i]);
- this.tagBits |= TagBits.AreFieldsComplete;
- return fields;
-}
-//NOTE: the return type, arg & exception types of each method of a binary type are resolved when needed
-public MethodBinding getExactConstructor(TypeBinding[] argumentTypes) {
-
- // 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 argCount = argumentTypes.length;
- 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 = methods[imethod];
- if (method.parameters.length == argCount) {
- resolveTypesFor(method);
- TypeBinding[] toMatch = method.parameters;
- for (int iarg = 0; iarg < argCount; iarg++)
- if (toMatch[iarg] != argumentTypes[iarg])
- continue nextMethod;
- return method;
- }
- }
- }
- return null;
-}
-
-//NOTE: the return type, arg & exception types of each method of a binary type are resolved when needed
-//searches up the hierarchy as long as no potential (but not exact) match was found.
-public MethodBinding getExactMethod(char[] selector, TypeBinding[] argumentTypes, CompilationUnitScope refScope) {
- // sender from refScope calls recordTypeReference(this)
-
- // 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 argCount = argumentTypes.length;
- boolean foundNothing = true;
-
- 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 = methods[imethod];
- foundNothing = false; // inner type lookups must know that a method with this name exists
- if (method.parameters.length == argCount) {
- resolveTypesFor(method);
- TypeBinding[] toMatch = method.parameters;
- for (int iarg = 0; iarg < argCount; iarg++)
- if (toMatch[iarg] != argumentTypes[iarg])
- continue nextMethod;
- return method;
- }
- }
- }
- if (foundNothing) {
- if (superclass() != null) { // ensure superclass is resolved before checking
- if (refScope != null)
- refScope.recordTypeReference(superclass);
- return superclass.getExactMethod(selector, argumentTypes, refScope);
- }
- }
- return null;
-}
-//NOTE: the type of a field of a binary type is resolved when needed
-public FieldBinding getField(char[] fieldName, boolean needResolve) {
- // 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;
- }
- FieldBinding field = ReferenceBinding.binarySearch(fieldName, this.fields);
- return needResolve && field != null ? resolveTypeFor(field) : field;
-}
-/**
- * Rewrite of default getMemberType to avoid resolving eagerly all member types when one is requested
- */
-public ReferenceBinding getMemberType(char[] typeName) {
- for (int i = this.memberTypes.length; --i >= 0;) {
- ReferenceBinding memberType = this.memberTypes[i];
- if (memberType instanceof UnresolvedReferenceBinding) {
- char[] name = memberType.sourceName; // source name is qualified with enclosing type name
- int prefixLength = this.compoundName[this.compoundName.length - 1].length + 1; // enclosing$
- if (name.length == (prefixLength + typeName.length)) // enclosing $ typeName
- if (CharOperation.fragmentEquals(typeName, name, prefixLength, true)) // only check trailing portion
- return this.memberTypes[i] = resolveType(memberType, this.environment, false); // no raw conversion for now
- } else if (CharOperation.equals(typeName, memberType.sourceName)) {
- return memberType;
- }
- }
- return null;
-}
-// NOTE: the return type, arg & exception types of each method of a binary type are resolved when needed
-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;
- if ((this.tagBits & TagBits.AreMethodsComplete) != 0) {
- // simply clone method subset
- MethodBinding[] result;
- System.arraycopy(this.methods, start, result = new MethodBinding[length], 0, length);
- return result;
- }
- }
- 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;
- }
- 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 = new MethodBinding[length];
- // iterate methods to resolve them
- for (int i = start, index = 0; i <= end; i++, index++)
- result[index] = resolveTypesFor(methods[i]);
- return result;
- }
- return Binding.NO_METHODS;
-}
-public boolean hasMemberTypes() {
- return this.memberTypes.length > 0;
-}
-/**
- * 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 int kind() {
- return Binding.TYPE;
-}
-// NOTE: member types of binary types are resolved when needed
-public ReferenceBinding[] memberTypes() {
- if ((this.tagBits & TagBits.HasUnresolvedMemberTypes) == 0)
- return this.memberTypes;
-
- for (int i = this.memberTypes.length; --i >= 0;)
- this.memberTypes[i] = resolveType(this.memberTypes[i], this.environment, false); // no raw conversion for now
- this.tagBits &= ~TagBits.HasUnresolvedMemberTypes;
- return this.memberTypes;
-}
-// NOTE: the return type, arg & exception types of each method of a binary type are resolved when needed
-public MethodBinding[] methods() {
- if ((this.tagBits & TagBits.AreMethodsComplete) != 0)
- return 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;
- }
- for (int i = methods.length; --i >= 0;)
- resolveTypesFor(methods[i]);
- this.tagBits |= TagBits.AreMethodsComplete;
- return methods;
-}
-private FieldBinding resolveTypeFor(FieldBinding field) {
- if ((field.modifiers & ExtraCompilerModifiers.AccUnresolved) == 0)
- return field;
-
- field.type = resolveType(field.type, this.environment, 0);
- field.modifiers &= ~ExtraCompilerModifiers.AccUnresolved;
- return field;
-}
-MethodBinding resolveTypesFor(MethodBinding method) {
- if ((method.modifiers & ExtraCompilerModifiers.AccUnresolved) == 0)
- return method;
-
- if (!method.isConstructor())
- method.returnType = resolveType(method.returnType, this.environment, 0);
- for (int i = method.parameters.length; --i >= 0;)
- method.parameters[i] = resolveType(method.parameters[i], this.environment, 0);
- method.modifiers &= ~ExtraCompilerModifiers.AccUnresolved;
- return method;
-}
-
-/* Answer the receiver's superclass... null if the receiver is Object or an interface.
-*
-* NOTE: superclass of a binary type is resolved when needed
-*/
-public ReferenceBinding superclass() {
- if ((this.tagBits & TagBits.HasUnresolvedSuperclass) == 0)
- return this.superclass;
-
- // finish resolving the type
- this.superclass = resolveType(this.superclass, this.environment, true);
- this.tagBits &= ~TagBits.HasUnresolvedSuperclass;
- if (this.superclass == null || this.superclass.problemId() == ProblemReasons.NotFound)
- this.tagBits |= TagBits.HierarchyHasProblems; // propagate type inconsistency
- return this.superclass;
-}
-
-public String toString() {
- StringBuffer buffer = new StringBuffer();
-
- 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((compoundName != null) ? CharOperation.toString(compoundName) : "UNNAMED TYPE"); //$NON-NLS-1$
-
- buffer.append("\n\textends "); //$NON-NLS-1$
- buffer.append((superclass != null) ? superclass.debugName() : "NULL TYPE"); //$NON-NLS-1$
-
- if (enclosingType != null) {
- buffer.append("\n\tenclosing type : "); //$NON-NLS-1$
- buffer.append(enclosingType.debugName());
- }
-
- if (fields != null) {
- if (fields != Binding.NO_FIELDS) {
- buffer.append("\n/* fields */"); //$NON-NLS-1$
- for (int i = 0, length = fields.length; i < length; i++)
- buffer.append((fields[i] != null) ? "\n" + fields[i].toString() : "\nNULL FIELD"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- } else {
- buffer.append("NULL FIELDS"); //$NON-NLS-1$
- }
-
- if (methods != null) {
- if (methods != Binding.NO_METHODS) {
- buffer.append("\n/* methods */"); //$NON-NLS-1$
- for (int i = 0, length = methods.length; i < length; i++)
- buffer.append((methods[i] != null) ? "\n" + methods[i].toString() : "\nNULL METHOD"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- } else {
- buffer.append("NULL METHODS"); //$NON-NLS-1$
- }
-
- if (memberTypes != null) {
- if (memberTypes != Binding.NO_MEMBER_TYPES) {
- buffer.append("\n/* members */"); //$NON-NLS-1$
- for (int i = 0, length = memberTypes.length; i < length; i++)
- buffer.append((memberTypes[i] != null) ? "\n" + memberTypes[i].toString() : "\nNULL TYPE"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- } else {
- buffer.append("NULL MEMBER TYPES"); //$NON-NLS-1$
- }
-
- buffer.append("\n\n\n"); //$NON-NLS-1$
- return buffer.toString();
-}
-MethodBinding[] unResolvedMethods() { // for the MethodVerifier so it doesn't resolve types
- return methods;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/Binding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/Binding.java
deleted file mode 100644
index 0a012c1f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/Binding.java
+++ /dev/null
@@ -1,84 +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.compiler.lookup;
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode;
-
-public abstract class Binding {
-
- // binding kinds
- public static final int FIELD = ASTNode.Bit1;
- public static final int LOCAL = ASTNode.Bit2;
- public static final int VARIABLE = FIELD | LOCAL;
- public static final int TYPE = ASTNode.Bit3;
- public static final int METHOD = ASTNode.Bit4;
- public static final int PACKAGE = ASTNode.Bit15;
- public static final int IMPORT = ASTNode.Bit6;
- public static final int ARRAY_TYPE = TYPE | ASTNode.Bit7;
- public static final int BASE_TYPE = TYPE | ASTNode.Bit8;
- public static final int GLOBAL = ASTNode.Bit9;
- public static final int COMPILATION_UNIT = ASTNode.Bit14;
-
- public static final int BASIC_BINDINGS_MASK= METHOD|TYPE|VARIABLE;
- public static final int NUMBER_BASIC_BINDING= (METHOD+TYPE+VARIABLE)+1;
-
- // Shared binding collections
- public static final TypeBinding[] NO_TYPES = new TypeBinding[0];
- public static final TypeBinding[] NO_PARAMETERS = new TypeBinding[0];
- public static final ReferenceBinding[] NO_EXCEPTIONS = new ReferenceBinding[0];
- public static final ReferenceBinding[] ANY_EXCEPTION = new ReferenceBinding[] { null }; // special handler for all exceptions
- public static final FieldBinding[] NO_FIELDS = new FieldBinding[0];
- public static final MethodBinding[] NO_METHODS = new MethodBinding[0];
- public static final ReferenceBinding[] NO_MIXINS = new ReferenceBinding[0];
- public static final ReferenceBinding[] NO_MEMBER_TYPES = new ReferenceBinding[0];
-
- /*
- * Answer the receiver's binding type from Binding.BindingID.
- */
- public abstract int kind();
- /*
- * Computes a key that uniquely identifies this binding.
- * Returns null if binding is not a TypeBinding, a FunctionBinding, a FieldBinding or a PackageBinding.
- */
- public char[] computeUniqueKey() {
- return computeUniqueKey(true/*leaf*/);
- }
- /*
- * Computes a key that uniquely identifies this binding. Optinaly include access flags.
- * Returns null if binding is not a TypeBinding, a FunctionBinding, a FieldBinding or a PackageBinding.
- */
- public char[] computeUniqueKey(boolean isLeaf) {
- return null;
- }
-
- /* API
- * Answer true if the receiver is not a problem binding
- */
- public final boolean isValidBinding() {
- return problemId() == ProblemReasons.NoError;
- }
- /* API
- * Answer the problem id associated with the receiver.
- * NoError if the receiver is a valid binding.
- */
- // TODO (philippe) should rename into problemReason()
- public int problemId() {
- return ProblemReasons.NoError;
- }
- /* Answer a printable representation of the receiver.
- */
- public abstract char[] readableName();
- /* Shorter printable representation of the receiver (no qualified type)
- */
- public char[] shortReadableName(){
- return readableName();
- }
-}
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
deleted file mode 100644
index 9d41c6f4..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/BlockScope.java
+++ /dev/null
@@ -1,816 +0,0 @@
-/*******************************************************************************
- * 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
- * David Thompson = bug 214171 -Class cast exception
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.lookup;
-
-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.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;
-import org.eclipse.wst.jsdt.internal.compiler.problem.ProblemReporter;
-
-public class BlockScope extends Scope {
-
- // Local variable management
- public LocalVariableBinding[] locals;
- public MethodBinding[] methods;
- public int numberMethods; // for variable allocation throughout scopes
- public int localIndex; // position for next variable
- public int startIndex; // start position in this scope - for ordering scopes vs. variables
- public int offset; // for variable allocation throughout scopes
- public int maxOffset; // for variable allocation throughout scopes
-
- // finally scopes must be shifted behind respective try&catch scope(s) so as to avoid
- // collisions of secret variables (return address, save value).
- public BlockScope[] shiftScopes;
-
- public Scope[] subscopes = new Scope[1]; // need access from code assist
- public int subscopeCount = 0; // need access from code assist
- // 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);
-}
-
-public BlockScope(BlockScope parent, boolean addToParentScope) {
- this(Scope.BLOCK_SCOPE, parent);
- this.locals = new LocalVariableBinding[5];
- this.methods=new MethodBinding[5];
- if (addToParentScope) parent.addSubscope(this);
- this.startIndex = parent.localIndex;
-}
-
-public BlockScope(BlockScope parent, int variableCount) {
- this(Scope.BLOCK_SCOPE, parent);
- this.locals = new LocalVariableBinding[variableCount];
- this.methods=new MethodBinding[5];
- parent.addSubscope(this);
- this.startIndex = parent.localIndex;
-}
-
-protected BlockScope(int kind, Scope parent) {
- super(kind, parent);
- this.locals = new LocalVariableBinding[5];
- this.methods=new MethodBinding[5];
-}
-
-/* Create the class scope & binding for the anonymous type.
- */
-public final void addAnonymousType(TypeDeclaration anonymousType, ReferenceBinding superBinding) {
- ClassScope anonymousClassScope = new ClassScope(this, anonymousType);
- anonymousClassScope.buildAnonymousTypeBinding(
- enclosingSourceType(),
- superBinding);
-}
-
-/* Create the class scope & binding for the local type.
- */
-public final void addLocalType(TypeDeclaration localType) {
- ClassScope localTypeScope = new ClassScope(this, localType);
- addSubscope(localTypeScope);
- localTypeScope.buildLocalTypeBinding(enclosingSourceType());
-}
-
-/* Insert a local variable into a given scope, updating its position
- * 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(
- this.locals,
- 0,
- (this.locals = new LocalVariableBinding[this.localIndex * 2]),
- 0,
- this.localIndex);
- this.locals[this.localIndex++] = binding;
-
- // update local variable binding
- binding.declaringScope = this;
-
- 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;
-}
-
-
-public void addSubscope(Scope childScope) {
- if (this.subscopeCount == this.subscopes.length)
- System.arraycopy(
- this.subscopes,
- 0,
- (this.subscopes = new Scope[this.subscopeCount * 2]),
- 0,
- this.subscopeCount);
- this.subscopes[this.subscopeCount++] = childScope;
-}
-
-/* Answer true if the receiver is suitable for assigning final blank fields.
- *
- * in other words, it is inside an initializer, a constructor or a clinit
- */
-public final boolean allowBlankFinalFieldAssignment(FieldBinding binding) {
- if (enclosingReceiverType() != binding.declaringClass)
- return false;
-
- MethodScope methodScope = methodScope();
- if (methodScope.isStatic != binding.isStatic())
- return false;
- return methodScope.isInsideInitializer() // inside initializer
- || ((AbstractMethodDeclaration) methodScope.referenceContext).isInitializationMethod(); // inside constructor or clinit
-}
-String basicToString(int tab) {
- String newLine = "\n"; //$NON-NLS-1$
- for (int i = tab; --i >= 0;)
- newLine += "\t"; //$NON-NLS-1$
-
- String s = newLine + "--- Block Scope ---"; //$NON-NLS-1$
- newLine += "\t"; //$NON-NLS-1$
- s += newLine + "locals:"; //$NON-NLS-1$
- for (int i = 0; i < this.localIndex; i++)
- s += newLine + "\t" + this.locals[i].toString(); //$NON-NLS-1$
- s += newLine + "startIndex = " + this.startIndex; //$NON-NLS-1$
- 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)
- for (int i = 0; i < localIndex; i++) {
- LocalVariableBinding local = this.locals[i]; // if no local at all, will be locals[ilocal]==null
-
-
- // do not report fake used variable
- if (local.useFlag == LocalVariableBinding.UNUSED
- && (local.declaration != null) // unused (and non secret) local
- && ((local.declaration.bits & ASTNode.IsLocalDeclarationReachable) != 0)) { // declaration is reachable
-
- if (!(local.declaration instanceof Argument)) // do not report unused catch arguments
- this.problemReporter().unusedLocalVariable(local.declaration);
- }
-
-
- }
-}
-
-
-/*
- * Record the suitable binding denoting a synthetic field or constructor argument,
- * mapping to the actual outer local variable in the scope context.
- * Note that this may not need any effect, in case the outer local variable does not
- * need to be emulated and can directly be used as is (using its back pointer to its
- * declaring scope).
- */
-public void emulateOuterAccess(LocalVariableBinding outerLocalVariable) {
- BlockScope outerVariableScope = outerLocalVariable.declaringScope;
- if (outerVariableScope == null)
- return; // no need to further emulate as already inserted (val$this$0)
- MethodScope currentMethodScope = this.methodScope();
- if (outerVariableScope.methodScope() != currentMethodScope &&
- this.enclosingSourceType() instanceof
- NestedTypeBinding) {
- NestedTypeBinding currentType = (NestedTypeBinding) this.enclosingSourceType();
-
- //do nothing for member types, pre emulation was performed already
- if (!currentType.isLocalType()) {
- return;
- }
- }
-}
-
-/* Note that it must never produce a direct access to the targetEnclosingType,
- * but instead a field sequence (this$2.this$1.this$0) so as to handle such a test case:
- *
- * class XX {
- * void foo() {
- * class A {
- * class B {
- * class C {
- * boolean foo() {
- * return (Object) A.this == (Object) B.this;
- * }
- * }
- * }
- * }
- * new A().new B().new C();
- * }
- * }
- * where we only want to deal with ONE enclosing instance for C (could not figure out an A for C)
- */
-public final ReferenceBinding findLocalType(char[] name) {
- long compliance = compilerOptions().complianceLevel;
- for (int i = this.subscopeCount-1; i >= 0; i--) {
- if (this.subscopes[i] instanceof ClassScope) {
- LocalTypeBinding sourceType = (LocalTypeBinding)((ClassScope) this.subscopes[i]).getReferenceBinding();
- // from 1.4 on, local types should not be accessed across switch case blocks (52221)
- if (compliance >= ClassFileConstants.JDK1_4 && sourceType.enclosingCase != null) {
- if (!this.isInsideCase(sourceType.enclosingCase)) {
- continue;
- }
- }
- if (CharOperation.equals(sourceType.sourceName(), name))
- return sourceType;
- }
- }
- return null;
-}
-public MethodBinding findMethod(char[] methodName,TypeBinding[]argumentTypes, boolean checkVars) {
- int methodLength = methodName.length;
- 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))
- return method;
- }
- if (checkVars)
- {
- LocalVariableBinding variable = findVariable(methodName);
- if (variable!=null)
- {
- MethodBinding binding;
- if (!(variable.type.isAnyType() || variable.type.isFunctionType()))
- {
- binding=new ProblemMethodBinding(methodName,null,ProblemReasons.NotAFunction);
- }
- else
- binding = new MethodBinding(ClassFileConstants.AccPublic,
- methodName,TypeBinding.UNKNOWN,null,variable.declaringScope.enclosingTypeBinding());
-
- addLocalMethod(binding);
- return binding;
- }
- }
- return null;
-}
-
-
-/**
- * Returns all declarations of most specific locals containing a given position in their source range.
- * This code does not recurse in nested types.
- * Returned array may have null values at trailing indexes.
- */
-public LocalDeclaration[] findLocalVariableDeclarations(int position) {
- // local variable init
- int ilocal = 0, maxLocals = this.localIndex;
- boolean hasMoreVariables = maxLocals > 0;
- LocalDeclaration[] localDeclarations = null;
- int declPtr = 0;
-
- // scope init
- int iscope = 0, maxScopes = this.subscopeCount;
- boolean hasMoreScopes = maxScopes > 0;
-
- // iterate scopes and variables in parallel
- while (hasMoreVariables || hasMoreScopes) {
- if (hasMoreScopes
- && (!hasMoreVariables || (this.subscopes[iscope].startIndex() <= ilocal))) {
- // consider subscope first
- Scope subscope = this.subscopes[iscope];
- if (subscope.kind == Scope.BLOCK_SCOPE) { // do not dive in nested types
- localDeclarations = ((BlockScope)subscope).findLocalVariableDeclarations(position);
- if (localDeclarations != null) {
- return localDeclarations;
- }
- }
- hasMoreScopes = ++iscope < maxScopes;
- } else {
- // consider variable first
- LocalVariableBinding local = this.locals[ilocal]; // if no local at all, will be locals[ilocal]==null
- if (local != null) {
- LocalDeclaration localDecl = local.declaration;
- if (localDecl != null) {
- if (localDecl.declarationSourceStart <= position) {
- if (position <= localDecl.declarationSourceEnd) {
- if (localDeclarations == null) {
- localDeclarations = new LocalDeclaration[maxLocals];
- }
- localDeclarations[declPtr++] = localDecl;
- }
- } else {
- return localDeclarations;
- }
- }
- }
- hasMoreVariables = ++ilocal < maxLocals;
- if (!hasMoreVariables && localDeclarations != null) {
- return localDeclarations;
- }
- }
- }
- return null;
-}
-
-public LocalVariableBinding findVariable(char[] variableName) {
- int varLength = variableName.length;
- for (int i = this.localIndex-1; i >= 0; i--) { // lookup backward to reach latest additions first
- LocalVariableBinding local;
- char[] localName;
- if ((localName = (local = this.locals[i]).name).length == varLength && CharOperation.equals(localName, variableName))
- return local;
- }
- return null;
-}
-
-/* API
- * flag is a mask of the following values VARIABLE (= FIELD or LOCAL), TYPE.
- * Only bindings corresponding to the mask will be answered.
- *
- * if the VARIABLE mask is set then
- * If the first name provided is a field (or local) then the field (or local) is answered
- * Otherwise, package names and type names are consumed until a field is found.
- * In this case, the field is answered.
- *
- * if the TYPE mask is set,
- * package names and type names are consumed until the end of the input.
- * Only if all of the input is consumed is the type answered
- *
- * All other conditions are errors, and a problem binding is returned.
- *
- * NOTE: If a problem binding is returned, senders should extract the compound name
- * from the binding & not assume the problem applies to the entire compoundName.
- *
- * The VARIABLE mask has precedence over the TYPE mask.
- *
- * InvocationSite implements
- * isSuperAccess(); this is used to determine if the discovered field is visible.
- * setFieldIndex(int); this is used to record the number of names that were consumed.
- *
- * For example, getBinding({"foo","y","q", VARIABLE, site) will answer
- * the binding for the field or local named "foo" (or an error binding if none exists).
- * In addition, setFieldIndex(1) will be sent to the invocation site.
- * If a type named "foo" exists, it will not be detected (and an error binding will be answered)
- *
- * IMPORTANT NOTE: This method is written under the assumption that compoundName is longer than length 1.
- */
-public Binding getBinding(char[][] compoundName, int mask, InvocationSite invocationSite, boolean needResolve) {
- Binding binding = getBinding(compoundName[0], mask | Binding.TYPE | Binding.PACKAGE, invocationSite, needResolve);
- invocationSite.setFieldIndex(1);
- if (binding instanceof VariableBinding) return binding;
- CompilationUnitScope unitScope = compilationUnitScope();
- // in the problem case, we want to ensure we record the qualified dependency in case a type is added
- // and we do not know that its package was also added (can happen with validationParticipants)
- unitScope.recordQualifiedReference(compoundName);
- if (!binding.isValidBinding()) return binding;
-
- int length = compoundName.length;
- int currentIndex = 1;
- foundType : if (binding instanceof PackageBinding) {
- PackageBinding packageBinding = (PackageBinding) binding;
- while (currentIndex < length) {
- unitScope.recordReference(packageBinding.compoundName, compoundName[currentIndex]);
- binding = packageBinding.getTypeOrPackage(compoundName[currentIndex++], mask);
- invocationSite.setFieldIndex(currentIndex);
- if (binding == null) {
- if (currentIndex == length) {
- // must be a type if its the last name, otherwise we have no idea if its a package or type
- return new ProblemReferenceBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- null,
- ProblemReasons.NotFound);
- }
- return new ProblemBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- ProblemReasons.NotFound);
- }
- if (binding instanceof ReferenceBinding) {
- if (!binding.isValidBinding())
- return new ProblemReferenceBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- ((ReferenceBinding)binding).closestMatch(),
- binding.problemId());
- if (!((ReferenceBinding) binding).canBeSeenBy(this))
- return new ProblemReferenceBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- (ReferenceBinding) binding,
- ProblemReasons.NotVisible);
- break foundType;
- }
- packageBinding = (PackageBinding) binding;
- }
-
- // It is illegal to request a PACKAGE from this method.
- return new ProblemReferenceBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- null,
- ProblemReasons.NotFound);
- }
-
- // know binding is now a ReferenceBinding
- ReferenceBinding referenceBinding = (ReferenceBinding) binding;
- binding = referenceBinding;
- if (invocationSite instanceof ASTNode) {
- ASTNode invocationNode = (ASTNode) invocationSite;
- if (invocationNode.isTypeUseDeprecated(referenceBinding, this)) {
- problemReporter().deprecatedType(referenceBinding, invocationNode);
- }
- }
- while (currentIndex < length) {
- referenceBinding = (ReferenceBinding) binding;
- char[] nextName = compoundName[currentIndex++];
- invocationSite.setFieldIndex(currentIndex);
- invocationSite.setActualReceiverType(referenceBinding);
- if ((mask & Binding.FIELD) != 0 && (binding = findField(referenceBinding, nextName, invocationSite, true /*resolve*/)) != null) {
- if (!binding.isValidBinding()) {
- return new ProblemFieldBinding(
- ((ProblemFieldBinding)binding).closestMatch,
- ((ProblemFieldBinding)binding).declaringClass,
- CharOperation.concatWith(CharOperation.subarray(compoundName, 0, currentIndex), '.'),
- binding.problemId());
- }
- break; // binding is now a field
- }
- if ((binding = findMemberType(nextName, referenceBinding)) == null) {
- if ((mask & Binding.FIELD) != 0) {
- return new ProblemBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- referenceBinding,
- ProblemReasons.NotFound);
- }
- return new ProblemReferenceBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- referenceBinding,
- ProblemReasons.NotFound);
- }
- // binding is a ReferenceBinding
- if (!binding.isValidBinding())
- return new ProblemReferenceBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- ((ReferenceBinding)binding).closestMatch(),
- binding.problemId());
- if (invocationSite instanceof ASTNode) {
- referenceBinding = (ReferenceBinding) binding;
- ASTNode invocationNode = (ASTNode) invocationSite;
- if (invocationNode.isTypeUseDeprecated(referenceBinding, this)) {
- problemReporter().deprecatedType(referenceBinding, invocationNode);
- }
- }
- }
- if ((mask & Binding.FIELD) != 0 && (binding instanceof FieldBinding)) {
- // was looking for a field and found a field
- FieldBinding field = (FieldBinding) binding;
- if (!field.isStatic())
- return new ProblemFieldBinding(
- field,
- field.declaringClass,
- CharOperation.concatWith(CharOperation.subarray(compoundName, 0, currentIndex), '.'),
- ProblemReasons.NonStaticReferenceInStaticContext);
- return binding;
- }
- if ((mask & Binding.TYPE) != 0 && (binding instanceof ReferenceBinding)) {
- // was looking for a type and found a type
- return binding;
- }
-
- // handle the case when a field or type was asked for but we resolved the compoundName to a type or field
- return new ProblemBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- ProblemReasons.NotFound);
-}
-
-// Added for code assist... NOT Public API
-public final Binding getBinding(char[][] compoundName, InvocationSite invocationSite) {
- int currentIndex = 0;
- int length = compoundName.length;
- Binding binding =
- getBinding(
- compoundName[currentIndex++],
- Binding.VARIABLE | Binding.TYPE | Binding.PACKAGE,
- invocationSite,
- true /*resolve*/);
- if (!binding.isValidBinding())
- return binding;
-
- foundType : if (binding instanceof PackageBinding) {
- while (currentIndex < length) {
- PackageBinding packageBinding = (PackageBinding) binding;
- binding = packageBinding.getTypeOrPackage(compoundName[currentIndex++], Binding.VARIABLE | Binding.TYPE | Binding.PACKAGE);
-
- if (binding == null) {
- if (currentIndex == length) {
- // must be a type if its the last name, otherwise we have no idea if its a package or type
- return new ProblemReferenceBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- null,
- ProblemReasons.NotFound);
- }
- return new ProblemBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- ProblemReasons.NotFound);
- }
- if (binding instanceof ReferenceBinding) {
- if (!binding.isValidBinding())
- return new ProblemReferenceBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- ((ReferenceBinding)binding).closestMatch(),
- binding.problemId());
- if (!((ReferenceBinding) binding).canBeSeenBy(this))
- return new ProblemReferenceBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- (ReferenceBinding) binding,
- ProblemReasons.NotVisible);
- break foundType;
- }
- }
- return binding;
- }
-
- foundField : if (binding instanceof ReferenceBinding) {
- while (currentIndex < length) {
- ReferenceBinding typeBinding = (ReferenceBinding) binding;
- char[] nextName = compoundName[currentIndex++];
- if ((binding = findField(typeBinding, nextName, invocationSite, true /*resolve*/)) != null) {
- if (!binding.isValidBinding()) {
- return new ProblemFieldBinding(
- (FieldBinding) binding,
- ((FieldBinding) binding).declaringClass,
- CharOperation.concatWith(CharOperation.subarray(compoundName, 0, currentIndex), '.'),
- binding.problemId());
- }
- if (!((FieldBinding) binding).isStatic())
- return new ProblemFieldBinding(
- (FieldBinding) binding,
- ((FieldBinding) binding).declaringClass,
- CharOperation.concatWith(CharOperation.subarray(compoundName, 0, currentIndex), '.'),
- ProblemReasons.NonStaticReferenceInStaticContext);
- break foundField; // binding is now a field
- }
- if ((binding = findMemberType(nextName, typeBinding)) == null) {
- return new ProblemBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- typeBinding,
- ProblemReasons.NotFound);
- }
- if (!binding.isValidBinding()) {
- return new ProblemReferenceBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- ((ReferenceBinding)binding).closestMatch(),
- binding.problemId());
- }
- }
- return binding;
- }
-
- VariableBinding variableBinding = (VariableBinding) binding;
- while (currentIndex < length) {
- TypeBinding typeBinding = variableBinding.type;
- if (typeBinding == null) {
- return new ProblemFieldBinding(
- null,
- null,
- CharOperation.concatWith(CharOperation.subarray(compoundName, 0, currentIndex), '.'),
- ProblemReasons.NotFound);
- }
- variableBinding = findField(typeBinding, compoundName[currentIndex++], invocationSite, true /*resolve*/);
- if (variableBinding == null) {
- return new ProblemFieldBinding(
- null,
- null,
- CharOperation.concatWith(CharOperation.subarray(compoundName, 0, currentIndex), '.'),
- ProblemReasons.NotFound);
- }
- if (!variableBinding.isValidBinding())
- return variableBinding;
- }
- return variableBinding;
-}
-
-/*
- * 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 ... this$p) : available as as a constructor arg + a sequence of fields
- * #((fieldDescr) this$n ... this$p) : available as a sequence of fields
- * nil : not found
- *
- * Note that this algorithm should answer the shortest possible sequence when
- * shortcuts are available:
- * this$0 . this$0 . this$0
- * instead of
- * this$2 . this$1 . this$0 . this$1 . this$0
- * thus the code generation will be more compact and runtime faster
- */
-public VariableBinding[] getEmulationPath(LocalVariableBinding outerLocalVariable) {
- MethodScope currentMethodScope = this.methodScope();
- SourceTypeBinding sourceType = currentMethodScope.enclosingSourceType();
-
- // identity check
- BlockScope variableScope = outerLocalVariable.declaringScope;
- if (variableScope == null /*val$this$0*/ || currentMethodScope == variableScope.methodScope()) {
- return new VariableBinding[] { outerLocalVariable };
- // implicit this is good enough
- }
- 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) {
- BlockScope current = this;
- while (true) {
- for (int i = 0; i < this.localIndex; i++) {
- if (CharOperation.equals(name, current.locals[i].name))
- return true;
- }
- if (current.kind != Scope.BLOCK_SCOPE) return false;
- current = (BlockScope)current.parent;
- }
-}
-
-public int maxShiftedOffset() {
- int max = -1;
- if (this.shiftScopes != null){
- for (int i = 0, length = this.shiftScopes.length; i < length; i++){
- int subMaxOffset = this.shiftScopes[i].maxOffset;
- if (subMaxOffset > max) max = subMaxOffset;
- }
- }
- return max;
-}
-
-/* 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() {
- Scope scope = outerMostMethodScope();
- if (scope==null)
- scope=compilationUnitScope();
- return scope.problemReporter();
-}
-
-/* Answer the reference type of this scope.
- *
- * It is the nearest enclosing type of this scope.
- */
-public TypeDeclaration referenceType() {
- return methodScope().referenceType();
-}
-
-/*
- * Answer the index of this scope relatively to its parent.
- * For method scope, answers -1 (not a classScope relative position)
- */
-public int scopeIndex() {
- if (this instanceof MethodScope ||this instanceof CompilationUnitScope) return -1;
- BlockScope parentScope = (BlockScope)this.parent;
- Scope[] parentSubscopes = parentScope.subscopes;
- for (int i = 0, max = parentScope.subscopeCount; i < max; i++) {
- if (parentSubscopes[i] == this) return i;
- }
- return -1;
-}
-public void setMethods(MethodBinding[] methods) {
- this.methods = methods;
-}
-// start position in this scope - for ordering scopes vs. variables
-int startIndex() {
- return this.startIndex;
-}
-
-public String toString() {
- return toString(0);
-}
-
-public String toString(int tab) {
- String s = basicToString(tab);
- for (int i = 0; i < this.subscopeCount; i++)
- if (this.subscopes[i] instanceof BlockScope)
- s += ((BlockScope) this.subscopes[i]).toString(tab + 1) + "\n"; //$NON-NLS-1$
- return s;
-}
-}
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
deleted file mode 100644
index abefc6d9..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ClassScope.java
+++ /dev/null
@@ -1,814 +0,0 @@
-/*******************************************************************************
- * 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.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;
-import org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration;
-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.classfmt.ClassFileConstants;
-import org.eclipse.wst.jsdt.internal.compiler.env.AccessRestriction;
-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;
-
-public class ClassScope extends Scope {
-
- public TypeDeclaration referenceContext;
- public TypeReference superTypeReference;
- public InferredType inferredType;
-
-
- public ClassScope(Scope parent, TypeDeclaration context) {
- super(CLASS_SCOPE, parent);
- this.referenceContext = context;
- }
- public ClassScope(Scope parent, InferredType type) {
- super(CLASS_SCOPE, parent);
- this.inferredType = type;
- }
-
- void buildAnonymousTypeBinding(SourceTypeBinding enclosingType, ReferenceBinding supertype) {
- LocalTypeBinding anonymousType = buildLocalType(enclosingType, enclosingType.fPackage);
- SourceTypeBinding sourceType = getReferenceBinding();
-
- sourceType.superclass = supertype;
-
- connectMemberTypes();
- buildFieldsAndMethods();
- anonymousType.faultInTypesForFieldsAndMethods();
- sourceType.verifyMethods(environment().methodVerifier());
- }
-
- private void buildFields() {
- if (referenceContext.fields == null) {
- getReferenceBinding().setFields(Binding.NO_FIELDS);
- return;
- }
- // count the number of fields vs. initializers
- FieldDeclaration[] fields = referenceContext.fields;
- int size = fields.length;
- int count = 0;
- for (int i = 0; i < size; i++) {
- switch (fields[i].getKind()) {
- case AbstractVariableDeclaration.FIELD:
- count++;
- }
- }
-
- // iterate the field declarations to create the bindings, lose all duplicates
- FieldBinding[] fieldBindings = new FieldBinding[count];
- HashtableOfObject knownFieldNames = new HashtableOfObject(count);
- boolean duplicate = false;
- count = 0;
- for (int i = 0; i < size; i++) {
- FieldDeclaration field = fields[i];
- if (field.getKind() == AbstractVariableDeclaration.INITIALIZER) {
- } else {
- //FieldBinding fieldBinding = new FieldBinding(field.name, null, field.modifiers | ExtraCompilerModifiers.AccUnresolved, getReferenceBinding());
- FieldBinding fieldBinding = new FieldBinding(field.binding, getReferenceBinding());
- 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++) {
- FieldDeclaration previousField = fields[f];
- if (previousField.binding == previousBinding) {
- problemReporter().duplicateFieldInType(getReferenceBinding(), previousField);
- previousField.binding = null;
- break;
- }
- }
- }
- knownFieldNames.put(field.name, null); // ensure that the duplicate field is found & removed
- problemReporter().duplicateFieldInType(getReferenceBinding(), field);
- field.binding = null;
- } else {
- knownFieldNames.put(field.name, fieldBinding);
- // remember that we have seen a field with this name
- fieldBindings[count++] = fieldBinding;
- }
- }
- }
- // 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);
- getReferenceBinding().setFields(fieldBindings);
- }
-
- void buildFieldsAndMethods() {
- buildFields();
- buildMethods();
-
- SourceTypeBinding sourceType = getReferenceBinding();
-
- ReferenceBinding[] memberTypes = sourceType.memberTypes;
- for (int i = 0, length = memberTypes.length; i < length; i++)
- ((SourceTypeBinding) memberTypes[i]).classScope.buildFieldsAndMethods();
- }
- public SourceTypeBinding getReferenceBinding()
- {
- if (referenceContext!=null)
- return referenceContext.binding;
- else
- return inferredType.binding;
- }
-
- private LocalTypeBinding buildLocalType(SourceTypeBinding enclosingType, PackageBinding packageBinding) {
-
- referenceContext.scope = this;
- referenceContext.staticInitializerScope = new MethodScope(this, referenceContext, true);
- referenceContext.initializerScope = new MethodScope(this, referenceContext, false);
-
- // build the binding or the local type
- LocalTypeBinding localType = new LocalTypeBinding(this, enclosingType, this.innermostSwitchCase());
- referenceContext.binding = localType;
- checkAndSetModifiers();
-
- // Look at member types
- ReferenceBinding[] memberTypeBindings = Binding.NO_MEMBER_TYPES;
- if (referenceContext.memberTypes != null) {
- int size = referenceContext.memberTypes.length;
- memberTypeBindings = new ReferenceBinding[size];
- int count = 0;
- nextMember : for (int i = 0; i < size; i++) {
- TypeDeclaration memberContext = referenceContext.memberTypes[i];
- ReferenceBinding type = localType;
- // check that the member does not conflict with an enclosing type
- do {
- if (CharOperation.equals(type.sourceName, memberContext.name)) {
- continue nextMember;
- }
- type = type.enclosingType();
- } while (type != null);
- // check the member type does not conflict with another sibling member type
- for (int j = 0; j < i; j++) {
- if (CharOperation.equals(referenceContext.memberTypes[j].name, memberContext.name)) {
- continue nextMember;
- }
- }
- ClassScope memberScope = new ClassScope(this, referenceContext.memberTypes[i]);
- LocalTypeBinding memberBinding = memberScope.buildLocalType(localType, packageBinding);
- memberBinding.setAsMemberType();
- memberTypeBindings[count++] = memberBinding;
- }
- if (count != size)
- System.arraycopy(memberTypeBindings, 0, memberTypeBindings = new ReferenceBinding[count], 0, count);
- }
- localType.memberTypes = memberTypeBindings;
- return localType;
- }
-
- void buildLocalTypeBinding(SourceTypeBinding enclosingType) {
-
- LocalTypeBinding localType = buildLocalType(enclosingType, enclosingType.fPackage);
- connectTypeHierarchy();
- buildFieldsAndMethods();
- localType.faultInTypesForFieldsAndMethods();
-
- getReferenceBinding().verifyMethods(environment().methodVerifier());
- }
-
- private void buildMemberTypes(AccessRestriction accessRestriction) {
- SourceTypeBinding sourceType = getReferenceBinding();
- ReferenceBinding[] memberTypeBindings = Binding.NO_MEMBER_TYPES;
- if (referenceContext.memberTypes != null) {
- int length = referenceContext.memberTypes.length;
- memberTypeBindings = new ReferenceBinding[length];
- int count = 0;
- nextMember : for (int i = 0; i < length; i++) {
- TypeDeclaration memberContext = referenceContext.memberTypes[i];
- ReferenceBinding type = sourceType;
- // check that the member does not conflict with an enclosing type
- do {
- if (CharOperation.equals(type.sourceName, memberContext.name)) {
- continue nextMember;
- }
- type = type.enclosingType();
- } while (type != null);
- // check that the member type does not conflict with another sibling member type
- for (int j = 0; j < i; j++) {
- if (CharOperation.equals(referenceContext.memberTypes[j].name, memberContext.name)) {
- continue nextMember;
- }
- }
-
- ClassScope memberScope = new ClassScope(this, memberContext);
- memberTypeBindings[count++] = memberScope.buildType(sourceType, sourceType.fPackage, accessRestriction);
- }
- if (count != length)
- System.arraycopy(memberTypeBindings, 0, memberTypeBindings = new ReferenceBinding[count], 0, count);
- }
- sourceType.memberTypes = memberTypeBindings;
- }
-
- private void buildMethods() {
- if (referenceContext.methods == null) {
- getReferenceBinding().setMethods(Binding.NO_METHODS);
- return;
- }
-
- // iterate the method declarations to create the bindings
- AbstractMethodDeclaration[] methods = referenceContext.methods;
- int size = methods == null ? 0 : methods.length;
- // look for <clinit> method
- int clinitIndex = -1;
- for (int i = 0; i < size; i++) {
- if (methods[i].isClinit()) {
- clinitIndex = i;
- break;
- }
- }
-
- int count = 0; // reserve 2 slots for special enum methods: #values() and #valueOf(String)
- 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 <EnumType>[] values()
-// methodBindings[1] = sourceType.addSyntheticEnumMethod(TypeConstants.VALUEOF); // add <EnumType> 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);
- if (methodBinding != null) // is null if binding could not be created
- methodBindings[count++] = methodBinding;
- }
- }
- if (count != methodBindings.length)
- System.arraycopy(methodBindings, 0, methodBindings = new MethodBinding[count], 0, count);
- sourceType.tagBits &= ~TagBits.AreMethodsSorted; // in case some static imports reached already into this type
- sourceType.setMethods(methodBindings);
- }
-
- SourceTypeBinding buildType(SourceTypeBinding enclosingType, PackageBinding packageBinding, AccessRestriction accessRestriction) {
- // provide the typeDeclaration with needed scopes
- referenceContext.scope = this;
- referenceContext.staticInitializerScope = new MethodScope(this, referenceContext, true);
- referenceContext.initializerScope = new MethodScope(this, referenceContext, false);
-
- if (enclosingType == null) {
- char[][] className = CharOperation.arrayConcat(packageBinding.compoundName, referenceContext.name);
- if (referenceContext!=null)
- referenceContext.binding= new SourceTypeBinding(className, packageBinding, this);
- } else {
- char[][] className = CharOperation.deepCopy(enclosingType.compoundName);
- className[className.length - 1] =
- CharOperation.concat(className[className.length - 1], referenceContext.name, '$');
- ReferenceBinding existingType = packageBinding.getType0(className[className.length - 1]);
- referenceContext.binding = new MemberTypeBinding(className, this, enclosingType);
- }
-
- SourceTypeBinding sourceType = getReferenceBinding();
- environment().setAccessRestriction(sourceType, accessRestriction);
- sourceType.fPackage.addType(sourceType);
- checkAndSetModifiers();
- buildMemberTypes(accessRestriction);
- return sourceType;
- }
-
- private void checkAndSetModifiers() {
- SourceTypeBinding sourceType = getReferenceBinding();
- int modifiers = sourceType.modifiers;
- ReferenceBinding enclosingType = sourceType.enclosingType();
- boolean isMemberType = sourceType.isMemberType();
- if (isMemberType) {
- modifiers |= (enclosingType.modifiers & (ClassFileConstants.AccStrictfp));
- // checks for member types before local types to catch local members
- if (enclosingType.isViewedAsDeprecated() && !sourceType.isDeprecated())
- modifiers |= ExtraCompilerModifiers.AccDeprecatedImplicitly;
- } else if (sourceType.isLocalType()) {
- if (sourceType.isAnonymousType()) {
- modifiers |= ClassFileConstants.AccFinal;
- }
- Scope scope = this;
- do {
- switch (scope.kind) {
- case METHOD_SCOPE :
- MethodScope methodScope = (MethodScope) scope;
- if (methodScope.isInsideInitializer()) {
- SourceTypeBinding type = ((TypeDeclaration) methodScope.referenceContext).binding;
-
- // inside field declaration ? check field modifier to see if deprecated
- if (methodScope.initializedField != null) {
- // currently inside this field initialization
- if (methodScope.initializedField.isViewedAsDeprecated() && !sourceType.isDeprecated())
- modifiers |= ExtraCompilerModifiers.AccDeprecatedImplicitly;
- } else {
- if (type.isStrictfp())
- modifiers |= ClassFileConstants.AccStrictfp;
- if (type.isViewedAsDeprecated() && !sourceType.isDeprecated())
- modifiers |= ExtraCompilerModifiers.AccDeprecatedImplicitly;
- }
- } else {
- MethodBinding method = ((AbstractMethodDeclaration) methodScope.referenceContext).binding;
- if (method != null) {
- if (method.isStrictfp())
- modifiers |= ClassFileConstants.AccStrictfp;
- if (method.isViewedAsDeprecated() && !sourceType.isDeprecated())
- modifiers |= ExtraCompilerModifiers.AccDeprecatedImplicitly;
- }
- }
- break;
- case CLASS_SCOPE :
- // local member
- if (enclosingType.isStrictfp())
- modifiers |= ClassFileConstants.AccStrictfp;
- if (enclosingType.isViewedAsDeprecated() && !sourceType.isDeprecated())
- modifiers |= ExtraCompilerModifiers.AccDeprecatedImplicitly;
- break;
- }
- scope = scope.parent;
- } while (scope != null);
- }
-
- // after this point, tests on the 16 bits reserved.
- int realModifiers = modifiers & ExtraCompilerModifiers.AccJustFlag;
-
- if (isMemberType) {
- // test visibility modifiers inconsistency, isolate the accessors bits
-
- int accessorBits = realModifiers & (ClassFileConstants.AccPublic | ClassFileConstants.AccProtected | ClassFileConstants.AccPrivate);
- if ((accessorBits & (accessorBits - 1)) > 1) {
-
- // need to keep the less restrictive so disable Protected/Private as necessary
- if ((accessorBits & ClassFileConstants.AccPublic) != 0) {
- if ((accessorBits & ClassFileConstants.AccProtected) != 0)
- modifiers &= ~ClassFileConstants.AccProtected;
- if ((accessorBits & ClassFileConstants.AccPrivate) != 0)
- modifiers &= ~ClassFileConstants.AccPrivate;
- } else if ((accessorBits & ClassFileConstants.AccProtected) != 0 && (accessorBits & ClassFileConstants.AccPrivate) != 0) {
- modifiers &= ~ClassFileConstants.AccPrivate;
- }
- }
- }
-
- sourceType.modifiers = modifiers;
- }
-
- /* This method checks the modifiers of a field.
- *
- * 9.3 & 8.3
- * Need to integrate the check for the final modifiers for nested types
- *
- * Note : A scope is accessible by : fieldBinding.declaringClass.scope
- */
- private void checkAndSetModifiersForField(FieldBinding fieldBinding, FieldDeclaration fieldDecl) {
- int modifiers = fieldBinding.modifiers;
- final ReferenceBinding declaringClass = fieldBinding.declaringClass;
-
- // after this point, tests on the 16 bits reserved.
- int realModifiers = modifiers & ExtraCompilerModifiers.AccJustFlag;
-
- int accessorBits = realModifiers & (ClassFileConstants.AccPublic | ClassFileConstants.AccProtected | ClassFileConstants.AccPrivate);
- if ((accessorBits & (accessorBits - 1)) > 1) {
-
- // need to keep the less restrictive so disable Protected/Private as necessary
- if ((accessorBits & ClassFileConstants.AccPublic) != 0) {
- if ((accessorBits & ClassFileConstants.AccProtected) != 0)
- modifiers &= ~ClassFileConstants.AccProtected;
- if ((accessorBits & ClassFileConstants.AccPrivate) != 0)
- modifiers &= ~ClassFileConstants.AccPrivate;
- } else if ((accessorBits & ClassFileConstants.AccProtected) != 0 && (accessorBits & ClassFileConstants.AccPrivate) != 0) {
- modifiers &= ~ClassFileConstants.AccPrivate;
- }
- }
-
- if (fieldDecl.initialization == null && (modifiers & ClassFileConstants.AccFinal) != 0)
- modifiers |= ExtraCompilerModifiers.AccBlankFinal;
- fieldBinding.modifiers = modifiers;
- }
-
- public void checkParameterizedSuperTypeCollisions() {
- ReferenceBinding[] memberTypes = getReferenceBinding().memberTypes;
- if (memberTypes != null && memberTypes != Binding.NO_MEMBER_TYPES)
- for (int i = 0, size = memberTypes.length; i < size; i++)
- ((SourceTypeBinding) memberTypes[i]).classScope.checkParameterizedSuperTypeCollisions();
- }
-
- private void checkForInheritedMemberTypes(SourceTypeBinding sourceType) {
- // search up the hierarchy of the sourceType to see if any superType defines a member type
- // when no member types are defined, tag the sourceType & each superType with the HasNoMemberTypes bit
- // assumes super types have already been checked & tagged
- ReferenceBinding currentType = sourceType;
- do {
- 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);
-
- // 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);
- }
-
- private void connectMemberTypes() {
- SourceTypeBinding sourceType = getReferenceBinding();
- ReferenceBinding[] memberTypes = sourceType.memberTypes;
- if (memberTypes != null && memberTypes != Binding.NO_MEMBER_TYPES) {
- for (int i = 0, size = memberTypes.length; i < size; i++)
- ((SourceTypeBinding) memberTypes[i]).classScope.connectTypeHierarchy();
- }
- }
- /*
- Our current belief based on available JCK tests is:
- inherited member types are visible as a potential superclass.
- inherited interfaces are not visible when defining a superinterface.
-
- Error recovery story:
- ensure the superclass is set to java.lang.Object if a problem is detected
- resolving the superclass.
-
- Answer false if an error was reported against the sourceType.
- */
- private boolean connectSuperclass() {
- SourceTypeBinding sourceType = getReferenceBinding();
- if (sourceType.id == T_JavaLangObject) { // handle the case of redefining java.lang.Object up front
- sourceType.superclass = 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)
- {
- TypeReference superclassRef = referenceContext.superclass;
- 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;
- return true;
- }
- }
- else
- {
- 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;
- if (superclass.isValidBinding())
- return true;
- }
-
- }
- sourceType.tagBits |= TagBits.HierarchyHasProblems;
- sourceType.superclass = getJavaLangObject();
- if ((sourceType.superclass.tagBits & TagBits.BeginHierarchyCheck) == 0)
- detectHierarchyCycle(sourceType, sourceType.superclass, null);
- return false; // reported some error against the source type
- }
-
- /**
- * <p>Iterate through all of the inferred types mixed in types and "mixin" the fields
- * and methods from the mixed in types into this scopes inferred type.</p>
- *
- * <p>NOTE: this can only successfully be done when all inference is done.</p>
- *
- * @return <code>true</code> if no problems occurred, <code>false</code> otherwise
- */
- protected boolean connectMixins() {
- SourceTypeBinding sourceType = this.inferredType.binding;
- if (sourceType.id == T_JavaLangObject) // already handled the case of redefining java.lang.Object
- return true;
- if (this.inferredType.mixins==null || this.inferredType.mixins.isEmpty())
- return true;
-
- boolean noProblems = true;
- 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);
- if (mixinBinding == null) { // detected cycle
- sourceType.tagBits |= TagBits.HierarchyHasProblems;
- noProblems = false;
- continue nextExtends;
- }
-
- //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;
-
- // 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;
- }
- }
- }
- }
-
- //get the next partial source type for this 'mixin'
- if(mixinBinding instanceof SourceTypeBinding) {
- mixinBinding = ((SourceTypeBinding)mixinBinding).nextType;
- } else {
- mixinBinding = null;
- }
- }
- }
- return noProblems;
- }
-
-
-
-
- void connectTypeHierarchy() {
- SourceTypeBinding sourceType = getReferenceBinding();
- if ((sourceType.tagBits & TagBits.BeginHierarchyCheck) == 0) {
- sourceType.tagBits |= TagBits.BeginHierarchyCheck;
- boolean noProblems = connectSuperclass();
- noProblems &= connectMixins();
- //noProblems &= connectSuperInterfaces();
- sourceType.tagBits |= TagBits.EndHierarchyCheck;
-// noProblems &= connectTypeVariables(referenceContext.typeParameters, false);
- if (noProblems && sourceType.isHierarchyInconsistent())
- problemReporter().hierarchyHasProblems(sourceType);
- }
- connectMemberTypes();
- LookupEnvironment env = environment();
- try {
- env.missingClassFileLocation = referenceContext;
- checkForInheritedMemberTypes(sourceType);
- } catch (AbortCompilation e) {
- e.updateContext(referenceContext, referenceCompilationUnit().compilationResult);
- throw e;
- } finally {
- env.missingClassFileLocation = null;
- }
- }
-
- private void connectTypeHierarchyWithoutMembers() {
- // must ensure the imports are resolved
- if (parent instanceof CompilationUnitScope) {
- if (((CompilationUnitScope) parent).imports == null)
- ((CompilationUnitScope) parent).checkAndSetImports();
- } else if (parent instanceof ClassScope) {
- // ensure that the enclosing type has already been checked
- ((ClassScope) parent).connectTypeHierarchyWithoutMembers();
- }
-
- // double check that the hierarchy search has not already begun...
- SourceTypeBinding sourceType = getReferenceBinding();
- if ((sourceType.tagBits & TagBits.BeginHierarchyCheck) != 0)
- return;
-
- sourceType.tagBits |= TagBits.BeginHierarchyCheck;
- boolean noProblems = connectSuperclass();
- noProblems &= connectMixins();
-// noProblems &= connectSuperInterfaces();
- sourceType.tagBits |= TagBits.EndHierarchyCheck;
-// noProblems &= connectTypeVariables(referenceContext.typeParameters, false);
- if (noProblems && sourceType.isHierarchyInconsistent())
- problemReporter().hierarchyHasProblems(sourceType);
- }
-
- public boolean detectHierarchyCycle(TypeBinding superType, TypeReference reference) {
- if (!(superType instanceof ReferenceBinding)) return false;
-
- if (reference == this.superTypeReference) { // see findSuperType()
- // abstract class X<K,V> implements java.util.Map<K,V>
- // static abstract class M<K,V> implements Entry<K,V>
- compilationUnitScope().recordSuperTypeReference(superType); // to record supertypes
- return detectHierarchyCycle(getReferenceBinding(), (ReferenceBinding) superType, reference);
- }
-
- if ((superType.tagBits & TagBits.BeginHierarchyCheck) == 0 && superType instanceof SourceTypeBinding)
- // ensure if this is a source superclass that it has already been checked
- ((SourceTypeBinding) superType).classScope.connectTypeHierarchyWithoutMembers();
- return false;
- }
-
- // Answer whether a cycle was found between the sourceType & the superType
- private boolean detectHierarchyCycle(SourceTypeBinding sourceType, ReferenceBinding superType, TypeReference reference) {
- // by this point the superType must be a binary or source type
-
- if (sourceType == superType) {
- problemReporter().hierarchyCircularity(sourceType, superType, reference);
- sourceType.tagBits |= TagBits.HierarchyHasProblems;
- return true;
- }
-
- if (superType.isMemberType()) {
- ReferenceBinding current = superType.enclosingType();
- do {
- if (current.isHierarchyBeingConnected() && current == sourceType) {
- problemReporter().hierarchyCircularity(sourceType, current, reference);
- sourceType.tagBits |= TagBits.HierarchyHasProblems;
- current.tagBits |= TagBits.HierarchyHasProblems;
- return true;
- }
- } while ((current = current.enclosingType()) != null);
- }
-
- if (superType.isBinaryBinding()) {
- // force its superclass & superinterfaces to be found... 2 possibilities exist - the source type is included in the hierarchy of:
- // - 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();
- if (parentType != null) {
- if (sourceType == parentType) {
- problemReporter().hierarchyCircularity(sourceType, superType, reference);
- sourceType.tagBits |= TagBits.HierarchyHasProblems;
- superType.tagBits |= TagBits.HierarchyHasProblems;
- return true;
- }
- hasCycle |= detectHierarchyCycle(sourceType, parentType, reference);
- if ((parentType.tagBits & TagBits.HierarchyHasProblems) != 0) {
- sourceType.tagBits |= TagBits.HierarchyHasProblems;
- parentType.tagBits |= TagBits.HierarchyHasProblems; // propagate down the hierarchy
- }
- }
-
- return hasCycle;
- }
-
- if (superType.isHierarchyBeingConnected()) {
- org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference ref = ((SourceTypeBinding) superType).classScope.superTypeReference;
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=133071
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=121734
- if (ref != null && (ref.resolvedType == null || ((ReferenceBinding) ref.resolvedType).isHierarchyBeingConnected())) {
- problemReporter().hierarchyCircularity(sourceType, superType, reference);
- sourceType.tagBits |= TagBits.HierarchyHasProblems;
- superType.tagBits |= TagBits.HierarchyHasProblems;
- return true;
- }
- }
- if ((superType.tagBits & TagBits.BeginHierarchyCheck) == 0)
- // ensure if this is a source superclass that it has already been checked
- ((SourceTypeBinding) superType).classScope.connectTypeHierarchyWithoutMembers();
- if ((superType.tagBits & TagBits.HierarchyHasProblems) != 0)
- sourceType.tagBits |= TagBits.HierarchyHasProblems;
- return false;
- }
-
- private ReferenceBinding findInferredSupertype(InferredType type) {
- try {
-// typeReference.aboutToResolve(this); // allows us to trap completion & selection nodes
- compilationUnitScope().recordQualifiedReference(new char[][]{type.superClass.getName()});
-// this.superTypeReference = typeReference;
- ReferenceBinding superType = type.resolveSuperType(this);
- this.superTypeReference = null;
- return superType;
- } catch (AbortCompilation e) {
- e.updateContext(type, referenceCompilationUnit().compilationResult);
- throw e;
- }
- }
-
-
- private ReferenceBinding findSupertype(TypeReference typeReference) {
- CompilationUnitScope unitScope = compilationUnitScope();
- LookupEnvironment env = unitScope.environment;
- try {
- env.missingClassFileLocation = typeReference;
- typeReference.aboutToResolve(this); // allows us to trap completion & selection nodes
- unitScope.recordQualifiedReference(typeReference.getTypeName());
- this.superTypeReference = typeReference;
- ReferenceBinding superType = (ReferenceBinding) typeReference.resolveSuperType(this);
- return superType;
- } catch (AbortCompilation e) {
- e.updateContext(typeReference, referenceCompilationUnit().compilationResult);
- throw e;
- } finally {
- env.missingClassFileLocation = null;
- this.superTypeReference = 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() {
- MethodScope outerMethodScope;
- if ((outerMethodScope = outerMostMethodScope()) == null) {
- ProblemReporter problemReporter = referenceCompilationUnit().problemReporter;
- problemReporter.referenceContext = referenceContext;
- return problemReporter;
- }
- return outerMethodScope.problemReporter();
- }
-
- /* Answer the reference type of this scope.
- * It is the nearest enclosing type of this scope.
- */
- public TypeDeclaration referenceType() {
- return referenceContext;
- }
-
- public String toString() {
- if (referenceContext != null)
- return "--- Class Scope ---\n\n" //$NON-NLS-1$
- + getReferenceBinding().toString();
- return "--- Class Scope ---\n\n Binding not initialized" ; //$NON-NLS-1$
- }
-
- SourceTypeBinding buildInferredType(SourceTypeBinding enclosingType, PackageBinding packageBinding, AccessRestriction accessRestriction) {
- // provide the typeDeclaration with needed scopes
- inferredType.scope = 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.isAnonymous )
- inferredType.binding.tagBits |= TagBits.AnonymousTypeMask;
- if( inferredType.isObjectLiteral )
- inferredType.binding.tagBits |= TagBits.IsObjectLiteralType;
- } else {
-// char[][] className = CharOperation.deepCopy(enclosingType.compoundName);
-// className[className.length - 1] =
-// CharOperation.concat(className[className.length - 1], referenceContext.name, '$');
-// referenceContext.binding = new MemberTypeBinding(className, this, enclosingType);
- }
-
- SourceTypeBinding sourceType = inferredType.binding;
- LookupEnvironment environment = environment();
- environment.setAccessRestriction(sourceType, accessRestriction);
- environment.defaultPackage.addType(sourceType);
- if (environment.defaultPackage != sourceType.fPackage)
- sourceType.fPackage.addType(sourceType);
- return sourceType;
- }
-
-}
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
deleted file mode 100644
index 93a7544d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/CombinedSourceTypeBinding.java
+++ /dev/null
@@ -1,182 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.lookup;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-
-import org.eclipse.wst.jsdt.core.UnimplementedException;
-import org.eclipse.wst.jsdt.core.infer.InferredType;
-
-public class CombinedSourceTypeBinding extends SourceTypeBinding {
-
- SourceTypeBinding [] sourceTypes=new SourceTypeBinding[2];
- public CombinedSourceTypeBinding( Scope scope, SourceTypeBinding initialSourceType, SourceTypeBinding initialSourceType2) {
- super(initialSourceType.compoundName, initialSourceType.fPackage, scope);
- sourceTypes[0]=initialSourceType;
- sourceTypes[1]=initialSourceType2;
- setSuperclass(initialSourceType);
- setSuperclass(initialSourceType2);
- this.tagBits|=initialSourceType.tagBits;
- this.tagBits|=initialSourceType2.tagBits;
- }
-
-
- public void addSourceType(SourceTypeBinding binding)
- {
- int length = this.sourceTypes.length;
- System.arraycopy(this.sourceTypes, 0, this.sourceTypes=new SourceTypeBinding[length+1], 0, length);
- this.sourceTypes[length]=binding;
- setSuperclass(binding);
- this.tagBits|=binding.tagBits;
- }
-
-
- public FieldBinding[] fields() {
- ArrayList list = new ArrayList();
- for (int i = 0; i < this.sourceTypes.length ; i++) {
- FieldBinding[] bindings = this.sourceTypes[i].fields();
- list.addAll(Arrays.asList(bindings));
- }
- return (FieldBinding[]) list.toArray(new FieldBinding[list.size()]);
- }
-
-
- public MethodBinding getExactMethod(char[] selector, TypeBinding[] argumentTypes, CompilationUnitScope refScope) {
- MethodBinding methodBinding=null;
- for (int i = 0; i < this.sourceTypes.length && methodBinding==null; i++) {
- methodBinding= this.sourceTypes[i].getExactMethod(selector, argumentTypes, refScope);
- }
- return methodBinding;
- }
-
-
- public FieldBinding getField(char[] fieldName, boolean needResolve) {
- FieldBinding fieldBinding=null;
- for (int i = 0; i < this.sourceTypes.length && fieldBinding==null; i++) {
- fieldBinding= this.sourceTypes[i].getField(fieldName, needResolve);
- }
- return fieldBinding;
- }
-
-
- public InferredType getInferredType() {
- throw new UnimplementedException("should not get here"); //$NON-NLS-1$
- }
-
-
- public MethodBinding[] getMethods(char[] selector) {
- ArrayList list = new ArrayList();
- for (int i = 0; i < this.sourceTypes.length ; i++) {
- MethodBinding[] bindings = this.sourceTypes[i].getMethods(selector);
- list.addAll(Arrays.asList(bindings));
- }
- return (MethodBinding[]) list.toArray(new MethodBinding[list.size()]);
- }
-
-
- public boolean hasMemberTypes() {
- for (int i = 0; i < this.sourceTypes.length ; i++) {
- if (this.sourceTypes[i].hasMemberTypes())
- return true;
- }
- return false;
- }
-
-
- public boolean isEquivalentTo(TypeBinding otherType) {
- if (this == otherType) return true;
-
- return false;
- }
-
-
- public ReferenceBinding[] memberTypes() {
- ArrayList list = new ArrayList();
- for (int i = 0; i < this.sourceTypes.length ; i++) {
- ReferenceBinding[] bindings = this.sourceTypes[i].memberTypes();
- list.addAll(Arrays.asList(bindings));
- }
- return (ReferenceBinding[]) list.toArray(new ReferenceBinding[list.size()]);
- }
-
-
- public MethodBinding[] methods() {
- ArrayList list = new ArrayList();
- for (int i = 0; i < this.sourceTypes.length ; i++) {
- MethodBinding[] bindings = this.sourceTypes[i].methods();
- list.addAll(Arrays.asList(bindings));
- }
- return (MethodBinding[]) list.toArray(new MethodBinding[list.size()]);
- }
-
-
- public void setFields(FieldBinding[] fields) {
- throw new UnimplementedException("should not get here"); //$NON-NLS-1$
- }
-
-
- public void setMethods(MethodBinding[] methods) {
- throw new UnimplementedException("should not get here"); //$NON-NLS-1$
- }
-
-
- public MethodBinding getExactConstructor(TypeBinding[] argumentTypes) {
- for (int i = 0; i < this.sourceTypes.length ; i++) {
- MethodBinding exactConstructor = this.sourceTypes[i].getExactConstructor(argumentTypes);
- if (exactConstructor!=null && exactConstructor.isValidBinding())
- return exactConstructor;
- }
- return null;
- }
-
-
- public boolean contains(ReferenceBinding binding)
- {
- for (int i = 0; i < this.sourceTypes.length ; i++)
- if (this.sourceTypes[i]==binding)
- return true;
-
- return false;
- }
-
- public void cleanup()
- {
- super.cleanup();
- for (int i = 0; i < this.sourceTypes.length ; i++)
- this.sourceTypes[i].cleanup();
- }
-
-
- private void setSuperclass(SourceTypeBinding from)
- {
- if (this.superclass==null || (from.superclass!=null && from.superclass.id!=TypeIds.T_JavaLangObject))
- this.superclass=from.superclass;
- }
-
-
- public ReferenceBinding superclass() {
- ReferenceBinding supercls = null;
- for (int i = 0; i < this.sourceTypes.length ; i++)
- {
- supercls = this.sourceTypes[i].superclass;
- if (supercls!=null && supercls.id!=TypeIds.T_JavaLangObject)
- return supercls;
- }
- if (supercls!=null && this.superclass==null)
- return supercls;
- return this.superclass;
- }
-
-
-
-}
-
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
deleted file mode 100644
index 99951f2e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/CompilationUnitBinding.java
+++ /dev/null
@@ -1,167 +0,0 @@
-/*******************************************************************************
- * 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.internal.compiler.lookup;
-
-import java.io.File;
-
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.infer.InferredType;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-import org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Assignment;
-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.MethodDeclaration;
-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.ThisReference;
-
-
-public class CompilationUnitBinding extends SourceTypeBinding {
-// public char[] sourceName;
-//
-// private FieldBinding[] fields;
-//
-// private FunctionBinding[] methods;
-// public long tagBits = 0; // See values in the interface TagBits below
- CompilationUnitScope compilationUnitScope;
- private char[]shortName;
-
- char [] path;
-
- public CompilationUnitBinding(CompilationUnitScope scope,PackageBinding fPackage,char [] path) {
- this(scope,fPackage,path,null);
- }
-
- public CompilationUnitBinding(CompilationUnitScope scope,PackageBinding fPackage,char [] path,ReferenceBinding superType ) {
- super(new char [][]{scope.referenceContext.getFileName()}, fPackage, scope);
- this.compilationUnitScope=scope;
- this.memberTypes=Binding.NO_MEMBER_TYPES;
- this.sourceName=this.fileName;
- setShortName(this.fileName);
- this.path=path;
- /* bc - allows super type of 'Window' (and other types) for a compilation unit */
- this.superclass = superType;
-
- }
-
- private void setShortName(char[] fileName) {
- for (int i=fileName.length-1;i>=0;i--)
- {
- if (fileName[i]==File.separatorChar || fileName[i]=='/')
- {
- shortName=new char[fileName.length-1-i];
- System.arraycopy(fileName, i+1, shortName, 0, shortName.length);
- return;
- }
- }
- shortName=fileName;
- }
-
- public int kind() {
- return COMPILATION_UNIT;
- }
-
- public char[] signature() /* Ljava/lang/Object; */ {
- if (this.signature != null)
- return this.signature;
-
- return this.signature = CharOperation.concat(Signature.C_COMPILATION_UNIT, constantPoolName(), ';');
- }
-
- 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)
- 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)
- return functionExpression.methodDeclaration;
- }
- }
-
- class MethodFinder extends ASTVisitor
- {
- MethodBinding binding;
- MethodDeclaration method;
- MethodFinder(MethodBinding binding)
- {this.binding=binding;}
-
- public boolean visit(MethodDeclaration methodDeclaration, Scope scope) {
- if (methodDeclaration.binding==this.binding)
- {
- method=methodDeclaration;
- return false;
- }
- return true;
- }
-
- public boolean visit(InferredType inferredType, BlockScope scope) { // not possible to contain method
- return false;
- }
-
- public boolean visit(Javadoc javadoc, BlockScope scope) { // not possible to contain method
- return false;
- }
-
- public boolean visit(Javadoc javadoc, ClassScope scope) { // not possible to contain method
- return false;
- }
-
- public boolean visit(PostfixExpression postfixExpression, // not possible to contain method
- BlockScope scope) {
- return false;
- }
-
- public boolean visit(PrefixExpression prefixExpression, // not possible to contain method
- BlockScope scope) {
- return false;
- }
-
- public boolean visit(ThisReference thisReference, // not possible to contain method
- BlockScope scope) {
- return false;
- }
-
- public boolean visit(ThisReference thisReference, // not possible to contain method
- ClassScope scope) {
- return false;
- }
-
-
-
- }
- MethodFinder visitor=new MethodFinder(binding);
- compilationUnitScope.referenceContext.traverse(visitor, compilationUnitScope,true);
- return visitor.method;
- }
-
- public char[] qualifiedSourceName() {
- return CharOperation.concatWith(compoundName, '.');
- }
-
- public char[] qualifiedPackageName() {
- return this.path;
- }
-
- public void cleanup()
- {
- super.cleanup();
- if (this.methods!=null)
- for (int i = 0; i < this.methods.length; i++) {
- this.methods[i].cleanup();
- }
- this.compilationUnitScope=null;
- }
-}
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
deleted file mode 100644
index 97b90f53..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/CompilationUnitScope.java
+++ /dev/null
@@ -1,1180 +0,0 @@
-/*******************************************************************************
- * 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
- * Erling Ellingsen - patch for bug 125570
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.lookup;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-
-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.InferredType;
-import org.eclipse.wst.jsdt.core.infer.InferrenceManager;
-import org.eclipse.wst.jsdt.core.infer.InferrenceProvider;
-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.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.classfmt.ClassFileConstants;
-import org.eclipse.wst.jsdt.internal.compiler.env.AccessRestriction;
-import org.eclipse.wst.jsdt.internal.compiler.problem.ProblemReporter;
-import org.eclipse.wst.jsdt.internal.compiler.util.CompoundNameVector;
-import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfObject;
-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.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;
-
-private CompoundNameVector qualifiedReferences;
-private SimpleNameVector simpleNameReferences;
-private ObjectVector referencedTypes;
-private ObjectVector referencedSuperTypes;
-
-HashtableOfType constantPoolNameUsage;
-public int analysisIndex;
-private int captureID = 1;
-
-/* Allows a compilation unit to inherit fields from a superType */
-public ReferenceBinding superBinding;
-private MethodScope methodScope;
-private ClassScope classScope;
-
-public int temporaryAnalysisIndex;
-
-
-public HashSet externalCompilationUnits=new HashSet();
-
-public static final char FILENAME_DOT_SUBSTITUTION='#';
-
-
-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);
- }
- return false;
- }
-
- public boolean visit(MethodDeclaration methodDeclaration, Scope parentScope) {
-
- char[] selector = null;
- boolean isConstructor = false;
-
- if(methodDeclaration.selector != null) {
- selector = methodDeclaration.selector;
- } else if(methodDeclaration.inferredMethod != null && methodDeclaration.inferredMethod.isConstructor) {
- //this is so that inferred constructors get added to the methods list
- //selector = methodDeclaration.inferredMethod.name;
- isConstructor = true;
- }
-
- if (selector!=null)
- {
- MethodScope scope = new MethodScope(parentScope,methodDeclaration, false);
- MethodBinding methodBinding = scope.createMethod(methodDeclaration,selector,referenceContext.compilationUnitBinding,isConstructor,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);
- }
- methodDeclaration.binding=methodBinding;
- methodDeclaration.bindArguments();
- }
- return false;
- }
-}
-
-
-
-public CompilationUnitScope(CompilationUnitDeclaration unit, LookupEnvironment environment) {
- super(COMPILATION_UNIT_SCOPE, null);
-
- this.environment = environment;
- this.referenceContext = unit;
- unit.scope = this;
-
- /* 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;
- }
-
-}
-
-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 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++)
- topLevelTypes[i].buildFieldsAndMethods();
-}
-
-void buildTypeBindings(AccessRestriction accessRestriction) {
- buildTypeBindings(new char[0][0], 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;
- }
- }
- 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;
-// }
- }
-// 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<fragments.length;i++) {
-// String packageName = fragments[i].getElementName();
-// PackageBinding binding = environment.getPackage0(packageName.toCharArray());
-// superBinding = binding.getType(libSuperType.getSuperTypeName().toCharArray());
-// if(superBinding!=null) break;
-//
-// }
-//
-// }else
-
-
- topLevelTypes = new SourceTypeBinding[typeLength];
-
- int count = 0;
-
-
- SimpleSetOfCharArray addTypes=new SimpleSetOfCharArray(10);
-// nextType:
- String fileName=new String(this.referenceContext.getFileName());
- nextType: for (int i = 0; i < typeLength; i++) {
- InferredType typeDecl = referenceContext.inferredTypes[i];
-
- if (typeDecl.isDefinition && !typeDecl.isEmptyGlobal()) {
- if(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)
- continue nextType;
-
- }
- 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;
- }
- 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);
- }
- 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;
- }
- }
- }
-
-
- char [][] typeNames= new char [addTypes.elementSize] [];
- addTypes.asArray(typeNames);
- environment.addUnitsContainingBindings(typeNames, Binding.TYPE, fileName);
-
-
- // 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();
- }
- 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 ;
- }
-
-
- /* If super type is combined source type, search through SourceTypes for the specific instance */
- if( (superBinding instanceof SourceTypeBinding) && ((SourceTypeBinding)superBinding).nextType!=null) {
-
-
- classScope = ((SourceTypeBinding)superBinding).classScope;
-
- SourceTypeBinding sourceType = null;
-
- if(superBinding instanceof SourceTypeBinding) {
- sourceType = (SourceTypeBinding)superBinding;
- }
- 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
-
- if (enclosingType == null) {
- char[][] className = CharOperation.arrayConcat(packageBinding.compoundName, inferredType.getName());
- inferredType.binding = new SourceTypeBinding(className, packageBinding, this);
-
- //@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;
-}
-
-
-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;
- }
- }
- 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;
-
- 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);
- }
- }
-
- // 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 {
- // 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);
- }
- }
- if (constantPoolNameUsage.get(candidateName) != null) {
- index ++;
- } else {
- constantPoolNameUsage.put(candidateName, localType);
- break;
- }
- }
- 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<memberTypes.length;i++) {
- // recordReference(memberTypes[i], memberTypes[i].sourceName);
- // }
- // }
-
- // if(superTypeName!=null) {
- // ReferenceBinding binding = environment.askForType(new char[][]
- // {superTypeName});
- // this.recordSuperTypeReference(binding);
- // }
- if (classScope != null)
- classScope.connectTypeHierarchy();
- nextType: for (int i = 0; i < referenceContext.numberInferredTypes; i++) {
- InferredType inferredType = referenceContext.inferredTypes[i];
- if(typeNames.length > 0) {
- boolean continueBuilding = false;
- for (int j = 0; !continueBuilding
- && j < typeNames.length; j++) {
- if (CharOperation.equals(inferredType.getName(),
- typeNames[j]))
- continueBuilding = true;
- }
- if (!continueBuilding)
- continue nextType;
-
- }
- if (inferredType.binding != 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;
- }
- }
-
- // 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;
- }
- }
- 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;
- }
- }
- }
- 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;
- }
- 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);
- }
-}
-public void faultInTypes() {
- faultInImports();
-
- this.referenceContext.compilationUnitBinding.faultInTypesForFieldsAndMethods();
- for (int i = 0, length = topLevelTypes.length; i < length; i++)
- topLevelTypes[i].faultInTypesForFieldsAndMethods();
-}
-
-//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);
- }
-}
-
-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;
- }
- 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;
-}
-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);
-}
-
-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;
- }
- }
-
- ((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;
- }
- 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);
- }
- }
- }
-
- }
- 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 ;
-}
-// 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++;
-}
-
-/* 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]);
- }
-}
-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
-
- 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 && !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))
- 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;
- }
- }
- 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);
- }
- ReferenceBinding superclass = type.superclass();
- 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);
- }
-
- 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;
-
- 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;
-}
-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 addExternalVar(LocalVariableBinding binding) {
- externalCompilationUnits.add(binding.declaringScope.compilationUnitScope());
-}
-}
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
deleted file mode 100644
index 12e7fc93..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ExtraCompilerModifiers.java
+++ /dev/null
@@ -1,39 +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.compiler.lookup;
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode;
-import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants;
-
-// TODO (philippe) these should be moved to tagbits
-public interface ExtraCompilerModifiers { // modifier constant
- // those constants are depending upon ClassFileConstants (relying that classfiles only use the 16 lower bits)
- final int AccJustFlag = 0xFFFF;// 16 lower bits
-
- // bit17 - free
- // bit18 - use by ClassFileConstants.AccAnnotationDefault
- final int AccRestrictedAccess = ASTNode.Bit19;
- final int AccFromClassFile = ASTNode.Bit20;
- final int AccDefaultAbstract = ASTNode.Bit20;
- // bit21 - use by ClassFileConstants.AccDeprecated
- final int AccDeprecatedImplicitly = ASTNode.Bit22; // record whether deprecated itself or contained by a deprecated type
- final int AccAlternateModifierProblem = ASTNode.Bit23;
- final int AccModifierProblem = ASTNode.Bit24;
- final int AccSemicolonBody = ASTNode.Bit25;
- final int AccUnresolved = ASTNode.Bit26;
- final int AccBlankFinal = ASTNode.Bit27; // for blank final variables
- final int AccIsDefaultConstructor = ASTNode.Bit27; // for default constructor
- final int AccLocallyUsed = ASTNode.Bit28; // used to diagnose unused private/local members
- final int AccVisibilityMASK = ClassFileConstants.AccPublic | ClassFileConstants.AccProtected | ClassFileConstants.AccPrivate;
-
- final int AccOverriding = ASTNode.Bit29; // record fact a method overrides another one
- final int AccImplementing = ASTNode.Bit30; // record fact a method implements another one (it is concrete and overrides an abstract one)
-}
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
deleted file mode 100644
index ab6daf66..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/FieldBinding.java
+++ /dev/null
@@ -1,268 +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.compiler.lookup;
-
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.infer.InferredAttribute;
-import org.eclipse.wst.jsdt.internal.compiler.ast.AbstractVariableDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants;
-
-public class FieldBinding extends VariableBinding {
- public ReferenceBinding declaringClass;
-protected FieldBinding() {
- super(null, null, 0);
- // for creating problem field
-}
-public FieldBinding(char[] name, TypeBinding type, int modifiers, ReferenceBinding declaringClass) {
- super(name, type, modifiers);
- this.declaringClass = declaringClass;
-}
-public FieldBinding(InferredAttribute field, TypeBinding type, int modifiers, ReferenceBinding declaringClass) {
- this(field.name, type, modifiers, declaringClass);
- field.binding = this; // record binding in declaration
-}
-// special API used to change field declaring class for runtime visibility check
-public FieldBinding(FieldBinding initialFieldBinding, ReferenceBinding declaringClass) {
- super(initialFieldBinding.name, initialFieldBinding.type, initialFieldBinding.modifiers);
- this.declaringClass = declaringClass;
- this.id = initialFieldBinding.id;
-}
-/* API
-* Answer the receiver's binding type from Binding.BindingID.
-*/
-
-public final int kind() {
- return FIELD;
-}
-/* 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: Cannot invoke this method with a compilation unit scope.
-*/
-
-public final boolean canBeSeenBy(TypeBinding receiverType, InvocationSite invocationSite, Scope scope) {
- 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 (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;
- int depth = 0;
- ReferenceBinding receiverErasure = (ReferenceBinding)receiverType;
- ReferenceBinding declaringErasure = declaringClass;
- 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; // 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;
- }
-
- if (isPrivate()) {
- // answer true if the receiverType is the declaringClass
- // AND the invocationType and the declaringClass have a common enclosingType
-
- if (receiverType != declaringClass) {
- // special tolerance for type variable direct bounds
- return false;
- }
-
-
- if (invocationType != declaringClass) {
- ReferenceBinding outerInvocationType = invocationType;
- ReferenceBinding temp = outerInvocationType.enclosingType();
- while (temp != null) {
- outerInvocationType = temp;
- temp = temp.enclosingType();
- }
-
- ReferenceBinding outerDeclaringClass = (ReferenceBinding) declaringClass;
- temp = outerDeclaringClass.enclosingType();
- while (temp != null) {
- outerDeclaringClass = temp;
- temp = temp.enclosingType();
- }
- if (outerInvocationType != outerDeclaringClass) return false;
- }
- return true;
- }
-
- // isDefault()
- PackageBinding declaringPackage = declaringClass.fPackage;
- if (invocationType.fPackage != declaringPackage) return false;
-
- // 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;
- 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 fieldName ) returnTypeUniqueKey
- * p.X { X<T> x} --> Lp/X;.x)p/X<TT;>;
- */
-public char[] computeUniqueKey(boolean isLeaf) {
- // declaring key
- char[] declaringKey =
- this.declaringClass == null /*case of length field for an array*/
- ? CharOperation.NO_CHAR
- : this.declaringClass.computeUniqueKey(false/*not a leaf*/);
- int declaringLength = declaringKey.length;
-
- // name
- int nameLength = this.name.length;
-
- // return type
- char[] returnTypeKey = this.type == null ? new char[] {'V'} : this.type.computeUniqueKey(false/*not a leaf*/);
- int returnTypeLength = returnTypeKey.length;
-
- char[] uniqueKey = new char[declaringLength + 1 + nameLength + 1 + returnTypeLength];
- int index = 0;
- System.arraycopy(declaringKey, 0, uniqueKey, index, declaringLength);
- index += declaringLength;
- uniqueKey[index++] = '.';
- System.arraycopy(this.name, 0, uniqueKey, index, nameLength);
- index += nameLength;
- uniqueKey[index++] = ')';
- System.arraycopy(returnTypeKey, 0, uniqueKey, index, returnTypeLength);
- return uniqueKey;
-}
-
-public final int getAccessFlags() {
- return modifiers & ExtraCompilerModifiers.AccJustFlag;
-}
-
-
-/* Answer true if the receiver has default visibility
-*/
-
-public final boolean isDefault() {
- return !isPublic() && !isProtected() && !isPrivate();
-}
-/* Answer true if the receiver is a deprecated field
-*/
-
-public final boolean isDeprecated() {
- return (modifiers & ClassFileConstants.AccDeprecated) != 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 field
-*/
-
-public final boolean isStatic() {
- return (modifiers & ClassFileConstants.AccStatic) != 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 field (as opposed to parameterized instances)
- */
-public FieldBinding original() {
- return this;
-}
-public boolean isFor(AbstractVariableDeclaration variableDeclaration)
-{
- return false;
-}
-//public FieldDeclaration sourceField() {
-// SourceTypeBinding sourceType;
-// try {
-// sourceType = (SourceTypeBinding) declaringClass;
-// } catch (ClassCastException e) {
-// return null;
-// }
-//
-// FieldDeclaration[] fields = sourceType.scope.referenceContext.fields;
-// if (fields != null) {
-// for (int i = fields.length; --i >= 0;)
-// if (this == fields[i].binding)
-// return fields[i];
-// }
-// return null;
-//}
-}
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
deleted file mode 100644
index e1fc3ae0..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/FunctionTypeBinding.java
+++ /dev/null
@@ -1,149 +0,0 @@
-/*******************************************************************************
- * 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
- * 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.core.infer.InferredType;
-import org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration;
-
-public class FunctionTypeBinding extends SourceTypeBinding {
-
-
- public MethodBinding functionBinding;
- SourceTypeBinding functionTypeBinding;
-
-
- public FunctionTypeBinding(MethodBinding function, Scope scope) {
- super(TypeConstants.FUNCTION, null, scope);
-
- this.functionTypeBinding=(SourceTypeBinding)scope.getJavaLangFunction();
- this.functionBinding=function;
- this.fPackage=this.functionTypeBinding.fPackage;
-
- this.compoundName=this.functionTypeBinding.compoundName;
- this.sourceName=this.functionTypeBinding.sourceName;
- this.modifiers=this.functionTypeBinding.modifiers;
- this.fileName=this.functionTypeBinding.fileName;
- this.constantPoolName=this.functionTypeBinding.constantPoolName;
- this.signature=this.functionTypeBinding.signature;
- this.tagBits=this.functionTypeBinding.tagBits;
- this.id=this.functionTypeBinding.id;
-
- }
-
-
- public void addMethod(MethodBinding binding) {
- functionTypeBinding.addMethod(binding);
- }
-
-
- public void cleanup() {
- super.cleanup();
- functionTypeBinding.cleanup();
- }
-
-
- public FieldBinding[] fields() {
- return functionTypeBinding.fields();
- }
-
-
- public char[] genericTypeSignature() {
- return functionTypeBinding.signature();
- }
-
-
- public MethodBinding getExactConstructor(TypeBinding[] argumentTypes) {
- return functionTypeBinding.getExactConstructor(argumentTypes);
- }
-
-
- public MethodBinding getExactMethod(char[] selector, TypeBinding[] argumentTypes, CompilationUnitScope refScope) {
- return functionTypeBinding.getExactMethod(selector, argumentTypes, refScope);
- }
-
-
- public FieldBinding getField(char[] fieldName, boolean needResolve) {
- return functionTypeBinding.getField(fieldName, needResolve);
- }
-
-
- public InferredType getInferredType() {
- return functionTypeBinding.getInferredType();
- }
-
-
- public MethodBinding[] getMethods(char[] selector) {
- return functionTypeBinding.getMethods(selector);
- }
-
-
- public boolean hasMemberTypes() {
- return functionTypeBinding.hasMemberTypes();
- }
-
-
- public boolean isEquivalentTo(TypeBinding otherType) {
- return functionTypeBinding.isEquivalentTo(otherType);
- }
-
-
- public int kind() {
- return functionTypeBinding.kind();
- }
-
-
- public ReferenceBinding[] memberTypes() {
- return functionTypeBinding.memberTypes();
- }
-
-
- public MethodBinding[] methods() {
- return functionTypeBinding.methods();
- }
-
-
- public void setFields(FieldBinding[] fields) {
- functionTypeBinding.setFields(fields);
- }
-
-
- public void setMethods(MethodBinding[] methods) {
- functionTypeBinding.setMethods(methods);
- }
-
-
- public AbstractMethodDeclaration sourceMethod(MethodBinding binding) {
- return functionTypeBinding.sourceMethod(binding);
- }
-
-
- public ReferenceBinding superclass() {
- return functionTypeBinding.superclass();
- }
-
- public String toString() {
- return functionTypeBinding.toString();
- }
-
- void verifyMethods(MethodVerifier verifier) {
- functionTypeBinding.verifyMethods(verifier);
- }
-
-
- public boolean isFunctionType()
- {
- return true;
- }
-
-
-
-
-}
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
deleted file mode 100644
index 380573a8..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/GlobalBinding.java
+++ /dev/null
@@ -1,199 +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.compiler.lookup;
-
-import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfBinding;
-
-public class GlobalBinding extends Binding implements TypeConstants {
- public long tagBits = 0; // See values in the interface TagBits below
-
- public LookupEnvironment environment;
- HashtableOfBinding[] knownBindings = new HashtableOfBinding[NUMBER_BASIC_BINDING];
-
- protected GlobalBinding() {
- // for creating problem package
- }
-
- public GlobalBinding(LookupEnvironment environment) {
- this.environment = environment;
- }
-
- private void addNotFoundBinding1(char[] simpleName, int mask) {
- if (knownBindings[mask] == null)
- knownBindings[mask] = new HashtableOfBinding(25);
- knownBindings[mask].put(simpleName, LookupEnvironment.TheNotFoundType);
- }
-
- private void addNotFoundBinding(char[] simpleName, int mask) {
- if (((Binding.VARIABLE | Binding.FIELD) & mask) != 0)
- addNotFoundBinding1(simpleName, Binding.VARIABLE | Binding.FIELD);
- if ((Binding.METHOD & mask) != 0)
- addNotFoundBinding1(simpleName, Binding.METHOD);
- if ((Binding.TYPE & mask) != 0)
- addNotFoundBinding1(simpleName, Binding.TYPE);
- }
-
- void addType(ReferenceBinding element) {
- if (knownBindings[Binding.TYPE] == null)
- knownBindings[Binding.TYPE] = new HashtableOfBinding(25);
- knownBindings[Binding.TYPE].put(
- element.compoundName[element.compoundName.length - 1], element);
- }
-
- public void addBinding(Binding element, char[] name, int mask) {
- if (mask < knownBindings.length) {
- if (knownBindings[mask] == null)
- knownBindings[mask] = new HashtableOfBinding(25);
- knownBindings[mask].put(name, element);
- }
- }
-
- /*
- * API Answer the receiver's binding type from Binding.BindingID.
- */
- public final int kind() {
- return Binding.GLOBAL;
- }
-
- /*
- * slash separated name org.eclipse.wst.wst.jsdt.core -->
- * org/eclipse/jdt/core
- */
- public char[] computeUniqueKey(boolean isLeaf) {
- return new char[]{'G','L','O','B','A','L','/'};
- }
-
- /*
- * Answer the type named name; ask the oracle for the type if its not in the
- * cache. Answer a NotVisible problem type if the type is not visible from
- * the invocationPackage. Answer null if it could not be resolved.
- *
- * NOTE: This should only be used by source types/scopes which know there is
- * NOT a package with the same name.
- */
- ReferenceBinding getType(char[] name) {
- return (ReferenceBinding) getBinding(name, Binding.TYPE);
- }
-
- public Binding getBinding(char[] name, int mask) {
- Binding typeBinding = getBinding0(name, mask);
- if (typeBinding == null) {
- if ((typeBinding = environment.askForBinding(this, name, mask)) == null) {
- // not found so remember a problem type binding in the cache for
- // future lookups
- addNotFoundBinding(name, mask);
- return null;
- }
- }
-
- if (typeBinding == LookupEnvironment.TheNotFoundType)
- return null;
-
- // typeBinding = BinaryTypeBinding.resolveType(typeBinding, environment,
- // false); // no raw conversion for now
- // if (typeBinding.isNestedType())
- // return new ProblemReferenceBinding(name, typeBinding,
- // ProblemReasons.InternalNameProvided);
- return typeBinding;
- }
-
- /*
- * Answer the type named name 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: Senders must convert theNotFoundType into a real problem reference
- * type if its to returned.
- */
-
- ReferenceBinding getType0(char[] name) {
- if (knownBindings[Binding.TYPE] == null)
- return null;
- return (ReferenceBinding) knownBindings[Binding.TYPE].get(name);
- }
-
- Binding getBinding1(char[] name, int mask) {
- if (knownBindings[mask] == null)
- return null;
- return knownBindings[mask].get(name);
- }
-
- Binding getBinding0(char[] name, int mask) {
- Binding binding;
- if ((mask & (Binding.VARIABLE | Binding.FIELD)) != 0) {
- binding = getBinding1(name, Binding.VARIABLE | Binding.FIELD);
- if (binding != null)
- return binding;
- }
- if ((mask & (Binding.TYPE)) != 0) {
- binding = getBinding1(name, Binding.TYPE);
- if (binding != null)
- return binding;
- }
- if ((mask & (Binding.METHOD)) != 0) {
- binding = getBinding1(name, Binding.METHOD);
- if (binding != null)
- return binding;
- }
- return null;
- }
-
- /*
- * Answer the package or type named name; ask the oracle if it is not in the
- * cache. Answer null if it could not be resolved.
- *
- * When collisions exist between a type name & a package name, answer the
- * type. Treat the package as if it does not exist... a problem was already
- * reported when the type was defined.
- *
- * NOTE: no visibility checks are performed. THIS SHOULD ONLY BE USED BY
- * SOURCE TYPES/SCOPES.
- */
-
- public Binding getType(char[] name, int mask) {
- Binding typeBinding = getBinding0(name, mask);
- // if (typeBinding != null && typeBinding !=
- // LookupEnvironment.TheNotFoundType) {
- // typeBinding = BinaryTypeBinding.resolveType(typeBinding, environment,
- // false); // no raw conversion for now
- // if (typeBinding.isNestedType())
- // return new ProblemReferenceBinding(name, typeBinding,
- // ProblemReasons.InternalNameProvided);
- // return typeBinding;
- // }
- if (typeBinding != null)
- return typeBinding;
-
- if (mask != Binding.PACKAGE) { // have not looked
- // for it before
- if ((typeBinding = environment.askForBinding(this, name, mask)) != null) {
- // if (typeBinding.isNestedType())
- // return new ProblemReferenceBinding(name, typeBinding,
- // ProblemReasons.InternalNameProvided);
- return typeBinding;
- }
-
- // Since name could not be found, add a problem binding
- // to the collections so it will be reported as an error next time.
- addNotFoundBinding(name, mask);
- }
-
- return null;
- }
-
- public char[] readableName() /* java.lang */{
- return new char[]{'G','L','O','B','A','L','/'};
- }
-
- public String toString() {
- return "Global Namespace"; //$NON-NLS-1$
- }
-}
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
deleted file mode 100644
index de5d5e2f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ImportBinding.java
+++ /dev/null
@@ -1,46 +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.compiler.lookup;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ImportReference;
-
-public class ImportBinding extends Binding {
- public char[][] compoundName;
- public boolean onDemand;
- public ImportReference reference;
-
- public Binding resolvedImport; // must ensure the import is resolved
-
-public ImportBinding(char[][] compoundName, boolean isOnDemand, Binding binding, ImportReference reference) {
- this.compoundName = compoundName;
- this.onDemand = isOnDemand;
- this.resolvedImport = binding;
- this.reference = reference;
-}
-/* API
-* Answer the receiver's binding type from Binding.BindingID.
-*/
-
-public final int kind() {
- return IMPORT;
-}
-
-public char[] readableName() {
- if (onDemand)
- return CharOperation.concat(CharOperation.concatWith(compoundName, '.'), ".*".toCharArray()); //$NON-NLS-1$
- else
- return CharOperation.concatWith(compoundName, '.');
-}
-public String toString() {
- return "import : " + new String(readableName()); //$NON-NLS-1$
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ImportConflictBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ImportConflictBinding.java
deleted file mode 100644
index 38e44661..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ImportConflictBinding.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ImportReference;
-
-public class ImportConflictBinding extends ImportBinding {
-public ReferenceBinding conflictingTypeBinding; // must ensure the import is resolved
-
-public ImportConflictBinding(char[][] compoundName, Binding methodBinding, ReferenceBinding conflictingTypeBinding, ImportReference reference) {
- super(compoundName, false, methodBinding, reference);
- this.conflictingTypeBinding = conflictingTypeBinding;
-}
-public char[] readableName() {
- return CharOperation.concatWith(compoundName, '.');
-}
-public String toString() {
- return "method import : " + new String(readableName()); //$NON-NLS-1$
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/IndirectMethodBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/IndirectMethodBinding.java
deleted file mode 100644
index a53628a1..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/IndirectMethodBinding.java
+++ /dev/null
@@ -1,22 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.lookup;
-
-public class IndirectMethodBinding extends MethodBinding {
- TypeBinding receiverType;
-
- public IndirectMethodBinding(int modifiers, TypeBinding receiverType, TypeBinding[] parameters,ReferenceBinding declaringClass)
- {
- super(modifiers,null,TypeBinding.UNKNOWN,parameters,declaringClass);
- this.receiverType=receiverType;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/InnerEmulationDependency.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/InnerEmulationDependency.java
deleted file mode 100644
index 776d638b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/InnerEmulationDependency.java
+++ /dev/null
@@ -1,22 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.lookup;
-
-public class InnerEmulationDependency{
-
- public BlockScope scope;
- public boolean wasEnclosingInstanceSupplied;
-
- public InnerEmulationDependency(BlockScope scope, boolean wasEnclosingInstanceSupplied) {
- this.scope = scope;
- this.wasEnclosingInstanceSupplied = wasEnclosingInstanceSupplied;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/InvocationSite.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/InvocationSite.java
deleted file mode 100644
index ac70381a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/InvocationSite.java
+++ /dev/null
@@ -1,27 +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.compiler.lookup;
-
-public interface InvocationSite {
-
- boolean isSuperAccess();
- boolean isTypeAccess();
- void setDepth(int depth);
- void setFieldIndex(int depth);
-
- // in case the receiver type does not match the actual receiver type
- // e.g. pkg.Type.C (receiver type of C is type of source context,
- // but actual receiver type is pkg.Type)
- // e.g2. in presence of implicit access to enclosing type
- void setActualReceiverType(ReferenceBinding receiverType);
- int sourceStart();
- int sourceEnd();
-}
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
deleted file mode 100644
index 432cc387..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/LibraryAPIsBinding.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.lookup;
-
-import java.io.File;
-
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration;
-
-
-public class LibraryAPIsBinding extends SourceTypeBinding {
- CompilationUnitScope compilationUnitScope;
- private char[]shortName;
-
- char [] path;
-
-
-
- public LibraryAPIsBinding(CompilationUnitScope scope,PackageBinding fPackage, char [] fileName ) {
- this.compilationUnitScope=scope;
- this.memberTypes=Binding.NO_MEMBER_TYPES;
- this.fileName=fileName;
- this.sourceName=this.fileName;
- setShortName(this.fileName);
- this.fPackage = fPackage;
- this.compoundName=new char [][]{fileName};
- this.scope = scope;
-
- // expect the fields & methods to be initialized correctly later
- this.fields = Binding.NO_FIELDS;
- this.methods = Binding.NO_METHODS;
-
- computeId();
-
- }
-
- private void setShortName(char[] fileName) {
- for (int i=fileName.length-1;i>=0;i--)
- {
- if (fileName[i]==File.separatorChar || fileName[i]=='/')
- {
- shortName=new char[fileName.length-1-i];
- this.path=new char[i];
- System.arraycopy(fileName, i+1, shortName, 0, shortName.length);
- System.arraycopy(fileName, 0, this.path, 0, this.path.length);
- return;
- }
- }
- shortName=fileName;
- this.path=new char[0];
- }
-
- public int kind() {
- return COMPILATION_UNIT;
- }
-
- public char[] signature() /* Ljava/lang/Object; */ {
- if (this.signature != null)
- return this.signature;
-
- return this.signature = CharOperation.concat(Signature.C_COMPILATION_UNIT, constantPoolName(), ';');
- }
-
-
- public AbstractMethodDeclaration sourceMethod(MethodBinding binding) {
- return null;
- }
-
- public char[] qualifiedSourceName() {
- return CharOperation.concatWith(compoundName, '.');
- }
-
- public char[] qualifiedPackageName() {
- return this.path;
- }
-
- public void cleanup()
- {
- super.cleanup();
- this.compilationUnitScope=null;
- }
-}
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
deleted file mode 100644
index 2fbb4cb2..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/LibraryAPIsScope.java
+++ /dev/null
@@ -1,139 +0,0 @@
-/*******************************************************************************
- * 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
- * Erling Ellingsen - patch for bug 125570
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.lookup;
-
-import java.util.HashMap;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.CompilationResult;
-import org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfObject;
-import org.eclipse.wst.jsdt.internal.oaametadata.LibraryAPIs;
-
-
-
-public class LibraryAPIsScope extends CompilationUnitScope {
-
-
- HashMap resolvedTypes=new HashMap();
- HashtableOfObject translations=new HashtableOfObject();
- LibraryAPIs apis;
-public LibraryAPIsScope(LibraryAPIs apis, LookupEnvironment environment) {
-
- super(environment);
- this.apis=apis;
- this.referenceContext = null;
-
-
- this.currentPackageName = CharOperation.NO_CHAR_CHAR;
-
- this.resolvedTypes.put("any", TypeBinding.ANY);
- this.resolvedTypes.put("Any", TypeBinding.ANY);
- this.resolvedTypes.put("null", TypeBinding.NULL);
-
- translations.put("object".toCharArray(), "Object".toCharArray());
- translations.put("boolean".toCharArray(), "Boolean".toCharArray());
- translations.put("number".toCharArray(), "Number".toCharArray());
- translations.put("string".toCharArray(), "String".toCharArray());
- translations.put("array".toCharArray(), "Array".toCharArray());
-
- 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;
-
-}
-
-
-
-
-public PackageBinding getDefaultPackage() {
- return environment.defaultPackage;
-}
-
-
-public TypeBinding resolveType(String name)
-{
-
- if (name==null)
- return TypeBinding.ANY;
-
- TypeBinding binding = (TypeBinding)this.resolvedTypes.get(name);
- if (binding!=null)
- return binding;
-
-
- if (name.length()>1 && name.charAt(0)=='[' && name.charAt(name.length()-1)==']')
- {
- name=name.substring(1, name.length()-1);
-
- TypeBinding memberType = resolveType(name);
- binding=new ArrayBinding(memberType, 1, this.compilationUnitScope().environment) ;
-
- }
- else {
- if (name.indexOf('|')>0)
- {
-
- char[][] names = CharOperation.splitAndTrimOn('|', name.toCharArray());
- for (int i = 0; i < names.length; i++) {
- names[i]=translateName(names[i]);
- }
- binding=new MultipleTypeBinding(this,names);
- }
- else
- {
- binding = this.getType(translateName(name.toCharArray()));
- }
- /* the inferred type isn't valid, so don't assign it to the variable */
- if(!binding.isValidBinding())
- binding=TypeBinding.UNKNOWN;
- }
-
-
-// if (node!=null && !this.resolvedType.isValidBinding()) {
-// libraryScope.problemReporter().invalidType(node, this.resolvedType);
-// return null;
-// }
-// if (node!=null && node.isTypeUseDeprecated(this.resolvedType, libraryScope))
-// libraryScope.problemReporter().deprecatedType(this.resolvedType, node);
-
-
- this.resolvedTypes.put(name, binding);
- return binding;
-}
-
-private char[] translateName(char[] name) {
- char [] newName=(char[])this.translations.get(name);
- return (newName!=null) ? newName : name;
-}
-
-
-
-
-public String toString() {
- return "--- LibraryAPIsScope Scope : " + new String(referenceContext.getFileName()); //$NON-NLS-1$
-}
-
-public void cleanup()
-{
- super.cleanup();
-}
-
-
-
-
-public char[] getFileName() {
- return this.apis.fileName;
-}
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/LocalFunctionBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/LocalFunctionBinding.java
deleted file mode 100644
index 49cf3262..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/LocalFunctionBinding.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.lookup;
-
-public class LocalFunctionBinding extends MethodBinding {
- final static char[] LocalFunctionPrefix = { '$', 'L', 'o', 'c', 'a', 'l', 'f', 'u', 'n', 'c', '$' };
-
-
- public LocalFunctionBinding(int modifiers, char[] selector,
- TypeBinding returnType, TypeBinding[] parameters, ReferenceBinding declaringClass) {
- super(modifiers, selector, returnType, parameters,
- declaringClass);
- }
-
-
-
-}
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
deleted file mode 100644
index 2e7dbbe6..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/LocalTypeBinding.java
+++ /dev/null
@@ -1,185 +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.compiler.lookup;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.CaseStatement;
-
-public final class LocalTypeBinding extends NestedTypeBinding {
- final static char[] LocalTypePrefix = { '$', 'L', 'o', 'c', 'a', 'l', '$' };
-
- private InnerEmulationDependency[] dependents;
- public ArrayBinding[] localArrayBindings; // used to cache array bindings of various dimensions for this local type
- public CaseStatement enclosingCase; // from 1.4 on, local types should not be accessed across switch case blocks (52221)
- public int sourceStart; // used by computeUniqueKey to uniquely identify this binding
- public MethodBinding enclosingMethod;
-
-public LocalTypeBinding(ClassScope scope, SourceTypeBinding enclosingType, CaseStatement switchCase) {
- super(
- new char[][] {CharOperation.concat(LocalTypePrefix, scope.referenceContext.name)},
- scope,
- enclosingType);
-
- if (this.sourceName == CharOperation.NO_CHAR)
- this.tagBits |= TagBits.AnonymousTypeMask;
- else
- this.tagBits |= TagBits.LocalTypeMask;
- this.enclosingCase = switchCase;
- this.sourceStart = scope.referenceContext.sourceStart;
- MethodScope methodScope = scope.enclosingMethodScope();
- AbstractMethodDeclaration declaration = methodScope.referenceMethod();
- if (declaration != null) {
- this.enclosingMethod = declaration.binding;
- }
-}
-/* Record a dependency onto a source target type which may be altered
-* by the end of the innerclass emulation. Later on, we will revisit
-* all its dependents so as to update them (see updateInnerEmulationDependents()).
-*/
-
-public void addInnerEmulationDependent(BlockScope dependentScope, boolean wasEnclosingInstanceSupplied) {
- int index;
- if (dependents == null) {
- index = 0;
- dependents = new InnerEmulationDependency[1];
- } else {
- index = dependents.length;
- for (int i = 0; i < index; i++)
- if (dependents[i].scope == dependentScope)
- return; // already stored
- System.arraycopy(dependents, 0, (dependents = new InnerEmulationDependency[index + 1]), 0, index);
- }
- dependents[index] = new InnerEmulationDependency(dependentScope, wasEnclosingInstanceSupplied);
- // System.out.println("Adding dependency: "+ new String(scope.enclosingType().readableName()) + " --> " + new String(this.readableName()));
-}
-public char[] computeUniqueKey(boolean isLeaf) {
- char[] outerKey = outermostEnclosingType().computeUniqueKey(isLeaf);
- int semicolon = CharOperation.lastIndexOf(';', outerKey);
-
- StringBuffer sig = new StringBuffer();
- sig.append(outerKey, 0, semicolon);
-
- // insert $sourceStart
- sig.append('$');
- sig.append(String.valueOf(this.sourceStart));
-
- // insert $LocalName if local
- if (!isAnonymousType()) {
- sig.append('$');
- sig.append(this.sourceName);
- }
-
- // insert remaining from outer key
- sig.append(outerKey, semicolon, outerKey.length-semicolon);
-
- int sigLength = sig.length();
- char[] uniqueKey = new char[sigLength];
- sig.getChars(0, sigLength, uniqueKey, 0);
- return uniqueKey;
-}
-
-public char[] constantPoolName() /* java/lang/Object */ {
- return constantPoolName;
-}
-
-ArrayBinding createArrayType(int dimensionCount, LookupEnvironment lookupEnvironment) {
- if (localArrayBindings == null) {
- localArrayBindings = new ArrayBinding[] {new ArrayBinding(this, dimensionCount, lookupEnvironment)};
- return localArrayBindings[0];
- }
-
- // find the cached array binding for this dimensionCount (if any)
- int length = localArrayBindings.length;
- for (int i = 0; i < length; i++)
- if (localArrayBindings[i].dimensions == dimensionCount)
- return localArrayBindings[i];
-
- // no matching array
- System.arraycopy(localArrayBindings, 0, localArrayBindings = new ArrayBinding[length + 1], 0, length);
- 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<T> */ {
- char[] readableName;
- if (isAnonymousType()) {
- readableName = CharOperation.concat(TypeConstants.ANONYM_PREFIX, superclass.readableName(), TypeConstants.ANONYM_SUFFIX);
- } else if (isMemberType()) {
- readableName = CharOperation.concat(enclosingType().readableName(), this.sourceName, '.');
- } else {
- readableName = this.sourceName;
- }
- return readableName;
-}
-
-public char[] shortReadableName() /*Object*/ {
- char[] shortReadableName;
- if (isAnonymousType()) {
- shortReadableName = CharOperation.concat(TypeConstants.ANONYM_PREFIX, superclass.shortReadableName(), TypeConstants.ANONYM_SUFFIX);
- } else if (isMemberType()) {
- shortReadableName = CharOperation.concat(enclosingType().shortReadableName(), sourceName, '.');
- } else {
- shortReadableName = sourceName;
- }
- return shortReadableName;
-}
-
-// Record that the type is a local member type
-public void setAsMemberType() {
- this.tagBits |= TagBits.MemberTypeMask;
-}
-
-public void setConstantPoolName(char[] computedConstantPoolName) /* java/lang/Object */ {
- this.constantPoolName = computedConstantPoolName;
-}
-/*
- * 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=102284)
- */
-public char[] signature() {
- if (this.signature == null && constantPoolName() == null) {
- if (isAnonymousType())
- setConstantPoolName(superclass().sourceName());
- else
- setConstantPoolName(sourceName());
- }
- return super.signature();
-}
-public char[] sourceName() {
- if (isAnonymousType()) {
- return CharOperation.concat(TypeConstants.ANONYM_PREFIX, superclass.sourceName(), TypeConstants.ANONYM_SUFFIX);
- } else
- return sourceName;
-}
-public String toString() {
- if (isAnonymousType())
- return "Anonymous type : " + super.toString(); //$NON-NLS-1$
- if (isMemberType())
- return "Local member type : " + new String(sourceName()) + " " + super.toString(); //$NON-NLS-2$ //$NON-NLS-1$
- return "Local type : " + new String(sourceName()) + " " + super.toString(); //$NON-NLS-2$ //$NON-NLS-1$
-}
-}
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
deleted file mode 100644
index c439b76f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/LocalVariableBinding.java
+++ /dev/null
@@ -1,248 +0,0 @@
-/*******************************************************************************
- * 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.compiler.lookup;
-
-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.CompilationUnitDeclaration;
-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.impl.ReferenceContext;
-
-public class LocalVariableBinding extends VariableBinding {
-
- public int resolvedPosition; // for code generation (position in method context)
-
- public static final int UNUSED = 0;
- public static final int USED = 1;
- public static final int FAKE_USED = 2;
- public int useFlag; // for flow analysis (default is UNUSED)
-
- public BlockScope declaringScope; // back-pointer to its declaring scope
- public LocalDeclaration declaration; // for source-positions
-
- public int[] initializationPCs;
- public int initializationCount = 0;
-
- // for synthetic local variables
- // if declaration slot is not positionned, the variable will not be listed in attribute
- // note that the name of a variable should be chosen so as not to conflict with user ones (usually starting with a space char is all needed)
- public LocalVariableBinding(char[] name, TypeBinding type, int modifiers, boolean isArgument) {
- super(name, type, modifiers);
- if (isArgument) this.tagBits |= TagBits.IsArgument;
- }
-
- // regular local variable or argument
- public LocalVariableBinding(LocalDeclaration declaration, TypeBinding type, int modifiers, boolean isArgument) {
-
- this(declaration.name, type!=null ? type : TypeBinding.UNKNOWN, modifiers, isArgument);
- this.declaration = declaration;
- }
-
- /* API
- * Answer the receiver's binding type from Binding.BindingID.
- */
- public final int kind() {
-
- return LOCAL;
- }
-
- /*
- * declaringUniqueKey # scopeIndex / varName p.X { void foo() { int local; }
- * } --> Lp/X;.foo()V#1/local
- */
- public char[] computeUniqueKey(boolean isLeaf) {
- StringBuffer buffer = new StringBuffer();
-
- // declaring method or type
- BlockScope scope = this.declaringScope;
- if (scope != null) {
- // the scope can be null. See
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=185129
-
- if (scope instanceof CompilationUnitScope) {
- CompilationUnitScope compilationUnitScope = (CompilationUnitScope) scope;
- buffer.append(compilationUnitScope.referenceContext.compilationUnitBinding
- .computeUniqueKey(false));
- } else {
- ReferenceContext referenceContext = null;
- MethodScope methodScope = scope instanceof MethodScope ? (MethodScope) scope
- : scope.enclosingMethodScope();
- if (methodScope != null) {
- referenceContext = methodScope.referenceContext;
- } else
- referenceContext = scope.enclosingCompilationUnit().scope
- .referenceCompilationUnit();
- if (referenceContext instanceof AbstractMethodDeclaration) {
- MethodBinding methodBinding = ((AbstractMethodDeclaration) referenceContext).binding;
- if (methodBinding != null) {
- 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
- */));
- }
- } else if (referenceContext instanceof CompilationUnitDeclaration) {
- CompilationUnitBinding compilationUnitBinding = ((CompilationUnitDeclaration) referenceContext).compilationUnitBinding;
- if (compilationUnitBinding != null) {
- buffer.append(compilationUnitBinding
- .computeUniqueKey(false/* not a leaf */));
- }
- }
- }
- // scope index
- getScopeKey(scope, buffer);
- }
-
-
- // variable name
- buffer.append('#');
- buffer.append(this.name);
-
- int length = buffer.length();
- char[] uniqueKey = new char[length];
- buffer.getChars(0, length, uniqueKey, 0);
- return uniqueKey;
- }
-
-// public AnnotationBinding[] getAnnotations() {
-// if (this.declaringScope == null) {
-// if ((this.tagBits & TagBits.AnnotationResolved) != 0) {
-// // annotation are already resolved
-// if (this.declaringScope == null)
-// if (this.declaration == null) {
-// return Binding.NO_ANNOTATIONS;
-// }
-// Annotation[] annotations = this.declaration.annotations;
-// if (annotations != null) {
-// int length = annotations.length;
-// AnnotationBinding[] annotationBindings = new AnnotationBinding[length];
-// for (int i = 0; i < length; i++) {
-// AnnotationBinding compilerAnnotation = annotations[i].getCompilerAnnotation();
-// if (compilerAnnotation == null) {
-// return Binding.NO_ANNOTATIONS;
-// }
-// annotationBindings[i] = compilerAnnotation;
-// }
-// return annotationBindings;
-// }
-// }
-// return Binding.NO_ANNOTATIONS;
-// }
-// SourceTypeBinding sourceType = this.declaringScope.enclosingSourceType();
-// if (sourceType == null)
-// return Binding.NO_ANNOTATIONS;
-//
-// AnnotationBinding[] annotations = sourceType.retrieveAnnotations(this);
-// if ((this.tagBits & TagBits.AnnotationResolved) == 0) {
-// if (((this.tagBits & TagBits.IsArgument) != 0) && this.declaration != null) {
-// Annotation[] annotationNodes = declaration.annotations;
-// if (annotationNodes != null) {
-// int length = annotationNodes.length;
-// ASTNode.resolveAnnotations(this.declaringScope, annotationNodes, this);
-// annotations = new AnnotationBinding[length];
-// for (int i = 0; i < length; i++)
-// annotations[i] = new AnnotationBinding(annotationNodes[i]);
-// setAnnotations(annotations);
-// }
-// }
-// }
-// return annotations;
-// }
-//
- private void getScopeKey(BlockScope scope, StringBuffer buffer) {
- int scopeIndex = scope.scopeIndex();
- if (scopeIndex != -1) {
- getScopeKey((BlockScope)scope.parent, buffer);
- buffer.append('#');
- buffer.append(scopeIndex);
- }
- }
-
- // Answer whether the variable binding is a secret variable added for code gen purposes
- public boolean isSecret() {
-
- return declaration == null && (this.tagBits & TagBits.IsArgument) == 0;
- }
-
- public final boolean isSameCompilationUnit(Scope scope)
- {
- return this.declaringScope.compilationUnitScope()==scope;
- }
-
- public void recordInitializationEndPC(int pc) {
-
- if (initializationPCs[((initializationCount - 1) << 1) + 1] == -1)
- initializationPCs[((initializationCount - 1) << 1) + 1] = pc;
- }
-
- public void recordInitializationStartPC(int pc) {
-
- if (initializationPCs == null) return;
- if (initializationCount > 0) {
- int previousEndPC = initializationPCs[ ((initializationCount - 1) << 1) + 1];
- // interval still open, keep using it (108180)
- if (previousEndPC == -1) {
- return;
- }
- // optimize cases where reopening a contiguous interval
- if (previousEndPC == pc) {
- initializationPCs[ ((initializationCount - 1) << 1) + 1] = -1; // reuse previous interval (its range will be augmented)
- return;
- }
- }
- int index = initializationCount << 1;
- if (index == initializationPCs.length) {
- System.arraycopy(initializationPCs, 0, (initializationPCs = new int[initializationCount << 2]), 0, index);
- }
- initializationPCs[index] = pc;
- initializationPCs[index + 1] = -1;
- initializationCount++;
- }
-
- public boolean isFor(AbstractVariableDeclaration variableDeclaration)
- {
- return variableDeclaration.equals(this.declaration);
- }
- public String toString() {
-
- String s = super.toString();
- switch (useFlag){
- case USED:
- s += "[pos: " + String.valueOf(resolvedPosition) + "]"; //$NON-NLS-2$ //$NON-NLS-1$
- break;
- case UNUSED:
- s += "[pos: unused]"; //$NON-NLS-1$
- break;
- case FAKE_USED:
- s += "[pos: fake_used]"; //$NON-NLS-1$
- break;
- }
- s += "[id:" + String.valueOf(id) + "]"; //$NON-NLS-2$ //$NON-NLS-1$
- if (initializationCount > 0) {
- s += "[pc: "; //$NON-NLS-1$
- for (int i = 0; i < initializationCount; i++) {
- if (i > 0)
- s += ", "; //$NON-NLS-1$
- s += String.valueOf(initializationPCs[i << 1]) + "-" + ((initializationPCs[(i << 1) + 1] == -1) ? "?" : String.valueOf(initializationPCs[(i<< 1) + 1])); //$NON-NLS-2$ //$NON-NLS-1$
- }
- s += "]"; //$NON-NLS-1$
- }
- return s;
- }
-}
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
deleted file mode 100644
index 31bf3f51..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/LookupEnvironment.java
+++ /dev/null
@@ -1,1009 +0,0 @@
-/*******************************************************************************
- * 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.compiler.lookup;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Stack;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-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.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.env.NameEnvironmentAnswer;
-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.problem.ProblemReporter;
-import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfPackage;
-import org.eclipse.wst.jsdt.internal.compiler.util.SimpleSetOfCharArray;
-import org.eclipse.wst.jsdt.internal.oaametadata.ClassData;
-import org.eclipse.wst.jsdt.internal.oaametadata.LibraryAPIs;
-
-public class LookupEnvironment implements ProblemReasons, TypeConstants {
-
- final static int BUILD_FIELDS_AND_METHODS = 4;
- final static int BUILD_TYPE_HIERARCHY = 1;
- final static int CHECK_AND_SET_IMPORTS = 2;
- final static int CONNECT_TYPE_HIERARCHY = 3;
- static final ProblemReferenceBinding TheNotFoundType = new ProblemReferenceBinding(CharOperation.NO_CHAR, null, NotFound);
-
- /**
- * Map from typeBinding -> accessRestriction rule
- */
- private Map accessRestrictions;
- ImportBinding[] defaultImports;
-
- public PackageBinding defaultPackage;
- HashtableOfPackage knownPackages;
- private int lastCompletedUnitIndex = -1;
- private int lastUnitIndex = -1;
-
- public INameEnvironment nameEnvironment;
- public CompilerOptions globalOptions;
- public ProblemReporter problemReporter;
-
-
- // indicate in which step on the compilation we are.
- // step 1 : build the reference binding
- // step 2 : conect the hierarchy (connect bindings)
- // step 3 : build fields and method bindings.
- private int stepCompleted;
- 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
-
- private CompilationUnitDeclaration[] units = new CompilationUnitDeclaration[4];
- private MethodVerifier verifier;
- 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;
-
- 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
- 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);
- //}
-
- }
-
-
- return getCachedType(compoundName);
-}
-/* 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;
- if (types.length == 1 && (kind & Binding.TYPE) > 1 && !fAskingForTypeBinding.isEmpty() && CharOperation.equals(types[0], (char[])fAskingForTypeBinding.peek()))
- return;
-
- fAddingUnits=true;
- try{
- for (int i = 0; i < types.length; i++) {
- 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();
-// 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());
-// }
- }
- 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());
-// }
- }
- }
- }
- }
- finally {
- fAddingUnits = false;
- }
-}
-
-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)
- return;
-
-
- 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());
- }
- }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] instanceof MetadataFile)
-// {
-// typeRequestor.accept(((MetadataFile)compilationUnits[i]).getAPIs());
-// }
-// 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());
-
-}
-
-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;
- }
- 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);
- }
-
- }
- }
- 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);
-
- 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;
- }
- }
-
- 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);
- //knownPackages.put(compoundName[0], packageBinding);
-
-
- }
-
- 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
-// 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.
- */
-
-public ReferenceBinding getCachedType(char[][] compoundName) {
- if (compoundName.length == 1) {
- if (defaultPackage == null)
- return null;
- return defaultPackage.getType0(compoundName[0]);
- }
-
- PackageBinding packageBinding = getPackage0(compoundName[0]);
- if (packageBinding == null)
- return null;
-
- 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()))
- 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;
-// return null;
-//}
- PackageBinding packageBinding = getPackage0(name);
- if (packageBinding != 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]);
- if (packageBinding != null)
- return null; // collides with a known package... should not call this method in such a case
- 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 {
- 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];
-
- for (int i = 0; i < typeLength; i++) {
- ClassData clazz=classes[i];
- char[][] className = CharOperation.arrayConcat(packageBinding.compoundName,clazz.name.toCharArray());
-
- SourceTypeBinding binding = new MetatdataTypeBinding(className, packageBinding, clazz, scope) ;
- this.defaultPackage.addType(binding);
- binding.fPackage.addType(binding);
- topLevelTypes[count++] = binding;
-
- }
- if (count != topLevelTypes.length)
- System.arraycopy(topLevelTypes, 0, topLevelTypes = new SourceTypeBinding[count], 0, count);
-
- char [] fullFileName=libraryMetaData.fileName;
-
- LibraryAPIsBinding libraryAPIsBinding=new LibraryAPIsBinding(null,defaultPackage,fullFileName);
-
- if (packageBinding!=this.defaultPackage)
- packageBinding.addBinding(libraryAPIsBinding, libraryAPIsBinding.shortReadableName(), Binding.COMPILATION_UNIT);
-
-
-}
-
-
-}
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
deleted file mode 100644
index a2f93291..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MemberTypeBinding.java
+++ /dev/null
@@ -1,35 +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.compiler.lookup;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-
-public final class MemberTypeBinding extends NestedTypeBinding {
-public MemberTypeBinding(char[][] compoundName, ClassScope scope, SourceTypeBinding enclosingType) {
- super(compoundName, scope, enclosingType);
- this.tagBits |= TagBits.MemberTypeMask;
-}
-/* Answer the receiver's constant pool name.
-*
-* NOTE: This method should only be used during/after code gen.
-*/
-
-public char[] constantPoolName() /* java/lang/Object */ {
- if (constantPoolName != null)
- return constantPoolName;
-
- return constantPoolName = CharOperation.concat(enclosingType().constantPoolName(), sourceName, '$');
-}
-
-public String toString() {
- return "Member type : " + new String(sourceName()) + " " + super.toString(); //$NON-NLS-2$ //$NON-NLS-1$
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/Messages.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/Messages.java
deleted file mode 100644
index 3e1d6378..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/Messages.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.lookup;
-
-import java.util.MissingResourceException;
-import java.util.ResourceBundle;
-
-public class Messages {
- private static final String BUNDLE_NAME = "org.eclipse.wst.jsdt.internal.compiler.lookup.messages"; //$NON-NLS-1$
-
- private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
- .getBundle(BUNDLE_NAME);
-
- private Messages() {
- }
-
- public static String getString(String key) {
- try {
- return RESOURCE_BUNDLE.getString(key);
- } catch (MissingResourceException e) {
- return '!' + key + '!';
- }
- }
-}
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
deleted file mode 100644
index 228d5cdc..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MetatdataTypeBinding.java
+++ /dev/null
@@ -1,965 +0,0 @@
-/*******************************************************************************
- * 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.compiler.lookup;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration;
-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;
-import org.eclipse.wst.jsdt.internal.oaametadata.ClassData;
-import org.eclipse.wst.jsdt.internal.oaametadata.Method;
-import org.eclipse.wst.jsdt.internal.oaametadata.Parameter;
-import org.eclipse.wst.jsdt.internal.oaametadata.Property;
-
-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;
- }
-
- // 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.id = count;
- // field's type will be resolved when needed for top level types
-// checkAndSetModifiersForField(fieldBinding, field);
-
- 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++]=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);
- 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);
-
-
- 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);
-}
-
-
-
-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;
-// 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);
-
- }
-
- 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;
- }
- }
- 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;
- }
- 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)
- 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];
- }
- this.fields = newFields;
- }
- }
- this.tagBits |= TagBits.AreFieldsComplete;
- }
- 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;
-// }
- }
- }
- } 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) {
-// 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;
- }
- }
- }
- 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;
- }
- }
- } 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];
-// 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);
- }
- }
- return null;
-}
-
-
-public FieldBinding getField(char[] fieldName, boolean needResolve) {
-
- if ((this.tagBits & TagBits.AreFieldsComplete) != 0)
- return ReferenceBinding.binarySearch(fieldName, this.fields);
-
- 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;
- }
- this.fields = newFields;
- }
- }
- }
- }
- return null;
-}
-
-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) {
- 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;
- System.arraycopy(this.methods, start, result = new MethodBinding[length], 0, length);
- } else {
- return Binding.NO_METHODS;
- }
- 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
- }
- }
- }
- 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);
- }
- 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)
- continue nextSibling;
-
- boolean equalTypeVars = true;
- MethodBinding subMethod = method2;
- if (!equalTypeVars) {
- MethodBinding temp = method2;
- if (temp != null) {
- 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])
- break;
- }
- if (index >= 0)
- 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;
- }
- }
-
- // handle forward references to potential default abstract methods
- // addDefaultAbstractMethods();
- this.tagBits |= TagBits.AreMethodsComplete;
- }
- }
- 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;
-
-}
-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;
-}
-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;
- }
- }
- // 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());
- }
-
- 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$
- }
-
- 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$
- }
-
- buffer.append("\n\n"); //$NON-NLS-1$
- return buffer.toString();
-}
-void verifyMethods(MethodVerifier verifier) {
- //verifier.verify(this);
-
-// for (int i = this.memberTypes.length; --i >= 0;)
-// ((SourceTypeBinding) this.memberTypes[i]).verifyMethods(verifier);
-}
-
-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 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();
-}
-
-
-public boolean contains(ReferenceBinding binding)
-{
- return false;
-}
-
-public ClassData getClassData()
-{
- return this.classData;
-}
-
-
-public LibraryAPIsScope getLibraryAPIsScope()
-{
- return this.libraryScope;
-}
-
-}
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
deleted file mode 100644
index 78a92555..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MethodBinding.java
+++ /dev/null
@@ -1,628 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.lookup;
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants;
-import org.eclipse.wst.jsdt.internal.oaametadata.Method;
-
-public class MethodBinding extends Binding {
-
- public int modifiers;
- public char[] selector;
- public TypeBinding returnType;
- public TypeBinding[] parameters;
- public ReferenceBinding declaringClass;
- char[] signature;
- public long tagBits;
- public FunctionTypeBinding functionTypeBinding;
- public ReferenceBinding allocationType;
- public Method oaaMethod;
-
-
-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;
-
- int length = parameters.length;
- if (length != args.length)
- return false;
-
- for (int i = 0; i < length; i++)
- if (parameters[i] != args[i])
- 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))
- 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
- }
- 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 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;
- }
-
- 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;
- }
-
- // isDefault()
- PackageBinding declaringPackage = declaringClass.fPackage;
- if (invocationType.fPackage != declaringPackage) return false;
-
- // 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 { <T> void bar(X<T> t) } --> Lp/X;.bar<T:Ljava/lang/Object;>(LX<TT;>;)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.
-*
-* <init> for constructors
-* <clinit> 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 <code>index</code>th parameter
-// * @throws ArrayIndexOutOfBoundsException when <code>index</code> 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 <code>null</code> if there is no default value
- */
-public Object getDefaultValue() {
- MethodBinding originalMethod = this.original();
- if ((originalMethod.tagBits & TagBits.DefaultValueResolved) == 0) {
- originalMethod.tagBits |= TagBits.DefaultValueResolved;
- }
- 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());
- }
- }
- 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());
- }
- }
- 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('(');
-
- 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();
-
- 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) 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 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;
-}
-/**
- * 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();
-
-}
-
-void ensureBindingsAreComplete()
-{
- if (this.declaringClass instanceof SourceTypeBinding) {
- SourceTypeBinding parentBinding = (SourceTypeBinding) this.declaringClass;
- if ((parentBinding.tagBits & TagBits.AreMethodsComplete) == 0) {
- parentBinding.methods(); //finish resolving method bindings
- }
- }
-}
-
-}
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
deleted file mode 100644
index 57874e80..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MethodScope.java
+++ /dev/null
@@ -1,410 +0,0 @@
-/*******************************************************************************
- * 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.compiler.lookup;
-
-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.QualifiedNameReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.SingleNameReference;
-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;
-
-/**
- * Particular block scope used for methods, constructors or clinits, representing
- * its outermost blockscope. Note also that such a scope will be provided to enclose
- * field initializers subscopes as well.
- */
-public class MethodScope extends BlockScope {
-
- public ReferenceContext referenceContext;
- public boolean isStatic; // method modifier or initializer one
-
- //fields used during name resolution
- public boolean isConstructorCall = false;
- public FieldBinding initializedField; // the field being initialized
- public int lastVisibleFieldID = -1; // the ID of the last field which got declared
- // note that #initializedField can be null AND lastVisibleFieldID >= 0, when processing instance field initializers.
-
- // flow analysis
- public int analysisIndex; // for setting flow-analysis id
- public boolean isPropagatingInnerClassEmulation;
-
- // for local variables table attributes
- public int lastIndex = 0;
- public long[] definiteInits = new long[4];
- public long[][] extraDefiniteInits = new long[4][];
-
-
- public static final char [] ARGUMENTS_NAME={'a','r','g','u','m','e','n','t','s'};
-
- public LocalVariableBinding argumentsBinding ;
-
-
- public MethodScope(Scope parent, ReferenceContext context, boolean isStatic) {
-
- super(METHOD_SCOPE, parent);
- locals = new LocalVariableBinding[5];
- this.referenceContext = context;
- this.isStatic = isStatic;
- this.startIndex = 0;
- argumentsBinding = new LocalVariableBinding(ARGUMENTS_NAME,TypeBinding.UNKNOWN,0,true);
- argumentsBinding.declaringScope=this;
- }
-
- /* Spec : 8.4.3 & 9.4
- */
- private void checkAndSetModifiersForConstructor(MethodBinding methodBinding) {
-
- int modifiers = methodBinding.modifiers;
- final ReferenceBinding declaringClass = methodBinding.declaringClass;
-
-// if (((ConstructorDeclaration) referenceContext).isDefaultConstructor) {
- if ((methodBinding.modifiers&ExtraCompilerModifiers.AccIsDefaultConstructor)>0) {
- // certain flags are propagated from declaring class onto constructor
- final int DECLARING_FLAGS = ClassFileConstants.AccPublic|ClassFileConstants.AccProtected;
- final int VISIBILITY_FLAGS = ClassFileConstants.AccPrivate|ClassFileConstants.AccPublic|ClassFileConstants.AccProtected;
- int flags;
- if ((flags = declaringClass.modifiers & DECLARING_FLAGS) != 0) {
- modifiers &= ~VISIBILITY_FLAGS;
- modifiers |= flags; // propagate public/protected
- }
- }
-
- // after this point, tests on the 16 bits reserved.
- int realModifiers = modifiers & ExtraCompilerModifiers.AccJustFlag;
-
- // check for incompatible modifiers in the visibility bits, isolate the visibility bits
- int accessorBits = realModifiers & (ClassFileConstants.AccPublic | ClassFileConstants.AccProtected | ClassFileConstants.AccPrivate);
- if ((accessorBits & (accessorBits - 1)) != 0) {
-
- // need to keep the less restrictive so disable Protected/Private as necessary
- if ((accessorBits & ClassFileConstants.AccPublic) != 0) {
- if ((accessorBits & ClassFileConstants.AccProtected) != 0)
- modifiers &= ~ClassFileConstants.AccProtected;
- if ((accessorBits & ClassFileConstants.AccPrivate) != 0)
- modifiers &= ~ClassFileConstants.AccPrivate;
- } else if ((accessorBits & ClassFileConstants.AccProtected) != 0 && (accessorBits & ClassFileConstants.AccPrivate) != 0) {
- modifiers &= ~ClassFileConstants.AccPrivate;
- }
- }
-
-// // if the receiver's declaring class is a private nested type, then make sure the receiver is not private (causes problems for inner type emulation)
-// if (declaringClass.isPrivate() && (modifiers & ClassFileConstants.AccPrivate) != 0)
-// modifiers &= ~ClassFileConstants.AccPrivate;
-
- methodBinding.modifiers = modifiers;
- }
-
- /* Spec : 8.4.3 & 9.4
- */
- private void checkAndSetModifiersForMethod(MethodBinding methodBinding) {
-
- int modifiers = methodBinding.modifiers;
- final ReferenceBinding declaringClass = methodBinding.declaringClass;
-
- // after this point, tests on the 16 bits reserved.
- int realModifiers = modifiers & ExtraCompilerModifiers.AccJustFlag;
-
- // set the requested modifiers for a method in an interface/annotation
-// if (declaringClass.isInterface()) {
-// if ((realModifiers & ~(ClassFileConstants.AccPublic | ClassFileConstants.AccAbstract)) != 0) {
-// if ((declaringClass.modifiers & ClassFileConstants.AccAnnotation) != 0)
-// problemReporter().illegalModifierForAnnotationMember((AbstractMethodDeclaration) referenceContext);
-// else
-// problemReporter().illegalModifierForInterfaceMethod((AbstractMethodDeclaration) referenceContext);
-// }
-// return;
-// }
-
- // check for incompatible modifiers in the visibility bits, isolate the visibility bits
- int accessorBits = realModifiers & (ClassFileConstants.AccPublic | ClassFileConstants.AccProtected | ClassFileConstants.AccPrivate);
- if ((accessorBits & (accessorBits - 1)) != 0) {
-
- // need to keep the less restrictive so disable Protected/Private as necessary
- if ((accessorBits & ClassFileConstants.AccPublic) != 0) {
- if ((accessorBits & ClassFileConstants.AccProtected) != 0)
- modifiers &= ~ClassFileConstants.AccProtected;
- if ((accessorBits & ClassFileConstants.AccPrivate) != 0)
- modifiers &= ~ClassFileConstants.AccPrivate;
- } else if ((accessorBits & ClassFileConstants.AccProtected) != 0 && (accessorBits & ClassFileConstants.AccPrivate) != 0) {
- modifiers &= ~ClassFileConstants.AccPrivate;
- }
- }
-
- /* DISABLED for backward compatibility with javac (if enabled should also mark private methods as final)
- // methods from a final class are final : 8.4.3.3
- if (methodBinding.declaringClass.isFinal())
- modifiers |= AccFinal;
- */
-// // static members are only authorized in a static member or top level type
-// if (((realModifiers & ClassFileConstants.AccStatic) != 0) && declaringClass.isNestedType() && !declaringClass.isStatic())
-// problemReporter().unexpectedStaticModifierForMethod(declaringClass, (AbstractMethodDeclaration) referenceContext);
-
- methodBinding.modifiers = modifiers;
- }
-
- MethodBinding createMethod(InferredMethod inferredMethod,SourceTypeBinding declaringClass) {
- boolean isConstructor=inferredMethod.isConstructor;
- if (isConstructor && declaringClass!=inferredMethod.inType.binding)
- isConstructor=false;
- MethodBinding binding = createMethod((AbstractMethodDeclaration) inferredMethod.getFunctionDeclaration(),inferredMethod.name,declaringClass, isConstructor,false);
- if (inferredMethod.isConstructor || declaringClass!=inferredMethod.inType.binding)
- binding.allocationType=inferredMethod.inType.binding;
- return binding;
- }
-
- public MethodBinding createMethod(AbstractMethodDeclaration method,char[] name,SourceTypeBinding declaringClass, boolean isConstructor, boolean isLocal) {
-
- MethodBinding methodBinding=null;
- // is necessary to ensure error reporting
- this.referenceContext = method;
- method.scope = 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 (method.isDefaultConstructor() || isConstructor) {
- modifiers |= ExtraCompilerModifiers.AccIsDefaultConstructor;
- }
- methodBinding = new MethodBinding(modifiers, name, TypeBinding.UNKNOWN, null, declaringClass);
- methodBinding.tagBits|=TagBits.IsConstructor;
- checkAndSetModifiersForConstructor(methodBinding);
- } else {
- TypeBinding returnType =
- (method.inferredType!=null)?method.inferredType.resolveType(this,method):TypeBinding.UNKNOWN;
- if (method.inferredType==null && method.inferredMethod!=null && method.inferredMethod.isConstructor
- && method.inferredMethod.inType!=null) {
- returnType=method.inferredMethod.inType.resolveType(this,method);
- }
-
- //return type still null, return type is unknown
- if (returnType==null) {
- returnType=TypeBinding.UNKNOWN;
- }
-
- if (isLocal && method.selector!=null) {
- methodBinding =
- new LocalFunctionBinding(modifiers, name,returnType, null, declaringClass);
- } else{// not local method
- methodBinding =
- new MethodBinding(modifiers, name,returnType, null, declaringClass);
- }
-
- if (method.inferredMethod!=null) {
- methodBinding.tagBits |= TagBits.IsInferredType;
- if ((method.bits&ASTNode.IsInferredJsDocType)!=0) {
- methodBinding.tagBits |= TagBits.IsInferredJsDocType;
-
- }
- }
- methodBinding.createFunctionTypeBinding(this);
- if (method.inferredMethod!=null && method.inferredMethod.isConstructor) {
- methodBinding.tagBits|=TagBits.IsConstructor;
- }
- checkAndSetModifiersForMethod(methodBinding);
- }
- this.isStatic =methodBinding.isStatic();
-
- //set arguments
- Argument[] argTypes = method.arguments;
- int argLength = argTypes == null ? 0 : argTypes.length;
- if (argLength > 0 && compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5) {
- if (argTypes[--argLength].isVarArgs())
- methodBinding.modifiers |= ClassFileConstants.AccVarargs;
- }
-
- return methodBinding;
- }
-
- public FieldBinding findField(
- TypeBinding receiverType,
- char[] fieldName,
- InvocationSite invocationSite,
- boolean needResolve) {
-
- FieldBinding field = super.findField(receiverType, fieldName, invocationSite, needResolve);
- if (field == null)
- return null;
- if (!field.isValidBinding())
- return field; // answer the error field
- if (field.isStatic())
- return field; // static fields are always accessible
-
- if (!isConstructorCall || receiverType != enclosingSourceType())
- return field;
-
- if (invocationSite instanceof SingleNameReference)
- return new ProblemFieldBinding(
- field, // closest match
- field.declaringClass,
- fieldName,
- ProblemReasons.NonStaticReferenceInConstructorInvocation);
- if (invocationSite instanceof QualifiedNameReference) {
- // look to see if the field is the first binding
- QualifiedNameReference name = (QualifiedNameReference) invocationSite;
- if (name.binding == null)
- // only true when the field is the fieldbinding at the beginning of name's tokens
- return new ProblemFieldBinding(
- field, // closest match
- field.declaringClass,
- fieldName,
- ProblemReasons.NonStaticReferenceInConstructorInvocation);
- }
- return field;
- }
-
- public boolean isInsideConstructor() {
-
- return (referenceContext instanceof ConstructorDeclaration);
- }
-
- public boolean isInsideInitializer() {
-
- return (referenceContext instanceof TypeDeclaration);
- }
-
- public boolean isInsideInitializerOrConstructor() {
-
- return (referenceContext instanceof TypeDeclaration)
- || (referenceContext instanceof ConstructorDeclaration);
- }
-
- /* 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() {
-
- MethodScope outerMethodScope;
- if ((outerMethodScope = outerMostMethodScope()) == this) {
- ProblemReporter problemReporter = referenceCompilationUnit().problemReporter;
- problemReporter.referenceContext = referenceContext;
- return problemReporter;
- }
- return outerMethodScope.problemReporter();
- }
-
- public final int recordInitializationStates(FlowInfo flowInfo) {
-
- if ((flowInfo.tagBits & FlowInfo.UNREACHABLE) != 0) return -1;
-
- UnconditionalFlowInfo unconditionalFlowInfo = flowInfo.unconditionalInitsWithoutSideEffect();
- long[] extraInits = unconditionalFlowInfo.extra == null ?
- null : unconditionalFlowInfo.extra[0];
- long inits = unconditionalFlowInfo.definiteInits;
- checkNextEntry : for (int i = lastIndex; --i >= 0;) {
- if (definiteInits[i] == inits) {
- long[] otherInits = extraDefiniteInits[i];
- if ((extraInits != null) && (otherInits != null)) {
- if (extraInits.length == otherInits.length) {
- int j, max;
- for (j = 0, max = extraInits.length; j < max; j++) {
- if (extraInits[j] != otherInits[j]) {
- continue checkNextEntry;
- }
- }
- return i;
- }
- } else {
- if ((extraInits == null) && (otherInits == null)) {
- return i;
- }
- }
- }
- }
-
- // add a new entry
- if (definiteInits.length == lastIndex) {
- // need a resize
- System.arraycopy(
- definiteInits,
- 0,
- (definiteInits = new long[lastIndex + 20]),
- 0,
- lastIndex);
- System.arraycopy(
- extraDefiniteInits,
- 0,
- (extraDefiniteInits = new long[lastIndex + 20][]),
- 0,
- lastIndex);
- }
- definiteInits[lastIndex] = inits;
- if (extraInits != null) {
- extraDefiniteInits[lastIndex] = new long[extraInits.length];
- System.arraycopy(
- extraInits,
- 0,
- extraDefiniteInits[lastIndex],
- 0,
- extraInits.length);
- }
- return lastIndex++;
- }
-
- /* Answer the reference method of this scope, or null if initialization scoope.
- */
- public AbstractMethodDeclaration referenceMethod() {
-
- if (referenceContext instanceof AbstractMethodDeclaration) return (AbstractMethodDeclaration) referenceContext;
- return null;
- }
-
- /* Answer the reference type of this scope.
- *
- * It is the nearest enclosing type of this scope.
- */
- public TypeDeclaration referenceType() {
- if (parent instanceof ClassScope)
- return ((ClassScope) parent).referenceContext;
- return null;
- }
-
- String basicToString(int tab) {
-
- String newLine = "\n"; //$NON-NLS-1$
- for (int i = tab; --i >= 0;)
- newLine += "\t"; //$NON-NLS-1$
-
- String s = newLine + "--- Method Scope ---"; //$NON-NLS-1$
- newLine += "\t"; //$NON-NLS-1$
- s += newLine + "locals:"; //$NON-NLS-1$
- for (int i = 0; i < localIndex; i++)
- s += newLine + "\t" + locals[i].toString(); //$NON-NLS-1$
- s += newLine + "startIndex = " + startIndex; //$NON-NLS-1$
- s += newLine + "isConstructorCall = " + isConstructorCall; //$NON-NLS-1$
- s += newLine + "initializedField = " + initializedField; //$NON-NLS-1$
- s += newLine + "lastVisibleFieldID = " + lastVisibleFieldID; //$NON-NLS-1$
- s += newLine + "referenceContext = " + referenceContext; //$NON-NLS-1$
- return s;
- }
-
- public LocalVariableBinding findVariable(char[] variableName) {
- LocalVariableBinding binding = super.findVariable(variableName);
- if (binding==null && CharOperation.equals(variableName,ARGUMENTS_NAME))
- binding=this.argumentsBinding;
- return binding;
- }
-
-
-}
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
deleted file mode 100644
index 7590611c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MethodVerifier.java
+++ /dev/null
@@ -1,499 +0,0 @@
-/*******************************************************************************
- * 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.compiler.lookup;
-
-import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants;
-import org.eclipse.wst.jsdt.internal.compiler.impl.CompilerOptions;
-import org.eclipse.wst.jsdt.internal.compiler.problem.ProblemReporter;
-import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfObject;
-
-public class MethodVerifier {
- SourceTypeBinding type;
- HashtableOfObject inheritedMethods;
- HashtableOfObject currentMethods;
- LookupEnvironment environment;
- private boolean allowCompatibleReturnTypes;
-/*
-Binding creation is responsible for reporting all problems with types:
- - all modifier problems (duplicates & multiple visibility modifiers + incompatible combinations - abstract/final)
- - plus invalid modifiers given the context (the verifier did not do this before)
- - qualified name collisions between a type and a package (types in default packages are excluded)
- - all type hierarchy problems:
- - cycles in the superclass or superinterface hierarchy
- - an ambiguous, invisible or missing superclass or superinterface
- - extending a final class
- - extending an interface instead of a class
- - implementing a class instead of an interface
- - implementing the same interface more than once (ie. duplicate interfaces)
- - with nested types:
- - shadowing an enclosing type's source name
- - defining a static class or interface inside a non-static nested class
- - defining an interface as a local type (local types can only be classes)
-*/
-MethodVerifier(LookupEnvironment environment) {
- this.type = null; // Initialized with the public method verify(SourceTypeBinding)
- this.inheritedMethods = null;
- this.currentMethods = null;
- this.environment = environment;
- this.allowCompatibleReturnTypes =
- environment.globalOptions.complianceLevel >= ClassFileConstants.JDK1_5
- && environment.globalOptions.sourceLevel < ClassFileConstants.JDK1_5;
-}
-boolean areMethodsCompatible(MethodBinding one, MethodBinding two) {
- return doesMethodOverride(one, two) && areReturnTypesCompatible(one, two);
-}
-boolean areParametersEqual(MethodBinding one, MethodBinding two) {
- TypeBinding[] oneArgs = one.parameters;
- TypeBinding[] twoArgs = two.parameters;
- if (oneArgs == twoArgs) return true;
-
- int length = oneArgs.length;
- if (length != twoArgs.length) return false;
-
- for (int i = 0; i < length; i++)
- if (!areTypesEqual(oneArgs[i], twoArgs[i])) return false;
- return true;
-}
-boolean areReturnTypesCompatible(MethodBinding one, MethodBinding two) {
- if (one.returnType == two.returnType) return true;
-
- if (areTypesEqual(one.returnType, two.returnType)) return true;
-
- // when sourceLevel < 1.5 but compliance >= 1.5, allow return types in binaries to be compatible instead of just equal
- if (this.allowCompatibleReturnTypes &&
- one.declaringClass instanceof BinaryTypeBinding &&
- two.declaringClass instanceof BinaryTypeBinding) {
- return areReturnTypesCompatible0(one, two);
- }
- return false;
-}
-boolean areReturnTypesCompatible0(MethodBinding one, MethodBinding two) {
- // short is compatible with int, but as far as covariance is concerned, its not
- if (one.returnType.isBaseType()) return false;
-
-
- if (one.declaringClass.id == TypeIds.T_JavaLangObject)
- return two.returnType.isCompatibleWith(one.returnType); // interface methods inherit from Object
- return one.returnType.isCompatibleWith(two.returnType);
-}
-boolean areTypesEqual(TypeBinding one, TypeBinding two) {
- if (one == two) return true;
-
- // its possible that an UnresolvedReferenceBinding can be compared to its resolved type
- // when they're both UnresolvedReferenceBindings then they must be identical like all other types
- // all wrappers of UnresolvedReferenceBindings are converted as soon as the type is resolved
- // so its not possible to have 2 arrays where one is UnresolvedX[] and the other is X[]
- if (one instanceof UnresolvedReferenceBinding)
- return ((UnresolvedReferenceBinding) one).resolvedType == two;
- if (two instanceof UnresolvedReferenceBinding)
- return ((UnresolvedReferenceBinding) two).resolvedType == one;
- if ( (one!=null && one.id==TypeIds.T_any) || (two!=null && two.id==TypeIds.T_any))
- return true;
- return false; // all other type bindings are identical
-}
-boolean canSkipInheritedMethods() {
- return true;
-}
-boolean canSkipInheritedMethods(MethodBinding one, MethodBinding two) {
- return two == null // already know one is not null
- || one.declaringClass == two.declaringClass;
-}
-void checkAgainstInheritedMethods(MethodBinding currentMethod, MethodBinding[] methods, int length, MethodBinding[] allInheritedMethods) {
- CompilerOptions options = type.scope.compilerOptions();
- // need to find the overridden methods to avoid blaming this type for issues which are already reported against a supertype
- // but cannot ignore an overridden inherited method completely when it comes to checking for bridge methods
- int[] overriddenInheritedMethods = length > 1 ? findOverriddenInheritedMethods(methods, length) : null;
- nextMethod : for (int i = length; --i >= 0;) {
- MethodBinding inheritedMethod = methods[i];
- if (overriddenInheritedMethods == null || overriddenInheritedMethods[i] == 0) {
- if (currentMethod.isStatic() != inheritedMethod.isStatic() && currentMethod.declaringClass == type) { // Cannot override a static method or hide an instance method
- problemReporter(currentMethod).staticAndInstanceConflict(currentMethod, inheritedMethod);
- continue nextMethod;
- }
-
- // want to tag currentMethod even if return types are not equal
- if (inheritedMethod.isAbstract()) {
- currentMethod.modifiers |= ExtraCompilerModifiers.AccImplementing | ExtraCompilerModifiers.AccOverriding;
-
-// with the above change an abstract method is tagged as implementing the inherited abstract method
-// if (!currentMethod.isAbstract() && inheritedMethod.isAbstract()) {
-// if ((currentMethod.modifiers & CompilerModifiers.AccOverriding) == 0)
-// currentMethod.modifiers |= CompilerModifiers.AccImplementing;
- } else {
- currentMethod.modifiers |= ExtraCompilerModifiers.AccOverriding;
- }
-
- if (!areReturnTypesCompatible(currentMethod, inheritedMethod))
- {
- if (!(currentMethod.returnType!=null && currentMethod.returnType.isObjectLiteralType()
- && inheritedMethod.returnType!=null && inheritedMethod.returnType.isObjectLiteralType()))
- if (reportIncompatibleReturnTypeError(currentMethod, inheritedMethod))
- continue nextMethod;
-
- }
-
- if (!isAsVisible(currentMethod, inheritedMethod))
- problemReporter(currentMethod).visibilityConflict(currentMethod, inheritedMethod);
- if (options.reportDeprecationWhenOverridingDeprecatedMethod && inheritedMethod.isViewedAsDeprecated()) {
- if (!currentMethod.isViewedAsDeprecated() || options.reportDeprecationInsideDeprecatedCode) {
- problemReporter(currentMethod).overridesDeprecatedMethod(currentMethod, inheritedMethod);
- }
- }
- }
- checkForBridgeMethod(currentMethod, inheritedMethod, allInheritedMethods);
- }
-}
-void checkForBridgeMethod(MethodBinding currentMethod, MethodBinding inheritedMethod, MethodBinding[] allInheritedMethods) {
- // no op before 1.5
-}
-void checkInheritedMethods(MethodBinding[] methods, int length) {
- int[] overriddenInheritedMethods = length > 1 ? findOverriddenInheritedMethods(methods, length) : null;
- if (overriddenInheritedMethods != null) {
- // detected some overridden methods that can be ignored when checking return types
- // but cannot ignore an overridden inherited method completely when it comes to checking for bridge methods
- int index = 0;
- MethodBinding[] closestMethods = new MethodBinding[length];
- for (int i = 0; i < length; i++)
- if (overriddenInheritedMethods[i] == 0)
- closestMethods[index++] = methods[i];
- if (!checkInheritedReturnTypes(closestMethods, index))
- return;
- } else if (!checkInheritedReturnTypes(methods, length)) {
- return;
- }
-
- MethodBinding concreteMethod = null;
-
- for (int i = length; --i >= 0;) { // Remember that only one of the methods can be non-abstract
- if (!methods[i].isAbstract()) {
- concreteMethod = methods[i];
- break;
- }
- }
-
- if (concreteMethod == null) {
-
- return;
- }
-}
-boolean checkInheritedReturnTypes(MethodBinding[] methods, int length) {
- MethodBinding first = methods[0];
- int index = length;
- while (--index > 0 && areReturnTypesCompatible(first, methods[index])){/*empty*/}
- if (index == 0)
- return true;
-
- problemReporter().inheritedMethodsHaveIncompatibleReturnTypes(this.type, methods, length);
- return false;
-}
-/*
-For each inherited method identifier (message pattern - vm signature minus the return type)
- if current method exists
- if current's vm signature does not match an inherited signature then complain
- else compare current's exceptions & visibility against each inherited method
- else
- if inherited methods = 1
- if inherited is abstract && type is NOT an interface or abstract, complain
- else
- if vm signatures do not match complain
- else
- find the concrete implementation amongst the abstract methods (can only be 1)
- if one exists then
- it must be a public instance method
- compare concrete's exceptions against each abstract method
- else
- complain about missing implementation only if type is NOT an interface or abstract
-*/
-void checkMethods() {
- char[][] methodSelectors = this.inheritedMethods.keyTable;
- nextSelector : for (int s = methodSelectors.length; --s >= 0;) {
- if (methodSelectors[s] == null) continue nextSelector;
-
- MethodBinding[] current = (MethodBinding[]) this.currentMethods.get(methodSelectors[s]);
-
- MethodBinding[] inherited = (MethodBinding[]) this.inheritedMethods.valueTable[s];
- if (inherited.length == 1 && current == null) { // handle the common case
- continue nextSelector;
- }
-
- int index = -1;
- MethodBinding[] matchingInherited = new MethodBinding[inherited.length];
- if (current != null) {
- for (int i = 0, length1 = current.length; i < length1; i++) {
- MethodBinding currentMethod = current[i];
- for (int j = 0, length2 = inherited.length; j < length2; j++) {
- MethodBinding inheritedMethod = computeSubstituteMethod(inherited[j], currentMethod);
- if (inheritedMethod != null) {
- if (doesMethodOverride(currentMethod, inheritedMethod)) {
- matchingInherited[++index] = inheritedMethod;
- inherited[j] = null; // do not want to find it again
- }
- }
- }
- if (index >= 0) {
- checkAgainstInheritedMethods(currentMethod, matchingInherited, index + 1, inherited); // pass in the length of matching
- while (index >= 0) matchingInherited[index--] = null; // clear the contents of the matching methods
- }
- }
- }
-
- for (int i = 0, length = inherited.length; i < length; i++) {
- MethodBinding inheritedMethod = inherited[i];
- if (inheritedMethod == null) continue;
-
- matchingInherited[++index] = inheritedMethod;
- for (int j = i + 1; j < length; j++) {
- MethodBinding otherInheritedMethod = inherited[j];
- if (canSkipInheritedMethods(inheritedMethod, otherInheritedMethod))
- continue;
- otherInheritedMethod = computeSubstituteMethod(otherInheritedMethod, inheritedMethod);
- if (otherInheritedMethod != null) {
- if (doesMethodOverride(inheritedMethod, otherInheritedMethod)) {
- matchingInherited[++index] = otherInheritedMethod;
- inherited[j] = null; // do not want to find it again
- }
- }
- }
- if (index == -1) continue;
- if (index > 0)
- checkInheritedMethods(matchingInherited, index + 1); // pass in the length of matching
- while (index >= 0) matchingInherited[index--] = null; // clear the contents of the matching methods
- }
- }
-}
-void checkPackagePrivateAbstractMethod(MethodBinding abstractMethod) {
- // check that the inherited abstract method (package private visibility) is implemented within the same package
- PackageBinding necessaryPackage = abstractMethod.declaringClass.fPackage;
- if (necessaryPackage == this.type.fPackage) return; // not a problem
-
- ReferenceBinding superType = this.type.superclass();
- do {
- if (!superType.isValidBinding()) return;
- return; // closer non abstract super type will be flagged instead
-
- } while ((superType = superType.superclass()) != abstractMethod.declaringClass);
-}
-void computeInheritedMethods() {
- ReferenceBinding superclass = this.type.superclass(); // class or enum
- computeInheritedMethods(superclass, null);
-}
-/*
-Binding creation is responsible for reporting:
- - all modifier problems (duplicates & multiple visibility modifiers + incompatible combinations)
- - plus invalid modifiers given the context... examples:
- - interface methods can only be public
- - abstract methods can only be defined by abstract classes
- - collisions... 2 methods with identical vmSelectors
- - multiple methods with the same message pattern but different return types
- - ambiguous, invisible or missing return/argument/exception types
- - check the type of any array is not void
- - check that each exception type is Throwable or a subclass of it
-*/
-void computeInheritedMethods(ReferenceBinding superclass, ReferenceBinding[] superInterfaces) {
- // only want to remember inheritedMethods that can have an impact on the current type
- // if an inheritedMethod has been 'replaced' by a supertype's method then skip it
-
- this.inheritedMethods = new HashtableOfObject(51); // maps method selectors to an array of methods... must search to match paramaters & return type
- ReferenceBinding[] interfacesToVisit = null;
- int nextPosition = 0;
- ReferenceBinding[] itsInterfaces = superInterfaces;
- if (itsInterfaces != null) {
- nextPosition = itsInterfaces.length;
- interfacesToVisit = itsInterfaces;
- }
-
- ReferenceBinding superType = superclass;
- HashtableOfObject nonVisibleDefaultMethods = new HashtableOfObject(3); // maps method selectors to an array of methods
-
- while (superType != null && superType.isValidBinding()) {
-
- MethodBinding[] methods = superType.unResolvedMethods();
- nextMethod : for (int m = methods.length; --m >= 0;) {
- MethodBinding inheritedMethod = methods[m];
- if (inheritedMethod.isPrivate() || inheritedMethod.isConstructor() || inheritedMethod.isDefaultAbstract())
- continue nextMethod;
- MethodBinding[] existingMethods = (MethodBinding[]) this.inheritedMethods.get(inheritedMethod.selector);
- if (existingMethods != null) {
- for (int i = 0, length = existingMethods.length; i < length; i++) {
- if (existingMethods[i].declaringClass != inheritedMethod.declaringClass && areMethodsCompatible(existingMethods[i], inheritedMethod)) {
- if (inheritedMethod.isDefault() && inheritedMethod.isAbstract())
- checkPackagePrivateAbstractMethod(inheritedMethod);
- continue nextMethod;
- }
- }
- }
- MethodBinding[] nonVisible = (MethodBinding[]) nonVisibleDefaultMethods.get(inheritedMethod.selector);
- if (nonVisible != null)
- for (int i = 0, l = nonVisible.length; i < l; i++)
- if (areMethodsCompatible(nonVisible[i], inheritedMethod))
- continue nextMethod;
-
- if (!inheritedMethod.isDefault() || inheritedMethod.declaringClass.fPackage == type.fPackage) {
- if (existingMethods == null) {
- existingMethods = new MethodBinding[] {inheritedMethod};
- } else {
- int length = existingMethods.length;
- System.arraycopy(existingMethods, 0, existingMethods = new MethodBinding[length + 1], 0, length);
- existingMethods[length] = inheritedMethod;
- }
- this.inheritedMethods.put(inheritedMethod.selector, existingMethods);
- } else {
- if (nonVisible == null) {
- nonVisible = new MethodBinding[] {inheritedMethod};
- } else {
- int length = nonVisible.length;
- System.arraycopy(nonVisible, 0, nonVisible = new MethodBinding[length + 1], 0, length);
- nonVisible[length] = inheritedMethod;
- }
- nonVisibleDefaultMethods.put(inheritedMethod.selector, nonVisible);
-
- MethodBinding[] current = (MethodBinding[]) this.currentMethods.get(inheritedMethod.selector);
- if (current != null) { // non visible methods cannot be overridden so a warning is issued
- foundMatch : for (int i = 0, length = current.length; i < length; i++) {
- if (areMethodsCompatible(current[i], inheritedMethod)) {
- break foundMatch;
- }
- }
- }
- }
- }
- superType = superType.superclass();
- }
- if (nextPosition == 0) return;
-
- for (int i = 0; i < nextPosition; i++) {
- superType = interfacesToVisit[i];
- if (superType.isValidBinding()) {
- MethodBinding[] methods = superType.unResolvedMethods();
- for (int m = methods.length; --m >= 0;) { // Interface methods are all abstract public
- MethodBinding inheritedMethod = methods[m];
- MethodBinding[] existingMethods = (MethodBinding[]) this.inheritedMethods.get(inheritedMethod.selector);
- if (existingMethods == null) {
- existingMethods = new MethodBinding[] {inheritedMethod};
- } else {
- int length = existingMethods.length;
-
- System.arraycopy(existingMethods, 0, existingMethods = new MethodBinding[length + 1], 0, length);
- existingMethods[length] = inheritedMethod;
- }
- this.inheritedMethods.put(inheritedMethod.selector, existingMethods);
- }
- }
- }
-}
-void computeMethods() {
- MethodBinding[] methods = type.methods();
- int size = methods.length;
- this.currentMethods = new HashtableOfObject(size == 0 ? 1 : size); // maps method selectors to an array of methods... must search to match paramaters & return type
- for (int m = size; --m >= 0;) {
- MethodBinding method = methods[m];
- if (!(method.isConstructor() || method.isDefaultAbstract())) { // keep all methods which are NOT constructors or default abstract
- MethodBinding[] existingMethods = (MethodBinding[]) this.currentMethods.get(method.selector);
- if (existingMethods == null)
- existingMethods = new MethodBinding[1];
- else
- System.arraycopy(existingMethods, 0,
- (existingMethods = new MethodBinding[existingMethods.length + 1]), 0, existingMethods.length - 1);
- existingMethods[existingMethods.length - 1] = method;
- this.currentMethods.put(method.selector, existingMethods);
- }
- }
-}
-MethodBinding computeSubstituteMethod(MethodBinding inheritedMethod, MethodBinding currentMethod) {
- if (inheritedMethod == null) return null;
- if (currentMethod.parameters.length != inheritedMethod.parameters.length) return null; // no match
- return inheritedMethod;
-}
-public boolean doesMethodOverride(MethodBinding method, MethodBinding inheritedMethod) {
- return areParametersEqual(method, inheritedMethod);
-}
-int[] findOverriddenInheritedMethods(MethodBinding[] methods, int length) {
- // NOTE assumes length > 1
- // inherited methods are added as we walk up the superclass hierarchy, then each superinterface
- // so method[1] from a class can NOT override method[0], but methods from superinterfaces can
- // since superinterfaces can be added from different superclasses or other superinterfaces
- int[] toSkip = null;
- int i = 0;
- ReferenceBinding declaringClass = methods[i].declaringClass;
-
- // in the first pass, skip overridden methods from superclasses
- // only keep methods from the closest superclass, all others from higher superclasses can be skipped
- // NOTE: methods were added in order by walking up the superclass hierarchy
- ReferenceBinding declaringClass2 = methods[++i].declaringClass;
- while (declaringClass == declaringClass2) {
- if (++i == length) return null;
- declaringClass2 = methods[i].declaringClass;
- }
-
- // skip all methods from different superclasses
- toSkip = new int[length];
- do {
- toSkip[i] = -1;
- if (++i == length) return toSkip;
- declaringClass2 = methods[i].declaringClass;
- } while (true);
-}
-boolean isAsVisible(MethodBinding newMethod, MethodBinding inheritedMethod) {
- if (inheritedMethod.modifiers == newMethod.modifiers) return true;
-
- if (newMethod.isPublic()) return true; // Covers everything
- if (inheritedMethod.isPublic()) return false;
-
- if (newMethod.isProtected()) return true;
- if (inheritedMethod.isProtected()) return false;
-
- return !newMethod.isPrivate(); // The inheritedMethod cannot be private since it would not be visible
-}
-boolean isSameClassOrSubclassOf(ReferenceBinding testClass, ReferenceBinding superclass) {
- do {
- if (testClass == superclass) return true;
- } while ((testClass = testClass.superclass()) != null);
- return false;
-}
-ProblemReporter problemReporter() {
- return this.type.scope.problemReporter();
-}
-ProblemReporter problemReporter(MethodBinding currentMethod) {
- ProblemReporter reporter = problemReporter();
- if (currentMethod.declaringClass == type && currentMethod.sourceMethod() != null) // only report against the currentMethod if its implemented by the type
- reporter.referenceContext = currentMethod.sourceMethod();
- return reporter;
-}
-/**
- * Return true and report an incompatibleReturnType error if currentMethod's
- * return type is strictly incompatible with inheritedMethod's, else return
- * false and report an unchecked conversion warning. Do not call when
- * areReturnTypesCompatible(currentMethod, inheritedMethod) returns true.
- * @param currentMethod the (potentially) inheriting method
- * @param inheritedMethod the inherited method
- * @return true if currentMethod's return type is strictly incompatible with
- * inheritedMethod's
- */
-boolean reportIncompatibleReturnTypeError(MethodBinding currentMethod, MethodBinding inheritedMethod) {
- problemReporter(currentMethod).incompatibleReturnType(currentMethod, inheritedMethod);
- return true;
-}
-void verify(SourceTypeBinding someType) {
- this.type = someType;
- computeMethods();
- computeInheritedMethods();
- checkMethods();
-}
-public String toString() {
- StringBuffer buffer = new StringBuffer(10);
- buffer.append("MethodVerifier for type: "); //$NON-NLS-1$
- buffer.append(type.readableName());
- buffer.append('\n');
- buffer.append("\t-inherited methods: "); //$NON-NLS-1$
- buffer.append(this.inheritedMethods);
- return buffer.toString();
-}
-}
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
deleted file mode 100644
index 7d9c7c94..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MissingBinaryTypeBinding.java
+++ /dev/null
@@ -1,57 +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.compiler.lookup;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.infer.InferredType;
-import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants;
-
-public class MissingBinaryTypeBinding extends SourceTypeBinding {
-
-/**
- * Special constructor for constructing proxies of missing binary types (114349)
- * @param packageBinding
- * @param compoundName
- * @param environment
- */
-public MissingBinaryTypeBinding(PackageBinding packageBinding, char[][] compoundName, LookupEnvironment environment, Scope parentScope) {
- super(compoundName,packageBinding,new ClassScope(parentScope,new InferredType(null)));
- this.compoundName = compoundName;
- computeId();
- this.tagBits |= TagBits.IsBinaryBinding | TagBits.HierarchyHasProblems;
-// this.environment = environment;
- this.fPackage = packageBinding;
- 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.memberTypes = Binding.NO_MEMBER_TYPES;
- this.fields = Binding.NO_FIELDS;
- this.methods = Binding.NO_METHODS;
-}
-
-/**
- * Missing binary type will answer <code>false</code> to #isValidBinding()
- * @see org.eclipse.wst.jsdt.internal.compiler.lookup.Binding#problemId()
- */
-public int problemId() {
- return ProblemReasons.NotFound;
-}
-
-/**
- * Only used to fixup the superclass hierarchy of proxy binary types
- * @param missingSuperclass
- * @see LookupEnvironment#cacheMissingBinaryType(char[][], org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration)
- */
-void setMissingSuperclass(ReferenceBinding missingSuperclass) {
- this.superclass = 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
deleted file mode 100644
index 3782260d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MultipleTypeBinding.java
+++ /dev/null
@@ -1,175 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.lookup;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-
-import org.eclipse.wst.jsdt.core.UnimplementedException;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.infer.InferredType;
-
-public class MultipleTypeBinding extends ReferenceBinding {
-
- public ReferenceBinding[] types;
- int problemID = ProblemReasons.NoError;
-
- public MultipleTypeBinding(Scope scope, char[][] names) {
-
- char [][] name={};
- ArrayList resolveTypes=new ArrayList(names.length);
- for (int i = 0; i < names.length; i++) {
- TypeBinding typeBinding= scope.getType(names[i]);
- if (typeBinding instanceof ReferenceBinding)
- {
- if (!typeBinding.isValidBinding())
- problemID=typeBinding.problemId();
- else
- {
- this.tagBits|=typeBinding.tagBits;
- this.modifiers|=((ReferenceBinding)typeBinding).modifiers;
- resolveTypes.add(typeBinding);
- this.compoundName=((ReferenceBinding)typeBinding).compoundName;
- }
- }
- }
- types = (ReferenceBinding[]) resolveTypes.toArray(new ReferenceBinding[resolveTypes.size()]);
-
- }
-
- public int problemId() {
- return problemID;
- }
-
- public FieldBinding[] availableFields() {
- ArrayList list = new ArrayList();
- for (int i = 0; i < this.types.length ; i++) {
- FieldBinding[] bindings = this.types[i].availableFields();
- list.addAll(Arrays.asList(bindings));
- }
- return (FieldBinding[]) list.toArray(new FieldBinding[list.size()]);
- }
-
- public MethodBinding[] availableMethods() {
- ArrayList list = new ArrayList();
- for (int i = 0; i < this.types.length ; i++) {
- MethodBinding[] bindings = this.types[i].availableMethods();
- list.addAll(Arrays.asList(bindings));
- }
- return (MethodBinding[]) list.toArray(new MethodBinding[list.size()]);
- }
-
- public FieldBinding[] fields() {
- ArrayList list = new ArrayList();
- for (int i = 0; i < this.types.length ; i++) {
- FieldBinding[] bindings = this.types[i].fields();
- list.addAll(Arrays.asList(bindings));
- }
- return (FieldBinding[]) list.toArray(new FieldBinding[list.size()]);
- }
-
- public MethodBinding getExactMethod(char[] selector,
- TypeBinding[] argumentTypes, CompilationUnitScope refScope) {
- MethodBinding methodBinding=null;
- for (int i = 0; i < this.types.length && methodBinding==null; i++) {
- methodBinding= this.types[i].getExactMethod(selector, argumentTypes, refScope);
- }
- return methodBinding;
- }
-
- public FieldBinding getField(char[] fieldName, boolean needResolve) {
- FieldBinding fieldBinding=null;
- for (int i = 0; i < this.types.length && fieldBinding==null; i++) {
- fieldBinding= this.types[i].getField(fieldName, needResolve);
- }
- return fieldBinding;
- }
-
- public InferredType getInferredType() {
- throw new UnimplementedException("should not get here"); //$NON-NLS-1$
- }
-
- public MethodBinding[] getMethods(char[] selector) {
- ArrayList list = new ArrayList();
- for (int i = 0; i < this.types.length ; i++) {
- MethodBinding[] bindings = this.types[i].getMethods(selector);
- list.addAll(Arrays.asList(bindings));
- }
- return (MethodBinding[]) list.toArray(new MethodBinding[list.size()]);
- }
-
- public boolean hasMemberTypes() {
- throw new UnimplementedException("should not get here"); //$NON-NLS-1$
- }
-
- public boolean isCompatibleWith(TypeBinding otherType) {
- for (int i = 0; i < this.types.length ; i++)
- if (types[i].isCompatibleWith(otherType))
- return true;
- return false;
-
- }
-
- public boolean isSuperclassOf(ReferenceBinding otherType) {
- for (int i = 0; i < this.types.length ; i++)
- if (types[i].isSuperclassOf(otherType))
- return true;
- return false;
- }
-
- public MethodBinding[] methods() {
- ArrayList list = new ArrayList();
- for (int i = 0; i < this.types.length ; i++) {
- MethodBinding[] bindings = this.types[i].methods();
- list.addAll(Arrays.asList(bindings));
- }
- return (MethodBinding[]) list.toArray(new MethodBinding[list.size()]);
- }
-
- public char[] signature() {
- char [] sig={};
- for (int i = 0; i < this.types.length ; i++) {
- if (i>0)
- sig=CharOperation.append(sig, '|');
- sig=CharOperation.concat(sig, this.types[i].signature());
- }
- return sig;
- }
-
- public boolean isViewedAsDeprecated() {
- for (int i = 0; i < this.types.length ; i++)
- if (types[i].isViewedAsDeprecated())
- return true;
- return false;
- }
-
- public char[] readableName() {
- char [] name={};
- for (int i = 0; i < this.types.length ; i++) {
- if (i>0)
- name=CharOperation.append(name, '|');
- name=CharOperation.concat(name, this.types[i].readableName());
- }
- return name;
- }
-
- public char[] shortReadableName() {
- char [] name={};
- for (int i = 0; i < this.types.length ; i++) {
- if (i>0)
- name=CharOperation.append(name, '|');
- name=CharOperation.concat(name, this.types[i].shortReadableName());
- }
- return name;
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/NestedTypeBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/NestedTypeBinding.java
deleted file mode 100644
index e845ec30..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/NestedTypeBinding.java
+++ /dev/null
@@ -1,32 +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.compiler.lookup;
-
-public class NestedTypeBinding extends SourceTypeBinding {
-
- public SourceTypeBinding enclosingType;
-
- public int enclosingInstancesSlotSize; // amount of slots used by synthetic enclosing instances
- public int outerLocalVariablesSlotSize; // amount of slots used by synthetic outer local variables
-
- public NestedTypeBinding(char[][] typeName, ClassScope scope, SourceTypeBinding enclosingType) {
- super(typeName, enclosingType.fPackage, scope);
- this.tagBits |= TagBits.IsNestedType;
- this.enclosingType = enclosingType;
- }
-
- /* Answer the receiver's enclosing type... null if the receiver is a top level type.
- */
- public ReferenceBinding enclosingType() {
-
- return enclosingType;
- }
-}
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
deleted file mode 100644
index 26dc8392..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/PackageBinding.java
+++ /dev/null
@@ -1,276 +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.compiler.lookup;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfBinding;
-import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfPackage;
-
-public class PackageBinding extends Binding implements TypeConstants {
- public long tagBits = 0; // See values in the interface TagBits below
-
- public char[][] compoundName;
- PackageBinding parent;
- public LookupEnvironment environment;
-// HashtableOfType knownTypes;
- HashtableOfBinding[] knownBindings=new HashtableOfBinding[NUMBER_BASIC_BINDING];
- HashtableOfPackage knownPackages;
- HashtableOfBinding knownCompUnits;
-
-
-
-protected PackageBinding() {
- // for creating problem package
-}
-public PackageBinding(char[][] compoundName, PackageBinding parent, LookupEnvironment environment) {
- this.compoundName = compoundName;
- this.parent = parent;
- this.environment = environment;
-// this.knownTypes = null; // initialized if used... class counts can be very large 300-600
- this.knownPackages = new HashtableOfPackage(3); // sub-package counts are typically 0-3
-}
-public PackageBinding(char[] topLevelPackageName, LookupEnvironment environment) {
- this(new char[][] {topLevelPackageName}, null, environment);
-}
-/* Create the default package.
-*/
-
-public PackageBinding(LookupEnvironment environment) {
- this(CharOperation.NO_CHAR_CHAR, null, environment);
-}
-//private void addNotFoundType(char[] simpleName) {
-// if (knownBindings[Binding.TYPE] == null)
-// knownBindings[Binding.TYPE] = new HashtableOfBinding(25);
-// knownBindings[Binding.TYPE].put(simpleName, LookupEnvironment.TheNotFoundType);
-//}
-
-private void addNotFoundBinding1(char[] simpleName,int mask) {
- if (knownBindings[mask] == null)
- knownBindings[mask] = new HashtableOfBinding(25);
- knownBindings[mask].put(simpleName, LookupEnvironment.TheNotFoundType);
-}
-private void addNotFoundBinding(char[] simpleName,int mask) {
- if (((Binding.VARIABLE|Binding.FIELD)&mask)!=0)
- addNotFoundBinding1(simpleName, Binding.VARIABLE|Binding.FIELD);
- if ((Binding.METHOD&mask)!=0)
- addNotFoundBinding1(simpleName, Binding.METHOD);
- if ((Binding.TYPE&mask)!=0)
- addNotFoundBinding1(simpleName, Binding.TYPE);
-}
-void addPackage(PackageBinding element) {
- knownPackages.put(element.compoundName[element.compoundName.length - 1], element);
-}
-void addType(ReferenceBinding element) {
- if (knownBindings[Binding.TYPE] == null)
- knownBindings[Binding.TYPE] = new HashtableOfBinding(25);
- knownBindings[Binding.TYPE].put(element.compoundName[element.compoundName.length - 1], element);
-}
-
-public void addBinding(Binding element, char[] name, int mask) {
- if (mask<knownBindings.length)
- {
- if (knownBindings[mask] == null)
- knownBindings[mask] = new HashtableOfBinding(25);
- knownBindings[mask].put(name, element);
- }
- else if ( (mask&(Binding.COMPILATION_UNIT))!=0)
- {
- if (knownCompUnits == null)
- knownCompUnits = new HashtableOfBinding(25);
- knownCompUnits.put(name, element);
-
- }
-}
-/* API
-* Answer the receiver's binding type from Binding.BindingID.
-*/
-
-public final int kind() {
- return Binding.PACKAGE;
-}
-/*
- * slash separated name
- * org.eclipse.wst.wst.jsdt.core --> org/eclipse/jdt/core
- */
-public char[] computeUniqueKey(boolean isLeaf) {
- return CharOperation.concatWith(compoundName, '/');
-}
-private PackageBinding findPackage(char[] name) {
- if (!environment.isPackage(this.compoundName, name))
- return null;
-
- char[][] subPkgCompoundName = CharOperation.arrayConcat(this.compoundName, name);
- PackageBinding subPackageBinding = new PackageBinding(subPkgCompoundName, this, environment);
- addPackage(subPackageBinding);
- return subPackageBinding;
-}
-/* Answer the subpackage named name; ask the oracle for the package if its not in the cache.
-* Answer null if it could not be resolved.
-*
-* NOTE: This should only be used when we know there is NOT a type with the same name.
-*/
-
-PackageBinding getPackage(char[] name) {
- PackageBinding binding = getPackage0(name);
- if (binding != null) {
- return binding;
- }
- if ((binding = findPackage(name)) != null)
- return binding;
-
- return null;
-}
-/* Answer the subpackage 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) {
- return knownPackages.get(name);
-}
-/* Answer the type named name; ask the oracle for the type if its not in the cache.
-* Answer a NotVisible problem type if the type is not visible from the invocationPackage.
-* Answer null if it could not be resolved.
-*
-* NOTE: This should only be used by source types/scopes which know there is NOT a
-* package with the same name.
-*/
-ReferenceBinding getType(char[] name) {
- return (ReferenceBinding)getBinding(name, Binding.TYPE);
-}
-
-public Binding getBinding(char[] name, int mask) {
- Binding typeBinding = getBinding0(name,mask);
- if (typeBinding == null) {
- if ((typeBinding = environment.askForBinding(this, name,mask)) == null) {
- // not found so remember a problem type binding in the cache for future lookups
- addNotFoundBinding(name,mask);
- return null;
- }
- }
-
- if (typeBinding == LookupEnvironment.TheNotFoundType)
- return null;
-
-// typeBinding = BinaryTypeBinding.resolveType(typeBinding, environment, false); // no raw conversion for now
-// if (typeBinding.isNestedType())
-// return new ProblemReferenceBinding(name, typeBinding, ProblemReasons.InternalNameProvided);
- return typeBinding;
-}
-/* Answer the type named name 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: Senders must convert theNotFoundType into a real problem
-* reference type if its to returned.
-*/
-
-ReferenceBinding getType0(char[] name) {
- if (knownBindings[Binding.TYPE] == null)
- return null;
- return (ReferenceBinding)knownBindings[Binding.TYPE].get(name);
-}
-
-Binding getBinding1(char[]name, int mask)
-{
- if (knownBindings[mask] == null)
- return null;
- return knownBindings[mask].get(name);
-}
-
-Binding getBinding0(char[] name, int mask) {
- Binding binding;
- if ( (mask&(Binding.VARIABLE|Binding.FIELD))!=0)
- {
- binding=getBinding1(name,Binding.VARIABLE|Binding.FIELD);
- if (binding!=null)
- return binding;
- }
- if ( (mask&(Binding.TYPE))!=0)
- {
- binding=getBinding1(name,Binding.TYPE);
- if (binding!=null)
- return binding;
- }
- if ( (mask&(Binding.METHOD))!=0)
- {
- binding=getBinding1(name,Binding.METHOD);
- if (binding!=null)
- return binding;
- }
- if ( (mask&(Binding.COMPILATION_UNIT))!=0)
- {
- name=CharOperation.replaceOnCopy(name, CompilationUnitScope.FILENAME_DOT_SUBSTITUTION, '.');
- if (knownCompUnits == null)
- return null;
- return knownCompUnits.get(name);
-
- }
- return null;
-}
-
-/* Answer the package or type named name; ask the oracle if it is not in the cache.
-* Answer null if it could not be resolved.
-*
-* When collisions exist between a type name & a package name, answer the type.
-* Treat the package as if it does not exist... a problem was already reported when the type was defined.
-*
-* NOTE: no visibility checks are performed.
-* THIS SHOULD ONLY BE USED BY SOURCE TYPES/SCOPES.
-*/
-
-public Binding getTypeOrPackage(char[] name, int mask) {
- Binding typeBinding = getBinding0(name, mask);
-// if (typeBinding != null && typeBinding != LookupEnvironment.TheNotFoundType) {
-// typeBinding = BinaryTypeBinding.resolveType(typeBinding, environment, false); // no raw conversion for now
-// if (typeBinding.isNestedType())
-// return new ProblemReferenceBinding(name, typeBinding, ProblemReasons.InternalNameProvided);
-// return typeBinding;
-// }
- if (typeBinding!=null)
- return typeBinding;
-
- PackageBinding packageBinding = getPackage0(name);
- if (packageBinding != null)
- return packageBinding;
-
- if (typeBinding == null && mask!=Binding.PACKAGE) { // have not looked for it before
- if ((typeBinding = environment.askForBinding(this, name,mask)) != null) {
-// if (typeBinding.isNestedType())
-// return new ProblemReferenceBinding(name, typeBinding, ProblemReasons.InternalNameProvided);
- return typeBinding;
- }
-
- // Since name could not be found, add a problem binding
- // to the collections so it will be reported as an error next time.
- addNotFoundBinding(name, mask);
- }
-
- if (packageBinding == null) { // have not looked for it before
- if ((packageBinding = findPackage(name)) != null)
- return packageBinding;
- }
-
- return null;
-}
-public char[] readableName() /*java.lang*/ {
- return CharOperation.concatWith(compoundName, '.');
-}
-public String toString() {
- if (compoundName == CharOperation.NO_CHAR_CHAR)
- return "The Default Package"; //$NON-NLS-1$
- else
- return "package " + ((compoundName != null) ? CharOperation.toString(compoundName) : "UNNAMED"); //$NON-NLS-1$ //$NON-NLS-2$
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ProblemBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ProblemBinding.java
deleted file mode 100644
index 1bdc3808..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ProblemBinding.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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.core.compiler.CharOperation;
-
-public class ProblemBinding extends Binding {
- public char[] name;
- public ReferenceBinding searchType;
- private int problemId;
-// NOTE: must only answer the subset of the name related to the problem
-
-public ProblemBinding(char[][] compoundName, int problemId) {
- this(CharOperation.concatWith(compoundName, '.'), problemId);
-}
-// NOTE: must only answer the subset of the name related to the problem
-
-public ProblemBinding(char[][] compoundName, ReferenceBinding searchType, int problemId) {
- this(CharOperation.concatWith(compoundName, '.'), searchType, problemId);
-}
-ProblemBinding(char[] name, int problemId) {
- this.name = name;
- this.problemId = problemId;
-}
-ProblemBinding(char[] name, ReferenceBinding searchType, int problemId) {
- this(name, problemId);
- this.searchType = searchType;
-}
-/* API
-* Answer the receiver's binding type from Binding.BindingID.
-*/
-
-public final int kind() {
- return VARIABLE | TYPE;
-}
-/* API
-* Answer the problem id associated with the receiver.
-* NoError if the receiver is a valid binding.
-*/
-
-public final int problemId() {
- return problemId;
-}
-public char[] readableName() {
- return name;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ProblemFieldBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ProblemFieldBinding.java
deleted file mode 100644
index e50994c7..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ProblemFieldBinding.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.lookup;
-
-public class ProblemFieldBinding extends FieldBinding {
- private int problemId;
- public FieldBinding closestMatch;
-
-// NOTE: must only answer the subset of the name related to the problem
-
-public ProblemFieldBinding(ReferenceBinding declaringClass, char[] name, int problemId) {
- this(null, declaringClass, name, problemId);
-}
-public ProblemFieldBinding(FieldBinding closestMatch, ReferenceBinding declaringClass, char[] name, int problemId) {
- this.closestMatch = closestMatch;
- this.declaringClass = declaringClass;
- this.name = name;
- this.problemId = problemId;
-}
-/* API
-* Answer the problem id associated with the receiver.
-* NoError if the receiver is a valid binding.
-*/
-
-public final int problemId() {
- return problemId;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ProblemMethodBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ProblemMethodBinding.java
deleted file mode 100644
index 758c3f51..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ProblemMethodBinding.java
+++ /dev/null
@@ -1,42 +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.compiler.lookup;
-
-public class ProblemMethodBinding extends MethodBinding {
-
- private int problemReason;
- public MethodBinding closestMatch; // TODO (philippe) should rename into #alternateMatch
-
-public ProblemMethodBinding(char[] selector, TypeBinding[] args, int problemReason) {
- this.selector = selector;
- this.parameters = (args == null || args.length == 0) ? Binding.NO_PARAMETERS : args;
- this.problemReason = problemReason;
-}
-public ProblemMethodBinding(char[] selector, TypeBinding[] args, ReferenceBinding declaringClass, int problemReason) {
- this.selector = selector;
- this.parameters = (args == null || args.length == 0) ? Binding.NO_PARAMETERS : args;
- this.declaringClass = declaringClass;
- this.problemReason = problemReason;
-}
-public ProblemMethodBinding(MethodBinding closestMatch, char[] selector, TypeBinding[] args, int problemReason) {
- this(selector, args, problemReason);
- this.closestMatch = closestMatch;
- if (closestMatch != null && problemReason != ProblemReasons.Ambiguous) this.declaringClass = closestMatch.declaringClass;
-}
-/* API
-* Answer the problem id associated with the receiver.
-* NoError if the receiver is a valid binding.
-*/
-
-public final int problemId() {
- return this.problemReason;
-}
-}
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
deleted file mode 100644
index 921b72a3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ProblemReasons.java
+++ /dev/null
@@ -1,25 +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.compiler.lookup;
-
-public interface ProblemReasons {
- final int NoError = 0;
- final int NotFound = 1;
- final int NotVisible = 2;
- final int Ambiguous = 3;
- final int InternalNameProvided = 4; // used if an internal name is used in source
- final int InheritedNameHidesEnclosingName = 5;
- final int NonStaticReferenceInConstructorInvocation = 6;
- final int NonStaticReferenceInStaticContext = 7;
- final int ReceiverTypeNotVisible = 8;
- final int IllegalSuperTypeVariable = 9;
- final int NotAFunction = 15;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ProblemReferenceBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ProblemReferenceBinding.java
deleted file mode 100644
index b79db848..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ProblemReferenceBinding.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.lookup;
-
-public class ProblemReferenceBinding extends ReferenceBinding {
- private ReferenceBinding closestMatch;
- private int problemReason;
-
-// NOTE: must only answer the subset of the name related to the problem
-
-public ProblemReferenceBinding(char[][] compoundName, ReferenceBinding closestMatch, int problemReason) {
- this.compoundName = compoundName;
- this.closestMatch = closestMatch;
- this.problemReason = problemReason;
-}
-public ProblemReferenceBinding(char[] name, ReferenceBinding closestMatch, int problemReason) {
- this(new char[][] {name}, closestMatch, problemReason);
-}
-
-/**
- * @see org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding#closestMatch()
- */
-public ReferenceBinding closestMatch() {
- return this.closestMatch;
-}
-
-/* API
-* Answer the problem id associated with the receiver.
-* NoError if the receiver is a valid binding.
-*/
-public int problemId() {
- return this.problemReason;
-}
-
-/**
- * @see org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding#shortReadableName()
- */
-public char[] shortReadableName() {
- return readableName();
-}
-
-}
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
deleted file mode 100644
index a8954b41..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ReferenceBinding.java
+++ /dev/null
@@ -1,819 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.lookup;
-
-import java.util.Arrays;
-import java.util.Comparator;
-
-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.classfmt.ClassFileConstants;
-import org.eclipse.wst.jsdt.internal.compiler.env.IDependent;
-import org.eclipse.wst.jsdt.internal.compiler.util.SimpleLookupTable;
-
-/*
-Not all fields defined by this type (& its subclasses) are initialized when it is created.
-Some are initialized only when needed.
-
-Accessors have been provided for some public fields so all TypeBindings have the same API...
-but access public fields directly whenever possible.
-Non-public fields have accessors which should be used everywhere you expect the field to be initialized.
-
-null is NOT a valid value for a non-public field... it just means the field is not initialized.
-*/
-
-abstract public class ReferenceBinding extends TypeBinding implements IDependent {
-
- public char[][] compoundName;
- public char[] sourceName;
- public int modifiers;
- public PackageBinding fPackage;
- char[] fileName;
- char[] constantPoolName;
- char[] signature;
-
- 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;
- char[] n2 = ((FieldBinding) o2).name;
- return ReferenceBinding.compare(n1, n2, n1.length, n2.length);
- }
- };
- private static final Comparator METHOD_COMPARATOR = new Comparator() {
- public int compare(Object o1, Object o2) {
- MethodBinding m1 = (MethodBinding) o1;
- MethodBinding m2 = (MethodBinding) o2;
- char[] s1 = m1.selector;
- char[] s2 = m2.selector;
- int c = ReferenceBinding.compare(s1, s2, s1.length, s2.length);
- return c == 0 ? m1.parameters.length - m2.parameters.length : c;
- }
- };
-
-public static FieldBinding binarySearch(char[] name, FieldBinding[] sortedFields) {
- if (sortedFields == null)
- return null;
- int max = sortedFields.length;
- if (max == 0)
- return null;
- int left = 0, right = max - 1, nameLength = name.length;
- int mid = 0;
- char[] midName;
- while (left <= right) {
- mid = left + (right - left) /2;
- int compare = compare(name, midName = sortedFields[mid].name, nameLength, midName.length);
- if (compare < 0) {
- right = mid-1;
- } else if (compare > 0) {
- left = mid+1;
- } else {
- return sortedFields[mid];
- }
- }
- return null;
-}
-
-/**
- * Returns a combined range value representing: (start + (end<<32)), where start is the index of the first matching method
- * (remember methods are sorted alphabetically on selectors), and end is the index of last contiguous methods with same
- * selector.
- * -1 means no method got found
- * @param selector
- * @param sortedMethods
- * @return (start + (end<<32)) or -1 if no method found
- */
-public static long binarySearch(char[] selector, MethodBinding[] sortedMethods) {
- if (sortedMethods == null)
- return -1;
- int max = sortedMethods.length;
- if (max == 0)
- return -1;
- int left = 0, right = max - 1, selectorLength = selector.length;
- int mid = 0;
- char[] midSelector;
- while (left <= right) {
- mid = left + (right - left) /2;
- int compare = compare(selector, midSelector = sortedMethods[mid].selector, selectorLength, midSelector.length);
- if (compare < 0) {
- right = mid-1;
- } else if (compare > 0) {
- left = mid+1;
- } else {
- int start = mid, end = mid;
- // find first method with same selector
- while (start > left && CharOperation.equals(sortedMethods[start-1].selector, selector)){ start--; }
- // find last method with same selector
- while (end < right && CharOperation.equals(sortedMethods[end+1].selector, selector)){ end++; }
- return start + ((long)end<< 32);
- }
- }
- return -1;
-}
-
-/**
- * Compares two strings lexicographically.
- * The comparison is based on the Unicode value of each character in
- * the strings.
- *
- * @return the value <code>0</code> if the str1 is equal to str2;
- * a value less than <code>0</code> if str1
- * is lexicographically less than str2;
- * and a value greater than <code>0</code> if str1 is
- * lexicographically greater than str2.
- */
-static int compare(char[] str1, char[] str2, int len1, int len2) {
- int n= Math.min(len1, len2);
- int i= 0;
- while (n-- != 0) {
- char c1= str1[i];
- char c2= str2[i++];
- if (c1 != c2) {
- return c1 - c2;
- }
- }
- return len1 - len2;
-}
-
-/**
- * Sort the field array using a quicksort
- */
-public static void sortFields(FieldBinding[] sortedFields, int left, int right) {
- Arrays.sort(sortedFields, left, right, FIELD_COMPARATOR);
-}
-
-/**
- * Sort the field array using a quicksort
- */
-public static void sortMethods(MethodBinding[] sortedMethods, int left, int right) {
- Arrays.sort(sortedMethods, left, right, METHOD_COMPARATOR);
-}
-
-public FieldBinding[] availableFields() {
- return fields();
-}
-public MethodBinding[] availableMethods() {
- return methods();
-}
-/* Answer true if the receiver can be instantiated
-*/
-public boolean canBeInstantiated() {
- return (this.modifiers & (ClassFileConstants.AccAbstract)) == 0;
-}
-/* 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 == this.fPackage;
-}
-/* Answer true if the receiver is visible to the receiverType and the invocationType.
-*/
-
-public final boolean canBeSeenBy(ReferenceBinding receiverType, ReferenceBinding invocationType) {
- if (isPublic()) return true;
-
- if (invocationType == this && invocationType == receiverType) return true;
-
- if (isPrivate()) {
- // answer true if the receiverType is the receiver or its enclosingType
- // AND the invocationType and the receiver have a common enclosingType
- if (!(receiverType == this || receiverType == enclosingType())) {
- // special tolerance for type variable direct bounds
- return false;
- }
-
-
- if (invocationType != this) {
- ReferenceBinding outerInvocationType = invocationType;
- ReferenceBinding temp = outerInvocationType.enclosingType();
- while (temp != null) {
- outerInvocationType = temp;
- temp = temp.enclosingType();
- }
-
- ReferenceBinding outerDeclaringClass = (ReferenceBinding)this;
- temp = outerDeclaringClass.enclosingType();
- while (temp != null) {
- outerDeclaringClass = temp;
- temp = temp.enclosingType();
- }
- if (outerInvocationType != outerDeclaringClass) return false;
- }
- return true;
- }
-
- // isDefault()
- if (invocationType.fPackage != this.fPackage) return false;
-
- ReferenceBinding currentType = receiverType;
- ReferenceBinding declaringClass = enclosingType() == null ? this : enclosingType();
- do {
- if (declaringClass == currentType) return true;
- 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);
- return false;
-}
-/*
- * Answer true if the receiver is visible to the type provided by the scope.
- */
-public final boolean canBeSeenBy(Scope scope) {
- if (isPublic()) return true;
-
- SourceTypeBinding invocationType = scope.enclosingSourceType();
- if (invocationType == this) return true;
-
- if (invocationType == null) // static import call
- return !isPrivate() && scope.getCurrentPackage() == this.fPackage;
-
- if (isPrivate()) {
- // answer true if the receiver and the invocationType 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 = (ReferenceBinding)this;
- temp = outerDeclaringClass.enclosingType();
- while (temp != null) {
- outerDeclaringClass = temp;
- temp = temp.enclosingType();
- }
- return outerInvocationType == outerDeclaringClass;
- }
-
- // isDefault()
- return invocationType.fPackage == this.fPackage;
-}
-
-/**
- * In case of problems, returns the closest match found. It may not be perfect match, but the
- * result of a best effort to improve fault-tolerance.
-*/
-public ReferenceBinding closestMatch() {
- return this; // by default, the closest match is the binding itself
-}
-
-public void computeId() {
-
- switch (this.compoundName.length) {
-
- case 1 :
- case 2 :
-// if (!CharOperation.endsWith(fileName, TypeConstants.SYSTEMJS)) return;
-// if (!CharOperation.equals(TypeConstants.SYSTEMJS, this.compoundName[0]))
-// return;
-
-// // remaining types MUST be in java.*.*
-// if (!CharOperation.equals(TypeConstants.LANG, this.compoundName[1])) {
-// if (CharOperation.equals(TypeConstants.IO, this.compoundName[1])) {
-// if (CharOperation.equals(TypeConstants.JAVA_IO_PRINTSTREAM[2], this.compoundName[2]))
-// this.id = TypeIds.T_JavaIoPrintStream;
-// else if (CharOperation.equals(TypeConstants.JAVA_IO_SERIALIZABLE[2], this.compoundName[2]))
-// this.id = TypeIds.T_JavaIoSerializable;
-// else if (CharOperation.equals(TypeConstants.JAVA_IO_EXTERNALIZABLE[2], this.compoundName[2]))
-// this.id = TypeIds.T_JavaIoExternalizable;
-// else if (CharOperation.equals(TypeConstants.JAVA_IO_OBJECTSTREAMEXCEPTION[2], this.compoundName[2]))
-// this.id = TypeIds.T_JavaIoObjectStreamException;
-// else if (CharOperation.equals(TypeConstants.JAVA_IO_IOEXCEPTION[2], this.compoundName[2]))
-// this.id = TypeIds.T_JavaIoException;
-// } else if (CharOperation.equals(TypeConstants.UTIL, this.compoundName[1])
-// && CharOperation.equals(TypeConstants.JAVA_UTIL_ITERATOR[2], this.compoundName[2])) {
-// this.id = TypeIds.T_JavaUtilIterator;
-// }
-// return;
-// }
-
-
- // remaining types MUST be in java.lang.*
- char[] typeName = (compoundName.length>1&&CharOperation.equals(compoundName[0], TypeConstants.SYSTEMJS))
- ? this.compoundName[1] : this.compoundName[0];
- if (typeName.length == 0) return; // just to be safe
- switch (typeName[0]) {
-// case 'A' :
-// if (CharOperation.equals(typeName, TypeConstants.JAVA_LANG_ASSERTIONERROR[2]))
-// this.id = TypeIds.T_JavaLangAssertionError;
-// return;
- case 'B' :
- if (CharOperation.equals(typeName, TypeConstants.BOOLEAN_OBJECT[0]))
- this.id = TypeIds.T_boolean;
-// else if (CharOperation.equals(typeName, TypeConstants.JAVA_LANG_BYTE[2]))
-// this.id = TypeIds.T_JavaLangByte;
- return;
-// case 'C' :
-// if (CharOperation.equals(typeName, TypeConstants.JAVA_LANG_CHARACTER[2]))
-// this.id = TypeIds.T_JavaLangCharacter;
-// else if (CharOperation.equals(typeName, TypeConstants.JAVA_LANG_CLASS[2]))
-// this.id = TypeIds.T_JavaLangClass;
-// else if (CharOperation.equals(typeName, TypeConstants.JAVA_LANG_CLASSNOTFOUNDEXCEPTION[2]))
-// this.id = TypeIds.T_JavaLangClassNotFoundException;
-// else if (CharOperation.equals(typeName, TypeConstants.JAVA_LANG_CLONEABLE[2]))
-// this.id = TypeIds.T_JavaLangCloneable;
-// return;
-// case 'D' :
-// if (CharOperation.equals(typeName, TypeConstants.JAVA_LANG_DOUBLE[2]))
-// this.id = TypeIds.T_JavaLangDouble;
-// else if (CharOperation.equals(typeName, TypeConstants.JAVA_LANG_DEPRECATED[2]))
-// this.id = TypeIds.T_JavaLangDeprecated;
-// return;
- case 'E' :
- if (CharOperation.equals(typeName, TypeConstants.ERROR[0]))
- this.id = TypeIds.T_JavaLangError;
-// else if (CharOperation.equals(typeName, TypeConstants.JAVA_LANG_EXCEPTION[2]))
-// this.id = TypeIds.T_JavaLangException;
-// else if (CharOperation.equals(typeName, TypeConstants.JAVA_LANG_ENUM[2]))
-// this.id = TypeIds.T_JavaLangEnum;
- return;
- case 'F' :
- if (CharOperation.equals(typeName, TypeConstants.FUNCTION[0]))
- this.id = TypeIds.T_function;
-// if (CharOperation.equals(typeName, TypeConstants.JAVA_LANG_FLOAT[2]))
-// this.id = TypeIds.T_JavaLangFloat;
- return;
-// case 'I' :
-// if (CharOperation.equals(typeName, TypeConstants.JAVA_LANG_INTEGER[2]))
-// this.id = TypeIds.T_JavaLangInteger;
-// else if (CharOperation.equals(typeName, TypeConstants.JAVA_LANG_ITERABLE[2]))
-// this.id = TypeIds.T_JavaLangIterable;
-// else if (CharOperation.equals(typeName, TypeConstants.JAVA_LANG_ILLEGALARGUMENTEXCEPTION[2]))
-// this.id = TypeIds.T_JavaLangIllegalArgumentException;
-// return;
-// case 'L' :
-// if (CharOperation.equals(typeName, TypeConstants.JAVA_LANG_LONG[2]))
-// this.id = TypeIds.T_JavaLangLong;
-// return;
- case 'N' :
- if (CharOperation.equals(typeName, TypeConstants.NUMBER[0]))
- this.id = TypeIds.T_int;
- return;
- case 'O' :
- if (CharOperation.equals(typeName, TypeConstants.JAVA_LANG_OBJECT[0]))
- this.id = TypeIds.T_JavaLangObject;
-// else if (CharOperation.equals(typeName, TypeConstants.JAVA_LANG_OVERRIDE[2]))
-// this.id = TypeIds.T_JavaLangOverride;
- return;
-// case 'R' :
-// if (CharOperation.equals(typeName, TypeConstants.JAVA_LANG_RUNTIMEEXCEPTION[2]))
-// this.id = TypeIds.T_JavaLangRuntimeException;
-// break;
- case 'S' :
- if (CharOperation.equals(typeName, TypeConstants.JAVA_LANG_STRING[0]))
- this.id = TypeIds.T_JavaLangString;
-// else if (CharOperation.equals(typeName, TypeConstants.JAVA_LANG_STRINGBUFFER[2]))
-// this.id = TypeIds.T_JavaLangStringBuffer;
-// else if (CharOperation.equals(typeName, TypeConstants.JAVA_LANG_STRINGBUILDER[2]))
-// this.id = TypeIds.T_JavaLangStringBuilder;
-// else if (CharOperation.equals(typeName, TypeConstants.JAVA_LANG_SYSTEM[2]))
-// this.id = TypeIds.T_JavaLangSystem;
-// else if (CharOperation.equals(typeName, TypeConstants.JAVA_LANG_SHORT[2]))
-// this.id = TypeIds.T_JavaLangShort;
-// else if (CharOperation.equals(typeName, TypeConstants.JAVA_LANG_SUPPRESSWARNINGS[2]))
-// this.id = TypeIds.T_JavaLangSuppressWarnings;
- return;
-// case 'T' :
-// if (CharOperation.equals(typeName, TypeConstants.JAVA_LANG_THROWABLE[2]))
-// this.id = TypeIds.T_JavaLangThrowable;
-// return;
- case 'V' :
- if (CharOperation.equals(typeName, TypeConstants.JAVA_LANG_VOID[2]))
- this.id = TypeIds.T_JavaLangVoid;
- return;
- }
- break;
-
- case 4:
- if (!CharOperation.equals(TypeConstants.JAVA, this.compoundName[0]))
- return;
- if (!CharOperation.equals(TypeConstants.LANG, this.compoundName[1]))
- return;
- char[] packageName = this.compoundName[2];
- if (packageName.length == 0) return; // just to be safe
- typeName = this.compoundName[3];
- if (typeName.length == 0) return; // just to be safe
- if (CharOperation.equals(packageName, TypeConstants.REFLECT)) {
- return;
- }
- break;
- }
-}
-/*
- * p.X<T extends Y & I, U extends Y> {} -> Lp/X<TT;TU;>;
- */
-public char[] computeUniqueKey(boolean isLeaf) {
- if (!isLeaf) return signature();
- return signature();
-}
-/* Answer the receiver's constant pool name.
-*
-* NOTE: This method should only be used during/after code gen.
-*/
-public char[] constantPoolName() /* java/lang/Object */ {
- if (this.constantPoolName != null) return this.constantPoolName;
-
- return this.constantPoolName = CharOperation.concatWith(this.compoundName, '/');
-}
-public String debugName() {
- return (this.compoundName != null) ? new String(readableName()) : "UNNAMED TYPE"; //$NON-NLS-1$
-}
-public final int depth() {
- int depth = 0;
- ReferenceBinding current = this;
- while ((current = current.enclosingType()) != null)
- depth++;
- return depth;
-}
-
-public final ReferenceBinding enclosingTypeAt(int relativeDepth) {
- ReferenceBinding current = this;
- while (relativeDepth-- > 0 && current != null)
- current = current.enclosingType();
- return current;
-}
-
-public int fieldCount() {
- return fields().length;
-}
-
-public FieldBinding[] fields() {
- return Binding.NO_FIELDS;
-}
-
-public final int getAccessFlags() {
- return this.modifiers & ExtraCompilerModifiers.AccJustFlag;
-}
-public MethodBinding getExactConstructor(TypeBinding[] argumentTypes) {
- return null;
-}
-public MethodBinding getExactMethod(char[] selector, TypeBinding[] argumentTypes, CompilationUnitScope refScope) {
- return null;
-}
-public FieldBinding getField(char[] fieldName, boolean needResolve) {
- return null;
-}
-/**
- * @see org.eclipse.wst.jsdt.internal.compiler.env.IDependent#getFileName()
- */
-public char[] getFileName() {
- return this.fileName;
-}
-public ReferenceBinding getMemberType(char[] typeName) {
- ReferenceBinding[] memberTypes = memberTypes();
- for (int i = memberTypes.length; --i >= 0;)
- if (CharOperation.equals(memberTypes[i].sourceName, typeName))
- return memberTypes[i];
- return null;
-}
-
-public MethodBinding[] getMethods(char[] selector) {
- return Binding.NO_METHODS;
-}
-
-public PackageBinding getPackage() {
- return this.fPackage;
-}
-
-public int hashCode() {
- // ensure ReferenceBindings hash to the same posiiton as UnresolvedReferenceBindings so they can be replaced without rehashing
- // ALL ReferenceBindings are unique when created so equals() is the same as ==
- return (this.compoundName == null || this.compoundName.length == 0)
- ? super.hashCode()
- : CharOperation.hashCode(this.compoundName[this.compoundName.length - 1]);
-}
-
-/**
- * Returns true if the two types have an incompatible common supertype,
- * e.g. List<String> and List<Integer>
- */
-public boolean hasIncompatibleSuperType(ReferenceBinding otherType) {
-
- if (this == otherType) return false;
-
- ReferenceBinding[] interfacesToVisit = null;
- int nextPosition = 0;
- ReferenceBinding currentType = this;
- TypeBinding match;
- do {
- match = otherType.findSuperTypeWithSameErasure(currentType);
- if (match != null && !match.isIntersectingWith(currentType))
- return true;
- } while ((currentType = currentType.superclass()) != null);
-
-// for (int i = 0; i < nextPosition; i++) {
-// currentType = interfacesToVisit[i];
-// if (currentType == otherType) return false;
-// match = otherType.findSuperTypeWithSameErasure(currentType);
-// if (match != null && !match.isIntersectingWith(currentType))
-// return true;
-// }
- return false;
-}
-public boolean hasMemberTypes() {
- return false;
-}
-public final boolean hasRestrictedAccess() {
- return (this.modifiers & ExtraCompilerModifiers.AccRestrictedAccess) != 0;
-}
-
-// Internal method... assume its only sent to classes NOT interfaces
-boolean implementsMethod(MethodBinding method) {
- char[] selector = method.selector;
- ReferenceBinding type = this;
- while (type != null) {
- MethodBinding[] methods = type.methods();
- long range;
- if ((range = ReferenceBinding.binarySearch(selector, methods)) >= 0) {
- int start = (int) range, end = (int) (range >> 32);
- for (int i = start; i <= end; i++) {
- if (methods[i].areParametersEqual(method))
- return true;
- }
- }
- type = type.superclass();
- }
- return false;
-}
-
-public final boolean isBinaryBinding() {
- return (this.tagBits & TagBits.IsBinaryBinding) != 0;
-}
-
-public boolean isClass() {
- return true;
-}
-
-/**
- * Answer true if the receiver type can be assigned to the argument type (right)
- * In addition to improving performance, caching also ensures there is no infinite regression
- * since per nature, the compatibility check is recursive through parameterized type arguments (122775)
- */
-public boolean isCompatibleWith(TypeBinding otherType) {
-
- if (otherType == this)
- return true;
- if (otherType.id == TypeIds.T_JavaLangObject || otherType.id == TypeIds.T_any)
- return true;
- Object result;
- if (this.compatibleCache == null) {
- this.compatibleCache = new SimpleLookupTable(3);
- result = null;
- } else {
- result = this.compatibleCache.get(otherType);
- if (result != null) {
- return result == Boolean.TRUE;
- }
- }
- this.compatibleCache.put(otherType, Boolean.FALSE); // protect from recursive call
- if (isCompatibleWith0(otherType)) {
- this.compatibleCache.put(otherType, Boolean.TRUE);
- return true;
- }
- return false;
-}
-
-/**
- * Answer true if the receiver type can be assigned to the argument type (right)
- */
-private boolean isCompatibleWith0(TypeBinding otherType) {
- if (otherType == this)
- return true;
- if (otherType.id == TypeIds.T_JavaLangObject)
- return true;
- // equivalence may allow compatibility with array type through wildcard
- // bound
- if (this.isEquivalentTo(otherType))
- return true;
- switch (otherType.kind()) {
- case Binding.TYPE :
- ReferenceBinding otherReferenceType = (ReferenceBinding) otherType;
- if(Arrays.equals(this.compoundName,otherReferenceType.compoundName) && Arrays.equals(this.fileName, otherReferenceType.fileName)) {
- return true;
- }
-
-
- if ( otherReferenceType.isSuperclassOf(this))
- return true;
- return (otherReferenceType.isAnonymousType() && this.isSuperclassOf(otherReferenceType));
- case Binding.ARRAY_TYPE:
- return this==((ArrayBinding)otherType).referenceBinding;
- default :
- return false;
- }
-}
-
-/**
- * Answer true if the receiver has default visibility
- */
-public final boolean isDefault() {
- return (this.modifiers & (ClassFileConstants.AccPublic | ClassFileConstants.AccProtected | ClassFileConstants.AccPrivate)) == 0;
-}
-
-/**
- * Answer true if the receiver is a deprecated type
- */
-public final boolean isDeprecated() {
- return (this.modifiers & ClassFileConstants.AccDeprecated) != 0;
-}
-
-/**
- * Returns true if the type hierarchy is being connected
- */
-public boolean isHierarchyBeingConnected() {
- return (this.tagBits & TagBits.EndHierarchyCheck) == 0 && (this.tagBits & TagBits.BeginHierarchyCheck) != 0;
-}
-
-/**
- * Answer true if the receiver has private visibility
- */
-public final boolean isPrivate() {
- return (this.modifiers & ClassFileConstants.AccPrivate) != 0;
-}
-
-/**
- * Answer true if the receiver has public visibility
- */
-public final boolean isPublic() {
- return (this.modifiers & ClassFileConstants.AccPublic) != 0;
-}
-
-/**
- * Answer true if the receiver is a static member type (or toplevel)
- */
-public final boolean isStatic() {
- return (this.modifiers & (ClassFileConstants.AccStatic)) != 0 || (this.tagBits & TagBits.IsNestedType) == 0;
-}
-/**
- * Answer true if all float operations must adher to IEEE 754 float/double rules
- */
-public final boolean isStrictfp() {
- return (this.modifiers & ClassFileConstants.AccStrictfp) != 0;
-}
-
-/**
- * Answer true if the receiver is in the superclass hierarchy of aType
- * NOTE: Object.isSuperclassOf(Object) -> false
- */
-public boolean isSuperclassOf(ReferenceBinding otherType) {
- while ((otherType = otherType.superclass()) != null) {
- if (otherType.isEquivalentTo(this)) return true;
- }
- return false;
-}
-/**
- * @see org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding#isThrowable()
- */
-public boolean isThrowable() {
- ReferenceBinding current = this;
- do {
- switch (current.id) {
- case TypeIds.T_JavaLangThrowable :
- case TypeIds.T_JavaLangError :
- case TypeIds.T_JavaLangRuntimeException :
- case TypeIds.T_JavaLangException :
- return true;
- }
- } while ((current = current.superclass()) != null);
- return false;
-}
-/**
- * JLS 11.5 ensures that Throwable, Exception, RuntimeException and Error are directly connected.
- * (Throwable<- Exception <- RumtimeException, Throwable <- Error). Thus no need to check #isCompatibleWith
- * but rather check in type IDs so as to avoid some eager class loading for JCL writers.
- * When 'includeSupertype' is true, answers true if the given type can be a supertype of some unchecked exception
- * type (i.e. Throwable or Exception).
- * @see org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding#isUncheckedException(boolean)
- */
-public boolean isUncheckedException(boolean includeSupertype) {
- if (JavaScriptCore.IS_ECMASCRIPT4) // no checked exceptions for now
- {
- switch (this.id) {
- case TypeIds.T_JavaLangError :
- case TypeIds.T_JavaLangRuntimeException :
- return true;
- case TypeIds.T_JavaLangThrowable :
- case TypeIds.T_JavaLangException :
- return includeSupertype;
- }
- ReferenceBinding current = this;
- while ((current = current.superclass()) != null) {
- switch (current.id) {
- case TypeIds.T_JavaLangError :
- case TypeIds.T_JavaLangRuntimeException :
- return true;
- case TypeIds.T_JavaLangThrowable :
- case TypeIds.T_JavaLangException :
- return false;
- }
- }
- return false;
- }
- else
- return true;
-}
-/**
- * Answer true if the receiver has private visibility and is used locally
- */
-public final boolean isUsed() {
- return (this.modifiers & ExtraCompilerModifiers.AccLocallyUsed) != 0;
-}
-
-/* Answer true if the receiver is deprecated (or any of its enclosing types)
-*/
-public boolean isViewedAsDeprecated() {
- return (this.modifiers & (ClassFileConstants.AccDeprecated | ExtraCompilerModifiers.AccDeprecatedImplicitly)) != 0;
-}
-public ReferenceBinding[] memberTypes() {
- return Binding.NO_MEMBER_TYPES;
-}
-public MethodBinding[] methods() {
- return Binding.NO_METHODS;
-}
-public final ReferenceBinding outermostEnclosingType() {
- ReferenceBinding current = this;
- while (true) {
- ReferenceBinding last = current;
- if ((current = current.enclosingType()) == null)
- return last;
- }
-}
-/**
-* Answer the source name for the type.
-* In the case of member types, as the qualified name from its top level type.
-* For example, for a member type N defined inside M & A: "A.M.N".
-*/
-
-public char[] qualifiedSourceName() {
- if (isMemberType())
- return CharOperation.concat(enclosingType().qualifiedSourceName(), sourceName(), '.');
- return sourceName();
-}
-
-/* Answer the receiver's signature.
-*
-* NOTE: This method should only be used during/after code gen.
-*/
-
-public char[] readableName() /*java.lang.Object, p.X<T> */ {
- char[] readableName;
- if (isMemberType()) {
- readableName = CharOperation.concat(enclosingType().readableName(), this.sourceName, '.');
- } else {
- readableName = CharOperation.concatWith(this.compoundName, '.');
- }
- return readableName;
-}
-
-public char[] shortReadableName() /*Object*/ {
- char[] shortReadableName;
- if (isMemberType()) {
- shortReadableName = CharOperation.concat(enclosingType().shortReadableName(), this.sourceName, '.');
- } else {
- shortReadableName = this.sourceName;
- }
- return shortReadableName;
-}
-public char[] signature() /* Ljava/lang/Object; */ {
- if (this.signature != null)
- return this.signature;
-
- return this.signature = CharOperation.concat('L', constantPoolName(), ';');
-}
-public char[] sourceName() {
- return this.sourceName;
-}
-
-public ReferenceBinding superclass() {
- return null;
-}
-public InferredType getInferredType() {
-
- return null;
-}
-
-MethodBinding[] unResolvedMethods() { // for the MethodVerifier so it doesn't resolve types
- return methods();
-}
-
-public void cleanup()
-{
-
-}
-}
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
deleted file mode 100644
index d9879f5a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/Scope.java
+++ /dev/null
@@ -1,2979 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.lookup;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.Map;
-
-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.ast.ASTNode;
-import org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.CaseStatement;
-import org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ImportReference;
-import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants;
-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.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 {
-
- /* Scope kinds */
- public final static int BLOCK_SCOPE = 1;
- public final static int CLASS_SCOPE = 3;
- public final static int COMPILATION_UNIT_SCOPE = 4;
- public final static int METHOD_SCOPE = 2;
- public final static int WITH_SCOPE = 5;
-
- /* Argument Compatibilities */
- public final static int NOT_COMPATIBLE = -1;
- public final static int COMPATIBLE = 0;
- public final static int AUTOBOX_COMPATIBLE = 1;
- public final static int VARARGS_COMPATIBLE = 2;
-
- /* Type Compatibilities */
- public static final int EQUAL_OR_MORE_SPECIFIC = -1;
- public static final int NOT_RELATED = 0;
- public static final int MORE_GENERIC = 1;
-
- public int kind;
- public Scope parent;
-
- /* Answer an int describing the relationship between the given types.
- *
- * NOT_RELATED
- * EQUAL_OR_MORE_SPECIFIC : left is compatible with right
- * MORE_GENERIC : right is compatible with left
- */
- public static int compareTypes(TypeBinding left, TypeBinding right) {
- if (left.isCompatibleWith(right))
- return Scope.EQUAL_OR_MORE_SPECIFIC;
- if (right.isCompatibleWith(left))
- return Scope.MORE_GENERIC;
- return Scope.NOT_RELATED;
- }
- public static TypeBinding getBaseType(char[] name) {
- // list should be optimized (with most often used first)
- int length = name.length;
- if (length > 2 && length < 8) {
- switch (name[0]) {
- case 'i' :
- if (length == 3 && name[1] == 'n' && name[2] == 't')
- return TypeBinding.INT;
- break;
- case 'v' :
- if (length == 4 && name[1] == 'o' && name[2] == 'i' && name[3] == 'd')
- return TypeBinding.VOID;
- break;
- case 'b' :
- if (length == 7
- && name[1] == 'o'
- && name[2] == 'o'
- && name[3] == 'l'
- && name[4] == 'e'
- && name[5] == 'a'
- && name[6] == 'n')
- return TypeBinding.BOOLEAN;
- break;
- case 'c' :
- if (length == 4 && name[1] == 'h' && name[2] == 'a' && name[3] == 'r')
- return TypeBinding.CHAR;
- break;
- case 'd' :
- if (length == 6
- && name[1] == 'o'
- && name[2] == 'u'
- && name[3] == 'b'
- && name[4] == 'l'
- && name[5] == 'e')
- return TypeBinding.DOUBLE;
- break;
- case 'f' :
- if (length == 5
- && name[1] == 'l'
- && name[2] == 'o'
- && name[3] == 'a'
- && name[4] == 't')
- return TypeBinding.FLOAT;
- break;
- case 'l' :
- if (length == 4 && name[1] == 'o' && name[2] == 'n' && name[3] == 'g')
- return TypeBinding.LONG;
- break;
- case 's' :
- if (length == 5
- && name[1] == 'h'
- && name[2] == 'o'
- && name[3] == 'r'
- && name[4] == 't')
- return TypeBinding.SHORT;
- }
- }
- return null;
- }
-
- protected Scope(int kind, Scope parent) {
- this.kind = kind;
- this.parent = parent;
- }
-
- /*
- * Boxing primitive
- */
- public TypeBinding boxing(TypeBinding type) {
- if (type.isBaseType())
- return environment().computeBoxingType(type);
- return type;
- }
-
- public ClassScope classScope() {
- Scope scope = this;
- do {
- if (scope instanceof ClassScope)
- return (ClassScope) scope;
- scope = scope.parent;
- } while (scope != null);
- return null;
- }
-
- public final CompilationUnitScope compilationUnitScope() {
- Scope lastScope = null;
- Scope scope = this;
- do {
- lastScope = scope;
- scope = scope.parent;
- } while (scope != null);
- return (CompilationUnitScope) lastScope;
- }
-
- /**
- * Finds the most specific compiler options
- */
- public final CompilerOptions compilerOptions() {
-
- return compilationUnitScope().environment.globalOptions;
- }
-
- /**
- * Internal use only
- * Given a method, returns null if arguments cannot be converted to parameters.
- * Will answer a subsituted method in case the method was generic and type inference got triggered;
- * in case the method was originally compatible, then simply answer it back.
- */
- protected final MethodBinding computeCompatibleMethod(MethodBinding method, TypeBinding[] arguments, InvocationSite invocationSite) {
-
- TypeBinding[] parameters = method.parameters;
- if (parameters == arguments
-// && (method.returnType.tagBits & TagBits.HasTypeVariable) == 0
- )
- return method;
-
- int argLength = arguments.length;
- int paramLength = parameters.length;
- boolean isVarArgs = method.isVarargs();
- if (argLength != paramLength)
- if (!isVarArgs || argLength < paramLength - 1)
- return null; // incompatible
-
- if (parameterCompatibilityLevel(method, arguments) > NOT_COMPATIBLE)
- return method;
- return null; // incompatible
- }
-
- public ArrayBinding createArrayType(TypeBinding type, int dimension) {
- if (type.isValidBinding())
- return environment().createArrayType(type, dimension);
- // do not cache obvious invalid types
- return new ArrayBinding(type, dimension, environment());
- }
-
- public final ClassScope enclosingClassScope() {
- Scope scope = this;
- while ((scope = scope.parent) != null) {
- if (scope instanceof ClassScope) return (ClassScope) scope;
- }
- return null; // may answer null if no type around
- }
-
- public final MethodScope enclosingMethodScope() {
- Scope scope = this;
- if (scope instanceof MethodScope) return (MethodScope) scope;
- while ((scope = scope.parent) != null) {
- if (scope instanceof MethodScope) return (MethodScope) scope;
- }
- return null; // may answer null if no method around
- }
-
- /* Answer the scope receiver type (could be parameterized)
- */
- public final ReferenceBinding enclosingReceiverType() {
- Scope scope = this;
- AbstractMethodDeclaration inMethod =null;
- do {
- if (scope instanceof MethodScope) {
- MethodScope methodScope = (MethodScope) scope;
- inMethod = methodScope.referenceMethod();
- if (inMethod.inferredMethod!=null && inMethod.inferredMethod.inType!=null && inMethod.inferredMethod.inType.binding!=null)
- return inMethod.inferredMethod.inType.binding;
- }
- else if (scope instanceof CompilationUnitScope) {
- CompilationUnitScope compilationUnitScope = (CompilationUnitScope) scope;
- for (int i=0;i<compilationUnitScope.referenceContext.numberInferredTypes;i++)
- {
- InferredType type= compilationUnitScope.referenceContext.inferredTypes[i];
- if (type.containsMethod(inMethod))
- return (ReferenceBinding)compilationUnitScope.getTypeOrPackage(type.getName(),Binding.TYPE);
- }
- }
- if (scope instanceof ClassScope) {
- ClassScope classScope=(ClassScope)scope;
- if (classScope.referenceContext!=null)
- return classScope.referenceContext.binding;
- if (classScope.inferredType!=null)
- return classScope.inferredType.binding;
-// return environment().convertToParameterizedType(((ClassScope) scope).referenceContext.binding);
- }
- scope = scope.parent;
- } while (scope != null);
- return null;
- }
- public final CompilationUnitBinding enclosingCompilationUnit() {
- Scope scope = this;
- do {
- if (scope instanceof CompilationUnitScope) {
- return ((CompilationUnitScope) scope).referenceContext.compilationUnitBinding;
- }
- scope = scope.parent;
- } while (scope != null);
- return null;
- }
-
- /**
- * Returns the immediately enclosing reference context, starting from current scope parent.
- * If starting on a class, it will skip current class. If starting on unitScope, returns null.
- */
- public ReferenceContext enclosingReferenceContext() {
- Scope current = this;
- while ((current = current.parent) != null) {
- switch(current.kind) {
- case METHOD_SCOPE :
- return ((MethodScope) current).referenceContext;
- case CLASS_SCOPE :
- return ((ClassScope) current).referenceContext;
- case COMPILATION_UNIT_SCOPE :
- return ((CompilationUnitScope) current).referenceContext;
- }
- }
- return null;
- }
-
- /* Answer the scope enclosing source type (could be generic)
- */
- public final SourceTypeBinding enclosingSourceType() {
- Scope scope = this;
- do {
- if (scope instanceof ClassScope)
- return ((ClassScope) scope).getReferenceBinding();
- else if(scope instanceof CompilationUnitScope)
- return ((CompilationUnitScope) scope).referenceContext.compilationUnitBinding;
- scope = scope.parent;
- } while (scope != null);
- return null;
- }
-
- public final SourceTypeBinding enclosingTypeBinding() {
- Scope scope = this;
- do {
- if (scope instanceof ClassScope)
- return ((ClassScope) scope).getReferenceBinding();
- else if (scope instanceof CompilationUnitScope)
- return ((CompilationUnitScope) scope).referenceContext.compilationUnitBinding;
- scope = scope.parent;
- } while (scope != null);
- return null;
- }
-
- public final LookupEnvironment environment() {
- Scope scope, unitScope = this;
- while ((scope = unitScope.parent) != null)
- unitScope = scope;
- return ((CompilationUnitScope) unitScope).environment;
- }
-
- // abstract method lookup lookup (since maybe missing default abstract methods)
- protected MethodBinding findDefaultAbstractMethod(
- ReferenceBinding receiverType,
- char[] selector,
- TypeBinding[] argumentTypes,
- InvocationSite invocationSite,
- ReferenceBinding classHierarchyStart,
- ObjectVector found,
- MethodBinding concreteMatch) {
-
- int startFoundSize = found.size;
- ReferenceBinding currentType = classHierarchyStart;
- while (currentType != null) {
- currentType = currentType.superclass();
- }
- MethodBinding[] candidates = null;
- int candidatesCount = 0;
- MethodBinding problemMethod = null;
- int foundSize = found.size;
- if (foundSize > startFoundSize) {
- // argument type compatibility check
- for (int i = startFoundSize; i < foundSize; i++) {
- MethodBinding methodBinding = (MethodBinding) found.elementAt(i);
- MethodBinding compatibleMethod = computeCompatibleMethod(methodBinding, argumentTypes, invocationSite);
- if (compatibleMethod != null) {
- if (compatibleMethod.isValidBinding()) {
- if (candidatesCount == 0) {
- candidates = new MethodBinding[foundSize - startFoundSize + 1];
- if (concreteMatch != null)
- candidates[candidatesCount++] = concreteMatch;
- }
- candidates[candidatesCount++] = compatibleMethod;
- } else if (problemMethod == null) {
- problemMethod = compatibleMethod;
- }
- }
- }
- }
-
- if (candidatesCount < 2) {
- if (concreteMatch == null) {
- if (candidatesCount == 0)
- return problemMethod; // can be null
- concreteMatch = candidates[0];
- }
- return concreteMatch;
- }
- // no need to check for visibility - interface methods are public
- if (compilerOptions().complianceLevel >= ClassFileConstants.JDK1_4)
- return mostSpecificMethodBinding(candidates, candidatesCount, argumentTypes, invocationSite, receiverType);
- return null;
- }
-
- // Internal use only
- public ReferenceBinding findDirectMemberType(char[] typeName, ReferenceBinding enclosingType) {
- if ((enclosingType.tagBits & TagBits.HasNoMemberTypes) != 0)
- return null; // know it has no member types (nor inherited member types)
-
- ReferenceBinding enclosingReceiverType = enclosingReceiverType();
- CompilationUnitScope unitScope = compilationUnitScope();
- unitScope.recordReference(enclosingType, typeName);
- ReferenceBinding memberType = enclosingType.getMemberType(typeName);
- if (memberType != null) {
- unitScope.recordTypeReference(memberType);
- if (enclosingReceiverType == null
- ? memberType.canBeSeenBy(getCurrentPackage())
- : memberType.canBeSeenBy(enclosingType, enclosingReceiverType))
- return memberType;
- return new ProblemReferenceBinding(typeName, memberType, ProblemReasons.NotVisible);
- }
- return null;
- }
-
- // Internal use only
- public MethodBinding findExactMethod(
- ReferenceBinding receiverType,
- char[] selector,
- TypeBinding[] argumentTypes,
- InvocationSite invocationSite) {
-
- CompilationUnitScope unitScope = compilationUnitScope();
- unitScope.recordTypeReferences(argumentTypes);
- MethodBinding exactMethod = (receiverType!=null) ?
- receiverType.getExactMethod(selector, argumentTypes, unitScope) :
- unitScope.referenceContext.compilationUnitBinding.getExactMethod(selector, argumentTypes, unitScope);
- if (exactMethod != null && !exactMethod.isBridge()) {
- // must find both methods for this case: <S extends A> void foo() {} and <N extends B> N foo() { return null; }
- // or find an inherited method when the exact match is to a bridge method
- // special treatment for Object.getClass() in 1.5 mode (substitute parameterized return type)
- if (exactMethod.canBeSeenBy(receiverType, invocationSite, this)) {
- return exactMethod;
- }
- }
- return null;
- }
-
- // Internal use only
- /* Answer the field binding that corresponds to fieldName.
- Start the lookup at the receiverType.
- InvocationSite implements
- isSuperAccess(); this is used to determine if the discovered field is visible.
- Only fields defined by the receiverType or its supertypes are answered;
- a field of an enclosing type will not be found using this API.
-
- If no visible field is discovered, null is answered.
- */
- public FieldBinding findField(TypeBinding receiverType, char[] fieldName, InvocationSite invocationSite, boolean needResolve) {
-
- CompilationUnitScope unitScope = compilationUnitScope();
- unitScope.recordTypeReference(receiverType);
-
- checkArrayField: {
- switch (receiverType.kind()) {
- case Binding.BASE_TYPE :
- return null;
- default:
- break checkArrayField;
- }
- }
-
- ReferenceBinding currentType = (ReferenceBinding) receiverType;
- if (!currentType.canBeSeenBy(this))
- return new ProblemFieldBinding(currentType, fieldName, ProblemReasons.ReceiverTypeNotVisible);
-
- FieldBinding field = currentType.getField(fieldName, needResolve);
- if (field != null) {
- if (invocationSite == null
- ? field.canBeSeenBy(getCurrentPackage())
- : field.canBeSeenBy(currentType, invocationSite, this))
- return field;
- 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
- while (keepLooking) {
- if (JavaScriptCore.IS_ECMASCRIPT4)
- {
- ((SourceTypeBinding) currentType).classScope.connectTypeHierarchy();
- }
- if ((currentType = currentType.superclass()) == null)
- break;
-
- unitScope.recordTypeReference(currentType);
- if ((field = currentType.getField(fieldName, needResolve)) != null) {
- keepLooking = false;
- if (field.canBeSeenBy(receiverType, invocationSite, this)) {
- if (visibleField == null)
- visibleField = field;
- else
- return new ProblemFieldBinding(visibleField /* closest match*/, visibleField.declaringClass, fieldName, ProblemReasons.Ambiguous);
- } else {
- if (notVisibleField == null)
- notVisibleField = field;
- }
- }
- }
-
- if (visibleField != null)
- return visibleField;
- if (notVisibleField != null) {
- return new ProblemFieldBinding(notVisibleField, currentType, fieldName, ProblemReasons.NotVisible);
- }
- return null;
- }
-
- // Internal use only
- public ReferenceBinding findMemberType(char[] typeName, ReferenceBinding enclosingType) {
- if ((enclosingType.tagBits & TagBits.HasNoMemberTypes) != 0)
- return null; // know it has no member types (nor inherited member types)
-
- ReferenceBinding enclosingSourceType = enclosingSourceType();
- PackageBinding currentPackage = getCurrentPackage();
- CompilationUnitScope unitScope = compilationUnitScope();
- unitScope.recordReference(enclosingType, typeName);
- ReferenceBinding memberType = enclosingType.getMemberType(typeName);
- if (memberType != null) {
- unitScope.recordTypeReference(memberType);
- if (enclosingSourceType == null
- ? memberType.canBeSeenBy(currentPackage)
- : memberType.canBeSeenBy(enclosingType, enclosingSourceType))
- return memberType;
- return new ProblemReferenceBinding(typeName, memberType, ProblemReasons.NotVisible);
- }
-
- // collect all superinterfaces of receiverType until the memberType is found in a supertype
- ReferenceBinding currentType = enclosingType;
- ReferenceBinding[] interfacesToVisit = null;
- int nextPosition = 0;
- ReferenceBinding visibleMemberType = null;
- boolean keepLooking = true;
- ReferenceBinding notVisible = null;
- // we could hold onto the not visible field for extra error reporting
- while (keepLooking) {
-
- ReferenceBinding sourceType = currentType;
- if (sourceType.isHierarchyBeingConnected())
- return null; // looking for an undefined member type in its own superclass ref
- ((SourceTypeBinding) sourceType).classScope.connectTypeHierarchy();
-
- if ((currentType = currentType.superclass()) == null)
- break;
-
- unitScope.recordReference(currentType, typeName);
- if ((memberType = currentType.getMemberType(typeName)) != null) {
- unitScope.recordTypeReference(memberType);
- keepLooking = false;
- if (enclosingSourceType == null
- ? memberType.canBeSeenBy(currentPackage)
- : memberType.canBeSeenBy(enclosingType, enclosingSourceType)) {
- if (visibleMemberType == null)
- visibleMemberType = memberType;
- else
- return new ProblemReferenceBinding(typeName, visibleMemberType, ProblemReasons.Ambiguous);
- } else {
- notVisible = memberType;
- }
- }
- }
- // walk all visible interfaces to find ambiguous references
- if (interfacesToVisit != null) {
- ProblemReferenceBinding ambiguous = null;
- done : for (int i = 0; i < nextPosition; i++) {
- ReferenceBinding anInterface = interfacesToVisit[i];
- unitScope.recordReference(anInterface, typeName);
- if ((memberType = anInterface.getMemberType(typeName)) != null) {
- unitScope.recordTypeReference(memberType);
- if (visibleMemberType == null) {
- visibleMemberType = memberType;
- } else {
- ambiguous = new ProblemReferenceBinding(typeName, visibleMemberType, ProblemReasons.Ambiguous);
- break done;
- }
- }
- }
- if (ambiguous != null)
- return ambiguous;
- }
- if (visibleMemberType != null)
- return visibleMemberType;
- if (notVisible != null)
- return new ProblemReferenceBinding(typeName, notVisible, ProblemReasons.NotVisible);
- return null;
- }
-
- // Internal use only - use findMethod()
- public MethodBinding findMethod(ReferenceBinding receiverType, char[] selector, TypeBinding[] argumentTypes, InvocationSite invocationSite) {
- ReferenceBinding currentType = receiverType;
- ObjectVector found = new ObjectVector(3);
- CompilationUnitScope unitScope = compilationUnitScope();
- unitScope.recordTypeReferences(argumentTypes);
-
- if (receiverType==null)
- {
- MethodBinding methodBinding = unitScope.referenceContext.compilationUnitBinding.getExactMethod(selector,argumentTypes, unitScope);
- if (methodBinding==null)
- methodBinding= new ProblemMethodBinding(selector, argumentTypes, ProblemReasons.NotFound);
- return methodBinding;
- }
-
- // superclass lookup
- long complianceLevel = compilerOptions().complianceLevel;
- boolean isCompliant14 = complianceLevel >= ClassFileConstants.JDK1_4;
- boolean isCompliant15 = complianceLevel >= ClassFileConstants.JDK1_5;
- ReferenceBinding classHierarchyStart = currentType;
- while (currentType != null) {
- unitScope.recordTypeReference(currentType);
- MethodBinding[] currentMethods = currentType.getMethods(selector);
- int currentLength = currentMethods.length;
- if (currentLength > 0) {
- if (isCompliant14 && (found.size > 0)) {
- nextMethod: for (int i = 0, l = currentLength; i < l; i++) { // currentLength can be modified inside the loop
- MethodBinding currentMethod = currentMethods[i];
- if (currentMethod == null) continue nextMethod;
-
- // if 1.4 compliant, must filter out redundant protected methods from superclasses
- // protected method need to be checked only - default access is already dealt with in #canBeSeen implementation
- // when checking that p.C -> q.B -> p.A cannot see default access members from A through B.
- // if ((currentMethod.modifiers & AccProtected) == 0) continue nextMethod;
- // BUT we can also ignore any overridden method since we already know the better match (fixes 80028)
- for (int j = 0, max = found.size; j < max; j++) {
- MethodBinding matchingMethod = (MethodBinding) found.elementAt(j);
- if (currentMethod.areParametersEqual(matchingMethod)) {
- if (isCompliant15) {
- if (matchingMethod.isBridge() && !currentMethod.isBridge())
- continue nextMethod; // keep inherited methods to find concrete method over a bridge method
- }
- currentLength--;
- currentMethods[i] = null;
- continue nextMethod;
- }
- }
- }
- }
-
- if (currentLength > 0) {
- // append currentMethods, filtering out null entries
- if (currentMethods.length == currentLength) {
- found.addAll(currentMethods);
- } else {
- for (int i = 0, max = currentMethods.length; i < max; i++) {
- MethodBinding currentMethod = currentMethods[i];
- if (currentMethod != null)
- found.add(currentMethod);
- }
- }
- }
- }
- currentType = currentType.superclass();
- }
-
- if (found.size==0 && (receiverType==null || receiverType instanceof CompilationUnitBinding))
- {
- Binding binding = getTypeOrPackage(selector, Binding.METHOD);
- if (binding instanceof MethodBinding)
- {
- ((MethodBinding) binding).ensureBindingsAreComplete();
- found.add(binding);
- }
- }
- // if found several candidates, then eliminate those not matching argument types
- int foundSize = found.size;
- MethodBinding[] candidates = null;
- int candidatesCount = 0;
- MethodBinding problemMethod = null;
- if (foundSize > 0) {
- // argument type compatibility check
- for (int i = 0; i < foundSize; i++) {
- MethodBinding methodBinding = (MethodBinding) found.elementAt(i);
- MethodBinding compatibleMethod = methodBinding;//computeCompatibleMethod(methodBinding, argumentTypes, invocationSite);
- if (compatibleMethod != null) {
- if (compatibleMethod.isValidBinding()) {
- if (foundSize == 1 && compatibleMethod.canBeSeenBy(receiverType, invocationSite, this)) {
- // return the single visible match now
- return compatibleMethod;
- }
- if (candidatesCount == 0)
- candidates = new MethodBinding[foundSize];
- candidates[candidatesCount++] = compatibleMethod;
- } else if (problemMethod == null) {
- problemMethod = compatibleMethod;
- }
- }
- }
- }
-
- // no match was found
- if (candidatesCount == 0) {
- // abstract classes may get a match in interfaces; for non abstract
- // classes, reduces secondary errors since missing interface method
- // error is already reported
- MethodBinding interfaceMethod =
- findDefaultAbstractMethod(receiverType, selector, argumentTypes, invocationSite, classHierarchyStart, found, null);
- if (interfaceMethod != null) return interfaceMethod;
- if (found.size == 0) return null;
- if (problemMethod != null) return problemMethod;
-
- // still no match; try to find a close match when the parameter
- // order is wrong or missing some parameters
-
-
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=69471
- // bad guesses are foo(), when argument types have been supplied
- // and foo(X, Y), when the argument types are (int, float, Y)
- // so answer the method with the most argType matches and least parameter type mismatches
- int bestArgMatches = -1;
- MethodBinding bestGuess = (MethodBinding) found.elementAt(0); // if no good match so just use the first one found
- int argLength = argumentTypes.length;
- foundSize = found.size;
- nextMethod : for (int i = 0; i < foundSize; i++) {
- MethodBinding methodBinding = (MethodBinding) found.elementAt(i);
- TypeBinding[] params = methodBinding.parameters;
- int paramLength = params.length;
- int argMatches = 0;
- next: for (int a = 0; a < argLength; a++) {
- TypeBinding arg = argumentTypes[a];
- for (int p = a == 0 ? 0 : a - 1; p < paramLength && p < a + 1; p++) { // look one slot before & after to see if the type matches
- if (params[p] == arg) {
- argMatches++;
- continue next;
- }
- }
- }
- if (argMatches < bestArgMatches)
- continue nextMethod;
- if (argMatches == bestArgMatches) {
- int diff1 = paramLength < argLength ? 2 * (argLength - paramLength) : paramLength - argLength;
- int bestLength = bestGuess.parameters.length;
- int diff2 = bestLength < argLength ? 2 * (argLength - bestLength) : bestLength - argLength;
- if (diff1 >= diff2)
- continue nextMethod;
- }
- bestArgMatches = argMatches;
- bestGuess = methodBinding;
- }
- return bestGuess;
-// return new ProblemMethodBinding(bestGuess, bestGuess.selector, argumentTypes, ProblemReasons.NotFound);
- }
-
- // tiebreak using visibility check
- int visiblesCount = 0;
-
- for (int i = 0; i < candidatesCount; i++) {
- MethodBinding methodBinding = candidates[i];
- if (methodBinding.canBeSeenBy(receiverType, invocationSite,
- this)) {
- if (visiblesCount != i) {
- candidates[i] = null;
- candidates[visiblesCount] = methodBinding;
- }
- visiblesCount++;
- }
-
- }
- if (visiblesCount == 1) {
- return candidates[0];
- }
- if (visiblesCount == 0) {
- MethodBinding interfaceMethod = findDefaultAbstractMethod(
- receiverType, selector, argumentTypes, invocationSite,
- classHierarchyStart, found, null);
- if (interfaceMethod != null)
- return interfaceMethod;
- return new ProblemMethodBinding(candidates[0],
- candidates[0].selector, candidates[0].parameters,
- ProblemReasons.NotVisible);
- }
-
- if (complianceLevel <= ClassFileConstants.JDK1_3) {
- ReferenceBinding declaringClass = candidates[0].declaringClass;
- return mostSpecificClassMethodBinding(candidates, visiblesCount, invocationSite);
- }
-
- MethodBinding mostSpecificMethod = mostSpecificMethodBinding(candidates, visiblesCount, argumentTypes, invocationSite, receiverType);
- return mostSpecificMethod;
- }
-
- // Internal use only
- public MethodBinding findMethodForArray(
- ArrayBinding receiverType,
- char[] selector,
- TypeBinding[] argumentTypes,
- InvocationSite invocationSite) {
-
- TypeBinding leafType = receiverType.leafComponentType();
- if (leafType instanceof ReferenceBinding) {
- if (!((ReferenceBinding) leafType).canBeSeenBy(this))
- return new ProblemMethodBinding(selector, Binding.NO_PARAMETERS, (ReferenceBinding)leafType, ProblemReasons.ReceiverTypeNotVisible);
- }
-
- ReferenceBinding object = getJavaLangObject();
- MethodBinding methodBinding = object.getExactMethod(selector, argumentTypes, null);
- if (methodBinding != null) {
- // handle the method clone() specially... cannot be protected or throw exceptions
- if (argumentTypes == Binding.NO_PARAMETERS) {
- switch (selector[0]) {
- case 'c':
- break;
- case 'g':
- break;
- }
- }
- if (methodBinding.canBeSeenBy(receiverType, invocationSite, this))
- return methodBinding;
- }
- methodBinding = findMethod(object, selector, argumentTypes, invocationSite);
- if (methodBinding == null)
- return new ProblemMethodBinding(selector, argumentTypes, ProblemReasons.NotFound);
- return methodBinding;
- }
-
- // Internal use only
- public Binding findBinding(
- char[] typeName,
- int mask,
- PackageBinding declarationPackage,
- PackageBinding invocationPackage, boolean searchEnvironment) {
-
- compilationUnitScope().recordReference(declarationPackage.compoundName, typeName);
- Binding typeBinding =
- (searchEnvironment) ? declarationPackage.getBinding(typeName,mask) :
- declarationPackage.getBinding0(typeName, mask);
- if (typeBinding == null)
- return null;
-
- if (typeBinding.isValidBinding()) {
- if (declarationPackage != invocationPackage && typeBinding instanceof ReferenceBinding
- && !((ReferenceBinding)typeBinding).canBeSeenBy(invocationPackage))
- return new ProblemReferenceBinding(typeName,(ReferenceBinding) typeBinding, ProblemReasons.NotVisible);
- }
- return typeBinding;
- }
-
- // Internal use only
- public ReferenceBinding findType(
- char[] typeName,
- PackageBinding declarationPackage,
- PackageBinding invocationPackage) {
-
- return (ReferenceBinding)findBinding(typeName, Binding.TYPE, declarationPackage, invocationPackage, true);
- }
-
- public LocalVariableBinding findVariable(char[] variable) {
-
- return null;
- }
-
- /* API
- *
- * Answer the binding that corresponds to the argument name.
- * flag is a mask of the following values VARIABLE (= FIELD or LOCAL), TYPE, PACKAGE.
- * Only bindings corresponding to the mask can be answered.
- *
- * For example, getBinding("foo", VARIABLE, site) will answer
- * the binding for the field or local named "foo" (or an error binding if none exists).
- * If a type named "foo" exists, it will not be detected (and an error binding will be answered)
- *
- * The VARIABLE mask has precedence over the TYPE mask.
- *
- * If the VARIABLE mask is not set, neither fields nor locals will be looked for.
- *
- * InvocationSite implements:
- * isSuperAccess(); this is used to determine if the discovered field is visible.
- *
- * Limitations: cannot request FIELD independently of LOCAL, or vice versa
- */
- public Binding getBinding(char[] name, int mask, InvocationSite invocationSite, boolean needResolve) {
- CompilationUnitScope unitScope = compilationUnitScope();
- LookupEnvironment env = unitScope.environment;
- try {
- env.missingClassFileLocation = invocationSite;
- Binding binding = null;
- FieldBinding problemField = null;
- if ((mask & Binding.VARIABLE) != 0) {
- boolean insideStaticContext = false;
- boolean insideConstructorCall = false;
-
- FieldBinding foundField = null;
- // can be a problem field which is answered if a valid field is not found
- ProblemFieldBinding foundInsideProblem = null;
- // inside Constructor call or inside static context
- Scope scope = this;
- int depth = 0;
- int foundDepth = 0;
- ReferenceBinding foundActualReceiverType = null;
- done : while (true) { // done when a COMPILATION_UNIT_SCOPE is found
- switch (scope.kind) {
- case METHOD_SCOPE :
- MethodScope methodScope = (MethodScope) scope;
- insideStaticContext |= methodScope.isStatic;
- insideConstructorCall |= methodScope.isConstructorCall;
-
- // Fall through... could duplicate the code below to save a cast - questionable optimization
- case BLOCK_SCOPE :
- LocalVariableBinding variableBinding = scope.findVariable(name);
- // looks in this scope only
- if (variableBinding != null) {
- if (foundField != null && foundField.isValidBinding())
- return new ProblemFieldBinding(
- foundField, // closest match
- foundField.declaringClass,
- name,
- ProblemReasons.InheritedNameHidesEnclosingName);
- if (depth > 0)
- invocationSite.setDepth(depth);
- return variableBinding;
- }
- break;
- case CLASS_SCOPE :
- ClassScope classScope = (ClassScope) scope;
- ReferenceBinding receiverType = classScope.enclosingReceiverType();
- FieldBinding fieldBinding = classScope.findField(receiverType, name, invocationSite, needResolve);
- // Use next line instead if willing to enable protected access accross inner types
- // FieldBinding fieldBinding = findField(enclosingType, name, invocationSite);
-
- if (fieldBinding != null) { // skip it if we did not find anything
- if (fieldBinding.problemId() == ProblemReasons.Ambiguous) {
- if (foundField == null || foundField.problemId() == ProblemReasons.NotVisible)
- // supercedes any potential InheritedNameHidesEnclosingName problem
- return fieldBinding;
- // make the user qualify the field, likely wants the first inherited field (javac generates an ambiguous error instead)
- return new ProblemFieldBinding(
- foundField, // closest match
- foundField.declaringClass,
- name,
- ProblemReasons.InheritedNameHidesEnclosingName);
- }
-
- ProblemFieldBinding insideProblem = null;
- if (fieldBinding.isValidBinding()) {
- if (!fieldBinding.isStatic()) {
- if (insideConstructorCall) {
- insideProblem =
- new ProblemFieldBinding(
- fieldBinding, // closest match
- fieldBinding.declaringClass,
- name,
- ProblemReasons.NonStaticReferenceInConstructorInvocation);
- } else if (insideStaticContext) {
- insideProblem =
- new ProblemFieldBinding(
- fieldBinding, // closest match
- fieldBinding.declaringClass,
- name,
- ProblemReasons.NonStaticReferenceInStaticContext);
- }
- }
- if (receiverType == fieldBinding.declaringClass || compilerOptions().complianceLevel >= ClassFileConstants.JDK1_4) {
- // found a valid field in the 'immediate' scope (ie. not inherited)
- // OR in 1.4 mode (inherited shadows enclosing)
- if (foundField == null) {
- if (depth > 0){
- invocationSite.setDepth(depth);
- invocationSite.setActualReceiverType(receiverType);
- }
- // return the fieldBinding if it is not declared in a superclass of the scope's binding (that is, inherited)
- return insideProblem == null ? fieldBinding : insideProblem;
- }
- if (foundField.isValidBinding())
- // if a valid field was found, complain when another is found in an 'immediate' enclosing type (that is, not inherited)
- if (foundField.declaringClass != fieldBinding.declaringClass)
- // ie. have we found the same field - do not trust field identity yet
- return new ProblemFieldBinding(
- foundField, // closest match
- foundField.declaringClass,
- name,
- ProblemReasons.InheritedNameHidesEnclosingName);
- }
- }
-
- if (foundField == null || (foundField.problemId() == ProblemReasons.NotVisible && fieldBinding.problemId() != ProblemReasons.NotVisible)) {
- // only remember the fieldBinding if its the first one found or the previous one was not visible & fieldBinding is...
- foundDepth = depth;
- foundActualReceiverType = receiverType;
- foundInsideProblem = insideProblem;
- foundField = fieldBinding;
- }
- }
-
- depth++;
- insideStaticContext |= receiverType.isStatic();
- // 1EX5I8Z - accessing outer fields within a constructor call is permitted
- // in order to do so, we change the flag as we exit from the type, not the method
- // itself, because the class scope is used to retrieve the fields.
- MethodScope enclosingMethodScope = scope.methodScope();
- insideConstructorCall = enclosingMethodScope == null ? false : enclosingMethodScope.isConstructorCall;
- break;
- case WITH_SCOPE :
- WithScope withScope = (WithScope) scope;
- TypeBinding withType = withScope.referenceContext;
- fieldBinding = withScope.findField(withType, name, invocationSite, needResolve);
- // Use next line instead if willing to enable protected access accross inner types
- // FieldBinding fieldBinding = findField(enclosingType, name, invocationSite);
-
- if (fieldBinding != null) { // skip it if we did not find anything
- if (fieldBinding.isValidBinding()) {
- return fieldBinding;
- }
- }
- break;
- case COMPILATION_UNIT_SCOPE :
- if ( (mask & (Binding.FIELD|Binding.VARIABLE)) >0)
- {
- variableBinding = scope.findVariable(name);
- // looks in this scope only
- if (variableBinding != null) {
- if (foundField != null && foundField.isValidBinding())
- return new ProblemFieldBinding(
- foundField, // closest match
- foundField.declaringClass,
- name,
- ProblemReasons.InheritedNameHidesEnclosingName);
- if (depth > 0)
- invocationSite.setDepth(depth);
- return variableBinding;
- }
-
- if(unitScope.classScope()!=null) {
- //ReferenceBinding bind = env.getType(new char[][]{unitScope.superTypeName});
- //if(bind==null) break done;
- foundField = (unitScope.classScope()).findField(unitScope.superBinding, name, invocationSite, true);
- if(foundField!=null && foundField.isValidBinding()) {
-
- return foundField;
- }
- }
-
-
-
- }else if ( (mask & (Binding.METHOD)) >0){
- MethodBinding methodBinding = (unitScope.classScope()).findMethod(unitScope.superBinding, name, new TypeBinding[0], invocationSite);
- if(methodBinding!=null && methodBinding.isValidBinding()) return methodBinding;
-
- }
-
- break done;
- }
- scope = scope.parent;
- }
-
- if (foundInsideProblem != null)
- return foundInsideProblem;
- if (foundField != null) {
- if (foundField.isValidBinding()) {
- if (foundDepth > 0) {
- invocationSite.setDepth(foundDepth);
- invocationSite.setActualReceiverType(foundActualReceiverType);
- }
- return foundField;
- }
- problemField = foundField;
- foundField = null;
- }
- }
-
- if ( (mask&Binding.METHOD)!=0)
- {
-
- Scope scope = this;
-
- done : while (true) { // done when a COMPILATION_UNIT_SCOPE is found
- switch (scope.kind) {
- case METHOD_SCOPE :
- MethodScope methodScope = (MethodScope) scope;
- binding = methodScope.findMethod(name, Binding.NO_PARAMETERS,true);
- if (binding!=null)
- return binding;
- break;
- case WITH_SCOPE :
- WithScope withScope = (WithScope) scope;
- ReferenceBinding withType = withScope.referenceContext;
- // retrieve an exact visible match (if possible)
- // compilationUnitScope().recordTypeReference(receiverType); not needed since receiver is the source type
- MethodBinding methBinding = withScope.findExactMethod(withType, name, Binding.NO_PARAMETERS, invocationSite);
- if (methBinding == null)
- methBinding = withScope.findMethod(withType,name, Binding.NO_PARAMETERS, invocationSite);
- if (methBinding != null) { // skip it if we did not find anything
- if (methBinding.isValidBinding()) {
- return methBinding;
- }
- }
- break;
- case CLASS_SCOPE :
- ClassScope classScope = (ClassScope) scope;
- ReferenceBinding receiverType = classScope.enclosingReceiverType();
- break;
- case COMPILATION_UNIT_SCOPE :
- CompilationUnitScope compilationUnitScope = (CompilationUnitScope) scope;
- CompilationUnitBinding compilationUnitBinding = compilationUnitScope.enclosingCompilationUnit();
- receiverType = compilationUnitBinding;
- MethodBinding methodBinding =
- compilationUnitScope.findExactMethod(receiverType, name, Binding.NO_PARAMETERS, invocationSite);
- if (methodBinding != null) { // skip it if we did not find anything
- return methodBinding;
- }
-
- break done;
- }
- scope = scope.parent;
- }
-
- }
- // We did not find a local or instance variable.
- if ((mask & Binding.TYPE|Binding.VARIABLE|Binding.METHOD) != 0) {
- if ((mask & Binding.TYPE) != 0 && (binding = getBaseType(name)) != null)
- return binding;
- binding = getTypeOrPackage(name, mask);// (mask & Binding.PACKAGE) == 0 ? Binding.TYPE : Binding.TYPE | Binding.PACKAGE);
- if (binding.isValidBinding() || mask == Binding.TYPE)
- return binding;
- // answer the problem type binding if we are only looking for a type
- } else if ((mask & Binding.PACKAGE) != 0) {
- unitScope.recordSimpleReference(name);
- if ((binding = env.getTopLevelPackage(name)) != null)
- return binding;
- }
- if (problemField != null) return problemField;
- if (binding != null && binding.problemId() != ProblemReasons.NotFound)
- return binding; // answer the better problem binding
- return new ProblemBinding(name, enclosingTypeBinding(), ProblemReasons.NotFound);
- } catch (AbortCompilation e) {
- e.updateContext(invocationSite, referenceCompilationUnit().compilationResult);
- throw e;
- } finally {
- env.missingClassFileLocation = null;
- }
- }
-
- /* API
- *
- * Answer the binding that corresponds to the argument name.
- * flag is a mask of the following values VARIABLE (= FIELD or LOCAL), TYPE, PACKAGE.
- * Only bindings corresponding to the mask can be answered.
- *
- * For example, getBinding("foo", VARIABLE, site) will answer
- * the binding for the field or local named "foo" (or an error binding if none exists).
- * If a type named "foo" exists, it will not be detected (and an error binding will be answered)
- *
- * The VARIABLE mask has precedence over the TYPE mask.
- *
- * If the VARIABLE mask is not set, neither fields nor locals will be looked for.
- *
- * InvocationSite implements:
- * isSuperAccess(); this is used to determine if the discovered field is visible.
- *
- * Limitations: cannot request FIELD independently of LOCAL, or vice versa
- */
- public Binding getLocalBinding(char[] name, int mask, InvocationSite invocationSite, boolean needResolve) {
- CompilationUnitScope unitScope = compilationUnitScope();
- try {
- Binding binding = null;
- FieldBinding problemField = null;
- if ((mask & Binding.VARIABLE) != 0) {
- boolean insideStaticContext = false;
- boolean insideConstructorCall = false;
-
- FieldBinding foundField = null;
- // can be a problem field which is answered if a valid field is not found
- ProblemFieldBinding foundInsideProblem = null;
- // inside Constructor call or inside static context
- Scope scope = this;
- int depth = 0;
- int foundDepth = 0;
- ReferenceBinding foundActualReceiverType = null;
- done : while (true) { // done when a COMPILATION_UNIT_SCOPE is found
- switch (scope.kind) {
- case METHOD_SCOPE :
- MethodScope methodScope = (MethodScope) scope;
- insideStaticContext |= methodScope.isStatic;
- insideConstructorCall |= methodScope.isConstructorCall;
-
- // Fall through... could duplicate the code below to save a cast - questionable optimization
- case BLOCK_SCOPE :
- LocalVariableBinding variableBinding = scope.findVariable(name);
- // looks in this scope only
- if (variableBinding != null) {
- if (foundField != null && foundField.isValidBinding())
- return new ProblemFieldBinding(
- foundField, // closest match
- foundField.declaringClass,
- name,
- ProblemReasons.InheritedNameHidesEnclosingName);
- if (depth > 0)
- invocationSite.setDepth(depth);
- return variableBinding;
- }
- break;
- case CLASS_SCOPE :
- ClassScope classScope = (ClassScope) scope;
- ReferenceBinding receiverType = classScope.enclosingReceiverType();
- FieldBinding fieldBinding = classScope.findField(receiverType, name, invocationSite, needResolve);
- // Use next line instead if willing to enable protected access accross inner types
- // FieldBinding fieldBinding = findField(enclosingType, name, invocationSite);
-
- if (fieldBinding != null) { // skip it if we did not find anything
- if (fieldBinding.problemId() == ProblemReasons.Ambiguous) {
- if (foundField == null || foundField.problemId() == ProblemReasons.NotVisible)
- // supercedes any potential InheritedNameHidesEnclosingName problem
- return fieldBinding;
- // make the user qualify the field, likely wants the first inherited field (javac generates an ambiguous error instead)
- return new ProblemFieldBinding(
- foundField, // closest match
- foundField.declaringClass,
- name,
- ProblemReasons.InheritedNameHidesEnclosingName);
- }
-
- ProblemFieldBinding insideProblem = null;
- if (fieldBinding.isValidBinding()) {
- if (!fieldBinding.isStatic()) {
- if (insideConstructorCall) {
- insideProblem =
- new ProblemFieldBinding(
- fieldBinding, // closest match
- fieldBinding.declaringClass,
- name,
- ProblemReasons.NonStaticReferenceInConstructorInvocation);
- } else if (insideStaticContext) {
- insideProblem =
- new ProblemFieldBinding(
- fieldBinding, // closest match
- fieldBinding.declaringClass,
- name,
- ProblemReasons.NonStaticReferenceInStaticContext);
- }
- }
- if (receiverType == fieldBinding.declaringClass || compilerOptions().complianceLevel >= ClassFileConstants.JDK1_4) {
- // found a valid field in the 'immediate' scope (ie. not inherited)
- // OR in 1.4 mode (inherited shadows enclosing)
- if (foundField == null) {
- if (depth > 0){
- invocationSite.setDepth(depth);
- invocationSite.setActualReceiverType(receiverType);
- }
- // return the fieldBinding if it is not declared in a superclass of the scope's binding (that is, inherited)
- return insideProblem == null ? fieldBinding : insideProblem;
- }
- if (foundField.isValidBinding())
- // if a valid field was found, complain when another is found in an 'immediate' enclosing type (that is, not inherited)
- if (foundField.declaringClass != fieldBinding.declaringClass)
- // ie. have we found the same field - do not trust field identity yet
- return new ProblemFieldBinding(
- foundField, // closest match
- foundField.declaringClass,
- name,
- ProblemReasons.InheritedNameHidesEnclosingName);
- }
- }
-
- if (foundField == null || (foundField.problemId() == ProblemReasons.NotVisible && fieldBinding.problemId() != ProblemReasons.NotVisible)) {
- // only remember the fieldBinding if its the first one found or the previous one was not visible & fieldBinding is...
- foundDepth = depth;
- foundActualReceiverType = receiverType;
- foundInsideProblem = insideProblem;
- foundField = fieldBinding;
- }
- }
- depth++;
- insideStaticContext |= receiverType.isStatic();
- // 1EX5I8Z - accessing outer fields within a constructor call is permitted
- // in order to do so, we change the flag as we exit from the type, not the method
- // itself, because the class scope is used to retrieve the fields.
- MethodScope enclosingMethodScope = scope.methodScope();
- insideConstructorCall = enclosingMethodScope == null ? false : enclosingMethodScope.isConstructorCall;
- break;
- case WITH_SCOPE :
- {
- WithScope withScope = (WithScope) scope;
- TypeBinding withType = withScope.referenceContext;
- FieldBinding withBinding = withScope.findField(withType, name, invocationSite, needResolve);
- // Use next line instead if willing to enable protected access accross inner types
- // FieldBinding fieldBinding = findField(enclosingType, name, invocationSite);
-
- if (withBinding != null) { // skip it if we did not find anything
- if (withBinding.isValidBinding()) {
- return withBinding;
- }
- }
- }
- break;
- case COMPILATION_UNIT_SCOPE :
- if ( (mask & (Binding.FIELD|Binding.VARIABLE)) >0)
- {
- variableBinding = scope.findVariable(name);
- // looks in this scope only
- if (variableBinding != null) {
- if (foundField != null && foundField.isValidBinding())
- return new ProblemFieldBinding(
- foundField, // closest match
- foundField.declaringClass,
- name,
- ProblemReasons.InheritedNameHidesEnclosingName);
- if (depth > 0)
- invocationSite.setDepth(depth);
- return variableBinding;
- }
-
- if(unitScope.classScope()!=null) {
- //ReferenceBinding bind = env.getType(new char[][]{unitScope.superTypeName});
- //if(bind==null) break done;
- foundField = (unitScope.classScope()).findField(unitScope.superBinding, name, invocationSite, true);
- if(foundField!=null && foundField.isValidBinding()) {
-
- return foundField;
- }
- }
-
-
-
- }else if ( (mask & (Binding.METHOD)) >0){
- MethodBinding methodBinding = (unitScope.classScope()).findMethod(unitScope.superBinding, name, new TypeBinding[0], invocationSite);
- if(methodBinding!=null && methodBinding.isValidBinding()) return methodBinding;
-
- }
-
- break done;
- }
- scope = scope.parent;
- }
-
- if (foundInsideProblem != null)
- return foundInsideProblem;
- if (foundField != null) {
- if (foundField.isValidBinding()) {
- if (foundDepth > 0) {
- invocationSite.setDepth(foundDepth);
- invocationSite.setActualReceiverType(foundActualReceiverType);
- }
- return foundField;
- }
- problemField = foundField;
- foundField = null;
- }
-
- }
-
- if ( (mask&Binding.METHOD)!=0)
- {
- MethodBinding methodBinding = findMethod(null, name, Binding.NO_PARAMETERS, invocationSite);
- if (methodBinding!=null && methodBinding.isValidBinding())
- return methodBinding;
- }
-
- if (problemField != null) return problemField;
- if (binding != null && binding.problemId() != ProblemReasons.NotFound)
- return binding; // answer the better problem binding
- return new ProblemBinding(name, enclosingTypeBinding(), ProblemReasons.NotFound);
- } catch (AbortCompilation e) {
- e.updateContext(invocationSite, referenceCompilationUnit().compilationResult);
- throw e;
- } finally {
- }
- }
-
- /**
- * <p><b>NOTE:</b> This function does not validate the given argument types because any number of arguments
- * can be passed to any JavaScript function or constructor.</p>
- *
- * @param receiverType
- * @param argumentTypes
- * @param invocationSite
- * @return The constructor for the given receiver type or a {@link ProblemMethodBinding} if the
- * constructor is not visible.
- */
- public MethodBinding getConstructor(ReferenceBinding receiverType, TypeBinding[] argumentTypes, InvocationSite invocationSite) {
- CompilationUnitScope unitScope = compilationUnitScope();
- LookupEnvironment env = unitScope.environment;
- try {
- env.missingClassFileLocation = invocationSite;
- unitScope.recordTypeReference(receiverType);
- unitScope.recordTypeReferences(argumentTypes);
- MethodBinding methodBinding = receiverType.getExactConstructor(argumentTypes);
- if (methodBinding != null && methodBinding.canBeSeenBy(invocationSite, this)) {
- return methodBinding;
- }
-
- //get the methods
- MethodBinding[] methods = receiverType.getMethods(receiverType.sourceName);
- 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 " +
- new String(receiverType.sourceName) + ". Using the first match.");
- }
-
- //should only ever be one constructor so use the first one in the list
- constructor = methods[0];
- }
-
- //if can't be seen return problem binding
- if(!constructor.canBeSeenBy(invocationSite, this)) {
- constructor = new ProblemMethodBinding(
- methods[0],
- methods[0].selector,
- methods[0].parameters,
- ProblemReasons.NotVisible);
- }
-
- return constructor;
- } catch (AbortCompilation e) {
- e.updateContext(invocationSite, referenceCompilationUnit().compilationResult);
- throw e;
- } finally {
- env.missingClassFileLocation = null;
- }
- }
-
- public final PackageBinding getCurrentPackage() {
- Scope scope, unitScope = this;
- while ((scope = unitScope.parent) != null)
- unitScope = scope;
- return ((CompilationUnitScope) unitScope).getDefaultPackage();
- }
-
- /**
- * Returns the modifiers of the innermost enclosing declaration.
- * @return modifiers
- */
- public int getDeclarationModifiers(){
- switch(this.kind){
- case Scope.BLOCK_SCOPE :
- case Scope.METHOD_SCOPE :
- MethodScope methodScope = methodScope();
- if (!methodScope.isInsideInitializer()){
- // check method modifiers to see if deprecated
- MethodBinding context = ((AbstractMethodDeclaration)methodScope.referenceContext).binding;
- if (context != null)
- return context.modifiers;
- } else {
- SourceTypeBinding type = ((BlockScope) this).referenceType().binding;
-
- // inside field declaration ? check field modifier to see if deprecated
- if (methodScope.initializedField != null)
- return methodScope.initializedField.modifiers;
- if (type != null)
- return type.modifiers;
- }
- break;
- case Scope.CLASS_SCOPE :
- ReferenceBinding context = ((ClassScope)this).referenceType().binding;
- if (context != null)
- return context.modifiers;
- break;
- }
- return -1;
- }
-
- public FieldBinding getField(TypeBinding receiverType, char[] fieldName, InvocationSite invocationSite) {
- LookupEnvironment env = environment();
- try {
- env.missingClassFileLocation = invocationSite;
- FieldBinding field = findField(receiverType, fieldName, invocationSite, true /*resolve*/);
- if (field != null) return field;
-
- return new ProblemFieldBinding(
- receiverType instanceof ReferenceBinding ? (ReferenceBinding) receiverType : null,
- fieldName,
- ProblemReasons.NotFound);
- } catch (AbortCompilation e) {
- e.updateContext(invocationSite, referenceCompilationUnit().compilationResult);
- throw e;
- } finally {
- env.missingClassFileLocation = null;
- }
- }
-
- public Binding getFieldOrMethod( TypeBinding receiverType, char[] fieldName, InvocationSite invocationSite ) {
- LookupEnvironment env = environment();
- try {
- env.missingClassFileLocation = invocationSite;
- //first look for field
- FieldBinding field = findField(receiverType, fieldName, invocationSite, true /*resolve*/);
- 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 );
- if( method != null )
- {
- if (!method.isValidBinding())
- {
- if (method.problemId()!=ProblemReasons.NotFound)
- return method;
- }
- else
- return method;
- }
-
- return new ProblemFieldBinding(
- receiverType instanceof ReferenceBinding ? (ReferenceBinding) receiverType : null,
- fieldName,
- ProblemReasons.NotFound);
- } catch (AbortCompilation e) {
- e.updateContext(invocationSite, referenceCompilationUnit().compilationResult);
- throw e;
- } finally {
- env.missingClassFileLocation = null;
- }
- }
-
- /* API
- *
- * Answer the method binding that corresponds to selector, argumentTypes.
- * Start the lookup at the enclosing type of the receiver.
- * InvocationSite implements
- * isSuperAccess(); this is used to determine if the discovered method is visible.
- * setDepth(int); this is used to record the depth of the discovered method
- * relative to the enclosing type of the receiver. (If the method is defined
- * in the enclosing type of the receiver, the depth is 0; in the next enclosing
- * type, the depth is 1; and so on
- *
- * If no visible method is discovered, an error binding is answered.
- */
- public MethodBinding getImplicitMethod(char[] selector, TypeBinding[] argumentTypes, InvocationSite invocationSite) {
-
- boolean insideStaticContext = false;
- boolean insideConstructorCall = false;
- MethodBinding foundMethod = null;
- MethodBinding foundProblem = null;
- boolean foundProblemVisible = false;
- Scope scope = this;
- int depth = 0;
- // in 1.4 mode (inherited visible shadows enclosing)
- CompilerOptions options;
- boolean inheritedHasPrecedence = (options = compilerOptions()).complianceLevel >= ClassFileConstants.JDK1_4;
-
- done : while (true) { // done when a COMPILATION_UNIT_SCOPE is found
- switch (scope.kind) {
- case METHOD_SCOPE :
- MethodScope methodScope = (MethodScope) scope;
- insideStaticContext |= methodScope.isStatic;
- insideConstructorCall |= methodScope.isConstructorCall;
- MethodBinding binding = methodScope.findMethod(selector,argumentTypes,true);
- if (binding!=null)
- return binding;
- LocalVariableBinding variable = methodScope.findVariable(selector);
- if (variable!=null)
- {
-
- }
- break;
- case WITH_SCOPE :
- WithScope withScope = (WithScope) scope;
- ReferenceBinding withType = withScope.referenceContext;
- // retrieve an exact visible match (if possible)
- // compilationUnitScope().recordTypeReference(receiverType); not needed since receiver is the source type
- MethodBinding methBinding = withScope.findExactMethod(withType, selector, argumentTypes, invocationSite);
- if (methBinding == null)
- methBinding = withScope.findMethod(withType, selector, argumentTypes, invocationSite);
- if (methBinding != null) { // skip it if we did not find anything
- if (methBinding.isValidBinding()) {
- return methBinding;
- }
- }
- break;
- case CLASS_SCOPE :
- ClassScope classScope = (ClassScope) scope;
- ReferenceBinding receiverType = classScope.enclosingReceiverType();
- // retrieve an exact visible match (if possible)
- // compilationUnitScope().recordTypeReference(receiverType); not needed since receiver is the source type
- MethodBinding methodBinding = classScope.findExactMethod(receiverType, selector, argumentTypes, invocationSite);
- if (methodBinding == null)
- methodBinding = classScope.findMethod(receiverType, selector, argumentTypes, invocationSite);
- if (methodBinding != null) { // skip it if we did not find anything
- if (foundMethod == null) {
- if (methodBinding.isValidBinding()) {
- if (!methodBinding.isStatic() && (insideConstructorCall || insideStaticContext)) {
- if (foundProblem != null && foundProblem.problemId() != ProblemReasons.NotVisible)
- return foundProblem; // takes precedence
- return new ProblemMethodBinding(
- methodBinding, // closest match
- methodBinding.selector,
- methodBinding.parameters,
- insideConstructorCall
- ? ProblemReasons.NonStaticReferenceInConstructorInvocation
- : ProblemReasons.NonStaticReferenceInStaticContext);
- }
- if (inheritedHasPrecedence
- || receiverType == methodBinding.declaringClass
- || (receiverType.getMethods(selector)) != Binding.NO_METHODS) {
- // found a valid method in the 'immediate' scope (ie. not inherited)
- // OR in 1.4 mode (inherited visible shadows enclosing)
- // OR the receiverType implemented a method with the correct name
- // return the methodBinding if it is not declared in a superclass of the scope's binding (that is, inherited)
- if (foundProblemVisible) {
- return foundProblem;
- }
- if (depth > 0) {
- invocationSite.setDepth(depth);
- invocationSite.setActualReceiverType(receiverType);
- }
- return methodBinding;
- }
-
- if (foundProblem == null || foundProblem.problemId() == ProblemReasons.NotVisible) {
- if (foundProblem != null) foundProblem = null;
- // only remember the methodBinding if its the first one found
- // remember that private methods are visible if defined directly by an enclosing class
- if (depth > 0) {
- invocationSite.setDepth(depth);
- invocationSite.setActualReceiverType(receiverType);
- }
- foundMethod = methodBinding;
- }
- } else { // methodBinding is a problem method
- if (methodBinding.problemId() != ProblemReasons.NotVisible && methodBinding.problemId() != ProblemReasons.NotFound)
- return methodBinding; // return the error now
- if (foundProblem == null) {
- foundProblem = methodBinding; // hold onto the first not visible/found error and keep the second not found if first is not visible
- }
- if (! foundProblemVisible && methodBinding.problemId() == ProblemReasons.NotFound) {
- MethodBinding closestMatch = ((ProblemMethodBinding) methodBinding).closestMatch;
- if (closestMatch != null && closestMatch.canBeSeenBy(receiverType, invocationSite, this)) {
- foundProblem = methodBinding; // hold onto the first not visible/found error and keep the second not found if first is not visible
- foundProblemVisible = true;
- }
- }
- }
- } else { // found a valid method so check to see if this is a hiding case
- if (methodBinding.problemId() == ProblemReasons.Ambiguous
- || (foundMethod.declaringClass != methodBinding.declaringClass
- && (receiverType == methodBinding.declaringClass || receiverType.getMethods(selector) != Binding.NO_METHODS)))
- // ambiguous case -> must qualify the method (javac generates an ambiguous error instead)
- // otherwise if a method was found, complain when another is found in an 'immediate' enclosing type (that is, not inherited)
- // NOTE: Unlike fields, a non visible method hides a visible method
- return new ProblemMethodBinding(
- methodBinding, // closest match
- selector,
- argumentTypes,
- ProblemReasons.InheritedNameHidesEnclosingName);
- }
- }
-
- depth++;
- insideStaticContext |= receiverType.isStatic();
- // 1EX5I8Z - accessing outer fields within a constructor call is permitted
- // in order to do so, we change the flag as we exit from the type, not the method
- // itself, because the class scope is used to retrieve the fields.
- MethodScope enclosingMethodScope = scope.methodScope();
- insideConstructorCall = enclosingMethodScope == null ? false : enclosingMethodScope.isConstructorCall;
- break;
- case COMPILATION_UNIT_SCOPE :
- CompilationUnitScope compilationUnitScope = (CompilationUnitScope) scope;
- CompilationUnitBinding compilationUnitBinding = compilationUnitScope.enclosingCompilationUnit();
- receiverType = compilationUnitBinding;
- methodBinding =
- (foundMethod == null)
- ? compilationUnitScope.findExactMethod(receiverType, selector, argumentTypes, invocationSite)
- : compilationUnitScope.findExactMethod(receiverType, foundMethod.selector, foundMethod.parameters, invocationSite);
- if (methodBinding == null)
- methodBinding = compilationUnitScope.findMethod(receiverType, selector, argumentTypes, invocationSite);
- if (methodBinding == null)
- methodBinding = compilationUnitScope.findMethod(selector, argumentTypes,true);
- if (methodBinding != null) { // skip it if we did not find anything
- if (methodBinding.problemId() == ProblemReasons.Ambiguous) {
- if (foundMethod == null || foundMethod.problemId() == ProblemReasons.NotVisible) {
- // supercedes any potential InheritedNameHidesEnclosingName problem
- return methodBinding;
- }
- // make the user qualify the method, likely wants the first inherited method (javac generates an ambiguous error instead)
- return new ProblemMethodBinding(
- methodBinding, // closest match
- selector,
- argumentTypes,
- ProblemReasons.InheritedNameHidesEnclosingName);
- }
- MethodBinding fuzzyProblem = null;
- MethodBinding insideProblem = null;
-
- if (foundMethod == null) {
- if (receiverType == methodBinding.declaringClass
- || (receiverType.getMethods(selector)) != Binding.NO_METHODS
- || ((foundProblem == null || foundProblem.problemId() != ProblemReasons.NotVisible) && compilerOptions().complianceLevel >= ClassFileConstants.JDK1_4)) {
- // found a valid method in the 'immediate' scope (ie. not inherited)
- // OR the receiverType implemented a method with the correct name
- // OR in 1.4 mode (inherited visible shadows enclosing)
- if (depth > 0) {
- invocationSite.setDepth(depth);
- invocationSite.setActualReceiverType(receiverType);
- }
- // return the methodBinding if it is not declared in a superclass of the scope's binding (that is, inherited)
- if (foundProblem != null && foundProblem.problemId() != ProblemReasons.NotVisible)
- return foundProblem;
- if (insideProblem != null)
- return insideProblem;
- return methodBinding;
- }
- }
-
- if (foundMethod == null || (foundMethod.problemId() == ProblemReasons.NotVisible && methodBinding.problemId() != ProblemReasons.NotVisible)) {
- // only remember the methodBinding if its the first one found or the previous one was not visible & methodBinding is...
- // remember that private methods are visible if defined directly by an enclosing class
- if (depth > 0) {
- invocationSite.setDepth(depth);
- invocationSite.setActualReceiverType(receiverType);
- }
- foundProblem = fuzzyProblem;
- foundProblem = insideProblem;
- if (fuzzyProblem == null)
- foundMethod = methodBinding; // only keep it if no error was found
- }
- }
- depth++;
- insideStaticContext |= receiverType.isStatic();
-
- break done;
- }
- scope = scope.parent;
- }
-
- if (insideStaticContext && options.sourceLevel >= ClassFileConstants.JDK1_5) {
- if (foundProblem != null) {
- if (foundProblem.declaringClass != null && foundProblem.declaringClass.id == TypeIds.T_JavaLangObject)
- return foundProblem; // static imports lose to methods from Object
- if (foundProblem.problemId() == ProblemReasons.NotFound && foundProblemVisible) {
- return foundProblem; // visible method selectors take precedence
- }
- }
- }
-
- if (foundMethod != null) {
- invocationSite.setActualReceiverType(foundMethod.declaringClass);
- return foundMethod;
- }
- if (foundProblem != null)
- return foundProblem;
-
- return new ProblemMethodBinding(selector, argumentTypes, ProblemReasons.NotFound);
- }
-
- public final ReferenceBinding getJavaLangAssertionError() {
- CompilationUnitScope unitScope = compilationUnitScope();
- unitScope.recordQualifiedReference(JAVA_LANG_ASSERTIONERROR);
- return unitScope.environment.getResolvedType(JAVA_LANG_ASSERTIONERROR, this);
- }
-
- public final ReferenceBinding getJavaLangClass() {
- CompilationUnitScope unitScope = compilationUnitScope();
- unitScope.recordQualifiedReference(JAVA_LANG_CLASS);
- return unitScope.environment.getResolvedType(JAVA_LANG_CLASS, this);
- }
-
- public final ReferenceBinding getJavaLangIterable() {
- CompilationUnitScope unitScope = compilationUnitScope();
- unitScope.recordQualifiedReference(JAVA_LANG_ITERABLE);
- return unitScope.environment.getResolvedType(JAVA_LANG_ITERABLE, this);
- }
- public final ReferenceBinding getJavaLangObject() {
- CompilationUnitScope unitScope = compilationUnitScope();
- unitScope.recordQualifiedReference(JAVA_LANG_OBJECT);
- return unitScope.environment.getResolvedType(JAVA_LANG_OBJECT, this);
- }
-
- public final ReferenceBinding getJavaLangArray() {
- compilationUnitScope().recordQualifiedReference(ARRAY);
- return environment().getResolvedType(ARRAY, this);
- }
-
- public final ReferenceBinding getJavaLangString() {
- compilationUnitScope().recordQualifiedReference(JAVA_LANG_STRING);
- return environment().getResolvedType(JAVA_LANG_STRING, this);
- }
-
- public final ReferenceBinding getJavaLangNumber() {
- compilationUnitScope().recordQualifiedReference(NUMBER);
- return environment().getResolvedType(NUMBER, this);
- }
-
- public final ReferenceBinding getJavaLangFunction() {
- compilationUnitScope().recordQualifiedReference(FUNCTION);
- return environment().getResolvedType(FUNCTION, this);
- }
-
- public final ReferenceBinding getJavaLangBoolean() {
- compilationUnitScope().recordQualifiedReference(BOOLEAN_OBJECT);
- return environment().getResolvedType(BOOLEAN_OBJECT, this);
- }
-
-
- public final ReferenceBinding getJavaLangThrowable() {
- CompilationUnitScope unitScope = compilationUnitScope();
- unitScope.recordQualifiedReference(JAVA_LANG_THROWABLE);
- return unitScope.environment.getResolvedType(JAVA_LANG_THROWABLE, this);
- }
-
- public final ReferenceBinding getJavaLangError() {
- CompilationUnitScope unitScope = compilationUnitScope();
- unitScope.recordQualifiedReference(ERROR);
- return unitScope.environment.getResolvedType(ERROR, this);
- }
-
- public final ReferenceBinding getJavaLangRegExp() {
- CompilationUnitScope unitScope = compilationUnitScope();
- unitScope.recordQualifiedReference(REGEXP);
- return unitScope.environment.getResolvedType(REGEXP, this);
- }
-
- /* Answer the type binding corresponding to the typeName argument, relative to the enclosingType.
- */
- public final ReferenceBinding getMemberType(char[] typeName, ReferenceBinding enclosingType) {
- ReferenceBinding memberType = findMemberType(typeName, enclosingType);
- if (memberType != null) return memberType;
- return new ProblemReferenceBinding(typeName, null, ProblemReasons.NotFound);
- }
-
- public MethodBinding getMethod(TypeBinding receiverType, char[] selector, TypeBinding[] argumentTypes, InvocationSite invocationSite) {
- CompilationUnitScope unitScope = compilationUnitScope();
- LookupEnvironment env = unitScope.environment;
- try {
- env.missingClassFileLocation = invocationSite;
- if (receiverType==null)
- return new ProblemMethodBinding(selector, argumentTypes, ProblemReasons.NotFound);
- switch (receiverType.kind()) {
- case Binding.BASE_TYPE :
- return new ProblemMethodBinding(selector, argumentTypes, ProblemReasons.NotFound);
-// case Binding.ARRAY_TYPE :
-// unitScope.recordTypeReference(receiverType);
-// return findMethodForArray((ArrayBinding) receiverType, selector, argumentTypes, invocationSite);
- }
- unitScope.recordTypeReference(receiverType);
-
- ReferenceBinding currentType = (ReferenceBinding) receiverType;
- if (!currentType.canBeSeenBy(this))
- return new ProblemMethodBinding(selector, argumentTypes, ProblemReasons.ReceiverTypeNotVisible);
-
- // retrieve an exact visible match (if possible)
- MethodBinding methodBinding = findExactMethod(currentType, selector, argumentTypes, invocationSite);
- if (methodBinding != null) return methodBinding;
-
- methodBinding = findMethod(currentType, selector, argumentTypes, invocationSite);
- if (methodBinding == null)
- return new ProblemMethodBinding(selector, argumentTypes, ProblemReasons.NotFound);
- if (!methodBinding.isValidBinding())
- return methodBinding;
-
- return methodBinding;
- } catch (AbortCompilation e) {
- e.updateContext(invocationSite, referenceCompilationUnit().compilationResult);
- throw e;
- } finally {
- env.missingClassFileLocation = null;
- }
- }
-
- /* Answer the package from the compoundName or null if it begins with a type.
- * Intended to be used while resolving a qualified type name.
- *
- * NOTE: If a problem binding is returned, senders should extract the compound name
- * from the binding & not assume the problem applies to the entire compoundName.
- */
- public final Binding getPackage(char[][] compoundName) {
- compilationUnitScope().recordQualifiedReference(compoundName);
- Binding binding = getTypeOrPackage(compoundName[0], Binding.TYPE | Binding.PACKAGE);
- if (binding == null)
- return new ProblemReferenceBinding(compoundName[0], null, ProblemReasons.NotFound);
- if (!binding.isValidBinding())
- return binding;
-
- if (!(binding instanceof PackageBinding)) return null; // compoundName does not start with a package
-
- int currentIndex = 1;
- PackageBinding packageBinding = (PackageBinding) binding;
- while (currentIndex < compoundName.length) {
- binding = packageBinding.getTypeOrPackage(compoundName[currentIndex++], Binding.PACKAGE);
- if (binding == null)
- return new ProblemReferenceBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- null,
- ProblemReasons.NotFound);
- if (!binding.isValidBinding())
- return new ProblemReferenceBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- binding instanceof ReferenceBinding ? ((ReferenceBinding)binding).closestMatch() : null,
- binding.problemId());
- if (!(binding instanceof PackageBinding))
- return packageBinding;
- packageBinding = (PackageBinding) binding;
- }
- return new ProblemReferenceBinding(compoundName, null, ProblemReasons.NotFound);
- }
-
- /* Answer the type binding that corresponds the given name, starting the lookup in the receiver.
- * The name provided is a simple source name (e.g., "Object" , "Point", ...)
- */
- // The return type of this method could be ReferenceBinding if we did not answer base types.
- // NOTE: We could support looking for Base Types last in the search, however any code using
- // this feature would be extraordinarily slow. Therefore we don't do this
- public final TypeBinding getType(char[] name) {
- // Would like to remove this test and require senders to specially handle base types
- TypeBinding binding = getBaseType(name);
- if (binding != null) return binding;
- return (ReferenceBinding) getTypeOrPackage(name, Binding.TYPE);
- }
-
- /* Answer the type binding that corresponds to the given name, starting the lookup in the receiver
- * or the packageBinding if provided.
- * The name provided is a simple source name (e.g., "Object" , "Point", ...)
- */
- public final TypeBinding getType(char[] name, PackageBinding packageBinding) {
- if (packageBinding == null)
- return getType(name);
-
- Binding binding = packageBinding.getTypeOrPackage(name, Binding.TYPE);
- if (binding == null)
- return new ProblemReferenceBinding(
- CharOperation.arrayConcat(packageBinding.compoundName, name),
- null,
- ProblemReasons.NotFound);
- if (!binding.isValidBinding())
- return new ProblemReferenceBinding(
- CharOperation.arrayConcat(packageBinding.compoundName, name),
- binding instanceof ReferenceBinding ? ((ReferenceBinding)binding).closestMatch() : null,
- binding.problemId());
-
- ReferenceBinding typeBinding = (ReferenceBinding) binding;
- if (!typeBinding.canBeSeenBy(this))
- return new ProblemReferenceBinding(
- CharOperation.arrayConcat(packageBinding.compoundName, name),
- typeBinding,
- ProblemReasons.NotVisible);
- return typeBinding;
- }
-
- /* Answer the type binding corresponding to the compoundName.
- *
- * NOTE: If a problem binding is returned, senders should extract the compound name
- * from the binding & not assume the problem applies to the entire compoundName.
- */
- public final TypeBinding getType(char[][] compoundName, int typeNameLength) {
- if (typeNameLength == 1) {
- // Would like to remove this test and require senders to specially handle base types
- TypeBinding binding = getBaseType(compoundName[0]);
- if (binding != null) return binding;
- }
-
- CompilationUnitScope unitScope = compilationUnitScope();
- unitScope.recordQualifiedReference(compoundName);
- Binding binding =
- getTypeOrPackage(compoundName[0], typeNameLength == 1 ? Binding.TYPE : Binding.TYPE | Binding.PACKAGE);
- if (binding == null)
- return new ProblemReferenceBinding(compoundName[0], null, ProblemReasons.NotFound);
- if (!binding.isValidBinding())
- return (ReferenceBinding) binding;
-
- int currentIndex = 1;
- boolean checkVisibility = false;
- if (binding instanceof PackageBinding) {
- PackageBinding packageBinding = (PackageBinding) binding;
- while (currentIndex < typeNameLength) {
- binding = packageBinding.getTypeOrPackage(compoundName[currentIndex++], Binding.TYPE); // does not check visibility
- if (binding == null)
- return new ProblemReferenceBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- null,
- ProblemReasons.NotFound);
- if (!binding.isValidBinding())
- return new ProblemReferenceBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- binding instanceof ReferenceBinding ? ((ReferenceBinding)binding).closestMatch() : null,
- binding.problemId());
- if (!(binding instanceof PackageBinding))
- break;
- packageBinding = (PackageBinding) binding;
- }
- if (binding instanceof PackageBinding)
- return new ProblemReferenceBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- null,
- ProblemReasons.NotFound);
- checkVisibility = true;
- }
-
- // binding is now a ReferenceBinding
- ReferenceBinding typeBinding = (ReferenceBinding) binding;
- unitScope.recordTypeReference(typeBinding);
- if (checkVisibility) // handles the fall through case
- if (!typeBinding.canBeSeenBy(this))
- return new ProblemReferenceBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- typeBinding,
- ProblemReasons.NotVisible);
-
- while (currentIndex < typeNameLength) {
- typeBinding = getMemberType(compoundName[currentIndex++], typeBinding);
- if (!typeBinding.isValidBinding()) {
- if (typeBinding instanceof ProblemReferenceBinding) {
- ProblemReferenceBinding problemBinding = (ProblemReferenceBinding) typeBinding;
- return new ProblemReferenceBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- problemBinding.closestMatch(),
- typeBinding.problemId());
- }
- return new ProblemReferenceBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- ((ReferenceBinding)binding).closestMatch(),
- typeBinding.problemId());
- }
- }
- return typeBinding;
- }
-
- /* Internal use only
- */
- final Binding getTypeOrPackage(char[] name, int mask) {
- Scope scope = this;
- Binding foundType = null;
- boolean insideStaticContext = false;
- if ((mask & Binding.TYPE) == 0) {
- Scope next = scope;
- while ((next = scope.parent) != null)
- scope = next;
- } else {
- done : while (true) { // done when a COMPILATION_UNIT_SCOPE is found
- switch (scope.kind) {
- case METHOD_SCOPE :
- MethodScope methodScope = (MethodScope) scope;
- insideStaticContext |= methodScope.isStatic;
- case BLOCK_SCOPE :
- ReferenceBinding localType = ((BlockScope) scope).findLocalType(name); // looks in this scope only
- if (localType != null) {
- return localType;
- }
- break;
- case CLASS_SCOPE :
- SourceTypeBinding sourceType = ((ClassScope) scope).getReferenceBinding();
-
- // type variables take precedence over the source type, ex. class X <X> extends X == class X <Y> extends Y
- // but not when we step out to the enclosing type
- if (CharOperation.equals(name, sourceType.sourceName))
- return sourceType;
- insideStaticContext |= sourceType.isStatic();
- break;
- case COMPILATION_UNIT_SCOPE :
- break done;
- }
- scope = scope.parent;
- }
- }
-
- // at this point the scope is a compilation unit scope
- CompilationUnitScope unitScope = (CompilationUnitScope) scope;
- HashtableOfObject typeOrPackageCache = unitScope.typeOrPackageCache;
- if (typeOrPackageCache != null) {
- Binding binding = (Binding) typeOrPackageCache.get(name);
- if (binding != null) { // can also include NotFound ProblemReferenceBindings if we already know this name is not found
- if (binding instanceof ImportBinding) { // single type import cached in faultInImports(), replace it in the cache with the type
- ImportReference importReference = ((ImportBinding) binding).reference;
- if (importReference != null)
- importReference.bits |= ASTNode.Used;
- if (binding instanceof ImportConflictBinding)
- typeOrPackageCache.put(name, binding = ((ImportConflictBinding) binding).conflictingTypeBinding); // already know its visible
- else
- typeOrPackageCache.put(name, binding = ((ImportBinding) binding).resolvedImport); // already know its visible
- }
- if ((mask & Binding.TYPE) != 0) {
- if (binding instanceof ReferenceBinding)
- return binding; // cached type found in previous walk below
- }
- if ((mask & Binding.PACKAGE) != 0 && binding instanceof PackageBinding)
- return binding; // cached package found in previous walk below
- }
- }
-
- // ask for the imports + name
- if ((mask & Binding.TYPE|Binding.VARIABLE|Binding.METHOD) != 0) {
- ImportBinding[] imports = unitScope.imports;
- if (imports != null && typeOrPackageCache == null) { // walk single type imports since faultInImports() has not run yet
- nextImport : for (int i = 0, length = imports.length; i < length; i++) {
- ImportBinding importBinding = imports[i];
- if (!importBinding.onDemand) {
- if (CharOperation.equals(importBinding.compoundName[importBinding.compoundName.length - 1], name)) {
- Binding resolvedImport = unitScope.resolveSingleImport(importBinding);
- if (resolvedImport == null) continue nextImport;
- if (resolvedImport instanceof MethodBinding) {
- resolvedImport = getType(importBinding.compoundName, importBinding.compoundName.length);
- if (!resolvedImport.isValidBinding()) continue nextImport;
- }
- if (resolvedImport instanceof TypeBinding) {
- ImportReference importReference = importBinding.reference;
- if (importReference != null)
- importReference.bits |= ASTNode.Used;
- return resolvedImport; // already know its visible
- }
- }
- }
- }
- }
-
-
- // check on file imports
- if (imports != null) {
- for (int i = 0, length = imports.length; i < length; i++) {
- ImportBinding someImport = imports[i];
- if (someImport.reference!=null && someImport.reference.isFileImport())
- {
- Binding resolvedImport = someImport.resolvedImport;
- Binding temp = null;
-
- if (resolvedImport instanceof CompilationUnitBinding) {
- CompilationUnitBinding compilationUnitBinding =(CompilationUnitBinding)resolvedImport;
-
- temp = findBinding(name, mask, compilationUnitBinding.getPackage(), unitScope.getDefaultPackage(), false);
- if (temp!=null && temp.isValidBinding())
- {
- ImportReference importReference = someImport.reference;
- importReference.bits |= ASTNode.Used;
- if (typeOrPackageCache != null)
- typeOrPackageCache.put(name, temp);
- return temp; // type is always visible to its own package
- }
- }
-
-
- }
- }
- }
-
- // check if the name is in the current package, skip it if its a sub-package
- PackageBinding currentPackage = unitScope.getDefaultPackage();
- unitScope.recordReference(currentPackage.compoundName, name);
- Binding binding=currentPackage.getTypeOrPackage(name, mask);
- if ( (binding instanceof ReferenceBinding || binding instanceof MethodBinding)
- && !(binding instanceof ProblemReferenceBinding)) {
- if (typeOrPackageCache != null)
- typeOrPackageCache.put(name, binding);
- return binding; // type is always visible to its own package
- }
- else if (binding instanceof LocalVariableBinding && binding.isValidBinding())
- {
- compilationUnitScope().addExternalVar((LocalVariableBinding)binding);
- return binding;
- }
-
- // check on demand imports
- if (imports != null) {
- boolean foundInImport = false;
- Binding type = null;
- for (int i = 0, length = imports.length; i < length; i++) {
- ImportBinding someImport = imports[i];
- if (someImport.onDemand) {
- Binding resolvedImport = someImport.resolvedImport;
- Binding temp = null;
- if (resolvedImport instanceof PackageBinding) {
- temp = findBinding(name, mask, (PackageBinding) resolvedImport, currentPackage, false);
- } else {
- temp = findDirectMemberType(name, (ReferenceBinding) resolvedImport);
- }
- if (temp != type && temp != null) {
- if (temp.isValidBinding()) {
- ImportReference importReference = someImport.reference;
- if (importReference != null)
- importReference.bits |= ASTNode.Used;
- if (foundInImport) {
- // Answer error binding -- import on demand conflict; name found in two import on demand packages.
- temp = new ProblemReferenceBinding(name, null, ProblemReasons.Ambiguous);
- if (typeOrPackageCache != null)
- typeOrPackageCache.put(name, temp);
- return temp;
- }
- type = temp;
- foundInImport = true;
- } else if (foundType == null) {
- foundType = temp;
- }
- }
- }
- }
- if (type != null) {
- if (typeOrPackageCache != null)
- typeOrPackageCache.put(name, type);
- return type;
- }
- }
- }
-
- unitScope.recordSimpleReference(name);
- if ((mask & Binding.PACKAGE) != 0) {
- PackageBinding packageBinding = unitScope.environment.getTopLevelPackage(name);
- if (packageBinding != null) {
- if (typeOrPackageCache != null)
- typeOrPackageCache.put(name, packageBinding);
- return packageBinding;
- }
- }
-
- // Answer error binding -- could not find name
- if (foundType == null) {
- foundType = new ProblemReferenceBinding(name, null, ProblemReasons.NotFound);
- if (typeOrPackageCache != null && (mask & Binding.PACKAGE) != 0) // only put NotFound type in cache if you know its not a package
- typeOrPackageCache.put(name, foundType);
- }
- return foundType;
- }
-
- // Added for code assist... NOT Public API
- // DO NOT USE to resolve import references since this method assumes 'A.B' is relative to a single type import of 'p1.A'
- // when it may actually mean the type B in the package A
- // use CompilationUnitScope.getImport(char[][]) instead
- public final Binding getTypeOrPackage(char[][] compoundName) {
- return getTypeOrPackage(compoundName,Binding.TYPE | Binding.PACKAGE);
- }
-
- public final Binding getTypeOrPackage(char[][] compoundName, int mask) {
- int nameLength = compoundName.length;
- if (nameLength == 1) {
- TypeBinding binding = getBaseType(compoundName[0]);
- if (binding != null) return binding;
- }
- Binding binding = getTypeOrPackage(compoundName[0], Binding.TYPE | Binding.PACKAGE);
- if (!binding.isValidBinding()) return binding;
-
- int currentIndex = 1;
- boolean checkVisibility = false;
- if (binding instanceof PackageBinding) {
- PackageBinding packageBinding = (PackageBinding) binding;
-
- while (currentIndex < nameLength) {
- binding = packageBinding.getTypeOrPackage(compoundName[currentIndex++], mask);
- if (binding == null)
- return new ProblemReferenceBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- null,
- ProblemReasons.NotFound);
- if (!binding.isValidBinding())
- return new ProblemReferenceBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- binding instanceof ReferenceBinding ? ((ReferenceBinding)binding).closestMatch() : null,
- binding.problemId());
- if (!(binding instanceof PackageBinding))
- break;
- packageBinding = (PackageBinding) binding;
- }
- if (binding instanceof PackageBinding) return binding;
- checkVisibility = true;
- }
- // binding is now a ReferenceBinding
- ReferenceBinding typeBinding = (ReferenceBinding) binding;
- ReferenceBinding qualifiedType = typeBinding;
-
- if (checkVisibility) // handles the fall through case
- if (!typeBinding.canBeSeenBy(this))
- return new ProblemReferenceBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- typeBinding,
- ProblemReasons.NotVisible);
-
- while (currentIndex < nameLength) {
- typeBinding = getMemberType(compoundName[currentIndex++], typeBinding);
- // checks visibility
- if (!typeBinding.isValidBinding())
- return new ProblemReferenceBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- ((ReferenceBinding)binding).closestMatch(),
- typeBinding.problemId());
-
-
- qualifiedType = typeBinding;
-
- }
- return qualifiedType;
- }
-
- protected boolean hasErasedCandidatesCollisions(TypeBinding one, TypeBinding two, Map invocations, ReferenceBinding type, ASTNode typeRef) {
- invocations.clear();
- TypeBinding[] mecs = minimalErasedCandidates(new TypeBinding[] {one, two}, invocations);
- if (mecs != null) {
- nextCandidate: for (int k = 0, max = mecs.length; k < max; k++) {
- TypeBinding mec = mecs[k];
- if (mec == null) continue nextCandidate;
- Object value = invocations.get(mec);
- if (value instanceof TypeBinding[]) {
- TypeBinding[] invalidInvocations = (TypeBinding[]) value;
- type.tagBits |= TagBits.HierarchyHasProblems;
- return true;
- }
- }
- }
- return false;
- }
-
- /**
- * Returns the immediately enclosing switchCase statement (carried by closest blockScope),
- */
- public CaseStatement innermostSwitchCase() {
- Scope scope = this;
- do {
- if (scope instanceof BlockScope)
- return ((BlockScope) scope).enclosingCase;
- scope = scope.parent;
- } while (scope != null);
- return null;
- }
-
- protected boolean isAcceptableMethod(MethodBinding one, MethodBinding two) {
- TypeBinding[] oneParams = one.parameters;
- TypeBinding[] twoParams = two.parameters;
- int oneParamsLength = oneParams.length;
- int twoParamsLength = twoParams.length;
- if (oneParamsLength == twoParamsLength) {
- for (int i = 0; i < oneParamsLength; i++) {
- TypeBinding oneParam = oneParams[i];
- TypeBinding twoParam = twoParams[i];
- if (oneParam == twoParam) {
- continue;
- }
- if (oneParam.isCompatibleWith(twoParam)) {
-
- } else {
- if (i == oneParamsLength - 1 && one.isVarargs() && two.isVarargs()) {
- TypeBinding eType = ((ArrayBinding) twoParam).elementsType();
- if (oneParam == eType || oneParam.isCompatibleWith(eType))
- return true; // special case to choose between 2 varargs methods when the last arg is Object[]
- }
- return false;
- }
- }
- return true;
- }
-
- if (one.isVarargs() && two.isVarargs()) {
- if (oneParamsLength > twoParamsLength) {
- // special case when autoboxing makes (int, int...) better than (Object...) but not (int...) or (Integer, int...)
- if (((ArrayBinding) twoParams[twoParamsLength - 1]).elementsType().id != TypeIds.T_JavaLangObject)
- return false;
- }
- // check that each parameter before the vararg parameters are compatible (no autoboxing allowed here)
- for (int i = (oneParamsLength > twoParamsLength ? twoParamsLength : oneParamsLength) - 2; i >= 0; i--)
- if (oneParams[i] != twoParams[i] && !oneParams[i].isCompatibleWith(twoParams[i]))
- return false;
- if (parameterCompatibilityLevel(one, twoParams) == NOT_COMPATIBLE
- && parameterCompatibilityLevel(two, oneParams) == VARARGS_COMPATIBLE)
- return true;
- }
- return false;
- }
-
- public boolean isBoxingCompatibleWith(TypeBinding expressionType, TypeBinding targetType) {
- LookupEnvironment environment = environment();
- if (environment.globalOptions.sourceLevel < ClassFileConstants.JDK1_5 || expressionType.isBaseType() == targetType.isBaseType())
- return false;
-
- // check if autoboxed type is compatible
- TypeBinding convertedType = environment.computeBoxingType(expressionType);
- return convertedType == targetType || convertedType.isCompatibleWith(targetType);
- }
-
- /* Answer true if the scope is nested inside a given field declaration.
- * Note: it works as long as the scope.fieldDeclarationIndex is reflecting the field being traversed
- * e.g. during name resolution.
- */
- public final boolean isDefinedInField(FieldBinding field) {
- Scope scope = this;
- do {
- if (scope instanceof MethodScope) {
- MethodScope methodScope = (MethodScope) scope;
- if (methodScope.initializedField == field) return true;
- }
- scope = scope.parent;
- } while (scope != null);
- return false;
- }
-
- /* Answer true if the scope is nested inside a given method declaration
- */
- public final boolean isDefinedInMethod(MethodBinding method) {
- Scope scope = this;
- do {
- if (scope instanceof MethodScope) {
- ReferenceContext refContext = ((MethodScope) scope).referenceContext;
- if (refContext instanceof AbstractMethodDeclaration)
- if (((AbstractMethodDeclaration) refContext).binding == method)
- return true;
- }
- scope = scope.parent;
- } while (scope != null);
- return false;
- }
-
- /* Answer whether the type is defined in the same compilation unit as the receiver
- */
- public final boolean isDefinedInSameUnit(ReferenceBinding type) {
- // find the outer most enclosing type
- ReferenceBinding enclosingType = type;
- while ((type = enclosingType.enclosingType()) != null)
- enclosingType = type;
-
- // find the compilation unit scope
- Scope scope, unitScope = this;
- while ((scope = unitScope.parent) != null)
- unitScope = scope;
-
- // test that the enclosingType is not part of the compilation unit
- SourceTypeBinding[] topLevelTypes = ((CompilationUnitScope) unitScope).topLevelTypes;
- for (int i = topLevelTypes.length; --i >= 0;)
- if (topLevelTypes[i] == enclosingType)
- return true;
- return false;
- }
-
- /* Answer true if the scope is nested inside a given type declaration
- */
- public final boolean isDefinedInType(ReferenceBinding type) {
- Scope scope = this;
- do {
- if (scope instanceof ClassScope)
- if (((ClassScope) scope).getReferenceBinding() == type)
- return true;
- scope = scope.parent;
- } while (scope != null);
- return false;
- }
-
- /**
- * Returns true if the scope or one of its parent is associated to a given caseStatement, denoting
- * being part of a given switch case statement.
- */
- public boolean isInsideCase(CaseStatement caseStatement) {
- Scope scope = this;
- do {
- switch (scope.kind) {
- case Scope.BLOCK_SCOPE :
- if (((BlockScope) scope).enclosingCase == caseStatement) {
- return true;
- }
- }
- scope = scope.parent;
- } while (scope != null);
- return false;
- }
-
- public boolean isInsideDeprecatedCode(){
- switch(this.kind){
- case Scope.BLOCK_SCOPE :
- case Scope.METHOD_SCOPE :
- MethodScope methodScope = methodScope();
- if (!methodScope.isInsideInitializer()){
- // check method modifiers to see if deprecated
- MethodBinding context = ((AbstractMethodDeclaration)methodScope.referenceContext).binding;
- if (context != null && context.isViewedAsDeprecated())
- return true;
- } else {
- SourceTypeBinding type = ((BlockScope)this).referenceType().binding;
- // inside field declaration ? check field modifier to see if deprecated
- if (methodScope.initializedField != null && methodScope.initializedField.isViewedAsDeprecated())
- return true;
- if (type != null) {
- if (type.isViewedAsDeprecated())
- return true;
- }
- }
- break;
- case Scope.CLASS_SCOPE :
- ReferenceBinding context = ((ClassScope)this).referenceType().binding;
- if (context != null) {
- if (context.isViewedAsDeprecated())
- return true;
- }
- break;
- case Scope.COMPILATION_UNIT_SCOPE :
- // consider import as being deprecated if first type is itself deprecated (123522)
- CompilationUnitDeclaration unit = referenceCompilationUnit();
- if (unit.types != null && unit.types.length > 0) {
- SourceTypeBinding type = unit.types[0].binding;
- if (type != null) {
- if (type.isViewedAsDeprecated())
- return true;
- }
- }
- }
- return false;
- }
-
- public MethodScope methodScope() {
- Scope scope = this;
- do {
- if (scope instanceof MethodScope)
- return (MethodScope) scope;
- scope = scope.parent;
- } while (scope != null);
- return null;
- }
-
- /**
- * Returns the most specific set of types compatible with all given types.
- * (i.e. most specific common super types)
- * If no types is given, will return an empty array. If not compatible
- * reference type is found, returns null. In other cases, will return an array
- * of minimal erased types, where some nulls may appear (and must simply be
- * ignored).
- */
- protected TypeBinding[] minimalErasedCandidates(TypeBinding[] types, Map allInvocations) {
- int length = types.length;
- int indexOfFirst = -1, actualLength = 0;
- for (int i = 0; i < length; i++) {
- TypeBinding type = types[i];
- if (type == null) continue;
- if (type.isBaseType()) return null;
- if (indexOfFirst < 0) indexOfFirst = i;
- actualLength ++;
- }
- switch (actualLength) {
- case 0: return Binding.NO_TYPES;
- case 1: return types;
- }
- TypeBinding firstType = types[indexOfFirst];
- if (firstType.isBaseType()) return null;
-
- // record all supertypes of type
- // intersect with all supertypes of otherType
- ArrayList typesToVisit = new ArrayList(5);
-
- int dim = firstType.dimensions();
- TypeBinding leafType = firstType.leafComponentType();
- TypeBinding firstErasure = firstType;
- if (firstErasure != firstType) {
- allInvocations.put(firstErasure, firstType);
- }
- typesToVisit.add(firstType);
- int max = 1;
- ReferenceBinding currentType;
- for (int i = 0; i < max; i++) {
- TypeBinding typeToVisit = (TypeBinding) typesToVisit.get(i);
- dim = typeToVisit.dimensions();
- if (dim > 0) {
- leafType = typeToVisit.leafComponentType();
- switch(leafType.id) {
- case T_JavaLangObject:
- if (dim > 1) { // Object[][] supertype is Object[]
- TypeBinding elementType = ((ArrayBinding)typeToVisit).elementsType();
- if (!typesToVisit.contains(elementType)) {
- typesToVisit.add(elementType);
- max++;
- }
- continue;
- }
- // fallthrough
- case T_short:
- case T_char:
- case T_boolean:
- case T_int:
- case T_long:
- case T_float:
- case T_double:
- TypeBinding superType = getJavaLangObject();
- if (!typesToVisit.contains(superType)) {
- typesToVisit.add(superType);
- max++;
- }
- continue;
-
- default:
- }
- typeToVisit = leafType;
- }
- currentType = (ReferenceBinding) typeToVisit;
-
- TypeBinding itsSuperclass = currentType.superclass();
- if (itsSuperclass != null) {
- TypeBinding superType = dim == 0 ? itsSuperclass : (TypeBinding)environment().createArrayType(itsSuperclass, dim); // recreate array if needed
- if (!typesToVisit.contains(superType)) {
- typesToVisit.add(superType);
- max++;
- TypeBinding superTypeErasure = superType;
- if (superTypeErasure != superType) {
- allInvocations.put(superTypeErasure, superType);
- }
- }
- }
- }
- int superLength = typesToVisit.size();
- TypeBinding[] erasedSuperTypes = new TypeBinding[superLength];
- int rank = 0;
- for (Iterator iter = typesToVisit.iterator(); iter.hasNext();) {
- TypeBinding type = (TypeBinding)iter.next();
- leafType = type.leafComponentType();
- erasedSuperTypes[rank++] = type;
- }
- // intersecting first type supertypes with other types' ones, nullifying non matching supertypes
- int remaining = superLength;
- nextOtherType: for (int i = indexOfFirst+1; i < length; i++) {
- TypeBinding otherType = types[i];
- if (otherType == null) continue nextOtherType;
- if (otherType.isArrayType()) {
- nextSuperType: for (int j = 0; j < superLength; j++) {
- TypeBinding erasedSuperType = erasedSuperTypes[j];
- if (erasedSuperType == null || erasedSuperType == otherType) continue nextSuperType;
- TypeBinding match;
- if ((match = otherType.findSuperTypeWithSameErasure(erasedSuperType)) == null) {
- erasedSuperTypes[j] = null;
- if (--remaining == 0) return null;
- continue nextSuperType;
- }
- // record invocation
- Object invocationData = allInvocations.get(erasedSuperType);
- if (invocationData == null) {
- allInvocations.put(erasedSuperType, match); // no array for singleton
- } else if (invocationData instanceof TypeBinding) {
- if (match != invocationData) {
- // using an array to record invocations in order (188103)
- TypeBinding[] someInvocations = { (TypeBinding) invocationData, match, };
- allInvocations.put(erasedSuperType, someInvocations);
- }
- } else { // using an array to record invocations in order (188103)
- TypeBinding[] someInvocations = (TypeBinding[]) invocationData;
- checkExisting: {
- int invocLength = someInvocations.length;
- for (int k = 0; k < invocLength; k++) {
- if (someInvocations[k] == match) break checkExisting;
- }
- System.arraycopy(someInvocations, 0, someInvocations = new TypeBinding[invocLength+1], 0, invocLength);
- allInvocations.put(erasedSuperType, someInvocations);
- someInvocations[invocLength] = match;
- }
- }
- }
- continue nextOtherType;
- }
- nextSuperType: for (int j = 0; j < superLength; j++) {
- TypeBinding erasedSuperType = erasedSuperTypes[j];
- if (erasedSuperType == null) continue nextSuperType;
- TypeBinding match;
- if (erasedSuperType == otherType) {
- match = erasedSuperType;
- } else {
- if (erasedSuperType.isArrayType()) {
- match = null;
- } else {
- match = otherType.findSuperTypeWithSameErasure(erasedSuperType);
- }
- if (match == null) { // incompatible super type
- erasedSuperTypes[j] = null;
- if (--remaining == 0) return null;
- continue nextSuperType;
- }
- }
- // record invocation
- Object invocationData = allInvocations.get(erasedSuperType);
- if (invocationData == null) {
- allInvocations.put(erasedSuperType, match); // no array for singleton
- } else if (invocationData instanceof TypeBinding) {
- if (match != invocationData) {
- // using an array to record invocations in order (188103)
- TypeBinding[] someInvocations = { (TypeBinding) invocationData, match, };
- allInvocations.put(erasedSuperType, someInvocations);
- }
- } else { // using an array to record invocations in order (188103)
- TypeBinding[] someInvocations = (TypeBinding[]) invocationData;
- checkExisting: {
- int invocLength = someInvocations.length;
- for (int k = 0; k < invocLength; k++) {
- if (someInvocations[k] == match) break checkExisting;
- }
- System.arraycopy(someInvocations, 0, someInvocations = new TypeBinding[invocLength+1], 0, invocLength);
- allInvocations.put(erasedSuperType, someInvocations);
- someInvocations[invocLength] = match;
- }
- }
- }
- }
- // eliminate non minimal super types
- if (remaining > 1) {
- nextType: for (int i = 0; i < superLength; i++) {
- TypeBinding erasedSuperType = erasedSuperTypes[i];
- if (erasedSuperType == null) continue nextType;
- nextOtherType: for (int j = 0; j < superLength; j++) {
- if (i == j) continue nextOtherType;
- TypeBinding otherType = erasedSuperTypes[j];
- if (otherType == null) continue nextOtherType;
- if (erasedSuperType instanceof ReferenceBinding) {
- if (erasedSuperType.findSuperTypeWithSameErasure(otherType) != null) {
- erasedSuperTypes[j] = null; // discard non minimal supertype
- remaining--;
- }
- } else if (erasedSuperType.isArrayType()) {
- if (erasedSuperType.findSuperTypeWithSameErasure(otherType) != null) {
- erasedSuperTypes[j] = null; // discard non minimal supertype
- remaining--;
- }
- }
- }
- }
- }
- return erasedSuperTypes;
- }
-
-
- // Internal use only
- /* All methods in visible are acceptable matches for the method in question...
- * The methods defined by the receiver type appear before those defined by its
- * superclass and so on. We want to find the one which matches best.
- *
- * Since the receiver type is a class, we know each method's declaring class is
- * either the receiver type or one of its superclasses. It is an error if the best match
- * is defined by a superclass, when a lesser match is defined by the receiver type
- * or a closer superclass.
- */
- protected final MethodBinding mostSpecificClassMethodBinding(MethodBinding[] visible, int visibleSize, InvocationSite invocationSite) {
- MethodBinding previous = null;
- nextVisible : for (int i = 0; i < visibleSize; i++) {
- MethodBinding method = visible[i];
- if (previous != null && method.declaringClass != previous.declaringClass)
- break; // cannot answer a method farther up the hierarchy than the first method found
-
- if (!method.isStatic()) previous = method; // no ambiguity for static methods
- for (int j = 0; j < visibleSize; j++) {
- if (i == j) continue;
- if (!visible[j].areParametersCompatibleWith(method.parameters))
- continue nextVisible;
- }
- return method;
- }
- return new ProblemMethodBinding(visible[0], visible[0].selector, visible[0].parameters, ProblemReasons.Ambiguous);
- }
-
- // caveat: this is not a direct implementation of JLS
- 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++)
- compatibilityLevels[i] = parameterCompatibilityLevel(visible[i], argumentTypes);
-
- MethodBinding[] moreSpecific = new MethodBinding[visibleSize];
- int count = 0;
- for (int level = 0, max = VARARGS_COMPATIBLE; level <= max; level++) {
- nextVisible : for (int i = 0; i < visibleSize; i++) {
- if (compatibilityLevels[i] != level) continue nextVisible;
- max = level; // do not examine further categories, will either return mostSpecific or report ambiguous case
- MethodBinding current = visible[i];
- MethodBinding original = current.original();
- MethodBinding tiebreakMethod = current.tiebreakMethod();
- for (int j = 0; j < visibleSize; j++) {
- if (i == j || compatibilityLevels[j] != level) continue;
- MethodBinding next = visible[j];
- if (original == next.original()) {
- // parameterized superclasses & interfaces may be walked twice from different paths so skip next from now on
- compatibilityLevels[j] = -1;
- continue;
- }
-
- MethodBinding methodToTest = next;
- MethodBinding acceptable = computeCompatibleMethod(methodToTest, tiebreakMethod.parameters, invocationSite);
- /* There are 4 choices to consider with current & next :
- foo(B) & foo(A) where B extends A
- 1. the 2 methods are equal (both accept each others parameters) -> want to continue
- 2. current has more specific parameters than next (so acceptable is a valid method) -> want to continue
- 3. current has less specific parameters than next (so acceptable is null) -> go on to next
- 4. current and next are not compatible with each other (so acceptable is null) -> go on to next
- */
- if (acceptable == null || !acceptable.isValidBinding())
- continue nextVisible;
- if (!isAcceptableMethod(tiebreakMethod, acceptable))
- continue nextVisible;
- // pick a concrete method over a bridge method when parameters are equal since the return type of the concrete method is more specific
- if (current.isBridge() && !next.isBridge())
- if (tiebreakMethod.areParametersEqual(acceptable))
- continue nextVisible; // skip current so acceptable wins over this bridge method
- }
- moreSpecific[i] = current;
- count++;
- }
- }
- if (count == 1) {
- for (int i = 0; i < visibleSize; i++) {
- if (moreSpecific[i] != null) {
- return visible[i];
- }
- }
- } else if (count == 0) {
- return new ProblemMethodBinding(visible[0], visible[0].selector, visible[0].parameters, ProblemReasons.Ambiguous);
- }
-
- // found several methods that are mutually acceptable -> must be equal
- // so now with the first acceptable method, find the 'correct' inherited method for each other acceptable method AND
- // see if they are equal after substitution of type variables (do the type variables have to be equal to be considered an override???)
- 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];
- if (next == null || i == j) continue;
- MethodBinding original2 = next.original();
- if (original.declaringClass == original2.declaringClass)
- break nextSpecific; // duplicates thru substitution
-
- if (!original.isAbstract()) {
- if (original2.isAbstract())
- continue; // only compare current against other concrete methods
- TypeBinding superType = original.declaringClass.findSuperTypeWithSameErasure(original2.declaringClass);
- if (superType == null)
- continue nextSpecific; // current's declaringClass is not a subtype of next's declaringClass
- } else if (receiverType != null) { // should not be null if original isAbstract, but be safe
- TypeBinding superType = receiverType.findSuperTypeWithSameErasure(original.declaringClass);
- if (original.declaringClass == superType || !(superType instanceof ReferenceBinding)) {
- // keep original
- } else {
- // must find inherited method with the same substituted variables
- MethodBinding[] superMethods = ((ReferenceBinding) superType).getMethods(original.selector);
- for (int m = 0, l = superMethods.length; m < l; m++) {
- if (superMethods[m].original() == original) {
- original = superMethods[m];
- break;
- }
- }
- }
- superType = receiverType.findSuperTypeWithSameErasure(original2.declaringClass);
- if (original2.declaringClass == superType || !(superType instanceof ReferenceBinding)) {
- // keep original2
- } else {
- // must find inherited method with the same substituted variables
- MethodBinding[] superMethods = ((ReferenceBinding) superType).getMethods(original2.selector);
- for (int m = 0, l = superMethods.length; m < l; m++) {
- if (superMethods[m].original() == original2) {
- original2 = superMethods[m];
- break;
- }
- }
- }
- if (original2 == null || !original.areParametersEqual(original2))
- continue nextSpecific; // current does not override next
- if (!original.returnType.isCompatibleWith(original2.returnType) &&
- !original.returnType.isCompatibleWith(original2.returnType)) {
- // 15.12.2
- continue nextSpecific; // choose original2 instead
- }
- }
- }
- 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);
- }
-
- public final ClassScope outerMostClassScope() {
- ClassScope lastClassScope = null;
- Scope scope = this;
- do {
- if (scope instanceof ClassScope)
- lastClassScope = (ClassScope) scope;
- scope = scope.parent;
- } while (scope != null);
- return lastClassScope; // may answer null if no class around
- }
-
- public final MethodScope outerMostMethodScope() {
- MethodScope lastMethodScope = null;
- Scope scope = this;
- do {
- if (scope instanceof MethodScope)
- lastMethodScope = (MethodScope) scope;
- scope = scope.parent;
- } while (scope != null);
- return lastMethodScope; // may answer null if no method around
- }
-
- public int parameterCompatibilityLevel(MethodBinding method, TypeBinding[] arguments) {
- TypeBinding[] parameters = method.parameters;
- int paramLength = parameters.length;
- int argLength = arguments.length;
-
- if (compilerOptions().sourceLevel < ClassFileConstants.JDK1_5) {
- if (paramLength != argLength)
- return NOT_COMPATIBLE;
- for (int i = 0; i < argLength; i++) {
- TypeBinding param = parameters[i];
- TypeBinding arg = arguments[i];
- if (arg != param && !arg.isCompatibleWith(param))
- return NOT_COMPATIBLE;
- }
- return COMPATIBLE;
- }
-
- int level = COMPATIBLE; // no autoboxing or varargs support needed
- int lastIndex = argLength;
- LookupEnvironment env = environment();
- if (method.isVarargs()) {
- lastIndex = paramLength - 1;
- if (paramLength == argLength) { // accept X or X[] but not X[][]
- TypeBinding param = parameters[lastIndex]; // is an ArrayBinding by definition
- TypeBinding arg = arguments[lastIndex];
- if (param != arg) {
- level = parameterCompatibilityLevel(arg, param, env);
- if (level == NOT_COMPATIBLE) {
- // expect X[], is it called with X
- param = ((ArrayBinding) param).elementsType();
- if (parameterCompatibilityLevel(arg, param, env) == NOT_COMPATIBLE)
- return NOT_COMPATIBLE;
- level = VARARGS_COMPATIBLE; // varargs support needed
- }
- }
- } else {
- if (paramLength < argLength) { // all remaining argument types must be compatible with the elementsType of varArgType
- TypeBinding param = ((ArrayBinding) parameters[lastIndex]).elementsType();
- for (int i = lastIndex; i < argLength; i++) {
- TypeBinding arg = arguments[i];
- if (param != arg && parameterCompatibilityLevel(arg, param, env) == NOT_COMPATIBLE)
- return NOT_COMPATIBLE;
- }
- } else if (lastIndex != argLength) { // can call foo(int i, X ... x) with foo(1) but NOT foo();
- return NOT_COMPATIBLE;
- }
- level = VARARGS_COMPATIBLE; // varargs support needed
- }
- } else if (paramLength != argLength) {
- return NOT_COMPATIBLE;
- }
- // now compare standard arguments from 0 to lastIndex
- for (int i = 0; i < lastIndex; i++) {
- TypeBinding param = parameters[i];
- TypeBinding arg = arguments[i];
- if (arg != param) {
- int newLevel = parameterCompatibilityLevel(arg, param, env);
- if (newLevel == NOT_COMPATIBLE)
- return NOT_COMPATIBLE;
- if (newLevel > level)
- level = newLevel;
- }
- }
- return level;
- }
-
- private int parameterCompatibilityLevel(TypeBinding arg, TypeBinding param, LookupEnvironment env) {
- // only called if env.options.sourceLevel >= ClassFileConstants.JDK1_5
- if (arg.isCompatibleWith(param))
- return COMPATIBLE;
- if (arg.isBaseType() != param.isBaseType()) {
- TypeBinding convertedType = env.computeBoxingType(arg);
- if (convertedType == param || convertedType.isCompatibleWith(param))
- return AUTOBOX_COMPATIBLE;
- }
- return NOT_COMPATIBLE;
- }
-
- public abstract ProblemReporter problemReporter();
-
- public final CompilationUnitDeclaration referenceCompilationUnit() {
- Scope scope, unitScope = this;
- while ((scope = unitScope.parent) != null)
- unitScope = scope;
- return ((CompilationUnitScope) unitScope).referenceContext;
- }
-
- /**
- * Returns the nearest reference context, starting from current scope.
- * If starting on a class, it will return current class. If starting on unitScope, returns unit.
- */
- public ReferenceContext referenceContext() {
- Scope current = this;
- do {
- switch(current.kind) {
- case METHOD_SCOPE :
- return ((MethodScope) current).referenceContext;
- case CLASS_SCOPE :
- return ((ClassScope) current).referenceContext;
- case COMPILATION_UNIT_SCOPE :
- return ((CompilationUnitScope) current).referenceContext;
- }
- } while ((current = current.parent) != null);
- return null;
- }
-
- // start position in this scope - for ordering scopes vs. variables
- int startIndex() {
- return 0;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/SignatureWrapper.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/SignatureWrapper.java
deleted file mode 100644
index d9577d54..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/SignatureWrapper.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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.core.compiler.CharOperation;
-
-public class SignatureWrapper {
- public char[] signature;
- public int start;
- public int end;
- public int bracket;
-
- public SignatureWrapper(char[] signature) {
- this.signature = signature;
- this.start = 0;
- this.end = this.bracket = -1;
- }
- public boolean atEnd() {
- return this.start < 0 || this.start >= this.signature.length;
- }
- public int computeEnd() {
- int index = this.start;
- while (this.signature[index] == '[')
- index++;
- switch (this.signature[index]) {
- case 'L' :
- case 'T' :
- this.end = CharOperation.indexOf(';', this.signature, this.start);
- if (this.bracket <= this.start) // already know it if its > start
- this.bracket = CharOperation.indexOf('<', this.signature, this.start);
-
- if (this.bracket > this.start && this.bracket < this.end)
- this.end = this.bracket;
- else if (this.end == -1)
- this.end = this.signature.length + 1;
- break;
- default :
- this.end = this.start;
- }
-
- this.start = this.end + 1; // skip ';'
- return this.end;
- }
- public char[] nextWord() {
- this.end = CharOperation.indexOf(';', this.signature, this.start);
- if (this.bracket <= this.start) // already know it if its > start
- this.bracket = CharOperation.indexOf('<', this.signature, this.start);
- int dot = CharOperation.indexOf('.', this.signature, this.start);
-
- if (this.bracket > this.start && this.bracket < this.end)
- this.end = this.bracket;
- if (dot > this.start && dot < this.end)
- this.end = dot;
-
- return CharOperation.subarray(this.signature, this.start, this.start = this.end); // skip word
- }
- public String toString() {
- return new String(this.signature) + " @ " + this.start; //$NON-NLS-1$
- }
-}
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
deleted file mode 100644
index 03ed1dd3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/SourceTypeBinding.java
+++ /dev/null
@@ -1,1418 +0,0 @@
-/*******************************************************************************
- * 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.compiler.lookup;
-
-import java.util.HashMap;
-import java.util.Hashtable;
-import java.util.Map;
-import java.util.zip.CRC32;
-
-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.MethodDeclaration;
-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;
- protected FieldBinding[] fields;
- protected MethodBinding[] methods;
- public ReferenceBinding[] memberTypes = Binding.NO_MEMBER_TYPES;
-
- public Scope scope;
- public ClassScope classScope;
-
- char[] genericReferenceTypeSignature;
-
- public SourceTypeBinding nextType;
-
- private static final CRC32 checksumCalculator = new CRC32();
-
- public SourceTypeBinding(char[][] compoundName, PackageBinding fPackage,
- Scope scope) {
- this.compoundName = compoundName;
- this.fPackage = fPackage;
- this.fileName = scope.referenceCompilationUnit().getFileName();
- if (scope instanceof ClassScope) {
- this.classScope = (ClassScope) scope;
- if (this.classScope.referenceContext != null) {
- this.modifiers = this.classScope.referenceContext.modifiers;
- this.sourceName = this.classScope.referenceContext.name;
- } else {
- this.sourceName = this.classScope.inferredType.getName();
-
- this.modifiers = ClassFileConstants.AccPublic;
- }
- }
- this.scope = scope;
-
- // expect the fields & methods to be initialized correctly later
- this.fields = Binding.NO_FIELDS;
- this.methods = Binding.NO_METHODS;
-
- computeId();
-
- }
-
- protected SourceTypeBinding() {
-
- }
-
- void buildFieldsAndMethods() {
- buildFields();
- buildMethods();
-
- }
-
- /**
- * <p><b>IMPORTANT:</b> Gets the {@link InferredType} for this binding only.
- * This means that if this binding has a {@link #nextType} then the {@link InferredType}
- * returned here is only a partially {@link InferredType}.</p>
- *
- * @see org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding#getInferredType()
- */
- public InferredType getInferredType() {
- ClassScope classScope = scope.classScope();
- return classScope.inferredType;
- }
-
- private void buildFields() {
- FieldBinding prototype = new FieldBinding(TypeConstants.PROTOTYPE,
- TypeBinding.UNKNOWN, modifiers
- | ExtraCompilerModifiers.AccUnresolved, this);
- 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
- 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;
- }
- }
- }
- 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)
- 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 = newFieldBindings;
- }
- if (count != fieldBindings.length)
- System.arraycopy(fieldBindings, 0,
- fieldBindings = new FieldBinding[count], 0, count);
- setFields(fieldBindings);
- }
-
- private void buildMethods() {
- InferredType inferredType = this.classScope.inferredType;
- int size = (inferredType.methods != null) ? inferredType.methods.size()
- : 0;
-
- if (size == 0) {
- setMethods(Binding.NO_METHODS);
- return;
- }
-
- int count = 0;
- 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();
-
- 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);
- }
- }
- 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);
- }
-
- 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;
- }
- }
- 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() {
- 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);
- }
- resolvedFields[i] = null;
- failed++;
- }
- fieldCache.put(this.fields[i].name, this.fields[i]);
- }
- } 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];
- }
- 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]);
- }
- }
-// 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;
- }
-
- public MethodBinding getExactConstructor(TypeBinding[] argumentTypes) {
- MethodBinding exactConstructor = getExactConstructor0(argumentTypes);
- if (exactConstructor == null && this.nextType != null)
- exactConstructor = this.nextType.getExactConstructor(argumentTypes);
- 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
- 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;
- // }
- }
- }
- } else {
- // 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) {
- // 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;
- }
- }
- }
- 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);
- 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.
- 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
- 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;
- }
- }
- } else {
- // 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 != null
- && 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];
- // 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);
- return field;
- }
-
- public FieldBinding getFieldInHierarchy(char[] fieldName,
- boolean needResolve) {
- SourceTypeBinding currentType = this;
- while (currentType != null) {
- FieldBinding field = currentType.getField(fieldName, needResolve);
- if (field != null)
- return field;
- currentType = (SourceTypeBinding) currentType.superclass();
- }
- return null;
- }
-
- // 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)
- return ReferenceBinding.binarySearch(fieldName, this.fields);
-
- // 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;
- }
- this.fields = newFields;
- }
- }
- }
- }
- 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;
- }
-
- // NOTE: the return type, arg & exception types of each method of a source
- // type are resolved when needed
- private MethodBinding[] getMethods0(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;
- }
- }
- // 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
- }
- }
- int length = end - start + 1;
- System.arraycopy(this.methods, start,
- result = new MethodBinding[length], 0, length);
- } else {
- return Binding.NO_METHODS;
- }
- boolean isSource15 = this.scope != null
- && this.scope.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
- }
- }
- }
- 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 FieldBinding getUpdatedFieldBinding(FieldBinding targetField,
- ReferenceBinding newDeclaringClass) {
- Hashtable fieldMap = new Hashtable(5);
- FieldBinding updatedField = new FieldBinding(targetField,
- newDeclaringClass);
- fieldMap.put(newDeclaringClass, updatedField);
- return updatedField;
- }
-
- public MethodBinding getUpdatedMethodBinding(MethodBinding targetMethod,
- ReferenceBinding newDeclaringClass) {
- MethodBinding updatedMethod = new MethodBinding(targetMethod,
- newDeclaringClass);
- updatedMethod.createFunctionTypeBinding(scope);
- return updatedMethod;
- }
-
- 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) {
- // 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++;
- }
- }
-
- // 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;
- }
- if (index >= 0 && index < pLength) {
- for (index = pLength; --index >= 0;)
- if (params1[index] != params2[index])
- break;
- }
- if (index >= 0)
- 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
- 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);
- }
- 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);
- }
- 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++;
- }
- }
- } 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;
- }
- }
-
- // handle forward references to potential default abstract
- // methods
- // addDefaultAbstractMethods();
- this.tagBits |= TagBits.AreMethodsComplete;
- }
- }
- 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;
-
- }
-
- 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;
- // 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) {
- return resolveTypesFor(method, null);
- }
-
- public MethodBinding resolveTypesFor(MethodBinding method,
- AbstractMethodDeclaration methodDecl) {
- if ((method.modifiers & ExtraCompilerModifiers.AccUnresolved) == 0)
- return method;
-
- if (isViewedAsDeprecated() && !method.isDeprecated())
- method.modifiers |= ExtraCompilerModifiers.AccDeprecatedImplicitly;
- if (hasRestrictedAccess())
- method.modifiers |= ExtraCompilerModifiers.AccRestrictedAccess;
-
- if (methodDecl == null)
- 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;
- TypeBinding[] newParameters = new TypeBinding[size];
- for (int i = 0; i < size; i++) {
- Argument arg = arguments[i];
- TypeBinding parameterType = TypeBinding.UNKNOWN;
- if (arg.type != null)
- parameterType = arg.type
- .resolveType(methodDecl.scope, true /* check bounds */);
- else if (arg.inferredType != null)
- parameterType = arg.inferredType.resolveType(
- methodDecl.scope, arg);
-
- if (parameterType == null) {
- // foundArgProblem = true;
- parameterType = TypeBinding.ANY;
- }
-
- newParameters[i] = parameterType;
- 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;
- }
-
- boolean foundReturnTypeProblem = false;
- if (!method.isConstructor()) {
- TypeReference returnType = methodDecl instanceof MethodDeclaration ? ((MethodDeclaration) methodDecl).returnType
- : null;
- if (returnType == null
- && !(methodDecl instanceof MethodDeclaration)) {
- methodDecl.scope.problemReporter()
- .missingReturnType(methodDecl);
- method.returnType = null;
- foundReturnTypeProblem = true;
- } else {
- TypeBinding methodType = (returnType != null) ? returnType
- .resolveType(methodDecl.scope, true /* check bounds */)
- : null;
- if (methodType == null)
- methodType = (methodDecl.inferredType != null) ? methodDecl.inferredType
- .resolveType(methodDecl.scope, 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
- // 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 int sourceEnd() {
- if (this.classScope.referenceContext != null)
- return this.classScope.referenceContext.sourceEnd;
- else
- return this.classScope.inferredType.sourceEnd;
- }
-
- public int sourceStart() {
- if (this.classScope.referenceContext != null)
- return this.classScope.referenceContext.sourceStart;
- 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();
-
- }
-
- 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());
- }
-
- 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$
- }
-
- 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$
- }
-
- 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)
- return null;
- InferredType inferredType = this.classScope.inferredType;
- InferredMethod inferredMethod = inferredType.findMethod(
- binding.selector, null);
- if (inferredMethod != null)
- return (AbstractMethodDeclaration) inferredMethod
- .getFunctionDeclaration();
- 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 void cleanup() {
- this.scope = null;
- this.classScope = null;
- }
-
- public boolean contains(ReferenceBinding binding) {
- if (binding == this)
- return true;
- if (this.nextType != null)
- return this.nextType.contains(binding);
- return false;
- }
-
- public void addNextType(SourceTypeBinding type) {
- SourceTypeBinding binding = this;
-
- // 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(!isDuplicate)
- binding.nextType = type;
- }
-
- public boolean checkIfDuplicateType(SourceTypeBinding binding1, SourceTypeBinding binding2) {
- InferredType type2 = binding2.classScope.inferredType;
- if(binding1.classScope == null) {
- if(binding1.superclass == null && type2.superClass != null)
- return false;
- if(binding1.superclass != null && type2.superClass == null)
- return false;
- if(binding1.superclass != null && type2.superClass != null &&
- !CharOperation.equals(binding1.superclass.sourceName, type2.superClass.getName()))
- return false;
- if(binding1.fields.length != type2.attributes.length)
- return false;
- if(binding1.methods == null && type2.methods != null)
- return false;
- if(binding1.methods != null && type2.methods == null)
- return false;
- if(binding1.methods != null && type2.methods != null && binding1.methods.length != type2.methods.size())
- return false;
- } else {
- InferredType type1 = binding1.classScope.inferredType;
-
- if(type1.superClass == null && type2.superClass != null)
- return false;
- if(type1.superClass != null && type2.superClass == null)
- return false;
- if(type1.superClass != null && type2.superClass != null &&
- !CharOperation.equals(type1.superClass.getName(), type2.superClass.getName()))
- return false;
- if(type1.attributes.length != type2.attributes.length)
- return false;
- if(type1.methods == null && type2.methods != null)
- return false;
- if(type1.methods != null && type2.methods == null)
- return false;
- 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$
-
- 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)));
- }
- checksumCalculator.reset();
- checksumCalculator.update(checkSumString1.toString().getBytes());
- long checkSum1 = checksumCalculator.getValue();
- checksumCalculator.reset();
- checksumCalculator.update(checkSumString2.toString().getBytes());
- long checkSum2 = checksumCalculator.getValue();
- if(checkSum1 != checkSum2)
- return false;
-
- checkSumString1 = new StringBuffer();
- checkSumString2 = new StringBuffer();
- if(type1.methods != null && type2.methods != null) {
- for(int i = 0; i < type1.methods.size(); i++) {
- checkSumString1.append(new String(((InferredMethod)type1.methods.get(i)).name));
- checkSumString2.append(new String(((InferredMethod)type2.methods.get(i)).name));
- }
- }
-
- checksumCalculator.reset();
- checksumCalculator.update(checkSumString1.toString().getBytes());
- checkSum1 = checksumCalculator.getValue();
- checksumCalculator.reset();
- checksumCalculator.update(checkSumString2.toString().getBytes());
- checkSum2 = checksumCalculator.getValue();
- if(checkSum1 != checkSum2)
- return false;
- }
- return true;
- }
-
- public TypeBinding reconcileAnonymous(TypeBinding other) {
- if (!(other instanceof SourceTypeBinding))
- return null;
- SourceTypeBinding otherBinding = (SourceTypeBinding) other;
- 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)
- 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)
- return null;
- }
- }
-
- return this;
- }
-}
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
deleted file mode 100644
index 0ddeb7a9..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/TagBits.java
+++ /dev/null
@@ -1,72 +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.compiler.lookup;
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode;
-
-public interface TagBits {
-
- // Tag bits in the tagBits int of every TypeBinding
- long IsArrayType = ASTNode.Bit1;
- long IsBaseType = ASTNode.Bit2;
- long IsNestedType = ASTNode.Bit3;
- long IsMemberType = ASTNode.Bit4;
- long MemberTypeMask = IsNestedType | IsMemberType;
- long IsLocalType = ASTNode.Bit5;
- long LocalTypeMask = IsNestedType | IsLocalType;
- long IsAnonymousType = ASTNode.Bit6;
- long AnonymousTypeMask = LocalTypeMask | IsAnonymousType;
- long IsBinaryBinding = ASTNode.Bit7;
-
- long HasInconsistentHierarchy = ASTNode.Bit8; // for binary type binding only
-
- // for the type cycle hierarchy check used by ClassScope
- long BeginHierarchyCheck = ASTNode.Bit9; // type
- long EndHierarchyCheck = ASTNode.Bit10; // type
- long ContainsNestedTypesInSignature = ASTNode.Bit10; // method
-
- // test bit to see if default abstract methods were computed
- long KnowsDefaultAbstractMethods = ASTNode.Bit11; // type
-
- long IsArgument = ASTNode.Bit11; // local
- long ClearPrivateModifier = ASTNode.Bit11; // constructor binding
-
- // test bits to see if parts of binary types are faulted
- long AreFieldsSorted = ASTNode.Bit13;
- long AreFieldsComplete = ASTNode.Bit14; // sorted and all resolved
- long AreMethodsSorted = ASTNode.Bit15;
- long AreMethodsComplete = ASTNode.Bit16; // sorted and all resolved
-
- // test bit to avoid asking a type for a member type (includes inherited member types)
- long HasNoMemberTypes = ASTNode.Bit17;
-
- // test bit to identify if the type's hierarchy is inconsistent
- long HierarchyHasProblems = ASTNode.Bit18;
-
- // used by BinaryTypeBinding
- long HasUnresolvedTypeVariables = ASTNode.Bit25;
- long HasUnresolvedSuperclass = ASTNode.Bit26;
- long HasUnresolvedSuperinterfaces = ASTNode.Bit27;
- long HasUnresolvedEnclosingType = ASTNode.Bit28;
- long HasUnresolvedMemberTypes = ASTNode.Bit29;
-
- long DefaultValueResolved = ASTNode.Bit52L;
-
- // set when type contains non-private constructor(s)
- long HasNonPrivateConstructor = ASTNode.Bit53L;
- long IsConstructor = ASTNode.Bit54L;
-
- long IsInferredJsDocType = ASTNode.Bit55L;
- long IsInferredType = ASTNode.Bit56L;
- long IsObjectLiteralType = ASTNode.Bit57L;
-
-
-}
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
deleted file mode 100644
index 43cb7136..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/TypeBinding.java
+++ /dev/null
@@ -1,487 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.lookup;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-
-/*
- * Not all fields defined by this type (& its subclasses) are initialized when it is created.
- * Some are initialized only when needed.
- *
- * Accessors have been provided for some public fields so all TypeBindings have the same API...
- * but access public fields directly whenever possible.
- * Non-public fields have accessors which should be used everywhere you expect the field to be initialized.
- *
- * null is NOT a valid value for a non-public field... it just means the field is not initialized.
- */
-abstract public class TypeBinding extends Binding {
-
- public int id = TypeIds.NoId;
- public long tagBits = 0; // See values in the interface TagBits below
-
- /** Base type definitions */
- public final static BaseTypeBinding INT = new BaseTypeBinding(
- TypeIds.T_int, TypeConstants.INT, new char[] { 'I' });
-
- public final static BaseTypeBinding SHORT = new BaseTypeBinding(
- TypeIds.T_short, TypeConstants.SHORT, new char[] { 'S' });
-
- public final static BaseTypeBinding CHAR = new BaseTypeBinding(
- TypeIds.T_char, TypeConstants.CHAR, new char[] { 'C' });
-
- public final static BaseTypeBinding LONG = new BaseTypeBinding(
- TypeIds.T_long, TypeConstants.LONG, new char[] { 'J' });
-
- public final static BaseTypeBinding FLOAT = new BaseTypeBinding(
- TypeIds.T_float, TypeConstants.FLOAT, new char[] { 'F' });
-
- public final static BaseTypeBinding DOUBLE = new BaseTypeBinding(
- TypeIds.T_double, TypeConstants.DOUBLE, new char[] { 'D' });
-
- public final static BaseTypeBinding BOOLEAN = new BaseTypeBinding(
- TypeIds.T_boolean, TypeConstants.BOOLEAN, new char[] { 'Z' });
-
- public final static BaseTypeBinding NULL = new BaseTypeBinding(
- TypeIds.T_null, TypeConstants.NULL, new char[] { 'N' }); // N stands
- // for
- // null
- // even
- // if it
- // is
- // never
- // internally
- // used
-
- public final static BaseTypeBinding VOID = new BaseTypeBinding(
- TypeIds.T_void, TypeConstants.VOID, new char[] { 'V' });
-
- public final static BaseTypeBinding UNDEFINED = new BaseTypeBinding(
- TypeIds.T_undefined, TypeConstants.UNDEFINED, new char[] { 'U' }); // N
- // stands
- // for
- // null
- // even
- // if
- // it
- // is
- // never
- // internally
- // used
-
- public final static BaseTypeBinding ANY = new BaseTypeBinding(
- TypeIds.T_any, TypeConstants.ANY, new char[] { 'A' });
- public final static BaseTypeBinding UNKNOWN = new BaseTypeBinding(
- TypeIds.T_any, TypeConstants.ANY, new char[] { 'A' });
-
- /**
- * Match a well-known type id to its binding
- */
- public static final TypeBinding wellKnownType(Scope scope, int id) {
- switch (id) {
- case TypeIds.T_boolean:
- return TypeBinding.BOOLEAN;
- case TypeIds.T_char:
- return TypeBinding.CHAR;
- case TypeIds.T_short:
- return TypeBinding.SHORT;
- case TypeIds.T_double:
- return TypeBinding.DOUBLE;
- case TypeIds.T_float:
- return TypeBinding.FLOAT;
- case TypeIds.T_int:
- return TypeBinding.INT;
- case TypeIds.T_long:
- return TypeBinding.LONG;
- case TypeIds.T_JavaLangObject:
- return scope.getJavaLangObject();
- case TypeIds.T_JavaLangString:
- return scope.getJavaLangString();
- default:
- return null;
- }
- }
-
- /*
- * Answer true if the receiver can be instantiated
- */
- public boolean canBeInstantiated() {
- return !isBaseType();
- }
-
- /**
- * Answer the receiver's constant pool name. NOTE: This method should only
- * be used during/after code gen. e.g. 'java/lang/Object'
- */
- public abstract char[] constantPoolName();
-
- public String debugName() {
- return new String(readableName());
- }
-
- /*
- * Answer the receiver's dimensions - 0 for non-array types
- */
- public int dimensions() {
- return 0;
- }
-
- /*
- * Answer the receiver's enclosing type... null if the receiver is a top
- * level type.
- */
- public ReferenceBinding enclosingType() {
- return null;
- }
-
- /**
- * Find supertype which erases to a given well-known type, or null if not
- * found (using id avoids triggering the load of well-known type: 73740)
- * NOTE: only works for erasures of well-known types, as random other types
- * may share same id though being distincts.
- *
- */
- public ReferenceBinding findSuperTypeErasingTo(int wellKnownErasureID,
- boolean erasureIsClass) {
-
- if (!(this instanceof ReferenceBinding))
- return null;
- ReferenceBinding reference = (ReferenceBinding) this;
-
- // do not allow type variables to match with erasures for free
- if (reference.id == wellKnownErasureID
- || (this.id == wellKnownErasureID))
- return reference;
-
- ReferenceBinding currentType = reference;
- // iterate superclass to avoid recording interfaces if searched
- // supertype is class
- if (erasureIsClass) {
- while ((currentType = currentType.superclass()) != null) {
- if (currentType.id == wellKnownErasureID
- || (currentType.id == wellKnownErasureID))
- return currentType;
- }
- return null;
- }
-// ReferenceBinding[] interfacesToVisit = null;
-// int nextPosition = 0;
-// do {
-// } while ((currentType = currentType.superclass()) != null);
-//
-// for (int i = 0; i < nextPosition; i++) {
-// currentType = interfacesToVisit[i];
-// if (currentType.id == wellKnownErasureID
-// || (currentType.id == wellKnownErasureID))
-// return currentType;
-// }
- return null;
- }
-
- /**
- * Find supertype which erases to a given type, or null if not found
- */
- public TypeBinding findSuperTypeWithSameErasure(TypeBinding otherType) {
- if (this == otherType)
- return this;
- if (otherType == null)
- return null;
- switch (kind()) {
- case Binding.ARRAY_TYPE:
- ArrayBinding arrayType = (ArrayBinding) this;
- int otherDim = otherType.dimensions();
- if (arrayType.dimensions != otherDim) {
- switch (otherType.id) {
- case TypeIds.T_JavaLangObject:
- return otherType;
- }
- if (otherDim < arrayType.dimensions
- && otherType.leafComponentType().id == TypeIds.T_JavaLangObject) {
- return otherType; // X[][] has Object[] as an implicit
- // supertype
- }
- return null;
- }
- if (!(arrayType.leafComponentType instanceof ReferenceBinding))
- return null;
- TypeBinding leafSuperType = arrayType.leafComponentType
- .findSuperTypeWithSameErasure(otherType.leafComponentType());
- if (leafSuperType == null)
- return null;
- return arrayType.environment().createArrayType(leafSuperType,
- arrayType.dimensions);
-
- case Binding.TYPE:
- if (this == otherType || (this == otherType))
- return this;
-
- ReferenceBinding currentType = (ReferenceBinding) this;
-
- while ((currentType = currentType.superclass()) != null) {
- if (currentType == otherType || (currentType == otherType))
- return currentType;
- }
- return null;
- }
- return null;
- }
-
- /**
- * Returns the type to use for generic cast, or null if none required
- */
- public TypeBinding genericCast(TypeBinding otherType) {
- if (this == otherType)
- return null;
- return otherType;
- }
-
- public abstract PackageBinding getPackage();
-
- public final boolean isAnonymousType() {
- return (this.tagBits & TagBits.IsAnonymousType) != 0;
- }
-
- public final boolean isObjectLiteralType() {
- return (this.tagBits & TagBits.IsObjectLiteralType) != 0;
- }
-
- /*
- * Answer true if the receiver is an array
- */
- public final boolean isArrayType() {
- return (this.tagBits & TagBits.IsArrayType) != 0;
- }
-
- /*
- * Answer true if the receiver is a base type
- */
- public final boolean isBaseType() {
- return (this.tagBits & TagBits.IsBaseType) != 0;
- }
-
- public boolean isBasicType() {
- if ((this.tagBits & TagBits.IsBaseType) != 0)
- return true;
- return id <= TypeIds.T_last_basic;
- }
-
- public boolean isClass() {
- return false;
- }
-
- /*
- * Answer true if the receiver type can be assigned to the argument type
- * (right)
- */
- public abstract boolean isCompatibleWith(TypeBinding right);
-
- /**
- * 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;
- }
-
- /*
- * Answer true if the receiver's hierarchy has problems (always false for
- * arrays & base types)
- */
- public final boolean isHierarchyInconsistent() {
- return (this.tagBits & TagBits.HierarchyHasProblems) != 0;
- }
-
- /**
- * Returns true if a type is intersecting with another one,
- */
- public boolean isIntersectingWith(TypeBinding otherType) {
- return this == otherType;
- }
-
- public final boolean isLocalType() {
- return (this.tagBits & TagBits.IsLocalType) != 0;
- }
-
- public final boolean isMemberType() {
- return (this.tagBits & TagBits.IsMemberType) != 0;
- }
-
- public final boolean isNestedType() {
- return (this.tagBits & TagBits.IsNestedType) != 0;
- }
-
- public final boolean isAnyType() {
- return id == TypeIds.T_any;
- }
-
- public final boolean isNumericType() {
- switch (id) {
- case TypeIds.T_int:
- case TypeIds.T_float:
- case TypeIds.T_double:
- case TypeIds.T_short:
- case TypeIds.T_long:
- case TypeIds.T_char:
- return true;
- default:
- return false;
- }
- }
-
- /**
- * Returns true if the two types are statically known to be different at
- * compile-time, e.g. a type variable is not provably known to be distinct
- * from another type
- */
- public boolean isProvablyDistinctFrom(TypeBinding otherType, int depth) {
- if (this == otherType)
- return false;
- if (depth > 1)
- return true;
- return this != otherType;
- }
-
- /**
- * JLS(3) 4.7. Note: Foo<?>.Bar is also reifiable
- */
- public boolean isReifiable() {
-
- TypeBinding leafType = leafComponentType();
- if (!(leafType instanceof ReferenceBinding))
- return true;
- ReferenceBinding current = (ReferenceBinding) leafType;
- do {
- if (current.isStatic())
- return true;
- if (current.isLocalType()) {
- // NestedTypeBinding nestedType = (NestedTypeBinding)
- // current.erasure();
- // if (nestedType.scope.methodScope().isStatic) return true;
- return true;
- }
- } while ((current = current.enclosingType()) != null);
- return true;
- }
-
- /**
- * Returns true if a given type may be thrown
- */
- public boolean isThrowable() {
- return false;
- }
-
- // JLS3: 4.5.1.1
- public boolean isTypeArgumentContainedBy(TypeBinding otherType) {
- if (this == otherType)
- return true;
- return false;
- }
-
- /**
- * Returns true if the type is a subclass of java.lang.Error or
- * java.lang.RuntimeException
- */
- public boolean isUncheckedException(boolean includeSupertype) {
- return false;
- }
-
- /*
- * API Answer the receiver's binding type from Binding.BindingID.
- */
- public int kind() {
- return Binding.TYPE;
- }
-
- public TypeBinding leafComponentType() {
- return this;
- }
-
- /**
- * Meant to be invoked on compatible types, to figure if unchecked
- * conversion is necessary
- */
- public boolean needsUncheckedConversion(TypeBinding targetType) {
-
- if (this == targetType)
- return false;
- targetType = targetType.leafComponentType();
- if (!(targetType instanceof ReferenceBinding))
- return false;
-
- TypeBinding currentType = this.leafComponentType();
- TypeBinding match = currentType
- .findSuperTypeWithSameErasure(targetType);
- if (!(match instanceof ReferenceBinding))
- return false;
- return false;
- }
-
- /**
- * Answer the qualified name of the receiver's package separated by periods
- * or an empty string if its the default package.
- *
- * For example, {java.util}.
- */
-
- public char[] qualifiedPackageName() {
- PackageBinding packageBinding = getPackage();
- return packageBinding == null
- || packageBinding.compoundName == CharOperation.NO_CHAR_CHAR ? CharOperation.NO_CHAR
- : packageBinding.readableName();
- }
-
- /**
- * Answer the source name for the type. In the case of member types, as the
- * qualified name from its top level type. For example, for a member type N
- * defined inside M & A: "A.M.N".
- */
-
- public abstract char[] qualifiedSourceName();
-
- /**
- * Answer the receiver classfile signature. Arrays & base types do not
- * distinguish between signature() & constantPoolName(). NOTE: This method
- * should only be used during/after code gen.
- */
- public char[] signature() {
- return constantPoolName();
- }
-
- public abstract char[] sourceName();
-
- public void swapUnresolved(UnresolvedReferenceBinding unresolvedType,
- ReferenceBinding resolvedType, LookupEnvironment environment) {
- // subclasses must override if they wrap another type binding
- }
-
- public boolean isFunctionType() {
- return false;
- }
-
- public char[] getFileName() {
- return new char[] {};
- }
-
- /**
- * Compare two type bindings. If all members of the other bindngs are a
- * member of this type, return this type.
- *
- * @param other
- * @return
- */
- public TypeBinding reconcileAnonymous(TypeBinding other) {
- return null;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/TypeConstants.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/TypeConstants.java
deleted file mode 100644
index f103d52c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/TypeConstants.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.lookup;
-
-// TODO should rename into TypeNames (once extracted last non name constants)
-public interface TypeConstants {
-
- char[] PROTOTYPE = "prototype".toCharArray(); //$NON-NLS-1$
- char[] JAVA = "java".toCharArray(); //$NON-NLS-1$
- char[] SYSTEMJS = "system.js".toCharArray(); //$NON-NLS-1$
- char[] LANG = "lang".toCharArray(); //$NON-NLS-1$
- char[] UTIL = "util".toCharArray(); //$NON-NLS-1$
- char[] REFLECT = "reflect".toCharArray(); //$NON-NLS-1$
- char[] LENGTH = "length".toCharArray(); //$NON-NLS-1$
- char[] GETCLASS = "getClass".toCharArray(); //$NON-NLS-1$
- char[] OBJECT = "Object".toCharArray(); //$NON-NLS-1$
- char[] READRESOLVE = "readResolve".toCharArray(); //$NON-NLS-1$
- char[] WRITEREPLACE = "writeReplace".toCharArray(); //$NON-NLS-1$
- char[] READOBJECT = "readObject".toCharArray(); //$NON-NLS-1$
- char[] WRITEOBJECT = "writeObject".toCharArray(); //$NON-NLS-1$
- char[] CharArray_JAVA_LANG_OBJECT = "java.lang.Object".toCharArray(); //$NON-NLS-1$
- char[] ANONYM_PREFIX = "new ".toCharArray(); //$NON-NLS-1$
- char[] ANONYM_SUFFIX = "(){}".toCharArray(); //$NON-NLS-1$
- char[] SHORT = "short".toCharArray(); //$NON-NLS-1$
- char[] INT = "int".toCharArray(); //$NON-NLS-1$
- char[] LONG = "long".toCharArray(); //$NON-NLS-1$
- char[] FLOAT = "float".toCharArray(); //$NON-NLS-1$
- char[] DOUBLE = "double".toCharArray(); //$NON-NLS-1$
- char[] CHAR = "char".toCharArray(); //$NON-NLS-1$
- char[] BOOLEAN = "boolean".toCharArray(); //$NON-NLS-1$
- char[] NULL = "null".toCharArray(); //$NON-NLS-1$
- char[] VOID = "void".toCharArray(); //$NON-NLS-1$
- char[] VALUE = "value".toCharArray(); //$NON-NLS-1$
- char[] VALUES = "values".toCharArray(); //$NON-NLS-1$
- char[] VALUEOF = "valueOf".toCharArray(); //$NON-NLS-1$
- char[] UPPER_SOURCE = "SOURCE".toCharArray(); //$NON-NLS-1$
- char[] UPPER_CLASS = "CLASS".toCharArray(); //$NON-NLS-1$
- char[] UPPER_RUNTIME = "RUNTIME".toCharArray(); //$NON-NLS-1$
- char[] TYPE = "TYPE".toCharArray(); //$NON-NLS-1$
- char[] UPPER_FIELD = "FIELD".toCharArray(); //$NON-NLS-1$
- char[] UPPER_METHOD = "METHOD".toCharArray(); //$NON-NLS-1$
- char[] UPPER_PARAMETER = "PARAMETER".toCharArray(); //$NON-NLS-1$
- char[] UPPER_CONSTRUCTOR = "CONSTRUCTOR".toCharArray(); //$NON-NLS-1$
- char[] UPPER_LOCAL_VARIABLE = "LOCAL_VARIABLE".toCharArray(); //$NON-NLS-1$
- char[] UPPER_PACKAGE = "PACKAGE".toCharArray(); //$NON-NLS-1$
- char[] UNDEFINED = "undefined".toCharArray(); //$NON-NLS-1$
- char[] ANY = "any".toCharArray(); //$NON-NLS-1$
-
- // Constant compound names
- char[][] JAVA_LANG = {JAVA, LANG};
- char[][] JAVA_LANG_ASSERTIONERROR = {JAVA, LANG, "AssertionError".toCharArray()}; //$NON-NLS-1$
- char[][] JAVA_LANG_CLASS = {JAVA, LANG, "Class".toCharArray()}; //$NON-NLS-1$
- char[][] JAVA_LANG_EXCEPTION = {JAVA, LANG, "Exception".toCharArray()}; //$NON-NLS-1$
- char[][] JAVA_LANG_ERROR = {JAVA, LANG, "Error".toCharArray()}; //$NON-NLS-1$
- char[][] JAVA_LANG_ILLEGALARGUMENTEXCEPTION = {JAVA, LANG, "IllegalArgumentException".toCharArray()}; //$NON-NLS-1$
- char[][] JAVA_LANG_ITERABLE = {JAVA, LANG, "Iterable".toCharArray()}; //$NON-NLS-1$
- char[][] JAVA_LANG_OBJECT = {/*JAVA, LANG, SYSTEMJS, */OBJECT};
- char[][] JAVA_LANG_STRING = {/*JAVA, LANG, SYSTEMJS,*/ "String".toCharArray()}; //$NON-NLS-1$
- char[][] NUMBER = {/*JAVA, LANG, SYSTEMJS,*/ "Number".toCharArray()}; //$NON-NLS-1$
- char[][] FUNCTION = {/*JAVA, LANG, SYSTEMJS,*/ "Function".toCharArray()}; //$NON-NLS-1$
- char[][] BOOLEAN_OBJECT = {/*JAVA, LANG, SYSTEMJS,*/ "Boolean".toCharArray()}; //$NON-NLS-1$
- char[][] ARRAY = {/*JAVA, LANG, SYSTEMJS, */ "Array".toCharArray()}; //$NON-NLS-1$
- char[][] REGEXP = {/*JAVA, LANG, SYSTEMJS, */ "RegExp".toCharArray()}; //$NON-NLS-1$
- char[][] ERROR = {/*JAVA, LANG, SYSTEMJS,*/ "Error".toCharArray()}; //$NON-NLS-1$
- char[][] JAVA_LANG_SYSTEM = {JAVA, LANG, "System".toCharArray()}; //$NON-NLS-1$
- char[][] JAVA_LANG_RUNTIMEEXCEPTION = {JAVA, LANG, "RuntimeException".toCharArray()}; //$NON-NLS-1$
- char[][] JAVA_LANG_THROWABLE = {JAVA, LANG, "Throwable".toCharArray()}; //$NON-NLS-1$
- char[][] JAVA_LANG_SHORT = {JAVA, LANG, "Short".toCharArray()}; //$NON-NLS-1$
- char[][] JAVA_LANG_CHARACTER = {JAVA, LANG, "Character".toCharArray()}; //$NON-NLS-1$
- char[][] JAVA_LANG_INTEGER = {JAVA, LANG, "Integer".toCharArray()}; //$NON-NLS-1$
- char[][] JAVA_LANG_LONG = {JAVA, LANG, "Long".toCharArray()}; //$NON-NLS-1$
- char[][] JAVA_LANG_FLOAT = {JAVA, LANG, "Float".toCharArray()}; //$NON-NLS-1$
- char[][] JAVA_LANG_DOUBLE = {JAVA, LANG, "Double".toCharArray()}; //$NON-NLS-1$
- char[][] JAVA_LANG_BOOLEAN = {JAVA, LANG, "Boolean".toCharArray()}; //$NON-NLS-1$
- char[][] JAVA_LANG_VOID = {JAVA, LANG, "Void".toCharArray()}; //$NON-NLS-1$
-
- // Constraints for generic type argument inference
- int CONSTRAINT_EQUAL = 0; // Actual = Formal
- int CONSTRAINT_EXTENDS = 1; // Actual << Formal
- int CONSTRAINT_SUPER = 2; // Actual >> Formal
-
- // Constants used to perform bound checks
- int OK = 0;
- int UNCHECKED = 1;
- int MISMATCH = 2;
-
- // Synthetics
- char[] INIT = "<init>".toCharArray(); //$NON-NLS-1$
- char[] CLINIT = "<clinit>".toCharArray(); //$NON-NLS-1$
-
- // synthetic package-info name
- public static final char[] PACKAGE_INFO_NAME = "package-info".toCharArray(); //$NON-NLS-1$
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/TypeIds.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/TypeIds.java
deleted file mode 100644
index 452ad2b3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/TypeIds.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.lookup;
-
-public interface TypeIds {
-
- //base type void null undefined Object String
- //should have an id that is 0<= id <= 15
- // The IDs below must be representable using 4 bits so as to fit in operator signatures.
- final int T_undefined = 0; // should not be changed
- final int T_JavaLangObject = 1;
- final int T_char = 2;
- final int T_short = 4;
- final int T_boolean = 5;
- final int T_void = 6;
- final int T_long = 7;
- final int T_double = 8;
- final int T_float = 9;
- final int T_int = 10;
- final int T_JavaLangString = 11;
- final int T_null = 12;
- final int T_any = 13;
- final int T_function = 14;
-
- final int T_last_basic = 14;
-
-
- //=========end of 4 bits constraint===========
-
- // well-known exception types
- final int T_JavaLangClass = 16;
- final int T_JavaLangStringBuffer = 17;
- final int T_JavaLangSystem = 18;
- final int T_JavaLangError = 19;
- final int T_JavaLangThrowable = 21;
- final int T_JavaLangNoClassDefError = 22;
- final int T_JavaLangClassNotFoundException = 23;
- final int T_JavaLangRuntimeException = 24;
- final int T_JavaLangException = 25;
-
- // wrapper types
- final int T_JavaLangShort = 27;
- final int T_JavaLangCharacter = 28;
- final int T_JavaLangInteger = 29;
- final int T_JavaLangLong = 30;
- final int T_JavaLangFloat = 31;
- final int T_JavaLangDouble = 32;
- final int T_JavaLangBoolean = 33;
- final int T_JavaLangVoid = 34;
-
- // 1.4 features
- final int T_JavaLangAssertionError = 35;
-
- // 1.5 features
- final int T_JavaLangIterable = 38;
- final int T_JavaUtilIterator = 39;
- final int T_JavaLangStringBuilder = 40;
- final int T_JavaLangIllegalArgumentException = 42;
- final int T_JavaLangDeprecated = 44;
- final int T_JavaLangOverride = 47;
- final int T_JavaLangSuppressWarnings = 49;
-
- final int NoId = Integer.MAX_VALUE;
-
- public static final int IMPLICIT_CONVERSION_MASK = 0xFF;
- public static final int COMPILE_TYPE_MASK = 0xF;
-
- // implicit conversions: <compileType> to <runtimeType> (note: booleans are integers at runtime)
- final int Boolean2Int = T_boolean + (T_int << 4);
- final int Boolean2String = T_boolean + (T_JavaLangString << 4);
- final int Boolean2Boolean = T_boolean + (T_boolean << 4);
- final int Short2Short = T_short + (T_short << 4);
- final int Short2Char = T_short + (T_char << 4);
- final int Short2Int = T_short + (T_int << 4);
- final int Short2Long = T_short + (T_long << 4);
- final int Short2Float = T_short + (T_float << 4);
- final int Short2Double = T_short + (T_double << 4);
- final int Short2String = T_short + (T_JavaLangString << 4);
- final int Char2Short = T_char + (T_short << 4);
- final int Char2Char = T_char + (T_char << 4);
- final int Char2Int = T_char + (T_int << 4);
- final int Char2Long = T_char + (T_long << 4);
- final int Char2Float = T_char + (T_float << 4);
- final int Char2Double = T_char + (T_double << 4);
- final int Char2String = T_char + (T_JavaLangString << 4);
- final int Int2Short = T_int + (T_short << 4);
- final int Int2Char = T_int + (T_char << 4);
- final int Int2Int = T_int + (T_int << 4);
- final int Int2Long = T_int + (T_long << 4);
- final int Int2Float = T_int + (T_float << 4);
- final int Int2Double = T_int + (T_double << 4);
- final int Int2String = T_int + (T_JavaLangString << 4);
- final int Long2Short = T_long + (T_short << 4);
- final int Long2Char = T_long + (T_char << 4);
- final int Long2Int = T_long + (T_int << 4);
- final int Long2Long = T_long + (T_long << 4);
- final int Long2Float = T_long + (T_float << 4);
- final int Long2Double = T_long + (T_double << 4);
- final int Long2String = T_long + (T_JavaLangString << 4);
- final int Float2Short = T_float + (T_short << 4);
- final int Float2Char = T_float + (T_char << 4);
- final int Float2Int = T_float + (T_int << 4);
- final int Float2Long = T_float + (T_long << 4);
- final int Float2Float = T_float + (T_float << 4);
- final int Float2Double = T_float + (T_double << 4);
- final int Float2String = T_float + (T_JavaLangString << 4);
- final int Double2Short = T_double + (T_short << 4);
- final int Double2Char = T_double + (T_char << 4);
- final int Double2Int = T_double + (T_int << 4);
- final int Double2Long = T_double + (T_long << 4);
- final int Double2Float = T_double + (T_float << 4);
- final int Double2Double = T_double + (T_double << 4);
- final int Double2String = T_double + (T_JavaLangString << 4);
- final int String2String = T_JavaLangString + (T_JavaLangString << 4);
- final int Object2String = T_JavaLangObject + (T_JavaLangString << 4);
- final int Null2String = T_null + (T_JavaLangString << 4);
- final int Object2Object = T_JavaLangObject + (T_JavaLangObject << 4);
- final int BOXING = 0x200;
- final int UNBOXING = 0x400;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/UnresolvedReferenceBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/UnresolvedReferenceBinding.java
deleted file mode 100644
index 6d0f29aa..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/UnresolvedReferenceBinding.java
+++ /dev/null
@@ -1,72 +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.compiler.lookup;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-
-public class UnresolvedReferenceBinding extends ReferenceBinding {
-
-ReferenceBinding resolvedType;
-TypeBinding[] wrappers;
-
-UnresolvedReferenceBinding(char[][] compoundName, PackageBinding packageBinding) {
- this.compoundName = compoundName;
- this.sourceName = compoundName[compoundName.length - 1]; // reasonable guess
- this.fPackage = packageBinding;
- this.wrappers = null;
-}
-void addWrapper(TypeBinding wrapper, LookupEnvironment environment) {
- if (this.resolvedType != null) {
- // the type reference B<B<T>.M> means a signature of <T:Ljava/lang/Object;>LB<LB<TT;>.M;>;
- // when the ParameterizedType for Unresolved B is created with args B<T>.M, the Unresolved B is resolved before the wrapper is added
- wrapper.swapUnresolved(this, this.resolvedType, environment);
- return;
- }
- if (this.wrappers == null) {
- this.wrappers = new TypeBinding[] {wrapper};
- } else {
- int length = this.wrappers.length;
- System.arraycopy(this.wrappers, 0, this.wrappers = new TypeBinding[length + 1], 0, length);
- this.wrappers[length] = wrapper;
- }
-}
-public String debugName() {
- return toString();
-}
-ReferenceBinding resolve(LookupEnvironment environment, boolean convertGenericToRawType) {
- ReferenceBinding targetType = this.resolvedType;
- if (targetType == null) {
- targetType = this.fPackage.getType0(this.compoundName[this.compoundName.length - 1]);
- if (targetType == this)
- targetType = environment.askForType(this.compoundName);
- if (targetType == null || targetType == this) { // could not resolve any better, error was already reported against it
- // create a proxy for the missing BinaryType
- targetType = environment.cacheMissingBinaryType(this.compoundName, null);
- }
- setResolvedType(targetType, environment);
- }
- return targetType;
-}
-void setResolvedType(ReferenceBinding targetType, LookupEnvironment environment) {
- if (this.resolvedType == targetType) return; // already resolved
-
- // targetType may be a source or binary type
- this.resolvedType = targetType;
- // must ensure to update any other type bindings that can contain the resolved type
- // otherwise we could create 2 : 1 for this unresolved type & 1 for the resolved type
- if (this.wrappers != null)
- for (int i = 0, l = this.wrappers.length; i < l; i++)
- this.wrappers[i].swapUnresolved(this, targetType, environment);
-}
-public String toString() {
- return "Unresolved type " + ((compoundName != null) ? CharOperation.toString(compoundName) : "UNNAMED"); //$NON-NLS-1$ //$NON-NLS-2$
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/UpdatedMethodBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/UpdatedMethodBinding.java
deleted file mode 100644
index 0bd609fc..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/UpdatedMethodBinding.java
+++ /dev/null
@@ -1,25 +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.compiler.lookup;
-
-public class UpdatedMethodBinding extends MethodBinding {
-
- public TypeBinding updatedDeclaringClass;
-
- public UpdatedMethodBinding(TypeBinding updatedDeclaringClass, int modifiers, char[] selector, TypeBinding returnType, TypeBinding[] args, ReferenceBinding declaringClass) {
- super(modifiers, selector, returnType, args, declaringClass);
- this.updatedDeclaringClass = updatedDeclaringClass;
- }
-
- public TypeBinding constantPoolDeclaringClass() {
- return this.updatedDeclaringClass;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/VariableBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/VariableBinding.java
deleted file mode 100644
index ec9b8520..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/VariableBinding.java
+++ /dev/null
@@ -1,42 +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.compiler.lookup;
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.AbstractVariableDeclaration;
-
-public abstract class VariableBinding extends Binding {
-
- public int modifiers;
- public TypeBinding type;
- public char[] name;
- public int id; // for flow-analysis (position in flowInfo bit vector)
- public long tagBits;
-
- public VariableBinding(char[] name, TypeBinding type, int modifiers) {
- this.name = name;
- this.type = type;
- this.modifiers = modifiers;
- }
-
- public char[] readableName() {
- return name;
- }
-
- public String toString() {
- String s = (type != null) ? type.debugName() : "UNDEFINED TYPE"; //$NON-NLS-1$
- s += " "; //$NON-NLS-1$
- s += (name != null) ? new String(name) : "UNNAMED FIELD"; //$NON-NLS-1$
- return s;
- }
-
- public abstract boolean isFor(
- AbstractVariableDeclaration variableDeclaration);
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/WithScope.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/WithScope.java
deleted file mode 100644
index d6d42744..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/WithScope.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.lookup;
-
-
-public class WithScope extends BlockScope {
- public ReferenceBinding referenceContext;
-
- public WithScope( Scope parent, ReferenceBinding context) {
- super(WITH_SCOPE, parent);
- this.referenceContext=context;
- }
-
-
-
-}
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
deleted file mode 100644
index 50eebd21..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/messages.properties
+++ /dev/null
@@ -1,63 +0,0 @@
-###############################################################################
-# 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
-###############################################################################
-### Eclipse Java Core Compiler messages.
-
-### compilation
-compilation_unresolvedProblem = Unresolved validation problem: \n
-compilation_unresolvedProblems = Unresolved validation problems: \n
-compilation_request = [parsing {2} - #{0}/{1}]
-compilation_loadBinary = [reading {0}.class]
-compilation_process = [analyzing {2} - #{0}/{1}]
-compilation_write = [writing {1} - #{0}]
-compilation_done = [completed {2} - #{0}/{1}]
-compilation_units = [{0} units compiled]
-compilation_unit = [{0} unit compiled]
-compilation_internalError = Internal validation error
-
-### output
-output_isFile = Regular file {0} cannot be used as output directory
-output_notValidAll = Could not create output directory {0}
-output_notValid = Could not create subdirectory {0} into output directory {1}
-
-### problem
-problem_noSourceInformation =
-problem_atLine = (at line {0})
-
-### abort
-abort_invalidAttribute = SANITY CHECK: Invalid attribute for local variable {0}
-abort_invalidExceptionAttribute = SANITY CHECK: Invalid attribute for exception attribute for {0}
-abort_missingCode = Missing code implementation in the compiler
-abort_againstSourceModel = Cannot compile against source model {0} issued from {1}
-
-### accept
-accept_cannot = Cannot accept the JavaScript unit:
-
-### parser
-parser_incorrectPath = The path for the javadcl.js file is incorrect
-parser_moveFiles = MOVE FILES IN THE Runtime DIRECTORY OF Parser.class
-parser_syntaxRecovery = SYNTAX RECOVERY
-parser_regularParse = REGULAR PARSE
-parser_missingFile = missing file {0}
-parser_corruptedFile = corrupted file {0}
-parser_endOfFile = end of file
-parser_endOfConstructor = end of constructor
-parser_endOfMethod = end of function
-parser_endOfInitializer = end of initializer
-
-### ast
-ast_missingCode = Missing code gen implementation
-
-### constant
-constant_cannotCastedInto = {0} constant cannot be casted into {1}
-constant_cannotConvertedTo = {0} constant cannot be converted to {1}
-Scanner_NON_TERM_REGEXP=Non Terminating Regular Expression
-Scanner_INVALID_REGEXP_OPT=Invalid Regular Expression Options
-Scanner_UNEXP_REGEXP=Unexpected Error Processing Regular Expression
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
deleted file mode 100644
index 32ff909d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/AbstractCommentParser.java
+++ /dev/null
@@ -1,1511 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.parser;
-
-import java.util.ArrayList;
-import java.util.List;
-
-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.util.Util;
-
-/**
- * Parser specialized for decoding javadoc comments
- */
-public abstract class AbstractCommentParser implements JavadocTagConstants {
-
- // Kind of comment parser
- public final static int COMPIL_PARSER = 1;
- public final static int DOM_PARSER = 2;
- public final static int SELECTION_PARSER = 3;
- public final static int COMPLETION_PARSER = 4;
- public final static int SOURCE_PARSER = 5;
- protected final static int PARSER_KIND = 0x00FF;
- protected final static int TEXT_PARSE = 0x0100; // flag saying that text must be stored
- protected final static int TEXT_VERIF = 0x0200; // flag saying that text must be verified
-
- // Parser recovery states
- protected final static int QUALIFIED_NAME_RECOVERY = 1;
- protected final static int ARGUMENT_RECOVERY= 2;
- protected final static int ARGUMENT_TYPE_RECOVERY = 3;
- protected final static int EMPTY_ARGUMENT_RECOVERY = 4;
-
- // Parse infos
- public Scanner scanner;
- public char[] source;
- protected Parser sourceParser;
- protected int currentTokenType = -1;
-
- // Options
- public boolean checkDocComment = true;
- public boolean reportProblems;
- protected long complianceLevel;
- protected long sourceLevel;
-
- // Results
- protected long inheritedPositions;
- protected boolean deprecated;
- protected Object returnStatement;
-
- // Positions
- protected int javadocStart, javadocEnd;
- protected int firstTagPosition;
- protected int index, lineEnd;
- protected int tokenPreviousPosition, lastIdentifierEndPosition, starPosition;
- protected int textStart, memberStart;
- protected int tagSourceStart, tagSourceEnd;
- protected int inlineTagStart;
- protected int[] lineEnds;
-
- // Flags
- protected boolean lineStarted = false;
- protected boolean inlineTagStarted = false;
- protected boolean abort = false;
- protected int kind;
- protected int tagValue = NO_TAG_VALUE;
-
- // Line pointers
- private int linePtr, lastLinePtr;
-
- // Identifier stack
- protected int identifierPtr;
- protected char[][] identifierStack;
- protected int identifierLengthPtr;
- protected int[] identifierLengthStack;
- protected long[] identifierPositionStack;
-
- // Ast stack
- protected final static int AST_STACK_INCREMENT = 10;
- protected int astPtr;
- protected Object[] astStack;
- protected int astLengthPtr;
- protected int[] astLengthStack;
-
- protected AbstractCommentParser(Parser sourceParser) {
- this.sourceParser = sourceParser;
- this.scanner = new Scanner(false, false, false, ClassFileConstants.JDK1_3, null, null, true/*taskCaseSensitive*/);
- this.identifierStack = new char[20][];
- this.identifierPositionStack = new long[20];
- this.identifierLengthStack = new int[10];
- this.astStack = new Object[30];
- this.astLengthStack = new int[20];
- this.reportProblems = sourceParser != null;
- if (sourceParser != null) {
- this.checkDocComment = this.sourceParser.options.docCommentSupport;
- this.sourceLevel = this.sourceParser.options.sourceLevel;
- this.scanner.sourceLevel = this.sourceLevel;
- this.complianceLevel = this.sourceParser.options.complianceLevel;
- }
- }
-
- /* (non-Javadoc)
- * Returns true if tag @deprecated is present in javadoc comment.
- *
- * If javadoc checking is enabled, will also construct an Javadoc node, which will be stored into Parser.javadoc
- * slot for being consumed later on.
- */
- protected boolean commentParse() {
-
- boolean validComment = true;
- try {
- // Init scanner position
- this.linePtr = getLineNumber(this.firstTagPosition);
- int realStart = this.linePtr==1 ? javadocStart : this.scanner.getLineEnd(this.linePtr-1)+1;
- if (realStart < javadocStart) realStart = javadocStart;
- this.scanner.resetTo(realStart, javadocEnd);
- this.index = realStart;
- if (realStart == javadocStart) {
- readChar(); // starting '/'
- readChar(); // first '*'
- }
- int previousPosition = this.index;
- char nextCharacter = 0;
- if (realStart == javadocStart) nextCharacter = readChar(); // second '*'
-
- // Init local variables
- this.astLengthPtr = -1;
- this.astPtr = -1;
- this.identifierPtr = -1;
- this.currentTokenType = -1;
- this.inlineTagStarted = false;
- this.inlineTagStart = -1;
- this.lineStarted = false;
- this.returnStatement = null;
- this.inheritedPositions = -1;
- this.deprecated = false;
- this.lastLinePtr = getLineNumber(javadocEnd);
- this.lineEnd = (this.linePtr == this.lastLinePtr) ? this.javadocEnd: this.scanner.getLineEnd(this.linePtr) - 1;
- this.textStart = -1;
- char previousChar = 0;
- int invalidTagLineEnd = -1;
- int invalidInlineTagLineEnd = -1;
- boolean pushText = (this.kind & TEXT_PARSE) != 0;
- boolean verifText = (this.kind & TEXT_VERIF) != 0;
- boolean isDomParser = (this.kind & DOM_PARSER) != 0;
-
- // Loop on each comment character
- while (!abort && this.index < this.javadocEnd) {
- previousPosition = this.index;
- previousChar = nextCharacter;
-
- // Calculate line end (cannot use this.scanner.linePtr as scanner does not parse line ends again)
- if (this.index > (this.lineEnd+1)) {
- updateLineEnd();
- }
-
- // Read next char only if token was consumed
- if (this.currentTokenType < 0) {
- nextCharacter = readChar(); // consider unicodes
- } else {
- previousPosition = this.scanner.getCurrentTokenStartPosition();
- switch (this.currentTokenType) {
- case TerminalTokens.TokenNameRBRACE:
- nextCharacter = '}';
- break;
- case TerminalTokens.TokenNameMULTIPLY:
- nextCharacter = '*';
- break;
- default:
- nextCharacter = this.scanner.currentCharacter;
- }
- consumeToken();
- }
-
- if (this.index >= this.javadocEnd) {
- break;
- }
-
- switch (nextCharacter) {
- case '@' :
- // Start tag parsing only if we are on line beginning or at inline tag beginning
- if ((!this.lineStarted || previousChar == '{')) {
- if (this.inlineTagStarted) {
- this.inlineTagStarted = false;
- // bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=53279
- // Cannot have @ inside inline comment
- if (this.reportProblems) {
- int end = previousPosition<invalidInlineTagLineEnd ? previousPosition : invalidInlineTagLineEnd;
- this.sourceParser.problemReporter().javadocUnterminatedInlineTag(this.inlineTagStart, end);
- }
- validComment = false;
- if (this.textStart != -1 && this.textStart < previousPosition) {
- if (pushText) pushText(this.textStart, previousPosition);
- }
- if (isDomParser) refreshInlineTagPosition(previousPosition);
- }
- if (previousChar == '{') {
- if (this.textStart != -1 && this.textStart < this.inlineTagStart) {
- if (pushText) pushText(this.textStart, this.inlineTagStart);
- }
- this.inlineTagStarted = true;
- invalidInlineTagLineEnd = this.lineEnd;
- } else if (this.textStart != -1 && this.textStart < invalidTagLineEnd) {
- if (pushText) pushText(this.textStart, invalidTagLineEnd);
- }
- this.scanner.resetTo(this.index, this.javadocEnd);
- this.currentTokenType = -1; // flush token cache at line begin
- try {
- if (!parseTag(previousPosition)) {
- // bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=51600
- // do not stop the inline tag when error is encountered to get text after
- validComment = false;
- // bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=51600
- // for DOM AST node, store tag as text in case of invalid syntax
- if (isDomParser) {
- createTag();
- }
- this.textStart = this.tagSourceEnd+1;
- invalidTagLineEnd = this.lineEnd;
- }
- } catch (InvalidInputException e) {
- consumeToken();
- }
- } else if (verifText && (this.tagValue == TAG_RETURN_VALUE || this.tagValue == TAG_RETURNS_VALUE) && this.returnStatement != null) {
- refreshReturnStatement();
- }
- this.lineStarted = true;
- break;
- case '\r':
- case '\n':
- if (this.lineStarted && this.textStart < previousPosition) {
- if (pushText) pushText(this.textStart, previousPosition);
- }
- this.lineStarted = false;
- // Fix bug 51650
- this.textStart = -1;
- break;
- case '}' :
- if (verifText && (this.tagValue == TAG_RETURN_VALUE || this.tagValue == TAG_RETURNS_VALUE) && this.returnStatement != null) {
- refreshReturnStatement();
- }
- if (this.inlineTagStarted) {
- if (pushText) {
- if (this.lineStarted && this.textStart != -1 && this.textStart < previousPosition) {
- pushText(this.textStart, previousPosition);
- }
- refreshInlineTagPosition(previousPosition);
- }
- this.textStart = this.index;
- this.inlineTagStarted = false;
- } else {
- if (!this.lineStarted) {
- this.textStart = previousPosition;
- }
- }
- this.lineStarted = true;
- break;
- case '{' :
- if (verifText && (this.tagValue == TAG_RETURN_VALUE || this.tagValue == TAG_RETURNS_VALUE) && this.returnStatement != null) {
- refreshReturnStatement();
- }
- if (this.inlineTagStarted) {
- this.inlineTagStarted = false;
- // bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=53279
- // Cannot have opening brace in inline comment
- if (this.reportProblems) {
- int end = previousPosition<invalidInlineTagLineEnd ? previousPosition : invalidInlineTagLineEnd;
- this.sourceParser.problemReporter().javadocUnterminatedInlineTag(this.inlineTagStart, end);
- }
- if (pushText) {
- if (this.lineStarted && this.textStart != -1 && this.textStart < previousPosition) {
- pushText(this.textStart, previousPosition);
- }
- refreshInlineTagPosition(previousPosition);
- }
- }
- if (!this.lineStarted) {
- this.textStart = previousPosition;
- }
- this.lineStarted = true;
- this.inlineTagStart = previousPosition;
- break;
- case '*' :
- case '\u000c' : /* FORM FEED */
- case ' ' : /* SPACE */
- case '\t' : /* HORIZONTAL TABULATION */
- // do nothing for space or '*' characters
- break;
- default :
- if (verifText && (this.tagValue == TAG_RETURN_VALUE || this.tagValue == TAG_RETURNS_VALUE) && this.returnStatement != null) {
- refreshReturnStatement();
- }
- if (!this.lineStarted) {
- this.textStart = previousPosition;
- }
- this.lineStarted = true;
- break;
- }
- }
- // bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=53279
- // Cannot leave comment inside inline comment
- if (this.inlineTagStarted) {
- this.inlineTagStarted = false;
- if (this.reportProblems) {
- int end = previousPosition<invalidInlineTagLineEnd ? previousPosition : invalidInlineTagLineEnd;
- if (this.index >= this.javadocEnd) end = invalidInlineTagLineEnd;
- this.sourceParser.problemReporter().javadocUnterminatedInlineTag(this.inlineTagStart, end);
- }
- if (pushText) {
- if (this.lineStarted && this.textStart != -1 && this.textStart < previousPosition) {
- pushText(this.textStart, previousPosition);
- }
- refreshInlineTagPosition(previousPosition);
- }
- } else if (pushText && this.lineStarted && this.textStart < previousPosition) {
- pushText(this.textStart, previousPosition);
- }
- updateDocComment();
- } catch (Exception ex) {
- validComment = false;
- }
- return validComment;
- }
-
- protected void consumeToken() {
- this.currentTokenType = -1; // flush token cache
- updateLineEnd();
- }
-
- protected abstract Object createArgumentReference(char[] name, int dim, boolean isVarargs, Object typeRef, long[] dimPos, long argNamePos) throws InvalidInputException;
- protected abstract Object createFieldReference(Object receiver) throws InvalidInputException;
- protected abstract Object createMethodReference(Object receiver, List arguments) throws InvalidInputException;
- protected Object createReturnStatement() { return null; }
- protected abstract void createTag();
- protected abstract Object createTypeReference(int primitiveToken);
-
- /**
- * Search the line number corresponding to a specific position.
- * Warning: returned position is 1-based index!
- * @see Scanner#getLineNumber(int) We cannot directly use this method
- * when linePtr field is not initialized.
- */
- private int getLineNumber(int position) {
-
- if (this.scanner.linePtr != -1) {
- return Util.getLineNumber(position, this.scanner.lineEnds, 0, this.scanner.linePtr);
- }
- if (this.lineEnds == null)
- return 1;
- return Util.getLineNumber(position, this.lineEnds, 0, this.lineEnds.length-1);
- }
-
- private int getTokenEndPosition() {
- if (this.scanner.getCurrentTokenEndPosition() > this.lineEnd) {
- return this.lineEnd;
- } else {
- return this.scanner.getCurrentTokenEndPosition();
- }
- }
-
- /**
- * @return Returns the currentTokenType.
- */
- protected int getCurrentTokenType() {
- return currentTokenType;
- }
-
- /*
- * Parse argument in @see tag method reference
- */
- protected Object parseArguments(Object receiver) throws InvalidInputException {
-
- // Init
- int modulo = 0; // should be 2 for (Type,Type,...) or 3 for (Type arg,Type arg,...)
- int iToken = 0;
- char[] argName = null;
- List arguments = new ArrayList(10);
- int start = this.scanner.getCurrentTokenStartPosition();
- Object typeRef = null;
- int dim = 0;
- boolean isVarargs = false;
- long[] dimPositions = new long[20]; // assume that there won't be more than 20 dimensions...
- char[] name = null;
- long argNamePos = -1;
-
- // Parse arguments declaration if method reference
- nextArg : while (this.index < this.scanner.eofPosition) {
-
- // Read argument type reference
- try {
- typeRef = parseQualifiedName(false);
- if (this.abort) return null; // May be aborted by specialized parser
- } catch (InvalidInputException e) {
- break nextArg;
- }
- boolean firstArg = modulo == 0;
- if (firstArg) { // verify position
- if (iToken != 0)
- break nextArg;
- } else if ((iToken % modulo) != 0) {
- break nextArg;
- }
- if (typeRef == null) {
- if (firstArg && this.currentTokenType == TerminalTokens.TokenNameRPAREN) {
- // verify characters after arguments declaration (expecting white space or end comment)
- if (!verifySpaceOrEndComment()) {
- int end = this.starPosition == -1 ? this.lineEnd : this.starPosition;
- if (this.source[end]=='\n') end--;
- if (this.reportProblems) this.sourceParser.problemReporter().javadocMalformedSeeReference(start, end);
- return null;
- }
- this.lineStarted = true;
- return createMethodReference(receiver, null);
- }
- break nextArg;
- }
- iToken++;
-
- // Read possible additional type info
- dim = 0;
- isVarargs = false;
- if (readToken() == TerminalTokens.TokenNameLBRACKET) {
- // array declaration
- int dimStart = this.scanner.getCurrentTokenStartPosition();
- while (readToken() == TerminalTokens.TokenNameLBRACKET) {
- consumeToken();
- if (readToken() != TerminalTokens.TokenNameRBRACKET) {
- break nextArg;
- }
- consumeToken();
- dimPositions[dim++] = (((long) dimStart) << 32) + this.scanner.getCurrentTokenEndPosition();
- }
-// } else if (readToken() == TerminalTokens.TokenNameELLIPSIS) {
-// // ellipsis declaration
-// int dimStart = this.scanner.getCurrentTokenStartPosition();
-// dimPositions[dim++] = (((long) dimStart) << 32) + this.scanner.getCurrentTokenEndPosition();
-// consumeToken();
-// isVarargs = true;
- }
-
- // Read argument name
- argNamePos = -1;
- if (readToken() == TerminalTokens.TokenNameIdentifier) {
- consumeToken();
- if (firstArg) { // verify position
- if (iToken != 1)
- break nextArg;
- } else if ((iToken % modulo) != 1) {
- break nextArg;
- }
- if (argName == null) { // verify that all arguments name are declared
- if (!firstArg) {
- break nextArg;
- }
- }
- argName = this.scanner.getCurrentIdentifierSource();
- argNamePos = (((long)this.scanner.getCurrentTokenStartPosition())<<32)+this.scanner.getCurrentTokenEndPosition();
- iToken++;
- } else if (argName != null) { // verify that no argument name is declared
- break nextArg;
- }
-
- // Verify token position
- if (firstArg) {
- modulo = iToken + 1;
- } else {
- if ((iToken % modulo) != (modulo - 1)) {
- break nextArg;
- }
- }
-
- // Read separator or end arguments declaration
- int token = readToken();
- name = argName == null ? CharOperation.NO_CHAR : argName;
- if (token == TerminalTokens.TokenNameCOMMA) {
- // Create new argument
- Object argument = createArgumentReference(name, dim, isVarargs, typeRef, dimPositions, argNamePos);
- if (this.abort) return null; // May be aborted by specialized parser
- arguments.add(argument);
- consumeToken();
- iToken++;
- } else if (token == TerminalTokens.TokenNameRPAREN) {
- // verify characters after arguments declaration (expecting white space or end comment)
- if (!verifySpaceOrEndComment()) {
- int end = this.starPosition == -1 ? this.lineEnd : this.starPosition;
- if (this.source[end]=='\n') end--;
- if (this.reportProblems) this.sourceParser.problemReporter().javadocMalformedSeeReference(start, end);
- return null;
- }
- // Create new argument
- Object argument = createArgumentReference(name, dim, isVarargs, typeRef, dimPositions, argNamePos);
- if (this.abort) return null; // May be aborted by specialized parser
- arguments.add(argument);
- consumeToken();
- return createMethodReference(receiver, arguments);
- } else {
- break nextArg;
- }
- }
-
- // Something wrong happened => Invalid input
- throw new InvalidInputException();
- }
-
- /*
- * Parse an URL link reference in @see tag
- */
- private boolean parseHref() throws InvalidInputException {
- int start = this.scanner.getCurrentTokenStartPosition();
- char currentChar = readChar();
- if (currentChar == 'a' || currentChar == 'A') {
- this.scanner.currentPosition = this.index;
- if (readToken() == TerminalTokens.TokenNameIdentifier) {
- consumeToken();
- try {
- if (CharOperation.equals(this.scanner.getCurrentIdentifierSource(), new char[]{'h', 'r', 'e', 'f'}, false) &&
- readToken() == TerminalTokens.TokenNameEQUAL) {
- consumeToken();
- if (readToken() == TerminalTokens.TokenNameStringLiteral) {
- consumeToken();
- // Skip all characters after string literal until closing '>' (see bug 68726)
- while (readToken() != TerminalTokens.TokenNameGREATER) {
- if (this.scanner.currentPosition >= this.scanner.eofPosition || this.scanner.currentCharacter == '@' ||
- (this.inlineTagStarted && this.scanner.currentCharacter == '}')) {
- // Reset position: we want to rescan last token
- this.index = this.tokenPreviousPosition;
- this.scanner.currentPosition = this.tokenPreviousPosition;
- this.currentTokenType = -1;
- // Signal syntax error
- if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidSeeUrlReference(start, this.lineEnd);
-
- return false;
- }
- this.currentTokenType = -1; // do not update line end
- }
- if (this.currentTokenType == TerminalTokens.TokenNameGREATER) {
- consumeToken(); // update line end as new lines are allowed in URL description
- while (readToken() != TerminalTokens.TokenNameLESS) {
- if (this.scanner.currentPosition >= this.scanner.eofPosition || this.scanner.currentCharacter == '@' ||
- (this.inlineTagStarted && this.scanner.currentCharacter == '}')) {
- // Reset position: we want to rescan last token
- this.index = this.tokenPreviousPosition;
- this.scanner.currentPosition = this.tokenPreviousPosition;
- this.currentTokenType = -1;
- // Signal syntax error
- if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidSeeUrlReference(start, this.lineEnd);
-
- return false;
- }
- consumeToken();
- }
- consumeToken();
- start = this.scanner.getCurrentTokenStartPosition();
- if (readChar() == '/') {
- currentChar = readChar();
- if (currentChar == 'a' || currentChar == 'A') {
- if (readChar() == '>') {
- // Valid href
- return true;
- }
- }
- }
- }
- }
- }
- } catch (InvalidInputException ex) {
- // Do nothing as we want to keep positions for error message
- }
- }
- }
- // Reset position: we want to rescan last token
- this.index = this.tokenPreviousPosition;
- this.scanner.currentPosition = this.tokenPreviousPosition;
- this.currentTokenType = -1;
- // Signal syntax error
- if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidSeeUrlReference(start, this.lineEnd);
-
- return false;
- }
-
- /*
- * Parse tag followed by an identifier
- */
- protected boolean parseIdentifierTag(boolean report) {
- int token = readTokenSafely();
- switch (token) {
- case TerminalTokens.TokenNameIdentifier:
- pushIdentifier(true, false);
- return true;
- }
- if (report) {
- this.sourceParser.problemReporter().javadocMissingIdentifier(this.tagSourceStart, this.tagSourceEnd, this.sourceParser.modifiers);
- }
- return false;
- }
-
- /*
- * Parse a method reference in @see tag
- */
- protected Object parseMember(Object receiver) throws InvalidInputException {
- // Init
- this.identifierPtr = -1;
- this.identifierLengthPtr = -1;
- int start = this.scanner.getCurrentTokenStartPosition();
- this.memberStart = start;
-
- // Get member identifier
- if (readToken() == TerminalTokens.TokenNameIdentifier) {
- if (this.scanner.currentCharacter == '.') { // member name may be qualified (inner class constructor reference)
- parseQualifiedName(true);
- } else {
- consumeToken();
- pushIdentifier(true, false);
- }
- // Look for next token to know whether it's a field or method reference
- int previousPosition = this.index;
- if (readToken() == TerminalTokens.TokenNameLPAREN) {
- consumeToken();
- start = this.scanner.getCurrentTokenStartPosition();
- try {
- return parseArguments(receiver);
- } catch (InvalidInputException e) {
- int end = this.scanner.getCurrentTokenEndPosition() < this.lineEnd ?
- this.scanner.getCurrentTokenEndPosition() :
- this.scanner.getCurrentTokenStartPosition();
- end = end < this.lineEnd ? end : this.lineEnd;
- if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidSeeReferenceArgs(start, end);
- }
- return null;
- }
-
- // Reset position: we want to rescan last token
- this.index = previousPosition;
- this.scanner.currentPosition = previousPosition;
- this.currentTokenType = -1;
-
- // Verify character(s) after identifier (expecting space or end comment)
- if (!verifySpaceOrEndComment()) {
- int end = this.starPosition == -1 ? this.lineEnd : this.starPosition;
- if (this.source[end]=='\n') end--;
- if (this.reportProblems) this.sourceParser.problemReporter().javadocMalformedSeeReference(start, end);
- return null;
- }
- return createFieldReference(receiver);
- }
- int end = getTokenEndPosition() - 1;
- end = start > end ? start : end;
- if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidReference(start, end);
- // Reset position: we want to rescan last token
- this.index = this.tokenPreviousPosition;
- this.scanner.currentPosition = this.tokenPreviousPosition;
- this.currentTokenType = -1;
- return null;
- }
-
- /*
- * Parse @param tag declaration
- */
- protected boolean parseParam() throws InvalidInputException {
-
- // Store current state
- int start = this.tagSourceStart;
- int end = this.tagSourceEnd;
- boolean tokenWhiteSpace = this.scanner.tokenizeWhiteSpace;
- this.scanner.tokenizeWhiteSpace = true;
- Object []typeReference=null;
-
- // Verify that there are whitespaces after tag
- boolean isCompletionParser = (this.kind & COMPLETION_PARSER) != 0;
- if (this.scanner.currentCharacter != ' ' && !ScannerHelper.isWhitespace(this.scanner.currentCharacter)) {
- if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidTag(start, this.scanner.getCurrentTokenEndPosition());
- if (!isCompletionParser) {
- this.scanner.currentPosition = start;
- this.index = start;
- }
- this.currentTokenType = -1;
- this.scanner.tokenizeWhiteSpace = tokenWhiteSpace;
- return false;
- }
-
- // Get first non whitespace token
- this.identifierPtr = -1;
- this.identifierLengthPtr = -1;
- boolean hasMultiLines = this.scanner.currentPosition > (this.lineEnd+1);
- boolean valid = true, empty = true;
- boolean isParmType=false;
- int token = -1;
- nextToken: while (true) {
- this.currentTokenType = -1;
- try {
- token = readToken();
- } catch (InvalidInputException e) {
- valid = false;
- }
- switch (token) {
- case TerminalTokens.TokenNameIdentifier :
- if (valid) {
- // store param name id
- pushIdentifier(true, false);
- start = this.scanner.getCurrentTokenStartPosition();
- end = hasMultiLines ? this.lineEnd: this.scanner.getCurrentTokenEndPosition();
- break nextToken;
- }
- // fall through next case to report error
- default:
- if (valid && !hasMultiLines) start = this.scanner.getCurrentTokenStartPosition();
- valid = false;
- if (!hasMultiLines) {
- empty = false;
- end = hasMultiLines ? this.lineEnd: this.scanner.getCurrentTokenEndPosition();
- break;
- }
- end = this.lineEnd;
- // when several lines, fall through next case to report problem immediately
- case TerminalTokens.TokenNameWHITESPACE:
- if (this.scanner.currentPosition > (this.lineEnd+1)) hasMultiLines = true;
- if (valid) break;
- // if not valid fall through next case to report error
- case TerminalTokens.TokenNameEOF:
- if (this.reportProblems)
- if (empty)
- this.sourceParser.problemReporter().javadocMissingParamName(start, end, this.sourceParser.modifiers);
- else
- this.sourceParser.problemReporter().javadocInvalidParamTagName(start, end);
- if (!isCompletionParser) {
- this.scanner.currentPosition = start;
- this.index = start;
- }
- this.currentTokenType = -1;
- this.scanner.tokenizeWhiteSpace = tokenWhiteSpace;
- return false;
- case TerminalTokens.TokenNameLBRACE:
- this.scanner.tokenizeWhiteSpace = false;
- typeReference=parseTypeReference();
- isParmType=true;
- this.identifierPtr = -1;
- this.identifierLengthPtr = -1;
- this.scanner.tokenizeWhiteSpace = true;
- break;
-
- }
- }
-
- // Verify that tag name is well followed by white spaces
- if (valid) {
- this.currentTokenType = -1;
- int restart = this.scanner.currentPosition;
- try {
- token = readToken();
- } catch (InvalidInputException e) {
- valid = false;
- }
- if (token == TerminalTokens.TokenNameWHITESPACE) {
- this.scanner.currentPosition = restart;
- this.index = restart;
- this.scanner.tokenizeWhiteSpace = tokenWhiteSpace;
- valid= pushParamName(false);
- if (valid && isParmType )
- {
- createParamType(typeReference);
-
- }
- return valid;
- }
- }
-
-
- // Report problem
- this.currentTokenType = -1;
- if (isCompletionParser) return false;
- end = hasMultiLines ? this.lineEnd: this.scanner.getCurrentTokenEndPosition();
- while ((token=readToken()) != TerminalTokens.TokenNameWHITESPACE && token != TerminalTokens.TokenNameEOF) {
- this.currentTokenType = -1;
- end = hasMultiLines ? this.lineEnd: this.scanner.getCurrentTokenEndPosition();
- }
- if (this.reportProblems)
- this.sourceParser.problemReporter().javadocInvalidParamTagName(start, end);
- this.scanner.currentPosition = start;
- this.index = start;
- this.currentTokenType = -1;
- this.scanner.tokenizeWhiteSpace = tokenWhiteSpace;
- return false;
- }
-
- protected abstract void createParamType(Object[] typeReference) ;
-
-
- protected Object [] parseTypeReference() {
- int currentPosition = this.scanner.currentPosition;
- try {
- ArrayList typeRefs = new ArrayList();
-// Object reference = null;
-// int previousPosition = -1;
-// int typeRefStartPosition = -1;
- boolean expectingRef=true;
-
- // Get reference tokens
- nextToken : while (this.index < this.scanner.eofPosition ) {
-// previousPosition = this.index;
- int token = readTokenSafely();
- switch (token) {
- case TerminalTokens.TokenNameRBRACE :
- // If typeRef != null we may raise a warning here to let user know there's an unused reference...
- // Currently as javadoc 1.4.2 ignore it, we do the same (see bug 69302)
- consumeToken();
- break nextToken;
-
- case TerminalTokens.TokenNameLBRACE :
- // If typeRef != null we may raise a warning here to let user know there's an unused reference...
- // Currently as javadoc 1.4.2 ignore it, we do the same (see bug 69302)
- consumeToken();
- break ;
-
- case TerminalTokens.TokenNameLESS : // @see "<a href="URL#Value">label</a>
- // If typeRef != null we may raise a warning here to let user know there's an unused reference...
- // Currently as javadoc 1.4.2 ignore it, we do the same (see bug 69302)
-// if (typeRef != null) break nextToken;
- if (!expectingRef)
- return null;
- consumeToken();
- int start = this.scanner.getCurrentTokenStartPosition();
- if (parseHref()) {
- consumeToken();
- // verify end line
-// if (verifyEndLine(previousPosition))
-// return true;
-// if (this.reportProblems) this.sourceParser.problemReporter().javadocUnexpectedText(this.scanner.currentPosition, this.lineEnd);
- }
- expectingRef=false;
- break;
- case TerminalTokens.TokenNameERROR :
- consumeToken();
- char[] currentError = this.scanner.getCurrentIdentifierSource();
- if (currentError.length>0 && currentError[0] == '"') {
- if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidReference(this.scanner.getCurrentTokenStartPosition(), getTokenEndPosition());
- return null;
- }
- break nextToken;
- case TerminalTokens.TokenNameIdentifier :
- if (!expectingRef)
- return null;
-// typeRefStartPosition = this.scanner.getCurrentTokenStartPosition();
- Object ref = parseQualifiedName(true);
- if (ref!=null)
- typeRefs.add(ref);
- expectingRef=false;
- if (this.abort) return null; // May be aborted by specialized parser
- break;
- case TerminalTokens.TokenNameOR :
- if (expectingRef)
- return null;
- consumeToken();
- expectingRef=true;
- break;
- default :
- break nextToken;
- }
- }
-
- if (typeRefs.isEmpty()) {
- this.index = this.tokenPreviousPosition;
- this.scanner.currentPosition = this.tokenPreviousPosition;
- this.currentTokenType = -1;
- if (this.reportProblems) {
- this.sourceParser.problemReporter().javadocMissingReference(this.tagSourceStart, this.tagSourceEnd, this.sourceParser.modifiers);
- }
- return null;
- }
-
-
- this.currentTokenType = -1;
-
-
-
-
- Object[] typeReferences=typeRefs.toArray();
- return typeReferences;
- }
- catch (InvalidInputException ex) {
- if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidReference(currentPosition, getTokenEndPosition());
- }
- // Reset position to avoid missing tokens when new line was encountered
- this.index = this.tokenPreviousPosition;
- this.scanner.currentPosition = this.tokenPreviousPosition;
- this.currentTokenType = -1;
- return null;
-
- }
-
- /*
- * Parse a qualified name and built a type reference if the syntax is valid.
- */
- protected Object parseQualifiedName(boolean reset) throws InvalidInputException {
-
- boolean tokenizeWhiteSpace=this.scanner.tokenizeWhiteSpace;
- this.scanner.tokenizeWhiteSpace=false;
- try {
- // Reset identifier stack if requested
- if (reset) {
- this.identifierPtr = -1;
- this.identifierLengthPtr = -1;
- }
- // Scan tokens
- int primitiveToken = -1;
- int parserKind = this.kind & PARSER_KIND;
- nextToken: for (int iToken = 0;; iToken++) {
- int token = readTokenSafely();
- switch (token) {
- case TerminalTokens.TokenNameIdentifier:
- if (((iToken & 1) != 0)) { // identifiers must be odd tokens
- break nextToken;
- }
- pushIdentifier(iToken == 0, false);
- consumeToken();
- break;
-
- case TerminalTokens.TokenNameDOT:
- if ((iToken & 1) == 0) { // dots must be even tokens
- throw new InvalidInputException();
- }
- consumeToken();
- break;
-
- case TerminalTokens.TokenNamevoid:
- case TerminalTokens.TokenNameboolean:
- case TerminalTokens.TokenNamebyte:
- case TerminalTokens.TokenNamechar:
- case TerminalTokens.TokenNamedouble:
- case TerminalTokens.TokenNamefloat:
- case TerminalTokens.TokenNameint:
- case TerminalTokens.TokenNamelong:
- case TerminalTokens.TokenNameshort:
- if (iToken > 0) {
- throw new InvalidInputException();
- }
- pushIdentifier(true, false);
- primitiveToken = token;
- consumeToken();
- break nextToken;
-
- default:
- if (iToken == 0) {
- if (this.identifierPtr >= 0) {
- this.lastIdentifierEndPosition = (int) this.identifierPositionStack[this.identifierPtr];
- }
- return null;
- }
- if ((iToken & 1) == 0) { // cannot leave on a dot
- switch (parserKind) {
- case COMPLETION_PARSER:
- if (this.identifierPtr >= 0) {
- this.lastIdentifierEndPosition = (int) this.identifierPositionStack[this.identifierPtr];
- }
- return syntaxRecoverQualifiedName(primitiveToken);
- case DOM_PARSER:
- if (this.currentTokenType != -1) {
- // Reset position: we want to rescan last token
- this.index = this.tokenPreviousPosition;
- this.scanner.currentPosition = this.tokenPreviousPosition;
- this.currentTokenType = -1;
- }
- // fall through default case to raise exception
- default:
- throw new InvalidInputException();
- }
- }
- break nextToken;
- }
- }
- // Reset position: we want to rescan last token
- if (parserKind != COMPLETION_PARSER && this.currentTokenType != -1) {
- this.index = this.tokenPreviousPosition;
- this.scanner.currentPosition = this.tokenPreviousPosition;
- this.currentTokenType = -1;
- }
- if (this.identifierPtr >= 0) {
- this.lastIdentifierEndPosition = (int) this.identifierPositionStack[this.identifierPtr];
- }
- return createTypeReference(primitiveToken);
- } finally {
- this.scanner.tokenizeWhiteSpace=tokenizeWhiteSpace;
- }
- }
-
- /*
- * Parse a reference in @see tag
- */
- protected boolean parseReference() throws InvalidInputException {
- int currentPosition = this.scanner.currentPosition;
- try {
- Object typeRef = null;
- Object reference = null;
- int previousPosition = -1;
- int typeRefStartPosition = -1;
-
- // Get reference tokens
- nextToken : while (this.index < this.scanner.eofPosition) {
- previousPosition = this.index;
- int token = readTokenSafely();
- switch (token) {
- case TerminalTokens.TokenNameStringLiteral : // @see "string"
- // If typeRef != null we may raise a warning here to let user know there's an unused reference...
- // Currently as javadoc 1.4.2 ignore it, we do the same (see bug 69302)
- if (typeRef != null) break nextToken;
- consumeToken();
- int start = this.scanner.getCurrentTokenStartPosition();
-
- // verify end line
- if (verifyEndLine(previousPosition)) {
- return true;
- }
- if (this.reportProblems) this.sourceParser.problemReporter().javadocUnexpectedText(this.scanner.currentPosition, this.lineEnd);
- return false;
- case TerminalTokens.TokenNameLESS : // @see "<a href="URL#Value">label</a>
- // If typeRef != null we may raise a warning here to let user know there's an unused reference...
- // Currently as javadoc 1.4.2 ignore it, we do the same (see bug 69302)
- if (typeRef != null) break nextToken;
- consumeToken();
- start = this.scanner.getCurrentTokenStartPosition();
- if (parseHref()) {
- consumeToken();
- // verify end line
- if (verifyEndLine(previousPosition)) return true;
- if (this.reportProblems) this.sourceParser.problemReporter().javadocUnexpectedText(this.scanner.currentPosition, this.lineEnd);
- }
- return false;
- case TerminalTokens.TokenNameERROR :
- consumeToken();
- if (this.scanner.currentCharacter == '#') { // @see ...#member
- reference = parseMember(typeRef);
- if (reference != null) {
- return pushSeeRef(reference);
- }
- return false;
- }
- char[] currentError = this.scanner.getCurrentIdentifierSource();
- if (currentError.length>0 && currentError[0] == '"') {
- if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidReference(this.scanner.getCurrentTokenStartPosition(), getTokenEndPosition());
- return false;
- }
- break nextToken;
- case TerminalTokens.TokenNameIdentifier :
- if (typeRef == null) {
- typeRefStartPosition = this.scanner.getCurrentTokenStartPosition();
- typeRef = parseQualifiedName(true);
- if (this.abort) return false; // May be aborted by specialized parser
- break;
- }
- default :
- break nextToken;
- }
- }
-
- // Verify that we got a reference
- if (reference == null) reference = typeRef;
- if (reference == null) {
- this.index = this.tokenPreviousPosition;
- this.scanner.currentPosition = this.tokenPreviousPosition;
- this.currentTokenType = -1;
- if (this.reportProblems) {
- this.sourceParser.problemReporter().javadocMissingReference(this.tagSourceStart, this.tagSourceEnd, this.sourceParser.modifiers);
- }
- return false;
- }
-
- // Reset position at the end of type reference
- if (this.lastIdentifierEndPosition > this.javadocStart) {
- this.index = this.lastIdentifierEndPosition+1;
- this.scanner.currentPosition = this.index;
- }
- this.currentTokenType = -1;
-
- // Verify that line end does not start with an open parenthese (which could be a constructor reference wrongly written...)
- // See bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=47215
- char ch = peekChar();
- if (ch == '(') {
- if (this.reportProblems) this.sourceParser.problemReporter().javadocMissingHashCharacter(typeRefStartPosition, this.lineEnd, String.valueOf(this.source, typeRefStartPosition, this.lineEnd-typeRefStartPosition+1));
- return false;
- }
-
- // Verify that we get white space after reference
- if (!verifySpaceOrEndComment()) {
- this.index = this.tokenPreviousPosition;
- this.scanner.currentPosition = this.tokenPreviousPosition;
- this.currentTokenType = -1;
- int end = this.starPosition == -1 ? this.lineEnd : this.starPosition;
- if (this.source[end]=='\n') end--;
- if (this.reportProblems) this.sourceParser.problemReporter().javadocMalformedSeeReference(typeRefStartPosition, end);
- return false;
- }
-
- // Everything is OK, store reference
- return pushSeeRef(reference);
- }
- catch (InvalidInputException ex) {
- if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidReference(currentPosition, getTokenEndPosition());
- }
- // Reset position to avoid missing tokens when new line was encountered
- this.index = this.tokenPreviousPosition;
- this.scanner.currentPosition = this.tokenPreviousPosition;
- this.currentTokenType = -1;
- return false;
- }
-
- /*
- * Parse tag declaration
- */
- protected abstract boolean parseTag(int previousPosition) throws InvalidInputException;
-
- /*
- * Parse @throws tag declaration
- */
- protected boolean parseThrows() {
- int start = this.scanner.currentPosition;
- try {
- Object typeRef = parseQualifiedName(true);
- if (this.abort) return false; // May be aborted by specialized parser
- if (typeRef == null) {
- if (this.reportProblems)
- this.sourceParser.problemReporter().javadocMissingThrowsClassName(this.tagSourceStart, this.tagSourceEnd, this.sourceParser.modifiers);
- } else {
- return pushThrowName(typeRef);
- }
- } catch (InvalidInputException ex) {
- if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidThrowsClass(start, getTokenEndPosition());
- }
- return false;
- }
-
- /*
- * Return current character without move index position.
- */
- protected char peekChar() {
- int idx = this.index;
- char c = this.source[idx++];
- if (c == '\\' && this.source[idx] == 'u') {
- int c1, c2, c3, c4;
- idx++;
- while (this.source[idx] == 'u')
- idx++;
- if (!(((c1 = ScannerHelper.getNumericValue(this.source[idx++])) > 15 || c1 < 0)
- || ((c2 = ScannerHelper.getNumericValue(this.source[idx++])) > 15 || c2 < 0)
- || ((c3 = ScannerHelper.getNumericValue(this.source[idx++])) > 15 || c3 < 0) || ((c4 = ScannerHelper.getNumericValue(this.source[idx++])) > 15 || c4 < 0))) {
- c = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4);
- }
- }
- return c;
- }
-
- /*
- * push the consumeToken on the identifier stack. Increase the total number of identifier in the stack.
- */
- protected void pushIdentifier(boolean newLength, boolean isToken) {
-
- int stackLength = this.identifierStack.length;
- if (++this.identifierPtr >= stackLength) {
- System.arraycopy(
- this.identifierStack, 0,
- this.identifierStack = new char[stackLength + 10][], 0,
- stackLength);
- System.arraycopy(
- this.identifierPositionStack, 0,
- this.identifierPositionStack = new long[stackLength + 10], 0,
- stackLength);
- }
- this.identifierStack[this.identifierPtr] = isToken ? this.scanner.getCurrentTokenSource() : this.scanner.getCurrentIdentifierSource();
- this.identifierPositionStack[this.identifierPtr] = (((long) this.scanner.startPosition) << 32) + (this.scanner.currentPosition - 1);
-
- if (newLength) {
- 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;
- } else {
- this.identifierLengthStack[this.identifierLengthPtr]++;
- }
- }
-
- /*
- * Add a new obj on top of the ast stack.
- * If new length is required, then add also a new length in length stack.
- */
- protected void pushOnAstStack(Object node, boolean newLength) {
-
- if (node == null) {
- this.astLengthStack[++this.astLengthPtr] = 0;
- return;
- }
-
- int stackLength = this.astStack.length;
- if (++this.astPtr >= stackLength) {
- System.arraycopy(
- this.astStack, 0,
- this.astStack = new Object[stackLength + AST_STACK_INCREMENT], 0,
- stackLength);
- this.astPtr = stackLength;
- }
- this.astStack[this.astPtr] = node;
-
- if (newLength) {
- stackLength = this.astLengthStack.length;
- if (++this.astLengthPtr >= stackLength) {
- System.arraycopy(
- this.astLengthStack, 0,
- this.astLengthStack = new int[stackLength + AST_STACK_INCREMENT], 0,
- stackLength);
- }
- this.astLengthStack[this.astLengthPtr] = 1;
- } else {
- this.astLengthStack[this.astLengthPtr]++;
- }
- }
-
- /*
- * Push a param name in ast node stack.
- */
- protected abstract boolean pushParamName(boolean isTypeParam);
-
- /*
- * Push a reference statement in ast node stack.
- */
- protected abstract boolean pushSeeRef(Object statement);
-
- /*
- * Push a text element in ast node stack
- */
- protected void pushText(int start, int end) {
- // do not store text by default
- }
-
- /*
- * Push a throws type ref in ast node stack.
- */
- protected abstract boolean pushThrowName(Object typeRef);
-
- /*
- * Read current character and move index position.
- * Warning: scanner position is unchanged using this method!
- */
- protected char readChar() {
-
- char c = this.source[this.index++];
- if (c == '\\' && this.source[this.index] == 'u') {
- int c1, c2, c3, c4;
- int pos = this.index;
- this.index++;
- while (this.source[this.index] == 'u')
- this.index++;
- if (!(((c1 = ScannerHelper.getNumericValue(this.source[this.index++])) > 15 || c1 < 0)
- || ((c2 = ScannerHelper.getNumericValue(this.source[this.index++])) > 15 || c2 < 0)
- || ((c3 = ScannerHelper.getNumericValue(this.source[this.index++])) > 15 || c3 < 0) || ((c4 = ScannerHelper.getNumericValue(this.source[this.index++])) > 15 || c4 < 0))) {
- c = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4);
- } else {
- // TODO (frederic) currently reset to previous position, perhaps signal a syntax error would be more appropriate
- this.index = pos;
- }
- }
- return c;
- }
-
- /*
- * Read token only if previous was consumed
- */
- protected int readToken() throws InvalidInputException {
- if (this.currentTokenType < 0) {
- this.tokenPreviousPosition = this.scanner.currentPosition;
- this.currentTokenType = this.scanner.getNextToken();
- if (this.scanner.currentPosition > (this.lineEnd+1)) { // be sure to be on next line (lineEnd is still on the same line)
- this.lineStarted = false;
- while (this.currentTokenType == TerminalTokens.TokenNameMULTIPLY) {
- this.currentTokenType = this.scanner.getNextToken();
- }
- }
- this.index = this.scanner.currentPosition;
- this.lineStarted = true; // after having read a token, line is obviously started...
- }
- return this.currentTokenType;
- }
-
- protected int readTokenAndConsume() throws InvalidInputException {
- int token = readToken();
- consumeToken();
- return token;
- }
-
- /*
- * Read token without throwing any InvalidInputException exception.
- * Returns TerminalTokens.TokenNameERROR instead.
- */
- protected int readTokenSafely() {
- int token = TerminalTokens.TokenNameERROR;
- try {
- token = readToken();
- }
- catch (InvalidInputException iie) {
- // token is already set to error
- }
- return token;
- }
-
- /*
- * Refresh start position and length of an inline tag.
- */
- protected void refreshInlineTagPosition(int previousPosition) {
- // do nothing by default
- }
-
- /*
- * Refresh return statement
- */
- protected void refreshReturnStatement() {
- // do nothing by default
- }
-
- /*
- * Entry point for recovery on invalid syntax
- */
- protected Object syntaxRecoverQualifiedName(int primitiveToken) throws InvalidInputException {
- // do nothing, just an entry point for recovery
- return null;
- }
-
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- int startPos = this.scanner.currentPosition<this.index ? this.scanner.currentPosition : this.index;
- int endPos = this.scanner.currentPosition<this.index ? this.index : this.scanner.currentPosition;
- if (startPos == this.source.length)
- return "EOF\n\n" + new String(this.source); //$NON-NLS-1$
- if (endPos > this.source.length)
- return "behind the EOF\n\n" + new String(this.source); //$NON-NLS-1$
-
- char front[] = new char[startPos];
- System.arraycopy(this.source, 0, front, 0, startPos);
-
- int middleLength = (endPos - 1) - startPos + 1;
- char middle[];
- if (middleLength > -1) {
- middle = new char[middleLength];
- System.arraycopy(
- this.source,
- startPos,
- middle,
- 0,
- middleLength);
- } else {
- middle = CharOperation.NO_CHAR;
- }
-
- char end[] = new char[this.source.length - (endPos - 1)];
- System.arraycopy(
- this.source,
- (endPos - 1) + 1,
- end,
- 0,
- this.source.length - (endPos - 1) - 1);
-
- buffer.append(front);
- if (this.scanner.currentPosition<this.index) {
- buffer.append("\n===============================\nScanner current position here -->"); //$NON-NLS-1$
- } else {
- buffer.append("\n===============================\nParser index here -->"); //$NON-NLS-1$
- }
- buffer.append(middle);
- if (this.scanner.currentPosition<this.index) {
- buffer.append("<-- Parser index here\n===============================\n"); //$NON-NLS-1$
- } else {
- buffer.append("<-- Scanner current position here\n===============================\n"); //$NON-NLS-1$
- }
- buffer.append(end);
-
- return buffer.toString();
- }
-
- /*
- * Update
- */
- protected abstract void updateDocComment();
-
- /*
- * Update line end
- */
- protected void updateLineEnd() {
- while (this.index > (this.lineEnd+1)) { // be sure to be on next line (lineEnd is still on the same line)
- if (this.linePtr < this.lastLinePtr) {
- this.lineEnd = this.scanner.getLineEnd(++this.linePtr) - 1;
- } else {
- this.lineEnd = this.javadocEnd;
- return;
- }
- }
- }
-
- /*
- * Verify that end of the line only contains space characters or end of comment.
- * Note that end of comment may be preceeding by several contiguous '*' chars.
- */
- protected boolean verifyEndLine(int textPosition) {
- boolean domParser = (this.kind & DOM_PARSER) != 0;
- // Special case for inline tag
- if (this.inlineTagStarted) {
- // expecting closing brace
- if (peekChar() == '}') {
- if (domParser) {
- createTag();
- pushText(textPosition, this.starPosition);
- }
- return true;
- }
- return false;
- }
-
- int startPosition = this.index;
- int previousPosition = this.index;
- this.starPosition = -1;
- char ch = readChar();
- nextChar: while (true) {
- switch (ch) {
- case '\r':
- case '\n':
- if (domParser) {
- createTag();
- pushText(textPosition, previousPosition);
- }
- this.index = previousPosition;
- return true;
- case '\u000c' : /* FORM FEED */
- case ' ' : /* SPACE */
- case '\t' : /* HORIZONTAL TABULATION */
- if (this.starPosition >= 0) break nextChar;
- break;
- case '*':
- this.starPosition = previousPosition;
- break;
- case '/':
- if (this.starPosition >= textPosition) {
- if (domParser) {
- createTag();
- pushText(textPosition, this.starPosition);
- }
- return true;
- }
- default :
- // leave loop
- break nextChar;
-
- }
- previousPosition = this.index;
- ch = readChar();
- }
- this.index = startPosition;
- return false;
- }
-
- /*
- * Verify characters after a name matches one of following conditions:
- * 1- first character is a white space
- * 2- first character is a closing brace *and* we're currently parsing an inline tag
- * 3- are the end of comment (several contiguous star ('*') characters may be
- * found before the last slash ('/') character).
- */
- protected boolean verifySpaceOrEndComment() {
- int startPosition = this.index;
- // Whitespace or inline tag closing brace
- char ch = peekChar();
- switch (ch) {
- case '}':
- return this.inlineTagStarted;
- default:
- if (ScannerHelper.isWhitespace(ch)) {
- return true;
- }
- }
- // End of comment
- int previousPosition = this.index;
- this.starPosition = -1;
- ch = readChar();
- while (this.index<this.source.length) {
- switch (ch) {
- case '*':
- // valid whatever the number of star before last '/'
- this.starPosition = previousPosition;
- break;
- case '/':
- if (this.starPosition >= startPosition) { // valid only if a star was previous character
- return true;
- }
- default :
- // invalid whatever other character, even white spaces
- this.index = startPosition;
- return false;
-
- }
- previousPosition = this.index;
- ch = readChar();
- }
- this.index = startPosition;
- return false;
- }
-}
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
deleted file mode 100644
index b328b4d1..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/JavadocParser.java
+++ /dev/null
@@ -1,1131 +0,0 @@
-/*******************************************************************************
- * 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
- * Olivier Oeuillot <oeuillot@free.fr> - bug 244411
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.parser;
-
-import java.util.List;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Expression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Javadoc;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocAllocationExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocArgumentExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocArrayQualifiedTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocArraySingleTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocFieldReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocImplicitTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocMessageSend;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocQualifiedTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocReturnStatement;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocSingleNameReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocSingleTypeReference;
-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.classfmt.ClassFileConstants;
-import org.eclipse.wst.jsdt.internal.compiler.util.Util;
-
-/**
- * Parser specialized for decoding javadoc comments
- */
-public class JavadocParser extends AbstractCommentParser {
-
- // Public fields
- public Javadoc docComment;
-
- // bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=51600
- // Store param references for tag with invalid syntax
- private int invalidParamReferencesPtr = -1;
- private ASTNode[] invalidParamReferencesStack;
-
- // bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=153399
- // Store value tag positions
- private long validValuePositions, invalidValuePositions;
-
- private int flags=0;
-
- private TypeReference namespace=null;
- private TypeReference memberOf=null;
- private TypeReference returnType=null;
- private TypeReference extendsType=null;
-
- private TypeReference classDef=null;
- private TypeReference methodDef=null;
- JavadocSingleNameReference property=null;
- private boolean isConstructor;
-
-
-
- protected boolean commentParse() {
- this.isConstructor=false;
- this.namespace=null;
- this.flags=0;
-
- this.namespace=null;
- this.memberOf=null;
- this.returnType=null;
- this.extendsType=null;
- this.property=null;
- this.classDef=null;
- this.methodDef=null;
- // TODO Auto-generated method stub
- boolean result= super.commentParse();
- return result;
- }
-
- public JavadocParser(Parser sourceParser) {
- super(sourceParser);
- this.kind = COMPIL_PARSER | TEXT_VERIF;
- }
-
- /* (non-Javadoc)
- * Returns true if tag @deprecated is present in javadoc comment.
- *
- * If javadoc checking is enabled, will also construct an Javadoc node, which will be stored into Parser.javadoc
- * slot for being consumed later on.
- */
- public boolean checkDeprecation(int commentPtr) {
-
- // Store javadoc positions
- this.javadocStart = this.sourceParser.scanner.commentStarts[commentPtr];
- this.javadocEnd = this.sourceParser.scanner.commentStops[commentPtr]-1;
- this.firstTagPosition = this.sourceParser.scanner.commentTagStarts[commentPtr];
- this.validValuePositions = -1;
- this.invalidValuePositions = -1;
-
- // Init javadoc if necessary
- if (this.checkDocComment) {
- this.docComment = new Javadoc(javadocStart, javadocEnd);
- } else {
- this.docComment = null;
- }
-
- // If there's no tag in javadoc, return without parsing it
- if (this.firstTagPosition == 0) {
- switch (this.kind & PARSER_KIND) {
- case COMPIL_PARSER:
- case SOURCE_PARSER:
- return false;
- }
- }
-
- // Parse
- try {
- this.source = this.sourceParser.scanner.source;
- if (this.checkDocComment) {
- // Initialization
- this.scanner.lineEnds = this.sourceParser.scanner.lineEnds;
- this.scanner.linePtr = this.sourceParser.scanner.linePtr;
- this.lineEnds = this.scanner.lineEnds;
- commentParse();
- } else {
-
- // Parse comment
- Scanner sourceScanner = this.sourceParser.scanner;
- int firstLineNumber = Util.getLineNumber(javadocStart, sourceScanner.lineEnds, 0, sourceScanner.linePtr);
- int lastLineNumber = Util.getLineNumber(javadocEnd, sourceScanner.lineEnds, 0, sourceScanner.linePtr);
- this.index = javadocStart +3;
-
- // scan line per line, since tags must be at beginning of lines only
- this.deprecated = false;
- nextLine : for (int line = firstLineNumber; line <= lastLineNumber; line++) {
- int lineStart = line == firstLineNumber
- ? javadocStart + 3 // skip leading /**
- : this.sourceParser.scanner.getLineStart(line);
- this.index = lineStart;
- this.lineEnd = line == lastLineNumber
- ? javadocEnd - 2 // remove trailing * /
- : this.sourceParser.scanner.getLineEnd(line);
- nextCharacter : while (this.index < this.lineEnd) {
- char c = readChar(); // consider unicodes
- switch (c) {
- case '*' :
- case '\u000c' : /* FORM FEED */
- case ' ' : /* SPACE */
- case '\t' : /* HORIZONTAL TABULATION */
- case '\n' : /* LINE FEED */
- case '\r' : /* CR */
- // do nothing for space or '*' characters
- continue nextCharacter;
- case '@' :
- parseSimpleTag();
- if (this.tagValue == TAG_DEPRECATED_VALUE) {
- if (this.abort) break nextCharacter;
- }
- }
- continue nextLine;
- }
- }
- return this.deprecated;
- }
- } finally {
- this.source = null; // release source as soon as finished
- }
- return this.deprecated;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.parser.AbstractCommentParser#createArgumentReference(char[], java.lang.Object, int)
- */
- protected Object createArgumentReference(char[] name, int dim, boolean isVarargs, Object typeRef, long[] dimPositions, long argNamePos) throws InvalidInputException {
- try {
- TypeReference argTypeRef = (TypeReference) typeRef;
- if (dim > 0) {
- long pos = (((long) argTypeRef.sourceStart) << 32) + argTypeRef.sourceEnd;
- if (typeRef instanceof JavadocSingleTypeReference) {
- JavadocSingleTypeReference singleRef = (JavadocSingleTypeReference) typeRef;
- argTypeRef = new JavadocArraySingleTypeReference(singleRef.token, dim, pos);
- } else {
- JavadocQualifiedTypeReference qualifRef = (JavadocQualifiedTypeReference) typeRef;
- argTypeRef = new JavadocArrayQualifiedTypeReference(qualifRef, dim);
- }
- }
- int argEnd = argTypeRef.sourceEnd;
- if (dim > 0) {
- argEnd = (int) dimPositions[dim-1];
- if (isVarargs) {
- argTypeRef.bits |= ASTNode.IsVarArgs; // set isVarArgs
- }
- }
- if (argNamePos >= 0) argEnd = (int) argNamePos;
- return new JavadocArgumentExpression(name, argTypeRef.sourceStart, argEnd, argTypeRef);
- }
- catch (ClassCastException ex) {
- throw new InvalidInputException();
- }
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.parser.AbstractCommentParser#createFieldReference()
- */
- protected Object createFieldReference(Object receiver) throws InvalidInputException {
- try {
- // Get receiver type
- TypeReference typeRef = (TypeReference) receiver;
- if (typeRef == null) {
- char[] name = this.sourceParser.compilationUnit.getMainTypeName();
- typeRef = new JavadocImplicitTypeReference(name, this.memberStart);
- }
- // Create field
- JavadocFieldReference field = new JavadocFieldReference(this.identifierStack[0], this.identifierPositionStack[0]);
- field.receiver = typeRef;
- field.tagSourceStart = this.tagSourceStart;
- field.tagSourceEnd = this.tagSourceEnd;
- field.tagValue = this.tagValue;
- return field;
- }
- catch (ClassCastException ex) {
- throw new InvalidInputException();
- }
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.parser.AbstractCommentParser#createMethodReference(java.lang.Object[])
- */
- protected Object createMethodReference(Object receiver, List arguments) throws InvalidInputException {
- try {
- // Get receiver type
- TypeReference typeRef = (TypeReference) receiver;
- // Decide whether we have a constructor or not
- boolean isConstructor = false;
- int length = this.identifierLengthStack[0]; // may be > 0 for member class constructor reference
- if (typeRef == null) {
- char[] name = this.sourceParser.compilationUnit.getMainTypeName();
- TypeDeclaration typeDecl = getParsedTypeDeclaration();
- if (typeDecl != null) {
- name = typeDecl.name;
- }
- isConstructor = CharOperation.equals(this.identifierStack[length-1], name);
- typeRef = new JavadocImplicitTypeReference(name, this.memberStart);
- } else {
- if (typeRef instanceof JavadocSingleTypeReference) {
- char[] name = ((JavadocSingleTypeReference)typeRef).token;
- isConstructor = CharOperation.equals(this.identifierStack[length-1], name);
- } else if (typeRef instanceof JavadocQualifiedTypeReference) {
- char[][] tokens = ((JavadocQualifiedTypeReference)typeRef).tokens;
- int last = tokens.length-1;
- isConstructor = CharOperation.equals(this.identifierStack[length-1], tokens[last]);
- if (isConstructor) {
- boolean valid = true;
- if (valid) {
- for (int i=0; i<length-1 && valid; i++) {
- valid = CharOperation.equals(this.identifierStack[i], tokens[i]);
- }
- }
- if (!valid) {
- return null;
- }
- }
- } else {
- throw new InvalidInputException();
- }
- }
- // Create node
- if (arguments == null) {
- if (isConstructor) {
- JavadocAllocationExpression allocation = new JavadocAllocationExpression(this.identifierPositionStack[length-1]);
- allocation.type = typeRef;
- allocation.tagValue = this.tagValue;
- allocation.sourceEnd = this.scanner.getCurrentTokenEndPosition();
- if (length == 1) {
- allocation.qualification = new char[][] { this.identifierStack[0] };
- } else {
- System.arraycopy(this.identifierStack, 0, allocation.qualification = new char[length][], 0, length);
- allocation.sourceStart = (int) (this.identifierPositionStack[0] >>> 32);
- }
- allocation.memberStart = this.memberStart;
- return allocation;
- } else {
- JavadocMessageSend msg = new JavadocMessageSend(this.identifierStack[length-1], this.identifierPositionStack[length-1]);
- msg.receiver = typeRef;
- msg.tagValue = this.tagValue;
- msg.sourceEnd = this.scanner.getCurrentTokenEndPosition();
- return msg;
- }
- } else {
- JavadocArgumentExpression[] expressions = new JavadocArgumentExpression[arguments.size()];
- arguments.toArray(expressions);
- if (isConstructor) {
- JavadocAllocationExpression allocation = new JavadocAllocationExpression(this.identifierPositionStack[length-1]);
- allocation.arguments = expressions;
- allocation.type = typeRef;
- allocation.tagValue = this.tagValue;
- allocation.sourceEnd = this.scanner.getCurrentTokenEndPosition();
- if (length == 1) {
- allocation.qualification = new char[][] { this.identifierStack[0] };
- } else {
- System.arraycopy(this.identifierStack, 0, allocation.qualification = new char[length][], 0, length);
- allocation.sourceStart = (int) (this.identifierPositionStack[0] >>> 32);
- }
- allocation.memberStart = this.memberStart;
- return allocation;
- } else {
- JavadocMessageSend msg = new JavadocMessageSend(this.identifierStack[length-1], this.identifierPositionStack[length-1], expressions);
- msg.receiver = typeRef;
- msg.tagValue = this.tagValue;
- msg.sourceEnd = this.scanner.getCurrentTokenEndPosition();
- return msg;
- }
- }
- }
- catch (ClassCastException ex) {
- throw new InvalidInputException();
- }
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.parser.AbstractCommentParser#createReturnStatement()
- */
- protected Object createReturnStatement() {
- return new JavadocReturnStatement(this.scanner.getCurrentTokenStartPosition(),
- this.scanner.getCurrentTokenEndPosition());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.parser.AbstractCommentParser#parseTagName()
- */
- protected void createTag() {
- this.tagValue = TAG_OTHERS_VALUE;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.parser.AbstractCommentParser#createTypeReference()
- */
- protected Object createTypeReference(int primitiveToken) {
- TypeReference typeRef = null;
- int size = this.identifierLengthStack[this.identifierLengthPtr];
- if (size == 1) { // Single Type ref
- typeRef = new JavadocSingleTypeReference(
- this.identifierStack[this.identifierPtr],
- this.identifierPositionStack[this.identifierPtr],
- this.tagSourceStart,
- this.tagSourceEnd);
- } else if (size > 1) { // Qualified Type ref
- char[][] tokens = new char[size][];
- System.arraycopy(this.identifierStack, this.identifierPtr - size + 1, tokens, 0, size);
- long[] positions = new long[size];
- System.arraycopy(this.identifierPositionStack, this.identifierPtr - size + 1, positions, 0, size);
- typeRef = new JavadocQualifiedTypeReference(tokens, positions, this.tagSourceStart, this.tagSourceEnd);
- }
- return typeRef;
- }
-
- /*
- * Get current parsed type declaration.
- */
- protected TypeDeclaration getParsedTypeDeclaration() {
- int ptr = this.sourceParser.astPtr;
- while (ptr >= 0) {
- Object node = this.sourceParser.astStack[ptr];
- if (node instanceof TypeDeclaration) {
- TypeDeclaration typeDecl = (TypeDeclaration) node;
- if (typeDecl.bodyEnd == 0) { // type declaration currenly parsed
- return typeDecl;
- }
- }
- ptr--;
- }
- return null;
- }
-
- /*
- * Parse @return tag declaration
- */
- protected boolean parseReturn() {
- if (this.returnStatement == null) {
- Object[] type = parseTypeReference();
- this.returnType = (TypeReference) (type != null && type.length > 0 ? type[0] : null);
- this.returnStatement = createReturnStatement();
- if((this.kind & TEXT_VERIF) != 0 && type != null && type.length > 0 && type[0] != null)
- refreshReturnStatement();
- return true;
- }
- if (this.reportProblems) {
- this.sourceParser.problemReporter().javadocDuplicatedReturnTag(
- this.scanner.getCurrentTokenStartPosition(),
- this.scanner.getCurrentTokenEndPosition());
- }
- return false;
- }
-
-
- protected void parseSimpleTag() {
-
- // Read first char
- // readChar() code is inlined to balance additional method call in checkDeprectation(int)
- char first = this.source[this.index++];
- if (first == '\\' && this.source[this.index] == 'u') {
- int c1, c2, c3, c4;
- int pos = this.index;
- this.index++;
- while (this.source[this.index] == 'u')
- this.index++;
- if (!(((c1 = ScannerHelper.getNumericValue(this.source[this.index++])) > 15 || c1 < 0)
- || ((c2 = ScannerHelper.getNumericValue(this.source[this.index++])) > 15 || c2 < 0)
- || ((c3 = ScannerHelper.getNumericValue(this.source[this.index++])) > 15 || c3 < 0) || ((c4 = ScannerHelper.getNumericValue(this.source[this.index++])) > 15 || c4 < 0))) {
- first = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4);
- } else {
- this.index = pos;
- }
- }
-
- // switch on first tag char
- switch (first) {
- case 'd':
- if ((readChar() == 'e') &&
- (readChar() == 'p') && (readChar() == 'r') &&
- (readChar() == 'e') && (readChar() == 'c') &&
- (readChar() == 'a') && (readChar() == 't') &&
- (readChar() == 'e') && (readChar() == 'd')) {
- // ensure the tag is properly ended: either followed by a space, a tab, line end or asterisk.
- char c = readChar();
- if (ScannerHelper.isWhitespace(c) || c == '*') {
- this.abort = true;
- this.deprecated = true;
- this.tagValue = TAG_DEPRECATED_VALUE;
- }
- }
- break;
- }
- }
-
- protected boolean parseTag(int previousPosition) throws InvalidInputException {
- boolean valid = false;
-
- // Read tag name
- int currentPosition = this.index;
- int token = readTokenAndConsume();
- if (currentPosition != this.scanner.startPosition) {
- this.tagSourceStart = previousPosition;
- this.tagSourceEnd = currentPosition;
- if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidTag(this.tagSourceStart, this.tagSourceEnd);
- return false;
- }
- if (this.index >= this.scanner.eofPosition) {
- this.tagSourceStart = previousPosition;
- this.tagSourceEnd = this.tokenPreviousPosition;
- if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidTag(this.tagSourceStart, this.tagSourceEnd);
- return false;
- }
- this.tagSourceStart = this.scanner.getCurrentTokenStartPosition();
- this.tagSourceEnd = this.scanner.getCurrentTokenEndPosition();
- char[] tagName = this.scanner.getCurrentIdentifierSource();
-
- // Try to get tag name other than java identifier
- // (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=51660)
- if (this.scanner.currentCharacter != ' ' && !ScannerHelper.isWhitespace(this.scanner.currentCharacter)) {
- boolean validTag = true;
- tagNameToken: while (token != TerminalTokens.TokenNameEOF && this.index < this.scanner.eofPosition) {
- int length = tagName.length;
- // !, ", #, %, &, ', -, :, <, >, * chars and spaces are not allowed in tag names
- switch (this.scanner.currentCharacter) {
- case '}':
- case '*': // break for '*' as this is perhaps the end of comment (bug 65288)
- break tagNameToken;
- case '!':
- case '#':
- case '%':
- case '&':
- case '\'':
- case '"':
- case ':':
- case '<':
- case '>':
- case '@':
- validTag = false;
- this.tagSourceEnd = this.scanner.getCurrentTokenEndPosition();
- this.index = this.scanner.currentPosition;
- break;
- case '-': // allowed in tag names as this character is often used in doclets (bug 68087)
- System.arraycopy(tagName, 0, tagName = new char[length+1], 0, length);
- tagName[length] = this.scanner.currentCharacter;
- this.tagSourceEnd = this.scanner.getCurrentTokenEndPosition();
- this.index = this.scanner.currentPosition;
- break;
- default:
- if (this.scanner.currentCharacter == ' ' || ScannerHelper.isWhitespace(this.scanner.currentCharacter)) {
- break tagNameToken;
- }
- token = readTokenAndConsume();
- char[] ident = this.scanner.getCurrentIdentifierSource();
- System.arraycopy(tagName, 0, tagName = new char[length+ident.length], 0, length);
- System.arraycopy(ident, 0, tagName, length, ident.length);
- this.tagSourceEnd = this.scanner.getCurrentTokenEndPosition();
- break;
- }
- this.scanner.getNextChar();
- }
- if (!validTag) {
- if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidTag(this.tagSourceStart, this.tagSourceEnd);
- return false;
- }
- }
- int length = tagName.length;
- if (length == 0) return false; // may happen for some parser (completion for example)
- this.index = this.tagSourceEnd+1;
- this.scanner.currentPosition = this.tagSourceEnd+1;
-
- // Decide which parse to perform depending on tag name
- this.tagValue = NO_TAG_VALUE;
- switch (token) {
- case TerminalTokens.TokenNameIdentifier :
- switch (tagName[0]) {
- case 'a':
- if (length == TAG_ADDON_LENGTH && CharOperation.equals(TAG_ADDON, tagName)) {
- this.tagValue = TAG_ADDON_VALUE;
- valid=true;
- } else
- if (length == TAG_ALIAS_LENGTH && CharOperation.equals(TAG_ALIAS, tagName)) {
- this.tagValue = TAG_ALIAS_VALUE;
- valid=true;
- }
- else if (length == TAG_ARGUMENT_LENGTH && CharOperation.equals(TAG_ARGUMENT, tagName)) {
- this.tagValue = TAG_ARGUMENT_VALUE;
- valid=parseParam();
- }
- break;
- case 'b':
- if (length == TAG_BASE_LENGTH && CharOperation.equals(TAG_BASE, tagName)) {
- this.tagValue = TAG_BASE_VALUE;
- valid=parseExtends();
- }
- break;
- case 'c':
- if (length == TAG_CLASSDECRIPTION_LENGTH && CharOperation.equals(TAG_CLASSDECRIPTION, tagName)) {
- this.tagValue = TAG_CLASSDECRIPTION_VALUE;
- valid =true;
- } else if (length == TAG_CLASS_LENGTH && CharOperation.equals(TAG_CLASS, tagName)) {
- this.tagValue = TAG_CLASS_VALUE;
- valid =parseClass() ;
- } else
- if (length == TAG_CONSTRUCTOR_LENGTH && CharOperation.equals(TAG_CONSTRUCTOR, tagName)) {
- this.tagValue = TAG_CONSTRUCTOR_VALUE;
- this.isConstructor=true;
- valid =true;
- }
- break;
- case 'd':
- if (length == TAG_DEPRECATED_LENGTH && CharOperation.equals(TAG_DEPRECATED, tagName)) {
- this.deprecated = true;
- valid = true;
- this.tagValue = TAG_DEPRECATED_VALUE;
- }
- break;
- case 'e':
- if (length == TAG_EXCEPTION_LENGTH && CharOperation.equals(TAG_EXCEPTION, tagName)) {
- this.tagValue = TAG_EXCEPTION_VALUE;
- valid = parseThrows();
- } else
- if (length == TAG_EXTENDS_LENGTH && CharOperation.equals(TAG_EXTENDS, tagName)) {
- this.tagValue = TAG_EXTENDS_VALUE;
- valid = parseExtends();
- } else
- if (length == TAG_EXEC_LENGTH && CharOperation.equals(TAG_EXEC, tagName)) {
- this.tagValue = TAG_EXEC_VALUE;
- valid = true;
- }
-
- break;
- case 'f':
- if (length == TAG_FILEOVERVIEW_LENGTH && CharOperation.equals(TAG_FILEOVERVIEW, tagName)) {
- this.tagValue = TAG_FILEOVERVIEW_VALUE;
- valid = true;
- } else
- if (length == TAG_FINAL_LENGTH && CharOperation.equals(TAG_FINAL, tagName)) {
- this.tagValue = TAG_FINAL_VALUE;
- this.flags|=ClassFileConstants.AccFinal;
- valid = true;
- }
- break;
- case 'i':
- if (length == TAG_ID_LENGTH && CharOperation.equals(TAG_ID, tagName)) {
- this.tagValue = TAG_ID_VALUE;
- valid = true;
- }
- else if (length == TAG_IGNORE_LENGTH && CharOperation.equals(TAG_IGNORE, tagName)) {
- this.tagValue = TAG_IGNORE_VALUE;
- valid = true;
- }
- break;
- case 'l':
- if (length == TAG_LINK_LENGTH && CharOperation.equals(TAG_LINK, tagName)) {
- this.tagValue = TAG_LINK_VALUE;
- if (this.inlineTagStarted || (this.kind & COMPLETION_PARSER) != 0) {
- valid= parseReference();
- } else {
- // bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=53290
- // Cannot have @link outside inline comment
- valid = false;
- if (this.reportProblems) {
- this.sourceParser.problemReporter().javadocUnexpectedTag(this.tagSourceStart, this.tagSourceEnd);
- }
- }
- }
- break;
- case 'm':
- if (length == TAG_MEMBER_LENGTH && CharOperation.equals(TAG_MEMBER, tagName)) {
- this.tagValue = TAG_MEMBER_VALUE;
- valid = parseMember();
- }
- else if (length == TAG_MEMBEROF_LENGTH && CharOperation.equals(TAG_MEMBEROF, tagName)) {
- this.tagValue = TAG_MEMBEROF_VALUE;
- valid = parseMember();
- }
- else if (length == TAG_METHOD_LENGTH && CharOperation.equals(TAG_METHOD, tagName)) {
- this.tagValue = TAG_METHOD_VALUE;
- valid = parseMethod();
- }
- break;
- case 'n':
- if (length == TAG_NAMESPACE_LENGTH && CharOperation.equals(TAG_NAMESPACE, tagName)) {
- this.tagValue = TAG_NAMESPACE_VALUE;
- valid = parseNamespace();
- }
- break;
- case 'p':
- if (length == TAG_PARAM_LENGTH && CharOperation.equals(TAG_PARAM, tagName)) {
- this.tagValue = TAG_PARAM_VALUE;
- valid = parseParam();
- }
- else if (length == TAG_PRIVATE_LENGTH && CharOperation.equals(TAG_PRIVATE, tagName)) {
- this.tagValue = TAG_PRIVATE_VALUE;
- this.flags|=ClassFileConstants.AccPrivate;
- valid = true;
- }
- else if (length == TAG_PROJECT_DESCRIPTION_LENGTH && CharOperation.equals(TAG_PROJECT_DESCRIPTION, tagName)) {
- this.tagValue = TAG_PROJECT_DESCRIPTION_VALUE;
- valid = true;
- }
- else if (length == TAG_PROPERTY_LENGTH && CharOperation.equals(TAG_PROPERTY, tagName)) {
- this.tagValue = TAG_PROPERTY_VALUE;
- valid = parseProperty();
- }
- else if (length == TAG_PROTECTED_LENGTH && CharOperation.equals(TAG_PROTECTED, tagName)) {
- this.tagValue = TAG_PRIVATE_VALUE;
- this.flags|=ClassFileConstants.AccProtected;
- valid = true;
- }
- break;
- case 'r':
- if (length == TAG_RETURNS_LENGTH && CharOperation.equals(TAG_RETURNS, tagName)) {
- this.tagValue = TAG_RETURNS_VALUE;
- valid = parseReturn();
- } else if (length == TAG_RETURN_LENGTH && CharOperation.equals(TAG_RETURN, tagName)) {
- this.tagValue = TAG_RETURNS_VALUE;
- valid = parseReturn();
- }
- else if (length == TAG_REQUIRES_LENGTH && CharOperation.equals(TAG_REQUIRES, tagName)) {
- this.tagValue = TAG_REQUIRES_VALUE;
- valid = parseRequires();
- }
- break;
- case 's':
- if (length == TAG_SEE_LENGTH && CharOperation.equals(TAG_SEE, tagName)) {
- if (this.inlineTagStarted) {
- // bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=53290
- // Cannot have @see inside inline comment
- valid = false;
- if (this.reportProblems) {
- this.sourceParser.problemReporter().javadocUnexpectedTag(this.tagSourceStart, this.tagSourceEnd);
- }
- } else {
- this.tagValue = TAG_SEE_VALUE;
- valid = parseReference();
- }
- }
- else if (length == TAG_SDOC_LENGTH && CharOperation.equals(TAG_SDOC, tagName)) {
- this.tagValue = TAG_SDOC_VALUE;
- valid = true;
- }
- break;
-
- case 't':
- if (length == TAG_TYPE_LENGTH && CharOperation.equals(TAG_TYPE, tagName)) {
- this.tagValue = TAG_TYPE_VALUE;
- valid=parseType();
- }
- break;
- default:
- createTag();
- break;
- }
- break;
- case TerminalTokens.TokenNamereturn :
- this.tagValue = TAG_RETURN_VALUE;
- valid = parseReturn();
- /* verify characters after return tag (we're expecting text description)
- if(!verifyCharsAfterReturnTag(this.index)) {
- if (this.sourceParser != null) {
- int end = this.starPosition == -1 || this.lineEnd<this.starPosition ? this.lineEnd : this.starPosition;
- this.sourceParser.problemReporter().javadocEmptyReturnTag(this.tagSourceStart, end);
- }
- }
- */
- break;
- case TerminalTokens.TokenNamethrows :
- this.tagValue = TAG_THROWS_VALUE;
- valid = parseThrows();
- break;
- case TerminalTokens.TokenNameclass :
- this.tagValue = TAG_CLASS_VALUE;
- valid=true;
- break;
- case TerminalTokens.TokenNameextends :
- this.tagValue = TAG_EXTENDS_VALUE;
- valid=parseExtends();
- break;
- case TerminalTokens.TokenNameprivate :
- this.tagValue = TAG_PRIVATE_VALUE;
- this.flags|=ClassFileConstants.AccPrivate;
- valid=true;
- break;
- case TerminalTokens.TokenNameprotected :
- this.tagValue = TAG_PROTECTED_VALUE;
- this.flags|=ClassFileConstants.AccProtected;
- valid=true;
- break;
- case TerminalTokens.TokenNamefinal :
- this.tagValue = TAG_FINAL_VALUE;
- this.flags|=ClassFileConstants.AccFinal;
- valid=true;
- break;
- }
- this.textStart = this.index;
- return valid;
- }
-
- private boolean parseExtends() throws InvalidInputException {
- this.extendsType=(TypeReference)parseQualifiedName(true);
- return this.extendsType!=null;
- }
-
- private boolean parseType() throws InvalidInputException {
- this.returnType=(TypeReference)parseQualifiedName(true);
- return this.returnType!=null;
- }
-
- private boolean parseNamespace() throws InvalidInputException {
- this.namespace=(TypeReference) parseQualifiedName(true);
- return this.namespace!=null;
- }
-
- private boolean parseProperty() throws InvalidInputException {
- // Store current state
- int start = this.tagSourceStart;
- int end = this.tagSourceEnd;
- boolean tokenWhiteSpace = this.scanner.tokenizeWhiteSpace;
- this.scanner.tokenizeWhiteSpace = true;
- Object []typeReference=null;
-
-
- // Get first non whitespace token
- this.identifierPtr = -1;
- this.identifierLengthPtr = -1;
- boolean hasMultiLines = this.scanner.currentPosition > (this.lineEnd+1);
- boolean valid = true, empty = true;
- boolean isParmType=false;
- int token = -1;
- nextToken: while (true) {
- this.currentTokenType = -1;
- try {
- token = readToken();
- } catch (InvalidInputException e) {
- valid = false;
- }
- switch (token) {
- case TerminalTokens.TokenNameIdentifier :
- if (valid) {
- // store param name id
- pushIdentifier(true, false);
- start = this.scanner.getCurrentTokenStartPosition();
- end = hasMultiLines ? this.lineEnd: this.scanner.getCurrentTokenEndPosition();
- break nextToken;
- }
-
- // fall through next case to report error
- default:
- if (valid && !hasMultiLines) start = this.scanner.getCurrentTokenStartPosition();
- valid = false;
- if (!hasMultiLines) {
- empty = false;
- end = hasMultiLines ? this.lineEnd: this.scanner.getCurrentTokenEndPosition();
- break;
- }
- end = this.lineEnd;
- // when several lines, fall through next case to report problem immediately
- case TerminalTokens.TokenNameWHITESPACE:
- if (this.scanner.currentPosition > (this.lineEnd+1)) hasMultiLines = true;
- if (valid) break;
- // if not valid fall through next case to report error
- case TerminalTokens.TokenNameEOF:
- if (this.reportProblems)
- if (empty)
- this.sourceParser.problemReporter().javadocMissingParamName(start, end, this.sourceParser.modifiers);
- else
- this.sourceParser.problemReporter().javadocInvalidParamTagName(start, end);
-
- this.currentTokenType = -1;
- this.scanner.tokenizeWhiteSpace = tokenWhiteSpace;
- return false;
- case TerminalTokens.TokenNameLBRACE:
- this.scanner.tokenizeWhiteSpace = false;
- typeReference=parseTypeReference();
- isParmType=true;
- this.identifierPtr = -1;
- this.identifierLengthPtr = -1;
- this.scanner.tokenizeWhiteSpace = true;
- break;
-
- }
- }
-
-
- // Verify that tag name is well followed by white spaces
- if (valid) {
- this.currentTokenType = -1;
- int restart = this.scanner.currentPosition;
- try {
- token = readToken();
- } catch (InvalidInputException e) {
- valid = false;
- }
- if (token == TerminalTokens.TokenNameWHITESPACE) {
- this.scanner.currentPosition = restart;
- this.index = restart;
- this.scanner.tokenizeWhiteSpace = tokenWhiteSpace;
- valid= pushParamName(false);
- if (valid )
- {
- JavadocSingleNameReference nameRef=(JavadocSingleNameReference)this.astStack[this.astPtr];
- TypeReference [] refs=null;
- if (typeReference!=null && isParmType)
- {
- refs = new TypeReference[typeReference.length];
- System.arraycopy(typeReference, 0, refs, 0, typeReference.length);
- }
- nameRef.types=refs;
- this.property=nameRef;
- }
- return valid;
- }
- }
-
-
- // Report problem
- this.currentTokenType = -1;
-
- end = hasMultiLines ? this.lineEnd: this.scanner.getCurrentTokenEndPosition();
- while ((token=readToken()) != TerminalTokens.TokenNameWHITESPACE && token != TerminalTokens.TokenNameEOF) {
- this.currentTokenType = -1;
- end = hasMultiLines ? this.lineEnd: this.scanner.getCurrentTokenEndPosition();
- }
- if (this.reportProblems)
- this.sourceParser.problemReporter().javadocInvalidParamTagName(start, end);
- this.scanner.currentPosition = start;
- this.index = start;
- this.currentTokenType = -1;
- this.scanner.tokenizeWhiteSpace = tokenWhiteSpace;
- return false;
-
- }
-
- private boolean parseClass() throws InvalidInputException {
- this.classDef=(TypeReference) parseQualifiedName(true);
- return this.classDef!=null;
- }
-
- private boolean parseMethod() throws InvalidInputException {
- this.methodDef=(TypeReference) parseQualifiedName(true);
- return this.methodDef!=null;
- }
-
- private boolean parseMember() throws InvalidInputException {
- this.memberOf=(TypeReference) parseQualifiedName(true);
- return this.memberOf!=null;
- }
-
- /*
- * Push a param name in ast node stack.
- */
- protected boolean pushParamName(boolean isTypeParam) {
- // Create param reference
- ASTNode nameRef = null;
- if (isTypeParam) {
- JavadocSingleTypeReference ref = new JavadocSingleTypeReference(this.identifierStack[1],
- this.identifierPositionStack[1],
- this.tagSourceStart,
- this.tagSourceEnd);
- nameRef = ref;
- } else {
- JavadocSingleNameReference ref = new JavadocSingleNameReference(this.identifierStack[0],
- this.identifierPositionStack[0],
- this.tagSourceStart,
- this.tagSourceEnd);
- nameRef = ref;
- }
- // Push ref on stack
- if (this.astLengthPtr == -1) { // First push
- pushOnAstStack(nameRef, true);
- } else {
- // Verify that no @throws has been declared before
-
- for (int i=THROWS_TAG_EXPECTED_ORDER; i<=this.astLengthPtr; i+=ORDERED_TAGS_NUMBER) {
- if (this.astLengthStack[i] != 0) {
- if (this.reportProblems) this.sourceParser.problemReporter().javadocUnexpectedTag(this.tagSourceStart, this.tagSourceEnd);
- // bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=51600
- // store invalid param references in specific array
- if (this.invalidParamReferencesPtr == -1l) {
- this.invalidParamReferencesStack = new JavadocSingleNameReference[10];
- }
- int stackLength = this.invalidParamReferencesStack.length;
- if (++this.invalidParamReferencesPtr >= stackLength) {
- System.arraycopy(
- this.invalidParamReferencesStack, 0,
- this.invalidParamReferencesStack = new JavadocSingleNameReference[stackLength + AST_STACK_INCREMENT], 0,
- stackLength);
- }
- this.invalidParamReferencesStack[this.invalidParamReferencesPtr] = nameRef;
- return false;
- }
- }
-
- switch (this.astLengthPtr % ORDERED_TAGS_NUMBER) {
- case PARAM_TAG_EXPECTED_ORDER :
- // previous push was a @param tag => push another param name
- pushOnAstStack(nameRef, false);
- break;
- case SEE_TAG_EXPECTED_ORDER :
- // previous push was a @see tag => push new param name
- pushOnAstStack(nameRef, true);
- break;
- default:
- return false;
- }
- }
- return true;
- }
-
- /*
- * Push a reference statement in ast node stack.
- */
- protected boolean pushSeeRef(Object statement) {
- if (this.astLengthPtr == -1) { // First push
- pushOnAstStack(null, true);
- pushOnAstStack(null, true);
- pushOnAstStack(statement, true);
- } else {
- switch (this.astLengthPtr % ORDERED_TAGS_NUMBER) {
- case PARAM_TAG_EXPECTED_ORDER :
- // previous push was a @param tag => push empty @throws tag and new @see tag
- pushOnAstStack(null, true);
- pushOnAstStack(statement, true);
- break;
- case THROWS_TAG_EXPECTED_ORDER :
- // previous push was a @throws tag => push new @see tag
- pushOnAstStack(statement, true);
- break;
- case SEE_TAG_EXPECTED_ORDER :
- // previous push was a @see tag => push another @see tag
- pushOnAstStack(statement, false);
- break;
- default:
- return false;
- }
- }
- return true;
- }
-
- /*
- * Push a throws type ref in ast node stack.
- */
- protected boolean pushThrowName(Object typeRef) {
- if (this.astLengthPtr == -1) { // First push
- pushOnAstStack(null, true);
- pushOnAstStack(typeRef, true);
- } else {
- switch (this.astLengthPtr % ORDERED_TAGS_NUMBER) {
- case PARAM_TAG_EXPECTED_ORDER :
- // previous push was a @param tag => push new @throws tag
- pushOnAstStack(typeRef, true);
- break;
- case THROWS_TAG_EXPECTED_ORDER :
- // previous push was a @throws tag => push another @throws tag
- pushOnAstStack(typeRef, false);
- break;
- case SEE_TAG_EXPECTED_ORDER :
- // previous push was a @see tag => push empty @param and new @throws tags
- pushOnAstStack(null, true);
- pushOnAstStack(typeRef, true);
- break;
- default:
- return false;
- }
- }
- return true;
- }
-
- /*
- * Refresh return statement
- */
- protected void refreshReturnStatement() {
- ((JavadocReturnStatement) this.returnStatement).bits &= ~ASTNode.Empty;
- }
-
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- buffer.append("check javadoc: ").append(this.checkDocComment).append("\n"); //$NON-NLS-1$ //$NON-NLS-2$
- buffer.append("javadoc: ").append(this.docComment).append("\n"); //$NON-NLS-1$ //$NON-NLS-2$
- buffer.append(super.toString());
- return buffer.toString();
- }
-
- /*
- * Fill associated comment fields with ast nodes information stored in stack.
- */
- protected void updateDocComment() {
-
- this.docComment.modifiers=this.flags;
-
-
- this.docComment.namespace=this.namespace;
- this.docComment.memberOf=this.memberOf;
- this.docComment.returnType=this.returnType;
- this.docComment.extendsType=this.extendsType;
- this.docComment.classDef=this.classDef;
- this.docComment.methodDef=this.methodDef;
- this.docComment.property=this.property;
-
- this.docComment.isConstructor=this.isConstructor;
-
- // Set positions
- this.docComment.inheritedPositions = this.inheritedPositions;
- this.docComment.valuePositions = this.validValuePositions != -1 ? this.validValuePositions : this.invalidValuePositions;
-
- // Set return node if present
- if (this.returnStatement != null) {
- this.docComment.returnStatement = (JavadocReturnStatement) this.returnStatement;
- }
-
- // Copy array of invalid syntax param tags
- if (this.invalidParamReferencesPtr >= 0) {
- this.docComment.invalidParameters = new JavadocSingleNameReference[this.invalidParamReferencesPtr+1];
- System.arraycopy(this.invalidParamReferencesStack, 0, this.docComment.invalidParameters, 0, this.invalidParamReferencesPtr+1);
- }
-
- // If no nodes stored return
- if (this.astLengthPtr == -1) {
- return;
- }
-
- // Initialize arrays
- int[] sizes = new int[ORDERED_TAGS_NUMBER];
- for (int i=0; i<=this.astLengthPtr; i++) {
- sizes[i%ORDERED_TAGS_NUMBER] += this.astLengthStack[i];
- }
- this.docComment.seeReferences = new Expression[sizes[SEE_TAG_EXPECTED_ORDER]];
- this.docComment.exceptionReferences = new TypeReference[sizes[THROWS_TAG_EXPECTED_ORDER]];
- int paramRefPtr = sizes[PARAM_TAG_EXPECTED_ORDER];
- this.docComment.paramReferences = new JavadocSingleNameReference[paramRefPtr];
-
- // Store nodes in arrays
- while (this.astLengthPtr >= 0) {
- int ptr = this.astLengthPtr % ORDERED_TAGS_NUMBER;
- // Starting with the stack top, so get references (eg. Expression) coming from @see declarations
- switch(ptr) {
- case SEE_TAG_EXPECTED_ORDER:
- int size = this.astLengthStack[this.astLengthPtr--];
- for (int i=0; i<size; i++) {
- this.docComment.seeReferences[--sizes[ptr]] = (Expression) this.astStack[this.astPtr--];
- }
- break;
-
- // Then continuing with class names (eg. TypeReference) coming from @throw/@exception declarations
- case THROWS_TAG_EXPECTED_ORDER:
- size = this.astLengthStack[this.astLengthPtr--];
- for (int i=0; i<size; i++) {
- this.docComment.exceptionReferences[--sizes[ptr]] = (TypeReference) this.astStack[this.astPtr--];
- }
- break;
-
- // Finally, finishing with parameters nales (ie. Argument) coming from @param declaration
- case PARAM_TAG_EXPECTED_ORDER:
- size = this.astLengthStack[this.astLengthPtr--];
- for (int i=0; i<size; i++) {
- Expression reference = (Expression) this.astStack[this.astPtr--];
- if (reference instanceof JavadocSingleNameReference)
- this.docComment.paramReferences[--paramRefPtr] = (JavadocSingleNameReference) reference;
- }
- break;
- }
- }
-
- // Resize param tag references arrays
- if (paramRefPtr != 0) { // there's no type parameters references
- // there both of references => resize arrays
- int size = sizes[PARAM_TAG_EXPECTED_ORDER];
- System.arraycopy(this.docComment.paramReferences, paramRefPtr, this.docComment.paramReferences = new JavadocSingleNameReference[size - paramRefPtr], 0, size - paramRefPtr);
- }
- }
-
- protected void createParamType(Object[] typeReference) {
- JavadocSingleNameReference nameRef=(JavadocSingleNameReference)this.astStack[this.astPtr];
- TypeReference [] refs=null;
- if (typeReference!=null)
- {
- refs = new TypeReference[typeReference.length];
- System.arraycopy(typeReference, 0, refs, 0, typeReference.length);
- }
- nameRef.types=refs;
- }
-
- protected boolean parseRequires()
- {
- return true;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/JavadocTagConstants.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/JavadocTagConstants.java
deleted file mode 100644
index 5d5560b5..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/JavadocTagConstants.java
+++ /dev/null
@@ -1,284 +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.compiler.parser;
-
-/**
- * Javadoc tag constants.
- *
- * @since 3.2
- */
-public interface JavadocTagConstants {
-
- // recognized JSdoc tags
- public static final char[] TAG_AUGMENTS = "augments".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_AUTHOR = "author".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_ARGUMENT = "argument".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_BORROWS = "borrows".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_CLASS = "class".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_CONSTANT = "constant".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_CONSTRUCTOR = "constructor".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_CONSTRUCTS = "constructs".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_DEFAULT = "default".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_DEPRECATED = "deprecated".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_DESCRIPTION = "description".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_EVENT = "event".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_EXAMPLE = "example".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_EXTENDS = "extends".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_FIELD = "field".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_FILEOVERVIEW = "fileOverview".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_FUNCTION = "function".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_IGNORE = "ignore".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_INNER = "inner".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_LENDS = "lends".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_LINK = "link".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_MEMBEROF = "memberOf".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_NAME = "name".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_NAMESPACE = "namespace".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_PARAM = "param".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_PRIVATE = "private".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_PROPERTY = "property".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_PUBLIC = "public".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_REQUIRES = "requires".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_RETURN = "return".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_RETURNS = "returns".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_SEE = "see".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_SINCE = "since".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_STATIC = "static".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_THROWS = "throws".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_TYPE = "type".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_VERSION = "version".toCharArray(); //$NON-NLS-1$
-
- // legacy JSdoc tags
- public static final char[] TAG_EXCEPTION = "exception".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_FINAL = "final".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_MEMBER = "member".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_BASE = "base".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_ADDON = "addon".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_EXEC = "exec".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_PROTECTED = "protected".toCharArray(); //$NON-NLS-1$
-
- // from scriptdoc.org
- public static final char[] TAG_ALIAS = "alias".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_CLASSDECRIPTION = "classDescription".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_ID = "id".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_PROJECT_DESCRIPTION = "projectDescription".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_SDOC = "sdoc".toCharArray(); //$NON-NLS-1$
- public static final char[] TAG_METHOD = "method".toCharArray(); //$NON-NLS-1$
-
- // tags lengths
- public static final int TAG_AUGMENTS_LENGTH = TAG_AUGMENTS.length;
- public static final int TAG_AUTHOR_LENGTH = TAG_AUTHOR.length;
- public static final int TAG_ARGUMENT_LENGTH = TAG_ARGUMENT.length;
- public static final int TAG_BORROWS_LENGTH = TAG_BORROWS.length;
- public static final int TAG_CLASS_LENGTH = TAG_CLASS.length;
- public static final int TAG_CONSTANT_LENGTH = TAG_CONSTANT.length;
- public static final int TAG_CONSTRUCTOR_LENGTH = TAG_CONSTRUCTOR.length;
- public static final int TAG_CONSTRUCTS_LENGTH = TAG_CONSTRUCTS.length;
- public static final int TAG_DEFAULT_LENGTH = TAG_DEFAULT.length;
- public static final int TAG_DEPRECATED_LENGTH = TAG_DEPRECATED.length;
- public static final int TAG_DESCRIPTION_LENGTH = TAG_DESCRIPTION.length;
- public static final int TAG_EVENT_LENGTH = TAG_EVENT.length;
- public static final int TAG_EXAMPLE_LENGTH = TAG_EXAMPLE.length;
- public static final int TAG_EXTENDS_LENGTH = TAG_EXTENDS.length;
- public static final int TAG_FIELD_LENGTH = TAG_FIELD.length;
- public static final int TAG_FILEOVERVIEW_LENGTH = TAG_FILEOVERVIEW.length;
- public static final int TAG_FUNCTION_LENGTH = TAG_FUNCTION.length;
- public static final int TAG_IGNORE_LENGTH = TAG_IGNORE.length;
- public static final int TAG_INNER_LENGTH = TAG_INNER.length;
- public static final int TAG_LENDS_LENGTH = TAG_LENDS.length;
- public static final int TAG_LINK_LENGTH = TAG_LINK.length;
- public static final int TAG_MEMBEROF_LENGTH = TAG_MEMBEROF.length;
- public static final int TAG_NAME_LENGTH = TAG_NAME.length;
- public static final int TAG_NAMESPACE_LENGTH = TAG_NAMESPACE.length;
- public static final int TAG_PARAM_LENGTH = TAG_PARAM.length;
- public static final int TAG_PRIVATE_LENGTH = TAG_PRIVATE.length;
- public static final int TAG_PROPERTY_LENGTH = TAG_PROPERTY.length;
- public static final int TAG_PUBLIC_LENGTH = TAG_PUBLIC.length;
- public static final int TAG_REQUIRES_LENGTH = TAG_REQUIRES.length;
- public static final int TAG_RETURN_LENGTH = TAG_RETURN.length;
- public static final int TAG_RETURNS_LENGTH = TAG_RETURNS.length;
- public static final int TAG_SEE_LENGTH = TAG_SEE.length;
- public static final int TAG_SINCE_LENGTH = TAG_SINCE.length;
- public static final int TAG_STATIC_LENGTH = TAG_STATIC.length;
- public static final int TAG_THROWS_LENGTH = TAG_THROWS.length;
- public static final int TAG_TYPE_LENGTH = TAG_TYPE.length;
- public static final int TAG_VERSION_LENGTH = TAG_VERSION.length;
-
- public static final int TAG_EXCEPTION_LENGTH = TAG_EXCEPTION.length;
- public static final int TAG_FINAL_LENGTH = TAG_FINAL.length;
- public static final int TAG_MEMBER_LENGTH = TAG_MEMBER.length;
- public static final int TAG_BASE_LENGTH = TAG_BASE.length;
- public static final int TAG_ADDON_LENGTH = TAG_ADDON.length;
- public static final int TAG_EXEC_LENGTH = TAG_EXEC.length;
- public static final int TAG_PROTECTED_LENGTH = TAG_PROTECTED.length;
-
- public static final int TAG_ALIAS_LENGTH = TAG_ALIAS.length;
- public static final int TAG_CLASSDECRIPTION_LENGTH = TAG_CLASSDECRIPTION.length;
- public static final int TAG_ID_LENGTH = TAG_ID.length;
- public static final int TAG_PROJECT_DESCRIPTION_LENGTH = TAG_PROJECT_DESCRIPTION.length;
- public static final int TAG_SDOC_LENGTH = TAG_SDOC.length;
- public static final int TAG_METHOD_LENGTH = TAG_METHOD.length;
-
- // tags value
- public static final int NO_TAG_VALUE = 0;
- public static final int TAG_AUGMENTS_VALUE = 1;
- public static final int TAG_AUTHOR_VALUE = 2;
- public static final int TAG_ARGUMENT_VALUE = 3;
- public static final int TAG_BORROWS_VALUE = 4;
- public static final int TAG_CLASS_VALUE = 5;
- public static final int TAG_CONSTANT_VALUE = 6;
- public static final int TAG_CONSTRUCTOR_VALUE = 7;
- public static final int TAG_CONSTRUCTS_VALUE = 8;
- public static final int TAG_DEFAULT_VALUE = 9;
- public static final int TAG_DEPRECATED_VALUE = 10;
- public static final int TAG_DESCRIPTION_VALUE = 11;
- public static final int TAG_EVENT_VALUE = 12;
- public static final int TAG_EXAMPLE_VALUE = 13;
- public static final int TAG_EXTENDS_VALUE = 14;
- public static final int TAG_FIELD_VALUE = 15;
- public static final int TAG_FILEOVERVIEW_VALUE = 16;
- public static final int TAG_FUNCTION_VALUE = 17;
- public static final int TAG_IGNORE_VALUE = 18;
- public static final int TAG_INNER_VALUE = 19;
- public static final int TAG_LENDS_VALUE = 20;
- public static final int TAG_LINK_VALUE = 21;
- public static final int TAG_MEMBEROF_VALUE = 22;
- public static final int TAG_NAME_VALUE = 23;
- public static final int TAG_NAMESPACE_VALUE = 24;
- public static final int TAG_PARAM_VALUE = 25;
- public static final int TAG_PRIVATE_VALUE = 26;
- public static final int TAG_PROPERTY_VALUE = 27;
- public static final int TAG_PUBLIC_VALUE = 28;
- public static final int TAG_REQUIRES_VALUE = 29;
- public static final int TAG_RETURN_VALUE = 30;
- public static final int TAG_RETURNS_VALUE = 31;
- public static final int TAG_SEE_VALUE = 32;
- public static final int TAG_SINCE_VALUE = 33;
- public static final int TAG_STATIC_VALUE = 34;
- public static final int TAG_THROWS_VALUE = 35;
- public static final int TAG_TYPE_VALUE = 36;
- public static final int TAG_VERSION_VALUE = 37;
-
- public static final int TAG_EXCEPTION_VALUE = 38;
- public static final int TAG_FINAL_VALUE = 39;
- public static final int TAG_MEMBER_VALUE = 40;
- public static final int TAG_BASE_VALUE = 41;
- public static final int TAG_ADDON_VALUE = 42;
- public static final int TAG_EXEC_VALUE = 43;
- public static final int TAG_PROTECTED_VALUE = 44;
-
- public static final int TAG_ALIAS_VALUE = 45;
- public static final int TAG_CLASSDECRIPTION_VALUE = 46;
- public static final int TAG_ID_VALUE = 47;
- public static final int TAG_PROJECT_DESCRIPTION_VALUE = 48;
- public static final int TAG_SDOC_VALUE = 49;
- public static final int TAG_METHOD_VALUE = 50;
-
- public static final int TAG_OTHERS_VALUE = 100;
-
- // tags expected positions
- public final static int PARAM_TAG_EXPECTED_ORDER = 0;
- public final static int THROWS_TAG_EXPECTED_ORDER = 1;
- public final static int SEE_TAG_EXPECTED_ORDER = 2;
- public final static int ORDERED_TAGS_NUMBER = 3;
-
- /*
- * Tag kinds indexes
- */
- public final static int BLOCK_IDX = 0;
- public final static int INLINE_IDX = 1;
-
- /*
- * Tags versions
- */
- public static final char[][][] BLOCK_TAGS = {
- // since 1.0
- { TAG_AUGMENTS, TAG_AUTHOR, TAG_ARGUMENT, TAG_BORROWS, TAG_CLASS, TAG_CONSTANT, TAG_CONSTRUCTOR, TAG_CONSTRUCTS,
- TAG_DEFAULT, TAG_DEPRECATED, TAG_DESCRIPTION, TAG_EVENT, TAG_EXAMPLE, TAG_EXTENDS, TAG_FIELD, TAG_FILEOVERVIEW,
- TAG_FUNCTION, TAG_IGNORE, TAG_INNER, TAG_LENDS, TAG_MEMBEROF, TAG_NAME, TAG_NAMESPACE, TAG_PARAM, TAG_PRIVATE,
- TAG_PROPERTY, TAG_PUBLIC, TAG_REQUIRES, TAG_RETURN, TAG_RETURNS, TAG_SEE, TAG_SINCE, TAG_STATIC, TAG_THROWS,
- TAG_TYPE, TAG_VERSION, TAG_EXCEPTION, TAG_FINAL, TAG_MEMBER, TAG_BASE, TAG_ADDON, TAG_EXEC, TAG_PROTECTED,
- TAG_ALIAS, TAG_CLASSDECRIPTION, TAG_ID, TAG_PROJECT_DESCRIPTION, TAG_SDOC, TAG_METHOD},
- // since 1.1
- {},
- // since 1.2
- {},
- // since 1.3
- {},
- // since 1.4
- {},
- // since 1.5
- {},
- // since 1.6
- {}
- };
- public static final char[][][] INLINE_TAGS = {
- // since 1.0
- {TAG_LINK},
- // since 1.1
- {},
- // since 1.2
- {},
- // since 1.3
- {},
- // since 1.4
- {},
- // since 1.5
- {},
- // since 1.6
- {}
- };
-
- public final static int INLINE_TAGS_LENGTH = INLINE_TAGS.length;
- public final static int BLOCK_TAGS_LENGTH = BLOCK_TAGS.length;
- public final static int ALL_TAGS_LENGTH = BLOCK_TAGS_LENGTH+INLINE_TAGS_LENGTH;
-
- /*
- * Tags usage
- */
- public static final char[][] PACKAGE_TAGS = {
- TAG_SEE,
- TAG_SINCE,
- TAG_AUTHOR,
- TAG_VERSION,
- TAG_LINK,
- TAG_CLASSDECRIPTION,TAG_FILEOVERVIEW,TAG_PROJECT_DESCRIPTION
- };
- public static final char[][] CLASS_TAGS = {
- TAG_SEE,
- TAG_SINCE,
- TAG_DEPRECATED,
- TAG_AUTHOR,
- TAG_VERSION,
- TAG_PARAM,
- TAG_LINK,
- TAG_CLASSDECRIPTION,TAG_NAMESPACE, TAG_REQUIRES, TAG_PRIVATE,TAG_CLASS
- };
- public static final char[][] FIELD_TAGS = {
- TAG_SEE,
- TAG_SINCE,
- TAG_DEPRECATED,
- TAG_LINK,
- TAG_MEMBEROF,TAG_FINAL,TAG_PRIVATE
- };
- public static final char[][] METHOD_TAGS = {
- TAG_SEE,
- TAG_SINCE,
- TAG_DEPRECATED,
- TAG_PARAM,
- TAG_RETURNS,
- TAG_THROWS,
- TAG_EXCEPTION,
- TAG_LINK,
- TAG_BASE, TAG_ADDON,TAG_CONSTRUCTOR,TAG_TYPE
- };
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/NLSTag.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/NLSTag.java
deleted file mode 100644
index 04fd1283..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/NLSTag.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.parser;
-
-public class NLSTag {
-
- public int start;
- public int end;
- public int lineNumber;
- public int index;
-
- public NLSTag(int start, int end, int lineNumber, int index) {
- this.start = start;
- this.end = end;
- this.lineNumber = lineNumber;
- this.index = index;
- }
-
- public String toString() {
- return "NLSTag(" + this.start + "," + this.end + "," + this.lineNumber + ")"; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$
- }
-}
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
deleted file mode 100644
index 4f401466..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/Parser.java
+++ /dev/null
@@ -1,7102 +0,0 @@
-/*******************************************************************************
- * 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 <epfister@hsr.ch> 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]+TokenNameSEMICOLON<term_check.length
- && (term_check[base_action[i]+TokenNameSEMICOLON] == TokenNameSEMICOLON))
- {
- int act=term_action[base_action[i]+TokenNameSEMICOLON];
- if (act>ERROR_ACTION)
- act-=ERROR_ACTION;
- boolean isEmptyStatementsState = false;
- if (act<NUM_RULES)
- isEmptyStatementsState = (state_flags[act]&FLAG_EMPTY_STATEMENT)>0;
- 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<compUnitStatments[compUnitStatments.length-1].sourceEnd)
- {
- ProgramElement programElement = compUnitStatments[compUnitStatments.length-1];
-
- this.lastCheckPoint=((programElement instanceof Expression) ? ((Expression)programElement).statementEnd : programElement.sourceEnd)+1;
- }
- return element;
-}
-
-public RecoveredElement recoverAST(RecoveredElement element) {
- for(int i = 0; i <= this.astPtr; i++){
- ASTNode node = this.astStack[i];
- if (node instanceof AbstractMethodDeclaration){
- AbstractMethodDeclaration method = (AbstractMethodDeclaration) node;
- if (method.selector!=null)
- {
- if (method.declarationSourceEnd == 0){
- element = element.add(method, 0);
- this.lastCheckPoint = method.bodyStart;
- } else {
- element = element.add(method, 0);
- this.lastCheckPoint = method.declarationSourceEnd + 1;
- }
- }
- else
- element = recoverFunctionExpression(element,method);
- continue;
- }
- if (node instanceof Initializer){
- Initializer initializer = (Initializer) node;
- if (initializer.declarationSourceEnd == 0){
- element = element.add(initializer, 1);
- this.lastCheckPoint = initializer.sourceStart;
- } else {
- element = element.add(initializer, 0);
- this.lastCheckPoint = initializer.declarationSourceEnd + 1;
- }
- continue;
- }
- if (node instanceof FieldDeclaration){
- FieldDeclaration field = (FieldDeclaration) node;
- if (field.declarationSourceEnd == 0){
- element = element.add(field, 0);
- if (field.initialization == null){
- this.lastCheckPoint = field.sourceEnd + 1;
- } else {
- this.lastCheckPoint = field.initialization.sourceEnd + 1;
- }
- } else {
- element = element.add(field, 0);
- this.lastCheckPoint = field.declarationSourceEnd + 1;
- }
- continue;
- }
- if (node instanceof LocalDeclaration){
- LocalDeclaration localDecl = (LocalDeclaration) node;
- if (localDecl.declarationSourceEnd == 0){
- element = element.add(localDecl, 0);
- if (localDecl.initialization == null){
- this.lastCheckPoint = localDecl.sourceEnd + 1;
- } else {
- this.lastCheckPoint = localDecl.initialization.sourceEnd + 1;
- }
- } else {
- element = element.add(localDecl, 0);
- this.lastCheckPoint = localDecl.declarationSourceEnd + 1;
- }
- continue;
- }
- if (node instanceof TypeDeclaration){
- TypeDeclaration type = (TypeDeclaration) node;
- if (type.declarationSourceEnd == 0){
- element = element.add(type, 0);
- this.lastCheckPoint = type.bodyStart;
- } else {
- element = element.add(type, 0);
- this.lastCheckPoint = type.declarationSourceEnd + 1;
- }
- continue;
- }
- if (node instanceof Statement){
- Statement statement = (Statement) node;
- if (statement.sourceEnd == 0){
- element = element.add(statement, 1);
- this.lastCheckPoint = statement.sourceStart;
- } else {
- element = element.add(statement, 0);
- this.lastCheckPoint = statement.sourceEnd + 1;
- }
- continue;
- }
- if (node instanceof ImportReference){
- ImportReference importRef = (ImportReference) node;
- element = element.add(importRef, 0);
- this.lastCheckPoint = importRef.declarationSourceEnd + 1;
- }
- if(this.statementRecoveryActivated) {
- if(node instanceof Block) {
- Block block = (Block) node;
- element = element.add(block, 0);
- this.lastCheckPoint = block.sourceEnd + 1;
- } else if(node instanceof LocalDeclaration) {
- LocalDeclaration statement = (LocalDeclaration) node;
- element = element.add(statement, 0);
- this.lastCheckPoint = statement.declarationSourceEnd + 1;
- } else if(node instanceof Expression) {
- if(node instanceof Assignment ||
- node instanceof PrefixExpression ||
- node instanceof PostfixExpression ||
- node instanceof MessageSend ||
- node instanceof AllocationExpression) {
- // recover only specific expressions
- Expression statement = (Expression) node;
- element = element.add(statement, 0);
- if(statement.statementEnd != -1) {
- this.lastCheckPoint = statement.statementEnd + 1;
- } else {
- this.lastCheckPoint = statement.sourceEnd + 1;
- }
- }
- } else if(node instanceof Statement) {
- Statement statement = (Statement) node;
- element = element.add(statement, 0);
- this.lastCheckPoint = statement.sourceEnd + 1;
- }
- }
- }
- return element;
-}
-
-protected RecoveredElement recoverFunctionExpression(RecoveredElement element, AbstractMethodDeclaration method) {
- int start = method.exprStackPtr;
-// int end=this.expressionPtr;
- boolean isAssignment=true;
- Statement expression=null;
-
- FunctionExpression funcExpr=new FunctionExpression((MethodDeclaration)method);
- funcExpr.sourceEnd=method.declarationSourceEnd;
- funcExpr.sourceStart=method.sourceStart;
-
-
- if (isAssignment && start>=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<variableDeclaratorsCounter; i++) {
- AbstractVariableDeclaration localDeclaration = (AbstractVariableDeclaration) this.astStack[this.astPtr - i];
- localDeclaration.declarationSourceEnd = this.endStatementPosition;
- localDeclaration.declarationEnd = this.endStatementPosition; // semi-colon included
- localDeclaration.nextLocal=nextDeclaration;
- nextDeclaration=localDeclaration;
- }
- this.astPtr-=variableDeclaratorsCounter-1;
- this.astLengthStack[this.astLengthPtr]=1;
- this.lastCheckPoint = endStatementPosition+1;
-
-}
-protected void consumeMemberExpressionWithArrayReference() {
- 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 consumeMemberExpressionWithSimpleName() {
- 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 consumeMethodBody() {
- // MethodBody ::= NestedMethod '{' BlockStatementsopt '}'
- this.nestedMethod[this.nestedType] --;
-}
-protected void consumeMethodDeclaration(boolean isNotAbstract) {
- // FunctionDeclaration ::= MethodHeader MethodBody
- // AbstractMethodDeclaration ::= MethodHeader ';'
-
- /*
- this.astStack : modifiers arguments throws statements
- this.identifierStack : type name
- this.intStack : dim dim dim
- ==>
- 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 <argument-block> [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 <HERE>
- 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++) //<HERE> 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 <HERE>
- 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++) //<HERE> 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 <position>, or the end position of a comment line
- * immediately following the <position> (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 <position> is immediately followed by a line comment, then
- // flush this comment and shift <position> 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 consume Token: "+scanner.toStringAction(this.currentToken)); //$NON-NLS-1$
- return false;
-// consumeToken(this.currentToken);
-// if (this.currentElement != null) this.recoveryTokenCheck();
-// try {
-// prevPos = scanner.currentPosition;
-// prevToken = currentToken;
-// insertedSemicolon = false;
-// this.currentToken = this.scanner.getNextToken();
-// 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 consume Token: "+scanner.toStringAction(this.currentToken)); //$NON-NLS-1$
- return false;
-// consumeToken(this.currentToken);
-// if (this.currentElement != null) this.recoveryTokenCheck();
-// try{
-// prevPos = scanner.currentPosition;
-// prevToken = currentToken;
-// insertedSemicolon = false;
-// this.currentToken = this.scanner.getNextToken();
-// 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 consume Token: "+scanner.toStringAction(this.currentToken)); //$NON-NLS-1$
- consumeToken(this.currentToken);
- if (this.currentElement != null) this.recoveryTokenCheck();
- try {
- prevPos = scanner.currentPosition;
- prevToken = currentToken;
- insertedSemicolon = false;
- this.currentToken = this.scanner.getNextToken();
- 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 consume Token: "+scanner.toStringAction(this.currentToken)); //$NON-NLS-1$
- consumeToken(this.currentToken);
- if (this.currentElement != null) this.recoveryTokenCheck();
- try{
- prevPos = scanner.currentPosition;
- prevToken = currentToken;
- insertedSemicolon = false;
- this.currentToken = this.scanner.getNextToken();
- 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<this.inferenceEngines.length;i++)
- {
- try {
- IInferEngine engine=this.inferenceEngines[i];
- engine.initialize();
- engine.setCompilationUnit(parsedUnit);
- engine.doInfer();
- } catch (RuntimeException e) {
- org.eclipse.wst.jsdt.internal.core.util.Util.log(e, "error during type inferencing");
- }
- }
- parsedUnit.typesHaveBeenInferred=true;
-}
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/ParserBasicInformation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/ParserBasicInformation.java
deleted file mode 100644
index 3fbaf5c4..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/ParserBasicInformation.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*******************************************************************************
- * 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.compiler.parser;
-
-/*An interface that contains static declarations for some basic information
- about the parser such as the number of rules in the grammar, the starting state, etc...*/
-public interface ParserBasicInformation {
-
- int
-
- ERROR_SYMBOL = 120,
- MAX_NAME_LENGTH = 36,
- NUM_STATES = 558,
-
- NT_OFFSET = 120,
- SCOPE_UBOUND = 56,
- SCOPE_SIZE = 57,
- LA_STATE_OFFSET = 7569,
- MAX_LA = 1,
- NUM_RULES = 398,
- NUM_TERMINALS = 120,
- NUM_NON_TERMINALS = 180,
- NUM_SYMBOLS = 300,
- START_STATE = 437,
- EOFT_SYMBOL = 70,
- EOLT_SYMBOL = 70,
- ACCEPT_ACTION = 7568,
- ERROR_ACTION = 7569;
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredBlock.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredBlock.java
deleted file mode 100644
index d32225d6..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredBlock.java
+++ /dev/null
@@ -1,409 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.parser;
-
-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.Block;
-import org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ProgramElement;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Statement;
-import org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration;
-
-public class RecoveredBlock extends RecoveredStatement implements TerminalTokens {
-
- public Block blockDeclaration;
- public RecoveredStatement[] statements;
- public int statementCount;
- public boolean preserveContent = false;
- public RecoveredLocalVariable pendingArgument;
-
-public RecoveredBlock(Block block, RecoveredElement parent, int bracketBalance){
- super(block, parent, bracketBalance);
- this.blockDeclaration = block;
- this.foundOpeningBrace = true;
-
- this.preserveContent = this.parser().methodRecoveryActivated || this.parser().statementRecoveryActivated;
-}
-public RecoveredElement add(AbstractMethodDeclaration methodDeclaration, int bracketBalanceValue) {
- if (this.parent != null && this.parent instanceof RecoveredMethod) {
- RecoveredMethod enclosingRecoveredMethod = (RecoveredMethod) this.parent;
- if (enclosingRecoveredMethod.methodBody == this && enclosingRecoveredMethod.parent == null) {
- // the element cannot be added because we are in the body of a top level method
- return this; // ignore this element
- }
- }
- return super.add(methodDeclaration, bracketBalanceValue);
-}
-
-/*
- * Record a nested block declaration
- */
-public RecoveredElement add(Block nestedBlockDeclaration, int bracketBalanceValue) {
-
- /* do not consider a nested block starting passed the block end (if set)
- it must be belonging to an enclosing block */
- if (this.blockDeclaration.sourceEnd != 0
- && nestedBlockDeclaration.sourceStart > this.blockDeclaration.sourceEnd){
- return this.parent.add(nestedBlockDeclaration, bracketBalanceValue);
- }
-
- RecoveredBlock element = new RecoveredBlock(nestedBlockDeclaration, this, bracketBalanceValue);
-
- // if we have a pending Argument, promote it into the new block
- if (this.pendingArgument != null){
- element.attach(this.pendingArgument);
- this.pendingArgument = null;
- }
- if(this.parser().statementRecoveryActivated) {
- this.addBlockStatement(element);
- }
- this.attach(element);
- if (nestedBlockDeclaration.sourceEnd == 0) return element;
- return this;
-}
-/*
- * Record a local declaration
- */
-public RecoveredElement add(LocalDeclaration localDeclaration, int bracketBalanceValue) {
- return this.add(localDeclaration, bracketBalanceValue, false);
-}
-/*
- * Record a local declaration
- */
-public RecoveredElement add(LocalDeclaration localDeclaration, int bracketBalanceValue, boolean delegatedByParent) {
-
- /* local variables inside method can only be final and non void */
-/*
- char[][] localTypeName;
- if ((localDeclaration.modifiers & ~AccFinal) != 0 // local var can only be final
- || (localDeclaration.type == null) // initializer
- || ((localTypeName = localDeclaration.type.getTypeName()).length == 1 // non void
- && CharOperation.equals(localTypeName[0], VoidBinding.sourceName()))){
-
- if (delegatedByParent){
- return this; //ignore
- } else {
- this.updateSourceEndIfNecessary(this.previousAvailableLineEnd(localDeclaration.declarationSourceStart - 1));
- return this.parent.add(localDeclaration, bracketBalance);
- }
- }
-*/
- /* do not consider a local variable starting passed the block end (if set)
- it must be belonging to an enclosing block */
- if (this.blockDeclaration.sourceEnd != 0
- && localDeclaration.declarationSourceStart > this.blockDeclaration.sourceEnd){
- if (delegatedByParent) return this; //ignore
- return this.parent.add(localDeclaration, bracketBalanceValue);
- }
-
- RecoveredLocalVariable element = new RecoveredLocalVariable(localDeclaration, this, bracketBalanceValue);
-
- if (localDeclaration instanceof Argument){
- this.pendingArgument = element;
- return this;
- }
-
- this.attach(element);
- if (localDeclaration.declarationSourceEnd == 0) return element;
- return this;
-}
-/*
- * Record a statement declaration
- */
-public RecoveredElement add(Statement stmt, int bracketBalanceValue) {
- return this.add(stmt, bracketBalanceValue, false);
-}
-
-/*
- * Record a statement declaration
- */
-public RecoveredElement add(Statement stmt, int bracketBalanceValue, boolean delegatedByParent) {
-
- /* do not consider a nested block starting passed the block end (if set)
- it must be belonging to an enclosing block */
- if (this.blockDeclaration.sourceEnd != 0
- && stmt.sourceStart > this.blockDeclaration.sourceEnd){
- if (delegatedByParent) return this; //ignore
- return this.parent.add(stmt, bracketBalanceValue);
- }
-
- RecoveredStatement element = new RecoveredStatement(stmt, this, bracketBalanceValue);
- this.attach(element);
- if (stmt.sourceEnd == 0) return element;
- return this;
-}
-/*
- * Addition of a type to an initializer (act like inside method body)
- */
-public RecoveredElement add(TypeDeclaration typeDeclaration, int bracketBalanceValue) {
- return this.add(typeDeclaration, bracketBalanceValue, false);
-}
-/*
- * Addition of a type to an initializer (act like inside method body)
- */
-public RecoveredElement add(TypeDeclaration typeDeclaration, int bracketBalanceValue, boolean delegatedByParent) {
-
- /* do not consider a type starting passed the block end (if set)
- it must be belonging to an enclosing block */
- if (this.blockDeclaration.sourceEnd != 0
- && typeDeclaration.declarationSourceStart > this.blockDeclaration.sourceEnd){
- if (delegatedByParent) return this; //ignore
- return this.parent.add(typeDeclaration, bracketBalanceValue);
- }
-
- RecoveredStatement element = new RecoveredType(typeDeclaration, this, bracketBalanceValue);
- this.attach(element);
- if (typeDeclaration.declarationSourceEnd == 0) return element;
- return this;
-}
-/*
- * Attach a recovered statement
- */
-void attach(RecoveredStatement recoveredStatement) {
-
- if (this.statements == null) {
- this.statements = new RecoveredStatement[5];
- this.statementCount = 0;
- } else {
- if (this.statementCount == this.statements.length) {
- System.arraycopy(
- this.statements,
- 0,
- (this.statements = new RecoveredStatement[2 * this.statementCount]),
- 0,
- this.statementCount);
- }
- }
- this.statements[this.statementCount++] = recoveredStatement;
-}
-/*
- * Answer the associated parsed structure
- */
-public ASTNode parseTree(){
- return this.blockDeclaration;
-}
-public String toString(int tab) {
- StringBuffer result = new StringBuffer(tabString(tab));
- result.append("Recovered block:\n"); //$NON-NLS-1$
- this.blockDeclaration.print(tab + 1, result);
- if (this.statements != null) {
- for (int i = 0; i < this.statementCount; i++) {
- result.append("\n"); //$NON-NLS-1$
- result.append(this.statements[i].toString(tab + 1));
- }
- }
- return result.toString();
-}
-/*
- * Rebuild a block from the nested structure which is in scope
- */
-public Block updatedBlock(){
-
- // if block was not marked to be preserved or empty, then ignore it
- if (!this.preserveContent || this.statementCount == 0) return null;
-
- Statement[] updatedStatements = new Statement[this.statementCount];
- int updatedCount = 0;
-
-
- // may need to update the end of the last statement
- RecoveredStatement lastStatement = statements[statementCount - 1];
- RecoveredMethod enclosingMethod = this.enclosingMethod();
- RecoveredInitializer enclosingIntializer = this.enclosingInitializer();
- int bodyEndValue = 0;
- if(enclosingMethod != null) {
- bodyEndValue = enclosingMethod.methodDeclaration.bodyEnd;
- if(enclosingIntializer != null && enclosingMethod.methodDeclaration.sourceStart < enclosingIntializer.fieldDeclaration.sourceStart) {
- bodyEndValue = enclosingIntializer.fieldDeclaration.declarationSourceEnd;
- }
- } else if(enclosingIntializer != null) {
- bodyEndValue = enclosingIntializer.fieldDeclaration.declarationSourceEnd;
- } else {
- bodyEndValue = this.blockDeclaration.sourceEnd - 1;
- }
-
- if(lastStatement instanceof RecoveredLocalVariable) {
- RecoveredLocalVariable lastLocalVariable = (RecoveredLocalVariable) lastStatement;
- if(lastLocalVariable.localDeclaration.declarationSourceEnd == 0) {
- lastLocalVariable.localDeclaration.declarationSourceEnd = bodyEndValue;
- lastLocalVariable.localDeclaration.declarationEnd = bodyEndValue;
- }
- } else if(lastStatement instanceof RecoveredBlock) {
- RecoveredBlock lastBlock = (RecoveredBlock) lastStatement;
- if(lastBlock.blockDeclaration.sourceEnd == 0) {
- lastBlock.blockDeclaration.sourceEnd = bodyEndValue;
- }
- } else if(!(lastStatement instanceof RecoveredType)){
- if(lastStatement.statement.sourceEnd == 0) {
- lastStatement.statement.sourceEnd = bodyEndValue;
- }
- }
-
- int lastEnd = blockDeclaration.sourceStart;
-
- // only collect the non-null updated statements
- for (int i = 0; i < this.statementCount; i++){
- Statement updatedStatement = this.statements[i].updatedStatement();
- if (updatedStatement != null){
- updatedStatements[updatedCount++] = updatedStatement;
-
- if (updatedStatement instanceof LocalDeclaration) {
- LocalDeclaration localDeclaration = (LocalDeclaration) updatedStatement;
- if(localDeclaration.declarationSourceEnd > lastEnd) {
- lastEnd = localDeclaration.declarationSourceEnd;
- }
- } else if (updatedStatement instanceof TypeDeclaration) {
- TypeDeclaration typeDeclaration = (TypeDeclaration) updatedStatement;
- if(typeDeclaration.declarationSourceEnd > lastEnd) {
- lastEnd = typeDeclaration.declarationSourceEnd;
- }
- } else {
- if (updatedStatement.sourceEnd > lastEnd) {
- lastEnd = updatedStatement.sourceEnd;
- }
- }
- }
- }
- if (updatedCount == 0) return null; // not interesting block
-
- // resize statement collection if necessary
- if (updatedCount != this.statementCount){
- this.blockDeclaration.statements = new Statement[updatedCount];
- System.arraycopy(updatedStatements, 0, this.blockDeclaration.statements, 0, updatedCount);
- } else {
- this.blockDeclaration.statements = updatedStatements;
- }
-
- if (this.blockDeclaration.sourceEnd == 0) {
- if(lastEnd < bodyEndValue) {
- this.blockDeclaration.sourceEnd = bodyEndValue;
- } else {
- this.blockDeclaration.sourceEnd = lastEnd;
- }
- }
-
- return this.blockDeclaration;
-}
-/*
- * Rebuild a statement from the nested structure which is in scope
- */
-public Statement updatedStatement(){
-
- return this.updatedBlock();
-}
-/*
- * A closing brace got consumed, might have closed the current element,
- * in which case both the currentElement is exited
- */
-public RecoveredElement updateOnClosingBrace(int braceStart, int braceEnd){
- if ((--this.bracketBalance <= 0) && (this.parent != null)){
- this.updateSourceEndIfNecessary(braceStart, braceEnd);
-
- /* if the block is the method body, then it closes the method too */
- RecoveredMethod method = enclosingMethod();
- if (method != null && method.methodBody == this){
- return this.parent.updateOnClosingBrace(braceStart, braceEnd);
- }
- RecoveredInitializer initializer = enclosingInitializer();
- if (initializer != null && initializer.initializerBody == this){
- return this.parent.updateOnClosingBrace(braceStart, braceEnd);
- }
- return this.parent;
- }
- return this;
-}
-/*
- * An opening brace got consumed, might be the expected opening one of the current element,
- * in which case the bodyStart is updated.
- */
-public RecoveredElement updateOnOpeningBrace(int braceStart, int braceEnd){
-
- // create a nested block
- Block block = new Block(0);
- block.sourceStart = parser().scanner.startPosition;
- return this.add(block, 1);
-}
-/*
- * Final update the corresponding parse node
- */
-public void updateParseTree(){
-
- this.updatedBlock();
-}
-/*
- * Rebuild a flattened block from the nested structure which is in scope
- */
-public Statement updateStatement(){
-
- // if block was closed or empty, then ignore it
- if (this.blockDeclaration.sourceEnd != 0 || this.statementCount == 0) return null;
-
- Statement[] updatedStatements = new Statement[this.statementCount];
- int updatedCount = 0;
-
- // only collect the non-null updated statements
- for (int i = 0; i < this.statementCount; i++){
- Statement updatedStatement = this.statements[i].updatedStatement();
- if (updatedStatement != null){
- updatedStatements[updatedCount++] = updatedStatement;
- }
- }
- if (updatedCount == 0) return null; // not interesting block
-
- // resize statement collection if necessary
- if (updatedCount != this.statementCount){
- this.blockDeclaration.statements = new Statement[updatedCount];
- System.arraycopy(updatedStatements, 0, this.blockDeclaration.statements, 0, updatedCount);
- } else {
- this.blockDeclaration.statements = updatedStatements;
- }
-
- return this.blockDeclaration;
-}
-
-/*
- * Record a field declaration
- */
-public RecoveredElement add(FieldDeclaration fieldDeclaration, int bracketBalanceValue) {
- return add(fieldDeclaration,bracketBalanceValue,false);
-}
-public RecoveredElement add(FieldDeclaration fieldDeclaration, int bracketBalanceValue, boolean delegatedByParent ) {
-
- throw new org.eclipse.wst.jsdt.core.UnimplementedException("SHOULD NOT BE CALLED"); //$NON-NLS-1$
-// /* local variables inside method can only be final and non void */
-// char[][] fieldTypeName;
-// if ((fieldDeclaration.modifiers & ~ClassFileConstants.AccFinal) != 0 // local var can only be final
-// || (fieldDeclaration.type == null) // initializer
-// || ((fieldTypeName = fieldDeclaration.type.getTypeName()).length == 1 // non void
-// && CharOperation.equals(fieldTypeName[0], TypeBinding.VOID.sourceName()))){
-// this.updateSourceEndIfNecessary(this.previousAvailableLineEnd(fieldDeclaration.declarationSourceStart - 1));
-// return this.parent.add(fieldDeclaration, bracketBalanceValue);
-// }
-//
-// /* do not consider a local variable starting passed the block end (if set)
-// it must be belonging to an enclosing block */
-// if (this.blockDeclaration.sourceEnd != 0
-// && fieldDeclaration.declarationSourceStart > this.blockDeclaration.sourceEnd){
-// return this.parent.add(fieldDeclaration, bracketBalanceValue);
-// }
-//
-// // ignore the added field, since indicates a local variable behind recovery point
-// // which thus got parsed as a field reference. This can happen if restarting after
-// // having reduced an assistNode to get the following context (see 1GEK7SG)
-// return this;
-}
-public ProgramElement updatedASTNode() {
- return updateStatement();
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredElement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredElement.java
deleted file mode 100644
index 9b2741a8..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredElement.java
+++ /dev/null
@@ -1,328 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.parser;
-
-/**
- * Internal structure for parsing recovery
- */
-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.Block;
-import org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration;
-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.ProgramElement;
-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.util.Util;
-
-public abstract class RecoveredElement {
-
- public RecoveredElement parent;
- public int bracketBalance;
- public boolean foundOpeningBrace;
- protected Parser recoveringParser;
-
-
-
-public RecoveredElement(RecoveredElement parent, int bracketBalance){
- this(parent, bracketBalance, null);
-}
-public RecoveredElement(RecoveredElement parent, int bracketBalance, Parser parser){
- this.parent = parent;
- this.bracketBalance = bracketBalance;
- this.recoveringParser = parser;
-}
-
-
-public abstract ProgramElement updatedASTNode();
-
-/*
- * Record a method declaration
- */
-public RecoveredElement add(AbstractMethodDeclaration methodDeclaration, int bracketBalanceValue) {
-
- /* default behavior is to delegate recording to parent if any */
- if (this.parent == null) return this; // ignore
- this.updateSourceEndIfNecessary(this.previousAvailableLineEnd(methodDeclaration.declarationSourceStart - 1));
- return this.parent.add(methodDeclaration, bracketBalanceValue);
-}
-/*
- * Record a nested block declaration
- */
-public RecoveredElement add(Block nestedBlockDeclaration, int bracketBalanceValue) {
-
- /* default behavior is to delegate recording to parent if any */
- if (this.parent == null) return this; // ignore
- this.updateSourceEndIfNecessary(this.previousAvailableLineEnd(nestedBlockDeclaration.sourceStart - 1));
- return this.parent.add(nestedBlockDeclaration, bracketBalanceValue);
-}
-/*
- * Record a field declaration
- */
-public RecoveredElement add(FieldDeclaration fieldDeclaration, int bracketBalanceValue) {
-
- /* default behavior is to delegate recording to parent if any */
- if (this.parent == null) return this; // ignore
- this.updateSourceEndIfNecessary(this.previousAvailableLineEnd(fieldDeclaration.declarationSourceStart - 1));
- return this.parent.add(fieldDeclaration, bracketBalanceValue);
-}
-/*
- * Record an import reference
- */
-public RecoveredElement add(ImportReference importReference, int bracketBalanceValue){
-
- /* default behavior is to delegate recording to parent if any */
- if (this.parent == null) return this; // ignore
- this.updateSourceEndIfNecessary(this.previousAvailableLineEnd(importReference.declarationSourceStart - 1));
- return this.parent.add(importReference, bracketBalanceValue);
-}
-/*
- * Record a local declaration
- */
-public RecoveredElement add(LocalDeclaration localDeclaration, int bracketBalanceValue) {
-
- /* default behavior is to delegate recording to parent if any */
- if (this.parent == null) return this; // ignore
- this.updateSourceEndIfNecessary(this.previousAvailableLineEnd(localDeclaration.declarationSourceStart - 1));
- return this.parent.add(localDeclaration, bracketBalanceValue);
-}
-/*
- * Record a statement
- */
-public RecoveredElement add(Statement statement, int bracketBalanceValue) {
-
- /* default behavior is to delegate recording to parent if any */
- if (this.parent == null) return this; // ignore
- this.updateSourceEndIfNecessary(this.previousAvailableLineEnd(statement.sourceStart - 1));
- return this.parent.add(statement, bracketBalanceValue);
-}
-/*
- * Record a type declaration
- */
-public RecoveredElement add(TypeDeclaration typeDeclaration, int bracketBalanceValue){
-
- /* default behavior is to delegate recording to parent if any */
- if (this.parent == null) return this; // ignore
- this.updateSourceEndIfNecessary(this.previousAvailableLineEnd(typeDeclaration.declarationSourceStart - 1));
- return this.parent.add(typeDeclaration, bracketBalanceValue);
-}
-protected void addBlockStatement(RecoveredBlock recoveredBlock) {
- Block block = recoveredBlock.blockDeclaration;
- if(block.statements != null) {
- Statement[] statements = block.statements;
- for (int i = 0; i < statements.length; i++) {
- recoveredBlock.add(statements[i], 0);
- }
- }
-}
-
-
-/*
- * Answer the depth of this element, considering the parent link.
- */
-public int depth(){
- int depth = 0;
- RecoveredElement current = this;
- while ((current = current.parent) != null) depth++;
- return depth;
-}
-/*
- * Answer the enclosing method node, or null if none
- */
-public RecoveredInitializer enclosingInitializer(){
- RecoveredElement current = this;
- while (current != null){
- if (current instanceof RecoveredInitializer){
- return (RecoveredInitializer) current;
- }
- current = current.parent;
- }
- return null;
-}
-/*
- * Answer the enclosing method node, or null if none
- */
-public RecoveredMethod enclosingMethod(){
- RecoveredElement current = this;
- while (current != null){
- if (current instanceof RecoveredMethod){
- return (RecoveredMethod) current;
- }
- current = current.parent;
- }
- return null;
-}
-/*
- * Answer the enclosing type node, or null if none
- */
-public RecoveredType enclosingType(){
- RecoveredElement current = this;
- while (current != null){
- if (current instanceof RecoveredType){
- return (RecoveredType) current;
- }
- current = current.parent;
- }
- return null;
-}
-/*
- * Answer the closest specified parser
- */
-public Parser parser(){
- RecoveredElement current = this;
- while (current != null){
- if (current.recoveringParser != null){
- return current.recoveringParser;
- }
- current = current.parent;
- }
- return null;
-}
-/*
- * Answer the associated parsed structure
- */
-public ASTNode parseTree(){
- return null;
-}
-/*
- * Iterate the enclosing blocks and tag them so as to preserve their content
- */
-public void preserveEnclosingBlocks(){
- RecoveredElement current = this;
- while (current != null){
- if (current instanceof RecoveredBlock){
- ((RecoveredBlock)current).preserveContent = true;
- }
- if (current instanceof RecoveredType){ // for anonymous types
- ((RecoveredType)current).preserveContent = true;
- }
- current = current.parent;
- }
-}
-/*
- * Answer the position of the previous line end if
- * there is nothing but spaces in between it and the
- * line end. Used to trim spaces on unclosed elements.
- */
-public int previousAvailableLineEnd(int position){
-
- Parser parser = this.parser();
- if (parser == null) return position;
-
- Scanner scanner = parser.scanner;
- if (scanner.lineEnds == null) return position;
-
- int index = Util.getLineNumber(position, scanner.lineEnds, 0, scanner.linePtr);
- if (index < 2) return position;
- int previousLineEnd = scanner.lineEnds[index-2];
-
- char[] source = scanner.source;
- for (int i = previousLineEnd+1; i < position; i++){
- if (!(source[i] == ' ' || source[i] == '\t')) return position;
- }
- return previousLineEnd;
-}
-/*
- * Answer the very source end of the corresponding parse node
- */
-public int sourceEnd(){
- return 0;
-}
-protected String tabString(int tab) {
- StringBuffer result = new StringBuffer();
- for (int i = tab; i > 0; i--) {
- result.append(" "); //$NON-NLS-1$
- }
- return result.toString();
-}
-/*
- * Answer the top node
- */
-public RecoveredElement topElement(){
- RecoveredElement current = this;
- while (current.parent != null){
- current = current.parent;
- }
- return current;
-}
-public String toString() {
- return toString(0);
-}
-public String toString(int tab) {
- return super.toString();
-}
-/*
- * Answer the enclosing type node, or null if none
- */
-public RecoveredType type(){
- RecoveredElement current = this;
- while (current != null){
- if (current instanceof RecoveredType){
- return (RecoveredType) current;
- }
- current = current.parent;
- }
- return null;
-}
-/*
- * Update the bodyStart of the corresponding parse node
- */
-public void updateBodyStart(int bodyStart){
- this.foundOpeningBrace = true;
-}
-/*
- * Update the corresponding parse node from parser state which
- * is about to disappear because of restarting recovery
- */
-public void updateFromParserState(){
- // default implementation: do nothing
-}
-/*
- * A closing brace got consumed, might have closed the current element,
- * in which case both the currentElement is exited
- */
-public RecoveredElement updateOnClosingBrace(int braceStart, int braceEnd){
- if ((--this.bracketBalance <= 0) && (this.parent != null)){
- this.updateSourceEndIfNecessary(braceStart, braceEnd);
- return this.parent;
- }
- return this;
-}
-/*
- * An opening brace got consumed, might be the expected opening one of the current element,
- * in which case the bodyStart is updated.
- */
-/*public RecoveredElement updateOnOpeningBrace(int braceEnd){return null;}*/
-public RecoveredElement updateOnOpeningBrace(int braceStart, int braceEnd){
-
- if (this.bracketBalance++ == 0){
- this.updateBodyStart(braceEnd + 1);
- return this;
- }
- return null; // no update is necessary
-}
-/*
- * Final update the corresponding parse node
- */
-public void updateParseTree(){
- // default implementation: do nothing
-}
-/*
- * Update the declarationSourceEnd of the corresponding parse node
- */
-public void updateSourceEndIfNecessary(int braceStart, int braceEnd){
- // default implementation: do nothing
-}
-public void updateSourceEndIfNecessary(int sourceEnd){
- this.updateSourceEndIfNecessary(sourceEnd + 1, sourceEnd);
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredField.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredField.java
deleted file mode 100644
index 16b7638c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredField.java
+++ /dev/null
@@ -1,190 +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.compiler.parser;
-
-/**
- * Internal field structure for parsing recovery
- */
-import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ArrayQualifiedTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ArrayTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Expression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ProgramElement;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Statement;
-import org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration;
-
-public class RecoveredField extends RecoveredElement {
-
- public FieldDeclaration fieldDeclaration;
- boolean alreadyCompletedFieldInitialization;
-
- public RecoveredType[] anonymousTypes;
- public int anonymousTypeCount;
-public RecoveredField(FieldDeclaration fieldDeclaration, RecoveredElement parent, int bracketBalance){
- this(fieldDeclaration, parent, bracketBalance, null);
-}
-public RecoveredField(FieldDeclaration fieldDeclaration, RecoveredElement parent, int bracketBalance, Parser parser){
- super(parent, bracketBalance, parser);
- this.fieldDeclaration = fieldDeclaration;
- this.alreadyCompletedFieldInitialization = fieldDeclaration.initialization != null;
-}
-/*
- * Record an expression statement if field is expecting an initialization expression,
- * used for completion inside field initializers.
- */
-public RecoveredElement add(Statement statement, int bracketBalanceValue) {
-
- if (this.alreadyCompletedFieldInitialization || !(statement instanceof Expression)) {
- return super.add(statement, bracketBalanceValue);
- } else {
- this.alreadyCompletedFieldInitialization = true;
- this.fieldDeclaration.initialization = (Expression)statement;
- this.fieldDeclaration.declarationSourceEnd = statement.sourceEnd;
- this.fieldDeclaration.declarationEnd = statement.sourceEnd;
- return this;
- }
-}
-/*
- * Record a type declaration if this field is expecting an initialization expression
- * and the type is an anonymous type.
- * Used for completion inside field initializers.
- */
-public RecoveredElement add(TypeDeclaration typeDeclaration, int bracketBalanceValue) {
-
- if (this.alreadyCompletedFieldInitialization
- || ((typeDeclaration.bits & ASTNode.IsAnonymousType) == 0)
- || (this.fieldDeclaration.declarationSourceEnd != 0 && typeDeclaration.sourceStart > this.fieldDeclaration.declarationSourceEnd)) {
- return super.add(typeDeclaration, bracketBalanceValue);
- } else {
- // Prepare anonymous type list
- if (this.anonymousTypes == null) {
- this.anonymousTypes = new RecoveredType[5];
- this.anonymousTypeCount = 0;
- } else {
- if (this.anonymousTypeCount == this.anonymousTypes.length) {
- System.arraycopy(
- this.anonymousTypes,
- 0,
- (this.anonymousTypes = new RecoveredType[2 * this.anonymousTypeCount]),
- 0,
- this.anonymousTypeCount);
- }
- }
- // Store type declaration as an anonymous type
- RecoveredType element = new RecoveredType(typeDeclaration, this, bracketBalanceValue);
- this.anonymousTypes[this.anonymousTypeCount++] = element;
- return element;
- }
-}
-/*
- * Answer the associated parsed structure
- */
-public ASTNode parseTree(){
- return fieldDeclaration;
-}
-/*
- * Answer the very source end of the corresponding parse node
- */
-public int sourceEnd(){
- return this.fieldDeclaration.declarationSourceEnd;
-}
-public String toString(int tab){
- StringBuffer buffer = new StringBuffer(tabString(tab));
- buffer.append("Recovered field:\n"); //$NON-NLS-1$
- fieldDeclaration.print(tab + 1, buffer);
- if (this.anonymousTypes != null) {
- for (int i = 0; i < this.anonymousTypeCount; i++){
- buffer.append("\n"); //$NON-NLS-1$
- buffer.append(anonymousTypes[i].toString(tab + 1));
- }
- }
- return buffer.toString();
-}
-public FieldDeclaration updatedFieldDeclaration(){
-
- if (this.anonymousTypes != null) {
- if(fieldDeclaration.initialization == null) {
- for (int i = 0; i < this.anonymousTypeCount; i++){
- RecoveredType recoveredType = anonymousTypes[i];
- TypeDeclaration typeDeclaration = recoveredType.typeDeclaration;
- if(typeDeclaration.declarationSourceEnd == 0) {
- typeDeclaration.declarationSourceEnd = this.fieldDeclaration.declarationSourceEnd;
- typeDeclaration.bodyEnd = this.fieldDeclaration.declarationSourceEnd;
- }
- if (recoveredType.preserveContent){
- TypeDeclaration anonymousType = recoveredType.updatedTypeDeclaration();
- fieldDeclaration.initialization = anonymousType.allocation;
- if(this.fieldDeclaration.declarationSourceEnd == 0) {
- int end = anonymousType.declarationSourceEnd;
- this.fieldDeclaration.declarationSourceEnd = end;
- this.fieldDeclaration.declarationEnd = end;
- }
- }
- }
- if (this.anonymousTypeCount > 0) fieldDeclaration.bits |= ASTNode.HasLocalType;
- }
- }
- return fieldDeclaration;
-}
-/*
- * A closing brace got consumed, might have closed the current element,
- * in which case both the currentElement is exited.
- *
- * Fields have no associated braces, thus if matches, then update parent.
- */
-public RecoveredElement updateOnClosingBrace(int braceStart, int braceEnd){
- if (bracketBalance > 0){ // was an array initializer
- bracketBalance--;
- if (bracketBalance == 0) {
- alreadyCompletedFieldInitialization = true;
- }
- return this;
- } else if (bracketBalance == 0) {
- alreadyCompletedFieldInitialization = true;
- updateSourceEndIfNecessary(braceEnd - 1);
- }
- if (parent != null){
- return parent.updateOnClosingBrace(braceStart, braceEnd);
- }
- return this;
-}
-/*
- * An opening brace got consumed, might be the expected opening one of the current element,
- * in which case the bodyStart is updated.
- */
-public RecoveredElement updateOnOpeningBrace(int braceStart, int braceEnd){
- if (fieldDeclaration.declarationSourceEnd == 0
- && (fieldDeclaration.type instanceof ArrayTypeReference || fieldDeclaration.type instanceof ArrayQualifiedTypeReference)
- && !alreadyCompletedFieldInitialization){
- bracketBalance++;
- return null; // no update is necessary (array initializer)
- }
- // might be an array initializer
- this.updateSourceEndIfNecessary(braceStart - 1, braceEnd - 1);
- return this.parent.updateOnOpeningBrace(braceStart, braceEnd);
-}
-public void updateParseTree(){
- this.updatedFieldDeclaration();
-}
-/*
- * Update the declarationSourceEnd of the corresponding parse node
- */
-public void updateSourceEndIfNecessary(int bodyStart, int bodyEnd){
- if (this.fieldDeclaration.declarationSourceEnd == 0) {
- this.fieldDeclaration.declarationSourceEnd = bodyEnd;
- this.fieldDeclaration.declarationEnd = bodyEnd;
- }
-}
-public ProgramElement updatedASTNode() {
- return updatedFieldDeclaration();
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredImport.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredImport.java
deleted file mode 100644
index 86873ec8..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredImport.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.parser;
-
-/**
- * Internal import structure for parsing recovery
- */
-import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ImportReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ProgramElement;
-
-public class RecoveredImport extends RecoveredElement {
-
- public ImportReference importReference;
-public RecoveredImport(ImportReference importReference, RecoveredElement parent, int bracketBalance){
- super(parent, bracketBalance);
- this.importReference = importReference;
-}
-/*
- * Answer the associated parsed structure
- */
-public ASTNode parseTree(){
- return importReference;
-}
-/*
- * Answer the very source end of the corresponding parse node
- */
-public int sourceEnd(){
- return this.importReference.declarationSourceEnd;
-}
-public String toString(int tab) {
- return tabString(tab) + "Recovered import: " + importReference.toString(); //$NON-NLS-1$
-}
-public ImportReference updatedImportReference(){
-
- return importReference;
-}
-public void updateParseTree(){
- this.updatedImportReference();
-}
-/*
- * Update the declarationSourceEnd of the corresponding parse node
- */
-public void updateSourceEndIfNecessary(int bodyStart, int bodyEnd){
- if (this.importReference.declarationSourceEnd == 0) {
- this.importReference.declarationSourceEnd = bodyEnd;
- this.importReference.declarationEnd = bodyEnd;
- }
-}
-public ProgramElement updatedASTNode() {
- // TODO Auto-generated method stub
- return null;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredInitializer.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredInitializer.java
deleted file mode 100644
index 83b96cf6..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredInitializer.java
+++ /dev/null
@@ -1,234 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.parser;
-
-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.Block;
-import org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Initializer;
-import org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration;
-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.lookup.TypeBinding;
-
-public class RecoveredInitializer extends RecoveredField implements TerminalTokens {
-
- public RecoveredType[] localTypes;
- public int localTypeCount;
-
- public RecoveredBlock initializerBody;
-
-public RecoveredInitializer(FieldDeclaration fieldDeclaration, RecoveredElement parent, int bracketBalance){
- this(fieldDeclaration, parent, bracketBalance, null);
-}
-public RecoveredInitializer(FieldDeclaration fieldDeclaration, RecoveredElement parent, int bracketBalance, Parser parser){
- super(fieldDeclaration, parent, bracketBalance, parser);
- this.foundOpeningBrace = true;
-}
-/*
- * Record a nested block declaration
- */
-public RecoveredElement add(Block nestedBlockDeclaration, int bracketBalanceValue) {
-
- /* default behavior is to delegate recording to parent if any,
- do not consider elements passed the known end (if set)
- it must be belonging to an enclosing element
- */
- if (fieldDeclaration.declarationSourceEnd > 0
- && nestedBlockDeclaration.sourceStart > fieldDeclaration.declarationSourceEnd){
- if (this.parent == null) return this; // ignore
- return this.parent.add(nestedBlockDeclaration, bracketBalanceValue);
- }
- /* consider that if the opening brace was not found, it is there */
- if (!foundOpeningBrace){
- foundOpeningBrace = true;
- this.bracketBalance++;
- }
- initializerBody = new RecoveredBlock(nestedBlockDeclaration, this, bracketBalanceValue);
- if (nestedBlockDeclaration.sourceEnd == 0) return initializerBody;
- return this;
-}
-/*
- * Record a field declaration (act like inside method body)
- */
-public RecoveredElement add(FieldDeclaration newFieldDeclaration, int bracketBalanceValue) {
-
- /* local variables inside initializer can only be final and non void */
- char[][] fieldTypeName;
- if ((newFieldDeclaration.modifiers & ~ClassFileConstants.AccFinal) != 0 /* local var can only be final */
- || (newFieldDeclaration.type == null) // initializer
- || ((fieldTypeName = newFieldDeclaration.type.getTypeName()).length == 1 // non void
- && CharOperation.equals(fieldTypeName[0], TypeBinding.VOID.sourceName()))){
- if (this.parent == null) return this; // ignore
- this.updateSourceEndIfNecessary(this.previousAvailableLineEnd(newFieldDeclaration.declarationSourceStart - 1));
- return this.parent.add(newFieldDeclaration, bracketBalanceValue);
- }
-
- /* default behavior is to delegate recording to parent if any,
- do not consider elements passed the known end (if set)
- it must be belonging to an enclosing element
- */
- if (this.fieldDeclaration.declarationSourceEnd > 0
- && newFieldDeclaration.declarationSourceStart > this.fieldDeclaration.declarationSourceEnd){
- if (this.parent == null) return this; // ignore
- return this.parent.add(newFieldDeclaration, bracketBalanceValue);
- }
- // still inside initializer, treat as local variable
- return this; // ignore
-}
-/*
- * Record a local declaration - regular method should have been created a block body
- */
-public RecoveredElement add(LocalDeclaration localDeclaration, int bracketBalanceValue) {
-
- /* do not consider a type starting passed the type end (if set)
- it must be belonging to an enclosing type */
- if (fieldDeclaration.declarationSourceEnd != 0
- && localDeclaration.declarationSourceStart > fieldDeclaration.declarationSourceEnd){
- if (parent == null) return this; // ignore
- return this.parent.add(localDeclaration, bracketBalanceValue);
- }
- /* method body should have been created */
- Block block = new Block(0);
- block.sourceStart = ((Initializer)fieldDeclaration).sourceStart;
- RecoveredElement element = this.add(block, 1);
- return element.add(localDeclaration, bracketBalanceValue);
-}
-/*
- * Record a statement - regular method should have been created a block body
- */
-public RecoveredElement add(Statement statement, int bracketBalanceValue) {
-
- /* do not consider a statement starting passed the initializer end (if set)
- it must be belonging to an enclosing type */
- if (fieldDeclaration.declarationSourceEnd != 0
- && statement.sourceStart > fieldDeclaration.declarationSourceEnd){
- if (parent == null) return this; // ignore
- return this.parent.add(statement, bracketBalanceValue);
- }
- /* initializer body should have been created */
- Block block = new Block(0);
- block.sourceStart = ((Initializer)fieldDeclaration).sourceStart;
- RecoveredElement element = this.add(block, 1);
- return element.add(statement, bracketBalanceValue);
-}
-public RecoveredElement add(TypeDeclaration typeDeclaration, int bracketBalanceValue) {
-
- /* do not consider a type starting passed the type end (if set)
- it must be belonging to an enclosing type */
- if (fieldDeclaration.declarationSourceEnd != 0
- && typeDeclaration.declarationSourceStart > fieldDeclaration.declarationSourceEnd){
- if (parent == null) return this; // ignore
- return this.parent.add(typeDeclaration, bracketBalanceValue);
- }
- if ((typeDeclaration.bits & ASTNode.IsLocalType) != 0){
- /* method body should have been created */
- Block block = new Block(0);
- block.sourceStart = ((Initializer)fieldDeclaration).sourceStart;
- RecoveredElement element = this.add(block, 1);
- return element.add(typeDeclaration, bracketBalanceValue);
- }
- if (localTypes == null) {
- localTypes = new RecoveredType[5];
- localTypeCount = 0;
- } else {
- if (localTypeCount == localTypes.length) {
- System.arraycopy(
- localTypes,
- 0,
- (localTypes = new RecoveredType[2 * localTypeCount]),
- 0,
- localTypeCount);
- }
- }
- RecoveredType element = new RecoveredType(typeDeclaration, this, bracketBalanceValue);
- localTypes[localTypeCount++] = element;
-
- /* consider that if the opening brace was not found, it is there */
- if (!foundOpeningBrace){
- foundOpeningBrace = true;
- this.bracketBalance++;
- }
- return element;
-}
-public String toString(int tab) {
- StringBuffer result = new StringBuffer(tabString(tab));
- result.append("Recovered initializer:\n"); //$NON-NLS-1$
- this.fieldDeclaration.print(tab + 1, result);
- if (this.initializerBody != null) {
- result.append("\n"); //$NON-NLS-1$
- result.append(this.initializerBody.toString(tab + 1));
- }
- return result.toString();
-}
-public FieldDeclaration updatedFieldDeclaration(){
-
- if (initializerBody != null){
- Block block = initializerBody.updatedBlock();
- if (block != null){
- ((Initializer)fieldDeclaration).block = block;
- }
- if (this.localTypeCount > 0) fieldDeclaration.bits |= ASTNode.HasLocalType;
-
- }
- if (fieldDeclaration.sourceEnd == 0){
- fieldDeclaration.sourceEnd = fieldDeclaration.declarationSourceEnd;
- }
- return fieldDeclaration;
-}
-/*
- * A closing brace got consumed, might have closed the current element,
- * in which case both the currentElement is exited
- */
-public RecoveredElement updateOnClosingBrace(int braceStart, int braceEnd){
- if ((--bracketBalance <= 0) && (parent != null)){
- this.updateSourceEndIfNecessary(braceStart, braceEnd);
- return parent;
- }
- return this;
-}
-/*
- * An opening brace got consumed, might be the expected opening one of the current element,
- * in which case the bodyStart is updated.
- */
-public RecoveredElement updateOnOpeningBrace(int braceStart, int braceEnd){
- bracketBalance++;
- return this; // request to restart
-}
-/*
- * Update the declarationSourceEnd of the corresponding parse node
- */
-public void updateSourceEndIfNecessary(int braceStart, int braceEnd){
- if (this.fieldDeclaration.declarationSourceEnd == 0) {
- Initializer initializer = (Initializer)fieldDeclaration;
- if(parser().rBraceSuccessorStart >= braceEnd) {
- if (initializer.bodyStart < parser().rBraceEnd) {
- initializer.declarationSourceEnd = parser().rBraceEnd;
- } else {
- initializer.declarationSourceEnd = initializer.bodyStart;
- }
- if (initializer.bodyStart < parser().rBraceStart) {
- initializer.bodyEnd = parser().rBraceStart;
- } else {
- initializer.bodyEnd = initializer.bodyStart;
- }
- } else {
- initializer.declarationSourceEnd = braceEnd;
- initializer.bodyEnd = braceStart - 1;
- }
- if(initializer.block != null) {
- initializer.block.sourceEnd = initializer.declarationSourceEnd;
- }
- }
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredLocalVariable.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredLocalVariable.java
deleted file mode 100644
index 2b2fe733..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredLocalVariable.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.parser;
-
-/**
- * Internal local variable structure for parsing recovery
- */
-import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ArrayQualifiedTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ArrayTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Expression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ProgramElement;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Statement;
-
-public class RecoveredLocalVariable extends RecoveredStatement {
-
- public LocalDeclaration localDeclaration;
- boolean alreadyCompletedLocalInitialization;
-public RecoveredLocalVariable(LocalDeclaration localDeclaration, RecoveredElement parent, int bracketBalance){
- super(localDeclaration, parent, bracketBalance);
- this.localDeclaration = localDeclaration;
- this.alreadyCompletedLocalInitialization = localDeclaration.initialization != null;
-}
-/*
- * Record an expression statement if local variable is expecting an initialization expression.
- */
-public RecoveredElement add(Statement stmt, int bracketBalanceValue) {
-
- if (this.alreadyCompletedLocalInitialization || !(stmt instanceof Expression)) {
- return super.add(stmt, bracketBalanceValue);
- } else {
- this.alreadyCompletedLocalInitialization = true;
- this.localDeclaration.initialization = (Expression)stmt;
- this.localDeclaration.declarationSourceEnd = stmt.sourceEnd;
- this.localDeclaration.declarationEnd = stmt.sourceEnd;
- return this;
- }
-}
-/*
- * Answer the associated parsed structure
- */
-public ASTNode parseTree(){
- return localDeclaration;
-}
-/*
- * Answer the very source end of the corresponding parse node
- */
-public int sourceEnd(){
- return this.localDeclaration.declarationSourceEnd;
-}
-public String toString(int tab) {
- return tabString(tab) + "Recovered local variable:\n" + localDeclaration.print(tab + 1, new StringBuffer(10)); //$NON-NLS-1$
-}
-public Statement updatedStatement(){
- return localDeclaration;
-}
-/*
- * A closing brace got consumed, might have closed the current element,
- * in which case both the currentElement is exited.
- *
- * Fields have no associated braces, thus if matches, then update parent.
- */
-public RecoveredElement updateOnClosingBrace(int braceStart, int braceEnd){
- if (bracketBalance > 0){ // was an array initializer
- bracketBalance--;
- if (bracketBalance == 0) alreadyCompletedLocalInitialization = true;
- return this;
- }
- if (parent != null){
- return parent.updateOnClosingBrace(braceStart, braceEnd);
- }
- return this;
-}
-/*
- * An opening brace got consumed, might be the expected opening one of the current element,
- * in which case the bodyStart is updated.
- */
-public RecoveredElement updateOnOpeningBrace(int braceStart, int braceEnd){
- if (localDeclaration.declarationSourceEnd == 0
- && (localDeclaration.type instanceof ArrayTypeReference || localDeclaration.type instanceof ArrayQualifiedTypeReference)
- && !alreadyCompletedLocalInitialization){
- bracketBalance++;
- return null; // no update is necessary (array initializer)
- }
- // might be an array initializer
- this.updateSourceEndIfNecessary(braceStart - 1, braceEnd - 1);
- return this.parent.updateOnOpeningBrace(braceStart, braceEnd);
-}
-public void updateParseTree(){
- this.updatedStatement();
-}
-/*
- * Update the declarationSourceEnd of the corresponding parse node
- */
-public void updateSourceEndIfNecessary(int bodyStart, int bodyEnd){
- if (this.localDeclaration.declarationSourceEnd == 0) {
- this.localDeclaration.declarationSourceEnd = bodyEnd;
- this.localDeclaration.declarationEnd = bodyEnd;
- }
-}
-
-public ProgramElement updatedASTNode() {
- return updatedStatement();
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredMethod.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredMethod.java
deleted file mode 100644
index 79aebb9f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredMethod.java
+++ /dev/null
@@ -1,455 +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.compiler.parser;
-
-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.Argument;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Block;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ConstructorDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ExplicitConstructorCall;
-import org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ProgramElement;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Statement;
-import org.eclipse.wst.jsdt.internal.compiler.ast.SuperReference;
-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.classfmt.ClassFileConstants;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-/**
- * Internal method structure for parsing recovery
- */
-
-public class RecoveredMethod extends RecoveredElement implements TerminalTokens {
-
- public AbstractMethodDeclaration methodDeclaration;
-
- public RecoveredType[] localTypes;
- public int localTypeCount;
-
- public RecoveredBlock methodBody;
- public boolean discardBody = true;
-
-public RecoveredMethod(AbstractMethodDeclaration methodDeclaration, RecoveredElement parent, int bracketBalance, Parser parser){
- super(parent, bracketBalance, parser);
- this.methodDeclaration = methodDeclaration;
- this.foundOpeningBrace = !bodyStartsAtHeaderEnd();
- if(this.foundOpeningBrace) {
- this.bracketBalance++;
- }
-}
-/*
- * Record a nested block declaration
- */
-public RecoveredElement add(Block nestedBlockDeclaration, int bracketBalanceValue) {
-
- /* default behavior is to delegate recording to parent if any,
- do not consider elements passed the known end (if set)
- it must be belonging to an enclosing element
- */
- if (methodDeclaration.declarationSourceEnd > 0
- && nestedBlockDeclaration.sourceStart
- > methodDeclaration.declarationSourceEnd){
- if (this.parent == null){
- return this; // ignore
- } else {
- return this.parent.add(nestedBlockDeclaration, bracketBalanceValue);
- }
- }
- /* consider that if the opening brace was not found, it is there */
- if (!foundOpeningBrace){
- foundOpeningBrace = true;
- this.bracketBalance++;
- }
-
- methodBody = new RecoveredBlock(nestedBlockDeclaration, this, bracketBalanceValue);
- if (nestedBlockDeclaration.sourceEnd == 0) return methodBody;
- return this;
-}
-/*
- * Record a field declaration
- */
-public RecoveredElement add(FieldDeclaration fieldDeclaration, int bracketBalanceValue) {
-
- /* local variables inside method can only be final and non void */
- char[][] fieldTypeName;
- if ((fieldDeclaration.modifiers & ~ClassFileConstants.AccFinal) != 0 // local var can only be final
- || (fieldDeclaration.type == null) // initializer
- || ((fieldTypeName = fieldDeclaration.type.getTypeName()).length == 1 // non void
- && CharOperation.equals(fieldTypeName[0], TypeBinding.VOID.sourceName()))){
-
- if (this.parent == null){
- return this; // ignore
- } else {
- this.updateSourceEndIfNecessary(this.previousAvailableLineEnd(fieldDeclaration.declarationSourceStart - 1));
- return this.parent.add(fieldDeclaration, bracketBalanceValue);
- }
- }
- /* default behavior is to delegate recording to parent if any,
- do not consider elements passed the known end (if set)
- it must be belonging to an enclosing element
- */
- if (methodDeclaration.declarationSourceEnd > 0
- && fieldDeclaration.declarationSourceStart
- > methodDeclaration.declarationSourceEnd){
- if (this.parent == null){
- return this; // ignore
- } else {
- return this.parent.add(fieldDeclaration, bracketBalanceValue);
- }
- }
- /* consider that if the opening brace was not found, it is there */
- if (!foundOpeningBrace){
- foundOpeningBrace = true;
- this.bracketBalance++;
- }
- // still inside method, treat as local variable
- return this; // ignore
-}
-/*
- * Record a local declaration - regular method should have been created a block body
- */
-public RecoveredElement add(LocalDeclaration localDeclaration, int bracketBalanceValue) {
-
- /* local variables inside method can only be final and non void */
-/*
- char[][] localTypeName;
- if ((localDeclaration.modifiers & ~AccFinal) != 0 // local var can only be final
- || (localDeclaration.type == null) // initializer
- || ((localTypeName = localDeclaration.type.getTypeName()).length == 1 // non void
- && CharOperation.equals(localTypeName[0], VoidBinding.sourceName()))){
-
- if (this.parent == null){
- return this; // ignore
- } else {
- this.updateSourceEndIfNecessary(this.previousAvailableLineEnd(localDeclaration.declarationSourceStart - 1));
- return this.parent.add(localDeclaration, bracketBalance);
- }
- }
-*/
- /* do not consider a type starting passed the type end (if set)
- it must be belonging to an enclosing type */
- if (methodDeclaration.declarationSourceEnd != 0
- && localDeclaration.declarationSourceStart > methodDeclaration.declarationSourceEnd){
-
- if (this.parent == null) {
- return this; // ignore
- } else {
- return this.parent.add(localDeclaration, bracketBalanceValue);
- }
- }
- if (methodBody == null){
- Block block = new Block(0);
- block.sourceStart = methodDeclaration.bodyStart;
- RecoveredElement currentBlock = this.add(block, 1);
- if (this.bracketBalance > 0){
- for (int i = 0; i < this.bracketBalance - 1; i++){
- currentBlock = currentBlock.add(new Block(0), 1);
- }
- this.bracketBalance = 1;
- }
- return currentBlock.add(localDeclaration, bracketBalanceValue);
- }
- return methodBody.add(localDeclaration, bracketBalanceValue, true);
-}
-/*
- * Record a statement - regular method should have been created a block body
- */
-public RecoveredElement add(Statement statement, int bracketBalanceValue) {
-
- /* do not consider a type starting passed the type end (if set)
- it must be belonging to an enclosing type */
- if (methodDeclaration.declarationSourceEnd != 0
- && statement.sourceStart > methodDeclaration.declarationSourceEnd){
-
- if (this.parent == null) {
- return this; // ignore
- } else {
- return this.parent.add(statement, bracketBalanceValue);
- }
- }
- if (methodBody == null){
- Block block = new Block(0);
- block.sourceStart = methodDeclaration.bodyStart;
- RecoveredElement currentBlock = this.add(block, 1);
- if (this.bracketBalance > 0){
- for (int i = 0; i < this.bracketBalance - 1; i++){
- currentBlock = currentBlock.add(new Block(0), 1);
- }
- this.bracketBalance = 1;
- }
- return currentBlock.add(statement, bracketBalanceValue);
- }
- return methodBody.add(statement, bracketBalanceValue, true);
-}
-public RecoveredElement add(TypeDeclaration typeDeclaration, int bracketBalanceValue) {
-
- /* do not consider a type starting passed the type end (if set)
- it must be belonging to an enclosing type */
- if (methodDeclaration.declarationSourceEnd != 0
- && typeDeclaration.declarationSourceStart > methodDeclaration.declarationSourceEnd){
-
- if (this.parent == null) {
- return this; // ignore
- }
- return this.parent.add(typeDeclaration, bracketBalanceValue);
- }
- if ((typeDeclaration.bits & ASTNode.IsLocalType) != 0 || this.parser().methodRecoveryActivated || this.parser().statementRecoveryActivated){
- if (methodBody == null){
- Block block = new Block(0);
- block.sourceStart = methodDeclaration.bodyStart;
- this.add(block, 1);
- }
- return methodBody.add(typeDeclaration, bracketBalanceValue, true);
- }
-
- if (localTypes == null) {
- localTypes = new RecoveredType[5];
- localTypeCount = 0;
- } else {
- if (localTypeCount == localTypes.length) {
- System.arraycopy(
- localTypes,
- 0,
- (localTypes = new RecoveredType[2 * localTypeCount]),
- 0,
- localTypeCount);
- }
- }
- RecoveredType element = new RecoveredType(typeDeclaration, this, bracketBalanceValue);
- localTypes[localTypeCount++] = element;
-
- /* consider that if the opening brace was not found, it is there */
- if (!foundOpeningBrace){
- foundOpeningBrace = true;
- this.bracketBalance++;
- }
- return element;
-}
-public boolean bodyStartsAtHeaderEnd(){
- return methodDeclaration.bodyStart == methodDeclaration.sourceEnd+1;
-}
-/*
- * Answer the associated parsed structure
- */
-public ASTNode parseTree(){
- return methodDeclaration;
-}
-/*
- * Answer the very source end of the corresponding parse node
- */
-public int sourceEnd(){
- return this.methodDeclaration.declarationSourceEnd;
-}
-public String toString(int tab) {
- StringBuffer result = new StringBuffer(tabString(tab));
- result.append("Recovered method:\n"); //$NON-NLS-1$
- this.methodDeclaration.print(tab + 1, result);
- if (this.localTypes != null) {
- for (int i = 0; i < this.localTypeCount; i++) {
- result.append("\n"); //$NON-NLS-1$
- result.append(this.localTypes[i].toString(tab + 1));
- }
- }
- if (this.methodBody != null) {
- result.append("\n"); //$NON-NLS-1$
- result.append(this.methodBody.toString(tab + 1));
- }
- return result.toString();
-}
-/*
- * Update the bodyStart of the corresponding parse node
- */
-public void updateBodyStart(int bodyStart){
- this.foundOpeningBrace = true;
- this.methodDeclaration.bodyStart = bodyStart;
-}
-public AbstractMethodDeclaration updatedMethodDeclaration(){
-
- if (methodBody != null){
- Block block = methodBody.updatedBlock();
- if (block != null){
- methodDeclaration.statements = block.statements;
-
- /* first statement might be an explict constructor call destinated to a special slot */
- if (methodDeclaration.isConstructor()) {
- ConstructorDeclaration constructor = (ConstructorDeclaration)methodDeclaration;
- if (methodDeclaration.statements != null
- && methodDeclaration.statements[0] instanceof ExplicitConstructorCall){
- constructor.constructorCall = (ExplicitConstructorCall)methodDeclaration.statements[0];
- int length = methodDeclaration.statements.length;
- System.arraycopy(
- methodDeclaration.statements,
- 1,
- (methodDeclaration.statements = new Statement[length-1]),
- 0,
- length-1);
- }
- if (constructor.constructorCall == null){ // add implicit constructor call
- constructor.constructorCall = SuperReference.implicitSuperConstructorCall();
- }
- }
- }
- }
- if (localTypeCount > 0) methodDeclaration.bits |= ASTNode.HasLocalType;
- return methodDeclaration;
-}
-/*
- * Update the corresponding parse node from parser state which
- * is about to disappear because of restarting recovery
- */
-public void updateFromParserState(){
- // if parent is null then recovery already occured in diet parser.
- if(this.bodyStartsAtHeaderEnd() && this.parent != null){
- Parser parser = this.parser();
- /* might want to recover arguments or thrown exceptions */
- if (parser.listLength > 0 && parser.astLengthPtr > 0){ // awaiting interface type references
- /* has consumed the arguments - listed elements must be thrown exceptions */
- if (methodDeclaration.sourceEnd == parser.rParenPos) {
-
- // protection for bugs 15142
- int length = parser.astLengthStack[parser.astLengthPtr];
- int astPtr = parser.astPtr - length;
- boolean canConsume = astPtr >= 0;
- if(canConsume) {
- if((!(parser.astStack[astPtr] instanceof AbstractMethodDeclaration))) {
- canConsume = false;
- }
- for (int i = 1, max = length + 1; i < max; i++) {
- if(!(parser.astStack[astPtr + i ] instanceof TypeReference)) {
- canConsume = false;
- }
- }
- }
- if (!canConsume){
- parser.listLength = 0;
- }
- } else {
- /* has not consumed arguments yet, listed elements must be arguments */
- if (parser.currentToken == TokenNameLPAREN || parser.currentToken == TokenNameSEMICOLON){
- /* if currentToken is parenthesis this last argument is a method/field signature */
- parser.astLengthStack[parser.astLengthPtr] --;
- parser.astPtr --;
- parser.listLength --;
- parser.currentToken = 0;
- }
- int argLength = parser.astLengthStack[parser.astLengthPtr];
- int argStart = parser.astPtr - argLength + 1;
- boolean needUpdateRParenPos = parser.rParenPos < parser.lParenPos; // 12387 : rParenPos will be used
-
- // to compute bodyStart, and thus used to set next checkpoint.
- int count;
- for (count = 0; count < argLength; count++){
- ASTNode aNode = parser.astStack[argStart+count];
- if(aNode instanceof Argument) {
- Argument argument = (Argument)aNode;
- /* cannot be an argument if non final */
- char[][] argTypeName = (argument.type!=null)?argument.type.getTypeName():new char[][]{};
- if ((argument.modifiers & ~ClassFileConstants.AccFinal) != 0
- || (argTypeName.length == 1
- && CharOperation.equals(argTypeName[0], TypeBinding.VOID.sourceName()))){
- parser.astLengthStack[parser.astLengthPtr] = count;
- parser.astPtr = argStart+count-1;
- parser.listLength = count;
- parser.currentToken = 0;
- break;
- }
- if (needUpdateRParenPos) parser.rParenPos = argument.sourceEnd + 1;
- } else {
- parser.astLengthStack[parser.astLengthPtr] = count;
- parser.astPtr = argStart+count-1;
- parser.listLength = count;
- parser.currentToken = 0;
- break;
- }
- }
- if (parser.listLength > 0 && parser.astLengthPtr > 0){
-
- // protection for bugs 15142
- int length = parser.astLengthStack[parser.astLengthPtr];
- int astPtr = parser.astPtr - length;
- boolean canConsume = astPtr >= 0;
- if(canConsume) {
- if((!(parser.astStack[astPtr] instanceof AbstractMethodDeclaration))) {
- canConsume = false;
- }
- for (int i = 1, max = length + 1; i < max; i++) {
- if(!(parser.astStack[astPtr + i ] instanceof Argument)) {
- canConsume = false;
- }
- }
- }
- if(canConsume) {
- parser.consumeMethodHeaderRightParen();
- /* fix-up positions, given they were updated against rParenPos, which did not get set */
- if (parser.currentElement == this){ // parameter addition might have added an awaiting (no return type) method - see 1FVXQZ4 */
- methodDeclaration.sourceEnd = methodDeclaration.arguments[methodDeclaration.arguments.length-1].sourceEnd;
- methodDeclaration.bodyStart = methodDeclaration.sourceEnd+1;
- parser.lastCheckPoint = methodDeclaration.bodyStart;
- }
- }
- }
- }
- }
- }
-}
-public RecoveredElement updateOnClosingBrace(int braceStart, int braceEnd){
- RecoveredElement recoveredElement = super.updateOnClosingBrace(braceStart, braceEnd);
- if (recoveredElement!=this)
- this.parser().recoverAST(this);
- return recoveredElement;}
-/*
- * An opening brace got consumed, might be the expected opening one of the current element,
- * in which case the bodyStart is updated.
- */
-public RecoveredElement updateOnOpeningBrace(int braceStart, int braceEnd){
-
- /* in case the opening brace is close enough to the signature */
- if (bracketBalance == 0){
- /*
- if (parser.scanner.searchLineNumber(methodDeclaration.sourceEnd)
- != parser.scanner.searchLineNumber(braceEnd)){
- */
- switch(parser().lastIgnoredToken){
- case -1 :
- case TokenNamethrows :
- break;
- default:
- this.foundOpeningBrace = true;
- bracketBalance = 1; // pretend the brace was already there
- }
- }
- return super.updateOnOpeningBrace(braceStart, braceEnd);
-}
-public void updateParseTree(){
- this.updatedMethodDeclaration();
-}
-/*
- * Update the declarationSourceEnd of the corresponding parse node
- */
-public void updateSourceEndIfNecessary(int braceStart, int braceEnd){
- if (this.methodDeclaration.declarationSourceEnd == 0) {
- if(parser().rBraceSuccessorStart >= braceEnd) {
- this.methodDeclaration.declarationSourceEnd = parser().rBraceEnd;
- this.methodDeclaration.bodyEnd = parser().rBraceStart;
- } else {
- this.methodDeclaration.declarationSourceEnd = braceEnd;
- this.methodDeclaration.bodyEnd = braceStart - 1;
- }
- }
-}
-public ProgramElement updatedASTNode() {
- return updatedMethodDeclaration();
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredStatement.java
deleted file mode 100644
index 1d96de7a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredStatement.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.parser;
-
-/**
- * Internal statement structure for parsing recovery
- */
-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.ProgramElement;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Statement;
-
-public class RecoveredStatement extends RecoveredElement {
-
- public Statement statement;
-
- public RecoveredElement[] childStatements;
- public int childCount;
-
- public RecoveredStatement(Statement statement, RecoveredElement parent, int bracketBalance){
- super(parent, bracketBalance);
- this.statement = statement;
-
-}
-/*
- * Answer the associated parsed structure
- */
-public ASTNode parseTree(){
- return statement;
-}
-/*
- * Answer the very source end of the corresponding parse node
- */
-public int sourceEnd(){
- return this.statement.sourceEnd;
-}
-public String toString(int tab){
- return tabString(tab) + "Recovered statement:\n" + statement.print(tab + 1, new StringBuffer(10)); //$NON-NLS-1$
-}
-public Statement updatedStatement(){
- for (int i = 0; i < childCount ; i++) {
- childStatements[i].updatedASTNode();
- }
- return statement;
-}
-public void updateParseTree(){
- this.updatedStatement();
-}
-/*
- * Update the declarationSourceEnd of the corresponding parse node
- */
-public void updateSourceEndIfNecessary(int bodyStart, int bodyEnd){
- if (this.statement.sourceEnd == 0)
- this.statement.sourceEnd = bodyEnd;
-}
-public ProgramElement updatedASTNode() {
- return updatedStatement();
-}
-
-
-public RecoveredElement add(AbstractMethodDeclaration methodDeclaration, int bracketBalanceValue) {
-
-
- RecoveredMethod element = new RecoveredMethod(methodDeclaration, this, bracketBalanceValue, this.recoveringParser);
- addChild(element);
-
-
- /* consider that if the opening brace was not found, it is there */
- if (!foundOpeningBrace){
- foundOpeningBrace = true;
- this.bracketBalance++;
- }
- /* if method not finished, then method becomes current */
- if (methodDeclaration.declarationSourceEnd == 0) return element;
- return this;
-}
-
-private void addChild(RecoveredElement statement)
-{
- if (this.childStatements == null) {
- this.childStatements = new RecoveredElement[5];
- this.childCount = 0;
- } else {
- if (this.childCount == this.childStatements.length) {
- System.arraycopy(
- this.childStatements,
- 0,
- (this.childStatements = new RecoveredElement[2 * this.childCount]),
- 0,
- this.childCount);
- }
- }
- this.childStatements[this.childCount++] = statement;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredType.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredType.java
deleted file mode 100644
index 93637aab..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredType.java
+++ /dev/null
@@ -1,510 +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.compiler.parser;
-
-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.Block;
-import org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Initializer;
-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.ast.TypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants;
-
-/**
- * Internal type structure for parsing recovery
- */
-
-public class RecoveredType extends RecoveredStatement implements TerminalTokens {
- public TypeDeclaration typeDeclaration;
-
- public RecoveredType[] memberTypes;
- public int memberTypeCount;
- public RecoveredField[] fields;
- public int fieldCount;
- public RecoveredMethod[] methods;
- public int methodCount;
-
- public boolean preserveContent = false; // only used for anonymous types
- public int bodyEnd;
-
- public int pendingTypeParametersStart;
-
-public RecoveredType(TypeDeclaration typeDeclaration, RecoveredElement parent, int bracketBalance){
- super(typeDeclaration, parent, bracketBalance);
- this.typeDeclaration = typeDeclaration;
- if(typeDeclaration.allocation != null && typeDeclaration.allocation.type == null) {
- // an enum constant body can not exist if there is no opening brace
- this.foundOpeningBrace = true;
- } else {
- this.foundOpeningBrace = !bodyStartsAtHeaderEnd();
- }
- if(this.foundOpeningBrace) {
- this.bracketBalance++;
- }
-
- this.preserveContent = this.parser().methodRecoveryActivated || this.parser().statementRecoveryActivated;
-}
-public RecoveredElement add(AbstractMethodDeclaration methodDeclaration, int bracketBalanceValue) {
-
- /* do not consider a method starting passed the type end (if set)
- it must be belonging to an enclosing type */
- if (typeDeclaration.declarationSourceEnd != 0
- && methodDeclaration.declarationSourceStart > typeDeclaration.declarationSourceEnd){
- return this.parent.add(methodDeclaration, bracketBalanceValue);
- }
-
- if (methods == null) {
- methods = new RecoveredMethod[5];
- methodCount = 0;
- } else {
- if (methodCount == methods.length) {
- System.arraycopy(
- methods,
- 0,
- (methods = new RecoveredMethod[2 * methodCount]),
- 0,
- methodCount);
- }
- }
- RecoveredMethod element = new RecoveredMethod(methodDeclaration, this, bracketBalanceValue, this.recoveringParser);
- methods[methodCount++] = element;
-
- /* consider that if the opening brace was not found, it is there */
- if (!foundOpeningBrace){
- foundOpeningBrace = true;
- this.bracketBalance++;
- }
- /* if method not finished, then method becomes current */
- if (methodDeclaration.declarationSourceEnd == 0) return element;
- return this;
-}
-public RecoveredElement add(Block nestedBlockDeclaration,int bracketBalanceValue) {
-
- int modifiers = ClassFileConstants.AccDefault;
- if(this.parser().recoveredStaticInitializerStart != 0) {
- modifiers = ClassFileConstants.AccStatic;
- }
- return this.add(new Initializer(nestedBlockDeclaration, modifiers), bracketBalanceValue);
-}
-public RecoveredElement add(FieldDeclaration fieldDeclaration, int bracketBalanceValue) {
-
- /* do not consider a field starting passed the type end (if set)
- it must be belonging to an enclosing type */
- if (typeDeclaration.declarationSourceEnd != 0
- && fieldDeclaration.declarationSourceStart > typeDeclaration.declarationSourceEnd) {
- return this.parent.add(fieldDeclaration, bracketBalanceValue);
- }
- if (fields == null) {
- fields = new RecoveredField[5];
- fieldCount = 0;
- } else {
- if (fieldCount == fields.length) {
- System.arraycopy(
- fields,
- 0,
- (fields = new RecoveredField[2 * fieldCount]),
- 0,
- fieldCount);
- }
- }
- RecoveredField element;
- switch (fieldDeclaration.getKind()) {
- case AbstractVariableDeclaration.FIELD:
- element = new RecoveredField(fieldDeclaration, this, bracketBalanceValue);
- break;
- case AbstractVariableDeclaration.INITIALIZER:
- element = new RecoveredInitializer(fieldDeclaration, this, bracketBalanceValue);
- break;
- default:
- // never happens, as field is always identified
- return this;
- }
- fields[fieldCount++] = element;
-
- /* consider that if the opening brace was not found, it is there */
- if (!foundOpeningBrace){
- foundOpeningBrace = true;
- this.bracketBalance++;
- }
- /* if field not finished, then field becomes current */
- if (fieldDeclaration.declarationSourceEnd == 0) return element;
- return this;
-}
-public RecoveredElement add(TypeDeclaration memberTypeDeclaration, int bracketBalanceValue) {
-
- /* do not consider a type starting passed the type end (if set)
- it must be belonging to an enclosing type */
- if (typeDeclaration.declarationSourceEnd != 0
- && memberTypeDeclaration.declarationSourceStart > typeDeclaration.declarationSourceEnd){
- return this.parent.add(memberTypeDeclaration, bracketBalanceValue);
- }
-
- if ((memberTypeDeclaration.bits & ASTNode.IsAnonymousType) != 0){
- if (this.methodCount > 0) {
- // add it to the last method body
- RecoveredMethod lastMethod = this.methods[this.methodCount-1];
- lastMethod.methodDeclaration.bodyEnd = 0; // reopen method
- lastMethod.methodDeclaration.declarationSourceEnd = 0; // reopen method
- lastMethod.bracketBalance++; // expect one closing brace
- return lastMethod.add(memberTypeDeclaration, bracketBalanceValue);
- } else {
- // ignore
- return this;
- }
- }
-
- if (memberTypes == null) {
- memberTypes = new RecoveredType[5];
- memberTypeCount = 0;
- } else {
- if (memberTypeCount == memberTypes.length) {
- System.arraycopy(
- memberTypes,
- 0,
- (memberTypes = new RecoveredType[2 * memberTypeCount]),
- 0,
- memberTypeCount);
- }
- }
- RecoveredType element = new RecoveredType(memberTypeDeclaration, this, bracketBalanceValue);
- memberTypes[memberTypeCount++] = element;
-
- /* consider that if the opening brace was not found, it is there */
- if (!foundOpeningBrace){
- foundOpeningBrace = true;
- this.bracketBalance++;
- }
- /* if member type not finished, then member type becomes current */
- if (memberTypeDeclaration.declarationSourceEnd == 0) return element;
- return this;
-}
-/*
- * Answer the body end of the corresponding parse node
- */
-public int bodyEnd(){
- if (bodyEnd == 0) return typeDeclaration.declarationSourceEnd;
- return bodyEnd;
-}
-public boolean bodyStartsAtHeaderEnd(){
- if (typeDeclaration.superclass == null){
- return typeDeclaration.bodyStart == typeDeclaration.sourceEnd+1;
- } else {
- return typeDeclaration.bodyStart == typeDeclaration.superclass.sourceEnd+1;
- }
-}
-/*
- * Answer the enclosing type node, or null if none
- */
-public RecoveredType enclosingType(){
- RecoveredElement current = parent;
- while (current != null){
- if (current instanceof RecoveredType){
- return (RecoveredType) current;
- }
- current = current.parent;
- }
- return null;
-}
-public char[] name(){
- return typeDeclaration.name;
-}
-/*
- * Answer the associated parsed structure
- */
-public ASTNode parseTree(){
- return typeDeclaration;
-}
-/*
- * Answer the very source end of the corresponding parse node
- */
-public int sourceEnd(){
- return this.typeDeclaration.declarationSourceEnd;
-}
-public String toString(int tab) {
- StringBuffer result = new StringBuffer(tabString(tab));
- result.append("Recovered type:\n"); //$NON-NLS-1$
- if ((typeDeclaration.bits & ASTNode.IsAnonymousType) != 0) {
- result.append(tabString(tab));
- result.append(" "); //$NON-NLS-1$
- }
- typeDeclaration.print(tab + 1, result);
- if (this.memberTypes != null) {
- for (int i = 0; i < this.memberTypeCount; i++) {
- result.append("\n"); //$NON-NLS-1$
- result.append(this.memberTypes[i].toString(tab + 1));
- }
- }
- if (this.fields != null) {
- for (int i = 0; i < this.fieldCount; i++) {
- result.append("\n"); //$NON-NLS-1$
- result.append(this.fields[i].toString(tab + 1));
- }
- }
- if (this.methods != null) {
- for (int i = 0; i < this.methodCount; i++) {
- result.append("\n"); //$NON-NLS-1$
- result.append(this.methods[i].toString(tab + 1));
- }
- }
- return result.toString();
-}
-/*
- * Update the bodyStart of the corresponding parse node
- */
-public void updateBodyStart(int bodyStart){
- this.foundOpeningBrace = true;
- this.typeDeclaration.bodyStart = bodyStart;
-}
-public Statement updatedStatement(){
-
- // ignore closed anonymous type
- if ((typeDeclaration.bits & ASTNode.IsAnonymousType) != 0 && !this.preserveContent){
- return null;
- }
-
- TypeDeclaration updatedType = this.updatedTypeDeclaration();
- if ((updatedType.bits & ASTNode.IsAnonymousType) != 0){
- /* in presence of an anonymous type, we want the full allocation expression */
- return updatedType.allocation;
- }
- return updatedType;
-}
-public TypeDeclaration updatedTypeDeclaration(){
- int lastEnd = typeDeclaration.bodyStart;
- /* update member types */
- if (memberTypeCount > 0){
- int existingCount = typeDeclaration.memberTypes == null ? 0 : typeDeclaration.memberTypes.length;
- TypeDeclaration[] memberTypeDeclarations = new TypeDeclaration[existingCount + memberTypeCount];
- if (existingCount > 0){
- System.arraycopy(typeDeclaration.memberTypes, 0, memberTypeDeclarations, 0, existingCount);
- }
- // may need to update the declarationSourceEnd of the last type
- if (memberTypes[memberTypeCount - 1].typeDeclaration.declarationSourceEnd == 0){
- int bodyEndValue = bodyEnd();
- memberTypes[memberTypeCount - 1].typeDeclaration.declarationSourceEnd = bodyEndValue;
- memberTypes[memberTypeCount - 1].typeDeclaration.bodyEnd = bodyEndValue;
- }
- for (int i = 0; i < memberTypeCount; i++){
- memberTypeDeclarations[existingCount + i] = memberTypes[i].updatedTypeDeclaration();
- }
- typeDeclaration.memberTypes = memberTypeDeclarations;
- if(memberTypeDeclarations[memberTypeDeclarations.length - 1].declarationSourceEnd > lastEnd) {
- lastEnd = memberTypeDeclarations[memberTypeDeclarations.length - 1].declarationSourceEnd;
- }
- }
- /* update fields */
- if (fieldCount > 0){
- int existingCount = typeDeclaration.fields == null ? 0 : typeDeclaration.fields.length;
- FieldDeclaration[] fieldDeclarations = new FieldDeclaration[existingCount + fieldCount];
- if (existingCount > 0){
- System.arraycopy(typeDeclaration.fields, 0, fieldDeclarations, 0, existingCount);
- }
- // may need to update the declarationSourceEnd of the last field
- if (fields[fieldCount - 1].fieldDeclaration.declarationSourceEnd == 0){
- int temp = bodyEnd();
- fields[fieldCount - 1].fieldDeclaration.declarationSourceEnd = temp;
- fields[fieldCount - 1].fieldDeclaration.declarationEnd = temp;
- }
- for (int i = 0; i < fieldCount; i++){
- fieldDeclarations[existingCount + i] = fields[i].updatedFieldDeclaration();
- }
- typeDeclaration.fields = fieldDeclarations;
- if(fieldDeclarations[fieldDeclarations.length - 1].declarationSourceEnd > lastEnd) {
- lastEnd = fieldDeclarations[fieldDeclarations.length - 1].declarationSourceEnd;
- }
- }
- /* update methods */
- int existingCount = typeDeclaration.methods == null ? 0 : typeDeclaration.methods.length;
- boolean hasConstructor = false, hasRecoveredConstructor = false;
- boolean hasAbstractMethods = false;
- int defaultConstructorIndex = -1;
- if (methodCount > 0){
- AbstractMethodDeclaration[] methodDeclarations = new AbstractMethodDeclaration[existingCount + methodCount];
- for (int i = 0; i < existingCount; i++){
- AbstractMethodDeclaration m = typeDeclaration.methods[i];
- if (m.isDefaultConstructor()) defaultConstructorIndex = i;
- if (m.isAbstract()) hasAbstractMethods = true;
- methodDeclarations[i] = m;
- }
- // may need to update the declarationSourceEnd of the last method
- if (methods[methodCount - 1].methodDeclaration.declarationSourceEnd == 0){
- int bodyEndValue = bodyEnd();
- methods[methodCount - 1].methodDeclaration.declarationSourceEnd = bodyEndValue;
- methods[methodCount - 1].methodDeclaration.bodyEnd = bodyEndValue;
- }
- for (int i = 0; i < methodCount; i++){
- AbstractMethodDeclaration updatedMethod = methods[i].updatedMethodDeclaration();
- if (updatedMethod.isConstructor()) hasRecoveredConstructor = true;
- if (updatedMethod.isAbstract()) hasAbstractMethods = true;
- methodDeclarations[existingCount + i] = updatedMethod;
- }
- typeDeclaration.methods = methodDeclarations;
- if(methodDeclarations[methodDeclarations.length - 1].declarationSourceEnd > lastEnd) {
- lastEnd = methodDeclarations[methodDeclarations.length - 1].declarationSourceEnd;
- }
- if (hasAbstractMethods) typeDeclaration.bits |= ASTNode.HasAbstractMethods;
- hasConstructor = typeDeclaration.checkConstructors(this.parser());
- } else {
- for (int i = 0; i < existingCount; i++){
- if (typeDeclaration.methods[i].isConstructor()) hasConstructor = true;
- }
- }
- /* add clinit ? */
- if (typeDeclaration.needClassInitMethod()){
- boolean alreadyHasClinit = false;
- for (int i = 0; i < existingCount; i++){
- if (typeDeclaration.methods[i].isClinit()){
- alreadyHasClinit = true;
- break;
- }
- }
- if (!alreadyHasClinit) typeDeclaration.addClinit();
- }
- /* add default constructor ? */
- if (defaultConstructorIndex >= 0 && hasRecoveredConstructor){
- /* should discard previous default construtor */
- AbstractMethodDeclaration[] methodDeclarations = new AbstractMethodDeclaration[typeDeclaration.methods.length - 1];
- if (defaultConstructorIndex != 0){
- System.arraycopy(typeDeclaration.methods, 0, methodDeclarations, 0, defaultConstructorIndex);
- }
- if (defaultConstructorIndex != typeDeclaration.methods.length-1){
- System.arraycopy(
- typeDeclaration.methods,
- defaultConstructorIndex+1,
- methodDeclarations,
- defaultConstructorIndex,
- typeDeclaration.methods.length - defaultConstructorIndex - 1);
- }
- typeDeclaration.methods = methodDeclarations;
- } else {
- if (!hasConstructor) {// if was already reduced, then constructor
- boolean insideFieldInitializer = false;
- RecoveredElement parentElement = this.parent;
- while (parentElement != null){
- if (parentElement instanceof RecoveredField){
- insideFieldInitializer = true;
- break;
- }
- parentElement = parentElement.parent;
- }
- typeDeclaration.createDefaultConstructor(!parser().diet || insideFieldInitializer, true);
- }
- }
- if (parent instanceof RecoveredType){
- typeDeclaration.bits |= ASTNode.IsMemberType;
- } else if (parent instanceof RecoveredMethod){
- typeDeclaration.bits |= ASTNode.IsLocalType;
- }
- if(typeDeclaration.declarationSourceEnd == 0) {
- typeDeclaration.declarationSourceEnd = lastEnd;
- typeDeclaration.bodyEnd = lastEnd;
- }
- return typeDeclaration;
-}
-/*
- * Update the corresponding parse node from parser state which
- * is about to disappear because of restarting recovery
- */
-public void updateFromParserState(){
-
- // anymous type and enum constant doesn't need to be updated
- if(this.bodyStartsAtHeaderEnd() && typeDeclaration.allocation == null){
- Parser parser = this.parser();
- /* might want to recover implemented interfaces */
- // protection for bugs 15142
- if (parser.listLength > 0 && parser.astLengthPtr > 0){ // awaiting interface type references
- int length = parser.astLengthStack[parser.astLengthPtr];
- int astPtr = parser.astPtr - length;
- boolean canConsume = astPtr >= 0;
- if(canConsume) {
- if((!(parser.astStack[astPtr] instanceof TypeDeclaration))) {
- canConsume = false;
- }
- for (int i = 1, max = length + 1; i < max; i++) {
- if(!(parser.astStack[astPtr + i ] instanceof TypeReference)) {
- canConsume = false;
- }
- }
- }
- }
- }
-}
-/*
- * A closing brace got consumed, might have closed the current element,
- * in which case both the currentElement is exited
- */
-public RecoveredElement updateOnClosingBrace(int braceStart, int braceEnd){
- if ((--bracketBalance <= 0) && (parent != null)){
- this.updateSourceEndIfNecessary(braceStart, braceEnd);
- this.bodyEnd = braceStart - 1;
- return parent;
- }
- return this;
-}
-/*
- * An opening brace got consumed, might be the expected opening one of the current element,
- * in which case the bodyStart is updated.
- */
-public RecoveredElement updateOnOpeningBrace(int braceStart, int braceEnd){
- /* in case the opening brace is not close enough to the signature, ignore it */
- if (bracketBalance == 0){
- /*
- if (parser.scanner.searchLineNumber(typeDeclaration.sourceEnd)
- != parser.scanner.searchLineNumber(braceEnd)){
- */
- Parser parser = this.parser();
- switch(parser.lastIgnoredToken){
- case -1 :
- case TokenNameextends :
- case TokenNameimplements :
- case TokenNameGREATER :
- case TokenNameRIGHT_SHIFT :
- case TokenNameUNSIGNED_RIGHT_SHIFT :
- if (parser.recoveredStaticInitializerStart == 0) break;
- default:
- this.foundOpeningBrace = true;
- bracketBalance = 1; // pretend the brace was already there
- }
- }
- // might be an initializer
- if (this.bracketBalance == 1){
- Block block = new Block(0);
- Parser parser = this.parser();
- block.sourceStart = parser.scanner.startPosition;
- Initializer init;
- if (parser.recoveredStaticInitializerStart == 0){
- init = new Initializer(block, ClassFileConstants.AccDefault);
- } else {
- init = new Initializer(block, ClassFileConstants.AccStatic);
- init.declarationSourceStart = parser.recoveredStaticInitializerStart;
- }
- init.bodyStart = parser.scanner.currentPosition;
- return this.add(init, 1);
- }
- return super.updateOnOpeningBrace(braceStart, braceEnd);
-}
-public void updateParseTree(){
- this.updatedTypeDeclaration();
-}
-/*
- * Update the declarationSourceEnd of the corresponding parse node
- */
-public void updateSourceEndIfNecessary(int start, int end){
- if (this.typeDeclaration.declarationSourceEnd == 0){
- this.bodyEnd = 0;
- this.typeDeclaration.declarationSourceEnd = end;
- this.typeDeclaration.bodyEnd = end;
- }
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredUnit.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredUnit.java
deleted file mode 100644
index f37d4a63..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveredUnit.java
+++ /dev/null
@@ -1,325 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.parser;
-
-/**
- * Internal field structure for parsing recovery
- */
-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.Assignment;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Block;
-import org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration;
-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.ProgramElement;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Statement;
-import org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration;
-
-public class RecoveredUnit extends RecoveredElement {
-
- public CompilationUnitDeclaration unitDeclaration;
-
-// public RecoveredImport[] imports;
-// public int importCount;
-// public RecoveredType[] types;
-// public int typeCount;
-
- public RecoveredElement[] statements;
- public int statementCount;
-
- public RecoveredUnit(CompilationUnitDeclaration unitDeclaration, int bracketBalance, Parser parser){
- super(null, bracketBalance, parser);
- this.unitDeclaration = unitDeclaration;
-}
-
-
-/*
- * Record a method declaration: should be attached to last type
- */
-public RecoveredElement add(AbstractMethodDeclaration methodDeclaration, int bracketBalanceValue) {
-
-
- RecoveredMethod element = new RecoveredMethod(methodDeclaration, this, bracketBalanceValue, this.recoveringParser);
- addStatement(element);
-
-
- /* consider that if the opening brace was not found, it is there */
- if (!foundOpeningBrace){
- foundOpeningBrace = true;
- this.bracketBalance++;
- }
- /* if method not finished, then method becomes current */
- if (methodDeclaration.declarationSourceEnd == 0) return element;
- return this;
-}
-/*
- * Record a field declaration: should be attached to last type
- */
-public RecoveredElement add(FieldDeclaration fieldDeclaration, int bracketBalanceValue) {
-
- RecoveredField element;
- element = new RecoveredField(fieldDeclaration, this, bracketBalanceValue);
- addStatement(element);
-
- /* consider that if the opening brace was not found, it is there */
- if (!foundOpeningBrace){
- foundOpeningBrace = true;
- this.bracketBalance++;
- }
- /* if field not finished, then field becomes current */
- if (fieldDeclaration.declarationSourceEnd == 0) return element;
- return this;
-}
-
-public RecoveredElement add(LocalDeclaration localDeclaration, int bracketBalanceValue) {
- RecoveredLocalVariable element;
- element = new RecoveredLocalVariable(localDeclaration, this, bracketBalanceValue);
-addStatement(element);
-
-/* consider that if the opening brace was not found, it is there */
-if (!foundOpeningBrace){
-foundOpeningBrace = true;
-this.bracketBalance++;
-}
-/* if field not finished, then field becomes current */
-if (localDeclaration.declarationSourceEnd == 0) return element;
-return this;
-}
-
-
-
-public RecoveredElement add(ImportReference importReference, int bracketBalanceValue) {
-// if (this.imports == null) {
-// this.imports = new RecoveredImport[5];
-// this.importCount = 0;
-// } else {
-// if (this.importCount == this.imports.length) {
-// System.arraycopy(
-// this.imports,
-// 0,
-// (this.imports = new RecoveredImport[2 * this.importCount]),
-// 0,
-// this.importCount);
-// }
-// }
-// RecoveredImport element = new RecoveredImport(importReference, this, bracketBalanceValue);
-// this.imports[this.importCount++] = element;
-//
-// /* if import not finished, then import becomes current */
-// if (importReference.declarationSourceEnd == 0) return element;
- return this;
-}
-public RecoveredElement add(TypeDeclaration typeDeclaration, int bracketBalanceValue) {
-
-// if ((typeDeclaration.bits & ASTNode.IsAnonymousType) != 0){
-// if (this.typeCount > 0) {
-// // add it to the last type
-// RecoveredType lastType = this.types[this.typeCount-1];
-// lastType.bodyEnd = 0; // reopen type
-// lastType.typeDeclaration.bodyEnd = 0; // reopen type
-// lastType.typeDeclaration.declarationSourceEnd = 0; // reopen type
-// lastType.bracketBalance++; // expect one closing brace
-// return lastType.add(typeDeclaration, bracketBalanceValue);
-// }
-// }
-// if (this.types == null) {
-// this.types = new RecoveredType[5];
-// this.typeCount = 0;
-// } else {
-// if (this.typeCount == this.types.length) {
-// System.arraycopy(
-// this.types,
-// 0,
-// (this.types = new RecoveredType[2 * this.typeCount]),
-// 0,
-// this.typeCount);
-// }
-// }
-// RecoveredType element = new RecoveredType(typeDeclaration, this, bracketBalanceValue);
-// this.types[this.typeCount++] = element;
-//
-// /* if type not finished, then type becomes current */
-// if (typeDeclaration.declarationSourceEnd == 0) return element;
- return this;
-}
-
-private void addStatement(RecoveredElement statement)
-{
- if (this.statements == null) {
- this.statements = new RecoveredElement[5];
- this.statementCount = 0;
- } else {
- if (this.statementCount == this.statements.length) {
- System.arraycopy(
- this.statements,
- 0,
- (this.statements = new RecoveredElement[2 * this.statementCount]),
- 0,
- this.statementCount);
- }
- }
- this.statements[this.statementCount++] = statement;
-}
-/*
- * Answer the associated parsed structure
- */
-public ASTNode parseTree(){
- return this.unitDeclaration;
-}
-/*
- * Answer the very source end of the corresponding parse node
- */
-public int sourceEnd(){
- return this.unitDeclaration.sourceEnd;
-}
-public String toString(int tab) {
- StringBuffer result = new StringBuffer(tabString(tab));
- result.append("Recovered unit: [\n"); //$NON-NLS-1$
- this.unitDeclaration.print(tab + 1, result);
- result.append(tabString(tab + 1));
- result.append("]"); //$NON-NLS-1$
-// if (this.imports != null) {
-// for (int i = 0; i < this.importCount; i++) {
-// result.append("\n"); //$NON-NLS-1$
-// result.append(this.imports[i].toString(tab + 1));
-// }
-// }
- if (this.statements != null) {
- for (int i = 0; i < this.statementCount; i++) {
- result.append("\n"); //$NON-NLS-1$
- result.append(this.statements[i].toString(tab + 1));
- }
- }
- return result.toString();
-}
-public CompilationUnitDeclaration updatedCompilationUnitDeclaration(){
-
- /* update imports */
-// if (this.importCount > 0){
-// ImportReference[] importRefences = new ImportReference[this.importCount];
-// for (int i = 0; i < this.importCount; i++){
-// importRefences[i] = this.imports[i].updatedImportReference();
-// }
-// this.unitDeclaration.imports = importRefences;
-// }
- /* update types */
- int sourceEnd=(this.unitDeclaration.sourceEnd>0)?this.unitDeclaration.sourceEnd:this.parser().scanner.eofPosition;
- if (this.statementCount > 0){
- int existingCount = this.unitDeclaration.statements == null ? 0 : this.unitDeclaration.statements.length;
- ProgramElement[] stmts = new ProgramElement[existingCount + this.statementCount];
- if (existingCount > 0){
- System.arraycopy(this.unitDeclaration.statements, 0, stmts, 0, existingCount);
- }
- ASTNode astNode = this.statements[this.statementCount - 1].parseTree();
- // may need to update the declarationSourceEnd of the last type
- if (astNode.sourceEnd == 0){
- astNode.sourceEnd= sourceEnd;
- if (astNode instanceof Assignment)
- {
- Assignment assign=(Assignment)astNode;
- if (assign.expression instanceof FunctionExpression)
- {
- FunctionExpression functionExpression=(FunctionExpression)assign.expression;
- functionExpression.sourceEnd=astNode.sourceEnd;
- functionExpression.methodDeclaration.bodyEnd=
- functionExpression.methodDeclaration.sourceEnd=astNode.sourceEnd;
- }
-
-
- }
-
-// this.statements[this.statementCount - 1].updateSourceEndIfNecessary(sourceEnd)typeDeclaration.bodyEnd = this.unitDeclaration.sourceEnd;
- }
- if (astNode instanceof AbstractMethodDeclaration && ((AbstractMethodDeclaration)astNode).bodyEnd<=0)
- ((AbstractMethodDeclaration)astNode).bodyEnd=this.unitDeclaration.sourceEnd;
- int actualCount = existingCount;
- for (int i = 0; i < this.statementCount; i++){
- ProgramElement updatedASTNode = this.statements[i].updatedASTNode();
- if (updatedASTNode!=null && updatedASTNode.sourceEnd<=0 )
- {
- updatedASTNode.sourceEnd=this.unitDeclaration.sourceEnd;
- }
- if (updatedASTNode instanceof AbstractMethodDeclaration && ((AbstractMethodDeclaration)updatedASTNode).bodyEnd<=0 )
- ((AbstractMethodDeclaration)updatedASTNode).bodyEnd=this.unitDeclaration.sourceEnd;
- else if (updatedASTNode instanceof AbstractVariableDeclaration && ((AbstractVariableDeclaration)updatedASTNode).declarationSourceEnd<=0 )
- ((AbstractVariableDeclaration)updatedASTNode).declarationSourceEnd=this.unitDeclaration.sourceEnd;
-
- // this.statements[i].updateParseTree();
- // filter out local types (12454)
-// if ((typeDecl.bits & ASTNode.IsLocalType) == 0){
- stmts[actualCount++] = updatedASTNode;
-// }
- }
-// if (actualCount != this.statementCount){
-// System.arraycopy(
-// stmts,
-// 0,
-// stmts = new ProgramElement[existingCount+actualCount],
-// 0,
-// existingCount+actualCount);
-// }
- this.unitDeclaration.statements = stmts;
- }
- else if (this.unitDeclaration.statements==null)
- this.unitDeclaration.statements=new ProgramElement[0];
- return this.unitDeclaration;
-}
-public RecoveredElement add(Block nestedBlockDeclaration, int bracketBalanceValue) {
- RecoveredBlock element = new RecoveredBlock(nestedBlockDeclaration, this, bracketBalanceValue);
-
- // if we have a pending Argument, promote it into the new block
-// if (this.pendingArgument != null){
-// element.attach(this.pendingArgument);
-// this.pendingArgument = null;
-// }
- if(this.parser().statementRecoveryActivated) {
- this.addBlockStatement(element);
- }
- addStatement(element);
- if (nestedBlockDeclaration.sourceEnd == 0) return element;
- return this;
-}
-public RecoveredElement add(Statement statement, int bracketBalanceValue) {
- RecoveredStatement element = new RecoveredStatement(statement, this, bracketBalanceValue);
- addStatement(element);
- if (statement.sourceEnd == 0) return element;
- return this;
-}
-
-
-public void updateParseTree(){
- this.updatedCompilationUnitDeclaration();
-}
-/*
- * Update the sourceEnd of the corresponding parse node
- */
-public void updateSourceEndIfNecessary(int bodyStart, int bodyEnd){
- if (this.unitDeclaration.sourceEnd == 0)
- this.unitDeclaration.sourceEnd = bodyEnd;
-}
-
-
-public ProgramElement updatedASTNode() {
- //TODO: implement SHOULD NOT GET HERE
- throw new org.eclipse.wst.jsdt.core.UnimplementedException();
-}
-
-
-public void updateFromParserState() {
- if (parser().astPtr>=0)
- {
- }
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveryScanner.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveryScanner.java
deleted file mode 100644
index 3821fc96..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveryScanner.java
+++ /dev/null
@@ -1,241 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.compiler.parser;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-
-public class RecoveryScanner extends Scanner {
- public static final char[] FAKE_IDENTIFIER = "$missing$".toCharArray(); //$NON-NLS-1$
-
- private RecoveryScannerData data;
-
- private int[] pendingTokens;
- private int pendingTokensPtr = -1;
- private char[] fakeTokenSource = null;
- private boolean isInserted = true;
- private boolean precededByRemoved = false;
- private int skipNextInsertedTokens = -1;
-
- public boolean record = true;
-
- public RecoveryScanner(Scanner scanner, RecoveryScannerData data) {
- super(false,
- scanner.tokenizeWhiteSpace,
- scanner.checkNonExternalizedStringLiterals,
- scanner.sourceLevel,
- scanner.complianceLevel,
- scanner.taskTags,
- scanner.taskPriorities,
- scanner.isTaskCaseSensitive);
- this.setData(data);
- }
-
- public void insertToken(int token, int completedToken, int position) {
- insertTokens(new int []{token}, completedToken, position);
- }
-
- private int[] reverse(int[] tokens) {
- int length = tokens.length;
- for(int i = 0, max = length / 2; i < max; i++) {
- int tmp = tokens[i];
- tokens[i] = tokens[length - i - 1];
- tokens[length - i - 1] = tmp;
- }
- return tokens;
- }
- public void insertTokens(int[] tokens, int completedToken, int position) {
- if(!this.record) return;
-
- if(completedToken > -1 && Parser.statements_recovery_filter[completedToken] != 0) return;
-
- this.data.insertedTokensPtr++;
- if(this.data.insertedTokens == null) {
- this.data.insertedTokens = new int[10][];
- this.data.insertedTokensPosition = new int[10];
- this.data.insertedTokenUsed = new boolean[10];
- } else if(this.data.insertedTokens.length == this.data.insertedTokensPtr) {
- int length = this.data.insertedTokens.length;
- System.arraycopy(this.data.insertedTokens, 0, this.data.insertedTokens = new int[length * 2][], 0, length);
- System.arraycopy(this.data.insertedTokensPosition, 0, this.data.insertedTokensPosition = new int[length * 2], 0, length);
- System.arraycopy(this.data.insertedTokenUsed, 0, this.data.insertedTokenUsed = new boolean[length * 2], 0, length);
- }
- this.data.insertedTokens[this.data.insertedTokensPtr] = reverse(tokens);
- this.data.insertedTokensPosition[this.data.insertedTokensPtr] = position;
- this.data.insertedTokenUsed[this.data.insertedTokensPtr] = false;
- }
-
- public void replaceTokens(int token, int start, int end) {
- replaceTokens(new int []{token}, start, end);
- }
-
- public void replaceTokens(int[] tokens, int start, int end) {
- if(!this.record) return;
- this.data.replacedTokensPtr++;
- if(this.data.replacedTokensStart == null) {
- this.data.replacedTokens = new int[10][];
- this.data.replacedTokensStart = new int[10];
- this.data.replacedTokensEnd = new int[10];
- this.data.replacedTokenUsed= new boolean[10];
- } else if(this.data.replacedTokensStart.length == this.data.replacedTokensPtr) {
- int length = this.data.replacedTokensStart.length;
- System.arraycopy(this.data.replacedTokens, 0, this.data.replacedTokens = new int[length * 2][], 0, length);
- System.arraycopy(this.data.replacedTokensStart, 0, this.data.replacedTokensStart = new int[length * 2], 0, length);
- System.arraycopy(this.data.replacedTokensEnd, 0, this.data.replacedTokensEnd = new int[length * 2], 0, length);
- System.arraycopy(this.data.replacedTokenUsed, 0, this.data.replacedTokenUsed = new boolean[length * 2], 0, length);
- }
- this.data.replacedTokens[this.data.replacedTokensPtr] = reverse(tokens);
- this.data.replacedTokensStart[this.data.replacedTokensPtr] = start;
- this.data.replacedTokensEnd[this.data.replacedTokensPtr] = end;
- this.data.replacedTokenUsed[this.data.replacedTokensPtr] = false;
- }
-
- public void removeTokens(int start, int end) {
- if(!this.record) return;
- this.data.removedTokensPtr++;
- if(this.data.removedTokensStart == null) {
- this.data.removedTokensStart = new int[10];
- this.data.removedTokensEnd = new int[10];
- this.data.removedTokenUsed = new boolean[10];
- } else if(this.data.removedTokensStart.length == this.data.removedTokensPtr) {
- int length = this.data.removedTokensStart.length;
- System.arraycopy(this.data.removedTokensStart, 0, this.data.removedTokensStart = new int[length * 2], 0, length);
- System.arraycopy(this.data.removedTokensEnd, 0, this.data.removedTokensEnd = new int[length * 2], 0, length);
- System.arraycopy(this.data.removedTokenUsed, 0, this.data.removedTokenUsed = new boolean[length * 2], 0, length);
- }
- this.data.removedTokensStart[this.data.removedTokensPtr] = start;
- this.data.removedTokensEnd[this.data.removedTokensPtr] = end;
- this.data.removedTokenUsed[this.data.removedTokensPtr] = false;
- }
-
- public int getNextToken() throws InvalidInputException {
- if(this.pendingTokensPtr > -1) {
- int nextToken = this.pendingTokens[this.pendingTokensPtr--];
- if(nextToken == TerminalTokens.TokenNameIdentifier){
- this.fakeTokenSource = FAKE_IDENTIFIER;
- } else {
- this.fakeTokenSource = CharOperation.NO_CHAR;
- }
- return nextToken;
- }
-
- this.fakeTokenSource = null;
- this.precededByRemoved = false;
-
- if(this.data.insertedTokens != null) {
- for (int i = 0; i <= this.data.insertedTokensPtr; i++) {
- if(this.data.insertedTokensPosition[i] == this.currentPosition - 1 && i > skipNextInsertedTokens) {
- this.data.insertedTokenUsed[i] = true;
- this.pendingTokens = this.data.insertedTokens[i];
- this.pendingTokensPtr = this.data.insertedTokens[i].length - 1;
- this.isInserted = true;
- this.startPosition = this.currentPosition;
- this.skipNextInsertedTokens = i;
- int nextToken = this.pendingTokens[this.pendingTokensPtr--];
- if(nextToken == TerminalTokens.TokenNameIdentifier){
- this.fakeTokenSource = FAKE_IDENTIFIER;
- } else {
- this.fakeTokenSource = CharOperation.NO_CHAR;
- }
- return nextToken;
- }
- }
- this.skipNextInsertedTokens = -1;
- }
-
- int previousLocation = this.currentPosition;
- int currentToken = super.getNextToken();
-
- if(this.data.replacedTokens != null) {
- for (int i = 0; i <= this.data.replacedTokensPtr; i++) {
- if(this.data.replacedTokensStart[i] >= previousLocation &&
- this.data.replacedTokensStart[i] <= this.startPosition &&
- this.data.replacedTokensEnd[i] >= this.currentPosition - 1) {
- this.data.replacedTokenUsed[i] = true;
- this.pendingTokens = this.data.replacedTokens[i];
- this.pendingTokensPtr = this.data.replacedTokens[i].length - 1;
- this.fakeTokenSource = FAKE_IDENTIFIER;
- this.isInserted = false;
- this.currentPosition = this.data.replacedTokensEnd[i] + 1;
- int nextToken = this.pendingTokens[this.pendingTokensPtr--];
- if(nextToken == TerminalTokens.TokenNameIdentifier){
- this.fakeTokenSource = FAKE_IDENTIFIER;
- } else {
- this.fakeTokenSource = CharOperation.NO_CHAR;
- }
- return nextToken;
- }
- }
- }
- if(this.data.removedTokensStart != null) {
- for (int i = 0; i <= this.data.removedTokensPtr; i++) {
- if(this.data.removedTokensStart[i] >= previousLocation &&
- this.data.removedTokensStart[i] <= this.startPosition &&
- this.data.removedTokensEnd[i] >= this.currentPosition - 1) {
- this.data.removedTokenUsed[i] = true;
- this.currentPosition = this.data.removedTokensEnd[i] + 1;
- this.precededByRemoved = false;
- return getNextToken();
- }
- }
- }
- return currentToken;
- }
-
- public char[] getCurrentIdentifierSource() {
- if(this.fakeTokenSource != null) return this.fakeTokenSource;
- return super.getCurrentIdentifierSource();
- }
-
- public char[] getCurrentTokenSourceString() {
- if(this.fakeTokenSource != null) return this.fakeTokenSource;
- return super.getCurrentTokenSourceString();
- }
-
- public char[] getCurrentTokenSource() {
- if(this.fakeTokenSource != null) return this.fakeTokenSource;
- return super.getCurrentTokenSource();
- }
-
- public RecoveryScannerData getData() {
- return this.data;
- }
-
- public boolean isFakeToken() {
- return this.fakeTokenSource != null;
- }
-
- public boolean isInsertedToken() {
- return this.fakeTokenSource != null && this.isInserted;
- }
-
- public boolean isReplacedToken() {
- return this.fakeTokenSource != null && !this.isInserted;
- }
-
- public boolean isPrecededByRemovedToken() {
- return this.precededByRemoved;
- }
-
- public void setData(RecoveryScannerData data) {
- if(data == null) {
- this.data = new RecoveryScannerData();
- } else {
- this.data = data;
- }
- }
-
- public void setPendingTokens(int[] pendingTokens) {
- this.pendingTokens = pendingTokens;
- this.pendingTokensPtr = pendingTokens.length - 1;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveryScannerData.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveryScannerData.java
deleted file mode 100644
index a2fea55e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/RecoveryScannerData.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.compiler.parser;
-
-public class RecoveryScannerData {
- public int insertedTokensPtr = -1;
- public int[][] insertedTokens;
- public int[] insertedTokensPosition;
- public boolean[] insertedTokenUsed;
-
- public int replacedTokensPtr = -1;
- public int[][] replacedTokens;
- public int[] replacedTokensStart;
- public int[] replacedTokensEnd;
- public boolean[] replacedTokenUsed;
-
- public int removedTokensPtr = -1;
- public int[] removedTokensStart;
- public int[] removedTokensEnd;
- public boolean[] removedTokenUsed;
-
- public RecoveryScannerData removeUnused() {
- if(this.insertedTokens != null) {
- int newInsertedTokensPtr = -1;
- for (int i = 0; i <= this.insertedTokensPtr; i++) {
- if(this.insertedTokenUsed[i]) {
- newInsertedTokensPtr++;
- this.insertedTokens[newInsertedTokensPtr] = this.insertedTokens[i];
- this.insertedTokensPosition[newInsertedTokensPtr] = this.insertedTokensPosition[i];
- this.insertedTokenUsed[newInsertedTokensPtr] = this.insertedTokenUsed[i];
- }
- }
- this.insertedTokensPtr = newInsertedTokensPtr;
- }
-
- if(this.replacedTokens != null) {
- int newReplacedTokensPtr = -1;
- for (int i = 0; i <= this.replacedTokensPtr; i++) {
- if(this.replacedTokenUsed[i]) {
- newReplacedTokensPtr++;
- this.replacedTokens[newReplacedTokensPtr] = this.replacedTokens[i];
- this.replacedTokensStart[newReplacedTokensPtr] = this.replacedTokensStart[i];
- this.replacedTokensEnd[newReplacedTokensPtr] = this.replacedTokensEnd[i];
- this.replacedTokenUsed[newReplacedTokensPtr] = this.replacedTokenUsed[i];
- }
- }
- this.replacedTokensPtr = newReplacedTokensPtr;
- }
- if(this.removedTokensStart != null) {
- int newRemovedTokensPtr = -1;
- for (int i = 0; i <= this.removedTokensPtr; i++) {
- if(this.removedTokenUsed[i]) {
- newRemovedTokensPtr++;
- this.removedTokensStart[newRemovedTokensPtr] = this.removedTokensStart[i];
- this.removedTokensEnd[newRemovedTokensPtr] = this.removedTokensEnd[i];
- this.removedTokenUsed[newRemovedTokensPtr] = this.removedTokenUsed[i];
- }
- }
- this.removedTokensPtr = newRemovedTokensPtr;
- }
-
- return this;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/Scanner.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/Scanner.java
deleted file mode 100644
index 99d5730f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/Scanner.java
+++ /dev/null
@@ -1,4400 +0,0 @@
-/*******************************************************************************
- * 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.compiler.parser;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.internal.compiler.CompilationResult;
-import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants;
-import org.eclipse.wst.jsdt.internal.compiler.util.Messages;
-import org.eclipse.wst.jsdt.internal.compiler.util.Util;
-/**
- * IMPORTANT NOTE: Internal Scanner implementation. It is mirrored in
- * org.eclipse.wst.jsdt.core.compiler public package where it is API.
- * The mirror implementation is using the backward compatible ITerminalSymbols constant
- * definitions (stable with 2.0), whereas the internal implementation uses TerminalTokens
- * which constant values reflect the latest parser generation state.
- */
-public class Scanner implements TerminalTokens {
-
- //public int newIdentCount = 0;
-
- /* APIs ares
- - getNextToken() which return the current type of the token
- (this value is not memorized by the scanner)
- - getCurrentTokenSource() which provides with the token "REAL" source
- (aka all unicode have been transformed into a correct char)
- - sourceStart gives the position into the stream
- - currentPosition-1 gives the sourceEnd position into the stream
- */
- public long sourceLevel;
- public long complianceLevel;
-
- // 1.4 feature
- public boolean useAssertAsAnIndentifier = false;
- //flag indicating if processed source contains occurrences of keyword assert
- public boolean containsAssertKeyword = false;
-
- // 1.5 feature
- public boolean useEnumAsAnIndentifier = false;
-
- public boolean recordLineSeparator = false;
- public char currentCharacter;
- public int startPosition;
- public int currentPosition;
- public int initialPosition, eofPosition;
- // after this position eof are generated instead of real token from the source
-
- public boolean tokenizeComments = false;
- public boolean tokenizeWhiteSpace = false;
-
- //source should be viewed as a window (aka a part)
- //of a entire very large stream
- public char source[];
-
- //unicode support
- public char[] withoutUnicodeBuffer;
- public int withoutUnicodePtr; //when == 0 ==> no unicode in the current token
- public boolean unicodeAsBackSlash = false;
-
- public boolean scanningFloatLiteral = false;
-
- //support for /** comments
- public static final int COMMENT_ARRAYS_SIZE = 30;
- public int[] commentStops = new int[COMMENT_ARRAYS_SIZE];
- public int[] commentStarts = new int[COMMENT_ARRAYS_SIZE];
- public int[] commentTagStarts = new int[COMMENT_ARRAYS_SIZE];
- public int commentPtr = -1; // no comment test with commentPtr value -1
- protected int lastCommentLinePosition = -1;
-
- // task tag support
- public char[][] foundTaskTags = null;
- public char[][] foundTaskMessages;
- public char[][] foundTaskPriorities = null;
- public int[][] foundTaskPositions;
- public int foundTaskCount = 0;
- public char[][] taskTags = null;
- public char[][] taskPriorities = null;
- public boolean isTaskCaseSensitive = true;
-
- //diet parsing support - jump over some method body when requested
- public boolean diet = false;
-
- //support for the poor-line-debuggers ....
- //remember the position of the cr/lf
- public int[] lineEnds = new int[250];
- public int linePtr = -1;
- public boolean wasAcr = false;
-
- public static final String END_OF_SOURCE = "End_Of_Source"; //$NON-NLS-1$
-
- public static final String INVALID_HEXA = "Invalid_Hexa_Literal"; //$NON-NLS-1$
- public static final String INVALID_OCTAL = "Invalid_Octal_Literal"; //$NON-NLS-1$
- public static final String INVALID_CHARACTER_CONSTANT = "Invalid_Character_Constant"; //$NON-NLS-1$
- public static final String INVALID_ESCAPE = "Invalid_Escape"; //$NON-NLS-1$
- public static final String INVALID_INPUT = "Invalid_Input"; //$NON-NLS-1$
- public static final String INVALID_UNICODE_ESCAPE = "Invalid_Unicode_Escape"; //$NON-NLS-1$
- public static final String INVALID_FLOAT = "Invalid_Float_Literal"; //$NON-NLS-1$
- public static final String INVALID_LOW_SURROGATE = "Invalid_Low_Surrogate"; //$NON-NLS-1$
- public static final String INVALID_HIGH_SURROGATE = "Invalid_High_Surrogate"; //$NON-NLS-1$
-
- public static final String NULL_SOURCE_STRING = "Null_Source_String"; //$NON-NLS-1$
- public static final String UNTERMINATED_STRING = "Unterminated_String"; //$NON-NLS-1$
- public static final String UNTERMINATED_COMMENT = "Unterminated_Comment"; //$NON-NLS-1$
- public static final String INVALID_CHAR_IN_STRING = "Invalid_Char_In_String"; //$NON-NLS-1$
- public static final String INVALID_DIGIT = "Invalid_Digit"; //$NON-NLS-1$
- private static final int[] EMPTY_LINE_ENDS = Util.EMPTY_INT_ARRAY;
-
- //----------------optimized identifier managment------------------
- static final char[] charArray_a = new char[] {'a'},
- charArray_b = new char[] {'b'},
- charArray_c = new char[] {'c'},
- charArray_d = new char[] {'d'},
- charArray_e = new char[] {'e'},
- charArray_f = new char[] {'f'},
- charArray_g = new char[] {'g'},
- charArray_h = new char[] {'h'},
- charArray_i = new char[] {'i'},
- charArray_j = new char[] {'j'},
- charArray_k = new char[] {'k'},
- charArray_l = new char[] {'l'},
- charArray_m = new char[] {'m'},
- charArray_n = new char[] {'n'},
- charArray_o = new char[] {'o'},
- charArray_p = new char[] {'p'},
- charArray_q = new char[] {'q'},
- charArray_r = new char[] {'r'},
- charArray_s = new char[] {'s'},
- charArray_t = new char[] {'t'},
- charArray_u = new char[] {'u'},
- charArray_v = new char[] {'v'},
- charArray_w = new char[] {'w'},
- charArray_x = new char[] {'x'},
- charArray_y = new char[] {'y'},
- charArray_z = new char[] {'z'};
-
- static final char[] initCharArray =
- new char[] {'\u0000', '\u0000', '\u0000', '\u0000', '\u0000', '\u0000'};
- static final int TableSize = 30, InternalTableSize = 6; //30*6 =210 entries
-
- public static final int OptimizedLength = 7;
- public /*static*/ final char[][][][] charArray_length =
- new char[OptimizedLength][TableSize][InternalTableSize][];
- // support for detecting non-externalized string literals
- public static final char[] TAG_PREFIX= "//$NON-NLS-".toCharArray(); //$NON-NLS-1$
- public static final int TAG_PREFIX_LENGTH= TAG_PREFIX.length;
- public static final char TAG_POSTFIX= '$';
- public static final int TAG_POSTFIX_LENGTH= 1;
- private NLSTag[] nlsTags = null;
- protected int nlsTagsPtr;
- public boolean checkNonExternalizedStringLiterals;
-
- // generic support
- public boolean returnOnlyGreater = false;
-
- /*static*/ {
- for (int i = 0; i < 6; i++) {
- for (int j = 0; j < TableSize; j++) {
- for (int k = 0; k < InternalTableSize; k++) {
- this.charArray_length[i][j][k] = initCharArray;
- }
- }
- }
- }
- /*static*/ int newEntry2 = 0,
- newEntry3 = 0,
- newEntry4 = 0,
- newEntry5 = 0,
- newEntry6 = 0;
- public boolean insideRecovery = false;
-
- public int currentToken;
- public int currentNonWhitespaceToken;
- protected boolean pushedBack=false;
-
- public static final int RoundBracket = 0;
- public static final int SquareBracket = 1;
- public static final int CurlyBracket = 2;
- public static final int BracketKinds = 3;
-
- // extended unicode support
- public static final int LOW_SURROGATE_MIN_VALUE = 0xDC00;
- public static final int HIGH_SURROGATE_MIN_VALUE = 0xD800;
- public static final int HIGH_SURROGATE_MAX_VALUE = 0xDBFF;
- public static final int LOW_SURROGATE_MAX_VALUE = 0xDFFF;
-
-public Scanner() {
- this(false /*comment*/, false /*whitespace*/, false /*nls*/, ClassFileConstants.JDK1_3 /*sourceLevel*/, null/*taskTag*/, null/*taskPriorities*/, true /*taskCaseSensitive*/);
-}
-
-public Scanner(
- boolean tokenizeComments,
- boolean tokenizeWhiteSpace,
- boolean checkNonExternalizedStringLiterals,
- long sourceLevel,
- long complianceLevel,
- char[][] taskTags,
- char[][] taskPriorities,
- boolean isTaskCaseSensitive) {
-
- this.eofPosition = Integer.MAX_VALUE;
- this.tokenizeComments = tokenizeComments;
- this.tokenizeWhiteSpace = tokenizeWhiteSpace;
- this.sourceLevel = sourceLevel;
- this.complianceLevel = complianceLevel;
- this.checkNonExternalizedStringLiterals = checkNonExternalizedStringLiterals;
- this.taskTags = taskTags;
- this.taskPriorities = taskPriorities;
- this.isTaskCaseSensitive = isTaskCaseSensitive;
-}
-
-public Scanner(
- boolean tokenizeComments,
- boolean tokenizeWhiteSpace,
- boolean checkNonExternalizedStringLiterals,
- long sourceLevel,
- char[][] taskTags,
- char[][] taskPriorities,
- boolean isTaskCaseSensitive) {
-
- this(
- tokenizeComments,
- tokenizeWhiteSpace,
- checkNonExternalizedStringLiterals,
- sourceLevel,
- sourceLevel,
- taskTags,
- taskPriorities,
- isTaskCaseSensitive);
-}
-
-public final boolean atEnd() {
- // This code is not relevant if source is
- // Only a part of the real stream input
-
- return this.eofPosition <= this.currentPosition;
-}
-
-// chech presence of task: tags
-// TODO (frederic) see if we need to take unicode characters into account...
-public void checkTaskTag(int commentStart, int commentEnd) throws InvalidInputException {
- char[] src = this.source;
-
- // only look for newer task: tags
- if (this.foundTaskCount > 0
- && this.foundTaskPositions[this.foundTaskCount - 1][0] >= commentStart) {
- return;
- }
- int foundTaskIndex = this.foundTaskCount;
- char previous = src[commentStart+1]; // should be '*' or '/'
- for (
- int i = commentStart + 2; i < commentEnd && i < this.eofPosition; i++) {
- char[] tag = null;
- char[] priority = null;
- // check for tag occurrence only if not ambiguous with javadoc tag
- if (previous != '@') {
- nextTag : for (int itag = 0; itag < this.taskTags.length; itag++) {
- tag = this.taskTags[itag];
- int tagLength = tag.length;
- if (tagLength == 0) continue nextTag;
-
- // ensure tag is not leaded with letter if tag starts with a letter
- if (ScannerHelper.isJavaIdentifierStart(tag[0])) {
- if (ScannerHelper.isJavaIdentifierPart(previous)) {
- continue nextTag;
- }
- }
-
- for (int t = 0; t < tagLength; t++) {
- char sc, tc;
- int x = i+t;
- if (x >= this.eofPosition || x >= commentEnd) continue nextTag;
- if ((sc = src[i + t]) != (tc = tag[t])) { // case sensitive check
- if (this.isTaskCaseSensitive || (ScannerHelper.toLowerCase(sc) != ScannerHelper.toLowerCase(tc))) { // case insensitive check
- continue nextTag;
- }
- }
- }
- // ensure tag is not followed with letter if tag finishes with a letter
- if (i+tagLength < commentEnd && ScannerHelper.isJavaIdentifierPart(src[i+tagLength-1])) {
- if (ScannerHelper.isJavaIdentifierPart(src[i + tagLength]))
- continue nextTag;
- }
- if (this.foundTaskTags == null) {
- this.foundTaskTags = new char[5][];
- this.foundTaskMessages = new char[5][];
- this.foundTaskPriorities = new char[5][];
- this.foundTaskPositions = new int[5][];
- } else if (this.foundTaskCount == this.foundTaskTags.length) {
- System.arraycopy(this.foundTaskTags, 0, this.foundTaskTags = new char[this.foundTaskCount * 2][], 0, this.foundTaskCount);
- System.arraycopy(this.foundTaskMessages, 0, this.foundTaskMessages = new char[this.foundTaskCount * 2][], 0, this.foundTaskCount);
- System.arraycopy(this.foundTaskPriorities, 0, this.foundTaskPriorities = new char[this.foundTaskCount * 2][], 0, this.foundTaskCount);
- System.arraycopy(this.foundTaskPositions, 0, this.foundTaskPositions = new int[this.foundTaskCount * 2][], 0, this.foundTaskCount);
- }
-
- priority = this.taskPriorities != null && itag < this.taskPriorities.length
- ? this.taskPriorities[itag]
- : null;
-
- this.foundTaskTags[this.foundTaskCount] = tag;
- this.foundTaskPriorities[this.foundTaskCount] = priority;
- this.foundTaskPositions[this.foundTaskCount] = new int[] { i, i + tagLength - 1 };
- this.foundTaskMessages[this.foundTaskCount] = CharOperation.NO_CHAR;
- this.foundTaskCount++;
- i += tagLength - 1; // will be incremented when looping
- break nextTag;
- }
- }
- previous = src[i];
- }
- boolean containsEmptyTask = false;
- for (int i = foundTaskIndex; i < this.foundTaskCount; i++) {
- // retrieve message start and end positions
- int msgStart = this.foundTaskPositions[i][0] + this.foundTaskTags[i].length;
- int max_value = i + 1 < this.foundTaskCount
- ? this.foundTaskPositions[i + 1][0] - 1
- : commentEnd - 1;
- // at most beginning of next task
- if (max_value < msgStart) {
- max_value = msgStart; // would only occur if tag is before EOF.
- }
- int end = -1;
- char c;
- for (int j = msgStart; j < max_value; j++) {
- if ((c = src[j]) == '\n' || c == '\r') {
- end = j - 1;
- break;
- }
- }
- if (end == -1) {
- for (int j = max_value; j > msgStart; j--) {
- if ((c = src[j]) == '*') {
- end = j - 1;
- break;
- }
- }
- if (end == -1)
- end = max_value;
- }
- if (msgStart == end) {
- // if the description is empty, we might want to see if two tags are not sharing the same message
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=110797
- containsEmptyTask = true;
- continue;
- }
- // trim the message
- while (CharOperation.isWhitespace(src[end]) && msgStart <= end)
- end--;
- while (CharOperation.isWhitespace(src[msgStart]) && msgStart <= end)
- msgStart++;
- // update the end position of the task
- this.foundTaskPositions[i][1] = end;
- // get the message source
- final int messageLength = end - msgStart + 1;
- char[] message = new char[messageLength];
- System.arraycopy(src, msgStart, message, 0, messageLength);
- this.foundTaskMessages[i] = message;
- }
- if (containsEmptyTask) {
- for (int i = foundTaskIndex, max = this.foundTaskCount; i < max; i++) {
- if (this.foundTaskMessages[i].length == 0) {
- loop: for (int j = i + 1; j < max; j++) {
- if (this.foundTaskMessages[j].length != 0) {
- this.foundTaskMessages[i] = this.foundTaskMessages[j];
- this.foundTaskPositions[i][1] = this.foundTaskPositions[j][1];
- break loop;
- }
- }
- }
- }
- }
-}
-
-public char[] getCurrentIdentifierSource() {
- //return the token REAL source (aka unicodes are precomputed)
-
- char[] result;
- if (this.withoutUnicodePtr != 0) {
- //0 is used as a fast test flag so the real first char is in position 1
- System.arraycopy(
- this.withoutUnicodeBuffer,
- 1,
- result = new char[this.withoutUnicodePtr],
- 0,
- this.withoutUnicodePtr);
- } else {
- int length = this.currentPosition - this.startPosition;
- if (length == this.eofPosition) return this.source;
- switch (length) { // see OptimizedLength
- case 1 :
- return optimizedCurrentTokenSource1();
- case 2 :
- return optimizedCurrentTokenSource2();
- case 3 :
- return optimizedCurrentTokenSource3();
- case 4 :
- return optimizedCurrentTokenSource4();
- case 5 :
- return optimizedCurrentTokenSource5();
- case 6 :
- return optimizedCurrentTokenSource6();
- }
- //no optimization
- System.arraycopy(this.source, this.startPosition, result = new char[length], 0, length);
- }
- //newIdentCount++;
- return result;
-}
-public int getCurrentTokenEndPosition(){
- return this.currentPosition - 1;
-}
-public char[] getCurrentTokenSource() {
- // Return the token REAL source (aka unicodes are precomputed)
-
- char[] result;
- if (this.withoutUnicodePtr != 0) {
- // 0 is used as a fast test flag so the real first char is in position 1
- System.arraycopy(
- this.withoutUnicodeBuffer,
- 1,
- result = new char[this.withoutUnicodePtr],
- 0,
- this.withoutUnicodePtr);
- } else {
- int length;
- System.arraycopy(
- this.source,
- this.startPosition,
- result = new char[length = this.currentPosition - this.startPosition],
- 0,
- length);
- }
- return result;
-}
-public final String getCurrentTokenString() {
- // Return current token as a string
-
- if (this.withoutUnicodePtr != 0) {
- // 0 is used as a fast test flag so the real first char is in position 1
- return new String(
- this.withoutUnicodeBuffer,
- 1,
- this.withoutUnicodePtr);
- }
- return new String(
- this.source,
- this.startPosition,
- this.currentPosition - this.startPosition);
-}
-public char[] getCurrentTokenSourceString() {
- //return the token REAL source (aka unicodes are precomputed).
- //REMOVE the two " that are at the beginning and the end.
-
- char[] result;
- if (this.withoutUnicodePtr != 0)
- //0 is used as a fast test flag so the real first char is in position 1
- System.arraycopy(this.withoutUnicodeBuffer, 2,
- //2 is 1 (real start) + 1 (to jump over the ")
- result = new char[this.withoutUnicodePtr - 2], 0, this.withoutUnicodePtr - 2);
- else {
- int length;
- System.arraycopy(
- this.source,
- this.startPosition + 1,
- result = new char[length = this.currentPosition - this.startPosition - 2],
- 0,
- length);
- }
- return result;
-}
-public final String getCurrentStringLiteral() {
- //return the token REAL source (aka unicodes are precomputed).
- //REMOVE the two " that are at the beginning and the end.
-
- if (this.withoutUnicodePtr != 0)
- //0 is used as a fast test flag so the real first char is in position 1
- //2 is 1 (real start) + 1 (to jump over the ")
- return new String(this.withoutUnicodeBuffer, 2, this.withoutUnicodePtr - 2);
- else {
- return new String(this.source, this.startPosition + 1, this.currentPosition - this.startPosition - 2);
- }
-}
-public final char[] getRawTokenSource() {
- int length = this.currentPosition - this.startPosition;
- char[] tokenSource = new char[length];
- System.arraycopy(this.source, this.startPosition, tokenSource, 0, length);
- return tokenSource;
-}
-
-public final char[] getRawTokenSourceEnd() {
- int length = this.eofPosition - this.currentPosition - 1;
- char[] sourceEnd = new char[length];
- System.arraycopy(this.source, this.currentPosition, sourceEnd, 0, length);
- return sourceEnd;
-}
-
-public int getCurrentTokenStartPosition(){
- return this.startPosition;
-}
-/*
- * Search the source position corresponding to the end of a given line number
- *
- * Line numbers are 1-based, and relative to the scanner initialPosition.
- * Character positions are 0-based.
- *
- * In case the given line number is inconsistent, answers -1.
- */
-public final int getLineEnd(int lineNumber) {
-
- if (this.lineEnds == null || this.linePtr == -1)
- return -1;
- if (lineNumber > this.lineEnds.length+1)
- return -1;
- if (lineNumber <= 0)
- return -1;
- if (lineNumber == this.lineEnds.length + 1)
- return this.eofPosition;
- return this.lineEnds[lineNumber-1]; // next line start one character behind the lineEnd of the previous line
-}
-
-public final int[] getLineEnds() {
- //return a bounded copy of this.lineEnds
- if (this.linePtr == -1) {
- return EMPTY_LINE_ENDS;
- }
- int[] copy;
- System.arraycopy(this.lineEnds, 0, copy = new int[this.linePtr + 1], 0, this.linePtr + 1);
- return copy;
-}
-
-/**
- * Search the source position corresponding to the beginning of a given line number
- *
- * Line numbers are 1-based, and relative to the scanner initialPosition.
- * Character positions are 0-based.
- *
- * e.g. getLineStart(1) --> 0 indicates that the first line starts at character 0.
- *
- * In case the given line number is inconsistent, answers -1.
- *
- * @param lineNumber int
- * @return int
- */
-public final int getLineStart(int lineNumber) {
-
- if (this.lineEnds == null || this.linePtr == -1)
- return -1;
- if (lineNumber > this.lineEnds.length + 1)
- return -1;
- if (lineNumber <= 0)
- return -1;
-
- if (lineNumber == 1)
- return this.initialPosition;
- return this.lineEnds[lineNumber-2]+1; // next line start one character behind the lineEnd of the previous line
-}
-public final int getNextChar() {
- try {
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- } else {
- this.unicodeAsBackSlash = false;
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
- return this.currentCharacter;
- } catch (IndexOutOfBoundsException e) {
- return -1;
- } catch(InvalidInputException e) {
- return -1;
- }
-}
-public final int getNextCharWithBoundChecks() {
- if (this.currentPosition >= this.eofPosition) {
- return -1;
- }
- this.currentCharacter = this.source[this.currentPosition++];
- if (this.currentPosition >= this.eofPosition) {
- this.unicodeAsBackSlash = false;
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- return this.currentCharacter;
- }
- if (this.currentCharacter == '\\' && this.source[this.currentPosition] == 'u') {
- try {
- getNextUnicodeChar();
- } catch (InvalidInputException e) {
- return -1;
- }
- } else {
- this.unicodeAsBackSlash = false;
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
- return this.currentCharacter;
-}
-
-public final boolean getNextChar(char testedChar) {
- //BOOLEAN
- //handle the case of unicode.
- //when a unicode appears then we must use a buffer that holds char internal values
- //At the end of this method currentCharacter holds the new visited char
- //and currentPosition points right next after it
- //Both previous lines are true if the currentCharacter is == to the testedChar
- //On false, no side effect has occured.
-
- //ALL getNextChar.... ARE OPTIMIZED COPIES
-
- if (this.currentPosition >= this.eofPosition) { // handle the obvious case upfront
- this.unicodeAsBackSlash = false;
- return false;
- }
-
- int temp = this.currentPosition;
- try {
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- if (this.currentCharacter != testedChar) {
- this.currentPosition = temp;
- this.withoutUnicodePtr--;
- return false;
- }
- return true;
- } //-------------end unicode traitement--------------
- else {
- if (this.currentCharacter != testedChar) {
- this.currentPosition = temp;
- return false;
- }
- this.unicodeAsBackSlash = false;
- if (this.withoutUnicodePtr != 0)
- unicodeStore();
- return true;
- }
- } catch (IndexOutOfBoundsException e) {
- this.unicodeAsBackSlash = false;
- this.currentPosition = temp;
- return false;
- } catch(InvalidInputException e) {
- this.unicodeAsBackSlash = false;
- this.currentPosition = temp;
- return false;
- }
-}
-public final int getNextChar(char testedChar1, char testedChar2) {
- //INT 0 : testChar1 \\\\///\\\\ 1 : testedChar2 \\\\///\\\\ -1 : others
- //test can be done with (x==0) for the first and (x>0) for the second
- //handle the case of unicode.
- //when a unicode appears then we must use a buffer that holds char internal values
- //At the end of this method currentCharacter holds the new visited char
- //and currentPosition points right next after it
- //Both previous lines are true if the currentCharacter is == to the testedChar1/2
- //On false, no side effect has occured.
-
- //ALL getNextChar.... ARE OPTIMIZED COPIES
- if (this.currentPosition >= this.eofPosition) // handle the obvious case upfront
- return -1;
-
- int temp = this.currentPosition;
- try {
- int result;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- if (this.currentCharacter == testedChar1) {
- result = 0;
- } else if (this.currentCharacter == testedChar2) {
- result = 1;
- } else {
- this.currentPosition = temp;
- this.withoutUnicodePtr--;
- result = -1;
- }
- return result;
- } else {
- if (this.currentCharacter == testedChar1) {
- result = 0;
- } else if (this.currentCharacter == testedChar2) {
- result = 1;
- } else {
- this.currentPosition = temp;
- return -1;
- }
-
- if (this.withoutUnicodePtr != 0)
- unicodeStore();
- return result;
- }
- } catch (IndexOutOfBoundsException e) {
- this.currentPosition = temp;
- return -1;
- } catch(InvalidInputException e) {
- this.currentPosition = temp;
- return -1;
- }
-}
-public final boolean getNextCharAsDigit() throws InvalidInputException {
- //BOOLEAN
- //handle the case of unicode.
- //when a unicode appears then we must use a buffer that holds char internal values
- //At the end of this method currentCharacter holds the new visited char
- //and currentPosition points right next after it
- //Both previous lines are true if the currentCharacter is a digit
- //On false, no side effect has occured.
-
- //ALL getNextChar.... ARE OPTIMIZED COPIES
- if (this.currentPosition >= this.eofPosition) // handle the obvious case upfront
- return false;
-
- int temp = this.currentPosition;
- try {
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- if (!ScannerHelper.isDigit(this.currentCharacter)) {
- this.currentPosition = temp;
- this.withoutUnicodePtr--;
- return false;
- }
- return true;
- } else {
- if (!ScannerHelper.isDigit(this.currentCharacter)) {
- this.currentPosition = temp;
- return false;
- }
- if (this.withoutUnicodePtr != 0)
- unicodeStore();
- return true;
- }
- } catch (IndexOutOfBoundsException e) {
- this.currentPosition = temp;
- return false;
- } catch(InvalidInputException e) {
- this.currentPosition = temp;
- return false;
- }
-}
-public final boolean getNextCharAsDigit(int radix) {
- //BOOLEAN
- //handle the case of unicode.
- //when a unicode appears then we must use a buffer that holds char internal values
- //At the end of this method currentCharacter holds the new visited char
- //and currentPosition points right next after it
- //Both previous lines are true if the currentCharacter is a digit base on radix
- //On false, no side effect has occured.
-
- //ALL getNextChar.... ARE OPTIMIZED COPIES
- if (this.currentPosition >= this.eofPosition) // handle the obvious case upfront
- return false;
-
- int temp = this.currentPosition;
- try {
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- if (ScannerHelper.digit(this.currentCharacter, radix) == -1) {
- this.currentPosition = temp;
- this.withoutUnicodePtr--;
- return false;
- }
- return true;
- } else {
- if (ScannerHelper.digit(this.currentCharacter, radix) == -1) {
- this.currentPosition = temp;
- return false;
- }
- if (this.withoutUnicodePtr != 0)
- unicodeStore();
- return true;
- }
- } catch (IndexOutOfBoundsException e) {
- this.currentPosition = temp;
- return false;
- } catch(InvalidInputException e) {
- this.currentPosition = temp;
- return false;
- }
-}
-public boolean getNextCharAsJavaIdentifierPartWithBoundCheck() {
- //BOOLEAN
- //handle the case of unicode.
- //when a unicode appears then we must use a buffer that holds char internal values
- //At the end of this method currentCharacter holds the new visited char
- //and currentPosition points right next after it
- //Both previous lines are true if the currentCharacter is a JavaIdentifierPart
- //On false, no side effect has occured.
-
- //ALL getNextChar.... ARE OPTIMIZED COPIES
- int pos = this.currentPosition;
- if (pos >= this.eofPosition) // handle the obvious case upfront
- return false;
-
- int temp2 = this.withoutUnicodePtr;
- try {
- boolean unicode = false;
- this.currentCharacter = this.source[this.currentPosition++];
- if (this.currentPosition < this.eofPosition) {
- if (this.currentCharacter == '\\' && this.source[this.currentPosition] == 'u') {
- getNextUnicodeChar();
- unicode = true;
- }
- }
- char c = this.currentCharacter;
- boolean isJavaIdentifierPart = false;
- if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) {
- if (this.complianceLevel < ClassFileConstants.JDK1_5) {
- this.currentPosition = pos;
- this.withoutUnicodePtr = temp2;
- return false;
- }
- // Unicode 4 detection
- char low = (char) getNextCharWithBoundChecks();
- if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) {
- // illegal low surrogate
- this.currentPosition = pos;
- this.withoutUnicodePtr = temp2;
- return false;
- }
- isJavaIdentifierPart = ScannerHelper.isJavaIdentifierPart(c, low);
- }
- else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) {
- this.currentPosition = pos;
- this.withoutUnicodePtr = temp2;
- return false;
- } else {
- isJavaIdentifierPart = ScannerHelper.isJavaIdentifierPart(c);
- }
- if (unicode) {
- if (!isJavaIdentifierPart) {
- this.currentPosition = pos;
- this.withoutUnicodePtr = temp2;
- return false;
- }
- return true;
- } else {
- if (!isJavaIdentifierPart) {
- this.currentPosition = pos;
- return false;
- }
-
- if (this.withoutUnicodePtr != 0)
- unicodeStore();
- return true;
- }
- } catch(InvalidInputException e) {
- this.currentPosition = pos;
- this.withoutUnicodePtr = temp2;
- return false;
- }
-}
-
-public boolean getNextCharAsJavaIdentifierPart() {
- //BOOLEAN
- //handle the case of unicode.
- //when a unicode appears then we must use a buffer that holds char internal values
- //At the end of this method currentCharacter holds the new visited char
- //and currentPosition points right next after it
- //Both previous lines are true if the currentCharacter is a JavaIdentifierPart
- //On false, no side effect has occured.
-
- //ALL getNextChar.... ARE OPTIMIZED COPIES
- int pos;
- if ((pos = this.currentPosition) >= this.eofPosition) // handle the obvious case upfront
- return false;
-
- int temp2 = this.withoutUnicodePtr;
- try {
- boolean unicode = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- unicode = true;
- }
- char c = this.currentCharacter;
- boolean isJavaIdentifierPart = false;
- if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) {
- if (this.complianceLevel < ClassFileConstants.JDK1_5) {
- this.currentPosition = pos;
- this.withoutUnicodePtr = temp2;
- return false;
- }
- // Unicode 4 detection
- char low = (char) getNextChar();
- if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) {
- // illegal low surrogate
- this.currentPosition = pos;
- this.withoutUnicodePtr = temp2;
- return false;
- }
- isJavaIdentifierPart = ScannerHelper.isJavaIdentifierPart(c, low);
- }
- else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) {
- this.currentPosition = pos;
- this.withoutUnicodePtr = temp2;
- return false;
- } else {
- isJavaIdentifierPart = ScannerHelper.isJavaIdentifierPart(c);
- }
- if (unicode) {
- if (!isJavaIdentifierPart) {
- this.currentPosition = pos;
- this.withoutUnicodePtr = temp2;
- return false;
- }
- return true;
- } else {
- if (!isJavaIdentifierPart) {
- this.currentPosition = pos;
- return false;
- }
-
- if (this.withoutUnicodePtr != 0)
- unicodeStore();
- return true;
- }
- } catch (IndexOutOfBoundsException e) {
- this.currentPosition = pos;
- this.withoutUnicodePtr = temp2;
- return false;
- } catch(InvalidInputException e) {
- this.currentPosition = pos;
- this.withoutUnicodePtr = temp2;
- return false;
- }
-}
-
-/*
- * External API in JavaScriptConventions.
- * This is used to optimize the case where the scanner is used to scan a single identifier.
- * In this case, the AIOOBE is slower to handle than a bound check
- */
-public int scanIdentifier() throws InvalidInputException {
- int whiteStart = 0;
- while (true) { //loop for jumping over comments
- this.withoutUnicodePtr = 0;
- //start with a new token (even comment written with unicode )
- // ---------Consume white space and handles startPosition---------
- whiteStart = this.currentPosition;
- boolean isWhiteSpace, hasWhiteSpaces = false;
- int offset;
- int unicodePtr;
- boolean checkIfUnicode = false;
- do {
- unicodePtr = this.withoutUnicodePtr;
- offset = this.currentPosition;
- this.startPosition = this.currentPosition;
- if (this.currentPosition < this.eofPosition) {
- this.currentCharacter = this.source[this.currentPosition++];
- checkIfUnicode = this.currentPosition < this.eofPosition
- && this.currentCharacter == '\\'
- && this.source[this.currentPosition] == 'u';
- } else if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) {
- // reposition scanner in case we are interested by spaces as tokens
- this.currentPosition--;
- this.startPosition = whiteStart;
- return TokenNameWHITESPACE;
- } else {
- return TokenNameEOF;
- }
- if (checkIfUnicode) {
- isWhiteSpace = jumpOverUnicodeWhiteSpace();
- offset = this.currentPosition - offset;
- } else {
- offset = this.currentPosition - offset;
- // inline version of:
- //isWhiteSpace =
- // (this.currentCharacter == ' ') || ScannerHelper.isWhitespace(this.currentCharacter);
- switch (this.currentCharacter) {
- case 10 : /* \ u000a: LINE FEED */
- case 12 : /* \ u000c: FORM FEED */
- case 13 : /* \ u000d: CARRIAGE RETURN */
- case 32 : /* \ u0020: SPACE */
- case 9 : /* \ u0009: HORIZONTAL TABULATION */
- isWhiteSpace = true;
- break;
- default :
- isWhiteSpace = false;
- }
- }
- if (isWhiteSpace) {
- hasWhiteSpaces = true;
- }
- } while (isWhiteSpace);
- if (hasWhiteSpaces) {
- if (this.tokenizeWhiteSpace) {
- // reposition scanner in case we are interested by spaces as tokens
- this.currentPosition-=offset;
- this.startPosition = whiteStart;
- if (checkIfUnicode) {
- this.withoutUnicodePtr = unicodePtr;
- }
- return TokenNameWHITESPACE;
- } else if (checkIfUnicode) {
- this.withoutUnicodePtr = 0;
- unicodeStore();
- } else {
- this.withoutUnicodePtr = 0;
- }
- }
- char c = this.currentCharacter;
- if (c < ScannerHelper.MAX_OBVIOUS) {
- if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) {
- return scanIdentifierOrKeywordWithBoundCheck();
- }
- return TokenNameERROR;
- }
- boolean isJavaIdStart;
- if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) {
- if (this.complianceLevel < ClassFileConstants.JDK1_5) {
- throw new InvalidInputException(INVALID_UNICODE_ESCAPE);
- }
- // Unicode 4 detection
- char low = (char) getNextCharWithBoundChecks();
- if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) {
- // illegal low surrogate
- throw new InvalidInputException(INVALID_LOW_SURROGATE);
- }
- isJavaIdStart = ScannerHelper.isJavaIdentifierStart(c, low);
- } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) {
- if (this.complianceLevel < ClassFileConstants.JDK1_5) {
- throw new InvalidInputException(INVALID_UNICODE_ESCAPE);
- }
- throw new InvalidInputException(INVALID_HIGH_SURROGATE);
- } else {
- // optimized case already checked
- isJavaIdStart = Character.isJavaIdentifierStart(c);
- }
- if (isJavaIdStart)
- return scanIdentifierOrKeywordWithBoundCheck();
- return TokenNameERROR;
- }
-}
-
-
-public int getNextToken() throws InvalidInputException {
- if ( pushedBack ) {
- pushedBack = false;
- return currentToken;
- }
-// int previousToken = this.currentToken;
- int previousTokenNonWS = this.currentNonWhitespaceToken;
- this.wasAcr = false;
- if (this.diet) {
- jumpOverMethodBody();
- this.diet = false;
- currentToken=this.currentPosition > this.eofPosition ? TokenNameEOF : TokenNameRBRACE;
- return currentToken;
- }
- int whiteStart = 0;
- try {
- while (true) { //loop for jumping over comments
- this.withoutUnicodePtr = 0;
- //start with a new token (even comment written with unicode )
-
- // ---------Consume white space and handles startPosition---------
- whiteStart = this.currentPosition;
- boolean isWhiteSpace, hasWhiteSpaces = false;
- int offset;
- int unicodePtr;
- boolean checkIfUnicode = false;
- do {
- unicodePtr = this.withoutUnicodePtr;
- offset = this.currentPosition;
- this.startPosition = this.currentPosition;
- try {
- checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u');
- } catch(IndexOutOfBoundsException e) {
- if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) {
- // reposition scanner in case we are interested by spaces as tokens
- this.currentPosition--;
- this.startPosition = whiteStart;
- currentToken=TokenNameWHITESPACE;
- return currentToken;
- }
- if (this.currentPosition > this.eofPosition)
- {
- currentToken=TokenNameEOF;
- return currentToken;
- }
- }
- if (this.currentPosition > this.eofPosition)
- {
- currentToken=TokenNameEOF;
- return currentToken;
- }
- if (checkIfUnicode) {
- isWhiteSpace = jumpOverUnicodeWhiteSpace();
- offset = this.currentPosition - offset;
- } else {
- offset = this.currentPosition - offset;
- if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) {
- if (this.recordLineSeparator) {
- pushLineSeparator();
- }
- // automatically insert semicolon if return followed by newline
- if (this.currentNonWhitespaceToken==TokenNamereturn)
- return TokenNameSEMICOLON;
- }
- // inline version of:
- //isWhiteSpace =
- // (this.currentCharacter == ' ') || ScannerHelper.isWhitespace(this.currentCharacter);
- switch (this.currentCharacter) {
- case 10 : /* \ u000a: LINE FEED */
- case 12 : /* \ u000c: FORM FEED */
- case 13 : /* \ u000d: CARRIAGE RETURN */
- case 32 : /* \ u0020: SPACE */
- case 9 : /* \ u0009: HORIZONTAL TABULATION */
- isWhiteSpace = true;
- break;
- default :
- isWhiteSpace = false;
- }
- }
- if (isWhiteSpace) {
- hasWhiteSpaces = true;
- }
- } while (isWhiteSpace);
- if (hasWhiteSpaces) {
- if (this.tokenizeWhiteSpace) {
- // reposition scanner in case we are interested by spaces as tokens
- this.currentPosition-=offset;
- this.startPosition = whiteStart;
- if (checkIfUnicode) {
- this.withoutUnicodePtr = unicodePtr;
- }
- currentToken=TokenNameWHITESPACE;
- return currentToken;
- } else if (checkIfUnicode) {
- this.withoutUnicodePtr = 0;
- unicodeStore();
- } else {
- this.withoutUnicodePtr = 0;
- }
- }
- // ---------Identify the next token-------------
- switch (this.currentCharacter) {
- case '(' :
- currentToken=currentNonWhitespaceToken=TokenNameLPAREN;
- return currentToken;
- case ')' :
- currentToken=currentNonWhitespaceToken=TokenNameRPAREN;
- return currentToken;
- case '{' :
- currentToken=currentNonWhitespaceToken=TokenNameLBRACE;
- return currentToken;
- case '}' :
- currentToken=currentNonWhitespaceToken=TokenNameRBRACE;
- return currentToken;
- case '[' :
- currentToken=currentNonWhitespaceToken=TokenNameLBRACKET;
- return currentToken;
- case ']' :
- currentToken=currentNonWhitespaceToken=TokenNameRBRACKET;
- return currentToken;
- case ';' :
- currentToken=currentNonWhitespaceToken=TokenNameSEMICOLON;
- return currentToken;
- case ',' :
- currentToken=currentNonWhitespaceToken=TokenNameCOMMA;
- return currentToken;
- case '.' :
- if (getNextCharAsDigit()) {
- currentToken=currentNonWhitespaceToken=scanNumber(true);
- return currentToken;
- }
- currentToken=currentNonWhitespaceToken=TokenNameDOT;
- return currentToken;
-
- case '+' :
- {
- int test;
- if ((test = getNextChar('+', '=')) == 0)
- {
- currentToken=currentNonWhitespaceToken=TokenNamePLUS_PLUS;
- return currentToken;
- }
- if (test > 0)
- {
- currentToken=currentNonWhitespaceToken=TokenNamePLUS_EQUAL;
- return currentToken;
- }
- currentToken=currentNonWhitespaceToken=TokenNamePLUS;
- return currentToken;
- }
- case '-' :
- {
- int test;
- if ((test = getNextChar('-', '=')) == 0)
- {
- currentToken=currentNonWhitespaceToken=TokenNameMINUS_MINUS;
- return currentToken;
- }
- if (test > 0)
- {
- currentToken=currentNonWhitespaceToken=TokenNameMINUS_EQUAL;
- return currentToken;
- }
- currentToken=currentNonWhitespaceToken=TokenNameMINUS;
- return currentToken;
- }
- case '~' :
- currentToken=currentNonWhitespaceToken=TokenNameTWIDDLE;
- return currentToken;
- case '!' :
- if (getNextChar('='))
- {
- if (getNextChar('='))
- {
- currentToken=currentNonWhitespaceToken=TokenNameNOT_EQUAL_EQUAL;
- return currentToken;
- }
- currentToken=currentNonWhitespaceToken=TokenNameNOT_EQUAL;
- return currentToken;
- }
- currentToken=currentNonWhitespaceToken=TokenNameNOT;
- return currentToken;
- case '*' :
- if (getNextChar('='))
- {
- currentToken=currentNonWhitespaceToken=TokenNameMULTIPLY_EQUAL;
- return currentToken;
- }
- currentToken=currentNonWhitespaceToken=TokenNameMULTIPLY;
- return currentToken;
- case '%' :
- if (getNextChar('='))
- {
- currentToken=currentNonWhitespaceToken=TokenNameREMAINDER_EQUAL;
- return currentToken;
- }
- currentToken=currentNonWhitespaceToken=TokenNameREMAINDER;
- return currentToken;
- case '<' :
- {
- int test;
- if ((test = getNextChar('=', '<')) == 0)
- {
- currentToken=currentNonWhitespaceToken=TokenNameLESS_EQUAL;
- return currentToken;
- }
- if (test > 0) {
- if (getNextChar('='))
- {
- currentToken=currentNonWhitespaceToken=TokenNameLEFT_SHIFT_EQUAL;
- return currentToken;
- }
- currentToken=currentNonWhitespaceToken=TokenNameLEFT_SHIFT;
- return currentToken;
- }
- currentToken=currentNonWhitespaceToken=TokenNameLESS;
- return currentToken;
- }
- case '>' :
- {
- int test;
- if (this.returnOnlyGreater) {
- currentToken=currentNonWhitespaceToken=TokenNameGREATER;
- return currentToken;
- }
- if ((test = getNextChar('=', '>')) == 0)
- {
- currentToken=currentNonWhitespaceToken=TokenNameGREATER_EQUAL;
- return currentToken;
- }
- if (test > 0) {
- if ((test = getNextChar('=', '>')) == 0)
- {
- currentToken=currentNonWhitespaceToken=TokenNameRIGHT_SHIFT_EQUAL;
- return currentToken;
- }
- if (test > 0) {
- if (getNextChar('='))
- {
- currentToken=currentNonWhitespaceToken=TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL;
- return currentToken;
- }
- currentToken=currentNonWhitespaceToken=TokenNameUNSIGNED_RIGHT_SHIFT;
- return currentToken;
- }
- currentToken=currentNonWhitespaceToken=TokenNameRIGHT_SHIFT;
- return currentToken;
- }
- currentToken=currentNonWhitespaceToken=TokenNameGREATER;
- return currentToken;
- }
- case '=' :
- if (getNextChar('='))
- {
- if (getNextChar('='))
- {
- currentToken=currentNonWhitespaceToken=TokenNameEQUAL_EQUAL_EQUAL;
- return currentToken;
- }
- currentToken=currentNonWhitespaceToken=TokenNameEQUAL_EQUAL;
- return currentToken;
- }
- currentToken=currentNonWhitespaceToken=TokenNameEQUAL;
- return currentToken;
- case '&' :
- {
- int test;
- if ((test = getNextChar('&', '=')) == 0)
- {
- currentToken=currentNonWhitespaceToken=TokenNameAND_AND;
- return currentToken;
- }
- if (test > 0)
- {
- currentToken=currentNonWhitespaceToken=TokenNameAND_EQUAL;
- return currentToken;
- }
- currentToken=currentNonWhitespaceToken=TokenNameAND;
- return currentToken;
- }
- case '|' :
- {
- int test;
- if ((test = getNextChar('|', '=')) == 0)
- {
- currentToken=currentNonWhitespaceToken=TokenNameOR_OR;
- return currentToken;
- }
- if (test > 0)
- {
- currentToken=currentNonWhitespaceToken=TokenNameOR_EQUAL;
- return currentToken;
- }
- currentToken=currentNonWhitespaceToken=TokenNameOR;
- return currentToken;
- }
- case '^' :
- if (getNextChar('='))
- {
- currentToken=currentNonWhitespaceToken=TokenNameXOR_EQUAL;
- return currentToken;
- }
- currentToken=currentNonWhitespaceToken=TokenNameXOR;
- return currentToken;
- case '?' :
- currentToken=currentNonWhitespaceToken=TokenNameQUESTION;
- return currentToken;
- case ':' :
- currentToken=currentNonWhitespaceToken=TokenNameCOLON;
- return currentToken;
-/* case '\'' :
- {
- int test;
- if ((test = getNextChar('\n', '\r')) == 0) {
- throw new InvalidInputException(INVALID_CHARACTER_CONSTANT);
- }
- if (test > 0) {
- // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed
- for (int lookAhead = 0; lookAhead < 3; lookAhead++) {
- if (this.currentPosition + lookAhead == this.eofPosition)
- break;
- if (this.source[this.currentPosition + lookAhead] == '\n')
- break;
- if (this.source[this.currentPosition + lookAhead] == '\'') {
- this.currentPosition += lookAhead + 1;
- break;
- }
- }
- throw new InvalidInputException(INVALID_CHARACTER_CONSTANT);
- }
- }
- if (getNextChar('\'')) {
- // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed
- for (int lookAhead = 0; lookAhead < 3; lookAhead++) {
- if (this.currentPosition + lookAhead == this.eofPosition)
- break;
- if (this.source[this.currentPosition + lookAhead] == '\n')
- break;
- if (this.source[this.currentPosition + lookAhead] == '\'') {
- this.currentPosition += lookAhead + 1;
- break;
- }
- }
- throw new InvalidInputException(INVALID_CHARACTER_CONSTANT);
- }
- if (getNextChar('\\')) {
- if (this.unicodeAsBackSlash) {
- // consume next character
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- } else {
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
- } else {
- this.currentCharacter = this.source[this.currentPosition++];
- }
- scanEscapeCharacter();
- } else { // consume next character
- this.unicodeAsBackSlash = false;
- checkIfUnicode = false;
- try {
- checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u');
- } catch(IndexOutOfBoundsException e) {
- this.currentPosition--;
- throw new InvalidInputException(INVALID_CHARACTER_CONSTANT);
- }
- if (checkIfUnicode) {
- getNextUnicodeChar();
- } else {
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
- }
- if (getNextChar('\''))
- {
- currentToken=TokenNameCharacterLiteral;
- return currentToken;
- }
- // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed
- for (int lookAhead = 0; lookAhead < 20; lookAhead++) {
- if (this.currentPosition + lookAhead == this.eofPosition)
- break;
- if (this.source[this.currentPosition + lookAhead] == '\n')
- break;
- if (this.source[this.currentPosition + lookAhead] == '\'') {
- this.currentPosition += lookAhead + 1;
- break;
- }
- }
- throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); */
- case '\'':
- case '"' :
- char character = this.currentCharacter;
- try {
- // consume next character
- this.unicodeAsBackSlash = false;
- boolean isUnicode = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- isUnicode = true;
- } else {
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
-
- while ((this.currentCharacter != character) || ((this.currentCharacter == character) && (isUnicode == true))) {
- if ((this.currentCharacter == '\n' && !isUnicode) || (this.currentCharacter == '\r' && !isUnicode)) {
- this.currentPosition--; // set current position on new line character
- throw new InvalidInputException(INVALID_CHAR_IN_STRING);
- }
- if (this.currentCharacter == '\\') {
- if (this.unicodeAsBackSlash) {
- this.withoutUnicodePtr--;
- // consume next character
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- isUnicode = true;
- this.withoutUnicodePtr--;
- } else {
- isUnicode = false;
- }
- } else {
- if (this.withoutUnicodePtr == 0) {
- unicodeInitializeBuffer(this.currentPosition - this.startPosition);
- }
- this.withoutUnicodePtr --;
- this.currentCharacter = this.source[this.currentPosition++];
- }
- // we need to compute the escape character in a separate buffer
- if (scanEscapeCharacter() && this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
- // consume next character
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- isUnicode = true;
- } else {
- isUnicode = false;
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
-
- }
- } catch (IndexOutOfBoundsException e) {
- this.currentPosition--;
- throw new InvalidInputException(UNTERMINATED_STRING);
- } catch (InvalidInputException e) {
- if (e.getMessage().equals(INVALID_ESCAPE)) {
- // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed
- for (int lookAhead = 0; lookAhead < 50; lookAhead++) {
- if (this.currentPosition + lookAhead == this.eofPosition)
- break;
- if (this.source[this.currentPosition + lookAhead] == '\n')
- break;
- if (this.source[this.currentPosition + lookAhead] == character) {
- this.currentPosition += lookAhead + 1;
- break;
- }
- }
-
- }
- throw e; // rethrow
- }
- if (character == '\''){
- currentToken=currentNonWhitespaceToken=TokenNameCharacterLiteral;
- } else {
- currentToken=currentNonWhitespaceToken=TokenNameStringLiteral;
- }
- return currentToken;
- case '/' :
- {
- int test;
- if ((test = getNextChar('/', '*')) == 0) { //line comment
- this.lastCommentLinePosition = this.currentPosition;
- try { //get the next char
-
- this.currentCharacter = this.source[this.currentPosition++];
- // Don't process unicode characters in JavaScript comments
-/* if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- }
-
- //handle the \\u case manually into comment
- if (this.currentCharacter == '\\') {
- if (this.source[this.currentPosition] == '\\')
- this.currentPosition++;
- } //jump over the \\
- boolean isUnicode = false; */
- while (this.currentCharacter != '\r' && this.currentCharacter != '\n') {
- this.lastCommentLinePosition = this.currentPosition;
- //get the next char
- this.currentCharacter = this.source[this.currentPosition++];
- // Don't process unicode characters in JavaScript comments
-/* isUnicode = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- isUnicode = true;
- }
- //handle the \\u case manually into comment
- if (this.currentCharacter == '\\') {
- if (this.source[this.currentPosition] == '\\')
- this.currentPosition++;
- } //jump over the \\ */
- }
- /*
- * We need to completely consume the line break
- */
- boolean isUnicode = false;
- if (this.currentCharacter == '\r'
- && this.eofPosition > this.currentPosition) {
- if (this.source[this.currentPosition] == '\n') {
- this.currentPosition++;
- this.currentCharacter = '\n';
- } else if ((this.source[this.currentPosition] == '\\')
- && (this.source[this.currentPosition + 1] == 'u')) {
- getNextUnicodeChar();
- isUnicode = true;
- }
- }
- recordComment(TokenNameCOMMENT_LINE);
- if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition);
- if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) {
- if (this.checkNonExternalizedStringLiterals) {
- parseTags();
- }
- if (this.recordLineSeparator) {
- if (isUnicode) {
- pushUnicodeLineSeparator();
- } else {
- pushLineSeparator();
- }
- }
- }
- if (this.tokenizeComments) {
- currentToken=TokenNameCOMMENT_LINE;
- return currentToken;
- }
- } catch (IndexOutOfBoundsException e) {
- this.currentPosition--;
- recordComment(TokenNameCOMMENT_LINE);
- if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition);
- if (this.checkNonExternalizedStringLiterals) {
- parseTags();
- }
- if (this.tokenizeComments) {
- currentToken=TokenNameCOMMENT_LINE;
- return currentToken;
- } else {
- this.currentPosition++;
- }
- }
- break;
- }
- if (test > 0) { //traditional and javadoc comment
- try { //get the next char
- boolean isJavadoc = false, star = false;
- boolean isUnicode = false;
- int previous;
- // consume next character
- this.unicodeAsBackSlash = false;
- this.currentCharacter = this.source[this.currentPosition++];
-// Don't process unicode characters in JavaScript comments
-/* if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- isUnicode = true;
- } else {
- isUnicode = false;
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- } */
-
- if (this.currentCharacter == '*') {
- isJavadoc = true;
- star = true;
- }
- if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) {
- if (this.recordLineSeparator) {
- if (isUnicode) {
- pushUnicodeLineSeparator();
- } else {
- pushLineSeparator();
- }
- }
- }
- isUnicode = false;
- previous = this.currentPosition;
- this.currentCharacter = this.source[this.currentPosition++];
-// Don't process unicode characters in JavaScript comments
-/* if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- //-------------unicode traitement ------------
- getNextUnicodeChar();
- isUnicode = true;
- } else {
- isUnicode = false;
- }
- //handle the \\u case manually into comment
- if (this.currentCharacter == '\\') {
- if (this.source[this.currentPosition] == '\\')
- this.currentPosition++; //jump over the \\
- } */
- // empty comment is not a javadoc /**/
- if (this.currentCharacter == '/') {
- isJavadoc = false;
- }
- //loop until end of comment */
- int firstTag = 0;
- while ((this.currentCharacter != '/') || (!star)) {
- if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) {
- if (this.recordLineSeparator) {
- if (isUnicode) {
- pushUnicodeLineSeparator();
- } else {
- pushLineSeparator();
- }
- }
- }
- switch (this.currentCharacter) {
- case '*':
- star = true;
- break;
- case '@':
- if (firstTag == 0) {
- firstTag = previous;
- }
- // fall through default case to set star to false
- //$FALL-THROUGH$
- default:
- star = false;
- }
- //get next char
- previous = this.currentPosition;
- this.currentCharacter = this.source[this.currentPosition++];
-/* if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- //-------------unicode traitement ------------
- getNextUnicodeChar();
- isUnicode = true;
- } else {
- isUnicode = false;
- }
- //handle the \\u case manually into comment
- if (this.currentCharacter == '\\') {
- if (this.source[this.currentPosition] == '\\')
- this.currentPosition++;
- } //jump over the \\ */
- }
- int token = isJavadoc ? TokenNameCOMMENT_JAVADOC : TokenNameCOMMENT_BLOCK;
- recordComment(token);
- this.commentTagStarts[this.commentPtr] = firstTag;
- if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition);
- if (this.tokenizeComments) {
- /*
- if (isJavadoc)
- return TokenNameCOMMENT_JAVADOC;
- return TokenNameCOMMENT_BLOCK;
- */
- currentToken=token;
- return token;
- }
- } catch (IndexOutOfBoundsException e) {
- this.currentPosition--;
- throw new InvalidInputException(UNTERMINATED_COMMENT);
- }
- break;
- }
-
- if (checkIfDivide(previousTokenNonWS)){
- if (getNextChar('='))
- {
- currentToken=currentNonWhitespaceToken=TokenNameDIVIDE_EQUAL;
- return currentToken;
- }
- currentToken=currentNonWhitespaceToken=TokenNameDIVIDE;
- return currentToken;
- }
-
- // check if regular expression
- if (checkIfRegExp()) {
- currentToken =currentNonWhitespaceToken= TokenNameRegExLiteral;
- return currentToken;
- } else {
- if (getNextChar('='))
- {
- currentToken=currentNonWhitespaceToken=TokenNameDIVIDE_EQUAL;
- return currentToken;
- }
- currentToken=currentNonWhitespaceToken=TokenNameDIVIDE;
- return currentToken;
- }
- }
- case '\u001a' :
- if (atEnd())
- {
- currentToken=TokenNameEOF;
- return currentToken;
- }
- //the atEnd may not be <currentPosition == eofPosition> if source is only some part of a real (external) stream
- throw new InvalidInputException("Ctrl-Z"); //$NON-NLS-1$
- default :
- char c = this.currentCharacter;
- if (c < ScannerHelper.MAX_OBVIOUS) {
- if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) {
- currentToken=currentNonWhitespaceToken=scanIdentifierOrKeyword();
- return currentToken;
- } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0) {
- currentToken=currentNonWhitespaceToken=scanNumber(false);
- return currentToken;
- } else {
- currentToken=currentNonWhitespaceToken=TokenNameERROR;
- return currentToken;
- }
- }
- boolean isJavaIdStart;
- if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) {
- if (this.complianceLevel < ClassFileConstants.JDK1_5) {
- throw new InvalidInputException(INVALID_UNICODE_ESCAPE);
- }
- // Unicode 4 detection
- char low = (char) getNextChar();
- if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) {
- // illegal low surrogate
- throw new InvalidInputException(INVALID_LOW_SURROGATE);
- }
- isJavaIdStart = ScannerHelper.isJavaIdentifierStart(c, low);
- }
- else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) {
- if (this.complianceLevel < ClassFileConstants.JDK1_5) {
- throw new InvalidInputException(INVALID_UNICODE_ESCAPE);
- }
- throw new InvalidInputException(INVALID_HIGH_SURROGATE);
- } else {
- // optimized case already checked
- isJavaIdStart = Character.isJavaIdentifierStart(c);
- }
- if (isJavaIdStart)
- {
- currentToken=currentNonWhitespaceToken=scanIdentifierOrKeyword();
- return currentToken;
- }
- if (ScannerHelper.isDigit(this.currentCharacter)) {
- currentToken=currentNonWhitespaceToken=scanNumber(false);
- return currentToken;
- }
- currentToken=TokenNameERROR;
- return currentToken;
- }
- }
- } //-----------------end switch while try--------------------
- catch (IndexOutOfBoundsException e) {
- if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) {
- // reposition scanner in case we are interested by spaces as tokens
- this.currentPosition--;
- this.startPosition = whiteStart;
- currentToken=TokenNameWHITESPACE;
- return currentToken;
- }
- }
- currentToken=TokenNameEOF;
- return currentToken;
-}
-public void getNextUnicodeChar() throws InvalidInputException {
- //VOID
- //handle the case of unicode.
- //when a unicode appears then we must use a buffer that holds char internal values
- //At the end of this method currentCharacter holds the new visited char
- //and currentPosition points right next after it
-
- //ALL getNextChar.... ARE OPTIMIZED COPIES
- int c1 = 0, c2 = 0, c3 = 0, c4 = 0, unicodeSize = 6;
- this.currentPosition++;
- if (this.currentPosition < this.eofPosition) {
- while (this.source[this.currentPosition] == 'u') {
- this.currentPosition++;
- if (this.currentPosition >= this.eofPosition) {
- this.currentPosition--;
- throw new InvalidInputException(INVALID_UNICODE_ESCAPE);
- }
- unicodeSize++;
- }
- } else {
- this.currentPosition--;
- throw new InvalidInputException(INVALID_UNICODE_ESCAPE);
- }
-
- if ((this.currentPosition + 4) > this.eofPosition) {
- this.currentPosition += (this.eofPosition - this.currentPosition);
- throw new InvalidInputException(INVALID_UNICODE_ESCAPE);
- }
- if ((c1 = ScannerHelper.getNumericValue(this.source[this.currentPosition++])) > 15
- || c1 < 0
- || (c2 = ScannerHelper.getNumericValue(this.source[this.currentPosition++])) > 15
- || c2 < 0
- || (c3 = ScannerHelper.getNumericValue(this.source[this.currentPosition++])) > 15
- || c3 < 0
- || (c4 = ScannerHelper.getNumericValue(this.source[this.currentPosition++])) > 15
- || c4 < 0){
- throw new InvalidInputException(INVALID_UNICODE_ESCAPE);
- }
- this.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4);
- //need the unicode buffer
- if (this.withoutUnicodePtr == 0) {
- //buffer all the entries that have been left aside....
- unicodeInitializeBuffer(this.currentPosition - unicodeSize - this.startPosition);
- }
- //fill the buffer with the char
- unicodeStore();
- this.unicodeAsBackSlash = this.currentCharacter == '\\';
-}
-
-public NLSTag[] getNLSTags() {
- final int length = this.nlsTagsPtr;
- if (length != 0) {
- NLSTag[] result = new NLSTag[length];
- System.arraycopy(this.nlsTags, 0, result, 0, length);
- this.nlsTagsPtr = 0;
- return result;
- }
- return null;
-}
-public char[] getSource(){
- return this.source;
-}
-public final void jumpOverMethodBody() {
-
- this.wasAcr = false;
- int found = 1;
- try {
- while (true) { //loop for jumping over comments
- this.withoutUnicodePtr = 0;
- // ---------Consume white space and handles startPosition---------
- boolean isWhiteSpace;
- do {
- this.startPosition = this.currentPosition;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- isWhiteSpace = jumpOverUnicodeWhiteSpace();
- } else {
- if (this.recordLineSeparator
- && ((this.currentCharacter == '\r') || (this.currentCharacter == '\n'))) {
- pushLineSeparator();
- }
- isWhiteSpace = CharOperation.isWhitespace(this.currentCharacter);
- }
- } while (isWhiteSpace);
-
- // -------consume token until } is found---------
- NextToken: switch (this.currentCharacter) {
- case '{' :
- found++;
- break NextToken;
- case '}' :
- found--;
- if (found == 0)
- return;
- break NextToken;
- case '\'' :
- {
- boolean test;
- test = getNextChar('\\');
- if (test) {
- try {
- if (this.unicodeAsBackSlash) {
- // consume next character
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- } else {
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
- } else {
- this.currentCharacter = this.source[this.currentPosition++];
- }
- scanEscapeCharacter();
- } catch (InvalidInputException ex) {
- // ignore
- }
- } else {
- try { // consume next character
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- } else {
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
- } catch (InvalidInputException ex) {
- // ignore
- }
- }
- getNextChar('\'');
- break NextToken;
- }
- case '"' :
- try {
- try { // consume next character
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- } else {
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
- } catch (InvalidInputException ex) {
- // ignore
- }
- while (this.currentCharacter != '"') {
- if (this.currentCharacter == '\r'){
- if (this.source[this.currentPosition] == '\n') this.currentPosition++;
- break NextToken; // the string cannot go further that the line
- }
- if (this.currentCharacter == '\n'){
- break; // the string cannot go further that the line
- }
- if (this.currentCharacter == '\\') {
- try {
- if (this.unicodeAsBackSlash) {
- // consume next character
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- } else {
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
- } else {
- this.currentCharacter = this.source[this.currentPosition++];
- }
- scanEscapeCharacter();
- } catch (InvalidInputException ex) {
- // ignore
- }
- }
- try { // consume next character
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- } else {
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
- } catch (InvalidInputException ex) {
- // ignore
- }
- }
- } catch (IndexOutOfBoundsException e) {
- return;
- }
- break NextToken;
- case '/' :
- {
- int test;
- if ((test = getNextChar('/', '*')) == 0) { //line comment
- try {
- this.lastCommentLinePosition = this.currentPosition;
- //get the next char
- this.currentCharacter = this.source[this.currentPosition++];
-/* if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- }
- //handle the \\u case manually into comment
- if (this.currentCharacter == '\\') {
- if (this.source[this.currentPosition] == '\\')
- this.currentPosition++;
- } //jump over the \\ */
-
- while (this.currentCharacter != '\r' && this.currentCharacter != '\n') {
- this.lastCommentLinePosition = this.currentPosition;
- this.currentCharacter = this.source[this.currentPosition++];
- //get the next char
-/* isUnicode = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- isUnicode = true;
- getNextUnicodeChar();
- }
- //handle the \\u case manually into comment
- if (this.currentCharacter == '\\') {
- if (this.source[this.currentPosition] == '\\')
- this.currentPosition++;
- } //jump over the \\ */
- }
- /*
- * We need to completely consume the line break
- */
- boolean isUnicode = false;
- if (this.currentCharacter == '\r'
- && this.eofPosition > this.currentPosition) {
- if (this.source[this.currentPosition] == '\n') {
- this.currentPosition++;
- this.currentCharacter = '\n';
- } else if ((this.source[this.currentPosition] == '\\')
- && (this.source[this.currentPosition + 1] == 'u')) {
- isUnicode = true;
- getNextUnicodeChar();
- }
- }
- recordComment(TokenNameCOMMENT_LINE);
- if (this.recordLineSeparator
- && ((this.currentCharacter == '\r') || (this.currentCharacter == '\n'))) {
- if (this.checkNonExternalizedStringLiterals) {
- parseTags();
- }
- if (this.recordLineSeparator) {
- if (isUnicode) {
- pushUnicodeLineSeparator();
- } else {
- pushLineSeparator();
- }
- }
- }
- } catch (IndexOutOfBoundsException e) {
- //an eof will then be generated
- this.currentPosition--;
- recordComment(TokenNameCOMMENT_LINE);
- if (this.checkNonExternalizedStringLiterals) {
- parseTags();
- }
- if (!this.tokenizeComments) {
- this.currentPosition++;
- }
- }
- break NextToken;
- }
- if (test > 0) { //traditional and javadoc comment
- boolean isJavadoc = false;
- try { //get the next char
- boolean star = false;
- int previous;
- boolean isUnicode = false;
- // consume next character
- this.unicodeAsBackSlash = false;
- this.currentCharacter = this.source[this.currentPosition++];
-/* if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- isUnicode = true;
- } else {
- isUnicode = false;
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- } */
-
- if (this.currentCharacter == '*') {
- isJavadoc = true;
- star = true;
- }
- if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) {
- if (this.recordLineSeparator) {
- if (isUnicode) {
- pushUnicodeLineSeparator();
- } else {
- pushLineSeparator();
- }
- }
- }
- isUnicode = false;
- previous = this.currentPosition;
- this.currentCharacter = this.source[this.currentPosition++];
-/* if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- isUnicode = true;
- } else {
- isUnicode = false;
- }
- //handle the \\u case manually into comment
- if (this.currentCharacter == '\\') {
- if (this.source[this.currentPosition] == '\\')
- this.currentPosition++; //jump over the \\
- } */
- // empty comment is not a javadoc /**/
- if (this.currentCharacter == '/') {
- isJavadoc = false;
- }
- //loop until end of comment */
- int firstTag = 0;
- while ((this.currentCharacter != '/') || (!star)) {
- if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) {
- if (this.recordLineSeparator) {
- if (isUnicode) {
- pushUnicodeLineSeparator();
- } else {
- pushLineSeparator();
- }
- }
- }
- switch (this.currentCharacter) {
- case '*':
- star = true;
- break;
- case '@':
- if (firstTag == 0) {
- firstTag = previous;
- }
- // fall through default case to set star to false
- //$FALL-THROUGH$
- default:
- star = false;
- }
- //get next char
- previous = this.currentPosition;
- this.currentCharacter = this.source[this.currentPosition++];
-/* if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- isUnicode = true;
- } else {
- isUnicode = false;
- }
- //handle the \\u case manually into comment
- if (this.currentCharacter == '\\') {
- if (this.source[this.currentPosition] == '\\')
- this.currentPosition++;
- } //jump over the \\ */
- }
- recordComment(isJavadoc ? TokenNameCOMMENT_JAVADOC : TokenNameCOMMENT_BLOCK);
- this.commentTagStarts[this.commentPtr] = firstTag;
- } catch (IndexOutOfBoundsException e) {
- return;
- }
- break NextToken;
- }
- break NextToken;
- }
-
- default :
- try {
- char c = this.currentCharacter;
- if (c < ScannerHelper.MAX_OBVIOUS) {
- if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) {
- scanIdentifierOrKeyword();
- break NextToken;
- } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0) {
- scanNumber(false);
- break NextToken;
- } else {
- break NextToken;
- }
- }
- boolean isJavaIdStart;
- if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) {
- if (this.complianceLevel < ClassFileConstants.JDK1_5) {
- throw new InvalidInputException(INVALID_UNICODE_ESCAPE);
- }
- // Unicode 4 detection
- char low = (char) getNextChar();
- if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) {
- // illegal low surrogate
- break NextToken;
- }
- isJavaIdStart = ScannerHelper.isJavaIdentifierStart(c, low);
- } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) {
- break NextToken;
- } else {
- // optimized case already checked
- isJavaIdStart = Character.isJavaIdentifierStart(c);
- }
- if (isJavaIdStart) {
- scanIdentifierOrKeyword();
- break NextToken;
- }
-// if (ScannerHelper.isDigit(this.currentCharacter)) {
-// scanNumber(false);
-// break NextToken;
-// }
- } catch (InvalidInputException ex) {
- // ignore
- }
- }
- }
- //-----------------end switch while try--------------------
- } catch (IndexOutOfBoundsException e) {
- // ignore
- } catch (InvalidInputException e) {
- // ignore
- }
- return;
-}
-public final boolean jumpOverUnicodeWhiteSpace() throws InvalidInputException {
- //BOOLEAN
- //handle the case of unicode. Jump over the next whiteSpace
- //making startPosition pointing on the next available char
- //On false, the currentCharacter is filled up with a potential
- //correct char
-
- this.wasAcr = false;
- getNextUnicodeChar();
- return CharOperation.isWhitespace(this.currentCharacter);
-}
-
-final char[] optimizedCurrentTokenSource1() {
- //return always the same char[] build only once
-
- //optimization at no speed cost of 99.5 % of the singleCharIdentifier
- char charOne = this.source[this.startPosition];
- switch (charOne) {
- case 'a' :
- return charArray_a;
- case 'b' :
- return charArray_b;
- case 'c' :
- return charArray_c;
- case 'd' :
- return charArray_d;
- case 'e' :
- return charArray_e;
- case 'f' :
- return charArray_f;
- case 'g' :
- return charArray_g;
- case 'h' :
- return charArray_h;
- case 'i' :
- return charArray_i;
- case 'j' :
- return charArray_j;
- case 'k' :
- return charArray_k;
- case 'l' :
- return charArray_l;
- case 'm' :
- return charArray_m;
- case 'n' :
- return charArray_n;
- case 'o' :
- return charArray_o;
- case 'p' :
- return charArray_p;
- case 'q' :
- return charArray_q;
- case 'r' :
- return charArray_r;
- case 's' :
- return charArray_s;
- case 't' :
- return charArray_t;
- case 'u' :
- return charArray_u;
- case 'v' :
- return charArray_v;
- case 'w' :
- return charArray_w;
- case 'x' :
- return charArray_x;
- case 'y' :
- return charArray_y;
- case 'z' :
- return charArray_z;
- default :
- return new char[] {charOne};
- }
-}
-final char[] optimizedCurrentTokenSource2() {
- //try to return the same char[] build only once
-
- char[] src = this.source;
- int start = this.startPosition;
- char c0 , c1;
- int hash = (((c0=src[start]) << 6) + (c1=src[start+1])) % TableSize;
- char[][] table = this.charArray_length[0][hash];
- int i = newEntry2;
- while (++i < InternalTableSize) {
- char[] charArray = table[i];
- if ((c0 == charArray[0]) && (c1 == charArray[1]))
- return charArray;
- }
- //---------other side---------
- i = -1;
- int max = newEntry2;
- while (++i <= max) {
- char[] charArray = table[i];
- if ((c0 == charArray[0]) && (c1 == charArray[1]))
- return charArray;
- }
- //--------add the entry-------
- if (++max >= InternalTableSize) max = 0;
- char[] r;
- System.arraycopy(src, start, r= new char[2], 0, 2);
- //newIdentCount++;
- return table[newEntry2 = max] = r; //(r = new char[] {c0, c1});
-}
-final char[] optimizedCurrentTokenSource3() {
- //try to return the same char[] build only once
-
- char[] src = this.source;
- int start = this.startPosition;
- char c0, c1=src[start+1], c2;
- int hash = (((c0=src[start])<< 6) + (c2=src[start+2])) % TableSize;
-// int hash = ((c0 << 12) + (c1<< 6) + c2) % TableSize;
- char[][] table = this.charArray_length[1][hash];
- int i = newEntry3;
- while (++i < InternalTableSize) {
- char[] charArray = table[i];
- if ((c0 == charArray[0]) && (c1 == charArray[1]) && (c2 == charArray[2]))
- return charArray;
- }
- //---------other side---------
- i = -1;
- int max = newEntry3;
- while (++i <= max) {
- char[] charArray = table[i];
- if ((c0 == charArray[0]) && (c1 == charArray[1]) && (c2 == charArray[2]))
- return charArray;
- }
- //--------add the entry-------
- if (++max >= InternalTableSize) max = 0;
- char[] r;
- System.arraycopy(src, start, r= new char[3], 0, 3);
- //newIdentCount++;
- return table[newEntry3 = max] = r; //(r = new char[] {c0, c1, c2});
-}
-final char[] optimizedCurrentTokenSource4() {
- //try to return the same char[] build only once
-
- char[] src = this.source;
- int start = this.startPosition;
- char c0, c1 = src[start+1], c2, c3 = src[start+3];
- int hash = (((c0=src[start]) << 6) + (c2=src[start+2])) % TableSize;
-// int hash = (int) (((((long) c0) << 18) + (c1 << 12) + (c2 << 6) + c3) % TableSize);
- char[][] table = this.charArray_length[2][hash];
- int i = newEntry4;
- while (++i < InternalTableSize) {
- char[] charArray = table[i];
- if ((c0 == charArray[0])
- && (c1 == charArray[1])
- && (c2 == charArray[2])
- && (c3 == charArray[3]))
- return charArray;
- }
- //---------other side---------
- i = -1;
- int max = newEntry4;
- while (++i <= max) {
- char[] charArray = table[i];
- if ((c0 == charArray[0])
- && (c1 == charArray[1])
- && (c2 == charArray[2])
- && (c3 == charArray[3]))
- return charArray;
- }
- //--------add the entry-------
- if (++max >= InternalTableSize) max = 0;
- char[] r;
- System.arraycopy(src, start, r= new char[4], 0, 4);
- //newIdentCount++;
- return table[newEntry4 = max] = r; //(r = new char[] {c0, c1, c2, c3});
-}
-final char[] optimizedCurrentTokenSource5() {
- //try to return the same char[] build only once
-
- char[] src = this.source;
- int start = this.startPosition;
- char c0, c1 = src[start+1], c2, c3 = src[start+3], c4;
- int hash = (((c0=src[start]) << 12) +((c2=src[start+2]) << 6) + (c4=src[start+4])) % TableSize;
-// int hash = (int) (((((long) c0) << 24) + (((long) c1) << 18) + (c2 << 12) + (c3 << 6) + c4) % TableSize);
- char[][] table = this.charArray_length[3][hash];
- int i = newEntry5;
- while (++i < InternalTableSize) {
- char[] charArray = table[i];
- if ((c0 == charArray[0])
- && (c1 == charArray[1])
- && (c2 == charArray[2])
- && (c3 == charArray[3])
- && (c4 == charArray[4]))
- return charArray;
- }
- //---------other side---------
- i = -1;
- int max = newEntry5;
- while (++i <= max) {
- char[] charArray = table[i];
- if ((c0 == charArray[0])
- && (c1 == charArray[1])
- && (c2 == charArray[2])
- && (c3 == charArray[3])
- && (c4 == charArray[4]))
- return charArray;
- }
- //--------add the entry-------
- if (++max >= InternalTableSize) max = 0;
- char[] r;
- System.arraycopy(src, start, r= new char[5], 0, 5);
- //newIdentCount++;
- return table[newEntry5 = max] = r; //(r = new char[] {c0, c1, c2, c3, c4});
-}
-final char[] optimizedCurrentTokenSource6() {
- //try to return the same char[] build only once
-
- char[] src = this.source;
- int start = this.startPosition;
- char c0, c1 = src[start+1], c2, c3 = src[start+3], c4, c5 = src[start+5];
- int hash = (((c0=src[start]) << 12) +((c2=src[start+2]) << 6) + (c4=src[start+4])) % TableSize;
-// int hash = (int)(((((long) c0) << 32) + (((long) c1) << 24) + (((long) c2) << 18) + (c3 << 12) + (c4 << 6) + c5) % TableSize);
- char[][] table = this.charArray_length[4][hash];
- int i = newEntry6;
- while (++i < InternalTableSize) {
- char[] charArray = table[i];
- if ((c0 == charArray[0])
- && (c1 == charArray[1])
- && (c2 == charArray[2])
- && (c3 == charArray[3])
- && (c4 == charArray[4])
- && (c5 == charArray[5]))
- return charArray;
- }
- //---------other side---------
- i = -1;
- int max = newEntry6;
- while (++i <= max) {
- char[] charArray = table[i];
- if ((c0 == charArray[0])
- && (c1 == charArray[1])
- && (c2 == charArray[2])
- && (c3 == charArray[3])
- && (c4 == charArray[4])
- && (c5 == charArray[5]))
- return charArray;
- }
- //--------add the entry-------
- if (++max >= InternalTableSize) max = 0;
- char[] r;
- System.arraycopy(src, start, r= new char[6], 0, 6);
- //newIdentCount++;
- return table[newEntry6 = max] = r; //(r = new char[] {c0, c1, c2, c3, c4, c5});
-}
-
-private void parseTags() {
- int position = 0;
- final int currentStartPosition = this.startPosition;
- final int currentLinePtr = this.linePtr;
- if (currentLinePtr >= 0) {
- position = this.lineEnds[currentLinePtr] + 1;
- }
- while (ScannerHelper.isWhitespace(this.source[position])) {
- position++;
- }
- if (currentStartPosition == position) {
- // the whole line is commented out
- return;
- }
- char[] s = null;
- int sourceEnd = this.currentPosition;
- int sourceStart = currentStartPosition;
- int sourceDelta = 0;
- if (this.withoutUnicodePtr != 0) {
- // 0 is used as a fast test flag so the real first char is in position 1
- System.arraycopy(
- this.withoutUnicodeBuffer,
- 1,
- s = new char[this.withoutUnicodePtr],
- 0,
- this.withoutUnicodePtr);
- sourceEnd = this.withoutUnicodePtr;
- sourceStart = 1;
- sourceDelta = currentStartPosition;
- } else {
- s = this.source;
- }
- int pos = CharOperation.indexOf(TAG_PREFIX, s, true, sourceStart, sourceEnd);
- if (pos != -1) {
- if (this.nlsTags == null) {
- this.nlsTags = new NLSTag[10];
- this.nlsTagsPtr = 0;
- }
- while (pos != -1) {
- int start = pos + TAG_PREFIX_LENGTH;
- int end = CharOperation.indexOf(TAG_POSTFIX, s, start, sourceEnd);
- if (end != -1) {
- NLSTag currentTag = null;
- final int currentLine = currentLinePtr + 1;
- try {
- currentTag = new NLSTag(pos + sourceDelta, end + sourceDelta, currentLine, extractInt(s, start, end));
- } catch (NumberFormatException e) {
- currentTag = new NLSTag(pos + sourceDelta, end + sourceDelta, currentLine, -1);
- }
- if (this.nlsTagsPtr == this.nlsTags.length) {
- // resize
- System.arraycopy(this.nlsTags, 0, (this.nlsTags = new NLSTag[this.nlsTagsPtr + 10]), 0, this.nlsTagsPtr);
- }
- this.nlsTags[this.nlsTagsPtr++] = currentTag;
- } else {
- end = start;
- }
- pos = CharOperation.indexOf(TAG_PREFIX, s, true, end, sourceEnd);
- }
- }
-}
-private int extractInt(char[] array, int start, int end) {
- int value = 0;
- for (int i = start; i < end; i++) {
- final char currentChar = array[i];
- int digit = 0;
- switch(currentChar) {
- case '0' :
- digit = 0;
- break;
- case '1' :
- digit = 1;
- break;
- case '2' :
- digit = 2;
- break;
- case '3' :
- digit = 3;
- break;
- case '4' :
- digit = 4;
- break;
- case '5' :
- digit = 5;
- break;
- case '6' :
- digit = 6;
- break;
- case '7' :
- digit = 7;
- break;
- case '8' :
- digit = 8;
- break;
- case '9' :
- digit = 9;
- break;
- default :
- throw new NumberFormatException();
- }
- value *= 10;
- if (digit < 0) throw new NumberFormatException();
- value += digit;
- }
- return value;
-}
-public final void pushLineSeparator() {
- //see comment on isLineDelimiter(char) for the use of '\n' and '\r'
- final int INCREMENT = 250;
- //currentCharacter is at position currentPosition-1
- // cr 000D
- if (this.currentCharacter == '\r') {
- int separatorPos = this.currentPosition - 1;
- if ((this.linePtr >= 0) && (this.lineEnds[this.linePtr] >= separatorPos)) return;
- int length = this.lineEnds.length;
- if (++this.linePtr >= length)
- System.arraycopy(this.lineEnds, 0, this.lineEnds = new int[length + INCREMENT], 0, length);
- this.lineEnds[this.linePtr] = separatorPos;
- // look-ahead for merged cr+lf
- try {
- if (this.source[this.currentPosition] == '\n') {
- //System.out.println("look-ahead LF-" + this.currentPosition);
- this.lineEnds[this.linePtr] = this.currentPosition;
- this.currentPosition++;
- this.wasAcr = false;
- } else {
- this.wasAcr = true;
- }
- } catch(IndexOutOfBoundsException e) {
- this.wasAcr = true;
- }
- } else {
- // lf 000A
- if (this.currentCharacter == '\n') { //must merge eventual cr followed by lf
- if (this.wasAcr && (this.lineEnds[this.linePtr] == (this.currentPosition - 2))) {
- //System.out.println("merge LF-" + (this.currentPosition - 1));
- this.lineEnds[this.linePtr] = this.currentPosition - 1;
- } else {
- int separatorPos = this.currentPosition - 1;
- if ((this.linePtr >= 0) && (this.lineEnds[this.linePtr] >= separatorPos)) return;
- int length = this.lineEnds.length;
- if (++this.linePtr >= length)
- System.arraycopy(this.lineEnds, 0, this.lineEnds = new int[length + INCREMENT], 0, length);
- this.lineEnds[this.linePtr] = separatorPos;
- }
- this.wasAcr = false;
- }
- }
-}
-public final void pushUnicodeLineSeparator() {
- // cr 000D
- if (this.currentCharacter == '\r') {
- if (this.source[this.currentPosition] == '\n') {
- this.wasAcr = false;
- } else {
- this.wasAcr = true;
- }
- } else {
- // lf 000A
- if (this.currentCharacter == '\n') { //must merge eventual cr followed by lf
- this.wasAcr = false;
- }
- }
-}
-
-public void recordComment(int token) {
- // compute position
- int stopPosition = this.currentPosition;
- switch (token) {
- case TokenNameCOMMENT_LINE:
- stopPosition = -this.lastCommentLinePosition;
- break;
- case TokenNameCOMMENT_BLOCK:
- stopPosition = -this.currentPosition;
- break;
- }
-
- // a new comment is recorded
- int length = this.commentStops.length;
- if (++this.commentPtr >= length) {
- int newLength = length + COMMENT_ARRAYS_SIZE*10;
- System.arraycopy(this.commentStops, 0, this.commentStops = new int[newLength], 0, length);
- System.arraycopy(this.commentStarts, 0, this.commentStarts = new int[newLength], 0, length);
- System.arraycopy(this.commentTagStarts, 0, this.commentTagStarts = new int[newLength], 0, length);
- }
- this.commentStops[this.commentPtr] = stopPosition;
- this.commentStarts[this.commentPtr] = this.startPosition;
-}
-
-/**
- * Reposition the scanner on some portion of the original source. The given endPosition is the last valid position.
- * Beyond this position, the scanner will answer EOF tokens (<code>ITerminalSymbols.TokenNameEOF</code>).
- *
- * @param begin the given start position
- * @param end the given end position
- */
-public void resetTo(int begin, int end) {
- resetTo(begin, end,this.currentToken,this.currentToken);
-}
-
-public void resetTo(int begin, int end, int currentToken, int currentNonWSToken) {
- //reset the scanner to a given position where it may rescan again
-
- this.diet = false;
- this.initialPosition = this.startPosition = this.currentPosition = begin;
- if (this.source != null && this.source.length < end) {
- this.eofPosition = this.source.length;
- } else {
- this.eofPosition = end < Integer.MAX_VALUE ? end + 1 : end;
- }
- this.commentPtr = -1; // reset comment stack
- this.foundTaskCount = 0;
- this.currentToken=currentToken;
- this.currentNonWhitespaceToken=currentNonWSToken;
-}
-
-
-
-/**
- * Processes an escaped character sequence on the current source position.
- * @return Whether a character was produced. Thus, false in case of a string line continuation.
- * @throws InvalidInputException
- */
-public final boolean scanEscapeCharacter() throws InvalidInputException {
- // the string with "\\u" is a legal string of two chars \ and u
- //thus we use a direct access to the source (for regular cases).
- switch (this.currentCharacter) {
- case 'b' :
- this.currentCharacter = '\b';
- break;
- case 't' :
- this.currentCharacter = '\t';
- break;
- case 'n' :
- this.currentCharacter = '\n';
- break;
- case 'f' :
- this.currentCharacter = '\f';
- break;
- case 'r' :
- this.currentCharacter = '\r';
- break;
- case '\"' :
- this.currentCharacter = '\"';
- break;
- case '\'' :
- this.currentCharacter = '\'';
- break;
- case '\\' :
- this.currentCharacter = '\\';
- break;
- case '\r':
- if (this.source[this.currentPosition] == '\n')
- this.currentPosition++;
- //$FALL-THROUGH$
- case '\n':
- case '\u2029':
- case '\u2028':
- return false;
- case 'x' :
- int digit1 = ScannerHelper.digit(this.source[this.currentPosition], 16);
- int digit2 = ScannerHelper.digit(this.source[this.currentPosition + 1], 16);
- if ( digit1 != -1 && digit2 != -1 ) {
-
- int number = (digit1 * 16) + digit2;
- this.currentPosition = this.currentPosition + 2;
- this.currentCharacter = (char)number;
- break;
- }
- //$FALL-THROUGH$
- default :
- // -----------octal escape--------------
- // OctalDigit
- // OctalDigit OctalDigit
- // ZeroToThree OctalDigit OctalDigit
-
- int number = ScannerHelper.getNumericValue(this.currentCharacter);
- if (number >= 0 && number <= 7) {
- boolean zeroToThreeNot = number > 3;
- if (ScannerHelper.isDigit(this.currentCharacter = this.source[this.currentPosition++])) {
- int digit = ScannerHelper.getNumericValue(this.currentCharacter);
- if (digit >= 0 && digit <= 7) {
- number = (number * 8) + digit;
- if (ScannerHelper.isDigit(this.currentCharacter = this.source[this.currentPosition++])) {
- if (zeroToThreeNot) {// has read \NotZeroToThree OctalDigit Digit --> ignore last character
- this.currentPosition--;
- } else {
- digit = ScannerHelper.getNumericValue(this.currentCharacter);
- if (digit >= 0 && digit <= 7){ // has read \ZeroToThree OctalDigit OctalDigit
- number = (number * 8) + digit;
- } else {// has read \ZeroToThree OctalDigit NonOctalDigit --> ignore last character
- this.currentPosition--;
- }
- }
- } else { // has read \OctalDigit NonDigit--> ignore last character
- this.currentPosition--;
- }
- } else { // has read \OctalDigit NonOctalDigit--> ignore last character
- this.currentPosition--;
- }
- } else { // has read \OctalDigit --> ignore last character
- this.currentPosition--;
- }
- if (number > 255)
- throw new InvalidInputException(INVALID_ESCAPE);
- this.currentCharacter = (char) number;
- }
- // in JavaScript when a backslash followed by character, the
- // backslash is ignored.
- }
- return true;
-}
-
-public int scanIdentifierOrKeywordWithBoundCheck() {
- //test keywords
-
- //first dispatch on the first char.
- //then the length. If there are several
- //keywors with the same length AND the same first char, then do another
- //dispatch on the second char
- this.useAssertAsAnIndentifier = false;
- this.useEnumAsAnIndentifier = false;
-
- char[] src = this.source;
- identLoop: {
- int pos;
- int srcLength = this.eofPosition;
- while (true) {
- if ((pos = this.currentPosition) >= srcLength) // handle the obvious case upfront
- break identLoop;
- char c = src[pos];
- if (c < ScannerHelper.MAX_OBVIOUS) {
- if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] &
- (ScannerHelper.C_UPPER_LETTER | ScannerHelper.C_LOWER_LETTER | ScannerHelper.C_IDENT_PART | ScannerHelper.C_DIGIT)) != 0) {
- if (this.withoutUnicodePtr != 0) {
- this.currentCharacter = c;
- unicodeStore();
- }
- this.currentPosition++;
- } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & (ScannerHelper.C_SEPARATOR | ScannerHelper.C_JLS_SPACE)) != 0) {
- this.currentCharacter = c;
- break identLoop;
- } else {
- //System.out.println("slow<=128: "+ c);
- while (getNextCharAsJavaIdentifierPartWithBoundCheck()){/*empty*/}
- break identLoop;
- }
- } else {
- //System.out.println("slow>>128: "+ c);
- while (getNextCharAsJavaIdentifierPartWithBoundCheck()){/*empty*/}
- break identLoop;
- }
- }
- }
-
- int index, length;
- char[] data;
- if (this.withoutUnicodePtr == 0) {
- //quick test on length == 1 but not on length > 12 while most identifier
- //have a length which is <= 12...but there are lots of identifier with
- //only one char....
- if ((length = this.currentPosition - this.startPosition) == 1) {
- return TokenNameIdentifier;
- }
- data = this.source;
- index = this.startPosition;
- } else {
- if ((length = this.withoutUnicodePtr) == 1)
- return TokenNameIdentifier;
- data = this.withoutUnicodeBuffer;
- index = 1;
- }
-
- return internalScanIdentifierOrKeyword(index, length, data);
-}
-
-
-public int scanIdentifierOrKeyword() {
- //test keywords
-
- //first dispatch on the first char.
- //then the length. If there are several
- //keywors with the same length AND the same first char, then do another
- //dispatch on the second char
- this.useAssertAsAnIndentifier = false;
- this.useEnumAsAnIndentifier = false;
-
- char[] src = this.source;
- identLoop: {
- int pos;
- int srcLength = this.eofPosition;
- while (true) {
- if ((pos = this.currentPosition) >= srcLength) // handle the obvious case upfront
- break identLoop;
- char c = src[pos];
- if (c < ScannerHelper.MAX_OBVIOUS) {
- if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] &
- (ScannerHelper.C_UPPER_LETTER | ScannerHelper.C_LOWER_LETTER | ScannerHelper.C_IDENT_PART | ScannerHelper.C_DIGIT)) != 0) {
- if (this.withoutUnicodePtr != 0) {
- this.currentCharacter = c;
- unicodeStore();
- }
- this.currentPosition++;
- } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & (ScannerHelper.C_SEPARATOR | ScannerHelper.C_JLS_SPACE)) != 0) {
- this.currentCharacter = c;
- break identLoop;
- } else {
- //System.out.println("slow<=128: "+ c);
- while (getNextCharAsJavaIdentifierPart()){/*empty*/}
- break identLoop;
- }
- } else {
- //System.out.println("slow>>128: "+ c);
- while (getNextCharAsJavaIdentifierPart()){/*empty*/}
- break identLoop;
- }
- }
- }
-
- int index, length;
- char[] data;
- if (this.withoutUnicodePtr == 0) {
-
-
- //quick test on length == 1 but not on length > 12 while most identifier
- //have a length which is <= 12...but there are lots of identifier with
- //only one char....
-
- if ((length = this.currentPosition - this.startPosition) == 1) {
- return TokenNameIdentifier;
- }
- data = this.source;
- index = this.startPosition;
- } else {
- if ((length = this.withoutUnicodePtr) == 1)
- return TokenNameIdentifier;
- data = this.withoutUnicodeBuffer;
- index = 1;
- }
- return internalScanIdentifierOrKeyword(index, length, data);
-}
-
-private int internalScanIdentifierOrKeyword(int index, int length, char[] data) {
-
- switch (data[index]) {
-
- case 'a' :
- if (length==8) {
- //abstract
- if ((data[++index] == 'b')
- && (data[++index] == 's')
- && (data[++index] == 't')
- && (data[++index] == 'r')
- && (data[++index] == 'a')
- && (data[++index] == 'c')
- && (data[++index] == 't')) {
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- this.containsAssertKeyword = true;
- return TokenNameabstract;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- } else {
- return TokenNameIdentifier;
- }
- }
- else
- return TokenNameIdentifier;
- case 'b' : //boolean break byte
- switch (length) {
- case 4 :
- if ((data[++index] == 'y') && (data[++index] == 't') && (data[++index] == 'e'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNamebyte;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- else
- return TokenNameIdentifier;
- case 5 :
- if ((data[++index] == 'r')
- && (data[++index] == 'e')
- && (data[++index] == 'a')
- && (data[++index] == 'k'))
- return TokenNamebreak;
- else
- return TokenNameIdentifier;
- case 7 :
- if ((data[++index] == 'o')
- && (data[++index] == 'o')
- && (data[++index] == 'l')
- && (data[++index] == 'e')
- && (data[++index] == 'a')
- && (data[++index] == 'n'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNameboolean;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
-
- else
- return TokenNameIdentifier;
- default :
- return TokenNameIdentifier;
- }
-
- case 'c' : //case char catch const class continue
- switch (length) {
- case 4 :
- if (data[++index] == 'a')
- if ((data[++index] == 's') && (data[++index] == 'e'))
- return TokenNamecase;
- else
- return TokenNameIdentifier;
- else
- if ((data[index] == 'h') && (data[++index] == 'a') && (data[++index] == 'r'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNamechar;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- else
- return TokenNameIdentifier;
- case 5 :
- if (data[++index] == 'a')
- if ((data[++index] == 't') && (data[++index] == 'c') && (data[++index] == 'h'))
- return TokenNamecatch;
- else
- return TokenNameIdentifier;
- else
- if (data[index] == 'l')
- if ((data[++index] == 'a')
- && (data[++index] == 's')
- && (data[++index] == 's'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNameclass;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- else
- return TokenNameIdentifier;
- else if ((data[index] == 'o')
- && (data[++index] == 'n')
- && (data[++index] == 's')
- && (data[++index] == 't'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNameconst;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- else
- return TokenNameIdentifier;
- case 8 :
- if ((data[++index] == 'o')
- && (data[++index] == 'n')
- && (data[++index] == 't')
- && (data[++index] == 'i')
- && (data[++index] == 'n')
- && (data[++index] == 'u')
- && (data[++index] == 'e'))
- return TokenNamecontinue;
- else
- return TokenNameIdentifier;
- default :
- return TokenNameIdentifier;
- }
-
- case 'd' : //default do double
- switch (length) {
- case 2 :
- if ((data[++index] == 'o'))
- return TokenNamedo;
- else
- return TokenNameIdentifier;
- case 6 :
- if (data[++index] == 'o')
- {
- if ((data[++index] == 'u')
- && (data[++index] == 'b')
- && (data[++index] == 'l')
- && (data[++index] == 'e'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNamedouble;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- else
- return TokenNameIdentifier;
- }
- else if (data[index]=='e')
- {
- if ((data[++index] == 'l')
- && (data[++index] == 'e')
- && (data[++index] == 't')
- && (data[++index] == 'e'))
- return TokenNamedelete;
- else
- return TokenNameIdentifier;
-
- }
- else
- return TokenNameIdentifier;
- case 7 :
- if ((data[++index] == 'e')
- && (data[++index] == 'f')
- && (data[++index] == 'a')
- && (data[++index] == 'u')
- && (data[++index] == 'l')
- && (data[++index] == 't'))
- return TokenNamedefault;
- else
- return TokenNameIdentifier;
- case 8 :
-//@GINO: Bug 197987 (Temp Fix)
-// if ((data[++index] == 'e')
-// && (data[++index] == 'b')
-// && (data[++index] == 'u')
-// && (data[++index] == 'g')
-// && (data[++index] == 'g')
-// && (data[++index] == 'e')
-// && (data[++index] == 'r'))
-// return TokenNamedebugger;
-// else
- return TokenNameIdentifier;
- default :
- return TokenNameIdentifier;
- }
- case 'e' : //else extends
- switch (length) {
- case 4 :
- if ((data[++index] == 'l') && (data[++index] == 's') && (data[++index] == 'e'))
- return TokenNameelse;
- else if ((data[index] == 'n')
- && (data[++index] == 'u')
- && (data[++index] == 'm')) {
- if (this.sourceLevel >= ClassFileConstants.JDK1_5) {
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNameenum;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- } else {
- this.useEnumAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- } else {
- return TokenNameIdentifier;
- }
- case 6 :
- if ((data[++index] == 'x')
- && (data[++index] == 'p')
- && (data[++index] == 'o')
- && (data[++index] == 'r')
- && (data[++index] == 't'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNameexport;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- else
- return TokenNameIdentifier;
- case 7 :
- if ((data[++index] == 'x')
- && (data[++index] == 't')
- && (data[++index] == 'e')
- && (data[++index] == 'n')
- && (data[++index] == 'd')
- && (data[++index] == 's'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNameextends;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- else
- return TokenNameIdentifier;
- default :
- return TokenNameIdentifier;
- }
-
- case 'f' : //final finally float for false
- switch (length) {
- case 3 :
- if ((data[++index] == 'o') && (data[++index] == 'r'))
- return TokenNamefor;
- else
- return TokenNameIdentifier;
- case 5 :
- if (data[++index] == 'i')
- if ((data[++index] == 'n')
- && (data[++index] == 'a')
- && (data[++index] == 'l')) {
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNamefinal;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- } else
- return TokenNameIdentifier;
- else
- if (data[index] == 'l')
- if ((data[++index] == 'o')
- && (data[++index] == 'a')
- && (data[++index] == 't'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNamefloat;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- else
- return TokenNameIdentifier;
- else
- if ((data[index] == 'a')
- && (data[++index] == 'l')
- && (data[++index] == 's')
- && (data[++index] == 'e'))
- return TokenNamefalse;
- else
- return TokenNameIdentifier;
- case 7 :
- if ((data[++index] == 'i')
- && (data[++index] == 'n')
- && (data[++index] == 'a')
- && (data[++index] == 'l')
- && (data[++index] == 'l')
- && (data[++index] == 'y'))
- return TokenNamefinally;
- else
- return TokenNameIdentifier;
-
- case 8 :
- if ((data[++index] == 'u')
- && (data[++index] == 'n')
- && (data[++index] == 'c')
- && (data[++index] == 't')
- && (data[++index] == 'i')
- && (data[++index] == 'o')
- && (data[++index] == 'n'))
- return TokenNamefunction;
- else
- return TokenNameIdentifier;
-
- default :
- return TokenNameIdentifier;
- }
- case 'g' : //goto
- if (length == 4) {
- if ((data[++index] == 'o')
- && (data[++index] == 't')
- && (data[++index] == 'o')) {
- return TokenNamegoto;
- }
- } //no goto in java are allowed, so why java removes this keyword ???
- return TokenNameIdentifier;
-
- case 'i' : //if implements import instanceof int interface
- switch (length) {
- case 2 :
- if (data[++index] == 'f')
- return TokenNameif;
- else if (data[index] == 'n')
- return TokenNamein;
- else
- return TokenNameIdentifier;
- case 3 :
- if ((data[++index] == 'n') && (data[++index] == 't'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNameint;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- else
- return TokenNameIdentifier;
- case 6 :
- if ((data[++index] == 'm')
- && (data[++index] == 'p')
- && (data[++index] == 'o')
- && (data[++index] == 'r')
- && (data[++index] == 't'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNameimport;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- else
- return TokenNameIdentifier;
- case 9 :
- if ((data[++index] == 'n')
- && (data[++index] == 't')
- && (data[++index] == 'e')
- && (data[++index] == 'r')
- && (data[++index] == 'f')
- && (data[++index] == 'a')
- && (data[++index] == 'c')
- && (data[++index] == 'e'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNameinterface;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- else
- return TokenNameIdentifier;
- case 10 :
- if (data[++index] == 'm')
- if ((data[++index] == 'p')
- && (data[++index] == 'l')
- && (data[++index] == 'e')
- && (data[++index] == 'm')
- && (data[++index] == 'e')
- && (data[++index] == 'n')
- && (data[++index] == 't')
- && (data[++index] == 's'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNameimplements;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- else
- return TokenNameIdentifier;
- else
- if ((data[index] == 'n')
- && (data[++index] == 's')
- && (data[++index] == 't')
- && (data[++index] == 'a')
- && (data[++index] == 'n')
- && (data[++index] == 'c')
- && (data[++index] == 'e')
- && (data[++index] == 'o')
- && (data[++index] == 'f'))
- return TokenNameinstanceof;
- else
- return TokenNameIdentifier;
-
- default :
- return TokenNameIdentifier;
- }
-
- case 'l' : //long
- if (length == 4) {
- if ((data[++index] == 'o')
- && (data[++index] == 'n')
- && (data[++index] == 'g')) {
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNamelong;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- }
- }
- return TokenNameIdentifier;
-
- case 'n' : //native new null
- switch (length) {
- case 3 :
- if ((data[++index] == 'e') && (data[++index] == 'w'))
- return TokenNamenew;
- else
- return TokenNameIdentifier;
- case 4 :
- if ((data[++index] == 'u') && (data[++index] == 'l') && (data[++index] == 'l'))
- return TokenNamenull;
- else
- return TokenNameIdentifier;
- case 6 :
- if ((data[++index] == 'a')
- && (data[++index] == 't')
- && (data[++index] == 'i')
- && (data[++index] == 'v')
- && (data[++index] == 'e')) {
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNamenative;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- } else
- return TokenNameIdentifier;
- default :
- return TokenNameIdentifier;
- }
-
- case 'p' : //package private protected public
- switch (length) {
- case 6 :
- if ((data[++index] == 'u')
- && (data[++index] == 'b')
- && (data[++index] == 'l')
- && (data[++index] == 'i')
- && (data[++index] == 'c')) {
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNamepublic;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- } else
- return TokenNameIdentifier;
- case 7 :
- if (data[++index] == 'a')
- if ((data[++index] == 'c')
- && (data[++index] == 'k')
- && (data[++index] == 'a')
- && (data[++index] == 'g')
- && (data[++index] == 'e'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNamepackage;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- else
- return TokenNameIdentifier;
- else
- if ((data[index] == 'r')
- && (data[++index] == 'i')
- && (data[++index] == 'v')
- && (data[++index] == 'a')
- && (data[++index] == 't')
- && (data[++index] == 'e')) {
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNameprivate;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- } else
- return TokenNameIdentifier;
- case 9 :
- if ((data[++index] == 'r')
- && (data[++index] == 'o')
- && (data[++index] == 't')
- && (data[++index] == 'e')
- && (data[++index] == 'c')
- && (data[++index] == 't')
- && (data[++index] == 'e')
- && (data[++index] == 'd')) {
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNameprotected;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- } else
- return TokenNameIdentifier;
-
- default :
- return TokenNameIdentifier;
- }
-
- case 'r' : //return
- if (length == 6) {
- if ((data[++index] == 'e')
- && (data[++index] == 't')
- && (data[++index] == 'u')
- && (data[++index] == 'r')
- && (data[++index] == 'n')) {
- return TokenNamereturn;
- }
- }
- return TokenNameIdentifier;
-
- case 's' : //short static super switch synchronized strictfp
- switch (length) {
- case 5 :
- if (data[++index] == 'h')
- if ((data[++index] == 'o') && (data[++index] == 'r') && (data[++index] == 't'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNameshort;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- else
- return TokenNameIdentifier;
- else
- if ((data[index] == 'u')
- && (data[++index] == 'p')
- && (data[++index] == 'e')
- && (data[++index] == 'r'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNamesuper;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- else
- return TokenNameIdentifier;
-
- case 6 :
- if (data[++index] == 't')
- if ((data[++index] == 'a')
- && (data[++index] == 't')
- && (data[++index] == 'i')
- && (data[++index] == 'c')) {
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNamestatic;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- } else
- return TokenNameIdentifier;
- else
- if ((data[index] == 'w')
- && (data[++index] == 'i')
- && (data[++index] == 't')
- && (data[++index] == 'c')
- && (data[++index] == 'h'))
- return TokenNameswitch;
- else
- return TokenNameIdentifier;
- case 12 :
- if ((data[++index] == 'y')
- && (data[++index] == 'n')
- && (data[++index] == 'c')
- && (data[++index] == 'h')
- && (data[++index] == 'r')
- && (data[++index] == 'o')
- && (data[++index] == 'n')
- && (data[++index] == 'i')
- && (data[++index] == 'z')
- && (data[++index] == 'e')
- && (data[++index] == 'd')) {
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNamesynchronized;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- } else
- return TokenNameIdentifier;
- default :
- return TokenNameIdentifier;
- }
-
- case 't' : //try throw throws transient this true
- switch (length) {
- case 3 :
- if ((data[++index] == 'r') && (data[++index] == 'y'))
- return TokenNametry;
- else
- return TokenNameIdentifier;
- case 4 :
- if (data[++index] == 'h')
- if ((data[++index] == 'i') && (data[++index] == 's'))
- return TokenNamethis;
- else
- return TokenNameIdentifier;
- else
- if ((data[index] == 'r') && (data[++index] == 'u') && (data[++index] == 'e'))
- return TokenNametrue;
- else
- return TokenNameIdentifier;
- case 5 :
- if ((data[++index] == 'h')
- && (data[++index] == 'r')
- && (data[++index] == 'o')
- && (data[++index] == 'w'))
- return TokenNamethrow;
- else
- return TokenNameIdentifier;
- case 6 :
- if ((data[++index] == 'h')
- && (data[++index] == 'r')
- && (data[++index] == 'o')
- && (data[++index] == 'w')
- && (data[++index] == 's'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNamethrows;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- else
- if ((data[index] == 'y')
- && (data[++index] == 'p')
- && (data[++index] == 'e')
- && (data[++index] == 'o')
- && (data[++index] == 'f'))
- return TokenNametypeof;
- else
- return TokenNameIdentifier;
- case 9 :
- if ((data[++index] == 'r')
- && (data[++index] == 'a')
- && (data[++index] == 'n')
- && (data[++index] == 's')
- && (data[++index] == 'i')
- && (data[++index] == 'e')
- && (data[++index] == 'n')
- && (data[++index] == 't')) {
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNametransient;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- } else
- return TokenNameIdentifier;
-
- default :
- return TokenNameIdentifier;
- }
-
-// case 'u' : //goto
-// if (length == 9) {
-// if ((data[++index] == 'n')
-// && (data[++index] == 'd')
-// && (data[++index] == 'e')
-// && (data[++index] == 'f')
-// && (data[++index] == 'i')
-// && (data[++index] == 'n')
-// && (data[++index] == 'e')
-// && (data[++index] == 'd')) {
-// return TokenNameIdentifier;
-// }
-// } //no goto in java are allowed, so why java removes this keyword ???
-// return TokenNameIdentifier;
-
- case 'v' : //void volatile
- switch (length) {
- case 3 :
- if ((data[++index] == 'a') && (data[++index] == 'r'))
- return TokenNamevar;
- else
- return TokenNameIdentifier;
- case 4 :
- if ((data[++index] == 'o') && (data[++index] == 'i') && (data[++index] == 'd'))
- return TokenNamevoid;
- else
- return TokenNameIdentifier;
- case 8 :
- if ((data[++index] == 'o')
- && (data[++index] == 'l')
- && (data[++index] == 'a')
- && (data[++index] == 't')
- && (data[++index] == 'i')
- && (data[++index] == 'l')
- && (data[++index] == 'e')) {
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNamevolatile;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- } else
- return TokenNameIdentifier;
-
- default :
- return TokenNameIdentifier;
- }
-
- case 'w' : //while widefp
- switch (length) {
- case 4 :
- if ((data[++index] == 'i')
- && (data[++index] == 't')
- && (data[++index] == 'h'))
- return TokenNamewith;
- else
- return TokenNameIdentifier;
- case 5 :
- if ((data[++index] == 'h')
- && (data[++index] == 'i')
- && (data[++index] == 'l')
- && (data[++index] == 'e'))
- return TokenNamewhile;
- else
- return TokenNameIdentifier;
- //case 6:if ( (data[++index] =='i') && (data[++index]=='d') && (data[++index]=='e') && (data[++index]=='f')&& (data[++index]=='p'))
- //return TokenNamewidefp ;
- //else
- //return TokenNameIdentifier;
- default :
- return TokenNameIdentifier;
- }
-
- default :
- return TokenNameIdentifier;
- }
-}
-
-
-public int scanNumber(boolean dotPrefix) throws InvalidInputException {
-
- //when entering this method the currentCharacter is the first
- //digit of the number. It may be preceeded by a '.' when
- //dotPrefix is true
-
- boolean floating = dotPrefix;
- if ((!dotPrefix) && (this.currentCharacter == '0')) {
- if (getNextChar('x', 'X') >= 0) { //----------hexa-----------------
- int start = this.currentPosition;
- while (getNextCharAsDigit(16)){/*empty*/}
- int end = this.currentPosition;
- if (getNextChar('l', 'L') >= 0) {
- if (end == start) {
- throw new InvalidInputException(INVALID_HEXA);
- }
- return TokenNameLongLiteral;
- } else if (getNextChar('.')) {
- if (this.sourceLevel < ClassFileConstants.JDK1_5) {
- if (end == start) {
- throw new InvalidInputException(INVALID_HEXA);
- }
- this.currentPosition = end;
- return TokenNameIntegerLiteral;
- }
- // hexadecimal floating point literal
- // read decimal part
- boolean hasNoDigitsBeforeDot = end == start;
- start = this.currentPosition;
- while (getNextCharAsDigit(16)){/*empty*/}
- end = this.currentPosition;
- if (hasNoDigitsBeforeDot && end == start) {
- throw new InvalidInputException(INVALID_HEXA);
- }
-
- if (getNextChar('p', 'P') >= 0) { // consume next character
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- } else {
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
-
- if ((this.currentCharacter == '-')
- || (this.currentCharacter == '+')) { // consume next character
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- } else {
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
- }
- if (!ScannerHelper.isDigit(this.currentCharacter)) {
- throw new InvalidInputException(INVALID_HEXA);
- }
- while (getNextCharAsDigit()){/*empty*/}
- if (getNextChar('f', 'F') >= 0) {
- return TokenNameFloatingPointLiteral;
- }
- if (getNextChar('d', 'D') >= 0) {
- return TokenNameDoubleLiteral;
- }
- if (getNextChar('l', 'L') >= 0) {
- throw new InvalidInputException(INVALID_HEXA);
- }
- return TokenNameDoubleLiteral;
- } else {
- throw new InvalidInputException(INVALID_HEXA);
- }
- } else if (getNextChar('p', 'P') >= 0) { // consume next character
- if (this.sourceLevel < ClassFileConstants.JDK1_5) {
- // if we are in source level < 1.5 we report an integer literal
- this.currentPosition = end;
- return TokenNameIntegerLiteral;
- }
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- } else {
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
-
- if ((this.currentCharacter == '-')
- || (this.currentCharacter == '+')) { // consume next character
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- } else {
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
- }
- if (!ScannerHelper.isDigit(this.currentCharacter))
- throw new InvalidInputException(INVALID_FLOAT);
- while (getNextCharAsDigit()){/*empty*/}
- if (getNextChar('f', 'F') >= 0)
- return TokenNameFloatingPointLiteral;
- if (getNextChar('d', 'D') >= 0)
- return TokenNameDoubleLiteral;
- if (getNextChar('l', 'L') >= 0) {
- throw new InvalidInputException(INVALID_HEXA);
- }
- return TokenNameDoubleLiteral;
- } else {
- if (end == start)
- throw new InvalidInputException(INVALID_HEXA);
- return TokenNameIntegerLiteral;
- }
- }
-
- //there is x or X in the number
- //potential octal ! ... some one may write 000099.0 ! thus 00100 < 00078.0 is true !!!!! crazy language
- if (getNextCharAsDigit()) { //-------------potential octal-----------------
- while (getNextCharAsDigit()){/*empty*/}
-
- if (getNextChar('l', 'L') >= 0) {
- return TokenNameLongLiteral;
- }
-
- if (getNextChar('f', 'F') >= 0) {
- return TokenNameFloatingPointLiteral;
- }
-
- if (getNextChar('d', 'D') >= 0) {
- return TokenNameDoubleLiteral;
- } else { //make the distinction between octal and float ....
- boolean isInteger = true;
- if (getNextChar('.')) {
- isInteger = false;
- while (getNextCharAsDigit()){/*empty*/}
- }
- if (getNextChar('e', 'E') >= 0) { // consume next character
- isInteger = false;
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- } else {
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
-
- if ((this.currentCharacter == '-')
- || (this.currentCharacter == '+')) { // consume next character
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- } else {
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
- }
- if (!ScannerHelper.isDigit(this.currentCharacter))
- throw new InvalidInputException(INVALID_FLOAT);
- while (getNextCharAsDigit()){/*empty*/}
- }
- if (getNextChar('f', 'F') >= 0)
- return TokenNameFloatingPointLiteral;
- if (getNextChar('d', 'D') >= 0 || !isInteger)
- return TokenNameDoubleLiteral;
- return TokenNameIntegerLiteral;
- }
- } else {
- /* carry on */
- }
- }
-
- while (getNextCharAsDigit()){/*empty*/}
-
- if ((!dotPrefix) && (getNextChar('l', 'L') >= 0))
- return TokenNameLongLiteral;
-
- if ((!dotPrefix) && (getNextChar('.'))) { //decimal part that can be empty
- while (getNextCharAsDigit()){/*empty*/}
- floating = true;
- }
-
- //if floating is true both exponant and suffix may be optional
-
- if (getNextChar('e', 'E') >= 0) {
- floating = true;
- // consume next character
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- } else {
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
-
- if ((this.currentCharacter == '-')
- || (this.currentCharacter == '+')) { // consume next character
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- } else {
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
- }
- if (!ScannerHelper.isDigit(this.currentCharacter))
- throw new InvalidInputException(INVALID_FLOAT);
- while (getNextCharAsDigit()){/*empty*/}
- }
-
- if (getNextChar('d', 'D') >= 0)
- return TokenNameDoubleLiteral;
- if (getNextChar('f', 'F') >= 0)
- return TokenNameFloatingPointLiteral;
-
- //the long flag has been tested before
-
- return floating ? TokenNameDoubleLiteral : TokenNameIntegerLiteral;
-}
-/**
- * Search the line number corresponding to a specific position
- * @param position int
- * @return int
- */
-public final int getLineNumber(int position) {
- return Util.getLineNumber(position, this.lineEnds, 0, this.linePtr);
-}
-public void setSource(char[] sourceString){
- //the source-buffer is set to sourceString
-
- int sourceLength;
- if (sourceString == null) {
- this.source = CharOperation.NO_CHAR;
- sourceLength = 0;
- } else {
- this.source = sourceString;
- sourceLength = sourceString.length;
- }
- this.startPosition = -1;
- this.eofPosition = sourceLength;
- this.initialPosition = this.currentPosition = 0;
- this.containsAssertKeyword = false;
- this.linePtr = -1;
-}
-/*
- * Should be used if a parse (usually a diet parse) has already been performed on the unit,
- * so as to get the already computed line end positions.
- */
-public final void setSource(char[] contents, CompilationResult compilationResult) {
- if (contents == null) {
- char[] cuContents = compilationResult.compilationUnit.getContents();
- setSource(cuContents);
- } else {
- setSource(contents);
- }
- int[] lineSeparatorPositions = compilationResult.lineSeparatorPositions;
- if (lineSeparatorPositions != null) {
- this.lineEnds = lineSeparatorPositions;
- this.linePtr = lineSeparatorPositions.length - 1;
- }
-}
-/*
- * Should be used if a parse (usually a diet parse) has already been performed on the unit,
- * so as to get the already computed line end positions.
- */
-public final void setSource(CompilationResult compilationResult) {
- setSource(null, compilationResult);
-}
-public String toString() {
- if (this.startPosition == this.eofPosition)
- return "EOF\n\n" + new String(this.source); //$NON-NLS-1$
- if (this.currentPosition > this.eofPosition)
- return "behind the EOF\n\n" + new String(this.source); //$NON-NLS-1$
-
- char front[] = new char[this.startPosition];
- System.arraycopy(this.source, 0, front, 0, this.startPosition);
-
- int middleLength = (this.currentPosition - 1) - this.startPosition + 1;
- char middle[];
- if (middleLength > -1) {
- middle = new char[middleLength];
- System.arraycopy(
- this.source,
- this.startPosition,
- middle,
- 0,
- middleLength);
- } else {
- middle = CharOperation.NO_CHAR;
- }
-
- char end[] = new char[this.eofPosition - (this.currentPosition - 1)];
- System.arraycopy(
- this.source,
- (this.currentPosition - 1) + 1,
- end,
- 0,
- this.eofPosition - (this.currentPosition - 1) - 1);
-
- return new String(front)
- + "\n===============================\nStarts here -->" //$NON-NLS-1$
- + new String(middle)
- + "<-- Ends here\n===============================\n" //$NON-NLS-1$
- + new String(end);
-}
-
-public String dumpCurrent()
-{
- return "token='"+toStringAction(currentToken)+"', position="+currentPosition; //$NON-NLS-1$ //$NON-NLS-2$
-}
-
-public String toStringAction(int act) {
- switch (act) {
- case TokenNameIdentifier :
- return "Identifier(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$
- case TokenNameabstract :
- return "abstract"; //$NON-NLS-1$
- case TokenNameboolean :
- return "boolean"; //$NON-NLS-1$
- case TokenNamebreak :
- return "break"; //$NON-NLS-1$
- case TokenNamebyte :
- return "byte"; //$NON-NLS-1$
- case TokenNamecase :
- return "case"; //$NON-NLS-1$
- case TokenNamecatch :
- return "catch"; //$NON-NLS-1$
- case TokenNamechar :
- return "char"; //$NON-NLS-1$
- case TokenNameclass :
- return "class"; //$NON-NLS-1$
- case TokenNamecontinue :
- return "continue"; //$NON-NLS-1$
- case TokenNamedelete :
- return "delete"; //$NON-NLS-1$
- case TokenNamedebugger :
- return "debugger"; //$NON-NLS-1$
- case TokenNamedefault :
- return "default"; //$NON-NLS-1$
- case TokenNamedo :
- return "do"; //$NON-NLS-1$
- case TokenNamedouble :
- return "double"; //$NON-NLS-1$
- case TokenNameelse :
- return "else"; //$NON-NLS-1$
- case TokenNameexport :
- return "export"; //$NON-NLS-1$
- case TokenNameextends :
- return "extends"; //$NON-NLS-1$
- case TokenNamefalse :
- return "false"; //$NON-NLS-1$
- case TokenNamefinal :
- return "final"; //$NON-NLS-1$
- case TokenNamefinally :
- return "finally"; //$NON-NLS-1$
- case TokenNamefloat :
- return "float"; //$NON-NLS-1$
- case TokenNamefunction :
- return "function"; //$NON-NLS-1$
- case TokenNamefor :
- return "for"; //$NON-NLS-1$
- case TokenNameif :
- return "if"; //$NON-NLS-1$
- case TokenNameimplements :
- return "implements"; //$NON-NLS-1$
- case TokenNameimport :
- return "import"; //$NON-NLS-1$
- case TokenNameinstanceof :
- return "instanceof"; //$NON-NLS-1$
- case TokenNameint :
- return "int"; //$NON-NLS-1$
- case TokenNamein :
- return "in"; //$NON-NLS-1$
- case TokenNameinterface :
- return "interface"; //$NON-NLS-1$
- case TokenNamelong :
- return "long"; //$NON-NLS-1$
- case TokenNamenative :
- return "native"; //$NON-NLS-1$
- case TokenNamenew :
- return "new"; //$NON-NLS-1$
- case TokenNamenull :
- return "null"; //$NON-NLS-1$
- case TokenNamepackage :
- return "package"; //$NON-NLS-1$
- case TokenNameprivate :
- return "private"; //$NON-NLS-1$
- case TokenNameprotected :
- return "protected"; //$NON-NLS-1$
- case TokenNamepublic :
- return "public"; //$NON-NLS-1$
- case TokenNamereturn :
- return "return"; //$NON-NLS-1$
- case TokenNameshort :
- return "short"; //$NON-NLS-1$
- case TokenNamestatic :
- return "static"; //$NON-NLS-1$
- case TokenNamesuper :
- return "super"; //$NON-NLS-1$
- case TokenNameswitch :
- return "switch"; //$NON-NLS-1$
- case TokenNamesynchronized :
- return "synchronized"; //$NON-NLS-1$
- case TokenNamethis :
- return "this"; //$NON-NLS-1$
- case TokenNamethrow :
- return "throw"; //$NON-NLS-1$
- case TokenNamethrows :
- return "throws"; //$NON-NLS-1$
- case TokenNametransient :
- return "transient"; //$NON-NLS-1$
- case TokenNametrue :
- return "true"; //$NON-NLS-1$
- case TokenNametry :
- return "try"; //$NON-NLS-1$
- case TokenNamevoid :
- return "void"; //$NON-NLS-1$
- case TokenNameundefined :
- return "undefined"; //$NON-NLS-1$
- case TokenNamevar :
- return "var"; //$NON-NLS-1$
- case TokenNamevolatile :
- return "volatile"; //$NON-NLS-1$
- case TokenNamewhile :
- return "while"; //$NON-NLS-1$
- case TokenNamewith :
- return "with"; //$NON-NLS-1$
-
- case TokenNameIntegerLiteral :
- return "Integer(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$
- case TokenNameLongLiteral :
- return "Long(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$
- case TokenNameFloatingPointLiteral :
- return "Float(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$
- case TokenNameDoubleLiteral :
- return "Double(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$
- case TokenNameCharacterLiteral :
- return "Char(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$
- case TokenNameStringLiteral :
- return "String(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$
- case TokenNameRegExLiteral :
- return "RegExp(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$
- case TokenNamePLUS_PLUS :
- return "++"; //$NON-NLS-1$
- case TokenNameMINUS_MINUS :
- return "--"; //$NON-NLS-1$
- case TokenNameEQUAL_EQUAL :
- return "=="; //$NON-NLS-1$
- case TokenNameEQUAL_EQUAL_EQUAL :
- return "==="; //$NON-NLS-1$
- case TokenNameLESS_EQUAL :
- return "<="; //$NON-NLS-1$
- case TokenNameGREATER_EQUAL :
- return ">="; //$NON-NLS-1$
- case TokenNameNOT_EQUAL :
- return "!="; //$NON-NLS-1$
- case TokenNameNOT_EQUAL_EQUAL :
- return "!=="; //$NON-NLS-1$
- case TokenNameLEFT_SHIFT :
- return "<<"; //$NON-NLS-1$
- case TokenNameRIGHT_SHIFT :
- return ">>"; //$NON-NLS-1$
- case TokenNameUNSIGNED_RIGHT_SHIFT :
- return ">>>"; //$NON-NLS-1$
- case TokenNamePLUS_EQUAL :
- return "+="; //$NON-NLS-1$
- case TokenNameMINUS_EQUAL :
- return "-="; //$NON-NLS-1$
- case TokenNameMULTIPLY_EQUAL :
- return "*="; //$NON-NLS-1$
- case TokenNameDIVIDE_EQUAL :
- return "/="; //$NON-NLS-1$
- case TokenNameAND_EQUAL :
- return "&="; //$NON-NLS-1$
- case TokenNameOR_EQUAL :
- return "|="; //$NON-NLS-1$
- case TokenNameXOR_EQUAL :
- return "^="; //$NON-NLS-1$
- case TokenNameREMAINDER_EQUAL :
- return "%="; //$NON-NLS-1$
- case TokenNameLEFT_SHIFT_EQUAL :
- return "<<="; //$NON-NLS-1$
- case TokenNameRIGHT_SHIFT_EQUAL :
- return ">>="; //$NON-NLS-1$
- case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL :
- return ">>>="; //$NON-NLS-1$
- case TokenNameOR_OR :
- return "||"; //$NON-NLS-1$
- case TokenNameAND_AND :
- return "&&"; //$NON-NLS-1$
- case TokenNamePLUS :
- return "+"; //$NON-NLS-1$
- case TokenNameMINUS :
- return "-"; //$NON-NLS-1$
- case TokenNameNOT :
- return "!"; //$NON-NLS-1$
- case TokenNameREMAINDER :
- return "%"; //$NON-NLS-1$
- case TokenNameXOR :
- return "^"; //$NON-NLS-1$
- case TokenNameAND :
- return "&"; //$NON-NLS-1$
- case TokenNameMULTIPLY :
- return "*"; //$NON-NLS-1$
- case TokenNameOR :
- return "|"; //$NON-NLS-1$
- case TokenNameTWIDDLE :
- return "~"; //$NON-NLS-1$
- case TokenNameDIVIDE :
- return "/"; //$NON-NLS-1$
- case TokenNameGREATER :
- return ">"; //$NON-NLS-1$
- case TokenNameLESS :
- return "<"; //$NON-NLS-1$
- case TokenNameLPAREN :
- return "("; //$NON-NLS-1$
- case TokenNameRPAREN :
- return ")"; //$NON-NLS-1$
- case TokenNameLBRACE :
- return "{"; //$NON-NLS-1$
- case TokenNameRBRACE :
- return "}"; //$NON-NLS-1$
- case TokenNameLBRACKET :
- return "["; //$NON-NLS-1$
- case TokenNameRBRACKET :
- return "]"; //$NON-NLS-1$
- case TokenNameSEMICOLON :
- return ";"; //$NON-NLS-1$
- case TokenNameQUESTION :
- return "?"; //$NON-NLS-1$
- case TokenNameCOLON :
- return ":"; //$NON-NLS-1$
- case TokenNameCOMMA :
- return ","; //$NON-NLS-1$
- case TokenNameDOT :
- return "."; //$NON-NLS-1$
- case TokenNameEQUAL :
- return "="; //$NON-NLS-1$
- case TokenNameEOF :
- return "EOF"; //$NON-NLS-1$
- case TokenNameWHITESPACE :
- return "white_space(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$
- default :
- return "not-a-token"; //$NON-NLS-1$
- }
-}
-public void unicodeInitializeBuffer(int length) {
- this.withoutUnicodePtr = length;
- if (this.withoutUnicodeBuffer == null) this.withoutUnicodeBuffer = new char[length+(1+10)];
- int bLength = this.withoutUnicodeBuffer.length;
- if (1+length >= bLength) {
- System.arraycopy(this.withoutUnicodeBuffer, 0, this.withoutUnicodeBuffer = new char[length + (1+10)], 0, bLength);
- }
- System.arraycopy(this.source, this.startPosition, this.withoutUnicodeBuffer, 1, length);
-}
-public void unicodeStore() {
- int pos = ++this.withoutUnicodePtr;
- if (this.withoutUnicodeBuffer == null) this.withoutUnicodeBuffer = new char[10];
- int length = this.withoutUnicodeBuffer.length;
- if (pos == length) {
- System.arraycopy(this.withoutUnicodeBuffer, 0, this.withoutUnicodeBuffer = new char[length * 2], 0, length);
- }
- this.withoutUnicodeBuffer[pos] = this.currentCharacter;
-}
-
-public void pushBack() {
- pushedBack=true;
-}
-
-/*
- * This code is duplicated in PublicScanner.java
- */
-protected boolean checkIfDivide(int previousToken){
-
- if (previousToken == TokenNameIdentifier || previousToken == TokenNameStringLiteral ||
- previousToken == TokenNameCharacterLiteral ||
- previousToken == TokenNameIntegerLiteral ||
- previousToken == TokenNameDoubleLiteral ||
- previousToken == TokenNameLongLiteral ||
- previousToken == TokenNameRPAREN ||
- previousToken == TokenNameRBRACKET ||
- previousToken == TokenNameUNKNOWN) {
-
- return true;
- }
-
- return false;
-}
-
-/*
- * This code is duplicated in PublicScanner.java
- */
-
-public static final String NON_TERM_REGEXP = Messages.Scanner_NON_TERM_REGEXP;
-public static final String INVALID_REGEXP_OPT = Messages.Scanner_INVALID_REGEXP_OPT;
-public static final String UNEXP_REGEXP = Messages.Scanner_UNEXP_REGEXP;
-
-protected boolean checkIfRegExp() throws IndexOutOfBoundsException, InvalidInputException {
- // Try to process as regular expression
-
- int regExpPosition = this.currentPosition;
- char orginalCharacter = this.currentCharacter;
- char previousCharacter = this.currentCharacter;
- int previousPosition = this.currentPosition;
- int previousUnicodePtr = this.withoutUnicodePtr;
- boolean regExp = false;
-
- // consume next character
- this.unicodeAsBackSlash = false;
- this.currentCharacter = this.source[this.currentPosition++];
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
-
- try {
- loop: while (true) {
-
- switch(this.currentCharacter) {
- case '\\' :
- // read next character
- this.unicodeAsBackSlash = false;
- this.currentCharacter = this.source[this.currentPosition++];
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- break;
- case '/' :
- regExp = true;
- break loop;
- case '\r' :
- case '\n' :
- break loop;
- }
-
- // consume next character
- previousCharacter=this.currentCharacter;
- previousPosition=this.currentPosition;
- previousUnicodePtr=this.withoutUnicodePtr;
- this.currentCharacter = this.source[this.currentPosition++];
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
-
- // Check for valid RegExp options
- if (regExp) {
- for (int count = 0; count <= 3; count++) {
- previousCharacter=this.currentCharacter;
- previousPosition=this.currentPosition;
- previousUnicodePtr=this.withoutUnicodePtr;
- if (getNextChar() != -1) {
- if (Character.isLetterOrDigit(this.currentCharacter)) {
- switch(this.currentCharacter) {
- case 'i' :
- case 'g' :
- case 'm' :
- break;
- default :
- if (count != 3) {
- throw new InvalidInputException(INVALID_REGEXP_OPT);
- }
- }
- } else {
- break;
- }
- } else {
- break;
- }
- }
- }
- } catch (IndexOutOfBoundsException e) {
- throw new InvalidInputException(NON_TERM_REGEXP);
- }
-
- if (!regExp){
- this.currentCharacter=orginalCharacter;
- this.currentPosition=regExpPosition;
- return false;
- }
- // Back up one character
- this.currentCharacter = previousCharacter;
- this.currentPosition = previousPosition;
- this.withoutUnicodePtr = previousUnicodePtr;
- return true;
-}
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/ScannerHelper.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/ScannerHelper.java
deleted file mode 100644
index 19bb6cf8..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/ScannerHelper.java
+++ /dev/null
@@ -1,355 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.parser;
-
-import java.io.DataInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode;
-
-public class ScannerHelper {
-
- public final static long[] Bits = {
- ASTNode.Bit1, ASTNode.Bit2, ASTNode.Bit3, ASTNode.Bit4, ASTNode.Bit5, ASTNode.Bit6,
- ASTNode.Bit7, ASTNode.Bit8, ASTNode.Bit9, ASTNode.Bit10, ASTNode.Bit11, ASTNode.Bit12,
- ASTNode.Bit13, ASTNode.Bit14, ASTNode.Bit15, ASTNode.Bit16, ASTNode.Bit17, ASTNode.Bit18,
- ASTNode.Bit19, ASTNode.Bit20, ASTNode.Bit21, ASTNode.Bit22, ASTNode.Bit23, ASTNode.Bit24,
- ASTNode.Bit25, ASTNode.Bit26, ASTNode.Bit27, ASTNode.Bit28, ASTNode.Bit29, ASTNode.Bit30,
- ASTNode.Bit31, ASTNode.Bit32, ASTNode.Bit33L, ASTNode.Bit34L, ASTNode.Bit35L, ASTNode.Bit36L,
- ASTNode.Bit37L, ASTNode.Bit38L, ASTNode.Bit39L, ASTNode.Bit40L, ASTNode.Bit41L, ASTNode.Bit42L,
- ASTNode.Bit43L, ASTNode.Bit44L, ASTNode.Bit45L, ASTNode.Bit46L, ASTNode.Bit47L, ASTNode.Bit48L,
- ASTNode.Bit49L, ASTNode.Bit50L, ASTNode.Bit51L, ASTNode.Bit52L, ASTNode.Bit53L, ASTNode.Bit54L,
- ASTNode.Bit55L, ASTNode.Bit56L, ASTNode.Bit57L, ASTNode.Bit58L, ASTNode.Bit59L, ASTNode.Bit60L,
- ASTNode.Bit61L, ASTNode.Bit62L, ASTNode.Bit63L, ASTNode.Bit64L,
- };
-
- private static final int START_INDEX = 0;
- private static final int PART_INDEX = 1;
-
- private static long[][][] Tables;
-
- public final static int MAX_OBVIOUS = 128;
- public final static int[] OBVIOUS_IDENT_CHAR_NATURES = new int[MAX_OBVIOUS];
-
- public final static int C_JLS_SPACE = ASTNode.Bit9;
- public final static int C_SPECIAL = ASTNode.Bit8;
- public final static int C_IDENT_START = ASTNode.Bit7;
- public final static int C_UPPER_LETTER = ASTNode.Bit6;
- public final static int C_LOWER_LETTER = ASTNode.Bit5;
- public final static int C_IDENT_PART = ASTNode.Bit4;
- public final static int C_DIGIT = ASTNode.Bit3;
- public final static int C_SEPARATOR = ASTNode.Bit2;
- public final static int C_SPACE = ASTNode.Bit1;
-
- static {
- OBVIOUS_IDENT_CHAR_NATURES[0] = C_IDENT_PART;
- OBVIOUS_IDENT_CHAR_NATURES[1] = C_IDENT_PART;
- OBVIOUS_IDENT_CHAR_NATURES[2] = C_IDENT_PART;
- OBVIOUS_IDENT_CHAR_NATURES[3] = C_IDENT_PART;
- OBVIOUS_IDENT_CHAR_NATURES[4] = C_IDENT_PART;
- OBVIOUS_IDENT_CHAR_NATURES[5] = C_IDENT_PART;
- OBVIOUS_IDENT_CHAR_NATURES[6] = C_IDENT_PART;
- OBVIOUS_IDENT_CHAR_NATURES[7] = C_IDENT_PART;
- OBVIOUS_IDENT_CHAR_NATURES[8] = C_IDENT_PART;
- OBVIOUS_IDENT_CHAR_NATURES[14] = C_IDENT_PART;
- OBVIOUS_IDENT_CHAR_NATURES[15] = C_IDENT_PART;
- OBVIOUS_IDENT_CHAR_NATURES[16] = C_IDENT_PART;
- OBVIOUS_IDENT_CHAR_NATURES[17] = C_IDENT_PART;
- OBVIOUS_IDENT_CHAR_NATURES[18] = C_IDENT_PART;
- OBVIOUS_IDENT_CHAR_NATURES[19] = C_IDENT_PART;
- OBVIOUS_IDENT_CHAR_NATURES[20] = C_IDENT_PART;
- OBVIOUS_IDENT_CHAR_NATURES[21] = C_IDENT_PART;
- OBVIOUS_IDENT_CHAR_NATURES[22] = C_IDENT_PART;
- OBVIOUS_IDENT_CHAR_NATURES[23] = C_IDENT_PART;
- OBVIOUS_IDENT_CHAR_NATURES[24] = C_IDENT_PART;
- OBVIOUS_IDENT_CHAR_NATURES[25] = C_IDENT_PART;
- OBVIOUS_IDENT_CHAR_NATURES[26] = C_IDENT_PART;
- OBVIOUS_IDENT_CHAR_NATURES[27] = C_IDENT_PART;
- OBVIOUS_IDENT_CHAR_NATURES[127] = C_IDENT_PART;
-
- for (int i = '0'; i <= '9'; i++)
- OBVIOUS_IDENT_CHAR_NATURES[i] = C_DIGIT | C_IDENT_PART;
-
- for (int i = 'a'; i <= 'z'; i++)
- OBVIOUS_IDENT_CHAR_NATURES[i] = C_LOWER_LETTER | C_IDENT_PART | C_IDENT_START;
- for (int i = 'A'; i <= 'Z'; i++)
- OBVIOUS_IDENT_CHAR_NATURES[i] = C_UPPER_LETTER | C_IDENT_PART | C_IDENT_START;
-
- OBVIOUS_IDENT_CHAR_NATURES['_'] = C_SPECIAL | C_IDENT_PART | C_IDENT_START;
- OBVIOUS_IDENT_CHAR_NATURES['$'] = C_SPECIAL | C_IDENT_PART | C_IDENT_START;
-
- OBVIOUS_IDENT_CHAR_NATURES[9] = C_SPACE | C_JLS_SPACE; // \ u0009: HORIZONTAL TABULATION
- OBVIOUS_IDENT_CHAR_NATURES[10] = C_SPACE | C_JLS_SPACE; // \ u000a: LINE FEED
- OBVIOUS_IDENT_CHAR_NATURES[11] = C_SPACE;
- OBVIOUS_IDENT_CHAR_NATURES[12] = C_SPACE | C_JLS_SPACE; // \ u000c: FORM FEED
- OBVIOUS_IDENT_CHAR_NATURES[13] = C_SPACE | C_JLS_SPACE; // \ u000d: CARRIAGE RETURN
- OBVIOUS_IDENT_CHAR_NATURES[28] = C_SPACE;
- OBVIOUS_IDENT_CHAR_NATURES[29] = C_SPACE;
- OBVIOUS_IDENT_CHAR_NATURES[30] = C_SPACE;
- OBVIOUS_IDENT_CHAR_NATURES[31] = C_SPACE;
- OBVIOUS_IDENT_CHAR_NATURES[32] = C_SPACE | C_JLS_SPACE; // \ u0020: SPACE
-
- OBVIOUS_IDENT_CHAR_NATURES['.'] = C_SEPARATOR;
- OBVIOUS_IDENT_CHAR_NATURES[':'] = C_SEPARATOR;
- OBVIOUS_IDENT_CHAR_NATURES[';'] = C_SEPARATOR;
- OBVIOUS_IDENT_CHAR_NATURES[','] = C_SEPARATOR;
- OBVIOUS_IDENT_CHAR_NATURES['['] = C_SEPARATOR;
- OBVIOUS_IDENT_CHAR_NATURES[']'] = C_SEPARATOR;
- OBVIOUS_IDENT_CHAR_NATURES['('] = C_SEPARATOR;
- OBVIOUS_IDENT_CHAR_NATURES[')'] = C_SEPARATOR;
- OBVIOUS_IDENT_CHAR_NATURES['{'] = C_SEPARATOR;
- OBVIOUS_IDENT_CHAR_NATURES['}'] = C_SEPARATOR;
- OBVIOUS_IDENT_CHAR_NATURES['+'] = C_SEPARATOR;
- OBVIOUS_IDENT_CHAR_NATURES['-'] = C_SEPARATOR;
- OBVIOUS_IDENT_CHAR_NATURES['*'] = C_SEPARATOR;
- OBVIOUS_IDENT_CHAR_NATURES['/'] = C_SEPARATOR;
- OBVIOUS_IDENT_CHAR_NATURES['='] = C_SEPARATOR;
- OBVIOUS_IDENT_CHAR_NATURES['&'] = C_SEPARATOR;
- OBVIOUS_IDENT_CHAR_NATURES['|'] = C_SEPARATOR;
- OBVIOUS_IDENT_CHAR_NATURES['?'] = C_SEPARATOR;
- OBVIOUS_IDENT_CHAR_NATURES['<'] = C_SEPARATOR;
- OBVIOUS_IDENT_CHAR_NATURES['>'] = C_SEPARATOR;
- OBVIOUS_IDENT_CHAR_NATURES['!'] = C_SEPARATOR;
- OBVIOUS_IDENT_CHAR_NATURES['%'] = C_SEPARATOR;
- OBVIOUS_IDENT_CHAR_NATURES['^'] = C_SEPARATOR;
- OBVIOUS_IDENT_CHAR_NATURES['~'] = C_SEPARATOR;
- OBVIOUS_IDENT_CHAR_NATURES['"'] = C_SEPARATOR;
- OBVIOUS_IDENT_CHAR_NATURES['\''] = C_SEPARATOR;
- }
-
-static {
- Tables = new long[2][][];
- Tables[START_INDEX] = new long[2][];
- Tables[PART_INDEX] = new long[3][];
- try {
- DataInputStream inputStream = new DataInputStream(ScannerHelper.class.getResourceAsStream("start1.rsc")); //$NON-NLS-1$
- long[] readValues = new long[1024];
- for (int i = 0; i < 1024; i++) {
- readValues[i] = inputStream.readLong();
- }
- inputStream.close();
- Tables[START_INDEX][0] = readValues;
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- try {
- DataInputStream inputStream = new DataInputStream(ScannerHelper.class.getResourceAsStream("start2.rsc")); //$NON-NLS-1$
- long[] readValues = new long[1024];
- for (int i = 0; i < 1024; i++) {
- readValues[i] = inputStream.readLong();
- }
- inputStream.close();
- Tables[START_INDEX][1] = readValues;
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- try {
- DataInputStream inputStream = new DataInputStream(ScannerHelper.class.getResourceAsStream("part1.rsc")); //$NON-NLS-1$
- long[] readValues = new long[1024];
- for (int i = 0; i < 1024; i++) {
- readValues[i] = inputStream.readLong();
- }
- inputStream.close();
- Tables[PART_INDEX][0] = readValues;
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- try {
- DataInputStream inputStream = new DataInputStream(ScannerHelper.class.getResourceAsStream("part2.rsc")); //$NON-NLS-1$
- long[] readValues = new long[1024];
- for (int i = 0; i < 1024; i++) {
- readValues[i] = inputStream.readLong();
- }
- inputStream.close();
- Tables[PART_INDEX][1] = readValues;
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- try {
- DataInputStream inputStream = new DataInputStream(ScannerHelper.class.getResourceAsStream("part14.rsc")); //$NON-NLS-1$
- long[] readValues = new long[1024];
- for (int i = 0; i < 1024; i++) {
- readValues[i] = inputStream.readLong();
- }
- inputStream.close();
- Tables[PART_INDEX][2] = readValues;
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
-}
-
-private final static boolean isBitSet(long[] values, int i) {
- try {
- return (values[i / 64] & Bits[i % 64]) != 0;
- } catch (NullPointerException e) {
- return false;
- }
-}
-public static boolean isJavaIdentifierPart(char c) {
- if (c < MAX_OBVIOUS) {
- return (ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_PART) != 0;
- }
- return Character.isJavaIdentifierPart(c);
-}
-public static boolean isJavaIdentifierPart(char high, char low) {
- int codePoint = toCodePoint(high, low);
- switch((codePoint & 0x1F0000) >> 16) {
- case 0 :
- return Character.isJavaIdentifierPart((char) codePoint);
- case 1 :
- return isBitSet(Tables[PART_INDEX][0], codePoint & 0xFFFF);
- case 2 :
- return isBitSet(Tables[PART_INDEX][1], codePoint & 0xFFFF);
- case 14 :
- return isBitSet(Tables[PART_INDEX][2], codePoint & 0xFFFF);
- }
- return false;
-}
-public static boolean isJavaIdentifierStart(char c) {
- if (c < MAX_OBVIOUS) {
- return (ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0;
- }
- return Character.isJavaIdentifierStart(c);
-}
-public static boolean isJavaIdentifierStart(char high, char low) {
- int codePoint = toCodePoint(high, low);
- switch((codePoint & 0x1F0000) >> 16) {
- case 0 :
- return Character.isJavaIdentifierStart((char) codePoint);
- case 1 :
- return isBitSet(Tables[START_INDEX][0], codePoint & 0xFFFF);
- case 2 :
- return isBitSet(Tables[START_INDEX][1], codePoint & 0xFFFF);
- }
- return false;
-}
-
-private static int toCodePoint(char high, char low) {
- return (high - Scanner.HIGH_SURROGATE_MIN_VALUE) * 0x400 + (low - Scanner.LOW_SURROGATE_MIN_VALUE) + 0x10000;
-}
-public static boolean isDigit(char c) throws InvalidInputException {
- if(c < ScannerHelper.MAX_OBVIOUS) {
- return (ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0;
- }
- if (Character.isDigit(c)) {
- throw new InvalidInputException(Scanner.INVALID_DIGIT);
- }
- return false;
-}
-public static int digit(char c, int radix) {
- if (c < ScannerHelper.MAX_OBVIOUS) {
- switch(radix) {
- case 8 :
- if (c >= 48 && c <= 55) {
- return c - 48;
- }
- return -1;
- case 10 :
- if (c >= 48 && c <= 57) {
- return c - 48;
- }
- return -1;
- case 16 :
- if (c >= 48 && c <= 57) {
- return c - 48;
- }
- if (c >= 65 && c <= 70) {
- return c - 65 + 10;
- }
- if (c >= 97 && c <= 102) {
- return c - 97 + 10;
- }
- return -1;
- }
- }
- return Character.digit(c, radix);
-}
-public static int getNumericValue(char c) {
- if (c < ScannerHelper.MAX_OBVIOUS) {
- switch(ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c]) {
- case C_DIGIT :
- return c - '0';
- case C_LOWER_LETTER :
- return 10 + c - 'a';
- case C_UPPER_LETTER :
- return 10 + c - 'A';
- }
- }
- return Character.getNumericValue(c);
-}
-public static char toUpperCase(char c) {
- if (c < MAX_OBVIOUS) {
- if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_UPPER_LETTER) != 0) {
- return c;
- } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_LOWER_LETTER) != 0) {
- return (char) (c - 32);
- }
- }
- return Character.toLowerCase(c);
-}
-public static char toLowerCase(char c) {
- if (c < MAX_OBVIOUS) {
- if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_LOWER_LETTER) != 0) {
- return c;
- } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_UPPER_LETTER) != 0) {
- return (char) (32 + c);
- }
- }
- return Character.toLowerCase(c);
-}
-public static boolean isLowerCase(char c) {
- if (c < MAX_OBVIOUS) {
- return (ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_LOWER_LETTER) != 0;
- }
- return Character.isLowerCase(c);
-}
-public static boolean isUpperCase(char c) {
- if (c < MAX_OBVIOUS) {
- return (ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_UPPER_LETTER) != 0;
- }
- return Character.isUpperCase(c);
-}
-/**
- * Include also non JLS whitespaces.
- *
- * return true if Character.isWhitespace(c) would return true
- */
-public static boolean isWhitespace(char c) {
- if (c < MAX_OBVIOUS) {
- return (ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_SPACE) != 0;
- }
- return Character.isWhitespace(c);
-}
-public static boolean isLetter(char c) {
- if (c < MAX_OBVIOUS) {
- return (ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & (ScannerHelper.C_UPPER_LETTER | ScannerHelper.C_LOWER_LETTER)) != 0;
- }
- return Character.isLetter(c);
-}
-public static boolean isLetterOrDigit(char c) {
- if (c < MAX_OBVIOUS) {
- return (ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & (ScannerHelper.C_UPPER_LETTER | ScannerHelper.C_LOWER_LETTER | ScannerHelper.C_DIGIT)) != 0;
- }
- return Character.isLetterOrDigit(c);
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/SourceTypeConverter.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/SourceTypeConverter.java
deleted file mode 100644
index bbb116be..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/SourceTypeConverter.java
+++ /dev/null
@@ -1,862 +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.compiler.parser;
-
-/**
- * Converter from source element type to parsed compilation unit.
- *
- * Limitation:
- * | The source element field does not carry any information for its constant part, thus
- * | the converted parse tree will not include any field initializations.
- * | Therefore, any binary produced by compiling against converted source elements will
- * | not take advantage of remote field constant inlining.
- * | Given the intended purpose of the conversion is to resolve references, this is not
- * | a problem.
- *
- */
-
-import java.util.ArrayList;
-
-import org.eclipse.wst.jsdt.core.IImportDeclaration;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-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.internal.compiler.CompilationResult;
-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.ArrayInitializer;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ArrayQualifiedTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ArrayTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Block;
-import org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ConstructorDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Expression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration;
-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.MethodDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedAllocationExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedTypeReference;
-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.TypeDeclaration;
-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.env.ICompilationUnit;
-import org.eclipse.wst.jsdt.internal.compiler.env.ISourceImport;
-import org.eclipse.wst.jsdt.internal.compiler.env.ISourceType;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ExtraCompilerModifiers;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-import org.eclipse.wst.jsdt.internal.compiler.problem.ProblemReporter;
-import org.eclipse.wst.jsdt.internal.core.ImportDeclaration;
-import org.eclipse.wst.jsdt.internal.core.InitializerElementInfo;
-import org.eclipse.wst.jsdt.internal.core.PackageFragment;
-import org.eclipse.wst.jsdt.internal.core.SourceField;
-import org.eclipse.wst.jsdt.internal.core.SourceFieldElementInfo;
-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.util.Util;
-
-public class SourceTypeConverter {
-
- /*
- * Exception thrown while converting an anonymous type of a member type
- * in this case, we must parse the source as the enclosing instance cannot be recreated
- * from the model
- */
- static class AnonymousMemberFound extends RuntimeException {
- private static final long serialVersionUID = 1L;
- }
-
- public static final int FIELD = 0x01;
- public static final int CONSTRUCTOR = 0x02;
- public static final int METHOD = 0x04;
- public static final int MEMBER_TYPE = 0x08;
- public static final int FIELD_INITIALIZATION = 0x10;
- public static final int FIELD_AND_METHOD = FIELD | CONSTRUCTOR | METHOD;
- public static final int LOCAL_TYPE = 0x20;
- public static final int NONE = 0;
-
- private int flags;
- private CompilationUnitDeclaration unit;
- private Parser parser;
- private ProblemReporter problemReporter;
- private ICompilationUnit cu;
- private char[] source;
- private boolean has1_5Compliance;
-
- int namePos;
-
- private SourceTypeConverter(int flags, ProblemReporter problemReporter) {
- this.flags = flags;
- this.problemReporter = problemReporter;
- this.has1_5Compliance = problemReporter.options.complianceLevel >= ClassFileConstants.JDK1_5;
- }
-
- /*
- * Convert a set of source element types into a parsed compilation unit declaration
- * The argument types are then all grouped in the same unit. The argument types must
- * at least contain one type.
- * Can optionally ignore fields & methods or member types or field initialization
- */
- public static CompilationUnitDeclaration buildCompilationUnit(
- ISourceType[] sourceTypes,
- int flags,
- ProblemReporter problemReporter,
- CompilationResult compilationResult) {
-
-// long start = System.currentTimeMillis();
- SourceTypeConverter converter = new SourceTypeConverter(flags, problemReporter);
- try {
- return converter.convert(sourceTypes, compilationResult);
- } catch (JavaScriptModelException e) {
- return null;
-/* } finally {
- System.out.println("Spent " + (System.currentTimeMillis() - start) + "ms to convert " + ((JavaElement) converter.cu).toStringWithAncestors());
-*/ }
- }
-
- /*
- * Convert a set of source element types into a parsed compilation unit declaration
- * The argument types are then all grouped in the same unit. The argument types must
- * at least contain one type.
- */
- private CompilationUnitDeclaration convert(ISourceType[] sourceTypes, CompilationResult compilationResult) throws JavaScriptModelException {
- this.unit = new CompilationUnitDeclaration(this.problemReporter, compilationResult, 0);
- // not filled at this point
-
- if (sourceTypes.length == 0) return this.unit;
- SourceTypeElementInfo topLevelTypeInfo = (SourceTypeElementInfo) sourceTypes[0];
- org.eclipse.wst.jsdt.core.IJavaScriptUnit cuHandle = topLevelTypeInfo.getHandle().getJavaScriptUnit();
- this.cu = (ICompilationUnit) cuHandle;
-
- if (true){//this.has1_5Compliance && this.annotationPositions != null && this.annotationPositions.size() > 10) { // experimental value
- // if more than 10 annotations, diet parse as this is faster
- return new Parser(this.problemReporter, true).dietParse(this.cu, compilationResult);
- }
-
- /* only positions available */
- int start = topLevelTypeInfo.getNameSourceStart();
- int end = topLevelTypeInfo.getNameSourceEnd();
-
- /* convert package and imports */
- String[] packageName = ((PackageFragment) cuHandle.getParent()).names;
- if (packageName.length > 0)
- // if its null then it is defined in the default package
- this.unit.currentPackage =
- createImportReference(packageName, start, end, false);
- IImportDeclaration[] importDeclarations = topLevelTypeInfo.getHandle().getJavaScriptUnit().getImports();
- int importCount = importDeclarations.length;
- this.unit.imports = new ImportReference[importCount];
- for (int i = 0; i < importCount; i++) {
- ImportDeclaration importDeclaration = (ImportDeclaration) importDeclarations[i];
- ISourceImport sourceImport = (ISourceImport) importDeclaration.getElementInfo();
- String nameWithoutStar = importDeclaration.getNameWithoutStar();
- this.unit.imports[i] = createImportReference(
- Util.splitOn('.', nameWithoutStar, 0, nameWithoutStar.length()),
- sourceImport.getDeclarationSourceStart(),
- sourceImport.getDeclarationSourceEnd(),
- importDeclaration.isOnDemand());
- }
- /* convert type(s) */
- try {
- int typeCount = sourceTypes.length;
- final TypeDeclaration[] types = new TypeDeclaration[typeCount];
- /*
- * We used a temporary types collection to prevent this.unit.types from being null during a call to
- * convert(...) when the source is syntactically incorrect and the parser is flushing the unit's types.
- * See https://bugs.eclipse.org/bugs/show_bug.cgi?id=97466
- */
- for (int i = 0; i < typeCount; i++) {
- SourceTypeElementInfo typeInfo = (SourceTypeElementInfo) sourceTypes[i];
- types[i] = convert((SourceType) typeInfo.getHandle(), compilationResult);
- }
- this.unit.types = types;
- return this.unit;
- } catch (AnonymousMemberFound e) {
- return new Parser(this.problemReporter, true).parse(this.cu, compilationResult);
- }
- }
-
- private void addIdentifiers(String typeSignature, int start, int endExclusive, int identCount, ArrayList fragments) {
- if (identCount == 1) {
- char[] identifier;
- typeSignature.getChars(start, endExclusive, identifier = new char[endExclusive-start], 0);
- fragments.add(identifier);
- } else
- fragments.add(extractIdentifiers(typeSignature, start, endExclusive-1, identCount));
- }
-
- /*
- * Convert an initializerinfo into a parsed initializer declaration
- */
- private Initializer convert(InitializerElementInfo initializerInfo, CompilationResult compilationResult) throws JavaScriptModelException {
-
- Block block = new Block(0);
- Initializer initializer = new Initializer(block, ClassFileConstants.AccDefault);
-
- int start = initializerInfo.getDeclarationSourceStart();
- int end = initializerInfo.getDeclarationSourceEnd();
-
- initializer.sourceStart = initializer.declarationSourceStart = start;
- initializer.sourceEnd = initializer.declarationSourceEnd = end;
- initializer.modifiers = initializerInfo.getModifiers();
-
- /* convert local and anonymous types */
- IJavaScriptElement[] children = initializerInfo.getChildren();
- int typesLength = children.length;
- if (typesLength > 0) {
- Statement[] statements = new Statement[typesLength];
- for (int i = 0; i < typesLength; i++) {
- SourceType type = (SourceType) children[i];
- TypeDeclaration localType = convert(type, compilationResult);
- if ((localType.bits & ASTNode.IsAnonymousType) != 0) {
- QualifiedAllocationExpression expression = new QualifiedAllocationExpression(localType);
- expression.type = localType.superclass;
- localType.superclass = null;
- localType.allocation = expression;
- statements[i] = expression;
- } else {
- statements[i] = localType;
- }
- }
- block.statements = statements;
- }
-
- return initializer;
- }
-
- /*
- * Convert a field source element into a parsed field declaration
- */
- private FieldDeclaration convert(SourceField fieldHandle, TypeDeclaration type, CompilationResult compilationResult) throws JavaScriptModelException {
-
- SourceFieldElementInfo fieldInfo = (SourceFieldElementInfo) fieldHandle.getElementInfo();
- FieldDeclaration field = new FieldDeclaration();
-
- int start = fieldInfo.getNameSourceStart();
- int end = fieldInfo.getNameSourceEnd();
-
- field.name = fieldHandle.getElementName().toCharArray();
- field.sourceStart = start;
- field.sourceEnd = end;
- field.declarationSourceStart = fieldInfo.getDeclarationSourceStart();
- field.declarationSourceEnd = fieldInfo.getDeclarationSourceEnd();
- int modifiers = fieldInfo.getModifiers();
-
- field.modifiers = modifiers;
- field.type = createTypeReference(fieldInfo.getTypeName(), start, end);
-
- /* conversion of field constant */
- if ((this.flags & FIELD_INITIALIZATION) != 0) {
- char[] initializationSource = fieldInfo.getInitializationSource();
- if (initializationSource != null) {
- if (this.parser == null) {
- this.parser = new Parser(this.problemReporter, true);
- }
- this.parser.parse(field, type, this.unit, initializationSource);
- }
- }
-
- /* conversion of local and anonymous types */
- if ((this.flags & LOCAL_TYPE) != 0) {
- IJavaScriptElement[] children = fieldInfo.getChildren();
- int childrenLength = children.length;
- if (childrenLength == 1) {
- field.initialization = convert(children[0], null, compilationResult);
- } else if (childrenLength > 1) {
- ArrayInitializer initializer = new ArrayInitializer();
- field.initialization = initializer;
- Expression[] expressions = new Expression[childrenLength];
- initializer.expressions = expressions;
- for (int i = 0; i < childrenLength; i++) {
- expressions[i] = convert(children[i], null, compilationResult);
- }
- }
- }
- return field;
- }
-
- private QualifiedAllocationExpression convert(IJavaScriptElement localType, FieldDeclaration enumConstant, CompilationResult compilationResult) throws JavaScriptModelException {
- TypeDeclaration anonymousLocalTypeDeclaration = convert((SourceType) localType, compilationResult);
- QualifiedAllocationExpression expression = new QualifiedAllocationExpression(anonymousLocalTypeDeclaration);
- expression.type = anonymousLocalTypeDeclaration.superclass;
- anonymousLocalTypeDeclaration.superclass = null;
- anonymousLocalTypeDeclaration.allocation = expression;
- if (enumConstant != null) {
- expression.type = null;
- }
- return expression;
- }
-
- /*
- * Convert a method source element into a parsed method/constructor declaration
- */
- private AbstractMethodDeclaration convert(SourceMethod methodHandle, SourceMethodElementInfo methodInfo, CompilationResult compilationResult) throws JavaScriptModelException {
- AbstractMethodDeclaration method;
-
- /* only source positions available */
- int start = methodInfo.getNameSourceStart();
- int end = methodInfo.getNameSourceEnd();
-
- int modifiers = methodInfo.getModifiers();
- if (methodInfo.isConstructor()) {
- ConstructorDeclaration decl = new ConstructorDeclaration(compilationResult);
- decl.isDefaultConstructor = false;
- method = decl;
- } else {
- MethodDeclaration decl = new MethodDeclaration(compilationResult);
-
- // convert return type
- decl.returnType = createTypeReference(methodInfo.getReturnTypeName(), start, end);
-
- method = decl;
- }
- method.selector = methodHandle.getElementName().toCharArray();
- boolean isVarargs = (modifiers & ClassFileConstants.AccVarargs) != 0;
- method.modifiers = modifiers & ~ClassFileConstants.AccVarargs;
- method.sourceStart = start;
- method.sourceEnd = end;
- method.declarationSourceStart = methodInfo.getDeclarationSourceStart();
- method.declarationSourceEnd = methodInfo.getDeclarationSourceEnd();
-
- /* convert arguments */
- String[] argumentTypeSignatures = methodHandle.getParameterTypes();
- char[][] argumentNames = methodInfo.getArgumentNames();
- int argumentCount = argumentTypeSignatures == null ? 0 : argumentTypeSignatures.length;
- if (argumentCount > 0) {
- long position = ((long) start << 32) + end;
- method.arguments = new Argument[argumentCount];
- for (int i = 0; i < argumentCount; i++) {
- TypeReference typeReference = createTypeReference(argumentTypeSignatures[i], start, end);
- if (isVarargs && i == argumentCount-1) {
- typeReference.bits |= ASTNode.IsVarArgs;
- }
- method.arguments[i] =
- new Argument(
- argumentNames[i],
- position,
- typeReference,
- ClassFileConstants.AccDefault);
- // do not care whether was final or not
- }
- }
-
- /* convert local and anonymous types */
- if ((this.flags & LOCAL_TYPE) != 0) {
- IJavaScriptElement[] children = methodInfo.getChildren();
- int typesLength = children.length;
- if (typesLength != 0) {
- Statement[] statements = new Statement[typesLength];
- for (int i = 0; i < typesLength; i++) {
- SourceType type = (SourceType) children[i];
- TypeDeclaration localType = convert(type, compilationResult);
- if ((localType.bits & ASTNode.IsAnonymousType) != 0) {
- QualifiedAllocationExpression expression = new QualifiedAllocationExpression(localType);
- expression.type = localType.superclass;
- localType.superclass = null;
- localType.allocation = expression;
- statements[i] = expression;
- } else {
- statements[i] = localType;
- }
- }
- method.statements = statements;
- }
- }
-
- return method;
- }
-
- /*
- * Convert a source element type into a parsed type declaration
- */
- private TypeDeclaration convert(SourceType typeHandle, CompilationResult compilationResult) throws JavaScriptModelException {
- SourceTypeElementInfo typeInfo = (SourceTypeElementInfo) typeHandle.getElementInfo();
- if (typeInfo.isAnonymousMember())
- throw new AnonymousMemberFound();
- /* create type declaration - can be member type */
- TypeDeclaration type = new TypeDeclaration(compilationResult);
- if (typeInfo.getEnclosingType() == null) {
- if (typeHandle.isAnonymous()) {
- type.name = CharOperation.NO_CHAR;
- type.bits |= (ASTNode.IsAnonymousType|ASTNode.IsLocalType);
- } else {
- if (typeHandle.isLocal()) {
- type.bits |= ASTNode.IsLocalType;
- }
- }
- } else {
- type.bits |= ASTNode.IsMemberType;
- }
- if ((type.bits & ASTNode.IsAnonymousType) == 0) {
- type.name = typeInfo.getName();
- }
- type.name = typeInfo.getName();
- int start, end; // only positions available
- type.sourceStart = start = typeInfo.getNameSourceStart();
- type.sourceEnd = end = typeInfo.getNameSourceEnd();
- type.modifiers = typeInfo.getModifiers();
- type.declarationSourceStart = typeInfo.getDeclarationSourceStart();
- type.declarationSourceEnd = typeInfo.getDeclarationSourceEnd();
- type.bodyEnd = type.declarationSourceEnd;
-
- /* set superclass and superinterfaces */
- if (typeInfo.getSuperclassName() != null) {
- type.superclass = createTypeReference(typeInfo.getSuperclassName(), start, end);
- type.superclass.bits |= ASTNode.IsSuperType;
- }
-
- /* convert member types */
- if ((this.flags & MEMBER_TYPE) != 0) {
- SourceType[] sourceMemberTypes = typeInfo.getMemberTypeHandles();
- int sourceMemberTypeCount = sourceMemberTypes.length;
- type.memberTypes = new TypeDeclaration[sourceMemberTypeCount];
- for (int i = 0; i < sourceMemberTypeCount; i++) {
- type.memberTypes[i] = convert(sourceMemberTypes[i], compilationResult);
- }
- }
-
- /* convert intializers and fields*/
- InitializerElementInfo[] initializers = null;
- int initializerCount = 0;
- if ((this.flags & LOCAL_TYPE) != 0) {
- initializers = typeInfo.getInitializers();
- initializerCount = initializers.length;
- }
- SourceField[] sourceFields = null;
- int sourceFieldCount = 0;
- if ((this.flags & FIELD) != 0) {
- sourceFields = typeInfo.getFieldHandles();
- sourceFieldCount = sourceFields.length;
- }
- int length = initializerCount + sourceFieldCount;
- if (length > 0) {
- type.fields = new FieldDeclaration[length];
- for (int i = 0; i < initializerCount; i++) {
- type.fields[i] = convert(initializers[i], compilationResult);
- }
- int index = 0;
- for (int i = initializerCount; i < length; i++) {
- type.fields[i] = convert(sourceFields[index++], type, compilationResult);
- }
- }
-
- /* convert methods - need to add default constructor if necessary */
- boolean needConstructor = (this.flags & CONSTRUCTOR) != 0;
- boolean needMethod = (this.flags & METHOD) != 0;
- if (needConstructor || needMethod) {
-
- SourceMethod[] sourceMethods = typeInfo.getMethodHandles();
- int sourceMethodCount = sourceMethods.length;
-
- /* source type has a constructor ? */
- /* by default, we assume that one is needed. */
- int extraConstructor = 0;
- int methodCount = 0;
- int kind = TypeDeclaration.kind(type.modifiers);
-
- extraConstructor = needConstructor ? 1 : 0;
- for (int i = 0; i < sourceMethodCount; i++) {
- if (sourceMethods[i].isConstructor()) {
- if (needConstructor) {
- extraConstructor = 0; // Does not need the extra constructor since one constructor already exists.
- methodCount++;
- }
- } else if (needMethod) {
- methodCount++;
- }
- }
-
- type.methods = new AbstractMethodDeclaration[methodCount + extraConstructor];
- if (extraConstructor != 0) { // add default constructor in first position
- type.methods[0] = type.createDefaultConstructor(false, false);
- }
- int index = 0;
- boolean hasAbstractMethods = false;
- for (int i = 0; i < sourceMethodCount; i++) {
- SourceMethod sourceMethod = sourceMethods[i];
- SourceMethodElementInfo methodInfo = (SourceMethodElementInfo)sourceMethod.getElementInfo();
- boolean isConstructor = methodInfo.isConstructor();
- if ((methodInfo.getModifiers() & ClassFileConstants.AccAbstract) != 0) {
- hasAbstractMethods = true;
- }
- if ((isConstructor && needConstructor) || (!isConstructor && needMethod)) {
- AbstractMethodDeclaration method = convert(sourceMethod, methodInfo, compilationResult);
- if (method.isAbstract()) { // fix-up flag
- method.modifiers |= ExtraCompilerModifiers.AccSemicolonBody;
- }
- type.methods[extraConstructor + index++] = method;
- }
- }
- if (hasAbstractMethods) type.bits |= ASTNode.HasAbstractMethods;
- }
-
- return type;
- }
-
- /*
- * Build an import reference from an import name, e.g. java.lang.*
- */
- private ImportReference createImportReference(
- String[] importName,
- int start,
- int end,
- boolean onDemand) {
-
- int length = importName.length;
- long[] positions = new long[length];
- long position = ((long) start << 32) + end;
- char[][] qImportName = new char[length][];
- for (int i = 0; i < length; i++) {
- qImportName[i] = importName[i].toCharArray();
- positions[i] = position; // dummy positions
- }
- return new ImportReference(
- qImportName,
- positions,
- onDemand);
- }
-
- /*
- * Build a type reference from a readable name, e.g. java.lang.Object[][]
- */
- private TypeReference createTypeReference(
- char[] typeName,
- int start,
- int end) {
-
- int length = typeName.length;
- this.namePos = 0;
- return decodeType(typeName, length, start, end);
- }
-
- /*
- * Build a type reference from a type signature, e.g. Ljava.lang.Object;
- */
- private TypeReference createTypeReference(
- String typeSignature,
- int start,
- int end) {
-
- int length = typeSignature.length();
- this.namePos = 0;
- return decodeType(typeSignature, length, start, end);
- }
-
- private TypeReference decodeType(String typeSignature, int length, int start, int end) {
- int identCount = 1;
- int dim = 0;
- int nameFragmentStart = this.namePos, nameFragmentEnd = -1;
- boolean nameStarted = false;
- ArrayList fragments = null;
- typeLoop: while (this.namePos < length) {
- char currentChar = typeSignature.charAt(this.namePos);
- switch (currentChar) {
- case Signature.C_VOID :
- if (!nameStarted) {
- this.namePos++;
- new SingleTypeReference(TypeBinding.VOID.simpleName, ((long) start << 32) + end);
- }
- break;
- case Signature.C_RESOLVED :
- case Signature.C_UNRESOLVED :
- if (!nameStarted) {
- nameFragmentStart = this.namePos+1;
- nameStarted = true;
- }
- break;
- case Signature.C_ARRAY :
- dim++;
- break;
- case Signature.C_SEMICOLON :
- nameFragmentEnd = this.namePos-1;
- this.namePos++;
- break typeLoop;
- case Signature.C_DOT :
- case Signature.C_DOLLAR:
- if (!nameStarted) {
- nameFragmentStart = this.namePos+1;
- nameStarted = true;
- } else if (this.namePos > nameFragmentStart) // handle name starting with a $ (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=91709)
- identCount ++;
- break;
- }
- this.namePos++;
- }
- if (fragments == null) { // non parameterized
- /* rebuild identifiers and dimensions */
- if (identCount == 1) { // simple type reference
- if (dim == 0) {
- char[] nameFragment = new char[nameFragmentEnd - nameFragmentStart + 1];
- typeSignature.getChars(nameFragmentStart, nameFragmentEnd +1, nameFragment, 0);
- return new SingleTypeReference(nameFragment, ((long) start << 32) + end);
- } else {
- char[] nameFragment = new char[nameFragmentEnd - nameFragmentStart + 1];
- typeSignature.getChars(nameFragmentStart, nameFragmentEnd +1, nameFragment, 0);
- return new ArrayTypeReference(nameFragment, dim, ((long) start << 32) + end);
- }
- } else { // qualified type reference
- long[] positions = new long[identCount];
- long pos = ((long) start << 32) + end;
- for (int i = 0; i < identCount; i++) {
- positions[i] = pos;
- }
- char[][] identifiers = extractIdentifiers(typeSignature, nameFragmentStart, nameFragmentEnd, identCount);
- if (dim == 0) {
- return new QualifiedTypeReference(identifiers, positions);
- } else {
- return new ArrayQualifiedTypeReference(identifiers, dim, positions);
- }
- }
- } else { // parameterized
- // rebuild type reference from available fragments: char[][], arguments, char[][], arguments...
- // check trailing qualified name
- if (nameStarted) {
- addIdentifiers(typeSignature, nameFragmentStart, nameFragmentEnd + 1, identCount, fragments);
- }
- int fragmentLength = fragments.size();
- if (fragmentLength == 2) {
- Object firstFragment = fragments.get(0);
- if (firstFragment instanceof char[]) {
- // parameterized single type
- return null;
- }
- }
- // parameterized qualified type
- identCount = 0;
- for (int i = 0; i < fragmentLength; i ++) {
- Object element = fragments.get(i);
- if (element instanceof char[][]) {
- identCount += ((char[][])element).length;
- } else if (element instanceof char[])
- identCount++;
- }
- char[][] tokens = new char[identCount][];
- TypeReference[][] arguments = new TypeReference[identCount][];
- int index = 0;
- for (int i = 0; i < fragmentLength; i ++) {
- Object element = fragments.get(i);
- if (element instanceof char[][]) {
- char[][] fragmentTokens = (char[][]) element;
- int fragmentTokenLength = fragmentTokens.length;
- System.arraycopy(fragmentTokens, 0, tokens, index, fragmentTokenLength);
- index += fragmentTokenLength;
- } else if (element instanceof char[]) {
- tokens[index++] = (char[]) element;
- } else {
- arguments[index-1] = (TypeReference[]) element;
- }
- }
- long[] positions = new long[identCount];
- long pos = ((long) start << 32) + end;
- for (int i = 0; i < identCount; i++) {
- positions[i] = pos;
- }
- return null;
- }
- }
-
- private TypeReference decodeType(char[] typeName, int length, int start, int end) {
- int identCount = 1;
- int dim = 0;
- int nameFragmentStart = this.namePos, nameFragmentEnd = -1;
- ArrayList fragments = null;
- typeLoop: while (this.namePos < length) {
- char currentChar = typeName[this.namePos];
- switch (currentChar) {
- case '?' :
- this.namePos++; // skip '?'
- while (typeName[this.namePos] == ' ') this.namePos++;
- switch(typeName[this.namePos]) {
- case 's' :
- break;
- case 'e' :
- break;
- }
- case '[' :
- if (dim == 0) nameFragmentEnd = this.namePos-1;
- dim++;
- break;
- case ']' :
- break;
- case '>' :
- case ',' :
- break typeLoop;
- case '.' :
- if (nameFragmentStart < 0) nameFragmentStart = this.namePos+1; // member type name
- identCount ++;
- break;
- case '<' :
- // convert 1.5 specific constructs only if compliance is 1.5 or above
- if (!this.has1_5Compliance)
- break typeLoop;
- if (fragments == null) fragments = new ArrayList(2);
- nameFragmentEnd = this.namePos-1;
- char[][] identifiers = CharOperation.splitOn('.', typeName, nameFragmentStart, this.namePos);
- fragments.add(identifiers);
- this.namePos++; // skip '<'
- TypeReference[] arguments = decodeTypeArguments(typeName, length, start, end); // positionned on '>' at end
- fragments.add(arguments);
- identCount = 0;
- nameFragmentStart = -1;
- nameFragmentEnd = -1;
- // next increment will skip '>'
- break;
- }
- this.namePos++;
- }
- if (nameFragmentEnd < 0) nameFragmentEnd = this.namePos-1;
- if (fragments == null) { // non parameterized
- /* rebuild identifiers and dimensions */
- if (identCount == 1) { // simple type reference
- if (dim == 0) {
- char[] nameFragment;
- if (nameFragmentStart != 0 || nameFragmentEnd >= 0) {
- int nameFragmentLength = nameFragmentEnd - nameFragmentStart + 1;
- System.arraycopy(typeName, nameFragmentStart, nameFragment = new char[nameFragmentLength], 0, nameFragmentLength);
- } else {
- nameFragment = typeName;
- }
- return new SingleTypeReference(nameFragment, ((long) start << 32) + end);
- } else {
- int nameFragmentLength = nameFragmentEnd - nameFragmentStart + 1;
- char[] nameFragment = new char[nameFragmentLength];
- System.arraycopy(typeName, nameFragmentStart, nameFragment, 0, nameFragmentLength);
- return new ArrayTypeReference(nameFragment, dim, ((long) start << 32) + end);
- }
- } else { // qualified type reference
- long[] positions = new long[identCount];
- long pos = ((long) start << 32) + end;
- for (int i = 0; i < identCount; i++) {
- positions[i] = pos;
- }
- char[][] identifiers = CharOperation.splitOn('.', typeName, nameFragmentStart, nameFragmentEnd+1);
- if (dim == 0) {
- return new QualifiedTypeReference(identifiers, positions);
- } else {
- return new ArrayQualifiedTypeReference(identifiers, dim, positions);
- }
- }
- } else { // parameterized
- // rebuild type reference from available fragments: char[][], arguments, char[][], arguments...
- // check trailing qualified name
- if (nameFragmentStart > 0 && nameFragmentStart < length) {
- char[][] identifiers = CharOperation.splitOn('.', typeName, nameFragmentStart, nameFragmentEnd+1);
- fragments.add(identifiers);
- }
- int fragmentLength = fragments.size();
- if (fragmentLength == 2) {
- char[][] firstFragment = (char[][]) fragments.get(0);
- if (firstFragment.length == 1) {
- // parameterized single type
- return null;
- }
- }
- // parameterized qualified type
- identCount = 0;
- for (int i = 0; i < fragmentLength; i ++) {
- Object element = fragments.get(i);
- if (element instanceof char[][]) {
- identCount += ((char[][])element).length;
- }
- }
- char[][] tokens = new char[identCount][];
- TypeReference[][] arguments = new TypeReference[identCount][];
- int index = 0;
- for (int i = 0; i < fragmentLength; i ++) {
- Object element = fragments.get(i);
- if (element instanceof char[][]) {
- char[][] fragmentTokens = (char[][]) element;
- int fragmentTokenLength = fragmentTokens.length;
- System.arraycopy(fragmentTokens, 0, tokens, index, fragmentTokenLength);
- index += fragmentTokenLength;
- } else {
- arguments[index-1] = (TypeReference[]) element;
- }
- }
- long[] positions = new long[identCount];
- long pos = ((long) start << 32) + end;
- for (int i = 0; i < identCount; i++) {
- positions[i] = pos;
- }
- return null;
- }
- }
-
- private TypeReference[] decodeTypeArguments(char[] typeName, int length, int start, int end) {
- ArrayList argumentList = new ArrayList(1);
- int count = 0;
- argumentsLoop: while (this.namePos < length) {
- TypeReference argument = decodeType(typeName, length, start, end);
- count++;
- argumentList.add(argument);
- if (this.namePos >= length) break argumentsLoop;
- if (typeName[this.namePos] == '>') {
- break argumentsLoop;
- }
- this.namePos++; // skip ','
- }
- TypeReference[] typeArguments = new TypeReference[count];
- argumentList.toArray(typeArguments);
- return typeArguments;
- }
-
- private TypeReference[] decodeTypeArguments(String typeSignature, int length, int start, int end) {
- ArrayList argumentList = new ArrayList(1);
- int count = 0;
- argumentsLoop: while (this.namePos < length) {
- TypeReference argument = decodeType(typeSignature, length, start, end);
- count++;
- argumentList.add(argument);
- if (this.namePos >= length) break argumentsLoop;
- if (typeSignature.charAt(this.namePos) == '>') {
- break argumentsLoop;
- }
- }
- TypeReference[] typeArguments = new TypeReference[count];
- argumentList.toArray(typeArguments);
- return typeArguments;
- }
-
- private char[][] extractIdentifiers(String typeSignature, int start, int endInclusive, int identCount) {
- char[][] result = new char[identCount][];
- int charIndex = start;
- int i = 0;
- while (charIndex < endInclusive) {
- if (typeSignature.charAt(charIndex) == '.') {
- typeSignature.getChars(start, charIndex, result[i++] = new char[charIndex - start], 0);
- start = ++charIndex;
- } else
- charIndex++;
- }
- typeSignature.getChars(start, charIndex + 1, result[i++] = new char[charIndex - start + 1], 0);
- return result;
- }
-
- private char[] getSource() {
- if (this.source == null)
- this.source = this.cu.getContents();
- return this.source;
- }
-
- private Expression parseMemberValue(char[] memberValue) {
- // memberValue must not be null
- if (this.parser == null) {
- this.parser = new Parser(this.problemReporter, true);
- }
- return this.parser.parseMemberValue(memberValue, 0, memberValue.length, this.unit);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/TerminalTokens.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/TerminalTokens.java
deleted file mode 100644
index e98347c5..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/TerminalTokens.java
+++ /dev/null
@@ -1,157 +0,0 @@
-/*******************************************************************************
- * 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.compiler.parser;
-
-/**
- * IMPORTANT NOTE: These constants are dedicated to the internal Scanner implementation.
- * It is mirrored in org.eclipse.wst.jsdt.core.compiler public package where it is API.
- * The mirror implementation is using the backward compatible ITerminalSymbols constant
- * definitions (stable with 2.0), whereas the internal implementation uses TerminalTokens
- * which constant values reflect the latest parser generation state.
- */
-/**
- * Maps each terminal symbol in the java-grammar into a unique integer.
- * This integer is used to represent the terminal when computing a parsing action.
- *
- * Disclaimer : These constant values are generated automatically using a Java
- * grammar, therefore their actual values are subject to change if new keywords
- * were added to the language (for instance, 'assert' is a keyword in 1.4).
- */
-public interface TerminalTokens {
-
- // special tokens not part of grammar - not autogenerated
- int TokenNameWHITESPACE = 1000,
- TokenNameCOMMENT_LINE = 1001,
- TokenNameCOMMENT_BLOCK = 1002,
- TokenNameCOMMENT_JAVADOC = 1003,
- TokenNameUNKNOWN = 1004;
-
- int TokenNameIdentifier = 32,
- TokenNameabstract = 88,
- TokenNameboolean = 89,
- TokenNamebreak = 59,
- TokenNamebyte = 90,
- TokenNamecase = 84,
- TokenNamecatch = 86,
- TokenNamechar = 91,
- TokenNameclass = 92,
- TokenNamecontinue = 60,
- TokenNameconst = 93,
- TokenNamedefault = 85,
- TokenNamedebugger = 61,
- TokenNamedelete = 47,
- TokenNamedo = 62,
- TokenNamedouble = 94,
- TokenNameelse = 83,
- TokenNameenum = 95,
- TokenNameexport = 96,
- TokenNameextends = 97,
- TokenNamefalse = 36,
- TokenNamefinal = 98,
- TokenNamefinally = 87,
- TokenNamefloat = 99,
- TokenNamefor = 63,
- TokenNamefunction = 55,
- TokenNamegoto = 100,
- TokenNameif = 64,
- TokenNamein = 24,
- TokenNameimplements = 101,
- TokenNameimport = 102,
- TokenNameinstanceof = 13,
- TokenNameint = 103,
- TokenNameinterface = 104,
- TokenNamelet = 105,
- TokenNamelong = 106,
- TokenNamenative = 107,
- TokenNamenew = 37,
- TokenNamenull = 38,
- TokenNamepackage = 108,
- TokenNameprivate = 109,
- TokenNameprotected = 110,
- TokenNamepublic = 111,
- TokenNamereturn = 65,
- TokenNameshort = 112,
- TokenNamestatic = 113,
- TokenNamesuper = 114,
- TokenNameswitch = 66,
- TokenNamesynchronized = 115,
- TokenNamethis = 39,
- TokenNamethrow = 67,
- TokenNamethrows = 116,
- TokenNametransient = 117,
- TokenNametrue = 40,
- TokenNametry = 68,
- TokenNametypeof = 48,
- TokenNameundefined = 41,
- TokenNamevar = 57,
- TokenNamevoid = 49,
- TokenNamevolatile = 118,
- TokenNamewhile = 58,
- TokenNamewith = 69,
- TokenNameyield = 119,
- TokenNameIntegerLiteral = 33,
- TokenNameLongLiteral = 42,
- TokenNameFloatingPointLiteral = 43,
- TokenNameDoubleLiteral = 44,
- TokenNameCharacterLiteral = 34,
- TokenNameStringLiteral = 35,
- TokenNameRegExLiteral = 45,
- TokenNamePLUS_PLUS = 3,
- TokenNameMINUS_MINUS = 4,
- TokenNameEQUAL_EQUAL = 14,
- TokenNameEQUAL_EQUAL_EQUAL = 15,
- TokenNameNOT_EQUAL_EQUAL = 16,
- TokenNameLESS_EQUAL = 17,
- TokenNameGREATER_EQUAL = 18,
- TokenNameNOT_EQUAL = 19,
- TokenNameLEFT_SHIFT = 7,
- TokenNameRIGHT_SHIFT = 8,
- TokenNameUNSIGNED_RIGHT_SHIFT = 6,
- TokenNamePLUS_EQUAL = 72,
- TokenNameMINUS_EQUAL = 73,
- TokenNameMULTIPLY_EQUAL = 74,
- TokenNameDIVIDE_EQUAL = 75,
- TokenNameAND_EQUAL = 76,
- TokenNameOR_EQUAL = 77,
- TokenNameXOR_EQUAL = 78,
- TokenNameREMAINDER_EQUAL = 79,
- TokenNameLEFT_SHIFT_EQUAL = 80,
- TokenNameRIGHT_SHIFT_EQUAL = 81,
- TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL = 82,
- TokenNameOR_OR = 29,
- TokenNameAND_AND = 28,
- TokenNamePLUS = 1,
- TokenNameMINUS = 2,
- TokenNameNOT = 50,
- TokenNameREMAINDER = 9,
- TokenNameXOR = 23,
- TokenNameAND = 22,
- TokenNameMULTIPLY = 10,
- TokenNameOR = 25,
- TokenNameTWIDDLE = 46,
- TokenNameDIVIDE = 11,
- TokenNameGREATER = 20,
- TokenNameLESS = 21,
- TokenNameLPAREN = 5,
- TokenNameRPAREN = 52,
- TokenNameLBRACE = 51,
- TokenNameRBRACE = 56,
- TokenNameLBRACKET = 12,
- TokenNameRBRACKET = 54,
- TokenNameSEMICOLON = 26,
- TokenNameQUESTION = 30,
- TokenNameCOLON = 53,
- TokenNameCOMMA = 27,
- TokenNameDOT = 31,
- TokenNameEQUAL = 71,
- TokenNameEOF = 70,
- TokenNameERROR = 120;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/UpdateParserFiles.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/UpdateParserFiles.java
deleted file mode 100644
index 20859390..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/UpdateParserFiles.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.parser;
-
-import java.io.IOException;
-
-public class UpdateParserFiles {
-
-
- public static void main(String[] args) throws IOException {
- if (args.length != 2) {
- printUsage();
- return;
- }
- Parser.buildFilesFromLPG(args[0], args[1]);
- }
-
- public static void printUsage() {
- System.out.println("Usage: UpdateParserFiles <path to javadcl.java> <path to javahdr.java>"); //$NON-NLS-1$
- System.out.println("e.g. UpdateParserFiles c:/javadcl.java c:/javahdr.java"); //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/diagnose/DiagnoseParser.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/diagnose/DiagnoseParser.java
deleted file mode 100644
index 1033cfec..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/diagnose/DiagnoseParser.java
+++ /dev/null
@@ -1,2530 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.parser.diagnose;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.impl.CompilerOptions;
-import org.eclipse.wst.jsdt.internal.compiler.parser.Parser;
-import org.eclipse.wst.jsdt.internal.compiler.parser.ParserBasicInformation;
-import org.eclipse.wst.jsdt.internal.compiler.parser.RecoveryScanner;
-import org.eclipse.wst.jsdt.internal.compiler.parser.ScannerHelper;
-import org.eclipse.wst.jsdt.internal.compiler.parser.TerminalTokens;
-import org.eclipse.wst.jsdt.internal.compiler.problem.ProblemReporter;
-import org.eclipse.wst.jsdt.internal.compiler.util.Util;
-
-public class DiagnoseParser implements ParserBasicInformation, TerminalTokens {
- private static final boolean DEBUG = false;
- private boolean DEBUG_PARSECHECK = false;
-
- private static final int STACK_INCREMENT = 256;
-
-// private static final int ERROR_CODE = 1;
- private static final int BEFORE_CODE = 2;
- private static final int INSERTION_CODE = 3;
- private static final int INVALID_CODE = 4;
- private static final int SUBSTITUTION_CODE = 5;
- private static final int DELETION_CODE = 6;
- private static final int MERGE_CODE = 7;
- private static final int MISPLACED_CODE = 8;
- private static final int SCOPE_CODE = 9;
- private static final int SECONDARY_CODE = 10;
- private static final int EOF_CODE = 11;
-
- private static final int BUFF_UBOUND = 31;
- private static final int BUFF_SIZE = 32;
- private static final int MAX_DISTANCE = 30;
- private static final int MIN_DISTANCE = 3;
-
- private CompilerOptions options;
-
- private LexStream lexStream;
- private int errorToken;
- private int errorTokenStart;
-
- private int currentToken = 0;
-
- private int stackLength;
- private int stateStackTop;
- private int[] stack;
-
- private int[] locationStack;
- private int[] locationStartStack;
-
- private int tempStackTop;
- private int[] tempStack;
-
- private int prevStackTop;
- private int[] prevStack;
- private int nextStackTop;
- private int[] nextStack;
-
- private int scopeStackTop;
- private int[] scopeIndex;
- private int[] scopePosition;
-
- int[] list = new int[NUM_SYMBOLS + 1];
- int[] buffer = new int[BUFF_SIZE];
-
- private static final int NIL = -1;
- int[] stateSeen;
-
- int statePoolTop;
- StateInfo[] statePool;
-
- private Parser parser;
-
- private RecoveryScanner recoveryScanner;
-
- private boolean reportProblem;
-
- private static class RepairCandidate {
- public int symbol;
- public int location;
-
- public RepairCandidate(){
- this.symbol = 0;
- this.location = 0;
- }
- }
-
- private static class PrimaryRepairInfo {
- public int distance;
- public int misspellIndex;
- public int code;
- public int bufferPosition;
- public int symbol;
-
- public PrimaryRepairInfo(){
- this.distance = 0;
- this.misspellIndex = 0;
- this.code = 0;
- this.bufferPosition = 0;
- this.symbol = 0;
- }
-
- public PrimaryRepairInfo copy(){
- PrimaryRepairInfo c = new PrimaryRepairInfo();
- c.distance = this.distance;
- c.misspellIndex = this.misspellIndex;
- c.code = this.code;
- c.bufferPosition = this .bufferPosition;
- c.symbol = this.symbol;
- return c;
-
- }
- }
-
- static class SecondaryRepairInfo {
- public int code;
- public int distance;
- public int bufferPosition;
- public int stackPosition;
- public int numDeletions;
- public int symbol;
-
- boolean recoveryOnNextStack;
- }
-
- private static class StateInfo {
- int state;
- int next;
-
- public StateInfo(int state, int next){
- this.state = state;
- this.next = next;
- }
- }
-
- public DiagnoseParser(Parser parser, int firstToken, int start, int end, CompilerOptions options) {
- this(parser, firstToken, start, end, Util.EMPTY_INT_ARRAY, Util.EMPTY_INT_ARRAY, Util.EMPTY_INT_ARRAY, options);
- }
-
- public DiagnoseParser(Parser parser, int firstToken, int start, int end, int[] intervalStartToSkip, int[] intervalEndToSkip, int[] intervalFlagsToSkip, CompilerOptions options) {
- this.parser = parser;
- this.options = options;
- this.lexStream = new LexStream(BUFF_SIZE, parser.scanner, intervalStartToSkip, intervalEndToSkip, intervalFlagsToSkip, firstToken, start, end);
- this.recoveryScanner = parser.recoveryScanner;
- }
-
- private ProblemReporter problemReporter(){
- return parser.problemReporter();
- }
-
- private void reallocateStacks() {
- int old_stack_length = stackLength;
-
- stackLength += STACK_INCREMENT;
-
- if(old_stack_length == 0){
- stack = new int[stackLength];
- locationStack = new int[stackLength];
- locationStartStack = new int[stackLength];
- tempStack = new int[stackLength];
- prevStack = new int[stackLength];
- nextStack = new int[stackLength];
- scopeIndex = new int[stackLength];
- scopePosition = new int[stackLength];
- } else {
- System.arraycopy(stack, 0, stack = new int[stackLength], 0, old_stack_length);
- System.arraycopy(locationStack, 0, locationStack = new int[stackLength], 0, old_stack_length);
- System.arraycopy(locationStartStack, 0, locationStartStack = new int[stackLength], 0, old_stack_length);
- System.arraycopy(tempStack, 0, tempStack = new int[stackLength], 0, old_stack_length);
- System.arraycopy(prevStack, 0, prevStack = new int[stackLength], 0, old_stack_length);
- System.arraycopy(nextStack, 0, nextStack = new int[stackLength], 0, old_stack_length);
- System.arraycopy(scopeIndex, 0, scopeIndex = new int[stackLength], 0, old_stack_length);
- System.arraycopy(scopePosition, 0, scopePosition = new int[stackLength], 0, old_stack_length);
- }
- return;
- }
-
-
- public void diagnoseParse(boolean record) {
- this.reportProblem = true;
- boolean oldRecord = false;
- if(this.recoveryScanner != null) {
- oldRecord = this.recoveryScanner.record;
- this.recoveryScanner.record = record;
- }
- try {
- lexStream.reset();
-
- currentToken = lexStream.getToken();
-
- int prev_pos;
- int pos;
- int next_pos;
- int act = START_STATE;
-
- reallocateStacks();
-
- //
- // Start parsing
- //
- stateStackTop = 0;
- stack[stateStackTop] = act;
-
- int tok = lexStream.kind(currentToken);
- locationStack[stateStackTop] = currentToken;
- locationStartStack[stateStackTop] = lexStream.start(currentToken);
-
- boolean forceRecoveryAfterLBracketMissing = false;
- // int forceRecoveryToken = -1;
-
- //
- // Process a terminal
- //
- do {
- //
- // Synchronize state stacks and update the location stack
- //
- prev_pos = -1;
- prevStackTop = -1;
-
- next_pos = -1;
- nextStackTop = -1;
-
- pos = stateStackTop;
- tempStackTop = stateStackTop - 1;
- for (int i = 0; i <= stateStackTop; i++)
- tempStack[i] = stack[i];
-
- act = Parser.tAction(act, tok);
- //
- // When a reduce action is encountered, we compute all REDUCE
- // and associated goto actions induced by the current token.
- // Eventually, a SHIFT, SHIFT-REDUCE, ACCEPT or ERROR action is
- // computed...
- //
- while (act <= NUM_RULES) {
- do {
- tempStackTop -= (Parser.rhs[act]-1);
- act = Parser.ntAction(tempStack[tempStackTop], Parser.lhs[act]);
- } while(act <= NUM_RULES);
- //
- // ... Update the maximum useful position of the
- // (STATE_)STACK, push goto state into stack, and
- // compute next action on current symbol ...
- //
- if (tempStackTop + 1 >= stackLength)
- reallocateStacks();
- pos = pos < tempStackTop ? pos : tempStackTop;
- tempStack[tempStackTop + 1] = act;
- act = Parser.tAction(act, tok);
- }
-
- //
- // At this point, we have a shift, shift-reduce, accept or error
- // action. STACK contains the configuration of the state stack
- // prior to executing any action on curtok. next_stack contains
- // the configuration of the state stack after executing all
- // reduce actions induced by curtok. The variable pos indicates
- // the highest position in STACK that is still useful after the
- // reductions are executed.
- //
- while(act > ERROR_ACTION || act < ACCEPT_ACTION) { // SHIFT-REDUCE action or SHIFT action ?
- nextStackTop = tempStackTop + 1;
- for (int i = next_pos + 1; i <= nextStackTop; i++)
- nextStack[i] = tempStack[i];
-
- for (int i = pos + 1; i <= nextStackTop; i++) {
- locationStack[i] = locationStack[stateStackTop];
- locationStartStack[i] = locationStartStack[stateStackTop];
- }
-
- //
- // If we have a shift-reduce, process it as well as
- // the goto-reduce actions that follow it.
- //
- if (act > ERROR_ACTION) {
- act -= ERROR_ACTION;
- do {
- nextStackTop -= (Parser.rhs[act]-1);
- act = Parser.ntAction(nextStack[nextStackTop], Parser.lhs[act]);
- } while(act <= NUM_RULES);
- pos = pos < nextStackTop ? pos : nextStackTop;
- }
-
- if (nextStackTop + 1 >= stackLength)
- reallocateStacks();
-
- tempStackTop = nextStackTop;
- nextStack[++nextStackTop] = act;
- next_pos = nextStackTop;
-
- //
- // Simulate the parser through the next token without
- // destroying STACK or next_stack.
- //
- currentToken = lexStream.getToken();
- tok = lexStream.kind(currentToken);
-// TODO: insert optional semicolon processing here
- act = Parser.tAction(act, tok);
- while(act <= NUM_RULES) {
- //
- // ... Process all goto-reduce actions following
- // reduction, until a goto action is computed ...
- //
- do {
- int lhs_symbol = Parser.lhs[act];
- if(DEBUG) {
- System.out.println(Parser.name[Parser.non_terminal_index[lhs_symbol]]);
- }
- tempStackTop -= (Parser.rhs[act]-1);
- act = (tempStackTop > next_pos
- ? tempStack[tempStackTop]
- : nextStack[tempStackTop]);
- act = Parser.ntAction(act, lhs_symbol);
- } while(act <= NUM_RULES);
-
- //
- // ... Update the maximum useful position of the
- // (STATE_)STACK, push GOTO state into stack, and
- // compute next action on current symbol ...
- //
- if (tempStackTop + 1 >= stackLength)
- reallocateStacks();
-
- next_pos = next_pos < tempStackTop ? next_pos : tempStackTop;
- tempStack[tempStackTop + 1] = act;
-//TODO: insert optional semicolon processing here
- act = Parser.tAction(act, tok);
- }
-
- // if((tok != TokenNameRBRACE || (forceRecoveryToken != currentToken && (lexStream.flags(currentToken) & LexStream.LBRACE_MISSING) != 0))
- // && (lexStream.flags(currentToken) & LexStream.IS_AFTER_JUMP) !=0) {
- // act = ERROR_ACTION;
- // if(forceRecoveryToken != currentToken
- // && (lexStream.flags(currentToken) & LexStream.LBRACE_MISSING) != 0) {
- // forceRecoveryAfterLBracketMissing = true;
- // forceRecoveryToken = currentToken;
- // }
- // }
-
- //
- // No error was detected, Read next token into
- // PREVTOK element, advance CURTOK pointer and
- // update stacks.
- //
- if (act != ERROR_ACTION) {
- prevStackTop = stateStackTop;
- for (int i = prev_pos + 1; i <= prevStackTop; i++)
- prevStack[i] = stack[i];
- prev_pos = pos;
-
- stateStackTop = nextStackTop;
- for (int i = pos + 1; i <= stateStackTop; i++)
- stack[i] = nextStack[i];
- locationStack[stateStackTop] = currentToken;
- locationStartStack[stateStackTop] = lexStream.start(currentToken);
- pos = next_pos;
- }
- }
-
- //
- // At this stage, either we have an ACCEPT or an ERROR
- // action.
- //
- if (act == ERROR_ACTION) {
- //
- // An error was detected.
- //
- RepairCandidate candidate = errorRecovery(currentToken, forceRecoveryAfterLBracketMissing);
-
- forceRecoveryAfterLBracketMissing = false;
-
- if(parser.reportOnlyOneSyntaxError) {
- return;
- }
-
- if(this.parser.problemReporter().options.maxProblemsPerUnit < this.parser.compilationUnit.compilationResult.problemCount) {
- if(this.recoveryScanner == null || !this.recoveryScanner.record) return;
- this.reportProblem = false;
- }
-
- act = stack[stateStackTop];
-
- //
- // If the recovery was successful on a nonterminal candidate,
- // parse through that candidate and "read" the next token.
- //
- if (candidate.symbol == 0) {
- break;
- } else if (candidate.symbol > NT_OFFSET) {
- int lhs_symbol = candidate.symbol - NT_OFFSET;
- if(DEBUG) {
- System.out.println(Parser.name[Parser.non_terminal_index[lhs_symbol]]);
- }
- act = Parser.ntAction(act, lhs_symbol);
- while(act <= NUM_RULES) {
- stateStackTop -= (Parser.rhs[act]-1);
- act = Parser.ntAction(stack[stateStackTop], Parser.lhs[act]);
- }
- stack[++stateStackTop] = act;
- currentToken = lexStream.getToken();
- tok = lexStream.kind(currentToken);
- locationStack[stateStackTop] = currentToken;
- locationStartStack[stateStackTop] = lexStream.start(currentToken);
- } else {
- tok = candidate.symbol;
- locationStack[stateStackTop] = candidate.location;
- locationStartStack[stateStackTop] = lexStream.start(candidate.location);
- }
- }
- } while (act != ACCEPT_ACTION);
- } finally {
- if(this.recoveryScanner != null) {
- this.recoveryScanner.record = oldRecord;
- }
- }
- return;
- }
-
- //
-// This routine is invoked when an error is encountered. It
-// tries to diagnose the error and recover from it. If it is
-// successful, the state stack, the current token and the buffer
-// are readjusted; i.e., after a successful recovery,
-// state_stack_top points to the location in the state stack
-// that contains the state on which to recover; curtok
-// identifies the symbol on which to recover.
-//
-// Up to three configurations may be available when this routine
-// is invoked. PREV_STACK may contain the sequence of states
-// preceding any action on prevtok, STACK always contains the
-// sequence of states preceding any action on curtok, and
-// NEXT_STACK may contain the sequence of states preceding any
-// action on the successor of curtok.
-//
- private RepairCandidate errorRecovery(int error_token, boolean forcedError) {
- this.errorToken = error_token;
- this.errorTokenStart = lexStream.start(error_token);
-
- int prevtok = lexStream.previous(error_token);
- int prevtokKind = lexStream.kind(prevtok);
-
- if(forcedError) {
- int name_index = Parser.terminal_index[TokenNameLBRACE];
-
- reportError(INSERTION_CODE, name_index, prevtok, prevtok);
-
- RepairCandidate candidate = new RepairCandidate();
- candidate.symbol = TokenNameLBRACE;
- candidate.location = error_token;
- lexStream.reset(error_token);
-
- stateStackTop = nextStackTop;
- for (int j = 0; j <= stateStackTop; j++) {
- stack[j] = nextStack[j];
- }
- locationStack[stateStackTop] = error_token;
- locationStartStack[stateStackTop] = lexStream.start(error_token);
-
- return candidate;
- }
-
- //
- // Try primary phase recoveries. If not successful, try secondary
- // phase recoveries. If not successful and we are at end of the
- // file, we issue the end-of-file error and quit. Otherwise, ...
- //
- RepairCandidate candidate = primaryPhase(error_token);
- if (candidate.symbol != 0) {
- return candidate;
- }
-
- candidate = secondaryPhase(error_token);
- if (candidate.symbol != 0) {
- return candidate;
- }
-
- if (lexStream.kind(error_token) == EOFT_SYMBOL) {
- reportError(EOF_CODE,
- Parser.terminal_index[EOFT_SYMBOL],
- prevtok,
- prevtok);
- candidate.symbol = 0;
- candidate.location = error_token;
- return candidate;
- }
-
- //
- // At this point, primary and (initial attempt at) secondary
- // recovery did not work. We will now get into "panic mode" and
- // keep trying secondary phase recoveries until we either find
- // a successful recovery or have consumed the remaining input
- // tokens.
- //
- while(lexStream.kind(buffer[BUFF_UBOUND]) != EOFT_SYMBOL) {
- candidate = secondaryPhase(buffer[MAX_DISTANCE - MIN_DISTANCE + 2]);
- if (candidate.symbol != 0) {
- return candidate;
- }
- }
-
- //
- // We reached the end of the file while panicking. Delete all
- // remaining tokens in the input.
- //
- int i;
- for (i = BUFF_UBOUND; lexStream.kind(buffer[i]) == EOFT_SYMBOL; i--){/*empty*/}
-
- reportError(DELETION_CODE,
- Parser.terminal_index[prevtokKind],//Parser.terminal_index[lexStream.kind(prevtok)],
- error_token,
- buffer[i]);
-
- candidate.symbol = 0;
- candidate.location = buffer[i];
-
- return candidate;
- }
-
-//
-// This function tries primary and scope recovery on each
-// available configuration. If a successful recovery is found
-// and no secondary phase recovery can do better, a diagnosis is
-// issued, the configuration is updated and the function returns
-// "true". Otherwise, it returns "false".
-//
- private RepairCandidate primaryPhase(int error_token) {
- PrimaryRepairInfo repair = new PrimaryRepairInfo();
- RepairCandidate candidate = new RepairCandidate();
-
- //
- // Initialize the buffer.
- //
- int i = (nextStackTop >= 0 ? 3 : 2);
- buffer[i] = error_token;
-
- for (int j = i; j > 0; j--)
- buffer[j - 1] = lexStream.previous(buffer[j]);
-
- for (int k = i + 1; k < BUFF_SIZE; k++)
- buffer[k] = lexStream.next(buffer[k - 1]);
-
- //
- // If NEXT_STACK_TOP > 0 then the parse was successful on CURTOK
- // and the error was detected on the successor of CURTOK. In
- // that case, first check whether or not primary recovery is
- // possible on next_stack ...
- //
- if (nextStackTop >= 0) {
- repair.bufferPosition = 3;
- repair = checkPrimaryDistance(nextStack, nextStackTop, repair);
- }
-
- //
- // ... Next, try primary recovery on the current token...
- //
- PrimaryRepairInfo new_repair = repair.copy();
-
- new_repair.bufferPosition = 2;
- new_repair = checkPrimaryDistance(stack, stateStackTop, new_repair);
- if (new_repair.distance > repair.distance || new_repair.misspellIndex > repair.misspellIndex) {
- repair = new_repair;
- }
-
- //
- // Finally, if prev_stack_top >= 0 then try primary recovery on
- // the prev_stack configuration.
- //
-
- if (prevStackTop >= 0) {
- new_repair = repair.copy();
- new_repair.bufferPosition = 1;
- new_repair = checkPrimaryDistance(prevStack,prevStackTop, new_repair);
- if (new_repair.distance > repair.distance || new_repair.misspellIndex > repair.misspellIndex) {
- repair = new_repair;
- }
- }
-
- //
- // Before accepting the best primary phase recovery obtained,
- // ensure that we cannot do better with a similar secondary
- // phase recovery.
- //
- if (nextStackTop >= 0) {// next_stack available
- if (secondaryCheck(nextStack,nextStackTop,3,repair.distance)) {
- return candidate;
- }
- }
- else if (secondaryCheck(stack, stateStackTop, 2, repair.distance)) {
- return candidate;
- }
-
- //
- // First, adjust distance if the recovery is on the error token;
- // it is important that the adjustment be made here and not at
- // each primary trial to prevent the distance tests from being
- // biased in favor of deferred recoveries which have access to
- // more input tokens...
- //
- repair.distance = repair.distance - repair.bufferPosition + 1;
-
- //
- // ...Next, adjust the distance if the recovery is a deletion or
- // (some form of) substitution...
- //
- if (repair.code == INVALID_CODE ||
- repair.code == DELETION_CODE ||
- repair.code == SUBSTITUTION_CODE ||
- repair.code == MERGE_CODE) {
- repair.distance--;
- }
-
- //
- // ... After adjustment, check if the most successful primary
- // recovery can be applied. If not, continue with more radical
- // recoveries...
- //
- if (repair.distance < MIN_DISTANCE) {
- return candidate;
- }
-
- //
- // When processing an insertion error, if the token preceeding
- // the error token is not available, we change the repair code
- // into a BEFORE_CODE to instruct the reporting routine that it
- // indicates that the repair symbol should be inserted before
- // the error token.
- //
- if (repair.code == INSERTION_CODE) {
- if (buffer[repair.bufferPosition - 1] == 0) {
- repair.code = BEFORE_CODE;
- }
- }
-
- //
- // Select the proper sequence of states on which to recover,
- // update stack accordingly and call diagnostic routine.
- //
- if (repair.bufferPosition == 1) {
- stateStackTop = prevStackTop;
- for (int j = 0; j <= stateStackTop; j++) {
- stack[j] = prevStack[j];
- }
- } else if (nextStackTop >= 0 && repair.bufferPosition >= 3) {
- stateStackTop = nextStackTop;
- for (int j = 0; j <= stateStackTop; j++) {
- stack[j] = nextStack[j];
- }
- locationStack[stateStackTop] = buffer[3];
- locationStartStack[stateStackTop] = lexStream.start(buffer[3]);
- }
-
- return primaryDiagnosis(repair);
- }
-
-
-//
-// This function checks whether or not a given state has a
-// candidate, whose string representaion is a merging of the two
-// tokens at positions buffer_position and buffer_position+1 in
-// the buffer. If so, it returns the candidate in question;
-// otherwise it returns 0.
-//
- private int mergeCandidate(int state, int buffer_position) {
- char[] name1 = lexStream.name(buffer[buffer_position]);
- char[] name2 = lexStream.name(buffer[buffer_position + 1]);
-
- int len = name1.length + name2.length;
-
- char[] str = CharOperation.concat(name1, name2);
-
- for (int k = Parser.asi(state); Parser.asr[k] != 0; k++) {
- int l = Parser.terminal_index[Parser.asr[k]];
-
- if (len == Parser.name[l].length()) {
- char[] name = Parser.name[l].toCharArray();
-
- if (CharOperation.equals(str, name, false)) {
- return Parser.asr[k];
- }
- }
- }
-
- return 0;
- }
-
-
-//
-// This procedure takes as arguments a parsing configuration
-// consisting of a state stack (stack and stack_top) and a fixed
-// number of input tokens (starting at buffer_position) in the
-// input BUFFER; and some reference arguments: repair_code,
-// distance, misspell_index, candidate, and stack_position
-// which it sets based on the best possible recovery that it
-// finds in the given configuration. The effectiveness of a
-// a repair is judged based on two criteria:
-//
-// 1) the number of tokens that can be parsed after the repair
-// is applied: distance.
-// 2) how close to perfection is the candidate that is chosen:
-// misspell_index.
-// When this procedure is entered, distance, misspell_index and
-// repair_code are assumed to be initialized.
-//
- private PrimaryRepairInfo checkPrimaryDistance(int stck[], int stack_top, PrimaryRepairInfo repair) {
- int i, j, k, next_state, max_pos, act, root, symbol, tok;
-
- //
- // First, try scope and manual recovery.
- //
- PrimaryRepairInfo scope_repair = scopeTrial(stck, stack_top, repair.copy());
- if (scope_repair.distance > repair.distance)
- repair = scope_repair;
-
- //
- // Next, try merging the error token with its successor.
- //
- if(buffer[repair.bufferPosition] != 0 && buffer[repair.bufferPosition + 1] != 0) {// do not merge the first token
- symbol = mergeCandidate(stck[stack_top], repair.bufferPosition);
- if (symbol != 0) {
- j = parseCheck(stck, stack_top, symbol, repair.bufferPosition+2);
- if ((j > repair.distance) || (j == repair.distance && repair.misspellIndex < 10)) {
- repair.misspellIndex = 10;
- repair.symbol = symbol;
- repair.distance = j;
- repair.code = MERGE_CODE;
- }
- }
- }
-
- //
- // Next, try deletion of the error token.
- //
- j = parseCheck(
- stck,
- stack_top,
- lexStream.kind(buffer[repair.bufferPosition + 1]),
- repair.bufferPosition + 2);
- if (lexStream.kind(buffer[repair.bufferPosition]) == EOLT_SYMBOL &&
- lexStream.afterEol(buffer[repair.bufferPosition+1])) {
- k = 10;
- } else {
- k = 0;
- }
- if (j > repair.distance || (j == repair.distance && k > repair.misspellIndex)) {
- repair.misspellIndex = k;
- repair.code = DELETION_CODE;
- repair.distance = j;
- }
-
- //
- // Update the error configuration by simulating all reduce and
- // goto actions induced by the error token. Then assign the top
- // most state of the new configuration to next_state.
- //
- next_state = stck[stack_top];
- max_pos = stack_top;
- tempStackTop = stack_top - 1;
-
- tok = lexStream.kind(buffer[repair.bufferPosition]);
- lexStream.reset(buffer[repair.bufferPosition + 1]);
- act = Parser.tAction(next_state, tok);
- while(act <= NUM_RULES) {
- do {
- tempStackTop -= (Parser.rhs[act]-1);
- symbol = Parser.lhs[act];
- act = (tempStackTop > max_pos
- ? tempStack[tempStackTop]
- : stck[tempStackTop]);
- act = Parser.ntAction(act, symbol);
- } while(act <= NUM_RULES);
- max_pos = max_pos < tempStackTop ? max_pos : tempStackTop;
- tempStack[tempStackTop + 1] = act;
- next_state = act;
- act = Parser.tAction(next_state, tok);
- }
-
- //
- // Next, place the list of candidates in proper order.
- //
- root = 0;
- for (i = Parser.asi(next_state); Parser.asr[i] != 0; i++) {
- symbol = Parser.asr[i];
- if (symbol != EOFT_SYMBOL && symbol != ERROR_SYMBOL) {
- if (root == 0) {
- list[symbol] = symbol;
- } else {
- list[symbol] = list[root];
- list[root] = symbol;
- }
- root = symbol;
- }
- }
-
- if (stck[stack_top] != next_state) {
- for (i = Parser.asi(stck[stack_top]); Parser.asr[i] != 0; i++) {
- symbol = Parser.asr[i];
- if (symbol != EOFT_SYMBOL && symbol != ERROR_SYMBOL && list[symbol] == 0) {
- if (root == 0) {
- list[symbol] = symbol;
- } else {
- list[symbol] = list[root];
- list[root] = symbol;
- }
- root = symbol;
- }
- }
- }
-
- i = list[root];
- list[root] = 0;
- root = i;
-
- //
- // Next, try insertion for each possible candidate available in
- // the current state, except EOFT and ERROR_SYMBOL.
- //
- symbol = root;
- while(symbol != 0) {
- if (symbol == EOLT_SYMBOL && lexStream.afterEol(buffer[repair.bufferPosition])) {
- k = 10;
- } else {
- k = 0;
- }
- j = parseCheck(stck, stack_top, symbol, repair.bufferPosition);
- if (j > repair.distance) {
- repair.misspellIndex = k;
- repair.distance = j;
- repair.symbol = symbol;
- repair.code = INSERTION_CODE;
- } else if (j == repair.distance && k > repair.misspellIndex) {
- repair.misspellIndex = k;
- repair.distance = j;
- repair.symbol = symbol;
- repair.code = INSERTION_CODE;
- } else if (j == repair.distance && k == repair.misspellIndex && isBetterSymbol(symbol, repair.symbol)) {
- repair.misspellIndex = k;
- repair.distance = j;
- repair.symbol = symbol;
- repair.code = INSERTION_CODE;
- }
-
- symbol = list[symbol];
- }
-
- //
- // Next, Try substitution for each possible candidate available
- // in the current state, except EOFT and ERROR_SYMBOL.
- //
- symbol = root;
-
- if(buffer[repair.bufferPosition] != 0) {// do not replace the first token
- while(symbol != 0) {
- if (symbol == EOLT_SYMBOL && lexStream.afterEol(buffer[repair.bufferPosition+1])) {
- k = 10;
- } else {
- k = misspell(symbol, buffer[repair.bufferPosition]);
- }
- j = parseCheck(stck, stack_top, symbol, repair.bufferPosition+1);
- if (j > repair.distance) {
- repair.misspellIndex = k;
- repair.distance = j;
- repair.symbol = symbol;
- repair.code = SUBSTITUTION_CODE;
- } else if (j == repair.distance && k > repair.misspellIndex) {
- repair.misspellIndex = k;
- repair.symbol = symbol;
- repair.code = SUBSTITUTION_CODE;
- } else if (j == repair.distance && k > repair.misspellIndex && isBetterSymbol(symbol, repair.symbol)) {
- repair.misspellIndex = k;
- repair.symbol = symbol;
- repair.code = SUBSTITUTION_CODE;
- }
- i = symbol;
- symbol = list[symbol];
- list[i] = 0; // reset element
- }
- }
-
-
- //
- // Next, we try to insert a nonterminal candidate in front of the
- // error token, or substituting a nonterminal candidate for the
- // error token. Precedence is given to insertion.
- //
- for (i = Parser.nasi(stck[stack_top]); Parser.nasr[i] != 0; i++) {
- symbol = Parser.nasr[i] + NT_OFFSET;
- j = parseCheck(stck, stack_top, symbol, repair.bufferPosition+1);
- if (j > repair.distance) {
- repair.misspellIndex = 0;
- repair.distance = j;
- repair.symbol = symbol;
- repair.code = INVALID_CODE;
- }
-
- j = parseCheck(stck, stack_top, symbol, repair.bufferPosition);
- if ((j > repair.distance) || (j == repair.distance && repair.code == INVALID_CODE)) {
- repair.misspellIndex = 0;
- repair.distance = j;
- repair.symbol = symbol;
- repair.code = INSERTION_CODE;
- }
- }
-
- return repair;
- }
-
-
-//
-// This procedure is invoked to issue a diagnostic message and
-// adjust the input buffer. The recovery in question is either
-// the insertion of one or more scopes, the merging of the error
-// token with its successor, the deletion of the error token,
-// the insertion of a single token in front of the error token
-// or the substitution of another token for the error token.
-//
- private RepairCandidate primaryDiagnosis(PrimaryRepairInfo repair) {
- int name_index;
-
- //
- // Issue diagnostic.
- //
- int prevtok = buffer[repair.bufferPosition - 1];
- int curtok = buffer[repair.bufferPosition];
-
- switch(repair.code) {
- case INSERTION_CODE:
- case BEFORE_CODE: {
- if (repair.symbol > NT_OFFSET)
- name_index = getNtermIndex(stack[stateStackTop],
- repair.symbol,
- repair.bufferPosition);
- else name_index = getTermIndex(stack,
- stateStackTop,
- repair.symbol,
- repair.bufferPosition);
-
- int t = (repair.code == INSERTION_CODE ? prevtok : curtok);
- reportError(repair.code, name_index, t, t);
- break;
- }
- case INVALID_CODE: {
- name_index = getNtermIndex(stack[stateStackTop],
- repair.symbol,
- repair.bufferPosition + 1);
- reportError(repair.code, name_index, curtok, curtok);
- break;
- }
- case SUBSTITUTION_CODE: {
- if (repair.misspellIndex >= 6)
- name_index = Parser.terminal_index[repair.symbol];
- else
- {
- name_index = getTermIndex(stack, stateStackTop,
- repair.symbol,
- repair.bufferPosition + 1);
- if (name_index != Parser.terminal_index[repair.symbol])
- repair.code = INVALID_CODE;
- }
- reportError(repair.code, name_index, curtok, curtok);
- break;
- }
- case MERGE_CODE: {
- reportError(repair.code,
- Parser.terminal_index[repair.symbol],
- curtok,
- lexStream.next(curtok));
- break;
- }
- case SCOPE_CODE: {
- for (int i = 0; i < scopeStackTop; i++) {
- reportError(repair.code,
- -scopeIndex[i],
- locationStack[scopePosition[i]],
- prevtok,
- Parser.non_terminal_index[Parser.scope_lhs[scopeIndex[i]]]);
- }
-
- repair.symbol = Parser.scope_lhs[scopeIndex[scopeStackTop]] + NT_OFFSET;
- stateStackTop = scopePosition[scopeStackTop];
- reportError(repair.code,
- -scopeIndex[scopeStackTop],
- locationStack[scopePosition[scopeStackTop]],
- prevtok,
- getNtermIndex(stack[stateStackTop],
- repair.symbol,
- repair.bufferPosition)
- );
- break;
- }
- default: {// deletion
- reportError(repair.code, Parser.terminal_index[ERROR_SYMBOL], curtok, curtok);
- }
- }
-
- //
- // Update buffer.
- //
- RepairCandidate candidate = new RepairCandidate();
- switch (repair.code) {
- case INSERTION_CODE:
- case BEFORE_CODE:
- case SCOPE_CODE: {
- candidate.symbol = repair.symbol;
- candidate.location = buffer[repair.bufferPosition];
- lexStream.reset(buffer[repair.bufferPosition]);
- break;
- }
- case INVALID_CODE:
- case SUBSTITUTION_CODE: {
- candidate.symbol = repair.symbol;
- candidate.location = buffer[repair.bufferPosition];
- lexStream.reset(buffer[repair.bufferPosition + 1]);
- break;
- }
- case MERGE_CODE: {
- candidate.symbol = repair.symbol;
- candidate.location = buffer[repair.bufferPosition];
- lexStream.reset(buffer[repair.bufferPosition + 2]);
- break;
- }
- default: {// deletion
- candidate.location = buffer[repair.bufferPosition + 1];
- candidate.symbol =
- lexStream.kind(buffer[repair.bufferPosition + 1]);
- lexStream.reset(buffer[repair.bufferPosition + 2]);
- break;
- }
- }
-
- return candidate;
- }
-
-
-//
-// This function takes as parameter an integer STACK_TOP that
-// points to a STACK element containing the state on which a
-// primary recovery will be made; the terminal candidate on which
-// to recover; and an integer: buffer_position, which points to
-// the position of the next input token in the BUFFER. The
-// parser is simulated until a shift (or shift-reduce) action
-// is computed on the candidate. Then we proceed to compute the
-// the name index of the highest level nonterminal that can
-// directly or indirectly produce the candidate.
-//
- private int getTermIndex(int stck[], int stack_top, int tok, int buffer_position) {
- //
- // Initialize stack index of temp_stack and initialize maximum
- // position of state stack that is still useful.
- //
- int act = stck[stack_top],
- max_pos = stack_top,
- highest_symbol = tok;
-
- tempStackTop = stack_top - 1;
-
- //
- // Compute all reduce and associated actions induced by the
- // candidate until a SHIFT or SHIFT-REDUCE is computed. ERROR
- // and ACCEPT actions cannot be computed on the candidate in
- // this context, since we know that it is suitable for recovery.
- //
- lexStream.reset(buffer[buffer_position]);
- act = Parser.tAction(act, tok);
- while(act <= NUM_RULES) {
- //
- // Process all goto-reduce actions following reduction,
- // until a goto action is computed ...
- //
- do {
- tempStackTop -= (Parser.rhs[act]-1);
- int lhs_symbol = Parser.lhs[act];
- act = (tempStackTop > max_pos
- ? tempStack[tempStackTop]
- : stck[tempStackTop]);
- act = Parser.ntAction(act, lhs_symbol);
- } while(act <= NUM_RULES);
-
- //
- // Compute new maximum useful position of (STATE_)stack,
- // push goto state into the stack, and compute next
- // action on candidate ...
- //
- max_pos = max_pos < tempStackTop ? max_pos : tempStackTop;
- tempStack[tempStackTop + 1] = act;
- act = Parser.tAction(act, tok);
- }
-
- //
- // At this stage, we have simulated all actions induced by the
- // candidate and we are ready to shift or shift-reduce it. First,
- // set tok and next_ptr appropriately and identify the candidate
- // as the initial highest_symbol. If a shift action was computed
- // on the candidate, update the stack and compute the next
- // action. Next, simulate all actions possible on the next input
- // token until we either have to shift it or are about to reduce
- // below the initial starting point in the stack (indicated by
- // max_pos as computed in the previous loop). At that point,
- // return the highest_symbol computed.
- //
- tempStackTop++; // adjust top of stack to reflect last goto
- // next move is shift or shift-reduce.
- int threshold = tempStackTop;
-
- tok = lexStream.kind(buffer[buffer_position]);
- lexStream.reset(buffer[buffer_position + 1]);
-
- if (act > ERROR_ACTION) { // shift-reduce on candidate?
- act -= ERROR_ACTION;
- } else {
- tempStack[tempStackTop + 1] = act;
- act = Parser.tAction(act, tok);
- }
-
- while(act <= NUM_RULES) {
- //
- // Process all goto-reduce actions following reduction,
- // until a goto action is computed ...
- //
- do {
- tempStackTop -= (Parser.rhs[act]-1);
-
- if (tempStackTop < threshold) {
- return (highest_symbol > NT_OFFSET
- ? Parser.non_terminal_index[highest_symbol - NT_OFFSET]
- : Parser.terminal_index[highest_symbol]);
- }
-
- int lhs_symbol = Parser.lhs[act];
- if (tempStackTop == threshold)
- highest_symbol = lhs_symbol + NT_OFFSET;
- act = (tempStackTop > max_pos
- ? tempStack[tempStackTop]
- : stck[tempStackTop]);
- act = Parser.ntAction(act, lhs_symbol);
- } while(act <= NUM_RULES);
-
- tempStack[tempStackTop + 1] = act;
- act = Parser.tAction(act, tok);
- }
-
- return (highest_symbol > NT_OFFSET
- ? Parser.non_terminal_index[highest_symbol - NT_OFFSET]
- : Parser.terminal_index[highest_symbol]);
- }
-
-//
-// This function takes as parameter a starting state number:
-// start, a nonterminal symbol, A (candidate), and an integer,
-// buffer_position, which points to the position of the next
-// input token in the BUFFER.
-// It returns the highest level non-terminal B such that
-// B =>*rm A. I.e., there does not exists a nonterminal C such
-// that C =>+rm B. (Recall that for an LALR(k) grammar if
-// C =>+rm B, it cannot be the case that B =>+rm C)
-//
- private int getNtermIndex(int start, int sym, int buffer_position) {
- int highest_symbol = sym - NT_OFFSET,
- tok = lexStream.kind(buffer[buffer_position]);
- lexStream.reset(buffer[buffer_position + 1]);
-
- //
- // Initialize stack index of temp_stack and initialize maximum
- // position of state stack that is still useful.
- //
- tempStackTop = 0;
- tempStack[tempStackTop] = start;
-
- int act = Parser.ntAction(start, highest_symbol);
- if (act > NUM_RULES) { // goto action?
- tempStack[tempStackTop + 1] = act;
- act = Parser.tAction(act, tok);
- }
-
- while(act <= NUM_RULES) {
- //
- // Process all goto-reduce actions following reduction,
- // until a goto action is computed ...
- //
- do {
- tempStackTop -= (Parser.rhs[act]-1);
- if (tempStackTop < 0)
- return Parser.non_terminal_index[highest_symbol];
- if (tempStackTop == 0)
- highest_symbol = Parser.lhs[act];
- act = Parser.ntAction(tempStack[tempStackTop], Parser.lhs[act]);
- } while(act <= NUM_RULES);
- tempStack[tempStackTop + 1] = act;
- act = Parser.tAction(act, tok);
- }
-
- return Parser.non_terminal_index[highest_symbol];
- }
-
- private boolean isBetterSymbol(int symbol, int actualSymbol) {
-// switch (actualSymbol) {
-// case TokenNameinterface :
-// if(symbol == TokenNameclass) {
-// return true;
-// }
-// break;
-// }
- return false;
- }
-
-//
-// Check whether or not there is a high probability that a
-// given string is a misspelling of another.
-// Certain singleton symbols (such as ":" and ";") are also
-// considered to be misspelling of each other.
-//
- private int misspell(int sym, int tok) {
-
-
- //
- //
- //
- char[] name = Parser.name[Parser.terminal_index[sym]].toCharArray();
- int n = name.length;
- char[] s1 = new char[n + 1];
- for (int k = 0; k < n; k++) {
- char c = name[k];
- s1[k] = ScannerHelper.toLowerCase(c);
- }
- s1[n] = '\0';
-
- //
- //
- //
- char[] tokenName = lexStream.name(tok);
- int len = tokenName.length;
- int m = len < MAX_NAME_LENGTH ? len : MAX_NAME_LENGTH;
- char[] s2 = new char[m + 1];
- for (int k = 0; k < m; k++) {
- char c = tokenName[k];
- s2[k] = ScannerHelper.toLowerCase(c);
- }
- s2[m] = '\0';
-
- //
- // Singleton mispellings:
- //
- // ; <----> ,
- //
- // ; <----> :
- //
- // . <----> ,
- //
- // ' <----> "
- //
- //
- if (n == 1 && m == 1) {
- if ((s1[0] == ';' && s2[0] == ',') ||
- (s1[0] == ',' && s2[0] == ';') ||
- (s1[0] == ';' && s2[0] == ':') ||
- (s1[0] == ':' && s2[0] == ';') ||
- (s1[0] == '.' && s2[0] == ',') ||
- (s1[0] == ',' && s2[0] == '.') ||
- (s1[0] == '\'' && s2[0] == '\"') ||
- (s1[0] == '\"' && s2[0] == '\'')) {
- return 3;
- }
- }
-
- //
- // Scan the two strings. Increment "match" count for each match.
- // When a transposition is encountered, increase "match" count
- // by two but count it as an error. When a typo is found, skip
- // it and count it as an error. Otherwise we have a mismatch; if
- // one of the strings is longer, increment its index, otherwise,
- // increment both indices and continue.
- //
- // This algorithm is an adaptation of a boolean misspelling
- // algorithm proposed by Juergen Uhl.
- //
- int count = 0;
- int prefix_length = 0;
- int num_errors = 0;
-
- int i = 0;
- int j = 0;
- while ((i < n) && (j < m)) {
- if (s1[i] == s2[j]) {
- count++;
- i++;
- j++;
- if (num_errors == 0) {
- prefix_length++;
- }
- } else if (s1[i+1] == s2[j] && s1[i] == s2[j+1]) {
- count += 2;
- i += 2;
- j += 2;
- num_errors++;
- } else if (s1[i+1] == s2[j+1]) {
- i++;
- j++;
- num_errors++;
- } else {
- if ((n - i) > (m - j)) {
- i++;
- } else if ((m - j) > (n - i)) {
- j++;
- } else {
- i++;
- j++;
- }
- num_errors++;
- }
- }
-
- if (i < n || j < m)
- num_errors++;
-
- if (num_errors > ((n < m ? n : m) / 6 + 1))
- count = prefix_length;
-
- return(count * 10 / ((n < len ? len : n) + num_errors));
- }
-
- private PrimaryRepairInfo scopeTrial(int stck[], int stack_top, PrimaryRepairInfo repair) {
- stateSeen = new int[stackLength];
- for (int i = 0; i < stackLength; i++)
- stateSeen[i] = NIL;
-
- statePoolTop = 0;
- statePool = new StateInfo[stackLength];
-
- scopeTrialCheck(stck, stack_top, repair, 0);
-
- stateSeen = null;
- statePoolTop = 0;
-
- repair.code = SCOPE_CODE;
- repair.misspellIndex = 10;
-
- return repair;
- }
-
- private void scopeTrialCheck(int stck[], int stack_top, PrimaryRepairInfo repair, int indx) {
- if(indx > 20) return; // avoid too much recursive call to improve performance
-
- int act = stck[stack_top];
-
- for (int i = stateSeen[stack_top]; i != NIL; i = statePool[i].next) {
- if (statePool[i].state == act) return;
- }
-
- int old_state_pool_top = statePoolTop++;
- if(statePoolTop >= statePool.length) {
- System.arraycopy(statePool, 0, statePool = new StateInfo[statePoolTop * 2], 0, statePoolTop);
- }
-
- statePool[old_state_pool_top] = new StateInfo(act, stateSeen[stack_top]);
- stateSeen[stack_top] = old_state_pool_top;
-
- next : for (int i = 0; i < SCOPE_SIZE; i++) {
- //
- // Use the scope lookahead symbol to force all reductions
- // inducible by that symbol.
- //
- act = stck[stack_top];
- tempStackTop = stack_top - 1;
- int max_pos = stack_top;
- int tok = Parser.scope_la[i];
- lexStream.reset(buffer[repair.bufferPosition]);
- act = Parser.tAction(act, tok);
- while(act <= NUM_RULES) {
- //
- // ... Process all goto-reduce actions following
- // reduction, until a goto action is computed ...
- //
- do {
- tempStackTop -= (Parser.rhs[act]-1);
- int lhs_symbol = Parser.lhs[act];
- act = (tempStackTop > max_pos
- ? tempStack[tempStackTop]
- : stck[tempStackTop]);
- act = Parser.ntAction(act, lhs_symbol);
- } while(act <= NUM_RULES);
- if (tempStackTop + 1 >= stackLength)
- return;
- max_pos = max_pos < tempStackTop ? max_pos : tempStackTop;
- tempStack[tempStackTop + 1] = act;
- act = Parser.tAction(act, tok);
- }
-
- //
- // If the lookahead symbol is parsable, then we check
- // whether or not we have a match between the scope
- // prefix and the transition symbols corresponding to
- // the states on top of the stack.
- //
- if (act != ERROR_ACTION) {
- int j, k;
- k = Parser.scope_prefix[i];
- for (j = tempStackTop + 1;
- j >= (max_pos + 1) &&
- Parser.in_symbol(tempStack[j]) == Parser.scope_rhs[k]; j--) {
- k++;
- }
- if (j == max_pos) {
- for (j = max_pos;
- j >= 1 && Parser.in_symbol(stck[j]) == Parser.scope_rhs[k];
- j--) {
- k++;
- }
- }
- //
- // If the prefix matches, check whether the state
- // newly exposed on top of the stack, (after the
- // corresponding prefix states are popped from the
- // stack), is in the set of "source states" for the
- // scope in question and that it is at a position
- // below the threshold indicated by MARKED_POS.
- //
- int marked_pos = (max_pos < stack_top ? max_pos + 1 : stack_top);
- if (Parser.scope_rhs[k] == 0 && j < marked_pos) { // match?
- int stack_position = j;
- for (j = Parser.scope_state_set[i];
- stck[stack_position] != Parser.scope_state[j] &&
- Parser.scope_state[j] != 0;
- j++){/*empty*/}
- //
- // If the top state is valid for scope recovery,
- // the left-hand side of the scope is used as
- // starting symbol and we calculate how far the
- // parser can advance within the forward context
- // after parsing the left-hand symbol.
- //
- if (Parser.scope_state[j] != 0) { // state was found
- int previous_distance = repair.distance;
- int distance = parseCheck(stck,
- stack_position,
- Parser.scope_lhs[i]+NT_OFFSET,
- repair.bufferPosition);
- //
- // if the recovery is not successful, we
- // update the stack with all actions induced
- // by the left-hand symbol, and recursively
- // call SCOPE_TRIAL_CHECK to try again.
- // Otherwise, the recovery is successful. If
- // the new distance is greater than the
- // initial SCOPE_DISTANCE, we update
- // SCOPE_DISTANCE and set scope_stack_top to INDX
- // to indicate the number of scopes that are
- // to be applied for a succesful recovery.
- // NOTE that this procedure cannot get into
- // an infinite loop, since each prefix match
- // is guaranteed to take us to a lower point
- // within the stack.
- //
- if ((distance - repair.bufferPosition + 1) < MIN_DISTANCE) {
- int top = stack_position;
- act = Parser.ntAction(stck[top], Parser.scope_lhs[i]);
- while(act <= NUM_RULES) {
- if(Parser.rules_compliance[act] > this.options.sourceLevel) {
- continue next;
- }
- top -= (Parser.rhs[act]-1);
- act = Parser.ntAction(stck[top], Parser.lhs[act]);
- }
- top++;
-
- j = act;
- act = stck[top]; // save
- stck[top] = j; // swap
- scopeTrialCheck(stck, top, repair, indx+1);
- stck[top] = act; // restore
- } else if (distance > repair.distance) {
- scopeStackTop = indx;
- repair.distance = distance;
- }
-
- if (lexStream.kind(buffer[repair.bufferPosition]) == EOFT_SYMBOL &&
- repair.distance == previous_distance) {
- scopeStackTop = indx;
- repair.distance = MAX_DISTANCE;
- }
-
- //
- // If this scope recovery has beaten the
- // previous distance, then we have found a
- // better recovery (or this recovery is one
- // of a list of scope recoveries). Record
- // its information at the proper location
- // (INDX) in SCOPE_INDEX and SCOPE_STACK.
- //
- if (repair.distance > previous_distance) {
- scopeIndex[indx] = i;
- scopePosition[indx] = stack_position;
- return;
- }
- }
- }
- }
- }
- }
-//
-// This function computes the ParseCheck distance for the best
-// possible secondary recovery for a given configuration that
-// either deletes none or only one symbol in the forward context.
-// If the recovery found is more effective than the best primary
-// recovery previously computed, then the function returns true.
-// Only misplacement, scope and manual recoveries are attempted;
-// simple insertion or substitution of a nonterminal are tried
-// in CHECK_PRIMARY_DISTANCE as part of primary recovery.
-//
- private boolean secondaryCheck(int stck[], int stack_top, int buffer_position, int distance) {
- int top, j;
-
- for (top = stack_top - 1; top >= 0; top--) {
- j = parseCheck(stck, top,
- lexStream.kind(buffer[buffer_position]),
- buffer_position + 1);
- if (((j - buffer_position + 1) > MIN_DISTANCE) && (j > distance))
- return true;
- }
-
- PrimaryRepairInfo repair = new PrimaryRepairInfo();
- repair.bufferPosition = buffer_position + 1;
- repair.distance = distance;
- repair = scopeTrial(stck, stack_top, repair);
- if ((repair.distance - buffer_position) > MIN_DISTANCE && repair.distance > distance)
- return true;
- return false;
- }
-
-
-//
-// Secondary_phase is a boolean function that checks whether or
-// not some form of secondary recovery is applicable to one of
-// the error configurations. First, if "next_stack" is available,
-// misplacement and secondary recoveries are attempted on it.
-// Then, in any case, these recoveries are attempted on "stack".
-// If a successful recovery is found, a diagnosis is issued, the
-// configuration is updated and the function returns "true".
-// Otherwise, the function returns false.
-//
- private RepairCandidate secondaryPhase(int error_token) {
- SecondaryRepairInfo repair = new SecondaryRepairInfo();
- SecondaryRepairInfo misplaced = new SecondaryRepairInfo();
-
- RepairCandidate candidate = new RepairCandidate();
-
- int i, j, k, top;
- int next_last_index = 0;
- int last_index;
-
- candidate.symbol = 0;
-
- repair.code = 0;
- repair.distance = 0;
- repair.recoveryOnNextStack = false;
-
- misplaced.distance = 0;
- misplaced.recoveryOnNextStack = false;
-
- //
- // If the next_stack is available, try misplaced and secondary
- // recovery on it first.
- //
- if (nextStackTop >= 0) {
- int save_location;
-
- buffer[2] = error_token;
- buffer[1] = lexStream.previous(buffer[2]);
- buffer[0] = lexStream.previous(buffer[1]);
-
- for (k = 3; k < BUFF_UBOUND; k++)
- buffer[k] = lexStream.next(buffer[k - 1]);
-
- buffer[BUFF_UBOUND] = lexStream.badtoken();// elmt not available
-
- //
- // If we are at the end of the input stream, compute the
- // index position of the first EOFT symbol (last useful
- // index).
- //
- for (next_last_index = MAX_DISTANCE - 1;
- next_last_index >= 1 &&
- lexStream.kind(buffer[next_last_index]) == EOFT_SYMBOL;
- next_last_index--){/*empty*/}
- next_last_index = next_last_index + 1;
-
- save_location = locationStack[nextStackTop];
- int save_location_start = locationStartStack[nextStackTop];
- locationStack[nextStackTop] = buffer[2];
- locationStartStack[nextStackTop] = lexStream.start(buffer[2]);
- misplaced.numDeletions = nextStackTop;
- misplaced = misplacementRecovery(nextStack, nextStackTop,
- next_last_index,
- misplaced, true);
- if (misplaced.recoveryOnNextStack)
- misplaced.distance++;
-
- repair.numDeletions = nextStackTop + BUFF_UBOUND;
- repair = secondaryRecovery(nextStack, nextStackTop,
- next_last_index,
- repair, true);
- if (repair.recoveryOnNextStack)
- repair.distance++;
-
- locationStack[nextStackTop] = save_location;
- locationStartStack[nextStackTop] = save_location_start;
- } else { // next_stack not available, initialize ...
- misplaced.numDeletions = stateStackTop;
- repair.numDeletions = stateStackTop + BUFF_UBOUND;
- }
-
- //
- // Try secondary recovery on the "stack" configuration.
- //
- buffer[3] = error_token;
-
- buffer[2] = lexStream.previous(buffer[3]);
- buffer[1] = lexStream.previous(buffer[2]);
- buffer[0] = lexStream.previous(buffer[1]);
-
- for (k = 4; k < BUFF_SIZE; k++)
- buffer[k] = lexStream.next(buffer[k - 1]);
-
- for (last_index = MAX_DISTANCE - 1;
- last_index >= 1 && lexStream.kind(buffer[last_index]) == EOFT_SYMBOL;
- last_index--){/*empty*/}
- last_index++;
-
- misplaced = misplacementRecovery(stack, stateStackTop,
- last_index,
- misplaced, false);
-
- repair = secondaryRecovery(stack, stateStackTop,
- last_index, repair, false);
-
- //
- // If a successful misplaced recovery was found, compare it with
- // the most successful secondary recovery. If the misplaced
- // recovery either deletes fewer symbols or parse-checks further
- // then it is chosen.
- //
- if (misplaced.distance > MIN_DISTANCE) {
- if (misplaced.numDeletions <= repair.numDeletions ||
- (misplaced.distance - misplaced.numDeletions) >=
- (repair.distance - repair.numDeletions)) {
- repair.code = MISPLACED_CODE;
- repair.stackPosition = misplaced.stackPosition;
- repair.bufferPosition = 2;
- repair.numDeletions = misplaced.numDeletions;
- repair.distance = misplaced.distance;
- repair.recoveryOnNextStack = misplaced.recoveryOnNextStack;
- }
- }
-
- //
- // If the successful recovery was on next_stack, update: stack,
- // buffer, location_stack and last_index.
- //
- if (repair.recoveryOnNextStack) {
- stateStackTop = nextStackTop;
- for (i = 0; i <= stateStackTop; i++)
- stack[i] = nextStack[i];
-
- buffer[2] = error_token;
- buffer[1] = lexStream.previous(buffer[2]);
- buffer[0] = lexStream.previous(buffer[1]);
-
- for (k = 3; k < BUFF_UBOUND; k++)
- buffer[k] = lexStream.next(buffer[k - 1]);
-
- buffer[BUFF_UBOUND] = lexStream.badtoken();// elmt not available
-
- locationStack[nextStackTop] = buffer[2];
- locationStartStack[nextStackTop] = lexStream.start(buffer[2]);
- last_index = next_last_index;
- }
-
- //
- // Next, try scope recoveries after deletion of one, two, three,
- // four ... buffer_position tokens from the input stream.
- //
- if (repair.code == SECONDARY_CODE || repair.code == DELETION_CODE) {
- PrimaryRepairInfo scope_repair = new PrimaryRepairInfo();
-
- scope_repair.distance = 0;
- for (scope_repair.bufferPosition = 2;
- scope_repair.bufferPosition <= repair.bufferPosition &&
- repair.code != SCOPE_CODE; scope_repair.bufferPosition++) {
- scope_repair = scopeTrial(stack, stateStackTop, scope_repair);
- j = (scope_repair.distance == MAX_DISTANCE
- ? last_index
- : scope_repair.distance);
- k = scope_repair.bufferPosition - 1;
- if ((j - k) > MIN_DISTANCE && (j - k) > (repair.distance - repair.numDeletions)) {
- repair.code = SCOPE_CODE;
- i = scopeIndex[scopeStackTop]; // upper bound
- repair.symbol = Parser.scope_lhs[i] + NT_OFFSET;
- repair.stackPosition = stateStackTop;
- repair.bufferPosition = scope_repair.bufferPosition;
- }
- }
- }
-
- //
- // If no successful recovery is found and we have reached the
- // end of the file, check whether or not scope recovery is
- // applicable at the end of the file after discarding some
- // states.
- //
- if (repair.code == 0 && lexStream.kind(buffer[last_index]) == EOFT_SYMBOL) {
- PrimaryRepairInfo scope_repair = new PrimaryRepairInfo();
-
- scope_repair.bufferPosition = last_index;
- scope_repair.distance = 0;
- for (top = stateStackTop;
- top >= 0 && repair.code == 0; top--)
- {
- scope_repair = scopeTrial(stack, top, scope_repair);
- if (scope_repair.distance > 0)
- {
- repair.code = SCOPE_CODE;
- i = scopeIndex[scopeStackTop]; // upper bound
- repair.symbol = Parser.scope_lhs[i] + NT_OFFSET;
- repair.stackPosition = top;
- repair.bufferPosition = scope_repair.bufferPosition;
- }
- }
- }
-
- //
- // If a successful repair was not found, quit! Otherwise, issue
- // diagnosis and adjust configuration...
- //
- if (repair.code == 0)
- return candidate;
-
- secondaryDiagnosis(repair);
-
- //
- // Update buffer based on number of elements that are deleted.
- //
- switch(repair.code) {
- case MISPLACED_CODE:
- candidate.location = buffer[2];
- candidate.symbol = lexStream.kind(buffer[2]);
- lexStream.reset(lexStream.next(buffer[2]));
-
- break;
-
- case DELETION_CODE:
- candidate.location = buffer[repair.bufferPosition];
- candidate.symbol =
- lexStream.kind(buffer[repair.bufferPosition]);
- lexStream.reset(lexStream.next(buffer[repair.bufferPosition]));
-
- break;
-
- default: // SCOPE_CODE || SECONDARY_CODE
- candidate.symbol = repair.symbol;
- candidate.location = buffer[repair.bufferPosition];
- lexStream.reset(buffer[repair.bufferPosition]);
-
- break;
- }
-
- return candidate;
- }
-
-
-//
-// This boolean function checks whether or not a given
-// configuration yields a better misplacement recovery than
-// the best misplacement recovery computed previously.
-//
- private SecondaryRepairInfo misplacementRecovery(int stck[], int stack_top, int last_index, SecondaryRepairInfo repair, boolean stack_flag) {
- int previous_loc = buffer[2];
- int stack_deletions = 0;
-
- for (int top = stack_top - 1; top >= 0; top--) {
- if (locationStack[top] < previous_loc) {
- stack_deletions++;
- }
- previous_loc = locationStack[top];
-
- int j = parseCheck(stck, top, lexStream.kind(buffer[2]), 3);
- if (j == MAX_DISTANCE) {
- j = last_index;
- }
- if ((j > MIN_DISTANCE) && (j - stack_deletions) > (repair.distance - repair.numDeletions)) {
- repair.stackPosition = top;
- repair.distance = j;
- repair.numDeletions = stack_deletions;
- repair.recoveryOnNextStack = stack_flag;
- }
- }
-
- return repair;
- }
-
-
-//
-// This boolean function checks whether or not a given
-// configuration yields a better secondary recovery than the
-// best misplacement recovery computed previously.
-//
- private SecondaryRepairInfo secondaryRecovery(int stck[],int stack_top, int last_index, SecondaryRepairInfo repair, boolean stack_flag) {
- int previous_loc;
- int stack_deletions = 0;
-
- previous_loc = buffer[2];
- for (int top = stack_top; top >= 0 && repair.numDeletions >= stack_deletions; top--) {
- if (locationStack[top] < previous_loc) {
- stack_deletions++;
- }
- previous_loc = locationStack[top];
-
- for (int i = 2;
- i <= (last_index - MIN_DISTANCE + 1) &&
- (repair.numDeletions >= (stack_deletions + i - 1)); i++) {
- int j = parseCheck(stck, top, lexStream.kind(buffer[i]), i + 1);
-
- if (j == MAX_DISTANCE) {
- j = last_index;
- }
- if ((j - i + 1) > MIN_DISTANCE) {
- int k = stack_deletions + i - 1;
- if ((k < repair.numDeletions) ||
- (j - k) > (repair.distance - repair.numDeletions) ||
- ((repair.code == SECONDARY_CODE) && (j - k) == (repair.distance - repair.numDeletions))) {
- repair.code = DELETION_CODE;
- repair.distance = j;
- repair.stackPosition = top;
- repair.bufferPosition = i;
- repair.numDeletions = k;
- repair.recoveryOnNextStack = stack_flag;
- }
- }
-
- for (int l = Parser.nasi(stck[top]); l >= 0 && Parser.nasr[l] != 0; l++) {
- int symbol = Parser.nasr[l] + NT_OFFSET;
- j = parseCheck(stck, top, symbol, i);
- if (j == MAX_DISTANCE) {
- j = last_index;
- }
- if ((j - i + 1) > MIN_DISTANCE) {
- int k = stack_deletions + i - 1;
- if (k < repair.numDeletions || (j - k) > (repair.distance - repair.numDeletions)) {
- repair.code = SECONDARY_CODE;
- repair.symbol = symbol;
- repair.distance = j;
- repair.stackPosition = top;
- repair.bufferPosition = i;
- repair.numDeletions = k;
- repair.recoveryOnNextStack = stack_flag;
- }
- }
- }
- }
- }
-
- return repair;
- }
-
-
-//
-// This procedure is invoked to issue a secondary diagnosis and
-// adjust the input buffer. The recovery in question is either
-// an automatic scope recovery, a manual scope recovery, a
-// secondary substitution or a secondary deletion.
-//
- private void secondaryDiagnosis(SecondaryRepairInfo repair) {
- switch(repair.code) {
- case SCOPE_CODE: {
- if (repair.stackPosition < stateStackTop) {
- reportError(DELETION_CODE,
- Parser.terminal_index[ERROR_SYMBOL],
- locationStack[repair.stackPosition],
- buffer[1]);
- }
- for (int i = 0; i < scopeStackTop; i++) {
- reportError(SCOPE_CODE,
- -scopeIndex[i],
- locationStack[scopePosition[i]],
- buffer[1],
- Parser.non_terminal_index[Parser.scope_lhs[scopeIndex[i]]]);
- }
-
- repair.symbol = Parser.scope_lhs[scopeIndex[scopeStackTop]] + NT_OFFSET;
- stateStackTop = scopePosition[scopeStackTop];
- reportError(SCOPE_CODE,
- -scopeIndex[scopeStackTop],
- locationStack[scopePosition[scopeStackTop]],
- buffer[1],
- getNtermIndex(stack[stateStackTop],
- repair.symbol,
- repair.bufferPosition)
- );
- break;
- }
- default: {
- reportError(repair.code,
- (repair.code == SECONDARY_CODE
- ? getNtermIndex(stack[repair.stackPosition],
- repair.symbol,
- repair.bufferPosition)
- : Parser.terminal_index[ERROR_SYMBOL]),
- locationStack[repair.stackPosition],
- buffer[repair.bufferPosition - 1]);
- stateStackTop = repair.stackPosition;
- }
- }
- }
-
-
-
-
-//
-// Try to parse until first_token and all tokens in BUFFER have
-// been consumed, or an error is encountered. Return the number
-// of tokens that were expended before the parse blocked.
-//
- private int parseCheck(int stck[], int stack_top, int first_token, int buffer_position) {
- int max_pos;
- int indx;
- int ct;
- int act;
-
- //
- // Initialize pointer for temp_stack and initialize maximum
- // position of state stack that is still useful.
- //
- act = stck[stack_top];
- if (first_token > NT_OFFSET) {
- tempStackTop = stack_top;
- if(DEBUG_PARSECHECK) {
- System.out.println(tempStackTop);
- }
- max_pos = stack_top;
- indx = buffer_position;
- ct = lexStream.kind(buffer[indx]);
- lexStream.reset(lexStream.next(buffer[indx]));
- int lhs_symbol = first_token - NT_OFFSET;
- act = Parser.ntAction(act, lhs_symbol);
- if (act <= NUM_RULES) {
- // same loop as 'process_non_terminal'
- do {
- tempStackTop -= (Parser.rhs[act]-1);
-
- if(DEBUG_PARSECHECK) {
- System.out.print(tempStackTop);
- System.out.print(" ("); //$NON-NLS-1$
- System.out.print(-(Parser.rhs[act]-1));
- System.out.print(") [max:"); //$NON-NLS-1$
- System.out.print(max_pos);
- System.out.print("]\tprocess_non_terminal\t"); //$NON-NLS-1$
- System.out.print(act);
- System.out.print("\t"); //$NON-NLS-1$
- System.out.print(Parser.name[Parser.non_terminal_index[Parser.lhs[act]]]);
- System.out.println();
- }
-
- if(Parser.rules_compliance[act] > this.options.sourceLevel) {
- return 0;
- }
- lhs_symbol = Parser.lhs[act];
- act = (tempStackTop > max_pos
- ? tempStack[tempStackTop]
- : stck[tempStackTop]);
- act = Parser.ntAction(act, lhs_symbol);
- } while(act <= NUM_RULES);
-
- max_pos = max_pos < tempStackTop ? max_pos : tempStackTop;
- }
- } else {
- tempStackTop = stack_top - 1;
-
- if(DEBUG_PARSECHECK) {
- System.out.println(tempStackTop);
- }
-
- max_pos = tempStackTop;
- indx = buffer_position - 1;
- ct = first_token;
- lexStream.reset(buffer[buffer_position]);
- }
-
- process_terminal: for (;;) {
- if(DEBUG_PARSECHECK) {
- System.out.print(tempStackTop + 1);
- System.out.print(" (+1) [max:"); //$NON-NLS-1$
- System.out.print(max_pos);
- System.out.print("]\tprocess_terminal \t"); //$NON-NLS-1$
- System.out.print(ct);
- System.out.print("\t"); //$NON-NLS-1$
- System.out.print(Parser.name[Parser.terminal_index[ct]]);
- System.out.println();
- }
-
- if (++tempStackTop >= stackLength) // Stack overflow!!!
- return indx;
- tempStack[tempStackTop] = act;
-
- act = Parser.tAction(act, ct);
-
- if (act <= NUM_RULES) { // reduce action
- tempStackTop--;
-
- if(DEBUG_PARSECHECK) {
- System.out.print(tempStackTop);
- System.out.print(" (-1) [max:"); //$NON-NLS-1$
- System.out.print(max_pos);
- System.out.print("]\treduce"); //$NON-NLS-1$
- System.out.println();
- }
- } else if (act < ACCEPT_ACTION || // shift action
- act > ERROR_ACTION) { // shift-reduce action
- if (indx == MAX_DISTANCE)
- return indx;
- indx++;
- ct = lexStream.kind(buffer[indx]);
- lexStream.reset(lexStream.next(buffer[indx]));
- if (act > ERROR_ACTION) {
- act -= ERROR_ACTION;
-
- if(DEBUG_PARSECHECK) {
- System.out.print(tempStackTop);
- System.out.print("\tshift reduce"); //$NON-NLS-1$
- System.out.println();
- }
- } else {
- if(DEBUG_PARSECHECK) {
- System.out.println("\tshift"); //$NON-NLS-1$
- }
- continue process_terminal;
- }
- } else if (act == ACCEPT_ACTION) { // accept action
- return MAX_DISTANCE;
- } else {
- return indx; // error action
- }
-
- // same loop as first token initialization
- // process_non_terminal:
- do {
- tempStackTop -= (Parser.rhs[act]-1);
-
- if(DEBUG_PARSECHECK) {
- System.out.print(tempStackTop);
- System.out.print(" ("); //$NON-NLS-1$
- System.out.print(-(Parser.rhs[act]-1));
- System.out.print(") [max:"); //$NON-NLS-1$
- System.out.print(max_pos);
- System.out.print("]\tprocess_non_terminal\t"); //$NON-NLS-1$
- System.out.print(act);
- System.out.print("\t"); //$NON-NLS-1$
- System.out.print(Parser.name[Parser.non_terminal_index[Parser.lhs[act]]]);
- System.out.println();
- }
-
- if(act <= NUM_RULES) {
- if(Parser.rules_compliance[act] > this.options.sourceLevel) {
- return 0;
- }
- }
- int lhs_symbol = Parser.lhs[act];
- act = (tempStackTop > max_pos
- ? tempStack[tempStackTop]
- : stck[tempStackTop]);
- act = Parser.ntAction(act, lhs_symbol);
- } while(act <= NUM_RULES);
-
- max_pos = max_pos < tempStackTop ? max_pos : tempStackTop;
- } // process_terminal;
- }
- private void reportError(int msgCode, int nameIndex, int leftToken, int rightToken) {
- reportError(msgCode, nameIndex, leftToken, rightToken, 0);
- }
-
- private void reportError(int msgCode, int nameIndex, int leftToken, int rightToken, int scopeNameIndex) {
- int lToken = (leftToken > rightToken ? rightToken : leftToken);
-
- if (lToken < rightToken) {
- reportSecondaryError(msgCode, nameIndex, lToken, rightToken, scopeNameIndex);
- } else {
- reportPrimaryError(msgCode, nameIndex, rightToken, scopeNameIndex);
- }
- }
- private void reportPrimaryError(int msgCode, int nameIndex, int token, int scopeNameIndex) {
- String name;
- if (nameIndex >= 0) {
- name = Parser.readableName[nameIndex];
- } else {
- name = Util.EMPTY_STRING;
- }
-
- int errorStart = lexStream.start(token);
- int errorEnd = lexStream.end(token);
- int currentKind = lexStream.kind(token);
- String errorTokenName = Parser.name[Parser.terminal_index[lexStream.kind(token)]];
- char[] errorTokenSource = lexStream.name(token);
-
- int addedToken = -1;
- if(recoveryScanner != null) {
- if (nameIndex >= 0) {
- addedToken = Parser.reverse_index[nameIndex];
- }
- }
- switch(msgCode) {
- case BEFORE_CODE:
- if(recoveryScanner != null) {
- if(addedToken > -1) {
- recoveryScanner.insertToken(addedToken, -1, errorStart);
- } else {
- int[] template = getNTermTemplate(-addedToken);
- if(template != null) {
- recoveryScanner.insertTokens(template, -1, errorStart);
- }
- }
- }
- if(this.reportProblem) problemReporter().parseErrorInsertBeforeToken(
- errorStart,
- errorEnd,
- currentKind,
- errorTokenSource,
- errorTokenName,
- name);
- break;
- case INSERTION_CODE:
- if(recoveryScanner != null) {
- if(addedToken > -1) {
- recoveryScanner.insertToken(addedToken, -1, errorEnd);
- } else {
- int[] template = getNTermTemplate(-addedToken);
- if(template != null) {
- recoveryScanner.insertTokens(template, -1, errorEnd);
- }
- }
- }
- if(this.reportProblem) problemReporter().parseErrorInsertAfterToken(
- errorStart,
- errorEnd,
- currentKind,
- errorTokenSource,
- errorTokenName,
- name);
- break;
- case DELETION_CODE:
- if(recoveryScanner != null) {
- recoveryScanner.removeTokens(errorStart, errorEnd);
- }
- if(this.reportProblem) problemReporter().parseErrorDeleteToken(
- errorStart,
- errorEnd,
- currentKind,
- errorTokenSource,
- errorTokenName);
- break;
- case INVALID_CODE:
- if (name.length() == 0) {
- if(recoveryScanner != null) {
- recoveryScanner.removeTokens(errorStart, errorEnd);
- }
- if(this.reportProblem) problemReporter().parseErrorReplaceToken(
- errorStart,
- errorEnd,
- currentKind,
- errorTokenSource,
- errorTokenName,
- name);
- } else {
- if(recoveryScanner != null) {
- if(addedToken > -1) {
- recoveryScanner.replaceTokens(addedToken, errorStart, errorEnd);
- } else {
- int[] template = getNTermTemplate(-addedToken);
- if(template != null) {
- recoveryScanner.replaceTokens(template, errorStart, errorEnd);
- }
- }
- }
- if(this.reportProblem) problemReporter().parseErrorInvalidToken(
- errorStart,
- errorEnd,
- currentKind,
- errorTokenSource,
- errorTokenName,
- name);
- }
- break;
- case SUBSTITUTION_CODE:
- if(recoveryScanner != null) {
- if(addedToken > -1) {
- recoveryScanner.replaceTokens(addedToken, errorStart, errorEnd);
- } else {
- int[] template = getNTermTemplate(-addedToken);
- if(template != null) {
- recoveryScanner.replaceTokens(template, errorStart, errorEnd);
- }
- }
- }
- if(this.reportProblem) problemReporter().parseErrorReplaceToken(
- errorStart,
- errorEnd,
- currentKind,
- errorTokenSource,
- errorTokenName,
- name);
- break;
- case SCOPE_CODE:
- StringBuffer buf = new StringBuffer();
-
- int[] addedTokens = null;
- int addedTokenCount = 0;
- if(this.recoveryScanner != null) {
- addedTokens = new int[Parser.scope_rhs.length - Parser.scope_suffix[- nameIndex]];
- }
-
- for (int i = Parser.scope_suffix[- nameIndex]; Parser.scope_rhs[i] != 0; i++) {
- buf.append(Parser.readableName[Parser.scope_rhs[i]]);
- if (Parser.scope_rhs[i + 1] != 0) // any more symbols to print?
- buf.append(' ');
-
- if(addedTokens != null) {
- int tmpAddedToken = Parser.reverse_index[Parser.scope_rhs[i]];
- if (tmpAddedToken > -1) {
- int length = addedTokens.length;
- if(addedTokenCount == length) {
- System.arraycopy(addedTokens, 0, addedTokens = new int[length * 2], 0, length);
- }
- addedTokens[addedTokenCount++] = tmpAddedToken;
- } else {
- int[] template = getNTermTemplate(-tmpAddedToken);
- if(template != null) {
- for (int j = 0; j < template.length; j++) {
- int length = addedTokens.length;
- if(addedTokenCount == length) {
- System.arraycopy(addedTokens, 0, addedTokens = new int[length * 2], 0, length);
- }
- addedTokens[addedTokenCount++] = template[j];
- }
- } else {
- addedTokenCount = 0;
- addedTokens = null;
- }
- }
- }
- }
-
- if(addedTokenCount > 0) {
- System.arraycopy(addedTokens, 0, addedTokens = new int[addedTokenCount], 0, addedTokenCount);
-
- int completedToken = -1;
- if(scopeNameIndex != 0) {
- completedToken = -Parser.reverse_index[scopeNameIndex];
- }
- this.recoveryScanner.insertTokens(addedTokens, completedToken, errorEnd);
- }
-
- if (scopeNameIndex != 0) {
- if(this.reportProblem) problemReporter().parseErrorInsertToComplete(
- errorStart,
- errorEnd,
- buf.toString(),
- Parser.readableName[scopeNameIndex]);
- } else {
- if(this.reportProblem) problemReporter().parseErrorInsertToCompleteScope(
- errorStart,
- errorEnd,
- buf.toString());
- }
-
- break;
- case EOF_CODE:
- if(this.reportProblem) problemReporter().parseErrorUnexpectedEnd(
- errorStart,
- errorEnd);
- break;
- case MERGE_CODE:
- if(recoveryScanner != null) {
- if(addedToken > -1) {
- recoveryScanner.replaceTokens(addedToken, errorStart, errorEnd);
- } else {
- int[] template = getNTermTemplate(-addedToken);
- if(template != null) {
- recoveryScanner.replaceTokens(template, errorStart, errorEnd);
- }
- }
- }
- if(this.reportProblem) problemReporter().parseErrorMergeTokens(
- errorStart,
- errorEnd,
- name);
- break;
- case MISPLACED_CODE:
- if(recoveryScanner != null) {
- recoveryScanner.removeTokens(errorStart, errorEnd);
- }
- if(this.reportProblem) problemReporter().parseErrorMisplacedConstruct(
- errorStart,
- errorEnd);
- break;
- default:
- if (name.length() == 0) {
- if(recoveryScanner != null) {
- recoveryScanner.removeTokens(errorStart, errorEnd);
- }
- if(this.reportProblem) problemReporter().parseErrorNoSuggestion(
- errorStart,
- errorEnd,
- currentKind,
- errorTokenSource,
- errorTokenName);
- } else {
- if(recoveryScanner != null) {
- if(addedToken > -1) {
- recoveryScanner.replaceTokens(addedToken, errorStart, errorEnd);
- } else {
- int[] template = getNTermTemplate(-addedToken);
- if(template != null) {
- recoveryScanner.replaceTokens(template, errorStart, errorEnd);
- }
- }
- }
- if(this.reportProblem) problemReporter().parseErrorReplaceToken(
- errorStart,
- errorEnd,
- currentKind,
- errorTokenSource,
- errorTokenName,
- name);
- }
- break;
- }
- }
-
- private void reportSecondaryError(int msgCode, int nameIndex, int leftToken, int rightToken, int scopeNameIndex) {
- String name;
- if (nameIndex >= 0) {
- name = Parser.readableName[nameIndex];
- } else {
- name = Util.EMPTY_STRING;
- }
-
- int errorStart = -1;
- if(lexStream.isInsideStream(leftToken)) {
- if(leftToken == 0) {
- errorStart = lexStream.start(leftToken + 1);
- } else {
- errorStart = lexStream.start(leftToken);
- }
- } else {
- if(leftToken == errorToken) {
- errorStart = errorTokenStart;
- } else {
- for (int i = 0; i <= stateStackTop; i++) {
- if(locationStack[i] == leftToken) {
- errorStart = locationStartStack[i];
- }
- }
- }
- if(errorStart == -1) {
- errorStart = lexStream.start(rightToken);
- }
- }
- int errorEnd = lexStream.end(rightToken);
-
- int addedToken = -1;
- if(recoveryScanner != null) {
- if (nameIndex >= 0) {
- addedToken = Parser.reverse_index[nameIndex];
- }
- }
-
- switch(msgCode) {
- case MISPLACED_CODE:
- if(recoveryScanner != null) {
- recoveryScanner.removeTokens(errorStart, errorEnd);
- }
- if(this.reportProblem) problemReporter().parseErrorMisplacedConstruct(
- errorStart,
- errorEnd);
- break;
- case SCOPE_CODE:
- // error start is on the last token start
- errorStart = lexStream.start(rightToken);
-
- StringBuffer buf = new StringBuffer();
-
- int[] addedTokens = null;
- int addedTokenCount = 0;
- if(this.recoveryScanner != null) {
- addedTokens = new int[Parser.scope_rhs.length - Parser.scope_suffix[- nameIndex]];
- }
-
- for (int i = Parser.scope_suffix[- nameIndex]; Parser.scope_rhs[i] != 0; i++) {
-
- buf.append(Parser.readableName[Parser.scope_rhs[i]]);
- if (Parser.scope_rhs[i+1] != 0)
- buf.append(' ');
-
- if(addedTokens != null) {
- int tmpAddedToken = Parser.reverse_index[Parser.scope_rhs[i]];
- if (tmpAddedToken > -1) {
- int length = addedTokens.length;
- if(addedTokenCount == length) {
- System.arraycopy(addedTokens, 0, addedTokens = new int[length * 2], 0, length);
- }
- addedTokens[addedTokenCount++] = tmpAddedToken;
- } else {
- int[] template = getNTermTemplate(-tmpAddedToken);
- if(template != null) {
- for (int j = 0; j < template.length; j++) {
- int length = addedTokens.length;
- if(addedTokenCount == length) {
- System.arraycopy(addedTokens, 0, addedTokens = new int[length * 2], 0, length);
- }
- addedTokens[addedTokenCount++] = template[j];
- }
- } else {
- addedTokenCount = 0;
- addedTokens = null;
- }
- }
- }
- }
- if(addedTokenCount > 0) {
- System.arraycopy(addedTokens, 0, addedTokens = new int[addedTokenCount], 0, addedTokenCount);
- int completedToken = -1;
- if(scopeNameIndex != 0) {
- completedToken = -Parser.reverse_index[scopeNameIndex];
- }
- this.recoveryScanner.insertTokens(addedTokens, completedToken, errorEnd);
- }
- if (scopeNameIndex != 0) {
- if(this.reportProblem) problemReporter().parseErrorInsertToComplete(
- errorStart,
- errorEnd,
- buf.toString(),
- Parser.readableName[scopeNameIndex]);
- } else {
- if(this.reportProblem) problemReporter().parseErrorInsertToCompletePhrase(
- errorStart,
- errorEnd,
- buf.toString());
- }
- break;
- case MERGE_CODE:
- if(recoveryScanner != null) {
- if(addedToken > -1) {
- recoveryScanner.replaceTokens(addedToken, errorStart, errorEnd);
- } else {
- int[] template = getNTermTemplate(-addedToken);
- if(template != null) {
- recoveryScanner.replaceTokens(template, errorStart, errorEnd);
- }
- }
- }
- if(this.reportProblem) problemReporter().parseErrorMergeTokens(
- errorStart,
- errorEnd,
- name);
- break;
- case DELETION_CODE:
- if(recoveryScanner != null) {
- recoveryScanner.removeTokens(errorStart, errorEnd);
- }
- if(this.reportProblem) problemReporter().parseErrorDeleteTokens(
- errorStart,
- errorEnd);
- break;
- default:
- if (name.length() == 0) {
- if(recoveryScanner != null) {
- recoveryScanner.removeTokens(errorStart, errorEnd);
- }
- if(this.reportProblem) problemReporter().parseErrorNoSuggestionForTokens(
- errorStart,
- errorEnd);
- } else {
- if(recoveryScanner != null) {
- if(addedToken > -1) {
- recoveryScanner.replaceTokens(addedToken, errorStart, errorEnd);
- } else {
- int[] template = getNTermTemplate(-addedToken);
- if(template != null) {
- recoveryScanner.replaceTokens(template, errorStart, errorEnd);
- }
- }
- }
- if(this.reportProblem) problemReporter().parseErrorReplaceTokens(
- errorStart,
- errorEnd,
- name);
- }
- }
- return;
- }
-
- private int[] getNTermTemplate(int sym) {
- int templateIndex = Parser.recovery_templates_index[sym];
- if(templateIndex > 0) {
- int[] result = new int[Parser.recovery_templates.length];
- int count = 0;
- for(int j = templateIndex; Parser.recovery_templates[j] != 0; j++) {
- result[count++] = Parser.recovery_templates[j];
- }
- System.arraycopy(result, 0, result = new int[count], 0, count);
- return result;
- } else {
- return null;
- }
- }
-
- public String toString() {
- StringBuffer res = new StringBuffer();
-
- res.append(lexStream.toString());
-
- return res.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/diagnose/LexStream.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/diagnose/LexStream.java
deleted file mode 100644
index df113e26..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/diagnose/LexStream.java
+++ /dev/null
@@ -1,291 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.parser.diagnose;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-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.Util;
-
-public class LexStream implements TerminalTokens {
- public static final int IS_AFTER_JUMP = 1;
- public static final int LBRACE_MISSING = 2;
-
- public static class Token{
- int kind;
- char[] name;
- int start;
- int end;
- int line;
- int flags;
-
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- buffer.append(name).append('[').append(kind).append(']');
- buffer.append('{').append(start).append(',').append(end).append('}').append(line);
- return buffer.toString();
- }
-
- }
-
- private int tokenCacheIndex;
- private int tokenCacheEOFIndex;
- private Token[] tokenCache;
-
- private int currentIndex = -1;
-
- private Scanner scanner;
- private int[] intervalStartToSkip;
- private int[] intervalEndToSkip;
- private int[] intervalFlagsToSkip;
-
- private int previousInterval = -1;
- private int currentInterval = -1;
-
- public LexStream(int size, Scanner scanner, int[] intervalStartToSkip, int[] intervalEndToSkip, int[] intervalFlagsToSkip, int firstToken, int init, int eof) {
- this.tokenCache = new Token[size];
- this.tokenCacheIndex = 0;
- this.tokenCacheEOFIndex = Integer.MAX_VALUE;
- this.tokenCache[0] = new Token();
- this.tokenCache[0].kind = firstToken;
- this.tokenCache[0].name = CharOperation.NO_CHAR;
- this.tokenCache[0].start = init;
- this.tokenCache[0].end = init;
- this.tokenCache[0].line = 0;
-
- this.intervalStartToSkip = intervalStartToSkip;
- this.intervalEndToSkip = intervalEndToSkip;
- this.intervalFlagsToSkip = intervalFlagsToSkip;
-
- scanner.resetTo(init, eof);
- this.scanner = scanner;
- }
-
- private void readTokenFromScanner(){
- int length = tokenCache.length;
- boolean tokenNotFound = true;
-
- while(tokenNotFound) {
- try {
- int tokenKind = scanner.getNextToken();
- if(tokenKind != TokenNameEOF) {
- int start = scanner.getCurrentTokenStartPosition();
- int end = scanner.getCurrentTokenEndPosition();
-
- int nextInterval = currentInterval + 1;
- if(intervalStartToSkip.length == 0 ||
- nextInterval >= intervalStartToSkip.length ||
- start < intervalStartToSkip[nextInterval]) {
- Token token = new Token();
- token.kind = tokenKind;
- token.name = scanner.getCurrentTokenSource();
- token.start = start;
- token.end = end;
- token.line = Util.getLineNumber(end, scanner.lineEnds, 0, scanner.linePtr);
-
- if(currentInterval != previousInterval && (intervalFlagsToSkip[currentInterval] & RangeUtil.IGNORE) == 0){
- token.flags = IS_AFTER_JUMP;
- if((intervalFlagsToSkip[currentInterval] & RangeUtil.LBRACE_MISSING) != 0){
- token.flags |= LBRACE_MISSING;
- }
- }
- previousInterval = currentInterval;
-
- tokenCache[++tokenCacheIndex % length] = token;
-
- tokenNotFound = false;
- } else {
- scanner.resetTo(intervalEndToSkip[++currentInterval] + 1, scanner.eofPosition - 1);
- }
- } else {
- int start = scanner.getCurrentTokenStartPosition();
- int end = scanner.getCurrentTokenEndPosition();
- Token token = new Token();
- token.kind = tokenKind;
- token.name = CharOperation.NO_CHAR;
- token.start = start;
- token.end = end;
- token.line = Util.getLineNumber(end, scanner.lineEnds, 0, scanner.linePtr);
-
- tokenCache[++tokenCacheIndex % length] = token;
-
- tokenCacheEOFIndex = tokenCacheIndex;
- tokenNotFound = false;
- }
- } catch (InvalidInputException e) {
- // return next token
- }
- }
- }
-
- public Token token(int index) {
- if(index < 0) {
- Token eofToken = new Token();
- eofToken.kind = TokenNameEOF;
- eofToken.name = CharOperation.NO_CHAR;
- return eofToken;
- }
- if(this.tokenCacheEOFIndex >= 0 && index > this.tokenCacheEOFIndex) {
- return token(this.tokenCacheEOFIndex);
- }
- int length = tokenCache.length;
- if(index > this.tokenCacheIndex) {
- int tokensToRead = index - this.tokenCacheIndex;
- while(tokensToRead-- != 0) {
- readTokenFromScanner();
- }
- } else if(this.tokenCacheIndex - length >= index) {
- return null;
- }
-
- return tokenCache[index % length];
- }
-
-
-
- public int getToken() {
- return currentIndex = next(currentIndex);
- }
-
- public int previous(int tokenIndex) {
- return tokenIndex > 0 ? tokenIndex - 1 : 0;
- }
-
- public int next(int tokenIndex) {
- return tokenIndex < this.tokenCacheEOFIndex ? tokenIndex + 1 : this.tokenCacheEOFIndex;
- }
-
- public boolean afterEol(int i) {
- return i < 1 ? true : line(i - 1) < line(i);
- }
-
- public void reset() {
- currentIndex = -1;
- }
-
- public void reset(int i) {
- currentIndex = previous(i);
- }
-
- public int badtoken() {
- return 0;
- }
-
- public int kind(int tokenIndex) {
- return token(tokenIndex).kind;
- }
-
- public char[] name(int tokenIndex) {
- return token(tokenIndex).name;
- }
-
- public int line(int tokenIndex) {
- return token(tokenIndex).line;
- }
-
- public int start(int tokenIndex) {
- return token(tokenIndex).start;
- }
-
- public int end(int tokenIndex) {
- return token(tokenIndex).end;
- }
-
- public int flags(int tokenIndex) {
- return token(tokenIndex).flags;
- }
-
- public boolean isInsideStream(int index) {
- if(this.tokenCacheEOFIndex >= 0 && index > this.tokenCacheEOFIndex) {
- return false;
- } else if(index > this.tokenCacheIndex) {
- return true;
- } else if(this.tokenCacheIndex - tokenCache.length >= index) {
- return false;
- } else {
- return true;
- }
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#toString()
- */
- public String toString() {
- StringBuffer res = new StringBuffer();
-
- String source = new String(scanner.source);
- if(currentIndex < 0) {
- int previousEnd = -1;
- for (int i = 0; i < intervalStartToSkip.length; i++) {
- int intervalStart = intervalStartToSkip[i];
- int intervalEnd = intervalEndToSkip[i];
-
- res.append(source.substring(previousEnd + 1, intervalStart));
- res.append('<');
- res.append('@');
- res.append(source.substring(intervalStart, intervalEnd + 1));
- res.append('@');
- res.append('>');
-
- previousEnd = intervalEnd;
- }
- res.append(source.substring(previousEnd + 1));
- } else {
- Token token = token(currentIndex);
- int curtokKind = token.kind;
- int curtokStart = token.start;
- int curtokEnd = token.end;
-
- int previousEnd = -1;
- for (int i = 0; i < intervalStartToSkip.length; i++) {
- int intervalStart = intervalStartToSkip[i];
- int intervalEnd = intervalEndToSkip[i];
-
- if(curtokStart >= previousEnd && curtokEnd <= intervalStart) {
- res.append(source.substring(previousEnd + 1, curtokStart));
- res.append('<');
- res.append('#');
- res.append(source.substring(curtokStart, curtokEnd + 1));
- res.append('#');
- res.append('>');
- res.append(source.substring(curtokEnd+1, intervalStart));
- } else {
- res.append(source.substring(previousEnd + 1, intervalStart));
- }
- res.append('<');
- res.append('@');
- res.append(source.substring(intervalStart, intervalEnd + 1));
- res.append('@');
- res.append('>');
-
- previousEnd = intervalEnd;
- }
- if(curtokStart >= previousEnd) {
- res.append(source.substring(previousEnd + 1, curtokStart));
- res.append('<');
- res.append('#');
- if(curtokKind == TokenNameEOF) {
- res.append("EOF#>"); //$NON-NLS-1$
- } else {
- res.append(source.substring(curtokStart, curtokEnd + 1));
- res.append('#');
- res.append('>');
- res.append(source.substring(curtokEnd+1));
- }
- } else {
- res.append(source.substring(previousEnd + 1));
- }
- }
-
- return res.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/diagnose/RangeUtil.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/diagnose/RangeUtil.java
deleted file mode 100644
index cb923ff2..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/diagnose/RangeUtil.java
+++ /dev/null
@@ -1,179 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.parser.diagnose;
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ProgramElement;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ExtraCompilerModifiers;
-
-public class RangeUtil {
-
- // flags
- public static final int NO_FLAG = 0;
- public static final int LBRACE_MISSING = 1;
- public static final int IGNORE = 2;
-
- static class RangeResult {
- private static final int INITIAL_SIZE = 10;
- int pos;
- int[] intervalStarts;
- int[] intervalEnds;
- int[] intervalFlags;
-
- RangeResult() {
- this.pos = 0;
- this.intervalStarts = new int[INITIAL_SIZE];
- this.intervalEnds = new int[INITIAL_SIZE];
- this.intervalFlags = new int[INITIAL_SIZE];
- }
-
- void addInterval(int start, int end){
- addInterval(start, end, NO_FLAG);
- }
-
- void addInterval(int start, int end, int flags){
- if(pos >= intervalStarts.length) {
- System.arraycopy(intervalStarts, 0, intervalStarts = new int[pos * 2], 0, pos);
- System.arraycopy(intervalEnds, 0, intervalEnds = new int[pos * 2], 0, pos);
- System.arraycopy(intervalFlags, 0, intervalFlags = new int[pos * 2], 0, pos);
- }
- intervalStarts[pos] = start;
- intervalEnds[pos] = end;
- intervalFlags[pos] = flags;
- pos++;
- }
-
- int[][] getRanges() {
- int[] resultStarts = new int[pos];
- int[] resultEnds = new int[pos];
- int[] resultFlags = new int[pos];
-
- System.arraycopy(intervalStarts, 0, resultStarts, 0, pos);
- System.arraycopy(intervalEnds, 0, resultEnds, 0, pos);
- System.arraycopy(intervalFlags, 0, resultFlags, 0, pos);
-
- if (resultStarts.length > 1) {
- quickSort(resultStarts, resultEnds, resultFlags, 0, resultStarts.length - 1);
- }
- return new int[][]{resultStarts, resultEnds, resultFlags};
- }
-
- private void quickSort(int[] list, int[] list2, int[] list3, int left, int right) {
- int original_left= left;
- int original_right= right;
- int mid= list[left + (right - left) / 2];
- do {
- while (compare(list[left], mid) < 0) {
- left++;
- }
- while (compare(mid, list[right]) < 0) {
- right--;
- }
- if (left <= right) {
- int tmp= list[left];
- list[left]= list[right];
- list[right]= tmp;
-
- tmp = list2[left];
- list2[left]= list2[right];
- list2[right]= tmp;
-
- tmp = list3[left];
- list3[left]= list3[right];
- list3[right]= tmp;
-
- left++;
- right--;
- }
- } while (left <= right);
-
- if (original_left < right) {
- quickSort(list, list2, list3, original_left, right);
- }
- if (left < original_right) {
- quickSort(list, list2, list3, left, original_right);
- }
- }
-
- private int compare(int i1, int i2) {
- return i1 - i2;
- }
- }
-
-
-
- public static boolean containsErrorInSignature(AbstractMethodDeclaration method){
- return method.sourceEnd + 1 == method.bodyStart || method.bodyEnd == method.declarationSourceEnd;
- }
-
- public static int[][] computeDietRange(ProgramElement[] statements) {
- if(statements == null || statements.length == 0) {
- return new int[3][0];
- } else {
- RangeResult result = new RangeResult();
- computeDietRange0(statements, result);
- return result.getRanges();
- }
- }
-
- private static void computeDietRange0(ProgramElement[] statements, RangeResult result) {
- for (int j = 0; j < statements.length; j++) {
- //members
-// TypeDeclaration[] memberTypeDeclarations = types[j].memberTypes;
-// if(memberTypeDeclarations != null && memberTypeDeclarations.length > 0) {
-// computeDietRange0(types[j].memberTypes, result);
-// }
- //methods
- if (statements[j] instanceof AbstractMethodDeclaration) {
- AbstractMethodDeclaration method = (AbstractMethodDeclaration) statements[j];
-
-// AbstractMethodDeclaration[] methods = types[j].methods;
-// if (methods != null) {
-// int length = methods.length;
-// for (int i = 0; i < length; i++) {
-// AbstractMethodDeclaration method = methods[i];
- if(containsIgnoredBody(method)) {
- if(containsErrorInSignature(method)) {
- method.errorInSignature = true;
- result.addInterval(method.declarationSourceStart, method.declarationSourceEnd, IGNORE);
- } else {
- int flags = method.sourceEnd + 1 == method.bodyStart ? LBRACE_MISSING : NO_FLAG;
- result.addInterval(method.bodyStart, method.bodyEnd, flags);
- }
- }
-// }
- }
-
- //initializers
-// FieldDeclaration[] fields = types[j].fields;
-// if (fields != null) {
-// int length = fields.length;
-// for (int i = 0; i < length; i++) {
-// if (fields[i] instanceof Initializer) {
-// Initializer initializer = (Initializer)fields[i];
-// if(initializer.declarationSourceEnd == initializer.bodyEnd && initializer.declarationSourceStart != initializer.declarationSourceEnd){
-// initializer.errorInSignature = true;
-// result.addInterval(initializer.declarationSourceStart, initializer.declarationSourceEnd, IGNORE);
-// } else {
-// result.addInterval(initializer.bodyStart, initializer.bodyEnd);
-// }
-// }
-// }
-// }
- }
- }
-
- public static boolean containsIgnoredBody(AbstractMethodDeclaration method){
- return !method.isDefaultConstructor()
- && !method.isClinit()
- && (method.modifiers & ExtraCompilerModifiers.AccSemicolonBody) == 0;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser1.rsc b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser1.rsc
deleted file mode 100644
index a96f645b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser1.rsc
+++ /dev/null
Binary files differ
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser10.rsc b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser10.rsc
deleted file mode 100644
index 867bcd23..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser10.rsc
+++ /dev/null
Binary files differ
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser11.rsc b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser11.rsc
deleted file mode 100644
index 5b5e8af9..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser11.rsc
+++ /dev/null
Binary files differ
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser12.rsc b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser12.rsc
deleted file mode 100644
index 737d0cf3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser12.rsc
+++ /dev/null
Binary files differ
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser13.rsc b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser13.rsc
deleted file mode 100644
index 5c7a3807..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser13.rsc
+++ /dev/null
Binary files differ
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser14.rsc b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser14.rsc
deleted file mode 100644
index 89704f4a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser14.rsc
+++ /dev/null
Binary files differ
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser15.rsc b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser15.rsc
deleted file mode 100644
index d2321213..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser15.rsc
+++ /dev/null
Binary files differ
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser16.rsc b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser16.rsc
deleted file mode 100644
index e782249d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser16.rsc
+++ /dev/null
Binary files differ
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser17.rsc b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser17.rsc
deleted file mode 100644
index 03ef34ad..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser17.rsc
+++ /dev/null
Binary files differ
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser18.rsc b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser18.rsc
deleted file mode 100644
index b80b8dcb..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser18.rsc
+++ /dev/null
Binary files differ
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser19.rsc b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser19.rsc
deleted file mode 100644
index 2fc4f8f4..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser19.rsc
+++ /dev/null
@@ -1 +0,0 @@
-44444SSSS8866668W8855544444444444464V588T:9 \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser2.rsc b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser2.rsc
deleted file mode 100644
index e303bdca..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser2.rsc
+++ /dev/null
Binary files differ
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser20.rsc b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser20.rsc
deleted file mode 100644
index 0fc84113..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser20.rsc
+++ /dev/null
Binary files differ
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser21.rsc b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser21.rsc
deleted file mode 100644
index 139e0e28..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser21.rsc
+++ /dev/null
Binary files differ
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser22.rsc b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser22.rsc
deleted file mode 100644
index 48dd21b0..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser22.rsc
+++ /dev/null
Binary files differ
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser23.rsc b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser23.rsc
deleted file mode 100644
index 03c6b139..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser23.rsc
+++ /dev/null
Binary files differ
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser24.rsc b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser24.rsc
deleted file mode 100644
index 0520075d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser24.rsc
+++ /dev/null
Binary files differ
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser25.rsc b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser25.rsc
deleted file mode 100644
index 3fb7193d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser25.rsc
+++ /dev/null
Binary files differ
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser3.rsc b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser3.rsc
deleted file mode 100644
index c6f1434f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser3.rsc
+++ /dev/null
Binary files differ
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser4.rsc b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser4.rsc
deleted file mode 100644
index 34417593..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser4.rsc
+++ /dev/null
Binary files differ
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser5.rsc b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser5.rsc
deleted file mode 100644
index 0f167cf5..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser5.rsc
+++ /dev/null
Binary files differ
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser6.rsc b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser6.rsc
deleted file mode 100644
index c39b53ab..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser6.rsc
+++ /dev/null
Binary files differ
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser7.rsc b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser7.rsc
deleted file mode 100644
index 1222bab7..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser7.rsc
+++ /dev/null
Binary files differ
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser8.rsc b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser8.rsc
deleted file mode 100644
index 43d1c1d3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser8.rsc
+++ /dev/null
Binary files differ
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser9.rsc b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser9.rsc
deleted file mode 100644
index 19b80474..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/parser9.rsc
+++ /dev/null
Binary files differ
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/part1.rsc b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/part1.rsc
deleted file mode 100644
index b7d2df1e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/part1.rsc
+++ /dev/null
Binary files differ
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/part14.rsc b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/part14.rsc
deleted file mode 100644
index 14f90424..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/part14.rsc
+++ /dev/null
Binary files differ
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/part2.rsc b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/part2.rsc
deleted file mode 100644
index e37032a2..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/part2.rsc
+++ /dev/null
Binary files differ
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/readableNames.properties b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/readableNames.properties
deleted file mode 100644
index 384011ed..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/readableNames.properties
+++ /dev/null
@@ -1,189 +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
-###############################################################################
-AbstractMethodDeclaration=MethodDeclaration
-AdditiveExpression=Expression
-AdditiveExpressionStmt=AdditiveExpression
-AndExpression=Expression
-AndExpressionNoIn=Expression
-AndExpressionStmt=Expression
-ArgumentList=ArgumentList
-ArgumentListopt=ArgumentList
-Arguments=Arguments
-ArrayLiteral=ArrayLiteral
-ArrayLiteralElement=ArrayLiteralElement
-ArrayLiteralElementList=ArrayLiteralElementList
-ArrayLiteralHeader=ArrayLiteralHeader
-Assignment=Assignment
-AssignmentExpression=Expression
-AssignmentExpressionNoIn=Expression
-AssignmentExpressionStmt=Expression
-AssignmentNoIn=Assignment
-AssignmentOperator=AssignmentOperator
-AssignmentStmt=AssignmentStmt
-Block=Block
-BlockStatement=BlockStatement
-BlockStatements=BlockStatements
-BlockStatementsopt=BlockStatements
-BooleanLiteral=BooleanLiteral
-BreakStatement=BreakStatement
-CallExpression=CallExpression
-CallExpressionStmt=CallExpression
-CatchClause=CatchClause
-CatchHeader=CatchHeader
-Catches=Catches
-Catchesopt=Catches
-CompilationUnit=CompilationUnit
-ConditionalAndExpression=Expression
-ConditionalAndExpressionNoIn=Expression
-ConditionalAndExpressionStmt=Expression
-ConditionalExpression=Expression
-ConditionalExpressionNoIn=Expression
-ConditionalExpressionStmt=Expression
-ConditionalOrExpression=Expression
-ConditionalOrExpressionNoIn=Expression
-ConditionalOrExpressionStmt=Expression
-ConstantExpression=ConstantExpression
-ContinueStatement=ContinueStatement
-DebuggerStatement=DebuggerStatement
-DoStatement=DoStatement
-Elision=Elision
-ElisionOpt=ElisionOpt
-EmptyStatement=EmptyStatement
-EnterCompilationUnit=EnterCompilationUnit
-EnterVariable=EnterVariable
-EqualityExpression=Expression
-EqualityExpressionNoIn=Expression
-EqualityExpressionStmt=Expression
-ExclusiveOrExpression=Expression
-ExclusiveOrExpressionNoIn=Expression
-ExclusiveOrExpressionStmt=Expression
-ExitTryBlock=ExitTryBlock
-ExitVariableWithInitialization=ExitVariableWithInitialization
-ExitVariableWithoutInitialization=ExitVariableWithoutInitialization
-Expression=Expression
-ExpressionNoIn=Expression
-ExpressionStatement=Statement
-Expressionopt=Expression
-Finally=Finally
-ForInInit=ForInInit
-ForInit=ForInit
-ForInitopt=ForInit
-ForStatement=ForStatement
-ForStatementNoShortIf=ForStatement
-ForUpdate=ForUpdate
-ForUpdateopt=ForUpdate
-ForceNoDiet=ForceNoDiet
-FormalParameter=FormalParameter
-FormalParameterList=FormalParameterList
-FormalParameterListopt=FormalParameterList
-FunctionBody=FunctionBody
-FunctionExpression=FunctionExpression
-FunctionExpressionHeader=FunctionExpressionHeader
-FunctionExpressionHeaderName=FunctionExpressionHeaderName
-Goal=Goal
-Header1=Header1
-Header=Header
-IfThenElseStatement=IfStatement
-IfThenElseStatementNoShortIf=IfStatement
-IfThenStatement=IfStatement
-InclusiveOrExpression=Expression
-InclusiveOrExpressionNoIn=Expression
-InclusiveOrExpressionStmt=Expression
-InternalCompilationUnit=CompilationUnit
-Label=Label
-LabeledStatement=LabeledStatement
-LabeledStatementNoShortIf=LabeledStatement
-LeftHandSideExpression=LeftHandSideExpression
-LeftHandSideExpressionStmt=LeftHandSideExpressionStmt
-ListExpression=ListExpression
-ListExpressionNoIn=ListExpression
-ListExpressionStmt=ListExpression
-Literal=Literal
-LocalVariableDeclaration=LocalVariableDeclaration
-LocalVariableDeclarationNoIn=LocalVariableDeclaration
-LocalVariableDeclarationStatement=LocalVariableDeclarationStatement
-MemberExpression=MemberExpression
-MemberExpressionStmt=MemberExpression
-MethodBody=MethodBody
-MethodDeclaration=MethodDeclaration
-MethodHeader=MethodDeclaration
-MethodHeaderName=MethodHeaderName
-MethodHeaderRightParen=)
-Modifiersopt=Modifiers
-MultiplicativeExpression=Expression
-MultiplicativeExpressionStmt=MultiplicativeExpression
-NestedMethod=NestedMethod
-NewExpression=NewExpression
-NewExpressionStmt=NewExpression
-ObjectLiteral=ObjectLiteral
-OpenBlock=OpenBlock
-PostDoc=PostDoc
-PostfixExpression=PostFixExpression
-PostfixExpressionStmt=PostfixExpression
-PreDecrementExpression=PreDecrementExpression
-PreDecrementExpressionStmt=PreDecrementExpression
-PreIncrementExpression=PreIncrementExpression
-PreIncrementExpressionStmt=PreIncrementExpression
-Primary=Primary
-PrimaryNoNewArray=PrimaryNoNewArray
-PrimaryNoNewArrayStmt=PrimaryNoNewArray
-PrimaryStmt=Primary
-ProgramElement=ProgramElement
-ProgramElements=ProgramElements
-ProgramElementsopt=ProgramElementsopt
-PropertyAssignment=PropertyAssignment
-PropertyName=FieldName
-PropertyNameAndValueList=NonemptyFieldList
-PropertySetParameterList=PropertySetParameterList
-PushLPAREN=(
-PushLeftBraceObjectLiteral=PushLeftBrace
-PushModifiers=PushModifiers
-PushPosition=PushPosition
-PushRPAREN=)
-RecoveryMethodHeader=MethodHeader
-RecoveryMethodHeaderName=MethodHeaderName
-RelationalExpression=Expression
-RelationalExpressionNoIn=Expression
-RelationalExpressionStmt=Expression
-RestoreDiet=RestoreDiet
-ReturnStatement=ReturnStatement
-ShiftExpression=Expression
-ShiftExpressionStmt=Expression
-SimpleName=SimpleName
-Statement=Statement
-StatementExpression=Expression
-StatementExpressionList=StatementExpressionList
-StatementNoShortIf=Statement
-StatementWithoutTrailingSubstatement=Statement
-SwitchBlock=SwitchBlock
-SwitchBlockStatement=SwitchBlockStatement
-SwitchBlockStatements=SwitchBlockStatements
-SwitchLabel=SwitchLabel
-SwitchLabels=SwitchLabels
-SwitchStatement=SwitchStatement
-ThrowStatement=ThrowStatement
-TryBlock=Block
-TryStatement=TryStatement
-UnaryExpression=Expression
-UnaryExpressionNotPlusMinus=Expression
-UnaryExpressionNotPlusMinusStmt=UnaryExpression
-UnaryExpressionStmt=UnaryExpression
-VariableDeclarator=VariableDeclarator
-VariableDeclaratorId=VariableDeclaratorId
-VariableDeclaratorNoIn=VariableDeclarator
-VariableDeclarators=VariableDeclarators
-VariableDeclaratorsNoIn=VariableDeclarators
-VariableInitializer=VariableInitializer
-VariableInitializerNoIn=VariableInitializer
-WhileStatement=WhileStatement
-WhileStatementNoShortIf=WhileStatement
-WithStatement=WithStatement
-WithStatementNoShortIf=WithStatementNoShortIf
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/start1.rsc b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/start1.rsc
deleted file mode 100644
index bf7e5aa0..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/start1.rsc
+++ /dev/null
Binary files differ
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/start2.rsc b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/start2.rsc
deleted file mode 100644
index e37032a2..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/start2.rsc
+++ /dev/null
Binary files differ
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/AbortCompilation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/AbortCompilation.java
deleted file mode 100644
index 35e633f7..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/AbortCompilation.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*******************************************************************************
- * 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.compiler.problem;
-
-import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem;
-import org.eclipse.wst.jsdt.core.infer.InferredType;
-import org.eclipse.wst.jsdt.internal.compiler.CompilationResult;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.InvocationSite;
-import org.eclipse.wst.jsdt.internal.compiler.util.Util;
-
-/*
- * Special unchecked exception type used
- * to abort from the compilation process
- *
- * should only be thrown from within problem handlers.
- */
-public class AbortCompilation extends RuntimeException {
-
- public CompilationResult compilationResult;
- public Throwable exception;
- public CategorizedProblem problem;
-
- /* special fields used to abort silently (e.g. when cancelling build process) */
- public boolean isSilent;
- public RuntimeException silentException;
-
- private static final long serialVersionUID = -2047226595083244852L; // backward compatible
-
- public AbortCompilation() {
- // empty
- }
-
- public AbortCompilation(CompilationResult compilationResult, CategorizedProblem problem) {
- this();
- this.compilationResult = compilationResult;
- this.problem = problem;
- }
-
- public AbortCompilation(CompilationResult compilationResult, Throwable exception) {
- this();
- this.compilationResult = compilationResult;
- this.exception = exception;
- }
-
- public AbortCompilation(boolean isSilent, RuntimeException silentException) {
- this();
- this.isSilent = isSilent;
- this.silentException = silentException;
- }
-
- public void updateContext(InvocationSite invocationSite, CompilationResult unitResult) {
- if (this.problem == null) return;
- if (this.problem.getSourceStart() != 0 || this.problem.getSourceEnd() != 0) return;
- this.problem.setSourceStart(invocationSite.sourceStart());
- this.problem.setSourceEnd(invocationSite.sourceEnd());
- int[] lineEnds = unitResult.getLineSeparatorPositions();
- this.problem.setSourceLineNumber(Util.getLineNumber(invocationSite.sourceStart(), lineEnds, 0, lineEnds.length-1));
- this.compilationResult = unitResult;
- }
-
- public void updateContext(ASTNode astNode, CompilationResult unitResult) {
- if (this.problem == null) return;
- if (this.problem.getSourceStart() != 0 || this.problem.getSourceEnd() != 0) return;
- this.problem.setSourceStart(astNode.sourceStart());
- this.problem.setSourceEnd(astNode.sourceEnd());
- int[] lineEnds = unitResult.getLineSeparatorPositions();
- this.problem.setSourceLineNumber(Util.getLineNumber(astNode.sourceStart(), lineEnds, 0, lineEnds.length-1));
- }
-
- public void updateContext(InferredType inferredType, CompilationResult unitResult) {
- if (this.problem == null) return;
- if (this.problem.getSourceStart() != 0 || this.problem.getSourceEnd() != 0) return;
- this.problem.setSourceStart(inferredType.sourceStart);
- this.problem.setSourceEnd(inferredType.sourceEnd);
- int[] lineEnds = unitResult.getLineSeparatorPositions();
- this.problem.setSourceLineNumber(Util.getLineNumber(inferredType.sourceStart,lineEnds, 0, lineEnds.length-1));
- this.compilationResult = unitResult;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/AbortCompilationUnit.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/AbortCompilationUnit.java
deleted file mode 100644
index c5410d95..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/AbortCompilationUnit.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.problem;
-
-import java.io.IOException;
-
-import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem;
-import org.eclipse.wst.jsdt.internal.compiler.CompilationResult;
-
-/*
- * Special unchecked exception type used
- * to abort from the compilation process
- *
- * should only be thrown from within problem handlers.
- */
-public class AbortCompilationUnit extends AbortCompilation {
-
- private static final long serialVersionUID = -4253893529982226734L; // backward compatible
-
- public String encoding;
-
-public AbortCompilationUnit(CompilationResult compilationResult, CategorizedProblem problem) {
- super(compilationResult, problem);
-}
-
-/**
- * Used to surface encoding issues when reading sources
- */
-public AbortCompilationUnit(CompilationResult compilationResult, IOException exception, String encoding) {
- super(compilationResult, exception);
- this.encoding = encoding;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/AbortMethod.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/AbortMethod.java
deleted file mode 100644
index 5f1b4736..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/AbortMethod.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.problem;
-
-import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem;
-import org.eclipse.wst.jsdt.internal.compiler.CompilationResult;
-
-/*
- * Special unchecked exception type used
- * to abort from the compilation process
- *
- * should only be thrown from within problem handlers.
- */
-public class AbortMethod extends AbortType {
-
- private static final long serialVersionUID = -1480267398969840003L; // backward compatible
-
-public AbortMethod(CompilationResult compilationResult, CategorizedProblem problem) {
- super(compilationResult, problem);
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/AbortType.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/AbortType.java
deleted file mode 100644
index 64a1616f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/AbortType.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.problem;
-
-import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem;
-import org.eclipse.wst.jsdt.internal.compiler.CompilationResult;
-
-/*
- * Special unchecked exception type used
- * to abort from the compilation process
- *
- * should only be thrown from within problem handlers.
- */
-public class AbortType extends AbortCompilationUnit {
-
- private static final long serialVersionUID = -5882417089349134385L; // backward compatible
-
-public AbortType(CompilationResult compilationResult, CategorizedProblem problem) {
- super(compilationResult, problem);
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/DefaultProblem.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/DefaultProblem.java
deleted file mode 100644
index 4ee3616f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/DefaultProblem.java
+++ /dev/null
@@ -1,289 +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.compiler.problem;
-
-import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.internal.compiler.util.Messages;
-import org.eclipse.wst.jsdt.internal.compiler.util.Util;
-
-public class DefaultProblem extends CategorizedProblem {
- private char[] fileName;
- private int id;
- private int startPosition, endPosition, line, column;
- private int severity;
- private String[] arguments;
- private String message;
-
- // cannot directly point to IJavaScriptModelMarker constants from within batch compiler
- private static final String MARKER_TYPE_PROBLEM = "org.eclipse.wst.jsdt.core.problem"; //$NON-NLS-1$
- private static final String MARKER_TYPE_TASK = "org.eclipse.wst.jsdt.core.task"; //$NON-NLS-1$
-
- public static final Object[] EMPTY_VALUES = {};
-
-public DefaultProblem(
- char[] originatingFileName,
- String message,
- int id,
- String[] stringArguments,
- int severity,
- int startPosition,
- int endPosition,
- int line,
- int column) {
-
- this.fileName = originatingFileName;
- this.message = message;
- this.id = id;
- this.arguments = stringArguments;
- this.severity = severity;
- this.startPosition = startPosition;
- this.endPosition = endPosition;
- this.line = line;
- this.column = column;
-}
-
-public String errorReportSource(char[] unitSource) {
- //extra from the source the innacurate token
- //and "highlight" it using some underneath ^^^^^
- //put some context around too.
-
- //this code assumes that the font used in the console is fixed size
-
- //sanity .....
- if ((this.startPosition > this.endPosition)
- || ((this.startPosition < 0) && (this.endPosition < 0))
- || unitSource.length == 0)
- return Messages.problem_noSourceInformation;
-
- StringBuffer errorBuffer = new StringBuffer();
- errorBuffer.append(' ').append(Messages.bind(Messages.problem_atLine, String.valueOf(this.line)));
- errorBuffer.append(Util.LINE_SEPARATOR);
- errorBuffer.append('\t');
-
- char c;
- final char SPACE = '\u0020';
- final char MARK = '^';
- final char TAB = '\t';
- //the next code tries to underline the token.....
- //it assumes (for a good display) that token source does not
- //contain any \r \n. This is false on statements !
- //(the code still works but the display is not optimal !)
-
- // expand to line limits
- int length = unitSource.length, begin, end;
- for (begin = this.startPosition >= length ? length - 1 : this.startPosition; begin > 0; begin--) {
- if ((c = unitSource[begin - 1]) == '\n' || c == '\r') break;
- }
- for (end = this.endPosition >= length ? length - 1 : this.endPosition ; end+1 < length; end++) {
- if ((c = unitSource[end + 1]) == '\r' || c == '\n') break;
- }
-
- // trim left and right spaces/tabs
- while ((c = unitSource[begin]) == ' ' || c == '\t') begin++;
- //while ((c = unitSource[end]) == ' ' || c == '\t') end--; TODO (philippe) should also trim right, but all tests are to be updated
-
- // copy source
- errorBuffer.append(unitSource, begin, end-begin+1);
- errorBuffer.append(Util.LINE_SEPARATOR).append("\t"); //$NON-NLS-1$
-
- // compute underline
- for (int i = begin; i <this.startPosition; i++) {
- errorBuffer.append((unitSource[i] == TAB) ? TAB : SPACE);
- }
- for (int i = this.startPosition; i <= (this.endPosition >= length ? length - 1 : this.endPosition); i++) {
- errorBuffer.append(MARK);
- }
- return errorBuffer.toString();
-}
-/**
- * Answer back the original arguments recorded into the problem.
- * @return java.lang.String[]
- */
-public String[] getArguments() {
- return this.arguments;
-}
-/**
- * @see org.eclipse.wst.jsdt.core.compiler.CategorizedProblem#getCategoryID()
- */
-public int getCategoryID() {
- return ProblemReporter.getProblemCategory(this.severity, this.id);
-}
-
-/**
- * Answer the type of problem.
- * @see org.eclipse.wst.jsdt.core.compiler.IProblem#getID()
- * @return int
- */
-public int getID() {
- return this.id;
-}
-
-/**
- * Answers a readable name for the category which this problem belongs to,
- * or null if none could be found.
- * FOR TESTING PURPOSE
- * @return java.lang.String
- */
-public String getInternalCategoryMessage() {
- switch(getCategoryID()) {
- case CAT_UNSPECIFIED:
- return "unspecified"; //$NON-NLS-1$
- case CAT_BUILDPATH:
- return "buildpath"; //$NON-NLS-1$
- case CAT_SYNTAX:
- return "syntax"; //$NON-NLS-1$
- case CAT_IMPORT:
- return "import"; //$NON-NLS-1$
- case CAT_TYPE:
- return "type"; //$NON-NLS-1$
- case CAT_MEMBER:
- return "member"; //$NON-NLS-1$
- case CAT_INTERNAL:
- return "internal"; //$NON-NLS-1$
- case CAT_JAVADOC:
- return "javadoc"; //$NON-NLS-1$
- case CAT_CODE_STYLE:
- return "code style"; //$NON-NLS-1$
- case CAT_POTENTIAL_PROGRAMMING_PROBLEM:
- return "potential programming problem"; //$NON-NLS-1$
- case CAT_NAME_SHADOWING_CONFLICT:
- return "name shadowing conflict"; //$NON-NLS-1$
- case CAT_UNNECESSARY_CODE:
- return "unnecessary code"; //$NON-NLS-1$
- case CAT_RESTRICTION:
- return "restriction"; //$NON-NLS-1$
- }
- return null;
-}
-
-/**
- * Returns the marker type associated to this problem.
- * @see org.eclipse.wst.jsdt.core.compiler.CategorizedProblem#getMarkerType()
- */
-public String getMarkerType() {
- return this.id == IProblem.Task
- ? MARKER_TYPE_TASK
- : MARKER_TYPE_PROBLEM;
-}
-
-/**
- * Answer a localized, human-readable message string which describes the problem.
- * @return java.lang.String
- */
-public String getMessage() {
- return this.message;
-}
-
-/**
- * Answer the file name in which the problem was found.
- * @return char[]
- */
-public char[] getOriginatingFileName() {
- return this.fileName;
-}
-
-/**
- * Answer the end position of the problem (inclusive), or -1 if unknown.
- * @return int
- */
-public int getSourceEnd() {
- return this.endPosition;
-}
-/**
- * Answer the line number in source where the problem begins.
- * @return int
- */
-public int getSourceColumnNumber() {
- return this.column;
-}
-/**
- * Answer the line number in source where the problem begins.
- * @return int
- */
-public int getSourceLineNumber() {
- return this.line;
-}
-/**
- * Answer the start position of the problem (inclusive), or -1 if unknown.
- * @return int
- */
-public int getSourceStart() {
- return this.startPosition;
-}
-
-/*
- * Helper method: checks the severity to see if the Error bit is set.
- * @return boolean
- */
-public boolean isError() {
- return (this.severity & ProblemSeverities.Error) != 0;
-}
-
-/*
- * Helper method: checks the severity to see if the Error bit is not set.
- * @return boolean
- */
-public boolean isWarning() {
- return (this.severity & ProblemSeverities.Error) == 0;
-}
-
-public void setOriginatingFileName(char[] fileName) {
- this.fileName = fileName;
-}
-
-/**
- * Set the end position of the problem (inclusive), or -1 if unknown.
- *
- * Used for shifting problem positions.
- * @param sourceEnd the new value of the sourceEnd of the receiver
- */
-public void setSourceEnd(int sourceEnd) {
- this.endPosition = sourceEnd;
-}
-
-/**
- * Set the line number in source where the problem begins.
- * @param lineNumber the new value of the line number of the receiver
- */
-public void setSourceLineNumber(int lineNumber) {
-
- this.line = lineNumber;
-}
-
-/**
- * Set the start position of the problem (inclusive), or -1 if unknown.
- *
- * Used for shifting problem positions.
- * @param sourceStart the new value of the source start position of the receiver
- */
-public void setSourceStart(int sourceStart) {
- this.startPosition = sourceStart;
-}
-
-public String toString() {
- String s = "Pb(" + (this.id & IProblem.IgnoreCategoriesMask) + ") "; //$NON-NLS-1$ //$NON-NLS-2$
- if (this.message != null) {
- s += this.message;
- } else {
- if (this.arguments != null)
- for (int i = 0; i < this.arguments.length; i++)
- s += " " + this.arguments[i]; //$NON-NLS-1$
- }
- return s;
-}
-
-
-public void setMessage(String msg)
-{
- this.message=msg;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/DefaultProblemFactory.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/DefaultProblemFactory.java
deleted file mode 100644
index f70812d9..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/DefaultProblemFactory.java
+++ /dev/null
@@ -1,206 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.problem;
-
-import java.util.Enumeration;
-import java.util.Locale;
-import java.util.MissingResourceException;
-import java.util.ResourceBundle;
-
-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.IProblemFactory;
-import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfInt;
-import org.eclipse.wst.jsdt.internal.compiler.util.Util;
-
-public class DefaultProblemFactory implements IProblemFactory {
-
- public HashtableOfInt messageTemplates;
- private Locale locale;
- private static HashtableOfInt DEFAULT_LOCALE_TEMPLATES;
- private final static char[] DOUBLE_QUOTES = "''".toCharArray(); //$NON-NLS-1$
- private final static char[] SINGLE_QUOTE = "'".toCharArray(); //$NON-NLS-1$
-
-public DefaultProblemFactory() {
- this(Locale.getDefault());
-}
-/**
- * @param loc the locale used to get the right message
- */
-public DefaultProblemFactory(Locale loc) {
- setLocale(loc);
-}
-/**
- * Answer a new IProblem created according to the parameters value
- * <ul>
- * <li>originatingFileName the name of the file name from which the problem is originated
- * <li>problemId the problem id
- * <li>problemArguments the fully qualified arguments recorded inside the problem
- * <li>messageArguments the arguments needed to set the error message (shorter names than problemArguments ones)
- * <li>severity the severity of the problem
- * <li>startPosition the starting position of the problem
- * <li>endPosition the end position of the problem
- * <li>lineNumber the line on which the problem occured
- * </ul>
- * @param originatingFileName char[]
- * @param problemId int
- * @param problemArguments String[]
- * @param messageArguments String[]
- * @param severity int
- * @param startPosition int
- * @param endPosition int
- * @param lineNumber int
- * @return CategorizedProblem
- */
-public CategorizedProblem createProblem(
- char[] originatingFileName,
- int problemId,
- String[] problemArguments,
- String[] messageArguments,
- int severity,
- int startPosition,
- int endPosition,
- int lineNumber,
- int columnNumber) {
-
- return new DefaultProblem(
- originatingFileName,
- this.getLocalizedMessage(problemId, messageArguments),
- problemId,
- problemArguments,
- severity,
- startPosition,
- endPosition,
- lineNumber,
- columnNumber);
-}
-private final static int keyFromID(int id) {
- return id + 1; // keys are offsetted by one in table, since it cannot handle 0 key
-}
-/**
- * Answer the locale used to retrieve the error messages
- * @return java.util.Locale
- */
-public Locale getLocale() {
- return this.locale;
-}
-public void setLocale(Locale locale) {
- if (locale == this.locale) return;
- this.locale = locale;
- if (Locale.getDefault().equals(locale)){
- if (DEFAULT_LOCALE_TEMPLATES == null){
- DEFAULT_LOCALE_TEMPLATES = loadMessageTemplates(locale);
- }
- this.messageTemplates = DEFAULT_LOCALE_TEMPLATES;
- } else {
- this.messageTemplates = loadMessageTemplates(locale);
- }
-}
-
-public final String getLocalizedMessage(int id, String[] problemArguments) {
- String message = (String) this.messageTemplates.get(keyFromID(id & IProblem.IgnoreCategoriesMask));
- if (message == null) {
- return "Unable to retrieve the error message for problem id: " //$NON-NLS-1$
- + (id & IProblem.IgnoreCategoriesMask)
- + ". Check compiler resources."; //$NON-NLS-1$
- }
-
- // for compatibility with MessageFormat which eliminates double quotes in original message
- char[] messageWithNoDoubleQuotes =
- CharOperation.replace(message.toCharArray(), DOUBLE_QUOTES, SINGLE_QUOTE);
-
- if (problemArguments == null) return new String(messageWithNoDoubleQuotes);
-
- int length = messageWithNoDoubleQuotes.length;
- int start = 0;
- int end = length;
- StringBuffer output = null;
- if ((id & IProblem.Javadoc) != 0) {
- output = new StringBuffer(10+length+problemArguments.length*20);
- output.append((String) this.messageTemplates.get(keyFromID(IProblem.JavadocMessagePrefix & IProblem.IgnoreCategoriesMask)));
- }
- while (true) {
- if ((end = CharOperation.indexOf('{', messageWithNoDoubleQuotes, start)) > -1) {
- if (output == null) output = new StringBuffer(length+problemArguments.length*20);
- output.append(messageWithNoDoubleQuotes, start, end - start);
- if ((start = CharOperation.indexOf('}', messageWithNoDoubleQuotes, end + 1)) > -1) {
- int index = -1;
- String argId = new String(messageWithNoDoubleQuotes, end + 1, start - end - 1);
- try {
- index = Integer.parseInt(argId);
- output.append(problemArguments[index]);
- } catch (NumberFormatException nfe) {
- output.append(messageWithNoDoubleQuotes, end + 1, start - end);
- } catch (ArrayIndexOutOfBoundsException e) {
- return "Cannot bind message for problem (id: " //$NON-NLS-1$
- + (id & IProblem.IgnoreCategoriesMask)
- + ") \"" //$NON-NLS-1$
- + message
- + "\" with arguments: {" //$NON-NLS-1$
- + Util.toString(problemArguments)
- +"}"; //$NON-NLS-1$
- }
- start++;
- } else {
- output.append(messageWithNoDoubleQuotes, end, length);
- break;
- }
- } else {
- if (output == null) return new String(messageWithNoDoubleQuotes);
- output.append(messageWithNoDoubleQuotes, start, length - start);
- break;
- }
- }
-
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=120410
- return new String(output.toString());
-}
-/**
- * @param problem CategorizedProblem
- * @return String
- */
-public final String localizedMessage(CategorizedProblem problem) {
- return getLocalizedMessage(problem.getID(), problem.getArguments());
-}
-
-/**
- * This method initializes the MessageTemplates class variable according
- * to the current Locale.
- * @param loc Locale
- * @return HashtableOfInt
- */
-public static HashtableOfInt loadMessageTemplates(Locale loc) {
- ResourceBundle bundle = null;
- String bundleName = "org.eclipse.wst.jsdt.internal.compiler.problem.messages"; //$NON-NLS-1$
- try {
- bundle = ResourceBundle.getBundle(bundleName, loc);
- } catch(MissingResourceException e) {
- System.out.println("Missing resource : " + bundleName.replace('.', '/') + ".properties for locale " + loc); //$NON-NLS-1$//$NON-NLS-2$
- throw e;
- }
- HashtableOfInt templates = new HashtableOfInt(700);
- Enumeration keys = bundle.getKeys();
- while (keys.hasMoreElements()) {
- String key = (String)keys.nextElement();
- try {
- int messageID = Integer.parseInt(key);
- templates.put(keyFromID(messageID), bundle.getString(key));
- } catch(NumberFormatException e) {
- // key ill-formed
- } catch (MissingResourceException e) {
- // available ID
- }
- }
- return templates;
-}
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/ProblemHandler.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/ProblemHandler.java
deleted file mode 100644
index 7e1ac208..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/ProblemHandler.java
+++ /dev/null
@@ -1,167 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.problem;
-
-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.IErrorHandlingPolicy;
-import org.eclipse.wst.jsdt.internal.compiler.IProblemFactory;
-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.util.Util;
-
-/*
- * Compiler error handler, responsible to determine whether
- * a problem is actually a warning or an error; also will
- * decide whether the compilation task can be processed further or not.
- *
- * Behavior : will request its current policy if need to stop on
- * first error, and if should proceed (persist) with problems.
- */
-
-public class ProblemHandler {
-
- public final static String[] NoArgument = CharOperation.NO_STRINGS;
-
- final public IErrorHandlingPolicy policy;
- public final IProblemFactory problemFactory;
- public final CompilerOptions options;
-/*
- * Problem handler can be supplied with a policy to specify
- * its behavior in error handling. Also see static methods for
- * built-in policies.
- *
- */
-public ProblemHandler(IErrorHandlingPolicy policy, CompilerOptions options, IProblemFactory problemFactory) {
- this.policy = policy;
- this.problemFactory = problemFactory;
- this.options = options;
-}
-/*
- * Given the current configuration, answers which category the problem
- * falls into:
- * Error | Warning | Ignore
- */
-public int computeSeverity(int problemId){
-
- return ProblemSeverities.Error; // by default all problems are errors
-}
-public CategorizedProblem createProblem(
- char[] fileName,
- int problemId,
- String[] problemArguments,
- String[] messageArguments,
- int severity,
- int problemStartPosition,
- int problemEndPosition,
- int lineNumber,
- int columnNumber) {
-
- return this.problemFactory.createProblem(
- fileName,
- problemId,
- problemArguments,
- messageArguments,
- severity,
- problemStartPosition,
- problemEndPosition,
- lineNumber,
- columnNumber);
-}
-public void handle(
- int problemId,
- String[] problemArguments,
- String[] messageArguments,
- int severity,
- int problemStartPosition,
- int problemEndPosition,
- ReferenceContext referenceContext,
- CompilationResult unitResult) {
-
- if (severity == ProblemSeverities.Ignore)
- return;
-
- // if no reference context, we need to abort from the current compilation process
- if (referenceContext == null) {
- if ((severity & ProblemSeverities.Error) != 0) { // non reportable error is fatal
- CategorizedProblem problem = this.createProblem(null, problemId, problemArguments, messageArguments, severity, 0, 0, 0, 0);
- throw new AbortCompilation(null, problem);
- } else {
- return; // ignore non reportable warning
- }
- }
-
- int[] lineEnds;
- int lineNumber = problemStartPosition >= 0
- ? Util.getLineNumber(problemStartPosition, lineEnds = unitResult.getLineSeparatorPositions(), 0, lineEnds.length-1)
- : 0;
- int columnNumber = problemStartPosition >= 0
- ? Util.searchColumnNumber(unitResult.getLineSeparatorPositions(), lineNumber, problemStartPosition)
- : 0;
- CategorizedProblem problem =
- this.createProblem(
- unitResult.getFileName(),
- problemId,
- problemArguments,
- messageArguments,
- severity,
- problemStartPosition,
- problemEndPosition,
- lineNumber,
- columnNumber);
-
- if (problem == null) return; // problem couldn't be created, ignore
-
- switch (severity & ProblemSeverities.Error) {
- case ProblemSeverities.Error :
- this.record(problem, unitResult, referenceContext);
- if ((severity & ProblemSeverities.Fatal) != 0) {
- referenceContext.tagAsHavingErrors();
- // should abort ?
- int abortLevel;
- if ((abortLevel = this.policy.stopOnFirstError() ? ProblemSeverities.AbortCompilation : severity & ProblemSeverities.Abort) != 0) {
- referenceContext.abort(abortLevel, problem);
- }
- }
- break;
- case ProblemSeverities.Warning :
- this.record(problem, unitResult, referenceContext);
- break;
- }
-}
-/**
- * Standard problem handling API, the actual severity (warning/error/ignore) is deducted
- * from the problem ID and the current compiler options.
- */
-public void handle(
- int problemId,
- String[] problemArguments,
- String[] messageArguments,
- int problemStartPosition,
- int problemEndPosition,
- ReferenceContext referenceContext,
- CompilationResult unitResult) {
-
- this.handle(
- problemId,
- problemArguments,
- messageArguments,
- this.computeSeverity(problemId), // severity inferred using the ID
- problemStartPosition,
- problemEndPosition,
- referenceContext,
- unitResult);
-}
-public void record(CategorizedProblem problem, CompilationResult unitResult, ReferenceContext referenceContext) {
- unitResult.record(problem, referenceContext);
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/ProblemReporter.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/ProblemReporter.java
deleted file mode 100644
index 4bb6b947..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/ProblemReporter.java
+++ /dev/null
@@ -1,3306 +0,0 @@
-/*******************************************************************************
- * 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 <spektom@gmail.com> - Bug 243886
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.problem;
-
-import java.io.CharConversionException;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.text.MessageFormat;
-
-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.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.core.infer.InferredAttribute;
-import org.eclipse.wst.jsdt.core.infer.InferredType;
-import org.eclipse.wst.jsdt.internal.compiler.CompilationResult;
-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.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.ArrayQualifiedTypeReference;
-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.BranchStatement;
-import org.eclipse.wst.jsdt.internal.compiler.ast.CaseStatement;
-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.ConstructorDeclaration;
-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.FieldDeclaration;
-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.InstanceOfExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.IntLiteral;
-import org.eclipse.wst.jsdt.internal.compiler.ast.LabeledStatement;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Literal;
-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.NumberLiteral;
-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.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.ast.TypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.UnaryExpression;
-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.ArrayBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Binding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ExtraCompilerModifiers;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.FieldBinding;
-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.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.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;
-import org.eclipse.wst.jsdt.internal.compiler.parser.Parser;
-import org.eclipse.wst.jsdt.internal.compiler.parser.RecoveryScanner;
-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.compiler.util.Messages;
-import org.eclipse.wst.jsdt.internal.compiler.util.Util;
-
-public class ProblemReporter extends ProblemHandler {
-
- public ReferenceContext referenceContext;
- private Scanner positionScanner;
-
-public static long getIrritant(int problemID) {
- switch(problemID){
-
- case IProblem.UninitializedLocalVariable:
- return CompilerOptions.UninitializedLocalVariable;
-
- case IProblem.UninitializedGlobalVariable:
- return CompilerOptions.UninitializedGlobalVariable;
-
- case IProblem.MaskedCatch :
- return CompilerOptions.MaskedCatchBlock;
-
- case IProblem.MethodButWithConstructorName :
- return CompilerOptions.MethodWithConstructorName;
-
- /* START -------------------------------- Bug 203292 Type/Method/Filed resolution error configuration --------------------- */
-
- case IProblem.UndefinedName:
- return CompilerOptions.UnresolvedType;
- case IProblem.UndefinedFunction:
- case IProblem.UndefinedMethod:
- case IProblem.UndefinedConstructor:
- return CompilerOptions.UnresolvedMethod;
- /* END -------------------------------- Bug 203292 Type/Method/Filed resolution error configuration --------------------- */
- case IProblem.OptionalSemiColon:
- return CompilerOptions.OptionalSemicolon;
- case IProblem.LooseVarDecl:
- return CompilerOptions.LooseVariableDecl;
- /* START -------------------------------- Bug 197884 Loosly defined var (for statement) and optional semi-colon --------------------- */
-
-
- /* END -------------------------------- Bug 197884 Loosly defined var (for statement) and optional semi-colon --------------------- */
-
- case IProblem.OverridingDeprecatedMethod :
- case IProblem.UsingDeprecatedType :
- case IProblem.UsingDeprecatedMethod :
- case IProblem.UsingDeprecatedConstructor :
- case IProblem.UsingDeprecatedField :
- return CompilerOptions.UsingDeprecatedAPI;
-
- case IProblem.LocalVariableIsNeverUsed :
- return CompilerOptions.UnusedLocalVariable;
-
- case IProblem.ArgumentIsNeverUsed :
- return CompilerOptions.UnusedArgument;
-
- case IProblem.NeedToEmulateFieldReadAccess :
- case IProblem.NeedToEmulateFieldWriteAccess :
- case IProblem.NeedToEmulateMethodAccess :
- case IProblem.NeedToEmulateConstructorAccess :
- return CompilerOptions.AccessEmulation;
-
- case IProblem.NonExternalizedStringLiteral :
- case IProblem.UnnecessaryNLSTag :
- return CompilerOptions.NonExternalizedString;
-
- case IProblem.UseAssertAsAnIdentifier :
- return CompilerOptions.AssertUsedAsAnIdentifier;
-
- case IProblem.UseEnumAsAnIdentifier :
- return CompilerOptions.EnumUsedAsAnIdentifier;
-
- case IProblem.NonStaticAccessToStaticMethod :
- case IProblem.NonStaticAccessToStaticField :
- return CompilerOptions.NonStaticAccessToStatic;
-
- case IProblem.IndirectAccessToStaticMethod :
- case IProblem.IndirectAccessToStaticField :
- case IProblem.IndirectAccessToStaticType :
- return CompilerOptions.IndirectStaticAccess;
-
- case IProblem.AssignmentHasNoEffect:
- return CompilerOptions.NoEffectAssignment;
-
- case IProblem.UnusedPrivateConstructor:
- case IProblem.UnusedPrivateMethod:
- case IProblem.UnusedPrivateField:
- case IProblem.UnusedPrivateType:
- return CompilerOptions.UnusedPrivateMember;
-
- case IProblem.LocalVariableHidingLocalVariable:
- case IProblem.LocalVariableHidingField:
- case IProblem.ArgumentHidingLocalVariable:
- case IProblem.ArgumentHidingField:
- return CompilerOptions.LocalVariableHiding;
-
- case IProblem.FieldHidingLocalVariable:
- case IProblem.FieldHidingField:
- return CompilerOptions.FieldHiding;
-
- case IProblem.TypeHidingType:
- return CompilerOptions.TypeHiding;
-
- case IProblem.PossibleAccidentalBooleanAssignment:
- return CompilerOptions.AccidentalBooleanAssign;
-
- case IProblem.SuperfluousSemicolon:
- case IProblem.EmptyControlFlowStatement:
- return CompilerOptions.EmptyStatement;
-
- case IProblem.UndocumentedEmptyBlock:
- return CompilerOptions.UndocumentedEmptyBlock;
-
- case IProblem.UnnecessaryInstanceof:
- return CompilerOptions.UnnecessaryTypeCheck;
-
- case IProblem.FinallyMustCompleteNormally:
- return CompilerOptions.FinallyBlockNotCompleting;
-
- case IProblem.UnusedMethodDeclaredThrownException:
- case IProblem.UnusedConstructorDeclaredThrownException:
- return CompilerOptions.UnusedDeclaredThrownException;
-
- case IProblem.UnqualifiedFieldAccess:
- return CompilerOptions.UnqualifiedFieldAccess;
-
- case IProblem.UnnecessaryElse:
- return CompilerOptions.UnnecessaryElse;
-
- case IProblem.ForbiddenReference:
- return CompilerOptions.ForbiddenReference;
-
- case IProblem.DiscouragedReference:
- return CompilerOptions.DiscouragedReference;
-
- case IProblem.NullLocalVariableReference:
- return CompilerOptions.NullReference;
-
- case IProblem.PotentialNullLocalVariableReference:
- return CompilerOptions.PotentialNullReference;
-
- case IProblem.RedefinedLocal:
- return CompilerOptions.DuplicateLocalVariables;
-
- case IProblem.RedundantLocalVariableNullAssignment:
- case IProblem.RedundantNullCheckOnNonNullLocalVariable:
- case IProblem.RedundantNullCheckOnNullLocalVariable:
- case IProblem.NonNullLocalVariableComparisonYieldsFalse:
- case IProblem.NullLocalVariableComparisonYieldsFalse:
- case IProblem.NullLocalVariableInstanceofYieldsFalse:
- return CompilerOptions.RedundantNullCheck;
-
- case IProblem.UnusedLabel :
- return CompilerOptions.UnusedLabel;
-
- case IProblem.JavadocUnexpectedTag:
- case IProblem.JavadocDuplicateReturnTag:
- case IProblem.JavadocInvalidThrowsClass:
- case IProblem.JavadocInvalidSeeReference:
- case IProblem.JavadocInvalidParamTagName:
- case IProblem.JavadocMalformedSeeReference:
- case IProblem.JavadocInvalidSeeHref:
- case IProblem.JavadocInvalidSeeArgs:
- case IProblem.JavadocInvalidTag:
- case IProblem.JavadocUnterminatedInlineTag:
- case IProblem.JavadocMissingHashCharacter:
- case IProblem.JavadocEmptyReturnTag:
- case IProblem.JavadocUnexpectedText:
- case IProblem.JavadocInvalidParamName:
- case IProblem.JavadocDuplicateParamName:
- case IProblem.JavadocMissingParamName:
- case IProblem.JavadocMissingIdentifier:
- case IProblem.JavadocInvalidMemberTypeQualification:
- case IProblem.JavadocInvalidThrowsClassName:
- case IProblem.JavadocDuplicateThrowsClassName:
- case IProblem.JavadocMissingThrowsClassName:
- case IProblem.JavadocMissingSeeReference:
- case IProblem.JavadocUndefinedField:
- case IProblem.JavadocAmbiguousField:
- case IProblem.JavadocUndefinedConstructor:
- case IProblem.JavadocAmbiguousConstructor:
- case IProblem.JavadocUndefinedMethod:
- case IProblem.JavadocAmbiguousMethod:
- case IProblem.JavadocParameterMismatch:
- case IProblem.JavadocUndefinedType:
- case IProblem.JavadocAmbiguousType:
- case IProblem.JavadocInternalTypeNameProvided:
- case IProblem.JavadocNoMessageSendOnArrayType:
- case IProblem.JavadocNoMessageSendOnBaseType:
- case IProblem.JavadocInheritedMethodHidesEnclosingName:
- case IProblem.JavadocInheritedFieldHidesEnclosingName:
- case IProblem.JavadocInheritedNameHidesEnclosingTypeName:
- case IProblem.JavadocNonStaticTypeFromStaticInvocation:
- case IProblem.JavadocNotVisibleField:
- case IProblem.JavadocNotVisibleConstructor:
- case IProblem.JavadocNotVisibleMethod:
- case IProblem.JavadocNotVisibleType:
- case IProblem.JavadocUsingDeprecatedField:
- case IProblem.JavadocUsingDeprecatedConstructor:
- case IProblem.JavadocUsingDeprecatedMethod:
- case IProblem.JavadocUsingDeprecatedType:
- case IProblem.JavadocHiddenReference:
- return CompilerOptions.InvalidJavadoc;
-
- case IProblem.JavadocMissingParamTag:
- case IProblem.JavadocMissingReturnTag:
- case IProblem.JavadocMissingThrowsTag:
- return CompilerOptions.MissingJavadocTags;
-
- case IProblem.JavadocMissing:
- return CompilerOptions.MissingJavadocComments;
-
- case IProblem.ParameterAssignment:
- return CompilerOptions.ParameterAssignment;
-
- case IProblem.FallthroughCase:
- return CompilerOptions.FallthroughCase;
-
- case IProblem.OverridingMethodWithoutSuperInvocation:
- return CompilerOptions.OverridingMethodWithoutSuperInvocation;
- case IProblem.UndefinedField:
- return CompilerOptions.UndefinedField;
-
- case IProblem.WrongNumberOfArguments:
- return CompilerOptions.WrongNumberOfArguments;
-
- case IProblem.MissingSemiColon:
- return CompilerOptions.OptionalSemicolon;
-
-
- }
- return 0;
-}
-/**
- * Compute problem category ID based on problem ID
- * @param problemID
- * @return a category ID
- * @see CategorizedProblem
- */
-public static int getProblemCategory(int severity, int problemID) {
- categorizeOnIrritant: {
- // fatal problems even if optional are all falling into same category (not irritant based)
- if ((severity & ProblemSeverities.Fatal) != 0)
- break categorizeOnIrritant;
- long irritant = getIrritant(problemID);
- int irritantInt = (int) irritant;
- if (irritantInt == irritant) {
- switch (irritantInt) {
- case (int)CompilerOptions.MethodWithConstructorName:
- case (int)CompilerOptions.AccessEmulation:
- case (int)CompilerOptions.AssertUsedAsAnIdentifier:
- case (int)CompilerOptions.NonStaticAccessToStatic:
- case (int)CompilerOptions.UnqualifiedFieldAccess:
- case (int)CompilerOptions.UndocumentedEmptyBlock:
- case (int)CompilerOptions.IndirectStaticAccess:
- return CategorizedProblem.CAT_CODE_STYLE;
-
- case (int)CompilerOptions.MaskedCatchBlock:
- case (int)CompilerOptions.NoEffectAssignment:
- case (int)CompilerOptions.AccidentalBooleanAssign:
- case (int)CompilerOptions.EmptyStatement:
- case (int)CompilerOptions.FinallyBlockNotCompleting:
- case (int)CompilerOptions.UndefinedField:
- return CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM;
-
- case (int)CompilerOptions.LocalVariableHiding:
- case (int)CompilerOptions.FieldHiding:
- return CategorizedProblem.CAT_NAME_SHADOWING_CONFLICT;
-
- case (int)CompilerOptions.UnusedLocalVariable:
- case (int)CompilerOptions.UnusedArgument:
- case (int)CompilerOptions.UnusedPrivateMember:
- case (int)CompilerOptions.UnusedDeclaredThrownException:
- case (int)CompilerOptions.UnnecessaryTypeCheck:
- case (int)CompilerOptions.UnnecessaryElse:
- return CategorizedProblem.CAT_UNNECESSARY_CODE;
-
- case (int)CompilerOptions.Task:
- return CategorizedProblem.CAT_UNSPECIFIED; // TODO may want to improve
-
- case (int)CompilerOptions.MissingJavadocComments:
- case (int)CompilerOptions.MissingJavadocTags:
- case (int)CompilerOptions.InvalidJavadoc:
- case (int)(CompilerOptions.InvalidJavadoc | CompilerOptions.UsingDeprecatedAPI):
- return CategorizedProblem.CAT_JAVADOC;
-
- default:
- break categorizeOnIrritant;
- }
- } else {
- irritantInt = (int)(irritant >>> 32);
- switch (irritantInt) {
- case (int)(CompilerOptions.FinalParameterBound >>> 32):
- case (int)(CompilerOptions.EnumUsedAsAnIdentifier >>> 32):
- case (int)(CompilerOptions.ParameterAssignment >>> 32):
- return CategorizedProblem.CAT_CODE_STYLE;
-
- case (int)(CompilerOptions.NullReference >>> 32):
- case (int)(CompilerOptions.PotentialNullReference >>> 32):
- case (int)(CompilerOptions.DuplicateLocalVariables >>> 32):
- case (int)(CompilerOptions.RedundantNullCheck >>> 32):
- case (int)(CompilerOptions.FallthroughCase >>> 32):
- case (int)(CompilerOptions.OverridingMethodWithoutSuperInvocation >>> 32):
- case (int)(CompilerOptions.UninitializedLocalVariable >>> 32):
- case (int)(CompilerOptions.UninitializedGlobalVariable >>> 32):
- return CategorizedProblem.CAT_POTENTIAL_PROGRAMMING_PROBLEM;
-
- case (int)(CompilerOptions.TypeHiding >>> 32):
- return CategorizedProblem.CAT_NAME_SHADOWING_CONFLICT;
-
- case (int)(CompilerOptions.UnusedLabel >>> 32):
- return CategorizedProblem.CAT_UNNECESSARY_CODE;
-
- case (int)(CompilerOptions.ForbiddenReference >>> 32):
- case (int)(CompilerOptions.DiscouragedReference >>> 32):
- return CategorizedProblem.CAT_RESTRICTION;
-
- default:
- break categorizeOnIrritant;
- }
- }
- }
- // categorize fatal problems per ID
- switch (problemID) {
- case IProblem.IsClassPathCorrect :
- case IProblem.CorruptedSignature :
- return CategorizedProblem.CAT_BUILDPATH;
-
- default :
- if ((problemID & IProblem.Syntax) != 0)
- return CategorizedProblem.CAT_SYNTAX;
- if ((problemID & IProblem.ImportRelated) != 0)
- return CategorizedProblem.CAT_IMPORT;
- if ((problemID & IProblem.TypeRelated) != 0)
- return CategorizedProblem.CAT_TYPE;
- if ((problemID & (IProblem.FieldRelated|IProblem.MethodRelated|IProblem.ConstructorRelated)) != 0)
- return CategorizedProblem.CAT_MEMBER;
- }
- return CategorizedProblem.CAT_INTERNAL;
-}
-public ProblemReporter(IErrorHandlingPolicy policy, CompilerOptions options, IProblemFactory problemFactory) {
- super(policy, options, problemFactory);
-}
-public void abortDueToInternalError(String errorMessage) {
- this.abortDueToInternalError(errorMessage, null);
-}
-public void abortDueToInternalError(String errorMessage, ASTNode location) {
- String[] arguments = new String[] {errorMessage};
- this.handle(
- IProblem.Unclassified,
- arguments,
- arguments,
- ProblemSeverities.Error | ProblemSeverities.Abort | ProblemSeverities.Fatal,
- location == null ? 0 : location.sourceStart,
- location == null ? 0 : location.sourceEnd);
-}
-public void alreadyDefinedLabel(char[] labelName, ASTNode location) {
- String[] arguments = new String[] {new String(labelName)};
- this.handle(
- IProblem.DuplicateLabel,
- arguments,
- arguments,
- location.sourceStart,
- location.sourceEnd);
-}
-public void assignmentHasNoEffect(AbstractVariableDeclaration location, char[] name){
- int severity = computeSeverity(IProblem.AssignmentHasNoEffect);
- if (severity == ProblemSeverities.Ignore) return;
- String[] arguments = new String[] { new String(name) };
- int start = location.sourceStart;
- int end = location.sourceEnd;
- if (location.initialization != null) {
- end = location.initialization.sourceEnd;
- }
- this.handle(
- IProblem.AssignmentHasNoEffect,
- arguments,
- arguments,
- severity,
- start,
- end);
-}
-public void assignmentHasNoEffect(Assignment location, char[] name){
- int severity = computeSeverity(IProblem.AssignmentHasNoEffect);
- if (severity == ProblemSeverities.Ignore) return;
- String[] arguments = new String[] { new String(name) };
- this.handle(
- IProblem.AssignmentHasNoEffect,
- arguments,
- arguments,
- severity,
- location.sourceStart,
- location.sourceEnd);
-}
-public void cannotReadSource(CompilationUnitDeclaration unit, AbortCompilationUnit abortException, boolean verbose) {
- String fileName = new String(unit.compilationResult.fileName);
- if (abortException.exception instanceof CharConversionException) {
- // specific encoding issue
- String encoding = abortException.encoding;
- if (encoding == null) {
- encoding = System.getProperty("file.encoding"); //$NON-NLS-1$
- }
- String[] arguments = new String[]{ fileName, encoding, };
- this.handle(
- IProblem.InvalidEncoding,
- arguments,
- arguments,
- 0,
- 0);
- return;
- }
- StringWriter stringWriter = new StringWriter();
- PrintWriter writer = new PrintWriter(stringWriter);
- if (verbose) {
- abortException.exception.printStackTrace(writer);
- } else {
- writer.print(abortException.exception.getClass().getName());
- writer.print(':');
- writer.print(abortException.exception.getMessage());
- }
- String exceptionTrace = stringWriter.toString();
- String[] arguments = new String[]{ fileName, exceptionTrace, };
- this.handle(
- IProblem.CannotReadSource,
- arguments,
- arguments,
- 0,
- 0);
-}
-public void cannotReturnOutsideFunction(ASTNode location) {
- this.handle(
- IProblem.CannotReturnOutsideFunction,
- NoArgument,
- NoArgument,
- location.sourceStart,
- location.sourceEnd);
-}
-/*
- * Given the current configuration, answers which category the problem
- * falls into:
- * ProblemSeverities.Error | ProblemSeverities.Warning | ProblemSeverities.Ignore
- * when different from Ignore, severity can be coupled with ProblemSeverities.Optional
- * to indicate that this problem is configurable through options
- */
-public int computeSeverity(int problemID){
-
-
- /*
- * If semantic validation is not enabled and this is anything but a
- * syntax, documentation, or task problem, ignore.
- */
- if (!this.options.enableSemanticValidation && (problemID & IProblem.Syntax) == 0 && (problemID & IProblem.Javadoc) == 0 && problemID != IProblem.Task) {
- return ProblemSeverities.Ignore;
- }
-
- switch (problemID) {
- case IProblem.Task :
- return ProblemSeverities.Warning;
- case IProblem.TypeCollidesWithPackage :
- return ProblemSeverities.Warning;
-
- /*
- * JS Type mismatch is set to default as Warning
- */
- case IProblem.NotAFunction:
- case IProblem.TypeMismatch:
- return ProblemSeverities.Warning;
-
-// case IProblem.UndefinedName:
-// case IProblem.UndefinedFunction:
-// case IProblem.UndefinedMethod:
-// case IProblem.UndefinedField:
-// case IProblem.UndefinedConstructor:
-// break;
- /*
- * Javadoc tags resolved references errors
- */
- case IProblem.JavadocInvalidParamName:
- case IProblem.JavadocDuplicateParamName:
- case IProblem.JavadocMissingParamName:
- case IProblem.JavadocMissingIdentifier:
- case IProblem.JavadocInvalidMemberTypeQualification:
- case IProblem.JavadocInvalidThrowsClassName:
- case IProblem.JavadocDuplicateThrowsClassName:
- case IProblem.JavadocMissingThrowsClassName:
- case IProblem.JavadocMissingSeeReference:
- case IProblem.JavadocUndefinedField:
- case IProblem.JavadocAmbiguousField:
- case IProblem.JavadocUndefinedConstructor:
- case IProblem.JavadocAmbiguousConstructor:
- case IProblem.JavadocUndefinedMethod:
- case IProblem.JavadocAmbiguousMethod:
- case IProblem.JavadocParameterMismatch:
- case IProblem.JavadocUndefinedType:
- case IProblem.JavadocAmbiguousType:
- case IProblem.JavadocInternalTypeNameProvided:
- case IProblem.JavadocNoMessageSendOnArrayType:
- case IProblem.JavadocNoMessageSendOnBaseType:
- case IProblem.JavadocInheritedMethodHidesEnclosingName:
- case IProblem.JavadocInheritedFieldHidesEnclosingName:
- case IProblem.JavadocInheritedNameHidesEnclosingTypeName:
- case IProblem.JavadocNonStaticTypeFromStaticInvocation:
- case IProblem.JavadocEmptyReturnTag:
- if (!this.options.reportInvalidJavadocTags) {
- return ProblemSeverities.Ignore;
- }
- break;
- /*
- * Javadoc invalid tags due to deprecated references
- */
- case IProblem.JavadocUsingDeprecatedField:
- case IProblem.JavadocUsingDeprecatedConstructor:
- case IProblem.JavadocUsingDeprecatedMethod:
- case IProblem.JavadocUsingDeprecatedType:
- if (!(this.options.reportInvalidJavadocTags && this.options.reportInvalidJavadocTagsDeprecatedRef)) {
- return ProblemSeverities.Ignore;
- }
- break;
- /*
- * Javadoc invalid tags due to non-visible references
- */
- case IProblem.JavadocNotVisibleField:
- case IProblem.JavadocNotVisibleConstructor:
- case IProblem.JavadocNotVisibleMethod:
- case IProblem.JavadocNotVisibleType:
- case IProblem.JavadocHiddenReference:
- if (!(this.options.reportInvalidJavadocTags && this.options.reportInvalidJavadocTagsNotVisibleRef)) {
- return ProblemSeverities.Ignore;
- }
- break;
- }
- long irritant = getIrritant(problemID);
- if (irritant != 0) {
- if ((problemID & IProblem.Javadoc) != 0 && !this.options.docCommentSupport)
- return ProblemSeverities.Ignore;
- return this.options.getSeverity(irritant);
- }
- return ProblemSeverities.Error | ProblemSeverities.Fatal;
-}
-public void constantOutOfFormat(NumberLiteral literal) {
- // the literal is not in a correct format
- // this code is called on IntLiteral
- // example 000811 ...the 8 is uncorrect.
-
- if (literal instanceof IntLiteral) {
- char[] source = literal.source();
- try {
- final String Radix;
- final int radix;
- if ((source[1] == 'x') || (source[1] == 'X')) {
- radix = 16;
- Radix = "Hex"; //$NON-NLS-1$
- } else {
- radix = 8;
- Radix = "Octal"; //$NON-NLS-1$
- }
- //look for the first digit that is incorrect
- int place = -1;
- label : for (int i = radix == 8 ? 1 : 2; i < source.length; i++) {
- if (ScannerHelper.digit(source[i], radix) == -1) {
- place = i;
- break label;
- }
- }
- String[] arguments = new String[] {
- new String(literal.literalType(null).readableName()), // numeric literals do not need scope to reach type
- Radix + " " + new String(source) + " (digit " + new String(new char[] {source[place]}) + ")"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
- this.handle(
- IProblem.NumericValueOutOfRange,
- arguments,
- arguments,
- ProblemSeverities.Ignore,
- literal.sourceStart,
- literal.sourceEnd);
- return;
- } catch (IndexOutOfBoundsException ex) {
- // should never happen
- }
-
- // just in case .... use a predefined error..
- // we should never come here...(except if the code changes !)
- this.constantOutOfRange(literal, literal.literalType(null)); // numeric literals do not need scope to reach type
- }
-}
-public void constantOutOfRange(Literal literal, TypeBinding literalType) {
- String[] arguments = new String[] {new String(literalType.readableName()), new String(literal.source())};
- this.handle(
- IProblem.NumericValueOutOfRange,
- arguments,
- arguments,
- ProblemSeverities.Ignore,
- literal.sourceStart,
- literal.sourceEnd);
-}
-public void corruptedSignature(TypeBinding enclosingType, char[] signature, int position) {
- this.handle(
- IProblem.CorruptedSignature,
- new String[] { new String(enclosingType.readableName()), new String(signature), String.valueOf(position) },
- new String[] { new String(enclosingType.shortReadableName()), new String(signature), String.valueOf(position) },
- ProblemSeverities.Ignore,
- 0,
- 0);
-}
-public void deprecatedField(FieldBinding field, ASTNode location) {
- int severity = computeSeverity(IProblem.UsingDeprecatedField);
- if (severity == ProblemSeverities.Ignore) return;
- this.handle(
- IProblem.UsingDeprecatedField,
- new String[] {new String(field.declaringClass.readableName()), new String(field.name)},
- new String[] {new String(field.declaringClass.shortReadableName()), new String(field.name)},
- ProblemSeverities.Ignore,
- nodeSourceStart(field, location),
- nodeSourceEnd(field, location));
-}
-public void deprecatedMethod(MethodBinding method, ASTNode location) {
- boolean isConstructor = method.isConstructor();
- int severity = computeSeverity(isConstructor ? IProblem.UsingDeprecatedConstructor : IProblem.UsingDeprecatedMethod);
- if (severity == ProblemSeverities.Ignore) return;
- if (isConstructor) {
- this.handle(
- IProblem.UsingDeprecatedConstructor,
- new String[] {new String(method.declaringClass.readableName()), typesAsString(method.isVarargs(), method.parameters, false)},
- new String[] {new String(method.declaringClass.shortReadableName()), typesAsString(method.isVarargs(), method.parameters, true)},
- ProblemSeverities.Ignore,
- location.sourceStart,
- location.sourceEnd);
- } else {
- this.handle(
- IProblem.UsingDeprecatedMethod,
- new String[] {new String(method.declaringClass.readableName()), new String(method.selector), typesAsString(method.isVarargs(), method.parameters, false)},
- new String[] {new String(method.declaringClass.shortReadableName()), new String(method.selector), typesAsString(method.isVarargs(), method.parameters, true)},
- ProblemSeverities.Ignore,
- location.sourceStart,
- location.sourceEnd);
- }
-}
-public void deprecatedType(TypeBinding type, ASTNode location) {
- if (location == null) return; // 1G828DN - no type ref for synthetic arguments
- int severity = computeSeverity(IProblem.UsingDeprecatedType);
- if (severity == ProblemSeverities.Ignore) return;
- type = type.leafComponentType();
- this.handle(
- IProblem.UsingDeprecatedType,
- new String[] {new String(type.readableName())},
- new String[] {new String(type.shortReadableName())},
- ProblemSeverities.Ignore,
- location.sourceStart,
- nodeSourceEnd(null, location));
-}
-public void duplicateCase(CaseStatement caseStatement) {
- this.handle(
- IProblem.DuplicateCase,
- NoArgument,
- NoArgument,
- caseStatement.sourceStart,
- caseStatement.sourceEnd);
-}
-public void duplicateDefaultCase(ASTNode statement) {
- this.handle(
- IProblem.DuplicateDefaultCase,
- NoArgument,
- NoArgument,
- statement.sourceStart,
- statement.sourceEnd);
-}
-public void duplicateFieldInType(SourceTypeBinding type, FieldDeclaration fieldDecl) {
- this.handle(
- IProblem.DuplicateField,
- new String[] {new String(type.sourceName()), new String(fieldDecl.name)},
- new String[] {new String(type.shortReadableName()), new String(fieldDecl.name)},
- ProblemSeverities.Ignore,
- fieldDecl.sourceStart,
- fieldDecl.sourceEnd);
-}
-
-public void duplicateFieldInType(SourceTypeBinding type, InferredAttribute fieldDecl) {
- this.handle(
- IProblem.DuplicateField,
- new String[] {new String(type.sourceName()), new String(fieldDecl.name)},
- new String[] {new String(type.shortReadableName()), new String(fieldDecl.name)},
- ProblemSeverities.Ignore,
- fieldDecl.sourceStart,
- fieldDecl.sourceEnd);
-}
-public void duplicateMethodInType( Binding type, AbstractMethodDeclaration methodDecl) {
- MethodBinding method = methodDecl.binding;
-
- this.handle(
- IProblem.DuplicateMethod,
- new String[] {
- new String(methodDecl.getSafeName()),
- new String(method.declaringClass.readableName()),
- typesAsString(method.isVarargs(), method.parameters, false)},
- new String[] {
- new String(methodDecl.getSafeName()),
- new String(method.declaringClass.shortReadableName()),
- typesAsString(method.isVarargs(), method.parameters, true)},
- ProblemSeverities.Ignore,
- methodDecl.sourceStart,
- methodDecl.sourceEnd);
-
-}
-public void duplicateTypes(CompilationUnitDeclaration compUnitDecl, InferredType typeDecl) {
- String[] arguments = new String[] {new String(compUnitDecl.getFileName()), new String(typeDecl.getName())};
- this.referenceContext = compUnitDecl; // report the problem against the type not the entire compilation unit
- this.handle(
- IProblem.DuplicateTypes,
- arguments,
- arguments,
- ProblemSeverities.Ignore,
- typeDecl.sourceStart,
- typeDecl.sourceEnd,
- this.referenceContext,
- compUnitDecl.compilationResult);
-}
-public void emptyControlFlowStatement(int sourceStart, int sourceEnd) {
- this.handle(
- IProblem.EmptyControlFlowStatement,
- NoArgument,
- NoArgument,
- sourceStart,
- sourceEnd);
-}
-public void expressionShouldBeAVariable(Expression expression) {
- this.handle(
- IProblem.ExpressionShouldBeAVariable,
- NoArgument,
- NoArgument,
- expression.sourceStart,
- expression.sourceEnd);
-}
-public void fieldHiding(FieldDeclaration fieldDecl, Binding hiddenVariable) {
- FieldBinding field = fieldDecl.binding;
- boolean isLocal = hiddenVariable instanceof LocalVariableBinding;
- int severity = computeSeverity(isLocal ? IProblem.FieldHidingLocalVariable : IProblem.FieldHidingField);
- if (severity == ProblemSeverities.Ignore) return;
- if (isLocal) {
- this.handle(
- IProblem.FieldHidingLocalVariable,
- new String[] {new String(field.declaringClass.readableName()), new String(field.name) },
- new String[] {new String(field.declaringClass.shortReadableName()), new String(field.name) },
- ProblemSeverities.Ignore,
- nodeSourceStart(hiddenVariable, fieldDecl),
- nodeSourceEnd(hiddenVariable, fieldDecl));
- } else if (hiddenVariable instanceof FieldBinding) {
- FieldBinding hiddenField = (FieldBinding) hiddenVariable;
- this.handle(
- IProblem.FieldHidingField,
- new String[] {new String(field.declaringClass.readableName()), new String(field.name) , new String(hiddenField.declaringClass.readableName()) },
- new String[] {new String(field.declaringClass.shortReadableName()), new String(field.name) , new String(hiddenField.declaringClass.shortReadableName()) },
- ProblemSeverities.Ignore,
- nodeSourceStart(hiddenField, fieldDecl),
- nodeSourceEnd(hiddenField, fieldDecl));
- }
-}
-public void finallyMustCompleteNormally(Block finallyBlock) {
- this.handle(
- IProblem.FinallyMustCompleteNormally,
- NoArgument,
- NoArgument,
- finallyBlock.sourceStart,
- finallyBlock.sourceEnd);
-}
-public void forbiddenReference(FieldBinding field, ASTNode location,
- String messageTemplate, int problemId) {
- this.handle(
- problemId,
- new String[] { new String(field.readableName()) }, // distinct from msg arg for quickfix purpose
- new String[] {
- MessageFormat.format(messageTemplate,
- new String[]{
- new String(field.shortReadableName()),
- new String(field.declaringClass.shortReadableName())})},
- ProblemSeverities.Ignore,
- nodeSourceStart(field, location),
- nodeSourceEnd(field, location));
-}
-public void forbiddenReference(MethodBinding method, ASTNode location,
- String messageTemplate, int problemId) {
- if (method.isConstructor())
- this.handle(
- problemId,
- new String[] { new String(method.readableName()) }, // distinct from msg arg for quickfix purpose
- new String[] {
- MessageFormat.format(messageTemplate,
- new String[]{new String(method.shortReadableName())})},
- ProblemSeverities.Ignore,
- location.sourceStart,
- location.sourceEnd);
- else
- this.handle(
- problemId,
- new String[] { new String(method.readableName()) }, // distinct from msg arg for quickfix purpose
- new String[] {
- MessageFormat.format(messageTemplate,
- new String[]{
- new String(method.shortReadableName()),
- new String(method.declaringClass.shortReadableName())})},
- ProblemSeverities.Ignore,
- location.sourceStart,
- location.sourceEnd);
-}
-public void forbiddenReference(TypeBinding type, ASTNode location, String messageTemplate, int problemId) {
- if (location == null) return;
- int severity = computeSeverity(problemId);
- if (severity == ProblemSeverities.Ignore) return;
- // this problem has a message template extracted from the access restriction rule
- this.handle(
- problemId,
- new String[] { new String(type.readableName()) }, // distinct from msg arg for quickfix purpose
- new String[] { MessageFormat.format(messageTemplate, new String[]{ new String(type.shortReadableName())})},
- ProblemSeverities.Ignore,
- location.sourceStart,
- location.sourceEnd);
-}
-public void forwardReference(Reference reference, int indexInQualification, TypeBinding type) {
- this.handle(
- IProblem.ReferenceToForwardField,
- NoArgument,
- NoArgument,
- ProblemSeverities.Ignore,
- reference.sourceStart,
- reference.sourceEnd);
-}
-// use this private API when the compilation unit result can be found through the
-// reference context. Otherwise, use the other API taking a problem and a compilation result
-// as arguments
-private void handle(
- int problemId,
- String[] problemArguments,
- String[] messageArguments,
- int problemStartPosition,
- int problemEndPosition){
-
- this.handle(
- problemId,
- problemArguments,
- messageArguments,
- problemStartPosition,
- problemEndPosition,
- this.referenceContext,
- this.referenceContext == null ? null : this.referenceContext.compilationResult());
- this.referenceContext = null;
-}
-// use this private API when the compilation unit result cannot be found through the
-// reference context.
-private void handle(
- int problemId,
- String[] problemArguments,
- String[] messageArguments,
- int problemStartPosition,
- int problemEndPosition,
- CompilationResult unitResult){
-
- this.handle(
- problemId,
- problemArguments,
- messageArguments,
- problemStartPosition,
- problemEndPosition,
- this.referenceContext,
- unitResult);
- this.referenceContext = null;
-}
-// use this private API when the compilation unit result can be found through the
-// reference context. Otherwise, use the other API taking a problem and a compilation result
-// as arguments
-private void handle(
- int problemId,
- String[] problemArguments,
- String[] messageArguments,
- int severity,
- int problemStartPosition,
- int problemEndPosition){
-
- this.handle(
- problemId,
- problemArguments,
- messageArguments,
- severity,
- problemStartPosition,
- problemEndPosition,
- this.referenceContext,
- this.referenceContext == null ? null : this.referenceContext.compilationResult());
- this.referenceContext = null;
-}
-public void hierarchyCircularity(SourceTypeBinding sourceType, ReferenceBinding superType, TypeReference reference) {
- int start = 0;
- int end = 0;
-
- if (reference == null) { // can only happen when java.lang.Object is busted
- start = sourceType.sourceStart();
- end = sourceType.sourceEnd();
- } else {
- start = reference.sourceStart;
- end = reference.sourceEnd;
- }
-
- if (sourceType == superType)
- this.handle(
- IProblem.HierarchyCircularitySelfReference,
- new String[] {new String(sourceType.readableName()) },
- new String[] {new String(sourceType.shortReadableName()) },
- start,
- end);
- else
- this.handle(
- IProblem.HierarchyCircularity,
- new String[] {new String(sourceType.readableName()), new String(superType.readableName())},
- new String[] {new String(sourceType.shortReadableName()), new String(superType.shortReadableName())},
- start,
- end);
-}
-
-public void hierarchyHasProblems(SourceTypeBinding type) {
- String[] arguments = new String[] {new String(type.sourceName())};
- this.handle(
- IProblem.HierarchyHasProblems,
- arguments,
- arguments,
- ProblemSeverities.Ignore,
- type.sourceStart(),
- type.sourceEnd());
-}
-public void incompatibleReturnType(MethodBinding currentMethod, MethodBinding inheritedMethod) {
- StringBuffer methodSignature = new StringBuffer();
- methodSignature
- .append(inheritedMethod.declaringClass.readableName())
- .append('.')
- .append(inheritedMethod.readableName());
-
- StringBuffer shortSignature = new StringBuffer();
- shortSignature
- .append(inheritedMethod.declaringClass.shortReadableName())
- .append('.')
- .append(inheritedMethod.shortReadableName());
-
- int id;
- final ReferenceBinding declaringClass = currentMethod.declaringClass;
-
- id = IProblem.IncompatibleReturnType;
-
- AbstractMethodDeclaration method = currentMethod.sourceMethod();
- int sourceStart = 0;
- int sourceEnd = 0;
- if (method == null) {
- if (declaringClass instanceof SourceTypeBinding && ((SourceTypeBinding) declaringClass).classScope != null) {
- SourceTypeBinding sourceTypeBinding = (SourceTypeBinding) declaringClass;
- sourceStart = sourceTypeBinding.sourceStart();
- sourceEnd = sourceTypeBinding.sourceEnd();
- }
- } else if (method.isConstructor() || ((MethodDeclaration) method).returnType==null){
- sourceStart = method.sourceStart;
- sourceEnd = method.sourceEnd;
- } else {
- TypeReference returnType = ((MethodDeclaration) method).returnType;
- sourceStart = returnType.sourceStart;
- sourceEnd = returnType.sourceEnd;
- }
- this.handle(
- id,
- new String[] {methodSignature.toString()},
- new String[] {shortSignature.toString()},
- ProblemSeverities.Ignore,
- sourceStart,
- sourceEnd);
-}
-public void indirectAccessToStaticField(ASTNode location, FieldBinding field){
- int severity = computeSeverity(IProblem.IndirectAccessToStaticField);
- if (severity == ProblemSeverities.Ignore) return;
- this.handle(
- IProblem.IndirectAccessToStaticField,
- new String[] {new String(field.declaringClass.readableName()), new String(field.name)},
- new String[] {new String(field.declaringClass.shortReadableName()), new String(field.name)},
- ProblemSeverities.Ignore,
- nodeSourceStart(field, location),
- nodeSourceEnd(field, location));
-}
-public void indirectAccessToStaticMethod(ASTNode location, MethodBinding method) {
- int severity = computeSeverity(IProblem.IndirectAccessToStaticMethod);
- if (severity == ProblemSeverities.Ignore) return;
- this.handle(
- IProblem.IndirectAccessToStaticMethod,
- new String[] {new String(method.declaringClass.readableName()), new String(method.selector), typesAsString(method.isVarargs(), method.parameters, false)},
- new String[] {new String(method.declaringClass.shortReadableName()), new String(method.selector), typesAsString(method.isVarargs(), method.parameters, true)},
- ProblemSeverities.Ignore,
- location.sourceStart,
- location.sourceEnd);
-}
-public void inheritedMethodsHaveIncompatibleReturnTypes(SourceTypeBinding type, MethodBinding[] inheritedMethods, int length) {
- StringBuffer methodSignatures = new StringBuffer();
- StringBuffer shortSignatures = new StringBuffer();
- for (int i = length; --i >= 0;) {
- methodSignatures
- .append(inheritedMethods[i].declaringClass.readableName())
- .append('.')
- .append(inheritedMethods[i].readableName());
- shortSignatures
- .append(inheritedMethods[i].declaringClass.shortReadableName())
- .append('.')
- .append(inheritedMethods[i].shortReadableName());
- if (i != 0){
- methodSignatures.append(", "); //$NON-NLS-1$
- shortSignatures.append(", "); //$NON-NLS-1$
- }
- }
-
- this.handle(
- // Return type is incompatible with %1
- // 9.4.2 - The return type from the method is incompatible with the declaration.
- IProblem.IncompatibleReturnType,
- new String[] {methodSignatures.toString()},
- new String[] {shortSignatures.toString()},
- ProblemSeverities.Ignore,
- type.sourceStart(),
- type.sourceEnd());
-}
-public void invalidBreak(ASTNode location) {
- this.handle(
- IProblem.InvalidBreak,
- NoArgument,
- NoArgument,
- location.sourceStart,
- location.sourceEnd);
-}
-public void invalidConstructor(Statement statement, MethodBinding targetConstructor) {
- boolean insideDefaultConstructor =
- (this.referenceContext instanceof ConstructorDeclaration)
- && ((ConstructorDeclaration)this.referenceContext).isDefaultConstructor();
- boolean insideImplicitConstructorCall =
- (statement instanceof ExplicitConstructorCall)
- && (((ExplicitConstructorCall) statement).accessMode == ExplicitConstructorCall.ImplicitSuper);
-
- int sourceStart = statement.sourceStart;
- int sourceEnd = statement.sourceEnd;
-
- int id = IProblem.UndefinedConstructor; //default...
- MethodBinding shownConstructor = targetConstructor;
- switch (targetConstructor.problemId()) {
- case ProblemReasons.NotFound :
- if (insideDefaultConstructor){
- id = IProblem.UndefinedConstructorInDefaultConstructor;
- } else if (insideImplicitConstructorCall){
- id = IProblem.UndefinedConstructorInImplicitConstructorCall;
- } else {
- id = IProblem.UndefinedConstructor;
- }
- break;
- case ProblemReasons.NotVisible :
- if (insideDefaultConstructor){
- id = IProblem.NotVisibleConstructorInDefaultConstructor;
- } else if (insideImplicitConstructorCall){
- id = IProblem.NotVisibleConstructorInImplicitConstructorCall;
- } else {
- id = IProblem.NotVisibleConstructor;
- }
- ProblemMethodBinding problemConstructor = (ProblemMethodBinding) targetConstructor;
- if (problemConstructor.closestMatch != null) {
- shownConstructor = problemConstructor.closestMatch.original();
- }
- break;
- case ProblemReasons.Ambiguous :
- if (insideDefaultConstructor){
- id = IProblem.AmbiguousConstructorInDefaultConstructor;
- } else if (insideImplicitConstructorCall){
- id = IProblem.AmbiguousConstructorInImplicitConstructorCall;
- } else {
- id = IProblem.AmbiguousConstructor;
- }
- break;
-
- case ProblemReasons.NoError : // 0
- default :
- needImplementation(); // want to fail to see why we were here...
- break;
- }
-
- this.handle(
- id,
- new String[] {new String(targetConstructor.declaringClass.readableName()), typesAsString(shownConstructor.isVarargs(), shownConstructor.parameters, false)},
- new String[] {new String(targetConstructor.declaringClass.shortReadableName()), typesAsString(shownConstructor.isVarargs(), shownConstructor.parameters, true)},
- ProblemSeverities.Ignore,
- sourceStart,
- sourceEnd);
-}
-public void invalidContinue(ASTNode location) {
- this.handle(
- IProblem.InvalidContinue,
- NoArgument,
- NoArgument,
- location.sourceStart,
- location.sourceEnd);
-}
-public void invalidField(FieldReference fieldRef, TypeBinding searchedType) {
- if(isRecoveredName(fieldRef.token)) return;
-
- int id = IProblem.UndefinedField;
- FieldBinding field = fieldRef.binding;
- switch (field.problemId()) {
- case ProblemReasons.NotFound :
- id = IProblem.UndefinedField;
-/* also need to check that the searchedType is the receiver type
- if (searchedType.isHierarchyInconsistent())
- severity = SecondaryError;
-*/
- break;
- case ProblemReasons.NotVisible :
- this.handle(
- IProblem.NotVisibleField,
- new String[] {new String(fieldRef.token), new String(field.declaringClass.readableName())},
- new String[] {new String(fieldRef.token), new String(field.declaringClass.shortReadableName())},
- ProblemSeverities.Ignore,
- nodeSourceStart(field, fieldRef),
- nodeSourceEnd(field, fieldRef));
- return;
- case ProblemReasons.Ambiguous :
- id = IProblem.AmbiguousField;
- break;
- case ProblemReasons.NonStaticReferenceInStaticContext :
- id = IProblem.NonStaticFieldFromStaticInvocation;
- break;
- case ProblemReasons.NonStaticReferenceInConstructorInvocation :
- id = IProblem.InstanceFieldDuringConstructorInvocation;
- break;
- case ProblemReasons.InheritedNameHidesEnclosingName :
- id = IProblem.InheritedFieldHidesEnclosingName;
- break;
- case ProblemReasons.ReceiverTypeNotVisible :
- this.handle(
- IProblem.NotVisibleType, // cannot occur in javadoc comments
- new String[] {new String(searchedType.leafComponentType().readableName())},
- new String[] {new String(searchedType.leafComponentType().shortReadableName())},
- ProblemSeverities.Ignore,
- fieldRef.receiver.sourceStart,
- fieldRef.receiver.sourceEnd);
- return;
-
- case ProblemReasons.NoError : // 0
- default :
- needImplementation(); // want to fail to see why we were here...
- break;
- }
-
- String[] arguments = new String[] {new String(field.readableName())};
- this.handle(
- id,
- arguments,
- arguments,
- ProblemSeverities.Ignore,
- nodeSourceStart(field, fieldRef),
- nodeSourceEnd(field, fieldRef));
-}
-public void invalidField(NameReference nameRef, FieldBinding field) {
- if (nameRef instanceof QualifiedNameReference) {
- QualifiedNameReference ref = (QualifiedNameReference) nameRef;
- if (isRecoveredName(ref.tokens)) return;
- } else {
- SingleNameReference ref = (SingleNameReference) nameRef;
- if (isRecoveredName(ref.token)) return;
- }
- int id = IProblem.UndefinedField;
- switch (field.problemId()) {
- case ProblemReasons.NotFound :
- id = IProblem.UndefinedField;
- break;
- case ProblemReasons.NotVisible :
- char[] name = field.readableName();
- name = CharOperation.lastSegment(name, '.');
- this.handle(
- IProblem.NotVisibleField,
- new String[] {new String(name), new String(field.declaringClass.readableName())},
- new String[] {new String(name), new String(field.declaringClass.shortReadableName())},
- ProblemSeverities.Ignore,
- nodeSourceStart(field, nameRef),
- nodeSourceEnd(field, nameRef));
- return;
- case ProblemReasons.Ambiguous :
- id = IProblem.AmbiguousField;
- break;
- case ProblemReasons.NonStaticReferenceInStaticContext :
- id = IProblem.NonStaticFieldFromStaticInvocation;
- break;
- case ProblemReasons.NonStaticReferenceInConstructorInvocation :
- id = IProblem.InstanceFieldDuringConstructorInvocation;
- break;
- case ProblemReasons.InheritedNameHidesEnclosingName :
- id = IProblem.InheritedFieldHidesEnclosingName;
- break;
- case ProblemReasons.ReceiverTypeNotVisible :
- this.handle(
- IProblem.NotVisibleType,
- new String[] {new String(field.declaringClass.leafComponentType().readableName())},
- new String[] {new String(field.declaringClass.leafComponentType().shortReadableName())},
- ProblemSeverities.Ignore,
- nameRef.sourceStart,
- nameRef.sourceEnd);
- return;
- case ProblemReasons.NoError : // 0
- default :
- needImplementation(); // want to fail to see why we were here...
- break;
- }
- String[] arguments = new String[] {new String(field.readableName())};
- this.handle(
- id,
- arguments,
- arguments,
- ProblemSeverities.Ignore,
- nameRef.sourceStart,
- nameRef.sourceEnd);
-}
-public void invalidField(QualifiedNameReference nameRef, FieldBinding field, int index, TypeBinding searchedType) {
- //the resolution of the index-th field of qname failed
- //qname.otherBindings[index] is the binding that has produced the error
-
- //The different targetted errors should be :
- //UndefinedField
- //NotVisibleField
- //AmbiguousField
-
- if (isRecoveredName(nameRef.tokens)) return;
-
- if (searchedType.isBaseType()) {
- this.handle(
- IProblem.NoFieldOnBaseType,
- new String[] {
- new String(searchedType.readableName()),
- CharOperation.toString(CharOperation.subarray(nameRef.tokens, 0, index)),
- new String(nameRef.tokens[index])},
- new String[] {
- new String(searchedType.sourceName()),
- CharOperation.toString(CharOperation.subarray(nameRef.tokens, 0, index)),
- new String(nameRef.tokens[index])},
- ProblemSeverities.Ignore,
- nameRef.sourceStart,
- (int) nameRef.sourcePositions[index]);
- return;
- }
-
- int id = IProblem.UndefinedField;
- switch (field.problemId()) {
- case ProblemReasons.NotFound :
- id = IProblem.UndefinedField;
-/* also need to check that the searchedType is the receiver type
- if (searchedType.isHierarchyInconsistent())
- severity = SecondaryError;
-*/
- break;
- case ProblemReasons.NotVisible :
- String fieldName = new String(nameRef.tokens[index]);
- this.handle(
- IProblem.NotVisibleField,
- new String[] {fieldName, new String(field.declaringClass.readableName())},
- new String[] {fieldName, new String(field.declaringClass.shortReadableName())},
- ProblemSeverities.Ignore,
- nodeSourceStart(field, nameRef),
- nodeSourceEnd(field, nameRef));
- return;
- case ProblemReasons.Ambiguous :
- id = IProblem.AmbiguousField;
- break;
- case ProblemReasons.NonStaticReferenceInStaticContext :
- id = IProblem.NonStaticFieldFromStaticInvocation;
- break;
- case ProblemReasons.NonStaticReferenceInConstructorInvocation :
- id = IProblem.InstanceFieldDuringConstructorInvocation;
- break;
- case ProblemReasons.InheritedNameHidesEnclosingName :
- id = IProblem.InheritedFieldHidesEnclosingName;
- break;
- case ProblemReasons.ReceiverTypeNotVisible :
- this.handle(
- IProblem.NotVisibleType,
- new String[] {new String(searchedType.leafComponentType().readableName())},
- new String[] {new String(searchedType.leafComponentType().shortReadableName())},
- ProblemSeverities.Ignore,
- nameRef.sourceStart,
- nameRef.sourceEnd);
- return;
- case ProblemReasons.NoError : // 0
- default :
- needImplementation(); // want to fail to see why we were here...
- break;
- }
- String[] arguments = new String[] {CharOperation.toString(CharOperation.subarray(nameRef.tokens, 0, index + 1))};
- this.handle(
- id,
- arguments,
- arguments,
- ProblemSeverities.Ignore,
- nameRef.sourceStart,
- (int) nameRef.sourcePositions[index]);
-}
-public void invalidMethod(MessageSend messageSend, MethodBinding method) {
- if (isRecoveredName(messageSend.selector)) return;
-
- boolean isFunction = method.declaringClass==null;
- int id = isFunction? IProblem.UndefinedFunction : IProblem.UndefinedMethod; //default...
- MethodBinding shownMethod = method;
-
- switch (method.problemId()) {
- case ProblemReasons.NotFound :
- id = isFunction? IProblem.UndefinedFunction : IProblem.UndefinedMethod;
- ProblemMethodBinding problemMethod = (ProblemMethodBinding) method;
- if (problemMethod.closestMatch != null) {
- shownMethod = problemMethod.closestMatch;
- String closestParameterTypeNames = typesAsString(shownMethod.isVarargs(), shownMethod.parameters, false);
- String parameterTypeNames = typesAsString(false, problemMethod.parameters, false);
- String closestParameterTypeShortNames = typesAsString(shownMethod.isVarargs(), shownMethod.parameters, true);
- String parameterTypeShortNames = typesAsString(false, problemMethod.parameters, true);
- this.handle(
- IProblem.ParameterMismatch,
- new String[] {
- new String(shownMethod.declaringClass.readableName()),
- new String(shownMethod.selector),
- closestParameterTypeNames,
- parameterTypeNames
- },
- new String[] {
- new String(shownMethod.declaringClass.shortReadableName()),
- new String(shownMethod.selector),
- closestParameterTypeShortNames,
- parameterTypeShortNames
- },
- ProblemSeverities.Ignore,
- (int) (messageSend.nameSourcePosition >>> 32),
- (int) messageSend.nameSourcePosition);
- return;
- }
- break;
- case ProblemReasons.NotVisible :
- id = IProblem.NotVisibleMethod;
- problemMethod = (ProblemMethodBinding) method;
- if (problemMethod.closestMatch != null) {
- shownMethod = problemMethod.closestMatch.original();
- }
- break;
- case ProblemReasons.Ambiguous :
- id = IProblem.AmbiguousMethod;
- break;
- case ProblemReasons.NotAFunction :
- id = IProblem.NotAFunction;
- break;
- case ProblemReasons.InheritedNameHidesEnclosingName :
- id = IProblem.InheritedMethodHidesEnclosingName;
- break;
- case ProblemReasons.NonStaticReferenceInConstructorInvocation :
- id = IProblem.InstanceMethodDuringConstructorInvocation;
- break;
- case ProblemReasons.NonStaticReferenceInStaticContext :
- id = IProblem.StaticMethodRequested;
- break;
- case ProblemReasons.ReceiverTypeNotVisible :
- this.handle(
- IProblem.NotVisibleType, // cannot occur in javadoc comments
- new String[] {new String(method.declaringClass.leafComponentType().readableName())},
- new String[] {new String(method.declaringClass.leafComponentType().shortReadableName())},
- ProblemSeverities.Ignore,
- messageSend.receiver.sourceStart,
- messageSend.receiver.sourceEnd);
- return;
- case ProblemReasons.NoError : // 0
- default :
- needImplementation(); // want to fail to see why we were here...
- break;
- }
-
- String shortName=""; //$NON-NLS-1$
- String readableName=""; //$NON-NLS-1$
- String methodName=(shownMethod.selector!=null)? new String(shownMethod.selector):""; //$NON-NLS-1$
- if (method.declaringClass!=null)
- {
- shortName= readableName=new String(method.declaringClass.readableName());
-
- }
- this.handle(
- id,
- new String[] {
- readableName,
- shortName, typesAsString(shownMethod.isVarargs(), shownMethod.parameters, false)},
- new String[] {
- shortName,
- methodName, typesAsString(shownMethod.isVarargs(), shownMethod.parameters, true)},
- ProblemSeverities.Ignore,
- (int) (messageSend.nameSourcePosition >>> 32),
- (int) messageSend.nameSourcePosition);
-}
-public void wrongNumberOfArguments(MessageSend functionCall, MethodBinding binding) {
- String functionName = new String(functionCall.selector);
- int actualArguments=(functionCall.arguments!=null) ? functionCall.arguments.length : 0;
- String actualNumber=String.valueOf(actualArguments);
- String expectingNumber=String.valueOf(binding.parameters.length);
-
- this.handle(
- IProblem.WrongNumberOfArguments,
- new String[] {
- functionName,expectingNumber,actualNumber}, //$NON-NLS-1$
- new String[] {
- functionName,expectingNumber,actualNumber}, //$NON-NLS-1$
- ProblemSeverities.Ignore,
- functionCall.sourceStart,
- functionCall.sourceEnd);
-}
-
-public void wrongNumberOfArguments(AllocationExpression allocationExpression, MethodBinding binding) {
- char[] typeName = Util.getTypeName(allocationExpression.member);
- String functionName = typeName!=null ? new String(typeName) : "";
- int actualArguments=(allocationExpression.arguments!=null) ? allocationExpression.arguments.length : 0;
- String actualNumber=String.valueOf(actualArguments);
- String expectingNumber=String.valueOf(binding.parameters.length);
-
- this.handle(
- IProblem.WrongNumberOfArguments,
- new String[] {
- functionName,expectingNumber,actualNumber}, //$NON-NLS-1$
- new String[] {
- functionName,expectingNumber,actualNumber}, //$NON-NLS-1$
- ProblemSeverities.Ignore,
- allocationExpression.sourceStart,
- allocationExpression.sourceEnd);
-}
-
-
-public void invalidOperator(BinaryExpression expression, TypeBinding leftType, TypeBinding rightType) {
- String leftName = new String(leftType.readableName());
- String rightName = new String(rightType.readableName());
- String leftShortName = new String(leftType.shortReadableName());
- String rightShortName = new String(rightType.shortReadableName());
- if (leftShortName.equals(rightShortName)){
- leftShortName = leftName;
- rightShortName = rightName;
- }
- this.handle(
- IProblem.InvalidOperator,
- new String[] {
- expression.operatorToString(),
- leftName + ", " + rightName}, //$NON-NLS-1$
- new String[] {
- expression.operatorToString(),
- leftShortName + ", " + rightShortName}, //$NON-NLS-1$
- ProblemSeverities.Ignore,
- expression.sourceStart,
- expression.sourceEnd);
-}
-public void invalidOperator(CompoundAssignment assign, TypeBinding leftType, TypeBinding rightType) {
- String leftName = new String(leftType.readableName());
- String rightName = new String(rightType.readableName());
- String leftShortName = new String(leftType.shortReadableName());
- String rightShortName = new String(rightType.shortReadableName());
- if (leftShortName.equals(rightShortName)){
- leftShortName = leftName;
- rightShortName = rightName;
- }
- this.handle(
- IProblem.InvalidOperator,
- new String[] {
- assign.operatorToString(),
- leftName + ", " + rightName}, //$NON-NLS-1$
- new String[] {
- assign.operatorToString(),
- leftShortName + ", " + rightShortName}, //$NON-NLS-1$
- ProblemSeverities.Ignore,
- assign.sourceStart,
- assign.sourceEnd);
-}
-public void invalidOperator(UnaryExpression expression, TypeBinding type) {
- this.handle(
- IProblem.InvalidOperator,
- new String[] {expression.operatorToString(), new String(type.readableName())},
- new String[] {expression.operatorToString(), new String(type.shortReadableName())},
- ProblemSeverities.Ignore,
- expression.sourceStart,
- expression.sourceEnd);
-}
-public void invalidType(ASTNode location, TypeBinding type) {
- if (type instanceof ReferenceBinding) {
- if (isRecoveredName(((ReferenceBinding)type).compoundName)) return;
- }
- else if (type instanceof ArrayBinding) {
- TypeBinding leafType = ((ArrayBinding)type).leafComponentType;
- if (leafType instanceof ReferenceBinding) {
- if (isRecoveredName(((ReferenceBinding)leafType).compoundName)) return;
- }
- }
-
- int id = IProblem.UndefinedType; // default
- switch (type.problemId()) {
- case ProblemReasons.NotFound :
- id = IProblem.UndefinedType;
- break;
- case ProblemReasons.NotVisible :
- id = IProblem.NotVisibleType;
- break;
- case ProblemReasons.Ambiguous :
- id = IProblem.AmbiguousType;
- break;
- case ProblemReasons.InternalNameProvided :
- id = IProblem.InternalTypeNameProvided;
- break;
- case ProblemReasons.InheritedNameHidesEnclosingName :
- id = IProblem.InheritedTypeHidesEnclosingName;
- break;
- case ProblemReasons.NoError : // 0
- default :
- needImplementation(); // want to fail to see why we were here...
- break;
- }
-
- int end = location.sourceEnd;
- if (location instanceof QualifiedNameReference) {
- QualifiedNameReference ref = (QualifiedNameReference) location;
- if (isRecoveredName(ref.tokens)) return;
- if (ref.indexOfFirstFieldBinding >= 1)
- end = (int) ref.sourcePositions[ref.indexOfFirstFieldBinding - 1];
- } else if (location instanceof ArrayQualifiedTypeReference) {
- ArrayQualifiedTypeReference arrayQualifiedTypeReference = (ArrayQualifiedTypeReference) location;
- if (isRecoveredName(arrayQualifiedTypeReference.tokens)) return;
- long[] positions = arrayQualifiedTypeReference.sourcePositions;
- end = (int) positions[positions.length - 1];
- } else if (location instanceof QualifiedTypeReference) {
- QualifiedTypeReference ref = (QualifiedTypeReference) location;
- if (isRecoveredName(ref.tokens)) return;
- if (type instanceof ReferenceBinding) {
- char[][] name = ((ReferenceBinding) type).compoundName;
- if (name.length <= ref.sourcePositions.length)
- end = (int) ref.sourcePositions[name.length - 1];
- }
- } else if (location instanceof ImportReference) {
- ImportReference ref = (ImportReference) location;
- if (isRecoveredName(ref.tokens)) return;
- if (type instanceof ReferenceBinding) {
- char[][] name = ((ReferenceBinding) type).compoundName;
- end = (int) ref.sourcePositions[name.length - 1];
- }
- } else if (location instanceof ArrayTypeReference) {
- ArrayTypeReference arrayTypeReference = (ArrayTypeReference) location;
- if (isRecoveredName(arrayTypeReference.token)) return;
- end = arrayTypeReference.originalSourceEnd;
- }
- this.handle(
- id,
- new String[] {new String(type.leafComponentType().readableName()) },
- new String[] {new String(type.leafComponentType().shortReadableName())},
- ProblemSeverities.Ignore,
- location.sourceStart,
- end);
-}
-public void invalidUnaryExpression(Expression expression) {
- this.handle(
- IProblem.InvalidUnaryExpression,
- NoArgument,
- NoArgument,
- expression.sourceStart,
- expression.sourceEnd);
-}
-public void invalidValueForGetterSetter(Expression expression, boolean isSetter) {
- int problemID;
- if (isSetter) {
- problemID = IProblem.InvalidValueForSetter;
- } else {
- problemID = IProblem.InvalidValueForGetter;
- }
- this.handle(
- problemID,
- NoArgument,
- NoArgument,
- expression.sourceStart,
- expression.sourceEnd);
-}
-private boolean isIdentifier(int token) {
- return token == TerminalTokens.TokenNameIdentifier;
-}
-private boolean isKeyword(int token) {
- switch(token) {
- case TerminalTokens.TokenNameabstract:
- case TerminalTokens.TokenNamebyte:
- case TerminalTokens.TokenNamebreak:
- case TerminalTokens.TokenNameboolean:
- case TerminalTokens.TokenNamecase:
- case TerminalTokens.TokenNamechar:
- case TerminalTokens.TokenNamecatch:
- case TerminalTokens.TokenNameclass:
- case TerminalTokens.TokenNamecontinue:
- case TerminalTokens.TokenNamedo:
- case TerminalTokens.TokenNamedouble:
- case TerminalTokens.TokenNamedefault:
- case TerminalTokens.TokenNameelse:
- case TerminalTokens.TokenNameextends:
- case TerminalTokens.TokenNamefor:
- case TerminalTokens.TokenNamefinal:
- case TerminalTokens.TokenNamefloat:
- case TerminalTokens.TokenNamefalse:
- case TerminalTokens.TokenNamefinally:
- case TerminalTokens.TokenNameif:
- case TerminalTokens.TokenNameint:
- case TerminalTokens.TokenNameimport:
- case TerminalTokens.TokenNameinterface:
- case TerminalTokens.TokenNameimplements:
- case TerminalTokens.TokenNameinstanceof:
- case TerminalTokens.TokenNamelong:
- case TerminalTokens.TokenNamenew:
- case TerminalTokens.TokenNamenull:
- case TerminalTokens.TokenNamenative:
- case TerminalTokens.TokenNamepublic:
- case TerminalTokens.TokenNamepackage:
- case TerminalTokens.TokenNameprivate:
- case TerminalTokens.TokenNameprotected:
- case TerminalTokens.TokenNamereturn:
- case TerminalTokens.TokenNameshort:
- case TerminalTokens.TokenNamesuper:
- case TerminalTokens.TokenNamestatic:
- case TerminalTokens.TokenNameswitch:
- case TerminalTokens.TokenNamesynchronized:
- case TerminalTokens.TokenNametry:
- case TerminalTokens.TokenNamethis:
- case TerminalTokens.TokenNametrue:
- case TerminalTokens.TokenNamethrow:
- case TerminalTokens.TokenNamethrows:
- case TerminalTokens.TokenNametransient:
- case TerminalTokens.TokenNamevoid:
- case TerminalTokens.TokenNamevolatile:
- case TerminalTokens.TokenNamewhile:
- case TerminalTokens.TokenNamedelete :
- case TerminalTokens.TokenNamedebugger :
- case TerminalTokens.TokenNameexport :
- case TerminalTokens.TokenNamefunction :
- case TerminalTokens.TokenNamein :
-// case TerminalTokens.TokenNameinfinity :
- case TerminalTokens.TokenNameundefined :
- case TerminalTokens.TokenNamewith :
- return true;
- default:
- return false;
- }
-}
-private boolean isLiteral(int token) {
- switch(token) {
- case TerminalTokens.TokenNameIntegerLiteral:
- case TerminalTokens.TokenNameLongLiteral:
- case TerminalTokens.TokenNameFloatingPointLiteral:
- case TerminalTokens.TokenNameDoubleLiteral:
- case TerminalTokens.TokenNameStringLiteral:
- case TerminalTokens.TokenNameCharacterLiteral:
- return true;
- default:
- return false;
- }
-}
-private boolean isRecoveredName(char[] simpleName) {
- return simpleName == RecoveryScanner.FAKE_IDENTIFIER;
-}
-private boolean isRecoveredName(char[][] qualifiedName) {
- if(qualifiedName == null) return false;
-
- for (int i = 0; i < qualifiedName.length; i++) {
- if(qualifiedName[i] == RecoveryScanner.FAKE_IDENTIFIER) return true;
- }
-
- return false;
-}
-
-public void javadocDeprecatedField(FieldBinding field, ASTNode location, int modifiers) {
- int severity = computeSeverity(IProblem.JavadocUsingDeprecatedField);
- if (severity == ProblemSeverities.Ignore) return;
- if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, modifiers)) {
- this.handle(
- IProblem.JavadocUsingDeprecatedField,
- new String[] {new String(field.declaringClass.readableName()), new String(field.name)},
- new String[] {new String(field.declaringClass.shortReadableName()), new String(field.name)},
- ProblemSeverities.Ignore,
- nodeSourceStart(field, location),
- nodeSourceEnd(field, location));
- }
-}
-
-public void javadocDeprecatedMethod(MethodBinding method, ASTNode location, int modifiers) {
- boolean isConstructor = method.isConstructor();
- int severity = computeSeverity(isConstructor ? IProblem.JavadocUsingDeprecatedConstructor : IProblem.JavadocUsingDeprecatedMethod);
- if (severity == ProblemSeverities.Ignore) return;
- if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, modifiers)) {
- if (isConstructor) {
- this.handle(
- IProblem.JavadocUsingDeprecatedConstructor,
- new String[] {new String(method.declaringClass.readableName()), typesAsString(method.isVarargs(), method.parameters, false)},
- new String[] {new String(method.declaringClass.shortReadableName()), typesAsString(method.isVarargs(), method.parameters, true)},
- ProblemSeverities.Ignore,
- location.sourceStart,
- location.sourceEnd);
- } else {
- this.handle(
- IProblem.JavadocUsingDeprecatedMethod,
- new String[] {new String(method.declaringClass.readableName()), new String(method.selector), typesAsString(method.isVarargs(), method.parameters, false)},
- new String[] {new String(method.declaringClass.shortReadableName()), new String(method.selector), typesAsString(method.isVarargs(), method.parameters, true)},
- ProblemSeverities.Ignore,
- location.sourceStart,
- location.sourceEnd);
- }
- }
-}
-public void javadocDeprecatedType(TypeBinding type, ASTNode location, int modifiers) {
- if (location == null) return; // 1G828DN - no type ref for synthetic arguments
- int severity = computeSeverity(IProblem.JavadocUsingDeprecatedType);
- if (severity == ProblemSeverities.Ignore) return;
- if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, modifiers)) {
- if (type.isMemberType() && type instanceof ReferenceBinding && !javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, ((ReferenceBinding)type).modifiers)) {
- this.handle(IProblem.JavadocHiddenReference, NoArgument, NoArgument, location.sourceStart, location.sourceEnd);
- } else {
- this.handle(
- IProblem.JavadocUsingDeprecatedType,
- new String[] {new String(type.readableName())},
- new String[] {new String(type.shortReadableName())},
- ProblemSeverities.Ignore,
- location.sourceStart,
- location.sourceEnd);
- }
- }
-}
-public void javadocDuplicatedParamTag(char[] token, int sourceStart, int sourceEnd, int modifiers) {
- int severity = computeSeverity(IProblem.JavadocDuplicateParamName);
- if (severity == ProblemSeverities.Ignore) return;
- if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, modifiers)) {
- String[] arguments = new String[] {String.valueOf(token)};
- this.handle(
- IProblem.JavadocDuplicateParamName,
- arguments,
- arguments,
- severity,
- sourceStart,
- sourceEnd);
- }
-}
-public void javadocDuplicatedReturnTag(int sourceStart, int sourceEnd){
- this.handle(IProblem.JavadocDuplicateReturnTag, NoArgument, NoArgument, sourceStart, sourceEnd);
-}
-public void javadocEmptyReturnTag(int sourceStart, int sourceEnd, int modifiers) {
- int severity = computeSeverity(IProblem.JavadocEmptyReturnTag);
- if (severity == ProblemSeverities.Ignore) return;
- if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, modifiers)) {
- this.handle(IProblem.JavadocEmptyReturnTag, NoArgument, NoArgument, sourceStart, sourceEnd);
- }
-}
-public void javadocHiddenReference(int sourceStart, int sourceEnd, Scope scope, int modifiers) {
- Scope currentScope = scope;
- while (currentScope.parent.kind != Scope.COMPILATION_UNIT_SCOPE ) {
- if (!javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, currentScope.getDeclarationModifiers())) {
- return;
- }
- currentScope = currentScope.parent;
- }
- String[] arguments = new String[] { this.options.getVisibilityString(this.options.reportInvalidJavadocTagsVisibility), this.options.getVisibilityString(modifiers) };
- this.handle(IProblem.JavadocHiddenReference, arguments, arguments, ProblemSeverities.Ignore, sourceStart, sourceEnd);
-}
-public void javadocInvalidConstructor(Statement statement, MethodBinding targetConstructor, int modifiers) {
-
- if (!javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, modifiers)) return;
- int id = IProblem.JavadocUndefinedConstructor; //default...
- switch (targetConstructor.problemId()) {
- case ProblemReasons.NotFound :
- id = IProblem.JavadocUndefinedConstructor;
- break;
- case ProblemReasons.NotVisible :
- id = IProblem.JavadocNotVisibleConstructor;
- break;
- case ProblemReasons.Ambiguous :
- id = IProblem.JavadocAmbiguousConstructor;
- break;
- case ProblemReasons.NoError : // 0
- default :
- needImplementation(); // want to fail to see why we were here...
- break;
- }
- int severity = computeSeverity(id);
- if (severity == ProblemSeverities.Ignore) return;
- this.handle(
- id,
- new String[] {new String(targetConstructor.declaringClass.readableName()), typesAsString(targetConstructor.isVarargs(), targetConstructor.parameters, false)},
- new String[] {new String(targetConstructor.declaringClass.shortReadableName()), typesAsString(targetConstructor.isVarargs(), targetConstructor.parameters, true)},
- ProblemSeverities.Ignore,
- statement.sourceStart,
- statement.sourceEnd);
-}
-/*
- * Similar implementation than invalidField(FieldReference...)
- * Note that following problem id cannot occur for Javadoc:
- * - NonStaticReferenceInStaticContext :
- * - NonStaticReferenceInConstructorInvocation :
- * - ReceiverTypeNotVisible :
- */
-public void javadocInvalidField(int sourceStart, int sourceEnd, Binding fieldBinding, TypeBinding searchedType, int modifiers) {
- int id = IProblem.JavadocUndefinedField;
- switch (fieldBinding.problemId()) {
- case ProblemReasons.NotFound :
- id = IProblem.JavadocUndefinedField;
- break;
- case ProblemReasons.NotVisible :
- id = IProblem.JavadocNotVisibleField;
- break;
- case ProblemReasons.Ambiguous :
- id = IProblem.JavadocAmbiguousField;
- break;
- case ProblemReasons.NoError : // 0
- default :
- needImplementation(); // want to fail to see why we were here...
- break;
- }
- int severity = computeSeverity(id);
- if (severity == ProblemSeverities.Ignore) return;
- // report issue
- if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, modifiers)) {
- String[] arguments = new String[] {new String(fieldBinding.readableName())};
- handle(
- id,
- arguments,
- arguments,
- ProblemSeverities.Ignore,
- sourceStart,
- sourceEnd);
- }
-}
-/*
- * Similar implementation than invalidMethod(MessageSend...)
- * Note that following problem id cannot occur for Javadoc:
- * - NonStaticReferenceInStaticContext :
- * - NonStaticReferenceInConstructorInvocation :
- * - ReceiverTypeNotVisible :
- */
-public void javadocInvalidMethod(MessageSend messageSend, MethodBinding method, int modifiers) {
- if (!javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, modifiers)) return;
- // set problem id
- ProblemMethodBinding problemMethod = null;
- int id = IProblem.JavadocUndefinedMethod; //default...
- switch (method.problemId()) {
- case ProblemReasons.NotFound :
- id = IProblem.JavadocUndefinedMethod;
- problemMethod = (ProblemMethodBinding) method;
- if (problemMethod.closestMatch != null) {
- int severity = computeSeverity(IProblem.JavadocParameterMismatch);
- if (severity == ProblemSeverities.Ignore) return;
- String closestParameterTypeNames = typesAsString(problemMethod.closestMatch.isVarargs(), problemMethod.closestMatch.parameters, false);
- String parameterTypeNames = typesAsString(method.isVarargs(), method.parameters, false);
- String closestParameterTypeShortNames = typesAsString(problemMethod.closestMatch.isVarargs(), problemMethod.closestMatch.parameters, true);
- String parameterTypeShortNames = typesAsString(method.isVarargs(), method.parameters, true);
- if (closestParameterTypeShortNames.equals(parameterTypeShortNames)){
- closestParameterTypeShortNames = closestParameterTypeNames;
- parameterTypeShortNames = parameterTypeNames;
- }
- this.handle(
- IProblem.JavadocParameterMismatch,
- new String[] {
- new String(problemMethod.closestMatch.declaringClass.readableName()),
- new String(problemMethod.closestMatch.selector),
- closestParameterTypeNames,
- parameterTypeNames
- },
- new String[] {
- new String(problemMethod.closestMatch.declaringClass.shortReadableName()),
- new String(problemMethod.closestMatch.selector),
- closestParameterTypeShortNames,
- parameterTypeShortNames
- },
- ProblemSeverities.Ignore,
- (int) (messageSend.nameSourcePosition >>> 32),
- (int) messageSend.nameSourcePosition);
- return;
- }
- break;
- case ProblemReasons.NotVisible :
- id = IProblem.JavadocNotVisibleMethod;
- break;
- case ProblemReasons.Ambiguous :
- id = IProblem.JavadocAmbiguousMethod;
- break;
- case ProblemReasons.NoError : // 0
- default :
- needImplementation(); // want to fail to see why we were here...
- break;
- }
- int severity = computeSeverity(id);
- if (severity == ProblemSeverities.Ignore) return;
- // report issue
- this.handle(
- id,
- new String[] {
- new String(method.declaringClass.readableName()),
- new String(method.selector), typesAsString(method.isVarargs(), method.parameters, false)},
- new String[] {
- new String(method.declaringClass.shortReadableName()),
- new String(method.selector), typesAsString(method.isVarargs(), method.parameters, true)},
- ProblemSeverities.Ignore,
- (int) (messageSend.nameSourcePosition >>> 32),
- (int) messageSend.nameSourcePosition);
-}
-public void javadocInvalidParamTagName(int sourceStart, int sourceEnd) {
- this.handle(IProblem.JavadocInvalidParamTagName, NoArgument, NoArgument, sourceStart, sourceEnd);
-}
-public void javadocInvalidReference(int sourceStart, int sourceEnd) {
- this.handle(IProblem.JavadocInvalidSeeReference, NoArgument, NoArgument, ProblemSeverities.Ignore, sourceStart, sourceEnd);
-}
-public void javadocInvalidSeeReferenceArgs(int sourceStart, int sourceEnd) {
- this.handle(IProblem.JavadocInvalidSeeArgs, NoArgument, NoArgument, ProblemSeverities.Ignore, sourceStart, sourceEnd);
-}
-public void javadocInvalidSeeUrlReference(int sourceStart, int sourceEnd) {
- this.handle(IProblem.JavadocInvalidSeeHref, NoArgument, NoArgument, ProblemSeverities.Ignore, sourceStart, sourceEnd);
-}
-public void javadocInvalidTag(int sourceStart, int sourceEnd) {
- this.handle(IProblem.JavadocInvalidTag, NoArgument, NoArgument, ProblemSeverities.Ignore, sourceStart, sourceEnd);
-}
-public void javadocInvalidThrowsClass(int sourceStart, int sourceEnd) {
- this.handle(IProblem.JavadocInvalidThrowsClass, NoArgument, NoArgument, ProblemSeverities.Ignore, sourceStart, sourceEnd);
-}
-public void javadocInvalidThrowsClassName(TypeReference typeReference, int modifiers) {
- int severity = computeSeverity(IProblem.JavadocInvalidThrowsClassName);
- if (severity == ProblemSeverities.Ignore) return;
- if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, modifiers)) {
- String[] arguments = new String[] {String.valueOf(typeReference.resolvedType.sourceName())};
- this.handle(
- IProblem.JavadocInvalidThrowsClassName,
- arguments,
- arguments,
- severity,
- typeReference.sourceStart,
- typeReference.sourceEnd);
- }
-}
-public void javadocInvalidType(ASTNode location, TypeBinding type, int modifiers) {
- if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, modifiers)) {
- int id = IProblem.JavadocUndefinedType; // default
- switch (type.problemId()) {
- case ProblemReasons.NotFound :
- id = IProblem.JavadocUndefinedType;
- break;
- case ProblemReasons.NotVisible :
- id = IProblem.JavadocNotVisibleType;
- break;
- case ProblemReasons.Ambiguous :
- id = IProblem.JavadocAmbiguousType;
- break;
- case ProblemReasons.InternalNameProvided :
- id = IProblem.JavadocInternalTypeNameProvided;
- break;
- case ProblemReasons.InheritedNameHidesEnclosingName :
- id = IProblem.JavadocInheritedNameHidesEnclosingTypeName;
- break;
- case ProblemReasons.NonStaticReferenceInStaticContext :
- id = IProblem.JavadocNonStaticTypeFromStaticInvocation;
- break;
- case ProblemReasons.NoError : // 0
- default :
- needImplementation(); // want to fail to see why we were here...
- break;
- }
- int severity = computeSeverity(id);
- if (severity == ProblemSeverities.Ignore) return;
- this.handle(
- id,
- new String[] {new String(type.readableName())},
- new String[] {new String(type.shortReadableName())},
- ProblemSeverities.Ignore,
- location.sourceStart,
- location.sourceEnd);
- }
-}
-public void javadocMalformedSeeReference(int sourceStart, int sourceEnd) {
- this.handle(IProblem.JavadocMalformedSeeReference, NoArgument, NoArgument, ProblemSeverities.Ignore, sourceStart, sourceEnd);
-}
-public void javadocMissing(int sourceStart, int sourceEnd, int modifiers){
- int severity = computeSeverity(IProblem.JavadocMissing);
- if (severity == ProblemSeverities.Ignore) return;
- boolean overriding = (modifiers & (ExtraCompilerModifiers.AccImplementing|ExtraCompilerModifiers.AccOverriding)) != 0;
- boolean report = (this.options.getSeverity(CompilerOptions.MissingJavadocComments) != ProblemSeverities.Ignore)
- && (!overriding || this.options.reportMissingJavadocCommentsOverriding);
- if (report) {
- String arg = javadocVisibilityArgument(this.options.reportMissingJavadocCommentsVisibility, modifiers);
- if (arg != null) {
- String[] arguments = new String[] { arg };
- this.handle(
- IProblem.JavadocMissing,
- arguments,
- arguments,
- ProblemSeverities.Ignore,
- sourceStart,
- sourceEnd);
- }
- }
-}
-public void javadocMissingHashCharacter(int sourceStart, int sourceEnd, String ref){
- int severity = computeSeverity(IProblem.JavadocMissingHashCharacter);
- if (severity == ProblemSeverities.Ignore) return;
- String[] arguments = new String[] { ref };
- this.handle(
- IProblem.JavadocMissingHashCharacter,
- arguments,
- arguments,
- ProblemSeverities.Ignore,
- sourceStart,
- sourceEnd);
-}
-public void javadocMissingIdentifier(int sourceStart, int sourceEnd, int modifiers){
- if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, modifiers))
- this.handle(IProblem.JavadocMissingIdentifier, NoArgument, NoArgument, ProblemSeverities.Ignore, sourceStart, sourceEnd);
-}
-public void javadocMissingParamName(int sourceStart, int sourceEnd, int modifiers){
- if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, modifiers))
- this.handle(IProblem.JavadocMissingParamName, NoArgument, NoArgument, sourceStart, sourceEnd);
-}
-public void javadocMissingParamTag(char[] name, int sourceStart, int sourceEnd, int modifiers) {
- int severity = computeSeverity(IProblem.JavadocMissingParamTag);
- if (severity == ProblemSeverities.Ignore) return;
- boolean overriding = (modifiers & (ExtraCompilerModifiers.AccImplementing|ExtraCompilerModifiers.AccOverriding)) != 0;
- boolean report = (this.options.getSeverity(CompilerOptions.MissingJavadocTags) != ProblemSeverities.Ignore)
- && (!overriding || this.options.reportMissingJavadocTagsOverriding);
- if (report && javadocVisibility(this.options.reportMissingJavadocTagsVisibility, modifiers)) {
- String[] arguments = new String[] { String.valueOf(name) };
- this.handle(
- IProblem.JavadocMissingParamTag,
- arguments,
- arguments,
- severity,
- sourceStart,
- sourceEnd);
- }
-}
-public void javadocMissingReference(int sourceStart, int sourceEnd, int modifiers){
- if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, modifiers))
- this.handle(IProblem.JavadocMissingSeeReference, NoArgument, NoArgument, ProblemSeverities.Ignore, sourceStart, sourceEnd);
-}
-public void javadocMissingReturnTag(int sourceStart, int sourceEnd, int modifiers){
- boolean overriding = (modifiers & (ExtraCompilerModifiers.AccImplementing|ExtraCompilerModifiers.AccOverriding)) != 0;
- boolean report = (this.options.getSeverity(CompilerOptions.MissingJavadocTags) != ProblemSeverities.Ignore)
- && (!overriding || this.options.reportMissingJavadocTagsOverriding);
- if (report && javadocVisibility(this.options.reportMissingJavadocTagsVisibility, modifiers)) {
- this.handle(IProblem.JavadocMissingReturnTag, NoArgument, NoArgument, sourceStart, sourceEnd);
- }
-}
-public void javadocMissingThrowsClassName(int sourceStart, int sourceEnd, int modifiers){
- if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, modifiers))
- this.handle(IProblem.JavadocMissingThrowsClassName, NoArgument, NoArgument, ProblemSeverities.Ignore, sourceStart, sourceEnd);
-}
-public void javadocUndeclaredParamTagName(char[] token, int sourceStart, int sourceEnd, int modifiers) {
- int severity = computeSeverity(IProblem.JavadocInvalidParamName);
- if (severity == ProblemSeverities.Ignore) return;
- if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, modifiers)) {
- String[] arguments = new String[] {String.valueOf(token)};
- this.handle(
- IProblem.JavadocInvalidParamName,
- arguments,
- arguments,
- severity,
- sourceStart,
- sourceEnd);
- }
-}
-public void javadocUnexpectedTag(int sourceStart, int sourceEnd) {
- this.handle(IProblem.JavadocUnexpectedTag, NoArgument, NoArgument, ProblemSeverities.Ignore, sourceStart, sourceEnd);
-}
-public void javadocUnexpectedText(int sourceStart, int sourceEnd) {
- this.handle(IProblem.JavadocUnexpectedText, NoArgument, NoArgument, ProblemSeverities.Ignore, sourceStart, sourceEnd);
-}
-public void javadocUnterminatedInlineTag(int sourceStart, int sourceEnd) {
- this.handle(IProblem.JavadocUnterminatedInlineTag, NoArgument, NoArgument, sourceStart, sourceEnd);
-}
-private boolean javadocVisibility(int visibility, int modifiers) {
- if (modifiers < 0) return true;
- switch (modifiers & ExtraCompilerModifiers.AccVisibilityMASK) {
- case ClassFileConstants.AccPublic :
- return true;
- case ClassFileConstants.AccProtected:
- return (visibility != ClassFileConstants.AccPublic);
- case ClassFileConstants.AccDefault:
- return (visibility == ClassFileConstants.AccDefault || visibility == ClassFileConstants.AccPrivate);
- case ClassFileConstants.AccPrivate:
- return (visibility == ClassFileConstants.AccPrivate);
- }
- return true;
-}
-private String javadocVisibilityArgument(int visibility, int modifiers) {
- String argument = null;
- switch (modifiers & ExtraCompilerModifiers.AccVisibilityMASK) {
- case ClassFileConstants.AccPublic :
- argument = CompilerOptions.PUBLIC;
- break;
- case ClassFileConstants.AccProtected:
- if (visibility != ClassFileConstants.AccPublic) {
- argument = CompilerOptions.PROTECTED;
- }
- break;
- case ClassFileConstants.AccDefault:
- if (visibility == ClassFileConstants.AccDefault || visibility == ClassFileConstants.AccPrivate) {
- argument = CompilerOptions.DEFAULT;
- }
- break;
- case ClassFileConstants.AccPrivate:
- if (visibility == ClassFileConstants.AccPrivate) {
- argument = CompilerOptions.PRIVATE;
- }
- break;
- }
- return argument;
-}
-public void localVariableHiding(LocalDeclaration local, Binding hiddenVariable, boolean isSpecialArgHidingField) {
- if (hiddenVariable instanceof LocalVariableBinding) {
- int id = (local instanceof Argument)
- ? IProblem.ArgumentHidingLocalVariable
- : IProblem.LocalVariableHidingLocalVariable;
- int severity = computeSeverity(id);
- if (severity == ProblemSeverities.Ignore) return;
- String[] arguments = new String[] {new String(local.name) };
- this.handle(
- id,
- arguments,
- arguments,
- severity,
- nodeSourceStart(hiddenVariable, local),
- nodeSourceEnd(hiddenVariable, local));
- } else if (hiddenVariable instanceof FieldBinding) {
- if (isSpecialArgHidingField && !this.options.reportSpecialParameterHidingField){
- return;
- }
- int id = (local instanceof Argument)
- ? IProblem.ArgumentHidingField
- : IProblem.LocalVariableHidingField;
- int severity = computeSeverity(id);
- if (severity == ProblemSeverities.Ignore) return;
- FieldBinding field = (FieldBinding) hiddenVariable;
- this.handle(
- id,
- new String[] {new String(local.name) , new String(field.declaringClass.readableName()) },
- new String[] {new String(local.name), new String(field.declaringClass.shortReadableName()) },
- severity,
- local.sourceStart,
- local.sourceEnd);
- }
-}
-public void localVariableNonNullComparedToNull(LocalVariableBinding local, ASTNode location) {
- int severity = computeSeverity(IProblem.NonNullLocalVariableComparisonYieldsFalse);
- if (severity == ProblemSeverities.Ignore) return;
- String[] arguments = new String[] {new String(local.name) };
- this.handle(
- IProblem.NonNullLocalVariableComparisonYieldsFalse,
- arguments,
- arguments,
- ProblemSeverities.Ignore,
- nodeSourceStart(local, location),
- nodeSourceEnd(local, location));
-}
-public void localVariableNullComparedToNonNull(LocalVariableBinding local, ASTNode location) {
- int severity = computeSeverity(IProblem.NullLocalVariableComparisonYieldsFalse);
- if (severity == ProblemSeverities.Ignore) return;
- String[] arguments = new String[] {new String(local.name) };
- this.handle(
- IProblem.NullLocalVariableComparisonYieldsFalse,
- arguments,
- arguments,
- ProblemSeverities.Ignore,
- nodeSourceStart(local, location),
- nodeSourceEnd(local, location));
-}
-public void localVariableNullInstanceof(LocalVariableBinding local, ASTNode location) {
- int severity = computeSeverity(IProblem.NullLocalVariableInstanceofYieldsFalse);
- if (severity == ProblemSeverities.Ignore) return;
- String[] arguments = new String[] {new String(local.name) };
- this.handle(
- IProblem.NullLocalVariableInstanceofYieldsFalse,
- arguments,
- arguments,
- ProblemSeverities.Ignore,
- nodeSourceStart(local, location),
- nodeSourceEnd(local, location));
-}
-public void localVariableNullReference(LocalVariableBinding local, ASTNode location) {
- int severity = computeSeverity(IProblem.NullLocalVariableReference);
- if (severity == ProblemSeverities.Ignore) return;
- String[] arguments = new String[] {new String(local.name) };
- this.handle(
- IProblem.NullLocalVariableReference,
- arguments,
- arguments,
- ProblemSeverities.Ignore,
- nodeSourceStart(local, location),
- nodeSourceEnd(local, location));
-}
-public void localVariablePotentialNullReference(LocalVariableBinding local, ASTNode location) {
- int severity = computeSeverity(IProblem.PotentialNullLocalVariableReference);
- if (severity == ProblemSeverities.Ignore) return;
- String[] arguments = new String[] {new String(local.name)};
- this.handle(
- IProblem.PotentialNullLocalVariableReference,
- arguments,
- arguments,
- ProblemSeverities.Ignore,
- nodeSourceStart(local, location),
- nodeSourceEnd(local, location));
-}
-public void localVariableRedundantCheckOnNonNull(LocalVariableBinding local, ASTNode location) {
- int severity = computeSeverity(IProblem.RedundantNullCheckOnNonNullLocalVariable);
- if (severity == ProblemSeverities.Ignore) return;
- String[] arguments = new String[] {new String(local.name) };
- this.handle(
- IProblem.RedundantNullCheckOnNonNullLocalVariable,
- arguments,
- arguments,
- ProblemSeverities.Ignore,
- nodeSourceStart(local, location),
- nodeSourceEnd(local, location));
-}
-public void localVariableRedundantCheckOnNull(LocalVariableBinding local, ASTNode location) {
- int severity = computeSeverity(IProblem.RedundantNullCheckOnNullLocalVariable);
- if (severity == ProblemSeverities.Ignore) return;
- String[] arguments = new String[] {new String(local.name) };
- this.handle(
- IProblem.RedundantNullCheckOnNullLocalVariable,
- arguments,
- arguments,
- ProblemSeverities.Ignore,
- nodeSourceStart(local, location),
- nodeSourceEnd(local, location));
-}
-public void localVariableRedundantNullAssignment(LocalVariableBinding local, ASTNode location) {
- int severity = computeSeverity(IProblem.RedundantLocalVariableNullAssignment);
- if (severity == ProblemSeverities.Ignore) return;
- String[] arguments = new String[] {new String(local.name) };
- this.handle(
- IProblem.RedundantLocalVariableNullAssignment,
- arguments,
- arguments,
- ProblemSeverities.Ignore,
- nodeSourceStart(local, location),
- nodeSourceEnd(local, location));
-}
-public void missingReturnType(AbstractMethodDeclaration methodDecl) {
- this.handle(
- IProblem.MissingReturnType,
- NoArgument,
- NoArgument,
- ProblemSeverities.Ignore,
- methodDecl.sourceStart,
- methodDecl.sourceEnd);
-}
-public void missingSemiColon(Expression expression, int start, int end){
- this.handle(
- IProblem.MissingSemiColon,
- NoArgument,
- NoArgument,
- start,
- end);
-}
-public void mustUseAStaticMethod(ASTNode messageSend, MethodBinding method) {
- this.handle(
- IProblem.StaticMethodRequested,
- new String[] {new String(method.declaringClass.readableName()), new String(method.selector != null ? method.selector : "".toCharArray()), typesAsString(method.isVarargs(), method.parameters, false)},
- new String[] {new String(method.declaringClass.shortReadableName()), new String(method.selector != null ? method.selector : "".toCharArray()), typesAsString(method.isVarargs(), method.parameters, true)},
- ProblemSeverities.Ignore,
- messageSend.sourceStart,
- messageSend.sourceEnd);
-}
-public void needImplementation() {
- this.abortDueToInternalError(Messages.abort_missingCode);
-}
-private int nodeSourceEnd(Binding field, ASTNode node) {
- return nodeSourceEnd(field, node, 0);
-}
-private int nodeSourceEnd(Binding field, ASTNode node, int index) {
- if (node instanceof ArrayTypeReference) {
- return ((ArrayTypeReference) node).originalSourceEnd;
- } else if (node instanceof QualifiedNameReference) {
- QualifiedNameReference ref = (QualifiedNameReference) node;
- if (ref.binding == field) {
- return (int) (ref.sourcePositions[ref.indexOfFirstFieldBinding-1]);
- }
- FieldBinding[] otherFields = ref.otherBindings;
- if (otherFields != null) {
- int offset = ref.indexOfFirstFieldBinding;
- for (int i = 0, length = otherFields.length; i < length; i++) {
- if (otherFields[i] == field)
- return (int) (ref.sourcePositions[i + offset]);
- }
- }
- } else if (node instanceof ArrayQualifiedTypeReference) {
- ArrayQualifiedTypeReference arrayQualifiedTypeReference = (ArrayQualifiedTypeReference) node;
- int length = arrayQualifiedTypeReference.sourcePositions.length;
- return (int) arrayQualifiedTypeReference.sourcePositions[length - 1];
- }
- return node.sourceEnd;
-}
-private int nodeSourceStart(Binding field, ASTNode node) {
- if (node instanceof FieldReference) {
- FieldReference fieldReference = (FieldReference) node;
- return (int) (fieldReference.nameSourcePosition >> 32);
- } else if (node instanceof QualifiedNameReference) {
- QualifiedNameReference ref = (QualifiedNameReference) node;
- if (ref.binding == field) {
- return (int) (ref.sourcePositions[ref.indexOfFirstFieldBinding-1] >> 32);
- }
- FieldBinding[] otherFields = ref.otherBindings;
- if (otherFields != null) {
- int offset = ref.indexOfFirstFieldBinding;
- for (int i = 0, length = otherFields.length; i < length; i++) {
- if (otherFields[i] == field)
- return (int) (ref.sourcePositions[i + offset] >> 32);
- }
- }
- }
- return node.sourceStart;
-}
-public void noMoreAvailableSpaceForArgument(LocalVariableBinding local, ASTNode location) {
- String[] arguments = new String[]{ new String(local.name) };
- this.handle(
- IProblem.TooManyArgumentSlots,
- arguments,
- arguments,
- ProblemSeverities.Ignore,
- nodeSourceStart(local, location),
- nodeSourceEnd(local, location));
-}
-
-public void noMoreAvailableSpaceForLocal(LocalVariableBinding local, ASTNode location) {
- String[] arguments = new String[]{ new String(local.name) };
- this.handle(
- IProblem.TooManyLocalVariableSlots,
- arguments,
- arguments,
- ProblemSeverities.Ignore,
- nodeSourceStart(local, location),
- nodeSourceEnd(local, location));
-}
-
-public void nonExternalizedStringLiteral(ASTNode location) {
- this.handle(
- IProblem.NonExternalizedStringLiteral,
- NoArgument,
- NoArgument,
- location.sourceStart,
- location.sourceEnd);
-}
-public void nonStaticAccessToStaticField(ASTNode location, FieldBinding field) {
- int severity = computeSeverity(IProblem.NonStaticAccessToStaticField);
- if (severity == ProblemSeverities.Ignore) return;
- this.handle(
- IProblem.NonStaticAccessToStaticField,
- new String[] {new String(field.declaringClass.readableName()), new String(field.name)},
- new String[] {new String(field.declaringClass.shortReadableName()), new String(field.name)},
- ProblemSeverities.Ignore,
- nodeSourceStart(field, location),
- nodeSourceEnd(field, location));
-}
-public void nonStaticAccessToStaticMethod(ASTNode location, MethodBinding method) {
- this.handle(
- IProblem.NonStaticAccessToStaticMethod,
- new String[] {new String(method.declaringClass.readableName()), new String(method.selector), typesAsString(method.isVarargs(), method.parameters, false)},
- new String[] {new String(method.declaringClass.shortReadableName()), new String(method.selector), typesAsString(method.isVarargs(), method.parameters, true)},
- ProblemSeverities.Ignore,
- location.sourceStart,
- location.sourceEnd);
-}
-
-
-public void looseVariableDecleration(ASTNode location, Assignment assignment) {
- String[] arguments = new String[] {assignment.lhs.toString()};
- this.handle(
- IProblem.LooseVarDecl,
- arguments,
- arguments,
- assignment.sourceStart,
- assignment.sourceEnd);
-
-}
-
-public void optionalSemicolon(ASTNode location) {
- // Do something else
- System.out.println("Optional Semi"); //$NON-NLS-1$
-}
-public void notCompatibleTypesError(InstanceOfExpression expression, TypeBinding leftType, TypeBinding rightType) {
- String leftName = new String(leftType.readableName());
- String rightName = new String(rightType.readableName());
- String leftShortName = new String(leftType.shortReadableName());
- String rightShortName = new String(rightType.shortReadableName());
- if (leftShortName.equals(rightShortName)){
- leftShortName = leftName;
- rightShortName = rightName;
- }
- this.handle(
- IProblem.IncompatibleTypesInConditionalOperator,
- new String[] {leftName, rightName },
- new String[] {leftShortName, rightShortName },
- ProblemSeverities.Ignore,
- expression.sourceStart,
- expression.sourceEnd);
-}
-public void operatorOnlyValidOnNumericType(CompoundAssignment assignment, TypeBinding leftType, TypeBinding rightType) {
- String leftName = new String(leftType.readableName());
- String rightName = new String(rightType.readableName());
- String leftShortName = new String(leftType.shortReadableName());
- String rightShortName = new String(rightType.shortReadableName());
- if (leftShortName.equals(rightShortName)){
- leftShortName = leftName;
- rightShortName = rightName;
- }
- this.handle(
- IProblem.TypeMismatch,
- new String[] {leftName, rightName },
- new String[] {leftShortName, rightShortName },
- ProblemSeverities.Ignore,
- assignment.sourceStart,
- assignment.sourceEnd);
-}
-public void overridesDeprecatedMethod(MethodBinding localMethod, MethodBinding inheritedMethod) {
- this.handle(
- IProblem.OverridingDeprecatedMethod,
- new String[] {
- new String(
- CharOperation.concat(
- localMethod.declaringClass.readableName(),
- localMethod.readableName(),
- '.')),
- new String(inheritedMethod.declaringClass.readableName())},
- new String[] {
- new String(
- CharOperation.concat(
- localMethod.declaringClass.shortReadableName(),
- localMethod.shortReadableName(),
- '.')),
- new String(inheritedMethod.declaringClass.shortReadableName())},
- ProblemSeverities.Ignore,
- localMethod.sourceStart(),
- localMethod.sourceEnd());
-}
-public void parameterAssignment(LocalVariableBinding local, ASTNode location) {
- int severity = computeSeverity(IProblem.ParameterAssignment);
- if (severity == ProblemSeverities.Ignore) return;
- String[] arguments = new String[] { new String(local.readableName())};
- this.handle(
- IProblem.ParameterAssignment,
- arguments,
- arguments,
- severity,
- nodeSourceStart(local, location),
- nodeSourceEnd(local, location)); // should never be a qualified name reference
-}
-public void parseError(
- int startPosition,
- int endPosition,
- int currentToken,
- char[] currentTokenSource,
- String errorTokenName,
- String[] possibleTokens) {
-
- if (possibleTokens.length == 0) { //no suggestion available
- if (isKeyword(currentToken)) {
- String[] arguments = new String[] {new String(currentTokenSource)};
- this.handle(
- IProblem.ParsingErrorOnKeywordNoSuggestion,
- arguments,
- arguments,
- // this is the current -invalid- token position
- startPosition,
- endPosition);
- return;
- } else {
- String[] arguments = new String[] {errorTokenName};
- this.handle(
- IProblem.ParsingErrorNoSuggestion,
- arguments,
- arguments,
- // this is the current -invalid- token position
- startPosition,
- endPosition);
- return;
- }
- }
-
- //build a list of probable right tokens
- StringBuffer list = new StringBuffer(20);
- for (int i = 0, max = possibleTokens.length; i < max; i++) {
- if (i > 0)
- list.append(", "); //$NON-NLS-1$
- list.append('"');
- list.append(possibleTokens[i]);
- list.append('"');
- }
-
- if (isKeyword(currentToken)) {
- String[] arguments = new String[] {new String(currentTokenSource), list.toString()};
- this.handle(
- IProblem.ParsingErrorOnKeyword,
- arguments,
- arguments,
- // this is the current -invalid- token position
- startPosition,
- endPosition);
- return;
- }
- //extract the literal when it's a literal
- if (isLiteral(currentToken) ||
- isIdentifier(currentToken)) {
- errorTokenName = new String(currentTokenSource);
- }
-
- String[] arguments = new String[] {errorTokenName, list.toString()};
- this.handle(
- IProblem.ParsingError,
- arguments,
- arguments,
- // this is the current -invalid- token position
- startPosition,
- endPosition);
-}
-public void parseErrorDeleteToken(
- int start,
- int end,
- int currentKind,
- char[] errorTokenSource,
- String errorTokenName){
- this.syntaxError(
- IProblem.ParsingErrorDeleteToken,
- start,
- end,
- currentKind,
- errorTokenSource,
- errorTokenName,
- null);
-}
-
-public void parseErrorDeleteTokens(
- int start,
- int end){
- this.handle(
- IProblem.ParsingErrorDeleteTokens,
- NoArgument,
- NoArgument,
- start,
- end);
-}
-public void parseErrorInsertAfterToken(
- int start,
- int end,
- int currentKind,
- char[] errorTokenSource,
- String errorTokenName,
- String expectedToken){
- this.syntaxError(
- IProblem.ParsingErrorInsertTokenAfter,
- start,
- end,
- currentKind,
- errorTokenSource,
- errorTokenName,
- expectedToken);
-}
-public void parseErrorInsertBeforeToken(
- int start,
- int end,
- int currentKind,
- char[] errorTokenSource,
- String errorTokenName,
- String expectedToken){
- this.syntaxError(
- IProblem.ParsingErrorInsertTokenBefore,
- start,
- end,
- currentKind,
- errorTokenSource,
- errorTokenName,
- expectedToken);
-}
-public void parseErrorInsertToComplete(
- int start,
- int end,
- String inserted,
- String completed){
- String[] arguments = new String[] {inserted, completed};
- if (";".equals(inserted)) // ignore missing semicolon error //$NON-NLS-1$
- return;
- this.handle(
- IProblem.ParsingErrorInsertToComplete,
- arguments,
- arguments,
- start,
- end);
-}
-
-public void parseErrorInsertToCompletePhrase(
- int start,
- int end,
- String inserted){
- String[] arguments = new String[] {inserted};
- this.handle(
- IProblem.ParsingErrorInsertToCompletePhrase,
- arguments,
- arguments,
- start,
- end);
-}
-public void parseErrorInsertToCompleteScope(
- int start,
- int end,
- String inserted){
- String[] arguments = new String[] {inserted};
- this.handle(
- IProblem.ParsingErrorInsertToCompleteScope,
- arguments,
- arguments,
- start,
- end);
-}
-public void parseErrorInvalidToken(
- int start,
- int end,
- int currentKind,
- char[] errorTokenSource,
- String errorTokenName,
- String expectedToken){
- this.syntaxError(
- IProblem.ParsingErrorInvalidToken,
- start,
- end,
- currentKind,
- errorTokenSource,
- errorTokenName,
- expectedToken);
-}
-public void parseErrorMergeTokens(
- int start,
- int end,
- String expectedToken){
- String[] arguments = new String[] {expectedToken};
- this.handle(
- IProblem.ParsingErrorMergeTokens,
- arguments,
- arguments,
- start,
- end);
-}
-public void parseErrorMisplacedConstruct(
- int start,
- int end){
- this.handle(
- IProblem.ParsingErrorMisplacedConstruct,
- NoArgument,
- NoArgument,
- start,
- end);
-}
-public void parseErrorNoSuggestion(
- int start,
- int end,
- int currentKind,
- char[] errorTokenSource,
- String errorTokenName){
- this.syntaxError(
- IProblem.ParsingErrorNoSuggestion,
- start,
- end,
- currentKind,
- errorTokenSource,
- errorTokenName,
- null);
-}
-public void parseErrorNoSuggestionForTokens(
- int start,
- int end){
- this.handle(
- IProblem.ParsingErrorNoSuggestionForTokens,
- NoArgument,
- NoArgument,
- start,
- end);
-}
-public void parseErrorReplaceToken(
- int start,
- int end,
- int currentKind,
- char[] errorTokenSource,
- String errorTokenName,
- String expectedToken){
- this.syntaxError(
- IProblem.ParsingError,
- start,
- end,
- currentKind,
- errorTokenSource,
- errorTokenName,
- expectedToken);
-}
-public void parseErrorReplaceTokens(
- int start,
- int end,
- String expectedToken){
- String[] arguments = new String[] {expectedToken};
- this.handle(
- IProblem.ParsingErrorReplaceTokens,
- arguments,
- arguments,
- start,
- end);
-}
-public void parseErrorUnexpectedEnd(
- int start,
- int end){
-
- String[] arguments;
- if(this.referenceContext instanceof ConstructorDeclaration) {
- arguments = new String[] {Messages.parser_endOfConstructor};
- } else if(this.referenceContext instanceof MethodDeclaration) {
- arguments = new String[] {Messages.parser_endOfMethod};
- } else if(this.referenceContext instanceof TypeDeclaration) {
- arguments = new String[] {Messages.parser_endOfInitializer};
- } else {
- arguments = new String[] {Messages.parser_endOfFile};
- }
- this.handle(
- IProblem.ParsingErrorUnexpectedEOF,
- arguments,
- arguments,
- start,
- end);
-}
-public void possibleAccidentalBooleanAssignment(Assignment assignment) {
- this.handle(
- IProblem.PossibleAccidentalBooleanAssignment,
- NoArgument,
- NoArgument,
- ProblemSeverities.Ignore,
- assignment.sourceStart,
- assignment.sourceEnd);
-}
-public void possibleFallThroughCase(CaseStatement caseStatement) {
- // as long as we consider fake reachable as reachable, better keep 'possible' in the name
- this.handle(
- IProblem.FallthroughCase,
- NoArgument,
- NoArgument,
- caseStatement.sourceStart,
- caseStatement.sourceEnd);
-}
-public void redefineArgument(Argument arg) {
- String[] arguments = new String[] {new String(arg.name)};
- this.handle(
- IProblem.RedefinedArgument,
- arguments,
- arguments,
- ProblemSeverities.Ignore,
- arg.sourceStart,
- arg.sourceEnd);
-}
-public void redefineLocal(LocalDeclaration localDecl) {
- String[] arguments = new String[] {new String(localDecl.name)};
- this.handle(
- IProblem.RedefinedLocal,
- arguments,
- arguments,
- ProblemSeverities.Ignore,
- localDecl.sourceStart,
- localDecl.sourceEnd);
-}
-public void reset() {
- this.positionScanner = null;
-}
-private int retrieveEndingPositionAfterOpeningParenthesis(int sourceStart, int sourceEnd, int numberOfParen) {
- if (this.referenceContext == null) return sourceEnd;
- CompilationResult compilationResult = this.referenceContext.compilationResult();
- if (compilationResult == null) return sourceEnd;
- ICompilationUnit compilationUnit = compilationResult.getCompilationUnit();
- if (compilationUnit == null) return sourceEnd;
- char[] contents = compilationUnit.getContents();
- if (contents.length == 0) return sourceEnd;
- if (this.positionScanner == null) {
- this.positionScanner = new Scanner(false, false, false, this.options.sourceLevel, this.options.complianceLevel, null, null, false);
- }
- this.positionScanner.setSource(contents);
- this.positionScanner.resetTo(sourceStart, sourceEnd);
- try {
- int token;
- int previousSourceEnd = sourceEnd;
- while ((token = this.positionScanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
- switch(token) {
- case TerminalTokens.TokenNameRPAREN:
- return previousSourceEnd;
- default :
- previousSourceEnd = this.positionScanner.currentPosition - 1;
- }
- }
- } catch(InvalidInputException e) {
- // ignore
- }
- return sourceEnd;
-}
-private int retrieveStartingPositionAfterOpeningParenthesis(int sourceStart, int sourceEnd, int numberOfParen) {
- if (this.referenceContext == null) return sourceStart;
- CompilationResult compilationResult = this.referenceContext.compilationResult();
- if (compilationResult == null) return sourceStart;
- ICompilationUnit compilationUnit = compilationResult.getCompilationUnit();
- if (compilationUnit == null) return sourceStart;
- char[] contents = compilationUnit.getContents();
- if (contents.length == 0) return sourceStart;
- if (this.positionScanner == null) {
- this.positionScanner = new Scanner(false, false, false, this.options.sourceLevel, this.options.complianceLevel, null, null, false);
- }
- this.positionScanner.setSource(contents);
- this.positionScanner.resetTo(sourceStart, sourceEnd);
- int count = 0;
- try {
- int token;
- while ((token = this.positionScanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
- switch(token) {
- case TerminalTokens.TokenNameLPAREN:
- count++;
- if (count == numberOfParen) {
- this.positionScanner.getNextToken();
- return this.positionScanner.startPosition;
- }
- }
- }
- } catch(InvalidInputException e) {
- // ignore
- }
- return sourceStart;
-}
-public void scannerError(Parser parser, String errorTokenName) {
- Scanner scanner = parser.scanner;
-
- int flag = IProblem.ParsingErrorNoSuggestion;
- int startPos = scanner.startPosition;
- int endPos = scanner.currentPosition - 1;
-
- //special treatment for recognized errors....
- if (errorTokenName.equals(Scanner.END_OF_SOURCE))
- flag = IProblem.EndOfSource;
- else if (errorTokenName.equals(Scanner.INVALID_HEXA))
- flag = IProblem.InvalidHexa;
- else if (errorTokenName.equals(Scanner.INVALID_OCTAL))
- flag = IProblem.InvalidOctal;
- else if (errorTokenName.equals(Scanner.INVALID_CHARACTER_CONSTANT))
- flag = IProblem.InvalidCharacterConstant;
- else if (errorTokenName.equals(Scanner.INVALID_ESCAPE))
- flag = IProblem.InvalidEscape;
- else if (errorTokenName.equals(Scanner.INVALID_UNICODE_ESCAPE)){
- flag = IProblem.InvalidUnicodeEscape;
- // better locate the error message
- char[] source = scanner.source;
- int checkPos = scanner.currentPosition - 1;
- if (checkPos >= source.length) checkPos = source.length - 1;
- while (checkPos >= startPos){
- if (source[checkPos] == '\\') break;
- checkPos --;
- }
- startPos = checkPos;
- } else if (errorTokenName.equals(Scanner.INVALID_LOW_SURROGATE)) {
- flag = IProblem.InvalidLowSurrogate;
- } else if (errorTokenName.equals(Scanner.INVALID_HIGH_SURROGATE)) {
- flag = IProblem.InvalidHighSurrogate;
- // better locate the error message
- char[] source = scanner.source;
- int checkPos = scanner.startPosition + 1;
- while (checkPos <= endPos){
- if (source[checkPos] == '\\') break;
- checkPos ++;
- }
- endPos = checkPos - 1;
- } else if (errorTokenName.equals(Scanner.INVALID_FLOAT))
- flag = IProblem.InvalidFloat;
- else if (errorTokenName.equals(Scanner.UNTERMINATED_STRING))
- flag = IProblem.UnterminatedString;
- else if (errorTokenName.equals(Scanner.UNTERMINATED_COMMENT))
- flag = IProblem.UnterminatedComment;
- else if (errorTokenName.equals(Scanner.INVALID_CHAR_IN_STRING))
- flag = IProblem.UnterminatedString;
- else if (errorTokenName.equals(Scanner.INVALID_DIGIT))
- flag = IProblem.InvalidDigit;
-
- String[] arguments = flag == IProblem.ParsingErrorNoSuggestion
- ? new String[] {errorTokenName}
- : NoArgument;
- this.handle(
- flag,
- arguments,
- arguments,
- // this is the current -invalid- token position
- startPos,
- endPos,
- parser.compilationUnit.compilationResult);
-}
-public void shouldReturn(TypeBinding returnType, ASTNode location) {
- this.handle(
- IProblem.ShouldReturnValue,
- new String[] { new String (returnType.readableName())},
- new String[] { new String (returnType.shortReadableName())},
- ProblemSeverities.Ignore,
- location.sourceStart,
- location.sourceEnd);
-}
-public void staticAndInstanceConflict(MethodBinding currentMethod, MethodBinding inheritedMethod) {
- if (currentMethod.isStatic())
- this.handle(
- // This static method cannot hide the instance method from %1
- // 8.4.6.4 - If a class inherits more than one method with the same signature a static (non-abstract) method cannot hide an instance method.
- IProblem.CannotHideAnInstanceMethodWithAStaticMethod,
- new String[] {new String(inheritedMethod.declaringClass.readableName())},
- new String[] {new String(inheritedMethod.declaringClass.shortReadableName())},
- ProblemSeverities.Ignore,
- currentMethod.sourceStart(),
- currentMethod.sourceEnd());
- else
- this.handle(
- // This instance method cannot override the static method from %1
- // 8.4.6.4 - If a class inherits more than one method with the same signature an instance (non-abstract) method cannot override a static method.
- IProblem.CannotOverrideAStaticMethodWithAnInstanceMethod,
- new String[] {new String(inheritedMethod.declaringClass.readableName())},
- new String[] {new String(inheritedMethod.declaringClass.shortReadableName())},
- currentMethod.sourceStart(),
- currentMethod.sourceEnd());
-}
-public void staticFieldAccessToNonStaticVariable(ASTNode location, FieldBinding field) {
- String[] arguments = new String[] {new String(field.readableName())};
- this.handle(
- IProblem.NonStaticFieldFromStaticInvocation,
- arguments,
- arguments,
- ProblemSeverities.Ignore,
- nodeSourceStart(field,location),
- nodeSourceEnd(field, location));
-}
-public void superfluousSemicolon(int sourceStart, int sourceEnd) {
- this.handle(
- IProblem.SuperfluousSemicolon,
- NoArgument,
- NoArgument,
- sourceStart,
- sourceEnd);
-}
-private void syntaxError(
- int id,
- int startPosition,
- int endPosition,
- int currentKind,
- char[] currentTokenSource,
- String errorTokenName,
- String expectedToken) {
-
- String eTokenName;
- if (isKeyword(currentKind) ||
- isLiteral(currentKind) ||
- isIdentifier(currentKind)) {
- eTokenName = new String(currentTokenSource);
- } else {
- eTokenName = errorTokenName;
- }
-
- String[] arguments;
- if(expectedToken != null) {
- arguments = new String[] {eTokenName, expectedToken};
- } else {
- arguments = new String[] {eTokenName};
- }
- this.handle(
- id,
- arguments,
- arguments,
- startPosition,
- endPosition);
-}
-public void task(String tag, String message, String priority, int start, int end){
- this.handle(
- IProblem.Task,
- new String[] { tag, message, priority/*secret argument that is not surfaced in getMessage()*/},
- new String[] { tag, message, priority/*secret argument that is not surfaced in getMessage()*/},
- start,
- end);
-}
-public void typeMismatchError(TypeBinding actualType, TypeBinding expectedType, ASTNode location) {
- this.handle(
- IProblem.TypeMismatch,
- new String[] {new String(actualType.readableName()), new String(expectedType.readableName())},
- new String[] {new String(actualType.shortReadableName()), new String(expectedType.shortReadableName())},
- location.sourceStart,
- location.sourceEnd);
-}
-private String typesAsString(boolean isVarargs, TypeBinding[] types, boolean makeShort) {
- StringBuffer buffer = new StringBuffer(10);
- for (int i = 0, length = types.length; i < length; i++) {
- if (i != 0)
- buffer.append(", "); //$NON-NLS-1$
- TypeBinding type = types[i];
- boolean isVarargType = isVarargs && i == length-1;
- if (isVarargType) type = ((ArrayBinding)type).elementsType();
- buffer.append(new String(makeShort ? type.shortReadableName() : type.readableName()));
- if (isVarargType) buffer.append("..."); //$NON-NLS-1$
- }
- return buffer.toString();
-}
-public void undefinedLabel(BranchStatement statement) {
- if (isRecoveredName(statement.label)) return;
- String[] arguments = new String[] {new String(statement.label)};
- this.handle(
- IProblem.UndefinedLabel,
- arguments,
- arguments,
- statement.sourceStart,
- statement.sourceEnd);
-}
-public void undocumentedEmptyBlock(int blockStart, int blockEnd) {
- this.handle(
- IProblem.UndocumentedEmptyBlock,
- NoArgument,
- NoArgument,
- blockStart,
- blockEnd);
-}
-public void uninitializedLocalVariable(LocalVariableBinding binding, ASTNode location) {
- int severity = computeSeverity(IProblem.UninitializedLocalVariable);
- if (severity == ProblemSeverities.Ignore) return;
- String[] arguments = new String[] {new String(binding.readableName())};
- this.handle(
- IProblem.UninitializedLocalVariable,
- arguments,
- arguments,
- severity,
- nodeSourceStart(binding, location),
- nodeSourceEnd(binding, location));
-}
-public void uninitializedGlobalVariable(LocalVariableBinding binding, ASTNode location) {
- int severity = computeSeverity(IProblem.UninitializedGlobalVariable);
- if (severity == ProblemSeverities.Ignore) return;
- String[] arguments = new String[] {new String(binding.readableName())};
- this.handle(
- IProblem.UninitializedGlobalVariable,
- arguments,
- arguments,
- ProblemSeverities.Ignore,
- nodeSourceStart(binding, location),
- nodeSourceEnd(binding, location));
-}
-public void unnecessaryElse(ASTNode location) {
- this.handle(
- IProblem.UnnecessaryElse,
- NoArgument,
- NoArgument,
- location.sourceStart,
- location.sourceEnd);
-}
-public void unnecessaryNLSTags(int sourceStart, int sourceEnd) {
- this.handle(
- IProblem.UnnecessaryNLSTag,
- NoArgument,
- NoArgument,
- sourceStart,
- sourceEnd);
-}
-public void unreachableCode(Statement statement) {
- int sourceStart = statement.sourceStart;
- int sourceEnd = statement.sourceEnd;
- if (statement instanceof LocalDeclaration) {
- LocalDeclaration declaration = (LocalDeclaration) statement;
- sourceStart = declaration.declarationSourceStart;
- sourceEnd = declaration.declarationSourceEnd;
- } else if (statement instanceof Expression) {
- int statemendEnd = ((Expression) statement).statementEnd;
- if (statemendEnd != -1) sourceEnd = statemendEnd;
- }
- this.handle(
- IProblem.CodeCannotBeReached,
- NoArgument,
- NoArgument,
- ProblemSeverities.Ignore,
- sourceStart,
- sourceEnd);
-}
-public void unresolvableReference(NameReference nameRef, Binding binding) {
-/* also need to check that the searchedType is the receiver type
- if (binding instanceof ProblemBinding) {
- ProblemBinding problem = (ProblemBinding) binding;
- if (problem.searchType != null && problem.searchType.isHierarchyInconsistent())
- severity = SecondaryError;
- }
-*/
- String[] arguments = new String[] {new String(binding.readableName())};
- int end = nameRef.sourceEnd;
- if (nameRef instanceof QualifiedNameReference) {
- QualifiedNameReference ref = (QualifiedNameReference) nameRef;
- if (isRecoveredName(ref.tokens)) return;
- if (ref.indexOfFirstFieldBinding >= 1)
- end = (int) ref.sourcePositions[ref.indexOfFirstFieldBinding - 1];
- } else {
- SingleNameReference ref = (SingleNameReference) nameRef;
- if (isRecoveredName(ref.token)) return;
- }
- this.handle(
- IProblem.UndefinedName,
- arguments,
- arguments,
- ProblemSeverities.Ignore,
- nameRef.sourceStart,
- end);
-}
-public void unusedArgument(LocalDeclaration localDecl) {
- int severity = computeSeverity(IProblem.ArgumentIsNeverUsed);
- if (severity == ProblemSeverities.Ignore) return;
- String[] arguments = new String[] {new String(localDecl.name)};
- this.handle(
- IProblem.ArgumentIsNeverUsed,
- arguments,
- arguments,
- ProblemSeverities.Ignore,
- localDecl.sourceStart,
- localDecl.sourceEnd);
-}
-public void unusedLabel(LabeledStatement statement) {
- int severity = computeSeverity(IProblem.UnusedLabel);
- if (severity == ProblemSeverities.Ignore) return;
- String[] arguments = new String[] {new String(statement.label)};
- this.handle(
- IProblem.UnusedLabel,
- arguments,
- arguments,
- ProblemSeverities.Ignore,
- statement.sourceStart,
- statement.labelEnd);
-}
-public void unusedLocalVariable(LocalDeclaration localDecl) {
- int severity = computeSeverity(IProblem.LocalVariableIsNeverUsed);
- if (severity == ProblemSeverities.Ignore) return;
- String[] arguments = new String[] {new String(localDecl.name)};
- this.handle(
- IProblem.LocalVariableIsNeverUsed,
- arguments,
- arguments,
- severity,
- localDecl.sourceStart,
- localDecl.sourceEnd);
-}
-public void unusedPrivateField(FieldDeclaration fieldDecl) {
-
- int severity = computeSeverity(IProblem.UnusedPrivateField);
- if (severity == ProblemSeverities.Ignore) return;
-
- FieldBinding field = fieldDecl.binding;
-
- this.handle(
- IProblem.UnusedPrivateField,
- new String[] {
- new String(field.declaringClass.readableName()),
- new String(field.name),
- },
- new String[] {
- new String(field.declaringClass.shortReadableName()),
- new String(field.name),
- },
- ProblemSeverities.Ignore,
- nodeSourceStart(field, fieldDecl),
- nodeSourceEnd(field, fieldDecl));
-}
-public void unusedPrivateMethod(AbstractMethodDeclaration methodDecl) {
-
- int severity = computeSeverity(IProblem.UnusedPrivateMethod);
- if (severity == ProblemSeverities.Ignore) return;
-
- MethodBinding method = methodDecl.binding;
- char[] methodSelector = method.selector;
- if(methodSelector == null)
- methodSelector = methodDecl.getSafeName();
-
- // no report for serialization support 'Object readResolve()'
- if (!method.isStatic()
- && TypeIds.T_JavaLangObject == method.returnType.id
- && method.parameters.length == 0
- && CharOperation.equals(methodSelector, TypeConstants.READRESOLVE)) {
- return;
- }
- // no report for serialization support 'Object writeReplace()'
- if (!method.isStatic()
- && TypeIds.T_JavaLangObject == method.returnType.id
- && method.parameters.length == 0
- && CharOperation.equals(methodSelector, TypeConstants.WRITEREPLACE)) {
- return;
- }
- this.handle(
- IProblem.UnusedPrivateMethod,
- new String[] {
- new String(method.declaringClass.readableName()),
- new String(methodSelector),
- typesAsString(method.isVarargs(), method.parameters, false)
- },
- new String[] {
- new String(method.declaringClass.shortReadableName()),
- new String(methodSelector),
- typesAsString(method.isVarargs(), method.parameters, true)
- },
- ProblemSeverities.Ignore,
- methodDecl.sourceStart,
- methodDecl.sourceEnd);
-}
-public void unusedPrivateType(TypeDeclaration typeDecl) {
- int severity = computeSeverity(IProblem.UnusedPrivateType);
- if (severity == ProblemSeverities.Ignore) return;
-
- ReferenceBinding type = typeDecl.binding;
- this.handle(
- IProblem.UnusedPrivateType,
- new String[] {
- new String(type.readableName()),
- },
- new String[] {
- new String(type.shortReadableName()),
- },
- ProblemSeverities.Ignore,
- typeDecl.sourceStart,
- typeDecl.sourceEnd);
-}
-public void visibilityConflict(MethodBinding currentMethod, MethodBinding inheritedMethod) {
- this.handle(
- // Cannot reduce the visibility of the inherited method from %1
- // 8.4.6.3 - The access modifier of an hiding method must provide at least as much access as the hidden method.
- // 8.4.6.3 - The access modifier of an overiding method must provide at least as much access as the overriden method.
- IProblem.MethodReducesVisibility,
- new String[] {new String(inheritedMethod.declaringClass.readableName())},
- new String[] {new String(inheritedMethod.declaringClass.shortReadableName())},
- ProblemSeverities.Ignore,
- currentMethod.sourceStart(),
- currentMethod.sourceEnd());
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/ProblemSeverities.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/ProblemSeverities.java
deleted file mode 100644
index d0e4079c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/ProblemSeverities.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.problem;
-
-public interface ProblemSeverities {
-
- final int Ignore = -1; // during handling only
- final int Warning = 0; // during handling only
-
- final int Error = 1; // when bit is set: problem is error, if not it is a warning
- final int AbortCompilation = 2;
- final int AbortCompilationUnit = 4;
- final int AbortType = 8;
- final int AbortMethod = 16;
- final int Abort = 30; // 2r11110
- final int Optional = 32; // when bit is set: problem was configurable
- final int SecondaryError = 64;
- final int Fatal = 128; // when bit is set: problem was either a mandatory error, or an optional+treatOptionalErrorAsFatal
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/ShouldNotImplement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/ShouldNotImplement.java
deleted file mode 100644
index 7c37a400..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/ShouldNotImplement.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.problem;
-
-/*
- * Special unchecked exception type used
- * to denote implementation that should never be reached.
- *
- * (internal only)
- */
-public class ShouldNotImplement extends RuntimeException {
- private static final long serialVersionUID = 2669970476264283736L; // backward compatible
- public ShouldNotImplement(String message) {
- super(message);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/messages.properties b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/messages.properties
deleted file mode 100644
index 62ce4dc6..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/problem/messages.properties
+++ /dev/null
@@ -1,374 +0,0 @@
-###############################################################################
-# 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
-###############################################################################
-0 = {0}
-2 = {0} cannot be resolved to a type
-3 = The type {0} is not visible
-4 = The type {0} is ambiguous
-5 = The type {0} is deprecated
-6 = The nested type {0} cannot be referenced using its binary name
-7 = The type {0} is never used locally
-
-15 = Incompatible operand types {0} and {1}
-16 = Incompatible conditional operand types {0} and {1}
-17 = Type mismatch: cannot convert from {0} to {1}
-18 = The static member type {0}.{1} should be accessed directly
-
-20 = No enclosing instance of type {0} is accessible to invoke the super constructor. Must define a constructor and explicitly qualify its super constructor invocation with an instance of {0} (e.g. x.super() where x is an instance of {0}).
-21 = No enclosing instance of type {0} is accessible. Must qualify the allocation with an enclosing instance of type {0} (e.g. x.new A() where x is an instance of {0}).
-22 = No enclosing instance of the type {0} is accessible in scope
-23 = Illegal enclosing instance specification for type {0}
-24 = Cannot define static initializer in inner type {0}
-25 = Cannot refer to a non-final variable {0} inside an inner class defined in a different function
-27 = Cannot use an expression of the type {0} as a valid enclosing instance
-28 = No enclosing instance of type {0} is available due to some intermediate constructor invocation
-33 = The type {0} is hiding the type {1}
-
-50 = {0} cannot be resolved
-51 = The local variable {0} may not have been initialized
-52 = void is an invalid type for the variable {0}
-54 = void[] is an invalid type
-55 = Duplicate local variable {0}
-56 = Duplicate parameter {0}
-57 = The final local variable {0} may already have been assigned
-58 = The final local variable {0} cannot be assigned. It must be blank and not using a compound assignment
-59 = The parameter {0} should not be assigned
-60 = The final local variable {0} cannot be assigned, since it is defined in an enclosing type
-61 = The local variable {0} is never read
-62 = The parameter {0} is never read
-63 = The code of function {0}({1}) is exceeding the 65535 bytes limit
-64 = The code for the static initializer is exceeding the 65535 bytes limit
-65 = Too many parameters, parameter {0} is exceeding the limit of 255 words eligible for function parameters
-66 = Too many local variables, local variable {0} is exceeding the limit of 65535 words eligible for function local variables
-68 = Too many array dimensions. Maximum is 255
-69 = The code of constructor {0}({1}) is exceeding the 65535 bytes limit
-70 = {0} cannot be resolved or is not a field
-71 = The field {1}.{0} is not visible
-72 = The field {0} is ambiguous
-73 = The field {0}.{1} is deprecated
-74 = Cannot make a static reference to the non-static field {0}
-75 = Cannot reference a field before it is defined
-76 = The static field {0}.{1} should be accessed in a static way
-77 = The field {0}.{1} is never read locally
-78 = The static field {0}.{1} should be accessed directly
-79 = Unqualified access to the field {0}.{1}
-80 = The final field {0}.{1} cannot be assigned
-81 = The blank final field {0} may not have been initialized
-82 = The final field {0} may already have been assigned
-
-90 = The local variable {0} is hiding a global variable
-91 = The local variable {0} is hiding a field from type {1}
-92 = The field {0}.{1} is hiding another local variable defined in an enclosing type scope
-93 = The field {0}.{1} is hiding a field from type {2}
-94 = The parameter {0} is hiding another local variable or global variable
-95 = The parameter {0} is hiding a field from type {1}
-97 = The variable {0} is Globaly Scoped.
-98 = The global variable {0} may not have been initialized
-
-
-100 = The function {1}({2}) is undefined for the type {0}
-101 = The function {1}({2}) from the file {0} is not visible
-102 = The function {1}({2}) is ambiguous for the type {0}
-103 = The function {1}({2}) from the file {0} is deprecated
-104 = Cannot directly invoke the abstract function {1}({2}) for the type {0}
-105 = Void functions cannot return a value
-106 = Cannot return a void result
-107 = This function requires a body instead of a semicolon
-108 = This function must return a result of type {0}
-109 = The function {1}({2}) is undefined
-
-110 = This function has a constructor name
-111 = Return type for the function is missing
-112 = Native functions do not specify a body
-113 = Abstract functions do not specify a body
-114 = Cannot invoke {1}({2}) on the primitive type {0}
-115 = The function {1}({2}) in the type {0} is not applicable for the arguments ({3})
-116 = Cannot invoke {1}({2}) on the array type {0}
-117 = The static function {1}({2}) from the type {0} should be accessed in a static way
-118 = The function {1}({2}) from the type {0} is never used locally
-119 = The static function {1}({2}) from the type {0} should be accessed directly
-120 = Wrong number of arguments for the function {0} (), expecting {1} argument(s), but there was {2}
-121 = {1} is not a function
-
-130 = The constructor {0}({1}) is undefined
-131 = The constructor {0}({1}) is not visible
-132 = The constructor {0}({1}) is ambiguous
-133 = The constructor {0}({1}) is deprecated
-134 = The constructor {0}({1}) is never used locally
-135 = Cannot refer to an instance field {0} while explicitly invoking a constructor
-136 = Cannot refer to an instance function while explicitly invoking a constructor
-137 = Recursive constructor invocation {0}({1})
-138 = Cannot refer to 'this' nor 'super' while explicitly invoking a constructor
-139 = Constructor call must be the first statement in a constructor
-140 = Implicit super constructor {0}({1}) is undefined for default constructor. Must define an explicit constructor
-141 = Implicit super constructor {0}({1}) is not visible for default constructor. Must define an explicit constructor
-142 = Implicit super constructor {0}({1}) is ambiguous for default constructor. Must define an explicit constructor
-143 = Implicit super constructor {0}({1}) is undefined. Must explicitly invoke another constructor
-144 = Implicit super constructor {0}({1}) is not visible. Must explicitly invoke another constructor
-145 = Implicit super constructor {0}({1}) is ambiguous. Must explicitly invoke another constructor
-146 = Default constructor cannot handle exception type {0} thrown by implicit super constructor. Must define an explicit constructor
-147 = Unhandled exception type {0} thrown by implicit super constructor
-
-150 = The type of the expression must be an array type but it resolved to {0}
-152 = String constant is exceeding the limit of 65535 bytes of UTF8 encoding
-154 = The literal {1} of type {0} is out of range
-157 = Cannot instantiate the type {0}
-158 = Cannot define dimension expressions when an array initializer is provided
-159 = Variable must provide either dimension expressions or an array initializer
-160 = The operator {0} is undefined for the argument type(s) {1}
-161 = Unreachable code
-162 = Cannot return from outside a function or method.
-163 = Initializer does not complete normally
-164 = Expression must return a value
-165 = Unreachable catch block for {0}. Only more specific exceptions are thrown and handled by previous catch block(s).
-166 = The default case is already defined
-167 = Unreachable catch block for {0}. This exception is never thrown from the try statement body
-168 = Unhandled exception type {0}
-169 = Cannot switch on a value of type {0}. Only int values or enum constants are permitted
-170 = Duplicate case
-171 = Duplicate label {0}
-172 = break cannot be used outside of a loop or a switch
-173 = continue cannot be used outside of a loop
-174 = The label {0} is missing
-175 = {0} is not a valid type''s argument for the synchronized statement
-176 = null is not a valid argument for the synchronized statement
-177 = Cannot throw null as an exception
-178 = The assignment to variable {0} has no effect
-179 = Possible accidental assignment in place of a comparison. A condition expression should not be reduced to an assignment
-180 = Unnecessary semicolon
-183 = The expression of type {0} is already an instance of type {1}
-184 = finally block does not complete normally
-185 = The declared exception {3} is not actually thrown by the function {1}({2}) from type {0}
-186 = The declared exception {2} is not actually thrown by the constructor {0}({1})
-187 = Unreachable catch block for {0}. It is already handled by the catch block for {1}
-188 = Empty control-flow statement
-189 = Statement unnecessarily nested within else clause. The corresponding then clause does not complete normally
-190 = Read access to enclosing field {0}.{1} is emulated by a synthetic accessor function. Increasing its visibility will improve your performance
-191 = Write access to enclosing field {0}.{1} is emulated by a synthetic accessor function. Increasing its visibility will improve your performance
-192 = Access to enclosing function {1}({2}) from the type {0} is emulated by a synthetic accessor function. Increasing its visibility will improve your performance
-193 = Access to enclosing constructor {0}({1}) is emulated by a synthetic accessor function. Increasing its visibility will improve your performance
-194 = Switch case may be entered by falling through previous case
-195 = The function {1} is defined in an inherited type and an enclosing scope
-196 = The field {0} is defined in an inherited type and an enclosing scope
-197 = The type {0} is defined in an inherited type and an enclosing scope
-198 = Cannot allocate the member type {0} using its compound name when qualified by an enclosing instance. The member type name is resolved relatively to the qualifying instance type
-199 = The label {0} is never explicitly referenced
-200 = Cannot use {0} in a static context
-201 = Cannot make a static reference to the non-static function {1}({2}) from the type {0}
-202 = Cannot specify an array dimension after an empty dimension
-204 = Syntax error on token "{0}", {1} expected
-205 = Syntax error on token "{0}", no accurate correction available
-206 = Invalid argument to operation ++/--
-208 = Array constants can only be used in initializers
-209 = Syntax error on keyword "{0}"; {1} expected
-210 = Syntax error on keyword "{0}", no accurate correction available
-
-220 = Unmatched bracket
-221 = The primitive type {0} of {1} does not have a field {2}
-222 = Invalid expression as statement
-223 = The left-hand side of an assignment must be a variable
-224 = Missing semicolon
-225 = Invalid parenthesized expression
-
-230 = Syntax error on token "{0}", {1} expected before this token
-231 = Syntax error on token "{0}", {1} expected after this token
-232 = Syntax error on token "{0}", delete this token
-233 = Syntax error on tokens, delete these tokens
-234 = Syntax error on tokens, they can be merge to form {0}
-235 = Syntax error on token "{0}", invalid {1}
-236 = Syntax error on token(s), misplaced construct(s)
-237 = Syntax error on tokens, {0} expected instead
-238 = Syntax error on tokens, no accurate correction available
-239 = Syntax error, unexpected {0}
-240 = Syntax error, insert "{0}" to complete {1}
-241 = Syntax error, insert "{0}" to complete scope
-242 = Syntax error, insert "{0}" to complete phrase
-
-250 = Unexpected end of file
-251 = Invalid hex literal number
-252 = Invalid octal literal number
-253 = Invalid character constant
-254 = Invalid escape sequence (valid ones are \\b \\t \\n \\f \\r \\" \\' \\\\ )
-255 = Invalid input
-256 = Invalid unicode
-257 = Invalid float literal number
-258 = Null source string
-259 = String literal is not properly closed by a matching quote
-260 = Unexpected end of comment
-261 = Non-externalized string literal; it should be followed by //$NON-NLS-<n>$
-262 = Invalid digit (valid ones are 0..9)
-263 = Invalid low surrogate: must be within 0xDC00 and 0xDFFF
-264 = Invalid high surrogate: must be within 0xD800 and 0xDBFF
-265 = Unnecessary $NON-NLS$ tag
-
-280 = Discouraged access: {0}
-
-301 = Duplicate modifier for the type {0}
-302 = Illegal modifier for the class {0}; only public, abstract & final are permitted
-304 = Illegal modifier for the member class {0}; only public, protected, private, static, abstract & final are permitted
-306 = Illegal modifier for the local class {0}; only abstract or final is permitted
-307 = Access restriction: {0}
-308 = The class {0} can be either abstract or final, not both
-310 = The member type {0} can only set one of public / protected / private
-311 = The member type {0} cannot be declared static; static types can only be declared in static or top level types
-312 = The type {0} cannot be the superclass of {1}; a superclass must be a class
-313 = The type {1} cannot subclass the final class {0}
-316 = Cycle detected: the type {0} cannot extend/implement itself or one of its own member types
-317 = Cycle detected: a cycle exists in the type hierarchy between {0} and {1}
-318 = The nested type {0} cannot hide an enclosing type
-319 = Duplicate nested type {0}
-320 = No exception of type {0} can be thrown; an exception type must be a subclass of Throwable
-321 = The package {0} collides with a type
-322 = The type {1} collides with a package
-323 = The type {1} is already defined
-324 = The type {0} cannot be resolved. It is indirectly referenced from required library files
-325 = The public type {1} must be defined in its own file
-326 = A package must be specified in {0} or a default package created
-327 = The hierarchy of the type {0} is inconsistent
-328 = The declared package "{1}" does not match the expected package "{0}"
-329 = The type java.lang.Object cannot have a superclass or superinterfaces
-330 = The type java.lang.Object must be a class
-
-340 = Duplicate field {0}.{1}
-341 = Duplicate modifier for the field {0}
-342 = Illegal modifier for the field {0}; only public, protected, private, static, final, transient & volatile are permitted
-344 = The field {0} can only set one of public / protected / private
-345 = The field {0} can be either final or volatile, not both
-346 = The field {0} cannot be declared static; static fields can only be declared in static or top level types
-
-355 = Duplicate function {0}({2}) in type {1}
-357 = Duplicate modifier for the function {1} in type {0}
-358 = Illegal modifier for the function {0}.{2}({1})
-360 = The function {1} in type {0} can only set one of public / protected / private
-361 = The function {1} cannot be declared static; static functions can only be declared in a static or top level type
-362 = The abstract function {1} in type {0} can only set a visibility modifier, one of public or protected
-363 = The abstract function {1} in type {0} can only be defined by an abstract class
-364 = void is an invalid type for the parameter {1} of the function {0}
-367 = The native function {1} cannot also be declared strictfp
-368 = Duplicate modifier for parameter {0}
-
-385 = The import {0} conflicts with a type defined in the same file
-386 = The import {0} collides with another import statement
-387 = Only a type can be imported. {0} resolves to a package
-388 = The import {0} is never used
-390 = The import {0} cannot be resolved
-
-395 = Duplicate modifier for the variable {0}
-
-400 = The type {3} must implement the inherited abstract function {2}.{0}({1})
-402 = Exception {0} is not compatible with throws clause in {1}
-403 = Exception {0} in throws clause of {1} is not compatible with {2}
-404 = The return type is incompatible with {0}
-405 = The inherited function {0} cannot hide the public abstract function in {1}
-406 = This instance function cannot override the static function from {0}
-407 = This static function cannot hide the instance function from {0}
-408 = The static function {0} conflicts with the abstract function in {1}
-409 = Cannot reduce the visibility of the inherited function from {0}
-410 = The function {0} does not override the inherited function from {1} since it is private to a different package
-411 = This class must implement the inherited abstract function {1}, but cannot override it since it is not visible from {0}. Either make the type abstract or make the inherited function visible
-412 = The function {0} overrides a deprecated function from {1}
-415 = The variable argument type {0} of the function {1} must be the last parameter
-416 = The function {0} is overriding a function without making a super invocation
-
-420 = Code snippet support cannot find the class {0}
-421 = Code snippet support cannot find the function {0}.{1}({2})
-
-430 = Too many constants, the constant pool for {0} would exceed 65536 entries
-431 = The type generates a string that requires more than 65535 bytes to encode in Utf8 format in the constant pool
-
-432 = Too many fields for type {0}. Maximum is 65535
-433 = Too many functions for type {0}. Maximum is 65535
-
-440 = ''{0}'' should not be used as an identifier, since it is a reserved keyword
-441 = 'enum' should not be used as an identifier, since it is a reserved keyword from source level 5.0 on
-
-450 = {0} {1}
-451 = Null pointer access: The variable {0} can only be null at this location
-452 = Potential null pointer access: The variable {0} may be null at this location
-453 = Redundant null check: The variable {0} can only be null at this location
-454 = Null comparison always yields false: The variable {0} can only be null at this location
-455 = Redundant assignment: The variable {0} can only be null at this location
-456 = instanceof always yields false: The variable {0} can only be null at this location
-457 = Redundant null check: The variable {0} cannot be null at this location
-458 = Null comparison always yields false: The variable {0} cannot be null at this location
-
-460 = Empty block should be documented
-
-### DOC
-
-465 = ''{0}'' visibility for malformed doc comments hides this ''{1}'' reference
-466 = Invalid member type qualification
-467 = Missing identifier
-468 = Cannot make a static reference to the non-static type variable {0}
-470 = Unexpected tag
-471 = Missing tag for parameter {0}
-472 = Missing parameter name
-473 = Duplicate tag for parameter
-474 = Parameter {0} is not declared
-475 = Missing tag for return type
-476 = Duplicate tag for return type
-477 = Missing tag for declared exception {0}
-478 = Missing class name
-479 = Invalid class name
-480 = Duplicate tag for thrown exception
-481 = Exception {0} is not declared
-482 = Missing reference
-483 = Invalid reference
-484 = Malformed link reference
-485 = Invalid parameters declaration
-486 = Missing comment for {0} declaration
-487 = Invalid tag
-488 = {0} cannot be resolved or is not a field
-489 = The field {0} is not visible
-490 = The field {0} is ambiguous
-491 = The field {0}.{1} is deprecated
-492 = The constructor {0}({1}) is undefined
-493 = The constructor {0}({1}) is not visible
-494 = The constructor {0}({1}) is ambiguous
-495 = The constructor {0}({1}) is deprecated
-496 = The function {1}({2}) is undefined for the type {0}
-497 = The function {1}({2}) from the file {0} is not visible
-498 = The function {1}({2}) is ambiguous for the type {0}
-499 = The function {1}({2}) from the file {0} is deprecated
-500 = Cannot invoke {1}({2}) on the primitive type {0}
-501 = The function {1}({2}) in the type {0} is not applicable for the arguments ({3})
-502 = Cannot invoke {1}({2}) on the array type {0}
-503 = {0} cannot be resolved to a type
-504 = The type {0} is not visible
-505 = The type {0} is ambiguous
-506 = The type {0} is deprecated
-507 = The nested type {0} cannot be referenced using its binary name
-508 = The function {1} is defined in an inherited type and an enclosing scope
-509 = The field {0} is defined in an inherited type and an enclosing scope
-510 = The type {0} is defined in an inherited type and an enclosing scope
-512 = Missing closing brace for inline tag
-513 = Malformed reference (missing end space separator)
-514 = JSdoc:
-515 = Missing #: "{0}"
-516 = Missing return type description
-518 = Unexpected text
-519 = Invalid param tag name
-
-### FOREACH
-580 = Type mismatch: cannot convert from element type {0} to {1}
-581 = Can only iterate over an array or an instance of java.lang.Iterable
-
-### SOURCE LEVEL
-592 = Syntax error, 'for each' statements are only available if source level is 5.0
-
-### CORRUPTED BINARIES
-700 = The class file {0} contains a signature ''{1}'' ill-formed at position {2}
-
-### CORRUPTED SOURCES
-701 = Cannot read the source from {0}; either the file uses a different encoding than {1} or it is corrupted
-702 = Cannot read the source from {0} due to internal exception {1}
-
-902 = Only 'set' is accepted at this location
-903 = Only 'get' is accepted at this location \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/CompoundNameVector.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/CompoundNameVector.java
deleted file mode 100644
index e7298de9..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/CompoundNameVector.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.util;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-
-public final class CompoundNameVector {
- static int INITIAL_SIZE = 10;
-
- public int size;
- int maxSize;
- char[][][] elements;
-public CompoundNameVector() {
- maxSize = INITIAL_SIZE;
- size = 0;
- elements = new char[maxSize][][];
-}
-public void add(char[][] newElement) {
- if (size == maxSize) // knows that size starts <= maxSize
- System.arraycopy(elements, 0, (elements = new char[maxSize *= 2][][]), 0, size);
- elements[size++] = newElement;
-}
-public void addAll(char[][][] newElements) {
- if (size + newElements.length >= maxSize) {
- maxSize = size + newElements.length; // assume no more elements will be added
- System.arraycopy(elements, 0, (elements = new char[maxSize][][]), 0, size);
- }
- System.arraycopy(newElements, 0, elements, size, newElements.length);
- size += newElements.length;
-}
-public boolean contains(char[][] element) {
- for (int i = size; --i >= 0;)
- if (CharOperation.equals(element, elements[i]))
- return true;
- return false;
-}
-public char[][] elementAt(int index) {
- return elements[index];
-}
-public char[][] remove(char[][] element) {
- // assumes only one occurrence of the element exists
- for (int i = size; --i >= 0;)
- if (element == elements[i]) {
- // shift the remaining elements down one spot
- System.arraycopy(elements, i + 1, elements, i, --size - i);
- elements[size] = null;
- return element;
- }
- return null;
-}
-public void removeAll() {
- for (int i = size; --i >= 0;)
- elements[i] = null;
- size = 0;
-}
-public String toString() {
- StringBuffer buffer = new StringBuffer();
- for (int i = 0; i < size; i++) {
- buffer.append(CharOperation.toString(elements[i])).append("\n"); //$NON-NLS-1$
- }
- return buffer.toString();
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/FloatUtil.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/FloatUtil.java
deleted file mode 100644
index 31623014..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/FloatUtil.java
+++ /dev/null
@@ -1,421 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.util;
-
-/**
- * Internal utility for declaing with hexadecimal double and float literals.
- *
- * @since 3.1
- */
-public class FloatUtil {
-
- private static final int DOUBLE_FRACTION_WIDTH = 52;
-
- private static final int DOUBLE_PRECISION = 53;
-
- private static final int MAX_DOUBLE_EXPONENT = +1023;
-
- private static final int MIN_NORMALIZED_DOUBLE_EXPONENT = -1022;
-
- private static final int MIN_UNNORMALIZED_DOUBLE_EXPONENT = MIN_NORMALIZED_DOUBLE_EXPONENT
- - DOUBLE_PRECISION;
-
- private static final int DOUBLE_EXPONENT_BIAS = +1023;
-
- private static final int DOUBLE_EXPONENT_SHIFT = 52;
-
- private static final int SINGLE_FRACTION_WIDTH = 23;
-
- private static final int SINGLE_PRECISION = 24;
-
- private static final int MAX_SINGLE_EXPONENT = +127;
-
- private static final int MIN_NORMALIZED_SINGLE_EXPONENT = -126;
-
- private static final int MIN_UNNORMALIZED_SINGLE_EXPONENT = MIN_NORMALIZED_SINGLE_EXPONENT
- - SINGLE_PRECISION;
-
- private static final int SINGLE_EXPONENT_BIAS = +127;
-
- private static final int SINGLE_EXPONENT_SHIFT = 23;
-
- /**
- * Returns the float value corresponding to the given
- * hexadecimal floating-point single precision literal.
- * The literal must be syntactially correct, and must be
- * a float literal (end in a 'f' or 'F'). It must not
- * include either leading or trailing whitespace or
- * a sign.
- * <p>
- * This method returns the same answer as
- * Float.parseFloat(new String(source)) does in JDK 1.5,
- * except that this method returns Floal.NaN if it
- * would underflow to 0 (parseFloat just returns 0).
- * The method handles all the tricky cases, including
- * fraction rounding to 24 bits and gradual underflow.
- * </p>
- *
- * @param source source string containing single precision
- * hexadecimal floating-point literal
- * @return the float value, including Float.POSITIVE_INFINITY
- * if the non-zero value is too large to be represented, and
- * Float.NaN if the non-zero value is too small to be represented
- */
- public static float valueOfHexFloatLiteral(char[] source) {
- long bits = convertHexFloatingPointLiteralToBits(source);
- return Float.intBitsToFloat((int) bits);
- }
-
- /**
- * Returns the double value corresponding to the given
- * hexadecimal floating-point double precision literal.
- * The literal must be syntactially correct, and must be
- * a double literal (end in an optional 'd' or 'D').
- * It must not include either leading or trailing whitespace or
- * a sign.
- * <p>
- * This method returns the same answer as
- * Double.parseDouble(new String(source)) does in JDK 1.5,
- * except that this method throw NumberFormatException in
- * the case of overflow to infinity or underflow to 0.
- * The method handles all the tricky cases, including
- * fraction rounding to 53 bits and gradual underflow.
- * </p>
- *
- * @param source source string containing double precision
- * hexadecimal floating-point literal
- * @return the double value, including Double.POSITIVE_INFINITY
- * if the non-zero value is too large to be represented, and
- * Double.NaN if the non-zero value is too small to be represented
- */
- public static double valueOfHexDoubleLiteral(char[] source) {
- long bits = convertHexFloatingPointLiteralToBits(source);
- return Double.longBitsToDouble(bits);
- }
-
- /**
- * Returns the given hexadecimal floating-point literal as
- * the bits for a single-precision (float) or a
- * double-precision (double) IEEE floating point number.
- * The literal must be syntactially correct. It must not
- * include either leading or trailing whitespace or a sign.
- *
- * @param source source string containing hexadecimal floating-point literal
- * @return for double precision literals, bits suitable
- * for passing to Double.longBitsToDouble; for single precision literals,
- * bits suitable for passing to Single.intBitsToDouble in the bottom
- * 32 bits of the result
- * @throws NumberFormatException if the number cannot be parsed
- */
- private static long convertHexFloatingPointLiteralToBits(char[] source) {
- int length = source.length;
- long mantissa = 0;
-
- // Step 1: process the '0x' lead-in
- int next = 0;
- char nextChar = source[next];
- nextChar = source[next];
- if (nextChar == '0') {
- next++;
- } else {
- throw new NumberFormatException();
- }
- nextChar = source[next];
- if (nextChar == 'X' || nextChar == 'x') {
- next++;
- } else {
- throw new NumberFormatException();
- }
-
- // Step 2: process leading '0's either before or after the '.'
- int binaryPointPosition = -1;
- loop: while (true) {
- nextChar = source[next];
- switch (nextChar) {
- case '0':
- next++;
- continue loop;
- case '.':
- binaryPointPosition = next;
- next++;
- continue loop;
- default:
- break loop;
- }
- }
-
- // Step 3: process the mantissa
- // leading zeros have been trimmed
- int mantissaBits = 0;
- int leadingDigitPosition = -1;
- loop: while (true) {
- nextChar = source[next];
- int hexdigit;
- switch (nextChar) {
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- hexdigit = nextChar - '0';
- break;
- case 'a':
- case 'b':
- case 'c':
- case 'd':
- case 'e':
- case 'f':
- hexdigit = (nextChar - 'a') + 10;
- break;
- case 'A':
- case 'B':
- case 'C':
- case 'D':
- case 'E':
- case 'F':
- hexdigit = (nextChar - 'A') + 10;
- break;
- case '.':
- binaryPointPosition = next;
- next++;
- continue loop;
- default:
- if (binaryPointPosition < 0) {
- // record virtual '.' as being to right of all digits
- binaryPointPosition = next;
- }
- break loop;
- }
- if (mantissaBits == 0) {
- // this is the first non-zero hex digit
- // ignore leading binary 0's in hex digit
- leadingDigitPosition = next;
- mantissa = hexdigit;
- mantissaBits = 4;
- } else if (mantissaBits < 60) {
- // middle hex digits
- mantissa <<= 4;
- mantissa |= hexdigit;
- mantissaBits += 4;
- } else {
- // more mantissa bits than we can handle
- // drop this hex digit on the ground
- }
- next++;
- continue loop;
- }
-
- // Step 4: process the 'P'
- nextChar = source[next];
- if (nextChar == 'P' || nextChar == 'p') {
- next++;
- } else {
- throw new NumberFormatException();
- }
-
- // Step 5: process the exponent
- int exponent = 0;
- int exponentSign = +1;
- loop: while (next < length) {
- nextChar = source[next];
- switch (nextChar) {
- case '+':
- exponentSign = +1;
- next++;
- continue loop;
- case '-':
- exponentSign = -1;
- next++;
- continue loop;
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- int digit = nextChar - '0';
- exponent = (exponent * 10) + digit;
- next++;
- continue loop;
- default:
- break loop;
- }
- }
-
- // Step 6: process the optional 'f' or 'd'
- boolean doublePrecision = true;
- if (next < length) {
- nextChar = source[next];
- switch (nextChar) {
- case 'f':
- case 'F':
- doublePrecision = false;
- next++;
- break;
- case 'd':
- case 'D':
- doublePrecision = true;
- next++;
- break;
- default:
- throw new NumberFormatException();
- }
- }
-
- // at this point, all the parsing is done
- // Step 7: handle mantissa of zero
- if (mantissa == 0) {
- return 0L;
- }
-
- // Step 8: normalize non-zero mantissa
- // mantissa is in right-hand mantissaBits
- // ensure that top bit (as opposed to hex digit) is 1
- int scaleFactorCompensation = 0;
- long top = (mantissa >>> (mantissaBits - 4));
- if ((top & 0x8) == 0) {
- mantissaBits--;
- scaleFactorCompensation++;
- if ((top & 0x4) == 0) {
- mantissaBits--;
- scaleFactorCompensation++;
- if ((top & 0x2) == 0) {
- mantissaBits--;
- scaleFactorCompensation++;
- }
- }
- }
-
- // Step 9: convert double literals to IEEE double
- long result = 0L;
- if (doublePrecision) {
- long fraction;
- if (mantissaBits > DOUBLE_PRECISION) {
- // more bits than we can keep
- int extraBits = mantissaBits - DOUBLE_PRECISION;
- // round to DOUBLE_PRECISION bits
- fraction = mantissa >>> (extraBits - 1);
- long lowBit = fraction & 0x1;
- fraction += lowBit;
- fraction = fraction >>> 1;
- if ((fraction & (1L << DOUBLE_PRECISION)) != 0) {
- fraction = fraction >>> 1;
- scaleFactorCompensation -= 1;
- }
- } else {
- // less bits than the faction can hold - pad on right with 0s
- fraction = mantissa << (DOUBLE_PRECISION - mantissaBits);
- }
-
- int scaleFactor = 0; // how many bits to move '.' to before leading hex digit
- if (mantissaBits > 0) {
- if (leadingDigitPosition < binaryPointPosition) {
- // e.g., 0x80.0p0 has scaleFactor == +8
- scaleFactor = 4 * (binaryPointPosition - leadingDigitPosition);
- // e.g., 0x10.0p0 has scaleFactorCompensation == +3
- scaleFactor -= scaleFactorCompensation;
- } else {
- // e.g., 0x0.08p0 has scaleFactor == -4
- scaleFactor = -4
- * (leadingDigitPosition - binaryPointPosition - 1);
- // e.g., 0x0.01p0 has scaleFactorCompensation == +3
- scaleFactor -= scaleFactorCompensation;
- }
- }
-
- int e = (exponentSign * exponent) + scaleFactor;
- if (e - 1 > MAX_DOUBLE_EXPONENT) {
- // overflow to +infinity
- result = Double.doubleToLongBits(Double.POSITIVE_INFINITY);
- } else if (e - 1 >= MIN_NORMALIZED_DOUBLE_EXPONENT) {
- // can be represented as a normalized double
- // the left most bit must be discarded (it's always a 1)
- long biasedExponent = e - 1 + DOUBLE_EXPONENT_BIAS;
- result = fraction & ~(1L << DOUBLE_FRACTION_WIDTH);
- result |= (biasedExponent << DOUBLE_EXPONENT_SHIFT);
- } else if (e - 1 > MIN_UNNORMALIZED_DOUBLE_EXPONENT) {
- // can be represented as an unnormalized double
- long biasedExponent = 0;
- result = fraction >>> (MIN_NORMALIZED_DOUBLE_EXPONENT - e + 1);
- result |= (biasedExponent << DOUBLE_EXPONENT_SHIFT);
- } else {
- // underflow - return Double.NaN
- result = Double.doubleToLongBits(Double.NaN);
- }
- return result;
- }
-
- // Step 10: convert float literals to IEEE single
- long fraction;
- if (mantissaBits > SINGLE_PRECISION) {
- // more bits than we can keep
- int extraBits = mantissaBits - SINGLE_PRECISION;
- // round to DOUBLE_PRECISION bits
- fraction = mantissa >>> (extraBits - 1);
- long lowBit = fraction & 0x1;
- fraction += lowBit;
- fraction = fraction >>> 1;
- if ((fraction & (1L << SINGLE_PRECISION)) != 0) {
- fraction = fraction >>> 1;
- scaleFactorCompensation -= 1;
- }
- } else {
- // less bits than the faction can hold - pad on right with 0s
- fraction = mantissa << (SINGLE_PRECISION - mantissaBits);
- }
-
- int scaleFactor = 0; // how many bits to move '.' to before leading hex digit
- if (mantissaBits > 0) {
- if (leadingDigitPosition < binaryPointPosition) {
- // e.g., 0x80.0p0 has scaleFactor == +8
- scaleFactor = 4 * (binaryPointPosition - leadingDigitPosition);
- // e.g., 0x10.0p0 has scaleFactorCompensation == +3
- scaleFactor -= scaleFactorCompensation;
- } else {
- // e.g., 0x0.08p0 has scaleFactor == -4
- scaleFactor = -4
- * (leadingDigitPosition - binaryPointPosition - 1);
- // e.g., 0x0.01p0 has scaleFactorCompensation == +3
- scaleFactor -= scaleFactorCompensation;
- }
- }
-
- int e = (exponentSign * exponent) + scaleFactor;
- if (e - 1 > MAX_SINGLE_EXPONENT) {
- // overflow to +infinity
- result = Float.floatToIntBits(Float.POSITIVE_INFINITY);
- } else if (e - 1 >= MIN_NORMALIZED_SINGLE_EXPONENT) {
- // can be represented as a normalized single
- // the left most bit must be discarded (it's always a 1)
- long biasedExponent = e - 1 + SINGLE_EXPONENT_BIAS;
- result = fraction & ~(1L << SINGLE_FRACTION_WIDTH);
- result |= (biasedExponent << SINGLE_EXPONENT_SHIFT);
- } else if (e - 1 > MIN_UNNORMALIZED_SINGLE_EXPONENT) {
- // can be represented as an unnormalized single
- long biasedExponent = 0;
- result = fraction >>> (MIN_NORMALIZED_SINGLE_EXPONENT - e + 1);
- result |= (biasedExponent << SINGLE_EXPONENT_SHIFT);
- } else {
- // underflow - return Float.NaN
- result = Float.floatToIntBits(Float.NaN);
- }
- return result;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/GenericXMLWriter.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/GenericXMLWriter.java
deleted file mode 100644
index 604abeb8..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/GenericXMLWriter.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.util;
-
-import java.io.OutputStream;
-import java.io.PrintWriter;
-import java.io.Writer;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.Map;
-
-public class GenericXMLWriter extends PrintWriter {
- /* constants */
- private static final String XML_VERSION= "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; //$NON-NLS-1$
- private static void appendEscapedChar(StringBuffer buffer, char c) {
- String replacement= getReplacement(c);
- if (replacement != null) {
- buffer.append('&');
- buffer.append(replacement);
- buffer.append(';');
- } else {
- buffer.append(c);
- }
- }
- private static String getEscaped(String s) {
- StringBuffer result= new StringBuffer(s.length() + 10);
- for (int i= 0; i < s.length(); ++i)
- appendEscapedChar(result, s.charAt(i));
- return result.toString();
- }
- private static String getReplacement(char c) {
- // Encode special XML characters into the equivalent character references.
- // These five are defined by default for all XML documents.
- switch (c) {
- case '<' :
- return "lt"; //$NON-NLS-1$
- case '>' :
- return "gt"; //$NON-NLS-1$
- case '"' :
- return "quot"; //$NON-NLS-1$
- case '\'' :
- return "apos"; //$NON-NLS-1$
- case '&' :
- return "amp"; //$NON-NLS-1$
- }
- return null;
- }
- private String lineSeparator;
- private int tab;
- public GenericXMLWriter(OutputStream stream, String lineSeparator, boolean printXmlVersion) {
- this(new PrintWriter(stream), lineSeparator, printXmlVersion);
- }
- public GenericXMLWriter(Writer writer, String lineSeparator, boolean printXmlVersion) {
- super(writer);
- this.tab= 0;
- this.lineSeparator = lineSeparator;
- if (printXmlVersion) {
- print(XML_VERSION);
- print(this.lineSeparator);
- }
- }
- public void endTag(String name, boolean insertTab, boolean insertNewLine) {
- this.tab --;
- printTag('/' + name, null/*no parameters*/, insertTab, insertNewLine, false/*don't close tag*/);
- }
- /*
- * External API
- */
- public void printString(String string, boolean insertTab, boolean insertNewLine) {
- if (insertTab) {
- printTabulation();
- }
- print(string);
- if (insertNewLine) {
- print(this.lineSeparator);
- }
- }
- private void printTabulation() {
- for (int i= 0; i < this.tab; i++) this.print('\t');
- }
- public void printTag(String name, HashMap parameters, boolean insertTab, boolean insertNewLine, boolean closeTag) {
- if (insertTab) {
- this.printTabulation();
- }
- this.print('<');
- this.print(name);
- if (parameters != null) {
- int length = parameters.size();
- Map.Entry[] entries = new Map.Entry[length];
- parameters.entrySet().toArray(entries);
- Arrays.sort(entries, new Comparator() {
- public int compare(Object o1, Object o2) {
- Map.Entry entry1 = (Map.Entry) o1;
- Map.Entry entry2 = (Map.Entry) o2;
- return ((String) entry1.getKey()).compareTo((String) entry2.getKey());
- }
- });
- for (int i = 0; i < length; i++) {
- this.print(' ');
- this.print(entries[i].getKey());
- this.print("=\""); //$NON-NLS-1$
- this.print(getEscaped(String.valueOf(entries[i].getValue())));
- this.print('\"');
- }
- }
- if (closeTag) {
- this.print("/>"); //$NON-NLS-1$
- } else {
- this.print(">"); //$NON-NLS-1$
- }
- if (insertNewLine) {
- print(this.lineSeparator);
- }
- if (parameters != null && !closeTag)
- this.tab++;
-
- }
- public void startTag(String name, boolean insertTab) {
- printTag(name, null/*no parameters*/, insertTab, true/*insert new line*/, false/*don't close tag*/);
- this.tab++;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfBinding.java
deleted file mode 100644
index 013676fb..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfBinding.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.util;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Binding;
-
-public final class HashtableOfBinding {
- // to avoid using Enumerations, walk the individual tables skipping nulls
- public char[] keyTable[];
- public Binding valueTable[];
-
- public int elementSize; // number of elements in the table
- int threshold;
-public HashtableOfBinding() {
- this(3);
-}
-public HashtableOfBinding(int size) {
- this.elementSize = 0;
- this.threshold = size; // size represents the expected number of elements
- int extraRoom = (int) (size * 1.75f);
- if (this.threshold == extraRoom)
- extraRoom++;
- this.keyTable = new char[extraRoom][];
- this.valueTable = new Binding[extraRoom];
-}
-public boolean containsKey(char[] key) {
- int length = keyTable.length,
- index = CharOperation.hashCode(key) % length;
- int keyLength = key.length;
- char[] currentKey;
- while ((currentKey = keyTable[index]) != null) {
- if (currentKey.length == keyLength && CharOperation.equals(currentKey, key))
- return true;
- if (++index == length) {
- index = 0;
- }
- }
- return false;
-}
-public Binding get(char[] key) {
- int length = keyTable.length,
- index = CharOperation.hashCode(key) % length;
- int keyLength = key.length;
- char[] currentKey;
- while ((currentKey = keyTable[index]) != null) {
- if (currentKey.length == keyLength && CharOperation.equals(currentKey, key))
- return valueTable[index];
- if (++index == length) {
- index = 0;
- }
- }
- return null;
-}
-public Binding put(char[] key, Binding value) {
- int length = keyTable.length,
- index = CharOperation.hashCode(key) % length;
- int keyLength = key.length;
- char[] currentKey;
- while ((currentKey = keyTable[index]) != null) {
- if (currentKey.length == keyLength && CharOperation.equals(currentKey, key))
- return valueTable[index] = value;
- if (++index == length) {
- index = 0;
- }
- }
- keyTable[index] = key;
- valueTable[index] = value;
-
- // assumes the threshold is never equal to the size of the table
- if (++elementSize > threshold)
- rehash();
- return value;
-}
-private void rehash() {
- HashtableOfBinding newHashtable = new HashtableOfBinding(elementSize < 100 ? 100 : elementSize * 2); // double the number of expected elements
- char[] currentKey;
- for (int i = keyTable.length; --i >= 0;)
- if ((currentKey = keyTable[i]) != null)
- newHashtable.put(currentKey, valueTable[i]);
-
- this.keyTable = newHashtable.keyTable;
- this.valueTable = newHashtable.valueTable;
- this.threshold = newHashtable.threshold;
-}
-public int size() {
- return elementSize;
-}
-public String toString() {
- String s = ""; //$NON-NLS-1$
- Binding type;
- for (int i = 0, length = valueTable.length; i < length; i++)
- if ((type = valueTable[i]) != null)
- s += type.toString() + "\n"; //$NON-NLS-1$
- return s;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfInt.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfInt.java
deleted file mode 100644
index f1c22232..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfInt.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.util;
-
- /**
- * Hashtable for non-zero int keys.
- */
-
-public final class HashtableOfInt {
- // to avoid using Enumerations, walk the individual tables skipping nulls
- public int[] keyTable;
- public Object[] valueTable;
-
- public int elementSize; // number of elements in the table
- int threshold;
-public HashtableOfInt() {
- this(13);
-}
-public HashtableOfInt(int size) {
- this.elementSize = 0;
- this.threshold = size; // size represents the expected number of elements
- int extraRoom = (int) (size * 1.75f);
- if (this.threshold == extraRoom)
- extraRoom++;
- this.keyTable = new int[extraRoom];
- this.valueTable = new Object[extraRoom];
-}
-public boolean containsKey(int key) {
- int length = keyTable.length, index = key % length;
- int currentKey;
- while ((currentKey = keyTable[index]) != 0) {
- if (currentKey == key)
- return true;
- if (++index == length) {
- index = 0;
- }
- }
- return false;
-}
-public Object get(int key) {
- int length = keyTable.length, index = key % length;
- int currentKey;
- while ((currentKey = keyTable[index]) != 0) {
- if (currentKey == key) return valueTable[index];
- if (++index == length) {
- index = 0;
- }
- }
- return null;
-}
-public Object put(int key, Object value) {
- int length = keyTable.length, index = key % length;
- int currentKey;
- while ((currentKey = keyTable[index]) != 0) {
- if (currentKey == key) return valueTable[index] = value;
- if (++index == length) {
- index = 0;
- }
- }
- keyTable[index] = key;
- valueTable[index] = value;
-
- // assumes the threshold is never equal to the size of the table
- if (++elementSize > threshold)
- rehash();
- return value;
-}
-private void rehash() {
- HashtableOfInt newHashtable = new HashtableOfInt(elementSize * 2); // double the number of expected elements
- int currentKey;
- for (int i = keyTable.length; --i >= 0;)
- if ((currentKey = keyTable[i]) != 0)
- newHashtable.put(currentKey, valueTable[i]);
-
- this.keyTable = newHashtable.keyTable;
- this.valueTable = newHashtable.valueTable;
- this.threshold = newHashtable.threshold;
-}
-public int size() {
- return elementSize;
-}
-public String toString() {
- String s = ""; //$NON-NLS-1$
- Object object;
- for (int i = 0, length = valueTable.length; i < length; i++)
- if ((object = valueTable[i]) != null)
- s += keyTable[i] + " -> " + object.toString() + "\n"; //$NON-NLS-2$ //$NON-NLS-1$
- return s;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfIntValues.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfIntValues.java
deleted file mode 100644
index af522c06..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfIntValues.java
+++ /dev/null
@@ -1,156 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.util;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-
-/**
- * Hashtable of {char[] --> int}
- */
-public final class HashtableOfIntValues implements Cloneable {
-
- public static final int NO_VALUE = Integer.MIN_VALUE;
-
- // to avoid using Enumerations, walk the individual tables skipping nulls
- public char[] keyTable[];
- public int valueTable[];
-
- public int elementSize; // number of elements in the table
- int threshold;
-
- public HashtableOfIntValues() {
- this(13);
- }
-
- public HashtableOfIntValues(int size) {
-
- this.elementSize = 0;
- this.threshold = size; // size represents the expected number of elements
- int extraRoom = (int) (size * 1.75f);
- if (this.threshold == extraRoom)
- extraRoom++;
- this.keyTable = new char[extraRoom][];
- this.valueTable = new int[extraRoom];
- }
-
- public Object clone() throws CloneNotSupportedException {
- HashtableOfIntValues result = (HashtableOfIntValues) super.clone();
- result.elementSize = this.elementSize;
- result.threshold = this.threshold;
-
- int length = this.keyTable.length;
- result.keyTable = new char[length][];
- System.arraycopy(this.keyTable, 0, result.keyTable, 0, length);
-
- length = this.valueTable.length;
- result.valueTable = new int[length];
- System.arraycopy(this.valueTable, 0, result.valueTable, 0, length);
- return result;
- }
-
- public boolean containsKey(char[] key) {
- int length = keyTable.length,
- index = CharOperation.hashCode(key) % length;
- int keyLength = key.length;
- char[] currentKey;
- while ((currentKey = keyTable[index]) != null) {
- if (currentKey.length == keyLength && CharOperation.equals(currentKey, key))
- return true;
- if (++index == length) {
- index = 0;
- }
- }
- return false;
- }
-
- public int get(char[] key) {
- int length = keyTable.length,
- index = CharOperation.hashCode(key) % length;
- int keyLength = key.length;
- char[] currentKey;
- while ((currentKey = keyTable[index]) != null) {
- if (currentKey.length == keyLength && CharOperation.equals(currentKey, key))
- return valueTable[index];
- if (++index == length) {
- index = 0;
- }
- }
- return NO_VALUE;
- }
-
- public int put(char[] key, int value) {
- int length = keyTable.length,
- index = CharOperation.hashCode(key) % length;
- int keyLength = key.length;
- char[] currentKey;
- while ((currentKey = keyTable[index]) != null) {
- if (currentKey.length == keyLength && CharOperation.equals(currentKey, key))
- return valueTable[index] = value;
- if (++index == length) {
- index = 0;
- }
- }
- keyTable[index] = key;
- valueTable[index] = value;
-
- // assumes the threshold is never equal to the size of the table
- if (++elementSize > threshold)
- rehash();
- return value;
- }
-
- public int removeKey(char[] key) {
- int length = keyTable.length,
- index = CharOperation.hashCode(key) % length;
- int keyLength = key.length;
- char[] currentKey;
- while ((currentKey = keyTable[index]) != null) {
- if (currentKey.length == keyLength && CharOperation.equals(currentKey, key)) {
- int value = valueTable[index];
- elementSize--;
- keyTable[index] = null;
- valueTable[index] = NO_VALUE;
- rehash();
- return value;
- }
- if (++index == length) {
- index = 0;
- }
- }
- return NO_VALUE;
- }
-
- private void rehash() {
-
- HashtableOfIntValues newHashtable = new HashtableOfIntValues(elementSize * 2); // double the number of expected elements
- char[] currentKey;
- for (int i = keyTable.length; --i >= 0;)
- if ((currentKey = keyTable[i]) != null)
- newHashtable.put(currentKey, valueTable[i]);
-
- this.keyTable = newHashtable.keyTable;
- this.valueTable = newHashtable.valueTable;
- this.threshold = newHashtable.threshold;
- }
-
- public int size() {
- return elementSize;
- }
-
- public String toString() {
- String s = ""; //$NON-NLS-1$
- char[] key;
- for (int i = 0, length = valueTable.length; i < length; i++)
- if ((key = keyTable[i]) != null)
- s += new String(key) + " -> " + valueTable[i] + "\n"; //$NON-NLS-2$ //$NON-NLS-1$
- return s;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfLong.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfLong.java
deleted file mode 100644
index 547a492b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfLong.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.util;
-
- /**
- * Hashtable for non-zero long keys.
- */
-
-public final class HashtableOfLong {
- // to avoid using Enumerations, walk the individual tables skipping nulls
- public long[] keyTable;
- public Object[] valueTable;
-
- public int elementSize; // number of elements in the table
- int threshold;
-public HashtableOfLong() {
- this(13);
-}
-public HashtableOfLong(int size) {
- this.elementSize = 0;
- this.threshold = size; // size represents the expected number of elements
- int extraRoom = (int) (size * 1.75f);
- if (this.threshold == extraRoom)
- extraRoom++;
- this.keyTable = new long[extraRoom];
- this.valueTable = new Object[extraRoom];
-}
-public boolean containsKey(long key) {
- int length = keyTable.length,
- index = ((int)(key >>> 32)) % length;
- long currentKey;
- while ((currentKey = keyTable[index]) != 0) {
- if (currentKey == key)
- return true;
- if (++index == length) {
- index = 0;
- }
- }
- return false;
-}
-public Object get(long key) {
- int length = keyTable.length,
- index = ((int)(key >>> 32)) % length;
- long currentKey;
- while ((currentKey = keyTable[index]) != 0) {
- if (currentKey == key) return valueTable[index];
- if (++index == length) {
- index = 0;
- }
- }
- return null;
-}
-public Object put(long key, Object value) {
- int length = keyTable.length,
- index = ((int)(key >>> 32)) % length;
- long currentKey;
- while ((currentKey = keyTable[index]) != 0) {
- if (currentKey == key) return valueTable[index] = value;
- if (++index == length) {
- index = 0;
- }
- }
- keyTable[index] = key;
- valueTable[index] = value;
-
- // assumes the threshold is never equal to the size of the table
- if (++elementSize > threshold)
- rehash();
- return value;
-}
-private void rehash() {
- HashtableOfLong newHashtable = new HashtableOfLong(elementSize * 2); // double the number of expected elements
- long currentKey;
- for (int i = keyTable.length; --i >= 0;)
- if ((currentKey = keyTable[i]) != 0)
- newHashtable.put(currentKey, valueTable[i]);
-
- this.keyTable = newHashtable.keyTable;
- this.valueTable = newHashtable.valueTable;
- this.threshold = newHashtable.threshold;
-}
-public int size() {
- return elementSize;
-}
-public String toString() {
- String s = ""; //$NON-NLS-1$
- Object object;
- for (int i = 0, length = valueTable.length; i < length; i++)
- if ((object = valueTable[i]) != null)
- s += keyTable[i] + " -> " + object.toString() + "\n"; //$NON-NLS-2$ //$NON-NLS-1$
- return s;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfObject.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfObject.java
deleted file mode 100644
index c3589b5b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfObject.java
+++ /dev/null
@@ -1,162 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.util;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-
-/**
- * Hashtable of {char[] --> Object }
- */
-public final class HashtableOfObject implements Cloneable {
-
- // to avoid using Enumerations, walk the individual tables skipping nulls
- public char[] keyTable[];
- public Object valueTable[];
-
- public int elementSize; // number of elements in the table
- int threshold;
-
- public HashtableOfObject() {
- this(13);
- }
-
- public HashtableOfObject(int size) {
-
- this.elementSize = 0;
- this.threshold = size; // size represents the expected number of elements
- int extraRoom = (int) (size * 1.75f);
- if (this.threshold == extraRoom)
- extraRoom++;
- this.keyTable = new char[extraRoom][];
- this.valueTable = new Object[extraRoom];
- }
-
- public void clear() {
- for (int i = this.keyTable.length; --i >= 0;) {
- this.keyTable[i] = null;
- this.valueTable[i] = null;
- }
- this.elementSize = 0;
- }
-
- public Object clone() throws CloneNotSupportedException {
- HashtableOfObject result = (HashtableOfObject) super.clone();
- result.elementSize = this.elementSize;
- result.threshold = this.threshold;
-
- int length = this.keyTable.length;
- result.keyTable = new char[length][];
- System.arraycopy(this.keyTable, 0, result.keyTable, 0, length);
-
- length = this.valueTable.length;
- result.valueTable = new Object[length];
- System.arraycopy(this.valueTable, 0, result.valueTable, 0, length);
- return result;
- }
-
- public boolean containsKey(char[] key) {
- int length = keyTable.length,
- index = CharOperation.hashCode(key) % length;
- int keyLength = key.length;
- char[] currentKey;
- while ((currentKey = keyTable[index]) != null) {
- if (currentKey.length == keyLength && CharOperation.equals(currentKey, key))
- return true;
- if (++index == length) {
- index = 0;
- }
- }
- return false;
- }
-
- public Object get(char[] key) {
- int length = keyTable.length,
- index = CharOperation.hashCode(key) % length;
- int keyLength = key.length;
- char[] currentKey;
- while ((currentKey = keyTable[index]) != null) {
- if (currentKey.length == keyLength && CharOperation.equals(currentKey, key))
- return valueTable[index];
- if (++index == length) {
- index = 0;
- }
- }
- return null;
- }
-
- public Object put(char[] key, Object value) {
- int length = keyTable.length,
- index = CharOperation.hashCode(key) % length;
- int keyLength = key.length;
- char[] currentKey;
- while ((currentKey = keyTable[index]) != null) {
- if (currentKey.length == keyLength && CharOperation.equals(currentKey, key))
- return valueTable[index] = value;
- if (++index == length) {
- index = 0;
- }
- }
- keyTable[index] = key;
- valueTable[index] = value;
-
- // assumes the threshold is never equal to the size of the table
- if (++elementSize > threshold)
- rehash();
- return value;
- }
-
- public Object removeKey(char[] key) {
- int length = keyTable.length,
- index = CharOperation.hashCode(key) % length;
- int keyLength = key.length;
- char[] currentKey;
- while ((currentKey = keyTable[index]) != null) {
- if (currentKey.length == keyLength && CharOperation.equals(currentKey, key)) {
- Object value = valueTable[index];
- elementSize--;
- keyTable[index] = null;
- valueTable[index] = null;
- rehash();
- return value;
- }
- if (++index == length) {
- index = 0;
- }
- }
- return null;
- }
-
- private void rehash() {
-
- HashtableOfObject newHashtable = new HashtableOfObject(elementSize * 2); // double the number of expected elements
- char[] currentKey;
- for (int i = keyTable.length; --i >= 0;)
- if ((currentKey = keyTable[i]) != null)
- newHashtable.put(currentKey, valueTable[i]);
-
- this.keyTable = newHashtable.keyTable;
- this.valueTable = newHashtable.valueTable;
- this.threshold = newHashtable.threshold;
- }
-
- public int size() {
- return elementSize;
- }
-
- public String toString() {
- String s = ""; //$NON-NLS-1$
- Object object;
- for (int i = 0, length = valueTable.length; i < length; i++)
- if ((object = valueTable[i]) != null)
- s += new String(keyTable[i]) + " -> " + object.toString() + "\n"; //$NON-NLS-2$ //$NON-NLS-1$
- return s;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfObjectToInt.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfObjectToInt.java
deleted file mode 100644
index c2de6854..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfObjectToInt.java
+++ /dev/null
@@ -1,155 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.util;
-
-/**
- * Hashtable of {Object --> int }
- */
-public final class HashtableOfObjectToInt implements Cloneable {
-
- // to avoid using Enumerations, walk the individual tables skipping nulls
- public Object[] keyTable;
- public int[] valueTable;
-
- public int elementSize; // number of elements in the table
- int threshold;
-
- public HashtableOfObjectToInt() {
- this(13);
- }
-
- public HashtableOfObjectToInt(int size) {
-
- this.elementSize = 0;
- this.threshold = size; // size represents the expected number of elements
- int extraRoom = (int) (size * 1.75f);
- if (this.threshold == extraRoom)
- extraRoom++;
- this.keyTable = new Object[extraRoom];
- this.valueTable = new int[extraRoom];
- }
-
- public Object clone() throws CloneNotSupportedException {
- HashtableOfObjectToInt result = (HashtableOfObjectToInt) super.clone();
- result.elementSize = this.elementSize;
- result.threshold = this.threshold;
-
- int length = this.keyTable.length;
- result.keyTable = new Object[length];
- System.arraycopy(this.keyTable, 0, result.keyTable, 0, length);
-
- length = this.valueTable.length;
- result.valueTable = new int[length];
- System.arraycopy(this.valueTable, 0, result.valueTable, 0, length);
- return result;
- }
-
- public boolean containsKey(Object key) {
- int length = this.keyTable.length,
- index = (key.hashCode()& 0x7FFFFFFF) % length;
- Object currentKey;
- while ((currentKey = this.keyTable[index]) != null) {
- if (currentKey.equals(key))
- return true;
- if (++index == length) {
- index = 0;
- }
- }
- return false;
- }
-
- public int get(Object key) {
- int length = this.keyTable.length,
- index = (key.hashCode()& 0x7FFFFFFF) % length;
- Object currentKey;
- while ((currentKey = this.keyTable[index]) != null) {
- if (currentKey.equals(key))
- return this.valueTable[index];
- if (++index == length) {
- index = 0;
- }
- }
- return -1;
- }
-
- public void keysToArray(Object[] array) {
- int index = 0;
- for (int i=0, length=this.keyTable.length; i<length; i++) {
- if (this.keyTable[i] != null)
- array[index++] = this.keyTable[i];
- }
- }
-
- public int put(Object key, int value) {
- int length = this.keyTable.length,
- index = (key.hashCode()& 0x7FFFFFFF) % length;
- Object currentKey;
- while ((currentKey = this.keyTable[index]) != null) {
- if (currentKey.equals(key))
- return this.valueTable[index] = value;
- if (++index == length) {
- index = 0;
- }
- }
- this.keyTable[index] = key;
- this.valueTable[index] = value;
-
- // assumes the threshold is never equal to the size of the table
- if (++elementSize > threshold)
- rehash();
- return value;
- }
-
- public int removeKey(Object key) {
- int length = this.keyTable.length,
- index = (key.hashCode()& 0x7FFFFFFF) % length;
- Object currentKey;
- while ((currentKey = this.keyTable[index]) != null) {
- if (currentKey.equals(key)) {
- int value = this.valueTable[index];
- elementSize--;
- this.keyTable[index] = null;
- rehash();
- return value;
- }
- if (++index == length) {
- index = 0;
- }
- }
- return -1;
- }
-
- private void rehash() {
-
- HashtableOfObjectToInt newHashtable = new HashtableOfObjectToInt(elementSize * 2); // double the number of expected elements
- Object currentKey;
- for (int i = this.keyTable.length; --i >= 0;)
- if ((currentKey = this.keyTable[i]) != null)
- newHashtable.put(currentKey, this.valueTable[i]);
-
- this.keyTable = newHashtable.keyTable;
- this.valueTable = newHashtable.valueTable;
- this.threshold = newHashtable.threshold;
- }
-
- public int size() {
- return elementSize;
- }
-
- public String toString() {
- String s = ""; //$NON-NLS-1$
- Object key;
- for (int i = 0, length = this.keyTable.length; i < length; i++)
- if ((key = this.keyTable[i]) != null)
- s += key + " -> " + this.valueTable[i] + "\n"; //$NON-NLS-2$ //$NON-NLS-1$
- return s;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfObjectToIntArray.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfObjectToIntArray.java
deleted file mode 100644
index 0c10d581..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfObjectToIntArray.java
+++ /dev/null
@@ -1,155 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.util;
-
-/**
- * Hashtable of {Object --> int[] }
- */
-public final class HashtableOfObjectToIntArray implements Cloneable {
-
- // to avoid using Enumerations, walk the individual tables skipping nulls
- public Object[] keyTable;
- public int[][] valueTable;
-
- public int elementSize; // number of elements in the table
- int threshold;
-
- public HashtableOfObjectToIntArray() {
- this(13);
- }
-
- public HashtableOfObjectToIntArray(int size) {
-
- this.elementSize = 0;
- this.threshold = size; // size represents the expected number of elements
- int extraRoom = (int) (size * 1.75f);
- if (this.threshold == extraRoom)
- extraRoom++;
- this.keyTable = new Object[extraRoom];
- this.valueTable = new int[extraRoom][];
- }
-
- public Object clone() throws CloneNotSupportedException {
- HashtableOfObjectToIntArray result = (HashtableOfObjectToIntArray) super.clone();
- result.elementSize = this.elementSize;
- result.threshold = this.threshold;
-
- int length = this.keyTable.length;
- result.keyTable = new Object[length];
- System.arraycopy(this.keyTable, 0, result.keyTable, 0, length);
-
- length = this.valueTable.length;
- result.valueTable = new int[length][];
- System.arraycopy(this.valueTable, 0, result.valueTable, 0, length);
- return result;
- }
-
- public boolean containsKey(Object key) {
- int length = this.keyTable.length,
- index = (key.hashCode()& 0x7FFFFFFF) % length;
- Object currentKey;
- while ((currentKey = this.keyTable[index]) != null) {
- if (currentKey.equals(key))
- return true;
- if (++index == length) {
- index = 0;
- }
- }
- return false;
- }
-
- public int[] get(Object key) {
- int length = this.keyTable.length,
- index = (key.hashCode()& 0x7FFFFFFF) % length;
- Object currentKey;
- while ((currentKey = this.keyTable[index]) != null) {
- if (currentKey.equals(key))
- return this.valueTable[index];
- if (++index == length) {
- index = 0;
- }
- }
- return null;
- }
-
- public void keysToArray(Object[] array) {
- int index = 0;
- for (int i=0, length=this.keyTable.length; i<length; i++) {
- if (this.keyTable[i] != null)
- array[index++] = this.keyTable[i];
- }
- }
-
- public int[] put(Object key, int[] value) {
- int length = this.keyTable.length,
- index = (key.hashCode()& 0x7FFFFFFF) % length;
- Object currentKey;
- while ((currentKey = this.keyTable[index]) != null) {
- if (currentKey.equals(key))
- return this.valueTable[index] = value;
- if (++index == length) {
- index = 0;
- }
- }
- this.keyTable[index] = key;
- this.valueTable[index] = value;
-
- // assumes the threshold is never equal to the size of the table
- if (++elementSize > threshold)
- rehash();
- return value;
- }
-
- public int[] removeKey(Object key) {
- int length = this.keyTable.length,
- index = (key.hashCode()& 0x7FFFFFFF) % length;
- Object currentKey;
- while ((currentKey = this.keyTable[index]) != null) {
- if (currentKey.equals(key)) {
- int[] value = this.valueTable[index];
- elementSize--;
- this.keyTable[index] = null;
- rehash();
- return value;
- }
- if (++index == length) {
- index = 0;
- }
- }
- return null;
- }
-
- private void rehash() {
-
- HashtableOfObjectToIntArray newHashtable = new HashtableOfObjectToIntArray(elementSize * 2); // double the number of expected elements
- Object currentKey;
- for (int i = this.keyTable.length; --i >= 0;)
- if ((currentKey = this.keyTable[i]) != null)
- newHashtable.put(currentKey, this.valueTable[i]);
-
- this.keyTable = newHashtable.keyTable;
- this.valueTable = newHashtable.valueTable;
- this.threshold = newHashtable.threshold;
- }
-
- public int size() {
- return elementSize;
- }
-
- public String toString() {
- String s = ""; //$NON-NLS-1$
- Object key;
- for (int i = 0, length = this.keyTable.length; i < length; i++)
- if ((key = this.keyTable[i]) != null)
- s += key + " -> " + this.valueTable[i] + "\n"; //$NON-NLS-2$ //$NON-NLS-1$
- return s;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfPackage.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfPackage.java
deleted file mode 100644
index 89634ab2..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfPackage.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.util;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding;
-
-public final class HashtableOfPackage {
- // to avoid using Enumerations, walk the individual tables skipping nulls
- public char[] keyTable[];
- public PackageBinding valueTable[];
-
- public int elementSize; // number of elements in the table
- int threshold;
-public HashtableOfPackage() {
- this(3); // usually not very large
-}
-public HashtableOfPackage(int size) {
- this.elementSize = 0;
- this.threshold = size; // size represents the expected number of elements
- int extraRoom = (int) (size * 1.75f);
- if (this.threshold == extraRoom)
- extraRoom++;
- this.keyTable = new char[extraRoom][];
- this.valueTable = new PackageBinding[extraRoom];
-}
-public boolean containsKey(char[] key) {
- int length = keyTable.length,
- index = CharOperation.hashCode(key) % length;
- int keyLength = key.length;
- char[] currentKey;
- while ((currentKey = keyTable[index]) != null) {
- if (currentKey.length == keyLength && CharOperation.equals(currentKey, key))
- return true;
- if (++index == length) {
- index = 0;
- }
- }
- return false;
-}
-public PackageBinding get(char[] key) {
- int length = keyTable.length,
- index = CharOperation.hashCode(key) % length;
- int keyLength = key.length;
- char[] currentKey;
- while ((currentKey = keyTable[index]) != null) {
- if (currentKey.length == keyLength && CharOperation.equals(currentKey, key))
- return valueTable[index];
- if (++index == length) {
- index = 0;
- }
- }
- return null;
-}
-public PackageBinding put(char[] key, PackageBinding value) {
- int length = keyTable.length,
- index = CharOperation.hashCode(key) % length;
- int keyLength = key.length;
- char[] currentKey;
- while ((currentKey = keyTable[index]) != null) {
- if (currentKey.length == keyLength && CharOperation.equals(currentKey, key))
- return valueTable[index] = value;
- if (++index == length) {
- index = 0;
- }
- }
- keyTable[index] = key;
- valueTable[index] = value;
-
- // assumes the threshold is never equal to the size of the table
- if (++elementSize > threshold)
- rehash();
- return value;
-}
-private void rehash() {
- HashtableOfPackage newHashtable = new HashtableOfPackage(elementSize * 2); // double the number of expected elements
- char[] currentKey;
- for (int i = keyTable.length; --i >= 0;)
- if ((currentKey = keyTable[i]) != null)
- newHashtable.put(currentKey, valueTable[i]);
-
- this.keyTable = newHashtable.keyTable;
- this.valueTable = newHashtable.valueTable;
- this.threshold = newHashtable.threshold;
-}
-public int size() {
- return elementSize;
-}
-public String toString() {
- String s = ""; //$NON-NLS-1$
- PackageBinding pkg;
- for (int i = 0, length = valueTable.length; i < length; i++)
- if ((pkg = valueTable[i]) != null)
- s += pkg.toString() + "\n"; //$NON-NLS-1$
- return s;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfType.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfType.java
deleted file mode 100644
index d9d32269..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/HashtableOfType.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.util;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding;
-
-public final class HashtableOfType {
- // to avoid using Enumerations, walk the individual tables skipping nulls
- public char[] keyTable[];
- public ReferenceBinding valueTable[];
-
- public int elementSize; // number of elements in the table
- int threshold;
-public HashtableOfType() {
- this(3);
-}
-public HashtableOfType(int size) {
- this.elementSize = 0;
- this.threshold = size; // size represents the expected number of elements
- int extraRoom = (int) (size * 1.75f);
- if (this.threshold == extraRoom)
- extraRoom++;
- this.keyTable = new char[extraRoom][];
- this.valueTable = new ReferenceBinding[extraRoom];
-}
-public boolean containsKey(char[] key) {
- int length = keyTable.length,
- index = CharOperation.hashCode(key) % length;
- int keyLength = key.length;
- char[] currentKey;
- while ((currentKey = keyTable[index]) != null) {
- if (currentKey.length == keyLength && CharOperation.equals(currentKey, key))
- return true;
- if (++index == length) {
- index = 0;
- }
- }
- return false;
-}
-public ReferenceBinding get(char[] key) {
- int length = keyTable.length,
- index = CharOperation.hashCode(key) % length;
- int keyLength = key.length;
- char[] currentKey;
- while ((currentKey = keyTable[index]) != null) {
- if (currentKey.length == keyLength && CharOperation.equals(currentKey, key))
- return valueTable[index];
- if (++index == length) {
- index = 0;
- }
- }
- return null;
-}
-public ReferenceBinding put(char[] key, ReferenceBinding value) {
- int length = keyTable.length,
- index = CharOperation.hashCode(key) % length;
- int keyLength = key.length;
- char[] currentKey;
- while ((currentKey = keyTable[index]) != null) {
- if (currentKey.length == keyLength && CharOperation.equals(currentKey, key))
- return valueTable[index] = value;
- if (++index == length) {
- index = 0;
- }
- }
- keyTable[index] = key;
- valueTable[index] = value;
-
- // assumes the threshold is never equal to the size of the table
- if (++elementSize > threshold)
- rehash();
- return value;
-}
-private void rehash() {
- HashtableOfType newHashtable = new HashtableOfType(elementSize < 100 ? 100 : elementSize * 2); // double the number of expected elements
- char[] currentKey;
- for (int i = keyTable.length; --i >= 0;)
- if ((currentKey = keyTable[i]) != null)
- newHashtable.put(currentKey, valueTable[i]);
-
- this.keyTable = newHashtable.keyTable;
- this.valueTable = newHashtable.valueTable;
- this.threshold = newHashtable.threshold;
-}
-public int size() {
- return elementSize;
-}
-public String toString() {
- String s = ""; //$NON-NLS-1$
- ReferenceBinding type;
- for (int i = 0, length = valueTable.length; i < length; i++)
- if ((type = valueTable[i]) != null)
- s += type.toString() + "\n"; //$NON-NLS-1$
- return s;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/Messages.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/Messages.java
deleted file mode 100644
index dcf08211..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/Messages.java
+++ /dev/null
@@ -1,245 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.util;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.lang.reflect.Field;
-import java.lang.reflect.Modifier;
-import java.text.MessageFormat;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Properties;
-
-public final class Messages {
- private static class MessagesProperties extends Properties {
-
- private static final int MOD_EXPECTED = Modifier.PUBLIC | Modifier.STATIC;
- private static final int MOD_MASK = MOD_EXPECTED | Modifier.FINAL;
- private static final long serialVersionUID = 1L;
-
- private final Map fields;
-
- public MessagesProperties(Field[] fieldArray, String bundleName) {
- super();
- final int len = fieldArray.length;
- fields = new HashMap(len * 2);
- for (int i = 0; i < len; i++) {
- fields.put(fieldArray[i].getName(), fieldArray[i]);
- }
- }
-
- /* (non-Javadoc)
- * @see java.util.Hashtable#put(java.lang.Object, java.lang.Object)
- */
- public synchronized Object put(Object key, Object value) {
- try {
- Field field = (Field) fields.get(key);
- if (field == null) {
- return null;
- }
- //can only set value of public static non-final fields
- if ((field.getModifiers() & MOD_MASK) != MOD_EXPECTED)
- return null;
- // Set the value into the field. We should never get an exception here because
- // we know we have a public static non-final field. If we do get an exception, silently
- // log it and continue. This means that the field will (most likely) be un-initialized and
- // will fail later in the code and if so then we will see both the NPE and this error.
- try {
- field.set(null, value);
- } catch (Exception e) {
- // ignore
- }
- } catch (SecurityException e) {
- // ignore
- }
- return null;
- }
- }
-
-
- private static String[] nlSuffixes;
- private static final String EXTENSION = ".properties"; //$NON-NLS-1$
-
- private static final String BUNDLE_NAME = "org.eclipse.wst.jsdt.internal.compiler.messages";//$NON-NLS-1$
-
- private Messages() {
- // Do not instantiate
- }
-
- public static String compilation_unresolvedProblem;
- public static String compilation_unresolvedProblems;
- public static String compilation_request;
- public static String compilation_loadBinary;
- public static String compilation_process;
- public static String compilation_write;
- public static String compilation_done;
- public static String compilation_units;
- public static String compilation_unit;
- public static String compilation_internalError;
- public static String output_isFile;
- public static String output_notValidAll;
- public static String output_notValid;
- public static String problem_noSourceInformation;
- public static String problem_atLine;
- public static String abort_invalidAttribute;
- public static String abort_invalidExceptionAttribute;
- public static String abort_missingCode;
- public static String abort_againstSourceModel;
- public static String accept_cannot;
- public static String parser_incorrectPath;
- public static String parser_moveFiles;
- public static String parser_syntaxRecovery;
- public static String parser_regularParse;
- public static String parser_missingFile;
- public static String parser_corruptedFile;
- public static String parser_endOfFile;
- public static String parser_endOfConstructor;
- public static String parser_endOfMethod;
- public static String parser_endOfInitializer;
- public static String ast_missingCode;
- public static String constant_cannotCastedInto;
- public static String constant_cannotConvertedTo;
- public static String Scanner_NON_TERM_REGEXP;
- public static String Scanner_INVALID_REGEXP_OPT;
- public static String Scanner_UNEXP_REGEXP;
-
- static {
- initializeMessages(BUNDLE_NAME, Messages.class);
- }
-
- /**
- * Bind the given message's substitution locations with the given string values.
- *
- * @param message the message to be manipulated
- * @return the manipulated String
- */
- public static String bind(String message) {
- return bind(message, null);
- }
-
- /**
- * Bind the given message's substitution locations with the given string values.
- *
- * @param message the message to be manipulated
- * @param binding the object to be inserted into the message
- * @return the manipulated String
- */
- public static String bind(String message, Object binding) {
- return bind(message, new Object[] {binding});
- }
-
- /**
- * Bind the given message's substitution locations with the given string values.
- *
- * @param message the message to be manipulated
- * @param binding1 An object to be inserted into the message
- * @param binding2 A second object to be inserted into the message
- * @return the manipulated String
- */
- public static String bind(String message, Object binding1, Object binding2) {
- return bind(message, new Object[] {binding1, binding2});
- }
-
- /**
- * Bind the given message's substitution locations with the given string values.
- *
- * @param message the message to be manipulated
- * @param bindings An array of objects to be inserted into the message
- * @return the manipulated String
- */
- public static String bind(String message, Object[] bindings) {
- return MessageFormat.format(message, bindings);
- }
-
- /*
- * Build an array of directories to search
- */
- private static String[] buildVariants(String root) {
- if (nlSuffixes == null) {
- //build list of suffixes for loading resource bundles
- String nl = Locale.getDefault().toString();
- ArrayList result = new ArrayList(4);
- int lastSeparator;
- while (true) {
- result.add('_' + nl + EXTENSION);
- lastSeparator = nl.lastIndexOf('_');
- if (lastSeparator == -1)
- break;
- nl = nl.substring(0, lastSeparator);
- }
- //add the empty suffix last (most general)
- result.add(EXTENSION);
- nlSuffixes = (String[]) result.toArray(new String[result.size()]);
- }
- root = root.replace('.', '/');
- String[] variants = new String[nlSuffixes.length];
- for (int i = 0; i < variants.length; i++)
- variants[i] = root + nlSuffixes[i];
- return variants;
- }
- public static void initializeMessages(String bundleName, Class clazz) {
- // load the resource bundle and set the fields
- final Field[] fields = clazz.getDeclaredFields();
- load(bundleName, clazz.getClassLoader(), fields);
-
- // iterate over the fields in the class to make sure that there aren't any empty ones
- final int MOD_EXPECTED = Modifier.PUBLIC | Modifier.STATIC;
- final int MOD_MASK = MOD_EXPECTED | Modifier.FINAL;
- final int numFields = fields.length;
- for (int i = 0; i < numFields; i++) {
- Field field = fields[i];
- if ((field.getModifiers() & MOD_MASK) != MOD_EXPECTED)
- continue;
- try {
- // Set the value into the field if its empty. We should never get an exception here because
- // we know we have a public static non-final field. If we do get an exception, silently
- // log it and continue. This means that the field will (most likely) be un-initialized and
- // will fail later in the code and if so then we will see both the NPE and this error.
- if (field.get(clazz) == null) {
- String value = "Missing message: " + field.getName() + " in: " + bundleName; //$NON-NLS-1$ //$NON-NLS-2$
- field.set(null, value);
- }
- } catch (IllegalArgumentException e) {
- // ignore
- } catch (IllegalAccessException e) {
- // ignore
- }
- }
- }
- /**
- * Load the given resource bundle using the specified class loader.
- */
- public static void load(final String bundleName, final ClassLoader loader, final Field[] fields) {
- final String[] variants = buildVariants(bundleName);
- // search the dirs in reverse order so the cascading defaults is set correctly
- for (int i = variants.length; --i >= 0;) {
- InputStream input = (loader == null)
- ? ClassLoader.getSystemResourceAsStream(variants[i])
- : loader.getResourceAsStream(variants[i]);
- if (input == null) continue;
- try {
- final MessagesProperties properties = new MessagesProperties(fields, bundleName);
- properties.load(input);
- } catch (IOException e) {
- // ignore
- } finally {
- try {
- input.close();
- } catch (IOException e) {
- // ignore
- }
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/ObjectCache.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/ObjectCache.java
deleted file mode 100644
index cadf5478..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/ObjectCache.java
+++ /dev/null
@@ -1,158 +0,0 @@
-/*******************************************************************************
- * 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.compiler.util;
-
-public class ObjectCache {
- public Object keyTable[];
- public int valueTable[];
- int elementSize;
- int threshold;
-/**
- * Constructs a new, empty hashtable. A default capacity is used.
- * Note that the hashtable will automatically grow when it gets full.
- */
-public ObjectCache() {
- this(13);
-}
-/**
- * Constructs a new, empty hashtable with the specified initial
- * capacity.
- * @param initialCapacity int
- * the initial number of buckets
- */
-public ObjectCache(int initialCapacity) {
- this.elementSize = 0;
- this.threshold = (int) (initialCapacity * 0.66f);
- this.keyTable = new Object[initialCapacity];
- this.valueTable = new int[initialCapacity];
-}
-/**
- * Clears the hash table so that it has no more elements in it.
- */
-public void clear() {
- for (int i = this.keyTable.length; --i >= 0;) {
- this.keyTable[i] = null;
- this.valueTable[i] = 0;
- }
- this.elementSize = 0;
-}
-/** Returns true if the collection contains an element for the key.
- *
- * @param key char[] the key that we are looking for
- * @return boolean
- */
-public boolean containsKey(Object key) {
- int index = hashCode(key), length = this.keyTable.length;
- while (this.keyTable[index] != null) {
- if (this.keyTable[index] == key)
- return true;
- if (++index == length) {
- index = 0;
- }
- }
- return false;
-}
-/** Gets the object associated with the specified key in the
- * hashtable.
- * @param key <CODE>char[]</CODE> the specified key
- * @return int the element for the key or -1 if the key is not
- * defined in the hash table.
- */
-public int get(Object key) {
- int index = hashCode(key), length = this.keyTable.length;
- while (this.keyTable[index] != null) {
- if (this.keyTable[index] == key)
- return this.valueTable[index];
- if (++index == length) {
- index = 0;
- }
- }
- return -1;
-}
-/**
- * Return the hashcode for the key parameter
- *
- * @param key org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding
- * @return int
- */
-public int hashCode(Object key) {
- return (key.hashCode() & 0x7FFFFFFF) % this.keyTable.length;
-}
-/**
- * Puts the specified element into the hashtable, using the specified
- * key. The element may be retrieved by doing a get() with the same key.
- * The key and the element cannot be null.
- *
- * @param key <CODE>Object</CODE> the specified key in the hashtable
- * @param value <CODE>int</CODE> the specified element
- * @return int the old value of the key, or -1 if it did not have one.
- */
-public int put(Object key, int value) {
- int index = hashCode(key), length = this.keyTable.length;
- while (this.keyTable[index] != null) {
- if (this.keyTable[index] == key)
- return this.valueTable[index] = value;
- if (++index == length) {
- index = 0;
- }
- }
- this.keyTable[index] = key;
- this.valueTable[index] = value;
-
- // assumes the threshold is never equal to the size of the table
- if (++this.elementSize > this.threshold)
- rehash();
- return value;
-}
-/**
- * Rehashes the content of the table into a bigger table.
- * This method is called automatically when the hashtable's
- * size exceeds the threshold.
- */
-private void rehash() {
- ObjectCache newHashtable = new ObjectCache(this.keyTable.length * 2);
- for (int i = this.keyTable.length; --i >= 0;)
- if (this.keyTable[i] != null)
- newHashtable.put(this.keyTable[i], this.valueTable[i]);
-
- this.keyTable = newHashtable.keyTable;
- this.valueTable = newHashtable.valueTable;
- this.threshold = newHashtable.threshold;
-}
-/**
- * Returns the number of elements contained in the hashtable.
- *
- * @return <CODE>int</CODE> The size of the table
- */
-public int size() {
- return this.elementSize;
-}
-/**
- * Converts to a rather lengthy String.
- *
- * @return String the ascii representation of the receiver
- */
-public String toString() {
- int max = size();
- StringBuffer buf = new StringBuffer();
- buf.append("{"); //$NON-NLS-1$
- for (int i = 0; i < max; ++i) {
- if (this.keyTable[i] != null) {
- buf.append(this.keyTable[i]).append("->").append(this.valueTable[i]); //$NON-NLS-1$
- }
- if (i < max) {
- buf.append(", "); //$NON-NLS-1$
- }
- }
- buf.append("}"); //$NON-NLS-1$
- return buf.toString();
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/ObjectVector.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/ObjectVector.java
deleted file mode 100644
index ab53bd75..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/ObjectVector.java
+++ /dev/null
@@ -1,135 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.util;
-
-public final class ObjectVector {
-
- static int INITIAL_SIZE = 10;
-
- public int size;
- int maxSize;
- Object[] elements;
-
- public ObjectVector() {
- this(INITIAL_SIZE);
- }
-
- public ObjectVector(int initialSize) {
- this.maxSize = initialSize > 0 ? initialSize : INITIAL_SIZE;
- this.size = 0;
- this.elements = new Object[this.maxSize];
- }
-
- public void add(Object newElement) {
-
- if (this.size == this.maxSize) // knows that size starts <= maxSize
- System.arraycopy(this.elements, 0, (this.elements = new Object[this.maxSize *= 2]), 0, this.size);
- this.elements[this.size++] = newElement;
- }
-
- public void addAll(Object[] newElements) {
-
- if (this.size + newElements.length >= this.maxSize) {
- maxSize = this.size + newElements.length; // assume no more elements will be added
- System.arraycopy(this.elements, 0, (this.elements = new Object[this.maxSize]), 0, this.size);
- }
- System.arraycopy(newElements, 0, this.elements, size, newElements.length);
- this.size += newElements.length;
- }
-
- public void addAll(ObjectVector newVector) {
-
- if (this.size + newVector.size >= this.maxSize) {
- maxSize = this.size + newVector.size; // assume no more elements will be added
- System.arraycopy(this.elements, 0, (this.elements = new Object[this.maxSize]), 0, this.size);
- }
- System.arraycopy(newVector.elements, 0, this.elements, size, newVector.size);
- this.size += newVector.size;
- }
-
- /**
- * Identity check
- */
- public boolean containsIdentical(Object element) {
-
- for (int i = this.size; --i >= 0;)
- if (element == this.elements[i])
- return true;
- return false;
- }
-
- /**
- * Equality check
- */
- public boolean contains(Object element) {
-
- for (int i = this.size; --i >= 0;)
- if (element.equals(this.elements[i]))
- return true;
- return false;
- }
-
- public void copyInto(Object[] targetArray){
-
- this.copyInto(targetArray, 0);
- }
-
- public void copyInto(Object[] targetArray, int index){
-
- System.arraycopy(this.elements, 0, targetArray, index, this.size);
- }
-
- public Object elementAt(int index) {
-
- return this.elements[index];
- }
-
- public Object find(Object element) {
-
- for (int i = this.size; --i >= 0;)
- if (element.equals(this.elements[i]))
- return element;
- return null;
- }
-
- public Object remove(Object element) {
-
- // assumes only one occurrence of the element exists
- for (int i = this.size; --i >= 0;)
- if (element.equals(this.elements[i])) {
- // shift the remaining elements down one spot
- System.arraycopy(this.elements, i + 1, this.elements, i, --this.size - i);
- this.elements[this.size] = null;
- return element;
- }
- return null;
- }
-
- public void removeAll() {
-
- for (int i = this.size; --i >= 0;)
- this.elements[i] = null;
- this.size = 0;
- }
-
- public int size(){
-
- return this.size;
- }
-
- public String toString() {
-
- String s = ""; //$NON-NLS-1$
- for (int i = 0; i < this.size; i++)
- s += this.elements[i].toString() + "\n"; //$NON-NLS-1$
- return s;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/SimpleLookupTable.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/SimpleLookupTable.java
deleted file mode 100644
index 0ec30675..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/SimpleLookupTable.java
+++ /dev/null
@@ -1,167 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.util;
-
-/**
- * A simple lookup table is a non-synchronized Hashtable, whose keys
- * and values are Objects. It also uses linear probing to resolve collisions
- * rather than a linked list of hash table entries.
- */
-public final class SimpleLookupTable implements Cloneable {
-
-// to avoid using Enumerations, walk the individual tables skipping nulls
-public Object[] keyTable;
-public Object[] valueTable;
-public int elementSize; // number of elements in the table
-public int threshold;
-
-public SimpleLookupTable() {
- this(13);
-}
-
-public SimpleLookupTable(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.keyTable = new Object[extraRoom];
- this.valueTable = new Object[extraRoom];
-}
-
-public Object clone() throws CloneNotSupportedException {
- SimpleLookupTable result = (SimpleLookupTable) super.clone();
- result.elementSize = this.elementSize;
- result.threshold = this.threshold;
-
- int length = this.keyTable.length;
- result.keyTable = new Object[length];
- System.arraycopy(this.keyTable, 0, result.keyTable, 0, length);
-
- length = this.valueTable.length;
- result.valueTable = new Object[length];
- System.arraycopy(this.valueTable, 0, result.valueTable, 0, length);
- return result;
-}
-
-public boolean containsKey(Object key) {
- int length = keyTable.length;
- int index = (key.hashCode() & 0x7FFFFFFF) % length;
- Object currentKey;
- while ((currentKey = keyTable[index]) != null) {
- if (currentKey.equals(key)) return true;
- if (++index == length) index = 0;
- }
- return false;
-}
-
-public Object get(Object key) {
- int length = keyTable.length;
- int index = (key.hashCode() & 0x7FFFFFFF) % length;
- Object currentKey;
- while ((currentKey = keyTable[index]) != null) {
- if (currentKey.equals(key)) return valueTable[index];
- if (++index == length) index = 0;
- }
- return null;
-}
-
-public Object getKey(Object key) {
- int length = keyTable.length;
- int index = (key.hashCode() & 0x7FFFFFFF) % length;
- Object currentKey;
- while ((currentKey = keyTable[index]) != null) {
- if (currentKey.equals(key)) return currentKey;
- if (++index == length) index = 0;
- }
- return key;
-}
-
-public Object keyForValue(Object valueToMatch) {
- if (valueToMatch != null)
- for (int i = 0, l = keyTable.length; i < l; i++)
- if (keyTable[i] != null && valueToMatch.equals(valueTable[i]))
- return keyTable[i];
- return null;
-}
-
-public Object put(Object key, Object value) {
- int length = keyTable.length;
- int index = (key.hashCode() & 0x7FFFFFFF) % length;
- Object currentKey;
- while ((currentKey = keyTable[index]) != null) {
- if (currentKey.equals(key)) return valueTable[index] = value;
- if (++index == length) index = 0;
- }
- keyTable[index] = key;
- valueTable[index] = value;
-
- // assumes the threshold is never equal to the size of the table
- if (++elementSize > threshold) rehash();
- return value;
-}
-
-public Object removeKey(Object key) {
- int length = keyTable.length;
- int index = (key.hashCode() & 0x7FFFFFFF) % length;
- Object currentKey;
- while ((currentKey = keyTable[index]) != null) {
- if (currentKey.equals(key)) {
- elementSize--;
- Object oldValue = valueTable[index];
- keyTable[index] = null;
- valueTable[index] = null;
- if (keyTable[index + 1 == length ? 0 : index + 1] != null)
- rehash(); // only needed if a possible collision existed
- return oldValue;
- }
- if (++index == length) index = 0;
- }
- return null;
-}
-
-public void removeValue(Object valueToRemove) {
- boolean rehash = false;
- for (int i = 0, l = valueTable.length; i < l; i++) {
- Object value = valueTable[i];
- if (value != null && value.equals(valueToRemove)) {
- elementSize--;
- keyTable[i] = null;
- valueTable[i] = null;
- if (!rehash && keyTable[i + 1 == l ? 0 : i + 1] != null)
- rehash = true; // only needed if a possible collision existed
- }
- }
- if (rehash) rehash();
-}
-
-private void rehash() {
- SimpleLookupTable newLookupTable = new SimpleLookupTable(elementSize * 2); // double the number of expected elements
- Object currentKey;
- for (int i = keyTable.length; --i >= 0;)
- if ((currentKey = keyTable[i]) != null)
- newLookupTable.put(currentKey, valueTable[i]);
-
- this.keyTable = newLookupTable.keyTable;
- this.valueTable = newLookupTable.valueTable;
- this.elementSize = newLookupTable.elementSize;
- this.threshold = newLookupTable.threshold;
-}
-
-public String toString() {
- String s = ""; //$NON-NLS-1$
- Object object;
- for (int i = 0, l = valueTable.length; i < l; i++)
- if ((object = valueTable[i]) != null)
- s += keyTable[i].toString() + " -> " + object.toString() + "\n"; //$NON-NLS-2$ //$NON-NLS-1$
- return s;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/SimpleNameVector.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/SimpleNameVector.java
deleted file mode 100644
index 2d093111..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/SimpleNameVector.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.util;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-
-public final class SimpleNameVector {
-
- static int INITIAL_SIZE = 10;
-
- public int size;
- int maxSize;
- char[][] elements;
-
- public SimpleNameVector() {
-
- this.maxSize = INITIAL_SIZE;
- this.size = 0;
- this.elements = new char[this.maxSize][];
- }
-
- public void add(char[] newElement) {
-
- if (this.size == this.maxSize) // knows that size starts <= maxSize
- System.arraycopy(this.elements, 0, (this.elements = new char[this.maxSize *= 2][]), 0, this.size);
- this.elements[size++] = newElement;
- }
-
- public void addAll(char[][] newElements) {
-
- if (this.size + newElements.length >= this.maxSize) {
- this.maxSize = this.size + newElements.length; // assume no more elements will be added
- System.arraycopy(this.elements, 0, (this.elements = new char[this.maxSize][]), 0, this.size);
- }
- System.arraycopy(newElements, 0, this.elements, this.size, newElements.length);
- this.size += newElements.length;
- }
-
- public void copyInto(Object[] targetArray){
-
- System.arraycopy(this.elements, 0, targetArray, 0, this.size);
- }
-
- public boolean contains(char[] element) {
-
- for (int i = this.size; --i >= 0;)
- if (CharOperation.equals(element, this.elements[i]))
- return true;
- return false;
- }
-
- public char[] elementAt(int index) {
- return this.elements[index];
- }
-
- public char[] remove(char[] element) {
-
- // assumes only one occurrence of the element exists
- for (int i = this.size; --i >= 0;)
- if (element == this.elements[i]) {
- // shift the remaining elements down one spot
- System.arraycopy(this.elements, i + 1, this.elements, i, --this.size - i);
- this.elements[this.size] = null;
- return element;
- }
- return null;
- }
-
- public void removeAll() {
-
- for (int i = this.size; --i >= 0;)
- this.elements[i] = null;
- this.size = 0;
- }
-
- public int size(){
-
- return this.size;
- }
-
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- for (int i = 0; i < this.size; i++) {
- buffer.append(this.elements[i]).append("\n"); //$NON-NLS-1$
- }
- return buffer.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/SimpleSet.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/SimpleSet.java
deleted file mode 100644
index c947cc64..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/SimpleSet.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.util;
-
-/**
- * A simple lookup table is a non-synchronized Hashtable, whose keys
- * and values are Objects. It also uses linear probing to resolve collisions
- * rather than a linked list of hash table entries.
- */
-public final class SimpleSet implements Cloneable {
-
-// to avoid using Enumerations, walk the individual values skipping nulls
-public Object[] values;
-public int elementSize; // number of elements in the table
-public int threshold;
-
-public SimpleSet() {
- this(13);
-}
-
-public SimpleSet(int size) {
- if (size < 3) size = 3;
- this.elementSize = 0;
- this.threshold = size + 1; // size is the expected number of elements
- this.values = new Object[2 * size + 1];
-}
-
-public Object add(Object object) {
- int length = this.values.length;
- int index = (object.hashCode() & 0x7FFFFFFF) % length;
- Object current;
- while ((current = this.values[index]) != null) {
- if (current.equals(object)) return this.values[index] = object;
- if (++index == length) index = 0;
- }
- this.values[index] = object;
-
- // assumes the threshold is never equal to the size of the table
- if (++this.elementSize > this.threshold) rehash();
- return object;
-}
-
-public Object addIfNotIncluded(Object object) {
- int length = this.values.length;
- int index = (object.hashCode() & 0x7FFFFFFF) % length;
- Object current;
- while ((current = this.values[index]) != null) {
- if (current.equals(object)) return null; // already existed
- if (++index == length) index = 0;
- }
- this.values[index] = object;
-
- // assumes the threshold is never equal to the size of the table
- if (++this.elementSize > this.threshold) rehash();
- return object;
-}
-
-public void asArray(Object[] copy) {
- if (this.elementSize != copy.length)
- throw new IllegalArgumentException();
- int index = this.elementSize;
- for (int i = 0, l = this.values.length; i < l && index > 0; i++)
- if (this.values[i] != null)
- copy[--index] = this.values[i];
-}
-
-public void clear() {
- for (int i = this.values.length; --i >= 0;)
- this.values[i] = null;
- this.elementSize = 0;
-}
-
-public Object clone() throws CloneNotSupportedException {
- SimpleSet result = (SimpleSet) super.clone();
- result.elementSize = this.elementSize;
- result.threshold = this.threshold;
-
- int length = this.values.length;
- result.values = new Object[length];
- System.arraycopy(this.values, 0, result.values, 0, length);
- return result;
-}
-
-public boolean includes(Object object) {
- int length = values.length;
- int index = (object.hashCode() & 0x7FFFFFFF) % length;
- Object current;
- while ((current = values[index]) != null) {
- if (current.equals(object)) return true;
- if (++index == length) index = 0;
- }
- return false;
-}
-
-public Object remove(Object object) {
- int length = values.length;
- int index = (object.hashCode() & 0x7FFFFFFF) % length;
- Object current;
- while ((current = values[index]) != null) {
- if (current.equals(object)) {
- elementSize--;
- Object oldValue = values[index];
- values[index] = null;
- if (values[index + 1 == length ? 0 : index + 1] != null)
- rehash(); // only needed if a possible collision existed
- return oldValue;
- }
- if (++index == length) index = 0;
- }
- return null;
-}
-
-private void rehash() {
- SimpleSet newSet = new SimpleSet(elementSize * 2); // double the number of expected elements
- Object current;
- for (int i = values.length; --i >= 0;)
- if ((current = values[i]) != null)
- newSet.add(current);
-
- this.values = newSet.values;
- this.elementSize = newSet.elementSize;
- this.threshold = newSet.threshold;
-}
-
-public String toString() {
- String s = ""; //$NON-NLS-1$
- Object object;
- for (int i = 0, l = values.length; i < l; i++)
- if ((object = values[i]) != null)
- s += object.toString() + "\n"; //$NON-NLS-1$
- return s;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/SimpleSetOfCharArray.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/SimpleSetOfCharArray.java
deleted file mode 100644
index a1a8b9f9..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/SimpleSetOfCharArray.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.util;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-
-/**
- * A simple lookup table is a non-synchronized Hashtable, whose keys
- * and values are char[]. It also uses linear probing to resolve collisions
- * rather than a linked list of hash table entries.
- */
-public final class SimpleSetOfCharArray implements Cloneable {
-
-// to avoid using Enumerations, walk the individual values skipping nulls
-public char[][] values;
-public int elementSize; // number of elements in the table
-public int threshold;
-
-public SimpleSetOfCharArray() {
- this(13);
-}
-
-public SimpleSetOfCharArray(int size) {
- if (size < 3) size = 3;
- this.elementSize = 0;
- this.threshold = size + 1; // size is the expected number of elements
- this.values = new char[2 * size + 1][];
-}
-
-public Object add(char[] object) {
- int length = this.values.length;
- int index = (CharOperation.hashCode(object) & 0x7FFFFFFF) % length;
- char[] current;
- while ((current = this.values[index]) != null) {
- if (CharOperation.equals(current, object)) return this.values[index] = object;
- if (++index == length) index = 0;
- }
- this.values[index] = object;
-
- // assumes the threshold is never equal to the size of the table
- if (++this.elementSize > this.threshold) rehash();
- return object;
-}
-
-public void asArray(Object[] copy) {
- if (this.elementSize != copy.length)
- throw new IllegalArgumentException();
- int index = this.elementSize;
- for (int i = 0, l = this.values.length; i < l && index > 0; i++)
- if (this.values[i] != null)
- copy[--index] = this.values[i];
-}
-
-public void clear() {
- for (int i = this.values.length; --i >= 0;)
- this.values[i] = null;
- this.elementSize = 0;
-}
-
-public Object clone() throws CloneNotSupportedException {
- SimpleSetOfCharArray result = (SimpleSetOfCharArray) super.clone();
- result.elementSize = this.elementSize;
- result.threshold = this.threshold;
-
- int length = this.values.length;
- result.values = new char[length][];
- System.arraycopy(this.values, 0, result.values, 0, length);
- return result;
-}
-
-public char[] get(char[] object) {
- int length = this.values.length;
- int index = (CharOperation.hashCode(object) & 0x7FFFFFFF) % length;
- char[] current;
- while ((current = this.values[index]) != null) {
- if (CharOperation.equals(current, object)) return current;
- if (++index == length) index = 0;
- }
- this.values[index] = object;
-
- // assumes the threshold is never equal to the size of the table
- if (++this.elementSize > this.threshold) rehash();
- return object;
-}
-
-public boolean includes(char[] object) {
- int length = values.length;
- int index = (CharOperation.hashCode(object) & 0x7FFFFFFF) % length;
- char[] current;
- while ((current = values[index]) != null) {
- if (CharOperation.equals(current, object)) return true;
- if (++index == length) index = 0;
- }
- return false;
-}
-
-public char[] remove(char[] object) {
- int length = values.length;
- int index = (CharOperation.hashCode(object) & 0x7FFFFFFF) % length;
- char[] current;
- while ((current = values[index]) != null) {
- if (CharOperation.equals(current, object)) {
- elementSize--;
- char[] oldValue = values[index];
- values[index] = null;
- if (values[index + 1 == length ? 0 : index + 1] != null)
- rehash(); // only needed if a possible collision existed
- return oldValue;
- }
- if (++index == length) index = 0;
- }
- return null;
-}
-
-private void rehash() {
- SimpleSetOfCharArray newSet = new SimpleSetOfCharArray(elementSize * 2); // double the number of expected elements
- char[] current;
- for (int i = values.length; --i >= 0;)
- if ((current = values[i]) != null)
- newSet.add(current);
-
- this.values = newSet.values;
- this.elementSize = newSet.elementSize;
- this.threshold = newSet.threshold;
-}
-
-public String toString() {
- String s = ""; //$NON-NLS-1$
- char[] object;
- for (int i = 0, l = values.length; i < l; i++)
- if ((object = values[i]) != null)
- s += new String(object) + "\n"; //$NON-NLS-1$
- return s;
-}
-}
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
deleted file mode 100644
index bcfa58e2..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/SuffixConstants.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.compiler.util;
-
-public interface SuffixConstants {
- public final static String EXTENSION_java = "js"; //$NON-NLS-1$
- public final static String EXTENSION_JAVA = "JS"; //$NON-NLS-1$
-
- public final static String SUFFIX_STRING_java = "." + EXTENSION_java; //$NON-NLS-1$
- public final static String SUFFIX_STRING_JAVA = "." + EXTENSION_JAVA; //$NON-NLS-1$
-
- public final static char[] SUFFIX_java = SUFFIX_STRING_java.toCharArray();
- public final static char[] SUFFIX_JAVA = SUFFIX_STRING_JAVA.toCharArray();
-
- public final static String EXTENSION_zip = "zip"; //$NON-NLS-1$
- public final static String EXTENSION_ZIP = "ZIP"; //$NON-NLS-1$
-
- public final static String SUFFIX_STRING_zip = "." + EXTENSION_zip; //$NON-NLS-1$
- public final static String SUFFIX_STRING_ZIP = "." + EXTENSION_ZIP; //$NON-NLS-1$
-
- public final static char[] SUFFIX_zip = SUFFIX_STRING_zip.toCharArray();
- public final static char[] SUFFIX_ZIP = SUFFIX_STRING_ZIP.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
deleted file mode 100644
index 8eaaa5d4..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/Util.java
+++ /dev/null
@@ -1,623 +0,0 @@
-/*******************************************************************************
- * 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.compiler.util;
-
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-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;
-import org.eclipse.wst.jsdt.core.ast.ILiteral;
-import org.eclipse.wst.jsdt.core.ast.ISingleNameReference;
-import org.eclipse.wst.jsdt.core.ast.IThisReference;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ArrayReference;
-
-public class Util implements SuffixConstants {
-
- public interface Displayable {
- String displayString(Object o);
- }
-
- private static final int DEFAULT_READING_SIZE = 8192;
- public final static String UTF_8 = "UTF-8"; //$NON-NLS-1$
- public static final String LINE_SEPARATOR = System.getProperty("line.separator"); //$NON-NLS-1$
-
- public static final String EMPTY_STRING = new String(CharOperation.NO_CHAR);
- public static final int[] EMPTY_INT_ARRAY= new int[0];
-
- /**
- * Returns the given bytes as a char array using a given encoding (null means platform default).
- */
- public static char[] bytesToChar(byte[] bytes, String encoding) throws IOException {
-
- return getInputStreamAsCharArray(new ByteArrayInputStream(bytes), bytes.length, encoding);
-
- }
- /**
- * Returns the contents of the given file as a byte array.
- * @throws IOException if a problem occured reading the file.
- */
- public static byte[] getFileByteContent(File file) throws IOException {
- InputStream stream = null;
- try {
- stream = new FileInputStream(file);
- return getInputStreamAsByteArray(stream, (int) file.length());
- } finally {
- if (stream != null) {
- try {
- stream.close();
- } catch (IOException e) {
- // ignore
- }
- }
- }
- }
- /**
- * Returns the contents of the given file as a char array.
- * When encoding is null, then the platform default one is used
- * @throws IOException if a problem occured reading the file.
- */
- public static char[] getFileCharContent(File file, String encoding) throws IOException {
- InputStream stream = null;
- try {
- stream = new FileInputStream(file);
- return getInputStreamAsCharArray(stream, (int) file.length(), encoding);
- } finally {
- if (stream != null) {
- try {
- stream.close();
- } catch (IOException e) {
- // ignore
- }
- }
- }
- }
- /*
- * NIO support to get input stream as byte array.
- * Not used as with JDK 1.4.2 this support is slower than standard IO one...
- * Keep it as comment for future in case of next JDK versions improve performance
- * in this area...
- *
- public static byte[] getInputStreamAsByteArray(FileInputStream stream, int length)
- throws IOException {
-
- FileChannel channel = stream.getChannel();
- int size = (int)channel.size();
- if (length >= 0 && length < size) size = length;
- byte[] contents = new byte[size];
- ByteBuffer buffer = ByteBuffer.wrap(contents);
- channel.read(buffer);
- return contents;
- }
- */
- /**
- * Returns the given input stream's contents as a byte array.
- * 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 occured reading the stream.
- */
- public static byte[] getInputStreamAsByteArray(InputStream stream, int length)
- throws IOException {
- byte[] contents;
- if (length == -1) {
- contents = new byte[0];
- int contentsLength = 0;
- int amountRead = -1;
- do {
- int amountRequested = Math.max(stream.available(), DEFAULT_READING_SIZE); // read at least 8K
-
- // resize contents if needed
- if (contentsLength + amountRequested > contents.length) {
- System.arraycopy(
- contents,
- 0,
- contents = new byte[contentsLength + amountRequested],
- 0,
- contentsLength);
- }
-
- // read as many bytes as possible
- amountRead = stream.read(contents, contentsLength, amountRequested);
-
- if (amountRead > 0) {
- // remember length of contents
- contentsLength += amountRead;
- }
- } while (amountRead != -1);
-
- // resize contents if necessary
- if (contentsLength < contents.length) {
- System.arraycopy(
- contents,
- 0,
- contents = new byte[contentsLength],
- 0,
- contentsLength);
- }
- } else {
- contents = new byte[length];
- int len = 0;
- int readSize = 0;
- while ((readSize != -1) && (len != length)) {
- // See PR 1FMS89U
- // We record first the read size. In this case len is the actual read size.
- len += readSize;
- readSize = stream.read(contents, len, length - len);
- }
- }
-
- return contents;
- }
- /*
- * NIO support to get input stream as char array.
- * Not used as with JDK 1.4.2 this support is slower than standard IO one...
- * Keep it as comment for future in case of next JDK versions improve performance
- * in this area...
- public static char[] getInputStreamAsCharArray(FileInputStream stream, int length, String encoding)
- throws IOException {
-
- FileChannel channel = stream.getChannel();
- int size = (int)channel.size();
- if (length >= 0 && length < size) size = length;
- Charset charset = encoding==null?systemCharset:Charset.forName(encoding);
- if (charset != null) {
- MappedByteBuffer bbuffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, size);
- CharsetDecoder decoder = charset.newDecoder();
- CharBuffer buffer = decoder.decode(bbuffer);
- char[] contents = new char[buffer.limit()];
- buffer.get(contents);
- return contents;
- }
- throw new UnsupportedCharsetException(SYSTEM_FILE_ENCODING);
- }
- */
- /**
- * Returns the given input stream's contents as a character array.
- * If a length is specified (ie. if length != -1), this represents the number of bytes in the stream.
- * Note this doesn't close the stream.
- * @throws IOException if a problem occured reading the stream.
- */
- public static char[] getInputStreamAsCharArray(InputStream stream, int length, String encoding)
- throws IOException {
- InputStreamReader reader = null;
- try {
- reader = encoding == null
- ? new InputStreamReader(stream)
- : new InputStreamReader(stream, encoding);
- } catch (UnsupportedEncodingException e) {
- // encoding is not supported
- reader = new InputStreamReader(stream);
- }
- char[] contents;
- int totalRead = 0;
- if (length == -1) {
- contents = CharOperation.NO_CHAR;
- } else {
- // length is a good guess when the encoding produces less or the same amount of characters than the file length
- contents = new char[length]; // best guess
- }
-
- while (true) {
- int amountRequested;
- if (totalRead < length) {
- // until known length is met, reuse same array sized eagerly
- amountRequested = length - totalRead;
- } else {
- // reading beyond known length
- int current = reader.read();
- if (current < 0) break;
-
- amountRequested = Math.max(stream.available(), DEFAULT_READING_SIZE); // read at least 8K
-
- // resize contents if needed
- if (totalRead + 1 + amountRequested > contents.length)
- System.arraycopy(contents, 0, contents = new char[totalRead + 1 + amountRequested], 0, totalRead);
-
- // add current character
- contents[totalRead++] = (char) current; // coming from totalRead==length
- }
- // read as many chars as possible
- int amountRead = reader.read(contents, totalRead, amountRequested);
- if (amountRead < 0) break;
- totalRead += amountRead;
- }
-
- // Do not keep first character for UTF-8 BOM encoding
- int start = 0;
- if (totalRead > 0 && UTF_8.equals(encoding)) {
- if (contents[0] == 0xFEFF) { // if BOM char then skip
- totalRead--;
- start = 1;
- }
- }
-
- // resize contents if necessary
- if (totalRead < contents.length)
- System.arraycopy(contents, start, contents = new char[totalRead], 0, totalRead);
-
- return contents;
- }
-
- public static int getLineNumber(int position, int[] lineEnds, int g, int d) {
- if (lineEnds == null)
- return 1;
- if (d == -1)
- return 1;
- int m = g, start;
- while (g <= d) {
- m = g + (d - g) /2;
- if (position < (start = lineEnds[m])) {
- d = m-1;
- } else if (position > start) {
- g = m+1;
- } else {
- return m + 1;
- }
- }
- if (position < lineEnds[m]) {
- return m+1;
- }
- return m+2;
- }
-
-
- /**
- * Returns the contents of the given zip entry as a byte array.
- * @throws IOException if a problem occured reading the zip entry.
- */
- public static byte[] getZipEntryByteContent(ZipEntry ze, ZipFile zip)
- throws IOException {
-
- InputStream stream = null;
- try {
- stream = zip.getInputStream(ze);
- if (stream == null) throw new IOException("Invalid zip entry name : " + ze.getName()); //$NON-NLS-1$
- return getInputStreamAsByteArray(stream, (int) ze.getSize());
- } finally {
- if (stream != null) {
- try {
- stream.close();
- } catch (IOException e) {
- // ignore
- }
- }
- }
- }
-
- /**
- * Returns true iff str.toLowerCase().endsWith(".jar") || str.toLowerCase().endsWith(".zip")
- * implementation is not creating extra strings.
- */
- public final static boolean isArchiveFileName(String name) {
- int nameLength = name == null ? 0 : name.length();
- int suffixLength = SUFFIX_ZIP.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;
- }
- return true;
- }
- /**
- * Returns true iff str.toLowerCase().endsWith(".class")
- * implementation is not creating extra strings.
- */
- public final static boolean isClassFileName(char[] name) {
- int nameLength = name == null ? 0 : name.length;
- int suffixLength = SUFFIX_JAVA.length;
- if (nameLength < suffixLength) return false;
-
- for (int i = 0, offset = nameLength - suffixLength; i < suffixLength; i++) {
- char c = name[offset + i];
- if (c != SUFFIX_java[i] && c != SUFFIX_JAVA[i]) return false;
- }
- return true;
- }
- /**
- * Returns true iff str.toLowerCase().endsWith(".class")
- * implementation is not creating extra strings.
- */
- public final static boolean isClassFileName(String name) {
- int nameLength = name == null ? 0 : name.length();
- int suffixLength = SUFFIX_JAVA.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_java[suffixIndex] && c != SUFFIX_JAVA[suffixIndex]) return false;
- }
- return true;
- }
-
- /**
- * <p>If any inclusion patterns are provided then the given path is considered
- * excluded if it does not match one of the inclusion patterns or if it matches
- * an inclusion pattern and an exclusion pattern. If no inclusion patterns are
- * provided then to be considered excluded the given pattern must match one of
- * the exclusion patterns.</p>
- *
- * <p>NOTE: should not be asked directly using pkg root paths</p>
- *
- * @param path determine if this path is excluded
- * @param inclusionPatterns if not <code>null</code> consider the given <code>path</code>
- * excluded if it does not match one of these paths, if <code>null</code> then a path is
- * only considered excluded if it matches one of the given <code>exclusionPatterns</code>
- * @param exclusionPatterns if the given <code>path</code> matches one
- * of these patterns then it is considered to be excluded
- * @param isFolderPath <code>true</code> if the given <code>path</code> is
- * a folder path, <code>false</code> otherwise
- * @return <code>true</code> if <code>inclusionPatterns</code> is not <code>null</code>
- * and the given <code>path</code> is not included, or if the given <code>path</code>
- * is included in the given <code>exclusionPatterns</code>
- *
- * @see IIncludePathEntry#getInclusionPatterns
- * @see IIncludePathEntry#getExclusionPatterns
- */
- public final static boolean isExcluded(char[] path, char[][] inclusionPatterns, char[][] exclusionPatterns, boolean isFolderPath) {
- if (inclusionPatterns == null && exclusionPatterns == null) return false;
-
- inclusionCheck: if (inclusionPatterns != null) {
- for (int i = 0, length = inclusionPatterns.length; i < length; i++) {
- char[] pattern = inclusionPatterns[i];
- char[] folderPattern = pattern;
- if (isFolderPath) {
- int lastSlash = CharOperation.lastIndexOf('/', pattern);
- if (lastSlash != -1 && lastSlash != pattern.length-1){ // trailing slash -> adds '**' for free (see http://ant.apache.org/manual/dirtasks.html)
- int star = CharOperation.indexOf('*', pattern, lastSlash);
- if ((star == -1
- || star >= pattern.length-1
- || pattern[star+1] != '*')) {
- folderPattern = CharOperation.subarray(pattern, 0, lastSlash);
- }
- }
- }
- if (pathMatch(path, folderPattern)) {
- break inclusionCheck;
- }
- }
- return true; // never included
- }
- if (isFolderPath) {
- path = CharOperation.concat(path, new char[] {'*'}, '/');
- }
- if (exclusionPatterns != null) {
- for (int i = 0, length = exclusionPatterns.length; i < length; i++) {
- if (pathMatch(path, exclusionPatterns[i])) {
- return true;
- }
- }
- }
- return false;
- }
- /**
- * Returns true iff str.toLowerCase().endsWith(".js")
- * implementation is not creating extra strings.
- */
- public final static boolean isJavaFileName(char[] name) {
- int nameLength = name == null ? 0 : name.length;
- int suffixLength = SUFFIX_JAVA.length;
- if (nameLength < suffixLength) return false;
-
- for (int i = 0, offset = nameLength - suffixLength; i < suffixLength; i++) {
- char c = name[offset + i];
- if (c != SUFFIX_java[i] && c != SUFFIX_JAVA[i]) return false;
- }
- return true;
- }
- /**
- * Returns true iff str.toLowerCase().endsWith(".js")
- * implementation is not creating extra strings.
- */
- public final static boolean isJavaFileName(String name) {
- int nameLength = name == null ? 0 : name.length();
- int suffixLength = SUFFIX_JAVA.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_java[suffixIndex] && c != SUFFIX_JAVA[suffixIndex]) return false;
- }
- return true;
- }
-
- /**
- * INTERNAL USE-ONLY
- * Search the column number corresponding to a specific position
- */
- public static final int searchColumnNumber(int[] startLineIndexes, int lineNumber, int position) {
- switch(lineNumber) {
- case 1 :
- return position + 1;
- case 2:
- return position - startLineIndexes[0];
- default:
- int line = lineNumber - 2;
- int length = startLineIndexes.length;
- if (line >= length) {
- return position - startLineIndexes[length - 1];
- }
- return position - startLineIndexes[line];
- }
- }
-
- /**
- * Converts a boolean value into Boolean.
- * @param bool The boolean to convert
- * @return The corresponding Boolean object (TRUE or FALSE).
- */
- public static Boolean toBoolean(boolean bool) {
- if (bool) {
- return Boolean.TRUE;
- } else {
- return Boolean.FALSE;
- }
- }
- /**
- * Converts an array of Objects into String.
- */
- public static String toString(Object[] objects) {
- return toString(objects,
- new Displayable(){
- public String displayString(Object o) {
- if (o == null) return "null"; //$NON-NLS-1$
- return o.toString();
- }
- });
- }
-
- /**
- * Converts an array of Objects into String.
- */
- public static String toString(Object[] objects, Displayable renderer) {
- if (objects == null) return ""; //$NON-NLS-1$
- StringBuffer buffer = new StringBuffer(10);
- for (int i = 0; i < objects.length; i++){
- if (i > 0) buffer.append(", "); //$NON-NLS-1$
- buffer.append(renderer.displayString(objects[i]));
- }
- return buffer.toString();
- }
-
- /**
- * <p>Builds a type name from an expression by iterating over all parts of the expression.<p>
- *
- * @param expression to iterate over and build a type name from
- * @return type name built from iterating over the given <code>expression</code>, or
- * <code>null</code> if a type name can not be built from the given expression
- */
- public final static char[] getTypeName(IExpression expression) {
-
- IExpression currExpr = expression;
-
- char[] selector = null;
- while (currExpr != null) {
- if (currExpr instanceof IFieldReference) {
- if (selector == null) {
- selector = ((IFieldReference) currExpr).getToken();
- }
- else {
- selector = CharOperation.concatWith(new char[][]{((IFieldReference) currExpr).getToken(), selector}, '.');
- }
- currExpr = ((IFieldReference) currExpr).getReceiver();
- }
- else if (currExpr instanceof ISingleNameReference) {
- if (selector == null) {
- selector = ((ISingleNameReference) currExpr).getToken();
- }
- else {
- selector = CharOperation.concatWith(new char[][]{((ISingleNameReference) currExpr).getToken(), selector}, '.');
- }
- currExpr = null;
- }
- else if (currExpr instanceof ArrayReference) {
- ArrayReference arrayRef = (ArrayReference) currExpr;
-
- /*
- * if the array reference position is a literately keep
- * building selector else there is a dynamic selector of some
- * sort so there is no way to build a type name from it
- */
- if (arrayRef.position instanceof ILiteral) {
- if (selector == null) {
- selector = ((ILiteral) arrayRef.position).source();
- }
- else {
- selector = CharOperation.concatWith(new char[][]{((ILiteral) arrayRef.position).source(), selector}, '.');
- }
- currExpr = arrayRef.receiver;
- }
- else {
- currExpr = null;
- }
- }
- else if (currExpr instanceof IThisReference) {
- // this can not be handled right now because the resolved type
- // for 'this' never seems to be resolved yet
- currExpr = null;
- selector = null;
- }
- else {
- // do not know how to handle the rest of the expression so
- // give up
- currExpr = null;
- selector = null;
- }
- }
-
- return selector;
- }
-
- /**
- * <p>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.</p>
- *
- * @param pathChars check to see if this path matches the <code>matchpathChars</code>
- * @param matchPathChars check to see if the given <code>pathChars</code> match this pattern
- * @return <code>true</code> if the given <code>pathChars</code> match the given given
- * <code>matchPathChars<code>, <code>false</code> 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/ASTHolderCUInfo.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ASTHolderCUInfo.java
deleted file mode 100644
index d604758c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ASTHolderCUInfo.java
+++ /dev/null
@@ -1,23 +0,0 @@
-/*******************************************************************************
- * 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 java.util.HashMap;
-
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-
-public class ASTHolderCUInfo extends CompilationUnitElementInfo {
- int astLevel;
- boolean resolveBindings;
- int reconcileFlags;
- HashMap problems = null;
- JavaScriptUnit ast;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BasicCompilationUnit.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BasicCompilationUnit.java
deleted file mode 100644
index a1414272..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BasicCompilationUnit.java
+++ /dev/null
@@ -1,162 +0,0 @@
-/*******************************************************************************
- * 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 java.io.File;
-import java.io.IOException;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.LibrarySuperType;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit;
-import org.eclipse.wst.jsdt.internal.compiler.util.Util;
-
-/**
- * A basic implementation of <code>IJavaScriptUnit</code>
- * for use in the <code>SourceMapper</code>.
- * @see IJavaScriptUnit
- */
-public class BasicCompilationUnit implements ICompilationUnit {
- protected char[] contents;
-
- // Note that if this compiler IJavaScriptUnit's content is known in advance, the fileName is not used to retrieve this content.
- // Instead it is used to keep enough information to recreate the IJavaScriptElement corresponding to this compiler IJavaScriptUnit.
- // Thus the fileName can be a path to a .class file, or even a path in a .jar to a .class file.
- // (e.g. /P/lib/mylib.jar|org/eclipse/test/X.class)
- protected char[] fileName;
-
- protected char[][] packageName;
- protected char[] mainTypeName;
- protected String encoding;
- protected LibrarySuperType superType;
-
-public BasicCompilationUnit(char[] contents, char[][] packageName, String fileName) {
- this.contents = contents;
- this.fileName = fileName.toCharArray();
- this.packageName = packageName;
-}
-
-public BasicCompilationUnit(char[] contents, char[][] packageName, String fileName, String encoding) {
- this(contents, packageName, fileName);
- this.encoding = encoding;
-}
-
-public BasicCompilationUnit(char[] contents, char[][] packageName, String fileName, IJavaScriptElement javaElement) {
- this(contents, packageName, fileName);
- if(javaElement instanceof ICompilationUnit) {
- superType = ((ICompilationUnit)javaElement).getCommonSuperType();
- //mainTypeName = ((IJavaScriptUnit)javaElement).getMainTypeName();
- }
- initEncoding(javaElement);
-}
-
-public BasicCompilationUnit(char[] contents, char[][] packageName, String fileName, IJavaScriptElement javaElement, String mainTypeName) {
- this(contents, packageName, fileName);
- initEncoding(javaElement);
- if(mainTypeName!=null) this.mainTypeName = mainTypeName.toCharArray();
-}
-
-/*
- * Initialize compilation unit encoding.
- * If we have a project, then get file name corresponding IFile and retrieve its encoding using
- * new API for encoding.
- * In case of a class file, then go through project in order to let the possibility to retrieve
- * a corresponding source file resource.
- * If we have a compilation unit, then get encoding from its resource directly...
- */
-private void initEncoding(IJavaScriptElement javaElement) {
- if (javaElement != null) {
- try {
- IJavaScriptProject javaProject = javaElement.getJavaScriptProject();
- switch (javaElement.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- IFile file = (IFile) javaElement.getResource();
- if (file != null) {
- this.encoding = file.getCharset();
- break;
- }
- // if no file, then get project encoding
- default:
- IProject project = (IProject) javaProject.getResource();
- if (project != null) {
- this.encoding = project.getDefaultCharset();
- }
- break;
- }
- } catch (CoreException e1) {
- this.encoding = null;
- }
- } else {
- this.encoding = null;
- }
-}
-
-public char[] getContents() {
- if (this.contents != null)
- return this.contents; // answer the cached source
-
- // otherwise retrieve it
- try {
- return Util.getFileCharContent(new File(new String(this.fileName)), this.encoding);
- } catch (IOException e) {
- // could not read file: returns an empty array
- }
- return CharOperation.NO_CHAR;
-}
-/**
- * @see org.eclipse.wst.jsdt.internal.compiler.env.IDependent#getFileName()
- */
-public char[] getFileName() {
- return this.fileName;
-}
-public char[] getMainTypeName() {
- if (this.mainTypeName == null) {
- int start = CharOperation.lastIndexOf('/', this.fileName) + 1;
- if (start == 0 || start < CharOperation.lastIndexOf('\\', this.fileName))
- start = CharOperation.lastIndexOf('\\', this.fileName) + 1;
- int separator = CharOperation.indexOf('|', this.fileName) + 1;
- if (separator > start) // case of a .class file in a default package in a jar
- start = separator;
-
- int end = CharOperation.lastIndexOf('$', this.fileName);
- if (end == -1 || !Util.isClassFileName(this.fileName)) {
- end = CharOperation.lastIndexOf('.', this.fileName);
- if (end == -1)
- end = this.fileName.length;
- }
-
- this.mainTypeName = CharOperation.subarray(this.fileName, start, end);
- }
- return this.mainTypeName;
-}
-public char[][] getPackageName() {
- return this.packageName;
-}
-public String toString(){
- return "JavaScriptUnit: "+new String(this.fileName); //$NON-NLS-1$
-}
-
-/* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit#getCommonSuperType()
- */
-public LibrarySuperType getCommonSuperType() {
- return superType;
-}
-
-public String getInferenceID() {
- return null;
-}
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BatchOperation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BatchOperation.java
deleted file mode 100644
index 2d90c42c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BatchOperation.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*******************************************************************************
- * 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.core.resources.IResourceStatus;
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatus;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-
-/**
- * An operation created as a result of a call to JavaScriptCore.run(IWorkspaceRunnable, IProgressMonitor)
- * that encapsulates a user defined IWorkspaceRunnable.
- */
-public class BatchOperation extends JavaModelOperation {
- protected IWorkspaceRunnable runnable;
- public BatchOperation(IWorkspaceRunnable runnable) {
- this.runnable = runnable;
- }
-
- protected boolean canModifyRoots() {
- // anything in the workspace runnable can modify the roots
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.core.JavaModelOperation#executeOperation()
- */
- protected void executeOperation() throws JavaScriptModelException {
- try {
- this.runnable.run(this.progressMonitor);
- } catch (CoreException ce) {
- if (ce instanceof JavaScriptModelException) {
- throw (JavaScriptModelException)ce;
- } else {
- if (ce.getStatus().getCode() == IResourceStatus.OPERATION_FAILED) {
- Throwable e= ce.getStatus().getException();
- if (e instanceof JavaScriptModelException) {
- throw (JavaScriptModelException) e;
- }
- }
- throw new JavaScriptModelException(ce);
- }
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.core.JavaModelOperation#verify()
- */
- protected IJavaScriptModelStatus verify() {
- // cannot verify user defined operation
- return JavaModelStatus.VERIFIED_OK;
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BecomeWorkingCopyOperation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BecomeWorkingCopyOperation.java
deleted file mode 100644
index 7cd671da..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BecomeWorkingCopyOperation.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*******************************************************************************
- * 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.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptElementDelta;
-import org.eclipse.wst.jsdt.core.IProblemRequestor;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-
-/**
- * Switch and IJavaScriptUnit to working copy mode
- * and signal the working copy addition through a delta.
- */
-public class BecomeWorkingCopyOperation extends JavaModelOperation {
-
- IProblemRequestor problemRequestor;
-
- /*
- * Creates a BecomeWorkingCopyOperation for the given working copy.
- * perOwnerWorkingCopies map is not null if the working copy is a shared working copy.
- */
- public BecomeWorkingCopyOperation(CompilationUnit workingCopy, IProblemRequestor problemRequestor) {
- super(new IJavaScriptElement[] {workingCopy});
- this.problemRequestor = problemRequestor;
- }
- protected void executeOperation() throws JavaScriptModelException {
-
- // open the working copy now to ensure contents are that of the current state of this element
- CompilationUnit workingCopy = getWorkingCopy();
- JavaModelManager.getJavaModelManager().getPerWorkingCopyInfo(workingCopy, true/*create if needed*/, true/*record usage*/, this.problemRequestor);
- workingCopy.openWhenClosed(workingCopy.createElementInfo(), this.progressMonitor);
-
- if (!workingCopy.isPrimary()) {
- // report added java delta for a non-primary working copy
- JavaElementDelta delta = new JavaElementDelta(getJavaModel());
- delta.added(workingCopy);
- addDelta(delta);
- } else {
- if (workingCopy.getResource().isAccessible()) {
- // report a F_PRIMARY_WORKING_COPY change delta for a primary working copy
- JavaElementDelta delta = new JavaElementDelta(getJavaModel());
- delta.changed(workingCopy, IJavaScriptElementDelta.F_PRIMARY_WORKING_COPY);
- addDelta(delta);
- } else {
- // report an ADDED delta
- JavaElementDelta delta = new JavaElementDelta(this.getJavaModel());
- delta.added(workingCopy, IJavaScriptElementDelta.F_PRIMARY_WORKING_COPY);
- addDelta(delta);
- }
- }
-
- this.resultElements = new IJavaScriptElement[] {workingCopy};
- }
- /*
- * Returns the working copy this operation is working on.
- */
- protected CompilationUnit getWorkingCopy() {
- return (CompilationUnit)getElementToProcess();
- }
- /*
- * @see JavaModelOperation#isReadOnly
- */
- public boolean isReadOnly() {
- return true;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BinaryField.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BinaryField.java
deleted file mode 100644
index 954238af..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BinaryField.java
+++ /dev/null
@@ -1,124 +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;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatusConstants;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.internal.compiler.env.IBinaryField;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Binding;
-
-/**
- * @see IField
- */
-
-/* package */ class BinaryField extends BinaryMember implements IField {
-
-/*
- * Constructs a handle to the field with the given name in the specified type.
- */
-protected BinaryField(JavaElement parent, String name) {
- super(parent, name);
-}
-public boolean equals(Object o) {
- if (!(o instanceof BinaryField)) return false;
- return super.equals(o);
-}
-/*
- * @see IField
- */
-public Object getConstant() throws JavaScriptModelException {
- IBinaryField info = (IBinaryField) getElementInfo();
- return convertConstant(info.getConstant());
-}
-/*
- * @see IMember
- */
-public int getFlags() throws JavaScriptModelException {
- IBinaryField info = (IBinaryField) getElementInfo();
- return info.getModifiers();
-}
-/*
- * @see IJavaScriptElement
- */
-public int getElementType() {
- return FIELD;
-}
-/*
- * @see JavaElement#getHandleMemento()
- */
-protected char getHandleMementoDelimiter() {
- return JavaElement.JEM_FIELD;
-}
-public String getKey(boolean forceOpen) throws JavaScriptModelException {
- return getKey(this, forceOpen);
-}
-/*
- * @see IField
- */
-public String getTypeSignature() throws JavaScriptModelException {
- IBinaryField info = (IBinaryField) getElementInfo();
- return new String(ClassFile.translatedName(info.getTypeName()));
-}
-/* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.IField#isResolved()
- */
-public boolean isResolved() {
- return false;
-}
-public JavaElement resolved(Binding binding) {
- SourceRefElement resolvedHandle = new ResolvedBinaryField(this.parent, this.name, new String(binding.computeUniqueKey()));
- resolvedHandle.occurrenceCount = this.occurrenceCount;
- return resolvedHandle;
-}
-/*
- * @private Debugging purposes
- */
-protected void toStringInfo(int tab, StringBuffer buffer, Object info, boolean showResolvedInfo) {
- buffer.append(this.tabString(tab));
- if (info == null) {
- toStringName(buffer);
- buffer.append(" (not open)"); //$NON-NLS-1$
- } else if (info == NO_INFO) {
- toStringName(buffer);
- } else {
- try {
- buffer.append(Signature.toString(this.getTypeSignature()));
- buffer.append(" "); //$NON-NLS-1$
- toStringName(buffer);
- } catch (JavaScriptModelException e) {
- buffer.append("<JavaScriptModelException in toString of " + getElementName()); //$NON-NLS-1$
- }
- }
-}
-public String getAttachedJavadoc(IProgressMonitor monitor) throws JavaScriptModelException {
- String contents = ((BinaryType) this.getDeclaringType()).getJavadocContents(monitor);
- if (contents == null) return null;
- int indexAnchor = contents.indexOf(
- JavadocConstants.ANCHOR_PREFIX_START + this.getElementName() + JavadocConstants.ANCHOR_PREFIX_END);
- if (indexAnchor == -1) throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.UNKNOWN_JSDOC_FORMAT, this));
- int indexOfEndLink = contents.indexOf(JavadocConstants.ANCHOR_SUFFIX, indexAnchor);
- if (indexOfEndLink == -1) throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.UNKNOWN_JSDOC_FORMAT, this));
- int indexOfNextField = contents.indexOf(JavadocConstants.ANCHOR_PREFIX_START, indexOfEndLink);
- int indexOfBottom = contents.indexOf(JavadocConstants.CONSTRUCTOR_DETAIL, indexOfEndLink);
- if (indexOfBottom == -1) {
- indexOfBottom = contents.indexOf(JavadocConstants.METHOD_DETAIL, indexOfEndLink);
- if (indexOfBottom == -1) {
- indexOfBottom = contents.indexOf(JavadocConstants.END_OF_CLASS_DATA, indexOfEndLink);
- }
- }
- indexOfNextField= Math.min(indexOfNextField, indexOfBottom);
- if (indexOfNextField == -1) throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.UNKNOWN_JSDOC_FORMAT, this));
- return contents.substring(indexOfEndLink + JavadocConstants.ANCHOR_SUFFIX_LENGTH, indexOfNextField);
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BinaryMember.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BinaryMember.java
deleted file mode 100644
index 722a2673..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BinaryMember.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*******************************************************************************
- * 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 java.util.HashMap;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatusConstants;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-
-/**
- * Common functionality for Binary member handles.
- */
-public abstract class BinaryMember extends NamedMember {
-/*
- * Constructs a binary member.
- */
-protected BinaryMember(JavaElement parent, String name) {
- super(parent, name);
-}
-/*
- * @see ISourceManipulation
- */
-public void copy(IJavaScriptElement container, IJavaScriptElement sibling, String rename, boolean force, IProgressMonitor monitor) throws JavaScriptModelException {
- throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.READ_ONLY, this));
-}
-/*
- * @see JavaElement#generateInfos
- */
-protected void generateInfos(Object info, HashMap newElements, IProgressMonitor pm) throws JavaScriptModelException {
- Openable openableParent = (Openable) getOpenableParent();
- if (JavaModelManager.getJavaModelManager().getInfo(openableParent) == null) {
- openableParent.generateInfos(openableParent.createElementInfo(), newElements, pm);
- }
-}
-public String[] getCategories() throws JavaScriptModelException {
- SourceMapper mapper= getSourceMapper();
- if (mapper != null) {
- // ensure the class file's buffer is open so that categories are computed
- ((ClassFile)getClassFile()).getBuffer();
-
- if (mapper.categories != null) {
- String[] categories = (String[]) mapper.categories.get(this);
- if (categories != null)
- return categories;
- }
- }
- return CharOperation.NO_STRINGS;
-}
-public String getKey() {
- try {
- return getKey(false/*don't open*/);
- } catch (JavaScriptModelException e) {
- // happen only if force open is true
- return null;
- }
-}
-/**
- * @see org.eclipse.wst.jsdt.internal.compiler.lookup.Binding#computeUniqueKey()
- */
-public abstract String getKey(boolean forceOpen) throws JavaScriptModelException;
-/*
- * @see ISourceReference
- */
-public ISourceRange getNameRange() throws JavaScriptModelException {
- SourceMapper mapper= getSourceMapper();
- if (mapper != null) {
- // ensure the class file's buffer is open so that source ranges are computed
- ((ClassFile)getClassFile()).getBuffer();
-
- return mapper.getNameRange(this);
- } else {
- return SourceMapper.UNKNOWN_RANGE;
- }
-}
-/*
- * @see ISourceReference
- */
-//public ISourceRange getSourceRange() throws JavaScriptModelException {
-// SourceMapper mapper= getSourceMapper();
-// if (mapper != null) {
-// // ensure the class file's buffer is open so that source ranges are computed
-// ((ClassFile)getClassFile()).getBuffer();
-//
-// return mapper.getSourceRange(this);
-// } else {
-// return SourceMapper.UNKNOWN_RANGE;
-// }
-//}
-/*
- * @see IMember
- */
-public boolean isBinary() {
- return true;
-}
-/*
- * @see IJavaScriptElement
- */
-public boolean isStructureKnown() throws JavaScriptModelException {
- return ((IJavaScriptElement)getOpenableParent()).isStructureKnown();
-}
-/*
- * @see ISourceManipulation
- */
-public void move(IJavaScriptElement container, IJavaScriptElement sibling, String rename, boolean force, IProgressMonitor monitor) throws JavaScriptModelException {
- throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.READ_ONLY, this));
-}
-/*
- * @see ISourceManipulation
- */
-public void rename(String newName, boolean force, IProgressMonitor monitor) throws JavaScriptModelException {
- throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.READ_ONLY, this));
-}
-/*
- * Sets the contents of this element.
- * Throws an exception as this element is read only.
- */
-public void setContents(String contents, IProgressMonitor monitor) throws JavaScriptModelException {
- throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.READ_ONLY, this));
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BinaryMethod.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BinaryMethod.java
deleted file mode 100644
index 9033e9b5..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BinaryMethod.java
+++ /dev/null
@@ -1,620 +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;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatusConstants;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-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.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.env.IBinaryMethod;
-import org.eclipse.wst.jsdt.internal.compiler.env.IBinaryType;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Binding;
-import org.eclipse.wst.jsdt.internal.core.JavaModelManager.PerProjectInfo;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * @see IFunction
- */
-
-/* package */ class BinaryMethod extends BinaryMember implements IFunction {
- /**
- * The parameter type signatures of the method - stored locally
- * to perform equality test. <code>null</code> indicates no
- * parameters.
- */
- protected String[] parameterTypes;
- /**
- * The parameter names for the method.
- */
- protected String[] parameterNames;
-
- protected String[] exceptionTypes;
- protected String returnType;
-
-protected BinaryMethod(JavaElement parent, String name, String[] paramTypes) {
- super(parent, name);
- // Assertion disabled since bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=179011
- // Assert.isTrue(name.indexOf('.') == -1);
- if (paramTypes == null) {
- this.parameterTypes= CharOperation.NO_STRINGS;
- } else {
- this.parameterTypes= paramTypes;
- }
-}
-public boolean equals(Object o) {
- if (!(o instanceof BinaryMethod)) return false;
- return super.equals(o) && Util.equalArraysOrNull(this.parameterTypes, ((BinaryMethod)o).parameterTypes);
-}
-/*
- * @see IFunction
- */
-public String[] getExceptionTypes() throws JavaScriptModelException {
- if (this.exceptionTypes == null) {
- IBinaryMethod info = (IBinaryMethod) getElementInfo();
- char[] genericSignature = info.getGenericSignature();
- if (genericSignature != null) {
- char[] dotBasedSignature = CharOperation.replaceOnCopy(genericSignature, '/', '.');
- this.exceptionTypes = new String[0];
- }
- if (this.exceptionTypes == null || this.exceptionTypes.length == 0) {
- char[][] eTypeNames = info.getExceptionTypeNames();
- if (eTypeNames == null || eTypeNames.length == 0) {
- this.exceptionTypes = CharOperation.NO_STRINGS;
- } else {
- eTypeNames = ClassFile.translatedNames(eTypeNames);
- this.exceptionTypes = new String[eTypeNames.length];
- for (int j = 0, length = eTypeNames.length; j < length; j++) {
- // 1G01HRY: ITPJCORE:WINNT - method.getExceptionType not in correct format
- int nameLength = eTypeNames[j].length;
- char[] convertedName = new char[nameLength + 2];
- System.arraycopy(eTypeNames[j], 0, convertedName, 1, nameLength);
- convertedName[0] = 'L';
- convertedName[nameLength + 1] = ';';
- this.exceptionTypes[j] = new String(convertedName);
- }
- }
- }
- }
- return this.exceptionTypes;
-}
-/*
- * @see IJavaScriptElement
- */
-public int getElementType() {
- return METHOD;
-}
-/*
- * @see IMember
- */
-public int getFlags() throws JavaScriptModelException {
- IBinaryMethod info = (IBinaryMethod) getElementInfo();
- return info.getModifiers();
-}
-/*
- * @see JavaElement#getHandleMemento(StringBuffer)
- */
-protected void getHandleMemento(StringBuffer buff) {
- ((JavaElement) getParent()).getHandleMemento(buff);
- char delimiter = getHandleMementoDelimiter();
- buff.append(delimiter);
- escapeMementoName(buff, getElementName());
- for (int i = 0; i < this.parameterTypes.length; i++) {
- buff.append(delimiter);
- escapeMementoName(buff, this.parameterTypes[i]);
- }
- if (this.occurrenceCount > 1) {
- buff.append(JEM_COUNT);
- buff.append(this.occurrenceCount);
- }
-}
-/*
- * @see JavaElement#getHandleMemento()
- */
-protected char getHandleMementoDelimiter() {
- return JavaElement.JEM_METHOD;
-}
-public String getKey(boolean forceOpen) throws JavaScriptModelException {
- return getKey(this, forceOpen);
-}
-/*
- * @see IFunction
- */
-public int getNumberOfParameters() {
- return this.parameterTypes == null ? 0 : this.parameterTypes.length;
-}
-/*
- * @see IFunction
- * Look for source attachment information to retrieve the actual parameter names as stated in source.
- */
-public String[] getParameterNames() throws JavaScriptModelException {
- if (this.parameterNames != null)
- return this.parameterNames;
-
- // force source mapping if not already done
- IType type = (IType) getParent();
- SourceMapper mapper = getSourceMapper();
- if (mapper != null) {
- char[][] paramNames = mapper.getMethodParameterNames(this);
-
- // map source and try to find parameter names
- if(paramNames == null) {
- IBinaryType info = (IBinaryType) ((BinaryType) getDeclaringType()).getElementInfo();
- char[] source = mapper.findSource(type, info);
- if (source != null){
- mapper.mapSource(type, source, info);
- }
- paramNames = mapper.getMethodParameterNames(this);
- }
-
- // if parameter names exist, convert parameter names to String array
- if(paramNames != null) {
- this.parameterNames = new String[paramNames.length];
- for (int i = 0; i < paramNames.length; i++) {
- this.parameterNames[i] = new String(paramNames[i]);
- }
- return this.parameterNames;
- }
- }
-
- // try to see if we can retrieve the names from the attached javadoc
- IBinaryMethod info = (IBinaryMethod) getElementInfo();
- final int paramCount = Signature.getParameterCount(new String(info.getMethodDescriptor()));
- if (paramCount != 0) {
- // don't try to look for javadoc for synthetic methods
- int modifiers = this.getFlags();
-
- String javadocContents = null;
- IType declaringType = this.getDeclaringType();
- PerProjectInfo projectInfo = JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(this.getJavaScriptProject().getProject());
- synchronized (projectInfo.javadocCache) {
- javadocContents = (String) projectInfo.javadocCache.get(declaringType);
- if (javadocContents == null) {
- projectInfo.javadocCache.put(declaringType, BinaryType.EMPTY_JAVADOC);
- }
- }
- if (javadocContents == null) {
- long timeOut = 50; // default value
- try {
- String option = this.getJavaScriptProject().getOption(JavaScriptCore.TIMEOUT_FOR_PARAMETER_NAME_FROM_ATTACHED_JAVADOC, true);
- if (option != null) {
- timeOut = Long.parseLong(option);
- }
- } catch(NumberFormatException e) {
- // ignore
- }
- if (timeOut == 0) {
- // don't try to fetch the values
- return this.parameterNames = getRawParameterNames(paramCount);
- }
- final class ParametersNameCollector {
- String javadoc;
- public void setJavadoc(String s) {
- this.javadoc = s;
- }
- public String getJavadoc() {
- return this.javadoc;
- }
- }
- /*
- * The declaring type is not in the cache yet. The thread wil retrieve the javadoc contents
- */
- final ParametersNameCollector nameCollector = new ParametersNameCollector();
- Thread collect = new Thread() {
- public void run() {
- try {
- // this call has a side-effect on the per project info cache
- nameCollector.setJavadoc(BinaryMethod.this.getAttachedJavadoc(null));
- } catch (JavaScriptModelException e) {
- // ignore
- }
- synchronized(nameCollector) {
- nameCollector.notify();
- }
- }
- };
- collect.start();
- synchronized(nameCollector) {
- try {
- nameCollector.wait(timeOut);
- } catch (InterruptedException e) {
- // ignore
- }
- }
- javadocContents = nameCollector.getJavadoc();
- } else if (javadocContents != BinaryType.EMPTY_JAVADOC){
- // need to extract the part relative to the binary method since javadoc contains the javadoc for the declaring type
- try {
- javadocContents = extractJavadoc(declaringType, javadocContents);
- } catch(JavaScriptModelException e) {
- // ignore
- }
- } else {
- // let's see if we can retrieve them from the debug infos
- char[][] argumentNames = info.getArgumentNames();
- if (argumentNames != null && argumentNames.length == paramCount) {
- String[] names = new String[paramCount];
- for (int i = 0; i < paramCount; i++) {
- names[i] = new String(argumentNames[i]);
- }
- return this.parameterNames = names;
- }
- return getRawParameterNames(paramCount);
- }
- if (javadocContents != null && javadocContents != BinaryType.EMPTY_JAVADOC) {
- final int indexOfOpenParen = javadocContents.indexOf('(');
- if (indexOfOpenParen != -1) {
- final int indexOfClosingParen = javadocContents.indexOf(')', indexOfOpenParen);
- if (indexOfClosingParen != -1) {
- final char[] paramsSource =
- CharOperation.replace(
- javadocContents.substring(indexOfOpenParen + 1, indexOfClosingParen).toCharArray(),
- "&nbsp;".toCharArray(), //$NON-NLS-1$
- new char[] {' '});
- final char[][] params = splitParameters(paramsSource, paramCount);
- final int paramsLength = params.length;
- this.parameterNames = new String[paramsLength];
- for (int i = 0; i < paramsLength; i++) {
- final char[] param = params[i];
- int indexOfSpace = CharOperation.lastIndexOf(' ', param);
- if (indexOfSpace != -1) {
- this.parameterNames[i] = String.valueOf(param, indexOfSpace + 1, param.length - indexOfSpace -1);
- } else {
- this.parameterNames[i] = "arg" + i; //$NON-NLS-1$
- }
- }
- return this.parameterNames;
- }
- }
- }
- // let's see if we can retrieve them from the debug infos
- char[][] argumentNames = info.getArgumentNames();
- if (argumentNames != null && argumentNames.length == paramCount) {
- String[] names = new String[paramCount];
- for (int i = 0; i < paramCount; i++) {
- names[i] = new String(argumentNames[i]);
- }
- return this.parameterNames = names;
- }
- }
- // if still no parameter names, produce fake ones
- return this.parameterNames = getRawParameterNames(paramCount);
-}
-private char[][] splitParameters(char[] parametersSource, int paramCount) {
- // we have generic types as one of the parameter types
- char[][] params = new char[paramCount][];
- int paramIndex = 0;
- int index = 0;
- int balance = 0;
- int length = parametersSource.length;
- int start = 0;
- while(index < length) {
- switch (parametersSource[index]) {
- case '<':
- balance++;
- index++;
- while(index < length && parametersSource[index] != '>') {
- index++;
- }
- break;
- case '>' :
- balance--;
- index++;
- break;
- case ',' :
- if (balance == 0 && paramIndex < paramCount) {
- params[paramIndex++] = CharOperation.subarray(parametersSource, start, index);
- start = index + 1;
- }
- index++;
- break;
- case '&' :
- if ((index + 4) < length) {
- if (parametersSource[index + 1] == 'l'
- && parametersSource[index + 2] == 't'
- && parametersSource[index + 3] == ';') {
- balance++;
- index += 4;
- } else if (parametersSource[index + 1] == 'g'
- && parametersSource[index + 2] == 't'
- && parametersSource[index + 3] == ';') {
- balance--;
- index += 4;
- } else {
- index++;
- }
- } else {
- index++;
- }
- break;
- default:
- index++;
- }
- }
- if (paramIndex < paramCount) {
- params[paramIndex++] = CharOperation.subarray(parametersSource, start, index);
- }
- if (paramIndex != paramCount) {
- // happens only for constructors with synthetic enclosing type in the signature
- System.arraycopy(params, 0, (params = new char[paramIndex][]), 0, paramIndex);
- }
- return params;
-}
-/*
- * @see IFunction
- */
-public String[] getParameterTypes() {
- return this.parameterTypes;
-}
-
-public String[] getRawParameterNames() throws JavaScriptModelException {
- IBinaryMethod info = (IBinaryMethod) getElementInfo();
- int paramCount = Signature.getParameterCount(new String(info.getMethodDescriptor()));
- return getRawParameterNames(paramCount);
-}
-private String[] getRawParameterNames(int paramCount) {
- String[] result = new String[paramCount];
- for (int i = 0; i < paramCount; i++) {
- result[i] = "arg" + i; //$NON-NLS-1$
- }
- return result;
-}
-
-/*
- * @see IFunction
- */
-public String getReturnType() throws JavaScriptModelException {
- if (this.returnType == null) {
- IBinaryMethod info = (IBinaryMethod) getElementInfo();
- this.returnType = getReturnType(info);
- }
- return this.returnType;
-}
-private String getReturnType(IBinaryMethod info) {
- char[] genericSignature = info.getGenericSignature();
- char[] signature = genericSignature == null ? info.getMethodDescriptor() : genericSignature;
- char[] dotBasedSignature = CharOperation.replaceOnCopy(signature, '/', '.');
- String returnTypeName= Signature.getReturnType(new String(dotBasedSignature));
- return new String(ClassFile.translatedName(returnTypeName.toCharArray()));
-}
-/*
- * @see IFunction
- */
-public String getSignature() throws JavaScriptModelException {
- IBinaryMethod info = (IBinaryMethod) getElementInfo();
- return new String(info.getMethodDescriptor());
-}
-/**
- * @see org.eclipse.wst.jsdt.internal.core.JavaElement#hashCode()
- */
-public int hashCode() {
- int hash = super.hashCode();
-// for (int i = 0, length = parameterTypes.length; i < length; i++) {
-// hash = Util.combineHashCodes(hash, parameterTypes[i].hashCode());
-// }
- return hash;
-}
-/*
- * @see IFunction
- */
-public boolean isConstructor() throws JavaScriptModelException {
- if (!this.getElementName().equals(this.parent.getElementName())) {
- // faster than reaching the info
- return false;
- }
- IBinaryMethod info = (IBinaryMethod) getElementInfo();
- return info.isConstructor();
-}
-/*
- * @see IFunction#isMainMethod()
- */
-public boolean isMainMethod() throws JavaScriptModelException {
- return this.isMainMethod(this);
-}
-/* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.IFunction#isResolved()
- */
-public boolean isResolved() {
- return false;
-}
-/*
- * @see IFunction#isSimilar(IFunction)
- */
-public boolean isSimilar(IFunction method) {
- return
- areSimilarMethods(
- this.getElementName(), this.getParameterTypes(),
- method.getElementName(), method.getParameterTypes(),
- null);
-}
-
-public String readableName() {
-
- StringBuffer buffer = new StringBuffer(super.readableName());
- buffer.append("("); //$NON-NLS-1$
- String[] paramTypes = this.parameterTypes;
- int length;
- if (paramTypes != null && (length = paramTypes.length) > 0) {
- for (int i = 0; i < length; i++) {
- buffer.append(Signature.toString(paramTypes[i]));
- if (i < length - 1) {
- buffer.append(", "); //$NON-NLS-1$
- }
- }
- }
- buffer.append(")"); //$NON-NLS-1$
- return buffer.toString();
-}
-public JavaElement resolved(Binding binding) {
- SourceRefElement resolvedHandle = new ResolvedBinaryMethod(this.parent, this.name, this.parameterTypes, new String(binding.computeUniqueKey()));
- resolvedHandle.occurrenceCount = this.occurrenceCount;
- return resolvedHandle;
-}/*
- * @private Debugging purposes
- */
-protected void toStringInfo(int tab, StringBuffer buffer, Object info, boolean showResolvedInfo) {
- buffer.append(tabString(tab));
- if (info == null) {
- toStringName(buffer);
- buffer.append(" (not open)"); //$NON-NLS-1$
- } else if (info == NO_INFO) {
- toStringName(buffer);
- } else {
- IBinaryMethod methodInfo = (IBinaryMethod) info;
- int flags = methodInfo.getModifiers();
- if (Flags.isStatic(flags)) {
- buffer.append("static "); //$NON-NLS-1$
- }
- if (!methodInfo.isConstructor()) {
- buffer.append(Signature.toString(getReturnType(methodInfo)));
- buffer.append(' ');
- }
- toStringName(buffer, flags);
- }
-}
-protected void toStringName(StringBuffer buffer) {
- toStringName(buffer, 0);
-}
-protected void toStringName(StringBuffer buffer, int flags) {
- buffer.append(getElementName());
- buffer.append('(');
- String[] parameters = getParameterTypes();
- int length;
- if (parameters != null && (length = parameters.length) > 0) {
- boolean isVarargs = Flags.isVarargs(flags);
- for (int i = 0; i < length; i++) {
- try {
- if (i < length - 1) {
- buffer.append(Signature.toString(parameters[i]));
- buffer.append(", "); //$NON-NLS-1$
- } else if (isVarargs) {
- // remove array from signature
- String parameter = parameters[i].substring(1);
- buffer.append(Signature.toString(parameter));
- buffer.append(" ..."); //$NON-NLS-1$
- } else {
- buffer.append(Signature.toString(parameters[i]));
- }
- } catch (IllegalArgumentException e) {
- // parameter signature is malformed
- buffer.append("*** invalid signature: "); //$NON-NLS-1$
- buffer.append(parameters[i]);
- }
- }
- }
- buffer.append(')');
- if (this.occurrenceCount > 1) {
- buffer.append("#"); //$NON-NLS-1$
- buffer.append(this.occurrenceCount);
- }
-}
-public String getAttachedJavadoc(IProgressMonitor monitor) throws JavaScriptModelException {
- IType declaringType = this.getDeclaringType();
-
- String contents = ((BinaryType) declaringType).getJavadocContents(monitor);
- return extractJavadoc(declaringType, contents);
-}
-private String extractJavadoc(IType declaringType, String contents) throws JavaScriptModelException {
- if (contents == null) return null;
-
- String typeQualifiedName = null;
- final boolean declaringTypeIsMember = declaringType.isMember();
- if (declaringTypeIsMember) {
- IType currentType = declaringType;
- StringBuffer buffer = new StringBuffer();
- while (currentType != null) {
- buffer.insert(0, currentType.getElementName());
- currentType = currentType.getDeclaringType();
- if (currentType != null) {
- buffer.insert(0, '.');
- }
- }
- typeQualifiedName = new String(buffer.toString());
- } else {
- typeQualifiedName = declaringType.getElementName();
- }
- String methodName = this.getElementName();
- if (this.isConstructor()) {
- methodName = typeQualifiedName;
- }
- IBinaryMethod info = (IBinaryMethod) getElementInfo();
- char[] genericSignature = info.getGenericSignature();
- String anchor = null;
- if (genericSignature != null) {
- genericSignature = CharOperation.replaceOnCopy(genericSignature, '/', '.');
- anchor = Util.toAnchor(genericSignature, methodName, Flags.isVarargs(this.getFlags()));
- if (anchor == null) throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.UNKNOWN_JSDOC_FORMAT, this));
- } else {
- anchor = Signature.toString(this.getSignature().replace('/', '.'), methodName, null, true, false, Flags.isVarargs(this.getFlags()));
- }
- if (declaringTypeIsMember) {
- int depth = 0;
- final String packageFragmentName = declaringType.getPackageFragment().getElementName();
- // might need to remove a part of the signature corresponding to the synthetic argument
- final IJavaScriptProject javaProject = declaringType.getJavaScriptProject();
- char[][] typeNames = CharOperation.splitOn('.', typeQualifiedName.toCharArray());
- if (!Flags.isStatic(declaringType.getFlags())) depth++;
- StringBuffer typeName = new StringBuffer();
- for (int i = 0, max = typeNames.length; i < max; i++) {
- if (typeName.length() == 0) {
- typeName.append(typeNames[i]);
- } else {
- typeName.append('.').append(typeNames[i]);
- }
- IType resolvedType = javaProject.findType(packageFragmentName, String.valueOf(typeName));
- if (resolvedType != null && resolvedType.isMember() && !Flags.isStatic(resolvedType.getFlags())) depth++;
- }
- if (depth != 0) {
- int indexOfOpeningParen = anchor.indexOf('(');
- if (indexOfOpeningParen == -1) return null;
- int index = indexOfOpeningParen;
- indexOfOpeningParen++;
- for (int i = 0; i < depth; i++) {
- int indexOfComma = anchor.indexOf(',', index);
- if (indexOfComma != -1) {
- index = indexOfComma + 2;
- }
- }
- anchor = anchor.substring(0, indexOfOpeningParen) + anchor.substring(index);
- }
- }
- int indexAnchor = contents.indexOf(JavadocConstants.ANCHOR_PREFIX_START + anchor + JavadocConstants.ANCHOR_PREFIX_END);
- if (indexAnchor == -1) {
- return null; // method without javadoc
- }
- int indexOfEndLink = contents.indexOf(JavadocConstants.ANCHOR_SUFFIX, indexAnchor);
- if (indexOfEndLink == -1) throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.UNKNOWN_JSDOC_FORMAT, this));
- int indexOfNextMethod = contents.indexOf(JavadocConstants.ANCHOR_PREFIX_START, indexOfEndLink);
- // find bottom
- int indexOfBottom = -1;
- if (this.isConstructor()) {
- indexOfBottom = contents.indexOf(JavadocConstants.METHOD_DETAIL, indexOfEndLink);
- if (indexOfBottom == -1) {
- indexOfBottom = contents.indexOf(JavadocConstants.END_OF_CLASS_DATA, indexOfEndLink);
- }
- } else {
- indexOfBottom = contents.indexOf(JavadocConstants.END_OF_CLASS_DATA, indexOfEndLink);
- }
- if (indexOfBottom == -1) throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.UNKNOWN_JSDOC_FORMAT, this));
- indexOfNextMethod = Math.min(indexOfNextMethod, indexOfBottom);
- if (indexOfNextMethod == -1) throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.UNKNOWN_JSDOC_FORMAT, this));
- return contents.substring(indexOfEndLink + JavadocConstants.ANCHOR_SUFFIX_LENGTH, indexOfNextMethod);
-}
-public IFunction getFunction(String selector, String[] parameterTypeSignatures) {
- // TODO Auto-generated method stub
- return null;
-}
-}
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
deleted file mode 100644
index 91859647..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BinaryType.java
+++ /dev/null
@@ -1,882 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core;
-
-import java.io.InputStream;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.HashMap;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.wst.jsdt.core.CompletionRequestor;
-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.IInitializer;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-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.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-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.search.SearchEngine;
-import org.eclipse.wst.jsdt.internal.codeassist.CompletionEngine;
-import org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.env.IBinaryType;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Binding;
-import org.eclipse.wst.jsdt.internal.compiler.util.SuffixConstants;
-import org.eclipse.wst.jsdt.internal.core.JavaModelManager.PerProjectInfo;
-import org.eclipse.wst.jsdt.internal.core.hierarchy.TypeHierarchy;
-import org.eclipse.wst.jsdt.internal.core.util.MementoTokenizer;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * Parent is an IClassFile.
- *
- * @see IType
- */
-
-public class BinaryType extends BinaryMember implements IType, SuffixConstants {
-
- private static final IField[] NO_FIELDS = new IField[0];
- private static final IFunction[] NO_METHODS = new IFunction[0];
- private static final IType[] NO_TYPES = new IType[0];
- private static final IInitializer[] NO_INITIALIZERS = new IInitializer[0];
- public static final String EMPTY_JAVADOC = org.eclipse.wst.jsdt.internal.compiler.util.Util.EMPTY_STRING;
-
-protected BinaryType(JavaElement parent, String name) {
- super(parent, name);
-}
-/*
- * Remove my cached children from the Java Model
- */
-protected void closing(Object info) throws JavaScriptModelException {
- ClassFileInfo cfi = getClassFileInfo();
- cfi.removeBinaryChildren();
-}
-
-/*
- * @see IType#codeComplete(char[], int, int, char[][], char[][], int[], boolean, ICompletionRequestor)
- */
-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#codeComplete(char[], int, int, char[][], char[][], int[], boolean, ICompletionRequestor, WorkingCopyOwner)
- */
-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$
- }
- JavaProject project = (JavaProject) getJavaScriptProject();
- SearchableEnvironment environment = newSearchableNameEnvironment(owner);
- CompletionEngine engine = new CompletionEngine(environment, requestor, project.getOptions(true), project);
-
- String source = getClassFile().getSource();
- if (source != null && insertion > -1 && insertion < source.length()) {
- // code complete
-
- 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);
-
- BasicCompilationUnit cu =
- new BasicCompilationUnit(
- fakeSource,
- null,
- getElementName(),
- project); // use project to retrieve corresponding .js IFile
-
- 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$
- }
-}
-
-/*
- * @see IType#createField(String, IJavaScriptElement, boolean, IProgressMonitor)
- */
-public IField createField(String contents, IJavaScriptElement sibling, boolean force, IProgressMonitor monitor) throws JavaScriptModelException {
- throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.READ_ONLY, this));
-}
-/*
- * @see IType#createInitializer(String, IJavaScriptElement, IProgressMonitor)
- */
-public IInitializer createInitializer(String contents, IJavaScriptElement sibling, IProgressMonitor monitor) throws JavaScriptModelException {
- throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.READ_ONLY, this));
-}
-/*
- * @see IType#createMethod(String, IJavaScriptElement, boolean, IProgressMonitor)
- */
-public IFunction createMethod(String contents, IJavaScriptElement sibling, boolean force, IProgressMonitor monitor) throws JavaScriptModelException {
- throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.READ_ONLY, this));
-}
-/*
- * @see IType#createType(String, IJavaScriptElement, boolean, IProgressMonitor)
- */
-public IType createType(String contents, IJavaScriptElement sibling, boolean force, IProgressMonitor monitor) throws JavaScriptModelException {
- throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.READ_ONLY, this));
-}
-public boolean equals(Object o) {
- if (!(o instanceof BinaryType)) return false;
- return super.equals(o);
-}
-/*
- * @see IType#findMethods(IFunction)
- */
-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 IParent#getChildren()
- */
-public IJavaScriptElement[] getChildren() throws JavaScriptModelException {
- ClassFileInfo cfi = getClassFileInfo();
- return cfi.binaryChildren;
-}
-public IJavaScriptElement[] getChildrenForCategory(String category) throws JavaScriptModelException {
- IJavaScriptElement[] children = getChildren();
- int length = children.length;
- if (length == 0) return children;
- SourceMapper mapper= getSourceMapper();
- if (mapper != null) {
- // ensure the class file's buffer is open so that categories are computed
- ((ClassFile)getClassFile()).getBuffer();
-
- HashMap categories = mapper.categories;
- IJavaScriptElement[] result = new IJavaScriptElement[length];
- int index = 0;
- if (categories != null) {
- for (int i = 0; i < length; i++) {
- IJavaScriptElement child = children[i];
- String[] cats = (String[]) categories.get(child);
- if (cats != null) {
- for (int j = 0, length2 = cats.length; j < length2; j++) {
- if (cats[j].equals(category)) {
- result[index++] = child;
- break;
- }
- }
- }
- }
- }
- if (index < length)
- System.arraycopy(result, 0, result = new IJavaScriptElement[index], 0, index);
- return result;
- }
- return NO_ELEMENTS;
-}
-protected ClassFileInfo getClassFileInfo() throws JavaScriptModelException {
- ClassFile cf = (ClassFile)this.parent;
- return (ClassFileInfo) cf.getElementInfo();
-}
-/*
- * @see IMember#getDeclaringType()
- */
-public IType getDeclaringType() {
- IClassFile classFile = this.getClassFile();
- if (classFile.isOpen()) {
- try {
- char[] enclosingTypeName = ((IBinaryType) getElementInfo()).getEnclosingTypeName();
- if (enclosingTypeName == null) {
- return null;
- }
- enclosingTypeName = ClassFile.unqualifiedName(enclosingTypeName);
-
- // workaround problem with class files compiled with javac 1.1.*
- // that return a non-null enclosing type name for local types defined in anonymous (e.g. A$1$B)
- if (classFile.getElementName().length() > enclosingTypeName.length+1
- && Character.isDigit(classFile.getElementName().charAt(enclosingTypeName.length+1))) {
- return null;
- }
-
- return getPackageFragment().getClassFile(new String(enclosingTypeName) + SUFFIX_STRING_java).getType();
- } catch (JavaScriptModelException npe) {
- return null;
- }
- } else {
- // cannot access .class file without opening it
- // and getDeclaringType() is supposed to be a handle-only method,
- // so default to assuming $ is an enclosing type separator
- String classFileName = classFile.getElementName();
- int lastDollar = -1;
- for (int i = 0, length = classFileName.length(); i < length; i++) {
- char c = classFileName.charAt(i);
- if (Character.isDigit(c) && lastDollar == i-1) {
- // anonymous or local type
- return null;
- } else if (c == '$') {
- lastDollar = i;
- }
- }
- if (lastDollar == -1) {
- return null;
- } else {
- String enclosingName = classFileName.substring(0, lastDollar);
- String enclosingClassFileName = enclosingName + SUFFIX_STRING_java;
- return
- new BinaryType(
- (JavaElement)this.getPackageFragment().getClassFile(enclosingClassFileName),
- Util.localTypeName(enclosingName, enclosingName.lastIndexOf('$'), enclosingName.length()));
- }
- }
-}
-public Object getElementInfo(IProgressMonitor monitor) throws JavaScriptModelException {
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- Object info = manager.getInfo(this);
- if (info != null && info != JavaModelCache.NON_EXISTING_JAR_TYPE_INFO) return info;
- return openWhenClosed(createElementInfo(), monitor);
-}
-/*
- * @see IJavaScriptElement
- */
-public int getElementType() {
- return TYPE;
-}
-/*
- * @see IType#getField(String name)
- */
-public IField getField(String fieldName) {
- return new BinaryField(this, fieldName);
-}
-/*
- * @see IType#getFields()
- */
-public IField[] getFields() throws JavaScriptModelException {
- ArrayList list = getChildrenOfType(FIELD);
- int size;
- if ((size = list.size()) == 0) {
- return NO_FIELDS;
- } else {
- IField[] array= new IField[size];
- list.toArray(array);
- return array;
- }
-}
-/*
- * @see IMember#getFlags()
- */
-public int getFlags() throws JavaScriptModelException {
- IBinaryType info = (IBinaryType) getElementInfo();
- return info.getModifiers();
-}
-/*
- * @see IType#getFullyQualifiedName()
- */
-public String getFullyQualifiedName() {
- return this.getFullyQualifiedName('$');
-}
-/*
- * @see IType#getFullyQualifiedName(char enclosingTypeSeparator)
- */
-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:
- 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$
- } else {
- 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);
- }
- case JEM_TYPE_PARAMETER:
- if (!memento.hasMoreTokens()) return this;
-// String typeParameterName = memento.nextToken();
-// JavaElement typeParameter = null;
-// return typeParameter.getHandleFromMemento(memento, workingCopyOwner);
- }
- return null;
-}
-/*
- * @see IType#getInitializer(int occurrenceCount)
- */
-public IInitializer getInitializer(int count) {
- return new Initializer(this, count);
-}
-/*
- * @see IType#getInitializers()
- */
-public IInitializer[] getInitializers() {
- return NO_INITIALIZERS;
-}
-public String getKey(boolean forceOpen) throws JavaScriptModelException {
- return getKey(this, forceOpen);
-}
-/*
- * @see IType#getMethod(String name, String[] parameterTypeSignatures)
- */
-public IFunction getFunction(String selector, String[] parameterTypeSignatures) {
- return new BinaryMethod(this, selector, parameterTypeSignatures);
-}
-
-/*
- * @see IType#getMethods()
- */
-public IFunction[] getFunctions() throws JavaScriptModelException {
- ArrayList list = getChildrenOfType(METHOD);
- int size;
- if ((size = list.size()) == 0) {
- return NO_METHODS;
- } else {
- IFunction[] array= new IFunction[size];
- list.toArray(array);
- return array;
- }
-}
-/*
- * @see IType#getPackageFragment()
- */
-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 IType#getSuperclassTypeSignature()
- * @since 3.0
- */
-public String getSuperclassTypeSignature() throws JavaScriptModelException {
- IBinaryType info = (IBinaryType) getElementInfo();
- char[] genericSignature = info.getGenericSignature();
- if (genericSignature != null) {
- int signatureLength = genericSignature.length;
- // skip type parameters
- int index = 0;
- if (genericSignature[0] == '<') {
- int count = 1;
- while (count > 0 && ++index < signatureLength) {
- switch (genericSignature[index]) {
- case '<':
- count++;
- break;
- case '>':
- count--;
- break;
- }
- }
- index++;
- }
- int start = index;
- index = Util.scanClassTypeSignature(genericSignature, start) + 1;
- char[] superclassSig = CharOperation.subarray(genericSignature, start, index);
- return new String(ClassFile.translatedName(superclassSig));
- } else {
- char[] superclassName = info.getSuperclassName();
- if (superclassName == null) {
- return null;
- }
- return new String(Signature.createTypeSignature(ClassFile.translatedName(superclassName), true));
- }
-}
-
-public String getSourceFileName(IBinaryType info) {
- if (info == null) {
- try {
- info = (IBinaryType) getElementInfo();
- } catch (JavaScriptModelException e) {
- // default to using the outer most declaring type name
- IType type = this;
- IType enclosingType = getDeclaringType();
- while (enclosingType != null) {
- type = enclosingType;
- enclosingType = type.getDeclaringType();
- }
- return type.getElementName() + Util.defaultJavaExtension();
- }
- }
- return sourceFileName(info);
-}
-
-/*
- * @see IType#getSuperclassName()
- */
-public String getSuperclassName() throws JavaScriptModelException {
- IBinaryType info = (IBinaryType) getElementInfo();
- char[] superclassName = info.getSuperclassName();
- if (superclassName == null) {
- return null;
- }
- return new String(ClassFile.translatedName(superclassName));
-}
-
-/**
- * @see IType#getTypeParameterSignatures()
- * @since 3.0
- */
-public String[] getTypeParameterSignatures() throws JavaScriptModelException {
- IBinaryType info = (IBinaryType) getElementInfo();
- char[] genericSignature = info.getGenericSignature();
- if (genericSignature == null)
- return CharOperation.NO_STRINGS;
-
- char[][] typeParams = new char[0][0];
- return CharOperation.toStrings(typeParams);
-}
-
-/*
- * @see IType#getType(String)
- */
-public IType getType(String typeName) {
- IClassFile classFile= getPackageFragment().getClassFile(getTypeQualifiedName() + "$" + typeName + SUFFIX_STRING_java); //$NON-NLS-1$
- return new BinaryType((JavaElement)classFile, 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#getTypes()
- */
-public IType[] getTypes() throws JavaScriptModelException {
- ArrayList list = getChildrenOfType(TYPE);
- int size;
- if ((size = list.size()) == 0) {
- return NO_TYPES;
- } else {
- IType[] array= new IType[size];
- list.toArray(array);
- return array;
- }
-}
-
-/*
- * @see IType#isAnonymous()
- */
-public boolean isAnonymous() throws JavaScriptModelException {
- IBinaryType info = (IBinaryType) getElementInfo();
- return info.isAnonymous();
-}
-/*
- * @see IType#isClass()
- */
-public boolean isClass() throws JavaScriptModelException {
- IBinaryType info = (IBinaryType) getElementInfo();
- return TypeDeclaration.kind(info.getModifiers()) == TypeDeclaration.CLASS_DECL;
-
-}
-
-/*
- * @see IType#isLocal()
- */
-public boolean isLocal() throws JavaScriptModelException {
- IBinaryType info = (IBinaryType) getElementInfo();
- return info.isLocal();
-}
-/*
- * @see IType#isMember()
- */
-public boolean isMember() throws JavaScriptModelException {
- IBinaryType info = (IBinaryType) getElementInfo();
- return info.isMember();
-}
-/* (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);
-}
-/*
- * @see IType
- */
-public ITypeHierarchy loadTypeHierachy(InputStream input, WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaScriptModelException {
- return TypeHierarchy.load(this, input, owner);
-}
-/*
- * @see IType#newSupertypeHierarchy(IProgressMonitor monitor)
- */
-public ITypeHierarchy newSupertypeHierarchy(IProgressMonitor monitor) throws JavaScriptModelException {
- return this.newSupertypeHierarchy(DefaultWorkingCopyOwner.PRIMARY, monitor);
-}
-/*
- *@see IType#newSupertypeHierarchy(IJavaScriptUnit[], IProgressMonitor monitor)
- */
-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#newTypeHierarchy(IJavaScriptProject, IProgressMonitor)
- */
-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;
- }
- }
- 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();
-}
-/**
- * @param monitor the given progress monitor
- * @exception JavaScriptModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- * @return a type hierarchy for this type containing
- *
- * @see IType#newTypeHierarchy(IProgressMonitor monitor)
- * @deprecated
- */
-public ITypeHierarchy newTypeHierarchy(IProgressMonitor monitor) throws JavaScriptModelException {
- return newTypeHierarchy((IJavaScriptUnit[])null, monitor);
-}
-/*
- * @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 ResolvedBinaryType(this.parent, this.name, new String(binding.computeUniqueKey()));
- resolvedHandle.occurrenceCount = this.occurrenceCount;
- return resolvedHandle;
-}
-/*
- * @see IType#resolveType(String)
- */
-public String[][] resolveType(String typeName) {
- // not implemented for binary types
- return null;
-}
-/*
- * @see IType#resolveType(String, WorkingCopyOwner)
- */
-public String[][] resolveType(String typeName, WorkingCopyOwner owner) {
- // not implemented for binary types
- return null;
-}
-/*
- * Returns the source file name as defined in the given info.
- * If not present in the info, infers it from this type.
- */
-public String sourceFileName(IBinaryType info) {
- char[] sourceFileName = info.sourceFileName();
- if (sourceFileName == null) {
- /*
- * We assume that this type has been compiled from a file with its name
- * For example, A.class comes from A.js and p.A.class comes from a file A.js
- * in the folder p.
- */
- if (info.isMember()) {
- IType enclosingType = getDeclaringType();
- if (enclosingType == null) return null; // play it safe
- while (enclosingType.getDeclaringType() != null) {
- enclosingType = enclosingType.getDeclaringType();
- }
- return enclosingType.getElementName() + Util.defaultJavaExtension();
- } else if (info.isLocal() || info.isAnonymous()){
- String typeQualifiedName = getTypeQualifiedName();
- int dollar = typeQualifiedName.indexOf('$');
- if (dollar == -1) {
- // malformed inner type: name doesn't contain a dollar
- return getElementName() + Util.defaultJavaExtension();
- }
- return typeQualifiedName.substring(0, dollar) + Util.defaultJavaExtension();
- } else {
- return getElementName() + Util.defaultJavaExtension();
- }
- } else {
- return new String(sourceFileName);
- }
-}
-/*
- * @private Debugging purposes
- */
-protected void toStringInfo(int tab, StringBuffer buffer, Object info, boolean showResolvedInfo) {
- buffer.append(this.tabString(tab));
- if (info == null) {
- toStringName(buffer);
- buffer.append(" (not open)"); //$NON-NLS-1$
- } else if (info == NO_INFO) {
- toStringName(buffer);
- } else {
- buffer.append("class "); //$NON-NLS-1$
- toStringName(buffer);
- }
-}
-protected void toStringName(StringBuffer buffer) {
- if (getElementName().length() > 0)
- super.toStringName(buffer);
- else
- buffer.append("<anonymous>"); //$NON-NLS-1$
-}
-public String getAttachedJavadoc(IProgressMonitor monitor) throws JavaScriptModelException {
- final String contents = getJavadocContents(monitor);
- if (contents == null) return null;
- final int indexOfStartOfClassData = contents.indexOf(JavadocConstants.START_OF_CLASS_DATA);
- if (indexOfStartOfClassData == -1) throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.UNKNOWN_JSDOC_FORMAT, this));
- int indexOfNextSummary = contents.indexOf(JavadocConstants.NESTED_CLASS_SUMMARY);
-
- if (indexOfNextSummary == -1) {
- // try to find field summary start
- indexOfNextSummary = contents.indexOf(JavadocConstants.FIELD_SUMMARY);
- }
- if (indexOfNextSummary == -1) {
- // try to find constructor summary start
- indexOfNextSummary = contents.indexOf(JavadocConstants.CONSTRUCTOR_SUMMARY);
- }
- if (indexOfNextSummary == -1) {
- // try to find method summary start
- indexOfNextSummary = contents.indexOf(JavadocConstants.METHOD_SUMMARY);
- }
- if (indexOfNextSummary == -1) {
- // we take the end of class data
- indexOfNextSummary = contents.indexOf(JavadocConstants.END_OF_CLASS_DATA);
- }
- if (indexOfNextSummary == -1) {
- throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.UNKNOWN_JSDOC_FORMAT, this));
- }
- /*
- * Check out to cut off the hierarchy see 119844
- * We remove what the contents between the start of class data and the first <P>
- */
- int start = indexOfStartOfClassData + JavadocConstants.START_OF_CLASS_DATA_LENGTH;
- int indexOfFirstParagraph = contents.indexOf("<P>", start); //$NON-NLS-1$
- if (indexOfFirstParagraph == -1) {
- indexOfFirstParagraph = contents.indexOf("<p>", start); //$NON-NLS-1$
- }
- if (indexOfFirstParagraph != -1 && indexOfFirstParagraph < indexOfNextSummary) {
- start = indexOfFirstParagraph;
- }
- return contents.substring(start, indexOfNextSummary);
-}
-public String getJavadocContents(IProgressMonitor monitor) throws JavaScriptModelException {
- PerProjectInfo projectInfo = JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(this.getJavaScriptProject().getProject());
- String cachedJavadoc = null;
- synchronized (projectInfo.javadocCache) {
- cachedJavadoc = (String) projectInfo.javadocCache.get(this);
- }
- if (cachedJavadoc != null && cachedJavadoc != EMPTY_JAVADOC) {
- return cachedJavadoc;
- }
- URL baseLocation= getJavadocBaseLocation();
- if (baseLocation == null) {
- return null;
- }
- StringBuffer pathBuffer = new StringBuffer(baseLocation.toExternalForm());
-
- if (!(pathBuffer.charAt(pathBuffer.length() - 1) == '/')) {
- pathBuffer.append('/');
- }
- IPackageFragment pack= this.getPackageFragment();
- String typeQualifiedName = null;
- if (this.isMember()) {
- IType currentType = this;
- StringBuffer typeName = new StringBuffer();
- while (currentType != null) {
- typeName.insert(0, currentType.getElementName());
- currentType = currentType.getDeclaringType();
- if (currentType != null) {
- typeName.insert(0, '.');
- }
- }
- typeQualifiedName = new String(typeName.toString());
- } else {
- typeQualifiedName = this.getElementName();
- }
-
- pathBuffer.append(pack.getElementName().replace('.', '/')).append('/').append(typeQualifiedName).append(JavadocConstants.HTML_EXTENSION);
-
- if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException();
- final String contents = getURLContents(String.valueOf(pathBuffer));
- synchronized (projectInfo.javadocCache) {
- projectInfo.javadocCache.put(this, contents);
- }
- return contents;
-}
-}
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
deleted file mode 100644
index 1dd61321..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BinaryTypeConverter.java
+++ /dev/null
@@ -1,236 +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;
-
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IField;
-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.Signature;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.CompilationResult;
-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.ArrayQualifiedTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ArrayTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ConstructorDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ImportReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.SingleTypeReference;
-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.classfmt.ClassFileConstants;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ExtraCompilerModifiers;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * Converter from a binary type to an AST type declaration.
- */
-public class BinaryTypeConverter {
-
- /**
- * Convert a binary type into an AST type declaration and put it in the given compilation unit.
- */
- public static TypeDeclaration buildTypeDeclaration(IType type, CompilationUnitDeclaration compilationUnit, CompilationResult compilationResult) throws JavaScriptModelException {
- PackageFragment pkg = (PackageFragment) type.getPackageFragment();
- char[][] packageName = Util.toCharArrays(pkg.names);
-
- if (packageName.length > 0) {
- compilationUnit.currentPackage = new ImportReference(packageName, new long[]{0}, false);
- }
-
- /* convert type */
- TypeDeclaration typeDeclaration = convert(type, null, null, compilationResult);
-
- IType alreadyComputedMember = type;
- IType parent = type.getDeclaringType();
- TypeDeclaration previousDeclaration = typeDeclaration;
- while(parent != null) {
- TypeDeclaration declaration = convert(parent, alreadyComputedMember, previousDeclaration, compilationResult);
-
- alreadyComputedMember = parent;
- previousDeclaration = declaration;
- parent = parent.getDeclaringType();
- }
-
- compilationUnit.types = new TypeDeclaration[]{previousDeclaration};
-
- return typeDeclaration;
- }
-
- private static FieldDeclaration convert(IField field, IType type) throws JavaScriptModelException {
-
- FieldDeclaration fieldDeclaration = new FieldDeclaration();
-
- fieldDeclaration.name = field.getElementName().toCharArray();
- fieldDeclaration.type = createTypeReference(Signature.toString(field.getTypeSignature()).toCharArray());
- fieldDeclaration.modifiers = field.getFlags();
-
- return fieldDeclaration;
- }
-
- private static AbstractMethodDeclaration convert(IFunction method, IType type, CompilationResult compilationResult) throws JavaScriptModelException {
-
- AbstractMethodDeclaration methodDeclaration;
-
- if (method.isConstructor()) {
- ConstructorDeclaration decl = new ConstructorDeclaration(compilationResult);
- decl.isDefaultConstructor = false;
- methodDeclaration = decl;
- } else {
- MethodDeclaration decl = new MethodDeclaration(compilationResult);
- /* convert return type */
- decl.returnType = createTypeReference(Signature.toString(method.getReturnType()).toCharArray());
- methodDeclaration = decl;
- }
- methodDeclaration.selector = method.getElementName().toCharArray();
- int flags = method.getFlags();
- boolean isVarargs = Flags.isVarargs(flags);
- methodDeclaration.modifiers = flags & ~Flags.AccVarargs;
-
- /* convert arguments */
- String[] argumentTypeNames = method.getParameterTypes();
- String[] argumentNames = method.getParameterNames();
- int argumentCount = argumentTypeNames == null ? 0 : argumentTypeNames.length;
- methodDeclaration.arguments = new Argument[argumentCount];
- for (int i = 0; i < argumentCount; i++) {
- String argumentTypeName = argumentTypeNames[i];
- TypeReference typeReference = createTypeReference(Signature.toString(argumentTypeName).toCharArray());
- if (isVarargs && i == argumentCount-1) {
- typeReference.bits |= ASTNode.IsVarArgs;
- }
- methodDeclaration.arguments[i] = new Argument(
- argumentNames[i].toCharArray(),
- 0,
- typeReference,
- ClassFileConstants.AccDefault);
- // do not care whether was final or not
- }
-
- return methodDeclaration;
- }
-
- private static TypeDeclaration convert(IType type, IType alreadyComputedMember,TypeDeclaration alreadyComputedMemberDeclaration, CompilationResult compilationResult) throws JavaScriptModelException {
- /* create type declaration - can be member type */
- TypeDeclaration typeDeclaration = new TypeDeclaration(compilationResult);
-
- if (type.getDeclaringType() != null) {
- typeDeclaration.bits |= ASTNode.IsMemberType;
- }
- typeDeclaration.name = type.getElementName().toCharArray();
- typeDeclaration.modifiers = type.getFlags();
-
-
- /* set superclass and superinterfaces */
- if (type.getSuperclassName() != null) {
- typeDeclaration.superclass = createTypeReference(type.getSuperclassName().toCharArray());
- typeDeclaration.superclass.bits |= ASTNode.IsSuperType;
- }
-
- /* convert member types */
- IType[] memberTypes = type.getTypes();
- int memberTypeCount = memberTypes == null ? 0 : memberTypes.length;
- typeDeclaration.memberTypes = new TypeDeclaration[memberTypeCount];
- for (int i = 0; i < memberTypeCount; i++) {
- if(alreadyComputedMember != null && alreadyComputedMember.getFullyQualifiedName().equals(memberTypes[i].getFullyQualifiedName())) {
- typeDeclaration.memberTypes[i] = alreadyComputedMemberDeclaration;
- } else {
- typeDeclaration.memberTypes[i] = convert(memberTypes[i], null, null, compilationResult);
- }
- }
-
- /* convert fields */
- IField[] fields = type.getFields();
- int fieldCount = fields == null ? 0 : fields.length;
- typeDeclaration.fields = new FieldDeclaration[fieldCount];
- for (int i = 0; i < fieldCount; i++) {
- typeDeclaration.fields[i] = convert(fields[i], type);
- }
-
- /* convert methods - need to add default constructor if necessary */
- IFunction[] methods = type.getFunctions();
- int methodCount = methods == null ? 0 : methods.length;
-
- /* source type has a constructor ? */
- /* by default, we assume that one is needed. */
- int neededCount = 1;
- for (int i = 0; i < methodCount; i++) {
- if (methods[i].isConstructor()) {
- neededCount = 0;
- // Does not need the extra constructor since one constructor already exists.
- break;
- }
- }
-
- typeDeclaration.methods = new AbstractMethodDeclaration[methodCount + neededCount];
- if (neededCount != 0) { // add default constructor in first position
- typeDeclaration.methods[0] = typeDeclaration.createDefaultConstructor(false, false);
- }
- boolean hasAbstractMethods = false;
- for (int i = 0; i < methodCount; i++) {
- AbstractMethodDeclaration method =convert(methods[i], type, compilationResult);
- boolean isAbstract = method.isAbstract();
- if (isAbstract) { // fix-up flag
- method.modifiers |= ExtraCompilerModifiers.AccSemicolonBody;
- }
- if (isAbstract) {
- hasAbstractMethods = true;
- }
- typeDeclaration.methods[neededCount + i] = method;
- }
- if (hasAbstractMethods) {
- typeDeclaration.bits |= ASTNode.HasAbstractMethods;
- }
- return typeDeclaration;
- }
-
- private static TypeReference createTypeReference(char[] type) {
- /* count identifiers and dimensions */
- int max = type.length;
- int dimStart = max;
- int dim = 0;
- int identCount = 1;
- for (int i = 0; i < max; i++) {
- switch (type[i]) {
- case '[' :
- if (dim == 0)
- dimStart = i;
- dim++;
- break;
- case '.' :
- identCount++;
- break;
- }
- }
- /* rebuild identifiers and dimensions */
- if (identCount == 1) { // simple type reference
- if (dim == 0) {
- return new SingleTypeReference(type, 0);
- } else {
- char[] identifier = new char[dimStart];
- System.arraycopy(type, 0, identifier, 0, dimStart);
- return new ArrayTypeReference(identifier, dim, 0);
- }
- } else { // qualified type reference
- char[][] identifiers = CharOperation.splitOn('.', type, 0, dimStart);
- if (dim == 0) {
- return new QualifiedTypeReference(identifiers, new long[identifiers.length]);
- } else {
- return new ArrayQualifiedTypeReference(identifiers, dim, new long[identifiers.length]);
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/Buffer.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/Buffer.java
deleted file mode 100644
index e362390a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/Buffer.java
+++ /dev/null
@@ -1,475 +0,0 @@
-/*******************************************************************************
- * 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
- * Tim Hanson (thanson@bea.com) - patch for https://bugs.eclipse.org/bugs/show_bug.cgi?id=126673
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.util.ArrayList;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.ISafeRunnable;
-import org.eclipse.core.runtime.SafeRunner;
-import org.eclipse.core.runtime.content.IContentDescription;
-import org.eclipse.wst.jsdt.core.BufferChangedEvent;
-import org.eclipse.wst.jsdt.core.IBuffer;
-import org.eclipse.wst.jsdt.core.IBufferChangedListener;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatusConstants;
-import org.eclipse.wst.jsdt.core.IOpenable;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * @see IBuffer
- */
-public class Buffer implements IBuffer {
- protected IFile file;
- protected int flags;
- protected char[] contents;
- protected ArrayList changeListeners;
- protected IOpenable owner;
- protected int gapStart = -1;
- protected int gapEnd = -1;
-
- protected Object lock = new Object();
-
- protected static final int F_HAS_UNSAVED_CHANGES = 1;
- protected static final int F_IS_READ_ONLY = 2;
- protected static final int F_IS_CLOSED = 4;
-
-/**
- * Creates a new buffer on an underlying resource.
- */
-protected Buffer(IFile file, IOpenable owner, boolean readOnly) {
- this.file = file;
- this.owner = owner;
- if (file == null) {
- setReadOnly(readOnly);
- }
-}
-/**
- * @see IBuffer
- */
-public synchronized void addBufferChangedListener(IBufferChangedListener listener) {
- if (this.changeListeners == null) {
- this.changeListeners = new ArrayList(5);
- }
- if (!this.changeListeners.contains(listener)) {
- this.changeListeners.add(listener);
- }
-}
-/**
- * Append the <code>text</code> to the actual content, the gap is moved
- * to the end of the <code>text</code>.
- */
-public void append(char[] text) {
- if (!isReadOnly()) {
- if (text == null || text.length == 0) {
- return;
- }
- int length = getLength();
- synchronized(this.lock) {
- if (this.contents == null) return;
- moveAndResizeGap(length, text.length);
- System.arraycopy(text, 0, this.contents, length, text.length);
- this.gapStart += text.length;
- this.flags |= F_HAS_UNSAVED_CHANGES;
- }
- notifyChanged(new BufferChangedEvent(this, length, 0, new String(text)));
- }
-}
-/**
- * Append the <code>text</code> to the actual content, the gap is moved
- * to the end of the <code>text</code>.
- */
-public void append(String text) {
- if (text == null) {
- return;
- }
- this.append(text.toCharArray());
-}
-/**
- * @see IBuffer
- */
-public void close() {
- BufferChangedEvent event = null;
- synchronized (this.lock) {
- if (isClosed())
- return;
- event = new BufferChangedEvent(this, 0, 0, null);
- this.contents = null;
- this.flags |= F_IS_CLOSED;
- }
- notifyChanged(event); // notify outside of synchronized block
- synchronized(this) { // ensure that no other thread is adding/removing a listener at the same time (https://bugs.eclipse.org/bugs/show_bug.cgi?id=126673)
- this.changeListeners = null;
- }
-}
-/**
- * @see IBuffer
- */
-public char getChar(int position) {
- synchronized (this.lock) {
- if (this.contents == null) return Character.MIN_VALUE;
- if (position < this.gapStart) {
- return this.contents[position];
- }
- int gapLength = this.gapEnd - this.gapStart;
- return this.contents[position + gapLength];
- }
-}
-/**
- * @see IBuffer
- */
-public char[] getCharacters() {
- synchronized (this.lock) {
- if (this.contents == null) return null;
- if (this.gapStart < 0) {
- return this.contents;
- }
- int length = this.contents.length;
- char[] newContents = new char[length - this.gapEnd + this.gapStart];
- System.arraycopy(this.contents, 0, newContents, 0, this.gapStart);
- System.arraycopy(this.contents, this.gapEnd, newContents, this.gapStart, length - this.gapEnd);
- return newContents;
- }
-}
-/**
- * @see IBuffer
- */
-public String getContents() {
- char[] chars = this.getCharacters();
- if (chars == null) return null;
- return new String(chars);
-}
-/**
- * @see IBuffer
- */
-public int getLength() {
- synchronized (this.lock) {
- if (this.contents == null) return -1;
- int length = this.gapEnd - this.gapStart;
- return (this.contents.length - length);
- }
-}
-/**
- * @see IBuffer
- */
-public IOpenable getOwner() {
- return this.owner;
-}
-/**
- * @see IBuffer
- */
-public String getText(int offset, int length) {
- synchronized (this.lock) {
- if (this.contents == null) return ""; //$NON-NLS-1$
- if (offset + length < this.gapStart)
- return new String(this.contents, offset, length);
- if (this.gapStart < offset) {
- int gapLength = this.gapEnd - this.gapStart;
- return new String(this.contents, offset + gapLength, length);
- }
- StringBuffer buf = new StringBuffer();
- buf.append(this.contents, offset, this.gapStart - offset);
- buf.append(this.contents, this.gapEnd, offset + length - this.gapStart);
- return buf.toString();
- }
-}
-/**
- * @see IBuffer
- */
-public IResource getUnderlyingResource() {
- return this.file;
-}
-/**
- * @see IBuffer
- */
-public boolean hasUnsavedChanges() {
- return (this.flags & F_HAS_UNSAVED_CHANGES) != 0;
-}
-/**
- * @see IBuffer
- */
-public boolean isClosed() {
- return (this.flags & F_IS_CLOSED) != 0;
-}
-/**
- * @see IBuffer
- */
-public boolean isReadOnly() {
- return (this.flags & F_IS_READ_ONLY) != 0;
-}
-/**
- * Moves the gap to location and adjust its size to the
- * anticipated change size. The size represents the expected
- * range of the gap that will be filled after the gap has been moved.
- * Thus the gap is resized to actual size + the specified size and
- * moved to the given position.
- */
-protected void moveAndResizeGap(int position, int size) {
- char[] content = null;
- int oldSize = this.gapEnd - this.gapStart;
- if (size < 0) {
- if (oldSize > 0) {
- content = new char[this.contents.length - oldSize];
- System.arraycopy(this.contents, 0, content, 0, this.gapStart);
- System.arraycopy(this.contents, this.gapEnd, content, this.gapStart, content.length - this.gapStart);
- this.contents = content;
- }
- this.gapStart = this.gapEnd = position;
- return;
- }
- content = new char[this.contents.length + (size - oldSize)];
- int newGapStart = position;
- int newGapEnd = newGapStart + size;
- if (oldSize == 0) {
- System.arraycopy(this.contents, 0, content, 0, newGapStart);
- System.arraycopy(this.contents, newGapStart, content, newGapEnd, content.length - newGapEnd);
- } else
- if (newGapStart < this.gapStart) {
- int delta = this.gapStart - newGapStart;
- System.arraycopy(this.contents, 0, content, 0, newGapStart);
- System.arraycopy(this.contents, newGapStart, content, newGapEnd, delta);
- System.arraycopy(this.contents, this.gapEnd, content, newGapEnd + delta, this.contents.length - this.gapEnd);
- } else {
- int delta = newGapStart - this.gapStart;
- System.arraycopy(this.contents, 0, content, 0, this.gapStart);
- System.arraycopy(this.contents, this.gapEnd, content, this.gapStart, delta);
- System.arraycopy(this.contents, this.gapEnd + delta, content, newGapEnd, content.length - newGapEnd);
- }
- this.contents = content;
- this.gapStart = newGapStart;
- this.gapEnd = newGapEnd;
-}
-/**
- * Notify the listeners that this buffer has changed.
- * To avoid deadlock, this should not be called in a synchronized block.
- */
-protected void notifyChanged(final BufferChangedEvent event) {
- ArrayList listeners = this.changeListeners;
- if (listeners != null) {
- for (int i = 0, size = listeners.size(); i < size; ++i) {
- final IBufferChangedListener listener = (IBufferChangedListener) listeners.get(i);
- SafeRunner.run(new ISafeRunnable() {
- public void handleException(Throwable exception) {
- Util.log(exception, "Exception occurred in listener of buffer change notification"); //$NON-NLS-1$
- }
- public void run() throws Exception {
- listener.bufferChanged(event);
- }
- });
-
- }
- }
-}
-/**
- * @see IBuffer
- */
-public synchronized void removeBufferChangedListener(IBufferChangedListener listener) {
- if (this.changeListeners != null) {
- this.changeListeners.remove(listener);
- if (this.changeListeners.size() == 0) {
- this.changeListeners = null;
- }
- }
-}
-/**
- * Replaces <code>length</code> characters starting from <code>position</code> with <code>text<code>.
- * After that operation, the gap is placed at the end of the
- * inserted <code>text</code>.
- */
-public void replace(int position, int length, char[] text) {
- if (!isReadOnly()) {
- int textLength = text == null ? 0 : text.length;
- synchronized (this.lock) {
- if (this.contents == null) return;
-
- // move gap
- moveAndResizeGap(position + length, textLength - length);
-
- // overwrite
- int min = Math.min(textLength, length);
- if (min > 0) {
- System.arraycopy(text, 0, this.contents, position, min);
- }
- if (length > textLength) {
- // enlarge the gap
- this.gapStart -= length - textLength;
- } else if (textLength > length) {
- // shrink gap
- this.gapStart += textLength - length;
- System.arraycopy(text, 0, this.contents, position, textLength);
- }
- this.flags |= F_HAS_UNSAVED_CHANGES;
- }
- String string = null;
- if (textLength > 0) {
- string = new String(text);
- }
- notifyChanged(new BufferChangedEvent(this, position, length, string));
- }
-}
-/**
- * Replaces <code>length</code> characters starting from <code>position</code> with <code>text<code>.
- * After that operation, the gap is placed at the end of the
- * inserted <code>text</code>.
- */
-public void replace(int position, int length, String text) {
- this.replace(position, length, text == null ? null : text.toCharArray());
-}
-/**
- * @see IBuffer
- */
-public void save(IProgressMonitor progress, boolean force) throws JavaScriptModelException {
-
- // determine if saving is required
- if (isReadOnly() || this.file == null) {
- return;
- }
- if (!hasUnsavedChanges())
- return;
-
- // use a platform operation to update the resource contents
- try {
- String stringContents = this.getContents();
- if (stringContents == null) return;
-
- // Get encoding
- String encoding = null;
- try {
- encoding = this.file.getCharset();
- }
- catch (CoreException ce) {
- // use no encoding
- }
-
- // Create bytes array
- byte[] bytes = encoding == null
- ? stringContents.getBytes()
- : stringContents.getBytes(encoding);
-
- // Special case for UTF-8 BOM files
- // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=110576
- if (encoding != null && encoding.equals(org.eclipse.wst.jsdt.internal.compiler.util.Util.UTF_8)) {
- IContentDescription description = this.file.getContentDescription();
- if (description != null && description.getProperty(IContentDescription.BYTE_ORDER_MARK) != null) {
- int bomLength= IContentDescription.BOM_UTF_8.length;
- byte[] bytesWithBOM= new byte[bytes.length + bomLength];
- System.arraycopy(IContentDescription.BOM_UTF_8, 0, bytesWithBOM, 0, bomLength);
- System.arraycopy(bytes, 0, bytesWithBOM, bomLength, bytes.length);
- bytes= bytesWithBOM;
- }
- }
-
- // Set file contents
- ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
- if (this.file.exists()) {
- this.file.setContents(
- stream,
- force ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY,
- null);
- } else {
- this.file.create(stream, force, null);
- }
- } catch (IOException e) {
- throw new JavaScriptModelException(e, IJavaScriptModelStatusConstants.IO_EXCEPTION);
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- }
-
- // the resource no longer has unsaved changes
- this.flags &= ~ (F_HAS_UNSAVED_CHANGES);
-}
-/**
- * @see IBuffer
- */
-public void setContents(char[] newContents) {
- // allow special case for first initialization
- // after creation by buffer factory
- if (this.contents == null) {
- synchronized (this.lock) {
- this.contents = newContents;
- this.flags &= ~ (F_HAS_UNSAVED_CHANGES);
- }
- return;
- }
-
- if (!isReadOnly()) {
- String string = null;
- if (newContents != null) {
- string = new String(newContents);
- }
- synchronized (this.lock) {
- if (this.contents == null) return; // ignore if buffer is closed (as per spec)
- this.contents = newContents;
- this.flags |= F_HAS_UNSAVED_CHANGES;
- this.gapStart = -1;
- this.gapEnd = -1;
- }
- BufferChangedEvent event = new BufferChangedEvent(this, 0, this.getLength(), string);
- notifyChanged(event);
- }
-}
-/**
- * @see IBuffer
- */
-public void setContents(String newContents) {
- this.setContents(newContents.toCharArray());
-}
-/**
- * Sets this <code>Buffer</code> to be read only.
- */
-protected void setReadOnly(boolean readOnly) {
- if (readOnly) {
- this.flags |= F_IS_READ_ONLY;
- } else {
- this.flags &= ~(F_IS_READ_ONLY);
- }
-}
-public String toString() {
- StringBuffer buffer = new StringBuffer();
- buffer.append("Owner: " + ((JavaElement)this.owner).toStringWithAncestors()); //$NON-NLS-1$
- buffer.append("\nHas unsaved changes: " + this.hasUnsavedChanges()); //$NON-NLS-1$
- buffer.append("\nIs readonly: " + this.isReadOnly()); //$NON-NLS-1$
- buffer.append("\nIs closed: " + this.isClosed()); //$NON-NLS-1$
- buffer.append("\nContents:\n"); //$NON-NLS-1$
- char[] charContents = this.getCharacters();
- if (charContents == null) {
- buffer.append("<null>"); //$NON-NLS-1$
- } else {
- int length = charContents.length;
- for (int i = 0; i < length; i++) {
- char c = charContents[i];
- switch (c) {
- case '\n':
- buffer.append("\\n\n"); //$NON-NLS-1$
- break;
- case '\r':
- if (i < length-1 && this.contents[i+1] == '\n') {
- buffer.append("\\r\\n\n"); //$NON-NLS-1$
- i++;
- } else {
- buffer.append("\\r\n"); //$NON-NLS-1$
- }
- break;
- default:
- buffer.append(c);
- break;
- }
- }
- }
- return buffer.toString();
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BufferCache.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BufferCache.java
deleted file mode 100644
index b64224aa..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BufferCache.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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 org.eclipse.wst.jsdt.core.IBuffer;
-import org.eclipse.wst.jsdt.internal.core.util.LRUCache;
-
-/**
- * An LRU cache of <code>IBuffers</code>.
- */
-public class BufferCache extends OverflowingLRUCache {
-
- private ThreadLocal buffersToClose = new ThreadLocal();
-/**
- * Constructs a new buffer cache of the given size.
- */
-public BufferCache(int size) {
- super(size);
-}
-/**
- * Constructs a new buffer cache of the given size.
- */
-public BufferCache(int size, int overflow) {
- super(size, overflow);
-}
-/**
- * Returns true if the buffer is successfully closed and
- * removed from the cache, otherwise false.
- *
- * <p>NOTE: this triggers an external removal of this buffer
- * by closing the buffer.
- */
-protected boolean close(LRUCacheEntry entry) {
- IBuffer buffer= (IBuffer) entry._fValue;
-
- // prevent buffer that have unsaved changes or working copy buffer to be removed
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=39311
- if (!((Openable)buffer.getOwner()).canBufferBeRemovedFromCache(buffer)) {
- return false;
- } else {
- ArrayList buffers = (ArrayList) this.buffersToClose.get();
- if (buffers == null) {
- buffers = new ArrayList();
- this.buffersToClose.set(buffers);
- }
- buffers.add(buffer);
- return true;
- }
-}
-
-void closeBuffers() {
- ArrayList buffers = (ArrayList) this.buffersToClose.get();
- if (buffers == null)
- return;
- this.buffersToClose.set(null);
- for (int i = 0, length = buffers.size(); i < length; i++) {
- ((IBuffer) buffers.get(i)).close();
- }
-}
- /**
- * Returns a new instance of the reciever.
- */
- protected LRUCache newInstance(int size, int overflow) {
- return new BufferCache(size, overflow);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BufferFactoryWrapper.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BufferFactoryWrapper.java
deleted file mode 100644
index 53a376ac..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BufferFactoryWrapper.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*******************************************************************************
- * 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.core.IBuffer;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-
-/**
- * Wraps an IBufferFactory.
- * TODO remove when removing IBufferFactory
- * @deprecated
- */
-public class BufferFactoryWrapper extends WorkingCopyOwner {
-
- public org.eclipse.wst.jsdt.core.IBufferFactory factory;
-
- private BufferFactoryWrapper(org.eclipse.wst.jsdt.core.IBufferFactory factory) {
- this.factory = factory;
- }
-
- public static WorkingCopyOwner create(org.eclipse.wst.jsdt.core.IBufferFactory factory) {
- return new BufferFactoryWrapper(factory);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.WorkingCopyOwner#createBuffer(org.eclipse.wst.jsdt.core.IJavaScriptUnit)
- */
- public IBuffer createBuffer(IJavaScriptUnit workingCopy) {
- if (this.factory == null) return super.createBuffer(workingCopy);
- return this.factory.createBuffer(workingCopy);
- }
-
- public boolean equals(Object obj) {
- if (!(obj instanceof BufferFactoryWrapper)) return false;
- BufferFactoryWrapper other = (BufferFactoryWrapper)obj;
- if (this.factory == null) return other.factory == null;
- return this.factory.equals(other.factory);
- }
- public int hashCode() {
- if (this.factory == null) return 0;
- return this.factory.hashCode();
- }
- public String toString() {
- return "FactoryWrapper for " + this.factory; //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BufferManager.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BufferManager.java
deleted file mode 100644
index a0885c60..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BufferManager.java
+++ /dev/null
@@ -1,146 +0,0 @@
-/*******************************************************************************
- * 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 java.text.NumberFormat;
-import java.util.Enumeration;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.wst.jsdt.core.IBuffer;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IOpenable;
-
-/**
- * The buffer manager manages the set of open buffers.
- * It implements an LRU cache of buffers.
- */
-public class BufferManager {
-
- protected static BufferManager DEFAULT_BUFFER_MANAGER;
- protected static boolean VERBOSE;
-
- /**
- * LRU cache of buffers. The key and value for an entry
- * in the table is the identical buffer.
- */
- private BufferCache openBuffers = new BufferCache(60);
-
- /**
- * @deprecated
- */
- protected org.eclipse.wst.jsdt.core.IBufferFactory defaultBufferFactory = new org.eclipse.wst.jsdt.core.IBufferFactory() {
- /**
- * @deprecated
- */
- public IBuffer createBuffer(IOpenable owner) {
- return BufferManager.createBuffer(owner);
- }
- };
-
-/**
- * Adds a buffer to the table of open buffers.
- */
-protected void addBuffer(IBuffer buffer) {
- if (VERBOSE) {
- String owner = ((Openable)buffer.getOwner()).toStringWithAncestors();
- System.out.println("Adding buffer for " + owner); //$NON-NLS-1$
- }
- synchronized (this.openBuffers) {
- this.openBuffers.put(buffer.getOwner(), buffer);
- }
- // close buffers that were removed from the cache if space was needed
- this.openBuffers.closeBuffers();
- if (VERBOSE) {
- System.out.println("-> Buffer cache filling ratio = " + NumberFormat.getInstance().format(this.openBuffers.fillingRatio()) + "%"); //$NON-NLS-1$//$NON-NLS-2$
- }
-}
-public static IBuffer createBuffer(IOpenable owner) {
- IJavaScriptElement element = (IJavaScriptElement)owner;
- IResource resource = element.getResource();
- return
- new Buffer(
- resource instanceof IFile ? (IFile)resource : null,
- owner,
- element.isReadOnly());
-}
-public static IBuffer createNullBuffer(IOpenable owner) {
- IJavaScriptElement element = (IJavaScriptElement)owner;
- IResource resource = element.getResource();
- return
- new NullBuffer(
- resource instanceof IFile ? (IFile)resource : null,
- owner,
- element.isReadOnly());
-}
-/**
- * Returns the open buffer associated with the given owner,
- * or <code>null</code> if the owner does not have an open
- * buffer associated with it.
- */
-public IBuffer getBuffer(IOpenable owner) {
- synchronized (this.openBuffers) {
- return (IBuffer)this.openBuffers.get(owner);
- }
-}
-/**
- * Returns the default buffer manager.
- */
-public synchronized static BufferManager getDefaultBufferManager() {
- if (DEFAULT_BUFFER_MANAGER == null) {
- DEFAULT_BUFFER_MANAGER = new BufferManager();
- }
- return DEFAULT_BUFFER_MANAGER;
-}
-/**
- * Returns the default buffer factory.
- * @deprecated
- */
-public org.eclipse.wst.jsdt.core.IBufferFactory getDefaultBufferFactory() {
- return this.defaultBufferFactory;
-}
-/**
- * Returns an enumeration of all open buffers.
- * <p>
- * The <code>Enumeration</code> answered is thread safe.
- *
- * @see OverflowingLRUCache
- * @return Enumeration of IBuffer
- */
-public Enumeration getOpenBuffers() {
- Enumeration result;
- synchronized (this.openBuffers) {
- this.openBuffers.shrink();
- result = this.openBuffers.elements();
- }
- // close buffers that were removed from the cache if space was needed
- this.openBuffers.closeBuffers();
- return result;
-}
-
-/**
- * Removes a buffer from the table of open buffers.
- */
-protected void removeBuffer(IBuffer buffer) {
- if (VERBOSE) {
- String owner = ((Openable)buffer.getOwner()).toStringWithAncestors();
- System.out.println("Removing buffer for " + owner); //$NON-NLS-1$
- }
- synchronized (this.openBuffers) {
- this.openBuffers.remove(buffer.getOwner());
- }
- // close buffers that were removed from the cache (should be only one)
- this.openBuffers.closeBuffers();
- if (VERBOSE) {
- System.out.println("-> Buffer cache filling ratio = " + NumberFormat.getInstance().format(this.openBuffers.fillingRatio()) + "%"); //$NON-NLS-1$//$NON-NLS-2$
- }
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CancelableNameEnvironment.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CancelableNameEnvironment.java
deleted file mode 100644
index 797853f4..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CancelableNameEnvironment.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*******************************************************************************
- * 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
- * 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.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.internal.codeassist.ISearchRequestor;
-import org.eclipse.wst.jsdt.internal.compiler.env.NameEnvironmentAnswer;
-import org.eclipse.wst.jsdt.internal.compiler.impl.ITypeRequestor;
-import org.eclipse.wst.jsdt.internal.compiler.problem.AbortCompilation;
-import org.eclipse.wst.jsdt.internal.core.search.IRestrictedAccessBindingRequestor;
-
-
-public class CancelableNameEnvironment extends SearchableEnvironment {
- public IProgressMonitor monitor;
-
- public CancelableNameEnvironment(JavaProject project, WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaScriptModelException {
- super(project, owner);
- this.monitor = monitor;
- }
- public CancelableNameEnvironment(JavaProject project, IRestrictedAccessBindingRequestor scope, WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaScriptModelException {
- super(project,scope, owner);
- this.monitor = monitor;
- }
- private void checkCanceled() {
- if (this.monitor != null && this.monitor.isCanceled()) {
- if (NameLookup.VERBOSE)
- System.out.println(Thread.currentThread() + " CANCELLING LOOKUP "); //$NON-NLS-1$
- throw new AbortCompilation(true/*silent*/, new OperationCanceledException());
- }
- }
-
- public void findPackages(char[] prefix, ISearchRequestor requestor) {
- checkCanceled();
- super.findPackages(prefix, requestor);
- }
-
- public NameEnvironmentAnswer findType(char[] name, char[][] packageName, ITypeRequestor requestor) {
- checkCanceled();
- return super.findType(name, packageName, requestor);
- }
-
- public NameEnvironmentAnswer findBinding(char[] typeName, char[][] packageName, int type, ITypeRequestor requestor, boolean returnMultiple, String excludePath) {
- checkCanceled();
- return super.findBinding(typeName, packageName, type, requestor, returnMultiple, excludePath);
- }
-
- public NameEnvironmentAnswer findType(char[][] compoundTypeName, ITypeRequestor requestor) {
- checkCanceled();
- return super.findType(compoundTypeName,requestor);
- }
-
- public void findTypes(char[] prefix, boolean findMembers, boolean camelCaseMatch, int searchFor, ISearchRequestor storage) {
- checkCanceled();
- super.findTypes(prefix, findMembers, camelCaseMatch, searchFor, storage);
- }
-}
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
deleted file mode 100644
index a6b5086c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CancelableProblemFactory.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*******************************************************************************
- * 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
- * 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.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;
-
-
-public class CancelableProblemFactory extends DefaultProblemFactory {
- public IProgressMonitor monitor;
-
- public CancelableProblemFactory(IProgressMonitor monitor) {
- super();
- this.monitor = monitor;
- }
-
- public CategorizedProblem createProblem(char[] originatingFileName, int problemId, String[] problemArguments, String[] messageArguments, int severity, int startPosition, int endPosition, int lineNumber, int columnNumber) {
- 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/ChangeClasspathOperation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ChangeClasspathOperation.java
deleted file mode 100644
index 441f3513..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ChangeClasspathOperation.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*******************************************************************************
- * 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.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.jobs.ISchedulingRule;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-
-/*
- * Abstract class for operations that change the classpath
- */
-public abstract class ChangeClasspathOperation extends JavaModelOperation {
-
- protected boolean canChangeResources;
-
- public ChangeClasspathOperation(IJavaScriptElement[] elements, boolean canChangeResources) {
- super(elements);
- this.canChangeResources = canChangeResources;
- }
-
- protected boolean canModifyRoots() {
- // changing the classpath can modify roots
- return true;
- }
-
- /*
- * The resolved classpath of the given project may have changed:
- * - generate a delta
- * - trigger indexing
- * - update project references
- * - create resolved classpath markers
- */
- protected void classpathChanged(JavaProject project) throws JavaScriptModelException {
- DeltaProcessingState state = JavaModelManager.getJavaModelManager().deltaState;
- DeltaProcessor deltaProcessor = state.getDeltaProcessor();
- ClasspathChange change = (ClasspathChange) deltaProcessor.classpathChanges.get(project.getProject());
- if (this.canChangeResources) {
- // workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=177922
- if (isTopLevelOperation() && !ResourcesPlugin.getWorkspace().isTreeLocked()) {
- new ClasspathValidation(project).validate();
- }
-
- // delta, indexing and classpath markers are going to be created by the delta processor
- // while handling the .classpath file change
-
- // however ensure project references are updated
- // since some clients rely on the project references when run inside an IWorkspaceRunnable
- new ProjectReferenceChange(project, change.oldResolvedClasspath).updateProjectReferencesIfNecessary();
- } else {
- JavaElementDelta delta = new JavaElementDelta(getJavaModel());
- int result = change.generateDelta(delta);
- if ((result & ClasspathChange.HAS_DELTA) != 0) {
- // create delta
- addDelta(delta);
-
- // ensure indexes are updated
- change.requestIndexing();
-
- // ensure classpath is validated on next build
- state.addClasspathValidation(project);
- }
- if ((result & ClasspathChange.HAS_PROJECT_CHANGE) != 0) {
- // ensure project references are updated on next build
- state.addProjectReferenceChange(project, change.oldResolvedClasspath);
- }
- }
- }
-
- protected ISchedulingRule getSchedulingRule() {
- return null; // no lock taken while changing classpath
- }
-
- public boolean isReadOnly() {
- return !this.canChangeResources;
- }
-
-}
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
deleted file mode 100644
index 893657fe..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ClassFile.java
+++ /dev/null
@@ -1,909 +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;
-
-import java.io.File;
-import java.io.IOException;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.Map;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.wst.jsdt.core.CompletionRequestor;
-import org.eclipse.wst.jsdt.core.IBuffer;
-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.IJavaScriptElement;
-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.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IParent;
-import org.eclipse.wst.jsdt.core.IProblemRequestor;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeRoot;
-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.JsGlobalScopeContainerInitializer;
-import org.eclipse.wst.jsdt.core.LibrarySuperType;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.IProblemFactory;
-import org.eclipse.wst.jsdt.internal.compiler.SourceElementParser;
-import org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.env.IBinaryType;
-import org.eclipse.wst.jsdt.internal.compiler.impl.CompilerOptions;
-import org.eclipse.wst.jsdt.internal.compiler.problem.DefaultProblemFactory;
-import org.eclipse.wst.jsdt.internal.compiler.util.SuffixConstants;
-import org.eclipse.wst.jsdt.internal.core.util.MementoTokenizer;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * @see IClassFile
- */
-
-public class ClassFile extends Openable implements IClassFile, SuffixConstants, org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit, IVirtualParent {
-
- protected String name;
- protected IPath filePath;
- protected BinaryType binaryType = null;
- private static final IField[] NO_FIELDS = new IField[0];
- private static final IFunction[] NO_METHODS = new IFunction[0];
-
-/*
- * Creates a handle to a class file.
- */
-protected ClassFile(PackageFragment parent, String path) {
- super(parent);
- this.filePath = Path.fromOSString(path);
- if (filePath.getFileExtension()!=null)
- {
- String lastSegment = filePath.lastSegment();
- this.name=lastSegment.substring(0,lastSegment.length()-(filePath.getFileExtension().length()+1));
- }
- else
- this.name=path;
-}
-
-/*
- * @see IClassFile#becomeWorkingCopy(IProblemRequestor, WorkingCopyOwner, IProgressMonitor)
- */
-public IJavaScriptUnit becomeWorkingCopy(IProblemRequestor problemRequestor, WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaScriptModelException {
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- CompilationUnit workingCopy = new ClassFileWorkingCopy(this, owner == null ? DefaultWorkingCopyOwner.PRIMARY : owner);
- JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = manager.getPerWorkingCopyInfo(workingCopy, 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(workingCopy, problemRequestor);
- operation.runOperation(monitor);
-
- return workingCopy;
- }
- return perWorkingCopyInfo.workingCopy;
-}
-
-
-
-/**
- * Creates the children elements for this class file adding the resulting
- * new handles and info objects to the newElements table. Returns true
- * if successful, or false if an error is encountered parsing the class file.
- *
- * @see Openable
- * @see org.eclipse.wst.jsdt.core.Signature
- */
-protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaScriptModelException {
- // check whether the class file can be opened
- IStatus status = validateClassFile();
- if (!status.isOK()) throw newJavaModelException(status);
- if (underlyingResource != null && !underlyingResource.isAccessible()) {
- throw newNotPresentException();
- }
-
-
-
- CompilationUnitElementInfo unitInfo = new CompilationUnitElementInfo();
-
- // get buffer contents
-
- // generate structure and compute syntax problems if needed
- CompilationUnitStructureRequestor requestor = new CompilationUnitStructureRequestor(this, unitInfo, newElements);
- IJavaScriptProject project = getJavaScriptProject();
-
- boolean createAST;
- boolean resolveBindings;
- int reconcileFlags;
-// HashMap problems;
- if (info instanceof ASTHolderCUInfo) {
- ASTHolderCUInfo astHolder = (ASTHolderCUInfo) info;
- createAST = astHolder.astLevel != IJavaScriptUnit.NO_AST;
- resolveBindings = astHolder.resolveBindings;
- reconcileFlags = astHolder.reconcileFlags;
-// problems = astHolder.problems;
- } else {
- createAST = false;
- resolveBindings = false;
- reconcileFlags = 0;
-// problems = null;
- }
-
- boolean computeProblems = false;//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.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(
- this,
- 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;
- info.setChildren(unitInfo.children);
- try {
-
- if (createAST) {
-// int astLevel = ((ASTHolderCUInfo) info).astLevel;
-// org.eclipse.wst.jsdt.core.dom.JavaScriptUnit cu = AST.convertCompilationUnit(astLevel, unit, contents, options, computeProblems, this, pm);
-// ((ASTHolderCUInfo) info).ast = cu;
- throw new RuntimeException("Implement this"); //$NON-NLS-1$
- }
- } finally {
- if (unit != null) {
- unit.cleanUp();
- }
- }
-
-
-
-
-// IBinaryType typeInfo = getBinaryTypeInfo((IFile) underlyingResource);
-// if (typeInfo == null) {
-// // The structure of a class file is unknown if a class file format errors occurred
-// //during the creation of the diet class file representative of this ClassFile.
-// info.setChildren(new IJavaScriptElement[] {});
-// return false;
-// }
-//
-// // Make the type
-// IType type = getType();
-// info.setChildren(new IJavaScriptElement[] {type});
-// newElements.put(type, typeInfo);
-// // Read children
-// ((ClassFileInfo) info).readBinaryChildren(this, (HashMap) newElements, typeInfo);
- return true;
-}
-/* (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 owner) throws JavaScriptModelException {
- String source = getSource();
- if (source != null) {
- BinaryType type = (BinaryType) getType();
- BasicCompilationUnit cu =
- new BasicCompilationUnit(
- getSource().toCharArray(),
- null,
- type.sourceFileName((IBinaryType) type.getElementInfo()),
- getJavaScriptProject()); // use project to retrieve corresponding .js IFile
- codeComplete(cu, cu, offset, requestor, owner);
- }
-}
-
-/**
- * @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 owner) throws JavaScriptModelException {
- IBuffer buffer = getBuffer();
- char[] contents;
- if (buffer != null && (contents = buffer.getCharacters()) != null) {
- // BinaryType type = (BinaryType) getType();
-// BasicCompilationUnit cu = new BasicCompilationUnit(contents, null, type.sourceFileName((IBinaryType) type.getElementInfo()));
- PackageFragment packageFragment =(PackageFragment)getParent();
- String[] names = packageFragment.names;
- char [][] pkgNames=new char[names.length][];
- for (int i = 0; i < names.length; i++) {
- pkgNames[i]=names[i].toCharArray();
- }
- BasicCompilationUnit cu = new BasicCompilationUnit(contents, pkgNames, filePath.toOSString());
- return super.codeSelect(cu, offset, length, owner);
- } else {
- //has no associated souce
- return new IJavaScriptElement[] {};
- }
-}
-/**
- * Returns a new element info for this element.
- */
-protected Object createElementInfo() {
- return new ClassFileInfo();
-}
-public boolean equals(Object o) {
- if (!(o instanceof ClassFile)) return false;
- ClassFile other = (ClassFile) o;
- return this.name.equals(other.name) && this.parent.equals(other.parent);
-}
-public boolean exists() {
- return super.exists() && validateClassFile().isOK();
-}
-
-/**
- * Finds the deepest <code>IJavaScriptElement</code> in the hierarchy of
- * <code>elt</elt>'s children (including <code>elt</code> itself)
- * which has a source range that encloses <code>position</code>
- * according to <code>mapper</code>.
- */
-protected IJavaScriptElement findElement(IJavaScriptElement elt, int position, SourceMapper mapper) {
- SourceRange range = mapper.getSourceRange(elt);
- if (range == null || position < range.getOffset() || range.getOffset() + range.getLength() - 1 < position) {
- return null;
- }
- if (elt instanceof IParent) {
- try {
- IJavaScriptElement[] children = ((IParent) elt).getChildren();
- for (int i = 0; i < children.length; i++) {
- IJavaScriptElement match = findElement(children[i], position, mapper);
- if (match != null) {
- return match;
- }
- }
- } catch (JavaScriptModelException npe) {
- // elt doesn't exist: return the element
- }
- }
- return elt;
-}
-/**
- * @see ITypeRoot#findPrimaryType()
- */
-public IType findPrimaryType() {
- IType primaryType= getType();
- if (primaryType.exists()) {
- return primaryType;
- }
- return null;
-}
-public String getAttachedJavadoc(IProgressMonitor monitor) throws JavaScriptModelException {
- return this.getType().getAttachedJavadoc(monitor);
-}
-
-
-public byte[] getBytes() throws JavaScriptModelException {
- JavaElement pkg = (JavaElement) getParent();
-// if (pkg instanceof JarPackageFragment) {
-// JarPackageFragmentRoot root = (JarPackageFragmentRoot) pkg.getParent();
-// ZipFile zip = null;
-// try {
-// zip = root.getJar();
-// String entryName = Util.concatWith(((PackageFragment) pkg).names, getElementName(), '/');
-// ZipEntry ze = zip.getEntry(entryName);
-// if (ze != null) {
-// return org.eclipse.wst.jsdt.internal.compiler.util.Util.getZipEntryByteContent(ze, zip);
-// }
-// throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.ELEMENT_DOES_NOT_EXIST, this));
-// } catch (IOException ioe) {
-// throw new JavaScriptModelException(ioe, IJavaScriptModelStatusConstants.IO_EXCEPTION);
-// } catch (CoreException e) {
-// if (e instanceof JavaScriptModelException) {
-// throw (JavaScriptModelException)e;
-// } else {
-// throw new JavaScriptModelException(e);
-// }
-// } finally {
-// JavaModelManager.getJavaModelManager().closeZipFile(zip);
-// }
-// } else {
- IFile file = (IFile) getResource();
- return Util.getResourceContentsAsByteArray(file);
-// }
-}
-
-/**
- * @see org.eclipse.wst.jsdt.core.IMember
- */
-public IClassFile getClassFile() {
- return this;
-}
-/**
- * @see org.eclipse.wst.jsdt.core.IMember#getTypeRoot()
- */
-public ITypeRoot getTypeRoot() {
- return this;
-}
-/**
- * A class file has a corresponding resource unless it is contained
- * in a jar.
- *
- * @see IJavaScriptElement
- */
-public IResource getCorrespondingResource() throws JavaScriptModelException {
- IPackageFragmentRoot root= (IPackageFragmentRoot)getParent().getParent();
- if (root.isArchive()) {
- return null;
- } else {
- return getUnderlyingResource();
- }
-}
-/**
- * @see IClassFile
- */
-public IJavaScriptElement getElementAt(int position) throws JavaScriptModelException {
- IJavaScriptElement parentElement = getParent();
- while (parentElement.getElementType() != IJavaScriptElement.PACKAGE_FRAGMENT_ROOT) {
- parentElement = parentElement.getParent();
- }
- PackageFragmentRoot root = (PackageFragmentRoot) parentElement;
- SourceMapper mapper = root.getSourceMapper();
- if (mapper == null) {
- return null;
- } else {
- // ensure this class file's buffer is open so that source ranges are computed
- getBuffer();
-
-// IType type = getType();
- return findElement(this, position, mapper);
- }
-}
-public IJavaScriptElement getElementAtConsideringSibling(int position) throws JavaScriptModelException {
- IPackageFragment fragment = (IPackageFragment)getParent();
- PackageFragmentRoot root = (PackageFragmentRoot) fragment.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- SourceMapper mapper = root.getSourceMapper();
- if (mapper == null) {
- return null;
- } else {
- int index = this.name.indexOf('$');
- int prefixLength = index < 0 ? this.name.length() : index;
-
- IType type = null;
- int start = -1;
- int end = Integer.MAX_VALUE;
- IJavaScriptElement[] children = fragment.getChildren();
- for (int i = 0; i < children.length; i++) {
- String childName = children[i].getElementName();
-
- int childIndex = childName.indexOf('$');
- int childPrefixLength = childIndex < 0 ? childName.indexOf('.') : childIndex;
- if (prefixLength == childPrefixLength && this.name.regionMatches(0, childName, 0, prefixLength)) {
- IClassFile classFile = (IClassFile) children[i];
-
- // ensure this class file's buffer is open so that source ranges are computed
- classFile.getBuffer();
-
- SourceRange range = mapper.getSourceRange(classFile.getType());
- if (range == SourceMapper.UNKNOWN_RANGE) continue;
- int newStart = range.offset;
- int newEnd = newStart + range.length - 1;
- if(newStart > start && newEnd < end
- && newStart <= position && newEnd >= position) {
- type = classFile.getType();
- start = newStart;
- end = newEnd;
- }
- }
- }
- if(type != null) {
- return findElement(type, position, mapper);
- }
- return null;
- }
-}
-public String getElementName() {
- /* check if the name already has the .js extension */
- if(this.name!=null && this.name.toUpperCase().endsWith(SuffixConstants.SUFFIX_STRING_java.toUpperCase())){
- return this.name;
- }
-
- return this.name + SuffixConstants.SUFFIX_STRING_java;
-}
-/**
- * @see IJavaScriptElement
- */
-public int getElementType() {
- return CLASS_FILE;
-}
-/*
- * @see JavaElement
- */
-public IJavaScriptElement getHandleFromMemento(String token, MementoTokenizer memento, WorkingCopyOwner owner) {
- switch (token.charAt(0)) {
- case JEM_TYPE:
- if (!memento.hasMoreTokens()) return this;
- String typeName = memento.nextToken();
- JavaElement type = new BinaryType(this, typeName);
- return type.getHandleFromMemento(memento, owner);
- }
- return null;
-}
-/**
- * @see JavaElement#getHandleMemento()
- */
-protected char getHandleMementoDelimiter() {
- return JavaElement.JEM_CLASSFILE;
-}
-
-protected void getHandleMemento(StringBuffer buff) {
-
- PackageFragmentRoot root = getPackageFragmentRoot();
- try {
- if (root.isArchive() ||
- (( root instanceof LibraryFragmentRoot || (getParent() instanceof PackageFragment && ((PackageFragment)getParent()).getKind()==IPackageFragmentRoot.K_BINARY))
- && root.getPath().lastSegment().equalsIgnoreCase(getElementName()))
- ) {
-
- ((JavaElement)getParent()).getHandleMemento(buff);
- buff.append(getHandleMementoDelimiter());
- escapeMementoName(buff, getPath().toPortableString());
- }
- else
- super.getHandleMemento(buff);
- } catch (JavaScriptModelException e) {
- e.printStackTrace();
- }
-}
-/*
- * @see IJavaScriptElement
- */
-
-protected boolean resourceExists() {
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- if (workspace == null) return false; // workaround for http://bugs.eclipse.org/bugs/show_bug.cgi?id=34069
- Object me = JavaModel.getTarget(workspace.getRoot(), this.getPath(), true) ;
- if(me!=null) return true;
- me = JavaModel.getTarget(workspace.getRoot(), this.getPath().makeRelative(), true);
- return (me!=null);
-
-}
-public IPath getPath() {
- PackageFragmentRoot root = getPackageFragmentRoot();
- if (root.isArchive() || (root instanceof LibraryFragmentRoot && root.getPath().lastSegment().equalsIgnoreCase(getElementName()))) {
- return root.getPath();
- } else {
- return getParent().getPath().append(getElementName());
- }
-}
-/*
- * @see IJavaScriptElement
- */
-public IResource getResource() {
- PackageFragmentRoot root = this.getPackageFragmentRoot();
- if (!root.isResourceContainer()) {
- return root.getResource();
- } else {
- return ((IContainer)this.getParent().getResource()).getFile(new Path(this.getElementName()));
- }
-}
-/**
- * @see org.eclipse.wst.jsdt.core.ISourceReference
- */
-public String getSource() throws JavaScriptModelException {
- IBuffer buffer = getBuffer();
- if (buffer == null) {
- return null;
- }
- return buffer.getContents();
-}
-
-
-public void makeConsistent(IProgressMonitor monitor) throws JavaScriptModelException {
- openBuffer(monitor, createElementInfo()); // open buffer independently from the info, since we are building the info
-}
-/**
- * @see org.eclipse.wst.jsdt.core.ISourceReference
- */
-public ISourceRange getSourceRange() throws JavaScriptModelException {
- IBuffer buffer = getBuffer();
- if (buffer != null) {
- String contents = buffer.getContents();
- if (contents == null) return null;
- return new SourceRange(0, contents.length());
- } else {
- return null;
- }
-}
-/*
- * Returns the name of the toplevel type of this class file.
- */
-public String getTopLevelTypeName() {
- String topLevelTypeName = getElementName();
- int firstDollar = topLevelTypeName.indexOf('$');
- if (firstDollar != -1) {
- topLevelTypeName = topLevelTypeName.substring(0, firstDollar);
- } else {
- topLevelTypeName = topLevelTypeName.substring(0, topLevelTypeName.length()-SUFFIX_JAVA.length);
- }
- return topLevelTypeName;
-}
-/**
- * @see IClassFile
- */
-public IType getType() {
- if (this.binaryType == null) {
- this.binaryType = new BinaryType(this, getTypeName());
- }
- return this.binaryType;
-}
-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;
-}
-/*
- * @see IClassFile
- */
-public IJavaScriptUnit getWorkingCopy(WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaScriptModelException {
- CompilationUnit workingCopy = new ClassFileWorkingCopy(this, owner == null ? DefaultWorkingCopyOwner.PRIMARY : owner);
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- 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, null);
- op.runOperation(monitor);
- return workingCopy;
-}
-/**
- * @see Openable
- */
-protected boolean hasBuffer() {
- return true;
-}
-public int hashCode() {
- return Util.combineHashCodes(this.name.hashCode(), this.parent.hashCode());
-}
-/**
- * @see IClassFile
- */
-public boolean isClass() throws JavaScriptModelException {
- return getType().isClass();
-}
-/**
- * Returns true - class files are always read only.
- */
-public boolean isReadOnly() {
- return true;
-}
-private IStatus validateClassFile() {
- IPackageFragmentRoot root = getPackageFragmentRoot();
- try {
- if (root.getKind() != IPackageFragmentRoot.K_BINARY)
- {
- if (((PackageFragment)this.getParent()).getKind()!= IPackageFragmentRoot.K_BINARY)
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_ELEMENT_TYPES, root);
-
- }
- } catch (JavaScriptModelException e) {
- return e.getJavaScriptModelStatus();
- }
- IJavaScriptProject project = getJavaScriptProject();
- return JavaScriptConventions.validateClassFileName(getElementName(), project.getOption(JavaScriptCore.COMPILER_SOURCE, true), project.getOption(JavaScriptCore.COMPILER_COMPLIANCE, true));
-}
-/**
- * Opens and returns buffer on the source code associated with this class file.
- * Maps the source code to the children elements of this class file.
- * If no source code is associated with this class file,
- * <code>null</code> is returned.
- *
- * @see Openable
- */
-protected IBuffer openBuffer(IProgressMonitor pm, Object info) throws JavaScriptModelException {
- SourceMapper mapper = getSourceMapper();
- if (mapper != null) {
- return mapSource(mapper, info instanceof IBinaryType ? (IBinaryType) info : null);
- }
- return null;
-}
-private IBuffer mapSource(SourceMapper mapper, IBinaryType info) {
- char[] contents =null;
-
-
- String fileEncoding = null;
- try {
- IResource resource =(this.getResource());
- fileEncoding = (resource!=null&&resource instanceof IFile)?((IFile)resource).getCharset():null;
- } catch (CoreException e) {
- // resource not in workspace, use default encoding.
- }
- try {
- contents=org.eclipse.wst.jsdt.internal.compiler.util.Util.getFileCharContent(new File(filePath.toOSString()),fileEncoding);
- } catch (IOException ex){}
- //mapper.findSource(getType(), info);
- if (contents != null) {
- // create buffer
- IBuffer buffer = BufferManager.createBuffer(this);
- if (buffer == null) return null;
- BufferManager bufManager = getBufferManager();
- bufManager.addBuffer(buffer);
-
- // set the buffer source
- if (buffer.getCharacters() == null){
- buffer.setContents(contents);
- }
-
- // listen to buffer changes
- buffer.addBufferChangedListener(this);
-
- // do the source mapping
-// mapper.mapSource(getType(), contents, info);
-
- return buffer;
- } else {
- // create buffer
- IBuffer buffer = BufferManager.createNullBuffer(this);
- if (buffer == null) return null;
- BufferManager bufManager = getBufferManager();
- bufManager.addBuffer(buffer);
-
- // listen to buffer changes
- buffer.addBufferChangedListener(this);
- return buffer;
- }
-}
-/* package */ static String simpleName(char[] className) {
- 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;
-}
-/**
- * Returns the Java Model representation of the given name
- * which is provided in diet class file format, or <code>null</code>
- * if the given name is <code>null</code>.
- *
- * <p><code>ClassFileReader</code> format is similar to "java/lang/Object",
- * and corresponding Java Model format is "java.lang.Object".
- */
-
-public static char[] translatedName(char[] name) {
- if (name == null)
- return null;
- int nameLength = name.length;
- char[] newName= new char[nameLength];
- for (int i= 0; i < nameLength; i++) {
- if (name[i] == '/') {
- newName[i]= '.';
- } else {
- newName[i]= name[i];
- }
- }
- return newName;
-}
-/**
- * Returns the Java Model representation of the given names
- * which are provided in diet class file format, or <code>null</code>
- * if the given names are <code>null</code>.
- *
- * <p><code>ClassFileReader</code> format is similar to "java/lang/Object",
- * and corresponding Java Model format is "java.lang.Object".
- */
-
-/* package */ static char[][] translatedNames(char[][] names) {
- if (names == null)
- return null;
- int length = names.length;
- char[][] newNames = new char[length][];
- for(int i = 0; i < length; i++) {
- newNames[i] = translatedName(names[i]);
- }
- return newNames;
-}
-/**
- * Returns the Java Model format of the unqualified class name for the
- * given className which is provided in diet class file format,
- * or <code>null</code> if the given className is <code>null</code>.
- * (This removes the package name, but not enclosing type names).
- *
- * <p><code>ClassFileReader</code> format is similar to "java/lang/Object",
- * and corresponding Java Model simple name format is "Object".
- */
-
-/* package */ static char[] unqualifiedName(char[] className) {
- if (className == null)
- return null;
- int count = 0;
- for (int i = className.length - 1; i > -1; i--) {
- if (className[i] == '/') {
- char[] name = new char[count];
- System.arraycopy(className, i + 1, name, 0, count);
- return name;
- }
- count++;
- }
- return className;
-}
-
-/*
- * @see IType#getField(String name)
- */
-public IField getField(String fieldName) {
- return new SourceField(this, fieldName);
-
-}
-/*
- * @see IType#getFields()
- */
-public IField[] getFields() throws JavaScriptModelException {
- ArrayList list = getChildrenOfType(FIELD);
- int size;
- if ((size = list.size()) == 0) {
- return NO_FIELDS;
- } else {
- IField[] array= new IField[size];
- list.toArray(array);
- return array;
- }
-}
-public IFunction getFunction(String selector, String[] parameterTypeSignatures) {
- return new SourceMethod(this, selector, parameterTypeSignatures);
-}
-
-public IType getType(String typeName) {
- return new SourceType(this, typeName);
-}
-
-/*
- * @see IType#getMethods()
- */
-/**
- * @deprecated Use {@link #getFunctions()} instead
- */
-public IFunction[] getMethods() throws JavaScriptModelException {
- return getFunctions();
-}
-
-/*
- * @see IType#getMethods()
- */
-public IFunction[] getFunctions() throws JavaScriptModelException {
- ArrayList list = getChildrenOfType(METHOD);
- int size;
- if ((size = list.size()) == 0) {
- return NO_METHODS;
- } else {
- IFunction[] array= new IFunction[size];
- list.toArray(array);
- return array;
- }
-}
-
-public IType[] getTypes() throws JavaScriptModelException {
- ArrayList list = getChildrenOfType(TYPE);
- IType[] array= new IType[list.size()];
- list.toArray(array);
- return array;
-}
-
- public char[] getContents() {
- String fileEncoding = null;
- try {
- IResource resource =(this.getResource());
- fileEncoding = (resource!=null&&resource instanceof IFile)?((IFile)resource).getCharset():null;
- } catch (CoreException e) {
- // resource not in workspace, use default encoding.
- }
- char [] chars=null;
- try {
- chars=org.eclipse.wst.jsdt.internal.compiler.util.Util.getFileCharContent(new File(filePath.toOSString()),fileEncoding);
- } catch (IOException e) {
- e.printStackTrace();
- }
- return chars;
- }
- public char[] getMainTypeName() {
- return name.toCharArray();
- }
- public char[][] getPackageName() {
-// return new char[][] {getParent().getElementName().toCharArray()};
- PackageFragment packageFragment = (PackageFragment) getParent();
- if (packageFragment == null) return CharOperation.NO_CHAR_CHAR;
- return Util.toCharArrays(packageFragment.names);
- }
- public char[] getFileName() {
- //return getElementName().toCharArray();
- return this.filePath!=null?this.filePath.toString().toCharArray():getElementName().toCharArray();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.core.JavaElement#getDisplayName()
- */
- 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 LibrarySuperType getCommonSuperType() {
- return null;
- //return getJavaProject().getCommonSuperType();
- }
- public JsGlobalScopeContainerInitializer getContainerInitializer() {
- JsGlobalScopeContainerInitializer init = ((IVirtualParent)parent).getContainerInitializer();
- return init;
- }
-
- 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;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ClassFileInfo.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ClassFileInfo.java
deleted file mode 100644
index 9c438478..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ClassFileInfo.java
+++ /dev/null
@@ -1,171 +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;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-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.internal.compiler.env.IBinaryField;
-import org.eclipse.wst.jsdt.internal.compiler.env.IBinaryMethod;
-import org.eclipse.wst.jsdt.internal.compiler.env.IBinaryNestedType;
-import org.eclipse.wst.jsdt.internal.compiler.env.IBinaryType;
-import org.eclipse.wst.jsdt.internal.compiler.util.SuffixConstants;
-
-/**
- * Element info for <code>ClassFile</code> handles.
- */
-
-/* package */ class ClassFileInfo extends OpenableElementInfo implements SuffixConstants {
- /**
- * The children of the <code>BinaryType</code> corresponding to our
- * <code>ClassFile</code>. These are kept here because we don't have
- * access to the <code>BinaryType</code> info (<code>ClassFileReader</code>).
- */
- protected JavaElement[] binaryChildren = null;
-
-/**
- * Creates the handles and infos for the fields of the given binary type.
- * Adds new handles to the given vector.
- */
-private void generateFieldInfos(IType type, IBinaryType typeInfo, HashMap newElements, ArrayList childrenHandles) {
- // Make the fields
- IBinaryField[] fields = typeInfo.getFields();
- if (fields == null) {
- return;
- }
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- for (int i = 0, fieldCount = fields.length; i < fieldCount; i++) {
- IBinaryField fieldInfo = fields[i];
- IField field = new BinaryField((JavaElement)type, manager.intern(new String(fieldInfo.getName())));
- newElements.put(field, fieldInfo);
- childrenHandles.add(field);
- }
-}
-/**
- * Creates the handles for the inner types of the given binary type.
- * Adds new handles to the given vector.
- */
-private void generateInnerClassHandles(IType type, IBinaryType typeInfo, ArrayList childrenHandles) {
- // Add inner types
- // If the current type is an inner type, innerClasses returns
- // an extra entry for the current type. This entry must be removed.
- // Can also return an entry for the enclosing type of an inner type.
- IBinaryNestedType[] innerTypes = typeInfo.getMemberTypes();
- if (innerTypes != null) {
- IPackageFragment pkg = (IPackageFragment) type.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT);
- for (int i = 0, typeCount = innerTypes.length; i < typeCount; i++) {
- IBinaryNestedType binaryType = innerTypes[i];
- IClassFile parentClassFile= pkg.getClassFile(new String(ClassFile.unqualifiedName(binaryType.getName())) + SUFFIX_STRING_java);
- IType innerType = new BinaryType((JavaElement) parentClassFile, ClassFile.simpleName(binaryType.getName()));
- childrenHandles.add(innerType);
- }
- }
-}
-/**
- * Creates the handles and infos for the methods of the given binary type.
- * Adds new handles to the given vector.
- */
-private void generateMethodInfos(IType type, IBinaryType typeInfo, HashMap newElements, ArrayList childrenHandles, ArrayList typeParameterHandles) {
- IBinaryMethod[] methods = typeInfo.getMethods();
- if (methods == null) {
- return;
- }
- for (int i = 0, methodCount = methods.length; i < methodCount; i++) {
- IBinaryMethod methodInfo = methods[i];
- // TODO (jerome) filter out synthetic members
- // indexer should not index them as well
- // if ((methodInfo.getModifiers() & IConstants.AccSynthetic) != 0) continue; // skip synthetic
- char[] signature = methodInfo.getGenericSignature();
- if (signature == null) signature = methodInfo.getMethodDescriptor();
- String[] pNames = null;
- try {
- pNames = Signature.getParameterTypes(new String(signature));
- } catch (IllegalArgumentException e) {
- // protect against malformed .class file (e.g. com/sun/crypto/provider/SunJCE_b.class has a 'a' generic signature)
- signature = methodInfo.getMethodDescriptor();
- pNames = Signature.getParameterTypes(new String(signature));
- }
- char[][] paramNames= new char[pNames.length][];
- for (int j= 0; j < pNames.length; j++) {
- paramNames[j]= pNames[j].toCharArray();
- }
- char[][] parameterTypes = ClassFile.translatedNames(paramNames);
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- String selector = new String(methodInfo.getSelector());
- if (methodInfo.isConstructor()) {
- selector =type.getElementName();
- }
- selector = manager.intern(selector);
- for (int j= 0; j < pNames.length; j++) {
- pNames[j]= manager.intern(new String(parameterTypes[j]));
- }
- BinaryMethod method = new BinaryMethod((JavaElement)type, selector, pNames);
- childrenHandles.add(method);
-
- // ensure that 2 binary methods with the same signature but with different return types have different occurence counts.
- // (case of bridge methods in 1.5)
- while (newElements.containsKey(method))
- method.occurrenceCount++;
-
- newElements.put(method, methodInfo);
- }
-}
-/**
- * Returns true iff the <code>readBinaryChildren</code> has already
- * been called.
- */
-boolean hasReadBinaryChildren() {
- return this.binaryChildren != null;
-}
-/**
- * Creates the handles for <code>BinaryMember</code>s defined in this
- * <code>ClassFile</code> and adds them to the
- * <code>JavaModelManager</code>'s cache.
- */
-protected void readBinaryChildren(ClassFile classFile, HashMap newElements, IBinaryType typeInfo) {
- ArrayList childrenHandles = new ArrayList();
- BinaryType type = (BinaryType) classFile.getType();
- ArrayList typeParameterHandles = new ArrayList();
- if (typeInfo != null) { //may not be a valid class file
- generateFieldInfos(type, typeInfo, newElements, childrenHandles);
- generateMethodInfos(type, typeInfo, newElements, childrenHandles, typeParameterHandles);
- generateInnerClassHandles(type, typeInfo, childrenHandles); // Note inner class are separate openables that are not opened here: no need to pass in newElements
- }
-
- this.binaryChildren = new JavaElement[childrenHandles.size()];
- childrenHandles.toArray(this.binaryChildren);
-}
-/**
- * Removes the binary children handles and remove their infos from
- * the <code>JavaModelManager</code>'s cache.
- */
-void removeBinaryChildren() throws JavaScriptModelException {
- if (this.binaryChildren != null) {
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- for (int i = 0; i <this.binaryChildren.length; i++) {
- JavaElement child = this.binaryChildren[i];
- if (child instanceof BinaryType) {
- manager.removeInfoAndChildren((JavaElement)child.getParent());
- } else {
- manager.removeInfoAndChildren(child);
- }
- }
- this.binaryChildren = JavaElement.NO_ELEMENTS;
- }
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ClassFileWorkingCopy.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ClassFileWorkingCopy.java
deleted file mode 100644
index 0fa263c8..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ClassFileWorkingCopy.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*******************************************************************************
- * 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.core.resources.IResource;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.wst.jsdt.core.IBuffer;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatusConstants;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-
-/**
- * A working copy on an <code>IClassFile</code>.
- */
-public class ClassFileWorkingCopy extends CompilationUnit {
-
- public IClassFile classFile;
-
-public ClassFileWorkingCopy(IClassFile classFile, WorkingCopyOwner owner) {
- super((PackageFragment) classFile.getParent(), ((BinaryType) ((ClassFile) classFile).getType()).getSourceFileName(null/*no info available*/), owner);
- this.classFile = classFile;
-}
-
-public void commitWorkingCopy(boolean force, IProgressMonitor monitor) throws JavaScriptModelException {
- throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_ELEMENT_TYPES, this));
-}
-
-public IBuffer getBuffer() throws JavaScriptModelException {
- if (isWorkingCopy())
- return super.getBuffer();
- else
- return this.classFile.getBuffer();
-}
-
-public char[] getContents() {
- try {
- IBuffer buffer = getBuffer();
- if (buffer == null) return CharOperation.NO_CHAR;
- char[] characters = buffer.getCharacters();
- if (characters == null) return CharOperation.NO_CHAR;
- return characters;
- } catch (JavaScriptModelException e) {
- return CharOperation.NO_CHAR;
- }
-}
-
-public IPath getPath() {
- return this.classFile.getPath();
-}
-
-public IJavaScriptElement getPrimaryElement(boolean checkOwner) {
- if (checkOwner && isPrimary()) return this;
- return new ClassFileWorkingCopy(this.classFile, DefaultWorkingCopyOwner.PRIMARY);
-}
-
-public IResource getResource() {
- return this.classFile.getResource();
-}
-
-
-
-protected void toStringName(StringBuffer buffer) {
- buffer.append(this.classFile.getElementName());
-}
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ClasspathAccessRule.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ClasspathAccessRule.java
deleted file mode 100644
index 206d36fc..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ClasspathAccessRule.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.wst.jsdt.core.IAccessRule;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.internal.compiler.env.AccessRule;
-
-public class ClasspathAccessRule extends AccessRule implements IAccessRule {
-
- public ClasspathAccessRule(IPath pattern, int kind) {
- this(pattern.toString().toCharArray(), toProblemId(kind));
- }
-
- public ClasspathAccessRule(char[] pattern, int problemId) {
- super(pattern, problemId);
- }
-
- private static int toProblemId(int kind) {
- boolean ignoreIfBetter = (kind & IAccessRule.IGNORE_IF_BETTER) != 0;
- switch (kind & ~IAccessRule.IGNORE_IF_BETTER) {
- case K_NON_ACCESSIBLE:
- return ignoreIfBetter ? IProblem.ForbiddenReference | AccessRule.IgnoreIfBetter : IProblem.ForbiddenReference;
- case K_DISCOURAGED:
- return ignoreIfBetter ? IProblem.DiscouragedReference | AccessRule.IgnoreIfBetter : IProblem.DiscouragedReference;
- default:
- return ignoreIfBetter ? AccessRule.IgnoreIfBetter : 0;
- }
- }
-
- public IPath getPattern() {
- return new Path(new String(this.pattern));
- }
-
- public int getKind() {
- switch (getProblemId()) {
- case IProblem.ForbiddenReference:
- return K_NON_ACCESSIBLE;
- case IProblem.DiscouragedReference:
- return K_DISCOURAGED;
- default:
- return K_ACCESSIBLE;
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ClasspathAttribute.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ClasspathAttribute.java
deleted file mode 100644
index 5f570557..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ClasspathAttribute.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*******************************************************************************
- * 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
- * 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.core.IIncludePathAttribute;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-public class ClasspathAttribute implements IIncludePathAttribute {
-
- private String name;
- private String value;
-
- public ClasspathAttribute(String name, String value) {
- this.name = name;
- this.value = value;
- }
-
- public boolean equals(Object obj) {
- if (!(obj instanceof ClasspathAttribute)) return false;
- ClasspathAttribute other = (ClasspathAttribute) obj;
- return this.name.equals(other.name) && this.value.equals(other.value);
- }
-
- public String getName() {
- return this.name!=null?this.name:""; //$NON-NLS-1$
- }
-
- public String getValue() {
- return this.value!=null?this.value:""; //$NON-NLS-1$
- }
-
- public int hashCode() {
- return Util.combineHashCodes(this.name.hashCode(), this.value.hashCode());
- }
-
- public String toString() {
- return this.name + "=" + this.value; //$NON-NLS-1$
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ClasspathChange.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ClasspathChange.java
deleted file mode 100644
index 3ba98ed2..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ClasspathChange.java
+++ /dev/null
@@ -1,491 +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;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptElementDelta;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.compiler.util.ObjectVector;
-import org.eclipse.wst.jsdt.internal.core.JavaModelManager.PerProjectInfo;
-import org.eclipse.wst.jsdt.internal.core.search.indexing.IndexManager;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-public class ClasspathChange {
- public static int NO_DELTA = 0x00;
- public static int HAS_DELTA = 0x01;
- public static int HAS_PROJECT_CHANGE = 0x10;
-
- JavaProject project;
- IIncludePathEntry[] oldRawClasspath;
- IPath oldOutputLocation;
- IIncludePathEntry[] oldResolvedClasspath;
-
- public ClasspathChange(JavaProject project, IIncludePathEntry[] oldRawClasspath, IPath oldOutputLocation, IIncludePathEntry[] oldResolvedClasspath) {
- this.project = project;
- this.oldRawClasspath = oldRawClasspath;
- this.oldOutputLocation = oldOutputLocation;
- this.oldResolvedClasspath = oldResolvedClasspath;
- }
-
- private void addClasspathDeltas(JavaElementDelta delta, IPackageFragmentRoot[] roots, int flag) {
- for (int i = 0; i < roots.length; i++) {
- IPackageFragmentRoot root = roots[i];
- delta.changed(root, flag);
- if ((flag & IJavaScriptElementDelta.F_REMOVED_FROM_CLASSPATH) != 0
- || (flag & IJavaScriptElementDelta.F_SOURCEATTACHED) != 0
- || (flag & IJavaScriptElementDelta.F_SOURCEDETACHED) != 0){
- try {
- root.close();
- } catch (JavaScriptModelException e) {
- // ignore
- }
- }
- }
- }
-
- /*
- * Returns the index of the item in the list if the given list contains the specified entry. If the list does
- * not contain the entry, -1 is returned.
- */
- private int classpathContains(IIncludePathEntry[] list, IIncludePathEntry entry) {
- IPath[] exclusionPatterns = entry.getExclusionPatterns();
- IPath[] inclusionPatterns = entry.getInclusionPatterns();
- nextEntry: for (int i = 0; i < list.length; i++) {
- IIncludePathEntry other = list[i];
- if (other.getContentKind() == entry.getContentKind()
- && other.getEntryKind() == entry.getEntryKind()
- && other.isExported() == entry.isExported()
- && other.getPath().equals(entry.getPath())) {
-
- // check inclusion patterns
- IPath[] otherIncludes = other.getInclusionPatterns();
- if (inclusionPatterns != otherIncludes) {
- if (inclusionPatterns == null) continue;
- int includeLength = inclusionPatterns.length;
- if (otherIncludes == null || otherIncludes.length != includeLength)
- continue;
- for (int j = 0; j < includeLength; j++) {
- // compare toStrings instead of IPaths
- // since IPath.equals is specified to ignore trailing separators
- if (!inclusionPatterns[j].toString().equals(otherIncludes[j].toString()))
- continue nextEntry;
- }
- }
- // check exclusion patterns
- IPath[] otherExcludes = other.getExclusionPatterns();
- if (exclusionPatterns != otherExcludes) {
- if (exclusionPatterns == null) continue;
- int excludeLength = exclusionPatterns.length;
- if (otherExcludes == null || otherExcludes.length != excludeLength)
- continue;
- for (int j = 0; j < excludeLength; j++) {
- // compare toStrings instead of IPaths
- // since IPath.equals is specified to ignore trailing separators
- if (!exclusionPatterns[j].toString().equals(otherExcludes[j].toString()))
- continue nextEntry;
- }
- }
- return i;
- }
- }
- return -1;
- }
-
- /*
- * Recursively adds all subfolders of <code>folder</code> to the given collection.
- */
- private void collectAllSubfolders(IFolder folder, ArrayList collection) throws JavaScriptModelException {
- try {
- IResource[] members= folder.members();
- for (int i = 0, max = members.length; i < max; i++) {
- IResource r= members[i];
- if (r.getType() == IResource.FOLDER) {
- collection.add(r);
- collectAllSubfolders((IFolder)r, collection);
- }
- }
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- }
- }
-
- /*
- * Returns a collection of package fragments that have been added/removed
- * as the result of changing the output location to/from the given
- * location. The collection is empty if no package fragments are
- * affected.
- */
- private ArrayList determineAffectedPackageFragments(IPath location) throws JavaScriptModelException {
- ArrayList fragments = new ArrayList();
-
- // see if this will cause any package fragments to be affected
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- IResource resource = null;
- if (location != null) {
- resource = workspace.getRoot().findMember(location);
- }
- if (resource != null && resource.getType() == IResource.FOLDER) {
- IFolder folder = (IFolder) resource;
- // only changes if it actually existed
- IIncludePathEntry[] classpath = this.project.getExpandedClasspath();
- for (int i = 0; i < classpath.length; i++) {
- IIncludePathEntry entry = classpath[i];
- IPath path = classpath[i].getPath();
- if (entry.getEntryKind() != IIncludePathEntry.CPE_PROJECT && path.isPrefixOf(location) && !path.equals(location)) {
- IPackageFragmentRoot[] roots = this.project.computePackageFragmentRoots(classpath[i]);
- PackageFragmentRoot root = (PackageFragmentRoot) roots[0];
- // now the output location becomes a package fragment - along with any subfolders
- ArrayList folders = new ArrayList();
- folders.add(folder);
- collectAllSubfolders(folder, folders);
- Iterator elements = folders.iterator();
- int segments = path.segmentCount();
- while (elements.hasNext()) {
- IFolder f = (IFolder) elements.next();
- IPath relativePath = f.getFullPath().removeFirstSegments(segments);
- String[] pkgName = relativePath.segments();
- IPackageFragment pkg = root.getPackageFragment(pkgName);
- if (!Util.isExcluded(pkg))
- fragments.add(pkg);
- }
- }
- }
- }
- return fragments;
- }
-
- public boolean equals(Object obj) {
- if (!(obj instanceof ClasspathChange))
- return false;
- return this.project.equals(((ClasspathChange) obj).project);
- }
-
- /*
- * Generates a classpath change delta for this classpath change.
- * Returns whether a delta was generated, and whether project reference have changed.
- */
- public int generateDelta(JavaElementDelta delta) {
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- DeltaProcessingState state = manager.deltaState;
- if (state.findJavaProject(this.project.getElementName()) == null)
- // project doesn't exist yet (we're in an IWorkspaceRunnable)
- // no need to create a delta here and no need to index (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=133334)
- // the delta processor will create an ADDED project delta, and index the project
- return NO_DELTA;
-
- DeltaProcessor deltaProcessor = state.getDeltaProcessor();
- IIncludePathEntry[] newResolvedClasspath = null;
- IPath newOutputLocation = null;
- int result = NO_DELTA;
- try {
- PerProjectInfo perProjectInfo = this.project.getPerProjectInfo();
-
- // get new info
- this.project.resolveClasspath(perProjectInfo);
- IIncludePathEntry[] newRawClasspath;
-
- // use synchronized block to ensure consistency
- synchronized (perProjectInfo) {
- newRawClasspath = perProjectInfo.rawClasspath;
- newResolvedClasspath = perProjectInfo.resolvedClasspath;
- newOutputLocation = perProjectInfo.outputLocation;
- }
-
- // check if raw classpath has changed
- if (this.oldRawClasspath != null && !JavaProject.areClasspathsEqual(this.oldRawClasspath, newRawClasspath, this.oldOutputLocation, newOutputLocation)) {
- delta.changed(this.project, IJavaScriptElementDelta.F_INCLUDEPATH_CHANGED);
- result |= HAS_DELTA;
- }
-
- // if no changes to resolved classpath, nothing more to do
- if (this.oldResolvedClasspath != null && JavaProject.areClasspathsEqual(this.oldResolvedClasspath, newResolvedClasspath, this.oldOutputLocation, newOutputLocation))
- return NO_DELTA;
-
- // close cached info
- this.project.close();
- } catch (JavaScriptModelException e) {
- if (DeltaProcessor.VERBOSE) {
- e.printStackTrace();
- }
- // project no longer exist
- return NO_DELTA;
- }
-
- if (this.oldResolvedClasspath == null)
- return NO_DELTA;
-
- Map removedRoots = null;
- IPackageFragmentRoot[] roots = null;
- Map allOldRoots ;
- if ((allOldRoots = deltaProcessor.oldRoots) != null) {
- roots = (IPackageFragmentRoot[]) allOldRoots.get(this.project);
- }
- if (roots != null) {
- removedRoots = new HashMap();
- for (int i = 0; i < roots.length; i++) {
- IPackageFragmentRoot root = roots[i];
- removedRoots.put(root.getPath(), root);
- }
- }
-
- int newLength = newResolvedClasspath.length;
- int oldLength = this.oldResolvedClasspath.length;
- for (int i = 0; i < oldLength; i++) {
- int index = classpathContains(newResolvedClasspath, this.oldResolvedClasspath[i]);
- if (index == -1) {
- // remote project changes
- if (this.oldResolvedClasspath[i].getEntryKind() == IIncludePathEntry.CPE_PROJECT) {
- result |= HAS_PROJECT_CHANGE;
- continue;
- }
-
- IPackageFragmentRoot[] pkgFragmentRoots = null;
- if (removedRoots != null) {
- IPackageFragmentRoot oldRoot = (IPackageFragmentRoot) removedRoots.get(this.oldResolvedClasspath[i].getPath());
- if (oldRoot != null) { // use old root if any (could be none if entry wasn't bound)
- pkgFragmentRoots = new IPackageFragmentRoot[] { oldRoot };
- }
- }
- if (pkgFragmentRoots == null) {
- try {
- ObjectVector accumulatedRoots = new ObjectVector();
- HashSet rootIDs = new HashSet(5);
- rootIDs.add(this.project.rootID());
- this.project.computePackageFragmentRoots(
- this.oldResolvedClasspath[i],
- accumulatedRoots,
- rootIDs,
- null, // inside original project
- false, // don't check existency
- false, // don't retrieve exported roots
- null); /*no reverse map*/
- pkgFragmentRoots = new IPackageFragmentRoot[accumulatedRoots.size()];
- accumulatedRoots.copyInto(pkgFragmentRoots);
- } catch (JavaScriptModelException e) {
- pkgFragmentRoots = new IPackageFragmentRoot[] {};
- }
- }
- addClasspathDeltas(delta, pkgFragmentRoots, IJavaScriptElementDelta.F_REMOVED_FROM_CLASSPATH);
- result |= HAS_DELTA;
- } else {
- // remote project changes
- if (this.oldResolvedClasspath[i].getEntryKind() == IIncludePathEntry.CPE_PROJECT) {
- result |= HAS_PROJECT_CHANGE;
- continue;
- }
- if (index != i) { //reordering of the classpath
- addClasspathDeltas(delta, this.project.computePackageFragmentRoots(this.oldResolvedClasspath[i]), IJavaScriptElementDelta.F_REORDER);
- result |= HAS_DELTA;
- }
-
- // check source attachment
- IPath newSourcePath = newResolvedClasspath[index].getSourceAttachmentPath();
- int sourceAttachmentFlags = getSourceAttachmentDeltaFlag(this.oldResolvedClasspath[i].getSourceAttachmentPath(), newSourcePath);
- IPath oldRootPath = this.oldResolvedClasspath[i].getSourceAttachmentRootPath();
- IPath newRootPath = newResolvedClasspath[index].getSourceAttachmentRootPath();
- int sourceAttachmentRootFlags = getSourceAttachmentDeltaFlag(oldRootPath, newRootPath);
- int flags = sourceAttachmentFlags | sourceAttachmentRootFlags;
- if (flags != 0) {
- addClasspathDeltas(delta, this.project.computePackageFragmentRoots(this.oldResolvedClasspath[i]), flags);
- result |= HAS_DELTA;
- } else {
- if (oldRootPath == null && newRootPath == null) {
- // if source path is specified and no root path, it needs to be recomputed dynamically
- // force detach source on jar package fragment roots (source will be lazily computed when needed)
- IPackageFragmentRoot[] computedRoots = this.project.computePackageFragmentRoots(this.oldResolvedClasspath[i]);
- for (int j = 0; j < computedRoots.length; j++) {
- IPackageFragmentRoot root = computedRoots[j];
- // force detach source on jar package fragment roots (source will be lazily computed when needed)
- try {
- root.close();
- } catch (JavaScriptModelException e) {
- // ignore
- }
- }
- }
- }
- }
- }
-
- for (int i = 0; i < newLength; i++) {
- int index = classpathContains(this.oldResolvedClasspath, newResolvedClasspath[i]);
- if (index == -1) {
- // remote project changes
- if (newResolvedClasspath[i].getEntryKind() == IIncludePathEntry.CPE_PROJECT) {
- result |= HAS_PROJECT_CHANGE;
- continue;
- }
- addClasspathDeltas(delta, this.project.computePackageFragmentRoots(newResolvedClasspath[i]), IJavaScriptElementDelta.F_ADDED_TO_CLASSPATH);
- result |= HAS_DELTA;
- } // classpath reordering has already been generated in previous loop
- }
-
- // see if a change in output location will cause any package fragments to be added/removed
- if ((newOutputLocation == null && this.oldOutputLocation != null)
- || (newOutputLocation != null && !newOutputLocation.equals(this.oldOutputLocation))) {
- try {
- ArrayList added= determineAffectedPackageFragments(this.oldOutputLocation);
- Iterator iter = added.iterator();
- while (iter.hasNext()){
- IPackageFragment frag= (IPackageFragment)iter.next();
- ((IPackageFragmentRoot)frag.getParent()).close();
- delta.added(frag);
- result |= HAS_DELTA;
- }
-
- // see if this will cause any package fragments to be removed
- ArrayList removed= determineAffectedPackageFragments(newOutputLocation);
- iter = removed.iterator();
- while (iter.hasNext()) {
- IPackageFragment frag= (IPackageFragment)iter.next();
- ((IPackageFragmentRoot)frag.getParent()).close();
- delta.removed(frag);
- result |= HAS_DELTA;
- }
- } catch (JavaScriptModelException e) {
- if (DeltaProcessor.VERBOSE)
- e.printStackTrace();
- }
- }
-
- return result;
- }
-
- /*
- * Returns the source attachment flag for the delta between the 2 give source paths.
- * Returns either F_SOURCEATTACHED, F_SOURCEDETACHED, F_SOURCEATTACHED | F_SOURCEDETACHED
- * or 0 if there is no difference.
- */
- private int getSourceAttachmentDeltaFlag(IPath oldPath, IPath newPath) {
- if (oldPath == null) {
- if (newPath != null) {
- return IJavaScriptElementDelta.F_SOURCEATTACHED;
- } else {
- return 0;
- }
- } else if (newPath == null) {
- return IJavaScriptElementDelta.F_SOURCEDETACHED;
- } else if (!oldPath.equals(newPath)) {
- return IJavaScriptElementDelta.F_SOURCEATTACHED | IJavaScriptElementDelta.F_SOURCEDETACHED;
- } else {
- return 0;
- }
- }
-
- public int hashCode() {
- return this.project.hashCode();
- }
-
- /*
- * Request the indexing of entries that have been added, and remove the index for removed entries.
- */
- public void requestIndexing() {
- IIncludePathEntry[] newResolvedClasspath = null;
- try {
- newResolvedClasspath = this.project.getResolvedClasspath();
- } catch (JavaScriptModelException e) {
- // project doesn't exist
- return;
- }
-
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- IndexManager indexManager = manager.indexManager;
- if (indexManager == null)
- return;
- DeltaProcessingState state = manager.deltaState;
-
- int newLength = newResolvedClasspath.length;
- int oldLength = this.oldResolvedClasspath.length;
- for (int i = 0; i < oldLength; i++) {
- int index = classpathContains(newResolvedClasspath, this.oldResolvedClasspath[i]);
- if (index == -1) {
- // remote projects are not indexed in this project
- if (this.oldResolvedClasspath[i].getEntryKind() == IIncludePathEntry.CPE_PROJECT){
- continue;
- }
-
- // Remove the .js files from the index for a source folder
- // For a lib folder or a .jar file, remove the corresponding index if not shared.
- IIncludePathEntry oldEntry = this.oldResolvedClasspath[i];
- final IPath path = oldEntry.getPath();
- int changeKind = this.oldResolvedClasspath[i].getEntryKind();
- switch (changeKind) {
- case IIncludePathEntry.CPE_SOURCE:
- char[][] inclusionPatterns = ((ClasspathEntry)oldEntry).fullInclusionPatternChars();
- char[][] exclusionPatterns = ((ClasspathEntry)oldEntry).fullExclusionPatternChars();
- indexManager.removeSourceFolderFromIndex(this.project, path, inclusionPatterns, exclusionPatterns);
- break;
- case IIncludePathEntry.CPE_LIBRARY:
- if (state.otherRoots.get(path) == null) { // if root was not shared
- indexManager.discardJobs(path.toString());
- indexManager.removeIndex(path);
- // TODO (kent) we could just remove the in-memory index and have the indexing check for timestamps
- }
- break;
- }
- }
- }
-
- for (int i = 0; i < newLength; i++) {
- int index = classpathContains(this.oldResolvedClasspath, newResolvedClasspath[i]);
- if (index == -1) {
- // remote projects are not indexed in this project
- if (newResolvedClasspath[i].getEntryKind() == IIncludePathEntry.CPE_PROJECT){
- continue;
- }
-
- // Request indexing
- int entryKind = newResolvedClasspath[i].getEntryKind();
- switch (entryKind) {
- case IIncludePathEntry.CPE_LIBRARY:
- boolean pathHasChanged = true;
- IPath newPath = newResolvedClasspath[i].getPath();
- for (int j = 0; j < oldLength; j++) {
- IIncludePathEntry oldEntry = this.oldResolvedClasspath[j];
- if (oldEntry.getPath().equals(newPath)) {
- pathHasChanged = false;
- break;
- }
- }
- if (pathHasChanged) {
- indexManager.indexLibrary(newResolvedClasspath[i], this.project.getProject());
- }
- break;
- case IIncludePathEntry.CPE_SOURCE:
- IIncludePathEntry entry = newResolvedClasspath[i];
- IPath path = entry.getPath();
- char[][] inclusionPatterns = ((ClasspathEntry)entry).fullInclusionPatternChars();
- char[][] exclusionPatterns = ((ClasspathEntry)entry).fullExclusionPatternChars();
- indexManager.indexSourceFolder(this.project, path, inclusionPatterns, exclusionPatterns);
- break;
- }
- }
- }
- }
-
- public String toString() {
- return "ClasspathChange: " + this.project.getElementName(); //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ClasspathEntry.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ClasspathEntry.java
deleted file mode 100644
index 10cbfd5a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ClasspathEntry.java
+++ /dev/null
@@ -1,1688 +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;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.OutputStreamWriter;
-import java.io.UnsupportedEncodingException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.AssertionFailedException;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-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.IJavaScriptModelStatus;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatusConstants;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer;
-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.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.internal.compiler.env.AccessRule;
-import org.eclipse.wst.jsdt.internal.compiler.env.AccessRuleSet;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-import org.w3c.dom.DOMException;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.w3c.dom.Text;
-
-/**
- * @see IIncludePathEntry
- */
-public class ClasspathEntry implements IIncludePathEntry {
-
- public static final String TAG_CLASSPATH = "classpath"; //$NON-NLS-1$
- public static final String TAG_CLASSPATHENTRY = "classpathentry"; //$NON-NLS-1$
- public static final String TAG_OUTPUT = "output"; //$NON-NLS-1$
- public static final String TAG_KIND = "kind"; //$NON-NLS-1$
- public static final String TAG_PATH = "path"; //$NON-NLS-1$
- public static final String TAG_SOURCEPATH = "sourcepath"; //$NON-NLS-1$
- public static final String TAG_ROOTPATH = "rootpath"; //$NON-NLS-1$
- public static final String TAG_EXPORTED = "exported"; //$NON-NLS-1$
- public static final String TAG_INCLUDING = "including"; //$NON-NLS-1$
- public static final String TAG_EXCLUDING = "excluding"; //$NON-NLS-1$
- public static final String TAG_ATTRIBUTES = "attributes"; //$NON-NLS-1$
- public static final String TAG_ATTRIBUTE = "attribute"; //$NON-NLS-1$
- public static final String TAG_ATTRIBUTE_NAME = "name"; //$NON-NLS-1$
- public static final String TAG_ATTRIBUTE_VALUE = "value"; //$NON-NLS-1$
- public static final String TAG_COMBINE_ACCESS_RULES = "combineaccessrules"; //$NON-NLS-1$
- public static final String TAG_ACCESS_RULES = "accessrules"; //$NON-NLS-1$
- public static final String TAG_ACCESS_RULE = "accessrule"; //$NON-NLS-1$
- public static final String TAG_PATTERN = "pattern"; //$NON-NLS-1$
- public static final String TAG_ACCESSIBLE = "accessible"; //$NON-NLS-1$
- public static final String TAG_NON_ACCESSIBLE = "nonaccessible"; //$NON-NLS-1$
- public static final String TAG_DISCOURAGED = "discouraged"; //$NON-NLS-1$
- public static final String TAG_IGNORE_IF_BETTER = "ignoreifbetter"; //$NON-NLS-1$
- //public static final IIncludePathAttribute EXCLUDE_VALIDATE = new ClasspathAttribute("validate","false");
- //public static final IIncludePathAttribute HIDE = new ClasspathAttribute("hide","true");
- /**
- * Describes the kind of classpath entry - one of
- * CPE_PROJECT, CPE_LIBRARY, CPE_SOURCE, CPE_VARIABLE or CPE_CONTAINER
- */
- public int entryKind;
-
- /**
- * Describes the kind of package fragment roots found on
- * this classpath entry - either K_BINARY or K_SOURCE or
- * K_OUTPUT.
- */
- public int contentKind;
-
- /**
- * The meaning of the path of a classpath entry depends on its entry kind:<ul>
- * <li>Source code in the current project (<code>CPE_SOURCE</code>) -
- * The path associated with this entry is the absolute path to the root folder. </li>
- * <li>A binary library in the current project (<code>CPE_LIBRARY</code>) - the path
- * associated with this entry is the absolute path to the JAR (or root folder), and
- * in case it refers to an external JAR, then there is no associated resource in
- * the workbench.
- * <li>A required project (<code>CPE_PROJECT</code>) - the path of the entry denotes the
- * path to the corresponding project resource.</li>
- * <li>A variable entry (<code>CPE_VARIABLE</code>) - the first segment of the path
- * is the name of a classpath variable. If this classpath variable
- * is bound to the path <it>P</it>, the path of the corresponding classpath entry
- * is computed by appending to <it>P</it> the segments of the returned
- * path without the variable.</li>
- * <li> A container entry (<code>CPE_CONTAINER</code>) - the first segment of the path is denoting
- * the unique container identifier (for which a <code>JsGlobalScopeContainerInitializer</code> could be
- * registered), and the remaining segments are used as additional hints for resolving the container entry to
- * an actual <code>IJsGlobalScopeContainer</code>.</li>
- */
- public IPath path;
-
- /**
- * Patterns allowing to include/exclude portions of the resource tree denoted by this entry path.
- */
- private IPath[] inclusionPatterns;
- private char[][] fullInclusionPatternChars;
- private IPath[] exclusionPatterns;
- private char[][] fullExclusionPatternChars;
- private final static char[][] UNINIT_PATTERNS = new char[][] { "Non-initialized yet".toCharArray() }; //$NON-NLS-1$
-
- private boolean combineAccessRules;
-
- private String rootID;
- private AccessRuleSet accessRuleSet;
-
-
- static class UnknownXmlElements {
- String[] attributes;
- ArrayList children;
- }
-
- /*
- * Default inclusion pattern set
- */
- public final static IPath[] INCLUDE_ALL = {};
-
- /*
- * Default exclusion pattern set
- */
- public final static IPath[] EXCLUDE_NONE = {};
-
- /*
- * Default extra attributes
- */
- public final static IIncludePathAttribute[] NO_EXTRA_ATTRIBUTES = {};
-
- /*
- * Default access rules
- */
- public final static IAccessRule[] NO_ACCESS_RULES = {};
-
- /**
- * Describes the path to the source archive associated with this
- * classpath entry, or <code>null</code> if this classpath entry has no
- * source attachment.
- * <p>
- * Only library and variable classpath entries may have source attachments.
- * For library classpath entries, the result path (if present) locates a source
- * archive. For variable classpath entries, the result path (if present) has
- * an analogous form and meaning as the variable path, namely the first segment
- * is the name of a classpath variable.
- */
- public IPath sourceAttachmentPath;
-
- /**
- * Describes the path within the source archive where package fragments
- * are located. An empty path indicates that packages are located at
- * the root of the source archive. Returns a non-<code>null</code> value
- * if and only if <code>getSourceAttachmentPath</code> returns
- * a non-<code>null</code> value.
- */
- public IPath sourceAttachmentRootPath;
-
- /**
- * Specific output location (for this source entry)
- */
- public IPath specificOutputLocation;
-
- /**
- * A constant indicating an output location.
- */
- public static final int K_OUTPUT = 10;
-
- /**
- * The export flag
- */
- public boolean isExported;
-
- /*
- * The extra attributes
- */
- IIncludePathAttribute[] extraAttributes;
-
- /**
- * Creates a class path entry of the specified kind with the given path.
- */
- public ClasspathEntry(
- int contentKind,
- int entryKind,
- IPath path,
- IPath[] inclusionPatterns,
- IPath[] exclusionPatterns,
- IPath sourceAttachmentPath,
- IPath sourceAttachmentRootPath,
- IPath specificOutputLocation,
- boolean isExported,
- IAccessRule[] accessRules,
- boolean combineAccessRules,
- IIncludePathAttribute[] extraAttributes) {
-
- this.contentKind = contentKind;
- this.entryKind = entryKind;
- this.path = path;
- this.inclusionPatterns = inclusionPatterns;
- this.exclusionPatterns = exclusionPatterns;
-
- int length;
- if (accessRules != null && (length = accessRules.length) > 0) {
- AccessRule[] rules = new AccessRule[length];
- System.arraycopy(accessRules, 0, rules, 0, length);
- this.accessRuleSet = new AccessRuleSet(rules, getMessageTemplates());
- }
-// else { -- implicit!
-// this.accessRuleSet = null;
-// }
-
- this.combineAccessRules = combineAccessRules;
- this.extraAttributes = extraAttributes;
-
- if (inclusionPatterns != INCLUDE_ALL && inclusionPatterns.length > 0) {
- this.fullInclusionPatternChars = UNINIT_PATTERNS;
- }
- if (exclusionPatterns.length > 0) {
- this.fullExclusionPatternChars = UNINIT_PATTERNS;
- }
- this.sourceAttachmentPath = sourceAttachmentPath;
- this.sourceAttachmentRootPath = sourceAttachmentRootPath;
- this.specificOutputLocation = specificOutputLocation;
- this.isExported = isExported;
- }
-
- public boolean combineAccessRules() {
- return this.combineAccessRules;
- }
-
- /**
- * Used to perform export/restriction propagation across referring projects/containers
- */
- public ClasspathEntry combineWith(ClasspathEntry referringEntry) {
- if (referringEntry == null) return this;
- if (referringEntry.isExported() || referringEntry.getAccessRuleSet() != null ) {
- boolean combine = this.entryKind == CPE_SOURCE || referringEntry.combineAccessRules();
- return new ClasspathEntry(
- getContentKind(),
- getEntryKind(),
- getPath(),
- this.inclusionPatterns,
- this.exclusionPatterns,
- getSourceAttachmentPath(),
- getSourceAttachmentRootPath(),
- getOutputLocation(),
- referringEntry.isExported() || this.isExported, // duplicate container entry for tagging it as exported
- combine(referringEntry.getAccessRules(), getAccessRules(), combine),
- this.combineAccessRules,
- this.extraAttributes);
- }
- // no need to clone
- return this;
- }
-
- private IAccessRule[] combine(IAccessRule[] referringRules, IAccessRule[] rules, boolean combine) {
- if (!combine) return rules;
- if (rules == null || rules.length == 0) return referringRules;
-
- // concat access rules
- int referringRulesLength = referringRules.length;
- int accessRulesLength = rules.length;
- int rulesLength = referringRulesLength + accessRulesLength;
- IAccessRule[] result = new IAccessRule[rulesLength];
- System.arraycopy(referringRules, 0, result, 0, referringRulesLength);
- System.arraycopy(rules, 0, result, referringRulesLength, accessRulesLength);
-
- return result;
- }
-
- static IIncludePathAttribute[] decodeExtraAttributes(NodeList attributes) {
- if (attributes == null) return NO_EXTRA_ATTRIBUTES;
- int length = attributes.getLength();
- if (length == 0) return NO_EXTRA_ATTRIBUTES;
- IIncludePathAttribute[] result = new IIncludePathAttribute[length];
- int index = 0;
- for (int i = 0; i < length; ++i) {
- Node node = attributes.item(i);
- if (node.getNodeType() == Node.ELEMENT_NODE) {
- Element attribute = (Element)node;
- String name = attribute.getAttribute(TAG_ATTRIBUTE_NAME);
- if (name == null) continue;
- String value = attribute.getAttribute(TAG_ATTRIBUTE_VALUE);
- if (value == null) continue;
- result[index++] = new ClasspathAttribute(name, value);
- }
- }
- if (index != length)
- System.arraycopy(result, 0, result = new IIncludePathAttribute[index], 0, index);
- return result;
- }
-
- static IAccessRule[] decodeAccessRules(NodeList list) {
- if (list == null) return null;
- int length = list.getLength();
- if (length == 0) return null;
- IAccessRule[] result = new IAccessRule[length];
- int index = 0;
- for (int i = 0; i < length; i++) {
- Node accessRule = list.item(i);
- if (accessRule.getNodeType() == Node.ELEMENT_NODE) {
- Element elementAccessRule = (Element) accessRule;
- String pattern = elementAccessRule.getAttribute(TAG_PATTERN);
- if (pattern == null) continue;
- String tagKind = elementAccessRule.getAttribute(TAG_KIND);
- int kind;
- if (TAG_ACCESSIBLE.equals(tagKind))
- kind = IAccessRule.K_ACCESSIBLE;
- else if (TAG_NON_ACCESSIBLE.equals(tagKind))
- kind = IAccessRule.K_NON_ACCESSIBLE;
- else if (TAG_DISCOURAGED.equals(tagKind))
- kind = IAccessRule.K_DISCOURAGED;
- else
- continue;
- boolean ignoreIfBetter = "true".equals(elementAccessRule.getAttribute(TAG_IGNORE_IF_BETTER)); //$NON-NLS-1$
- result[index++] = new ClasspathAccessRule(new Path(pattern), ignoreIfBetter ? kind | IAccessRule.IGNORE_IF_BETTER : kind);
- }
- }
- if (index != length)
- System.arraycopy(result, 0, result = new IAccessRule[index], 0, index);
- return result;
- }
-
- /**
- * Decode some element tag containing a sequence of patterns into IPath[]
- */
- private static IPath[] decodePatterns(NamedNodeMap nodeMap, String tag) {
- String sequence = removeAttribute(tag, nodeMap);
- if (!sequence.equals("")) { //$NON-NLS-1$
- char[][] patterns = CharOperation.splitOn('|', sequence.toCharArray());
- int patternCount;
- if ((patternCount = patterns.length) > 0) {
- IPath[] paths = new IPath[patternCount];
- int index = 0;
- for (int j = 0; j < patternCount; j++) {
- char[] pattern = patterns[j];
- if (pattern.length == 0) continue; // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=105581
- paths[index++] = new Path(new String(pattern));
- }
- if (index < patternCount)
- System.arraycopy(paths, 0, paths = new IPath[index], 0, index);
- return paths;
- }
- }
- return null;
- }
-
- private static void decodeUnknownNode(Node node, StringBuffer buffer, IJavaScriptProject project) {
- ByteArrayOutputStream s = new ByteArrayOutputStream();
- OutputStreamWriter writer;
- try {
- writer = new OutputStreamWriter(s, "UTF8"); //$NON-NLS-1$
- XMLWriter xmlWriter = new XMLWriter(writer, project, false/*don't print XML version*/);
- decodeUnknownNode(node, xmlWriter, true/*insert new line*/);
- xmlWriter.flush();
- xmlWriter.close();
- buffer.append(s.toString("UTF8")); //$NON-NLS-1$
- } catch (UnsupportedEncodingException e) {
- // ignore (UTF8 is always supported)
- }
- }
-
- private static void decodeUnknownNode(Node node, XMLWriter xmlWriter, boolean insertNewLine) {
- switch (node.getNodeType()) {
- case Node.ELEMENT_NODE:
- NamedNodeMap attributes;
- HashMap parameters = null;
- if ((attributes = node.getAttributes()) != null) {
- int length = attributes.getLength();
- if (length > 0) {
- parameters = new HashMap();
- for (int i = 0; i < length; i++) {
- Node attribute = attributes.item(i);
- parameters.put(attribute.getNodeName(), attribute.getNodeValue());
- }
- }
- }
- NodeList children = node.getChildNodes();
- int childrenLength = children.getLength();
- String nodeName = node.getNodeName();
- xmlWriter.printTag(nodeName, parameters, false/*don't insert tab*/, false/*don't insert new line*/, childrenLength == 0/*close tag if no children*/);
- if (childrenLength > 0) {
- for (int i = 0; i < childrenLength; i++) {
- decodeUnknownNode(children.item(i), xmlWriter, false/*don't insert new line*/);
- }
- xmlWriter.endTag(nodeName, false/*don't insert tab*/, insertNewLine);
- }
- break;
- case Node.TEXT_NODE:
- String data = ((Text) node).getData();
- xmlWriter.printString(data, false/*don't insert tab*/, false/*don't insert new line*/);
- break;
- }
- }
-
- /*
- * Returns a char based representation of the exclusions patterns full path.
- */
- public char[][] fullExclusionPatternChars() {
-
- if (this.fullExclusionPatternChars == UNINIT_PATTERNS) {
- int length = this.exclusionPatterns.length;
- this.fullExclusionPatternChars = new char[length][];
- IPath prefixPath = this.path.removeTrailingSeparator();
- for (int i = 0; i < length; i++) {
- this.fullExclusionPatternChars[i] =
- prefixPath.append(this.exclusionPatterns[i]).toString().toCharArray();
- }
- }
- return this.fullExclusionPatternChars;
- }
-
- /*
- * Returns a char based representation of the exclusions patterns full path.
- */
- public char[][] fullInclusionPatternChars() {
-
- if (this.fullInclusionPatternChars == UNINIT_PATTERNS) {
- int length = this.inclusionPatterns.length;
- this.fullInclusionPatternChars = new char[length][];
- IPath prefixPath = this.path.removeTrailingSeparator();
- for (int i = 0; i < length; i++) {
- this.fullInclusionPatternChars[i] =
- prefixPath.append(this.inclusionPatterns[i]).toString().toCharArray();
- }
- }
- return this.fullInclusionPatternChars;
- }
-
- /**
- * Returns the XML encoding of the class path.
- */
- public void elementEncode(XMLWriter writer, IPath projectPath, boolean indent, boolean newLine, Map unknownElements) {
- HashMap parameters = new HashMap();
-
- parameters.put(TAG_KIND, ClasspathEntry.kindToString(this.entryKind));
-
- IPath xmlPath = this.path;
- if (this.entryKind != IIncludePathEntry.CPE_VARIABLE && this.entryKind != IIncludePathEntry.CPE_CONTAINER) {
- // translate to project relative from absolute (unless a device path)
- if (xmlPath.isAbsolute()) {
- if (projectPath != null && projectPath.isPrefixOf(xmlPath)) {
- if (xmlPath.segment(0).equals(projectPath.segment(0))) {
- xmlPath = xmlPath.removeFirstSegments(1);
- xmlPath = xmlPath.makeRelative();
- } else {
- xmlPath = xmlPath.makeAbsolute();
- }
- }
- }
- }
- parameters.put(TAG_PATH, String.valueOf(xmlPath));
-
- if (this.sourceAttachmentPath != null) {
- xmlPath = this.sourceAttachmentPath;
- // translate to project relative from absolute
- if (this.entryKind != IIncludePathEntry.CPE_VARIABLE && projectPath != null && projectPath.isPrefixOf(xmlPath)) {
- if (xmlPath.segment(0).equals(projectPath.segment(0))) {
- xmlPath = xmlPath.removeFirstSegments(1);
- xmlPath = xmlPath.makeRelative();
- }
- }
- parameters.put(TAG_SOURCEPATH, String.valueOf(xmlPath));
- }
- if (this.sourceAttachmentRootPath != null) {
- parameters.put(TAG_ROOTPATH, String.valueOf(this.sourceAttachmentRootPath));
- }
- if (this.isExported) {
- parameters.put(TAG_EXPORTED, "true");//$NON-NLS-1$
- }
- encodePatterns(this.inclusionPatterns, TAG_INCLUDING, parameters);
- encodePatterns(this.exclusionPatterns, TAG_EXCLUDING, parameters);
- if (this.entryKind == CPE_PROJECT && !this.combineAccessRules)
- parameters.put(TAG_COMBINE_ACCESS_RULES, "false"); //$NON-NLS-1$
-
-
- // unknown attributes
- UnknownXmlElements unknownXmlElements = unknownElements == null ? null : (UnknownXmlElements) unknownElements.get(this.path);
- String[] unknownAttributes;
- if (unknownXmlElements != null && (unknownAttributes = unknownXmlElements.attributes) != null)
- for (int i = 0, length = unknownAttributes.length; i < length; i+=2) {
- String tagName = unknownAttributes[i];
- String tagValue = unknownAttributes[i+1];
- parameters.put(tagName, tagValue);
- }
-
- if (this.specificOutputLocation != null) {
- IPath outputLocation = this.specificOutputLocation.removeFirstSegments(1);
- outputLocation = outputLocation.makeRelative();
- parameters.put(TAG_OUTPUT, String.valueOf(outputLocation));
- }
-
- boolean hasExtraAttributes = this.extraAttributes.length != 0;
- boolean hasRestrictions = getAccessRuleSet() != null; // access rule set is null if no access rules
- ArrayList unknownChildren = unknownXmlElements != null ? unknownXmlElements.children : null;
- boolean hasUnknownChildren = unknownChildren != null;
- writer.printTag(
- TAG_CLASSPATHENTRY,
- parameters,
- indent,
- newLine,
- !hasExtraAttributes && !hasRestrictions && !hasUnknownChildren/*close tag if no extra attributes, no restriction and no unknown children*/);
-
- if (hasExtraAttributes)
- encodeExtraAttributes(writer, indent, newLine);
-
- if (hasRestrictions)
- encodeAccessRules(writer, indent, newLine);
-
- if (hasUnknownChildren)
- encodeUnknownChildren(writer, indent, newLine, unknownChildren);
-
- if (hasExtraAttributes || hasRestrictions || hasUnknownChildren)
- writer.endTag(TAG_CLASSPATHENTRY, indent, true/*insert new line*/);
- }
-
- void encodeExtraAttributes(XMLWriter writer, boolean indent, boolean newLine) {
- writer.startTag(TAG_ATTRIBUTES, indent);
- for (int i = 0; i < this.extraAttributes.length; i++) {
- IIncludePathAttribute attribute = this.extraAttributes[i];
- HashMap parameters = new HashMap();
- parameters.put(TAG_ATTRIBUTE_NAME, attribute.getName());
- parameters.put(TAG_ATTRIBUTE_VALUE, attribute.getValue());
- writer.printTag(TAG_ATTRIBUTE, parameters, indent, newLine, true);
- }
- writer.endTag(TAG_ATTRIBUTES, indent, true/*insert new line*/);
- }
-
- void encodeAccessRules(XMLWriter writer, boolean indent, boolean newLine) {
-
- writer.startTag(TAG_ACCESS_RULES, indent);
- AccessRule[] rules = getAccessRuleSet().getAccessRules();
- for (int i = 0, length = rules.length; i < length; i++) {
- encodeAccessRule(rules[i], writer, indent, newLine);
- }
- writer.endTag(TAG_ACCESS_RULES, indent, true/*insert new line*/);
- }
-
- private void encodeAccessRule(AccessRule accessRule, XMLWriter writer, boolean indent, boolean newLine) {
-
- HashMap parameters = new HashMap();
- parameters.put(TAG_PATTERN, new String(accessRule.pattern));
-
- switch (accessRule.getProblemId()) {
- case IProblem.ForbiddenReference:
- parameters.put(TAG_KIND, TAG_NON_ACCESSIBLE);
- break;
- case IProblem.DiscouragedReference:
- parameters.put(TAG_KIND, TAG_DISCOURAGED);
- break;
- default:
- parameters.put(TAG_KIND, TAG_ACCESSIBLE);
- break;
- }
- if (accessRule.ignoreIfBetter())
- parameters.put(TAG_IGNORE_IF_BETTER, "true"); //$NON-NLS-1$
-
- writer.printTag(TAG_ACCESS_RULE, parameters, indent, newLine, true);
-
- }
-
- private void encodeUnknownChildren(XMLWriter writer, boolean indent, boolean newLine, ArrayList unknownChildren) {
- for (int i = 0, length = unknownChildren.size(); i < length; i++) {
- String child = (String) unknownChildren.get(i);
- writer.printString(child, indent, false/*don't insert new line*/);
- }
- }
-
- public static IIncludePathEntry elementDecode(Element element, IJavaScriptProject project, Map unknownElements) {
-
- IPath projectPath = project.getProject().getFullPath();
- NamedNodeMap attributes = element.getAttributes();
- NodeList children = element.getChildNodes();
- boolean[] foundChildren = new boolean[children.getLength()];
- String kindAttr = removeAttribute(TAG_KIND, attributes);
- String pathAttr = removeAttribute(TAG_PATH, attributes);
-
- // ensure path is absolute
- IPath path = new Path(pathAttr);
- int kind = kindFromString(kindAttr);
- if (kind != IIncludePathEntry.CPE_VARIABLE && kind != IIncludePathEntry.CPE_CONTAINER && !path.isAbsolute()) {
- path = projectPath.append(path);
- }
- // source attachment info (optional)
- IPath sourceAttachmentPath =
- element.hasAttribute(TAG_SOURCEPATH)
- ? new Path(removeAttribute(TAG_SOURCEPATH, attributes))
- : null;
- if (kind != IIncludePathEntry.CPE_VARIABLE && sourceAttachmentPath != null && !sourceAttachmentPath.isAbsolute()) {
- sourceAttachmentPath = projectPath.append(sourceAttachmentPath);
- }
- IPath sourceAttachmentRootPath =
- element.hasAttribute(TAG_ROOTPATH)
- ? new Path(removeAttribute(TAG_ROOTPATH, attributes))
- : null;
-
- // exported flag (optional)
- boolean isExported = removeAttribute(TAG_EXPORTED, attributes).equals("true"); //$NON-NLS-1$
-
- // inclusion patterns (optional)
- IPath[] inclusionPatterns = decodePatterns(attributes, TAG_INCLUDING);
- if (inclusionPatterns == null) inclusionPatterns = INCLUDE_ALL;
-
- // exclusion patterns (optional)
- IPath[] exclusionPatterns = decodePatterns(attributes, TAG_EXCLUDING);
- if (exclusionPatterns == null) exclusionPatterns = EXCLUDE_NONE;
-
- // access rules (optional)
- NodeList attributeList = getChildAttributes(TAG_ACCESS_RULES, children, foundChildren);
- IAccessRule[] accessRules = decodeAccessRules(attributeList);
-
- // backward compatibility
- if (accessRules == null) {
- accessRules = getAccessRules(inclusionPatterns, exclusionPatterns);
- }
-
- // combine access rules (optional)
- boolean combineAccessRestrictions = !removeAttribute(TAG_COMBINE_ACCESS_RULES, attributes).equals("false"); //$NON-NLS-1$
-
- // extra attributes (optional)
- attributeList = getChildAttributes(TAG_ATTRIBUTES, children, foundChildren);
- IIncludePathAttribute[] extraAttributes = decodeExtraAttributes(attributeList);
-
- // custom output location
- IPath outputLocation = element.hasAttribute(TAG_OUTPUT) ? projectPath.append(removeAttribute(TAG_OUTPUT, attributes)) : null;
-
- String[] unknownAttributes = null;
- ArrayList unknownChildren = null;
-
- if (unknownElements != null) {
- // unknown attributes
- int unknownAttributeLength = attributes.getLength();
- if (unknownAttributeLength != 0) {
- unknownAttributes = new String[unknownAttributeLength*2];
- for (int i = 0; i < unknownAttributeLength; i++) {
- Node attribute = attributes.item(i);
- unknownAttributes[i*2] = attribute.getNodeName();
- unknownAttributes[i*2 + 1] = attribute.getNodeValue();
- }
- }
-
- // unknown children
- for (int i = 0, length = foundChildren.length; i < length; i++) {
- if (!foundChildren[i]) {
- Node node = children.item(i);
- if (node.getNodeType() != Node.ELEMENT_NODE) continue;
- if (unknownChildren == null)
- unknownChildren = new ArrayList();
- StringBuffer buffer = new StringBuffer();
- decodeUnknownNode(node, buffer, project);
- unknownChildren.add(buffer.toString());
- }
- }
- }
-
- // recreate the CP entry
- IIncludePathEntry entry = null;
- switch (kind) {
-
- case IIncludePathEntry.CPE_PROJECT :
- entry = new ClasspathEntry(
- IPackageFragmentRoot.K_SOURCE,
- IIncludePathEntry.CPE_PROJECT,
- path,
- ClasspathEntry.INCLUDE_ALL, // inclusion patterns
- ClasspathEntry.EXCLUDE_NONE, // exclusion patterns
- null, // source attachment
- null, // source attachment root
- null, // specific output folder
- isExported,
- accessRules,
- combineAccessRestrictions,
- extraAttributes);
- break;
- case IIncludePathEntry.CPE_LIBRARY :
- entry = JavaScriptCore.newLibraryEntry(
- path,
- sourceAttachmentPath,
- sourceAttachmentRootPath,
- accessRules,
- extraAttributes,
- isExported);
- break;
- case IIncludePathEntry.CPE_SOURCE :
- // must be an entry in this project or specify another project
- String projSegment = path.segment(0);
- if (projSegment != null && projSegment.equals(project.getElementName())) { // this project
- entry = JavaScriptCore.newSourceEntry(path, inclusionPatterns, exclusionPatterns, outputLocation, extraAttributes);
- } else {
- if (path.segmentCount() == 1) {
- // another project
- entry = JavaScriptCore.newProjectEntry(
- path,
- accessRules,
- combineAccessRestrictions,
- extraAttributes,
- isExported);
- } else {
- // an invalid source folder
- entry = JavaScriptCore.newSourceEntry(path, inclusionPatterns, exclusionPatterns, outputLocation, extraAttributes);
- }
- }
- break;
- case IIncludePathEntry.CPE_VARIABLE :
- entry = JavaScriptCore.newVariableEntry(
- path,
- sourceAttachmentPath,
- sourceAttachmentRootPath,
- accessRules,
- extraAttributes,
- isExported);
- break;
- case IIncludePathEntry.CPE_CONTAINER :
- entry = JavaScriptCore.newContainerEntry(
- path,
- accessRules,
- extraAttributes,
- isExported);
- break;
- case ClasspathEntry.K_OUTPUT :
- if (!path.isAbsolute()) return null;
- entry = new ClasspathEntry(
- ClasspathEntry.K_OUTPUT,
- IIncludePathEntry.CPE_LIBRARY,
- path,
- INCLUDE_ALL,
- EXCLUDE_NONE,
- null, // source attachment
- null, // source attachment root
- null, // custom output location
- false,
- null, // no access rules
- false, // no accessible files to combine
- NO_EXTRA_ATTRIBUTES);
- break;
- default :
- throw new AssertionFailedException(Messages.bind(Messages.classpath_unknownKind, kindAttr));
- }
-
- if (unknownAttributes != null || unknownChildren != null) {
- UnknownXmlElements unknownXmlElements = new UnknownXmlElements();
- unknownXmlElements.attributes = unknownAttributes;
- unknownXmlElements.children = unknownChildren;
- unknownElements.put(path, unknownXmlElements);
- }
-
- return entry;
- }
-
- public static NodeList getChildAttributes(String childName, NodeList children, boolean[] foundChildren) {
- for (int i = 0, length = foundChildren.length; i < length; i++) {
- Node node = children.item(i);
- if (childName.equals(node.getNodeName())) {
- foundChildren[i] = true;
- return node.getChildNodes();
- }
- }
- return null;
- }
-
-
- private static String removeAttribute(String nodeName, NamedNodeMap nodeMap) {
- Node node = removeNode(nodeName, nodeMap);
- if (node == null)
- return ""; // //$NON-NLS-1$
- return node.getNodeValue();
- }
-
- private static Node removeNode(String nodeName, NamedNodeMap nodeMap) {
- try {
- return nodeMap.removeNamedItem(nodeName);
- } catch (DOMException e) {
- if (e.code != DOMException.NOT_FOUND_ERR)
- throw e;
- return null;
- }
- }
-
- /**
- * Encode some patterns into XML parameter tag
- */
- private static void encodePatterns(IPath[] patterns, String tag, Map parameters) {
- if (patterns != null && patterns.length > 0) {
- StringBuffer rule = new StringBuffer(10);
- for (int i = 0, max = patterns.length; i < max; i++){
- if (i > 0) rule.append('|');
- rule.append(patterns[i]);
- }
- parameters.put(tag, String.valueOf(rule));
- }
- }
-
- /**
- * Returns true if the given object is a classpath entry
- * with equivalent attributes.
- */
- public boolean equals(Object object) {
- if (this == object)
- return true;
- if (object instanceof ClasspathEntry) {
- ClasspathEntry otherEntry = (ClasspathEntry) object;
-
- if (this.contentKind != otherEntry.getContentKind())
- return false;
-
- if (this.entryKind != otherEntry.getEntryKind())
- return false;
-
- if (this.isExported != otherEntry.isExported())
- return false;
-
- if (!this.path.equals(otherEntry.getPath()))
- return false;
-
- IPath otherPath = otherEntry.getSourceAttachmentPath();
- if (this.sourceAttachmentPath == null) {
- if (otherPath != null)
- return false;
- } else {
- if (!this.sourceAttachmentPath.equals(otherPath))
- return false;
- }
-
- otherPath = otherEntry.getSourceAttachmentRootPath();
- if (this.sourceAttachmentRootPath == null) {
- if (otherPath != null)
- return false;
- } else {
- if (!this.sourceAttachmentRootPath.equals(otherPath))
- return false;
- }
-
- if (!equalPatterns(this.inclusionPatterns, otherEntry.getInclusionPatterns()))
- return false;
- if (!equalPatterns(this.exclusionPatterns, otherEntry.getExclusionPatterns()))
- return false;
- AccessRuleSet otherRuleSet = otherEntry.getAccessRuleSet();
- if (getAccessRuleSet() != null) {
- if (!getAccessRuleSet().equals(otherRuleSet))
- return false;
- } else if (otherRuleSet != null)
- return false;
- if (this.combineAccessRules != otherEntry.combineAccessRules())
- return false;
- otherPath = otherEntry.getOutputLocation();
- if (this.specificOutputLocation == null) {
- if (otherPath != null)
- return false;
- } else {
- if (!this.specificOutputLocation.equals(otherPath))
- return false;
- }
- if (!equalAttributes(this.extraAttributes, otherEntry.getExtraAttributes()))
- return false;
- return true;
- } else {
- return false;
- }
- }
-
- private static boolean equalAttributes(IIncludePathAttribute[] firstAttributes, IIncludePathAttribute[] secondAttributes) {
- if (firstAttributes != secondAttributes){
- if (firstAttributes == null) return false;
- int length = firstAttributes.length;
- if (secondAttributes == null || secondAttributes.length != length)
- return false;
- for (int i = 0; i < length; i++) {
- if (!firstAttributes[i].equals(secondAttributes[i]))
- return false;
- }
- }
- return true;
- }
-
- private static boolean equalPatterns(IPath[] firstPatterns, IPath[] secondPatterns) {
- if (firstPatterns != secondPatterns){
- if (firstPatterns == null) return false;
- int length = firstPatterns.length;
- if (secondPatterns == null || secondPatterns.length != length)
- return false;
- for (int i = 0; i < length; i++) {
- // compare toStrings instead of IPaths
- // since IPath.equals is specified to ignore trailing separators
- if (!firstPatterns[i].toString().equals(secondPatterns[i].toString()))
- return false;
- }
- }
- return true;
- }
-
- /**
- * @see IIncludePathEntry#getAccessRules()
- */
- public IAccessRule[] getAccessRules() {
- if (this.accessRuleSet == null) return NO_ACCESS_RULES;
- AccessRule[] rules = this.accessRuleSet.getAccessRules();
- int length = rules.length;
- if (length == 0) return NO_ACCESS_RULES;
- IAccessRule[] result = new IAccessRule[length];
- System.arraycopy(rules, 0, result, 0, length);
- return result;
- }
-
- public AccessRuleSet getAccessRuleSet() {
- return this.accessRuleSet;
- }
-
- /**
- * @see IIncludePathEntry
- */
- public int getContentKind() {
- return this.contentKind;
- }
-
- /**
- * @see IIncludePathEntry
- */
- public int getEntryKind() {
- return this.entryKind;
- }
-
- /**
- * @see IIncludePathEntry#getExclusionPatterns()
- */
- public IPath[] getExclusionPatterns() {
- return this.exclusionPatterns;
- }
-
- public IIncludePathAttribute[] getExtraAttributes() {
- return this.extraAttributes;
- }
-
- private String[] getMessageTemplates() {
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- String [] result = new String[AccessRuleSet.MESSAGE_TEMPLATES_LENGTH];
- if (this.entryKind == CPE_PROJECT || this.entryKind == CPE_SOURCE) { // can be remote source entry when reconciling
- result[0] = manager.intern(Messages.bind(
- org.eclipse.wst.jsdt.internal.core.util.Messages.restrictedAccess_project,
- new String[] {"{0}", getPath().segment(0)})); //$NON-NLS-1$
- result[1] = manager.intern(Messages.bind(
- org.eclipse.wst.jsdt.internal.core.util.Messages.restrictedAccess_constructor_project,
- new String[] {"{0}", getPath().segment(0)})); //$NON-NLS-1$
- result[2] = manager.intern(Messages.bind(
- org.eclipse.wst.jsdt.internal.core.util.Messages.restrictedAccess_method_project,
- new String[] {"{0}", "{1}", getPath().segment(0)})); //$NON-NLS-1$ //$NON-NLS-2$
- result[3] = manager.intern(Messages.bind(
- org.eclipse.wst.jsdt.internal.core.util.Messages.restrictedAccess_field_project,
- new String[] {"{0}", "{1}", getPath().segment(0)})); //$NON-NLS-1$ //$NON-NLS-2$
- } else {
- IPath libPath = getPath();
- Object target = JavaModel.getTarget(ResourcesPlugin.getWorkspace().getRoot(), libPath, false);
- String pathString;
- if (target instanceof java.io.File)
- pathString = libPath.toOSString();
- else
- pathString = libPath.makeRelative().toString();
- result[0] = manager.intern(Messages.bind(
- org.eclipse.wst.jsdt.internal.core.util.Messages.restrictedAccess_library,
- new String[] {"{0}", pathString})); //$NON-NLS-1$
- result[1] = manager.intern(Messages.bind(
- org.eclipse.wst.jsdt.internal.core.util.Messages.restrictedAccess_constructor_library,
- new String[] {"{0}", pathString})); //$NON-NLS-1$
- result[2] = manager.intern(Messages.bind(
- org.eclipse.wst.jsdt.internal.core.util.Messages.restrictedAccess_method_library,
- new String[] {"{0}", "{1}", pathString})); //$NON-NLS-1$ //$NON-NLS-2$
- result[3] = manager.intern(Messages.bind(
- org.eclipse.wst.jsdt.internal.core.util.Messages.restrictedAccess_field_library,
- new String[] {"{0}", "{1}", pathString})); //$NON-NLS-1$ //$NON-NLS-2$
- }
- return result;
- }
-
- /**
- * @see IIncludePathEntry#getExclusionPatterns()
- */
- public IPath[] getInclusionPatterns() {
- return this.inclusionPatterns;
- }
-
- /**
- * @see IIncludePathEntry#getOutputLocation()
- */
- public IPath getOutputLocation() {
- return this.specificOutputLocation;
- }
-
- /**
- * @see IIncludePathEntry
- */
- public IPath getPath() {
- return this.path;
- }
-
- /**
- * @see IIncludePathEntry
- */
- public IPath getSourceAttachmentPath() {
- return this.sourceAttachmentPath;
- }
-
- /**
- * @see IIncludePathEntry
- */
- public IPath getSourceAttachmentRootPath() {
- return this.sourceAttachmentRootPath;
- }
-
- /**
- * Returns the hash code for this classpath entry
- */
- public int hashCode() {
- return this.path.hashCode();
- }
-
- /**
- * @see IIncludePathEntry#isExported()
- */
- public boolean isExported() {
- return this.isExported;
- }
-
- public boolean isOptional() {
- for (int i = 0, length = this.extraAttributes.length; i < length; i++) {
- IIncludePathAttribute attribute = this.extraAttributes[i];
- if (IIncludePathAttribute.OPTIONAL.equals(attribute.getName()) && "true".equals(attribute.getValue())) //$NON-NLS-1$
- return true;
- }
- return false;
- }
-
- /**
- * Returns the kind of a <code>PackageFragmentRoot</code> from its <code>String</code> form.
- */
- static int kindFromString(String kindStr) {
-
- if (kindStr.equalsIgnoreCase("prj")) //$NON-NLS-1$
- return IIncludePathEntry.CPE_PROJECT;
- if (kindStr.equalsIgnoreCase("var")) //$NON-NLS-1$
- return IIncludePathEntry.CPE_VARIABLE;
- if (kindStr.equalsIgnoreCase("con")) //$NON-NLS-1$
- return IIncludePathEntry.CPE_CONTAINER;
- if (kindStr.equalsIgnoreCase("src")) //$NON-NLS-1$
- return IIncludePathEntry.CPE_SOURCE;
- if (kindStr.equalsIgnoreCase("lib")) //$NON-NLS-1$
- return IIncludePathEntry.CPE_LIBRARY;
- if (kindStr.equalsIgnoreCase("output")) //$NON-NLS-1$
- return ClasspathEntry.K_OUTPUT;
- return -1;
- }
-
- /**
- * Returns a <code>String</code> for the kind of a class path entry.
- */
- static String kindToString(int kind) {
-
- switch (kind) {
- case IIncludePathEntry.CPE_PROJECT :
- return "src"; // backward compatibility //$NON-NLS-1$
- case IIncludePathEntry.CPE_SOURCE :
- return "src"; //$NON-NLS-1$
- case IIncludePathEntry.CPE_LIBRARY :
- return "lib"; //$NON-NLS-1$
- case IIncludePathEntry.CPE_VARIABLE :
- return "var"; //$NON-NLS-1$
- case IIncludePathEntry.CPE_CONTAINER :
- return "con"; //$NON-NLS-1$
- case ClasspathEntry.K_OUTPUT :
- return "output"; //$NON-NLS-1$
- default :
- return "unknown"; //$NON-NLS-1$
- }
- }
-
- /*
- * Backward compatibility: only accessible and non-accessible files are suported.
- */
- public static IAccessRule[] getAccessRules(IPath[] accessibleFiles, IPath[] nonAccessibleFiles) {
- int accessibleFilesLength = accessibleFiles == null ? 0 : accessibleFiles.length;
- int nonAccessibleFilesLength = nonAccessibleFiles == null ? 0 : nonAccessibleFiles.length;
- int length = accessibleFilesLength + nonAccessibleFilesLength;
- if (length == 0) return null;
- IAccessRule[] accessRules = new IAccessRule[length];
- for (int i = 0; i < accessibleFilesLength; i++) {
- accessRules[i] = JavaScriptCore.newAccessRule(accessibleFiles[i], IAccessRule.K_ACCESSIBLE);
- }
- for (int i = 0; i < nonAccessibleFilesLength; i++) {
- accessRules[accessibleFilesLength + i] = JavaScriptCore.newAccessRule(nonAccessibleFiles[i], IAccessRule.K_NON_ACCESSIBLE);
- }
- return accessRules;
- }
-
- /**
- * Returns a printable representation of this classpath entry.
- */
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- buffer.append(String.valueOf(getPath()));
- buffer.append('[');
- switch (getEntryKind()) {
- case IIncludePathEntry.CPE_LIBRARY :
- buffer.append("CPE_LIBRARY"); //$NON-NLS-1$
- break;
- case IIncludePathEntry.CPE_PROJECT :
- buffer.append("CPE_PROJECT"); //$NON-NLS-1$
- break;
- case IIncludePathEntry.CPE_SOURCE :
- buffer.append("CPE_SOURCE"); //$NON-NLS-1$
- break;
- case IIncludePathEntry.CPE_VARIABLE :
- buffer.append("CPE_VARIABLE"); //$NON-NLS-1$
- break;
- case IIncludePathEntry.CPE_CONTAINER :
- buffer.append("CPE_CONTAINER"); //$NON-NLS-1$
- break;
- }
- buffer.append("]["); //$NON-NLS-1$
- switch (getContentKind()) {
- case IPackageFragmentRoot.K_BINARY :
- buffer.append("K_BINARY"); //$NON-NLS-1$
- break;
- case IPackageFragmentRoot.K_SOURCE :
- buffer.append("K_SOURCE"); //$NON-NLS-1$
- break;
- case ClasspathEntry.K_OUTPUT :
- buffer.append("K_OUTPUT"); //$NON-NLS-1$
- break;
- }
- buffer.append(']');
- if (getSourceAttachmentPath() != null) {
- buffer.append("[sourcePath:"); //$NON-NLS-1$
- buffer.append(getSourceAttachmentPath());
- buffer.append(']');
- }
- if (getSourceAttachmentRootPath() != null) {
- buffer.append("[rootPath:"); //$NON-NLS-1$
- buffer.append(getSourceAttachmentRootPath());
- buffer.append(']');
- }
- buffer.append("[isExported:"); //$NON-NLS-1$
- buffer.append(this.isExported);
- buffer.append(']');
- IPath[] patterns = this.inclusionPatterns;
- int length;
- if ((length = patterns == null ? 0 : patterns.length) > 0) {
- buffer.append("[including:"); //$NON-NLS-1$
- for (int i = 0; i < length; i++) {
- buffer.append(patterns[i]);
- if (i != length-1) {
- buffer.append('|');
- }
- }
- buffer.append(']');
- }
- patterns = this.exclusionPatterns;
- if ((length = patterns == null ? 0 : patterns.length) > 0) {
- buffer.append("[excluding:"); //$NON-NLS-1$
- for (int i = 0; i < length; i++) {
- buffer.append(patterns[i]);
- if (i != length-1) {
- buffer.append('|');
- }
- }
- buffer.append(']');
- }
- if (this.accessRuleSet != null) {
- buffer.append('[');
- buffer.append(this.accessRuleSet.toString(false/*on one line*/));
- buffer.append(']');
- }
- if (this.entryKind == CPE_PROJECT) {
- buffer.append("[combine access rules:"); //$NON-NLS-1$
- buffer.append(this.combineAccessRules);
- buffer.append(']');
- }
- if (getOutputLocation() != null) {
- buffer.append("[output:"); //$NON-NLS-1$
- buffer.append(getOutputLocation());
- buffer.append(']');
- }
- if ((length = this.extraAttributes == null ? 0 : this.extraAttributes.length) > 0) {
- buffer.append("[attributes:"); //$NON-NLS-1$
- for (int i = 0; i < length; i++) {
- buffer.append(this.extraAttributes[i]);
- if (i != length-1) {
- buffer.append(',');
- }
- }
- buffer.append(']');
- }
- return buffer.toString();
- }
-
- /**
- * Answers an ID which is used to distinguish entries during package
- * fragment root computations
- */
- public String rootID(){
-
- if (this.rootID == null) {
- switch(this.entryKind){
- case IIncludePathEntry.CPE_LIBRARY :
- this.rootID = "[LIB]"+this.path; //$NON-NLS-1$
- break;
- case IIncludePathEntry.CPE_PROJECT :
- this.rootID = "[PRJ]"+this.path; //$NON-NLS-1$
- break;
- case IIncludePathEntry.CPE_SOURCE :
- this.rootID = "[SRC]"+this.path; //$NON-NLS-1$
- break;
- case IIncludePathEntry.CPE_VARIABLE :
- this.rootID = "[VAR]"+this.path; //$NON-NLS-1$
- break;
- case IIncludePathEntry.CPE_CONTAINER :
- this.rootID = "[CON]"+this.path; //$NON-NLS-1$
- break;
- default :
- this.rootID = ""; //$NON-NLS-1$
- break;
- }
- }
- return this.rootID;
- }
-
- /**
- * Validate a given classpath for a project, using the following rules:
- * <ul>
- * <li> Classpath entries cannot collide with each other; that is, all entry paths must be unique.
- * <li> A project entry cannot refer to itself directly (that is, a project cannot prerequisite itself).
- * <li> Classpath entries or output locations cannot coincidate or be nested in each other, except for the following scenarii listed below:
- * <ul>
- * <li> A source/library folder can be nested in any source folder as long as the nested folder is excluded from the enclosing one. </li>
- * </ul>
- * </ul>
- *
- * Note that the classpath entries are not validated automatically. Only bound variables or containers are considered
- * in the checking process (this allows to perform a consistency check on a classpath which has references to
- * yet non existing projects, folders, ...).
- * <p>
- * This validation is intended to anticipate classpath issues prior to assigning it to a project. In particular, it will automatically
- * be performed during the classpath setting operation (if validation fails, the classpath setting will not complete).
- * <p>
- * @param javaProject the given java project
- * @param rawClasspath a given classpath
- * @return a status object with code <code>IStatus.OK</code> if
- * the given classpath and output location are compatible, otherwise a status
- * object indicating what is wrong with the classpath or output location
- */
- public static IJavaScriptModelStatus validateClasspath(IJavaScriptProject javaProject, IIncludePathEntry[] rawClasspath) {
-
- IProject project = javaProject.getProject();
- IPath projectPath= project.getFullPath();
- String projectName = javaProject.getElementName();
-
- boolean hasSource = false;
- boolean hasLibFolder = false;
-
-
- // tolerate null path, it will be reset to default
- if (rawClasspath == null)
- return JavaModelStatus.VERIFIED_OK;
-
- // retrieve resolved classpath
- IIncludePathEntry[] classpath;
- try {
- classpath = ((JavaProject)javaProject).resolveClasspath(rawClasspath);
- } catch(JavaScriptModelException e){
- return e.getJavaScriptModelStatus();
- }
- int length = classpath.length;
-
- // retrieve and check output locations
- IPath potentialNestedOutput = null; // for error reporting purpose
- int sourceEntryCount = 0;
- boolean disableExclusionPatterns = JavaScriptCore.DISABLED.equals(javaProject.getOption(JavaScriptCore.CORE_ENABLE_CLASSPATH_EXCLUSION_PATTERNS, true));
- boolean disableCustomOutputLocations = JavaScriptCore.DISABLED.equals(javaProject.getOption(JavaScriptCore.CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS, true));
-
- for (int i = 0 ; i < length; i++) {
- IIncludePathEntry resolvedEntry = classpath[i];
- if (disableExclusionPatterns &&
- ((resolvedEntry.getInclusionPatterns() != null && resolvedEntry.getInclusionPatterns().length > 0)
- || (resolvedEntry.getExclusionPatterns() != null && resolvedEntry.getExclusionPatterns().length > 0))) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.DISABLED_CP_EXCLUSION_PATTERNS, javaProject, resolvedEntry.getPath());
- }
- switch(resolvedEntry.getEntryKind()){
- case IIncludePathEntry.CPE_SOURCE :
- sourceEntryCount++;
- }
- }
-
- for (int i = 0 ; i < length; i++) {
- IIncludePathEntry resolvedEntry = classpath[i];
- IPath path = resolvedEntry.getPath();
- switch(resolvedEntry.getEntryKind()){
-
- case IIncludePathEntry.CPE_SOURCE :
- hasSource = true;
- break;
- case IIncludePathEntry.CPE_LIBRARY:
- hasLibFolder |= !org.eclipse.wst.jsdt.internal.compiler.util.Util.isArchiveFileName(path.lastSegment());
- break;
- }
- }
-
- HashSet pathes = new HashSet(length);
-
- // check all entries
- for (int i = 0 ; i < length; i++) {
- IIncludePathEntry entry = classpath[i];
- if (entry == null) continue;
- IPath entryPath = entry.getPath();
- int kind = entry.getEntryKind();
-
- // Build some common strings for status message
- boolean isProjectRelative = projectName.equals(entryPath.segment(0));
- String entryPathMsg = isProjectRelative ? entryPath.removeFirstSegments(1).toString() : entryPath.makeRelative().toString();
-
- // complain if duplicate path
- if (!pathes.add(entryPath)){
- return new JavaModelStatus(IJavaScriptModelStatusConstants.NAME_COLLISION, Messages.bind(Messages.classpath_duplicateEntryPath, new String[] {entryPathMsg, projectName}));
- }
- // no further check if entry coincidates with project or output location
- if (entryPath.equals(projectPath)){
- // complain if self-referring project entry
- if (kind == IIncludePathEntry.CPE_PROJECT){
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_PATH, Messages.bind(Messages.classpath_cannotReferToItself, entryPath.makeRelative().toString()));
- }
- // tolerate nesting output in src if src==prj
- continue;
- }
-
- // allow nesting source entries in each other as long as the outer entry excludes the inner one
- if (kind == IIncludePathEntry.CPE_SOURCE
- || (kind == IIncludePathEntry.CPE_LIBRARY && !org.eclipse.wst.jsdt.internal.compiler.util.Util.isArchiveFileName(entryPath.lastSegment()))){
- for (int j = 0; j < classpath.length; j++){
- IIncludePathEntry otherEntry = classpath[j];
- if (otherEntry == null) continue;
- int otherKind = otherEntry.getEntryKind();
- IPath otherPath = otherEntry.getPath();
- if (entry != otherEntry
- && (otherKind == IIncludePathEntry.CPE_SOURCE
- || (otherKind == IIncludePathEntry.CPE_LIBRARY
- && !org.eclipse.wst.jsdt.internal.compiler.util.Util.isArchiveFileName(otherPath.lastSegment())))){
- char[][] inclusionPatterns, exclusionPatterns;
- if (otherPath.isPrefixOf(entryPath)
- && !otherPath.equals(entryPath)
- && !Util.isExcluded(entryPath.append("*"), inclusionPatterns = ((ClasspathEntry)otherEntry).fullInclusionPatternChars(), exclusionPatterns = ((ClasspathEntry)otherEntry).fullExclusionPatternChars(), false)) { //$NON-NLS-1$
- String exclusionPattern = entryPath.removeFirstSegments(otherPath.segmentCount()).segment(0);
- if (Util.isExcluded(entryPath, inclusionPatterns, exclusionPatterns, false)) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_INCLUDEPATH, Messages.bind(Messages.classpath_mustEndWithSlash, new String[] {exclusionPattern, entryPath.makeRelative().toString()}));
- } else {
- if (otherKind == IIncludePathEntry.CPE_SOURCE) {
- exclusionPattern += '/';
- if (!disableExclusionPatterns) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_INCLUDEPATH, Messages.bind(Messages.classpath_cannotNestEntryInEntry, new String[] {entryPath.makeRelative().toString(), otherEntry.getPath().makeRelative().toString(), exclusionPattern}));
- } else {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_INCLUDEPATH, Messages.bind(Messages.classpath_cannotNestEntryInEntryNoExclusion, new String[] {entryPath.makeRelative().toString(), otherEntry.getPath().makeRelative().toString(), exclusionPattern}));
- }
- } else {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_INCLUDEPATH, Messages.bind(Messages.classpath_cannotNestEntryInLibrary, new String[] {entryPath.makeRelative().toString(), otherEntry.getPath().makeRelative().toString()}));
- }
- }
- }
- }
- }
- }
-
-// // prevent nesting output location inside entry unless enclosing is a source entry which explicitly exclude the output location
-// char[][] inclusionPatterns = ((ClasspathEntry)entry).fullInclusionPatternChars();
-// char[][] exclusionPatterns = ((ClasspathEntry)entry).fullExclusionPatternChars();
-// for (int j = 0; j < outputCount; j++){
-// IPath currentOutput = outputLocations[j];
-// if (entryPath.equals(currentOutput)) continue;
-// if (entryPath.isPrefixOf(currentOutput)) {
-// if (kind != IIncludePathEntry.CPE_SOURCE || !Util.isExcluded(currentOutput, inclusionPatterns, exclusionPatterns, true)) {
-// return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_INCLUDEPATH, Messages.bind(Messages.classpath_cannotNestOutputInEntry, new String[] {currentOutput.makeRelative().toString(), entryPath.makeRelative().toString()}));
-// }
-// }
-// }
-
- // prevent nesting entry inside output location - when distinct from project or a source folder
-// for (int j = 0; j < outputCount; j++){
-// if (allowNestingInOutputLocations[j]) continue;
-// IPath currentOutput = outputLocations[j];
-// if (currentOutput.isPrefixOf(entryPath)) {
-// return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_INCLUDEPATH, Messages.bind(Messages.classpath_cannotNestEntryInOutput, new String[] {entryPath.makeRelative().toString(), currentOutput.makeRelative().toString()}));
-// }
-// }
- }
- // ensure that no specific output is coincidating with another source folder (only allowed if matching current source folder)
- // 36465 - for 2.0 backward compatibility, only check specific output locations (the default can still coincidate)
- // perform one separate iteration so as to not take precedence over previously checked scenarii (in particular should
- // diagnose nesting source folder issue before this one, for example, [src]"Project/", [src]"Project/source/" and output="Project/" should
- // first complain about missing exclusion pattern
-// for (int i = 0 ; i < length; i++) {
-// IIncludePathEntry entry = classpath[i];
-// if (entry == null) continue;
-// IPath entryPath = entry.getPath();
-// int kind = entry.getEntryKind();
-//
-// // Build some common strings for status message
-// boolean isProjectRelative = projectName.equals(entryPath.segment(0));
-// String entryPathMsg = isProjectRelative ? entryPath.removeFirstSegments(1).toString() : entryPath.makeRelative().toString();
-
-// if (kind == IIncludePathEntry.CPE_SOURCE) {
-// IPath output = entry.getOutputLocation();
-// if (output == null) continue; // 36465 - for 2.0 backward compatibility, only check specific output locations (the default can still coincidate)
-// // if (output == null) output = projectOutputLocation; // if no specific output, still need to check using default output (this line would check default output)
-// for (int j = 0; j < length; j++) {
-// IIncludePathEntry otherEntry = classpath[j];
-// if (otherEntry == entry) continue;
-//
-// // Build some common strings for status message
-// boolean opStartsWithProject = projectName.equals(otherEntry.getPath().segment(0));
-// String otherPathMsg = opStartsWithProject ? otherEntry.getPath().removeFirstSegments(1).toString() : otherEntry.getPath().makeRelative().toString();
-//
-// switch (otherEntry.getEntryKind()) {
-// case IIncludePathEntry.CPE_SOURCE :
-// if (otherEntry.getPath().equals(output)) {
-// return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_INCLUDEPATH, Messages.bind(Messages.classpath_cannotUseDistinctSourceFolderAsOutput, new String[] {entryPathMsg, otherPathMsg, projectName}));
-// }
-// break;
-// case IIncludePathEntry.CPE_LIBRARY :
-// if (otherEntry.getPath().equals(output)) {
-// return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_INCLUDEPATH, Messages.bind(Messages.classpath_cannotUseLibraryAsOutput, new String[] {entryPathMsg, otherPathMsg, projectName}));
-// }
-// }
-// }
-// }
-// }
- return JavaModelStatus.VERIFIED_OK;
- }
-
- /**
- * Returns a Java model status describing the problem related to this classpath entry if any,
- * a status object with code <code>IStatus.OK</code> if the entry is fine (that is, if the
- * given classpath entry denotes a valid element to be referenced onto a classpath).
- *
- * @param project the given java project
- * @param entry the given classpath entry
- * @param checkSourceAttachment a flag to determine if source attachement should be checked
- * @param recurseInContainers flag indicating whether validation should be applied to container entries recursively
- * @return a java model status describing the problem related to this classpath entry if any, a status object with code <code>IStatus.OK</code> if the entry is fine
- */
- public static IJavaScriptModelStatus validateClasspathEntry(IJavaScriptProject project, IIncludePathEntry entry, boolean checkSourceAttachment, boolean recurseInContainers){
-
- IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
- IPath path = entry.getPath();
-
- // Build some common strings for status message
- String projectName = project.getElementName();
- boolean pathStartsWithProject = projectName.equals(path.segment(0));
- String entryPathMsg = pathStartsWithProject ? path.removeFirstSegments(1).makeRelative().toString() : path.toString();
-
- switch(entry.getEntryKind()){
-
- // container entry check
- case IIncludePathEntry.CPE_CONTAINER :
- if (path != null && path.segmentCount() >= 1){
- try {
- IJsGlobalScopeContainer container = JavaModelManager.getJavaModelManager().getJsGlobalScopeContainer(path, project);
- // container retrieval is performing validation check on container entry kinds.
- if (container == null){
- return new JavaModelStatus(IJavaScriptModelStatusConstants.CP_CONTAINER_PATH_UNBOUND, project, path);
- } else if (container == JavaModelManager.CONTAINER_INITIALIZATION_IN_PROGRESS) {
- // Validate extra attributes
- IIncludePathAttribute[] extraAttributes = entry.getExtraAttributes();
- if (extraAttributes != null) {
- int length = extraAttributes.length;
- HashSet set = new HashSet(length);
- for (int i=0; i<length; i++) {
- String attName = extraAttributes[i].getName();
- if (!set.add(attName)) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.NAME_COLLISION, Messages.bind(Messages.classpath_duplicateEntryExtraAttribute, new String[] {attName, entryPathMsg, projectName}));
- }
- }
- }
- // don't create a marker if initialization is in progress (case of cp initialization batching)
- return JavaModelStatus.VERIFIED_OK;
- }
- IIncludePathEntry[] containerEntries = container.getIncludepathEntries();
- if (containerEntries != null){
- for (int i = 0, length = containerEntries.length; i < length; i++){
- IIncludePathEntry containerEntry = containerEntries[i];
- int kind = containerEntry == null ? 0 : containerEntry.getEntryKind();
- if (containerEntry == null
- || kind == IIncludePathEntry.CPE_SOURCE
- || kind == IIncludePathEntry.CPE_VARIABLE
- || kind == IIncludePathEntry.CPE_CONTAINER){
- String description = container.getDescription();
- if (description == null) description = path.makeRelative().toString();
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_CP_CONTAINER_ENTRY, project, path);
- }
- if (recurseInContainers) {
- IJavaScriptModelStatus containerEntryStatus = validateClasspathEntry(project, containerEntry, checkSourceAttachment, recurseInContainers);
- if (!containerEntryStatus.isOK()){
- return containerEntryStatus;
- }
- }
- }
- }
- } catch(JavaScriptModelException e){
- return new JavaModelStatus(e);
- }
- } else {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_INCLUDEPATH, Messages.bind(Messages.classpath_illegalContainerPath, new String[] {entryPathMsg, projectName}));
- }
- break;
-
- // variable entry check
- case IIncludePathEntry.CPE_VARIABLE :
- if (path != null && path.segmentCount() >= 1){
- try {
- entry = JavaScriptCore.getResolvedIncludepathEntry(entry);
- } catch (AssertionFailedException e) {
- // Catch the assertion failure and throw java model exception instead
- // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=55992
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_PATH, e.getMessage());
- }
- if (entry == null){
- return new JavaModelStatus(IJavaScriptModelStatusConstants.CP_VARIABLE_PATH_UNBOUND, project, path);
- }
-
- // get validation status
- IJavaScriptModelStatus status = validateClasspathEntry(project, entry, checkSourceAttachment, recurseInContainers);
- if (!status.isOK()) return status;
-
- // return deprecation status if any
- String variableName = path.segment(0);
- String deprecatedMessage = JavaScriptCore.getIncludepathVariableDeprecationMessage(variableName);
- if (deprecatedMessage != null) {
- return new JavaModelStatus(IStatus.WARNING, IJavaScriptModelStatusConstants.DEPRECATED_VARIABLE, project, path, deprecatedMessage);
- }
- return status;
- } else {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_INCLUDEPATH, Messages.bind(Messages.classpath_illegalVariablePath, new String[] {entryPathMsg, projectName}));
- }
-
- // library entry check
- case IIncludePathEntry.CPE_LIBRARY :
- if (path != null && path.isAbsolute() && !path.isEmpty()) {
- IPath sourceAttachment = entry.getSourceAttachmentPath();
- Object target = JavaModel.getTarget(workspaceRoot, path, true);
-// if (target != null && !JavaScriptCore.IGNORE.equals(project.getOption(JavaScriptCore.CORE_INCOMPATIBLE_JDK_LEVEL, true))) {
-// long projectTargetJDK = CompilerOptions.versionToJdkLevel(project.getOption(JavaScriptCore.COMPILER_CODEGEN_TARGET_PLATFORM, true));
-// long libraryJDK = Util.getJdkLevel(target);
-// if (libraryJDK != 0 && libraryJDK > projectTargetJDK) {
-// return new JavaModelStatus(IJavaScriptModelStatusConstants.INCOMPATIBLE_JDK_LEVEL, project, path, CompilerOptions.versionFromJdkLevel(libraryJDK));
-// }
-// }
- if (target instanceof IResource){
- IResource resolvedResource = (IResource) target;
- switch(resolvedResource.getType()){
- case IResource.FILE :
- if (
- org.eclipse.wst.jsdt.internal.compiler.util.Util.isArchiveFileName(resolvedResource.getName()) ||
- org.eclipse.wst.jsdt.internal.compiler.util.Util.isJavaFileName(resolvedResource.getName())
- ) {
- if (checkSourceAttachment
- && sourceAttachment != null
- && !sourceAttachment.isEmpty()
- && JavaModel.getTarget(workspaceRoot, sourceAttachment, true) == null){
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_INCLUDEPATH, Messages.bind(Messages.classpath_unboundSourceAttachment, new String [] {sourceAttachment.toString(), path.toString(), projectName}));
- }
- } else {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_INCLUDEPATH, Messages.bind(Messages.classpath_illegalLibraryArchive, new String[] {entryPathMsg, projectName}));
- }
- break;
- case IResource.FOLDER : // internal binary folder
- if (checkSourceAttachment
- && sourceAttachment != null
- && !sourceAttachment.isEmpty()
- && JavaModel.getTarget(workspaceRoot, sourceAttachment, true) == null){
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_INCLUDEPATH, Messages.bind(Messages.classpath_unboundSourceAttachment, new String [] {sourceAttachment.toString(), path.toString(), projectName}));
- }
- }
- } else if (target instanceof File){
- File file = JavaModel.getFile(target);
- if (file == null) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_INCLUDEPATH, Messages.bind(Messages.classpath_illegalExternalFolder, new String[] {path.toOSString(), projectName}));
- } else if (!
- (org.eclipse.wst.jsdt.internal.compiler.util.Util.isArchiveFileName(file.getName())
- || org.eclipse.wst.jsdt.internal.compiler.util.Util.isJavaFileName(file.getName()))
- ) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_INCLUDEPATH, Messages.bind(Messages.classpath_illegalLibraryArchive, (new String[] {path.toOSString(), projectName})));
- } else if (checkSourceAttachment
- && sourceAttachment != null
- && !sourceAttachment.isEmpty()
- && JavaModel.getTarget(workspaceRoot, sourceAttachment, true) == null){
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_INCLUDEPATH, Messages.bind(Messages.classpath_unboundSourceAttachment, new String [] {sourceAttachment.toString(), path.toOSString(), projectName}));
- }
- } else {
- boolean isExternal = path.getDevice() != null || !workspaceRoot.getProject(path.segment(0)).exists();
- if (isExternal) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_INCLUDEPATH, Messages.bind(Messages.classpath_unboundLibrary, new String[] {path.toOSString(), projectName}));
- } else {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_INCLUDEPATH, Messages.bind(Messages.classpath_unboundLibrary, new String[] {entryPathMsg, projectName}));
- }
- }
- } else {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_INCLUDEPATH, Messages.bind(Messages.classpath_illegalLibraryPath, new String[] {entryPathMsg, projectName}));
- }
- break;
-
- // project entry check
- case IIncludePathEntry.CPE_PROJECT :
- if (path != null && path.isAbsolute() && path.segmentCount() == 1) {
- IProject prereqProjectRsc = workspaceRoot.getProject(path.segment(0));
- IJavaScriptProject prereqProject = JavaScriptCore.create(prereqProjectRsc);
- try {
- if (!prereqProjectRsc.exists() || !prereqProjectRsc.hasNature(JavaScriptCore.NATURE_ID)){
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_INCLUDEPATH, Messages.bind(Messages.classpath_unboundProject, new String[] {path.segment(0), projectName}));
- }
- if (!prereqProjectRsc.isOpen()){
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_INCLUDEPATH, Messages.bind(Messages.classpath_closedProject, new String[] {path.segment(0)}));
- }
-// if (!JavaScriptCore.IGNORE.equals(project.getOption(JavaScriptCore.CORE_INCOMPATIBLE_JDK_LEVEL, true))) {
-// long projectTargetJDK = CompilerOptions.versionToJdkLevel(project.getOption(JavaScriptCore.COMPILER_CODEGEN_TARGET_PLATFORM, true));
-// long prereqProjectTargetJDK = CompilerOptions.versionToJdkLevel(prereqProject.getOption(JavaScriptCore.COMPILER_CODEGEN_TARGET_PLATFORM, true));
-// if (prereqProjectTargetJDK > projectTargetJDK) {
-// return new JavaModelStatus(IJavaScriptModelStatusConstants.INCOMPATIBLE_JDK_LEVEL, project, path, CompilerOptions.versionFromJdkLevel(prereqProjectTargetJDK));
-// }
-// }
- } catch (CoreException e){
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_INCLUDEPATH, Messages.bind(Messages.classpath_unboundProject, new String[] {path.segment(0), projectName}));
- }
- } else {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_INCLUDEPATH, Messages.bind(Messages.classpath_illegalProjectPath, new String[] {path.toString(), projectName}));
- }
- break;
-
- // project source folder
- case IIncludePathEntry.CPE_SOURCE :
- if (((entry.getInclusionPatterns() != null && entry.getInclusionPatterns().length > 0)
- || (entry.getExclusionPatterns() != null && entry.getExclusionPatterns().length > 0))
- && JavaScriptCore.DISABLED.equals(project.getOption(JavaScriptCore.CORE_ENABLE_CLASSPATH_EXCLUSION_PATTERNS, true))) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.DISABLED_CP_EXCLUSION_PATTERNS, project, path);
- }
-// if (entry.getOutputLocation() != null && JavaScriptCore.DISABLED.equals(project.getOption(JavaScriptCore.CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS, true))) {
-// return new JavaModelStatus(IJavaScriptModelStatusConstants.DISABLED_CP_MULTIPLE_OUTPUT_LOCATIONS, project, path);
-// }
- if (path != null && path.isAbsolute() && !path.isEmpty()) {
- IPath projectPath= project.getProject().getFullPath();
- if (!projectPath.isPrefixOf(path) || JavaModel.getTarget(workspaceRoot, path, true) == null){
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_INCLUDEPATH, Messages.bind(Messages.classpath_unboundSourceFolder, new String[] {entryPathMsg, projectName}));
- }
- } else {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_INCLUDEPATH, Messages.bind(Messages.classpath_illegalSourceFolderPath, new String[] {entryPathMsg, projectName}));
- }
- break;
- }
-
- // Validate extra attributes
- IIncludePathAttribute[] extraAttributes = entry.getExtraAttributes();
- if (extraAttributes != null) {
- int length = extraAttributes.length;
- HashSet set = new HashSet(length);
- for (int i=0; i<length; i++) {
- String attName = extraAttributes[i].getName();
- if (!set.add(attName)) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.NAME_COLLISION, Messages.bind(Messages.classpath_duplicateEntryExtraAttribute, new String[] {attName, entryPathMsg, projectName}));
- }
- }
- }
-
- return JavaModelStatus.VERIFIED_OK;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ClasspathValidation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ClasspathValidation.java
deleted file mode 100644
index 72e291e0..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ClasspathValidation.java
+++ /dev/null
@@ -1,84 +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;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatus;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatusConstants;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.core.builder.JavaBuilder;
-
-/*
- * Validates the raw classpath format and the resolved classpath of this project,
- * updating markers if necessary.
- */
-public class ClasspathValidation {
-
-
- /* Shut OFF classpath validation */
- private static final boolean VALIDATE_CLASSPATH=false;
-
- private JavaProject project;
-
- public ClasspathValidation(JavaProject project) {
- this.project = project;
- }
-
- public void validate() {
- if(!VALIDATE_CLASSPATH) return;
- JavaModelManager.PerProjectInfo perProjectInfo;
- try {
- perProjectInfo = this.project.getPerProjectInfo();
- } catch (JavaScriptModelException e) {
- // project doesn't exist
- IProject resource = this.project.getProject();
- if (resource.isAccessible()) {
- this.project.flushClasspathProblemMarkers(true/*flush cycle markers*/, true/*flush classpath format markers*/);
-
- // remove problems and tasks created by the builder
- JavaBuilder.removeProblemsAndTasksFor(resource);
- }
- return;
- }
-
- // use synchronized block to ensure consistency
- IIncludePathEntry[] rawClasspath;
- IJavaScriptModelStatus status;
- synchronized (perProjectInfo) {
- rawClasspath = perProjectInfo.rawClasspath;
- status = perProjectInfo.rawClasspathStatus; // status has been set during POST_CHANGE
- }
-
- // update classpath format problems
- this.project.flushClasspathProblemMarkers(false/*cycle*/, true/*format*/);
- if (!status.isOK())
- this.project.createClasspathProblemMarker(status);
-
- // update resolved classpath problems
- this.project.flushClasspathProblemMarkers(false/*cycle*/, false/*format*/);
-
- if (rawClasspath != JavaProject.INVALID_CLASSPATH) {
- for (int i = 0; i < rawClasspath.length; i++) {
- status = ClasspathEntry.validateClasspathEntry(this.project, rawClasspath[i], false/*src attach*/, true /*recurse in container*/);
- if (!status.isOK()) {
- if (status.getCode() == IJavaScriptModelStatusConstants.INVALID_INCLUDEPATH && ((ClasspathEntry) rawClasspath[i]).isOptional())
- continue; // ignore this entry
- this.project.createClasspathProblemMarker(status);
- }
- }
- status = ClasspathEntry.validateClasspath(this.project, rawClasspath);
- if (!status.isOK())
- this.project.createClasspathProblemMarker(status);
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CommitWorkingCopyOperation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CommitWorkingCopyOperation.java
deleted file mode 100644
index 7f9efb60..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CommitWorkingCopyOperation.java
+++ /dev/null
@@ -1,221 +0,0 @@
-/*******************************************************************************
- * 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 java.io.ByteArrayInputStream;
-import java.io.UnsupportedEncodingException;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.jobs.ISchedulingRule;
-import org.eclipse.wst.jsdt.core.IBuffer;
-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.JavaScriptCore;
-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;
-
-/**
- * Commits the contents of a working copy compilation
- * unit to its original element and resource, bringing
- * the Java Model up-to-date with the current contents of the working
- * copy.
- *
- * <p>It is possible that the contents of the
- * original resource have changed since the working copy was created,
- * in which case there is an update conflict. This operation allows
- * for two settings to resolve conflict set by the <code>fForce</code> flag:<ul>
- * <li>force flag is <code>false</code> - in this case an <code>JavaScriptModelException</code>
- * is thrown</li>
- * <li>force flag is <code>true</code> - in this case the contents of
- * the working copy are applied to the underlying resource even though
- * the working copy was created before a subsequent change in the
- * resource</li>
- * </ul>
- *
- * <p>The default conflict resolution setting is the force flag is <code>false</code>
- *
- * A JavaModelOperation exception is thrown either if the commit could not
- * be performed or if the new content of the compilation unit violates some Java Model
- * constraint (e.g. if the new package declaration doesn't match the name of the folder
- * containing the compilation unit).
- */
-public class CommitWorkingCopyOperation extends JavaModelOperation {
- /**
- * Constructs an operation to commit the contents of a working copy
- * to its original compilation unit.
- */
- public CommitWorkingCopyOperation(IJavaScriptUnit element, boolean force) {
- super(new IJavaScriptElement[] {element}, force);
- }
- /**
- * @exception JavaScriptModelException if setting the source
- * of the original compilation unit fails
- */
- protected void executeOperation() throws JavaScriptModelException {
- try {
- beginTask(Messages.workingCopy_commit, 2);
- CompilationUnit workingCopy = getCompilationUnit();
-
- if (ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals(workingCopy.getJavaScriptProject().getElementName())) {
- // case of a working copy without a resource
- workingCopy.getBuffer().save(this.progressMonitor, this.force);
- return;
- }
-
- IJavaScriptUnit primary = workingCopy.getPrimary();
- boolean isPrimary = workingCopy.isPrimary();
-
- JavaElementDeltaBuilder deltaBuilder = null;
- PackageFragmentRoot root = (PackageFragmentRoot)workingCopy.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- boolean isIncluded = !Util.isExcluded(workingCopy);
- IFile resource = (IFile)workingCopy.getResource();
- IJavaScriptProject project = root.getJavaScriptProject();
- if (isPrimary || (root.validateOnClasspath().isOK() && isIncluded && resource.isAccessible() && Util.isValidCompilationUnitName(workingCopy.getElementName(), project.getOption(JavaScriptCore.COMPILER_SOURCE, true), project.getOption(JavaScriptCore.COMPILER_COMPLIANCE, true)))) {
-
- // force opening so that the delta builder can get the old info
- if (!isPrimary && !primary.isOpen()) {
- primary.open(null);
- }
-
- // creates the delta builder (this remembers the content of the cu) if:
- // - it is not excluded
- // - and it is not a primary or it is a non-consistent primary
- if (isIncluded && (!isPrimary || !workingCopy.isConsistent())) {
- deltaBuilder = new JavaElementDeltaBuilder(primary);
- }
-
- // save the cu
- IBuffer primaryBuffer = primary.getBuffer();
- if (!isPrimary) {
- if (primaryBuffer == null) return;
- char[] primaryContents = primaryBuffer.getCharacters();
- boolean hasSaved = false;
- try {
- IBuffer workingCopyBuffer = workingCopy.getBuffer();
- if (workingCopyBuffer == null) return;
- primaryBuffer.setContents(workingCopyBuffer.getCharacters());
- primaryBuffer.save(this.progressMonitor, this.force);
- primary.makeConsistent(this);
- hasSaved = true;
- } finally {
- if (!hasSaved){
- // restore original buffer contents since something went wrong
- primaryBuffer.setContents(primaryContents);
- }
- }
- } else {
- // for a primary working copy no need to set the content of the buffer again
- primaryBuffer.save(this.progressMonitor, this.force);
- primary.makeConsistent(this);
- }
- } else {
- // working copy on cu outside classpath OR resource doesn't exist yet
- String encoding = null;
- try {
- encoding = resource.getCharset();
- }
- catch (CoreException ce) {
- // use no encoding
- }
- String contents = workingCopy.getSource();
- if (contents == null) return;
- try {
- byte[] bytes = encoding == null
- ? contents.getBytes()
- : contents.getBytes(encoding);
- ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
- if (resource.exists()) {
- resource.setContents(
- stream,
- this.force ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY,
- null);
- } else {
- resource.create(
- stream,
- this.force,
- this.progressMonitor);
- }
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- } catch (UnsupportedEncodingException e) {
- throw new JavaScriptModelException(e, IJavaScriptModelStatusConstants.IO_EXCEPTION);
- }
-
- }
-
- setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
-
- // make sure working copy is in sync
- workingCopy.updateTimeStamp((CompilationUnit)primary);
- workingCopy.makeConsistent(this);
- worked(1);
-
- // build the deltas
- if (deltaBuilder != null) {
- deltaBuilder.buildDeltas();
-
- // add the deltas to the list of deltas created during this operation
- if (deltaBuilder.delta != null) {
- addDelta(deltaBuilder.delta);
- }
- }
- worked(1);
- } finally {
- done();
- }
- }
- /**
- * Returns the compilation unit this operation is working on.
- */
- protected CompilationUnit getCompilationUnit() {
- return (CompilationUnit)getElementToProcess();
- }
- protected ISchedulingRule getSchedulingRule() {
- IResource resource = getElementToProcess().getResource();
- if (resource == null) return null;
- IWorkspace workspace = resource.getWorkspace();
- if (resource.exists()) {
- return workspace.getRuleFactory().modifyRule(resource);
- } else {
- return workspace.getRuleFactory().createRule(resource);
- }
- }
- /**
- * Possible failures: <ul>
- * <li>INVALID_ELEMENT_TYPES - the compilation unit supplied to this
- * operation is not a working copy
- * <li>ELEMENT_NOT_PRESENT - the compilation unit the working copy is
- * based on no longer exists.
- * <li>UPDATE_CONFLICT - the original compilation unit has changed since
- * the working copy was created and the operation specifies no force
- * <li>READ_ONLY - the original compilation unit is in read-only mode
- * </ul>
- */
- public IJavaScriptModelStatus verify() {
- CompilationUnit cu = getCompilationUnit();
- if (!cu.isWorkingCopy()) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_ELEMENT_TYPES, cu);
- }
- if (cu.hasResourceChanged() && !this.force) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.UPDATE_CONFLICT);
- }
- // no read-only check, since some repository adapters can change the flag on save
- // operation.
- return JavaModelStatus.VERIFIED_OK;
- }
-}
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
deleted file mode 100644
index 5cbe7762..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CompilationUnit.java
+++ /dev/null
@@ -1,1404 +0,0 @@
-/*******************************************************************************
- * 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
- * Alex Smirnoff (alexsmr@sympatico.ca) - part of the changes to support Java-like extension
- * (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=71460)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core;
-
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.PerformanceStats;
-import org.eclipse.wst.jsdt.core.CompletionRequestor;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IBuffer;
-import org.eclipse.wst.jsdt.core.IBufferFactory;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IImportContainer;
-import org.eclipse.wst.jsdt.core.IImportDeclaration;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-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.IMember;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IProblemRequestor;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeRoot;
-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.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;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.internal.compiler.IProblemFactory;
-import org.eclipse.wst.jsdt.internal.compiler.SourceElementParser;
-import org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.impl.CompilerOptions;
-import org.eclipse.wst.jsdt.internal.compiler.problem.DefaultProblemFactory;
-import org.eclipse.wst.jsdt.internal.compiler.util.SuffixConstants;
-import org.eclipse.wst.jsdt.internal.core.util.MementoTokenizer;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * @see IJavaScriptUnit
- */
-public class CompilationUnit extends Openable implements IJavaScriptUnit, org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit, SuffixConstants, IVirtualParent {
- /**
- * Internal synonynm for deprecated constant AST.JSL2
- * to alleviate deprecation warnings.
- * @deprecated
- */
- /*package*/ static final int JLS2_INTERNAL = AST.JLS2;
-
- private static final IImportDeclaration[] NO_IMPORTS = new IImportDeclaration[0];
- protected String name;
- public WorkingCopyOwner owner;
- public String superTypeName;
-
-/**
- * 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();
- }
-
- 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);
-
-// 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();
- }
- // 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();
- }
- } 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();
- }
- }
-
- 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$
- }
- 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];
-}
-/**
- * @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;
- }
-
- }
- if (currentElement != null && currentElement.exists()) {
- return new IJavaScriptElement[] {currentElement};
- } else {
- return 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();
- } 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;
-}
-/**
- * @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();
- }
-}
-/**
- * @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;
-}
-/**
- * @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);
- 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;
-}
-
-/**
- * @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;
-}
-/**
- * @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;
- }
-
- 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);
- 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);
- }
- 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 {
- 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));
- }
- }
-
- // 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();
- }
- 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);
- } else {
- 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());
- }
- 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();
- for (int i = 0, length = methods.length; i < length; i++) {
- IFunction existingMethod = methods[i];
- if (elementName.equals(existingMethod.getElementName()))
- {
- list.add(existingMethod);
- }
- }
- } catch (JavaScriptModelException e) {
- }
- int size = list.size();
- if (size == 0) {
- 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;
-}
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CompilationUnitElementInfo.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CompilationUnitElementInfo.java
deleted file mode 100644
index 3c6ab913..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CompilationUnitElementInfo.java
+++ /dev/null
@@ -1,66 +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;
-
-import java.util.HashMap;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-
-public class CompilationUnitElementInfo extends OpenableElementInfo {
-
- /**
- * The length of this compilation unit's source code <code>String</code>
- */
- protected int sourceLength;
-
- /**
- * Timestamp of original resource at the time this element
- * was opened or last updated.
- */
- protected long timestamp;
-
- /*
- * A map from an IJavaScriptElement (this type or a child of this type) to a String[] (the categories of this element)
- */
- protected HashMap categories;
-
-protected void addCategories(IJavaScriptElement element, char[][] elementCategories) {
- if (elementCategories == null) return;
- if (this.categories == null)
- this.categories = new HashMap();
- this.categories.put(element, CharOperation.toStrings(elementCategories));
-}
-
-/*
- * Return a map from an IJavaScriptElement (this type or a child of this type) to a String[] (the categories of this element)
- */
-public HashMap getCategories() {
- return this.categories;
-}
-
-/**
- * Returns the length of the source string.
- */
-public int getSourceLength() {
- return this.sourceLength;
-}
-protected ISourceRange getSourceRange() {
- return new SourceRange(0, this.sourceLength);
-}
-/**
- * Sets the length of the source string.
- */
-public void setSourceLength(int newSourceLength) {
- this.sourceLength = newSourceLength;
-}
-}
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
deleted file mode 100644
index 75534301..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CompilationUnitProblemFinder.java
+++ /dev/null
@@ -1,345 +0,0 @@
-/*******************************************************************************
- * 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;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelMarker;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatusConstants;
-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.internal.compiler.CompilationResult;
-import org.eclipse.wst.jsdt.internal.compiler.Compiler;
-import org.eclipse.wst.jsdt.internal.compiler.DefaultErrorHandlingPolicies;
-import org.eclipse.wst.jsdt.internal.compiler.ICompilerRequestor;
-import org.eclipse.wst.jsdt.internal.compiler.IErrorHandlingPolicy;
-import org.eclipse.wst.jsdt.internal.compiler.IProblemFactory;
-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.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;
-import org.eclipse.wst.jsdt.internal.compiler.impl.ITypeRequestor2;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding;
-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.AbortCompilationUnit;
-import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfObject;
-import org.eclipse.wst.jsdt.internal.compiler.util.Messages;
-import org.eclipse.wst.jsdt.internal.core.search.IRestrictedAccessBindingRequestor;
-import org.eclipse.wst.jsdt.internal.core.util.CommentRecorderParser;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * Responsible for resolving types inside a compilation unit being reconciled,
- * reporting the discovered problems to a given IProblemRequestor.
- */
-public class CompilationUnitProblemFinder extends Compiler implements ITypeRequestor2 {
-
- /**
- * Answer a new CompilationUnitVisitor using the given name environment and compiler options.
- * The environment and options will be in effect for the lifetime of the compiler.
- * When the compiler is run, compilation results are sent to the given requestor.
- *
- * @param environment org.eclipse.wst.jsdt.internal.compiler.api.env.INameEnvironment
- * Environment used by the compiler in order to resolve type and package
- * names. The name environment implements the actual connection of the compiler
- * to the outside world (e.g. in batch mode the name environment is performing
- * pure file accesses, reuse previous build state or connection to repositories).
- * Note: the name environment is responsible for implementing the actual classpath
- * rules.
- *
- * @param policy org.eclipse.wst.jsdt.internal.compiler.api.problem.IErrorHandlingPolicy
- * Configurable part for problem handling, allowing the compiler client to
- * specify the rules for handling problems (stop on first error or accumulate
- * them all) and at the same time perform some actions such as opening a dialog
- * in UI when compiling interactively.
- * @see org.eclipse.wst.jsdt.internal.compiler.DefaultErrorHandlingPolicies
- *
- * @param compilerOptions The compiler options to use for the resolution.
- *
- * @param requestor org.eclipse.wst.jsdt.internal.compiler.api.ICompilerRequestor
- * Component which will receive and persist all compilation results and is intended
- * to consume them as they are produced. Typically, in a batch compiler, it is
- * responsible for writing out the actual .class files to the file system.
- * @see org.eclipse.wst.jsdt.internal.compiler.CompilationResult
- *
- * @param problemFactory org.eclipse.wst.jsdt.internal.compiler.api.problem.IProblemFactory
- * Factory used inside the compiler to create problem descriptors. It allows the
- * compiler client to supply its own representation of compilation problems in
- * order to avoid object conversions. Note that the factory is not supposed
- * to accumulate the created problems, the compiler will gather them all and hand
- * them back as part of the compilation unit result.
- */
- protected CompilationUnitProblemFinder(
- INameEnvironment environment,
- IErrorHandlingPolicy policy,
- CompilerOptions compilerOptions,
- ICompilerRequestor requestor,
- IProblemFactory problemFactory) {
-
- super(environment,
- policy,
- compilerOptions,
- requestor,
- problemFactory
- );
- }
-
- /**
- * Add additional source types
- */
- public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding, AccessRestriction accessRestriction) {
- // ensure to jump back to toplevel type for first one (could be a member)
-// while (sourceTypes[0].getEnclosingType() != null)
-// sourceTypes[0] = sourceTypes[0].getEnclosingType();
-
- CompilationResult result =
- new CompilationResult(sourceTypes[0].getFileName(), sourceTypes[0].getPackageName(), 1, 1, this.options.maxProblemsPerUnit);
-
- // need to hold onto this
- CompilationUnitDeclaration unit =
- SourceTypeConverter.buildCompilationUnit(
- sourceTypes,//sourceTypes[0] is always toplevel here
- SourceTypeConverter.FIELD_AND_METHOD // need field and methods
- | SourceTypeConverter.MEMBER_TYPE // need member types
- | SourceTypeConverter.FIELD_INITIALIZATION, // need field initialization
- this.lookupEnvironment.problemReporter,
- result);
-
- if (unit != null) {
- this.lookupEnvironment.buildTypeBindings(unit, accessRestriction);
- this.lookupEnvironment.completeTypeBindings(unit);
- }
- }
-
-
- /**
- * Add an additional compilation unit into the loop
- * -> 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);
- }
-
- 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, 1, 1, this.options.maxProblemsPerUnit);
- 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);
- }
- 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
- }
- }
-
- }
-
-
- protected static CompilerOptions getCompilerOptions(Map settings, boolean creatingAST, boolean statementsRecovery) {
- CompilerOptions compilerOptions = new CompilerOptions(settings);
- compilerOptions.performMethodsFullRecovery = statementsRecovery;
- compilerOptions.performStatementsRecovery = statementsRecovery;
- compilerOptions.parseLiteralExpressionsAsConstants = !creatingAST; /*parse literal expressions as constants only if not creating a DOM AST*/
- compilerOptions.storeAnnotations = creatingAST; /*store annotations in the bindings if creating a DOM AST*/
- return compilerOptions;
- }
-
- /*
- * Low-level API performing the actual compilation
- */
- protected static IErrorHandlingPolicy getHandlingPolicy() {
- return DefaultErrorHandlingPolicies.proceedWithAllProblems();
- }
-
- /*
- * Answer the component to which will be handed back compilation results from the compiler
- */
- protected static ICompilerRequestor getRequestor() {
- return new ICompilerRequestor() {
- public void acceptResult(CompilationResult compilationResult) {
- // default requestor doesn't handle compilation results back
- }
- };
- }
-
- public static CompilationUnitDeclaration process(
- CompilationUnitDeclaration unit,
- IJavaScriptUnit unitElement,
- char[] contents,
- Parser parser,
- WorkingCopyOwner workingCopyOwner,
- HashMap problems,
- boolean creatingAST,
- int reconcileFlags,
- IProgressMonitor monitor)
- throws JavaScriptModelException {
-
- JavaProject project = (JavaProject) unitElement.getJavaScriptProject();
- CancelableNameEnvironment environment = null;
- CancelableProblemFactory problemFactory = null;
- CompilationUnitProblemFinder problemFinder = null;
- try {
- IRestrictedAccessBindingRequestor accessRequestor = null;
- if(unitElement.getParent().getParent() instanceof DocumentContextFragmentRoot) {
- accessRequestor = ((DocumentContextFragmentRoot)unitElement.getParent().getParent()).getRestrictedAccessRequestor();
- }
- environment = new CancelableNameEnvironment(project, accessRequestor, workingCopyOwner, monitor);
-
-
- if (unitElement instanceof CompilationUnit)
- {
- environment.unitToSkip=(CompilationUnit)unitElement;
- environment.setCompilationUnit(environment.unitToSkip);
- }
- else if (unitElement instanceof CompilationUnit)
- environment.unitToSkip=(CompilationUnit)unitElement;
- problemFactory = new CancelableProblemFactory(monitor);
- problemFinder = new CompilationUnitProblemFinder(
- environment,
- getHandlingPolicy(),
- getCompilerOptions(project.getOptions(true), creatingAST, ((reconcileFlags & IJavaScriptUnit.ENABLE_STATEMENTS_RECOVERY) != 0)),
- getRequestor(),
- problemFactory);
- if (parser != null) {
- problemFinder.parser = parser;
- }
- PackageFragment packageFragment = (PackageFragment)unitElement.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT);
- char[][] expectedPackageName = null;
- if (packageFragment != null){
- expectedPackageName = Util.toCharArrays(packageFragment.names);
- }
- if (unit == null) {
- unit = problemFinder.resolve(
- new BasicCompilationUnit(
- contents,
- expectedPackageName,
- unitElement.getPath().toString(),
- unitElement),
- true, // verify methods
- true, // analyze code
- true); // generate code
- } else {
- problemFinder.resolve(
- unit,
- null, // no need for source
- true, // verify methods
- true, // analyze code
- true); // generate code
- }
- CompilationResult unitResult = unit.compilationResult;
- CategorizedProblem[] unitProblems = unitResult.getProblems();
- int length = unitProblems == null ? 0 : unitProblems.length;
- if (length > 0) {
- CategorizedProblem[] categorizedProblems = new CategorizedProblem[length];
- System.arraycopy(unitProblems, 0, categorizedProblems, 0, length);
- problems.put(IJavaScriptModelMarker.JAVASCRIPT_MODEL_PROBLEM_MARKER, categorizedProblems);
- }
- unitProblems = unitResult.getTasks();
- length = unitProblems == null ? 0 : unitProblems.length;
- if (length > 0) {
- CategorizedProblem[] categorizedProblems = new CategorizedProblem[length];
- System.arraycopy(unitProblems, 0, categorizedProblems, 0, length);
- problems.put(IJavaScriptModelMarker.TASK_MARKER, categorizedProblems);
- }
- 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 unit;
- } catch (OperationCanceledException e) {
- throw e;
- } catch(RuntimeException e) {
- // avoid breaking other tools due to internal compiler failure (40334)
- String lineDelimiter = unitElement.findRecommendedLineSeparator();
- StringBuffer message = new StringBuffer("Exception occurred during problem detection:"); //$NON-NLS-1$
- message.append(lineDelimiter);
- message.append("----------------------------------- SOURCE BEGIN -------------------------------------"); //$NON-NLS-1$
- message.append(lineDelimiter);
- message.append(contents);
- message.append(lineDelimiter);
- message.append("----------------------------------- SOURCE END -------------------------------------"); //$NON-NLS-1$
- Util.log(e, message.toString());
- throw new JavaScriptModelException(e, IJavaScriptModelStatusConstants.VALIDATION_FAILURE);
- } finally {
- if (environment != null)
- environment.monitor = null; // don't hold a reference to this external object
- if (problemFactory != null)
- problemFactory.monitor = null; // don't hold a reference to this external object
- // NB: unit.cleanUp() is done by caller
- if (problemFinder != null )//&& !creatingAST)
- problemFinder.lookupEnvironment.reset();
- }
- }
-
- public static CompilationUnitDeclaration process(
- IJavaScriptUnit unitElement,
- char[] contents,
- WorkingCopyOwner workingCopyOwner,
- HashMap problems,
- boolean creatingAST,
- int reconcileFlags,
- IProgressMonitor monitor)
- throws JavaScriptModelException {
-
- return process(null/*no CompilationUnitDeclaration*/, unitElement, contents, null/*use default Parser*/, workingCopyOwner, problems, creatingAST, reconcileFlags, monitor);
- }
-
- /* (non-Javadoc)
- * Fix for bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=60689.
- * @see org.eclipse.wst.jsdt.internal.compiler.Compiler#initializeParser()
- */
- public void initializeParser() {
- this.parser = new CommentRecorderParser(this.problemReporter, this.options.parseLiteralExpressionsAsConstants);
- }
-}
-
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
deleted file mode 100644
index 96a231b8..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CompilationUnitStructureRequestor.java
+++ /dev/null
@@ -1,453 +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;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Stack;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-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.internal.compiler.ISourceElementRequestor;
-import org.eclipse.wst.jsdt.internal.compiler.parser.Parser;
-import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfObject;
-import org.eclipse.wst.jsdt.internal.core.util.ReferenceInfoAdapter;
-
-/**
- * A requestor for the fuzzy parser, used to compute the children of an IJavaScriptUnit.
- */
-public class CompilationUnitStructureRequestor extends ReferenceInfoAdapter implements ISourceElementRequestor {
-
- /**
- * The handle to the compilation unit being parsed
- */
- protected IJavaScriptElement unit;
-
- /**
- * The info object for the compilation unit being parsed
- */
- protected CompilationUnitElementInfo unitInfo;
-
- /**
- * The import container info - null until created
- */
- protected JavaElementInfo importContainerInfo = null;
-
- /**
- * Hashtable of children elements of the compilation unit.
- * Children are added to the table as they are found by
- * the parser. Keys are handles, values are corresponding
- * info objects.
- */
- protected Map newElements;
-
- /**
- * Stack of parent scope info objects. The info on the
- * top of the stack is the parent of the next element found.
- * For example, when we locate a method, the parent info object
- * will be the type the method is contained in.
- */
- protected Stack infoStack;
-
- /*
- * Map from JavaElementInfo to of ArrayList of IJavaScriptElement representing the children
- * of the given info.
- */
- protected HashMap children;
-
- /**
- * Stack of parent handles, corresponding to the info stack. We
- * keep both, since info objects do not have back pointers to
- * handles.
- */
- protected Stack handleStack;
-
- /**
- * The number of references reported thus far. Used to
- * expand the arrays of reference kinds and names.
- */
- protected int referenceCount= 0;
-
- /**
- * Problem requestor which will get notified of discovered problems
- */
- protected boolean hasSyntaxErrors = false;
-
- /*
- * The parser this requestor is using.
- */
- protected Parser parser;
-
- /**
- * Empty collections used for efficient initialization
- */
- protected static byte[] NO_BYTES= new byte[]{};
-
- protected HashtableOfObject fieldRefCache;
- protected HashtableOfObject messageRefCache;
- protected HashtableOfObject typeRefCache;
- protected HashtableOfObject unknownRefCache;
-
-protected CompilationUnitStructureRequestor(IJavaScriptElement unit, CompilationUnitElementInfo unitInfo, Map newElements) {
- this.unit = unit;
- this.unitInfo = unitInfo;
- this.newElements = newElements;
-}
-/**
- * @see ISourceElementRequestor
- */
-public void acceptImport(int declarationStart, int declarationEnd, char[][] tokens, boolean onDemand) {
- JavaElement parentHandle= (JavaElement) this.handleStack.peek();
- if (!(parentHandle.getElementType() == IJavaScriptElement.JAVASCRIPT_UNIT)) {
- Assert.isTrue(false); // Should not happen
- }
-
- IJavaScriptUnit parentCU= (IJavaScriptUnit)parentHandle;
- //create the import container and its info
- ImportContainer importContainer= (ImportContainer)parentCU.getImportContainer();
- if (this.importContainerInfo == null) {
- this.importContainerInfo = new JavaElementInfo();
- JavaElementInfo parentInfo = (JavaElementInfo) this.infoStack.peek();
- addToChildren(parentInfo, importContainer);
- this.newElements.put(importContainer, this.importContainerInfo);
- }
-
- String elementName = JavaModelManager.getJavaModelManager().intern(new String(CharOperation.concatWith(tokens, '.')));
- ImportDeclaration handle = new ImportDeclaration(importContainer, elementName, onDemand);
- resolveDuplicates(handle);
-
- ImportDeclarationElementInfo info = new ImportDeclarationElementInfo();
- info.setSourceRangeStart(declarationStart);
- info.setSourceRangeEnd(declarationEnd);
-
- addToChildren(this.importContainerInfo, handle);
- this.newElements.put(handle, info);
-}
-/*
- * Table of line separator position. This table is passed once at the end
- * of the parse action, so as to allow computation of normalized ranges.
- *
- * A line separator might corresponds to several characters in the source,
- *
- */
-public void acceptLineSeparatorPositions(int[] positions) {
- // ignore line separator positions
-}
-public void acceptProblem(CategorizedProblem problem) {
- if ((problem.getID() & IProblem.Syntax) != 0){
- this.hasSyntaxErrors = true;
- }
-}
-private void addToChildren(JavaElementInfo parentInfo, JavaElement handle) {
- ArrayList childrenList = (ArrayList) this.children.get(parentInfo);
- if (childrenList == null)
- this.children.put(parentInfo, childrenList = new ArrayList());
- childrenList.add(handle);
-}
-/**
- * Convert these type names to signatures.
- * @see Signature
- */
-/* default */ static String[] convertTypeNamesToSigs(char[][] typeNames) {
- if (typeNames == null)
- return CharOperation.NO_STRINGS;
- int n = typeNames.length;
- if (n == 0)
- return CharOperation.NO_STRINGS;
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- String[] typeSigs = new String[n];
- for (int i = 0; i < n; ++i) {
- typeSigs[i] = manager.intern(Signature.createTypeSignature(typeNames[i], false));
- }
- return typeSigs;
-}
-/**
- * @see ISourceElementRequestor
- */
-public void enterCompilationUnit() {
- this.infoStack = new Stack();
- this.children = new HashMap();
- this.handleStack= new Stack();
- this.infoStack.push(this.unitInfo);
- this.handleStack.push(this.unit);
-}
-/**
- * @see ISourceElementRequestor
- */
-public void enterConstructor(MethodInfo methodInfo) {
- enterMethod(methodInfo);
-}
-/**
- * @see ISourceElementRequestor
- */
-public void enterField(FieldInfo fieldInfo) {
-
- JavaElementInfo parentInfo = (JavaElementInfo) this.infoStack.peek();
- JavaElement parentHandle= (JavaElement) this.handleStack.peek();
- SourceField handle = null;
- if (parentHandle.getElementType() == IJavaScriptElement.TYPE
- || parentHandle.getElementType() == IJavaScriptElement.JAVASCRIPT_UNIT
- || parentHandle.getElementType() == IJavaScriptElement.CLASS_FILE
- || parentHandle.getElementType() == IJavaScriptElement.METHOD
- ) {
- String fieldName = JavaModelManager.getJavaModelManager().intern(new String(fieldInfo.name));
- handle = new SourceField(parentHandle, fieldName);
- }
- else {
- Assert.isTrue(false); // Should not happen
- }
- resolveDuplicates(handle);
-
- SourceFieldElementInfo info = new SourceFieldElementInfo();
- info.setNameSourceStart(fieldInfo.nameSourceStart);
- info.setNameSourceEnd(fieldInfo.nameSourceEnd);
- info.setSourceRangeStart(fieldInfo.declarationStart);
- info.setFlags(fieldInfo.modifiers);
- if (fieldInfo.type!=null)
- {
- char[] typeName = JavaModelManager.getJavaModelManager().intern(fieldInfo.type);
- info.setTypeName(typeName);
- }
-
- addToChildren(parentInfo, handle);
- if (parentInfo instanceof CompilationUnitElementInfo) {
- CompilationUnitElementInfo compilationUnitInfo = (CompilationUnitElementInfo) parentInfo;
- compilationUnitInfo.addCategories(handle, fieldInfo.categories);
- }
- this.newElements.put(handle, info);
-
- this.infoStack.push(info);
- this.handleStack.push(handle);
-}
-/**
- * @see ISourceElementRequestor
- */
-public void enterInitializer(
- int declarationSourceStart,
- int modifiers) {
- JavaElementInfo parentInfo = (JavaElementInfo) this.infoStack.peek();
- JavaElement parentHandle= (JavaElement) this.handleStack.peek();
- Initializer handle = null;
-
- if (parentHandle.getElementType() == IJavaScriptElement.TYPE) {
- handle = new Initializer(parentHandle, 1);
- }
- else {
- Assert.isTrue(false); // Should not happen
- }
- resolveDuplicates(handle);
-
- InitializerElementInfo info = new InitializerElementInfo();
- info.setSourceRangeStart(declarationSourceStart);
- info.setFlags(modifiers);
-
- addToChildren(parentInfo, handle);
- this.newElements.put(handle, info);
-
- this.infoStack.push(info);
- this.handleStack.push(handle);
-}
-/**
- * @see ISourceElementRequestor
- */
-public void enterMethod(MethodInfo methodInfo) {
-
- JavaElementInfo parentInfo = (JavaElementInfo) this.infoStack.peek();
- JavaElement parentHandle= (JavaElement) this.handleStack.peek();
- SourceMethod handle = null;
-
- // translate nulls to empty arrays
- if (methodInfo.parameterTypes == null) {
- methodInfo.parameterTypes= CharOperation.NO_CHAR_CHAR;
- }
- if (methodInfo.parameterNames == null) {
- methodInfo.parameterNames= CharOperation.NO_CHAR_CHAR;
- }
-
- String[] parameterTypeSigs = convertTypeNamesToSigs(methodInfo.parameterTypes);
- if (parentHandle.getElementType() == IJavaScriptElement.TYPE
- || parentHandle.getElementType() == IJavaScriptElement.JAVASCRIPT_UNIT
- || parentHandle.getElementType() == IJavaScriptElement.CLASS_FILE
- || parentHandle.getElementType() == IJavaScriptElement.METHOD
- ) {
-
- char[] cs = methodInfo.name!=null ? methodInfo.name: CharOperation.NO_CHAR;
-
- String selector = JavaModelManager.getJavaModelManager().intern(new String(cs));
- handle = new SourceMethod(parentHandle, selector, parameterTypeSigs);
- }
- else {
- Assert.isTrue(false); // Should not happen
- }
- resolveDuplicates(handle);
-
- SourceMethodElementInfo info;
- if (methodInfo.isConstructor)
- info = new SourceConstructorInfo();
- else
- info = new SourceMethodInfo();
- info.setSourceRangeStart(methodInfo.declarationStart);
- int flags = methodInfo.modifiers;
- info.setNameSourceStart(methodInfo.nameSourceStart);
- info.setNameSourceEnd(methodInfo.nameSourceEnd);
- info.setFlags(flags);
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- char[][] parameterNames = methodInfo.parameterNames;
- for (int i = 0, length = parameterNames.length; i < length; i++)
- parameterNames[i] = manager.intern(parameterNames[i]);
- info.setArgumentNames(parameterNames);
- char[] returnType = methodInfo.returnType == null ? null : manager.intern(methodInfo.returnType);
- info.setReturnType(returnType);
- addToChildren(parentInfo, handle);
- if (parentInfo instanceof CompilationUnitElementInfo) {
- CompilationUnitElementInfo compilationUnitInfo = (CompilationUnitElementInfo) parentInfo;
- compilationUnitInfo.addCategories(handle, methodInfo.categories);
- }
- this.newElements.put(handle, info);
- this.infoStack.push(info);
- this.handleStack.push(handle);
-}
-/**
- * @see ISourceElementRequestor
- */
-public void enterType(TypeInfo typeInfo) {
-
- JavaElementInfo parentInfo = (JavaElementInfo) this.infoStack.peek();
- JavaElement parentHandle= (JavaElement) this.handleStack.peek();
- String nameString= new String(typeInfo.name);
-
- //@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
-
- resolveDuplicates(handle);
-
- SourceTypeElementInfo info =
-// typeInfo.anonymousMember ?
-// new SourceTypeElementInfo( parentHandle instanceof ClassFile ) {
-// public boolean isAnonymousMember() {
-// return true;
-// }
-// } :
- new SourceTypeElementInfo( parentHandle instanceof ClassFile , typeInfo.anonymousMember);
- info.setHandle(handle);
- info.setSourceRangeStart(typeInfo.declarationStart);
- info.setFlags(typeInfo.modifiers);
- info.setNameSourceStart(typeInfo.nameSourceStart);
- info.setNameSourceEnd(typeInfo.nameSourceEnd);
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- char[] superclass = typeInfo.superclass;
- info.setSuperclassName(superclass == null ? null : manager.intern(superclass));
- info.addCategories(handle, typeInfo.categories);
- if (parentHandle.getElementType() == IJavaScriptElement.TYPE)
- ((SourceTypeElementInfo) parentInfo).addCategories(handle, typeInfo.categories);
- addToChildren(parentInfo, handle);
- this.newElements.put(handle, info);
- this.infoStack.push(info);
- this.handleStack.push(handle);
-}
-/**
- * @see ISourceElementRequestor
- */
-public void exitCompilationUnit(int declarationEnd) {
- // set import container children
- if (this.importContainerInfo != null) {
- setChildren(this.importContainerInfo);
- }
-
- // set children
- setChildren(this.unitInfo);
-
- this.unitInfo.setSourceLength(declarationEnd + 1);
-
- // determine if there were any parsing errors
- this.unitInfo.setIsStructureKnown(!this.hasSyntaxErrors);
-}
-/**
- * @see ISourceElementRequestor
- */
-public void exitConstructor(int declarationEnd) {
- exitMember(declarationEnd);
-}
-/**
- * @see ISourceElementRequestor
- */
-public void exitField(int initializationStart, int declarationEnd, int declarationSourceEnd) {
- SourceFieldElementInfo info = (SourceFieldElementInfo) this.infoStack.pop();
- info.setSourceRangeEnd(declarationSourceEnd);
- setChildren(info);
-
- this.handleStack.pop();
-}
-/**
- * @see ISourceElementRequestor
- */
-public void exitInitializer(int declarationEnd) {
- exitMember(declarationEnd);
-}
-/**
- * common processing for classes and interfaces
- */
-protected void exitMember(int declarationEnd) {
- SourceRefElementInfo info = (SourceRefElementInfo) this.infoStack.pop();
- info.setSourceRangeEnd(declarationEnd);
- setChildren(info);
- this.handleStack.pop();
-}
-/**
- * @see ISourceElementRequestor
- */
-public void exitMethod(int declarationEnd, int defaultValueStart, int defaultValueEnd) {
- SourceMethodElementInfo info = (SourceMethodElementInfo) this.infoStack.pop();
- info.setSourceRangeEnd(declarationEnd);
- setChildren(info);
- this.handleStack.pop();
-}
-/**
- * @see ISourceElementRequestor
- */
-public void exitType(int declarationEnd) {
-
- exitMember(declarationEnd);
-}
-/**
- * Resolves duplicate handles by incrementing the occurrence count
- * of the handle being created until there is no conflict.
- */
-protected void resolveDuplicates(SourceRefElement handle) {
- while (this.newElements.containsKey(handle)) {
- handle.occurrenceCount++;
- }
-}
-private void setChildren(JavaElementInfo info) {
- ArrayList childrenList = (ArrayList) this.children.get(info);
- if (childrenList != null) {
- int length = childrenList.size();
- IJavaScriptElement[] elements = new IJavaScriptElement[length];
- childrenList.toArray(elements);
- info.children = elements;
- }
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CopyElementsOperation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CopyElementsOperation.java
deleted file mode 100644
index 7e7ff207..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CopyElementsOperation.java
+++ /dev/null
@@ -1,262 +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;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.wst.jsdt.core.IImportDeclaration;
-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.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IParent;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.compiler.util.SuffixConstants;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-
-/**
- * This operation copies/moves a collection of elements from their current
- * container to a new container, optionally renaming the
- * elements.
- * <p>Notes:<ul>
- * <li>If there is already an element with the same name in
- * the new container, the operation either overwrites or aborts,
- * depending on the collision policy setting. The default setting is
- * abort.
- *
- * <li>When constructors are copied to a type, the constructors
- * are automatically renamed to the name of the destination
- * type.
- *
- * <li>When main types are renamed (move within the same parent),
- * the compilation unit and constructors are automatically renamed
- *
- * <li>The collection of elements being copied must all share the
- * same type of container (for example, must all be type members).
- *
- * <li>The elements are inserted in the new container in the order given.
- *
- * <li>The elements can be positioned in the new container - see #setInsertBefore.
- * By default, the elements are inserted based on the default positions as specified in
- * the creation operation for that element type.
- *
- * <li>This operation can be used to copy and rename elements within
- * the same container.
- *
- * <li>This operation only copies elements contained within compilation units.
- * </ul>
- *
- */
-public class CopyElementsOperation extends MultiOperation implements SuffixConstants {
-
-
- private Map sources = new HashMap();
-/**
- * When executed, this operation will copy the given elements to the
- * given containers. The elements and destination containers must be in
- * the correct order. If there is > 1 destination, the number of destinations
- * must be the same as the number of elements being copied/moved/renamed.
- */
-public CopyElementsOperation(IJavaScriptElement[] elementsToCopy, IJavaScriptElement[] destContainers, boolean force) {
- super(elementsToCopy, destContainers, force);
-}
-/**
- * When executed, this operation will copy the given elements to the
- * given container.
- */
-public CopyElementsOperation(IJavaScriptElement[] elementsToCopy, IJavaScriptElement destContainer, boolean force) {
- this(elementsToCopy, new IJavaScriptElement[]{destContainer}, force);
-}
-/**
- * Returns the <code>String</code> to use as the main task name
- * for progress monitoring.
- */
-protected String getMainTaskName() {
- return Messages.operation_copyElementProgress;
-}
-/**
- * Returns the nested operation to use for processing this element
- */
-protected JavaModelOperation getNestedOperation(IJavaScriptElement element) {
- try {
- IJavaScriptElement dest = getDestinationParent(element);
- switch (element.getElementType()) {
- case IJavaScriptElement.IMPORT_DECLARATION :
- IImportDeclaration importDeclaration = (IImportDeclaration) element;
- return new CreateImportOperation(element.getElementName(), (IJavaScriptUnit) dest, importDeclaration.getFlags());
- case IJavaScriptElement.TYPE :
- if (isRenamingMainType(element, dest)) {
- IPath path = element.getPath();
- String extension = path.getFileExtension();
- return new RenameResourceElementsOperation(new IJavaScriptElement[] {dest}, new IJavaScriptElement[] {dest.getParent()}, new String[]{getNewNameFor(element) + '.' + extension}, this.force);
- } else {
- String source = getSourceFor(element);
- String lineSeparator = org.eclipse.wst.jsdt.internal.core.util.Util.getLineSeparator(source, element.getJavaScriptProject());
- return new CreateTypeOperation(dest, source + lineSeparator, this.force);
- }
- case IJavaScriptElement.METHOD :
- String source = getSourceFor(element);
- String lineSeparator = org.eclipse.wst.jsdt.internal.core.util.Util.getLineSeparator(source, element.getJavaScriptProject());
- return new CreateMethodOperation(dest, source + lineSeparator, this.force);
- case IJavaScriptElement.FIELD :
- source = getSourceFor(element);
- lineSeparator = org.eclipse.wst.jsdt.internal.core.util.Util.getLineSeparator(source, element.getJavaScriptProject());
- return new CreateFieldOperation(dest, source + lineSeparator, this.force);
- default :
- return null;
- }
- } catch (JavaScriptModelException npe) {
- return null;
- }
-}
-/**
- * Returns the cached source for this element or compute it if not already cached.
- */
-private String getSourceFor(IJavaScriptElement element) throws JavaScriptModelException {
- String source = (String) this.sources.get(element);
- if (source == null && element instanceof IMember) {
- source = ((IMember)element).getSource();
- this.sources.put(element, source);
- }
- return source;
-}
-/**
- * Returns <code>true</code> if this element is the main type of its compilation unit.
- */
-protected boolean isRenamingMainType(IJavaScriptElement element, IJavaScriptElement dest) throws JavaScriptModelException {
- if ((isRename() || getNewNameFor(element) != null)
- && dest.getElementType() == IJavaScriptElement.JAVASCRIPT_UNIT) {
- String typeName = dest.getElementName();
- typeName = org.eclipse.wst.jsdt.internal.core.util.Util.getNameWithoutJavaLikeExtension(typeName);
- return element.getElementName().equals(typeName) && element.getParent().equals(dest);
- }
- return false;
-}
-/**
- * Copy/move the element from the source to destination, renaming
- * the elements as specified, honoring the collision policy.
- *
- * @exception JavaScriptModelException if the operation is unable to
- * be completed
- */
-protected void processElement(IJavaScriptElement element) throws JavaScriptModelException {
- JavaModelOperation op = getNestedOperation(element);
- boolean createElementInCUOperation =op instanceof CreateElementInCUOperation;
- if (op == null) {
- return;
- }
- if (createElementInCUOperation) {
- IJavaScriptElement sibling = (IJavaScriptElement) this.insertBeforeElements.get(element);
- if (sibling != null) {
- ((CreateElementInCUOperation) op).setRelativePosition(sibling, CreateElementInCUOperation.INSERT_BEFORE);
- } else
- if (isRename()) {
- IJavaScriptElement anchor = resolveRenameAnchor(element);
- if (anchor != null) {
- ((CreateElementInCUOperation) op).setRelativePosition(anchor, CreateElementInCUOperation.INSERT_AFTER); // insert after so that the anchor is found before when deleted below
- }
- }
- String newName = getNewNameFor(element);
- if (newName != null) {
- ((CreateElementInCUOperation) op).setAlteredName(newName);
- }
- }
- executeNestedOperation(op, 1);
-
- JavaElement destination = (JavaElement) getDestinationParent(element);
- IJavaScriptUnit unit= destination.getJavaScriptUnit();
- if (!unit.isWorkingCopy()) {
- unit.close();
- }
-
- if (createElementInCUOperation && isMove() && !isRenamingMainType(element, destination)) {
- DeleteElementsOperation deleteOp = new DeleteElementsOperation(new IJavaScriptElement[] { element }, this.force);
- executeNestedOperation(deleteOp, 1);
- }
-}
-/**
- * Returns the anchor used for positioning in the destination for
- * the element being renamed. For renaming, if no anchor has
- * explicitly been provided, the element is anchored in the same position.
- */
-private IJavaScriptElement resolveRenameAnchor(IJavaScriptElement element) throws JavaScriptModelException {
- IParent parent = (IParent) element.getParent();
- IJavaScriptElement[] children = parent.getChildren();
- for (int i = 0; i < children.length; i++) {
- IJavaScriptElement child = children[i];
- if (child.equals(element)) {
- return child;
- }
- }
- return null;
-}
-/**
- * Possible failures:
- * <ul>
- * <li>NO_ELEMENTS_TO_PROCESS - no elements supplied to the operation
- * <li>INDEX_OUT_OF_BOUNDS - the number of renamings supplied to the operation
- * does not match the number of elements that were supplied.
- * </ul>
- */
-protected IJavaScriptModelStatus verify() {
- IJavaScriptModelStatus status = super.verify();
- if (!status.isOK()) {
- return status;
- }
- if (this.renamingsList != null && this.renamingsList.length != this.elementsToProcess.length) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INDEX_OUT_OF_BOUNDS);
- }
- return JavaModelStatus.VERIFIED_OK;
-}
-/**
- * @see MultiOperation
- *
- * Possible failure codes:
- * <ul>
- *
- * <li>ELEMENT_DOES_NOT_EXIST - <code>element</code> or its specified destination is
- * is <code>null</code> or does not exist. If a <code>null</code> element is
- * supplied, no element is provided in the status, otherwise, the non-existant element
- * is supplied in the status.
- * <li>INVALID_ELEMENT_TYPES - <code>element</code> is not contained within a compilation unit.
- * This operation only operates on elements contained within compilation units.
- * <li>READ_ONLY - <code>element</code> is read only.
- * <li>INVALID_DESTINATION - The destination parent specified for <code>element</code>
- * is of an incompatible type. The destination for a package declaration or import declaration must
- * be a compilation unit; the destination for a type must be a type or compilation
- * unit; the destinaion for any type member (other than a type) must be a type. When
- * this error occurs, the element provided in the operation status is the <code>element</code>.
- * <li>INVALID_NAME - the new name for <code>element</code> does not have valid syntax.
- * In this case the element and name are provided in the status.
-
- * </ul>
- */
-protected void verify(IJavaScriptElement element) throws JavaScriptModelException {
- if (element == null || !element.exists())
- error(IJavaScriptModelStatusConstants.ELEMENT_DOES_NOT_EXIST, element);
-
- if (element.getElementType() < IJavaScriptElement.TYPE)
- error(IJavaScriptModelStatusConstants.INVALID_ELEMENT_TYPES, element);
-
- if (element.isReadOnly())
- error(IJavaScriptModelStatusConstants.READ_ONLY, element);
-
- IJavaScriptElement dest = getDestinationParent(element);
- verifyDestination(element, dest);
- verifySibling(element, dest);
- if (this.renamingsList != null) {
- verifyRenaming(element);
- }
-}
-}
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
deleted file mode 100644
index e5dd1889..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CopyPackageFragmentRootOperation.java
+++ /dev/null
@@ -1,274 +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;
-
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceProxy;
-import org.eclipse.core.resources.IResourceProxyVisitor;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.AssertionFailedException;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-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.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-
-public class CopyPackageFragmentRootOperation extends JavaModelOperation {
- IPath destination;
- int updateResourceFlags;
- int updateModelFlags;
- IIncludePathEntry sibling;
-
- public CopyPackageFragmentRootOperation(
- IPackageFragmentRoot root,
- IPath destination,
- int updateResourceFlags,
- int updateModelFlags,
- IIncludePathEntry sibling) {
-
- super(root);
- this.destination = destination;
- this.updateResourceFlags = updateResourceFlags;
- this.updateModelFlags = updateModelFlags;
- this.sibling = sibling;
- }
- protected void executeOperation() throws JavaScriptModelException {
-
- IPackageFragmentRoot root = (IPackageFragmentRoot)this.getElementToProcess();
- IIncludePathEntry rootEntry = root.getRawIncludepathEntry();
- IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
-
- // copy resource
- if (!root.isExternal() && (this.updateModelFlags & IPackageFragmentRoot.NO_RESOURCE_MODIFICATION) == 0) {
- copyResource(root, rootEntry, workspaceRoot);
- }
-
- // update classpath if needed
- if ((this.updateModelFlags & IPackageFragmentRoot.DESTINATION_PROJECT_INCLUDEPATH) != 0) {
- addEntryToClasspath(rootEntry, workspaceRoot);
- }
- }
- protected void copyResource(
- IPackageFragmentRoot root,
- IIncludePathEntry rootEntry,
- final IWorkspaceRoot workspaceRoot)
- throws JavaScriptModelException {
- final char[][] exclusionPatterns = ((ClasspathEntry)rootEntry).fullExclusionPatternChars();
- IResource rootResource = root.getResource();
- if (root.getKind() == IPackageFragmentRoot.K_BINARY || exclusionPatterns == null) {
- try {
- IResource destRes;
- if ((this.updateModelFlags & IPackageFragmentRoot.REPLACE) != 0) {
- if (rootEntry.getPath().equals(this.destination)) return;
- if ((destRes = workspaceRoot.findMember(this.destination)) != null) {
- destRes.delete(this.updateResourceFlags, progressMonitor);
- }
- }
- rootResource.copy(this.destination, this.updateResourceFlags, progressMonitor);
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- }
- } else {
- final int sourceSegmentCount = rootEntry.getPath().segmentCount();
- final IFolder destFolder = workspaceRoot.getFolder(this.destination);
- final IPath[] nestedFolders = getNestedFolders(root);
- IResourceProxyVisitor visitor = new IResourceProxyVisitor() {
- public boolean visit(IResourceProxy proxy) throws CoreException {
- if (proxy.getType() == IResource.FOLDER) {
- IPath path = proxy.requestFullPath();
- if (prefixesOneOf(path, nestedFolders)) {
- if (equalsOneOf(path, nestedFolders)) {
- // nested source folder
- return false;
- } else {
- // folder containing nested source folder
- IFolder folder = destFolder.getFolder(path.removeFirstSegments(sourceSegmentCount));
- if ((updateModelFlags & IPackageFragmentRoot.REPLACE) != 0
- && folder.exists()) {
- return true;
- }
- folder.create(updateResourceFlags, true, progressMonitor);
- return true;
- }
- } else {
- // subtree doesn't contain any nested source folders
- IPath destPath = destination.append(path.removeFirstSegments(sourceSegmentCount));
- IResource destRes;
- if ((updateModelFlags & IPackageFragmentRoot.REPLACE) != 0
- && (destRes = workspaceRoot.findMember(destPath)) != null) {
- destRes.delete(updateResourceFlags, progressMonitor);
- }
- proxy.requestResource().copy(destPath, updateResourceFlags, progressMonitor);
- return false;
- }
- } else {
- IPath path = proxy.requestFullPath();
- IPath destPath = destination.append(path.removeFirstSegments(sourceSegmentCount));
- IResource destRes;
- if ((updateModelFlags & IPackageFragmentRoot.REPLACE) != 0
- && (destRes = workspaceRoot.findMember(destPath)) != null) {
- destRes.delete(updateResourceFlags, progressMonitor);
- }
- proxy.requestResource().copy(destPath, updateResourceFlags, progressMonitor);
- return false;
- }
- }
- };
- try {
- rootResource.accept(visitor, IResource.NONE);
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- }
- }
- setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
- }
- protected void addEntryToClasspath(IIncludePathEntry rootEntry, IWorkspaceRoot workspaceRoot) throws JavaScriptModelException {
-
- IProject destProject = workspaceRoot.getProject(this.destination.segment(0));
- IJavaScriptProject jProject = JavaScriptCore.create(destProject);
- IIncludePathEntry[] classpath = jProject.getRawIncludepath();
- int length = classpath.length;
- IIncludePathEntry[] newClasspath;
-
- // case of existing entry and REPLACE was specified
- if ((this.updateModelFlags & IPackageFragmentRoot.REPLACE) != 0) {
- // find existing entry
- for (int i = 0; i < length; i++) {
- if (this.destination.equals(classpath[i].getPath())) {
- newClasspath = new IIncludePathEntry[length];
- System.arraycopy(classpath, 0, newClasspath, 0, length);
- newClasspath[i] = copy(rootEntry);
- jProject.setRawIncludepath(newClasspath, progressMonitor);
- return;
- }
- }
- }
-
- // other cases
- int position;
- if (this.sibling == null) {
- // insert at the end
- position = length;
- } else {
- // insert before sibling
- position = -1;
- for (int i = 0; i < length; i++) {
- if (this.sibling.equals(classpath[i])) {
- position = i;
- break;
- }
- }
- }
- if (position == -1) {
- throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_SIBLING, this.sibling.toString()));
- }
- newClasspath = new IIncludePathEntry[length+1];
- if (position != 0) {
- System.arraycopy(classpath, 0, newClasspath, 0, position);
- }
- if (position != length) {
- System.arraycopy(classpath, position, newClasspath, position+1, length-position);
- }
- IIncludePathEntry newEntry = copy(rootEntry);
- newClasspath[position] = newEntry;
- jProject.setRawIncludepath(newClasspath, progressMonitor);
- }
- /*
- * Copies the given classpath entry replacing its path with the destination path
- * if it is a source folder or a library.
- */
- protected IIncludePathEntry copy(IIncludePathEntry entry) throws JavaScriptModelException {
- switch (entry.getEntryKind()) {
- case IIncludePathEntry.CPE_CONTAINER:
- return JavaScriptCore.newContainerEntry(entry.getPath(), entry.getAccessRules(), entry.getExtraAttributes(), entry.isExported());
- case IIncludePathEntry.CPE_LIBRARY:
- try {
- return JavaScriptCore.newLibraryEntry(this.destination, entry.getSourceAttachmentPath(), entry.getSourceAttachmentRootPath(), entry.getAccessRules(), entry.getExtraAttributes(), entry.isExported());
- } catch (AssertionFailedException e) {
- IJavaScriptModelStatus status = new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_PATH, e.getMessage());
- throw new JavaScriptModelException(status);
- }
- case IIncludePathEntry.CPE_PROJECT:
- return JavaScriptCore.newProjectEntry(entry.getPath(), entry.getAccessRules(), entry.combineAccessRules(), entry.getExtraAttributes(), entry.isExported());
- case IIncludePathEntry.CPE_SOURCE:
- return JavaScriptCore.newSourceEntry(this.destination, entry.getInclusionPatterns(), entry.getExclusionPatterns(), null, entry.getExtraAttributes());
- case IIncludePathEntry.CPE_VARIABLE:
- try {
- return JavaScriptCore.newVariableEntry(entry.getPath(), entry.getSourceAttachmentPath(), entry.getSourceAttachmentRootPath(), entry.getAccessRules(), entry.getExtraAttributes(), entry.isExported());
- } catch (AssertionFailedException e) {
- IJavaScriptModelStatus status = new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_PATH, e.getMessage());
- throw new JavaScriptModelException(status);
- }
- default:
- throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.ELEMENT_DOES_NOT_EXIST, this.getElementToProcess()));
- }
- }
- public IJavaScriptModelStatus verify() {
- IJavaScriptModelStatus status = super.verify();
- if (!status.isOK()) {
- return status;
- }
- IPackageFragmentRoot root = (IPackageFragmentRoot)getElementToProcess();
- if (root == null || !root.exists()) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.ELEMENT_DOES_NOT_EXIST, root);
- }
-
- IResource resource = root.getResource();
- if (resource instanceof IFolder) {
- if (resource.isLinked()) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_RESOURCE, root);
- }
- }
-
- if ((this.updateModelFlags & IPackageFragmentRoot.DESTINATION_PROJECT_INCLUDEPATH) != 0) {
- String destProjectName = this.destination.segment(0);
- IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(destProjectName);
- if (JavaProject.hasJavaNature(project)) {
- try {
- IJavaScriptProject destProject = JavaScriptCore.create(project);
- IIncludePathEntry[] destClasspath = destProject.getRawIncludepath();
- boolean foundSibling = false;
- boolean foundExistingEntry = false;
- for (int i = 0, length = destClasspath.length; i < length; i++) {
- IIncludePathEntry entry = destClasspath[i];
- if (entry.equals(this.sibling)) {
- foundSibling = true;
- break;
- }
- if (entry.getPath().equals(this.destination)) {
- foundExistingEntry = true;
- }
- }
- if (this.sibling != null && !foundSibling) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_SIBLING, this.sibling.toString());
- }
- if (foundExistingEntry && (this.updateModelFlags & IPackageFragmentRoot.REPLACE) == 0) {
- return new JavaModelStatus(
- IJavaScriptModelStatusConstants.NAME_COLLISION,
- Messages.bind(Messages.status_nameCollision, new String[] {this.destination.toString()}));
- }
- } catch (JavaScriptModelException e) {
- return e.getJavaScriptModelStatus();
- }
- }
- }
-
- return JavaModelStatus.VERIFIED_OK;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CopyResourceElementsOperation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CopyResourceElementsOperation.java
deleted file mode 100644
index a21755bc..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CopyResourceElementsOperation.java
+++ /dev/null
@@ -1,724 +0,0 @@
-/*******************************************************************************
- * 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 java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptElementDelta;
-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.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.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.PackageDeclaration;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.internal.compiler.util.SuffixConstants;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * This operation copies/moves/renames a collection of resources from their current
- * container to a new container, optionally renaming the
- * elements.
- * <p>Notes:<ul>
- * <li>If there is already an resource with the same name in
- * the new container, the operation either overwrites or aborts,
- * depending on the collision policy setting. The default setting is
- * abort.
- *
- * <li>When a compilation unit is copied to a new package, the
- * package declaration in the compilation unit is automatically updated.
- *
- * <li>The collection of elements being copied must all share the
- * same type of container.
- *
- * <li>This operation can be used to copy and rename elements within
- * the same container.
- *
- * <li>This operation only copies compilation units and package fragments.
- * It does not copy package fragment roots - a platform operation must be used for that.
- * </ul>
- *
- */
-public class CopyResourceElementsOperation extends MultiOperation implements SuffixConstants {
- /**
- * The list of new resources created during this operation.
- */
- protected ArrayList createdElements;
- /**
- * Table specifying deltas for elements being
- * copied/moved/renamed. Keyed by elements' project(s), and
- * values are the corresponding deltas.
- */
- protected Map deltasPerProject = new HashMap(1);
- /**
- * The <code>ASTParser</code> used to manipulate the source code of
- * <code>IJavaScriptUnit</code>.
- */
- protected ASTParser parser;
- /**
- * When executed, this operation will copy the given resources to the
- * given container.
- */
- public CopyResourceElementsOperation(IJavaScriptElement[] resourcesToCopy, IJavaScriptElement destContainer, boolean force) {
- this(resourcesToCopy, new IJavaScriptElement[]{destContainer}, force);
- }
- /**
- * When executed, this operation will copy the given resources to the
- * given containers. The resources and destination containers must be in
- * the correct order. If there is > 1 destination, the number of destinations
- * must be the same as the number of resources being copied/moved.
- */
- public CopyResourceElementsOperation(IJavaScriptElement[] resourcesToCopy, IJavaScriptElement[] destContainers, boolean force) {
- super(resourcesToCopy, destContainers, force);
- initializeASTParser();
- }
- private void initializeASTParser() {
- this.parser = ASTParser.newParser(AST.JLS3);
- }
- /**
- * Returns the children of <code>source</code> which are affected by this operation.
- * If <code>source</code> is a <code>K_SOURCE</code>, these are the <code>.java</code>
- * files, if it is a <code>K_BINARY</code>, they are the <code>.class</code> files.
- */
- private IResource[] collectResourcesOfInterest(IPackageFragment source) throws JavaScriptModelException {
- IJavaScriptElement[] children = source.getChildren();
- int childOfInterest = IJavaScriptElement.JAVASCRIPT_UNIT;
- if (source.getKind() == IPackageFragmentRoot.K_BINARY) {
- childOfInterest = IJavaScriptElement.CLASS_FILE;
- }
- ArrayList correctKindChildren = new ArrayList(children.length);
- for (int i = 0; i < children.length; i++) {
- IJavaScriptElement child = children[i];
- if (child.getElementType() == childOfInterest) {
- correctKindChildren.add(child.getResource());
- }
- }
- // Gather non-java resources
- Object[] nonJavaResources = source.getNonJavaScriptResources();
- int actualNonJavaResourceCount = 0;
- for (int i = 0, max = nonJavaResources.length; i < max; i++){
- if (nonJavaResources[i] instanceof IResource) actualNonJavaResourceCount++;
- }
- IResource[] actualNonJavaResources = new IResource[actualNonJavaResourceCount];
- for (int i = 0, max = nonJavaResources.length, index = 0; i < max; i++){
- if (nonJavaResources[i] instanceof IResource) actualNonJavaResources[index++] = (IResource)nonJavaResources[i];
- }
-
- if (actualNonJavaResourceCount != 0) {
- int correctKindChildrenSize = correctKindChildren.size();
- IResource[] result = new IResource[correctKindChildrenSize + actualNonJavaResourceCount];
- correctKindChildren.toArray(result);
- System.arraycopy(actualNonJavaResources, 0, result, correctKindChildrenSize, actualNonJavaResourceCount);
- return result;
- } else {
- IResource[] result = new IResource[correctKindChildren.size()];
- correctKindChildren.toArray(result);
- return result;
- }
- }
- /**
- * Creates any destination package fragment(s) which do not exists yet.
- * Return true if a read-only package fragment has been found among package fragments, false otherwise
- */
- private boolean createNeededPackageFragments(IContainer sourceFolder, PackageFragmentRoot root, String[] newFragName, boolean moveFolder) throws JavaScriptModelException {
- boolean containsReadOnlyPackageFragment = false;
- IContainer parentFolder = (IContainer) root.getResource();
- JavaElementDelta projectDelta = null;
- String[] sideEffectPackageName = null;
- char[][] inclusionPatterns = root.fullInclusionPatternChars();
- char[][] exclusionPatterns = root.fullExclusionPatternChars();
- for (int i = 0; i < newFragName.length; i++) {
- String subFolderName = newFragName[i];
- sideEffectPackageName = Util.arrayConcat(sideEffectPackageName, subFolderName);
- IResource subFolder = parentFolder.findMember(subFolderName);
- if (subFolder == null) {
- // create deepest folder only if not a move (folder will be moved in processPackageFragmentResource)
- if (!(moveFolder && i == newFragName.length-1)) {
- createFolder(parentFolder, subFolderName, force);
- }
- parentFolder = parentFolder.getFolder(new Path(subFolderName));
- sourceFolder = sourceFolder.getFolder(new Path(subFolderName));
- if (Util.isReadOnly(sourceFolder)) {
- containsReadOnlyPackageFragment = true;
- }
- IPackageFragment sideEffectPackage = root.getPackageFragment(sideEffectPackageName);
- if (i < newFragName.length - 1 // all but the last one are side effect packages
- && !Util.isExcluded(parentFolder, inclusionPatterns, exclusionPatterns)) {
- if (projectDelta == null) {
- projectDelta = getDeltaFor(root.getJavaScriptProject());
- }
- projectDelta.added(sideEffectPackage);
- }
- createdElements.add(sideEffectPackage);
- } else {
- parentFolder = (IContainer) subFolder;
- }
- }
- return containsReadOnlyPackageFragment;
- }
-
- /**
- * Returns the <code>JavaElementDelta</code> for <code>javaProject</code>,
- * creating it and putting it in <code>fDeltasPerProject</code> if
- * it does not exist yet.
- */
- private JavaElementDelta getDeltaFor(IJavaScriptProject javaProject) {
- JavaElementDelta delta = (JavaElementDelta) deltasPerProject.get(javaProject);
- if (delta == null) {
- delta = new JavaElementDelta(javaProject);
- deltasPerProject.put(javaProject, delta);
- }
- return delta;
- }
- /**
- * @see MultiOperation
- */
- protected String getMainTaskName() {
- return Messages.operation_copyResourceProgress;
- }
- /**
- * Sets the deltas to register the changes resulting from this operation
- * for this source element and its destination.
- * If the operation is a cross project operation<ul>
- * <li>On a copy, the delta should be rooted in the dest project
- * <li>On a move, two deltas are generated<ul>
- * <li>one rooted in the source project
- * <li>one rooted in the destination project</ul></ul>
- * If the operation is rooted in a single project, the delta is rooted in that project
- *
- */
- protected void prepareDeltas(IJavaScriptElement sourceElement, IJavaScriptElement destinationElement, boolean isMove) {
- if (Util.isExcluded(sourceElement) || Util.isExcluded(destinationElement)) return;
- IJavaScriptProject destProject = destinationElement.getJavaScriptProject();
- if (isMove) {
- IJavaScriptProject sourceProject = sourceElement.getJavaScriptProject();
- getDeltaFor(sourceProject).movedFrom(sourceElement, destinationElement);
- getDeltaFor(destProject).movedTo(destinationElement, sourceElement);
- } else {
- getDeltaFor(destProject).added(destinationElement);
- }
- }
- /**
- * Copies/moves a compilation unit with the name <code>newCUName</code>
- * to the destination package.<br>
- * The package statement in the compilation unit is updated if necessary.
- * The main type of the compilation unit is renamed if necessary.
- *
- * @exception JavaScriptModelException if the operation is unable to
- * complete
- */
- private void processCompilationUnitResource(IJavaScriptUnit source, PackageFragment dest) throws JavaScriptModelException {
- String newCUName = getNewNameFor(source);
- String destName = (newCUName != null) ? newCUName : source.getElementName();
- ASTRewrite rewrite = updateContent(source, dest, newCUName); // null if unchanged
-
- // TODO (frederic) remove when bug 67606 will be fixed (bug 67823)
- // store encoding (fix bug 66898)
- IFile sourceResource = (IFile)source.getResource();
- String sourceEncoding = null;
- try {
- sourceEncoding = sourceResource.getCharset(false);
- }
- catch (CoreException ce) {
- // no problem, use default encoding
- }
- // end todo
- // copy resource
- IContainer destFolder = (IContainer)dest.getResource(); // can be an IFolder or an IProject
- IFile destFile = destFolder.getFile(new Path(destName));
- org.eclipse.wst.jsdt.internal.core.CompilationUnit destCU = new org.eclipse.wst.jsdt.internal.core.CompilationUnit(dest, destName, DefaultWorkingCopyOwner.PRIMARY);
- if (!destFile.equals(sourceResource)) {
- try {
- if (!destCU.isWorkingCopy()) {
- if (destFile.exists()) {
- if (this.force) {
- // we can remove it
- deleteResource(destFile, IResource.KEEP_HISTORY);
- destCU.close(); // ensure the in-memory buffer for the dest CU is closed
- } else {
- // abort
- throw new JavaScriptModelException(new JavaModelStatus(
- IJavaScriptModelStatusConstants.NAME_COLLISION,
- Messages.bind(Messages.status_nameCollision, destFile.getFullPath().toString())));
- }
- }
- int flags = this.force ? IResource.FORCE : IResource.NONE;
- if (this.isMove()) {
- flags |= IResource.KEEP_HISTORY;
- sourceResource.move(destFile.getFullPath(), flags, getSubProgressMonitor(1));
- } else {
- if (rewrite != null) flags |= IResource.KEEP_HISTORY;
- sourceResource.copy(destFile.getFullPath(), flags, getSubProgressMonitor(1));
- }
- setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
- } else {
- destCU.getBuffer().setContents(source.getBuffer().getContents());
- }
- } catch (JavaScriptModelException e) {
- throw e;
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- }
-
- // update new resource content
- if (rewrite != null){
- boolean wasReadOnly = destFile.isReadOnly();
- try {
- saveContent(dest, destName, rewrite, sourceEncoding, destFile);
- } catch (CoreException e) {
- if (e instanceof JavaScriptModelException) throw (JavaScriptModelException) e;
- throw new JavaScriptModelException(e);
- } finally {
- Util.setReadOnly(destFile, wasReadOnly);
- }
- }
-
- // register the correct change deltas
- prepareDeltas(source, destCU, isMove());
- if (newCUName != null) {
- //the main type has been renamed
- String oldName = Util.getNameWithoutJavaLikeExtension(source.getElementName());
- String newName = Util.getNameWithoutJavaLikeExtension(newCUName);
- prepareDeltas(source.getType(oldName), destCU.getType(newName), isMove());
- }
- } else {
- if (!this.force) {
- throw new JavaScriptModelException(new JavaModelStatus(
- IJavaScriptModelStatusConstants.NAME_COLLISION,
- Messages.bind(Messages.status_nameCollision, destFile.getFullPath().toString())));
- }
- // update new resource content
- // in case we do a saveas on the same resource we have to simply update the contents
- // see http://dev.eclipse.org/bugs/show_bug.cgi?id=9351
- if (rewrite != null){
- saveContent(dest, destName, rewrite, sourceEncoding, destFile);
- }
- }
- }
- /**
- * Process all of the changed deltas generated by this operation.
- */
- protected void processDeltas() {
- for (Iterator deltas = this.deltasPerProject.values().iterator(); deltas.hasNext();){
- addDelta((IJavaScriptElementDelta) deltas.next());
- }
- }
- /**
- * @see MultiOperation
- * This method delegates to <code>processCompilationUnitResource</code> or
- * <code>processPackageFragmentResource</code>, depending on the type of
- * <code>element</code>.
- */
- protected void processElement(IJavaScriptElement element) throws JavaScriptModelException {
- IJavaScriptElement dest = getDestinationParent(element);
- switch (element.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_UNIT :
- processCompilationUnitResource((IJavaScriptUnit) element, (PackageFragment) dest);
- createdElements.add(((IPackageFragment) dest).getJavaScriptUnit(element.getElementName()));
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT :
- processPackageFragmentResource((PackageFragment) element, (PackageFragmentRoot) dest, getNewNameFor(element));
- break;
- default :
- throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_ELEMENT_TYPES, element));
- }
- }
- /**
- * @see MultiOperation
- * Overridden to allow special processing of <code>JavaElementDelta</code>s
- * and <code>fResultElements</code>.
- */
- protected void processElements() throws JavaScriptModelException {
- createdElements = new ArrayList(elementsToProcess.length);
- try {
- super.processElements();
- } catch (JavaScriptModelException jme) {
- throw jme;
- } finally {
- resultElements = new IJavaScriptElement[createdElements.size()];
- createdElements.toArray(resultElements);
- processDeltas();
- }
- }
- /**
- * Copies/moves a package fragment with the name <code>newName</code>
- * to the destination package.<br>
- *
- * @exception JavaScriptModelException if the operation is unable to
- * complete
- */
- private void processPackageFragmentResource(PackageFragment source, PackageFragmentRoot root, String newName) throws JavaScriptModelException {
- try {
- String[] newFragName = (newName == null) ? source.names : Util.getTrimmedSimpleNames(newName);
- IPackageFragment newFrag = root.getPackageFragment(newFragName);
- IResource[] resources = collectResourcesOfInterest(source);
-
- // if isMove() can we move the folder itself ? (see http://bugs.eclipse.org/bugs/show_bug.cgi?id=22458)
- boolean shouldMoveFolder = isMove() && !newFrag.getResource().exists(); // if new pkg fragment exists, it is an override
- IFolder srcFolder = (IFolder)source.getResource();
- IPath destPath = newFrag.getPath();
- if (shouldMoveFolder) {
- // check if destination is not included in source
- if (srcFolder.getFullPath().isPrefixOf(destPath)) {
- shouldMoveFolder = false;
- } else {
- // check if there are no sub-packages
- IResource[] members = srcFolder.members();
- for (int i = 0; i < members.length; i++) {
- if ( members[i] instanceof IFolder) {
- shouldMoveFolder = false;
- break;
- }
- }
- }
- }
- boolean containsReadOnlySubPackageFragments = createNeededPackageFragments((IContainer) source.getParent().getResource(), root, newFragName, shouldMoveFolder);
- boolean sourceIsReadOnly = Util.isReadOnly(srcFolder);
-
- // Process resources
- if (shouldMoveFolder) {
- // move underlying resource
- // TODO Revisit once bug 43044 is fixed
- if (sourceIsReadOnly) {
- Util.setReadOnly(srcFolder, false);
- }
- srcFolder.move(destPath, force, true /* keep history */, getSubProgressMonitor(1));
- if (sourceIsReadOnly) {
- Util.setReadOnly(srcFolder, true);
- }
- setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
- } else {
- // process the leaf resources
- if (resources.length > 0) {
- if (isRename()) {
- if (! destPath.equals(source.getPath())) {
- moveResources(resources, destPath);
- }
- } else if (isMove()) {
- // we need to delete this resource if this operation wants to override existing resources
- for (int i = 0, max = resources.length; i < max; i++) {
- IResource destinationResource = ResourcesPlugin.getWorkspace().getRoot().findMember(destPath.append(resources[i].getName()));
- if (destinationResource != null) {
- if (force) {
- deleteResource(destinationResource, IResource.KEEP_HISTORY);
- } else {
- throw new JavaScriptModelException(new JavaModelStatus(
- IJavaScriptModelStatusConstants.NAME_COLLISION,
- Messages.bind(Messages.status_nameCollision, destinationResource.getFullPath().toString())));
- }
- }
- }
- moveResources(resources, destPath);
- } else {
- // we need to delete this resource if this operation wants to override existing resources
- for (int i = 0, max = resources.length; i < max; i++) {
- IResource destinationResource = ResourcesPlugin.getWorkspace().getRoot().findMember(destPath.append(resources[i].getName()));
- if (destinationResource != null) {
- if (force) {
- // we need to delete this resource if this operation wants to override existing resources
- deleteResource(destinationResource, IResource.KEEP_HISTORY);
- } else {
- throw new JavaScriptModelException(new JavaModelStatus(
- IJavaScriptModelStatusConstants.NAME_COLLISION,
- Messages.bind(Messages.status_nameCollision, destinationResource.getFullPath().toString())));
- }
- }
- }
- copyResources(resources, destPath);
- }
- }
- }
-
- // Update package statement in compilation unit if needed
- if (!Util.equalArraysOrNull(newFragName, source.names)) { // if package has been renamed, update the compilation units
- char[][] inclusionPatterns = root.fullInclusionPatternChars();
- char[][] exclusionPatterns = root.fullExclusionPatternChars();
- for (int i = 0; i < resources.length; i++) {
- String resourceName = resources[i].getName();
- if (Util.isJavaLikeFileName(resourceName)) {
- // we only consider potential compilation units
- IJavaScriptUnit cu = newFrag.getJavaScriptUnit(resourceName);
- if (Util.isExcluded(cu.getPath(), inclusionPatterns, exclusionPatterns, false/*not a folder*/)) continue;
- this.parser.setSource(cu);
- JavaScriptUnit astCU = (JavaScriptUnit) this.parser.createAST(this.progressMonitor);
- AST ast = astCU.getAST();
- ASTRewrite rewrite = ASTRewrite.create(ast);
- updatePackageStatement(astCU, newFragName, rewrite);
- IDocument document = getDocument(cu);
- TextEdit edits = rewrite.rewriteAST(document, null);
- try {
- edits.apply(document);
- } catch (BadLocationException e) {
- throw new JavaScriptModelException(e, IJavaScriptModelStatusConstants.INVALID_CONTENTS);
- }
- cu.save(null, false);
- }
- }
- }
-
- // Discard empty old package (if still empty after the rename)
- boolean isEmpty = true;
- if (isMove()) {
- // delete remaining files in this package (.class file in the case where Proj=src=bin)
- // in case of a copy
- updateReadOnlyPackageFragmentsForMove((IContainer) source.getParent().getResource(), root, newFragName, sourceIsReadOnly);
- if (srcFolder.exists()) {
- IResource[] remaining = srcFolder.members();
- for (int i = 0, length = remaining.length; i < length; i++) {
- IResource file = remaining[i];
- if (file instanceof IFile) {
- if (Util.isReadOnly(file)) {
- Util.setReadOnly(file, false);
- }
- this.deleteResource(file, IResource.FORCE | IResource.KEEP_HISTORY);
- } else {
- isEmpty = false;
- }
- }
- }
- if (isEmpty) {
- IResource rootResource;
- // check if source is included in destination
- if (destPath.isPrefixOf(srcFolder.getFullPath())) {
- rootResource = newFrag.getResource();
- } else {
- rootResource = source.getParent().getResource();
- }
-
- // delete recursively empty folders
- deleteEmptyPackageFragment(source, false, rootResource);
- }
- } else if (containsReadOnlySubPackageFragments) {
- // in case of a copy
- updateReadOnlyPackageFragmentsForCopy((IContainer) source.getParent().getResource(), root, newFragName);
- }
- // workaround for bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=24505
- if (isEmpty && isMove() && !(Util.isExcluded(source) || Util.isExcluded(newFrag))) {
- IJavaScriptProject sourceProject = source.getJavaScriptProject();
- getDeltaFor(sourceProject).movedFrom(source, newFrag);
- IJavaScriptProject destProject = newFrag.getJavaScriptProject();
- getDeltaFor(destProject).movedTo(newFrag, source);
- }
- } catch (JavaScriptModelException e) {
- throw e;
- } catch (CoreException ce) {
- throw new JavaScriptModelException(ce);
- }
- }
- private void saveContent(PackageFragment dest, String destName, ASTRewrite rewrite, String sourceEncoding, IFile destFile) throws JavaScriptModelException {
- try {
- // TODO (frederic) remove when bug 67606 will be fixed (bug 67823)
- // fix bug 66898
- if (sourceEncoding != null) destFile.setCharset(sourceEncoding, this.progressMonitor);
- // end todo
- }
- catch (CoreException ce) {
- // use no encoding
- }
- // when the file was copied, its read-only flag was preserved -> temporary set it to false
- // note this doesn't interfer with repository providers as this is a new resource that cannot be under
- // version control yet
- Util.setReadOnly(destFile, false);
- IJavaScriptUnit destCU = dest.getJavaScriptUnit(destName);
- IDocument document = getDocument(destCU);
- TextEdit edits = rewrite.rewriteAST(document, null);
- try {
- edits.apply(document);
- } catch (BadLocationException e) {
- throw new JavaScriptModelException(e, IJavaScriptModelStatusConstants.INVALID_CONTENTS);
- }
- destCU.save(getSubProgressMonitor(1), this.force);
- }
- /**
- * Updates the content of <code>cu</code>, modifying the type name and/or package
- * declaration as necessary.
- *
- * @return an AST rewrite or null if no rewrite needed
- */
- private ASTRewrite updateContent(IJavaScriptUnit cu, PackageFragment dest, String newName) throws JavaScriptModelException {
- String[] currPackageName = ((PackageFragment) cu.getParent()).names;
- String[] destPackageName = dest.names;
- if (Util.equalArraysOrNull(currPackageName, destPackageName) && newName == null) {
- return null; //nothing to change
- } else {
- // ensure cu is consistent (noop if already consistent)
- cu.makeConsistent(this.progressMonitor);
- this.parser.setSource(cu);
- JavaScriptUnit astCU = (JavaScriptUnit) this.parser.createAST(this.progressMonitor);
- AST ast = astCU.getAST();
- ASTRewrite rewrite = ASTRewrite.create(ast);
- updateTypeName(cu, astCU, cu.getElementName(), newName, rewrite);
-// updatePackageStatement(astCU, destPackageName, rewrite);
- return rewrite;
- }
- }
- private void updatePackageStatement(JavaScriptUnit astCU, String[] pkgName, ASTRewrite rewriter) throws JavaScriptModelException {
- boolean defaultPackage = pkgName.length == 0;
- AST ast = astCU.getAST();
- if (defaultPackage) {
- // remove existing package statement
- if (astCU.getPackage() != null)
- rewriter.set(astCU, JavaScriptUnit.PACKAGE_PROPERTY, null, null);
- } else {
- org.eclipse.wst.jsdt.core.dom.PackageDeclaration pkg = astCU.getPackage();
- if (pkg != null) {
- // rename package statement
- Name name = ast.newName(pkgName);
- rewriter.set(pkg, PackageDeclaration.NAME_PROPERTY, name, null);
- } else {
- // create new package statement
- pkg = ast.newPackageDeclaration();
- pkg.setName(ast.newName(pkgName));
- rewriter.set(astCU, JavaScriptUnit.PACKAGE_PROPERTY, pkg, null);
- }
- }
- }
-
- private void updateReadOnlyPackageFragmentsForCopy(IContainer sourceFolder, IPackageFragmentRoot root, String[] newFragName) {
- IContainer parentFolder = (IContainer) root.getResource();
- for (int i = 0, length = newFragName.length; i <length; i++) {
- String subFolderName = newFragName[i];
- parentFolder = parentFolder.getFolder(new Path(subFolderName));
- sourceFolder = sourceFolder.getFolder(new Path(subFolderName));
- if (sourceFolder.exists() && Util.isReadOnly(sourceFolder)) {
- Util.setReadOnly(parentFolder, true);
- }
- }
- }
-
- private void updateReadOnlyPackageFragmentsForMove(IContainer sourceFolder, IPackageFragmentRoot root, String[] newFragName, boolean sourceFolderIsReadOnly) {
- IContainer parentFolder = (IContainer) root.getResource();
- for (int i = 0, length = newFragName.length; i < length; i++) {
- String subFolderName = newFragName[i];
- parentFolder = parentFolder.getFolder(new Path(subFolderName));
- sourceFolder = sourceFolder.getFolder(new Path(subFolderName));
- if ((sourceFolder.exists() && Util.isReadOnly(sourceFolder)) || (i == length - 1 && sourceFolderIsReadOnly)) {
- Util.setReadOnly(parentFolder, true);
- // the source folder will be deleted anyway (move operation)
- Util.setReadOnly(sourceFolder, false);
- }
- }
- }
- /**
- * Renames the main type in <code>cu</code>.
- */
- private void updateTypeName(IJavaScriptUnit cu, JavaScriptUnit astCU, String oldName, String newName, ASTRewrite rewriter) throws JavaScriptModelException {
- if (newName != null) {
- String oldTypeName= Util.getNameWithoutJavaLikeExtension(oldName);
- String newTypeName= Util.getNameWithoutJavaLikeExtension(newName);
- AST ast = astCU.getAST();
- // update main type name
- IType[] types = cu.getTypes();
- for (int i = 0, max = types.length; i < max; i++) {
- IType currentType = types[i];
- if (currentType.getElementName().equals(oldTypeName)) {
- AbstractTypeDeclaration typeNode = (AbstractTypeDeclaration) ((JavaElement) currentType).findNode(astCU);
- if (typeNode != null) {
- // rename type
- rewriter.replace(typeNode.getName(), ast.newSimpleName(newTypeName), null);
- // rename constructors
- Iterator bodyDeclarations = typeNode.bodyDeclarations().iterator();
- while (bodyDeclarations.hasNext()) {
- Object bodyDeclaration = bodyDeclarations.next();
- if (bodyDeclaration instanceof FunctionDeclaration) {
- FunctionDeclaration methodDeclaration = (FunctionDeclaration) bodyDeclaration;
- if (methodDeclaration.isConstructor()) {
- SimpleName methodName = methodDeclaration.getName();
- if (methodName.getIdentifier().equals(oldTypeName)) {
- rewriter.replace(methodName, ast.newSimpleName(newTypeName), null);
- }
- }
- }
- }
- }
- }
- }
- }
- }
- /**
- * Possible failures:
- * <ul>
- * <li>NO_ELEMENTS_TO_PROCESS - no elements supplied to the operation
- * <li>INDEX_OUT_OF_BOUNDS - the number of renamings supplied to the operation
- * does not match the number of elements that were supplied.
- * </ul>
- */
- protected IJavaScriptModelStatus verify() {
- IJavaScriptModelStatus status = super.verify();
- if (!status.isOK()) {
- return status;
- }
-
- if (this.renamingsList != null && this.renamingsList.length != elementsToProcess.length) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INDEX_OUT_OF_BOUNDS);
- }
- return JavaModelStatus.VERIFIED_OK;
- }
- /**
- * @see MultiOperation
- */
- protected void verify(IJavaScriptElement element) throws JavaScriptModelException {
- if (element == null || !element.exists())
- error(IJavaScriptModelStatusConstants.ELEMENT_DOES_NOT_EXIST, element);
-
- if (element.isReadOnly() && (isRename() || isMove()))
- error(IJavaScriptModelStatusConstants.READ_ONLY, element);
-
- IResource resource = element.getResource();
- if (resource instanceof IFolder) {
- if (resource.isLinked()) {
- error(IJavaScriptModelStatusConstants.INVALID_RESOURCE, element);
- }
- }
-
- int elementType = element.getElementType();
-
- if (elementType == IJavaScriptElement.JAVASCRIPT_UNIT) {
- org.eclipse.wst.jsdt.internal.core.CompilationUnit compilationUnit = (org.eclipse.wst.jsdt.internal.core.CompilationUnit) element;
- if (isMove() && compilationUnit.isWorkingCopy() && !compilationUnit.isPrimary())
- error(IJavaScriptModelStatusConstants.INVALID_ELEMENT_TYPES, element);
- } else if (elementType != IJavaScriptElement.PACKAGE_FRAGMENT) {
- error(IJavaScriptModelStatusConstants.INVALID_ELEMENT_TYPES, element);
- }
-
- JavaElement dest = (JavaElement) getDestinationParent(element);
- verifyDestination(element, dest);
- if (this.renamings != null) {
- verifyRenaming(element);
- }
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreateCompilationUnitOperation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreateCompilationUnitOperation.java
deleted file mode 100644
index 7d257534..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreateCompilationUnitOperation.java
+++ /dev/null
@@ -1,176 +0,0 @@
-/*******************************************************************************
- * 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 java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.jobs.ISchedulingRule;
-import org.eclipse.wst.jsdt.core.IBuffer;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptElementDelta;
-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.IPackageFragment;
-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.internal.core.util.Messages;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * <p>This operation creates a compilation unit (CU).
- * If the CU doesn't exist yet, a new compilation unit will be created with the content provided.
- * Otherwise the operation will override the contents of an existing CU with the new content.
- *
- * <p>Note: It is possible to create a CU automatically when creating a
- * class or interface. Thus, the preferred method of creating a CU is
- * to perform a create type operation rather than
- * first creating a CU and secondly creating a type inside the CU.
- *
- * <p>Required Attributes:<ul>
- * <li>The package fragment in which to create the compilation unit.
- * <li>The name of the compilation unit.
- * Do not include the <code>".js"</code> suffix (ex. <code>"Object"</code> -
- * the <code>".js"</code> will be added for the name of the compilation unit.)
- * <li>
- * </ul>
- */
-public class CreateCompilationUnitOperation extends JavaModelOperation {
-
- /**
- * The name of the compilation unit being created.
- */
- protected String fName;
- /**
- * The source code to use when creating the element.
- */
- protected String fSource= null;
-/**
- * When executed, this operation will create a compilation unit with the given name.
- * The name should have the ".js" suffix.
- */
-public CreateCompilationUnitOperation(IPackageFragment parentElement, String name, String source, boolean force) {
- super(null, new IJavaScriptElement[] {parentElement}, force);
- fName = name;
- fSource = source;
-}
-/**
- * Creates a compilation unit.
- *
- * @exception JavaScriptModelException if unable to create the compilation unit.
- */
-protected void executeOperation() throws JavaScriptModelException {
- try {
- beginTask(Messages.operation_createUnitProgress, 2);
- JavaElementDelta delta = newJavaElementDelta();
- IJavaScriptUnit unit = getCompilationUnit();
- IPackageFragment pkg = (IPackageFragment) getParentElement();
- IContainer folder = (IContainer) pkg.getResource();
- worked(1);
- IFile compilationUnitFile = folder.getFile(new Path(fName));
- if (compilationUnitFile.exists()) {
- // update the contents of the existing unit if fForce is true
- if (force) {
- IBuffer buffer = unit.getBuffer();
- if (buffer == null) return;
- buffer.setContents(fSource);
- unit.save(new NullProgressMonitor(), false);
- resultElements = new IJavaScriptElement[] {unit};
- if (!Util.isExcluded(unit)
- && unit.getParent().exists()) {
- for (int i = 0; i < resultElements.length; i++) {
- delta.changed(resultElements[i], IJavaScriptElementDelta.F_CONTENT);
- }
- addDelta(delta);
- }
- } else {
- throw new JavaScriptModelException(new JavaModelStatus(
- IJavaScriptModelStatusConstants.NAME_COLLISION,
- Messages.bind(Messages.status_nameCollision, compilationUnitFile.getFullPath().toString())));
- }
- } else {
- try {
- String encoding = null;
- try {
- encoding = folder.getDefaultCharset(); // get folder encoding as file is not accessible
- }
- catch (CoreException ce) {
- // use no encoding
- }
- InputStream stream = new ByteArrayInputStream(encoding == null ? fSource.getBytes() : fSource.getBytes(encoding));
- createFile(folder, unit.getElementName(), stream, force);
- resultElements = new IJavaScriptElement[] {unit};
- if (!Util.isExcluded(unit)
- && unit.getParent().exists()) {
- for (int i = 0; i < resultElements.length; i++) {
- delta.added(resultElements[i]);
- }
- addDelta(delta);
- }
- } catch (IOException e) {
- throw new JavaScriptModelException(e, IJavaScriptModelStatusConstants.IO_EXCEPTION);
- }
- }
- worked(1);
- } finally {
- done();
- }
-}
-/**
- * @see CreateElementInCUOperation#getCompilationUnit()
- */
-protected IJavaScriptUnit getCompilationUnit() {
- return ((IPackageFragment)getParentElement()).getJavaScriptUnit(fName);
-}
-protected ISchedulingRule getSchedulingRule() {
- IResource resource = getCompilationUnit().getResource();
- IWorkspace workspace = resource.getWorkspace();
- if (resource.exists()) {
- return workspace.getRuleFactory().modifyRule(resource);
- } else {
- return workspace.getRuleFactory().createRule(resource);
- }
-}
-/**
- * Possible failures: <ul>
- * <li>NO_ELEMENTS_TO_PROCESS - the package fragment supplied to the operation is
- * <code>null</code>.
- * <li>INVALID_NAME - the compilation unit name provided to the operation
- * is <code>null</code> or has an invalid syntax
- * <li>INVALID_CONTENTS - the source specified for the compiliation unit is null
- * </ul>
- */
-public IJavaScriptModelStatus verify() {
- if (getParentElement() == null) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.NO_ELEMENTS_TO_PROCESS);
- }
- IJavaScriptProject project = getParentElement().getJavaScriptProject();
- if (JavaScriptConventions.validateCompilationUnitName(fName, project.getOption(JavaScriptCore.COMPILER_SOURCE, true), project.getOption(JavaScriptCore.COMPILER_COMPLIANCE, true)).getSeverity() == IStatus.ERROR) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_NAME, fName);
- }
- if (fSource == null) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_CONTENTS);
- }
- return JavaModelStatus.VERIFIED_OK;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreateElementInCUOperation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreateElementInCUOperation.java
deleted file mode 100644
index 09d2fa15..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreateElementInCUOperation.java
+++ /dev/null
@@ -1,330 +0,0 @@
-/*******************************************************************************
- * 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 java.util.Map;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.runtime.jobs.ISchedulingRule;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.text.edits.TextEdit;
-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.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.ChildListPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.StructuralPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * <p>This abstract class implements behavior common to <code>CreateElementInCUOperations</code>.
- * To create a compilation unit, or an element contained in a compilation unit, the
- * source code for the entire compilation unit is updated and saved.
- *
- * <p>The element being created can be positioned relative to an existing
- * element in the compilation unit via the methods <code>#createAfter</code>
- * and <code>#createBefore</code>. By default, the new element is positioned
- * as the last child of its parent element.
- *
- */
-public abstract class CreateElementInCUOperation extends JavaModelOperation {
- /**
- * The compilation unit AST used for this operation
- */
- protected JavaScriptUnit cuAST;
- /**
- * A constant meaning to position the new element
- * as the last child of its parent element.
- */
- protected static final int INSERT_LAST = 1;
- /**
- * A constant meaning to position the new element
- * after the element defined by <code>fAnchorElement</code>.
- */
- protected static final int INSERT_AFTER = 2;
-
- /**
- * A constant meaning to position the new element
- * before the element defined by <code>fAnchorElement</code>.
- */
- protected static final int INSERT_BEFORE = 3;
- /**
- * One of the position constants, describing where
- * to position the newly created element.
- */
- protected int insertionPolicy = INSERT_LAST;
- /**
- * The element that the newly created element is
- * positioned relative to, as described by
- * <code>fInsertPosition</code>, or <code>null</code>
- * if the newly created element will be positioned
- * last.
- */
- protected IJavaScriptElement anchorElement = null;
- /**
- * A flag indicating whether creation of a new element occurred.
- * A request for creating a duplicate element would request in this
- * flag being set to <code>false</code>. Ensures that no deltas are generated
- * when creation does not occur.
- */
- protected boolean creationOccurred = true;
- /**
- * Constructs an operation that creates a Java Language Element with
- * the specified parent, contained within a compilation unit.
- */
- public CreateElementInCUOperation(IJavaScriptElement parentElement) {
- super(null, new IJavaScriptElement[]{parentElement});
- initializeDefaultPosition();
- }
- protected void apply(ASTRewrite rewriter, IDocument document, Map options) throws JavaScriptModelException {
- TextEdit edits = rewriter.rewriteAST(document, options);
- try {
- edits.apply(document);
- } catch (BadLocationException e) {
- throw new JavaScriptModelException(e, IJavaScriptModelStatusConstants.INVALID_CONTENTS);
- }
- }
- /**
- * Only allow cancelling if this operation is not nested.
- */
- protected void checkCanceled() {
- if (!isNested) {
- super.checkCanceled();
- }
- }
- /**
- * Instructs this operation to position the new element after
- * the given sibling, or to add the new element as the last child
- * of its parent if <code>null</code>.
- */
- public void createAfter(IJavaScriptElement sibling) {
- setRelativePosition(sibling, INSERT_AFTER);
- }
- /**
- * Instructs this operation to position the new element before
- * the given sibling, or to add the new element as the last child
- * of its parent if <code>null</code>.
- */
- public void createBefore(IJavaScriptElement sibling) {
- setRelativePosition(sibling, INSERT_BEFORE);
- }
- /**
- * Execute the operation - generate new source for the compilation unit
- * and save the results.
- *
- * @exception JavaScriptModelException if the operation is unable to complete
- */
- protected void executeOperation() throws JavaScriptModelException {
- try {
- beginTask(getMainTaskName(), getMainAmountOfWork());
- JavaElementDelta delta = newJavaElementDelta();
- IJavaScriptUnit unit = getCompilationUnit();
- generateNewCompilationUnitAST(unit);
- if (this.creationOccurred) {
- //a change has really occurred
- unit.save(null, false);
- boolean isWorkingCopy = unit.isWorkingCopy();
- if (!isWorkingCopy)
- setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
- worked(1);
- resultElements = generateResultHandles();
- if (!isWorkingCopy // if unit is working copy, then save will have already fired the delta
- && !Util.isExcluded(unit)
- && unit.getParent().exists()) {
- for (int i = 0; i < resultElements.length; i++) {
- delta.added(resultElements[i]);
- }
- addDelta(delta);
- } // else unit is created outside classpath
- // non-java resource delta will be notified by delta processor
- }
- } finally {
- done();
- }
- }
-
- /*
- * Returns the property descriptor for the element being created.
- */
- protected abstract StructuralPropertyDescriptor getChildPropertyDescriptor(ASTNode parent);
-
- /*
- * Returns an AST node for the element being created.
- */
- protected abstract ASTNode generateElementAST(ASTRewrite rewriter, IDocument document, IJavaScriptUnit cu) throws JavaScriptModelException;
- /*
- * Generates a new AST for this operation and applies it to the given cu
- */
- protected void generateNewCompilationUnitAST(IJavaScriptUnit cu) throws JavaScriptModelException {
- this.cuAST = parse(cu);
-
- AST ast = this.cuAST.getAST();
- ASTRewrite rewriter = ASTRewrite.create(ast);
- IDocument document = getDocument(cu);
- ASTNode child = generateElementAST(rewriter, document, cu);
- if (child != null) {
- ASTNode parent = ((JavaElement) getParentElement()).findNode(this.cuAST);
- if (parent == null)
- parent = this.cuAST;
- insertASTNode(rewriter, parent, child);
- apply(rewriter, document, cu.getJavaScriptProject().getOptions(true));
- }
- worked(1);
- }
- /**
- * Creates and returns the handle for the element this operation created.
- */
- protected abstract IJavaScriptElement generateResultHandle();
- /**
- * Creates and returns the handles for the elements this operation created.
- */
- protected IJavaScriptElement[] generateResultHandles() {
- return new IJavaScriptElement[]{generateResultHandle()};
- }
- /**
- * Returns the compilation unit in which the new element is being created.
- */
- protected IJavaScriptUnit getCompilationUnit() {
- return getCompilationUnitFor(getParentElement());
- }
- /**
- * Returns the amount of work for the main task of this operation for
- * progress reporting.
- */
- protected int getMainAmountOfWork(){
- return 2;
- }
- /**
- * Returns the name of the main task of this operation for
- * progress reporting.
- */
- public abstract String getMainTaskName();
-
- protected ISchedulingRule getSchedulingRule() {
- IResource resource = getCompilationUnit().getResource();
- IWorkspace workspace = resource.getWorkspace();
- return workspace.getRuleFactory().modifyRule(resource);
- }
- /**
- * Sets the default position in which to create the new type
- * member.
- * Operations that require a different default position must
- * override this method.
- */
- protected void initializeDefaultPosition() {
- // By default, the new element is positioned as the
- // last child of the parent element in which it is created.
- }
- /**
- * Inserts the given child into the given AST,
- * based on the position settings of this operation.
- *
- * @see #createAfter(IJavaScriptElement)
- * @see #createBefore(IJavaScriptElement)
- */
- protected void insertASTNode(ASTRewrite rewriter, ASTNode parent, ASTNode child) throws JavaScriptModelException {
- StructuralPropertyDescriptor propertyDescriptor = getChildPropertyDescriptor(parent);
- if (propertyDescriptor instanceof ChildListPropertyDescriptor) {
- ChildListPropertyDescriptor childListPropertyDescriptor = (ChildListPropertyDescriptor) propertyDescriptor;
- ListRewrite rewrite = rewriter.getListRewrite(parent, childListPropertyDescriptor);
- switch (this.insertionPolicy) {
- case INSERT_BEFORE:
- ASTNode element = ((JavaElement) this.anchorElement).findNode(this.cuAST);
- if (childListPropertyDescriptor.getElementType().isAssignableFrom(element.getClass()))
- rewrite.insertBefore(child, element, null);
- else
- // case of an empty import list: the anchor element is the top level type and cannot be used in insertBefore as it is not the same type
- rewrite.insertLast(child, null);
- break;
- case INSERT_AFTER:
- element = ((JavaElement) this.anchorElement).findNode(this.cuAST);
- if (childListPropertyDescriptor.getElementType().isAssignableFrom(element.getClass()))
- rewrite.insertAfter(child, element, null);
- else
- // case of an empty import list: the anchor element is the top level type and cannot be used in insertAfter as it is not the same type
- rewrite.insertLast(child, null);
- break;
- case INSERT_LAST:
- rewrite.insertLast(child, null);
- break;
- }
- } else {
- rewriter.set(parent, propertyDescriptor, child, null);
- }
- }
- protected JavaScriptUnit parse(IJavaScriptUnit cu) throws JavaScriptModelException {
- // ensure cu is consistent (noop if already consistent)
- cu.makeConsistent(this.progressMonitor);
- // create an AST for the compilation unit
- ASTParser parser = ASTParser.newParser(AST.JLS3);
- parser.setSource(cu);
- return (JavaScriptUnit) parser.createAST(this.progressMonitor);
- }
- /**
- * Sets the name of the <code>DOMNode</code> that will be used to
- * create this new element.
- * Used by the <code>CopyElementsOperation</code> for renaming.
- * Only used for <code>CreateTypeMemberOperation</code>
- */
- protected void setAlteredName(String newName) {
- // implementation in CreateTypeMemberOperation
- }
- /**
- * Instructs this operation to position the new element relative
- * to the given sibling, or to add the new element as the last child
- * of its parent if <code>null</code>. The <code>position</code>
- * must be one of the position constants.
- */
- protected void setRelativePosition(IJavaScriptElement sibling, int policy) throws IllegalArgumentException {
- if (sibling == null) {
- this.anchorElement = null;
- this.insertionPolicy = INSERT_LAST;
- } else {
- this.anchorElement = sibling;
- this.insertionPolicy = policy;
- }
- }
- /**
- * Possible failures: <ul>
- * <li>NO_ELEMENTS_TO_PROCESS - the compilation unit supplied to the operation is
- * <code>null</code>.
- * <li>INVALID_NAME - no name, a name was null or not a valid
- * import declaration name.
- * <li>INVALID_SIBLING - the sibling provided for positioning is not valid.
- * </ul>
- * @see IJavaScriptModelStatus
- * @see org.eclipse.wst.jsdt.core.JavaScriptConventions
- */
- public IJavaScriptModelStatus verify() {
- if (getParentElement() == null) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.NO_ELEMENTS_TO_PROCESS);
- }
- if (this.anchorElement != null) {
- IJavaScriptElement domPresentParent = this.anchorElement.getParent();
- if (domPresentParent.getElementType() == IJavaScriptElement.IMPORT_CONTAINER) {
- domPresentParent = domPresentParent.getParent();
- }
- if (!domPresentParent.equals(getParentElement())) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_SIBLING, this.anchorElement);
- }
- }
- return JavaModelStatus.VERIFIED_OK;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreateFieldOperation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreateFieldOperation.java
deleted file mode 100644
index dca8ac01..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreateFieldOperation.java
+++ /dev/null
@@ -1,177 +0,0 @@
-/*******************************************************************************
- * 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 java.util.Iterator;
-
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IField;
-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.IParent;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-
-/**
- * <p>
- * This operation creates a field declaration in a type.
- *
- * <p>
- * Required Attributes:
- * <ul>
- * <li>Containing Type
- * <li>The source code for the declaration. No verification of the source is
- * performed.
- * </ul>
- */
-public class CreateFieldOperation extends CreateTypeMemberOperation {
- /**
- * When executed, this operation will create a field with the given name in
- * the given type with the specified source.
- *
- * <p>
- * By default the new field is positioned after the last existing field
- * declaration, or as the first member in the type if there are no field
- * declarations.
- */
- public CreateFieldOperation(IJavaScriptElement parentElement, String source,
- boolean force) {
- super(parentElement, source, force);
- }
-
- protected ASTNode generateElementAST(ASTRewrite rewriter,
- IDocument document, IJavaScriptUnit cu) throws JavaScriptModelException {
- ASTNode node = super.generateElementAST(rewriter, document, cu);
- if (node.getNodeType() != ASTNode.FIELD_DECLARATION)
- throw new JavaScriptModelException(new JavaModelStatus(
- IJavaScriptModelStatusConstants.INVALID_CONTENTS));
- return node;
- }
-
- /**
- * @see CreateElementInCUOperation#generateResultHandle
- */
- protected IJavaScriptElement generateResultHandle() {
- if (getType()!=null)
- return getType().getField(getASTNodeName());
- return getCompilationUnit().getField(getASTNodeName());
- }
-
- /**
- * @see CreateElementInCUOperation#getMainTaskName()
- */
- public String getMainTaskName() {
- return Messages.operation_createFieldProgress;
- }
-
- private VariableDeclarationFragment getFragment(ASTNode node) {
- Iterator fragments = ((FieldDeclaration) node).fragments().iterator();
- if (this.anchorElement != null) {
- VariableDeclarationFragment fragment = null;
- String fragmentName = this.anchorElement.getElementName();
- while (fragments.hasNext()) {
- fragment = (VariableDeclarationFragment) fragments.next();
- if (fragment.getName().getIdentifier().equals(fragmentName)) {
- return fragment;
- }
- }
- return fragment;
- } else {
- return (VariableDeclarationFragment) fragments.next();
- }
- }
-
- /**
- * By default the new field is positioned after the last existing field
- * declaration, or as the first member in the type if there are no field
- * declarations.
- */
- protected void initializeDefaultPosition() {
- IField[] fields = null;
- IParent parentElement;
- try {
- if (getType() != null) {
- parentElement = getType();
- fields = getType().getFields();
- } else {
- parentElement = getCompilationUnit();
- fields = getCompilationUnit().getFields();
-
- }
- if (fields != null && fields.length > 0) {
- final IField lastField = fields[fields.length - 1];
- // if (parentElement.isEnum()) {
- // IField field = lastField;
- // if (!field.isEnumConstant()) {
- // createAfter(lastField);
- // }
- // } else {
- createAfter(lastField);
- // }
- } else {
- IJavaScriptElement[] elements = parentElement.getChildren();
- if (elements != null && elements.length > 0) {
- createBefore(elements[0]);
- }
- }
- } catch (JavaScriptModelException e) {
- // type doesn't exist: ignore
- }
- }
-
- /**
- * @see CreateTypeMemberOperation#verifyNameCollision
- */
- protected IJavaScriptModelStatus verifyNameCollision() {
- if (this.createdNode != null) {
- IType type = getType();
- String fieldName = getASTNodeName();
- if (type != null) {
- if (type.getField(fieldName).exists()) {
- return new JavaModelStatus(
- IJavaScriptModelStatusConstants.NAME_COLLISION, Messages
- .bind(Messages.status_nameCollision,
- fieldName));
- }
- } else {
- if (getCompilationUnit().getField(fieldName).exists()) {
- return new JavaModelStatus(
- IJavaScriptModelStatusConstants.NAME_COLLISION, Messages
- .bind(Messages.status_nameCollision,
- fieldName));
- }
-
- }
- }
- return JavaModelStatus.VERIFIED_OK;
- }
-
- private String getASTNodeName() {
- if (this.alteredName != null)
- return this.alteredName;
- return getFragment(this.createdNode).getName().getIdentifier();
- }
-
- protected SimpleName rename(ASTNode node, SimpleName newName) {
- VariableDeclarationFragment fragment = getFragment(node);
- SimpleName oldName = fragment.getName();
- fragment.setName(newName);
- return oldName;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreateImportOperation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreateImportOperation.java
deleted file mode 100644
index 48aae3b6..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreateImportOperation.java
+++ /dev/null
@@ -1,168 +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;
-
-import java.util.Iterator;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IImportDeclaration;
-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.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.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.ImportDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.StructuralPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-
-/**
- * <p>This operation adds an import declaration to an existing compilation unit.
- * If the compilation unit already includes the specified import declaration,
- * the import is not generated (it does not generate duplicates).
- * Note that it is valid to specify both a single-type import and an on-demand import
- * for the same package, for example <code>"java.io.File"</code> and
- * <code>"java.io.*"</code>, in which case both are preserved since the semantics
- * of this are not the same as just importing <code>"java.io.*"</code>.
- * Importing <code>"java.lang.*"</code>, or the package in which the compilation unit
- * is defined, are not treated as special cases. If they are specified, they are
- * included in the result.
- *
- * <p>Required Attributes:<ul>
- * <li>Compilation unit
- * <li>Import name - the name of the import to add to the
- * compilation unit. For example: <code>"java.io.File"</code> or <code>"java.awt.*"</code>
- * </ul>
- */
-public class CreateImportOperation extends CreateElementInCUOperation {
-
- /*
- * The name of the import to be created.
- */
- protected String importName;
-
- /*
- * The flags of the import to be created (either Flags#AccDefault or Flags#AccStatic)
- */
- protected int flags;
-
-/**
- * When executed, this operation will add an import to the given compilation unit.
- */
-public CreateImportOperation(String importName, IJavaScriptUnit parentElement, int flags) {
- super(parentElement);
- this.importName = importName;
- this.flags = flags;
-}
-protected StructuralPropertyDescriptor getChildPropertyDescriptor(ASTNode parent) {
- return JavaScriptUnit.IMPORTS_PROPERTY;
-}
-protected ASTNode generateElementAST(ASTRewrite rewriter, IDocument document, IJavaScriptUnit cu) throws JavaScriptModelException {
- // ensure no duplicate
- Iterator imports = this.cuAST.imports().iterator();
- boolean onDemand = this.importName.endsWith(".*"); //$NON-NLS-1$
- String importActualName = this.importName;
- if (onDemand) {
- importActualName = this.importName.substring(0, this.importName.length() - 2);
- }
- while (imports.hasNext()) {
- ImportDeclaration importDeclaration = (ImportDeclaration) imports.next();
- if (importActualName.equals(importDeclaration.getName().getFullyQualifiedName())
- && (onDemand == importDeclaration.isOnDemand())
- && (Flags.isStatic(this.flags) == importDeclaration.isStatic())) {
- this.creationOccurred = false;
- return null;
- }
- }
-
- AST ast = this.cuAST.getAST();
- ImportDeclaration importDeclaration = ast.newImportDeclaration();
- importDeclaration.setStatic(Flags.isStatic(this.flags));
- // split import name into individual fragments, checking for on demand imports
- char[][] charFragments = CharOperation.splitOn('.', importActualName.toCharArray(), 0, importActualName.length());
- int length = charFragments.length;
- String[] strFragments = new String[length];
- for (int i = 0; i < length; i++) {
- strFragments[i] = String.valueOf(charFragments[i]);
- }
- Name name = ast.newName(strFragments);
- importDeclaration.setName(name);
- if (onDemand) importDeclaration.setOnDemand(true);
- return importDeclaration;
-}
-/**
- * @see CreateElementInCUOperation#generateResultHandle
- */
-protected IJavaScriptElement generateResultHandle() {
- return getCompilationUnit().getImport(this.importName);
-}
-/**
- * @see CreateElementInCUOperation#getMainTaskName()
- */
-public String getMainTaskName(){
- return Messages.operation_createImportsProgress;
-}
-/**
- * Sets the correct position for the new import:<ul>
- * <li> after the last import
- * <li> if no imports, before the first type
- * <li> if no type, after the package statement
- * <li> and if no package statement - first thing in the CU
- */
-protected void initializeDefaultPosition() {
- try {
- IJavaScriptUnit cu = getCompilationUnit();
- IImportDeclaration[] imports = cu.getImports();
- if (imports.length > 0) {
- createAfter(imports[imports.length - 1]);
- return;
- }
- IType[] types = cu.getTypes();
- if (types.length > 0) {
- createBefore(types[0]);
- return;
- }
- } catch (JavaScriptModelException e) {
- // cu doesn't exit: ignore
- }
-}
-/**
- * Possible failures: <ul>
- * <li>NO_ELEMENTS_TO_PROCESS - the compilation unit supplied to the operation is
- * <code>null</code>.
- * <li>INVALID_NAME - not a valid import declaration name.
- * </ul>
- * @see IJavaScriptModelStatus
- * @see JavaScriptConventions
- */
-public IJavaScriptModelStatus verify() {
- IJavaScriptModelStatus status = super.verify();
- if (!status.isOK()) {
- return status;
- }
- IJavaScriptProject project = getParentElement().getJavaScriptProject();
- if (JavaScriptConventions.validateImportDeclaration(this.importName, project.getOption(JavaScriptCore.COMPILER_SOURCE, true), project.getOption(JavaScriptCore.COMPILER_COMPLIANCE, true)).getSeverity() == IStatus.ERROR) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_NAME, this.importName);
- }
- return JavaModelStatus.VERIFIED_OK;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreateMethodOperation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreateMethodOperation.java
deleted file mode 100644
index 6fb9fb43..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreateMethodOperation.java
+++ /dev/null
@@ -1,135 +0,0 @@
-/*******************************************************************************
- * 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 java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.jface.text.IDocument;
-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.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * <p>This operation creates an instance method.
- *
- * <p>Required Attributes:<ul>
- * <li>Containing type
- * <li>The source code for the method. No verification of the source is
- * performed.
- * </ul>
- */
-public class CreateMethodOperation extends CreateTypeMemberOperation {
-
- protected String[] parameterTypes;
-
-/**
- * When executed, this operation will create a method
- * in the given type with the specified source.
- */
-public CreateMethodOperation(IJavaScriptElement parentElement, String source, boolean force) {
- super(parentElement, source, force);
-}
-/**
- * Returns the type signatures of the parameter types of the
- * current <code>FunctionDeclaration</code>
- */
-protected String[] convertASTMethodTypesToSignatures() {
- if (this.parameterTypes == null) {
- if (this.createdNode != null) {
- FunctionDeclaration methodDeclaration = (FunctionDeclaration) this.createdNode;
- List parameters = methodDeclaration.parameters();
- int size = parameters.size();
- this.parameterTypes = new String[size];
- Iterator iterator = parameters.iterator();
- // convert the AST types to signatures
- for (int i = 0; i < size; i++) {
- SingleVariableDeclaration parameter = (SingleVariableDeclaration) iterator.next();
- String typeSig = Util.getSignature(parameter.getType());
- int extraDimensions = parameter.getExtraDimensions();
- if (methodDeclaration.isVarargs() && i == size-1)
- extraDimensions++;
- this.parameterTypes[i] = Signature.createArraySignature(typeSig, extraDimensions);
- }
- }
- }
- return this.parameterTypes;
-}
-protected ASTNode generateElementAST(ASTRewrite rewriter, IDocument document, IJavaScriptUnit cu) throws JavaScriptModelException {
- ASTNode node = super.generateElementAST(rewriter, document, cu);
- if (node.getNodeType() != ASTNode.FUNCTION_DECLARATION)
- throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_CONTENTS));
- return node;
-}
-/**
- * @see CreateElementInCUOperation#generateResultHandle
- */
-protected IJavaScriptElement generateResultHandle() {
- String[] types = convertASTMethodTypesToSignatures();
- String name = getASTNodeName();
- if (getType()!=null)
- return getType().getFunction(name, types);
- return getCompilationUnit().getFunction(name,types);
-}
-private String getASTNodeName() {
- return ((FunctionDeclaration) this.createdNode).getName().getIdentifier();
-}
-/**
- * @see CreateElementInCUOperation#getMainTaskName()
- */
-public String getMainTaskName(){
- return Messages.operation_createMethodProgress;
-}
-protected SimpleName rename(ASTNode node, SimpleName newName) {
- FunctionDeclaration method = (FunctionDeclaration) node;
- SimpleName oldName = method.getName();
- method.setName(newName);
- return oldName;
-}
-/**
- * @see CreateTypeMemberOperation#verifyNameCollision
- */
- protected IJavaScriptModelStatus verifyNameCollision() {
- if (this.createdNode != null) {
- IType type = getType();
- String name;
- if (((FunctionDeclaration) this.createdNode).isConstructor())
- name = type.getElementName();
- else
- name = getASTNodeName();
- String[] types = convertASTMethodTypesToSignatures();
- if (type != null) {
- if (type.getFunction(name, types).exists())
- return new JavaModelStatus(
- IJavaScriptModelStatusConstants.NAME_COLLISION, Messages
- .bind(Messages.status_nameCollision, name));
- } else {
- if (this.getCompilationUnit().getFunction(name, types).exists())
- return new JavaModelStatus(
- IJavaScriptModelStatusConstants.NAME_COLLISION, Messages
- .bind(Messages.status_nameCollision, name));
- }
-
- }
- return JavaModelStatus.VERIFIED_OK;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreatePackageFragmentOperation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreatePackageFragmentOperation.java
deleted file mode 100644
index 6ae88f73..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreatePackageFragmentOperation.java
+++ /dev/null
@@ -1,157 +0,0 @@
-/*******************************************************************************
- * 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 java.util.ArrayList;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-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.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-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.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * This operation creates a new package fragment under a given package fragment root.
- * The following must be specified: <ul>
- * <li>the package fragment root
- * <li>the package name
- * </ul>
- * <p>Any needed folders/package fragments are created.
- * If the package fragment already exists, this operation has no effect.
- * The result elements include the <code>IPackageFragment</code> created and any side effect
- * package fragments that were created.
- *
- * <p>NOTE: A default package fragment exists by default for a given root.
- *
- * <p>Possible exception conditions: <ul>
- * <li>Package fragment root is read-only
- * <li>Package fragment's name is taken by a simple (non-folder) resource
- * </ul>
- */
-public class CreatePackageFragmentOperation extends JavaModelOperation {
- /**
- * The fully qualified, dot-delimited, package name.
- */
- protected String[] pkgName;
-/**
- * When executed, this operation will create a package fragment with the given name
- * under the given package fragment root. The dot-separated name is broken into
- * segments. Intermediate folders are created as required for each segment.
- * If the folders already exist, this operation has no effect.
- */
-public CreatePackageFragmentOperation(IPackageFragmentRoot parentElement, String packageName, boolean force) {
- super(null, new IJavaScriptElement[]{parentElement}, force);
- this.pkgName = packageName == null ? null : Util.getTrimmedSimpleNames(packageName);
-}
-/**
- * Execute the operation - creates the new package fragment and any
- * side effect package fragments.
- *
- * @exception JavaScriptModelException if the operation is unable to complete
- */
-protected void executeOperation() throws JavaScriptModelException {
- try {
- JavaElementDelta delta = null;
- PackageFragmentRoot root = (PackageFragmentRoot) getParentElement();
- beginTask(Messages.operation_createPackageFragmentProgress, this.pkgName.length);
- IContainer parentFolder = (IContainer) root.getResource();
- String[] sideEffectPackageName = CharOperation.NO_STRINGS;
- ArrayList results = new ArrayList(this.pkgName.length);
- char[][] inclusionPatterns = root.fullInclusionPatternChars();
- char[][] exclusionPatterns = root.fullExclusionPatternChars();
- int i;
- for (i = 0; i < this.pkgName.length; i++) {
- String subFolderName = this.pkgName[i];
- sideEffectPackageName = Util.arrayConcat(sideEffectPackageName, subFolderName);
- IResource subFolder = parentFolder.findMember(subFolderName);
- if (subFolder == null) {
- createFolder(parentFolder, subFolderName, force);
- parentFolder = parentFolder.getFolder(new Path(subFolderName));
- IPackageFragment addedFrag = root.getPackageFragment(sideEffectPackageName);
- if (!Util.isExcluded(parentFolder, inclusionPatterns, exclusionPatterns)) {
- if (delta == null) {
- delta = newJavaElementDelta();
- }
- delta.added(addedFrag);
- }
- results.add(addedFrag);
- } else {
- parentFolder = (IContainer) subFolder;
- }
- worked(1);
- }
- if (results.size() > 0) {
- this.resultElements = new IJavaScriptElement[results.size()];
- results.toArray(this.resultElements);
- if (delta != null) {
- addDelta(delta);
- }
- }
- } finally {
- done();
- }
-}
-/**
- * Possible failures: <ul>
- * <li>NO_ELEMENTS_TO_PROCESS - the root supplied to the operation is
- * <code>null</code>.
- * <li>INVALID_NAME - the name provided to the operation
- * is <code>null</code> or is not a valid package fragment name.
- * <li>READ_ONLY - the root provided to this operation is read only.
- * <li>NAME_COLLISION - there is a pre-existing resource (file)
- * with the same name as a folder in the package fragment's hierarchy.
- * <li>ELEMENT_NOT_PRESENT - the underlying resource for the root is missing
- * </ul>
- * @see IJavaScriptModelStatus
- * @see JavaScriptConventions
- */
-public IJavaScriptModelStatus verify() {
- IJavaScriptElement parentElement = getParentElement();
- if (parentElement == null) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.NO_ELEMENTS_TO_PROCESS);
- }
-
- String packageName = this.pkgName == null ? null : Util.concatWith(this.pkgName, '.');
- IJavaScriptProject project = parentElement.getJavaScriptProject();
- if (this.pkgName == null || (this.pkgName.length > 0 && JavaScriptConventions.validatePackageName(packageName, project.getOption(JavaScriptCore.COMPILER_SOURCE, true), project.getOption(JavaScriptCore.COMPILER_COMPLIANCE, true)).getSeverity() == IStatus.ERROR)) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_NAME, packageName);
- }
- IPackageFragmentRoot root = (IPackageFragmentRoot) getParentElement();
- if (root.isReadOnly()) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.READ_ONLY, root);
- }
- IContainer parentFolder = (IContainer) root.getResource();
- int i;
- for (i = 0; i < this.pkgName.length; i++) {
- IResource subFolder = parentFolder.findMember(this.pkgName[i]);
- if (subFolder != null) {
- if (subFolder.getType() != IResource.FOLDER) {
- return new JavaModelStatus(
- IJavaScriptModelStatusConstants.NAME_COLLISION,
- Messages.bind(Messages.status_nameCollision, subFolder.getFullPath().toString()));
- }
- parentFolder = (IContainer) subFolder;
- }
- }
- return JavaModelStatus.VERIFIED_OK;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreateTypeHierarchyOperation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreateTypeHierarchyOperation.java
deleted file mode 100644
index aeca6cf1..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreateTypeHierarchyOperation.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/*******************************************************************************
- * 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.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.IRegion;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.internal.core.hierarchy.RegionBasedTypeHierarchy;
-import org.eclipse.wst.jsdt.internal.core.hierarchy.TypeHierarchy;
-
-/**
- * This operation creates an <code>ITypeHierarchy</code> for a specific type within
- * a specified region, or for all types within a region. The specified
- * region limits the number of resolved subtypes (to the subset of
- * types in the specified region). The resolved supertypes may go outside
- * of the specified region in order to reach the root(s) of the type
- * hierarchy. A Java Project is required to provide a context (classpath)
- * to use while resolving supertypes and subtypes.
- *
- * @see ITypeHierarchy
- */
-
-public class CreateTypeHierarchyOperation extends JavaModelOperation {
- /**
- * The generated type hierarchy
- */
- protected TypeHierarchy typeHierarchy;
-
-/**
- * Constructs an operation to create a type hierarchy for the
- * given type within the specified region, in the context of
- * the given project.
- */
-public CreateTypeHierarchyOperation(IRegion region, IJavaScriptUnit[] workingCopies, IType element, boolean computeSubtypes) {
- super(element);
- this.typeHierarchy = new RegionBasedTypeHierarchy(region, workingCopies, element, computeSubtypes);
-}
-/**
- * Constructs an operation to create a type hierarchy for the
- * given type and working copies.
- */
-public CreateTypeHierarchyOperation(IType element, IJavaScriptUnit[] workingCopies, IJavaScriptSearchScope scope, boolean computeSubtypes) {
- super(element);
- IJavaScriptUnit[] copies;
- if (workingCopies != null) {
- int length = workingCopies.length;
- copies = new IJavaScriptUnit[length];
- System.arraycopy(workingCopies, 0, copies, 0, length);
- } else {
- copies = null;
- }
- this.typeHierarchy = new TypeHierarchy(element, copies, scope, computeSubtypes);
-}
-/**
- * Constructs an operation to create a type hierarchy for the
- * given type and working copies.
- */
-public CreateTypeHierarchyOperation(IType element, IJavaScriptUnit[] workingCopies, IJavaScriptProject project, boolean computeSubtypes) {
- super(element);
- IJavaScriptUnit[] copies;
- if (workingCopies != null) {
- int length = workingCopies.length;
- copies = new IJavaScriptUnit[length];
- System.arraycopy(workingCopies, 0, copies, 0, length);
- } else {
- copies = null;
- }
- this.typeHierarchy = new TypeHierarchy(element, copies, project, computeSubtypes);
-}
-/**
- * Performs the operation - creates the type hierarchy
- * @exception JavaScriptModelException The operation has failed.
- */
-protected void executeOperation() throws JavaScriptModelException {
- this.typeHierarchy.refresh(this);
-}
-/**
- * Returns the generated type hierarchy.
- */
-public ITypeHierarchy getResult() {
- return this.typeHierarchy;
-}
-/**
- * @see JavaModelOperation
- */
-public boolean isReadOnly() {
- return true;
-}
-/**
- * Possible failures: <ul>
- * <li>NO_ELEMENTS_TO_PROCESS - at least one of a type or region must
- * be provided to generate a type hierarchy.
- * <li>ELEMENT_NOT_PRESENT - the provided type or type's project does not exist
- * </ul>
- */
-public IJavaScriptModelStatus verify() {
- IJavaScriptElement elementToProcess= getElementToProcess();
- if (elementToProcess == null && !(this.typeHierarchy instanceof RegionBasedTypeHierarchy)) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.NO_ELEMENTS_TO_PROCESS);
- }
- if (elementToProcess != null && !elementToProcess.exists()) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.ELEMENT_DOES_NOT_EXIST, elementToProcess);
- }
- IJavaScriptProject project = this.typeHierarchy.javaProject();
- if (project != null && !project.exists()) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.ELEMENT_DOES_NOT_EXIST, project);
- }
- return JavaModelStatus.VERIFIED_OK;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreateTypeMemberOperation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreateTypeMemberOperation.java
deleted file mode 100644
index 057d6116..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreateTypeMemberOperation.java
+++ /dev/null
@@ -1,223 +0,0 @@
-/*******************************************************************************
- * 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 java.util.List;
-import java.util.Map;
-
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.TextUtilities;
-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.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.StructuralPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.formatter.IndentManipulation;
-import org.eclipse.wst.jsdt.internal.compiler.parser.ScannerHelper;
-
-/**
- * Implements functionality common to
- * operations that create type members.
- */
-public abstract class CreateTypeMemberOperation extends CreateElementInCUOperation {
- /**
- * The source code for the new member.
- */
- protected String source = null;
- /**
- * The name of the <code>ASTNode</code> that may be used to
- * create this new element.
- * Used by the <code>CopyElementsOperation</code> for renaming
- */
- protected String alteredName;
- /**
- * The AST node representing the element that
- * this operation created.
- */
- protected ASTNode createdNode;
-/**
- * When executed, this operation will create a type member
- * in the given parent element with the specified source.
- */
-public CreateTypeMemberOperation(IJavaScriptElement parentElement, String source, boolean force) {
- super(parentElement);
- this.source = source;
- this.force = force;
-}
-protected StructuralPropertyDescriptor getChildPropertyDescriptor(ASTNode parent) {
- switch (parent.getNodeType()) {
- case ASTNode.JAVASCRIPT_UNIT:
- if (createdNode instanceof AbstractTypeDeclaration)
- return JavaScriptUnit.TYPES_PROPERTY;
- else
- return JavaScriptUnit.STATEMENTS_PROPERTY;
- default:
- return TypeDeclaration.BODY_DECLARATIONS_PROPERTY;
- }
-}
-protected ASTNode generateElementAST(ASTRewrite rewriter, IDocument document, IJavaScriptUnit cu) throws JavaScriptModelException {
- if (this.createdNode == null) {
- this.source = removeIndentAndNewLines(this.source, document, cu);
- ASTParser parser = ASTParser.newParser(AST.JLS3);
- parser.setSource(this.source.toCharArray());
- parser.setProject(getCompilationUnit().getJavaScriptProject());
- parser.setKind(ASTParser.K_CLASS_BODY_DECLARATIONS);
- ASTNode node = parser.createAST(this.progressMonitor);
- String createdNodeSource;
- if (node.getNodeType() == ASTNode.JAVASCRIPT_UNIT) {
- JavaScriptUnit compilationUnit = (JavaScriptUnit) node;
- this.createdNode = (ASTNode) compilationUnit.statements().iterator().next();
- createdNodeSource = this.source;
- }
- else if (node.getNodeType() == ASTNode.TYPE_DECLARATION) {
- TypeDeclaration typeDeclaration = (TypeDeclaration) node;
- this.createdNode = (ASTNode) typeDeclaration.bodyDeclarations().iterator().next();
- createdNodeSource = this.source;
- }
- else {
- createdNodeSource = generateSyntaxIncorrectAST();
- if (this.createdNode == null)
- throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_CONTENTS));
- }
- if (this.alteredName != null) {
- SimpleName newName = this.createdNode.getAST().newSimpleName(this.alteredName);
- SimpleName oldName = rename(this.createdNode, newName);
- int nameStart = oldName.getStartPosition();
- int nameEnd = nameStart + oldName.getLength();
- StringBuffer newSource = new StringBuffer();
- if (this.source.equals(createdNodeSource)) {
- newSource.append(createdNodeSource.substring(0, nameStart));
- newSource.append(this.alteredName);
- newSource.append(createdNodeSource.substring(nameEnd));
- } else {
- // syntactically incorrect source
- int createdNodeStart = this.createdNode.getStartPosition();
- int createdNodeEnd = createdNodeStart + this.createdNode.getLength();
- newSource.append(createdNodeSource.substring(createdNodeStart, nameStart));
- newSource.append(this.alteredName);
- newSource.append(createdNodeSource.substring(nameEnd, createdNodeEnd));
-
- }
- this.source = newSource.toString();
- }
- }
- if (rewriter == null) return this.createdNode;
- // return a string place holder (instead of the created node) so has to not lose comments and formatting
- return rewriter.createStringPlaceholder(this.source, this.createdNode.getNodeType());
-}
-private String removeIndentAndNewLines(String code, IDocument document, IJavaScriptUnit cu) {
- IJavaScriptProject project = cu.getJavaScriptProject();
- Map options = project.getOptions(true/*inherit JavaScriptCore options*/);
- int tabWidth = IndentManipulation.getTabWidth(options);
- int indentWidth = IndentManipulation.getIndentWidth(options);
- int indent = IndentManipulation.measureIndentUnits(code, tabWidth, indentWidth);
- int firstNonWhiteSpace = -1;
- int length = code.length();
- while (firstNonWhiteSpace < length-1)
- if (!ScannerHelper.isWhitespace(code.charAt(++firstNonWhiteSpace)))
- break;
- int lastNonWhiteSpace = length;
- while (lastNonWhiteSpace > 0)
- if (!ScannerHelper.isWhitespace(code.charAt(--lastNonWhiteSpace)))
- break;
- String lineDelimiter = TextUtilities.getDefaultLineDelimiter(document);
- return IndentManipulation.changeIndent(code.substring(firstNonWhiteSpace, lastNonWhiteSpace+1), indent, tabWidth, indentWidth, "", lineDelimiter); //$NON-NLS-1$
-}
-/*
- * Renames the given node to the given name.
- * Returns the old name.
- */
-protected abstract SimpleName rename(ASTNode node, SimpleName newName);
-/**
- * Generates an <code>ASTNode</code> based on the source of this operation
- * when there is likely a syntax error in the source.
- * Returns the source used to generate this node.
- */
-protected String generateSyntaxIncorrectAST() {
- //create some dummy source to generate an ast node
- StringBuffer buff = new StringBuffer();
-// IType type = getType();
-// String lineSeparator = org.eclipse.wst.jsdt.internal.core.util.Util.getLineSeparator(this.source, type == null ? null : type.getJavaProject());
-// buff.append(lineSeparator + " public class A {" + lineSeparator); //$NON-NLS-1$
- buff.append(this.source);
-// buff.append(lineSeparator).append('}');
- ASTParser parser = ASTParser.newParser(AST.JLS3);
- parser.setSource(buff.toString().toCharArray());
- JavaScriptUnit compilationUnit = (JavaScriptUnit) parser.createAST(null);
-
-// TypeDeclaration typeDeclaration = (TypeDeclaration) compilationUnit.types().iterator().next();
- List statements = compilationUnit.statements() ;
- if (statements.size() != 0)
- this.createdNode = (ASTNode) statements.iterator().next();
- return buff.toString();
-}
-/**
- * Returns the IType the member is to be created in.
- */
-protected IType getType() {
- IJavaScriptElement parentElement = getParentElement();
- return (parentElement instanceof IType) ? (IType)parentElement : null;
-}
-/**
- * Sets the name of the <code>ASTNode</code> that will be used to
- * create this new element.
- * Used by the <code>CopyElementsOperation</code> for renaming
- */
-protected void setAlteredName(String newName) {
- this.alteredName = newName;
-}
-/**
- * Possible failures: <ul>
- * <li>NO_ELEMENTS_TO_PROCESS - the parent element supplied to the operation is
- * <code>null</code>.
- * <li>INVALID_CONTENTS - The source is <code>null</code> or has serious syntax errors.
- * <li>NAME_COLLISION - A name collision occurred in the destination
- * </ul>
- */
-public IJavaScriptModelStatus verify() {
- IJavaScriptModelStatus status = super.verify();
- if (!status.isOK()) {
- return status;
- }
- if (this.source == null) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_CONTENTS);
- }
- if (!force) {
- //check for name collisions
- try {
- IJavaScriptUnit cu = getCompilationUnit();
- generateElementAST(null, getDocument(cu), cu);
- } catch (JavaScriptModelException jme) {
- return jme.getJavaScriptModelStatus();
- }
- return verifyNameCollision();
- }
-
- return JavaModelStatus.VERIFIED_OK;
-}
-/**
- * Verify for a name collision in the destination container.
- */
-protected IJavaScriptModelStatus verifyNameCollision() {
- return JavaModelStatus.VERIFIED_OK;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreateTypeOperation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreateTypeOperation.java
deleted file mode 100644
index 7f1fb580..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CreateTypeOperation.java
+++ /dev/null
@@ -1,115 +0,0 @@
-/*******************************************************************************
- * 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.jface.text.IDocument;
-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.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-
-/**
- * <p>This operation creates a class or interface.
- *
- * <p>Required Attributes:<ul>
- * <li>Parent element - must be a compilation unit, or type.
- * <li>The source code for the type. No verification of the source is
- * performed.
- * </ul>
- */
-public class CreateTypeOperation extends CreateTypeMemberOperation {
-/**
- * When executed, this operation will create a type unit
- * in the given parent element (a compilation unit, type)
- */
-public CreateTypeOperation(IJavaScriptElement parentElement, String source, boolean force) {
- super(parentElement, source, force);
-}
-protected ASTNode generateElementAST(ASTRewrite rewriter, IDocument document, IJavaScriptUnit cu) throws JavaScriptModelException {
- ASTNode node = super.generateElementAST(rewriter, document, cu);
- if (!(node instanceof AbstractTypeDeclaration))
- throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_CONTENTS));
- return node;
-}
-
-/**
- * @see CreateElementInCUOperation#generateResultHandle()
- */
-protected IJavaScriptElement generateResultHandle() {
- IJavaScriptElement parent= getParentElement();
- switch (parent.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- return ((IJavaScriptUnit)parent).getType(getASTNodeName());
- case IJavaScriptElement.TYPE:
- return ((IType)parent).getType(getASTNodeName());
- // Note: creating local/anonymous type is not supported
- }
- return null;
-}
-/**
- * @see CreateElementInCUOperation#getMainTaskName()
- */
-public String getMainTaskName(){
- return Messages.operation_createTypeProgress;
-}
-/**
- * Returns the <code>IType</code> the member is to be created in.
- */
-protected IType getType() {
- IJavaScriptElement parent = getParentElement();
- if (parent.getElementType() == IJavaScriptElement.TYPE) {
- return (IType) parent;
- }
- return null;
-}
-/**
- * @see CreateTypeMemberOperation#verifyNameCollision
- */
-protected IJavaScriptModelStatus verifyNameCollision() {
- IJavaScriptElement parent = getParentElement();
- switch (parent.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- String typeName = getASTNodeName();
- if (((IJavaScriptUnit) parent).getType(typeName).exists()) {
- return new JavaModelStatus(
- IJavaScriptModelStatusConstants.NAME_COLLISION,
- Messages.bind(Messages.status_nameCollision, typeName));
- }
- break;
- case IJavaScriptElement.TYPE:
- typeName = getASTNodeName();
- if (((IType) parent).getType(typeName).exists()) {
- return new JavaModelStatus(
- IJavaScriptModelStatusConstants.NAME_COLLISION,
- Messages.bind(Messages.status_nameCollision, typeName));
- }
- break;
- // Note: creating local/anonymous type is not supported
- }
- return JavaModelStatus.VERIFIED_OK;
-}
-private String getASTNodeName() {
- return ((AbstractTypeDeclaration) this.createdNode).getName().getIdentifier();
-}
-protected SimpleName rename(ASTNode node, SimpleName newName) {
- AbstractTypeDeclaration type = (AbstractTypeDeclaration) node;
- SimpleName oldName = type.getName();
- type.setName(newName);
- return oldName;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DefaultWorkingCopyOwner.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DefaultWorkingCopyOwner.java
deleted file mode 100644
index 1f55d0ab..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DefaultWorkingCopyOwner.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*******************************************************************************
- * 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.core.IBuffer;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-
-/**
- * A working copy owner that creates internal buffers.
- * It also defines the PRIMARY working copy owner that is used by JDT/Core.
- */
-public class DefaultWorkingCopyOwner extends WorkingCopyOwner {
-
- public WorkingCopyOwner primaryBufferProvider;
-
- public static final DefaultWorkingCopyOwner PRIMARY = new DefaultWorkingCopyOwner();
-
- private DefaultWorkingCopyOwner() {
- // only one instance can be created
- }
-
- public IBuffer createBuffer(IJavaScriptUnit workingCopy) {
- if (this.primaryBufferProvider != null) return this.primaryBufferProvider.createBuffer(workingCopy);
- return super.createBuffer(workingCopy);
- }
- public String toString() {
- return "Primary owner"; //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DeleteElementsOperation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DeleteElementsOperation.java
deleted file mode 100644
index 53756d5a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DeleteElementsOperation.java
+++ /dev/null
@@ -1,195 +0,0 @@
-/*******************************************************************************
- * 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 java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.jobs.ISchedulingRule;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatusConstants;
-import org.eclipse.wst.jsdt.core.IRegion;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-
-/**
- * This operation deletes a collection of elements (and
- * all of their children).
- * If an element does not exist, it is ignored.
- *
- * <p>NOTE: This operation only deletes elements contained within leaf resources -
- * that is, elements within compilation units. To delete a compilation unit or
- * a package, etc (which have an actual resource), a DeleteResourcesOperation
- * should be used.
- */
-public class DeleteElementsOperation extends MultiOperation {
- /**
- * The elements this operation processes grouped by compilation unit
- * @see #processElements() Keys are compilation units,
- * values are <code>IRegion</code>s of elements to be processed in each
- * compilation unit.
- */
- protected Map childrenToRemove;
- /**
- * The <code>ASTParser</code> used to manipulate the source code of
- * <code>IJavaScriptUnit</code>.
- */
- protected ASTParser parser;
- /**
- * When executed, this operation will delete the given elements. The elements
- * to delete cannot be <code>null</code> or empty, and must be contained within a
- * compilation unit.
- */
- public DeleteElementsOperation(IJavaScriptElement[] elementsToDelete, boolean force) {
- super(elementsToDelete, force);
- initASTParser();
- }
-
- private void deleteElement(IJavaScriptElement elementToRemove, IJavaScriptUnit cu) throws JavaScriptModelException {
- // ensure cu is consistent (noop if already consistent)
- cu.makeConsistent(this.progressMonitor);
- this.parser.setSource(cu);
- JavaScriptUnit astCU = (JavaScriptUnit) this.parser.createAST(this.progressMonitor);
- ASTNode node = ((JavaElement) elementToRemove).findNode(astCU);
- if (node == null)
- Assert.isTrue(false, "Failed to locate " + elementToRemove.getElementName() + " in " + cu.getElementName()); //$NON-NLS-1$//$NON-NLS-2$
- IDocument document = getDocument(cu);
- AST ast = astCU.getAST();
- ASTRewrite rewriter = ASTRewrite.create(ast);
- rewriter.remove(node, null);
- TextEdit edits = rewriter.rewriteAST(document, null);
- try {
- edits.apply(document);
- } catch (BadLocationException e) {
- throw new JavaScriptModelException(e, IJavaScriptModelStatusConstants.INVALID_CONTENTS);
- }
- }
-
- private void initASTParser() {
- this.parser = ASTParser.newParser(AST.JLS3);
- }
-
- /**
- * @see MultiOperation
- */
- protected String getMainTaskName() {
- return Messages.operation_deleteElementProgress;
- }
- protected ISchedulingRule getSchedulingRule() {
- if (this.elementsToProcess != null && this.elementsToProcess.length == 1) {
- IResource resource = this.elementsToProcess[0].getResource();
- if (resource != null)
- return ResourcesPlugin.getWorkspace().getRuleFactory().modifyRule(resource);
- }
- return super.getSchedulingRule();
- }
- /**
- * Groups the elements to be processed by their compilation unit.
- * If parent/child combinations are present, children are
- * discarded (only the parents are processed). Removes any
- * duplicates specified in elements to be processed.
- */
- protected void groupElements() throws JavaScriptModelException {
- childrenToRemove = new HashMap(1);
- int uniqueCUs = 0;
- for (int i = 0, length = elementsToProcess.length; i < length; i++) {
- IJavaScriptElement e = elementsToProcess[i];
- IJavaScriptUnit cu = getCompilationUnitFor(e);
- if (cu == null) {
- throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.READ_ONLY, e));
- } else {
- IRegion region = (IRegion) childrenToRemove.get(cu);
- if (region == null) {
- region = new Region();
- childrenToRemove.put(cu, region);
- uniqueCUs += 1;
- }
- region.add(e);
- }
- }
- elementsToProcess = new IJavaScriptElement[uniqueCUs];
- Iterator iter = childrenToRemove.keySet().iterator();
- int i = 0;
- while (iter.hasNext()) {
- elementsToProcess[i++] = (IJavaScriptElement) iter.next();
- }
- }
- /**
- * Deletes this element from its compilation unit.
- * @see MultiOperation
- */
- protected void processElement(IJavaScriptElement element) throws JavaScriptModelException {
- IJavaScriptUnit cu = (IJavaScriptUnit) element;
-
- // keep track of the import statements - if all are removed, delete
- // the import container (and report it in the delta)
- int numberOfImports = cu.getImports().length;
-
- JavaElementDelta delta = new JavaElementDelta(cu);
- IJavaScriptElement[] cuElements = ((IRegion) childrenToRemove.get(cu)).getElements();
- for (int i = 0, length = cuElements.length; i < length; i++) {
- IJavaScriptElement e = cuElements[i];
- if (e.exists()) {
- deleteElement(e, cu);
- delta.removed(e);
- if (e.getElementType() == IJavaScriptElement.IMPORT_DECLARATION) {
- numberOfImports--;
- if (numberOfImports == 0) {
- delta.removed(cu.getImportContainer());
- }
- }
- }
- }
- if (delta.getAffectedChildren().length > 0) {
- cu.save(getSubProgressMonitor(1), force);
- if (!cu.isWorkingCopy()) { // if unit is working copy, then save will have already fired the delta
- addDelta(delta);
- setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
- }
- }
- }
- /**
- * @see MultiOperation
- * This method first group the elements by <code>IJavaScriptUnit</code>,
- * and then processes the <code>IJavaScriptUnit</code>.
- */
- protected void processElements() throws JavaScriptModelException {
- groupElements();
- super.processElements();
- }
- /**
- * @see MultiOperation
- */
- protected void verify(IJavaScriptElement element) throws JavaScriptModelException {
- IJavaScriptElement[] children = ((IRegion) childrenToRemove.get(element)).getElements();
- for (int i = 0; i < children.length; i++) {
- IJavaScriptElement child = children[i];
- if (child.getCorrespondingResource() != null)
- error(IJavaScriptModelStatusConstants.INVALID_ELEMENT_TYPES, child);
-
- if (child.isReadOnly())
- error(IJavaScriptModelStatusConstants.READ_ONLY, child);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DeletePackageFragmentRootOperation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DeletePackageFragmentRootOperation.java
deleted file mode 100644
index 6da62f8f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DeletePackageFragmentRootOperation.java
+++ /dev/null
@@ -1,173 +0,0 @@
-/*******************************************************************************
- * 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 java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceProxy;
-import org.eclipse.core.resources.IResourceProxyVisitor;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-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.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-
-public class DeletePackageFragmentRootOperation extends JavaModelOperation {
-
- int updateResourceFlags;
- int updateModelFlags;
-
- public DeletePackageFragmentRootOperation(
- IPackageFragmentRoot root,
- int updateResourceFlags,
- int updateModelFlags) {
-
- super(root);
- this.updateResourceFlags = updateResourceFlags;
- this.updateModelFlags = updateModelFlags;
- }
-
- protected void executeOperation() throws JavaScriptModelException {
-
- IPackageFragmentRoot root = (IPackageFragmentRoot)this.getElementToProcess();
- IIncludePathEntry rootEntry = root.getRawIncludepathEntry();
-
- // remember olds roots
- DeltaProcessor deltaProcessor = JavaModelManager.getJavaModelManager().getDeltaProcessor();
- if (deltaProcessor.oldRoots == null)
- deltaProcessor.oldRoots = new HashMap();
-
- // update classpath if needed
- if ((updateModelFlags & IPackageFragmentRoot.ORIGINATING_PROJECT_INCLUDEPATH) != 0) {
- updateProjectClasspath(rootEntry.getPath(), root.getJavaScriptProject(), deltaProcessor.oldRoots);
- }
- if ((updateModelFlags & IPackageFragmentRoot.OTHER_REFERRING_PROJECTS_INCLUDEPATH) != 0) {
- updateReferringProjectClasspaths(rootEntry.getPath(), root.getJavaScriptProject(), deltaProcessor.oldRoots);
- }
-
- // delete resource
- if (!root.isExternal() && (this.updateModelFlags & IPackageFragmentRoot.NO_RESOURCE_MODIFICATION) == 0) {
- deleteResource(root, rootEntry);
- }
- }
-
- protected void deleteResource(
- IPackageFragmentRoot root,
- IIncludePathEntry rootEntry)
- throws JavaScriptModelException {
- final char[][] exclusionPatterns = ((ClasspathEntry)rootEntry).fullExclusionPatternChars();
- IResource rootResource = root.getResource();
- if (rootEntry.getEntryKind() != IIncludePathEntry.CPE_SOURCE || exclusionPatterns == null) {
- try {
- rootResource.delete(this.updateResourceFlags, progressMonitor);
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- }
- } else {
- final IPath[] nestedFolders = getNestedFolders(root);
- IResourceProxyVisitor visitor = new IResourceProxyVisitor() {
- public boolean visit(IResourceProxy proxy) throws CoreException {
- if (proxy.getType() == IResource.FOLDER) {
- IPath path = proxy.requestFullPath();
- if (prefixesOneOf(path, nestedFolders)) {
- // equals if nested source folder
- return !equalsOneOf(path, nestedFolders);
- } else {
- // subtree doesn't contain any nested source folders
- proxy.requestResource().delete(updateResourceFlags, progressMonitor);
- return false;
- }
- } else {
- proxy.requestResource().delete(updateResourceFlags, progressMonitor);
- return false;
- }
- }
- };
- try {
- rootResource.accept(visitor, IResource.NONE);
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- }
- }
- setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
- }
-
-
- /*
- * Deletes the classpath entries equals to the given rootPath from all Java projects.
- */
- protected void updateReferringProjectClasspaths(IPath rootPath, IJavaScriptProject projectOfRoot, Map oldRoots) throws JavaScriptModelException {
- IJavaScriptModel model = this.getJavaModel();
- IJavaScriptProject[] projects = model.getJavaScriptProjects();
- for (int i = 0, length = projects.length; i < length; i++) {
- IJavaScriptProject project = projects[i];
- if (project.equals(projectOfRoot)) continue;
- updateProjectClasspath(rootPath, project, oldRoots);
- }
- }
-
- /*
- * Deletes the classpath entries equals to the given rootPath from the given project.
- */
- protected void updateProjectClasspath(IPath rootPath, IJavaScriptProject project, Map oldRoots) throws JavaScriptModelException {
- // remember old roots
- oldRoots.put(project, project.getPackageFragmentRoots());
-
- IIncludePathEntry[] classpath = project.getRawIncludepath();
- IIncludePathEntry[] newClasspath = null;
- int cpLength = classpath.length;
- int newCPIndex = -1;
- for (int j = 0; j < cpLength; j++) {
- IIncludePathEntry entry = classpath[j];
- if (rootPath.equals(entry.getPath())) {
- if (newClasspath == null) {
- newClasspath = new IIncludePathEntry[cpLength-1];
- System.arraycopy(classpath, 0, newClasspath, 0, j);
- newCPIndex = j;
- }
- } else if (newClasspath != null) {
- newClasspath[newCPIndex++] = entry;
- }
- }
- if (newClasspath != null) {
- if (newCPIndex < newClasspath.length) {
- System.arraycopy(newClasspath, 0, newClasspath = new IIncludePathEntry[newCPIndex], 0, newCPIndex);
- }
- project.setRawIncludepath(newClasspath, progressMonitor);
- }
- }
- protected IJavaScriptModelStatus verify() {
- IJavaScriptModelStatus status = super.verify();
- if (!status.isOK()) {
- return status;
- }
- IPackageFragmentRoot root = (IPackageFragmentRoot) this.getElementToProcess();
- if (root == null || !root.exists()) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.ELEMENT_DOES_NOT_EXIST, root);
- }
-
- IResource resource = root.getResource();
- if (resource instanceof IFolder) {
- if (resource.isLinked()) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_RESOURCE, root);
- }
- }
- return JavaModelStatus.VERIFIED_OK;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DeleteResourceElementsOperation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DeleteResourceElementsOperation.java
deleted file mode 100644
index 431adeac..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DeleteResourceElementsOperation.java
+++ /dev/null
@@ -1,142 +0,0 @@
-/*******************************************************************************
- * 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.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatusConstants;
-import org.eclipse.wst.jsdt.core.IOpenable;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-
-/**
- * This operation deletes a collection of resources and all of their children.
- * It does not delete resources which do not belong to the Java Model
- * (eg GIF files).
- */
-public class DeleteResourceElementsOperation extends MultiOperation {
-/**
- * When executed, this operation will delete the given elements. The elements
- * to delete cannot be <code>null</code> or empty, and must have a corresponding
- * resource.
- */
-protected DeleteResourceElementsOperation(IJavaScriptElement[] elementsToProcess, boolean force) {
- super(elementsToProcess, force);
-}
-/**
- * Deletes the direct children of <code>frag</code> corresponding to its kind
- * (K_SOURCE or K_BINARY), and deletes the corresponding folder if it is then
- * empty.
- */
-private void deletePackageFragment(IPackageFragment frag)
- throws JavaScriptModelException {
- IResource res = frag.getResource();
- if (res != null) {
- // collect the children to remove
- IJavaScriptElement[] childrenOfInterest = frag.getChildren();
- if (childrenOfInterest.length > 0) {
- IResource[] resources = new IResource[childrenOfInterest.length];
- // remove the children
- for (int i = 0; i < childrenOfInterest.length; i++) {
- resources[i] = childrenOfInterest[i].getCorrespondingResource();
- }
- deleteResources(resources, force);
- }
-
- // Discard non-java resources
- Object[] nonJavaResources = frag.getNonJavaScriptResources();
- int actualResourceCount = 0;
- for (int i = 0, max = nonJavaResources.length; i < max; i++){
- if (nonJavaResources[i] instanceof IResource) actualResourceCount++;
- }
- IResource[] actualNonJavaResources = new IResource[actualResourceCount];
- for (int i = 0, max = nonJavaResources.length, index = 0; i < max; i++){
- if (nonJavaResources[i] instanceof IResource) actualNonJavaResources[index++] = (IResource)nonJavaResources[i];
- }
- deleteResources(actualNonJavaResources, force);
-
- // delete remaining files in this package (.class file in the case where Proj=src=bin)
- IResource[] remainingFiles;
- try {
- remainingFiles = ((IContainer) res).members();
- } catch (CoreException ce) {
- throw new JavaScriptModelException(ce);
- }
- boolean isEmpty = true;
- for (int i = 0, length = remainingFiles.length; i < length; i++) {
- IResource file = remainingFiles[i];
- if (file instanceof IFile && org.eclipse.wst.jsdt.internal.compiler.util.Util.isClassFileName(file.getName())) {
- this.deleteResource(file, IResource.FORCE | IResource.KEEP_HISTORY);
- } else {
- isEmpty = false;
- }
- }
- if (isEmpty && !frag.isDefaultPackage()/*don't delete default package's folder: see https://bugs.eclipse.org/bugs/show_bug.cgi?id=38450*/) {
- // delete recursively empty folders
- IResource fragResource = frag.getResource();
- if (fragResource != null) {
- deleteEmptyPackageFragment(frag, false, fragResource.getParent());
- }
- }
- }
-}
-/**
- * @see MultiOperation
- */
-protected String getMainTaskName() {
- return Messages.operation_deleteResourceProgress;
-}
-/**
- * @see MultiOperation This method delegate to <code>deleteResource</code> or
- * <code>deletePackageFragment</code> depending on the type of <code>element</code>.
- */
-protected void processElement(IJavaScriptElement element) throws JavaScriptModelException {
- switch (element.getElementType()) {
- case IJavaScriptElement.CLASS_FILE :
- case IJavaScriptElement.JAVASCRIPT_UNIT :
- deleteResource(element.getResource(), force ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY);
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT :
- deletePackageFragment((IPackageFragment) element);
- break;
- default :
- throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_ELEMENT_TYPES, element));
- }
- // ensure the element is closed
- if (element instanceof IOpenable) {
- ((IOpenable)element).close();
- }
-}
-/**
- * @see MultiOperation
- */
-protected void verify(IJavaScriptElement element) throws JavaScriptModelException {
- if (element == null || !element.exists())
- error(IJavaScriptModelStatusConstants.ELEMENT_DOES_NOT_EXIST, element);
-
- int type = element.getElementType();
- if (type <= IJavaScriptElement.PACKAGE_FRAGMENT_ROOT || type > IJavaScriptElement.JAVASCRIPT_UNIT)
- error(IJavaScriptModelStatusConstants.INVALID_ELEMENT_TYPES, element);
-// else if (type == IJavaScriptElement.PACKAGE_FRAGMENT && element instanceof JarPackageFragment)
-// error(IJavaScriptModelStatusConstants.INVALID_ELEMENT_TYPES, element);
- IResource resource = element.getResource();
- if (resource instanceof IFolder) {
- if (resource.isLinked()) {
- error(IJavaScriptModelStatusConstants.INVALID_RESOURCE, element);
- }
- }
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DeltaProcessingState.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DeltaProcessingState.java
deleted file mode 100644
index ff7dfd9e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DeltaProcessingState.java
+++ /dev/null
@@ -1,539 +0,0 @@
-/*******************************************************************************
- * 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 java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.DataInputStream;
-import java.io.DataOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.resources.IResourceChangeEvent;
-import org.eclipse.core.resources.IResourceChangeListener;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.ISafeRunnable;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.SafeRunner;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IElementChangedListener;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * Keep the global states used during Java element delta processing.
- */
-public class DeltaProcessingState implements IResourceChangeListener {
-
- /*
- * Collection of listeners for Java element deltas
- */
- public IElementChangedListener[] elementChangedListeners = new IElementChangedListener[5];
- public int[] elementChangedListenerMasks = new int[5];
- public int elementChangedListenerCount = 0;
-
- /*
- * Collection of pre Java resource change listeners
- */
- public IResourceChangeListener[] preResourceChangeListeners = new IResourceChangeListener[1];
- public int[] preResourceChangeEventMasks = new int[1];
- public int preResourceChangeListenerCount = 0;
-
- /*
- * The delta processor for the current thread.
- */
- private ThreadLocal deltaProcessors = new ThreadLocal();
-
- /* A table from IPath (from a classpath entry) to DeltaProcessor.RootInfo */
- public HashMap roots = new HashMap();
-
- /* A table from IPath (from a classpath entry) to ArrayList of DeltaProcessor.RootInfo
- * Used when an IPath corresponds to more than one root */
- public HashMap otherRoots = new HashMap();
-
- /* A table from IPath (from a classpath entry) to DeltaProcessor.RootInfo
- * from the last time the delta processor was invoked. */
- public HashMap oldRoots = new HashMap();
-
- /* A table from IPath (from a classpath entry) to ArrayList of DeltaProcessor.RootInfo
- * from the last time the delta processor was invoked.
- * Used when an IPath corresponds to more than one root */
- public HashMap oldOtherRoots = new HashMap();
-
- /* A table from IPath (a source attachment path from a classpath entry) to IPath (a root path) */
- public HashMap sourceAttachments = new HashMap();
-
- /* A table from IJavaScriptProject to IJavaScriptProject[] (the list of direct dependent of the key) */
- public HashMap projectDependencies = new HashMap();
-
- /* Whether the roots tables should be recomputed */
- public boolean rootsAreStale = true;
-
- /* Threads that are currently running initializeRoots() */
- private Set initializingThreads = Collections.synchronizedSet(new HashSet());
-
- /* A table from file system absoulte path (String) to timestamp (Long) */
- public Hashtable externalTimeStamps;
-
- /* A table from JavaProject to ClasspathValidation */
- private HashMap classpathValidations = new HashMap();
-
- /* A table from JavaProject to ProjectReferenceChange */
- private HashMap projectReferenceChanges= new HashMap();
-
- /**
- * Workaround for bug 15168 circular errors not reported
- * This is a cache of the projects before any project addition/deletion has started.
- */
- private HashSet javaProjectNamesCache;
-
- /*
- * Need to clone defensively the listener information, in case some listener is reacting to some notification iteration by adding/changing/removing
- * any of the other (for example, if it deregisters itself).
- */
- public synchronized void addElementChangedListener(IElementChangedListener listener, int eventMask) {
- for (int i = 0; i < this.elementChangedListenerCount; i++){
- if (this.elementChangedListeners[i] == listener){
-
- // only clone the masks, since we could be in the middle of notifications and one listener decide to change
- // any event mask of another listeners (yet not notified).
- int cloneLength = this.elementChangedListenerMasks.length;
- System.arraycopy(this.elementChangedListenerMasks, 0, this.elementChangedListenerMasks = new int[cloneLength], 0, cloneLength);
- this.elementChangedListenerMasks[i] |= eventMask; // could be different
- return;
- }
- }
- // may need to grow, no need to clone, since iterators will have cached original arrays and max boundary and we only add to the end.
- int length;
- if ((length = this.elementChangedListeners.length) == this.elementChangedListenerCount){
- System.arraycopy(this.elementChangedListeners, 0, this.elementChangedListeners = new IElementChangedListener[length*2], 0, length);
- System.arraycopy(this.elementChangedListenerMasks, 0, this.elementChangedListenerMasks = new int[length*2], 0, length);
- }
- this.elementChangedListeners[this.elementChangedListenerCount] = listener;
- this.elementChangedListenerMasks[this.elementChangedListenerCount] = eventMask;
- this.elementChangedListenerCount++;
- }
-
- public synchronized void addPreResourceChangedListener(IResourceChangeListener listener, int eventMask) {
- for (int i = 0; i < this.preResourceChangeListenerCount; i++){
- if (this.preResourceChangeListeners[i] == listener) {
- this.preResourceChangeEventMasks[i] |= eventMask;
- return;
- }
- }
- // may need to grow, no need to clone, since iterators will have cached original arrays and max boundary and we only add to the end.
- int length;
- if ((length = this.preResourceChangeListeners.length) == this.preResourceChangeListenerCount) {
- System.arraycopy(this.preResourceChangeListeners, 0, this.preResourceChangeListeners = new IResourceChangeListener[length*2], 0, length);
- System.arraycopy(this.preResourceChangeEventMasks, 0, this.preResourceChangeEventMasks = new int[length*2], 0, length);
- }
- this.preResourceChangeListeners[this.preResourceChangeListenerCount] = listener;
- this.preResourceChangeEventMasks[this.preResourceChangeListenerCount] = eventMask;
- this.preResourceChangeListenerCount++;
- }
-
- public DeltaProcessor getDeltaProcessor() {
- DeltaProcessor deltaProcessor = (DeltaProcessor)this.deltaProcessors.get();
- if (deltaProcessor != null) return deltaProcessor;
- deltaProcessor = new DeltaProcessor(this, JavaModelManager.getJavaModelManager());
- this.deltaProcessors.set(deltaProcessor);
- return deltaProcessor;
- }
-
- public synchronized ClasspathValidation addClasspathValidation(JavaProject project) {
- ClasspathValidation validation = (ClasspathValidation) this.classpathValidations.get(project);
- if (validation == null) {
- validation = new ClasspathValidation(project);
- this.classpathValidations.put(project, validation);
- }
- return validation;
- }
-
- public synchronized void addProjectReferenceChange(JavaProject project, IIncludePathEntry[] oldResolvedClasspath) {
- ProjectReferenceChange change = (ProjectReferenceChange) this.projectReferenceChanges.get(project);
- if (change == null) {
- change = new ProjectReferenceChange(project, oldResolvedClasspath);
- this.projectReferenceChanges.put(project, change);
- }
- }
-
- public void initializeRoots() {
-
- // recompute root infos only if necessary
- HashMap newRoots = null;
- HashMap newOtherRoots = null;
- HashMap newSourceAttachments = null;
- HashMap newProjectDependencies = null;
- if (this.rootsAreStale) {
- Thread currentThread = Thread.currentThread();
- boolean addedCurrentThread = false;
- try {
- // if reentering initialization (through a container initializer for example) no need to compute roots again
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=47213
- if (!this.initializingThreads.add(currentThread)) return;
- addedCurrentThread = true;
-
- // all classpaths in the workspace are going to be resolved
- // ensure that containers are initialized in one batch
- JavaModelManager.getJavaModelManager().batchContainerInitializations = true;
-
- newRoots = new HashMap();
- newOtherRoots = new HashMap();
- newSourceAttachments = new HashMap();
- newProjectDependencies = new HashMap();
-
- IJavaScriptModel model = JavaModelManager.getJavaModelManager().getJavaModel();
- IJavaScriptProject[] projects;
- try {
- projects = model.getJavaScriptProjects();
- } catch (JavaScriptModelException e) {
- // nothing can be done
- return;
- }
- for (int i = 0, length = projects.length; i < length; i++) {
- JavaProject project = (JavaProject) projects[i];
- IIncludePathEntry[] classpath;
- try {
- classpath = project.getResolvedClasspath();
- } catch (JavaScriptModelException e) {
- // continue with next project
- continue;
- }
- for (int j= 0, classpathLength = classpath.length; j < classpathLength; j++) {
- IIncludePathEntry entry = classpath[j];
- if (entry.getEntryKind() == IIncludePathEntry.CPE_PROJECT) {
- IJavaScriptProject key = model.getJavaScriptProject(entry.getPath().segment(0)); // TODO (jerome) reuse handle
- IJavaScriptProject[] dependents = (IJavaScriptProject[]) newProjectDependencies.get(key);
- if (dependents == null) {
- dependents = new IJavaScriptProject[] {project};
- } else {
- int dependentsLength = dependents.length;
- System.arraycopy(dependents, 0, dependents = new IJavaScriptProject[dependentsLength+1], 0, dependentsLength);
- dependents[dependentsLength] = project;
- }
- newProjectDependencies.put(key, dependents);
- continue;
- }
-
- // root path
- IPath path = entry.getPath();
- if (newRoots.get(path) == null) {
- newRoots.put(path, new DeltaProcessor.RootInfo(project, path, ((ClasspathEntry)entry).fullInclusionPatternChars(), ((ClasspathEntry)entry).fullExclusionPatternChars(), entry.getEntryKind()));
- } else {
- ArrayList rootList = (ArrayList)newOtherRoots.get(path);
- if (rootList == null) {
- rootList = new ArrayList();
- newOtherRoots.put(path, rootList);
- }
- rootList.add(new DeltaProcessor.RootInfo(project, path, ((ClasspathEntry)entry).fullInclusionPatternChars(), ((ClasspathEntry)entry).fullExclusionPatternChars(), entry.getEntryKind()));
- }
-
- // source attachment path
- if (entry.getEntryKind() != IIncludePathEntry.CPE_LIBRARY) continue;
- String propertyString = null;
- try {
- propertyString = Util.getSourceAttachmentProperty(path);
- } catch (JavaScriptModelException e) {
- e.printStackTrace();
- }
- IPath sourceAttachmentPath;
- if (propertyString != null) {
- int index= propertyString.lastIndexOf(PackageFragmentRoot.ATTACHMENT_PROPERTY_DELIMITER);
- sourceAttachmentPath = (index < 0) ? new Path(propertyString) : new Path(propertyString.substring(0, index));
- } else {
- sourceAttachmentPath = entry.getSourceAttachmentPath();
- }
- if (sourceAttachmentPath != null) {
- newSourceAttachments.put(sourceAttachmentPath, path);
- }
- }
- }
- } finally {
- if (addedCurrentThread) {
- this.initializingThreads.remove(currentThread);
- }
- }
- }
- synchronized(this) {
- this.oldRoots = this.roots;
- this.oldOtherRoots = this.otherRoots;
- if (this.rootsAreStale && newRoots != null) { // double check again
- this.roots = newRoots;
- this.otherRoots = newOtherRoots;
- this.sourceAttachments = newSourceAttachments;
- this.projectDependencies = newProjectDependencies;
- this.rootsAreStale = false;
- }
- }
- }
-
- public synchronized ClasspathValidation[] removeClasspathValidations() {
- int length = this.classpathValidations.size();
- if (length == 0) return null;
- ClasspathValidation[] validations = new ClasspathValidation[length];
- this.classpathValidations.values().toArray(validations);
- this.classpathValidations.clear();
- return validations;
- }
-
- public synchronized ProjectReferenceChange[] removeProjectReferenceChanges() {
- int length = this.projectReferenceChanges.size();
- if (length == 0) return null;
- ProjectReferenceChange[] updates = new ProjectReferenceChange[length];
- this.projectReferenceChanges.values().toArray(updates);
- this.projectReferenceChanges.clear();
- return updates;
- }
-
- public synchronized void removeElementChangedListener(IElementChangedListener listener) {
-
- for (int i = 0; i < this.elementChangedListenerCount; i++){
-
- if (this.elementChangedListeners[i] == listener){
-
- // need to clone defensively since we might be in the middle of listener notifications (#fire)
- int length = this.elementChangedListeners.length;
- IElementChangedListener[] newListeners = new IElementChangedListener[length];
- System.arraycopy(this.elementChangedListeners, 0, newListeners, 0, i);
- int[] newMasks = new int[length];
- System.arraycopy(this.elementChangedListenerMasks, 0, newMasks, 0, i);
-
- // copy trailing listeners
- int trailingLength = this.elementChangedListenerCount - i - 1;
- if (trailingLength > 0){
- System.arraycopy(this.elementChangedListeners, i+1, newListeners, i, trailingLength);
- System.arraycopy(this.elementChangedListenerMasks, i+1, newMasks, i, trailingLength);
- }
-
- // update manager listener state (#fire need to iterate over original listeners through a local variable to hold onto
- // the original ones)
- this.elementChangedListeners = newListeners;
- this.elementChangedListenerMasks = newMasks;
- this.elementChangedListenerCount--;
- return;
- }
- }
- }
-
- public synchronized void removePreResourceChangedListener(IResourceChangeListener listener) {
-
- for (int i = 0; i < this.preResourceChangeListenerCount; i++){
-
- if (this.preResourceChangeListeners[i] == listener){
-
- // need to clone defensively since we might be in the middle of listener notifications (#fire)
- int length = this.preResourceChangeListeners.length;
- IResourceChangeListener[] newListeners = new IResourceChangeListener[length];
- int[] newEventMasks = new int[length];
- System.arraycopy(this.preResourceChangeListeners, 0, newListeners, 0, i);
- System.arraycopy(this.preResourceChangeEventMasks, 0, newEventMasks, 0, i);
-
- // copy trailing listeners
- int trailingLength = this.preResourceChangeListenerCount - i - 1;
- if (trailingLength > 0) {
- System.arraycopy(this.preResourceChangeListeners, i+1, newListeners, i, trailingLength);
- System.arraycopy(this.preResourceChangeEventMasks, i+1, newEventMasks, i, trailingLength);
- }
-
- // update manager listener state (#fire need to iterate over original listeners through a local variable to hold onto
- // the original ones)
- this.preResourceChangeListeners = newListeners;
- this.preResourceChangeEventMasks = newEventMasks;
- this.preResourceChangeListenerCount--;
- return;
- }
- }
- }
-
- public void resourceChanged(final IResourceChangeEvent event) {
- for (int i = 0; i < this.preResourceChangeListenerCount; i++) {
- // wrap callbacks with Safe runnable for subsequent listeners to be called when some are causing grief
- final IResourceChangeListener listener = this.preResourceChangeListeners[i];
- if ((this.preResourceChangeEventMasks[i] & event.getType()) != 0)
- SafeRunner.run(new ISafeRunnable() {
- public void handleException(Throwable exception) {
- Util.log(exception, "Exception occurred in listener of pre Java resource change notification"); //$NON-NLS-1$
- }
- public void run() throws Exception {
- listener.resourceChanged(event);
- }
- });
- }
- try {
- getDeltaProcessor().resourceChanged(event);
- } finally {
- // TODO (jerome) see 47631, may want to get rid of following so as to reuse delta processor ?
- if (event.getType() == IResourceChangeEvent.POST_CHANGE) {
- this.deltaProcessors.set(null);
- }
- }
-
- }
-
- public Hashtable getExternalLibTimeStamps() {
- if (this.externalTimeStamps == null) {
- Hashtable timeStamps = new Hashtable();
- File timestampsFile = getTimeStampsFile();
- DataInputStream in = null;
- try {
- in = new DataInputStream(new BufferedInputStream(new FileInputStream(timestampsFile)));
- int size = in.readInt();
- while (size-- > 0) {
- String key = in.readUTF();
- long timestamp = in.readLong();
- timeStamps.put(Path.fromPortableString(key), new Long(timestamp));
- }
- } catch (IOException e) {
- if (timestampsFile.exists())
- Util.log(e, "Unable to read external time stamps"); //$NON-NLS-1$
- } finally {
- if (in != null) {
- try {
- in.close();
- } catch (IOException e) {
- // nothing we can do: ignore
- }
- }
- }
- this.externalTimeStamps = timeStamps;
- }
- return this.externalTimeStamps;
- }
-
- public IJavaScriptProject findJavaProject(String name) {
- if (getOldJavaProjecNames().contains(name))
- return JavaModelManager.getJavaModelManager().getJavaModel().getJavaScriptProject(name);
- return null;
- }
-
- /*
- * Workaround for bug 15168 circular errors not reported
- * Returns the list of java projects before resource delta processing
- * has started.
- */
- public synchronized HashSet getOldJavaProjecNames() {
- if (this.javaProjectNamesCache == null) {
- HashSet result = new HashSet();
- IJavaScriptProject[] projects;
- try {
- projects = JavaModelManager.getJavaModelManager().getJavaModel().getJavaScriptProjects();
- } catch (JavaScriptModelException e) {
- return this.javaProjectNamesCache;
- }
- for (int i = 0, length = projects.length; i < length; i++) {
- IJavaScriptProject project = projects[i];
- result.add(project.getElementName());
- }
- return this.javaProjectNamesCache = result;
- }
- return this.javaProjectNamesCache;
- }
-
- public synchronized void resetOldJavaProjectNames() {
- this.javaProjectNamesCache = null;
- }
-
- private File getTimeStampsFile() {
- return JavaScriptCore.getPlugin().getStateLocation().append("externalLibsTimeStamps").toFile(); //$NON-NLS-1$
- }
-
- public void saveExternalLibTimeStamps() throws CoreException {
- if (this.externalTimeStamps == null) return;
- File timestamps = getTimeStampsFile();
- DataOutputStream out = null;
- try {
- out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(timestamps)));
- out.writeInt(this.externalTimeStamps.size());
- Iterator entries = this.externalTimeStamps.entrySet().iterator();
- while (entries.hasNext()) {
- Map.Entry entry = (Map.Entry) entries.next();
- IPath key = (IPath) entry.getKey();
- out.writeUTF(key.toPortableString());
- Long timestamp = (Long) entry.getValue();
- out.writeLong(timestamp.longValue());
- }
- } catch (IOException e) {
- IStatus status = new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving timestamps", e); //$NON-NLS-1$
- throw new CoreException(status);
- } finally {
- if (out != null) {
- try {
- out.close();
- } catch (IOException e) {
- // nothing we can do: ignore
- }
- }
- }
- }
-
- /*
- * Update the roots that are affected by the addition or the removal of the given container resource.
- */
- public synchronized void updateRoots(IPath containerPath, IResourceDelta containerDelta, DeltaProcessor deltaProcessor) {
- Map updatedRoots;
- Map otherUpdatedRoots;
- if (containerDelta.getKind() == IResourceDelta.REMOVED) {
- updatedRoots = this.oldRoots;
- otherUpdatedRoots = this.oldOtherRoots;
- } else {
- updatedRoots = this.roots;
- otherUpdatedRoots = this.otherRoots;
- }
- int containerSegmentCount = containerPath.segmentCount();
- boolean containerIsProject = containerSegmentCount == 1;
- Iterator iterator = updatedRoots.entrySet().iterator();
- while (iterator.hasNext()) {
- Map.Entry entry = (Map.Entry) iterator.next();
- IPath path = (IPath) entry.getKey();
- if (containerPath.isPrefixOf(path) && !containerPath.equals(path)) {
- IResourceDelta rootDelta = containerDelta.findMember(path.removeFirstSegments(containerSegmentCount));
- if (rootDelta == null) continue;
- DeltaProcessor.RootInfo rootInfo = (DeltaProcessor.RootInfo) entry.getValue();
-
- if (!containerIsProject
- || !rootInfo.project.getPath().isPrefixOf(path)) { // only consider folder roots that are not included in the container
- deltaProcessor.updateCurrentDeltaAndIndex(rootDelta, IJavaScriptElement.PACKAGE_FRAGMENT_ROOT, rootInfo);
- }
-
- ArrayList rootList = (ArrayList)otherUpdatedRoots.get(path);
- if (rootList != null) {
- Iterator otherProjects = rootList.iterator();
- while (otherProjects.hasNext()) {
- rootInfo = (DeltaProcessor.RootInfo)otherProjects.next();
- if (!containerIsProject
- || !rootInfo.project.getPath().isPrefixOf(path)) { // only consider folder roots that are not included in the container
- deltaProcessor.updateCurrentDeltaAndIndex(rootDelta, IJavaScriptElement.PACKAGE_FRAGMENT_ROOT, rootInfo);
- }
- }
- }
- }
- }
- }
-
-}
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
deleted file mode 100644
index ad7c9f19..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DeltaProcessor.java
+++ /dev/null
@@ -1,2571 +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;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceChangeEvent;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.resources.IResourceDeltaVisitor;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.ISafeRunnable;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.PerformanceStats;
-import org.eclipse.core.runtime.SafeRunner;
-import org.eclipse.wst.jsdt.core.ElementChangedEvent;
-import org.eclipse.wst.jsdt.core.IElementChangedListener;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptElementDelta;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-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.compiler.SourceElementParser;
-import org.eclipse.wst.jsdt.internal.core.builder.JavaBuilder;
-import org.eclipse.wst.jsdt.internal.core.hierarchy.TypeHierarchy;
-import org.eclipse.wst.jsdt.internal.core.search.AbstractSearchScope;
-import org.eclipse.wst.jsdt.internal.core.search.JavaWorkspaceScope;
-import org.eclipse.wst.jsdt.internal.core.search.indexing.IndexManager;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * This class is used by <code>JavaModelManager</code> to convert
- * <code>IResourceDelta</code>s into <code>IJavaScriptElementDelta</code>s.
- * It also does some processing on the <code>JavaElement</code>s involved
- * (e.g. closing them or updating classpaths).
- * <p>
- * High level summary of what the delta processor does:
- * <ul>
- * <li>reacts to resource deltas</li>
- * <li>fires corresponding Java element deltas</li>
- * <li>deltas also contain non-Java resources changes</li>
- * <li>updates the model to reflect the Java element changes</li>
- * <li>notifies type hierarchies of the changes</li>
- * <li>triggers indexing of the changed elements</li>
- * <li>refresh external archives (delta, model update, indexing)</li>
- * <li>is thread safe (one delta processor instance per thread, see DeltaProcessingState#resourceChanged(...))</li>
- * <li>handles .classpath changes (updates package fragment roots, update project references, validate classpath (.classpath format,
- * resolved classpath, cycles))</li>
- * </ul>
- */
-public class DeltaProcessor {
-
- static class OutputsInfo {
- int outputCount;
- IPath[] paths;
- int[] traverseModes;
- OutputsInfo(IPath[] paths, int[] traverseModes, int outputCount) {
- this.paths = paths;
- this.traverseModes = traverseModes;
- this.outputCount = outputCount;
- }
- public String toString() {
- if (this.paths == null) return "<none>"; //$NON-NLS-1$
- StringBuffer buffer = new StringBuffer();
- for (int i = 0; i < this.outputCount; i++) {
- buffer.append("path="); //$NON-NLS-1$
- buffer.append(this.paths[i].toString());
- buffer.append("\n->traverse="); //$NON-NLS-1$
- switch (this.traverseModes[i]) {
- case BINARY:
- buffer.append("BINARY"); //$NON-NLS-1$
- break;
- case IGNORE:
- buffer.append("IGNORE"); //$NON-NLS-1$
- break;
- case SOURCE:
- buffer.append("SOURCE"); //$NON-NLS-1$
- break;
- default:
- buffer.append("<unknown>"); //$NON-NLS-1$
- }
- if (i+1 < this.outputCount) {
- buffer.append('\n');
- }
- }
- return buffer.toString();
- }
- }
-
- static class RootInfo {
- char[][] inclusionPatterns;
- char[][] exclusionPatterns;
- JavaProject project;
- IPath rootPath;
- int entryKind;
- IPackageFragmentRoot root;
- RootInfo(JavaProject project, IPath rootPath, char[][] inclusionPatterns, char[][] exclusionPatterns, int entryKind) {
- this.project = project;
- this.rootPath = rootPath;
- this.inclusionPatterns = inclusionPatterns;
- this.exclusionPatterns = exclusionPatterns;
- this.entryKind = entryKind;
- }
- IPackageFragmentRoot getPackageFragmentRoot(IResource resource) {
- if (this.root == null) {
- if (resource != null) {
- this.root = this.project.getPackageFragmentRoot(resource);
- } else {
- Object target = JavaModel.getTarget(ResourcesPlugin.getWorkspace().getRoot(), this.rootPath, false/*don't check existence*/);
- if (target instanceof IResource) {
- this.root = this.project.getPackageFragmentRoot((IResource)target);
- } else {
- this.root = this.project.getPackageFragmentRoot(this.rootPath.toOSString());
- }
- }
- }
- return this.root;
- }
- boolean isRootOfProject(IPath path) {
- return this.rootPath.equals(path) && this.project.getProject().getFullPath().isPrefixOf(path);
- }
- public String toString() {
- StringBuffer buffer = new StringBuffer("project="); //$NON-NLS-1$
- if (this.project == null) {
- buffer.append("null"); //$NON-NLS-1$
- } else {
- buffer.append(this.project.getElementName());
- }
- buffer.append("\npath="); //$NON-NLS-1$
- if (this.rootPath == null) {
- buffer.append("null"); //$NON-NLS-1$
- } else {
- buffer.append(this.rootPath.toString());
- }
- buffer.append("\nincluding="); //$NON-NLS-1$
- if (this.inclusionPatterns == null) {
- buffer.append("null"); //$NON-NLS-1$
- } else {
- for (int i = 0, length = this.inclusionPatterns.length; i < length; i++) {
- buffer.append(new String(this.inclusionPatterns[i]));
- if (i < length-1) {
- buffer.append("|"); //$NON-NLS-1$
- }
- }
- }
- buffer.append("\nexcluding="); //$NON-NLS-1$
- if (this.exclusionPatterns == null) {
- buffer.append("null"); //$NON-NLS-1$
- } else {
- for (int i = 0, length = this.exclusionPatterns.length; i < length; i++) {
- buffer.append(new String(this.exclusionPatterns[i]));
- if (i < length-1) {
- buffer.append("|"); //$NON-NLS-1$
- }
- }
- }
- return buffer.toString();
- }
- }
-
- private final static int IGNORE = 0;
- private final static int SOURCE = 1;
- private final static int BINARY = 2;
-
- private final static String EXTERNAL_JAR_ADDED = "external jar added"; //$NON-NLS-1$
- private final static String EXTERNAL_JAR_CHANGED = "external jar changed"; //$NON-NLS-1$
- private final static String EXTERNAL_JAR_REMOVED = "external jar removed"; //$NON-NLS-1$
- private final static String EXTERNAL_JAR_UNCHANGED = "external jar unchanged"; //$NON-NLS-1$
- private final static String INTERNAL_JAR_IGNORE = "internal jar ignore"; //$NON-NLS-1$
-
- private final static int NON_JAVA_RESOURCE = -1;
- public static boolean DEBUG = false;
- public static boolean VERBOSE = false;
- public static boolean PERF = false;
-
- public static final int DEFAULT_CHANGE_EVENT = 0; // must not collide with ElementChangedEvent event masks
-
- /*
- * Answer a combination of the lastModified stamp and the size.
- * Used for detecting external JAR changes
- */
- public static long getTimeStamp(File file) {
- return file.lastModified() + file.length();
- }
-
- /*
- * The global state of delta processing.
- */
- private DeltaProcessingState state;
-
- /*
- * The Java model manager
- */
- JavaModelManager manager;
-
- /*
- * The <code>JavaElementDelta</code> corresponding to the <code>IResourceDelta</code> being translated.
- */
- private JavaElementDelta currentDelta;
-
- /* The java element that was last created (see createElement(IResource)).
- * This is used as a stack of java elements (using getParent() to pop it, and
- * using the various get*(...) to push it. */
- private Openable currentElement;
-
- /*
- * Queue of deltas created explicily by the Java Model that
- * have yet to be fired.
- */
- public ArrayList javaModelDeltas= new ArrayList();
-
- /*
- * Queue of reconcile deltas on working copies that have yet to be fired.
- * This is a table form IWorkingCopy to IJavaScriptElementDelta
- */
- public HashMap reconcileDeltas = new HashMap();
-
- /*
- * Turns delta firing on/off. By default it is on.
- */
- private boolean isFiring= true;
-
- /*
- * Used to update the JavaModel for <code>IJavaScriptElementDelta</code>s.
- */
- private final ModelUpdater modelUpdater = new ModelUpdater();
-
- /* A set of IJavaScriptProject whose caches need to be reset */
- public HashSet projectCachesToReset = new HashSet();
-
- /*
- * A list of IJavaScriptElement used as a scope for external archives refresh during POST_CHANGE.
- * This is null if no refresh is needed.
- */
- private HashSet refreshedElements;
-
- /* A table from IJavaScriptProject to an array of IPackageFragmentRoot.
- * This table contains the pkg fragment roots of the project that are being deleted.
- */
- public Map oldRoots;
-
- /* A set of IJavaScriptProject whose package fragment roots need to be refreshed */
- private HashSet rootsToRefresh = new HashSet();
-
- /*
- * Type of event that should be processed no matter what the real event type is.
- */
- public int overridenEventType = -1;
-
- /*
- * Cache SourceElementParser for the project being visited
- */
- private SourceElementParser sourceElementParserCache;
-
- /*
- * Map from IProject to ClasspathChange
- */
- public HashMap classpathChanges = new HashMap();
-
- public DeltaProcessor(DeltaProcessingState state, JavaModelManager manager) {
- this.state = state;
- this.manager = manager;
- }
-
- public ClasspathChange addClasspathChange(IProject project, IIncludePathEntry[] oldRawClasspath, IPath oldOutputLocation, IIncludePathEntry[] oldResolvedClasspath) {
- ClasspathChange change = (ClasspathChange) this.classpathChanges.get(project);
- if (change == null) {
- change = new ClasspathChange((JavaProject) this.manager.getJavaModel().getJavaProject(project), oldRawClasspath, oldOutputLocation, oldResolvedClasspath);
- this.classpathChanges.put(project, change);
- } else {
- if (change.oldRawClasspath == null)
- change.oldRawClasspath = oldRawClasspath;
- if (change.oldOutputLocation == null)
- change.oldOutputLocation = oldOutputLocation;
- if (change.oldResolvedClasspath == null)
- change.oldResolvedClasspath = oldResolvedClasspath;
- }
- return change;
- }
-
- /*
- * Adds the dependents of the given project to the list of the projects
- * to update.
- */
- private void addDependentProjects(IJavaScriptProject project, HashMap projectDependencies, HashSet result) {
- IJavaScriptProject[] dependents = (IJavaScriptProject[]) projectDependencies.get(project);
- if (dependents == null) return;
- for (int i = 0, length = dependents.length; i < length; i++) {
- IJavaScriptProject dependent = dependents[i];
- if (result.contains(dependent))
- continue; // no need to go further as the project is already known
- result.add(dependent);
- addDependentProjects(dependent, projectDependencies, result);
- }
- }
- /*
- * Adds the given element to the list of elements used as a scope for external jars refresh.
- */
- public void addForRefresh(IJavaScriptElement element) {
- if (this.refreshedElements == null) {
- this.refreshedElements = new HashSet();
- }
- this.refreshedElements.add(element);
- }
- /*
- * Adds the given child handle to its parent's cache of children.
- */
- private void addToParentInfo(Openable child) {
- Openable parent = (Openable) child.getParent();
- if (parent != null && parent.isOpen()) {
- try {
- JavaElementInfo info = (JavaElementInfo)parent.getElementInfo();
- info.addChild(child);
- } catch (JavaScriptModelException e) {
- // do nothing - we already checked if open
- }
- }
- }
- /*
- * Adds the given project and its dependents to the list of the roots to refresh.
- */
- private void addToRootsToRefreshWithDependents(IJavaScriptProject javaProject) {
- this.rootsToRefresh.add(javaProject);
- this.addDependentProjects(javaProject, this.state.projectDependencies, this.rootsToRefresh);
- }
- /*
- * Check all external archive (referenced by given roots, projects or model) status and issue a corresponding root delta.
- * Also triggers index updates
- */
- public void checkExternalArchiveChanges(IJavaScriptElement[] elementsToRefresh, IProgressMonitor monitor) throws JavaScriptModelException {
- if (monitor != null && monitor.isCanceled())
- throw new OperationCanceledException();
- try {
- if (monitor != null) monitor.beginTask("", 1); //$NON-NLS-1$
-
- for (int i = 0, length = elementsToRefresh.length; i < length; i++) {
- this.addForRefresh(elementsToRefresh[i]);
- }
- boolean hasDelta = this.createExternalArchiveDelta(monitor);
- if (monitor != null && monitor.isCanceled()) return;
- if (hasDelta){
- // force classpath marker refresh of affected projects
- JavaModel.flushExternalFileCache();
-
- // flush jar type cache
- JavaModelManager.getJavaModelManager().resetJarTypeCache();
-
- IJavaScriptElementDelta[] projectDeltas = this.currentDelta.getAffectedChildren();
- final int length = projectDeltas.length;
- final IProject[] projectsToTouch = new IProject[length];
- for (int i = 0; i < length; i++) {
- IJavaScriptElementDelta delta = projectDeltas[i];
- JavaProject javaProject = (JavaProject)delta.getElement();
- projectsToTouch[i] = javaProject.getProject();
- }
-
- // touch the projects to force them to be recompiled while taking the workspace lock
- // so that there is no concurrency with the Java builder
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=96575
- IWorkspaceRunnable runnable = new IWorkspaceRunnable() {
- public void run(IProgressMonitor progressMonitor) throws CoreException {
- for (int i = 0; i < length; i++) {
- IProject project = projectsToTouch[i];
-
- // touch to force a build of this project
- if (JavaBuilder.DEBUG)
- System.out.println("Touching project " + project.getName() + " due to external jar file change"); //$NON-NLS-1$ //$NON-NLS-2$
- project.touch(progressMonitor);
- }
- }
- };
- try {
- ResourcesPlugin.getWorkspace().run(runnable, monitor);
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- }
-
- if (this.currentDelta != null) { // if delta has not been fired while creating markers
- this.fire(this.currentDelta, DEFAULT_CHANGE_EVENT);
- }
- }
- } finally {
- this.currentDelta = null;
- if (monitor != null) monitor.done();
- }
- }
- /*
- * Process the given delta and look for projects being added, opened, closed or
- * with a java nature being added or removed.
- * Note that projects being deleted are checked in deleting(IProject).
- * In all cases, add the project's dependents to the list of projects to update
- * so that the classpath related markers can be updated.
- */
- private void checkProjectsBeingAddedOrRemoved(IResourceDelta delta) {
- IResource resource = delta.getResource();
- IResourceDelta[] children = null;
-
- switch (resource.getType()) {
- case IResource.ROOT :
- // workaround for bug 15168 circular errors not reported
- this.state.getOldJavaProjecNames(); // force list to be computed
- children = delta.getAffectedChildren();
- break;
- case IResource.PROJECT :
- // NB: No need to check project's nature as if the project is not a java project:
- // - if the project is added or changed this is a noop for projectsBeingDeleted
- // - if the project is closed, it has already lost its java nature
- IProject project = (IProject)resource;
- JavaProject javaProject = (JavaProject)JavaScriptCore.create(project);
- switch (delta.getKind()) {
- case IResourceDelta.ADDED :
- this.manager.batchContainerInitializations = true;
-
- // remember project and its dependents
- addToRootsToRefreshWithDependents(javaProject);
-
- // workaround for bug 15168 circular errors not reported
- if (JavaProject.hasJavaNature(project)) {
- addToParentInfo(javaProject);
- readRawClasspath(javaProject);
- // ensure project references are updated (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=121569)
- checkProjectReferenceChange(project, javaProject);
- }
-
- this.state.rootsAreStale = true;
- break;
-
- case IResourceDelta.CHANGED :
- if ((delta.getFlags() & IResourceDelta.OPEN) != 0) {
- this.manager.batchContainerInitializations = true;
-
- // project opened or closed: remember project and its dependents
- addToRootsToRefreshWithDependents(javaProject);
-
- // workaround for bug 15168 circular errors not reported
- if (project.isOpen()) {
- if (JavaProject.hasJavaNature(project)) {
- addToParentInfo(javaProject);
- readRawClasspath(javaProject);
- // ensure project references are updated
- checkProjectReferenceChange(project, javaProject);
- }
- } else {
- try {
- javaProject.close();
- } catch (JavaScriptModelException e) {
- // java project doesn't exist: ignore
- }
- this.removeFromParentInfo(javaProject);
- this.manager.removePerProjectInfo(javaProject);
- this.manager.containerRemove(javaProject);
- }
- this.state.rootsAreStale = true;
- } else if ((delta.getFlags() & IResourceDelta.DESCRIPTION) != 0) {
- boolean wasJavaProject = this.state.findJavaProject(project.getName()) != null;
- boolean isJavaProject = JavaProject.hasJavaNature(project);
- if (wasJavaProject != isJavaProject) {
- this.manager.batchContainerInitializations = true;
-
- // java nature added or removed: remember project and its dependents
- this.addToRootsToRefreshWithDependents(javaProject);
-
- // workaround for bug 15168 circular errors not reported
- if (isJavaProject) {
- this.addToParentInfo(javaProject);
- readRawClasspath(javaProject);
- // ensure project references are updated (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=172666)
- checkProjectReferenceChange(project, javaProject);
- } else {
- // remove classpath cache so that initializeRoots() will not consider the project has a classpath
- this.manager.removePerProjectInfo(javaProject);
- // remove container cache for this project
- this.manager.containerRemove(javaProject);
- // close project
- try {
- javaProject.close();
- } catch (JavaScriptModelException e) {
- // java project doesn't exist: ignore
- }
- this.removeFromParentInfo(javaProject);
- }
- this.state.rootsAreStale = true;
- } else {
- // in case the project was removed then added then changed (see bug 19799)
- if (isJavaProject) { // need nature check - 18698
- this.addToParentInfo(javaProject);
- children = delta.getAffectedChildren();
- }
- }
- } else {
- // workaround for bug 15168 circular errors not reported
- // in case the project was removed then added then changed
- if (JavaProject.hasJavaNature(project)) { // need nature check - 18698
- this.addToParentInfo(javaProject);
- children = delta.getAffectedChildren();
- }
- }
- break;
-
- case IResourceDelta.REMOVED :
- this.manager.batchContainerInitializations = true;
-
- // remove classpath cache so that initializeRoots() will not consider the project has a classpath
- this.manager.removePerProjectInfo(javaProject);
- // remove container cache for this project
- this.manager.containerRemove(javaProject);
-
- this.state.rootsAreStale = true;
- break;
- }
-
- // in all cases, refresh the external jars for this project
- addForRefresh(javaProject);
-
- break;
- case IResource.FOLDER :
- IFolder folder = (IFolder) resource;
- if(folder.getName().equals(JavaProject.SHARED_PROPERTIES_DIRECTORY)) {
- switch (delta.getKind()) {
- case IResourceDelta.CHANGED :
- // fall through
- case IResourceDelta.ADDED :
- children = delta.getAffectedChildren();
- break;
- }
- }
- break;
- case IResource.FILE :
- IFile file = (IFile) resource;
- /* classpath file change */
- if (file.getName().equals(JavaProject.CLASSPATH_FILENAME)) {
- this.manager.batchContainerInitializations = true;
- switch (delta.getKind()) {
- case IResourceDelta.CHANGED :
- int flags = delta.getFlags();
- if ((flags & IResourceDelta.CONTENT) == 0 // only consider content change
- && (flags & IResourceDelta.ENCODING) == 0 // and encoding change
- && (flags & IResourceDelta.MOVED_FROM) == 0) {// and also move and overide scenario (see http://dev.eclipse.org/bugs/show_bug.cgi?id=21420)
- break;
- }
- // fall through
- case IResourceDelta.ADDED :
- javaProject = (JavaProject)JavaScriptCore.create(file.getProject());
-
- // force to (re)read the .classpath file
- try {
- javaProject.getPerProjectInfo().readAndCacheClasspath(javaProject);
- } catch (JavaScriptModelException e) {
- // project doesn't exist
- return;
- }
- break;
- }
- this.state.rootsAreStale = true;
- }
- break;
-
- }
- if (children != null) {
- for (int i = 0; i < children.length; i++) {
- checkProjectsBeingAddedOrRemoved(children[i]);
- }
- }
- }
-
- private void checkProjectReferenceChange(IProject project, JavaProject javaProject) {
- ClasspathChange change = (ClasspathChange) this.classpathChanges.get(project);
- this.state.addProjectReferenceChange(javaProject, change == null ? null : change.oldResolvedClasspath);
- }
-
- private void readRawClasspath(JavaProject javaProject) {
- try {
- // force to (re)read the .classpath file
- javaProject.getPerProjectInfo().readAndCacheClasspath(javaProject);
- } catch (JavaScriptModelException e) {
- if (VERBOSE) {
- e.printStackTrace();
- }
- }
- }
- private void checkSourceAttachmentChange(IResourceDelta delta, IResource res) {
- IPath rootPath = (IPath)this.state.sourceAttachments.get(res.getFullPath());
- if (rootPath != null) {
- RootInfo rootInfo = this.rootInfo(rootPath, delta.getKind());
- if (rootInfo != null) {
- IJavaScriptProject projectOfRoot = rootInfo.project;
- IPackageFragmentRoot root = null;
- try {
- // close the root so that source attachement cache is flushed
- root = projectOfRoot.findPackageFragmentRoot(rootPath);
- if (root != null) {
- root.close();
- }
- } catch (JavaScriptModelException e) {
- // root doesn't exist: ignore
- }
- if (root == null) return;
- switch (delta.getKind()) {
- case IResourceDelta.ADDED:
- currentDelta().sourceAttached(root);
- break;
- case IResourceDelta.CHANGED:
- currentDelta().sourceDetached(root);
- currentDelta().sourceAttached(root);
- break;
- case IResourceDelta.REMOVED:
- currentDelta().sourceDetached(root);
- break;
- }
- }
- }
- }
- /*
- * Closes the given element, which removes it from the cache of open elements.
- */
- private void close(Openable element) {
- try {
- element.close();
- } catch (JavaScriptModelException e) {
- // do nothing
- }
- }
- /*
- * Generic processing for elements with changed contents:<ul>
- * <li>The element is closed such that any subsequent accesses will re-open
- * the element reflecting its new structure.
- * <li>An entry is made in the delta reporting a content change (K_CHANGE with F_CONTENT flag set).
- * </ul>
- * Delta argument could be null if processing an external JAR change
- */
- private void contentChanged(Openable element) {
-
- boolean isPrimary = false;
- boolean isPrimaryWorkingCopy = false;
- if (element.getElementType() == IJavaScriptElement.JAVASCRIPT_UNIT) {
- CompilationUnit cu = (CompilationUnit)element;
- isPrimary = cu.isPrimary();
- isPrimaryWorkingCopy = isPrimary && cu.isWorkingCopy();
- }
- if (isPrimaryWorkingCopy) {
- // filter out changes to primary compilation unit in working copy mode
- // just report a change to the resource (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=59500)
- currentDelta().changed(element, IJavaScriptElementDelta.F_PRIMARY_RESOURCE);
- } else {
- close(element);
- int flags = IJavaScriptElementDelta.F_CONTENT;
-// if (element instanceof JarPackageFragmentRoot){
-// flags |= IJavaScriptElementDelta.F_ARCHIVE_CONTENT_CHANGED;
-// // need also to reset project cache otherwise it will be out-of-date
-// // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=162621
-// this.projectCachesToReset.add(element.getJavaScriptProject());
-// }
- if (isPrimary) {
- flags |= IJavaScriptElementDelta.F_PRIMARY_RESOURCE;
- }
- currentDelta().changed(element, flags);
- }
- }
- /*
- * Creates the openables corresponding to this resource.
- * Returns null if none was found.
- */
- private Openable createElement(IResource resource, int elementType, RootInfo rootInfo) {
- if (resource == null) return null;
-
- IPath path = resource.getFullPath();
- IJavaScriptElement element = null;
- switch (elementType) {
-
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
-
- // note that non-java resources rooted at the project level will also enter this code with
- // an elementType JAVASCRIPT_PROJECT (see #elementType(...)).
- if (resource instanceof IProject){
-
- this.popUntilPrefixOf(path);
-
- if (this.currentElement != null
- && this.currentElement.getElementType() == IJavaScriptElement.JAVASCRIPT_PROJECT
- && ((IJavaScriptProject)this.currentElement).getProject().equals(resource)) {
- return this.currentElement;
- }
- if (rootInfo != null && rootInfo.project.getProject().equals(resource)){
- element = rootInfo.project;
- break;
- }
- IProject proj = (IProject)resource;
- if (JavaProject.hasJavaNature(proj)) {
- element = JavaScriptCore.create(proj);
- } else {
- // java project may have been been closed or removed (look for
- // element amongst old java project s list).
- element = this.state.findJavaProject(proj.getName());
- }
- }
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- element = rootInfo == null ? JavaScriptCore.create(resource) : rootInfo.getPackageFragmentRoot(resource);
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- if (rootInfo != null) {
- if (rootInfo.project.contains(resource)) {
- PackageFragmentRoot root = (PackageFragmentRoot) rootInfo.getPackageFragmentRoot(null);
- // create package handle
- IPath pkgPath = path.removeFirstSegments(rootInfo.rootPath.segmentCount());
- String[] pkgName = pkgPath.segments();
- element = root.getPackageFragment(pkgName);
- }
- } else {
- // find the element that encloses the resource
- this.popUntilPrefixOf(path);
-
- if (this.currentElement == null) {
- element = JavaScriptCore.create(resource);
- } else {
- // find the root
- PackageFragmentRoot root = this.currentElement.getPackageFragmentRoot();
- if (root == null) {
- element = JavaScriptCore.create(resource);
- } else if (((JavaProject)root.getJavaScriptProject()).contains(resource)) {
- // create package handle
- IPath pkgPath = path.removeFirstSegments(root.getPath().segmentCount());
- String[] pkgName = pkgPath.segments();
- element = root.getPackageFragment(pkgName);
- }
- }
- }
- break;
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- case IJavaScriptElement.CLASS_FILE:
- // find the element that encloses the resource
- this.popUntilPrefixOf(path);
-
- if (this.currentElement == null) {
- element = rootInfo == null ? JavaScriptCore.create(resource) : JavaModelManager.create(resource, rootInfo.project);
- } else {
- // find the package
- IPackageFragment pkgFragment = null;
- switch (this.currentElement.getElementType()) {
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- PackageFragmentRoot root = (PackageFragmentRoot)this.currentElement;
- IPath rootPath = root.getPath();
- IPath pkgPath = path.removeLastSegments(1);
- String[] pkgName = pkgPath.removeFirstSegments(rootPath.segmentCount()).segments();
- pkgFragment = root.getPackageFragment(pkgName);
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- Openable pkg = this.currentElement;
- if (pkg.getPath().equals(path.removeLastSegments(1))) {
- pkgFragment = (IPackageFragment)pkg;
- } // else case of package x which is a prefix of x.y
- break;
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- case IJavaScriptElement.CLASS_FILE:
- pkgFragment = (IPackageFragment)this.currentElement.getParent();
- break;
- }
- if (pkgFragment == null) {
- boolean isSource = rootInfo == null || rootInfo.entryKind == IIncludePathEntry.CPE_SOURCE;
- if(!isSource)
- element = JavaScriptCore.createClassFileFrom((IFile)resource);
- else
- element = rootInfo == null ? JavaScriptCore.create(resource) : JavaModelManager.create(resource, rootInfo.project);
- } else {
- if (elementType == IJavaScriptElement.JAVASCRIPT_UNIT) {
- // create compilation unit handle
- // fileName validation has been done in elementType(IResourceDelta, int, boolean)
- String fileName = path.lastSegment();
- element = pkgFragment.getJavaScriptUnit(fileName);
- } else {
- // create class file handle
- // fileName validation has been done in elementType(IResourceDelta, int, boolean)
- String fileName = path.lastSegment();
- element = pkgFragment.getClassFile(fileName);
- }
- }
- }
- break;
- }
- if (element == null) return null;
- this.currentElement = (Openable)element;
- return this.currentElement;
- }
- /*
- * Check if external archives have changed and create the corresponding deltas.
- * Returns whether at least on delta was created.
- */
- private boolean createExternalArchiveDelta(IProgressMonitor monitor) {
-
- if (this.refreshedElements == null) return false;
-
- HashMap externalArchivesStatus = new HashMap();
- boolean hasDelta = false;
-
- // find JARs to refresh
- HashSet archivePathsToRefresh = new HashSet();
- Iterator iterator = this.refreshedElements.iterator();
- this.refreshedElements = null; // null out early to avoid concurrent modification exception (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=63534)
- while (iterator.hasNext()) {
- IJavaScriptElement element = (IJavaScriptElement)iterator.next();
- switch(element.getElementType()){
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT :
- archivePathsToRefresh.add(element.getPath());
- break;
- case IJavaScriptElement.JAVASCRIPT_PROJECT :
- JavaProject javaProject = (JavaProject) element;
- if (!JavaProject.hasJavaNature(javaProject.getProject())) {
- // project is not accessible or has lost its Java nature
- break;
- }
- IIncludePathEntry[] classpath;
- try {
- classpath = javaProject.getResolvedClasspath();
- for (int j = 0, cpLength = classpath.length; j < cpLength; j++){
- if (classpath[j].getEntryKind() == IIncludePathEntry.CPE_LIBRARY){
- archivePathsToRefresh.add(classpath[j].getPath());
- }
- }
- } catch (JavaScriptModelException e) {
- // project doesn't exist -> ignore
- }
- break;
- case IJavaScriptElement.JAVASCRIPT_MODEL :
- Iterator projectNames = this.state.getOldJavaProjecNames().iterator();
- while (projectNames.hasNext()) {
- String projectName = (String) projectNames.next();
- IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
- if (!JavaProject.hasJavaNature(project)) {
- // project is not accessible or has lost its Java nature
- continue;
- }
- javaProject = (JavaProject) JavaScriptCore.create(project);
- try {
- classpath = javaProject.getResolvedClasspath();
- } catch (JavaScriptModelException e2) {
- // project doesn't exist -> ignore
- continue;
- }
- for (int k = 0, cpLength = classpath.length; k < cpLength; k++){
- if (classpath[k].getEntryKind() == IIncludePathEntry.CPE_LIBRARY){
- archivePathsToRefresh.add(classpath[k].getPath());
- }
- }
- }
- break;
- }
- }
-
- // perform refresh
- Iterator projectNames = this.state.getOldJavaProjecNames().iterator();
- IWorkspaceRoot wksRoot = ResourcesPlugin.getWorkspace().getRoot();
- while (projectNames.hasNext()) {
-
- if (monitor != null && monitor.isCanceled()) break;
-
- String projectName = (String) projectNames.next();
- IProject project = wksRoot.getProject(projectName);
- if (!JavaProject.hasJavaNature(project)) {
- // project is not accessible or has lost its Java nature
- continue;
- }
- JavaProject javaProject = (JavaProject) JavaScriptCore.create(project);
- IIncludePathEntry[] entries;
- try {
- entries = javaProject.getResolvedClasspath();
- } catch (JavaScriptModelException e1) {
- // project does not exist -> ignore
- continue;
- }
- for (int j = 0; j < entries.length; j++){
- if (entries[j].getEntryKind() == IIncludePathEntry.CPE_LIBRARY) {
-
- IPath entryPath = entries[j].getPath();
-
- if (!archivePathsToRefresh.contains(entryPath)) continue; // not supposed to be refreshed
-
- String status = (String)externalArchivesStatus.get(entryPath);
- if (status == null){
-
- // compute shared status
- Object targetLibrary = JavaModel.getTarget(wksRoot, entryPath, true);
-
- if (targetLibrary == null){ // missing JAR
- if (this.state.getExternalLibTimeStamps().remove(entryPath) != null){
- externalArchivesStatus.put(entryPath, EXTERNAL_JAR_REMOVED);
- // the jar was physically removed: remove the index
- this.manager.indexManager.removeIndex(entryPath);
- }
-
- } else if (targetLibrary instanceof File){ // external JAR
-
- File externalFile = (File)targetLibrary;
-
- // check timestamp to figure if JAR has changed in some way
- Long oldTimestamp =(Long) this.state.getExternalLibTimeStamps().get(entryPath);
- long newTimeStamp = getTimeStamp(externalFile);
- if (oldTimestamp != null){
-
- if (newTimeStamp == 0){ // file doesn't exist
- externalArchivesStatus.put(entryPath, EXTERNAL_JAR_REMOVED);
- this.state.getExternalLibTimeStamps().remove(entryPath);
- // remove the index
- this.manager.indexManager.removeIndex(entryPath);
-
- } else if (oldTimestamp.longValue() != newTimeStamp){
- externalArchivesStatus.put(entryPath, EXTERNAL_JAR_CHANGED);
- this.state.getExternalLibTimeStamps().put(entryPath, new Long(newTimeStamp));
- // first remove the index so that it is forced to be re-indexed
- this.manager.indexManager.removeIndex(entryPath);
- // then index the jar
- this.manager.indexManager.indexLibrary(entries[j], project.getProject());
- } else {
- externalArchivesStatus.put(entryPath, EXTERNAL_JAR_UNCHANGED);
- }
- } else {
- if (newTimeStamp == 0){ // jar still doesn't exist
- externalArchivesStatus.put(entryPath, EXTERNAL_JAR_UNCHANGED);
- } else {
- externalArchivesStatus.put(entryPath, EXTERNAL_JAR_ADDED);
- this.state.getExternalLibTimeStamps().put(entryPath, new Long(newTimeStamp));
- // index the new jar
- this.manager.indexManager.indexLibrary(entries[j], project.getProject());
- }
- }
- } else { // internal JAR
- externalArchivesStatus.put(entryPath, INTERNAL_JAR_IGNORE);
- }
- }
- // according to computed status, generate a delta
- status = (String)externalArchivesStatus.get(entryPath);
- if (status != null){
- if (status == EXTERNAL_JAR_ADDED){
- PackageFragmentRoot root = (PackageFragmentRoot) javaProject.getPackageFragmentRoot(entryPath.toString());
- if (VERBOSE){
- System.out.println("- External JAR ADDED, affecting root: "+root.getElementName()); //$NON-NLS-1$
- }
- elementAdded(root, null, null);
- this.state.addClasspathValidation(javaProject); // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=185733
- hasDelta = true;
- } else if (status == EXTERNAL_JAR_CHANGED) {
- PackageFragmentRoot root = (PackageFragmentRoot) javaProject.getPackageFragmentRoot(entryPath.toString());
- if (VERBOSE){
- System.out.println("- External JAR CHANGED, affecting root: "+root.getElementName()); //$NON-NLS-1$
- }
- contentChanged(root);
- hasDelta = true;
- } else if (status == EXTERNAL_JAR_REMOVED) {
- PackageFragmentRoot root = (PackageFragmentRoot) javaProject.getPackageFragmentRoot(entryPath.toString());
- if (VERBOSE){
- System.out.println("- External JAR REMOVED, affecting root: "+root.getElementName()); //$NON-NLS-1$
- }
- elementRemoved(root, null, null);
- this.state.addClasspathValidation(javaProject); // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=185733
- hasDelta = true;
- }
- }
- }
- }
- }
- return hasDelta;
- }
- private JavaElementDelta currentDelta() {
- if (this.currentDelta == null) {
- this.currentDelta = new JavaElementDelta(this.manager.getJavaModel());
- }
- return this.currentDelta;
- }
- /*
- * Note that the project is about to be deleted.
- */
- private void deleting(IProject project) {
-
- try {
- // discard indexing jobs that belong to this project so that the project can be
- // deleted without interferences from the index manager
- this.manager.indexManager.discardJobs(project.getName());
-
- JavaProject javaProject = (JavaProject)JavaScriptCore.create(project);
-
- // remember roots of this project
- if (this.oldRoots == null) {
- this.oldRoots = new HashMap();
- }
- if (javaProject.isOpen()) {
- this.oldRoots.put(javaProject, javaProject.getPackageFragmentRoots());
- } else {
- // compute roots without opening project
- this.oldRoots.put(
- javaProject,
- javaProject.computePackageFragmentRoots(
- javaProject.getResolvedClasspath(),
- false,
- null /*no reverse map*/));
- }
-
- javaProject.close();
-
- // workaround for bug 15168 circular errors not reported
- this.state.getOldJavaProjecNames(); // foce list to be computed
-
- this.removeFromParentInfo(javaProject);
-
- // remove preferences from per project info
- this.manager.resetProjectPreferences(javaProject);
- } catch (JavaScriptModelException e) {
- // java project doesn't exist: ignore
- }
- }
- /*
- * Processing for an element that has been added:<ul>
- * <li>If the element is a project, do nothing, and do not process
- * children, as when a project is created it does not yet have any
- * natures - specifically a java nature.
- * <li>If the elemet is not a project, process it as added (see
- * <code>basicElementAdded</code>.
- * </ul>
- * Delta argument could be null if processing an external JAR change
- */
- private void elementAdded(Openable element, IResourceDelta delta, RootInfo rootInfo) {
- int elementType = element.getElementType();
-
- if (elementType == IJavaScriptElement.JAVASCRIPT_PROJECT) {
- // project add is handled by JavaProject.configure() because
- // when a project is created, it does not yet have a java nature
- if (delta != null && JavaProject.hasJavaNature((IProject)delta.getResource())) {
- addToParentInfo(element);
- if ((delta.getFlags() & IResourceDelta.MOVED_FROM) != 0) {
- Openable movedFromElement = (Openable)element.getJavaScriptModel().getJavaScriptProject(delta.getMovedFromPath().lastSegment());
- currentDelta().movedTo(element, movedFromElement);
- } else {
- // Force the project to be closed as it might have been opened
- // before the resource modification came in and it might have a new child
- // For example, in an IWorkspaceRunnable:
- // 1. create a Java project P (where P=src)
- // 2. open project P
- // 3. add folder f in P's pkg fragment root
- // When the resource delta comes in, only the addition of P is notified,
- // but the pkg fragment root of project P is already opened, thus its children are not recomputed
- // and it appears to contain only the default package.
- close(element);
-
- currentDelta().added(element);
- }
- this.state.updateRoots(element.getPath(), delta, this);
-
- // refresh pkg fragment roots and caches of the project (and its dependents)
- this.rootsToRefresh.add(element);
- this.projectCachesToReset.add(element);
- }
- } else {
- if (delta == null || (delta.getFlags() & IResourceDelta.MOVED_FROM) == 0) {
- // regular element addition
- if (isPrimaryWorkingCopy(element, elementType) ) {
- // filter out changes to primary compilation unit in working copy mode
- // just report a change to the resource (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=59500)
- currentDelta().changed(element, IJavaScriptElementDelta.F_PRIMARY_RESOURCE);
- } else {
- addToParentInfo(element);
-
- // Force the element to be closed as it might have been opened
- // before the resource modification came in and it might have a new child
- // For example, in an IWorkspaceRunnable:
- // 1. create a package fragment p using a java model operation
- // 2. open package p
- // 3. add file X.js in folder p
- // When the resource delta comes in, only the addition of p is notified,
- // but the package p is already opened, thus its children are not recomputed
- // and it appears empty.
- close(element);
-
- currentDelta().added(element);
- }
- } else {
- // element is moved
- addToParentInfo(element);
- close(element);
-
- IPath movedFromPath = delta.getMovedFromPath();
- IResource res = delta.getResource();
- IResource movedFromRes;
- if (res instanceof IFile) {
- movedFromRes = res.getWorkspace().getRoot().getFile(movedFromPath);
- } else {
- movedFromRes = res.getWorkspace().getRoot().getFolder(movedFromPath);
- }
-
- // find the element type of the moved from element
- RootInfo movedFromInfo = this.enclosingRootInfo(movedFromPath, IResourceDelta.REMOVED);
- int movedFromType =
- this.elementType(
- movedFromRes,
- IResourceDelta.REMOVED,
- element.getParent().getElementType(),
- movedFromInfo);
-
- // reset current element as it might be inside a nested root (popUntilPrefixOf() may use the outer root)
- this.currentElement = null;
-
- // create the moved from element
- Openable movedFromElement =
- elementType != IJavaScriptElement.JAVASCRIPT_PROJECT && movedFromType == IJavaScriptElement.JAVASCRIPT_PROJECT ?
- null : // outside classpath
- this.createElement(movedFromRes, movedFromType, movedFromInfo);
- if (movedFromElement == null) {
- // moved from outside classpath
- currentDelta().added(element);
- } else {
- currentDelta().movedTo(element, movedFromElement);
- }
- }
-
- switch (elementType) {
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT :
- // when a root is added, and is on the classpath, the project must be updated
- JavaProject project = (JavaProject) element.getJavaScriptProject();
-
- // refresh pkg fragment roots and caches of the project (and its dependents)
- this.rootsToRefresh.add(project);
- this.projectCachesToReset.add(project);
-
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT :
- // reset project's package fragment cache
- project = (JavaProject) element.getJavaScriptProject();
- this.projectCachesToReset.add(project);
-
- break;
- }
- }
- }
- /*
- * Generic processing for a removed element:<ul>
- * <li>Close the element, removing its structure from the cache
- * <li>Remove the element from its parent's cache of children
- * <li>Add a REMOVED entry in the delta
- * </ul>
- * Delta argument could be null if processing an external JAR change
- */
- private void elementRemoved(Openable element, IResourceDelta delta, RootInfo rootInfo) {
-
- int elementType = element.getElementType();
- if (delta == null || (delta.getFlags() & IResourceDelta.MOVED_TO) == 0) {
- // regular element removal
- if (isPrimaryWorkingCopy(element, elementType) ) {
- // filter out changes to primary compilation unit in working copy mode
- // just report a change to the resource (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=59500)
- currentDelta().changed(element, IJavaScriptElementDelta.F_PRIMARY_RESOURCE);
- } else {
- close(element);
- removeFromParentInfo(element);
- currentDelta().removed(element);
- }
- } else {
- // element is moved
- close(element);
- removeFromParentInfo(element);
- IPath movedToPath = delta.getMovedToPath();
- IResource res = delta.getResource();
- IResource movedToRes;
- switch (res.getType()) {
- case IResource.PROJECT:
- movedToRes = res.getWorkspace().getRoot().getProject(movedToPath.lastSegment());
- break;
- case IResource.FOLDER:
- movedToRes = res.getWorkspace().getRoot().getFolder(movedToPath);
- break;
- case IResource.FILE:
- movedToRes = res.getWorkspace().getRoot().getFile(movedToPath);
- break;
- default:
- return;
- }
-
- // find the element type of the moved from element
- RootInfo movedToInfo = this.enclosingRootInfo(movedToPath, IResourceDelta.ADDED);
- int movedToType =
- this.elementType(
- movedToRes,
- IResourceDelta.ADDED,
- element.getParent().getElementType(),
- movedToInfo);
-
- // reset current element as it might be inside a nested root (popUntilPrefixOf() may use the outer root)
- this.currentElement = null;
-
- // create the moved To element
- Openable movedToElement =
- elementType != IJavaScriptElement.JAVASCRIPT_PROJECT && movedToType == IJavaScriptElement.JAVASCRIPT_PROJECT ?
- null : // outside classpath
- this.createElement(movedToRes, movedToType, movedToInfo);
- if (movedToElement == null) {
- // moved outside classpath
- currentDelta().removed(element);
- } else {
- currentDelta().movedFrom(element, movedToElement);
- }
- }
-
- switch (elementType) {
- case IJavaScriptElement.JAVASCRIPT_MODEL :
- this.manager.indexManager.reset();
- break;
- case IJavaScriptElement.JAVASCRIPT_PROJECT :
- this.state.updateRoots(element.getPath(), delta, this);
-
- // refresh pkg fragment roots and caches of the project (and its dependents)
- this.rootsToRefresh.add(element);
- this.projectCachesToReset.add(element);
-
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT :
- JavaProject project = (JavaProject) element.getJavaScriptProject();
-
- // refresh pkg fragment roots and caches of the project (and its dependents)
- this.rootsToRefresh.add(project);
- this.projectCachesToReset.add(project);
-
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT :
- // reset package fragment cache
- project = (JavaProject) element.getJavaScriptProject();
- this.projectCachesToReset.add(project);
-
- break;
- }
- }
- /*
- * Returns the type of the java element the given delta matches to.
- * Returns NON_JAVA_RESOURCE if unknown (e.g. a non-java resource or excluded .js file)
- */
- private int elementType(IResource res, int kind, int parentType, RootInfo rootInfo) {
- switch (parentType) {
- case IJavaScriptElement.JAVASCRIPT_MODEL:
- // case of a movedTo or movedFrom project (other cases are handled in processResourceDelta(...)
- return IJavaScriptElement.JAVASCRIPT_PROJECT;
-
- case NON_JAVA_RESOURCE:
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- if (rootInfo == null) {
- rootInfo = this.enclosingRootInfo(res.getFullPath(), kind);
- }
- if (rootInfo != null && rootInfo.isRootOfProject(res.getFullPath())) {
- return IJavaScriptElement.PACKAGE_FRAGMENT_ROOT;
- }
- // not yet in a package fragment root or root of another project
- // or package fragment to be included (see below)
- // -> let it go through
-
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- if (rootInfo == null) {
- rootInfo = this.enclosingRootInfo(res.getFullPath(), kind);
- }
- if (rootInfo == null) {
- return NON_JAVA_RESOURCE;
- }
- if (Util.isExcluded(res, rootInfo.inclusionPatterns, rootInfo.exclusionPatterns)) {
- return NON_JAVA_RESOURCE;
- }
- if (res.getType() == IResource.FOLDER) {
- if (parentType == NON_JAVA_RESOURCE && !Util.isExcluded(res.getParent(), rootInfo.inclusionPatterns, rootInfo.exclusionPatterns)) {
- // parent is a non-Java resource because it doesn't have a valid package name (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=130982)
- return NON_JAVA_RESOURCE;
- }
- String sourceLevel = rootInfo.project == null ? null : rootInfo.project.getOption(JavaScriptCore.COMPILER_SOURCE, true);
- String complianceLevel = rootInfo.project == null ? null : rootInfo.project.getOption(JavaScriptCore.COMPILER_COMPLIANCE, true);
- if (Util.isValidFolderNameForPackage(res.getName(), sourceLevel, complianceLevel)) {
- return IJavaScriptElement.PACKAGE_FRAGMENT;
- }
- return NON_JAVA_RESOURCE;
- }
- String fileName = res.getName();
- String sourceLevel = rootInfo.project == null ? null : rootInfo.project.getOption(JavaScriptCore.COMPILER_SOURCE, true);
- String complianceLevel = rootInfo.project == null ? null : rootInfo.project.getOption(JavaScriptCore.COMPILER_COMPLIANCE, true);
- boolean isSource = rootInfo.entryKind == IIncludePathEntry.CPE_SOURCE;
- if ((Util.isValidClassFileName(fileName, sourceLevel, complianceLevel) || Util.isMetadataFileName(fileName)) && !isSource) {
- return IJavaScriptElement.CLASS_FILE;
- } else if (Util.isValidCompilationUnitName(fileName, sourceLevel, complianceLevel)) {
- return IJavaScriptElement.JAVASCRIPT_UNIT;
- } else if ((rootInfo = this.rootInfo(res.getFullPath(), kind)) != null
- && rootInfo.project.getProject().getFullPath().isPrefixOf(res.getFullPath()) /*ensure root is a root of its project (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=185310) */) {
- // case of proj=src=bin and resource is a jar file on the classpath
- return IJavaScriptElement.PACKAGE_FRAGMENT_ROOT;
- } else {
- return NON_JAVA_RESOURCE;
- }
-
- default:
- return NON_JAVA_RESOURCE;
- }
- }
- /*
- * Flushes all deltas without firing them.
- */
- public void flush() {
- this.javaModelDeltas = new ArrayList();
- }
-
- private SourceElementParser getSourceElementParser(Openable element) {
- if (this.sourceElementParserCache == null)
- this.sourceElementParserCache = this.manager.indexManager.getSourceElementParser(element.getJavaScriptProject(), null/*requestor will be set by indexer*/);
- return this.sourceElementParserCache;
- }
- /*
- * Finds the root info this path is included in.
- * Returns null if not found.
- */
- private RootInfo enclosingRootInfo(IPath path, int kind) {
- while (path != null && path.segmentCount() > 0) {
- RootInfo rootInfo = this.rootInfo(path, kind);
- if (rootInfo != null) return rootInfo;
- path = path.removeLastSegments(1);
- }
- return null;
- }
- /*
- * Fire Java Model delta, flushing them after the fact after post_change notification.
- * If the firing mode has been turned off, this has no effect.
- */
- public void fire(IJavaScriptElementDelta customDelta, int eventType) {
- if (!this.isFiring) return;
-
- if (DEBUG) {
- System.out.println("-----------------------------------------------------------------------------------------------------------------------");//$NON-NLS-1$
- }
-
- IJavaScriptElementDelta deltaToNotify;
- if (customDelta == null){
- deltaToNotify = this.mergeDeltas(this.javaModelDeltas);
- } else {
- deltaToNotify = customDelta;
- }
-
- // Refresh internal scopes
- if (deltaToNotify != null) {
- Iterator scopes = this.manager.searchScopes.keySet().iterator();
- while (scopes.hasNext()) {
- AbstractSearchScope scope = (AbstractSearchScope)scopes.next();
- scope.processDelta(deltaToNotify);
- }
- JavaWorkspaceScope workspaceScope = this.manager.workspaceScope;
- if (workspaceScope != null)
- workspaceScope.processDelta(deltaToNotify);
- }
-
- // Notification
-
- // Important: if any listener reacts to notification by updating the listeners list or mask, these lists will
- // be duplicated, so it is necessary to remember original lists in a variable (since field values may change under us)
- IElementChangedListener[] listeners;
- int[] listenerMask;
- int listenerCount;
- synchronized (this.state) {
- listeners = this.state.elementChangedListeners;
- listenerMask = this.state.elementChangedListenerMasks;
- listenerCount = this.state.elementChangedListenerCount;
- }
-
- switch (eventType) {
- case DEFAULT_CHANGE_EVENT:
- firePostChangeDelta(deltaToNotify, listeners, listenerMask, listenerCount);
- fireReconcileDelta(listeners, listenerMask, listenerCount);
- break;
- case ElementChangedEvent.POST_CHANGE:
- firePostChangeDelta(deltaToNotify, listeners, listenerMask, listenerCount);
- fireReconcileDelta(listeners, listenerMask, listenerCount);
- break;
- }
- }
-
- private void firePostChangeDelta(
- IJavaScriptElementDelta deltaToNotify,
- IElementChangedListener[] listeners,
- int[] listenerMask,
- int listenerCount) {
-
- // post change deltas
- if (DEBUG){
- System.out.println("FIRING POST_CHANGE Delta ["+Thread.currentThread()+"]:"); //$NON-NLS-1$//$NON-NLS-2$
- System.out.println(deltaToNotify == null ? "<NONE>" : deltaToNotify.toString()); //$NON-NLS-1$
- }
- if (deltaToNotify != null) {
- // flush now so as to keep listener reactions to post their own deltas for subsequent iteration
- this.flush();
-
- // mark the operation stack has not modifying resources since resource deltas are being fired
- JavaModelOperation.setAttribute(JavaModelOperation.HAS_MODIFIED_RESOURCE_ATTR, null);
-
- notifyListeners(deltaToNotify, ElementChangedEvent.POST_CHANGE, listeners, listenerMask, listenerCount);
- }
- }
- private void fireReconcileDelta(
- IElementChangedListener[] listeners,
- int[] listenerMask,
- int listenerCount) {
-
-
- IJavaScriptElementDelta deltaToNotify = mergeDeltas(this.reconcileDeltas.values());
- if (DEBUG){
- System.out.println("FIRING POST_RECONCILE Delta ["+Thread.currentThread()+"]:"); //$NON-NLS-1$//$NON-NLS-2$
- System.out.println(deltaToNotify == null ? "<NONE>" : deltaToNotify.toString()); //$NON-NLS-1$
- }
- if (deltaToNotify != null) {
- // flush now so as to keep listener reactions to post their own deltas for subsequent iteration
- this.reconcileDeltas = new HashMap();
-
- notifyListeners(deltaToNotify, ElementChangedEvent.POST_RECONCILE, listeners, listenerMask, listenerCount);
- }
- }
- /*
- * Returns whether a given delta contains some information relevant to the JavaModel,
- * in particular it will not consider SYNC or MARKER only deltas.
- */
- private boolean isAffectedBy(IResourceDelta rootDelta){
- //if (rootDelta == null) System.out.println("NULL DELTA");
- //long start = System.currentTimeMillis();
- if (rootDelta != null) {
- // use local exception to quickly escape from delta traversal
- class FoundRelevantDeltaException extends RuntimeException {
- private static final long serialVersionUID = 7137113252936111022L; // backward compatible
- // only the class name is used (to differenciate from other RuntimeExceptions)
- }
- try {
- rootDelta.accept(new IResourceDeltaVisitor() {
- public boolean visit(IResourceDelta delta) /* throws CoreException */ {
- switch (delta.getKind()){
- case IResourceDelta.ADDED :
- case IResourceDelta.REMOVED :
- throw new FoundRelevantDeltaException();
- case IResourceDelta.CHANGED :
- // if any flag is set but SYNC or MARKER, this delta should be considered
- if (delta.getAffectedChildren().length == 0 // only check leaf delta nodes
- && (delta.getFlags() & ~(IResourceDelta.SYNC | IResourceDelta.MARKERS)) != 0) {
- throw new FoundRelevantDeltaException();
- }
- }
- return true;
- }
- });
- } catch(FoundRelevantDeltaException e) {
- //System.out.println("RELEVANT DELTA detected in: "+ (System.currentTimeMillis() - start));
- return true;
- } catch(CoreException e) { // ignore delta if not able to traverse
- }
- }
- //System.out.println("IGNORE SYNC DELTA took: "+ (System.currentTimeMillis() - start));
- return false;
- }
- /*
- * Returns whether the given element is a primary compilation unit in working copy mode.
- */
- private boolean isPrimaryWorkingCopy(IJavaScriptElement element, int elementType) {
- if (elementType == IJavaScriptElement.JAVASCRIPT_UNIT) {
- CompilationUnit cu = (CompilationUnit)element;
- return cu.isPrimary() && cu.isWorkingCopy();
- }
- return false;
- }
- /*
- * Returns whether the given resource is in one of the given output folders and if
- * it is filtered out from this output folder.
- */
- private boolean isResFilteredFromOutput(RootInfo rootInfo, OutputsInfo info, IResource res, int elementType) {
- if (info != null) {
- JavaProject javaProject = null;
- String sourceLevel = null;
- String complianceLevel = null;
- IPath resPath = res.getFullPath();
- for (int i = 0; i < info.outputCount; i++) {
- if (info.paths[i].isPrefixOf(resPath)) {
- if (info.traverseModes[i] != IGNORE) {
- // case of bin=src
- if (info.traverseModes[i] == SOURCE && elementType == IJavaScriptElement.CLASS_FILE) {
- return true;
- }
- // case of .class file under project and no source folder
- // proj=bin
- if (elementType == IJavaScriptElement.JAVASCRIPT_PROJECT && res instanceof IFile) {
- if (sourceLevel == null) {
- // Get java project to use its source and compliance levels
- javaProject = rootInfo == null ?
- (JavaProject)this.createElement(res.getProject(), IJavaScriptElement.JAVASCRIPT_PROJECT, null) :
- rootInfo.project;
- if (javaProject != null) {
- sourceLevel = javaProject.getOption(JavaScriptCore.COMPILER_SOURCE, true);
- complianceLevel = javaProject.getOption(JavaScriptCore.COMPILER_COMPLIANCE, true);
- }
- }
- if (Util.isValidClassFileName(res.getName(), sourceLevel, complianceLevel)) {
- return true;
- }
- }
- } else {
- return true;
- }
- }
- }
- }
- return false;
- }
- /*
- * Merges all awaiting deltas.
- */
- private IJavaScriptElementDelta mergeDeltas(Collection deltas) {
- if (deltas.size() == 0) return null;
- if (deltas.size() == 1) return (IJavaScriptElementDelta)deltas.iterator().next();
-
- if (VERBOSE) {
- System.out.println("MERGING " + deltas.size() + " DELTAS ["+Thread.currentThread()+"]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- Iterator iterator = deltas.iterator();
- JavaElementDelta rootDelta = new JavaElementDelta(this.manager.javaModel);
- boolean insertedTree = false;
- while (iterator.hasNext()) {
- JavaElementDelta delta = (JavaElementDelta)iterator.next();
- if (VERBOSE) {
- System.out.println(delta.toString());
- }
- IJavaScriptElement element = delta.getElement();
- if (this.manager.javaModel.equals(element)) {
- IJavaScriptElementDelta[] children = delta.getAffectedChildren();
- for (int j = 0; j < children.length; j++) {
- JavaElementDelta projectDelta = (JavaElementDelta) children[j];
- rootDelta.insertDeltaTree(projectDelta.getElement(), projectDelta);
- insertedTree = true;
- }
- IResourceDelta[] resourceDeltas = delta.getResourceDeltas();
- if (resourceDeltas != null) {
- for (int i = 0, length = resourceDeltas.length; i < length; i++) {
- rootDelta.addResourceDelta(resourceDeltas[i]);
- insertedTree = true;
- }
- }
- } else {
- rootDelta.insertDeltaTree(element, delta);
- insertedTree = true;
- }
- }
- if (insertedTree) return rootDelta;
- return null;
- }
- private void notifyListeners(IJavaScriptElementDelta deltaToNotify, int eventType, IElementChangedListener[] listeners, int[] listenerMask, int listenerCount) {
- final ElementChangedEvent extraEvent = new ElementChangedEvent(deltaToNotify, eventType);
- for (int i= 0; i < listenerCount; i++) {
- if ((listenerMask[i] & eventType) != 0){
- final IElementChangedListener listener = listeners[i];
- long start = -1;
- if (VERBOSE) {
- System.out.print("Listener #" + (i+1) + "=" + listener.toString());//$NON-NLS-1$//$NON-NLS-2$
- start = System.currentTimeMillis();
- }
- // wrap callbacks with Safe runnable for subsequent listeners to be called when some are causing grief
- SafeRunner.run(new ISafeRunnable() {
- public void handleException(Throwable exception) {
- Util.log(exception, "Exception occurred in listener of Java element change notification"); //$NON-NLS-1$
- }
- public void run() throws Exception {
- PerformanceStats stats = null;
- if(PERF) {
- stats = PerformanceStats.getStats(JavaModelManager.DELTA_LISTENER_PERF, listener);
- stats.startRun();
- }
- listener.elementChanged(extraEvent);
- if(PERF) {
- stats.endRun();
- }
- }
- });
- if (VERBOSE) {
- System.out.println(" -> " + (System.currentTimeMillis()-start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
- }
- }
- private void notifyTypeHierarchies(IElementChangedListener[] listeners, int listenerCount) {
- for (int i= 0; i < listenerCount; i++) {
- final IElementChangedListener listener = listeners[i];
- if (!(listener instanceof TypeHierarchy)) continue;
-
- // wrap callbacks with Safe runnable for subsequent listeners to be called when some are causing grief
- SafeRunner.run(new ISafeRunnable() {
- public void handleException(Throwable exception) {
- Util.log(exception, "Exception occurred in listener of Java element change notification"); //$NON-NLS-1$
- }
- public void run() throws Exception {
- TypeHierarchy typeHierarchy = (TypeHierarchy)listener;
- if (typeHierarchy.hasFineGrainChanges()) {
- // case of changes in primary working copies
- typeHierarchy.needsRefresh = true;
- typeHierarchy.fireChange();
- }
- }
- });
- }
- }
- /*
- * Generic processing for elements with changed contents:<ul>
- * <li>The element is closed such that any subsequent accesses will re-open
- * the element reflecting its new structure.
- * <li>An entry is made in the delta reporting a content change (K_CHANGE with F_CONTENT flag set).
- * </ul>
- */
- private void nonJavaResourcesChanged(Openable element, IResourceDelta delta)
- throws JavaScriptModelException {
-
- // reset non-java resources if element was open
- if (element.isOpen()) {
- JavaElementInfo info = (JavaElementInfo)element.getElementInfo();
- switch (element.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_MODEL :
- ((JavaModelInfo) info).nonJavaResources = null;
- currentDelta().addResourceDelta(delta);
- return;
- case IJavaScriptElement.JAVASCRIPT_PROJECT :
- ((JavaProjectElementInfo) info).setNonJavaResources(null);
-
- // if a package fragment root is the project, clear it too
- JavaProject project = (JavaProject) element;
- PackageFragmentRoot projectRoot =
- (PackageFragmentRoot) project.getPackageFragmentRoot(project.getProject());
- if (projectRoot.isOpen()) {
- ((PackageFragmentRootInfo) projectRoot.getElementInfo()).setNonJavaResources(
- null);
- }
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT :
- ((PackageFragmentInfo) info).setNonJavaResources(null);
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT :
- ((PackageFragmentRootInfo) info).setNonJavaResources(null);
- }
- }
-
- JavaElementDelta current = currentDelta();
- JavaElementDelta elementDelta = current.find(element);
- if (elementDelta == null) {
- // don't use find after creating the delta as it can be null (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=63434)
- elementDelta = current.changed(element, IJavaScriptElementDelta.F_CONTENT);
- }
- elementDelta.addResourceDelta(delta);
- }
- /*
- * Returns the other root infos for the given path. Look in the old other roots table if kind is REMOVED.
- */
- private ArrayList otherRootsInfo(IPath path, int kind) {
- if (kind == IResourceDelta.REMOVED) {
- return (ArrayList)this.state.oldOtherRoots.get(path);
- }
- return (ArrayList)this.state.otherRoots.get(path);
- }
-
- private OutputsInfo outputsInfo(RootInfo rootInfo, IResource res) {
- try {
- JavaProject proj =
- rootInfo == null ?
- (JavaProject)this.createElement(res.getProject(), IJavaScriptElement.JAVASCRIPT_PROJECT, null) :
- rootInfo.project;
- if (proj != null) {
- IPath projectOutput = proj.getOutputLocation();
- int traverseMode = IGNORE;
- if (proj.getProject().getFullPath().equals(projectOutput)){ // case of proj==bin==src
- return new OutputsInfo(new IPath[] {projectOutput}, new int[] {SOURCE}, 1);
- }
- IIncludePathEntry[] classpath = proj.getResolvedClasspath();
- IPath[] outputs = new IPath[classpath.length+1];
- int[] traverseModes = new int[classpath.length+1];
- int outputCount = 1;
- outputs[0] = projectOutput;
- traverseModes[0] = traverseMode;
- for (int i = 0, length = classpath.length; i < length; i++) {
- IIncludePathEntry entry = classpath[i];
- IPath entryPath = entry.getPath();
-
- // check case of src==bin
- if (entryPath.equals(projectOutput)) {
- traverseModes[0] = (entry.getEntryKind() == IIncludePathEntry.CPE_SOURCE) ? SOURCE : BINARY;
- }
- }
- return new OutputsInfo(outputs, traverseModes, outputCount);
- }
- } catch (JavaScriptModelException e) {
- // java project doesn't exist: ignore
- }
- return null;
- }
- private void popUntilPrefixOf(IPath path) {
- while (this.currentElement != null) {
- IPath currentElementPath = null;
- if (this.currentElement instanceof IPackageFragmentRoot) {
- currentElementPath = ((IPackageFragmentRoot)this.currentElement).getPath();
- } else {
- IResource currentElementResource = this.currentElement.getResource();
- if (currentElementResource != null) {
- currentElementPath = currentElementResource.getFullPath();
- }
- }
- if (currentElementPath != null) {
- if (this.currentElement instanceof IPackageFragment
- && ((IPackageFragment) this.currentElement).isDefaultPackage()
- && currentElementPath.segmentCount() != path.segmentCount()-1) {
- // default package and path is not a direct child
- this.currentElement = (Openable)this.currentElement.getParent();
- }
- if (currentElementPath.isPrefixOf(path)) {
- return;
- }
- }
- this.currentElement = (Openable)this.currentElement.getParent();
- }
- }
- /*
- * Converts a <code>IResourceDelta</code> rooted in a <code>Workspace</code> into
- * the corresponding set of <code>IJavaScriptElementDelta</code>, rooted in the
- * relevant <code>JavaModel</code>s.
- */
- private IJavaScriptElementDelta processResourceDelta(IResourceDelta changes) {
-
- try {
- IJavaScriptModel model = this.manager.getJavaModel();
- if (!model.isOpen()) {
- // force opening of java model so that java element delta are reported
- try {
- model.open(null);
- } catch (JavaScriptModelException e) {
- if (VERBOSE) {
- e.printStackTrace();
- }
- return null;
- }
- }
- this.state.initializeRoots();
- this.currentElement = null;
-
- // get the workspace delta, and start processing there.
- IResourceDelta[] deltas = changes.getAffectedChildren();
- for (int i = 0; i < deltas.length; i++) {
- IResourceDelta delta = deltas[i];
- IResource res = delta.getResource();
-
- // find out the element type
- RootInfo rootInfo = null;
- int elementType;
- IProject proj = (IProject)res;
- boolean wasJavaProject = this.state.findJavaProject(proj.getName()) != null;
- boolean isJavaProject = JavaProject.hasJavaNature(proj);
- if (!wasJavaProject && !isJavaProject) {
- elementType = NON_JAVA_RESOURCE;
- } else {
- rootInfo = this.enclosingRootInfo(res.getFullPath(), delta.getKind());
- if (rootInfo != null && rootInfo.isRootOfProject(res.getFullPath())) {
- elementType = IJavaScriptElement.PACKAGE_FRAGMENT_ROOT;
- } else {
- elementType = IJavaScriptElement.JAVASCRIPT_PROJECT;
- }
- }
-
- // traverse delta
- this.traverseDelta(delta, elementType, rootInfo, null);
-
- if (elementType == NON_JAVA_RESOURCE
- || (wasJavaProject != isJavaProject && (delta.getKind()) == IResourceDelta.CHANGED)) { // project has changed nature (description or open/closed)
- try {
- // add child as non java resource
- nonJavaResourcesChanged((JavaModel)model, delta);
- } catch (JavaScriptModelException e) {
- // java model could not be opened
- }
- }
-
- }
- refreshPackageFragmentRoots();
- resetProjectCaches();
-
- return this.currentDelta;
- } finally {
- this.currentDelta = null;
- this.rootsToRefresh.clear();
- this.projectCachesToReset.clear();
- }
- }
- /*
- * Traverse the set of projects which have changed namespace, and reset their
- * caches and their dependents
- */
- public void resetProjectCaches() {
- if (this.projectCachesToReset.size() == 0)
- return;
-
- JavaModelManager.getJavaModelManager().resetJarTypeCache();
-
- Iterator iterator = this.projectCachesToReset.iterator();
- HashMap projectDepencies = this.state.projectDependencies;
- HashSet affectedDependents = new HashSet();
- while (iterator.hasNext()) {
- JavaProject project = (JavaProject)iterator.next();
- project.resetCaches();
- addDependentProjects(project, projectDepencies, affectedDependents);
- }
- // reset caches of dependent projects
- iterator = affectedDependents.iterator();
- while (iterator.hasNext()) {
- JavaProject project = (JavaProject) iterator.next();
- project.resetCaches();
- }
- }
- /*
- * Refresh package fragment roots of projects that were affected
- */
- private void refreshPackageFragmentRoots() {
- Iterator iterator = this.rootsToRefresh.iterator();
- while (iterator.hasNext()) {
- JavaProject project = (JavaProject)iterator.next();
- project.updatePackageFragmentRoots();
- }
- }
- /*
- * Registers the given delta with this delta processor.
- */
- public void registerJavaModelDelta(IJavaScriptElementDelta delta) {
- this.javaModelDeltas.add(delta);
- }
- /*
- * Removes the given element from its parents cache of children. If the
- * element does not have a parent, or the parent is not currently open,
- * this has no effect.
- */
- private void removeFromParentInfo(Openable child) {
-
- Openable parent = (Openable) child.getParent();
- if (parent != null && parent.isOpen()) {
- try {
- JavaElementInfo info = (JavaElementInfo)parent.getElementInfo();
- info.removeChild(child);
- } catch (JavaScriptModelException e) {
- // do nothing - we already checked if open
- }
- }
- }
- /*
- * Notification that some resource changes have happened
- * on the platform, and that the Java Model should update any required
- * internal structures such that its elements remain consistent.
- * Translates <code>IResourceDeltas</code> into <code>IJavaElementDeltas</code>.
- *
- * @see IResourceDelta
- * @see IResource
- */
- public void resourceChanged(IResourceChangeEvent event) {
-
- int eventType = this.overridenEventType == -1 ? event.getType() : this.overridenEventType;
- IResource resource = event.getResource();
- IResourceDelta delta = event.getDelta();
-
- switch(eventType){
- case IResourceChangeEvent.PRE_DELETE :
- try {
- if(resource.getType() == IResource.PROJECT
- && ((IProject) resource).hasNature(JavaScriptCore.NATURE_ID)) {
-
- deleting((IProject)resource);
- }
- } catch(CoreException e){
- // project doesn't exist or is not open: ignore
- }
- return;
-
- case IResourceChangeEvent.POST_CHANGE :
- if (isAffectedBy(delta)) { // avoid populating for SYNC or MARKER deltas
- try {
- try {
- stopDeltas();
- checkProjectsBeingAddedOrRemoved(delta);
-
- // generate classpath change deltas
- if (this.classpathChanges.size() > 0) {
- boolean hasDelta = this.currentDelta != null;
- JavaElementDelta javaDelta = currentDelta();
- Iterator changes = this.classpathChanges.values().iterator();
- while (changes.hasNext()) {
- ClasspathChange change = (ClasspathChange) changes.next();
- int result = change.generateDelta(javaDelta);
- if ((result & ClasspathChange.HAS_DELTA) != 0) {
- hasDelta = true;
- change.requestIndexing();
- this.state.addClasspathValidation(change.project);
- }
- if ((result & ClasspathChange.HAS_PROJECT_CHANGE) != 0) {
- this.state.addProjectReferenceChange(change.project, change.oldResolvedClasspath);
- }
- }
- this.classpathChanges.clear();
- if (!hasDelta)
- this.currentDelta = null;
- }
-
- // generate external archive change deltas
- if (this.refreshedElements != null) {
- createExternalArchiveDelta(null);
- }
-
- // generate Java deltas from resource changes
- IJavaScriptElementDelta translatedDelta = processResourceDelta(delta);
- if (translatedDelta != null) {
- registerJavaModelDelta(translatedDelta);
- }
- } finally {
- this.sourceElementParserCache = null; // don't hold onto parser longer than necessary
- startDeltas();
- }
- IElementChangedListener[] listeners;
- int listenerCount;
- synchronized (this.state) {
- listeners = this.state.elementChangedListeners;
- listenerCount = this.state.elementChangedListenerCount;
- }
- notifyTypeHierarchies(listeners, listenerCount);
- fire(null, ElementChangedEvent.POST_CHANGE);
- } finally {
- // workaround for bug 15168 circular errors not reported
- this.state.resetOldJavaProjectNames();
- this.oldRoots = null;
- }
- }
- return;
-
- case IResourceChangeEvent.PRE_BUILD :
- if(!isAffectedBy(delta))
- return; // avoid populating for SYNC or MARKER deltas
-
- // create classpath markers if necessary
- boolean needCycleValidation = validateClasspaths(delta);
- ClasspathValidation[] validations = this.state.removeClasspathValidations();
- if (validations != null) {
- for (int i = 0, length = validations.length; i < length; i++) {
- ClasspathValidation validation = validations[i];
- validation.validate();
- }
- }
-
- // update project references if necessary
- ProjectReferenceChange[] projectRefChanges = this.state.removeProjectReferenceChanges();
- if (projectRefChanges != null) {
- for (int i = 0, length = projectRefChanges.length; i < length; i++) {
- try {
- projectRefChanges[i].updateProjectReferencesIfNecessary();
- } catch(JavaScriptModelException e) {
- // project doesn't exist any longer, continue with next one
- }
- }
- }
-
- if (needCycleValidation || projectRefChanges != null) {
- // update all cycle markers since the project references changes may have affected cycles
- try {
- JavaProject.validateCycles(null);
- } catch (JavaScriptModelException e) {
- // a project no longer exists
- }
- }
-
- JavaModel.flushExternalFileCache();
- JavaBuilder.buildStarting();
-
- // does not fire any deltas
- return;
-
- case IResourceChangeEvent.POST_BUILD :
- JavaBuilder.buildFinished();
- return;
- }
- }
-
- /*
- * Returns the root info for the given path. Look in the old roots table if kind is REMOVED.
- */
- private RootInfo rootInfo(IPath path, int kind) {
- if (kind == IResourceDelta.REMOVED) {
- return (RootInfo)this.state.oldRoots.get(path);
- }
- return (RootInfo)this.state.roots.get(path);
- }
- /*
- * Turns the firing mode to on. That is, deltas that are/have been
- * registered will be fired.
- */
- private void startDeltas() {
- this.isFiring= true;
- }
- /*
- * Turns the firing mode to off. That is, deltas that are/have been
- * registered will not be fired until deltas are started again.
- */
- private void stopDeltas() {
- this.isFiring= false;
- }
- /*
- * Converts an <code>IResourceDelta</code> and its children into
- * the corresponding <code>IJavaScriptElementDelta</code>s.
- */
- private void traverseDelta(
- IResourceDelta delta,
- int elementType,
- RootInfo rootInfo,
- OutputsInfo outputsInfo) {
-
- IResource res = delta.getResource();
-
- // set stack of elements
- if (this.currentElement == null && rootInfo != null) {
- this.currentElement = rootInfo.project;
- }
-
- // process current delta
- boolean processChildren = true;
- if (res instanceof IProject) {
- // reset source element parser cache
- this.sourceElementParserCache = null;
-
- processChildren =
- this.updateCurrentDeltaAndIndex(
- delta,
- elementType == IJavaScriptElement.PACKAGE_FRAGMENT_ROOT ?
- IJavaScriptElement.JAVASCRIPT_PROJECT : // case of prj=src
- elementType,
- rootInfo);
- } else if (rootInfo != null) {
- processChildren = this.updateCurrentDeltaAndIndex(delta, elementType, rootInfo);
- } else {
- // not yet inside a package fragment root
- processChildren = true;
- }
-
- // get the project's output locations and traverse mode
- if (outputsInfo == null) outputsInfo = this.outputsInfo(rootInfo, res);
-
- // process children if needed
- if (processChildren) {
- IResourceDelta[] children = delta.getAffectedChildren();
- boolean oneChildOnClasspath = false;
- int length = children.length;
- IResourceDelta[] orphanChildren = null;
- Openable parent = null;
- boolean isValidParent = true;
- for (int i = 0; i < length; i++) {
- IResourceDelta child = children[i];
- IResource childRes = child.getResource();
-
- // check source attachment change
- this.checkSourceAttachmentChange(child, childRes);
-
- // find out whether the child is a package fragment root of the current project
- IPath childPath = childRes.getFullPath();
- int childKind = child.getKind();
- RootInfo childRootInfo = this.rootInfo(childPath, childKind);
- if (childRootInfo != null && !childRootInfo.isRootOfProject(childPath)) {
- // package fragment root of another project (dealt with later)
- childRootInfo = null;
- }
-
- // compute child type
- int childType =
- this.elementType(
- childRes,
- childKind,
- elementType,
- rootInfo == null ? childRootInfo : rootInfo
- );
-
- // is childRes in the output folder and is it filtered out ?
- boolean isResFilteredFromOutput = false; //this.isResFilteredFromOutput(rootInfo, outputsInfo, childRes, childType);
-
- boolean isNestedRoot = rootInfo != null && childRootInfo != null;
- if (!isResFilteredFromOutput
- && !isNestedRoot) { // do not treat as non-java rsc if nested root
-
- this.traverseDelta(child, childType, rootInfo == null ? childRootInfo : rootInfo, outputsInfo); // traverse delta for child in the same project
-
- if (childType == NON_JAVA_RESOURCE) {
- if (rootInfo != null) { // if inside a package fragment root
- if (!isValidParent) continue;
- if (parent == null) {
- // find the parent of the non-java resource to attach to
- if (this.currentElement == null
- || !rootInfo.project.equals(this.currentElement.getJavaScriptProject())) { // note if currentElement is the IJavaScriptModel, getJavaProject() is null
- // force the currentProject to be used
- this.currentElement = rootInfo.project;
- }
- if (elementType == IJavaScriptElement.JAVASCRIPT_PROJECT
- || (elementType == IJavaScriptElement.PACKAGE_FRAGMENT_ROOT
- && res instanceof IProject)) {
- // NB: attach non-java resource to project (not to its package fragment root)
- parent = rootInfo.project;
- } else {
- parent = this.createElement(res, elementType, rootInfo);
- }
- if (parent == null) {
- isValidParent = false;
- continue;
- }
- }
- // add child as non java resource
- try {
- nonJavaResourcesChanged(parent, child);
- } catch (JavaScriptModelException e) {
- // ignore
- }
- } else {
- // the non-java resource (or its parent folder) will be attached to the java project
- if (orphanChildren == null) orphanChildren = new IResourceDelta[length];
- orphanChildren[i] = child;
- }
- } else {
- oneChildOnClasspath = true;
- }
- } else {
- oneChildOnClasspath = true; // to avoid reporting child delta as non-java resource delta
- }
-
- // if child is a nested root
- // or if it is not a package fragment root of the current project
- // but it is a package fragment root of another project, traverse delta too
- if (isNestedRoot
- || (childRootInfo == null && (childRootInfo = this.rootInfo(childPath, childKind)) != null)) {
- this.traverseDelta(child, IJavaScriptElement.PACKAGE_FRAGMENT_ROOT, childRootInfo, null); // binary output of childRootInfo.project cannot be this root
- }
-
- // if the child is a package fragment root of one or several other projects
- ArrayList rootList;
- if ((rootList = this.otherRootsInfo(childPath, childKind)) != null) {
- Iterator iterator = rootList.iterator();
- while (iterator.hasNext()) {
- childRootInfo = (RootInfo) iterator.next();
- this.traverseDelta(child, IJavaScriptElement.PACKAGE_FRAGMENT_ROOT, childRootInfo, null); // binary output of childRootInfo.project cannot be this root
- }
- }
- }
- if (orphanChildren != null
- && (oneChildOnClasspath // orphan children are siblings of a package fragment root
- || res instanceof IProject)) { // non-java resource directly under a project
-
- // attach orphan children
- IProject rscProject = res.getProject();
- JavaProject adoptiveProject = (JavaProject)JavaScriptCore.create(rscProject);
- if (adoptiveProject != null
- && JavaProject.hasJavaNature(rscProject)) { // delta iff Java project (18698)
- for (int i = 0; i < length; i++) {
- if (orphanChildren[i] != null) {
- try {
- nonJavaResourcesChanged(adoptiveProject, orphanChildren[i]);
- } catch (JavaScriptModelException e) {
- // ignore
- }
- }
- }
- }
- } // else resource delta will be added by parent
- } // else resource delta will be added by parent
- }
-
- private void validateClasspaths(IResourceDelta delta, HashSet affectedProjects) {
- IResource resource = delta.getResource();
- boolean processChildren = false;
- switch (resource.getType()) {
- case IResource.ROOT :
- if (delta.getKind() == IResourceDelta.CHANGED) {
- processChildren = true;
- }
- break;
- case IResource.PROJECT :
- IProject project = (IProject)resource;
- int kind = delta.getKind();
- boolean isJavaProject = JavaProject.hasJavaNature(project);
- switch (kind) {
- case IResourceDelta.ADDED:
- processChildren = isJavaProject;
- affectedProjects.add(project.getFullPath());
- break;
- case IResourceDelta.CHANGED:
- processChildren = isJavaProject;
- if ((delta.getFlags() & IResourceDelta.OPEN) != 0) {
- // project opened or closed
- if (isJavaProject) {
- JavaProject javaProject = (JavaProject)JavaScriptCore.create(project);
- this.state.addClasspathValidation(javaProject); // in case .classpath got modified while closed
- }
- affectedProjects.add(project.getFullPath());
- } else if ((delta.getFlags() & IResourceDelta.DESCRIPTION) != 0) {
- boolean wasJavaProject = this.state.findJavaProject(project.getName()) != null;
- if (wasJavaProject != isJavaProject) {
- // project gained or lost Java nature
- JavaProject javaProject = (JavaProject)JavaScriptCore.create(project);
- this.state.addClasspathValidation(javaProject); // add/remove classpath markers
- affectedProjects.add(project.getFullPath());
- }
- }
- break;
- case IResourceDelta.REMOVED:
- affectedProjects.add(project.getFullPath());
- break;
- }
- break;
- case IResource.FILE :
- /* check classpath or prefs files change */
- IFile file = (IFile) resource;
- String fileName = file.getName();
- if (fileName.equals(JavaProject.CLASSPATH_FILENAME)) {
- JavaProject javaProject = (JavaProject)JavaScriptCore.create(file.getProject());
- this.state.addClasspathValidation(javaProject);
- affectedProjects.add(file.getProject().getFullPath());
- }
- break;
- }
- if (processChildren) {
- IResourceDelta[] children = delta.getAffectedChildren();
- for (int i = 0; i < children.length; i++) {
- validateClasspaths(children[i], affectedProjects);
- }
- }
- }
-
- /*
- * Validate the classpaths of the projects affected by the given delta.
- * Create markers if necessary.
- * Returns whether cycle markers should be recomputed.
- */
- private boolean validateClasspaths(IResourceDelta delta) {
- HashSet affectedProjects = new HashSet(5);
- validateClasspaths(delta, affectedProjects);
- boolean needCycleValidation = false;
-
- // validate classpaths of affected projects (dependent projects
- // or projects that reference a library in one of the projects that have changed)
- if (!affectedProjects.isEmpty()) {
- IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
- IProject[] projects = workspaceRoot.getProjects();
- 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;
- }
- }
- } catch(JavaScriptModelException e) {
- // project no longer exists
- }
- }
- }
- return needCycleValidation;
- }
-
- /*
- * Update the current delta (ie. add/remove/change the given element) and update the correponding index.
- * Returns whether the children of the given delta must be processed.
- * @throws a JavaScriptModelException if the delta doesn't correspond to a java element of the given type.
- */
- public boolean updateCurrentDeltaAndIndex(IResourceDelta delta, int elementType, RootInfo rootInfo) {
- Openable element;
- switch (delta.getKind()) {
- case IResourceDelta.ADDED :
- IResource deltaRes = delta.getResource();
- element = createElement(deltaRes, elementType, rootInfo);
- if (element == null) {
- // resource might be containing shared roots (see bug 19058)
- this.state.updateRoots(deltaRes.getFullPath(), delta, this);
- return rootInfo != null && rootInfo.inclusionPatterns != null;
- }
- updateIndex(element, delta);
- elementAdded(element, delta, rootInfo);
- if (elementType == IJavaScriptElement.PACKAGE_FRAGMENT_ROOT)
- this.state.addClasspathValidation(rootInfo.project);
- return elementType == IJavaScriptElement.PACKAGE_FRAGMENT;
- case IResourceDelta.REMOVED :
- deltaRes = delta.getResource();
- element = createElement(deltaRes, elementType, rootInfo);
- if (element == null) {
- // resource might be containing shared roots (see bug 19058)
- this.state.updateRoots(deltaRes.getFullPath(), delta, this);
- return rootInfo != null && rootInfo.inclusionPatterns != null;
- }
- updateIndex(element, delta);
- elementRemoved(element, delta, rootInfo);
- if (elementType == IJavaScriptElement.PACKAGE_FRAGMENT_ROOT)
- this.state.addClasspathValidation(rootInfo.project);
-
- if (deltaRes.getType() == IResource.PROJECT){
- // reset the corresponding project built state, since cannot reuse if added back
- if (JavaBuilder.DEBUG)
- System.out.println("Clearing last state for removed project : " + deltaRes); //$NON-NLS-1$
- this.manager.setLastBuiltState((IProject)deltaRes, null /*no state*/);
-
- // clean up previous session containers (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=89850)
- this.manager.previousSessionContainers.remove(element);
- }
- return elementType == IJavaScriptElement.PACKAGE_FRAGMENT;
- case IResourceDelta.CHANGED :
- int flags = delta.getFlags();
- if ((flags & IResourceDelta.CONTENT) != 0 || (flags & IResourceDelta.ENCODING) != 0) {
- // content or encoding has changed
- element = createElement(delta.getResource(), elementType, rootInfo);
- if (element == null) return false;
- updateIndex(element, delta);
- contentChanged(element);
- } else if (elementType == IJavaScriptElement.JAVASCRIPT_PROJECT) {
- if ((flags & IResourceDelta.OPEN) != 0) {
- // project has been opened or closed
- IProject res = (IProject)delta.getResource();
- element = createElement(res, elementType, rootInfo);
- if (element == null) {
- // resource might be containing shared roots (see bug 19058)
- this.state.updateRoots(res.getFullPath(), delta, this);
- return false;
- }
- if (res.isOpen()) {
- if (JavaProject.hasJavaNature(res)) {
- addToParentInfo(element);
- currentDelta().opened(element);
- this.state.updateRoots(element.getPath(), delta, this);
-
- // refresh pkg fragment roots and caches of the project (and its dependents)
- this.rootsToRefresh.add(element);
- this.projectCachesToReset.add(element);
-
- this.manager.indexManager.indexAll(res);
- }
- } else {
- boolean wasJavaProject = this.state.findJavaProject(res.getName()) != null;
- if (wasJavaProject) {
- close(element);
- removeFromParentInfo(element);
- currentDelta().closed(element);
- this.manager.indexManager.discardJobs(element.getElementName());
- this.manager.indexManager.removeIndexFamily(res.getFullPath());
- }
- }
- return false; // when a project is open/closed don't process children
- }
- if ((flags & IResourceDelta.DESCRIPTION) != 0) {
- IProject res = (IProject)delta.getResource();
- boolean wasJavaProject = this.state.findJavaProject(res.getName()) != null;
- boolean isJavaProject = JavaProject.hasJavaNature(res);
- if (wasJavaProject != isJavaProject) {
- // project's nature has been added or removed
- element = this.createElement(res, elementType, rootInfo);
- if (element == null) return false; // note its resources are still visible as roots to other projects
- if (isJavaProject) {
- elementAdded(element, delta, rootInfo);
- this.manager.indexManager.indexAll(res);
- } else {
- elementRemoved(element, delta, rootInfo);
- this.manager.indexManager.discardJobs(element.getElementName());
- this.manager.indexManager.removeIndexFamily(res.getFullPath());
- // reset the corresponding project built state, since cannot reuse if added back
- if (JavaBuilder.DEBUG)
- System.out.println("Clearing last state for project loosing Java nature: " + res); //$NON-NLS-1$
- this.manager.setLastBuiltState(res, null /*no state*/);
- }
- return false; // when a project's nature is added/removed don't process children
- }
- }
- }
- return true;
- }
- return true;
- }
- private void updateIndex(Openable element, IResourceDelta delta) {
-
- IndexManager indexManager = this.manager.indexManager;
- if (indexManager == null)
- return;
-
- switch (element.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_PROJECT :
- switch (delta.getKind()) {
- case IResourceDelta.ADDED :
- indexManager.indexAll(element.getJavaScriptProject().getProject());
- break;
- case IResourceDelta.REMOVED :
- indexManager.removeIndexFamily(element.getJavaScriptProject().getProject().getFullPath());
- // NB: Discarding index jobs belonging to this project was done during PRE_DELETE
- break;
- // NB: Update of index if project is opened, closed, or its java nature is added or removed
- // is done in updateCurrentDeltaAndIndex
- }
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT :
- if (element instanceof LibraryFragmentRoot) {
- LibraryFragmentRoot root = (LibraryFragmentRoot)element;
- // index jar file only once (if the root is in its declaring project)
- IPath jarPath = root.getPath();
- switch (delta.getKind()) {
- case IResourceDelta.ADDED:
- // index the new jar
- indexManager.indexLibrary((LibraryFragmentRoot)element, root.getJavaScriptProject().getProject());
- break;
- case IResourceDelta.CHANGED:
- // first remove the index so that it is forced to be re-indexed
- indexManager.removeIndex(jarPath);
- // then index the jar
- indexManager.indexLibrary((LibraryFragmentRoot)element, root.getJavaScriptProject().getProject());
- break;
- case IResourceDelta.REMOVED:
- // the jar was physically removed: remove the index
- indexManager.discardJobs(jarPath.toString());
- indexManager.removeIndex(jarPath);
- break;
- }
- break;
- }
- int kind = delta.getKind();
- if (kind == IResourceDelta.ADDED || kind == IResourceDelta.REMOVED) {
- PackageFragmentRoot root = (PackageFragmentRoot)element;
- this.updateRootIndex(root, CharOperation.NO_STRINGS, delta);
- break;
- }
- // don't break as packages of the package fragment root can be indexed below
- case IJavaScriptElement.PACKAGE_FRAGMENT :
- switch (delta.getKind()) {
- case IResourceDelta.ADDED:
- case IResourceDelta.REMOVED:
- IPackageFragment pkg = null;
- if (element instanceof IPackageFragmentRoot) {
- PackageFragmentRoot root = (PackageFragmentRoot)element;
- pkg = root.getPackageFragment(CharOperation.NO_STRINGS);
- } else {
- pkg = (IPackageFragment)element;
- }
- RootInfo rootInfo = rootInfo(pkg.getParent().getPath(), delta.getKind());
- boolean isSource =
- rootInfo == null // if null, defaults to source
- || rootInfo.entryKind == IIncludePathEntry.CPE_SOURCE;
- IResourceDelta[] children = delta.getAffectedChildren();
- for (int i = 0, length = children.length; i < length; i++) {
- IResourceDelta child = children[i];
- IResource resource = child.getResource();
- // TODO (philippe) Why do this? Every child is added anyway as the delta is walked
- if (resource instanceof IFile) {
- String name = resource.getName();
- if (isSource) {
- if (org.eclipse.wst.jsdt.internal.core.util.Util.isJavaLikeFileName(name)) {
- Openable cu = (Openable)pkg.getJavaScriptUnit(name);
- this.updateIndex(cu, child);
- }
- } else if (org.eclipse.wst.jsdt.internal.compiler.util.Util.isClassFileName(name)) {
- Openable classFile = (Openable)pkg.getClassFile(name);
- this.updateIndex(classFile, child);
- }
- }
- }
- break;
- }
- break;
- case IJavaScriptElement.CLASS_FILE :
- IFile file = (IFile) delta.getResource();
- IJavaScriptProject project = element.getJavaScriptProject();
- IPath binaryFolderPath = element.getPackageFragmentRoot().getPath();
-
- switch (delta.getKind()) {
- case IResourceDelta.CHANGED :
- // no need to index if the content has not changed
- int flags = delta.getFlags();
- if ((flags & IResourceDelta.CONTENT) == 0 && (flags & IResourceDelta.ENCODING) == 0)
- break;
- case IResourceDelta.ADDED :
- indexManager.addBinary(file, binaryFolderPath);
- break;
- case IResourceDelta.REMOVED :
- String containerRelativePath = Util.relativePath(file.getFullPath(), binaryFolderPath.segmentCount());
- indexManager.remove(containerRelativePath, binaryFolderPath);
- break;
- }
- break;
- case IJavaScriptElement.JAVASCRIPT_UNIT :
- file = (IFile) delta.getResource();
- switch (delta.getKind()) {
- case IResourceDelta.CHANGED :
- // no need to index if the content has not changed
- int flags = delta.getFlags();
- if ((flags & IResourceDelta.CONTENT) == 0 && (flags & IResourceDelta.ENCODING) == 0)
- break;
- case IResourceDelta.ADDED :
- indexManager.addSource(file, file.getProject().getFullPath(), getSourceElementParser(element));
- // Clean file from secondary types cache but do not update indexing secondary type cache as it will be updated through indexing itself
- this.manager.secondaryTypesRemoving(file, false);
- break;
- case IResourceDelta.REMOVED :
- indexManager.remove(Util.relativePath(file.getFullPath(), 1/*remove project segment*/), file.getProject().getFullPath());
- // Clean file from secondary types cache and update indexing secondary type cache as indexing cannot remove secondary types from cache
- this.manager.secondaryTypesRemoving(file, true);
- break;
- }
- }
- }
- /*
- * Update Java Model given some delta
- */
- public void updateJavaModel(IJavaScriptElementDelta customDelta) {
-
- if (customDelta == null){
- for (int i = 0, length = this.javaModelDeltas.size(); i < length; i++){
- IJavaScriptElementDelta delta = (IJavaScriptElementDelta)this.javaModelDeltas.get(i);
- this.modelUpdater.processJavaDelta(delta);
- }
- } else {
- this.modelUpdater.processJavaDelta(customDelta);
- }
- }
- /*
- * Updates the index of the given root (assuming it's an addition or a removal).
- * This is done recusively, pkg being the current package.
- */
- private void updateRootIndex(PackageFragmentRoot root, String[] pkgName, IResourceDelta delta) {
- Openable pkg = root.getPackageFragment(pkgName);
- this.updateIndex(pkg, delta);
- IResourceDelta[] children = delta.getAffectedChildren();
- for (int i = 0, length = children.length; i < length; i++) {
- IResourceDelta child = children[i];
- IResource resource = child.getResource();
- if (resource instanceof IFolder) {
- String[] subpkgName = Util.arrayConcat(pkgName, resource.getName());
- this.updateRootIndex(root, subpkgName, child);
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DiscardWorkingCopyOperation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DiscardWorkingCopyOperation.java
deleted file mode 100644
index f2b1ecb2..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DiscardWorkingCopyOperation.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*******************************************************************************
- * 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.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptElementDelta;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-
-/**
- * Discards a working copy (decrement its use count and remove its working copy info if the use count is 0)
- * and signal its removal through a delta.
- */
-public class DiscardWorkingCopyOperation extends JavaModelOperation {
-
- public DiscardWorkingCopyOperation(IJavaScriptElement workingCopy) {
- super(new IJavaScriptElement[] {workingCopy});
- }
- protected void executeOperation() throws JavaScriptModelException {
- CompilationUnit workingCopy = getWorkingCopy();
-
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- int useCount = manager.discardPerWorkingCopyInfo(workingCopy);
- if (useCount == 0) {
- IJavaScriptProject javaProject = workingCopy.getJavaScriptProject();
- if (ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals(javaProject.getElementName())) {
- manager.removePerProjectInfo((JavaProject) javaProject);
- manager.containerRemove(javaProject);
- }
- if (!workingCopy.isPrimary()) {
- // report removed java delta for a non-primary working copy
- JavaElementDelta delta = new JavaElementDelta(getJavaModel());
- delta.removed(workingCopy);
- addDelta(delta);
- removeReconcileDelta(workingCopy);
- } else {
- if (workingCopy.getResource().isAccessible()) {
- // report a F_PRIMARY_WORKING_COPY change delta for a primary working copy
- JavaElementDelta delta = new JavaElementDelta(getJavaModel());
- delta.changed(workingCopy, IJavaScriptElementDelta.F_PRIMARY_WORKING_COPY);
- addDelta(delta);
- } else {
- // report a REMOVED delta
- JavaElementDelta delta = new JavaElementDelta(getJavaModel());
- delta.removed(workingCopy, IJavaScriptElementDelta.F_PRIMARY_WORKING_COPY);
- addDelta(delta);
- }
- }
- }
- }
- /**
- * Returns the working copy this operation is working on.
- */
- protected CompilationUnit getWorkingCopy() {
- return (CompilationUnit)getElementToProcess();
- }
- /**
- * @see JavaModelOperation#isReadOnly
- */
- public boolean isReadOnly() {
- return true;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DocumentAdapter.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DocumentAdapter.java
deleted file mode 100644
index c2e242e3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DocumentAdapter.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 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
- * 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.jface.text.BadLocationException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.wst.jsdt.core.IBuffer;
-
-/*
- * Adapts an IBuffer to IDocument
- */
-public class DocumentAdapter extends Document {
-
- private IBuffer buffer;
-
- public DocumentAdapter(IBuffer buffer) {
- super(buffer.getContents());
- this.buffer = buffer;
- }
-
- public void set(String text) {
- super.set(text);
- this.buffer.setContents(text);
- }
-
- public void replace(int offset, int length, String text) throws BadLocationException {
- super.replace(offset, length, text);
- this.buffer.replace(offset, length, text);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DocumentContextFragment.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DocumentContextFragment.java
deleted file mode 100644
index 03666852..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DocumentContextFragment.java
+++ /dev/null
@@ -1,187 +0,0 @@
-/*******************************************************************************
- * 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
- * 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.core.resources.IContainer;
-import org.eclipse.core.resources.IResource;
-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.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-
-public class DocumentContextFragment extends PackageFragment{
-
- private String fileInScope;
-
- protected DocumentContextFragment(PackageFragmentRoot root, String names) {
- super(root, new String[] {names});
- this.names =new String[] {names};
- fileInScope = names;
- }
-// protected DocumentContextFragment(PackageFragmentRoot root, IPath you, String[] names) {
-// super(root, new String[0]);
-// filesInScope = names;
-// this.names = names;
-// me = you;
-// }
-//
-// public IPath resolveRelativePath(String path) {
-// IResource member = getRelativeAsResource(path);
-// if(member!=null) return member.getLocation();
-// return ((DocumentContextFragmentRoot)parent).resolveRelativePath(path);
-// }
-//
-// public IResource getRelativeAsResource(String path) {
-//
-// return ((DocumentContextFragmentRoot)parent).getRelativeAsResource(path);
-// }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.core.PackageFragment#buildStructure(org.eclipse.wst.jsdt.internal.core.OpenableElementInfo, org.eclipse.core.runtime.IProgressMonitor, java.util.Map, org.eclipse.core.resources.IResource)
- */
-// protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaScriptModelException {
-// IJavaScriptElement[] children = info.getChildren();
-// for(int k = 0;k<children.length;k++) {
-// if(children[k] instanceof JavaScriptUnit) {
-// try {
-// CompilationUnitElementInfo compInfo = new CompilationUnitElementInfo();
-// IPath myPath = ((JavaScriptUnit)children[k]).getPath();
-// IContainer parent = ((IContainer)getParent().getResource());
-// IResource me = parent.findMember(myPath);
-// //((JavaScriptUnit)children[k]).openWhenClosed(compInfo, pm);
-// //((JavaScriptUnit)children[k]).buildStructure(compInfo, pm, newElements, me);
-//
-// } catch (/*JavaScriptModelException*/ Exception ex) {
-// // TODO Auto-generated catch block
-// ex.printStackTrace();
-// }
-// }
-// info.addChild(children[k]);
-// }
-// return true;
-//
-// }
-
- protected boolean computeChildren(OpenableElementInfo info) {
- //for(int i = 0;i<filesInScope.length;i++) {
- //ClassFile classFile = new ClassFile(this,resolvePath(filesInScope[i]).toOSString());
-// JavaScriptUnit cu= new JavaScriptUnit(this, this.getPackageFragmentRoot().getPath().toOSString(), DefaultWorkingCopyOwner.PRIMARY);
- IJavaScriptElement[] children= new IJavaScriptElement[]{getJavaElement(fileInScope)};
- for(int k=0;k<children.length;k++) {
-
- info.addChild(children[k]);
- }
- //}
- return true;
- }
-
- public IJavaScriptElement getJavaElement(String resource) {
- /* if resource exists in project, return compunit, else return class */
- //if(!DocumentContextFragmentRoot.RETURN_CU) return getClassFile(resource);
-// IPath workspacePath = getPackageFragmentRoot().getJavaProject().getProject().getWorkspace().getRoot().getLocation();
- /* remove the file part of the path */
- IResource elementResource=null;
- if(getResource() instanceof IContainer) {
- elementResource = ((IContainer)getResource()).findMember(resource);
- }
- //if(true) return getClassFile(resource);
-
- if(elementResource!=null && elementResource.exists()) {
- try {
- //return createCompilationUnit(resource, null, true, new NullProgressMonitor());
- IJavaScriptUnit unit = getJavaScriptUnit(resource);
- //((JavaScriptUnit)unit).buildStructure(new CompilationUnitElementInfo(), new NullProgressMonitor(), new HashMap(), ((IContainer)getParent().getResource()).findMember(resource));
- //unit.makeConsistent(new NullProgressMonitor());
- //((JavaElement)unit).openWhenClosed(new CompilationUnitElementInfo(), new NullProgressMonitor());
-// boolean unitExists = unit.exists();
- return unit;
- } catch (Exception ex) {
- // TODO Auto-generated catch block
- ex.printStackTrace();
- }
- return null;
- }else {
- return getClassFile(resource);
- }
-
- }
-
-
- public IClassFile[] getClassFiles() throws JavaScriptModelException {
-// IClassFile[] classFiles = new IClassFile[filesInScope.length];
-// for(int i = 0;i<filesInScope.length;i++) {
-// ClassFile classFile = new ClassFile(this,filesInScope[i]);
-// classFiles[i] = classFile;
-//
-// }
-// return classFiles;
- return new IClassFile[] { new ClassFile(this,fileInScope) };
- }
-
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.core.PackageFragment#getKind()
- */
- public int getKind() throws JavaScriptModelException {
- if(hasSource()) return IPackageFragmentRoot.K_SOURCE;
- return super.getKind();
- }
-
- public boolean hasSource() {
- //if(DocumentContextFragmentRoot.RETURN_CU /*&& filesInScope.length>0*/) {
- IResource file = ((IContainer)parent.getResource()).findMember(fileInScope);
- if(file!=null && file.exists()) return true;
- // }
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.core.PackageFragment#getResource()
- */
- public IResource getResource() {
- IPath resourcePath = new Path(fileInScope);
- return ((IContainer)parent.getResource()).findMember(resourcePath.removeLastSegments(1));
-
- }
-
- public IClassFile getClassFile(String classFileName) {
- return new ClassFile(this,classFileName);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.core.PackageFragment#getCompilationUnit(java.lang.String)
- */
- public IJavaScriptUnit getJavaScriptUnit(String cuName) {
- return new CompilationUnit(this, cuName, DefaultWorkingCopyOwner.PRIMARY);
- }
-
- public IJavaScriptUnit createCompilationUnit(String cuName, String contents, boolean force, IProgressMonitor monitor) throws JavaScriptModelException {
- CreateCompilationUnitOperation op= new CreateCompilationUnitOperation(this, cuName, contents, force);
- op.runOperation(monitor);
- return new CompilationUnit(this, cuName, DefaultWorkingCopyOwner.PRIMARY);
- }
-
- public String getElementName() {
- return DEFAULT_PACKAGE_NAME;
- }
-
- public boolean isDefaultPackage() {
- return true;
- }
-
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DocumentContextFragmentRoot.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DocumentContextFragmentRoot.java
deleted file mode 100644
index 180848ad..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DocumentContextFragmentRoot.java
+++ /dev/null
@@ -1,644 +0,0 @@
-/*******************************************************************************
- * 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
- * bug:244839 - eugene@genuitec.com
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.NullProgressMonitor;
-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.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JSDScopeUtil;
-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.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.internal.compiler.env.AccessRestriction;
-import org.eclipse.wst.jsdt.internal.core.search.IRestrictedAccessBindingRequestor;
-import org.eclipse.wst.jsdt.internal.core.search.JavaSearchScope;
-
-
-public class DocumentContextFragmentRoot extends PackageFragmentRoot{
-
- /*
- * if user includes dojo.js check if dojo.js.uncompressed.js exists instead and replace with that.
- */
- public static final boolean HACK_DOJO= true;
- private final String UNCOMPRESSED_DOJO="dojo.js.uncompressed.js"; //$NON-NLS-1$
- private final String DOJO_COMPRESSED = "dojo.js"; //$NON-NLS-1$
- //private static final ClasspathAttribute HIDE = new ClasspathAttribute("hide","true"); //$NON-NLS-1$ //$NON-NLS-2$
- private String[] includedFiles;
- //private Long[] timeStamps;
- private IFile fRelativeFile;
- private IResource absolutePath;
- private IPath webContext;
- private IIncludePathEntry rawClassPathEntry;
-
- //public static final boolean RETURN_CU = true;
- private static final boolean DEBUG = false;
- //private boolean dirty;
-
- private static int instances=0;
- private IJavaScriptUnit[] workingCopies;
- private String[] fSystemFiles;
- private RestrictedDocumentBinding importPolice;
-
- class RestrictedDocumentBinding implements IRestrictedAccessBindingRequestor {
-
- private ArrayList foundPaths=new ArrayList();
- private String exclude;
- private boolean shown;
-
- public void reset() {
- foundPaths.clear();
- shown=false;
- }
-
- public boolean acceptBinding(int type,int modifiers, char[] packageName,char[] simpleTypeName, String path, AccessRestriction access) {
- if(path!=null && exclude!=null && path.compareTo(exclude)==0) return false;
-
- if(DEBUG && !shown) {
- shown=false;
- IJavaScriptProject proj = getJavaScriptProject();
- try {
- IIncludePathEntry[] entries = proj.getResolvedIncludepath(true);
- System.out.println("DocumentContextFragmentRoot ====>" +"Project Classpath : \n"); //$NON-NLS-1$ //$NON-NLS-2$
-
- for(int i = 0;i<entries.length;i++) {
- System.out.println("\t" + entries[i].getPath()); //$NON-NLS-1$
-
- }
- } catch (JavaScriptModelException ex) {
- // TODO Auto-generated catch block
- ex.printStackTrace();
- }
- }
- for (int i = 0; workingCopies!=null && i < workingCopies.length; i++) {
- if (workingCopies[i].getPath().toString().equals(path)) {
- if(DEBUG) System.out.println("DocumentContextFragmentRoot ====>" +"REJECTING binding..\n\t" + new String(simpleTypeName) + " in " + path + "\n\tfor file " + fRelativeFile.toString()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- if(DEBUG) System.out.println("\tType is in WorkingCopies "); //$NON-NLS-1$
- return false;
- }
- }
-
- this.foundPaths.add(path);
- return true;
-
-// for(int i = 0;i<includedFiles.length;i++) {
-// if(Util.isSameResourceString(path, includedFiles[i])) {
-// if(DEBUG) System.out.println("DocumentContextFragmentRoot ====>" + "Accepting binding.. " + new String(simpleTypeName) + " in " + path + "\n\tfor file " + fRelativeFile.toString()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-// this.foundPaths.add(path);
-// return true;
-// } else if(includedFiles[i].equals("*")) { //$NON-NLS-1$
-// this.foundPaths.add(path);
-// return true;
-// }
-// else if(HACK_DOJO) {
-// String includeString = includedFiles[i];
-// if(path.toLowerCase().indexOf(DOJO_COMPRESSED)>0 && (includeString.toLowerCase().indexOf(UNCOMPRESSED_DOJO)>0)) {
-// this.foundPaths.add(path);
-// return true;
-// }
-//
-// }
-// }
-//
-// String systemFiles[] = getProjectSystemFiles();
-//
-// for(int i = 0;i<systemFiles.length;i++) {
-// if(Util.isSameResourceString(path, systemFiles[i]) || (new Path(systemFiles[i])).isPrefixOf(new Path(path))) {
-// if(DEBUG) System.out.println("DocumentContextFragmentRoot ====>" + "Accepting binding.. " + new String(simpleTypeName) + " in " + path + " \n\tfor file " + fRelativeFile.toString()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-// this.foundPaths.add(path);
-// return true;
-// }
-// }
-// if(DEBUG) System.out.println("DocumentContextFragmentRoot ====>" +"REJECTING binding..\n\t" + new String(simpleTypeName) + " in " + path + " \n\tfor file " + fRelativeFile.toString()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-// if(DEBUG) System.out.println("\t(relative) page includes = : " ); //$NON-NLS-1$
-// if(DEBUG) {
-// for(int i = 0;includedFiles!=null && i<includedFiles.length;i++) {
-// System.out.println("\t\t" + includedFiles[i]); //$NON-NLS-1$
-// }
-// }
-// //this.foundPath=null;
-// return false;
- }
-
- public String getFoundPath() {
- return foundPaths.size()>0?(String)foundPaths.get(0):null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.core.search.IRestrictedAccessBindingRequestor#getFoundPaths()
- */
- public ArrayList getFoundPaths() {
- return foundPaths;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.core.search.IRestrictedAccessBindingRequestor#setExcludePath(java.lang.String)
- */
- public void setExcludePath(String excludePath) {
- this.exclude=excludePath;
-
- }
- }
-
- public String[] getProjectSystemFiles() {
-
- if(fSystemFiles!=null) return fSystemFiles;
-
- IJavaScriptProject javaProject = getJavaScriptProject();
- int lastGood = 0;
- IPackageFragmentRoot[] projectRoots = null;
-
- try {
- projectRoots = javaProject.getPackageFragmentRoots();
- for(int i =0;i<projectRoots.length;i++) {
- if(projectRoots[i].isLanguageRuntime()) {
- projectRoots[lastGood++]=projectRoots[i];
- }else if(projectRoots[i].getRawIncludepathEntry().getEntryKind()== IIncludePathEntry.CPE_SOURCE) {
- projectRoots[lastGood++]=projectRoots[i];
- }
- }
- } catch (JavaScriptModelException ex) {
- projectRoots = new IPackageFragmentRoot[0];
- }
-
- fSystemFiles = new String[lastGood ];
- for(int i = 0;i<fSystemFiles.length;i++) {
- fSystemFiles[i] = projectRoots[i].getPath().toString().intern();
- }
- return fSystemFiles;
- }
-
-
- public void classpathChange() {
- fSystemFiles=null;
- }
-
-
-
- public DocumentContextFragmentRoot(IJavaScriptProject project,
- IFile resourceRelativeFile,
- IPath resourceAbsolutePath,
- IPath webContext,
- IIncludePathEntry rawClassPath) {
-
- super(resourceRelativeFile, (JavaProject)project);
-
- fRelativeFile = resourceRelativeFile ;
- // this.includedFiles = new IPath[0];
- //this.timeStamps = new Long[0];
- this.absolutePath = ((IContainer)project.getResource()).findMember(resourceAbsolutePath);
- this.webContext=webContext;
- this.rawClassPathEntry = rawClassPath;
- //dirty = true;
- if(DEBUG) System.out.println("DocumentContextFragmentRoot ====>" + "Creating instance for total of:>>" + ++instances + "<<. \n\tRelative file:" + fRelativeFile.toString()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
-
- }
-
- public void finalize() {
-
- if(DEBUG) System.out.println("DocumentContextFragmentRoot ====>" + "finalize() for a total of:>>" + --instances + "<<. \n\tRelative file:" + fRelativeFile!=null?null:fRelativeFile.toString()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.core.PackageFragmentRoot#getRawClasspathEntry()
- */
- public IIncludePathEntry getRawIncludepathEntry() throws JavaScriptModelException {
- if(rawClassPathEntry!=null) return rawClassPathEntry;
- return super.getRawIncludepathEntry();
- }
-
- protected RestrictedDocumentBinding getRestrictedAccessRequestor() {
- if(importPolice==null) {
- importPolice = new RestrictedDocumentBinding();
- }
- importPolice.reset();
- return importPolice;
- }
-
- public DocumentContextFragmentRoot(IJavaScriptProject project,
- IFile resourceRelativeFile,
- IPath resourceAbsolutePath,
- IPath webContext) {
- this(project,resourceRelativeFile,resourceAbsolutePath,webContext,null);
- }
-
- public DocumentContextFragmentRoot(IJavaScriptProject project,
- IFile resourceRelativeFile) {
-
- this(project,resourceRelativeFile, new Path(""), new Path("")); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
-
- public void setIncludedFiles2(String[] fileNames) {
-
-
-
- ArrayList newImports = new ArrayList();
- //int arrayLength = 0;
-
- for(int i = 0; i<fileNames.length;i++) {
- File importFile = isValidImport(fileNames[i]);
- if(importFile==null) continue;
- IPath importPath = resolveChildPath(fileNames[i]);
- newImports.add( importPath.toString() );
- }
-
- boolean equals = includedFiles!=null && newImports.size()==includedFiles.length;
-
- for(int i=0;equals && i<newImports.size();i++) {
- if(((String)newImports.get(i)).compareTo(includedFiles[i])!=0) equals=false;
- }
-
- if(DEBUG) System.out.println("DocumentContextFragmentRoot ====>" + "Imports " + (equals?"did NOT change": "CHANGED:") + "\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- if(DEBUG) {
- for(int i = 0;includedFiles!=null && i<includedFiles.length;i++) {
- System.out.println("\t\t" + includedFiles[i]); //$NON-NLS-1$
- }
- }
- if(equals) return;
-/* start try and expand the include paths from the library entries if necisary */
- IIncludePathEntry[] current = new IIncludePathEntry[0];
- IJavaScriptProject javaProject = getJavaScriptProject();
-
- try {
- current = javaProject.getRawIncludepath();
- } catch (JavaScriptModelException ex) {
- // TODO Auto-generated catch block
- // ex.printStackTrace();
- }
- for(int i = 0;i<current.length;i++) {
- JsGlobalScopeContainerInitializer init = JSDScopeUtil.getContainerInitializer(current[i].getPath());
- for(int k=0;k<fileNames.length;k++) {
- String[] newEntries = init.resolvedLibraryImport(fileNames[k]);
- if(newEntries!=null && newEntries.length>0 ) {
- newImports.removeAll(Arrays.asList(newEntries));
- newImports.addAll(Arrays.asList(newEntries));
- }
- }
- }
-
-/* end class path expansion */
- this.includedFiles = (String[])newImports.toArray(new String[newImports.size()]);
- // System.arraycopy(newImports, 0, this.includedFiles, 0, arrayLength);
- updateClasspathIfNeeded();
- dojoHack();
- }
- public void setIncludedFiles(String[] fileNames) {
-
-
-
- String[] newImports = new String[fileNames.length];
- //Long[] newTimestamps = new Long[fileNames.length];
- int arrayLength = 0;
-
- for(int i = 0; i<fileNames.length;i++) {
- File importFile = isValidImport(fileNames[i]);
- if(importFile==null && !fileNames[i].equals("*")) continue; //$NON-NLS-1$
- if(fileNames[i].equals("*")) {
- newImports[arrayLength++] = fileNames[i];
- } else {
- IPath importPath = resolveChildPath(fileNames[i]);
- newImports[arrayLength++] = importPath.toString();
- }
- //newTimestamps[arrayLength] = new Long(importFile.lastModified());
-
- //arrayLength++;
- }
-
- boolean equals = includedFiles!=null && arrayLength==includedFiles.length;
-
- for(int i=0;equals && i<arrayLength;i++) {
- if(newImports[i].compareTo(includedFiles[i])!=0) equals=false;
- }
-
- //this.includedFiles!=null && (newImports !=null) && this.includedFiles.length == arrayLength;
-
- //equals = equals || (this.includedFiles==null && newImports ==null);
- //if(!equals) removeStaleClasspath(this.includedFiles);
-
- //
-//
-// if(!equals) dirty = true;
-//
-// /* try some more cases */
-//
-// for(int i = 0;!dirty && i<this.includedFiles.length;i++) {
-// if(!(this.includedFiles[i].equals(newImports[i]))) {
-// dirty = true;
-//
-// }
-// }
-//
-// for(int i = 0;!dirty && i<newTimestamps.length;i++) {
-// if(!(this.timeStamps[i].equals(newTimestamps[i]))) {
-// dirty = true;
-// }
-// }
-//
-// if(!dirty) return;
- if(DEBUG) System.out.println("DocumentContextFragmentRoot ====>" + "Imports " + (equals?"did NOT change": "CHANGED:") + "\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- if(DEBUG) {
- for(int i = 0;includedFiles!=null && i<includedFiles.length;i++) {
- System.out.println("\t\t" + includedFiles[i]); //$NON-NLS-1$
- }
- }
- if(equals) return;
- this.includedFiles = new String[arrayLength];
- // this.timeStamps = new Long[arrayLength];
- System.arraycopy(newImports, 0, this.includedFiles, 0, arrayLength);
- // System.arraycopy(newTimestamps, 0, this.timeStamps, 0, arrayLength);
- dojoHack();
- updateClasspathIfNeeded();
-
-
- }
- private void dojoHack() {
- if(!HACK_DOJO) return;
-
-
- for(int i = 0;i<includedFiles.length;i++) {
- String includeString = includedFiles[i];
-
- int dojoIndex = includeString.toLowerCase().indexOf(DOJO_COMPRESSED);
-
- if(includeString!=null && dojoIndex>=0) {
- /* found dojo.js replace it with dojo.js.uncompressed.js if it exists */
- String newIncludeString = includeString.substring(0, dojoIndex) + UNCOMPRESSED_DOJO + includeString.substring(dojoIndex + DOJO_COMPRESSED.length(),includeString.length());
- File djUncom = isValidImport(newIncludeString);
- if(djUncom!=null && djUncom.exists()) {
- includedFiles[i] = newIncludeString;
- }
- }
- }
- }
-
- //private void removeStaleClasspath(String[] oldEntries) {
-//
-// }
-
- private void updateClasspathIfNeeded() {
-
-
-
- ArrayList newEntriesList = new ArrayList();
- IJavaScriptProject javaProject = getJavaScriptProject();
- IResource myResource = getResource();
- IContainer folder = (IContainer)myResource;
-
- for(int i = 0;i<includedFiles.length;i++) {
- IResource theFile = folder.findMember(includedFiles[i]);
- if(theFile == null || javaProject.isOnIncludepath(theFile)) continue;
- IIncludePathEntry entry = JavaScriptCore.newLibraryEntry(theFile.getLocation().makeAbsolute(), null, null, new IAccessRule[0], new IIncludePathAttribute[] {IIncludePathAttribute.HIDE}, true);
-
- newEntriesList.add(entry);
- }
- IIncludePathEntry[] current = new IIncludePathEntry[0];
- try {
- current = javaProject.getRawIncludepath();
- } catch (JavaScriptModelException ex) {
- // TODO Auto-generated catch block
- // ex.printStackTrace();
- }
-
-
- IIncludePathEntry[] newCpEntries = new IIncludePathEntry[newEntriesList.size() + current.length];
- System.arraycopy(current, 0, newCpEntries, 0, current.length);
- int newPtr = 0 ;
- for(int i = current.length; i<newCpEntries.length;i++) {
- newCpEntries[i] = (IIncludePathEntry)newEntriesList.get(newPtr++);
- }
- try {
- javaProject.setRawIncludepath(newCpEntries, false, new NullProgressMonitor());
- } catch (JavaScriptModelException ex) {}
-
- }
-
- public IPath resolveChildPath(String childPathString) {
- // Genuitec Begin Fix 6149: Exception opening external HTML file
- if (getResource() == null) {
- return null;
- }
- // Genuitec End Fix 6149: Exception opening external HTML file
- /* relative paths:
- * ./testfile.js are relative to file scope
- * absolute paths: /scripts/file.js are relative to absolutePath, and must be made relative to this resource
- * if the file does not exist in context root, the path is the absolute path on the filesystem.
- */
- if(childPathString==null) return null;
- if(childPathString.length()==0) return new Path(""); //$NON-NLS-1$
- IPath resolvedPath = null;
- IResource member;
- switch(childPathString.charAt(0)) {
-
- default:
- resolvedPath = new Path(childPathString);
- //if(resolvedPath.toFile()!=null && resolvedPath.toFile().exists()) break;
-
- member = ((IContainer)getResource()).findMember(resolvedPath);
-
- if(member!=null && member.exists()) break;
- case '/':
- case '\\':
- IPath childPath = new Path(childPathString);
-
- IPath newPath = childPath.removeFirstSegments(childPath.matchingFirstSegments(webContext));
-
- member = ((IContainer)getResource()).findMember(newPath);
- //if(member.exists()) return new Path(newPath);
-
- resolvedPath = newPath;
- if(member!=null && member.exists()) break;
-
- case '.':
- /* returns a new relative path thats relative to the resource */
- IPath relative=null;
- try {
- relative = fRelativeFile.getFullPath().removeLastSegments(1);
- } catch (Exception ex) {
- /* file usually outside of workspace in this instance */
- return null;
- }
- IPath relRes = getResource().getFullPath();
- if(relRes.isPrefixOf(relative)) {
- IPath amended = relative.removeFirstSegments(relRes.matchingFirstSegments(relative));
- resolvedPath = amended.append(childPathString);
- }
- break;
-
-
- }
-
- return resolvedPath;
-
- }
-
- public IPath getPath() {
- if(fRelativeFile!=null) return fRelativeFile.getFullPath().removeLastSegments(1);
- return super.getPath();
- }
-
- public boolean equals(Object o) {
-// if (this == o)
-// return true;
- if (!(o instanceof DocumentContextFragmentRoot)) return false;
-
- DocumentContextFragmentRoot other= (DocumentContextFragmentRoot) o;
-
-
-
- boolean equalRelativeFileAndIncludedFileLengths = (this.fRelativeFile!=null && this.fRelativeFile.equals(other.fRelativeFile)) &&
- this.includedFiles!=null && (other.includedFiles !=null) &&
- this.includedFiles.length == other.includedFiles.length;
-
- if(!equalRelativeFileAndIncludedFileLengths) return false;
-
- /* try some more cases */
-
- for(int i = 0;i<this.includedFiles.length;i++) {
- if(!(this.includedFiles[i].equals(other.includedFiles[i]))) return false;
- }
-
-// for(int i = 0;i<this.timeStamps.length;i++) {
-// if(!(this.timeStamps[i].equals( other.timeStamps[i] ) )) return false;
-// }
-
-
- return true;
- }
-
- public String getElementName() {
- if(fRelativeFile!=null) return this.fRelativeFile.getName();
- return super.getElementName();
- }
-
- public int hashCode() {
- return fRelativeFile!=null?this.fRelativeFile.hashCode():super.hashCode();
- }
-
- public boolean isExternal() {
- return false;
- }
- /**
- * Jars and jar entries are all read only
- */
- public boolean isReadOnly() {
- return false;
- }
-
- /**
- * Returns whether the corresponding resource or associated file exists
- */
- protected boolean resourceExists() {
- return true;
- }
-
-
- public SearchableEnvironment newSearchableNameEnvironment(WorkingCopyOwner owner) throws JavaScriptModelException {
- /* previously restricted searchable environment to 'this'. But that removes library entries from search results so going back to global project */
- SearchableEnvironment env = super.newSearchableNameEnvironment(owner);//new SearchableEnvironment((JavaProject)getJavaProject(),this, owner);
- int includeMask = IJavaScriptSearchScope.SOURCES | IJavaScriptSearchScope.APPLICATION_LIBRARIES | IJavaScriptSearchScope.SYSTEM_LIBRARIES | IJavaScriptSearchScope.REFERENCED_PROJECTS;
- env.nameLookup.setRestrictedAccessRequestor(getRestrictedAccessRequestor());
- ((JavaSearchScope)env.searchScope).add((JavaProject)getJavaScriptProject(), includeMask, new HashSet(2));
- return env;
- }
-
- /*
- * Returns a new name lookup. This name lookup first looks in the given working copies.
- */
- public NameLookup newNameLookup(IJavaScriptUnit[] workingCopies) throws JavaScriptModelException {
- this.workingCopies = workingCopies;
- NameLookup lookup = super.newNameLookup(this.workingCopies);
- lookup.setRestrictedAccessRequestor(getRestrictedAccessRequestor());
- return lookup;
- //return ((LookupScopeElementInfo)getElementInfo()).newNameLookup( workingCopies);
- }
-
- /*
- * Returns a new name lookup. This name lookup first looks in the working copies of the given owner.
- */
- public NameLookup newNameLookup(WorkingCopyOwner owner) throws JavaScriptModelException {
-
- NameLookup lookup = super.newNameLookup(owner);
- lookup.setRestrictedAccessRequestor(getRestrictedAccessRequestor());
- return lookup;
-//
-// JavaModelManager manager = JavaModelManager.getJavaModelManager();
-// IJavaScriptUnit[] workingCopies = owner == null ? null : manager.getWorkingCopies(owner, true/*add primary WCs*/);
-// return newNameLookup(workingCopies);
- }
-
- public File isValidImport(String importName) {
- IPath filePath = resolveChildPath(importName);
- if(filePath==null) return null;
- File file = filePath.toFile();
- if(file.isFile()) {
- return file;
- }else {
- // IPath childPath = new Path(importName);
- IFile resolved = null;
- /* since eclipse throws an exception if it doesn't exists (contrary to its API) we have to catch it*/
-
- try {
- resolved = ((IContainer)getResource()).getFile(new Path(file.getPath()));
- }catch(Exception e) {}
-
- boolean exists = resolved!=null && resolved.exists();
- /* Special case for absolute paths specified with \ and / */
- if( importName.charAt(0)=='\\' || importName.charAt(0)=='/'){
- int seg = resolved.getFullPath().matchingFirstSegments(webContext);
-
- exists = exists && (webContext!=new Path("") && seg >0); //$NON-NLS-1$
- }
- if(exists) return new File(resolved.getLocation().toString());
- }
- return null;
- }
-
- public int getKind() throws JavaScriptModelException {
- return IPackageFragmentRoot.K_SOURCE;
- }
-
-
- public String toString() {
- StringBuffer me = new StringBuffer("Relative to: " + fRelativeFile.getName() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
- me.append("Absolute to: " + webContext + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
- me.append("Included File\t\t\tLast Moddified\n"); //$NON-NLS-1$
- for(int i = 0;i<includedFiles.length;i++) {
- me.append(includedFiles[i] /*+ "\t\t\t\t" + timeStamps[i].longValue()*/ + "\n"); //$NON-NLS-1$
- }
-
- return me.toString();
- }
-
- public IResource getResource() {
- return absolutePath;
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ElementCache.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ElementCache.java
deleted file mode 100644
index d31ad32f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ElementCache.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*******************************************************************************
- * 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.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.core.util.LRUCache;
-
-/**
- * An LRU cache of <code>JavaElements</code>.
- */
-public class ElementCache extends OverflowingLRUCache {
-
- IJavaScriptElement spaceLimitParent = null;
-
-/**
- * Constructs a new element cache of the given size.
- */
-public ElementCache(int size) {
- super(size);
-}
-/**
- * Constructs a new element cache of the given size.
- */
-public ElementCache(int size, int overflow) {
- super(size, overflow);
-}
-/**
- * Returns true if the element is successfully closed and
- * removed from the cache, otherwise false.
- *
- * <p>NOTE: this triggers an external removal of this element
- * by closing the element.
- */
-protected boolean close(LRUCacheEntry entry) {
- Openable element = (Openable) entry._fKey;
- try {
- if (!element.canBeRemovedFromCache()) {
- return false;
- } else {
- // We must close an entire JarPackageFragmentRoot at once.
-// if (element instanceof JarPackageFragment) {
-// JarPackageFragment packageFragment= (JarPackageFragment) element;
-// JarPackageFragmentRoot root = (JarPackageFragmentRoot) packageFragment.getParent();
-// root.close();
-// } else {
- element.close();
-// }
- return true;
- }
- } catch (JavaScriptModelException npe) {
- return false;
- }
-}
-
-/*
- * Ensures that there is enough room for adding the given number of children.
- * If the space limit must be increased, record the parent that needed this space limit.
- */
-protected void ensureSpaceLimit(int childrenSize, IJavaScriptElement parent) {
- // ensure the children can be put without closing other elements
- int spaceNeeded = 1 + (int)((1 + fLoadFactor) * (childrenSize + fOverflow));
- if (fSpaceLimit < spaceNeeded) {
- // parent is being opened with more children than the space limit
- shrink(); // remove overflow
- setSpaceLimit(spaceNeeded);
- this.spaceLimitParent = parent;
- }
-}
-
-/*
- * Returns a new instance of the receiver.
- */
-protected LRUCache newInstance(int size, int overflow) {
- return new ElementCache(size, overflow);
-}
-
-/*
- * If the given parent was the one that increased the space limit, reset
- * the space limit to the given default value.
- */
-protected void resetSpaceLimit(int defaultLimit, IJavaScriptElement parent) {
- if (parent.equals(this.spaceLimitParent)) {
- setSpaceLimit(defaultLimit);
- this.spaceLimitParent = null;
- }
-}
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ExternalJavaProject.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ExternalJavaProject.java
deleted file mode 100644
index 9d1c0874..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ExternalJavaProject.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*******************************************************************************
- * 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.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-
-public class ExternalJavaProject extends JavaProject {
-
- /*
- * Note this name can be surfaced in the UI (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=128258)
- */
- public static final String EXTERNAL_PROJECT_NAME = " "; //$NON-NLS-1$
-
- public ExternalJavaProject(IIncludePathEntry[] rawClasspath) {
- super(ResourcesPlugin.getWorkspace().getRoot().getProject(EXTERNAL_PROJECT_NAME), JavaModelManager.getJavaModelManager().getJavaModel());
- try {
- getPerProjectInfo().setClasspath(rawClasspath, defaultOutputLocation(), JavaModelStatus.VERIFIED_OK/*no .classpath format problem*/, null/*no resolved claspath*/, null/*no reverse map*/, null/*no resolve entry map*/, null/*no resolved status*/);
- } catch (JavaScriptModelException e) {
- // getPerProjectInfo() never throws JavaScriptModelException for an ExternalJavaProject
- }
- }
-
- public boolean equals(Object o) {
- return this == o;
- }
-
- public boolean exists() {
- // external project never exists
- return false;
- }
-
- public String getOption(String optionName, boolean inheritJavaCoreOptions) {
- if (JavaScriptCore.COMPILER_PB_FORBIDDEN_REFERENCE.equals(optionName)
- || JavaScriptCore.COMPILER_PB_DISCOURAGED_REFERENCE.equals(optionName))
- return JavaScriptCore.IGNORE;
- return super.getOption(optionName, inheritJavaCoreOptions);
- }
-
- public boolean isOnIncludepath(IJavaScriptElement element) {
- // since project is external, no element is on classpath (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=61013#c16)
- return false;
- }
-
- public boolean isOnIncludepath(IResource resource) {
- // since project is external, no resource is on classpath (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=61013#c16)
- return false;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/IJavaElementRequestor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/IJavaElementRequestor.java
deleted file mode 100644
index 89765097..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/IJavaElementRequestor.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*******************************************************************************
- * 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.core.IField;
-import org.eclipse.wst.jsdt.core.IInitializer;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IType;
-
-/**
- * This interface is used by IRequestorNameLookup. As results
- * are found by IRequestorNameLookup, they are reported to this
- * interface. An IJavaElementRequestor is able to cancel
- * at any time (that is, stop receiving results), by responding
- * <code>true</code> to <code>#isCancelled</code>.
- */
-public interface IJavaElementRequestor {
-public void acceptField(IField field);
-public void acceptInitializer(IInitializer initializer);
-public void acceptMemberType(IType type);
-public void acceptMethod(IFunction method);
-public void acceptPackageFragment(IPackageFragment packageFragment);
-public void acceptType(IType type);
-/**
- * Returns <code>true</code> if this IJavaElementRequestor does
- * not want to receive any more results.
- */
-boolean isCanceled();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/INamingRequestor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/INamingRequestor.java
deleted file mode 100644
index 159ffd00..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/INamingRequestor.java
+++ /dev/null
@@ -1,18 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core;
-
-public interface INamingRequestor {
- void acceptNameWithPrefixAndSuffix(char[] name, boolean isFirstPrefix, boolean isFirstSuffix, int reusedCharacters);
- void acceptNameWithPrefix(char[] name, boolean isFirstPrefix, int reusedCharacters);
- void acceptNameWithSuffix(char[] name, boolean isFirstSuffix, int reusedCharacters);
- void acceptNameWithoutPrefixAndSuffix(char[] name, int reusedCharacters);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/IPathRequestor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/IPathRequestor.java
deleted file mode 100644
index 47c841ed..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/IPathRequestor.java
+++ /dev/null
@@ -1,15 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core;
-
-public interface IPathRequestor {
- void acceptPath(String path, boolean containsLocalTypes);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/IVirtualParent.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/IVirtualParent.java
deleted file mode 100644
index a90f4ea6..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/IVirtualParent.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*******************************************************************************
- * 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
- * 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.core.JsGlobalScopeContainerInitializer;
-
-/**
- * @author childsb
- *
- */
-public interface IVirtualParent {
- public JsGlobalScopeContainerInitializer getContainerInitializer();
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ImportContainer.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ImportContainer.java
deleted file mode 100644
index 69f22ff7..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ImportContainer.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*******************************************************************************
- * 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.core.IImportContainer;
-import org.eclipse.wst.jsdt.core.IImportDeclaration;
-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;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.internal.core.util.MementoTokenizer;
-
-/**
- * @see IImportContainer
- */
-public class ImportContainer extends SourceRefElement implements IImportContainer {
-protected ImportContainer(CompilationUnit parent) {
- super(parent);
-}
-public boolean equals(Object o) {
- if (!(o instanceof ImportContainer)) return false;
- return super.equals(o);
-}
-/**
- * @see IJavaScriptElement
- */
-public int getElementType() {
- return IMPORT_CONTAINER;
-}
-/*
- * @see JavaElement
- */
-public IJavaScriptElement getHandleFromMemento(String token, MementoTokenizer memento, WorkingCopyOwner workingCopyOwner) {
- switch (token.charAt(0)) {
- case JEM_COUNT:
- return getHandleUpdatingCountFromMemento(memento, workingCopyOwner);
- case JEM_IMPORTDECLARATION:
- if (memento.hasMoreTokens()) {
- String importName = memento.nextToken();
- JavaElement importDecl = (JavaElement)getImport(importName);
- return importDecl.getHandleFromMemento(memento, workingCopyOwner);
- } else {
- return this;
- }
- }
- return null;
-}
-/**
- * @see JavaElement#getHandleMemento()
- */
-protected char getHandleMementoDelimiter() {
- return JavaElement.JEM_IMPORTDECLARATION;
-}
-/**
- * @see IImportContainer
- */
-public IImportDeclaration getImport(String importName) {
- int index = importName.indexOf(".*"); ///$NON-NLS-1$
- boolean isOnDemand = index != -1;
- if (isOnDemand)
- // make sure to copy the string (so that it doesn't hold on the underlying char[] that might be much bigger than necessary)
- importName = new String(importName.substring(0, index));
- return new ImportDeclaration(this, importName, isOnDemand);
-}
-/*
- * @see JavaElement#getPrimaryElement(boolean)
- */
-public IJavaScriptElement getPrimaryElement(boolean checkOwner) {
- CompilationUnit cu = (CompilationUnit)this.parent;
- if (checkOwner && cu.isPrimary()) return this;
- return cu.getImportContainer();
-}
-/**
- * @see ISourceReference
- */
-public ISourceRange getSourceRange() throws JavaScriptModelException {
- IJavaScriptElement[] imports= getChildren();
- ISourceRange firstRange= ((ISourceReference)imports[0]).getSourceRange();
- ISourceRange lastRange= ((ISourceReference)imports[imports.length - 1]).getSourceRange();
- SourceRange range= new SourceRange(firstRange.getOffset(), lastRange.getOffset() + lastRange.getLength() - firstRange.getOffset());
- return range;
-}
-/**
- */
-public String readableName() {
-
- return null;
-}
-/**
- * @private Debugging purposes
- */
-protected void toString(int tab, StringBuffer buffer) {
- Object info = JavaModelManager.getJavaModelManager().peekAtInfo(this);
- if (info == null || !(info instanceof JavaElementInfo)) return;
- IJavaScriptElement[] children = ((JavaElementInfo)info).getChildren();
- for (int i = 0; i < children.length; i++) {
- if (i > 0) buffer.append("\n"); //$NON-NLS-1$
- ((JavaElement)children[i]).toString(tab, buffer);
- }
-}
-/**
- * Debugging purposes
- */
-protected void toStringInfo(int tab, StringBuffer buffer, Object info, boolean showResolvedInfo) {
- buffer.append(this.tabString(tab));
- buffer.append("<import container>"); //$NON-NLS-1$
- if (info == null) {
- buffer.append(" (not open)"); //$NON-NLS-1$
- }
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ImportDeclaration.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ImportDeclaration.java
deleted file mode 100644
index 50248d2f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ImportDeclaration.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*******************************************************************************
- * 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.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.IImportDeclaration;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-
-/**
- * Handle for an import declaration. Info object is a ImportDeclarationElementInfo.
- * @see IImportDeclaration
- */
-
-public class ImportDeclaration extends SourceRefElement implements IImportDeclaration {
-
- protected String name;
- protected boolean isOnDemand;
-
-/**
- * Constructs an ImportDeclaration in the given import container
- * with the given name.
- */
-protected ImportDeclaration(ImportContainer parent, String name, boolean isOnDemand) {
- super(parent);
- this.name = name;
- this.isOnDemand = isOnDemand;
-}
-public boolean equals(Object o) {
- if (!(o instanceof ImportDeclaration)) return false;
- return super.equals(o);
-}
-public String getElementName() {
- if (this.isOnDemand)
- return this.name + ".*"; //$NON-NLS-1$
- return this.name;
-}
-public String getNameWithoutStar() {
- return this.name;
-}
-/**
- * @see IJavaScriptElement
- */
-public int getElementType() {
- return IMPORT_DECLARATION;
-}
-/**
- * @see org.eclipse.wst.jsdt.core.IImportDeclaration#getFlags()
- */
-public int getFlags() throws JavaScriptModelException {
- ImportDeclarationElementInfo info = (ImportDeclarationElementInfo)getElementInfo();
- return info.getModifiers();
-}
-/**
- * @see JavaElement#getHandleMemento(StringBuffer)
- * For import declarations, the handle delimiter is associated to the import container already
- */
-protected void getHandleMemento(StringBuffer buff) {
- ((JavaElement)getParent()).getHandleMemento(buff);
- escapeMementoName(buff, getElementName());
- if (this.occurrenceCount > 1) {
- buff.append(JEM_COUNT);
- buff.append(this.occurrenceCount);
- }
-}
-/**
- * @see JavaElement#getHandleMemento()
- */
-protected char getHandleMementoDelimiter() {
- // For import declarations, the handle delimiter is associated to the import container already
- Assert.isTrue(false, "Should not be called"); //$NON-NLS-1$
- return 0;
-}
-/*
- * @see JavaElement#getPrimaryElement(boolean)
- */
-public IJavaScriptElement getPrimaryElement(boolean checkOwner) {
- CompilationUnit cu = (CompilationUnit)this.parent.getParent();
- if (checkOwner && cu.isPrimary()) return this;
- return cu.getImport(getElementName());
-}
-/**
- * Returns true if the import is on-demand (ends with ".*")
- */
-public boolean isOnDemand() {
- return this.isOnDemand;
-}
-/**
- */
-public String readableName() {
-
- return null;
-}
-/**
- * @private Debugging purposes
- */
-protected void toStringInfo(int tab, StringBuffer buffer, Object info, boolean showResolvedInfo) {
- buffer.append(this.tabString(tab));
- buffer.append("import "); //$NON-NLS-1$
- toStringName(buffer);
- if (info == null) {
- buffer.append(" (not open)"); //$NON-NLS-1$
- }
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ImportDeclarationElementInfo.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ImportDeclarationElementInfo.java
deleted file mode 100644
index 17fa8c8f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ImportDeclarationElementInfo.java
+++ /dev/null
@@ -1,22 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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.compiler.env.ISourceImport;
-
-/**
- * Element info for IImportDeclaration elements.
- * @see org.eclipse.wst.jsdt.core.IImportDeclaration
- */
-public class ImportDeclarationElementInfo extends MemberElementInfo implements ISourceImport{
-
- // empty element info
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/Initializer.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/Initializer.java
deleted file mode 100644
index 50e57cb2..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/Initializer.java
+++ /dev/null
@@ -1,119 +0,0 @@
-/*******************************************************************************
- * 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.core.runtime.IProgressMonitor;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IInitializer;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatusConstants;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * @see IInitializer
- */
-
-/* package */ class Initializer extends Member implements IInitializer {
-
-protected Initializer(JavaElement parent, int count) {
- super(parent);
- // 0 is not valid: this first occurrence is occurrence 1.
- if (count <= 0)
- throw new IllegalArgumentException();
- this.occurrenceCount = count;
-}
-public boolean equals(Object o) {
- if (!(o instanceof Initializer)) return false;
- return super.equals(o);
-}
-/**
- * @see IJavaScriptElement
- */
-public int getElementType() {
- return INITIALIZER;
-}
-/**
- * @see JavaElement#getHandleMemento(StringBuffer)
- */
-protected void getHandleMemento(StringBuffer buff) {
- ((JavaElement)getParent()).getHandleMemento(buff);
- buff.append(getHandleMementoDelimiter());
- buff.append(this.occurrenceCount);
-}
-/**
- * @see JavaElement#getHandleMemento()
- */
-protected char getHandleMementoDelimiter() {
- return JavaElement.JEM_INITIALIZER;
-}
-public int hashCode() {
- return Util.combineHashCodes(this.parent.hashCode(), this.occurrenceCount);
-}
-/**
- */
-public String readableName() {
-
- return ((JavaElement)getDeclaringType()).readableName();
-}
-/**
- * @see org.eclipse.wst.jsdt.core.ISourceManipulation
- */
-public void rename(String newName, boolean force, IProgressMonitor monitor) throws JavaScriptModelException {
- throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_ELEMENT_TYPES, this));
-}
-/**
- * @see org.eclipse.wst.jsdt.core.IMember
- */
-public ISourceRange getNameRange() {
- return null;
-}
-/*
- * @see JavaElement#getPrimaryElement(boolean)
- */
-public IJavaScriptElement getPrimaryElement(boolean checkOwner) {
- if (checkOwner) {
- CompilationUnit cu = (CompilationUnit)getAncestor(JAVASCRIPT_UNIT);
- if (cu == null || cu.isPrimary()) return this;
- }
- IJavaScriptElement primaryParent = this.parent.getPrimaryElement(false);
- return ((IType)primaryParent).getInitializer(this.occurrenceCount);
-}
-/**
- * @private Debugging purposes
- */
-protected void toStringInfo(int tab, StringBuffer buffer, Object info, boolean showResolvedInfo) {
- buffer.append(this.tabString(tab));
- if (info == null) {
- buffer.append("<initializer #"); //$NON-NLS-1$
- buffer.append(this.occurrenceCount);
- buffer.append("> (not open)"); //$NON-NLS-1$
- } else if (info == NO_INFO) {
- buffer.append("<initializer #"); //$NON-NLS-1$
- buffer.append(this.occurrenceCount);
- buffer.append(">"); //$NON-NLS-1$
- } else {
- try {
- buffer.append("<"); //$NON-NLS-1$
- if (Flags.isStatic(this.getFlags())) {
- buffer.append("static "); //$NON-NLS-1$
- }
- buffer.append("initializer #"); //$NON-NLS-1$
- buffer.append(this.occurrenceCount);
- buffer.append(">"); //$NON-NLS-1$
- } catch (JavaScriptModelException e) {
- buffer.append("<JavaScriptModelException in toString of " + getElementName()); //$NON-NLS-1$
- }
- }
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/InitializerElementInfo.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/InitializerElementInfo.java
deleted file mode 100644
index f844f306..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/InitializerElementInfo.java
+++ /dev/null
@@ -1,18 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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 IInitializer elements.
- */
-public class InitializerElementInfo extends MemberElementInfo {
- // used only as a marker class: contains no methods
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/InternalNamingConventions.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/InternalNamingConventions.java
deleted file mode 100644
index 31fb18bb..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/InternalNamingConventions.java
+++ /dev/null
@@ -1,423 +0,0 @@
-/*******************************************************************************
- * 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 java.util.Map;
-
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.internal.codeassist.impl.AssistOptions;
-import org.eclipse.wst.jsdt.internal.compiler.impl.CompilerOptions;
-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;
-
-public class InternalNamingConventions {
- private static final char[] DEFAULT_NAME = "name".toCharArray(); //$NON-NLS-1$
-
- private static Scanner getNameScanner(CompilerOptions compilerOptions) {
- return
- new Scanner(
- false /*comment*/,
- false /*whitespace*/,
- false /*nls*/,
- compilerOptions.sourceLevel /*sourceLevel*/,
- null /*taskTags*/,
- null/*taskPriorities*/,
- true/*taskCaseSensitive*/);
- }
- public static void suggestArgumentNames(IJavaScriptProject javaProject, char[] packageName, char[] qualifiedTypeName, int dim, char[] internalPrefix, char[][] excludedNames, INamingRequestor requestor) {
- Map options = javaProject.getOptions(true);
- CompilerOptions compilerOptions = new CompilerOptions(options);
- AssistOptions assistOptions = new AssistOptions(options);
-
- suggestNames(
- packageName,
- qualifiedTypeName,
- dim,
- internalPrefix,
- assistOptions.argumentPrefixes,
- assistOptions.argumentSuffixes,
- excludedNames,
- getNameScanner(compilerOptions),
- requestor);
- }
- public static void suggestFieldNames(IJavaScriptProject javaProject, char[] packageName, char[] qualifiedTypeName, int dim, int modifiers, char[] internalPrefix, char[][] excludedNames, INamingRequestor requestor) {
- boolean isStatic = Flags.isStatic(modifiers);
-
- Map options = javaProject.getOptions(true);
- CompilerOptions compilerOptions = new CompilerOptions(options);
- AssistOptions assistOptions = new AssistOptions(options);
-
- suggestNames(
- packageName,
- qualifiedTypeName,
- dim,
- internalPrefix,
- isStatic ? assistOptions.staticFieldPrefixes : assistOptions.fieldPrefixes,
- isStatic ? assistOptions.staticFieldSuffixes : assistOptions.fieldSuffixes,
- excludedNames,
- getNameScanner(compilerOptions),
- requestor);
- }
- public static void suggestLocalVariableNames(IJavaScriptProject javaProject, char[] packageName, char[] qualifiedTypeName, int dim, char[] internalPrefix, char[][] excludedNames, INamingRequestor requestor) {
- Map options = javaProject.getOptions(true);
- CompilerOptions compilerOptions = new CompilerOptions(options);
- AssistOptions assistOptions = new AssistOptions(options);
-
- suggestNames(
- packageName,
- qualifiedTypeName,
- dim,
- internalPrefix,
- assistOptions.localPrefixes,
- assistOptions.localSuffixes,
- excludedNames,
- getNameScanner(compilerOptions),
- requestor);
- }
-
- private static void suggestNames(
- char[] packageName,
- char[] qualifiedTypeName,
- int dim,
- char[] internalPrefix,
- char[][] prefixes,
- char[][] suffixes,
- char[][] excludedNames,
- Scanner nameScanner,
- INamingRequestor requestor){
-
- if(qualifiedTypeName == null || qualifiedTypeName.length == 0)
- return;
-
- if(internalPrefix == null) {
- internalPrefix = CharOperation.NO_CHAR;
- } else {
- internalPrefix = removePrefix(internalPrefix, prefixes);
- }
-
- char[] typeName = (qualifiedTypeName!=null)? CharOperation.lastSegment(qualifiedTypeName, '.'):null;
-
- if(prefixes == null || prefixes.length == 0) {
- prefixes = new char[1][0];
- } else {
- int length = prefixes.length;
- System.arraycopy(prefixes, 0, prefixes = new char[length+1][], 0, length);
- prefixes[length] = CharOperation.NO_CHAR;
- }
-
- if(suffixes == null || suffixes.length == 0) {
- suffixes = new char[1][0];
- } else {
- int length = suffixes.length;
- System.arraycopy(suffixes, 0, suffixes = new char[length+1][], 0, length);
- suffixes[length] = CharOperation.NO_CHAR;
- }
-
- char[][] tempNames = null;
-
- // compute variable name for base type
- try{
- nameScanner.setSource(typeName);
- switch (nameScanner.getNextToken()) {
- case TerminalTokens.TokenNameint :
- case TerminalTokens.TokenNamebyte :
- case TerminalTokens.TokenNameshort :
- case TerminalTokens.TokenNamechar :
- case TerminalTokens.TokenNamelong :
- case TerminalTokens.TokenNamefloat :
- case TerminalTokens.TokenNamedouble :
- case TerminalTokens.TokenNameboolean :
-
- if (internalPrefix != null && internalPrefix.length > 0) return;
-
- char[] name = computeBaseTypeNames(typeName[0], excludedNames);
- if(name != null) {
- tempNames = new char[][]{name};
- }
- break;
- }
- } catch(InvalidInputException e){
- // ignore
- }
-
- // compute variable name for non base type
- if(tempNames == null) {
- tempNames = computeNames(typeName);
- }
-
- boolean acceptDefaultName = true;
-
- next : for (int i = 0; i < tempNames.length; i++) {
- char[] tempName = tempNames[i];
- if(dim > 0) {
- int length = tempName.length;
- if (tempName[length-1] == 's'){
- if(tempName.length > 1 && tempName[length-2] == 's') {
- System.arraycopy(tempName, 0, tempName = new char[length + 2], 0, length);
- tempName[length] = 'e';
- tempName[length+1] = 's';
- }
- } else if(tempName[length-1] == 'y') {
- System.arraycopy(tempName, 0, tempName = new char[length + 2], 0, length);
- tempName[length-1] = 'i';
- tempName[length] = 'e';
- tempName[length+1] = 's';
- } else {
- System.arraycopy(tempName, 0, tempName = new char[length + 1], 0, length);
- tempName[length] = 's';
- }
- }
-
- char[] unprefixedName = tempName;
- for (int j = 0; j <= internalPrefix.length; j++) {
- if(j == internalPrefix.length || CharOperation.prefixEquals(CharOperation.subarray(internalPrefix, j, -1), unprefixedName, false)) {
- tempName = CharOperation.concat(CharOperation.subarray(internalPrefix, 0, j), unprefixedName);
- if(j != 0) tempName[j] = ScannerHelper.toUpperCase(tempName[j]);
- for (int k = 0; k < prefixes.length; k++) {
- if(prefixes[k].length > 0
- && ScannerHelper.isLetterOrDigit(prefixes[k][prefixes[k].length - 1])) {
- tempName[0] = ScannerHelper.toUpperCase(tempName[0]);
- } else {
- tempName[0] = ScannerHelper.toLowerCase(tempName[0]);
- }
- char[] prefixName = CharOperation.concat(prefixes[k], tempName);
- for (int l = 0; l < suffixes.length; l++) {
- char[] suffixName = CharOperation.concat(prefixName, suffixes[l]);
- suffixName =
- excludeNames(
- suffixName,
- prefixName,
- suffixes[l],
- excludedNames);
- try{
- nameScanner.setSource(suffixName);
- switch (nameScanner.getNextToken()) {
- case TerminalTokens.TokenNameIdentifier :
- int token = nameScanner.getNextToken();
- if (token == TerminalTokens.TokenNameEOF && nameScanner.startPosition == suffixName.length) {
- acceptName(suffixName, prefixes[k], suffixes[l], k == 0, l == 0, internalPrefix.length - j, requestor);
- acceptDefaultName = false;
- }
- break;
- default:
- suffixName = CharOperation.concat(
- prefixName,
- String.valueOf(1).toCharArray(),
- suffixes[l]
- );
- suffixName =
- excludeNames(
- suffixName,
- prefixName,
- suffixes[l],
- excludedNames);
- nameScanner.setSource(suffixName);
- switch (nameScanner.getNextToken()) {
- case TerminalTokens.TokenNameIdentifier :
- token = nameScanner.getNextToken();
- if (token == TerminalTokens.TokenNameEOF && nameScanner.startPosition == suffixName.length) {
- acceptName(suffixName, prefixes[k], suffixes[l], k == 0, l == 0, internalPrefix.length - j, requestor);
- acceptDefaultName = false;
- }
- }
- }
- } catch(InvalidInputException e){
- // ignore
- }
- }
- }
- continue next;
- }
- }
- }
- // if no names were found
- if(acceptDefaultName) {
- char[] name = excludeNames(DEFAULT_NAME, DEFAULT_NAME, CharOperation.NO_CHAR, excludedNames);
- requestor.acceptNameWithoutPrefixAndSuffix(name, 0);
- }
- }
-
- private static void acceptName(
- char[] name,
- char[] prefix,
- char[] suffix,
- boolean isFirstPrefix,
- boolean isFirstSuffix,
- int reusedCharacters,
- INamingRequestor requestor) {
- if(prefix.length > 0 && suffix.length > 0) {
- requestor.acceptNameWithPrefixAndSuffix(name, isFirstPrefix, isFirstSuffix, reusedCharacters);
- } else if(prefix.length > 0){
- requestor.acceptNameWithPrefix(name, isFirstPrefix, reusedCharacters);
- } else if(suffix.length > 0){
- requestor.acceptNameWithSuffix(name, isFirstSuffix, reusedCharacters);
- } else {
- requestor.acceptNameWithoutPrefixAndSuffix(name, reusedCharacters);
- }
- }
-
- private static char[] computeBaseTypeNames(char firstName, char[][] excludedNames){
- char[] name = new char[]{firstName};
-
- for(int i = 0 ; i < excludedNames.length ; i++){
- if(CharOperation.equals(name, excludedNames[i], false)) {
- name[0]++;
- if(name[0] > 'z')
- name[0] = 'a';
- if(name[0] == firstName)
- return null;
- i = 0;
- }
- }
-
- return name;
- }
-
- private static char[][] computeNames(char[] sourceName){
- char[][] names = new char[5][];
- int nameCount = 0;
- boolean previousIsUpperCase = false;
- boolean previousIsLetter = true;
- for(int i = sourceName.length - 1 ; i >= 0 ; i--){
- boolean isUpperCase = ScannerHelper.isUpperCase(sourceName[i]);
- boolean isLetter = ScannerHelper.isLetter(sourceName[i]);
- if(isUpperCase && !previousIsUpperCase && previousIsLetter){
- char[] name = CharOperation.subarray(sourceName,i,sourceName.length);
- if(name.length > 1){
- if(nameCount == names.length) {
- System.arraycopy(names, 0, names = new char[nameCount * 2][], 0, nameCount);
- }
- name[0] = ScannerHelper.toLowerCase(name[0]);
- names[nameCount++] = name;
- }
- }
- previousIsUpperCase = isUpperCase;
- previousIsLetter = isLetter;
- }
- if(nameCount == 0){
- names[nameCount++] = CharOperation.toLowerCase(sourceName);
- }
- System.arraycopy(names, 0, names = new char[nameCount][], 0, nameCount);
- return names;
- }
-
- private static char[] excludeNames(
- char[] suffixName,
- char[] prefixName,
- char[] suffix,
- char[][] excludedNames) {
- int count = 2;
- int m = 0;
- while (m < excludedNames.length) {
- if(CharOperation.equals(suffixName, excludedNames[m], false)) {
- suffixName = CharOperation.concat(
- prefixName,
- String.valueOf(count++).toCharArray(),
- suffix
- );
- m = 0;
- } else {
- m++;
- }
- }
- return suffixName;
- }
-
- private static char[] removePrefix(char[] name, char[][] prefixes) {
- // remove longer prefix
- char[] withoutPrefixName = name;
- if (prefixes != null) {
- int bestLength = 0;
- int nameLength = name.length;
- for (int i= 0; i < prefixes.length; i++) {
- char[] prefix = prefixes[i];
-
- int prefixLength = prefix.length;
- if(prefixLength <= nameLength) {
- if(CharOperation.prefixEquals(prefix, name, false)) {
- if (prefixLength > bestLength) {
- bestLength = prefixLength;
- }
- }
- } else {
- int currLen = 0;
- for (; currLen < nameLength; currLen++) {
- if(ScannerHelper.toLowerCase(prefix[currLen]) != ScannerHelper.toLowerCase(name[currLen])) {
- if (currLen > bestLength) {
- bestLength = currLen;
- }
- break;
- }
- }
- if(currLen == nameLength && currLen > bestLength) {
- bestLength = currLen;
- }
- }
- }
- if(bestLength > 0) {
- if(bestLength == nameLength) {
- withoutPrefixName = CharOperation.NO_CHAR;
- } else {
- withoutPrefixName = CharOperation.subarray(name, bestLength, nameLength);
- }
- }
- }
-//
-//
-// // remove longer prefix
-// char[] withoutPrefixName = name;
-// if (prefixes != null) {
-// int bestLength = 0;
-// for (int i= 0; i < prefixes.length; i++) {
-// char[] prefix = prefixes[i];
-// int max = prefix.length < name.length ? prefix.length : name.length;
-// int currLen = 0;
-// for (; currLen < max; currLen++) {
-// if(Character.toLowerCase(prefix[currLen]) != Character.toLowerCase(name[currLen])) {
-// if (currLen > bestLength) {
-// bestLength = currLen;
-// }
-// break;
-// }
-// }
-// if(currLen == max && currLen > bestLength) {
-// bestLength = max;
-// }
-// }
-// if(bestLength > 0) {
-// if(bestLength == name.length) {
-// withoutPrefixName = CharOperation.NO_CHAR;
-// } else {
-// withoutPrefixName = CharOperation.subarray(name, bestLength, name.length);
-// }
-// }
-// }
-
- return withoutPrefixName;
- }
-
- public static final boolean prefixEquals(char[] prefix, char[] name) {
-
- int max = prefix.length;
- if (name.length < max)
- return false;
- for (int i = max;
- --i >= 0;
- ) // assumes the prefix is not larger than the name
- if (prefix[i] != name[i])
- return false;
- return true;
- }
-}
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
deleted file mode 100644
index 206f97dd..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaCorePreferenceInitializer.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*******************************************************************************
- * 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;
-
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
-import org.eclipse.core.runtime.preferences.DefaultScope;
-import org.eclipse.core.runtime.preferences.IEclipsePreferences;
-import org.eclipse.core.runtime.preferences.IScopeContext;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants;
-import org.eclipse.wst.jsdt.internal.compiler.impl.CompilerOptions;
-
-/**
- * JavaScriptCore eclipse preferences initializer.
- * Initially done in JavaScriptCore.initializeDefaultPreferences which was deprecated
- * with new eclipse preferences mechanism.
- */
-public class JavaCorePreferenceInitializer extends AbstractPreferenceInitializer {
-
- /* (non-Javadoc)
- * @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#initializeDefaultPreferences()
- */
- public void initializeDefaultPreferences() {
- // If modified, also modify the method JavaModelManager#getDefaultOptionsNoInitialization()
- // Get options names set
- HashSet optionNames = JavaModelManager.getJavaModelManager().optionNames;
-
- // Compiler settings
- Map defaultOptionsMap = new CompilerOptions().getMap(); // compiler defaults
-
- // Override some compiler defaults
- defaultOptionsMap.put(JavaScriptCore.COMPILER_LOCAL_VARIABLE_ATTR, JavaScriptCore.GENERATE);
- defaultOptionsMap.put(JavaScriptCore.COMPILER_CODEGEN_UNUSED_LOCAL, JavaScriptCore.PRESERVE);
- defaultOptionsMap.put(JavaScriptCore.COMPILER_TASK_TAGS, JavaScriptCore.DEFAULT_TASK_TAGS);
- defaultOptionsMap.put(JavaScriptCore.COMPILER_TASK_PRIORITIES, JavaScriptCore.DEFAULT_TASK_PRIORITIES);
- defaultOptionsMap.put(JavaScriptCore.COMPILER_TASK_CASE_SENSITIVE, JavaScriptCore.ENABLED);
- defaultOptionsMap.put(JavaScriptCore.COMPILER_DOC_COMMENT_SUPPORT, JavaScriptCore.ENABLED);
- defaultOptionsMap.put(JavaScriptCore.COMPILER_PB_FORBIDDEN_REFERENCE, JavaScriptCore.ERROR);
- defaultOptionsMap.put(JavaScriptCore.COMPILER_SEMANTIC_VALIDATION, JavaScriptCore.ENABLED);
-
- // Builder settings
- defaultOptionsMap.put(JavaScriptCore.CORE_JAVA_BUILD_RESOURCE_COPY_FILTER, ""); //$NON-NLS-1$
- defaultOptionsMap.put(JavaScriptCore.CORE_JAVA_BUILD_INVALID_CLASSPATH, JavaScriptCore.ABORT);
- defaultOptionsMap.put(JavaScriptCore.CORE_JAVA_BUILD_DUPLICATE_RESOURCE, JavaScriptCore.WARNING);
- defaultOptionsMap.put(JavaScriptCore.CORE_JAVA_BUILD_CLEAN_OUTPUT_FOLDER, JavaScriptCore.CLEAN);
- defaultOptionsMap.put(JavaScriptCore.CORE_JAVA_BUILD_RECREATE_MODIFIED_CLASS_FILES_IN_OUTPUT_FOLDER, JavaScriptCore.IGNORE);
-
- // JavaScriptCore settings
- defaultOptionsMap.put(JavaScriptCore.CORE_JAVA_BUILD_ORDER, JavaScriptCore.IGNORE);
- defaultOptionsMap.put(JavaScriptCore.CORE_INCOMPLETE_CLASSPATH, JavaScriptCore.ERROR);
- defaultOptionsMap.put(JavaScriptCore.CORE_CIRCULAR_CLASSPATH, JavaScriptCore.ERROR);
- defaultOptionsMap.put(JavaScriptCore.CORE_INCOMPATIBLE_JDK_LEVEL, JavaScriptCore.IGNORE);
- defaultOptionsMap.put(JavaScriptCore.CORE_ENABLE_CLASSPATH_EXCLUSION_PATTERNS, JavaScriptCore.ENABLED);
- defaultOptionsMap.put(JavaScriptCore.CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS, JavaScriptCore.ENABLED);
-
- // encoding setting comes from resource plug-in
- optionNames.add(JavaScriptCore.CORE_ENCODING);
-
- // Formatter settings
- Map codeFormatterOptionsMap = DefaultCodeFormatterConstants.getEclipseDefaultSettings(); // code formatter defaults
- for (Iterator iter = codeFormatterOptionsMap.entrySet().iterator(); iter.hasNext();) {
- Map.Entry entry = (Map.Entry) iter.next();
- String optionName = (String) entry.getKey();
- defaultOptionsMap.put(optionName, entry.getValue());
- optionNames.add(optionName);
- }
-
- // CodeAssist settings
- defaultOptionsMap.put(JavaScriptCore.CODEASSIST_VISIBILITY_CHECK, JavaScriptCore.DISABLED);
- defaultOptionsMap.put(JavaScriptCore.CODEASSIST_DEPRECATION_CHECK, JavaScriptCore.DISABLED);
- defaultOptionsMap.put(JavaScriptCore.CODEASSIST_IMPLICIT_QUALIFICATION, JavaScriptCore.DISABLED);
- defaultOptionsMap.put(JavaScriptCore.CODEASSIST_FIELD_PREFIXES, ""); //$NON-NLS-1$
- defaultOptionsMap.put(JavaScriptCore.CODEASSIST_STATIC_FIELD_PREFIXES, ""); //$NON-NLS-1$
- defaultOptionsMap.put(JavaScriptCore.CODEASSIST_LOCAL_PREFIXES, ""); //$NON-NLS-1$
- defaultOptionsMap.put(JavaScriptCore.CODEASSIST_ARGUMENT_PREFIXES, ""); //$NON-NLS-1$
- defaultOptionsMap.put(JavaScriptCore.CODEASSIST_FIELD_SUFFIXES, ""); //$NON-NLS-1$
- defaultOptionsMap.put(JavaScriptCore.CODEASSIST_STATIC_FIELD_SUFFIXES, ""); //$NON-NLS-1$
- defaultOptionsMap.put(JavaScriptCore.CODEASSIST_LOCAL_SUFFIXES, ""); //$NON-NLS-1$
- defaultOptionsMap.put(JavaScriptCore.CODEASSIST_ARGUMENT_SUFFIXES, ""); //$NON-NLS-1$
- defaultOptionsMap.put(JavaScriptCore.CODEASSIST_FORBIDDEN_REFERENCE_CHECK, JavaScriptCore.ENABLED);
- defaultOptionsMap.put(JavaScriptCore.CODEASSIST_DISCOURAGED_REFERENCE_CHECK, JavaScriptCore.DISABLED);
- defaultOptionsMap.put(JavaScriptCore.CODEASSIST_CAMEL_CASE_MATCH, JavaScriptCore.ENABLED);
- defaultOptionsMap.put(JavaScriptCore.CODEASSIST_SUGGEST_STATIC_IMPORTS, JavaScriptCore.ENABLED);
-
- /* START -------------------------------- Bug 203292 Type/Method/Filed resolution error configuration --------------------- */
- /*
- * Default ERROR for unresolved types/fields/methods
- */
- defaultOptionsMap.put(JavaScriptCore.UNRESOLVED_TYPE_REFERENCE, JavaScriptCore.ERROR);
- defaultOptionsMap.put(JavaScriptCore.UNRESOLVED_FIELD_REFERENCE, JavaScriptCore.ERROR);
- defaultOptionsMap.put(JavaScriptCore.UNRESOLVED_METHOD_REFERENCE, JavaScriptCore.ERROR);
- /* END -------------------------------- Bug 203292 Type/Method/Filed resolution error configuration --------------------- */
- /* START -------------------------------- Bug 197884 Loosly defined var (for statement) and optional semi-colon --------------------- */
- defaultOptionsMap.put(JavaScriptCore.LOOSE_VAR_DECL, JavaScriptCore.WARNING);
- defaultOptionsMap.put(JavaScriptCore.OPTIONAL_SEMICOLON, JavaScriptCore.WARNING);
- defaultOptionsMap.put(JavaScriptCore.COMPILER_PB_DUPLICATE_LOCAL_VARIABLES, JavaScriptCore.WARNING);
- defaultOptionsMap.put(JavaScriptCore.COMPILER_PB_UNINITIALIZED_LOCAL_VARIABLE, JavaScriptCore.WARNING);
- /* END -------------------------------- Bug 197884 Loosly defined var (for statement) and optional semi-colon --------------------- */
-
- // Time out for parameter names
- defaultOptionsMap.put(JavaScriptCore.TIMEOUT_FOR_PARAMETER_NAME_FROM_ATTACHED_JAVADOC, "50"); //$NON-NLS-1$
-
- // Store default values to default preferences
- IEclipsePreferences defaultPreferences = ((IScopeContext) new DefaultScope()).getNode(JavaScriptCore.PLUGIN_ID);
- for (Iterator iter = defaultOptionsMap.entrySet().iterator(); iter.hasNext();) {
- Map.Entry entry = (Map.Entry) iter.next();
- String optionName = (String) entry.getKey();
- defaultPreferences.put(optionName, (String)entry.getValue());
- optionNames.add(optionName);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaCorePreferenceModifyListener.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaCorePreferenceModifyListener.java
deleted file mode 100644
index 39dcc43d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaCorePreferenceModifyListener.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*******************************************************************************
- * 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.core.runtime.preferences.IEclipsePreferences;
-import org.eclipse.core.runtime.preferences.InstanceScope;
-import org.eclipse.core.runtime.preferences.PreferenceModifyListener;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.osgi.service.prefs.BackingStoreException;
-import org.osgi.service.prefs.Preferences;
-
-public class JavaCorePreferenceModifyListener extends PreferenceModifyListener {
-
- static int PREFIX_LENGTH = JavaModelManager.CP_CONTAINER_PREFERENCES_PREFIX.length();
- JavaModel javaModel = JavaModelManager.getJavaModelManager().getJavaModel();
-
- /* (non-Javadoc)
- * @see org.eclipse.core.runtime.preferences.PreferenceModifyListener#preApply(org.eclipse.core.runtime.preferences.IEclipsePreferences)
- */
- public IEclipsePreferences preApply(IEclipsePreferences node) {
- Preferences instance = node.node(InstanceScope.SCOPE);
- cleanJavaCore(instance.node(JavaScriptCore.PLUGIN_ID));
- return super.preApply(node);
- }
-
- /**
- * Clean imported preferences from obsolete keys.
- *
- * @param preferences JavaScriptCore preferences.
- */
- void cleanJavaCore(Preferences preferences) {
- try {
- String[] keys = preferences.keys();
- for (int k = 0, kl= keys.length; k<kl; k++) {
- String key = keys[k];
- if (key.startsWith(JavaModelManager.CP_CONTAINER_PREFERENCES_PREFIX) && !isJavaProjectAccessible(key)) {
- preferences.remove(key);
- }
- }
- } catch (BackingStoreException e) {
- // do nothing
- }
- }
-
- /**
- * Returns whether a java project referenced in property key
- * is still longer accessible or not.
- *
- * @param propertyName
- * @return true if a project is referenced in given key and this project
- * is still accessible, false otherwise.
- */
- boolean isJavaProjectAccessible(String propertyName) {
- int index = propertyName.indexOf('|', PREFIX_LENGTH);
- if (index > 0) {
- final String projectName = propertyName.substring(PREFIX_LENGTH, index).trim();
- JavaProject project = (JavaProject) javaModel.getJavaScriptProject(projectName);
- if (project.getProject().isAccessible()) {
- return true;
- }
- }
- return false;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaElement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaElement.java
deleted file mode 100644
index 2162eea9..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaElement.java
+++ /dev/null
@@ -1,890 +0,0 @@
-/*******************************************************************************
- * 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 java.io.BufferedInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.net.JarURLConnection;
-import java.net.MalformedURLException;
-import java.net.URI;
-import java.net.URL;
-import java.net.URLConnection;
-import java.util.ArrayList;
-import java.util.HashMap;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.PlatformObject;
-import org.eclipse.core.runtime.jobs.ISchedulingRule;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IIncludePathAttribute;
-import org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-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.IOpenable;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IParent;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.LibrarySuperType;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Binding;
-import org.eclipse.wst.jsdt.internal.core.util.MementoTokenizer;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * Root of Java element handle hierarchy.
- *
- * @see IJavaScriptElement
- */
-public abstract class JavaElement extends PlatformObject implements IJavaScriptElement {
-// private static final QualifiedName PROJECT_JAVADOC= new QualifiedName(JavaScriptCore.PLUGIN_ID, "project_javadoc_location"); //$NON-NLS-1$
-
- private static final byte[] CLOSING_DOUBLE_QUOTE = new byte[] { 34 };
- private static final byte[] CHARSET = new byte[] {99, 104, 97, 114, 115, 101, 116, 61 };
- private static final byte[] CONTENT_TYPE = new byte[] { 34, 67, 111, 110, 116, 101, 110, 116, 45, 84, 121, 112, 101, 34 };
- private static final byte[] CONTENT = new byte[] { 99, 111, 110, 116, 101, 110, 116, 61, 34 };
- public static final char JEM_ESCAPE = '\\';
- public static final char JEM_JAVAPROJECT = '=';
- public static final char JEM_PACKAGEFRAGMENTROOT = '/';
- public static final char JEM_PACKAGEFRAGMENT = '<';
- public static final char JEM_FIELD = '^';
- public static final char JEM_METHOD = '~';
- public static final char JEM_INITIALIZER = '|';
- public static final char JEM_COMPILATIONUNIT = '{';
- public static final char JEM_CLASSFILE = '(';
- public static final char JEM_METADATA = '&';
- public static final char JEM_TYPE = '[';
- public static final char JEM_PACKAGEDECLARATION = '%';
- public static final char JEM_IMPORTDECLARATION = '#';
- public static final char JEM_COUNT = '!';
- public static final char JEM_LOCALVARIABLE = '@';
- public static final char JEM_TYPE_PARAMETER = ']';
-
- /**
- * This element's parent, or <code>null</code> if this
- * element does not have a parent.
- */
- protected JavaElement parent;
-
- protected static final JavaElement[] NO_ELEMENTS = new JavaElement[0];
- protected static final Object NO_INFO = new Object();
-
- /**
- * Constructs a handle for a java element with
- * the given parent element.
- *
- * @param parent The parent of java element
- *
- * @exception IllegalArgumentException if the type is not one of the valid
- * Java element type constants
- *
- */
- protected JavaElement(JavaElement parent) throws IllegalArgumentException {
- this.parent = parent;
- }
- /**
- * @see IOpenable
- */
- public void close() throws JavaScriptModelException {
- JavaModelManager.getJavaModelManager().removeInfoAndChildren(this);
- }
- /**
- * This element is being closed. Do any necessary cleanup.
- */
- protected abstract void closing(Object info) throws JavaScriptModelException;
- /*
- * Returns a new element info for this element.
- */
- protected abstract Object createElementInfo();
- /**
- * Returns true if this handle represents the same Java element
- * as the given handle. By default, two handles represent the same
- * element if they are identical or if they represent the same type
- * of element, have equal names, parents, and occurrence counts.
- *
- * <p>If a subclass has other requirements for equality, this method
- * must be overridden.
- *
- * @see Object#equals
- */
- public boolean equals(Object o) {
-
- if (this == o) return true;
-
- // Java model parent is null
- if (this.parent == null) return super.equals(o);
-
- // assume instanceof check is done in subclass
- JavaElement other = (JavaElement) o;
- return getElementName().equals(other.getElementName()) &&
- this.parent.equals(other.parent);
- }
- protected void escapeMementoName(StringBuffer buffer, String mementoName) {
- for (int i = 0, length = mementoName.length(); i < length; i++) {
- char character = mementoName.charAt(i);
- switch (character) {
- case JEM_ESCAPE:
- case JEM_COUNT:
- case JEM_JAVAPROJECT:
- case JEM_PACKAGEFRAGMENTROOT:
- case JEM_PACKAGEFRAGMENT:
- case JEM_FIELD:
- case JEM_METHOD:
- case JEM_INITIALIZER:
- case JEM_COMPILATIONUNIT:
- case JEM_CLASSFILE:
- case JEM_TYPE:
- case JEM_PACKAGEDECLARATION:
- case JEM_IMPORTDECLARATION:
- case JEM_LOCALVARIABLE:
- case JEM_TYPE_PARAMETER:
- buffer.append(JEM_ESCAPE);
- }
- buffer.append(character);
- }
- }
- /**
- * @see IJavaScriptElement
- */
- public boolean exists() {
-
- try {
- getElementInfo();
- return true;
- } catch (JavaScriptModelException e) {
- // element doesn't exist: return false
- }
- return false;
- }
-
- /**
- * Returns the <code>ASTNode</code> that corresponds to this <code>JavaElement</code>
- * or <code>null</code> if there is no corresponding node.
- */
- public ASTNode findNode(JavaScriptUnit ast) {
- return null; // works only inside a compilation unit
- }
- /**
- * Generates the element infos for this element, its ancestors (if they are not opened) and its children (if it is an Openable).
- * Puts the newly created element info in the given map.
- */
- protected abstract void generateInfos(Object info, HashMap newElements, IProgressMonitor pm) throws JavaScriptModelException;
-
- /**
- * @see IJavaScriptElement
- */
- public IJavaScriptElement getAncestor(int ancestorType) {
-
- IJavaScriptElement element = this;
- while (element != null) {
- if (element.getElementType() == ancestorType) return element;
- element= element.getParent();
- }
- return null;
- }
- /**
- * @see IParent
- */
- public IJavaScriptElement[] getChildren() throws JavaScriptModelException {
- Object elementInfo = getElementInfo();
- if (elementInfo instanceof JavaElementInfo) {
- return ((JavaElementInfo)elementInfo).getChildren();
- } else {
- return NO_ELEMENTS;
- }
- }
- /**
- * Returns a collection of (immediate) children of this node of the
- * specified type.
- *
- * @param type - one of the JEM_* constants defined by JavaElement
- */
- public ArrayList getChildrenOfType(int type) throws JavaScriptModelException {
- IJavaScriptElement[] children = getChildren();
- int size = children.length;
- ArrayList list = new ArrayList(size);
- for (int i = 0; i < size; ++i) {
- JavaElement elt = (JavaElement)children[i];
- if (elt.getElementType() == type) {
- list.add(elt);
- }
- }
- return list;
- }
- /**
- * @see org.eclipse.wst.jsdt.core.IMember
- */
- public IClassFile getClassFile() {
- return null;
- }
- /**
- * @see org.eclipse.wst.jsdt.core.IMember
- * @deprecated Use {@link #getJavaScriptUnit()} instead
- */
- public IJavaScriptUnit getCompilationUnit() {
- return getJavaScriptUnit();
- }
- /**
- * @see org.eclipse.wst.jsdt.core.IMember
- */
- public IJavaScriptUnit getJavaScriptUnit() {
- return null;
- }
- /**
- * Returns the info for this handle.
- * If this element is not already open, it and all of its parents are opened.
- * Does not return null.
- * NOTE: BinaryType infos are NOT rooted under JavaElementInfo.
- * @exception JavaScriptModelException if the element is not present or not accessible
- */
- public Object getElementInfo() throws JavaScriptModelException {
- return getElementInfo(null);
- }
- /**
- * Returns the info for this handle.
- * If this element is not already open, it and all of its parents are opened.
- * Does not return null.
- * NOTE: BinaryType infos are NOT rooted under JavaElementInfo.
- * @exception JavaScriptModelException if the element is not present or not accessible
- */
- public Object getElementInfo(IProgressMonitor monitor) throws JavaScriptModelException {
-
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- Object info = manager.getInfo(this);
- if (info != null) return info;
- return openWhenClosed(createElementInfo(), monitor);
- }
- /**
- * @see org.eclipse.core.runtime.IAdaptable
- */
- public String getElementName() {
- return ""; //$NON-NLS-1$
- }
- /*
- * Creates a Java element handle from the given memento.
- * The given token is the current delimiter indicating the type of the next token(s).
- * The given working copy owner is used only for compilation unit handles.
- */
- public abstract IJavaScriptElement getHandleFromMemento(String token, MementoTokenizer memento, WorkingCopyOwner owner);
- /*
- * Creates a Java element handle from the given memento.
- * The given working copy owner is used only for compilation unit handles.
- */
- public IJavaScriptElement getHandleFromMemento(MementoTokenizer memento, WorkingCopyOwner owner) {
- if (!memento.hasMoreTokens()) return this;
- String token = memento.nextToken();
- return getHandleFromMemento(token, memento, owner);
- }
- /**
- * @see IJavaScriptElement
- */
- public String getHandleIdentifier() {
- return getHandleMemento();
- }
- /**
- * @see JavaElement#getHandleMemento()
- */
- public String getHandleMemento(){
- StringBuffer buff = new StringBuffer();
- getHandleMemento(buff);
- return buff.toString();
- }
- protected void getHandleMemento(StringBuffer buff) {
- ((JavaElement)getParent()).getHandleMemento(buff);
- buff.append(getHandleMementoDelimiter());
- escapeMementoName(buff, getElementName());
- }
- /**
- * Returns the <code>char</code> that marks the start of this handles
- * contribution to a memento.
- */
- protected abstract char getHandleMementoDelimiter();
- /**
- * @see IJavaScriptElement
- */
- public IJavaScriptModel getJavaScriptModel() {
- IJavaScriptElement current = this;
- do {
- if (current instanceof IJavaScriptModel) return (IJavaScriptModel) current;
- } while ((current = current.getParent()) != null);
- return null;
- }
-
- /**
- * @see IJavaScriptElement
- */
- public IJavaScriptProject getJavaScriptProject() {
- IJavaScriptElement current = this;
- do {
- if (current instanceof IJavaScriptProject) return (IJavaScriptProject) current;
- } while ((current = current.getParent()) != null);
- return null;
- }
- /*
- * @see IJavaScriptElement
- */
- public IOpenable getOpenable() {
- return this.getOpenableParent();
- }
- /**
- * Return the first instance of IOpenable in the parent
- * hierarchy of this element.
- *
- * <p>Subclasses that are not IOpenable's must override this method.
- */
- public IOpenable getOpenableParent() {
- return (IOpenable)this.parent;
- }
- /**
- * @see IJavaScriptElement
- */
- public IJavaScriptElement getParent() {
- return this.parent;
- }
- /*
- * @see IJavaScriptElement#getPrimaryElement()
- */
- public IJavaScriptElement getPrimaryElement() {
- return getPrimaryElement(true);
- }
- /*
- * Returns the primary element. If checkOwner, and the cu owner is primary,
- * return this element.
- */
- public IJavaScriptElement getPrimaryElement(boolean checkOwner) {
- return this;
- }
- /**
- * Returns the element that is located at the given source position
- * in this element. This is a helper method for <code>IJavaScriptUnit#getElementAt</code>,
- * and only works on compilation units and types. The position given is
- * known to be within this element's source range already, and if no finer
- * grained element is found at the position, this element is returned.
- */
- protected IJavaScriptElement getSourceElementAt(int position) throws JavaScriptModelException {
- if (this instanceof ISourceReference) {
- IJavaScriptElement[] children = getChildren();
- for (int i = children.length-1; i >= 0; i--) {
- IJavaScriptElement aChild = children[i];
- if (aChild instanceof SourceRefElement) {
- SourceRefElement child = (SourceRefElement) children[i];
- ISourceRange range = child.getSourceRange();
- int start = range.getOffset();
- int end = start + range.getLength();
- if (start <= position && position <= end) {
- if (child instanceof IField) {
- // check muti-declaration case (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=39943)
- int declarationStart = start;
- SourceRefElement candidate = null;
- do {
- // check name range
- range = ((IField)child).getNameRange();
- if (position <= range.getOffset() + range.getLength()) {
- candidate = child;
- } else {
- return candidate == null ? child.getSourceElementAt(position) : candidate.getSourceElementAt(position);
- }
- child = --i>=0 ? (SourceRefElement) children[i] : null;
- } while (child != null && child.getSourceRange().getOffset() == declarationStart);
- // position in field's type: use first field
- return candidate.getSourceElementAt(position);
- } else if (child instanceof IParent) {
- return child.getSourceElementAt(position);
- } else {
- return child;
- }
- }
- }
- }
- } else {
- // should not happen
- Assert.isTrue(false);
- }
- return this;
- }
- /**
- * Returns the SourceMapper facility for this element, or
- * <code>null</code> if this element does not have a
- * SourceMapper.
- */
- public SourceMapper getSourceMapper() {
- return ((JavaElement)getParent()).getSourceMapper();
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.IJavaScriptElement#getSchedulingRule()
- */
- public ISchedulingRule getSchedulingRule() {
- IResource resource = getResource();
- if (resource == null) {
- class NoResourceSchedulingRule implements ISchedulingRule {
- public IPath path;
- public NoResourceSchedulingRule(IPath path) {
- this.path = path;
- }
- public boolean contains(ISchedulingRule rule) {
- if (rule instanceof NoResourceSchedulingRule) {
- return this.path.isPrefixOf(((NoResourceSchedulingRule)rule).path);
- } else {
- return false;
- }
- }
- public boolean isConflicting(ISchedulingRule rule) {
- if (rule instanceof NoResourceSchedulingRule) {
- IPath otherPath = ((NoResourceSchedulingRule)rule).path;
- return this.path.isPrefixOf(otherPath) || otherPath.isPrefixOf(this.path);
- } else {
- return false;
- }
- }
- }
- return new NoResourceSchedulingRule(getPath());
- } else {
- return resource;
- }
- }
- /**
- * @see IParent
- */
- public boolean hasChildren() throws JavaScriptModelException {
- // if I am not open, return true to avoid opening (case of a Java project, a compilation unit or a class file).
- // also see https://bugs.eclipse.org/bugs/show_bug.cgi?id=52474
- Object elementInfo = JavaModelManager.getJavaModelManager().getInfo(this);
- if (elementInfo instanceof JavaElementInfo) {
- return ((JavaElementInfo)elementInfo).getChildren().length > 0;
- } else {
- return true;
- }
- }
-
- /**
- * Returns the hash code for this Java element. By default,
- * the hash code for an element is a combination of its name
- * and parent's hash code. Elements with other requirements must
- * override this method.
- */
- public int hashCode() {
- if (this.parent == null) return super.hashCode();
- return Util.combineHashCodes(getElementName().hashCode(), this.parent.hashCode());
- }
- /**
- * Returns true if this element is an ancestor of the given element,
- * otherwise false.
- */
- public boolean isAncestorOf(IJavaScriptElement e) {
- IJavaScriptElement parentElement= e.getParent();
- while (parentElement != null && !parentElement.equals(this)) {
- parentElement= parentElement.getParent();
- }
- return parentElement != null;
- }
-
- /**
- * @see IJavaScriptElement
- */
- public boolean isReadOnly() {
- return false;
- }
- /**
- * Creates and returns a new not present exception for this element.
- */
- public JavaScriptModelException newNotPresentException() {
- return new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.ELEMENT_DOES_NOT_EXIST, this));
- }
- /**
- * Creates and returns a new Java model exception for this element with the given status.
- */
- public JavaScriptModelException newJavaModelException(IStatus status) {
- if (status instanceof IJavaScriptModelStatus)
- return new JavaScriptModelException((IJavaScriptModelStatus) status);
- else
- return new JavaScriptModelException(new JavaModelStatus(status.getSeverity(), status.getCode(), status.getMessage()));
- }
- /*
- * Opens an <code>Openable</code> that is known to be closed (no check for <code>isOpen()</code>).
- * Returns the created element info.
- */
- protected Object openWhenClosed(Object info, IProgressMonitor monitor) throws JavaScriptModelException {
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- boolean hadTemporaryCache = manager.hasTemporaryCache();
- try {
- HashMap newElements = manager.getTemporaryCache();
- generateInfos(info, newElements, monitor);
- if (info == null) {
- info = newElements.get(this);
- }
- if (info == null) { // a source ref element could not be opened
- // close the buffer that was opened for the openable parent
- // close only the openable's buffer (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=62854)
- Openable openable = (Openable) getOpenable();
- if (newElements.containsKey(openable)) {
- openable.closeBuffer();
- }
- throw newNotPresentException();
- }
- if (!hadTemporaryCache) {
- manager.putInfos(this, newElements);
- }
- } finally {
- if (!hadTemporaryCache) {
- manager.resetTemporaryCache();
- }
- }
- return info;
- }
- /**
- */
- public String readableName() {
- return this.getElementName();
- }
- public JavaElement resolved(Binding binding) {
- return this;
- }
- public JavaElement unresolved() {
- return this;
- }
- protected String tabString(int tab) {
- StringBuffer buffer = new StringBuffer();
- for (int i = tab; i > 0; i--)
- buffer.append(" "); //$NON-NLS-1$
- return buffer.toString();
- }
- /**
- * Debugging purposes
- */
- public String toDebugString() {
- StringBuffer buffer = new StringBuffer();
- this.toStringInfo(0, buffer, NO_INFO, true/*show resolved info*/);
- return buffer.toString();
- }
- /**
- * Debugging purposes
- */
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- toString(0, buffer);
- return buffer.toString();
- }
- /**
- * Debugging purposes
- */
- protected void toString(int tab, StringBuffer buffer) {
- Object info = this.toStringInfo(tab, buffer);
- if (tab == 0) {
- this.toStringAncestors(buffer);
- }
- this.toStringChildren(tab, buffer, info);
- }
- /**
- * Debugging purposes
- */
- public String toStringWithAncestors() {
- return toStringWithAncestors(true/*show resolved info*/);
- }
- /**
- * Debugging purposes
- */
- public String toStringWithAncestors(boolean showResolvedInfo) {
- StringBuffer buffer = new StringBuffer();
- this.toStringInfo(0, buffer, NO_INFO, showResolvedInfo);
- this.toStringAncestors(buffer);
- return buffer.toString();
- }
- /**
- * Debugging purposes
- */
- protected void toStringAncestors(StringBuffer buffer) {
- JavaElement parentElement = (JavaElement)this.getParent();
- if (parentElement != null && parentElement.getParent() != null) {
- buffer.append(" [in "); //$NON-NLS-1$
- parentElement.toStringInfo(0, buffer, NO_INFO, false/*don't show resolved info*/);
- parentElement.toStringAncestors(buffer);
- buffer.append("]"); //$NON-NLS-1$
- }
- }
- /**
- * Debugging purposes
- */
- protected void toStringChildren(int tab, StringBuffer buffer, Object info) {
- if (info == null || !(info instanceof JavaElementInfo)) return;
- IJavaScriptElement[] children = ((JavaElementInfo)info).getChildren();
- for (int i = 0; i < children.length; i++) {
- buffer.append("\n"); //$NON-NLS-1$
- ((JavaElement)children[i]).toString(tab + 1, buffer);
- }
- }
- /**
- * Debugging purposes
- */
- public Object toStringInfo(int tab, StringBuffer buffer) {
- Object info = JavaModelManager.getJavaModelManager().peekAtInfo(this);
- this.toStringInfo(tab, buffer, info, true/*show resolved info*/);
- return info;
- }
- /**
- * Debugging purposes
- * @param showResolvedInfo TODO
- */
- protected void toStringInfo(int tab, StringBuffer buffer, Object info, boolean showResolvedInfo) {
- buffer.append(this.tabString(tab));
- toStringName(buffer);
- if (info == null) {
- buffer.append(" (not open)"); //$NON-NLS-1$
- }
- }
- /**
- * Debugging purposes
- */
- protected void toStringName(StringBuffer buffer) {
- buffer.append(getElementName());
- }
-
- protected URL getJavadocBaseLocation() throws JavaScriptModelException {
- IPackageFragmentRoot root= (IPackageFragmentRoot) this.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- if (root == null) {
- return null;
- }
-
- if (root.getKind() == IPackageFragmentRoot.K_BINARY) {
- IIncludePathEntry entry= root.getRawIncludepathEntry();
- if (entry == null) {
- return null;
- }
- if (entry.getEntryKind() == IIncludePathEntry.CPE_CONTAINER) {
- entry= getRealClasspathEntry(root.getJavaScriptProject(), entry.getPath(), root.getPath());
- if (entry == null) {
- return null;
- }
- }
- return getLibraryJavadocLocation(entry);
- }
- return null;
- }
-
- private static IIncludePathEntry getRealClasspathEntry(IJavaScriptProject jproject, IPath containerPath, IPath libPath) throws JavaScriptModelException {
- IJsGlobalScopeContainer container= JavaScriptCore.getJsGlobalScopeContainer(containerPath, jproject);
- if (container != null) {
- IIncludePathEntry[] entries= container.getIncludepathEntries();
- for (int i= 0; i < entries.length; i++) {
- IIncludePathEntry curr = entries[i];
- if (curr == null) {
- if (JavaModelManager.CP_RESOLVE_VERBOSE) {
- JavaModelManager.getJavaModelManager().verbose_missbehaving_container(jproject, containerPath, entries);
- }
- break;
- }
- IIncludePathEntry resolved= JavaScriptCore.getResolvedIncludepathEntry(curr);
- if (resolved != null && libPath.equals(resolved.getPath())) {
- return curr; // return the real entry
- }
- }
- }
- return null; // not found
- }
-
- protected static URL getLibraryJavadocLocation(IIncludePathEntry entry) throws JavaScriptModelException {
- switch(entry.getEntryKind()) {
- case IIncludePathEntry.CPE_LIBRARY :
- case IIncludePathEntry.CPE_VARIABLE :
- break;
- default :
- throw new IllegalArgumentException("Entry must be of kind CPE_LIBRARY or CPE_VARIABLE"); //$NON-NLS-1$
- }
-
- IIncludePathAttribute[] extraAttributes= entry.getExtraAttributes();
- for (int i= 0; i < extraAttributes.length; i++) {
- IIncludePathAttribute attrib= extraAttributes[i];
- if (IIncludePathAttribute.JSDOC_LOCATION_ATTRIBUTE_NAME.equals(attrib.getName())) {
- String value = attrib.getValue();
- try {
- return new URL(value);
- } catch (MalformedURLException e) {
- throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JSDOC, value));
- }
- }
- }
- return null;
- }
-
- /*
- * @see IJavaScriptElement#getAttachedJavadoc(IProgressMonitor)
- */
- public String getAttachedJavadoc(IProgressMonitor monitor) throws JavaScriptModelException {
- return null;
- }
-
- int getIndexOf(byte[] array, byte[] toBeFound, int start) {
- if (array == null || toBeFound == null)
- return -1;
- final int toBeFoundLength = toBeFound.length;
- final int arrayLength = array.length;
- if (arrayLength < toBeFoundLength)
- return -1;
- loop: for (int i = start, max = arrayLength - toBeFoundLength + 1; i < max; i++) {
- if (array[i] == toBeFound[0]) {
- for (int j = 1; j < toBeFoundLength; j++) {
- if (array[i + j] != toBeFound[j])
- continue loop;
- }
- return i;
- }
- }
- return -1;
- }
- /*
- * We don't use getContentEncoding() on the URL connection, because it might leave open streams behind.
- * See https://bugs.eclipse.org/bugs/show_bug.cgi?id=117890
- */
- protected String getURLContents(String docUrlValue) throws JavaScriptModelException {
- InputStream stream = null;
- JarURLConnection connection2 = null;
- try {
- URL docUrl = new URL(docUrlValue);
- URLConnection connection = docUrl.openConnection();
- if (connection instanceof JarURLConnection) {
- connection2 = (JarURLConnection) connection;
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=156307
- connection.setUseCaches(false);
- }
- stream = new BufferedInputStream(connection.getInputStream());
- String encoding = connection.getContentEncoding();
- byte[] contents = org.eclipse.wst.jsdt.internal.compiler.util.Util.getInputStreamAsByteArray(stream, connection.getContentLength());
- if (encoding == null) {
- int index = getIndexOf(contents, CONTENT_TYPE, 0);
- if (index != -1) {
- index = getIndexOf(contents, CONTENT, index);
- if (index != -1) {
- int offset = index + CONTENT.length;
- int index2 = getIndexOf(contents, CLOSING_DOUBLE_QUOTE, offset);
- if (index2 != -1) {
- final int charsetIndex = getIndexOf(contents, CHARSET, offset);
- if (charsetIndex != -1) {
- int start = charsetIndex + CHARSET.length;
- encoding = new String(contents, start, index2 - start, "UTF-8"); //$NON-NLS-1$
- }
- }
- }
- }
- }
- try {
- if (encoding == null) {
- encoding = this.getJavaScriptProject().getProject().getDefaultCharset();
- }
- } catch (CoreException e) {
- // ignore
- }
- if (contents != null) {
- if (encoding != null) {
- return new String(contents, encoding);
- } else {
- // platform encoding is used
- return new String(contents);
- }
- }
- } catch (MalformedURLException e) {
- throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JSDOC, this));
- } catch (FileNotFoundException e) {
- // ignore. see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=120559
- } catch(IOException e) {
- StringWriter stringWriter = new StringWriter();
- PrintWriter writer = new PrintWriter(stringWriter);
- e.printStackTrace(writer);
- writer.flush();
- writer.close();
- throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JSDOC, this, String.valueOf(stringWriter.getBuffer())));
- } finally {
- if (stream != null) {
- try {
- stream.close();
- } catch (IOException e) {
- // ignore
- }
- }
- if (connection2 != null) {
- try {
- connection2.getJarFile().close();
- } catch(IOException e) {
- // ignore
- } catch(IllegalStateException e) {
- /*
- * ignore. Can happen in case the stream.close() did close the jar file
- * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=140750
- */
- }
- }
- }
- return null;
- }
-
- /*
- * Returns a new name lookup. This name lookup first looks in the given working copies.
- */
- public NameLookup newNameLookup(IJavaScriptUnit[] workingCopies) throws JavaScriptModelException {
- return parent!=null?parent.newNameLookup(workingCopies):getJavaScriptProject().newNameLookup(workingCopies);
- }
-
- /*
- * Returns a new name lookup. This name lookup first looks in the working copies of the given owner.
- */
- public NameLookup newNameLookup(WorkingCopyOwner owner) throws JavaScriptModelException {
-
- return parent!=null?parent.newNameLookup(owner):getJavaScriptProject().newNameLookup(owner);
- }
-
- /*
- * Returns a new search name environment for this project. This name environment first looks in the given working copies.
- */
- public SearchableEnvironment newSearchableNameEnvironment(IJavaScriptUnit[] workingCopies) throws JavaScriptModelException {
- return parent!=null?parent.newSearchableNameEnvironment(workingCopies):getJavaScriptProject().newSearchableNameEnvironment(workingCopies);
- }
-
- /*
- * Returns a new search name environment for this project. This name environment first looks in the working copies
- * of the given owner.
- */
- public SearchableEnvironment newSearchableNameEnvironment(WorkingCopyOwner owner) throws JavaScriptModelException {
- return parent!=null?parent.newSearchableNameEnvironment(owner):getJavaScriptProject().newSearchableNameEnvironment(owner);
- }
-
- public String getDisplayName() {
- return getElementName();
- }
-
- public boolean isVirtual() {
- return parent.isVirtual();
- }
-
- public URI getHostPath() {
- if(isVirtual()) return parent.getHostPath();
- return null;
- }
- public LibrarySuperType getCommonSuperType() {
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaElementDelta.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaElementDelta.java
deleted file mode 100644
index 7c5e4dda..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaElementDelta.java
+++ /dev/null
@@ -1,732 +0,0 @@
-/*******************************************************************************
- * 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 java.util.ArrayList;
-
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptElementDelta;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-
-/**
- * @see IJavaScriptElementDelta
- */
-public class JavaElementDelta extends SimpleDelta implements IJavaScriptElementDelta {
- /**
- * @see #getAffectedChildren()
- */
- protected IJavaScriptElementDelta[] affectedChildren = EMPTY_DELTA;
-
- /*
- * The AST created during the last reconcile operation.
- * Non-null only iff:
- * - in a POST_RECONCILE event
- * - an AST was requested during the last reconcile operation
- * - the changed element is an IJavaScriptUnit in working copy mode
- */
- protected JavaScriptUnit ast = null;
-
- /*
- * The element that this delta describes the change to.
- */
- protected IJavaScriptElement changedElement;
-
- /**
- * Collection of resource deltas that correspond to non java resources deltas.
- */
- protected IResourceDelta[] resourceDeltas = null;
-
- /**
- * Counter of resource deltas
- */
- protected int resourceDeltasCounter;
- /**
- * @see #getMovedFromElement()
- */
- protected IJavaScriptElement movedFromHandle = null;
- /**
- * @see #getMovedToElement()
- */
- protected IJavaScriptElement movedToHandle = null;
- /**
- * Empty array of IJavaScriptElementDelta
- */
- protected static IJavaScriptElementDelta[] EMPTY_DELTA= new IJavaScriptElementDelta[] {};
-/**
- * Creates the root delta. To create the nested delta
- * hierarchies use the following convenience methods. The root
- * delta can be created at any level (for example: project, package root,
- * package fragment...).
- * <ul>
- * <li><code>added(IJavaScriptElement)</code>
- * <li><code>changed(IJavaScriptElement)</code>
- * <li><code>moved(IJavaScriptElement, IJavaScriptElement)</code>
- * <li><code>removed(IJavaScriptElement)</code>
- * <li><code>renamed(IJavaScriptElement, IJavaScriptElement)</code>
- * </ul>
- */
-public JavaElementDelta(IJavaScriptElement element) {
- this.changedElement = element;
-}
-/**
- * Adds the child delta to the collection of affected children. If the
- * child is already in the collection, walk down the hierarchy.
- */
-protected void addAffectedChild(JavaElementDelta child) {
- switch (this.kind) {
- case ADDED:
- case REMOVED:
- // no need to add a child if this parent is added or removed
- return;
- case CHANGED:
- this.changeFlags |= F_CHILDREN;
- break;
- default:
- this.kind = CHANGED;
- this.changeFlags |= F_CHILDREN;
- }
-
- // if a child delta is added to a compilation unit delta or below,
- // it's a fine grained delta
- if (this.changedElement.getElementType() >= IJavaScriptElement.JAVASCRIPT_UNIT) {
- this.fineGrained();
- }
-
- if (this.affectedChildren.length == 0) {
- this.affectedChildren = new IJavaScriptElementDelta[] {child};
- return;
- }
- JavaElementDelta existingChild = null;
- int existingChildIndex = -1;
- if (this.affectedChildren != null) {
- for (int i = 0; i < this.affectedChildren.length; i++) {
- if (this.equalsAndSameParent(this.affectedChildren[i].getElement(), child.getElement())) { // handle case of two jars that can be equals but not in the same project
- existingChild = (JavaElementDelta)this.affectedChildren[i];
- existingChildIndex = i;
- break;
- }
- }
- }
- if (existingChild == null) { //new affected child
- this.affectedChildren= growAndAddToArray(this.affectedChildren, child);
- } else {
- switch (existingChild.getKind()) {
- case ADDED:
- switch (child.getKind()) {
- case ADDED: // child was added then added -> it is added
- case CHANGED: // child was added then changed -> it is added
- return;
- case REMOVED: // child was added then removed -> noop
- this.affectedChildren = this.removeAndShrinkArray(this.affectedChildren, existingChildIndex);
- return;
- }
- break;
- case REMOVED:
- switch (child.getKind()) {
- case ADDED: // child was removed then added -> it is changed
- child.kind = CHANGED;
- this.affectedChildren[existingChildIndex] = child;
- return;
- case CHANGED: // child was removed then changed -> it is removed
- case REMOVED: // child was removed then removed -> it is removed
- return;
- }
- break;
- case CHANGED:
- switch (child.getKind()) {
- case ADDED: // child was changed then added -> it is added
- case REMOVED: // child was changed then removed -> it is removed
- this.affectedChildren[existingChildIndex] = child;
- return;
- case CHANGED: // child was changed then changed -> it is changed
- IJavaScriptElementDelta[] children = child.getAffectedChildren();
- for (int i = 0; i < children.length; i++) {
- JavaElementDelta childsChild = (JavaElementDelta) children[i];
- existingChild.addAffectedChild(childsChild);
- }
-
- // update flags
- boolean childHadContentFlag = (child.changeFlags & F_CONTENT) != 0;
- boolean existingChildHadChildrenFlag = (existingChild.changeFlags & F_CHILDREN) != 0;
- existingChild.changeFlags |= child.changeFlags;
-
- // remove F_CONTENT flag if existing child had F_CHILDREN flag set
- // (case of fine grained delta (existing child) and delta coming from
- // DeltaProcessor (child))
- if (childHadContentFlag && existingChildHadChildrenFlag) {
- existingChild.changeFlags &= ~F_CONTENT;
- }
-
- // add the non-java resource deltas if needed
- // note that the child delta always takes precedence over this existing child delta
- // as non-java resource deltas are always created last (by the DeltaProcessor)
- IResourceDelta[] resDeltas = child.getResourceDeltas();
- if (resDeltas != null) {
- existingChild.resourceDeltas = resDeltas;
- existingChild.resourceDeltasCounter = child.resourceDeltasCounter;
- }
-
- return;
- }
- break;
- default:
- // unknown -> existing child becomes the child with the existing child's flags
- int flags = existingChild.getFlags();
- this.affectedChildren[existingChildIndex] = child;
- child.changeFlags |= flags;
- }
- }
-}
-/**
- * Creates the nested deltas resulting from an add operation.
- * Convenience method for creating add deltas.
- * The constructor should be used to create the root delta
- * and then an add operation should call this method.
- */
-public void added(IJavaScriptElement element) {
- added(element, 0);
-}
-public void added(IJavaScriptElement element, int flags) {
- JavaElementDelta addedDelta = new JavaElementDelta(element);
- addedDelta.added();
- addedDelta.changeFlags |= flags;
- insertDeltaTree(element, addedDelta);
-}
-/**
- * Adds the child delta to the collection of affected children. If the
- * child is already in the collection, walk down the hierarchy.
- */
-protected void addResourceDelta(IResourceDelta child) {
- switch (this.kind) {
- case ADDED:
- case REMOVED:
- // no need to add a child if this parent is added or removed
- return;
- case CHANGED:
- this.changeFlags |= F_CONTENT;
- break;
- default:
- this.kind = CHANGED;
- this.changeFlags |= F_CONTENT;
- }
- if (resourceDeltas == null) {
- resourceDeltas = new IResourceDelta[5];
- resourceDeltas[resourceDeltasCounter++] = child;
- return;
- }
- if (resourceDeltas.length == resourceDeltasCounter) {
- // need a resize
- System.arraycopy(resourceDeltas, 0, (resourceDeltas = new IResourceDelta[resourceDeltasCounter * 2]), 0, resourceDeltasCounter);
- }
- resourceDeltas[resourceDeltasCounter++] = child;
-}
-/**
- * Creates the nested deltas resulting from a change operation.
- * Convenience method for creating change deltas.
- * The constructor should be used to create the root delta
- * and then a change operation should call this method.
- */
-public JavaElementDelta changed(IJavaScriptElement element, int changeFlag) {
- JavaElementDelta changedDelta = new JavaElementDelta(element);
- changedDelta.changed(changeFlag);
- insertDeltaTree(element, changedDelta);
- return changedDelta;
-}
-/*
- * Records the last changed AST .
- */
-public void changedAST(JavaScriptUnit changedAST) {
- this.ast = changedAST;
- changed(F_AST_AFFECTED);
-}
-/**
- * Mark this delta as a content changed delta.
- */
-public void contentChanged() {
- this.changeFlags |= F_CONTENT;
-}
-/**
- * Creates the nested deltas for a closed element.
- */
-public void closed(IJavaScriptElement element) {
- JavaElementDelta delta = new JavaElementDelta(element);
- delta.changed(F_CLOSED);
- insertDeltaTree(element, delta);
-}
-/**
- * Creates the nested delta deltas based on the affected element
- * its delta, and the root of this delta tree. Returns the root
- * of the created delta tree.
- */
-protected JavaElementDelta createDeltaTree(IJavaScriptElement element, JavaElementDelta delta) {
- JavaElementDelta childDelta = delta;
- ArrayList ancestors= getAncestors(element);
- if (ancestors == null) {
- if (this.equalsAndSameParent(delta.getElement(), getElement())) { // handle case of two jars that can be equals but not in the same project
- // the element being changed is the root element
- this.kind= delta.kind;
- this.changeFlags = delta.changeFlags;
- this.movedToHandle = delta.movedToHandle;
- this.movedFromHandle = delta.movedFromHandle;
- }
- } else {
- for (int i = 0, size = ancestors.size(); i < size; i++) {
- IJavaScriptElement ancestor = (IJavaScriptElement) ancestors.get(i);
- JavaElementDelta ancestorDelta = new JavaElementDelta(ancestor);
- ancestorDelta.addAffectedChild(childDelta);
- childDelta = ancestorDelta;
- }
- }
- return childDelta;
-}
-/**
- * Returns whether the two java elements are equals and have the same parent.
- */
-protected boolean equalsAndSameParent(IJavaScriptElement e1, IJavaScriptElement e2) {
- IJavaScriptElement parent1;
- return e1.equals(e2) && ((parent1 = e1.getParent()) != null) && parent1.equals(e2.getParent());
-}
-/**
- * Returns the <code>JavaElementDelta</code> for the given element
- * in the delta tree, or null, if no delta for the given element is found.
- */
-protected JavaElementDelta find(IJavaScriptElement e) {
- if (this.equalsAndSameParent(this.changedElement, e)) { // handle case of two jars that can be equals but not in the same project
- return this;
- } else {
- for (int i = 0; i < this.affectedChildren.length; i++) {
- JavaElementDelta delta = ((JavaElementDelta)this.affectedChildren[i]).find(e);
- if (delta != null) {
- return delta;
- }
- }
- }
- return null;
-}
-/**
- * Mark this delta as a fine-grained delta.
- */
-public void fineGrained() {
- changed(F_FINE_GRAINED);
-}
-/**
- * @see IJavaScriptElementDelta
- */
-public IJavaScriptElementDelta[] getAddedChildren() {
- return getChildrenOfType(ADDED);
-}
-/**
- * @see IJavaScriptElementDelta
- */
-public IJavaScriptElementDelta[] getAffectedChildren() {
- return this.affectedChildren;
-}
-/**
- * Returns a collection of all the parents of this element up to (but
- * not including) the root of this tree in bottom-up order. If the given
- * element is not a descendant of the root of this tree, <code>null</code>
- * is returned.
- */
-private ArrayList getAncestors(IJavaScriptElement element) {
- IJavaScriptElement parent = element.getParent();
- if (parent == null) {
- return null;
- }
- ArrayList parents = new ArrayList();
- while (!parent.equals(this.changedElement)) {
- parents.add(parent);
- parent = parent.getParent();
- if (parent == null) {
- return null;
- }
- }
- parents.trimToSize();
- return parents;
-}
-public JavaScriptUnit getJavaScriptUnitAST() {
- return this.ast;
-}
-/**
- * @see IJavaScriptElementDelta
- */
-public IJavaScriptElementDelta[] getChangedChildren() {
- return getChildrenOfType(CHANGED);
-}
-/**
- * @see IJavaScriptElementDelta
- */
-protected IJavaScriptElementDelta[] getChildrenOfType(int type) {
- int length = this.affectedChildren.length;
- if (length == 0) {
- return new IJavaScriptElementDelta[] {};
- }
- ArrayList children= new ArrayList(length);
- for (int i = 0; i < length; i++) {
- if (this.affectedChildren[i].getKind() == type) {
- children.add(this.affectedChildren[i]);
- }
- }
-
- IJavaScriptElementDelta[] childrenOfType = new IJavaScriptElementDelta[children.size()];
- children.toArray(childrenOfType);
-
- return childrenOfType;
-}
-/**
- * Returns the delta for a given element. Only looks below this
- * delta.
- */
-protected JavaElementDelta getDeltaFor(IJavaScriptElement element) {
- if (this.equalsAndSameParent(getElement(), element)) // handle case of two jars that can be equals but not in the same project
- return this;
- if (this.affectedChildren.length == 0)
- return null;
- int childrenCount = this.affectedChildren.length;
- for (int i = 0; i < childrenCount; i++) {
- JavaElementDelta delta = (JavaElementDelta)this.affectedChildren[i];
- if (this.equalsAndSameParent(delta.getElement(), element)) { // handle case of two jars that can be equals but not in the same project
- return delta;
- } else {
- delta = delta.getDeltaFor(element);
- if (delta != null)
- return delta;
- }
- }
- return null;
-}
-/**
- * @see IJavaScriptElementDelta
- */
-public IJavaScriptElement getElement() {
- return this.changedElement;
-}
-/**
- * @see IJavaScriptElementDelta
- */
-public IJavaScriptElement getMovedFromElement() {
- return this.movedFromHandle;
-}
-/**
- * @see IJavaScriptElementDelta
- */
-public IJavaScriptElement getMovedToElement() {
- return movedToHandle;
-}
-/**
- * @see IJavaScriptElementDelta
- */
-public IJavaScriptElementDelta[] getRemovedChildren() {
- return getChildrenOfType(REMOVED);
-}
-/**
- * Return the collection of resource deltas. Return null if none.
- */
-public IResourceDelta[] getResourceDeltas() {
- if (resourceDeltas == null) return null;
- if (resourceDeltas.length != resourceDeltasCounter) {
- System.arraycopy(resourceDeltas, 0, resourceDeltas = new IResourceDelta[resourceDeltasCounter], 0, resourceDeltasCounter);
- }
- return resourceDeltas;
-}
-/**
- * Adds the new element to a new array that contains all of the elements of the old array.
- * Returns the new array.
- */
-protected IJavaScriptElementDelta[] growAndAddToArray(IJavaScriptElementDelta[] array, IJavaScriptElementDelta addition) {
- IJavaScriptElementDelta[] old = array;
- array = new IJavaScriptElementDelta[old.length + 1];
- System.arraycopy(old, 0, array, 0, old.length);
- array[old.length] = addition;
- return array;
-}
-/**
- * Creates the delta tree for the given element and delta, and then
- * inserts the tree as an affected child of this node.
- */
-protected void insertDeltaTree(IJavaScriptElement element, JavaElementDelta delta) {
- JavaElementDelta childDelta= createDeltaTree(element, delta);
- if (!this.equalsAndSameParent(element, getElement())) { // handle case of two jars that can be equals but not in the same project
- addAffectedChild(childDelta);
- }
-}
-/**
- * Creates the nested deltas resulting from an move operation.
- * Convenience method for creating the "move from" delta.
- * The constructor should be used to create the root delta
- * and then the move operation should call this method.
- */
-public void movedFrom(IJavaScriptElement movedFromElement, IJavaScriptElement movedToElement) {
- JavaElementDelta removedDelta = new JavaElementDelta(movedFromElement);
- removedDelta.kind = REMOVED;
- removedDelta.changeFlags |= F_MOVED_TO;
- removedDelta.movedToHandle = movedToElement;
- insertDeltaTree(movedFromElement, removedDelta);
-}
-/**
- * Creates the nested deltas resulting from an move operation.
- * Convenience method for creating the "move to" delta.
- * The constructor should be used to create the root delta
- * and then the move operation should call this method.
- */
-public void movedTo(IJavaScriptElement movedToElement, IJavaScriptElement movedFromElement) {
- JavaElementDelta addedDelta = new JavaElementDelta(movedToElement);
- addedDelta.kind = ADDED;
- addedDelta.changeFlags |= F_MOVED_FROM;
- addedDelta.movedFromHandle = movedFromElement;
- insertDeltaTree(movedToElement, addedDelta);
-}
-/**
- * Creates the nested deltas for an opened element.
- */
-public void opened(IJavaScriptElement element) {
- JavaElementDelta delta = new JavaElementDelta(element);
- delta.changed(F_OPENED);
- insertDeltaTree(element, delta);
-}
-/**
- * Removes the child delta from the collection of affected children.
- */
-protected void removeAffectedChild(JavaElementDelta child) {
- int index = -1;
- if (this.affectedChildren != null) {
- for (int i = 0; i < this.affectedChildren.length; i++) {
- if (this.equalsAndSameParent(this.affectedChildren[i].getElement(), child.getElement())) { // handle case of two jars that can be equals but not in the same project
- index = i;
- break;
- }
- }
- }
- if (index >= 0) {
- this.affectedChildren= removeAndShrinkArray(this.affectedChildren, index);
- }
-}
-/**
- * Removes the element from the array.
- * Returns the a new array which has shrunk.
- */
-protected IJavaScriptElementDelta[] removeAndShrinkArray(IJavaScriptElementDelta[] old, int index) {
- IJavaScriptElementDelta[] array = new IJavaScriptElementDelta[old.length - 1];
- if (index > 0)
- System.arraycopy(old, 0, array, 0, index);
- int rest = old.length - index - 1;
- if (rest > 0)
- System.arraycopy(old, index + 1, array, index, rest);
- return array;
-}
-/**
- * Creates the nested deltas resulting from an delete operation.
- * Convenience method for creating removed deltas.
- * The constructor should be used to create the root delta
- * and then the delete operation should call this method.
- */
-public void removed(IJavaScriptElement element) {
- removed(element, 0);
-}
-public void removed(IJavaScriptElement element, int flags) {
- JavaElementDelta removedDelta= new JavaElementDelta(element);
- insertDeltaTree(element, removedDelta);
- JavaElementDelta actualDelta = getDeltaFor(element);
- if (actualDelta != null) {
- actualDelta.removed();
- actualDelta.changeFlags |= flags;
- actualDelta.affectedChildren = EMPTY_DELTA;
- }
-}
-/**
- * Creates the nested deltas resulting from a change operation.
- * Convenience method for creating change deltas.
- * The constructor should be used to create the root delta
- * and then a change operation should call this method.
- */
-public void sourceAttached(IJavaScriptElement element) {
- JavaElementDelta attachedDelta = new JavaElementDelta(element);
- attachedDelta.changed(F_SOURCEATTACHED);
- insertDeltaTree(element, attachedDelta);
-}
-/**
- * Creates the nested deltas resulting from a change operation.
- * Convenience method for creating change deltas.
- * The constructor should be used to create the root delta
- * and then a change operation should call this method.
- */
-public void sourceDetached(IJavaScriptElement element) {
- JavaElementDelta detachedDelta = new JavaElementDelta(element);
- detachedDelta.changed(F_SOURCEDETACHED);
- insertDeltaTree(element, detachedDelta);
-}
-/**
- * Returns a string representation of this delta's
- * structure suitable for debug purposes.
- *
- * @see #toString()
- */
-public String toDebugString(int depth) {
- StringBuffer buffer = new StringBuffer();
- for (int i= 0; i < depth; i++) {
- buffer.append('\t');
- }
- buffer.append(((JavaElement)getElement()).toDebugString());
- toDebugString(buffer);
- IJavaScriptElementDelta[] children = getAffectedChildren();
- if (children != null) {
- for (int i = 0; i < children.length; ++i) {
- buffer.append("\n"); //$NON-NLS-1$
- buffer.append(((JavaElementDelta) children[i]).toDebugString(depth + 1));
- }
- }
- for (int i = 0; i < resourceDeltasCounter; i++) {
- buffer.append("\n");//$NON-NLS-1$
- for (int j = 0; j < depth+1; j++) {
- buffer.append('\t');
- }
- IResourceDelta resourceDelta = resourceDeltas[i];
- buffer.append(resourceDelta.toString());
- buffer.append("["); //$NON-NLS-1$
- switch (resourceDelta.getKind()) {
- case IResourceDelta.ADDED :
- buffer.append('+');
- break;
- case IResourceDelta.REMOVED :
- buffer.append('-');
- break;
- case IResourceDelta.CHANGED :
- buffer.append('*');
- break;
- default :
- buffer.append('?');
- break;
- }
- buffer.append("]"); //$NON-NLS-1$
- }
- return buffer.toString();
-}
-protected boolean toDebugString(StringBuffer buffer, int flags) {
- boolean prev = super.toDebugString(buffer, flags);
-
- if ((flags & IJavaScriptElementDelta.F_CHILDREN) != 0) {
- if (prev)
- buffer.append(" | "); //$NON-NLS-1$
- buffer.append("CHILDREN"); //$NON-NLS-1$
- prev = true;
- }
- if ((flags & IJavaScriptElementDelta.F_CONTENT) != 0) {
- if (prev)
- buffer.append(" | "); //$NON-NLS-1$
- buffer.append("CONTENT"); //$NON-NLS-1$
- prev = true;
- }
- if ((flags & IJavaScriptElementDelta.F_MOVED_FROM) != 0) {
- if (prev)
- buffer.append(" | "); //$NON-NLS-1$
- buffer.append("MOVED_FROM(" + ((JavaElement)getMovedFromElement()).toStringWithAncestors() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
- prev = true;
- }
- if ((flags & IJavaScriptElementDelta.F_MOVED_TO) != 0) {
- if (prev)
- buffer.append(" | "); //$NON-NLS-1$
- buffer.append("MOVED_TO(" + ((JavaElement)getMovedToElement()).toStringWithAncestors() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
- prev = true;
- }
- if ((flags & IJavaScriptElementDelta.F_ADDED_TO_CLASSPATH) != 0) {
- if (prev)
- buffer.append(" | "); //$NON-NLS-1$
- buffer.append("ADDED TO CLASSPATH"); //$NON-NLS-1$
- prev = true;
- }
- if ((flags & IJavaScriptElementDelta.F_REMOVED_FROM_CLASSPATH) != 0) {
- if (prev)
- buffer.append(" | "); //$NON-NLS-1$
- buffer.append("REMOVED FROM CLASSPATH"); //$NON-NLS-1$
- prev = true;
- }
- if ((flags & IJavaScriptElementDelta.F_REORDER) != 0) {
- if (prev)
- buffer.append(" | "); //$NON-NLS-1$
- buffer.append("REORDERED"); //$NON-NLS-1$
- prev = true;
- }
- if ((flags & IJavaScriptElementDelta.F_ARCHIVE_CONTENT_CHANGED) != 0) {
- if (prev)
- buffer.append(" | "); //$NON-NLS-1$
- buffer.append("ARCHIVE CONTENT CHANGED"); //$NON-NLS-1$
- prev = true;
- }
- if ((flags & IJavaScriptElementDelta.F_SOURCEATTACHED) != 0) {
- if (prev)
- buffer.append(" | "); //$NON-NLS-1$
- buffer.append("SOURCE ATTACHED"); //$NON-NLS-1$
- prev = true;
- }
- if ((flags & IJavaScriptElementDelta.F_SOURCEDETACHED) != 0) {
- if (prev)
- buffer.append(" | "); //$NON-NLS-1$
- buffer.append("SOURCE DETACHED"); //$NON-NLS-1$
- prev = true;
- }
- if ((flags & IJavaScriptElementDelta.F_FINE_GRAINED) != 0) {
- if (prev)
- buffer.append(" | "); //$NON-NLS-1$
- buffer.append("FINE GRAINED"); //$NON-NLS-1$
- prev = true;
- }
- if ((flags & IJavaScriptElementDelta.F_PRIMARY_WORKING_COPY) != 0) {
- if (prev)
- buffer.append(" | "); //$NON-NLS-1$
- buffer.append("PRIMARY WORKING COPY"); //$NON-NLS-1$
- prev = true;
- }
- if ((flags & IJavaScriptElementDelta.F_INCLUDEPATH_CHANGED) != 0) {
- if (prev)
- buffer.append(" | "); //$NON-NLS-1$
- buffer.append("CLASSPATH CHANGED"); //$NON-NLS-1$
- prev = true;
- }
- if ((flags & IJavaScriptElementDelta.F_PRIMARY_RESOURCE) != 0) {
- if (prev)
- buffer.append(" | "); //$NON-NLS-1$
- buffer.append("PRIMARY RESOURCE"); //$NON-NLS-1$
- prev = true;
- }
- if ((flags & IJavaScriptElementDelta.F_OPENED) != 0) {
- if (prev)
- buffer.append(" | "); //$NON-NLS-1$
- buffer.append("OPENED"); //$NON-NLS-1$
- prev = true;
- }
- if ((flags & IJavaScriptElementDelta.F_CLOSED) != 0) {
- if (prev)
- buffer.append(" | "); //$NON-NLS-1$
- buffer.append("CLOSED"); //$NON-NLS-1$
- prev = true;
- }
- if ((flags & IJavaScriptElementDelta.F_AST_AFFECTED) != 0) {
- if (prev)
- buffer.append(" | "); //$NON-NLS-1$
- buffer.append("AST AFFECTED"); //$NON-NLS-1$
- prev = true;
- }
- if ((flags & IJavaScriptElementDelta.F_CATEGORIES) != 0) {
- if (prev)
- buffer.append(" | "); //$NON-NLS-1$
- buffer.append("CATEGORIES"); //$NON-NLS-1$
- prev = true;
- }
- return prev;
-}
-/**
- * Returns a string representation of this delta's
- * structure suitable for debug purposes.
- */
-public String toString() {
- return toDebugString(0);
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaElementDeltaBuilder.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaElementDeltaBuilder.java
deleted file mode 100644
index d0d7af6f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaElementDeltaBuilder.java
+++ /dev/null
@@ -1,449 +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;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptElementDelta;
-import org.eclipse.wst.jsdt.core.IParent;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * A java element delta biulder creates a java element delta on
- * a java element between the version of the java element
- * at the time the comparator was created and the current version
- * of the java element.
- *
- * It performs this operation by locally caching the contents of
- * the java element when it is created. When the method
- * createDeltas() is called, it creates a delta over the cached
- * contents and the new contents.
- */
-public class JavaElementDeltaBuilder {
- /**
- * The java element handle
- */
- IJavaScriptElement javaElement;
-
- /**
- * The maximum depth in the java element children we should look into
- */
- int maxDepth = Integer.MAX_VALUE;
-
- /**
- * The old handle to info relationships
- */
- Map infos;
-
- /**
- * The old position info
- */
- Map oldPositions;
-
- /**
- * The new position info
- */
- Map newPositions;
-
- /**
- * Change delta
- */
- public JavaElementDelta delta = null;
-
- /**
- * List of added elements
- */
- ArrayList added;
-
- /**
- * List of removed elements
- */
- ArrayList removed;
-
- /**
- * Doubly linked list item
- */
- static class ListItem {
- public IJavaScriptElement previous;
- public IJavaScriptElement next;
-
- public ListItem(IJavaScriptElement previous, IJavaScriptElement next) {
- this.previous = previous;
- this.next = next;
- }
- }
-/**
- * Creates a java element comparator on a java element
- * looking as deep as necessary.
- */
-public JavaElementDeltaBuilder(IJavaScriptElement javaElement) {
- this.javaElement = javaElement;
- this.initialize();
- this.recordElementInfo(
- javaElement,
- (JavaModel)this.javaElement.getJavaScriptModel(),
- 0);
-}
-/**
- * Creates a java element comparator on a java element
- * looking only 'maxDepth' levels deep.
- */
-public JavaElementDeltaBuilder(IJavaScriptElement javaElement, int maxDepth) {
- this.javaElement = javaElement;
- this.maxDepth = maxDepth;
- this.initialize();
- this.recordElementInfo(
- javaElement,
- (JavaModel)this.javaElement.getJavaScriptModel(),
- 0);
-}
-/**
- * Repairs the positioning information
- * after an element has been added
- */
-private void added(IJavaScriptElement element) {
- this.added.add(element);
- ListItem current = this.getNewPosition(element);
- ListItem previous = null, next = null;
- if (current.previous != null)
- previous = this.getNewPosition(current.previous);
- if (current.next != null)
- next = this.getNewPosition(current.next);
- if (previous != null)
- previous.next = current.next;
- if (next != null)
- next.previous = current.previous;
-}
-/**
- * Builds the java element deltas between the old content of the compilation
- * unit and its new content.
- */
-public void buildDeltas() {
- this.delta = new JavaElementDelta(this.javaElement);
- // if building a delta on a compilation unit or below,
- // it's a fine grained delta
- if (this.javaElement.getElementType() >= IJavaScriptElement.JAVASCRIPT_UNIT) {
- this.delta.fineGrained();
- }
- this.recordNewPositions(this.javaElement, 0);
- this.findAdditions(this.javaElement, 0);
- this.findDeletions();
- this.findChangesInPositioning(this.javaElement, 0);
- this.trimDelta(this.delta);
- if (this.delta.getAffectedChildren().length == 0) {
- // this is a fine grained but not children affected -> mark as content changed
- this.delta.contentChanged();
- }
-}
-private boolean equals(char[][][] first, char[][][] second) {
- if (first == second)
- return true;
- if (first == null || second == null)
- return false;
- if (first.length != second.length)
- return false;
-
- for (int i = first.length; --i >= 0;)
- if (!CharOperation.equals(first[i], second[i]))
- return false;
- return true;
-}
-/**
- * Finds elements which have been added or changed.
- */
-private void findAdditions(IJavaScriptElement newElement, int depth) {
- JavaElementInfo oldInfo = this.getElementInfo(newElement);
- if (oldInfo == null && depth < this.maxDepth) {
- this.delta.added(newElement);
- added(newElement);
- } else {
- this.removeElementInfo(newElement);
- }
-
- if (depth >= this.maxDepth) {
- // mark element as changed
- this.delta.changed(newElement, IJavaScriptElementDelta.F_CONTENT);
- return;
- }
-
- JavaElementInfo newInfo = null;
- try {
- newInfo = (JavaElementInfo)((JavaElement)newElement).getElementInfo();
- } catch (JavaScriptModelException npe) {
- return;
- }
-
- this.findContentChange(oldInfo, newInfo, newElement);
-
- if (oldInfo != null && newElement instanceof IParent) {
-
- IJavaScriptElement[] children = newInfo.getChildren();
- if (children != null) {
- int length = children.length;
- for(int i = 0; i < length; i++) {
- this.findAdditions(children[i], depth + 1);
- }
- }
- }
-}
-/**
- * Looks for changed positioning of elements.
- */
-private void findChangesInPositioning(IJavaScriptElement element, int depth) {
- if (depth >= this.maxDepth || this.added.contains(element) || this.removed.contains(element))
- return;
-
- if (!isPositionedCorrectly(element)) {
- this.delta.changed(element, IJavaScriptElementDelta.F_REORDER);
- }
-
- if (element instanceof IParent) {
- JavaElementInfo info = null;
- try {
- info = (JavaElementInfo)((JavaElement)element).getElementInfo();
- } catch (JavaScriptModelException npe) {
- return;
- }
-
- IJavaScriptElement[] children = info.getChildren();
- if (children != null) {
- int length = children.length;
- for(int i = 0; i < length; i++) {
- this.findChangesInPositioning(children[i], depth + 1);
- }
- }
- }
-}
-/**
- * The elements are equivalent, but might have content changes.
- */
-private void findContentChange(JavaElementInfo oldInfo, JavaElementInfo newInfo, IJavaScriptElement newElement) {
- if (oldInfo instanceof MemberElementInfo && newInfo instanceof MemberElementInfo) {
- if (((MemberElementInfo)oldInfo).getModifiers() != ((MemberElementInfo)newInfo).getModifiers()) {
- this.delta.changed(newElement, IJavaScriptElementDelta.F_MODIFIERS);
- } else if (oldInfo instanceof SourceMethodElementInfo && newInfo instanceof SourceMethodElementInfo) {
- SourceMethodElementInfo oldSourceMethodInfo = (SourceMethodElementInfo)oldInfo;
- SourceMethodElementInfo newSourceMethodInfo = (SourceMethodElementInfo)newInfo;
- if (!CharOperation.equals(oldSourceMethodInfo.getReturnTypeName(), newSourceMethodInfo.getReturnTypeName())) {
- this.delta.changed(newElement, IJavaScriptElementDelta.F_CONTENT);
- }
- } else if (oldInfo instanceof SourceFieldElementInfo && newInfo instanceof SourceFieldElementInfo) {
- if (!CharOperation.equals(
- ((SourceFieldElementInfo)oldInfo).getTypeName(),
- ((SourceFieldElementInfo)newInfo).getTypeName())) {
- this.delta.changed(newElement, IJavaScriptElementDelta.F_CONTENT);
- }
- }
- }
- if (oldInfo instanceof SourceTypeElementInfo && newInfo instanceof SourceTypeElementInfo) {
- SourceTypeElementInfo oldSourceTypeInfo = (SourceTypeElementInfo)oldInfo;
- SourceTypeElementInfo newSourceTypeInfo = (SourceTypeElementInfo)newInfo;
- if (!CharOperation.equals(oldSourceTypeInfo.getSuperclassName(), newSourceTypeInfo.getSuperclassName())
- || !CharOperation.equals(oldSourceTypeInfo.getInterfaceNames(), newSourceTypeInfo.getInterfaceNames())) {
- this.delta.changed(newElement, IJavaScriptElementDelta.F_SUPER_TYPES);
- }
-
- HashMap oldTypeCategories = oldSourceTypeInfo.categories;
- HashMap newTypeCategories = newSourceTypeInfo.categories;
- if (oldTypeCategories != null) {
- // take the union of old and new categories elements (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=125675)
- Set elements;
- if (newTypeCategories != null) {
- elements = new HashSet(oldTypeCategories.keySet());
- elements.addAll(newTypeCategories.keySet());
- } else
- elements = oldTypeCategories.keySet();
- Iterator iterator = elements.iterator();
- while (iterator.hasNext()) {
- IJavaScriptElement element = (IJavaScriptElement) iterator.next();
- String[] oldCategories = (String[]) oldTypeCategories.get(element);
- String[] newCategories = newTypeCategories == null ? null : (String[]) newTypeCategories.get(element);
- if (!Util.equalArraysOrNull(oldCategories, newCategories)) {
- this.delta.changed(element, IJavaScriptElementDelta.F_CATEGORIES);
- }
- }
- } else if (newTypeCategories != null) {
- Iterator elements = newTypeCategories.keySet().iterator();
- while (elements.hasNext()) {
- IJavaScriptElement element = (IJavaScriptElement) elements.next();
- this.delta.changed(element, IJavaScriptElementDelta.F_CATEGORIES); // all categories for this element were removed
- }
- }
- }
-}
-/**
- * Adds removed deltas for any handles left in the table
- */
-private void findDeletions() {
- Iterator iter = this.infos.keySet().iterator();
- while(iter.hasNext()) {
- IJavaScriptElement element = (IJavaScriptElement)iter.next();
- this.delta.removed(element);
- this.removed(element);
- }
-}
-private JavaElementInfo getElementInfo(IJavaScriptElement element) {
- return (JavaElementInfo)this.infos.get(element);
-}
-private ListItem getNewPosition(IJavaScriptElement element) {
- return (ListItem)this.newPositions.get(element);
-}
-private ListItem getOldPosition(IJavaScriptElement element) {
- return (ListItem)this.oldPositions.get(element);
-}
-private void initialize() {
- this.infos = new HashMap(20);
- this.oldPositions = new HashMap(20);
- this.newPositions = new HashMap(20);
- this.putOldPosition(this.javaElement, new ListItem(null, null));
- this.putNewPosition(this.javaElement, new ListItem(null, null));
- this.added = new ArrayList(5);
- this.removed = new ArrayList(5);
-}
-/**
- * Inserts position information for the elements into the new or old positions table
- */
-private void insertPositions(IJavaScriptElement[] elements, boolean isNew) {
- int length = elements.length;
- IJavaScriptElement previous = null, current = null, next = (length > 0) ? elements[0] : null;
- for(int i = 0; i < length; i++) {
- previous = current;
- current = next;
- next = (i + 1 < length) ? elements[i + 1] : null;
- if (isNew) {
- this.putNewPosition(current, new ListItem(previous, next));
- } else {
- this.putOldPosition(current, new ListItem(previous, next));
- }
- }
-}
-/**
- * Returns whether the elements position has not changed.
- */
-private boolean isPositionedCorrectly(IJavaScriptElement element) {
- ListItem oldListItem = this.getOldPosition(element);
- if (oldListItem == null) return false;
-
- ListItem newListItem = this.getNewPosition(element);
- if (newListItem == null) return false;
-
- IJavaScriptElement oldPrevious = oldListItem.previous;
- IJavaScriptElement newPrevious = newListItem.previous;
- if (oldPrevious == null) {
- return newPrevious == null;
- } else {
- return oldPrevious.equals(newPrevious);
- }
-}
-private void putElementInfo(IJavaScriptElement element, JavaElementInfo info) {
- this.infos.put(element, info);
-}
-private void putNewPosition(IJavaScriptElement element, ListItem position) {
- this.newPositions.put(element, position);
-}
-private void putOldPosition(IJavaScriptElement element, ListItem position) {
- this.oldPositions.put(element, position);
-}
-/**
- * Records this elements info, and attempts
- * to record the info for the children.
- */
-private void recordElementInfo(IJavaScriptElement element, JavaModel model, int depth) {
- if (depth >= this.maxDepth) {
- return;
- }
- JavaElementInfo info = (JavaElementInfo)JavaModelManager.getJavaModelManager().getInfo(element);
- if (info == null) // no longer in the java model.
- return;
- this.putElementInfo(element, info);
-
- if (element instanceof IParent) {
- IJavaScriptElement[] children = info.getChildren();
- if (children != null) {
- insertPositions(children, false);
- for(int i = 0, length = children.length; i < length; i++)
- recordElementInfo(children[i], model, depth + 1);
- }
- }
-}
-/**
- * Fills the newPositions hashtable with the new position information
- */
-private void recordNewPositions(IJavaScriptElement newElement, int depth) {
- if (depth < this.maxDepth && newElement instanceof IParent) {
- JavaElementInfo info = null;
- try {
- info = (JavaElementInfo)((JavaElement)newElement).getElementInfo();
- } catch (JavaScriptModelException npe) {
- return;
- }
-
- IJavaScriptElement[] children = info.getChildren();
- if (children != null) {
- insertPositions(children, true);
- for(int i = 0, length = children.length; i < length; i++) {
- recordNewPositions(children[i], depth + 1);
- }
- }
- }
-}
-/**
- * Repairs the positioning information
- * after an element has been removed
- */
-private void removed(IJavaScriptElement element) {
- this.removed.add(element);
- ListItem current = this.getOldPosition(element);
- ListItem previous = null, next = null;
- if (current.previous != null)
- previous = this.getOldPosition(current.previous);
- if (current.next != null)
- next = this.getOldPosition(current.next);
- if (previous != null)
- previous.next = current.next;
- if (next != null)
- next.previous = current.previous;
-
-}
-private void removeElementInfo(IJavaScriptElement element) {
- this.infos.remove(element);
-}
-public String toString() {
- StringBuffer buffer = new StringBuffer();
- buffer.append("Built delta:\n"); //$NON-NLS-1$
- buffer.append(this.delta == null ? "<null>" : this.delta.toString()); //$NON-NLS-1$
- return buffer.toString();
-}
-/**
- * Trims deletion deltas to only report the highest level of deletion
- */
-private void trimDelta(JavaElementDelta elementDelta) {
- if (elementDelta.getKind() == IJavaScriptElementDelta.REMOVED) {
- IJavaScriptElementDelta[] children = elementDelta.getAffectedChildren();
- for(int i = 0, length = children.length; i < length; i++) {
- elementDelta.removeAffectedChild((JavaElementDelta)children[i]);
- }
- } else {
- IJavaScriptElementDelta[] children = elementDelta.getAffectedChildren();
- for(int i = 0, length = children.length; i < length; i++) {
- trimDelta((JavaElementDelta)children[i]);
- }
- }
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaElementInfo.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaElementInfo.java
deleted file mode 100644
index f17100c0..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaElementInfo.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*******************************************************************************
- * 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.core.IJavaScriptElement;
-
-/**
- * Holds cached structure and properties for a Java element.
- * Subclassed to carry properties for specific kinds of elements.
- */
-/* package */ class JavaElementInfo {
-
- /**
- * Collection of handles of immediate children of this
- * object. This is an empty array if this element has
- * no children.
- */
- protected IJavaScriptElement[] children;
-
- /**
- * Shared empty collection used for efficiency.
- */
- static Object[] NO_NON_JAVA_RESOURCES = new Object[] {};
-
- protected JavaElementInfo() {
- this.children = JavaElement.NO_ELEMENTS;
- }
- public void addChild(IJavaScriptElement child) {
- int length = this.children.length;
- if (length == 0) {
- this.children = new IJavaScriptElement[] {child};
- } else {
- for (int i = 0; i < length; i++) {
- if (children[i].equals(child))
- return; // already included
- }
- System.arraycopy(this.children, 0, this.children = new IJavaScriptElement[length+1], 0, length);
- this.children[length] = child;
- }
- }
- public Object clone() {
- try {
- return super.clone();
- }
- catch (CloneNotSupportedException e) {
- throw new Error();
- }
- }
- public IJavaScriptElement[] getChildren() {
- return this.children;
- }
- public void removeChild(IJavaScriptElement child) {
- for (int i = 0, length = this.children.length; i < length; i++) {
- IJavaScriptElement element = this.children[i];
- if (element.equals(child)) {
- if (length == 1) {
- this.children = JavaElement.NO_ELEMENTS;
- } else {
- IJavaScriptElement[] newChildren = new IJavaScriptElement[length-1];
- System.arraycopy(this.children, 0, newChildren , 0, i);
- if (i < length-1)
- System.arraycopy(this.children, i+1, newChildren, i, length-1-i);
- this.children = newChildren;
- }
- break;
- }
- }
- }
- public void setChildren(IJavaScriptElement[] children) {
- this.children = children;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaElementRequestor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaElementRequestor.java
deleted file mode 100644
index 0a8801d6..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaElementRequestor.java
+++ /dev/null
@@ -1,226 +0,0 @@
-/*******************************************************************************
- * 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 java.util.ArrayList;
-
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IInitializer;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IType;
-
-/**
- * @see IJavaElementRequestor
- */
-
-public class JavaElementRequestor implements IJavaElementRequestor {
- /**
- * True if this requestor no longer wants to receive
- * results from its <code>IRequestorNameLookup</code>.
- */
- protected boolean fCanceled= false;
-
- /**
- * A collection of the resulting fields, or <code>null</code>
- * if no field results have been received.
- */
- protected ArrayList fFields= null;
-
- /**
- * A collection of the resulting initializers, or <code>null</code>
- * if no initializer results have been received.
- */
- protected ArrayList fInitializers= null;
-
- /**
- * A collection of the resulting member types, or <code>null</code>
- * if no member type results have been received.
- */
- protected ArrayList fMemberTypes= null;
-
- /**
- * A collection of the resulting methods, or <code>null</code>
- * if no method results have been received.
- */
- protected ArrayList fMethods= null;
-
- /**
- * A collection of the resulting package fragments, or <code>null</code>
- * if no package fragment results have been received.
- */
- protected ArrayList fPackageFragments= null;
-
- /**
- * A collection of the resulting types, or <code>null</code>
- * if no type results have been received.
- */
- protected ArrayList fTypes= null;
-
- /**
- * Empty arrays used for efficiency
- */
- protected static IField[] fgEmptyFieldArray= new IField[0];
- protected static IInitializer[] fgEmptyInitializerArray= new IInitializer[0];
- protected static IType[] fgEmptyTypeArray= new IType[0];
- protected static IPackageFragment[] fgEmptyPackageFragmentArray= new IPackageFragment[0];
- protected static IFunction[] fgEmptyMethodArray= new IFunction[0];
-/**
- * @see IJavaElementRequestor
- */
-public void acceptField(IField field) {
- if (fFields == null) {
- fFields= new ArrayList();
- }
- fFields.add(field);
-}
-/**
- * @see IJavaElementRequestor
- */
-public void acceptInitializer(IInitializer initializer) {
- if (fInitializers == null) {
- fInitializers= new ArrayList();
- }
- fInitializers.add(initializer);
-}
-/**
- * @see IJavaElementRequestor
- */
-public void acceptMemberType(IType type) {
- if (fMemberTypes == null) {
- fMemberTypes= new ArrayList();
- }
- fMemberTypes.add(type);
-}
-/**
- * @see IJavaElementRequestor
- */
-public void acceptMethod(IFunction method) {
- if (fMethods == null) {
- fMethods = new ArrayList();
- }
- fMethods.add(method);
-}
-/**
- * @see IJavaElementRequestor
- */
-public void acceptPackageFragment(IPackageFragment packageFragment) {
- if (fPackageFragments== null) {
- fPackageFragments= new ArrayList();
- }
- fPackageFragments.add(packageFragment);
-}
-/**
- * @see IJavaElementRequestor
- */
-public void acceptType(IType type) {
- if (fTypes == null) {
- fTypes= new ArrayList();
- }
- fTypes.add(type);
-}
-/**
- * @see IJavaElementRequestor
- */
-public IField[] getFields() {
- if (fFields == null) {
- return fgEmptyFieldArray;
- }
- int size = fFields.size();
- IField[] results = new IField[size];
- fFields.toArray(results);
- return results;
-}
-/**
- * @see IJavaElementRequestor
- */
-public IInitializer[] getInitializers() {
- if (fInitializers == null) {
- return fgEmptyInitializerArray;
- }
- int size = fInitializers.size();
- IInitializer[] results = new IInitializer[size];
- fInitializers.toArray(results);
- return results;
-}
-/**
- * @see IJavaElementRequestor
- */
-public IType[] getMemberTypes() {
- if (fMemberTypes == null) {
- return fgEmptyTypeArray;
- }
- int size = fMemberTypes.size();
- IType[] results = new IType[size];
- fMemberTypes.toArray(results);
- return results;
-}
-/**
- * @see IJavaElementRequestor
- */
-public IFunction[] getMethods() {
- if (fMethods == null) {
- return fgEmptyMethodArray;
- }
- int size = fMethods.size();
- IFunction[] results = new IFunction[size];
- fMethods.toArray(results);
- return results;
-}
-/**
- * @see IJavaElementRequestor
- */
-public IPackageFragment[] getPackageFragments() {
- if (fPackageFragments== null) {
- return fgEmptyPackageFragmentArray;
- }
- int size = fPackageFragments.size();
- IPackageFragment[] results = new IPackageFragment[size];
- fPackageFragments.toArray(results);
- return results;
-}
-/**
- * @see IJavaElementRequestor
- */
-public IType[] getTypes() {
- if (fTypes== null) {
- return fgEmptyTypeArray;
- }
- int size = fTypes.size();
- IType[] results = new IType[size];
- fTypes.toArray(results);
- return results;
-}
-/**
- * @see IJavaElementRequestor
- */
-public boolean isCanceled() {
- return fCanceled;
-}
-/**
- * Reset the state of this requestor.
- */
-public void reset() {
- fCanceled = false;
- fFields = null;
- fInitializers = null;
- fMemberTypes = null;
- fMethods = null;
- fPackageFragments = null;
- fTypes = null;
-}
-/**
- * Sets the #isCanceled state of this requestor to true or false.
- */
-public void setCanceled(boolean b) {
- fCanceled= b;
-}
-}
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
deleted file mode 100644
index e190c53e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaModel.java
+++ /dev/null
@@ -1,385 +0,0 @@
-/*******************************************************************************
- * 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 java.io.File;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Map;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.internal.core.util.MementoTokenizer;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-
-/**
- * Implementation of <code>IJavaScriptModel<code>. The Java Model maintains a cache of
- * active <code>IJavaScriptProject</code>s in a workspace. A Java Model is specific to a
- * workspace. To retrieve a workspace's model, use the
- * <code>#getJavaModel(IWorkspace)</code> method.
- *
- * @see IJavaScriptModel
- */
-public class JavaModel extends Openable implements IJavaScriptModel {
-
- /**
- * A set of java.io.Files used as a cache of external jars that
- * are known to be existing.
- * Note this cache is kept for the whole session.
- */
- public static HashSet existingExternalFiles = new HashSet();
-
- /**
- * A set of external files ({@link #existingExternalFiles}) which have
- * been confirmed as file (ie. which returns true to {@link java.io.File#isFile()}.
- * Note this cache is kept for the whole session.
- */
- public static HashSet existingExternalConfirmedFiles = new HashSet();
-
-/**
- * Constructs a new Java Model on the given workspace.
- * Note that only one instance of JavaModel handle should ever be created.
- * One should only indirect through JavaModelManager#getJavaModel() to get
- * access to it.
- *
- * @exception Error if called more than once
- */
-protected JavaModel() throws Error {
- super(null);
-}
-protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) /*throws JavaScriptModelException*/ {
-
- // determine my children
- IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
- int length = projects.length;
- IJavaScriptElement[] children = new IJavaScriptElement[length];
- int index = 0;
- for (int i = 0; i < length; i++) {
- IProject project = projects[i];
- if (JavaProject.hasJavaNature(project)) {
- children[index++] = getJavaProject(project);
- }
- }
- if (index < length)
- System.arraycopy(children, 0, children = new IJavaScriptElement[index], 0, index);
- info.setChildren(children);
-
- newElements.put(this, info);
-
- return true;
-}
-/*
- * @see IJavaScriptModel
- */
-public boolean contains(IResource resource) {
- switch (resource.getType()) {
- case IResource.ROOT:
- case IResource.PROJECT:
- return true;
- }
- // file or folder
- IJavaScriptProject[] projects;
- try {
- projects = this.getJavaScriptProjects();
- } catch (JavaScriptModelException e) {
- return false;
- }
- for (int i = 0, length = projects.length; i < length; i++) {
- JavaProject project = (JavaProject)projects[i];
- if (!project.contains(resource)) {
- return false;
- }
- }
- return true;
-}
-/**
- * @see IJavaScriptModel
- */
-public void copy(IJavaScriptElement[] elements, IJavaScriptElement[] containers, IJavaScriptElement[] siblings, String[] renamings, boolean force, IProgressMonitor monitor) throws JavaScriptModelException {
- if (elements != null && elements.length > 0 && elements[0] != null && elements[0].getElementType() < IJavaScriptElement.TYPE) {
- runOperation(new CopyResourceElementsOperation(elements, containers, force), elements, siblings, renamings, monitor);
- } else {
- runOperation(new CopyElementsOperation(elements, containers, force), elements, siblings, renamings, monitor);
- }
-}
-/**
- * Returns a new element info for this element.
- */
-protected Object createElementInfo() {
- return new JavaModelInfo();
-}
-
-/**
- * @see IJavaScriptModel
- */
-public void delete(IJavaScriptElement[] elements, boolean force, IProgressMonitor monitor) throws JavaScriptModelException {
- if (elements != null && elements.length > 0 && elements[0] != null && elements[0].getElementType() < IJavaScriptElement.TYPE) {
- new DeleteResourceElementsOperation(elements, force).runOperation(monitor);
- } else {
- new DeleteElementsOperation(elements, force).runOperation(monitor);
- }
-}
-public boolean equals(Object o) {
- if (!(o instanceof JavaModel)) return false;
- return super.equals(o);
-}
-/**
- * @see IJavaScriptElement
- */
-public int getElementType() {
- return JAVASCRIPT_MODEL;
-}
-/**
- * Flushes the cache of external files known to be existing.
- */
-public static void flushExternalFileCache() {
- existingExternalFiles = new HashSet();
- existingExternalConfirmedFiles = new HashSet();
-}
-
-/*
- * @see JavaElement
- */
-public IJavaScriptElement getHandleFromMemento(String token, MementoTokenizer memento, WorkingCopyOwner owner) {
- switch (token.charAt(0)) {
- case JEM_JAVAPROJECT:
- if (!memento.hasMoreTokens()) return this;
- String projectName = memento.nextToken();
- JavaElement project = (JavaElement)getJavaScriptProject(projectName);
- return project.getHandleFromMemento(memento, owner);
- }
- return null;
-}
-/**
- * @see JavaElement#getHandleMemento(StringBuffer)
- */
-protected void getHandleMemento(StringBuffer buff) {
- buff.append(getElementName());
-}
-/**
- * Returns the <code>char</code> that marks the start of this handles
- * contribution to a memento.
- */
-protected char getHandleMementoDelimiter(){
- Assert.isTrue(false, "Should not be called"); //$NON-NLS-1$
- return 0;
-}
-/**
- * @see IJavaScriptModel
- */
-public IJavaScriptProject getJavaScriptProject(String projectName) {
- return new JavaProject(ResourcesPlugin.getWorkspace().getRoot().getProject(projectName), this);
-}
-/**
- * Returns the active Java project associated with the specified
- * resource, or <code>null</code> if no Java project yet exists
- * for the resource.
- *
- * @exception IllegalArgumentException if the given resource
- * is not one of an IProject, IFolder, or IFile.
- */
-public IJavaScriptProject getJavaProject(IResource resource) {
- switch(resource.getType()){
- case IResource.FOLDER:
- return new JavaProject(((IFolder)resource).getProject(), this);
- case IResource.FILE:
- return new JavaProject(((IFile)resource).getProject(), this);
- case IResource.PROJECT:
- return new JavaProject((IProject)resource, this);
- default:
- throw new IllegalArgumentException(Messages.element_invalidResourceForProject);
- }
-}
-/**
- * @see IJavaScriptModel
- */
-public IJavaScriptProject[] getJavaScriptProjects() throws JavaScriptModelException {
- ArrayList list = getChildrenOfType(JAVASCRIPT_PROJECT);
- IJavaScriptProject[] array= new IJavaScriptProject[list.size()];
- list.toArray(array);
- return array;
-
-}
-/**
- * @see IJavaScriptModel
- */
-public Object[] getNonJavaScriptResources() throws JavaScriptModelException {
- return ((JavaModelInfo) getElementInfo()).getNonJavaResources();
-}
-
-/*
- * @see IJavaScriptElement
- */
-public IPath getPath() {
- return Path.ROOT;
-}
-/*
- * @see IJavaScriptElement
- */
-public IResource getResource() {
- return ResourcesPlugin.getWorkspace().getRoot();
-}
-/**
- * @see org.eclipse.wst.jsdt.core.IOpenable
- */
-public IResource getUnderlyingResource() {
- return null;
-}
-/**
- * Returns the workbench associated with this object.
- */
-public IWorkspace getWorkspace() {
- return ResourcesPlugin.getWorkspace();
-}
-
-/**
- * @see IJavaScriptModel
- */
-public void move(IJavaScriptElement[] elements, IJavaScriptElement[] containers, IJavaScriptElement[] siblings, String[] renamings, boolean force, IProgressMonitor monitor) throws JavaScriptModelException {
- if (elements != null && elements.length > 0 && elements[0] != null && elements[0].getElementType() < IJavaScriptElement.TYPE) {
- runOperation(new MoveResourceElementsOperation(elements, containers, force), elements, siblings, renamings, monitor);
- } else {
- runOperation(new MoveElementsOperation(elements, containers, force), elements, siblings, renamings, monitor);
- }
-}
-
-/**
- * @see IJavaScriptModel#refreshExternalArchives(IJavaScriptElement[], IProgressMonitor)
- */
-public void refreshExternalArchives(IJavaScriptElement[] elementsScope, IProgressMonitor monitor) throws JavaScriptModelException {
- if (elementsScope == null){
- elementsScope = new IJavaScriptElement[] { this };
- }
- JavaModelManager.getJavaModelManager().getDeltaProcessor().checkExternalArchiveChanges(elementsScope, monitor);
-}
-
-/**
- * @see IJavaScriptModel
- */
-public void rename(IJavaScriptElement[] elements, IJavaScriptElement[] destinations, String[] renamings, boolean force, IProgressMonitor monitor) throws JavaScriptModelException {
- MultiOperation op;
- if (elements != null && elements.length > 0 && elements[0] != null && elements[0].getElementType() < IJavaScriptElement.TYPE) {
- op = new RenameResourceElementsOperation(elements, destinations, renamings, force);
- } else {
- op = new RenameElementsOperation(elements, destinations, renamings, force);
- }
-
- op.runOperation(monitor);
-}
-/**
- * Configures and runs the <code>MultiOperation</code>.
- */
-protected void runOperation(MultiOperation op, IJavaScriptElement[] elements, IJavaScriptElement[] siblings, String[] renamings, IProgressMonitor monitor) throws JavaScriptModelException {
- op.setRenamings(renamings);
- if (siblings != null) {
- for (int i = 0; i < elements.length; i++) {
- op.setInsertBefore(elements[i], siblings[i]);
- }
- }
- op.runOperation(monitor);
-}
-/**
- * @private Debugging purposes
- */
-protected void toStringInfo(int tab, StringBuffer buffer, Object info, boolean showResolvedInfo) {
- buffer.append(this.tabString(tab));
- buffer.append("Java Model"); //$NON-NLS-1$
- if (info == null) {
- buffer.append(" (not open)"); //$NON-NLS-1$
- }
-}
-
-/**
- * Helper method - returns the targeted item (IResource if internal or java.io.File if external),
- * or null if unbound
- * Internal items must be referred to using container relative paths.
- */
-public static Object getTarget(IContainer container, IPath path, boolean checkResourceExistence) {
-
- if (path == null) return null;
-
- // lookup - inside the container
- if (path.getDevice() == null) { // container relative paths should not contain a device
- // (see http://dev.eclipse.org/bugs/show_bug.cgi?id=18684)
- // (case of a workspace rooted at d:\ )
- IResource resource = container.findMember(path);
- if (resource != null){
- if (!checkResourceExistence ||resource.exists()) return resource;
- return null;
- }
- }
-
- // if path is relative, it cannot be an external path
- // (see http://dev.eclipse.org/bugs/show_bug.cgi?id=22517)
- if (!path.isAbsolute()) return null;
-
- // lookup - outside the container
- return getTargetAsExternalFile(path, checkResourceExistence);
-}
-private synchronized static Object getTargetAsExternalFile(IPath path, boolean checkResourceExistence) {
- File externalFile = new File(path.toOSString());
- if (!checkResourceExistence) {
- return externalFile;
- } else if (existingExternalFiles.contains(externalFile)) {
- return externalFile;
- } else {
- if (JavaModelManager.ZIP_ACCESS_VERBOSE) {
- System.out.println("(" + Thread.currentThread() + ") [JavaModel.getTarget(...)] Checking existence of " + path.toString()); //$NON-NLS-1$ //$NON-NLS-2$
- }
- if (externalFile.exists()) {
- // cache external file
- existingExternalFiles.add(externalFile);
- return externalFile;
- }
- }
- return null;
-}
-
-/**
- * Helper method - returns whether an object is afile (ie. which returns true to {@link java.io.File#isFile()}.
- */
-public static boolean isFile(Object target) {
- return getFile(target) != null;
-}
-
-/**
- * Helper method - returns the file item (ie. which returns true to {@link java.io.File#isFile()},
- * or null if unbound
- */
-public static synchronized File getFile(Object target) {
- if (existingExternalConfirmedFiles.contains(target))
- return (File) target;
- if (target instanceof File) {
- File f = (File) target;
-// if (f.isFile()) {
- if (f.exists()) {
- existingExternalConfirmedFiles.add(f);
- return f;
- }
- }
-
- return null;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaModelCache.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaModelCache.java
deleted file mode 100644
index 6b20c405..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaModelCache.java
+++ /dev/null
@@ -1,236 +0,0 @@
-/*******************************************************************************
- * 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 java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.core.util.LRUCache;
-
-/**
- * The cache of java elements to their respective info.
- */
-public class JavaModelCache {
- public static boolean VERBOSE = false;
-
- public static final int DEFAULT_PROJECT_SIZE = 5; // average 25552 bytes per project.
- public static final int DEFAULT_ROOT_SIZE = 50; // average 2590 bytes per root -> maximum size : 25900*BASE_VALUE bytes
- public static final int DEFAULT_PKG_SIZE = 500; // average 1782 bytes per pkg -> maximum size : 178200*BASE_VALUE bytes
- public static final int DEFAULT_OPENABLE_SIZE = 500; // average 6629 bytes per openable (includes children) -> maximum size : 662900*BASE_VALUE bytes
- public static final int DEFAULT_CHILDREN_SIZE = 500*20; // average 20 children per openable
-
- public static final Object NON_EXISTING_JAR_TYPE_INFO = new Object();
-
- /*
- * The memory ratio that should be applied to the above constants.
- */
- protected double memoryRatio = -1;
-
- /**
- * Active Java Model Info
- */
- protected JavaModelInfo modelInfo;
-
- /**
- * Cache of open projects.
- */
- protected HashMap projectCache;
-
- /**
- * Cache of open package fragment roots.
- */
- protected ElementCache rootCache;
-
- /**
- * Cache of open package fragments
- */
- protected ElementCache pkgCache;
-
- /**
- * Cache of open compilation unit and class files
- */
- protected ElementCache openableCache;
-
- /**
- * Cache of open children of openable Java Model Java elements
- */
- protected Map childrenCache;
-
- /*
- * Cache of open binary type (inside a jar) that have a non-open parent
- */
- protected LRUCache jarTypeCache;
-
-public JavaModelCache() {
- // set the size of the caches in function of the maximum amount of memory available
- double ratio = getMemoryRatio();
- this.projectCache = new HashMap(DEFAULT_PROJECT_SIZE); // NB: Don't use a LRUCache for projects as they are constantly reopened (e.g. during delta processing)
- if (VERBOSE) {
- this.rootCache = new VerboseElementCache((int) (DEFAULT_ROOT_SIZE * ratio), "Root cache"); //$NON-NLS-1$
- this.pkgCache = new VerboseElementCache((int) (DEFAULT_PKG_SIZE * ratio), "Package cache"); //$NON-NLS-1$
- this.openableCache = new VerboseElementCache((int) (DEFAULT_OPENABLE_SIZE * ratio), "Openable cache"); //$NON-NLS-1$
- } else {
- this.rootCache = new ElementCache((int) (DEFAULT_ROOT_SIZE * ratio));
- this.pkgCache = new ElementCache((int) (DEFAULT_PKG_SIZE * ratio));
- this.openableCache = new ElementCache((int) (DEFAULT_OPENABLE_SIZE * ratio));
- }
- this.childrenCache = new HashMap((int) (DEFAULT_CHILDREN_SIZE * ratio));
- resetJarTypeCache();
-}
-
-/**
- * Returns the info for the element.
- */
-public Object getInfo(IJavaScriptElement element) {
- switch (element.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_MODEL:
- return this.modelInfo;
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- return this.projectCache.get(element);
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- return this.rootCache.get(element);
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- return this.pkgCache.get(element);
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- case IJavaScriptElement.CLASS_FILE:
- return this.openableCache.get(element);
- case IJavaScriptElement.TYPE:
- Object result = this.jarTypeCache.get(element);
- if (result != null)
- return result;
- else
- return this.childrenCache.get(element);
- default:
- return this.childrenCache.get(element);
- }
-}
-
-protected double getMemoryRatio() {
- if (this.memoryRatio == -1) {
- long maxMemory = Runtime.getRuntime().maxMemory();
- // if max memory is infinite, set the ratio to 4d which corresponds to the 256MB that Eclipse defaults to
- // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=111299)
- this.memoryRatio = maxMemory == Long.MAX_VALUE ? 4d : ((double) maxMemory) / (64 * 0x100000); // 64MB is the base memory for most JVM
- }
- return this.memoryRatio;
-}
-
-/**
- * Returns the info for this element without
- * disturbing the cache ordering.
- */
-protected Object peekAtInfo(IJavaScriptElement element) {
- switch (element.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_MODEL:
- return this.modelInfo;
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- return this.projectCache.get(element);
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- return this.rootCache.peek(element);
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- return this.pkgCache.peek(element);
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- case IJavaScriptElement.CLASS_FILE:
- return this.openableCache.peek(element);
- case IJavaScriptElement.TYPE:
- Object result = this.jarTypeCache.peek(element);
- if (result != null)
- return result;
- else
- return this.childrenCache.get(element);
- default:
- return this.childrenCache.get(element);
- }
-}
-
-/**
- * Remember the info for the element.
- */
-protected void putInfo(IJavaScriptElement element, Object info) {
- switch (element.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_MODEL:
- this.modelInfo = (JavaModelInfo) info;
- break;
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- this.projectCache.put(element, info);
- this.rootCache.ensureSpaceLimit(((JavaElementInfo) info).children.length, element);
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- this.rootCache.put(element, info);
- this.pkgCache.ensureSpaceLimit(((JavaElementInfo) info).children.length, element);
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- this.pkgCache.put(element, info);
- this.openableCache.ensureSpaceLimit(((JavaElementInfo) info).children.length, element);
- break;
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- case IJavaScriptElement.CLASS_FILE:
- this.openableCache.put(element, info);
- break;
- default:
- this.childrenCache.put(element, info);
- }
-}
-/**
- * Removes the info of the element from the cache.
- */
-protected void removeInfo(JavaElement element) {
- switch (element.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_MODEL:
- this.modelInfo = null;
- break;
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- this.projectCache.remove(element);
- this.rootCache.resetSpaceLimit((int) (DEFAULT_ROOT_SIZE * getMemoryRatio()), element);
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- this.rootCache.remove(element);
- this.pkgCache.resetSpaceLimit((int) (DEFAULT_PKG_SIZE * getMemoryRatio()), element);
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- this.pkgCache.remove(element);
- this.openableCache.resetSpaceLimit((int) (DEFAULT_OPENABLE_SIZE * getMemoryRatio()), element);
- break;
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- case IJavaScriptElement.CLASS_FILE:
- this.openableCache.remove(element);
- break;
- default:
- this.childrenCache.remove(element);
- }
-}
-protected void resetJarTypeCache() {
- this.jarTypeCache = new LRUCache((int) (DEFAULT_OPENABLE_SIZE * getMemoryRatio()));
-}
-public String toString() {
- return toStringFillingRation(""); //$NON-NLS-1$
-}
-public String toStringFillingRation(String prefix) {
- StringBuffer buffer = new StringBuffer();
- buffer.append(prefix);
- buffer.append("Project cache: "); //$NON-NLS-1$
- buffer.append(this.projectCache.size());
- buffer.append(" projects\n"); //$NON-NLS-1$
- buffer.append(prefix);
- buffer.append(this.rootCache.toStringFillingRation("Root cache")); //$NON-NLS-1$
- buffer.append('\n');
- buffer.append(prefix);
- buffer.append(this.pkgCache.toStringFillingRation("Package cache")); //$NON-NLS-1$
- buffer.append('\n');
- buffer.append(prefix);
- buffer.append(this.openableCache.toStringFillingRation("Openable cache")); //$NON-NLS-1$
- buffer.append('\n');
- buffer.append(prefix);
- buffer.append(this.jarTypeCache.toStringFillingRation("Jar type cache")); //$NON-NLS-1$
- buffer.append('\n');
- return buffer.toString();
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaModelInfo.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaModelInfo.java
deleted file mode 100644
index a4851ef2..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaModelInfo.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*******************************************************************************
- * 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.core.resources.IProject;
-import org.eclipse.core.resources.ResourcesPlugin;
-
-/**
- * Implementation of IJavaScriptModel. A Java Model is specific to a
- * workspace.
- *
- * @see org.eclipse.wst.jsdt.core.IJavaScriptModel
- */
-public class JavaModelInfo extends OpenableElementInfo {
-
- /**
- * A array with all the non-java projects contained by this model
- */
- Object[] nonJavaResources;
-
-/**
- * Compute the non-java resources contained in this java project.
- */
-private Object[] computeNonJavaResources() {
- IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
- int length = projects.length;
- Object[] resources = null;
- int index = 0;
- for (int i = 0; i < length; i++) {
- IProject project = projects[i];
- if (!JavaProject.hasJavaNature(project)) {
- if (resources == null) {
- resources = new Object[length];
- }
- resources[index++] = project;
- }
- }
- if (index == 0) return NO_NON_JAVA_RESOURCES;
- if (index < length) {
- System.arraycopy(resources, 0, resources = new Object[index], 0, index);
- }
- return resources;
-}
-
-/**
- * Returns an array of non-java resources contained in the receiver.
- */
-Object[] getNonJavaResources() {
-
- if (this.nonJavaResources == null) {
- this.nonJavaResources = computeNonJavaResources();
- }
- return this.nonJavaResources;
-}
-}
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
deleted file mode 100644
index 8dab98d4..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaModelManager.java
+++ /dev/null
@@ -1,4376 +0,0 @@
-/*******************************************************************************
- * 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
- * Theodora Yeung (tyeung@bea.com) - ensure that JarPackageFragmentRoot make it into cache
- * before its contents
- * (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=102422)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.DataInputStream;
-import java.io.DataOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.StringReader;
-import java.net.URI;
-import java.text.MessageFormat;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-import java.util.WeakHashMap;
-import java.util.Map.Entry;
-import java.util.zip.ZipFile;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceChangeEvent;
-import org.eclipse.core.resources.ISaveContext;
-import org.eclipse.core.resources.ISaveParticipant;
-import org.eclipse.core.resources.ISavedState;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.IWorkspaceDescription;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.AssertionFailedException;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IExtension;
-import org.eclipse.core.runtime.IExtensionPoint;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.ISafeRunnable;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.MultiStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.PerformanceStats;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.Plugin;
-import org.eclipse.core.runtime.Preferences;
-import org.eclipse.core.runtime.QualifiedName;
-import org.eclipse.core.runtime.SafeRunner;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.content.IContentTypeManager.ContentTypeChangeEvent;
-import org.eclipse.core.runtime.content.IContentTypeManager.IContentTypeChangeListener;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.core.runtime.preferences.DefaultScope;
-import org.eclipse.core.runtime.preferences.IEclipsePreferences;
-import org.eclipse.core.runtime.preferences.IPreferencesService;
-import org.eclipse.core.runtime.preferences.IScopeContext;
-import org.eclipse.core.runtime.preferences.InstanceScope;
-import org.eclipse.wst.jsdt.core.IAccessRule;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IIncludePathAttribute;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-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.IJsGlobalScopeContainer;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IParent;
-import org.eclipse.wst.jsdt.core.IProblemRequestor;
-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.JsGlobalScopeContainerInitializer;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-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.internal.codeassist.CompletionEngine;
-import org.eclipse.wst.jsdt.internal.codeassist.SelectionEngine;
-import org.eclipse.wst.jsdt.internal.compiler.Compiler;
-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.impl.CompilerOptions;
-import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfObjectToInt;
-import org.eclipse.wst.jsdt.internal.core.JavaProjectElementInfo.LookupCache;
-import org.eclipse.wst.jsdt.internal.core.builder.JavaBuilder;
-import org.eclipse.wst.jsdt.internal.core.hierarchy.TypeHierarchy;
-import org.eclipse.wst.jsdt.internal.core.search.AbstractSearchScope;
-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.JavaWorkspaceScope;
-import org.eclipse.wst.jsdt.internal.core.search.indexing.IndexManager;
-import org.eclipse.wst.jsdt.internal.core.search.processing.JobManager;
-import org.eclipse.wst.jsdt.internal.core.util.HashtableOfArrayToObject;
-import org.eclipse.wst.jsdt.internal.core.util.LRUCache;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-import org.eclipse.wst.jsdt.internal.core.util.WeakHashSet;
-import org.eclipse.wst.jsdt.internal.core.util.WeakHashSetOfCharArray;
-import org.osgi.service.prefs.BackingStoreException;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-
-/**
- * The <code>JavaModelManager</code> manages instances of <code>IJavaScriptModel</code>.
- * <code>IElementChangedListener</code>s register with the <code>JavaModelManager</code>,
- * and receive <code>ElementChangedEvent</code>s for all <code>IJavaScriptModel</code>s.
- * <p>
- * The single instance of <code>JavaModelManager</code> is available from
- * the static method <code>JavaModelManager.getJavaModelManager()</code>.
- */
-public class JavaModelManager implements ISaveParticipant, IContentTypeChangeListener {
-
- /**
- * Unique handle onto the JavaModel
- */
- final JavaModel javaModel = new JavaModel();
-
- /**
- * Classpath variables pool
- */
- public HashMap variables = new HashMap(5);
- public HashSet variablesWithInitializer = new HashSet(5);
- public HashMap deprecatedVariables = new HashMap(5);
- public HashSet readOnlyVariables = new HashSet(5);
- public HashMap previousSessionVariables = new HashMap(5);
- private ThreadLocal variableInitializationInProgress = new ThreadLocal();
-
- /**
- * Classpath containers pool
- */
- public HashMap containers = new HashMap(5);
- public HashMap previousSessionContainers = new HashMap(5);
- private ThreadLocal containerInitializationInProgress = new ThreadLocal();
- public boolean batchContainerInitializations = false;
- public ThreadLocal batchContainerInitializationsProgress = new ThreadLocal();
- public HashMap containerInitializersCache = new HashMap(5);
-
- /*
- * A HashSet that contains the IJavaScriptProject whose classpath is being resolved.
- */
- private ThreadLocal classpathsBeingResolved = new ThreadLocal();
-
- /*
- * The unique workspace scope
- */
- public JavaWorkspaceScope workspaceScope;
-
- /*
- * Pools of symbols used in the Java model.
- * Used as a replacement for String#intern() that could prevent garbage collection of strings on some VMs.
- */
- private WeakHashSet stringSymbols = new WeakHashSet(5);
- private WeakHashSetOfCharArray charArraySymbols = new WeakHashSetOfCharArray(5);
-
- /*
- * Extension used to construct Java 6 annotation processor managers
- */
- private IConfigurationElement annotationProcessorManagerFactory = null;
-
- /*
- * Map from a package fragment root's path to a source attachment property (source path + ATTACHMENT_PROPERTY_DELIMITER + source root path)
- */
- public Map rootPathToAttachments = new HashMap();
-
- public final static String CP_VARIABLE_PREFERENCES_PREFIX = JavaScriptCore.PLUGIN_ID+".classpathVariable."; //$NON-NLS-1$
- public final static String CP_CONTAINER_PREFERENCES_PREFIX = JavaScriptCore.PLUGIN_ID+".JsGlobalScopeContainer."; //$NON-NLS-1$
- public final static String CP_ENTRY_IGNORE = "##<cp entry ignore>##"; //$NON-NLS-1$
- public final static IPath CP_ENTRY_IGNORE_PATH = new Path(CP_ENTRY_IGNORE);
- public final static String TRUE = "true"; //$NON-NLS-1$
-
- private final static int VARIABLES_AND_CONTAINERS_FILE_VERSION = 2;
-
- /**
- * Name of the extension point for contributing classpath variable initializers
- */
- public static final String CPVARIABLE_INITIALIZER_EXTPOINT_ID = "JsGlobalScopeVariableInitializer" ; //$NON-NLS-1$
-
- /**
- * Name of the extension point for contributing classpath container initializers
- */
- public static final String CPCONTAINER_INITIALIZER_EXTPOINT_ID = "JsGlobalScopeContainerInitializer" ; //$NON-NLS-1$
-
- /**
- * Name of the extension point for contributing a source code formatter
- */
- public static final String FORMATTER_EXTPOINT_ID = "codeFormatter" ; //$NON-NLS-1$
-
- /**
- * Name of the extension point for contributing a compilation participant
- */
- public static final String COMPILATION_PARTICIPANT_EXTPOINT_ID = "validationParticipant" ; //$NON-NLS-1$
-
- /**
- * Name of the extension point for contributing the Java 6 annotation processor manager
- */
- public static final String ANNOTATION_PROCESSOR_MANAGER_EXTPOINT_ID = "annotationProcessorManager" ; //$NON-NLS-1$
-
- /**
- * Special value used for recognizing ongoing initialization and breaking initialization cycles
- */
- public final static IPath VARIABLE_INITIALIZATION_IN_PROGRESS = new Path("Variable Initialization In Progress"); //$NON-NLS-1$
- public final static IJsGlobalScopeContainer CONTAINER_INITIALIZATION_IN_PROGRESS = new IJsGlobalScopeContainer() {
- /**
- * @deprecated Use {@link #getIncludepathEntries()} instead
- */
- public IIncludePathEntry[] getClasspathEntries() {
- return getIncludepathEntries();
- }
- public IIncludePathEntry[] getIncludepathEntries() { return null; }
- public String getDescription() { return "Container Initialization In Progress"; } //$NON-NLS-1$
- public int getKind() { return 0; }
- public IPath getPath() { return null; }
- public String toString() { return getDescription(); }
- public String[] resolvedLibraryImport(String a) {return new String[] {a};}
- };
-
- private static final String BUFFER_MANAGER_DEBUG = JavaScriptCore.PLUGIN_ID + "/debug/buffermanager" ; //$NON-NLS-1$
- private static final String INDEX_MANAGER_DEBUG = JavaScriptCore.PLUGIN_ID + "/debug/indexmanager" ; //$NON-NLS-1$
- private static final String COMPILER_DEBUG = JavaScriptCore.PLUGIN_ID + "/debug/compiler" ; //$NON-NLS-1$
- private static final String JAVAMODEL_DEBUG = JavaScriptCore.PLUGIN_ID + "/debug/javamodel" ; //$NON-NLS-1$
- private static final String JAVAMODELCACHE_DEBUG = JavaScriptCore.PLUGIN_ID + "/debug/javamodel/cache" ; //$NON-NLS-1$
- private static final String CP_RESOLVE_DEBUG = JavaScriptCore.PLUGIN_ID + "/debug/cpresolution" ; //$NON-NLS-1$
- private static final String CP_RESOLVE_ADVANCED_DEBUG = JavaScriptCore.PLUGIN_ID + "/debug/cpresolution/advanced" ; //$NON-NLS-1$
- private static final String ZIP_ACCESS_DEBUG = JavaScriptCore.PLUGIN_ID + "/debug/zipaccess" ; //$NON-NLS-1$
- private static final String DELTA_DEBUG =JavaScriptCore.PLUGIN_ID + "/debug/javadelta" ; //$NON-NLS-1$
- private static final String DELTA_DEBUG_VERBOSE =JavaScriptCore.PLUGIN_ID + "/debug/javadelta/verbose" ; //$NON-NLS-1$
- private static final String HIERARCHY_DEBUG = JavaScriptCore.PLUGIN_ID + "/debug/hierarchy" ; //$NON-NLS-1$
- private static final String POST_ACTION_DEBUG = JavaScriptCore.PLUGIN_ID + "/debug/postaction" ; //$NON-NLS-1$
- private static final String BUILDER_DEBUG = JavaScriptCore.PLUGIN_ID + "/debug/builder" ; //$NON-NLS-1$
- private static final String COMPLETION_DEBUG = JavaScriptCore.PLUGIN_ID + "/debug/completion" ; //$NON-NLS-1$
- private static final String RESOLUTION_DEBUG = JavaScriptCore.PLUGIN_ID + "/debug/resolution" ; //$NON-NLS-1$
- 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$
-
- 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$
- public static final String DELTA_LISTENER_PERF = JavaScriptCore.PLUGIN_ID + "/perf/javadeltalistener" ; //$NON-NLS-1$
- public static final String VARIABLE_INITIALIZER_PERF = JavaScriptCore.PLUGIN_ID + "/perf/variableinitializer" ; //$NON-NLS-1$
- public static final String CONTAINER_INITIALIZER_PERF = JavaScriptCore.PLUGIN_ID + "/perf/containerinitializer" ; //$NON-NLS-1$
- public static final String RECONCILE_PERF = JavaScriptCore.PLUGIN_ID + "/perf/reconcile" ; //$NON-NLS-1$
-
- private final static String INDEXED_SECONDARY_TYPES = "#@*_indexing secondary cache_*@#"; //$NON-NLS-1$
-
- public static boolean PERF_VARIABLE_INITIALIZER = false;
- public static boolean PERF_CONTAINER_INITIALIZER = false;
-
- public final static IJavaScriptUnit[] NO_WORKING_COPY = new IJavaScriptUnit[0];
-
- // Preferences
- HashSet optionNames = new HashSet(20);
- Hashtable optionsCache;
-
- public final IEclipsePreferences[] preferencesLookup = new IEclipsePreferences[2];
- static final int PREF_INSTANCE = 0;
- static final int PREF_DEFAULT = 1;
-
- static final Object[][] NO_PARTICIPANTS = new Object[0][];
-
- public static class validationParticipants {
-
- private final static int MAX_SOURCE_LEVEL = 7; // 1.1 to 1.7
-
- /*
- * The registered compilation participants (a table from int (source level) to Object[])
- * The Object array contains first IConfigurationElements when not resolved yet, then
- * it contains validationParticipants.
- */
- private Object[][] registeredParticipants = null;
- private HashSet managedMarkerTypes;
-
- public ValidationParticipant[] getvalidationParticipants(IJavaScriptProject project) {
- final Object[][] participantsPerSource = getRegisteredParticipants();
- if (participantsPerSource == NO_PARTICIPANTS)
- return null;
- String sourceLevel = project.getOption(JavaScriptCore.COMPILER_SOURCE, true/*inherit options*/);
- final int sourceLevelIndex = indexForSourceLevel(sourceLevel);
- final Object[] participants = participantsPerSource[sourceLevelIndex];
- int length = participants.length;
- ValidationParticipant[] result = new ValidationParticipant[length];
- int index = 0;
- for (int i = 0; i < length; i++) {
- if (participants[i] instanceof IConfigurationElement) {
- final IConfigurationElement configElement = (IConfigurationElement) participants[i];
- final int participantIndex = i;
- SafeRunner.run(new ISafeRunnable() {
- public void handleException(Throwable exception) {
- Util.log(exception, "Exception occurred while creating compilation participant"); //$NON-NLS-1$
- }
- public void run() throws Exception {
- Object executableExtension = configElement.createExecutableExtension("class"); //$NON-NLS-1$
- for (int j = sourceLevelIndex; j < MAX_SOURCE_LEVEL; j++)
- participantsPerSource[j][participantIndex] = executableExtension;
- }
- });
- }
- ValidationParticipant participant = (ValidationParticipant) participants[i];
- if (participant != null && participant.isActive(project))
- result[index++] = participant;
- }
- if (index == 0)
- return null;
- if (index < length)
- System.arraycopy(result, 0, result = new ValidationParticipant[index], 0, index);
- return result;
- }
-
- public HashSet managedMarkerTypes() {
- if (this.managedMarkerTypes == null) {
- // force extension points to be read
- getRegisteredParticipants();
- }
- return this.managedMarkerTypes;
- }
-
- private synchronized Object[][] getRegisteredParticipants() {
- if (this.registeredParticipants != null) {
- return this.registeredParticipants;
- }
- this.managedMarkerTypes = new HashSet();
- IExtensionPoint extension = Platform.getExtensionRegistry().getExtensionPoint(JavaScriptCore.PLUGIN_ID, COMPILATION_PARTICIPANT_EXTPOINT_ID);
- if (extension == null)
- return this.registeredParticipants = NO_PARTICIPANTS;
- final ArrayList modifyingEnv = new ArrayList();
- final ArrayList creatingProblems = new ArrayList();
- final ArrayList others = new ArrayList();
- IExtension[] extensions = extension.getExtensions();
- // for all extensions of this point...
- for(int i = 0; i < extensions.length; i++) {
- IConfigurationElement[] configElements = extensions[i].getConfigurationElements();
- // for all config elements named "validationParticipant"
- for(int j = 0; j < configElements.length; j++) {
- final IConfigurationElement configElement = configElements[j];
- String elementName =configElement.getName();
- if (!("validationParticipant".equals(elementName))) { //$NON-NLS-1$
- continue;
- }
- // add config element in the group it belongs to
- if (TRUE.equals(configElement.getAttribute("modifiesEnvironment"))) //$NON-NLS-1$
- modifyingEnv.add(configElement);
- else if (TRUE.equals(configElement.getAttribute("createsProblems"))) //$NON-NLS-1$
- creatingProblems.add(configElement);
- else
- others.add(configElement);
- // add managed marker types
- IConfigurationElement[] managedMarkers = configElement.getChildren("managedMarker"); //$NON-NLS-1$
- for (int k = 0, length = managedMarkers.length; k < length; k++) {
- IConfigurationElement element = managedMarkers[k];
- String markerType = element.getAttribute("markerType"); //$NON-NLS-1$
- if (markerType != null)
- this.managedMarkerTypes.add(markerType);
- }
- }
- }
- int size = modifyingEnv.size() + creatingProblems.size() + others.size();
- if (size == 0)
- return this.registeredParticipants = NO_PARTICIPANTS;
-
- // sort config elements in each group
- IConfigurationElement[] configElements = new IConfigurationElement[size];
- int index = 0;
- index = sortParticipants(modifyingEnv, configElements, index);
- index = sortParticipants(creatingProblems, configElements, index);
- index = sortParticipants(others, configElements, index);
-
- // create result table
- Object[][] result = new Object[MAX_SOURCE_LEVEL][];
- int length = configElements.length;
- for (int i = 0; i < MAX_SOURCE_LEVEL; i++) {
- result[i] = new Object[length];
- }
- for (int i = 0; i < length; i++) {
- String sourceLevel = configElements[i].getAttribute("requiredSourceLevel"); //$NON-NLS-1$
- int sourceLevelIndex = indexForSourceLevel(sourceLevel);
- for (int j = sourceLevelIndex; j < MAX_SOURCE_LEVEL; j++) {
- result[j][i] = configElements[i];
- }
- }
- return this.registeredParticipants = result;
- }
-
- /*
- * 1.1 -> 0
- * 1.2 -> 1
- * ...
- * 1.6 -> 5
- * 1.7 -> 6
- * null -> 0
- */
- private int indexForSourceLevel(String sourceLevel) {
- if (sourceLevel == null) return 0;
- int majVersion = (int) (CompilerOptions.versionToJdkLevel(sourceLevel) >>> 16);
- switch (majVersion) {
- case ClassFileConstants.MAJOR_VERSION_1_2:
- return 1;
- case ClassFileConstants.MAJOR_VERSION_1_3:
- return 2;
- case ClassFileConstants.MAJOR_VERSION_1_4:
- return 3;
- case ClassFileConstants.MAJOR_VERSION_1_5:
- return 4;
- case ClassFileConstants.MAJOR_VERSION_1_6:
- return 5;
- case ClassFileConstants.MAJOR_VERSION_1_7:
- return 6;
- default:
- // all other cases including ClassFileConstants.MAJOR_VERSION_1_1
- return 0;
- }
- }
-
- private int sortParticipants(ArrayList group, IConfigurationElement[] configElements, int index) {
- int size = group.size();
- if (size == 0) return index;
- Object[] elements = group.toArray();
- Util.sort(elements, new Util.Comparer() {
- public int compare(Object a, Object b) {
- if (a == b) return 0;
- String id = ((IConfigurationElement) a).getAttribute("id"); //$NON-NLS-1$
- if (id == null) return -1;
- IConfigurationElement[] requiredElements = ((IConfigurationElement) b).getChildren("requires"); //$NON-NLS-1$
- for (int i = 0, length = requiredElements.length; i < length; i++) {
- IConfigurationElement required = requiredElements[i];
- if (id.equals(required.getAttribute("id"))) //$NON-NLS-1$
- return 1;
- }
- return -1;
- }
- });
- for (int i = 0; i < size; i++)
- configElements[index+i] = (IConfigurationElement) elements[i];
- return index + size;
- }
- }
-
- public final validationParticipants validationParticipants = new validationParticipants();
-
- public synchronized IJsGlobalScopeContainer containerGet(IJavaScriptProject project, IPath containerPath) {
- // check initialization in progress first
- if (containerIsInitializationInProgress(project, containerPath)) {
- return CONTAINER_INITIALIZATION_IN_PROGRESS;
- }
-
- Map projectContainers = (Map)this.containers.get(project);
- if (projectContainers == null){
- return null;
- }
- IJsGlobalScopeContainer container = (IJsGlobalScopeContainer)projectContainers.get(containerPath);
- return container;
- }
-
- public synchronized IJsGlobalScopeContainer containerGetDefaultToPreviousSession(IJavaScriptProject project, IPath containerPath) {
- Map projectContainers = (Map)this.containers.get(project);
- if (projectContainers == null)
- return getPreviousSessionContainer(containerPath, project);
- IJsGlobalScopeContainer container = (IJsGlobalScopeContainer)projectContainers.get(containerPath);
- if (container == null)
- return getPreviousSessionContainer(containerPath, project);
- return container;
- }
-
- private synchronized Map containerClone(IJavaScriptProject project) {
- Map originalProjectContainers = (Map)this.containers.get(project);
- if (originalProjectContainers == null) return null;
- Map projectContainers = new HashMap(originalProjectContainers.size());
- projectContainers.putAll(originalProjectContainers);
- return projectContainers;
- }
-
- private boolean containerIsInitializationInProgress(IJavaScriptProject project, IPath containerPath) {
- Map initializations = (Map)this.containerInitializationInProgress.get();
- if (initializations == null)
- return false;
- HashSet projectInitializations = (HashSet) initializations.get(project);
- if (projectInitializations == null)
- return false;
- return projectInitializations.contains(containerPath);
- }
-
- private void containerAddInitializationInProgress(IJavaScriptProject project, IPath containerPath) {
- Map initializations = (Map)this.containerInitializationInProgress.get();
- if (initializations == null)
- this.containerInitializationInProgress.set(initializations = new HashMap());
- HashSet projectInitializations = (HashSet) initializations.get(project);
- if (projectInitializations == null)
- initializations.put(project, projectInitializations = new HashSet());
- projectInitializations.add(containerPath);
- }
-
- public synchronized void containerPut(IJavaScriptProject project, IPath containerPath, IJsGlobalScopeContainer container){
-
- // set/unset the initialization in progress
- if (container == CONTAINER_INITIALIZATION_IN_PROGRESS) {
- containerAddInitializationInProgress(project, containerPath);
-
- // do not write out intermediate initialization value
- return;
- } else {
- containerRemoveInitializationInProgress(project, containerPath);
-
- Map projectContainers = (Map)this.containers.get(project);
- if (projectContainers == null){
- projectContainers = new HashMap(1);
- this.containers.put(project, projectContainers);
- }
-
- if (container == null) {
- projectContainers.remove(containerPath);
- } else {
- projectContainers.put(containerPath, container);
- }
- // discard obsoleted information about previous session
- Map previousContainers = (Map)this.previousSessionContainers.get(project);
- if (previousContainers != null){
- previousContainers.remove(containerPath);
- }
- }
- // container values are persisted in preferences during save operations, see #saving(ISaveContext)
- }
-
- /*
- * The given project is being removed. Remove all containers for this project from the cache.
- */
- public synchronized void containerRemove(IJavaScriptProject project) {
- Map initializations = (Map) this.containerInitializationInProgress.get();
- if (initializations != null) {
- initializations.remove(project);
- }
- this.containers.remove(project);
- }
-
- public boolean containerPutIfInitializingWithSameEntries(IPath containerPath, IJavaScriptProject[] projects, IJsGlobalScopeContainer[] respectiveContainers) {
- int projectLength = projects.length;
- if (projectLength != 1)
- return false;
- final IJsGlobalScopeContainer container = respectiveContainers[0];
- IJavaScriptProject project = projects[0];
- // optimize only if initializing, otherwise we are in a regular setContainer(...) call
- if (!containerIsInitializationInProgress(project, containerPath))
- return false;
- IJsGlobalScopeContainer previousContainer = containerGetDefaultToPreviousSession(project, containerPath);
- if (container == null) {
- if (previousContainer == null) {
- containerPut(project, containerPath, null);
- return true;
- }
- return false;
- }
- final IIncludePathEntry[] newEntries = container.getIncludepathEntries();
- if (previousContainer == null)
- if (newEntries.length == 0) {
- containerPut(project, containerPath, container);
- return true;
- } else {
- if (CP_RESOLVE_VERBOSE)
- verbose_missbehaving_container(containerPath, projects, respectiveContainers, container, newEntries, null/*no old entries*/);
- return false;
- }
- final IIncludePathEntry[] oldEntries = previousContainer.getIncludepathEntries();
- if (oldEntries.length != newEntries.length) {
- if (CP_RESOLVE_VERBOSE)
- verbose_missbehaving_container(containerPath, projects, respectiveContainers, container, newEntries, oldEntries);
- return false;
- }
- for (int i = 0, length = newEntries.length; i < length; i++) {
- if (newEntries[i] == null) {
- if (CP_RESOLVE_VERBOSE)
- verbose_missbehaving_container(project, containerPath, newEntries);
- return false;
- }
- if (!newEntries[i].equals(oldEntries[i])) {
- if (CP_RESOLVE_VERBOSE)
- verbose_missbehaving_container(containerPath, projects, respectiveContainers, container, newEntries, oldEntries);
- return false;
- }
- }
- containerPut(project, containerPath, container);
- return true;
- }
-
- private void verbose_missbehaving_container(
- IPath containerPath,
- IJavaScriptProject[] projects,
- IJsGlobalScopeContainer[] respectiveContainers,
- final IJsGlobalScopeContainer container,
- final IIncludePathEntry[] newEntries,
- final IIncludePathEntry[] oldEntries) {
- Util.verbose(
- "CPContainer SET - missbehaving container\n" + //$NON-NLS-1$
- " container path: " + containerPath + '\n' + //$NON-NLS-1$
- " projects: {" +//$NON-NLS-1$
- org.eclipse.wst.jsdt.internal.compiler.util.Util.toString(
- projects,
- new org.eclipse.wst.jsdt.internal.compiler.util.Util.Displayable(){
- public String displayString(Object o) { return ((IJavaScriptProject) o).getElementName(); }
- }) +
- "}\n values on previous session: {\n" +//$NON-NLS-1$
- org.eclipse.wst.jsdt.internal.compiler.util.Util.toString(
- respectiveContainers,
- new org.eclipse.wst.jsdt.internal.compiler.util.Util.Displayable(){
- public String displayString(Object o) {
- StringBuffer buffer = new StringBuffer(" "); //$NON-NLS-1$
- if (o == null) {
- buffer.append("<null>"); //$NON-NLS-1$
- return buffer.toString();
- }
- buffer.append(container.getDescription());
- buffer.append(" {\n"); //$NON-NLS-1$
- if (oldEntries == null) {
- buffer.append(" "); //$NON-NLS-1$
- buffer.append("<null>\n"); //$NON-NLS-1$
- } else {
- for (int j = 0; j < oldEntries.length; j++){
- buffer.append(" "); //$NON-NLS-1$
- buffer.append(oldEntries[j]);
- buffer.append('\n');
- }
- }
- buffer.append(" }"); //$NON-NLS-1$
- return buffer.toString();
- }
- }) +
- "}\n new values: {\n" +//$NON-NLS-1$
- org.eclipse.wst.jsdt.internal.compiler.util.Util.toString(
- respectiveContainers,
- new org.eclipse.wst.jsdt.internal.compiler.util.Util.Displayable(){
- public String displayString(Object o) {
- StringBuffer buffer = new StringBuffer(" "); //$NON-NLS-1$
- if (o == null) {
- buffer.append("<null>"); //$NON-NLS-1$
- return buffer.toString();
- }
- buffer.append(container.getDescription());
- buffer.append(" {\n"); //$NON-NLS-1$
- for (int j = 0; j < newEntries.length; j++){
- buffer.append(" "); //$NON-NLS-1$
- buffer.append(newEntries[j]);
- buffer.append('\n');
- }
- buffer.append(" }"); //$NON-NLS-1$
- return buffer.toString();
- }
- }) +
- "\n }"); //$NON-NLS-1$
- }
-
- void verbose_missbehaving_container(IJavaScriptProject project, IPath containerPath, IIncludePathEntry[] classpathEntries) {
- Util.verbose(
- "CPContainer GET - missbehaving container (returning null classpath entry)\n" + //$NON-NLS-1$
- " project: " + project.getElementName() + '\n' + //$NON-NLS-1$
- " container path: " + containerPath + '\n' + //$NON-NLS-1$
- " classpath entries: {\n" + //$NON-NLS-1$
- org.eclipse.wst.jsdt.internal.compiler.util.Util.toString(
- classpathEntries,
- new org.eclipse.wst.jsdt.internal.compiler.util.Util.Displayable(){
- public String displayString(Object o) {
- StringBuffer buffer = new StringBuffer(" "); //$NON-NLS-1$
- if (o == null) {
- buffer.append("<null>"); //$NON-NLS-1$
- return buffer.toString();
- }
- buffer.append(o);
- return buffer.toString();
- }
- }) +
- "\n }" //$NON-NLS-1$
- );
- }
-
- private void containerRemoveInitializationInProgress(IJavaScriptProject project, IPath containerPath) {
- Map initializations = (Map)this.containerInitializationInProgress.get();
- if (initializations == null)
- return;
- HashSet projectInitializations = (HashSet) initializations.get(project);
- if (projectInitializations == null)
- return;
- projectInitializations.remove(containerPath);
- if (projectInitializations.size() == 0)
- initializations.remove(project);
- if (initializations.size() == 0)
- this.containerInitializationInProgress.set(null);
- }
-
- private synchronized void containersReset(String[] containerIDs) {
- for (int i = 0; i < containerIDs.length; i++) {
- String containerID = containerIDs[i];
- Iterator projectIterator = this.containers.values().iterator();
- while (projectIterator.hasNext()){
- Map projectContainers = (Map) projectIterator.next();
- if (projectContainers != null){
- Iterator containerIterator = projectContainers.keySet().iterator();
- while (containerIterator.hasNext()){
- IPath containerPath = (IPath)containerIterator.next();
- if (containerPath.segment(0).equals(containerID)) { // registered container
- projectContainers.put(containerPath, null); // reset container value, but leave entry in Map
- }
- }
- }
- }
- }
- }
-
- /**
- * Returns the Java element corresponding to the given resource, or
- * <code>null</code> if unable to associate the given resource
- * with a Java element.
- * <p>
- * The resource must be one of:<ul>
- * <li>a project - the element returned is the corresponding <code>IJavaScriptProject</code></li>
- * <li>a <code>.js</code> file - the element returned is the corresponding <code>IJavaScriptUnit</code></li>
- * <li>a <code>.class</code> file - the element returned is the corresponding <code>IClassFile</code></li>
- * <li>a <code>.jar</code> file - the element returned is the corresponding <code>IPackageFragmentRoot</code></li>
- * <li>a folder - the element returned is the corresponding <code>IPackageFragmentRoot</code>
- * or <code>IPackageFragment</code></li>
- * <li>the workspace root resource - the element returned is the <code>IJavaScriptModel</code></li>
- * </ul>
- * <p>
- * Creating a Java element has the side effect of creating and opening all of the
- * element's parents if they are not yet open.
- */
- public static IJavaScriptElement create(IResource resource, IJavaScriptProject project) {
- if (resource == null) {
- return null;
- }
- int type = resource.getType();
- switch (type) {
- case IResource.PROJECT :
- return JavaScriptCore.create((IProject) resource);
- case IResource.FILE :
- return create((IFile) resource, project);
- case IResource.FOLDER :
- return create((IFolder) resource, project);
- case IResource.ROOT :
- return JavaScriptCore.create((IWorkspaceRoot) resource);
- default :
- return null;
- }
- }
-
- /**
- * Returns the Java element corresponding to the given file, its project being the given
- * project.
- * Returns <code>null</code> if unable to associate the given file
- * with a Java element.
- *
- * <p>The file must be one of:<ul>
- * <li>a <code>.js</code> file - the element returned is the corresponding <code>IJavaScriptUnit</code></li>
- * <li>a <code>.class</code> file - the element returned is the corresponding <code>IClassFile</code></li>
- * <li>a <code>.jar</code> file - the element returned is the corresponding <code>IPackageFragmentRoot</code></li>
- * </ul>
- * <p>
- * Creating a Java element has the side effect of creating and opening all of the
- * element's parents if they are not yet open.
- */
- public static IJavaScriptElement create(IFile file, IJavaScriptProject project) {
- if (file == null) {
- return null;
- }
- if (project == null) {
- project = JavaScriptCore.create(file.getProject());
- }
-
- if (file.getFileExtension() != null) {
- String name = file.getName();
- if (org.eclipse.wst.jsdt.internal.core.util.Util.isJavaLikeFileName(name))
- return createCompilationUnitFrom(file, project);
- if (org.eclipse.wst.jsdt.internal.compiler.util.Util.isClassFileName(name))
- return createClassFileFrom(file, project);
- if (org.eclipse.wst.jsdt.internal.compiler.util.Util.isArchiveFileName(name))
- return createJarPackageFragmentRootFrom(file, project);
- }
- return null;
- }
-
- /**
- * Returns the package fragment or package fragment root corresponding to the given folder,
- * its parent or great parent being the given project.
- * or <code>null</code> if unable to associate the given folder with a Java element.
- * <p>
- * Note that a package fragment root is returned rather than a default package.
- * <p>
- * Creating a Java element has the side effect of creating and opening all of the
- * element's parents if they are not yet open.
- */
- public static IJavaScriptElement create(IFolder folder, IJavaScriptProject project) {
- if (folder == null) {
- return null;
- }
- IJavaScriptElement element;
- if (project == null) {
- project = JavaScriptCore.create(folder.getProject());
- element = determineIfOnClasspath(folder, project);
- if (element == null) {
- // walk all projects and find one that have the given folder on its classpath
- IJavaScriptProject[] projects;
- try {
- projects = JavaModelManager.getJavaModelManager().getJavaModel().getJavaScriptProjects();
- } catch (JavaScriptModelException e) {
- return null;
- }
- for (int i = 0, length = projects.length; i < length; i++) {
- project = projects[i];
- element = determineIfOnClasspath(folder, project);
- if (element != null)
- break;
- }
- }
- } else {
- element = determineIfOnClasspath(folder, project);
- }
- return element;
- }
-
- /**
- * Creates and returns a class file element for the given <code>.class</code> file,
- * its project being the given project. Returns <code>null</code> if unable
- * to recognize the class file.
- */
- public static IClassFile createClassFileFrom(IFile file, IJavaScriptProject project ) {
- if (file == null) {
- return null;
- }
- if (project == null) {
- project = JavaScriptCore.create(file.getProject());
- }
- IPackageFragment pkg = (IPackageFragment) determineIfOnClasspath(file, project);
- if (pkg == null) {
- // fix for 1FVS7WE
- // not on classpath - make the root its folder, and a default package
- PackageFragmentRoot root = (PackageFragmentRoot) project.getPackageFragmentRoot(file.getParent());
- pkg = root.getPackageFragment(CharOperation.NO_STRINGS);
- }
- return pkg.getClassFile(file.getName());
- }
-
- /**
- * Creates and returns a compilation unit element for the given <code>.java</code>
- * file, its project being the given project. Returns <code>null</code> if unable
- * to recognize the compilation unit.
- */
- public static IJavaScriptUnit createCompilationUnitFrom(IFile file, IJavaScriptProject project) {
-
- if (file == null) return null;
-
- if (project == null) {
- project = JavaScriptCore.create(file.getProject());
- }
- IPackageFragment pkg = (IPackageFragment) determineIfOnClasspath(file, project);
- if (pkg == null) {
- // not on classpath - make the root its folder, and a default package
- IPackageFragmentRoot root = project.getPackageFragmentRoot(file.getParent());
- pkg = root.getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME);
-
- if (VERBOSE){
- System.out.println("WARNING : creating unit element outside classpath ("+ Thread.currentThread()+"): " + file.getFullPath()); //$NON-NLS-1$//$NON-NLS-2$
- }
- }
- return pkg.getJavaScriptUnit(file.getName());
- }
-
- /**
- * Creates and returns a handle for the given JAR file, its project being the given project.
- * The Java model associated with the JAR's project may be
- * created as a side effect.
- * Returns <code>null</code> if unable to create a JAR package fragment root.
- * (for example, if the JAR file represents a non-Java resource)
- */
- public static IPackageFragmentRoot createJarPackageFragmentRootFrom(IFile file, IJavaScriptProject project) {
- if (file == null) {
- return null;
- }
- if (project == null) {
- project = JavaScriptCore.create(file.getProject());
- }
-
- // Create a jar package fragment root only if on the classpath
- IPath resourcePath = file.getFullPath();
- try {
- IIncludePathEntry entry = ((JavaProject)project).getClasspathEntryFor(resourcePath);
- if (entry != null) {
- return project.getPackageFragmentRoot(file);
- }
- } catch (JavaScriptModelException e) {
- // project doesn't exist: return null
- }
- return null;
- }
-
- /**
- * Returns the package fragment root represented by the resource, or
- * the package fragment the given resource is located in, or <code>null</code>
- * if the given resource is not on the classpath of the given project.
- */
- public static IJavaScriptElement determineIfOnClasspath(
- IResource resource,
- IJavaScriptProject project) {
-
- IPath resourcePath = resource.getFullPath();
- try {
- JavaProjectElementInfo projectInfo = (JavaProjectElementInfo) getJavaModelManager().getInfo(project);
- LookupCache projectCache = projectInfo == null ? null : projectInfo.projectCache;
- HashtableOfArrayToObject allPkgFragmentsCache = projectCache == null ? null : projectCache.allPkgFragmentsCache;
- IIncludePathEntry[] entries = ((JavaProject)project).getResolvedClasspath();
-
- int length = entries.length;
- if (length > 0) {
- String sourceLevel = project.getOption(JavaScriptCore.COMPILER_SOURCE, true);
- String complianceLevel = project.getOption(JavaScriptCore.COMPILER_COMPLIANCE, true);
- for (int i = 0; i < length; i++) {
- IIncludePathEntry entry = entries[i];
- if (entry.getEntryKind() == IIncludePathEntry.CPE_PROJECT) continue;
- IPath rootPath = entry.getPath();
- if (rootPath.equals(resourcePath)) {
- return project.getPackageFragmentRoot(resource);
- } else if (rootPath.isPrefixOf(resourcePath)) {
- // allow creation of package fragment if it contains a .js file that is included
- if (!Util.isExcluded(resource, ((ClasspathEntry)entry).fullInclusionPatternChars(), ((ClasspathEntry)entry).fullExclusionPatternChars())) {
- // given we have a resource child of the root, it cannot be a JAR pkg root
- PackageFragmentRoot root =(PackageFragmentRoot) ((JavaProject) project).getFolderPackageFragmentRoot(rootPath);
- if (root == null) return null;
- IPath pkgPath = resourcePath.removeFirstSegments(rootPath.segmentCount());
-
- if (resource.getType() == IResource.FILE) {
- // if the resource is a file, then remove the last segment which
- // is the file name in the package
- pkgPath = pkgPath.removeLastSegments(1);
- }
- String[] pkgName = pkgPath.segments();
-
- // if package name is in the cache, then it has already been validated
- // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=133141)
- if (allPkgFragmentsCache != null && allPkgFragmentsCache.containsKey(pkgName))
- return root.getPackageFragment(pkgName);
-
- if (pkgName.length != 0 && JavaScriptConventions.validatePackageName(Util.packageName(pkgPath, sourceLevel, complianceLevel), sourceLevel, complianceLevel).getSeverity() == IStatus.ERROR) {
- return null;
- }
- return root.getPackageFragment(pkgName);
- }
- }
- }
- }
- } catch (JavaScriptModelException npe) {
- return null;
- }
- return null;
- }
-
- /**
- * The singleton manager
- */
- private static JavaModelManager MANAGER= new JavaModelManager();
-
- /**
- * Infos cache.
- */
- private JavaModelCache cache;
-
- /*
- * Temporary cache of newly opened elements
- */
- private ThreadLocal temporaryCache = new ThreadLocal();
-
- /**
- * Set of elements which are out of sync with their buffers.
- */
- protected HashSet elementsOutOfSynchWithBuffers = new HashSet(11);
-
- /**
- * Holds the state used for delta processing.
- */
- public DeltaProcessingState deltaState = new DeltaProcessingState();
-
- public IndexManager indexManager = null;
-
- /**
- * Table from IProject to PerProjectInfo.
- * NOTE: this object itself is used as a lock to synchronize creation/removal of per project infos
- */
- protected Map perProjectInfos = new HashMap(5);
-
- /**
- * Table from WorkingCopyOwner to a table of IJavaScriptUnit (working copy handle) to PerWorkingCopyInfo.
- * NOTE: this object itself is used as a lock to synchronize creation/removal of per working copy infos
- */
- protected Map perWorkingCopyInfos = new HashMap(5);
-
- /**
- * A weak set of the known search scopes.
- */
- protected WeakHashMap searchScopes = new WeakHashMap();
-
- public static class PerProjectInfo {
- private static final int JAVADOC_CACHE_INITIAL_SIZE = 10;
-
- public IProject project;
- public Object savedState;
- public boolean triedRead;
- public IIncludePathEntry[] rawClasspath;
- public IJavaScriptModelStatus rawClasspathStatus;
- public IIncludePathEntry[] resolvedClasspath;
- public IJavaScriptModelStatus unresolvedEntryStatus;
- public Map rootPathToRawEntries; // reverse map from a package fragment root's path to the raw entry
- public Map rootPathToResolvedEntries; // map from a package fragment root's path to the resolved entry
- public IPath outputLocation;
-
- public IEclipsePreferences preferences;
- public Hashtable options;
- public Hashtable secondaryTypes;
- public LRUCache javadocCache;
-
- public PerProjectInfo(IProject project) {
-
- this.triedRead = false;
- this.savedState = null;
- this.project = project;
- this.javadocCache = new LRUCache(JAVADOC_CACHE_INITIAL_SIZE);
- }
-
- public void rememberExternalLibTimestamps() {
- IIncludePathEntry[] classpath = this.resolvedClasspath;
- if (classpath == null) return;
- IWorkspaceRoot wRoot = ResourcesPlugin.getWorkspace().getRoot();
- Map externalTimeStamps = JavaModelManager.getJavaModelManager().deltaState.getExternalLibTimeStamps();
- for (int i = 0, length = classpath.length; i < length; i++) {
- IIncludePathEntry entry = classpath[i];
- if (entry.getEntryKind() == IIncludePathEntry.CPE_LIBRARY) {
- IPath path = entry.getPath();
- if (externalTimeStamps.get(path) == null) {
- Object target = JavaModel.getTarget(wRoot, path, true);
- if (target instanceof java.io.File) {
- long timestamp = DeltaProcessor.getTimeStamp((java.io.File)target);
- externalTimeStamps.put(path, new Long(timestamp));
- }
- }
- }
- }
- }
-
- public synchronized void resetResolvedClasspath() {
- // null out resolved information
- setClasspath(this.rawClasspath, this.outputLocation, this.rawClasspathStatus, null, null, null, null);
- }
-
- public synchronized void setClasspath(IIncludePathEntry[] newRawClasspath, IPath newOutputLocation, IJavaScriptModelStatus newRawClasspathStatus, IIncludePathEntry[] newResolvedClasspath, Map newRootPathToRawEntries, Map newRootPathToResolvedEntries, IJavaScriptModelStatus newUnresolvedEntryStatus) {
- // remember old info
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- DeltaProcessor deltaProcessor = manager.deltaState.getDeltaProcessor();
- deltaProcessor.addClasspathChange(this.project, this.rawClasspath, this.outputLocation, this.resolvedClasspath);
-
- this.rawClasspath = newRawClasspath;
- this.outputLocation = newOutputLocation;
- this.rawClasspathStatus = newRawClasspathStatus;
- this.resolvedClasspath = newResolvedClasspath;
- this.rootPathToRawEntries = newRootPathToRawEntries;
- this.rootPathToResolvedEntries = newRootPathToResolvedEntries;
- this.unresolvedEntryStatus = newUnresolvedEntryStatus;
- this.javadocCache = new LRUCache(JAVADOC_CACHE_INITIAL_SIZE);
- }
-
- /*
- * Reads the raw classpath and output location from disk, and remember them.
- * Return the raw classpath, or JavaProject#INVALID_CLASSPATH if unable to read it.
- */
- public synchronized IIncludePathEntry[] readAndCacheClasspath(JavaProject javaProject) {
- // read file entries and update status
- IIncludePathEntry[] classpath;
- IJavaScriptModelStatus status;
- try {
- classpath = javaProject.readFileEntriesWithException(null/*not interested in unknown elements*/);
- status = JavaModelStatus.VERIFIED_OK;
- } catch (CoreException e) {
- classpath = JavaProject.INVALID_CLASSPATH;
- status =
- new JavaModelStatus(
- IJavaScriptModelStatusConstants.INVALID_INCLUDEPATH_FILE_FORMAT,
- Messages.bind(Messages.classpath_cannotReadClasspathFile, javaProject.getElementName()));
- } catch (IOException e) {
- classpath = JavaProject.INVALID_CLASSPATH;
- if (Messages.file_badFormat.equals(e.getMessage()))
- status =
- new JavaModelStatus(
- IJavaScriptModelStatusConstants.INVALID_INCLUDEPATH_FILE_FORMAT,
- Messages.bind(Messages.classpath_xmlFormatError, javaProject.getElementName(), Messages.file_badFormat));
- else
- status =
- new JavaModelStatus(
- IJavaScriptModelStatusConstants.INVALID_INCLUDEPATH_FILE_FORMAT,
- Messages.bind(Messages.classpath_cannotReadClasspathFile, javaProject.getElementName()));
- } catch (AssertionFailedException e) {
- classpath = JavaProject.INVALID_CLASSPATH;
- status =
- new JavaModelStatus(
- IJavaScriptModelStatusConstants.INVALID_INCLUDEPATH_FILE_FORMAT,
- Messages.bind(Messages.classpath_illegalEntryInClasspathFile, new String[] {javaProject.getElementName(), e.getMessage()}));
- }
-
- // extract out the output location
- IPath output = null;
- if (classpath.length > 0) {
- IIncludePathEntry entry = classpath[classpath.length - 1];
- if (entry.getContentKind() == ClasspathEntry.K_OUTPUT) {
- output = entry.getPath();
- IIncludePathEntry[] copy = new IIncludePathEntry[classpath.length - 1];
- System.arraycopy(classpath, 0, copy, 0, copy.length);
- classpath = copy;
- }
- }
-
- // store new raw classpath, new output and new status, and null out resolved info
- setClasspath(classpath, output, status, null, null, null, null);
-
- return classpath;
- }
-
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- buffer.append("Info for "); //$NON-NLS-1$
- buffer.append(this.project.getFullPath());
- buffer.append("\nRaw classpath:\n"); //$NON-NLS-1$
- if (this.rawClasspath == null) {
- buffer.append(" <null>\n"); //$NON-NLS-1$
- } else {
- for (int i = 0, length = this.rawClasspath.length; i < length; i++) {
- buffer.append(" "); //$NON-NLS-1$
- buffer.append(this.rawClasspath[i]);
- buffer.append('\n');
- }
- }
- buffer.append("Resolved classpath:\n"); //$NON-NLS-1$
- IIncludePathEntry[] resolvedCP = this.resolvedClasspath;
- if (resolvedCP == null) {
- buffer.append(" <null>\n"); //$NON-NLS-1$
- } else {
- for (int i = 0, length = resolvedCP.length; i < length; i++) {
- buffer.append(" "); //$NON-NLS-1$
- buffer.append(resolvedCP[i]);
- buffer.append('\n');
- }
- }
- buffer.append("Output location:\n "); //$NON-NLS-1$
- if (this.outputLocation == null) {
- buffer.append("<null>"); //$NON-NLS-1$
- } else {
- buffer.append(this.outputLocation);
- }
- return buffer.toString();
- }
- }
-
- public static class PerWorkingCopyInfo implements IProblemRequestor {
- int useCount = 0;
- IProblemRequestor problemRequestor;
- CompilationUnit workingCopy;
- public PerWorkingCopyInfo(CompilationUnit workingCopy, IProblemRequestor problemRequestor) {
- this.workingCopy = workingCopy;
- this.problemRequestor = problemRequestor;
- }
- public void acceptProblem(IProblem problem) {
- IProblemRequestor requestor = getProblemRequestor();
- if (requestor == null) return;
- requestor.acceptProblem(problem);
- }
- public void beginReporting() {
- IProblemRequestor requestor = getProblemRequestor();
- if (requestor == null) return;
- requestor.beginReporting();
- }
- public void endReporting() {
- IProblemRequestor requestor = getProblemRequestor();
- if (requestor == null) return;
- requestor.endReporting();
- }
- public IProblemRequestor getProblemRequestor() {
- if (this.problemRequestor == null && this.workingCopy.owner != null) {
- return this.workingCopy.owner.getProblemRequestor(this.workingCopy);
- }
- return this.problemRequestor;
- }
- public IJavaScriptUnit getWorkingCopy() {
- return this.workingCopy;
- }
- public boolean isActive() {
- IProblemRequestor requestor = getProblemRequestor();
- return requestor != null && requestor.isActive();
- }
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- buffer.append("Info for "); //$NON-NLS-1$
- buffer.append(((JavaElement)this.workingCopy).toStringWithAncestors());
- buffer.append("\nUse count = "); //$NON-NLS-1$
- buffer.append(this.useCount);
- buffer.append("\nProblem requestor:\n "); //$NON-NLS-1$
- buffer.append(this.problemRequestor);
- if (this.problemRequestor == null) {
- IProblemRequestor requestor = getProblemRequestor();
- buffer.append("\nOwner problem requestor:\n "); //$NON-NLS-1$
- buffer.append(requestor);
- }
- return buffer.toString();
- }
- }
-
- public static boolean VERBOSE = false;
- public static boolean CP_RESOLVE_VERBOSE = false;
- public static boolean CP_RESOLVE_VERBOSE_ADVANCED = false;
- public static boolean ZIP_ACCESS_VERBOSE = false;
-
- /**
- * A cache of opened zip files per thread.
- * (for a given thread, the object value is a HashMap from IPath to java.io.ZipFile)
- */
- private ThreadLocal zipFiles = new ThreadLocal();
-
-
- /**
- * Update the classpath variable cache
- */
- public class EclipsePreferencesListener implements IEclipsePreferences.IPreferenceChangeListener {
- /**
- * @see org.eclipse.core.runtime.preferences.IEclipsePreferences.IPreferenceChangeListener#preferenceChange(org.eclipse.core.runtime.preferences.IEclipsePreferences.PreferenceChangeEvent)
- */
- public void preferenceChange(IEclipsePreferences.PreferenceChangeEvent event) {
- String propertyName = event.getKey();
- if (propertyName.startsWith(CP_VARIABLE_PREFERENCES_PREFIX)) {
- String varName = propertyName.substring(CP_VARIABLE_PREFERENCES_PREFIX.length());
- JavaModelManager manager = getJavaModelManager();
- if (manager.variablesWithInitializer.contains(varName)) {
- // revert preference value as we will not apply it to JavaScriptCore classpath variable
- String oldValue = (String) event.getOldValue();
- if (oldValue == null) {
- // unexpected old value => remove variable from set
- manager.variablesWithInitializer.remove(varName);
- } else {
- manager.getInstancePreferences().put(varName, oldValue);
- }
- } else {
- String newValue = (String)event.getNewValue();
- IPath newPath;
- if (newValue != null && !(newValue = newValue.trim()).equals(CP_ENTRY_IGNORE)) {
- newPath = new Path(newValue);
- } else {
- newPath = null;
- }
- try {
- SetVariablesOperation operation = new SetVariablesOperation(new String[] {varName}, new IPath[] {newPath}, false/*don't update preferences*/);
- operation.runOperation(null/*no progress available*/);
- } catch (JavaScriptModelException e) {
- Util.log(e, "Could not set classpath variable " + varName + " to " + newPath); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
- } else if (propertyName.startsWith(CP_CONTAINER_PREFERENCES_PREFIX)) {
- recreatePersistedContainer(propertyName, (String)event.getNewValue(), false);
- } else if (propertyName.equals(JavaScriptCore.CORE_JAVA_BUILD_CLEAN_OUTPUT_FOLDER) ||
- propertyName.equals(JavaScriptCore.CORE_JAVA_BUILD_RESOURCE_COPY_FILTER) ||
- propertyName.equals(JavaScriptCore.CORE_JAVA_BUILD_DUPLICATE_RESOURCE) ||
- propertyName.equals(JavaScriptCore.CORE_JAVA_BUILD_RECREATE_MODIFIED_CLASS_FILES_IN_OUTPUT_FOLDER) ||
- propertyName.equals(JavaScriptCore.CORE_JAVA_BUILD_INVALID_CLASSPATH) ||
- propertyName.equals(JavaScriptCore.CORE_ENABLE_CLASSPATH_EXCLUSION_PATTERNS) ||
- propertyName.equals(JavaScriptCore.CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS) ||
- propertyName.equals(JavaScriptCore.CORE_INCOMPLETE_CLASSPATH) ||
- propertyName.equals(JavaScriptCore.CORE_CIRCULAR_CLASSPATH) ||
- propertyName.equals(JavaScriptCore.CORE_INCOMPATIBLE_JDK_LEVEL)) {
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- IJavaScriptModel model = manager.getJavaModel();
- IJavaScriptProject[] projects;
- try {
- projects = model.getJavaScriptProjects();
- for (int i = 0, pl = projects.length; i < pl; i++) {
- JavaProject javaProject = (JavaProject) projects[i];
- manager.deltaState.addClasspathValidation(javaProject);
- try {
- // need to touch the project to force validation by DeltaProcessor
- javaProject.getProject().touch(null);
- } catch (CoreException e) {
- // skip
- }
- }
- } catch (JavaScriptModelException e) {
- // skip
- }
- }
- }
- }
-
- /**
- * Constructs a new JavaModelManager
- */
- private JavaModelManager() {
- // singleton: prevent others from creating a new instance
- if (Platform.isRunning()) this.indexManager = new IndexManager();
- }
-
- /**
- * @deprecated
- */
- private void addDeprecatedOptions(Hashtable options) {
- options.put(JavaScriptCore.COMPILER_PB_INVALID_IMPORT, JavaScriptCore.ERROR);
- options.put(JavaScriptCore.COMPILER_PB_UNREACHABLE_CODE, JavaScriptCore.ERROR);
- }
-
- /**
- * Starts caching ZipFiles.
- * Ignores if there are already clients.
- */
- public void cacheZipFiles() {
- if (this.zipFiles.get() != null) return;
- this.zipFiles.set(new HashMap());
- }
- public void closeZipFile(ZipFile zipFile) {
- if (zipFile == null) return;
- if (this.zipFiles.get() != null) {
- return; // zip file will be closed by call to flushZipFiles
- }
- try {
- if (JavaModelManager.ZIP_ACCESS_VERBOSE) {
- System.out.println("(" + Thread.currentThread() + ") [JavaModelManager.closeZipFile(ZipFile)] Closing ZipFile on " +zipFile.getName()); //$NON-NLS-1$ //$NON-NLS-2$
- }
- zipFile.close();
- } catch (IOException e) {
- // problem occured closing zip file: cannot do much more
- }
- }
-
- /**
- * Configure the plugin with respect to option settings defined in ".options" file
- */
- public void configurePluginDebugOptions(){
- if(JavaScriptCore.getPlugin().isDebugging()){
- String option = Platform.getDebugOption(BUFFER_MANAGER_DEBUG);
- if(option != null) BufferManager.VERBOSE = option.equalsIgnoreCase(TRUE) ;
-
- option = Platform.getDebugOption(BUILDER_DEBUG);
- if(option != null) JavaBuilder.DEBUG = option.equalsIgnoreCase(TRUE) ;
-
- option = Platform.getDebugOption(COMPILER_DEBUG);
- if(option != null) Compiler.DEBUG = option.equalsIgnoreCase(TRUE) ;
-
- option = Platform.getDebugOption(COMPLETION_DEBUG);
- if(option != null) CompletionEngine.DEBUG = option.equalsIgnoreCase(TRUE) ;
-
- option = Platform.getDebugOption(CP_RESOLVE_DEBUG);
- if(option != null) JavaModelManager.CP_RESOLVE_VERBOSE = option.equalsIgnoreCase(TRUE) ;
-
- option = Platform.getDebugOption(CP_RESOLVE_ADVANCED_DEBUG);
- if(option != null) JavaModelManager.CP_RESOLVE_VERBOSE_ADVANCED = option.equalsIgnoreCase(TRUE) ;
-
- option = Platform.getDebugOption(DELTA_DEBUG);
- if(option != null) DeltaProcessor.DEBUG = option.equalsIgnoreCase(TRUE) ;
-
- option = Platform.getDebugOption(DELTA_DEBUG_VERBOSE);
- if(option != null) DeltaProcessor.VERBOSE = option.equalsIgnoreCase(TRUE) ;
-
- option = Platform.getDebugOption(HIERARCHY_DEBUG);
- if(option != null) TypeHierarchy.DEBUG = option.equalsIgnoreCase(TRUE) ;
-
- option = Platform.getDebugOption(INDEX_MANAGER_DEBUG);
- if(option != null) JobManager.VERBOSE = option.equalsIgnoreCase(TRUE) ;
-
- option = Platform.getDebugOption(JAVAMODEL_DEBUG);
- if(option != null) JavaModelManager.VERBOSE = option.equalsIgnoreCase(TRUE) ;
-
- option = Platform.getDebugOption(JAVAMODELCACHE_DEBUG);
- if(option != null) JavaModelCache.VERBOSE = option.equalsIgnoreCase(TRUE) ;
-
- option = Platform.getDebugOption(POST_ACTION_DEBUG);
- if(option != null) JavaModelOperation.POST_ACTION_VERBOSE = option.equalsIgnoreCase(TRUE) ;
-
- option = Platform.getDebugOption(RESOLUTION_DEBUG);
- if(option != null) NameLookup.VERBOSE = option.equalsIgnoreCase(TRUE) ;
-
- option = Platform.getDebugOption(SEARCH_DEBUG);
- if(option != null) BasicSearchEngine.VERBOSE = option.equalsIgnoreCase(TRUE) ;
-
- option = Platform.getDebugOption(SELECTION_DEBUG);
- if(option != null) SelectionEngine.DEBUG = option.equalsIgnoreCase(TRUE) ;
-
- option = Platform.getDebugOption(ZIP_ACCESS_DEBUG);
- if(option != null) JavaModelManager.ZIP_ACCESS_VERBOSE = option.equalsIgnoreCase(TRUE) ;
-
- option = Platform.getDebugOption(SOURCE_MAPPER_DEBUG_VERBOSE);
- if(option != null) SourceMapper.VERBOSE = option.equalsIgnoreCase(TRUE) ;
- }
-
- // configure performance options
- if(PerformanceStats.ENABLED) {
- CompletionEngine.PERF = PerformanceStats.isEnabled(COMPLETION_PERF);
- SelectionEngine.PERF = PerformanceStats.isEnabled(SELECTION_PERF);
- DeltaProcessor.PERF = PerformanceStats.isEnabled(DELTA_LISTENER_PERF);
- JavaModelManager.PERF_VARIABLE_INITIALIZER = PerformanceStats.isEnabled(VARIABLE_INITIALIZER_PERF);
- JavaModelManager.PERF_CONTAINER_INITIALIZER = PerformanceStats.isEnabled(CONTAINER_INITIALIZER_PERF);
- ReconcileWorkingCopyOperation.PERF = PerformanceStats.isEnabled(RECONCILE_PERF);
- }
- }
-
- /*
- * Discards the per working copy info for the given working copy (making it a compilation unit)
- * if its use count was 1. Otherwise, just decrement the use count.
- * If the working copy is primary, computes the delta between its state and the original compilation unit
- * and register it.
- * Close the working copy, its buffer and remove it from the shared working copy table.
- * Ignore if no per-working copy info existed.
- * NOTE: it must NOT be synchronized as it may interact with the element info cache (if useCount is decremented to 0), see bug 50667.
- * Returns the new use count (or -1 if it didn't exist).
- */
- public int discardPerWorkingCopyInfo(CompilationUnit workingCopy) throws JavaScriptModelException {
-
- // create the delta builder (this remembers the current content of the working copy)
- // outside the perWorkingCopyInfos lock (see bug 50667)
- JavaElementDeltaBuilder deltaBuilder = null;
- if (workingCopy.isPrimary() && workingCopy.hasUnsavedChanges()) {
- deltaBuilder = new JavaElementDeltaBuilder(workingCopy);
- }
- PerWorkingCopyInfo info = null;
- synchronized(this.perWorkingCopyInfos) {
- WorkingCopyOwner owner = workingCopy.owner;
- Map workingCopyToInfos = (Map)this.perWorkingCopyInfos.get(owner);
- if (workingCopyToInfos == null) return -1;
-
- info = (PerWorkingCopyInfo)workingCopyToInfos.get(workingCopy);
- if (info == null) return -1;
-
- if (--info.useCount == 0) {
- // remove per working copy info
- workingCopyToInfos.remove(workingCopy);
- if (workingCopyToInfos.isEmpty()) {
- this.perWorkingCopyInfos.remove(owner);
- }
- }
- }
- if (info.useCount == 0) { // info cannot be null here (check was done above)
- // remove infos + close buffer (since no longer working copy)
- // outside the perWorkingCopyInfos lock (see bug 50667)
- removeInfoAndChildren(workingCopy);
- workingCopy.closeBuffer();
-
- // compute the delta if needed and register it if there are changes
- if (deltaBuilder != null) {
- deltaBuilder.buildDeltas();
- if (deltaBuilder.delta != null) {
- getDeltaProcessor().registerJavaModelDelta(deltaBuilder.delta);
- }
- }
- }
- return info.useCount;
- }
-
- /**
- * @see ISaveParticipant
- */
- public void doneSaving(ISaveContext context){
- // nothing to do for jdt.core
- }
-
- /**
- * Flushes ZipFiles cache if there are no more clients.
- */
- public void flushZipFiles() {
- Thread currentThread = Thread.currentThread();
- HashMap map = (HashMap)this.zipFiles.get();
- if (map == null) return;
- this.zipFiles.set(null);
- Iterator iterator = map.values().iterator();
- while (iterator.hasNext()) {
- try {
- ZipFile zipFile = (ZipFile)iterator.next();
- if (JavaModelManager.ZIP_ACCESS_VERBOSE) {
- System.out.println("(" + currentThread + ") [JavaModelManager.flushZipFiles()] Closing ZipFile on " +zipFile.getName()); //$NON-NLS-1$//$NON-NLS-2$
- }
- zipFile.close();
- } catch (IOException e) {
- // problem occured closing zip file: cannot do much more
- }
- }
- }
-
- private synchronized boolean batchContainerInitializations() {
- if (this.batchContainerInitializations) {
- this.batchContainerInitializations = false;
- return true;
- }
- return false;
- }
-
- public IJsGlobalScopeContainer getJsGlobalScopeContainer(final IPath containerPath, final IJavaScriptProject project) throws JavaScriptModelException {
-
- IJsGlobalScopeContainer container = containerGet(project, containerPath);
-
- if (container == null) {
- if (batchContainerInitializations()) {
- // avoid deep recursion while initializaing container on workspace restart
- // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=60437)
- container = initializeAllContainers(project, containerPath);
- } else {
- container = initializeContainer(project, containerPath);
- }
-
- }
- return container;
- }
-
- public DeltaProcessor getDeltaProcessor() {
- return this.deltaState.getDeltaProcessor();
- }
-
- /**
- * Returns the set of elements which are out of synch with their buffers.
- */
- protected HashSet getElementsOutOfSynchWithBuffers() {
- return this.elementsOutOfSynchWithBuffers;
- }
-
- public IndexManager getIndexManager() {
- return this.indexManager;
- }
-
- /**
- * Returns the info for the element.
- */
- public synchronized Object getInfo(IJavaScriptElement element) {
- HashMap tempCache = (HashMap)this.temporaryCache.get();
- if (tempCache != null) {
- Object result = tempCache.get(element);
- if (result != null) {
- return result;
- }
- }
- return this.cache.getInfo(element);
- }
-
- /**
- * Get workpsace eclipse preference for JavaScriptCore plugin.
- */
- public IEclipsePreferences getInstancePreferences() {
- return preferencesLookup[PREF_INSTANCE];
- }
-
- // If modified, also modify the method getDefaultOptionsNoInitialization()
- public Hashtable getDefaultOptions(){
-
- Hashtable defaultOptions = new Hashtable(10);
-
- // see JavaCorePreferenceInitializer#initializeDefaultPluginPreferences() for changing default settings
- // If modified, also modify the method getDefaultOptionsNoInitialization()
- IEclipsePreferences defaultPreferences = getDefaultPreferences();
-
- // initialize preferences to their default
- Iterator iterator = this.optionNames.iterator();
- while (iterator.hasNext()) {
- String propertyName = (String) iterator.next();
- String value = defaultPreferences.get(propertyName, null);
- if (value != null) defaultOptions.put(propertyName, value);
- }
- // get encoding through resource plugin
- defaultOptions.put(JavaScriptCore.CORE_ENCODING, JavaScriptCore.getEncoding());
- // backward compatibility
- addDeprecatedOptions(defaultOptions);
-
- return defaultOptions;
- }
-
- /**
- * Get default eclipse preference for JavaScriptCore plugin.
- */
- public IEclipsePreferences getDefaultPreferences() {
- return preferencesLookup[PREF_DEFAULT];
- }
-
- /**
- * Returns the handle to the active Java Model.
- */
- public final JavaModel getJavaModel() {
- return this.javaModel;
- }
-
- /**
- * Returns the singleton JavaModelManager
- */
- public final static JavaModelManager getJavaModelManager() {
- return MANAGER;
- }
-
- /**
- * Returns the last built state for the given project, or null if there is none.
- * Deserializes the state if necessary.
- *
- * For use by image builder and evaluation support only
- */
- public Object getLastBuiltState(IProject project, IProgressMonitor monitor) {
- if (!JavaProject.hasJavaNature(project)) {
- if (JavaBuilder.DEBUG)
- System.out.println(project + " is not a Java project"); //$NON-NLS-1$
- return null; // should never be requested on non-Java projects
- }
- PerProjectInfo info = getPerProjectInfo(project, true/*create if missing*/);
- if (!info.triedRead) {
- info.triedRead = true;
- try {
- if (monitor != null)
- monitor.subTask(Messages.bind(Messages.build_readStateProgress, project.getName()));
- info.savedState = readState(project);
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
- return info.savedState;
- }
-
- public String getOption(String optionName) {
-
- if (JavaScriptCore.CORE_ENCODING.equals(optionName)){
- return JavaScriptCore.getEncoding();
- }
- // backward compatibility
- if (isDeprecatedOption(optionName)) {
- return JavaScriptCore.ERROR;
- }
- String propertyName = optionName;
- if (this.optionNames.contains(propertyName)){
- IPreferencesService service = Platform.getPreferencesService();
- String value = service.get(optionName, null, this.preferencesLookup);
- return value==null ? null : value.trim();
- }
- return null;
- }
-
- public Hashtable getOptions() {
-
- // return cached options if already computed
- if (this.optionsCache != null) return new Hashtable(this.optionsCache);
-
- if (!Platform.isRunning()) {
- return this.optionsCache = getDefaultOptionsNoInitialization();
- }
- // init
- Hashtable options = new Hashtable(10);
- IPreferencesService service = Platform.getPreferencesService();
-
- // set options using preferences service lookup
- Iterator iterator = optionNames.iterator();
- while (iterator.hasNext()) {
- String propertyName = (String) iterator.next();
- String propertyValue = service.get(propertyName, null, this.preferencesLookup);
- if (propertyValue != null) {
- options.put(propertyName, propertyValue);
- }
- }
-
- // get encoding through resource plugin
- options.put(JavaScriptCore.CORE_ENCODING, JavaScriptCore.getEncoding());
-
- // backward compatibility
- addDeprecatedOptions(options);
-
- // store built map in cache
- this.optionsCache = new Hashtable(options);
-
- // return built map
- return options;
- }
-
- // Do not modify without modifying getDefaultOptions()
- private Hashtable getDefaultOptionsNoInitialization() {
- Map defaultOptionsMap = new CompilerOptions().getMap(); // compiler defaults
-
- /* START -------------------------------- Bug 203292 Type/Method/Filed resolution error configuration --------------------- */
- /*
- * Default ERROR for unresolved types/fields/methods
- */
- defaultOptionsMap.put(JavaScriptCore.UNRESOLVED_TYPE_REFERENCE, JavaScriptCore.ERROR);
- defaultOptionsMap.put(JavaScriptCore.UNRESOLVED_FIELD_REFERENCE, JavaScriptCore.ERROR);
- defaultOptionsMap.put(JavaScriptCore.UNRESOLVED_METHOD_REFERENCE, JavaScriptCore.ERROR);
- /* END -------------------------------- Bug 203292 Type/Method/Filed resolution error configuration --------------------- */
-
- /* START -------------------------------- Bug 197884 Loosly defined var (for statement) and optional semi-colon --------------------- */
- defaultOptionsMap.put(JavaScriptCore.LOOSE_VAR_DECL, JavaScriptCore.WARNING);
- defaultOptionsMap.put(JavaScriptCore.OPTIONAL_SEMICOLON, JavaScriptCore.WARNING);
-
- /* END -------------------------------- Bug 197884 Loosly defined var (for statement) and optional semi-colon --------------------- */
-
- // Override some compiler defaults
- defaultOptionsMap.put(JavaScriptCore.COMPILER_LOCAL_VARIABLE_ATTR, JavaScriptCore.GENERATE);
- defaultOptionsMap.put(JavaScriptCore.COMPILER_CODEGEN_UNUSED_LOCAL, JavaScriptCore.PRESERVE);
- defaultOptionsMap.put(JavaScriptCore.COMPILER_TASK_TAGS, JavaScriptCore.DEFAULT_TASK_TAGS);
- defaultOptionsMap.put(JavaScriptCore.COMPILER_TASK_PRIORITIES, JavaScriptCore.DEFAULT_TASK_PRIORITIES);
- defaultOptionsMap.put(JavaScriptCore.COMPILER_TASK_CASE_SENSITIVE, JavaScriptCore.ENABLED);
- defaultOptionsMap.put(JavaScriptCore.COMPILER_DOC_COMMENT_SUPPORT, JavaScriptCore.ENABLED);
- defaultOptionsMap.put(JavaScriptCore.COMPILER_PB_FORBIDDEN_REFERENCE, JavaScriptCore.ERROR);
- defaultOptionsMap.put(JavaScriptCore.COMPILER_SEMANTIC_VALIDATION, JavaScriptCore.ENABLED);
-
- // Builder settings
- defaultOptionsMap.put(JavaScriptCore.CORE_JAVA_BUILD_RESOURCE_COPY_FILTER, ""); //$NON-NLS-1$
- defaultOptionsMap.put(JavaScriptCore.CORE_JAVA_BUILD_INVALID_CLASSPATH, JavaScriptCore.ABORT);
- defaultOptionsMap.put(JavaScriptCore.CORE_JAVA_BUILD_DUPLICATE_RESOURCE, JavaScriptCore.WARNING);
- defaultOptionsMap.put(JavaScriptCore.CORE_JAVA_BUILD_CLEAN_OUTPUT_FOLDER, JavaScriptCore.CLEAN);
-
- // JavaScriptCore settings
- defaultOptionsMap.put(JavaScriptCore.CORE_JAVA_BUILD_ORDER, JavaScriptCore.IGNORE);
- defaultOptionsMap.put(JavaScriptCore.CORE_INCOMPLETE_CLASSPATH, JavaScriptCore.ERROR);
- defaultOptionsMap.put(JavaScriptCore.CORE_CIRCULAR_CLASSPATH, JavaScriptCore.ERROR);
- defaultOptionsMap.put(JavaScriptCore.CORE_INCOMPATIBLE_JDK_LEVEL, JavaScriptCore.IGNORE);
- defaultOptionsMap.put(JavaScriptCore.CORE_ENABLE_CLASSPATH_EXCLUSION_PATTERNS, JavaScriptCore.ENABLED);
- defaultOptionsMap.put(JavaScriptCore.CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS, JavaScriptCore.ENABLED);
-
- // Formatter settings
- defaultOptionsMap.putAll(DefaultCodeFormatterConstants.getEclipseDefaultSettings());
-
- // CodeAssist settings
- defaultOptionsMap.put(JavaScriptCore.CODEASSIST_VISIBILITY_CHECK, JavaScriptCore.DISABLED);
- defaultOptionsMap.put(JavaScriptCore.CODEASSIST_DEPRECATION_CHECK, JavaScriptCore.DISABLED);
- defaultOptionsMap.put(JavaScriptCore.CODEASSIST_IMPLICIT_QUALIFICATION, JavaScriptCore.DISABLED);
- defaultOptionsMap.put(JavaScriptCore.CODEASSIST_FIELD_PREFIXES, ""); //$NON-NLS-1$
- defaultOptionsMap.put(JavaScriptCore.CODEASSIST_STATIC_FIELD_PREFIXES, ""); //$NON-NLS-1$
- defaultOptionsMap.put(JavaScriptCore.CODEASSIST_LOCAL_PREFIXES, ""); //$NON-NLS-1$
- defaultOptionsMap.put(JavaScriptCore.CODEASSIST_ARGUMENT_PREFIXES, ""); //$NON-NLS-1$
- defaultOptionsMap.put(JavaScriptCore.CODEASSIST_FIELD_SUFFIXES, ""); //$NON-NLS-1$
- defaultOptionsMap.put(JavaScriptCore.CODEASSIST_STATIC_FIELD_SUFFIXES, ""); //$NON-NLS-1$
- defaultOptionsMap.put(JavaScriptCore.CODEASSIST_LOCAL_SUFFIXES, ""); //$NON-NLS-1$
- defaultOptionsMap.put(JavaScriptCore.CODEASSIST_ARGUMENT_SUFFIXES, ""); //$NON-NLS-1$
- defaultOptionsMap.put(JavaScriptCore.CODEASSIST_FORBIDDEN_REFERENCE_CHECK, JavaScriptCore.ENABLED);
- defaultOptionsMap.put(JavaScriptCore.CODEASSIST_DISCOURAGED_REFERENCE_CHECK, JavaScriptCore.DISABLED);
- defaultOptionsMap.put(JavaScriptCore.CODEASSIST_CAMEL_CASE_MATCH, JavaScriptCore.ENABLED);
- defaultOptionsMap.put(JavaScriptCore.CODEASSIST_SUGGEST_STATIC_IMPORTS, JavaScriptCore.ENABLED);
-
- // Time out for parameter names
- defaultOptionsMap.put(JavaScriptCore.TIMEOUT_FOR_PARAMETER_NAME_FROM_ATTACHED_JAVADOC, "50"); //$NON-NLS-1$
-
- return new Hashtable(defaultOptionsMap);
- }
-
- /*
- * Returns the per-project info for the given project. If specified, create the info if the info doesn't exist.
- */
- public PerProjectInfo getPerProjectInfo(IProject project, boolean create) {
- synchronized(this.perProjectInfos) { // use the perProjectInfo collection as its own lock
- PerProjectInfo info= (PerProjectInfo) this.perProjectInfos.get(project);
- if (info == null && create) {
- info= new PerProjectInfo(project);
- this.perProjectInfos.put(project, info);
- }
- return info;
- }
- }
-
- /*
- * Returns the per-project info for the given project.
- * If the info doesn't exist, check for the project existence and create the info.
- * @throws JavaScriptModelException if the project doesn't exist.
- */
- public PerProjectInfo getPerProjectInfoCheckExistence(IProject project) throws JavaScriptModelException {
- JavaModelManager.PerProjectInfo info = getPerProjectInfo(project, false /* don't create info */);
- if (info == null) {
-// continue even if not js project if (!JavaProject.hasJSDTScope(project)&& !JavaProject.hasJavaNature(project)) {
-// throw ((JavaProject)JavaScriptCore.create(project)).newNotPresentException();
-// }
- info = getPerProjectInfo(project, true /* create info */);
- }
- return info;
- }
-
- /*
- * Returns the per-working copy info for the given working copy at the given path.
- * If it doesn't exist and if create, add a new per-working copy info with the given problem requestor.
- * If recordUsage, increment the per-working copy info's use count.
- * Returns null if it doesn't exist and not create.
- */
- public PerWorkingCopyInfo getPerWorkingCopyInfo(CompilationUnit workingCopy,boolean create, boolean recordUsage, IProblemRequestor problemRequestor) {
- synchronized(this.perWorkingCopyInfos) { // use the perWorkingCopyInfo collection as its own lock
- WorkingCopyOwner owner = workingCopy.owner;
- Map workingCopyToInfos = (Map)this.perWorkingCopyInfos.get(owner);
- if (workingCopyToInfos == null && create) {
- workingCopyToInfos = new HashMap();
- this.perWorkingCopyInfos.put(owner, workingCopyToInfos);
- }
-
- PerWorkingCopyInfo info = workingCopyToInfos == null ? null : (PerWorkingCopyInfo) workingCopyToInfos.get(workingCopy);
- if (info == null && create) {
- info= new PerWorkingCopyInfo(workingCopy, problemRequestor);
- workingCopyToInfos.put(workingCopy, info);
- }
- if (info != null && recordUsage) info.useCount++;
- return info;
- }
- }
-
- /**
- * Returns a persisted container from previous session if any. Note that it is not the original container from previous
- * session (i.e. it did not get serialized) but rather a summary of its entries recreated for CP initialization purpose.
- * As such it should not be stored into container caches.
- */
- public IJsGlobalScopeContainer getPreviousSessionContainer(IPath containerPath, IJavaScriptProject project) {
- Map previousContainerValues = (Map)this.previousSessionContainers.get(project);
- if (previousContainerValues != null){
- IJsGlobalScopeContainer previousContainer = (IJsGlobalScopeContainer)previousContainerValues.get(containerPath);
- if (previousContainer != null) {
- if (JavaModelManager.CP_RESOLVE_VERBOSE_ADVANCED)
- verbose_reentering_project_container_access(containerPath, project, previousContainer);
- return previousContainer;
- }
- }
- return null; // break cycle if none found
- }
-
- private void verbose_reentering_project_container_access( IPath containerPath, IJavaScriptProject project, IJsGlobalScopeContainer previousContainer) {
- StringBuffer buffer = new StringBuffer();
- buffer.append("CPContainer INIT - reentering access to project container during its initialization, will see previous value\n"); //$NON-NLS-1$
- buffer.append(" project: " + project.getElementName() + '\n'); //$NON-NLS-1$
- buffer.append(" container path: " + containerPath + '\n'); //$NON-NLS-1$
- buffer.append(" previous value: "); //$NON-NLS-1$
- buffer.append(previousContainer.getDescription());
- buffer.append(" {\n"); //$NON-NLS-1$
- IIncludePathEntry[] entries = previousContainer.getIncludepathEntries();
- if (entries != null){
- for (int j = 0; j < entries.length; j++){
- buffer.append(" "); //$NON-NLS-1$
- buffer.append(entries[j]);
- buffer.append('\n');
- }
- }
- buffer.append(" }"); //$NON-NLS-1$
- Util.verbose(buffer.toString());
- new Exception("<Fake exception>").printStackTrace(System.out); //$NON-NLS-1$
- }
-
- /**
- * Returns a persisted container from previous session if any
- */
- public IPath getPreviousSessionVariable(String variableName) {
- IPath previousPath = (IPath)this.previousSessionVariables.get(variableName);
- if (previousPath != null){
- if (CP_RESOLVE_VERBOSE_ADVANCED)
- verbose_reentering_variable_access(variableName, previousPath);
- return previousPath;
- }
- return null; // break cycle
- }
-
- private void verbose_reentering_variable_access(String variableName, IPath previousPath) {
- Util.verbose(
- "CPVariable INIT - reentering access to variable during its initialization, will see previous value\n" + //$NON-NLS-1$
- " variable: "+ variableName + '\n' + //$NON-NLS-1$
- " previous value: " + previousPath); //$NON-NLS-1$
- new Exception("<Fake exception>").printStackTrace(System.out); //$NON-NLS-1$
- }
-
- /**
- * Returns the temporary cache for newly opened elements for the current thread.
- * Creates it if not already created.
- */
- public HashMap getTemporaryCache() {
- HashMap result = (HashMap)this.temporaryCache.get();
- if (result == null) {
- result = new HashMap();
- this.temporaryCache.set(result);
- }
- return result;
- }
-
- private File getVariableAndContainersFile() {
- return JavaScriptCore.getPlugin().getStateLocation().append("variablesAndContainers.dat").toFile(); //$NON-NLS-1$
- }
-
- /**
- * Returns the name of the variables for which an CP variable initializer is registered through an extension point
- */
- public static String[] getRegisteredVariableNames(){
-
- Plugin jdtCorePlugin = JavaScriptCore.getPlugin();
- if (jdtCorePlugin == null) return null;
-
- ArrayList variableList = new ArrayList(5);
- IExtensionPoint extension = Platform.getExtensionRegistry().getExtensionPoint(JavaScriptCore.PLUGIN_ID, JavaModelManager.CPVARIABLE_INITIALIZER_EXTPOINT_ID);
- if (extension != null) {
- IExtension[] extensions = extension.getExtensions();
- for(int i = 0; i < extensions.length; i++){
- IConfigurationElement [] configElements = extensions[i].getConfigurationElements();
- for(int j = 0; j < configElements.length; j++){
- String varAttribute = configElements[j].getAttribute("variable"); //$NON-NLS-1$
- if (varAttribute != null) variableList.add(varAttribute);
- }
- }
- }
- String[] variableNames = new String[variableList.size()];
- variableList.toArray(variableNames);
- return variableNames;
- }
-
- /**
- * Returns the name of the container IDs for which an CP container initializer is registered through an extension point
- */
- public static String[] getRegisteredContainerIDs(){
-
- Plugin jdtCorePlugin = JavaScriptCore.getPlugin();
- if (jdtCorePlugin == null) return null;
-
- ArrayList containerIDList = new ArrayList(5);
- IExtensionPoint extension = Platform.getExtensionRegistry().getExtensionPoint(JavaScriptCore.PLUGIN_ID, JavaModelManager.CPCONTAINER_INITIALIZER_EXTPOINT_ID);
- if (extension != null) {
- IExtension[] extensions = extension.getExtensions();
- for(int i = 0; i < extensions.length; i++){
- IConfigurationElement [] configElements = extensions[i].getConfigurationElements();
- for(int j = 0; j < configElements.length; j++){
- String idAttribute = configElements[j].getAttribute("id"); //$NON-NLS-1$
- if (idAttribute != null) containerIDList.add(idAttribute);
- }
- }
- }
- String[] containerIDs = new String[containerIDList.size()];
- containerIDList.toArray(containerIDs);
- return containerIDs;
- }
-
- /**
- * Returns the File to use for saving and restoring the last built state for the given project.
- */
- private File getSerializationFile(IProject project) {
- if (!project.exists()) return null;
- IPath workingLocation = project.getWorkingLocation(JavaScriptCore.PLUGIN_ID);
- return workingLocation.append("state.dat").toFile(); //$NON-NLS-1$
- }
-
- /*
- * Returns all the working copies which have the given owner.
- * Adds the working copies of the primary owner if specified.
- * Returns null if it has none.
- */
- public IJavaScriptUnit[] getWorkingCopies(WorkingCopyOwner owner, boolean addPrimary) {
- synchronized(this.perWorkingCopyInfos) {
- IJavaScriptUnit[] primaryWCs = addPrimary && owner != DefaultWorkingCopyOwner.PRIMARY
- ? getWorkingCopies(DefaultWorkingCopyOwner.PRIMARY, false)
- : null;
- Map workingCopyToInfos = (Map)this.perWorkingCopyInfos.get(owner);
- if (workingCopyToInfos == null) return primaryWCs;
- int primaryLength = primaryWCs == null ? 0 : primaryWCs.length;
- int size = workingCopyToInfos.size(); // note size is > 0 otherwise pathToPerWorkingCopyInfos would be null
- IJavaScriptUnit[] result = new IJavaScriptUnit[primaryLength + size];
- int index = 0;
- if (primaryWCs != null) {
- for (int i = 0; i < primaryLength; i++) {
- IJavaScriptUnit primaryWorkingCopy = primaryWCs[i];
- IJavaScriptUnit workingCopy = new CompilationUnit((PackageFragment) primaryWorkingCopy.getParent(), primaryWorkingCopy.getElementName(), owner);
- if (!workingCopyToInfos.containsKey(workingCopy))
- result[index++] = primaryWorkingCopy;
- }
- if (index != primaryLength)
- System.arraycopy(result, 0, result = new IJavaScriptUnit[index+size], 0, index);
- }
- Iterator iterator = workingCopyToInfos.values().iterator();
- while(iterator.hasNext()) {
- result[index++] = ((JavaModelManager.PerWorkingCopyInfo)iterator.next()).getWorkingCopy();
- }
- return result;
- }
- }
-
- public JavaWorkspaceScope getWorkspaceScope() {
- if (this.workspaceScope == null) {
- this.workspaceScope = new JavaWorkspaceScope();
- }
- return this.workspaceScope;
- }
-
- /**
- * Returns the open ZipFile at the given path. If the ZipFile
- * does not yet exist, it is created, opened, and added to the cache
- * of open ZipFiles.
- *
- * The path must be a file system path if representing an external
- * zip/jar, or it must be an absolute workspace relative path if
- * representing a zip/jar inside the workspace.
- *
- * @exception CoreException If unable to create/open the ZipFile
- */
- public ZipFile getZipFile(IPath path) throws CoreException {
-
- HashMap map;
- ZipFile zipFile;
- if ((map = (HashMap)this.zipFiles.get()) != null
- && (zipFile = (ZipFile)map.get(path)) != null) {
-
- return zipFile;
- }
- File localFile = null;
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- IResource file = root.findMember(path);
- if (file != null) {
- // internal resource
- URI location;
- if (file.getType() != IResource.FILE || (location = file.getLocationURI()) == null) {
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, -1, Messages.bind(Messages.file_notFound, path.toString()), null));
- }
- localFile = Util.toLocalFile(location, null/*no progress availaible*/);
- if (localFile == null)
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, -1, Messages.bind(Messages.file_notFound, path.toString()), null));
- } else {
- // external resource -> it is ok to use toFile()
- localFile= path.toFile();
- }
-
- try {
- if (ZIP_ACCESS_VERBOSE) {
- System.out.println("(" + Thread.currentThread() + ") [JavaModelManager.getZipFile(IPath)] Creating ZipFile on " + localFile ); //$NON-NLS-1$ //$NON-NLS-2$
- }
- zipFile = new ZipFile(localFile);
- if (map != null) {
- map.put(path, zipFile);
- }
- return zipFile;
- } catch (IOException e) {
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, -1, Messages.status_IOException, e));
- }
- }
-
- /*
- * Returns whether there is a temporary cache for the current thread.
- */
- public boolean hasTemporaryCache() {
- return this.temporaryCache.get() != null;
- }
-
- /*
- * Initialize all container at the same time as the given container.
- * Return the container for the given path and project.
- */
- private IJsGlobalScopeContainer initializeAllContainers(IJavaScriptProject javaProjectToInit, IPath containerToInit) throws JavaScriptModelException {
- if (CP_RESOLVE_VERBOSE_ADVANCED)
- verbose_batching_containers_initialization(javaProjectToInit, containerToInit);
-
- // collect all container paths
- final HashMap allContainerPaths = new HashMap();
- IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
- for (int i = 0, length = projects.length; i < length; i++) {
- IProject project = projects[i];
- if (!JavaProject.hasJavaNature(project)) continue;
- IJavaScriptProject javaProject = new JavaProject(project, getJavaModel());
- HashSet paths = (HashSet) allContainerPaths.get(javaProject);
- IIncludePathEntry[] rawClasspath = javaProject.getRawIncludepath();
- for (int j = 0, length2 = rawClasspath.length; j < length2; j++) {
- IIncludePathEntry entry = rawClasspath[j];
- IPath path = entry.getPath();
- if (entry.getEntryKind() == IIncludePathEntry.CPE_CONTAINER
- && containerGet(javaProject, path) == null) {
- if (paths == null) {
- paths = new HashSet();
- allContainerPaths.put(javaProject, paths);
- }
- paths.add(path);
- // mark container as being initialized
- containerAddInitializationInProgress(javaProject, path);
- }
- }
- /* TODO (frederic) put back when JDT/UI dummy project will be thrown away...
- * See https://bugs.eclipse.org/bugs/show_bug.cgi?id=97524
- *
- if (javaProject.equals(javaProjectToInit)) {
- if (paths == null) {
- paths = new HashSet();
- allContainerPaths.put(javaProject, paths);
- }
- paths.add(containerToInit);
- }
- */
- }
- // TODO (frederic) remove following block when JDT/UI dummy project will be thrown away...
- HashSet containerPaths = (HashSet) allContainerPaths.get(javaProjectToInit);
- if (containerPaths == null) {
- containerPaths = new HashSet();
- allContainerPaths.put(javaProjectToInit, containerPaths);
- }
- containerPaths.add(containerToInit);
- // mark container as being initialized
- containerAddInitializationInProgress(javaProjectToInit, containerToInit);
- // end block
-
- // initialize all containers
- boolean ok = false;
- try {
- // if possible run inside an IWokspaceRunnable with AVOID_UPATE to avoid unwanted builds
- // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=118507)
- IWorkspaceRunnable runnable =
- new IWorkspaceRunnable() {
- public void run(IProgressMonitor monitor) throws CoreException {
- try {
- Set entrySet = allContainerPaths.entrySet();
- int length = entrySet.size();
- if (monitor != null)
- monitor.beginTask("", length); //$NON-NLS-1$
- Map.Entry[] entries = new Map.Entry[length]; // clone as the following will have a side effect
- entrySet.toArray(entries);
- for (int i = 0; i < length; i++) {
- Map.Entry entry = entries[i];
- IJavaScriptProject javaProject = (IJavaScriptProject) entry.getKey();
- HashSet pathSet = (HashSet) entry.getValue();
- if (pathSet == null) continue;
- int length2 = pathSet.size();
- IPath[] paths = new IPath[length2];
- pathSet.toArray(paths); // clone as the following will have a side effect
- for (int j = 0; j < length2; j++) {
- IPath path = paths[j];
- initializeContainer(javaProject, path);
- }
- if (monitor != null)
- monitor.worked(1);
- }
- } finally {
- if (monitor != null)
- monitor.done();
- }
- }
- };
- IProgressMonitor monitor = (IProgressMonitor) this.batchContainerInitializationsProgress.get();
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- if (workspace.isTreeLocked())
- runnable.run(monitor);
- else
- workspace.run(
- runnable,
- null/*don't take any lock*/,
- IWorkspace.AVOID_UPDATE,
- monitor);
- ok = true;
- } catch (CoreException e) {
- // ignore
- Util.log(e, "Exception while initializing all containers"); //$NON-NLS-1$
- } finally {
- if (!ok) {
- // if we're being traversed by an exception, ensure that that containers are
- // no longer marked as initialization in progress
- // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=66437)
- this.containerInitializationInProgress.set(null);
- }
- }
-
- return containerGet(javaProjectToInit, containerToInit);
- }
-
- private void verbose_batching_containers_initialization(IJavaScriptProject javaProjectToInit, IPath containerToInit) {
- Util.verbose(
- "CPContainer INIT - batching containers initialization\n" + //$NON-NLS-1$
- " project to init: " + javaProjectToInit.getElementName() + '\n' + //$NON-NLS-1$
- " container path to init: " + containerToInit); //$NON-NLS-1$
- }
-
- IJsGlobalScopeContainer initializeContainer(IJavaScriptProject project, IPath containerPath) throws JavaScriptModelException {
-
- IProgressMonitor monitor = (IProgressMonitor) this.batchContainerInitializationsProgress.get();
- if (monitor != null && monitor.isCanceled())
- throw new OperationCanceledException();
-
- IJsGlobalScopeContainer container = null;
- final JsGlobalScopeContainerInitializer initializer = JavaScriptCore.getJsGlobalScopeContainerInitializer(containerPath.segment(0));
- if (initializer != null){
- if (CP_RESOLVE_VERBOSE)
- verbose_triggering_container_initialization(project, containerPath, initializer);
- if (CP_RESOLVE_VERBOSE_ADVANCED)
- verbose_triggering_container_initialization_invocation_trace();
- PerformanceStats stats = null;
- if(JavaModelManager.PERF_CONTAINER_INITIALIZER) {
- stats = PerformanceStats.getStats(JavaModelManager.CONTAINER_INITIALIZER_PERF, this);
- stats.startRun(containerPath + " of " + project.getPath()); //$NON-NLS-1$
- }
- containerPut(project, containerPath, CONTAINER_INITIALIZATION_IN_PROGRESS); // avoid initialization cycles
- boolean ok = false;
- try {
- if (monitor != null)
- monitor.subTask(Messages.bind(Messages.javamodel_configuring, initializer.getDescription(containerPath, project)));
-
- // let OperationCanceledException go through
- // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=59363)
- initializer.initialize(containerPath, project);
-
- if (monitor != null)
- monitor.subTask(""); //$NON-NLS-1$
-
- // retrieve value (if initialization was successful)
- container = containerGet(project, containerPath);
- if (container == CONTAINER_INITIALIZATION_IN_PROGRESS) {
- // initializer failed to do its job: redirect to the failure container
- container = initializer.getFailureContainer(containerPath, project);
- if (container == null)
- return null; // break cycle
- containerPut(project, containerPath, container);
- }
- ok = true;
- } catch (CoreException e) {
- if (e instanceof JavaScriptModelException) {
- throw (JavaScriptModelException) e;
- } else {
- throw new JavaScriptModelException(e);
- }
- } catch (RuntimeException e) {
- if (JavaModelManager.CP_RESOLVE_VERBOSE) {
- e.printStackTrace();
- }
- throw e;
- } catch (Error e) {
- if (JavaModelManager.CP_RESOLVE_VERBOSE) {
- e.printStackTrace();
- }
- throw e;
- } finally {
- if(JavaModelManager.PERF_CONTAINER_INITIALIZER) {
- stats.endRun();
- }
- if (!ok) {
- // just remove initialization in progress and keep previous session container so as to avoid a full build
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=92588
- containerRemoveInitializationInProgress(project, containerPath);
- if (CP_RESOLVE_VERBOSE)
- verbose_container_initialization_failed(project, containerPath, container, initializer);
- }
- }
- if (CP_RESOLVE_VERBOSE_ADVANCED)
- verbose_container_value_after_initialization(project, containerPath, container);
- } else {
- // create a dummy initializer and get the default failure container
- container = (new JsGlobalScopeContainerInitializer() {
- public void initialize(IPath path, IJavaScriptProject javaProject) throws CoreException {
- // not used
- }
-
- public LibraryLocation getLibraryLocation() {
- return null;
- }
- }).getFailureContainer(containerPath, project);
- if (CP_RESOLVE_VERBOSE_ADVANCED)
- verbose_no_container_initializer_found(project, containerPath);
- }
- return container;
- }
-
- private void verbose_no_container_initializer_found(IJavaScriptProject project, IPath containerPath) {
- Util.verbose(
- "CPContainer INIT - no initializer found\n" + //$NON-NLS-1$
- " project: " + project.getElementName() + '\n' + //$NON-NLS-1$
- " container path: " + containerPath); //$NON-NLS-1$
- }
-
- private void verbose_container_value_after_initialization(IJavaScriptProject project, IPath containerPath, IJsGlobalScopeContainer container) {
- StringBuffer buffer = new StringBuffer();
- buffer.append("CPContainer INIT - after resolution\n"); //$NON-NLS-1$
- buffer.append(" project: " + project.getElementName() + '\n'); //$NON-NLS-1$
- buffer.append(" container path: " + containerPath + '\n'); //$NON-NLS-1$
- if (container != null){
- buffer.append(" container: "+container.getDescription()+" {\n"); //$NON-NLS-2$//$NON-NLS-1$
- IIncludePathEntry[] entries = container.getIncludepathEntries();
- if (entries != null){
- for (int i = 0; i < entries.length; i++) {
- buffer.append(" " + entries[i] + '\n'); //$NON-NLS-1$
- }
- }
- buffer.append(" }");//$NON-NLS-1$
- } else {
- buffer.append(" container: {unbound}");//$NON-NLS-1$
- }
- Util.verbose(buffer.toString());
- }
-
- private void verbose_container_initialization_failed(IJavaScriptProject project, IPath containerPath, IJsGlobalScopeContainer container, JsGlobalScopeContainerInitializer initializer) {
- if (container == CONTAINER_INITIALIZATION_IN_PROGRESS) {
- Util.verbose(
- "CPContainer INIT - FAILED (initializer did not initialize container)\n" + //$NON-NLS-1$
- " project: " + project.getElementName() + '\n' + //$NON-NLS-1$
- " container path: " + containerPath + '\n' + //$NON-NLS-1$
- " initializer: " + initializer); //$NON-NLS-1$
-
- } else {
- Util.verbose(
- "CPContainer INIT - FAILED (see exception above)\n" + //$NON-NLS-1$
- " project: " + project.getElementName() + '\n' + //$NON-NLS-1$
- " container path: " + containerPath + '\n' + //$NON-NLS-1$
- " initializer: " + initializer); //$NON-NLS-1$
- }
- }
-
- private void verbose_triggering_container_initialization(IJavaScriptProject project, IPath containerPath, JsGlobalScopeContainerInitializer initializer) {
- Util.verbose(
- "CPContainer INIT - triggering initialization\n" + //$NON-NLS-1$
- " project: " + project.getElementName() + '\n' + //$NON-NLS-1$
- " container path: " + containerPath + '\n' + //$NON-NLS-1$
- " initializer: " + initializer); //$NON-NLS-1$
- }
-
- private void verbose_triggering_container_initialization_invocation_trace() {
- Util.verbose(
- "CPContainer INIT - triggering initialization\n" + //$NON-NLS-1$
- " invocation trace:"); //$NON-NLS-1$
- new Exception("<Fake exception>").printStackTrace(System.out); //$NON-NLS-1$
- }
-
- /**
- * Initialize preferences lookups for JavaScriptCore plugin.
- */
- public void initializePreferences() {
-
- // Create lookups
- preferencesLookup[PREF_INSTANCE] = ((IScopeContext) new InstanceScope()).getNode(JavaScriptCore.PLUGIN_ID);
- preferencesLookup[PREF_DEFAULT] = ((IScopeContext) new DefaultScope()).getNode(JavaScriptCore.PLUGIN_ID);
-
- // Listen to instance preferences node removal from parent in order to refresh stored one
- IEclipsePreferences.INodeChangeListener listener = new IEclipsePreferences.INodeChangeListener() {
- public void added(IEclipsePreferences.NodeChangeEvent event) {
- // do nothing
- }
- public void removed(IEclipsePreferences.NodeChangeEvent event) {
- if (event.getChild() == preferencesLookup[PREF_INSTANCE]) {
- preferencesLookup[PREF_INSTANCE] = ((IScopeContext) new InstanceScope()).getNode(JavaScriptCore.PLUGIN_ID);
- preferencesLookup[PREF_INSTANCE].addPreferenceChangeListener(new EclipsePreferencesListener());
- }
- }
- };
- ((IEclipsePreferences) preferencesLookup[PREF_INSTANCE].parent()).addNodeChangeListener(listener);
- preferencesLookup[PREF_INSTANCE].addPreferenceChangeListener(new EclipsePreferencesListener());
-
- // Listen to default preferences node removal from parent in order to refresh stored one
- listener = new IEclipsePreferences.INodeChangeListener() {
- public void added(IEclipsePreferences.NodeChangeEvent event) {
- // do nothing
- }
- public void removed(IEclipsePreferences.NodeChangeEvent event) {
- if (event.getChild() == preferencesLookup[PREF_DEFAULT]) {
- preferencesLookup[PREF_DEFAULT] = ((IScopeContext) new DefaultScope()).getNode(JavaScriptCore.PLUGIN_ID);
- }
- }
- };
- ((IEclipsePreferences) preferencesLookup[PREF_DEFAULT].parent()).addNodeChangeListener(listener);
- }
-
- public synchronized char[] intern(char[] array) {
- return this.charArraySymbols.add(array);
- }
-
- public synchronized String intern(String s) {
- // make sure to copy the string (so that it doesn't hold on the underlying char[] that might be much bigger than necessary)
- return (String) this.stringSymbols.add(new String(s));
-
- // Note1: String#intern() cannot be used as on some VMs this prevents the string from being garbage collected
- // Note 2: Instead of using a WeakHashset, one could use a WeakHashMap with the following implementation
- // This would costs more per entry (one Entry object and one WeakReference more))
-
- /*
- WeakReference reference = (WeakReference) this.symbols.get(s);
- String existing;
- if (reference != null && (existing = (String) reference.get()) != null)
- return existing;
- this.symbols.put(s, new WeakReference(s));
- return s;
- */
- }
-
- private HashSet getClasspathBeingResolved() {
- HashSet result = (HashSet) this.classpathsBeingResolved.get();
- if (result == null) {
- result = new HashSet();
- this.classpathsBeingResolved.set(result);
- }
- return result;
- }
-
- public boolean isClasspathBeingResolved(IJavaScriptProject project) {
- return getClasspathBeingResolved().contains(project);
- }
-
- /**
- * @deprecated
- */
- private boolean isDeprecatedOption(String optionName) {
- return JavaScriptCore.COMPILER_PB_INVALID_IMPORT.equals(optionName)
- || JavaScriptCore.COMPILER_PB_UNREACHABLE_CODE.equals(optionName);
- }
-
- public void setClasspathBeingResolved(IJavaScriptProject project, boolean classpathIsResolved) {
- if (classpathIsResolved) {
- getClasspathBeingResolved().add(project);
- } else {
- getClasspathBeingResolved().remove(project);
- }
- }
-
- public void loadVariablesAndContainers() throws CoreException {
- // backward compatibility, consider persistent property
- QualifiedName qName = new QualifiedName(JavaScriptCore.PLUGIN_ID, "variables"); //$NON-NLS-1$
- String xmlString = ResourcesPlugin.getWorkspace().getRoot().getPersistentProperty(qName);
-
- try {
- if (xmlString != null){
- StringReader reader = new StringReader(xmlString);
- Element cpElement;
- try {
- DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
- cpElement = parser.parse(new InputSource(reader)).getDocumentElement();
- } catch(SAXException e) {
- return;
- } catch(ParserConfigurationException e){
- return;
- } finally {
- reader.close();
- }
- if (cpElement == null) return;
- if (!cpElement.getNodeName().equalsIgnoreCase("variables")) { //$NON-NLS-1$
- return;
- }
-
- NodeList list= cpElement.getChildNodes();
- int length= list.getLength();
- for (int i= 0; i < length; ++i) {
- Node node= list.item(i);
- short type= node.getNodeType();
- if (type == Node.ELEMENT_NODE) {
- Element element= (Element) node;
- if (element.getNodeName().equalsIgnoreCase("variable")) { //$NON-NLS-1$
- variablePut(
- element.getAttribute("name"), //$NON-NLS-1$
- new Path(element.getAttribute("path"))); //$NON-NLS-1$
- }
- }
- }
- }
- } catch(IOException e){
- // problem loading xml file: nothing we can do
- } finally {
- if (xmlString != null){
- ResourcesPlugin.getWorkspace().getRoot().setPersistentProperty(qName, null); // flush old one
- }
- }
-
- // backward compatibility, load variables and containers from preferences into cache
- loadVariablesAndContainers(getDefaultPreferences());
- loadVariablesAndContainers(getInstancePreferences());
-
- // load variables and containers from saved file into cache
- File file = getVariableAndContainersFile();
- DataInputStream in = null;
- try {
- in = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
- switch (in.readInt()) {
- case 2 :
- new VariablesAndContainersLoadHelper(in).load();
- break;
- case 1 : // backward compatibility, load old format
- // variables
- int size = in.readInt();
- while (size-- > 0) {
- String varName = in.readUTF();
- String pathString = in.readUTF();
- if (CP_ENTRY_IGNORE.equals(pathString))
- continue;
- IPath varPath = Path.fromPortableString(pathString);
- this.variables.put(varName, varPath);
- this.previousSessionVariables.put(varName, varPath);
- }
-
- // containers
- IJavaScriptModel model = getJavaModel();
- int projectSize = in.readInt();
- while (projectSize-- > 0) {
- String projectName = in.readUTF();
- IJavaScriptProject project = model.getJavaScriptProject(projectName);
- int containerSize = in.readInt();
- while (containerSize-- > 0) {
- IPath containerPath = Path.fromPortableString(in.readUTF());
- int length = in.readInt();
- byte[] containerString = new byte[length];
- in.readFully(containerString);
- recreatePersistedContainer(project, containerPath, new String(containerString), true/*add to container values*/);
- }
- }
- break;
- }
- } catch (IOException e) {
- if (file.exists())
- Util.log(e, "Unable to read variable and containers file"); //$NON-NLS-1$
- } catch (RuntimeException e) {
- if (file.exists())
- Util.log(e, "Unable to read variable and containers file (file is corrupt)"); //$NON-NLS-1$
- } finally {
- if (in != null) {
- try {
- in.close();
- } catch (IOException e) {
- // nothing we can do: ignore
- }
- }
- }
-
- // override persisted values for variables which have a registered initializer
- String[] registeredVariables = getRegisteredVariableNames();
- for (int i = 0; i < registeredVariables.length; i++) {
- String varName = registeredVariables[i];
- this.variables.put(varName, null); // reset variable, but leave its entry in the Map, so it will be part of variable names.
- }
- // override persisted values for containers which have a registered initializer
- containersReset(getRegisteredContainerIDs());
- }
-
- private void loadVariablesAndContainers(IEclipsePreferences preferences) {
- try {
- // only get variable from preferences not set to their default
- String[] propertyNames = preferences.keys();
- int variablePrefixLength = CP_VARIABLE_PREFERENCES_PREFIX.length();
- for (int i = 0; i < propertyNames.length; i++){
- String propertyName = propertyNames[i];
- if (propertyName.startsWith(CP_VARIABLE_PREFERENCES_PREFIX)){
- String varName = propertyName.substring(variablePrefixLength);
- String propertyValue = preferences.get(propertyName, null);
- if (propertyValue != null) {
- String pathString = propertyValue.trim();
-
- if (CP_ENTRY_IGNORE.equals(pathString)) {
- // cleanup old preferences
- preferences.remove(propertyName);
- continue;
- }
-
- // add variable to table
- IPath varPath = new Path(pathString);
- this.variables.put(varName, varPath);
- this.previousSessionVariables.put(varName, varPath);
- }
- } else if (propertyName.startsWith(CP_CONTAINER_PREFERENCES_PREFIX)){
- String propertyValue = preferences.get(propertyName, null);
- if (propertyValue != null) {
- // cleanup old preferences
- preferences.remove(propertyName);
-
- // recreate container
- recreatePersistedContainer(propertyName, propertyValue, true/*add to container values*/);
- }
- }
- }
- } catch (BackingStoreException e1) {
- // TODO (frederic) see if it's necessary to report this failure...
- }
- }
-
- private static final class PersistedJsGlobalScopeContainer implements
- IJsGlobalScopeContainer {
-
- private final IPath containerPath;
-
- private final IIncludePathEntry[] entries;
-
- private final IJavaScriptProject project;
-
- PersistedJsGlobalScopeContainer(IJavaScriptProject project, IPath containerPath,
- IIncludePathEntry[] entries) {
- super();
- this.containerPath = containerPath;
- this.entries = entries;
- this.project = project;
- }
-
- /**
- * @deprecated Use {@link #getIncludepathEntries()} instead
- */
- public IIncludePathEntry[] getClasspathEntries() {
- return getIncludepathEntries();
- }
-
- public IIncludePathEntry[] getIncludepathEntries() {
- return entries;
- }
-
- public String getDescription() {
- return "Persisted container [" + containerPath //$NON-NLS-1$
- + " for project [" + project.getElementName() //$NON-NLS-1$
- + "]]"; //$NON-NLS-1$
- }
-
- public int getKind() {
- return 0;
- }
-
- public IPath getPath() {
- return containerPath;
- }
-
- public String toString() {
- return getDescription();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer#resolvedLibraryImport(java.lang.String)
- */
- public String[] resolvedLibraryImport(String a) {
- return new String[] {a};
- }
- }
-
- private final class VariablesAndContainersLoadHelper {
-
- private static final int ARRAY_INCREMENT = 200;
-
- private IIncludePathEntry[] allClasspathEntries;
- private int allClasspathEntryCount;
-
- private final Map allPaths; // String -> IPath
-
- private String[] allStrings;
- private int allStringsCount;
-
- private final DataInputStream in;
-
- VariablesAndContainersLoadHelper(DataInputStream in) {
- super();
- this.allClasspathEntries = null;
- this.allClasspathEntryCount = 0;
- this.allPaths = new HashMap();
- this.allStrings = null;
- this.allStringsCount = 0;
- this.in = in;
- }
-
- void load() throws IOException {
- loadProjects(JavaModelManager.this.getJavaModel());
- loadVariables();
- }
-
- private IAccessRule loadAccessRule() throws IOException {
- int problemId = loadInt();
- IPath pattern = loadPath();
- return new ClasspathAccessRule(pattern.toString().toCharArray(), problemId);
- }
-
- private IAccessRule[] loadAccessRules() throws IOException {
- int count = loadInt();
-
- if (count == 0)
- return ClasspathEntry.NO_ACCESS_RULES;
-
- IAccessRule[] rules = new IAccessRule[count];
-
- for (int i = 0; i < count; ++i)
- rules[i] = loadAccessRule();
-
- return rules;
- }
-
- private IIncludePathAttribute loadAttribute() throws IOException {
- String name = loadString();
- String value = loadString();
-
- return new ClasspathAttribute(name, value);
- }
-
- private IIncludePathAttribute[] loadAttributes() throws IOException {
- int count = loadInt();
-
- if (count == 0)
- return ClasspathEntry.NO_EXTRA_ATTRIBUTES;
-
- IIncludePathAttribute[] attributes = new IIncludePathAttribute[count];
-
- for (int i = 0; i < count; ++i)
- attributes[i] = loadAttribute();
-
- return attributes;
- }
-
- private boolean loadBoolean() throws IOException {
- return this.in.readBoolean();
- }
-
- private IIncludePathEntry[] loadClasspathEntries() throws IOException {
- int count = loadInt();
- IIncludePathEntry[] entries = new IIncludePathEntry[count];
-
- for (int i = 0; i < count; ++i)
- entries[i] = loadClasspathEntry();
-
- return entries;
- }
-
- private IIncludePathEntry loadClasspathEntry() throws IOException {
- int id = loadInt();
-
- if (id < 0 || id > this.allClasspathEntryCount)
- throw new IOException("Unexpected classpathentry id"); //$NON-NLS-1$
-
- if (id < this.allClasspathEntryCount)
- return this.allClasspathEntries[id];
-
- int contentKind = loadInt();
- int entryKind = loadInt();
- IPath path = loadPath();
- IPath[] inclusionPatterns = loadPaths();
- IPath[] exclusionPatterns = loadPaths();
- IPath sourceAttachmentPath = loadPath();
- IPath sourceAttachmentRootPath = loadPath();
- IPath specificOutputLocation = loadPath();
- boolean isExported = loadBoolean();
- IAccessRule[] accessRules = loadAccessRules();
- boolean combineAccessRules = loadBoolean();
- IIncludePathAttribute[] extraAttributes = loadAttributes();
-
- IIncludePathEntry entry = new ClasspathEntry(contentKind, entryKind,
- path, inclusionPatterns, exclusionPatterns,
- sourceAttachmentPath, sourceAttachmentRootPath,
- specificOutputLocation, isExported, accessRules,
- combineAccessRules, extraAttributes);
-
- IIncludePathEntry[] array = this.allClasspathEntries;
-
- if (array == null || id == array.length) {
- array = new IIncludePathEntry[id + ARRAY_INCREMENT];
-
- if (id != 0)
- System.arraycopy(this.allClasspathEntries, 0, array, 0, id);
-
- this.allClasspathEntries = array;
- }
-
- array[id] = entry;
- this.allClasspathEntryCount = id + 1;
-
- return entry;
- }
-
- private void loadContainers(IJavaScriptProject project) throws IOException {
- boolean projectIsAccessible = project.getProject().isAccessible();
- int count = loadInt();
- for (int i = 0; i < count; ++i) {
- IPath path = loadPath();
- IIncludePathEntry[] entries = loadClasspathEntries();
-
- if (!projectIsAccessible)
- // avoid leaking deleted project's persisted container,
- // but still read the container as it is is part of the file format
- continue;
-
- IJsGlobalScopeContainer container = new PersistedJsGlobalScopeContainer(project, path, entries);
-
- JavaModelManager.this.containerPut(project, path, container);
-
- Map oldContainers = (Map) JavaModelManager.this.previousSessionContainers.get(project);
-
- if (oldContainers == null) {
- oldContainers = new HashMap();
- JavaModelManager.this.previousSessionContainers.put(project, oldContainers);
- }
-
- oldContainers.put(path, container);
- }
- }
-
- private int loadInt() throws IOException {
- return this.in.readInt();
- }
-
- private IPath loadPath() throws IOException {
- if (loadBoolean())
- return null;
-
- String portableString = loadString();
- IPath path = (IPath) this.allPaths.get(portableString);
-
- if (path == null) {
- path = Path.fromPortableString(portableString);
- this.allPaths.put(portableString, path);
- }
-
- return path;
- }
-
- private IPath[] loadPaths() throws IOException {
- int count = loadInt();
- IPath[] pathArray = new IPath[count];
-
- for (int i = 0; i < count; ++i)
- pathArray[i] = loadPath();
-
- return pathArray;
- }
-
- private void loadProjects(IJavaScriptModel model) throws IOException {
- int count = loadInt();
-
- for (int i = 0; i < count; ++i) {
- String projectName = loadString();
-
- loadContainers(model.getJavaScriptProject(projectName));
- }
- }
-
- private String loadString() throws IOException {
- int id = loadInt();
-
- if (id < 0 || id > this.allStringsCount)
- throw new IOException("Unexpected string id"); //$NON-NLS-1$
-
- if (id < this.allStringsCount)
- return this.allStrings[id];
-
- String string = this.in.readUTF();
- String[] array = this.allStrings;
-
- if (array == null || id == array.length) {
- array = new String[id + ARRAY_INCREMENT];
-
- if (id != 0)
- System.arraycopy(this.allStrings, 0, array, 0, id);
-
- this.allStrings = array;
- }
-
- array[id] = string;
- this.allStringsCount = id + 1;
-
- return string;
- }
-
- private void loadVariables() throws IOException {
- int size = loadInt();
- Map loadedVars = new HashMap(size);
-
- for (int i = 0; i < size; ++i) {
- String varName = loadString();
- IPath varPath = loadPath();
-
- if (varPath != null)
- loadedVars.put(varName, varPath);
- }
-
- JavaModelManager.this.previousSessionVariables.putAll(loadedVars);
- JavaModelManager.this.variables.putAll(loadedVars);
- }
- }
-
- /**
- * Returns the info for this element without
- * disturbing the cache ordering.
- */
- protected synchronized Object peekAtInfo(IJavaScriptElement element) {
- HashMap tempCache = (HashMap)this.temporaryCache.get();
- if (tempCache != null) {
- Object result = tempCache.get(element);
- if (result != null) {
- return result;
- }
- }
- return this.cache.peekAtInfo(element);
- }
-
- /**
- * @see ISaveParticipant
- */
- public void prepareToSave(ISaveContext context) /*throws CoreException*/ {
- // nothing to do
- }
- /*
- * Puts the infos in the given map (keys are IJavaElements and values are JavaElementInfos)
- * in the Java model cache in an atomic way.
- * First checks that the info for the opened element (or one of its ancestors) has not been
- * added to the cache. If it is the case, another thread has opened the element (or one of
- * its ancestors). So returns without updating the cache.
- */
- protected synchronized void putInfos(IJavaScriptElement openedElement, Map newElements) {
- // remove children
- Object existingInfo = this.cache.peekAtInfo(openedElement);
- if (openedElement instanceof IParent && existingInfo instanceof JavaElementInfo) {
- IJavaScriptElement[] children = ((JavaElementInfo)existingInfo).getChildren();
- for (int i = 0, size = children.length; i < size; ++i) {
- JavaElement child = (JavaElement) children[i];
- try {
- child.close();
- } catch (JavaScriptModelException e) {
- // ignore
- }
- }
- }
-
- // Need to put any JarPackageFragmentRoot in first.
- // This is due to the way the LRU cache flushes entries.
- // When a JarPackageFragment is flused from the LRU cache, the entire
- // jar is flushed by removing the JarPackageFragmentRoot and all of its
- // children (see ElementCache.close()). If we flush the JarPackageFragment
- // when its JarPackageFragmentRoot is not in the cache and the root is about to be
- // added (during the 'while' loop), we will end up in an inconsist state.
- // Subsequent resolution against package in the jar would fail as a result.
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=102422
- // (theodora)
- for(Iterator it = newElements.entrySet().iterator(); it.hasNext(); ) {
- Map.Entry entry = (Map.Entry)it.next();
- IJavaScriptElement element = (IJavaScriptElement)entry.getKey();
-// if( element instanceof JarPackageFragmentRoot || element instanceof LibraryFragmentRoot ){
-// Object info = entry.getValue();
-// it.remove();
-// this.cache.putInfo(element, info);
-// }
- }
-
- Iterator iterator = newElements.entrySet().iterator();
- while (iterator.hasNext()) {
- Map.Entry entry = (Map.Entry) iterator.next();
- this.cache.putInfo((IJavaScriptElement) entry.getKey(), entry.getValue());
- }
- }
-
- /*
- * Remember the info for the jar binary type
- */
- protected synchronized void putJarTypeInfo(IJavaScriptElement type, Object info) {
- this.cache.jarTypeCache.put(type, info);
- }
-
- /**
- * Reads the build state for the relevant project.
- */
- protected Object readState(IProject project) throws CoreException {
- File file = getSerializationFile(project);
- if (file != null && file.exists()) {
- try {
- DataInputStream in= new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
- try {
- String pluginID= in.readUTF();
- if (!pluginID.equals(JavaScriptCore.PLUGIN_ID))
- throw new IOException(Messages.build_wrongFileFormat);
- String kind= in.readUTF();
- if (!kind.equals("STATE")) //$NON-NLS-1$
- throw new IOException(Messages.build_wrongFileFormat);
- if (in.readBoolean())
- return JavaBuilder.readState(project, in);
- if (JavaBuilder.DEBUG)
- System.out.println("Saved state thinks last build failed for " + project.getName()); //$NON-NLS-1$
- } finally {
- in.close();
- }
- } catch (Exception e) {
- e.printStackTrace();
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, Platform.PLUGIN_ERROR, "Error reading last build state for project "+ project.getName(), e)); //$NON-NLS-1$
- }
- } else if (JavaBuilder.DEBUG) {
- if (file == null)
- System.out.println("Project does not exist: " + project); //$NON-NLS-1$
- else
- System.out.println("Build state file " + file.getPath() + " does not exist"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- return null;
- }
-
- public static void recreatePersistedContainer(String propertyName, String containerString, boolean addToContainerValues) {
- int containerPrefixLength = CP_CONTAINER_PREFERENCES_PREFIX.length();
- int index = propertyName.indexOf('|', containerPrefixLength);
- if (containerString != null) containerString = containerString.trim();
- if (index > 0) {
- String projectName = propertyName.substring(containerPrefixLength, index).trim();
- IJavaScriptProject project = getJavaModelManager().getJavaModel().getJavaScriptProject(projectName);
- IPath containerPath = new Path(propertyName.substring(index+1).trim());
- recreatePersistedContainer(project, containerPath, containerString, addToContainerValues);
- }
- }
-
- private static void recreatePersistedContainer(final IJavaScriptProject project, final IPath containerPath, String containerString, boolean addToContainerValues) {
- if (!project.getProject().isAccessible()) return; // avoid leaking deleted project's persisted container
- if (containerString == null) {
- getJavaModelManager().containerPut(project, containerPath, null);
- } else {
- IIncludePathEntry[] entries;
- try {
- entries = ((JavaProject) project).decodeClasspath(containerString, null/*not interested in unknown elements*/);
- } catch (IOException e) {
- Util.log(e, "Could not recreate persisted container: \n" + containerString); //$NON-NLS-1$
- entries = JavaProject.INVALID_CLASSPATH;
- }
- if (entries != JavaProject.INVALID_CLASSPATH) {
- final IIncludePathEntry[] containerEntries = entries;
- IJsGlobalScopeContainer container = new IJsGlobalScopeContainer() {
- /**
- * @deprecated Use {@link #getIncludepathEntries()} instead
- */
- public IIncludePathEntry[] getClasspathEntries() {
- return getIncludepathEntries();
- }
- public IIncludePathEntry[] getIncludepathEntries() {
- return containerEntries;
- }
- public String getDescription() {
- return "Persisted container ["+containerPath+" for project ["+ project.getElementName()+"]"; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
- }
- public int getKind() {
- return 0;
- }
- public IPath getPath() {
- return containerPath;
- }
- public String toString() {
- return getDescription();
- }
- public String[] resolvedLibraryImport(String a) {
- return new String[] {a};
- }
-
- };
- if (addToContainerValues) {
- getJavaModelManager().containerPut(project, containerPath, container);
- }
- Map projectContainers = (Map)getJavaModelManager().previousSessionContainers.get(project);
- if (projectContainers == null){
- projectContainers = new HashMap(1);
- getJavaModelManager().previousSessionContainers.put(project, projectContainers);
- }
- projectContainers.put(containerPath, container);
- }
- }
- }
-
- /**
- * Remembers the given scope in a weak set
- * (so no need to remove it: it will be removed by the garbage collector)
- */
- public void rememberScope(AbstractSearchScope scope) {
- // NB: The value has to be null so as to not create a strong reference on the scope
- this.searchScopes.put(scope, null);
- }
-
- /*
- * Removes all cached info for the given element (including all children)
- * from the cache.
- * Returns the info for the given element, or null if it was closed.
- */
- public synchronized Object removeInfoAndChildren(JavaElement element) throws JavaScriptModelException {
- Object info = this.cache.peekAtInfo(element);
- if (info != null) {
- boolean wasVerbose = false;
- try {
- if (JavaModelCache.VERBOSE) {
- String elementType;
- switch (element.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- elementType = "project"; //$NON-NLS-1$
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- elementType = "root"; //$NON-NLS-1$
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- elementType = "package"; //$NON-NLS-1$
- break;
- case IJavaScriptElement.CLASS_FILE:
- elementType = "class file"; //$NON-NLS-1$
- break;
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- elementType = "compilation unit"; //$NON-NLS-1$
- break;
- default:
- elementType = "element"; //$NON-NLS-1$
- }
- System.out.println(Thread.currentThread() + " CLOSING "+ elementType + " " + element.toStringWithAncestors()); //$NON-NLS-1$//$NON-NLS-2$
- wasVerbose = true;
- JavaModelCache.VERBOSE = false;
- }
- element.closing(info);
- if (element instanceof IParent && info instanceof JavaElementInfo) {
- IJavaScriptElement[] children = ((JavaElementInfo)info).getChildren();
- for (int i = 0, size = children.length; i < size; ++i) {
- JavaElement child = (JavaElement) children[i];
- child.close();
- }
- }
- this.cache.removeInfo(element);
- if (wasVerbose) {
- System.out.println(this.cache.toStringFillingRation("-> ")); //$NON-NLS-1$
- }
- } finally {
- JavaModelCache.VERBOSE = wasVerbose;
- }
- return info;
- }
- return null;
- }
-
- public void removePerProjectInfo(JavaProject javaProject) {
- synchronized(this.perProjectInfos) { // use the perProjectInfo collection as its own lock
- IProject project = javaProject.getProject();
- PerProjectInfo info= (PerProjectInfo) this.perProjectInfos.get(project);
- if (info != null) {
- this.perProjectInfos.remove(project);
- }
- }
- }
-
- /*
- * Reset project options stored in info cache.
- */
- public void resetProjectOptions(JavaProject javaProject) {
- synchronized(this.perProjectInfos) { // use the perProjectInfo collection as its own lock
- IProject project = javaProject.getProject();
- PerProjectInfo info= (PerProjectInfo) this.perProjectInfos.get(project);
- if (info != null) {
- info.options = null;
- }
- }
- }
-
- /*
- * Reset project preferences stored in info cache.
- */
- public void resetProjectPreferences(JavaProject javaProject) {
- synchronized(this.perProjectInfos) { // use the perProjectInfo collection as its own lock
- IProject project = javaProject.getProject();
- PerProjectInfo info= (PerProjectInfo) this.perProjectInfos.get(project);
- if (info != null) {
- info.preferences = null;
- }
- }
- }
-
- public static final void doNotUse() {
- // used by tests to simulate a startup
- MANAGER = new JavaModelManager();
- }
-
- /*
- * Resets the cache that holds on binary type in jar files
- */
- protected synchronized void resetJarTypeCache() {
- this.cache.resetJarTypeCache();
- }
-
- /*
- * Resets the temporary cache for newly created elements to null.
- */
- public void resetTemporaryCache() {
- this.temporaryCache.set(null);
- }
-
- /**
- * @see ISaveParticipant
- */
- public void rollback(ISaveContext context){
- // nothing to do
- }
-
- private void saveState(PerProjectInfo info, ISaveContext context) throws CoreException {
-
- // passed this point, save actions are non trivial
- if (context.getKind() == ISaveContext.SNAPSHOT) return;
-
- // save built state
- if (info.triedRead) saveBuiltState(info);
- }
-
- /**
- * Saves the built state for the project.
- */
- private void saveBuiltState(PerProjectInfo info) throws CoreException {
- if (JavaBuilder.DEBUG)
- System.out.println(Messages.bind(Messages.build_saveStateProgress, info.project.getName()));
- File file = getSerializationFile(info.project);
- if (file == null) return;
- long t = System.currentTimeMillis();
- try {
- DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
- try {
- out.writeUTF(JavaScriptCore.PLUGIN_ID);
- out.writeUTF("STATE"); //$NON-NLS-1$
- if (info.savedState == null) {
- out.writeBoolean(false);
- } else {
- out.writeBoolean(true);
- JavaBuilder.writeState(info.savedState, out);
- }
- } finally {
- out.close();
- }
- } catch (RuntimeException e) {
- try {
- file.delete();
- } catch(SecurityException se) {
- // could not delete file: cannot do much more
- }
- throw new CoreException(
- new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, Platform.PLUGIN_ERROR,
- Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e));
- } catch (IOException e) {
- try {
- file.delete();
- } catch(SecurityException se) {
- // could not delete file: cannot do much more
- }
- throw new CoreException(
- new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, Platform.PLUGIN_ERROR,
- Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e));
- }
- if (JavaBuilder.DEBUG) {
- t = System.currentTimeMillis() - t;
- System.out.println(Messages.bind(Messages.build_saveStateComplete, String.valueOf(t)));
- }
- }
-
- private void saveVariablesAndContainers(ISaveContext context) throws CoreException {
- File file = getVariableAndContainersFile();
- DataOutputStream out = null;
- try {
- out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
- out.writeInt(VARIABLES_AND_CONTAINERS_FILE_VERSION);
- if (VARIABLES_AND_CONTAINERS_FILE_VERSION != 1)
- new VariablesAndContainersSaveHelper(out).save(context);
- else {
- // old code retained for performance comparisons
-
- // variables
- out.writeInt(this.variables.size());
- Iterator iterator = this.variables.entrySet().iterator();
- while (iterator.hasNext()) {
- Map.Entry entry = (Map.Entry) iterator.next();
- String variableName = (String) entry.getKey();
- out.writeUTF(variableName);
- IPath path = (IPath) entry.getValue();
- out.writeUTF(path == null ? CP_ENTRY_IGNORE : path.toPortableString());
- }
-
- // containers
- IJavaScriptProject[] projects = getJavaModel().getJavaScriptProjects();
- int length = projects.length;
- out.writeInt(length);
- for (int i = 0; i < length; i++) {
- IJavaScriptProject project = projects[i];
- // clone while iterating (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=59638)
- Map projectContainers = containerClone(project);
- out.writeUTF(project.getElementName());
- if (projectContainers == null) {
- out.writeInt(0);
- continue;
- }
- HashMap containersToSave = new HashMap();
- for (iterator = projectContainers.entrySet().iterator(); iterator.hasNext();) {
- Map.Entry entry = (Map.Entry) iterator.next();
- IPath containerPath = (IPath) entry.getKey();
- IJsGlobalScopeContainer container = (IJsGlobalScopeContainer) entry.getValue();
- String containerString = null;
- try {
- if (container == null) {
- // container has not been initialized yet, use previous session value
- // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=73969)
- container = getPreviousSessionContainer(containerPath, project);
- }
- if (container != null) {
- IIncludePathEntry[] entries = container.getIncludepathEntries();
- containerString = ((JavaProject)project).encodeClasspath(
- entries,
- null,
- false,
- null/*not interested in unknown elements*/);
- }
- } catch(JavaScriptModelException e){
- // could not encode entry: will not persist
- Util.log(e, "Could not persist container " + containerPath + " for project " + project.getElementName()); //$NON-NLS-1$ //$NON-NLS-2$
- }
- if (containerString != null)
- containersToSave.put(containerPath, containerString);
- }
- out.writeInt(containersToSave.size());
- iterator = containersToSave.entrySet().iterator();
- while (iterator.hasNext()) {
- Map.Entry entry = (Map.Entry) iterator.next();
- IPath containerPath = (IPath) entry.getKey();
- out.writeUTF(containerPath.toPortableString());
- String containerString = (String) entry.getValue();
- out.writeInt(containerString.length());
- out.writeBytes(containerString);
- }
- }
- }
- } catch (IOException e) {
- IStatus status = new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving variables and containers", e); //$NON-NLS-1$
- throw new CoreException(status);
- } finally {
- if (out != null) {
- try {
- out.close();
- } catch (IOException e) {
- // nothing we can do: ignore
- }
- }
- }
- }
-
- private final class VariablesAndContainersSaveHelper {
-
- private final HashtableOfObjectToInt classpathEntryIds; // IIncludePathEntry -> int
- private final DataOutputStream out;
- private final HashtableOfObjectToInt stringIds; // Strings -> int
-
- VariablesAndContainersSaveHelper(DataOutputStream out) {
- super();
- this.classpathEntryIds = new HashtableOfObjectToInt();
- this.out = out;
- this.stringIds = new HashtableOfObjectToInt();
- }
-
- void save(ISaveContext context) throws IOException, JavaScriptModelException {
- IProject project = context.getProject();
- if (project == null) { // save all projects if none specified (snapshot or full save)
- saveProjects(JavaModelManager.this.getJavaModel().getJavaScriptProjects());
- }
- else {
- saveProjects(new IJavaScriptProject[] {JavaScriptCore.create(project)});
- }
-
- switch (context.getKind()) {
- case ISaveContext.FULL_SAVE :
- // TODO (eric) - investigate after 3.3 if variables should be saved for a SNAPSHOT
- case ISaveContext.SNAPSHOT :
- // remove variables that should not be saved
- HashMap varsToSave = null;
- Iterator iterator = JavaModelManager.this.variables.entrySet().iterator();
- IEclipsePreferences defaultPreferences = getDefaultPreferences();
- while (iterator.hasNext()) {
- Map.Entry entry = (Map.Entry) iterator.next();
- String varName = (String) entry.getKey();
- if (defaultPreferences.get(CP_VARIABLE_PREFERENCES_PREFIX + varName, null) != null // don't save classpath variables from the default preferences as there is no delta if they are removed
- || CP_ENTRY_IGNORE_PATH.equals(entry.getValue())) {
-
- if (varsToSave == null)
- varsToSave = new HashMap(JavaModelManager.this.variables);
- varsToSave.remove(varName);
- }
- }
- saveVariables(varsToSave != null ? varsToSave : JavaModelManager.this.variables);
- break;
- default :
- // do nothing
- }
- }
-
- private void saveAccessRule(ClasspathAccessRule rule) throws IOException {
- saveInt(rule.problemId);
- savePath(rule.getPattern());
- }
-
- private void saveAccessRules(IAccessRule[] rules) throws IOException {
- int count = rules == null ? 0 : rules.length;
-
- saveInt(count);
- for (int i = 0; i < count; ++i)
- saveAccessRule((ClasspathAccessRule) rules[i]);
- }
-
- private void saveAttribute(IIncludePathAttribute attribute)
- throws IOException {
- saveString(attribute.getName());
- saveString(attribute.getValue());
- }
-
- private void saveAttributes(IIncludePathAttribute[] attributes)
- throws IOException {
- int count = attributes == null ? 0 : attributes.length;
-
- saveInt(count);
- for (int i = 0; i < count; ++i)
- saveAttribute(attributes[i]);
- }
-
- private void saveClasspathEntries(IIncludePathEntry[] entries)
- throws IOException {
- int count = entries == null ? 0 : entries.length;
-
- saveInt(count);
- for (int i = 0; i < count; ++i)
- saveClasspathEntry(entries[i]);
- }
-
- private void saveClasspathEntry(IIncludePathEntry entry)
- throws IOException {
- if (saveNewId(entry, this.classpathEntryIds)) {
- saveInt(entry.getContentKind());
- saveInt(entry.getEntryKind());
- savePath(entry.getPath());
- savePaths(entry.getInclusionPatterns());
- savePaths(entry.getExclusionPatterns());
- savePath(entry.getSourceAttachmentPath());
- savePath(entry.getSourceAttachmentRootPath());
- savePath(Path.EMPTY);
- this.out.writeBoolean(entry.isExported());
- saveAccessRules(entry.getAccessRules());
- this.out.writeBoolean(entry.combineAccessRules());
- saveAttributes(entry.getExtraAttributes());
- }
- }
-
- private void saveContainers(IJavaScriptProject project, Map containerMap)
- throws IOException {
- saveInt(containerMap.size());
-
- for (Iterator i = containerMap.entrySet().iterator(); i.hasNext();) {
- Entry entry = (Entry) i.next();
- IPath path = (IPath) entry.getKey();
- IJsGlobalScopeContainer container = (IJsGlobalScopeContainer) entry.getValue();
- IIncludePathEntry[] cpEntries = null;
-
- if (container == null) {
- // container has not been initialized yet, use previous
- // session value
- // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=73969)
- container = JavaModelManager.this.getPreviousSessionContainer(path, project);
- }
-
- if (container != null)
- cpEntries = container.getIncludepathEntries();
-
- savePath(path);
- saveClasspathEntries(cpEntries);
- }
- }
-
- private void saveInt(int value) throws IOException {
- this.out.writeInt(value);
- }
-
- private boolean saveNewId(Object key, HashtableOfObjectToInt map) throws IOException {
- int id = map.get(key);
-
- if (id == -1) {
- int newId = map.size();
-
- map.put(key, newId);
-
- saveInt(newId);
-
- return true;
- } else {
- saveInt(id);
-
- return false;
- }
- }
-
- private void savePath(IPath path) throws IOException {
- if (path == null) {
- this.out.writeBoolean(true);
- } else {
- this.out.writeBoolean(false);
- saveString(path.toPortableString());
- }
- }
-
- private void savePaths(IPath[] paths) throws IOException {
- int count = paths == null ? 0 : paths.length;
-
- saveInt(count);
- for (int i = 0; i < count; ++i)
- savePath(paths[i]);
- }
-
- private void saveProjects(IJavaScriptProject[] projects) throws IOException,
- JavaScriptModelException {
- int count = projects.length;
-
- saveInt(count);
-
- for (int i = 0; i < count; ++i) {
- IJavaScriptProject project = projects[i];
-
- saveString(project.getElementName());
-
- Map containerMap = (Map) JavaModelManager.this.containers.get(project);
-
- if (containerMap == null) {
- containerMap = Collections.EMPTY_MAP;
- } else {
- // clone while iterating
- // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=59638)
- containerMap = new HashMap(containerMap);
- }
-
- saveContainers(project, containerMap);
- }
- }
-
- private void saveString(String string) throws IOException {
- if (saveNewId(string, this.stringIds))
- this.out.writeUTF(string);
- }
-
- private void saveVariables(Map map) throws IOException {
- saveInt(map.size());
-
- for (Iterator i = map.entrySet().iterator(); i.hasNext();) {
- Entry entry = (Entry) i.next();
- String varName = (String) entry.getKey();
- IPath varPath = (IPath) entry.getValue();
-
- saveString(varName);
- savePath(varPath);
- }
- }
- }
-
- private void traceVariableAndContainers(String action, long start) {
-
- Long delta = new Long(System.currentTimeMillis() - start);
- Long length = new Long(getVariableAndContainersFile().length());
- String pattern = "{0} {1} bytes in variablesAndContainers.dat in {2}ms"; //$NON-NLS-1$
- String message = MessageFormat.format(pattern, new Object[]{action, length, delta});
-
- System.out.println(message);
- }
-
- /**
- * @see ISaveParticipant
- */
- public void saving(ISaveContext context) throws CoreException {
-
- long start = -1;
- if (VERBOSE)
- start = System.currentTimeMillis();
-
- // save variable and container values on snapshot/full save
- saveVariablesAndContainers(context);
-
- if (VERBOSE)
- traceVariableAndContainers("Saved", start); //$NON-NLS-1$
-
- if (context.getKind() == ISaveContext.FULL_SAVE) {
- // will need delta since this save (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=38658)
- context.needDelta();
-
- // clean up indexes on workspace full save
- // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=52347)
- IndexManager manager = this.indexManager;
- if (manager != null
- // don't force initialization of workspace scope as we could be shutting down
- // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=93941)
- && this.workspaceScope != null) {
- manager.cleanUpIndexes();
- }
- }
-
- IProject savedProject = context.getProject();
- if (savedProject != null) {
- if (!JavaProject.hasJavaNature(savedProject)) return; // ignore
- PerProjectInfo info = getPerProjectInfo(savedProject, true /* create info */);
- saveState(info, context);
- info.rememberExternalLibTimestamps();
- return;
- }
-
- ArrayList vStats= null; // lazy initialized
- ArrayList values = null;
- synchronized(this.perProjectInfos) {
- values = new ArrayList(this.perProjectInfos.values());
- }
- Iterator iterator = values.iterator();
- while (iterator.hasNext()) {
- try {
- PerProjectInfo info = (PerProjectInfo) iterator.next();
- saveState(info, context);
- info.rememberExternalLibTimestamps();
- } catch (CoreException e) {
- if (vStats == null)
- vStats= new ArrayList();
- vStats.add(e.getStatus());
- }
- }
- if (vStats != null) {
- IStatus[] stats= new IStatus[vStats.size()];
- vStats.toArray(stats);
- throw new CoreException(new MultiStatus(JavaScriptCore.PLUGIN_ID, IStatus.ERROR, stats, Messages.build_cannotSaveStates, null));
- }
-
- // save external libs timestamps
- this.deltaState.saveExternalLibTimeStamps();
- }
-
- /**
- * Add a secondary type in temporary indexing cache for a project got from given path.
- *
- * Current secondary types cache is not modified as we want to wait that indexing
- * was finished before taking new secondary types into account.
- *
- * Indexing cache is a specific entry in secondary types cache which key is
- * {@link #INDEXED_SECONDARY_TYPES } and value a map with same structure than
- * secondary types cache itself.
- *
- * @see #secondaryTypes(IJavaScriptProject, boolean, IProgressMonitor)
- */
- public void secondaryTypeAdding(String path, char[] typeName, char[] packageName) {
- if (VERBOSE) {
- StringBuffer buffer = new StringBuffer("JavaModelManager.addSecondaryType("); //$NON-NLS-1$
- buffer.append(path);
- buffer.append(',');
- buffer.append('[');
- buffer.append(new String(packageName));
- buffer.append('.');
- buffer.append(new String(typeName));
- buffer.append(']');
- buffer.append(')');
- Util.verbose(buffer.toString());
- }
- IWorkspaceRoot wRoot = ResourcesPlugin.getWorkspace().getRoot();
- IResource resource = wRoot.findMember(path);
- if (resource != null) {
- if (org.eclipse.wst.jsdt.internal.core.util.Util.isJavaLikeFileName(path) && resource.getType() == IResource.FILE) {
- IProject project = resource.getProject();
- try {
- PerProjectInfo projectInfo = getPerProjectInfoCheckExistence(project);
- // Get or create map to cache secondary types while indexing (can be not synchronized as indexing insure a non-concurrent usage)
- HashMap indexedSecondaryTypes = null;
- if (projectInfo.secondaryTypes == null) {
- projectInfo.secondaryTypes = new Hashtable(3);
- indexedSecondaryTypes = new HashMap(3);
- projectInfo.secondaryTypes.put(INDEXED_SECONDARY_TYPES, indexedSecondaryTypes);
- } else {
- indexedSecondaryTypes = (HashMap) projectInfo.secondaryTypes.get(INDEXED_SECONDARY_TYPES);
- if (indexedSecondaryTypes == null) {
- indexedSecondaryTypes = new HashMap(3);
- projectInfo.secondaryTypes.put(INDEXED_SECONDARY_TYPES, indexedSecondaryTypes);
- }
- }
- // Store the secondary type in temporary cache (these are just handles => no problem to create it now...)
- HashMap allTypes = (HashMap) indexedSecondaryTypes.get(resource);
- if (allTypes == null) {
- allTypes = new HashMap(3);
- indexedSecondaryTypes.put(resource, allTypes);
- }
- IJavaScriptUnit unit = JavaModelManager.createCompilationUnitFrom((IFile)resource, null);
- if (unit != null) {
- String typeString = new String(typeName);
- String packageString = new String(packageName);
- HashMap packageTypes = (HashMap) allTypes.get(packageString);
- if (packageTypes == null) {
- packageTypes = new HashMap(3);
- allTypes.put(packageString, packageTypes);
- }
- packageTypes.put(typeString, unit.getType(typeString));
- }
- if (VERBOSE) {
- Util.verbose(" - indexing cache:"); //$NON-NLS-1$
- Iterator entries = indexedSecondaryTypes.entrySet().iterator();
- while (entries.hasNext()) {
- Map.Entry entry = (Map.Entry) entries.next();
- IFile file = (IFile) entry.getKey();
- Util.verbose(" + "+file.getFullPath()+':'+ entry.getValue()); //$NON-NLS-1$
- }
- }
- }
- catch (JavaScriptModelException jme) {
- // do nothing
- }
- }
- }
- }
-
- /**
- * Get all secondary types for a project and store result in per project info cache.
- *
- * This cache is an Hashtable<String, HashMap<String, IType>>:
- * - key: package name
- * - value:
- * + key: type name
- * + value: java model handle for the secondary type
- * Hashtable was used to protect callers from possible concurrent access.
- *
- * Note that this map may have a specific entry which key is {@link #INDEXED_SECONDARY_TYPES }
- * and value is a map containing all secondary types created during indexing.
- * When this key is in cache and indexing is finished, returned map is merged
- * with the value of this special key. If indexing is not finished and caller does
- * not wait for the end of indexing, returned map is the current secondary
- * types cache content which may be invalid...
- *
- * @param project Project we want get secondary types from
- * @return HashMap Table of secondary type names->path for given project
- */
- public Map secondaryTypes(IJavaScriptProject project, boolean waitForIndexes, IProgressMonitor monitor) throws JavaScriptModelException {
- if (VERBOSE) {
- StringBuffer buffer = new StringBuffer("JavaModelManager.secondaryTypes("); //$NON-NLS-1$
- buffer.append(project.getElementName());
- buffer.append(',');
- buffer.append(waitForIndexes);
- buffer.append(')');
- Util.verbose(buffer.toString());
- }
-
- // Return cache if not empty and there's no new secondary types created during indexing
- final PerProjectInfo projectInfo = getPerProjectInfoCheckExistence(project.getProject());
- Map indexingSecondaryCache = projectInfo.secondaryTypes == null ? null : (Map) projectInfo.secondaryTypes.get(INDEXED_SECONDARY_TYPES);
- if (projectInfo.secondaryTypes != null && indexingSecondaryCache == null) {
- return projectInfo.secondaryTypes;
- }
-
- // Perform search request only if secondary types cache is not initialized yet (this will happen only once!)
- if (projectInfo.secondaryTypes == null) {
- return secondaryTypesSearching(project, waitForIndexes, monitor, projectInfo);
- }
-
- // New secondary types have been created while indexing secondary types cache
- // => need to know whether the indexing is finished or not
- boolean indexing = this.indexManager.awaitingJobsCount() > 0;
- if (indexing) {
- if (!waitForIndexes) {
- // Indexing is running but caller cannot wait => return current cache
- return projectInfo.secondaryTypes;
- }
-
- // Wait for the end of indexing or a cancel
- while (this.indexManager.awaitingJobsCount() > 0) {
- if (monitor != null && monitor.isCanceled()) {
- return projectInfo.secondaryTypes;
- }
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- return projectInfo.secondaryTypes;
- }
- }
- }
-
- // Indexing is finished => merge caches and return result
- return secondaryTypesMerging(projectInfo.secondaryTypes);
- }
-
- /*
- * Return secondary types cache merged with new secondary types created while indexing
- * Note that merge result is directly stored in given parameter map.
- */
- private Hashtable secondaryTypesMerging(Hashtable secondaryTypes) {
- if (VERBOSE) {
- Util.verbose("JavaModelManager.getSecondaryTypesMerged()"); //$NON-NLS-1$
- Util.verbose(" - current cache to merge:"); //$NON-NLS-1$
- Iterator entries = secondaryTypes.entrySet().iterator();
- while (entries.hasNext()) {
- Map.Entry entry = (Map.Entry) entries.next();
- String packName = (String) entry.getKey();
- Util.verbose(" + "+packName+':'+ entry.getValue() ); //$NON-NLS-1$
- }
- }
-
- // Return current cache if there's no indexing cache (double check, this should not happen)
- HashMap indexedSecondaryTypes = (HashMap) secondaryTypes.remove(INDEXED_SECONDARY_TYPES);
- if (indexedSecondaryTypes == null) {
- return secondaryTypes;
- }
-
- // Merge indexing cache in secondary types one
- Iterator entries = indexedSecondaryTypes.entrySet().iterator();
- while (entries.hasNext()) {
- Map.Entry entry = (Map.Entry) entries.next();
- IFile file = (IFile) entry.getKey();
-
- // Remove all secondary types of indexed file from cache
- secondaryTypesRemoving(secondaryTypes, file);
-
- // Add all indexing file secondary types in given secondary types cache
- HashMap fileSecondaryTypes = (HashMap) entry.getValue();
- Iterator entries2 = fileSecondaryTypes.entrySet().iterator();
- while (entries2.hasNext()) {
- Map.Entry entry2 = (Map.Entry) entries2.next();
- String packageName = (String) entry2.getKey();
- HashMap cachedTypes = (HashMap) secondaryTypes.get(packageName);
- if (cachedTypes == null) {
- secondaryTypes.put(packageName, entry2.getValue());
- } else {
- HashMap types = (HashMap) entry2.getValue();
- Iterator entries3 = types.entrySet().iterator();
- while (entries3.hasNext()) {
- Map.Entry entry3 = (Map.Entry) entries3.next();
- String typeName = (String) entry3.getKey();
- cachedTypes.put(typeName, entry3.getValue());
- }
- }
- }
- }
- if (VERBOSE) {
- Util.verbose(" - secondary types cache merged:"); //$NON-NLS-1$
- entries = secondaryTypes.entrySet().iterator();
- while (entries.hasNext()) {
- Map.Entry entry = (Map.Entry) entries.next();
- String packName = (String) entry.getKey();
- Util.verbose(" + "+packName+':'+ entry.getValue()); //$NON-NLS-1$
- }
- }
- return secondaryTypes;
- }
-
- /*
- * Perform search request to get all secondary types of a given project.
- * If not waiting for indexes and indexing is running, will return types found in current built indexes...
- */
- private Map secondaryTypesSearching(IJavaScriptProject project, boolean waitForIndexes, IProgressMonitor monitor, final PerProjectInfo projectInfo) throws JavaScriptModelException {
- if (VERBOSE || BasicSearchEngine.VERBOSE) {
- StringBuffer buffer = new StringBuffer("JavaModelManager.secondaryTypesSearch("); //$NON-NLS-1$
- buffer.append(project.getElementName());
- buffer.append(',');
- buffer.append(waitForIndexes);
- buffer.append(')');
- Util.verbose(buffer.toString());
- }
-
- 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) {
- String key = packageName==null ? "" : new String(packageName); //$NON-NLS-1$
- HashMap types = (HashMap) secondaryTypes.get(key);
- if (types == null) types = new HashMap(3);
- types.put(new String(simpleTypeName), path);
- secondaryTypes.put(key, types);
- }
- };
-
- // Build scope using prereq projects but only source folders
- IPackageFragmentRoot[] allRoots = project.getAllPackageFragmentRoots();
- int length = allRoots.length, size = 0;
- IPackageFragmentRoot[] allSourceFolders = new IPackageFragmentRoot[length];
- for (int i=0; i<length; i++) {
- if (allRoots[i].getKind() == IPackageFragmentRoot.K_SOURCE) {
- allSourceFolders[size++] = allRoots[i];
- }
- }
- if (size < length) {
- System.arraycopy(allSourceFolders, 0, allSourceFolders = new IPackageFragmentRoot[size], 0, size);
- }
-
- // Search all secondary types on scope
- new BasicSearchEngine().searchAllSecondaryTypeNames(allSourceFolders, nameRequestor, waitForIndexes, monitor);
-
- // Build types from paths
- Iterator packages = secondaryTypes.values().iterator();
- while (packages.hasNext()) {
- HashMap types = (HashMap) packages.next();
- Iterator names = types.entrySet().iterator();
- while (names.hasNext()) {
- Map.Entry entry = (Map.Entry) names.next();
- String typeName = (String) entry.getKey();
- String path = (String) entry.getValue();
- if (org.eclipse.wst.jsdt.internal.core.util.Util.isJavaLikeFileName(path)) {
- IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(path));
- IJavaScriptUnit unit = JavaModelManager.createCompilationUnitFrom(file, null);
- IType type = unit.getType(typeName);
- types.put(typeName, type); // replace stored path with type itself
- }
- }
- }
-
- // Store result in per project info cache if still null or there's still an indexing cache (may have been set by another thread...)
- if (projectInfo.secondaryTypes == null || projectInfo.secondaryTypes.get(INDEXED_SECONDARY_TYPES) != null) {
- projectInfo.secondaryTypes = secondaryTypes;
- if (VERBOSE || BasicSearchEngine.VERBOSE) {
- System.out.print(Thread.currentThread() + " -> secondary paths stored in cache: "); //$NON-NLS-1$
- System.out.println();
- Iterator entries = secondaryTypes.entrySet().iterator();
- while (entries.hasNext()) {
- Map.Entry entry = (Map.Entry) entries.next();
- String qualifiedName = (String) entry.getKey();
- Util.verbose(" - "+qualifiedName+'-'+ entry.getValue()); //$NON-NLS-1$
- }
- }
- }
- return projectInfo.secondaryTypes;
- }
-
- /**
- * Remove from secondary types cache all types belonging to a given file.
- * Clean secondary types cache built while indexing if requested.
- *
- * Project's secondary types cache is found using file location.
- *
- * @param file File to remove
- */
- public void secondaryTypesRemoving(IFile file, boolean cleanIndexCache) {
- if (VERBOSE) {
- StringBuffer buffer = new StringBuffer("JavaModelManager.removeFromSecondaryTypesCache("); //$NON-NLS-1$
- buffer.append(file.getName());
- buffer.append(')');
- Util.verbose(buffer.toString());
- }
- if (file != null) {
- PerProjectInfo projectInfo = getPerProjectInfo(file.getProject(), false);
- if (projectInfo != null && projectInfo.secondaryTypes != null) {
- if (VERBOSE) {
- Util.verbose("-> remove file from cache of project: "+file.getProject().getName()); //$NON-NLS-1$
- }
-
- // Clean current cache
- secondaryTypesRemoving(projectInfo.secondaryTypes, file);
-
- // Clean indexing cache if necessary
- if (!cleanIndexCache) return;
- HashMap indexingCache = (HashMap) projectInfo.secondaryTypes.get(INDEXED_SECONDARY_TYPES);
- if (indexingCache != null) {
- Set keys = indexingCache.keySet();
- int filesSize = keys.size(), filesCount = 0;
- IFile[] removed = null;
- Iterator cachedFiles = keys.iterator();
- while (cachedFiles.hasNext()) {
- IFile cachedFile = (IFile) cachedFiles.next();
- if (file.equals(cachedFile)) {
- if (removed == null) removed = new IFile[filesSize];
- filesSize--;
- removed[filesCount++] = cachedFile;
- }
- }
- if (removed != null) {
- for (int i=0; i<filesCount; i++) {
- indexingCache.remove(removed[i]);
- }
- }
- }
- }
- }
- }
-
- /*
- * Remove from a given cache map all secondary types belonging to a given file.
- * Note that there can have several secondary types per file...
- */
- private void secondaryTypesRemoving(Hashtable secondaryTypesMap, IFile file) {
- if (VERBOSE) {
- StringBuffer buffer = new StringBuffer("JavaModelManager.removeSecondaryTypesFromMap("); //$NON-NLS-1$
- Iterator entries = secondaryTypesMap.entrySet().iterator();
- while (entries.hasNext()) {
- Map.Entry entry = (Map.Entry) entries.next();
- String qualifiedName = (String) entry.getKey();
- buffer.append(qualifiedName+':'+ entry.getValue());
- }
- buffer.append(',');
- buffer.append(file.getFullPath());
- buffer.append(')');
- Util.verbose(buffer.toString());
- }
- Set packageEntries = secondaryTypesMap.entrySet();
- int packagesSize = packageEntries.size(), removedPackagesCount = 0;
- String[] removedPackages = null;
- Iterator packages = packageEntries.iterator();
- while (packages.hasNext()) {
- Map.Entry entry = (Map.Entry) packages.next();
- String packName = (String) entry.getKey();
- if (packName != INDEXED_SECONDARY_TYPES) { // skip indexing cache entry if present (!= is intentional)
- HashMap types = (HashMap) entry.getValue();
- Set nameEntries = types.entrySet();
- int namesSize = nameEntries.size(), removedNamesCount = 0;
- String[] removedNames = null;
- Iterator names = nameEntries.iterator();
- while (names.hasNext()) {
- Map.Entry entry2 = (Map.Entry) names.next();
- String typeName = (String) entry2.getKey();
- IType type = (IType) entry2.getValue();
- if (file.equals(type.getResource())) {
- if (removedNames == null) removedNames = new String[namesSize];
- namesSize--;
- removedNames[removedNamesCount++] = typeName;
- }
- }
- if (removedNames != null) {
- for (int i=0; i<removedNamesCount; i++) {
- types.remove(removedNames[i]);
- }
- }
- if (types.size() == 0) {
- if (removedPackages == null) removedPackages = new String[packagesSize];
- packagesSize--;
- removedPackages[removedPackagesCount++] = packName;
- }
- }
- }
- if (removedPackages != null) {
- for (int i=0; i<removedPackagesCount; i++) {
- secondaryTypesMap.remove(removedPackages[i]);
- }
- }
- if (VERBOSE) {
- Util.verbose(" - new secondary types map:"); //$NON-NLS-1$
- Iterator entries = secondaryTypesMap.entrySet().iterator();
- while (entries.hasNext()) {
- Map.Entry entry = (Map.Entry) entries.next();
- String qualifiedName = (String) entry.getKey();
- Util.verbose(" + "+qualifiedName+':'+ entry.getValue()); //$NON-NLS-1$
- }
- }
- }
-
- /**
- * Record the order in which to build the java projects (batch build). This order is based
- * on the projects classpath settings.
- */
- protected void setBuildOrder(String[] javaBuildOrder) throws JavaScriptModelException {
-
- // optional behaviour
- // possible value of index 0 is Compute
- if (!JavaScriptCore.COMPUTE.equals(JavaScriptCore.getOption(JavaScriptCore.CORE_JAVA_BUILD_ORDER))) return; // cannot be customized at project level
-
- if (javaBuildOrder == null || javaBuildOrder.length <= 1) return;
-
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- IWorkspaceDescription description = workspace.getDescription();
- String[] wksBuildOrder = description.getBuildOrder();
-
- String[] newOrder;
- if (wksBuildOrder == null){
- newOrder = javaBuildOrder;
- } else {
- // remove projects which are already mentionned in java builder order
- int javaCount = javaBuildOrder.length;
- HashMap newSet = new HashMap(javaCount); // create a set for fast check
- for (int i = 0; i < javaCount; i++){
- newSet.put(javaBuildOrder[i], javaBuildOrder[i]);
- }
- int removed = 0;
- int oldCount = wksBuildOrder.length;
- for (int i = 0; i < oldCount; i++){
- if (newSet.containsKey(wksBuildOrder[i])){
- wksBuildOrder[i] = null;
- removed++;
- }
- }
- // add Java ones first
- newOrder = new String[oldCount - removed + javaCount];
- System.arraycopy(javaBuildOrder, 0, newOrder, 0, javaCount); // java projects are built first
-
- // copy previous items in their respective order
- int index = javaCount;
- for (int i = 0; i < oldCount; i++){
- if (wksBuildOrder[i] != null){
- newOrder[index++] = wksBuildOrder[i];
- }
- }
- }
- // commit the new build order out
- description.setBuildOrder(newOrder);
- try {
- workspace.setDescription(description);
- } catch(CoreException e){
- throw new JavaScriptModelException(e);
- }
- }
-
- /**
- * Sets the last built state for the given project, or null to reset it.
- */
- public void setLastBuiltState(IProject project, Object state) {
- if (JavaProject.hasJavaNature(project)) {
- // should never be requested on non-Java projects
- PerProjectInfo info = getPerProjectInfo(project, true /*create if missing*/);
- info.triedRead = true; // no point trying to re-read once using setter
- info.savedState = state;
- }
- if (state == null) { // delete state file to ensure a full build happens if the workspace crashes
- try {
- File file = getSerializationFile(project);
- if (file != null && file.exists())
- file.delete();
- } catch(SecurityException se) {
- // could not delete file: cannot do much more
- }
- }
- }
-
- public void setOptions(Hashtable newOptions) {
-
- try {
- IEclipsePreferences defaultPreferences = getDefaultPreferences();
- IEclipsePreferences instancePreferences = getInstancePreferences();
-
- if (newOptions == null){
- instancePreferences.clear();
- } else {
- Enumeration keys = newOptions.keys();
- while (keys.hasMoreElements()){
- String key = (String)keys.nextElement();
- if (!this.optionNames.contains(key)) continue; // unrecognized option
- if (key.equals(JavaScriptCore.CORE_ENCODING)) continue; // skipped, contributed by resource prefs
- String value = (String)newOptions.get(key);
- String defaultValue = defaultPreferences.get(key, null);
- if (defaultValue != null && defaultValue.equals(value)) {
- instancePreferences.remove(key);
- } else {
- instancePreferences.put(key, value);
- }
- }
- }
-
- // persist options
- instancePreferences.flush();
-
- // update cache
- this.optionsCache = newOptions==null ? null : new Hashtable(newOptions);
- } catch (BackingStoreException e) {
- // ignore
- }
- }
-
- public void startup() throws CoreException {
- try {
- configurePluginDebugOptions();
-
- // initialize Java model cache
- this.cache = new JavaModelCache();
-
- // request state folder creation (workaround 19885)
- JavaScriptCore.getPlugin().getStateLocation();
-
- // Initialize eclipse preferences
- initializePreferences();
-
- // Listen to preference changes
- Preferences.IPropertyChangeListener propertyListener = new Preferences.IPropertyChangeListener() {
- public void propertyChange(Preferences.PropertyChangeEvent event) {
- JavaModelManager.this.optionsCache = null;
- }
- };
- JavaScriptCore.getPlugin().getPluginPreferences().addPropertyChangeListener(propertyListener);
-
- // Listen to content-type changes
- Platform.getContentTypeManager().addContentTypeChangeListener(this);
-
- // retrieve variable values
- long start = -1;
- if (VERBOSE)
- start = System.currentTimeMillis();
- loadVariablesAndContainers();
- if (VERBOSE)
- traceVariableAndContainers("Loaded", start); //$NON-NLS-1$
-
- final IWorkspace workspace = ResourcesPlugin.getWorkspace();
-
- IProject[] projects = new IProject[0];
- IWorkspaceRoot workSpaceRoot = workspace.getRoot();
- if(workSpaceRoot!=null) {
- projects = workSpaceRoot.getProjects();
- }
-
- for(int i = 0;projects!=null && i<projects.length;i++) {
- copyJsdtScopeFile(projects[i]);
-
- }
-
- workspace.addResourceChangeListener(
- this.deltaState,
- /* update spec in JavaScriptCore#addPreProcessingResourceChangedListener(...) if adding more event types */
- IResourceChangeEvent.PRE_BUILD
- | IResourceChangeEvent.POST_BUILD
- | IResourceChangeEvent.POST_CHANGE
- | IResourceChangeEvent.PRE_DELETE
- | IResourceChangeEvent.PRE_CLOSE);
-
- startIndexing();
-
- // process deltas since last activated in indexer thread so that indexes are up-to-date.
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=38658
- Job processSavedState = new Job(Messages.savedState_jobName) {
- protected IStatus run(IProgressMonitor monitor) {
- try {
- // add save participant and process delta atomically
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=59937
- workspace.run(
- new IWorkspaceRunnable() {
- public void run(IProgressMonitor progress) throws CoreException {
- ISavedState savedState = workspace.addSaveParticipant(JavaScriptCore.getJavaScriptCore(), JavaModelManager.this);
- if (savedState != null) {
- // the event type coming from the saved state is always POST_AUTO_BUILD
- // force it to be POST_CHANGE so that the delta processor can handle it
- JavaModelManager.this.deltaState.getDeltaProcessor().overridenEventType = IResourceChangeEvent.POST_CHANGE;
- savedState.processResourceChangeEvents(JavaModelManager.this.deltaState);
- }
- }
- },
- monitor);
- } catch (CoreException e) {
- return e.getStatus();
- }
- return Status.OK_STATUS;
- }
- };
- processSavedState.setSystem(true);
- processSavedState.setPriority(Job.SHORT); // process asap
- processSavedState.schedule();
- } catch (RuntimeException e) {
- shutdown();
- throw e;
- }
- }
-
- /**
- * Initiate the background indexing process.
- * This should be deferred after the plugin activation.
- */
- private void startIndexing() {
- getIndexManager().reset();
- }
-
- public void shutdown () {
- JavaScriptCore javaCore = JavaScriptCore.getJavaScriptCore();
- javaCore.savePluginPreferences();
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- workspace.removeResourceChangeListener(this.deltaState);
- workspace.removeSaveParticipant(javaCore);
-
- // Stop listening to content-type changes
- Platform.getContentTypeManager().removeContentTypeChangeListener(this);
-
- if (this.indexManager != null){ // no more indexing
- this.indexManager.shutdown();
- }
-
- // wait for the initialization job to finish
- try {
- Job.getJobManager().join(JavaScriptCore.PLUGIN_ID, null);
- } catch (InterruptedException e) {
- // ignore
- }
-
- // Note: no need to close the Java model as this just removes Java element infos from the Java model cache
- }
-
-
- private void copyJsdtScopeFile(IProject project) {
-
- IResource oldJsdtScope = project.findMember(JavaProject.CLASSPATH_FILENAME);
- if(oldJsdtScope==null || ! oldJsdtScope.exists()) return;
-
- IFolder rscPath = project.getFolder(JavaProject.SHARED_PROPERTIES_DIRECTORY);
- if(!rscPath.exists())
- try {
- rscPath.create(true, true, new NullProgressMonitor());
- }
- catch (CoreException e) {}
-
-
- IFile jsdtScope = rscPath.getFile(JavaProject.CLASSPATH_FILENAME);
-
- if(!jsdtScope.exists()) {
- // Check for the file in its older location project root and move it.
-
- if(oldJsdtScope!=null && oldJsdtScope.exists()) {
- try {
- oldJsdtScope.move(jsdtScope.getFullPath(), false, new NullProgressMonitor());
- }
- catch (CoreException e) {
-
- }
- }
- }
-
- }
-
- public synchronized IPath variableGet(String variableName){
- // check initialization in progress first
- HashSet initializations = variableInitializationInProgress();
- if (initializations.contains(variableName)) {
- return VARIABLE_INITIALIZATION_IN_PROGRESS;
- }
- return (IPath)this.variables.get(variableName);
- }
-
- private synchronized IPath variableGetDefaultToPreviousSession(String variableName){
- IPath variablePath = (IPath)this.variables.get(variableName);
- if (variablePath == null)
- return getPreviousSessionVariable(variableName);
- return variablePath;
- }
-
- /*
- * Returns the set of variable names that are being initialized in the current thread.
- */
- private HashSet variableInitializationInProgress() {
- HashSet initializations = (HashSet)this.variableInitializationInProgress.get();
- if (initializations == null) {
- initializations = new HashSet();
- this.variableInitializationInProgress.set(initializations);
- }
- return initializations;
- }
-
- public synchronized String[] variableNames(){
- int length = this.variables.size();
- String[] result = new String[length];
- Iterator vars = this.variables.keySet().iterator();
- int index = 0;
- while (vars.hasNext()) {
- result[index++] = (String) vars.next();
- }
- return result;
- }
-
- public synchronized void variablePut(String variableName, IPath variablePath){
-
- // set/unset the initialization in progress
- HashSet initializations = variableInitializationInProgress();
- if (variablePath == VARIABLE_INITIALIZATION_IN_PROGRESS) {
- initializations.add(variableName);
-
- // do not write out intermediate initialization value
- return;
- } else {
- initializations.remove(variableName);
-
- // update cache - do not only rely on listener refresh
- if (variablePath == null) {
- // if path is null, record that the variable was removed to avoid asking the initializer to initialize it again
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=112609
- this.variables.put(variableName, CP_ENTRY_IGNORE_PATH);
- } else {
- this.variables.put(variableName, variablePath);
- }
- // discard obsoleted information about previous session
- this.previousSessionVariables.remove(variableName);
- }
- }
-
- public void variablePreferencesPut(String variableName, IPath variablePath) {
- String variableKey = CP_VARIABLE_PREFERENCES_PREFIX+variableName;
- if (variablePath == null) {
- this.variablesWithInitializer.remove(variableName);
- getInstancePreferences().remove(variableKey);
- } else {
- getInstancePreferences().put(variableKey, variablePath.toString());
- }
- try {
- getInstancePreferences().flush();
- } catch (BackingStoreException e) {
- // ignore exception
- }
- }
-
- /*
- * Optimize startup case where 1 variable is initialized at a time with the same value as on shutdown.
- */
- public boolean variablePutIfInitializingWithSameValue(String[] variableNames, IPath[] variablePaths) {
- if (variableNames.length != 1)
- return false;
- String variableName = variableNames[0];
- IPath oldPath = variableGetDefaultToPreviousSession(variableName);
- if (oldPath == null)
- return false;
- IPath newPath = variablePaths[0];
- if (!oldPath.equals(newPath))
- return false;
- variablePut(variableName, newPath);
- return true;
- }
-
- public void contentTypeChanged(ContentTypeChangeEvent event) {
- Util.resetJavaLikeExtensions();
-
- }
-
- public synchronized String cacheToString(String prefix) {
- return this.cache.toStringFillingRation(prefix);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaModelOperation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaModelOperation.java
deleted file mode 100644
index a8f57cb2..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaModelOperation.java
+++ /dev/null
@@ -1,899 +0,0 @@
-/*******************************************************************************
- * 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 java.io.InputStream;
-import java.util.ArrayList;
-import java.util.HashMap;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceStatus;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-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.core.runtime.SubProgressMonitor;
-import org.eclipse.core.runtime.jobs.ISchedulingRule;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.wst.jsdt.core.IBuffer;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptElementDelta;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatus;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatusConstants;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-
-/**
- * Defines behavior common to all Java Model operations
- */
-public abstract class JavaModelOperation implements IWorkspaceRunnable, IProgressMonitor {
- protected interface IPostAction {
- /*
- * Returns the id of this action.
- * @see JavaModelOperation#postAction
- */
- String getID();
- /*
- * Run this action.
- */
- void run() throws JavaScriptModelException;
- }
- /*
- * Constants controlling the insertion mode of an action.
- * @see JavaModelOperation#postAction
- */
- protected static final int APPEND = 1; // insert at the end
- protected static final int REMOVEALL_APPEND = 2; // remove all existing ones with same ID, and add new one at the end
- protected static final int KEEP_EXISTING = 3; // do not insert if already existing with same ID
-
- /*
- * Whether tracing post actions is enabled.
- */
- protected static boolean POST_ACTION_VERBOSE;
-
- /*
- * A list of IPostActions.
- */
- protected IPostAction[] actions;
- protected int actionsStart = 0;
- protected int actionsEnd = -1;
- /*
- * A HashMap of attributes that can be used by operations
- */
- protected HashMap attributes;
-
- public static final String HAS_MODIFIED_RESOURCE_ATTR = "hasModifiedResource"; //$NON-NLS-1$
- public static final String TRUE = JavaModelManager.TRUE;
- //public static final String FALSE = "false";
-
- /**
- * The elements this operation operates on,
- * or <code>null</code> if this operation
- * does not operate on specific elements.
- */
- protected IJavaScriptElement[] elementsToProcess;
- /**
- * The parent elements this operation operates with
- * or <code>null</code> if this operation
- * does not operate with specific parent elements.
- */
- protected IJavaScriptElement[] parentElements;
- /**
- * An empty collection of <code>IJavaScriptElement</code>s - the common
- * empty result if no elements are created, or if this
- * operation is not actually executed.
- */
- protected static IJavaScriptElement[] NO_ELEMENTS= new IJavaScriptElement[] {};
-
-
- /**
- * The elements created by this operation - empty
- * until the operation actually creates elements.
- */
- protected IJavaScriptElement[] resultElements= NO_ELEMENTS;
-
- /**
- * The progress monitor passed into this operation
- */
- public IProgressMonitor progressMonitor= null;
- /**
- * A flag indicating whether this operation is nested.
- */
- protected boolean isNested = false;
- /**
- * Conflict resolution policy - by default do not force (fail on a conflict).
- */
- protected boolean force = false;
-
- /*
- * A per thread stack of java model operations (PerThreadObject of ArrayList).
- */
- protected static ThreadLocal operationStacks = new ThreadLocal();
- protected JavaModelOperation() {
- // default constructor used in subclasses
- }
- /**
- * A common constructor for all Java Model operations.
- */
- protected JavaModelOperation(IJavaScriptElement[] elements) {
- this.elementsToProcess = elements;
- }
- /**
- * Common constructor for all Java Model operations.
- */
- protected JavaModelOperation(IJavaScriptElement[] elementsToProcess, IJavaScriptElement[] parentElements) {
- this.elementsToProcess = elementsToProcess;
- this.parentElements= parentElements;
- }
- /**
- * A common constructor for all Java Model operations.
- */
- protected JavaModelOperation(IJavaScriptElement[] elementsToProcess, IJavaScriptElement[] parentElements, boolean force) {
- this.elementsToProcess = elementsToProcess;
- this.parentElements= parentElements;
- this.force= force;
- }
- /**
- * A common constructor for all Java Model operations.
- */
- protected JavaModelOperation(IJavaScriptElement[] elements, boolean force) {
- this.elementsToProcess = elements;
- this.force= force;
- }
-
- /**
- * Common constructor for all Java Model operations.
- */
- protected JavaModelOperation(IJavaScriptElement element) {
- this.elementsToProcess = new IJavaScriptElement[]{element};
- }
- /**
- * A common constructor for all Java Model operations.
- */
- protected JavaModelOperation(IJavaScriptElement element, boolean force) {
- this.elementsToProcess = new IJavaScriptElement[]{element};
- this.force= force;
- }
-
- /*
- * Registers the given action at the end of the list of actions to run.
- */
- protected void addAction(IPostAction action) {
- int length = this.actions.length;
- if (length == ++this.actionsEnd) {
- System.arraycopy(this.actions, 0, this.actions = new IPostAction[length*2], 0, length);
- }
- this.actions[this.actionsEnd] = action;
- }
- /*
- * Registers the given delta with the Java Model Manager.
- */
- protected void addDelta(IJavaScriptElementDelta delta) {
- JavaModelManager.getJavaModelManager().getDeltaProcessor().registerJavaModelDelta(delta);
- }
- /*
- * Registers the given reconcile delta with the Java Model Manager.
- */
- protected void addReconcileDelta(IJavaScriptUnit workingCopy, IJavaScriptElementDelta delta) {
- HashMap reconcileDeltas = JavaModelManager.getJavaModelManager().getDeltaProcessor().reconcileDeltas;
- JavaElementDelta previousDelta = (JavaElementDelta)reconcileDeltas.get(workingCopy);
- if (previousDelta != null) {
- IJavaScriptElementDelta[] children = delta.getAffectedChildren();
- for (int i = 0, length = children.length; i < length; i++) {
- JavaElementDelta child = (JavaElementDelta)children[i];
- previousDelta.insertDeltaTree(child.getElement(), child);
- }
- // note that the last delta's AST always takes precedence over the existing delta's AST
- // since it is the result of the last reconcile operation
- if ((delta.getFlags() & IJavaScriptElementDelta.F_AST_AFFECTED) != 0) {
- previousDelta.changedAST(delta.getJavaScriptUnitAST());
- }
-
- } else {
- reconcileDeltas.put(workingCopy, delta);
- }
- }
- /*
- * Deregister the reconcile delta for the given working copy
- */
- protected void removeReconcileDelta(IJavaScriptUnit workingCopy) {
- JavaModelManager.getJavaModelManager().getDeltaProcessor().reconcileDeltas.remove(workingCopy);
- }
- /**
- * @see IProgressMonitor
- */
- public void beginTask(String name, int totalWork) {
- if (progressMonitor != null) {
- progressMonitor.beginTask(name, totalWork);
- }
- }
- /*
- * Returns whether this operation can modify the package fragment roots.
- */
- protected boolean canModifyRoots() {
- return false;
- }
- /**
- * Checks with the progress monitor to see whether this operation
- * should be canceled. An operation should regularly call this method
- * during its operation so that the user can cancel it.
- *
- * @exception OperationCanceledException if cancelling the operation has been requested
- * @see IProgressMonitor#isCanceled
- */
- protected void checkCanceled() {
- if (isCanceled()) {
- throw new OperationCanceledException(Messages.operation_cancelled);
- }
- }
- /**
- * Common code used to verify the elements this operation is processing.
- * @see JavaModelOperation#verify()
- */
- protected IJavaScriptModelStatus commonVerify() {
- if (elementsToProcess == null || elementsToProcess.length == 0) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.NO_ELEMENTS_TO_PROCESS);
- }
- for (int i = 0; i < elementsToProcess.length; i++) {
- if (elementsToProcess[i] == null) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.NO_ELEMENTS_TO_PROCESS);
- }
- }
- return JavaModelStatus.VERIFIED_OK;
- }
- /**
- * Convenience method to copy resources
- */
- protected void copyResources(IResource[] resources, IPath destinationPath) throws JavaScriptModelException {
- IProgressMonitor subProgressMonitor = getSubProgressMonitor(resources.length);
- IWorkspace workspace = resources[0].getWorkspace();
- try {
- workspace.copy(resources, destinationPath, false, subProgressMonitor);
- setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- }
- }
- /**
- * Convenience method to create a file
- */
- protected void createFile(IContainer folder, String name, InputStream contents, boolean forceFlag) throws JavaScriptModelException {
- IFile file= folder.getFile(new Path(name));
- try {
- file.create(
- contents,
- forceFlag ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY,
- getSubProgressMonitor(1));
- setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- }
- }
- /**
- * Convenience method to create a folder
- */
- protected void createFolder(IContainer parentFolder, String name, boolean forceFlag) throws JavaScriptModelException {
- IFolder folder= parentFolder.getFolder(new Path(name));
- try {
- // we should use true to create the file locally. Only VCM should use tru/false
- folder.create(
- forceFlag ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY,
- true, // local
- getSubProgressMonitor(1));
- setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- }
- }
- /**
- * Convenience method to delete an empty package fragment
- */
- protected void deleteEmptyPackageFragment(
- IPackageFragment fragment,
- boolean forceFlag,
- IResource rootResource)
- throws JavaScriptModelException {
-
- IContainer resource = (IContainer) fragment.getResource();
-
- try {
- resource.delete(
- forceFlag ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY,
- getSubProgressMonitor(1));
- setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
- while (resource instanceof IFolder) {
- // deleting a package: delete the parent if it is empty (eg. deleting x.y where folder x doesn't have resources but y)
- // without deleting the package fragment root
- resource = resource.getParent();
- if (!resource.equals(rootResource) && resource.members().length == 0) {
- resource.delete(
- forceFlag ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY,
- getSubProgressMonitor(1));
- setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
- }
- }
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- }
- }
- /**
- * Convenience method to delete a resource
- */
- protected void deleteResource(IResource resource,int flags) throws JavaScriptModelException {
- try {
- resource.delete(flags, getSubProgressMonitor(1));
- setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- }
- }
- /**
- * Convenience method to delete resources
- */
- protected void deleteResources(IResource[] resources, boolean forceFlag) throws JavaScriptModelException {
- if (resources == null || resources.length == 0) return;
- IProgressMonitor subProgressMonitor = getSubProgressMonitor(resources.length);
- IWorkspace workspace = resources[0].getWorkspace();
- try {
- workspace.delete(
- resources,
- forceFlag ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY,
- subProgressMonitor);
- setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- }
- }
- /**
- * @see IProgressMonitor
- */
- public void done() {
- if (progressMonitor != null) {
- progressMonitor.done();
- }
- }
- /*
- * Returns whether the given path is equals to one of the given other paths.
- */
- protected boolean equalsOneOf(IPath path, IPath[] otherPaths) {
- for (int i = 0, length = otherPaths.length; i < length; i++) {
- if (path.equals(otherPaths[i])) {
- return true;
- }
- }
- return false;
- }
- /**
- * Convenience method to run an operation within this operation
- */
- public void executeNestedOperation(JavaModelOperation operation, int subWorkAmount) throws JavaScriptModelException {
- IJavaScriptModelStatus status= operation.verify();
- if (!status.isOK()) {
- throw new JavaScriptModelException(status);
- }
- IProgressMonitor subProgressMonitor = getSubProgressMonitor(subWorkAmount);
- // fix for 1FW7IKC, part (1)
- try {
- operation.setNested(true);
- operation.run(subProgressMonitor);
- } catch (CoreException ce) {
- if (ce instanceof JavaScriptModelException) {
- throw (JavaScriptModelException)ce;
- } else {
- // translate the core exception to a java model exception
- if (ce.getStatus().getCode() == IResourceStatus.OPERATION_FAILED) {
- Throwable e = ce.getStatus().getException();
- if (e instanceof JavaScriptModelException) {
- throw (JavaScriptModelException) e;
- }
- }
- throw new JavaScriptModelException(ce);
- }
- }
- }
- /**
- * Performs the operation specific behavior. Subclasses must override.
- */
- protected abstract void executeOperation() throws JavaScriptModelException;
- /*
- * Returns the attribute registered at the given key with the top level operation.
- * Returns null if no such attribute is found.
- */
- protected static Object getAttribute(Object key) {
- ArrayList stack = getCurrentOperationStack();
- if (stack.size() == 0) return null;
- JavaModelOperation topLevelOp = (JavaModelOperation)stack.get(0);
- if (topLevelOp.attributes == null) {
- return null;
- } else {
- return topLevelOp.attributes.get(key);
- }
- }
- /**
- * Returns the compilation unit the given element is contained in,
- * or the element itself (if it is a compilation unit),
- * otherwise <code>null</code>.
- */
- protected IJavaScriptUnit getCompilationUnitFor(IJavaScriptElement element) {
-
- return ((JavaElement)element).getJavaScriptUnit();
- }
- /*
- * Returns the stack of operations running in the current thread.
- * Returns an empty stack if no operations are currently running in this thread.
- */
- protected static ArrayList getCurrentOperationStack() {
- ArrayList stack = (ArrayList)operationStacks.get();
- if (stack == null) {
- stack = new ArrayList();
- operationStacks.set(stack);
- }
- return stack;
- }
- /*
- * Returns the existing document for the given cu, or a DocumentAdapter if none.
- */
- protected IDocument getDocument(IJavaScriptUnit cu) throws JavaScriptModelException {
- IBuffer buffer = cu.getBuffer();
- if (buffer instanceof IDocument)
- return (IDocument) buffer;
- return new DocumentAdapter(buffer);
- }
- /**
- * Returns the elements to which this operation applies,
- * or <code>null</code> if not applicable.
- */
- protected IJavaScriptElement[] getElementsToProcess() {
- return elementsToProcess;
- }
- /**
- * Returns the element to which this operation applies,
- * or <code>null</code> if not applicable.
- */
- protected IJavaScriptElement getElementToProcess() {
- if (elementsToProcess == null || elementsToProcess.length == 0) {
- return null;
- }
- return elementsToProcess[0];
- }
- /**
- * Returns the Java Model this operation is operating in.
- */
- public IJavaScriptModel getJavaModel() {
- return JavaModelManager.getJavaModelManager().getJavaModel();
- }
- protected IPath[] getNestedFolders(IPackageFragmentRoot root) throws JavaScriptModelException {
- IPath rootPath = root.getPath();
- IIncludePathEntry[] classpath = root.getJavaScriptProject().getRawIncludepath();
- int length = classpath.length;
- IPath[] result = new IPath[length];
- int index = 0;
- for (int i = 0; i < length; i++) {
- IPath path = classpath[i].getPath();
- if (rootPath.isPrefixOf(path) && !rootPath.equals(path)) {
- result[index++] = path;
- }
- }
- if (index < length) {
- System.arraycopy(result, 0, result = new IPath[index], 0, index);
- }
- return result;
- }
- /**
- * Returns the parent element to which this operation applies,
- * or <code>null</code> if not applicable.
- */
- protected IJavaScriptElement getParentElement() {
- if (parentElements == null || parentElements.length == 0) {
- return null;
- }
- return parentElements[0];
- }
- /**
- * Returns the parent elements to which this operation applies,
- * or <code>null</code> if not applicable.
- */
- protected IJavaScriptElement[] getParentElements() {
- return parentElements;
- }
- /**
- * Returns the elements created by this operation.
- */
- public IJavaScriptElement[] getResultElements() {
- return resultElements;
- }
- /*
- * Returns the scheduling rule for this operation (i.e. the resource that needs to be locked
- * while this operation is running.
- * Subclasses can override.
- */
- protected ISchedulingRule getSchedulingRule() {
- return ResourcesPlugin.getWorkspace().getRoot();
- }
- /**
- * Creates and returns a subprogress monitor if appropriate.
- */
- protected IProgressMonitor getSubProgressMonitor(int workAmount) {
- IProgressMonitor sub = null;
- if (progressMonitor != null) {
- sub = new SubProgressMonitor(progressMonitor, workAmount, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
- }
- return sub;
- }
-
- /**
- * Returns whether this operation has performed any resource modifications.
- * Returns false if this operation has not been executed yet.
- */
- public boolean hasModifiedResource() {
- return !this.isReadOnly() && getAttribute(HAS_MODIFIED_RESOURCE_ATTR) == TRUE;
- }
- public void internalWorked(double work) {
- if (progressMonitor != null) {
- progressMonitor.internalWorked(work);
- }
- }
- /**
- * @see IProgressMonitor
- */
- public boolean isCanceled() {
- if (progressMonitor != null) {
- return progressMonitor.isCanceled();
- }
- return false;
- }
- /**
- * Returns <code>true</code> if this operation performs no resource modifications,
- * otherwise <code>false</code>. Subclasses must override.
- */
- public boolean isReadOnly() {
- return false;
- }
- /*
- * Returns whether this operation is the first operation to run in the current thread.
- */
- protected boolean isTopLevelOperation() {
- ArrayList stack;
- return
- (stack = getCurrentOperationStack()).size() > 0
- && stack.get(0) == this;
- }
- /*
- * Returns the index of the first registered action with the given id, starting from a given position.
- * Returns -1 if not found.
- */
- protected int firstActionWithID(String id, int start) {
- for (int i = start; i <= this.actionsEnd; i++) {
- if (this.actions[i].getID().equals(id)) {
- return i;
- }
- }
- return -1;
- }
-
- /**
- * Convenience method to move resources
- */
- protected void moveResources(IResource[] resources, IPath destinationPath) throws JavaScriptModelException {
- IProgressMonitor subProgressMonitor = null;
- if (progressMonitor != null) {
- subProgressMonitor = new SubProgressMonitor(progressMonitor, resources.length, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
- }
- IWorkspace workspace = resources[0].getWorkspace();
- try {
- workspace.move(resources, destinationPath, false, subProgressMonitor);
- setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- }
- }
- /**
- * Creates and returns a new <code>IJavaScriptElementDelta</code>
- * on the Java Model.
- */
- public JavaElementDelta newJavaElementDelta() {
- return new JavaElementDelta(getJavaModel());
- }
- /*
- * Removes the last pushed operation from the stack of running operations.
- * Returns the poped operation or null if the stack was empty.
- */
- protected JavaModelOperation popOperation() {
- ArrayList stack = getCurrentOperationStack();
- int size = stack.size();
- if (size > 0) {
- if (size == 1) { // top level operation
- operationStacks.set(null); // release reference (see http://bugs.eclipse.org/bugs/show_bug.cgi?id=33927)
- }
- return (JavaModelOperation)stack.remove(size-1);
- } else {
- return null;
- }
- }
- /*
- * Registers the given action to be run when the outer most java model operation has finished.
- * The insertion mode controls whether:
- * - the action should discard all existing actions with the same id, and be queued at the end (REMOVEALL_APPEND),
- * - the action should be ignored if there is already an action with the same id (KEEP_EXISTING),
- * - the action should be queued at the end without looking at existing actions (APPEND)
- */
- protected void postAction(IPostAction action, int insertionMode) {
- if (POST_ACTION_VERBOSE) {
- System.out.print("(" + Thread.currentThread() + ") [JavaModelOperation.postAction(IPostAction, int)] Posting action " + action.getID()); //$NON-NLS-1$ //$NON-NLS-2$
- switch(insertionMode) {
- case REMOVEALL_APPEND:
- System.out.println(" (REMOVEALL_APPEND)"); //$NON-NLS-1$
- break;
- case KEEP_EXISTING:
- System.out.println(" (KEEP_EXISTING)"); //$NON-NLS-1$
- break;
- case APPEND:
- System.out.println(" (APPEND)"); //$NON-NLS-1$
- break;
- }
- }
-
- JavaModelOperation topLevelOp = (JavaModelOperation)getCurrentOperationStack().get(0);
- IPostAction[] postActions = topLevelOp.actions;
- if (postActions == null) {
- topLevelOp.actions = postActions = new IPostAction[1];
- postActions[0] = action;
- topLevelOp.actionsEnd = 0;
- } else {
- String id = action.getID();
- switch (insertionMode) {
- case REMOVEALL_APPEND :
- int index = this.actionsStart-1;
- while ((index = topLevelOp.firstActionWithID(id, index+1)) >= 0) {
- // remove action[index]
- System.arraycopy(postActions, index+1, postActions, index, topLevelOp.actionsEnd - index);
- postActions[topLevelOp.actionsEnd--] = null;
- }
- topLevelOp.addAction(action);
- break;
- case KEEP_EXISTING:
- if (topLevelOp.firstActionWithID(id, 0) < 0) {
- topLevelOp.addAction(action);
- }
- break;
- case APPEND:
- topLevelOp.addAction(action);
- break;
- }
- }
- }
- /*
- * Returns whether the given path is the prefix of one of the given other paths.
- */
- protected boolean prefixesOneOf(IPath path, IPath[] otherPaths) {
- for (int i = 0, length = otherPaths.length; i < length; i++) {
- if (path.isPrefixOf(otherPaths[i])) {
- return true;
- }
- }
- return false;
- }
- /*
- * Pushes the given operation on the stack of operations currently running in this thread.
- */
- protected void pushOperation(JavaModelOperation operation) {
- getCurrentOperationStack().add(operation);
- }
- /*
- * Removes all actions with the given id from the queue of post actions.
- * Does nothing if no such action is in the queue.
- */
- protected void removeAllPostAction(String actionID) {
- if (POST_ACTION_VERBOSE) {
- System.out.println("(" + Thread.currentThread() + ") [JavaModelOperation.removeAllPostAction(String)] Removing actions " + actionID); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- JavaModelOperation topLevelOp = (JavaModelOperation)getCurrentOperationStack().get(0);
- IPostAction[] postActions = topLevelOp.actions;
- if (postActions == null) return;
- int index = this.actionsStart-1;
- while ((index = topLevelOp.firstActionWithID(actionID, index+1)) >= 0) {
- // remove action[index]
- System.arraycopy(postActions, index+1, postActions, index, topLevelOp.actionsEnd - index);
- postActions[topLevelOp.actionsEnd--] = null;
- }
- }
-
- /**
- * Runs this operation and registers any deltas created.
- *
- * @see IWorkspaceRunnable
- * @exception CoreException if the operation fails
- */
- public void run(IProgressMonitor monitor) throws CoreException {
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- DeltaProcessor deltaProcessor = manager.getDeltaProcessor();
- int previousDeltaCount = deltaProcessor.javaModelDeltas.size();
- try {
- progressMonitor = monitor;
- pushOperation(this);
- try {
- if (canModifyRoots()) {
- // computes the root infos before executing the operation
- // noop if aready initialized
- JavaModelManager.getJavaModelManager().deltaState.initializeRoots();
- }
-
- executeOperation();
- } finally {
- if (this.isTopLevelOperation()) {
- this.runPostActions();
- }
- }
- } finally {
- try {
- // reacquire delta processor as it can have been reset during executeOperation()
- deltaProcessor = manager.getDeltaProcessor();
-
- // update JavaModel using deltas that were recorded during this operation
- for (int i = previousDeltaCount, size = deltaProcessor.javaModelDeltas.size(); i < size; i++) {
- deltaProcessor.updateJavaModel((IJavaScriptElementDelta)deltaProcessor.javaModelDeltas.get(i));
- }
-
- // close the parents of the created elements and reset their project's cache (in case we are in an
- // IWorkspaceRunnable and the clients wants to use the created element's parent)
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=83646
- for (int i = 0, length = this.resultElements.length; i < length; i++) {
- IJavaScriptElement element = this.resultElements[i];
- Openable openable = (Openable) element.getOpenable();
- if (!(openable instanceof CompilationUnit) || !((CompilationUnit) openable).isWorkingCopy()) { // a working copy must remain a child of its parent even after a move
- ((JavaElement) openable.getParent()).close();
- }
- switch (element.getElementType()) {
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- deltaProcessor.projectCachesToReset.add(element.getJavaScriptProject());
- break;
- }
- }
- deltaProcessor.resetProjectCaches();
-
- // fire only iff:
- // - the operation is a top level operation
- // - the operation did produce some delta(s)
- // - but the operation has not modified any resource
- if (this.isTopLevelOperation()) {
- if ((deltaProcessor.javaModelDeltas.size() > previousDeltaCount || !deltaProcessor.reconcileDeltas.isEmpty())
- && !this.hasModifiedResource()) {
- deltaProcessor.fire(null, DeltaProcessor.DEFAULT_CHANGE_EVENT);
- } // else deltas are fired while processing the resource delta
- }
- } finally {
- popOperation();
- }
- }
- }
- /**
- * Main entry point for Java Model operations. Runs a Java Model Operation as an IWorkspaceRunnable
- * if not read-only.
- */
- public void runOperation(IProgressMonitor monitor) throws JavaScriptModelException {
- IJavaScriptModelStatus status= verify();
- if (!status.isOK()) {
- throw new JavaScriptModelException(status);
- }
- try {
- if (isReadOnly()) {
- run(monitor);
- } else {
- // Use IWorkspace.run(...) to ensure that a build will be done in autobuild mode.
- // Note that if the tree is locked, this will throw a CoreException, but this is ok
- // as this operation is modifying the tree (not read-only) and a CoreException will be thrown anyway.
- ResourcesPlugin.getWorkspace().run(this, getSchedulingRule(), IWorkspace.AVOID_UPDATE, monitor);
- }
- } catch (CoreException ce) {
- if (ce instanceof JavaScriptModelException) {
- throw (JavaScriptModelException)ce;
- } else {
- if (ce.getStatus().getCode() == IResourceStatus.OPERATION_FAILED) {
- Throwable e= ce.getStatus().getException();
- if (e instanceof JavaScriptModelException) {
- throw (JavaScriptModelException) e;
- }
- }
- throw new JavaScriptModelException(ce);
- }
- }
- }
- protected void runPostActions() throws JavaScriptModelException {
- while (this.actionsStart <= this.actionsEnd) {
- IPostAction postAction = this.actions[this.actionsStart++];
- if (POST_ACTION_VERBOSE) {
- System.out.println("(" + Thread.currentThread() + ") [JavaModelOperation.runPostActions()] Running action " + postAction.getID()); //$NON-NLS-1$ //$NON-NLS-2$
- }
- postAction.run();
- }
- }
- /*
- * Registers the given attribute at the given key with the top level operation.
- */
- protected static void setAttribute(Object key, Object attribute) {
- ArrayList operationStack = getCurrentOperationStack();
- if (operationStack.size() == 0)
- return;
- JavaModelOperation topLevelOp = (JavaModelOperation) operationStack.get(0);
- if (topLevelOp.attributes == null) {
- topLevelOp.attributes = new HashMap();
- }
- topLevelOp.attributes.put(key, attribute);
- }
- /**
- * @see IProgressMonitor
- */
- public void setCanceled(boolean b) {
- if (progressMonitor != null) {
- progressMonitor.setCanceled(b);
- }
- }
- /**
- * Sets whether this operation is nested or not.
- * @see CreateElementInCUOperation#checkCanceled
- */
- protected void setNested(boolean nested) {
- isNested = nested;
- }
- /**
- * @see IProgressMonitor
- */
- public void setTaskName(String name) {
- if (progressMonitor != null) {
- progressMonitor.setTaskName(name);
- }
- }
- /**
- * @see IProgressMonitor
- */
- public void subTask(String name) {
- if (progressMonitor != null) {
- progressMonitor.subTask(name);
- }
- }
- /**
- * Returns a status indicating if there is any known reason
- * this operation will fail. Operations are verified before they
- * are run.
- *
- * Subclasses must override if they have any conditions to verify
- * before this operation executes.
- *
- * @see IJavaScriptModelStatus
- */
- protected IJavaScriptModelStatus verify() {
- return commonVerify();
- }
-
- /**
- * @see IProgressMonitor
- */
- public void worked(int work) {
- if (progressMonitor != null) {
- progressMonitor.worked(work);
- checkCanceled();
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaModelStatus.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaModelStatus.java
deleted file mode 100644
index 094a3feb..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaModelStatus.java
+++ /dev/null
@@ -1,481 +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;
-
-import org.eclipse.core.resources.IResourceStatus;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-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.IJsGlobalScopeContainer;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-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.internal.core.util.Messages;
-
-/**
- * @see IJavaScriptModelStatus
- */
-
-public class JavaModelStatus extends Status implements IJavaScriptModelStatus, IJavaScriptModelStatusConstants, IResourceStatus {
-
- /**
- * The elements related to the failure, or <code>null</code>
- * if no elements are involved.
- */
- protected IJavaScriptElement[] elements = new IJavaScriptElement[0];
- /**
- * The path related to the failure, or <code>null</code>
- * if no path is involved.
- */
- protected IPath path;
- /**
- * The <code>String</code> related to the failure, or <code>null</code>
- * if no <code>String</code> is involved.
- */
- protected String string;
- /**
- * Empty children
- */
- protected final static IStatus[] NO_CHILDREN = new IStatus[] {};
- protected IStatus[] children= NO_CHILDREN;
-
- /**
- * Singleton OK object
- */
- public static final IJavaScriptModelStatus VERIFIED_OK = new JavaModelStatus(OK, OK, Messages.status_OK);
-
- /**
- * Constructs an Java model status with no corresponding elements.
- */
- public JavaModelStatus() {
- // no code for an multi-status
- super(ERROR, JavaScriptCore.PLUGIN_ID, 0, "JavaScriptModelStatus", null); //$NON-NLS-1$
- }
- /**
- * Constructs an Java model status with no corresponding elements.
- */
- public JavaModelStatus(int code) {
- super(ERROR, JavaScriptCore.PLUGIN_ID, code, "JavaScriptModelStatus", null); //$NON-NLS-1$
- this.elements= JavaElement.NO_ELEMENTS;
- }
- /**
- * Constructs an Java model status with the given corresponding
- * elements.
- */
- public JavaModelStatus(int code, IJavaScriptElement[] elements) {
- super(ERROR, JavaScriptCore.PLUGIN_ID, code, "JavaScriptModelStatus", null); //$NON-NLS-1$
- this.elements= elements;
- this.path= null;
- }
- /**
- * Constructs an Java model status with no corresponding elements.
- */
- public JavaModelStatus(int code, String string) {
- this(ERROR, code, string);
- }
- /**
- * Constructs an Java model status with no corresponding elements.
- */
- public JavaModelStatus(int severity, int code, String string) {
- super(severity, JavaScriptCore.PLUGIN_ID, code, "JavaScriptModelStatus", null); //$NON-NLS-1$
- this.elements= JavaElement.NO_ELEMENTS;
- this.path= null;
- this.string = string;
- }
- /**
- * Constructs an Java model status with no corresponding elements.
- */
- public JavaModelStatus(int code, Throwable throwable) {
- super(ERROR, JavaScriptCore.PLUGIN_ID, code, "JavaScriptModelStatus", throwable); //$NON-NLS-1$
- this.elements= JavaElement.NO_ELEMENTS;
- }
- /**
- * Constructs an Java model status with no corresponding elements.
- */
- public JavaModelStatus(int code, IPath path) {
- super(ERROR, JavaScriptCore.PLUGIN_ID, code, "JavaScriptModelStatus", null); //$NON-NLS-1$
- this.elements= JavaElement.NO_ELEMENTS;
- this.path= path;
- }
- /**
- * Constructs an Java model status with the given corresponding
- * element.
- */
- public JavaModelStatus(int code, IJavaScriptElement element) {
- this(code, new IJavaScriptElement[]{element});
- }
- /**
- * Constructs an Java model status with the given corresponding
- * element and string
- */
- public JavaModelStatus(int code, IJavaScriptElement element, String string) {
- this(code, new IJavaScriptElement[]{element});
- this.string = string;
- }
-
- /**
- * Constructs an Java model status with the given corresponding
- * element and path
- */
- public JavaModelStatus(int code, IJavaScriptElement element, IPath path) {
- this(code, new IJavaScriptElement[]{element});
- this.path = path;
- }
-
- /**
- * Constructs an Java model status with the given corresponding
- * element, path and string
- */
- public JavaModelStatus(int code, IJavaScriptElement element, IPath path, String string) {
- this(code, new IJavaScriptElement[]{element});
- this.path = path;
- this.string = string;
- }
-
- /**
- * Constructs an Java model status with the given corresponding
- * element and path
- */
- public JavaModelStatus(int severity, int code, IJavaScriptElement element, IPath path, String msg) {
- super(severity, JavaScriptCore.PLUGIN_ID, code, "JavaScriptModelStatus", null); //$NON-NLS-1$
- this.elements= new IJavaScriptElement[]{element};
- this.path = path;
- this.string = msg;
- }
-
- /**
- * Constructs an Java model status with no corresponding elements.
- */
- public JavaModelStatus(CoreException coreException) {
- super(ERROR, JavaScriptCore.PLUGIN_ID, CORE_EXCEPTION, "JavaScriptModelStatus", coreException); //$NON-NLS-1$
- elements= JavaElement.NO_ELEMENTS;
- }
- protected int getBits() {
- int severity = 1 << (getCode() % 100 / 33);
- int category = 1 << ((getCode() / 100) + 3);
- return severity | category;
- }
- /**
- * @see IStatus
- */
- public IStatus[] getChildren() {
- return children;
- }
- /**
- * @see IJavaScriptModelStatus
- */
- public IJavaScriptElement[] getElements() {
- return elements;
- }
- /**
- * Returns the message that is relevant to the code of this status.
- */
- public String getMessage() {
- Throwable exception = getException();
- if (exception == null) {
- switch (getCode()) {
- case CORE_EXCEPTION :
- return Messages.status_coreException;
-
- case BUILDER_INITIALIZATION_ERROR:
- return Messages.build_initializationError;
-
- case BUILDER_SERIALIZATION_ERROR:
- return Messages.build_serializationError;
-
- case DEVICE_PATH:
- return Messages.bind(Messages.status_cannotUseDeviceOnPath, getPath().toString());
-
- case DOM_EXCEPTION:
- return Messages.status_JDOMError;
-
- case ELEMENT_DOES_NOT_EXIST:
- return Messages.bind(Messages.element_doesNotExist, ((JavaElement)elements[0]).toStringWithAncestors());
-
- case ELEMENT_NOT_ON_CLASSPATH:
- return Messages.bind(Messages.element_notOnClasspath, ((JavaElement)elements[0]).toStringWithAncestors());
-
- case EVALUATION_ERROR:
- return Messages.bind(Messages.status_evaluationError, string);
-
- case INDEX_OUT_OF_BOUNDS:
- return Messages.status_indexOutOfBounds;
-
- case INVALID_CONTENTS:
- return Messages.status_invalidContents;
-
- case INVALID_DESTINATION:
- return Messages.bind(Messages.status_invalidDestination, ((JavaElement)elements[0]).toStringWithAncestors());
-
- case INVALID_ELEMENT_TYPES:
- StringBuffer buff= new StringBuffer(Messages.operation_notSupported);
- for (int i= 0; i < elements.length; i++) {
- if (i > 0) {
- buff.append(", "); //$NON-NLS-1$
- }
- buff.append(((JavaElement)elements[i]).toStringWithAncestors());
- }
- return buff.toString();
-
- case INVALID_NAME:
- return Messages.bind(Messages.status_invalidName, string);
-
- case INVALID_PACKAGE:
- return Messages.bind(Messages.status_invalidPackage, string);
-
- case INVALID_PATH:
- if (string != null) {
- return string;
- } else {
- return Messages.bind(
- Messages.status_invalidPath,
- new String[] {getPath() == null ? "null" : getPath().toString()} //$NON-NLS-1$
- );
- }
-
- case INVALID_PROJECT:
- return Messages.bind(Messages.status_invalidProject, string);
-
- case INVALID_RESOURCE:
- return Messages.bind(Messages.status_invalidResource, string);
-
- case INVALID_RESOURCE_TYPE:
- return Messages.bind(Messages.status_invalidResourceType, string);
-
- case INVALID_SIBLING:
- if (string != null) {
- return Messages.bind(Messages.status_invalidSibling, string);
- } else {
- return Messages.bind(Messages.status_invalidSibling, ((JavaElement)elements[0]).toStringWithAncestors());
- }
-
- case IO_EXCEPTION:
- return Messages.status_IOException;
-
- case NAME_COLLISION:
- if (elements != null && elements.length > 0) {
- IJavaScriptElement element = elements[0];
- if (element instanceof PackageFragment && ((PackageFragment) element).isDefaultPackage()) {
- return Messages.operation_cannotRenameDefaultPackage;
- }
- }
- if (string != null) {
- return string;
- } else {
- return Messages.bind(Messages.status_nameCollision, ""); //$NON-NLS-1$
- }
- case NO_ELEMENTS_TO_PROCESS:
- return Messages.operation_needElements;
-
- case NULL_NAME:
- return Messages.operation_needName;
-
- case NULL_PATH:
- return Messages.operation_needPath;
-
- case NULL_STRING:
- return Messages.operation_needString;
-
- case PATH_OUTSIDE_PROJECT:
- return Messages.bind(Messages.operation_pathOutsideProject, new String[] {string, ((JavaElement)elements[0]).toStringWithAncestors()});
-
- case READ_ONLY:
- IJavaScriptElement element = elements[0];
- String name = element.getElementName();
- if (element instanceof IPackageFragment && name.equals(IPackageFragment.DEFAULT_PACKAGE_NAME)) {
- return Messages.status_defaultPackageReadOnly;
- }
- return Messages.bind(Messages.status_readOnly, name);
-
- case RELATIVE_PATH:
- return Messages.bind(Messages.operation_needAbsolutePath, getPath().toString());
-
- case TARGET_EXCEPTION:
- return Messages.status_targetException;
-
- case UPDATE_CONFLICT:
- return Messages.status_updateConflict;
-
- case NO_LOCAL_CONTENTS :
- return Messages.bind(Messages.status_noLocalContents, getPath().toString());
-
- case CP_CONTAINER_PATH_UNBOUND:
- IJavaScriptProject javaProject = (IJavaScriptProject)elements[0];
- JsGlobalScopeContainerInitializer initializer = JavaScriptCore.getJsGlobalScopeContainerInitializer(this.path.segment(0));
- String description = null;
- if (initializer != null) description = initializer.getDescription(this.path, javaProject);
- if (description == null) description = path.makeRelative().toString();
- return Messages.bind(Messages.classpath_unboundContainerPath, new String[] {description, javaProject.getElementName()});
-
- case INVALID_CP_CONTAINER_ENTRY:
- javaProject = (IJavaScriptProject)elements[0];
- IJsGlobalScopeContainer container = null;
- description = null;
- try {
- container = JavaScriptCore.getJsGlobalScopeContainer(path, javaProject);
- } catch(JavaScriptModelException e){
- // project doesn't exist: ignore
- }
- if (container == null) {
- initializer = JavaScriptCore.getJsGlobalScopeContainerInitializer(path.segment(0));
- if (initializer != null) description = initializer.getDescription(path, javaProject);
- } else {
- description = container.getDescription();
- }
- if (description == null) description = path.makeRelative().toString();
- return Messages.bind(Messages.classpath_invalidContainer, new String[] {description, javaProject.getElementName()});
-
- case CP_VARIABLE_PATH_UNBOUND:
- javaProject = (IJavaScriptProject)elements[0];
- return Messages.bind(Messages.classpath_unboundVariablePath, new String[] {path.makeRelative().toString(), javaProject.getElementName()});
-
- case INCLUDEPATH_CYCLE:
- javaProject = (IJavaScriptProject)elements[0];
- return Messages.bind(Messages.classpath_cycle, javaProject.getElementName());
-
- case DISABLED_CP_EXCLUSION_PATTERNS:
- javaProject = (IJavaScriptProject)elements[0];
- String projectName = javaProject.getElementName();
- IPath newPath = path;
- if (path.segment(0).toString().equals(projectName)) {
- newPath = path.removeFirstSegments(1);
- }
- return Messages.bind(Messages.classpath_disabledInclusionExclusionPatterns, new String[] {newPath.makeRelative().toString(), projectName});
-
-
-
- case CANNOT_RETRIEVE_ATTACHED_JSDOC :
- if (elements != null && elements.length == 1) {
- if (this.string != null) {
- return Messages.bind(Messages.status_cannot_retrieve_attached_javadoc, ((JavaElement)elements[0]).toStringWithAncestors(), this.string);
- }
- return Messages.bind(Messages.status_cannot_retrieve_attached_javadoc, ((JavaElement)elements[0]).toStringWithAncestors(), ""); //$NON-NLS-1$
- }
- if (this.string != null) {
- return Messages.bind(Messages.status_cannot_retrieve_attached_javadoc, this.string, "");//$NON-NLS-1$
- }
- break;
-
- case UNKNOWN_JSDOC_FORMAT :
- return Messages.bind(Messages.status_unknown_javadoc_format, ((JavaElement)elements[0]).toStringWithAncestors());
-
- case DEPRECATED_VARIABLE :
- javaProject = (IJavaScriptProject)elements[0];
- return Messages.bind(Messages.classpath_deprecated_variable, new String[] {path.segment(0).toString(), javaProject.getElementName(), this.string});
- }
- if (string != null) {
- return string;
- } else {
- return ""; //$NON-NLS-1$
- }
- } else {
- String message = exception.getMessage();
- if (message != null) {
- return message;
- } else {
- return exception.toString();
- }
- }
- }
- /**
- * @see IJavaScriptModelStatus#getPath()
- */
- public IPath getPath() {
- return path;
- }
- /**
- * @see IStatus#getSeverity()
- */
- public int getSeverity() {
- if (children == NO_CHILDREN) return super.getSeverity();
- int severity = -1;
- for (int i = 0, max = children.length; i < max; i++) {
- int childrenSeverity = children[i].getSeverity();
- if (childrenSeverity > severity) {
- severity = childrenSeverity;
- }
- }
- return severity;
- }
- /**
- * @see IJavaScriptModelStatus#isDoesNotExist()
- */
- public boolean isDoesNotExist() {
- int code = getCode();
- return code == ELEMENT_DOES_NOT_EXIST || code == ELEMENT_NOT_ON_CLASSPATH;
- }
- /**
- * @see IStatus#isMultiStatus()
- */
- public boolean isMultiStatus() {
- return children != NO_CHILDREN;
- }
- /**
- * @see IStatus#isOK()
- */
- public boolean isOK() {
- return getCode() == OK;
- }
- /**
- * @see IStatus#matches(int)
- */
- public boolean matches(int mask) {
- if (! isMultiStatus()) {
- return matches(this, mask);
- } else {
- for (int i = 0, max = children.length; i < max; i++) {
- if (matches((JavaModelStatus) children[i], mask))
- return true;
- }
- return false;
- }
- }
- /**
- * Helper for matches(int).
- */
- protected boolean matches(JavaModelStatus status, int mask) {
- int severityMask = mask & 0x7;
- int categoryMask = mask & ~0x7;
- int bits = status.getBits();
- return ((severityMask == 0) || (bits & severityMask) != 0) && ((categoryMask == 0) || (bits & categoryMask) != 0);
- }
- /**
- * Creates and returns a new <code>IJavaScriptModelStatus</code> that is a
- * a multi-status status.
- *
- * @see IStatus#isMultiStatus()
- */
- public static IJavaScriptModelStatus newMultiStatus(IJavaScriptModelStatus[] children) {
- JavaModelStatus jms = new JavaModelStatus();
- jms.children = children;
- return jms;
- }
- /**
- * Returns a printable representation of this exception for debugging
- * purposes.
- */
- public String toString() {
- if (this == VERIFIED_OK){
- return "JavaScriptModelStatus[OK]"; //$NON-NLS-1$
- }
- StringBuffer buffer = new StringBuffer();
- buffer.append("JavaScript Model Status ["); //$NON-NLS-1$
- buffer.append(getMessage());
- buffer.append("]"); //$NON-NLS-1$
- return buffer.toString();
- }
-}
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
deleted file mode 100644
index f2acc4c2..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaProject.java
+++ /dev/null
@@ -1,3227 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core;
-
-import java.io.BufferedInputStream;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStreamWriter;
-import java.io.StringReader;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.Map;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-
-import org.eclipse.core.resources.ICommand;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IProjectDescription;
-import org.eclipse.core.resources.IProjectNature;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ProjectScope;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.AssertionFailedException;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Preferences;
-import org.eclipse.core.runtime.QualifiedName;
-import org.eclipse.core.runtime.preferences.IEclipsePreferences;
-import org.eclipse.core.runtime.preferences.IScopeContext;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelMarker;
-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.IJsGlobalScopeContainer;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IRegion;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-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.core.LibrarySuperType;
-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.eval.IEvaluationContext;
-import org.eclipse.wst.jsdt.internal.compiler.util.ObjectVector;
-import org.eclipse.wst.jsdt.internal.compiler.util.SuffixConstants;
-import org.eclipse.wst.jsdt.internal.core.JavaModelManager.PerProjectInfo;
-import org.eclipse.wst.jsdt.internal.core.JavaProjectElementInfo.LookupCache;
-import org.eclipse.wst.jsdt.internal.core.builder.JavaBuilder;
-import org.eclipse.wst.jsdt.internal.core.util.HandleFactory;
-import org.eclipse.wst.jsdt.internal.core.util.MementoTokenizer;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-import org.eclipse.wst.jsdt.launching.JavaRuntime;
-import org.osgi.service.prefs.BackingStoreException;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-
-/**
- * Handle for a Java Project.
- *
- * <p>A Java Project internally maintains a devpath that corresponds
- * to the project's classpath. The classpath may include source folders
- * from the current project; jars in the current project, other projects,
- * and the local file system; and binary folders (output location) of other
- * projects. The Java Model presents source elements corresponding to output
- * .class files in other projects, and thus uses the devpath rather than
- * the classpath (which is really a compilation path). The devpath mimics
- * the classpath, except has source folder entries in place of output
- * locations in external projects.
- *
- * <p>Each JavaProject has a NameLookup facility that locates elements
- * on by name, based on the devpath.
- *
- * @see IJavaScriptProject
- */
-public class JavaProject
- extends Openable
- implements IJavaScriptProject, IProjectNature, SuffixConstants {
-
- /**
- * Name of file containing project classpath
- */
- //public static final String CLASSPATH_FILENAME = ".jsdtscope"; //$NON-NLS-1$
-
- /**
- * Value of the project's raw classpath if the .classpath file contains invalid entries.
- */
- public static final IIncludePathEntry[] INVALID_CLASSPATH = new IIncludePathEntry[0];
-
- /* default CLASSPATH for projects without a classpath set.
- *
- */
-
- /**
- * Whether the underlying file system is case sensitive.
- */
- protected static final boolean IS_CASE_SENSITIVE = !new File("Temp").equals(new File("temp")); //$NON-NLS-1$ //$NON-NLS-2$
-
- /**
- * An empty array of strings indicating that a project doesn't have any prerequesite projects.
- */
- protected static final String[] NO_PREREQUISITES = CharOperation.NO_STRINGS;
-
- /**
- * Name of file containing custom project preferences
- * @see <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=59258">bug 59258</a>
- */
- private static final String PREF_FILENAME = ".jprefs"; //$NON-NLS-1$
-
- /**
- * Name of directory containing preferences file
- */
- public static final String DEFAULT_PREFERENCES_DIRNAME = ".settings"; //$NON-NLS-1$
-
- /**
- * Extension for file containing custom project preferences
- */
- public static final String JAVA_CORE_PREFS_FILE = JavaScriptCore.PLUGIN_ID+".prefs"; //$NON-NLS-1$
-
- /*
- * Value of project's resolved classpath while it is being resolved
- */
- private static final IIncludePathEntry[] RESOLUTION_IN_PROGRESS = new IIncludePathEntry[0];
-
- public static final String SHARED_PROPERTIES_DIRECTORY = ".settings"; //$NON-NLS-1$
-
- /**
- * Name of file containing project classpath
- * appended settings directory per bug: 210831
- */
-
- public static final String CLASSPATH_FILENAME = ".jsdtscope"; //$NON-NLS-1$
- /**
- * The platform project this <code>IJavaScriptProject</code> is based on
- */
- protected IProject project;
-
- /**
- * Constructor needed for <code>IProject.getNature()</code> and <code>IProject.addNature()</code>.
- *
- * @see #setProject(IProject)
- */
- public JavaProject() {
- super(null);
- }
-
- public IFile getJSDTScopeFile() {
- return getJSDTScopeFile(false);
- }
-
- public IFile getJSDTScopeFile(boolean forceCreate) {
-
- // Return the projects .jsdtscope file
- IFolder rscPath = this.project.getFolder(JavaProject.SHARED_PROPERTIES_DIRECTORY);
- if(!rscPath.exists()&&forceCreate)
- try {
- rscPath.create(true, true, new NullProgressMonitor());
- }
- catch (CoreException e) {}
-
-
- return rscPath.getFile(CLASSPATH_FILENAME);
-
-
-
- }
-
-
- public JavaProject(IProject project, JavaElement parent) {
- super(parent);
- this.project = project;
- }
-
- public static boolean areClasspathsEqual(
- IIncludePathEntry[] firstClasspath, IIncludePathEntry[] secondClasspath,
- IPath firstOutputLocation, IPath secondOutputLocation) {
- int length = firstClasspath.length;
- if (length != secondClasspath.length) return false;
- for (int i = 0; i < length; i++) {
- if (!firstClasspath[i].equals(secondClasspath[i]))
- return false;
- }
- if (firstOutputLocation == null)
- return secondOutputLocation == null;
- return firstOutputLocation.equals(secondOutputLocation);
- }
-
- /**
- * Compare current classpath with given one to see if any different.
- * Note that the argument classpath contains its binary output.
- * @param newClasspath IIncludePathEntry[]
- * @param newOutputLocation IPath
- * @param otherClasspathWithOutput IIncludePathEntry[]
- * @return boolean
- */
- private static boolean areClasspathsEqual(IIncludePathEntry[] newClasspath, IPath newOutputLocation, IIncludePathEntry[] otherClasspathWithOutput) {
-
- if (otherClasspathWithOutput == null || otherClasspathWithOutput.length == 0)
- return false;
-
- int length = otherClasspathWithOutput.length;
- if (length != newClasspath.length + 1)
- // output is amongst file entries (last one)
- return false;
-
-
- // compare classpath entries
- for (int i = 0; i < length - 1; i++) {
- if (!otherClasspathWithOutput[i].equals(newClasspath[i]))
- return false;
- }
- // compare binary outputs
- IIncludePathEntry output = otherClasspathWithOutput[length - 1];
- if (output.getContentKind() != ClasspathEntry.K_OUTPUT
- || !output.getPath().equals(newOutputLocation))
- return false;
- return true;
- }
-
- /**
- * Returns a canonicalized path from the given external path.
- * Note that the return path contains the same number of segments
- * and it contains a device only if the given path contained one.
- * @param externalPath IPath
- * @see java.io.File for the definition of a canonicalized path
- * @return IPath
- */
- public static IPath canonicalizedPath(IPath externalPath) {
-
- if (externalPath == null)
- return null;
-
-// if (JavaModelManager.VERBOSE) {
-// System.out.println("JAVA MODEL - Canonicalizing " + externalPath.toString());
-// }
-
- if (IS_CASE_SENSITIVE) {
-// if (JavaModelManager.VERBOSE) {
-// System.out.println("JAVA MODEL - Canonical path is original path (file system is case sensitive)");
-// }
- return new Path(new File(externalPath.toOSString()).getPath());
- }
-
- // if not external path, return original path
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- if (workspace == null) return externalPath; // protection during shutdown (30487)
- if (workspace.getRoot().findMember(externalPath) != null) {
-// if (JavaModelManager.VERBOSE) {
-// System.out.println("JAVA MODEL - Canonical path is original path (member of workspace)");
-// }
- return externalPath;
- }
-
- IPath canonicalPath = null;
- try {
- canonicalPath =
- new Path(new File(externalPath.toOSString()).getCanonicalPath());
- } catch (IOException e) {
- // default to original path
-// if (JavaModelManager.VERBOSE) {
-// System.out.println("JAVA MODEL - Canonical path is original path (IOException)");
-// }
- return externalPath;
- }
-
- IPath result;
- int canonicalLength = canonicalPath.segmentCount();
- if (canonicalLength == 0) {
- // the java.io.File canonicalization failed
-// if (JavaModelManager.VERBOSE) {
-// System.out.println("JAVA MODEL - Canonical path is original path (canonical path is empty)");
-// }
- return externalPath;
- } else if (externalPath.isAbsolute()) {
- result = canonicalPath;
- } else {
- // if path is relative, remove the first segments that were added by the java.io.File canonicalization
- // e.g. 'lib/classes.zip' was converted to 'd:/myfolder/lib/classes.zip'
- int externalLength = externalPath.segmentCount();
- if (canonicalLength >= externalLength) {
- result = canonicalPath.removeFirstSegments(canonicalLength - externalLength);
- } else {
-// if (JavaModelManager.VERBOSE) {
-// System.out.println("JAVA MODEL - Canonical path is original path (canonical path is " + canonicalPath.toString() + ")");
-// }
- return externalPath;
- }
- }
-
- // keep device only if it was specified (this is because File.getCanonicalPath() converts '/lib/classed.zip' to 'd:/lib/classes/zip')
- if (externalPath.getDevice() == null) {
- result = result.setDevice(null);
- }
-// if (JavaModelManager.VERBOSE) {
-// System.out.println("JAVA MODEL - Canonical path is " + result.toString());
-// }
- return result;
- }
-
- /**
- * Returns true if the given project is accessible and it has
- * a java nature, otherwise false.
- * @param project IProject
- * @return boolean
- */
- public static boolean hasJavaNature(IProject project) {
- try {
- return project.hasNature(JavaScriptCore.NATURE_ID);
- } catch (CoreException e) {
- if (ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals(project.getName()))
- return true;
- // project does not exist or is not open
- }
- return false;
- }
-
- public static boolean hasJSDTScope(IProject project) {
-
-
- IFile file = project.getFile(CLASSPATH_FILENAME);
- if (file!=null && file.exists())
- return true;
-
- IFolder rscPath = project.getFolder(JavaProject.SHARED_PROPERTIES_DIRECTORY);
- if(rscPath.exists())
- {
- file = rscPath.getFile(CLASSPATH_FILENAME);
- if (file!=null && file.exists())
- return true;
-
- }
-
- return false;
- }
-
-
-
- /*
- * Detect cycles in the classpath of the workspace's projects
- * and create markers if necessary.
- * @param preferredClasspaths Map
- * @throws JavaScriptModelException
- */
- public static void validateCycles(Map preferredClasspaths) throws JavaScriptModelException {
-
- //long start = System.currentTimeMillis();
-
- IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
- IProject[] rscProjects = workspaceRoot.getProjects();
- int length = rscProjects.length;
- JavaProject[] projects = new JavaProject[length];
-
- HashSet cycleParticipants = new HashSet();
- HashSet traversed = new HashSet();
-
- // compute cycle participants
- ArrayList prereqChain = new ArrayList();
- for (int i = 0; i < length; i++){
- if (hasJavaNature(rscProjects[i])) {
- JavaProject project = (projects[i] = (JavaProject)JavaScriptCore.create(rscProjects[i]));
- if (!traversed.contains(project.getPath())){
- prereqChain.clear();
- project.updateCycleParticipants(prereqChain, cycleParticipants, workspaceRoot, traversed, preferredClasspaths);
- }
- }
- }
- //System.out.println("updateAllCycleMarkers: " + (System.currentTimeMillis() - start) + " ms");
-
- for (int i = 0; i < length; i++){
- JavaProject project = projects[i];
- if (project != null) {
- if (cycleParticipants.contains(project.getPath())){
- IMarker cycleMarker = project.getCycleMarker();
- String circularCPOption = project.getOption(JavaScriptCore.CORE_CIRCULAR_CLASSPATH, true);
- int circularCPSeverity = JavaScriptCore.ERROR.equals(circularCPOption) ? IMarker.SEVERITY_ERROR : IMarker.SEVERITY_WARNING;
- if (cycleMarker != null) {
- // update existing cycle marker if needed
- try {
- int existingSeverity = ((Integer)cycleMarker.getAttribute(IMarker.SEVERITY)).intValue();
- if (existingSeverity != circularCPSeverity) {
- cycleMarker.setAttribute(IMarker.SEVERITY, circularCPSeverity);
- }
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- }
- } else {
- // create new marker
- project.createClasspathProblemMarker(
- new JavaModelStatus(IJavaScriptModelStatusConstants.INCLUDEPATH_CYCLE, project));
- }
- } else {
- project.flushClasspathProblemMarkers(true, false);
- }
- }
- }
- }
-
- /**
- * Adds a builder to the build spec for the given project.
- */
- public void addToBuildSpec(String builderID) throws CoreException {
-
- IProjectDescription description = this.project.getDescription();
- int javaCommandIndex = getJavaCommandIndex(description.getBuildSpec(), builderID);
-
- if (javaCommandIndex == -1) {
-
- // Add a Java command to the build spec
- ICommand command = description.newCommand();
- command.setBuilderName(builderID);
- setJavaCommand(description, command);
- }
- }
- /**
- * @see Openable
- */
- protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaScriptModelException {
-
- IIncludePathEntry[] resolvedClasspath =null;
- // check whether the java project can be opened
- if (!hasJavaNature((IProject) underlyingResource)) {
-// throw newNotPresentException();
-// resolvedClasspath = getDefaultClasspath();
- }
- // cannot refresh cp markers on opening (emulate cp check on startup) since can create deadlocks (see bug 37274)
- resolvedClasspath = getResolvedClasspath();
-
- // compute the pkg fragment roots
- info.setChildren(computePackageFragmentRoots(resolvedClasspath, false, null /*no reverse map*/));
-
- // remember the timestamps of external libraries the first time they are looked up
- try {
- getPerProjectInfo().rememberExternalLibTimestamps();
- } catch (JavaScriptModelException e) {
- if (e.getStatus().getCode()!=IJavaScriptModelStatusConstants.ELEMENT_DOES_NOT_EXIST)
- throw e;
- }
-
- return true;
- }
-
- private IIncludePathEntry[] getDefaultClasspath() {
- IIncludePathEntry[] defaultClasspath = {JavaScriptCore.newContainerEntry(new Path(JavaRuntime.JRE_CONTAINER)),
- JavaScriptCore.newContainerEntry(new Path(JavaRuntime.BASE_BROWSER_LIB)),
- JavaScriptCore.newSourceEntry(getProject().getFullPath())};
-
-
- return defaultClasspath;
- }
-
- /**
- * Computes the collection of package fragment roots (local ones) and set it on the given info.
- * Need to check *all* package fragment roots in order to reset NameLookup
- * @param info JavaProjectElementInfo
- * @throws JavaScriptModelException
- */
- public void computeChildren(JavaProjectElementInfo info) throws JavaScriptModelException {
- IIncludePathEntry[] classpath = getResolvedClasspath();
- JavaProjectElementInfo.LookupCache projectCache = info.projectCache;
- if (projectCache != null) {
- IPackageFragmentRoot[] newRoots = computePackageFragmentRoots(classpath, true, null /*no reverse map*/);
- checkIdentical: { // compare all pkg fragment root lists
- IPackageFragmentRoot[] oldRoots = projectCache.allPkgFragmentRootsCache;
- if (oldRoots.length == newRoots.length){
- for (int i = 0, length = oldRoots.length; i < length; i++){
- if (!oldRoots[i].equals(newRoots[i])){
- break checkIdentical;
- }
- }
- return; // no need to update
- }
- }
- }
- info.setNonJavaResources(null);
- info.setChildren(
- computePackageFragmentRoots(classpath, false, null /*no reverse map*/));
- }
-
- /**
- * Internal computation of an expanded classpath. It will eliminate duplicates, and produce copies
- * of exported or restricted classpath entries to avoid possible side-effects ever after.
- */
- private void computeExpandedClasspath(
- ClasspathEntry referringEntry,
- HashSet rootIDs,
- ObjectVector accumulatedEntries) throws JavaScriptModelException {
-
- String projectRootId = this.rootID();
- if (rootIDs.contains(projectRootId)){
- return; // break cycles if any
- }
- rootIDs.add(projectRootId);
-
- IIncludePathEntry[] resolvedClasspath = getResolvedClasspath();
-
- IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
- boolean isInitialProject = referringEntry == null;
- for (int i = 0, length = resolvedClasspath.length; i < length; i++){
- ClasspathEntry entry = (ClasspathEntry) resolvedClasspath[i];
- if (isInitialProject || entry.isExported()){
- String rootID = entry.rootID();
- if (rootIDs.contains(rootID)) {
- continue;
- }
- // combine restrictions along the project chain
- ClasspathEntry combinedEntry = entry.combineWith(referringEntry);
- accumulatedEntries.add(combinedEntry);
-
- // recurse in project to get all its indirect exports (only consider exported entries from there on)
- if (entry.getEntryKind() == IIncludePathEntry.CPE_PROJECT) {
- IResource member = workspaceRoot.findMember(entry.getPath());
- if (member != null && member.getType() == IResource.PROJECT){ // double check if bound to project (23977)
- IProject projRsc = (IProject) member;
- if (JavaProject.hasJavaNature(projRsc)) {
- JavaProject javaProject = (JavaProject) JavaScriptCore.create(projRsc);
- javaProject.computeExpandedClasspath(
- combinedEntry,
- rootIDs,
- accumulatedEntries);
- }
- }
- } else {
- rootIDs.add(rootID);
- }
- }
- }
- }
-
- /**
- * Computes the package fragment roots identified by the given entry.
- * Only works with resolved entry
- * @param resolvedEntry IIncludePathEntry
- * @return IPackageFragmentRoot[]
- */
- public IPackageFragmentRoot[] computePackageFragmentRoots(IIncludePathEntry resolvedEntry) {
- try {
- return
- computePackageFragmentRoots(
- new IIncludePathEntry[]{ resolvedEntry },
- false, // don't retrieve exported roots
- null /* no reverse map */
- );
- } catch (JavaScriptModelException e) {
- return new IPackageFragmentRoot[] {};
- }
- }
-
- /**
- * Returns the package fragment roots identified by the given entry. In case it refers to
- * a project, it will follow its classpath so as to find exported roots as well.
- * Only works with resolved entry
- * @param resolvedEntry IIncludePathEntry
- * @param accumulatedRoots ObjectVector
- * @param rootIDs HashSet
- * @param referringEntry the CP entry (project) referring to this entry, or null if initial project
- * @param checkExistency boolean
- * @param retrieveExportedRoots boolean
- * @throws JavaScriptModelException
- */
- public void computePackageFragmentRoots(
- IIncludePathEntry resolvedEntry,
- ObjectVector accumulatedRoots,
- HashSet rootIDs,
- IIncludePathEntry referringEntry,
- boolean checkExistency,
- boolean retrieveExportedRoots,
- Map rootToResolvedEntries) throws JavaScriptModelException {
-
- String rootID = ((ClasspathEntry)resolvedEntry).rootID();
- if (rootIDs.contains(rootID)) return;
-
- IPath projectPath = this.project.getFullPath();
- IPath entryPath = resolvedEntry.getPath();
- IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
- IPackageFragmentRoot root = null;
-
- switch(resolvedEntry.getEntryKind()){
-
- // source folder
- case IIncludePathEntry.CPE_SOURCE :
-
- if (projectPath.isPrefixOf(entryPath)){
- if (checkExistency) {
- Object target = JavaModel.getTarget(workspaceRoot, entryPath, checkExistency);
- if (target == null) return;
-
- if (target instanceof IFolder || target instanceof IProject){
- root = getPackageFragmentRoot((IResource)target);
- }
- } else {
- root = getFolderPackageFragmentRoot(entryPath);
- }
- }
- break;
-
- // internal/external JAR or folder
- case IIncludePathEntry.CPE_LIBRARY :
-
- if (referringEntry != null && !resolvedEntry.isExported()) return;
-
- if (checkExistency) {
- Object target = JavaModel.getTarget(workspaceRoot, entryPath, checkExistency);
- if (target == null) return;
-
- if (target instanceof IResource){
- // internal target
- root = getPackageFragmentRoot((IResource) target);
- } else {
- // external target - only JARs 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);
-
- }
- }
- }
- } else {
- root = getPackageFragmentRoot(entryPath);
- }
- break;
-
- // recurse into required project
- case IIncludePathEntry.CPE_PROJECT :
-
- if (!retrieveExportedRoots) return;
- if (referringEntry != null && !resolvedEntry.isExported()) return;
-
- IResource member = workspaceRoot.findMember(entryPath);
- if (member != null && member.getType() == IResource.PROJECT){// double check if bound to project (23977)
- IProject requiredProjectRsc = (IProject) member;
- if (JavaProject.hasJavaNature(requiredProjectRsc)){ // special builder binary output
- rootIDs.add(rootID);
- JavaProject requiredProject = (JavaProject)JavaScriptCore.create(requiredProjectRsc);
- requiredProject.computePackageFragmentRoots(
- requiredProject.getResolvedClasspath(),
- accumulatedRoots,
- rootIDs,
- rootToResolvedEntries == null ? resolvedEntry : ((ClasspathEntry)resolvedEntry).combineWith((ClasspathEntry) referringEntry), // only combine if need to build the reverse map
- checkExistency,
- retrieveExportedRoots,
- rootToResolvedEntries);
- }
- break;
- }
- }
- if (root != null) {
- accumulatedRoots.add(root);
- rootIDs.add(rootID);
- if (rootToResolvedEntries != null) rootToResolvedEntries.put(root, ((ClasspathEntry)resolvedEntry).combineWith((ClasspathEntry) referringEntry));
- }
- }
-
- /**
- * Returns (local/all) the package fragment roots identified by the given project's classpath.
- * Note: this follows project classpath references to find required project contributions,
- * eliminating duplicates silently.
- * Only works with resolved entries
- * @param resolvedClasspath IIncludePathEntry[]
- * @param retrieveExportedRoots boolean
- * @return IPackageFragmentRoot[]
- * @throws JavaScriptModelException
- */
- public IPackageFragmentRoot[] computePackageFragmentRoots(
- IIncludePathEntry[] resolvedClasspath,
- boolean retrieveExportedRoots,
- Map rootToResolvedEntries) throws JavaScriptModelException {
-
- ObjectVector accumulatedRoots = new ObjectVector();
- computePackageFragmentRoots(
- resolvedClasspath,
- accumulatedRoots,
- new HashSet(5), // rootIDs
- null, // inside original project
- true, // check existency
- retrieveExportedRoots,
- rootToResolvedEntries);
- IPackageFragmentRoot[] rootArray = new IPackageFragmentRoot[accumulatedRoots.size()];
- accumulatedRoots.copyInto(rootArray);
- return rootArray;
- }
-
- /**
- * Returns (local/all) the package fragment roots identified by the given project's classpath.
- * Note: this follows project classpath references to find required project contributions,
- * eliminating duplicates silently.
- * Only works with resolved entries
- * @param resolvedClasspath IIncludePathEntry[]
- * @param accumulatedRoots ObjectVector
- * @param rootIDs HashSet
- * @param referringEntry project entry referring to this CP or null if initial project
- * @param checkExistency boolean
- * @param retrieveExportedRoots boolean
- * @throws JavaScriptModelException
- */
- public void computePackageFragmentRoots(
- IIncludePathEntry[] resolvedClasspath,
- ObjectVector accumulatedRoots,
- HashSet rootIDs,
- IIncludePathEntry referringEntry,
- boolean checkExistency,
- boolean retrieveExportedRoots,
- Map rootToResolvedEntries) throws JavaScriptModelException {
-
- if (referringEntry == null){
- rootIDs.add(rootID());
- }
- for (int i = 0, length = resolvedClasspath.length; i < length; i++){
- computePackageFragmentRoots(
- resolvedClasspath[i],
- accumulatedRoots,
- rootIDs,
- referringEntry,
- checkExistency,
- retrieveExportedRoots,
- rootToResolvedEntries);
- }
- }
- /**
- * Compute the file name to use for a given shared property
- * @param qName QualifiedName
- * @return String
- */
- public String computeSharedPropertyFileName(QualifiedName qName) {
-
- return '.' + qName.getLocalName();
- }
-
- /**
- * Configure the project with Java nature.
- */
- public void configure() throws CoreException {
-
- // register Java builder
- addToBuildSpec(JavaScriptCore.BUILDER_ID);
- }
-
- /*
- * Returns whether the given resource is accessible through the children or the non-Java resources of this project.
- * Returns true if the resource is not in the project.
- * Assumes that the resource is a folder or a file.
- */
- public boolean contains(IResource resource) {
-
- IIncludePathEntry[] classpath;
- IPath output;
- try {
- classpath = getResolvedClasspath();
- output = getOutputLocation();
- } catch (JavaScriptModelException e) {
- return false;
- }
-
- IPath fullPath = resource.getFullPath();
- IPath innerMostOutput = output.isPrefixOf(fullPath) ? output : null;
- IIncludePathEntry innerMostEntry = null;
- for (int j = 0, cpLength = classpath.length; j < cpLength; j++) {
- IIncludePathEntry entry = classpath[j];
-
- IPath entryPath = entry.getPath();
- if ((innerMostEntry == null || innerMostEntry.getPath().isPrefixOf(entryPath))
- && entryPath.isPrefixOf(fullPath)) {
- innerMostEntry = entry;
- }
- }
- if (innerMostEntry != null) {
- // special case prj==src and nested output location
- if (innerMostOutput != null && innerMostOutput.segmentCount() > 1 // output isn't project
- && innerMostEntry.getPath().segmentCount() == 1) { // 1 segment must be project name
- return false;
- }
- if (resource instanceof IFolder) {
- // folders are always included in src/lib entries
- return true;
- }
- return true;
-// switch (innerMostEntry.getEntryKind()) {
-// case IIncludePathEntry.CPE_SOURCE:
-// // .class files are not visible in source folders
-// return !org.eclipse.wst.jsdt.internal.compiler.util.Util.isClassFileName(fullPath.lastSegment());
-// case IIncludePathEntry.CPE_LIBRARY:
-// // .js files are not visible in library folders
-// return !org.eclipse.wst.jsdt.internal.core.util.Util.isJavaLikeFileName(fullPath.lastSegment());
-// }
- }
- if (innerMostOutput != null) {
- return false;
- }
- return true;
- }
-
- /**
- * Record a new marker denoting a classpath problem
- */
- public void createClasspathProblemMarker(IJavaScriptModelStatus status) {
-
- IMarker marker = null;
- int severity;
- String[] arguments = CharOperation.NO_STRINGS;
- boolean isCycleProblem = false, isClasspathFileFormatProblem = false;
- switch (status.getCode()) {
-
- case IJavaScriptModelStatusConstants.INCLUDEPATH_CYCLE :
- isCycleProblem = true;
- if (JavaScriptCore.ERROR.equals(getOption(JavaScriptCore.CORE_CIRCULAR_CLASSPATH, true))) {
- severity = IMarker.SEVERITY_ERROR;
- } else {
- severity = IMarker.SEVERITY_WARNING;
- }
- break;
-
- case IJavaScriptModelStatusConstants.INVALID_INCLUDEPATH_FILE_FORMAT :
- isClasspathFileFormatProblem = true;
- severity = IMarker.SEVERITY_ERROR;
- break;
-
-// case IJavaScriptModelStatusConstants.INCOMPATIBLE_JDK_LEVEL :
-// String setting = getOption(JavaScriptCore.CORE_INCOMPATIBLE_JDK_LEVEL, true);
-// if (JavaScriptCore.ERROR.equals(setting)) {
-// severity = IMarker.SEVERITY_ERROR;
-// } else if (JavaScriptCore.WARNING.equals(setting)) {
-// severity = IMarker.SEVERITY_WARNING;
-// } else {
-// return; // setting == IGNORE
-// }
-// break;
-
- default:
- IPath path = status.getPath();
- if (path != null) arguments = new String[] { path.toString() };
- if (JavaScriptCore.ERROR.equals(getOption(JavaScriptCore.CORE_INCOMPLETE_CLASSPATH, true)) &&
- status.getSeverity() != IStatus.WARNING) {
- severity = IMarker.SEVERITY_ERROR;
- } else {
- severity = IMarker.SEVERITY_WARNING;
- }
- break;
- }
-
- try {
- marker = this.project.createMarker(IJavaScriptModelMarker.BUILDPATH_PROBLEM_MARKER);
- marker.setAttributes(
- new String[] {
- IMarker.MESSAGE,
- IMarker.SEVERITY,
- IMarker.LOCATION,
- IJavaScriptModelMarker.CYCLE_DETECTED,
- IJavaScriptModelMarker.INCLUDEPATH_FILE_FORMAT,
- IJavaScriptModelMarker.ID,
- IJavaScriptModelMarker.ARGUMENTS ,
- IJavaScriptModelMarker.CATEGORY_ID,
- IMarker.SOURCE_ID,
- },
- new Object[] {
- status.getMessage(),
- new Integer(severity),
- Messages.classpath_buildPath,
- isCycleProblem ? "true" : "false",//$NON-NLS-1$ //$NON-NLS-2$
- isClasspathFileFormatProblem ? "true" : "false",//$NON-NLS-1$ //$NON-NLS-2$
- new Integer(status.getCode()),
- Util.getProblemArgumentsForMarker(arguments) ,
- new Integer(CategorizedProblem.CAT_BUILDPATH),
- JavaBuilder.SOURCE_ID,
- }
- );
- } catch (CoreException e) {
- // could not create marker: cannot do much
- if (JavaModelManager.VERBOSE) {
- e.printStackTrace();
- }
- }
- }
-
- /**
- * Returns a new element info for this element.
- */
- protected Object createElementInfo() {
- return new JavaProjectElementInfo();
- }
-
- /*
- * Reads and decode an XML classpath string
- */
- public IIncludePathEntry[] decodeClasspath(String xmlClasspath, Map unknownElements) throws IOException, AssertionFailedException {
-
- ArrayList paths = new ArrayList();
- IIncludePathEntry defaultOutput = null;
- StringReader reader = new StringReader(xmlClasspath);
- Element cpElement;
- try {
- DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
- cpElement = parser.parse(new InputSource(reader)).getDocumentElement();
- } catch (SAXException e) {
- throw new IOException(Messages.file_badFormat);
- } catch (ParserConfigurationException e) {
- throw new IOException(Messages.file_badFormat);
- } finally {
- reader.close();
- }
-
- if (!cpElement.getNodeName().equalsIgnoreCase("classpath")) { //$NON-NLS-1$
- throw new IOException(Messages.file_badFormat);
- }
- NodeList list = cpElement.getElementsByTagName("classpathentry"); //$NON-NLS-1$
- int length = list.getLength();
-
- for (int i = 0; i < length; ++i) {
- Node node = list.item(i);
- if (node.getNodeType() == Node.ELEMENT_NODE) {
- IIncludePathEntry entry = ClasspathEntry.elementDecode((Element)node, this, unknownElements);
- if (entry != null){
- if (entry.getContentKind() == ClasspathEntry.K_OUTPUT) {
- defaultOutput = entry; // separate output
- } else {
- paths.add(entry);
- }
- }
- }
- }
- // return a new empty classpath is it size is 0, to differenciate from an INVALID_INCLUDEPATH
- int pathSize = paths.size();
- IIncludePathEntry[] entries = new IIncludePathEntry[pathSize + (defaultOutput == null ? 0 : 1)];
- paths.toArray(entries);
- if (defaultOutput != null) entries[pathSize] = defaultOutput; // ensure output is last item
- return entries;
- }
-
- public IIncludePathEntry decodeIncludepathEntry(String encodedEntry) {
-
- try {
- if (encodedEntry == null) return null;
- StringReader reader = new StringReader(encodedEntry);
- Element node;
-
- try {
- DocumentBuilder parser =
- DocumentBuilderFactory.newInstance().newDocumentBuilder();
- node = parser.parse(new InputSource(reader)).getDocumentElement();
- } catch (SAXException e) {
- return null;
- } catch (ParserConfigurationException e) {
- return null;
- } finally {
- reader.close();
- }
-
- if (!node.getNodeName().equalsIgnoreCase("classpathentry") //$NON-NLS-1$
- || node.getNodeType() != Node.ELEMENT_NODE) {
- return null;
- }
- return ClasspathEntry.elementDecode(node, this, null/*not interested in unknown elements*/);
- } catch (IOException e) {
- // bad format
- return null;
- }
- }
-
- /**
- /**
- * Removes the Java nature from the project.
- */
- public void deconfigure() throws CoreException {
-
- // deregister Java builder
- removeFromBuildSpec(JavaScriptCore.BUILDER_ID);
-
- // remove .classpath file
-// getProject().getFile(ClasspathHelper.CLASSPATH_FILENAME).delete(false, null);
- }
-
- /**
- * Returns a default class path.
- * This is the root of the project
- */
- protected IIncludePathEntry[] defaultClasspath() {
- return getDefaultClasspath();
-// return new IIncludePathEntry[] {
-// JavaScriptCore.newSourceEntry(this.project.getFullPath())};
- }
-
- /**
- * Returns a default output location.
- * This is the project bin folder
- */
- protected IPath defaultOutputLocation() {
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=272495
- return this.project.getFullPath(); //$NON-NLS-1$
- }
-
- /**
- * Returns the XML String encoding of the class path.
- */
- protected String encodeClasspath(IIncludePathEntry[] classpath, IPath outputLocation, boolean indent, Map unknownElements) throws JavaScriptModelException {
- try {
- ByteArrayOutputStream s = new ByteArrayOutputStream();
- OutputStreamWriter writer = new OutputStreamWriter(s, "UTF8"); //$NON-NLS-1$
- XMLWriter xmlWriter = new XMLWriter(writer, this, true/*print XML version*/);
-
- xmlWriter.startTag(ClasspathEntry.TAG_CLASSPATH, indent);
- for (int i = 0; i < classpath.length; ++i) {
- ((ClasspathEntry)classpath[i]).elementEncode(xmlWriter, this.project.getFullPath(), indent, true, unknownElements);
- }
-
- if (outputLocation != null) {
- outputLocation = outputLocation.removeFirstSegments(1);
- outputLocation = outputLocation.makeRelative();
- HashMap parameters = new HashMap();
- parameters.put(ClasspathEntry.TAG_KIND, ClasspathEntry.kindToString(ClasspathEntry.K_OUTPUT));
- parameters.put(ClasspathEntry.TAG_PATH, String.valueOf(outputLocation));
- xmlWriter.printTag(ClasspathEntry.TAG_CLASSPATHENTRY, parameters, indent, true, true);
- }
-
- xmlWriter.endTag(ClasspathEntry.TAG_CLASSPATH, indent, true/*insert new line*/);
- writer.flush();
- writer.close();
- return s.toString("UTF8");//$NON-NLS-1$
- } catch (IOException e) {
- throw new JavaScriptModelException(e, IJavaScriptModelStatusConstants.IO_EXCEPTION);
- }
- }
-
- public String encodeIncludepathEntry(IIncludePathEntry classpathEntry) {
- try {
- ByteArrayOutputStream s = new ByteArrayOutputStream();
- OutputStreamWriter writer = new OutputStreamWriter(s, "UTF8"); //$NON-NLS-1$
- XMLWriter xmlWriter = new XMLWriter(writer, this, false/*don't print XML version*/);
-
- ((ClasspathEntry)classpathEntry).elementEncode(xmlWriter, this.project.getFullPath(), true/*indent*/, true/*insert new line*/, null/*not interested in unknown elements*/);
-
- writer.flush();
- writer.close();
- return s.toString("UTF8");//$NON-NLS-1$
- } catch (IOException e) {
- return null; // never happens since all is done in memory
- }
- }
-
- /**
- * Returns true if this handle represents the same Java project
- * as the given handle. Two handles represent the same
- * project if they are identical or if they represent a project with
- * the same underlying resource and occurrence counts.
- *
- * @see JavaElement#equals(Object)
- */
- public boolean equals(Object o) {
-
- if (this == o)
- return true;
-
- if (!(o instanceof JavaProject))
- return false;
-
- JavaProject other = (JavaProject) o;
- return this.project.equals(other.getProject());
- }
-
- public boolean exists() {
- try {
- return this.project.hasNature(JavaScriptCore.NATURE_ID);
- } catch (CoreException e) {
- // project does not exist or is not open
- }
- return false;
- }
-
- /**
- * @see IJavaScriptProject#findElement(IPath)
- */
- public IJavaScriptElement findElement(IPath path) throws JavaScriptModelException {
- return findElement(path, DefaultWorkingCopyOwner.PRIMARY);
- }
-
- /**
- * @see IJavaScriptProject#findElement(IPath, WorkingCopyOwner)
- */
- public IJavaScriptElement findElement(IPath path, WorkingCopyOwner owner) throws JavaScriptModelException {
-
- if (path == null || path.isAbsolute()) {
- throw new JavaScriptModelException(
- new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_PATH, path));
- }
- try {
-
- String extension = path.getFileExtension();
- if (extension == null) {
- String packageName = path.toString().replace(IPath.SEPARATOR, '.');
-
- NameLookup lookup = newNameLookup((WorkingCopyOwner)null/*no need to look at working copies for pkgs*/);
- IPackageFragment[] pkgFragments = lookup.findPackageFragments(packageName, false);
- if (pkgFragments == null) {
- return null;
-
- } else {
- // try to return one that is a child of this project
- for (int i = 0, length = pkgFragments.length; i < length; i++) {
-
- IPackageFragment pkgFragment = pkgFragments[i];
- if (this.equals(pkgFragment.getParent().getParent())) {
- return pkgFragment;
- }
- }
- // default to the first one
- return pkgFragments[0];
- }
- } else if (Util.isJavaLikeFileName(path.lastSegment())) {
- IPath packagePath = path.removeLastSegments(1);
- String packageName = packagePath.toString().replace(IPath.SEPARATOR, '.');
- String typeName = path.lastSegment();
- typeName = typeName.substring(0, typeName.length() - extension.length() - 1);
- String qualifiedName = null;
- if (packageName.length() > 0) {
- qualifiedName = packageName + "." + typeName; //$NON-NLS-1$
- } else {
- qualifiedName = typeName;
- }
- // lookup cu
- NameLookup lookup = newNameLookup(owner);
- ITypeRoot cu = lookup.findCompilationUnit(qualifiedName);
- if(cu!=null) return cu;
- // lookup type
-
-
- NameLookup.Answer answer =
- lookup.findType(
- qualifiedName,
- false,
- NameLookup.ACCEPT_ALL,
- true/* consider secondary types */,
- false/* do NOT wait for indexes */,
- false/*don't check restrictions*/,
- null);
-
- if (answer != null) {
- return answer.type.getParent();
- } else {
- return null;
- }
- } else {
- // unsupported extension
- return null;
- }
- } catch (JavaScriptModelException e) {
- if (e.getStatus().getCode()
- == IJavaScriptModelStatusConstants.ELEMENT_DOES_NOT_EXIST) {
- return null;
- } else {
- throw e;
- }
- }
- }
-
- /**
- * @see IJavaScriptProject
- */
- public IPackageFragment findPackageFragment(IPath path)
- throws JavaScriptModelException {
-
- return findPackageFragment0(JavaProject.canonicalizedPath(path));
- }
- /*
- * non path canonicalizing version
- */
- private IPackageFragment findPackageFragment0(IPath path)
- throws JavaScriptModelException {
-
- NameLookup lookup = newNameLookup((WorkingCopyOwner)null/*no need to look at working copies for pkgs*/);
- return lookup.findPackageFragment(path);
- }
-
- /**
- * @see IJavaScriptProject
- */
- public IPackageFragmentRoot findPackageFragmentRoot(IPath path)
- throws JavaScriptModelException {
-
- return findPackageFragmentRoot0(JavaProject.canonicalizedPath(path));
- }
- /*
- * no path canonicalization
- */
- public IPackageFragmentRoot findPackageFragmentRoot0(IPath path)
- throws JavaScriptModelException {
-
- IPackageFragmentRoot[] allRoots = this.getAllPackageFragmentRoots();
- if (!path.isAbsolute()) {
- throw new IllegalArgumentException(Messages.path_mustBeAbsolute);
- }
- for (int i= 0; i < allRoots.length; i++) {
- IPackageFragmentRoot classpathRoot= allRoots[i];
- if (classpathRoot.getPath().equals(path)) {
- return classpathRoot;
- }
- }
- return null;
- }
- /**
- * @see IJavaScriptProject
- */
- public IPackageFragmentRoot[] findPackageFragmentRoots(IIncludePathEntry entry) {
- try {
- IIncludePathEntry[] classpath = this.getRawIncludepath();
- for (int i = 0, length = classpath.length; i < length; i++) {
- if (classpath[i].equals(entry)) { // entry may need to be resolved
- return
- computePackageFragmentRoots(
- resolveClasspath(new IIncludePathEntry[] {entry}),
- false, // don't retrieve exported roots
- null); /*no reverse map*/
- }
- }
- } catch (JavaScriptModelException e) {
- // project doesn't exist: return an empty array
- }
- return new IPackageFragmentRoot[] {};
- }
- /**
- * @see IJavaScriptProject#findType(String)
- */
- public IType findType(String fullyQualifiedName) throws JavaScriptModelException {
- return findType(fullyQualifiedName, DefaultWorkingCopyOwner.PRIMARY);
- }
-
- /**
- * @see IJavaScriptProject#findTypes(String)
- */
- public IType[] findTypes(String fullyQualifiedName) throws JavaScriptModelException {
- return findTypes(fullyQualifiedName, DefaultWorkingCopyOwner.PRIMARY);
- }
- /**
- * @see IJavaScriptProject#findType(String, IProgressMonitor)
- */
- public IType findType(String fullyQualifiedName, IProgressMonitor progressMonitor) throws JavaScriptModelException {
- return findType(fullyQualifiedName, DefaultWorkingCopyOwner.PRIMARY, progressMonitor);
- }
-
- /*
- * Internal findType with instanciated name lookup
- */
- IType findType(String fullyQualifiedName, NameLookup lookup, boolean considerSecondaryTypes, IProgressMonitor progressMonitor) throws JavaScriptModelException {
- NameLookup.Answer answer = lookup.findType(
- fullyQualifiedName,
- false,
- NameLookup.ACCEPT_ALL,
- considerSecondaryTypes,
- true, /* wait for indexes (only if consider secondary types)*/
- false/*don't check restrictions*/,
- progressMonitor);
- if (answer == null) {
- // try to find enclosing type
- int lastDot = fullyQualifiedName.lastIndexOf('.');
- if (lastDot == -1) return null;
- IType type = findType(fullyQualifiedName.substring(0, lastDot), lookup, considerSecondaryTypes, progressMonitor);
- if (type != null) {
- type = type.getType(fullyQualifiedName.substring(lastDot+1));
- if (!type.exists()) {
- return null;
- }
- }
- return type;
- }
- if (answer.type==null && answer.element instanceof ITypeRoot)
- {
- answer.type=((ITypeRoot)answer.element).getType(fullyQualifiedName);
- }
- else if (answer.type==null && answer.element!=null && answer.element.getClass().isArray())
- {
- Object [] elements=(Object [])answer.element;
- if(elements[0] instanceof ITypeRoot)
- answer.type=((ITypeRoot)elements[0]).getType(fullyQualifiedName);
- }
- return answer.type;
- }
-
- /*
- * Internal findType with instanciated name lookup - can return multiple IType's
- */
- IType[] findTypes(String fullyQualifiedName, NameLookup lookup, boolean considerSecondaryTypes, IProgressMonitor progressMonitor) throws JavaScriptModelException {
- NameLookup.Answer answer = lookup.findType(
- fullyQualifiedName,
- false,
- NameLookup.ACCEPT_ALL,
- considerSecondaryTypes,
- true, /* wait for indexes (only if consider secondary types)*/
- false/*don't check restrictions*/,
- progressMonitor);
- if (answer == null) {
- // try to find enclosing type
- int lastDot = fullyQualifiedName.lastIndexOf('.');
- if (lastDot == -1) return null;
- IType type = findType(fullyQualifiedName.substring(0, lastDot), lookup, considerSecondaryTypes, progressMonitor);
- if (type != null) {
- type = type.getType(fullyQualifiedName.substring(lastDot+1));
- if (type != null && type.exists()) {
- return new IType[]{type};
- }
- }
- return null;
- }
- if (answer.type==null && answer.element instanceof ITypeRoot)
- {
- answer.type=((ITypeRoot)answer.element).getType(fullyQualifiedName);
- }
- else if (answer.type==null && answer.element!=null && answer.element.getClass().isArray())
- {
- Object [] elements=(Object [])answer.element;
- IType[] iTypes = new IType[elements.length];
- for(int i = 0; i < elements.length; i++) {
- if(elements[i] instanceof ITypeRoot)
- iTypes[i] =((ITypeRoot)elements[i]).getType(fullyQualifiedName);
- }
- return iTypes;
- }
- return new IType[] {answer.type};
- }
- /**
- * @see IJavaScriptProject#findType(String, String)
- */
- public IType findType(String packageName, String typeQualifiedName) throws JavaScriptModelException {
- return findType(packageName, typeQualifiedName, DefaultWorkingCopyOwner.PRIMARY);
- }
- /**
- * @see IJavaScriptProject#findType(String, String, IProgressMonitor)
- */
- public IType findType(String packageName, String typeQualifiedName, IProgressMonitor progressMonitor) throws JavaScriptModelException {
- return findType(packageName, typeQualifiedName, DefaultWorkingCopyOwner.PRIMARY, progressMonitor);
- }
- /*
- * Internal findType with instanciated name lookup
- */
- IType findType(String packageName, String typeQualifiedName, NameLookup lookup, boolean considerSecondaryTypes, IProgressMonitor progressMonitor) throws JavaScriptModelException {
- NameLookup.Answer answer = lookup.findType(
- typeQualifiedName,
- packageName,
- false,
- NameLookup.ACCEPT_ALL,
- considerSecondaryTypes,
- true, // wait for indexes (in case we need to consider secondary types)
- false/*don't check restrictions*/,
- progressMonitor);
- return answer == null ? null : answer.type;
- }
- /**
- * @see IJavaScriptProject#findType(String, String, WorkingCopyOwner)
- */
- public IType findType(String packageName, String typeQualifiedName, WorkingCopyOwner owner) throws JavaScriptModelException {
- NameLookup lookup = newNameLookup(owner);
- return findType(
- packageName,
- typeQualifiedName,
- lookup,
- false, // do not consider secondary types
- null);
- }
-
- /**
- * @see IJavaScriptProject#findType(String, String, WorkingCopyOwner, IProgressMonitor)
- */
- public IType findType(String packageName, String typeQualifiedName, WorkingCopyOwner owner, IProgressMonitor progressMonitor) throws JavaScriptModelException {
- NameLookup lookup = newNameLookup(owner);
- return findType(
- packageName,
- typeQualifiedName,
- lookup,
- true, // consider secondary types
- progressMonitor);
- }
-
- /**
- * @see IJavaScriptProject#findType(String, WorkingCopyOwner)
- */
- public IType findType(String fullyQualifiedName, WorkingCopyOwner owner) throws JavaScriptModelException {
- NameLookup lookup = newNameLookup(owner);
- return findType(fullyQualifiedName, lookup, false, null);
- }
-
- /**
- * @see IJavaScriptProject#findTypes(String, WorkingCopyOwner)
- */
- public IType[] findTypes(String fullyQualifiedName, WorkingCopyOwner owner) throws JavaScriptModelException {
- NameLookup lookup = newNameLookup(owner);
- return findTypes(fullyQualifiedName, lookup, false, null);
- }
-
- /**
- * @see IJavaScriptProject#findType(String, WorkingCopyOwner, IProgressMonitor)
- */
- public IType findType(String fullyQualifiedName, WorkingCopyOwner owner, IProgressMonitor progressMonitor) throws JavaScriptModelException {
- NameLookup lookup = newNameLookup(owner);
- return findType(fullyQualifiedName, lookup, true, progressMonitor);
- }
-
- /**
- * Remove all markers denoting classpath problems
- */ //TODO (philippe) should improve to use a bitmask instead of booleans (CYCLE, FORMAT, VALID)
- protected void flushClasspathProblemMarkers(boolean flushCycleMarkers, boolean flushClasspathFormatMarkers) {
- try {
- if (this.project.isAccessible()) {
- IMarker[] markers = this.project.findMarkers(IJavaScriptModelMarker.BUILDPATH_PROBLEM_MARKER, false, IResource.DEPTH_ZERO);
- for (int i = 0, length = markers.length; i < length; i++) {
- IMarker marker = markers[i];
- if (flushCycleMarkers && flushClasspathFormatMarkers) {
- marker.delete();
- } else {
- String cycleAttr = (String)marker.getAttribute(IJavaScriptModelMarker.CYCLE_DETECTED);
- String classpathFileFormatAttr = (String)marker.getAttribute(IJavaScriptModelMarker.INCLUDEPATH_FILE_FORMAT);
- if ((flushCycleMarkers == (cycleAttr != null && cycleAttr.equals("true"))) //$NON-NLS-1$
- && (flushClasspathFormatMarkers == (classpathFileFormatAttr != null && classpathFileFormatAttr.equals("true")))){ //$NON-NLS-1$
- marker.delete();
- }
- }
- }
- }
- } catch (CoreException e) {
- // could not flush markers: not much we can do
- if (JavaModelManager.VERBOSE) {
- e.printStackTrace();
- }
- }
- }
-
- /**
- * Returns the set of patterns corresponding to this project visibility given rules
- * @return an array of IPath or null if none
- */
- public IPath[] getAccessRestrictions(String optionName) {
- String sequence = getOption(optionName, true); // inherit from workspace
- if (sequence == null || sequence.length() == 0) return null;
- IPath[] rules = null;
- char[][] patterns = CharOperation.splitOn('|', sequence.toCharArray());
- int patternCount;
- if ((patternCount = patterns.length) > 0) {
- rules = new IPath[patternCount];
- for (int j = 0; j < patterns.length; j++){
- rules[j] = new Path(new String(patterns[j]));
- }
- }
- return rules;
- }
-
- /**
- * @see IJavaScriptProject
- */
- public IPackageFragmentRoot[] getAllPackageFragmentRoots()
- throws JavaScriptModelException {
-
- return getAllPackageFragmentRoots(null /*no reverse map*/);
- }
-
- public IPackageFragmentRoot[] getAllPackageFragmentRoots(Map rootToResolvedEntries) throws JavaScriptModelException {
-
- return computePackageFragmentRoots(getResolvedClasspath(), true/*retrieveExportedRoots*/, rootToResolvedEntries);
- }
-
- /**
- * Returns the classpath entry that refers to the given path
- * or <code>null</code> if there is no reference to the path.
- * @param path IPath
- * @return IIncludePathEntry
- * @throws JavaScriptModelException
- */
- public IIncludePathEntry getClasspathEntryFor(IPath path) throws JavaScriptModelException {
- getResolvedClasspath(); // force resolution
- PerProjectInfo perProjectInfo = getPerProjectInfo();
- if (perProjectInfo == null)
- return null;
- Map rootPathToResolvedEntries = perProjectInfo.rootPathToResolvedEntries;
- if (rootPathToResolvedEntries == null)
- return null;
- return (IIncludePathEntry) rootPathToResolvedEntries.get(path);
- }
-
- /*
- * Returns the cycle marker associated with this project or null if none.
- */
- public IMarker getCycleMarker(){
- try {
- if (this.project.isAccessible()) {
- IMarker[] markers = this.project.findMarkers(IJavaScriptModelMarker.BUILDPATH_PROBLEM_MARKER, false, IResource.DEPTH_ZERO);
- for (int i = 0, length = markers.length; i < length; i++) {
- IMarker marker = markers[i];
- String cycleAttr = (String)marker.getAttribute(IJavaScriptModelMarker.CYCLE_DETECTED);
- if (cycleAttr != null && cycleAttr.equals("true")){ //$NON-NLS-1$
- return marker;
- }
- }
- }
- } catch (CoreException e) {
- // could not get markers: return null
- }
- return null;
- }
-
- /**
- * Returns the project custom preference pool.
- * Project preferences may include custom encoding.
- * @return IEclipsePreferences
- */
- public IEclipsePreferences getEclipsePreferences(){
- if (!JavaProject.hasJavaNature(this.project)) return null;
- // Get cached preferences if exist
- JavaModelManager.PerProjectInfo perProjectInfo = JavaModelManager.getJavaModelManager().getPerProjectInfo(this.project, true);
- if (perProjectInfo.preferences != null) return perProjectInfo.preferences;
- // Init project preferences
- IScopeContext context = new ProjectScope(getProject());
- final IEclipsePreferences eclipsePreferences = context.getNode(JavaScriptCore.PLUGIN_ID);
- updatePreferences(eclipsePreferences);
- perProjectInfo.preferences = eclipsePreferences;
-
- // Listen to node removal from parent in order to reset cache (see bug 68993)
- IEclipsePreferences.INodeChangeListener nodeListener = new IEclipsePreferences.INodeChangeListener() {
- public void added(IEclipsePreferences.NodeChangeEvent event) {
- // do nothing
- }
- public void removed(IEclipsePreferences.NodeChangeEvent event) {
- if (event.getChild() == eclipsePreferences) {
- JavaModelManager.getJavaModelManager().resetProjectPreferences(JavaProject.this);
- }
- }
- };
- ((IEclipsePreferences) eclipsePreferences.parent()).addNodeChangeListener(nodeListener);
-
- // Listen to preference changes
- IEclipsePreferences.IPreferenceChangeListener preferenceListener = new IEclipsePreferences.IPreferenceChangeListener() {
- public void preferenceChange(IEclipsePreferences.PreferenceChangeEvent event) {
- String propertyName = event.getKey();
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- if (propertyName.startsWith(JavaScriptCore.PLUGIN_ID)) {
- if (propertyName.equals(JavaScriptCore.CORE_JAVA_BUILD_CLEAN_OUTPUT_FOLDER) ||
- propertyName.equals(JavaScriptCore.CORE_JAVA_BUILD_RESOURCE_COPY_FILTER) ||
- propertyName.equals(JavaScriptCore.CORE_JAVA_BUILD_DUPLICATE_RESOURCE) ||
- propertyName.equals(JavaScriptCore.CORE_JAVA_BUILD_RECREATE_MODIFIED_CLASS_FILES_IN_OUTPUT_FOLDER) ||
- propertyName.equals(JavaScriptCore.CORE_JAVA_BUILD_INVALID_CLASSPATH) ||
- propertyName.equals(JavaScriptCore.CORE_ENABLE_CLASSPATH_EXCLUSION_PATTERNS) ||
- propertyName.equals(JavaScriptCore.CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS) ||
- propertyName.equals(JavaScriptCore.CORE_INCOMPLETE_CLASSPATH) ||
- propertyName.equals(JavaScriptCore.CORE_CIRCULAR_CLASSPATH) ||
- propertyName.equals(JavaScriptCore.CORE_INCOMPATIBLE_JDK_LEVEL))
- {
- manager.deltaState.addClasspathValidation(JavaProject.this);
- }
- manager.resetProjectOptions(JavaProject.this);
- }
- }
- };
- eclipsePreferences.addPreferenceChangeListener(preferenceListener);
- return eclipsePreferences;
- }
-
- public String getElementName() {
- return this.project.getName();
- }
-
- /**
- * @see IJavaScriptElement
- */
- public int getElementType() {
- return JAVASCRIPT_PROJECT;
- }
-
- /**
- * This is a helper method returning the expanded classpath for the project, as a list of classpath entries,
- * where all classpath variable entries have been resolved and substituted with their final target entries.
- * All project exports have been appended to project entries.
- * @return IIncludePathEntry[]
- * @throws JavaScriptModelException
- */
- public IIncludePathEntry[] getExpandedClasspath() throws JavaScriptModelException {
-
- ObjectVector accumulatedEntries = new ObjectVector();
- computeExpandedClasspath(null, new HashSet(5), accumulatedEntries);
-
- IIncludePathEntry[] expandedPath = new IIncludePathEntry[accumulatedEntries.size()];
- accumulatedEntries.copyInto(expandedPath);
-
- return expandedPath;
- }
-
- /**
- * The path is known to match a source/library folder entry.
- * @param path IPath
- * @return IPackageFragmentRoot
- */
- public IPackageFragmentRoot getFolderPackageFragmentRoot(IPath path) {
- if (path.segmentCount() == 1) { // default project root
- return getPackageFragmentRoot(this.project);
- }
- return getPackageFragmentRoot(this.project.getWorkspace().getRoot().getFolder(path));
- }
-
- /*
- * @see JavaElement
- */
- public IJavaScriptElement getHandleFromMemento(String token, MementoTokenizer memento, WorkingCopyOwner owner) {
- switch (token.charAt(0)) {
- case JEM_PACKAGEFRAGMENTROOT:
- String rootPath = IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH;
- token = null;
- while (memento.hasMoreTokens()) {
- token = memento.nextToken();
- char firstChar = token.charAt(0);
- if (firstChar != JEM_PACKAGEFRAGMENT && firstChar != JEM_COUNT) {
- rootPath += token;
- } else {
- break;
- }
- }
- JavaElement root = (JavaElement)getPackageFragmentRoot(new Path(rootPath));
- if (token != null && token.charAt(0) == JEM_PACKAGEFRAGMENT) {
- return root.getHandleFromMemento(token, memento, owner);
- } else {
- return root.getHandleFromMemento(memento, owner);
- }
- }
- return null;
- }
-
- /**
- * Returns the <code>char</code> that marks the start of this handles
- * contribution to a memento.
- */
- protected char getHandleMementoDelimiter() {
-
- return JEM_JAVAPROJECT;
- }
-
- /**
- * Find the specific Java command amongst the given build spec
- * and return its index or -1 if not found.
- */
- private int getJavaCommandIndex(ICommand[] buildSpec, String builder_ID) {
-
- for (int i = 0; i < buildSpec.length; ++i) {
- if (buildSpec[i].getBuilderName().equals(builder_ID)) {
- return i;
- }
- }
- return -1;
- }
-// private int getJavaCommandIndex(ICommand[] buildSpec) {
-// return getJavaCommandIndex(buildSpec, JavaScriptCore.BUILDER_ID);
-//
-// }
- /**
- * Convenience method that returns the specific type of info for a Java project.
- */
- protected JavaProjectElementInfo getJavaProjectElementInfo()
- throws JavaScriptModelException {
-
- return (JavaProjectElementInfo) getElementInfo();
- }
-
- /**
- * Returns an array of non-java resources contained in the receiver.
- */
- public Object[] getNonJavaScriptResources() throws JavaScriptModelException {
-
- return ((JavaProjectElementInfo) getElementInfo()).getNonJavaResources(this);
- }
-
- /**
- * @see org.eclipse.wst.jsdt.core.IJavaScriptProject#getOption(String, boolean)
- */
- public String getOption(String optionName, boolean inheritJavaCoreOptions) {
-
- String propertyName = optionName;
- if (JavaModelManager.getJavaModelManager().optionNames.contains(propertyName)){
- IEclipsePreferences projectPreferences = getEclipsePreferences();
- String javaCoreDefault = inheritJavaCoreOptions ? JavaScriptCore.getOption(propertyName) : null;
- if (projectPreferences == null) return javaCoreDefault;
- String value = projectPreferences.get(propertyName, javaCoreDefault);
- return value == null ? null : value.trim();
- }
- return null;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.core.IJavaScriptProject#getOptions(boolean)
- */
- public Map getOptions(boolean inheritJavaCoreOptions) {
-
- // initialize to the defaults from JavaScriptCore options pool
- Map options = inheritJavaCoreOptions ? JavaScriptCore.getOptions() : new Hashtable(5);
-
- // Get project specific options
- JavaModelManager.PerProjectInfo perProjectInfo = null;
- Hashtable projectOptions = null;
- HashSet optionNames = JavaModelManager.getJavaModelManager().optionNames;
- try {
- perProjectInfo = getPerProjectInfo();
- projectOptions = perProjectInfo.options;
- if (projectOptions == null) {
- // get eclipse preferences
- IEclipsePreferences projectPreferences= getEclipsePreferences();
- if (projectPreferences == null) return options; // cannot do better (non-Java project)
- // create project options
- String[] propertyNames = projectPreferences.keys();
- projectOptions = new Hashtable(propertyNames.length);
- for (int i = 0; i < propertyNames.length; i++){
- String propertyName = propertyNames[i];
- String value = projectPreferences.get(propertyName, null);
- if (value != null && optionNames.contains(propertyName)){
- projectOptions.put(propertyName, value.trim());
- }
- }
- // cache project options
- perProjectInfo.options = projectOptions;
- }
- } catch (JavaScriptModelException jme) {
- projectOptions = new Hashtable();
- } catch (BackingStoreException e) {
- projectOptions = new Hashtable();
- }
-
- // Inherit from JavaScriptCore options if specified
- if (inheritJavaCoreOptions) {
- Iterator propertyNames = projectOptions.entrySet().iterator();
- while (propertyNames.hasNext()) {
- Map.Entry entry = (Map.Entry) propertyNames.next();
- String propertyName = (String) entry.getKey();
- String propertyValue = (String) entry.getValue();
- if (propertyValue != null && optionNames.contains(propertyName)){
- options.put(propertyName, propertyValue.trim());
- }
- }
- return options;
- }
- return projectOptions;
- }
-
- /**
- * @see IJavaScriptProject
- */
- public IPath getOutputLocation() throws JavaScriptModelException {
- // Do not create marker while getting output location
- JavaModelManager.PerProjectInfo perProjectInfo = this.getPerProjectInfo();
- IPath outputLocation = perProjectInfo.outputLocation;
- if (outputLocation != null) return outputLocation;
-
- // force to read classpath - will position output location as well
- getRawIncludepath();
-
- outputLocation = perProjectInfo.outputLocation;
- if (outputLocation == null) {
- return this.defaultOutputLocation();
- }
- return outputLocation;
- }
-
- /**
- * @param path IPath
- * @return A handle to the package fragment root identified by the given path.
- * This method is handle-only and the element may or may not exist. Returns
- * <code>null</code> if unable to generate a handle from the path (for example,
- * an absolute path that has less than 1 segment. The path may be relative or
- * absolute.
- */
- public IPackageFragmentRoot getPackageFragmentRoot(IPath path) {
- if (!path.isAbsolute()) {
- path = getPath().append(path);
- }
- int segmentCount = path.segmentCount();
- String lastSegment = path.lastSegment();
- switch (segmentCount) {
- case 0:
- return null;
- case 1:
- if (path.equals(getPath())) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=75814
- // default root
- return getPackageFragmentRoot(this.project);
- }
- default:
- // a path ending with .jar/.zip is still ambiguous and could still resolve to a source/lib folder
- // thus will try to guess based on existing resource
- if (org.eclipse.wst.jsdt.internal.compiler.util.Util.isArchiveFileName(lastSegment)
- || org.eclipse.wst.jsdt.internal.compiler.util.Util.isJavaFileName(lastSegment)) {
- IResource resource = this.project.getWorkspace().getRoot().findMember(path);
- if (resource != null && resource.getType() == IResource.FOLDER){
- return getPackageFragmentRoot(resource);
- }
- return getPackageFragmentRoot0(path);
- } else if (segmentCount == 1) {
- // lib being another project
- return getPackageFragmentRoot(this.project.getWorkspace().getRoot().getProject(lastSegment));
- } else {
- // lib being a folder
- IFolder folder = this.project.getWorkspace().getRoot().getFolder(path);
- if (folder!=null && folder.exists())
- return getPackageFragmentRoot(folder);
- return getPackageFragmentRoot0(path);
- }
- }
- }
-
- /**
- * @see IJavaScriptProject
- */
- public IPackageFragmentRoot getPackageFragmentRoot(IResource resource) {
-
- switch (resource.getType()) {
- case IResource.FILE:
- if (org.eclipse.wst.jsdt.internal.compiler.util.Util.isArchiveFileName(resource.getName())) {
-// return new JarPackageFragmentRoot(resource, this);
- } else {
- return null;
- }
- case IResource.FOLDER:
- return new PackageFragmentRoot(resource, this);
- case IResource.PROJECT:
- return new PackageFragmentRoot(resource, this);
- default:
- return null;
- }
- }
-
- /**
- * @see IJavaScriptProject
- */
- public IPackageFragmentRoot getPackageFragmentRoot(String jarPath) {
-
- return getPackageFragmentRoot0(JavaProject.canonicalizedPath(new Path(jarPath)));
- }
-
- /*
- * no path canonicalization
- */
- public IPackageFragmentRoot getPackageFragmentRoot0(IPath jarPath) {
-
- return new LibraryFragmentRoot(jarPath, this);
- }
-
- /**
- * @see IJavaScriptProject
- */
- public IPackageFragmentRoot[] getPackageFragmentRoots()
- throws JavaScriptModelException {
-
- Object[] children;
- int length;
- IPackageFragmentRoot[] roots;
-
- System.arraycopy(
- children = getChildren(),
- 0,
- roots = new IPackageFragmentRoot[length = children.length],
- 0,
- length);
-
- return roots;
- }
-
- /**
- * @see IJavaScriptProject
- */
- public IPackageFragment[] getPackageFragments() throws JavaScriptModelException {
-
- IPackageFragmentRoot[] roots = getPackageFragmentRoots();
- return getPackageFragmentsInRoots(roots);
- }
-
- /**
- * Returns all the package fragments found in the specified
- * package fragment roots.
- * @param roots IPackageFragmentRoot[]
- * @return IPackageFragment[]
- */
- public IPackageFragment[] getPackageFragmentsInRoots(IPackageFragmentRoot[] roots) {
-
- ArrayList frags = new ArrayList();
- for (int i = 0; i < roots.length; i++) {
- IPackageFragmentRoot root = roots[i];
- try {
- IJavaScriptElement[] rootFragments = root.getChildren();
- for (int j = 0; j < rootFragments.length; j++) {
- frags.add(rootFragments[j]);
- }
- } catch (JavaScriptModelException e) {
- // do nothing
- }
- }
- IPackageFragment[] fragments = new IPackageFragment[frags.size()];
- frags.toArray(fragments);
- return fragments;
- }
-
- /**
- * @see IJavaScriptElement
- */
- public IPath getPath() {
- return this.project.getFullPath();
- }
-
- public JavaModelManager.PerProjectInfo getPerProjectInfo() throws JavaScriptModelException {
- return JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(this.project);
- }
-
- private IPath getPluginWorkingLocation() {
- return this.project.getWorkingLocation(JavaScriptCore.PLUGIN_ID);
- }
-
- /**
- * Returns the project custom preference pool.
- * Project preferences may include custom encoding.
- * @return Preferences
- * @deprecated WARNING: this method do nothing from now and will be removed soon!
- * If you use it, switch as soon as possible to new preferences API by using
- * {@link #getEclipsePreferences()} to avoid future compilation error...
- * @see <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=59258">bug 59258</a>
- * TODO (frederic) remove for 3.1...
- */
- public Preferences getPreferences(){
- /*
- if (!JavaProject.hasJavaNature(this.project)) return null;
- JavaModelManager.PerProjectInfo perProjectInfo = JavaModelManager.getJavaModelManager().getPerProjectInfo(this.project, true);
- Preferences preferences = perProjectInfo.preferences;
- if (preferences != null) return preferences;
- preferences = loadPreferences();
- if (preferences == null) preferences = new Preferences();
- perProjectInfo.preferences = preferences;
- return preferences;
- */
- return new Preferences();
- }
-
- /**
- * @see IJavaScriptProject#getProject()
- */
- public IProject getProject() {
- return this.project;
- }
-
- public LookupCache getProjectCache() throws JavaScriptModelException {
- return ((JavaProjectElementInfo) getElementInfo()).getProjectCache(this);
- }
-
- /**
- * @see IJavaScriptProject
- */
- public IIncludePathEntry[] getRawIncludepath() throws JavaScriptModelException {
- JavaModelManager.PerProjectInfo perProjectInfo = getPerProjectInfo();
- IIncludePathEntry[] classpath = perProjectInfo.rawClasspath;
- if (classpath != null) return classpath;
-
- classpath = perProjectInfo.readAndCacheClasspath(this);
-
- if (classpath == JavaProject.INVALID_CLASSPATH)
- return defaultClasspath();
-
- return classpath;
- }
-
- /**
- * @see IJavaScriptProject#getRequiredProjectNames()
- */
- public String[] getRequiredProjectNames() throws JavaScriptModelException {
-
- return this.projectPrerequisites(getResolvedClasspath());
- }
-
- /*
- * Returns the cached resolved classpath, or compute it ignoring unresolved entries and cache it.
- */
- public IIncludePathEntry[] getResolvedClasspath() throws JavaScriptModelException {
- try {
- PerProjectInfo perProjectInfo = getPerProjectInfo();
- if (perProjectInfo.resolvedClasspath == null)
- resolveClasspath(perProjectInfo);
- return perProjectInfo.resolvedClasspath;
- } catch (JavaScriptModelException e) {
- if (e.getStatus().getCode()==IJavaScriptModelStatusConstants.ELEMENT_DOES_NOT_EXIST)
- {
- IIncludePathEntry[] defaultClasspath = defaultClasspath();
- return resolveClasspath(defaultClasspath);
- }
- else
- throw e;
- }
- }
-
- /**
- * @see IJavaScriptProject
- */
- public IIncludePathEntry[] getResolvedIncludepath(boolean ignoreUnresolvedEntry) throws JavaScriptModelException {
- if (JavaModelManager.getJavaModelManager().isClasspathBeingResolved(this)) {
- if (JavaModelManager.CP_RESOLVE_VERBOSE_ADVANCED)
- verbose_reentering_classpath_resolution();
- return RESOLUTION_IN_PROGRESS;
- }
- PerProjectInfo perProjectInfo = getPerProjectInfo();
-
- // use synchronized block to ensure consistency
- IIncludePathEntry[] resolvedClasspath;
- IJavaScriptModelStatus unresolvedEntryStatus;
- synchronized (perProjectInfo) {
- resolvedClasspath = perProjectInfo.resolvedClasspath;
- unresolvedEntryStatus = perProjectInfo.unresolvedEntryStatus;
- }
-
- if (resolvedClasspath == null
- || (unresolvedEntryStatus != null && !unresolvedEntryStatus.isOK())) { // force resolution to ensure initializers are run again
- resolveClasspath(perProjectInfo);
- synchronized (perProjectInfo) {
- resolvedClasspath = perProjectInfo.resolvedClasspath;
- unresolvedEntryStatus = perProjectInfo.unresolvedEntryStatus;
- }
- }
- if (!ignoreUnresolvedEntry && unresolvedEntryStatus != null && !unresolvedEntryStatus.isOK())
- throw new JavaScriptModelException(unresolvedEntryStatus);
- return resolvedClasspath;
- }
-
- private void verbose_reentering_classpath_resolution() {
- Util.verbose(
- "CPResolution: reentering raw classpath resolution, will use empty classpath instead" + //$NON-NLS-1$
- " project: " + getElementName() + '\n' + //$NON-NLS-1$
- " invocation stack trace:"); //$NON-NLS-1$
- new Exception("<Fake exception>").printStackTrace(System.out); //$NON-NLS-1$
- }
-
- /**
- * @see IJavaScriptElement
- */
- public IResource getResource() {
- return this.project;
- }
-
- /**
- * Retrieve a shared property on a project. If the property is not defined, answers null.
- * Note that it is orthogonal to IResource persistent properties, and client code has to decide
- * which form of storage to use appropriately. Shared properties produce real resource files which
- * can be shared through a VCM onto a server. Persistent properties are not shareable.
- *
- * @param key String
- * @see JavaProject#setSharedProperty(String, String)
- * @return String
- * @throws CoreException
- */
- public String getSharedProperty(String key) throws CoreException {
-
- IFile rscFile = this.project.getFile(key);
- String property = null;
- //IFile rscFile = this.project.getFile(key);
- if (rscFile.exists()) {
- byte[] bytes = Util.getResourceContentsAsByteArray(rscFile);
- try {
- property = new String(bytes, org.eclipse.wst.jsdt.internal.compiler.util.Util.UTF_8); // .classpath always encoded with UTF-8
- } catch (UnsupportedEncodingException e) {
- Util.log(e, "Could not read .jsdtscope with UTF-8 encoding"); //$NON-NLS-1$
- // fallback to default
- property = new String(bytes);
- }
- } else {
- // when a project is imported, we get a first delta for the addition of the .project, but the .classpath is not accessible
- // so default to using java.io.File
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=96258
- URI location = rscFile.getLocationURI();
- if (location != null) {
- File file = Util.toLocalFile(location, null/*no progress monitor available*/);
- if (file != null && file.exists()) {
- byte[] bytes;
- try {
- bytes = org.eclipse.wst.jsdt.internal.compiler.util.Util.getFileByteContent(file);
- } catch (IOException e) {
- return null;
- }
- try {
- property = new String(bytes, org.eclipse.wst.jsdt.internal.compiler.util.Util.UTF_8); // .classpath always encoded with UTF-8
- } catch (UnsupportedEncodingException e) {
- Util.log(e, "Could not read .jsdtscope with UTF-8 encoding"); //$NON-NLS-1$
- // fallback to default
- property = new String(bytes);
- }
- }
- }
- }
- return property;
- }
-
- /**
- * @see JavaElement
- */
- public SourceMapper getSourceMapper() {
-
- return null;
- }
-
- /**
- * @see IJavaScriptElement
- */
- public IResource getUnderlyingResource() throws JavaScriptModelException {
- if (!exists()) throw newNotPresentException();
- return this.project;
- }
-
- /**
- * @see IJavaScriptProject
- */
- public boolean hasBuildState() {
-
- return JavaModelManager.getJavaModelManager().getLastBuiltState(this.project, null) != null;
- }
-
- /**
- * @see IJavaScriptProject
- */
- public boolean hasIncludepathCycle(IIncludePathEntry[] preferredClasspath) {
- HashSet cycleParticipants = new HashSet();
- HashMap preferredClasspaths = new HashMap(1);
- preferredClasspaths.put(this, preferredClasspath);
- updateCycleParticipants(new ArrayList(2), cycleParticipants, ResourcesPlugin.getWorkspace().getRoot(), new HashSet(2), preferredClasspaths);
- return !cycleParticipants.isEmpty();
- }
-
- public boolean hasCycleMarker(){
- return this.getCycleMarker() != null;
- }
-
- public int hashCode() {
- return this.project.hashCode();
- }
-
- /**
- * Answers true if the project potentially contains any source. A project which has no source is immutable.
- * @return boolean
- */
- public boolean hasSource() {
-
- // look if any source folder on the classpath
- // no need for resolved path given source folder cannot be abstracted
- IIncludePathEntry[] entries;
- try {
- entries = this.getRawIncludepath();
- } catch (JavaScriptModelException e) {
- return true; // unsure
- }
- for (int i = 0, max = entries.length; i < max; i++) {
- if (entries[i].getEntryKind() == IIncludePathEntry.CPE_SOURCE) {
- return true;
- }
- }
- return false;
- }
-
-
-
- /*
- * @see IJavaScriptProject
- */
- public boolean isOnIncludepath(IJavaScriptElement element) {
- IIncludePathEntry[] rawClasspath;
- try {
- rawClasspath = getRawIncludepath();
- } catch(JavaScriptModelException e){
- return false; // not a Java project
- }
- int elementType = element.getElementType();
- boolean isPackageFragmentRoot = false;
- boolean isFolderPath = false;
- boolean isSource = false;
- switch (elementType) {
- case IJavaScriptElement.JAVASCRIPT_MODEL:
- return false;
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- isPackageFragmentRoot = true;
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- isFolderPath = !((IPackageFragmentRoot)element.getParent()).isArchive();
- break;
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- isSource = true;
- break;
- default:
- isSource = element.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT) != null;
- break;
- }
- IPath elementPath = element.getPath();
-
- // first look at unresolved entries
- int length = rawClasspath.length;
- for (int i = 0; i < length; i++) {
- IIncludePathEntry entry = rawClasspath[i];
- switch (entry.getEntryKind()) {
- case IIncludePathEntry.CPE_LIBRARY:
- case IIncludePathEntry.CPE_PROJECT:
- case IIncludePathEntry.CPE_SOURCE:
- if (isOnClasspathEntry(elementPath, isFolderPath, isPackageFragmentRoot, entry))
- return true;
- break;
- }
- }
-
- // no need to go further for compilation units and elements inside a compilation unit
- // it can only be in a source folder, thus on the raw classpath
- if (isSource)
- return false;
-
- // then look at resolved entries
- for (int i = 0; i < length; i++) {
- IIncludePathEntry rawEntry = rawClasspath[i];
- switch (rawEntry.getEntryKind()) {
- case IIncludePathEntry.CPE_CONTAINER:
- IJsGlobalScopeContainer container;
- try {
- container = JavaScriptCore.getJsGlobalScopeContainer(rawEntry.getPath(), this);
- } catch (JavaScriptModelException e) {
- break;
- }
- if (container == null)
- break;
- IIncludePathEntry[] containerEntries = container.getIncludepathEntries();
- if (containerEntries == null)
- break;
- // container was bound
- for (int j = 0, containerLength = containerEntries.length; j < containerLength; j++){
- IIncludePathEntry resolvedEntry = containerEntries[j];
- if (resolvedEntry == null) {
- if (JavaModelManager.CP_RESOLVE_VERBOSE) {
- JavaModelManager.getJavaModelManager().verbose_missbehaving_container(this, rawEntry.getPath(), containerEntries);
- }
- return false;
- }
- if (isOnClasspathEntry(elementPath, isFolderPath, isPackageFragmentRoot, resolvedEntry))
- return true;
- }
- break;
- case IIncludePathEntry.CPE_VARIABLE:
- IIncludePathEntry resolvedEntry = JavaScriptCore.getResolvedIncludepathEntry(rawEntry);
- if (resolvedEntry == null)
- break;
- if (isOnClasspathEntry(elementPath, isFolderPath, isPackageFragmentRoot, resolvedEntry))
- return true;
- break;
- }
- }
-
- return false;
- }
-
- /*
- * @see IJavaScriptProject
- */
- public boolean isOnIncludepath(IResource resource) {
- IPath exactPath = resource.getLocation();
- IPath path = resource.getFullPath();
-
- // ensure that folders are only excluded if all of their children are excluded
- int resourceType = resource.getType();
- boolean isFolderPath = resourceType == IResource.FOLDER || resourceType == IResource.PROJECT;
-
- IIncludePathEntry[] classpath;
- try {
- classpath = this.getResolvedClasspath();
- } catch(JavaScriptModelException e){
- return false; // not a Java project
- }
- for (int i = 0; i < classpath.length; i++) {
- IIncludePathEntry entry = classpath[i];
- IPath entryPath = entry.getPath();
- if (entryPath.equals(exactPath) || entryPath.equals(exactPath)) { // package fragment roots must match exactly entry pathes (no exclusion there)
- return true;
- }
- if (entryPath.isPrefixOf(path)
- && !Util.isExcluded(path, ((ClasspathEntry)entry).fullInclusionPatternChars(), ((ClasspathEntry)entry).fullExclusionPatternChars(), isFolderPath)) {
- return true;
- }
- }
- return false;
- }
-
- private boolean isOnClasspathEntry(IPath elementPath, boolean isFolderPath, boolean isPackageFragmentRoot, IIncludePathEntry entry) {
- IPath entryPath = entry.getPath();
- if (isPackageFragmentRoot) {
- // package fragment roots must match exactly entry pathes (no exclusion there)
- if (entryPath.equals(elementPath))
- return true;
- } else {
- if (entryPath.isPrefixOf(elementPath)
- && !Util.isExcluded(elementPath, ((ClasspathEntry)entry).fullInclusionPatternChars(), ((ClasspathEntry)entry).fullExclusionPatternChars(), isFolderPath))
- return true;
- }
- return false;
- }
-
- /**
- * load preferences from a shareable format (VCM-wise)
- */
- public Preferences loadPreferences() {
-
- Preferences preferences = new Preferences();
- IPath projectMetaLocation = getPluginWorkingLocation();
- if (projectMetaLocation != null) {
- File prefFile = projectMetaLocation.append(PREF_FILENAME).toFile();
- if (prefFile.exists()) { // load preferences from file
- InputStream in = null;
- try {
- in = new BufferedInputStream(new FileInputStream(prefFile));
- preferences.load(in);
- } catch (IOException e) { // problems loading preference store - quietly ignore
- } finally {
- if (in != null) {
- try {
- in.close();
- } catch (IOException e) { // ignore problems with close
- }
- }
- }
- // one shot read, delete old preferences
- prefFile.delete();
- return preferences;
- }
- }
- return null;
- }
-
- /**
- * @see IJavaScriptProject#newEvaluationContext()
- */
- public IEvaluationContext newEvaluationContext() {
-// EvaluationContext context = new EvaluationContext();
-// context.setLineSeparator(Util.getLineSeparator(null/*no existing source*/, this));
-// return new EvaluationContextWrapper(context, this);
- return null;
- }
-
- /*
- * Returns a new name lookup. This name lookup first looks in the given working copies.
- */
- public NameLookup newNameLookup(IJavaScriptUnit[] workingCopies) throws JavaScriptModelException {
- return getJavaProjectElementInfo().newNameLookup(this, workingCopies);
- }
-
- /*
- * Returns a new name lookup. This name lookup first looks in the working copies of the given owner.
- */
- public NameLookup newNameLookup(WorkingCopyOwner owner) throws JavaScriptModelException {
-
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- IJavaScriptUnit[] workingCopies = owner == null ? null : manager.getWorkingCopies(owner, true/*add primary WCs*/);
- return newNameLookup(workingCopies);
- }
-
- /*
- * Returns a new search name environment for this project. This name environment first looks in the given working copies.
- */
- public SearchableEnvironment newSearchableNameEnvironment(IJavaScriptUnit[] workingCopies) throws JavaScriptModelException {
- return new SearchableEnvironment(this, workingCopies);
- }
-
- /*
- * Returns a new search name environment for this project. This name environment first looks in the working copies
- * of the given owner.
- */
- public SearchableEnvironment newSearchableNameEnvironment(WorkingCopyOwner owner) throws JavaScriptModelException {
- return new SearchableEnvironment(this, owner);
- }
-
- /**
- * @see IJavaScriptProject
- */
- public ITypeHierarchy newTypeHierarchy(
- IRegion region,
- IProgressMonitor monitor)
- throws JavaScriptModelException {
-
- return newTypeHierarchy(region, DefaultWorkingCopyOwner.PRIMARY, monitor);
- }
-
- /**
- * @see IJavaScriptProject
- */
- public ITypeHierarchy newTypeHierarchy(
- IRegion region,
- WorkingCopyOwner owner,
- IProgressMonitor monitor)
- throws JavaScriptModelException {
-
- if (region == null) {
- throw new IllegalArgumentException(Messages.hierarchy_nullRegion);
- }
- IJavaScriptUnit[] workingCopies = JavaModelManager.getJavaModelManager().getWorkingCopies(owner, true/*add primary working copies*/);
- CreateTypeHierarchyOperation op =
- new CreateTypeHierarchyOperation(region, workingCopies, null, true);
- op.runOperation(monitor);
- return op.getResult();
- }
-
- /**
- * @see IJavaScriptProject
- */
- public ITypeHierarchy newTypeHierarchy(
- IType type,
- IRegion region,
- IProgressMonitor monitor)
- throws JavaScriptModelException {
-
- return newTypeHierarchy(type, region, DefaultWorkingCopyOwner.PRIMARY, monitor);
- }
-
- /**
- * @see IJavaScriptProject
- */
- public ITypeHierarchy newTypeHierarchy(
- IType type,
- IRegion region,
- WorkingCopyOwner owner,
- IProgressMonitor monitor)
- throws JavaScriptModelException {
-
- if (type == null) {
- throw new IllegalArgumentException(Messages.hierarchy_nullFocusType);
- }
- if (region == null) {
- throw new IllegalArgumentException(Messages.hierarchy_nullRegion);
- }
- IJavaScriptUnit[] workingCopies = JavaModelManager.getJavaModelManager().getWorkingCopies(owner, true/*add primary working copies*/);
- CreateTypeHierarchyOperation op =
- new CreateTypeHierarchyOperation(region, workingCopies, type, true/*compute subtypes*/);
- op.runOperation(monitor);
- return op.getResult();
- }
- public String[] projectPrerequisites(IIncludePathEntry[] entries)
- throws JavaScriptModelException {
-
- ArrayList prerequisites = new ArrayList();
- // need resolution
- entries = resolveClasspath(entries);
- for (int i = 0, length = entries.length; i < length; i++) {
- IIncludePathEntry entry = entries[i];
- if (entry.getEntryKind() == IIncludePathEntry.CPE_PROJECT) {
- prerequisites.add(entry.getPath().lastSegment());
- }
- }
- int size = prerequisites.size();
- if (size == 0) {
- return NO_PREREQUISITES;
- } else {
- String[] result = new String[size];
- prerequisites.toArray(result);
- return result;
- }
- }
-
- /*
- * Reads the classpath file entries of this project's .classpath file.
- * This includes the output entry.
- * As a side effect, unknown elements are stored in the given map (if not null)
- * Throws exceptions if the file cannot be accessed or is malformed.
- */
- public IIncludePathEntry[] readFileEntriesWithException(Map unknownElements) throws CoreException, IOException, AssertionFailedException {
- String xmlClasspath;
- IFile rscFile = getJSDTScopeFile();
- if (rscFile.exists()) {
- byte[] bytes = Util.getResourceContentsAsByteArray(rscFile);
- try {
- xmlClasspath = new String(bytes, org.eclipse.wst.jsdt.internal.compiler.util.Util.UTF_8); // .classpath always encoded with UTF-8
- } catch (UnsupportedEncodingException e) {
- Util.log(e, "Could not read .jsdtscope with UTF-8 encoding"); //$NON-NLS-1$
- // fallback to default
- xmlClasspath = new String(bytes);
- }
- } else {
- // when a project is imported, we get a first delta for the addition of the .project, but the .classpath is not accessible
- // so default to using java.io.File
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=96258
- URI location = rscFile.getLocationURI();
- if (location == null)
- throw new IOException("Cannot obtain a location URI for " + rscFile); //$NON-NLS-1$
- File file = Util.toLocalFile(location, null/*no progress monitor available*/);
- if (file == null)
- throw new IOException("Unable to fetch file from " + location); //$NON-NLS-1$
- byte[] bytes;
- try {
- bytes = org.eclipse.wst.jsdt.internal.compiler.util.Util.getFileByteContent(file);
- } catch (IOException e) {
- if (!file.exists())
- return defaultClasspath();
- throw e;
- }
- try {
- xmlClasspath = new String(bytes, org.eclipse.wst.jsdt.internal.compiler.util.Util.UTF_8); // .classpath always encoded with UTF-8
- } catch (UnsupportedEncodingException e) {
- Util.log(e, "Could not read .jsdtscope with UTF-8 encoding"); //$NON-NLS-1$
- // fallback to default
- xmlClasspath = new String(bytes);
- }
- }
- return decodeClasspath(xmlClasspath, unknownElements);
- }
-
- /*
- * Reads the classpath file entries of this project's .classpath file.
- * This includes the output entry.
- * As a side effect, unknown elements are stored in the given map (if not null)
- */
- private IIncludePathEntry[] readFileEntries(Map unkwownElements) {
- try {
- return readFileEntriesWithException(unkwownElements);
- } catch (CoreException e) {
- Util.log(e, "Exception while reading " + getPath().append(JavaProject.CLASSPATH_FILENAME)); //$NON-NLS-1$
- return JavaProject.INVALID_CLASSPATH;
- } catch (IOException e) {
- Util.log(e, "Exception while reading " + getPath().append(JavaProject.CLASSPATH_FILENAME)); //$NON-NLS-1$
- return JavaProject.INVALID_CLASSPATH;
- } catch (AssertionFailedException e) {
- Util.log(e, "Exception while reading " + getPath().append(JavaProject.CLASSPATH_FILENAME)); //$NON-NLS-1$
- return JavaProject.INVALID_CLASSPATH;
- }
- }
-
- /**
- * @see IJavaScriptProject
- */
- public IPath readOutputLocation() {
- // Read classpath file without creating markers nor logging problems
- IIncludePathEntry[] classpath = readFileEntries(null/*not interested in unknown elements*/);
- if (classpath == JavaProject.INVALID_CLASSPATH)
- return defaultOutputLocation();
-
- // extract the output location
- IPath outputLocation = null;
- if (classpath.length > 0) {
- IIncludePathEntry entry = classpath[classpath.length - 1];
- if (entry.getContentKind() == ClasspathEntry.K_OUTPUT) {
- outputLocation = entry.getPath();
- }
- }
- return outputLocation;
- }
-
- /**
- * @see IJavaScriptProject
- */
- public IIncludePathEntry[] readRawIncludepath() {
- // Read classpath file without creating markers nor logging problems
- IIncludePathEntry[] classpath = readFileEntries(null/*not interested in unknown elements*/);
- if (classpath == JavaProject.INVALID_CLASSPATH)
- return defaultClasspath();
-
- // discard the output location
- if (classpath.length > 0) {
- IIncludePathEntry entry = classpath[classpath.length - 1];
- if (entry.getContentKind() == ClasspathEntry.K_OUTPUT) {
- IIncludePathEntry[] copy = new IIncludePathEntry[classpath.length - 1];
- System.arraycopy(classpath, 0, copy, 0, copy.length);
- classpath = copy;
- }
- }
- return classpath;
- }
-
- /**
- * Removes the given builder from the build spec for the given project.
- */
- public void removeFromBuildSpec(String builderID) throws CoreException {
-
- IProjectDescription description = this.project.getDescription();
- ICommand[] commands = description.getBuildSpec();
- for (int i = 0; i < commands.length; ++i) {
- if (commands[i].getBuilderName().equals(builderID)) {
- ICommand[] newCommands = new ICommand[commands.length - 1];
- System.arraycopy(commands, 0, newCommands, 0, i);
- System.arraycopy(commands, i + 1, newCommands, i, commands.length - i - 1);
- description.setBuildSpec(newCommands);
- this.project.setDescription(description, null);
- return;
- }
- }
- }
-
- /*
- * Resets this project's caches
- */
- public void resetCaches() {
- JavaProjectElementInfo info = (JavaProjectElementInfo) JavaModelManager.getJavaModelManager().peekAtInfo(this);
- if (info != null){
- info.resetCaches();
- }
- }
-
- /*
- * Resolve the given raw classpath.
- */
- public IIncludePathEntry[] resolveClasspath(IIncludePathEntry[] rawClasspath) throws JavaScriptModelException {
- ArrayList resolvedEntries = new ArrayList();
- for (int i = 0, length = rawClasspath.length; i < length; i++) {
- IIncludePathEntry rawEntry = rawClasspath[i];
- switch (rawEntry.getEntryKind()){
- case IIncludePathEntry.CPE_VARIABLE:
- IIncludePathEntry resolvedEntry = null;
- try {
- resolvedEntry = JavaScriptCore.getResolvedIncludepathEntry(rawEntry);
- } catch (AssertionFailedException e) {
- // Catch the assertion failure
- // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=55992
- break;
- }
- if (resolvedEntry != null)
- resolvedEntries.add(resolvedEntry);
- break;
- case IIncludePathEntry.CPE_CONTAINER:
- IJsGlobalScopeContainer container = JavaScriptCore.getJsGlobalScopeContainer(rawEntry.getPath(), this);
- if (container == null)
- break;
- IIncludePathEntry[] containerEntries = container.getIncludepathEntries();
- if (containerEntries == null)
- break;
-
- // container was bound
- for (int j = 0, containerLength = containerEntries.length; j < containerLength; j++){
- ClasspathEntry cEntry = (ClasspathEntry) containerEntries[j];
- if (cEntry == null) {
- if (JavaModelManager.CP_RESOLVE_VERBOSE) {
- JavaModelManager.getJavaModelManager().verbose_missbehaving_container(this, rawEntry.getPath(), containerEntries);
- }
- break;
- }
- // if container is exported or restricted, then its nested entries must in turn be exported (21749) and/or propagate restrictions
- cEntry = cEntry.combineWith((ClasspathEntry) rawEntry);
- resolvedEntries.add(cEntry);
- }
- break;
- default:
- resolvedEntries.add(rawEntry);
- }
- }
- IIncludePathEntry[] result = new IIncludePathEntry[resolvedEntries.size()];
- resolvedEntries.toArray(result);
- return result;
- }
-
- /*
- * Resolve the given perProjectInfo's raw classpath and store the resolved classpath in the perProjectInfo.
- */
- public void resolveClasspath(PerProjectInfo perProjectInfo) throws JavaScriptModelException {
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- try {
- manager.setClasspathBeingResolved(this, true);
-
- // get raw info inside a synchronized block to ensure that it is consistent
- IIncludePathEntry[] rawClasspath;
- IPath outputLocation;
- IJavaScriptModelStatus rawClasspathStatus;
- synchronized (perProjectInfo) {
- rawClasspath= perProjectInfo.rawClasspath;
- if (rawClasspath == null)
- rawClasspath = perProjectInfo.readAndCacheClasspath(this);
- outputLocation = perProjectInfo.outputLocation;
- rawClasspathStatus = perProjectInfo.rawClasspathStatus;
- }
-
- IJavaScriptModelStatus unresolvedEntryStatus = JavaModelStatus.VERIFIED_OK;
- HashMap rawReverseMap = new HashMap();
- Map rootPathToResolvedEntries = new HashMap();
-
- ArrayList resolvedEntries = new ArrayList();
- int length = rawClasspath.length;
- for (int i = 0; i < length; i++) {
-
- IIncludePathEntry rawEntry = rawClasspath[i];
- IPath resolvedPath;
-
- switch (rawEntry.getEntryKind()){
-
- case IIncludePathEntry.CPE_VARIABLE :
- IIncludePathEntry resolvedEntry = null;
- try {
- resolvedEntry = JavaScriptCore.getResolvedIncludepathEntry(rawEntry);
- } catch (AssertionFailedException e) {
- // Catch the assertion failure and set ststus instead
- // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=55992
- unresolvedEntryStatus = new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_PATH, e.getMessage());
- break;
- }
- if (resolvedEntry == null) {
- unresolvedEntryStatus = new JavaModelStatus(IJavaScriptModelStatusConstants.CP_VARIABLE_PATH_UNBOUND, this, rawEntry.getPath());
- } else {
- if (rawReverseMap.get(resolvedPath = resolvedEntry.getPath()) == null) {
- rawReverseMap.put(resolvedPath , rawEntry);
- rootPathToResolvedEntries.put(resolvedPath, resolvedEntry);
- }
- resolvedEntries.add(resolvedEntry);
- }
- break;
-
- case IIncludePathEntry.CPE_CONTAINER :
- IJsGlobalScopeContainer container = JavaScriptCore.getJsGlobalScopeContainer(rawEntry.getPath(), this);
- if (container == null){
- unresolvedEntryStatus = new JavaModelStatus(IJavaScriptModelStatusConstants.CP_CONTAINER_PATH_UNBOUND, this, rawEntry.getPath());
- break;
- }
-
- IIncludePathEntry[] containerEntries = container.getIncludepathEntries();
- if (containerEntries == null) break;
-
- // container was bound
- for (int j = 0, containerLength = containerEntries.length; j < containerLength; j++){
- ClasspathEntry cEntry = (ClasspathEntry) containerEntries[j];
- if (cEntry == null) {
- if (JavaModelManager.CP_RESOLVE_VERBOSE) {
- JavaModelManager.getJavaModelManager().verbose_missbehaving_container(this, rawEntry.getPath(), containerEntries);
- }
- break;
- }
- // if container is exported or restricted, then its nested entries must in turn be exported (21749) and/or propagate restrictions
- cEntry = cEntry.combineWith((ClasspathEntry) rawEntry);
- if (rawReverseMap.get(resolvedPath = cEntry.getPath()) == null) {
- rawReverseMap.put(resolvedPath , rawEntry);
- rootPathToResolvedEntries.put(resolvedPath, cEntry);
- }
- resolvedEntries.add(cEntry);
- }
- break;
-
- default :
- if (rawReverseMap.get(resolvedPath = rawEntry.getPath()) == null) {
- rawReverseMap.put(resolvedPath , rawEntry);
- rootPathToResolvedEntries.put(resolvedPath, rawEntry);
- }
- resolvedEntries.add(rawEntry);
-
- }
- }
-
- // store resolved info along with the raw info to ensure consistency
- IIncludePathEntry[] resolvedClasspath = new IIncludePathEntry[resolvedEntries.size()];
- resolvedEntries.toArray(resolvedClasspath);
- perProjectInfo.setClasspath(rawClasspath, outputLocation, rawClasspathStatus, resolvedClasspath, rawReverseMap, rootPathToResolvedEntries, unresolvedEntryStatus);
- } finally {
- manager.setClasspathBeingResolved(this, false);
- }
- }
-
- /**
- * Answers an ID which is used to distinguish project/entries during package
- * fragment root computations
- * @return String
- */
- public String rootID(){
- return "[PRJ]"+this.project.getFullPath(); //$NON-NLS-1$
- }
-
- /**
- * Saves the classpath in a shareable format (VCM-wise) only when necessary, that is, if it is semantically different
- * from the existing one in file. Will never write an identical one.
- *
- * @param newClasspath IIncludePathEntry[]
- * @param newOutputLocation IPath
- * @return boolean Return whether the .classpath file was modified.
- * @throws JavaScriptModelException
- */
- public boolean saveClasspath(IIncludePathEntry[] newClasspath, IPath newOutputLocation) throws JavaScriptModelException {
-
- if (!this.project.isAccessible()) return false;
-
- Map unknownElements = new HashMap();
- IIncludePathEntry[] fileEntries = readFileEntries(unknownElements);
- if (fileEntries != JavaProject.INVALID_CLASSPATH && areClasspathsEqual(newClasspath, newOutputLocation, fileEntries)) {
- // no need to save it, it is the same
- return false;
- }
-
- // actual file saving
- try {
- setSharedProperty(getJSDTScopeFile(true).getProjectRelativePath().toString(), encodeClasspath(newClasspath, newOutputLocation, true, unknownElements));
- return true;
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- }
- }
-
- /**
- * Update the Java command in the build spec (replace existing one if present,
- * add one first if none).
- */
- private void setJavaCommand(
- IProjectDescription description,
- ICommand newCommand)
- throws CoreException {
-
- ICommand[] oldBuildSpec = description.getBuildSpec();
- int oldJavaCommandIndex = getJavaCommandIndex(oldBuildSpec, newCommand.getBuilderName());
- ICommand[] newCommands;
-
- if (oldJavaCommandIndex == -1) {
- // Add a Java build spec before other builders (1FWJK7I)
- newCommands = new ICommand[oldBuildSpec.length + 1];
- System.arraycopy(oldBuildSpec, 0, newCommands, 1, oldBuildSpec.length);
- newCommands[0] = newCommand;
- } else {
- oldBuildSpec[oldJavaCommandIndex] = newCommand;
- newCommands = oldBuildSpec;
- }
-
- // Commit the spec change into the project
- description.setBuildSpec(newCommands);
- this.project.setDescription(description, null);
- }
-
- /**
- * @see org.eclipse.wst.jsdt.core.IJavaScriptProject#setOption(java.lang.String, java.lang.String)
- */
- public void setOption(String optionName, String optionValue) {
- if (!JavaModelManager.getJavaModelManager().optionNames.contains(optionName)) return; // unrecognized option
- if (optionValue == null) return; // invalid value
- IEclipsePreferences projectPreferences = getEclipsePreferences();
- String defaultValue = JavaScriptCore.getOption(optionName);
- if (optionValue.equals(defaultValue)) {
- // set default value => remove preference
- projectPreferences.remove(optionName);
- } else {
- projectPreferences.put(optionName, optionValue);
- }
-
- // Dump changes
- try {
- projectPreferences.flush();
- } catch (BackingStoreException e) {
- // problem with pref store - quietly ignore
- }
- }
-
- /**
- * @see org.eclipse.wst.jsdt.core.IJavaScriptProject#setOptions(Map)
- */
- public void setOptions(Map newOptions) {
-
- IEclipsePreferences projectPreferences = getEclipsePreferences();
- try {
- if (newOptions == null){
- projectPreferences.clear();
- } else {
- Iterator entries = newOptions.entrySet().iterator();
- while (entries.hasNext()){
- Map.Entry entry = (Map.Entry) entries.next();
- String key = (String) entry.getKey();
- if (!JavaModelManager.getJavaModelManager().optionNames.contains(key)) continue; // unrecognized option
- // no filtering for encoding (custom encoding for project is allowed)
- projectPreferences.put(key, (String) entry.getValue());
- }
-
- // reset to default all options not in new map
- // @see https://bugs.eclipse.org/bugs/show_bug.cgi?id=26255
- // @see https://bugs.eclipse.org/bugs/show_bug.cgi?id=49691
- String[] pNames = projectPreferences.keys();
- int ln = pNames.length;
- for (int i=0; i<ln; i++) {
- String key = pNames[i];
- if (!newOptions.containsKey(key)) {
- projectPreferences.remove(key); // old preferences => remove from preferences table
- }
- }
- }
-
- // persist options
- projectPreferences.flush();
-
- // flush cache immediately
- try {
- getPerProjectInfo().options = null;
- } catch (JavaScriptModelException e) {
- // do nothing
- }
- } catch (BackingStoreException e) {
- // problem with pref store - quietly ignore
- }
- }
- /**
- * @see IJavaScriptProject
- */
- public void setOutputLocation(IPath path, IProgressMonitor monitor) throws JavaScriptModelException {
- if (path == null) {
- throw new IllegalArgumentException(Messages.path_nullPath);
- }
- if (path.equals(getOutputLocation())) {
- return;
- }
- setRawIncludepath(getRawIncludepath(), path, monitor);
- }
-
- /**
- * Sets the underlying kernel project of this Java project,
- * and fills in its parent and name.
- * Called by IProject.getNature().
- *
- * @see IProjectNature#setProject(IProject)
- */
- public void setProject(IProject project) {
-
- this.project = project;
- this.parent = JavaModelManager.getJavaModelManager().getJavaModel();
- /* Make sure the scope file is properly set. */
- getJSDTScopeFile(true);
- }
-
- /**
- * @see IJavaScriptProject#setRawIncludepath(IIncludePathEntry[],boolean,IProgressMonitor)
- */
- public void setRawIncludepath(
- IIncludePathEntry[] entries,
- boolean canModifyResources,
- IProgressMonitor monitor)
- throws JavaScriptModelException {
-
- setRawIncludepath(
- entries,
- getOutputLocation()/*don't change output*/,
- canModifyResources,
- monitor);
- }
-
- /**
- * @see IJavaScriptProject#setRawIncludepath(IIncludePathEntry[],IPath,boolean,IProgressMonitor)
- */
- public void setRawIncludepath(
- IIncludePathEntry[] newRawClasspath,
- IPath newOutputLocation,
- boolean canModifyResources,
- IProgressMonitor monitor)
- throws JavaScriptModelException {
-
- try {
- if (newRawClasspath == null) //are we already with the default classpath
- newRawClasspath = defaultClasspath();
-
- SetClasspathOperation op =
- new SetClasspathOperation(
- this,
- newRawClasspath,
- newOutputLocation,
- canModifyResources);
- op.runOperation(monitor);
- } catch (JavaScriptModelException e) {
- JavaModelManager.getJavaModelManager().getDeltaProcessor().flush();
- throw e;
- }
- }
-
- /**
- * @see IJavaScriptProject#setRawIncludepath(IIncludePathEntry[],IPath,IProgressMonitor)
- */
- public void setRawIncludepath(
- IIncludePathEntry[] entries,
- IPath outputLocation,
- IProgressMonitor monitor)
- throws JavaScriptModelException {
-
- setRawIncludepath(
- entries,
- outputLocation,
- true/*can change resource (as per API contract)*/,
- monitor);
- }
-
- /**
- * @see IJavaScriptProject
- */
- public void setRawIncludepath(
- IIncludePathEntry[] entries,
- IProgressMonitor monitor)
- throws JavaScriptModelException {
-
- setRawIncludepath(
- entries,
- getOutputLocation()/*don't change output*/,
- true/*can change resource (as per API contract)*/,
- monitor);
- }
-
- /**
- * Record a shared persistent property onto a project.
- * Note that it is orthogonal to IResource persistent properties, and client code has to decide
- * which form of storage to use appropriately. Shared properties produce real resource files which
- * can be shared through a VCM onto a server. Persistent properties are not shareable.
- *
- * shared properties end up in resource files, and thus cannot be modified during
- * delta notifications (a CoreException would then be thrown).
- *
- * @param key String
- * @param value String
- * @see JavaProject#getSharedProperty(String key)
- * @throws CoreException
- */
- public void setSharedProperty(String key, String value) throws CoreException {
-
- //IFile rscFile = this.project.getFile(key);
- IFile rscFile = this.project.getFile(key);
- byte[] bytes = null;
- try {
- bytes = value.getBytes(org.eclipse.wst.jsdt.internal.compiler.util.Util.UTF_8); // .classpath always encoded with UTF-8
- } catch (UnsupportedEncodingException e) {
- Util.log(e, "Could not write .jsdtscope with UTF-8 encoding "); //$NON-NLS-1$
- // fallback to default
- bytes = value.getBytes();
- }
- InputStream inputStream = new ByteArrayInputStream(bytes);
- // update the resource content
- if (rscFile.exists()) {
- if (rscFile.isReadOnly()) {
- // provide opportunity to checkout read-only .classpath file (23984)
- ResourcesPlugin.getWorkspace().validateEdit(new IFile[]{rscFile}, null);
- }
- rscFile.setContents(inputStream, IResource.FORCE, null);
- } else {
- rscFile.create(inputStream, IResource.FORCE, null);
- }
- }
-
- /**
- * If a cycle is detected, then cycleParticipants contains all the paths of projects involved in this cycle (directly and indirectly),
- * no cycle if the set is empty (and started empty)
- * @param prereqChain ArrayList
- * @param cycleParticipants HashSet
- * @param workspaceRoot IWorkspaceRoot
- * @param traversed HashSet
- * @param preferredClasspaths Map
- */
- public void updateCycleParticipants(
- ArrayList prereqChain,
- HashSet cycleParticipants,
- IWorkspaceRoot workspaceRoot,
- HashSet traversed,
- Map preferredClasspaths){
-
- IPath path = this.getPath();
- prereqChain.add(path);
- traversed.add(path);
- try {
- IIncludePathEntry[] classpath = null;
- if (preferredClasspaths != null) classpath = (IIncludePathEntry[])preferredClasspaths.get(this);
- if (classpath == null) classpath = getResolvedClasspath();
- for (int i = 0, length = classpath.length; i < length; i++) {
- IIncludePathEntry entry = classpath[i];
-
- if (entry.getEntryKind() == IIncludePathEntry.CPE_PROJECT){
- IPath prereqProjectPath = entry.getPath();
- int index = cycleParticipants.contains(prereqProjectPath) ? 0 : prereqChain.indexOf(prereqProjectPath);
- if (index >= 0) { // refer to cycle, or in cycle itself
- for (int size = prereqChain.size(); index < size; index++) {
- cycleParticipants.add(prereqChain.get(index));
- }
- } else {
- if (!traversed.contains(prereqProjectPath)) {
- IResource member = workspaceRoot.findMember(prereqProjectPath);
- if (member != null && member.getType() == IResource.PROJECT){
- JavaProject javaProject = (JavaProject)JavaScriptCore.create((IProject)member);
- javaProject.updateCycleParticipants(prereqChain, cycleParticipants, workspaceRoot, traversed, preferredClasspaths);
- }
- }
- }
- }
- }
- } catch(JavaScriptModelException e){
- // project doesn't exist: ignore
- }
- prereqChain.remove(path);
- }
-
- /**
- * Reset the collection of package fragment roots (local ones) - only if opened.
- */
- public void updatePackageFragmentRoots(){
-
- if (this.isOpen()) {
- try {
- JavaProjectElementInfo info = getJavaProjectElementInfo();
- computeChildren(info);
- info.resetCaches(); // discard caches (hold onto roots and pkg fragments)
- } catch(JavaScriptModelException e){
- try {
- close(); // could not do better
- } catch(JavaScriptModelException ex){
- // ignore
- }
- }
- }
- }
-
- /*
- * Update eclipse preferences from old preferences.
- */
- private void updatePreferences(IEclipsePreferences preferences) {
-
- Preferences oldPreferences = loadPreferences();
- if (oldPreferences != null) {
- String[] propertyNames = oldPreferences.propertyNames();
- for (int i = 0; i < propertyNames.length; i++){
- String propertyName = propertyNames[i];
- String propertyValue = oldPreferences.getString(propertyName);
- if (!"".equals(propertyValue)) { //$NON-NLS-1$
- preferences.put(propertyName, propertyValue);
- }
- }
- try {
- // save immediately new preferences
- preferences.flush();
- } catch (BackingStoreException e) {
- // fails silently
- }
- }
- }
- public LibrarySuperType getCommonSuperType() {
- String superTypeName = null;
- String superTypeContainer = null;
-
-
-
- try {
- IFolder rscPath = this.project.getFolder(JavaProject.SHARED_PROPERTIES_DIRECTORY);
-// if(!rscPath.exists()) rscPath.create(true, true, new NullProgressMonitor());
-
- IPath fullPath = new Path(JavaProject.SHARED_PROPERTIES_DIRECTORY);//.append(LibrarySuperType.SUPER_TYPE_NAME);
-
- superTypeName = getSharedProperty(fullPath.append(LibrarySuperType.SUPER_TYPE_NAME).toString());
- superTypeContainer = getSharedProperty(fullPath.append(LibrarySuperType.SUPER_TYPE_CONTAINER).toString());
- } catch (CoreException ex) {
- // TODO Auto-generated catch block
- ex.printStackTrace();
- }
- if (superTypeContainer==null || superTypeName==null)
- return null;
- return new LibrarySuperType(new Path(superTypeContainer),this,superTypeName);
-
- }
-
- public void setCommonSuperType(LibrarySuperType newSuperType) {
- String superTypeName = newSuperType.getSuperTypeName();
- String superTypeContainer = newSuperType.getRawContainerPath().toString();
-
- try {
- IFolder rscPath = this.project.getFolder(JavaProject.SHARED_PROPERTIES_DIRECTORY);
- if(!rscPath.exists()) rscPath.create(true, true, new NullProgressMonitor());
-
- IPath fullPath = new Path(JavaProject.SHARED_PROPERTIES_DIRECTORY);
- //.append(LibrarySuperType.SUPER_TYPE_NAME);
-
- setSharedProperty(fullPath.append(LibrarySuperType.SUPER_TYPE_NAME).toString(), superTypeName);
- setSharedProperty(fullPath.append(LibrarySuperType.SUPER_TYPE_CONTAINER).toString(), superTypeContainer);
- } catch (CoreException ex) {
- // TODO Auto-generated catch block
- ex.printStackTrace();
- }
-
- }
-
- public ITypeRoot findTypeRoot(String fullyQualifiedName) throws JavaScriptModelException {
-
- HandleFactory handleFactory=new HandleFactory();
- Openable openable = handleFactory.createOpenable(fullyQualifiedName, null);
- if (openable instanceof ITypeRoot)
- return (ITypeRoot) openable;
- return null;
-// IPath path = new Path(fullyQualifiedName);
-// IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
-// if (root.getLocation().isPrefixOf(path))
-// path=path.removeFirstSegments(root.getLocation().segmentCount());
-// IResource resource = root.findMember(path);
-// if (resource.exists())
-// {
-// PackageFragmentRoot packageFragmentRoot = (PackageFragmentRoot)getPackageFragmentRoot(path.removeLastSegments(1));
-// path=path.removeFirstSegments(packageFragmentRoot.getPath().segmentCount());
-// String[] simpleNames = path.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;
-// }
-// PackageFragment pkgFragment = packageFragmentRoot.getPackageFragment(pkgName);
-// String simpleName= simpleNames[length];
-// if (org.eclipse.wst.jsdt.internal.core.util.Util.isJavaLikeFileName(simpleName)) {
-// IJavaScriptUnit unit= pkgFragment.getCompilationUnit(simpleName);
-// return unit;
-// } else {
-// IClassFile classFile= pkgFragment.getClassFile(simpleName);
-// return classFile;
-// }
-// }
-// return null;
- }
-}
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
deleted file mode 100644
index e49853ea..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaProjectElementInfo.java
+++ /dev/null
@@ -1,360 +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;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-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.internal.core.util.HashSetOfArray;
-import org.eclipse.wst.jsdt.internal.core.util.HashtableOfArrayToObject;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * Info for IJavaScriptProject.
- * <p>
- * Note: <code>getChildren()</code> returns all of the <code>IPackageFragmentRoots</code>
- * specified on the classpath for the project. This can include roots external to the
- * project. See <code>JavaProject#getAllPackageFragmentRoots()</code> and
- * <code>JavaProject#getPackageFragmentRoots()</code>. To get only the <code>IPackageFragmentRoots</code>
- * that are internal to the project, use <code>JavaProject#getChildren()</code>.
- */
-
-/* package */
-class JavaProjectElementInfo extends OpenableElementInfo {
-
- static final IPackageFragmentRoot[] NO_ROOTS = new IPackageFragmentRoot[0];
-
- static class LookupCache {
- LookupCache(IPackageFragmentRoot[] allPkgFragmentRootsCache, Map rootToResolvedEntries, Map pkgFragmentsCaches) {
- this.allPkgFragmentRootsCache = allPkgFragmentRootsCache;
- this.rootToResolvedEntries = rootToResolvedEntries;
- this.pkgFragmentsCaches = pkgFragmentsCaches;
- }
-
- /*
- * A cache of all package fragment roots of this project.
- */
- public IPackageFragmentRoot[] allPkgFragmentRootsCache;
-
- /*
- * A cache of all package fragments in this project.
- * (a map from String[] (the package name) to IPackageFragmentRoot[] (the package fragment roots that contain a package fragment with this name))
- */
- public HashtableOfArrayToObject allPkgFragmentsCache;
-
- /*
- * A cache of package fragments for each package fragment root of this project
- * (a map from IPackageFragmentRoot to a set of String[] (the package name))
- */
- public Map pkgFragmentsCaches;
-
- public Map rootToResolvedEntries;
- }
-
- /**
- * A array with all the non-java resources contained by this PackageFragment
- */
- private Object[] nonJavaResources;
-
- LookupCache projectCache;
-
- /*
- * Adds the given name and its super names to the given set
- * (e.g. for {"a", "b", "c"}, adds {"a", "b", "c"}, {"a", "b"}, and {"a"})
- */
- static void addSuperPackageNames(String[] pkgName, HashtableOfArrayToObject packageFragments) {
- for (int i = pkgName.length-1; i > 0; i--) {
- if (packageFragments.getKey(pkgName, i) == null) {
- System.arraycopy(pkgName, 0, pkgName = new String[i], 0, i);
- packageFragments.put(pkgName, NO_ROOTS);
- }
- }
- }
-
- /**
- * Create and initialize a new instance of the receiver
- */
- public JavaProjectElementInfo() {
- this.nonJavaResources = null;
- }
-
- /**
- * Compute the non-java resources contained in this java project.
- */
- private Object[] computeNonJavaResources(JavaProject project) {
-
- // determine if src == project and/or if bin == project
- IPath projectPath = project.getProject().getFullPath();
- boolean srcIsProject = false;
- boolean binIsProject = false;
- char[][] inclusionPatterns = null;
- char[][] exclusionPatterns = null;
- IPath projectOutput = null;
- boolean isClasspathResolved = true;
- try {
- IIncludePathEntry entry = project.getClasspathEntryFor(projectPath);
- if (entry != null) {
- srcIsProject = true;
- inclusionPatterns = ((ClasspathEntry)entry).fullInclusionPatternChars();
- exclusionPatterns = ((ClasspathEntry)entry).fullExclusionPatternChars();
- }
- projectOutput = project.getOutputLocation();
- binIsProject = projectPath.equals(projectOutput);
- } catch (JavaScriptModelException e) {
- isClasspathResolved = false;
- }
-
- Object[] resources = new IResource[5];
- int resourcesCounter = 0;
- try {
- IResource[] members = ((IContainer) project.getResource()).members();
- int length = members.length;
- if (length > 0) {
- String sourceLevel = project.getOption(JavaScriptCore.COMPILER_SOURCE, true);
- String complianceLevel = project.getOption(JavaScriptCore.COMPILER_COMPLIANCE, true);
- IIncludePathEntry[] classpath = project.getResolvedClasspath();
- for (int i = 0; i < length; i++) {
- IResource res = members[i];
- switch (res.getType()) {
- case IResource.FILE :
- IPath resFullPath = res.getFullPath();
- String resName = res.getName();
-
- // ignore a jar file on the classpath
- if (isClasspathResolved && org.eclipse.wst.jsdt.internal.compiler.util.Util.isArchiveFileName(resName) && this.isClasspathEntryOrOutputLocation(resFullPath, classpath, projectOutput)) {
- break;
- }
- // ignore .java file if src == project
- if (srcIsProject
- && Util.isValidCompilationUnitName(resName, sourceLevel, complianceLevel)
- && !Util.isExcluded(res, inclusionPatterns, exclusionPatterns)) {
- break;
- }
- // ignore .class file if bin == project
- if (binIsProject && Util.isValidClassFileName(resName, sourceLevel, complianceLevel)) {
- break;
- }
- // else add non java resource
- if (resources.length == resourcesCounter) {
- // resize
- System.arraycopy(
- resources,
- 0,
- (resources = new IResource[resourcesCounter * 2]),
- 0,
- resourcesCounter);
- }
- resources[resourcesCounter++] = res;
- break;
- case IResource.FOLDER :
- resFullPath = res.getFullPath();
-
- // ignore non-excluded folders on the classpath or that correspond to an output location
- if ((srcIsProject && !Util.isExcluded(res, inclusionPatterns, exclusionPatterns) && Util.isValidFolderNameForPackage(res.getName(), sourceLevel, complianceLevel))
- || (isClasspathResolved && this.isClasspathEntryOrOutputLocation(resFullPath, classpath, projectOutput))) {
- break;
- }
- // else add non java resource
- if (resources.length == resourcesCounter) {
- // resize
- System.arraycopy(
- resources,
- 0,
- (resources = new IResource[resourcesCounter * 2]),
- 0,
- resourcesCounter);
- }
- resources[resourcesCounter++] = res;
- }
- }
- }
- if (resources.length != resourcesCounter) {
- System.arraycopy(
- resources,
- 0,
- (resources = new IResource[resourcesCounter]),
- 0,
- resourcesCounter);
- }
- } catch (CoreException e) {
- resources = NO_NON_JAVA_RESOURCES;
- resourcesCounter = 0;
- }
- return resources;
- }
-
- LookupCache getProjectCache(JavaProject project) {
- LookupCache cache = this.projectCache;
- if (cache == null) {
- IPackageFragmentRoot[] roots;
- Map reverseMap = new HashMap(3);
- try {
- roots = project.getAllPackageFragmentRoots(reverseMap);
- } catch (JavaScriptModelException e) {
- // project does not exist: cannot happen since this is the info of the project
- roots = new IPackageFragmentRoot[0];
- reverseMap.clear();
- }
-
- HashMap rootInfos = JavaModelManager.getJavaModelManager().deltaState.roots;
- HashMap pkgFragmentsCaches = new HashMap();
- int length = roots.length;
- for (int i = 0; i < length; i++) {
- IPackageFragmentRoot root = roots[i];
- DeltaProcessor.RootInfo rootInfo = (DeltaProcessor.RootInfo) rootInfos.get(root.getPath());
- if (rootInfo == null || rootInfo.project.equals(project)) {
- // compute fragment cache
- HashSetOfArray fragmentsCache = new HashSetOfArray();
- initializePackageNames(root, fragmentsCache);
- pkgFragmentsCaches.put(root, fragmentsCache);
- }
- }
-
- cache = new LookupCache(roots, reverseMap, pkgFragmentsCaches);
- this.projectCache = cache;
- }
- return cache;
- }
-
- /**
- * Returns an array of non-java resources contained in the receiver.
- */
- Object[] getNonJavaResources(JavaProject project) {
-
- if (this.nonJavaResources == null) {
- this.nonJavaResources = computeNonJavaResources(project);
- }
- return this.nonJavaResources;
- }
-
- private void initializePackageNames(IPackageFragmentRoot root, HashSetOfArray fragmentsCache) {
- IJavaScriptElement[] frags = null;
- try {
- if (!root.isOpen()) {
- PackageFragmentRootInfo info = new PackageFragmentRootInfo();
- ((PackageFragmentRoot) root).computeChildren(info, new HashMap());
- frags = info.children;
- } else
- frags = root.getChildren();
- } catch (JavaScriptModelException e) {
- // root doesn't exist: ignore
- return;
- }
- for (int j = 0, length2 = frags.length; j < length2; j++) {
- fragmentsCache.add(((PackageFragment) frags[j]).names);
- }
- }
-
- /*
- * Returns whether the given path is a classpath entry or an output location.
- */
- private boolean isClasspathEntryOrOutputLocation(IPath path, IIncludePathEntry[] resolvedClasspath, IPath projectOutput) {
- if (projectOutput.equals(path)) return true;
- for (int i = 0, length = resolvedClasspath.length; i < length; i++) {
- IIncludePathEntry entry = resolvedClasspath[i];
- if (entry.getPath().equals(path)) {
- return true;
- }
- }
- return false;
- }
-
- /*
- * Creates a new name lookup for this project info.
- * The given project is assumed to be the handle of this info.
- * This name lookup first looks in the given working copies.
- */
- NameLookup newNameLookup(JavaProject project, IJavaScriptUnit[] workingCopies) {
- LookupCache cache = getProjectCache(project);
- HashtableOfArrayToObject allPkgFragmentsCache = cache.allPkgFragmentsCache;
- if (allPkgFragmentsCache == null) {
- HashMap rootInfos = JavaModelManager.getJavaModelManager().deltaState.roots;
- IPackageFragmentRoot[] allRoots = cache.allPkgFragmentRootsCache;
- int length = allRoots.length;
- allPkgFragmentsCache = new HashtableOfArrayToObject();
- for (int i = 0; i < length; i++) {
- IPackageFragmentRoot root = allRoots[i];
- DeltaProcessor.RootInfo rootInfo = (DeltaProcessor.RootInfo) rootInfos.get(root.getPath());
- JavaProject rootProject = rootInfo == null ? project : rootInfo.project;
- HashSetOfArray fragmentsCache;
- if (rootProject.equals(project)) {
- // retrieve package fragments cache from this project
- fragmentsCache = (HashSetOfArray) cache.pkgFragmentsCaches.get(root);
- } else {
- // retrieve package fragments cache from the root's project
- LookupCache rootProjectCache;
- try {
- rootProjectCache = rootProject.getProjectCache();
- } catch (JavaScriptModelException e) {
- // project doesn't exit
- continue;
- }
- fragmentsCache = (HashSetOfArray) rootProjectCache.pkgFragmentsCaches.get(root);
- }
- if (fragmentsCache == null) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=183833
- fragmentsCache = new HashSetOfArray();
- initializePackageNames(root, fragmentsCache);
- }
- Object[][] set = fragmentsCache.set;
- for (int j = 0, length2 = set.length; j < length2; j++) {
- String[] pkgName = (String[]) set[j];
- if (pkgName == null)
- continue;
- Object existing = allPkgFragmentsCache.get(pkgName);
- if (existing == null || existing == NO_ROOTS) {
- allPkgFragmentsCache.put(pkgName, root);
- // ensure super packages (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=119161)
- // are also in the map
- addSuperPackageNames(pkgName, allPkgFragmentsCache);
- } else {
- if (existing instanceof PackageFragmentRoot) {
- allPkgFragmentsCache.put(pkgName, new IPackageFragmentRoot[] {(PackageFragmentRoot) existing, root});
- } else {
- IPackageFragmentRoot[] roots = (IPackageFragmentRoot[]) existing;
- int rootLength = roots.length;
- System.arraycopy(roots, 0, roots = new IPackageFragmentRoot[rootLength+1], 0, rootLength);
- roots[rootLength] = root;
- allPkgFragmentsCache.put(pkgName, roots);
- }
- }
- }
- }
- cache.allPkgFragmentsCache = allPkgFragmentsCache;
- }
- return new NameLookup(cache.allPkgFragmentRootsCache, cache.allPkgFragmentsCache, workingCopies, cache.rootToResolvedEntries);
- }
-
- /*
- * Reset the package fragment roots and package fragment caches
- */
- void resetCaches() {
- this.projectCache = null;
- }
-
- /**
- * Set the fNonJavaResources to res value
- */
- void setNonJavaResources(Object[] resources) {
-
- this.nonJavaResources = resources;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavadocConstants.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavadocConstants.java
deleted file mode 100644
index 59de881f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavadocConstants.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core;
-
-public interface JavadocConstants {
-
- String ANCHOR_PREFIX_END = "\""; //$NON-NLS-1$
- String ANCHOR_PREFIX_START = "<A NAME=\""; //$NON-NLS-1$
- String ANCHOR_SUFFIX = "</A>"; //$NON-NLS-1$
- int ANCHOR_SUFFIX_LENGTH = JavadocConstants.ANCHOR_SUFFIX.length();
- String CONSTRUCTOR_DETAIL = "<!-- ========= CONSTRUCTOR DETAIL ======== -->"; //$NON-NLS-1$
- String CONSTRUCTOR_SUMMARY = "<!-- ======== CONSTRUCTOR SUMMARY ======== -->"; //$NON-NLS-1$
- String FIELD_SUMMARY = "<!-- =========== FIELD SUMMARY =========== -->"; //$NON-NLS-1$
- String ENUM_CONSTANT_SUMMARY = "<!-- =========== ENUM CONSTANT SUMMARY =========== -->"; //$NON-NLS-1$
- String ANNOTATION_TYPE_REQUIRED_MEMBER_SUMMARY = "<!-- =========== ANNOTATION TYPE REQUIRED MEMBER SUMMARY =========== -->"; //$NON-NLS-1$
- String ANNOTATION_TYPE_OPTIONAL_MEMBER_SUMMARY = "<!-- =========== ANNOTATION TYPE OPTIONAL MEMBER SUMMARY =========== -->"; //$NON-NLS-1$
- String END_OF_CLASS_DATA = "<!-- ========= END OF CLASS DATA ========= -->"; //$NON-NLS-1$
- String HTML_EXTENSION = ".html"; //$NON-NLS-1$
- String INDEX_FILE_NAME = "index.html"; //$NON-NLS-1$
- String METHOD_DETAIL = "<!-- ============ METHOD DETAIL ========== -->"; //$NON-NLS-1$
- String METHOD_SUMMARY = "<!-- ========== METHOD SUMMARY =========== -->"; //$NON-NLS-1$
- String NESTED_CLASS_SUMMARY = "<!-- ======== NESTED CLASS SUMMARY ======== -->"; //$NON-NLS-1$
- String PACKAGE_FILE_NAME = "package-summary.html"; //$NON-NLS-1$
- String START_OF_CLASS_DATA = "<!-- ======== START OF CLASS DATA ======== -->"; //$NON-NLS-1$
- int START_OF_CLASS_DATA_LENGTH = JavadocConstants.START_OF_CLASS_DATA.length();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/LRUCacheEnumerator.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/LRUCacheEnumerator.java
deleted file mode 100644
index 658a196b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/LRUCacheEnumerator.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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.Enumeration;
-
-/**
- * The <code>LRUCacheEnumerator</code> returns its elements in
- * the order they are found in the <code>LRUCache</code>, with the
- * most recent elements first.
- *
- * Once the enumerator is created, elements which are later added
- * to the cache are not returned by the enumerator. However,
- * elements returned from the enumerator could have been closed
- * by the cache.
- */
-public class LRUCacheEnumerator implements Enumeration {
- /**
- * Current element;
- */
- protected LRUEnumeratorElement fElementQueue;
-
- public static class LRUEnumeratorElement {
- /**
- * Value returned by <code>nextElement()</code>;
- */
- public Object fValue;
-
- /**
- * Next element
- */
- public LRUEnumeratorElement fNext;
-
- /**
- * Constructor
- */
- public LRUEnumeratorElement(Object value) {
- fValue = value;
- }
- }
-/**
- * Creates a CacheEnumerator on the list of <code>LRUEnumeratorElements</code>.
- */
-public LRUCacheEnumerator(LRUEnumeratorElement firstElement) {
- fElementQueue = firstElement;
-}
-/**
- * Returns true if more elements exist.
- */
-public boolean hasMoreElements() {
- return fElementQueue != null;
-}
-/**
- * Returns the next element.
- */
-public Object nextElement() {
- Object temp = fElementQueue.fValue;
- fElementQueue = fElementQueue.fNext;
- return temp;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/LibraryFragmentRoot.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/LibraryFragmentRoot.java
deleted file mode 100644
index 765a7979..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/LibraryFragmentRoot.java
+++ /dev/null
@@ -1,285 +0,0 @@
-/*******************************************************************************
- * 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
- * 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.util.ArrayList;
-import java.util.Map;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatusConstants;
-import org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.util.Util;
-
-
-
-public class LibraryFragmentRoot extends PackageFragmentRoot{
-
- protected final IPath libraryPath;
- protected boolean[] fLangeRuntime= new boolean[] {false,false};
-
- protected LibraryFragmentRoot(IPath jarPath, JavaProject project) {
- super(null, project);
- this.libraryPath = jarPath;
- }
-
- /**
- * Constructs a package fragment root which is the root of the Java package directory hierarchy
- * based on a JAR file.
- */
- protected LibraryFragmentRoot(IResource resource, JavaProject project) {
- super(resource, project);
- this.libraryPath = resource.getFullPath();
- }
-
- public PackageFragment getPackageFragment(String[] pkgName) {
- return new LibraryPackageFragment(this, pkgName);
- }
-
-
- public IPath getPath() {
- if (isExternal()) {
- return this.libraryPath;
- } else {
- return super.getPath();
- }
- }
-
- public IPath getLocation() {
- if (isExternal()) {
- return this.libraryPath;
- } else {
- return super.getLocation();
- }
- }
-
- public IResource getUnderlyingResource() throws JavaScriptModelException {
- if (isExternal()) {
- if (!exists()) throw newNotPresentException();
- return null;
- } else {
- return super.getUnderlyingResource();
- }
- }
- public IResource getResource() {
- if (this.resource == null) {
- this.resource = JavaModel.getTarget(ResourcesPlugin.getWorkspace().getRoot(), this.libraryPath, false);
- }
- if (this.resource instanceof IResource) {
- return super.getResource();
- } else {
- // external jar
- return null;
- }
- }
-
- protected boolean computeChildren(OpenableElementInfo info, Map newElements) throws JavaScriptModelException {
-
- String name[]={""};//libraryPath.lastSegment()}; //$NON-NLS-1$
- ArrayList vChildren = new ArrayList(5);
- if (!isDirectory())
- {
- LibraryPackageFragment packFrag= new LibraryPackageFragment(this, name);
- LibraryPackageFragmentInfo fragInfo= new LibraryPackageFragmentInfo();
-
- packFrag.computeChildren(fragInfo);
- newElements.put(packFrag, fragInfo);
- vChildren.add(packFrag);
- }
- else
- {
- computeDirectoryChildren(getFile(),true, CharOperation.NO_STRINGS, vChildren);
- }
- IJavaScriptElement[] children = new IJavaScriptElement[vChildren.size()];
- vChildren.toArray(children);
- info.setChildren(children);
- return true;
- }
-
-
- protected void computeDirectoryChildren(File file, boolean isIncluded, String[] pkgName, ArrayList vChildren) throws JavaScriptModelException {
-
- if (isIncluded) {
- IPackageFragment pkg = getPackageFragment(pkgName);
- vChildren.add(pkg);
- }
- try {
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- File[] members = file.listFiles();
- boolean hasIncluded = isIncluded;
- if (members != null && members.length > 0) {
- for (int i = 0; i < members.length; i++) {
- File member = members[i];
- String memberName = member.getName();
-
- if (member.isDirectory()) {
-
- String[] newNames = org.eclipse.wst.jsdt.internal.core.util.Util.arrayConcat(pkgName, manager.intern(memberName));
- computeDirectoryChildren( member, true, newNames, vChildren);
- }
- else
- {
- if (!hasIncluded
- && Util.isJavaFileName(memberName)) {
- hasIncluded = true;
- IPackageFragment pkg = getPackageFragment(pkgName);
- vChildren.add(pkg);
- }
- }
- }
- }
- } catch(IllegalArgumentException e){
- throw new JavaScriptModelException(e, IJavaScriptModelStatusConstants.ELEMENT_DOES_NOT_EXIST); // could be thrown by ElementTree when path is not found
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- }
- }
-
-
- protected Object createElementInfo() {
- return new LibraryFragmentRootInfo();
- }
-
-
- protected int determineKind(IResource underlyingResource) {
- return IPackageFragmentRoot.K_BINARY;
- }
- public boolean equals(Object o) {
- if (this == o)
- return true;
- if (o instanceof LibraryFragmentRoot) {
- LibraryFragmentRoot other= (LibraryFragmentRoot) o;
- return this.libraryPath.equals(other.libraryPath);
- }
- return false;
- }
- public String getElementName() {
- //return "";
- return this.libraryPath.lastSegment();
- }
-
-
- public int hashCode() {
- return this.libraryPath.hashCode();
- }
-
- public boolean isExternal() {
- return getResource() == null;
- }
- /**
- * Jars and jar entries are all read only
- */
- public boolean isReadOnly() {
- return true;
- }
-
- /**
- * Returns whether the corresponding resource or associated file exists
- */
-protected boolean resourceExists() {
- if (this.isExternal()) {
- return
- JavaModel.getTarget(
- ResourcesPlugin.getWorkspace().getRoot(),
- this.getPath(), // don't make the path relative as this is an external archive
- true) != null;
- } else {
- return super.resourceExists();
- }
-}
-
-//private ClassFile getLibraryClassFile(){
-// try {
-// ArrayList childrenOfType = getChildrenOfType(IJavaScriptElement.PACKAGE_FRAGMENT);
-// if (!childrenOfType.isEmpty())
-// {
-// IPackageFragment child=(IPackageFragment)childrenOfType.get(0);
-// IClassFile[] classFiles = child.getClassFiles();
-// if (classFiles!=null && classFiles.length>0)
-// return (ClassFile)classFiles[0];
-// }
-// } catch (JavaScriptModelException e) {
-// // TODO Auto-generated catch block
-// e.printStackTrace();
-// }
-// return null;
-//}
-
- 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);
- }
-
- public boolean isResourceContainer() {
- return false;
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.core.JavaElement#getDisplayName()
- */
- public String getDisplayName() {
-
- JsGlobalScopeContainerInitializer containerInitializer = getContainerInitializer();
- if(containerInitializer!=null) return containerInitializer.getDescription(getPath(), getJavaScriptProject());
- return super.getDisplayName();
-
- }
-
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.core.JavaElement#isVirtual()
- */
- public boolean isVirtual() {
- return true;
- }
-
- public boolean isLanguageRuntime() {
- if(fLangeRuntime[0]) {
- return fLangeRuntime[1];
- }
-
- JsGlobalScopeContainerInitializer init = getContainerInitializer();
- if(init==null) {
- fLangeRuntime[0]=true;
- fLangeRuntime[1]=false;
- return fLangeRuntime[1];
- }
- fLangeRuntime[1]= init.getKind()==IJsGlobalScopeContainer.K_SYSTEM ||init.getKind()==IJsGlobalScopeContainer.K_DEFAULT_SYSTEM ;
- fLangeRuntime[0]=true;
- return fLangeRuntime[1];
- }
-
- public boolean isLibrary() {
- return true;
- }
-
- public boolean isDirectory()
- {
- return !Util.isJavaFileName(this.libraryPath.lastSegment());
- }
-
- public File getFile()
- {
- return new File(this.libraryPath.toOSString());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/LibraryFragmentRootInfo.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/LibraryFragmentRootInfo.java
deleted file mode 100644
index d6e4d92f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/LibraryFragmentRootInfo.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core;
-
-/**
- * The element info for <code>LibraryFragmentRootInfo</code>s.
- */
-class LibraryFragmentRootInfo extends PackageFragmentRootInfo {
-/**
- * Returns an array of non-java resources contained in the receiver.
- */
-public Object[] getNonJavaResources() {
- fNonJavaResources = NO_NON_JAVA_RESOURCES;
- return fNonJavaResources;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/LibraryPackageFragment.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/LibraryPackageFragment.java
deleted file mode 100644
index 41378de3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/LibraryPackageFragment.java
+++ /dev/null
@@ -1,270 +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;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-
-import org.eclipse.core.resources.IResource;
-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.IClassFile;
-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.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer;
-import org.eclipse.wst.jsdt.internal.compiler.util.SuffixConstants;
-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.wst.jsdt.core.IPackageFragment
- */
-public class LibraryPackageFragment extends PackageFragment implements SuffixConstants {
-final static String[]DEFAULT_PACKAGE={""}; //$NON-NLS-1$
-/**
- * Constructs a package fragment that is contained within a jar or a zip.
- */
-protected LibraryPackageFragment(PackageFragmentRoot root, String[] names) {
- super(root, names);
-}
-/**
- * Compute the children of this package fragment. Children of jar package fragments
- * can only be IClassFile (representing .class files).
- */
-protected boolean computeChildren(OpenableElementInfo info) {
- String name = this.getPackageFragmentRoot().getPath().toOSString();
- ClassFile classFile = new ClassFile(this,name);
-// JavaScriptUnit cu= new JavaScriptUnit(this, this.getPackageFragmentRoot().getPath().toOSString(), DefaultWorkingCopyOwner.PRIMARY);
- IJavaScriptElement[] children= new IJavaScriptElement[]{classFile};
- info.setChildren(children);
- return true;
-}
-
-/**
- * Returns true if this fragment contains at least one java resource.
- * Returns false otherwise.
- */
-public boolean containsJavaResources() throws JavaScriptModelException {
- return true;
-}
-/**
- * @see org.eclipse.wst.jsdt.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 LibraryPackageFragmentInfo();
-}
-/*
- * @see JavaElement#generateInfos
- */
-protected void generateInfos(Object info, HashMap newElements, IProgressMonitor pm) throws JavaScriptModelException {
- // Open my jar: this creates all the pkg infos
-
- if (!getLibraryFragmentRoot().isDirectory())
- {
- Openable openableParent = (Openable)this.parent;
- if (!openableParent.isOpen()) {
- openableParent.generateInfos(openableParent.createElementInfo(), newElements, pm);
- }
- }
- else
- super.generateInfos(info, newElements, pm);
-}
-
-
-protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaScriptModelException {
-
- if (!getLibraryFragmentRoot().isDirectory())
- return true; // already built
- // check whether this pkg can be opened
-
- // add compilation units/class files from resources
- HashSet vChildren = new HashSet();
- try {
- File file = getUnderlyingFile();
- File[] members = file.listFiles();
- if (members != null && members.length > 0) {
- for (int i = 0; i < members.length; i++) {
- File child = members[i];
- if (child.isFile()) {
- IJavaScriptElement childElement;
- if (org.eclipse.wst.jsdt.internal.compiler.util.Util.isJavaFileName(child.getName())) {
- childElement = getClassFile(child.getName());
- vChildren.add(childElement);
- } else if (Util.isMetadataFileName(child.getName())) {
- childElement = getClassFile(child.getName());
- vChildren.add(childElement);
- }
- }
- }
- }
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- }
-
-
- IJavaScriptElement[] children = new IJavaScriptElement[vChildren.size()];
- vChildren.toArray(children);
- info.setChildren(children);
- return true;
-}
-
-
-
-/**
- * @see org.eclipse.wst.jsdt.core.IPackageFragment
- */
-public IClassFile[] getClassFiles() throws JavaScriptModelException {
- ArrayList list = getChildrenOfType(CLASS_FILE);
- IClassFile[] array= new IClassFile[list.size()];
- list.toArray(array);
- return array;
-}
-/**
- * A jar package fragment never contains compilation units.
- * @see org.eclipse.wst.jsdt.core.IPackageFragment
- */
-public IJavaScriptUnit[] getJavaScriptUnits() {
- 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[] getNonJavaScriptResources() throws JavaScriptModelException {
- if (this.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 this.storedNonJavaResources();
- }
-}
-/**
- * Jars and jar entries are all read only
- */
-public boolean isReadOnly() {
- return true;
-}
- static final Object[] NO_OBJECTS={};
-protected Object[] storedNonJavaResources() throws JavaScriptModelException {
- return NO_OBJECTS;
-}
-
-protected boolean resourceExists() {
- return getPackageFragmentRoot().resourceExists();
-}
-
-protected LibraryFragmentRoot getLibraryFragmentRoot()
-{
- return (LibraryFragmentRoot) getPackageFragmentRoot();
-}
-
-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);
- }
-
- LibraryFragmentRoot libraryFragmentRoot = getLibraryFragmentRoot();
- if (!libraryFragmentRoot.isDirectory())
- {
- IPath path = getLibraryFragmentRoot().getPath();
-// if (org.eclipse.wst.jsdt.internal.compiler.util.Util.isClassFileName(path.lastSegment().toCharArray())
-// && path.lastSegment().equalsIgnoreCase(classFileName))
-// {
- if(path.toOSString().endsWith(classFileName)
- || path.isPrefixOf(new Path(classFileName))) {
- return new ClassFile(this, path.toOSString());
- }
- }
- else
- {
- String filename= "";
- if (this.getFile()!=null)
- filename= this.getFile().getAbsolutePath()+File.separator+classFileName;
- else
- filename=classFileName;
-
- return (!Util.isMetadataFileName(classFileName)) ? (IClassFile)new ClassFile(this,filename) : (IClassFile)new MetadataFile(this,filename);
-
- }
- return super.getClassFile(classFileName);
-}
-public String getDisplayName() {
- if(parent instanceof LibraryFragmentRoot) {
- JsGlobalScopeContainerInitializer initializer = ((LibraryFragmentRoot)parent).getContainerInitializer();
- if(initializer==null) return getPath().removeLastSegments(1).toString();
- String name = initializer.getDescription(getPath(), getJavaScriptProject());
- if(name!=null) return name;
- }
- return parent.getPath().lastSegment();
-}
-
-public File getUnderlyingFile() throws JavaScriptModelException {
- File file = getLibraryFragmentRoot().getFile();
- if (file == null) {
- return null;
- }
- if (this.names.length == 0)
- return file;
- // the underlying resource may be a folder or a project (in the case that the project folder
- // is atually the package fragment root)
- String[] segs = this.names;
- for (int i = 0; i < segs.length; ++i) {
- File child = new File(file,segs[i]);
- if (!child.exists() ) {
- throw newNotPresentException();
- }
- file = child;
- }
- return file;
-}
-
-public File getFile() {
- File file = getLibraryFragmentRoot().getFile();
- int length = this.names.length;
- if (length == 0) {
- return file;
- } else {
- String[] segs = this.names;
- for (int i = 0; i < segs.length; ++i) {
- File child = new File(file,segs[i]);
- if (!child.exists() ) {
- return null;
- }
- file = child;
- }
- return file;
- }
-}
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/LibraryPackageFragmentInfo.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/LibraryPackageFragmentInfo.java
deleted file mode 100644
index a8ba991e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/LibraryPackageFragmentInfo.java
+++ /dev/null
@@ -1,23 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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 LibraryPackageFragmentInfo 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/LocalVariable.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/LocalVariable.java
deleted file mode 100644
index 53651efe..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/LocalVariable.java
+++ /dev/null
@@ -1,195 +0,0 @@
-/*******************************************************************************
- * 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 java.util.HashMap;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.wst.jsdt.core.IBuffer;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.ILocalVariable;
-import org.eclipse.wst.jsdt.core.IOpenable;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-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.internal.core.util.MementoTokenizer;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-
-public class LocalVariable extends SourceRefElement implements ILocalVariable {
-
- String name;
- public int declarationSourceStart, declarationSourceEnd;
- public int nameStart, nameEnd;
- String typeSignature;
-
- public LocalVariable(
- JavaElement parent,
- String name,
- int declarationSourceStart,
- int declarationSourceEnd,
- int nameStart,
- int nameEnd,
- String typeSignature) {
-
- super(parent);
- this.name = name;
- this.declarationSourceStart = declarationSourceStart;
- this.declarationSourceEnd = declarationSourceEnd;
- this.nameStart = nameStart;
- this.nameEnd = nameEnd;
- this.typeSignature = typeSignature;
- }
-
- protected void closing(Object info) {
- // a local variable has no info
- }
-
- protected Object createElementInfo() {
- // a local variable has no info
- return null;
- }
-
- public boolean equals(Object o) {
- if (!(o instanceof LocalVariable)) return false;
- LocalVariable other = (LocalVariable)o;
- return
- this.declarationSourceStart == other.declarationSourceStart
- && this.declarationSourceEnd == other.declarationSourceEnd
- && this.nameStart == other.nameStart
- && this.nameEnd == other.nameEnd
- && super.equals(o);
- }
-
- public boolean exists() {
- return this.parent.exists(); // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=46192
- }
-
- protected void generateInfos(Object info, HashMap newElements, IProgressMonitor pm) {
- // a local variable has no info
- }
-
- public IJavaScriptElement getHandleFromMemento(String token, MementoTokenizer memento, WorkingCopyOwner owner) {
- switch (token.charAt(0)) {
- case JEM_COUNT:
- return getHandleUpdatingCountFromMemento(memento, owner);
- }
- return this;
- }
-
- /*
- * @see JavaElement#getHandleMemento(StringBuffer)
- */
- protected void getHandleMemento(StringBuffer buff) {
- ((JavaElement)getParent()).getHandleMemento(buff);
- buff.append(getHandleMementoDelimiter());
- buff.append(this.name);
- buff.append(JEM_COUNT);
- buff.append(this.declarationSourceStart);
- buff.append(JEM_COUNT);
- buff.append(this.declarationSourceEnd);
- buff.append(JEM_COUNT);
- buff.append(this.nameStart);
- buff.append(JEM_COUNT);
- buff.append(this.nameEnd);
- buff.append(JEM_COUNT);
- buff.append(this.typeSignature);
- if (this.occurrenceCount > 1) {
- buff.append(JEM_COUNT);
- buff.append(this.occurrenceCount);
- }
- }
-
- protected char getHandleMementoDelimiter() {
- return JavaElement.JEM_LOCALVARIABLE;
- }
-
- public IResource getCorrespondingResource() {
- return null;
- }
-
- public String getElementName() {
- return this.name;
- }
-
- public int getElementType() {
- return LOCAL_VARIABLE;
- }
-
- public ISourceRange getNameRange() {
- return new SourceRange(this.nameStart, this.nameEnd-this.nameStart+1);
- }
-
- public IPath getPath() {
- return this.parent.getPath();
- }
-
- public IResource getResource() {
- return this.parent.getResource();
- }
-
- /**
- * @see org.eclipse.wst.jsdt.core.ISourceReference
- */
- public String getSource() throws JavaScriptModelException {
- IOpenable openable = this.parent.getOpenableParent();
- IBuffer buffer = openable.getBuffer();
- if (buffer == null) {
- return null;
- }
- ISourceRange range = getSourceRange();
- int offset = range.getOffset();
- int length = range.getLength();
- if (offset == -1 || length == 0 ) {
- return null;
- }
- try {
- return buffer.getText(offset, length);
- } catch(RuntimeException e) {
- return null;
- }
- }
-
- /**
- * @see org.eclipse.wst.jsdt.core.ISourceReference
- */
- public ISourceRange getSourceRange() {
- return new SourceRange(this.declarationSourceStart, this.declarationSourceEnd-this.declarationSourceStart+1);
- }
-
- public String getTypeSignature() {
- return this.typeSignature;
- }
-
- public IResource getUnderlyingResource() throws JavaScriptModelException {
- return this.parent.getUnderlyingResource();
- }
-
- public int hashCode() {
- return Util.combineHashCodes(this.parent.hashCode(), this.nameStart);
- }
-
- public boolean isStructureKnown() throws JavaScriptModelException {
- return true;
- }
-
- protected void toStringInfo(int tab, StringBuffer buffer, Object info, boolean showResolvedInfo) {
- buffer.append(this.tabString(tab));
- if (info != NO_INFO) {
- buffer.append(Signature.toString(this.getTypeSignature()));
- buffer.append(" "); //$NON-NLS-1$
- }
- toStringName(buffer);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/Logger.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/Logger.java
deleted file mode 100644
index c236141a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/Logger.java
+++ /dev/null
@@ -1,100 +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;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.osgi.framework.Bundle;
-
-/**
-*
-* 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.
-*
-* @see org.eclipse.wst.jsdt.web.core.internal.Logger
-*/
-public class Logger {
- public static final int ERROR = IStatus.ERROR; // 4
- public static final int ERROR_DEBUG = 200 + Logger.ERROR;
- public static final int INFO = IStatus.INFO; // 1
- public static final int INFO_DEBUG = 200 + Logger.INFO;
- public static final int OK = IStatus.OK; // 0
- public static final int OK_DEBUG = 200 + Logger.OK;
- private static final String PLUGIN_ID = JavaScriptCore.PLUGIN_ID;
- public static final int WARNING = IStatus.WARNING; // 2
- public static final int WARNING_DEBUG = 200 + Logger.WARNING;
-
- /**
- * Adds message to log.
- *
- * @param level
- * severity level of the message (OK, INFO, WARNING, ERROR,
- * OK_DEBUG, INFO_DEBUG, WARNING_DEBUG, ERROR_DEBUG)
- * @param message
- * text to add to the log
- * @param exception
- * exception thrown
- */
- protected static void _log(int level, String message, Throwable exception) {
- if (level == Logger.OK_DEBUG || level == Logger.INFO_DEBUG || level == Logger.WARNING_DEBUG || level == Logger.ERROR_DEBUG) {
- if (!Logger.isDebugging()) {
- return;
- }
- }
- int severity = IStatus.OK;
- switch (level) {
- case INFO_DEBUG:
- case INFO:
- severity = IStatus.INFO;
- break;
- case WARNING_DEBUG:
- case WARNING:
- severity = IStatus.WARNING;
- break;
- case ERROR_DEBUG:
- case ERROR:
- severity = IStatus.ERROR;
- }
- message = (message != null) ? message : "null"; //$NON-NLS-1$
- Status statusObj = new Status(severity, Logger.PLUGIN_ID, severity, message, exception);
- Bundle bundle = Platform.getBundle(Logger.PLUGIN_ID);
- if (bundle != null) {
- Platform.getLog(bundle).log(statusObj);
- }
- }
-
- /**
- * @return true if the platform is debugging
- */
- public static boolean isDebugging() {
- return Platform.inDebugMode();
- }
-
- public static void log(int level, String message) {
- Logger._log(level, message, null);
- }
-
- public static void log(int level, String message, Throwable exception) {
- Logger._log(level, message, exception);
- }
-
- public static void logException(String message, Throwable exception) {
- Logger._log(Logger.ERROR, message, exception);
- }
-
- public static void logException(Throwable exception) {
- Logger._log(Logger.ERROR, exception.getMessage(), exception);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/LookupScopeElementInfo.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/LookupScopeElementInfo.java
deleted file mode 100644
index 55c12c20..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/LookupScopeElementInfo.java
+++ /dev/null
@@ -1,219 +0,0 @@
-/*******************************************************************************
- * 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
- * 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.HashMap;
-import java.util.Map;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.core.util.HashtableOfArrayToObject;
-
-public class LookupScopeElementInfo extends PackageFragmentRootInfo {
-
- private JavaProject javaProject;
- private IPackageFragmentRoot[] rootsInScope;
- private LookupCache cache;
-
- //public static final String[] SYSTEM_LIBRARIES = {"system.js"};
-
- /* places imports in the document scope before the classpath entries */
- private static final boolean LOOKUP_LOCAL_SCOPE_FIRST = false;
-
- static class LookupCache {
- LookupCache(IPackageFragmentRoot[] allPkgFragmentRootsCache, HashtableOfArrayToObject allPkgFragmentsCache, HashtableOfArrayToObject isPackageCache, Map rootToResolvedEntries) {
- this.allPkgFragmentRootsCache = allPkgFragmentRootsCache;
- this.allPkgFragmentsCache = allPkgFragmentsCache;
- this.isPackageCache = isPackageCache;
- this.rootToResolvedEntries = rootToResolvedEntries;
- }
-
- /*
- * A cache of all package fragment roots of this project.
- */
- public IPackageFragmentRoot[] allPkgFragmentRootsCache;
-
- /*
- * A cache of all package fragments in this project.
- * (a map from String[] (the package name) to IPackageFragmentRoot[] (the package fragment roots that contain a package fragment with this name)
- */
- public HashtableOfArrayToObject allPkgFragmentsCache;
-
- /*
- * A set of package names (String[]) that are known to be packages.
- */
- public HashtableOfArrayToObject isPackageCache;
-
- public Map rootToResolvedEntries;
- }
-
-
- public IPackageFragmentRoot[] getAllRoots() {
- if(LOOKUP_LOCAL_SCOPE_FIRST) return getAllRootsLocalFirst();
-
- return getAllRootsGlobalFirst();
- }
-
- private IPackageFragmentRoot[] getAllRootsGlobalFirst() {
- IPackageFragmentRoot[] projectRoots = new IPackageFragmentRoot[0];
- int lastGood = 0;
- try {
- projectRoots = javaProject.getPackageFragmentRoots();
-
-
- for(int i =0;i<projectRoots.length;i++) {
- if(projectRoots[i].isLanguageRuntime()) {
- projectRoots[lastGood++]=projectRoots[i];
- }
- }
- } catch (JavaScriptModelException ex) {
- projectRoots = new IPackageFragmentRoot[0];
- }
-
- IPackageFragmentRoot[] allRoots = new IPackageFragmentRoot[lastGood + rootsInScope.length ];
-
- System.arraycopy(projectRoots, 0, allRoots, 0, lastGood);
- System.arraycopy(rootsInScope, 0, allRoots, lastGood, rootsInScope.length);
- return allRoots;
- }
-
- private IPackageFragmentRoot[] getAllRootsLocalFirst() {
- IPackageFragmentRoot[] projectRoots = new IPackageFragmentRoot[0];
- int lastGood = 0;
- try {
- projectRoots = javaProject.getPackageFragmentRoots();
-
-
- for(int i =0;i<projectRoots.length;i++) {
- if(projectRoots[i].isLanguageRuntime()) {
- projectRoots[lastGood++]=projectRoots[i];
- }
- }
- } catch (JavaScriptModelException ex) {
- projectRoots = new IPackageFragmentRoot[0];
- }
-
- IPackageFragmentRoot[] allRoots = new IPackageFragmentRoot[lastGood + rootsInScope.length ];
-
- System.arraycopy(rootsInScope, 0, allRoots, 0, rootsInScope.length);
- System.arraycopy(projectRoots, 0, allRoots, rootsInScope.length, lastGood);
- return allRoots;
- }
-
- public LookupScopeElementInfo(JavaProject project,IPackageFragmentRoot[] rootsInScope){
- this.javaProject = project;
- this.rootsInScope = rootsInScope;
-
-
- }
-
- NameLookup newNameLookup(IJavaScriptUnit[] workingCopies) {
- BuildLookupScopeCache(getAllRoots());
-
- return new NameLookup(cache.allPkgFragmentRootsCache, cache.allPkgFragmentsCache, workingCopies, cache.rootToResolvedEntries);
- }
-
- public LookupCache BuildLookupScopeCache(IPackageFragmentRoot[] rootsInScope) {
-
-
- Map reverseMap = new HashMap(3);
-// IPackageFragmentRoot[] roots=null;
-//
-// for(int i = 0;i<rootsInScope.length;i++) {
-// try {
-//
-// IIncludePathEntry entry = javaProject.getClasspathEntryFor(rootsInScope[i].getPath());
-// reverseMap.put(rootsInScope[i],entry);
-// } catch (JavaScriptModelException ex) {
-// // TODO Auto-generated catch block
-// ex.printStackTrace();
-// }
-//
-// }
-
-// try {
-// roots = javaProject.getAllPackageFragmentRoots(reverseMap);
-// } catch (JavaScriptModelException e) {
-// // project does not exist: cannot happen since this is the info of the project
-// roots = new IPackageFragmentRoot[0];
-// reverseMap.clear();
-// }
- HashtableOfArrayToObject fragmentsCache = new HashtableOfArrayToObject();
- HashtableOfArrayToObject isPackageCache = new HashtableOfArrayToObject();
- for (int i = 0, length = rootsInScope.length; i < length; i++) {
- IPackageFragmentRoot root = rootsInScope[i];
- IJavaScriptElement[] frags = null;
- try {
- if(root instanceof DocumentContextFragmentRoot) {
- LibraryFragmentRootInfo info = new LibraryFragmentRootInfo();
- ((DocumentContextFragmentRoot) root).computeChildren(info, new HashMap());
- frags = info.children;
- }else if (root instanceof LibraryFragmentRoot) {
- LibraryFragmentRootInfo info = new LibraryFragmentRootInfo();
- ((LibraryFragmentRoot) root).computeChildren(info, new HashMap());
- frags = info.children;
-// } else if (root.isArchive() && !root.isOpen()) {
-// JarPackageFragmentRootInfo info = new JarPackageFragmentRootInfo();
-// ((JarPackageFragmentRoot) root).computeChildren(info, new HashMap());
-// frags = info.children;
- } else if (root instanceof PackageFragmentRoot) {
- PackageFragmentRootInfo info = new PackageFragmentRootInfo();
- ((PackageFragmentRoot) root).computeChildren(info, new HashMap());
- frags = info.children;
- }else
- frags = root.getChildren();
- } catch (JavaScriptModelException e) {
- // root doesn't exist: ignore
- continue;
- }
- for (int j = 0, length2 = frags.length; j < length2; j++) {
- PackageFragment fragment= (PackageFragment) frags[j];
- /* Keep folders off the classpath */
- //if(fragment.getPath().getFileExtension()==null || !fragment.getPath().getFileExtension().equals(".js")) continue;
- String[] pkgName = fragment.names;
- Object existing = fragmentsCache.get(pkgName);
- if (existing == null) {
- fragmentsCache.put(pkgName, root);
- // cache whether each package and its including packages (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=119161)
- // are actual packages
- addNames(pkgName, isPackageCache);
- } else {
- if (existing instanceof PackageFragmentRoot) {
- fragmentsCache.put(pkgName, new IPackageFragmentRoot[] {(PackageFragmentRoot) existing, root});
- } else {
- IPackageFragmentRoot[] entry= (IPackageFragmentRoot[]) existing;
- IPackageFragmentRoot[] copy= new IPackageFragmentRoot[entry.length + 1];
- System.arraycopy(entry, 0, copy, 0, entry.length);
- copy[entry.length]= root;
- fragmentsCache.put(pkgName, copy);
- }
- }
- }
- }
- cache = new LookupCache(rootsInScope, fragmentsCache, isPackageCache, reverseMap);
-
-
- return cache;
- }
-
- public static void addNames(String[] name, HashtableOfArrayToObject set) {
- set.put(name, name);
- int length = name.length;
- for (int i = length-1; i > 0; i--) {
- String[] superName = new String[i];
- System.arraycopy(name, 0, superName, 0, i);
- set.put(superName, superName);
- }
- }
-
-}
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
deleted file mode 100644
index 15d686a8..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/Member.java
+++ /dev/null
@@ -1,396 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IBuffer;
-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.IMember;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-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.ToolFactory;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.compiler.IScanner;
-import org.eclipse.wst.jsdt.core.compiler.ITerminalSymbols;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.internal.compiler.impl.Constant;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeIds;
-import org.eclipse.wst.jsdt.internal.core.util.MementoTokenizer;
-
-/**
- * @see IMember
- */
-
-public abstract class Member extends SourceRefElement implements IMember {
-
-protected Member(JavaElement parent) {
- super(parent);
-}
-protected static boolean areSimilarMethods(
- String name1, String[] params1,
- String name2, String[] params2,
- String[] simpleNames1) {
-
- if (name1.equals(name2)) {
- int params1Length = params1.length;
- if (params1Length == params2.length) {
- for (int i = 0; i < params1Length; i++) {
- String simpleName1 =
- simpleNames1 == null ?
- Signature.getSimpleName(Signature.toString(params1[i])) :
- simpleNames1[i];
- String simpleName2 = Signature.getSimpleName(Signature.toString(params2[i]));
- if (!simpleName1.equals(simpleName2)) {
- return false;
- }
- }
- return true;
- }
- }
- return false;
-}
-/**
- * Converts a field constant from the compiler's representation
- * to the Java Model constant representation (Number or String).
- */
-protected static Object convertConstant(Constant constant) {
- if (constant == null)
- return null;
- if (constant == Constant.NotAConstant) {
- return null;
- }
- switch (constant.typeID()) {
- case TypeIds.T_boolean :
- return constant.booleanValue() ? Boolean.TRUE : Boolean.FALSE;
- case TypeIds.T_char :
- return new Character(constant.charValue());
- case TypeIds.T_double :
- return new Double(constant.doubleValue());
- case TypeIds.T_float :
- return new Float(constant.floatValue());
- case TypeIds.T_int :
- return new Integer(constant.intValue());
- case TypeIds.T_long :
- return new Long(constant.longValue());
- case TypeIds.T_short :
- return new Short(constant.shortValue());
- case TypeIds.T_JavaLangString :
- return constant.stringValue();
- default :
- return null;
- }
-}
-/*
- * Helper method for SourceType.findMethods and BinaryType.findMethods
- */
-public static IFunction[] findMethods(IFunction method, IFunction[] methods) {
- String elementName = method.getElementName();
- String[] parameters = method.getParameterTypes();
- int paramLength = parameters.length;
- String[] simpleNames = new String[paramLength];
- for (int i = 0; i < paramLength; i++) {
- String erasure = parameters[i];
- simpleNames[i] = Signature.getSimpleName(Signature.toString(erasure));
- }
- ArrayList list = new ArrayList();
- for (int i = 0, length = methods.length; i < length; i++) {
- IFunction existingMethod = methods[i];
- if (areSimilarMethods(
- elementName,
- parameters,
- existingMethod.getElementName(),
- existingMethod.getParameterTypes(),
- simpleNames)) {
- list.add(existingMethod);
- }
- }
- int size = list.size();
- if (size == 0) {
- return null;
- } else {
- IFunction[] result = new IFunction[size];
- list.toArray(result);
- return result;
- }
-}
-public String[] getCategories() throws JavaScriptModelException {
- IType type = (IType) getAncestor(IJavaScriptElement.TYPE);
- if (type == null) return CharOperation.NO_STRINGS;
- if (type.isBinary()) {
- return CharOperation.NO_STRINGS;
- } else {
- SourceTypeElementInfo info = (SourceTypeElementInfo) ((SourceType) type).getElementInfo();
- HashMap map = info.getCategories();
- if (map == null) return CharOperation.NO_STRINGS;
- String[] categories = (String[]) map.get(this);
- if (categories == null) return CharOperation.NO_STRINGS;
- return categories;
- }
-}
-/**
- * @see IMember
- */
-public IClassFile getClassFile() {
- IJavaScriptElement element = getParent();
- while (element instanceof IMember) {
- element= element.getParent();
- }
- if (element instanceof IClassFile) {
- return (IClassFile) element;
- }
- return null;
-}
-/**
- * @see IMember
- */
-public IType getDeclaringType() {
- JavaElement parentElement = (JavaElement)getParent();
- if (parentElement.getElementType() == TYPE) {
- return (IType) parentElement;
- }
- return null;
-}
-/**
- * @see IMember
- */
-public int getFlags() throws JavaScriptModelException {
- MemberElementInfo info = (MemberElementInfo) getElementInfo();
- return info.getModifiers();
-}
-/*
- * @see JavaElement
- */
-public IJavaScriptElement getHandleFromMemento(String token, MementoTokenizer memento, WorkingCopyOwner workingCopyOwner) {
- switch (token.charAt(0)) {
- case JEM_COUNT:
- return getHandleUpdatingCountFromMemento(memento, workingCopyOwner);
- 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;
- }
- JavaElement type = (JavaElement)getType(typeName, 1);
- if (token == null) {
- return type.getHandleFromMemento(memento, workingCopyOwner);
- } else {
- return type.getHandleFromMemento(token, 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);
- }
- return null;
-}
-/**
- * @see JavaElement#getHandleMemento()
- */
-protected char getHandleMementoDelimiter() {
- return JavaElement.JEM_TYPE;
-}
-/*
- * Returns the outermost context defining a local element. Per construction, it can only be a
- * method/field/initializarer member; thus, returns null if this member is already a top-level type or member type.
- * e.g for X.js/X/Y/foo()/Z/bar()/T, it will return X.js/X/Y/foo()
- */
-public Member getOuterMostLocalContext() {
- IJavaScriptElement current = this;
- Member lastLocalContext = null;
- parentLoop: while (true) {
- switch (current.getElementType()) {
- case CLASS_FILE:
- case JAVASCRIPT_UNIT:
- break parentLoop; // done recursing
- case TYPE:
- // cannot be a local context
- break;
- case INITIALIZER:
- case FIELD:
- case METHOD:
- // these elements can define local members
- lastLocalContext = (Member) current;
- break;
- }
- current = current.getParent();
- }
- return lastLocalContext;
-}
-public ISourceRange getJSdocRange() throws JavaScriptModelException {
- ISourceRange range= this.getSourceRange();
- if (range == null) return null;
- IBuffer buf= null;
- if (this.isBinary()) {
- buf = this.getClassFile().getBuffer();
- } else {
- IJavaScriptUnit compilationUnit = this.getJavaScriptUnit();
- if (!compilationUnit.isConsistent()) {
- return null;
- }
- buf = compilationUnit.getBuffer();
- }
- final int start= range.getOffset();
- final int length= range.getLength();
- if (length > 0 && buf.getChar(start) == '/') {
- IScanner scanner= ToolFactory.createScanner(true, false, false, false);
- scanner.setSource(buf.getText(start, length).toCharArray());
- try {
- int docOffset= -1;
- int docEnd= -1;
-
- int terminal= scanner.getNextToken();
- loop: while (true) {
- switch(terminal) {
- case ITerminalSymbols.TokenNameCOMMENT_JAVADOC :
- docOffset= scanner.getCurrentTokenStartPosition();
- docEnd= scanner.getCurrentTokenEndPosition() + 1;
- terminal= scanner.getNextToken();
- break;
- case ITerminalSymbols.TokenNameCOMMENT_LINE :
- case ITerminalSymbols.TokenNameCOMMENT_BLOCK :
- terminal= scanner.getNextToken();
- continue loop;
- default :
- break loop;
- }
- }
- if (docOffset != -1) {
- return new SourceRange(docOffset + start, docEnd - docOffset + 1);
- }
- } catch (InvalidInputException ex) {
- // try if there is inherited Javadoc
- }
- }
- return null;
-}
-/**
- * @see IMember
- */
-public ISourceRange getNameRange() throws JavaScriptModelException {
- MemberElementInfo info= (MemberElementInfo)getElementInfo();
- return new SourceRange(info.getNameSourceStart(), info.getNameSourceEnd() - info.getNameSourceStart() + 1);
-}
-/**
- * @see IMember
- */
-public IType getType(String typeName, int count) {
- if (isBinary()) {
- throw new IllegalArgumentException("Not a source member " + toStringWithAncestors()); //$NON-NLS-1$
- } else {
- SourceType type = new SourceType(this, typeName);
- type.occurrenceCount = count;
- return type;
- }
-}
-/**
- * @see IMember#getTypeRoot()
- */
-public ITypeRoot getTypeRoot() {
- IJavaScriptElement element = getParent();
- while (element instanceof IMember) {
- element= element.getParent();
- }
- return (ITypeRoot) element;
-}
-/**
- * @see IMember
- */
-public boolean isBinary() {
- if (getClassFile()!=null)
- return true;
- return false;
-}
-protected boolean isMainMethod(IFunction method) throws JavaScriptModelException {
- if ("main".equals(method.getElementName()) && Signature.SIG_VOID.equals(method.getReturnType())) { //$NON-NLS-1$
- int flags= method.getFlags();
- if (Flags.isStatic(flags) && Flags.isPublic(flags)) {
- String[] paramTypes= method.getParameterTypes();
- if (paramTypes.length == 1) {
- String typeSignature= Signature.toString(paramTypes[0]);
- return "String[]".equals(Signature.getSimpleName(typeSignature)); //$NON-NLS-1$
- }
- }
- }
- return false;
-}
-/**
- * @see IJavaScriptElement
- */
-public boolean isReadOnly() {
- return getClassFile() != null;
-}
-/**
- */
-public String readableName() {
-
- IJavaScriptElement declaringType = getDeclaringType();
- if (declaringType != null) {
- String declaringName = ((JavaElement) getDeclaringType()).readableName();
- StringBuffer buffer = new StringBuffer(declaringName);
- buffer.append('.');
- buffer.append(this.getElementName());
- return buffer.toString();
- } else {
- return super.readableName();
- }
-}
-/**
- * Updates the name range for this element.
- */
-protected void updateNameRange(int nameStart, int nameEnd) {
- try {
- MemberElementInfo info = (MemberElementInfo) getElementInfo();
- info.setNameSourceStart(nameStart);
- info.setNameSourceEnd(nameEnd);
- } catch (JavaScriptModelException npe) {
- return;
- }
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/MemberElementInfo.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/MemberElementInfo.java
deleted file mode 100644
index c865dca3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/MemberElementInfo.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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 IMember elements.
- */
-/* package */ abstract class MemberElementInfo extends SourceRefElementInfo {
- /**
- * The modifiers associated with this member.
- *
- * @see org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants
- */
- protected int flags;
-
- /**
- * The start position of this member's name in the its
- * openable's buffer.
- */
- protected int nameStart= -1;
-
- /**
- * The last position of this member's name in the its
- * openable's buffer.
- */
- protected int nameEnd= -1;
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.env.IGenericType#getModifiers()
- * @see org.eclipse.wst.jsdt.internal.compiler.env.IGenericMethod#getModifiers()
- * @see org.eclipse.wst.jsdt.internal.compiler.env.IGenericField#getModifiers()
- */
- public int getModifiers() {
- return this.flags;
- }
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.env.ISourceType#getNameSourceEnd()
- * @see org.eclipse.wst.jsdt.internal.compiler.env.ISourceMethod#getNameSourceEnd()
- * @see org.eclipse.wst.jsdt.internal.compiler.env.ISourceField#getNameSourceEnd()
- */
- public int getNameSourceEnd() {
- return this.nameEnd;
- }
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.env.ISourceType#getNameSourceStart()
- * @see org.eclipse.wst.jsdt.internal.compiler.env.ISourceMethod#getNameSourceStart()
- * @see org.eclipse.wst.jsdt.internal.compiler.env.ISourceField#getNameSourceStart()
- */
- public int getNameSourceStart() {
- return this.nameStart;
- }
- protected void setFlags(int flags) {
- this.flags = flags;
- }
- /**
- * Sets the last position of this member's name, relative
- * to its openable's source buffer.
- */
- protected void setNameSourceEnd(int end) {
- this.nameEnd= end;
- }
- /**
- * Sets the start position of this member's name, relative
- * to its openable's source buffer.
- */
- protected void setNameSourceStart(int start) {
- this.nameStart= start;
- }
-}
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
deleted file mode 100644
index 0b4cf622..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/MetadataFile.java
+++ /dev/null
@@ -1,393 +0,0 @@
-/*******************************************************************************
- * 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.internal.core;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Map;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-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.CompletionRequestor;
-import org.eclipse.wst.jsdt.core.IBuffer;
-import org.eclipse.wst.jsdt.core.IBufferFactory;
-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.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IProblemRequestor;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.internal.core.util.MementoTokenizer;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-import org.eclipse.wst.jsdt.internal.oaametadata.ClassData;
-import org.eclipse.wst.jsdt.internal.oaametadata.DocumentedElement;
-import org.eclipse.wst.jsdt.internal.oaametadata.LibraryAPIs;
-import org.eclipse.wst.jsdt.internal.oaametadata.MetadataReader;
-import org.eclipse.wst.jsdt.internal.oaametadata.MetadataSourceElementNotifier;
-import org.xml.sax.InputSource;
-
-public class MetadataFile extends Openable implements
- IClassFile, org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit, IVirtualParent
- {
-
- protected String name;
- protected IPath filePath;
- private static final IField[] NO_FIELDS = new IField[0];
- private static final IFunction[] NO_METHODS = new IFunction[0];
- private LibraryAPIs apis=null;
- protected BinaryType binaryType = null;
-
-
- protected MetadataFile(PackageFragment parent, String path) {
- super(parent);
- this.filePath = Path.fromOSString(path);
- if (filePath.getFileExtension()!=null)
- {
- String lastSegment = filePath.lastSegment();
- this.name=lastSegment.substring(0,lastSegment.length()-(filePath.getFileExtension().length()+1));
- }
- else
- this.name=path;
- }
-
- protected boolean buildStructure(OpenableElementInfo info,
- IProgressMonitor pm, Map newElements, IResource underlyingResource)
- throws JavaScriptModelException {
- if (underlyingResource != null && !underlyingResource.isAccessible()) {
- throw newNotPresentException();
- }
-
-
-
- CompilationUnitElementInfo unitInfo = new CompilationUnitElementInfo();
-
- // get buffer contents
-
- // generate structure and compute syntax problems if needed
- CompilationUnitStructureRequestor requestor = new CompilationUnitStructureRequestor(this, unitInfo, newElements);
-
- boolean createAST;
-// HashMap problems;
- if (info instanceof ASTHolderCUInfo) {
- ASTHolderCUInfo astHolder = (ASTHolderCUInfo) info;
- createAST = astHolder.astLevel != IJavaScriptUnit.NO_AST;
-// problems = astHolder.problems;
- } else {
- createAST = false;
-// problems = null;
- }
-
-
- new MetadataSourceElementNotifier(getAPIs(),requestor).notifyRequestor();
-
-
-
- // 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;
- info.setChildren(unitInfo.children);
- try {
-
- if (createAST) {
-// int astLevel = ((ASTHolderCUInfo) info).astLevel;
-// org.eclipse.wst.jsdt.core.dom.JavaScriptUnit cu = AST.convertCompilationUnit(astLevel, unit, contents, options, computeProblems, this, pm);
-// ((ASTHolderCUInfo) info).ast = cu;
- throw new RuntimeException("Implement this"); //$NON-NLS-1$
- }
- } finally {
-
- }
-
- return true;
-
- }
-
- public LibraryAPIs getAPIs()
- {
- if (apis==null)
- {
- IFile file = (IFile) getResource();
- try {
- apis = MetadataReader.readAPIsFromStream(new InputSource(file.getContents()),file.getLocation().toOSString());
- apis.fileName=file.getFullPath().toPortableString().toCharArray();
- } catch (Exception e) {
- Util.log(e, "error reading metadata");
- apis=new LibraryAPIs();
- apis.fileName=file.getFullPath().toPortableString().toCharArray();
- }
- }
- return apis;
- }
-
- public IJavaScriptElement getHandleFromMemento(String token,
- MementoTokenizer memento, WorkingCopyOwner owner) {
- switch (token.charAt(0)) {
- case JEM_TYPE:
- if (!memento.hasMoreTokens()) return this;
- String typeName = memento.nextToken();
- JavaElement type = new BinaryType(this, typeName);
- return type.getHandleFromMemento(memento, owner);
- }
- return null;
- }
-
- protected char getHandleMementoDelimiter() {
- return JavaElement.JEM_METADATA;
-
- }
-
- public IJavaScriptUnit becomeWorkingCopy(
- IProblemRequestor problemRequestor, WorkingCopyOwner owner,
- IProgressMonitor monitor) throws JavaScriptModelException {
- return null;
- }
-
- public byte[] getBytes() throws JavaScriptModelException {
- IFile file = (IFile) getResource();
- return Util.getResourceContentsAsByteArray(file);
- }
-
- public IType getType() {
- if (this.binaryType == null) {
- this.binaryType = new BinaryType(this, getTypeName());
- }
- return this.binaryType;
- }
-
- public IType[] getTypes() throws JavaScriptModelException {
- ArrayList list = getChildrenOfType(TYPE);
- IType[] array= new IType[list.size()];
- list.toArray(array);
- return array;
- }
-
- public IJavaScriptElement getWorkingCopy(IProgressMonitor monitor,
- IBufferFactory factory) throws JavaScriptModelException {
- return null;
- }
-
- public boolean isClass() throws JavaScriptModelException {
- return true;
- }
-
- public boolean isInterface() throws JavaScriptModelException {
- return false;
- }
-
- public IType findPrimaryType() {
- return null;
- }
-
- public IJavaScriptElement getElementAt(int position) throws JavaScriptModelException {
- return null;
- }
-
- public IJavaScriptUnit getWorkingCopy(WorkingCopyOwner owner,
- IProgressMonitor monitor) throws JavaScriptModelException {
- return null;
- }
-
- public int getElementType() {
- return CLASS_FILE;
- }
-
- public IPath getPath() {
- return this.filePath;
- }
-
- public IResource getResource() {
- return ((IContainer)this.getParent().getResource()).getFile(new Path(this.getElementName()));
- }
-
- public String getSource() throws JavaScriptModelException {
- IBuffer buffer = super.getBuffer();
- if (buffer == null) {
- return null;
- }
- return buffer.getContents();
- }
-
- public ISourceRange getSourceRange() throws JavaScriptModelException {
- return null;
- }
-
- public void codeComplete(int offset, CompletionRequestor requestor)
- throws JavaScriptModelException {
-
- }
-
- public void codeComplete(int offset, CompletionRequestor requestor,
- WorkingCopyOwner owner) throws JavaScriptModelException {
-
- }
-
- public IJavaScriptElement[] codeSelect(int offset, int length)
- throws JavaScriptModelException {
- return null;
- }
-
- public IJavaScriptElement[] codeSelect(int offset, int length,
- WorkingCopyOwner owner) throws JavaScriptModelException {
- return null;
- }
-
- public IField getField(String fieldName) {
- return new SourceField(this, fieldName);
- }
-
- public IField[] getFields() throws JavaScriptModelException {
- ArrayList list = getChildrenOfType(FIELD);
- int size;
- if ((size = list.size()) == 0) {
- return NO_FIELDS;
- } else {
- IField[] array= new IField[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);
- int size;
- if ((size = list.size()) == 0) {
- return NO_METHODS;
- } else {
- IFunction[] array= new IFunction[size];
- list.toArray(array);
- return array;
- }
- }
-
- public IType getType(String typeName) {
- return new SourceType(this, typeName);
- }
-
- public char[] getContents() {
- char [] chars=null;
- try {
- chars=org.eclipse.wst.jsdt.internal.compiler.util.Util.getFileCharContent(new File(filePath.toOSString()),null);
- } catch (IOException e) {
- e.printStackTrace();
- }
- return chars;
- }
-
- public String getInferenceID() {
- return null;
- }
-
- public char[] getMainTypeName() {
- return null;
- }
-
- public char[][] getPackageName() {
- return new char[][] {getParent().getElementName().toCharArray()};
- }
-
- public char[] getFileName() {
- return this.filePath!=null?this.filePath.toString().toCharArray():getElementName().toCharArray();
- }
-
- public JsGlobalScopeContainerInitializer getContainerInitializer() {
- JsGlobalScopeContainerInitializer init = ((IVirtualParent)parent).getContainerInitializer();
- return init;
- }
-
- public String getElementName() {
- return filePath.lastSegment();
- }
-
-
- protected boolean resourceExists() {
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- if (workspace == null) return false; // workaround for http://bugs.eclipse.org/bugs/show_bug.cgi?id=34069
- Object me = JavaModel.getTarget(workspace.getRoot(), this.getPath(), true) ;
- if(me!=null) return true;
- me = JavaModel.getTarget(workspace.getRoot(), this.getPath().makeRelative(), true);
- return (me!=null);
-
- }
-
- public DocumentedElement getDocumentation(IMember member)
- {
- IJavaScriptElement parent = member.getParent();
- String elementName = member.getElementName();
- LibraryAPIs apis = getAPIs();
- switch (member.getElementType()) {
- case IJavaScriptElement.TYPE:
- return apis.getClass(elementName);
-
- case IJavaScriptElement.METHOD:
- if (parent.equals(this))
- return apis.getGlobalMethod(elementName);
- ClassData clazz = apis.getClass(parent.getElementName());
- if (clazz!=null)
- return clazz.getMethod(elementName);
- return null;
-
- case IJavaScriptElement.FIELD:
- if (parent.equals(this))
- return apis.getGlobalVar(elementName);
- clazz = apis.getClass(parent.getElementName());
- if (clazz!=null)
- return clazz.getField(elementName);
- return null;
-
- }
- return null;
- }
-
- 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;
- }
-
- public boolean equals(Object o) {
- if (!(o instanceof MetadataFile)) return false;
- MetadataFile other = (MetadataFile) o;
- return this.name.equals(other.name) && this.parent.equals(other.parent);
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ModelUpdater.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ModelUpdater.java
deleted file mode 100644
index c4fcb70c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ModelUpdater.java
+++ /dev/null
@@ -1,248 +0,0 @@
-/*******************************************************************************
- * 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 java.util.HashSet;
-import java.util.Iterator;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptElementDelta;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-
-/**
- * This class is used by <code>JavaModelManager</code> to update the JavaModel
- * based on some <code>IJavaScriptElementDelta</code>s.
- */
-public class ModelUpdater {
-
- HashSet projectsToUpdate = new HashSet();
-
- /**
- * Adds the given child handle to its parent's cache of children.
- */
- protected void addToParentInfo(Openable child) {
-
- Openable parent = (Openable) child.getParent();
- if (parent != null && parent.isOpen()) {
- try {
- JavaElementInfo info = (JavaElementInfo)parent.getElementInfo();
- info.addChild(child);
- } catch (JavaScriptModelException e) {
- // do nothing - we already checked if open
- }
- }
- }
-
- /**
- * Closes the given element, which removes it from the cache of open elements.
- */
- protected static void close(Openable element) {
-
- try {
- element.close();
- } catch (JavaScriptModelException e) {
- // do nothing
- }
- }
-
- /**
- * Processing for an element that has been added:<ul>
- * <li>If the element is a project, do nothing, and do not process
- * children, as when a project is created it does not yet have any
- * natures - specifically a java nature.
- * <li>If the elemet is not a project, process it as added (see
- * <code>basicElementAdded</code>.
- * </ul>
- */
- protected void elementAdded(Openable element) {
-
- int elementType = element.getElementType();
- if (elementType == IJavaScriptElement.JAVASCRIPT_PROJECT) {
- // project add is handled by JavaProject.configure() because
- // when a project is created, it does not yet have a java nature
- addToParentInfo(element);
- this.projectsToUpdate.add(element);
- } else {
- addToParentInfo(element);
-
- // Force the element to be closed as it might have been opened
- // before the resource modification came in and it might have a new child
- // For example, in an IWorkspaceRunnable:
- // 1. create a package fragment p using a java model operation
- // 2. open package p
- // 3. add file X.js in folder p
- // When the resource delta comes in, only the addition of p is notified,
- // but the package p is already opened, thus its children are not recomputed
- // and it appears empty.
- close(element);
- }
-
- switch (elementType) {
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT :
- // when a root is added, and is on the classpath, the project must be updated
- this.projectsToUpdate.add(element.getJavaScriptProject());
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT :
- // get rid of package fragment cache
- JavaProject project = (JavaProject) element.getJavaScriptProject();
- project.resetCaches();
- break;
- }
- }
-
- /**
- * Generic processing for elements with changed contents:<ul>
- * <li>The element is closed such that any subsequent accesses will re-open
- * the element reflecting its new structure.
- * </ul>
- */
- protected void elementChanged(Openable element) {
-
- close(element);
- }
-
- /**
- * Generic processing for a removed element:<ul>
- * <li>Close the element, removing its structure from the cache
- * <li>Remove the element from its parent's cache of children
- * <li>Add a REMOVED entry in the delta
- * </ul>
- */
- protected void elementRemoved(Openable element) {
-
- if (element.isOpen()) {
- close(element);
- }
- removeFromParentInfo(element);
- int elementType = element.getElementType();
-
- switch (elementType) {
- case IJavaScriptElement.JAVASCRIPT_MODEL :
- JavaModelManager.getJavaModelManager().getIndexManager().reset();
- break;
- case IJavaScriptElement.JAVASCRIPT_PROJECT :
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- JavaProject javaProject = (JavaProject) element;
- manager.removePerProjectInfo(javaProject);
- manager.containerRemove(javaProject);
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT :
- this.projectsToUpdate.add(element.getJavaScriptProject());
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT :
- // get rid of package fragment cache
- JavaProject project = (JavaProject) element.getJavaScriptProject();
- project.resetCaches();
- break;
- }
- }
-
- /**
- * Converts a <code>IResourceDelta</code> rooted in a <code>Workspace</code> into
- * the corresponding set of <code>IJavaScriptElementDelta</code>, rooted in the
- * relevant <code>JavaModel</code>s.
- */
- public void processJavaDelta(IJavaScriptElementDelta delta) {
-
-// if (DeltaProcessor.VERBOSE){
-// System.out.println("UPDATING Model with Delta: ["+Thread.currentThread()+":" + delta + "]:");
-// }
-
- try {
- this.traverseDelta(delta, null, null); // traverse delta
-
- // update package fragment roots of projects that were affected
- Iterator iterator = this.projectsToUpdate.iterator();
- while (iterator.hasNext()) {
- JavaProject project = (JavaProject) iterator.next();
- project.updatePackageFragmentRoots();
- }
- } finally {
- this.projectsToUpdate = new HashSet();
- }
- }
-
- /**
- * Removes the given element from its parents cache of children. If the
- * element does not have a parent, or the parent is not currently open,
- * this has no effect.
- */
- protected void removeFromParentInfo(Openable child) {
-
- Openable parent = (Openable) child.getParent();
- if (parent != null && parent.isOpen()) {
- try {
- JavaElementInfo info = (JavaElementInfo)parent.getElementInfo();
- info.removeChild(child);
- } catch (JavaScriptModelException e) {
- // do nothing - we already checked if open
- }
- }
- }
-
- /**
- * Converts an <code>IResourceDelta</code> and its children into
- * the corresponding <code>IJavaScriptElementDelta</code>s.
- * Return whether the delta corresponds to a resource on the classpath.
- * If it is not a resource on the classpath, it will be added as a non-java
- * resource by the sender of this method.
- */
- protected void traverseDelta(
- IJavaScriptElementDelta delta,
- IPackageFragmentRoot root,
- IJavaScriptProject project) {
-
- boolean processChildren = true;
-
- Openable element = (Openable) delta.getElement();
- switch (element.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_PROJECT :
- project = (IJavaScriptProject) element;
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT :
- root = (IPackageFragmentRoot) element;
- break;
- case IJavaScriptElement.JAVASCRIPT_UNIT :
- // filter out working copies that are not primary (we don't want to add/remove them to/from the package fragment
- CompilationUnit cu = (CompilationUnit)element;
- if (cu.isWorkingCopy() && !cu.isPrimary()) {
- return;
- }
- case IJavaScriptElement.CLASS_FILE :
- processChildren = false;
- break;
- }
-
- switch (delta.getKind()) {
- case IJavaScriptElementDelta.ADDED :
- elementAdded(element);
- break;
- case IJavaScriptElementDelta.REMOVED :
- elementRemoved(element);
- break;
- case IJavaScriptElementDelta.CHANGED :
- if ((delta.getFlags() & IJavaScriptElementDelta.F_CONTENT) != 0){
- elementChanged(element);
- }
- break;
- }
- if (processChildren) {
- IJavaScriptElementDelta[] children = delta.getAffectedChildren();
- for (int i = 0; i < children.length; i++) {
- IJavaScriptElementDelta childDelta = children[i];
- this.traverseDelta(childDelta, root, project);
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/MoveElementsOperation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/MoveElementsOperation.java
deleted file mode 100644
index 47a55b31..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/MoveElementsOperation.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*******************************************************************************
- * 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.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-
-/**
- * This operation moves elements from their current
- * container to a specified destination container, optionally renaming the
- * elements.
- * A move operation is equivalent to a copy operation, where
- * the source elements are deleted after the copy.
- * <p>This operation can be used for reorganizing elements within the same container.
- *
- * @see CopyElementsOperation
- */
-public class MoveElementsOperation extends CopyElementsOperation {
-/**
- * When executed, this operation will move the given elements to the given containers.
- */
-public MoveElementsOperation(IJavaScriptElement[] elementsToMove, IJavaScriptElement[] destContainers, boolean force) {
- super(elementsToMove, destContainers, force);
-}
-/**
- * Returns the <code>String</code> to use as the main task name
- * for progress monitoring.
- */
-protected String getMainTaskName() {
- return Messages.operation_moveElementProgress;
-}
-/**
- * @see CopyElementsOperation#isMove()
- */
-protected boolean isMove() {
- return true;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/MovePackageFragmentRootOperation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/MovePackageFragmentRootOperation.java
deleted file mode 100644
index c2de7df5..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/MovePackageFragmentRootOperation.java
+++ /dev/null
@@ -1,283 +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;
-
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceProxy;
-import org.eclipse.core.resources.IResourceProxyVisitor;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatus;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptConventions;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-
-public class MovePackageFragmentRootOperation extends CopyPackageFragmentRootOperation {
- /*
- * Renames the classpath entries equal to the given path in the given project.
- * If an entry with the destination path already existed, remove it.
- */
- protected void renameEntryInClasspath(IPath rootPath, IJavaScriptProject project) throws JavaScriptModelException {
-
- IIncludePathEntry[] classpath = project.getRawIncludepath();
- IIncludePathEntry[] newClasspath = null;
- int cpLength = classpath.length;
- int newCPIndex = -1;
-
- for (int i = 0; i < cpLength; i++) {
- IIncludePathEntry entry = classpath[i];
- IPath entryPath = entry.getPath();
- if (rootPath.equals(entryPath)) {
- // rename entry
- if (newClasspath == null) {
- newClasspath = new IIncludePathEntry[cpLength];
- System.arraycopy(classpath, 0, newClasspath, 0, i);
- newCPIndex = i;
- }
- newClasspath[newCPIndex++] = copy(entry);
- } else if (this.destination.equals(entryPath)) {
- // remove entry equals to destination
- if (newClasspath == null) {
- newClasspath = new IIncludePathEntry[cpLength];
- System.arraycopy(classpath, 0, newClasspath, 0, i);
- newCPIndex = i;
- }
- } else if (entry.getEntryKind() == IIncludePathEntry.CPE_SOURCE) {
- // update exclusion/inclusion patterns
- IPath projectRelativePath = rootPath.removeFirstSegments(1);
- IPath[] newExclusionPatterns = renamePatterns(projectRelativePath, entry.getExclusionPatterns());
- IPath[] newInclusionPatterns = renamePatterns(projectRelativePath, entry.getInclusionPatterns());
- if (newExclusionPatterns != null || newInclusionPatterns != null) {
- if (newClasspath == null) {
- newClasspath = new IIncludePathEntry[cpLength];
- System.arraycopy(classpath, 0, newClasspath, 0, i);
- newCPIndex = i;
- }
- newClasspath[newCPIndex++] =
- JavaScriptCore.newSourceEntry(
- entry.getPath(),
- newInclusionPatterns == null ? entry.getInclusionPatterns() : newInclusionPatterns,
- newExclusionPatterns == null ? entry.getExclusionPatterns() : newExclusionPatterns,
- null,
- entry.getExtraAttributes());
- } else if (newClasspath != null) {
- newClasspath[newCPIndex++] = entry;
- }
- } else if (newClasspath != null) {
- newClasspath[newCPIndex++] = entry;
- }
- }
-
- if (newClasspath != null) {
- if (newCPIndex < newClasspath.length) {
- System.arraycopy(newClasspath, 0, newClasspath = new IIncludePathEntry[newCPIndex], 0, newCPIndex);
- }
- IJavaScriptModelStatus status = JavaScriptConventions.validateClasspath(project, newClasspath);
- if (status.isOK())
- project.setRawIncludepath(newClasspath, progressMonitor);
- // don't update classpath if status is not ok to avoid JavaScriptModelException (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=129991)
- }
- }
-
- private IPath[] renamePatterns(IPath rootPath, IPath[] patterns) {
- IPath[] newPatterns = null;
- int newPatternsIndex = -1;
- for (int i = 0, length = patterns.length; i < length; i++) {
- IPath pattern = patterns[i];
- if (pattern.equals(rootPath)) {
- if (newPatterns == null) {
- newPatterns = new IPath[length];
- System.arraycopy(patterns, 0, newPatterns, 0, i);
- newPatternsIndex = i;
- }
- IPath newPattern = this.destination.removeFirstSegments(1);
- if (pattern.hasTrailingSeparator())
- newPattern = newPattern.addTrailingSeparator();
- newPatterns[newPatternsIndex++] = newPattern;
- }
- }
- return newPatterns;
- }
-
- public MovePackageFragmentRootOperation(
- IPackageFragmentRoot root,
- IPath destination,
- int updateResourceFlags,
- int updateModelFlags,
- IIncludePathEntry sibling) {
-
- super(
- root,
- destination,
- updateResourceFlags,
- updateModelFlags,
- sibling);
- }
- protected void executeOperation() throws JavaScriptModelException {
-
- IPackageFragmentRoot root = (IPackageFragmentRoot)this.getElementToProcess();
- IIncludePathEntry rootEntry = root.getRawIncludepathEntry();
- IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
-
- // move resource
- if (!root.isExternal() && (this.updateModelFlags & IPackageFragmentRoot.NO_RESOURCE_MODIFICATION) == 0) {
- moveResource(root, rootEntry, workspaceRoot);
- }
-
- // update refering projects classpath excluding orignating project
- IJavaScriptProject originatingProject = root.getJavaScriptProject();
- if ((this.updateModelFlags & IPackageFragmentRoot.OTHER_REFERRING_PROJECTS_INCLUDEPATH) != 0) {
- updateReferringProjectClasspaths(rootEntry.getPath(), originatingProject);
- }
-
- boolean isRename = this.destination.segment(0).equals(originatingProject.getElementName());
- boolean updateOriginating = (this.updateModelFlags & IPackageFragmentRoot.ORIGINATING_PROJECT_INCLUDEPATH) != 0;
- boolean updateDestination = (this.updateModelFlags & IPackageFragmentRoot.DESTINATION_PROJECT_INCLUDEPATH) != 0;
-
- // update originating classpath
- if (updateOriginating) {
- if (isRename && updateDestination) {
- renameEntryInClasspath(rootEntry.getPath(), originatingProject);
- } else {
- removeEntryFromClasspath(rootEntry.getPath(), originatingProject);
- }
- }
-
- // update destination classpath
- if (updateDestination) {
- if (!isRename || !updateOriginating) {
- addEntryToClasspath(rootEntry, workspaceRoot);
- } // else reference has been updated when updating originating project classpath
- }
- }
- protected void moveResource(
- IPackageFragmentRoot root,
- IIncludePathEntry rootEntry,
- final IWorkspaceRoot workspaceRoot)
- throws JavaScriptModelException {
-
- final char[][] exclusionPatterns = ((ClasspathEntry)rootEntry).fullExclusionPatternChars();
- IResource rootResource = root.getResource();
- if (rootEntry.getEntryKind() != IIncludePathEntry.CPE_SOURCE || exclusionPatterns == null) {
- try {
- IResource destRes;
- if ((this.updateModelFlags & IPackageFragmentRoot.REPLACE) != 0
- && (destRes = workspaceRoot.findMember(this.destination)) != null) {
- destRes.delete(this.updateResourceFlags, progressMonitor);
- }
- rootResource.move(this.destination, this.updateResourceFlags, progressMonitor);
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- }
- } else {
- final int sourceSegmentCount = rootEntry.getPath().segmentCount();
- final IFolder destFolder = workspaceRoot.getFolder(this.destination);
- final IPath[] nestedFolders = getNestedFolders(root);
- IResourceProxyVisitor visitor = new IResourceProxyVisitor() {
- public boolean visit(IResourceProxy proxy) throws CoreException {
- if (proxy.getType() == IResource.FOLDER) {
- IPath path = proxy.requestFullPath();
- if (prefixesOneOf(path, nestedFolders)) {
- if (equalsOneOf(path, nestedFolders)) {
- // nested source folder
- return false;
- } else {
- // folder containing nested source folder
- IFolder folder = destFolder.getFolder(path.removeFirstSegments(sourceSegmentCount));
- if ((updateModelFlags & IPackageFragmentRoot.REPLACE) != 0
- && folder.exists()) {
- return true;
- }
- folder.create(updateResourceFlags, true, progressMonitor);
- return true;
- }
- } else {
- // subtree doesn't contain any nested source folders
- IPath destPath = destination.append(path.removeFirstSegments(sourceSegmentCount));
- IResource destRes;
- if ((updateModelFlags & IPackageFragmentRoot.REPLACE) != 0
- && (destRes = workspaceRoot.findMember(destPath)) != null) {
- destRes.delete(updateResourceFlags, progressMonitor);
- }
- proxy.requestResource().move(destPath, updateResourceFlags, progressMonitor);
- return false;
- }
- } else {
- IPath path = proxy.requestFullPath();
- IPath destPath = destination.append(path.removeFirstSegments(sourceSegmentCount));
- IResource destRes;
- if ((updateModelFlags & IPackageFragmentRoot.REPLACE) != 0
- && (destRes = workspaceRoot.findMember(destPath)) != null) {
- destRes.delete(updateResourceFlags, progressMonitor);
- }
- proxy.requestResource().move(destPath, updateResourceFlags, progressMonitor);
- return false;
- }
- }
- };
- try {
- rootResource.accept(visitor, IResource.NONE);
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- }
- }
- setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
- }
- /*
- * Renames the classpath entries equal to the given path in all Java projects.
- */
- protected void updateReferringProjectClasspaths(IPath rootPath, IJavaScriptProject projectOfRoot) throws JavaScriptModelException {
- IJavaScriptModel model = this.getJavaModel();
- IJavaScriptProject[] projects = model.getJavaScriptProjects();
- for (int i = 0, length = projects.length; i < length; i++) {
- IJavaScriptProject project = projects[i];
- if (project.equals(projectOfRoot)) continue;
- renameEntryInClasspath(rootPath, project);
- }
- }
- /*
- * Removes the classpath entry equal to the given path from the given project's classpath.
- */
- protected void removeEntryFromClasspath(IPath rootPath, IJavaScriptProject project) throws JavaScriptModelException {
-
- IIncludePathEntry[] classpath = project.getRawIncludepath();
- IIncludePathEntry[] newClasspath = null;
- int cpLength = classpath.length;
- int newCPIndex = -1;
-
- for (int i = 0; i < cpLength; i++) {
- IIncludePathEntry entry = classpath[i];
- if (rootPath.equals(entry.getPath())) {
- if (newClasspath == null) {
- newClasspath = new IIncludePathEntry[cpLength];
- System.arraycopy(classpath, 0, newClasspath, 0, i);
- newCPIndex = i;
- }
- } else if (newClasspath != null) {
- newClasspath[newCPIndex++] = entry;
- }
- }
-
- if (newClasspath != null) {
- if (newCPIndex < newClasspath.length) {
- System.arraycopy(newClasspath, 0, newClasspath = new IIncludePathEntry[newCPIndex], 0, newCPIndex);
- }
- project.setRawIncludepath(newClasspath, progressMonitor);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/MoveResourceElementsOperation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/MoveResourceElementsOperation.java
deleted file mode 100644
index b370ff4b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/MoveResourceElementsOperation.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*******************************************************************************
- * 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.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-
-/**
- * This operation moves resources (package fragments and compilation units) from their current
- * container to a specified destination container, optionally renaming the
- * elements.
- * A move resource operation is equivalent to a copy resource operation, where
- * the source resources are deleted after the copy.
- * <p>This operation can be used for reorganizing resources within the same container.
- *
- * @see CopyResourceElementsOperation
- */
-public class MoveResourceElementsOperation extends CopyResourceElementsOperation {
-/**
- * When executed, this operation will move the given elements to the given containers.
- */
-public MoveResourceElementsOperation(IJavaScriptElement[] elementsToMove, IJavaScriptElement[] destContainers, boolean force) {
- super(elementsToMove, destContainers, force);
-}
-/**
- * @see MultiOperation
- */
-protected String getMainTaskName() {
- return Messages.operation_moveResourceProgress;
-}
-/**
- * @see CopyResourceElementsOperation#isMove()
- */
-protected boolean isMove() {
- return true;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/MultiOperation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/MultiOperation.java
deleted file mode 100644
index f82b2f71..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/MultiOperation.java
+++ /dev/null
@@ -1,317 +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;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.core.runtime.IStatus;
-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.IFunction;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.JavaScriptConventions;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-
-/**
- * This class is used to perform operations on multiple <code>IJavaScriptElement</code>.
- * It is responible for running each operation in turn, collecting
- * the errors and merging the corresponding <code>JavaElementDelta</code>s.
- * <p>
- * If several errors occured, they are collected in a multi-status
- * <code>JavaModelStatus</code>. Otherwise, a simple <code>JavaModelStatus</code>
- * is thrown.
- */
-public abstract class MultiOperation extends JavaModelOperation {
- /**
- * Table specifying insertion positions for elements being
- * copied/moved/renamed. Keyed by elements being processed, and
- * values are the corresponding insertion point.
- * @see #processElements()
- */
- protected Map insertBeforeElements = new HashMap(1);
- /**
- * Table specifying the new parent for elements being
- * copied/moved/renamed.
- * Keyed by elements being processed, and
- * values are the corresponding destination parent.
- */
- protected Map newParents;
- /**
- * This table presents the data in <code>fRenamingList</code> in a more
- * convenient way.
- */
- protected Map renamings;
- /**
- * The list of renamings supplied to the operation
- */
- protected String[] renamingsList = null;
- /**
- * Creates a new <code>MultiOperation</code> on <code>elementsToProcess</code>.
- */
- protected MultiOperation(IJavaScriptElement[] elementsToProcess, boolean force) {
- super(elementsToProcess, force);
- }
- /**
- * Creates a new <code>MultiOperation</code>.
- */
- protected MultiOperation(IJavaScriptElement[] elementsToProcess, IJavaScriptElement[] parentElements, boolean force) {
- super(elementsToProcess, parentElements, force);
- this.newParents = new HashMap(elementsToProcess.length);
- if (elementsToProcess.length == parentElements.length) {
- for (int i = 0; i < elementsToProcess.length; i++) {
- this.newParents.put(elementsToProcess[i], parentElements[i]);
- }
- } else { //same destination for all elements to be moved/copied/renamed
- for (int i = 0; i < elementsToProcess.length; i++) {
- this.newParents.put(elementsToProcess[i], parentElements[0]);
- }
- }
-
- }
- /**
- * Convenience method to create a <code>JavaScriptModelException</code>
- * embending a <code>JavaModelStatus</code>.
- */
- protected void error(int code, IJavaScriptElement element) throws JavaScriptModelException {
- throw new JavaScriptModelException(new JavaModelStatus(code, element));
- }
- /**
- * Executes the operation.
- *
- * @exception JavaScriptModelException if one or several errors occured during the operation.
- * If multiple errors occured, the corresponding <code>JavaModelStatus</code> is a
- * multi-status. Otherwise, it is a simple one.
- */
- protected void executeOperation() throws JavaScriptModelException {
- processElements();
- }
- /**
- * Returns the parent of the element being copied/moved/renamed.
- */
- protected IJavaScriptElement getDestinationParent(IJavaScriptElement child) {
- return (IJavaScriptElement)this.newParents.get(child);
- }
- /**
- * Returns the name to be used by the progress monitor.
- */
- protected abstract String getMainTaskName();
- /**
- * Returns the new name for <code>element</code>, or <code>null</code>
- * if there are no renamings specified.
- */
- protected String getNewNameFor(IJavaScriptElement element) throws JavaScriptModelException {
- String newName = null;
- if (this.renamings != null)
- newName = (String) this.renamings.get(element);
- if (newName == null && element instanceof IFunction && ((IFunction) element).isConstructor())
- newName = getDestinationParent(element).getElementName();
- return newName;
- }
- /**
- * Sets up the renamings hashtable - keys are the elements and
- * values are the new name.
- */
- private void initializeRenamings() {
- if (this.renamingsList != null && this.renamingsList.length == this.elementsToProcess.length) {
- this.renamings = new HashMap(this.renamingsList.length);
- for (int i = 0; i < this.renamingsList.length; i++) {
- if (this.renamingsList[i] != null) {
- this.renamings.put(this.elementsToProcess[i], this.renamingsList[i]);
- }
- }
- }
- }
- /**
- * Returns <code>true</code> if this operation represents a move or rename, <code>false</code>
- * if this operation represents a copy.<br>
- * Note: a rename is just a move within the same parent with a name change.
- */
- protected boolean isMove() {
- return false;
- }
- /**
- * Returns <code>true</code> if this operation represents a rename, <code>false</code>
- * if this operation represents a copy or move.
- */
- protected boolean isRename() {
- return false;
- }
-
- /**
- * Subclasses must implement this method to process a given <code>IJavaScriptElement</code>.
- */
- protected abstract void processElement(IJavaScriptElement element) throws JavaScriptModelException;
- /**
- * Processes all the <code>IJavaScriptElement</code>s in turn, collecting errors
- * and updating the progress monitor.
- *
- * @exception JavaScriptModelException if one or several operation(s) was unable to
- * be completed.
- */
- protected void processElements() throws JavaScriptModelException {
- try {
- beginTask(getMainTaskName(), this.elementsToProcess.length);
- IJavaScriptModelStatus[] errors = new IJavaScriptModelStatus[3];
- int errorsCounter = 0;
- for (int i = 0; i < this.elementsToProcess.length; i++) {
- try {
- verify(this.elementsToProcess[i]);
- processElement(this.elementsToProcess[i]);
- } catch (JavaScriptModelException jme) {
- if (errorsCounter == errors.length) {
- // resize
- System.arraycopy(errors, 0, (errors = new IJavaScriptModelStatus[errorsCounter*2]), 0, errorsCounter);
- }
- errors[errorsCounter++] = jme.getJavaScriptModelStatus();
- } finally {
- worked(1);
- }
- }
- if (errorsCounter == 1) {
- throw new JavaScriptModelException(errors[0]);
- } else if (errorsCounter > 1) {
- if (errorsCounter != errors.length) {
- // resize
- System.arraycopy(errors, 0, (errors = new IJavaScriptModelStatus[errorsCounter]), 0, errorsCounter);
- }
- throw new JavaScriptModelException(JavaModelStatus.newMultiStatus(errors));
- }
- } finally {
- done();
- }
- }
- /**
- * Sets the insertion position in the new container for the modified element. The element
- * being modified will be inserted before the specified new sibling. The given sibling
- * must be a child of the destination container specified for the modified element.
- * The default is <code>null</code>, which indicates that the element is to be
- * inserted at the end of the container.
- */
- public void setInsertBefore(IJavaScriptElement modifiedElement, IJavaScriptElement newSibling) {
- this.insertBeforeElements.put(modifiedElement, newSibling);
- }
- /**
- * Sets the new names to use for each element being copied. The renamings
- * correspond to the elements being processed, and the number of
- * renamings must match the number of elements being processed.
- * A <code>null</code> entry in the list indicates that an element
- * is not to be renamed.
- *
- * <p>Note that some renamings may not be used. If both a parent
- * and a child have been selected for copy/move, only the parent
- * is changed. Therefore, if a new name is specified for the child,
- * the child's name will not be changed.
- */
- public void setRenamings(String[] renamingsList) {
- this.renamingsList = renamingsList;
- initializeRenamings();
- }
- /**
- * This method is called for each <code>IJavaScriptElement</code> before
- * <code>processElement</code>. It should check that this <code>element</code>
- * can be processed.
- */
- protected abstract void verify(IJavaScriptElement element) throws JavaScriptModelException;
- /**
- * Verifies that the <code>destination</code> specified for the <code>element</code> is valid for the types of the
- * <code>element</code> and <code>destination</code>.
- */
- protected void verifyDestination(IJavaScriptElement element, IJavaScriptElement destination) throws JavaScriptModelException {
- if (destination == null || !destination.exists())
- error(IJavaScriptModelStatusConstants.ELEMENT_DOES_NOT_EXIST, destination);
-
- int destType = destination.getElementType();
- switch (element.getElementType()) {
- case IJavaScriptElement.IMPORT_DECLARATION :
- if (destType != IJavaScriptElement.JAVASCRIPT_UNIT)
- error(IJavaScriptModelStatusConstants.INVALID_DESTINATION, element);
- break;
- case IJavaScriptElement.TYPE :
- if (destType != IJavaScriptElement.JAVASCRIPT_UNIT && destType != IJavaScriptElement.TYPE)
- error(IJavaScriptModelStatusConstants.INVALID_DESTINATION, element);
- break;
- case IJavaScriptElement.METHOD :
- case IJavaScriptElement.FIELD :
- case IJavaScriptElement.INITIALIZER :
- if (!(destType == IJavaScriptElement.TYPE ||destType == IJavaScriptElement.JAVASCRIPT_UNIT) || destination instanceof BinaryType)
- error(IJavaScriptModelStatusConstants.INVALID_DESTINATION, element);
- break;
- case IJavaScriptElement.JAVASCRIPT_UNIT :
- if (destType != IJavaScriptElement.PACKAGE_FRAGMENT)
- error(IJavaScriptModelStatusConstants.INVALID_DESTINATION, element);
- else {
- CompilationUnit cu = (CompilationUnit)element;
- if (isMove() && cu.isWorkingCopy() && !cu.isPrimary())
- error(IJavaScriptModelStatusConstants.INVALID_ELEMENT_TYPES, element);
- }
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT :
- IPackageFragment fragment = (IPackageFragment) element;
- IJavaScriptElement parent = fragment.getParent();
- if (parent.isReadOnly())
- error(IJavaScriptModelStatusConstants.READ_ONLY, element);
- else if (destType != IJavaScriptElement.PACKAGE_FRAGMENT_ROOT)
- error(IJavaScriptModelStatusConstants.INVALID_DESTINATION, element);
- break;
- default :
- error(IJavaScriptModelStatusConstants.INVALID_ELEMENT_TYPES, element);
- }
- }
- /**
- * Verify that the new name specified for <code>element</code> is
- * valid for that type of Java element.
- */
- protected void verifyRenaming(IJavaScriptElement element) throws JavaScriptModelException {
- String newName = getNewNameFor(element);
- boolean isValid = true;
- IJavaScriptProject project = element.getJavaScriptProject();
- String sourceLevel = project.getOption(JavaScriptCore.COMPILER_SOURCE, true);
- String complianceLevel = project.getOption(JavaScriptCore.COMPILER_COMPLIANCE, true);
- switch (element.getElementType()) {
- case IJavaScriptElement.PACKAGE_FRAGMENT :
- if (((IPackageFragment) element).isDefaultPackage()) {
- // don't allow renaming of default package (see PR #1G47GUM)
- throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.NAME_COLLISION, element));
- }
- isValid = JavaScriptConventions.validatePackageName(newName, sourceLevel, complianceLevel).getSeverity() != IStatus.ERROR;
- break;
- case IJavaScriptElement.JAVASCRIPT_UNIT :
- isValid = JavaScriptConventions.validateCompilationUnitName(newName,sourceLevel, complianceLevel).getSeverity() != IStatus.ERROR;
- break;
- case IJavaScriptElement.INITIALIZER :
- isValid = false; //cannot rename initializers
- break;
- default :
- isValid = JavaScriptConventions.validateIdentifier(newName, sourceLevel, complianceLevel).getSeverity() != IStatus.ERROR;
- break;
- }
-
- if (!isValid) {
- throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_NAME, element, newName));
- }
- }
- /**
- * Verifies that the positioning sibling specified for the <code>element</code> is exists and
- * its parent is the destination container of this <code>element</code>.
- */
- protected void verifySibling(IJavaScriptElement element, IJavaScriptElement destination) throws JavaScriptModelException {
- IJavaScriptElement insertBeforeElement = (IJavaScriptElement) this.insertBeforeElements.get(element);
- if (insertBeforeElement != null) {
- if (!insertBeforeElement.exists() || !insertBeforeElement.getParent().equals(destination)) {
- error(IJavaScriptModelStatusConstants.INVALID_SIBLING, insertBeforeElement);
- }
- }
- }
-}
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
deleted file mode 100644
index a5bc80cf..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/NameLookup.java
+++ /dev/null
@@ -1,2302 +0,0 @@
-/*******************************************************************************
- * 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;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map;
-
-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.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-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.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IInitializer;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IOpenable;
-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.ITypeRoot;
-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.core.infer.IInferenceFile;
-import org.eclipse.wst.jsdt.core.infer.InferrenceManager;
-import org.eclipse.wst.jsdt.core.infer.InferrenceProvider;
-import org.eclipse.wst.jsdt.core.infer.ResolutionConfiguration;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-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.TypeDeclaration;
-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.lookup.Binding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.CompilationUnitScope;
-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.parser.ScannerHelper;
-import org.eclipse.wst.jsdt.internal.compiler.util.SuffixConstants;
-import org.eclipse.wst.jsdt.internal.core.search.BasicSearchEngine;
-import org.eclipse.wst.jsdt.internal.core.search.IRestrictedAccessBindingRequestor;
-import org.eclipse.wst.jsdt.internal.core.util.HandleFactory;
-import org.eclipse.wst.jsdt.internal.core.util.HashtableOfArrayToObject;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * A <code>NameLookup</code> provides name resolution within a Java project.
- * The name lookup facility uses the project's classpath to prioritize the
- * order in which package fragments are searched when resolving a name.
- *
- * <p>Name lookup only returns a handle when the named element actually
- * exists in the model; otherwise <code>null</code> is returned.
- *
- * <p>There are two logical sets of methods within this interface. Methods
- * which start with <code>find*</code> are intended to be convenience methods for quickly
- * finding an element within another element; for instance, for finding a class within a
- * package. The other set of methods all begin with <code>seek*</code>. These methods
- * do comprehensive searches of the <code>IJavaScriptProject</code> returning hits
- * in real time through an <code>IJavaElementRequestor</code>.
- *
- */
-public class NameLookup implements SuffixConstants {
- public static class Answer {
- public IType type;
- public Object element;
- AccessRestriction restriction;
- Answer(IType type, AccessRestriction restriction) {
- this.type = type;
- this.restriction = restriction;
- }
- Answer(Object element, AccessRestriction restriction) {
- this.element = element;
- this.restriction = restriction;
- }
- public boolean ignoreIfBetter() {
- return this.restriction != null && this.restriction.ignoreIfBetter();
- }
- /*
- * Returns whether this answer is better than the other awswer.
- * (accessible is better than discouraged, which is better than
- * non-accessible)
- */
- public boolean isBetter(Answer otherAnswer) {
- if (otherAnswer == null) return true;
- if (this.restriction == null) return true;
- return otherAnswer.restriction != null
- && this.restriction.getProblemId() < otherAnswer.restriction.getProblemId();
- }
- }
-
- // TODO (jerome) suppress the accept flags (qualified name is sufficient to find a type)
- /**
- * Accept flag for specifying classes.
- */
- public static final int ACCEPT_CLASSES = ASTNode.Bit2;
-
- /**
- * Accept flag for specifying interfaces.
- */
- public static final int ACCEPT_INTERFACES = ASTNode.Bit3;
-
- /**
- * Accept flag for specifying enums.
- */
- public static final int ACCEPT_ENUMS = ASTNode.Bit4;
-
- /**
- * Accept flag for specifying annotations.
- */
- public static final int ACCEPT_ANNOTATIONS = ASTNode.Bit5;
-
- /*
- * Accept flag for all kinds of types
- */
- public static final int ACCEPT_ALL = ACCEPT_CLASSES | ACCEPT_INTERFACES | ACCEPT_ENUMS | ACCEPT_ANNOTATIONS;
-
- public static boolean VERBOSE = false;
-
- private static final IType[] NO_TYPES = {};
- private static final IJavaScriptElement[] NO_BINDINGS = {};
-
- private boolean searchFiles=true;
-
- /**
- * The <code>IPackageFragmentRoot</code>'s associated
- * with the classpath of this NameLookup facility's
- * project.
- */
- protected IPackageFragmentRoot[] packageFragmentRoots;
-
- /**
- * Table that maps package names to lists of package fragment roots
- * that contain such a package known by this name lookup facility.
- * To allow > 1 package fragment with the same name, values are
- * arrays of package fragment roots ordered as they appear on the
- * classpath.
- * Note if the list is of size 1, then the IPackageFragmentRoot object
- * replaces the array.
- */
- protected HashtableOfArrayToObject packageFragments;
-
- /**
- * Reverse map from root path to corresponding resolved CP entry
- * (so as to be able to figure inclusion/exclusion rules)
- */
- protected Map rootToResolvedEntries;
-
- /**
- * A map from package handles to a map from type name to an IType or an IType[].
- * Allows working copies to take precedence over compilation units.
- */
- protected HashMap typesInWorkingCopies;
- protected HashMap[] bindingsInWorkingCopies;
-
- public long timeSpentInSeekTypesInSourcePackage = 0;
- public long timeSpentInSeekTypesInBinaryPackage = 0;
-
- protected HashSet acceptedCUs=new HashSet();
- private IJavaScriptUnit[] workingCopies;
-
- IRestrictedAccessBindingRequestor restrictedRequestor;
-
- public NameLookup(
- IPackageFragmentRoot[] packageFragmentRoots,
- HashtableOfArrayToObject packageFragments,
- IJavaScriptUnit[] workingCopies,
- Map rootToResolvedEntries) {
- long start = -1;
- if (VERBOSE) {
- Util.verbose(" BUILDING NameLoopkup"); //$NON-NLS-1$
- Util.verbose(" -> pkg roots size: " + (packageFragmentRoots == null ? 0 : packageFragmentRoots.length)); //$NON-NLS-1$
- Util.verbose(" -> pkgs size: " + (packageFragments == null ? 0 : packageFragments.size())); //$NON-NLS-1$
- Util.verbose(" -> working copy size: " + (workingCopies == null ? 0 : workingCopies.length)); //$NON-NLS-1$
- start = System.currentTimeMillis();
- }
-// this.restrictedRequestor=restrictedRequestor;
- //this.restrictToLanguage=restrictToLanguage;
- this.packageFragmentRoots = packageFragmentRoots;
- if (workingCopies == null) {
- this.packageFragments = packageFragments;
- } else {
- // clone tables as we're adding packages from working copies
- try {
- this.packageFragments = (HashtableOfArrayToObject) packageFragments.clone();
- } catch (CloneNotSupportedException e1) {
- // ignore (implementation of HashtableOfArrayToObject supports cloning)
- }
- this.typesInWorkingCopies = new HashMap();
- this.bindingsInWorkingCopies = new HashMap[Binding.NUMBER_BASIC_BINDING];
- for (int j = 0; j <Binding.NUMBER_BASIC_BINDING; j++) {
- this.bindingsInWorkingCopies[j] = new HashMap();
- }
- this.workingCopies=workingCopies;
- for (int i = 0, length = workingCopies.length; i < length; i++) {
- IJavaScriptUnit workingCopy = workingCopies[i];
-
- try {
- IType[] types = workingCopy.getTypes();
- int typeLength = types.length;
- if (typeLength == 0) {
- String typeName = Util.getNameWithoutJavaLikeExtension(workingCopy.getElementName());
- this.typesInWorkingCopies.put(typeName, NO_TYPES);
- } else {
- for (int j = 0; j < typeLength; j++) {
- IType type = types[j];
- String typeName = type.getElementName();
- Object existing = this.typesInWorkingCopies.get(typeName);
- if (existing == null) {
- this.typesInWorkingCopies.put(typeName, type);
- } else if (existing instanceof IType) {
- this.typesInWorkingCopies.put(typeName, new IType[] {(IType) existing, type});
- } else {
- IType[] existingTypes = (IType[]) existing;
- int existingTypeLength = existingTypes.length;
- System.arraycopy(existingTypes, 0, existingTypes = new IType[existingTypeLength+1], 0, existingTypeLength);
- existingTypes[existingTypeLength] = type;
- this.typesInWorkingCopies.put(typeName, existingTypes);
- }
- }
- }
-
- addWorkingCopyBindings(types, this.bindingsInWorkingCopies[Binding.TYPE]);
- addWorkingCopyBindings(workingCopy.getFields(), this.bindingsInWorkingCopies[Binding.VARIABLE]);
- addWorkingCopyBindings(workingCopy.getFields(), this.bindingsInWorkingCopies[Binding.LOCAL]);
- addWorkingCopyBindings(workingCopy.getFunctions(), this.bindingsInWorkingCopies[Binding.METHOD]);
-
- } catch (JavaScriptModelException e) {
- // working copy doesn't exist -> ignore
- }
-
- // add root of package fragment to cache
- PackageFragment pkg = (PackageFragment) workingCopy.getParent();
- IPackageFragmentRoot root = (IPackageFragmentRoot) pkg.getParent();
- String[] pkgName = pkg.names;
- Object existing = this.packageFragments.get(pkgName);
- if (existing == null || existing == JavaProjectElementInfo.NO_ROOTS) {
- this.packageFragments.put(pkgName, root);
- // ensure super packages (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=119161)
- // are also in the map
- JavaProjectElementInfo.addSuperPackageNames(pkgName, this.packageFragments);
- } else {
- if (existing instanceof PackageFragmentRoot) {
- if (!existing.equals(root))
- this.packageFragments.put(pkgName, new IPackageFragmentRoot[] {(PackageFragmentRoot) existing, root});
- } else {
- IPackageFragmentRoot[] roots = (IPackageFragmentRoot[]) existing;
- int rootLength = roots.length;
- boolean containsRoot = false;
- for (int j = 0; j < rootLength; j++) {
- if (roots[j].equals(root)) {
- containsRoot = true;
- break;
- }
- }
- if (containsRoot) {
- System.arraycopy(roots, 0, roots = new IPackageFragmentRoot[rootLength+1], 0, rootLength);
- roots[rootLength] = root;
- this.packageFragments.put(pkgName, roots);
- }
- }
- }
- }
- }
-
- this.rootToResolvedEntries = rootToResolvedEntries;
- if (VERBOSE) {
- Util.verbose(" -> spent: " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
-
- public void setRestrictedAccessRequestor(IRestrictedAccessBindingRequestor restrictedRequestor) {
- this.restrictedRequestor=restrictedRequestor;
- }
-
- protected IRestrictedAccessBindingRequestor getRestrictedAccessRequestor() {
- if(this.restrictedRequestor==null) {
- this.restrictedRequestor=new IRestrictedAccessBindingRequestor() {
- ArrayList foundPaths=new ArrayList();
- String excludePath;
-
- public void setExcludePath(String excludePath) {
- this.excludePath = excludePath;
- }
- public boolean acceptBinding(int type,int modifiers, char[] packageName,
- char[] simpleTypeName,
- String path, AccessRestriction access) {
- if (excludePath!=null && path.equals(excludePath))
- return false;
- foundPaths.add(path);
- return true;
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.core.search.IRestrictedAccessBindingRequestor#getFoundPaths()
- */
- public String getFoundPath() {
- return foundPaths.size()>0?(String)foundPaths.get(0):null;
- }
-
-
- public void reset() {
- foundPaths.clear();
- }
- public ArrayList getFoundPaths()
- {
- return foundPaths;
- }
-
- };
- }
-
- return this.restrictedRequestor;
- }
-
- private void addWorkingCopyBindings(IJavaScriptElement [] elements, HashMap bindingsMap)
- {
- for (int j = 0; j < elements.length; j++) {
- IJavaScriptElement element = elements[j];
- String elementName = element.getElementName();
- Object existing = bindingsMap.get(elementName);
- if (existing == null) {
- bindingsMap.put(elementName, element);
- } else if (existing instanceof IJavaScriptElement) {
- bindingsMap.put(elementName, new IJavaScriptElement[] {(IJavaScriptElement) existing, element});
- } else {
- IJavaScriptElement[] existingElements = (IJavaScriptElement[]) existing;
- int existingElementsLength = existingElements.length;
- System.arraycopy(existingElements, 0, existingElements = new IJavaScriptElement[existingElementsLength+1], 0, existingElementsLength);
- existingElements[existingElementsLength] = element;
- bindingsMap.put(elementName, existingElements);
- }
- }
-
- }
-
- /**
- * Returns true if:<ul>
- * <li>the given type is an existing class and the flag's <code>ACCEPT_CLASSES</code>
- * bit is on
- * <li>the given type is an existing interface and the <code>ACCEPT_INTERFACES</code>
- * bit is on
- * <li>neither the <code>ACCEPT_CLASSES</code> or <code>ACCEPT_INTERFACES</code>
- * bit is on
- * </ul>
- * Otherwise, false is returned.
- */
- protected boolean acceptType(IType type, int acceptFlags, boolean isSourceType) {
- if (!type.exists())
- return false;
- if (acceptFlags == 0 || acceptFlags == ACCEPT_ALL)
- return true; // no flags or all flags, always accepted
- try {
- int kind = TypeDeclaration.kind(((SourceTypeElementInfo) ((SourceType) type).getElementInfo()).getModifiers());
-
-// int kind = isSourceType
-// ? TypeDeclaration.kind(((SourceTypeElementInfo) ((SourceType) type).getElementInfo()).getModifiers())
-// : TypeDeclaration.kind(((IBinaryType) ((BinaryType) type).getElementInfo()).getModifiers());
- switch (kind) {
- case TypeDeclaration.CLASS_DECL :
- return (acceptFlags & ACCEPT_CLASSES) != 0;
- default:
- //case IGenericType.ANNOTATION_TYPE :
- return (acceptFlags & ACCEPT_ANNOTATIONS) != 0;
- }
- } catch (JavaScriptModelException npe) {
- return false; // the class is not present, do not accept.
- }
- }
-
- protected boolean doAcceptBinding(IJavaScriptElement element, int bindingType, boolean isSourceType,IJavaElementRequestor requestor) {
- switch (bindingType)
- {
- case Binding.FIELD | Binding.METHOD:
- if (element instanceof IFunction)
- {
-
- requestor.acceptMethod((IFunction)element);
- return true;
- }
- if (element instanceof IField)
- {
- requestor.acceptField( (IField)element);
- return true;
- }
- return false;
- case Binding.FIELD:
- case Binding.VARIABLE:
- if (element instanceof IField)
- {
- requestor.acceptField( (IField)element);
- return true;
- }
- return false;
- case Binding.METHOD:
- if (element instanceof IFunction)
- {
- requestor.acceptMethod((IFunction)element);
- return true;
- }
- case Binding.TYPE:
- if (element instanceof IType)
- {
- requestor.acceptType((IType)element);
- return true;
- }
-
- }
- return false;
- }
-
- /**
- * Finds every type in the project whose simple name matches
- * the prefix, informing the requestor of each hit. The requestor
- * is polled for cancellation at regular intervals.
- *
- * <p>The <code>partialMatch</code> argument indicates partial matches
- * should be considered.
- */
- private void findAllTypes(String prefix, boolean partialMatch, int acceptFlags, IJavaElementRequestor requestor) {
- int count= this.packageFragmentRoots.length;
- for (int i= 0; i < count; i++) {
- if (requestor.isCanceled())
- return;
- IPackageFragmentRoot root= this.packageFragmentRoots[i];
- IJavaScriptElement[] packages= null;
- try {
- packages= root.getChildren();
- } catch (JavaScriptModelException npe) {
- continue; // the root is not present, continue;
- }
- if (packages != null) {
- for (int j= 0, packageCount= packages.length; j < packageCount; j++) {
- if (requestor.isCanceled())
- return;
- seekTypes(prefix, (IPackageFragment) packages[j], partialMatch, acceptFlags, requestor);
- }
- }
- }
- }
-
- private void findAllBindings(String prefix,int bindingType, boolean partialMatch, int acceptFlags, IJavaElementRequestor requestor) {
- int count= this.packageFragmentRoots.length;
- for (int i= 0; i < count; i++) {
- if (requestor.isCanceled())
- return;
- IPackageFragmentRoot root= this.packageFragmentRoots[i];
- IJavaScriptElement[] packages= null;
- try {
- packages= root.getChildren();
- } catch (JavaScriptModelException npe) {
- continue; // the root is not present, continue;
- }
- if (packages != null) {
- for (int j= 0, packageCount= packages.length; j < packageCount; j++) {
- if (requestor.isCanceled())
- return;
- seekBindings(prefix,bindingType, (IPackageFragment) packages[j], partialMatch, acceptFlags, requestor);
- }
- }
- }
- }
-
- /**
- * Returns the <code>IJavaScriptUnit</code> which defines the type
- * named <code>qualifiedTypeName</code>, or <code>null</code> if
- * none exists. The domain of the search is bounded by the classpath
- * of the <code>IJavaScriptProject</code> this <code>NameLookup</code> was
- * obtained from.
- * <p>
- * The name must be fully qualified (eg "java.lang.Object", "java.util.Hashtable$Entry")
- */
- public ITypeRoot findCompilationUnit(String qualifiedTypeName) {
- String[] pkgName = CharOperation.NO_STRINGS;
- String cuName = qualifiedTypeName;
-
- int index= qualifiedTypeName.lastIndexOf('.');
- if (index != -1) {
- pkgName= Util.splitOn('.', qualifiedTypeName, 0, index);
- 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) {
- return findCompilationUnit(pkgName, cuName, (PackageFragmentRoot) value);
- } else {
- IPackageFragmentRoot[] roots = (IPackageFragmentRoot[]) value;
- for (int i= 0; i < roots.length; i++) {
- PackageFragmentRoot root= (PackageFragmentRoot) roots[i];
- ITypeRoot cu = findCompilationUnit(pkgName, cuName, root);
- if (cu != null)
- return cu;
- }
- }
- }
- return null;
- }
-
- private ITypeRoot findCompilationUnit(String[] pkgName, String cuName, PackageFragmentRoot root) {
- if (!root.isArchive()) {
- IPackageFragment pkg = root.getPackageFragment(pkgName);
- try {
- IJavaScriptUnit[] cus = pkg.getJavaScriptUnits();
- for (int j = 0, length = cus.length; j < length; j++) {
- IJavaScriptUnit cu = cus[j];
- if (Util.equalsIgnoreJavaLikeExtension(cu.getElementName(), cuName))
- return cu;
- }
- IClassFile[] classFiles = pkg.getClassFiles();
- for (int j = 0, length = classFiles.length; j < length; j++) {
- IClassFile cu = classFiles[j];
- if (Util.equalsIgnoreJavaLikeExtension(cu.getElementName(), cuName))
- return cu;
- }
- } catch (JavaScriptModelException e) {
- // pkg does not exist
- // -> try next package
- }
- }
- return null;
-}
-
- /**
- * Returns the package fragment whose path matches the given
- * (absolute) path, or <code>null</code> if none exist. The domain of
- * the search is bounded by the classpath of the <code>IJavaScriptProject</code>
- * this <code>NameLookup</code> was obtained from.
- * The path can be:
- * - internal to the workbench: "/Project/src"
- * - external to the workbench: "c:/jdk/classes.zip/java/lang"
- */
- public IPackageFragment findPackageFragment(IPath path) {
- if (!path.isAbsolute()) {
- throw new IllegalArgumentException(Messages.path_mustBeAbsolute);
- }
-/*
- * TODO (jerome) this code should rather use the package fragment map to find the candidate package, then
- * check if the respective enclosing root maps to the one on this given IPath.
- */
- IResource possibleFragment = ResourcesPlugin.getWorkspace().getRoot().findMember(path);
- if (possibleFragment == null) {
- //external jar
- for (int i = 0; i < this.packageFragmentRoots.length; i++) {
- IPackageFragmentRoot root = this.packageFragmentRoots[i];
- if (!root.isExternal()) {
- continue;
- }
- IPath rootPath = root.getPath();
- int matchingCount = rootPath.matchingFirstSegments(path);
- if (matchingCount != 0) {
- String name = path.toOSString();
- // + 1 is for the File.separatorChar
- name = name.substring(rootPath.toOSString().length() + 1, name.length());
- name = name.replace(File.separatorChar, '.');
- IJavaScriptElement[] list = null;
- try {
- list = root.getChildren();
- } catch (JavaScriptModelException npe) {
- continue; // the package fragment root is not present;
- }
- int elementCount = list.length;
- for (int j = 0; j < elementCount; j++) {
- IPackageFragment packageFragment = (IPackageFragment) list[j];
- if (nameMatches(name, packageFragment, false)) {
- return packageFragment;
- }
- }
- }
- }
- } else {
- IJavaScriptElement fromFactory = JavaScriptCore.create(possibleFragment);
- if (fromFactory == null) {
- return null;
- }
- switch (fromFactory.getElementType()) {
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- return (IPackageFragment) fromFactory;
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- // default package in a default root
- JavaProject project = (JavaProject) fromFactory;
- try {
- IIncludePathEntry entry = project.getClasspathEntryFor(path);
- if (entry != null) {
- IPackageFragmentRoot root =
- project.getPackageFragmentRoot(project.getResource());
- Object defaultPkgRoot = this.packageFragments.get(CharOperation.NO_STRINGS);
- if (defaultPkgRoot == null) {
- return null;
- }
- if (defaultPkgRoot instanceof PackageFragmentRoot && defaultPkgRoot.equals(root))
- return ((PackageFragmentRoot) root).getPackageFragment(CharOperation.NO_STRINGS);
- else {
- IPackageFragmentRoot[] roots = (IPackageFragmentRoot[]) defaultPkgRoot;
- for (int i = 0; i < roots.length; i++) {
- if (roots[i].equals(root)) {
- return ((PackageFragmentRoot) root).getPackageFragment(CharOperation.NO_STRINGS);
- }
- }
- }
- }
- } catch (JavaScriptModelException e) {
- return null;
- }
- return null;
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- return ((PackageFragmentRoot)fromFactory).getPackageFragment(CharOperation.NO_STRINGS);
- }
- }
- return null;
- }
-
- /**
- * Returns the package fragments whose name matches the given
- * (qualified) name, or <code>null</code> if none exist.
- *
- * The name can be:
- * <ul>
- * <li>empty: ""</li>
- * <li>qualified: "pack.pack1.pack2"</li>
- * </ul>
- * @param partialMatch partial name matches qualify when <code>true</code>,
- * only exact name matches qualify when <code>false</code>
- */
- public IPackageFragment[] findPackageFragments(String name, boolean partialMatch) {
- return findPackageFragments(name, partialMatch, false);
- }
-
- /**
- * Returns the package fragments whose name matches the given
- * (qualified) name or pattern, or <code>null</code> if none exist.
- *
- * The name can be:
- * <ul>
- * <li>empty: ""</li>
- * <li>qualified: "pack.pack1.pack2"</li>
- * <li>a pattern: "pack.*.util"</li>
- * </ul>
- * @param partialMatch partial name matches qualify when <code>true</code>,
- * @param patternMatch <code>true</code> when the given name might be a pattern,
- * <code>false</code> otherwise.
- */
- public IPackageFragment[] findPackageFragments(String name, boolean partialMatch, boolean patternMatch) {
- ArrayList fragRootChildren = new ArrayList();
- for (int i = 0; i < this.packageFragmentRoots.length; i++) {
- IJavaScriptElement[] children;
- try {
- children = packageFragmentRoots[i].getChildren();
- for (int j = 0; j < children.length; j++) {
- IPackageFragment packageFragment = (IPackageFragment)children[j];
- if(packageFragment!=null && packageFragment.getElementName().equals(name))
- fragRootChildren.add((packageFragment));
- }
- } catch (JavaScriptModelException e) {}
-
- }
-
- return (IPackageFragment[])fragRootChildren.toArray(new IPackageFragment[fragRootChildren.size()]);
- // if (partialMatch) {
-// String[] splittedName = Util.splitOn('.', name, 0, name.length());
-// IPackageFragment[] oneFragment = null;
-// ArrayList pkgs = null;
-// Object[][] keys = this.packageFragments.keyTable;
-// for (int i = 0, length = keys.length; i < length; i++) {
-// String[] pkgName = (String[]) keys[i];
-// if (pkgName != null && Util.startsWithIgnoreCase(pkgName, splittedName)) {
-// Object value = this.packageFragments.valueTable[i];
-// if (value instanceof PackageFragmentRoot) {
-// IPackageFragment pkg = ((PackageFragmentRoot) value).getPackageFragment(pkgName);
-// if (oneFragment == null) {
-// oneFragment = new IPackageFragment[] {pkg};
-// } else {
-// if (pkgs == null) {
-// pkgs = new ArrayList();
-// pkgs.add(oneFragment[0]);
-// }
-// pkgs.add(pkg);
-// }
-// } else {
-// IPackageFragmentRoot[] roots = (IPackageFragmentRoot[]) value;
-// for (int j = 0, length2 = roots.length; j < length2; j++) {
-// PackageFragmentRoot root = (PackageFragmentRoot) roots[j];
-// IPackageFragment pkg = root.getPackageFragment(pkgName);
-// if (oneFragment == null) {
-// oneFragment = new IPackageFragment[] {pkg};
-// } else {
-// if (pkgs == null) {
-// pkgs = new ArrayList();
-// pkgs.add(oneFragment[0]);
-// }
-// pkgs.add(pkg);
-// }
-// }
-// }
-// }
-// }
-// if (pkgs == null) return oneFragment;
-// int resultLength = pkgs.size();
-// IPackageFragment[] result = new IPackageFragment[resultLength];
-// pkgs.toArray(result);
-// return result;
-// } else {
-// String[] splittedName = (name.length()>0)? new String[]{name}: new String[0];//Util.splitOn('.', name, 0, name.length());
-// Object value = this.packageFragments.get(splittedName);
-// if (value==null)
-// value=this.packageFragments.get(new String[]{name});
-// if (value == null)
-// return null;
-// if (value instanceof PackageFragmentRoot) {
-// return new IPackageFragment[] {((PackageFragmentRoot) value).getPackageFragment(splittedName)};
-// } else {
-// IPackageFragmentRoot[] roots = (IPackageFragmentRoot[]) value;
-// IPackageFragment[] result = new IPackageFragment[roots.length];
-// for (int i= 0; i < roots.length; i++) {
-// result[i] = ((PackageFragmentRoot) roots[i]).getPackageFragment(splittedName);
-// }
-// return result;
-// }
-// }
- }
-
- /*
- * Find secondary type for a project.
- */
- private IType findSecondaryType(String packageName, String typeName, IJavaScriptProject project, boolean waitForIndexes, IProgressMonitor monitor) {
- if (JavaModelManager.VERBOSE) {
- Util.verbose("NameLookup FIND SECONDARY TYPES:"); //$NON-NLS-1$
- Util.verbose(" -> pkg name: " + packageName); //$NON-NLS-1$
- Util.verbose(" -> type name: " + typeName); //$NON-NLS-1$
- Util.verbose(" -> project: "+project.getElementName()); //$NON-NLS-1$
- }
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- try {
- IJavaScriptProject javaProject = project;
- Map secondaryTypePaths = manager.secondaryTypes(javaProject, waitForIndexes, monitor);
- if (secondaryTypePaths.size() > 0) {
- Map types = (Map) secondaryTypePaths.get(packageName==null?"":packageName); //$NON-NLS-1$
- if (types != null && types.size() > 0) {
- IType type = (IType) types.get(typeName);
- if (type != null) {
- if (JavaModelManager.VERBOSE) {
- Util.verbose(" -> type: " + type.getElementName()); //$NON-NLS-1$
- }
- return type;
- }
- }
- }
- }
- catch (JavaScriptModelException jme) {
- // give up
- }
- return null;
- }
-
- /**
- * Find type considering secondary types but without waiting for indexes.
- * It means that secondary types may be not found under certain circumstances...
- * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=118789"
- */
- public Answer findType(String typeName, String packageName, boolean partialMatch, int acceptFlags, boolean checkRestrictions) {
-
- if (USE_BINDING_SEARCH && this.searchFiles)
- {
- Answer answer =findBindingSearch(typeName, packageName, Binding.TYPE, partialMatch, acceptFlags, true, true, checkRestrictions, null,false,null);
- if (answer!=null && answer.type==null && answer.element instanceof ITypeRoot)
- {
- ITypeRoot typeroot=(ITypeRoot)answer.element;
- answer.type=typeroot.getType(typeName);
- }
- return answer;
- }
-
- return findType(typeName,
- packageName,
- partialMatch,
- acceptFlags,
- true/* consider secondary types */,
- false/* do NOT wait for indexes */,
- checkRestrictions,
- null);
- }
-
- public Answer findBinding(String typeName, String packageName,int type, boolean partialMatch,
- int acceptFlags, boolean checkRestrictions, boolean returnMultiple , String excludePath){
-
- if ((type&Binding.COMPILATION_UNIT)!=0)
- {
- String fullName=typeName;
- if (packageName.length()>0)
- fullName=packageName+"."+typeName;
- ITypeRoot compilationUnit = findCompilationUnit(fullName);
- if (compilationUnit!=null )
- {
- return new Answer(compilationUnit, null);
- }
- type &= ~Binding.COMPILATION_UNIT;
- if (type==0)
- return null;
- }
-
- if ((type&Binding.PACKAGE)!=0)
- {
- type &= ~Binding.PACKAGE;
- if (type==0)
- return null;
- }
-
- if (USE_BINDING_SEARCH && searchFiles)
- return findBindingSearch(typeName,
- packageName,
- type,
- partialMatch,
- acceptFlags,
- true/* consider secondary types */,
- false/* do NOT wait for indexes */,
- checkRestrictions,
- null, returnMultiple, excludePath);
- return findBinding(typeName,
- packageName,
- type,
- partialMatch,
- acceptFlags,
- true/* consider secondary types */,
- false/* do NOT wait for indexes */,
- checkRestrictions,
- null);
- }
-
- /* return all CUs defining a type */
- /**
- * Returns all compilationUnits containing a specific type
- *
- * NOT FULLY IMPLEMENTED YET.
- *
- * @param typeName
- * @param waitForIndexes
- * @return all found compilationUnits containg [typeName]
- */
- public IJavaScriptUnit[] findTypeSources(String typeName, boolean waitForIndexes) {
-
- // Look for concerned package fragments
- JavaElementRequestor elementRequestor = new JavaElementRequestor();
- seekPackageFragments(IPackageFragment.DEFAULT_PACKAGE_NAME, false, elementRequestor);
- IPackageFragment[] packages= elementRequestor.getPackageFragments();
-
- IType type = null;
- int length= packages.length;
- HashSet projects = null;
- IJavaScriptProject javaProject = null;
-// Answer suggestedAnswer = null;
- ArrayList found = new ArrayList();
-
- for (int i= 0; i < length; i++) {
- type = findType(typeName, packages[i], false, NameLookup.ACCEPT_ALL);
- if (type != null && type.exists()) {
- found.add(type);
- }
- if (javaProject == null) {
- javaProject = packages[i].getJavaScriptProject();
- } else if (projects == null) {
- if (!javaProject.equals(packages[i].getJavaScriptProject())) {
- projects = new HashSet(3);
- projects.add(javaProject);
- projects.add(packages[i].getJavaScriptProject());
- }
- } else {
- projects.add(packages[i].getJavaScriptProject());
- }
-
- }
-
- // If type was not found, try to find it as secondary in source folders
- if (javaProject != null) {
- if (projects == null) {
- type = findSecondaryType(IPackageFragment.DEFAULT_PACKAGE_NAME, typeName, javaProject, waitForIndexes, new NullProgressMonitor());
- } else {
- Iterator allProjects = projects.iterator();
- while (type == null && allProjects.hasNext()) {
- type = findSecondaryType(IPackageFragment.DEFAULT_PACKAGE_NAME, typeName, (IJavaScriptProject) allProjects.next(), waitForIndexes, new NullProgressMonitor());
- }
- }
- }
- return null;
- }
-
- /**
- * Find type. Considering secondary types and waiting for indexes depends on given corresponding parameters.
- */
- public Answer findType(
- String typeName,
- String packageName,
- boolean partialMatch,
- int acceptFlags,
- boolean considerSecondaryTypes,
- boolean waitForIndexes,
- boolean checkRestrictions,
- IProgressMonitor monitor) {
- if (packageName == null || packageName.length() == 0) {
- packageName= IPackageFragment.DEFAULT_PACKAGE_NAME;
- } else if (typeName.length() > 0 && ScannerHelper.isLowerCase(typeName.charAt(0))) {
- // see if this is a known package and not a type
- if (findPackageFragments(packageName + "." + typeName, false) != null) return null; //$NON-NLS-1$
- }
-
- // Look for concerned package fragments
- JavaElementRequestor elementRequestor = new JavaElementRequestor();
- seekPackageFragments(packageName, false, elementRequestor);
- IPackageFragment[] packages= elementRequestor.getPackageFragments();
-
- // Try to find type in package fragments list
- IType type = null;
- int length= packages.length;
- HashSet projects = null;
- IJavaScriptProject javaProject = null;
- Answer suggestedAnswer = null;
- for (int i= 0; i < length; i++) {
- type = findType(typeName, packages[i], partialMatch, acceptFlags);
- if (type != null) {
- AccessRestriction accessRestriction = null;
- if (checkRestrictions) {
- accessRestriction = getViolatedRestriction(typeName, packageName, type, accessRestriction);
- }
- Answer answer = new Answer(type, accessRestriction);
- if (!answer.ignoreIfBetter()) {
- if (answer.isBetter(suggestedAnswer))
- return answer;
- } else if (answer.isBetter(suggestedAnswer))
- // remember suggestion and keep looking
- suggestedAnswer = answer;
- }
- else if (suggestedAnswer == null && considerSecondaryTypes) {
- if (javaProject == null) {
- javaProject = packages[i].getJavaScriptProject();
- } else if (projects == null) {
- if (!javaProject.equals(packages[i].getJavaScriptProject())) {
- projects = new HashSet(3);
- projects.add(javaProject);
- projects.add(packages[i].getJavaScriptProject());
- }
- } else {
- projects.add(packages[i].getJavaScriptProject());
- }
- }
- }
- if (suggestedAnswer != null)
- // no better answer was found
- return suggestedAnswer;
-
- // If type was not found, try to find it as secondary in source folders
- if (considerSecondaryTypes && javaProject != null) {
- if (projects == null) {
- type = findSecondaryType(packageName, typeName, javaProject, waitForIndexes, monitor);
- } else {
- Iterator allProjects = projects.iterator();
- while (type == null && allProjects.hasNext()) {
- type = findSecondaryType(packageName, typeName, (IJavaScriptProject) allProjects.next(), waitForIndexes, monitor);
- }
- }
- }
- return type == null ? null : new Answer(type, null);
- }
-
- public Answer findBinding(
- String bindingName,
- String packageName,
- int bindingType,
- boolean partialMatch,
- int acceptFlags,
- boolean considerSecondaryTypes,
- boolean waitForIndexes,
- boolean checkRestrictions,
- IProgressMonitor monitor) {
- if (packageName == null || packageName.length() == 0) {
- packageName= IPackageFragment.DEFAULT_PACKAGE_NAME;
- } else if (bindingName.length() > 0 && ScannerHelper.isLowerCase(bindingName.charAt(0))) {
- // see if this is a known package and not a type
- if (findPackageFragments(packageName + "." + bindingName, false) != null) return null; //$NON-NLS-1$
- }
-
- if (VERBOSE)
- System.out.println("find binding: "+bindingName); //$NON-NLS-1$
- // Look for concerned package fragments
- JavaElementRequestor elementRequestor = new JavaElementRequestor();
- seekPackageFragments(packageName, false, elementRequestor);
- IPackageFragment[] packages= elementRequestor.getPackageFragments();
-
- // Try to find type in package fragments list
-// IType type = null;
- Object element = null;
- int length= packages.length;
- HashSet projects = null;
- IJavaScriptProject javaProject = null;
- Answer suggestedAnswer = null;
- for (int i= 0; i < length; i++) {
- element = findBinding(bindingName, bindingType,packages[i], partialMatch, acceptFlags);
- if (element != null) {
- AccessRestriction accessRestriction = null;
- if (checkRestrictions) {
- accessRestriction = getViolatedRestriction(bindingName, packageName, element, accessRestriction);
- }
- char[] path = null;
-
- if(element instanceof SourceTypeBinding) {
- path = ((SourceTypeBinding)element).getFileName();
- }else if ( element instanceof ReferenceBinding) {
- path = ((ReferenceBinding)element).getFileName();
- }else if(element instanceof SourceType){
- path = ((SourceType)element).getPath().toString().toCharArray();
- }
- if(path!=null && !getRestrictedAccessRequestor().acceptBinding(bindingType, acceptFlags, packageName.toCharArray(), bindingName.toCharArray(), new String(path), accessRestriction)){
- element = null;
- continue;
- }
-//
- Answer answer = new Answer(element, accessRestriction);
- if (!answer.ignoreIfBetter()) {
- if (answer.isBetter(suggestedAnswer))
- return answer;
- } else if (answer.isBetter(suggestedAnswer))
- // remember suggestion and keep looking
- suggestedAnswer = answer;
- }
- else if (suggestedAnswer == null && considerSecondaryTypes) {
- if (javaProject == null) {
- javaProject = packages[i].getJavaScriptProject();
- } else if (projects == null) {
- if (!javaProject.equals(packages[i].getJavaScriptProject())) {
- projects = new HashSet(3);
- projects.add(javaProject);
- projects.add(packages[i].getJavaScriptProject());
- }
- } else {
- projects.add(packages[i].getJavaScriptProject());
- }
- }
- }
- if (suggestedAnswer != null)
- // no better answer was found
- return suggestedAnswer;
-
-// // If type was not found, try to find it as secondary in source folders
-// if (considerSecondaryTypes && javaProject != null) {
-// if (projects == null) {
-// type = findSecondaryType(packageName, bindingName, javaProject, waitForIndexes, monitor);
-// } else {
-// Iterator allProjects = projects.iterator();
-// while (type == null && allProjects.hasNext()) {
-// type = findSecondaryType(packageName, typeName, (IJavaScriptProject) allProjects.next(), waitForIndexes, monitor);
-// }
-// }
-// }
- return element == null ? null : new Answer(element, null);
- }
-
- private AccessRestriction getViolatedRestriction(String typeName, String packageName, IType type, AccessRestriction accessRestriction) {
- PackageFragmentRoot root = (PackageFragmentRoot) type.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- ClasspathEntry entry = (ClasspathEntry) this.rootToResolvedEntries.get(root);
- if (entry != null) { // reverse map always contains resolved CP entry
- AccessRuleSet accessRuleSet = entry.getAccessRuleSet();
- if (accessRuleSet != null) {
- // TODO (philippe) improve char[] <-> String conversions to avoid performing them on the fly
- char[][] packageChars = CharOperation.splitOn('.', packageName.toCharArray());
- char[] typeChars = typeName.toCharArray();
- accessRestriction = accessRuleSet.getViolatedRestriction(CharOperation.concatWith(packageChars, typeChars, '/'));
- }
- }
- return accessRestriction;
- }
-
- private AccessRestriction getViolatedRestriction(String typeName, String packageName, Object element, AccessRestriction accessRestriction) {
-//TODO: implement
-// System.out.println("implement NameLookup.getViolatedRestriction");
-// PackageFragmentRoot root = (PackageFragmentRoot) type.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
-// ClasspathEntry entry = (ClasspathEntry) this.rootToResolvedEntries.get(root);
-// if (entry != null) { // reverse map always contains resolved CP entry
-// AccessRuleSet accessRuleSet = entry.getAccessRuleSet();
-// if (accessRuleSet != null) {
-// // TODO (philippe) improve char[] <-> String conversions to avoid performing them on the fly
-// char[][] packageChars = CharOperation.splitOn('.', packageName.toCharArray());
-// char[] typeChars = typeName.toCharArray();
-// accessRestriction = accessRuleSet.getViolatedRestriction(CharOperation.concatWith(packageChars, typeChars, '/'));
-// }
-// }
- return accessRestriction;
- }
-
- /**
- * Returns the first type in the given package whose name
- * matches the given (unqualified) name, or <code>null</code> if none
- * exist. Specifying a <code>null</code> package will result in no matches.
- * The domain of the search is bounded by the Java project from which
- * this name lookup was obtained.
- *
- * @param name the name of the type to find
- * @param pkg the package to search
- * @param partialMatch partial name matches qualify when <code>true</code>,
- * only exact name matches qualify when <code>false</code>
- * @param acceptFlags a bit mask describing if classes, interfaces or both classes and interfaces
- * are desired results. If no flags are specified, all types are returned.
- * @param considerSecondaryTypes flag to know whether secondary types has to be considered
- * during the search
- *
- * @see #ACCEPT_CLASSES
- * @see #ACCEPT_INTERFACES
- * @see #ACCEPT_ENUMS
- * @see #ACCEPT_ANNOTATIONS
- */
- public IType findType(String name, IPackageFragment pkg, boolean partialMatch, int acceptFlags, boolean considerSecondaryTypes) {
- IType type = findType(name, pkg, partialMatch, acceptFlags);
- if (type == null && considerSecondaryTypes) {
- type = findSecondaryType(pkg.getElementName(), name, pkg.getJavaScriptProject(), false, null);
- }
- return type;
- }
-
- /**
- * Returns the first type in the given package whose name
- * matches the given (unqualified) name, or <code>null</code> if none
- * exist. Specifying a <code>null</code> package will result in no matches.
- * The domain of the search is bounded by the Java project from which
- * this name lookup was obtained.
- * <br>
- * Note that this method does not find secondary types.
- * <br>
- * @param name the name of the type to find
- * @param pkg the package to search
- * @param partialMatch partial name matches qualify when <code>true</code>,
- * only exact name matches qualify when <code>false</code>
- * @param acceptFlags a bit mask describing if classes, interfaces or both classes and interfaces
- * are desired results. If no flags are specified, all types are returned.
- *
- * @see #ACCEPT_CLASSES
- * @see #ACCEPT_INTERFACES
- * @see #ACCEPT_ENUMS
- * @see #ACCEPT_ANNOTATIONS
- */
- public IType findType(String name, IPackageFragment pkg, boolean partialMatch, int acceptFlags) {
- if (pkg == null) return null;
-
- // Return first found (ignore duplicates).
- SingleTypeRequestor typeRequestor = new SingleTypeRequestor();
- seekTypes(name, pkg, partialMatch, acceptFlags, typeRequestor);
- return typeRequestor.getType();
- }
-
- public IJavaScriptElement findBinding(String name, int type, IPackageFragment pkg, boolean partialMatch, int acceptFlags) {
- if (pkg == null) return null;
-
- // Return first found (ignore duplicates).
- JavaElementRequestor requestor = new JavaElementRequestor();
- seekBindings(name,type, pkg, partialMatch, acceptFlags, requestor);
- IField[] fields = requestor.getFields();
- IFunction[] methods = requestor.getMethods();
- IType[] types = requestor.getTypes();
- switch (type)
- {
- case Binding.FIELD | Binding.METHOD:
- if (methods.length>0)
- return methods[0];
- case Binding.FIELD:
- return (fields.length>0)?fields[0]:null;
-
- case Binding.METHOD:
- return (methods.length>0)?methods[0]:null;
- case Binding.TYPE:
- case Binding.TYPE|Binding.PACKAGE:
- return (types.length>0)?types[0]:null;
-
- default:
- {
- if ((Binding.TYPE & type)!=0)
- {
- if (types.length>0)
- return types[0];
- }
- if ((Binding.METHOD & type)!=0)
- {
- if (methods.length>0)
- return methods[0];
- }
- if ((Binding.VARIABLE & type)!=0)
- {
- if (fields.length>0)
- return fields[0];
- }
- }
-
- }
- return null;
- }
-
- /**
- * Returns the type specified by the qualified name, or <code>null</code>
- * if none exist. The domain of
- * the search is bounded by the Java project from which this name lookup was obtained.
- *
- * @param name the name of the type to find
- * @param partialMatch partial name matches qualify when <code>true</code>,
- * only exact name matches qualify when <code>false</code>
- * @param acceptFlags a bit mask describing if classes, interfaces or both classes and interfaces
- * are desired results. If no flags are specified, all types are returned.
- *
- * @see #ACCEPT_CLASSES
- * @see #ACCEPT_INTERFACES
- * @see #ACCEPT_ENUMS
- * @see #ACCEPT_ANNOTATIONS
- */
- public IType findType(String name, boolean partialMatch, int acceptFlags) {
- NameLookup.Answer answer = findType(name, partialMatch, acceptFlags, false/*don't check restrictions*/);
- return answer == null ? null : answer.type;
- }
-
- public Answer findType(String name, boolean partialMatch, int acceptFlags, boolean checkRestrictions) {
- return findType(name, partialMatch, acceptFlags, true/*consider secondary types*/, true/*wait for indexes*/, checkRestrictions, null);
- }
- public Answer findType(String name, boolean partialMatch, int acceptFlags, boolean considerSecondaryTypes, boolean waitForIndexes, boolean checkRestrictions, IProgressMonitor monitor) {
-// int index= name.lastIndexOf('.');
- String className= null, packageName= null;
-// if (index == -1) {
- packageName= IPackageFragment.DEFAULT_PACKAGE_NAME;
- className= name;
-// } else {
-// packageName= name.substring(0, index);
-// className= name.substring(index + 1);
-// }
- if (USE_BINDING_SEARCH && searchFiles)
- return findBindingSearch(className, packageName, Binding.TYPE, partialMatch, acceptFlags, considerSecondaryTypes, waitForIndexes, checkRestrictions, monitor,true,null);
- return findType(className, packageName, partialMatch, acceptFlags, considerSecondaryTypes, waitForIndexes, checkRestrictions, monitor);
- }
-
- private IType getMemberType(IType type, String name, int dot) {
- //while (dot != -1) {
- //int start = dot+1;
- // dot = name.indexOf('.', start);
- // String typeName = name.substring(start, dot == -1 ? name.length() : dot);
- // type = type.getType(name);
- //}
- return type;
- }
-
- public boolean isPackage(String[] pkgName) {
- return this.packageFragments.get(pkgName) != null;
- }
-
- /**
- * Returns true if the given element's name matches the
- * specified <code>searchName</code>, otherwise false.
- *
- * <p>The <code>partialMatch</code> argument indicates partial matches
- * should be considered.
- * NOTE: in partialMatch mode, the case will be ignored, and the searchName must already have
- * been lowercased.
- */
- protected boolean nameMatches(String searchName, IJavaScriptElement element, boolean partialMatch) {
- if (partialMatch) {
- // partial matches are used in completion mode, thus case insensitive mode
- return element.getElementName().toLowerCase().startsWith(searchName);
- } else {
- return element.getElementName().equals(searchName);
- }
- }
-
- /**
- * Returns true if the given cu's name matches the
- * specified <code>searchName</code>, otherwise false.
- *
- * <p>The <code>partialMatch</code> argument indicates partial matches
- * should be considered.
- * NOTE: in partialMatch mode, the case will be ignored, and the searchName must already have
- * been lowercased.
- */
- protected boolean nameMatches(String searchName, IJavaScriptUnit cu, boolean partialMatch) {
- if (partialMatch) {
- // partial matches are used in completion mode, thus case insensitive mode
- return cu.getElementName().toLowerCase().startsWith(searchName);
- } else {
- return Util.equalsIgnoreJavaLikeExtension(cu.getElementName(), searchName);
- }
- }
-
- /**
- * Notifies the given requestor of all package fragments with the
- * given name. Checks the requestor at regular intervals to see if the
- * requestor has canceled. The domain of
- * the search is bounded by the <code>IJavaScriptProject</code>
- * this <code>NameLookup</code> was obtained from.
- *
- * @param partialMatch partial name matches qualify when <code>true</code>;
- * only exact name matches qualify when <code>false</code>
- */
- public void seekPackageFragments(String name, boolean partialMatch, IJavaElementRequestor requestor) {
-/* if (VERBOSE) {
- Util.verbose(" SEEKING PACKAGE FRAGMENTS"); //$NON-NLS-1$
- Util.verbose(" -> name: " + name); //$NON-NLS-1$
- Util.verbose(" -> partial match:" + partialMatch); //$NON-NLS-1$
- }
- */
- for (int i = 0; i < this.packageFragmentRoots.length; i++) {
-
-
- IJavaScriptElement[] children;
- try {
- if (this.searchFiles || packageFragmentRoots[i].isLibrary())
- {
- children = packageFragmentRoots[i].getChildren();
- for (int j = 0; j < children.length; j++) {
- requestor.acceptPackageFragment((IPackageFragment)children[j]);
- }
- }
- } catch (JavaScriptModelException e) {}
-
- }
-
-
-
-// if (partialMatch) {
-// String[] splittedName = splitPackageName(name);
-// Object[][] keys = this.packageFragments.keyTable;
-// for (int i = 0, length = keys.length; i < length; i++) {
-// if (requestor.isCanceled())
-// return;
-// String[] pkgName = (String[]) keys[i];
-// if (pkgName != null && Util.startsWithIgnoreCase(pkgName, splittedName)) {
-// Object value = this.packageFragments.valueTable[i];
-// if (value instanceof PackageFragmentRoot) {
-// PackageFragmentRoot root = (PackageFragmentRoot) value;
-// requestor.acceptPackageFragment(root.getPackageFragment(pkgName));
-// } else {
-// IPackageFragmentRoot[] roots = (IPackageFragmentRoot[]) value;
-// for (int j = 0, length2 = roots.length; j < length2; j++) {
-// if (requestor.isCanceled())
-// return;
-// PackageFragmentRoot root = (PackageFragmentRoot) roots[j];
-// requestor.acceptPackageFragment(root.getPackageFragment(pkgName));
-// }
-// }
-// }
-// }
-// } else {
-// String[] splittedName = splitPackageName(name);
-// Object value = this.packageFragments.get(splittedName);
-// if (value instanceof PackageFragmentRoot) {
-// requestor.acceptPackageFragment(((PackageFragmentRoot) value).getPackageFragment(splittedName));
-// } else {
-// IPackageFragmentRoot[] roots = (IPackageFragmentRoot[]) value;
-// if (roots != null) {
-// for (int i = 0, length = roots.length; i < length; i++) {
-// if (requestor.isCanceled())
-// return;
-// PackageFragmentRoot root = (PackageFragmentRoot) roots[i];
-// requestor.acceptPackageFragment(root.getPackageFragment(splittedName));
-// }
-// }
-// }
-// }
-// if (name==null || name.equals(IPackageFragment.DEFAULT_PACKAGE_NAME))
-// {
-// for (int i = 0; i < this.packageFragmentRoots.length; i++) {
-// if (packageFragmentRoots[i] instanceof LibraryFragmentRoot)
-// {
-// IJavaScriptElement[] children;
-// try {
-// children = packageFragmentRoots[i].getChildren();
-// for (int j = 0; j < children.length; j++) {
-// requestor.acceptPackageFragment((IPackageFragment)children[j]);
-// }
-// } catch (JavaScriptModelException e) {
-// }
-// }
-// }
-// }
- }
-
-// private String [] splitPackageName(String name)
-// {
-// String[] strings;
-// int index=Util.indexOfJavaLikeExtension(name);
-// if (index>=0)
-// {
-// String extension=name.substring(index+1);
-// name=name.substring(0,index);
-// strings= Util.splitOn('.', name, 0, name.length());
-// strings[strings.length-1]=strings[strings.length-1]+extension;
-// }
-// else
-// strings = Util.splitOn('.', name, 0, name.length());
-//
-// return strings;
-// }
- /**
- * Notifies the given requestor of all types (classes and interfaces) in the
- * given package fragment with the given (unqualified) name.
- * Checks the requestor at regular intervals to see if the requestor
- * has canceled. If the given package fragment is <code>null</code>, all types in the
- * project whose simple name matches the given name are found.
- *
- * @param name The name to search
- * @param pkg The corresponding package fragment
- * @param partialMatch partial name matches qualify when <code>true</code>;
- * only exact name matches qualify when <code>false</code>
- * @param acceptFlags a bit mask describing if classes, interfaces or both classes and interfaces
- * are desired results. If no flags are specified, all types are returned.
- * @param requestor The requestor that collects the result
- *
- * @see #ACCEPT_CLASSES
- * @see #ACCEPT_INTERFACES
- * @see #ACCEPT_ENUMS
- * @see #ACCEPT_ANNOTATIONS
- */
- public void seekTypes(String name, IPackageFragment pkg, boolean partialMatch, int acceptFlags, IJavaElementRequestor requestor) {
-/* if (VERBOSE) {
- Util.verbose(" SEEKING TYPES"); //$NON-NLS-1$
- Util.verbose(" -> name: " + name); //$NON-NLS-1$
- Util.verbose(" -> pkg: " + ((JavaElement) pkg).toStringWithAncestors()); //$NON-NLS-1$
- Util.verbose(" -> partial match:" + partialMatch); //$NON-NLS-1$
- }
-*/
- String matchName= partialMatch ? name.toLowerCase() : name;
- if (pkg == null) {
- findAllTypes(matchName, partialMatch, acceptFlags, requestor);
- return;
- }
- IPackageFragmentRoot root= (IPackageFragmentRoot) pkg.getParent();
- try {
-
- // look in working copies first
- int firstDot = -1;
- String topLevelTypeName = matchName;
- int packageFlavor= root.getKind();
-// if (this.typesInWorkingCopies != null || packageFlavor == IPackageFragmentRoot.K_SOURCE) {
-// firstDot = matchName.indexOf('.');
-// if (!partialMatch)
-// topLevelTypeName = firstDot == -1 ? matchName : matchName.substring(0, firstDot);
-// }
- if (this.typesInWorkingCopies != null) {
- if (seekTypesInWorkingCopies(matchName, pkg, firstDot, partialMatch, topLevelTypeName, acceptFlags, requestor))
- return;
- }
-
- // 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 :
- seekTypesInSourcePackage(matchName, pkg, firstDot, partialMatch, topLevelTypeName, acceptFlags, requestor);
- break;
- default :
- return;
- }
- } catch (JavaScriptModelException e) {
- return;
- }
- }
-
-
- public void seekBindings(String name, int bindingType, IPackageFragment pkg, boolean partialMatch, int acceptFlags, IJavaElementRequestor requestor) {
- /* if (VERBOSE) {
- Util.verbose(" SEEKING TYPES"); //$NON-NLS-1$
- Util.verbose(" -> name: " + name); //$NON-NLS-1$
- Util.verbose(" -> pkg: " + ((JavaElement) pkg).toStringWithAncestors()); //$NON-NLS-1$
- Util.verbose(" -> partial match:" + partialMatch); //$NON-NLS-1$
- }
- */
- String matchName= partialMatch ? name.toLowerCase() : name;
- if (pkg == null) {
- findAllBindings(matchName, bindingType, partialMatch, acceptFlags, requestor);
- return;
- }
- IPackageFragmentRoot root= (IPackageFragmentRoot) pkg.getParent();
- try {
-
- // look in working copies first
- int firstDot = -1;
- String topLevelTypeName = null;
- int packageFlavor= root.getKind();
- if (this.typesInWorkingCopies != null || packageFlavor == IPackageFragmentRoot.K_SOURCE) {
- firstDot = matchName.indexOf('.');
- if (!partialMatch)
- topLevelTypeName = firstDot == -1 ? matchName : matchName.substring(0, firstDot);
- }
- if (this.bindingsInWorkingCopies != null) {
- if (seekBindingsInWorkingCopies(matchName,bindingType, firstDot, partialMatch, topLevelTypeName, acceptFlags, requestor))
- return;
- }
-
- // look in model
- switch (packageFlavor) {
- case IPackageFragmentRoot.K_BINARY :
-// matchName= matchName.replace('.', '$');
- seekBindingsInBinaryPackage(matchName, bindingType,pkg, partialMatch, acceptFlags, requestor);
- break;
- case IPackageFragmentRoot.K_SOURCE :
- seekBindingsInSourcePackage(matchName, bindingType,pkg, firstDot, partialMatch, topLevelTypeName, acceptFlags, requestor);
- break;
- default :
- return;
- }
- } catch (JavaScriptModelException e) {
- return;
- }
- }
-
-
- /**
- * Performs type search in a binary package.
- */
-// protected void seekTypesInBinaryPackage(String name, IPackageFragment pkg, boolean partialMatch, int acceptFlags, IJavaElementRequestor requestor) {
-// long start = -1;
-// if (VERBOSE)
-// start = System.currentTimeMillis();
-// try {
-// if (!partialMatch) {
-// // exact match
-// if (requestor.isCanceled()) return;
-// ClassFile classFile = new ClassFile((PackageFragment) pkg, name);
-// if (classFile.existsUsingJarTypeCache()) {
-// IType type = classFile.getType();
-// if (acceptType(type, acceptFlags, false/*not a source type*/)) {
-// requestor.acceptType(type);
-// }
-// }
-// } else {
-// IJavaScriptElement[] classFiles= null;
-// try {
-// classFiles= pkg.getChildren();
-// } catch (JavaScriptModelException npe) {
-// return; // the package is not present
-// }
-// int length= classFiles.length;
-// 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())
-// return;
-// IJavaScriptElement classFile= classFiles[i];
-// // MatchName will never have the extension ".class" and the elementName always will.
-// String elementName = classFile.getElementName();
-// if (elementName.regionMatches(true /*ignore case*/, 0, name, 0, matchLength)) {
-// IType type = ((ClassFile) classFile).getType();
-// String typeName = type.getElementName();
-// if (typeName.length() > 0 && !Character.isDigit(typeName.charAt(0))) { //not an anonymous type
-// if (nameMatches(unqualifiedName, type, true/*partial match*/) && acceptType(type, acceptFlags, false/*not a source type*/))
-// requestor.acceptType(type);
-// }
-// }
-// }
-// }
-// } finally {
-// if (VERBOSE)
-// this.timeSpentInSeekTypesInBinaryPackage += System.currentTimeMillis()-start;
-// }
-// }
-//
- protected void seekBindingsInBinaryPackage(String name, int bindingType,IPackageFragment pkg, boolean partialMatch, int acceptFlags, IJavaElementRequestor requestor) {
- long start = -1;
- if (VERBOSE)
- start = System.currentTimeMillis();
- try {
- this.acceptedCUs.clear();
- IJavaScriptElement[] classFiles= null;
- try {
- classFiles= pkg.getChildren();
- } catch (JavaScriptModelException npe) {
- return; // the package is not present
- }
- int length= classFiles.length;
- if (!partialMatch) {
- for (int i = 0; i < length; i++) {
- ClassFile classFile=(ClassFile)classFiles[i];
- if (this.acceptedCUs.contains(classFile))
- continue;
- switch (bindingType) {
- case Binding.TYPE:
- case Binding.TYPE | Binding.PACKAGE:
- IType type = classFile.getType(name);
- if (acceptType(type, acceptFlags, false/*not a source type*/)) {
- acceptedCUs.add(classFile);
- requestor.acceptType(type);
- }
-
- break;
- case Binding.VARIABLE:
-// String cuName = cu.getElementName();
-// int lastDot = cuName.lastIndexOf('.');
-// if (lastDot != topLevelTypeName.length() || !topLevelTypeName.regionMatches(0, cuName, 0, lastDot))
-// continue;
- IField field = classFile.getField(name);
- if (field.exists()) {
- acceptedCUs.add(classFile);
- requestor.acceptField(field);
- }
-
- break;
-
- case Binding.METHOD:
-// String cuName = cu.getElementName();
-// int lastDot = cuName.lastIndexOf('.');
-// if (lastDot != topLevelTypeName.length() || !topLevelTypeName.regionMatches(0, cuName, 0, lastDot))
-// continue;
- IFunction method = classFile.getFunction(name, null);
- if (method.exists()) {
- acceptedCUs.add(classFile);
- requestor.acceptMethod(method);
- }
- break;
- case Binding.METHOD | Binding.VARIABLE:
- method = classFile.getFunction(name, null);
- if (method!=null
- && method.exists()) {
- acceptedCUs.add(classFile);
- requestor.acceptMethod(method);
- } else
- {
- field = classFile.getField(name);
- if (field!=null && field.exists())
- {
- acceptedCUs.add(classFile);
- requestor.acceptField(field);
-
- }
- }
- break;
- default:
- {
- if ((Binding.TYPE & bindingType)!=0)
- {
- IType thisType = classFile.getType(name);
- if (acceptType(thisType, acceptFlags, false/*not a source type*/)) {
- acceptedCUs.add(classFile);
- requestor.acceptType(thisType);
- }
- }
- if ((Binding.METHOD & bindingType)!=0)
- {
- method = classFile.getFunction(name, null);
- if (method!=null && method.exists()) {
- acceptedCUs.add(classFile);
- requestor.acceptMethod(method);
- }
- }
- if ((Binding.VARIABLE & bindingType)!=0)
- {
- field = classFile.getField(name);
- if (field!=null && field.exists()) {
- acceptedCUs.add(classFile);
- requestor.acceptField(field);
- }
- }
- }
- }
- }
- } 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())
- return;
- IJavaScriptElement classFile= classFiles[i];
- // MatchName will never have the extension ".class" and the elementName always will.
- String elementName = classFile.getElementName();
- if (elementName.regionMatches(true /*ignore case*/, 0, name, 0, matchLength)) {
- IType type = ((ClassFile) classFile).getType();
- String typeName = type.getElementName();
- if (typeName.length() > 0 && !Character.isDigit(typeName.charAt(0))) { //not an anonymous type
- if (nameMatches(unqualifiedName, type, true/*partial match*/) && acceptType(type, acceptFlags, false/*not a source type*/))
- requestor.acceptType(type);
- }
- }
- }
- }
- } finally {
- if (VERBOSE)
- this.timeSpentInSeekTypesInBinaryPackage += System.currentTimeMillis()-start;
- }
- }
-
- /**
- * Performs type search in a source package.
- */
- protected void seekTypesInSourcePackage(
- String name,
- IPackageFragment pkg,
- int firstDot,
- boolean partialMatch,
- String topLevelTypeName,
- int acceptFlags,
- IJavaElementRequestor requestor) {
-
- long start = -1;
- if (VERBOSE)
- start = System.currentTimeMillis();
- try {
- if (!partialMatch) {
- try {
- IJavaScriptElement[] compilationUnits = pkg.getChildren();
- for (int i = 0, length = compilationUnits.length; i < length; i++) {
- if (requestor.isCanceled())
- return;
- IJavaScriptElement cu = compilationUnits[i];
-// String cuName = cu.getElementName();
- //int lastDot = cuName.lastIndexOf('.');
- //if (lastDot != topLevelTypeName.length() || !topLevelTypeName.regionMatches(0, cuName, 0, lastDot)) \
- //if(topLevelTypeName!=null && !topLevelTypeName.equals(cuName))
- // continue;
- IType type = ((IJavaScriptUnit) cu).getType(name);
- //type = getMemberType(type, name, firstDot);
- if (acceptType(type, acceptFlags, true/*a source type*/)) { // accept type checks for existence
- requestor.acceptType(type);
- break; // since an exact match was requested, no other matching type can exist
- }
- }
- } catch (JavaScriptModelException e) {
- // package doesn't exist -> ignore
- }
- } else {
- try {
- String cuPrefix = firstDot == -1 ? name : name.substring(0, firstDot);
- IJavaScriptElement[] compilationUnits = pkg.getChildren();
- for (int i = 0, length = compilationUnits.length; i < length; i++) {
- if (requestor.isCanceled())
- return;
- IJavaScriptElement cu = compilationUnits[i];
- if (!cu.getElementName().toLowerCase().startsWith(cuPrefix))
- continue;
- try {
- IType[] types = ((IJavaScriptUnit) cu).getTypes();
- for (int j = 0, typeLength = types.length; j < typeLength; j++)
- seekTypesInTopLevelType(name, firstDot, types[j], requestor, acceptFlags);
- } catch (JavaScriptModelException e) {
- // cu doesn't exist -> ignore
- }
- }
- } catch (JavaScriptModelException e) {
- // package doesn't exist -> ignore
- }
- }
- } finally {
- if (VERBOSE)
- this.timeSpentInSeekTypesInSourcePackage += System.currentTimeMillis()-start;
- }
- }
-
- protected void seekBindingsInSourcePackage(
- String name,
- int bindingType,
- IPackageFragment pkg,
- int firstDot,
- boolean partialMatch,
- String topLevelTypeName,
- int acceptFlags,
- IJavaElementRequestor requestor) {
-
- long start = -1;
- if (VERBOSE)
- start = System.currentTimeMillis();
- try {
- if (!partialMatch) {
- try {
- IJavaScriptElement[] compilationUnits = pkg.getChildren();
- for (int i = 0, length = compilationUnits.length; i < length; i++) {
- if (requestor.isCanceled())
- return;
- IJavaScriptElement cu = compilationUnits[i];
- if (cu instanceof IJavaScriptUnit && ((IJavaScriptUnit)cu).isWorkingCopy())
- continue;
- if (this.acceptedCUs.contains(cu))
- continue;
-
- switch (bindingType) {
- case Binding.TYPE:
-// String cuName = cu.getElementName();
-// int lastDot = cuName.lastIndexOf('.');
-// if (lastDot != topLevelTypeName.length() || !topLevelTypeName.regionMatches(0, cuName, 0, lastDot))
-// continue;
- IType type = ((IJavaScriptUnit) cu).getType(topLevelTypeName);
- type = getMemberType(type, name, firstDot);
- if (acceptType(type, acceptFlags, true/*a source type*/)) { // accept type checks for existence
- acceptedCUs.add(cu);
- requestor.acceptType(type);
- break; // since an exact match was requested, no other matching type can exist
- }
-
- break;
- case Binding.VARIABLE:
-// String cuName = cu.getElementName();
-// int lastDot = cuName.lastIndexOf('.');
-// if (lastDot != topLevelTypeName.length() || !topLevelTypeName.regionMatches(0, cuName, 0, lastDot))
-// continue;
- IField field = ((IJavaScriptUnit) cu).getField(name);
- if (field.exists()) {
- acceptedCUs.add(cu);
- requestor.acceptField(field);
- }
-
- break;
-
- case Binding.METHOD:
-// String cuName = cu.getElementName();
-// int lastDot = cuName.lastIndexOf('.');
-// if (lastDot != topLevelTypeName.length() || !topLevelTypeName.regionMatches(0, cuName, 0, lastDot))
-// continue;
- IFunction method = ((IJavaScriptUnit) cu).getFunction(name, null);
- if (method.exists()) {
- acceptedCUs.add(cu);
- requestor.acceptMethod(method);
- }
- break;
- case Binding.METHOD | Binding.VARIABLE:
- method = ((IJavaScriptUnit) cu).getFunction(name, null);
- if (method!=null)
- if (method.exists()) {
- acceptedCUs.add(cu);
- requestor.acceptMethod(method);
- } else
- {
- field = ((IJavaScriptUnit) cu).getField(name);
- if (field.exists()) {
- acceptedCUs.add(cu);
- requestor.acceptField(field);
- }
- }
- break;
-
- default:
- break;
- }
-
- }
- } catch (JavaScriptModelException e) {
- // package doesn't exist -> ignore
- }
- } else {
- try {
- String cuPrefix = firstDot == -1 ? name : name.substring(0, firstDot);
- IJavaScriptElement[] compilationUnits = pkg.getChildren();
- for (int i = 0, length = compilationUnits.length; i < length; i++) {
- if (requestor.isCanceled())
- return;
- IJavaScriptElement cu = compilationUnits[i];
- if (!cu.getElementName().toLowerCase().startsWith(cuPrefix))
- continue;
- try {
- IType[] types = ((IJavaScriptUnit) cu).getTypes();
- for (int j = 0, typeLength = types.length; j < typeLength; j++)
- seekTypesInTopLevelType(name, firstDot, types[j], requestor, acceptFlags);
- } catch (JavaScriptModelException e) {
- // cu doesn't exist -> ignore
- }
- }
- } catch (JavaScriptModelException e) {
- // package doesn't exist -> ignore
- }
- }
- } finally {
- if (VERBOSE)
- this.timeSpentInSeekTypesInSourcePackage += System.currentTimeMillis()-start;
- }
- }
-
- /**
- * Notifies the given requestor of all types (classes and interfaces) in the
- * given type with the given (possibly qualified) name. Checks
- * the requestor at regular intervals to see if the requestor
- * has canceled.
- */
- protected boolean seekTypesInType(String prefix, int firstDot, IType type, IJavaElementRequestor requestor, int acceptFlags) {
- IType[] types= null;
- try {
- types= type.getTypes();
- } catch (JavaScriptModelException npe) {
- return false; // the enclosing type is not present
- }
- int length= types.length;
- if (length == 0) return false;
-
- String memberPrefix = prefix;
- boolean isMemberTypePrefix = false;
- if (firstDot != -1) {
- memberPrefix= prefix.substring(0, firstDot);
- isMemberTypePrefix = true;
- }
- for (int i= 0; i < length; i++) {
- if (requestor.isCanceled())
- return false;
- IType memberType= types[i];
- if (memberType.getElementName().toLowerCase().startsWith(memberPrefix))
- if (isMemberTypePrefix) {
- String subPrefix = prefix.substring(firstDot + 1, prefix.length());
- return seekTypesInType(subPrefix, subPrefix.indexOf('.'), memberType, requestor, acceptFlags);
- } else {
- if (acceptType(memberType, acceptFlags, true/*a source type*/)) {
- requestor.acceptMemberType(memberType);
- return true;
- }
- }
- }
- return false;
- }
-
- protected boolean seekTypesInTopLevelType(String prefix, int firstDot, IType topLevelType, IJavaElementRequestor requestor, int acceptFlags) {
- if (!topLevelType.getElementName().toLowerCase().startsWith(prefix))
- return false;
- if (firstDot == -1) {
- if (acceptType(topLevelType, acceptFlags, true/*a source type*/)) {
- requestor.acceptType(topLevelType);
- return true;
- }
- } else {
- return seekTypesInType(prefix, firstDot, topLevelType, requestor, acceptFlags);
- }
- return false;
- }
-
- /*
- * Seeks the type with the given name in the map of types with precedence (coming from working copies)
- * Return whether a type has been found.
- */
- protected boolean seekTypesInWorkingCopies(
- String name,
- IPackageFragment pkg,
- int firstDot,
- boolean partialMatch,
- String topLevelTypeName,
- int acceptFlags,
- IJavaElementRequestor requestor) {
-
- if (!partialMatch) {
- HashMap typeMap = (HashMap) (this.typesInWorkingCopies == null ? null : this.typesInWorkingCopies.get(pkg));
- if (typeMap != null) {
- Object object = typeMap.get(topLevelTypeName);
- if (object instanceof IType) {
- IType type = getMemberType((IType) object, name, firstDot);
- if (acceptType(type, acceptFlags, true/*a source type*/)) {
- requestor.acceptType(type);
- return true; // don't continue with compilation unit
- }
- } else if (object instanceof IType[]) {
- if (object == NO_TYPES) return true; // all types where deleted -> type is hidden
- IType[] topLevelTypes = (IType[]) object;
- for (int i = 0, length = topLevelTypes.length; i < length; i++) {
- if (requestor.isCanceled())
- return false;
- IType type = getMemberType(topLevelTypes[i], name, firstDot);
- if (acceptType(type, acceptFlags, true/*a source type*/)) {
- requestor.acceptType(type);
- return true; // return the first one
- }
- }
- }
- }
- } else {
- HashMap typeMap = (HashMap) (this.typesInWorkingCopies == null ? null : this.typesInWorkingCopies.get(pkg));
- if (typeMap != null) {
- Iterator iterator = typeMap.values().iterator();
- while (iterator.hasNext()) {
- if (requestor.isCanceled())
- return false;
- Object object = iterator.next();
- if (object instanceof IType) {
- seekTypesInTopLevelType(name, firstDot, (IType) object, requestor, acceptFlags);
- } else if (object instanceof IType[]) {
- IType[] topLevelTypes = (IType[]) object;
- for (int i = 0, length = topLevelTypes.length; i < length; i++)
- seekTypesInTopLevelType(name, firstDot, topLevelTypes[i], requestor, acceptFlags);
- }
- }
- }
- }
- return false;
- }
-
-
- private boolean checkBindingAccept(String topLevelTypeName,HashMap []bindingsMap,int bindingType,IJavaElementRequestor requestor)
- {
- Object object = bindingsMap[bindingType].get(topLevelTypeName);
- if (object instanceof IJavaScriptElement) {
- if (doAcceptBinding((IJavaScriptElement)object, bindingType , true/*a source type*/,requestor)) {
- return true; // don't continue with compilation unit
- }
- } else if (object instanceof IJavaScriptElement[]) {
- if (object == NO_BINDINGS) return true; // all types where deleted -> type is hidden
- IJavaScriptElement[] topLevelElements = (IJavaScriptElement[]) object;
- boolean isAnyBindingAccepted = false;
- for (int i = 0, length = topLevelElements.length; i < length; i++) {
- if (requestor.isCanceled())
- return false;
- if (doAcceptBinding(topLevelElements[i], bindingType, true/*a source type*/,requestor)) {
- isAnyBindingAccepted = true;
- }
- }
- return isAnyBindingAccepted;
- }
- return false;
-
- }
- protected boolean seekBindingsInWorkingCopies(
- String name,
- int bindingType,
- int firstDot,
- boolean partialMatch,
- String topLevelTypeName,
- int acceptFlags,
- IJavaElementRequestor requestor) {
-
- bindingType=bindingType & Binding.BASIC_BINDINGS_MASK;
- if (!partialMatch) {
- HashMap []bindingsMap = (this.bindingsInWorkingCopies == null ? null : this.bindingsInWorkingCopies);
- if (bindingsMap != null) {
- if (checkBindingAccept(topLevelTypeName, bindingsMap, bindingType, requestor))
- return true;
- if ((bindingType&Binding.VARIABLE)>0 && bindingType!=Binding.VARIABLE)
- if (checkBindingAccept(topLevelTypeName, bindingsMap, Binding.VARIABLE, requestor))
- return true;
- if ((bindingType&Binding.LOCAL)>0 && bindingType!=Binding.LOCAL)
- if (checkBindingAccept(topLevelTypeName, bindingsMap, Binding.LOCAL, requestor))
- return true;
- if ((bindingType&Binding.METHOD)>0 && bindingType!=Binding.METHOD)
- if (checkBindingAccept(topLevelTypeName, bindingsMap, Binding.METHOD, requestor))
- return true;
- if ((bindingType&Binding.TYPE)>0 && bindingType!=Binding.TYPE)
- if (checkBindingAccept(topLevelTypeName, bindingsMap, Binding.TYPE, requestor))
- return true;
- }
- } else {
- HashMap[] bindingsMap = (this.bindingsInWorkingCopies == null ? null : this.bindingsInWorkingCopies);
- if (bindingsMap != null) {
- Iterator iterator = bindingsMap[bindingType].values().iterator();
- while (iterator.hasNext()) {
- if (requestor.isCanceled())
- return false;
- Object object = iterator.next();
- if (object instanceof IType) {
- seekTypesInTopLevelType(name, firstDot, (IType) object, requestor, acceptFlags);
- } else if (object instanceof IType[]) {
- IType[] topLevelTypes = (IType[]) object;
- for (int i = 0, length = topLevelTypes.length; i < length; i++)
- seekTypesInTopLevelType(name, firstDot, topLevelTypes[i], requestor, acceptFlags);
- }
- }
- }
- }
- return false;
- }
-
- public static final boolean USE_BINDING_SEARCH=true;
- private HandleFactory handleFactory;
- protected IJavaScriptSearchScope searchScope;
- public Answer findBindingSearch(
- String bindingName,
- String packageName,
- int bindingType,
- boolean partialMatch,
- int acceptFlags,
- boolean considerSecondaryTypes,
- boolean waitForIndexes,
- boolean checkRestrictions,
- IProgressMonitor progressMonitor, boolean returnMultiple, String exclude) {
-
-
- class MyRequestor implements IJavaElementRequestor
- {
- ArrayList element;
-
- public void acceptField(IField field) {
- if(element == null)
- element = new ArrayList();
- element.add(field);
- }
-
- public void acceptInitializer(IInitializer initializer) {
- }
-
- public void acceptMemberType(IType type) {
- if(element == null)
- element = new ArrayList();
- element.add(type);
- }
-
- public void acceptMethod(IFunction method) {
- if(element == null)
- element = new ArrayList();
- element.add(method);
-
- }
-
- public void acceptPackageFragment(
- IPackageFragment packageFragment) {
- }
-
- public void acceptType(IType type) {
- if(element == null)
- element = new ArrayList();
- element.add(type);
- }
-
- public boolean isCanceled() {
- return false;
- }
-
- }
-
- if (this.searchScope==null)
- this.searchScope = BasicSearchEngine.createJavaSearchScope(packageFragmentRoots);
-
- ArrayList foundAnswers=new ArrayList();
- 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) {
- for(int i = 0; i < requestor.element.size(); i++) {
- IOpenable openable = ((IJavaScriptElement)requestor.element.get(i)).getOpenable();
- if (excludePath!=null && ((IJavaScriptElement)requestor.element.get(i)).getPath().equals(excludePath))
- continue;
- if (!returnMultiple) {
- return new Answer(openable, null);
- } else
- foundAnswers.add(openable);
- }
- requestor.element=null;
- }
- /*
- * if (true){ findTypes(new String(prefix), storage,
- * NameLookup.ACCEPT_CLASSES | NameLookup.ACCEPT_INTERFACES); return; }
- */
- try {
-
-
-
- IRestrictedAccessBindingRequestor bindingAcceptor = getRestrictedAccessRequestor();
- if (exclude!=null)
- exclude=exclude.replace('\\', '/');
- bindingAcceptor.setExcludePath(exclude);
-
- try {
- int matchRule = SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE;
- new BasicSearchEngine().searchAllBindingNames(
- CharOperation.NO_CHAR,
- bindingName.toCharArray(),
- bindingType,
- matchRule, // not case sensitive
- /*IJavaScriptSearchConstants.TYPE,*/ this.searchScope,
- bindingAcceptor, IJavaScriptSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
- false,
- progressMonitor);
- if (bindingAcceptor.getFoundPath()!=null)
- {
-
- Object[] foundPaths = bindingAcceptor.getFoundPaths().toArray();
- for (int i = 0; i < foundPaths.length; ++i) {
- String path = (String) foundPaths[i];
-
- IOpenable openable ; //= createOpenable(getRestrictedAccessRequestor().getFoundPath(), this.searchScope);
-// if (openable!=null)
-// return new Answer(openable, null);
-
- if (this.handleFactory == null)
- this.handleFactory = new HandleFactory();
-
- openable = this.handleFactory.createOpenable(path, this.searchScope);
-
-
- if (openable!=null)
- {
- if (!returnMultiple)
- return new Answer(openable, null);
- else
- foundAnswers.add(openable);
- }
- }
- if (foundAnswers.size()>0 && returnMultiple)
- return new Answer(foundAnswers.toArray(),null);
- }
-
- } catch (OperationCanceledException e) {
- return findBinding( bindingName,packageName,bindingType,partialMatch,acceptFlags,considerSecondaryTypes,waitForIndexes,
- checkRestrictions,progressMonitor);
- }
- finally
- {
- bindingAcceptor.reset();
- }
- } catch (JavaScriptModelException e) {
- return findBinding( bindingName,packageName,bindingType,partialMatch,acceptFlags,considerSecondaryTypes,waitForIndexes,
- checkRestrictions,progressMonitor);
- }
-
- if (foundAnswers.size()>0 && returnMultiple)
- return new Answer(foundAnswers.toArray(),null);
- return null;
- }
- /* creates an openable from PackageFragmentRoots in this lookup
- * i thought i was going to use, but found another way. This may still
- * be faster then the current method so leaveing in case...
- *
- * */
- public IOpenable createOpenable(String resourcePath, IJavaScriptSearchScope scope) {
- if(packageFragmentRoots==null) return null;
- IPath resourceP = new Path(resourcePath);
- for(int i = 0;i<packageFragmentRoots.length;i++) {
- IPackageFragmentRoot root = packageFragmentRoots[i];
- IPath fragPath = root.getPath();
-
- String fileName = resourceP.lastSegment();
- IPath rootPostFix=null;
-
- if( root.isLanguageRuntime() /*&& restrictToLanguage*/) {
- int rootSegs = fragPath.segmentCount();
- int resourceSegs = resourceP.segmentCount();
- if(rootSegs>resourceSegs)
- rootPostFix = (fragPath.removeFirstSegments(rootSegs - resourceSegs )).setDevice(null).makeAbsolute();
- }
-
- if(fragPath.isPrefixOf(resourceP) || (rootPostFix!=null && rootPostFix.equals(resourceP.makeAbsolute()))) {
- if(root instanceof LibraryFragmentRoot /*&& (!restrictToLanguage || root.isLanguageRuntime() )*/ ) {
- IClassFile file = root.getPackageFragment(root.getPath().toString()).getClassFile(root.getPath().toString());
- return file;
-
- }else{
- if(resourceP.toFile().exists()){
- IClassFile file = root.getPackageFragment(resourcePath).getClassFile(resourcePath);
- return file;
- }else {
- String pkgName = resourcePath.substring(fragPath.toString().length());
- int indexName = pkgName.indexOf(fileName);
- if(indexName>-1) {
- pkgName = pkgName.substring(0,indexName-1);
- }
- IJavaScriptUnit file = root.getPackageFragment(pkgName).getJavaScriptUnit((fileName));
- return file;
- }
- }
-
-
- }
-
- }
- return null;
-
-
- }
-
-
- public void setScriptFile(IInferenceFile compUnit)
- {
- InferrenceProvider[] inferenceProviders = InferrenceManager.getInstance().getInferenceProviders(compUnit);
- if (inferenceProviders!=null && inferenceProviders.length>0)
- {
- for(int i = 0; i < inferenceProviders.length; i++) {
- ResolutionConfiguration resolutionConfiguration = inferenceProviders[i].getResolutionConfiguration();
- if (resolutionConfiguration!=null)
- searchFiles=resolutionConfiguration.searchAllFiles();
- if(!searchFiles)
- break;
- }
- }
- }
-
-}
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
deleted file mode 100644
index 08d7d862..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/NamedMember.java
+++ /dev/null
@@ -1,206 +0,0 @@
-/*******************************************************************************
- * 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
- * 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.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-
-public abstract class NamedMember extends Member {
-
- /*
- * This element's name, or an empty <code>String</code> if this
- * element does not have a name.
- */
- protected String name;
-
- public NamedMember(JavaElement parent, String name) {
- super(parent);
- this.name = name;
- }
-
- public String getElementName() {
- return this.name;
- }
-
- protected String getKey(IField field, boolean forceOpen) throws JavaScriptModelException {
- StringBuffer key = new StringBuffer();
-
- // declaring class
-
- IJavaScriptElement parent = field.getParent();
- String declaringKey = "??"; //$NON-NLS-1$
- if (parent instanceof IJavaScriptUnit)
- declaringKey = getKey((IJavaScriptUnit) parent, forceOpen);
- else if (parent instanceof IType)
- declaringKey = getKey((IType) parent, forceOpen);
- key.append(declaringKey);
-
- // field name
- key.append('.');
- key.append(field.getElementName());
-
- return key.toString();
- }
-
- protected String getKey(IFunction method, boolean forceOpen) throws JavaScriptModelException {
- StringBuffer key = new StringBuffer();
-
- // declaring class
- IJavaScriptElement parent = method.getParent();
- String declaringKey = "??"; //$NON-NLS-1$
- if (parent instanceof IJavaScriptUnit)
- declaringKey = getKey((IJavaScriptUnit) parent, forceOpen);
- else if (parent instanceof IType)
- declaringKey = getKey((IType) parent, forceOpen);
- key.append(declaringKey);
-
- // selector
- key.append('.');
- String selector = method.getElementName();
- key.append(selector);
-
- // parameters
- key.append('(');
- String[] parameters = method.getParameterNames();
- for (int i = 0, length = parameters.length; i < length; i++)
- key.append(parameters[i].replace('.', '/'));
- key.append(')');
-
- // return type
- if (forceOpen)
- {
- if (method.getReturnType()!=null)
- key.append(method.getReturnType().replace('.', '/'));
- }
- else
- key.append('V');
-
- return key.toString();
- }
-
- protected String getKey(IJavaScriptUnit unit, boolean forceOpen) throws JavaScriptModelException {
- StringBuffer key = new StringBuffer();
- key.append('U');
- String packageName = unit.getParent().getElementName();
- key.append(packageName.replace('.', '/'));
- if (packageName.length() > 0)
- key.append('/');
- key.append(unit.getElementName());
- key.append(';');
- return key.toString();
- }
-
- protected String getKey(IType type, boolean forceOpen) throws JavaScriptModelException {
- StringBuffer key = new StringBuffer();
- key.append('L');
- String packageName = type.getPackageFragment().getElementName();
- key.append(packageName.replace('.', '/'));
- if (packageName.length() > 0)
- key.append('/');
- 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);
- if (!mainTypeName.equals(topLevelTypeName)) {
- key.append(mainTypeName);
- key.append('~');
- }
- }
- key.append(typeQualifiedName);
- key.append(';');
- return key.toString();
- }
-
- protected String getFullyQualifiedParameterizedName(String fullyQualifiedName, String uniqueKey) throws JavaScriptModelException {
- String[] typeArguments = new String[0];
- int length = typeArguments.length;
- if (length == 0) return fullyQualifiedName;
- StringBuffer buffer = new StringBuffer();
- buffer.append(fullyQualifiedName);
- buffer.append('<');
- for (int i = 0; i < length; i++) {
- String typeArgument = typeArguments[i];
- buffer.append(Signature.toString(typeArgument));
- if (i < length-1)
- buffer.append(',');
- }
- buffer.append('>');
- return buffer.toString();
- }
-
- protected IPackageFragment getPackageFragment() {
- return null;
- }
-
- public String getFullyQualifiedName(char enclosingTypeSeparator, boolean showParameters) throws JavaScriptModelException {
- String packageName = getPackageFragment().getElementName();
- if (packageName.equals(IPackageFragment.DEFAULT_PACKAGE_NAME)) {
- return getTypeQualifiedName(enclosingTypeSeparator, showParameters);
- }
- return packageName + '.' + getTypeQualifiedName(enclosingTypeSeparator, showParameters);
- }
-
- public String getTypeQualifiedName(char enclosingTypeSeparator, boolean showParameters) throws JavaScriptModelException {
- NamedMember declaringType;
- switch (this.parent.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- if (showParameters) {
- StringBuffer buffer = new StringBuffer(this.name);
- return buffer.toString();
- }
- 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
- }
- if (showParameters) {
- StringBuffer buffer = new StringBuffer(typeName);
- return buffer.toString();
- }
- return typeName;
- case IJavaScriptElement.TYPE:
- declaringType = (NamedMember) this.parent;
- break;
- case IJavaScriptElement.FIELD:
- case IJavaScriptElement.INITIALIZER:
- case IJavaScriptElement.METHOD:
- declaringType = (NamedMember) ((IMember) this.parent).getDeclaringType();
- break;
- default:
- return null;
- }
- String typeQualifiedName = declaringType!=null ?
- declaringType.getTypeQualifiedName(enclosingTypeSeparator, showParameters) : ""; //$NON-NLS-1$
- StringBuffer buffer = new StringBuffer(typeQualifiedName);
- buffer.append(enclosingTypeSeparator);
- String simpleName = this.name.length() == 0 ? Integer.toString(this.occurrenceCount) : this.name;
- buffer.append(simpleName);
- return buffer.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/NullBuffer.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/NullBuffer.java
deleted file mode 100644
index b09ff5b2..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/NullBuffer.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 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
- * 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.core.resources.IFile;
-import org.eclipse.wst.jsdt.core.IOpenable;
-
-/**
- * This class represents a null buffer. This buffer is used to represent a buffer for a class file
- * that has no source attached.
- */
-public class NullBuffer extends Buffer {
- /**
- * Creates a new null buffer on an underlying resource.
- */
- public NullBuffer(IFile file, IOpenable owner, boolean readOnly) {
- super(file, owner, readOnly);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/Openable.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/Openable.java
deleted file mode 100644
index 9c7c482e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/Openable.java
+++ /dev/null
@@ -1,484 +0,0 @@
-/*******************************************************************************
- * 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 java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.PerformanceStats;
-import org.eclipse.wst.jsdt.core.BufferChangedEvent;
-import org.eclipse.wst.jsdt.core.CompletionRequestor;
-import org.eclipse.wst.jsdt.core.IBuffer;
-import org.eclipse.wst.jsdt.core.IBufferChangedListener;
-import org.eclipse.wst.jsdt.core.IBufferFactory;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatusConstants;
-import org.eclipse.wst.jsdt.core.IOpenable;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.internal.codeassist.CompletionEngine;
-import org.eclipse.wst.jsdt.internal.codeassist.SelectionEngine;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-
-/**
- * Abstract class for implementations of java elements which are IOpenable.
- *
- * @see IJavaScriptElement
- * @see IOpenable
- */
-public abstract class Openable extends JavaElement implements IOpenable, IBufferChangedListener {
-
-protected Openable(JavaElement parent) {
- super(parent);
-}
-/**
- * The buffer associated with this element has changed. Registers
- * this element as being out of synch with its buffer's contents.
- * If the buffer has been closed, this element is set as NOT out of
- * synch with the contents.
- *
- * @see IBufferChangedListener
- */
-public void bufferChanged(BufferChangedEvent event) {
- if (event.getBuffer().isClosed()) {
- JavaModelManager.getJavaModelManager().getElementsOutOfSynchWithBuffers().remove(this);
- getBufferManager().removeBuffer(event.getBuffer());
- } else {
- JavaModelManager.getJavaModelManager().getElementsOutOfSynchWithBuffers().add(this);
- }
-}
-/**
- * Builds this element's structure and properties in the given
- * info object, based on this element's current contents (reuse buffer
- * contents if this element has an open buffer, or resource contents
- * if this element does not have an open buffer). Children
- * are placed in the given newElements table (note, this element
- * has already been placed in the newElements table). Returns true
- * if successful, or false if an error is encountered while determining
- * the structure of this element.
- */
-protected abstract boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaScriptModelException;
-/*
- * Returns whether this element can be removed from the Java model cache to make space.
- */
-public boolean canBeRemovedFromCache() {
- try {
- return !hasUnsavedChanges();
- } catch (JavaScriptModelException e) {
- return false;
- }
-}
-/*
- * Returns whether the buffer of this element can be removed from the Java model cache to make space.
- */
-public boolean canBufferBeRemovedFromCache(IBuffer buffer) {
- return !buffer.hasUnsavedChanges();
-}
-/**
- * Close the buffer associated with this element, if any.
- */
-protected void closeBuffer() {
- if (!hasBuffer()) return; // nothing to do
- IBuffer buffer = getBufferManager().getBuffer(this);
- if (buffer != null) {
- buffer.close();
- buffer.removeBufferChangedListener(this);
- }
-}
-/**
- * This element is being closed. Do any necessary cleanup.
- */
-protected void closing(Object info) {
- closeBuffer();
-}
-protected void codeComplete(org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit cu, org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit unitToSkip, int position, CompletionRequestor requestor, WorkingCopyOwner owner) throws JavaScriptModelException {
- if (requestor == null) {
- throw new IllegalArgumentException("Completion requestor cannot be null"); //$NON-NLS-1$
- }
- PerformanceStats performanceStats = CompletionEngine.PERF
- ? PerformanceStats.getStats(JavaModelManager.COMPLETION_PERF, this)
- : null;
- if(performanceStats != null) {
- performanceStats.startRun(new String(cu.getFileName()) + " at " + position); //$NON-NLS-1$
- }
- IBuffer buffer = getBuffer();
- if (buffer == null) {
- return;
- }
- if (position < -1 || position > buffer.getLength()) {
- throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.INDEX_OUT_OF_BOUNDS));
- }
- JavaProject project = (JavaProject) getJavaScriptProject();
- SearchableEnvironment environment = newSearchableNameEnvironment(owner);
-
- // set unit to skip
- environment.unitToSkip = unitToSkip;
-
- // code complete
- CompletionEngine engine = new CompletionEngine(environment, requestor, project.getOptions(true), project);
- engine.complete(cu, position, 0);
- if(performanceStats != null) {
- performanceStats.endRun();
- }
- 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$
- }
-}
-protected IJavaScriptElement[] codeSelect(org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit cu, int offset, int length, WorkingCopyOwner owner) throws JavaScriptModelException {
- PerformanceStats performanceStats = SelectionEngine.PERF
- ? PerformanceStats.getStats(JavaModelManager.SELECTION_PERF, this)
- : null;
- if(performanceStats != null) {
- performanceStats.startRun(new String(cu.getFileName()) + " at [" + offset + "," + length + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- JavaProject project = (JavaProject)getJavaScriptProject();
- SearchableEnvironment environment = newSearchableNameEnvironment(owner);
-
- SelectionRequestor requestor= new SelectionRequestor(environment.nameLookup, this);
- IBuffer buffer = getBuffer();
- if (buffer == null) {
- return requestor.getElements();
- }
- int end= buffer.getLength();
- if (offset < 0 || length < 0 || offset + length > end ) {
- throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.INDEX_OUT_OF_BOUNDS));
- }
-
- // fix for 1FVXGDK
- SelectionEngine engine = new SelectionEngine(environment, requestor, project.getOptions(true));
- engine.select(cu, offset, offset + length - 1);
-
- if(performanceStats != null) {
- performanceStats.endRun();
- }
- 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.getElements();
-}
-/*
- * Returns a new element info for this element.
- */
-protected Object createElementInfo() {
- return new OpenableElementInfo();
-}
-/**
- * @see IJavaScriptElement
- */
-public boolean exists() {
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- if (manager.getInfo(this) != null) return true;
- if (!parentExists()) return false;
- PackageFragmentRoot root = getPackageFragmentRoot();
- if (root != null
- && (root == this || !root.isArchive())) {
- return resourceExists();
- }
- return super.exists();
-}
-public String findRecommendedLineSeparator() throws JavaScriptModelException {
- IBuffer buffer = getBuffer();
- String source = buffer == null ? null : buffer.getContents();
- return Util.getLineSeparator(source, getJavaScriptProject());
-}
-protected void generateInfos(Object info, HashMap newElements, IProgressMonitor monitor) throws JavaScriptModelException {
-
- if (JavaModelCache.VERBOSE){
- String element;
- switch (getElementType()) {
- case JAVASCRIPT_PROJECT:
- element = "project"; //$NON-NLS-1$
- break;
- case PACKAGE_FRAGMENT_ROOT:
- element = "root"; //$NON-NLS-1$
- break;
- case PACKAGE_FRAGMENT:
- element = "package"; //$NON-NLS-1$
- break;
- case CLASS_FILE:
- element = "class file"; //$NON-NLS-1$
- break;
- case JAVASCRIPT_UNIT:
- element = "compilation unit"; //$NON-NLS-1$
- break;
- default:
- element = "element"; //$NON-NLS-1$
- }
- System.out.println(Thread.currentThread() +" OPENING " + element + " " + this.toStringWithAncestors()); //$NON-NLS-1$//$NON-NLS-2$
- }
-
- // open the parent if necessary
- openParent(info, newElements, monitor);
- if (monitor != null && monitor.isCanceled())
- throw new OperationCanceledException();
-
- // puts the info before building the structure so that questions to the handle behave as if the element existed
- // (case of compilation units becoming working copies)
- newElements.put(this, info);
-
- // build the structure of the openable (this will open the buffer if needed)
- try {
- OpenableElementInfo openableElementInfo = (OpenableElementInfo)info;
- boolean isStructureKnown = buildStructure(openableElementInfo, monitor, newElements, getResource());
- openableElementInfo.setIsStructureKnown(isStructureKnown);
- } catch (JavaScriptModelException e) {
- newElements.remove(this);
- throw e;
- }
-
- // remove out of sync buffer for this element
- JavaModelManager.getJavaModelManager().getElementsOutOfSynchWithBuffers().remove(this);
-
- if (JavaModelCache.VERBOSE) {
- System.out.println(JavaModelManager.getJavaModelManager().cacheToString("-> ")); //$NON-NLS-1$
- }
-}
-/**
- * Note: a buffer with no unsaved changes can be closed by the Java Model
- * since it has a finite number of buffers allowed open at one time. If this
- * is the first time a request is being made for the buffer, an attempt is
- * made to create and fill this element's buffer. If the buffer has been
- * closed since it was first opened, the buffer is re-created.
- *
- * @see IOpenable
- */
-public IBuffer getBuffer() throws JavaScriptModelException {
- if (hasBuffer()) {
- // ensure element is open
- Object info = getElementInfo();
- IBuffer buffer = getBufferManager().getBuffer(this);
- if (buffer == null) {
- // try to (re)open a buffer
- buffer = openBuffer(null, info);
- }
- if (buffer instanceof NullBuffer) {
- return null;
- }
- return buffer;
- } else {
- return null;
- }
-}
-/**
- * Answers the buffer factory to use for creating new buffers
- * @deprecated
- */
-public IBufferFactory getBufferFactory(){
- return getBufferManager().getDefaultBufferFactory();
-}
-
-/**
- * Returns the buffer manager for this element.
- */
-protected BufferManager getBufferManager() {
- return BufferManager.getDefaultBufferManager();
-}
-/**
- * Return my underlying resource. Elements that may not have a
- * corresponding resource must override this method.
- *
- * @see IJavaScriptElement
- */
-public IResource getCorrespondingResource() throws JavaScriptModelException {
- return getUnderlyingResource();
-}
-/*
- * @see IJavaScriptElement
- */
-public IOpenable getOpenable() {
- return this;
-}
-
-
-
-/**
- * @see IJavaScriptElement
- */
-public IResource getUnderlyingResource() throws JavaScriptModelException {
- IResource parentResource = this.parent.getUnderlyingResource();
- if (parentResource == null) {
- return null;
- }
- int type = parentResource.getType();
- if (type == IResource.FOLDER || type == IResource.PROJECT) {
- IContainer folder = (IContainer) parentResource;
- IResource resource = folder.findMember(getElementName());
- if (resource == null) {
- throw newNotPresentException();
- } else {
- return resource;
- }
- } else {
- return parentResource;
- }
-}
-
-/**
- * Returns true if this element may have an associated source buffer,
- * otherwise false. Subclasses must override as required.
- */
-protected boolean hasBuffer() {
- return false;
-}
-/**
- * @see IOpenable
- */
-public boolean hasUnsavedChanges() throws JavaScriptModelException{
-
- if (isReadOnly() || !isOpen()) {
- return false;
- }
- IBuffer buf = this.getBuffer();
- if (buf != null && buf.hasUnsavedChanges()) {
- return true;
- }
- // for package fragments, package fragment roots, and projects must check open buffers
- // to see if they have an child with unsaved changes
- int elementType = getElementType();
- if (elementType == PACKAGE_FRAGMENT ||
- elementType == PACKAGE_FRAGMENT_ROOT ||
- elementType == JAVASCRIPT_PROJECT ||
- elementType == JAVASCRIPT_MODEL) { // fix for 1FWNMHH
- Enumeration openBuffers= getBufferManager().getOpenBuffers();
- while (openBuffers.hasMoreElements()) {
- IBuffer buffer= (IBuffer)openBuffers.nextElement();
- if (buffer.hasUnsavedChanges()) {
- IJavaScriptElement owner= (IJavaScriptElement)buffer.getOwner();
- if (isAncestorOf(owner)) {
- return true;
- }
- }
- }
- }
-
- return false;
-}
-/**
- * Subclasses must override as required.
- *
- * @see IOpenable
- */
-public boolean isConsistent() {
- return true;
-}
-/**
- *
- * @see IOpenable
- */
-public boolean isOpen() {
- return JavaModelManager.getJavaModelManager().getInfo(this) != null;
-}
-/**
- * Returns true if this represents a source element.
- * Openable source elements have an associated buffer created
- * when they are opened.
- */
-protected boolean isSourceElement() {
- return false;
-}
-/**
- * @see IJavaScriptElement
- */
-public boolean isStructureKnown() throws JavaScriptModelException {
- return ((OpenableElementInfo)getElementInfo()).isStructureKnown();
-}
-/**
- * @see IOpenable
- */
-public void makeConsistent(IProgressMonitor monitor) throws JavaScriptModelException {
- // only compilation units can be inconsistent
- // other openables cannot be inconsistent so default is to do nothing
-}
-/**
- * @see IOpenable
- */
-public void open(IProgressMonitor pm) throws JavaScriptModelException {
- getElementInfo(pm);
-}
-
-/**
- * Opens a buffer on the contents of this element, and returns
- * the buffer, or returns <code>null</code> if opening fails.
- * By default, do nothing - subclasses that have buffers
- * must override as required.
- */
-protected IBuffer openBuffer(IProgressMonitor pm, Object info) throws JavaScriptModelException {
- return null;
-}
-
-/**
- * Open the parent element if necessary.
- */
-protected void openParent(Object childInfo, HashMap newElements, IProgressMonitor pm) throws JavaScriptModelException {
-
- Openable openableParent = (Openable)getOpenableParent();
- if (openableParent != null && !openableParent.isOpen()){
- openableParent.generateInfos(openableParent.createElementInfo(), newElements, pm);
- }
-}
-
-/**
- * Answers true if the parent exists (null parent is answering true)
- *
- */
-protected boolean parentExists(){
-
- IJavaScriptElement parentElement = getParent();
- if (parentElement == null) return true;
- return parentElement.exists();
-}
-
-/**
- * Returns whether the corresponding resource or associated file exists
- */
-protected boolean resourceExists() {
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- if (workspace == null) return false; // workaround for http://bugs.eclipse.org/bugs/show_bug.cgi?id=34069
- return
- JavaModel.getTarget(
- workspace.getRoot(),
- this.getPath().makeRelative(), // ensure path is relative (see http://dev.eclipse.org/bugs/show_bug.cgi?id=22517)
- true) != null;
-}
-
-/**
- * @see IOpenable
- */
-public void save(IProgressMonitor pm, boolean force) throws JavaScriptModelException {
- if (isReadOnly()) {
- throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.READ_ONLY, this));
- }
- IBuffer buf = getBuffer();
- if (buf != null) { // some Openables (like a JavaProject) don't have a buffer
- buf.save(pm, force);
- this.makeConsistent(pm); // update the element info of this element
- }
-}
-
-/**
- * Find enclosing package fragment root if any
- */
-public PackageFragmentRoot getPackageFragmentRoot() {
- return (PackageFragmentRoot) getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
-}
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/OpenableElementInfo.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/OpenableElementInfo.java
deleted file mode 100644
index 8c079449..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/OpenableElementInfo.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*******************************************************************************
- * 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;
-
-
-/** Element info for IOpenable elements. */
-public class OpenableElementInfo extends JavaElementInfo {
-
- /**
- * Is the structure of this element known
- * @see org.eclipse.wst.jsdt.core.IJavaScriptElement#isStructureKnown()
- */
- protected boolean isStructureKnown = false;
-
- /**
- * @see org.eclipse.wst.jsdt.core.IJavaScriptElement#isStructureKnown()
- */
- public boolean isStructureKnown() {
- return this.isStructureKnown;
- }
-
- /**
- * Sets whether the structure of this element known
- * @see org.eclipse.wst.jsdt.core.IJavaScriptElement#isStructureKnown()
- */
- public void setIsStructureKnown(boolean newIsStructureKnown) {
- this.isStructureKnown = newIsStructureKnown;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/OverflowingLRUCache.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/OverflowingLRUCache.java
deleted file mode 100644
index baa99c2b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/OverflowingLRUCache.java
+++ /dev/null
@@ -1,417 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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.Enumeration;
-import java.util.Iterator;
-
-import org.eclipse.wst.jsdt.internal.core.util.LRUCache;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-
-/**
- * The <code>OverflowingLRUCache</code> is an LRUCache which attempts
- * to maintain a size equal or less than its <code>fSpaceLimit</code>
- * by removing the least recently used elements.
- *
- * <p>The cache will remove elements which successfully close and all
- * elements which are explicitly removed.
- *
- * <p>If the cache cannot remove enough old elements to add new elements
- * it will grow beyond <code>fSpaceLimit</code>. Later, it will attempt to
- * shink back to the maximum space limit.
- *
- * The method <code>close</code> should attempt to close the element. If
- * the element is successfully closed it will return true and the element will
- * be removed from the cache. Otherwise the element will remain in the cache.
- *
- * <p>The cache implicitly attempts shrinks on calls to <code>put</code>and
- * <code>setSpaceLimit</code>. Explicitly calling the <code>shrink</code> method
- * will also cause the cache to attempt to shrink.
- *
- * <p>The cache calculates the used space of all elements which implement
- * <code>ILRUCacheable</code>. All other elements are assumed to be of size one.
- *
- * <p>Use the <code>#peek(Object)</code> and <code>#disableTimestamps()</code> method to
- * circumvent the timestamp feature of the cache. This feature is intended to be used
- * only when the <code>#close(LRUCacheEntry)</code> method causes changes to the cache.
- * For example, if a parent closes its children when </code>#close(LRUCacheEntry)</code> is called,
- * it should be careful not to change the LRU linked list. It can be sure it is not causing
- * problems by calling <code>#peek(Object)</code> instead of <code>#get(Object)</code> method.
- *
- * @see LRUCache
- */
-public abstract class OverflowingLRUCache extends LRUCache {
- /**
- * Indicates if the cache has been over filled and by how much.
- */
- protected int fOverflow = 0;
- /**
- * Indicates whether or not timestamps should be updated
- */
- protected boolean fTimestampsOn = true;
- /**
- * Indicates how much space should be reclaimed when the cache overflows.
- * Inital load factor of one third.
- */
- protected double fLoadFactor = 0.333;
-/**
- * Creates a OverflowingLRUCache.
- * @param size Size limit of cache.
- */
-public OverflowingLRUCache(int size) {
- this(size, 0);
-}
-/**
- * Creates a OverflowingLRUCache.
- * @param size Size limit of cache.
- * @param overflow Size of the overflow.
- */
-public OverflowingLRUCache(int size, int overflow) {
- super(size);
- fOverflow = overflow;
-}
- /**
- * Returns a new cache containing the same contents.
- *
- * @return New copy of this object.
- */
- public Object clone() {
-
- OverflowingLRUCache newCache = (OverflowingLRUCache)newInstance(fSpaceLimit, fOverflow);
- LRUCacheEntry qEntry;
-
- /* Preserve order of entries by copying from oldest to newest */
- qEntry = this.fEntryQueueTail;
- while (qEntry != null) {
- newCache.privateAdd (qEntry._fKey, qEntry._fValue, qEntry._fSpace);
- qEntry = qEntry._fPrevious;
- }
- return newCache;
- }
-/**
- * Returns true if the element is successfully closed and
- * removed from the cache, otherwise false.
- *
- * <p>NOTE: this triggers an external remove from the cache
- * by closing the obejct.
- *
- */
-protected abstract boolean close(LRUCacheEntry entry);
- /**
- * Returns an enumerator of the values in the cache with the most
- * recently used first.
- */
- public Enumeration elements() {
- if (fEntryQueue == null)
- return new LRUCacheEnumerator(null);
- LRUCacheEnumerator.LRUEnumeratorElement head =
- new LRUCacheEnumerator.LRUEnumeratorElement(fEntryQueue._fValue);
- LRUCacheEntry currentEntry = fEntryQueue._fNext;
- LRUCacheEnumerator.LRUEnumeratorElement currentElement = head;
- while(currentEntry != null) {
- currentElement.fNext = new LRUCacheEnumerator.LRUEnumeratorElement(currentEntry._fValue);
- currentElement = currentElement.fNext;
-
- currentEntry = currentEntry._fNext;
- }
- return new LRUCacheEnumerator(head);
- }
- public double fillingRatio() {
- return (fCurrentSpace + fOverflow) * 100.0 / fSpaceLimit;
- }
- /**
- * For internal testing only.
- * This method exposed only for testing purposes!
- *
- * @return Hashtable of entries
- */
- public java.util.Hashtable getEntryTable() {
- return fEntryTable;
- }
-/**
- * Returns the load factor for the cache. The load factor determines how
- * much space is reclaimed when the cache exceeds its space limit.
- * @return double
- */
-public double getLoadFactor() {
- return fLoadFactor;
-}
- /**
- * @return The space by which the cache has overflown.
- */
- public int getOverflow() {
- return fOverflow;
- }
- /**
- * Ensures there is the specified amount of free space in the receiver,
- * by removing old entries if necessary. Returns true if the requested space was
- * made available, false otherwise. May not be able to free enough space
- * since some elements cannot be removed until they are saved.
- *
- * @param space Amount of space to free up
- */
- protected boolean makeSpace(int space) {
-
- int limit = fSpaceLimit;
- if (fOverflow == 0 && fCurrentSpace + space <= limit) {
- /* if space is already available */
- return true;
- }
-
- /* Free up space by removing oldest entries */
- int spaceNeeded = (int)((1 - fLoadFactor) * limit);
- spaceNeeded = (spaceNeeded > space) ? spaceNeeded : space;
- LRUCacheEntry entry = fEntryQueueTail;
-
- try {
- // disable timestamps update while making space so that the previous and next links are not changed
- // (by a call to get(Object) for example)
- fTimestampsOn = false;
-
- while (fCurrentSpace + spaceNeeded > limit && entry != null) {
- this.privateRemoveEntry(entry, false, false);
- entry = entry._fPrevious;
- }
- } finally {
- fTimestampsOn = true;
- }
-
- /* check again, since we may have aquired enough space */
- if (fCurrentSpace + space <= limit) {
- fOverflow = 0;
- return true;
- }
-
- /* update fOverflow */
- fOverflow = fCurrentSpace + space - limit;
- return false;
- }
- /**
- * Returns a new instance of the reciever.
- */
- protected abstract LRUCache newInstance(int size, int overflow);
-/**
- * For testing purposes only
- */
-public void printStats() {
- int forwardListLength = 0;
- LRUCacheEntry entry = fEntryQueue;
- while(entry != null) {
- forwardListLength++;
- entry = entry._fNext;
- }
- System.out.println("Forward length: " + forwardListLength); //$NON-NLS-1$
-
- int backwardListLength = 0;
- entry = fEntryQueueTail;
- while(entry != null) {
- backwardListLength++;
- entry = entry._fPrevious;
- }
- System.out.println("Backward length: " + backwardListLength); //$NON-NLS-1$
-
- Enumeration keys = fEntryTable.keys();
- class Temp {
- public Class fClass;
- public int fCount;
- public Temp(Class aClass) {
- fClass = aClass;
- fCount = 1;
- }
- public String toString() {
- return "Class: " + fClass + " has " + fCount + " entries."; //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-1$
- }
- }
- java.util.HashMap h = new java.util.HashMap();
- while(keys.hasMoreElements()) {
- entry = (LRUCacheEntry)fEntryTable.get(keys.nextElement());
- Class key = entry._fValue.getClass();
- Temp t = (Temp)h.get(key);
- if (t == null) {
- h.put(key, new Temp(key));
- } else {
- t.fCount++;
- }
- }
-
- for (Iterator iter = h.values().iterator(); iter.hasNext();){
- System.out.println(iter.next());
- }
-}
- /**
- * Removes the entry from the entry queue.
- * Calls <code>privateRemoveEntry</code> with the external functionality enabled.
- *
- * @param shuffle indicates whether we are just shuffling the queue
- * (in which case, the entry table is not modified).
- */
- protected void privateRemoveEntry (LRUCacheEntry entry, boolean shuffle) {
- privateRemoveEntry(entry, shuffle, true);
- }
-/**
- * Removes the entry from the entry queue. If <i>external</i> is true, the entry is removed
- * without checking if it can be removed. It is assumed that the client has already closed
- * the element it is trying to remove (or will close it promptly).
- *
- * If <i>external</i> is false, and the entry could not be closed, it is not removed and the
- * pointers are not changed.
- *
- * @param shuffle indicates whether we are just shuffling the queue
- * (in which case, the entry table is not modified).
- */
-protected void privateRemoveEntry(LRUCacheEntry entry, boolean shuffle, boolean external) {
-
- if (!shuffle) {
- if (external) {
- fEntryTable.remove(entry._fKey);
- fCurrentSpace -= entry._fSpace;
- } else {
- if (!close(entry)) return;
- // buffer close will recursively call #privateRemoveEntry with external==true
- // thus entry will already be removed if reaching this point.
- if (fEntryTable.get(entry._fKey) == null){
- return;
- } else {
- // basic removal
- fEntryTable.remove(entry._fKey);
- fCurrentSpace -= entry._fSpace;
- }
- }
- }
- LRUCacheEntry previous = entry._fPrevious;
- LRUCacheEntry next = entry._fNext;
-
- /* if this was the first entry */
- if (previous == null) {
- fEntryQueue = next;
- } else {
- previous._fNext = next;
- }
- /* if this was the last entry */
- if (next == null) {
- fEntryQueueTail = previous;
- } else {
- next._fPrevious = previous;
- }
-}
- /**
- * Sets the value in the cache at the given key. Returns the value.
- *
- * @param key Key of object to add.
- * @param value Value of object to add.
- * @return added value.
- */
- public Object put(Object key, Object value) {
- /* attempt to rid ourselves of the overflow, if there is any */
- if (fOverflow > 0)
- shrink();
-
- /* Check whether there's an entry in the cache */
- int newSpace = spaceFor(value);
- LRUCacheEntry entry = (LRUCacheEntry) fEntryTable.get (key);
-
- if (entry != null) {
-
- /**
- * Replace the entry in the cache if it would not overflow
- * the cache. Otherwise flush the entry and re-add it so as
- * to keep cache within budget
- */
- int oldSpace = entry._fSpace;
- int newTotal = fCurrentSpace - oldSpace + newSpace;
- if (newTotal <= fSpaceLimit) {
- updateTimestamp (entry);
- entry._fValue = value;
- entry._fSpace = newSpace;
- fCurrentSpace = newTotal;
- fOverflow = 0;
- return value;
- } else {
- privateRemoveEntry (entry, false, false);
- }
- }
-
- // attempt to make new space
- makeSpace(newSpace);
-
- // add without worring about space, it will
- // be handled later in a makeSpace call
- privateAdd (key, value, newSpace);
-
- return value;
- }
- /**
- * Removes and returns the value in the cache for the given key.
- * If the key is not in the cache, returns null.
- *
- * @param key Key of object to remove from cache.
- * @return Value removed from cache.
- */
- public Object remove(Object key) {
- return removeKey(key);
- }
-/**
- * Sets the load factor for the cache. The load factor determines how
- * much space is reclaimed when the cache exceeds its space limit.
- * @param newLoadFactor double
- * @throws IllegalArgumentException when the new load factor is not in (0.0, 1.0]
- */
-public void setLoadFactor(double newLoadFactor) throws IllegalArgumentException {
- if(newLoadFactor <= 1.0 && newLoadFactor > 0.0)
- fLoadFactor = newLoadFactor;
- else
- throw new IllegalArgumentException(Messages.cache_invalidLoadFactor);
-}
- /**
- * Sets the maximum amount of space that the cache can store
- *
- * @param limit Number of units of cache space
- */
- public void setSpaceLimit(int limit) {
- if (limit < fSpaceLimit) {
- makeSpace(fSpaceLimit - limit);
- }
- fSpaceLimit = limit;
- }
- /**
- * Attempts to shrink the cache if it has overflown.
- * Returns true if the cache shrinks to less than or equal to <code>fSpaceLimit</code>.
- */
- public boolean shrink() {
- if (fOverflow > 0)
- return makeSpace(0);
- return true;
- }
-/**
- * Returns a String that represents the value of this object. This method
- * is for debugging purposes only.
- */
-public String toString() {
- return
- toStringFillingRation("OverflowingLRUCache ") + //$NON-NLS-1$
- toStringContents();
-}
-/**
- * Updates the timestamp for the given entry, ensuring that the queue is
- * kept in correct order. The entry must exist.
- *
- * <p>This method will do nothing if timestamps have been disabled.
- */
-protected void updateTimestamp(LRUCacheEntry entry) {
- if (fTimestampsOn) {
- entry._fTimestamp = fTimestampCounter++;
- if (fEntryQueue != entry) {
- this.privateRemoveEntry(entry, true);
- this.privateAddEntry(entry, true);
- }
- }
-}
-}
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
deleted file mode 100644
index e4dd0bab..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/PackageFragment.java
+++ /dev/null
@@ -1,544 +0,0 @@
-/*******************************************************************************
- * 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 java.io.File;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Map;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-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.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatusConstants;
-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.JsGlobalScopeContainerInitializer;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.internal.compiler.util.SuffixConstants;
-import org.eclipse.wst.jsdt.internal.core.JavaModelManager.PerProjectInfo;
-import org.eclipse.wst.jsdt.internal.core.util.MementoTokenizer;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * @see IPackageFragment
- */
-public class PackageFragment extends Openable implements IPackageFragment, IVirtualParent, SuffixConstants {
- /**
- * Constant empty list of class files
- */
- protected static final IClassFile[] NO_CLASSFILES = new IClassFile[] {};
- /**
- * Constant empty list of compilation units
- */
- protected static final IJavaScriptUnit[] NO_COMPILATION_UNITS = new IJavaScriptUnit[] {};
-
- public String[] names;
-
-protected PackageFragment(PackageFragmentRoot root, String[] names) {
- super(root);
- this.names = names;
-}
-/**
- * @see Openable
- */
-protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaScriptModelException {
-
- // check whether this pkg can be opened
- if (!underlyingResource.isAccessible()) throw newNotPresentException();
-
- // check that it is not excluded (https://bugs.eclipse.org/bugs/show_bug.cgi?id=138577)
- int kind = getKind();
- if (kind == IPackageFragmentRoot.K_SOURCE && Util.isExcluded(this))
- throw newNotPresentException();
-
-
- // add compilation units/class files from resources
- HashSet vChildren = new HashSet();
- try {
- PackageFragmentRoot root = getPackageFragmentRoot();
- char[][] inclusionPatterns = root.fullInclusionPatternChars();
- char[][] exclusionPatterns = root.fullExclusionPatternChars();
- IResource[] members = ((IContainer) underlyingResource).members();
- int length = members.length;
- if (length > 0) {
- IJavaScriptProject project = getJavaScriptProject();
- String sourceLevel = project.getOption(JavaScriptCore.COMPILER_SOURCE, true);
- String complianceLevel = project.getOption(JavaScriptCore.COMPILER_COMPLIANCE, true);
- for (int i = 0; i < length; i++) {
- IResource child = members[i];
- if (child.getType() != IResource.FOLDER
- && !Util.isExcluded(child, inclusionPatterns, exclusionPatterns)) {
- IJavaScriptElement childElement;
- if (kind == IPackageFragmentRoot.K_SOURCE && Util.isValidCompilationUnitName(child.getName(), sourceLevel, complianceLevel)) {
- childElement = new CompilationUnit(this, child.getName(), DefaultWorkingCopyOwner.PRIMARY);
- vChildren.add(childElement);
- } else if (kind == IPackageFragmentRoot.K_BINARY && Util.isValidClassFileName(child.getName(), sourceLevel, complianceLevel)) {
- childElement = getClassFile(child.getName());
- vChildren.add(childElement);
- } else if (Util.isMetadataFileName(child.getName())) {
- childElement = getClassFile(child.getName());
- vChildren.add(childElement);
- }
- }
- }
- }
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- }
-
- if (kind == IPackageFragmentRoot.K_SOURCE) {
- // add primary compilation units
- IJavaScriptUnit[] primaryCompilationUnits = getJavaScriptUnits(DefaultWorkingCopyOwner.PRIMARY);
- for (int i = 0, length = primaryCompilationUnits.length; i < length; i++) {
- IJavaScriptUnit primary = primaryCompilationUnits[i];
- vChildren.add(primary);
- }
- }
-
- IJavaScriptElement[] children = new IJavaScriptElement[vChildren.size()];
- vChildren.toArray(children);
- info.setChildren(children);
- return true;
-}
-/**
- * Returns true if this fragment contains at least one java resource.
- * Returns false otherwise.
- */
-public boolean containsJavaResources() throws JavaScriptModelException {
- return ((PackageFragmentInfo) getElementInfo()).containsJavaResources();
-}
-/**
- * @see org.eclipse.wst.jsdt.core.ISourceManipulation
- */
-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};
- IJavaScriptElement[] siblings= null;
- if (sibling != null) {
- siblings= new IJavaScriptElement[] {sibling};
- }
- String[] renamings= null;
- if (rename != null) {
- renamings= new String[] {rename};
- }
- getJavaScriptModel().copy(elements, containers, siblings, renamings, force, monitor);
-}
-/**
- * @see IPackageFragment
- */
-public IJavaScriptUnit createCompilationUnit(String cuName, String contents, boolean force, IProgressMonitor monitor) throws JavaScriptModelException {
- CreateCompilationUnitOperation op= new CreateCompilationUnitOperation(this, cuName, contents, force);
- op.runOperation(monitor);
- return new CompilationUnit(this, cuName, DefaultWorkingCopyOwner.PRIMARY);
-}
-/**
- * @see JavaElement
- */
-protected Object createElementInfo() {
- return new PackageFragmentInfo();
-}
-/**
- * @see org.eclipse.wst.jsdt.core.ISourceManipulation
- */
-public void delete(boolean force, IProgressMonitor monitor) throws JavaScriptModelException {
- IJavaScriptElement[] elements = new IJavaScriptElement[] {this};
- getJavaScriptModel().delete(elements, force, monitor);
-}
-public boolean equals(Object o) {
- if (this == o) return true;
- if (!(o instanceof PackageFragment)) return false;
-
- PackageFragment other = (PackageFragment) o;
- return Util.equalArraysOrNull(this.names, other.names) &&
- this.parent.equals(other.parent);
-}
-public boolean exists() {
- // super.exist() only checks for the parent and the resource existence
- // so also ensure that the package is not exceluded (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=138577)
- return super.exists() && !Util.isExcluded(this);
-}
-/**
- * @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= "";
- if (this.getResource()!=null)
- filename= this.getResource().getLocation().toOSString()+File.separator+classFileName;
- else
- filename=classFileName;
-
- return (!Util.isMetadataFileName(classFileName)) ? (IClassFile)new ClassFile(this,filename) : (IClassFile)new MetadataFile(this,filename);
-}
-/**
- * Returns a the collection of class files in this - a folder package fragment which has a root
- * that has its kind set to <code>IPackageFragmentRoot.K_Source</code> does not
- * recognize class files.
- *
- * @see IPackageFragment#getClassFiles()
- */
-public IClassFile[] getClassFiles() throws JavaScriptModelException {
- if (getKind() == IPackageFragmentRoot.K_SOURCE) {
- return NO_CLASSFILES;
- }
-
- ArrayList list = getChildrenOfType(CLASS_FILE);
- IClassFile[] array= new IClassFile[list.size()];
- list.toArray(array);
- return array;
-}
-/**
- * @see IPackageFragment#getJavaScriptUnit(String)
- * @exception IllegalArgumentException if the name does not end with ".js"
- */
-public IJavaScriptUnit getCompilationUnit(String cuName, String superTypeName) {
- if (!org.eclipse.wst.jsdt.internal.core.util.Util.isJavaLikeFileName(cuName)) {
- throw new IllegalArgumentException(Messages.convention_unit_notJavaName);
- }
- // If parent specified in filename remove it
- String parentName = new String();
- try {
- IResource parentNameR = this.parent.getResource();
- parentName = parentNameR==null?null:parentNameR.getName() + "/"; //$NON-NLS-1$
- //String parentString = parentName.getProjectRelativePath().toString();
- } catch (Exception ex) {
-
- ex.printStackTrace();
- }
- if(parentName!=null) {
- int pi = cuName.indexOf(parentName);
- if( pi>-1 && pi<2 ) {
- String newCp = "/" + cuName.substring(pi+parentName.length(),cuName.length()); //$NON-NLS-1$
- return new CompilationUnit(this, newCp,superTypeName, DefaultWorkingCopyOwner.PRIMARY);
- }
- }
- return new CompilationUnit(this, cuName,superTypeName, DefaultWorkingCopyOwner.PRIMARY);
-}
-
-public IJavaScriptUnit getJavaScriptUnit(String cuName) {
- return getCompilationUnit(cuName,null);
-}
-/**
- * @see IPackageFragment#getJavaScriptUnits()
- */
-public IJavaScriptUnit[] getJavaScriptUnits() throws JavaScriptModelException {
- if (getKind() == IPackageFragmentRoot.K_BINARY) {
- return NO_COMPILATION_UNITS;
- }
-
- ArrayList list = getChildrenOfType(JAVASCRIPT_UNIT);
- IJavaScriptUnit[] array= new IJavaScriptUnit[list.size()];
- list.toArray(array);
- return array;
-}
-/**
- * @see IPackageFragment#getJavaScriptUnits(WorkingCopyOwner)
- */
-public IJavaScriptUnit[] getJavaScriptUnits(WorkingCopyOwner owner) {
- IJavaScriptUnit[] workingCopies = JavaModelManager.getJavaModelManager().getWorkingCopies(owner, false/*don't add primary*/);
- if (workingCopies == null) return JavaModelManager.NO_WORKING_COPY;
- int length = workingCopies.length;
- IJavaScriptUnit[] result = new IJavaScriptUnit[length];
- int index = 0;
- for (int i = 0; i < length; i++) {
- IJavaScriptUnit wc = workingCopies[i];
- if (equals(wc.getParent()) && !Util.isExcluded(wc)) { // 59933 - excluded wc shouldn't be answered back
- result[index++] = wc;
- }
- }
- if (index != length) {
- System.arraycopy(result, 0, result = new IJavaScriptUnit[index], 0, index);
- }
- return result;
-}
-public String getElementName() {
- //if (this.names.length == 0)
- //return DEFAULT_PACKAGE_NAME;
- return Util.concatWith(this.names, '/');
-}
-/**
- * @see IJavaScriptElement
- */
-public int getElementType() {
- return PACKAGE_FRAGMENT;
-}
-/*
- * @see JavaElement
- */
-public IJavaScriptElement getHandleFromMemento(String token, MementoTokenizer memento, WorkingCopyOwner owner) {
- switch (token.charAt(0)) {
- case JEM_CLASSFILE:
- if (!memento.hasMoreTokens()) return this;
- String classFileName = memento.nextToken();
- JavaElement classFile = (JavaElement)getClassFile(classFileName);
- return classFile.getHandleFromMemento(memento, owner);
- case JEM_COMPILATIONUNIT:
- if (!memento.hasMoreTokens()) return this;
- String cuName = memento.nextToken();
- JavaElement cu = new CompilationUnit(this, cuName, owner);
- return cu.getHandleFromMemento(memento, owner);
- }
- return null;
-}
-/**
- * @see JavaElement#getHandleMementoDelimiter()
- */
-protected char getHandleMementoDelimiter() {
- return JavaElement.JEM_PACKAGEFRAGMENT;
-}
-/**
- * @see IPackageFragment#getKind()
- */
-public int getKind() throws JavaScriptModelException {
- int kind= ((IPackageFragmentRoot)getParent()).getKind();
- if (kind==IPackageFragmentRoot.K_SOURCE)
- {
- if (JavaScriptCore.isReadOnly(getUnderlyingResource()))
- kind=IPackageFragmentRoot.K_BINARY;
- }
- return kind;
-}
-/**
- * Returns an array of non-java resources contained in the receiver.
- */
-public Object[] getNonJavaScriptResources() throws JavaScriptModelException {
- if (this.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 ((PackageFragmentInfo) getElementInfo()).getNonJavaResources(getResource(), getPackageFragmentRoot());
- }
-}
-/**
- * @see IJavaScriptElement#getPath()
- */
-public IPath getPath() {
- PackageFragmentRoot root = this.getPackageFragmentRoot();
- if (root.isArchive()) {
- return root.getPath();
- } else {
- IPath path = root.getPath();
- for (int i = 0, length = this.names.length; i < length; i++) {
- String name = this.names[i];
- path = path.append(name);
- }
- return path;
- }
-}
-/**
- * @see IJavaScriptElement#getResource()
- */
-public IResource getResource() {
- PackageFragmentRoot root = this.getPackageFragmentRoot();
- if (!root.isResourceContainer()) {
- return root.getResource();
- } else {
- int length = this.names.length;
- if (length == 0) {
- return root.getResource();
- } else {
- IPath path = new Path(this.names[0]);
- for (int i = 1; i < length; i++)
- path = path.append(this.names[i]);
- return ((IContainer)root.getResource()).getFolder(path);
- }
- }
-}
-/**
- * @see IJavaScriptElement#getUnderlyingResource()
- */
-public IResource getUnderlyingResource() throws JavaScriptModelException {
- IResource rootResource = this.parent.getUnderlyingResource();
- if (rootResource == null) {
- //jar package fragment root that has no associated resource
- return null;
- }
- // the underlying resource may be a folder or a project (in the case that the project folder
- // is atually the package fragment root)
- if (rootResource.getType() == IResource.FOLDER || rootResource.getType() == IResource.PROJECT) {
- IContainer folder = (IContainer) rootResource;
- String[] segs = this.names;
- for (int i = 0; i < segs.length; ++i) {
- IResource child = folder.findMember(segs[i]);
- if (child == null || child.getType() != IResource.FOLDER) {
- throw newNotPresentException();
- }
- folder = (IFolder) child;
- }
- return folder;
- } else {
- return rootResource;
- }
-}
-public int hashCode() {
- int hash = this.parent.hashCode();
- for (int i = 0, length = this.names.length; i < length; i++)
- hash = Util.combineHashCodes(this.names[i].hashCode(), hash);
- return hash;
-}
-/**
- * @see org.eclipse.wst.jsdt.core.IParent
- */
-public boolean hasChildren() throws JavaScriptModelException {
- return getChildren().length > 0;
-}
-/**
- * @see IPackageFragment#hasSubpackages()
- */
-public boolean hasSubpackages() throws JavaScriptModelException {
- IJavaScriptElement[] packages= ((IPackageFragmentRoot)getParent()).getChildren();
- int namesLength = this.names.length;
- nextPackage: for (int i= 0, length = packages.length; i < length; i++) {
- String[] otherNames = ((PackageFragment) packages[i]).names;
- if (otherNames.length <= namesLength) continue nextPackage;
- for (int j = 0; j < namesLength; j++)
- if (!this.names[j].equals(otherNames[j]))
- continue nextPackage;
- return true;
- }
- return false;
-}
-/**
- * @see IPackageFragment#isDefaultPackage()
- */
-public boolean isDefaultPackage() {
- return this.names.length == 0;
-}
-/**
- * @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};
- IJavaScriptElement[] siblings= null;
- if (sibling != null) {
- siblings= new IJavaScriptElement[] {sibling};
- }
- String[] renamings= null;
- if (rename != null) {
- renamings= new String[] {rename};
- }
- getJavaScriptModel().move(elements, containers, siblings, renamings, force, monitor);
-}
-/**
- * @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.element_nullName);
- }
- IJavaScriptElement[] elements= new IJavaScriptElement[] {this};
- IJavaScriptElement[] dests= new IJavaScriptElement[] {this.getParent()};
- String[] renamings= new String[] {newName};
- getJavaScriptModel().rename(elements, dests, renamings, force, monitor);
-}
-/**
- * Debugging purposes
- */
-protected void toStringChildren(int tab, StringBuffer buffer, Object info) {
- if (tab == 0) {
- super.toStringChildren(tab, buffer, info);
- }
-}
-/**
- * Debugging purposes
- */
-protected void toStringInfo(int tab, StringBuffer buffer, Object info, boolean showResolvedInfo) {
- buffer.append(this.tabString(tab));
- if (this.names.length == 0) {
- buffer.append("<default>"); //$NON-NLS-1$
- } else {
- toStringName(buffer);
- }
- if (info == null) {
- buffer.append(" (not open)"); //$NON-NLS-1$
- } else {
- if (tab > 0) {
- buffer.append(" (...)"); //$NON-NLS-1$
- }
- }
-}
-/*
- * @see IJavaScriptElement#getAttachedJavadoc(IProgressMonitor)
- */
-public String getAttachedJavadoc(IProgressMonitor monitor) throws JavaScriptModelException {
- PerProjectInfo projectInfo = JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(this.getJavaScriptProject().getProject());
- String cachedJavadoc = null;
- synchronized (projectInfo.javadocCache) {
- cachedJavadoc = (String) projectInfo.javadocCache.get(this);
- }
- if (cachedJavadoc != null) {
- return cachedJavadoc;
- }
- URL baseLocation= getJavadocBaseLocation();
- if (baseLocation == null) {
- return null;
- }
- StringBuffer pathBuffer = new StringBuffer(baseLocation.toExternalForm());
-
- if (!(pathBuffer.charAt(pathBuffer.length() - 1) == '/')) {
- pathBuffer.append('/');
- }
- String packPath= this.getElementName().replace('.', '/');
- pathBuffer.append(packPath).append('/').append(JavadocConstants.PACKAGE_FILE_NAME);
-
- if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException();
- final String contents = getURLContents(String.valueOf(pathBuffer));
- if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException();
- if (contents == null) throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JSDOC, this));
- synchronized (projectInfo.javadocCache) {
- projectInfo.javadocCache.put(this, contents);
- }
- return contents;
-}
-public JsGlobalScopeContainerInitializer getContainerInitializer() {
- if(parent instanceof PackageFragmentRoot) {
- return ((PackageFragmentRoot)parent).getContainerInitializer();
- }
- return null;
-}
-public boolean isSource() {
- try {
- return getKind() == IPackageFragmentRoot.K_SOURCE;
- } catch (JavaScriptModelException e) {
- }
- return true;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/PackageFragmentInfo.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/PackageFragmentInfo.java
deleted file mode 100644
index a660ce6c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/PackageFragmentInfo.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*******************************************************************************
- * 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.core.resources.IContainer;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-
-/**
- * Element info for PackageFragments.
- */
-class PackageFragmentInfo extends OpenableElementInfo {
-
- /**
- * A array with all the non-java resources contained by this PackageFragment
- */
- protected Object[] nonJavaResources;
-
-/**
- * Create and initialize a new instance of the receiver
- */
-public PackageFragmentInfo() {
- this.nonJavaResources = null;
-}
-/**
- */
-boolean containsJavaResources() {
- return this.children.length != 0;
-}
-/**
- * Returns an array of non-java resources contained in the receiver.
- */
-Object[] getNonJavaResources(IResource underlyingResource, PackageFragmentRoot rootHandle) {
- if (this.nonJavaResources == null) {
- try {
- this.nonJavaResources =
- PackageFragmentRootInfo.computeFolderNonJavaResources(
- (JavaProject)rootHandle.getJavaScriptProject(),
- (IContainer)underlyingResource,
- rootHandle.fullInclusionPatternChars(),
- rootHandle.fullExclusionPatternChars());
- } catch (JavaScriptModelException e) {
- // root doesn't exist: consider package has no nonJavaResources
- this.nonJavaResources = NO_NON_JAVA_RESOURCES;
- }
- }
- return this.nonJavaResources;
-}
-/**
- * Set the nonJavaResources to res value
- */
-void setNonJavaResources(Object[] resources) {
- this.nonJavaResources = resources;
-}
-}
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
deleted file mode 100644
index d610f15e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/PackageFragmentRoot.java
+++ /dev/null
@@ -1,918 +0,0 @@
-/*******************************************************************************
- * 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 java.util.ArrayList;
-import java.util.Enumeration;
-import java.util.Map;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.wst.jsdt.core.IBuffer;
-import org.eclipse.wst.jsdt.core.IIncludePathAttribute;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatusConstants;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IOpenable;
-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.JsGlobalScopeContainerInitializer;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.core.util.MementoTokenizer;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * @see IPackageFragmentRoot
- */
-public class PackageFragmentRoot extends Openable implements IPackageFragmentRoot, IVirtualParent {
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.core.JavaElement#isVirtual()
- */
- public boolean isVirtual() {
- return false;
- }
-
- /**
- * The delimiter between the source path and root path in the
- * attachment server property.
- */
- protected final static char ATTACHMENT_PROPERTY_DELIMITER= '*';
- /*
- * No source attachment property
- */
- public final static String NO_SOURCE_ATTACHMENT = ""; //$NON-NLS-1$
-
- /**
- * The resource associated with this root.
- * (an IResource or a java.io.File (for external jar only))
- */
- protected Object resource;
-
-/**
- * Constructs a package fragment root which is the root of the java package
- * directory hierarchy.
- */
-protected PackageFragmentRoot(IResource resource, JavaProject project) {
- super(project);
- this.resource = resource;
-}
-
-/**
- * @see IPackageFragmentRoot
- */
-public void attachSource(IPath sourcePath, IPath rootPath, IProgressMonitor monitor) throws JavaScriptModelException {
- try {
- verifyAttachSource(sourcePath);
- if (monitor != null) {
- monitor.beginTask(Messages.element_attachingSource, 2);
- }
- SourceMapper oldMapper= getSourceMapper();
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- boolean rootNeedsToBeClosed= false;
-
- if (sourcePath == null) {
- //source being detached
- rootNeedsToBeClosed= true;
- setSourceMapper(null);
- /* Disable deltas (see 1GDTUSD)
- // fire a delta to notify the UI about the source detachement.
- JavaModelManager manager = (JavaModelManager) JavaModelManager.getJavaModelManager();
- JavaModel model = (JavaModel) getJavaModel();
- JavaElementDelta attachedSourceDelta = new JavaElementDelta(model);
- attachedSourceDelta .sourceDetached(this); // this would be a PackageFragmentRoot
- manager.registerResourceDelta(attachedSourceDelta );
- manager.fire(); // maybe you want to fire the change later. Let us know about it.
- */
- } else {
- /*
- // fire a delta to notify the UI about the source attachement.
- JavaModelManager manager = (JavaModelManager) JavaModelManager.getJavaModelManager();
- JavaModel model = (JavaModel) getJavaModel();
- JavaElementDelta attachedSourceDelta = new JavaElementDelta(model);
- attachedSourceDelta .sourceAttached(this); // this would be a PackageFragmentRoot
- manager.registerResourceDelta(attachedSourceDelta );
- manager.fire(); // maybe you want to fire the change later. Let us know about it.
- */
-
- //check if different from the current attachment
- IPath storedSourcePath= getSourceAttachmentPath();
- IPath storedRootPath= getSourceAttachmentRootPath();
- if (monitor != null) {
- monitor.worked(1);
- }
- if (storedSourcePath != null) {
- if (!(storedSourcePath.equals(sourcePath) && (rootPath != null && rootPath.equals(storedRootPath)) || storedRootPath == null)) {
- rootNeedsToBeClosed= true;
- }
- }
- // check if source path is valid
- Object target = JavaModel.getTarget(workspace.getRoot(), sourcePath, false);
- if (target == null) {
- throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_PATH, sourcePath));
- }
- SourceMapper mapper = createSourceMapper(sourcePath, rootPath);
- if (rootPath == null && mapper.rootPath != null) {
- // as a side effect of calling the SourceMapper constructor, the root path was computed
- rootPath = new Path(mapper.rootPath);
- }
- setSourceMapper(mapper);
- }
- if (sourcePath == null) {
- Util.setSourceAttachmentProperty(getPath(), null); //remove the property
- } else {
- //set the property to the path of the mapped source
- Util.setSourceAttachmentProperty(
- getPath(),
- sourcePath.toString()
- + (rootPath == null ? "" : (ATTACHMENT_PROPERTY_DELIMITER + rootPath.toString()))); //$NON-NLS-1$
- }
- if (rootNeedsToBeClosed) {
- if (oldMapper != null) {
- oldMapper.close();
- }
- BufferManager manager= BufferManager.getDefaultBufferManager();
- Enumeration openBuffers= manager.getOpenBuffers();
- while (openBuffers.hasMoreElements()) {
- IBuffer buffer= (IBuffer) openBuffers.nextElement();
- IOpenable possibleMember= buffer.getOwner();
- if (isAncestorOf((IJavaScriptElement) possibleMember)) {
- buffer.close();
- }
- }
- if (monitor != null) {
- monitor.worked(1);
- }
- }
- } catch (JavaScriptModelException e) {
- Util.setSourceAttachmentProperty(getPath(), null); // loose info - will be recomputed
- throw e;
- } finally {
- if (monitor != null) {
- monitor.done();
- }
- }
-}
-
-/**
- * @see Openable
- */
-protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaScriptModelException {
-
- // check whether this pkg fragment root can be opened
- IStatus status = validateOnClasspath();
- if (!status.isOK()) throw newJavaModelException(status);
- if (!resourceExists()) throw newNotPresentException();
-
- ((PackageFragmentRootInfo) info).setRootKind(determineKind(underlyingResource));
- return computeChildren(info, newElements);
-}
-
-SourceMapper createSourceMapper(IPath sourcePath, IPath rootPath) {
- SourceMapper mapper = new SourceMapper(
- sourcePath,
- rootPath == null ? null : rootPath.toOSString(),
- getJavaScriptProject().getOptions(true)); // cannot use workspace options if external jar is 1.5 jar and workspace options are 1.4 options
- return mapper;
-}
-/*
- * @see org.eclipse.wst.jsdt.core.IPackageFragmentRoot#delete
- */
-public void delete(
- int updateResourceFlags,
- int updateModelFlags,
- IProgressMonitor monitor)
- throws JavaScriptModelException {
-
- DeletePackageFragmentRootOperation op = new DeletePackageFragmentRootOperation(this, updateResourceFlags, updateModelFlags);
- op.runOperation(monitor);
-}
-
-/**
- * Compute the package fragment children of this package fragment root.
- *
- * @exception JavaScriptModelException The resource associated with this package fragment root does not exist
- */
-protected boolean computeChildren(OpenableElementInfo info, Map newElements) throws JavaScriptModelException {
- // Note the children are not opened (so not added to newElements) for a regular package fragment root
- // Howver they are opened for a Jar package fragment root (see JarPackageFragmentRoot#computeChildren)
- try {
- // the underlying resource may be a folder or a project (in the case that the project folder
- // is actually the package fragment root)
- IResource underlyingResource = getResource();
- if (underlyingResource.getType() == IResource.FOLDER || underlyingResource.getType() == IResource.PROJECT) {
- ArrayList vChildren = new ArrayList(5);
- IContainer rootFolder = (IContainer) underlyingResource;
- char[][] inclusionPatterns = fullInclusionPatternChars();
- char[][] exclusionPatterns = fullExclusionPatternChars();
- computeFolderChildren(rootFolder, !Util.isExcluded(rootFolder, inclusionPatterns, exclusionPatterns), CharOperation.NO_STRINGS, vChildren, inclusionPatterns, exclusionPatterns);
- IJavaScriptElement[] children = new IJavaScriptElement[vChildren.size()];
- vChildren.toArray(children);
- info.setChildren(children);
- }
- } catch (JavaScriptModelException e) {
- //problem resolving children; structure remains unknown
- info.setChildren(new IJavaScriptElement[]{});
- throw e;
- }
- return true;
-}
-
-/**
- * Starting at this folder, create package fragments and add the fragments that are not exclused
- * to the collection of children.
- *
- * @exception JavaScriptModelException The resource associated with this package fragment does not exist
- */
-protected void computeFolderChildren(IContainer folder, boolean isIncluded, String[] pkgName, ArrayList vChildren, char[][] inclusionPatterns, char[][] exclusionPatterns) throws JavaScriptModelException {
-
- if (isIncluded) {
- IPackageFragment pkg = getPackageFragment(pkgName);
- vChildren.add(pkg);
- }
- try {
- JavaProject javaProject = (JavaProject)getJavaScriptProject();
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- IResource[] members = folder.members();
- boolean hasIncluded = isIncluded;
- int length = members.length;
- if (length >0) {
- String sourceLevel = javaProject.getOption(JavaScriptCore.COMPILER_SOURCE, true);
- String complianceLevel = javaProject.getOption(JavaScriptCore.COMPILER_COMPLIANCE, true);
- for (int i = 0; i < length; i++) {
- IResource member = members[i];
- String memberName = member.getName();
-
- switch(member.getType()) {
-
- case IResource.FOLDER:
- // recurse into sub folders even even parent not included as a sub folder could be included
- // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=65637)
- if (Util.isValidFolderNameForPackage(memberName, sourceLevel, complianceLevel)) {
- // eliminate binary output only if nested inside direct subfolders
- if (javaProject.contains(member)) {
- String[] newNames = Util.arrayConcat(pkgName, manager.intern(memberName));
- boolean isMemberIncluded = !Util.isExcluded(member, inclusionPatterns, exclusionPatterns);
- computeFolderChildren((IFolder) member, isMemberIncluded, newNames, vChildren, inclusionPatterns, exclusionPatterns);
- }
- }
- break;
- case IResource.FILE:
- // inclusion filter may only include files, in which case we still want to include the immediate parent package (lazily)
- if (!hasIncluded
- && Util.isValidCompilationUnitName(memberName, sourceLevel, complianceLevel)
- && !Util.isExcluded(member, inclusionPatterns, exclusionPatterns)) {
- hasIncluded = true;
- IPackageFragment pkg = getPackageFragment(pkgName);
- vChildren.add(pkg);
- }
- break;
- }
- }
- }
- } catch(IllegalArgumentException e){
- throw new JavaScriptModelException(e, IJavaScriptModelStatusConstants.ELEMENT_DOES_NOT_EXIST); // could be thrown by ElementTree when path is not found
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- }
-}
-
-/*
- * @see org.eclipse.wst.jsdt.core.IPackageFragmentRoot#copy
- */
-public void copy(
- IPath destination,
- int updateResourceFlags,
- int updateModelFlags,
- IIncludePathEntry sibling,
- IProgressMonitor monitor)
- throws JavaScriptModelException {
-
- CopyPackageFragmentRootOperation op =
- new CopyPackageFragmentRootOperation(this, destination, updateResourceFlags, updateModelFlags, sibling);
- op.runOperation(monitor);
-}
-
-/**
- * Returns a new element info for this element.
- */
-protected Object createElementInfo() {
- return new PackageFragmentRootInfo();
-}
-
-/**
- * @see IPackageFragmentRoot
- */
-public IPackageFragment createPackageFragment(String pkgName, boolean force, IProgressMonitor monitor) throws JavaScriptModelException {
- CreatePackageFragmentOperation op = new CreatePackageFragmentOperation(this, pkgName, force);
- op.runOperation(monitor);
- return getPackageFragment(op.pkgName);
-}
-
-/**
- * Returns the root's kind - K_SOURCE or K_BINARY, defaults
- * to K_SOURCE if it is not on the classpath.
- *
- * @exception JavaScriptModelException if the project and root do
- * not exist.
- */
-protected int determineKind(IResource underlyingResource) throws JavaScriptModelException {
- IIncludePathEntry entry = ((JavaProject)getJavaScriptProject()).getClasspathEntryFor(underlyingResource.getFullPath());
- if (entry != null) {
- return entry.getContentKind();
- }
- return IPackageFragmentRoot.K_SOURCE;
-}
-
-/**
- * Compares two objects for equality;
- * for <code>PackageFragmentRoot</code>s, equality is having the
- * same parent, same resources, and occurrence count.
- *
- */
-public boolean equals(Object o) {
- if (this == o)
- return true;
- if (!(o instanceof PackageFragmentRoot))
- return false;
- PackageFragmentRoot other = (PackageFragmentRoot) o;
- return this.resource.equals(other.resource) &&
- this.parent.equals(other.parent);
-}
-
-/**
- * @see IJavaScriptElement
- */
-public boolean exists() {
- return super.exists() && validateOnClasspath().isOK();
-}
-
-private IIncludePathEntry findSourceAttachmentRecommendation() {
- try {
- IPath rootPath = this.getPath();
- IIncludePathEntry entry;
- IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
-
- // try on enclosing project first
- JavaProject parentProject = (JavaProject) getJavaScriptProject();
- try {
- entry = parentProject.getClasspathEntryFor(rootPath);
- if (entry != null){
- Object target = JavaModel.getTarget(workspaceRoot, entry.getSourceAttachmentPath(), true);
- if (target instanceof IResource) {
- if (target instanceof IFile) {
- IFile file = (IFile) target;
- if (org.eclipse.wst.jsdt.internal.compiler.util.Util.isArchiveFileName(file.getName())){
- return entry;
- }
- } else if (target instanceof IContainer) {
- return entry;
- }
- } else if (target instanceof java.io.File){
- java.io.File file = JavaModel.getFile(target);
- if (file != null) {
- if (org.eclipse.wst.jsdt.internal.compiler.util.Util.isArchiveFileName(file.getName())){
- return entry;
- }
- } else {
- // external directory
- return entry;
- }
- }
- }
- } catch(JavaScriptModelException e){
- // ignore
- }
-
- // iterate over all projects
- IJavaScriptModel model = getJavaScriptModel();
- IJavaScriptProject[] jProjects = model.getJavaScriptProjects();
- for (int i = 0, max = jProjects.length; i < max; i++){
- JavaProject jProject = (JavaProject) jProjects[i];
- if (jProject == parentProject) continue; // already done
- try {
- entry = jProject.getClasspathEntryFor(rootPath);
- if (entry != null){
- Object target = JavaModel.getTarget(workspaceRoot, entry.getSourceAttachmentPath(), true);
- if (target instanceof IResource) {
- if (target instanceof IFile){
- IFile file = (IFile) target;
- if (org.eclipse.wst.jsdt.internal.compiler.util.Util.isArchiveFileName(file.getName())){
- return entry;
- }
- } else if (target instanceof IContainer) {
- return entry;
- }
- } else if (target instanceof java.io.File){
- java.io.File file = (java.io.File) target;
- if (file.isFile()) {
- if (org.eclipse.wst.jsdt.internal.compiler.util.Util.isArchiveFileName(file.getName())){
- return entry;
- }
- } else {
- // external directory
- return entry;
- }
- }
- }
- } catch(JavaScriptModelException e){
- // ignore
- }
- }
- } catch(JavaScriptModelException e){
- // ignore
- }
-
- return null;
-}
-
-/*
- * Returns the exclusion patterns from the classpath entry associated with this root.
- */
-public char[][] fullExclusionPatternChars() {
- try {
- if (this.isOpen() && this.getKind() != IPackageFragmentRoot.K_SOURCE) return null;
- ClasspathEntry entry = (ClasspathEntry)getRawIncludepathEntry();
- if (entry == null) {
- return null;
- } else {
- return entry.fullExclusionPatternChars();
- }
- } catch (JavaScriptModelException e) {
- return null;
- }
-}
-
-/*
- * Returns the inclusion patterns from the classpath entry associated with this root.
- */
-public char[][] fullInclusionPatternChars() {
- try {
- if (this.isOpen() && this.getKind() != IPackageFragmentRoot.K_SOURCE) return null;
- ClasspathEntry entry = (ClasspathEntry)getRawIncludepathEntry();
- if (entry == null) {
- return null;
- } else {
- return entry.fullInclusionPatternChars();
- }
- } catch (JavaScriptModelException e) {
- return null;
- }
-}
-public String getElementName() {
- if (this.resource instanceof IFolder)
- return ((IFolder) this.resource).getName();
- return ""; //$NON-NLS-1$
-}
-/**
- * @see IJavaScriptElement
- */
-public int getElementType() {
- return PACKAGE_FRAGMENT_ROOT;
-}
-/**
- * @see JavaElement#getHandleMemento()
- */
-protected char getHandleMementoDelimiter() {
- return JavaElement.JEM_PACKAGEFRAGMENTROOT;
-}
-/*
- * @see JavaElement
- */
-public IJavaScriptElement getHandleFromMemento(String token, MementoTokenizer memento, WorkingCopyOwner owner) {
- switch (token.charAt(0)) {
- case JEM_PACKAGEFRAGMENT:
- String pkgName;
- if (memento.hasMoreTokens()) {
- pkgName = memento.nextToken();
- char firstChar = pkgName.charAt(0);
- if (firstChar == JEM_CLASSFILE || firstChar == JEM_COMPILATIONUNIT || firstChar == JEM_COUNT) {
- token = pkgName;
- pkgName = IPackageFragment.DEFAULT_PACKAGE_NAME;
- } else {
- token = null;
- }
- } else {
- pkgName = IPackageFragment.DEFAULT_PACKAGE_NAME;
- token = null;
- }
- JavaElement pkg = (JavaElement)getPackageFragment(pkgName);
- if (token == null) {
- return pkg.getHandleFromMemento(memento, owner);
- } else {
- return pkg.getHandleFromMemento(token, memento, owner);
- }
- }
- return null;
-}
-/**
- * @see JavaElement#getHandleMemento(StringBuffer)
- */
-protected void getHandleMemento(StringBuffer buff) {
- IPath path;
- IResource underlyingResource = getResource();
- if (underlyingResource != null) {
- // internal jar or regular root
- if (getResource().getProject().equals(getJavaScriptProject().getProject())) {
- path = underlyingResource.getProjectRelativePath();
- } else {
- path = underlyingResource.getFullPath();
- }
- } else {
- // external jar
- path = getPath();
- }
- ((JavaElement)getParent()).getHandleMemento(buff);
- buff.append(getHandleMementoDelimiter());
- escapeMementoName(buff, path.toString());
-}
-/**
- * @see IPackageFragmentRoot
- */
-public int getKind() throws JavaScriptModelException {
- return ((PackageFragmentRootInfo)getElementInfo()).getRootKind();
-}
-
-/**
- * Returns an array of non-java resources contained in the receiver.
- */
-public Object[] getNonJavaScriptResources() throws JavaScriptModelException {
- return ((PackageFragmentRootInfo) getElementInfo()).getNonJavaResources(getJavaScriptProject(), getResource(), this);
-}
-
-/**
- * @see IPackageFragmentRoot
- */
-public IPackageFragment getPackageFragment(String packageName) {
- // tolerate package names with spaces (e.g. 'x . y') (http://bugs.eclipse.org/bugs/show_bug.cgi?id=21957)
- String[] pkgName = Util.getTrimmedSimpleNames(packageName);
- return getPackageFragment(pkgName);
-}
-public PackageFragment getPackageFragment(String[] pkgName) {
- return new PackageFragment(this, pkgName);
-}
-/**
- * Returns the package name for the given folder
- * (which is a decendent of this root).
- */
-protected String getPackageName(IFolder folder) {
- IPath myPath= getPath();
- IPath pkgPath= folder.getFullPath();
- int mySegmentCount= myPath.segmentCount();
- int pkgSegmentCount= pkgPath.segmentCount();
- StringBuffer pkgName = new StringBuffer(IPackageFragment.DEFAULT_PACKAGE_NAME);
- for (int i= mySegmentCount; i < pkgSegmentCount; i++) {
- if (i > mySegmentCount) {
- pkgName.append('.');
- }
- pkgName.append(pkgPath.segment(i));
- }
- return pkgName.toString();
-}
-
-/**
- * @see IJavaScriptElement
- */
-public IPath getPath() {
- IResource resource = getResource();
- if(resource!=null) return resource.getFullPath();
-
- if(parent!=null) return parent.getPath();
- return null;
-}
-
-/*
- * @see IPackageFragmentRoot
- */
-public IIncludePathEntry getRawIncludepathEntry() throws JavaScriptModelException {
-
- IIncludePathEntry rawEntry = null;
- JavaProject project = (JavaProject)this.getJavaScriptProject();
- project.getResolvedClasspath(); // force the reverse rawEntry cache to be populated
- Map rootPathToRawEntries = project.getPerProjectInfo().rootPathToRawEntries;
- if (rootPathToRawEntries != null) {
- rawEntry = (IIncludePathEntry) rootPathToRawEntries.get(this.getPath());
- }
- if(rawEntry!=null) return rawEntry;
- /* no raw entry, so this must be a packagefragmentroot of a project with undefined source folder */
-
- return JavaScriptCore.newLibraryEntry(getPath().makeAbsolute(), getPath().makeAbsolute(), getPath().makeAbsolute());
-}
-
-public IIncludePathEntry getResolvedIncludepathEntry() throws JavaScriptModelException {
-
- IIncludePathEntry rawEntry = null;
- JavaProject project = (JavaProject)this.getJavaScriptProject();
- project.getResolvedClasspath(); // force the reverse rawEntry cache to be populated
- Map rootPathToResolvedEntries = project.getPerProjectInfo().rootPathToResolvedEntries;
- if (rootPathToResolvedEntries != null) {
- rawEntry = (IIncludePathEntry) rootPathToResolvedEntries.get(this.getPath());
- }
- if(rawEntry!=null) return rawEntry;
- /* no raw entry, so this must be a packagefragmentroot of a project with undefined source folder */
- /* no luck */
- return null;
-}
-
-
-/*
- * @see IJavaScriptElement
- */
-public IResource getResource() {
- return (IResource)this.resource;
-}
-
-/**
- * @see IPackageFragmentRoot
- */
-public IPath getSourceAttachmentPath() throws JavaScriptModelException {
- if (getKind() != K_BINARY) return null;
-
- // 1) look source attachment property (set iff attachSource(...) was called
- IPath path = getPath();
- String serverPathString= Util.getSourceAttachmentProperty(path);
- if (serverPathString != null) {
- int index= serverPathString.lastIndexOf(ATTACHMENT_PROPERTY_DELIMITER);
- if (index < 0) {
- // no root path specified
- return new Path(serverPathString);
- } else {
- String serverSourcePathString= serverPathString.substring(0, index);
- return new Path(serverSourcePathString);
- }
- }
-
- // 2) look at classpath entry
- IIncludePathEntry entry = ((JavaProject) getParent()).getClasspathEntryFor(path);
- IPath sourceAttachmentPath;
- if (entry != null && (sourceAttachmentPath = entry.getSourceAttachmentPath()) != null)
- return sourceAttachmentPath;
-
- // 3) look for a recommendation
- entry = findSourceAttachmentRecommendation();
- if (entry != null && (sourceAttachmentPath = entry.getSourceAttachmentPath()) != null) {
- return sourceAttachmentPath;
- }
-
- return null;
-}
-
-/**
- * For use by <code>AttachSourceOperation</code> only.
- * Sets the source mapper associated with this root.
- */
-public void setSourceMapper(SourceMapper mapper) throws JavaScriptModelException {
- ((PackageFragmentRootInfo) getElementInfo()).setSourceMapper(mapper);
-}
-
-
-
-/**
- * @see IPackageFragmentRoot
- */
-public IPath getSourceAttachmentRootPath() throws JavaScriptModelException {
- if (getKind() != K_BINARY) return null;
-
- // 1) look source attachment property (set iff attachSource(...) was called
- IPath path = getPath();
- String serverPathString= Util.getSourceAttachmentProperty(path);
- if (serverPathString != null) {
- int index = serverPathString.lastIndexOf(ATTACHMENT_PROPERTY_DELIMITER);
- if (index == -1) return null;
- String serverRootPathString= IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH;
- if (index != serverPathString.length() - 1) {
- serverRootPathString= serverPathString.substring(index + 1);
- }
- return new Path(serverRootPathString);
- }
-
- // 2) look at classpath entry
- IIncludePathEntry entry = ((JavaProject) getParent()).getClasspathEntryFor(path);
- IPath sourceAttachmentRootPath;
- if (entry != null && (sourceAttachmentRootPath = entry.getSourceAttachmentRootPath()) != null)
- return sourceAttachmentRootPath;
-
- // 3) look for a recomendation
- entry = findSourceAttachmentRecommendation();
- if (entry != null && (sourceAttachmentRootPath = entry.getSourceAttachmentRootPath()) != null)
- return sourceAttachmentRootPath;
-
- return null;
-}
-
-/**
- * @see JavaElement
- */
-public SourceMapper getSourceMapper() {
- SourceMapper mapper;
- try {
- PackageFragmentRootInfo rootInfo = (PackageFragmentRootInfo) getElementInfo();
- mapper = rootInfo.getSourceMapper();
- if (mapper == null) {
- // first call to this method
- IPath sourcePath= getSourceAttachmentPath();
- IPath rootPath= getSourceAttachmentRootPath();
- if (sourcePath == null)
- mapper = createSourceMapper(getPath(), rootPath); // attach root to itself
- else
- mapper = createSourceMapper(sourcePath, rootPath);
- rootInfo.setSourceMapper(mapper);
- }
- } catch (JavaScriptModelException e) {
- // no source can be attached
- mapper = null;
- }
- return mapper;
-}
-
-/**
- * @see IJavaScriptElement
- */
-public IResource getUnderlyingResource() throws JavaScriptModelException {
- if (!exists()) throw newNotPresentException();
- return getResource();
-}
-
-/**
- * @see org.eclipse.wst.jsdt.core.IParent
- */
-public boolean hasChildren() throws JavaScriptModelException {
- // a package fragment root always has the default package as a child
- return true;
-}
-
-public int hashCode() {
- if(this.resource!=null) return this.resource.hashCode();
- return super.hashCode();
-}
-
-/**
- * @see IPackageFragmentRoot
- */
-public boolean isArchive() {
- return false;
-}
-
-
-public boolean isResourceContainer()
-{
- return !isArchive();
-}
-
-/**
- * @see IPackageFragmentRoot
- */
-public boolean isExternal() {
- return false;
-}
-
-/*
- * Validate whether this package fragment root is on the classpath of its project.
- */
-protected IStatus validateOnClasspath() {
- return Status.OK_STATUS;
-// IPath path = this.getPath();
-// try {
-// // check package fragment root on classpath of its project
-// JavaProject project = (JavaProject) getJavaScriptProject();
-// IIncludePathEntry entry = project.getClasspathEntryFor(path);
-// if (entry != null) {
-// return Status.OK_STATUS;
-// }
-// } catch(JavaScriptModelException e){
-// // could not read classpath, then assume it is outside
-// return e.getJavaScriptModelStatus();
-// }
-// return new JavaModelStatus(IJavaScriptModelStatusConstants.ELEMENT_NOT_ON_CLASSPATH, this);
-}
-/*
- * @see org.eclipse.wst.jsdt.core.IPackageFragmentRoot#move
- */
-public void move(
- IPath destination,
- int updateResourceFlags,
- int updateModelFlags,
- IIncludePathEntry sibling,
- IProgressMonitor monitor)
- throws JavaScriptModelException {
-
- MovePackageFragmentRootOperation op =
- new MovePackageFragmentRootOperation(this, destination, updateResourceFlags, updateModelFlags, sibling);
- op.runOperation(monitor);
-}
-
-/**
- * @private Debugging purposes
- */
-protected void toStringInfo(int tab, StringBuffer buffer, Object info, boolean showResolvedInfo) {
- buffer.append(this.tabString(tab));
- IPath path = getPath();
- if (getJavaScriptProject().getElementName().equals(path.segment(0))) {
- if (path.segmentCount() == 1) {
- buffer.append("<project root>"); //$NON-NLS-1$
- } else {
- buffer.append(path.removeFirstSegments(1).makeRelative());
- }
- } else {
- if (isExternal()) {
- buffer.append(path.toOSString());
- } else {
- buffer.append(path);
- }
- }
- if (info == null) {
- buffer.append(" (not open)"); //$NON-NLS-1$
- }
-}
-
-/**
- * Possible failures: <ul>
- * <li>ELEMENT_NOT_PRESENT - the root supplied to the operation
- * does not exist
- * <li>INVALID_ELEMENT_TYPES - the root is not of kind K_BINARY
- * <li>RELATIVE_PATH - the path supplied to this operation must be
- * an absolute path
- * </ul>
- */
-protected void verifyAttachSource(IPath sourcePath) throws JavaScriptModelException {
- if (!exists()) {
- throw newNotPresentException();
- } else if (this.getKind() != K_BINARY) {
- throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_ELEMENT_TYPES, this));
- } else if (sourcePath != null && !sourcePath.isAbsolute()) {
- throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.RELATIVE_PATH, sourcePath));
- }
-}
-
-/* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.IPackageFragmentRoot#isLanguageRuntime()
- */
-public boolean isLanguageRuntime() {
- return false;
-}
-
-public IIncludePathAttribute[] getIncludepathAttributes() {
- IJavaScriptProject javaProject = getJavaScriptProject();
- IIncludePathEntry[] entries=null;
- IPath rootPath = getPath();
- if(rootPath==null) return new IIncludePathAttribute[0];
- try {
- entries = javaProject.getResolvedIncludepath(true);
- } catch (JavaScriptModelException ex) {}
-
- IIncludePathAttribute[] attribs=null;
- for(int i = 0;entries!=null && i<entries.length;i++) {
- if(rootPath.equals(entries[i].getPath())){
- attribs = entries[i].getExtraAttributes();
- break;
- }
- }
- if(attribs!=null) return attribs;
- return new IIncludePathAttribute[0];
-}
-public boolean isLibrary() {
- return false;
-}
-public JsGlobalScopeContainerInitializer getContainerInitializer() {
- IIncludePathEntry fClassPathEntry=null;
-
- try {
- fClassPathEntry = getRawIncludepathEntry();
- } catch (JavaScriptModelException ex) {}
-
- if(fClassPathEntry==null) return null;
-
-
- return JavaScriptCore.getJsGlobalScopeContainerInitializer(fClassPathEntry.getPath().segment(0));
-
-}
-
-public IPath getLocation() {
- return getResource().getLocation();
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/PackageFragmentRootInfo.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/PackageFragmentRootInfo.java
deleted file mode 100644
index 53ead4a8..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/PackageFragmentRootInfo.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*******************************************************************************
- * 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.core.resources.IContainer;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-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.internal.core.util.Util;
-
-/**
- * The element info for <code>PackageFragmentRoot</code>s.
- */
-class PackageFragmentRootInfo extends OpenableElementInfo {
-
- /**
- * The SourceMapper for this JAR (or <code>null</code> if
- * this JAR does not have source attached).
- */
- protected SourceMapper sourceMapper = null;
-
- /**
- * The kind of the root associated with this info.
- * Valid kinds are: <ul>
- * <li><code>IPackageFragmentRoot.K_SOURCE</code>
- * <li><code>IPackageFragmentRoot.K_BINARY</code></ul>
- */
- protected int fRootKind= IPackageFragmentRoot.K_SOURCE;
-
- /**
- * A array with all the non-java resources contained by this PackageFragment
- */
- protected Object[] fNonJavaResources;
-/**
- * Create and initialize a new instance of the receiver
- */
-public PackageFragmentRootInfo() {
- this.fNonJavaResources = null;
-}
-/**
- * Starting at this folder, create non-java resources for this package fragment root
- * and add them to the non-java resources collection.
- *
- * @exception JavaScriptModelException The resource associated with this package fragment does not exist
- */
-static Object[] computeFolderNonJavaResources(JavaProject project, IContainer folder, char[][] inclusionPatterns, char[][] exclusionPatterns) throws JavaScriptModelException {
- Object[] nonJavaResources = new IResource[5];
- int nonJavaResourcesCounter = 0;
- try {
- IIncludePathEntry[] classpath = project.getResolvedClasspath();
- IResource[] members = folder.members();
- int length = members.length;
- if (length > 0) {
- String sourceLevel = project.getOption(JavaScriptCore.COMPILER_SOURCE, true);
- String complianceLevel = project.getOption(JavaScriptCore.COMPILER_COMPLIANCE, true);
- nextResource: for (int i = 0; i < length; i++) {
- IResource member = members[i];
- switch (member.getType()) {
- case IResource.FILE :
- String fileName = member.getName();
-
- // ignore .js files that are not excluded
- if (Util.isValidCompilationUnitName(fileName, sourceLevel, complianceLevel) && !Util.isExcluded(member, inclusionPatterns, exclusionPatterns))
- continue nextResource;
- // ignore .class files
- if (Util.isValidClassFileName(fileName, sourceLevel, complianceLevel))
- continue nextResource;
- // ignore .zip or .jar file on classpath
- if (org.eclipse.wst.jsdt.internal.compiler.util.Util.isArchiveFileName(fileName) && isClasspathEntry(member.getFullPath(), classpath))
- continue nextResource;
- break;
-
- case IResource.FOLDER :
- // ignore valid packages or excluded folders that correspond to a nested pkg fragment root
- if (Util.isValidFolderNameForPackage(member.getName(), sourceLevel, complianceLevel)
- && (!Util.isExcluded(member, inclusionPatterns, exclusionPatterns)
- || isClasspathEntry(member.getFullPath(), classpath)))
- continue nextResource;
- break;
- }
- if (nonJavaResources.length == nonJavaResourcesCounter) {
- // resize
- System.arraycopy(nonJavaResources, 0, (nonJavaResources = new IResource[nonJavaResourcesCounter * 2]), 0, nonJavaResourcesCounter);
- }
- nonJavaResources[nonJavaResourcesCounter++] = member;
- }
- }
- if (nonJavaResources.length != nonJavaResourcesCounter) {
- System.arraycopy(nonJavaResources, 0, (nonJavaResources = new IResource[nonJavaResourcesCounter]), 0, nonJavaResourcesCounter);
- }
- return nonJavaResources;
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- }
-}
-/**
- * Compute the non-package resources of this package fragment root.
- */
-private Object[] computeNonJavaResources(IJavaScriptProject project, IResource underlyingResource, PackageFragmentRoot handle) {
- Object[] nonJavaResources = NO_NON_JAVA_RESOURCES;
- try {
- // the underlying resource may be a folder or a project (in the case that the project folder
- // is actually the package fragment root)
- if (underlyingResource!=null && (underlyingResource.getType() == IResource.FOLDER || underlyingResource.getType() == IResource.PROJECT)) {
- nonJavaResources =
- computeFolderNonJavaResources(
- (JavaProject)project,
- (IContainer) underlyingResource,
- handle.fullInclusionPatternChars(),
- handle.fullExclusionPatternChars());
- }
- } catch (JavaScriptModelException e) {
- // ignore
- }
- return nonJavaResources;
-}
-/**
- * Returns an array of non-java resources contained in the receiver.
- */
-synchronized Object[] getNonJavaResources(IJavaScriptProject project, IResource underlyingResource, PackageFragmentRoot handle) {
- Object[] nonJavaResources = this.fNonJavaResources;
- if (nonJavaResources == null) {
- nonJavaResources = this.computeNonJavaResources(project, underlyingResource, handle);
- this.fNonJavaResources = nonJavaResources;
- }
- return nonJavaResources;
-}
-/**
- * Returns the kind of this root.
- */
-public int getRootKind() {
- return this.fRootKind;
-}
-/**
- * Retuns the SourceMapper for this root, or <code>null</code>
- * if this root does not have attached source.
- */
-protected SourceMapper getSourceMapper() {
- return this.sourceMapper;
-}
-private static boolean isClasspathEntry(IPath path, IIncludePathEntry[] resolvedClasspath) {
- for (int i = 0, length = resolvedClasspath.length; i < length; i++) {
- IIncludePathEntry entry = resolvedClasspath[i];
- if (entry.getPath().equals(path)) {
- return true;
- }
- }
- return false;
-}
-/**
- * Set the fNonJavaResources to res value
- */
-void setNonJavaResources(Object[] resources) {
- this.fNonJavaResources = resources;
-}
-/**
- * Sets the kind of this root.
- */
-protected void setRootKind(int newRootKind) {
- this.fRootKind = newRootKind;
-}
-/**
- * Sets the SourceMapper for this root.
- */
-protected void setSourceMapper(SourceMapper mapper) {
- this.sourceMapper= mapper;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ProjectReferenceChange.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ProjectReferenceChange.java
deleted file mode 100644
index 55e17984..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ProjectReferenceChange.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*******************************************************************************
- * 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 java.util.HashSet;
-import java.util.Iterator;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IProjectDescription;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-public class ProjectReferenceChange {
-
- private JavaProject project;
- private IIncludePathEntry[] oldResolvedClasspath;
-
- public ProjectReferenceChange(JavaProject project, IIncludePathEntry[] oldResolvedClasspath) {
- this.project = project;
- this.oldResolvedClasspath = oldResolvedClasspath;
- }
-
- /*
- * Update projects references so that the build order is consistent with the classpath
- */
- public void updateProjectReferencesIfNecessary() throws JavaScriptModelException {
-
- String[] oldRequired = this.oldResolvedClasspath == null ? CharOperation.NO_STRINGS : this.project.projectPrerequisites(this.oldResolvedClasspath);
- IIncludePathEntry[] newResolvedClasspath = this.project.getResolvedClasspath();
- String[] newRequired = this.project.projectPrerequisites(newResolvedClasspath);
- try {
- IProject projectResource = this.project.getProject();
- IProjectDescription description = projectResource.getDescription();
-
- IProject[] projectReferences = description.getDynamicReferences();
-
- HashSet oldReferences = new HashSet(projectReferences.length);
- for (int i = 0; i < projectReferences.length; i++){
- String projectName = projectReferences[i].getName();
- oldReferences.add(projectName);
- }
- HashSet newReferences = (HashSet)oldReferences.clone();
-
- for (int i = 0; i < oldRequired.length; i++){
- String projectName = oldRequired[i];
- newReferences.remove(projectName);
- }
- for (int i = 0; i < newRequired.length; i++){
- String projectName = newRequired[i];
- newReferences.add(projectName);
- }
-
- Iterator iter;
- int newSize = newReferences.size();
-
- checkIdentity: {
- if (oldReferences.size() == newSize){
- iter = newReferences.iterator();
- while (iter.hasNext()){
- if (!oldReferences.contains(iter.next())){
- break checkIdentity;
- }
- }
- return;
- }
- }
- String[] requiredProjectNames = new String[newSize];
- int index = 0;
- iter = newReferences.iterator();
- while (iter.hasNext()){
- requiredProjectNames[index++] = (String)iter.next();
- }
- Util.sort(requiredProjectNames); // ensure that if changed, the order is consistent
-
- IProject[] requiredProjectArray = new IProject[newSize];
- IWorkspaceRoot wksRoot = projectResource.getWorkspace().getRoot();
- for (int i = 0; i < newSize; i++){
- requiredProjectArray[i] = wksRoot.getProject(requiredProjectNames[i]);
- }
- description.setDynamicReferences(requiredProjectArray);
- projectResource.setDescription(description, null);
-
- } catch(CoreException e){
- if (!ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals(this.project.getElementName()))
- throw new JavaScriptModelException(e);
- }
- }
- public String toString() {
- return "ProjectRefenceChange: " + this.project.getElementName(); //$NON-NLS-1$
- }
-}
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
deleted file mode 100644
index d02b640f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ReconcileWorkingCopyOperation.java
+++ /dev/null
@@ -1,283 +0,0 @@
-/*******************************************************************************
- * 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 java.util.HashMap;
-import java.util.Iterator;
-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.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.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;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * Reconcile a working copy and signal the changes through a delta.
- * <p>
- * High level summmary of what a reconcile does:
- * <ul>
- * <li>populates the model with the new working copy contents</li>
- * <li>fires a fine grained delta (flag F_FINE_GRAINED) describing the difference between the previous content
- * and the new content (which method was added/removed, which field was changed, etc.)</li>
- * <li>computes problems and reports them to the IProblemRequestor (begingReporting(), n x acceptProblem(...), endReporting()) iff
- * (working copy is not consistent with its buffer || forceProblemDetection is set)
- * && problem requestor is active
- * </li>
- * <li>produces a DOM AST (either JLS_2, JLS_3 or NO_AST) that is resolved if flag is set</li>
- * <li>notifies compilation participants of the reconcile allowing them to participate in this operation and report problems</li>
- * </ul>
- */
-public class ReconcileWorkingCopyOperation extends JavaModelOperation {
- public static boolean PERF = false;
-
- public int astLevel;
- public boolean resolveBindings;
- public HashMap problems;
- public int reconcileFlags;
- WorkingCopyOwner workingCopyOwner;
- public org.eclipse.wst.jsdt.core.dom.JavaScriptUnit ast;
- public JavaElementDeltaBuilder deltaBuilder;
- public boolean requestorIsActive;
-
- public ReconcileWorkingCopyOperation(IJavaScriptElement workingCopy, int astLevel, int reconcileFlags, WorkingCopyOwner workingCopyOwner) {
- super(new IJavaScriptElement[] {workingCopy});
- this.astLevel = astLevel;
- this.reconcileFlags = reconcileFlags;
- this.workingCopyOwner = workingCopyOwner;
- }
-
- /**
- * @exception JavaScriptModelException if setting the source
- * of the original compilation unit fails
- */
- protected void executeOperation() throws JavaScriptModelException {
- checkCanceled();
- try {
- beginTask(Messages.element_reconciling, 2);
-
- CompilationUnit workingCopy = getWorkingCopy();
- boolean wasConsistent = workingCopy.isConsistent();
-
- // check is problem requestor is active
- IProblemRequestor problemRequestor = workingCopy.getPerWorkingCopyInfo();
- if (problemRequestor != null)
- problemRequestor = ((JavaModelManager.PerWorkingCopyInfo)problemRequestor).getProblemRequestor();
- boolean defaultRequestorIsActive = problemRequestor != null && problemRequestor.isActive();
- IProblemRequestor ownerProblemRequestor = this.workingCopyOwner.getProblemRequestor(workingCopy);
- boolean ownerRequestorIsActive = ownerProblemRequestor != null && ownerProblemRequestor != problemRequestor && ownerProblemRequestor.isActive();
- this.requestorIsActive = defaultRequestorIsActive || ownerRequestorIsActive;
-
- // create the delta builder (this remembers the current content of the cu)
- this.deltaBuilder = new JavaElementDeltaBuilder(workingCopy);
-
- // make working copy consistent if needed and compute AST if needed
- makeConsistent(workingCopy);
-
- // notify reconcile participants only if working copy was not consistent or if forcing problem detection
- // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=177319)
- if (!wasConsistent || ((this.reconcileFlags & IJavaScriptUnit.FORCE_PROBLEM_DETECTION) != 0)) {
- notifyParticipants(workingCopy);
-
- // recreate ast if one participant reset it
- if (this.ast == null && this.astLevel!=IJavaScriptUnit.NO_AST)
- makeConsistent(workingCopy);
- }
-
- // report problems
- if (this.problems != null && (((this.reconcileFlags & IJavaScriptUnit.FORCE_PROBLEM_DETECTION) != 0) || !wasConsistent)) {
- if (defaultRequestorIsActive) {
- reportProblems(workingCopy, problemRequestor);
- }
- if (ownerRequestorIsActive) {
- reportProblems(workingCopy, ownerProblemRequestor);
- }
- }
-
- // report delta
- JavaElementDelta delta = this.deltaBuilder.delta;
- if (delta != null) {
- addReconcileDelta(workingCopy, delta);
- }
- } finally {
- done();
- }
- }
-
- /**
- * Report working copy problems to a given requestor.
- *
- * @param workingCopy
- * @param problemRequestor
- */
- private void reportProblems(CompilationUnit workingCopy, IProblemRequestor problemRequestor) {
- try {
- problemRequestor.beginReporting();
- for (Iterator iteraror = this.problems.values().iterator(); iteraror.hasNext();) {
- CategorizedProblem[] categorizedProblems = (CategorizedProblem[]) iteraror.next();
- if (categorizedProblems == null) continue;
- for (int i = 0, length = categorizedProblems.length; i < length; i++) {
- CategorizedProblem problem = categorizedProblems[i];
- if (JavaModelManager.VERBOSE){
- System.out.println("PROBLEM FOUND while reconciling : " + problem.getMessage());//$NON-NLS-1$
- }
- if (this.progressMonitor != null && this.progressMonitor.isCanceled()) break;
- problemRequestor.acceptProblem(problem);
- }
- }
- } finally {
- problemRequestor.endReporting();
- }
- }
-
- /**
- * Returns the working copy this operation is working on.
- */
- protected CompilationUnit getWorkingCopy() {
- return (CompilationUnit)getElementToProcess();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.core.JavaModelOperation#isReadOnly()
- */
- public boolean isReadOnly() {
- return true;
- }
-
- /*
- * Makes the given working copy consistent, computes the delta and computes an AST if needed.
- * Returns the AST.
- */
- public org.eclipse.wst.jsdt.core.dom.JavaScriptUnit makeConsistent(CompilationUnit workingCopy) throws JavaScriptModelException {
- if (!workingCopy.isConsistent()) {
- // make working copy consistent
- if (this.problems == null) this.problems = new HashMap();
- this.resolveBindings = this.requestorIsActive;
- this.ast = workingCopy.makeConsistent(this.astLevel, this.resolveBindings, reconcileFlags, this.problems, this.progressMonitor);
- this.deltaBuilder.buildDeltas();
- if (this.ast != null && this.deltaBuilder.delta != null)
- this.deltaBuilder.delta.changedAST(this.ast);
- return this.ast;
- }
- if (this.ast != null)
- return this.ast; // no need to recompute AST if known already
-
- CompilationUnitDeclaration unit = null;
- char[] contents = null;
- try {
- // find problems if needed
- if (JavaProject.hasJavaNature(workingCopy.getJavaScriptProject().getProject())
- && (this.reconcileFlags & IJavaScriptUnit.FORCE_PROBLEM_DETECTION) != 0) {
- this.resolveBindings = this.requestorIsActive;
- if (this.problems == null)
- this.problems = new HashMap();
- contents = workingCopy.getContents();
- unit =
- CompilationUnitProblemFinder.process(
- workingCopy,
- contents,
- this.workingCopyOwner,
- this.problems,
- this.astLevel != IJavaScriptUnit.NO_AST/*creating AST if level is not NO_AST */,
- reconcileFlags,
- this.progressMonitor);
- if (this.progressMonitor != null) this.progressMonitor.worked(1);
- }
-
- // create AST if needed
- if (this.astLevel != IJavaScriptUnit.NO_AST
- && unit !=null/*unit is null if working copy is consistent && (problem detection not forced || non-Java project) -> don't create AST as per API*/) {
- Map options = workingCopy.getJavaScriptProject().getOptions(true);
- // convert AST
- this.ast =
- AST.convertCompilationUnit(
- this.astLevel,
- unit,
- contents,
- options,
- this.resolveBindings,
- workingCopy,
- reconcileFlags,
- this.progressMonitor);
- if (this.ast != null) {
- this.deltaBuilder.delta = new JavaElementDelta(workingCopy);
- this.deltaBuilder.delta.changedAST(this.ast);
- }
- if (this.progressMonitor != null) this.progressMonitor.worked(1);
- }
- } catch (JavaScriptModelException e) {
- if (JavaProject.hasJavaNature(workingCopy.getJavaScriptProject().getProject()))
- throw e;
- // else JavaProject has lost its nature (or most likely was closed/deleted) while reconciling -> ignore
- // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=100919)
- } finally {
- if (unit != null) {
- unit.cleanUp();
- if (unit.scope!=null)
- unit.scope.cleanup();
- }
- }
- return this.ast;
- }
-
- private void notifyParticipants(final CompilationUnit workingCopy) {
- IJavaScriptProject javaProject = getWorkingCopy().getJavaScriptProject();
- ValidationParticipant[] participants = JavaModelManager.getJavaModelManager().validationParticipants.getvalidationParticipants(javaProject);
- if (participants == null) return;
-
- final ReconcileContext context = new ReconcileContext(this, workingCopy);
- for (int i = 0, length = participants.length; i < length; i++) {
- final ValidationParticipant participant = participants[i];
- SafeRunner.run(new ISafeRunnable() {
- public void handleException(Throwable exception) {
- if (exception instanceof Error) {
- throw (Error) exception; // errors are not supposed to be caught
- } else if (exception instanceof OperationCanceledException)
- throw (OperationCanceledException) exception;
- else if (exception instanceof UnsupportedOperationException) {
- // might want to disable participant as it tried to modify the buffer of the working copy being reconciled
- Util.log(exception, "Reconcile participant attempted to modify the buffer of the working copy being reconciled"); //$NON-NLS-1$
- } else
- Util.log(exception, "Exception occurred in reconcile participant"); //$NON-NLS-1$
- }
- public void run() throws Exception {
- participant.reconcile(context);
- }
- });
- }
- }
-
- protected IJavaScriptModelStatus verify() {
- IJavaScriptModelStatus status = super.verify();
- if (!status.isOK()) {
- return status;
- }
- CompilationUnit workingCopy = getWorkingCopy();
- if (!workingCopy.isWorkingCopy()) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.ELEMENT_DOES_NOT_EXIST, workingCopy); //was destroyed
- }
- return status;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/Region.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/Region.java
deleted file mode 100644
index 7c25d175..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/Region.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/*******************************************************************************
- * 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 java.util.ArrayList;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IParent;
-import org.eclipse.wst.jsdt.core.IRegion;
-
-/**
- * @see IRegion
- */
-
-public class Region implements IRegion {
-
- /**
- * A collection of the top level elements
- * that have been added to the region
- */
- protected ArrayList fRootElements;
-/**
- * Creates an empty region.
- *
- * @see IRegion
- */
-public Region() {
- fRootElements = new ArrayList(1);
-}
-/**
- * @see IRegion#add(IJavaScriptElement)
- */
-public void add(IJavaScriptElement element) {
- if (!contains(element)) {
- //"new" element added to region
- removeAllChildren(element);
- fRootElements.add(element);
- fRootElements.trimToSize();
- }
-}
-/**
- * @see IRegion
- */
-public boolean contains(IJavaScriptElement element) {
-
- int size = fRootElements.size();
- ArrayList parents = getAncestors(element);
-
- for (int i = 0; i < size; i++) {
- IJavaScriptElement aTop = (IJavaScriptElement) fRootElements.get(i);
- if (aTop.equals(element)) {
- return true;
- }
- for (int j = 0, pSize = parents.size(); j < pSize; j++) {
- if (aTop.equals(parents.get(j))) {
- //an ancestor is already included
- return true;
- }
- }
- }
- return false;
-}
-/**
- * Returns a collection of all the parents of this element
- * in bottom-up order.
- *
- */
-private ArrayList getAncestors(IJavaScriptElement element) {
- ArrayList parents = new ArrayList();
- IJavaScriptElement parent = element.getParent();
- while (parent != null) {
- parents.add(parent);
- parent = parent.getParent();
- }
- parents.trimToSize();
- return parents;
-}
-/**
- * @see IRegion
- */
-public IJavaScriptElement[] getElements() {
- int size= fRootElements.size();
- IJavaScriptElement[] roots= new IJavaScriptElement[size];
- for (int i = 0; i < size; i++) {
- roots[i]= (IJavaScriptElement) fRootElements.get(i);
- }
-
- return roots;
-}
-/**
- * @see IRegion#remove(IJavaScriptElement)
- */
-public boolean remove(IJavaScriptElement element) {
-
- removeAllChildren(element);
- return fRootElements.remove(element);
-}
-/**
- * Removes any children of this element that are contained within this
- * region as this parent is about to be added to the region.
- *
- * <p>Children are all children, not just direct children.
- */
-protected void removeAllChildren(IJavaScriptElement element) {
- if (element instanceof IParent) {
- ArrayList newRootElements = new ArrayList();
- for (int i = 0, size = fRootElements.size(); i < size; i++) {
- IJavaScriptElement currentRoot = (IJavaScriptElement)fRootElements.get(i);
- //walk the current root hierarchy
- IJavaScriptElement parent = currentRoot.getParent();
- boolean isChild= false;
- while (parent != null) {
- if (parent.equals(element)) {
- isChild= true;
- break;
- }
- parent = parent.getParent();
- }
- if (!isChild) {
- newRootElements.add(currentRoot);
- }
- }
- fRootElements= newRootElements;
- }
-}
-/**
- * Returns a printable representation of this region.
- */
-public String toString() {
- StringBuffer buffer= new StringBuffer();
- IJavaScriptElement[] roots= getElements();
- buffer.append('[');
- for (int i= 0; i < roots.length; i++) {
- buffer.append(roots[i].getElementName());
- if (i < (roots.length - 1)) {
- buffer.append(", "); //$NON-NLS-1$
- }
- }
- buffer.append(']');
- return buffer.toString();
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/RenameElementsOperation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/RenameElementsOperation.java
deleted file mode 100644
index 388f78f7..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/RenameElementsOperation.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*******************************************************************************
- * 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.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatus;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatusConstants;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-
-/**
- * This operation renames elements.
- *
- * <p>Notes:<ul>
- * <li>Resource rename is not supported - this operation only renames
- * elements contained in compilation units.
- * <li>When a main type is renamed, its compilation unit and constructors are renamed.
- * <li>Constructors cannot be renamed.
- * </ul>
- */
-public class RenameElementsOperation extends MoveElementsOperation {
-/**
- * When executed, this operation will rename the specified elements with the given names in the
- * corresponding destinations.
- */
-public RenameElementsOperation(IJavaScriptElement[] elements, IJavaScriptElement[] destinations, String[] newNames, boolean force) {
- //a rename is a move to the same parent with a new name specified
- //these elements are from different parents
- super(elements, destinations, force);
- setRenamings(newNames);
-}
-/**
- * @see MultiOperation
- */
-protected String getMainTaskName() {
- return Messages.operation_renameElementProgress;
-}
-/**
- * @see CopyElementsOperation#isRename()
- */
-protected boolean isRename() {
- return true;
-}
-/**
- * @see MultiOperation
- */
-protected IJavaScriptModelStatus verify() {
- IJavaScriptModelStatus status = super.verify();
- if (! status.isOK())
- return status;
- if (this.renamingsList == null || this.renamingsList.length == 0)
- return new JavaModelStatus(IJavaScriptModelStatusConstants.NULL_NAME);
- return JavaModelStatus.VERIFIED_OK;
-}
-/**
- * @see MultiOperation
- */
-protected void verify(IJavaScriptElement element) throws JavaScriptModelException {
- if (element == null || !element.exists())
- error(IJavaScriptModelStatusConstants.ELEMENT_DOES_NOT_EXIST, element);
-
- if (element.isReadOnly())
- error(IJavaScriptModelStatusConstants.READ_ONLY, element);
-
- if (!(element instanceof ISourceReference))
- error(IJavaScriptModelStatusConstants.INVALID_ELEMENT_TYPES, element);
-
- int elementType = element.getElementType();
- if (elementType < IJavaScriptElement.TYPE || elementType == IJavaScriptElement.INITIALIZER)
- error(IJavaScriptModelStatusConstants.INVALID_ELEMENT_TYPES, element);
-
- verifyRenaming(element);
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/RenameResourceElementsOperation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/RenameResourceElementsOperation.java
deleted file mode 100644
index 893adb40..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/RenameResourceElementsOperation.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*******************************************************************************
- * 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.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatusConstants;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-
-/**
- * This operation renames resources (Package fragments and compilation units).
- *
- * <p>Notes:<ul>
- * <li>When a compilation unit is renamed, its main type and the constructors of the
- * main type are renamed.
- * </ul>
- */
-public class RenameResourceElementsOperation extends MoveResourceElementsOperation {
-/**
- * When executed, this operation will rename the specified elements with the given names in the
- * corresponding destinations.
- */
-public RenameResourceElementsOperation(IJavaScriptElement[] elements, IJavaScriptElement[] destinations, String[] newNames, boolean force) {
- //a rename is a move to the same parent with a new name specified
- //these elements are from different parents
- super(elements, destinations, force);
- setRenamings(newNames);
-}
-/**
- * @see MultiOperation
- */
-protected String getMainTaskName() {
- return Messages.operation_renameResourceProgress;
-}
-/**
- * @see CopyResourceElementsOperation#isRename()
- */
-protected boolean isRename() {
- return true;
-}
-/**
- * @see MultiOperation
- */
-protected void verify(IJavaScriptElement element) throws JavaScriptModelException {
- super.verify(element);
-
- int elementType = element.getElementType();
-
- if (!(elementType == IJavaScriptElement.JAVASCRIPT_UNIT || elementType == IJavaScriptElement.PACKAGE_FRAGMENT)) {
- error(IJavaScriptModelStatusConstants.INVALID_ELEMENT_TYPES, element);
- }
- if (elementType == IJavaScriptElement.JAVASCRIPT_UNIT) {
- CompilationUnit cu = (CompilationUnit)element;
- if (cu.isWorkingCopy() && !cu.isPrimary()) {
- error(IJavaScriptModelStatusConstants.INVALID_ELEMENT_TYPES, element);
- }
- }
- verifyRenaming(element);
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ResolvedBinaryField.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ResolvedBinaryField.java
deleted file mode 100644
index 31706e67..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ResolvedBinaryField.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core;
-
-/**
- * Handle representing a binary field that is resolved.
- * The uniqueKey contains the genericSignature of the resolved field. Use BindingKey to decode it.
- */
-public class ResolvedBinaryField extends BinaryField {
-
- private String uniqueKey;
-
- /*
- * See class comments.
- */
- public ResolvedBinaryField(JavaElement parent, String name, String uniqueKey) {
- super(parent, name);
- this.uniqueKey = uniqueKey;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.core.BinaryField#getKey()
- */
- public String getKey() {
- return this.uniqueKey;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.IField#isResolved()
- */
- public boolean isResolved() {
- return true;
- }
-
- /**
- * @private Debugging purposes
- */
- protected void toStringInfo(int tab, StringBuffer buffer, Object info, boolean showResolvedInfo) {
- super.toStringInfo(tab, buffer, info, showResolvedInfo);
- if (showResolvedInfo) {
- buffer.append(" {key="); //$NON-NLS-1$
- buffer.append(this.uniqueKey);
- buffer.append("}"); //$NON-NLS-1$
- }
- }
-
- public JavaElement unresolved() {
- SourceRefElement handle = new BinaryField(this.parent, this.name);
- handle.occurrenceCount = this.occurrenceCount;
- return handle;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ResolvedBinaryMethod.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ResolvedBinaryMethod.java
deleted file mode 100644
index 9e924e14..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ResolvedBinaryMethod.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core;
-
-/**
- * Handle representing a binary method that is resolved.
- * The uniqueKey contains the genericSignature of the resolved method. Use BindingKey to decode it.
- */
-public class ResolvedBinaryMethod extends BinaryMethod {
-
- private String uniqueKey;
-
- /*
- * See class comments.
- */
- public ResolvedBinaryMethod(JavaElement parent, String name, String[] parameterTypes, String uniqueKey) {
- super(parent, name, parameterTypes);
- this.uniqueKey = uniqueKey;
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.core.BinaryMethod#getKey()
- */
- public String getKey() {
- return this.uniqueKey;
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.IFunction#isResolved()
- */
- public boolean isResolved() {
- return true;
- }
-
- /**
- * @private Debugging purposes
- */
- protected void toStringInfo(int tab, StringBuffer buffer, Object info, boolean showResolvedInfo) {
- super.toStringInfo(tab, buffer, info, showResolvedInfo);
- if (showResolvedInfo) {
- buffer.append(" {key="); //$NON-NLS-1$
- buffer.append(this.uniqueKey);
- buffer.append("}"); //$NON-NLS-1$
- }
- }
-
- public JavaElement unresolved() {
- SourceRefElement handle = new BinaryMethod(this.parent, this.name, this.parameterTypes);
- handle.occurrenceCount = this.occurrenceCount;
- return handle;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ResolvedBinaryType.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ResolvedBinaryType.java
deleted file mode 100644
index 7e6f1001..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ResolvedBinaryType.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*******************************************************************************
- * 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
- * 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.core.JavaScriptModelException;
-
-/**
- * Handle representing a binary type that is resolved.
- * The uniqueKey contains the genericTypeSignature of the resolved type. Use BindingKey to decode it.
- */
-public class ResolvedBinaryType extends BinaryType {
-
- private String uniqueKey;
-
- /*
- * See class comments.
- */
- public ResolvedBinaryType(JavaElement parent, String name, String uniqueKey) {
- super(parent, name);
- this.uniqueKey = uniqueKey;
- }
-
- public String getFullyQualifiedParameterizedName() throws JavaScriptModelException {
- return getFullyQualifiedParameterizedName(getFullyQualifiedName(), this.uniqueKey);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.core.BinaryType#getKey()
- */
- public String getKey() {
- return this.uniqueKey;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.core.BinaryType#isResolved()
- */
- public boolean isResolved() {
- return true;
- }
-
- /**
- * @private Debugging purposes
- */
- protected void toStringInfo(int tab, StringBuffer buffer, Object info, boolean showResolvedInfo) {
- super.toStringInfo(tab, buffer, info, showResolvedInfo);
- if (showResolvedInfo) {
- buffer.append(" {key="); //$NON-NLS-1$
- buffer.append(this.uniqueKey);
- buffer.append("}"); //$NON-NLS-1$
- }
- }
-
- public JavaElement unresolved() {
- SourceRefElement handle = new BinaryType(this.parent, this.name);
- handle.occurrenceCount = this.occurrenceCount;
- return handle;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ResolvedSourceField.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ResolvedSourceField.java
deleted file mode 100644
index 8b392220..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ResolvedSourceField.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2004, 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.internal.core;
-
-import org.eclipse.wst.jsdt.core.IBuffer;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.ToolFactory;
-import org.eclipse.wst.jsdt.core.compiler.IScanner;
-import org.eclipse.wst.jsdt.core.compiler.ITerminalSymbols;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-
-/**
- * Handle representing a source field that is resolved. The uniqueKey contains
- * the genericSignature of the resolved field. Use BindingKey to decode it.
- */
-public class ResolvedSourceField extends SourceField {
-
- private String uniqueKey;
-
- /*
- * See class comments.
- */
- public ResolvedSourceField(JavaElement parent, String name, String uniqueKey) {
- super(parent, name);
- this.uniqueKey = uniqueKey;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.wst.jsdt.internal.core.SourceField#getKey()
- */
- public String getKey() {
- return this.uniqueKey;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.wst.jsdt.core.IField#isResolved()
- */
- public boolean isResolved() {
- return true;
- }
-
- /**
- * @private Debugging purposes
- */
- protected void toStringInfo(int tab, StringBuffer buffer, Object info, boolean showResolvedInfo) {
- super.toStringInfo(tab, buffer, info, showResolvedInfo);
- if (showResolvedInfo) {
- buffer.append(" {key="); //$NON-NLS-1$
- buffer.append(this.uniqueKey);
- buffer.append("}"); //$NON-NLS-1$
- }
- }
-
- public JavaElement unresolved() {
- SourceRefElement handle = new SourceField(this.parent, this.name);
- handle.occurrenceCount = this.occurrenceCount;
- return handle;
- }
-
- // workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=278904
- public ISourceRange getJSdocRange() throws JavaScriptModelException {
- ISourceRange defaultRange = super.getJSdocRange();
- if (defaultRange != null)
- return defaultRange;
-
- ISourceRange range = this.getSourceRange();
- if (range == null)
- return null;
- IBuffer buf = null;
- if (this.isBinary()) {
- buf = this.getClassFile().getBuffer();
- }
- else {
- IJavaScriptUnit compilationUnit = this.getJavaScriptUnit();
- if (!compilationUnit.isConsistent()) {
- return null;
- }
- buf = compilationUnit.getBuffer();
- }
- final int start = range.getOffset();
- final int length = range.getLength();
- if (length > 0 && buf.getChar(start) != '/') {
- IScanner scanner = ToolFactory.createScanner(true, false, false, false);
- scanner.setSource(buf.getContents().toCharArray());
- try {
- int docOffset = -1;
- int docEnd = -1;
-
- int previousTerminal = -1;
- int previousOffset = -1;
- int previousEnd = -1;
-
- int terminal = scanner.getNextToken();
- loop : while (true) {
- if (scanner.getCurrentTokenEndPosition() < start) {
- previousTerminal = terminal;
- previousOffset = scanner.getCurrentTokenStartPosition();
- previousEnd = scanner.getCurrentTokenEndPosition() + 1;
- terminal = scanner.getNextToken();
- continue loop;
- }
-
- switch (previousTerminal) {
- case ITerminalSymbols.TokenNameCOMMENT_BLOCK :
- case ITerminalSymbols.TokenNameCOMMENT_JAVADOC :
- docOffset = previousOffset;
- docEnd = previousEnd;
- terminal = scanner.getNextToken();
- break loop;
- default :
- break loop;
- }
- }
- if (docOffset != -1) {
- return new SourceRange(docOffset, docEnd - docOffset + 1);
- }
- }
- catch (InvalidInputException ex) {
- // try if there is inherited Javadoc
- }
- }
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ResolvedSourceMethod.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ResolvedSourceMethod.java
deleted file mode 100644
index 4f40027d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ResolvedSourceMethod.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core;
-
-/**
- * Handle representing a source method that is resolved.
- * The uniqueKey contains the genericSignature of the resolved method. Use BindingKey to decode it.
- */
-public class ResolvedSourceMethod extends SourceMethod {
-
- private String uniqueKey;
-
- /*
- * See class comments.
- */
- public ResolvedSourceMethod(JavaElement parent, String name, String[] parameterTypes, String uniqueKey) {
- super(parent, name, parameterTypes);
- this.uniqueKey = uniqueKey;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.core.SourceMethod#getKey()
- */
- public String getKey() {
- return this.uniqueKey;
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.IFunction#isResolved()
- */
- public boolean isResolved() {
- return true;
- }
-
- /**
- * @private Debugging purposes
- */
- protected void toStringInfo(int tab, StringBuffer buffer, Object info, boolean showResolvedInfo) {
- super.toStringInfo(tab, buffer, info, showResolvedInfo);
- if (showResolvedInfo) {
- buffer.append(" {key="); //$NON-NLS-1$
- buffer.append(this.uniqueKey);
- buffer.append("}"); //$NON-NLS-1$
- }
- }
-
- public JavaElement unresolved() {
- SourceRefElement handle = new SourceMethod(this.parent, this.name, this.parameterTypes);
- handle.occurrenceCount = this.occurrenceCount;
- return handle;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ResolvedSourceType.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ResolvedSourceType.java
deleted file mode 100644
index eb4379da..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ResolvedSourceType.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*******************************************************************************
- * 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
- * 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.core.JavaScriptModelException;
-
-/**
- * Handle representing a source type that is resolved.
- * The uniqueKey contains the genericTypeSignature of the resolved type. Use BindingKey to decode it.
- */
-public class ResolvedSourceType extends SourceType {
-
- private String uniqueKey;
-
- /*
- * See class comments.
- */
- public ResolvedSourceType(JavaElement parent, String name, String uniqueKey) {
- super(parent, name);
- this.uniqueKey = uniqueKey;
- }
-
- public String getFullyQualifiedParameterizedName() throws JavaScriptModelException {
- return getFullyQualifiedParameterizedName(getFullyQualifiedName(), this.uniqueKey);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.core.SourceType#getKey()
- */
- public String getKey() {
- return this.uniqueKey;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.core.SourceType#isResolved()
- */
- public boolean isResolved() {
- return true;
- }
-
- /**
- * @private Debugging purposes
- */
- protected void toStringInfo(int tab, StringBuffer buffer, Object info, boolean showResolvedInfo) {
- super.toStringInfo(tab, buffer, info, showResolvedInfo);
- if (showResolvedInfo) {
- buffer.append(" {key="); //$NON-NLS-1$
- buffer.append(this.uniqueKey);
- buffer.append("}"); //$NON-NLS-1$
- }
- }
-
- public JavaElement unresolved() {
- SourceRefElement handle = new SourceType(this.parent, this.name);
- handle.occurrenceCount = this.occurrenceCount;
- return handle;
- }
-}
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
deleted file mode 100644
index 3dd28835..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SearchableEnvironment.java
+++ /dev/null
@@ -1,880 +0,0 @@
-/*******************************************************************************
- * 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;
-
-import java.util.ArrayList;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IOpenable;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-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.UnimplementedException;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.infer.IInferenceFile;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.codeassist.ISearchRequestor;
-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.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.IRestrictedAccessBindingRequestor;
-import org.eclipse.wst.jsdt.internal.core.search.IRestrictedAccessTypeRequestor;
-
-/**
- * This class provides a <code>SearchableBuilderEnvironment</code> for code
- * assist which uses the Java model as a search tool.
- */
-public class SearchableEnvironment implements INameEnvironment,
- IJavaScriptSearchConstants {
-
- public NameLookup nameLookup;
-
- protected ICompilationUnit unitToSkip;
-
- protected org.eclipse.wst.jsdt.core.IJavaScriptUnit[] workingCopies;
-
- protected JavaProject javaProject;
-
- protected IJavaScriptSearchScope searchScope;
-
- protected boolean checkAccessRestrictions;
-
- /**
- * Creates a SearchableEnvironment on the given project
- */
- public SearchableEnvironment(JavaProject project,
- IRestrictedAccessBindingRequestor resolutionScope,
- org.eclipse.wst.jsdt.core.IJavaScriptUnit[] workingCopies)
- throws JavaScriptModelException {
-
- this.javaProject = project;
- this.checkAccessRestrictions = !JavaScriptCore.IGNORE.equals(project
- .getOption(JavaScriptCore.COMPILER_PB_FORBIDDEN_REFERENCE, true))
- || !JavaScriptCore.IGNORE.equals(project.getOption(
- JavaScriptCore.COMPILER_PB_DISCOURAGED_REFERENCE, true));
- this.workingCopies = workingCopies;
- 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.nameLookup.searchScope=this.searchScope;
- }
- public SearchableEnvironment(JavaProject project,
-
- org.eclipse.wst.jsdt.core.IJavaScriptUnit[] workingCopies)
- throws JavaScriptModelException {
- this(project,null,workingCopies);
- }
- /**
- * Creates a SearchableEnvironment on the given project
- */
- public SearchableEnvironment(JavaProject project, WorkingCopyOwner owner)
- throws JavaScriptModelException {
- this(project, owner == null ? null : JavaModelManager
- .getJavaModelManager()
- .getWorkingCopies(owner, true/* add primary WCs */));
- }
-
- public SearchableEnvironment(JavaProject project, IRestrictedAccessBindingRequestor resolutionScope,WorkingCopyOwner owner)
- throws JavaScriptModelException {
- this(project, resolutionScope, owner == null ? null : JavaModelManager
- .getJavaModelManager()
- .getWorkingCopies(owner, true/* add primary WCs */));
-}
- private static int convertSearchFilterToModelFilter(int searchFilter) {
- switch (searchFilter) {
- case IJavaScriptSearchConstants.CLASS:
- return NameLookup.ACCEPT_CLASSES;
- default:
- return NameLookup.ACCEPT_ALL;
- }
- }
-
- /**
- * Returns the given type in the the given package if it exists, otherwise
- * <code>null</code>.
- */
- protected NameEnvironmentAnswer find(String typeName, String packageName) {
- if (packageName == null)
- packageName = IPackageFragment.DEFAULT_PACKAGE_NAME;
- NameLookup.Answer answer = this.nameLookup.findType(typeName,
- packageName, false/* exact match */, NameLookup.ACCEPT_ALL,
- this.checkAccessRestrictions);
- if (answer != null) {
- // construct name env answer
- if (answer.type instanceof BinaryType) { // BinaryType
- try {
- return new NameEnvironmentAnswer(
- (IBinaryType) ((BinaryType) answer.type)
- .getElementInfo(), answer.restriction);
- } catch (JavaScriptModelException npe) {
- return null;
- }
- } else { // SourceType
- try {
- // retrieve the requested type
- SourceTypeElementInfo sourceType = (SourceTypeElementInfo) ((SourceType) answer.type)
- .getElementInfo();
- if (answer.type.isBinary())
- {
- ICompilationUnit compUnit=(ICompilationUnit)answer.type.getClassFile();
- return new NameEnvironmentAnswer(compUnit,answer.restriction);
- }
- ISourceType topLevelType = sourceType;
- while (topLevelType.getEnclosingType() != null) {
- topLevelType = topLevelType.getEnclosingType();
- }
- IType[] types = null;
- org.eclipse.wst.jsdt.core.IJavaScriptUnit compilationUnit = sourceType.getHandle().getJavaScriptUnit();
- // find all siblings (other types declared in same unit,
- // since may be used for name resolution)
- if (compilationUnit!=null)
- types = compilationUnit.getTypes();
- else if (sourceType.getHandle().getClassFile()!=null)
- types = sourceType.getHandle().getClassFile().getTypes();
-
- ISourceType[] sourceTypes = new ISourceType[types.length];
-
- // in the resulting collection, ensure the requested type is
- // the first one
- sourceTypes[0] = sourceType;
- int length = types.length;
- for (int i = 0, index = 1; i < length; i++) {
- ISourceType otherType = (ISourceType) ((JavaElement) types[i])
- .getElementInfo();
- if (!otherType.equals(topLevelType) && index < length) // check
- // that
- // the
- // index
- // is
- // in
- // bounds
- // (see
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=62861)
- sourceTypes[index++] = otherType;
- }
- return new NameEnvironmentAnswer(sourceTypes,
- answer.restriction);
- } catch (JavaScriptModelException npe) {
- return null;
- }
- }
- }
- return null;
- }
-
- /**
- * Returns the given type in the the given package if it exists, otherwise
- * <code>null</code>.
- */
- protected NameEnvironmentAnswer findBinding(String typeName, String packageName,
- int type, boolean returnMultiple, String excludePath) {
- if (packageName == null)
- packageName = IPackageFragment.DEFAULT_PACKAGE_NAME;
- NameLookup.Answer answer =
- this.nameLookup.findBinding(
- typeName,
- packageName,
- type,
- false/* exact match */,
- NameLookup.ACCEPT_ALL,
- this.checkAccessRestrictions, returnMultiple, excludePath);
- if (answer != null && answer.element!=null) {
- if (answer.element instanceof IJavaScriptElement)
- {
- IOpenable openable = ((IJavaScriptElement)answer.element).getOpenable();
-
- ICompilationUnit compilationUnit= null;
- if (openable instanceof ClassFile) {
- ClassFile classFile = (ClassFile) openable;
- compilationUnit=classFile;
- }
- else if (openable instanceof MetadataFile) {
- return new NameEnvironmentAnswer(((MetadataFile)openable).getAPIs());
- }
- else if (openable instanceof ICompilationUnit) {
- compilationUnit=(ICompilationUnit)openable;
- }
- return new NameEnvironmentAnswer(compilationUnit,answer.restriction);
-
- }
- else if (answer.element!=null && answer.element.getClass().isArray())
- {
- Object [] elements=(Object [])answer.element;
- ICompilationUnit[] units = new ICompilationUnit[elements.length];
- 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;
- }
-
- /**
- * Find the packages that start with the given prefix. A valid prefix is a
- * qualified name separated by periods (ex. java.util). The packages found
- * are passed to: ISearchRequestor.acceptPackage(char[][] packageName)
- */
- public void findPackages(char[] prefix, ISearchRequestor requestor) {
- this.nameLookup.seekPackageFragments(new String(prefix), true,
- new SearchableEnvironmentRequestor(requestor));
- }
-
- /**
- * Find the top-level types that are defined
- * in the current environment and whose simple name matches the given name.
- *
- * The types found are passed to one of the following methods (if additional
- * information is known about the types):
- * ISearchRequestor.acceptType(char[][] packageName, char[] typeName)
- * ISearchRequestor.acceptClass(char[][] packageName, char[] typeName, int modifiers)
- * ISearchRequestor.acceptInterface(char[][] packageName, char[] typeName, int modifiers)
- *
- * This method can not be used to find member types... member
- * types are found relative to their enclosing type.
- */
- public void findExactTypes(char[] name, final boolean findMembers, int searchFor, final ISearchRequestor storage) {
-
- try {
- final String excludePath;
- if (this.unitToSkip != null) {
- if (!(this.unitToSkip instanceof IJavaScriptElement)) {
- // revert to model investigation
- findExactTypes(
- new String(name),
- storage,
- convertSearchFilterToModelFilter(searchFor));
- return;
- }
- excludePath = ((IJavaScriptElement) this.unitToSkip).getPath().toString();
- } else {
- 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) {
- if (excludePath != null && excludePath.equals(path))
- return;
- if (!findMembers && enclosingTypeNames != null && enclosingTypeNames.length > 0)
- return; // accept only top level types
- storage.acceptType(packageName, path.toCharArray(),simpleTypeName, enclosingTypeNames, modifiers, access);
- }
- };
- 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);
- } catch (OperationCanceledException e) {
- findExactTypes(
- new String(name),
- storage,
- convertSearchFilterToModelFilter(searchFor));
- }
- } catch (JavaScriptModelException e) {
- findExactTypes(
- new String(name),
- storage,
- convertSearchFilterToModelFilter(searchFor));
- }
- }
-
- /**
- * Returns all types whose simple name matches with the given <code>name</code>.
- */
- private void findExactTypes(String name, ISearchRequestor storage, int type) {
- SearchableEnvironmentRequestor requestor =
- new SearchableEnvironmentRequestor(storage, this.unitToSkip, this.javaProject, this.nameLookup);
- this.nameLookup.seekTypes(name, null, false, type, requestor);
- }
-
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.env.INameEnvironment#findType(char[][])
- */
- public NameEnvironmentAnswer findType(char[][] compoundTypeName,
- ITypeRequestor requestor) {
- if (compoundTypeName == null)
- return null;
-
- int length = compoundTypeName.length;
- if (length <= 1) {
- if (length == 0)
- return null;
- return find(new String(compoundTypeName[0]), null);
- }
-
- int lengthM1 = length - 1;
- char[][] packageName = new char[lengthM1][];
- System.arraycopy(compoundTypeName, 0, packageName, 0, lengthM1);
-
- return find(new String(compoundTypeName[lengthM1]), CharOperation
- .toString(packageName));
- }
-
- public NameEnvironmentAnswer findBinding(char[] typeName,
- char[][] packageName, int type, ITypeRequestor requestor, boolean returnMultiple, String excludePath) {
- if (typeName == null)
- return null;
-
- return findBinding(new String(typeName), packageName == null
- || packageName.length == 0 ? null : CharOperation
- .toString(packageName), type, returnMultiple,excludePath );
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.env.INameEnvironment#findType(char[],
- * char[][])
- */
- public NameEnvironmentAnswer findType(char[] name, char[][] packageName,
- ITypeRequestor requestor) {
- if (name == null)
- return null;
-
- return find(new String(name), packageName == null
- || packageName.length == 0 ? null : CharOperation
- .toString(packageName));
- }
-
- /**
- * Find the top-level types that are defined in the
- * current environment and whose name starts with the given prefix. The
- * prefix is a qualified name separated by periods or a simple name (ex.
- * java.util.V or V).
- *
- * The types found are passed to one of the following methods (if additional
- * information is known about the types):
- * ISearchRequestor.acceptType(char[][] packageName, char[] typeName)
- * ISearchRequestor.acceptClass(char[][] packageName, char[] typeName, int
- * modifiers) ISearchRequestor.acceptInterface(char[][] packageName, char[]
- * typeName, int modifiers)
- *
- * This method can not be used to find member types... member types are
- * found relative to their enclosing type.
- */
- public void findTypes(char[] prefix, final boolean findMembers,
- boolean camelCaseMatch, int searchFor, final ISearchRequestor storage) {
-
- /*
- * if (true){ findTypes(new String(prefix), storage,
- * NameLookup.ACCEPT_CLASSES | NameLookup.ACCEPT_INTERFACES); return; }
- */
- try {
- final String excludePath;
- if (this.unitToSkip != null) {
- if (!(this.unitToSkip instanceof IJavaScriptElement)) {
- // revert to model investigation
- findTypes(new String(prefix), storage,
- convertSearchFilterToModelFilter(searchFor));
- return;
- }
- 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;
- 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
- }
- };
- IRestrictedAccessTypeRequestor typeRequestor = new IRestrictedAccessTypeRequestor() {
- public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path, AccessRestriction access) {
- if (excludePath != null && excludePath.equals(path))
- return;
- if (!findMembers && enclosingTypeNames != null && enclosingTypeNames.length > 0)
- return; // accept only top level types
- storage.acceptType(packageName, path.toCharArray(),simpleTypeName, enclosingTypeNames, modifiers, access);
- }
- };
- try {
- int matchRule = SearchPattern.R_PREFIX_MATCH;
- if (camelCaseMatch)
- matchRule |= SearchPattern.R_CAMELCASE_MATCH;
- new BasicSearchEngine(this.workingCopies).searchAllTypeNames(
- qualification,
- SearchPattern.R_EXACT_MATCH,
- simpleName,
- matchRule, // not case sensitive
- searchFor,
- this.searchScope,
- typeRequestor, CANCEL_IF_NOT_READY_TO_SEARCH,
- progressMonitor);
- } catch (OperationCanceledException e) {
- findTypes(new String(prefix), storage, convertSearchFilterToModelFilter(searchFor));
- }
- } catch (JavaScriptModelException e) {
- findTypes(new String(prefix), storage, NameLookup.ACCEPT_ALL);
- }
- }
-
-
-
- /**
- * Find the top-level types (classes and interfaces) that are defined in the
- * current environment and whose name starts with the given prefix. The
- * prefix is a qualified name separated by periods or a simple name (ex.
- * java.util.V or V).
- *
- * The types found are passed to one of the following methods (if additional
- * information is known about the types):
- * ISearchRequestor.acceptType(char[][] packageName, char[] typeName)
- * ISearchRequestor.acceptClass(char[][] packageName, char[] typeName, int
- * modifiers) ISearchRequestor.acceptInterface(char[][] packageName, char[]
- * typeName, int modifiers)
- *
- * This method can not be used to find member types... member types are
- * found relative to their enclosing type.
- */
- public void findBindings(char[] prefix, final int bindingType,
- boolean camelCaseMatch, final ISearchRequestor storage) {
-
- /*
- * if (true){ findTypes(new String(prefix), storage,
- * NameLookup.ACCEPT_CLASSES | NameLookup.ACCEPT_INTERFACES); return; }
- */
- try {
- final String excludePath;
- if (this.unitToSkip != null) {
- if (!(this.unitToSkip instanceof IJavaScriptElement)) {
- // revert to model investigation
- findBindings(new String(prefix),bindingType, storage,
- NameLookup.ACCEPT_ALL);
- return;
- }
- excludePath = ((IJavaScriptElement) this.unitToSkip).getPath()
- .toString();
- } else {
- excludePath = null;
- }
- int lastDotIndex = CharOperation.lastIndexOf('.', prefix);
- char[] qualification, simpleName;
- if (lastDotIndex < 0) {
- qualification = null;
- if (camelCaseMatch) {
- simpleName = prefix;
- } else {
- simpleName = CharOperation.toLowerCase(prefix);
- }
- } else {
- qualification = CharOperation.subarray(prefix, 0, lastDotIndex);
- if (camelCaseMatch) {
- simpleName = CharOperation.subarray(prefix,
- lastDotIndex + 1, prefix.length);
- } else {
- simpleName = CharOperation.toLowerCase(CharOperation
- .subarray(prefix, lastDotIndex + 1, prefix.length));
- }
- }
-
- IProgressMonitor progressMonitor = new IProgressMonitor() {
- boolean isCanceled = false;
-
- 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
- }
- };
- IRestrictedAccessBindingRequestor bindingRequestor = new IRestrictedAccessBindingRequestor() {
- String exclude;
- public boolean acceptBinding(int type,int modifiers, char[] packageName,
- char[] simpleTypeName,
- String path, AccessRestriction access) {
- if (exclude!=null && exclude.equals(path))
- return false;
- if (excludePath != null && excludePath.equals(path))
- return false;
- storage.acceptBinding(packageName, path.toCharArray(),simpleTypeName,type,
- modifiers, access);
- return true;
- }
-
-
- public String getFoundPath() {
-
- return null;
- }
-
- public void reset() {}
-
-
- public ArrayList getFoundPaths() {
- return null;
- }
-
-
- public void setExcludePath(String excludePath) {
- this.exclude=excludePath;
-
- }
- };
- try {
- int matchRule = SearchPattern.R_PREFIX_MATCH;
- if (camelCaseMatch)
- matchRule |= SearchPattern.R_CAMELCASE_MATCH;
- new BasicSearchEngine(this.workingCopies).searchAllBindingNames(
- qualification,
- simpleName,
- bindingType,
- matchRule, // not case sensitive
- /*IJavaScriptSearchConstants.TYPE,*/ this.searchScope,
- bindingRequestor, CANCEL_IF_NOT_READY_TO_SEARCH,
- true,
- progressMonitor);
- } catch (OperationCanceledException e) {
- findBindings(new String(prefix),bindingType, storage, NameLookup.ACCEPT_ALL);
- }
- } catch (JavaScriptModelException e) {
- findTypes(new String(prefix), storage, NameLookup.ACCEPT_ALL);
- }
- }
-
- /**
- * <p>The progress monitor is used to be able to cancel completion operations</p>
- *
- * <p>Find constructor declarations that are defined
- * in the current environment and whose name starts with the
- * given prefix. The prefix is a qualified name separated by periods
- * or a simple name (ex. foo.bar.V or V).</p>
- *
- * <p>The constructors found are passed to
- * {@link ISearchRequestor#acceptConstructor(int, char[], int, char[][], char[][], String, AccessRestriction)}</p>
- *
- * @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) {
- final String excludePath;
- if (this.unitToSkip != null && this.unitToSkip instanceof IJavaScriptElement) {
- excludePath = ((IJavaScriptElement) this.unitToSkip).getPath().toString();
- } else {
- 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
- }
- };
-
- IConstructorRequestor constructorRequestor = new IConstructorRequestor() {
- /**
- * @see org.eclipse.wst.jsdt.internal.core.search.IConstructorRequestor#acceptConstructor(
- * int, char[], int, 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 access) {
-
- if (excludePath != null && excludePath.equals(path))
- return;
-
- storage.acceptConstructor(
- modifiers,
- typeName,
- parameterCount,
- parameterTypes,
- parameterNames,
- path,
- access);
- }
- };
-
- /* 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 + ".*)";
-
- try {
- new BasicSearchEngine(this.workingCopies).searchAllConstructorDeclarations(
- regex.toCharArray(),
- matchRule,
- this.searchScope,
- constructorRequestor,
- CANCEL_IF_NOT_READY_TO_SEARCH,
- progressMonitor);
- } catch (OperationCanceledException e) {
- Logger.logException("Constructor search operation canceled.", e);
- }
- }
-
- /**
- * Returns all types whose name starts with the given (qualified)
- * <code>prefix</code>.
- *
- * If the <code>prefix</code> is unqualified, all types whose simple name
- * matches the <code>prefix</code> are returned.
- */
- private void findTypes(String prefix, ISearchRequestor storage, int type) {
- // TODO (david) should add camel case support
- SearchableEnvironmentRequestor requestor = new SearchableEnvironmentRequestor(
- storage, this.unitToSkip, this.javaProject, this.nameLookup);
- int index = prefix.lastIndexOf('.');
- if (index == -1) {
- this.nameLookup.seekTypes(prefix, null, true, type, requestor);
- } else {
- String packageName = prefix.substring(0, index);
- JavaElementRequestor elementRequestor = new JavaElementRequestor();
- this.nameLookup.seekPackageFragments(packageName, false,
- elementRequestor);
- IPackageFragment[] fragments = elementRequestor
- .getPackageFragments();
- if (fragments != null) {
- String className = prefix.substring(index + 1);
- for (int i = 0, length = fragments.length; i < length; i++)
- if (fragments[i] != null)
- this.nameLookup.seekTypes(className, fragments[i],
- true, type, requestor);
- }
- }
- }
-
- private void findBindings(String prefix, int bindingType, ISearchRequestor storage, int type) {
- SearchableEnvironmentRequestor requestor = new SearchableEnvironmentRequestor(
- storage, this.unitToSkip, this.javaProject, this.nameLookup);
- int index = prefix.lastIndexOf('.');
- if (index == -1) {
- 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);
-// }
- }
- }
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.env.INameEnvironment#isPackage(char[][],
- * char[])
- */
- public boolean isPackage(char[][] parentPackageName, char[] subPackageName) {
- String[] pkgName;
- if (parentPackageName == null)
- pkgName = new String[] { new String(subPackageName) };
- else {
- int length = parentPackageName.length;
- pkgName = new String[length + 1];
- for (int i = 0; i < length; i++)
- pkgName[i] = new String(parentPackageName[i]);
- pkgName[length] = new String(subPackageName);
- }
- return this.nameLookup.isPackage(pkgName);
- }
-
- /**
- * Returns a printable string for the array.
- */
- protected String toStringChar(char[] name) {
- return "[" //$NON-NLS-1$
- + new String(name) + "]"; //$NON-NLS-1$
- }
-
- /**
- * Returns a printable string for the array.
- */
- protected String toStringCharChar(char[][] names) {
- StringBuffer result = new StringBuffer();
- for (int i = 0; i < names.length; i++) {
- result.append(toStringChar(names[i]));
- }
- return result.toString();
- }
-
- public void cleanup() {
- // nothing to do
- }
-
- public void setCompilationUnit(IInferenceFile file)
- {
- nameLookup.setScriptFile(file);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SearchableEnvironmentRequestor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SearchableEnvironmentRequestor.java
deleted file mode 100644
index dad0bf55..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SearchableEnvironmentRequestor.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*******************************************************************************
- * 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.core.IInitializer;
-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.IType;
-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.codeassist.ISearchRequestor;
-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;
-
-/**
- * Implements <code>IJavaElementRequestor</code>, wrappering and forwarding
- * results onto a <code>org.eclipse.wst.jsdt.internal.codeassist.api.ISearchRequestor</code>.
- */
-class SearchableEnvironmentRequestor extends JavaElementRequestor {
- /**
- * The <code>ISearchRequestor</code> this JavaElementRequestor wraps
- * and forwards results to.
- */
- protected ISearchRequestor requestor;
- /**
- * The <code>ICompilationUNit</code> this JavaElementRequestor will not
- * accept types within.
- */
- protected ICompilationUnit unitToSkip;
-
- protected IJavaScriptProject project;
-
- protected NameLookup nameLookup;
-
- protected boolean checkAccessRestrictions;
-/**
- * Constructs a SearchableEnvironmentRequestor that wraps the
- * given SearchRequestor.
- */
-public SearchableEnvironmentRequestor(ISearchRequestor requestor) {
- this.requestor = requestor;
- this.unitToSkip= null;
- this.project= null;
- this.nameLookup= null;
- this.checkAccessRestrictions = false;
-
-}
-/**
- * Constructs a SearchableEnvironmentRequestor that wraps the
- * given SearchRequestor. The requestor will not accept types in
- * the <code>unitToSkip</code>.
- */
-public SearchableEnvironmentRequestor(ISearchRequestor requestor, ICompilationUnit unitToSkip, IJavaScriptProject project, NameLookup nameLookup) {
- this.requestor = requestor;
- this.unitToSkip= unitToSkip;
- this.project= project;
- this.nameLookup = nameLookup;
- this.checkAccessRestrictions =
- !JavaScriptCore.IGNORE.equals(project.getOption(JavaScriptCore.COMPILER_PB_FORBIDDEN_REFERENCE, true))
- || !JavaScriptCore.IGNORE.equals(project.getOption(JavaScriptCore.COMPILER_PB_DISCOURAGED_REFERENCE, true));
-}
-/**
- * Do nothing, a SearchRequestor does not accept initializers
- * so there is no need to forward this results.
- *
- * @see IJavaElementRequestor
- */
-public void acceptInitializer(IInitializer initializer) {
- // implements interface method
-}
-/**
- * @see IJavaElementRequestor
- */
-public void acceptPackageFragment(IPackageFragment packageFragment) {
- this.requestor.acceptPackage(packageFragment.getElementName().toCharArray());
-}
-/**
- * @see IJavaElementRequestor
- */
-public void acceptType(IType type) {
- try {
- if (this.unitToSkip != null && this.unitToSkip.equals(type.getJavaScriptUnit())){
- return;
- }
- char[] packageName = type.getPackageFragment().getElementName().toCharArray();
- boolean isBinary = type instanceof BinaryType;
-
- // determine associated access restriction
- AccessRestriction accessRestriction = null;
-
- if (this.checkAccessRestrictions && (isBinary || !type.getJavaScriptProject().equals(this.project))) {
- PackageFragmentRoot root = (PackageFragmentRoot)type.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- ClasspathEntry entry = (ClasspathEntry) this.nameLookup.rootToResolvedEntries.get(root);
- if (entry != null) { // reverse map always contains resolved CP entry
- AccessRuleSet accessRuleSet = entry.getAccessRuleSet();
- if (accessRuleSet != null) {
- // TODO (philippe) improve char[] <-> String conversions to avoid performing them on the fly
- char[][] packageChars = CharOperation.splitOn('.', packageName);
- char[] fileWithoutExtension = type.getElementName().toCharArray();
- accessRestriction = accessRuleSet.getViolatedRestriction(CharOperation.concatWith(packageChars, fileWithoutExtension, '/'));
- }
- }
- }
- this.requestor.acceptType(packageName,null, type.getElementName().toCharArray(), null, type.getFlags(), accessRestriction);
- } catch (JavaScriptModelException jme) {
- // ignore
- }
-}
-}
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
deleted file mode 100644
index 7f7d7297..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SelectionRequestor.java
+++ /dev/null
@@ -1,1005 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core;
-
-import java.util.ArrayList;
-
-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.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-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.compiler.CategorizedProblem;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.codeassist.ISelectionRequestor;
-import org.eclipse.wst.jsdt.internal.codeassist.SelectionEngine;
-import org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.CompilationUnitScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.FieldBinding;
-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.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.core.util.HandleFactory;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * Implementation of <code>ISelectionRequestor</code> to assist with
- * code resolve in a compilation unit. Translates names to elements.
- */
-public class SelectionRequestor implements ISelectionRequestor {
- /*
- * The name lookup facility used to resolve packages
- */
- protected NameLookup nameLookup;
-
- /*
- * The compilation unit or class file we are resolving in
- */
- protected Openable openable;
-
- /*
- * The collection of resolved elements.
- */
- protected IJavaScriptElement[] elements = JavaElement.NO_ELEMENTS;
- protected int elementIndex = -1;
-
- protected HandleFactory handleFactory = new HandleFactory();
-
-/**
- * Creates a selection requestor that uses that given
- * name lookup facility to resolve names.
- *
- * Fix for 1FVXGDK
- */
-public SelectionRequestor(NameLookup nameLookup, Openable openable) {
- super();
- this.nameLookup = nameLookup;
- this.openable = openable;
-}
-private void acceptBinaryMethod(
- IType type,
- IFunction method,
- char[] uniqueKey,
- boolean isConstructor) {
- try {
- if(!isConstructor || ((JavaElement)method).getSourceMapper() == null) {
- if (uniqueKey != null) {
- ResolvedBinaryMethod resolvedMethod = new ResolvedBinaryMethod(
- (JavaElement)method.getParent(),
- method.getElementName(),
- method.getParameterTypes(),
- new String(uniqueKey));
- resolvedMethod.occurrenceCount = method.getOccurrenceCount();
- method = resolvedMethod;
- }
-
- addElement(method);
- if(SelectionEngine.DEBUG){
- System.out.print("SELECTION - accept method("); //$NON-NLS-1$
- System.out.print(method.toString());
- System.out.println(")"); //$NON-NLS-1$
- }
- } else {
- ISourceRange range = method.getSourceRange();
- if (range.getOffset() != -1 && range.getLength() != 0 ) {
- if (uniqueKey != null) {
- ResolvedBinaryMethod resolvedMethod = new ResolvedBinaryMethod(
- (JavaElement)method.getParent(),
- method.getElementName(),
- method.getParameterTypes(),
- new String(uniqueKey));
- resolvedMethod.occurrenceCount = method.getOccurrenceCount();
- method = resolvedMethod;
- }
- addElement(method);
- if(SelectionEngine.DEBUG){
- System.out.print("SELECTION - accept method("); //$NON-NLS-1$
- System.out.print(method.toString());
- System.out.println(")"); //$NON-NLS-1$
- }
- } else {
- // no range was actually found, but a method was originally given -> default constructor
- addElement(type);
- if(SelectionEngine.DEBUG){
- System.out.print("SELECTION - accept type("); //$NON-NLS-1$
- System.out.print(type.toString());
- System.out.println(")"); //$NON-NLS-1$
- }
- }
- }
- } catch (JavaScriptModelException e) {
- // an exception occurs, return nothing
- }
-}
-/**
- * Resolve the binary method
- *
- * fix for 1FWFT6Q
- */
-protected void acceptBinaryMethod(
- IType type,
- char[] selector,
- char[][] parameterPackageNames,
- char[][] parameterTypeNames,
- String[] parameterSignatures,
- char[][] typeParameterNames,
- char[][][] typeParameterBoundNames,
- char[] uniqueKey,
- boolean isConstructor) {
- IFunction method= type.getFunction(new String(selector), parameterSignatures);
-
- if (method.exists()) {
- if (typeParameterNames != null && typeParameterNames.length != 0) {
- IFunction[] methods = type.findMethods(method);
- if (methods.length > 1) {
- for (int i = 0; i < methods.length; i++) {
- acceptBinaryMethod(type, method, uniqueKey, isConstructor);
- }
- return;
- }
- }
- acceptBinaryMethod(type, method, uniqueKey, isConstructor);
- }
-}
-/**
- * Resolve the type.
- */
-public void acceptType(char[] packageName, char[] fileName,char[] typeName, int modifiers, boolean isDeclaration, char[] uniqueKey, int start, int end) {
- int acceptFlags = 0;
- int kind = 0;
- switch (kind) {
- default:
- acceptFlags = NameLookup.ACCEPT_CLASSES;
- break;
- }
- IType type = null;
- if(isDeclaration) {
- type = resolveTypeByLocation(packageName, typeName, acceptFlags, start, end);
- } else {
- type = resolveType(packageName,fileName, typeName, acceptFlags);
- if(type != null ) {
- String key = uniqueKey == null ? type.getKey() : new String(uniqueKey);
-// if(type.isBinary()) {
-// ResolvedBinaryType resolvedType = new ResolvedBinaryType((JavaElement)type.getParent(), type.getElementName(), key);
-// resolvedType.occurrenceCount = type.getOccurrenceCount();
-// type = resolvedType;
-// } else {
- ResolvedSourceType resolvedType = new ResolvedSourceType((JavaElement)type.getParent(), type.getElementName(), key);
- resolvedType.occurrenceCount = type.getOccurrenceCount();
- type = resolvedType;
-// }
- }
- }
-
- if (type != null) {
- addElement(type);
- if(SelectionEngine.DEBUG){
- System.out.print("SELECTION - accept type("); //$NON-NLS-1$
- System.out.print(type.toString());
- System.out.println(")"); //$NON-NLS-1$
- }
- }
-}
-/**
- * @see ISelectionRequestor#acceptError
- */
-public void acceptError(CategorizedProblem error) {
- // do nothing
-}
-/**
- * Resolve the field.
- */
-public void acceptField(char[] declaringTypePackageName, char[] fileName, char[] declaringTypeName, char[] name, boolean isDeclaration, char[] uniqueKey, int start, int end) {
- if(isDeclaration) {
- IType type= resolveTypeByLocation(declaringTypePackageName, declaringTypeName,
- NameLookup.ACCEPT_ALL,
- start, end);
- if(type != null) {
- try {
- IField[] fields = type.getFields();
- for (int i = 0; i < fields.length; i++) {
- IField field = fields[i];
- ISourceRange range = field.getNameRange();
- if(range.getOffset() <= start
- && range.getOffset() + range.getLength() >= end
- && field.getElementName().equals(new String(name))) {
- addElement(fields[i]);
- if(SelectionEngine.DEBUG){
- System.out.print("SELECTION - accept field("); //$NON-NLS-1$
- System.out.print(field.toString());
- System.out.println(")"); //$NON-NLS-1$
- }
- return; // only one method is possible
- }
- }
- } catch (JavaScriptModelException e) {
- return;
- }
- }
- } else {
- IType type= resolveType(declaringTypePackageName, fileName, declaringTypeName, NameLookup.ACCEPT_ALL);
- if (type != null) {
- IField field= type.getField(new String(name));
- if (field.exists()) {
- if (uniqueKey != null) {
-// if(field.isBinary()) {
-// ResolvedBinaryField resolvedField = new ResolvedBinaryField(
-// (JavaElement)field.getParent(),
-// field.getElementName(),
-// new String(uniqueKey));
-// resolvedField.occurrenceCount = field.getOccurrenceCount();
-// field = resolvedField;
-// } else {
- ResolvedSourceField resolvedField = new ResolvedSourceField(
- (JavaElement)field.getParent(),
- field.getElementName(),
- new String(uniqueKey));
- resolvedField.occurrenceCount = field.getOccurrenceCount();
- field = resolvedField;
-// }
- }
- addElement(field);
- if(SelectionEngine.DEBUG){
- System.out.print("SELECTION - accept field("); //$NON-NLS-1$
- System.out.print(field.toString());
- System.out.println(")"); //$NON-NLS-1$
- }
- } else {
- IFunction method = type.getFunction(new String(name), null);
- if(method.exists()) {
- if (uniqueKey != null) {
- ResolvedSourceField resolvedField = new ResolvedSourceField(
- (JavaElement)method.getParent(),
- method.getElementName(),
- new String(uniqueKey));
- resolvedField.occurrenceCount = method.getOccurrenceCount();
- field = resolvedField;
- }
- addElement(field);
- if(SelectionEngine.DEBUG){
- System.out.print("SELECTION - accept field("); //$NON-NLS-1$
- System.out.print(field.toString());
- System.out.println(")"); //$NON-NLS-1$
- }
- }
- }
- }
- }
-}
-public void acceptLocalField(FieldBinding fieldBinding) {
- IJavaScriptElement res;
-
- SourceTypeBinding typeBinding = (SourceTypeBinding)fieldBinding.declaringClass;
- res = findLocalElement(typeBinding.sourceStart());
-
- if (res != null && res.getElementType() == IJavaScriptElement.TYPE) {
- IType type = (IType) res;
- IField field= type.getField(new String(fieldBinding.name));
- if (field.exists()) {
- char[] uniqueKey = fieldBinding.computeUniqueKey();
- if(field.isBinary()) {
- ResolvedBinaryField resolvedField = new ResolvedBinaryField(
- (JavaElement)field.getParent(),
- field.getElementName(),
- new String(uniqueKey));
- resolvedField.occurrenceCount = field.getOccurrenceCount();
- field = resolvedField;
- } else {
- ResolvedSourceField resolvedField = new ResolvedSourceField(
- (JavaElement)field.getParent(),
- field.getElementName(),
- new String(uniqueKey));
- resolvedField.occurrenceCount = field.getOccurrenceCount();
- field = resolvedField;
- }
- addElement(field);
- if(SelectionEngine.DEBUG){
- System.out.print("SELECTION - accept field("); //$NON-NLS-1$
- System.out.print(field.toString());
- System.out.println(")"); //$NON-NLS-1$
- }
- }
- }
-}
-public void acceptLocalMethod(MethodBinding methodBinding) {
- IJavaScriptElement res = findLocalElement(methodBinding.sourceStart());
- if(res != null) {
- if(res.getElementType() == IJavaScriptElement.METHOD) {
- IFunction method = (IFunction) res;
-
- char[] uniqueKey = methodBinding.computeUniqueKey();
- if(method.isBinary()) {
- ResolvedBinaryMethod resolvedRes = new ResolvedBinaryMethod(
- (JavaElement)res.getParent(),
- method.getElementName(),
- method.getParameterTypes(),
- new String(uniqueKey));
- resolvedRes.occurrenceCount = method.getOccurrenceCount();
- res = resolvedRes;
- } else {
- ResolvedSourceMethod resolvedRes = new ResolvedSourceMethod(
- (JavaElement)res.getParent(),
- method.getElementName(),
- method.getParameterTypes(),
- new String(uniqueKey));
- resolvedRes.occurrenceCount = method.getOccurrenceCount();
- res = resolvedRes;
- }
- addElement(res);
- if(SelectionEngine.DEBUG){
- System.out.print("SELECTION - accept method("); //$NON-NLS-1$
- System.out.print(res.toString());
- System.out.println(")"); //$NON-NLS-1$
- }
- } else if(methodBinding.selector == TypeConstants.INIT && res.getElementType() == IJavaScriptElement.TYPE) {
- // it's a default constructor
- res = ((JavaElement)res).resolved(methodBinding.declaringClass);
- addElement(res);
- if(SelectionEngine.DEBUG){
- System.out.print("SELECTION - accept type("); //$NON-NLS-1$
- System.out.print(res.toString());
- System.out.println(")"); //$NON-NLS-1$
- }
- }
- }
-}
-public void acceptLocalType(TypeBinding typeBinding) {
- IJavaScriptElement res = null;
- if(typeBinding instanceof SourceTypeBinding) {
- res = findLocalElement(((SourceTypeBinding)typeBinding).sourceStart());
- }
- if(res != null && res.getElementType() == IJavaScriptElement.TYPE) {
- res = ((JavaElement)res).resolved(typeBinding);
- addElement(res);
- if(SelectionEngine.DEBUG){
- System.out.print("SELECTION - accept type("); //$NON-NLS-1$
- System.out.print(res.toString());
- System.out.println(")"); //$NON-NLS-1$
- }
- }
-}
-public void acceptLocalVariable(LocalVariableBinding binding) {
- LocalDeclaration local = binding.declaration;
- if (local==null)
- return;
- IJavaScriptElement parent =null;
- if (binding.declaringScope instanceof CompilationUnitScope) {
- CompilationUnitScope compilationUnitScope = (CompilationUnitScope) binding.declaringScope;
- char [] packageName=CharOperation.concatWith(compilationUnitScope.currentPackageName, '.');
- char[] fileName = compilationUnitScope.referenceContext.compilationUnitBinding.qualifiedSourceName();
-
- parent=resolveCompilationUnit(packageName, fileName);
- if(parent==null) {
- parent=resolveCompilationUnit(new char[0], fileName);
- }
- } else
- parent = findLocalElement(local.sourceStart); // findLocalElement() cannot find local variable
- IJavaScriptElement localVar = null;
- if(parent != null) {
- String localName=new String(local.name);
- // this may have been put in model as Source Field
- if (parent instanceof SourceField) {
- SourceField sourceField = (SourceField) parent;
- if (sourceField.name.equals(localName))
- parent=sourceField.getParent();
- }
- localVar = new LocalVariable(
- (JavaElement)parent,
- localName,
- local.declarationSourceStart,
- local.declarationSourceEnd,
- local.sourceStart,
- local.sourceEnd,
- Util.typeSignature(local.type));
- }
- if (localVar != null) {
- addElement(localVar);
- if(SelectionEngine.DEBUG){
- System.out.print("SELECTION - accept local variable("); //$NON-NLS-1$
- System.out.print(localVar.toString());
- System.out.println(")"); //$NON-NLS-1$
- }
- }
-
-}
-/**
- * Resolve the method
- */
-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) {
- IJavaScriptElement[] previousElement = this.elements;
- int previousElementIndex = this.elementIndex;
- this.elements = JavaElement.NO_ELEMENTS;
- this.elementIndex = -1;
- boolean isFileName= isFileName(declaringTypeName);
-
-
- if(isDeclaration) {
- IType type = resolveTypeByLocation(declaringTypePackageName, declaringTypeName,
- NameLookup.ACCEPT_ALL,
- start, end);
-
-// if(type != null) {
- this.acceptMethodDeclaration(type, selector, start, end);
-// }
- } else {
- IJavaScriptElement parent = (!isFileName) ?
- resolveType(declaringTypePackageName, fileName,declaringTypeName,NameLookup.ACCEPT_ALL)
- :
- resolveCompilationUnit(declaringTypePackageName, declaringTypeName); // fix for 1FWFT6Q
-// if (type != null) {
-// if (type.isBinary()) {
-//
-// // need to add a paramater for constructor in binary type
-// IType declaringDeclaringType = type.getDeclaringType();
-//
-// boolean isStatic = false;
-// try {
-// isStatic = Flags.isStatic(type.getFlags());
-// } catch (JavaScriptModelException e) {
-// // isStatic == false
-// }
-//
-// if(declaringDeclaringType != null && isConstructor && !isStatic) {
-// int length = parameterPackageNames.length;
-// System.arraycopy(parameterPackageNames, 0, parameterPackageNames = new char[length+1][], 1, length);
-// System.arraycopy(parameterTypeNames, 0, parameterTypeNames = new char[length+1][], 1, length);
-// System.arraycopy(parameterSignatures, 0, parameterSignatures = new String[length+1], 1, length);
-//
-// parameterPackageNames[0] = declaringDeclaringType.getPackageFragment().getElementName().toCharArray();
-// parameterTypeNames[0] = declaringDeclaringType.getTypeQualifiedName().toCharArray();
-// parameterSignatures[0] = Signature.getTypeErasure(enclosingDeclaringTypeSignature);
-// }
-//
-// acceptBinaryMethod(type, selector, parameterPackageNames, parameterTypeNames, parameterSignatures, typeParameterNames, typeParameterBoundNames, uniqueKey, isConstructor);
-// } else {
- acceptSourceMethod(parent, selector, parameterPackageNames, parameterTypeNames, parameterSignatures, typeParameterNames, typeParameterBoundNames, uniqueKey);
-// }
-// }
- }
-
- if(previousElementIndex > -1) {
- int elementsLength = this.elementIndex + previousElementIndex + 2;
- if(elementsLength > this.elements.length) {
- System.arraycopy(this.elements, 0, this.elements = new IJavaScriptElement[elementsLength * 2 + 1], 0, this.elementIndex + 1);
- }
- System.arraycopy(previousElement, 0, this.elements, this.elementIndex + 1, previousElementIndex + 1);
- this.elementIndex += previousElementIndex + 1;
- }
-}
-
-private static final char [] js={'.','j','s'};
-private static boolean isFileName(char [] name)
-{
- return (CharOperation.endsWith(name, js) && CharOperation.contains('/', name));
-}
-/**
- * Resolve the package
- */
-public void acceptPackage(char[] packageName) {
- IPackageFragment[] pkgs = this.nameLookup.findPackageFragments(new String(packageName), false);
- if (pkgs != null) {
- for (int i = 0, length = pkgs.length; i < length; i++) {
- addElement(pkgs[i]);
- if(SelectionEngine.DEBUG){
- System.out.print("SELECTION - accept package("); //$NON-NLS-1$
- System.out.print(pkgs[i].toString());
- System.out.println(")"); //$NON-NLS-1$
- }
- }
- }
-}
-/**
- * Resolve the source method
- *
- * fix for 1FWFT6Q
- */
-protected void acceptSourceMethod(
- IJavaScriptElement parent,
- char[] selector,
- char[][] parameterPackageNames,
- char[][] parameterTypeNames,
- String[] parameterSignatures,
- char[][] typeParameterNames,
- char[][][] typeParameterBoundNames,
- char[] uniqueKey) {
-
- String name = new String(selector);
- IFunction[] methods = null;
- try {
- if (parent instanceof IType)
- methods = ((IType)parent).getFunctions();
- else if (parent instanceof IJavaScriptUnit)
- methods=((IJavaScriptUnit)parent).getFunctions();
- else if (parent instanceof IClassFile)
- {
- methods=((IClassFile)parent).getFunctions();
- }
- if (methods!=null)
- for (int i = 0; i < methods.length; i++) {
- if (methods[i].getElementName().equals(name)
-// && methods[i].getParameterTypes().length == parameterTypeNames.length
- ) {
- IFunction method = methods[i];
- if (uniqueKey != null) {
- ResolvedSourceMethod resolvedMethod = new ResolvedSourceMethod(
- (JavaElement)method.getParent(),
- method.getElementName(),
- method.getParameterTypes(),
- new String(uniqueKey));
- resolvedMethod.occurrenceCount = method.getOccurrenceCount();
- method = resolvedMethod;
- }
- addElement(method);
- }
- }
- } catch (JavaScriptModelException e) {
- return;
- }
-
- // if no matches, nothing to report
- if (this.elementIndex == -1) {
- // no match was actually found, but a method was originally given -> default constructor
- addElement(parent);
- if(SelectionEngine.DEBUG){
- System.out.print("SELECTION - accept type("); //$NON-NLS-1$
- System.out.print(parent.toString());
- System.out.println(")"); //$NON-NLS-1$
- }
- return;
- }
-
- // if there is only one match, we've got it
- if (this.elementIndex == 0) {
- if(SelectionEngine.DEBUG){
- System.out.print("SELECTION - accept method("); //$NON-NLS-1$
- System.out.print(this.elements[0].toString());
- System.out.println(")"); //$NON-NLS-1$
- }
- return;
- }
-
- // more than one match - must match simple parameter types
- IJavaScriptElement[] matches = this.elements;
- int matchesIndex = this.elementIndex;
- this.elements = JavaElement.NO_ELEMENTS;
- this.elementIndex = -1;
- for (int i = 0; i <= matchesIndex; i++) {
- IFunction method= (IFunction)matches[i];
- String[] signatures = method.getParameterTypes();
- boolean match= true;
- for (int p = 0; p < signatures.length; p++) {
- String simpleName= Signature.getSimpleName(Signature.toString(signatures[p]));
- char[] simpleParameterName = CharOperation.lastSegment(parameterTypeNames[p], '.');
- if (!simpleName.equals(new String(simpleParameterName))) {
- match = false;
- break;
- }
- }
-
- if (match) {
- addElement(method);
- if(SelectionEngine.DEBUG){
- System.out.print("SELECTION - accept method("); //$NON-NLS-1$
- System.out.print(method.toString());
- System.out.println(")"); //$NON-NLS-1$
- }
- }
- }
-
-}
-protected void acceptMethodDeclaration(IType type, char[] selector, int start, int end) {
- String name = new String(selector);
- IFunction[] methods = null;
- try {
- if (type!=null)
- methods = type.getFunctions();
- else
- if (this.openable instanceof CompilationUnit)
- methods=((CompilationUnit)this.openable).getFunctions();
- else if (this.openable instanceof ClassFile)
- methods=((ClassFile)this.openable).getFunctions();
- for (int i = 0; i < methods.length; i++) {
- ISourceRange range = methods[i].getNameRange();
- if(range.getOffset() <= start
- && range.getOffset() + range.getLength() >= end
- && methods[i].getElementName().equals(name)) {
- addElement(methods[i]);
- if(SelectionEngine.DEBUG){
- System.out.print("SELECTION - accept method("); //$NON-NLS-1$
- System.out.print(this.elements[0].toString());
- System.out.println(")"); //$NON-NLS-1$
- }
- return; // only one method is possible
- }
- }
- } catch (JavaScriptModelException e) {
- return;
- }
-
- // no match was actually found
- addElement(type);
- if(SelectionEngine.DEBUG){
- System.out.print("SELECTION - accept type("); //$NON-NLS-1$
- System.out.print(type.toString());
- System.out.println(")"); //$NON-NLS-1$
- }
- return;
-}
-public void acceptTypeParameter(char[] declaringTypePackageName, char[] fileName, char[] declaringTypeName, char[] typeParameterName, boolean isDeclaration, int start, int end) {
- IType type;
- if(isDeclaration) {
- type = resolveTypeByLocation(declaringTypePackageName, declaringTypeName,
- NameLookup.ACCEPT_ALL,
- start, end);
- } else {
- type = resolveType(declaringTypePackageName, fileName, declaringTypeName,
- NameLookup.ACCEPT_ALL);
- }
-
- if(type != null) {
- addElement(type);
- if(SelectionEngine.DEBUG){
- System.out.print("SELECTION - accept type("); //$NON-NLS-1$
- System.out.print(type.toString());
- System.out.println(")"); //$NON-NLS-1$
- }
- }
-}
-public void acceptMethodTypeParameter(char[] declaringTypePackageName, char[] fileName, char[] declaringTypeName, char[] selector,int selectorStart, int selectorEnd, char[] typeParameterName, boolean isDeclaration, int start, int end) {
- IType type = resolveTypeByLocation(declaringTypePackageName, declaringTypeName,
- NameLookup.ACCEPT_ALL,
- selectorStart, selectorEnd);
-
- if(type != null) {
- IFunction method = null;
-
- String name = new String(selector);
- IFunction[] methods = null;
-
- try {
- methods = type.getFunctions();
- done : for (int i = 0; i < methods.length; i++) {
- ISourceRange range = methods[i].getNameRange();
- if(range.getOffset() >= selectorStart
- && range.getOffset() + range.getLength() <= selectorEnd
- && methods[i].getElementName().equals(name)) {
- method = methods[i];
- break done;
- }
- }
- } catch (JavaScriptModelException e) {
- //nothing to do
- }
-
- if(method == null) {
- addElement(type);
- if(SelectionEngine.DEBUG){
- System.out.print("SELECTION - accept type("); //$NON-NLS-1$
- System.out.print(type.toString());
- System.out.println(")"); //$NON-NLS-1$
- }
- } else {
- addElement(method);
- if(SelectionEngine.DEBUG){
- System.out.print("SELECTION - accept method("); //$NON-NLS-1$
- System.out.print(method.toString());
- System.out.println(")"); //$NON-NLS-1$
- }
- }
- }
-}
-/*
- * Adds the given element to the list of resolved elements.
- */
-protected void addElement(IJavaScriptElement element) {
- int elementLength = this.elementIndex + 1;
- if (elementLength == this.elements.length) {
- System.arraycopy(this.elements, 0, this.elements = new IJavaScriptElement[(elementLength*2) + 1], 0, elementLength);
- }
- this.elements[++this.elementIndex] = element;
-}
-/*
- * findLocalElement() cannot find local variable
- */
-protected IJavaScriptElement findLocalElement(int pos) {
- IJavaScriptElement res = null;
- if(this.openable instanceof ITypeRoot) {
- ITypeRoot cu = (ITypeRoot) this.openable;
- try {
- res = cu.getElementAt(pos);
- } catch (JavaScriptModelException e) {
- // do nothing
- }
- } else if (this.openable instanceof ClassFile) {
- ClassFile cf = (ClassFile) this.openable;
- try {
- res = cf.getElementAtConsideringSibling(pos);
- } catch (JavaScriptModelException e) {
- // do nothing
- }
- }
- return res;
-}
-/**
- * Returns the resolved elements.
- */
-public IJavaScriptElement[] getElements() {
- int elementLength = this.elementIndex + 1;
- if (this.elements.length != elementLength) {
- System.arraycopy(this.elements, 0, this.elements = new IJavaScriptElement[elementLength], 0, elementLength);
- }
- return this.elements;
-}
-/**
- * Resolve the type
- */
-protected IType resolveType(char[] packageName, char[] fileName, char[] typeName, int acceptFlags) {
-
- IType type= null;
-
- if (fileName!=null)
- {
- ITypeRoot compilationUnit = (ITypeRoot)resolveCompilationUnit(packageName, fileName);
- if (compilationUnit!=null && compilationUnit.exists())
- {
- String fulltypeName=null;
- if (packageName==null || packageName.length==0)
- fulltypeName=new String(typeName);
- else {
- fulltypeName=new String(CharOperation.concat(packageName, typeName, '.'));
- }
- type=compilationUnit.getType(fulltypeName);
- if (type!=null && type.exists())
- return type;
- }
-
- }
-
- if (this.openable instanceof CompilationUnit && ((CompilationUnit)this.openable).isWorkingCopy()) {
- CompilationUnit wc = (CompilationUnit) this.openable;
- if(((packageName == null || packageName.length == 0))) {
-
- char[][] compoundName = CharOperation.splitOn('.', typeName);
- if(compoundName.length > 0) {
- type = wc.getType(new String(compoundName[0]));
- for (int i = 1, length = compoundName.length; i < length; i++) {
- type = type.getType(new String(compoundName[i]));
- }
- }
-
- if(type != null && !type.exists()) {
- type = null;
- }
- }
- }
-
- if(type == null) {
- IPackageFragment[] pkgs = this.nameLookup.findPackageFragments(
- (packageName == null || packageName.length == 0) ? IPackageFragment.DEFAULT_PACKAGE_NAME : new String(packageName),
- false);
- // iterate type lookup in each package fragment
- for (int i = 0, length = pkgs == null ? 0 : pkgs.length; i < length; i++) {
- type= this.nameLookup.findType(new String(typeName), pkgs[i], false, acceptFlags, true/*consider secondary types*/);
- if (type != null) break;
- }
- if (type == null) {
- String pName= IPackageFragment.DEFAULT_PACKAGE_NAME;
- if (packageName != null) {
- pName = new String(packageName);
- }
- 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('.','$');
- IType[] allTypes= null;
- try {
- ArrayList list = this.openable.getChildrenOfType(IJavaScriptElement.TYPE);
- allTypes = new IType[list.size()];
- list.toArray(allTypes);
- } catch (JavaScriptModelException e) {
- return null;
- }
- for (int i= 0; i < allTypes.length; i++) {
- if (allTypes[i].getTypeQualifiedName().equals(tName)) {
- return allTypes[i];
- }
- }
- }
- }
- }
- return type;
-}
-
-
-protected IJavaScriptElement resolveCompilationUnit(char[] packageName, char[] compilationUnitName) {
-
- IJavaScriptUnit compilationUnit= null;
-
- String fullCUName=new String(compilationUnitName);
- Path cuPath = new Path(fullCUName);
- String cuName=cuPath.lastSegment();
-
- Openable cu = new HandleFactory().createOpenable(fullCUName,null);
- if ((cu instanceof CompilationUnit || cu instanceof ClassFile)&& cu.exists())
- return cu;
-
- if (this.openable instanceof CompilationUnit || this.openable instanceof ClassFile) {
- if ( (cuName.equals(this.openable.getElementName()) &&
- new String(packageName).equals(this.openable.getParent().getElementName())
- ) || fullCUName.startsWith("http:")&&fullCUName.equals(this.openable.getElementName())) //$NON-NLS-1$
- {
- return this.openable;
- }
- }
-
- IPackageFragment[] pkgs = this.nameLookup.findPackageFragments(
- (packageName == null || packageName.length == 0) ? IPackageFragment.DEFAULT_PACKAGE_NAME : new String(packageName),
- false);
- // iterate type lookup in each package fragment
- for (int i = 0, length = pkgs == null ? 0 : pkgs.length; i < length; i++) {
- if (!Util.isMetadataFileName(cuName))
- {
- IJavaScriptUnit compUnit=pkgs[i].getJavaScriptUnit(cuName);
- if (compUnit.exists())
- return compUnit;
- }
- IClassFile classFile=pkgs[i].getClassFile(cuName);
- if (classFile.exists())
- return classFile;
- //compUnit = pkgs[i].getCompilationUnit(fullCUName);
- //if(compUnit.exists()) return compUnit;
- //classFile=pkgs[i].getClassFile(fullCUName);
- //if (classFile.exists())
- // return classFile;
-
- }
-// if (type == null) {
-// String pName= IPackageFragment.DEFAULT_PACKAGE_NAME;
-// if (packageName != null) {
-// pName = new String(packageName);
-// }
-// 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('.','$');
-// IType[] allTypes= null;
-// try {
-// ArrayList list = this.openable.getChildrenOfType(IJavaScriptElement.TYPE);
-// allTypes = new IType[list.size()];
-// list.toArray(allTypes);
-// } catch (JavaScriptModelException e) {
-// return null;
-// }
-// for (int i= 0; i < allTypes.length; i++) {
-// if (allTypes[i].getTypeQualifiedName().equals(tName)) {
-// return allTypes[i];
-// }
-// }
-// }
-// }
- return compilationUnit;
-}
-
-
-protected IType resolveTypeByLocation(char[] packageName, char[] typeName, int acceptFlags, int start, int end) {
-
- IType type= null;
-
- // TODO (david) post 3.0 should remove isOpen check, and investigate reusing IJavaScriptUnit#getElementAt. may need to optimize #getElementAt to remove recursions
- if (this.openable instanceof CompilationUnit && ((CompilationUnit)this.openable).isOpen()) {
- CompilationUnit wc = (CompilationUnit) this.openable;
- try {
- if(((packageName == null || packageName.length == 0))) {
-
- char[][] compoundName = CharOperation.splitOn('.', typeName);
- if(compoundName.length > 0) {
-
- IType[] tTypes = wc.getTypes();
- int i = 0;
- int depth = 0;
- done : while(i < tTypes.length) {
- ISourceRange range = tTypes[i].getSourceRange();
- if(range.getOffset() <= start
- && range.getOffset() + range.getLength() >= end
- && tTypes[i].getElementName().equals(new String(compoundName[depth]))) {
- if(depth == compoundName.length - 1) {
- type = tTypes[i];
- break done;
- }
- tTypes = tTypes[i].getTypes();
- i = 0;
- depth++;
- continue done;
- }
- i++;
- }
- }
-
- IType[] tTypes = wc.getTypes();
- String typeNameString = new String(typeName);
- for (int i = 0; i < tTypes.length && type == null; i++) {
- ISourceRange range = tTypes[i].getSourceRange();
- if (range.getOffset() <= start && range.getOffset() + range.getLength() >= end && tTypes[i].getElementName().equals(typeNameString)) {
- type = tTypes[i];
- }
- }
-
- if(type != null && !type.exists()) {
- type = null;
- }
- }
- }catch (JavaScriptModelException e) {
- // type is null
- }
- }
-
- if(type == null&& typeName!=null) {
-// IPackageFragment[] pkgs = this.nameLookup.findPackageFragments(
-// (packageName == null || packageName.length == 0) ? IPackageFragment.DEFAULT_PACKAGE_NAME : new String(packageName),
-// false);
-// // iterate type lookup in each package fragment
-// for (int i = 0, length = pkgs == null ? 0 : pkgs.length; i < length; i++) {
-// type= this.nameLookup.findType(new String(typeName), pkgs[i], false, acceptFlags, true/*consider secondary types*/);
-// if (type != null) break;
-// }
- type=this.nameLookup.findType(new String(typeName),false,acceptFlags);
- if (type == null) {
- String pName= IPackageFragment.DEFAULT_PACKAGE_NAME;
- if (packageName != null) {
- pName = new String(packageName);
- }
- 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('.','$');
- IType[] allTypes= null;
- try {
- ArrayList list = this.openable.getChildrenOfType(IJavaScriptElement.TYPE);
- allTypes = new IType[list.size()];
- list.toArray(allTypes);
- } catch (JavaScriptModelException e) {
- return null;
- }
- for (int i= 0; i < allTypes.length; i++) {
- if (allTypes[i].getTypeQualifiedName().equals(tName)) {
- return allTypes[i];
- }
- }
- }
- }
- }
- return type;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SetClasspathOperation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SetClasspathOperation.java
deleted file mode 100644
index f3c84546..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SetClasspathOperation.java
+++ /dev/null
@@ -1,87 +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;
-
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatus;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-
-/**
- * This operation sets an <code>IJavaScriptProject</code>'s classpath.
- *
- * @see org.eclipse.wst.jsdt.core.IJavaScriptProject
- */
-public class SetClasspathOperation extends ChangeClasspathOperation {
-
- IIncludePathEntry[] newRawClasspath;
- IPath newOutputLocation;
- JavaProject project;
-
- /**
- * When executed, this operation sets the raw classpath and output location of the given project.
- */
- public SetClasspathOperation(
- JavaProject project,
- IIncludePathEntry[] newRawClasspath,
- IPath newOutputLocation,
- boolean canChangeResource) {
-
- super(new IJavaScriptElement[] { project }, canChangeResource);
- this.project = project;
- this.newRawClasspath = newRawClasspath;
- this.newOutputLocation = newOutputLocation;
- }
-
- /**
- * Sets the classpath of the pre-specified project.
- */
- protected void executeOperation() throws JavaScriptModelException {
- checkCanceled();
- try {
- // set raw classpath and null out resolved info
- this.project.getPerProjectInfo().setClasspath(this.newRawClasspath, this.newOutputLocation, JavaModelStatus.VERIFIED_OK/*format is ok*/, null, null, null, null);
-
- // if needed, generate delta, update project ref, create markers, ...
- classpathChanged(this.project);
-
- // write .classpath file
- if (this.canChangeResources && this.project.saveClasspath(this.newRawClasspath, this.newOutputLocation))
- setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
- } finally {
- done();
- }
- }
-
- public String toString(){
- StringBuffer buffer = new StringBuffer(20);
- buffer.append("SetClasspathOperation\n"); //$NON-NLS-1$
- buffer.append(" - classpath : "); //$NON-NLS-1$
- buffer.append("{"); //$NON-NLS-1$
- for (int i = 0; i < this.newRawClasspath.length; i++) {
- if (i > 0) buffer.append(","); //$NON-NLS-1$
- IIncludePathEntry element = this.newRawClasspath[i];
- buffer.append(" ").append(element.toString()); //$NON-NLS-1$
- }
- buffer.append("\n - output location : "); //$NON-NLS-1$
- buffer.append(this.newOutputLocation.toString());
- return buffer.toString();
- }
-
- public IJavaScriptModelStatus verify() {
- IJavaScriptModelStatus status = super.verify();
- if (!status.isOK())
- return status;
- return ClasspathEntry.validateClasspath( this.project, this.newRawClasspath);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SetContainerOperation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SetContainerOperation.java
deleted file mode 100644
index 1b2d329e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SetContainerOperation.java
+++ /dev/null
@@ -1,210 +0,0 @@
-/*******************************************************************************
- * 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.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-public class SetContainerOperation extends ChangeClasspathOperation {
-
- IPath containerPath;
- IJavaScriptProject[] affectedProjects;
- IJsGlobalScopeContainer[] respectiveContainers;
-
- /*
- * Creates a new SetContainerOperation.
- */
- public SetContainerOperation(IPath containerPath, IJavaScriptProject[] affectedProjects, IJsGlobalScopeContainer[] respectiveContainers) {
- super(new IJavaScriptElement[] {JavaModelManager.getJavaModelManager().getJavaModel()}, !ResourcesPlugin.getWorkspace().isTreeLocked());
- this.containerPath = containerPath;
- this.affectedProjects = affectedProjects;
- this.respectiveContainers = respectiveContainers;
- }
-
- protected void executeOperation() throws JavaScriptModelException {
- execute();
- }
-
- public void execute() throws JavaScriptModelException {
-
- checkCanceled();
- try {
- beginTask("", 1); //$NON-NLS-1$
- if (JavaModelManager.CP_RESOLVE_VERBOSE)
- verbose_set_container();
- if (JavaModelManager.CP_RESOLVE_VERBOSE_ADVANCED)
- verbose_set_container_invocation_trace();
-
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- if (manager.containerPutIfInitializingWithSameEntries(this.containerPath, this.affectedProjects, this.respectiveContainers))
- return;
-
- final int projectLength = this.affectedProjects.length;
- final IJavaScriptProject[] modifiedProjects;
- System.arraycopy(this.affectedProjects, 0, modifiedProjects = new IJavaScriptProject[projectLength], 0, projectLength);
- final IIncludePathEntry[][] oldResolvedPaths = new IIncludePathEntry[projectLength][];
-
- // filter out unmodified project containers
- int remaining = 0;
- for (int i = 0; i < projectLength; i++){
- if (isCanceled())
- return;
- JavaProject affectedProject = (JavaProject) this.affectedProjects[i];
- IJsGlobalScopeContainer newContainer = this.respectiveContainers[i];
- if (newContainer == null) newContainer = JavaModelManager.CONTAINER_INITIALIZATION_IN_PROGRESS; // 30920 - prevent infinite loop
- boolean found = false;
- if (JavaProject.hasJavaNature(affectedProject.getProject())){
- IIncludePathEntry[] rawClasspath = affectedProject.getRawIncludepath();
- for (int j = 0, cpLength = rawClasspath.length; j <cpLength; j++) {
- IIncludePathEntry entry = rawClasspath[j];
- if (entry.getEntryKind() == IIncludePathEntry.CPE_CONTAINER && entry.getPath().equals(this.containerPath)){
- found = true;
- break;
- }
- }
- }
- if (!found) {
- modifiedProjects[i] = null; // filter out this project - does not reference the container path, or isnt't yet Java project
- manager.containerPut(affectedProject, this.containerPath, newContainer);
- continue;
- }
- IJsGlobalScopeContainer oldContainer = manager.containerGet(affectedProject, this.containerPath);
- if (oldContainer == JavaModelManager.CONTAINER_INITIALIZATION_IN_PROGRESS) {
- oldContainer = null;
- }
- if ((oldContainer != null && oldContainer.equals(this.respectiveContainers[i]))
- || (oldContainer == this.respectiveContainers[i])/*handle case where old and new containers are null (see bug 149043*/) {
- modifiedProjects[i] = null; // filter out this project - container did not change
- continue;
- }
- remaining++;
- oldResolvedPaths[i] = affectedProject.getResolvedClasspath();
- manager.containerPut(affectedProject, this.containerPath, newContainer);
- }
-
- if (remaining == 0) return;
-
- // trigger model refresh
- try {
- for(int i = 0; i < projectLength; i++){
- if (isCanceled())
- return;
-
- JavaProject affectedProject = (JavaProject)modifiedProjects[i];
- if (affectedProject == null) continue; // was filtered out
- if (JavaModelManager.CP_RESOLVE_VERBOSE_ADVANCED)
- verbose_update_project(affectedProject);
-
- // force resolved classpath to be recomputed
- affectedProject.getPerProjectInfo().resetResolvedClasspath();
-
- // if needed, generate delta, update project ref, create markers, ...
- classpathChanged(affectedProject);
-
- if (this.canChangeResources) {
- // touch project to force a build if needed
- try {
- affectedProject.getProject().touch(this.progressMonitor);
- } catch (CoreException e) {
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=148970
- if (!ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals(affectedProject.getElementName()))
- throw e;
- }
- }
- }
- } catch(CoreException e) {
- if (JavaModelManager.CP_RESOLVE_VERBOSE)
- verbose_failure(e);
- if (e instanceof JavaScriptModelException) {
- throw (JavaScriptModelException)e;
- } else {
- throw new JavaScriptModelException(e);
- }
- } finally {
- for (int i = 0; i < projectLength; i++) {
- if (this.respectiveContainers[i] == null) {
- manager.containerPut(this.affectedProjects[i], this.containerPath, null); // reset init in progress marker
- }
- }
- }
- } finally {
- done();
- }
- }
-
- private void verbose_failure(CoreException e) {
- Util.verbose(
- "CPContainer SET - FAILED DUE TO EXCEPTION\n" + //$NON-NLS-1$
- " container path: " + this.containerPath, //$NON-NLS-1$
- System.err);
- e.printStackTrace();
- }
-
- private void verbose_update_project(JavaProject affectedProject) {
- Util.verbose(
- "CPContainer SET - updating affected project due to setting container\n" + //$NON-NLS-1$
- " project: " + affectedProject.getElementName() + '\n' + //$NON-NLS-1$
- " container path: " + this.containerPath); //$NON-NLS-1$
- }
-
- private void verbose_set_container() {
- Util.verbose(
- "CPContainer SET - setting container\n" + //$NON-NLS-1$
- " container path: " + this.containerPath + '\n' + //$NON-NLS-1$
- " projects: {" +//$NON-NLS-1$
- org.eclipse.wst.jsdt.internal.compiler.util.Util.toString(
- this.affectedProjects,
- new org.eclipse.wst.jsdt.internal.compiler.util.Util.Displayable(){
- public String displayString(Object o) { return ((IJavaScriptProject) o).getElementName(); }
- }) +
- "}\n values: {\n" +//$NON-NLS-1$
- org.eclipse.wst.jsdt.internal.compiler.util.Util.toString(
- this.respectiveContainers,
- new org.eclipse.wst.jsdt.internal.compiler.util.Util.Displayable(){
- public String displayString(Object o) {
- StringBuffer buffer = new StringBuffer(" "); //$NON-NLS-1$
- if (o == null) {
- buffer.append("<null>"); //$NON-NLS-1$
- return buffer.toString();
- }
- IJsGlobalScopeContainer container = (IJsGlobalScopeContainer) o;
- buffer.append(container.getDescription());
- buffer.append(" {\n"); //$NON-NLS-1$
- IIncludePathEntry[] entries = container.getIncludepathEntries();
- if (entries != null){
- for (int i = 0; i < entries.length; i++){
- buffer.append(" "); //$NON-NLS-1$
- buffer.append(entries[i]);
- buffer.append('\n');
- }
- }
- buffer.append(" }"); //$NON-NLS-1$
- return buffer.toString();
- }
- }) +
- "\n }");//$NON-NLS-1$
- }
-
- private void verbose_set_container_invocation_trace() {
- Util.verbose(
- "CPContainer SET - setting container\n" + //$NON-NLS-1$
- " invocation stack trace:"); //$NON-NLS-1$
- new Exception("<Fake exception>").printStackTrace(System.out); //$NON-NLS-1$
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SetVariablesOperation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SetVariablesOperation.java
deleted file mode 100644
index 1675044a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SetVariablesOperation.java
+++ /dev/null
@@ -1,193 +0,0 @@
-/*******************************************************************************
- * 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 java.util.HashMap;
-import java.util.Iterator;
-
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-public class SetVariablesOperation extends ChangeClasspathOperation {
-
- String[] variableNames;
- IPath[] variablePaths;
- boolean updatePreferences;
-
- /*
- * Creates a new SetVariablesOperation for the given variable values (null path meaning removal), allowing to change multiple variable values at once.
- */
- public SetVariablesOperation(String[] variableNames, IPath[] variablePaths, boolean updatePreferences) {
- super(new IJavaScriptElement[] {JavaModelManager.getJavaModelManager().getJavaModel()}, !ResourcesPlugin.getWorkspace().isTreeLocked());
- this.variableNames = variableNames;
- this.variablePaths = variablePaths;
- this.updatePreferences = updatePreferences;
- }
-
- protected void executeOperation() throws JavaScriptModelException {
- checkCanceled();
- try {
- beginTask("", 1); //$NON-NLS-1$
- if (JavaModelManager.CP_RESOLVE_VERBOSE)
- verbose_set_variables();
-
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- if (manager.variablePutIfInitializingWithSameValue(this.variableNames, this.variablePaths))
- return;
-
- int varLength = this.variableNames.length;
-
- // gather classpath information for updating
- final HashMap affectedProjectClasspaths = new HashMap(5);
- IJavaScriptModel model = getJavaModel();
-
- // filter out unmodified variables
- int discardCount = 0;
- for (int i = 0; i < varLength; i++){
- String variableName = this.variableNames[i];
- IPath oldPath = manager.variableGet(variableName); // if reentering will provide previous session value
- if (oldPath == JavaModelManager.VARIABLE_INITIALIZATION_IN_PROGRESS) {
- oldPath = null; //33695 - cannot filter out restored variable, must update affected project to reset cached CP
- }
- if (oldPath != null && oldPath.equals(this.variablePaths[i])){
- this.variableNames[i] = null;
- discardCount++;
- }
- }
- if (discardCount > 0){
- if (discardCount == varLength) return;
- int changedLength = varLength - discardCount;
- String[] changedVariableNames = new String[changedLength];
- IPath[] changedVariablePaths = new IPath[changedLength];
- for (int i = 0, index = 0; i < varLength; i++){
- if (this.variableNames[i] != null){
- changedVariableNames[index] = this.variableNames[i];
- changedVariablePaths[index] = this.variablePaths[i];
- index++;
- }
- }
- this.variableNames = changedVariableNames;
- this.variablePaths = changedVariablePaths;
- varLength = changedLength;
- }
-
- if (isCanceled())
- return;
-
- IJavaScriptProject[] projects = model.getJavaScriptProjects();
- nextProject : for (int i = 0, projectLength = projects.length; i < projectLength; i++){
- JavaProject project = (JavaProject) projects[i];
-
- // check to see if any of the modified variables is present on the classpath
- IIncludePathEntry[] classpath = project.getRawIncludepath();
- for (int j = 0, cpLength = classpath.length; j < cpLength; j++){
-
- IIncludePathEntry entry = classpath[j];
- for (int k = 0; k < varLength; k++){
-
- String variableName = this.variableNames[k];
- if (entry.getEntryKind() == IIncludePathEntry.CPE_VARIABLE){
-
- if (variableName.equals(entry.getPath().segment(0))){
- affectedProjectClasspaths.put(project, project.getResolvedClasspath());
- continue nextProject;
- }
- IPath sourcePath, sourceRootPath;
- if (((sourcePath = entry.getSourceAttachmentPath()) != null && variableName.equals(sourcePath.segment(0)))
- || ((sourceRootPath = entry.getSourceAttachmentRootPath()) != null && variableName.equals(sourceRootPath.segment(0)))) {
-
- affectedProjectClasspaths.put(project, project.getResolvedClasspath());
- continue nextProject;
- }
- }
- }
- }
- }
-
- // update variables
- for (int i = 0; i < varLength; i++){
- manager.variablePut(this.variableNames[i], this.variablePaths[i]);
- if (this.updatePreferences)
- manager.variablePreferencesPut(this.variableNames[i], this.variablePaths[i]);
- }
-
- // update affected project classpaths
- if (!affectedProjectClasspaths.isEmpty()) {
- String[] dbgVariableNames = this.variableNames;
- try {
- // propagate classpath change
- Iterator projectsToUpdate = affectedProjectClasspaths.keySet().iterator();
- while (projectsToUpdate.hasNext()) {
-
- if (this.progressMonitor != null && this.progressMonitor.isCanceled()) return;
-
- JavaProject affectedProject = (JavaProject) projectsToUpdate.next();
-
- // force resolved classpath to be recomputed
- if (JavaModelManager.CP_RESOLVE_VERBOSE_ADVANCED)
- verbose_update_project(dbgVariableNames, affectedProject);
- affectedProject.getPerProjectInfo().resetResolvedClasspath();
-
- // if needed, generate delta, update project ref, create markers, ...
- classpathChanged(affectedProject);
-
- if (this.canChangeResources) {
- // touch project to force a build if needed
- affectedProject.getProject().touch(this.progressMonitor);
- }
- }
- } catch (CoreException e) {
- if (JavaModelManager.CP_RESOLVE_VERBOSE){
- verbose_failure(dbgVariableNames);
- e.printStackTrace();
- }
- if (e instanceof JavaScriptModelException) {
- throw (JavaScriptModelException)e;
- } else {
- throw new JavaScriptModelException(e);
- }
- }
- }
- } finally {
- done();
- }
- }
-
- private void verbose_failure(String[] dbgVariableNames) {
- Util.verbose(
- "CPVariable SET - FAILED DUE TO EXCEPTION\n" + //$NON-NLS-1$
- " variables: " + org.eclipse.wst.jsdt.internal.compiler.util.Util.toString(dbgVariableNames), //$NON-NLS-1$
- System.err);
- }
-
- private void verbose_update_project(String[] dbgVariableNames,
- JavaProject affectedProject) {
- Util.verbose(
- "CPVariable SET - updating affected project due to setting variables\n" + //$NON-NLS-1$
- " project: " + affectedProject.getElementName() + '\n' + //$NON-NLS-1$
- " variables: " + org.eclipse.wst.jsdt.internal.compiler.util.Util.toString(dbgVariableNames)); //$NON-NLS-1$
- }
-
- private void verbose_set_variables() {
- Util.verbose(
- "CPVariable SET - setting variables\n" + //$NON-NLS-1$
- " variables: " + org.eclipse.wst.jsdt.internal.compiler.util.Util.toString(this.variableNames) + '\n' +//$NON-NLS-1$
- " values: " + org.eclipse.wst.jsdt.internal.compiler.util.Util.toString(this.variablePaths)); //$NON-NLS-1$
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SimpleDelta.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SimpleDelta.java
deleted file mode 100644
index 6c6bdf98..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SimpleDelta.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*******************************************************************************
- * 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.core.IJavaScriptElementDelta;
-
-/**
- * A simple Java element delta that remembers the kind of changes only.
- */
-public class SimpleDelta {
-
- /*
- * @see IJavaScriptElementDelta#getKind()
- */
- protected int kind = 0;
-
- /*
- * @see IJavaScriptElementDelta#getFlags()
- */
- protected int changeFlags = 0;
-
- /*
- * Marks this delta as added
- */
- public void added() {
- this.kind = IJavaScriptElementDelta.ADDED;
- }
-
- /*
- * Marks this delta as changed with the given change flag
- */
- public void changed(int flags) {
- this.kind = IJavaScriptElementDelta.CHANGED;
- this.changeFlags |= flags;
- }
-
- /*
- * @see IJavaScriptElementDelta#getFlags()
- */
- public int getFlags() {
- return this.changeFlags;
- }
-
- /*
- * @see IJavaScriptElementDelta#getKind()
- */
- public int getKind() {
- return this.kind;
- }
-
- /*
- * Mark this delta has a having a modifiers change
- */
- public void modifiers() {
- changed(IJavaScriptElementDelta.F_MODIFIERS);
- }
-
- /*
- * Marks this delta as removed
- */
- public void removed() {
- this.kind = IJavaScriptElementDelta.REMOVED;
- this.changeFlags = 0;
- }
-
- /*
- * Mark this delta has a having a super type change
- */
- public void superTypes() {
- changed(IJavaScriptElementDelta.F_SUPER_TYPES);
- }
-
- protected void toDebugString(StringBuffer buffer) {
- buffer.append("["); //$NON-NLS-1$
- switch (getKind()) {
- case IJavaScriptElementDelta.ADDED :
- buffer.append('+');
- break;
- case IJavaScriptElementDelta.REMOVED :
- buffer.append('-');
- break;
- case IJavaScriptElementDelta.CHANGED :
- buffer.append('*');
- break;
- default :
- buffer.append('?');
- break;
- }
- buffer.append("]: {"); //$NON-NLS-1$
- toDebugString(buffer, getFlags());
- buffer.append("}"); //$NON-NLS-1$
- }
-
- protected boolean toDebugString(StringBuffer buffer, int flags) {
- boolean prev = false;
- if ((flags & IJavaScriptElementDelta.F_MODIFIERS) != 0) {
- if (prev)
- buffer.append(" | "); //$NON-NLS-1$
- buffer.append("MODIFIERS CHANGED"); //$NON-NLS-1$
- prev = true;
- }
- if ((flags & IJavaScriptElementDelta.F_SUPER_TYPES) != 0) {
- if (prev)
- buffer.append(" | "); //$NON-NLS-1$
- buffer.append("SUPER TYPES CHANGED"); //$NON-NLS-1$
- prev = true;
- }
- return prev;
- }
-
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- toDebugString(buffer);
- return buffer.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SingleTypeRequestor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SingleTypeRequestor.java
deleted file mode 100644
index a3bb8483..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SingleTypeRequestor.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*******************************************************************************
- * 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.core.IField;
-import org.eclipse.wst.jsdt.core.IInitializer;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IType;
-
-/**
- * The SingleTypeRequestor is an IJavaElementRequestor that
- * only accepts one result element and then cancels.
- */
-/* package */ class SingleTypeRequestor implements IJavaElementRequestor {
- /**
- * The single accepted element
- */
- protected IType fElement= null;
-/**
- * @see IJavaElementRequestor
- */
-public void acceptField(IField field) {
- // implements interface method
-}
-/**
- * @see IJavaElementRequestor
- */
-public void acceptInitializer(IInitializer initializer) {
- // implements interface method
-}
-/**
- * @see IJavaElementRequestor
- */
-public void acceptMemberType(IType type) {
- fElement= type;
-}
-/**
- * @see IJavaElementRequestor
- */
-public void acceptMethod(IFunction method) {
- // implements interface method
-}
-/**
- * @see IJavaElementRequestor
- */
-public void acceptPackageFragment(IPackageFragment packageFragment) {
- // implements interface method
-}
-/**
- * @see IJavaElementRequestor
- */
-public void acceptType(IType type) {
- fElement= type;
-}
-/**
- * Returns the type accepted by this requestor, or <code>null</code>
- * if no type has been accepted.
- */
-public IType getType() {
- return fElement;
-}
-/**
- * @see IJavaElementRequestor
- */
-public boolean isCanceled() {
- return fElement != null;
-}
-/**
- * Reset the state of this requestor
- */
-public void reset() {
- fElement= null;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SortElementsOperation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SortElementsOperation.java
deleted file mode 100644
index 7a2bc2bb..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SortElementsOperation.java
+++ /dev/null
@@ -1,342 +0,0 @@
-/*******************************************************************************
- * 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
- * Alex Blewitt - alex_blewitt@yahoo.com https://bugs.eclipse.org/bugs/show_bug.cgi?id=171066
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.text.edits.RangeMarker;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.IBuffer;
-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.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.core.util.JavaScriptUnitSorter;
-import org.eclipse.wst.jsdt.internal.compiler.impl.CompilerOptions;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-
-/**
- * This operation is used to sort elements in a compilation unit according to
- * certain criteria.
- *
- * @since 2.1
- */
-public class SortElementsOperation extends JavaModelOperation {
- public static final String CONTAINS_MALFORMED_NODES = "malformed"; //$NON-NLS-1$
-
- Comparator comparator;
- int[] positions;
- int apiLevel;
-
- /**
- * Constructor for SortElementsOperation.
- *
- * @param level the AST API level; one of the AST LEVEL constants
- * @param elements
- * @param positions
- * @param comparator
- */
- public SortElementsOperation(int level, IJavaScriptElement[] elements, int[] positions, Comparator comparator) {
- super(elements);
- this.comparator = comparator;
- this.positions = positions;
- this.apiLevel = level;
- }
-
- /**
- * Returns the amount of work for the main task of this operation for
- * progress reporting.
- */
- protected int getMainAmountOfWork(){
- return this.elementsToProcess.length;
- }
-
- boolean checkMalformedNodes(ASTNode node) {
- Object property = node.getProperty(CONTAINS_MALFORMED_NODES);
- if (property == null) return false;
- return ((Boolean) property).booleanValue();
- }
-
- protected boolean isMalformed(ASTNode node) {
- return (node.getFlags() & ASTNode.MALFORMED) != 0;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.core.JavaModelOperation#executeOperation()
- */
- protected void executeOperation() throws JavaScriptModelException {
- try {
- beginTask(Messages.operation_sortelements, getMainAmountOfWork());
- CompilationUnit copy = (CompilationUnit) this.elementsToProcess[0];
- IJavaScriptUnit unit = copy.getPrimary();
- IBuffer buffer = copy.getBuffer();
- if (buffer == null) {
- return;
- }
- char[] bufferContents = buffer.getCharacters();
- String result = processElement(unit, bufferContents);
- if (!CharOperation.equals(result.toCharArray(), bufferContents)) {
- copy.getBuffer().setContents(result);
- }
- worked(1);
- } finally {
- done();
- }
- }
-
- /**
- * Calculates the required text edits to sort the <code>unit</code>
- * @param group
- * @return the edit or null if no sorting is required
- */
- public TextEdit calculateEdit(org.eclipse.wst.jsdt.core.dom.JavaScriptUnit unit, TextEditGroup group) throws JavaScriptModelException {
- if (this.elementsToProcess.length != 1)
- throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.NO_ELEMENTS_TO_PROCESS));
-
- if (!(this.elementsToProcess[0] instanceof IJavaScriptUnit))
- throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_ELEMENT_TYPES, this.elementsToProcess[0]));
-
- try {
- beginTask(Messages.operation_sortelements, getMainAmountOfWork());
-
- IJavaScriptUnit cu= (IJavaScriptUnit)this.elementsToProcess[0];
- String content= cu.getBuffer().getContents();
- ASTRewrite rewrite= sortCompilationUnit(unit, group);
- if (rewrite == null) {
- return null;
- }
-
- Document document= new Document(content);
- return rewrite.rewriteAST(document, null);
- } finally {
- done();
- }
- }
-
- /**
- * Method processElement.
- * @param unit
- * @param source
- */
- private String processElement(IJavaScriptUnit unit, char[] source) {
- Document document = new Document(new String(source));
- CompilerOptions options = new CompilerOptions(unit.getJavaScriptProject().getOptions(true));
- ASTParser parser = ASTParser.newParser(this.apiLevel);
- parser.setCompilerOptions(options.getMap());
- parser.setSource(source);
- parser.setKind(ASTParser.K_COMPILATION_UNIT);
- parser.setResolveBindings(false);
- org.eclipse.wst.jsdt.core.dom.JavaScriptUnit ast = (org.eclipse.wst.jsdt.core.dom.JavaScriptUnit) parser.createAST(null);
-
- ASTRewrite rewriter= sortCompilationUnit(ast, null);
- if (rewriter == null)
- return document.get();
-
- TextEdit edits = rewriter.rewriteAST(document, null);
-
- RangeMarker[] markers = null;
- if (this.positions != null) {
- markers = new RangeMarker[this.positions.length];
- for (int i = 0, max = this.positions.length; i < max; i++) {
- markers[i]= new RangeMarker(this.positions[i], 0);
- insert(edits, markers[i]);
- }
- }
- try {
- edits.apply(document, TextEdit.UPDATE_REGIONS);
- if (this.positions != null) {
- for (int i= 0, max = markers.length; i < max; i++) {
- this.positions[i]= markers[i].getOffset();
- }
- }
- } catch (BadLocationException e) {
- // ignore
- }
- return document.get();
- }
-
-
- private ASTRewrite sortCompilationUnit(org.eclipse.wst.jsdt.core.dom.JavaScriptUnit ast, final TextEditGroup group) {
- ast.accept(new ASTVisitor() {
- public boolean visit(org.eclipse.wst.jsdt.core.dom.JavaScriptUnit compilationUnit) {
- List types = compilationUnit.types();
- for (Iterator iter = types.iterator(); iter.hasNext();) {
- AbstractTypeDeclaration typeDeclaration = (AbstractTypeDeclaration) iter.next();
- typeDeclaration.setProperty(JavaScriptUnitSorter.RELATIVE_ORDER, new Integer(typeDeclaration.getStartPosition()));
- compilationUnit.setProperty(CONTAINS_MALFORMED_NODES, Boolean.valueOf(isMalformed(typeDeclaration)));
- }
- return true;
- }
-
- public boolean visit(AnonymousClassDeclaration anonymousClassDeclaration) {
- List bodyDeclarations = anonymousClassDeclaration.bodyDeclarations();
- for (Iterator iter = bodyDeclarations.iterator(); iter.hasNext();) {
- BodyDeclaration bodyDeclaration = (BodyDeclaration) iter.next();
- bodyDeclaration.setProperty(JavaScriptUnitSorter.RELATIVE_ORDER, new Integer(bodyDeclaration.getStartPosition()));
- anonymousClassDeclaration.setProperty(CONTAINS_MALFORMED_NODES, Boolean.valueOf(isMalformed(bodyDeclaration)));
- }
- return true;
- }
-
- public boolean visit(TypeDeclaration typeDeclaration) {
- List bodyDeclarations = typeDeclaration.bodyDeclarations();
- for (Iterator iter = bodyDeclarations.iterator(); iter.hasNext();) {
- BodyDeclaration bodyDeclaration = (BodyDeclaration) iter.next();
- bodyDeclaration.setProperty(JavaScriptUnitSorter.RELATIVE_ORDER, new Integer(bodyDeclaration.getStartPosition()));
- typeDeclaration.setProperty(CONTAINS_MALFORMED_NODES, Boolean.valueOf(isMalformed(bodyDeclaration)));
- }
- return true;
- }
-
- });
-
- final ASTRewrite rewriter= ASTRewrite.create(ast.getAST());
- final boolean[] hasChanges= new boolean[] {false};
-
- ast.accept(new ASTVisitor() {
-
- private void sortElements(List elements, ListRewrite listRewrite) {
- if (elements.size() == 0)
- return;
-
- final List myCopy = new ArrayList();
- myCopy.addAll(elements);
- Collections.sort(myCopy, SortElementsOperation.this.comparator);
-
- for (int i = 0; i < elements.size(); i++) {
- ASTNode oldNode= (ASTNode) elements.get(i);
- ASTNode newNode= (ASTNode) myCopy.get(i);
- if (oldNode != newNode) {
- listRewrite.replace(oldNode, rewriter.createMoveTarget(newNode), group);
- hasChanges[0]= true;
- }
- }
- }
-
- public boolean visit(org.eclipse.wst.jsdt.core.dom.JavaScriptUnit compilationUnit) {
- if (checkMalformedNodes(compilationUnit)) {
- return true; // abort sorting of current element
- }
-
- sortElements(compilationUnit.types(), rewriter.getListRewrite(compilationUnit, org.eclipse.wst.jsdt.core.dom.JavaScriptUnit.TYPES_PROPERTY));
- return true;
- }
-
-
- public boolean visit(AnonymousClassDeclaration anonymousClassDeclaration) {
- if (checkMalformedNodes(anonymousClassDeclaration)) {
- return true; // abort sorting of current element
- }
-
- sortElements(anonymousClassDeclaration.bodyDeclarations(), rewriter.getListRewrite(anonymousClassDeclaration, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY));
- return true;
- }
-
- public boolean visit(TypeDeclaration typeDeclaration) {
- if (checkMalformedNodes(typeDeclaration)) {
- return true; // abort sorting of current element
- }
-
- sortElements(typeDeclaration.bodyDeclarations(), rewriter.getListRewrite(typeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY));
- return true;
- }
-
- });
-
- if (!hasChanges[0])
- return null;
-
- return rewriter;
- }
-
- /**
- * Possible failures:
- * <ul>
- * <li>NO_ELEMENTS_TO_PROCESS - the compilation unit supplied to the operation is <code>null</code></li>.
- * <li>INVALID_ELEMENT_TYPES - the supplied elements are not an instance of IWorkingCopy</li>.
- * </ul>
- * @return IJavaScriptModelStatus
- */
- public IJavaScriptModelStatus verify() {
- if (this.elementsToProcess.length != 1) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.NO_ELEMENTS_TO_PROCESS);
- }
- if (this.elementsToProcess[0] == null) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.NO_ELEMENTS_TO_PROCESS);
- }
- if (!(this.elementsToProcess[0] instanceof IJavaScriptUnit) || !((IJavaScriptUnit) this.elementsToProcess[0]).isWorkingCopy()) {
- return new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_ELEMENT_TYPES, this.elementsToProcess[0]);
- }
- return JavaModelStatus.VERIFIED_OK;
- }
-
- public static void insert(TextEdit parent, TextEdit edit) {
- if (!parent.hasChildren()) {
- parent.addChild(edit);
- return;
- }
- TextEdit[] children= parent.getChildren();
- // First dive down to find the right parent.
- for (int i= 0; i < children.length; i++) {
- TextEdit child= children[i];
- if (covers(child, edit)) {
- insert(child, edit);
- return;
- }
- }
- // We have the right parent. Now check if some of the children have to
- // be moved under the new edit since it is covering it.
- for (int i= children.length - 1; i >= 0; i--) {
- TextEdit child= children[i];
- if (covers(edit, child)) {
- parent.removeChild(i);
- edit.addChild(child);
- }
- }
- parent.addChild(edit);
- }
-
- private static boolean covers(TextEdit thisEdit, TextEdit otherEdit) {
- if (thisEdit.getLength() == 0) {
- return false;
- }
-
- int thisOffset= thisEdit.getOffset();
- int thisEnd= thisEdit.getExclusiveEnd();
- if (otherEdit.getLength() == 0) {
- int otherOffset= otherEdit.getOffset();
- return thisOffset <= otherOffset && otherOffset < thisEnd;
- } else {
- int otherOffset= otherEdit.getOffset();
- int otherEnd= otherEdit.getExclusiveEnd();
- return thisOffset <= otherOffset && otherEnd <= thisEnd;
- }
- }
-}
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
deleted file mode 100644
index 96e2acc3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceConstructorInfo.java
+++ /dev/null
@@ -1,21 +0,0 @@
-/*******************************************************************************
- * 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
- * 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 constructor from source.
- */
-public class SourceConstructorInfo extends SourceMethodElementInfo {
-
- public boolean isConstructor() {
- return true;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceField.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceField.java
deleted file mode 100644
index a7ae0bd3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceField.java
+++ /dev/null
@@ -1,170 +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;
-
-import org.eclipse.wst.jsdt.core.IField;
-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.dom.ASTNode;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Binding;
-
-/**
- * @see IField
- */
-
-public class SourceField extends NamedMember implements IField {
-
-/**
- * Constructs a handle to the field with the given name in the specified type.
- */
-protected SourceField(JavaElement parent, String name) {
- super(parent, name);
-}
-public boolean equals(Object o) {
- if (!(o instanceof SourceField)) return false;
- return super.equals(o);
-}
-public ASTNode findNode(org.eclipse.wst.jsdt.core.dom.JavaScriptUnit ast) {
- // For field declarations, a variable declaration fragment is returned
- // Return the FieldDeclaration instead
- // For enum constant declaration, we return the node directly
- ASTNode node = super.findNode(ast);
- if (node == null) return null;
- return node.getParent();
-}
-/**
- * @see IField
- */
-public Object getConstant() throws JavaScriptModelException {
- Object constant = null;
- SourceFieldElementInfo info = (SourceFieldElementInfo) getElementInfo();
- final char[] constantSourceChars = info.initializationSource;
- if (constantSourceChars == null) {
- return null;
- }
-
- String constantSource = new String(constantSourceChars);
- String signature = info.getTypeSignature();
- try {
-// if (signature.equals(Signature.SIG_INT)) {
-// constant = new Integer(constantSource);
-// } else if (signature.equals(Signature.SIG_SHORT)) {
-// constant = new Short(constantSource);
-// } else if (signature.equals(Signature.SIG_BYTE)) {
-// constant = new Byte(constantSource);
-// } else if (signature.equals(Signature.SIG_BOOLEAN)) {
-// constant = Boolean.valueOf(constantSource);
-// } else if (signature.equals(Signature.SIG_CHAR)) {
-// if (constantSourceChars.length != 3) {
-// return null;
-// }
-// constant = new Character(constantSourceChars[1]);
-// } else if (signature.equals(Signature.SIG_DOUBLE)) {
-// constant = new Double(constantSource);
-// } else if (signature.equals(Signature.SIG_FLOAT)) {
-// constant = new Float(constantSource);
-// } else if (signature.equals(Signature.SIG_LONG)) {
-// if (constantSource.endsWith("L") || constantSource.endsWith("l")) { //$NON-NLS-1$ //$NON-NLS-2$
-// int index = constantSource.lastIndexOf("L");//$NON-NLS-1$
-// if (index != -1) {
-// constant = new Long(constantSource.substring(0, index));
-// } else {
-// constant = new Long(constantSource.substring(0, constantSource.lastIndexOf("l")));//$NON-NLS-1$
-// }
-// } else {
-// constant = new Long(constantSource);
-// }
- /*} else*/ if (signature.equals("QString;")) {//$NON-NLS-1$
- constant = constantSource;
- }
- } catch (NumberFormatException e) {
- // not a parsable constant
- return null;
- }
- return constant;
-}
-/**
- * @see IJavaScriptElement
- */
-public int getElementType() {
- return FIELD;
-}
-/* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.IField#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 JavaElement#getHandleMemento()
- */
-protected char getHandleMementoDelimiter() {
- return JavaElement.JEM_FIELD;
-}
-/*
- * @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);
- if (primaryParent instanceof IType)
- return ((IType)primaryParent).getField(this.name);
- return ((IJavaScriptUnit)primaryParent).getField(this.name);
-}
-/**
- * @see IField
- */
-public String getTypeSignature() throws JavaScriptModelException {
- SourceFieldElementInfo info = (SourceFieldElementInfo) getElementInfo();
- return info.getTypeSignature();
-}
-/* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.IField#isResolved()
- */
-public boolean isResolved() {
- return false;
-}
-public JavaElement resolved(Binding binding) {
- SourceRefElement resolvedHandle = new ResolvedSourceField(this.parent, this.name, new String(binding.computeUniqueKey()));
- resolvedHandle.occurrenceCount = this.occurrenceCount;
- return resolvedHandle;
-}
-/**
- * @private Debugging purposes
- */
-protected void toStringInfo(int tab, StringBuffer buffer, Object info, boolean showResolvedInfo) {
- buffer.append(this.tabString(tab));
- if (info == null) {
- toStringName(buffer);
- buffer.append(" (not open)"); //$NON-NLS-1$
- } else if (info == NO_INFO) {
- toStringName(buffer);
- } else {
-// try {
-// buffer.append(Signature.toString(this.getTypeSignature()));
- buffer.append("var "); //$NON-NLS-1$
- toStringName(buffer);
-// } catch (JavaScriptModelException e) {
-// buffer.append("<JavaScriptModelException in toString of " + getElementName()); //$NON-NLS-1$
-// }
- }
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceFieldElementInfo.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceFieldElementInfo.java
deleted file mode 100644
index 9b1ecff5..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceFieldElementInfo.java
+++ /dev/null
@@ -1,78 +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;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.internal.compiler.env.ISourceField;
-
-/**
- * Element info for IField elements.
- */
-
-public class SourceFieldElementInfo extends MemberElementInfo implements ISourceField {
-
- /**
- * The type name of this field.
- */
- protected char[] typeName;
-
- /**
- * The field's initializer string (if the field is a constant).
- */
- protected char[] initializationSource;
-
-/*
- * Returns the initialization source for this field.
- * Returns null if the field is not a constant or if it has no initialization.
- */
-public char[] getInitializationSource() {
- return this.initializationSource;
-}
-/**
- * Returns the type name of the field.
- */
-public char[] getTypeName() {
- return this.typeName;
-}
-/**
- * Returns the type signature of the field.
- *
- * @see Signature
- */
-protected String getTypeSignature() {
- return Signature.createTypeSignature(this.typeName, false);
-}
-
-/**
- * Sets the type name of the field.
- */
-protected void setTypeName(char[] typeName) {
- this.typeName = typeName;
-}
-
-public IJavaScriptElement[] getChildren() {
- IJavaScriptElement[] children = super.getChildren();
- if(children != null && children.length == 1) {
- if(children[0] instanceof SourceType) {
- if(((SourceType)children[0]).isAnonymous()) {
- try {
- children = ((SourceType)children[0]).getChildren();
- } catch (JavaScriptModelException e) {
- e.printStackTrace();
- }
- }
- }
- }
- return children;
-}
-}
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
deleted file mode 100644
index 8872389d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceMapper.java
+++ /dev/null
@@ -1,1305 +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;
-
-import java.io.File;
-import java.io.FilenameFilter;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipFile;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.wst.jsdt.core.Flags;
-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.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-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.CategorizedProblem;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.IProblemFactory;
-import org.eclipse.wst.jsdt.internal.compiler.ISourceElementRequestor;
-import org.eclipse.wst.jsdt.internal.compiler.SourceElementParser;
-import org.eclipse.wst.jsdt.internal.compiler.env.IBinaryType;
-import org.eclipse.wst.jsdt.internal.compiler.impl.CompilerOptions;
-import org.eclipse.wst.jsdt.internal.compiler.problem.DefaultProblemFactory;
-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.util.ReferenceInfoAdapter;
-
-/**
- * A SourceMapper maps source code in a ZIP file to binary types in
- * a JAR. The SourceMapper uses the fuzzy parser to identify source
- * fragments in a .js file, and attempts to match the source code
- * with children in a binary type. A SourceMapper is associated
- * with a JarPackageFragment by an AttachSourceOperation.
- *
- * @see org.eclipse.wst.jsdt.internal.core.JarPackageFragment
- */
-public class SourceMapper
- extends ReferenceInfoAdapter
- implements ISourceElementRequestor, SuffixConstants {
-
- public static boolean VERBOSE = false;
- /**
- * Specifies the file name filter use to compute the root paths.
- */
- private static final FilenameFilter FILENAME_FILTER = new FilenameFilter() {
- public boolean accept(File dir, String name) {
- return org.eclipse.wst.jsdt.internal.core.util.Util.isJavaLikeFileName(name);
- }
- };
- /**
- * Specifies the location of the package fragment roots within
- * the zip (empty specifies the default root). <code>null</code> is
- * not a valid root path.
- */
- protected ArrayList rootPaths;
-
- /**
- * The binary type source is being mapped for
- */
- protected BinaryType binaryType;
-
- /**
- * The location of the zip file containing source.
- */
- protected IPath sourcePath;
- /**
- * Specifies the location of the package fragment root within
- * the zip (empty specifies the default root). <code>null</code> is
- * not a valid root path.
- */
- protected String rootPath = ""; //$NON-NLS-1$
-
- /**
- * Table that maps a binary method to its parameter names.
- * Keys are the method handles, entries are <code>char[][]</code>.
- */
- protected HashMap parameterNames;
-
- /**
- * Table that maps a binary element to its <code>SourceRange</code>s.
- * Keys are the element handles, entries are <code>SourceRange[]</code> which
- * is a two element array; the first being source range, the second
- * being name range.
- */
- protected HashMap sourceRanges;
-
- /*
- * A map from IJavaScriptElement to String[]
- */
- protected HashMap categories;
-
-
- /**
- * The unknown source range {-1, 0}
- */
- public static final SourceRange UNKNOWN_RANGE = new SourceRange(-1, 0);
-
- /**
- * The position within the source of the start of the
- * current member element, or -1 if we are outside a member.
- */
- protected int[] memberDeclarationStart;
- /**
- * The <code>SourceRange</code> of the name of the current member element.
- */
- protected SourceRange[] memberNameRange;
- /**
- * The name of the current member element.
- */
- protected String[] memberName;
-
- /**
- * The parameter names for the current member method element.
- */
- protected char[][][] methodParameterNames;
-
- /**
- * The parameter types for the current member method element.
- */
- protected char[][][] methodParameterTypes;
-
-
- /**
- * The element searched for
- */
- protected IJavaScriptElement searchedElement;
-
- /**
- * imports references
- */
- private HashMap importsTable;
- private HashMap importsCounterTable;
-
- /**
- * Enclosing type information
- */
- IType[] types;
- int[] typeDeclarationStarts;
- SourceRange[] typeNameRanges;
- int[] typeModifiers;
- int typeDepth;
-
- /**
- * Anonymous counter in case we want to map the source of an anonymous class.
- */
- int anonymousCounter;
- int anonymousClassName;
-
- /**
- *Options to be used
- */
- String encoding;
- Map options;
-
- /**
- * Use to handle root paths inference
- */
- private boolean areRootPathsComputed;
-
- public SourceMapper() {
- this.areRootPathsComputed = false;
- }
-
- /**
- * Creates a <code>SourceMapper</code> that locates source in the zip file
- * at the given location in the specified package fragment root.
- */
- public SourceMapper(IPath sourcePath, String rootPath, Map options) {
- this.areRootPathsComputed = false;
- this.options = options;
- try {
- this.encoding = ResourcesPlugin.getWorkspace().getRoot().getDefaultCharset();
- } catch (CoreException e) {
- // use no encoding
- }
- if (rootPath != null) {
- this.rootPaths = new ArrayList();
- this.rootPaths.add(rootPath);
- }
- this.sourcePath = sourcePath;
- this.sourceRanges = new HashMap();
- this.parameterNames = new HashMap();
- this.importsTable = new HashMap();
- this.importsCounterTable = new HashMap();
- }
-
- /**
- * @see ISourceElementRequestor
- */
- public void acceptImport(
- int declarationStart,
- int declarationEnd,
- char[][] tokens,
- boolean onDemand) {
- char[][] imports = (char[][]) this.importsTable.get(this.binaryType);
- int importsCounter;
- if (imports == null) {
- imports = new char[5][];
- importsCounter = 0;
- } else {
- importsCounter = ((Integer) this.importsCounterTable.get(this.binaryType)).intValue();
- }
- if (imports.length == importsCounter) {
- System.arraycopy(
- imports,
- 0,
- (imports = new char[importsCounter * 2][]),
- 0,
- importsCounter);
- }
- char[] name = CharOperation.concatWith(tokens, '.');
- if (onDemand) {
- int nameLength = name.length;
- System.arraycopy(name, 0, (name = new char[nameLength + 2]), 0, nameLength);
- name[nameLength] = '.';
- name[nameLength + 1] = '*';
- }
- imports[importsCounter++] = name;
- this.importsTable.put(this.binaryType, imports);
- this.importsCounterTable.put(this.binaryType, new Integer(importsCounter));
- }
-
- /**
- * @see ISourceElementRequestor
- */
- public void acceptLineSeparatorPositions(int[] positions) {
- //do nothing
- }
-
- /**
- * @see ISourceElementRequestor
- */
- public void acceptPackage(
- int declarationStart,
- int declarationEnd,
- char[] name) {
- //do nothing
- }
-
- /**
- * @see ISourceElementRequestor
- */
- public void acceptProblem(CategorizedProblem problem) {
- //do nothing
- }
-
- private void addCategories(IJavaScriptElement element, char[][] elementCategories) {
- if (elementCategories == null) return;
- if (this.categories == null)
- this.categories = new HashMap();
- this.categories.put(element, CharOperation.toStrings(elementCategories));
- }
-
- /**
- * Closes this <code>SourceMapper</code>'s zip file. Once this is done, this
- * <code>SourceMapper</code> cannot be used again.
- */
- public void close() {
- this.sourceRanges = null;
- this.parameterNames = null;
- }
-
- /**
- * Converts these type names to unqualified signatures. This needs to be done in order to be consistent
- * with the way the source range is retrieved.
- * @see SourceMapper#getUnqualifiedMethodHandle
- * @see Signature
- */
- private String[] convertTypeNamesToSigs(char[][] typeNames) {
- if (typeNames == null)
- return CharOperation.NO_STRINGS;
- int n = typeNames.length;
- if (n == 0)
- return CharOperation.NO_STRINGS;
- String[] typeSigs = new String[n];
- for (int i = 0; i < n; ++i) {
- char[] typeSig = Signature.createCharArrayTypeSignature(typeNames[i], false);
-
- // transforms signatures that contains a qualification into unqualified signatures
- // e.g. "QX<+QMap.Entry;>;" becomes "QX<+QEntry;>;"
- StringBuffer simpleTypeSig = null;
- int start = 0;
- int dot = -1;
- int length = typeSig.length;
- for (int j = 0; j < length; j++) {
- switch (typeSig[j]) {
- case Signature.C_UNRESOLVED:
- if (simpleTypeSig != null)
- simpleTypeSig.append(typeSig, start, j-start);
- start = j;
- break;
- case Signature.C_DOT:
- dot = j;
- break;
- case Signature.C_NAME_END:
- if (dot > start) {
- if (simpleTypeSig == null)
- simpleTypeSig = new StringBuffer().append(typeSig, 0, start);
- simpleTypeSig.append(Signature.C_UNRESOLVED);
- simpleTypeSig.append(typeSig, dot+1, j-dot-1);
- start = j;
- }
- break;
- }
- }
- if (simpleTypeSig == null) {
- typeSigs[i] = new String(typeSig);
- } else {
- simpleTypeSig.append(typeSig, start, length-start);
- typeSigs[i] = simpleTypeSig.toString();
- }
- }
- return typeSigs;
- }
-
- private synchronized void computeAllRootPaths(IType type) {
- if (this.areRootPathsComputed) {
- return;
- }
- IPackageFragmentRoot root = (IPackageFragmentRoot) type.getPackageFragment().getParent();
- final HashSet tempRoots = new HashSet();
- long time = 0;
- if (VERBOSE) {
- System.out.println("compute all root paths for " + root.getElementName()); //$NON-NLS-1$
- time = System.currentTimeMillis();
- }
- final HashSet firstLevelPackageNames = new HashSet();
- boolean containsADefaultPackage = false;
-
-// if (root.isArchive()) {
-// JarPackageFragmentRoot jarPackageFragmentRoot = (JarPackageFragmentRoot) root;
-// IJavaScriptProject project = jarPackageFragmentRoot.getJavaScriptProject();
-// String sourceLevel = null;
-// String complianceLevel = null;
-// JavaModelManager manager = JavaModelManager.getJavaModelManager();
-// ZipFile zip = null;
-// try {
-// zip = manager.getZipFile(jarPackageFragmentRoot.getPath());
-// for (Enumeration entries = zip.entries(); entries.hasMoreElements(); ) {
-// ZipEntry entry = (ZipEntry) entries.nextElement();
-// String entryName = entry.getName();
-// if (!entry.isDirectory()) {
-// int index = entryName.indexOf('/');
-// if (index != -1 && Util.isClassFileName(entryName)) {
-// String firstLevelPackageName = entryName.substring(0, index);
-// if (!firstLevelPackageNames.contains(firstLevelPackageName)) {
-// if (sourceLevel == null) {
-// sourceLevel = project.getOption(JavaScriptCore.COMPILER_SOURCE, true);
-// complianceLevel = project.getOption(JavaScriptCore.COMPILER_COMPLIANCE, true);
-// }
-// IStatus status = JavaScriptConventions.validatePackageName(firstLevelPackageName, sourceLevel, complianceLevel);
-// if (status.isOK() || status.getSeverity() == IStatus.WARNING) {
-// firstLevelPackageNames.add(firstLevelPackageName);
-// }
-// }
-// } else if (Util.isClassFileName(entryName)) {
-// containsADefaultPackage = true;
-// }
-// }
-// }
-// } catch (CoreException e) {
-// // ignore
-// } finally {
-// manager.closeZipFile(zip); // handle null case
-// }
-// } else
- {
- Object target = JavaModel.getTarget(ResourcesPlugin.getWorkspace().getRoot(), root.getPath(), true);
- if (target instanceof IResource) {
- IResource resource = (IResource) target;
- if (resource instanceof IContainer) {
- try {
- IResource[] members = ((IContainer) resource).members();
- for (int i = 0, max = members.length; i < max; i++) {
- IResource member = members[i];
- if (member.getType() == IResource.FOLDER) {
- firstLevelPackageNames.add(member.getName());
- } else if (Util.isClassFileName(member.getName())) {
- containsADefaultPackage = true;
- }
- }
- } catch (CoreException e) {
- // ignore
- }
- }
- } else if (target instanceof File) {
- File file = (File)target;
- if (file.isDirectory()) {
- File[] files = file.listFiles();
- for (int i = 0, max = files.length; i < max; i++) {
- File currentFile = files[i];
- if (currentFile.isDirectory()) {
- firstLevelPackageNames.add(currentFile.getName());
- } else if (Util.isClassFileName(currentFile.getName())) {
- containsADefaultPackage = true;
- }
- }
- }
- }
- }
-
- if (Util.isArchiveFileName(this.sourcePath.lastSegment())) {
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- ZipFile zip = null;
- try {
- zip = manager.getZipFile(this.sourcePath);
- for (Enumeration entries = zip.entries(); entries.hasMoreElements(); ) {
- ZipEntry entry = (ZipEntry) entries.nextElement();
- String entryName;
- if (!entry.isDirectory() && org.eclipse.wst.jsdt.internal.core.util.Util.isJavaLikeFileName(entryName = entry.getName())) {
- IPath path = new Path(entryName);
- int segmentCount = path.segmentCount();
- if (segmentCount > 1) {
- for (int i = 0, max = path.segmentCount() - 1; i < max; i++) {
- if (firstLevelPackageNames.contains(path.segment(i))) {
- tempRoots.add(path.uptoSegment(i));
- // don't break here as this path could contain other first level package names (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=74014)
- }
- if (i == max - 1 && containsADefaultPackage) {
- tempRoots.add(path.uptoSegment(max));
- }
- }
- } else if (containsADefaultPackage) {
- tempRoots.add(new Path("")); //$NON-NLS-1$
- }
- }
- }
- } catch (CoreException e) {
- // ignore
- } finally {
- manager.closeZipFile(zip); // handle null case
- }
- } else {
- Object target = JavaModel.getTarget(ResourcesPlugin.getWorkspace().getRoot(), this.sourcePath, true);
- if (target instanceof IResource) {
- if (target instanceof IContainer) {
- computeRootPath((IContainer)target, firstLevelPackageNames, containsADefaultPackage, tempRoots);
- }
- } else if (target instanceof File) {
- File file = (File)target;
- if (file.isDirectory()) {
- computeRootPath(file, firstLevelPackageNames, containsADefaultPackage, tempRoots);
- }
- }
- }
- int size = tempRoots.size();
- if (this.rootPaths != null) {
- for (Iterator iterator = this.rootPaths.iterator(); iterator.hasNext(); ) {
- tempRoots.add(new Path((String) iterator.next()));
- }
- this.rootPaths.clear();
- } else {
- this.rootPaths = new ArrayList(size);
- }
- size = tempRoots.size();
- if (size > 0) {
- ArrayList sortedRoots = new ArrayList(tempRoots);
- if (size > 1) {
- Collections.sort(sortedRoots, new Comparator() {
- public int compare(Object o1, Object o2) {
- IPath path1 = (IPath) o1;
- IPath path2 = (IPath) o2;
- return path1.segmentCount() - path2.segmentCount();
- }
- });
- }
- for (Iterator iter = sortedRoots.iterator(); iter.hasNext();) {
- IPath path = (IPath) iter.next();
- this.rootPaths.add(path.toString());
- }
- }
- this.areRootPathsComputed = true;
- if (VERBOSE) {
- System.out.println("Spent " + (System.currentTimeMillis() - time) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
- System.out.println("Found " + size + " root paths"); //$NON-NLS-1$ //$NON-NLS-2$
- int i = 0;
- for (Iterator iterator = this.rootPaths.iterator(); iterator.hasNext();) {
- System.out.println("root[" + i + "]=" + ((String) iterator.next()));//$NON-NLS-1$ //$NON-NLS-2$
- i++;
- }
- }
- }
-
- private void computeRootPath(File directory, HashSet firstLevelPackageNames, boolean hasDefaultPackage, Set set) {
- File[] files = directory.listFiles();
- boolean hasSubDirectories = false;
- loop: for (int i = 0, max = files.length; i < max; i++) {
- File file = files[i];
- if (file.isDirectory()) {
- hasSubDirectories = true;
- if (firstLevelPackageNames.contains(file.getName())) {
- IPath fullPath = new Path(file.getParentFile().getPath());
- IPath rootPathEntry = fullPath.removeFirstSegments(this.sourcePath.segmentCount()).setDevice(null);
- set.add(rootPathEntry);
- break loop;
- } else {
- computeRootPath(file, firstLevelPackageNames, hasDefaultPackage, set);
- }
- } else if (i == max - 1 && !hasSubDirectories && hasDefaultPackage) {
- File parentDir = file.getParentFile();
- if (parentDir.list(FILENAME_FILTER).length != 0) {
- IPath fullPath = new Path(parentDir.getPath());
- IPath rootPathEntry = fullPath.removeFirstSegments(this.sourcePath.segmentCount()).setDevice(null);
- set.add(rootPathEntry);
- }
- }
- }
- }
-
- private void computeRootPath(IContainer container, HashSet firstLevelPackageNames, boolean hasDefaultPackage, Set set) {
- try {
- IResource[] resources = container.members();
- boolean hasSubDirectories = false;
- loop: for (int i = 0, max = resources.length; i < max; i++) {
- IResource resource = resources[i];
- if (resource.getType() == IResource.FOLDER) {
- hasSubDirectories = true;
- if (firstLevelPackageNames.contains(resource.getName())) {
- IPath fullPath = container.getFullPath();
- IPath rootPathEntry = fullPath.removeFirstSegments(this.sourcePath.segmentCount()).setDevice(null);
- set.add(rootPathEntry);
- break loop;
- } else {
- computeRootPath((IFolder) resource, firstLevelPackageNames, hasDefaultPackage, set);
- }
- }
- if (i == max - 1 && !hasSubDirectories && hasDefaultPackage) {
- // check if one member is a .js file
- boolean hasJavaSourceFile = false;
- for (int j = 0; j < max; j++) {
- if (org.eclipse.wst.jsdt.internal.core.util.Util.isJavaLikeFileName(resources[i].getName())) {
- hasJavaSourceFile = true;
- break;
- }
- }
- if (hasJavaSourceFile) {
- IPath fullPath = container.getFullPath();
- IPath rootPathEntry = fullPath.removeFirstSegments(this.sourcePath.segmentCount()).setDevice(null);
- set.add(rootPathEntry);
- }
- }
- }
- } catch (CoreException e) {
- // ignore
- }
- }
-
- /**
- * @see ISourceElementRequestor
- */
- public void enterType(TypeInfo typeInfo) {
-
- this.typeDepth++;
- if (this.typeDepth == this.types.length) { // need to grow
- System.arraycopy(
- this.types,
- 0,
- this.types = new IType[this.typeDepth * 2],
- 0,
- this.typeDepth);
- System.arraycopy(
- this.typeNameRanges,
- 0,
- this.typeNameRanges = new SourceRange[this.typeDepth * 2],
- 0,
- this.typeDepth);
- System.arraycopy(
- this.typeDeclarationStarts,
- 0,
- this.typeDeclarationStarts = new int[this.typeDepth * 2],
- 0,
- this.typeDepth);
- System.arraycopy(
- this.memberName,
- 0,
- this.memberName = new String[this.typeDepth * 2],
- 0,
- this.typeDepth);
- System.arraycopy(
- this.memberDeclarationStart,
- 0,
- this.memberDeclarationStart = new int[this.typeDepth * 2],
- 0,
- this.typeDepth);
- System.arraycopy(
- this.memberNameRange,
- 0,
- this.memberNameRange = new SourceRange[this.typeDepth * 2],
- 0,
- this.typeDepth);
- System.arraycopy(
- this.methodParameterTypes,
- 0,
- this.methodParameterTypes = new char[this.typeDepth * 2][][],
- 0,
- this.typeDepth);
- System.arraycopy(
- this.methodParameterNames,
- 0,
- this.methodParameterNames = new char[this.typeDepth * 2][][],
- 0,
- this.typeDepth);
- System.arraycopy(
- this.typeModifiers,
- 0,
- this.typeModifiers = new int[this.typeDepth * 2],
- 0,
- this.typeDepth);
- }
- if (typeInfo.name.length == 0) {
- this.anonymousCounter++;
- if (this.anonymousCounter == this.anonymousClassName) {
- this.types[typeDepth] = this.getType(this.binaryType.getElementName());
- } else {
- this.types[typeDepth] = this.getType(new String(typeInfo.name));
- }
- } else {
- this.types[typeDepth] = this.getType(new String(typeInfo.name));
- }
- this.typeNameRanges[typeDepth] =
- new SourceRange(typeInfo.nameSourceStart, typeInfo.nameSourceEnd - typeInfo.nameSourceStart + 1);
- this.typeDeclarationStarts[typeDepth] = typeInfo.declarationStart;
-
- IType currentType = this.types[typeDepth];
-
- // type modifiers
- this.typeModifiers[typeDepth] = typeInfo.modifiers;
-
- // categories
- addCategories(currentType, typeInfo.categories);
- }
-
- /**
- * @see ISourceElementRequestor
- */
- public void enterCompilationUnit() {
- // do nothing
- }
-
- /**
- * @see ISourceElementRequestor
- */
- public void enterConstructor(MethodInfo methodInfo) {
- enterAbstractMethod(methodInfo);
- }
-
- /**
- * @see ISourceElementRequestor
- */
- public void enterField(FieldInfo fieldInfo) {
- if (typeDepth >= 0) {
- this.memberDeclarationStart[typeDepth] = fieldInfo.declarationStart;
- this.memberNameRange[typeDepth] =
- new SourceRange(fieldInfo.nameSourceStart, fieldInfo.nameSourceEnd - fieldInfo.nameSourceStart + 1);
- String fieldName = new String(fieldInfo.name);
- this.memberName[typeDepth] = fieldName;
-
- // categories
- IType currentType = this.types[typeDepth];
- IField field = currentType.getField(fieldName);
- addCategories(field, fieldInfo.categories);
- }
- }
-
- /**
- * @see ISourceElementRequestor
- */
- public void enterInitializer(
- int declarationSourceStart,
- int modifiers) {
- //do nothing
- }
-
- /**
- * @see ISourceElementRequestor
- */
- public void enterMethod(MethodInfo methodInfo) {
- enterAbstractMethod(methodInfo);
- }
- private void enterAbstractMethod(MethodInfo methodInfo) {
- if (typeDepth >= 0) {
- this.memberName[typeDepth] = new String(methodInfo.name);
- this.memberNameRange[typeDepth] =
- new SourceRange(methodInfo.nameSourceStart, methodInfo.nameSourceEnd - methodInfo.nameSourceStart + 1);
- this.memberDeclarationStart[typeDepth] = methodInfo.declarationStart;
- IType currentType = this.types[typeDepth];
- int currenTypeModifiers = this.typeModifiers[typeDepth];
- char[][] parameterTypes = methodInfo.parameterTypes;
- if (parameterTypes != null && methodInfo.isConstructor && currentType.getDeclaringType() != null && !Flags.isStatic(currenTypeModifiers)) {
- IType declaringType = currentType.getDeclaringType();
- String declaringTypeName = declaringType.getElementName();
- if (declaringTypeName.length() == 0) {
- IClassFile classFile = declaringType.getClassFile();
- int length = parameterTypes.length;
- char[][] newParameterTypes = new char[length+1][];
- declaringTypeName = classFile.getElementName();
- declaringTypeName = declaringTypeName.substring(0, declaringTypeName.indexOf('.'));
- newParameterTypes[0] = declaringTypeName.toCharArray();
- System.arraycopy(parameterTypes, 0, newParameterTypes, 1, length);
- this.methodParameterTypes[typeDepth] = newParameterTypes;
- } else {
- int length = parameterTypes.length;
- char[][] newParameterTypes = new char[length+1][];
- newParameterTypes[0] = declaringTypeName.toCharArray();
- System.arraycopy(parameterTypes, 0, newParameterTypes, 1, length);
- this.methodParameterTypes[typeDepth] = newParameterTypes;
- }
- } else {
- this.methodParameterTypes[typeDepth] = parameterTypes;
- }
- this.methodParameterNames[typeDepth] = methodInfo.parameterNames;
-
- IFunction method = currentType.getFunction(
- this.memberName[typeDepth],
- convertTypeNamesToSigs(this.methodParameterTypes[typeDepth]));
-
- // categories
- addCategories(method, methodInfo.categories);
- }
- }
-
- /**
- * @see ISourceElementRequestor
- */
- public void exitType(int declarationEnd) {
- if (typeDepth >= 0) {
- IType currentType = this.types[typeDepth];
- setSourceRange(
- currentType,
- new SourceRange(
- this.typeDeclarationStarts[typeDepth],
- declarationEnd - this.typeDeclarationStarts[typeDepth] + 1),
- this.typeNameRanges[typeDepth]);
- this.typeDepth--;
- }
- }
-
- /**
- * @see ISourceElementRequestor
- */
- public void exitCompilationUnit(int declarationEnd) {
- //do nothing
- }
-
- /**
- * @see ISourceElementRequestor
- */
- public void exitConstructor(int declarationEnd) {
- exitAbstractMethod(declarationEnd);
- }
-
- /**
- * @see ISourceElementRequestor
- */
- public void exitField(int initializationStart, int declarationEnd, int declarationSourceEnd) {
- if (typeDepth >= 0) {
- IType currentType = this.types[typeDepth];
- setSourceRange(
- currentType.getField(this.memberName[typeDepth]),
- new SourceRange(
- this.memberDeclarationStart[typeDepth],
- declarationEnd - this.memberDeclarationStart[typeDepth] + 1),
- this.memberNameRange[typeDepth]);
- }
- }
-
- /**
- * @see ISourceElementRequestor
- */
- public void exitInitializer(int declarationEnd) {
- // implements abstract method
- }
-
- /**
- * @see ISourceElementRequestor
- */
- public void exitMethod(int declarationEnd, int defaultValueStart, int defaultValueEnd) {
- exitAbstractMethod(declarationEnd);
- }
- private void exitAbstractMethod(int declarationEnd) {
- if (typeDepth >= 0) {
- IType currentType = this.types[typeDepth];
- SourceRange sourceRange =
- new SourceRange(
- this.memberDeclarationStart[typeDepth],
- declarationEnd - this.memberDeclarationStart[typeDepth] + 1);
- IFunction method = currentType.getFunction(
- this.memberName[typeDepth],
- convertTypeNamesToSigs(this.methodParameterTypes[typeDepth]));
- setSourceRange(
- method,
- sourceRange,
- this.memberNameRange[typeDepth]);
- setMethodParameterNames(
- method,
- this.methodParameterNames[typeDepth]);
- }
- }
-
- /**
- * Locates and returns source code for the given (binary) type, in this
- * SourceMapper's ZIP file, or returns <code>null</code> if source
- * code cannot be found.
- */
- public char[] findSource(IType type, IBinaryType info) {
- if (!type.isBinary()) {
- return null;
- }
- String simpleSourceFileName = ((BinaryType) type).getSourceFileName(info);
- if (simpleSourceFileName == null) {
- return null;
- }
- return findSource(type, simpleSourceFileName);
- }
-
- /**
- * Locates and returns source code for the given (binary) type, in this
- * SourceMapper's ZIP file, or returns <code>null</code> if source
- * code cannot be found.
- * The given simpleSourceFileName is the .js file name (without the enclosing
- * folder) used to create the given type (e.g. "A.js" for x/y/A$Inner.class)
- */
- public char[] findSource(IType type, String simpleSourceFileName) {
- long time = 0;
- if (VERBOSE) {
- time = System.currentTimeMillis();
- }
- PackageFragment pkgFrag = (PackageFragment) type.getPackageFragment();
- String name = org.eclipse.wst.jsdt.internal.core.util.Util.concatWith(pkgFrag.names, simpleSourceFileName, '/');
-
- char[] source = null;
-
- if (this.rootPath != null) {
- source = getSourceForRootPath(this.rootPath, name);
- }
-
- if (source == null) {
- computeAllRootPaths(type);
- if (this.rootPaths != null) {
- loop: for (Iterator iterator = this.rootPaths.iterator(); iterator.hasNext(); ) {
- String currentRootPath = (String) iterator.next();
- if (!currentRootPath.equals(this.rootPath)) {
- source = getSourceForRootPath(currentRootPath, name);
- if (source != null) {
- // remember right root path
- this.rootPath = currentRootPath;
- break loop;
- }
- }
- }
- }
- }
- if (VERBOSE) {
- System.out.println("spent " + (System.currentTimeMillis() - time) + "ms for " + type.getElementName()); //$NON-NLS-1$ //$NON-NLS-2$
- }
- return source;
- }
-
- private char[] getSourceForRootPath(String currentRootPath, String name) {
- String newFullName;
- if (!currentRootPath.equals(IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH)) {
- if (currentRootPath.endsWith("/")) { //$NON-NLS-1$
- newFullName = currentRootPath + name;
- } else {
- newFullName = currentRootPath + '/' + name;
- }
- } else {
- newFullName = name;
- }
- return this.findSource(newFullName);
- }
-
- public char[] findSource(String fullName) {
- char[] source = null;
- if (Util.isArchiveFileName(this.sourcePath.lastSegment())) {
- // try to get the entry
- ZipEntry entry = null;
- ZipFile zip = null;
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- try {
- zip = manager.getZipFile(this.sourcePath);
- entry = zip.getEntry(fullName);
- if (entry != null) {
- // now read the source code
- source = readSource(entry, zip);
- }
- } catch (CoreException e) {
- return null;
- } finally {
- manager.closeZipFile(zip); // handle null case
- }
- } else {
- Object target = JavaModel.getTarget(ResourcesPlugin.getWorkspace().getRoot(), this.sourcePath, true);
- if (target instanceof IResource) {
- if (target instanceof IContainer) {
- IResource res = ((IContainer)target).findMember(fullName);
- if (res instanceof IFile) {
- try {
- source = org.eclipse.wst.jsdt.internal.core.util.Util.getResourceContentsAsCharArray((IFile)res);
- } catch (JavaScriptModelException e) {
- // ignore
- }
- }
- }
- } else if (target instanceof File) {
- File file = (File)target;
- if (file.isDirectory()) {
- File sourceFile = new File(file, fullName);
- if (sourceFile.isFile()) {
- try {
- source = Util.getFileCharContent(sourceFile, this.encoding);
- } catch (IOException e) {
- // ignore
- }
- }
- }
- }
- }
- return source;
- }
-
-
-
- /**
- * Returns the SourceRange for the name of the given element, or
- * {-1, -1} if no source range is known for the name of the element.
- */
- public SourceRange getNameRange(IJavaScriptElement element) {
- switch(element.getElementType()) {
- case IJavaScriptElement.METHOD :
- if (((IMember) element).isBinary()) {
- IJavaScriptElement[] el = getUnqualifiedMethodHandle((IFunction) element, false);
- if(el[1] != null && this.sourceRanges.get(el[0]) == null) {
- element = getUnqualifiedMethodHandle((IFunction) element, true)[0];
- } else {
- element = el[0];
- }
- }
- break;
- }
- SourceRange[] ranges = (SourceRange[]) this.sourceRanges.get(element);
- if (ranges == null) {
- return UNKNOWN_RANGE;
- } else {
- return ranges[1];
- }
- }
-
- /**
- * Returns parameters names for the given method, or
- * null if no parameter names are known for the method.
- */
- public char[][] getMethodParameterNames(IFunction method) {
- if (method.isBinary()) {
- IJavaScriptElement[] el = getUnqualifiedMethodHandle(method, false);
- if(el[1] != null && this.parameterNames.get(el[0]) == null) {
- method = (IFunction) getUnqualifiedMethodHandle(method, true)[0];
- } else {
- method = (IFunction) el[0];
- }
- }
- char[][] parameters = (char[][]) this.parameterNames.get(method);
- if (parameters == null) {
- return null;
- } else {
- return parameters;
- }
- }
-
- /**
- * Returns the <code>SourceRange</code> for the given element, or
- * {-1, -1} if no source range is known for the element.
- */
- public SourceRange getSourceRange(IJavaScriptElement element) {
- if (!this.areRootPathsComputed && element instanceof ISourceReference)
- try {
- return (SourceRange)((ISourceReference)element).getSourceRange();
- } catch (JavaScriptModelException e) {
- org.eclipse.wst.jsdt.internal.core.util.Util.log(e, "error getting source range"); //$NON-NLS-1$
- return UNKNOWN_RANGE;
- }
- switch(element.getElementType()) {
- case IJavaScriptElement.METHOD :
- if (((IMember) element).isBinary()) {
- IJavaScriptElement[] el = getUnqualifiedMethodHandle((IFunction) element, false);
- if(el[1] != null && this.sourceRanges.get(el[0]) == null) {
- element = getUnqualifiedMethodHandle((IFunction) element, true)[0];
- } else {
- element = el[0];
- }
- }
- break;
- }
- SourceRange[] ranges = (SourceRange[]) this.sourceRanges.get(element);
- if (ranges == null) {
- return UNKNOWN_RANGE;
- } else {
- return ranges[0];
- }
- }
-
- /**
- * Returns the type with the given <code>typeName</code>. Returns inner classes
- * as well.
- */
- protected IType getType(String typeName) {
- if (typeName.length() == 0) {
- IJavaScriptElement classFile = this.binaryType.getParent();
- String classFileName = classFile.getElementName();
- StringBuffer newClassFileName = new StringBuffer();
- int lastDollar = classFileName.lastIndexOf('$');
- for (int i = 0; i <= lastDollar; i++)
- newClassFileName.append(classFileName.charAt(i));
- newClassFileName.append(Integer.toString(this.anonymousCounter));
- PackageFragment pkg = (PackageFragment) classFile.getParent();
- return new BinaryType(new ClassFile(pkg, newClassFileName.toString()), typeName);
- } else if (this.binaryType.getElementName().equals(typeName))
- return this.binaryType;
- else
- return this.binaryType.getType(typeName);
- }
-
- /**
- * Creates a handle that has parameter types that are not
- * fully qualified so that the correct source is found.
- */
- protected IJavaScriptElement[] getUnqualifiedMethodHandle(IFunction method, boolean noDollar) {
- 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;
- }
-
- IJavaScriptElement[] result = new IJavaScriptElement[2];
- result[0] = ((IType) method.getParent()).getFunction(
- method.getElementName(),
- unqualifiedParameterTypes);
- if(hasDollar) {
- result[1] = result[0];
- }
- return result;
- }
-
- private int getUnqualifiedTypeSignature(String qualifiedTypeSig, int start, int length, StringBuffer unqualifiedTypeSig, boolean noDollar) {
- char firstChar = qualifiedTypeSig.charAt(start);
- int end = start + 1;
- boolean sigStart = false;
- firstPass: for (int i = start; i < length; i++) {
- char current = qualifiedTypeSig.charAt(i);
- switch (current) {
- case Signature.C_ARRAY :
- unqualifiedTypeSig.append(current);
- start = i + 1;
- end = start + 1;
- firstChar = qualifiedTypeSig.charAt(start);
- break;
- case Signature.C_RESOLVED :
- case Signature.C_UNRESOLVED :
- if (!sigStart) {
- start = ++i;
- sigStart = true;
- }
- break;
- case Signature.C_NAME_END:
- end = i;
- break firstPass;
- case Signature.C_DOT:
- start = ++i;
- break;
- }
- }
- switch (firstChar) {
- case Signature.C_RESOLVED :
- case Signature.C_UNRESOLVED :
- unqualifiedTypeSig.append(Signature.C_UNRESOLVED);
- if (noDollar) {
- int lastDollar = qualifiedTypeSig.lastIndexOf('$', end);
- if (lastDollar > start)
- start = lastDollar + 1;
- }
- for (int i = start; i < length; i++) {
- char current = qualifiedTypeSig.charAt(i);
- switch (current) {
- case Signature.C_NAME_END:
- unqualifiedTypeSig.append(current);
- return i + 1;
- default:
- unqualifiedTypeSig.append(current);
- break;
- }
- }
- return length;
- default :
- // primitive type or wildcard
- unqualifiedTypeSig.append(qualifiedTypeSig.substring(start, end));
- return end;
- }
- }
-
- /**
- * Maps the given source code to the given binary type and its children.
- */
- public void mapSource(IType type, char[] contents, IBinaryType info) {
- this.mapSource(type, contents, info, null);
- }
-
- /**
- * Maps the given source code to the given binary type and its children.
- * If a non-null java element is passed, finds the name range for the
- * given java element without storing it.
- */
- public synchronized ISourceRange mapSource(
- IType type,
- char[] contents,
- IBinaryType info,
- IJavaScriptElement elementToFind) {
-
- this.binaryType = (BinaryType) type;
-
- // check whether it is already mapped
- if (this.sourceRanges.get(type) != null) return (elementToFind != null) ? getNameRange(elementToFind) : null;
-
- this.importsTable.remove(this.binaryType);
- this.importsCounterTable.remove(this.binaryType);
- this.searchedElement = elementToFind;
- this.types = new IType[1];
- this.typeDeclarationStarts = new int[1];
- this.typeNameRanges = new SourceRange[1];
- this.typeModifiers = new int[1];
- this.typeDepth = -1;
- this.memberDeclarationStart = new int[1];
- this.memberName = new String[1];
- this.memberNameRange = new SourceRange[1];
- this.methodParameterTypes = new char[1][][];
- this.methodParameterNames = new char[1][][];
- this.anonymousCounter = 0;
-
- HashMap oldSourceRanges = (HashMap) this.sourceRanges.clone();
- try {
- IProblemFactory factory = new DefaultProblemFactory();
- SourceElementParser parser = null;
- this.anonymousClassName = 0;
- if (info == null) {
- try {
- info = (IBinaryType) this.binaryType.getElementInfo();
- } catch(JavaScriptModelException e) {
- return null;
- }
- }
- boolean isAnonymousClass = info.isAnonymous();
- char[] fullName = info.getName();
- if (isAnonymousClass) {
- String eltName = this.binaryType.getParent().getElementName();
- eltName = eltName.substring(eltName.lastIndexOf('$') + 1, eltName.length());
- try {
- this.anonymousClassName = Integer.parseInt(eltName);
- } catch(NumberFormatException e) {
- // ignore
- }
- }
- boolean doFullParse = hasToRetrieveSourceRangesForLocalClass(fullName);
- parser = new SourceElementParser(this, factory, new CompilerOptions(this.options), doFullParse, true/*optimize string literals*/);
- parser.javadocParser.checkDocComment = false; // disable javadoc parsing
- IJavaScriptElement javaElement = this.binaryType.getJavaScriptUnit();
- if (javaElement == null) javaElement = this.binaryType.getParent();
- parser.parseCompilationUnit(
- new BasicCompilationUnit(contents, null, this.binaryType.sourceFileName(info), javaElement),
- doFullParse);
- if (elementToFind != null) {
- ISourceRange range = this.getNameRange(elementToFind);
- return range;
- } else {
- return null;
- }
- } finally {
- if (elementToFind != null) {
- this.sourceRanges = oldSourceRanges;
- }
- this.binaryType = null;
- this.searchedElement = null;
- this.types = null;
- this.typeDeclarationStarts = null;
- this.typeNameRanges = null;
- this.typeDepth = -1;
- }
- }
- private char[] readSource(ZipEntry entry, ZipFile zip) {
- try {
- byte[] bytes = Util.getZipEntryByteContent(entry, zip);
- if (bytes != null) {
- return Util.bytesToChar(bytes, this.encoding);
- }
- } catch (IOException e) {
- // ignore
- }
- return null;
- }
-
- /**
- * Sets the mapping for this method to its parameter names.
- *
- * @see #parameterNames
- */
- protected void setMethodParameterNames(
- IFunction method,
- char[][] parameterNames) {
- if (parameterNames == null) {
- parameterNames = CharOperation.NO_CHAR_CHAR;
- }
- this.parameterNames.put(method, parameterNames);
- }
-
- /**
- * Sets the mapping for this element to its source ranges for its source range
- * and name range.
- *
- * @see #sourceRanges
- */
- protected void setSourceRange(
- IJavaScriptElement element,
- SourceRange sourceRange,
- SourceRange nameRange) {
- this.sourceRanges.put(element, new SourceRange[] { sourceRange, nameRange });
- }
-
- /**
- * Return a char[][] array containing the imports of the attached source for the binary type
- */
- public char[][] getImports(BinaryType type) {
- char[][] imports = (char[][]) this.importsTable.get(type);
- if (imports != null) {
- int importsCounter = ((Integer) this.importsCounterTable.get(type)).intValue();
- if (imports.length != importsCounter) {
- System.arraycopy(
- imports,
- 0,
- (imports = new char[importsCounter][]),
- 0,
- importsCounter);
- }
- this.importsTable.put(type, imports);
- }
- return imports;
- }
-
- private boolean hasToRetrieveSourceRangesForLocalClass(char[] eltName) {
- /*
- * A$1$B$2 : true
- * A$B$B$2 : true
- * A$C$B$D : false
- * A$F$B$D$1$F : true
- * A$F$B$D$1F : true
- * A$1 : true
- * A$B : false
- */
- if (eltName == null) return false;
- int length = eltName.length;
- int dollarIndex = CharOperation.indexOf('$', eltName, 0);
- while (dollarIndex != -1) {
- int nameStart = dollarIndex+1;
- if (nameStart == length) return false;
- if (Character.isDigit(eltName[nameStart]))
- return true;
- dollarIndex = CharOperation.indexOf('$', eltName, nameStart);
- }
- return false;
- }
-
-}
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
deleted file mode 100644
index 4d6dafc4..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceMethod.java
+++ /dev/null
@@ -1,277 +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;
-
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IFunction;
-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.Signature;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Binding;
-
-/**
- * @see IFunction
- */
-
-public class SourceMethod extends NamedMember implements IFunction {
-
- /**
- * The parameter type signatures of the method - stored locally
- * to perform equality test. <code>null</code> indicates no
- * parameters.
- */
- protected String[] parameterTypes;
-
-protected SourceMethod(JavaElement parent, String name, String[] parameterTypes) {
- super(parent, name);
- // Assertion disabled since bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=179011
- // Assert.isTrue(name.indexOf('.') == -1);
- if (parameterTypes == null) {
- this.parameterTypes= CharOperation.NO_STRINGS;
- } else {
- this.parameterTypes= parameterTypes;
- }
-}
-public boolean equals(Object o) {
- if (!(o instanceof SourceMethod)) return false;
- return super.equals(o);// && Util.equalArraysOrNull(this.parameterTypes, ((SourceMethod)o).parameterTypes);
-}
-/**
- * @see IJavaScriptElement
- */
-public int getElementType() {
- return METHOD;
-}
-/**
- * @see JavaElement#getHandleMemento(StringBuffer)
- */
-protected void getHandleMemento(StringBuffer buff) {
- ((JavaElement) getParent()).getHandleMemento(buff);
- char delimiter = getHandleMementoDelimiter();
- buff.append(delimiter);
- escapeMementoName(buff, getElementName());
-// for (int i = 0; i < this.parameterTypes.length; i++) {
-// buff.append(delimiter);
-// escapeMementoName(buff, this.parameterTypes[i]);
-// }
- if (this.occurrenceCount > 1) {
- buff.append(JEM_COUNT);
- buff.append(this.occurrenceCount);
- }
-}
-/**
- * @see JavaElement#getHandleMemento()
- */
-protected char getHandleMementoDelimiter() {
- return JavaElement.JEM_METHOD;
-}
-/* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.IFunction#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 IFunction
- */
-public int getNumberOfParameters() {
- return this.parameterTypes == null ? 0 : this.parameterTypes.length;
-}
-/**
- * @see IFunction
- */
-public String[] getParameterNames() throws JavaScriptModelException {
- SourceMethodElementInfo info = (SourceMethodElementInfo) getElementInfo();
- char[][] names= info.getArgumentNames();
- return CharOperation.toStrings(names);
-}
-/**
- * @see IFunction
- */
-public String[] getParameterTypes() {
- return this.parameterTypes;
-}
-
-/*
- * @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);
- if (primaryParent instanceof IType)
- return ((IType)primaryParent).getFunction(this.name, this.parameterTypes);
- return ((IJavaScriptUnit)primaryParent).getFunction(this.name, this.parameterTypes);
-}
-public String[] getRawParameterNames() throws JavaScriptModelException {
- return getParameterNames();
-}
-/**
- * @see IFunction
- */
-public String getReturnType() throws JavaScriptModelException {
- SourceMethodElementInfo info = (SourceMethodElementInfo) getElementInfo();
- return Signature.createTypeSignature(info.getReturnTypeName(), false) ;
-}
-/**
- * @see IFunction
- */
-public String getSignature() throws JavaScriptModelException {
- SourceMethodElementInfo info = (SourceMethodElementInfo) getElementInfo();
- return Signature.createMethodSignature(this.parameterTypes, Signature.createTypeSignature(info.getReturnTypeName(), false));
-}
-/**
- * @see org.eclipse.wst.jsdt.internal.core.JavaElement#hashCode()
- */
-public int hashCode() {
- int hash = super.hashCode();
-// for (int i = 0, length = this.parameterTypes.length; i < length; i++) {
-// int hashCode = (this.parameterTypes[i]!=null) ? this.parameterTypes[i].hashCode() : "".hashCode();
-// hash = Util.combineHashCodes(hash, hashCode);
-// }
- return hash;
-}
-/**
- * @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();
-}
-/**
- * @see IFunction#isMainMethod()
- */
-public boolean isMainMethod() throws JavaScriptModelException {
- return this.isMainMethod(this);
-}
-/* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.IFunction#isResolved()
- */
-public boolean isResolved() {
- return false;
-}
-/**
- * @see IFunction#isSimilar(IFunction)
- */
-public boolean isSimilar(IFunction method) {
- return
- areSimilarMethods(
- this.getElementName(), this.getParameterTypes(),
- method.getElementName(), method.getParameterTypes(),
- null);
-}
-
-/**
- */
-public String readableName() {
-
- StringBuffer buffer = new StringBuffer(super.readableName());
- buffer.append('(');
- int length;
- if (this.parameterTypes != null && (length = this.parameterTypes.length) > 0) {
- for (int i = 0; i < length; i++) {
- buffer.append(Signature.toString(this.parameterTypes[i]));
- if (i < length - 1) {
- buffer.append(", "); //$NON-NLS-1$
- }
- }
- }
- buffer.append(')');
- return buffer.toString();
-}
-public JavaElement resolved(Binding binding) {
- SourceRefElement resolvedHandle = new ResolvedSourceMethod(this.parent, this.name, this.parameterTypes, new String(binding.computeUniqueKey()));
- resolvedHandle.occurrenceCount = this.occurrenceCount;
- return resolvedHandle;
-}
-/**
- * @private Debugging purposes
- */
-protected void toStringInfo(int tab, StringBuffer buffer, Object info, boolean showResolvedInfo) {
- buffer.append(tabString(tab));
- if (info == null) {
- toStringName(buffer);
- buffer.append(" (not open)"); //$NON-NLS-1$
- } else if (info == NO_INFO) {
- toStringName(buffer);
- } else {
- SourceMethodElementInfo methodInfo = (SourceMethodElementInfo) info;
- int flags = methodInfo.getModifiers();
- if (Flags.isStatic(flags)) {
- buffer.append("static "); //$NON-NLS-1$
- }
- if (!methodInfo.isConstructor()) {
-// buffer.append(methodInfo.getReturnTypeName());
- buffer.append("function "); //$NON-NLS-1$
- }
- toStringName(buffer, flags);
- }
-}
-protected void toStringName(StringBuffer buffer) {
- toStringName(buffer, 0);
-}
-protected void toStringName(StringBuffer buffer, int flags) {
- buffer.append(getElementName());
- buffer.append('(');
- String[] parameters = getParameterTypes();
- int length;
- if (parameters != null && (length = parameters.length) > 0) {
- boolean isVarargs = Flags.isVarargs(flags);
- for (int i = 0; i < length; i++) {
- try {
- if (i < length - 1) {
-// buffer.append(Signature.toString(parameters[i]));
- buffer.append("p"+i); //$NON-NLS-1$
- buffer.append(", "); //$NON-NLS-1$
- } else if (isVarargs) {
- // remove array from signature
- String parameter = parameters[i].substring(1);
- buffer.append(Signature.toString(parameter));
- buffer.append(" ..."); //$NON-NLS-1$
- } else {
-// buffer.append(Signature.toString(parameters[i]));
- buffer.append("p"+i); //$NON-NLS-1$
- }
- } catch (IllegalArgumentException e) {
- // parameter signature is malformed
- buffer.append("*** invalid signature: "); //$NON-NLS-1$
- buffer.append(parameters[i]);
- }
- }
- }
- buffer.append(')');
- if (this.occurrenceCount > 1) {
- buffer.append("#"); //$NON-NLS-1$
- buffer.append(this.occurrenceCount);
- }
-}
-
-public IFunction getFunction(String selector, String[] parameterTypeSignatures)
-{
- return new SourceMethod(this, selector, parameterTypeSignatures);
-
-}
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceMethodElementInfo.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceMethodElementInfo.java
deleted file mode 100644
index 0ee8d627..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceMethodElementInfo.java
+++ /dev/null
@@ -1,53 +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;
-
-import org.eclipse.wst.jsdt.internal.compiler.env.ISourceMethod;
-
-/**
- * Element info for IFunction elements.
- */
-public abstract class SourceMethodElementInfo extends MemberElementInfo implements ISourceMethod {
-
- /**
- * For a source method (that is, a method contained in a compilation unit)
- * this is a collection of the names of the parameters for this method,
- * in the order the parameters are delcared. For a binary method (that is,
- * a method declared in a binary type), these names are invented as
- * "arg"i where i starts at 1. This is an empty array if this method
- * has no parameters.
- */
- protected char[][] argumentNames;
-
- /**
- * Return type name for this method.
- */
- protected char[] returnType;
-
-
- public char[][] getArgumentNames() {
- return this.argumentNames;
- }
-
- protected void setArgumentNames(char[][] names) {
- this.argumentNames = names;
- }
-
- public char[] getReturnTypeName() {
- return this.returnType;
- }
-
- protected void setReturnType(char[] type) {
- this.returnType = type;
- }
-
- public abstract boolean isConstructor();
-} \ No newline at end of file
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
deleted file mode 100644
index 24fd34df..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceMethodInfo.java
+++ /dev/null
@@ -1,20 +0,0 @@
-/*******************************************************************************
- * 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
- * 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 method from source.
- */
-public class SourceMethodInfo extends SourceMethodElementInfo {
- public boolean isConstructor() {
- return false;
- }
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceRange.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceRange.java
deleted file mode 100644
index be3113dc..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceRange.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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.core.ISourceRange;
-
-/**
- * @see ISourceRange
- */
-public class SourceRange implements ISourceRange {
-
-protected int offset, length;
-
-public SourceRange(int offset, int length) {
- this.offset = offset;
- this.length = length;
-}
-/*
- * @see Object#equals(Object)
- */
-public boolean equals(Object obj) {
- if (!(obj instanceof ISourceRange))
- return false;
- ISourceRange sourceRange = (ISourceRange) obj;
- return sourceRange.getOffset() == this.offset && sourceRange.getLength() == this.length;
-}
-/**
- * @see ISourceRange
- */
-public int getLength() {
- return this.length;
-}
-/**
- * @see ISourceRange
- */
-public int getOffset() {
- return this.offset;
-}
-/*
- * @see Object#hashCode()
- */
-public int hashCode() {
- return this.length ^ this.offset;
-}
-public String toString() {
- StringBuffer buffer = new StringBuffer();
- buffer.append("[offset="); //$NON-NLS-1$
- buffer.append(this.offset);
- buffer.append(", length="); //$NON-NLS-1$
- buffer.append(this.length);
- buffer.append("]"); //$NON-NLS-1$
- return buffer.toString();
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceRefElement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceRefElement.java
deleted file mode 100644
index dd13019d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceRefElement.java
+++ /dev/null
@@ -1,293 +0,0 @@
-/*******************************************************************************
- * 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 java.util.HashMap;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.wst.jsdt.core.IBuffer;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatusConstants;
-import org.eclipse.wst.jsdt.core.IOpenable;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.core.util.DOMFinder;
-import org.eclipse.wst.jsdt.internal.core.util.MementoTokenizer;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-
-/**
- * Abstract class for Java elements which implement ISourceReference.
- */
-public abstract class SourceRefElement extends JavaElement implements ISourceReference {
- /*
- * A count to uniquely identify this element in the case
- * that a duplicate named element exists. For example, if
- * there are two fields in a compilation unit with the
- * same name, the occurrence count is used to distinguish
- * them. The occurrence count starts at 1 (thus the first
- * occurrence is occurrence 1, not occurrence 0).
- */
- public int occurrenceCount = 1;
-
-protected SourceRefElement(JavaElement parent) {
- super(parent);
-}
-/**
- * This element is being closed. Do any necessary cleanup.
- */
-protected void closing(Object info) throws JavaScriptModelException {
- // Do any necessary cleanup
-}
-/**
- * Returns a new element info for this element.
- */
-protected Object createElementInfo() {
- return null; // not used for source ref elements
-}
-/**
- * @see org.eclipse.wst.jsdt.core.ISourceManipulation
- */
-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};
- IJavaScriptElement[] siblings= null;
- if (sibling != null) {
- siblings= new IJavaScriptElement[] {sibling};
- }
- String[] renamings= null;
- if (rename != null) {
- renamings= new String[] {rename};
- }
- getJavaScriptModel().copy(elements, containers, siblings, renamings, force, monitor);
-}
-/**
- * @see org.eclipse.wst.jsdt.core.ISourceManipulation
- */
-public void delete(boolean force, IProgressMonitor monitor) throws JavaScriptModelException {
- IJavaScriptElement[] elements = new IJavaScriptElement[] {this};
- getJavaScriptModel().delete(elements, force, monitor);
-}
-public boolean equals(Object o) {
- if (!(o instanceof SourceRefElement)) return false;
- return this.occurrenceCount == ((SourceRefElement)o).occurrenceCount &&
- super.equals(o);
-}
-/**
- * Returns the <code>ASTNode</code> that corresponds to this <code>JavaElement</code>
- * or <code>null</code> if there is no corresponding node.
- */
-public ASTNode findNode(JavaScriptUnit ast) {
- DOMFinder finder = new DOMFinder(ast, this, false);
- try {
- return finder.search();
- } catch (JavaScriptModelException e) {
- // receiver doesn't exist
- return null;
- }
-}
-/*
- * @see JavaElement#generateInfos
- */
-protected void generateInfos(Object info, HashMap newElements, IProgressMonitor pm) throws JavaScriptModelException {
- Openable openableParent = (Openable)getOpenableParent();
- if (openableParent == null) return;
-
- JavaElementInfo openableParentInfo = (JavaElementInfo) JavaModelManager.getJavaModelManager().getInfo(openableParent);
- if (openableParentInfo == null) {
- openableParent.generateInfos(openableParent.createElementInfo(), newElements, pm);
- }
-}
-/**
- * @see org.eclipse.wst.jsdt.core.IMember
- * @deprecated Use {@link #getJavaScriptUnit()} instead
- */
-public IJavaScriptUnit getCompilationUnit() {
- return getJavaScriptUnit();
-}
-/**
- * @see org.eclipse.wst.jsdt.core.IMember
- */
-public IJavaScriptUnit getJavaScriptUnit() {
- return (IJavaScriptUnit) getAncestor(JAVASCRIPT_UNIT);
-}
-/**
- * Elements within compilation units and class files have no
- * corresponding resource.
- *
- * @see IJavaScriptElement
- */
-public IResource getCorrespondingResource() throws JavaScriptModelException {
- if (!exists()) throw newNotPresentException();
- return null;
-}
-/*
- * @see JavaElement
- */
-public IJavaScriptElement getHandleFromMemento(String token, MementoTokenizer memento, WorkingCopyOwner workingCopyOwner) {
- switch (token.charAt(0)) {
- case JEM_COUNT:
- return getHandleUpdatingCountFromMemento(memento, workingCopyOwner);
- }
- return this;
-}
-protected void getHandleMemento(StringBuffer buff) {
- super.getHandleMemento(buff);
- if (this.occurrenceCount > 1) {
- buff.append(JEM_COUNT);
- buff.append(this.occurrenceCount);
- }
-}
-/*
- * Update the occurence count of the receiver and creates a Java element handle from the given memento.
- * The given working copy owner is used only for compilation unit handles.
- */
-public IJavaScriptElement getHandleUpdatingCountFromMemento(MementoTokenizer memento, WorkingCopyOwner owner) {
- if (!memento.hasMoreTokens()) return this;
- this.occurrenceCount = Integer.parseInt(memento.nextToken());
- if (!memento.hasMoreTokens()) return this;
- String token = memento.nextToken();
- return getHandleFromMemento(token, memento, owner);
-}
-/*
- * @see org.eclipse.wst.jsdt.core.IMember#getOccurrenceCount()
- */
-public int getOccurrenceCount() {
- return this.occurrenceCount;
-}
-/**
- * Return the first instance of IOpenable in the hierarchy of this
- * type (going up the hierarchy from this type);
- */
-public IOpenable getOpenableParent() {
- IJavaScriptElement current = getParent();
- while (current != null){
- if (current instanceof IOpenable){
- return (IOpenable) current;
- }
- current = current.getParent();
- }
- return null;
-}
-/*
- * @see IJavaScriptElement
- */
-public IPath getPath() {
- return this.getParent().getPath();
-}
-/*
- * @see IJavaScriptElement
- */
-public IResource getResource() {
- return this.getParent().getResource();
-}
-/**
- * @see ISourceReference
- */
-public String getSource() throws JavaScriptModelException {
- IOpenable openable = getOpenableParent();
- IBuffer buffer = openable.getBuffer();
- if (buffer == null) {
- return null;
- }
- ISourceRange range = getSourceRange();
- int offset = range.getOffset();
- int length = range.getLength();
- if (offset == -1 || length == 0 ) {
- return null;
- }
- try {
- return buffer.getText(offset, length);
- } catch(RuntimeException e) {
- return null;
- }
-}
-/**
- * @see ISourceReference
- */
-public ISourceRange getSourceRange() throws JavaScriptModelException {
- SourceRefElementInfo info = (SourceRefElementInfo) getElementInfo();
- return info.getSourceRange();
-}
-/**
- * @see IJavaScriptElement
- */
-public IResource getUnderlyingResource() throws JavaScriptModelException {
- if (!exists()) throw newNotPresentException();
- return getParent().getUnderlyingResource();
-}
-/**
- * @see org.eclipse.wst.jsdt.core.IParent
- */
-public boolean hasChildren() throws JavaScriptModelException {
- return getChildren().length > 0;
-}
-/**
- * @see IJavaScriptElement
- */
-public boolean isStructureKnown() throws JavaScriptModelException {
- // structure is always known inside an openable
- return true;
-}
-/**
- * @see org.eclipse.wst.jsdt.core.ISourceManipulation
- */
-public void move(IJavaScriptElement container, IJavaScriptElement sibling, String rename, boolean force, IProgressMonitor monitor) throws JavaScriptModelException {
- if (container == null) {
- throw new IllegalArgumentException(Messages.operation_nullContainer);
- }
- if (getClassFile()!=null)
- throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.READ_ONLY, this));
-
- IJavaScriptElement[] elements= new IJavaScriptElement[] {this};
- IJavaScriptElement[] containers= new IJavaScriptElement[] {container};
- IJavaScriptElement[] siblings= null;
- if (sibling != null) {
- siblings= new IJavaScriptElement[] {sibling};
- }
- String[] renamings= null;
- if (rename != null) {
- renamings= new String[] {rename};
- }
- getJavaScriptModel().move(elements, containers, siblings, renamings, force, monitor);
-}
-/**
- * @see org.eclipse.wst.jsdt.core.ISourceManipulation
- */
-public void rename(String newName, boolean force, IProgressMonitor monitor) throws JavaScriptModelException {
- if (newName == null) {
- throw new IllegalArgumentException(Messages.element_nullName);
- }
- if (getClassFile()!=null)
- throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.READ_ONLY, this));
-
- IJavaScriptElement[] elements= new IJavaScriptElement[] {this};
- IJavaScriptElement[] dests= new IJavaScriptElement[] {this.getParent()};
- String[] renamings= new String[] {newName};
- getJavaScriptModel().rename(elements, dests, renamings, force, monitor);
-}
-protected void toStringName(StringBuffer buffer) {
- super.toStringName(buffer);
- if (this.occurrenceCount > 1) {
- buffer.append("#"); //$NON-NLS-1$
- buffer.append(this.occurrenceCount);
- }
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceRefElementInfo.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceRefElementInfo.java
deleted file mode 100644
index 50db031f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceRefElementInfo.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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.core.ISourceRange;
-
-/**
- * Element info for ISourceReference elements.
- */
-/* package */ class SourceRefElementInfo extends JavaElementInfo {
- protected int fSourceRangeStart, fSourceRangeEnd;
-/**
- * @see org.eclipse.wst.jsdt.internal.compiler.env.ISourceType#getDeclarationSourceEnd()
- * @see org.eclipse.wst.jsdt.internal.compiler.env.ISourceMethod#getDeclarationSourceEnd()
- * @see org.eclipse.wst.jsdt.internal.compiler.env.ISourceField#getDeclarationSourceEnd()
- */
-public int getDeclarationSourceEnd() {
- return fSourceRangeEnd;
-}
-/**
- * @see org.eclipse.wst.jsdt.internal.compiler.env.ISourceType#getDeclarationSourceStart()
- * @see org.eclipse.wst.jsdt.internal.compiler.env.ISourceMethod#getDeclarationSourceStart()
- * @see org.eclipse.wst.jsdt.internal.compiler.env.ISourceField#getDeclarationSourceStart()
- */
-public int getDeclarationSourceStart() {
- return fSourceRangeStart;
-}
-protected ISourceRange getSourceRange() {
- return new SourceRange(fSourceRangeStart, fSourceRangeEnd - fSourceRangeStart + 1);
-}
-protected void setSourceRangeEnd(int end) {
- fSourceRangeEnd = end;
-}
-protected void setSourceRangeStart(int start) {
- fSourceRangeStart = start;
-}
-}
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
deleted file mode 100644
index 50b00db2..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceType.java
+++ /dev/null
@@ -1,747 +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;
-
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.HashMap;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.wst.jsdt.core.CompletionRequestor;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IInitializer;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-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.CategorizedProblem;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.internal.codeassist.CompletionEngine;
-import org.eclipse.wst.jsdt.internal.codeassist.ISelectionRequestor;
-import org.eclipse.wst.jsdt.internal.codeassist.SelectionEngine;
-import org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.env.ISourceType;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Binding;
-import org.eclipse.wst.jsdt.internal.core.hierarchy.TypeHierarchy;
-import org.eclipse.wst.jsdt.internal.core.util.MementoTokenizer;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-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$
- }
-
- JavaProject project = (JavaProject) getJavaScriptProject();
- SearchableEnvironment environment = newSearchableNameEnvironment(owner);
- CompletionEngine engine = new CompletionEngine(environment, requestor, project.getOptions(true), project);
-
- String source = getJavaScriptUnit().getSource();
- if (source != null && insertion > -1 && insertion < source.length()) {
-
- 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);
-
- 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$
- }
-}
-/**
- * @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 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];
-}
-/**
- * @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];
-}
-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;
- }
-}
-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;
-}
-/**
- * @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)) {
- 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:
- 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$
- } else {
- 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);
- }
-
- }
- 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;
- }
- 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 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);
-}
-
-/**
- * @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;
- }
-}
-/**
- * @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:
- * <p>
- * 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:
- * <ul>
- * <li>IType#newSupertypeHierarchy(IProgressMonitor)</li>
- * <li>IType#newSupertypeHierarchy(WorkingCopyOwner, IProgressMonitor)</li>
- * <li>IType#newTypeHierarchy(IJavaScriptProject, IProgressMonitor)</li>
- * <li>IType#newTypeHierarchy(IJavaScriptProject, WorkingCopyOwner, IProgressMonitor)</li>
- * <li>IType#newTypeHierarchy(IProgressMonitor)</li>
- * <li>IType#newTypeHierarchy(WorkingCopyOwner, IProgressMonitor)</li>
- * </u>
- *
- * @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;
- }
- }
- 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();
-}
-/*
- * @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;
- }
- }
- 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();
-}
-/**
- * @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("<anonymous #"); //$NON-NLS-1$
- buffer.append(this.occurrenceCount);
- 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("<anonymous #"); //$NON-NLS-1$
- buffer.append(this.occurrenceCount);
- buffer.append(">"); //$NON-NLS-1$
- } else {
- toStringName(buffer);
- }
- } else {
- buffer.append("class "); //$NON-NLS-1$
-
- String elementName = getElementName();
- if (elementName.length() == 0) {
- buffer.append("<anonymous #"); //$NON-NLS-1$
- buffer.append(this.occurrenceCount);
- 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
deleted file mode 100644
index 86742655..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceTypeElementInfo.java
+++ /dev/null
@@ -1,305 +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;
-
-import java.util.HashMap;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-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.internal.compiler.env.ISourceField;
-import org.eclipse.wst.jsdt.internal.compiler.env.ISourceImport;
-import org.eclipse.wst.jsdt.internal.compiler.env.ISourceMethod;
-import org.eclipse.wst.jsdt.internal.compiler.env.ISourceType;
-
-/**
- * Element info for an IType element that originated from source.
- */
-public class SourceTypeElementInfo extends MemberElementInfo implements ISourceType {
-
- protected static final ISourceImport[] NO_IMPORTS = new ISourceImport[0];
- protected static final InitializerElementInfo[] NO_INITIALIZERS = new InitializerElementInfo[0];
- protected static final SourceField[] NO_FIELDS = new SourceField[0];
- protected static final SourceMethod[] NO_METHODS = new SourceMethod[0];
- protected static final SourceType[] NO_TYPES = new SourceType[0];
- /**
- * The name of the superclass for this type. This name
- * is fully qualified for binary types and is NOT
- * fully qualified for source types.
- */
- protected char[] superclassName;
-
- /**
- * The names of the interfaces this type implements or
- * extends. These names are fully qualified in the case
- * of a binary type, and are NOT fully qualified in the
- * case of a source type
- */
- protected char[][] superInterfaceNames;
-
- /**
- * Backpointer to my type handle - useful for translation
- * from info to handle.
- */
- protected IType handle = null;
-
- /*
- * A map from an IJavaScriptElement (this type or a child of this type) to a String[] (the categories of this element)
- */
- protected HashMap categories;
-
- protected boolean isBinary;
-
- protected boolean isAnonymous;
-
- public SourceTypeElementInfo(boolean isBinary,boolean anonymous) {
- super();
- this.isBinary=isBinary;
- this.isAnonymous=anonymous;
- }
-
- public SourceTypeElementInfo(boolean isBinary) {
- this(isBinary,false);
- }
-
-protected void addCategories(IJavaScriptElement element, char[][] elementCategories) {
- if (elementCategories == null) return;
- if (this.categories == null)
- this.categories = new HashMap();
- this.categories.put(element, CharOperation.toStrings(elementCategories));
-}
-
-/*
- * Return a map from an IJavaScriptElement (this type or a child of this type) to a String[] (the categories of this element)
- */
-public HashMap getCategories() {
- return this.categories;
-}
-
-/**
- * Returns the ISourceType that is the enclosing type for this
- * type, or <code>null</code> if this type is a top level type.
- */
-public ISourceType getEnclosingType() {
- IJavaScriptElement parent= this.handle.getParent();
- if (parent != null && parent.getElementType() == IJavaScriptElement.TYPE) {
- try {
- return (ISourceType)((JavaElement)parent).getElementInfo();
- } catch (JavaScriptModelException e) {
- return null;
- }
- } else {
- return null;
- }
-}
-/**
- * @see ISourceType
- */
-public ISourceField[] getFields() {
- SourceField[] fieldHandles = getFieldHandles();
- int length = fieldHandles.length;
- ISourceField[] fields = new ISourceField[length];
- for (int i = 0; i < length; i++) {
- try {
- ISourceField field = (ISourceField) fieldHandles[i].getElementInfo();
- fields[i] = field;
- } catch (JavaScriptModelException e) {
- // ignore
- }
- }
- return fields;
-}
-public SourceField[] getFieldHandles() {
- int length = this.children.length;
- if (length == 0) return NO_FIELDS;
- SourceField[] fields = new SourceField[length];
- int fieldIndex = 0;
- for (int i = 0; i < length; i++) {
- IJavaScriptElement child = this.children[i];
- if (child instanceof SourceField)
- fields[fieldIndex++] = (SourceField) child;
- }
- if (fieldIndex == 0) return NO_FIELDS;
- if (fieldIndex < length)
- System.arraycopy(fields, 0, fields = new SourceField[fieldIndex], 0, fieldIndex);
- return fields;
-}
-/**
- * @see org.eclipse.wst.jsdt.internal.compiler.env.IDependent#getFileName()
- */
-public char[] getFileName() {
- return this.handle.getPath().toString().toCharArray();
-}
-/**
- * Returns the handle for this type info
- */
-public IType getHandle() {
- return this.handle;
-}
-/*
- * Returns the InitializerElementInfos for this type.
- * Returns an empty array if none.
- */
-public InitializerElementInfo[] getInitializers() {
- int length = this.children.length;
- if (length == 0) return NO_INITIALIZERS;
- InitializerElementInfo[] initializers = new InitializerElementInfo[length];
- int initializerIndex = 0;
- for (int i = 0; i < length; i++) {
- IJavaScriptElement child = this.children[i];
- if (child instanceof Initializer) {
- try {
- InitializerElementInfo initializer = (InitializerElementInfo)((Initializer)child).getElementInfo();
- initializers[initializerIndex++] = initializer;
- } catch (JavaScriptModelException e) {
- // ignore
- }
- }
- }
- if (initializerIndex == 0) return NO_INITIALIZERS;
- System.arraycopy(initializers, 0, initializers = new InitializerElementInfo[initializerIndex], 0, initializerIndex);
- return initializers;
-}
-/**
- * @see ISourceType
- */
-public char[][] getInterfaceNames() {
- if (this.handle.getElementName().length() == 0) { // if anonymous type
- return null;
- }
- return this.superInterfaceNames;
-}
-
-/**
- * @see ISourceType
- */
-public ISourceType[] getMemberTypes() {
- SourceType[] memberTypeHandles = getMemberTypeHandles();
- int length = memberTypeHandles.length;
- ISourceType[] memberTypes = new ISourceType[length];
- for (int i = 0; i < length; i++) {
- try {
- ISourceType type = (ISourceType) memberTypeHandles[i].getElementInfo();
- memberTypes[i] = type;
- } catch (JavaScriptModelException e) {
- // ignore
- }
- }
- return memberTypes;
-}
-public SourceType[] getMemberTypeHandles() {
- int length = this.children.length;
- if (length == 0) return NO_TYPES;
- SourceType[] memberTypes = new SourceType[length];
- int typeIndex = 0;
- for (int i = 0; i < length; i++) {
- IJavaScriptElement child = this.children[i];
- if (child instanceof SourceType)
- memberTypes[typeIndex++] = (SourceType)child;
- }
- if (typeIndex == 0) return NO_TYPES;
- if (typeIndex < length)
- System.arraycopy(memberTypes, 0, memberTypes = new SourceType[typeIndex], 0, typeIndex);
- return memberTypes;
-}
-/**
- * @see ISourceType
- */
-public ISourceMethod[] getMethods() {
- SourceMethod[] methodHandles = getMethodHandles();
- int length = methodHandles.length;
- ISourceMethod[] methods = new ISourceMethod[length];
- int methodIndex = 0;
- for (int i = 0; i < length; i++) {
- try {
- ISourceMethod method = (ISourceMethod) methodHandles[i].getElementInfo();
- methods[methodIndex++] = method;
- } catch (JavaScriptModelException e) {
- // ignore
- }
- }
- return methods;
-}
-public SourceMethod[] getMethodHandles() {
- int length = this.children.length;
- if (length == 0) return NO_METHODS;
- SourceMethod[] methods = new SourceMethod[length];
- int methodIndex = 0;
- for (int i = 0; i < length; i++) {
- IJavaScriptElement child = this.children[i];
- if (child instanceof SourceMethod)
- methods[methodIndex++] = (SourceMethod) child;
- }
- if (methodIndex == 0) return NO_METHODS;
- if (methodIndex < length)
- System.arraycopy(methods, 0, methods = new SourceMethod[methodIndex], 0, methodIndex);
- return methods;
-}
-/**
- * @see org.eclipse.wst.jsdt.internal.compiler.env.ISourceType#getName()
- */
-public char[] getName() {
- return this.handle.getElementName().toCharArray();
-}
-/**
- * @see ISourceType
- */
-public char[] getSuperclassName() {
- if (this.handle.getElementName().length() == 0) { // if anonymous type
- char[][] interfaceNames = this.superInterfaceNames;
- if (interfaceNames != null && interfaceNames.length > 0) {
- return interfaceNames[0];
- }
- }
- return this.superclassName;
-}
-/**
- * @see ISourceType
- */
-public boolean isBinaryType() {
- return isBinary;
-}
-/*
- * Returns whether the source type is an anonymous type of a member type.
- */
-public boolean isAnonymousMember() {
- return isAnonymous;
-}
-/**
- * Sets the handle for this type info
- */
-protected void setHandle(IType handle) {
- this.handle = handle;
-}
-/**
- * Sets the (unqualified) name of this type's superclass
- */
-protected void setSuperclassName(char[] superclassName) {
- this.superclassName = superclassName;
-}
-/**
- * Sets the (unqualified) names of the interfaces this type implements or extends
- */
-protected void setSuperInterfaceNames(char[][] superInterfaceNames) {
- this.superInterfaceNames = superInterfaceNames;
-}
-public String toString() {
- return "Info for " + this.handle.toString(); //$NON-NLS-1$
-}
-
-public char[][] getPackageName() {
- ISourceType enclosingType = getEnclosingType();
- if (enclosingType!=null)
- return enclosingType.getPackageName();
- return new char[0][];
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/TypeVector.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/TypeVector.java
deleted file mode 100644
index 26374441..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/TypeVector.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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.core.IType;
-
-public final class TypeVector {
- static int INITIAL_SIZE = 10;
-
- public int size;
- int maxSize;
- IType[] elements;
-
- public final static IType[] NoElements = new IType[0];
-
-public TypeVector() {
- maxSize = INITIAL_SIZE;
- size = 0;
- elements = new IType[maxSize];
-}
-public TypeVector(IType[] types) {
- this.size = types.length;
- this.maxSize = this.size + 1; // when an element is added, it assumes that the length is > 0
- elements = new IType[this.maxSize];
- System.arraycopy(types, 0, elements, 0, this.size);
-}
-public TypeVector(IType type) {
- this.maxSize = INITIAL_SIZE;
- this.size = 1;
- elements = new IType[this.maxSize];
- elements[0] = type;
-}
-public void add(IType newElement) {
- if (size == maxSize) // knows that size starts <= maxSize
- System.arraycopy(elements, 0, (elements = new IType[maxSize *= 2]), 0, size);
- elements[size++] = newElement;
-}
-public void addAll(IType[] newElements) {
- if (size + newElements.length >= maxSize) {
- maxSize = size + newElements.length; // assume no more elements will be added
- System.arraycopy(elements, 0, (elements = new IType[maxSize]), 0, size);
- }
- System.arraycopy(newElements, 0, elements, size, newElements.length);
- size += newElements.length;
-}
-public boolean contains(IType element) {
- for (int i = size; --i >= 0;)
- if (element.equals(elements[i]))
- return true;
- return false;
-}
-public TypeVector copy() {
- TypeVector clone = new TypeVector();
- int length = this.elements.length;
- System.arraycopy(this.elements, 0, clone.elements = new IType[length], 0, length);
- clone.size = this.size;
- clone.maxSize = this.maxSize;
- return clone;
-}
-public IType elementAt(int index) {
- return elements[index];
-}
-public IType[] elements() {
-
- // do not resize to 0 if empty since may add more elements later
- if (this.size == 0) return NoElements;
-
- if (this.size < this.maxSize) {
- maxSize = size;
- System.arraycopy(this.elements, 0, (this.elements = new IType[maxSize]), 0, size);
- }
- return this.elements;
-}
-public IType find(IType element) {
- for (int i = size; --i >= 0;)
- if (element == elements[i])
- return elements[i];
- return null;
-}
-public IType remove(IType element) {
- // assumes only one occurrence of the element exists
- for (int i = size; --i >= 0;)
- if (element == elements[i]) {
- // shift the remaining elements down one spot
- System.arraycopy(elements, i + 1, elements, i, --size - i);
- elements[size] = null;
- return element;
- }
- return null;
-}
-public void removeAll() {
- for (int i = size; --i >= 0;)
- elements[i] = null;
- size = 0;
-}
-public String toString() {
- StringBuffer buffer = new StringBuffer("["); //$NON-NLS-1$
- for (int i = 0; i < size; i++) {
- buffer.append("\n"); //$NON-NLS-1$
- buffer.append(elements[i]);
- }
- buffer.append("\n]"); //$NON-NLS-1$
- return buffer.toString();
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/UserLibrary.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/UserLibrary.java
deleted file mode 100644
index e40a9039..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/UserLibrary.java
+++ /dev/null
@@ -1,210 +0,0 @@
-/*******************************************************************************
- * 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 java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.OutputStreamWriter;
-import java.io.Reader;
-import java.util.ArrayList;
-import java.util.HashMap;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-
-import org.eclipse.core.runtime.Assert;
-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.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-
-/**
- * Internal model element to represent a user library and code to serialize / deserialize.
- */
-public class UserLibrary {
-
- private static final String CURRENT_VERSION= "1"; //$NON-NLS-1$
-
- private static final String TAG_VERSION= "version"; //$NON-NLS-1$
- private static final String TAG_USERLIBRARY= "userlibrary"; //$NON-NLS-1$
- private static final String TAG_SOURCEATTACHMENT= "sourceattachment"; //$NON-NLS-1$
- private static final String TAG_SOURCEATTACHMENTROOT= "sourceattachmentroot"; //$NON-NLS-1$
- private static final String TAG_PATH= "path"; //$NON-NLS-1$
- private static final String TAG_ARCHIVE= "archive"; //$NON-NLS-1$
- private static final String TAG_SYSTEMLIBRARY= "systemlibrary"; //$NON-NLS-1$
-
- private boolean isSystemLibrary;
- private IIncludePathEntry[] entries;
-
- public UserLibrary(IIncludePathEntry[] entries, boolean isSystemLibrary) {
- Assert.isNotNull(entries);
- this.entries= entries;
- this.isSystemLibrary= isSystemLibrary;
- }
-
- public IIncludePathEntry[] getEntries() {
- return this.entries;
- }
-
- public boolean isSystemLibrary() {
- return this.isSystemLibrary;
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public boolean equals(Object obj) {
- if (obj != null && obj.getClass() == getClass()) {
- UserLibrary other= (UserLibrary) obj;
- if (this.entries.length == other.entries.length && this.isSystemLibrary == other.isSystemLibrary) {
- for (int i= 0; i < this.entries.length; i++) {
- if (!this.entries[i].equals(other.entries[i])) {
- return false;
- }
- }
- return true;
- }
- }
- return false;
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#hashCode()
- */
- public int hashCode() {
- int hashCode= 0;
- if (this.isSystemLibrary) {
- hashCode++;
- }
- for (int i= 0; i < this.entries.length; i++) {
- hashCode= hashCode * 17 + this.entries.hashCode();
- }
- return hashCode;
- }
-
- /* package */ String serialize() throws IOException {
- ByteArrayOutputStream s = new ByteArrayOutputStream();
- OutputStreamWriter writer = new OutputStreamWriter(s, "UTF8"); //$NON-NLS-1$
- XMLWriter xmlWriter = new XMLWriter(writer, null/*use the workspace line delimiter*/, true/*print XML version*/);
-
- HashMap library = new HashMap();
- library.put(TAG_VERSION, String.valueOf(CURRENT_VERSION));
- library.put(TAG_SYSTEMLIBRARY, String.valueOf(this.isSystemLibrary));
- xmlWriter.printTag(TAG_USERLIBRARY, library, true, true, false);
-
- for (int i = 0; i < this.entries.length; ++i) {
- ClasspathEntry cpEntry = (ClasspathEntry) this.entries[i];
-
- HashMap archive = new HashMap();
- archive.put(TAG_PATH, cpEntry.getPath().toString());
- IPath sourceAttach= cpEntry.getSourceAttachmentPath();
- if (sourceAttach != null)
- archive.put(TAG_SOURCEATTACHMENT, sourceAttach);
- IPath sourceAttachRoot= cpEntry.getSourceAttachmentRootPath();
- if (sourceAttachRoot != null)
- archive.put(TAG_SOURCEATTACHMENTROOT, sourceAttachRoot);
-
- boolean hasExtraAttributes = cpEntry.extraAttributes != null && cpEntry.extraAttributes.length != 0;
- boolean hasRestrictions = cpEntry.getAccessRuleSet() != null; // access rule set is null if no access rules
- xmlWriter.printTag(TAG_ARCHIVE, archive, true, true, !(hasExtraAttributes || hasRestrictions));
-
- // write extra attributes if necessary
- if (hasExtraAttributes) {
- cpEntry.encodeExtraAttributes(xmlWriter, true, true);
- }
-
- // write extra attributes and restriction if necessary
- if (hasRestrictions) {
- cpEntry.encodeAccessRules(xmlWriter, true, true);
- }
-
- // write archive end tag if necessary
- if (hasExtraAttributes || hasRestrictions) {
- xmlWriter.endTag(TAG_ARCHIVE, true/*insert tab*/, true/*insert new line*/);
- }
- }
- xmlWriter.endTag(TAG_USERLIBRARY, true/*insert tab*/, true/*insert new line*/);
- writer.flush();
- writer.close();
- return s.toString("UTF8");//$NON-NLS-1$
- }
-
- /* package */ static UserLibrary createFromString(Reader reader) throws IOException {
- Element cpElement;
- try {
- DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
- cpElement = parser.parse(new InputSource(reader)).getDocumentElement();
- } catch (SAXException e) {
- throw new IOException(Messages.file_badFormat);
- } catch (ParserConfigurationException e) {
- throw new IOException(Messages.file_badFormat);
- } finally {
- reader.close();
- }
-
- if (!cpElement.getNodeName().equalsIgnoreCase(TAG_USERLIBRARY)) {
- throw new IOException(Messages.file_badFormat);
- }
- // String version= cpElement.getAttribute(TAG_VERSION);
- // in case we update the format: add code to read older versions
-
- boolean isSystem= Boolean.valueOf(cpElement.getAttribute(TAG_SYSTEMLIBRARY)).booleanValue();
-
- NodeList list= cpElement.getChildNodes();
- int length = list.getLength();
-
- ArrayList res= new ArrayList(length);
- for (int i = 0; i < length; ++i) {
- Node node = list.item(i);
-
- if (node.getNodeType() == Node.ELEMENT_NODE) {
- Element element= (Element) node;
- if (element.getNodeName().equals(TAG_ARCHIVE)) {
- String path = element.getAttribute(TAG_PATH);
- IPath sourceAttach= element.hasAttribute(TAG_SOURCEATTACHMENT) ? new Path(element.getAttribute(TAG_SOURCEATTACHMENT)) : null;
- IPath sourceAttachRoot= element.hasAttribute(TAG_SOURCEATTACHMENTROOT) ? new Path(element.getAttribute(TAG_SOURCEATTACHMENTROOT)) : null;
- NodeList children = element.getElementsByTagName("*"); //$NON-NLS-1$
- boolean[] foundChildren = new boolean[children.getLength()];
- NodeList attributeList = ClasspathEntry.getChildAttributes(ClasspathEntry.TAG_ATTRIBUTES, children, foundChildren);
- IIncludePathAttribute[] extraAttributes = ClasspathEntry.decodeExtraAttributes(attributeList);
- attributeList = ClasspathEntry.getChildAttributes(ClasspathEntry.TAG_ACCESS_RULES, children, foundChildren);
- IAccessRule[] accessRules = ClasspathEntry.decodeAccessRules(attributeList);
- IIncludePathEntry entry = JavaScriptCore.newLibraryEntry(new Path(path), sourceAttach, sourceAttachRoot, accessRules, extraAttributes, false/*not exported*/);
- res.add(entry);
- }
- }
- }
-
- IIncludePathEntry[] entries= (IIncludePathEntry[]) res.toArray(new IIncludePathEntry[res.size()]);
-
- return new UserLibrary(entries, isSystem);
- }
-
- public String toString() {
- if (this.entries == null)
- return "null"; //$NON-NLS-1$
- StringBuffer buffer = new StringBuffer();
- int length = this.entries.length;
- for (int i=0; i<length; i++) {
- buffer.append(this.entries[i].toString()+'\n');
- }
- return buffer.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/UserLibraryJsGlobalScopeContainer.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/UserLibraryJsGlobalScopeContainer.java
deleted file mode 100644
index 3069d95e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/UserLibraryJsGlobalScopeContainer.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*******************************************************************************
- * 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.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-
-/**
- *
- */
-public class UserLibraryJsGlobalScopeContainer implements IJsGlobalScopeContainer {
-
- private String name;
-
- public UserLibraryJsGlobalScopeContainer(String libName) {
- this.name= libName;
- }
-
- private UserLibrary getUserLibrary() {
- return UserLibraryManager.getUserLibrary(this.name);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer#getClasspathEntries()
- */
- /**
- * @deprecated Use {@link #getIncludepathEntries()} instead
- */
- public IIncludePathEntry[] getClasspathEntries() {
- return getIncludepathEntries();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer#getClasspathEntries()
- */
- public IIncludePathEntry[] getIncludepathEntries() {
- UserLibrary library= getUserLibrary();
- if (library != null) {
- return library.getEntries();
- }
- return new IIncludePathEntry[0];
-
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer#getDescription()
- */
- public String getDescription() {
- return this.name;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer#getKind()
- */
- public int getKind() {
- UserLibrary library= getUserLibrary();
- if (library != null && library.isSystemLibrary()) {
- return K_SYSTEM;
- }
- return K_APPLICATION;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer#getPath()
- */
- public IPath getPath() {
- return new Path(JavaScriptCore.USER_LIBRARY_CONTAINER_ID).append(this.name);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer#resolvedLibraryImport(java.lang.String)
- */
- public String[] resolvedLibraryImport(String a) {
- return new String[] {a};
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/UserLibraryJsGlobalScopeContainerInitializer.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/UserLibraryJsGlobalScopeContainerInitializer.java
deleted file mode 100644
index c7313eee..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/UserLibraryJsGlobalScopeContainerInitializer.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*******************************************************************************
- * 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.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer;
-import org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.UnimplementedException;
-import org.eclipse.wst.jsdt.core.compiler.libraries.LibraryLocation;
-
-/**
- *
- */
-public class UserLibraryJsGlobalScopeContainerInitializer extends JsGlobalScopeContainerInitializer {
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer#initialize(org.eclipse.core.runtime.IPath, org.eclipse.wst.jsdt.core.IJavaScriptProject)
- */
- public void initialize(IPath containerPath, IJavaScriptProject project) throws CoreException {
- if (isUserLibraryContainer(containerPath)) {
- String userLibName= containerPath.segment(1);
-
- UserLibrary entries= UserLibraryManager.getUserLibrary(userLibName);
- if (entries != null) {
- UserLibraryJsGlobalScopeContainer container= new UserLibraryJsGlobalScopeContainer(userLibName);
- JavaScriptCore.setJsGlobalScopeContainer(containerPath, new IJavaScriptProject[] { project }, new IJsGlobalScopeContainer[] { container }, null);
- }
- }
- }
-
- private boolean isUserLibraryContainer(IPath path) {
- return path != null && path.segmentCount() == 2 && JavaScriptCore.USER_LIBRARY_CONTAINER_ID.equals(path.segment(0));
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer#canUpdateJsGlobalScopeContainer(org.eclipse.core.runtime.IPath, org.eclipse.wst.jsdt.core.IJavaScriptProject)
- */
- public boolean canUpdateJsGlobalScopeContainer(IPath containerPath, IJavaScriptProject project) {
- return isUserLibraryContainer(containerPath);
- }
-
- /**
- * @see org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer#requestJsGlobalScopeContainerUpdate(org.eclipse.core.runtime.IPath, org.eclipse.wst.jsdt.core.IJavaScriptProject, org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer)
- */
- public void requestJsGlobalScopeContainerUpdate(IPath containerPath, IJavaScriptProject project, IJsGlobalScopeContainer containerSuggestion) throws CoreException {
- if (isUserLibraryContainer(containerPath)) {
- String name= containerPath.segment(1);
- if (containerSuggestion != null) {
- UserLibrary library= new UserLibrary(containerSuggestion.getIncludepathEntries(), containerSuggestion.getKind() == IJsGlobalScopeContainer.K_SYSTEM);
- UserLibraryManager.setUserLibrary(name, library, null); // should use a real progress monitor
- } else {
- UserLibraryManager.setUserLibrary(name, null, null); // should use a real progress monitor
- }
- }
- }
-
- /**
- * @see org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer#getDescription(org.eclipse.core.runtime.IPath, org.eclipse.wst.jsdt.core.IJavaScriptProject)
- */
- public String getDescription(IPath containerPath, IJavaScriptProject project) {
- if (isUserLibraryContainer(containerPath)) {
- return containerPath.segment(1);
- }
- return super.getDescription(containerPath, project);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer#getComparisonID(org.eclipse.core.runtime.IPath, org.eclipse.wst.jsdt.core.IJavaScriptProject)
- */
- public Object getComparisonID(IPath containerPath, IJavaScriptProject project) {
- return containerPath;
- }
-
- public LibraryLocation getLibraryLocation() {
-throw new UnimplementedException();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/UserLibraryManager.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/UserLibraryManager.java
deleted file mode 100644
index 2f73b14f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/UserLibraryManager.java
+++ /dev/null
@@ -1,276 +0,0 @@
-/*******************************************************************************
- * 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 java.io.IOException;
-import java.io.StringReader;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.core.runtime.preferences.IEclipsePreferences;
-import org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-import org.osgi.service.prefs.BackingStoreException;
-
-/**
- *
- */
-public class UserLibraryManager {
-
- public final static String CP_USERLIBRARY_PREFERENCES_PREFIX = JavaScriptCore.PLUGIN_ID+".userLibrary."; //$NON-NLS-1$
- public final static String CP_ENTRY_IGNORE = "##<cp entry ignore>##"; //$NON-NLS-1$
-
- private static Map UserLibraries;
- private static ThreadLocal InitializingLibraries = new ThreadLocal();
- private static final boolean logProblems= false;
- private static IEclipsePreferences.IPreferenceChangeListener listener= new IEclipsePreferences.IPreferenceChangeListener() {
-
- public void preferenceChange(IEclipsePreferences.PreferenceChangeEvent event) {
- String key= event.getKey();
- if (key.startsWith(CP_USERLIBRARY_PREFERENCES_PREFIX)) {
- try {
- recreatePersistedUserLibraryEntry(key, (String) event.getNewValue(), false, true);
- } catch (JavaScriptModelException e) {
- if (logProblems) {
- Util.log(e, "Exception while rebinding user library '"+ key.substring(CP_USERLIBRARY_PREFERENCES_PREFIX.length()) +"'."); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- }
- }
- }
- };
-
- private UserLibraryManager() {
- // do not instantiate
- }
-
- /**
- * Returns the names of all defined user libraries. The corresponding classpath container path
- * is the name appended to the CONTAINER_ID.
- * @return Return an array containing the names of all known user defined.
- */
- public static String[] getUserLibraryNames() {
- Set set= getLibraryMap().keySet();
- return (String[]) set.toArray(new String[set.size()]);
- }
-
- /**
- * Gets the library for a given name or <code>null</code> if no such library exists.
- * @param name The name of the library
- * @return The library registered for the given name or <code>null</code>.
- */
- public static UserLibrary getUserLibrary(String name) {
- return (UserLibrary) getLibraryMap().get(name);
- }
-
- /**
- * Registers user libraries for given names. If a library for the given name already exists, its value will be updated.
- * This call will also rebind all related classpath container.
- * @param newNames The names to register the libraries for
- * @param newLibs The libraries to register
- * @param monitor A progress monitor used when rebinding the classpath containers
- * @throws JavaScriptModelException
- */
- public static void setUserLibraries(String[] newNames, UserLibrary[] newLibs, IProgressMonitor monitor) throws JavaScriptModelException {
- Assert.isTrue(newNames.length == newLibs.length, "names and libraries should have the same length"); //$NON-NLS-1$
-
- if (monitor == null) {
- monitor= new NullProgressMonitor();
- }
-
- try {
- monitor.beginTask("", newNames.length); //$NON-NLS-1$
- int last= newNames.length - 1;
- for (int i= 0; i < newLibs.length; i++) {
- internalSetUserLibrary(newNames[i], newLibs[i], i == last, true, new SubProgressMonitor(monitor, 1));
- }
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Registers a user library for a given name. If a library for the given name already exists, its value will be updated.
- * This call will also rebind all related classpath container.
- * @param name The name to register the library for
- * @param library The library to register
- * @param monitor A progress monitor used when rebinding the classpath containers
- * @throws JavaScriptModelException
- */
- public static void setUserLibrary(String name, UserLibrary library, IProgressMonitor monitor) throws JavaScriptModelException {
- internalSetUserLibrary(name, library, true, true, monitor);
- }
-
- static Map getLibraryMap() {
- if (UserLibraries == null) {
- HashMap libraries = (HashMap) InitializingLibraries.get();
- if (libraries != null)
- return libraries;
- try {
- InitializingLibraries.set(libraries = new HashMap());
- // load variables and containers from preferences into cache
- IEclipsePreferences instancePreferences = JavaModelManager.getJavaModelManager().getInstancePreferences();
- instancePreferences.addPreferenceChangeListener(listener);
-
- // only get variable from preferences not set to their default
- try {
- String[] propertyNames = instancePreferences.keys();
- for (int i = 0; i < propertyNames.length; i++) {
- String propertyName = propertyNames[i];
- if (propertyName.startsWith(CP_USERLIBRARY_PREFERENCES_PREFIX)) {
- try {
- String propertyValue = instancePreferences.get(propertyName, null);
- if (propertyValue != null)
- recreatePersistedUserLibraryEntry(propertyName,propertyValue, false, false);
- } catch (JavaScriptModelException e) {
- // won't happen: no rebinding
- }
- }
- }
- } catch (BackingStoreException e) {
- // nothing to do in this case
- }
- UserLibraries = libraries;
- } finally {
- InitializingLibraries.set(null);
- }
- }
- return UserLibraries;
- }
-
- static void recreatePersistedUserLibraryEntry(String propertyName, String savedString, boolean save, boolean rebind) throws JavaScriptModelException {
- String libName= propertyName.substring(CP_USERLIBRARY_PREFERENCES_PREFIX.length());
- if (savedString == null || savedString.equals(CP_ENTRY_IGNORE)) {
- internalSetUserLibrary(libName, null, save, rebind, null);
- } else {
- try {
- StringReader reader = new StringReader(savedString);
- UserLibrary library= UserLibrary.createFromString(reader);
- internalSetUserLibrary(libName, library, save, rebind, null);
- } catch (IOException e) {
- if (logProblems) {
- Util.log(e, "Exception while retrieving user library '"+ propertyName +"', library will be removed."); //$NON-NLS-1$ //$NON-NLS-2$
- }
- internalSetUserLibrary(libName, null, save, rebind, null);
- }
- }
- }
-
-
-
- static void internalSetUserLibrary(String name, UserLibrary library, boolean save, boolean rebind, IProgressMonitor monitor) throws JavaScriptModelException {
- if (library == null) {
- Object previous= getLibraryMap().remove(name);
- if (previous == null) {
- return; // no change
- }
- } else {
- Object previous= getLibraryMap().put(name, library);
- if (library.equals(previous)) {
- return; // no change
- }
- }
-
- IEclipsePreferences instancePreferences = JavaModelManager.getJavaModelManager().getInstancePreferences();
- String containerKey = CP_USERLIBRARY_PREFERENCES_PREFIX+name;
- String containerString = CP_ENTRY_IGNORE;
- if (library != null) {
- try {
- containerString= library.serialize();
- } catch (IOException e) {
- // could not encode entry: leave it as CP_ENTRY_IGNORE
- }
- }
- instancePreferences.removePreferenceChangeListener(listener);
- try {
- instancePreferences.put(containerKey, containerString);
- if (save) {
- try {
- instancePreferences.flush();
- } catch (BackingStoreException e) {
- // nothing to do in this case
- }
- }
- if (rebind) {
- rebindClasspathEntries(name, library==null, monitor);
- }
-
- } finally {
- instancePreferences.addPreferenceChangeListener(listener);
- }
- }
-
- private static void rebindClasspathEntries(String name, boolean remove, IProgressMonitor monitor) throws JavaScriptModelException {
- try {
- if (monitor != null) {
- monitor.beginTask("", 1); //$NON-NLS-1$
- }
- IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
- IJavaScriptProject[] projects= JavaScriptCore.create(root).getJavaScriptProjects();
- IPath containerPath= new Path(JavaScriptCore.USER_LIBRARY_CONTAINER_ID).append(name);
-
- ArrayList affectedProjects= new ArrayList();
-
- for (int i= 0; i < projects.length; i++) {
- IJavaScriptProject project= projects[i];
- IIncludePathEntry[] entries= project.getRawIncludepath();
- for (int k= 0; k < entries.length; k++) {
- IIncludePathEntry curr= entries[k];
- if (curr.getEntryKind() == IIncludePathEntry.CPE_CONTAINER) {
- if (containerPath.equals(curr.getPath())) {
- affectedProjects.add(project);
- break;
- }
- }
- }
- }
- if (!affectedProjects.isEmpty()) {
- IJavaScriptProject[] affected= (IJavaScriptProject[]) affectedProjects.toArray(new IJavaScriptProject[affectedProjects.size()]);
- IJsGlobalScopeContainer[] containers= new IJsGlobalScopeContainer[affected.length];
- if (!remove) {
- // Previously, containers array only contained a null value. Then, user library classpath entry was first removed
- // and then added a while after when post change delta event on .classpath file was fired...
- // Unfortunately, in some cases, this event was fired a little bit too late and missed the refresh of Package Explorer
- // (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=61872)
- // So now, instanciate a new user library classpath container instead which allow to refresh its content immediately
- // as there's no classpath entry removal...
- // Note that it works because equals(Object) method is not overridden for UserLibraryJsGlobalScopeContainer.
- // If it was, the update wouldn't happen while setting classpath container
- // @see javaCore.setJsGlobalScopeContainer(IPath, IJavaScriptProject[], IJsGlobalScopeContainer[], IProgressMonitor)
- UserLibraryJsGlobalScopeContainer container= new UserLibraryJsGlobalScopeContainer(name);
- containers[0] = container;
- }
- JavaScriptCore.setJsGlobalScopeContainer(containerPath, affected, containers, monitor == null ? null : new SubProgressMonitor(monitor, 1));
- }
- } finally {
- if (monitor != null) {
- monitor.done();
- }
- }
- }
-
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/VerboseElementCache.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/VerboseElementCache.java
deleted file mode 100644
index 3d9dd694..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/VerboseElementCache.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core;
-
-import java.text.NumberFormat;
-import java.util.Date;
-
-public class VerboseElementCache extends ElementCache {
-
- private Object beingAdded;
- private String name;
-
- public VerboseElementCache(int size, String name) {
- super(size);
- this.name = name;
- }
-
- protected boolean makeSpace(int space) {
- if (this.beingAdded == null) return super.makeSpace(space);
- String fillingRatio = toStringFillingRation(this.name);
- boolean result = super.makeSpace(space);
- String newFillingRatio = toStringFillingRation(this.name);
- if (!fillingRatio.equals(newFillingRatio)) {
- System.out.println(Thread.currentThread() + " " + new Date(System.currentTimeMillis()).toString()); //$NON-NLS-1$
- System.out.println(Thread.currentThread() + " MADE SPACE FOR " + fillingRatio + " (NOW " + NumberFormat.getInstance().format(fillingRatio()) + "% full)"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- System.out.println(Thread.currentThread() + " WHILE OPENING "+ ((JavaElement) this.beingAdded).toStringWithAncestors()); //$NON-NLS-1$
- System.out.println();
- }
- return result;
- }
-
- public Object put(Object key, Object value) {
- try {
- if (this.beingAdded == null)
- this.beingAdded = key;
- return super.put(key, value);
- } finally {
- if (key.equals(this.beingAdded))
- this.beingAdded = null;
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/XMLWriter.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/XMLWriter.java
deleted file mode 100644
index 9387359e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/XMLWriter.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*******************************************************************************
- * 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 java.io.Writer;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.internal.compiler.util.GenericXMLWriter;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-/**
- * @since 3.0
- */
-class XMLWriter extends GenericXMLWriter {
-
- public XMLWriter(Writer writer, IJavaScriptProject project, boolean printXmlVersion) {
- super(writer, Util.getLineSeparator((String) null, project), printXmlVersion);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/AbortIncrementalBuildException.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/AbortIncrementalBuildException.java
deleted file mode 100644
index 0a9481ae..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/AbortIncrementalBuildException.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.builder;
-
-/**
- * Exception thrown when an incremental builder cannot find a .class file.
- * Its possible the type can no longer be found because it was renamed inside its existing
- * source file.
- */
-public class AbortIncrementalBuildException extends RuntimeException {
-
-protected String qualifiedTypeName;
-private static final long serialVersionUID = -8874662133883858502L; // backward compatible
-
-public AbortIncrementalBuildException(String qualifiedTypeName) {
- this.qualifiedTypeName = qualifiedTypeName;
-}
-}
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
deleted file mode 100644
index 71b8713b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/AbstractImageBuilder.java
+++ /dev/null
@@ -1,667 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.builder;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Locale;
-import java.util.Map;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceProxy;
-import org.eclipse.core.resources.IResourceProxyVisitor;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelMarker;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.compiler.BuildContext;
-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.CompilationResult;
-import org.eclipse.wst.jsdt.internal.compiler.Compiler;
-import org.eclipse.wst.jsdt.internal.compiler.DefaultErrorHandlingPolicies;
-import org.eclipse.wst.jsdt.internal.compiler.ICompilerRequestor;
-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.problem.AbortCompilation;
-import org.eclipse.wst.jsdt.internal.compiler.util.SimpleSet;
-import org.eclipse.wst.jsdt.internal.core.JavaModelManager;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * The abstract superclass of Java builders.
- * Provides the building and compilation mechanism
- * in common with the batch and incremental builders.
- */
-public abstract class AbstractImageBuilder implements ICompilerRequestor, ICompilationUnitLocator {
-
-protected JavaBuilder javaBuilder;
-protected State newState;
-
-// local copies
-protected NameEnvironment nameEnvironment;
-protected ClasspathMultiDirectory[] sourceLocations;
-protected BuildNotifier notifier;
-
-protected Compiler compiler;
-protected WorkQueue workQueue;
-protected ArrayList problemSourceFiles;
-protected boolean compiledAllAtOnce;
-
-private boolean inCompiler;
-protected boolean keepStoringProblemMarkers;
-
-public static int MAX_AT_ONCE = 2000; // best compromise between space used and speed
-public final static String[] JAVA_PROBLEM_MARKER_ATTRIBUTE_NAMES = {
- IMarker.MESSAGE,
- IMarker.SEVERITY,
- IJavaScriptModelMarker.ID,
- IMarker.CHAR_START,
- IMarker.CHAR_END,
- IMarker.LINE_NUMBER,
- IJavaScriptModelMarker.ARGUMENTS,
- IJavaScriptModelMarker.CATEGORY_ID,
-};
-public final static String[] JAVA_TASK_MARKER_ATTRIBUTE_NAMES = {
- IMarker.MESSAGE,
- IMarker.PRIORITY,
- IJavaScriptModelMarker.ID,
- IMarker.CHAR_START,
- IMarker.CHAR_END,
- IMarker.LINE_NUMBER,
- IMarker.USER_EDITABLE,
- IMarker.SOURCE_ID,
-};
-public final static Integer S_ERROR = new Integer(IMarker.SEVERITY_ERROR);
-public final static Integer S_WARNING = new Integer(IMarker.SEVERITY_WARNING);
-public final static Integer P_HIGH = new Integer(IMarker.PRIORITY_HIGH);
-public final static Integer P_NORMAL = new Integer(IMarker.PRIORITY_NORMAL);
-public final static Integer P_LOW = new Integer(IMarker.PRIORITY_LOW);
-
-protected AbstractImageBuilder(JavaBuilder javaBuilder, boolean buildStarting, State newState) {
- // local copies
- this.javaBuilder = javaBuilder;
- this.nameEnvironment = javaBuilder.nameEnvironment;
- this.sourceLocations = this.nameEnvironment.sourceLocations;
- this.notifier = javaBuilder.notifier;
- this.keepStoringProblemMarkers = true; // may get disabled when missing classfiles are encountered
-
- if (buildStarting) {
- this.newState = newState == null ? new State(javaBuilder) : newState;
- this.compiler = newCompiler();
- this.workQueue = new WorkQueue();
- this.problemSourceFiles = new ArrayList(3);
- }
-}
-
-public void acceptResult(CompilationResult result) {
- // In Batch mode, we write out the class files, hold onto the dependency info
- // & additional types and report problems.
-
- // In Incremental mode, when writing out a class file we need to compare it
- // against the previous file, remembering if structural changes occured.
- // Before reporting the new problems, we need to update the problem count &
- // remove the old problems. Plus delete additional class files that no longer exist.
-
- SourceFile compilationUnit = (SourceFile) result.getCompilationUnit(); // go directly back to the sourceFile
- if (!workQueue.isCompiled(compilationUnit)) {
- workQueue.finished(compilationUnit);
-
- try {
- updateProblemsFor(compilationUnit, result); // record compilation problems before potentially adding duplicate errors
- updateTasksFor(compilationUnit, result); // record tasks
- } catch (CoreException e) {
- throw internalException(e);
- }
-
- if (result.hasInconsistentToplevelHierarchies)
- // ensure that this file is always retrieved from source for the rest of the build
- if (!problemSourceFiles.contains(compilationUnit))
- problemSourceFiles.add(compilationUnit);
-
- String typeLocator = compilationUnit.typeLocator();
-
- finishedWith(typeLocator, result, compilationUnit.getMainTypeName(), new ArrayList(), new ArrayList());
- notifier.compiled(compilationUnit);
- }
-}
-
-
-protected void addAllSourceFiles(final ArrayList sourceFiles) throws CoreException {
- for (int i = 0, l = sourceLocations.length; i < l; i++) {
- final ClasspathMultiDirectory sourceLocation = sourceLocations[i];
- final char[][] exclusionPatterns = sourceLocation.exclusionPatterns;
- final char[][] inclusionPatterns = sourceLocation.inclusionPatterns;
- final boolean isAlsoProject = sourceLocation.sourceFolder.equals(javaBuilder.currentProject);
- final int segmentCount = sourceLocation.sourceFolder.getFullPath().segmentCount();
- final IContainer outputFolder = sourceLocation.binaryFolder;
- final boolean isOutputFolder = sourceLocation.sourceFolder.equals(outputFolder);
- sourceLocation.sourceFolder.accept(
- new IResourceProxyVisitor() {
- public boolean visit(IResourceProxy proxy) throws CoreException {
- if (proxy.isDerived())
- return false;
- switch(proxy.getType()) {
- case IResource.FILE :
- if (org.eclipse.wst.jsdt.internal.core.util.Util.isJavaLikeFileName(proxy.getName())) {
- IResource resource = proxy.requestResource();
- if (exclusionPatterns != null || inclusionPatterns != null)
- if (Util.isExcluded(resource.getFullPath(), inclusionPatterns, exclusionPatterns, false))
- return false;
- sourceFiles.add(new SourceFile((IFile) resource, sourceLocation));
- }
- return false;
- case IResource.FOLDER :
- IPath folderPath = null;
- if (isAlsoProject)
- if (isExcludedFromProject(folderPath = proxy.requestFullPath()))
- return false;
- if (JavaScriptCore.isReadOnly(proxy.requestResource()))
- return false;
- if (exclusionPatterns != null) {
- if (folderPath == null)
- folderPath = proxy.requestFullPath();
- if (Util.isExcluded(folderPath, inclusionPatterns, exclusionPatterns, true)) {
- // must walk children if inclusionPatterns != null, can skip them if == null
- // but folder is excluded so do not create it in the output folder
- return inclusionPatterns != null;
- }
- }
- }
- return true;
- }
- },
- IResource.NONE
- );
- notifier.checkCancel();
- }
-}
-
-protected void cleanUp() {
- this.nameEnvironment.cleanup();
-
- this.javaBuilder = null;
- this.nameEnvironment = null;
- this.sourceLocations = null;
- this.notifier = null;
- this.compiler = null;
- this.workQueue = null;
- this.problemSourceFiles = null;
-}
-
-/* Compile the given elements, adding more elements to the work queue
-* if they are affected by the changes.
-*/
-protected void compile(SourceFile[] units) {
- // notify validationParticipants which source files are about to be compiled
- BuildContext[] participantResults = this.javaBuilder.participants == null ? null : notifyParticipants(units);
- if (participantResults != null && participantResults.length > units.length) {
- units = new SourceFile[participantResults.length];
- for (int i = participantResults.length; --i >= 0;)
- units[i] = participantResults[i].sourceFile;
- }
-
- int unitsLength = units.length;
- this.compiledAllAtOnce = unitsLength <= MAX_AT_ONCE;
- if (this.compiledAllAtOnce) {
- // do them all now
- if (JavaBuilder.DEBUG)
- for (int i = 0; i < unitsLength; i++)
- System.out.println("About to compile " + units[i].typeLocator()); //$NON-NLS-1$
- compile(units, null, true);
- } else {
- SourceFile[] remainingUnits = new SourceFile[unitsLength]; // copy of units, removing units when about to compile
- System.arraycopy(units, 0, remainingUnits, 0, unitsLength);
- int doNow = unitsLength < MAX_AT_ONCE ? unitsLength : MAX_AT_ONCE;
- SourceFile[] toCompile = new SourceFile[doNow];
- int remainingIndex = 0;
- boolean compilingFirstGroup = true;
- while (remainingIndex < unitsLength) {
- int count = 0;
- while (remainingIndex < unitsLength && count < doNow) {
- // Although it needed compiling when this method was called, it may have
- // already been compiled when it was referenced by another unit.
- SourceFile unit = remainingUnits[remainingIndex];
- if (unit != null && (compilingFirstGroup || this.workQueue.isWaiting(unit))) {
- if (JavaBuilder.DEBUG)
- System.out.println("About to compile #" + remainingIndex + " : "+ unit.typeLocator()); //$NON-NLS-1$ //$NON-NLS-2$
- toCompile[count++] = unit;
- }
- remainingUnits[remainingIndex++] = null;
- }
- if (count < doNow)
- System.arraycopy(toCompile, 0, toCompile = new SourceFile[count], 0, count);
- if (!compilingFirstGroup)
- for (int a = remainingIndex; a < unitsLength; a++)
- if (remainingUnits[a] != null && this.workQueue.isCompiled(remainingUnits[a]))
- remainingUnits[a] = null; // use the class file for this source file since its been compiled
- compile(toCompile, remainingUnits, compilingFirstGroup);
- compilingFirstGroup = false;
- }
- }
-
- if (participantResults != null) {
- for (int i = participantResults.length; --i >= 0;)
- if (participantResults[i] != null)
- recordParticipantResult(participantResults[i]);
- }
-}
-
-protected void compile(SourceFile[] units, SourceFile[] additionalUnits, boolean compilingFirstGroup) {
- if (units.length == 0) return;
- notifier.aboutToCompile(units[0]); // just to change the message
-
- // extend additionalFilenames with all hierarchical problem types found during this entire build
- if (!problemSourceFiles.isEmpty()) {
- int toAdd = problemSourceFiles.size();
- int length = additionalUnits == null ? 0 : additionalUnits.length;
- if (length == 0)
- additionalUnits = new SourceFile[toAdd];
- else
- System.arraycopy(additionalUnits, 0, additionalUnits = new SourceFile[length + toAdd], 0, length);
- for (int i = 0; i < toAdd; i++)
- additionalUnits[length + i] = (SourceFile) problemSourceFiles.get(i);
- }
-// String[] initialTypeNames = new String[units.length];
-// for (int i = 0, l = units.length; i < l; i++)
-// initialTypeNames[i] = units[i].initialTypeName;
-// nameEnvironment.setNames(initialTypeNames, additionalUnits);
- notifier.checkCancel();
- try {
- inCompiler = true;
- compiler.compile(units);
- } catch (AbortCompilation ignored) {
- // ignore the AbortCompilcation coming from BuildNotifier.checkCancelWithinCompiler()
- // the Compiler failed after the user has chose to cancel... likely due to an OutOfMemory error
- } finally {
- inCompiler = false;
- }
- // Check for cancel immediately after a compile, because the compiler may
- // have been cancelled but without propagating the correct exception
- notifier.checkCancel();
-}
-
-protected void createProblemFor(IResource resource, IMember javaElement, String message, String problemSeverity) {
- try {
- IMarker marker = resource.createMarker(IJavaScriptModelMarker.JAVASCRIPT_MODEL_PROBLEM_MARKER);
- int severity = problemSeverity.equals(JavaScriptCore.WARNING) ? IMarker.SEVERITY_WARNING : IMarker.SEVERITY_ERROR;
-
- ISourceRange range = javaElement == null ? null : javaElement.getNameRange();
- int start = range == null ? 0 : range.getOffset();
- int end = range == null ? 1 : start + range.getLength();
- marker.setAttributes(
- new String[] {IMarker.MESSAGE, IMarker.SEVERITY, IMarker.CHAR_START, IMarker.CHAR_END, IMarker.SOURCE_ID},
- new Object[] {message, new Integer(severity), new Integer(start), new Integer(end), JavaBuilder.SOURCE_ID});
- } catch (CoreException e) {
- throw internalException(e);
- }
-}
-
-protected void deleteGeneratedFiles(IFile[] deletedGeneratedFiles) {
- // no op by default
-}
-
-protected SourceFile findSourceFile(IFile file, boolean mustExist) {
- if (mustExist && !file.exists()) return null;
- if (file.isDerived()) return null;
-
- // assumes the file exists in at least one of the source folders & is not excluded
- ClasspathMultiDirectory md = sourceLocations[0];
- if (sourceLocations.length > 1) {
- IPath sourceFileFullPath = file.getFullPath();
- for (int j = 0, m = sourceLocations.length; j < m; j++) {
- if (sourceLocations[j].sourceFolder.getFullPath().isPrefixOf(sourceFileFullPath)) {
- md = sourceLocations[j];
- if (md.exclusionPatterns == null && md.inclusionPatterns == null)
- break;
- if (!Util.isExcluded(file, md.inclusionPatterns, md.exclusionPatterns))
- break;
- }
- }
- }
- return new SourceFile(file, md);
-}
-
-protected void finishedWith(String sourceLocator, CompilationResult result, char[] mainTypeName, ArrayList definedTypeNames, ArrayList duplicateTypeNames) {
- if (duplicateTypeNames == null) {
- newState.record(sourceLocator, result.qualifiedReferences, result.simpleNameReferences, mainTypeName, definedTypeNames);
- return;
- }
-
- char[][][] qualifiedRefs = result.qualifiedReferences;
- char[][] simpleRefs = result.simpleNameReferences;
- // for each duplicate type p1.p2.A, add the type name A (package was already added)
- next : for (int i = 0, l = duplicateTypeNames.size(); i < l; i++) {
- char[][] compoundName = (char[][]) duplicateTypeNames.get(i);
- char[] typeName = compoundName[compoundName.length - 1];
- int sLength = simpleRefs.length;
- for (int j = 0; j < sLength; j++)
- if (CharOperation.equals(simpleRefs[j], typeName))
- continue next;
- System.arraycopy(simpleRefs, 0, simpleRefs = new char[sLength + 1][], 0, sLength);
- simpleRefs[sLength] = typeName;
- }
- newState.record(sourceLocator, qualifiedRefs, simpleRefs, mainTypeName, definedTypeNames);
-}
-
-
-
-
-
-/* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.core.builder.ICompilationUnitLocator#fromIFile(org.eclipse.core.resources.IFile)
- */
-public ICompilationUnit fromIFile(IFile file) {
- return findSourceFile(file, true);
-}
-
-protected RuntimeException internalException(CoreException t) {
- ImageBuilderInternalException imageBuilderException = new ImageBuilderInternalException(t);
- if (inCompiler)
- return new AbortCompilation(true, imageBuilderException);
- return imageBuilderException;
-}
-
-protected boolean isExcludedFromProject(IPath childPath) throws JavaScriptModelException {
- // answer whether the folder should be ignored when walking the project as a source folder
- if (childPath.segmentCount() > 2) return false; // is a subfolder of a package
-
- for (int j = 0, k = sourceLocations.length; j < k; j++) {
- if (childPath.equals(sourceLocations[j].binaryFolder.getFullPath())) return true;
- if (childPath.equals(sourceLocations[j].sourceFolder.getFullPath())) return true;
- }
- // skip default output folder which may not be used by any source folder
- return childPath.equals(javaBuilder.javaProject.getOutputLocation());
-}
-
-protected Compiler newCompiler() {
- // disable entire javadoc support if not interested in diagnostics
- Map projectOptions = javaBuilder.javaProject.getOptions(true);
- String option = (String) projectOptions.get(JavaScriptCore.COMPILER_PB_INVALID_JAVADOC);
- if (option == null || option.equals(JavaScriptCore.IGNORE)) { // TODO (frederic) see why option is null sometimes while running model tests!?
- option = (String) projectOptions.get(JavaScriptCore.COMPILER_PB_MISSING_JAVADOC_TAGS);
- if (option == null || option.equals(JavaScriptCore.IGNORE)) {
- option = (String) projectOptions.get(JavaScriptCore.COMPILER_PB_MISSING_JAVADOC_COMMENTS);
- if (option == null || option.equals(JavaScriptCore.IGNORE)) {
- option = (String) projectOptions.get(JavaScriptCore.COMPILER_PB_UNUSED_IMPORT);
- if (option == null || option.equals(JavaScriptCore.IGNORE)) { // Unused import need also to look inside javadoc comment
- projectOptions.put(JavaScriptCore.COMPILER_DOC_COMMENT_SUPPORT, JavaScriptCore.DISABLED);
- }
- }
- }
- }
-
- // called once when the builder is initialized... can override if needed
- CompilerOptions compilerOptions = new CompilerOptions(projectOptions);
- compilerOptions.performMethodsFullRecovery = true;
- compilerOptions.performStatementsRecovery = true;
- Compiler newCompiler = new Compiler(
- nameEnvironment,
- DefaultErrorHandlingPolicies.proceedWithAllProblems(),
- compilerOptions,
- this,
- ProblemFactory.getProblemFactory(Locale.getDefault()));
- CompilerOptions options = newCompiler.options;
-
- // enable the compiler reference info support
- options.produceReferenceInfo = true;
-
- return newCompiler;
-}
-
-protected BuildContext[] notifyParticipants(SourceFile[] unitsAboutToCompile) {
- BuildContext[] results = new BuildContext[unitsAboutToCompile.length];
- for (int i = unitsAboutToCompile.length; --i >= 0;)
- results[i] = new BuildContext(unitsAboutToCompile[i]);
-
- // TODO (kent) do we expect to have more than one participant?
- // and if so should we pass the generated files from the each processor to the others to process?
- // and what happens if some participants do not expect to be called with only a few files, after seeing 'all' the files?
- for (int i = 0, l = this.javaBuilder.participants.length; i < l; i++)
- this.javaBuilder.participants[i].buildStarting(results, this instanceof BatchImageBuilder);
-
- SimpleSet uniqueFiles = null;
- ValidationParticipantResult[] toAdd = null;
- int added = 0;
- for (int i = results.length; --i >= 0;) {
- ValidationParticipantResult result = results[i];
- if (result == null) continue;
-
- IFile[] deletedGeneratedFiles = result.deletedFiles;
- if (deletedGeneratedFiles != null)
- deleteGeneratedFiles(deletedGeneratedFiles);
-
- IFile[] addedGeneratedFiles = result.addedFiles;
- if (addedGeneratedFiles != null) {
- for (int j = addedGeneratedFiles.length; --j >= 0;) {
- SourceFile sourceFile = findSourceFile(addedGeneratedFiles[j], true);
- if (sourceFile == null) continue;
- if (uniqueFiles == null) {
- uniqueFiles = new SimpleSet(unitsAboutToCompile.length + 3);
- for (int f = unitsAboutToCompile.length; --f >= 0;)
- uniqueFiles.add(unitsAboutToCompile[f]);
- }
- if (uniqueFiles.addIfNotIncluded(sourceFile) == sourceFile) {
- ValidationParticipantResult newResult = new BuildContext(sourceFile);
- // is there enough room to add all the addedGeneratedFiles.length ?
- if (toAdd == null) {
- toAdd = new ValidationParticipantResult[addedGeneratedFiles.length];
- } else {
- int length = toAdd.length;
- if (added == length)
- System.arraycopy(toAdd, 0, toAdd = new ValidationParticipantResult[length + addedGeneratedFiles.length], 0, length);
- }
- toAdd[added++] = newResult;
- }
- }
- }
- }
-
- if (added >0 ) {
- int length = results.length;
- System.arraycopy(results, 0, results = new BuildContext[length + added], 0 , length);
- System.arraycopy(toAdd, 0, results, length, added);
- }
- return results;
-}
-
-protected void recordParticipantResult(ValidationParticipantResult result) {
- // any added/changed/deleted generated files have already been taken care
- // just record the problems and dependencies - do not expect there to be many
- // must be called after we're finished with the compilation unit results but before incremental loop adds affected files
- CategorizedProblem[] problems = result.problems;
- if (problems != null && problems.length > 0) {
- // existing problems have already been removed so just add these as new problems
- this.notifier.updateProblemCounts(problems);
- try {
- storeProblemsFor(result.sourceFile, problems);
- } catch (CoreException e) {
- // must continue with compile loop so just log the CoreException
- e.printStackTrace();
- }
- }
-
- String[] dependencies = result.dependencies;
- if (dependencies != null) {
- ReferenceCollection refs = (ReferenceCollection) this.newState.references.get(result.sourceFile.typeLocator());
- if (refs != null)
- refs.addDependencies(dependencies);
- }
-}
-
-/**
- * Creates a marker from each problem and adds it to the resource.
- * The marker is as follows:
- * - its type is T_PROBLEM
- * - its plugin ID is the JavaBuilder's plugin ID
- * - its message is the problem's message
- * - its priority reflects the severity of the problem
- * - its range is the problem's range
- * - it has an extra attribute "ID" which holds the problem's id
- * - it's GENERATED_BY attribute is positioned to JavaBuilder.GENERATED_BY if
- * the problem was generated by JDT; else the GENERATED_BY attribute is
- * carried from the problem to the marker in extra attributes, if present.
- */
-protected void storeProblemsFor(SourceFile sourceFile, CategorizedProblem[] problems) throws CoreException {
- if (sourceFile == null || problems == null || problems.length == 0) return;
- // once a classpath error is found, ignore all other problems for this project so the user can see the main error
- // but still try to compile as many source files as possible to help the case when the base libraries are in source
- if (!this.keepStoringProblemMarkers) return; // only want the one error recorded on this source file
-
- IResource resource = sourceFile.resource;
- IResource container=(resource instanceof IFile)? resource.getParent():resource;
- if (JavaScriptCore.isReadOnly(container))
- return;
- HashSet managedMarkerTypes = JavaModelManager.getJavaModelManager().validationParticipants.managedMarkerTypes();
- for (int i = 0, l = problems.length; i < l; i++) {
- CategorizedProblem problem = problems[i];
- int id = problem.getID();
-
- // handle missing classfile situation
- if (id == IProblem.IsClassPathCorrect) {
- String missingClassfileName = problem.getArguments()[0];
- if (JavaBuilder.DEBUG)
- System.out.println(Messages.bind(Messages.build_incompleteClassPath, missingClassfileName));
- boolean isInvalidClasspathError = JavaScriptCore.ERROR.equals(javaBuilder.javaProject.getOption(JavaScriptCore.CORE_INCOMPLETE_CLASSPATH, true));
- // insert extra classpath problem, and make it the only problem for this project (optional)
- if (isInvalidClasspathError && JavaScriptCore.ABORT.equals(javaBuilder.javaProject.getOption(JavaScriptCore.CORE_JAVA_BUILD_INVALID_CLASSPATH, true))) {
- JavaBuilder.removeProblemsAndTasksFor(javaBuilder.currentProject); // make this the only problem for this project
- this.keepStoringProblemMarkers = false;
- }
- IMarker marker = this.javaBuilder.currentProject.createMarker(IJavaScriptModelMarker.JAVASCRIPT_MODEL_PROBLEM_MARKER);
- marker.setAttributes(
- new String[] {IMarker.MESSAGE, IMarker.SEVERITY, IJavaScriptModelMarker.CATEGORY_ID, IMarker.SOURCE_ID},
- new Object[] {
- Messages.bind(Messages.build_incompleteClassPath, missingClassfileName),
- new Integer(isInvalidClasspathError ? IMarker.SEVERITY_ERROR : IMarker.SEVERITY_WARNING),
- new Integer(CategorizedProblem.CAT_BUILDPATH),
- JavaBuilder.SOURCE_ID
- }
- );
- // even if we're not keeping more markers, still fall through rest of the problem reporting, so that offending
- // IsClassPathCorrect problem gets recorded since it may help locate the offending reference
- }
-
- String markerType = problem.getMarkerType();
- boolean managedProblem = false;
- if (IJavaScriptModelMarker.JAVASCRIPT_MODEL_PROBLEM_MARKER.equals(markerType)
- || (managedProblem = managedMarkerTypes.contains(markerType))) {
- IMarker marker = resource.createMarker(markerType);
-
- String[] attributeNames = JAVA_PROBLEM_MARKER_ATTRIBUTE_NAMES;
- int standardLength = attributeNames.length;
- String[] allNames = attributeNames;
- int managedLength = managedProblem ? 0 : 1;
- String[] extraAttributeNames = problem.getExtraMarkerAttributeNames();
- int extraLength = extraAttributeNames == null ? 0 : extraAttributeNames.length;
- if (managedLength > 0 || extraLength > 0) {
- allNames = new String[standardLength + managedLength + extraLength];
- System.arraycopy(attributeNames, 0, allNames, 0, standardLength);
- if (managedLength > 0)
- allNames[standardLength] = IMarker.SOURCE_ID;
- System.arraycopy(extraAttributeNames, 0, allNames, standardLength + managedLength, extraLength);
- }
-
- Object[] allValues = new Object[allNames.length];
- // standard attributes
- int index = 0;
- allValues[index++] = problem.getMessage(); // message
- allValues[index++] = problem.isError() ? S_ERROR : S_WARNING; // severity
- allValues[index++] = new Integer(id); // ID
- allValues[index++] = new Integer(problem.getSourceStart()); // start
- allValues[index++] = new Integer(problem.getSourceEnd() + 1); // end
- allValues[index++] = new Integer(problem.getSourceLineNumber()); // line
- allValues[index++] = Util.getProblemArgumentsForMarker(problem.getArguments()); // arguments
- allValues[index++] = new Integer(problem.getCategoryID()); // category ID
- // GENERATED_BY attribute for JDT problems
- if (managedLength > 0)
- allValues[index++] = JavaBuilder.SOURCE_ID;
- // optional extra attributes
- if (extraLength > 0)
- System.arraycopy(problem.getExtraMarkerAttributeValues(), 0, allValues, index, extraLength);
-
- marker.setAttributes(allNames, allValues);
-
- if (!this.keepStoringProblemMarkers) return; // only want the one error recorded on this source file
- }
- }
-}
-
-protected void storeTasksFor(SourceFile sourceFile, CategorizedProblem[] tasks) throws CoreException {
- if (sourceFile == null || tasks == null || tasks.length == 0) return;
-
- IResource resource = sourceFile.resource;
- for (int i = 0, l = tasks.length; i < l; i++) {
- CategorizedProblem task = tasks[i];
- if (task.getID() == IProblem.Task) {
- IMarker marker = resource.createMarker(IJavaScriptModelMarker.TASK_MARKER);
- Integer priority = P_NORMAL;
- String compilerPriority = task.getArguments()[2];
- if (JavaScriptCore.COMPILER_TASK_PRIORITY_HIGH.equals(compilerPriority))
- priority = P_HIGH;
- else if (JavaScriptCore.COMPILER_TASK_PRIORITY_LOW.equals(compilerPriority))
- priority = P_LOW;
-
- String[] attributeNames = JAVA_TASK_MARKER_ATTRIBUTE_NAMES;
- int standardLength = attributeNames.length;
- String[] allNames = attributeNames;
- String[] extraAttributeNames = task.getExtraMarkerAttributeNames();
- int extraLength = extraAttributeNames == null ? 0 : extraAttributeNames.length;
- if (extraLength > 0) {
- allNames = new String[standardLength + extraLength];
- System.arraycopy(attributeNames, 0, allNames, 0, standardLength);
- System.arraycopy(extraAttributeNames, 0, allNames, standardLength, extraLength);
- }
-
- Object[] allValues = new Object[allNames.length];
- // standard attributes
- int index = 0;
- allValues[index++] = task.getMessage();
- allValues[index++] = priority;
- allValues[index++] = new Integer(task.getID());
- allValues[index++] = new Integer(task.getSourceStart());
- allValues[index++] = new Integer(task.getSourceEnd() + 1);
- allValues[index++] = new Integer(task.getSourceLineNumber());
- allValues[index++] = Boolean.FALSE;
- allValues[index++] = JavaBuilder.SOURCE_ID;
- // optional extra attributes
- if (extraLength > 0)
- System.arraycopy(task.getExtraMarkerAttributeValues(), 0, allValues, index, extraLength);
-
- marker.setAttributes(allNames, allValues);
- }
- }
-}
-
-protected void updateProblemsFor(SourceFile sourceFile, CompilationResult result) throws CoreException {
- CategorizedProblem[] problems = result.getProblems();
- if (problems == null || problems.length == 0) return;
-
- notifier.updateProblemCounts(problems);
- storeProblemsFor(sourceFile, problems);
-}
-
-protected void updateTasksFor(SourceFile sourceFile, CompilationResult result) throws CoreException {
- CategorizedProblem[] tasks = result.getTasks();
- if (tasks == null || tasks.length == 0) return;
-
- storeTasksFor(sourceFile, tasks);
-}
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/AdditionalTypeCollection.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/AdditionalTypeCollection.java
deleted file mode 100644
index 9fca750d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/AdditionalTypeCollection.java
+++ /dev/null
@@ -1,22 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.builder;
-
-public class AdditionalTypeCollection extends ReferenceCollection {
-
-char[][] definedTypeNames;
-
-protected AdditionalTypeCollection(char[][] definedTypeNames, char[][][] qualifiedReferences, char[][] simpleNameReferences) {
- super(qualifiedReferences, simpleNameReferences);
- this.definedTypeNames = definedTypeNames; // do not bother interning member type names (ie. 'A$M')
-}
-}
-
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
deleted file mode 100644
index 73726076..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/BatchImageBuilder.java
+++ /dev/null
@@ -1,137 +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.builder;
-
-import java.util.ArrayList;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-
-public class BatchImageBuilder extends AbstractImageBuilder {
-
- IncrementalImageBuilder incrementalBuilder; // if annotations or secondary types have to be processed after the compile loop
- ArrayList secondaryTypes; // qualified names for all secondary types found during batch compile
- StringSet typeLocatorsWithUndefinedTypes; // type locators for all source files with errors that may be caused by 'not found' secondary types
-
-protected BatchImageBuilder(JavaBuilder javaBuilder, boolean buildStarting) {
- super(javaBuilder, buildStarting, null);
- this.nameEnvironment.isIncrementalBuild = false;
- this.incrementalBuilder = null;
- this.secondaryTypes = null;
- this.typeLocatorsWithUndefinedTypes = null;
-}
-
-public void build() {
- if (JavaBuilder.DEBUG)
- System.out.println("FULL build"); //$NON-NLS-1$
-
- try {
-// notifier.subTask(Messages.bind(Messages.build_cleaningOutput, this.javaBuilder.currentProject.getName()));
- JavaBuilder.removeProblemsAndTasksFor(javaBuilder.currentProject);
-// cleanOutputFolders(true);
- notifier.updateProgressDelta(0.05f);
-
- notifier.subTask(Messages.build_analyzingSources);
- ArrayList sourceFiles = new ArrayList(33);
- addAllSourceFiles(sourceFiles);
- notifier.updateProgressDelta(0.10f);
-
- if (sourceFiles.size() > 0) {
- SourceFile[] allSourceFiles = new SourceFile[sourceFiles.size()];
- sourceFiles.toArray(allSourceFiles);
-
- notifier.setProgressPerCompilationUnit(0.75f / allSourceFiles.length);
- workQueue.addAll(allSourceFiles);
- compile(allSourceFiles);
-
- if (this.typeLocatorsWithUndefinedTypes != null)
- if (this.secondaryTypes != null && !this.secondaryTypes.isEmpty())
- rebuildTypesAffectedBySecondaryTypes();
- if (this.incrementalBuilder != null)
- this.incrementalBuilder.buildAfterBatchBuild();
- }
-
- if (javaBuilder.javaProject.hasCycleMarker())
- javaBuilder.mustPropagateStructuralChanges();
- } catch (CoreException e) {
- throw internalException(e);
- } finally {
- cleanUp();
- }
-}
-
-protected void cleanUp() {
- this.incrementalBuilder = null;
- this.secondaryTypes = null;
- this.typeLocatorsWithUndefinedTypes = null;
- super.cleanUp();
-}
-
-protected void compile(SourceFile[] units, SourceFile[] additionalUnits, boolean compilingFirstGroup) {
- if (additionalUnits != null && this.secondaryTypes == null)
- this.secondaryTypes = new ArrayList(7);
- super.compile(units, additionalUnits, compilingFirstGroup);
-}
-
-protected IResource findOriginalResource(IPath partialPath) {
- for (int i = 0, l = sourceLocations.length; i < l; i++) {
- ClasspathMultiDirectory sourceLocation = sourceLocations[i];
- if (sourceLocation.hasIndependentOutputFolder) {
- IResource originalResource = sourceLocation.sourceFolder.getFile(partialPath);
- if (originalResource.exists()) return originalResource;
- }
- }
- return null;
-}
-
-protected void rebuildTypesAffectedBySecondaryTypes() {
- // to compile types that could not find 'missing' secondary types because of multiple
- // compile groups, we need to incrementally recompile all affected types as if the missing
- // secondary types have just been added, see bug 146324
- if (this.incrementalBuilder == null)
- this.incrementalBuilder = new IncrementalImageBuilder(this);
-
- for (int i = this.secondaryTypes.size(); --i >=0;) {
- char[] secondaryTypeName = (char[]) this.secondaryTypes.get(i);
- IPath path = new Path(null, new String(secondaryTypeName));
- this.incrementalBuilder.addDependentsOf(path, false);
- }
- this.incrementalBuilder.addAffectedSourceFiles(
- this.incrementalBuilder.qualifiedStrings,
- this.incrementalBuilder.simpleStrings,
- this.typeLocatorsWithUndefinedTypes);
-}
-
-protected void storeProblemsFor(SourceFile sourceFile, CategorizedProblem[] problems) throws CoreException {
- if (sourceFile == null || problems == null || problems.length == 0) return;
-
- for (int i = problems.length; --i >= 0;) {
- CategorizedProblem problem = problems[i];
- if (problem != null && problem.getID() == IProblem.UndefinedType) {
- if (this.typeLocatorsWithUndefinedTypes == null)
- this.typeLocatorsWithUndefinedTypes = new StringSet(3);
- this.typeLocatorsWithUndefinedTypes.add(sourceFile.typeLocator());
- break;
- }
- }
-
- super.storeProblemsFor(sourceFile, problems);
-}
-
-public String toString() {
- return "batch image builder for:\n\tnew state: " + newState; //$NON-NLS-1$
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/BuildNotifier.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/BuildNotifier.java
deleted file mode 100644
index b5d5c3a6..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/BuildNotifier.java
+++ /dev/null
@@ -1,278 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.builder;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-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.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.internal.compiler.problem.AbortCompilation;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-
-public class BuildNotifier {
-
-protected IProgressMonitor monitor;
-protected boolean cancelling;
-protected float percentComplete;
-protected float progressPerCompilationUnit;
-protected int newErrorCount;
-protected int fixedErrorCount;
-protected int newWarningCount;
-protected int fixedWarningCount;
-protected int workDone;
-protected int totalWork;
-protected String previousSubtask;
-
-public static int NewErrorCount = 0;
-public static int FixedErrorCount = 0;
-public static int NewWarningCount = 0;
-public static int FixedWarningCount = 0;
-
-public static void resetProblemCounters() {
- NewErrorCount = 0;
- FixedErrorCount = 0;
- NewWarningCount = 0;
- FixedWarningCount = 0;
-}
-
-public BuildNotifier(IProgressMonitor monitor, IProject project) {
- this.monitor = monitor;
- this.cancelling = false;
- this.newErrorCount = NewErrorCount;
- this.fixedErrorCount = FixedErrorCount;
- this.newWarningCount = NewWarningCount;
- this.fixedWarningCount = FixedWarningCount;
- this.workDone = 0;
- this.totalWork = 1000000;
-}
-
-/**
- * Notification before a compile that a unit is about to be compiled.
- */
-public void aboutToCompile(SourceFile unit) {
- String message = Messages.bind(Messages.build_compiling, unit.resource.getFullPath().removeLastSegments(1).makeRelative().toString());
- subTask(message);
-}
-
-public void begin() {
- if (monitor != null)
- monitor.beginTask("", totalWork); //$NON-NLS-1$
- this.previousSubtask = null;
-}
-
-/**
- * Check whether the build has been canceled.
- */
-public void checkCancel() {
- if (monitor != null && monitor.isCanceled())
- throw new OperationCanceledException();
-}
-
-/**
- * Check whether the build has been canceled.
- * Must use this call instead of checkCancel() when within the compiler.
- */
-public void checkCancelWithinCompiler() {
- if (monitor != null && monitor.isCanceled() && !cancelling) {
- // Once the compiler has been canceled, don't check again.
- setCancelling(true);
- // Only AbortCompilation can stop the compiler cleanly.
- // We check cancelation again following the call to compile.
- throw new AbortCompilation(true, null);
- }
-}
-
-/**
- * Notification while within a compile that a unit has finished being compiled.
- */
-public void compiled(SourceFile unit) {
- String message = Messages.bind(Messages.build_compiling, unit.resource.getFullPath().removeLastSegments(1).makeRelative().toString());
- subTask(message);
- updateProgressDelta(progressPerCompilationUnit);
- checkCancelWithinCompiler();
-}
-
-public void done() {
- NewErrorCount = this.newErrorCount;
- FixedErrorCount = this.fixedErrorCount;
- NewWarningCount = this.newWarningCount;
- FixedWarningCount = this.fixedWarningCount;
-
- updateProgress(1.0f);
- subTask(Messages.build_done);
- if (monitor != null)
- monitor.done();
- this.previousSubtask = null;
-}
-
-/**
- * Returns a string describing the problems.
- */
-protected String problemsMessage() {
- int numNew = newErrorCount + newWarningCount;
- int numFixed = fixedErrorCount + fixedWarningCount;
- if (numNew == 0 && numFixed == 0) return ""; //$NON-NLS-1$
-
- boolean displayBoth = numNew > 0 && numFixed > 0;
- StringBuffer buffer = new StringBuffer();
- buffer.append('(');
- if (numNew > 0) {
- // (Found x errors + y warnings)
- buffer.append(Messages.build_foundHeader);
- buffer.append(' ');
- if (displayBoth || newErrorCount > 0) {
- if (newErrorCount == 1)
- buffer.append(Messages.build_oneError);
- else
- buffer.append(Messages.bind(Messages.build_multipleErrors, String.valueOf(newErrorCount)));
- if (displayBoth || newWarningCount > 0)
- buffer.append(" + "); //$NON-NLS-1$
- }
- if (displayBoth || newWarningCount > 0) {
- if (newWarningCount == 1)
- buffer.append(Messages.build_oneWarning);
- else
- buffer.append(Messages.bind(Messages.build_multipleWarnings, String.valueOf(newWarningCount)));
- }
- if (numFixed > 0)
- buffer.append(", "); //$NON-NLS-1$
- }
- if (numFixed > 0) {
- // (Fixed x errors + y warnings) or (Found x errors + y warnings, Fixed x + y)
- buffer.append(Messages.build_fixedHeader);
- buffer.append(' ');
- if (displayBoth) {
- buffer.append(String.valueOf(fixedErrorCount));
- buffer.append(" + "); //$NON-NLS-1$
- buffer.append(String.valueOf(fixedWarningCount));
- } else {
- if (fixedErrorCount > 0) {
- if (fixedErrorCount == 1)
- buffer.append(Messages.build_oneError);
- else
- buffer.append(Messages.bind(Messages.build_multipleErrors, String.valueOf(fixedErrorCount)));
- if (fixedWarningCount > 0)
- buffer.append(" + "); //$NON-NLS-1$
- }
- if (fixedWarningCount > 0) {
- if (fixedWarningCount == 1)
- buffer.append(Messages.build_oneWarning);
- else
- buffer.append(Messages.bind(Messages.build_multipleWarnings, String.valueOf(fixedWarningCount)));
- }
- }
- }
- buffer.append(')');
- return buffer.toString();
-}
-
-/**
- * Sets the cancelling flag, which indicates we are in the middle
- * of being cancelled. Certain places (those callable indirectly from the compiler)
- * should not check cancel again while this is true, to avoid OperationCanceledException
- * being thrown at an inopportune time.
- */
-public void setCancelling(boolean cancelling) {
- this.cancelling = cancelling;
-}
-
-/**
- * Sets the amount of progress to report for compiling each compilation unit.
- */
-public void setProgressPerCompilationUnit(float progress) {
- this.progressPerCompilationUnit = progress;
-}
-
-public void subTask(String message) {
- String pm = problemsMessage();
- String msg = pm.length() == 0 ? message : pm + " " + message; //$NON-NLS-1$
-
- if (msg.equals(this.previousSubtask)) return; // avoid refreshing with same one
- //if (JavaBuilder.DEBUG) System.out.println(msg);
- if (monitor != null)
- monitor.subTask(msg);
-
- this.previousSubtask = msg;
-}
-
-protected void updateProblemCounts(CategorizedProblem[] newProblems) {
- for (int i = 0, l = newProblems.length; i < l; i++)
- if (newProblems[i].isError()) newErrorCount++; else newWarningCount++;
-}
-
-/**
- * Update the problem counts from one compilation result given the old and new problems,
- * either of which may be null.
- */
-protected void updateProblemCounts(IMarker[] oldProblems, CategorizedProblem[] newProblems) {
- if (newProblems != null) {
- next : for (int i = 0, l = newProblems.length; i < l; i++) {
- CategorizedProblem newProblem = newProblems[i];
- if (newProblem.getID() == IProblem.Task) continue; // skip task
- boolean isError = newProblem.isError();
- String message = newProblem.getMessage();
-
- if (oldProblems != null) {
- for (int j = 0, m = oldProblems.length; j < m; j++) {
- IMarker pb = oldProblems[j];
- if (pb == null) continue; // already matched up with a new problem
- boolean wasError = IMarker.SEVERITY_ERROR
- == pb.getAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
- if (isError == wasError && message.equals(pb.getAttribute(IMarker.MESSAGE, ""))) { //$NON-NLS-1$
- oldProblems[j] = null;
- continue next;
- }
- }
- }
- if (isError) newErrorCount++; else newWarningCount++;
- }
- }
- if (oldProblems != null) {
- next : for (int i = 0, l = oldProblems.length; i < l; i++) {
- IMarker oldProblem = oldProblems[i];
- if (oldProblem == null) continue next; // already matched up with a new problem
- boolean wasError = IMarker.SEVERITY_ERROR
- == oldProblem.getAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
- String message = oldProblem.getAttribute(IMarker.MESSAGE, ""); //$NON-NLS-1$
-
- if (newProblems != null) {
- for (int j = 0, m = newProblems.length; j < m; j++) {
- CategorizedProblem pb = newProblems[j];
- if (pb.getID() == IProblem.Task) continue; // skip task
- if (wasError == pb.isError() && message.equals(pb.getMessage()))
- continue next;
- }
- }
- if (wasError) fixedErrorCount++; else fixedWarningCount++;
- }
- }
-}
-
-public void updateProgress(float newPercentComplete) {
- if (newPercentComplete > this.percentComplete) {
- this.percentComplete = Math.min(newPercentComplete, 1.0f);
- int work = Math.round(this.percentComplete * this.totalWork);
- if (work > this.workDone) {
- if (monitor != null)
- monitor.worked(work - this.workDone);
- //if (JavaBuilder.DEBUG)
- //System.out.println(java.text.NumberFormat.getPercentInstance().format(this.percentComplete));
- this.workDone = work;
- }
- }
-}
-
-public void updateProgressDelta(float percentWorked) {
- updateProgress(percentComplete + percentWorked);
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ClasspathDirectory.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ClasspathDirectory.java
deleted file mode 100644
index 812b242c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ClasspathDirectory.java
+++ /dev/null
@@ -1,127 +0,0 @@
-/*******************************************************************************
- * 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.builder;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.wst.jsdt.internal.compiler.env.AccessRuleSet;
-import org.eclipse.wst.jsdt.internal.compiler.env.NameEnvironmentAnswer;
-import org.eclipse.wst.jsdt.internal.compiler.util.SimpleLookupTable;
-
-public class ClasspathDirectory extends ClasspathLocation {
-
-IContainer binaryFolder; // includes .class files for a single directory
-boolean isOutputFolder;
-SimpleLookupTable directoryCache;
-String[] missingPackageHolder = new String[1];
-AccessRuleSet accessRuleSet;
-
-ClasspathDirectory(IContainer binaryFolder, boolean isOutputFolder, AccessRuleSet accessRuleSet) {
- this.binaryFolder = binaryFolder;
- this.isOutputFolder = isOutputFolder;
- this.directoryCache = new SimpleLookupTable(5);
- this.accessRuleSet = accessRuleSet;
-}
-
-public void cleanup() {
- this.directoryCache = null;
-}
-
-String[] directoryList(String qualifiedPackageName) {
- String[] dirList = (String[]) directoryCache.get(qualifiedPackageName);
- if (dirList == missingPackageHolder) return null; // package exists in another classpath directory or jar
- if (dirList != null) return dirList;
-
- try {
- IResource container = binaryFolder.findMember(qualifiedPackageName); // this is a case-sensitive check
- if (container instanceof IContainer) {
- IResource[] members = ((IContainer) container).members();
- dirList = new String[members.length];
- int index = 0;
- for (int i = 0, l = members.length; i < l; i++) {
- IResource m = members[i];
- if (m.getType() == IResource.FILE && org.eclipse.wst.jsdt.internal.compiler.util.Util.isClassFileName(m.getName()))
- // add exclusion pattern check here if we want to hide .class files
- dirList[index++] = m.getName();
- }
- if (index < dirList.length)
- System.arraycopy(dirList, 0, dirList = new String[index], 0, index);
- directoryCache.put(qualifiedPackageName, dirList);
- return dirList;
- }
- } catch(CoreException ignored) {
- // ignore
- }
- directoryCache.put(qualifiedPackageName, missingPackageHolder);
- return null;
-}
-
-boolean doesFileExist(String fileName, String qualifiedPackageName, String qualifiedFullName) {
- String[] dirList = directoryList(qualifiedPackageName);
- if (dirList == null) return false; // most common case
-
- for (int i = dirList.length; --i >= 0;)
- if (fileName.equals(dirList[i]))
- return true;
- return false;
-}
-
-public boolean equals(Object o) {
- if (this == o) return true;
- if (!(o instanceof ClasspathDirectory)) return false;
-
- ClasspathDirectory dir = (ClasspathDirectory) o;
- if (this.accessRuleSet != dir.accessRuleSet)
- if (this.accessRuleSet == null || !this.accessRuleSet.equals(dir.accessRuleSet))
- return false;
- return this.binaryFolder.equals(dir.binaryFolder);
-}
-
-public NameEnvironmentAnswer findClass(String binaryFileName, String qualifiedPackageName, String qualifiedBinaryFileName) {
-
- return null;
-}
-
-public IPath getProjectRelativePath() {
- return binaryFolder.getProjectRelativePath();
-}
-
-protected boolean isExcluded(IResource resource) {
- return false;
-}
-
-public boolean isOutputFolder() {
- return isOutputFolder;
-}
-
-public boolean isPackage(String qualifiedPackageName) {
- return directoryList(qualifiedPackageName) != null;
-}
-
-public void reset() {
- this.directoryCache = new SimpleLookupTable(5);
-}
-
-public String toString() {
- String start = "Binary classpath directory " + this.binaryFolder.getFullPath().toString(); //$NON-NLS-1$
- if (this.accessRuleSet == null)
- return start;
- return start + " with " + this.accessRuleSet; //$NON-NLS-1$
-}
-
-public String debugPathString() {
- return this.binaryFolder.getFullPath().toString();
-}
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ClasspathLibrary.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ClasspathLibrary.java
deleted file mode 100644
index e17f263a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ClasspathLibrary.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- * Tal Lev-Ami - added package cache for zip files
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.builder;
-
-import java.io.File;
-import java.util.Date;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.wst.jsdt.internal.compiler.env.AccessRuleSet;
-import org.eclipse.wst.jsdt.internal.compiler.env.NameEnvironmentAnswer;
-import org.eclipse.wst.jsdt.internal.compiler.util.SimpleSet;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-public class ClasspathLibrary extends ClasspathLocation {
-
-
-
-String filename; // keep for equals
-IFile resource;
-long lastModified;
-boolean closeZipFileAtEnd;
-SimpleSet knownPackageNames;
-AccessRuleSet accessRuleSet;
-
-ClasspathLibrary(IFile resource, AccessRuleSet accessRuleSet) {
- this.resource = resource;
- try {
- java.net.URI location = resource.getLocationURI();
- if (location == null) {
- this.filename = ""; //$NON-NLS-1$
- } else {
- File localFile = Util.toLocalFile(location, null);
- this.filename = localFile.getPath();
- }
- } catch (CoreException e) {
- // ignore
- }
- this.knownPackageNames = null;
- this.accessRuleSet = accessRuleSet;
-}
-
-ClasspathLibrary(String filename, long lastModified, AccessRuleSet accessRuleSet) {
- this.filename = filename;
- this.lastModified = lastModified;
- this.knownPackageNames = null;
- this.accessRuleSet = accessRuleSet;
-}
-
-
-public void cleanup() {
- this.knownPackageNames = null;
-}
-
-public boolean equals(Object o) {
- if (this == o) return true;
- if (!(o instanceof ClasspathLibrary)) return false;
-
- ClasspathLibrary library = (ClasspathLibrary) o;
- if (this.accessRuleSet != library.accessRuleSet)
- if (this.accessRuleSet == null || !this.accessRuleSet.equals(library.accessRuleSet))
- return false;
- return this.filename.equals(library.filename) && this.lastModified() == library.lastModified();
-}
-
-public NameEnvironmentAnswer findClass(String binaryFileName, String qualifiedPackageName, String qualifiedBinaryFileName) {
-// if (!isPackage(qualifiedPackageName)) return null; // most common case
-//
-// try {
-// ClassFileReader reader = ClassFileReader.read(this.zipFile, qualifiedBinaryFileName);
-// if (reader != null) {
-// if (this.accessRuleSet == null)
-// return new NameEnvironmentAnswer(reader, null);
-// String fileNameWithoutExtension = qualifiedBinaryFileName.substring(0, qualifiedBinaryFileName.length() - SuffixConstants.SUFFIX_CLASS.length);
-// return new NameEnvironmentAnswer(reader, this.accessRuleSet.getViolatedRestriction(fileNameWithoutExtension.toCharArray()));
-// }
-// } catch (Exception e) { // treat as if class file is missing
-// }
-// return null;
- //TODO: implement
- throw new org.eclipse.wst.jsdt.core.UnimplementedException();
-}
-
-public IPath getProjectRelativePath() {
- if (this.resource == null) return null;
- return this.resource.getProjectRelativePath();
-}
-
-public boolean isPackage(String qualifiedPackageName) {
- return this.filename.endsWith(qualifiedPackageName);
-// if (this.knownPackageNames != null)
-// return this.knownPackageNames.includes(qualifiedPackageName);
-//
-// try {
-// if (this.zipFile == null) {
-// if (org.eclipse.wst.jsdt.internal.core.JavaModelManager.ZIP_ACCESS_VERBOSE) {
-// System.out.println("(" + Thread.currentThread() + ") [ClasspathJar.isPackage(String)] Creating ZipFile on " + zipFilename); //$NON-NLS-1$ //$NON-NLS-2$
-// }
-// this.zipFile = new ZipFile(zipFilename);
-// this.closeZipFileAtEnd = true;
-// }
-// this.knownPackageNames = findPackageSet(this);
-// } catch(Exception e) {
-// this.knownPackageNames = new SimpleSet(); // assume for this build the zipFile is empty
-// }
-// return this.knownPackageNames.includes(qualifiedPackageName);
-}
-
-public long lastModified() {
- if (this.lastModified == 0)
- this.lastModified = new File(this.filename).lastModified();
- return this.lastModified;
-}
-
-public String toString() {
- String start = "Classpath library file " + this.filename; //$NON-NLS-1$
- if (this.accessRuleSet == null)
- return start;
- return start + " with " + this.accessRuleSet; //$NON-NLS-1$
-}
-
-public String debugPathString() {
- if (this.lastModified == 0)
- return this.filename;
- return this.filename + '(' + (new Date(this.lastModified)) + " : " + this.lastModified + ')'; //$NON-NLS-1$
-}
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ClasspathLocation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ClasspathLocation.java
deleted file mode 100644
index 3cfac9b6..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ClasspathLocation.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*******************************************************************************
- * 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.builder;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.wst.jsdt.internal.compiler.env.AccessRuleSet;
-import org.eclipse.wst.jsdt.internal.compiler.env.NameEnvironmentAnswer;
-
-public abstract class ClasspathLocation {
-
-static ClasspathLocation forSourceFolder(IContainer sourceFolder, IContainer outputFolder, char[][] inclusionPatterns, char[][] exclusionPatterns) {
- return new ClasspathMultiDirectory(sourceFolder, outputFolder, inclusionPatterns, exclusionPatterns);
-}
-
-public static ClasspathLocation forBinaryFolder(IContainer binaryFolder, boolean isOutputFolder, AccessRuleSet accessRuleSet) {
- return new ClasspathDirectory(binaryFolder, isOutputFolder, accessRuleSet);
-}
-
-public static ClasspathLocation forLibrary(String libraryPathname, long lastModified, AccessRuleSet accessRuleSet) {
- return new ClasspathLibrary(libraryPathname, lastModified, accessRuleSet);
-}
-
-public static ClasspathLocation forLibrary(String libraryPathname, AccessRuleSet accessRuleSet) {
- return forLibrary(libraryPathname, 0, accessRuleSet);
-}
-
-
-public abstract NameEnvironmentAnswer findClass(String binaryFileName, String qualifiedPackageName, String qualifiedBinaryFileName);
-
-public abstract IPath getProjectRelativePath();
-
-public boolean isOutputFolder() {
- return false;
-}
-
-public abstract boolean isPackage(String qualifiedPackageName);
-
-public void cleanup() {
- // free anything which is not required when the state is saved
-}
-public void reset() {
- // reset any internal caches before another compile loop starts
-}
-
-public abstract String debugPathString();
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ClasspathMultiDirectory.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ClasspathMultiDirectory.java
deleted file mode 100644
index ff692ae2..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ClasspathMultiDirectory.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.builder;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-class ClasspathMultiDirectory extends ClasspathDirectory {
-
-IContainer sourceFolder;
-char[][] inclusionPatterns; // used by builders when walking source folders
-char[][] exclusionPatterns; // used by builders when walking source folders
-boolean hasIndependentOutputFolder; // if output folder is not equal to any of the source folders
-
-ClasspathMultiDirectory(IContainer sourceFolder, IContainer binaryFolder, char[][] inclusionPatterns, char[][] exclusionPatterns) {
- super(binaryFolder, true, null);
-
- this.sourceFolder = sourceFolder;
- this.inclusionPatterns = inclusionPatterns;
- this.exclusionPatterns = exclusionPatterns;
- this.hasIndependentOutputFolder = false;
-
- // handle the case when a state rebuilds a source folder
- if (this.inclusionPatterns != null && this.inclusionPatterns.length == 0)
- this.inclusionPatterns = null;
- if (this.exclusionPatterns != null && this.exclusionPatterns.length == 0)
- this.exclusionPatterns = null;
-}
-
-public boolean equals(Object o) {
- if (this == o) return true;
- if (!(o instanceof ClasspathMultiDirectory)) return false;
-
- ClasspathMultiDirectory md = (ClasspathMultiDirectory) o;
- return sourceFolder.equals(md.sourceFolder) && binaryFolder.equals(md.binaryFolder)
- && CharOperation.equals(inclusionPatterns, md.inclusionPatterns)
- && CharOperation.equals(exclusionPatterns, md.exclusionPatterns);
-}
-
-protected boolean isExcluded(IResource resource) {
- if (this.exclusionPatterns != null || this.inclusionPatterns != null)
- if (this.sourceFolder.equals(this.binaryFolder))
- return Util.isExcluded(resource, this.inclusionPatterns, this.exclusionPatterns);
- return false;
-}
-
-public String toString() {
- return "Source classpath directory " + sourceFolder.getFullPath().toString() + //$NON-NLS-1$
- " with " + super.toString(); //$NON-NLS-1$
-}
-}
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
deleted file mode 100644
index bc45ca4e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ICompilationUnitLocator.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * wharley@bea.com - initial API and implementation
- *
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.core.builder;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit;
-
-/**
- * Used to convert an IFile into an IJavaScriptUnit,
- * for clients outside of this package.
- * @since 3.3
- */
-public interface ICompilationUnitLocator {
- public ICompilationUnit fromIFile(IFile file);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ImageBuilderInternalException.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ImageBuilderInternalException.java
deleted file mode 100644
index 677a0e3c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ImageBuilderInternalException.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.builder;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-
-/**
- * Exception thrown when there is an internal error in the image builder.
- * May wrapper another exception.
- */
-public class ImageBuilderInternalException extends RuntimeException {
-
-private static final long serialVersionUID = 28252254530437336L; // backward compatible
-protected CoreException coreException;
-
-public ImageBuilderInternalException(CoreException e) {
- this.coreException = e;
-}
-
-public String getLocalizedMessage() {
- IStatus status = this.coreException.getStatus();
- if (status.isMultiStatus()) {
- IStatus[] children = status.getChildren();
- if (children != null && children.length > 0)
- return children[0].getMessage();
- }
- return this.coreException.getLocalizedMessage();
-}
-
-public CoreException getThrowable() {
- return coreException;
-}
-
-public void printStackTrace() {
- if (coreException != null) {
- System.err.println(this);
- System.err.println("Stack trace of embedded core exception:"); //$NON-NLS-1$
- coreException.printStackTrace();
- } else {
- super.printStackTrace();
- }
-}
-}
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
deleted file mode 100644
index 50b936ce..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/IncrementalImageBuilder.java
+++ /dev/null
@@ -1,752 +0,0 @@
-/*******************************************************************************
- * 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.builder;
-
-import java.util.ArrayList;
-import java.util.Date;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.resources.IResourceStatus;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelMarker;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-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.util.SimpleLookupTable;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * The incremental image builder
- */
-public class IncrementalImageBuilder extends AbstractImageBuilder {
-
-protected ArrayList sourceFiles;
-protected ArrayList previousSourceFiles;
-protected StringSet qualifiedStrings;
-protected StringSet simpleStrings;
-protected SimpleLookupTable secondaryTypesToRemove;
-protected boolean hasStructuralChanges;
-protected int compileLoop;
-protected boolean makeOutputFolderConsistent;
-
-public static int MaxCompileLoop = 5; // perform a full build if it takes more than ? incremental compile loops
-
-protected IncrementalImageBuilder(JavaBuilder javaBuilder, State buildState) {
- super(javaBuilder, true, buildState);
- this.nameEnvironment.isIncrementalBuild = true;
- this.makeOutputFolderConsistent = JavaScriptCore.ENABLED.equals(
- javaBuilder.javaProject.getOption(JavaScriptCore.CORE_JAVA_BUILD_RECREATE_MODIFIED_CLASS_FILES_IN_OUTPUT_FOLDER, true));
-}
-
-protected IncrementalImageBuilder(JavaBuilder javaBuilder) {
- this(javaBuilder, null);
- this.newState.copyFrom(javaBuilder.lastState);
-}
-
-protected IncrementalImageBuilder(BatchImageBuilder batchBuilder) {
- this(batchBuilder.javaBuilder, batchBuilder.newState);
- resetCollections();
-}
-
-public boolean build(SimpleLookupTable deltas) {
- // initialize builder
- // walk this project's deltas, find changed source files
- // walk prereq projects' deltas, find changed class files & add affected source files
- // use the build state # to skip the deltas for certain prereq projects
- // ignore changed zip/jar files since they caused a full build
- // compile the source files & acceptResult()
- // compare the produced class files against the existing ones on disk
- // recompile all dependent source files of any type with structural changes or new/removed secondary type
- // keep a loop counter to abort & perform a full build
-
- if (JavaBuilder.DEBUG)
- System.out.println("INCREMENTAL build"); //$NON-NLS-1$
-
- try {
- resetCollections();
-
- notifier.subTask(Messages.build_analyzingDeltas);
- if (javaBuilder.hasBuildpathErrors()) {
- // if a mssing class file was detected in the last build, a build state was saved since its no longer fatal
- // but we need to rebuild every source file since problems were not recorded
- // AND to avoid the infinite build scenario if this project is involved in a cycle, see bug 160550
- // we need to avoid unnecessary deltas caused by doing a full build in this case
- javaBuilder.currentProject.deleteMarkers(IJavaScriptModelMarker.JAVASCRIPT_MODEL_PROBLEM_MARKER, false, IResource.DEPTH_ZERO);
- addAllSourceFiles(sourceFiles);
- notifier.updateProgressDelta(0.25f);
- } else {
- IResourceDelta sourceDelta = (IResourceDelta) deltas.get(javaBuilder.currentProject);
- if (sourceDelta != null)
- if (!findSourceFiles(sourceDelta)) return false;
- notifier.updateProgressDelta(0.10f);
-
- Object[] keyTable = deltas.keyTable;
- Object[] valueTable = deltas.valueTable;
- for (int i = 0, l = valueTable.length; i < l; i++) {
- IResourceDelta delta = (IResourceDelta) valueTable[i];
- if (delta != null) {
- IProject p = (IProject) keyTable[i];
- ClasspathLocation[] classFoldersAndJars = (ClasspathLocation[]) javaBuilder.binaryLocationsPerProject.get(p);
- if (classFoldersAndJars != null)
- if (!findAffectedSourceFiles(delta, classFoldersAndJars, p)) return false;
- }
- }
- notifier.updateProgressDelta(0.10f);
-
- notifier.subTask(Messages.build_analyzingSources);
- addAffectedSourceFiles();
- notifier.updateProgressDelta(0.05f);
- }
-
- this.compileLoop = 0;
- float increment = 0.40f;
- while (sourceFiles.size() > 0) { // added to in acceptResult
- if (++this.compileLoop > MaxCompileLoop) {
- if (JavaBuilder.DEBUG)
- System.out.println("ABORTING incremental build... exceeded loop count"); //$NON-NLS-1$
- return false;
- }
- notifier.checkCancel();
-
- SourceFile[] allSourceFiles = new SourceFile[sourceFiles.size()];
- sourceFiles.toArray(allSourceFiles);
- resetCollections();
-
- workQueue.addAll(allSourceFiles);
- notifier.setProgressPerCompilationUnit(increment / allSourceFiles.length);
- increment = increment / 2;
- compile(allSourceFiles);
- //removeSecondaryTypes();
- addAffectedSourceFiles();
- }
- if (this.hasStructuralChanges && javaBuilder.javaProject.hasCycleMarker())
- javaBuilder.mustPropagateStructuralChanges();
- } catch (AbortIncrementalBuildException e) {
- // abort the incremental build and let the batch builder handle the problem
- if (JavaBuilder.DEBUG)
- System.out.println("ABORTING incremental build... problem with " + e.qualifiedTypeName + //$NON-NLS-1$
- ". Likely renamed inside its existing source file."); //$NON-NLS-1$
- return false;
- } catch (CoreException e) {
- throw internalException(e);
- } finally {
- cleanUp();
- }
- return true;
-}
-
-protected void buildAfterBatchBuild() {
- // called from a batch builder once all source files have been compiled AND some changes
- // need to be propagated incrementally (annotations, missing secondary types)
-
- if (JavaBuilder.DEBUG)
- System.out.println("INCREMENTAL build after batch build @ " + new Date(System.currentTimeMillis())); //$NON-NLS-1$
-
- // this is a copy of the incremental build loop
- try {
- addAffectedSourceFiles();
- while (this.sourceFiles.size() > 0) {
- notifier.checkCancel();
- SourceFile[] allSourceFiles = new SourceFile[this.sourceFiles.size()];
- this.sourceFiles.toArray(allSourceFiles);
- resetCollections();
- notifier.setProgressPerCompilationUnit(0.08f / allSourceFiles.length);
- this.workQueue.addAll(allSourceFiles);
- compile(allSourceFiles);
- //removeSecondaryTypes();
- addAffectedSourceFiles();
- }
-// } catch (Exception e) {
-// throw internalException(e);
- } finally {
- cleanUp();
- }
-}
-
-protected void addAffectedSourceFiles() {
- if (qualifiedStrings.elementSize == 0 && simpleStrings.elementSize == 0) return;
-
- addAffectedSourceFiles(qualifiedStrings, simpleStrings, null);
-}
-
-protected void addAffectedSourceFiles(StringSet qualifiedSet, StringSet simpleSet, StringSet affectedTypes) {
- // the qualifiedStrings are of the form 'p1/p2' & the simpleStrings are just 'X'
- char[][][] internedQualifiedNames = ReferenceCollection.internQualifiedNames(qualifiedSet);
- // if a well known qualified name was found then we can skip over these
- if (internedQualifiedNames.length < qualifiedSet.elementSize)
- internedQualifiedNames = null;
- char[][] internedSimpleNames = ReferenceCollection.internSimpleNames(simpleSet);
- // if a well known name was found then we can skip over these
- if (internedSimpleNames.length < simpleSet.elementSize)
- internedSimpleNames = null;
-
- Object[] keyTable = newState.references.keyTable;
- Object[] valueTable = newState.references.valueTable;
- next : for (int i = 0, l = valueTable.length; i < l; i++) {
- String typeLocator = (String) keyTable[i];
- if (typeLocator != null) {
- if (affectedTypes != null && !affectedTypes.includes(typeLocator)) continue next;
- ReferenceCollection refs = (ReferenceCollection) valueTable[i];
- if (refs.includes(internedQualifiedNames, internedSimpleNames)) {
- IFile file = javaBuilder.currentProject.getFile(typeLocator);
- SourceFile sourceFile = findSourceFile(file, true);
- if (sourceFile == null) continue next;
- if (sourceFiles.contains(sourceFile)) continue next;
- if (compiledAllAtOnce && previousSourceFiles != null && previousSourceFiles.contains(sourceFile))
- continue next; // can skip previously compiled files since already saw hierarchy related problems
-
- if (JavaBuilder.DEBUG)
- System.out.println(" adding affected source file " + typeLocator); //$NON-NLS-1$
- sourceFiles.add(sourceFile);
- }
- }
- }
-}
-
-protected void addDependentsOf(IPath path, boolean isStructuralChange) {
- if (isStructuralChange && !this.hasStructuralChanges) {
- newState.tagAsStructurallyChanged();
- this.hasStructuralChanges = true;
- }
- // the qualifiedStrings are of the form 'p1/p2' & the simpleStrings are just 'X'
- path = path.setDevice(null);
- 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$
-}
-
-protected boolean checkForClassFileChanges(IResourceDelta binaryDelta, ClasspathMultiDirectory md, int segmentCount) throws CoreException {
- IResource resource = binaryDelta.getResource();
- // remember that if inclusion & exclusion patterns change then a full build is done
- boolean isExcluded = (md.exclusionPatterns != null || md.inclusionPatterns != null)
- && Util.isExcluded(resource, md.inclusionPatterns, md.exclusionPatterns);
- switch(resource.getType()) {
- case IResource.FOLDER :
- if (isExcluded && md.inclusionPatterns == null)
- return true; // no need to go further with this delta since its children cannot be included
-
- IResourceDelta[] children = binaryDelta.getAffectedChildren();
- for (int i = 0, l = children.length; i < l; i++)
- if (!checkForClassFileChanges(children[i], md, segmentCount))
- return false;
- return true;
- case IResource.FILE :
- if (!isExcluded && org.eclipse.wst.jsdt.internal.compiler.util.Util.isClassFileName(resource.getName())) {
- // perform full build if a managed class file has been changed
- IPath typePath = resource.getFullPath().removeFirstSegments(segmentCount).removeFileExtension();
- if (newState.isKnownType(typePath.toString())) {
- if (JavaBuilder.DEBUG)
- System.out.println("MUST DO FULL BUILD. Found change to class file " + typePath); //$NON-NLS-1$
- return false;
- }
- return true;
- }
- }
- return true;
-}
-
-protected void cleanUp() {
- super.cleanUp();
-
- this.sourceFiles = null;
- this.previousSourceFiles = null;
- this.qualifiedStrings = null;
- this.simpleStrings = null;
- this.secondaryTypesToRemove = null;
- this.hasStructuralChanges = false;
- this.compileLoop = 0;
-}
-
-protected void compile(SourceFile[] units, SourceFile[] additionalUnits, boolean compilingFirstGroup) {
- if (compilingFirstGroup && additionalUnits != null) {
- // add any source file from additionalUnits to units if it defines secondary types
- // otherwise its possible during testing with MAX_AT_ONCE == 1 that a secondary type
- // can cause an infinite loop as it alternates between not found and defined, see bug 146324
- ArrayList extras = null;
- for (int i = 0, l = additionalUnits.length; i < l; i++) {
- SourceFile unit = additionalUnits[i];
- if (unit != null && newState.getDefinedTypeNamesFor(unit.typeLocator()) != null) {
- if (JavaBuilder.DEBUG)
- System.out.println("About to compile file with secondary types "+ unit.typeLocator()); //$NON-NLS-1$
- if (extras == null)
- extras = new ArrayList(3);
- extras.add(unit);
- }
- }
- if (extras != null) {
- int oldLength = units.length;
- int toAdd = extras.size();
- System.arraycopy(units, 0, units = new SourceFile[oldLength + toAdd], 0, oldLength);
- for (int i = 0; i < toAdd; i++)
- units[oldLength++] = (SourceFile) extras.get(i);
- }
- }
- super.compile(units, additionalUnits, compilingFirstGroup);
-}
-
-protected void deleteGeneratedFiles(IFile[] deletedGeneratedFiles) {
- // delete generated files and recompile any affected source files
-// try {
- for (int j = deletedGeneratedFiles.length; --j >= 0;) {
- IFile deletedFile = deletedGeneratedFiles[j];
- if (deletedFile.exists()) continue; // only delete .class files for source files that were actually deleted
-
- SourceFile sourceFile = findSourceFile(deletedFile, false);
- String typeLocator = sourceFile.typeLocator();
- int mdSegmentCount = sourceFile.sourceLocation.sourceFolder.getFullPath().segmentCount();
- IPath typePath = sourceFile.resource.getFullPath().removeFirstSegments(mdSegmentCount).removeFileExtension();
- addDependentsOf(typePath, true); // add dependents of the source file since its now deleted
- previousSourceFiles = null; // existing source files did not see it as deleted since they were compiled before it was
- char[][] definedTypeNames = newState.getDefinedTypeNamesFor(typeLocator);
-// if (definedTypeNames == null) { // defined a single type matching typePath
-// removeClassFile(typePath, sourceFile.sourceLocation.binaryFolder);
-// } else {
-// if (definedTypeNames.length > 0) { // skip it if it failed to successfully define a type
-// IPath packagePath = typePath.removeLastSegments(1);
-// for (int d = 0, l = definedTypeNames.length; d < l; d++)
-// removeClassFile(packagePath.append(new String(definedTypeNames[d])), sourceFile.sourceLocation.binaryFolder);
-// }
-// }
- this.newState.removeLocator(typeLocator);
- }
-// } catch (CoreException e) {
-// // must continue with compile loop so just log the CoreException
-// e.printStackTrace();
-// }
-}
-
-protected boolean findAffectedSourceFiles(IResourceDelta delta, ClasspathLocation[] classFoldersAndJars, IProject prereqProject) {
- for (int i = 0, l = classFoldersAndJars.length; i < l; i++) {
- ClasspathLocation bLocation = classFoldersAndJars[i];
- // either a .class file folder or a zip/jar file
- if (bLocation != null) { // skip unchanged output folder
- IPath p = bLocation.getProjectRelativePath();
- if (p != null) {
- IResourceDelta binaryDelta = delta.findMember(p);
- if (binaryDelta != null) {
- if (binaryDelta.getKind() == IResourceDelta.ADDED || binaryDelta.getKind() == IResourceDelta.REMOVED) {
- if (JavaBuilder.DEBUG)
- System.out.println("ABORTING incremental build... found added/removed binary folder"); //$NON-NLS-1$
- return false; // added/removed binary folder should not make it here (classpath change), but handle anyways
- }
- int segmentCount = binaryDelta.getFullPath().segmentCount();
- IResourceDelta[] children = binaryDelta.getAffectedChildren(); // .class files from class folder
- StringSet structurallyChangedTypes = null;
- if (bLocation.isOutputFolder())
- structurallyChangedTypes = this.newState.getStructurallyChangedTypes(javaBuilder.getLastState(prereqProject));
- for (int j = 0, m = children.length; j < m; j++)
- findAffectedSourceFiles(children[j], segmentCount, structurallyChangedTypes);
- notifier.checkCancel();
- }
- }
- }
- }
- return true;
-}
-
-protected void findAffectedSourceFiles(IResourceDelta binaryDelta, int segmentCount, StringSet structurallyChangedTypes) {
- // When a package becomes a type or vice versa, expect 2 deltas,
- // one on the folder & one on the class file
- IResource resource = binaryDelta.getResource();
- switch(resource.getType()) {
- case IResource.FOLDER :
- switch (binaryDelta.getKind()) {
- case IResourceDelta.ADDED :
- case IResourceDelta.REMOVED :
- IPath packagePath = resource.getFullPath().removeFirstSegments(segmentCount);
- String packageName = packagePath.toString();
- if (binaryDelta.getKind() == IResourceDelta.ADDED) {
- // see if any known source file is from the same package... classpath already includes new package
- if (!newState.isKnownPackage(packageName)) {
- if (JavaBuilder.DEBUG)
- System.out.println("Found added package " + packageName); //$NON-NLS-1$
- addDependentsOf(packagePath, false);
- return;
- }
- if (JavaBuilder.DEBUG)
- System.out.println("Skipped dependents of added package " + packageName); //$NON-NLS-1$
- } else {
- // see if the package still exists on the classpath
- if (!nameEnvironment.isPackage(packageName)) {
- if (JavaBuilder.DEBUG)
- System.out.println("Found removed package " + packageName); //$NON-NLS-1$
- addDependentsOf(packagePath, false);
- return;
- }
- if (JavaBuilder.DEBUG)
- System.out.println("Skipped dependents of removed package " + packageName); //$NON-NLS-1$
- }
- // fall thru & traverse the sub-packages and .class files
- case IResourceDelta.CHANGED :
- IResourceDelta[] children = binaryDelta.getAffectedChildren();
- for (int i = 0, l = children.length; i < l; i++)
- findAffectedSourceFiles(children[i], segmentCount, structurallyChangedTypes);
- }
- return;
- case IResource.FILE :
- if (org.eclipse.wst.jsdt.internal.compiler.util.Util.isClassFileName(resource.getName())) {
- IPath typePath = resource.getFullPath().removeFirstSegments(segmentCount).removeFileExtension();
- switch (binaryDelta.getKind()) {
- case IResourceDelta.ADDED :
- case IResourceDelta.REMOVED :
- if (JavaBuilder.DEBUG)
- System.out.println("Found added/removed class file " + typePath); //$NON-NLS-1$
- addDependentsOf(typePath, false);
- return;
- case IResourceDelta.CHANGED :
- if ((binaryDelta.getFlags() & IResourceDelta.CONTENT) == 0)
- return; // skip it since it really isn't changed
- if (structurallyChangedTypes != null && !structurallyChangedTypes.includes(typePath.toString()))
- return; // skip since it wasn't a structural change
- if (JavaBuilder.DEBUG)
- System.out.println("Found changed class file " + typePath); //$NON-NLS-1$
- addDependentsOf(typePath, false);
- }
- return;
- }
- }
-}
-
-protected boolean findSourceFiles(IResourceDelta delta) throws CoreException {
- ArrayList visited = this.makeOutputFolderConsistent ? new ArrayList(sourceLocations.length) : null;
- for (int i = 0, l = sourceLocations.length; i < l; i++) {
- ClasspathMultiDirectory md = sourceLocations[i];
- if (this.makeOutputFolderConsistent && md.hasIndependentOutputFolder && !visited.contains(md.binaryFolder)) {
- // even a project which acts as its own source folder can have an independent/nested output folder
- visited.add(md.binaryFolder);
- IResourceDelta binaryDelta = delta.findMember(md.binaryFolder.getProjectRelativePath());
- if (binaryDelta != null) {
- int segmentCount = binaryDelta.getFullPath().segmentCount();
- IResourceDelta[] children = binaryDelta.getAffectedChildren();
- for (int j = 0, m = children.length; j < m; j++)
- if (!checkForClassFileChanges(children[j], md, segmentCount))
- return false;
- }
- }
- if (md.sourceFolder.equals(javaBuilder.currentProject)) {
- // skip nested source & output folders when the project is a source folder
- int segmentCount = delta.getFullPath().segmentCount();
- IResourceDelta[] children = delta.getAffectedChildren();
- for (int j = 0, m = children.length; j < m; j++)
- if (!isExcludedFromProject(children[j].getFullPath()))
- if (!findSourceFiles(children[j], md, segmentCount))
- return false;
- } else {
- IResourceDelta sourceDelta = delta.findMember(md.sourceFolder.getProjectRelativePath());
- if (sourceDelta != null) {
- if (sourceDelta.getKind() == IResourceDelta.REMOVED) {
- if (JavaBuilder.DEBUG)
- System.out.println("ABORTING incremental build... found removed source folder"); //$NON-NLS-1$
- return false; // removed source folder should not make it here, but handle anyways (ADDED is supported)
- }
- int segmentCount = sourceDelta.getFullPath().segmentCount();
- IResourceDelta[] children = sourceDelta.getAffectedChildren();
- try {
- for (int j = 0, m = children.length; j < m; j++)
- if (!findSourceFiles(children[j], md, segmentCount))
- return false;
- } catch (CoreException e) {
- // catch the case that a package has been renamed and collides on disk with an as-yet-to-be-deleted package
- if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) {
- if (JavaBuilder.DEBUG)
- System.out.println("ABORTING incremental build... found renamed package"); //$NON-NLS-1$
- return false;
- }
- throw e; // rethrow
- }
- }
- }
- notifier.checkCancel();
- }
- return true;
-}
-
-protected boolean findSourceFiles(IResourceDelta sourceDelta, ClasspathMultiDirectory md, int segmentCount) throws CoreException {
- // When a package becomes a type or vice versa, expect 2 deltas,
- // one on the folder & one on the source file
- IResource resource = sourceDelta.getResource();
- // remember that if inclusion & exclusion patterns change then a full build is done
- boolean isExcluded = (md.exclusionPatterns != null || md.inclusionPatterns != null)
- && Util.isExcluded(resource, md.inclusionPatterns, md.exclusionPatterns);
- switch(resource.getType()) {
- case IResource.FOLDER :
- if (isExcluded && md.inclusionPatterns == null)
- return true; // no need to go further with this delta since its children cannot be included
-
- switch (sourceDelta.getKind()) {
- case IResourceDelta.ADDED :
- if (!isExcluded) {
- IPath addedPackagePath = resource.getFullPath().removeFirstSegments(segmentCount);
- // add dependents even when the package thinks it exists to be on the safe side
- if (JavaBuilder.DEBUG)
- System.out.println("Found added package " + addedPackagePath); //$NON-NLS-1$
- addDependentsOf(addedPackagePath, true);
- }
- // fall thru & collect all the source files
- case IResourceDelta.CHANGED :
- IResourceDelta[] children = sourceDelta.getAffectedChildren();
- for (int i = 0, l = children.length; i < l; i++)
- if (!findSourceFiles(children[i], md, segmentCount))
- return false;
- return true;
- case IResourceDelta.REMOVED :
- if (isExcluded) {
- // since this folder is excluded then there is nothing to delete (from this md), but must walk any included subfolders
- children = sourceDelta.getAffectedChildren();
- for (int i = 0, l = children.length; i < l; i++)
- if (!findSourceFiles(children[i], md, segmentCount))
- return false;
- return true;
- }
- IPath removedPackagePath = resource.getFullPath().removeFirstSegments(segmentCount);
- if (sourceLocations.length > 1) {
- for (int i = 0, l = sourceLocations.length; i < l; i++) {
- if (sourceLocations[i].sourceFolder.getFolder(removedPackagePath).exists()) {
- // only a package fragment was removed, same as removing multiple source files
- IResourceDelta[] removedChildren = sourceDelta.getAffectedChildren();
- for (int j = 0, m = removedChildren.length; j < m; j++)
- if (!findSourceFiles(removedChildren[j], md, segmentCount))
- return false;
- return true;
- }
- }
- }
- IFolder removedPackageFolder = md.binaryFolder.getFolder(removedPackagePath);
-// if (removedPackageFolder.exists())
-// removedPackageFolder.delete(IResource.FORCE, null);
- // add dependents even when the package thinks it does not exist to be on the safe side
- if (JavaBuilder.DEBUG)
- System.out.println("Found removed package " + removedPackagePath); //$NON-NLS-1$
- addDependentsOf(removedPackagePath, true);
- newState.removePackage(sourceDelta);
- }
- return true;
- case IResource.FILE :
- if (isExcluded) return true;
-
- String resourceName = resource.getName();
- if (org.eclipse.wst.jsdt.internal.core.util.Util.isJavaLikeFileName(resourceName)) {
- IPath typePath = resource.getFullPath().removeFirstSegments(segmentCount).removeFileExtension();
- String typeLocator = resource.getProjectRelativePath().toString();
- switch (sourceDelta.getKind()) {
- case IResourceDelta.ADDED :
- if (JavaBuilder.DEBUG)
- System.out.println("Compile this added source file " + typeLocator); //$NON-NLS-1$
- if (!resource.isDerived())
- sourceFiles.add(new SourceFile((IFile) resource, md, true));
- String typeName = typePath.toString();
- if (!newState.isDuplicateLocator(typeName, typeLocator)) { // adding dependents results in 2 duplicate errors
- if (JavaBuilder.DEBUG)
- System.out.println("Found added source file " + typeName); //$NON-NLS-1$
- addDependentsOf(typePath, true);
- }
- return true;
- case IResourceDelta.REMOVED :
- char[][] definedTypeNames = newState.getDefinedTypeNamesFor(typeLocator);
- if (definedTypeNames == null) { // defined a single type matching typePath
-// removeClassFile(typePath, md.binaryFolder);
- if ((sourceDelta.getFlags() & IResourceDelta.MOVED_TO) != 0) {
- // remove problems and tasks for a compilation unit that is being moved (to another package or renamed)
- // if the target file is a compilation unit, the new cu will be recompiled
- // if the target file is a non-java resource, then markers are removed
- // see bug 2857
- IResource movedFile = javaBuilder.workspaceRoot.getFile(sourceDelta.getMovedToPath());
- JavaBuilder.removeProblemsAndTasksFor(movedFile);
- }
- } else {
- if (JavaBuilder.DEBUG)
- System.out.println("Found removed source file " + typePath.toString()); //$NON-NLS-1$
- addDependentsOf(typePath, true); // add dependents of the source file since it may be involved in a name collision
-// if (definedTypeNames.length > 0) { // skip it if it failed to successfully define a type
-// IPath packagePath = typePath.removeLastSegments(1);
-// for (int i = 0, l = definedTypeNames.length; i < l; i++)
-// removeClassFile(packagePath.append(new String(definedTypeNames[i])), md.binaryFolder);
-// }
- }
- newState.removeLocator(typeLocator);
- return true;
- case IResourceDelta.CHANGED :
- if ((sourceDelta.getFlags() & IResourceDelta.CONTENT) == 0
- && (sourceDelta.getFlags() & IResourceDelta.ENCODING) == 0)
- return true; // skip it since it really isn't changed
- if (JavaBuilder.DEBUG)
- System.out.println("Compile this changed source file " + typeLocator); //$NON-NLS-1$
- if (!resource.isDerived())
- sourceFiles.add(new SourceFile((IFile) resource, md, true));
- }
- return true;
- } else if (org.eclipse.wst.jsdt.internal.compiler.util.Util.isClassFileName(resourceName)) {
- // perform full build if a managed class file has been changed
- if (this.makeOutputFolderConsistent) {
- IPath typePath = resource.getFullPath().removeFirstSegments(segmentCount).removeFileExtension();
- if (newState.isKnownType(typePath.toString())) {
- if (JavaBuilder.DEBUG)
- System.out.println("MUST DO FULL BUILD. Found change to class file " + typePath); //$NON-NLS-1$
- return false;
- }
- }
- return true;
- } else if (md.hasIndependentOutputFolder) {
- return true;
- }
- }
- return true;
-}
-
-protected void finishedWith(String sourceLocator, CompilationResult result, char[] mainTypeName, ArrayList definedTypeNames, ArrayList duplicateTypeNames) {
- char[][] previousTypeNames = newState.getDefinedTypeNamesFor(sourceLocator);
- if (previousTypeNames == null)
- previousTypeNames = new char[][] {mainTypeName};
- IPath packagePath = null;
- next : for (int i = 0, l = previousTypeNames.length; i < l; i++) {
- char[] previous = previousTypeNames[i];
- for (int j = 0, m = definedTypeNames.size(); j < m; j++)
- if (CharOperation.equals(previous, (char[]) definedTypeNames.get(j)))
- continue next;
-
- SourceFile sourceFile = (SourceFile) result.getCompilationUnit();
- if (packagePath == null) {
- int count = sourceFile.sourceLocation.sourceFolder.getFullPath().segmentCount();
- packagePath = sourceFile.resource.getFullPath().removeFirstSegments(count).removeLastSegments(1);
- }
- if (secondaryTypesToRemove == null)
- this.secondaryTypesToRemove = new SimpleLookupTable();
- ArrayList types = (ArrayList) secondaryTypesToRemove.get(sourceFile.sourceLocation.binaryFolder);
- if (types == null)
- types = new ArrayList(definedTypeNames.size());
- types.add(packagePath.append(new String(previous)));
- secondaryTypesToRemove.put(sourceFile.sourceLocation.binaryFolder, types);
- }
- super.finishedWith(sourceLocator, result, mainTypeName, definedTypeNames, duplicateTypeNames);
-}
-
-//protected void removeClassFile(IPath typePath, IContainer outputFolder) throws CoreException {
-// if (typePath.lastSegment().indexOf('$') == -1) { // is not a nested type
-// newState.removeQualifiedTypeName(typePath.toString());
-// // add dependents even when the type thinks it does not exist to be on the safe side
-// if (JavaBuilder.DEBUG)
-// System.out.println("Found removed type " + typePath); //$NON-NLS-1$
-// addDependentsOf(typePath, true); // when member types are removed, their enclosing type is structurally changed
-// }
-// IFile classFile = outputFolder.getFile(typePath.addFileExtension(SuffixConstants.EXTENSION_class));
-// if (classFile.exists()) {
-// if (JavaBuilder.DEBUG)
-// System.out.println("Deleting class file of removed type " + typePath); //$NON-NLS-1$
-// classFile.delete(IResource.FORCE, null);
-// }
-//}
-
-//protected void removeSecondaryTypes() throws CoreException {
-// if (secondaryTypesToRemove != null) { // delayed deleting secondary types until the end of the compile loop
-// Object[] keyTable = secondaryTypesToRemove.keyTable;
-// Object[] valueTable = secondaryTypesToRemove.valueTable;
-// for (int i = 0, l = keyTable.length; i < l; i++) {
-// IContainer outputFolder = (IContainer) keyTable[i];
-// if (outputFolder != null) {
-// ArrayList paths = (ArrayList) valueTable[i];
-// for (int j = 0, m = paths.size(); j < m; j++)
-// removeClassFile((IPath) paths.get(j), outputFolder);
-// }
-// }
-// this.secondaryTypesToRemove = null;
-// if (previousSourceFiles != null)
-// this.previousSourceFiles = null; // cannot optimize recompile case when a secondary type is deleted, see 181269
-// }
-//}
-
-protected void resetCollections() {
- if (this.sourceFiles == null) {
- this.sourceFiles = new ArrayList(33);
- this.previousSourceFiles = null;
- this.qualifiedStrings = new StringSet(3);
- this.simpleStrings = new StringSet(3);
- this.hasStructuralChanges = false;
- this.compileLoop = 0;
- } else {
- this.previousSourceFiles = this.sourceFiles.isEmpty() ? null : (ArrayList) this.sourceFiles.clone();
-
- this.sourceFiles.clear();
- this.qualifiedStrings.clear();
- this.simpleStrings.clear();
- this.workQueue.clear();
- }
-}
-
-protected void updateProblemsFor(SourceFile sourceFile, CompilationResult result) throws CoreException {
- IMarker[] markers = JavaBuilder.getProblemsFor(sourceFile.resource);
- CategorizedProblem[] problems = result.getProblems();
- if (problems == null && markers.length == 0) return;
-
- notifier.updateProblemCounts(markers, problems);
- JavaBuilder.removeProblemsFor(sourceFile.resource);
- storeProblemsFor(sourceFile, problems);
-}
-
-protected void updateTasksFor(SourceFile sourceFile, CompilationResult result) throws CoreException {
- IMarker[] markers = JavaBuilder.getTasksFor(sourceFile.resource);
- CategorizedProblem[] tasks = result.getTasks();
- if (tasks == null && markers.length == 0) return;
-
- JavaBuilder.removeTasksFor(sourceFile.resource);
- storeTasksFor(sourceFile, tasks);
-}
-
-public String toString() {
- return "incremental image builder for:\n\tnew state: " + newState; //$NON-NLS-1$
-}
-
-
-/* Debug helper
-
-static void dump(IResourceDelta delta) {
- StringBuffer buffer = new StringBuffer();
- IPath path = delta.getFullPath();
- for (int i = path.segmentCount(); --i > 0;)
- buffer.append(" ");
- switch (delta.getKind()) {
- case IResourceDelta.ADDED:
- buffer.append('+');
- break;
- case IResourceDelta.REMOVED:
- buffer.append('-');
- break;
- case IResourceDelta.CHANGED:
- buffer.append('*');
- break;
- case IResourceDelta.NO_CHANGE:
- buffer.append('=');
- break;
- default:
- buffer.append('?');
- break;
- }
- buffer.append(path);
- System.out.println(buffer.toString());
- IResourceDelta[] children = delta.getAffectedChildren();
- for (int i = 0, l = children.length; i < l; i++)
- dump(children[i]);
-}
-*/
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/JavaBuilder.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/JavaBuilder.java
deleted file mode 100644
index 5daa39ce..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/JavaBuilder.java
+++ /dev/null
@@ -1,778 +0,0 @@
-/*******************************************************************************
- * 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.builder;
-
-import java.io.DataInputStream;
-import java.io.DataOutputStream;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.resources.ICommand;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.IncrementalProjectBuilder;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelMarker;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.compiler.ValidationParticipant;
-import org.eclipse.wst.jsdt.internal.compiler.util.SimpleLookupTable;
-import org.eclipse.wst.jsdt.internal.core.ClasspathEntry;
-import org.eclipse.wst.jsdt.internal.core.JavaModel;
-import org.eclipse.wst.jsdt.internal.core.JavaModelManager;
-import org.eclipse.wst.jsdt.internal.core.JavaProject;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-public class JavaBuilder extends IncrementalProjectBuilder {
-
-IProject currentProject;
-JavaProject javaProject;
-IWorkspaceRoot workspaceRoot;
-ValidationParticipant[] participants;
-NameEnvironment nameEnvironment;
-SimpleLookupTable binaryLocationsPerProject; // maps a project to its binary resources (output folders, class folders, zip/jar files)
-public State lastState;
-BuildNotifier notifier;
-char[][] extraResourceFileFilters;
-String[] extraResourceFolderFilters;
-public static final String SOURCE_ID = "JSDT"; //$NON-NLS-1$
-
-public static boolean DEBUG = false;
-
-/**
- * A list of project names that have been built.
- * This list is used to reset the JavaModel.existingExternalFiles cache when a build cycle begins
- * so that deleted external jars are discovered.
- */
-static ArrayList builtProjects = null;
-
-public static IMarker[] getProblemsFor(IResource resource) {
- try {
- if (resource != null && resource.exists()) {
- IMarker[] markers = resource.findMarkers(IJavaScriptModelMarker.JAVASCRIPT_MODEL_PROBLEM_MARKER, false, IResource.DEPTH_INFINITE);
- Set markerTypes = JavaModelManager.getJavaModelManager().validationParticipants.managedMarkerTypes();
- if (markerTypes.isEmpty()) return markers;
- ArrayList markerList = new ArrayList(5);
- for (int i = 0, length = markers.length; i < length; i++) {
- markerList.add(markers[i]);
- }
- Iterator iterator = markerTypes.iterator();
- while (iterator.hasNext()) {
- markers = resource.findMarkers((String) iterator.next(), false, IResource.DEPTH_INFINITE);
- for (int i = 0, length = markers.length; i < length; i++) {
- markerList.add(markers[i]);
- }
- }
- IMarker[] result;
- markerList.toArray(result = new IMarker[markerList.size()]);
- return result;
- }
- } catch (CoreException e) {
- // assume there are no problems
- }
- return new IMarker[0];
-}
-
-public static IMarker[] getTasksFor(IResource resource) {
- try {
- if (resource != null && resource.exists())
- return resource.findMarkers(IJavaScriptModelMarker.TASK_MARKER, false, IResource.DEPTH_INFINITE);
- } catch (CoreException e) {
- // assume there are no tasks
- }
- return new IMarker[0];
-}
-
-/**
- * Hook allowing to initialize some static state before a complete build iteration.
- * This hook is invoked during PRE_AUTO_BUILD notification
- */
-public static void buildStarting() {
- // build is about to start
-}
-
-/**
- * Hook allowing to reset some static state after a complete build iteration.
- * This hook is invoked during POST_AUTO_BUILD notification
- */
-public static void buildFinished() {
- BuildNotifier.resetProblemCounters();
-}
-
-public static void removeProblemsFor(IResource resource) {
- try {
- if (resource != null && resource.exists()) {
- resource.deleteMarkers(IJavaScriptModelMarker.JAVASCRIPT_MODEL_PROBLEM_MARKER, false, IResource.DEPTH_INFINITE);
-
- // delete managed markers
- Set markerTypes = JavaModelManager.getJavaModelManager().validationParticipants.managedMarkerTypes();
- if (markerTypes.size() == 0) return;
- Iterator iterator = markerTypes.iterator();
- while (iterator.hasNext())
- resource.deleteMarkers((String) iterator.next(), false, IResource.DEPTH_INFINITE);
- }
- } catch (CoreException e) {
- // assume there were no problems
- }
-}
-
-public static void removeTasksFor(IResource resource) {
- try {
- if (resource != null && resource.exists())
- resource.deleteMarkers(IJavaScriptModelMarker.TASK_MARKER, false, IResource.DEPTH_INFINITE);
- } catch (CoreException e) {
- // assume there were no problems
- }
-}
-
-public static void removeProblemsAndTasksFor(IResource resource) {
- try {
- if (resource != null && resource.exists()) {
- resource.deleteMarkers(IJavaScriptModelMarker.JAVASCRIPT_MODEL_PROBLEM_MARKER, false, IResource.DEPTH_INFINITE);
- resource.deleteMarkers(IJavaScriptModelMarker.TASK_MARKER, false, IResource.DEPTH_INFINITE);
-
- // delete managed markers
- Set markerTypes = JavaModelManager.getJavaModelManager().validationParticipants.managedMarkerTypes();
- if (markerTypes.size() == 0) return;
- Iterator iterator = markerTypes.iterator();
- while (iterator.hasNext())
- resource.deleteMarkers((String) iterator.next(), false, IResource.DEPTH_INFINITE);
- }
- } catch (CoreException e) {
- // assume there were no problems
- }
-}
-
-public static State readState(IProject project, DataInputStream in) throws IOException {
- return State.read(project, in);
-}
-
-public static void writeState(Object state, DataOutputStream out) throws IOException {
- ((State) state).write(out);
-}
-
-protected IProject[] build(int kind, Map ignored, IProgressMonitor monitor) throws CoreException {
- this.currentProject = getProject();
- if (currentProject == null || !currentProject.isAccessible()) return new IProject[0];
-
- if (DEBUG)
- System.out.println("\nStarting build of " + currentProject.getName() //$NON-NLS-1$
- + " @ " + new Date(System.currentTimeMillis())); //$NON-NLS-1$
- this.notifier = new BuildNotifier(monitor, currentProject);
- notifier.begin();
- boolean ok = false;
- try {
- notifier.checkCancel();
- kind = initializeBuilder(kind, true);
-
- if (isWorthBuilding()) {
- if (kind == FULL_BUILD) {
- if (DEBUG)
- System.out.println("Performing full build as requested by user"); //$NON-NLS-1$
- buildAll();
- } else {
- if ((this.lastState = getLastState(currentProject)) == null) {
- if (DEBUG)
- System.out.println("Performing full build since last saved state was not found"); //$NON-NLS-1$
- buildAll();
- } else if (hasClasspathChanged()) {
- // if the output location changes, do not delete the binary files from old location
- // the user may be trying something
- if (DEBUG)
- System.out.println("Performing full build since classpath has changed"); //$NON-NLS-1$
- buildAll();
- } else if (nameEnvironment.sourceLocations.length > 0) {
- // if there is no source to compile & no classpath changes then we are done
- SimpleLookupTable deltas = findDeltas();
- if (deltas == null) {
- if (DEBUG)
- System.out.println("Performing full build since deltas are missing after incremental request"); //$NON-NLS-1$
- buildAll();
- } else if (deltas.elementSize > 0) {
- buildDeltas(deltas);
- } else if (DEBUG) {
- System.out.println("Nothing to build since deltas were empty"); //$NON-NLS-1$
- }
- } else {
- if (hasStructuralDelta()) { // double check that a jar file didn't get replaced in a binary project
- if (DEBUG)
- System.out.println("Performing full build since there are structural deltas"); //$NON-NLS-1$
- buildAll();
- } else {
- if (DEBUG)
- System.out.println("Nothing to build since there are no source folders and no deltas"); //$NON-NLS-1$
- lastState.tagAsNoopBuild();
- }
- }
- }
- ok = true;
- }
- } catch (CoreException e) {
- Util.log(e, "JavaBuilder handling CoreException while building: " + currentProject.getName()); //$NON-NLS-1$
- IMarker marker = currentProject.createMarker(IJavaScriptModelMarker.JAVASCRIPT_MODEL_PROBLEM_MARKER);
- marker.setAttributes(
- new String[] {IMarker.MESSAGE, IMarker.SEVERITY, IJavaScriptModelMarker.CATEGORY_ID, IMarker.SOURCE_ID},
- new Object[] {
- Messages.bind(Messages.build_inconsistentProject, e.getLocalizedMessage()),
- new Integer(IMarker.SEVERITY_ERROR),
- new Integer(CategorizedProblem.CAT_BUILDPATH),
- JavaBuilder.SOURCE_ID
- }
- );
- } catch (ImageBuilderInternalException e) {
- Util.log(e.getThrowable(), "JavaBuilder handling ImageBuilderInternalException while building: " + currentProject.getName()); //$NON-NLS-1$
- IMarker marker = currentProject.createMarker(IJavaScriptModelMarker.JAVASCRIPT_MODEL_PROBLEM_MARKER);
- marker.setAttributes(
- new String[] {IMarker.MESSAGE, IMarker.SEVERITY, IJavaScriptModelMarker.CATEGORY_ID, IMarker.SOURCE_ID},
- new Object[] {
- Messages.bind(Messages.build_inconsistentProject, e.getLocalizedMessage()),
- new Integer(IMarker.SEVERITY_ERROR),
- new Integer(CategorizedProblem.CAT_BUILDPATH),
- JavaBuilder.SOURCE_ID
- }
- );
- } catch (MissingSourceFileException e) {
- // do not log this exception since its thrown to handle aborted compiles because of missing source files
- if (DEBUG)
- System.out.println(Messages.bind(Messages.build_missingSourceFile, e.missingSourceFile));
- removeProblemsAndTasksFor(currentProject); // make this the only problem for this project
- IMarker marker = currentProject.createMarker(IJavaScriptModelMarker.JAVASCRIPT_MODEL_PROBLEM_MARKER);
- marker.setAttributes(
- new String[] {IMarker.MESSAGE, IMarker.SEVERITY, IMarker.SOURCE_ID},
- new Object[] {
- Messages.bind(Messages.build_missingSourceFile, e.missingSourceFile),
- new Integer(IMarker.SEVERITY_ERROR),
- JavaBuilder.SOURCE_ID
- }
- );
- } finally {
- if (!ok)
- // If the build failed, clear the previously built state, forcing a full build next time.
- clearLastState();
- notifier.done();
- cleanup();
- }
- IProject[] requiredProjects = getRequiredProjects(true);
- if (DEBUG)
- System.out.println("Finished build of " + currentProject.getName() //$NON-NLS-1$
- + " @ " + new Date(System.currentTimeMillis())); //$NON-NLS-1$
- return requiredProjects;
-}
-
-private void buildAll() {
- notifier.checkCancel();
- notifier.subTask(Messages.bind(Messages.build_preparingBuild, this.currentProject.getName()));
- if (DEBUG && lastState != null)
- System.out.println("Clearing last state : " + lastState); //$NON-NLS-1$
- clearLastState();
- BatchImageBuilder imageBuilder = new BatchImageBuilder(this, true);
- imageBuilder.build();
- recordNewState(imageBuilder.newState);
-}
-
-private void buildDeltas(SimpleLookupTable deltas) {
- notifier.checkCancel();
- notifier.subTask(Messages.bind(Messages.build_preparingBuild, this.currentProject.getName()));
- if (DEBUG && lastState != null)
- System.out.println("Clearing last state : " + lastState); //$NON-NLS-1$
- clearLastState(); // clear the previously built state so if the build fails, a full build will occur next time
- IncrementalImageBuilder imageBuilder = new IncrementalImageBuilder(this);
- if (imageBuilder.build(deltas)) {
- recordNewState(imageBuilder.newState);
- } else {
- if (DEBUG)
- System.out.println("Performing full build since incremental build failed"); //$NON-NLS-1$
- buildAll();
- }
-}
-
-protected void clean(IProgressMonitor monitor) throws CoreException {
- this.currentProject = getProject();
- if (currentProject == null || !currentProject.isAccessible()) return;
-
- if (DEBUG)
- System.out.println("\nCleaning " + currentProject.getName() //$NON-NLS-1$
- + " @ " + new Date(System.currentTimeMillis())); //$NON-NLS-1$
- this.notifier = new BuildNotifier(monitor, currentProject);
- notifier.begin();
- try {
- notifier.checkCancel();
-
- initializeBuilder(CLEAN_BUILD, true);
- if (DEBUG)
- System.out.println("Clearing last state as part of clean : " + lastState); //$NON-NLS-1$
- clearLastState();
- removeProblemsAndTasksFor(currentProject);
-// new BatchImageBuilder(this, false).cleanOutputFolders(false);
- } catch (CoreException e) {
- Util.log(e, "JavaBuilder handling CoreException while cleaning: " + currentProject.getName()); //$NON-NLS-1$
- IMarker marker = currentProject.createMarker(IJavaScriptModelMarker.JAVASCRIPT_MODEL_PROBLEM_MARKER);
- marker.setAttributes(
- new String[] {IMarker.MESSAGE, IMarker.SEVERITY, IMarker.SOURCE_ID},
- new Object[] {
- Messages.bind(Messages.build_inconsistentProject, e.getLocalizedMessage()),
- new Integer(IMarker.SEVERITY_ERROR),
- JavaBuilder.SOURCE_ID
- }
- );
- } finally {
- notifier.done();
- cleanup();
- }
- if (DEBUG)
- System.out.println("Finished cleaning " + currentProject.getName() //$NON-NLS-1$
- + " @ " + new Date(System.currentTimeMillis())); //$NON-NLS-1$
-}
-
-private void cleanup() {
- this.participants = null;
- this.nameEnvironment = null;
- this.binaryLocationsPerProject = null;
- this.lastState = null;
- this.notifier = null;
- this.extraResourceFileFilters = null;
- this.extraResourceFolderFilters = null;
-}
-
-private void clearLastState() {
- JavaModelManager.getJavaModelManager().setLastBuiltState(currentProject, null);
-}
-
-boolean filterExtraResource(IResource resource) {
- if (extraResourceFileFilters != null) {
- char[] name = resource.getName().toCharArray();
- for (int i = 0, l = extraResourceFileFilters.length; i < l; i++)
- if (CharOperation.match(extraResourceFileFilters[i], name, true))
- return true;
- }
- if (extraResourceFolderFilters != null) {
- IPath path = resource.getProjectRelativePath();
- String pathName = path.toString();
- int count = path.segmentCount();
- if (resource.getType() == IResource.FILE) count--;
- for (int i = 0, l = extraResourceFolderFilters.length; i < l; i++)
- if (pathName.indexOf(extraResourceFolderFilters[i]) != -1)
- for (int j = 0; j < count; j++)
- if (extraResourceFolderFilters[i].equals(path.segment(j)))
- return true;
- }
- return false;
-}
-
-private SimpleLookupTable findDeltas() {
- notifier.subTask(Messages.bind(Messages.build_readingDelta, currentProject.getName()));
- IResourceDelta delta = getDelta(currentProject);
- SimpleLookupTable deltas = new SimpleLookupTable(3);
- if (delta != null) {
- if (delta.getKind() != IResourceDelta.NO_CHANGE) {
- if (DEBUG)
- System.out.println("Found source delta for: " + currentProject.getName()); //$NON-NLS-1$
- deltas.put(currentProject, delta);
- }
- } else {
- if (DEBUG)
- System.out.println("Missing delta for: " + currentProject.getName()); //$NON-NLS-1$
- notifier.subTask(""); //$NON-NLS-1$
- return null;
- }
-
- Object[] keyTable = binaryLocationsPerProject.keyTable;
- Object[] valueTable = binaryLocationsPerProject.valueTable;
- nextProject : for (int i = 0, l = keyTable.length; i < l; i++) {
- IProject p = (IProject) keyTable[i];
- if (p != null && p != currentProject) {
- State s = getLastState(p);
- if (!lastState.wasStructurallyChanged(p, s)) { // see if we can skip its delta
- if (s.wasNoopBuild())
- continue nextProject; // project has no source folders and can be skipped
- ClasspathLocation[] classFoldersAndJars = (ClasspathLocation[]) valueTable[i];
- boolean canSkip = true;
- for (int j = 0, m = classFoldersAndJars.length; j < m; j++) {
- if (classFoldersAndJars[j].isOutputFolder())
- classFoldersAndJars[j] = null; // can ignore output folder since project was not structurally changed
- else
- canSkip = false;
- }
- if (canSkip) continue nextProject; // project has no structural changes in its output folders
- }
-
- notifier.subTask(Messages.bind(Messages.build_readingDelta, p.getName()));
- delta = getDelta(p);
- if (delta != null) {
- if (delta.getKind() != IResourceDelta.NO_CHANGE) {
- if (DEBUG)
- System.out.println("Found binary delta for: " + p.getName()); //$NON-NLS-1$
- deltas.put(p, delta);
- }
- } else {
- if (DEBUG)
- System.out.println("Missing delta for: " + p.getName()); //$NON-NLS-1$
- notifier.subTask(""); //$NON-NLS-1$
- return null;
- }
- }
- }
- notifier.subTask(""); //$NON-NLS-1$
- return deltas;
-}
-
-public State getLastState(IProject project) {
- return (State) JavaModelManager.getJavaModelManager().getLastBuiltState(project, notifier.monitor);
-}
-
-/* Return the list of projects for which it requires a resource delta. This builder's project
-* is implicitly included and need not be specified. Builders must re-specify the list
-* of interesting projects every time they are run as this is not carried forward
-* beyond the next build. Missing projects should be specified but will be ignored until
-* they are added to the workspace.
-*/
-private IProject[] getRequiredProjects(boolean includeBinaryPrerequisites) {
- if (javaProject == null || workspaceRoot == null) return new IProject[0];
-
- ArrayList projects = new ArrayList();
- try {
- IIncludePathEntry[] entries = javaProject.getExpandedClasspath();
- for (int i = 0, l = entries.length; i < l; i++) {
- IIncludePathEntry entry = entries[i];
- IPath path = entry.getPath();
- IProject p = null;
- switch (entry.getEntryKind()) {
- case IIncludePathEntry.CPE_PROJECT :
- p = workspaceRoot.getProject(path.lastSegment()); // missing projects are considered too
- if (((ClasspathEntry) entry).isOptional() && !JavaProject.hasJavaNature(p)) // except if entry is optional
- p = null;
- break;
- case IIncludePathEntry.CPE_LIBRARY :
- if (includeBinaryPrerequisites && path.segmentCount() > 1) {
- // some binary resources on the class path can come from projects that are not included in the project references
- IResource resource = workspaceRoot.findMember(path.segment(0));
- if (resource instanceof IProject)
- p = (IProject) resource;
- }
- }
- if (p != null && !projects.contains(p))
- projects.add(p);
- }
- } catch(JavaScriptModelException e) {
- return new IProject[0];
- }
- IProject[] result = new IProject[projects.size()];
- projects.toArray(result);
- return result;
-}
-
-boolean hasBuildpathErrors() throws CoreException {
-// IMarker[] markers = this.currentProject.findMarkers(IJavaScriptModelMarker.JAVASCRIPT_MODEL_PROBLEM_MARKER, false, IResource.DEPTH_ZERO);
-// for (int i = 0, l = markers.length; i < l; i++)
-// if (markers[i].getAttribute(IJavaScriptModelMarker.CATEGORY_ID, -1) == CategorizedProblem.CAT_BUILDPATH)
-// return true;
- return false;
-}
-
-private boolean hasClasspathChanged() {
- ClasspathMultiDirectory[] newSourceLocations = nameEnvironment.sourceLocations;
- ClasspathMultiDirectory[] oldSourceLocations = lastState.sourceLocations;
- int newLength = newSourceLocations.length;
- int oldLength = oldSourceLocations.length;
- int n, o;
- for (n = o = 0; n < newLength && o < oldLength; n++, o++) {
- if (newSourceLocations[n].equals(oldSourceLocations[o])) continue; // checks source & output folders
- try {
- if (newSourceLocations[n].sourceFolder.members().length == 0) { // added new empty source folder
- o--;
- continue;
- }
- } catch (CoreException ignore) { // skip it
- }
- if (DEBUG) {
- System.out.println("New location: " + newSourceLocations[n] + "\n!= old location: " + oldSourceLocations[o]); //$NON-NLS-1$ //$NON-NLS-2$
- printLocations(newSourceLocations, oldSourceLocations);
- }
- return true;
- }
- while (n < newLength) {
- try {
- if (newSourceLocations[n].sourceFolder.members().length == 0) { // added new empty source folder
- n++;
- continue;
- }
- } catch (CoreException ignore) { // skip it
- }
- if (DEBUG) {
- System.out.println("Added non-empty source folder"); //$NON-NLS-1$
- printLocations(newSourceLocations, oldSourceLocations);
- }
- return true;
- }
- if (o < oldLength) {
- if (DEBUG) {
- System.out.println("Removed source folder"); //$NON-NLS-1$
- printLocations(newSourceLocations, oldSourceLocations);
- }
- return true;
- }
-
- ClasspathLocation[] newBinaryLocations = nameEnvironment.binaryLocations;
- ClasspathLocation[] oldBinaryLocations = lastState.binaryLocations;
- newLength = newBinaryLocations.length;
- oldLength = oldBinaryLocations.length;
- for (n = o = 0; n < newLength && o < oldLength; n++, o++) {
- if (newBinaryLocations[n].equals(oldBinaryLocations[o])) continue;
- if (DEBUG) {
- System.out.println("New location: " + newBinaryLocations[n] + "\n!= old location: " + oldBinaryLocations[o]); //$NON-NLS-1$ //$NON-NLS-2$
- printLocations(newBinaryLocations, oldBinaryLocations);
- }
- return true;
- }
- if (n < newLength || o < oldLength) {
- if (DEBUG) {
- System.out.println("Number of binary folders/jar files has changed:"); //$NON-NLS-1$
- printLocations(newBinaryLocations, oldBinaryLocations);
- }
- return true;
- }
- return false;
-}
-
-private boolean hasJavaBuilder(IProject project) throws CoreException {
- ICommand[] buildCommands = project.getDescription().getBuildSpec();
- for (int i = 0, l = buildCommands.length; i < l; i++)
- if (buildCommands[i].getBuilderName().equals(JavaScriptCore.BUILDER_ID))
- return true;
- return false;
-}
-
-private boolean hasStructuralDelta() {
- // handle case when currentProject has only .class file folders and/or jar files... no source/output folders
- IResourceDelta delta = getDelta(currentProject);
- if (delta != null && delta.getKind() != IResourceDelta.NO_CHANGE) {
- ClasspathLocation[] classFoldersAndJars = (ClasspathLocation[]) binaryLocationsPerProject.get(currentProject);
- if (classFoldersAndJars != null) {
- for (int i = 0, l = classFoldersAndJars.length; i < l; i++) {
- ClasspathLocation classFolderOrJar = classFoldersAndJars[i]; // either a .class file folder or a zip/jar file
- if (classFolderOrJar != null) {
- IPath p = classFolderOrJar.getProjectRelativePath();
- if (p != null) {
- IResourceDelta binaryDelta = delta.findMember(p);
- if (binaryDelta != null && binaryDelta.getKind() != IResourceDelta.NO_CHANGE)
- return true;
- }
- }
- }
- }
- }
- return false;
-}
-
-private int initializeBuilder(int kind, boolean forBuild) throws CoreException {
- // some calls just need the nameEnvironment initialized so skip the rest
- this.javaProject = (JavaProject) JavaScriptCore.create(currentProject);
- this.workspaceRoot = currentProject.getWorkspace().getRoot();
-
- if (forBuild) {
- // cache the known participants for this project
- this.participants = JavaModelManager.getJavaModelManager().validationParticipants.getvalidationParticipants(this.javaProject);
- if (this.participants != null)
- for (int i = 0, l = this.participants.length; i < l; i++)
- if (this.participants[i].aboutToBuild(this.javaProject) == ValidationParticipant.NEEDS_FULL_BUILD)
- kind = FULL_BUILD;
-
- // Flush the existing external files cache if this is the beginning of a build cycle
- String projectName = currentProject.getName();
- if (builtProjects == null || builtProjects.contains(projectName)) {
- JavaModel.flushExternalFileCache();
- builtProjects = new ArrayList();
- }
- builtProjects.add(projectName);
- }
-
- this.binaryLocationsPerProject = new SimpleLookupTable(3);
- this.nameEnvironment = new NameEnvironment(workspaceRoot, javaProject, binaryLocationsPerProject, notifier);
-
- if (forBuild) {
- String filterSequence = javaProject.getOption(JavaScriptCore.CORE_JAVA_BUILD_RESOURCE_COPY_FILTER, true);
- char[][] filters = filterSequence != null && filterSequence.length() > 0
- ? CharOperation.splitAndTrimOn(',', filterSequence.toCharArray())
- : null;
- if (filters == null) {
- this.extraResourceFileFilters = null;
- this.extraResourceFolderFilters = null;
- } else {
- int fileCount = 0, folderCount = 0;
- for (int i = 0, l = filters.length; i < l; i++) {
- char[] f = filters[i];
- if (f.length == 0) continue;
- if (f[f.length - 1] == '/') folderCount++; else fileCount++;
- }
- this.extraResourceFileFilters = new char[fileCount][];
- this.extraResourceFolderFilters = new String[folderCount];
- for (int i = 0, l = filters.length; i < l; i++) {
- char[] f = filters[i];
- if (f.length == 0) continue;
- if (f[f.length - 1] == '/')
- extraResourceFolderFilters[--folderCount] = new String(f, 0, f.length - 1);
- else
- extraResourceFileFilters[--fileCount] = f;
- }
- }
- }
- return kind;
-}
-
-private boolean isClasspathBroken(IIncludePathEntry[] classpath, IProject p) throws CoreException {
- IMarker[] markers = p.findMarkers(IJavaScriptModelMarker.BUILDPATH_PROBLEM_MARKER, false, IResource.DEPTH_ZERO);
- for (int i = 0, l = markers.length; i < l; i++)
- if (markers[i].getAttribute(IMarker.SEVERITY, -1) == IMarker.SEVERITY_ERROR)
- return true;
- return false;
-}
-
-private boolean isWorthBuilding() throws CoreException {
- boolean abortBuilds =
- JavaScriptCore.ABORT.equals(javaProject.getOption(JavaScriptCore.CORE_JAVA_BUILD_INVALID_CLASSPATH, true));
- if (!abortBuilds) return true;
-
- // Abort build only if there are classpath errors
- if (isClasspathBroken(javaProject.getRawIncludepath(), currentProject)) {
- if (DEBUG)
- System.out.println("Aborted build because project has classpath errors (incomplete or involved in cycle)"); //$NON-NLS-1$
-
- removeProblemsAndTasksFor(currentProject); // remove all compilation problems
-
- IMarker marker = currentProject.createMarker(IJavaScriptModelMarker.JAVASCRIPT_MODEL_PROBLEM_MARKER);
- marker.setAttributes(
- new String[] {IMarker.MESSAGE, IMarker.SEVERITY, IJavaScriptModelMarker.CATEGORY_ID, IMarker.SOURCE_ID},
- new Object[] {
- Messages.build_abortDueToClasspathProblems,
- new Integer(IMarker.SEVERITY_ERROR),
- new Integer(CategorizedProblem.CAT_BUILDPATH),
- JavaBuilder.SOURCE_ID
- }
- );
- return false;
- }
-
- if (JavaScriptCore.WARNING.equals(javaProject.getOption(JavaScriptCore.CORE_INCOMPLETE_CLASSPATH, true)))
- return true;
-
- // make sure all prereq projects have valid build states... only when aborting builds since projects in cycles do not have build states
- // except for projects involved in a 'warning' cycle (see below)
- IProject[] requiredProjects = getRequiredProjects(false);
- for (int i = 0, l = requiredProjects.length; i < l; i++) {
- IProject p = requiredProjects[i];
- if (getLastState(p) == null) {
- // The prereq project has no build state: if this prereq project has a 'warning' cycle marker then allow build (see bug id 23357)
- JavaProject prereq = (JavaProject) JavaScriptCore.create(p);
- if (prereq.hasCycleMarker() && JavaScriptCore.WARNING.equals(javaProject.getOption(JavaScriptCore.CORE_CIRCULAR_CLASSPATH, true))) {
- if (DEBUG)
- System.out.println("Continued to build even though prereq project " + p.getName() //$NON-NLS-1$
- + " was not built since its part of a cycle"); //$NON-NLS-1$
- continue;
- }
- if (!hasJavaBuilder(p)) {
- if (DEBUG)
- System.out.println("Continued to build even though prereq project " + p.getName() //$NON-NLS-1$
- + " is not built by JavaBuilder"); //$NON-NLS-1$
- continue;
- }
- if (DEBUG)
- System.out.println("Aborted build because prereq project " + p.getName() //$NON-NLS-1$
- + " was not built"); //$NON-NLS-1$
-
- removeProblemsAndTasksFor(currentProject); // make this the only problem for this project
- IMarker marker = currentProject.createMarker(IJavaScriptModelMarker.JAVASCRIPT_MODEL_PROBLEM_MARKER);
- marker.setAttributes(
- new String[] {IMarker.MESSAGE, IMarker.SEVERITY, IJavaScriptModelMarker.CATEGORY_ID, IMarker.SOURCE_ID},
- new Object[] {
- isClasspathBroken(prereq.getRawIncludepath(), p)
- ? Messages.bind(Messages.build_prereqProjectHasClasspathProblems, p.getName())
- : Messages.bind(Messages.build_prereqProjectMustBeRebuilt, p.getName()),
- new Integer(IMarker.SEVERITY_ERROR),
- new Integer(CategorizedProblem.CAT_BUILDPATH),
- JavaBuilder.SOURCE_ID
- }
- );
- return false;
- }
- }
- return true;
-}
-
-/*
- * Instruct the build manager that this project is involved in a cycle and
- * needs to propagate structural changes to the other projects in the cycle.
- */
-void mustPropagateStructuralChanges() {
- HashSet cycleParticipants = new HashSet(3);
- javaProject.updateCycleParticipants(new ArrayList(), cycleParticipants, workspaceRoot, new HashSet(3), null);
- IPath currentPath = javaProject.getPath();
- Iterator i= cycleParticipants.iterator();
- while (i.hasNext()) {
- IPath participantPath = (IPath) i.next();
- if (participantPath != currentPath) {
- IProject project = workspaceRoot.getProject(participantPath.segment(0));
- if (hasBeenBuilt(project)) {
- if (DEBUG)
- System.out.println("Requesting another build iteration since cycle participant " + project.getName() //$NON-NLS-1$
- + " has not yet seen some structural changes"); //$NON-NLS-1$
- needRebuild();
- return;
- }
- }
- }
-}
-
-private void printLocations(ClasspathLocation[] newLocations, ClasspathLocation[] oldLocations) {
- System.out.println("New locations:"); //$NON-NLS-1$
- for (int i = 0, length = newLocations.length; i < length; i++)
- System.out.println(" " + newLocations[i].debugPathString()); //$NON-NLS-1$
- System.out.println("Old locations:"); //$NON-NLS-1$
- for (int i = 0, length = oldLocations.length; i < length; i++)
- System.out.println(" " + oldLocations[i].debugPathString()); //$NON-NLS-1$
-}
-
-private void recordNewState(State state) {
- Object[] keyTable = binaryLocationsPerProject.keyTable;
- for (int i = 0, l = keyTable.length; i < l; i++) {
- IProject prereqProject = (IProject) keyTable[i];
- if (prereqProject != null && prereqProject != currentProject)
- state.recordStructuralDependency(prereqProject, getLastState(prereqProject));
- }
-
- if (DEBUG)
- System.out.println("Recording new state : " + state); //$NON-NLS-1$
- // state.dump();
- JavaModelManager.getJavaModelManager().setLastBuiltState(currentProject, state);
-}
-
-/**
- * String representation for debugging purposes
- */
-public String toString() {
- return currentProject == null
- ? "JavaBuilder for unknown project" //$NON-NLS-1$
- : "JavaBuilder for " + currentProject.getName(); //$NON-NLS-1$
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/MissingSourceFileException.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/MissingSourceFileException.java
deleted file mode 100644
index a5aff47c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/MissingSourceFileException.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.builder;
-
-/**
- * Exception thrown when the build should be aborted because a source file is missing/empty.
- */
-public class MissingSourceFileException extends RuntimeException {
-
- protected String missingSourceFile;
- private static final long serialVersionUID = -1416609004971115719L; // backward compatible
-
-public MissingSourceFileException(String missingSourceFile) {
- this.missingSourceFile = missingSourceFile;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/NameEnvironment.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/NameEnvironment.java
deleted file mode 100644
index 5dc5264c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/NameEnvironment.java
+++ /dev/null
@@ -1,484 +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.builder;
-
-import java.io.File;
-import java.util.ArrayList;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.wst.jsdt.core.IIncludePathAttribute;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.compiler.env.AccessRuleSet;
-import org.eclipse.wst.jsdt.internal.compiler.env.INameEnvironment;
-import org.eclipse.wst.jsdt.internal.compiler.env.NameEnvironmentAnswer;
-import org.eclipse.wst.jsdt.internal.compiler.impl.ITypeRequestor;
-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.SuffixConstants;
-import org.eclipse.wst.jsdt.internal.core.ClasspathEntry;
-import org.eclipse.wst.jsdt.internal.core.CompilationUnit;
-import org.eclipse.wst.jsdt.internal.core.JavaModel;
-import org.eclipse.wst.jsdt.internal.core.JavaProject;
-import org.eclipse.wst.jsdt.internal.core.SearchableEnvironment;
-
-public class NameEnvironment implements INameEnvironment, SuffixConstants {
-
-boolean isIncrementalBuild;
-ClasspathMultiDirectory[] sourceLocations;
-ClasspathLocation[] binaryLocations;
-BuildNotifier notifier;
-
-SimpleSet initialTypeNames; // assumed that each name is of the form "a/b/ClassName"
-SimpleLookupTable additionalUnits;
-SearchableEnvironment searchableEnvironment;
-
-NameEnvironment(IWorkspaceRoot root, JavaProject javaProject, SimpleLookupTable binaryLocationsPerProject, BuildNotifier notifier) throws CoreException {
- this.isIncrementalBuild = false;
- this.notifier = notifier;
- computeClasspathLocations(root, javaProject, binaryLocationsPerProject);
-// setNames(null, null);
- this.searchableEnvironment=javaProject.newSearchableNameEnvironment(new IJavaScriptUnit[0]);
-}
-
-public NameEnvironment(IJavaScriptProject javaProject) {
- this.isIncrementalBuild = false;
- try {
- computeClasspathLocations(javaProject.getProject().getWorkspace().getRoot(), (JavaProject) javaProject, null);
- } catch(CoreException e) {
- this.sourceLocations = new ClasspathMultiDirectory[0];
- this.binaryLocations = new ClasspathLocation[0];
- }
-// setNames(null, null);
- try {
- this.searchableEnvironment=javaProject.newSearchableNameEnvironment(new IJavaScriptUnit[0]);
- } catch (JavaScriptModelException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-}
-
-/* Some examples of resolved class path entries.
-* Remember to search class path in the order that it was defined.
-*
-* 1a. typical project with no source folders:
-* /Test[CPE_SOURCE][K_SOURCE] -> D:/eclipse.test/Test
-* 1b. project with source folders:
-* /Test/src1[CPE_SOURCE][K_SOURCE] -> D:/eclipse.test/Test/src1
-* /Test/src2[CPE_SOURCE][K_SOURCE] -> D:/eclipse.test/Test/src2
-* NOTE: These can be in any order & separated by prereq projects or libraries
-* 1c. project external to workspace (only detectable using getLocation()):
-* /Test/src[CPE_SOURCE][K_SOURCE] -> d:/eclipse.zzz/src
-* Need to search source folder & output folder
-*
-* 2. zip files:
-* D:/j9/lib/jclMax/classes.zip[CPE_LIBRARY][K_BINARY][sourcePath:d:/j9/lib/jclMax/source/source.zip]
-* -> D:/j9/lib/jclMax/classes.zip
-* ALWAYS want to take the library path as is
-*
-* 3a. prereq project (regardless of whether it has a source or output folder):
-* /Test[CPE_PROJECT][K_SOURCE] -> D:/eclipse.test/Test
-* ALWAYS want to append the output folder & ONLY search for .class files
-*/
-private void computeClasspathLocations(
- IWorkspaceRoot root,
- JavaProject javaProject,
- SimpleLookupTable binaryLocationsPerProject) throws CoreException {
-
- /* Update cycle marker */
- IMarker cycleMarker = javaProject.getCycleMarker();
- if (cycleMarker != null) {
- int severity = JavaScriptCore.ERROR.equals(javaProject.getOption(JavaScriptCore.CORE_CIRCULAR_CLASSPATH, true))
- ? IMarker.SEVERITY_ERROR
- : IMarker.SEVERITY_WARNING;
- if (severity != cycleMarker.getAttribute(IMarker.SEVERITY, severity))
- cycleMarker.setAttribute(IMarker.SEVERITY, severity);
- }
-
- IIncludePathEntry[] classpathEntries = javaProject.getExpandedClasspath();
- ArrayList sLocations = new ArrayList(classpathEntries.length);
- ArrayList bLocations = new ArrayList(classpathEntries.length);
- nextEntry : for (int i = 0, l = classpathEntries.length; i < l; i++) {
- ClasspathEntry entry = (ClasspathEntry) classpathEntries[i];
- IPath path = entry.getPath();
- Object target = JavaModel.getTarget(root, path, true);
- if (target == null) continue nextEntry;
-
- IIncludePathAttribute[] attribs = entry.getExtraAttributes();
-
- for(int k=0;attribs!=null && k<attribs.length;k++) {
- if(attribs[k].getName().equalsIgnoreCase("validate") && attribs[k].getValue().equalsIgnoreCase("false")) continue nextEntry; //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- switch(entry.getEntryKind()) {
- case IIncludePathEntry.CPE_SOURCE :
- if (!(target instanceof IContainer)) continue nextEntry;
-
- IPath outputPath = entry.getOutputLocation() != null
- ? entry.getOutputLocation()
- : javaProject.getOutputLocation();
- IContainer outputFolder;
- if (outputPath.segmentCount() == 1) {
- outputFolder = javaProject.getProject();
- } else {
- outputFolder = root.getFolder(outputPath);
- if (!outputFolder.exists())
- createOutputFolder(outputFolder);
- }
- sLocations.add(
- ClasspathLocation.forSourceFolder((IContainer) target, outputFolder, entry.fullInclusionPatternChars(), entry.fullExclusionPatternChars()));
- continue nextEntry;
-
- case IIncludePathEntry.CPE_PROJECT :
- if (!(target instanceof IProject)) continue nextEntry;
- IProject prereqProject = (IProject) target;
- if (!JavaProject.hasJavaNature(prereqProject)) continue nextEntry; // if project doesn't have java nature or is not accessible
-
- JavaProject prereqJavaProject = (JavaProject) JavaScriptCore.create(prereqProject);
- IIncludePathEntry[] prereqClasspathEntries = prereqJavaProject.getRawIncludepath();
- ArrayList seen = new ArrayList();
- nextPrereqEntry: for (int j = 0, m = prereqClasspathEntries.length; j < m; j++) {
- IIncludePathEntry prereqEntry = prereqClasspathEntries[j];
- if (prereqEntry.getEntryKind() == IIncludePathEntry.CPE_SOURCE) {
- Object prereqTarget = JavaModel.getTarget(root, prereqEntry.getPath(), true);
- if (!(prereqTarget instanceof IContainer)) continue nextPrereqEntry;
- IPath prereqOutputPath = prereqJavaProject.getOutputLocation();
- IContainer binaryFolder = prereqOutputPath.segmentCount() == 1
- ? (IContainer) prereqProject
- : (IContainer) root.getFolder(prereqOutputPath);
- if (binaryFolder.exists() && !seen.contains(binaryFolder)) {
- seen.add(binaryFolder);
- ClasspathLocation bLocation = ClasspathLocation.forBinaryFolder(binaryFolder, true, entry.getAccessRuleSet());
- bLocations.add(bLocation);
- if (binaryLocationsPerProject != null) { // normal builder mode
- ClasspathLocation[] existingLocations = (ClasspathLocation[]) binaryLocationsPerProject.get(prereqProject);
- if (existingLocations == null) {
- existingLocations = new ClasspathLocation[] {bLocation};
- } else {
- int size = existingLocations.length;
- System.arraycopy(existingLocations, 0, existingLocations = new ClasspathLocation[size + 1], 0, size);
- existingLocations[size] = bLocation;
- }
- binaryLocationsPerProject.put(prereqProject, existingLocations);
- }
- }
- }
- }
- continue nextEntry;
-
- case IIncludePathEntry.CPE_LIBRARY :
- if(true) continue nextEntry;
- if (target instanceof IResource) {
- IResource resource = (IResource) target;
- ClasspathLocation bLocation = null;
-// if (resource instanceof IFile) {
-// if (!(org.eclipse.wst.jsdt.internal.compiler.util.Util.isClassFileName(path.lastSegment())))
-// continue nextEntry;
-// AccessRuleSet accessRuleSet =
-// (JavaScriptCore.IGNORE.equals(javaProject.getOption(JavaScriptCore.COMPILER_PB_FORBIDDEN_REFERENCE, true))
-// && JavaScriptCore.IGNORE.equals(javaProject.getOption(JavaScriptCore.COMPILER_PB_DISCOURAGED_REFERENCE, true)))
-// ? null
-// : entry.getAccessRuleSet();
-// bLocation = ClasspathLocation.forLibrary((IFile) resource, accessRuleSet);
-// } else if (resource instanceof IContainer) {
-// AccessRuleSet accessRuleSet =
-// (JavaScriptCore.IGNORE.equals(javaProject.getOption(JavaScriptCore.COMPILER_PB_FORBIDDEN_REFERENCE, true))
-// && JavaScriptCore.IGNORE.equals(javaProject.getOption(JavaScriptCore.COMPILER_PB_DISCOURAGED_REFERENCE, true)))
-// ? null
-// : entry.getAccessRuleSet();
-// bLocation = ClasspathLocation.forBinaryFolder((IContainer) target, false, accessRuleSet); // is library folder not output folder
-// }
-// bLocations.add(bLocation);
- if (binaryLocationsPerProject != null) { // normal builder mode
- IProject p = resource.getProject(); // can be the project being built
- ClasspathLocation[] existingLocations = (ClasspathLocation[]) binaryLocationsPerProject.get(p);
- if (existingLocations == null) {
- existingLocations = new ClasspathLocation[] {bLocation};
- } else {
- int size = existingLocations.length;
- System.arraycopy(existingLocations, 0, existingLocations = new ClasspathLocation[size + 1], 0, size);
- existingLocations[size] = bLocation;
- }
- binaryLocationsPerProject.put(p, existingLocations);
- }
- } else if (target instanceof File) {
- if (!(org.eclipse.wst.jsdt.internal.compiler.util.Util.isClassFileName(path.lastSegment())))
- continue nextEntry;
- AccessRuleSet accessRuleSet =
- (JavaScriptCore.IGNORE.equals(javaProject.getOption(JavaScriptCore.COMPILER_PB_FORBIDDEN_REFERENCE, true))
- && JavaScriptCore.IGNORE.equals(javaProject.getOption(JavaScriptCore.COMPILER_PB_DISCOURAGED_REFERENCE, true)))
- ? null
- : entry.getAccessRuleSet();
- bLocations.add(ClasspathLocation.forLibrary(path.toString(), accessRuleSet));
- }
- continue nextEntry;
- }
- }
-
- // now split the classpath locations... place the output folders ahead of the other .class file folders & jars
- ArrayList outputFolders = new ArrayList(1);
- this.sourceLocations = new ClasspathMultiDirectory[sLocations.size()];
- if (!sLocations.isEmpty()) {
- sLocations.toArray(this.sourceLocations);
-
- // collect the output folders, skipping duplicates
- next : for (int i = 0, l = sourceLocations.length; i < l; i++) {
- ClasspathMultiDirectory md = sourceLocations[i];
- IPath outputPath = md.binaryFolder.getFullPath();
- for (int j = 0; j < i; j++) { // compare against previously walked source folders
- if (outputPath.equals(sourceLocations[j].binaryFolder.getFullPath())) {
- md.hasIndependentOutputFolder = sourceLocations[j].hasIndependentOutputFolder;
- continue next;
- }
- }
- outputFolders.add(md);
-
- // also tag each source folder whose output folder is an independent folder & is not also a source folder
- for (int j = 0, m = sourceLocations.length; j < m; j++)
- if (outputPath.equals(sourceLocations[j].sourceFolder.getFullPath()))
- continue next;
- md.hasIndependentOutputFolder = true;
- }
- }
-
- // combine the output folders with the binary folders & jars... place the output folders before other .class file folders & jars
- this.binaryLocations = new ClasspathLocation[outputFolders.size() + bLocations.size()];
- int index = 0;
- for (int i = 0, l = outputFolders.size(); i < l; i++)
- this.binaryLocations[index++] = (ClasspathLocation) outputFolders.get(i);
- for (int i = 0, l = bLocations.size(); i < l; i++)
- this.binaryLocations[index++] = (ClasspathLocation) bLocations.get(i);
-}
-
-public void cleanup() {
-// this.initialTypeNames = null;
-// this.additionalUnits = null;
-// for (int i = 0, l = sourceLocations.length; i < l; i++)
-// sourceLocations[i].cleanup();
-// for (int i = 0, l = binaryLocations.length; i < l; i++)
-// binaryLocations[i].cleanup();
- this.searchableEnvironment=null;
-}
-
-private void createOutputFolder(IContainer outputFolder) throws CoreException {
- createParentFolder(outputFolder.getParent());
- ((IFolder) outputFolder).create(IResource.FORCE | IResource.DERIVED, true, null);
-}
-
-private void createParentFolder(IContainer parent) throws CoreException {
- if (!parent.exists()) {
- createParentFolder(parent.getParent());
- ((IFolder) parent).create(true, true, null);
- }
-}
-
-//private NameEnvironmentAnswer findClass(String qualifiedTypeName, char[] typeName) {
-// if (this.notifier != null)
-// this.notifier.checkCancelWithinCompiler();
-//
-// if (this.initialTypeNames != null && this.initialTypeNames.includes(qualifiedTypeName)) {
-// if (isIncrementalBuild)
-// // catch the case that a type inside a source file has been renamed but other class files are looking for it
-// throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedTypeName));
-// return null; // looking for a file which we know was provided at the beginning of the compilation
-// }
-//
-// if (this.additionalUnits != null && this.sourceLocations.length > 0) {
-// // if an additional source file is waiting to be compiled, answer it BUT not if this is a secondary type search
-// // if we answer X.js & it no longer defines Y then the binary type looking for Y will think the class path is wrong
-// // let the recompile loop fix up dependents when the secondary type Y has been deleted from X.js
-// SourceFile unit = (SourceFile) this.additionalUnits.get(qualifiedTypeName); // doesn't have file extension
-// if (unit != null)
-// return new NameEnvironmentAnswer(unit, null /*no access restriction*/);
-// }
-//
-// String qBinaryFileName = qualifiedTypeName + SUFFIX_STRING_class;
-// String binaryFileName = qBinaryFileName;
-// String qPackageName = ""; //$NON-NLS-1$
-// if (qualifiedTypeName.length() > typeName.length) {
-// int typeNameStart = qBinaryFileName.length() - typeName.length - 6; // size of ".class"
-// qPackageName = qBinaryFileName.substring(0, typeNameStart - 1);
-// binaryFileName = qBinaryFileName.substring(typeNameStart);
-// }
-//
-// // NOTE: the output folders are added at the beginning of the binaryLocations
-// NameEnvironmentAnswer suggestedAnswer = null;
-// for (int i = 0, l = binaryLocations.length; i < l; i++) {
-// NameEnvironmentAnswer answer = binaryLocations[i].findClass(binaryFileName, qPackageName, qBinaryFileName);
-// if (answer != null) {
-// if (!answer.ignoreIfBetter()) {
-// if (answer.isBetter(suggestedAnswer))
-// return answer;
-// } else if (answer.isBetter(suggestedAnswer))
-// // remember suggestion and keep looking
-// suggestedAnswer = answer;
-// }
-// }
-// if (suggestedAnswer != null)
-// // no better answer was found
-// return suggestedAnswer;
-// return null;
-//}
-
-public NameEnvironmentAnswer findType(char[][] compoundName, ITypeRequestor requestor) {
-// if (compoundName != null)
-// return findClass(
-// new String(CharOperation.concatWith(compoundName, '/')),
-// compoundName[compoundName.length - 1]);
-// return null;
- return this.searchableEnvironment.findType(compoundName, requestor);
-}
-
-private SourceFile convertToSourceFile(CompilationUnit compilationUnit)
-{
- IPath path = compilationUnit.getPath();
- for (int i = 0; i < this.sourceLocations.length; i++) {
- IContainer srcFolder=sourceLocations[i].sourceFolder;
- if (srcFolder.getFullPath().isPrefixOf(path))
- {
- SourceFile sourceFile=new SourceFile((IFile)compilationUnit.getResource(),sourceLocations[i]);
- return sourceFile;
- }
- }
- return null;
-}
-
-private NameEnvironmentAnswer convertToSourceFile(NameEnvironmentAnswer answer)
-{
- if (answer==null )
- return answer;
-
- if (answer.getCompilationUnit() instanceof CompilationUnit) {
- CompilationUnit compilationUnit = (CompilationUnit) answer.getCompilationUnit();
- SourceFile sourceFile=convertToSourceFile(compilationUnit);
- if (sourceFile!=null)
- return new NameEnvironmentAnswer(sourceFile,answer.getAccessRestriction());
- }
- else if (answer.getCompilationUnits()!=null)
- {
- org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit[] compilationUnits = answer.getCompilationUnits();
- org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit[] newcompilationUnits =
- new org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit[compilationUnits.length];
- boolean newAnswer=false;
- for (int i = 0; i < compilationUnits.length; i++) {
- newcompilationUnits[i]=compilationUnits[i];
- if (compilationUnits[i] instanceof CompilationUnit) {
- SourceFile sourceFile=convertToSourceFile((CompilationUnit)compilationUnits[i]);
- if (sourceFile!=null)
- {
- newcompilationUnits[i]=sourceFile;
- newAnswer=true;
- }
-
- }
- }
- if (newAnswer)
- return new NameEnvironmentAnswer(newcompilationUnits,answer.getAccessRestriction());
- }
- return answer;
-}
-
-
-public NameEnvironmentAnswer findBinding(char[] bindingName, char[][] packageName, int type, ITypeRequestor requestor, boolean returnMultiple, String excludePath) {
- if (this.notifier != null)
- this.notifier.checkCancelWithinCompiler();
- NameEnvironmentAnswer answer= this.searchableEnvironment.findBinding(bindingName, packageName,type, requestor, returnMultiple, excludePath);
- answer=convertToSourceFile(answer);
- return answer;
-
-// String qBinaryFileName = qualifiedTypeName + SUFFIX_STRING_class;
-// String binaryFileName = qBinaryFileName;
-// String qPackageName = ""; //$NON-NLS-1$
-// if (qualifiedTypeName.length() > typeName.length) {
-// int typeNameStart = qBinaryFileName.length() - typeName.length - 6; // size of ".class"
-// qPackageName = qBinaryFileName.substring(0, typeNameStart - 1);
-// binaryFileName = qBinaryFileName.substring(typeNameStart);
-// }
-//
- // NOTE: the output folders are added at the beginning of the binaryLocations
-// NameEnvironmentAnswer suggestedAnswer = null;
-// for (int i = 0, l = binaryLocations.length; i < l; i++) {
-// NameEnvironmentAnswer answer = binaryLocations[i].findClass(binaryFileName, qPackageName, qBinaryFileName);
-// if (answer != null) {
-// if (!answer.ignoreIfBetter()) {
-// if (answer.isBetter(suggestedAnswer))
-// return answer;
-// } else if (answer.isBetter(suggestedAnswer))
-// // remember suggestion and keep looking
-// suggestedAnswer = answer;
-// }
-// }
-// if (suggestedAnswer != null)
-// // no better answer was found
-// return suggestedAnswer;
-// return null;
-}
-
-public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName, ITypeRequestor requestor) {
- return searchableEnvironment.findType( typeName,packageName, requestor);
-// if (typeName != null)
-// return findClass(
-// new String(CharOperation.concatWith(packageName, typeName, '/')),
-// typeName);
-// return null;
-}
-
-public boolean isPackage(char[][] compoundName, char[] packageName) {
- return searchableEnvironment.isPackage(compoundName,packageName);
-// return isPackage(new String(CharOperation.concatWith(compoundName, packageName, '/')));
-}
-
-public boolean isPackage(String qualifiedPackageName) {
- // NOTE: the output folders are added at the beginning of the binaryLocations
- for (int i = 0, l = binaryLocations.length; i < l; i++)
- if (binaryLocations[i].isPackage(qualifiedPackageName))
- return true;
- return false;
-}
-
-void setNames(String[] typeNames, SourceFile[] additionalFiles) {
- // convert the initial typeNames to a set
- if (typeNames == null) {
- this.initialTypeNames = null;
- } else {
- this.initialTypeNames = new SimpleSet(typeNames.length);
- for (int i = 0, l = typeNames.length; i < l; i++)
- this.initialTypeNames.add(typeNames[i]);
- }
- // map the additional source files by qualified type name
- if (additionalFiles == null) {
- this.additionalUnits = null;
- } else {
- this.additionalUnits = new SimpleLookupTable(additionalFiles.length);
- for (int i = 0, l = additionalFiles.length; i < l; i++) {
- SourceFile additionalUnit = additionalFiles[i];
- if (additionalUnit != null)
- this.additionalUnits.put(additionalUnit.initialTypeName, additionalFiles[i]);
- }
- }
-
- for (int i = 0, l = sourceLocations.length; i < l; i++)
- sourceLocations[i].reset();
- for (int i = 0, l = binaryLocations.length; i < l; i++)
- binaryLocations[i].reset();
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/NameSet.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/NameSet.java
deleted file mode 100644
index b8eb752b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/NameSet.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.builder;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-
-public final class NameSet {
-
-// to avoid using Enumerations, walk the individual values skipping nulls
-public char[][] names;
-public int elementSize; // number of elements in the table
-public int threshold;
-
-public NameSet(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][];
-}
-
-public 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;
-}
-
-private void rehash() {
- NameSet newSet = new NameSet(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;
-}
-
-public String toString() {
- String s = ""; //$NON-NLS-1$
- char[] name;
- for (int i = 0, l = names.length; i < l; i++)
- if ((name = names[i]) != null)
- s += new String(name) + "\n"; //$NON-NLS-1$
- return s;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ProblemFactory.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ProblemFactory.java
deleted file mode 100644
index 80fbb629..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ProblemFactory.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.builder;
-
-import java.util.Locale;
-
-import org.eclipse.wst.jsdt.internal.compiler.problem.DefaultProblemFactory;
-import org.eclipse.wst.jsdt.internal.compiler.util.SimpleLookupTable;
-
-public class ProblemFactory extends DefaultProblemFactory {
-
-static SimpleLookupTable factories = new SimpleLookupTable(5);
-
-private ProblemFactory(Locale locale) {
- super(locale);
-}
-
-public static ProblemFactory getProblemFactory(Locale locale) {
- ProblemFactory factory = (ProblemFactory) factories.get(locale);
- if (factory == null)
- factories.put(locale, factory = new ProblemFactory(locale));
- return factory;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/QualifiedNameSet.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/QualifiedNameSet.java
deleted file mode 100644
index 56970f7f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/QualifiedNameSet.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.builder;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-
-public class QualifiedNameSet {
-
-// to avoid using Enumerations, walk the individual values skipping nulls
-public char[][][] qualifiedNames;
-public int elementSize; // number of elements in the table
-public int threshold;
-
-public QualifiedNameSet(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.qualifiedNames = new char[extraRoom][][];
-}
-
-public char[][] add(char[][] qualifiedName) {
- int qLength = qualifiedName.length;
- if (qLength == 0) return CharOperation.NO_CHAR_CHAR;
-
- int length = qualifiedNames.length;
- int index = CharOperation.hashCode(qualifiedName[qLength - 1]) % length;
- char[][] current;
- while ((current = qualifiedNames[index]) != null) {
- if (CharOperation.equals(current, qualifiedName)) return current;
- if (++index == length) index = 0;
- }
- qualifiedNames[index] = qualifiedName;
-
- // assumes the threshold is never equal to the size of the table
- if (++elementSize > threshold) rehash();
- return qualifiedName;
-}
-
-private void rehash() {
- QualifiedNameSet newSet = new QualifiedNameSet(elementSize * 2); // double the number of expected elements
- char[][] current;
- for (int i = qualifiedNames.length; --i >= 0;)
- if ((current = qualifiedNames[i]) != null)
- newSet.add(current);
-
- this.qualifiedNames = newSet.qualifiedNames;
- this.elementSize = newSet.elementSize;
- this.threshold = newSet.threshold;
-}
-
-public String toString() {
- String s = ""; //$NON-NLS-1$
- char[][] qualifiedName;
- for (int i = 0, l = qualifiedNames.length; i < l; i++)
- if ((qualifiedName = qualifiedNames[i]) != null)
- s += CharOperation.toString(qualifiedName) + "\n"; //$NON-NLS-1$
- return s;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ReferenceCollection.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ReferenceCollection.java
deleted file mode 100644
index 2fc3745d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ReferenceCollection.java
+++ /dev/null
@@ -1,244 +0,0 @@
-/*******************************************************************************
- * 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
- * Tim Hanson <thanson@bea.com> - fix for https://bugs.eclipse.org/bugs/show_bug.cgi?id=137634
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.builder;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeConstants;
-
-public class ReferenceCollection {
-
-char[][][] qualifiedNameReferences; // contains no simple names as in just 'a' which is kept in simpleNameReferences instead
-char[][] simpleNameReferences;
-
-protected ReferenceCollection(char[][][] qualifiedNameReferences, char[][] simpleNameReferences) {
- this.qualifiedNameReferences = internQualifiedNames(qualifiedNameReferences);
- this.simpleNameReferences = internSimpleNames(simpleNameReferences, true);
-}
-
-void addDependencies(String[] typeNameDependencies) {
- // if each qualified type name is already known then all of its subNames can be skipped
- // and its expected that very few qualified names in typeNameDependencies need to be added
- // but could always take 'p1.p2.p3.X' and make all qualified names 'p1' 'p1.p2' 'p1.p2.p3' 'p1.p2.p3.X', then intern
- char[][][] qNames = new char[typeNameDependencies.length][][];
- for (int i = typeNameDependencies.length; --i >= 0;)
- qNames[i] = CharOperation.splitOn('.', typeNameDependencies[i].toCharArray());
- qNames = internQualifiedNames(qNames);
-
- next : for (int i = qNames.length; --i >= 0;) {
- char[][] qualifiedTypeName = qNames[i];
- while (!includes(qualifiedTypeName)) {
- if (!includes(qualifiedTypeName[qualifiedTypeName.length - 1])) {
- int length = this.simpleNameReferences.length;
- System.arraycopy(this.simpleNameReferences, 0, this.simpleNameReferences = new char[length + 1][], 0, length);
- this.simpleNameReferences[length] = qualifiedTypeName[qualifiedTypeName.length - 1];
- }
- int length = this.qualifiedNameReferences.length;
- System.arraycopy(this.qualifiedNameReferences, 0, this.qualifiedNameReferences = new char[length + 1][][], 0, length);
- this.qualifiedNameReferences[length] = qualifiedTypeName;
-
- qualifiedTypeName = CharOperation.subarray(qualifiedTypeName, 0, qualifiedTypeName.length - 1);
- char[][][] temp = internQualifiedNames(new char[][][] {qualifiedTypeName});
- if (temp == EmptyQualifiedNames)
- continue next; // qualifiedTypeName is a well known name
- qualifiedTypeName = temp[0];
- }
- }
-}
-
-boolean includes(char[] simpleName) {
- for (int i = 0, l = simpleNameReferences.length; i < l; i++)
- if (simpleName == simpleNameReferences[i]) return true;
- return false;
-}
-
-boolean includes(char[][] qualifiedName) {
- for (int i = 0, l = qualifiedNameReferences.length; i < l; i++)
- if (qualifiedName == qualifiedNameReferences[i]) return true;
- return false;
-}
-
-boolean includes(char[][][] qualifiedNames, char[][] simpleNames) {
- // if either collection of names is null, it means it contained a well known name so we know it already has a match
- if (simpleNames == null || qualifiedNames == null) {
- if (simpleNames == null && qualifiedNames == null) {
- if (JavaBuilder.DEBUG)
- System.out.println("Found well known match"); //$NON-NLS-1$
- return true;
- } else if (qualifiedNames == null) {
- for (int i = 0, l = simpleNames.length; i < l; i++) {
- if (includes(simpleNames[i])) {
- if (JavaBuilder.DEBUG)
- System.out.println("Found match in well known package to " + new String(simpleNames[i])); //$NON-NLS-1$
- return true;
- }
- }
- } else {
- for (int i = 0, l = qualifiedNames.length; i < l; i++) {
- char[][] qualifiedName = qualifiedNames[i];
- if (qualifiedName.length == 1 ? includes(qualifiedName[0]) : includes(qualifiedName)) {
- if (JavaBuilder.DEBUG)
- System.out.println("Found well known match in " + CharOperation.toString(qualifiedName)); //$NON-NLS-1$
- return true;
- }
- }
- }
- } else {
- for (int i = 0, l = simpleNames.length; i < l; i++) {
- if (includes(simpleNames[i])) {
- for (int j = 0, m = qualifiedNames.length; j < m; j++) {
- char[][] qualifiedName = qualifiedNames[j];
- if (qualifiedName.length == 1 ? includes(qualifiedName[0]) : includes(qualifiedName)) {
- if (JavaBuilder.DEBUG)
- System.out.println("Found match in " + CharOperation.toString(qualifiedName) //$NON-NLS-1$
- + " to " + new String(simpleNames[i])); //$NON-NLS-1$
- return true;
- }
- }
- return false;
- }
- }
- }
- return false;
-}
-
-
-// When any type is compiled, its methods are verified for certain problems
-// the MethodVerifier requests 3 well known types which end up in the reference collection
-// having WellKnownQualifiedNames & WellKnownSimpleNames, saves every type 40 bytes
-// NOTE: These collections are sorted by length
-static final char[][][] WellKnownQualifiedNames = new char[][][] {
-// TypeConstants.JAVA_LANG_RUNTIMEEXCEPTION,
-// TypeConstants.JAVA_LANG_THROWABLE,
- TypeConstants.JAVA_LANG_OBJECT,
-// TypeConstants.JAVA_LANG,
-// new char[][] {TypeConstants.JAVA},
-// new char[][] {new char[] {'o', 'r', 'g'}},
-// new char[][] {new char[] {'c', 'o', 'm'}},
- CharOperation.NO_CHAR_CHAR}; // default package
-static final char[][] WellKnownSimpleNames = new char[][] {
-// TypeConstants.JAVA_LANG_RUNTIMEEXCEPTION[2],
-// TypeConstants.JAVA_LANG_THROWABLE[2],
- TypeConstants.JAVA_LANG_OBJECT[0],
-// TypeConstants.JAVA,
-// TypeConstants.LANG,
-// new char[] {'o', 'r', 'g'},
-// new char[] {'c', 'o', 'm'}
- };
-
-static final char[][][] EmptyQualifiedNames = new char[0][][];
-static final char[][] EmptySimpleNames = CharOperation.NO_CHAR_CHAR;
-
-// each array contains qualified char[][], one for size 2, 3, 4, 5, 6, 7 & the rest
-static final int MaxQualifiedNames = 7;
-static QualifiedNameSet[] InternedQualifiedNames = new QualifiedNameSet[MaxQualifiedNames];
-// each array contains simple char[], one for size 1 to 29 & the rest
-static final int MaxSimpleNames = 30;
-static NameSet[] InternedSimpleNames = new NameSet[MaxSimpleNames];
-static {
- for (int i = 0; i < MaxQualifiedNames; i++)
- InternedQualifiedNames[i] = new QualifiedNameSet(37);
- for (int i = 0; i < MaxSimpleNames; i++)
- InternedSimpleNames[i] = new NameSet(37);
-}
-
-static char[][][] internQualifiedNames(StringSet qualifiedStrings) {
- if (qualifiedStrings == null) return EmptyQualifiedNames;
- int length = qualifiedStrings.elementSize;
- if (length == 0) return EmptyQualifiedNames;
-
- char[][][] result = new char[length][][];
- String[] strings = qualifiedStrings.values;
- for (int i = 0, l = strings.length; i < l; i++)
- if (strings[i] != null)
- result[--length] = CharOperation.splitOn('/', strings[i].toCharArray());
- return internQualifiedNames(result);
-}
-
-static char[][][] internQualifiedNames(char[][][] qualifiedNames) {
- if (qualifiedNames == null) return EmptyQualifiedNames;
- int length = qualifiedNames.length;
- if (length == 0) return EmptyQualifiedNames;
-
- char[][][] keepers = new char[length][][];
- int index = 0;
- next : for (int i = 0; i < length; i++) {
- char[][] qualifiedName = qualifiedNames[i];
- int qLength = qualifiedName.length;
- for (int j = 0, m = WellKnownQualifiedNames.length; j < m; j++) {
- char[][] wellKnownName = WellKnownQualifiedNames[j];
- if (qLength > wellKnownName.length)
- break; // all remaining well known names are shorter
- if (CharOperation.equals(qualifiedName, wellKnownName))
- continue next;
- }
-
- // InternedQualifiedNames[0] is for the rest (> 7 & 1)
- // InternedQualifiedNames[1] is for size 2...
- // InternedQualifiedNames[6] is for size 7
- QualifiedNameSet internedNames = InternedQualifiedNames[qLength <= MaxQualifiedNames ? qLength - 1 : 0];
- qualifiedName = internSimpleNames(qualifiedName, false);
- keepers[index++] = internedNames.add(qualifiedName);
- }
- if (length > index) {
- if (index == 0) return EmptyQualifiedNames;
- System.arraycopy(keepers, 0, keepers = new char[index][][], 0, index);
- }
- return keepers;
-}
-
-static char[][] internSimpleNames(StringSet simpleStrings) {
- if (simpleStrings == null) return EmptySimpleNames;
- int length = simpleStrings.elementSize;
- if (length == 0) return EmptySimpleNames;
-
- char[][] result = new char[length][];
- String[] strings = simpleStrings.values;
- for (int i = 0, l = strings.length; i < l; i++)
- if (strings[i] != null)
- result[--length] = strings[i].toCharArray();
- return internSimpleNames(result, true);
-}
-
-static char[][] internSimpleNames(char[][] simpleNames, boolean removeWellKnown) {
- if (simpleNames == null) return EmptySimpleNames;
- int length = simpleNames.length;
- if (length == 0) return EmptySimpleNames;
-
- char[][] keepers = new char[length][];
- int index = 0;
- next : for (int i = 0; i < length; i++) {
- char[] name = simpleNames[i];
- int sLength = name.length;
- for (int j = 0, m = WellKnownSimpleNames.length; j < m; j++) {
- char[] wellKnownName = WellKnownSimpleNames[j];
- if (sLength > wellKnownName.length)
- break; // all remaining well known names are shorter
- if (CharOperation.equals(name, wellKnownName)) {
- if (!removeWellKnown)
- keepers[index++] = WellKnownSimpleNames[j];
- continue next;
- }
- }
-
- // InternedSimpleNames[0] is for the rest (> 29)
- // InternedSimpleNames[1] is for size 1...
- // InternedSimpleNames[29] is for size 29
- NameSet internedNames = InternedSimpleNames[sLength < MaxSimpleNames ? sLength : 0];
- keepers[index++] = internedNames.add(name);
- }
- if (length > index) {
- if (index == 0) return EmptySimpleNames;
- System.arraycopy(keepers, 0, keepers = new char[index][], 0, index);
- }
- return keepers;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/SourceFile.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/SourceFile.java
deleted file mode 100644
index 6a653e8f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/SourceFile.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*******************************************************************************
- * 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.builder;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.LibrarySuperType;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit;
-import org.eclipse.wst.jsdt.internal.compiler.problem.AbortCompilation;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-public class SourceFile implements ICompilationUnit {
-
-public IFile resource;
-ClasspathMultiDirectory sourceLocation;
-String initialTypeName;
-boolean updateClassFile;
-
-public SourceFile(IFile resource, ClasspathMultiDirectory sourceLocation) {
- this.resource = resource;
- this.sourceLocation = sourceLocation;
- this.initialTypeName = extractTypeName();
- this.updateClassFile = false;
-}
-
-public SourceFile(IFile resource, ClasspathMultiDirectory sourceLocation, boolean updateClassFile) {
- this(resource, sourceLocation);
-
- this.updateClassFile = updateClassFile;
-}
-
-public boolean equals(Object o) {
- if (this == o) return true;
- if (!(o instanceof SourceFile)) return false;
-
- SourceFile f = (SourceFile) o;
- return this.sourceLocation == f.sourceLocation && this.resource.getFullPath().equals(f.resource.getFullPath());
-}
-
-String extractTypeName() {
- // answer a String with the qualified type name for the source file in the form: 'p1/p2/A'
- IPath fullPath = this.resource.getFullPath();
- int resourceSegmentCount = fullPath.segmentCount();
- int sourceFolderSegmentCount = this.sourceLocation.sourceFolder.getFullPath().segmentCount();
- int charCount = (resourceSegmentCount - sourceFolderSegmentCount - 1);
- resourceSegmentCount--; // deal with the last segment separately
- for (int i = sourceFolderSegmentCount; i < resourceSegmentCount; i++)
- charCount += fullPath.segment(i).length();
- String lastSegment = fullPath.segment(resourceSegmentCount);
- int extensionIndex = Util.indexOfJavaLikeExtension(lastSegment);
- charCount += extensionIndex;
-
- char[] result = new char[charCount];
- int offset = 0;
- for (int i = sourceFolderSegmentCount; i < resourceSegmentCount; i++) {
- String segment = fullPath.segment(i);
- int size = segment.length();
- segment.getChars(0, size, result, offset);
- offset += size;
- result[offset++] = '/';
- }
- lastSegment.getChars(0, extensionIndex, result, offset);
- return new String(result);
-}
-
-public char[] getContents() {
-
- try {
- return Util.getResourceContentsAsCharArray(this.resource);
- } catch (CoreException e) {
- throw new AbortCompilation(true, new MissingSourceFileException(this.resource.getFullPath().toString()));
- }
-}
-
-/**
- * @see org.eclipse.wst.jsdt.internal.compiler.env.IDependent#getFileName()
- */
-public char[] getFileName() {
- return this.resource.getFullPath().toString().toCharArray(); // do not know what you want to return here
-}
-
-public char[] getMainTypeName() {
- char[] typeName = this.initialTypeName.toCharArray();
- int lastIndex = CharOperation.lastIndexOf('/', typeName);
- return CharOperation.subarray(typeName, lastIndex + 1, -1);
-}
-
-public char[][] getPackageName() {
- char[] typeName = this.initialTypeName.toCharArray();
- int lastIndex = CharOperation.lastIndexOf('/', typeName);
- return CharOperation.splitOn('/', typeName, 0, lastIndex);
-}
-public int hashCode() {
- return this.initialTypeName.hashCode();
-}
-String typeLocator() {
- return this.resource.getProjectRelativePath().toString();
-}
-
-public String toString() {
- return "SourceFile[" //$NON-NLS-1$
- + this.resource.getFullPath() + "]"; //$NON-NLS-1$
-}
-
-/* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit#getCommonSuperType()
- */
-public LibrarySuperType getCommonSuperType() {
- IProject myProject = this.resource.getProject();
- IJavaScriptProject jp = JavaScriptCore.create(myProject);
- return jp.getCommonSuperType();
-}
-
-public String getInferenceID() {
- return null;
-}
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/State.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/State.java
deleted file mode 100644
index 1bc55b57..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/State.java
+++ /dev/null
@@ -1,728 +0,0 @@
-/*******************************************************************************
- * 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.builder;
-
-import java.io.DataInputStream;
-import java.io.DataOutputStream;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Date;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.env.AccessRule;
-import org.eclipse.wst.jsdt.internal.compiler.env.AccessRuleSet;
-import org.eclipse.wst.jsdt.internal.compiler.util.SimpleLookupTable;
-import org.eclipse.wst.jsdt.internal.core.ClasspathAccessRule;
-import org.eclipse.wst.jsdt.internal.core.JavaModelManager;
-
-public class State {
-// NOTE: this state cannot contain types that are not defined in this project
-
-String javaProjectName;
-ClasspathMultiDirectory[] sourceLocations;
-ClasspathLocation[] binaryLocations;
-// keyed by the project relative path of the type (ie. "src1/p1/p2/A.js"), value is a ReferenceCollection or an AdditionalTypeCollection
-SimpleLookupTable references;
-// keyed by qualified type name "p1/p2/A", value is the project relative path which defines this type "src1/p1/p2/A.js"
-public SimpleLookupTable typeLocators;
-
-int buildNumber;
-long lastStructuralBuildTime;
-SimpleLookupTable structuralBuildTimes;
-
-private String[] knownPackageNames; // of the form "p1/p2"
-
-private long previousStructuralBuildTime;
-private StringSet structurallyChangedTypes;
-public static int MaxStructurallyChangedTypes = 100; // keep track of ? structurally changed types, otherwise consider all to be changed
-
-public static final byte VERSION = 0x0015; // changed access rule presentation
-
-static final byte SOURCE_FOLDER = 1;
-static final byte BINARY_FOLDER = 2;
-static final byte EXTERNAL_JAR = 3;
-static final byte INTERNAL_JAR = 4;
-static final byte LIBRARY = 5;
-
-State() {
- // constructor with no argument
-}
-
-protected State(JavaBuilder javaBuilder) {
- this.knownPackageNames = null;
- this.previousStructuralBuildTime = -1;
- this.structurallyChangedTypes = null;
- this.javaProjectName = javaBuilder.currentProject.getName();
- this.sourceLocations = javaBuilder.nameEnvironment.sourceLocations;
- this.binaryLocations = javaBuilder.nameEnvironment.binaryLocations;
- this.references = new SimpleLookupTable(7);
- this.typeLocators = new SimpleLookupTable(7);
-
- this.buildNumber = 0; // indicates a full build
- this.lastStructuralBuildTime = computeStructuralBuildTime(javaBuilder.lastState == null ? 0 : javaBuilder.lastState.lastStructuralBuildTime);
- this.structuralBuildTimes = new SimpleLookupTable(3);
-}
-
-long computeStructuralBuildTime(long previousTime) {
- long newTime = System.currentTimeMillis();
- if (newTime <= previousTime)
- newTime = previousTime + 1;
- return newTime;
-}
-
-void copyFrom(State lastState) {
- this.knownPackageNames = null;
- this.previousStructuralBuildTime = lastState.previousStructuralBuildTime;
- this.structurallyChangedTypes = lastState.structurallyChangedTypes;
- this.buildNumber = lastState.buildNumber + 1;
- this.lastStructuralBuildTime = lastState.lastStructuralBuildTime;
- this.structuralBuildTimes = lastState.structuralBuildTimes;
-
- try {
- this.references = (SimpleLookupTable) lastState.references.clone();
- this.typeLocators = (SimpleLookupTable) lastState.typeLocators.clone();
- } catch (CloneNotSupportedException e) {
- this.references = new SimpleLookupTable(lastState.references.elementSize);
- Object[] keyTable = lastState.references.keyTable;
- Object[] valueTable = lastState.references.valueTable;
- for (int i = 0, l = keyTable.length; i < l; i++)
- if (keyTable[i] != null)
- this.references.put(keyTable[i], valueTable[i]);
-
- this.typeLocators = new SimpleLookupTable(lastState.typeLocators.elementSize);
- keyTable = lastState.typeLocators.keyTable;
- valueTable = lastState.typeLocators.valueTable;
- for (int i = 0, l = keyTable.length; i < l; i++)
- if (keyTable[i] != null)
- this.typeLocators.put(keyTable[i], valueTable[i]);
- }
-}
-public char[][] getDefinedTypeNamesFor(String typeLocator) {
- Object c = references.get(typeLocator);
- if (c instanceof AdditionalTypeCollection)
- return ((AdditionalTypeCollection) c).definedTypeNames;
- return null; // means only one type is defined with the same name as the file... saves space
-}
-
-StringSet getStructurallyChangedTypes(State prereqState) {
- if (prereqState != null && prereqState.previousStructuralBuildTime > 0) {
- Object o = structuralBuildTimes.get(prereqState.javaProjectName);
- long previous = o == null ? 0 : ((Long) o).longValue();
- if (previous == prereqState.previousStructuralBuildTime)
- return prereqState.structurallyChangedTypes;
- }
- return null;
-}
-
-boolean isDuplicateLocator(String qualifiedTypeName, String typeLocator) {
- String existing = (String) typeLocators.get(qualifiedTypeName);
- return existing != null && !existing.equals(typeLocator);
-}
-
-boolean isKnownPackage(String qualifiedPackageName) {
- if (knownPackageNames == null) {
- ArrayList names = new ArrayList(typeLocators.elementSize);
- Object[] keyTable = typeLocators.keyTable;
- for (int i = 0, l = keyTable.length; i < l; i++) {
- if (keyTable[i] != null) {
- String packageName = (String) keyTable[i]; // is a type name of the form p1/p2/A
- int last = packageName.lastIndexOf('/');
- packageName = last == -1 ? null : packageName.substring(0, last);
- while (packageName != null && !names.contains(packageName)) {
- names.add(packageName);
- last = packageName.lastIndexOf('/');
- packageName = last == -1 ? null : packageName.substring(0, last);
- }
- }
- }
- knownPackageNames = new String[names.size()];
- names.toArray(knownPackageNames);
- }
- for (int i = 0, l = knownPackageNames.length; i < l; i++)
- if (knownPackageNames[i].equals(qualifiedPackageName))
- return true;
- return false;
-}
-
-boolean isKnownType(String qualifiedTypeName) {
- return typeLocators.containsKey(qualifiedTypeName);
-}
-
-void record(String typeLocator, char[][][] qualifiedRefs, char[][] simpleRefs, char[] mainTypeName, ArrayList typeNames) {
- if (typeNames==null)
- typeNames=new ArrayList();
- if (typeNames.size() == 1 && CharOperation.equals(mainTypeName, (char[]) typeNames.get(0))) {
- references.put(typeLocator, new ReferenceCollection(qualifiedRefs, simpleRefs));
- } else {
- char[][] definedTypeNames = new char[typeNames.size()][]; // can be empty when no types are defined
- typeNames.toArray(definedTypeNames);
- references.put(typeLocator, new AdditionalTypeCollection(definedTypeNames, qualifiedRefs, simpleRefs));
- }
-}
-
-void recordLocatorForType(String qualifiedTypeName, String typeLocator) {
- this.knownPackageNames = null;
- // in the common case, the qualifiedTypeName is a substring of the typeLocator so share the char[] by using String.substring()
- int start = typeLocator.indexOf(qualifiedTypeName, 0);
- if (start > 0)
- qualifiedTypeName = typeLocator.substring(start, start + qualifiedTypeName.length());
- typeLocators.put(qualifiedTypeName, typeLocator);
-}
-
-void recordStructuralDependency(IProject prereqProject, State prereqState) {
- if (prereqState != null)
- if (prereqState.lastStructuralBuildTime > 0) // can skip if 0 (full build) since its assumed to be 0 if unknown
- structuralBuildTimes.put(prereqProject.getName(), new Long(prereqState.lastStructuralBuildTime));
-}
-
-void removeLocator(String typeLocatorToRemove) {
- this.knownPackageNames = null;
- references.removeKey(typeLocatorToRemove);
- typeLocators.removeValue(typeLocatorToRemove);
-}
-
-void removePackage(IResourceDelta sourceDelta) {
- IResource resource = sourceDelta.getResource();
- switch(resource.getType()) {
- case IResource.FOLDER :
- IResourceDelta[] children = sourceDelta.getAffectedChildren();
- for (int i = 0, l = children.length; i < l; i++)
- removePackage(children[i]);
- return;
- case IResource.FILE :
- IPath typeLocatorPath = resource.getProjectRelativePath();
- if (org.eclipse.wst.jsdt.internal.core.util.Util.isJavaLikeFileName(typeLocatorPath.lastSegment()))
- removeLocator(typeLocatorPath.toString());
- }
-}
-
-void removeQualifiedTypeName(String qualifiedTypeNameToRemove) {
- this.knownPackageNames = null;
- typeLocators.removeKey(qualifiedTypeNameToRemove);
-}
-
-static State read(IProject project, DataInputStream in) throws IOException {
- if (JavaBuilder.DEBUG)
- System.out.println("About to read state " + project.getName()); //$NON-NLS-1$
- if (VERSION != in.readByte()) {
- if (JavaBuilder.DEBUG)
- System.out.println("Found non-compatible state version... answered null for " + project.getName()); //$NON-NLS-1$
- return null;
- }
-
- State newState = new State();
- newState.javaProjectName = in.readUTF();
- if (!project.getName().equals(newState.javaProjectName)) {
- if (JavaBuilder.DEBUG)
- System.out.println("Project's name does not match... answered null"); //$NON-NLS-1$
- return null;
- }
- newState.buildNumber = in.readInt();
- newState.lastStructuralBuildTime = in.readLong();
-
- int length = in.readInt();
- newState.sourceLocations = new ClasspathMultiDirectory[length];
- for (int i = 0; i < length; i++) {
- IContainer sourceFolder = project, outputFolder = project;
- String folderName;
- if ((folderName = in.readUTF()).length() > 0) sourceFolder = project.getFolder(folderName);
- if ((folderName = in.readUTF()).length() > 0) outputFolder = project.getFolder(folderName);
- ClasspathMultiDirectory md =
- (ClasspathMultiDirectory) ClasspathLocation.forSourceFolder(sourceFolder, outputFolder, readNames(in), readNames(in));
- if (in.readBoolean())
- md.hasIndependentOutputFolder = true;
- newState.sourceLocations[i] = md;
- }
-
- length = in.readInt();
- newState.binaryLocations = new ClasspathLocation[length];
- IWorkspaceRoot root = project.getWorkspace().getRoot();
- for (int i = 0; i < length; i++) {
- switch (in.readByte()) {
- case SOURCE_FOLDER :
- newState.binaryLocations[i] = newState.sourceLocations[in.readInt()];
- break;
- case BINARY_FOLDER :
- IPath path = new Path(in.readUTF());
- IContainer outputFolder = path.segmentCount() == 1
- ? (IContainer) root.getProject(path.toString())
- : (IContainer) root.getFolder(path);
- newState.binaryLocations[i] = ClasspathLocation.forBinaryFolder(outputFolder, in.readBoolean(), readRestriction(in));
- break;
- case EXTERNAL_JAR :
- newState.binaryLocations[i] = ClasspathLocation.forLibrary(in.readUTF(), in.readLong(), readRestriction(in));
- break;
- case LIBRARY :
- newState.binaryLocations[i] = ClasspathLocation.forLibrary(in.readUTF(), readRestriction(in));
- }
- }
-
- newState.structuralBuildTimes = new SimpleLookupTable(length = in.readInt());
- for (int i = 0; i < length; i++)
- newState.structuralBuildTimes.put(in.readUTF(), new Long(in.readLong()));
-
- String[] internedTypeLocators = new String[length = in.readInt()];
- for (int i = 0; i < length; i++)
- internedTypeLocators[i] = in.readUTF();
-
- newState.typeLocators = new SimpleLookupTable(length = in.readInt());
- for (int i = 0; i < length; i++)
- newState.recordLocatorForType(in.readUTF(), internedTypeLocators[in.readInt()]);
-
- char[][] internedSimpleNames = ReferenceCollection.internSimpleNames(readNames(in), false);
- char[][][] internedQualifiedNames = new char[length = in.readInt()][][];
- for (int i = 0; i < length; i++) {
- int qLength = in.readInt();
- char[][] qName = new char[qLength][];
- for (int j = 0; j < qLength; j++)
- qName[j] = internedSimpleNames[in.readInt()];
- internedQualifiedNames[i] = qName;
- }
- internedQualifiedNames = ReferenceCollection.internQualifiedNames(internedQualifiedNames);
-
- newState.references = new SimpleLookupTable(length = in.readInt());
- for (int i = 0; i < length; i++) {
- String typeLocator = internedTypeLocators[in.readInt()];
- ReferenceCollection collection = null;
- switch (in.readByte()) {
- case 1 :
- char[][] additionalTypeNames = readNames(in);
- char[][][] qualifiedNames = new char[in.readInt()][][];
- for (int j = 0, m = qualifiedNames.length; j < m; j++)
- qualifiedNames[j] = internedQualifiedNames[in.readInt()];
- char[][] simpleNames = new char[in.readInt()][];
- for (int j = 0, m = simpleNames.length; j < m; j++)
- simpleNames[j] = internedSimpleNames[in.readInt()];
- collection = new AdditionalTypeCollection(additionalTypeNames, qualifiedNames, simpleNames);
- break;
- case 2 :
- char[][][] qNames = new char[in.readInt()][][];
- for (int j = 0, m = qNames.length; j < m; j++)
- qNames[j] = internedQualifiedNames[in.readInt()];
- char[][] sNames = new char[in.readInt()][];
- for (int j = 0, m = sNames.length; j < m; j++)
- sNames[j] = internedSimpleNames[in.readInt()];
- collection = new ReferenceCollection(qNames, sNames);
- }
- newState.references.put(typeLocator, collection);
- }
- if (JavaBuilder.DEBUG)
- System.out.println("Successfully read state for " + newState.javaProjectName); //$NON-NLS-1$
- return newState;
-}
-
-private static char[] readName(DataInputStream in) throws IOException {
- int nLength = in.readInt();
- char[] name = new char[nLength];
- for (int j = 0; j < nLength; j++)
- name[j] = in.readChar();
- return name;
-}
-
-private static char[][] readNames(DataInputStream in) throws IOException {
- int length = in.readInt();
- char[][] names = new char[length][];
- for (int i = 0; i < length; i++)
- names[i] = readName(in);
- return names;
-}
-
-private static AccessRuleSet readRestriction(DataInputStream in) throws IOException {
- int length = in.readInt();
- if (length == 0) return null; // no restriction specified
- AccessRule[] accessRules = new AccessRule[length];
- for (int i = 0; i < length; i++) {
- char[] pattern = readName(in);
- int problemId = in.readInt();
- accessRules[i] = new ClasspathAccessRule(pattern, problemId);
- }
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- String[] messageTemplates = new String[AccessRuleSet.MESSAGE_TEMPLATES_LENGTH];
- for (int i = 0; i < AccessRuleSet.MESSAGE_TEMPLATES_LENGTH; i++) {
- messageTemplates[i] = manager.intern(in.readUTF());
- }
- AccessRuleSet accessRuleSet = new AccessRuleSet(accessRules, messageTemplates);
- return accessRuleSet;
-}
-
-void tagAsNoopBuild() {
- this.buildNumber = -1; // tag the project since it has no source folders and can be skipped
-}
-
-boolean wasNoopBuild() {
- return buildNumber == -1;
-}
-
-void tagAsStructurallyChanged() {
- this.previousStructuralBuildTime = this.lastStructuralBuildTime;
- this.structurallyChangedTypes = new StringSet(7);
- this.lastStructuralBuildTime = computeStructuralBuildTime(this.previousStructuralBuildTime);
-}
-
-boolean wasStructurallyChanged(IProject prereqProject, State prereqState) {
- if (prereqState != null) {
- Object o = structuralBuildTimes.get(prereqProject.getName());
- long previous = o == null ? 0 : ((Long) o).longValue();
- if (previous == prereqState.lastStructuralBuildTime) return false;
- }
- return true;
-}
-
-void wasStructurallyChanged(String typeName) {
- if (this.structurallyChangedTypes != null) {
- if (this.structurallyChangedTypes.elementSize > MaxStructurallyChangedTypes)
- this.structurallyChangedTypes = null; // too many to keep track of
- else
- this.structurallyChangedTypes.add(typeName);
- }
-}
-
-void write(DataOutputStream out) throws IOException {
- int length;
- Object[] keyTable;
- Object[] valueTable;
-
-/*
- * byte VERSION
- * String project name
- * int build number
- * int last structural build number
-*/
- out.writeByte(VERSION);
- out.writeUTF(javaProjectName);
- out.writeInt(buildNumber);
- out.writeLong(lastStructuralBuildTime);
-
-/*
- * ClasspathMultiDirectory[]
- * int id
- * String path(s)
-*/
- out.writeInt(length = sourceLocations.length);
- for (int i = 0; i < length; i++) {
- ClasspathMultiDirectory md = sourceLocations[i];
- out.writeUTF(md.sourceFolder.getProjectRelativePath().toString());
- out.writeUTF(md.binaryFolder.getProjectRelativePath().toString());
- writeNames(md.inclusionPatterns, out);
- writeNames(md.exclusionPatterns, out);
- out.writeBoolean(md.hasIndependentOutputFolder);
- }
-
-/*
- * ClasspathLocation[]
- * int id
- * String path(s)
-*/
- out.writeInt(length = binaryLocations.length);
- next : for (int i = 0; i < length; i++) {
- ClasspathLocation c = binaryLocations[i];
- if (c instanceof ClasspathMultiDirectory) {
- out.writeByte(SOURCE_FOLDER);
- for (int j = 0, m = sourceLocations.length; j < m; j++) {
- if (sourceLocations[j] == c) {
- out.writeInt(j);
- continue next;
- }
- }
- } else if (c instanceof ClasspathDirectory) {
- out.writeByte(BINARY_FOLDER);
- ClasspathDirectory cd = (ClasspathDirectory) c;
- out.writeUTF(cd.binaryFolder.getFullPath().toString());
- out.writeBoolean(cd.isOutputFolder);
- writeRestriction(cd.accessRuleSet, out);
- } else {
- ClasspathLibrary library = (ClasspathLibrary) c;
- out.writeByte(LIBRARY);
- out.writeUTF(library.filename);
- writeRestriction(library.accessRuleSet, out);
- }
- }
-
-/*
- * Structural build numbers table
- * String prereq project name
- * int last structural build number
-*/
- out.writeInt(length = structuralBuildTimes.elementSize);
- if (length > 0) {
- keyTable = structuralBuildTimes.keyTable;
- valueTable = structuralBuildTimes.valueTable;
- for (int i = 0, l = keyTable.length; i < l; i++) {
- if (keyTable[i] != null) {
- length--;
- out.writeUTF((String) keyTable[i]);
- out.writeLong(((Long) valueTable[i]).longValue());
- }
- }
- if (JavaBuilder.DEBUG && length != 0)
- System.out.println("structuralBuildNumbers table is inconsistent"); //$NON-NLS-1$
- }
-
-/*
- * String[] Interned type locators
- */
- out.writeInt(length = references.elementSize);
- SimpleLookupTable internedTypeLocators = new SimpleLookupTable(length);
- if (length > 0) {
- keyTable = references.keyTable;
- for (int i = 0, l = keyTable.length; i < l; i++) {
- if (keyTable[i] != null) {
- length--;
- String key = (String) keyTable[i];
- out.writeUTF(key);
- internedTypeLocators.put(key, new Integer(internedTypeLocators.elementSize));
- }
- }
- if (JavaBuilder.DEBUG && length != 0)
- System.out.println("references table is inconsistent"); //$NON-NLS-1$
- }
-
-/*
- * Type locators table
- * String type name
- * int interned locator id
- */
- out.writeInt(length = typeLocators.elementSize);
- if (length > 0) {
- keyTable = typeLocators.keyTable;
- valueTable = typeLocators.valueTable;
- for (int i = 0, l = keyTable.length; i < l; i++) {
- if (keyTable[i] != null) {
- length--;
- out.writeUTF((String) keyTable[i]);
- Integer index = (Integer) internedTypeLocators.get(valueTable[i]);
- out.writeInt(index.intValue());
- }
- }
- if (JavaBuilder.DEBUG && length != 0)
- System.out.println("typeLocators table is inconsistent"); //$NON-NLS-1$
- }
-
-/*
- * char[][][] Interned qualified names
- * char[][] Interned simple names
- */
- SimpleLookupTable internedQualifiedNames = new SimpleLookupTable(31);
- SimpleLookupTable internedSimpleNames = new SimpleLookupTable(31);
- valueTable = references.valueTable;
- for (int i = 0, l = valueTable.length; i < l; i++) {
- if (valueTable[i] != null) {
- ReferenceCollection collection = (ReferenceCollection) valueTable[i];
- char[][][] qNames = collection.qualifiedNameReferences;
- for (int j = 0, m = qNames.length; j < m; j++) {
- char[][] qName = qNames[j];
- if (!internedQualifiedNames.containsKey(qName)) { // remember the names have been interned
- internedQualifiedNames.put(qName, new Integer(internedQualifiedNames.elementSize));
- for (int k = 0, n = qName.length; k < n; k++) {
- char[] sName = qName[k];
- if (!internedSimpleNames.containsKey(sName)) // remember the names have been interned
- internedSimpleNames.put(sName, new Integer(internedSimpleNames.elementSize));
- }
- }
- }
- char[][] sNames = collection.simpleNameReferences;
- for (int j = 0, m = sNames.length; j < m; j++) {
- char[] sName = sNames[j];
- if (!internedSimpleNames.containsKey(sName)) // remember the names have been interned
- internedSimpleNames.put(sName, new Integer(internedSimpleNames.elementSize));
- }
- }
- }
- char[][] internedArray = new char[internedSimpleNames.elementSize][];
- Object[] simpleNames = internedSimpleNames.keyTable;
- Object[] positions = internedSimpleNames.valueTable;
- for (int i = positions.length; --i >= 0; ) {
- if (positions[i] != null) {
- int index = ((Integer) positions[i]).intValue();
- internedArray[index] = (char[]) simpleNames[i];
- }
- }
- writeNames(internedArray, out);
- // now write the interned qualified names as arrays of interned simple names
- char[][][] internedQArray = new char[internedQualifiedNames.elementSize][][];
- Object[] qualifiedNames = internedQualifiedNames.keyTable;
- positions = internedQualifiedNames.valueTable;
- for (int i = positions.length; --i >= 0; ) {
- if (positions[i] != null) {
- int index = ((Integer) positions[i]).intValue();
- internedQArray[index] = (char[][]) qualifiedNames[i];
- }
- }
- out.writeInt(length = internedQArray.length);
- for (int i = 0; i < length; i++) {
- char[][] qName = internedQArray[i];
- int qLength = qName.length;
- out.writeInt(qLength);
- for (int j = 0; j < qLength; j++) {
- Integer index = (Integer) internedSimpleNames.get(qName[j]);
- out.writeInt(index.intValue());
- }
- }
-
-/*
- * References table
- * int interned locator id
- * ReferenceCollection
-*/
- out.writeInt(length = references.elementSize);
- if (length > 0) {
- keyTable = references.keyTable;
- for (int i = 0, l = keyTable.length; i < l; i++) {
- if (keyTable[i] != null) {
- length--;
- Integer index = (Integer) internedTypeLocators.get(keyTable[i]);
- out.writeInt(index.intValue());
- ReferenceCollection collection = (ReferenceCollection) valueTable[i];
- if (collection instanceof AdditionalTypeCollection) {
- out.writeByte(1);
- AdditionalTypeCollection atc = (AdditionalTypeCollection) collection;
- writeNames(atc.definedTypeNames, out);
- } else {
- out.writeByte(2);
- }
- char[][][] qNames = collection.qualifiedNameReferences;
- int qLength = qNames.length;
- out.writeInt(qLength);
- for (int j = 0; j < qLength; j++) {
- index = (Integer) internedQualifiedNames.get(qNames[j]);
- out.writeInt(index.intValue());
- }
- char[][] sNames = collection.simpleNameReferences;
- int sLength = sNames.length;
- out.writeInt(sLength);
- for (int j = 0; j < sLength; j++) {
- index = (Integer) internedSimpleNames.get(sNames[j]);
- out.writeInt(index.intValue());
- }
- }
- }
- if (JavaBuilder.DEBUG && length != 0)
- System.out.println("references table is inconsistent"); //$NON-NLS-1$
- }
-}
-
-private void writeName(char[] name, DataOutputStream out) throws IOException {
- int nLength = name.length;
- out.writeInt(nLength);
- for (int j = 0; j < nLength; j++)
- out.writeChar(name[j]);
-}
-
-private void writeNames(char[][] names, DataOutputStream out) throws IOException {
- int length = names == null ? 0 : names.length;
- out.writeInt(length);
- for (int i = 0; i < length; i++)
- writeName(names[i], out);
-}
-
-private void writeRestriction(AccessRuleSet accessRuleSet, DataOutputStream out) throws IOException {
- if (accessRuleSet == null) {
- out.writeInt(0);
- } else {
- AccessRule[] accessRules = accessRuleSet.getAccessRules();
- int length = accessRules.length;
- out.writeInt(length);
- if (length != 0) {
- for (int i = 0; i < length; i++) {
- AccessRule accessRule = accessRules[i];
- writeName(accessRule.pattern, out);
- out.writeInt(accessRule.problemId);
- }
- for (int i = 0; i < AccessRuleSet.MESSAGE_TEMPLATES_LENGTH; i++)
- out.writeUTF(accessRuleSet.messageTemplates[i]);
- }
- }
-}
-
-/**
- * Returns a string representation of the receiver.
- */
-public String toString() {
- return "State for " + javaProjectName //$NON-NLS-1$
- + " (#" + buildNumber //$NON-NLS-1$
- + " @ " + new Date(lastStructuralBuildTime) //$NON-NLS-1$
- + ")"; //$NON-NLS-1$
-}
-
-/* Debug helper
-void dump() {
- System.out.println("State for " + javaProjectName + " (" + buildNumber + " @ " + new Date(lastStructuralBuildTime) + ")");
- System.out.println("\tClass path source locations:");
- for (int i = 0, l = sourceLocations.length; i < l; i++)
- System.out.println("\t\t" + sourceLocations[i]);
- System.out.println("\tClass path binary locations:");
- for (int i = 0, l = binaryLocations.length; i < l; i++)
- System.out.println("\t\t" + binaryLocations[i]);
-
- System.out.print("\tStructural build numbers table:");
- if (structuralBuildTimes.elementSize == 0) {
- System.out.print(" <empty>");
- } else {
- Object[] keyTable = structuralBuildTimes.keyTable;
- Object[] valueTable = structuralBuildTimes.valueTable;
- for (int i = 0, l = keyTable.length; i < l; i++)
- if (keyTable[i] != null)
- System.out.print("\n\t\t" + keyTable[i].toString() + " -> " + valueTable[i].toString());
- }
-
- System.out.print("\tType locators table:");
- if (typeLocators.elementSize == 0) {
- System.out.print(" <empty>");
- } else {
- Object[] keyTable = typeLocators.keyTable;
- Object[] valueTable = typeLocators.valueTable;
- for (int i = 0, l = keyTable.length; i < l; i++)
- if (keyTable[i] != null)
- System.out.print("\n\t\t" + keyTable[i].toString() + " -> " + valueTable[i].toString());
- }
-
- System.out.print("\n\tReferences table:");
- if (references.elementSize == 0) {
- System.out.print(" <empty>");
- } else {
- Object[] keyTable = references.keyTable;
- Object[] valueTable = references.valueTable;
- for (int i = 0, l = keyTable.length; i < l; i++) {
- if (keyTable[i] != null) {
- System.out.print("\n\t\t" + keyTable[i].toString());
- ReferenceCollection c = (ReferenceCollection) valueTable[i];
- char[][][] qRefs = c.qualifiedNameReferences;
- System.out.print("\n\t\t\tqualified:");
- if (qRefs.length == 0)
- System.out.print(" <empty>");
- else for (int j = 0, m = qRefs.length; j < m; j++)
- System.out.print(" '" + CharOperation.toString(qRefs[j]) + "'");
- char[][] sRefs = c.simpleNameReferences;
- System.out.print("\n\t\t\tsimple:");
- if (sRefs.length == 0)
- System.out.print(" <empty>");
- else for (int j = 0, m = sRefs.length; j < m; j++)
- System.out.print(" " + new String(sRefs[j]));
- if (c instanceof AdditionalTypeCollection) {
- char[][] names = ((AdditionalTypeCollection) c).definedTypeNames;
- System.out.print("\n\t\t\tadditional type names:");
- for (int j = 0, m = names.length; j < m; j++)
- System.out.print(" " + new String(names[j]));
- }
- }
- }
- }
- System.out.print("\n\n");
-}
-*/
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/StringSet.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/StringSet.java
deleted file mode 100644
index 56c5a5cc..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/StringSet.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.builder;
-
-public class StringSet {
-
-// to avoid using Enumerations, walk the individual values skipping nulls
-public String[] values;
-public int elementSize; // number of elements in the table
-public int threshold;
-
-public StringSet(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.values = new String[extraRoom];
-}
-
-public boolean add(String value) {
- int length = this.values.length;
- int index = (value.hashCode() & 0x7FFFFFFF) % length;
- String current;
- while ((current = this.values[index]) != null) {
- if (value.equals(current)) return false; // did not add it since it already existed
- if (++index == length) index = 0;
- }
- this.values[index] = value;
-
- // assumes the threshold is never equal to the size of the table
- if (++elementSize > threshold) rehash();
- return true;
-}
-
-public void clear() {
- for (int i = this.values.length; --i >= 0;)
- this.values[i] = null;
- this.elementSize = 0;
-}
-
-public boolean includes(String value) {
- int length = values.length;
- int index = (value.hashCode() & 0x7FFFFFFF) % length;
- String current;
- while ((current = this.values[index]) != null) {
- if (value.equals(current)) return true;
- if (++index == length) index = 0;
- }
- return false;
-}
-
-private void rehash() {
- StringSet newSet = new StringSet(elementSize * 2); // double the number of expected elements
- String current;
- for (int i = this.values.length; --i >= 0;)
- if ((current = this.values[i]) != null)
- newSet.add(current);
-
- this.values = newSet.values;
- this.elementSize = newSet.elementSize;
- this.threshold = newSet.threshold;
-}
-
-public String toString() {
- String s = ""; //$NON-NLS-1$
- String value;
- for (int i = 0, l = this.values.length; i < l; i++)
- if ((value = this.values[i]) != null)
- s += value + "\n"; //$NON-NLS-1$
- return s;
-}
-}
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
deleted file mode 100644
index b2f9f4d9..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ValidationParticipantResult.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM - rewrote spec
- *
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.core.builder;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem;
-
-public class ValidationParticipantResult {
- protected SourceFile sourceFile;
- protected IFile[] addedFiles; // added/changed generated source files that need to be compiled
- protected IFile[] deletedFiles; // previously generated source files that should be deleted
- protected CategorizedProblem[] problems; // new problems to report against this compilationUnit
- protected String[] dependencies; // fully-qualified type names of any new dependencies, each name is of the form 'p1.p2.A.B'
-
-protected ValidationParticipantResult(SourceFile sourceFile) {
- this.sourceFile = sourceFile;
- this.addedFiles = null;
- this.deletedFiles = null;
- this.problems = null;
- this.dependencies = null;
-}
-
-void reset() {
- this.addedFiles = null;
- this.deletedFiles = null;
- this.problems = null;
- this.dependencies = null;
-}
-
-public String toString() {
- return this.sourceFile.toString();
-}
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/WorkQueue.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/WorkQueue.java
deleted file mode 100644
index b578dec0..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/WorkQueue.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.builder;
-
-import org.eclipse.wst.jsdt.internal.compiler.util.SimpleSet;
-
-public class WorkQueue {
-
-private SimpleSet needsCompileList;
-private SimpleSet compiledList;
-
-public WorkQueue() {
- this.needsCompileList = new SimpleSet();
- this.compiledList = new SimpleSet();
-}
-
-public void add(SourceFile element) {
- needsCompileList.add(element);
-}
-
-public void addAll(SourceFile[] elements) {
- for (int i = 0, l = elements.length; i < l; i++)
- add(elements[i]);
-}
-
-public void clear() {
- this.needsCompileList.clear();
- this.compiledList.clear();
-}
-
-public void finished(SourceFile element) {
- needsCompileList.remove(element);
- compiledList.add(element);
-}
-
-public boolean isCompiled(SourceFile element) {
- return compiledList.includes(element);
-}
-
-public boolean isWaiting(SourceFile element) {
- return needsCompileList.includes(element);
-}
-
-public String toString() {
- return "WorkQueue: " + needsCompileList; //$NON-NLS-1$
-}
-}
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
deleted file mode 100644
index 950f0df8..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
+++ /dev/null
@@ -1,3161 +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.dom.rewrite;
-
-import java.util.ArrayList;
-import java.util.IdentityHashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Stack;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.text.edits.CopySourceEdit;
-import org.eclipse.text.edits.CopyTargetEdit;
-import org.eclipse.text.edits.DeleteEdit;
-import org.eclipse.text.edits.InsertEdit;
-import org.eclipse.text.edits.MoveSourceEdit;
-import org.eclipse.text.edits.MoveTargetEdit;
-import org.eclipse.text.edits.RangeMarker;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.ToolFactory;
-import org.eclipse.wst.jsdt.core.compiler.IScanner;
-import org.eclipse.wst.jsdt.core.compiler.ITerminalSymbols;
-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.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ArrayAccess;
-import org.eclipse.wst.jsdt.core.dom.ArrayCreation;
-import org.eclipse.wst.jsdt.core.dom.ArrayInitializer;
-import org.eclipse.wst.jsdt.core.dom.ArrayType;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.BooleanLiteral;
-import org.eclipse.wst.jsdt.core.dom.BreakStatement;
-import org.eclipse.wst.jsdt.core.dom.CatchClause;
-import org.eclipse.wst.jsdt.core.dom.CharacterLiteral;
-import org.eclipse.wst.jsdt.core.dom.ChildListPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.ChildPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.ConditionalExpression;
-import org.eclipse.wst.jsdt.core.dom.ConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.ContinueStatement;
-import org.eclipse.wst.jsdt.core.dom.DoStatement;
-import org.eclipse.wst.jsdt.core.dom.EmptyStatement;
-import org.eclipse.wst.jsdt.core.dom.EnhancedForStatement;
-import org.eclipse.wst.jsdt.core.dom.ExpressionStatement;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ForInStatement;
-import org.eclipse.wst.jsdt.core.dom.ForStatement;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionExpression;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.FunctionRef;
-import org.eclipse.wst.jsdt.core.dom.FunctionRefParameter;
-import org.eclipse.wst.jsdt.core.dom.IfStatement;
-import org.eclipse.wst.jsdt.core.dom.ImportDeclaration;
-import org.eclipse.wst.jsdt.core.dom.InfixExpression;
-import org.eclipse.wst.jsdt.core.dom.Initializer;
-import org.eclipse.wst.jsdt.core.dom.InstanceofExpression;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.LabeledStatement;
-import org.eclipse.wst.jsdt.core.dom.ListExpression;
-import org.eclipse.wst.jsdt.core.dom.MemberRef;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.NullLiteral;
-import org.eclipse.wst.jsdt.core.dom.NumberLiteral;
-import org.eclipse.wst.jsdt.core.dom.ObjectLiteral;
-import org.eclipse.wst.jsdt.core.dom.ObjectLiteralField;
-import org.eclipse.wst.jsdt.core.dom.PackageDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ParenthesizedExpression;
-import org.eclipse.wst.jsdt.core.dom.PostfixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrefixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrimitiveType;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.QualifiedType;
-import org.eclipse.wst.jsdt.core.dom.RegularExpressionLiteral;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SimpleType;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.StringLiteral;
-import org.eclipse.wst.jsdt.core.dom.StructuralPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.SuperFieldAccess;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.SwitchCase;
-import org.eclipse.wst.jsdt.core.dom.SwitchStatement;
-import org.eclipse.wst.jsdt.core.dom.TagElement;
-import org.eclipse.wst.jsdt.core.dom.TextElement;
-import org.eclipse.wst.jsdt.core.dom.ThisExpression;
-import org.eclipse.wst.jsdt.core.dom.ThrowStatement;
-import org.eclipse.wst.jsdt.core.dom.TryStatement;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.TypeLiteral;
-import org.eclipse.wst.jsdt.core.dom.UndefinedLiteral;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.WhileStatement;
-import org.eclipse.wst.jsdt.core.dom.WithStatement;
-import org.eclipse.wst.jsdt.core.dom.rewrite.TargetSourceRangeComputer;
-import org.eclipse.wst.jsdt.core.dom.rewrite.TargetSourceRangeComputer.SourceRange;
-import org.eclipse.wst.jsdt.core.formatter.IndentManipulation;
-import org.eclipse.wst.jsdt.internal.compiler.parser.ScannerHelper;
-import org.eclipse.wst.jsdt.internal.core.dom.rewrite.ASTRewriteFormatter.BlockContext;
-import org.eclipse.wst.jsdt.internal.core.dom.rewrite.ASTRewriteFormatter.NodeMarker;
-import org.eclipse.wst.jsdt.internal.core.dom.rewrite.ASTRewriteFormatter.Prefix;
-import org.eclipse.wst.jsdt.internal.core.dom.rewrite.NodeInfoStore.CopyPlaceholderData;
-import org.eclipse.wst.jsdt.internal.core.dom.rewrite.NodeInfoStore.StringPlaceholderData;
-import org.eclipse.wst.jsdt.internal.core.dom.rewrite.RewriteEventStore.CopySourceInfo;
-
-
-/**
- * Infrastructure to support code modifications. Existing code must stay untouched, new code
- * added with correct formatting, moved code left with the user's formatting / comments.
- * Idea:
- * - Get the AST for existing code
- * - Describe changes
- * - This visitor analyzes the changes or annotations and generates text edits
- * (text manipulation API) that describe the required code changes.
- */
-public final class ASTRewriteAnalyzer extends ASTVisitor {
-
- /**
- * Internal synonym for deprecated constant AST.JLS2
- * to alleviate deprecated warnings.
- * @deprecated
- */
- /*package*/ static final int JLS2_INTERNAL = AST.JLS2;
-
- TextEdit currentEdit;
- final RewriteEventStore eventStore; // used from inner classes
-
- private TokenScanner tokenScanner; // shared scanner
-
- private final Map sourceCopyInfoToEdit;
- private final Stack sourceCopyEndNodes;
-
- private final char[] content;
- private final LineInformation lineInfo;
- private final ASTRewriteFormatter formatter;
- private final NodeInfoStore nodeInfos;
- private final TargetSourceRangeComputer extendedSourceRangeComputer;
- private final LineCommentEndOffsets lineCommentEndOffsets;
-
- /**
- * Constructor for ASTRewriteAnalyzer.
- * @param content the content of the compilation unit to rewrite.
- * @param lineInfo line information for the content of the compilation unit to rewrite.
- * @param rootEdit the edit to add all generated edits to
- * @param eventStore the event store containing the description of changes
- * @param nodeInfos annotations to nodes, such as if a node is a string placeholder or a copy target
- * @param comments list of comments of the compilation unit to rewrite (elements of type <code>Comment</code>) or <code>null</code>.
- * @param options the current jdt.core options (formatting/compliance) or <code>null</code>.
- * @param extendedSourceRangeComputer the source range computer to use
- */
- public ASTRewriteAnalyzer(char[] content, LineInformation lineInfo, String lineDelim, TextEdit rootEdit, RewriteEventStore eventStore, NodeInfoStore nodeInfos, List comments, Map options, TargetSourceRangeComputer extendedSourceRangeComputer) {
- this.eventStore= eventStore;
- this.content= content;
- this.lineInfo= lineInfo;
- this.nodeInfos= nodeInfos;
- this.tokenScanner= null;
- this.currentEdit= rootEdit;
- this.sourceCopyInfoToEdit= new IdentityHashMap();
- this.sourceCopyEndNodes= new Stack();
-
- this.formatter= new ASTRewriteFormatter(nodeInfos, eventStore, options, lineDelim);
-
- this.extendedSourceRangeComputer = extendedSourceRangeComputer;
- this.lineCommentEndOffsets= new LineCommentEndOffsets(comments);
- }
-
- final TokenScanner getScanner() {
- if (this.tokenScanner == null) {
- IScanner scanner= ToolFactory.createScanner(true, false, false, false);
- scanner.setSource(this.content);
- this.tokenScanner= new TokenScanner(scanner);
- }
- return this.tokenScanner;
- }
-
- final char[] getContent() {
- return this.content;
- }
-
- final LineInformation getLineInformation() {
- return this.lineInfo;
- }
-
- /**
- * Returns the extended source range for a node.
- *
- * @return an extended source range (never null)
- * @since 3.1
- */
- final SourceRange getExtendedRange(ASTNode node) {
- if (this.eventStore.isRangeCopyPlaceholder(node)) {
- return new SourceRange(node.getStartPosition(), node.getLength());
- }
- return this.extendedSourceRangeComputer.computeSourceRange(node);
- }
-
- final int getExtendedOffset(ASTNode node) {
- return getExtendedRange(node).getStartPosition();
- }
-
- final int getExtendedEnd(ASTNode node) {
- TargetSourceRangeComputer.SourceRange range= getExtendedRange(node);
- return range.getStartPosition() + range.getLength();
- }
-
- final TextEdit getCopySourceEdit(CopySourceInfo info) {
- TextEdit edit= (TextEdit) this.sourceCopyInfoToEdit.get(info);
- if (edit == null) {
- SourceRange range= getExtendedRange(info.getNode());
- int start= range.getStartPosition();
- int end= start + range.getLength();
- if (info.isMove) {
- MoveSourceEdit moveSourceEdit= new MoveSourceEdit(start, end - start);
- moveSourceEdit.setTargetEdit(new MoveTargetEdit(0));
- edit= moveSourceEdit;
- } else {
- CopySourceEdit copySourceEdit= new CopySourceEdit(start, end - start);
- copySourceEdit.setTargetEdit(new CopyTargetEdit(0));
- edit= copySourceEdit;
- }
- this.sourceCopyInfoToEdit.put(info, edit);
- }
- return edit;
- }
-
- private final int getChangeKind(ASTNode node, StructuralPropertyDescriptor property) {
- RewriteEvent event= getEvent(node, property);
- if (event != null) {
- return event.getChangeKind();
- }
- return RewriteEvent.UNCHANGED;
- }
-
- private final boolean hasChildrenChanges(ASTNode node) {
- return this.eventStore.hasChangedProperties(node);
- }
-
- private final boolean isChanged(ASTNode node, StructuralPropertyDescriptor property) {
- RewriteEvent event= getEvent(node, property);
- if (event != null) {
- return event.getChangeKind() != RewriteEvent.UNCHANGED;
- }
- return false;
- }
-
- private final boolean isCollapsed(ASTNode node) {
- return this.nodeInfos.isCollapsed(node);
- }
-
- final boolean isInsertBoundToPrevious(ASTNode node) {
- return this.eventStore.isInsertBoundToPrevious(node);
- }
-
- private final TextEditGroup getEditGroup(ASTNode parent, StructuralPropertyDescriptor property) {
- RewriteEvent event= getEvent(parent, property);
- if (event != null) {
- return getEditGroup(event);
- }
- return null;
- }
-
- final RewriteEvent getEvent(ASTNode parent, StructuralPropertyDescriptor property) {
- return this.eventStore.getEvent(parent, property);
- }
-
- final TextEditGroup getEditGroup(RewriteEvent change) {
- return this.eventStore.getEventEditGroup(change);
- }
-
- private final Object getOriginalValue(ASTNode parent, StructuralPropertyDescriptor property) {
- return this.eventStore.getOriginalValue(parent, property);
- }
-
- private final Object getNewValue(ASTNode parent, StructuralPropertyDescriptor property) {
- return this.eventStore.getNewValue(parent, property);
- }
-
- final void addEdit(TextEdit edit) {
- this.currentEdit.addChild(edit);
- }
-
- final String getLineDelimiter() {
- return this.formatter.getLineDelimiter();
- }
-
- final String createIndentString(int indent) {
- return this.formatter.createIndentString(indent);
- }
-
- final private String getIndentOfLine(int pos) {
- int line= getLineInformation().getLineOfOffset(pos);
- if (line >= 0) {
- char[] cont= getContent();
- int lineStart= getLineInformation().getLineOffset(line);
- int i= lineStart;
- while (i < cont.length && IndentManipulation.isIndentChar(content[i])) {
- i++;
- }
- return new String(cont, lineStart, i - lineStart);
- }
- return new String();
- }
-
-
- final String getIndentAtOffset(int pos) {
- return this.formatter.getIndentString(getIndentOfLine(pos));
- }
-
- final void doTextInsert(int offset, String insertString, TextEditGroup editGroup) {
- if (insertString.length() > 0) {
- // bug fix for 95839: problem with inserting at the end of a line comment
- if (this.lineCommentEndOffsets.isEndOfLineComment(offset, this.content)) {
- if (!insertString.startsWith(getLineDelimiter())) {
- TextEdit edit= new InsertEdit(offset, getLineDelimiter()); // add a line delimiter
- addEdit(edit);
- if (editGroup != null) {
- addEditGroup(editGroup, edit);
- }
- }
- this.lineCommentEndOffsets.remove(offset); // only one line delimiter per line comment required
- }
- TextEdit edit= new InsertEdit(offset, insertString);
- addEdit(edit);
- if (editGroup != null) {
- addEditGroup(editGroup, edit);
- }
- }
- }
-
- final void addEditGroup(TextEditGroup editGroup, TextEdit edit) {
- editGroup.addTextEdit(edit);
- }
-
- final TextEdit doTextRemove(int offset, int len, TextEditGroup editGroup) {
- if (len == 0) {
- return null;
- }
- TextEdit edit= new DeleteEdit(offset, len);
- addEdit(edit);
- if (editGroup != null) {
- addEditGroup(editGroup, edit);
- }
- return edit;
- }
-
- final void doTextRemoveAndVisit(int offset, int len, ASTNode node, TextEditGroup editGroup) {
- TextEdit edit= doTextRemove(offset, len, editGroup);
- if (edit != null) {
- this.currentEdit= edit;
- voidVisit(node);
- this.currentEdit= edit.getParent();
- } else {
- voidVisit(node);
- }
- }
-
- final int doVisit(ASTNode node) {
- node.accept(this);
- return getExtendedEnd(node);
- }
-
- private final int doVisit(ASTNode parent, StructuralPropertyDescriptor property, int offset) {
- Object node= getOriginalValue(parent, property);
- if (property.isChildProperty() && node != null) {
- return doVisit((ASTNode) node);
- } else if (property.isChildListProperty()) {
- return doVisitList((List) node, offset);
- }
- return offset;
- }
-
- private int doVisitList(List list, int offset) {
- int endPos= offset;
- for (Iterator iter= list.iterator(); iter.hasNext();) {
- ASTNode curr= ((ASTNode) iter.next());
- endPos= doVisit(curr);
- }
- return endPos;
- }
-
- final void voidVisit(ASTNode node) {
- node.accept(this);
- }
-
- private final void voidVisit(ASTNode parent, StructuralPropertyDescriptor property) {
- Object node= getOriginalValue(parent, property);
- if (property.isChildProperty() && node != null) {
- voidVisit((ASTNode) node);
- } else if (property.isChildListProperty()) {
- voidVisitList((List) node);
- }
- }
-
- private void voidVisitList(List list) {
- for (Iterator iter= list.iterator(); iter.hasNext();) {
- doVisit(((ASTNode) iter.next()));
- }
- }
-
- private final boolean doVisitUnchangedChildren(ASTNode parent) {
- List properties= parent.structuralPropertiesForType();
- for (int i= 0; i < properties.size(); i++) {
- voidVisit(parent, (StructuralPropertyDescriptor) properties.get(i));
- }
- return false;
- }
-
-
- private final void doTextReplace(int offset, int len, String insertString, TextEditGroup editGroup) {
- if (len > 0 || insertString.length() > 0) {
- TextEdit edit= new ReplaceEdit(offset, len, insertString);
- addEdit(edit);
- if (editGroup != null) {
- addEditGroup(editGroup, edit);
- }
- }
- }
-
- private final TextEdit doTextCopy(TextEdit sourceEdit, int destOffset, int sourceIndentLevel, String destIndentString, TextEditGroup editGroup) {
- TextEdit targetEdit;
- SourceModifier modifier= new SourceModifier(sourceIndentLevel, destIndentString, this.formatter.getTabWidth(), this.formatter.getIndentWidth());
-
- if (sourceEdit instanceof MoveSourceEdit) {
- MoveSourceEdit moveEdit= (MoveSourceEdit) sourceEdit;
- moveEdit.setSourceModifier(modifier);
-
- targetEdit= new MoveTargetEdit(destOffset, moveEdit);
- addEdit(targetEdit);
- } else {
- CopySourceEdit copyEdit= (CopySourceEdit) sourceEdit;
- copyEdit.setSourceModifier(modifier);
-
- targetEdit= new CopyTargetEdit(destOffset, copyEdit);
- addEdit(targetEdit);
- }
-
- if (editGroup != null) {
- addEditGroup(editGroup, sourceEdit);
- addEditGroup(editGroup, targetEdit);
- }
- return targetEdit;
-
- }
-
- private void changeNotSupported(ASTNode node) {
- Assert.isTrue(false, "Change not supported in " + node.getClass().getName()); //$NON-NLS-1$
- }
-
-
- class ListRewriter {
- protected String contantSeparator;
- protected int startPos;
-
- protected RewriteEvent[] list;
-
- protected final ASTNode getOriginalNode(int index) {
- return (ASTNode) this.list[index].getOriginalValue();
- }
-
- protected final ASTNode getNewNode(int index) {
- return (ASTNode) this.list[index].getNewValue();
- }
-
- protected String getSeparatorString(int nodeIndex) {
- return this.contantSeparator;
- }
-
- protected int getInitialIndent() {
- return getIndent(this.startPos);
- }
-
- protected int getNodeIndent(int nodeIndex) {
- ASTNode node= getOriginalNode(nodeIndex);
- if (node == null) {
- for (int i= nodeIndex - 1; i>= 0; i--) {
- ASTNode curr= getOriginalNode(i);
- if (curr != null) {
- return getIndent(curr.getStartPosition());
- }
- }
- return getInitialIndent();
- }
- return getIndent(node.getStartPosition());
- }
-
- protected int getStartOfNextNode(int nextIndex, int defaultPos) {
- for (int i= nextIndex; i < this.list.length; i++) {
- RewriteEvent elem= this.list[i];
- if (elem.getChangeKind() != RewriteEvent.INSERTED) {
- ASTNode node= (ASTNode) elem.getOriginalValue();
- return getExtendedOffset(node);
- }
- }
- return defaultPos;
- }
-
- protected int getEndOfNode(ASTNode node) {
- return getExtendedEnd(node);
- }
-
- public final int rewriteList(ASTNode parent, StructuralPropertyDescriptor property, int offset, String keyword, String separator) {
- this.contantSeparator= separator;
- return rewriteList(parent, property, offset, keyword);
- }
-
- private boolean insertAfterSeparator(ASTNode node) {
- return !isInsertBoundToPrevious(node);
- }
-
- public final int rewriteList(ASTNode parent, StructuralPropertyDescriptor property, int offset, String keyword) {
- this.startPos= offset;
- this.list= getEvent(parent, property).getChildren();
-
- int total= this.list.length;
- if (total == 0) {
- return this.startPos;
- }
-
- int currPos= -1;
-
- int lastNonInsert= -1;
- int lastNonDelete= -1;
-
- for (int i= 0; i < total; i++) {
- int currMark= this.list[i].getChangeKind();
-
- if (currMark != RewriteEvent.INSERTED) {
- lastNonInsert= i;
- if (currPos == -1) {
- ASTNode elem= (ASTNode) this.list[i].getOriginalValue();
- currPos= getExtendedOffset(elem);
- }
- }
- if (currMark != RewriteEvent.REMOVED) {
- lastNonDelete= i;
- }
- }
-
- if (currPos == -1) { // only inserts
- if (keyword.length() > 0) { // creating a new list -> insert keyword first (e.g. " throws ")
- TextEditGroup editGroup= getEditGroup(this.list[0]); // first node is insert
- doTextInsert(offset, keyword, editGroup);
- }
- currPos= offset;
- }
- if (lastNonDelete == -1) { // all removed, set back to start so the keyword is removed as well
- currPos= offset;
- }
-
- int prevEnd= currPos;
-
- final int NONE= 0, NEW= 1, EXISTING= 2;
- int separatorState= NEW;
-
- for (int i= 0; i < total; i++) {
- RewriteEvent currEvent= this.list[i];
- int currMark= currEvent.getChangeKind();
- int nextIndex= i + 1;
-
- if (currMark == RewriteEvent.INSERTED) {
- TextEditGroup editGroup= getEditGroup(currEvent);
- ASTNode node= (ASTNode) currEvent.getNewValue();
-
- if (separatorState == NONE) { // element after last existing element (but not first)
- doTextInsert(currPos, getSeparatorString(i - 1), editGroup); // insert separator
- separatorState= NEW;
- }
- if (separatorState == NEW || insertAfterSeparator(node)) {
- doTextInsert(currPos, node, getNodeIndent(i), true, editGroup); // insert node
-
- separatorState= NEW;
- if (i != lastNonDelete) {
- if (this.list[nextIndex].getChangeKind() != RewriteEvent.INSERTED) {
- doTextInsert(currPos, getSeparatorString(i), editGroup); // insert separator
- } else {
- separatorState= NONE;
- }
- }
- } else { // EXISTING && insert before separator
- doTextInsert(prevEnd, getSeparatorString(i - 1), editGroup);
- doTextInsert(prevEnd, node, getNodeIndent(i), true, editGroup);
- }
- } else if (currMark == RewriteEvent.REMOVED) {
- ASTNode node= (ASTNode) currEvent.getOriginalValue();
- TextEditGroup editGroup= getEditGroup(currEvent);
- int currEnd= getEndOfNode(node);
- if (i > lastNonDelete && separatorState == EXISTING) {
- // is last, remove previous separator: split delete to allow range copies
- doTextRemove(prevEnd, currPos - prevEnd, editGroup); // remove separator
- doTextRemoveAndVisit(currPos, currEnd - currPos, node, editGroup); // remove node
- currPos= currEnd;
- prevEnd= currEnd;
- } else {
- // remove element and next separator
- int end= getStartOfNextNode(nextIndex, currEnd); // start of next
- doTextRemoveAndVisit(currPos, currEnd - currPos, node, getEditGroup(currEvent)); // remove node
- doTextRemove(currEnd, end - currEnd, editGroup); // remove separator
- currPos= end;
- prevEnd= currEnd;
- separatorState= NEW;
- }
- } else { // replaced or unchanged
- if (currMark == RewriteEvent.REPLACED) {
- ASTNode node= (ASTNode) currEvent.getOriginalValue();
- int currEnd= getEndOfNode(node);
-
- TextEditGroup editGroup= getEditGroup(currEvent);
- ASTNode changed= (ASTNode) currEvent.getNewValue();
- doTextRemoveAndVisit(currPos, currEnd - currPos, node, editGroup);
- doTextInsert(currPos, changed, getNodeIndent(i), true, editGroup);
-
- prevEnd= currEnd;
- } else { // is unchanged
- ASTNode node= (ASTNode) currEvent.getOriginalValue();
- voidVisit(node);
- }
- if (i == lastNonInsert) { // last node or next nodes are all inserts
- separatorState= NONE;
- if (currMark == RewriteEvent.UNCHANGED) {
- ASTNode node= (ASTNode) currEvent.getOriginalValue();
- prevEnd= getEndOfNode(node);
- }
- currPos= prevEnd;
- } else if (this.list[nextIndex].getChangeKind() != RewriteEvent.UNCHANGED) {
- // no updates needed while nodes are unchanged
- if (currMark == RewriteEvent.UNCHANGED) {
- ASTNode node= (ASTNode) currEvent.getOriginalValue();
- prevEnd= getEndOfNode(node);
- }
- currPos= getStartOfNextNode(nextIndex, prevEnd); // start of next
- separatorState= EXISTING;
- }
- }
-
- }
- return currPos;
- }
-
- }
-
- private int rewriteRequiredNode(ASTNode parent, StructuralPropertyDescriptor property) {
- RewriteEvent event= getEvent(parent, property);
- if (event != null && event.getChangeKind() == RewriteEvent.REPLACED) {
- ASTNode node= (ASTNode) event.getOriginalValue();
- TextEditGroup editGroup= getEditGroup(event);
- SourceRange range= getExtendedRange(node);
- int offset= range.getStartPosition();
- int length= range.getLength();
- doTextRemoveAndVisit(offset, length, node, editGroup);
- doTextInsert(offset, (ASTNode) event.getNewValue(), getIndent(offset), true, editGroup);
- return offset + length;
- }
- return doVisit(parent, property, 0);
- }
-
- private int rewriteNode(ASTNode parent, StructuralPropertyDescriptor property, int offset, Prefix prefix) {
- RewriteEvent event= getEvent(parent, property);
- if (event != null) {
- switch (event.getChangeKind()) {
- case RewriteEvent.INSERTED: {
- ASTNode node= (ASTNode) event.getNewValue();
- TextEditGroup editGroup= getEditGroup(event);
- int indent= getIndent(offset);
- doTextInsert(offset, prefix.getPrefix(indent), editGroup);
- doTextInsert(offset, node, indent, true, editGroup);
- return offset;
- }
- case RewriteEvent.REMOVED: {
- ASTNode node= (ASTNode) event.getOriginalValue();
- TextEditGroup editGroup= getEditGroup(event);
-
- int nodeEnd= getExtendedEnd(node);
- // if there is a prefix, remove the prefix as well
- int len= nodeEnd - offset;
- doTextRemoveAndVisit(offset, len, node, editGroup);
- return nodeEnd;
- }
- case RewriteEvent.REPLACED: {
- ASTNode node= (ASTNode) event.getOriginalValue();
- TextEditGroup editGroup= getEditGroup(event);
- SourceRange range= getExtendedRange(node);
- int nodeOffset= range.getStartPosition();
- int nodeLen= range.getLength();
- doTextRemoveAndVisit(nodeOffset, nodeLen, node, editGroup);
- doTextInsert(nodeOffset, (ASTNode) event.getNewValue(), getIndent(offset), true, editGroup);
- return nodeOffset + nodeLen;
- }
- }
- }
- return doVisit(parent, property, offset);
- }
-
- private int rewriteJavadoc(ASTNode node, StructuralPropertyDescriptor property) {
- int pos= rewriteNode(node, property, node.getStartPosition(), ASTRewriteFormatter.NONE);
- int changeKind= getChangeKind(node, property);
- if (changeKind == RewriteEvent.INSERTED) {
- String indent= getLineDelimiter() + getIndentAtOffset(pos);
- doTextInsert(pos, indent, getEditGroup(node, property));
- } else if (changeKind == RewriteEvent.REMOVED) {
- try {
- getScanner().readNext(pos, false);
- doTextRemove(pos, getScanner().getCurrentStartOffset() - pos, getEditGroup(node, property));
- pos= getScanner().getCurrentStartOffset();
- } catch (CoreException e) {
- handleException(e);
- }
- }
- return pos;
- }
-
-
- /*
- * endpos can be -1 -> use the end pos of the body
- */
- private int rewriteBodyNode(ASTNode parent, StructuralPropertyDescriptor property, int offset, int endPos, int indent, BlockContext context) {
- RewriteEvent event= getEvent(parent, property);
- if (event != null) {
- switch (event.getChangeKind()) {
- case RewriteEvent.INSERTED: {
- ASTNode node= (ASTNode) event.getNewValue();
- TextEditGroup editGroup= getEditGroup(event);
-
- String[] strings= context.getPrefixAndSuffix(indent, node, this.eventStore);
-
- doTextInsert(offset, strings[0], editGroup);
- doTextInsert(offset, node, indent, true, editGroup);
- doTextInsert(offset, strings[1], editGroup);
- return offset;
- }
- case RewriteEvent.REMOVED: {
- ASTNode node= (ASTNode) event.getOriginalValue();
- if (endPos == -1) {
- endPos= getExtendedEnd(node);
- }
-
- TextEditGroup editGroup= getEditGroup(event);
- // if there is a prefix, remove the prefix as well
- int len= endPos - offset;
- doTextRemoveAndVisit(offset, len, node, editGroup);
- return endPos;
- }
- case RewriteEvent.REPLACED: {
- ASTNode node= (ASTNode) event.getOriginalValue();
- if (endPos == -1) {
- endPos= getExtendedEnd(node);
- }
- TextEditGroup editGroup= getEditGroup(event);
- int nodeLen= endPos - offset;
-
- ASTNode replacingNode= (ASTNode) event.getNewValue();
- String[] strings= context.getPrefixAndSuffix(indent, replacingNode, this.eventStore);
- doTextRemoveAndVisit(offset, nodeLen, node, editGroup);
-
- String prefix= strings[0];
- doTextInsert(offset, prefix, editGroup);
- String lineInPrefix= getCurrentLine(prefix, prefix.length());
- if (prefix.length() != lineInPrefix.length()) {
- // prefix contains a new line: update the indent to the one used in the prefix
- indent= this.formatter.computeIndentUnits(lineInPrefix);
- }
- doTextInsert(offset, replacingNode, indent, true, editGroup);
- doTextInsert(offset, strings[1], editGroup);
- return endPos;
- }
- }
- }
- int pos= doVisit(parent, property, offset);
- if (endPos != -1) {
- return endPos;
- }
- return pos;
- }
-
- private int rewriteOptionalQualifier(ASTNode parent, StructuralPropertyDescriptor property, int startPos) {
- RewriteEvent event= getEvent(parent, property);
- if (event != null) {
- switch (event.getChangeKind()) {
- case RewriteEvent.INSERTED: {
- ASTNode node= (ASTNode) event.getNewValue();
- TextEditGroup editGroup= getEditGroup(event);
- doTextInsert(startPos, node, getIndent(startPos), true, editGroup);
- doTextInsert(startPos, ".", editGroup); //$NON-NLS-1$
- return startPos;
- }
- case RewriteEvent.REMOVED: {
- try {
- ASTNode node= (ASTNode) event.getOriginalValue();
- TextEditGroup editGroup= getEditGroup(event);
- int dotEnd= getScanner().getTokenEndOffset(ITerminalSymbols.TokenNameDOT, node.getStartPosition() + node.getLength());
- doTextRemoveAndVisit(startPos, dotEnd - startPos, node, editGroup);
- return dotEnd;
- } catch (CoreException e) {
- handleException(e);
- }
- break;
- }
- case RewriteEvent.REPLACED: {
- ASTNode node= (ASTNode) event.getOriginalValue();
- TextEditGroup editGroup= getEditGroup(event);
- SourceRange range= getExtendedRange(node);
- int offset= range.getStartPosition();
- int length= range.getLength();
-
- doTextRemoveAndVisit(offset, length, node, editGroup);
- doTextInsert(offset, (ASTNode) event.getNewValue(), getIndent(startPos), true, editGroup);
- try {
- return getScanner().getTokenEndOffset(ITerminalSymbols.TokenNameDOT, offset + length);
- } catch (CoreException e) {
- handleException(e);
- }
- break;
- }
- }
- }
- Object node= getOriginalValue(parent, property);
- if (node == null) {
- return startPos;
- }
- int pos= doVisit((ASTNode) node);
- try {
- return getScanner().getTokenEndOffset(ITerminalSymbols.TokenNameDOT, pos);
- } catch (CoreException e) {
- handleException(e);
- }
- return pos;
- }
-
- class ParagraphListRewriter extends ListRewriter {
-
- public final static int DEFAULT_SPACING= 1;
-
- private int initialIndent;
- private int separatorLines;
-
- public ParagraphListRewriter(int initialIndent, int separator) {
- this.initialIndent= initialIndent;
- this.separatorLines= separator;
- }
-
- protected int getInitialIndent() {
- return this.initialIndent;
- }
-
- protected String getSeparatorString(int nodeIndex) {
- int newLines= this.separatorLines == -1 ? getNewLines(nodeIndex) : this.separatorLines;
-
- String lineDelim= getLineDelimiter();
- StringBuffer buf= new StringBuffer(lineDelim);
- for (int i= 0; i < newLines; i++) {
- buf.append(lineDelim);
- }
- buf.append(createIndentString(getNodeIndent(nodeIndex + 1)));
- return buf.toString();
- }
-
- private ASTNode getNode(int nodeIndex) {
- ASTNode elem= (ASTNode) this.list[nodeIndex].getOriginalValue();
- if (elem == null) {
- elem= (ASTNode) this.list[nodeIndex].getNewValue();
- }
- return elem;
- }
-
- private int getNewLines(int nodeIndex) {
- ASTNode curr= getNode(nodeIndex);
- ASTNode next= getNode(nodeIndex + 1);
-
- int currKind= curr.getNodeType();
- int nextKind= next.getNodeType();
-
- ASTNode last= null;
- ASTNode secondLast= null;
- for (int i= 0; i < this.list.length; i++) {
- ASTNode elem= (ASTNode) this.list[i].getOriginalValue();
- if (elem != null) {
- if (last != null) {
- if (elem.getNodeType() == nextKind && last.getNodeType() == currKind) {
- return countEmptyLines(last);
- }
- secondLast= last;
- }
- last= elem;
- }
- }
- if (currKind == ASTNode.FIELD_DECLARATION && nextKind == ASTNode.FIELD_DECLARATION ) {
- return 0;
- }
- if (secondLast != null) {
- return countEmptyLines(secondLast);
- }
- return DEFAULT_SPACING;
- }
-
- private int countEmptyLines(ASTNode last) {
- LineInformation lineInformation= getLineInformation();
- int lastLine= lineInformation.getLineOfOffset(getExtendedEnd(last));
- if (lastLine >= 0) {
- int startLine= lastLine + 1;
- int start= lineInformation.getLineOffset(startLine);
- if (start < 0) {
- return 0;
- }
- char[] cont= getContent();
- int i= start;
- while (i < cont.length && ScannerHelper.isWhitespace(cont[i])) {
- i++;
- }
- if (i > start) {
- lastLine= lineInformation.getLineOfOffset(i);
- if (lastLine > startLine) {
- return lastLine - startLine;
- }
- }
- }
- return 0;
- }
- }
-
- private int rewriteParagraphList(ASTNode parent, StructuralPropertyDescriptor property, int insertPos, int insertIndent, int separator, int lead) {
- RewriteEvent event= getEvent(parent, property);
- if (event == null || event.getChangeKind() == RewriteEvent.UNCHANGED) {
- return doVisit(parent, property, insertPos);
- }
-
- RewriteEvent[] events= event.getChildren();
- ParagraphListRewriter listRewriter= new ParagraphListRewriter(insertIndent, separator);
- StringBuffer leadString= new StringBuffer();
- if (isAllOfKind(events, RewriteEvent.INSERTED)) {
- for (int i= 0; i < lead; i++) {
- leadString.append(getLineDelimiter());
- }
- leadString.append(createIndentString(insertIndent));
- }
- return listRewriter.rewriteList(parent, property, insertPos, leadString.toString());
- }
-
- private int rewriteOptionalTypeParameters(ASTNode parent, StructuralPropertyDescriptor property, int offset, String keyword, boolean adjustOnNext, boolean needsSpaceOnRemoveAll) {
- int pos= offset;
- RewriteEvent event= getEvent(parent, property);
- if (event != null && event.getChangeKind() != RewriteEvent.UNCHANGED) {
- RewriteEvent[] children= event.getChildren();
- try {
- boolean isAllInserted= isAllOfKind(children, RewriteEvent.INSERTED);
- if (isAllInserted && adjustOnNext) {
- pos= getScanner().getNextStartOffset(pos, false); // adjust on next element
- }
- boolean isAllRemoved= !isAllInserted && isAllOfKind(children, RewriteEvent.REMOVED);
- if (isAllRemoved) { // all removed: set start to left bracket
- int posBeforeOpenBracket= getScanner().getTokenStartOffset(ITerminalSymbols.TokenNameLESS, pos);
- if (posBeforeOpenBracket != pos) {
- needsSpaceOnRemoveAll= false;
- }
- pos= posBeforeOpenBracket;
- }
- pos= new ListRewriter().rewriteList(parent, property, pos, String.valueOf('<'), ", "); //$NON-NLS-1$
- if (isAllRemoved) { // all removed: remove right and space up to next element
- int endPos= getScanner().getTokenEndOffset(ITerminalSymbols.TokenNameGREATER, pos); // set pos to '>'
- endPos= getScanner().getNextStartOffset(endPos, false);
- String replacement= needsSpaceOnRemoveAll ? String.valueOf(' ') : new String();
- doTextReplace(pos, endPos - pos, replacement, getEditGroup(children[children.length - 1]));
- return endPos;
- } else if (isAllInserted) {
- doTextInsert(pos, String.valueOf('>' + keyword), getEditGroup(children[children.length - 1]));
- return pos;
- }
- } catch (CoreException e) {
- handleException(e);
- }
- } else {
- pos= doVisit(parent, property, pos);
- }
- if (pos != offset) { // list contained some type -> parse after closing bracket
- try {
- return getScanner().getTokenEndOffset(ITerminalSymbols.TokenNameGREATER, pos);
- } catch (CoreException e) {
- handleException(e);
- }
- }
- return pos;
- }
-
- private boolean isAllOfKind(RewriteEvent[] children, int kind) {
- for (int i= 0; i < children.length; i++) {
- if (children[i].getChangeKind() != kind) {
- return false;
- }
- }
- return true;
- }
-
- private int rewriteNodeList(ASTNode parent, StructuralPropertyDescriptor property, int pos, String keyword, String separator) {
- RewriteEvent event= getEvent(parent, property);
- if (event != null && event.getChangeKind() != RewriteEvent.UNCHANGED) {
- return new ListRewriter().rewriteList(parent, property, pos, keyword, separator);
- }
- return doVisit(parent, property, pos);
- }
-
- private void rewriteMethodBody(FunctionDeclaration parent, int startPos) {
- RewriteEvent event= getEvent(parent, FunctionDeclaration.BODY_PROPERTY);
- if (event != null) {
- switch (event.getChangeKind()) {
- case RewriteEvent.INSERTED: {
- int endPos= parent.getStartPosition() + parent.getLength();
- TextEditGroup editGroup= getEditGroup(event);
- ASTNode body= (ASTNode) event.getNewValue();
- doTextRemove(startPos, endPos - startPos, editGroup);
- int indent= getIndent(parent.getStartPosition());
- String prefix= this.formatter.METHOD_BODY.getPrefix(indent);
- doTextInsert(startPos, prefix, editGroup);
- doTextInsert(startPos, body, indent, true, editGroup);
- return;
- }
- case RewriteEvent.REMOVED: {
- TextEditGroup editGroup= getEditGroup(event);
- ASTNode body= (ASTNode) event.getOriginalValue();
- int endPos= parent.getStartPosition() + parent.getLength();
- doTextRemoveAndVisit(startPos, endPos - startPos, body, editGroup);
- doTextInsert(startPos, ";", editGroup); //$NON-NLS-1$
- return;
- }
- case RewriteEvent.REPLACED: {
- TextEditGroup editGroup= getEditGroup(event);
- ASTNode body= (ASTNode) event.getOriginalValue();
- doTextRemoveAndVisit(body.getStartPosition(), body.getLength(), body, editGroup);
- doTextInsert(body.getStartPosition(), (ASTNode) event.getNewValue(), getIndent(body.getStartPosition()), true, editGroup);
- return;
- }
- }
- }
- voidVisit(parent, FunctionDeclaration.BODY_PROPERTY);
- }
-
- private int rewriteExtraDimensions(ASTNode parent, StructuralPropertyDescriptor property, int pos) {
- RewriteEvent event= getEvent(parent, property);
- if (event == null || event.getChangeKind() == RewriteEvent.UNCHANGED) {
- return ((Integer) getOriginalValue(parent, property)).intValue();
- }
- int oldDim= ((Integer) event.getOriginalValue()).intValue();
- int newDim= ((Integer) event.getNewValue()).intValue();
-
- if (oldDim != newDim) {
- TextEditGroup editGroup= getEditGroup(event);
- rewriteExtraDimensions(oldDim, newDim, pos, editGroup);
- }
- return oldDim;
- }
-
- private void rewriteExtraDimensions(int oldDim, int newDim, int pos, TextEditGroup editGroup) {
-
- if (oldDim < newDim) {
- for (int i= oldDim; i < newDim; i++) {
- doTextInsert(pos, "[]", editGroup); //$NON-NLS-1$
- }
- } else if (newDim < oldDim) {
- try {
- getScanner().setOffset(pos);
- for (int i= newDim; i < oldDim; i++) {
- getScanner().readToToken(ITerminalSymbols.TokenNameRBRACKET);
- }
- doTextRemove(pos, getScanner().getCurrentEndOffset() - pos, editGroup);
- } catch (CoreException e) {
- handleException(e);
- }
- }
- }
-
- /*
- * Next token is a left brace. Returns the offset after the brace. For incomplete code, return the start offset.
- */
- private int getPosAfterLeftBrace(int pos) {
- try {
- int nextToken= getScanner().readNext(pos, true);
- if (nextToken == ITerminalSymbols.TokenNameLBRACE) {
- return getScanner().getCurrentEndOffset();
- }
- } catch (CoreException e) {
- handleException(e);
- }
- return pos;
- }
-
- final int getIndent(int offset) {
- return this.formatter.computeIndentUnits(getIndentOfLine(offset));
- }
-
- final void doTextInsert(int insertOffset, ASTNode node, int initialIndentLevel, boolean removeLeadingIndent, TextEditGroup editGroup) {
- ArrayList markers= new ArrayList();
- String formatted= this.formatter.getFormattedResult(node, initialIndentLevel, markers);
-
-
- int currPos= 0;
- if (removeLeadingIndent) {
- while (currPos < formatted.length() && ScannerHelper.isWhitespace(formatted.charAt(currPos))) {
- currPos++;
- }
- }
- for (int i= 0; i < markers.size(); i++) { // markers.size can change!
- NodeMarker curr= (NodeMarker) markers.get(i);
-
- int offset= curr.offset;
- if (offset != currPos) {
- String insertStr= formatted.substring(currPos, offset);
- doTextInsert(insertOffset, insertStr, editGroup); // insert until the marker's begin
- }
-
- Object data= curr.data;
- if (data instanceof TextEditGroup) { // tracking a node
- // need to split and create 2 edits as tracking node can surround replaced node.
- TextEdit edit= new RangeMarker(insertOffset, 0);
- addEditGroup((TextEditGroup) data, edit);
- addEdit(edit);
- if (curr.length != 0) {
- int end= offset + curr.length;
- int k= i + 1;
- while (k < markers.size() && ((NodeMarker) markers.get(k)).offset < end) {
- k++;
- }
- curr.offset= end;
- curr.length= 0;
- markers.add(k, curr); // add again for end position
- }
- currPos= offset;
- } else {
- String destIndentString= this.formatter.getIndentString(getCurrentLine(formatted, offset));
- if (data instanceof CopyPlaceholderData) { // replace with a copy/move target
- CopySourceInfo copySource= ((CopyPlaceholderData) data).copySource;
- int srcIndentLevel= getIndent(copySource.getNode().getStartPosition());
- TextEdit sourceEdit= getCopySourceEdit(copySource);
- doTextCopy(sourceEdit, insertOffset, srcIndentLevel, destIndentString, editGroup);
- currPos= offset + curr.length; // continue to insert after the replaced string
- if (needsNewLineForLineComment(copySource.getNode(), formatted, currPos)) {
- doTextInsert(insertOffset, getLineDelimiter(), editGroup);
- }
- } else if (data instanceof StringPlaceholderData) { // replace with a placeholder
- String code= ((StringPlaceholderData) data).code;
- String str= this.formatter.changeIndent(code, 0, destIndentString);
- doTextInsert(insertOffset, str, editGroup);
- currPos= offset + curr.length; // continue to insert after the replaced string
- }
- }
-
- }
- if (currPos < formatted.length()) {
- String insertStr= formatted.substring(currPos);
- doTextInsert(insertOffset, insertStr, editGroup);
- }
- }
-
- private boolean needsNewLineForLineComment(ASTNode node, String formatted, int offset) {
- if (!this.lineCommentEndOffsets.isEndOfLineComment(getExtendedEnd(node), this.content)) {
- return false;
- }
- // copied code ends with a line comment, but doesn't contain the new line
- return offset < formatted.length() && !IndentManipulation.isLineDelimiterChar(formatted.charAt(offset));
- }
-
- private String getCurrentLine(String str, int pos) {
- for (int i= pos - 1; i>= 0; i--) {
- char ch= str.charAt(i);
- if (IndentManipulation.isLineDelimiterChar(ch)) {
- return str.substring(i + 1, pos);
- }
- }
- return str.substring(0, pos);
- }
-
-
- private void rewriteModifiers(ASTNode parent, StructuralPropertyDescriptor property, int offset) {
-// RewriteEvent event= getEvent(parent, property);
-// if (event == null || event.getChangeKind() != RewriteEvent.REPLACED) {
-// return;
-// }
-// try {
-// int oldModifiers= ((Integer) event.getOriginalValue()).intValue();
-// int newModifiers= ((Integer) event.getNewValue()).intValue();
-// TextEditGroup editGroup= getEditGroup(event);
-//
-// TokenScanner scanner= getScanner();
-//
-// int tok= scanner.readNext(offset, false);
-// int startPos= scanner.getCurrentStartOffset();
-// int nextStart= startPos;
-// loop: while (true) {
-// if (TokenScanner.isComment(tok)) {
-// tok= scanner.readNext(true); // next non-comment token
-// }
-// boolean keep= true;
-// switch (tok) {
-// case ITerminalSymbols.TokenNamepublic: keep= Modifier.isPublic(newModifiers); break;
-// case ITerminalSymbols.TokenNameprotected: keep= Modifier.isProtected(newModifiers); break;
-// case ITerminalSymbols.TokenNameprivate: keep= Modifier.isPrivate(newModifiers); break;
-// case ITerminalSymbols.TokenNamestatic: keep= Modifier.isStatic(newModifiers); break;
-// case ITerminalSymbols.TokenNamefinal: keep= Modifier.isFinal(newModifiers); break;
-// case ITerminalSymbols.TokenNameabstract: keep= Modifier.isAbstract(newModifiers); break;
-// case ITerminalSymbols.TokenNamenative: keep= Modifier.isNative(newModifiers); break;
-// case ITerminalSymbols.TokenNamevolatile: keep= Modifier.isVolatile(newModifiers); break;
-// case ITerminalSymbols.TokenNamestrictfp: keep= Modifier.isStrictfp(newModifiers); break;
-// case ITerminalSymbols.TokenNametransient: keep= Modifier.isTransient(newModifiers); break;
-// case ITerminalSymbols.TokenNamesynchronized: keep= Modifier.isSynchronized(newModifiers); break;
-// default:
-// break loop;
-// }
-// tok= getScanner().readNext(false); // include comments
-// int currPos= nextStart;
-// nextStart= getScanner().getCurrentStartOffset();
-// if (!keep) {
-// doTextRemove(currPos, nextStart - currPos, editGroup);
-// }
-// }
-// int addedModifiers= newModifiers & ~oldModifiers;
-// if (addedModifiers != 0) {
-// if (startPos != nextStart) {
-// int visibilityModifiers= addedModifiers & (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED);
-// if (visibilityModifiers != 0) {
-// StringBuffer buf= new StringBuffer();
-// ASTRewriteFlattener.printModifiers(visibilityModifiers, buf);
-// doTextInsert(startPos, buf.toString(), editGroup);
-// addedModifiers &= ~visibilityModifiers;
-// }
-// }
-// StringBuffer buf= new StringBuffer();
-// ASTRewriteFlattener.printModifiers(addedModifiers, buf);
-// doTextInsert(nextStart, buf.toString(), editGroup);
-// }
-// } catch (CoreException e) {
-// handleException(e);
-// }
- }
-
- class ModifierRewriter extends ListRewriter {
-
- private final Prefix annotationSeparation;
-
- public ModifierRewriter(Prefix annotationSeparation) {
- this.annotationSeparation= annotationSeparation;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.core.dom.rewrite.ASTRewriteAnalyzer.ListRewriter#getSeparatorString(int)
- */
- protected String getSeparatorString(int nodeIndex) {
- ASTNode curr= getNewNode(nodeIndex);
- return super.getSeparatorString(nodeIndex);
- }
- }
-
-
- private int rewriteModifiers2(ASTNode node, ChildListPropertyDescriptor property, int pos) {
-// RewriteEvent event= getEvent(node, property);
-// if (event == null || event.getChangeKind() == RewriteEvent.UNCHANGED) {
- return doVisit(node, property, pos);
-// }
-// RewriteEvent[] children= event.getChildren();
-// boolean isAllInsert= isAllOfKind(children, RewriteEvent.INSERTED);
-// boolean isAllRemove= isAllOfKind(children, RewriteEvent.REMOVED);
-// if (isAllInsert || isAllRemove) {
-// // update pos
-// try {
-// pos= getScanner().getNextStartOffset(pos, false);
-// } catch (CoreException e) {
-// handleException(e);
-// }
-// }
-//
-// int endPos= new ModifierRewriter(this.formatter.ANNOTATION_SEPARATION).rewriteList(node, property, pos, "", " "); //$NON-NLS-1$ //$NON-NLS-2$
-//
-// try {
-// int nextPos= getScanner().getNextStartOffset(endPos, false);
-//
-// boolean lastUnchanged= children[children.length - 1].getChangeKind() != RewriteEvent.UNCHANGED;
-//
-// if (isAllRemove) {
-// doTextRemove(endPos, nextPos - endPos, getEditGroup(children[children.length - 1]));
-// return nextPos;
-// } else if (isAllInsert || (nextPos == endPos && lastUnchanged)) { // see bug 165654
-// RewriteEvent lastChild= children[children.length - 1];
-// String separator;
-// if (lastChild.getNewValue() instanceof Annotation) {
-// separator= this.formatter.ANNOTATION_SEPARATION.getPrefix(getIndent(pos));
-// } else {
-// separator= String.valueOf(' ');
-// }
-// doTextInsert(endPos, separator, getEditGroup(lastChild));
-// }
-// } catch (CoreException e) {
-// handleException(e);
-// }
-// return endPos;
- }
-
-
- private void replaceOperation(int posBeforeOperation, String newOperation, TextEditGroup editGroup) {
- try {
- getScanner().readNext(posBeforeOperation, true);
- doTextReplace(getScanner().getCurrentStartOffset(), getScanner().getCurrentLength(), newOperation, editGroup);
- } catch (CoreException e) {
- handleException(e);
- }
- }
-
- private void rewriteOperation(ASTNode parent, StructuralPropertyDescriptor property, int posBeforeOperation) {
- RewriteEvent event= getEvent(parent, property);
- if (event != null && event.getChangeKind() != RewriteEvent.UNCHANGED) {
- try {
- String newOperation= event.getNewValue().toString();
- TextEditGroup editGroup= getEditGroup(event);
- getScanner().readNext(posBeforeOperation, true);
- doTextReplace(getScanner().getCurrentStartOffset(), getScanner().getCurrentLength(), newOperation, editGroup);
- } catch (CoreException e) {
- handleException(e);
- }
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#postVisit(ASTNode)
- */
- public void postVisit(ASTNode node) {
- TextEditGroup editGroup= this.eventStore.getTrackedNodeData(node);
- if (editGroup != null) {
- this.currentEdit= this.currentEdit.getParent();
- }
- // remove copy source edits
- doCopySourcePostVisit(node, this.sourceCopyEndNodes);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#preVisit(ASTNode)
- */
- public void preVisit(ASTNode node) {
- // copies, then range marker
-
- CopySourceInfo[] infos= this.eventStore.getNodeCopySources(node);
- doCopySourcePreVisit(infos, this.sourceCopyEndNodes);
-
- TextEditGroup editGroup= this.eventStore.getTrackedNodeData(node);
- if (editGroup != null) {
- SourceRange range= getExtendedRange(node);
- int offset= range.getStartPosition();
- int length= range.getLength();
- TextEdit edit= new RangeMarker(offset, length);
- addEditGroup(editGroup, edit);
- addEdit(edit);
- this.currentEdit= edit;
- }
- }
-
- final void doCopySourcePreVisit(CopySourceInfo[] infos, Stack nodeEndStack) {
- if (infos != null) {
- for (int i= 0; i < infos.length; i++) {
- CopySourceInfo curr= infos[i];
- TextEdit edit= getCopySourceEdit(curr);
- addEdit(edit);
- this.currentEdit= edit;
- nodeEndStack.push(curr.getNode());
- }
- }
- }
-
- final void doCopySourcePostVisit(ASTNode node, Stack nodeEndStack) {
- while (!nodeEndStack.isEmpty() && nodeEndStack.peek() == node) {
- nodeEndStack.pop();
- this.currentEdit= this.currentEdit.getParent();
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(JavaScriptUnit)
- */
- public boolean visit(JavaScriptUnit node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- int startPos= rewriteNode(node, JavaScriptUnit.PACKAGE_PROPERTY, 0, ASTRewriteFormatter.NONE);
-
- if (getChangeKind(node, JavaScriptUnit.PACKAGE_PROPERTY) == RewriteEvent.INSERTED) {
- doTextInsert(0, getLineDelimiter(), getEditGroup(node, JavaScriptUnit.PACKAGE_PROPERTY));
- }
-
- startPos= rewriteParagraphList(node, JavaScriptUnit.IMPORTS_PROPERTY, startPos, 0, 0, 2);
-// startPos= rewriteParagraphList(node, JavaScriptUnit.TYPES_PROPERTY, startPos, 0, -1, 2);
- rewriteParagraphList(node, JavaScriptUnit.STATEMENTS_PROPERTY, startPos, 0, -1, 1);
- return false;
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(TypeDeclaration)
- */
- public boolean visit(TypeDeclaration node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
- int apiLevel= node.getAST().apiLevel();
-
- int pos= rewriteJavadoc(node, TypeDeclaration.JAVADOC_PROPERTY);
-
- if (apiLevel == JLS2_INTERNAL) {
- rewriteModifiers(node, TypeDeclaration.MODIFIERS_PROPERTY, pos);
- } else {
- rewriteModifiers2(node, TypeDeclaration.MODIFIERS2_PROPERTY, pos);
- }
-
- // name
- pos= rewriteRequiredNode(node, TypeDeclaration.NAME_PROPERTY);
-
- // superclass
- ChildPropertyDescriptor superClassProperty= (apiLevel == JLS2_INTERNAL) ? TypeDeclaration.SUPERCLASS_PROPERTY : TypeDeclaration.SUPERCLASS_TYPE_PROPERTY;
-
- RewriteEvent superClassEvent= getEvent(node, superClassProperty);
-
- int changeKind= superClassEvent != null ? superClassEvent.getChangeKind() : RewriteEvent.UNCHANGED;
- switch (changeKind) {
- case RewriteEvent.INSERTED: {
- doTextInsert(pos, " extends ", getEditGroup(superClassEvent)); //$NON-NLS-1$
- doTextInsert(pos, (ASTNode) superClassEvent.getNewValue(), 0, false, getEditGroup(superClassEvent));
- break;
- }
- case RewriteEvent.REMOVED: {
- ASTNode superClass= (ASTNode) superClassEvent.getOriginalValue();
- int endPos= getExtendedEnd(superClass);
- doTextRemoveAndVisit(pos, endPos - pos, superClass, getEditGroup(superClassEvent));
- pos= endPos;
- break;
- }
- case RewriteEvent.REPLACED: {
- ASTNode superClass= (ASTNode) superClassEvent.getOriginalValue();
- SourceRange range= getExtendedRange(superClass);
- int offset= range.getStartPosition();
- int length= range.getLength();
- doTextRemoveAndVisit(offset, length, superClass, getEditGroup(superClassEvent));
- doTextInsert(offset, (ASTNode) superClassEvent.getNewValue(), 0, false, getEditGroup(superClassEvent));
- pos= offset + length;
- break;
- }
- case RewriteEvent.UNCHANGED: {
- pos= doVisit(node, superClassProperty, pos);
- }
- }
-
- // type members
- // startPos : find position after left brace of type, be aware that bracket might be missing
- int startIndent= getIndent(node.getStartPosition()) + 1;
- int startPos= getPosAfterLeftBrace(pos);
- rewriteParagraphList(node, TypeDeclaration.BODY_DECLARATIONS_PROPERTY, startPos, startIndent, -1, 2);
- return false;
- }
-
- private void rewriteReturnType(FunctionDeclaration node, boolean isConstructor, boolean isConstructorChange) {
- ChildPropertyDescriptor property= (node.getAST().apiLevel() == JLS2_INTERNAL) ? FunctionDeclaration.RETURN_TYPE_PROPERTY : FunctionDeclaration.RETURN_TYPE2_PROPERTY;
-
- // weakness in the AST: return type can exist, even if missing in source
- ASTNode originalReturnType= (ASTNode) getOriginalValue(node, property);
- boolean returnTypeExists= originalReturnType != null && originalReturnType.getStartPosition() != -1;
- if (!isConstructorChange && returnTypeExists) {
- rewriteRequiredNode(node, property);
- return;
- }
- // difficult cases: return type insert or remove
- ASTNode newReturnType= (ASTNode) getNewValue(node, property);
- if (isConstructorChange || !returnTypeExists && newReturnType != originalReturnType) {
- // use the start offset of the method name to insert
- ASTNode originalMethodName= (ASTNode) getOriginalValue(node, FunctionDeclaration.NAME_PROPERTY);
- int nextStart= originalMethodName.getStartPosition(); // see bug 84049: can't use extended offset
- TextEditGroup editGroup= getEditGroup(node, property);
- if (isConstructor || !returnTypeExists) { // insert
- doTextInsert(nextStart, newReturnType, getIndent(nextStart), true, editGroup);
- doTextInsert(nextStart, " ", editGroup); //$NON-NLS-1$
- } else { // remove up to the method name
- int offset= getExtendedOffset(originalReturnType);
- doTextRemoveAndVisit(offset, nextStart - offset, originalReturnType, editGroup);
- }
- }
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(FunctionDeclaration)
- */
- public boolean visit(FunctionDeclaration node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
- int pos= rewriteJavadoc(node, FunctionDeclaration.JAVADOC_PROPERTY);
-// if (node.getAST().apiLevel() == JLS2_INTERNAL) {
-// rewriteModifiers(node, FunctionDeclaration.MODIFIERS_PROPERTY, pos);
-// } else {
-// pos= rewriteModifiers2(node, FunctionDeclaration.MODIFIERS2_PROPERTY, pos);
-// pos= rewriteOptionalTypeParameters(node, FunctionDeclaration.TYPE_PARAMETERS_PROPERTY, pos, " ", true, pos != node.getStartPosition()); //$NON-NLS-1$
-// }
-
- boolean isConstructorChange= isChanged(node, FunctionDeclaration.CONSTRUCTOR_PROPERTY);
- boolean isConstructor= ((Boolean) getOriginalValue(node, FunctionDeclaration.CONSTRUCTOR_PROPERTY)).booleanValue();
- if (!isConstructor || isConstructorChange) {
- rewriteReturnType(node, isConstructor, isConstructorChange);
- }
-
- try {
- // method name
- pos= getScanner().getTokenEndOffset(ITerminalSymbols.TokenNamefunction, pos);
-
- pos= rewriteNode(node, FunctionDeclaration.NAME_PROPERTY, pos, ASTRewriteFormatter.NONE);
-
- // parameters
- if (isChanged(node, FunctionDeclaration.PARAMETERS_PROPERTY)) {
- pos= getScanner().getTokenEndOffset(ITerminalSymbols.TokenNameLPAREN, pos);
- pos= rewriteNodeList(node, FunctionDeclaration.PARAMETERS_PROPERTY, pos, "", ", "); //$NON-NLS-1$ //$NON-NLS-2$
- } else {
- pos= doVisit(node, FunctionDeclaration.PARAMETERS_PROPERTY, pos);
- }
-
- pos= getScanner().getTokenEndOffset(ITerminalSymbols.TokenNameRPAREN, pos);
-
- int extraDims= rewriteExtraDimensions(node, FunctionDeclaration.EXTRA_DIMENSIONS_PROPERTY, pos);
-
- boolean hasExceptionChanges= isChanged(node, FunctionDeclaration.THROWN_EXCEPTIONS_PROPERTY);
-
- int bodyChangeKind= getChangeKind(node, FunctionDeclaration.BODY_PROPERTY);
-
- if ((extraDims > 0) && (hasExceptionChanges || bodyChangeKind == RewriteEvent.INSERTED || bodyChangeKind == RewriteEvent.REMOVED)) {
- int dim= ((Integer) getOriginalValue(node, FunctionDeclaration.EXTRA_DIMENSIONS_PROPERTY)).intValue();
- while (dim > 0) {
- pos= getScanner().getTokenEndOffset(ITerminalSymbols.TokenNameRBRACKET, pos);
- dim--;
- }
- }
-
- pos= rewriteNodeList(node, FunctionDeclaration.THROWN_EXCEPTIONS_PROPERTY, pos, " throws ", ", "); //$NON-NLS-1$ //$NON-NLS-2$
- rewriteMethodBody(node, pos);
- } catch (CoreException e) {
- // ignore
- }
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jsdt.core.dom.ASTVisitor#visit(CastExpression)
- */
- public boolean visit(FunctionExpression node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- rewriteRequiredNode(node, FunctionExpression.METHOD_PROPERTY);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jsdt.core.dom.ASTVisitor#visit(CastExpression)
- */
- public boolean visit(ObjectLiteralField node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- rewriteRequiredNode(node, ObjectLiteralField.FIELD_NAME_PROPERTY);
-
- rewriteRequiredNode(node, ObjectLiteralField.INITIALIZER_PROPERTY);
- return false;
- }
-
- public boolean visit(RegularExpressionLiteral node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- String escapedSeq= (String) getNewValue(node, RegularExpressionLiteral.REGULAR_EXPRESSION_PROPERTY);
- TextEditGroup group = getEditGroup(node, RegularExpressionLiteral.REGULAR_EXPRESSION_PROPERTY);
- doTextReplace(node.getStartPosition(), node.getLength(), escapedSeq, group);
- return false;
- }
-
-
-
- public boolean visit(ObjectLiteral node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
- int pos= node.getStartPosition();
-
- try {
- if (isChanged(node, ObjectLiteral.FIELDS_PROPERTY)) {
- pos= getScanner().getTokenEndOffset(ITerminalSymbols.TokenNameLBRACE, pos);
- pos= rewriteNodeList(node, ObjectLiteral.FIELDS_PROPERTY, pos, "", ", "); //$NON-NLS-1$ //$NON-NLS-2$
- } else {
- pos= doVisit(node, ObjectLiteral.FIELDS_PROPERTY, pos);
- }
- } catch (CoreException e) {
- handleException(e);
- }
- return false;
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(Block)
- */
- public boolean visit(Block node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- int startPos;
- if (isCollapsed(node)) {
- startPos= node.getStartPosition();
- } else {
- startPos= getPosAfterLeftBrace(node.getStartPosition());
- }
- int startIndent= getIndent(node.getStartPosition()) + 1;
- rewriteParagraphList(node, Block.STATEMENTS_PROPERTY, startPos, startIndent, 0, 1);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(ReturnStatement)
- */
- public boolean visit(ReturnStatement node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- try {
- int offset= getScanner().getTokenEndOffset(ITerminalSymbols.TokenNamereturn, node.getStartPosition());
- ensureSpaceBeforeReplace(node, ReturnStatement.EXPRESSION_PROPERTY, offset, 0);
-
- rewriteNode(node, ReturnStatement.EXPRESSION_PROPERTY, offset, ASTRewriteFormatter.SPACE);
- } catch (CoreException e) {
- handleException(e);
- }
- return false;
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(AnonymousClassDeclaration)
- */
- public boolean visit(AnonymousClassDeclaration node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- int startPos= getPosAfterLeftBrace(node.getStartPosition());
- int startIndent= getIndent(node.getStartPosition()) + 1;
- rewriteParagraphList(node, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY, startPos, startIndent, -1, 2);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(ArrayAccess)
- */
- public boolean visit(ArrayAccess node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- rewriteRequiredNode(node, ArrayAccess.ARRAY_PROPERTY);
- rewriteRequiredNode(node, ArrayAccess.INDEX_PROPERTY);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(ArrayCreation)
- */
- public boolean visit(ArrayCreation node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- ArrayType arrayType= (ArrayType) getOriginalValue(node, ArrayCreation.TYPE_PROPERTY);
- int nOldBrackets= getDimensions(arrayType); // number of total brackets
- int nNewBrackets= nOldBrackets;
-
- TextEditGroup editGroup= null;
- RewriteEvent typeEvent= getEvent(node, ArrayCreation.TYPE_PROPERTY);
- if (typeEvent != null && typeEvent.getChangeKind() == RewriteEvent.REPLACED) { // changed arraytype can have different dimension or type name
- ArrayType replacingType= (ArrayType) typeEvent.getNewValue();
- editGroup= getEditGroup(typeEvent);
- Type newType= replacingType.getElementType();
- Type oldType= getElementType(arrayType);
- if (!newType.equals(oldType)) {
- SourceRange range= getExtendedRange(oldType);
- int offset= range.getStartPosition();
- int length= range.getLength();
- doTextRemove(offset, length, editGroup);
- doTextInsert(offset, newType, 0, false, editGroup);
- }
- nNewBrackets= replacingType.getDimensions(); // is replaced type
- }
- voidVisit(arrayType);
-
-
- try {
- int offset= getScanner().getTokenStartOffset(ITerminalSymbols.TokenNameLBRACKET, arrayType.getStartPosition());
- // dimension node with expressions
- RewriteEvent dimEvent= getEvent(node, ArrayCreation.DIMENSIONS_PROPERTY);
- boolean hasDimensionChanges= (dimEvent != null && dimEvent.getChangeKind() != RewriteEvent.UNCHANGED);
- if (hasDimensionChanges) {
- RewriteEvent[] events= dimEvent.getChildren();
- // offset on first opening brace
- for (int i= 0; i < events.length; i++) {
- RewriteEvent event= events[i];
- int changeKind= event.getChangeKind();
- if (changeKind == RewriteEvent.INSERTED) { // insert new dimension
- editGroup= getEditGroup(event);
- doTextInsert(offset, "[", editGroup); //$NON-NLS-1$
- doTextInsert(offset, (ASTNode) event.getNewValue(), 0, false, editGroup);
- doTextInsert(offset, "]", editGroup); //$NON-NLS-1$
- nNewBrackets--;
- } else {
- ASTNode elem= (ASTNode) event.getOriginalValue();
- int elemEnd= elem.getStartPosition() + elem.getLength();
- int endPos= getScanner().getTokenEndOffset(ITerminalSymbols.TokenNameRBRACKET, elemEnd);
- if (changeKind == RewriteEvent.REMOVED) {
- editGroup= getEditGroup(event);
- doTextRemoveAndVisit(offset, endPos - offset, elem, editGroup);
- } else if (changeKind == RewriteEvent.REPLACED) {
- editGroup= getEditGroup(event);
- SourceRange range= getExtendedRange(elem);
- int elemOffset= range.getStartPosition();
- int elemLength= range.getLength();
- doTextRemoveAndVisit(elemOffset, elemLength, elem, editGroup);
- doTextInsert(elemOffset, (ASTNode) event.getNewValue(), 0, false, editGroup);
- nNewBrackets--;
- } else {
- voidVisit(elem);
- nNewBrackets--;
- }
- offset= endPos;
- nOldBrackets--;
- }
- }
- } else {
- offset= doVisit(node, ArrayCreation.DIMENSIONS_PROPERTY, offset);
- }
- if (nOldBrackets != nNewBrackets) {
- if (!hasDimensionChanges) {
- offset= getScanner().getTokenEndOffset(ITerminalSymbols.TokenNameRBRACKET, offset);
- }
- rewriteExtraDimensions(nOldBrackets, nNewBrackets, offset, editGroup);
- }
-
- int kind= getChangeKind(node, ArrayCreation.INITIALIZER_PROPERTY);
- if (kind == RewriteEvent.REMOVED) {
- offset= getScanner().getPreviousTokenEndOffset(ITerminalSymbols.TokenNameLBRACE, offset);
- } else {
- offset= node.getStartPosition() + node.getLength(); // insert pos
- }
- rewriteNode(node, ArrayCreation.INITIALIZER_PROPERTY, offset, ASTRewriteFormatter.SPACE);
- } catch (CoreException e) {
- handleException(e);
- }
- return false;
- }
-
- private Type getElementType(ArrayType parent) {
- Type t = (Type) getOriginalValue(parent, ArrayType.COMPONENT_TYPE_PROPERTY);
- while (t.isArrayType()) {
- t = (Type) getOriginalValue(t, ArrayType.COMPONENT_TYPE_PROPERTY);
- }
- return t;
- }
-
- private int getDimensions(ArrayType parent) {
- Type t = (Type) getOriginalValue(parent, ArrayType.COMPONENT_TYPE_PROPERTY);
- int dimensions = 1; // always include this array type
- while (t.isArrayType()) {
- dimensions++;
- t = (Type) getOriginalValue(t, ArrayType.COMPONENT_TYPE_PROPERTY);
- }
- return dimensions;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(ArrayInitializer)
- */
- public boolean visit(ArrayInitializer node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- int startPos= getPosAfterLeftBrace(node.getStartPosition());
- rewriteNodeList(node, ArrayInitializer.EXPRESSIONS_PROPERTY, startPos, "", ", "); //$NON-NLS-1$ //$NON-NLS-2$
- return false;
- }
-
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(ArrayType)
- */
- public boolean visit(ArrayType node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- rewriteRequiredNode(node, ArrayType.COMPONENT_TYPE_PROPERTY);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(Assignment)
- */
- public boolean visit(Assignment node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- int pos= rewriteRequiredNode(node, Assignment.LEFT_HAND_SIDE_PROPERTY);
- rewriteOperation(node, Assignment.OPERATOR_PROPERTY, pos);
- rewriteRequiredNode(node, Assignment.RIGHT_HAND_SIDE_PROPERTY);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(BooleanLiteral)
- */
- public boolean visit(BooleanLiteral node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- Boolean newLiteral= (Boolean) getNewValue(node, BooleanLiteral.BOOLEAN_VALUE_PROPERTY);
- TextEditGroup group = getEditGroup(node, BooleanLiteral.BOOLEAN_VALUE_PROPERTY);
- doTextReplace(node.getStartPosition(), node.getLength(), newLiteral.toString(), group);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(BreakStatement)
- */
- public boolean visit(BreakStatement node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- try {
- int offset= getScanner().getTokenEndOffset(ITerminalSymbols.TokenNamebreak, node.getStartPosition());
- rewriteNode(node, BreakStatement.LABEL_PROPERTY, offset, ASTRewriteFormatter.SPACE); // space between break and label
- } catch (CoreException e) {
- handleException(e);
- }
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(CatchClause)
- */
- public boolean visit(CatchClause node) { // catch (Exception) Block
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- rewriteRequiredNode(node, CatchClause.EXCEPTION_PROPERTY);
- rewriteRequiredNode(node, CatchClause.BODY_PROPERTY);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(CharacterLiteral)
- */
- public boolean visit(CharacterLiteral node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- String escapedSeq= (String) getNewValue(node, CharacterLiteral.ESCAPED_VALUE_PROPERTY);
- TextEditGroup group = getEditGroup(node, CharacterLiteral.ESCAPED_VALUE_PROPERTY);
- doTextReplace(node.getStartPosition(), node.getLength(), escapedSeq, group);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(ClassInstanceCreation)
- */
- public boolean visit(ClassInstanceCreation node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- int pos= rewriteOptionalQualifier(node, ClassInstanceCreation.EXPRESSION_PROPERTY, node.getStartPosition());
- pos= rewriteRequiredNode(node, ClassInstanceCreation.MEMBER_PROPERTY);
-// if (node.getAST().apiLevel() == JLS2_INTERNAL) {
-// pos= rewriteRequiredNode(node, ClassInstanceCreation.NAME_PROPERTY);
-// } else {
-// if (isChanged(node, ClassInstanceCreation.TYPE_ARGUMENTS_PROPERTY)) {
-// try {
-// pos= getScanner().getTokenEndOffset(ITerminalSymbols.TokenNamenew, pos); //after 'new'
-// rewriteOptionalTypeParameters(node, ClassInstanceCreation.TYPE_ARGUMENTS_PROPERTY, pos, " ", true, true); //$NON-NLS-1$
-// } catch (CoreException e) {
-// handleException(e);
-// }
-// } else {
-// voidVisit(node, ClassInstanceCreation.TYPE_ARGUMENTS_PROPERTY);
-// }
-// pos= rewriteRequiredNode(node, ClassInstanceCreation.TYPE_PROPERTY);
-// }
-
- if (isChanged(node, ClassInstanceCreation.ARGUMENTS_PROPERTY)) {
- try {
- int startpos= getScanner().getTokenEndOffset(ITerminalSymbols.TokenNameLPAREN, pos);
- rewriteNodeList(node, ClassInstanceCreation.ARGUMENTS_PROPERTY, startpos, "", ", "); //$NON-NLS-1$ //$NON-NLS-2$
- } catch (CoreException e) {
- handleException(e);
- }
- } else {
- voidVisit(node, ClassInstanceCreation.ARGUMENTS_PROPERTY);
- }
-
- int kind= getChangeKind(node, ClassInstanceCreation.ANONYMOUS_CLASS_DECLARATION_PROPERTY);
- if (kind == RewriteEvent.REMOVED) {
- try {
- pos= getScanner().getPreviousTokenEndOffset(ITerminalSymbols.TokenNameLBRACE, pos);
- } catch (CoreException e) {
- handleException(e);
- }
- } else {
- pos= node.getStartPosition() + node.getLength(); // insert pos
- }
- rewriteNode(node, ClassInstanceCreation.ANONYMOUS_CLASS_DECLARATION_PROPERTY, pos, ASTRewriteFormatter.SPACE);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(ConditionalExpression)
- */
- public boolean visit(ConditionalExpression node) { // expression ? thenExpression : elseExpression
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- rewriteRequiredNode(node, ConditionalExpression.EXPRESSION_PROPERTY);
- rewriteRequiredNode(node, ConditionalExpression.THEN_EXPRESSION_PROPERTY);
- rewriteRequiredNode(node, ConditionalExpression.ELSE_EXPRESSION_PROPERTY);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(ConstructorInvocation)
- */
- public boolean visit(ConstructorInvocation node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
- int pos= node.getStartPosition();
- if (node.getAST().apiLevel() >= AST.JLS3) {
- pos= rewriteOptionalTypeParameters(node, ConstructorInvocation.TYPE_ARGUMENTS_PROPERTY, pos, "", false, false); //$NON-NLS-1$
- }
- try {
- pos= getScanner().getTokenEndOffset(ITerminalSymbols.TokenNameLPAREN, pos);
- rewriteNodeList(node, ConstructorInvocation.ARGUMENTS_PROPERTY, pos, "", ", "); //$NON-NLS-1$ //$NON-NLS-2$
- } catch (CoreException e) {
- handleException(e);
- }
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(ContinueStatement)
- */
- public boolean visit(ContinueStatement node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- try {
- int offset= getScanner().getTokenEndOffset(ITerminalSymbols.TokenNamecontinue, node.getStartPosition());
- rewriteNode(node, ContinueStatement.LABEL_PROPERTY, offset, ASTRewriteFormatter.SPACE); // space between continue and label
- } catch (CoreException e) {
- handleException(e);
- }
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(DoStatement)
- */
- public boolean visit(DoStatement node) { // do statement while expression
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- int pos= node.getStartPosition();
- try {
- RewriteEvent event= getEvent(node, DoStatement.BODY_PROPERTY);
- if (event != null && event.getChangeKind() == RewriteEvent.REPLACED) {
- int startOffset= getScanner().getTokenEndOffset(ITerminalSymbols.TokenNamedo, pos);
- ASTNode body= (ASTNode) event.getOriginalValue();
- int bodyEnd= body.getStartPosition() + body.getLength();
- int endPos= getScanner().getTokenStartOffset(ITerminalSymbols.TokenNamewhile, bodyEnd);
- rewriteBodyNode(node, DoStatement.BODY_PROPERTY, startOffset, endPos, getIndent(node.getStartPosition()), this.formatter.DO_BLOCK); // body
- } else {
- voidVisit(node, DoStatement.BODY_PROPERTY);
- }
- } catch (CoreException e) {
- handleException(e);
- }
-
- rewriteRequiredNode(node, DoStatement.EXPRESSION_PROPERTY);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(EmptyStatement)
- */
- public boolean visit(EmptyStatement node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- changeNotSupported(node); // no modification possible
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(ExpressionStatement)
- */
- public boolean visit(ExpressionStatement node) { // expression
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- rewriteRequiredNode(node, ExpressionStatement.EXPRESSION_PROPERTY);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(FieldAccess)
- */
- public boolean visit(FieldAccess node) { // expression.name
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- rewriteRequiredNode(node, FieldAccess.EXPRESSION_PROPERTY); // expression
- rewriteRequiredNode(node, FieldAccess.NAME_PROPERTY); // name
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(FieldDeclaration)
- */
- public boolean visit(FieldDeclaration node) { //{ Modifier } Type VariableDeclarationFragment { ',' VariableDeclarationFragment } ';'
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
- int pos= rewriteJavadoc(node, FieldDeclaration.JAVADOC_PROPERTY);
-
- if (node.getAST().apiLevel() == JLS2_INTERNAL) {
- rewriteModifiers(node, FieldDeclaration.MODIFIERS_PROPERTY, pos);
- } else {
- rewriteModifiers2(node, FieldDeclaration.MODIFIERS2_PROPERTY, pos);
- }
-
- pos= rewriteRequiredNode(node, FieldDeclaration.TYPE_PROPERTY);
- rewriteNodeList(node, FieldDeclaration.FRAGMENTS_PROPERTY, pos, "", ", "); //$NON-NLS-1$ //$NON-NLS-2$
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(ForStatement)
- */
- public boolean visit(ForStatement node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- try {
- int pos= node.getStartPosition();
-
- if (isChanged(node, ForStatement.INITIALIZERS_PROPERTY)) {
- // position after opening parent
- int startOffset= getScanner().getTokenEndOffset(ITerminalSymbols.TokenNameLPAREN, pos);
- pos= rewriteNodeList(node, ForStatement.INITIALIZERS_PROPERTY, startOffset, "", ", "); //$NON-NLS-1$ //$NON-NLS-2$
- } else {
- pos= doVisit(node, ForStatement.INITIALIZERS_PROPERTY, pos);
- }
-
- // position after first semicolon
- pos= getScanner().getTokenEndOffset(ITerminalSymbols.TokenNameSEMICOLON, pos);
-
- pos= rewriteNode(node, ForStatement.EXPRESSION_PROPERTY, pos, ASTRewriteFormatter.NONE);
-
- if (isChanged(node, ForStatement.UPDATERS_PROPERTY)) {
- int startOffset= getScanner().getTokenEndOffset(ITerminalSymbols.TokenNameSEMICOLON, pos);
- pos= rewriteNodeList(node, ForStatement.UPDATERS_PROPERTY, startOffset, "", ", "); //$NON-NLS-1$ //$NON-NLS-2$
- } else {
- pos= doVisit(node, ForStatement.UPDATERS_PROPERTY, pos);
- }
-
- RewriteEvent bodyEvent= getEvent(node, ForStatement.BODY_PROPERTY);
- if (bodyEvent != null && bodyEvent.getChangeKind() == RewriteEvent.REPLACED) {
- int startOffset= getScanner().getTokenEndOffset(ITerminalSymbols.TokenNameRPAREN, pos);
- rewriteBodyNode(node, ForStatement.BODY_PROPERTY, startOffset, -1, getIndent(node.getStartPosition()), this.formatter.FOR_BLOCK); // body
- } else {
- voidVisit(node, ForStatement.BODY_PROPERTY);
- }
-
- } catch (CoreException e) {
- handleException(e);
- }
-
-
- return false;
- }
-
-
- public boolean visit(ForInStatement node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- try {
- int pos= node.getStartPosition();
-
- pos= rewriteNode(node, ForInStatement.ITERATION_VARIABLE_PROPERTY, pos, ASTRewriteFormatter.NONE);
-
- // position after first semicolon
- pos= getScanner().getTokenEndOffset(ITerminalSymbols.TokenNamein, pos);
-
- pos= rewriteNode(node, ForInStatement.COLLECTION_PROPERTY, pos, ASTRewriteFormatter.NONE);
-
-
- RewriteEvent bodyEvent= getEvent(node, ForInStatement.BODY_PROPERTY);
- if (bodyEvent != null && bodyEvent.getChangeKind() == RewriteEvent.REPLACED) {
- int startOffset= getScanner().getTokenEndOffset(ITerminalSymbols.TokenNameRPAREN, pos);
- rewriteBodyNode(node, ForInStatement.BODY_PROPERTY, startOffset, -1, getIndent(node.getStartPosition()), this.formatter.FOR_BLOCK); // body
- } else {
- voidVisit(node, ForInStatement.BODY_PROPERTY);
- }
-
- } catch (CoreException e) {
- handleException(e);
- }
-
-
- return false;
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(IfStatement)
- */
- public boolean visit(IfStatement node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- int pos= rewriteRequiredNode(node, IfStatement.EXPRESSION_PROPERTY); // statement
-
- RewriteEvent thenEvent= getEvent(node, IfStatement.THEN_STATEMENT_PROPERTY);
- int elseChange= getChangeKind(node, IfStatement.ELSE_STATEMENT_PROPERTY);
-
- if (thenEvent != null && thenEvent.getChangeKind() != RewriteEvent.UNCHANGED) {
- try {
- pos= getScanner().getTokenEndOffset(ITerminalSymbols.TokenNameRPAREN, pos); // after the closing parent
- int indent= getIndent(node.getStartPosition());
-
- int endPos= -1;
- Object elseStatement= getOriginalValue(node, IfStatement.ELSE_STATEMENT_PROPERTY);
- if (elseStatement != null) {
- ASTNode thenStatement = (ASTNode) thenEvent.getOriginalValue();
- endPos= getScanner().getTokenStartOffset(ITerminalSymbols.TokenNameelse, thenStatement.getStartPosition() + thenStatement.getLength()); // else keyword
- }
- if (elseStatement == null || elseChange != RewriteEvent.UNCHANGED) {
- pos= rewriteBodyNode(node, IfStatement.THEN_STATEMENT_PROPERTY, pos, endPos, indent, this.formatter.IF_BLOCK_NO_ELSE);
- } else {
- pos= rewriteBodyNode(node, IfStatement.THEN_STATEMENT_PROPERTY, pos, endPos, indent, this.formatter.IF_BLOCK_WITH_ELSE);
- }
- } catch (CoreException e) {
- handleException(e);
- }
- } else {
- pos= doVisit(node, IfStatement.THEN_STATEMENT_PROPERTY, pos);
- }
-
- if (elseChange != RewriteEvent.UNCHANGED) {
- int indent= getIndent(node.getStartPosition());
- Object newThen= getNewValue(node, IfStatement.THEN_STATEMENT_PROPERTY);
- if (newThen instanceof Block) {
- rewriteBodyNode(node, IfStatement.ELSE_STATEMENT_PROPERTY, pos, -1, indent, this.formatter.ELSE_AFTER_BLOCK);
- } else {
- rewriteBodyNode(node, IfStatement.ELSE_STATEMENT_PROPERTY, pos, -1, indent, this.formatter.ELSE_AFTER_STATEMENT);
- }
- } else {
- pos= doVisit(node, IfStatement.ELSE_STATEMENT_PROPERTY, pos);
- }
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(ImportDeclaration)
- */
- public boolean visit(ImportDeclaration node) {
- if (node.isFileImport())
- return false;
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
- if (node.getAST().apiLevel() >= AST.JLS3) {
- RewriteEvent event= getEvent(node, ImportDeclaration.STATIC_PROPERTY);
- if (event != null && event.getChangeKind() != RewriteEvent.UNCHANGED) {
- try {
- int pos= getScanner().getTokenEndOffset(ITerminalSymbols.TokenNameimport, node.getStartPosition());
- boolean wasStatic= ((Boolean) event.getOriginalValue()).booleanValue();
- if (wasStatic) {
- int endPos= getScanner().getTokenEndOffset(ITerminalSymbols.TokenNamestatic, pos);
- doTextRemove(pos, endPos - pos, getEditGroup(event));
- } else {
- doTextInsert(pos, " static", getEditGroup(event)); //$NON-NLS-1$
- }
- } catch (CoreException e) {
- handleException(e);
- }
- }
- }
-
- int pos= rewriteRequiredNode(node, ImportDeclaration.NAME_PROPERTY);
-
- RewriteEvent event= getEvent(node, ImportDeclaration.ON_DEMAND_PROPERTY);
- if (event != null && event.getChangeKind() != RewriteEvent.UNCHANGED) {
- boolean isOnDemand= ((Boolean) event.getOriginalValue()).booleanValue();
- if (!isOnDemand) {
- doTextInsert(pos, ".*", getEditGroup(event)); //$NON-NLS-1$
- } else {
- try {
- int endPos= getScanner().getTokenStartOffset(ITerminalSymbols.TokenNameSEMICOLON, pos);
- doTextRemove(pos, endPos - pos, getEditGroup(event));
- } catch (CoreException e) {
- handleException(e);
- }
- }
- }
- return false;
- }
-
-
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(InfixExpression)
- */
- public boolean visit(InfixExpression node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- int pos= rewriteRequiredNode(node, InfixExpression.LEFT_OPERAND_PROPERTY);
-
- boolean needsNewOperation= isChanged(node, InfixExpression.OPERATOR_PROPERTY);
- String operation= getNewValue(node, InfixExpression.OPERATOR_PROPERTY).toString();
- if (needsNewOperation) {
- replaceOperation(pos, operation, getEditGroup(node, InfixExpression.OPERATOR_PROPERTY));
- }
-
- pos= rewriteRequiredNode(node, InfixExpression.RIGHT_OPERAND_PROPERTY);
-
- RewriteEvent event= getEvent(node, InfixExpression.EXTENDED_OPERANDS_PROPERTY);
- String prefixString= ' ' + operation + ' ';
-
- if (needsNewOperation) {
- int startPos= pos;
- TextEditGroup editGroup= getEditGroup(node, InfixExpression.OPERATOR_PROPERTY);
-
- if (event != null && event.getChangeKind() != RewriteEvent.UNCHANGED) {
- RewriteEvent[] extendedOperands= event.getChildren();
- for (int i= 0; i < extendedOperands.length; i++) {
- RewriteEvent curr= extendedOperands[i];
- ASTNode elem= (ASTNode) curr.getOriginalValue();
- if (elem != null) {
- if (curr.getChangeKind() != RewriteEvent.REPLACED) {
- replaceOperation(startPos, operation, editGroup);
- }
- startPos= elem.getStartPosition() + elem.getLength();
- }
- }
- } else {
- List extendedOperands= (List) getOriginalValue(node, InfixExpression.EXTENDED_OPERANDS_PROPERTY);
- for (int i= 0; i < extendedOperands.size(); i++) {
- ASTNode elem= (ASTNode) extendedOperands.get(i);
- replaceOperation(startPos, operation, editGroup);
- startPos= elem.getStartPosition() + elem.getLength();
- }
- }
- }
- rewriteNodeList(node, InfixExpression.EXTENDED_OPERANDS_PROPERTY, pos, prefixString, prefixString);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(Initializer)
- */
- public boolean visit(Initializer node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
- int pos= rewriteJavadoc(node, Initializer.JAVADOC_PROPERTY);
- if (node.getAST().apiLevel() == JLS2_INTERNAL) {
- rewriteModifiers(node, Initializer.MODIFIERS_PROPERTY, pos);
- } else {
- rewriteModifiers2(node, Initializer.MODIFIERS2_PROPERTY, pos);
- }
- rewriteRequiredNode(node, Initializer.BODY_PROPERTY);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(InstanceofExpression)
- */
- public boolean visit(InstanceofExpression node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- rewriteRequiredNode(node, InstanceofExpression.LEFT_OPERAND_PROPERTY);
- ensureSpaceAfterReplace(node, InstanceofExpression.LEFT_OPERAND_PROPERTY);
- rewriteRequiredNode(node, InstanceofExpression.RIGHT_OPERAND_PROPERTY);
- return false;
- }
-
- public void ensureSpaceAfterReplace(ASTNode node, ChildPropertyDescriptor desc) {
- if (getChangeKind(node, desc) == RewriteEvent.REPLACED) {
- int leftOperandEnd= getExtendedEnd((ASTNode) getOriginalValue(node, desc));
- try {
- int offset= getScanner().getNextStartOffset(leftOperandEnd, true); // instanceof
-
- if (offset == leftOperandEnd) {
- doTextInsert(offset, String.valueOf(' '), getEditGroup(node, desc));
- }
- } catch (CoreException e) {
- handleException(e);
- }
- }
- }
-
- public void ensureSpaceBeforeReplace(ASTNode node, ChildPropertyDescriptor desc, int offset, int numTokenBefore) {
- // bug 103970
- if (getChangeKind(node, desc) == RewriteEvent.REPLACED) {
- try {
- while (numTokenBefore > 0) {
- offset= getScanner().getNextEndOffset(offset, true);
- numTokenBefore--;
- }
- if (offset == getExtendedOffset((ASTNode) getOriginalValue(node, desc))) {
- doTextInsert(offset, String.valueOf(' '), getEditGroup(node, desc));
- }
- } catch (CoreException e) {
- handleException(e);
- }
- }
- }
-
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(Javadoc)
- */
- public boolean visit(JSdoc node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
- int startPos= node.getStartPosition() + 3;
- String separator= getLineDelimiter() + getIndentAtOffset(node.getStartPosition()) + " * "; //$NON-NLS-1$
-
- rewriteNodeList(node, JSdoc.TAGS_PROPERTY, startPos, separator, separator);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(LabeledStatement)
- */
- public boolean visit(LabeledStatement node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- rewriteRequiredNode(node, LabeledStatement.LABEL_PROPERTY);
- rewriteRequiredNode(node, LabeledStatement.BODY_PROPERTY);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(FunctionInvocation)
- */
- public boolean visit(FunctionInvocation node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- int pos= rewriteOptionalQualifier(node, FunctionInvocation.EXPRESSION_PROPERTY, node.getStartPosition());
- if (node.getAST().apiLevel() >= AST.JLS3) {
- pos= rewriteOptionalTypeParameters(node, FunctionInvocation.TYPE_ARGUMENTS_PROPERTY, pos, "", false, false); //$NON-NLS-1$
- }
-
- pos= rewriteNode(node, FunctionInvocation.NAME_PROPERTY,pos, ASTRewriteFormatter.NONE);
-
- if (isChanged(node, FunctionInvocation.ARGUMENTS_PROPERTY)) {
- // eval position after opening parent
- try {
- int startOffset= getScanner().getTokenEndOffset(ITerminalSymbols.TokenNameLPAREN, pos);
- rewriteNodeList(node, FunctionInvocation.ARGUMENTS_PROPERTY, startOffset, "", ", "); //$NON-NLS-1$ //$NON-NLS-2$
- } catch (CoreException e) {
- handleException(e);
- }
- } else {
- voidVisit(node, FunctionInvocation.ARGUMENTS_PROPERTY);
- }
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(NullLiteral)
- */
- public boolean visit(NullLiteral node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- changeNotSupported(node); // no modification possible
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(NumberLiteral)
- */
- public boolean visit(NumberLiteral node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
- String newLiteral= (String) getNewValue(node, NumberLiteral.TOKEN_PROPERTY);
- TextEditGroup group = getEditGroup(node, NumberLiteral.TOKEN_PROPERTY);
- doTextReplace(node.getStartPosition(), node.getLength(), newLiteral, group);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(PackageDeclaration)
- */
- public boolean visit(PackageDeclaration node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
- if (node.getAST().apiLevel() >= AST.JLS3) {
- int pos= rewriteJavadoc(node, PackageDeclaration.JAVADOC_PROPERTY);
- }
-
- rewriteRequiredNode(node, PackageDeclaration.NAME_PROPERTY);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(ParenthesizedExpression)
- */
- public boolean visit(ParenthesizedExpression node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- rewriteRequiredNode(node, ParenthesizedExpression.EXPRESSION_PROPERTY);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(PostfixExpression)
- */
- public boolean visit(PostfixExpression node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- int pos= rewriteRequiredNode(node, PostfixExpression.OPERAND_PROPERTY);
- rewriteOperation(node, PostfixExpression.OPERATOR_PROPERTY, pos);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(PrefixExpression)
- */
- public boolean visit(PrefixExpression node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- rewriteOperation(node, PrefixExpression.OPERATOR_PROPERTY, node.getStartPosition());
- rewriteRequiredNode(node, PrefixExpression.OPERAND_PROPERTY);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(PrimitiveType)
- */
- public boolean visit(PrimitiveType node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
- PrimitiveType.Code newCode= (PrimitiveType.Code) getNewValue(node, PrimitiveType.PRIMITIVE_TYPE_CODE_PROPERTY);
- TextEditGroup group = getEditGroup(node, PrimitiveType.PRIMITIVE_TYPE_CODE_PROPERTY);
- doTextReplace(node.getStartPosition(), node.getLength(), newCode.toString(), group);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(QualifiedName)
- */
- public boolean visit(QualifiedName node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- rewriteRequiredNode(node, QualifiedName.QUALIFIER_PROPERTY);
- rewriteRequiredNode(node, QualifiedName.NAME_PROPERTY);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(SimpleName)
- */
- public boolean visit(SimpleName node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
- String newString= (String) getNewValue(node, SimpleName.IDENTIFIER_PROPERTY);
- TextEditGroup group = getEditGroup(node, SimpleName.IDENTIFIER_PROPERTY);
- doTextReplace(node.getStartPosition(), node.getLength(), newString, group);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(SimpleType)
- */
- public boolean visit(SimpleType node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- rewriteRequiredNode(node, SimpleType.NAME_PROPERTY);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(SingleVariableDeclaration)
- */
- public boolean visit(SingleVariableDeclaration node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
- int pos= node.getStartPosition();
-// if (node.getAST().apiLevel() == JLS2_INTERNAL) {
-// rewriteModifiers(node, SingleVariableDeclaration.MODIFIERS_PROPERTY, pos);
-// } else {
-// rewriteModifiers2(node, SingleVariableDeclaration.MODIFIERS2_PROPERTY, pos);
-// }
- if (!node.getType().isInferred())
- pos= rewriteRequiredNode(node, SingleVariableDeclaration.TYPE_PROPERTY);
- if (node.getAST().apiLevel() >= AST.JLS3) {
- if (isChanged(node, SingleVariableDeclaration.VARARGS_PROPERTY)) {
- if (getNewValue(node, SingleVariableDeclaration.VARARGS_PROPERTY).equals(Boolean.TRUE)) {
- doTextInsert(pos, "...", getEditGroup(node, SingleVariableDeclaration.VARARGS_PROPERTY)); //$NON-NLS-1$
- } else {
- try {
- int ellipsisEnd= getScanner().getNextEndOffset(pos, true);
- doTextRemove(pos, ellipsisEnd - pos, getEditGroup(node, SingleVariableDeclaration.VARARGS_PROPERTY));
- } catch (CoreException e) {
- handleException(e);
- }
- }
- }
- }
-
- pos= rewriteRequiredNode(node, SingleVariableDeclaration.NAME_PROPERTY);
- int extraDims= rewriteExtraDimensions(node, SingleVariableDeclaration.EXTRA_DIMENSIONS_PROPERTY, pos);
-
- if (extraDims > 0) {
- int kind= getChangeKind(node, SingleVariableDeclaration.INITIALIZER_PROPERTY);
- if (kind == RewriteEvent.REMOVED) {
- try {
- pos= getScanner().getPreviousTokenEndOffset(ITerminalSymbols.TokenNameEQUAL, pos);
- } catch (CoreException e) {
- handleException(e);
- }
- } else {
- pos= node.getStartPosition() + node.getLength(); // insert pos
- }
- }
-
- rewriteNode(node, SingleVariableDeclaration.INITIALIZER_PROPERTY, pos, this.formatter.VAR_INITIALIZER);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(StringLiteral)
- */
- public boolean visit(StringLiteral node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
- String escapedSeq= (String) getNewValue(node, StringLiteral.ESCAPED_VALUE_PROPERTY);
- TextEditGroup group = getEditGroup(node, StringLiteral.ESCAPED_VALUE_PROPERTY);
- doTextReplace(node.getStartPosition(), node.getLength(), escapedSeq, group);
-
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(SuperConstructorInvocation)
- */
- public boolean visit(SuperConstructorInvocation node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- int pos= rewriteOptionalQualifier(node, SuperConstructorInvocation.EXPRESSION_PROPERTY, node.getStartPosition());
-
- if (node.getAST().apiLevel() >= AST.JLS3) {
- pos= rewriteOptionalTypeParameters(node, SuperConstructorInvocation.TYPE_ARGUMENTS_PROPERTY, pos, "", false, false); //$NON-NLS-1$
- }
-
- if (isChanged(node, SuperConstructorInvocation.ARGUMENTS_PROPERTY)) {
- // eval position after opening parent
- try {
- pos= getScanner().getTokenEndOffset(ITerminalSymbols.TokenNameLPAREN, pos);
- rewriteNodeList(node, SuperConstructorInvocation.ARGUMENTS_PROPERTY, pos, "", ", "); //$NON-NLS-1$ //$NON-NLS-2$
- } catch (CoreException e) {
- handleException(e);
- }
- } else {
- voidVisit(node, SuperConstructorInvocation.ARGUMENTS_PROPERTY);
- }
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(SuperFieldAccess)
- */
- public boolean visit(SuperFieldAccess node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- rewriteOptionalQualifier(node, SuperFieldAccess.QUALIFIER_PROPERTY, node.getStartPosition());
- rewriteRequiredNode(node, SuperFieldAccess.NAME_PROPERTY);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(SuperMethodInvocation)
- */
- public boolean visit(SuperMethodInvocation node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- int pos= rewriteOptionalQualifier(node, SuperMethodInvocation.QUALIFIER_PROPERTY, node.getStartPosition());
-
- if (node.getAST().apiLevel() >= AST.JLS3) {
- if (isChanged(node, SuperMethodInvocation.TYPE_ARGUMENTS_PROPERTY)) {
- try {
- pos= getScanner().getTokenEndOffset(ITerminalSymbols.TokenNameDOT, pos);
- rewriteOptionalTypeParameters(node, SuperMethodInvocation.TYPE_ARGUMENTS_PROPERTY, pos, "", false, false); //$NON-NLS-1$
- } catch (CoreException e) {
- handleException(e);
- }
- }
- }
-
- pos= rewriteRequiredNode(node, SuperMethodInvocation.NAME_PROPERTY);
-
- if (isChanged(node, SuperMethodInvocation.ARGUMENTS_PROPERTY)) {
- // eval position after opening parent
- try {
- pos= getScanner().getTokenEndOffset(ITerminalSymbols.TokenNameLPAREN, pos);
- rewriteNodeList(node, SuperMethodInvocation.ARGUMENTS_PROPERTY, pos, "", ", "); //$NON-NLS-1$ //$NON-NLS-2$
- } catch (CoreException e) {
- handleException(e);
- }
- } else {
- voidVisit(node, SuperMethodInvocation.ARGUMENTS_PROPERTY);
- }
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(SwitchCase)
- */
- public boolean visit(SwitchCase node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- // dont allow switching from case to default or back. New statements should be created.
- rewriteRequiredNode(node, SwitchCase.EXPRESSION_PROPERTY);
- return false;
- }
-
- class SwitchListRewriter extends ParagraphListRewriter {
-
- public SwitchListRewriter(int initialIndent) {
- super(initialIndent, 0);
- }
-
- protected int getNodeIndent(int nodeIndex) {
- int indent= getInitialIndent();
- ASTNode node= (ASTNode) this.list[nodeIndex].getOriginalValue();
- if (node == null) {
- node= (ASTNode) this.list[nodeIndex].getNewValue();
- }
- if (node.getNodeType() != ASTNode.SWITCH_CASE) {
- indent++;
- }
- return indent;
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(SwitchStatement)
- */
- public boolean visit(SwitchStatement node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- int pos= rewriteRequiredNode(node, SwitchStatement.EXPRESSION_PROPERTY);
-
- ChildListPropertyDescriptor property= SwitchStatement.STATEMENTS_PROPERTY;
- if (getChangeKind(node, property) != RewriteEvent.UNCHANGED) {
- try {
- pos= getScanner().getTokenEndOffset(ITerminalSymbols.TokenNameLBRACE, pos);
- int insertIndent= getIndent(node.getStartPosition()) + 1;
-
- ParagraphListRewriter listRewriter= new SwitchListRewriter(insertIndent);
- StringBuffer leadString= new StringBuffer();
- leadString.append(getLineDelimiter());
- leadString.append(createIndentString(insertIndent));
- listRewriter.rewriteList(node, property, pos, leadString.toString());
- } catch (CoreException e) {
- handleException(e);
- }
- } else {
- voidVisit(node, SwitchStatement.STATEMENTS_PROPERTY);
- }
- return false;
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(ThisExpression)
- */
- public boolean visit(ThisExpression node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- rewriteOptionalQualifier(node, ThisExpression.QUALIFIER_PROPERTY, node.getStartPosition());
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(ThrowStatement)
- */
- public boolean visit(ThrowStatement node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- rewriteRequiredNode(node, ThrowStatement.EXPRESSION_PROPERTY);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(TryStatement)
- */
- public boolean visit(TryStatement node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- int pos= rewriteRequiredNode(node, TryStatement.BODY_PROPERTY);
-
- if (isChanged(node, TryStatement.CATCH_CLAUSES_PROPERTY)) {
- int indent= getIndent(node.getStartPosition());
- String prefix= this.formatter.CATCH_BLOCK.getPrefix(indent);
- pos= rewriteNodeList(node, TryStatement.CATCH_CLAUSES_PROPERTY, pos, prefix, prefix);
- } else {
- pos= doVisit(node, TryStatement.CATCH_CLAUSES_PROPERTY, pos);
- }
- rewriteNode(node, TryStatement.FINALLY_PROPERTY, pos, this.formatter.FINALLY_BLOCK);
- return false;
- }
-
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(TypeDeclarationStatement)
- */
- public boolean visit(TypeDeclarationStatement node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
- if (node.getAST().apiLevel() == JLS2_INTERNAL) {
- rewriteRequiredNode(node, TypeDeclarationStatement.TYPE_DECLARATION_PROPERTY);
- } else {
- rewriteRequiredNode(node, TypeDeclarationStatement.DECLARATION_PROPERTY);
- }
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(TypeLiteral)
- */
- public boolean visit(TypeLiteral node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- rewriteRequiredNode(node, TypeLiteral.TYPE_PROPERTY);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(VariableDeclarationExpression)
- */
- public boolean visit(VariableDeclarationExpression node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- // same code as FieldDeclaration
- int pos= node.getStartPosition();
-// if (node.getAST().apiLevel() == JLS2_INTERNAL) {
-// rewriteModifiers(node, VariableDeclarationExpression.MODIFIERS_PROPERTY, pos);
-// } else {
-// rewriteModifiers2(node, VariableDeclarationExpression.MODIFIERS2_PROPERTY, pos);
-// }
- if (!node.getType().isInferred())
- pos= rewriteRequiredNode(node, VariableDeclarationExpression.TYPE_PROPERTY);
- rewriteNodeList(node, VariableDeclarationExpression.FRAGMENTS_PROPERTY, pos, "", ", "); //$NON-NLS-1$ //$NON-NLS-2$
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(VariableDeclarationFragment)
- */
- public boolean visit(VariableDeclarationFragment node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- int pos= rewriteRequiredNode(node, VariableDeclarationFragment.NAME_PROPERTY);
-
- int extraDims= rewriteExtraDimensions(node, VariableDeclarationFragment.EXTRA_DIMENSIONS_PROPERTY, pos);
-
- if (extraDims > 0) {
- int kind= getChangeKind(node, VariableDeclarationFragment.INITIALIZER_PROPERTY);
- if (kind == RewriteEvent.REMOVED) {
- try {
- pos= getScanner().getPreviousTokenEndOffset(ITerminalSymbols.TokenNameEQUAL, pos);
- } catch (CoreException e) {
- handleException(e);
- }
- } else {
- pos= node.getStartPosition() + node.getLength(); // insert pos
- }
- }
- rewriteNode(node, VariableDeclarationFragment.INITIALIZER_PROPERTY, pos, this.formatter.VAR_INITIALIZER);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(VariableDeclarationStatement)
- */
- public boolean visit(VariableDeclarationStatement node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- // same code as FieldDeclaration
- int pos= node.getStartPosition();
-// if (node.getAST().apiLevel() == JLS2_INTERNAL) {
-// rewriteModifiers(node, VariableDeclarationStatement.MODIFIERS_PROPERTY, pos);
-// } else {
-// rewriteModifiers2(node, VariableDeclarationStatement.MODIFIERS2_PROPERTY, pos);
-// }
- if (!node.getType().isInferred())
- pos= rewriteRequiredNode(node, VariableDeclarationStatement.TYPE_PROPERTY);
-
- rewriteNodeList(node, VariableDeclarationStatement.FRAGMENTS_PROPERTY, pos, "", ", "); //$NON-NLS-1$ //$NON-NLS-2$
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(WhileStatement)
- */
- public boolean visit(WhileStatement node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- int pos= rewriteRequiredNode(node, WhileStatement.EXPRESSION_PROPERTY);
-
- try {
- if (isChanged(node, WhileStatement.BODY_PROPERTY)) {
- int startOffset= getScanner().getTokenEndOffset(ITerminalSymbols.TokenNameRPAREN, pos);
- rewriteBodyNode(node, WhileStatement.BODY_PROPERTY, startOffset, -1, getIndent(node.getStartPosition()), this.formatter.WHILE_BLOCK); // body
- } else {
- voidVisit(node, WhileStatement.BODY_PROPERTY);
- }
- } catch (CoreException e) {
- handleException(e);
- }
- return false;
- }
-
-
- public boolean visit(WithStatement node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- int pos= rewriteRequiredNode(node, WithStatement.EXPRESSION_PROPERTY);
-
- try {
- if (isChanged(node, WithStatement.BODY_PROPERTY)) {
- int startOffset= getScanner().getTokenEndOffset(ITerminalSymbols.TokenNameRPAREN, pos);
- rewriteBodyNode(node, WithStatement.BODY_PROPERTY, startOffset, -1, getIndent(node.getStartPosition()), this.formatter.WHILE_BLOCK); // body
- } else {
- voidVisit(node, WithStatement.BODY_PROPERTY);
- }
- } catch (CoreException e) {
- handleException(e);
- }
- return false;
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.MemberRef)
- */
- public boolean visit(MemberRef node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
- rewriteNode(node, MemberRef.QUALIFIER_PROPERTY, node.getStartPosition(), ASTRewriteFormatter.NONE);
-
- rewriteRequiredNode(node, MemberRef.NAME_PROPERTY);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.FunctionRef)
- */
- public boolean visit(FunctionRef node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
- rewriteNode(node, FunctionRef.QUALIFIER_PROPERTY, node.getStartPosition(), ASTRewriteFormatter.NONE);
-
- int pos= rewriteRequiredNode(node, FunctionRef.NAME_PROPERTY);
-
- if (isChanged(node, FunctionRef.PARAMETERS_PROPERTY)) {
- // eval position after opening parent
- try {
- int startOffset= getScanner().getTokenEndOffset(ITerminalSymbols.TokenNameLPAREN, pos);
- rewriteNodeList(node, FunctionRef.PARAMETERS_PROPERTY, startOffset, "", ", "); //$NON-NLS-1$ //$NON-NLS-2$
- } catch (CoreException e) {
- handleException(e);
- }
- } else {
- voidVisit(node, FunctionRef.PARAMETERS_PROPERTY);
- }
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.FunctionRefParameter)
- */
- public boolean visit(FunctionRefParameter node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
- int pos= rewriteRequiredNode(node, FunctionRefParameter.TYPE_PROPERTY);
- if (node.getAST().apiLevel() >= AST.JLS3) {
- if (isChanged(node, FunctionRefParameter.VARARGS_PROPERTY)) {
- if (getNewValue(node, FunctionRefParameter.VARARGS_PROPERTY).equals(Boolean.TRUE)) {
- doTextInsert(pos, "...", getEditGroup(node, FunctionRefParameter.VARARGS_PROPERTY)); //$NON-NLS-1$
- } else {
- try {
- int ellipsisEnd= getScanner().getNextEndOffset(pos, true);
- doTextRemove(pos, ellipsisEnd - pos, getEditGroup(node, FunctionRefParameter.VARARGS_PROPERTY));
- } catch (CoreException e) {
- handleException(e);
- }
- }
- }
- }
- rewriteNode(node, FunctionRefParameter.NAME_PROPERTY, pos, ASTRewriteFormatter.SPACE);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.TagElement)
- */
- public boolean visit(TagElement node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- int changeKind= getChangeKind(node, TagElement.TAG_NAME_PROPERTY);
- switch (changeKind) {
- case RewriteEvent.INSERTED: {
- String newTagName= (String) getNewValue(node, TagElement.TAG_NAME_PROPERTY);
- doTextInsert(node.getStartPosition(), newTagName, getEditGroup(node, TagElement.TAG_NAME_PROPERTY));
- break;
- }
- case RewriteEvent.REMOVED: {
- doTextRemove(node.getStartPosition(), findTagNameEnd(node) - node.getStartPosition(), getEditGroup(node, TagElement.TAG_NAME_PROPERTY));
- break;
- }
- case RewriteEvent.REPLACED: {
- String newTagName= (String) getNewValue(node, TagElement.TAG_NAME_PROPERTY);
- doTextReplace(node.getStartPosition(), findTagNameEnd(node) - node.getStartPosition(), newTagName, getEditGroup(node, TagElement.TAG_NAME_PROPERTY));
- break;
- }
- }
-
- if (isChanged(node, TagElement.FRAGMENTS_PROPERTY)) {
- // eval position after name
- int endOffset= findTagNameEnd(node);
- rewriteNodeList(node, TagElement.FRAGMENTS_PROPERTY, endOffset, " ", " "); //$NON-NLS-1$//$NON-NLS-2$
- } else {
- voidVisit(node, TagElement.FRAGMENTS_PROPERTY);
- }
- return false;
- }
-
- private int findTagNameEnd(TagElement tagNode) {
- if (tagNode.getTagName() != null) {
- char[] cont= getContent();
- int len= cont.length;
- int i= tagNode.getStartPosition();
- while (i < len && !IndentManipulation.isIndentChar(cont[i])) {
- i++;
- }
- return i;
- }
- return tagNode.getStartPosition();
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.TextElement)
- */
- public boolean visit(TextElement node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
- String newText= (String) getNewValue(node, TextElement.TEXT_PROPERTY);
- TextEditGroup group = getEditGroup(node, TextElement.TEXT_PROPERTY);
- doTextReplace(node.getStartPosition(), node.getLength(), newText, group);
- return false;
- }
-
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.EnhancedForStatement)
- */
- public boolean visit(EnhancedForStatement node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
- rewriteRequiredNode(node, EnhancedForStatement.PARAMETER_PROPERTY);
- int pos= rewriteRequiredNode(node, EnhancedForStatement.EXPRESSION_PROPERTY);
-
- RewriteEvent bodyEvent= getEvent(node, EnhancedForStatement.BODY_PROPERTY);
- if (bodyEvent != null && bodyEvent.getChangeKind() == RewriteEvent.REPLACED) {
- int startOffset;
- try {
- startOffset= getScanner().getTokenEndOffset(ITerminalSymbols.TokenNameRPAREN, pos);
- rewriteBodyNode(node, EnhancedForStatement.BODY_PROPERTY, startOffset, -1, getIndent(node.getStartPosition()), this.formatter.FOR_BLOCK); // body
- } catch (CoreException e) {
- handleException(e);
- }
- } else {
- voidVisit(node, EnhancedForStatement.BODY_PROPERTY);
- }
- return false;
- }
-
-
- public boolean visit(ListExpression node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- int startPos= node.getStartPosition();
- rewriteNodeList(node, ListExpression.EXPRESSIONS_PROPERTY, startPos, "", ", "); //$NON-NLS-1$ //$NON-NLS-2$
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.Modifier)
- */
- public boolean visit(Modifier node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
- String newText= getNewValue(node, Modifier.KEYWORD_PROPERTY).toString(); // type Modifier.ModifierKeyword
- TextEditGroup group = getEditGroup(node, Modifier.KEYWORD_PROPERTY);
- doTextReplace(node.getStartPosition(), node.getLength(), newText, group);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.QualifiedType)
- */
- public boolean visit(QualifiedType node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
- rewriteRequiredNode(node, QualifiedType.QUALIFIER_PROPERTY);
- rewriteRequiredNode(node, QualifiedType.NAME_PROPERTY);
- return false;
- }
- public boolean visit(UndefinedLiteral node) {
- if (!hasChildrenChanges(node)) {
- return doVisitUnchangedChildren(node);
- }
-
- changeNotSupported(node); // no modification possible
- return false;
- }
-
- final void handleException(Throwable e) {
- IllegalArgumentException runtimeException= new IllegalArgumentException("Document does not match the AST"); //$NON-NLS-1$
- runtimeException.initCause(e);
- throw runtimeException;
- }
-}
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
deleted file mode 100644
index 81caabc2..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/ASTRewriteFlattener.java
+++ /dev/null
@@ -1,1277 +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.dom.rewrite;
-
-import java.util.List;
-
-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.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ArrayAccess;
-import org.eclipse.wst.jsdt.core.dom.ArrayCreation;
-import org.eclipse.wst.jsdt.core.dom.ArrayInitializer;
-import org.eclipse.wst.jsdt.core.dom.ArrayType;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.BlockComment;
-import org.eclipse.wst.jsdt.core.dom.BooleanLiteral;
-import org.eclipse.wst.jsdt.core.dom.BreakStatement;
-import org.eclipse.wst.jsdt.core.dom.CatchClause;
-import org.eclipse.wst.jsdt.core.dom.CharacterLiteral;
-import org.eclipse.wst.jsdt.core.dom.ChildPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.ConditionalExpression;
-import org.eclipse.wst.jsdt.core.dom.ConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.ContinueStatement;
-import org.eclipse.wst.jsdt.core.dom.DoStatement;
-import org.eclipse.wst.jsdt.core.dom.EmptyStatement;
-import org.eclipse.wst.jsdt.core.dom.EnhancedForStatement;
-import org.eclipse.wst.jsdt.core.dom.ExpressionStatement;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ForInStatement;
-import org.eclipse.wst.jsdt.core.dom.ForStatement;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionExpression;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.FunctionRef;
-import org.eclipse.wst.jsdt.core.dom.FunctionRefParameter;
-import org.eclipse.wst.jsdt.core.dom.IfStatement;
-import org.eclipse.wst.jsdt.core.dom.ImportDeclaration;
-import org.eclipse.wst.jsdt.core.dom.InfixExpression;
-import org.eclipse.wst.jsdt.core.dom.Initializer;
-import org.eclipse.wst.jsdt.core.dom.InstanceofExpression;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.LabeledStatement;
-import org.eclipse.wst.jsdt.core.dom.LineComment;
-import org.eclipse.wst.jsdt.core.dom.ListExpression;
-import org.eclipse.wst.jsdt.core.dom.MemberRef;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.NullLiteral;
-import org.eclipse.wst.jsdt.core.dom.NumberLiteral;
-import org.eclipse.wst.jsdt.core.dom.ObjectLiteral;
-import org.eclipse.wst.jsdt.core.dom.ObjectLiteralField;
-import org.eclipse.wst.jsdt.core.dom.PackageDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ParenthesizedExpression;
-import org.eclipse.wst.jsdt.core.dom.PostfixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrefixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrimitiveType;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.QualifiedType;
-import org.eclipse.wst.jsdt.core.dom.RegularExpressionLiteral;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SimpleType;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.StringLiteral;
-import org.eclipse.wst.jsdt.core.dom.StructuralPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.SuperFieldAccess;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.SwitchCase;
-import org.eclipse.wst.jsdt.core.dom.SwitchStatement;
-import org.eclipse.wst.jsdt.core.dom.TagElement;
-import org.eclipse.wst.jsdt.core.dom.TextElement;
-import org.eclipse.wst.jsdt.core.dom.ThisExpression;
-import org.eclipse.wst.jsdt.core.dom.ThrowStatement;
-import org.eclipse.wst.jsdt.core.dom.TryStatement;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.TypeLiteral;
-import org.eclipse.wst.jsdt.core.dom.UndefinedLiteral;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.WhileStatement;
-import org.eclipse.wst.jsdt.core.dom.WithStatement;
-import org.eclipse.wst.jsdt.internal.compiler.util.Util;
-
-
-public class ASTRewriteFlattener extends ASTVisitor {
-
- /**
- * Internal synonynm for deprecated constant AST.JSL2
- * to alleviate deprecation warnings.
- * @deprecated
- */
- /*package*/ static final int JLS2_INTERNAL = AST.JLS2;
-
- public static String asString(ASTNode node, RewriteEventStore store) {
- ASTRewriteFlattener flattener= new ASTRewriteFlattener(store);
- node.accept(flattener);
- return flattener.getResult();
- }
-
- protected StringBuffer result;
- private RewriteEventStore store;
-
- public ASTRewriteFlattener(RewriteEventStore store) {
- this.store= store;
- this.result= new StringBuffer();
- }
-
- /**
- * Returns the string accumulated in the visit.
- *
- * @return the serialized
- */
- public String getResult() {
- // convert to a string, but lose any extra space in the string buffer by copying
- return new String(this.result.toString());
- }
-
- /**
- * Resets this printer so that it can be used again.
- */
- public void reset() {
- this.result.setLength(0);
- }
-
- /**
- * Appends the text representation of the given modifier flags, followed by a single space.
- *
- * @param modifiers the modifiers
- * @param buf The <code>StringBuffer</code> to write the result to.
- */
- public static void printModifiers(int modifiers, StringBuffer buf) {
-// if (Modifier.isPublic(modifiers)) {
-// buf.append("public "); //$NON-NLS-1$
-// }
-// if (Modifier.isProtected(modifiers)) {
-// buf.append("protected "); //$NON-NLS-1$
-// }
-// if (Modifier.isPrivate(modifiers)) {
-// buf.append("private "); //$NON-NLS-1$
-// }
-// if (Modifier.isStatic(modifiers)) {
-// buf.append("static "); //$NON-NLS-1$
-// }
-// if (Modifier.isAbstract(modifiers)) {
-// buf.append("abstract "); //$NON-NLS-1$
-// }
-// if (Modifier.isFinal(modifiers)) {
-// buf.append("final "); //$NON-NLS-1$
-// }
-// if (Modifier.isSynchronized(modifiers)) {
-// buf.append("synchronized "); //$NON-NLS-1$
-// }
-// if (Modifier.isVolatile(modifiers)) {
-// buf.append("volatile "); //$NON-NLS-1$
-// }
-// if (Modifier.isNative(modifiers)) {
-// buf.append("native "); //$NON-NLS-1$
-// }
-// if (Modifier.isStrictfp(modifiers)) {
-// buf.append("strictfp "); //$NON-NLS-1$
-// }
-// if (Modifier.isTransient(modifiers)) {
-// buf.append("transient "); //$NON-NLS-1$
-// }
- }
-
- protected List getChildList(ASTNode parent, StructuralPropertyDescriptor childProperty) {
- return (List) getAttribute(parent, childProperty);
- }
-
- protected ASTNode getChildNode(ASTNode parent, StructuralPropertyDescriptor childProperty) {
- return (ASTNode) getAttribute(parent, childProperty);
- }
-
- protected int getIntAttribute(ASTNode parent, StructuralPropertyDescriptor childProperty) {
- return ((Integer) getAttribute(parent, childProperty)).intValue();
- }
-
- protected boolean getBooleanAttribute(ASTNode parent, StructuralPropertyDescriptor childProperty) {
- return ((Boolean) getAttribute(parent, childProperty)).booleanValue();
- }
-
- protected Object getAttribute(ASTNode parent, StructuralPropertyDescriptor childProperty) {
- return this.store.getNewValue(parent, childProperty);
- }
-
- protected void visitList(ASTNode parent, StructuralPropertyDescriptor childProperty, String separator) {
- List list= getChildList(parent, childProperty);
- for (int i= 0; i < list.size(); i++) {
- if (separator != null && i > 0) {
- this.result.append(separator);
- }
- ((ASTNode) list.get(i)).accept(this);
- }
- }
-
- protected void visitList(ASTNode parent, StructuralPropertyDescriptor childProperty, String separator, String lead, String post) {
- List list= getChildList(parent, childProperty);
- if (!list.isEmpty()) {
- this.result.append(lead);
- for (int i= 0; i < list.size(); i++) {
- if (separator != null && i > 0) {
- this.result.append(separator);
- }
- ((ASTNode) list.get(i)).accept(this);
- }
- this.result.append(post);
- }
- }
-
-
- /*
- * @see ASTVisitor#visit(AnonymousClassDeclaration)
- */
- public boolean visit(AnonymousClassDeclaration node) {
- this.result.append('{');
- visitList(node, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY, null);
- this.result.append('}');
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ArrayAccess)
- */
- public boolean visit(ArrayAccess node) {
- getChildNode(node, ArrayAccess.ARRAY_PROPERTY).accept(this);
- this.result.append('[');
- getChildNode(node, ArrayAccess.INDEX_PROPERTY).accept(this);
- this.result.append(']');
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ArrayCreation)
- */
- public boolean visit(ArrayCreation node) {
- this.result.append("new "); //$NON-NLS-1$
- ArrayType arrayType= (ArrayType) getChildNode(node, ArrayCreation.TYPE_PROPERTY);
-
- // get the element type and count dimensions
- Type elementType= (Type) getChildNode(arrayType, ArrayType.COMPONENT_TYPE_PROPERTY);
- int dimensions= 1; // always include this array type
- while (elementType.isArrayType()) {
- dimensions++;
- elementType = (Type) getChildNode(elementType, ArrayType.COMPONENT_TYPE_PROPERTY);
- }
-
- elementType.accept(this);
-
- List list= getChildList(node, ArrayCreation.DIMENSIONS_PROPERTY);
- for (int i= 0; i < list.size(); i++) {
- this.result.append('[');
- ((ASTNode) list.get(i)).accept(this);
- this.result.append(']');
- dimensions--;
- }
-
- // add empty "[]" for each extra array dimension
- for (int i= 0; i < dimensions; i++) {
- this.result.append("[]"); //$NON-NLS-1$
- }
- ASTNode initializer= getChildNode(node, ArrayCreation.INITIALIZER_PROPERTY);
- if (initializer != null) {
- getChildNode(node, ArrayCreation.INITIALIZER_PROPERTY).accept(this);
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ArrayInitializer)
- */
- public boolean visit(ArrayInitializer node) {
- this.result.append('[');
- visitList(node, ArrayInitializer.EXPRESSIONS_PROPERTY, String.valueOf(','));
- this.result.append(']');
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ArrayType)
- */
- public boolean visit(ArrayType node) {
- getChildNode(node, ArrayType.COMPONENT_TYPE_PROPERTY).accept(this);
- this.result.append("[]"); //$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(Assignment)
- */
- public boolean visit(Assignment node) {
- getChildNode(node, Assignment.LEFT_HAND_SIDE_PROPERTY).accept(this);
- this.result.append(getAttribute(node, Assignment.OPERATOR_PROPERTY).toString());
- getChildNode(node, Assignment.RIGHT_HAND_SIDE_PROPERTY).accept(this);
- return false;
- }
-
-
-
- /*
- * @see ASTVisitor#visit(Block)
- */
- public boolean visit(Block node) {
- this.result.append('{');
- visitList(node, Block.STATEMENTS_PROPERTY, null);
- this.result.append('}');
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(BooleanLiteral)
- */
- public boolean visit(BooleanLiteral node) {
- if (node.booleanValue() == true) {
- this.result.append("true"); //$NON-NLS-1$
- } else {
- this.result.append("false"); //$NON-NLS-1$
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(BreakStatement)
- */
- public boolean visit(BreakStatement node) {
- this.result.append("break"); //$NON-NLS-1$
- ASTNode label= getChildNode(node, BreakStatement.LABEL_PROPERTY);
- if (label != null) {
- this.result.append(' ');
- label.accept(this);
- }
- this.result.append(';');
- return false;
- }
-
- public boolean visit(FunctionExpression node) {
- getChildNode(node, FunctionExpression.METHOD_PROPERTY).accept(this);
- return false;
- }
-
- public boolean visit(ObjectLiteralField node) {
- getChildNode(node, ObjectLiteralField.FIELD_NAME_PROPERTY).accept(this);
- this.result.append(" : "); //$NON-NLS-1$
- getChildNode(node, ObjectLiteralField.INITIALIZER_PROPERTY).accept(this);
- return false;
- }
-
- public boolean visit(ObjectLiteral node) {
- this.result.append('{');
- visitList(node, ObjectLiteral.FIELDS_PROPERTY, String.valueOf(','));
- this.result.append('}');
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(CatchClause)
- */
- public boolean visit(CatchClause node) {
- this.result.append("catch ("); //$NON-NLS-1$
- getChildNode(node, CatchClause.EXCEPTION_PROPERTY).accept(this);
- this.result.append(')');
- getChildNode(node, CatchClause.BODY_PROPERTY).accept(this);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(CharacterLiteral)
- */
- public boolean visit(CharacterLiteral node) {
- this.result.append(getAttribute(node, CharacterLiteral.ESCAPED_VALUE_PROPERTY));
- return false;
- }
-
- public boolean visit(RegularExpressionLiteral node) {
- this.result.append(getAttribute(node, RegularExpressionLiteral.REGULAR_EXPRESSION_PROPERTY));
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ClassInstanceCreation)
- */
- public boolean visit(ClassInstanceCreation node) {
- ASTNode expression= getChildNode(node, ClassInstanceCreation.EXPRESSION_PROPERTY);
- if (expression != null) {
- expression.accept(this);
- this.result.append('.');
- }
- this.result.append("new ");//$NON-NLS-1$
-// if (node.getAST().apiLevel() == JLS2_INTERNAL) {
-// getChildNode(node, ClassInstanceCreation.NAME_PROPERTY).accept(this);
-// } else {
-// visitList(node, ClassInstanceCreation.TYPE_ARGUMENTS_PROPERTY, String.valueOf(','), String.valueOf('<'), String.valueOf('>'));
-// getChildNode(node, ClassInstanceCreation.TYPE_PROPERTY).accept(this);
-// }
- getChildNode(node, ClassInstanceCreation.MEMBER_PROPERTY).accept(this);
-
-
- this.result.append('(');
- visitList(node, ClassInstanceCreation.ARGUMENTS_PROPERTY, String.valueOf(','));
- this.result.append(')');
- ASTNode decl= getChildNode(node, ClassInstanceCreation.ANONYMOUS_CLASS_DECLARATION_PROPERTY);
- if (decl != null) {
- decl.accept(this);
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(JavaScriptUnit)
- */
- public boolean visit(JavaScriptUnit node) {
- ASTNode pack= getChildNode(node, JavaScriptUnit.PACKAGE_PROPERTY);
- if (pack != null) {
- pack.accept(this);
- }
- visitList(node, JavaScriptUnit.IMPORTS_PROPERTY, null);
-// visitList(node, JavaScriptUnit.TYPES_PROPERTY, null);
- visitList(node, JavaScriptUnit.STATEMENTS_PROPERTY, null);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ConditionalExpression)
- */
- public boolean visit(ConditionalExpression node) {
- getChildNode(node, ConditionalExpression.EXPRESSION_PROPERTY).accept(this);
- this.result.append('?');
- getChildNode(node, ConditionalExpression.THEN_EXPRESSION_PROPERTY).accept(this);
- this.result.append(':');
- getChildNode(node, ConditionalExpression.ELSE_EXPRESSION_PROPERTY).accept(this);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ConstructorInvocation)
- */
- public boolean visit(ConstructorInvocation node) {
- if (node.getAST().apiLevel() >= AST.JLS3) {
- visitList(node, ConstructorInvocation.TYPE_ARGUMENTS_PROPERTY, String.valueOf(','), String.valueOf('<'), String.valueOf('>'));
- }
- this.result.append("this("); //$NON-NLS-1$
- visitList(node, ConstructorInvocation.ARGUMENTS_PROPERTY, String.valueOf(','));
- this.result.append(");"); //$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ContinueStatement)
- */
- public boolean visit(ContinueStatement node) {
- this.result.append("continue"); //$NON-NLS-1$
- ASTNode label= getChildNode(node, ContinueStatement.LABEL_PROPERTY);
- if (label != null) {
- this.result.append(' ');
- label.accept(this);
- }
- this.result.append(';');
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(DoStatement)
- */
- public boolean visit(DoStatement node) {
- this.result.append("do "); //$NON-NLS-1$
- getChildNode(node, DoStatement.BODY_PROPERTY).accept(this);
- this.result.append(" while ("); //$NON-NLS-1$
- getChildNode(node, DoStatement.EXPRESSION_PROPERTY).accept(this);
- this.result.append(");"); //$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(EmptyStatement)
- */
- public boolean visit(EmptyStatement node) {
- this.result.append(';');
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ExpressionStatement)
- */
- public boolean visit(ExpressionStatement node) {
- getChildNode(node, ExpressionStatement.EXPRESSION_PROPERTY).accept(this);
- if (node.getParent().getNodeType()!=ASTNode.FOR_IN_STATEMENT)
- this.result.append(';');
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(FieldAccess)
- */
- public boolean visit(FieldAccess node) {
- getChildNode(node, FieldAccess.EXPRESSION_PROPERTY).accept(this);
- this.result.append('.');
- getChildNode(node, FieldAccess.NAME_PROPERTY).accept(this);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(FieldDeclaration)
- */
- public boolean visit(FieldDeclaration node) {
- ASTNode javadoc= getChildNode(node, FieldDeclaration.JAVADOC_PROPERTY);
- if (javadoc != null) {
- javadoc.accept(this);
- }
- if (node.getAST().apiLevel() == JLS2_INTERNAL) {
- printModifiers(getIntAttribute(node, FieldDeclaration.MODIFIERS_PROPERTY), this.result);
- } else {
- visitList(node, FieldDeclaration.MODIFIERS2_PROPERTY, String.valueOf(' '), Util.EMPTY_STRING, String.valueOf(' '));
- }
-// getChildNode(node, FieldDeclaration.TYPE_PROPERTY).accept(this);
- this.result.append("var "); //$NON-NLS-1$
- visitList(node, FieldDeclaration.FRAGMENTS_PROPERTY, String.valueOf(','));
- this.result.append(';');
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ForStatement)
- */
- public boolean visit(ForStatement node) {
- this.result.append("for ("); //$NON-NLS-1$
- visitList(node, ForStatement.INITIALIZERS_PROPERTY, String.valueOf(','));
- this.result.append(';');
- ASTNode expression= getChildNode(node, ForStatement.EXPRESSION_PROPERTY);
- if (expression != null) {
- expression.accept(this);
- }
- this.result.append(';');
- visitList(node, ForStatement.UPDATERS_PROPERTY, String.valueOf(','));
- this.result.append(')');
- getChildNode(node, ForStatement.BODY_PROPERTY).accept(this);
- return false;
- }
-
- public boolean visit(ForInStatement node) {
- this.result.append("for ("); //$NON-NLS-1$
- ASTNode expression= getChildNode(node, ForInStatement.ITERATION_VARIABLE_PROPERTY);
- if (expression != null) {
- expression.accept(this);
- }
- this.result.append(" in "); //$NON-NLS-1$
- expression= getChildNode(node, ForInStatement.COLLECTION_PROPERTY);
- if (expression != null) {
- expression.accept(this);
- }
- this.result.append(')');
- getChildNode(node, ForInStatement.BODY_PROPERTY).accept(this);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(IfStatement)
- */
- public boolean visit(IfStatement node) {
- this.result.append("if ("); //$NON-NLS-1$
- getChildNode(node, IfStatement.EXPRESSION_PROPERTY).accept(this);
- this.result.append(')');
- getChildNode(node, IfStatement.THEN_STATEMENT_PROPERTY).accept(this);
- ASTNode elseStatement= getChildNode(node, IfStatement.ELSE_STATEMENT_PROPERTY);
- if (elseStatement != null) {
- this.result.append(" else "); //$NON-NLS-1$
- elseStatement.accept(this);
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ImportDeclaration)
- */
- public boolean visit(ImportDeclaration node) {
- if (node.isFileImport())
- return false;
- this.result.append("import "); //$NON-NLS-1$
- if (node.getAST().apiLevel() >= AST.JLS3) {
- if (getBooleanAttribute(node, ImportDeclaration.STATIC_PROPERTY)) {
- this.result.append("static ");//$NON-NLS-1$
- }
- }
- getChildNode(node, ImportDeclaration.NAME_PROPERTY).accept(this);
- if (getBooleanAttribute(node, ImportDeclaration.ON_DEMAND_PROPERTY)) {
- this.result.append(".*"); //$NON-NLS-1$
- }
- this.result.append(';');
- return false;
- }
-
-
-
- /*
- * @see ASTVisitor#visit(InfixExpression)
- */
- public boolean visit(InfixExpression node) {
- getChildNode(node, InfixExpression.LEFT_OPERAND_PROPERTY).accept(this);
- this.result.append(' ');
- String operator= getAttribute(node, InfixExpression.OPERATOR_PROPERTY).toString();
-
- this.result.append(operator);
- this.result.append(' ');
- getChildNode(node, InfixExpression.RIGHT_OPERAND_PROPERTY).accept(this);
-
- List list= getChildList(node, InfixExpression.EXTENDED_OPERANDS_PROPERTY);
- for (int i= 0; i < list.size(); i++) {
- this.result.append(operator);
- ((ASTNode) list.get(i)).accept(this);
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(InstanceofExpression)
- */
- public boolean visit(InstanceofExpression node) {
- getChildNode(node, InstanceofExpression.LEFT_OPERAND_PROPERTY).accept(this);
- this.result.append(" instanceof "); //$NON-NLS-1$
- getChildNode(node, InstanceofExpression.RIGHT_OPERAND_PROPERTY).accept(this);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(Initializer)
- */
- public boolean visit(Initializer node) {
- ASTNode javadoc= getChildNode(node, Initializer.JAVADOC_PROPERTY);
- if (javadoc != null) {
- javadoc.accept(this);
- }
- if (node.getAST().apiLevel() == JLS2_INTERNAL) {
- printModifiers(getIntAttribute(node, Initializer.MODIFIERS_PROPERTY), this.result);
- } else {
- visitList(node, Initializer.MODIFIERS2_PROPERTY, String.valueOf(' '), Util.EMPTY_STRING, String.valueOf(' '));
- }
- getChildNode(node, Initializer.BODY_PROPERTY).accept(this);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(Javadoc)
- */
- public boolean visit(JSdoc node) {
- this.result.append("/**"); //$NON-NLS-1$
- List list= getChildList(node, JSdoc.TAGS_PROPERTY);
- for (int i= 0; i < list.size(); i++) {
- this.result.append("\n * "); //$NON-NLS-1$
- ((ASTNode) list.get(i)).accept(this);
- }
- this.result.append("\n */"); //$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(LabeledStatement)
- */
- public boolean visit(LabeledStatement node) {
- getChildNode(node, LabeledStatement.LABEL_PROPERTY).accept(this);
- this.result.append(": "); //$NON-NLS-1$
- getChildNode(node, LabeledStatement.BODY_PROPERTY).accept(this);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(FunctionDeclaration)
- */
- public boolean visit(FunctionDeclaration node) {
- ASTNode javadoc= getChildNode(node, FunctionDeclaration.JAVADOC_PROPERTY);
- if (javadoc != null) {
- javadoc.accept(this);
- }
- if (node.getAST().apiLevel() == JLS2_INTERNAL) {
- printModifiers(getIntAttribute(node, FunctionDeclaration.MODIFIERS_PROPERTY), this.result);
- } else {
-// visitList(node, FunctionDeclaration.MODIFIERS2_PROPERTY, String.valueOf(' '), Util.EMPTY_STRING, String.valueOf(' '));
-// visitList(node, FunctionDeclaration.TYPE_PARAMETERS_PROPERTY, String.valueOf(','), String.valueOf('<'), String.valueOf('>'));
- }
-
- this.result.append("function "); //$NON-NLS-1$
-
-// if (!getBooleanAttribute(node, FunctionDeclaration.CONSTRUCTOR_PROPERTY)) {
-// if (node.getAST().apiLevel() == JLS2_INTERNAL) {
-// getChildNode(node, FunctionDeclaration.RETURN_TYPE_PROPERTY).accept(this);
-// } else {
-// ASTNode returnType = getChildNode(node, FunctionDeclaration.RETURN_TYPE2_PROPERTY);
-// if (returnType != null) {
-// returnType.accept(this);
-// } else {
-// // methods really ought to have a return type
-// this.result.append("void");//$NON-NLS-1$
-// }
-// }
-// this.result.append(' ');
-// }
- ASTNode childNode = getChildNode(node, FunctionDeclaration.NAME_PROPERTY);
- if (childNode!=null)
- childNode.accept(this);
- this.result.append('(');
- visitList(node, FunctionDeclaration.PARAMETERS_PROPERTY, String.valueOf(','));
- this.result.append(')');
- int extraDims= getIntAttribute(node, FunctionDeclaration.EXTRA_DIMENSIONS_PROPERTY);
- for (int i = 0; i < extraDims; i++) {
- this.result.append("[]"); //$NON-NLS-1$
- }
- visitList(node, FunctionDeclaration.THROWN_EXCEPTIONS_PROPERTY, String.valueOf(','), " throws ", Util.EMPTY_STRING); //$NON-NLS-1$
- ASTNode body= getChildNode(node, FunctionDeclaration.BODY_PROPERTY);
- if (body == null) {
- this.result.append("{}"); //$NON-NLS-1$
- } else {
- body.accept(this);
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(FunctionInvocation)
- */
- public boolean visit(FunctionInvocation node) {
- ASTNode expression= getChildNode(node, FunctionInvocation.EXPRESSION_PROPERTY);
- ASTNode nameNode = getChildNode(node, FunctionInvocation.NAME_PROPERTY);
- if (expression != null) {
- expression.accept(this);
- if (nameNode!=null)
- this.result.append('.');
- }
- if (node.getAST().apiLevel() >= AST.JLS3) {
- visitList(node, FunctionInvocation.TYPE_ARGUMENTS_PROPERTY, String.valueOf(','), String.valueOf('<'), String.valueOf('>'));
- }
-
- if (nameNode!=null)
- nameNode.accept(this);
- this.result.append('(');
- visitList(node, FunctionInvocation.ARGUMENTS_PROPERTY, String.valueOf(','));
- this.result.append(')');
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(NullLiteral)
- */
- public boolean visit(NullLiteral node) {
- this.result.append("null"); //$NON-NLS-1$
- return false;
- }
-
- public boolean visit(UndefinedLiteral node) {
- this.result.append("undefined"); //$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(NumberLiteral)
- */
- public boolean visit(NumberLiteral node) {
- this.result.append(getAttribute(node, NumberLiteral.TOKEN_PROPERTY).toString());
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(PackageDeclaration)
- */
- public boolean visit(PackageDeclaration node) {
- if (node.getAST().apiLevel() >= AST.JLS3) {
- ASTNode javadoc = getChildNode(node, PackageDeclaration.JAVADOC_PROPERTY);
- if (javadoc != null) {
- javadoc.accept(this);
- }
- }
- this.result.append("package "); //$NON-NLS-1$
- getChildNode(node, PackageDeclaration.NAME_PROPERTY).accept(this);
- this.result.append(';');
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ParenthesizedExpression)
- */
- public boolean visit(ParenthesizedExpression node) {
- this.result.append('(');
- getChildNode(node, ParenthesizedExpression.EXPRESSION_PROPERTY).accept(this);
- this.result.append(')');
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(PostfixExpression)
- */
- public boolean visit(PostfixExpression node) {
- getChildNode(node, PostfixExpression.OPERAND_PROPERTY).accept(this);
- this.result.append(getAttribute(node, PostfixExpression.OPERATOR_PROPERTY).toString());
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(PrefixExpression)
- */
- public boolean visit(PrefixExpression node) {
- this.result.append(getAttribute(node, PrefixExpression.OPERATOR_PROPERTY).toString());
- getChildNode(node, PrefixExpression.OPERAND_PROPERTY).accept(this);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(PrimitiveType)
- */
- public boolean visit(PrimitiveType node) {
- this.result.append(getAttribute(node, PrimitiveType.PRIMITIVE_TYPE_CODE_PROPERTY).toString());
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(QualifiedName)
- */
- public boolean visit(QualifiedName node) {
- getChildNode(node, QualifiedName.QUALIFIER_PROPERTY).accept(this);
- this.result.append('.');
- getChildNode(node, QualifiedName.NAME_PROPERTY).accept(this);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ReturnStatement)
- */
- public boolean visit(ReturnStatement node) {
- this.result.append("return"); //$NON-NLS-1$
- ASTNode expression= getChildNode(node, ReturnStatement.EXPRESSION_PROPERTY);
- if (expression != null) {
- this.result.append(' ');
- expression.accept(this);
- }
- this.result.append(';');
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(SimpleName)
- */
- public boolean visit(SimpleName node) {
- this.result.append(getAttribute(node, SimpleName.IDENTIFIER_PROPERTY));
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(SimpleType)
- */
- public boolean visit(SimpleType node) {
- return true;
- }
-
- /*
- * @see ASTVisitor#visit(SingleVariableDeclaration)
- */
- public boolean visit(SingleVariableDeclaration node) {
- if (node.getAST().apiLevel() == JLS2_INTERNAL) {
- printModifiers(getIntAttribute(node, SingleVariableDeclaration.MODIFIERS_PROPERTY), this.result);
- } else {
- visitList(node, SingleVariableDeclaration.MODIFIERS2_PROPERTY, String.valueOf(' '), Util.EMPTY_STRING, String.valueOf(' '));
- }
-// getChildNode(node, SingleVariableDeclaration.TYPE_PROPERTY).accept(this);
-// if (node.getAST().apiLevel() >= AST.JLS3) {
-// if (getBooleanAttribute(node, SingleVariableDeclaration.VARARGS_PROPERTY)) {
-// this.result.append("...");//$NON-NLS-1$
-// }
-// }
- if (node.getParent()!=null && node.getParent().getNodeType()!=ASTNode.FUNCTION_DECLARATION)
- this.result.append("var "); //$NON-NLS-1$
- getChildNode(node, SingleVariableDeclaration.NAME_PROPERTY).accept(this);
- int extraDimensions= getIntAttribute(node, SingleVariableDeclaration.EXTRA_DIMENSIONS_PROPERTY);
- for (int i = 0; i < extraDimensions; i++) {
- this.result.append("[]"); //$NON-NLS-1$
- }
- ASTNode initializer= getChildNode(node, SingleVariableDeclaration.INITIALIZER_PROPERTY);
- if (initializer != null) {
- this.result.append('=');
- initializer.accept(this);
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(StringLiteral)
- */
- public boolean visit(StringLiteral node) {
- this.result.append(getAttribute(node, StringLiteral.ESCAPED_VALUE_PROPERTY));
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(SuperConstructorInvocation)
- */
- public boolean visit(SuperConstructorInvocation node) {
- ASTNode expression= getChildNode(node, SuperConstructorInvocation.EXPRESSION_PROPERTY);
- if (expression != null) {
- expression.accept(this);
- this.result.append('.');
- }
- if (node.getAST().apiLevel() >= AST.JLS3) {
- visitList(node, SuperConstructorInvocation.TYPE_ARGUMENTS_PROPERTY, String.valueOf(','), String.valueOf('<'), String.valueOf('>'));
- }
- this.result.append("super("); //$NON-NLS-1$
- visitList(node, SuperConstructorInvocation.ARGUMENTS_PROPERTY, String.valueOf(','));
- this.result.append(");"); //$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(SuperFieldAccess)
- */
- public boolean visit(SuperFieldAccess node) {
- ASTNode qualifier= getChildNode(node, SuperFieldAccess.QUALIFIER_PROPERTY);
- if (qualifier != null) {
- qualifier.accept(this);
- this.result.append('.');
- }
- this.result.append("super."); //$NON-NLS-1$
- getChildNode(node, SuperFieldAccess.NAME_PROPERTY).accept(this);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(SuperMethodInvocation)
- */
- public boolean visit(SuperMethodInvocation node) {
- ASTNode qualifier= getChildNode(node, SuperMethodInvocation.QUALIFIER_PROPERTY);
- if (qualifier != null) {
- qualifier.accept(this);
- this.result.append('.');
- }
- this.result.append("super."); //$NON-NLS-1$
- if (node.getAST().apiLevel() >= AST.JLS3) {
- visitList(node, SuperMethodInvocation.TYPE_ARGUMENTS_PROPERTY, String.valueOf(','), String.valueOf('<'), String.valueOf('>'));
- }
- getChildNode(node, SuperMethodInvocation.NAME_PROPERTY).accept(this);
- this.result.append('(');
- visitList(node, SuperMethodInvocation.ARGUMENTS_PROPERTY, String.valueOf(','));
- this.result.append(')');
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(SwitchCase)
- */
- public boolean visit(SwitchCase node) {
- ASTNode expression= getChildNode(node, SwitchCase.EXPRESSION_PROPERTY);
- if (expression == null) {
- this.result.append("default"); //$NON-NLS-1$
- } else {
- this.result.append("case "); //$NON-NLS-1$
- expression.accept(this);
- }
- this.result.append(':');
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(SwitchStatement)
- */
- public boolean visit(SwitchStatement node) {
- this.result.append("switch ("); //$NON-NLS-1$
- getChildNode(node, SwitchStatement.EXPRESSION_PROPERTY).accept(this);
- this.result.append(')');
- this.result.append('{');
- visitList(node, SwitchStatement.STATEMENTS_PROPERTY, null);
- this.result.append('}');
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ThisExpression)
- */
- public boolean visit(ThisExpression node) {
- ASTNode qualifier= getChildNode(node, ThisExpression.QUALIFIER_PROPERTY);
- if (qualifier != null) {
- qualifier.accept(this);
- this.result.append('.');
- }
- this.result.append("this"); //$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ThrowStatement)
- */
- public boolean visit(ThrowStatement node) {
- this.result.append("throw "); //$NON-NLS-1$
- getChildNode(node, ThrowStatement.EXPRESSION_PROPERTY).accept(this);
- this.result.append(';');
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(TryStatement)
- */
- public boolean visit(TryStatement node) {
- this.result.append("try "); //$NON-NLS-1$
- getChildNode(node, TryStatement.BODY_PROPERTY).accept(this);
- this.result.append(' ');
- visitList(node, TryStatement.CATCH_CLAUSES_PROPERTY, null);
- ASTNode finallyClause= getChildNode(node, TryStatement.FINALLY_PROPERTY);
- if (finallyClause != null) {
- this.result.append(" finally "); //$NON-NLS-1$
- finallyClause.accept(this);
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(TypeDeclaration)
- */
- public boolean visit(TypeDeclaration node) {
- int apiLevel= node.getAST().apiLevel();
-
- ASTNode javadoc= getChildNode(node, TypeDeclaration.JAVADOC_PROPERTY);
- if (javadoc != null) {
- javadoc.accept(this);
- }
-
- if (apiLevel == JLS2_INTERNAL) {
- printModifiers(getIntAttribute(node, TypeDeclaration.MODIFIERS_PROPERTY), this.result);
- } else {
- visitList(node, TypeDeclaration.MODIFIERS2_PROPERTY, String.valueOf(' '), Util.EMPTY_STRING, String.valueOf(' '));
- }
-
- this.result.append("class "); //$NON-NLS-1$
- getChildNode(node, TypeDeclaration.NAME_PROPERTY).accept(this);
-
- this.result.append(' ');
-
- ChildPropertyDescriptor superClassProperty= (apiLevel == JLS2_INTERNAL) ? TypeDeclaration.SUPERCLASS_PROPERTY : TypeDeclaration.SUPERCLASS_TYPE_PROPERTY;
- ASTNode superclass= getChildNode(node, superClassProperty);
- if (superclass != null) {
- this.result.append("extends "); //$NON-NLS-1$
- superclass.accept(this);
- this.result.append(' ');
- }
-
- this.result.append('{');
- visitList(node, TypeDeclaration.BODY_DECLARATIONS_PROPERTY, null);
- this.result.append('}');
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(TypeDeclarationStatement)
- */
- public boolean visit(TypeDeclarationStatement node) {
- if (node.getAST().apiLevel() == JLS2_INTERNAL) {
- getChildNode(node, TypeDeclarationStatement.TYPE_DECLARATION_PROPERTY).accept(this);
- } else {
- getChildNode(node, TypeDeclarationStatement.DECLARATION_PROPERTY).accept(this);
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(TypeLiteral)
- */
- public boolean visit(TypeLiteral node) {
- getChildNode(node, TypeLiteral.TYPE_PROPERTY).accept(this);
- this.result.append(".class"); //$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(VariableDeclarationExpression)
- */
- public boolean visit(VariableDeclarationExpression node) {
- if (node.getAST().apiLevel() == JLS2_INTERNAL) {
- printModifiers(getIntAttribute(node, VariableDeclarationExpression.MODIFIERS_PROPERTY), this.result);
- } else {
- visitList(node, VariableDeclarationExpression.MODIFIERS2_PROPERTY, String.valueOf(' '), Util.EMPTY_STRING, String.valueOf(' '));
- }
-// getChildNode(node, VariableDeclarationExpression.TYPE_PROPERTY).accept(this);
- this.result.append("var "); //$NON-NLS-1$
- visitList(node, VariableDeclarationExpression.FRAGMENTS_PROPERTY, String.valueOf(','));
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(VariableDeclarationFragment)
- */
- public boolean visit(VariableDeclarationFragment node) {
- getChildNode(node, VariableDeclarationFragment.NAME_PROPERTY).accept(this);
- int extraDimensions= getIntAttribute(node, VariableDeclarationFragment.EXTRA_DIMENSIONS_PROPERTY);
- for (int i = 0; i < extraDimensions; i++) {
- this.result.append("[]"); //$NON-NLS-1$
- }
- ASTNode initializer= getChildNode(node, VariableDeclarationFragment.INITIALIZER_PROPERTY);
- if (initializer != null) {
- this.result.append('=');
- initializer.accept(this);
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(VariableDeclarationStatement)
- */
- public boolean visit(VariableDeclarationStatement node) {
- if (node.getAST().apiLevel() == JLS2_INTERNAL) {
- printModifiers(getIntAttribute(node, VariableDeclarationStatement.MODIFIERS_PROPERTY), this.result);
- } else {
- visitList(node, VariableDeclarationStatement.MODIFIERS2_PROPERTY, String.valueOf(' '), Util.EMPTY_STRING, String.valueOf(' '));
- }
-// getChildNode(node, VariableDeclarationStatement.TYPE_PROPERTY).accept(this);
- this.result.append("var "); //$NON-NLS-1$
- visitList(node, VariableDeclarationStatement.FRAGMENTS_PROPERTY, String.valueOf(','));
- this.result.append(';');
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(WhileStatement)
- */
- public boolean visit(WhileStatement node) {
- this.result.append("while ("); //$NON-NLS-1$
- getChildNode(node, WhileStatement.EXPRESSION_PROPERTY).accept(this);
- this.result.append(')');
- getChildNode(node, WhileStatement.BODY_PROPERTY).accept(this);
- return false;
- }
-
- public boolean visit(WithStatement node) {
- this.result.append("with ("); //$NON-NLS-1$
- getChildNode(node, WithStatement.EXPRESSION_PROPERTY).accept(this);
- this.result.append(')');
- getChildNode(node, WithStatement.BODY_PROPERTY).accept(this);
- return false;
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.BlockComment)
- */
- public boolean visit(BlockComment node) {
- return false; // cant flatten, needs source
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.LineComment)
- */
- public boolean visit(LineComment node) {
- return false; // cant flatten, needs source
- }
-
- public boolean visit(ListExpression node) {
- visitList(node, ArrayInitializer.EXPRESSIONS_PROPERTY, String.valueOf(','));
- return false;
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.MemberRef)
- */
- public boolean visit(MemberRef node) {
- ASTNode qualifier= getChildNode(node, MemberRef.QUALIFIER_PROPERTY);
- if (qualifier != null) {
- qualifier.accept(this);
- }
- this.result.append('#');
- getChildNode(node, MemberRef.NAME_PROPERTY).accept(this);
- return false;
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.FunctionRef)
- */
- public boolean visit(FunctionRef node) {
- ASTNode qualifier= getChildNode(node, FunctionRef.QUALIFIER_PROPERTY);
- if (qualifier != null) {
- qualifier.accept(this);
- }
- this.result.append('#');
- getChildNode(node, FunctionRef.NAME_PROPERTY).accept(this);
- this.result.append('(');
- visitList(node, FunctionRef.PARAMETERS_PROPERTY, ","); //$NON-NLS-1$
- this.result.append(')');
- return false;
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.FunctionRefParameter)
- */
- public boolean visit(FunctionRefParameter node) {
- getChildNode(node, FunctionRefParameter.TYPE_PROPERTY).accept(this);
- if (node.getAST().apiLevel() >= AST.JLS3) {
- if (getBooleanAttribute(node, FunctionRefParameter.VARARGS_PROPERTY)) {
- this.result.append("..."); //$NON-NLS-1$
- }
- }
- ASTNode name= getChildNode(node, FunctionRefParameter.NAME_PROPERTY);
- if (name != null) {
- this.result.append(' ');
- name.accept(this);
- }
- return false;
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.TagElement)
- */
- public boolean visit(TagElement node) {
- Object tagName= getAttribute(node, TagElement.TAG_NAME_PROPERTY);
- if (tagName != null) {
- this.result.append((String) tagName);
- }
- List list= getChildList(node, TagElement.FRAGMENTS_PROPERTY);
- for (int i= 0; i < list.size(); i++) {
- if (i > 0 || tagName != null) {
- this.result.append(' ');
- }
- ASTNode curr= (ASTNode) list.get(i);
- if (curr instanceof TagElement) {
- this.result.append('{');
- curr.accept(this);
- this.result.append('}');
- } else {
- curr.accept(this);
- }
- }
- return false;
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.TextElement)
- */
- public boolean visit(TextElement node) {
- this.result.append(getAttribute(node, TextElement.TEXT_PROPERTY));
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(EnhancedForStatement)
- * @since 3.0
- */
- public boolean visit(EnhancedForStatement node) {
- this.result.append("for (");//$NON-NLS-1$
- getChildNode(node, EnhancedForStatement.PARAMETER_PROPERTY).accept(this);
- this.result.append(':');
- getChildNode(node, EnhancedForStatement.EXPRESSION_PROPERTY).accept(this);
- this.result.append(')');
- getChildNode(node, EnhancedForStatement.BODY_PROPERTY).accept(this);
- return false;
- }
-
-
- /*
- * @see ASTVisitor#visit(Modifier)
- * @since 3.0
- */
- public boolean visit(Modifier node) {
- this.result.append(getAttribute(node, Modifier.KEYWORD_PROPERTY).toString());
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(QualifiedType)
- * @since 3.0
- */
- public boolean visit(QualifiedType node) {
- getChildNode(node, QualifiedType.QUALIFIER_PROPERTY).accept(this);
- this.result.append('.');
- getChildNode(node, QualifiedType.NAME_PROPERTY).accept(this);
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/ASTRewriteFormatter.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/ASTRewriteFormatter.java
deleted file mode 100644
index c98c6acf..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/ASTRewriteFormatter.java
+++ /dev/null
@@ -1,539 +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.dom.rewrite;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.BadPositionCategoryException;
-import org.eclipse.jface.text.DefaultPositionUpdater;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.Position;
-import org.eclipse.text.edits.DeleteEdit;
-import org.eclipse.text.edits.InsertEdit;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.ToolFactory;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.core.formatter.CodeFormatter;
-import org.eclipse.wst.jsdt.core.formatter.IndentManipulation;
-
-/* package */ final class ASTRewriteFormatter {
-
- public static class NodeMarker extends Position {
- public Object data;
- }
-
- private class ExtendedFlattener extends ASTRewriteFlattener {
-
- private ArrayList positions;
-
- public ExtendedFlattener(RewriteEventStore store) {
- super(store);
- this.positions= new ArrayList();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#preVisit(ASTNode)
- */
- public void preVisit(ASTNode node) {
- Object trackData= getEventStore().getTrackedNodeData(node);
- if (trackData != null) {
- addMarker(trackData, this.result.length(), 0);
- }
- Object placeholderData= getPlaceholders().getPlaceholderData(node);
- if (placeholderData != null) {
- addMarker(placeholderData, this.result.length(), 0);
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#postVisit(ASTNode)
- */
- public void postVisit(ASTNode node) {
- Object placeholderData= getPlaceholders().getPlaceholderData(node);
- if (placeholderData != null) {
- fixupLength(placeholderData, this.result.length());
- }
- Object trackData= getEventStore().getTrackedNodeData(node);
- if (trackData != null) {
- fixupLength(trackData, this.result.length());
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.dom.ASTRewriteFlattener#visit(org.eclipse.wst.jsdt.core.dom.Block)
- */
- public boolean visit(Block node) {
- if (getPlaceholders().isCollapsed(node)) {
- visitList(node, Block.STATEMENTS_PROPERTY, null);
- return false;
- }
- return super.visit(node);
- }
-
- private NodeMarker addMarker(Object annotation, int startOffset, int length) {
- NodeMarker marker= new NodeMarker();
- marker.offset= startOffset;
- marker.length= length;
- marker.data= annotation;
- this.positions.add(marker);
- return marker;
- }
-
- private void fixupLength(Object data, int endOffset) {
- for (int i= this.positions.size()-1; i >= 0 ; i--) {
- NodeMarker marker= (NodeMarker) this.positions.get(i);
- if (marker.data == data) {
- marker.length= endOffset - marker.offset;
- return;
- }
- }
- }
-
- public NodeMarker[] getMarkers() {
- return (NodeMarker[]) this.positions.toArray(new NodeMarker[this.positions.size()]);
- }
- }
-
- private final String lineDelimiter;
- private final int tabWidth;
- private final int indentWidth;
-
- private final NodeInfoStore placeholders;
- private final RewriteEventStore eventStore;
-
- private final Map options;
-
-
- public ASTRewriteFormatter(NodeInfoStore placeholders, RewriteEventStore eventStore, Map options, String lineDelimiter) {
- this.placeholders= placeholders;
- this.eventStore= eventStore;
-
- if (options == null) {
- options= JavaScriptCore.getOptions();
- }
- //options.put(DefaultCodeFormatterConstants.FORMATTER_LINE_SPLIT, String.valueOf(9999));
-
- this.options= options;
- this.lineDelimiter= lineDelimiter;
-
- this.tabWidth= IndentManipulation.getTabWidth(options);
- this.indentWidth= IndentManipulation.getIndentWidth(options);
- }
-
-
-
- public NodeInfoStore getPlaceholders() {
- return this.placeholders;
- }
-
- public RewriteEventStore getEventStore() {
- return this.eventStore;
- }
-
- public int getTabWidth() {
- return this.tabWidth;
- }
-
- public int getIndentWidth() {
- return this.indentWidth;
- }
-
- public String getLineDelimiter() {
- return this.lineDelimiter;
- }
-
- /**
- * Returns the string accumulated in the visit formatted using the default formatter.
- * Updates the existing node's positions.
- *
- * @param node The node to flatten.
- * @param initialIndentationLevel The initial indentation level.
- * @param resultingMarkers Resulting the updated NodeMarkers.
- * @return Returns the serialized and formatted code.
- */
- public String getFormattedResult(ASTNode node, int initialIndentationLevel, Collection resultingMarkers) {
-
- ExtendedFlattener flattener= new ExtendedFlattener(this.eventStore);
- node.accept(flattener);
-
- NodeMarker[] markers= flattener.getMarkers();
- for (int i= 0; i < markers.length; i++) {
- resultingMarkers.add(markers[i]); // add to result
- }
-
- String unformatted= flattener.getResult();
- TextEdit edit= formatNode(node, unformatted, initialIndentationLevel);
- if (edit == null) {
- if (initialIndentationLevel > 0) {
- // at least correct the indent
- String indentString = createIndentString(initialIndentationLevel);
- ReplaceEdit[] edits = IndentManipulation.getChangeIndentEdits(unformatted, 0, this.tabWidth, this.indentWidth, indentString);
- edit= new MultiTextEdit();
- edit.addChild(new InsertEdit(0, indentString));
- edit.addChildren(edits);
- } else {
- return unformatted;
- }
- }
- return evaluateFormatterEdit(unformatted, edit, markers);
- }
-
- public String createIndentString(int indentationUnits) {
- return ToolFactory.createCodeFormatter(this.options).createIndentationString(indentationUnits);
- }
-
- public String getIndentString(String currentLine) {
- return IndentManipulation.extractIndentString(currentLine, this.tabWidth, this.indentWidth);
- }
-
- public String changeIndent(String code, int codeIndentLevel, String newIndent) {
- return IndentManipulation.changeIndent(code, codeIndentLevel, this.tabWidth, this.indentWidth, newIndent, this.lineDelimiter);
- }
-
- public int computeIndentUnits(String line) {
- return IndentManipulation.measureIndentUnits(line, this.tabWidth, this.indentWidth);
- }
-
- /**
- * Evaluates the edit on the given string.
- * @param string The string to format
- * @param edit The edit resulted from the code formatter
- * @param positions Positions to update or <code>null</code>.
- * @return The formatted string
- * @throws IllegalArgumentException If the positions are not inside the string, a
- * IllegalArgumentException is thrown.
- */
- public static String evaluateFormatterEdit(String string, TextEdit edit, Position[] positions) {
- try {
- Document doc= createDocument(string, positions);
- edit.apply(doc, 0);
- if (positions != null) {
- for (int i= 0; i < positions.length; i++) {
- Assert.isTrue(!positions[i].isDeleted, "Position got deleted"); //$NON-NLS-1$
- }
- }
- return doc.get();
- } catch (BadLocationException e) {
- //JavaPlugin.log(e); // bug in the formatter
- Assert.isTrue(false, "Fromatter created edits with wrong positions: " + e.getMessage()); //$NON-NLS-1$
- }
- return null;
- }
-
- public TextEdit formatString(int kind, String string, int offset, int length, int indentationLevel) {
- return ToolFactory.createCodeFormatter(this.options).format(kind, string, offset, length, indentationLevel, this.lineDelimiter);
- }
-
- /**
- * Creates edits that describe how to format the given string. Returns <code>null</code> if the code could not be formatted for the given kind.
- * @param node Node describing the type of the string
- * @param str The unformatted string
- * @param indentationLevel
- * @return Returns the edit representing the result of the formatter
- * @throws IllegalArgumentException If the offset and length are not inside the string, a
- * IllegalArgumentException is thrown.
- */
- private TextEdit formatNode(ASTNode node, String str, int indentationLevel) {
- int code;
- String prefix= ""; //$NON-NLS-1$
- String suffix= ""; //$NON-NLS-1$
- if (node instanceof Statement) {
- code= CodeFormatter.K_STATEMENTS;
- if (node.getNodeType() == ASTNode.SWITCH_CASE) {
- prefix= "switch(1) {"; //$NON-NLS-1$
- suffix= "}"; //$NON-NLS-1$
- code= CodeFormatter.K_STATEMENTS;
- }
- } else if (node instanceof Expression && node.getNodeType() != ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
- code= CodeFormatter.K_EXPRESSION;
- } else if (node instanceof BodyDeclaration) {
- code= CodeFormatter.K_CLASS_BODY_DECLARATIONS;
- } else {
- switch (node.getNodeType()) {
- case ASTNode.ARRAY_TYPE:
- case ASTNode.PRIMITIVE_TYPE:
- case ASTNode.QUALIFIED_TYPE:
- case ASTNode.SIMPLE_TYPE:
- suffix= " x;"; //$NON-NLS-1$
- code= CodeFormatter.K_CLASS_BODY_DECLARATIONS;
- break;
- case ASTNode.JAVASCRIPT_UNIT:
- code= CodeFormatter.K_JAVASCRIPT_UNIT;
- break;
- case ASTNode.VARIABLE_DECLARATION_EXPRESSION:
- case ASTNode.SINGLE_VARIABLE_DECLARATION:
- suffix= ";"; //$NON-NLS-1$
- code= CodeFormatter.K_STATEMENTS;
- break;
- case ASTNode.VARIABLE_DECLARATION_FRAGMENT:
- prefix= "A "; //$NON-NLS-1$
- suffix= ";"; //$NON-NLS-1$
- code= CodeFormatter.K_STATEMENTS;
- break;
- case ASTNode.PACKAGE_DECLARATION:
- case ASTNode.IMPORT_DECLARATION:
- suffix= "\nclass A {}"; //$NON-NLS-1$
- code= CodeFormatter.K_JAVASCRIPT_UNIT;
- break;
- case ASTNode.JSDOC:
- suffix= "\nfunction A() {}"; //$NON-NLS-1$
- code= CodeFormatter.K_JAVASCRIPT_UNIT;
- break;
- case ASTNode.CATCH_CLAUSE:
- prefix= "try {}"; //$NON-NLS-1$
- code= CodeFormatter.K_STATEMENTS;
- break;
- case ASTNode.ANONYMOUS_CLASS_DECLARATION:
- prefix= "new A()"; //$NON-NLS-1$
- suffix= ";"; //$NON-NLS-1$
- code= CodeFormatter.K_STATEMENTS;
- break;
- case ASTNode.MODIFIER:
- suffix= " function x() {}"; //$NON-NLS-1$
- code= CodeFormatter.K_JAVASCRIPT_UNIT;
- break;
- case ASTNode.MEMBER_REF:
- case ASTNode.FUNCTION_REF:
- case ASTNode.FUNCTION_REF_PARAMETER:
- case ASTNode.TAG_ELEMENT:
- case ASTNode.TEXT_ELEMENT:
- // javadoc formatting disabled due to bug 93644
- return null;
-
-// wiat for bug 93644
-// case ASTNode.MEMBER_REF:
-// case ASTNode.FUNCTION_REF:
-// prefix= "/**\n * @see ";
-// suffix= "\n*/";
-// code= CodeFormatter.K_JAVA_DOC;
-// break;
-// case ASTNode.FUNCTION_REF_PARAMETER:
-// prefix= "/**\n * @see A#foo(";
-// suffix= ")\n*/";
-// code= CodeFormatter.K_JAVA_DOC;
-// break;
-// case ASTNode.TAG_ELEMENT:
-// case ASTNode.TEXT_ELEMENT:
-// prefix= "/**\n * ";
-// suffix= "\n*/";
-// code= CodeFormatter.K_JAVA_DOC;
-// break;
- default:
- //Assert.isTrue(false, "Node type not covered: " + node.getClass().getName());
- return null;
- }
- }
-
- String concatStr= prefix + str + suffix;
- TextEdit edit= formatString(code, concatStr, prefix.length(), str.length(), indentationLevel);
-
- if (prefix.length() > 0) {
- edit= shifEdit(edit, prefix.length());
- }
- return edit;
- }
-
- private static TextEdit shifEdit(TextEdit oldEdit, int diff) {
- TextEdit newEdit;
- if (oldEdit instanceof ReplaceEdit) {
- ReplaceEdit edit= (ReplaceEdit) oldEdit;
- newEdit= new ReplaceEdit(edit.getOffset() - diff, edit.getLength(), edit.getText());
- } else if (oldEdit instanceof InsertEdit) {
- InsertEdit edit= (InsertEdit) oldEdit;
- newEdit= new InsertEdit(edit.getOffset() - diff, edit.getText());
- } else if (oldEdit instanceof DeleteEdit) {
- DeleteEdit edit= (DeleteEdit) oldEdit;
- newEdit= new DeleteEdit(edit.getOffset() - diff, edit.getLength());
- } else if (oldEdit instanceof MultiTextEdit) {
- newEdit= new MultiTextEdit();
- } else {
- return null; // not supported
- }
- TextEdit[] children= oldEdit.getChildren();
- for (int i= 0; i < children.length; i++) {
- TextEdit shifted= shifEdit(children[i], diff);
- if (shifted != null) {
- newEdit.addChild(shifted);
- }
- }
- return newEdit;
- }
-
- private static Document createDocument(String string, Position[] positions) throws IllegalArgumentException {
- Document doc= new Document(string);
- try {
- if (positions != null) {
- final String POS_CATEGORY= "myCategory"; //$NON-NLS-1$
-
- doc.addPositionCategory(POS_CATEGORY);
- doc.addPositionUpdater(new DefaultPositionUpdater(POS_CATEGORY) {
- protected boolean notDeleted() {
- int start= this.fOffset;
- int end= start + this.fLength;
- if (start < this.fPosition.offset && (this.fPosition.offset + this.fPosition.length < end)) {
- this.fPosition.offset= end; // deleted positions: set to end of remove
- return false;
- }
- return true;
- }
- });
- for (int i= 0; i < positions.length; i++) {
- try {
- doc.addPosition(POS_CATEGORY, positions[i]);
- } catch (BadLocationException e) {
- throw new IllegalArgumentException("Position outside of string. offset: " + positions[i].offset + ", length: " + positions[i].length + ", string size: " + string.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
- }
- }
- }
- } catch (BadPositionCategoryException cannotHappen) {
- // can not happen: category is correctly set up
- }
- return doc;
- }
-
-
-
- public static interface Prefix {
- String getPrefix(int indent);
- }
-
- public static interface BlockContext {
- String[] getPrefixAndSuffix(int indent, ASTNode node, RewriteEventStore events);
- }
-
- public static class ConstPrefix implements Prefix {
- private String prefix;
-
- public ConstPrefix(String prefix) {
- this.prefix= prefix;
- }
-
- public String getPrefix(int indent) {
- return this.prefix;
- }
- }
-
- private class FormattingPrefix implements Prefix {
- private int kind;
- private String string;
- private int start;
- private int length;
-
- public FormattingPrefix(String string, String sub, int kind) {
- this.start= string.indexOf(sub);
- this.length= sub.length();
- this.string= string;
- this.kind= kind;
- }
-
- public String getPrefix(int indent) {
- Position pos= new Position(this.start, this.length);
- String str= this.string;
- TextEdit res= formatString(this.kind, str, 0, str.length(), indent);
- if (res != null) {
- str= evaluateFormatterEdit(str, res, new Position[] { pos });
- }
- return str.substring(pos.offset + 1, pos.offset + pos.length - 1);
- }
- }
-
- private class BlockFormattingPrefix implements BlockContext {
- private String prefix;
- private int start;
-
- public BlockFormattingPrefix(String prefix, int start) {
- this.start= start;
- this.prefix= prefix;
- }
-
- public String[] getPrefixAndSuffix(int indent, ASTNode node, RewriteEventStore events) {
- String nodeString= ASTRewriteFlattener.asString(node, events);
- String str= this.prefix + nodeString;
- Position pos= new Position(this.start, this.prefix.length() + 1 - this.start);
-
- TextEdit res= formatString(CodeFormatter.K_STATEMENTS, str, 0, str.length(), indent);
- if (res != null) {
- str= evaluateFormatterEdit(str, res, new Position[] { pos });
- }
- return new String[] { str.substring(pos.offset + 1, pos.offset + pos.length - 1), ""}; //$NON-NLS-1$
- }
- }
-
- private class BlockFormattingPrefixSuffix implements BlockContext {
- private String prefix;
- private String suffix;
- private int start;
-
- public BlockFormattingPrefixSuffix(String prefix, String suffix, int start) {
- this.start= start;
- this.suffix= suffix;
- this.prefix= prefix;
- }
-
- public String[] getPrefixAndSuffix(int indent, ASTNode node, RewriteEventStore events) {
- String nodeString= ASTRewriteFlattener.asString(node, events);
- int nodeStart= this.prefix.length();
- int nodeEnd= nodeStart + nodeString.length() - 1;
-
- String str= this.prefix + nodeString + this.suffix;
-
- Position pos1= new Position(this.start, nodeStart + 1 - this.start);
- Position pos2= new Position(nodeEnd, 2);
-
- TextEdit res= formatString(CodeFormatter.K_STATEMENTS, str, 0, str.length(), indent);
- if (res != null) {
- str= evaluateFormatterEdit(str, res, new Position[] { pos1, pos2 });
- }
- return new String[] {
- str.substring(pos1.offset + 1, pos1.offset + pos1.length - 1),
- str.substring(pos2.offset + 1, pos2.offset + pos2.length - 1)
- };
- }
- }
-
- public final static Prefix NONE= new ConstPrefix(""); //$NON-NLS-1$
- public final static Prefix SPACE= new ConstPrefix(" "); //$NON-NLS-1$
- public final static Prefix ASSERT_COMMENT= new ConstPrefix(" : "); //$NON-NLS-1$
-
- public final Prefix VAR_INITIALIZER= new FormattingPrefix("A a={};", "a={" , CodeFormatter.K_STATEMENTS); //$NON-NLS-1$ //$NON-NLS-2$
- public final Prefix METHOD_BODY= new FormattingPrefix("void a() {}", ") {" , CodeFormatter.K_CLASS_BODY_DECLARATIONS); //$NON-NLS-1$ //$NON-NLS-2$
- public final Prefix FINALLY_BLOCK= new FormattingPrefix("try {} finally {}", "} finally {", CodeFormatter.K_STATEMENTS); //$NON-NLS-1$ //$NON-NLS-2$
- public final Prefix CATCH_BLOCK= new FormattingPrefix("try {} catch(Exception e) {}", "} c" , CodeFormatter.K_STATEMENTS); //$NON-NLS-1$ //$NON-NLS-2$
- public final Prefix ANNOT_MEMBER_DEFAULT= new FormattingPrefix("String value() default 1;", ") default 1" , CodeFormatter.K_CLASS_BODY_DECLARATIONS); //$NON-NLS-1$ //$NON-NLS-2$
- public final Prefix ENUM_BODY_START= new FormattingPrefix("enum E { A(){void foo(){}} }", "){v" , CodeFormatter.K_JAVASCRIPT_UNIT); //$NON-NLS-1$ //$NON-NLS-2$
- public final Prefix ENUM_BODY_END= new FormattingPrefix("enum E { A(){void foo(){ }}, B}", "}}," , CodeFormatter.K_JAVASCRIPT_UNIT); //$NON-NLS-1$ //$NON-NLS-2$
- public final Prefix WILDCARD_EXTENDS= new FormattingPrefix("A<? extends B> a;", "? extends B" , CodeFormatter.K_CLASS_BODY_DECLARATIONS); //$NON-NLS-1$ //$NON-NLS-2$
- public final Prefix WILDCARD_SUPER= new FormattingPrefix("A<? super B> a;", "? super B" , CodeFormatter.K_CLASS_BODY_DECLARATIONS); //$NON-NLS-1$ //$NON-NLS-2$
-
- public final Prefix FIRST_ENUM_CONST= new FormattingPrefix("enum E { X;}", "{ X" , CodeFormatter.K_JAVASCRIPT_UNIT); //$NON-NLS-1$ //$NON-NLS-2$
- public final Prefix ANNOTATION_SEPARATION= new FormattingPrefix("@A @B class C {}", "A @" , CodeFormatter.K_JAVASCRIPT_UNIT); //$NON-NLS-1$ //$NON-NLS-2$
-
- public final BlockContext IF_BLOCK_WITH_ELSE= new BlockFormattingPrefixSuffix("if (true)", "else{}", 8); //$NON-NLS-1$ //$NON-NLS-2$
- public final BlockContext IF_BLOCK_NO_ELSE= new BlockFormattingPrefix("if (true)", 8); //$NON-NLS-1$
- public final BlockContext ELSE_AFTER_STATEMENT= new BlockFormattingPrefix("if (true) foo(); else ", 15); //$NON-NLS-1$
- public final BlockContext ELSE_AFTER_BLOCK= new BlockFormattingPrefix("if (true) {} else ", 11); //$NON-NLS-1$
-
- public final BlockContext FOR_BLOCK= new BlockFormattingPrefix("for (;;) ", 7); //$NON-NLS-1$
- public final BlockContext WHILE_BLOCK= new BlockFormattingPrefix("while (true)", 11); //$NON-NLS-1$
- public final BlockContext DO_BLOCK= new BlockFormattingPrefixSuffix("do ", "while (true);", 1); //$NON-NLS-1$ //$NON-NLS-2$
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/ImportRewriteAnalyzer.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/ImportRewriteAnalyzer.java
deleted file mode 100644
index ad894cb8..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/ImportRewriteAnalyzer.java
+++ /dev/null
@@ -1,1062 +0,0 @@
-/*******************************************************************************
- * 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.dom.rewrite;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.text.edits.DeleteEdit;
-import org.eclipse.text.edits.InsertEdit;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.wst.jsdt.core.IBuffer;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.ImportDeclaration;
-import org.eclipse.wst.jsdt.core.dom.PackageDeclaration;
-import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants;
-import org.eclipse.wst.jsdt.core.infer.ImportRewriteSupport;
-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.TypeNameRequestor;
-
-public final class ImportRewriteAnalyzer {
-
- private final IJavaScriptUnit compilationUnit;
- private final ArrayList packageEntries;
-
- private final List importsCreated;
- private final List staticImportsCreated;
-
- private final IRegion replaceRange;
-
- private final int importOnDemandThreshold;
- private final int staticImportOnDemandThreshold;
-
- private boolean filterImplicitImports;
- private boolean findAmbiguousImports;
-
- private int flags= 0;
-
- private static final int F_NEEDS_LEADING_DELIM= 2;
- private static final int F_NEEDS_TRAILING_DELIM= 4;
-
- private static final String JAVA_LANG= "java.lang"; //$NON-NLS-1$
-
- private ImportRewriteSupport importRewriteExtension;
-
- private boolean isRewriteExisting=true;
-
- public ImportRewriteAnalyzer(IJavaScriptUnit cu, JavaScriptUnit root, String[] importOrder, int threshold, int staticThreshold, boolean restoreExistingImports,
- ImportRewriteSupport importRewriteExtension) {
- this.compilationUnit= cu;
- this.importOnDemandThreshold= threshold;
- this.staticImportOnDemandThreshold= staticThreshold;
-
- this.filterImplicitImports= true;
- this.findAmbiguousImports= true; //!restoreExistingImports;
-
- this.packageEntries= new ArrayList(20);
- this.importsCreated= new ArrayList();
- this.staticImportsCreated= new ArrayList();
- this.flags= 0;
- this.importRewriteExtension=importRewriteExtension;
- if (importRewriteExtension!=null)
- isRewriteExisting=importRewriteExtension.isRewriteExisting();
-
- this.replaceRange= evaluateReplaceRange(root);
- if (restoreExistingImports) {
- addExistingImports(root);
- }
-
- PackageEntry[] order= new PackageEntry[importOrder.length];
- for (int i= 0; i < order.length; i++) {
- String curr= importOrder[i];
- if (curr.length() > 0 && curr.charAt(0) == '#') {
- curr= curr.substring(1);
- order[i]= new PackageEntry(curr, curr, true); // static import group
- } else {
- order[i]= new PackageEntry(curr, curr, false); // normal import group
- }
- }
-
- addPreferenceOrderHolders(order);
- }
-
- private int getSpacesBetweenImportGroups() {
- try {
- int num= Integer.parseInt(this.compilationUnit.getJavaScriptProject().getOption(DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_BETWEEN_IMPORT_GROUPS, true));
- if (num >= 0)
- return num;
- } catch (NumberFormatException e) {
- // fall through
- }
- return 1;
- }
-
- private void addPreferenceOrderHolders(PackageEntry[] preferenceOrder) {
- if (this.packageEntries.isEmpty()) {
- // all new: copy the elements
- for (int i= 0; i < preferenceOrder.length; i++) {
- this.packageEntries.add(preferenceOrder[i]);
- }
- } else {
- // match the preference order entries to existing imports
- // entries not found are appended after the last successfully matched entry
-
- PackageEntry[] lastAssigned= new PackageEntry[preferenceOrder.length];
-
- // find an existing package entry that matches most
- for (int k= 0; k < this.packageEntries.size(); k++) {
- PackageEntry entry= (PackageEntry) this.packageEntries.get(k);
- if (!entry.isComment()) {
- String currName= entry.getName();
- int currNameLen= currName.length();
- int bestGroupIndex= -1;
- int bestGroupLen= -1;
- for (int i= 0; i < preferenceOrder.length; i++) {
- boolean currPrevStatic= preferenceOrder[i].isStatic();
- if (currPrevStatic == entry.isStatic()) {
- String currPrefEntry= preferenceOrder[i].getName();
- int currPrefLen= currPrefEntry.length();
- if (currName.startsWith(currPrefEntry) && currPrefLen >= bestGroupLen) {
- if (currPrefLen == currNameLen || currName.charAt(currPrefLen) == '.') {
- if (bestGroupIndex == -1 || currPrefLen > bestGroupLen) {
- bestGroupLen= currPrefLen;
- bestGroupIndex= i;
- }
- }
- }
- }
- }
- if (bestGroupIndex != -1) {
- entry.setGroupID(preferenceOrder[bestGroupIndex].getName());
- lastAssigned[bestGroupIndex]= entry; // remember last entry
- }
- }
- }
- // fill in not-assigned categories, keep partial order
- int currAppendIndex= 0;
- for (int i= 0; i < lastAssigned.length; i++) {
- PackageEntry entry= lastAssigned[i];
- if (entry == null) {
- PackageEntry newEntry= preferenceOrder[i];
- if (currAppendIndex == 0 && !newEntry.isStatic()) {
- currAppendIndex= getIndexAfterStatics();
- }
- this.packageEntries.add(currAppendIndex, newEntry);
- currAppendIndex++;
- } else {
- currAppendIndex= this.packageEntries.indexOf(entry) + 1;
- }
- }
- }
- }
-
- private static String getQualifier(ImportDeclaration decl) {
- String name= decl.getName().getFullyQualifiedName();
- return decl.isOnDemand() ? name : Signature.getQualifier(name);
- }
-
- private static String getFullName(ImportDeclaration decl) {
- String name= decl.getName().getFullyQualifiedName();
- return decl.isOnDemand() ? name + ".*": name; //$NON-NLS-1$
- }
-
- private void addExistingImports(JavaScriptUnit root) {
- List/*ImportDeclaration*/ decls= root.imports();
- if (decls.isEmpty()) {
- return;
- }
- PackageEntry currPackage= null;
-
- ImportDeclaration curr= (ImportDeclaration) decls.get(0);
- int currOffset= curr.getStartPosition();
- int currLength= curr.getLength();
- int currEndLine= root.getLineNumber(currOffset + currLength);
-
- for (int i= 1; i < decls.size(); i++) {
- boolean isStatic= curr.isStatic();
- String name= getFullName(curr);
- String packName= getQualifier(curr);
- if (currPackage == null || currPackage.compareTo(packName, isStatic) != 0) {
- currPackage= new PackageEntry(packName, null, isStatic);
- this.packageEntries.add(currPackage);
- }
-
- ImportDeclaration next= (ImportDeclaration) decls.get(i);
- int nextOffset= next.getStartPosition();
- int nextLength= next.getLength();
- int nextOffsetLine= root.getLineNumber(nextOffset);
-
- // if next import is on a different line, modify the end position to the next line begin offset
- if (currEndLine < nextOffsetLine) {
- currEndLine++;
- nextOffset= root.getPosition(currEndLine, 0);
- }
- currPackage.add(new ImportDeclEntry(name, isStatic, new Region(currOffset, nextOffset - currOffset)));
- currOffset= nextOffset;
- curr= next;
-
- // add a comment entry for spacing between imports
- if (currEndLine < nextOffsetLine) {
- nextOffset= root.getPosition(nextOffsetLine, 0);
-
- currPackage= new PackageEntry(); // create a comment package entry for this
- this.packageEntries.add(currPackage);
- currPackage.add(new ImportDeclEntry(null, false, new Region(currOffset, nextOffset - currOffset)));
-
- currOffset= nextOffset;
- }
- currEndLine= root.getLineNumber(nextOffset + nextLength);
- }
-
- boolean isStatic= curr.isStatic();
- String name= getFullName(curr);
- String packName= getQualifier(curr);
- if (currPackage == null || currPackage.compareTo(packName, isStatic) != 0) {
- currPackage= new PackageEntry(packName, null, isStatic);
- this.packageEntries.add(currPackage);
- }
- int length= this.replaceRange.getOffset() + this.replaceRange.getLength() - curr.getStartPosition();
- currPackage.add(new ImportDeclEntry(name, isStatic, new Region(curr.getStartPosition(), length)));
- }
-
- /**
- * Sets that implicit imports (types in default package, CU- package and
- * 'java.lang') should not be created. Note that this is a heuristic filter and can
- * lead to missing imports, e.g. in cases where a type is forced to be specified
- * due to a name conflict.
- * By default, the filter is enabled.
- * @param filterImplicitImports The filterImplicitImports to set
- */
- public void setFilterImplicitImports(boolean filterImplicitImports) {
- this.filterImplicitImports= filterImplicitImports;
- }
-
- /**
- * When set searches for imports that can not be folded into on-demand
- * imports but must be specified explicitly
- * @param findAmbiguousImports The new value
- */
- public void setFindAmbiguousImports(boolean findAmbiguousImports) {
- this.findAmbiguousImports= findAmbiguousImports;
- }
-
- private static class PackageMatcher {
- private String newName;
- private String bestName;
- private int bestMatchLen;
-
- public PackageMatcher() {
- // initialization in 'initialize'
- }
-
- public void initialize(String newImportName, String bestImportName) {
- this.newName= newImportName;
- this.bestName= bestImportName;
- this.bestMatchLen= getCommonPrefixLength(bestImportName, newImportName);
- }
-
- public boolean isBetterMatch(String currName, boolean preferCurr) {
- boolean isBetter;
- int currMatchLen= getCommonPrefixLength(currName, this.newName);
- int matchDiff= currMatchLen - this.bestMatchLen;
- if (matchDiff == 0) {
- if (currMatchLen == this.newName.length() && currMatchLen == currName.length() && currMatchLen == this.bestName.length()) {
- // duplicate entry and complete match
- isBetter= preferCurr;
- } else {
- isBetter= sameMatchLenTest(currName);
- }
- } else {
- isBetter= (matchDiff > 0); // curr has longer match
- }
- if (isBetter) {
- this.bestName= currName;
- this.bestMatchLen= currMatchLen;
- }
- return isBetter;
- }
-
- private boolean sameMatchLenTest(String currName) {
- int matchLen= this.bestMatchLen;
- // known: bestName and currName differ from newName at position 'matchLen'
- // currName and bestName don't have to differ at position 'matchLen'
-
- // determine the order and return true if currName is closer to newName
- char newChar= getCharAt(this.newName, matchLen);
- char currChar= getCharAt(currName, matchLen);
- char bestChar= getCharAt(this.bestName, matchLen);
-
- if (newChar < currChar) {
- if (bestChar < newChar) { // b < n < c
- return (currChar - newChar) < (newChar - bestChar); // -> (c - n) < (n - b)
- } else { // n < b && n < c
- if (currChar == bestChar) { // longer match between curr and best
- return false; // keep curr and best together, new should be before both
- } else {
- return currChar < bestChar; // -> (c < b)
- }
- }
- } else {
- if (bestChar > newChar) { // c < n < b
- return (newChar - currChar) < (bestChar - newChar); // -> (n - c) < (b - n)
- } else { // n > b && n > c
- if (currChar == bestChar) { // longer match between curr and best
- return true; // keep curr and best together, new should be ahead of both
- } else {
- return currChar > bestChar; // -> (c > b)
- }
- }
- }
- }
- }
-
- /* package */ static int getCommonPrefixLength(String s, String t) {
- int len= Math.min(s.length(), t.length());
- for (int i= 0; i < len; i++) {
- if (s.charAt(i) != t.charAt(i)) {
- return i;
- }
- }
- return len;
- }
-
- /* package */ static char getCharAt(String str, int index) {
- if (str.length() > index) {
- return str.charAt(index);
- }
- return 0;
- }
-
- private PackageEntry findBestMatch(String newName, boolean isStatic) {
- if (this.packageEntries.isEmpty()) {
- return null;
- }
- String groupId= null;
- int longestPrefix= -1;
- // find the matching group
- for (int i= 0; i < this.packageEntries.size(); i++) {
- PackageEntry curr= (PackageEntry) this.packageEntries.get(i);
- if (isStatic == curr.isStatic()) {
- String currGroup= curr.getGroupID();
- if (currGroup != null && newName.startsWith(currGroup)) {
- int prefixLen= currGroup.length();
- if (prefixLen == newName.length()) {
- return curr; // perfect fit, use entry
- }
- if ((newName.charAt(prefixLen) == '.') && prefixLen > longestPrefix) {
- longestPrefix= prefixLen;
- groupId= currGroup;
- }
- }
- }
- }
- PackageEntry bestMatch= null;
- PackageMatcher matcher= new PackageMatcher();
- matcher.initialize(newName, ""); //$NON-NLS-1$
- for (int i= 0; i < this.packageEntries.size(); i++) { // find the best match with the same group
- PackageEntry curr= (PackageEntry) this.packageEntries.get(i);
- if (!curr.isComment() && curr.isStatic() == isStatic) {
- if (groupId == null || groupId.equals(curr.getGroupID())) {
- boolean preferrCurr= (bestMatch == null) || (curr.getNumberOfImports() > bestMatch.getNumberOfImports());
- if (matcher.isBetterMatch(curr.getName(), preferrCurr)) {
- bestMatch= curr;
- }
- }
- }
- }
- return bestMatch;
- }
-
- private static boolean isImplicitImport(String qualifier, IJavaScriptUnit cu) {
-// if (JAVA_LANG.equals(qualifier)) {
-// return true;
-// }
-// String packageName= cu.getParent().getElementName();
-// if (qualifier.equals(packageName)) {
-// return true;
-// }
-// String mainTypeName= JavaScriptCore.removeJavaLikeExtension(cu.getElementName());
-// if (packageName.length() == 0) {
-// return qualifier.equals(mainTypeName);
-// }
-// return qualifier.equals(packageName +'.' + mainTypeName);
- return false;
- }
-
- public void addImport(String fullTypeName, boolean isStatic) {
- String typeContainerName= Signature.getQualifier(fullTypeName);
- ImportDeclEntry decl= new ImportDeclEntry(fullTypeName, isStatic, null);
- sortIn(typeContainerName, decl, isStatic);
- }
-
- public boolean removeImport(String qualifiedName, boolean isStatic) {
- String containerName= Signature.getQualifier(qualifiedName);
-
- int nPackages= this.packageEntries.size();
- for (int i= 0; i < nPackages; i++) {
- PackageEntry entry= (PackageEntry) this.packageEntries.get(i);
- if (entry.compareTo(containerName, isStatic) == 0) {
- if (entry.remove(qualifiedName, isStatic)) {
- return true;
- }
- }
- }
- return false;
- }
-
- private int getIndexAfterStatics() {
- for (int i= 0; i < this.packageEntries.size(); i++) {
- if (!((PackageEntry) this.packageEntries.get(i)).isStatic()) {
- return i;
- }
- }
- return this.packageEntries.size();
- }
-
-
- private void sortIn(String typeContainerName, ImportDeclEntry decl, boolean isStatic) {
- PackageEntry bestMatch= findBestMatch(typeContainerName, isStatic);
- if (bestMatch == null) {
- PackageEntry packEntry= new PackageEntry(typeContainerName, null, isStatic);
- packEntry.add(decl);
- int insertPos= packEntry.isStatic() ? 0 : getIndexAfterStatics();
- this.packageEntries.add(insertPos, packEntry);
- } else {
- int cmp= typeContainerName.compareTo(bestMatch.getName());
- if (cmp == 0) {
- bestMatch.sortIn(decl);
- } else {
- // create a new package entry
- String group= bestMatch.getGroupID();
- if (group != null) {
- if (!typeContainerName.startsWith(group)) {
- group= null;
- }
- }
- PackageEntry packEntry= new PackageEntry(typeContainerName, group, isStatic);
- packEntry.add(decl);
- int index= this.packageEntries.indexOf(bestMatch);
- if (cmp < 0) { // insert ahead of best match
- this.packageEntries.add(index, packEntry);
- } else { // insert after best match
- this.packageEntries.add(index + 1, packEntry);
- }
- }
- }
- }
-
- private IRegion evaluateReplaceRange(JavaScriptUnit root) {
- List imports= root.imports();
- if (!imports.isEmpty()) {
- ImportDeclaration first= (ImportDeclaration) imports.get(0);
- ImportDeclaration last= (ImportDeclaration) imports.get(imports.size() - 1);
-
- int startPos= first.getStartPosition(); // no extended range for first: bug 121428
- int endPos= root.getExtendedStartPosition(last) + root.getExtendedLength(last);
- int endLine= root.getLineNumber(endPos);
- if (endLine > 0) {
- int nextLinePos= root.getPosition(endLine + 1, 0);
- if (nextLinePos >= 0) {
- int firstTypePos= getFirstTypeBeginPos(root);
- if (firstTypePos != -1 && firstTypePos < nextLinePos) {
- endPos= firstTypePos;
- } else {
- endPos= nextLinePos;
- }
- }
- }
- return new Region(startPos, endPos - startPos);
- } else {
-
- int start= -1;
- if (this.importRewriteExtension!=null)
- {
- start=this.importRewriteExtension.getImportStartPosition(root);
- }
- if (start==-1)
- start=getPackageStatementEndPos(root);
- else
- this.flags |= F_NEEDS_TRAILING_DELIM;
- return new Region(start, 0);
- }
- }
-
- public MultiTextEdit getResultingEdits(IProgressMonitor monitor) throws JavaScriptModelException {
- if (monitor == null) {
- monitor= new NullProgressMonitor();
- }
- try {
- int importsStart= this.replaceRange.getOffset();
- int importsLen= this.replaceRange.getLength();
-
- String lineDelim= this.compilationUnit.findRecommendedLineSeparator();
- IBuffer buffer= this.compilationUnit.getBuffer();
-
- int currPos= importsStart;
- MultiTextEdit resEdit= new MultiTextEdit();
-
- if ((this.flags & F_NEEDS_LEADING_DELIM) != 0) {
- // new import container
- resEdit.addChild(new InsertEdit(currPos, lineDelim));
- }
-
- PackageEntry lastPackage= null;
-
- Set onDemandConflicts= null;
- if (this.findAmbiguousImports) {
- onDemandConflicts= evaluateStarImportConflicts(monitor);
- }
-
- int spacesBetweenGroups= getSpacesBetweenImportGroups();
-
- ArrayList stringsToInsert= new ArrayList();
-
- int nPackageEntries= this.packageEntries.size();
- for (int i= 0; i < nPackageEntries; i++) {
- PackageEntry pack= (PackageEntry) this.packageEntries.get(i);
- int nImports= pack.getNumberOfImports();
-
- if (this.filterImplicitImports && !pack.isStatic() && isImplicitImport(pack.getName(), this.compilationUnit)) {
- pack.removeAllNew(onDemandConflicts);
- nImports= pack.getNumberOfImports();
- }
- if (nImports == 0) {
- continue;
- }
-
-
- if (spacesBetweenGroups > 0) {
- // add a space between two different groups by looking at the two adjacent imports
- if (lastPackage != null && !pack.isComment() && !pack.isSameGroup(lastPackage)) {
- ImportDeclEntry last= lastPackage.getImportAt(lastPackage.getNumberOfImports() - 1);
- ImportDeclEntry first= pack.getImportAt(0);
- if (!lastPackage.isComment() && (last.isNew() || first.isNew())) {
- for (int k= spacesBetweenGroups; k > 0; k--) {
- stringsToInsert.add(lineDelim);
- }
- }
- }
- }
- lastPackage= pack;
-
- boolean isStatic= pack.isStatic();
- int threshold= isStatic ? staticImportOnDemandThreshold : importOnDemandThreshold;
-
- boolean doStarImport= pack.hasStarImport(threshold, onDemandConflicts);
- if (doStarImport && (pack.find("*") == null)) { //$NON-NLS-1$
- String starImportString= pack.getName() + ".*"; //$NON-NLS-1$
- String str= getNewImportString(starImportString, isStatic, lineDelim);
- stringsToInsert.add(str);
- }
-
- for (int k= 0; k < nImports; k++) {
- ImportDeclEntry currDecl= pack.getImportAt(k);
- IRegion region= currDecl.getSourceRange();
-
- if (region == null) { // new entry
- if (!doStarImport || currDecl.isOnDemand() || (onDemandConflicts != null && onDemandConflicts.contains(currDecl.getSimpleName()))) {
- String str= getNewImportString(currDecl.getElementName(), isStatic, lineDelim);
- stringsToInsert.add(str);
- }
- } else {
- if (!doStarImport || currDecl.isOnDemand() || onDemandConflicts == null || onDemandConflicts.contains(currDecl.getSimpleName())) {
- int offset= region.getOffset();
- removeAndInsertNew(buffer, currPos, offset, stringsToInsert, resEdit);
- stringsToInsert.clear();
- currPos= offset + region.getLength();
- }
- }
- }
- }
-
- int end= importsStart + importsLen;
- removeAndInsertNew(buffer, currPos, end, stringsToInsert, resEdit);
-
- if (importsLen == 0) {
- if (!this.importsCreated.isEmpty() || !this.staticImportsCreated.isEmpty()) { // new import container
- if ((this.flags & F_NEEDS_TRAILING_DELIM) != 0) {
- resEdit.addChild(new InsertEdit(currPos, lineDelim));
- }
- } else {
- return new MultiTextEdit(); // no changes
- }
- }
- return resEdit;
- } finally {
- monitor.done();
- }
- }
-
- private void removeAndInsertNew(IBuffer buffer, int contentOffset, int contentEnd, ArrayList stringsToInsert, MultiTextEdit resEdit) {
- int pos= contentOffset;
- for (int i= 0; i < stringsToInsert.size(); i++) {
- String curr= (String) stringsToInsert.get(i);
- int idx= findInBuffer(buffer, curr, pos, contentEnd);
- if (idx != -1) {
- if (idx != pos) {
- resEdit.addChild(new DeleteEdit(pos, idx - pos));
- }
- pos= idx + curr.length();
- } else {
- resEdit.addChild(new InsertEdit(pos, curr));
- }
- }
- if (pos < contentEnd) {
- resEdit.addChild(new DeleteEdit(pos, contentEnd - pos));
- }
- }
-
- private int findInBuffer(IBuffer buffer, String str, int start, int end) {
- int pos= start;
- int len= str.length();
- if (pos + len > end || str.length() == 0) {
- return -1;
- }
- char first= str.charAt(0);
- int step= str.indexOf(first, 1);
- if (step == -1) {
- step= len;
- }
- while (pos + len <= end) {
- if (buffer.getChar(pos) == first) {
- int k= 1;
- while (k < len && buffer.getChar(pos + k) == str.charAt(k)) {
- k++;
- }
- if (k == len) {
- return pos; // found
- }
- if (k < step) {
- pos+= k;
- } else {
- pos+= step;
- }
- } else {
- pos++;
- }
- }
- return -1;
- }
-
- private Set evaluateStarImportConflicts(IProgressMonitor monitor) throws JavaScriptModelException {
- //long start= System.currentTimeMillis();
-
- final HashSet/*String*/ onDemandConflicts= new HashSet();
-
- IJavaScriptSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaScriptElement[] { this.compilationUnit.getJavaScriptProject() });
-
- ArrayList/*<char[][]>*/ starImportPackages= new ArrayList();
- ArrayList/*<char[][]>*/ simpleTypeNames= new ArrayList();
- int nPackageEntries= this.packageEntries.size();
- for (int i= 0; i < nPackageEntries; i++) {
- PackageEntry pack= (PackageEntry) this.packageEntries.get(i);
- if (!pack.isStatic() && pack.hasStarImport(importOnDemandThreshold, null)) {
- starImportPackages.add(pack.getName().toCharArray());
- for (int k= 0; k < pack.getNumberOfImports(); k++) {
- ImportDeclEntry curr= pack.getImportAt(k);
- if (!curr.isOnDemand() && !curr.isComment()) {
- simpleTypeNames.add(curr.getSimpleName().toCharArray());
- }
- }
- }
- }
- if (starImportPackages.isEmpty()) {
- return null;
- }
-
- starImportPackages.add(this.compilationUnit.getParent().getElementName().toCharArray());
- starImportPackages.add(JAVA_LANG.toCharArray());
-
- char[][] allPackages= (char[][]) starImportPackages.toArray(new char[starImportPackages.size()][]);
- char[][] allTypes= (char[][]) simpleTypeNames.toArray(new char[simpleTypeNames.size()][]);
-
- TypeNameRequestor requestor= new TypeNameRequestor() {
- HashMap foundTypes= new HashMap();
-
- private String getTypeContainerName(char[] packageName, char[][] enclosingTypeNames) {
- StringBuffer buf= new StringBuffer();
- buf.append(packageName);
- for (int i= 0; i < enclosingTypeNames.length; i++) {
- if (buf.length() > 0)
- buf.append('.');
- buf.append(enclosingTypeNames[i]);
- }
- return buf.toString();
- }
-
- public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path) {
- String name= new String(simpleTypeName);
- String containerName= getTypeContainerName(packageName, enclosingTypeNames);
-
- String oldContainer= (String) this.foundTypes.put(name, containerName);
- if (oldContainer != null && !oldContainer.equals(containerName)) {
- onDemandConflicts.add(name);
- }
- }
- };
- new SearchEngine().searchAllTypeNames(allPackages, allTypes, scope, requestor, IJavaScriptSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, monitor);
- return onDemandConflicts;
- }
-
- private String getNewImportString(String importName, boolean isStatic, String lineDelim) {
- String newImportString=null;
- if (this.importRewriteExtension!=null)
- newImportString=this.importRewriteExtension.getImportString(importName, isStatic, lineDelim);
-
- if (newImportString==null) {
- StringBuffer buf = new StringBuffer();
- buf.append("import "); //$NON-NLS-1$
- if (isStatic) {
- buf.append("static "); //$NON-NLS-1$
- }
- buf.append(importName);
- buf.append(';');
- buf.append(lineDelim);
- newImportString=buf.toString();
- }
- if (isStatic) {
- this.staticImportsCreated.add(importName);
- } else {
- this.importsCreated.add(importName);
- }
- return newImportString;
- }
-
- private static int getFirstTypeBeginPos(JavaScriptUnit root) {
- List types= root.types();
- if (!types.isEmpty()) {
- return root.getExtendedStartPosition(((ASTNode) types.get(0)));
- }
- return -1;
- }
-
- private int getPackageStatementEndPos(JavaScriptUnit root) {
- PackageDeclaration packDecl= root.getPackage();
- if (packDecl != null) {
- int lineAfterPackage= root.getLineNumber(packDecl.getStartPosition() + packDecl.getLength()) + 1;
- int afterPackageStatementPos= root.getPosition(lineAfterPackage, 0);
- if (afterPackageStatementPos >= 0) {
- int firstTypePos= getFirstTypeBeginPos(root);
- if (firstTypePos != -1 && firstTypePos <= afterPackageStatementPos) {
- if (firstTypePos <= afterPackageStatementPos) {
- this.flags |= F_NEEDS_TRAILING_DELIM;
- if (firstTypePos == afterPackageStatementPos) {
- this.flags |= F_NEEDS_LEADING_DELIM;
- }
- return firstTypePos;
- }
- }
- this.flags |= F_NEEDS_LEADING_DELIM;
- return afterPackageStatementPos; // insert a line after after package statement
- }
- }
- this.flags |= F_NEEDS_TRAILING_DELIM;
- return 0;
- }
-
- public String toString() {
- int nPackages= this.packageEntries.size();
- StringBuffer buf= new StringBuffer("\n-----------------------\n"); //$NON-NLS-1$
- for (int i= 0; i < nPackages; i++) {
- PackageEntry entry= (PackageEntry) this.packageEntries.get(i);
- if (entry.isStatic()) {
- buf.append("static "); //$NON-NLS-1$
- }
- buf.append(entry.toString());
- }
- return buf.toString();
- }
-
- private static final class ImportDeclEntry {
-
- private String elementName;
- private IRegion sourceRange;
- private final boolean isStatic;
-
- public ImportDeclEntry(String elementName, boolean isStatic, IRegion sourceRange) {
- this.elementName= elementName;
- this.sourceRange= sourceRange;
- this.isStatic= isStatic;
- }
-
- public String getElementName() {
- return this.elementName;
- }
-
- public int compareTo(String fullName, boolean isStaticImport) {
- int cmp= this.elementName.compareTo(fullName);
- if (cmp == 0) {
- if (this.isStatic == isStaticImport) {
- return 0;
- }
- return this.isStatic ? -1 : 1;
- }
- return cmp;
- }
-
- public String getSimpleName() {
- return Signature.getSimpleName(this.elementName);
- }
-
- public boolean isOnDemand() {
- return this.elementName != null && this.elementName.endsWith(".*"); //$NON-NLS-1$
- }
-
- public boolean isStatic() {
- return this.isStatic;
- }
-
- public boolean isNew() {
- return this.sourceRange == null;
- }
-
- public boolean isComment() {
- return this.elementName == null;
- }
-
- public IRegion getSourceRange() {
- return this.sourceRange;
- }
-
- }
-
- /*
- * Internal element for the import structure: A container for imports
- * of all types from the same package
- */
- private final static class PackageEntry {
-
- public static PackageEntry createOnPlaceholderEntry(String preferenceOrder) {
- if (preferenceOrder.length() > 0 && preferenceOrder.charAt(0) == '#') {
- String curr= preferenceOrder.substring(1);
- return new PackageEntry(curr, curr, true);
- }
- return new PackageEntry(preferenceOrder, preferenceOrder, false);
- }
-
- private String name;
- private ArrayList importEntries;
- private String group;
- private boolean isStatic;
-
- /**
- * Comment package entry
- */
- public PackageEntry() {
- this("!", null, false); //$NON-NLS-1$
- }
-
- /**
- * @param name Name of the package entry. e.g. org.eclipse.wst.jsdt.ui, containing imports like
- * org.eclipse.wst.jsdt.ui.JavaUI.
- * @param group The index of the preference order entry assigned
- * different group id's will result in spacers between the entries
- */
- public PackageEntry(String name, String group, boolean isStatic) {
- this.name= name;
- this.importEntries= new ArrayList(5);
- this.group= group;
- this.isStatic= isStatic;
- }
-
- public boolean isStatic() {
- return this.isStatic;
- }
-
- public int compareTo(String otherName, boolean isOtherStatic) {
- int cmp= this.name.compareTo(otherName);
- if (cmp == 0) {
- if (this.isStatic == isOtherStatic) {
- return 0;
- }
- return this.isStatic ? -1 : 1;
- }
- return cmp;
- }
-
- public void sortIn(ImportDeclEntry imp) {
- String fullImportName= imp.getElementName();
- int insertPosition= -1;
- int nInports= this.importEntries.size();
- for (int i= 0; i < nInports; i++) {
- ImportDeclEntry curr= getImportAt(i);
- if (!curr.isComment()) {
- int cmp= curr.compareTo(fullImportName, imp.isStatic());
- if (cmp == 0) {
- return; // exists already
- } else if (cmp > 0 && insertPosition == -1) {
- insertPosition= i;
- }
- }
- }
- if (insertPosition == -1 ) {
- this.importEntries.add(imp);
- } else {
- this.importEntries.add(insertPosition, imp);
- }
- }
-
-
- public void add(ImportDeclEntry imp) {
- this.importEntries.add(imp);
- }
-
- public ImportDeclEntry find(String simpleName) {
- int nInports= this.importEntries.size();
- for (int i= 0; i < nInports; i++) {
- ImportDeclEntry curr= getImportAt(i);
- if (!curr.isComment()) {
- String currName= curr.getElementName();
- if (currName.endsWith(simpleName)) {
- int dotPos= currName.length() - simpleName.length() - 1;
- if ((dotPos == -1) || (dotPos > 0 && currName.charAt(dotPos) == '.')) {
- return curr;
- }
- }
- }
- }
- return null;
- }
-
- public boolean remove(String fullName, boolean isStaticImport) {
- int nInports= this.importEntries.size();
- for (int i= 0; i < nInports; i++) {
- ImportDeclEntry curr= getImportAt(i);
- if (!curr.isComment() && curr.compareTo(fullName, isStaticImport) == 0) {
- this.importEntries.remove(i);
- return true;
- }
- }
- return false;
- }
-
- public void removeAllNew(Set onDemandConflicts) {
- int nInports= this.importEntries.size();
- for (int i= nInports - 1; i >= 0; i--) {
- ImportDeclEntry curr= getImportAt(i);
- if (curr.isNew() /*&& (onDemandConflicts == null || onDemandConflicts.contains(curr.getSimpleName()))*/) {
- this.importEntries.remove(i);
- }
- }
- }
-
- public ImportDeclEntry getImportAt(int index) {
- return (ImportDeclEntry) this.importEntries.get(index);
- }
-
- public boolean hasStarImport(int threshold, Set explicitImports) {
- if (isComment() || isDefaultPackage()) { // can not star import default package
- return false;
- }
- int nImports= getNumberOfImports();
- int count= 0;
- boolean containsNew= false;
- for (int i= 0; i < nImports; i++) {
- ImportDeclEntry curr= getImportAt(i);
- if (curr.isOnDemand()) {
- return true;
- }
- if (!curr.isComment()) {
- count++;
- boolean isExplicit= !curr.isStatic() && (explicitImports != null) && explicitImports.contains(curr.getSimpleName());
- containsNew |= curr.isNew() && !isExplicit;
- }
- }
- return (count >= threshold) && containsNew;
- }
-
- public int getNumberOfImports() {
- return this.importEntries.size();
- }
-
- public String getName() {
- return this.name;
- }
-
- public String getGroupID() {
- return this.group;
- }
-
- public void setGroupID(String groupID) {
- this.group= groupID;
- }
-
- public boolean isSameGroup(PackageEntry other) {
- if (this.group == null) {
- return other.getGroupID() == null;
- } else {
- return this.group.equals(other.getGroupID()) && (this.isStatic == other.isStatic());
- }
- }
-
- public ImportDeclEntry getLast() {
- int nImports= getNumberOfImports();
- if (nImports > 0) {
- return getImportAt(nImports - 1);
- }
- return null;
- }
-
- public boolean isComment() {
- return "!".equals(this.name); //$NON-NLS-1$
- }
-
- public boolean isDefaultPackage() {
- return this.name.length() == 0;
- }
-
- public String toString() {
- StringBuffer buf= new StringBuffer();
- if (isComment()) {
- buf.append("comment\n"); //$NON-NLS-1$
- } else {
- buf.append(this.name); buf.append(", groupId: "); buf.append(this.group); buf.append("\n"); //$NON-NLS-1$ //$NON-NLS-2$
- int nImports= getNumberOfImports();
- for (int i= 0; i < nImports; i++) {
- ImportDeclEntry curr= getImportAt(i);
- buf.append(" "); //$NON-NLS-1$
- if (curr.isStatic()) {
- buf.append("static "); //$NON-NLS-1$
- }
- buf.append(curr.getSimpleName());
- if (curr.isNew()) {
- buf.append(" (new)"); //$NON-NLS-1$
- }
- buf.append("\n"); //$NON-NLS-1$
- }
- }
- return buf.toString();
- }
- }
-
- public String[] getCreatedImports() {
- return (String[]) this.importsCreated.toArray(new String[this.importsCreated.size()]);
- }
-
- public String[] getCreatedStaticImports() {
- return (String[]) this.staticImportsCreated.toArray(new String[this.staticImportsCreated.size()]);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/LineCommentEndOffsets.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/LineCommentEndOffsets.java
deleted file mode 100644
index c833744a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/LineCommentEndOffsets.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.core.dom.rewrite;
-
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.wst.jsdt.core.dom.LineComment;
-import org.eclipse.wst.jsdt.core.formatter.IndentManipulation;
-import org.eclipse.wst.jsdt.internal.compiler.util.Util;
-
-public class LineCommentEndOffsets {
-
- private int[] offsets;
- private final List commentList;
-
- public LineCommentEndOffsets(List commentList) {
- this.commentList= commentList;
- this.offsets= null; // create on demand
- }
-
- private int[] getOffsets() {
- if (this.offsets == null) {
- if (this.commentList != null) {
- int nComments= this.commentList.size();
- // count the number of line comments
- int count= 0;
- for (int i= 0; i < nComments; i++) {
- Object curr= this.commentList.get(i);
- if (curr instanceof LineComment) {
- count++;
- }
- }
- // fill the offset table
- this.offsets= new int[count];
- for (int i= 0, k= 0; i < nComments; i++) {
- Object curr= this.commentList.get(i);
- if (curr instanceof LineComment) {
- LineComment comment= (LineComment) curr;
- this.offsets[k++]= comment.getStartPosition() + comment.getLength();
- }
- }
- } else {
- this.offsets= Util.EMPTY_INT_ARRAY;
- }
- }
- return this.offsets;
- }
-
- public boolean isEndOfLineComment(int offset) {
- return offset >= 0 && Arrays.binarySearch(getOffsets(), offset) >= 0;
- }
-
- public boolean isEndOfLineComment(int offset, char[] content) {
- if (offset < 0 || (offset < content.length && !IndentManipulation.isLineDelimiterChar(content[offset]))) {
- return false;
- }
- return Arrays.binarySearch(getOffsets(), offset) >= 0;
- }
-
- public boolean remove(int offset) {
- int[] offsetArray= getOffsets(); // returns the shared array
- int index= Arrays.binarySearch(offsetArray, offset);
- if (index >= 0) {
- if (index > 0) {
- // shift from the beginning and insert -1 (smallest number) at the beginning
- // 1, 2, 3, x, 4, 5 -> -1, 1, 2, 3, 4, 5
- System.arraycopy(offsetArray, 0, offsetArray, 1, index);
- }
- offsetArray[0]= -1;
- return true;
- }
- return false;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/LineInformation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/LineInformation.java
deleted file mode 100644
index fc9b2c5a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/LineInformation.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*******************************************************************************
- * 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.dom.rewrite;
-
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-
-/**
- *
- */
-public abstract class LineInformation {
-
- public static LineInformation create(final IDocument doc) {
- return new LineInformation() {
- public int getLineOfOffset(int offset) {
- try {
- return doc.getLineOfOffset(offset);
- } catch (BadLocationException e) {
- return -1;
- }
- }
-
- public int getLineOffset(int line) {
- try {
- return doc.getLineOffset(line);
- } catch (BadLocationException e) {
- return -1;
- }
- }
- };
- }
-
- public static LineInformation create(final JavaScriptUnit astRoot) {
- return new LineInformation() {
- public int getLineOfOffset(int offset) {
- return astRoot.getLineNumber(offset) - 1;
- }
- public int getLineOffset(int line) {
- return astRoot.getPosition(line + 1, 0);
- }
- };
- }
-
-
-
- public abstract int getLineOfOffset(int offset);
- public abstract int getLineOffset(int line);
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/ListRewriteEvent.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/ListRewriteEvent.java
deleted file mode 100644
index 93de1492..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/ListRewriteEvent.java
+++ /dev/null
@@ -1,211 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.dom.rewrite;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-
-/**
- *
- */
-public class ListRewriteEvent extends RewriteEvent {
-
- public final static int NEW= 1;
- public final static int OLD= 2;
- public final static int BOTH= NEW | OLD;
-
- /** original list of 'ASTNode' */
- private List originalNodes;
-
- /** list of type 'RewriteEvent' */
- private List listEntries;
-
- /**
- * Creates a ListRewriteEvent from the original ASTNodes. The resulting event
- * represents the unmodified list.
- * @param originalNodes The original nodes (type ASTNode)
- */
- public ListRewriteEvent(List originalNodes) {
- this.originalNodes= new ArrayList(originalNodes);
- }
-
- /**
- * Creates a ListRewriteEvent from existing rewrite events.
- * @param children The rewrite events for this list.
- */
- public ListRewriteEvent(RewriteEvent[] children) {
- this.listEntries= new ArrayList(children.length * 2);
- this.originalNodes= new ArrayList(children.length * 2);
- for (int i= 0; i < children.length; i++) {
- RewriteEvent curr= children[i];
- this.listEntries.add(curr);
- if (curr.getOriginalValue() != null) {
- this.originalNodes.add(curr.getOriginalValue());
- }
- }
- }
-
- private List getEntries() {
- if (this.listEntries == null) {
- // create if not yet existing
- int nNodes= this.originalNodes.size();
- this.listEntries= new ArrayList(nNodes * 2);
- for (int i= 0; i < nNodes; i++) {
- ASTNode node= (ASTNode) this.originalNodes.get(i);
- // all nodes unchanged
- this.listEntries.add(new NodeRewriteEvent(node, node));
- }
- }
- return this.listEntries;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.dom.ASTRewriteChange#getChangeKind()
- */
- public int getChangeKind() {
- if (this.listEntries != null) {
- for (int i= 0; i < this.listEntries.size(); i++) {
- RewriteEvent curr= (RewriteEvent) this.listEntries.get(i);
- if (curr.getChangeKind() != UNCHANGED) {
- return CHILDREN_CHANGED;
- }
- }
- }
- return UNCHANGED;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.dom.ASTRewriteChange#isListChange()
- */
- public boolean isListRewrite() {
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.dom.RewriteEvent#getChildren()
- */
- public RewriteEvent[] getChildren() {
- List entries= getEntries();
- return (RewriteEvent[]) entries.toArray(new RewriteEvent[entries.size()]);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.dom.RewriteEvent#getOriginalNode()
- */
- public Object getOriginalValue() {
- return this.originalNodes;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.dom.RewriteEvent#getNewValue()
- */
- public Object getNewValue() {
- List entries= getEntries();
- ArrayList res= new ArrayList(entries.size());
- for (int i= 0; i < entries.size(); i++) {
- RewriteEvent curr= (RewriteEvent) entries.get(i);
- Object newVal= curr.getNewValue();
- if (newVal != null) {
- res.add(newVal);
- }
- }
- return res;
- }
-
- // API to modify the list nodes
-
- public RewriteEvent removeEntry(ASTNode originalEntry) {
- return replaceEntry(originalEntry, null);
- }
-
- public RewriteEvent replaceEntry(ASTNode originalEntry, ASTNode newEntry) {
- if (originalEntry == null) {
- throw new IllegalArgumentException();
- }
-
- List entries= getEntries();
- int nEntries= entries.size();
- for (int i= 0; i < nEntries; i++) {
- NodeRewriteEvent curr= (NodeRewriteEvent) entries.get(i);
- if (curr.getOriginalValue() == originalEntry) {
- curr.setNewValue(newEntry);
- return curr;
- }
- }
- return null;
- }
-
- public void revertChange(NodeRewriteEvent event) {
- Object originalValue = event.getOriginalValue();
- if(originalValue == null) {
- List entries= getEntries();
- entries.remove(event);
- } else {
- event.setNewValue(originalValue);
- }
- }
-
- public int getIndex(ASTNode node, int kind) {
- List entries= getEntries();
- for (int i= entries.size() - 1; i >= 0; i--) {
- RewriteEvent curr= (RewriteEvent) entries.get(i);
- if (((kind & OLD) != 0) && (curr.getOriginalValue() == node)) {
- return i;
- }
- if (((kind & NEW) != 0) && (curr.getNewValue() == node)) {
- return i;
- }
- }
- return -1;
- }
-
- public RewriteEvent insert(ASTNode insertedNode, int insertIndex) {
- NodeRewriteEvent change= new NodeRewriteEvent(null, insertedNode);
- if (insertIndex != -1) {
- getEntries().add(insertIndex, change);
- } else {
- getEntries().add(change);
- }
- return change;
- }
-
- public void setNewValue(ASTNode newValue, int insertIndex) {
- NodeRewriteEvent curr= (NodeRewriteEvent) getEntries().get(insertIndex);
- curr.setNewValue(newValue);
- }
-
- public int getChangeKind(int index) {
- return ((NodeRewriteEvent) getEntries().get(index)).getChangeKind();
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#toString()
- */
- public String toString() {
- StringBuffer buf= new StringBuffer();
- buf.append(" [list change\n\t"); //$NON-NLS-1$
-
- RewriteEvent[] events= getChildren();
- for (int i= 0; i < events.length; i++) {
- if (i != 0) {
- buf.append("\n\t"); //$NON-NLS-1$
- }
- buf.append(events[i]);
- }
- buf.append("\n]"); //$NON-NLS-1$
- return buf.toString();
- }
-
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/NodeInfoStore.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/NodeInfoStore.java
deleted file mode 100644
index 749869e7..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/NodeInfoStore.java
+++ /dev/null
@@ -1,158 +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.dom.rewrite;
-
-import java.util.HashSet;
-import java.util.IdentityHashMap;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.TryStatement;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.internal.core.dom.rewrite.RewriteEventStore.CopySourceInfo;
-
-/**
- *
- */
-public final class NodeInfoStore {
- private AST ast;
-
- private Map placeholderNodes;
- private Set collapsedNodes;
-
- public NodeInfoStore(AST ast) {
- super();
- this.ast= ast;
- this.placeholderNodes= null;
- this.collapsedNodes= null;
- }
-
- /**
- * Marks a node as a placehoder for a plain string content. The type of the node should correspond to the
- * code's code content.
- * @param placeholder The placeholder node that acts for the string content.
- * @param code The string content.
- */
- public final void markAsStringPlaceholder(ASTNode placeholder, String code) {
- StringPlaceholderData data= new StringPlaceholderData();
- data.code= code;
- setPlaceholderData(placeholder, data);
- }
-
- /**
- * Marks a node as a copy or move target. The copy target represents a copied node at the target (copied) site.
- * @param target The node at the target site. Can be a placeholder node but also the source node itself.
- * @param copySource The info at the source site.
- */
- public final void markAsCopyTarget(ASTNode target, CopySourceInfo copySource) {
- CopyPlaceholderData data= new CopyPlaceholderData();
- data.copySource= copySource;
- setPlaceholderData(target, data);
- }
-
- /**
- * Creates a placeholder node of the given type. <code>null</code> if the type is not supported
- * @param nodeType Type of the node to create. Use the type constants in {@link NodeInfoStore}.
- * @return Returns a place holder node.
- */
- public final ASTNode newPlaceholderNode(int nodeType) {
- try {
- ASTNode node= this.ast.createInstance(nodeType);
- switch (node.getNodeType()) {
- case ASTNode.FIELD_DECLARATION:
- ((FieldDeclaration) node).fragments().add(this.ast.newVariableDeclarationFragment());
- break;
- case ASTNode.MODIFIER:
- ((Modifier) node).setKeyword(Modifier.ModifierKeyword.ABSTRACT_KEYWORD);
- break;
- case ASTNode.TRY_STATEMENT :
- ((TryStatement) node).setFinally(this.ast.newBlock()); // have to set at least a finally block to be legal code
- break;
- case ASTNode.VARIABLE_DECLARATION_EXPRESSION :
- ((VariableDeclarationExpression) node).fragments().add(this.ast.newVariableDeclarationFragment());
- break;
- case ASTNode.VARIABLE_DECLARATION_STATEMENT :
- ((VariableDeclarationStatement) node).fragments().add(this.ast.newVariableDeclarationFragment());
- break;
- }
- return node;
- } catch (IllegalArgumentException e) {
- return null;
- }
- }
-
-
- // collapsed nodes: in source: use one node that represents many; to be used as
- // copy/move source or to replace at once.
- // in the target: one block node that is not flattened.
-
- public Block createCollapsePlaceholder() {
- Block placeHolder= this.ast.newBlock();
- if (this.collapsedNodes == null) {
- this.collapsedNodes= new HashSet();
- }
- this.collapsedNodes.add(placeHolder);
- return placeHolder;
- }
-
- public boolean isCollapsed(ASTNode node) {
- if (this.collapsedNodes != null) {
- return this.collapsedNodes.contains(node);
- }
- return false;
- }
-
- public Object getPlaceholderData(ASTNode node) {
- if (this.placeholderNodes != null) {
- return this.placeholderNodes.get(node);
- }
- return null;
- }
-
- private void setPlaceholderData(ASTNode node, PlaceholderData data) {
- if (this.placeholderNodes == null) {
- this.placeholderNodes= new IdentityHashMap();
- }
- this.placeholderNodes.put(node, data);
- }
-
- static class PlaceholderData {
- // base class
- }
-
- protected static final class CopyPlaceholderData extends PlaceholderData {
- public CopySourceInfo copySource;
- public String toString() {
- return "[placeholder " + this.copySource +"]"; //$NON-NLS-1$//$NON-NLS-2$
- }
- }
-
- protected static final class StringPlaceholderData extends PlaceholderData {
- public String code;
- public String toString() {
- return "[placeholder string: " + this.code +"]"; //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
-
- /**
- *
- */
- public void clear() {
- this.placeholderNodes= null;
- this.collapsedNodes= null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/NodeRewriteEvent.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/NodeRewriteEvent.java
deleted file mode 100644
index 461f5b24..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/NodeRewriteEvent.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.dom.rewrite;
-
-
-
-/**
- *
- */
-public class NodeRewriteEvent extends RewriteEvent {
-
- private Object originalValue;
- private Object newValue;
-
- public NodeRewriteEvent(Object originalValue, Object newValue) {
- this.originalValue= originalValue;
- this.newValue= newValue;
- }
-
- /**
- * @return Returns the new value.
- */
- public Object getNewValue() {
- return this.newValue;
- }
-
- /**
- * @return Returns the original value.
- */
- public Object getOriginalValue() {
- return this.originalValue;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.dom.RewriteEvent#getChangeKind()
- */
- public int getChangeKind() {
- if (this.originalValue == this.newValue) {
- return UNCHANGED;
- }
- if (this.originalValue == null) {
- return INSERTED;
- }
- if (this.newValue == null) {
- return REMOVED;
- }
- if (this.originalValue.equals(this.newValue)) {
- return UNCHANGED;
- }
- return REPLACED;
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.dom.RewriteEvent#isListRewrite()
- */
- public boolean isListRewrite() {
- return false;
- }
-
- /*
- * Sets a new value for the new node. Internal access only.
- * @param newValue The new value to set.
- */
- public void setNewValue(Object newValue) {
- this.newValue= newValue;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.dom.RewriteEvent#getChildren()
- */
- public RewriteEvent[] getChildren() {
- return null;
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#toString()
- */
- public String toString() {
- StringBuffer buf= new StringBuffer();
- switch (getChangeKind()) {
- case INSERTED:
- buf.append(" [inserted: "); //$NON-NLS-1$
- buf.append(getNewValue());
- buf.append(']');
- break;
- case REPLACED:
- buf.append(" [replaced: "); //$NON-NLS-1$
- buf.append(getOriginalValue());
- buf.append(" -> "); //$NON-NLS-1$
- buf.append(getNewValue());
- buf.append(']');
- break;
- case REMOVED:
- buf.append(" [removed: "); //$NON-NLS-1$
- buf.append(getOriginalValue());
- buf.append(']');
- break;
- default:
- buf.append(" [unchanged]"); //$NON-NLS-1$
- }
- return buf.toString();
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/RewriteEvent.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/RewriteEvent.java
deleted file mode 100644
index de0eead2..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/RewriteEvent.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.dom.rewrite;
-
-
-/**
- *
- */
-public abstract class RewriteEvent {
-
- /**
- * Change kind to describe that the event is an insert event.
- * Does not apply for list events.
- */
- public static final int INSERTED= 1;
-
- /**
- * Change kind to describe that the event is an remove event.
- * Does not apply for list events.
- */
- public static final int REMOVED= 2;
-
- /**
- * Change kind to describe that the event is an replace event.
- * Does not apply for list events.
- */
- public static final int REPLACED= 4;
-
- /**
- * Change kind to signal that children changed. Does only apply for list events.
- */
- public static final int CHILDREN_CHANGED= 8;
-
- /**
- * Change kind to signal that the property did not change
- */
- public static final int UNCHANGED= 0;
-
- /**
- * @return Returns the event's change kind.
- */
- public abstract int getChangeKind();
-
- /**
- * @return Returns true if the given event is a list event.
- */
- public abstract boolean isListRewrite();
-
- /**
- * @return Returns the original value. For lists this is a <code>List<code> of ASTNode's, for non-list
- * events this can be an ASTNode (for node properties), Integer (for an integer property),
- * Boolean (for boolean node properties) or properties like Operator.
- * <code>null</code> is returned if the event is a insert event.
- */
- public abstract Object getOriginalValue();
-
- /**
- * @return Returns the new value. For lists this is a <code>List<code> of ASTNode's, for non-list
- * events this can be an ASTNode (for node properties), Integer (for an integer property),
- * Boolean (for boolean node properties) or properties like Operator.
- * <code>null</code> is returned if the event is a remove event.
- */
- public abstract Object getNewValue();
-
- /**
- * @return Return the events describing the changes in a list. returns <code>null</code> if the
- * event is not a list event.
- */
- public abstract RewriteEvent[] getChildren();
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/RewriteEventStore.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/RewriteEventStore.java
deleted file mode 100644
index 63faba39..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/RewriteEventStore.java
+++ /dev/null
@@ -1,849 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.dom.rewrite;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.IdentityHashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.Stack;
-
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.StructuralPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.rewrite.TargetSourceRangeComputer;
-
-
-/**
- * Stores all rewrite events, descriptions of events and knows which nodes
- * are copy or move sources or tracked.
- */
-public final class RewriteEventStore {
-
-
- public static final class PropertyLocation {
- private final ASTNode parent;
- private final StructuralPropertyDescriptor property;
-
- public PropertyLocation(ASTNode parent, StructuralPropertyDescriptor property) {
- this.parent= parent;
- this.property= property;
- }
-
- public ASTNode getParent() {
- return this.parent;
- }
-
- public StructuralPropertyDescriptor getProperty() {
- return this.property;
- }
-
- public boolean equals(Object obj) {
- if (obj != null && obj.getClass().equals(this.getClass())) {
- PropertyLocation other= (PropertyLocation) obj;
- return other.getParent().equals(getParent()) && other.getProperty().equals(getProperty());
- }
- return false;
- }
-
- public int hashCode() {
- return getParent().hashCode() + getProperty().hashCode();
- }
-
- }
-
- /**
- * Interface that allows to override the way how children are accessed from
- * a parent. Use this interface when the rewriter is set up on an already
- * modified AST's (as it is the case in the old ASTRewrite infrastructure)
- */
- public static interface INodePropertyMapper {
- /**
- * Returns the node attribute for a given property name.
- * @param parent The parent node
- * @param childProperty The child property to access
- * @return The child node at the given property location.
- */
- Object getOriginalValue(ASTNode parent, StructuralPropertyDescriptor childProperty);
- }
-
- /*
- * Store element to associate event and node position/
- */
- private static class EventHolder {
- public final ASTNode parent;
- public final StructuralPropertyDescriptor childProperty;
- public final RewriteEvent event;
-
- public EventHolder(ASTNode parent, StructuralPropertyDescriptor childProperty, RewriteEvent change) {
- this.parent= parent;
- this.childProperty= childProperty;
- this.event= change;
- }
-
- public String toString() {
- StringBuffer buf= new StringBuffer();
- buf.append(this.parent).append(" - "); //$NON-NLS-1$
- buf.append(this.childProperty.getId()).append(": "); //$NON-NLS-1$
- buf.append(this.event).append('\n');
- return buf.toString();
- }
- }
-
- public static class CopySourceInfo implements Comparable {
- public final PropertyLocation location; // can be null, only used to mark as removed on move
- private final ASTNode node;
- public final boolean isMove;
-
- public CopySourceInfo(PropertyLocation location, ASTNode node, boolean isMove) {
- this.location= location;
- this.node= node;
- this.isMove= isMove;
- }
-
- public ASTNode getNode() {
- return this.node;
- }
-
- public int compareTo(Object o2) {
- CopySourceInfo r2= (CopySourceInfo) o2;
-
- int startDiff= this.getNode().getStartPosition() - r2.getNode().getStartPosition();
- if (startDiff != 0) {
- return startDiff; // insert before if start node is first
- }
-
- if (r2.isMove != this.isMove) {
- return this.isMove ? -1 : 1; // first move then copy
- }
- return 0;
- }
-
- public String toString() {
- StringBuffer buf= new StringBuffer();
- if (this.isMove) {
- buf.append("move source: "); //$NON-NLS-1$
- } else {
- buf.append("copy source: "); //$NON-NLS-1$
- }
- buf.append(this.node);
- return buf.toString();
- }
- }
-
- private static class NodeRangeInfo implements Comparable {
- private final ASTNode first;
- private final ASTNode last;
- public final CopySourceInfo copyInfo; // containing the internal placeholder and the 'isMove' flag
- public final ASTNode replacingNode;
- public final TextEditGroup editGroup;
-
- public NodeRangeInfo(ASTNode parent, StructuralPropertyDescriptor childProperty, ASTNode first, ASTNode last, CopySourceInfo copyInfo, ASTNode replacingNode, TextEditGroup editGroup) {
- this.first= first;
- this.last= last;
- this.copyInfo= copyInfo;
- this.replacingNode= replacingNode;
- this.editGroup= editGroup;
- }
-
- public ASTNode getStartNode() {
- return this.first;
- }
-
- public ASTNode getEndNode() {
- return this.last;
- }
-
- public boolean isMove() {
- return this.copyInfo.isMove;
- }
-
- public Block getInternalPlaceholder() {
- return (Block) this.copyInfo.getNode();
- }
-
- public int compareTo(Object o2) {
- NodeRangeInfo r2= (NodeRangeInfo) o2;
-
- int startDiff= this.getStartNode().getStartPosition() - r2.getStartNode().getStartPosition();
- if (startDiff != 0) {
- return startDiff; // insert before if start node is first
- }
- int endDiff= this.getEndNode().getStartPosition() - r2.getEndNode().getStartPosition();
- if (endDiff != 0) {
- return -endDiff; // insert before if length is longer
- }
- if (r2.isMove() != this.isMove()) {
- return this.isMove() ? -1 : 1; // first move then copy
- }
- return 0;
- }
-
- public void updatePlaceholderSourceRanges(TargetSourceRangeComputer sourceRangeComputer) {
- TargetSourceRangeComputer.SourceRange startRange= sourceRangeComputer.computeSourceRange(getStartNode());
- TargetSourceRangeComputer.SourceRange endRange= sourceRangeComputer.computeSourceRange(getEndNode());
- int startPos= startRange.getStartPosition();
- int endPos= endRange.getStartPosition() + endRange.getLength();
-
- Block internalPlaceholder= getInternalPlaceholder();
- internalPlaceholder.setSourceRange(startPos, endPos - startPos);
- }
-
- public String toString() {
- StringBuffer buf= new StringBuffer();
- if (this.first != this.last) {
- buf.append("range "); //$NON-NLS-1$
- }
- if (isMove()) {
- buf.append("move source: "); //$NON-NLS-1$
- } else {
- buf.append("copy source: "); //$NON-NLS-1$
- }
- buf.append(this.first);
- buf.append(" - "); //$NON-NLS-1$
- buf.append(this.last);
- return buf.toString();
- }
-
-
- }
-
- /**
- * Iterates over all event parent nodes, tracked nodes and all copy/move sources
- */
- private class ParentIterator implements Iterator {
-
- private Iterator eventIter;
- private Iterator sourceNodeIter;
- private Iterator rangeNodeIter;
- private Iterator trackedNodeIter;
-
- public ParentIterator() {
- this.eventIter= RewriteEventStore.this.events.iterator();
- if (RewriteEventStore.this.nodeCopySources != null) {
- this.sourceNodeIter= RewriteEventStore.this.nodeCopySources.iterator();
- } else {
- this.sourceNodeIter= Collections.EMPTY_LIST.iterator();
- }
- if (RewriteEventStore.this.nodeRangeInfos != null) {
- this.rangeNodeIter= RewriteEventStore.this.nodeRangeInfos.keySet().iterator();
- } else {
- this.rangeNodeIter= Collections.EMPTY_LIST.iterator();
- }
- if (RewriteEventStore.this.trackedNodes != null) {
- this.trackedNodeIter= RewriteEventStore.this.trackedNodes.keySet().iterator();
- } else {
- this.trackedNodeIter= Collections.EMPTY_LIST.iterator();
- }
- }
-
- /* (non-Javadoc)
- * @see java.util.Iterator#hasNext()
- */
- public boolean hasNext() {
- return this.eventIter.hasNext() || this.sourceNodeIter.hasNext() || this.rangeNodeIter.hasNext() || this.trackedNodeIter.hasNext();
- }
-
- /* (non-Javadoc)
- * @see java.util.Iterator#next()
- */
- public Object next() {
- if (this.eventIter.hasNext()) {
- return ((EventHolder) this.eventIter.next()).parent;
- }
- if (this.sourceNodeIter.hasNext()) {
- return ((CopySourceInfo) this.sourceNodeIter.next()).getNode();
- }
- if (this.rangeNodeIter.hasNext()) {
- return ((PropertyLocation) this.rangeNodeIter.next()).getParent();
- }
- return this.trackedNodeIter.next();
- }
-
- /* (non-Javadoc)
- * @see java.util.Iterator#remove()
- */
- public void remove() {
- throw new UnsupportedOperationException();
- }
- }
-
- public final static int NEW= 1;
- public final static int ORIGINAL= 2;
- public final static int BOTH= NEW | ORIGINAL;
-
-
- /** all events */
- final List events;
-
- /** cache for last accessed event */
- private EventHolder lastEvent;
-
- /** Maps events to group descriptions */
- private Map editGroups;
-
- /** Stores which nodes are source of a copy or move (list of CopySourceInfo)*/
- List nodeCopySources;
-
- /** Stores node ranges that are used to copy or move (map of <PropertyLocation, CopyRangeInfo>)*/
- Map nodeRangeInfos;
-
- /** Stores which nodes are tracked and the corresponding edit group*/
- Map trackedNodes;
-
- /** Stores which inserted nodes bound to the previous node. If not, a node is
- * always bound to the next node */
- private Set insertBoundToPrevious;
-
- /** optional mapper to allow fix already modified AST trees */
- private INodePropertyMapper nodePropertyMapper;
-
- private static final String INTERNAL_PLACEHOLDER_PROPERTY= "rewrite_internal_placeholder"; //$NON-NLS-1$
-
- public RewriteEventStore() {
- this.events= new ArrayList();
- this.lastEvent= null;
-
- this.editGroups= null; // lazy initialization
-
- this.trackedNodes= null;
- this.insertBoundToPrevious= null;
-
- this.nodePropertyMapper= null;
- this.nodeCopySources= null;
- this.nodeRangeInfos= null;
- }
-
- /**
- * Override the default way how to access children from a parent node.
- * @param nodePropertyMapper The new <code>INodePropertyMapper</code> or
- * <code>null</code>. to use the default.
- */
- public void setNodePropertyMapper(INodePropertyMapper nodePropertyMapper) {
- this.nodePropertyMapper= nodePropertyMapper;
- }
-
- public void clear() {
- this.events.clear();
- this.lastEvent= null;
- this.trackedNodes= null;
-
- this.editGroups= null; // lazy initialization
- this.insertBoundToPrevious= null;
- this.nodeCopySources= null;
- }
-
- public void addEvent(ASTNode parent, StructuralPropertyDescriptor childProperty, RewriteEvent event) {
- validateHasChildProperty(parent, childProperty);
-
- if (event.isListRewrite()) {
- validateIsListProperty(childProperty);
- }
-
- EventHolder holder= new EventHolder(parent, childProperty, event);
-
- // check if already in list
- for (int i= 0; i < this.events.size(); i++) {
- EventHolder curr= (EventHolder) this.events.get(i);
- if (curr.parent == parent && curr.childProperty == childProperty) {
- this.events.set(i, holder);
- this.lastEvent= null;
- return;
- }
- }
- this.events.add(holder);
- }
-
- public RewriteEvent getEvent(ASTNode parent, StructuralPropertyDescriptor property) {
- validateHasChildProperty(parent, property);
-
- if (this.lastEvent != null && this.lastEvent.parent == parent && this.lastEvent.childProperty == property) {
- return this.lastEvent.event;
- }
-
- for (int i= 0; i < this.events.size(); i++) {
- EventHolder holder= (EventHolder) this.events.get(i);
- if (holder.parent == parent && holder.childProperty == property) {
- this.lastEvent= holder;
- return holder.event;
- }
- }
- return null;
- }
-
- public NodeRewriteEvent getNodeEvent(ASTNode parent, StructuralPropertyDescriptor childProperty, boolean forceCreation) {
- validateIsNodeProperty(childProperty);
- NodeRewriteEvent event= (NodeRewriteEvent) getEvent(parent, childProperty);
- if (event == null && forceCreation) {
- Object originalValue= accessOriginalValue(parent, childProperty);
- event= new NodeRewriteEvent(originalValue, originalValue);
- addEvent(parent, childProperty, event);
- }
- return event;
- }
-
- public ListRewriteEvent getListEvent(ASTNode parent, StructuralPropertyDescriptor childProperty, boolean forceCreation) {
- validateIsListProperty(childProperty);
- ListRewriteEvent event= (ListRewriteEvent) getEvent(parent, childProperty);
- if (event == null && forceCreation) {
- List originalValue= (List) accessOriginalValue(parent, childProperty);
- event= new ListRewriteEvent(originalValue);
- addEvent(parent, childProperty, event);
- }
- return event;
- }
-
- public Iterator getChangeRootIterator() {
- return new ParentIterator();
- }
-
-
- public boolean hasChangedProperties(ASTNode parent) {
- for (int i= 0; i < this.events.size(); i++) {
- EventHolder holder= (EventHolder) this.events.get(i);
- if (holder.parent == parent) {
- if (holder.event.getChangeKind() != RewriteEvent.UNCHANGED) {
- return true;
- }
- }
- }
- return false;
- }
-
- public PropertyLocation getPropertyLocation(Object value, int kind) {
- for (int i= 0; i < this.events.size(); i++) {
- EventHolder holder= (EventHolder) this.events.get(i);
- RewriteEvent event= holder.event;
- if (isNodeInEvent(event, value, kind)) {
- return new PropertyLocation(holder.parent, holder.childProperty);
- }
- if (event.isListRewrite()) {
- RewriteEvent[] children= event.getChildren();
- for (int k= 0; k < children.length; k++) {
- if (isNodeInEvent(children[k], value, kind)) {
- return new PropertyLocation(holder.parent, holder.childProperty);
- }
- }
- }
- }
- if (value instanceof ASTNode) {
- ASTNode node= (ASTNode) value;
- return new PropertyLocation(node.getParent(), node.getLocationInParent());
- }
- return null;
- }
-
-
- /**
- * Kind is either ORIGINAL, NEW, or BOTH
- * @param value
- * @param kind
- * @return Returns the event with the given value of <code>null</code>.
- */
- public RewriteEvent findEvent(Object value, int kind) {
- for (int i= 0; i < this.events.size(); i++) {
- RewriteEvent event= ((EventHolder) this.events.get(i)).event;
- if (isNodeInEvent(event, value, kind)) {
- return event;
- }
- if (event.isListRewrite()) {
- RewriteEvent[] children= event.getChildren();
- for (int k= 0; k < children.length; k++) {
- if (isNodeInEvent(children[k], value, kind)) {
- return children[k];
- }
- }
- }
- }
- return null;
- }
-
- private boolean isNodeInEvent(RewriteEvent event, Object value, int kind) {
- if (((kind & NEW) != 0) && event.getNewValue() == value) {
- return true;
- }
- if (((kind & ORIGINAL) != 0) && event.getOriginalValue() == value) {
- return true;
- }
- return false;
- }
-
-
- public Object getOriginalValue(ASTNode parent, StructuralPropertyDescriptor property) {
- RewriteEvent event= getEvent(parent, property);
- if (event != null) {
- return event.getOriginalValue();
- }
- return accessOriginalValue(parent, property);
- }
-
- public Object getNewValue(ASTNode parent, StructuralPropertyDescriptor property) {
- RewriteEvent event= getEvent(parent, property);
- if (event != null) {
- return event.getNewValue();
- }
- return accessOriginalValue(parent, property);
- }
-
- public int getChangeKind(ASTNode node) {
- RewriteEvent event= findEvent(node, ORIGINAL);
- if (event != null) {
- return event.getChangeKind();
- }
- return RewriteEvent.UNCHANGED;
- }
-
- /*
- * Gets an original child from the AST.
- * Temporarily overridden to port the old rewriter to the new infrastructure.
- */
- private Object accessOriginalValue(ASTNode parent, StructuralPropertyDescriptor childProperty) {
- if (this.nodePropertyMapper != null) {
- return this.nodePropertyMapper.getOriginalValue(parent, childProperty);
- }
-
- return parent.getStructuralProperty(childProperty);
- }
-
- public TextEditGroup getEventEditGroup(RewriteEvent event) {
- if (this.editGroups == null) {
- return null;
- }
- return (TextEditGroup) this.editGroups.get(event);
- }
-
- public void setEventEditGroup(RewriteEvent event, TextEditGroup editGroup) {
- if (this.editGroups == null) {
- this.editGroups= new IdentityHashMap(5);
- }
- this.editGroups.put(event, editGroup);
- }
-
-
- public final TextEditGroup getTrackedNodeData(ASTNode node) {
- if (this.trackedNodes != null) {
- return (TextEditGroup) this.trackedNodes.get(node);
- }
- return null;
- }
-
- public void setTrackedNodeData(ASTNode node, TextEditGroup editGroup) {
- if (this.trackedNodes == null) {
- this.trackedNodes= new IdentityHashMap();
- }
- this.trackedNodes.put(node, editGroup);
- }
-
- /**
- * Marks a node as tracked. The edits added to the group editGroup can be used to get the
- * position of the node after the rewrite operation.
- * @param node The node to track
- * @param editGroup Collects the range markers describing the node position.
- */
- public final void markAsTracked(ASTNode node, TextEditGroup editGroup) {
- if (getTrackedNodeData(node) != null) {
- throw new IllegalArgumentException("Node is already marked as tracked"); //$NON-NLS-1$
- }
- setTrackedNodeData(node, editGroup);
- }
-
- private final CopySourceInfo createCopySourceInfo(PropertyLocation location, ASTNode node, boolean isMove) {
- CopySourceInfo copySource= new CopySourceInfo(location, node, isMove);
-
- if (this.nodeCopySources == null) {
- this.nodeCopySources= new ArrayList();
- }
- this.nodeCopySources.add(copySource);
- return copySource;
- }
-
- public final CopySourceInfo markAsCopySource(ASTNode parent, StructuralPropertyDescriptor property, ASTNode node, boolean isMove) {
- return createCopySourceInfo(new PropertyLocation(parent, property), node, isMove);
- }
-
- public final boolean isRangeCopyPlaceholder(ASTNode node) {
- return node.getProperty(INTERNAL_PLACEHOLDER_PROPERTY) != null;
- }
-
- public final CopySourceInfo createRangeCopy(ASTNode parent, StructuralPropertyDescriptor childProperty, ASTNode first, ASTNode last, boolean isMove, ASTNode internalPlaceholder, ASTNode replacingNode, TextEditGroup editGroup) {
- CopySourceInfo copyInfo= createCopySourceInfo(null, internalPlaceholder, isMove);
- internalPlaceholder.setProperty(INTERNAL_PLACEHOLDER_PROPERTY, internalPlaceholder);
-
- NodeRangeInfo copyRangeInfo= new NodeRangeInfo(parent, childProperty, first, last, copyInfo, replacingNode, editGroup);
-
- ListRewriteEvent listEvent= getListEvent(parent, childProperty, true);
-
- int indexFirst= listEvent.getIndex(first, ListRewriteEvent.OLD);
- if (indexFirst == -1) {
- throw new IllegalArgumentException("Start node is not a original child of the given list"); //$NON-NLS-1$
- }
- int indexLast= listEvent.getIndex(last, ListRewriteEvent.OLD);
- if (indexLast == -1) {
- throw new IllegalArgumentException("End node is not a original child of the given list"); //$NON-NLS-1$
- }
-
- if (indexFirst > indexLast) {
- throw new IllegalArgumentException("Start node must be before end node"); //$NON-NLS-1$
- }
-
- if (this.nodeRangeInfos == null) {
- this.nodeRangeInfos= new HashMap();
- }
- PropertyLocation loc= new PropertyLocation(parent, childProperty);
- List innerList= (List) this.nodeRangeInfos.get(loc);
- if (innerList == null) {
- innerList= new ArrayList(2);
- this.nodeRangeInfos.put(loc, innerList);
- } else {
- assertNoOverlap(listEvent, indexFirst, indexLast, innerList);
- }
- innerList.add(copyRangeInfo);
-
-
- return copyInfo;
- }
-
- public CopySourceInfo[] getNodeCopySources(ASTNode node) {
- if (this.nodeCopySources == null) {
- return null;
- }
- return internalGetCopySources(this.nodeCopySources, node);
- }
-
-
- public CopySourceInfo[] internalGetCopySources(List copySources, ASTNode node) {
- ArrayList res= new ArrayList(3);
- for (int i= 0; i < copySources.size(); i++) {
- CopySourceInfo curr= (CopySourceInfo) copySources.get(i);
- if (curr.getNode() == node) {
- res.add(curr);
- }
- }
- if (res.isEmpty()) {
- return null;
- }
-
- CopySourceInfo[] arr= (CopySourceInfo[]) res.toArray(new CopySourceInfo[res.size()]);
- Arrays.sort(arr);
- return arr;
- }
-
-
- private void assertNoOverlap(ListRewriteEvent listEvent, int indexFirst, int indexLast, List innerList) {
- for (Iterator iter= innerList.iterator(); iter.hasNext();) {
- NodeRangeInfo curr= (NodeRangeInfo) iter.next();
- int currStart= listEvent.getIndex(curr.getStartNode(), ListRewriteEvent.BOTH);
- int currEnd= listEvent.getIndex(curr.getEndNode(), ListRewriteEvent.BOTH);
- if (currStart < indexFirst && currEnd < indexLast && currEnd >= indexFirst
- || currStart > indexFirst && currStart <= currEnd && currEnd > indexLast) {
- throw new IllegalArgumentException("Range overlapps with an existing copy or move range"); //$NON-NLS-1$
- }
- }
- }
-
- public void prepareMovedNodes(TargetSourceRangeComputer sourceRangeComputer) {
- if (this.nodeCopySources != null) {
- prepareSingleNodeCopies();
- }
-
- if (this.nodeRangeInfos != null) {
- prepareNodeRangeCopies(sourceRangeComputer);
- }
- }
-
- public void revertMovedNodes() {
- if (this.nodeRangeInfos != null) {
- removeMoveRangePlaceholders();
- }
- }
-
- private void removeMoveRangePlaceholders() {
- for (Iterator iter= this.nodeRangeInfos.entrySet().iterator(); iter.hasNext();) {
- Map.Entry entry= (Map.Entry) iter.next();
- Set placeholders= new HashSet(); // collect all placeholders
- List rangeInfos= (List) entry.getValue(); // list of CopySourceRange
- for (int i= 0; i < rangeInfos.size(); i++) {
- placeholders.add(((NodeRangeInfo) rangeInfos.get(i)).getInternalPlaceholder());
- }
-
- PropertyLocation loc= (PropertyLocation) entry.getKey();
-
- RewriteEvent[] children= getListEvent(loc.getParent(), loc.getProperty(), true).getChildren();
- List revertedChildren= new ArrayList();
- revertListWithRanges(children, placeholders, revertedChildren);
- RewriteEvent[] revertedChildrenArr= (RewriteEvent[]) revertedChildren.toArray(new RewriteEvent[revertedChildren.size()]);
- addEvent(loc.getParent(), loc.getProperty(), new ListRewriteEvent(revertedChildrenArr)); // replace the current edits
- }
- }
-
- private void revertListWithRanges(RewriteEvent[] childEvents, Set placeholders, List revertedChildren) {
- for (int i= 0; i < childEvents.length; i++) {
- RewriteEvent event= childEvents[i];
- ASTNode node= (ASTNode) event.getOriginalValue();
- if (placeholders.contains(node)) {
- RewriteEvent[] placeholderChildren= getListEvent(node, Block.STATEMENTS_PROPERTY, false).getChildren();
- revertListWithRanges(placeholderChildren, placeholders, revertedChildren);
- } else {
- revertedChildren.add(event);
- }
- }
- }
-
- private void prepareNodeRangeCopies(TargetSourceRangeComputer sourceRangeComputer) {
- for (Iterator iter= this.nodeRangeInfos.entrySet().iterator(); iter.hasNext();) {
- Map.Entry entry= (Map.Entry) iter.next();
- List rangeInfos= (List) entry.getValue(); // list of CopySourceRange
- Collections.sort(rangeInfos); // sort by start index, length, move or copy
-
- PropertyLocation loc= (PropertyLocation) entry.getKey();
- RewriteEvent[] children= getListEvent(loc.getParent(), loc.getProperty(), true).getChildren();
-
- RewriteEvent[] newChildren= processListWithRanges(rangeInfos, children, sourceRangeComputer);
- addEvent(loc.getParent(), loc.getProperty(), new ListRewriteEvent(newChildren)); // replace the current edits
- }
- }
-
- private RewriteEvent[] processListWithRanges(List rangeInfos, RewriteEvent[] childEvents, TargetSourceRangeComputer sourceRangeComputer) {
- List newChildEvents= new ArrayList(childEvents.length);
- NodeRangeInfo topInfo= null;
- Stack newChildrenStack= new Stack();
- Stack topInfoStack= new Stack();
-
- Iterator rangeInfoIterator= rangeInfos.iterator();
- NodeRangeInfo nextInfo= (NodeRangeInfo) rangeInfoIterator.next();
-
- for (int k= 0; k < childEvents.length; k++) {
- RewriteEvent event= childEvents[k];
- ASTNode node= (ASTNode) event.getOriginalValue();
- // check for ranges and add a placeholder for them
- while (nextInfo != null && node == nextInfo.getStartNode()) { // is this child the beginning of a range?
- nextInfo.updatePlaceholderSourceRanges(sourceRangeComputer);
-
- Block internalPlaceholder= nextInfo.getInternalPlaceholder();
- RewriteEvent newEvent;
- if (nextInfo.isMove()) {
- newEvent= new NodeRewriteEvent(internalPlaceholder, nextInfo.replacingNode); // remove or replace
- } else {
- newEvent= new NodeRewriteEvent(internalPlaceholder, internalPlaceholder); // unchanged
- }
- newChildEvents.add(newEvent);
- if (nextInfo.editGroup != null) {
- setEventEditGroup(newEvent, nextInfo.editGroup);
- }
-
- newChildrenStack.push(newChildEvents);
- topInfoStack.push(topInfo);
-
- newChildEvents= new ArrayList(childEvents.length);
- topInfo= nextInfo;
-
- nextInfo= rangeInfoIterator.hasNext() ? (NodeRangeInfo) rangeInfoIterator.next() : null;
- }
-
- newChildEvents.add(event);
-
- while (topInfo != null && node == topInfo.getEndNode()) {
- RewriteEvent[] placeholderChildEvents= (RewriteEvent[]) newChildEvents.toArray(new RewriteEvent[newChildEvents.size()]);
- Block internalPlaceholder= topInfo.getInternalPlaceholder();
- addEvent(internalPlaceholder, Block.STATEMENTS_PROPERTY, new ListRewriteEvent(placeholderChildEvents));
-
- newChildEvents= (List) newChildrenStack.pop();
- topInfo= (NodeRangeInfo) topInfoStack.pop();
- }
- }
- return (RewriteEvent[]) newChildEvents.toArray(new RewriteEvent[newChildEvents.size()]);
- }
-
- /**
- * Make sure all moved nodes are marked as removed or replaced.
- */
- private void prepareSingleNodeCopies() {
- for (int i= 0; i < this.nodeCopySources.size(); i++) {
- CopySourceInfo curr= (CopySourceInfo) this.nodeCopySources.get(i);
- if (curr.isMove && curr.location != null) {
- doMarkMovedAsRemoved(curr, curr.location.getParent(), curr.location.getProperty());
- }
- }
-
- }
-
- private void doMarkMovedAsRemoved(CopySourceInfo curr, ASTNode parent, StructuralPropertyDescriptor childProperty) {
- if (childProperty.isChildListProperty()) {
- ListRewriteEvent event= getListEvent(parent, childProperty, true);
- int index= event.getIndex(curr.getNode(), ListRewriteEvent.OLD);
- if (index != -1 && event.getChangeKind(index) == RewriteEvent.UNCHANGED) {
- event.setNewValue(null, index);
- }
- } else {
- NodeRewriteEvent event= getNodeEvent(parent, childProperty, true);
- if (event.getChangeKind() == RewriteEvent.UNCHANGED) {
- event.setNewValue(null);
- }
- }
- }
-
- public boolean isInsertBoundToPrevious(ASTNode node) {
- if (this.insertBoundToPrevious != null) {
- return this.insertBoundToPrevious.contains(node);
- }
- return false;
- }
-
- public void setInsertBoundToPrevious(ASTNode node) {
- if (this.insertBoundToPrevious == null) {
- this.insertBoundToPrevious= new HashSet();
- }
- this.insertBoundToPrevious.add(node);
- }
-
- private void validateIsListProperty(StructuralPropertyDescriptor property) {
- if (!property.isChildListProperty()) {
- String message= property.getId() + " is not a list property"; //$NON-NLS-1$
- throw new IllegalArgumentException(message);
- }
- }
-
- private void validateHasChildProperty(ASTNode parent, StructuralPropertyDescriptor property) {
- if (!parent.structuralPropertiesForType().contains(property)) {
- String message= Signature.getSimpleName(parent.getClass().getName()) + " has no property " + property.getId(); //$NON-NLS-1$
- throw new IllegalArgumentException(message);
- }
- }
-
- private void validateIsNodeProperty(StructuralPropertyDescriptor property) {
- if (property.isChildListProperty()) {
- String message= property.getId() + " is not a node property"; //$NON-NLS-1$
- throw new IllegalArgumentException(message);
- }
- }
-
- public String toString() {
- StringBuffer buf= new StringBuffer();
- for (int i= 0; i < this.events.size(); i++) {
- buf.append(this.events.get(i).toString()).append('\n');
- }
- return buf.toString();
- }
-
- public static boolean isNewNode(ASTNode node) {
- return (node.getFlags() & ASTNode.ORIGINAL) == 0;
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/SourceModifier.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/SourceModifier.java
deleted file mode 100644
index 907c8bfb..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/SourceModifier.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.dom.rewrite;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.text.edits.ISourceModifier;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.wst.jsdt.core.formatter.IndentManipulation;
-
-
-public class SourceModifier implements ISourceModifier {
-
- private final String destinationIndent;
- private final int sourceIndentLevel;
- private final int tabWidth;
- private final int indentWidth;
-
- public SourceModifier(int sourceIndentLevel, String destinationIndent, int tabWidth, int indentWidth) {
- this.destinationIndent= destinationIndent;
- this.sourceIndentLevel= sourceIndentLevel;
- this.tabWidth= tabWidth;
- this.indentWidth= indentWidth;
- }
-
- public ISourceModifier copy() {
- // We are state less
- return this;
- }
-
- public ReplaceEdit[] getModifications(String source) {
- List result= new ArrayList();
- int destIndentLevel= IndentManipulation.measureIndentUnits(this.destinationIndent, this.tabWidth, this.indentWidth);
- if (destIndentLevel == this.sourceIndentLevel) {
- return (ReplaceEdit[])result.toArray(new ReplaceEdit[result.size()]);
- }
- return IndentManipulation.getChangeIndentEdits(source, this.sourceIndentLevel, this.tabWidth, this.indentWidth, this.destinationIndent);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/TokenScanner.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/TokenScanner.java
deleted file mode 100644
index beea8c1f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/TokenScanner.java
+++ /dev/null
@@ -1,238 +0,0 @@
-/*******************************************************************************
- * 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.dom.rewrite;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.compiler.IScanner;
-import org.eclipse.wst.jsdt.core.compiler.ITerminalSymbols;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-
-/**
- * Wraps a scanner and offers convenient methods for finding tokens
- */
-public class TokenScanner {
-
- public static final int END_OF_FILE= 20001;
- public static final int LEXICAL_ERROR= 20002;
- public static final int DOCUMENT_ERROR= 20003;
-
- private final IScanner scanner;
- private final int endPosition;
-
- /**
- * Creates a TokenScanner
- * @param scanner The scanner to be wrapped
- */
- public TokenScanner(IScanner scanner) {
- this.scanner= scanner;
- this.endPosition= this.scanner.getSource().length - 1;
- }
-
- /**
- * Returns the wrapped scanner
- * @return IScanner
- */
- public IScanner getScanner() {
- return this.scanner;
- }
-
- /**
- * Sets the scanner offset to the given offset.
- * @param offset The offset to set
- */
- public void setOffset(int offset) {
- this.scanner.resetTo(offset, this.endPosition);
- }
-
- /**
- * @return Returns the offset after the current token
- */
- public int getCurrentEndOffset() {
- return this.scanner.getCurrentTokenEndPosition() + 1;
- }
-
- /**
- * @return Returns the start offset of the current token
- */
- public int getCurrentStartOffset() {
- return this.scanner.getCurrentTokenStartPosition();
- }
-
- /**
- * @return Returns the length of the current token
- */
- public int getCurrentLength() {
- return getCurrentEndOffset() - getCurrentStartOffset();
- }
-
- /**
- * Reads the next token.
- * @param ignoreComments If set, comments will be overread
- * @return Return the token id.
- * @exception CoreException Thrown when the end of the file has been reached (code END_OF_FILE)
- * or a lexical error was detected while scanning (code LEXICAL_ERROR)
- */
- public int readNext(boolean ignoreComments) throws CoreException {
- int curr= 0;
- do {
- try {
- curr= this.scanner.getNextToken();
- if (curr == ITerminalSymbols.TokenNameEOF) {
- throw new CoreException(createError(END_OF_FILE, "End Of File", null)); //$NON-NLS-1$
- }
- } catch (InvalidInputException e) {
- throw new CoreException(createError(LEXICAL_ERROR, e.getMessage(), e));
- }
- } while (ignoreComments && isComment(curr));
- return curr;
- }
-
- /**
- * Reads the next token from the given offset.
- * @param offset The offset to start reading from.
- * @param ignoreComments If set, comments will be overread.
- * @return Returns the token id.
- * @exception CoreException Thrown when the end of the file has been reached (code END_OF_FILE)
- * or a lexical error was detected while scanning (code LEXICAL_ERROR)
- */
- public int readNext(int offset, boolean ignoreComments) throws CoreException {
- setOffset(offset);
- return readNext(ignoreComments);
- }
-
- /**
- * Reads the next token from the given offset and returns the start offset of the token.
- * @param offset The offset to start reading from.
- * @param ignoreComments If set, comments will be overread
- * @return Returns the start position of the next token.
- * @exception CoreException Thrown when the end of the file has been reached (code END_OF_FILE)
- * or a lexical error was detected while scanning (code LEXICAL_ERROR)
- */
- public int getNextStartOffset(int offset, boolean ignoreComments) throws CoreException {
- readNext(offset, ignoreComments);
- return getCurrentStartOffset();
- }
-
- /**
- * Reads the next token from the given offset and returns the offset after the token.
- * @param offset The offset to start reading from.
- * @param ignoreComments If set, comments will be overread
- * @return Returns the start position of the next token.
- * @exception CoreException Thrown when the end of the file has been reached (code END_OF_FILE)
- * or a lexical error was detected while scanning (code LEXICAL_ERROR)
- */
- public int getNextEndOffset(int offset, boolean ignoreComments) throws CoreException {
- readNext(offset, ignoreComments);
- return getCurrentEndOffset();
- }
-
- /**
- * Reads until a token is reached.
- * @param tok The token to read to.
- * @exception CoreException Thrown when the end of the file has been reached (code END_OF_FILE)
- * or a lexical error was detected while scanning (code LEXICAL_ERROR)
- */
- public void readToToken(int tok) throws CoreException {
- int curr= 0;
- do {
- curr= readNext(false);
- } while (curr != tok);
- }
-
- /**
- * Reads until a token is reached, starting from the given offset.
- * @param tok The token to read to.
- * @param offset The offset to start reading from.
- * @exception CoreException Thrown when the end of the file has been reached (code END_OF_FILE)
- * or a lexical error was detected while scanning (code LEXICAL_ERROR)
- */
- public void readToToken(int tok, int offset) throws CoreException {
- setOffset(offset);
- readToToken(tok);
- }
-
- /**
- * Reads from the given offset until a token is reached and returns the start offset of the token.
- * @param token The token to be found.
- * @param startOffset The offset to start reading from.
- * @return Returns the start position of the found token.
- * @exception CoreException Thrown when the end of the file has been reached (code END_OF_FILE)
- * or a lexical error was detected while scanning (code LEXICAL_ERROR)
- */
- public int getTokenStartOffset(int token, int startOffset) throws CoreException {
- readToToken(token, startOffset);
- return getCurrentStartOffset();
- }
-
- /**
- * Reads from the given offset until a token is reached and returns the offset after the token.
- * @param token The token to be found.
- * @param startOffset Offset to start reading from
- * @return Returns the end position of the found token.
- * @exception CoreException Thrown when the end of the file has been reached (code END_OF_FILE)
- * or a lexical error was detected while scanning (code LEXICAL_ERROR)
- */
- public int getTokenEndOffset(int token, int startOffset) throws CoreException {
- readToToken(token, startOffset);
- return getCurrentEndOffset();
- }
-
- /**
- * Reads from the given offset until a token is reached and returns the offset after the previous token.
- * @param token The token to be found.
- * @param startOffset The offset to start scanning from.
- * @return Returns the end offset of the token previous to the given token.
- * @exception CoreException Thrown when the end of the file has been reached (code END_OF_FILE)
- * or a lexical error was detected while scanning (code LEXICAL_ERROR)
- */
- public int getPreviousTokenEndOffset(int token, int startOffset) throws CoreException {
- setOffset(startOffset);
- int res= startOffset;
- int curr= readNext(false);
- while (curr != token) {
- res= getCurrentEndOffset();
- curr= readNext(false);
- }
- return res;
- }
-
- public static boolean isComment(int token) {
- return token == ITerminalSymbols.TokenNameCOMMENT_BLOCK || token == ITerminalSymbols.TokenNameCOMMENT_JAVADOC
- || token == ITerminalSymbols.TokenNameCOMMENT_LINE;
- }
-
- public static boolean isModifier(int token) {
- switch (token) {
- case ITerminalSymbols.TokenNamepublic:
- case ITerminalSymbols.TokenNameprotected:
- case ITerminalSymbols.TokenNameprivate:
- case ITerminalSymbols.TokenNamestatic:
- case ITerminalSymbols.TokenNamefinal:
- case ITerminalSymbols.TokenNameabstract:
- case ITerminalSymbols.TokenNamenative:
- case ITerminalSymbols.TokenNamevolatile:
- case ITerminalSymbols.TokenNamestrictfp:
- case ITerminalSymbols.TokenNametransient:
- case ITerminalSymbols.TokenNamesynchronized:
- return true;
- default:
- return false;
- }
- }
-
- public static IStatus createError(int code, String message, Throwable throwable) {
- return new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, code, message, throwable);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/TrackedNodePosition.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/TrackedNodePosition.java
deleted file mode 100644
index 5614797c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/TrackedNodePosition.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.dom.rewrite;
-
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ITrackedNodePosition;
-
-/**
- *
- */
-public class TrackedNodePosition implements ITrackedNodePosition {
-
- private final TextEditGroup group;
- private final ASTNode node;
-
- public TrackedNodePosition(TextEditGroup group, ASTNode node) {
- this.group= group;
- this.node= node;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.dom.ITrackedNodePosition#getStartPosition()
- */
- public int getStartPosition() {
- if (this.group.isEmpty()) {
- return this.node.getStartPosition();
- }
- IRegion coverage= TextEdit.getCoverage(this.group.getTextEdits());
- if (coverage == null) {
- return this.node.getStartPosition();
- }
- return coverage.getOffset();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.dom.ITrackedNodePosition#getLength()
- */
- public int getLength() {
- if (this.group.isEmpty()) {
- return this.node.getLength();
- }
- IRegion coverage= TextEdit.getCoverage(this.group.getTextEdits());
- if (coverage == null) {
- return this.node.getLength();
- }
- return coverage.getLength();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/ChangeCollector.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/ChangeCollector.java
deleted file mode 100644
index 77906908..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/ChangeCollector.java
+++ /dev/null
@@ -1,436 +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.hierarchy;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IImportContainer;
-import org.eclipse.wst.jsdt.core.IImportDeclaration;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptElementDelta;
-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.internal.core.JavaElement;
-import org.eclipse.wst.jsdt.internal.core.SimpleDelta;
-
-/*
- * Collects changes (reported through fine-grained deltas) that can affect a type hierarchy.
- */
-public class ChangeCollector {
-
- /*
- * A table from ITypes to TypeDeltas
- */
- HashMap changes = new HashMap();
-
- TypeHierarchy hierarchy;
-
- public ChangeCollector(TypeHierarchy hierarchy) {
- this.hierarchy = hierarchy;
- }
-
- /*
- * Adds the children of the given delta to the list of changes.
- */
- private void addAffectedChildren(IJavaScriptElementDelta delta) throws JavaScriptModelException {
- IJavaScriptElementDelta[] children = delta.getAffectedChildren();
- for (int i = 0, length = children.length; i < length; i++) {
- IJavaScriptElementDelta child = children[i];
- IJavaScriptElement childElement = child.getElement();
- switch (childElement.getElementType()) {
- case IJavaScriptElement.IMPORT_CONTAINER:
- addChange((IImportContainer)childElement, child);
- break;
- case IJavaScriptElement.IMPORT_DECLARATION:
- addChange((IImportDeclaration)childElement, child);
- break;
- case IJavaScriptElement.TYPE:
- addChange((IType)childElement, child);
- break;
- case IJavaScriptElement.INITIALIZER:
- case IJavaScriptElement.FIELD:
- case IJavaScriptElement.METHOD:
- addChange((IMember)childElement, child);
- break;
- }
- }
- }
-
- /*
- * Adds the given delta on a compilation unit to the list of changes.
- */
- public void addChange(IJavaScriptUnit cu, IJavaScriptElementDelta newDelta) throws JavaScriptModelException {
- int newKind = newDelta.getKind();
- switch (newKind) {
- case IJavaScriptElementDelta.ADDED:
- ArrayList allTypes = new ArrayList();
- getAllTypesFromElement(cu, allTypes);
- for (int i = 0, length = allTypes.size(); i < length; i++) {
- IType type = (IType)allTypes.get(i);
- addTypeAddition(type, (SimpleDelta)this.changes.get(type));
- }
- break;
- case IJavaScriptElementDelta.REMOVED:
- allTypes = new ArrayList();
- getAllTypesFromHierarchy((JavaElement)cu, allTypes);
- for (int i = 0, length = allTypes.size(); i < length; i++) {
- IType type = (IType)allTypes.get(i);
- addTypeRemoval(type, (SimpleDelta)this.changes.get(type));
- }
- break;
- case IJavaScriptElementDelta.CHANGED:
- addAffectedChildren(newDelta);
- break;
- }
- }
-
- private void addChange(IImportContainer importContainer, IJavaScriptElementDelta newDelta) throws JavaScriptModelException {
- int newKind = newDelta.getKind();
- if (newKind == IJavaScriptElementDelta.CHANGED) {
- addAffectedChildren(newDelta);
- return;
- }
- SimpleDelta existingDelta = (SimpleDelta)this.changes.get(importContainer);
- if (existingDelta != null) {
- switch (newKind) {
- case IJavaScriptElementDelta.ADDED:
- if (existingDelta.getKind() == IJavaScriptElementDelta.REMOVED) {
- // REMOVED then ADDED
- this.changes.remove(importContainer);
- }
- break;
- case IJavaScriptElementDelta.REMOVED:
- if (existingDelta.getKind() == IJavaScriptElementDelta.ADDED) {
- // ADDED then REMOVED
- this.changes.remove(importContainer);
- }
- break;
- // CHANGED handled above
- }
- } else {
- SimpleDelta delta = new SimpleDelta();
- switch (newKind) {
- case IJavaScriptElementDelta.ADDED:
- delta.added();
- break;
- case IJavaScriptElementDelta.REMOVED:
- delta.removed();
- break;
- }
- this.changes.put(importContainer, delta);
- }
- }
-
- private void addChange(IImportDeclaration importDecl, IJavaScriptElementDelta newDelta) {
- SimpleDelta existingDelta = (SimpleDelta)this.changes.get(importDecl);
- int newKind = newDelta.getKind();
- if (existingDelta != null) {
- switch (newKind) {
- case IJavaScriptElementDelta.ADDED:
- if (existingDelta.getKind() == IJavaScriptElementDelta.REMOVED) {
- // REMOVED then ADDED
- this.changes.remove(importDecl);
- }
- break;
- case IJavaScriptElementDelta.REMOVED:
- if (existingDelta.getKind() == IJavaScriptElementDelta.ADDED) {
- // ADDED then REMOVED
- this.changes.remove(importDecl);
- }
- break;
- // CHANGED cannot happen for import declaration
- }
- } else {
- SimpleDelta delta = new SimpleDelta();
- switch (newKind) {
- case IJavaScriptElementDelta.ADDED:
- delta.added();
- break;
- case IJavaScriptElementDelta.REMOVED:
- delta.removed();
- break;
- }
- this.changes.put(importDecl, delta);
- }
- }
-
- /*
- * Adds a change for the given member (a method, a field or an initializer) and the types it defines.
- */
- private void addChange(IMember member, IJavaScriptElementDelta newDelta) throws JavaScriptModelException {
- int newKind = newDelta.getKind();
- switch (newKind) {
- case IJavaScriptElementDelta.ADDED:
- ArrayList allTypes = new ArrayList();
- getAllTypesFromElement(member, allTypes);
- for (int i = 0, length = allTypes.size(); i < length; i++) {
- IType innerType = (IType)allTypes.get(i);
- addTypeAddition(innerType, (SimpleDelta)this.changes.get(innerType));
- }
- break;
- case IJavaScriptElementDelta.REMOVED:
- allTypes = new ArrayList();
- getAllTypesFromHierarchy((JavaElement)member, allTypes);
- for (int i = 0, length = allTypes.size(); i < length; i++) {
- IType type = (IType)allTypes.get(i);
- addTypeRemoval(type, (SimpleDelta)this.changes.get(type));
- }
- break;
- case IJavaScriptElementDelta.CHANGED:
- addAffectedChildren(newDelta);
- break;
- }
- }
-
- /*
- * Adds a change for the given type and the types it defines.
- */
- private void addChange(IType type, IJavaScriptElementDelta newDelta) throws JavaScriptModelException {
- int newKind = newDelta.getKind();
- SimpleDelta existingDelta = (SimpleDelta)this.changes.get(type);
- switch (newKind) {
- case IJavaScriptElementDelta.ADDED:
- addTypeAddition(type, existingDelta);
- ArrayList allTypes = new ArrayList();
- getAllTypesFromElement(type, allTypes);
- for (int i = 0, length = allTypes.size(); i < length; i++) {
- IType innerType = (IType)allTypes.get(i);
- addTypeAddition(innerType, (SimpleDelta)this.changes.get(innerType));
- }
- break;
- case IJavaScriptElementDelta.REMOVED:
- addTypeRemoval(type, existingDelta);
- allTypes = new ArrayList();
- getAllTypesFromHierarchy((JavaElement)type, allTypes);
- for (int i = 0, length = allTypes.size(); i < length; i++) {
- IType innerType = (IType)allTypes.get(i);
- addTypeRemoval(innerType, (SimpleDelta)this.changes.get(innerType));
- }
- break;
- case IJavaScriptElementDelta.CHANGED:
- addTypeChange(type, newDelta.getFlags(), existingDelta);
- addAffectedChildren(newDelta);
- break;
- }
- }
-
- private void addTypeAddition(IType type, SimpleDelta existingDelta) throws JavaScriptModelException {
- if (existingDelta != null) {
- switch (existingDelta.getKind()) {
- case IJavaScriptElementDelta.REMOVED:
- // REMOVED then ADDED
- boolean hasChange = false;
- if (hasSuperTypeChange(type)) {
- existingDelta.superTypes();
- hasChange = true;
- }
- if (hasVisibilityChange(type)) {
- existingDelta.modifiers();
- hasChange = true;
- }
- if (!hasChange) {
- this.changes.remove(type);
- }
- break;
- // CHANGED then ADDED
- // or ADDED then ADDED: should not happen
- }
- } else {
- // check whether the type addition affects the hierarchy
- String typeName = type.getElementName();
- if (this.hierarchy.hasSupertype(typeName)
- || this.hierarchy.subtypesIncludeSupertypeOf(type)
- || this.hierarchy.missingTypes.contains(typeName)) {
- SimpleDelta delta = new SimpleDelta();
- delta.added();
- this.changes.put(type, delta);
- }
- }
- }
-
- private void addTypeChange(IType type, int newFlags, SimpleDelta existingDelta) throws JavaScriptModelException {
- if (existingDelta != null) {
- switch (existingDelta.getKind()) {
- case IJavaScriptElementDelta.CHANGED:
- // CHANGED then CHANGED
- int existingFlags = existingDelta.getFlags();
- boolean hasChange = false;
- if ((existingFlags & IJavaScriptElementDelta.F_SUPER_TYPES) != 0
- && hasSuperTypeChange(type)) {
- existingDelta.superTypes();
- hasChange = true;
- }
- if ((existingFlags & IJavaScriptElementDelta.F_MODIFIERS) != 0
- && hasVisibilityChange(type)) {
- existingDelta.modifiers();
- hasChange = true;
- }
- if (!hasChange) {
- // super types and visibility are back to the ones in the existing hierarchy
- this.changes.remove(type);
- }
- break;
- // ADDED then CHANGED: leave it as ADDED
- // REMOVED then CHANGED: should not happen
- }
- } else {
- // check whether the type change affects the hierarchy
- SimpleDelta typeDelta = null;
- if ((newFlags & IJavaScriptElementDelta.F_SUPER_TYPES) != 0
- && this.hierarchy.includesTypeOrSupertype(type)) {
- typeDelta = new SimpleDelta();
- typeDelta.superTypes();
- }
- if ((newFlags & IJavaScriptElementDelta.F_MODIFIERS) != 0
- && (this.hierarchy.hasSupertype(type.getElementName())
- || type.equals(this.hierarchy.focusType))) {
- if (typeDelta == null) {
- typeDelta = new SimpleDelta();
- }
- typeDelta.modifiers();
- }
- if (typeDelta != null) {
- this.changes.put(type, typeDelta);
- }
- }
- }
-
- private void addTypeRemoval(IType type, SimpleDelta existingDelta) {
- if (existingDelta != null) {
- switch (existingDelta.getKind()) {
- case IJavaScriptElementDelta.ADDED:
- // ADDED then REMOVED
- this.changes.remove(type);
- break;
- case IJavaScriptElementDelta.CHANGED:
- // CHANGED then REMOVED
- existingDelta.removed();
- break;
- // REMOVED then REMOVED: should not happen
- }
- } else {
- // check whether the type removal affects the hierarchy
- if (this.hierarchy.contains(type)) {
- SimpleDelta typeDelta = new SimpleDelta();
- typeDelta.removed();
- this.changes.put(type, typeDelta);
- }
- }
- }
-
- /*
- * Returns all types defined in the given element excluding the given element.
- */
- private void getAllTypesFromElement(IJavaScriptElement element, ArrayList allTypes) throws JavaScriptModelException {
- switch (element.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- IType[] types = ((IJavaScriptUnit)element).getTypes();
- for (int i = 0, length = types.length; i < length; i++) {
- IType type = types[i];
- allTypes.add(type);
- getAllTypesFromElement(type, allTypes);
- }
- break;
- case IJavaScriptElement.TYPE:
- types = ((IType)element).getTypes();
- for (int i = 0, length = types.length; i < length; i++) {
- IType type = types[i];
- allTypes.add(type);
- getAllTypesFromElement(type, allTypes);
- }
- break;
- case IJavaScriptElement.INITIALIZER:
- case IJavaScriptElement.FIELD:
- case IJavaScriptElement.METHOD:
- IJavaScriptElement[] children = ((IMember)element).getChildren();
- for (int i = 0, length = children.length; i < length; i++) {
- if (element.getElementType()==IJavaScriptElement.TYPE)
- {
- IType type = (IType)children[i];
- allTypes.add(type);
- getAllTypesFromElement(type, allTypes);
- }
- }
- break;
- }
- }
-
- /*
- * Returns all types in the existing hierarchy that have the given element as a parent.
- */
- private void getAllTypesFromHierarchy(JavaElement element, ArrayList allTypes) {
- switch (element.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- ArrayList types = (ArrayList)this.hierarchy.files.get(element);
- if (types != null) {
- allTypes.addAll(types);
- }
- break;
- case IJavaScriptElement.TYPE:
- case IJavaScriptElement.INITIALIZER:
- case IJavaScriptElement.FIELD:
- case IJavaScriptElement.METHOD:
- types = (ArrayList)this.hierarchy.files.get(((IMember)element).getJavaScriptUnit());
- if (types != null) {
- for (int i = 0, length = types.size(); i < length; i++) {
- IType type = (IType)types.get(i);
- if (element.isAncestorOf(type)) {
- allTypes.add(type);
- }
- }
- }
- break;
- }
- }
-
- private boolean hasSuperTypeChange(IType type) throws JavaScriptModelException {
- // check super class
- IType superclass = this.hierarchy.getSuperclass(type);
- String existingSuperclassName = superclass == null ? null : superclass.getElementName();
- String newSuperclassName = type.getSuperclassName();
- if (existingSuperclassName != null && !existingSuperclassName.equals(newSuperclassName)) {
- return true;
- }
- return false;
- }
-
- private boolean hasVisibilityChange(IType type) throws JavaScriptModelException {
- int existingFlags = this.hierarchy.getCachedFlags(type);
- int newFlags = type.getFlags();
- return existingFlags != newFlags;
- }
-
- /*
- * Whether the hierarchy needs refresh according to the changes collected so far.
- */
- public boolean needsRefresh() {
- return changes.size() != 0;
- }
-
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- Iterator iterator = this.changes.entrySet().iterator();
- while (iterator.hasNext()) {
- Map.Entry entry = (Map.Entry)iterator.next();
- buffer.append(((JavaElement)entry.getKey()).toDebugString());
- buffer.append(entry.getValue());
- if (iterator.hasNext()) {
- buffer.append('\n');
- }
- }
- return buffer.toString();
- }
-}
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
deleted file mode 100644
index abc8c2b7..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/HierarchyBinaryType.java
+++ /dev/null
@@ -1,178 +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.hierarchy;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-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.env.IBinaryField;
-import org.eclipse.wst.jsdt.internal.compiler.env.IBinaryMethod;
-import org.eclipse.wst.jsdt.internal.compiler.env.IBinaryNestedType;
-import org.eclipse.wst.jsdt.internal.compiler.env.IBinaryType;
-
-public class HierarchyBinaryType implements IBinaryType {
- private int modifiers;
- private char[] sourceName;
- private char[] name;
- private char[] enclosingTypeName;
- private char[] superclass;
- private char[] genericSignature;
-
-public HierarchyBinaryType(int modifiers, char[] qualification, char[] sourceName, char[] enclosingTypeName){
-
- this.modifiers = modifiers;
- this.sourceName = sourceName;
- if (enclosingTypeName == null){
- this.name = CharOperation.concat(qualification, sourceName, '/');
- } else {
- this.name = CharOperation.concat(qualification, '/', enclosingTypeName, '$', sourceName); //rebuild A$B name
- this.enclosingTypeName = CharOperation.concat(qualification, enclosingTypeName,'/');
- CharOperation.replace(this.enclosingTypeName, '.', '/');
- }
- CharOperation.replace(this.name, '.', '/');
-}
-/**
- * Answer the resolved name of the enclosing type in the
- * class file format as specified in section 4.2 of the Java 2 VM spec
- * or null if the receiver is a top level type.
- *
- * For example, java.lang.String is java/lang/String.
- */
-public char[] getEnclosingTypeName() {
- return this.enclosingTypeName;
-}
-/**
- * Answer the receiver's fields or null if the array is empty.
- */
-public IBinaryField[] getFields() {
- return null;
-}
-/**
- * @see org.eclipse.wst.jsdt.internal.compiler.env.IDependent#getFileName()
- */
-public char[] getFileName() {
- return null;
-}
-public char[] getGenericSignature() {
- return this.genericSignature;
-}
-/**
- * Answer the receiver's nested types or null if the array is empty.
- *
- * This nested type info is extracted from the inner class attributes.
- * Ask the name environment to find a member type using its compound name.
- */
-public IBinaryNestedType[] getMemberTypes() {
- return null;
-}
-/**
- * Answer the receiver's methods or null if the array is empty.
- */
-public IBinaryMethod[] getMethods() {
- return null;
-}
-/**
- * Answer an int whose bits are set according the access constants
- * defined by the VM spec.
- */
-public int getModifiers() {
- return this.modifiers;
-}
-/**
- * Answer the resolved name of the type in the
- * class file format as specified in section 4.2 of the Java 2 VM spec.
- *
- * For example, java.lang.String is java/lang/String.
- */
-public char[] getName() {
- return this.name;
-}
-
-public char[] getSourceName() {
- return this.sourceName;
-}
-
-/**
- * Answer the resolved name of the receiver's superclass in the
- * class file format as specified in section 4.2 of the Java 2 VM spec
- * or null if it does not have one.
- *
- * For example, java.lang.String is java/lang/String.
- */
-public char[] getSuperclassName() {
- return this.superclass;
-}
-public boolean isAnonymous() {
- return false; // index did not record this information (since unused for hierarchies)
-}
-
-/**
- * Answer whether the receiver contains the resolved binary form
- * or the unresolved source form of the type.
- */
-public boolean isBinaryType() {
- return true;
-}
-public boolean isLocal() {
- return false; // index did not record this information (since unused for hierarchies)
-}
-public boolean isMember() {
- return false; // index did not record this information (since unused for hierarchies)
-}
-
-public void recordSuperType(char[] superTypeName, char[] superQualification){
-
- // index encoding of p.A$B was B/p.A$, rebuild the proper name
- if (superQualification != null){
- int length = superQualification.length;
- if (superQualification[length-1] == '$'){
- char[] enclosingSuperName = CharOperation.lastSegment(superQualification, '.');
- superTypeName = CharOperation.concat(enclosingSuperName, superTypeName);
- superQualification = CharOperation.subarray(superQualification, 0, length - enclosingSuperName.length - 1);
- }
- }
-
- char[] encodedName = CharOperation.concat(superQualification, superTypeName, '/');
- CharOperation.replace(encodedName, '.', '/');
- this.superclass = encodedName;
-
-}
-public String toString() {
- StringBuffer buffer = new StringBuffer();
- if (this.modifiers == ClassFileConstants.AccPublic) {
- buffer.append("public "); //$NON-NLS-1$
- }
- switch (TypeDeclaration.kind(this.modifiers)) {
- case TypeDeclaration.CLASS_DECL :
- buffer.append("class "); //$NON-NLS-1$
- break;
- }
- if (this.name != null) {
- buffer.append(this.name);
- }
- if (this.superclass != null) {
- buffer.append("\n extends "); //$NON-NLS-1$
- buffer.append(this.superclass);
- }
- return buffer.toString();
-}
-
-/**
- * @see org.eclipse.wst.jsdt.internal.compiler.env.IBinaryType
- */
-public char[] sourceFileName() {
- return null;
-}
-// TODO (jerome) please verify that we don't need the tagbits for the receiver
-public long getTagBits() {
- return 0;
-}
-}
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
deleted file mode 100644
index b0b517da..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/HierarchyBuilder.java
+++ /dev/null
@@ -1,257 +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.hierarchy;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.CoreException;
-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.internal.compiler.ast.TypeDeclaration;
-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.ISourceType;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding;
-import org.eclipse.wst.jsdt.internal.compiler.problem.DefaultProblemFactory;
-import org.eclipse.wst.jsdt.internal.core.ClassFile;
-import org.eclipse.wst.jsdt.internal.core.JavaElement;
-import org.eclipse.wst.jsdt.internal.core.JavaProject;
-import org.eclipse.wst.jsdt.internal.core.NameLookup;
-import org.eclipse.wst.jsdt.internal.core.Openable;
-import org.eclipse.wst.jsdt.internal.core.ResolvedBinaryType;
-import org.eclipse.wst.jsdt.internal.core.SearchableEnvironment;
-import org.eclipse.wst.jsdt.internal.core.SourceTypeElementInfo;
-import org.eclipse.wst.jsdt.internal.core.util.ResourceCompilationUnit;
-
-public abstract class HierarchyBuilder {
- /**
- * The hierarchy being built.
- */
- protected TypeHierarchy hierarchy;
- /**
- * @see NameLookup
- */
- protected NameLookup nameLookup;
- /**
- * The resolver used to resolve type hierarchies
- * @see HierarchyResolver
- */
- protected HierarchyResolver hierarchyResolver;
- /**
- * A temporary cache of infos 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 infoToHandle;
- /*
- * The dot-separated fully qualified name of the focus type, or null of none.
- */
- protected String focusQualifiedName;
-
- public HierarchyBuilder(TypeHierarchy hierarchy) throws JavaScriptModelException {
-
- this.hierarchy = hierarchy;
- JavaProject project = (JavaProject) hierarchy.javaProject();
-
- IType focusType = hierarchy.getType();
- org.eclipse.wst.jsdt.core.IJavaScriptUnit unitToLookInside = focusType == null ? null : focusType.getJavaScriptUnit();
- org.eclipse.wst.jsdt.core.IJavaScriptUnit[] workingCopies = this.hierarchy.workingCopies;
- org.eclipse.wst.jsdt.core.IJavaScriptUnit[] unitsToLookInside;
- ICompilationUnit mainFile=null;
- 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);
- }
- mainFile=(ICompilationUnit)unitToLookInside;
- } else {
- unitsToLookInside = workingCopies;
- if (workingCopies!=null && workingCopies.length>0)
- mainFile=(ICompilationUnit)workingCopies[0];
- }
- if (project != null) {
- SearchableEnvironment searchableEnvironment = project.newSearchableNameEnvironment(unitsToLookInside);
- if (mainFile!=null)
- searchableEnvironment.setCompilationUnit(mainFile);
- this.nameLookup = searchableEnvironment.nameLookup;
- this.hierarchyResolver =
- new HierarchyResolver(
- searchableEnvironment,
- project.getOptions(true),
- this,
- new DefaultProblemFactory());
- }
- this.infoToHandle = new HashMap(5);
- this.focusQualifiedName = focusType == null ? null : focusType.getFullyQualifiedName();
- }
-
- public abstract void build(boolean computeSubtypes)
- throws JavaScriptModelException, CoreException;
- /**
- * Configure this type hierarchy by computing the supertypes only.
- */
- protected void buildSupertypes() {
- IType focusType = this.getType();
- if (focusType == null)
- return;
- // get generic type from focus type
- IGenericType type;
- try {
- type = (IGenericType) ((JavaElement) focusType).getElementInfo();
- } catch (JavaScriptModelException e) {
- // if the focus type is not present, or if cannot get workbench path
- // we cannot create the hierarchy
- return;
- }
- //NB: no need to set focus type on hierarchy resolver since no other type is injected
- // in the hierarchy resolver, thus there is no need to check that a type is
- // a sub or super type of the focus type.
- this.hierarchyResolver.resolve(type);
-
- // Add focus if not already in (case of a type with no explicit super type)
- if (!this.hierarchy.contains(focusType)) {
- this.hierarchy.addRootClass(focusType);
- }
- }
- /**
- * Connect the supplied type to its superclass.
- * The superclass are the identical binary or source types as
- * supplied by the name environment.
- */
- public void connect(
- IGenericType type,
- IType typeHandle,
- IType superclassHandle) {
-
- /*
- * Temporary workaround for 1G2O5WK: ITPJCORE:WINNT - NullPointerException when selecting "Show in Type Hierarchy" for a inner class
- */
- if (typeHandle == null)
- return;
- if (TypeHierarchy.DEBUG) {
- System.out.println(
- "Connecting: " + ((JavaElement) typeHandle).toStringWithAncestors()); //$NON-NLS-1$
- System.out.println(
- " to superclass: " //$NON-NLS-1$
- + (superclassHandle == null
- ? "<None>" //$NON-NLS-1$
- : ((JavaElement) superclassHandle).toStringWithAncestors()));
- }
- // now do the caching
- switch (TypeDeclaration.kind(type.getModifiers())) {
- case TypeDeclaration.CLASS_DECL :
- if (superclassHandle == null) {
- this.hierarchy.addRootClass(typeHandle);
- } else {
- this.hierarchy.cacheSuperclass(typeHandle, superclassHandle);
- }
- break;
- }
-
- // record flags
- this.hierarchy.cacheFlags(typeHandle, type.getModifiers());
- }
- /**
- * Returns a handle for the given generic type or null if not found.
- */
- protected IType getHandle(IGenericType genericType, ReferenceBinding binding) {
- if (genericType == null)
- return null;
- if (genericType instanceof HierarchyType) {
- IType handle = (IType)this.infoToHandle.get(genericType);
- if (handle == null) {
- handle = ((HierarchyType)genericType).typeHandle;
- handle = (IType) ((JavaElement) handle).resolved(binding);
- this.infoToHandle.put(genericType, handle);
- }
- return handle;
- } else if (genericType.isBinaryType()) {
- ClassFile classFile = (ClassFile) this.infoToHandle.get(genericType);
- // if it's null, it's from outside the region, so do lookup
- if (classFile == null) {
- IType handle = lookupBinaryHandle((ISourceType) genericType);
- if (handle == null)
- return null;
- // case of an anonymous type (see 1G2O5WK: ITPJCORE:WINNT - NullPointerException when selecting "Show in Type Hierarchy" for a inner class)
- // optimization: remember the handle for next call (case of java.io.Serializable that a lot of classes implement)
- 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 null;
- }
- protected IType getType() {
- return this.hierarchy.getType();
- }
- /**
- * Looks up and returns a handle for the given binary info.
- */
- protected IType lookupBinaryHandle(ISourceType typeInfo) {
- int flag;
- String qualifiedName;
- switch (TypeDeclaration.kind(typeInfo.getModifiers())) {
- case TypeDeclaration.CLASS_DECL :
- flag = NameLookup.ACCEPT_CLASSES;
- break;
- default:
- //case IGenericType.ANNOTATION :
- flag = NameLookup.ACCEPT_ANNOTATIONS;
- break;
- }
- char[] bName = typeInfo.getName();
- qualifiedName = new String(ClassFile.translatedName(bName));
- if (qualifiedName.equals(this.focusQualifiedName)) return getType();
- NameLookup.Answer answer = this.nameLookup.findType(qualifiedName,
- false,
- flag,
- true/* consider secondary types */,
- false/* do NOT wait for indexes */,
- false/*don't check restrictions*/,
- null);
- return answer == null || answer.type == null || !answer.type.isBinary() ? null : answer.type;
-
- }
- protected void worked(IProgressMonitor monitor, int work) {
- if (monitor != null) {
- if (monitor.isCanceled()) {
- throw new OperationCanceledException();
- } else {
- monitor.worked(work);
- }
- }
- }
-/**
- * Create an IJavaScriptUnit info from the given compilation unit on disk.
- */
-protected ICompilationUnit createCompilationUnitFromPath(Openable handle, IFile file) {
- final char[] elementName = handle.getElementName().toCharArray();
- return new ResourceCompilationUnit(file, file.getLocationURI()) {
- public char[] getFileName() {
- return super.file.getFullPath().toString().toCharArray();
- }
- };
-}
-
-
-}
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
deleted file mode 100644
index bec60ac9..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/HierarchyResolver.java
+++ /dev/null
@@ -1,851 +0,0 @@
-/*******************************************************************************
- * 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<parsedUnit.numberInferredTypes;i++) {
- InferredType inferredType = parsedUnit.inferredTypes[i];
-
- if (inferredType.isDefinition && !inferredType.isEmptyGlobal()) {
- IType typeHandle = (cu != null) ? cu.getType(new String(
- inferredType.getName())) : classFile
- .getType(new String(inferredType.getName()));
- rememberInferredType(inferredType, typeHandle,
- inferredType.binding);
- }
- }
-// if (includeLocalTypes && parsedUnit.localTypes != null) {
-// HandleFactory factory = new HandleFactory();
-// HashSet existingElements = new HashSet(parsedUnit.localTypeCount);
-// HashMap knownScopes = new HashMap(parsedUnit.localTypeCount);
-// for (int i = 0; i < parsedUnit.localTypeCount; i++) {
-// LocalTypeBinding localType = parsedUnit.localTypes[i];
-// ClassScope classScope = localType.scope;
-// TypeDeclaration typeDecl = classScope.referenceType();
-// IType typeHandle = (IType)factory.createElement(classScope, cu, existingElements, knownScopes);
-// rememberWithMemberTypes(typeDecl, typeHandle);
-// }
-// }
-}
-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.
- */
-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/*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;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/HierarchyType.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/HierarchyType.java
deleted file mode 100644
index 93b2c1e2..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/HierarchyType.java
+++ /dev/null
@@ -1,60 +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.hierarchy;
-
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.internal.compiler.env.IGenericType;
-
-/**
- *
- * Partial implementation of an IGenericType used to
- * answer hierarchies.
- */
-public class HierarchyType implements IGenericType {
-
- public IType typeHandle;
- public char[] name;
- public int modifiers;
- public char[] superclassName;
-
-public HierarchyType(
- IType typeHandle,
- char[] name,
- int modifiers,
- char[] superclassName) {
-
- this.typeHandle = typeHandle;
- this.name = name;
- this.modifiers = modifiers;
- this.superclassName = superclassName;
-}
-/**
- * @see org.eclipse.wst.jsdt.internal.compiler.env.IDependent#getFileName()
- */
-public char[] getFileName() {
- return this.typeHandle.getJavaScriptUnit().getElementName().toCharArray();
-}
-
-/**
- * Answer an int whose bits are set according the access constants
- * defined by the VM spec.
- */
-public int getModifiers() {
- return this.modifiers;
-}
-/**
- * Answer whether the receiver contains the resolved binary form
- * or the unresolved source form of the type.
- */
-public boolean isBinaryType() {
- return false;
-}
-}
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
deleted file mode 100644
index 96a29687..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/IndexBasedHierarchyBuilder.java
+++ /dev/null
@@ -1,530 +0,0 @@
-/*******************************************************************************
- * 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;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-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.SubProgressMonitor;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-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.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.SearchParticipant;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-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;
-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.SuffixConstants;
-import org.eclipse.wst.jsdt.internal.core.IPathRequestor;
-import org.eclipse.wst.jsdt.internal.core.JavaModelManager;
-import org.eclipse.wst.jsdt.internal.core.JavaProject;
-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.IndexQueryRequestor;
-import org.eclipse.wst.jsdt.internal.core.search.JavaSearchParticipant;
-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.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
- /**
- * 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;
-
- /**
- * The scope this hierarchy builder should restrain results to.
- */
- protected IJavaScriptSearchScope scope;
-
- /**
- * Cache used to record binaries recreated from index matches
- */
- protected Map binariesFromIndexMatches;
-
- /**
- * Collection used to queue subtype index queries
- */
- static class Queue {
- 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){
- this.end -= this.start;
- 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
-
- char[] name = this.names[this.start++];
- if (this.start > this.end){
- this.start = 0;
- this.end = -1;
- }
- return name;
- }
- public String toString(){
- StringBuffer buffer = new StringBuffer("Queue:\n"); //$NON-NLS-1$
- 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;
- }
- 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();
- }
- } 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);
- }
- 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);
- }
- } 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;
- }
- }
- } 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;
- }
- }
- 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;
- }
- 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};
- }
- 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];
-
- // 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;
-
- 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;
- }
- }
-
- // 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());
- }
- }
- 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);
- }
- } 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;
-}
-
-/**
- * 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);
- }
- }
- }
- 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;
-}
-
-/**
- * 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();
- }
- }
- binaryType = new HierarchyBinaryType(record.modifiers, record.pkgName, typeName, enclosingTypeName);
- binariesFromIndexMatches.put(documentPath, binaryType);
- }
- 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);
- }
- public boolean isCanceled() {
- return progressMonitor.isCanceled();
- }
- });
- if (progressMonitor != null && ++ticks <= MAXTICKS)
- progressMonitor.worked(1);
-
- // in case, we search all subtypes, no need to search further
- if (currentTypeName == null) break;
- }
- } finally {
- job.finished();
- }
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/RegionBasedHierarchyBuilder.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/RegionBasedHierarchyBuilder.java
deleted file mode 100644
index 17cf92cb..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/RegionBasedHierarchyBuilder.java
+++ /dev/null
@@ -1,223 +0,0 @@
-/*******************************************************************************
- * 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.hierarchy;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-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.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.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.core.JavaModelManager;
-import org.eclipse.wst.jsdt.internal.core.JavaProject;
-import org.eclipse.wst.jsdt.internal.core.Openable;
-import org.eclipse.wst.jsdt.internal.core.SearchableEnvironment;
-
-public class RegionBasedHierarchyBuilder extends HierarchyBuilder {
-
- public RegionBasedHierarchyBuilder(TypeHierarchy hierarchy)
- throws JavaScriptModelException {
-
- super(hierarchy);
- }
-
-public void build(boolean computeSubtypes) {
-
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- try {
- // optimize access to zip files while building hierarchy
- manager.cacheZipFiles();
-
- if (this.hierarchy.focusType == null || computeSubtypes) {
- IProgressMonitor typeInRegionMonitor =
- this.hierarchy.progressMonitor == null ?
- null :
- new SubProgressMonitor(this.hierarchy.progressMonitor, 30);
- HashMap allOpenablesInRegion = determineOpenablesInRegion(typeInRegionMonitor);
- this.hierarchy.initialize(allOpenablesInRegion.size());
- IProgressMonitor buildMonitor =
- this.hierarchy.progressMonitor == null ?
- null :
- new SubProgressMonitor(this.hierarchy.progressMonitor, 70);
- createTypeHierarchyBasedOnRegion(allOpenablesInRegion, buildMonitor);
- ((RegionBasedTypeHierarchy)this.hierarchy).pruneDeadBranches();
- } else {
- this.hierarchy.initialize(1);
- this.buildSupertypes();
- }
- } finally {
- manager.flushZipFiles();
- }
-}
-/**
- * Configure this type hierarchy that is based on a region.
- */
-private void createTypeHierarchyBasedOnRegion(HashMap allOpenablesInRegion, IProgressMonitor monitor) {
-
- try {
- int size = allOpenablesInRegion.size();
- if (monitor != null) monitor.beginTask("", size * 2/* 1 for build binding, 1 for connect hierarchy*/); //$NON-NLS-1$
- this.infoToHandle = new HashMap(size);
- Iterator javaProjects = allOpenablesInRegion.entrySet().iterator();
- while (javaProjects.hasNext()) {
- Map.Entry entry = (Map.Entry) javaProjects.next();
- JavaProject project = (JavaProject) entry.getKey();
- ArrayList allOpenables = (ArrayList) entry.getValue();
- Openable[] openables = new Openable[allOpenables.size()];
- allOpenables.toArray(openables);
-
- try {
- // resolve
- SearchableEnvironment searchableEnvironment = project.newSearchableNameEnvironment(this.hierarchy.workingCopies);
- this.nameLookup = searchableEnvironment.nameLookup;
- this.hierarchyResolver.resolve(openables, null, monitor);
- } catch (JavaScriptModelException e) {
- // project doesn't exit: ignore
- }
- }
- } finally {
- if (monitor != null) monitor.done();
- }
-}
-
- /**
- * Returns all of the openables defined in the region of this type hierarchy.
- * Returns a map from IJavaScriptProject to ArrayList of Openable
- */
- private HashMap determineOpenablesInRegion(IProgressMonitor monitor) {
-
- try {
- HashMap allOpenables = new HashMap();
- IJavaScriptElement[] roots =
- ((RegionBasedTypeHierarchy) this.hierarchy).region.getElements();
- int length = roots.length;
- if (monitor != null) monitor.beginTask("", length); //$NON-NLS-1$
- for (int i = 0; i <length; i++) {
- IJavaScriptElement root = roots[i];
- IJavaScriptProject javaProject = root.getJavaScriptProject();
- ArrayList openables = (ArrayList) allOpenables.get(javaProject);
- if (openables == null) {
- openables = new ArrayList();
- allOpenables.put(javaProject, openables);
- }
- switch (root.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_PROJECT :
- injectAllOpenablesForJavaProject((IJavaScriptProject) root, openables);
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT :
- injectAllOpenablesForPackageFragmentRoot((IPackageFragmentRoot) root, openables);
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT :
- injectAllOpenablesForPackageFragment((IPackageFragment) root, openables);
- break;
- case IJavaScriptElement.CLASS_FILE :
- case IJavaScriptElement.JAVASCRIPT_UNIT :
- openables.add(root);
- break;
- case IJavaScriptElement.TYPE :
- IType type = (IType)root;
- if (type.isBinary()) {
- openables.add(type.getClassFile());
- } else {
- openables.add(type.getJavaScriptUnit());
- }
- break;
- default :
- break;
- }
- worked(monitor, 1);
- }
- return allOpenables;
- } finally {
- if (monitor != null) monitor.done();
- }
- }
-
- /**
- * Adds all of the openables defined within this java project to the
- * list.
- */
- private void injectAllOpenablesForJavaProject(
- IJavaScriptProject project,
- ArrayList openables) {
- try {
- IPackageFragmentRoot[] devPathRoots =
- ((JavaProject) project).getPackageFragmentRoots();
- if (devPathRoots == null) {
- return;
- }
- for (int j = 0; j < devPathRoots.length; j++) {
- IPackageFragmentRoot root = devPathRoots[j];
- injectAllOpenablesForPackageFragmentRoot(root, openables);
- }
- } catch (JavaScriptModelException e) {
- // ignore
- }
- }
-
- /**
- * Adds all of the openables defined within this package fragment to the
- * list.
- */
- private void injectAllOpenablesForPackageFragment(
- IPackageFragment packFrag,
- ArrayList openables) {
-
- try {
- IPackageFragmentRoot root = (IPackageFragmentRoot) packFrag.getParent();
- int kind = root.getKind();
- if (kind != 0) {
- boolean isSourcePackageFragment = (kind == IPackageFragmentRoot.K_SOURCE);
- if (isSourcePackageFragment) {
- IJavaScriptUnit[] cus = packFrag.getJavaScriptUnits();
- for (int i = 0, length = cus.length; i < length; i++) {
- openables.add(cus[i]);
- }
- } else {
- IClassFile[] classFiles = packFrag.getClassFiles();
- for (int i = 0, length = classFiles.length; i < length; i++) {
- openables.add(classFiles[i]);
- }
- }
- }
- } catch (JavaScriptModelException e) {
- // ignore
- }
- }
-
- /**
- * Adds all of the openables defined within this package fragment root to the
- * list.
- */
- private void injectAllOpenablesForPackageFragmentRoot(
- IPackageFragmentRoot root,
- ArrayList openables) {
- try {
- IJavaScriptElement[] packFrags = root.getChildren();
- for (int k = 0; k < packFrags.length; k++) {
- IPackageFragment packFrag = (IPackageFragment) packFrags[k];
- injectAllOpenablesForPackageFragment(packFrag, openables);
- }
- } catch (JavaScriptModelException e) {
- return;
- }
- }
-
-}
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
deleted file mode 100644
index 8400ba9a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/RegionBasedTypeHierarchy.java
+++ /dev/null
@@ -1,166 +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.hierarchy;
-
-import java.util.ArrayList;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptElementDelta;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IOpenable;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IRegion;
-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.internal.core.CompilationUnit;
-import org.eclipse.wst.jsdt.internal.core.JavaElement;
-import org.eclipse.wst.jsdt.internal.core.Openable;
-import org.eclipse.wst.jsdt.internal.core.Region;
-import org.eclipse.wst.jsdt.internal.core.TypeVector;
-
-public class RegionBasedTypeHierarchy extends TypeHierarchy {
- /**
- * The region of types for which to build the hierarchy
- */
- protected IRegion region;
-
-/**
- * Creates a TypeHierarchy on the types in the specified region,
- * considering first the given working copies,
- * using the projects in the given region for a name lookup context. If a specific
- * type is also specified, the type hierarchy is pruned to only
- * contain the branch including the specified type.
- */
-public RegionBasedTypeHierarchy(IRegion region, IJavaScriptUnit[] workingCopies, IType type, boolean computeSubtypes) {
- super(type, workingCopies, (IJavaScriptSearchScope)null, computeSubtypes);
-
- Region newRegion = new Region() {
- public void add(IJavaScriptElement element) {
- if (!contains(element)) {
- //"new" element added to region
- removeAllChildren(element);
- fRootElements.add(element);
- if (element.getElementType() == IJavaScriptElement.JAVASCRIPT_PROJECT) {
- // add jar roots as well so that jars don't rely on their parent to know
- // if they are contained in the region
- // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=146615)
- try {
- IPackageFragmentRoot[] roots = ((IJavaScriptProject) element).getPackageFragmentRoots();
- for (int i = 0, length = roots.length; i < length; i++) {
- if (roots[i].isArchive() && !fRootElements.contains(roots[i]))
- fRootElements.add(roots[i]);
- }
- } catch (JavaScriptModelException e) {
- // project doesn't exist
- }
- }
- fRootElements.trimToSize();
- }
- }
- };
- IJavaScriptElement[] elements = region.getElements();
- for (int i = 0, length = elements.length; i < length; i++) {
- newRegion.add(elements[i]);
-
- }
- this.region = newRegion;
- if (elements.length > 0)
- this.project = elements[0].getJavaScriptProject();
-}
-/*
- * @see TypeHierarchy#initializeRegions
- */
-protected void initializeRegions() {
- super.initializeRegions();
- IJavaScriptElement[] roots = this.region.getElements();
- for (int i = 0; i < roots.length; i++) {
- IJavaScriptElement root = roots[i];
- if (root instanceof IOpenable) {
- this.files.put(root, new ArrayList());
- } else {
- Openable o = (Openable) ((JavaElement) root).getOpenableParent();
- if (o != null) {
- this.files.put(o, new ArrayList());
- }
- }
- checkCanceled();
- }
-}
-/**
- * Compute this type hierarchy.
- */
-protected void compute() throws JavaScriptModelException, CoreException {
- HierarchyBuilder builder = new RegionBasedHierarchyBuilder(this);
- builder.build(this.computeSubtypes);
-}
-protected boolean isAffectedByOpenable(IJavaScriptElementDelta delta, IJavaScriptElement element) {
- // change to working copy
- if (element instanceof CompilationUnit && ((CompilationUnit)element).isWorkingCopy()) {
- return super.isAffectedByOpenable(delta, element);
- }
-
- // if no focus, hierarchy is affected if the element is part of the region
- if (this.focusType == null) {
- return this.region.contains(element);
- } else {
- return super.isAffectedByOpenable(delta, element);
- }
-}
-/**
- * Returns the java project this hierarchy was created in.
- */
-public IJavaScriptProject javaProject() {
- return this.project;
-}
-public void pruneDeadBranches() {
- pruneDeadBranches(getRootClasses());
-}
-/*
- * Returns whether all subtypes of the given type have been pruned.
- */
-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);
- return (subtypes == null || subtypes.size == 0);
-}
-private void pruneDeadBranches(IType[] types) {
- for (int i = 0, length = types.length; i < length; i++) {
- IType type = types[i];
- if (pruneDeadBranches(type) && !this.region.contains(type)) {
- removeType(type);
- }
- }
-}
-/**
- * Removes all the subtypes of the given type from the type hierarchy,
- * removes its superclass entry and removes the references from its super types.
- */
-protected void removeType(IType type) {
- IType[] subtypes = this.getSubclasses(type);
- this.typeToSubtypes.remove(type);
- if (subtypes != null) {
- for (int i= 0; i < subtypes.length; i++) {
- this.removeType(subtypes[i]);
- }
- }
- IType superclass = (IType)this.classToSuperclass.remove(type);
- if (superclass != null) {
- TypeVector types = (TypeVector)this.typeToSubtypes.get(superclass);
- 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
deleted file mode 100644
index e95bc9e2..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/TypeHierarchy.java
+++ /dev/null
@@ -1,1220 +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.hierarchy;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.ISafeRunnable;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SafeRunner;
-import org.eclipse.wst.jsdt.core.ElementChangedEvent;
-import org.eclipse.wst.jsdt.core.IElementChangedListener;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptElementDelta;
-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.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.ITypeHierarchyChangedListener;
-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.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-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.JavaModelStatus;
-import org.eclipse.wst.jsdt.internal.core.JavaProject;
-import org.eclipse.wst.jsdt.internal.core.Openable;
-import org.eclipse.wst.jsdt.internal.core.PackageFragment;
-import org.eclipse.wst.jsdt.internal.core.Region;
-import org.eclipse.wst.jsdt.internal.core.TypeVector;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * @see ITypeHierarchy
- */
-public class TypeHierarchy implements ITypeHierarchy, IElementChangedListener {
-
- public static boolean DEBUG = false;
-
- static final byte VERSION = 0x0000;
- // SEPARATOR
- static final byte SEPARATOR1 = '\n';
- static final byte SEPARATOR2 = ',';
- static final byte SEPARATOR3 = '>';
- static final byte SEPARATOR4 = '\r';
- // general info
- static final byte COMPUTE_SUBTYPES = 0x0001;
-
- // type info
- static final byte CLASS = 0x0000;
- static final byte COMPUTED_FOR = 0x0002;
- static final byte ROOT = 0x0004;
-
- // cst
- static final byte[] NO_FLAGS = new byte[]{};
- 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.
- */
- protected IJavaScriptProject project;
- /**
- * The type the hierarchy was specifically computed for,
- * possibly null.
- */
- protected IType focusType;
-
- /*
- * The working copies that take precedence over original compilation units
- */
- protected IJavaScriptUnit[] workingCopies;
-
- protected Map classToSuperclass;
- protected Map typeToSubtypes;
- protected Map typeFlags;
- protected TypeVector rootClasses = new TypeVector();
- public ArrayList missingTypes = new ArrayList(4);
-
- protected static final IType[] NO_TYPE = new IType[0];
-
- /**
- * The progress monitor to report work completed too.
- */
- protected IProgressMonitor progressMonitor = null;
-
- /**
- * Change listeners - null if no one is listening.
- */
- 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.
- */
- protected Region packageRegion = null;
-
- /**
- * A region describing the projects considered by this
- * hierarchy. Null if not activated.
- */
- protected Region projectRegion = null;
-
- /**
- * Whether this hierarchy should contains subtypes.
- */
- protected boolean computeSubtypes;
-
- /**
- * The scope this hierarchy should restrain itsef in.
- */
- 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);
- }
- types.add(type);
- }
- IPackageFragment pkg = type.getPackageFragment();
- this.packageRegion.add(pkg);
- IJavaScriptProject declaringProject = type.getJavaScriptProject();
- if (declaringProject != null) {
- this.projectRegion.add(declaringProject);
- }
- 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);
- }
- 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();
- }
-
- // 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);
- }
-}
-private static Integer bytesToFlags(byte[] bytes){
- if(bytes != null && bytes.length > 0) {
- return new Integer(new String(bytes));
- } else {
- return null;
- }
-}
-/**
- * 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();
- }
-}
-/**
- * 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;
- }
-
- // root classes
- if (this.rootClasses.contains(type)) return true;
-
- 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;
-
- if (isAffected(event.getDelta())) {
- this.needsRefresh = true;
- fireChange();
- }
-}
-/**
- * @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;
- }
- 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);
- }
- });
- }
-}
-private static byte[] flagsToBytes(Integer flags){
- if(flags != null) {
- return flags.toString().getBytes();
- } else {
- return NO_FLAGS;
- }
-}
-/**
- * @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 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);
- }
- }
-}
-/**
- * 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);
- }
- 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();
- }
- 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;
- }
- 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};
- }
- 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;
- }
- 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;
-}
-
-/**
- * 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;
- }
- }
- 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;
- }
- } 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;
-}
-/**
- * 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;
-}
-/**
- * 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;
-}
-/**
- * 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)) {
- return true;
- }
- }
- return false;
- case IJavaScriptElementDelta.CHANGED :
- return isAffectedByChildren(delta);
- }
- 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);
- }
- 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) {
- return true;
- }
- } catch (JavaScriptModelException e) {
- // igmore this project
- }
- }
- }
- }
- 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;
- }
- }
- 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);
- }
- 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) {
- 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;
-}
-/**
- * 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);
- }
- bytes[length++] = b;
- }
- if(b == -1) {
- throw new JavaScriptModelException(new JavaModelStatus(IStatus.ERROR));
- }
- 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;
-
- 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;
- }
-
- 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();
- }
-
- // 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 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(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);
- }
- }
-
- // 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();
-
- typeHierarchy.cacheSuperclass(
- types[subClass],
- types[superClass]);
- }
-
- if(b == -1) {
- throw new JavaScriptModelException(new JavaModelStatus(IStatus.ERROR));
- }
- return typeHierarchy;
- } catch(IOException e){
- throw new JavaScriptModelException(e, IJavaScriptModelStatusConstants.IO_EXCEPTION);
- }
-}
-/**
- * Returns <code>true</code> 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);
- }
- 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;
-
- 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());
- }
- } catch (JavaScriptModelException e) {
- throw e;
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- } finally {
- if (monitor != null) {
- monitor.done();
- }
- this.progressMonitor = null;
- }
-}
-
-/**
- * @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);
- }
- 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 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 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);
-
- // 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);
- }
- 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);
- }
-}
-/**
- * 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;
-}
-/**
- * @see ITypeHierarchy
- */
-public String toString() {
- StringBuffer buffer = new StringBuffer();
- buffer.append("Focus: "); //$NON-NLS-1$
- buffer.append(this.focusType == null ? "<NONE>" : ((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);
- }
- }
- 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 {
- buffer.append("(Hierarchy became stale)"); //$NON-NLS-1$
- }
- 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$
- }
- 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;
- }
- }
- return false;
-}
-/**
- * @see IProgressMonitor
- */
-protected void worked(int work) {
- if (this.progressMonitor != null) {
- this.progressMonitor.worked(work);
- checkCanceled();
- }
-}
-}
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
deleted file mode 100644
index 46c5a832..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/index/DiskIndex.java
+++ /dev/null
@@ -1,1263 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.index;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.RandomAccessFile;
-import java.io.UTFDataFormatException;
-
-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;
-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.util.Messages;
-import org.eclipse.wst.jsdt.internal.core.util.SimpleWordSet;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-public class DiskIndex {
-
-File indexFile;
-
-private int headerInfoOffset;
-private int numberOfChunks;
-private int sizeOfLastChunk;
-private int[] chunkOffsets;
-private int documentReferenceSize; // 1, 2 or more bytes... depends on # of document names
-private int startOfCategoryTables;
-private HashtableOfIntValues categoryOffsets, categoryEnds;
-
-private 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 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;
-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$
-private static final char[] SIGNATURE_CHARS = SIGNATURE.toCharArray();
-public static boolean DEBUG = false;
-
-private static final int RE_INDEXED = -1;
-private static final int DELETED = -2;
-
-private static final int CHUNK_SIZE = 100;
-
-private static final SimpleSetOfCharArray INTERNED_CATEGORY_NAMES = new SimpleSetOfCharArray(20);
-
-static class IntList {
-
-int size;
-int[] elements;
-
-IntList(int[] elements) {
- this.elements = elements;
- this.size = elements.length;
-}
-void add(int newElement) {
- if (this.size == this.elements.length) {
- int newSize = this.size * 3;
- if (newSize < 7) newSize = 7;
- System.arraycopy(this.elements, 0, this.elements = new int[newSize], 0, this.size);
- }
- this.elements[this.size++] = newElement;
-}
-int[] asArray() {
- int[] result = new int[this.size];
- System.arraycopy(this.elements, 0, result, 0, this.size);
- return result;
-}
-}
-
-
-DiskIndex(String fileName) {
- if (fileName == null)
- throw new java.lang.IllegalArgumentException();
- this.indexFile = new File(fileName);
-
- // clear cached items
- this.headerInfoOffset = -1;
- this.numberOfChunks = -1;
- this.sizeOfLastChunk = -1;
- this.chunkOffsets = null;
- this.documentReferenceSize = -1;
- this.cacheUserCount = -1;
- this.cachedChunks = null;
- this.categoryTables = null;
- this.cachedCategoryName = null;
- this.categoryOffsets = null;
- this.categoryEnds = null;
-}
-SimpleSet addDocumentNames(String substring, MemoryIndex memoryIndex) throws IOException {
- // must skip over documents which have been added/changed/deleted in the memory index
- String[] docNames = readAllDocumentNames();
- SimpleSet results = new SimpleSet(docNames.length);
- if (substring == null) {
- if (memoryIndex == null) {
- for (int i = 0, l = docNames.length; i < l; i++)
- results.add(docNames[i]);
- } else {
- SimpleLookupTable docsToRefs = memoryIndex.docsToReferences;
- for (int i = 0, l = docNames.length; i < l; i++) {
- String docName = docNames[i];
- if (!docsToRefs.containsKey(docName))
- results.add(docName);
- }
- }
- } else {
- if (memoryIndex == null) {
- for (int i = 0, l = docNames.length; i < l; i++)
- if (docNames[i].startsWith(substring, 0))
- results.add(docNames[i]);
- } else {
- SimpleLookupTable docsToRefs = memoryIndex.docsToReferences;
- for (int i = 0, l = docNames.length; i < l; i++) {
- String docName = docNames[i];
- if (docName.startsWith(substring, 0) && !docsToRefs.containsKey(docName))
- results.add(docName);
- }
- }
- }
- return results;
-}
-private HashtableOfObject addQueryResult(HashtableOfObject results, char[] word, HashtableOfObject wordsToDocNumbers, MemoryIndex memoryIndex) throws IOException {
- // must skip over documents which have been added/changed/deleted in the memory index
- if (results == null)
- results = new HashtableOfObject(13);
- EntryResult result = (EntryResult) results.get(word);
- if (memoryIndex == null) {
- if (result == null)
- results.put(word, new EntryResult(word, wordsToDocNumbers));
- else
- result.addDocumentTable(wordsToDocNumbers);
- } else {
- SimpleLookupTable docsToRefs = memoryIndex.docsToReferences;
- if (result == null) result = new EntryResult(word, null);
- int[] docNumbers = readDocumentNumbers(wordsToDocNumbers.get(word));
- for (int i = 0, l = docNumbers.length; i < l; i++) {
- String docName = readDocumentName(docNumbers[i]);
- if (!docsToRefs.containsKey(docName))
- result.addDocumentName(docName);
- }
- if (!result.isEmpty())
- results.put(word, result);
- }
- return results;
-}
-HashtableOfObject addQueryResults(char[][] categories, char[] key, int matchRule, MemoryIndex memoryIndex) throws IOException {
- // assumes sender has called startQuery() & will call stopQuery() when finished
- if (this.categoryOffsets == null) return null; // file is empty
-
- HashtableOfObject results = null; // initialized if needed
- if (key == null) {
- for (int i = 0, l = categories.length; i < l; i++) {
- HashtableOfObject wordsToDocNumbers = readCategoryTable(categories[i], true); // cache if key is null since its a definite match
- if (wordsToDocNumbers != null) {
- char[][] words = wordsToDocNumbers.keyTable;
- if (results == null)
- results = new HashtableOfObject(wordsToDocNumbers.elementSize);
- for (int j = 0, m = words.length; j < m; j++)
- if (words[j] != null)
- results = addQueryResult(results, words[j], wordsToDocNumbers, memoryIndex);
- }
- }
- if (results != null && this.cachedChunks == null)
- cacheDocumentNames();
- } else {
- switch (matchRule) {
- case SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE:
- for (int i = 0, l = categories.length; i < l; i++) {
- HashtableOfObject wordsToDocNumbers = readCategoryTable(categories[i], false);
- if (wordsToDocNumbers != null && wordsToDocNumbers.containsKey(key))
- results = addQueryResult(results, key, wordsToDocNumbers, memoryIndex);
- }
- break;
- case SearchPattern.R_PREFIX_MATCH | SearchPattern.R_CASE_SENSITIVE:
- for (int i = 0, l = categories.length; i < l; i++) {
- HashtableOfObject wordsToDocNumbers = readCategoryTable(categories[i], false);
- if (wordsToDocNumbers != null) {
- char[][] words = wordsToDocNumbers.keyTable;
- for (int j = 0, m = words.length; j < m; j++) {
- char[] word = words[j];
- if (word != null && key[0] == word[0] && CharOperation.prefixEquals(key, word))
- results = addQueryResult(results, word, wordsToDocNumbers, memoryIndex);
- }
- }
- }
- break;
- default:
- for (int i = 0, l = categories.length; i < l; i++) {
- HashtableOfObject wordsToDocNumbers = readCategoryTable(categories[i], false);
- if (wordsToDocNumbers != null) {
- char[][] words = wordsToDocNumbers.keyTable;
- for (int j = 0, m = words.length; j < m; j++) {
- char[] word = words[j];
- if (word != null && Index.isMatch(key, word, matchRule))
- results = addQueryResult(results, word, wordsToDocNumbers, memoryIndex);
- }
- }
- }
- }
- }
-
- if (results == null) return null;
- return results;
-}
-private 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);
- try {
- if (this.numberOfChunks > 5) BUFFER_READ_SIZE <<= 1;
- int offset = this.chunkOffsets[0];
- stream.skip(offset);
- this.streamBuffer = new byte[BUFFER_READ_SIZE];
- this.bufferIndex = 0;
- this.bufferEnd = stream.read(this.streamBuffer, 0, this.streamBuffer.length);
- for (int i = 0; i < this.numberOfChunks; i++) {
- int size = i == this.numberOfChunks - 1 ? this.sizeOfLastChunk : CHUNK_SIZE;
- readChunk(this.cachedChunks[i] = new String[size], stream, 0, size);
- }
- } catch (IOException e) {
- this.cachedChunks = null;
- throw e;
- } finally {
- stream.close();
- this.streamBuffer = null;
- BUFFER_READ_SIZE = DEFAULT_BUFFER_SIZE;
- }
-}
-private String[] computeDocumentNames(String[] onDiskNames, int[] positions, SimpleLookupTable indexedDocuments, MemoryIndex memoryIndex) {
- int onDiskLength = onDiskNames.length;
- Object[] docNames = memoryIndex.docsToReferences.keyTable;
- Object[] referenceTables = memoryIndex.docsToReferences.valueTable;
- if (onDiskLength == 0) {
- // disk index was empty, so add every indexed document
- for (int i = 0, l = referenceTables.length; i < l; i++)
- if (referenceTables[i] != null)
- indexedDocuments.put(docNames[i], null); // remember each new document
-
- String[] newDocNames = new String[indexedDocuments.elementSize];
- int count = 0;
- Object[] added = indexedDocuments.keyTable;
- for (int i = 0, l = added.length; i < l; i++)
- if (added[i] != null)
- newDocNames[count++] = (String) added[i];
- Util.sort(newDocNames);
- for (int i = 0, l = newDocNames.length; i < l; i++)
- indexedDocuments.put(newDocNames[i], new Integer(i));
- return newDocNames;
- }
-
- // initialize positions as if each document will remain in the same position
- for (int i = 0; i < onDiskLength; i++)
- positions[i] = i;
-
- // find out if the memory index has any new or deleted documents, if not then the names & positions are the same
- int numDeletedDocNames = 0;
- int numReindexedDocNames = 0;
- nextPath : for (int i = 0, l = docNames.length; i < l; i++) {
- String docName = (String) docNames[i];
- if (docName != null) {
- for (int j = 0; j < onDiskLength; j++) {
- if (docName.equals(onDiskNames[j])) {
- if (referenceTables[i] == null) {
- positions[j] = DELETED;
- numDeletedDocNames++;
- } else {
- positions[j] = RE_INDEXED;
- numReindexedDocNames++;
- }
- continue nextPath;
- }
- }
- if (referenceTables[i] != null)
- indexedDocuments.put(docName, null); // remember each new document, skip deleted documents which were never saved
- }
- }
-
- String[] newDocNames = onDiskNames;
- if (numDeletedDocNames > 0 || indexedDocuments.elementSize > 0) {
- // some new documents have been added or some old ones deleted
- newDocNames = new String[onDiskLength + indexedDocuments.elementSize - numDeletedDocNames];
- int count = 0;
- for (int i = 0; i < onDiskLength; i++)
- if (positions[i] >= RE_INDEXED)
- newDocNames[count++] = onDiskNames[i]; // keep each unchanged document
- Object[] added = indexedDocuments.keyTable;
- for (int i = 0, l = added.length; i < l; i++)
- if (added[i] != null)
- newDocNames[count++] = (String) added[i]; // add each new document
- Util.sort(newDocNames);
- for (int i = 0, l = newDocNames.length; i < l; i++)
- if (indexedDocuments.containsKey(newDocNames[i]))
- indexedDocuments.put(newDocNames[i], new Integer(i)); // remember the position for each new document
- }
-
- // need to be able to look up an old position (ref# from a ref[]) and map it to its new position
- // if its old position == DELETED then its forgotton
- // if its old position == ReINDEXED then its also forgotten but its new position is needed to map references
- int count = -1;
- for (int i = 0; i < onDiskLength;) {
- switch(positions[i]) {
- case DELETED :
- i++; // skip over deleted... references are forgotten
- break;
- case RE_INDEXED :
- String newName = newDocNames[++count];
- if (newName.equals(onDiskNames[i])) {
- indexedDocuments.put(newName, new Integer(count)); // the reindexed docName that was at position i is now at position count
- i++;
- }
- break;
- default :
- if (newDocNames[++count].equals(onDiskNames[i]))
- positions[i++] = count; // the unchanged docName that was at position i is now at position count
- }
- }
- return newDocNames;
-}
-private void copyQueryResults(HashtableOfObject categoryToWords, int newPosition) {
- char[][] categoryNames = categoryToWords.keyTable;
- Object[] wordSets = categoryToWords.valueTable;
- for (int i = 0, l = categoryNames.length; i < l; i++) {
- char[] categoryName = categoryNames[i];
- if (categoryName != null) {
- SimpleWordSet wordSet = (SimpleWordSet) wordSets[i];
- HashtableOfObject wordsToDocs = (HashtableOfObject) this.categoryTables.get(categoryName);
- if (wordsToDocs == null)
- this.categoryTables.put(categoryName, wordsToDocs = new HashtableOfObject(wordSet.elementSize));
-
- char[][] words = wordSet.words;
- for (int j = 0, m = words.length; j < m; j++) {
- char[] word = words[j];
- if (word != null) {
- Object o = wordsToDocs.get(word);
- if (o == null) {
- wordsToDocs.put(word, new int[] {newPosition});
- } else if (o instanceof IntList) {
- ((IntList) o).add(newPosition);
- } else {
- IntList list = new IntList((int[]) o);
- list.add(newPosition);
- wordsToDocs.put(word, list);
- }
- }
- }
- }
- }
-}
-void initialize(boolean reuseExistingFile) throws IOException {
- if (this.indexFile.exists()) {
- if (reuseExistingFile) {
- RandomAccessFile file = new RandomAccessFile(this.indexFile, "r"); //$NON-NLS-1$
- try {
- String signature = file.readUTF();
- if (!signature.equals(SIGNATURE))
- throw new IOException(Messages.exception_wrongFormat);
-
- this.headerInfoOffset = file.readInt();
- if (this.headerInfoOffset > 0) // file is empty if its not set
- readHeaderInfo(file);
- } finally {
- file.close();
- }
- return;
- }
- if (!this.indexFile.delete()) {
- if (DEBUG)
- System.out.println("initialize - Failed to delete index " + this.indexFile); //$NON-NLS-1$
- throw new IOException("Failed to delete index " + this.indexFile); //$NON-NLS-1$
- }
- }
- if (this.indexFile.createNewFile()) {
- RandomAccessFile file = new RandomAccessFile(this.indexFile, "rw"); //$NON-NLS-1$
- try {
- file.writeUTF(SIGNATURE);
- file.writeInt(-1); // file is empty
- } finally {
- file.close();
- }
- } else {
- if (DEBUG)
- System.out.println("initialize - Failed to create new index " + this.indexFile); //$NON-NLS-1$
- throw new IOException("Failed to create new index " + this.indexFile); //$NON-NLS-1$
- }
-}
-private void initializeFrom(DiskIndex diskIndex, File newIndexFile) throws IOException {
- if (newIndexFile.exists() && !newIndexFile.delete()) { // delete the temporary index file
- if (DEBUG)
- System.out.println("initializeFrom - Failed to delete temp index " + this.indexFile); //$NON-NLS-1$
- } else if (!newIndexFile.createNewFile()) {
- if (DEBUG)
- System.out.println("initializeFrom - Failed to create temp index " + this.indexFile); //$NON-NLS-1$
- throw new IOException("Failed to create temp index " + this.indexFile); //$NON-NLS-1$
- }
-
- int size = diskIndex.categoryOffsets == null ? 8 : diskIndex.categoryOffsets.elementSize;
- this.categoryOffsets = new HashtableOfIntValues(size);
- this.categoryEnds = new HashtableOfIntValues(size);
- this.categoryTables = new HashtableOfObject(size);
-}
-private void mergeCategories(DiskIndex onDisk, int[] positions, FileOutputStream stream) throws IOException {
- // at this point, this.categoryTables contains the names -> wordsToDocs added in copyQueryResults()
- char[][] oldNames = onDisk.categoryOffsets.keyTable;
- for (int i = 0, l = oldNames.length; i < l; i++) {
- char[] oldName = oldNames[i];
- if (oldName != null && !this.categoryTables.containsKey(oldName))
- this.categoryTables.put(oldName, null);
- }
-
- char[][] categoryNames = this.categoryTables.keyTable;
- for (int i = 0, l = categoryNames.length; i < l; i++)
- if (categoryNames[i] != null)
- mergeCategory(categoryNames[i], onDisk, positions, stream);
- this.categoryTables = null;
-}
-private void mergeCategory(char[] categoryName, DiskIndex onDisk, int[] positions, FileOutputStream stream) throws IOException {
- HashtableOfObject wordsToDocs = (HashtableOfObject) this.categoryTables.get(categoryName);
- if (wordsToDocs == null)
- wordsToDocs = new HashtableOfObject(3);
-
- HashtableOfObject oldWordsToDocs = onDisk.readCategoryTable(categoryName, true);
- if (oldWordsToDocs != null) {
- char[][] oldWords = oldWordsToDocs.keyTable;
- Object[] oldArrayOffsets = oldWordsToDocs.valueTable;
- nextWord: for (int i = 0, l = oldWords.length; i < l; i++) {
- char[] oldWord = oldWords[i];
- if (oldWord != null) {
- int[] oldDocNumbers = (int[]) oldArrayOffsets[i];
- int length = oldDocNumbers.length;
- int[] mappedNumbers = new int[length];
- int count = 0;
- for (int j = 0; j < length; j++) {
- int pos = positions[oldDocNumbers[j]];
- if (pos > RE_INDEXED) // forget any reference to a document which was deleted or re_indexed
- mappedNumbers[count++] = pos;
- }
- if (count < length) {
- if (count == 0) continue nextWord; // skip words which no longer have any references
- System.arraycopy(mappedNumbers, 0, mappedNumbers = new int[count], 0, count);
- }
-
- Object o = wordsToDocs.get(oldWord);
- if (o == null) {
- wordsToDocs.put(oldWord, mappedNumbers);
- } else {
- IntList list = null;
- if (o instanceof IntList) {
- list = (IntList) o;
- } else {
- list = new IntList((int[]) o);
- wordsToDocs.put(oldWord, list);
- }
- for (int j = 0; j < count; j++)
- list.add(mappedNumbers[j]);
- }
- }
- }
- onDisk.categoryTables.put(categoryName, null); // flush cached table
- }
- writeCategoryTable(categoryName, wordsToDocs, stream);
-}
-DiskIndex mergeWith(MemoryIndex memoryIndex) throws IOException {
- // assume write lock is held
- // compute & write out new docNames
- String[] docNames = readAllDocumentNames();
- int previousLength = docNames.length;
- int[] positions = new int[previousLength]; // keeps track of the position of each document in the new sorted docNames
- SimpleLookupTable indexedDocuments = new SimpleLookupTable(3); // for each new/changed document in the memoryIndex
- docNames = computeDocumentNames(docNames, positions, indexedDocuments, memoryIndex);
- if (docNames.length == 0) {
- if (previousLength == 0) return this; // nothing to do... memory index contained deleted documents that had never been saved
-
- // index is now empty since all the saved documents were removed
- DiskIndex newDiskIndex = new DiskIndex(this.indexFile.getPath());
- newDiskIndex.initialize(false);
- return newDiskIndex;
- }
-
- DiskIndex newDiskIndex = new DiskIndex(this.indexFile.getPath() + ".tmp"); //$NON-NLS-1$
- try {
- newDiskIndex.initializeFrom(this, newDiskIndex.indexFile);
- FileOutputStream stream = new FileOutputStream(newDiskIndex.indexFile, false);
- int offsetToHeader = -1;
- try {
- newDiskIndex.writeAllDocumentNames(docNames, stream);
- docNames = null; // free up the space
-
- // add each new/changed doc to empty category tables using its new position #
- if (indexedDocuments.elementSize > 0) {
- Object[] names = indexedDocuments.keyTable;
- Object[] integerPositions = indexedDocuments.valueTable;
- for (int i = 0, l = names.length; i < l; i++)
- if (names[i] != null)
- newDiskIndex.copyQueryResults(
- (HashtableOfObject) memoryIndex.docsToReferences.get(names[i]), ((Integer) integerPositions[i]).intValue());
- }
- indexedDocuments = null; // free up the space
-
- // merge each category table with the new ones & write them out
- if (previousLength == 0)
- newDiskIndex.writeCategories(stream);
- else
- newDiskIndex.mergeCategories(this, positions, stream);
- offsetToHeader = newDiskIndex.streamEnd;
- newDiskIndex.writeHeaderInfo(stream);
- positions = null; // free up the space
- } finally {
- stream.close();
- this.streamBuffer = null;
- }
- newDiskIndex.writeOffsetToHeader(offsetToHeader);
-
- // rename file by deleting previous index file & renaming temp one
- if (this.indexFile.exists() && !this.indexFile.delete()) {
- if (DEBUG)
- System.out.println("mergeWith - Failed to delete " + this.indexFile); //$NON-NLS-1$
- throw new IOException("Failed to delete index file " + this.indexFile); //$NON-NLS-1$
- }
- if (!newDiskIndex.indexFile.renameTo(this.indexFile)) {
- if (DEBUG)
- System.out.println("mergeWith - Failed to rename " + this.indexFile); //$NON-NLS-1$
- throw new IOException("Failed to rename index file " + this.indexFile); //$NON-NLS-1$
- }
- } catch (IOException e) {
- if (newDiskIndex.indexFile.exists() && !newDiskIndex.indexFile.delete())
- if (DEBUG)
- System.out.println("mergeWith - Failed to delete temp index " + newDiskIndex.indexFile); //$NON-NLS-1$
- throw e;
- }
-
- newDiskIndex.indexFile = this.indexFile;
- return newDiskIndex;
-}
-private synchronized String[] readAllDocumentNames() throws IOException {
- if (this.numberOfChunks <= 0)
- return CharOperation.NO_STRINGS;
-
- FileInputStream stream = new FileInputStream(this.indexFile);
- try {
- int offset = this.chunkOffsets[0];
- stream.skip(offset);
- this.streamBuffer = new byte[BUFFER_READ_SIZE];
- this.bufferIndex = 0;
- this.bufferEnd = stream.read(this.streamBuffer, 0, this.streamBuffer.length);
- int lastIndex = this.numberOfChunks - 1;
- String[] docNames = new String[lastIndex * CHUNK_SIZE + sizeOfLastChunk];
- for (int i = 0; i < this.numberOfChunks; i++)
- readChunk(docNames, stream, i * CHUNK_SIZE, i < lastIndex ? CHUNK_SIZE : sizeOfLastChunk);
- return docNames;
- } finally {
- stream.close();
- this.streamBuffer = null;
- }
-}
-private synchronized HashtableOfObject readCategoryTable(char[] categoryName, boolean readDocNumbers) throws IOException {
- // result will be null if categoryName is unknown
- int offset = this.categoryOffsets.get(categoryName);
- if (offset == HashtableOfIntValues.NO_VALUE) {
- return null;
- }
-
- if (this.categoryTables == null) {
- this.categoryTables = new HashtableOfObject(3);
- } else {
- HashtableOfObject cachedTable = (HashtableOfObject) this.categoryTables.get(categoryName);
- if (cachedTable != null) {
- if (readDocNumbers) { // must cache remaining document number arrays
- Object[] arrayOffsets = cachedTable.valueTable;
- for (int i = 0, l = arrayOffsets.length; i < l; i++)
- if (arrayOffsets[i] instanceof Integer)
- arrayOffsets[i] = readDocumentNumbers(arrayOffsets[i]);
- }
- return cachedTable;
- }
- }
-
- FileInputStream stream = new FileInputStream(this.indexFile);
- HashtableOfObject categoryTable = null;
- char[][] matchingWords = null;
- int count = 0;
- int firstOffset = -1;
- this.streamBuffer = new byte[BUFFER_READ_SIZE];
- try {
- stream.skip(offset);
- this.bufferIndex = 0;
- this.bufferEnd = stream.read(this.streamBuffer, 0, this.streamBuffer.length);
- int size = readStreamInt(stream);
- try {
- if (size < 0) { // DEBUG
- System.err.println("-------------------- DEBUG --------------------"); //$NON-NLS-1$
- System.err.println("file = "+this.indexFile); //$NON-NLS-1$
- System.err.println("offset = "+offset); //$NON-NLS-1$
- System.err.println("size = "+size); //$NON-NLS-1$
- System.err.println("-------------------- END --------------------"); //$NON-NLS-1$
- }
- categoryTable = new HashtableOfObject(size);
- } catch (OutOfMemoryError oom) {
- // DEBUG
- oom.printStackTrace();
- System.err.println("-------------------- DEBUG --------------------"); //$NON-NLS-1$
- System.err.println("file = "+this.indexFile); //$NON-NLS-1$
- System.err.println("offset = "+offset); //$NON-NLS-1$
- System.err.println("size = "+size); //$NON-NLS-1$
- System.err.println("-------------------- END --------------------"); //$NON-NLS-1$
- throw oom;
- }
- int largeArraySize = 256;
- for (int i = 0; i < size; i++) {
- char[] word = readStreamChars(stream);
- int arrayOffset = readStreamInt(stream);
- // if arrayOffset is:
- // <= 0 then the array size == 1 with the value -> -arrayOffset
- // > 1 & < 256 then the size of the array is > 1 & < 256, the document array follows immediately
- // 256 if the array size >= 256 followed by another int which is the offset to the array (written prior to the table)
- if (arrayOffset <= 0) {
- categoryTable.put(word, new int[] {-arrayOffset}); // store 1 element array by negating documentNumber
- } else if (arrayOffset < largeArraySize) {
- categoryTable.put(word, readStreamDocumentArray(stream, arrayOffset)); // read in-lined array providing size
- } else {
- arrayOffset = readStreamInt(stream); // read actual offset
- if (readDocNumbers) {
- if (matchingWords == null)
- matchingWords = new char[size][];
- if (count == 0)
- firstOffset = arrayOffset;
- matchingWords[count++] = word;
- }
- categoryTable.put(word, new Integer(arrayOffset)); // offset to array in the file
- }
- }
- this.categoryTables.put(INTERNED_CATEGORY_NAMES.get(categoryName), categoryTable);
- // cache the table as long as its not too big
- // in practice, some tables can be greater than 500K when they contain more than 10K elements
- this.cachedCategoryName = categoryTable.elementSize < 20000 ? categoryName : null;
- } catch (IOException ioe) {
- this.streamBuffer = null;
- throw ioe;
- } finally {
- stream.close();
- }
-
- if (matchingWords != null && count > 0) {
- stream = new FileInputStream(this.indexFile);
- try {
- stream.skip(firstOffset);
- this.bufferIndex = 0;
- this.bufferEnd = stream.read(this.streamBuffer, 0, this.streamBuffer.length);
- for (int i = 0; i < count; i++) { // each array follows the previous one
- categoryTable.put(matchingWords[i], readStreamDocumentArray(stream, readStreamInt(stream)));
- }
- } catch (IOException ioe) {
- this.streamBuffer = null;
- throw ioe;
- } finally {
- stream.close();
- }
- }
- this.streamBuffer = null;
- return categoryTable;
-}
-private void readChunk(String[] docNames, FileInputStream stream, int index, int size) throws IOException {
- String current = new String(readStreamChars(stream));
- docNames[index++] = current;
- for (int i = 1; i < size; i++) {
- if (stream != null && this.bufferIndex + 2 >= this.bufferEnd)
- readStreamBuffer(stream);
- int start = streamBuffer[this.bufferIndex++] & 0xFF;
- int end = streamBuffer[this.bufferIndex++] & 0xFF;
- String next = new String(readStreamChars(stream));
- if (start > 0) {
- if (end > 0) {
- int length = current.length();
- next = current.substring(0, start) + next + current.substring(length - end, length);
- } else {
- next = current.substring(0, start) + next;
- }
- } else if (end > 0) {
- int length = current.length();
- next = next + current.substring(length - end, length);
- }
- docNames[index++] = next;
- current = next;
- }
-}
-synchronized String readDocumentName(int docNumber) throws IOException {
- if (this.cachedChunks == null)
- this.cachedChunks = new String[this.numberOfChunks][];
-
- int chunkNumber = docNumber / CHUNK_SIZE;
- String[] chunk = this.cachedChunks[chunkNumber];
- if (chunk == null) {
- boolean isLastChunk = chunkNumber == this.numberOfChunks - 1;
- int start = this.chunkOffsets[chunkNumber];
- int numberOfBytes = (isLastChunk ? this.startOfCategoryTables : this.chunkOffsets[chunkNumber + 1]) - start;
- if (numberOfBytes < 0)
- throw new IllegalArgumentException();
- this.streamBuffer = new byte[numberOfBytes];
- this.bufferIndex = 0;
- FileInputStream file = new FileInputStream(this.indexFile);
- try {
- file.skip(start);
- if (file.read(this.streamBuffer, 0, numberOfBytes) != numberOfBytes)
- throw new IOException();
- } catch (IOException ioe) {
- this.streamBuffer = null;
- throw ioe;
- } finally {
- file.close();
- }
- int numberOfNames = isLastChunk ? this.sizeOfLastChunk : CHUNK_SIZE;
- chunk = new String[numberOfNames];
- try {
- readChunk(chunk, null, 0, numberOfNames);
- } catch (IOException ioe) {
- this.streamBuffer = null;
- throw ioe;
- }
- this.cachedChunks[chunkNumber] = chunk;
- }
- this.streamBuffer = null;
- return chunk[docNumber - (chunkNumber * CHUNK_SIZE)];
-}
-synchronized int[] readDocumentNumbers(Object arrayOffset) throws IOException {
- // arrayOffset is either a cached array of docNumbers or an Integer offset in the file
- if (arrayOffset instanceof int[])
- return (int[]) arrayOffset;
-
- FileInputStream stream = new FileInputStream(this.indexFile);
- try {
- int offset = ((Integer) arrayOffset).intValue();
- stream.skip(offset);
- this.streamBuffer = new byte[BUFFER_READ_SIZE];
- this.bufferIndex = 0;
- this.bufferEnd = stream.read(this.streamBuffer, 0, this.streamBuffer.length);
- return readStreamDocumentArray(stream, readStreamInt(stream));
- } finally {
- stream.close();
- this.streamBuffer = null;
- }
-}
-private void readHeaderInfo(RandomAccessFile file) throws IOException {
- file.seek(this.headerInfoOffset);
-
- // must be same order as writeHeaderInfo()
- this.numberOfChunks = file.readInt();
- this.sizeOfLastChunk = file.readUnsignedByte();
- this.documentReferenceSize = file.readUnsignedByte();
-
- this.chunkOffsets = new int[this.numberOfChunks];
- for (int i = 0; i < this.numberOfChunks; i++)
- this.chunkOffsets[i] = file.readInt();
-
- this.startOfCategoryTables = file.readInt();
-
- int size = file.readInt();
- this.categoryOffsets = new HashtableOfIntValues(size);
- this.categoryEnds = new HashtableOfIntValues(size);
- char[] previousCategory = null;
- int offset = -1;
- for (int i = 0; i < size; i++) {
- char[] categoryName = INTERNED_CATEGORY_NAMES.get(file.readUTF().toCharArray());
- offset = file.readInt();
- this.categoryOffsets.put(categoryName, offset); // cache offset to category table
- if (previousCategory != null) {
- this.categoryEnds.put(previousCategory, offset); // cache end of the category table
- }
- previousCategory = categoryName;
- }
- if (previousCategory != null) {
- this.categoryEnds.put(previousCategory, this.headerInfoOffset); // cache end of the category table
- }
- this.categoryTables = new HashtableOfObject(3);
-}
-synchronized void startQuery() {
- this.cacheUserCount++;
-}
-synchronized 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;
- }
- }
- }
-}
-private void readStreamBuffer(FileInputStream stream) throws IOException {
- // if we're about to read a known amount at the end of the existing buffer, but it does not completely fit
- // so we need to shift the remaining bytes to be read, and fill the buffer from the stream
- if (this.bufferEnd < this.streamBuffer.length)
- return; // we're at the end of the stream - nothing left to read
-
- int bytesInBuffer = this.bufferEnd - this.bufferIndex;
- if (bytesInBuffer > 0)
- System.arraycopy(this.streamBuffer, this.bufferIndex, this.streamBuffer, 0, bytesInBuffer);
- this.bufferEnd = bytesInBuffer + stream.read(this.streamBuffer, bytesInBuffer, this.bufferIndex);
- this.bufferIndex = 0;
-}
-/**
- * Reads in a string from the specified data input stream. The
- * string has been encoded using a modified UTF-8 format.
- * <p>
- * The first two bytes are read as an unsigned short.
- * This value gives the number of following bytes that are in the encoded string,
- * not the length of the resulting string. The following bytes are then
- * interpreted as bytes encoding characters in the UTF-8 format
- * and are converted into characters.
- * <p>
- * This method blocks until all the bytes are read, the end of the
- * stream is detected, or an exception is thrown.
- *
- * @param stream a data input stream.
- * @return UTF decoded string as a char array
- * @exception java.io.EOFException if this end of data input is reached while reading it.
- * @exception IOException if an I/O error occurs while reading data input.
- * @exception UTFDataFormatException if the bytes do not represent a
- * valid UTF-8 encoding of a Unicode string.
- */
-private char[] readStreamChars(FileInputStream stream) throws IOException {
- // read chars array length
- if (stream != null && this.bufferIndex + 2 >= this.bufferEnd)
- readStreamBuffer(stream);
- int length = (streamBuffer[this.bufferIndex++] & 0xFF) << 8;
- length += this.streamBuffer[this.bufferIndex++] & 0xFF;
-
- // fill the chars from bytes buffer
- char[] word = new char[length];
- int i = 0;
- while (i < length) {
- // how many characters can be decoded without refilling the buffer?
- int charsInBuffer = i + ((this.bufferEnd - this.bufferIndex) / 3);
- // all the characters must already be in the buffer if we're at the end of the stream
- if (charsInBuffer > length || this.bufferEnd != this.streamBuffer.length || stream == null)
- charsInBuffer = length;
- while (i < charsInBuffer) {
- byte b = this.streamBuffer[this.bufferIndex++];
- switch (b & 0xF0) {
- case 0x00 :
- case 0x10 :
- case 0x20 :
- case 0x30 :
- case 0x40 :
- case 0x50 :
- case 0x60 :
- case 0x70 :
- word[i++]= (char) b;
- break;
- case 0xC0 :
- case 0xD0 :
- char next = (char) this.streamBuffer[this.bufferIndex++];
- if ((next & 0xC0) != 0x80) {
- throw new UTFDataFormatException();
- }
- char ch = (char) ((b & 0x1F) << 6);
- ch |= next & 0x3F;
- word[i++] = ch;
- break;
- case 0xE0 :
- char first = (char) this.streamBuffer[this.bufferIndex++];
- char second = (char) this.streamBuffer[this.bufferIndex++];
- if ((first & second & 0xC0) != 0x80) {
- throw new UTFDataFormatException();
- }
- ch = (char) ((b & 0x0F) << 12);
- ch |= ((first& 0x3F) << 6);
- ch |= second & 0x3F;
- word[i++] = ch;
- break;
- default:
- throw new UTFDataFormatException();
- }
- }
- if (i < length && stream != null)
- readStreamBuffer(stream);
- }
- return word;
-}
-private int[] readStreamDocumentArray(FileInputStream stream, int arraySize) throws IOException {
- int[] indexes = new int[arraySize];
- if (arraySize == 0) return indexes;
-
- int i = 0;
- switch (this.documentReferenceSize) {
- case 1 :
- while (i < arraySize) {
- // how many bytes without refilling the buffer?
- int bytesInBuffer = i + this.bufferEnd - this.bufferIndex;
- if (bytesInBuffer > arraySize)
- bytesInBuffer = arraySize;
- while (i < bytesInBuffer) {
- indexes[i++] = this.streamBuffer[this.bufferIndex++] & 0xFF;
- }
- if (i < arraySize && stream != null)
- readStreamBuffer(stream);
- }
- break;
- case 2 :
- while (i < arraySize) {
- // how many shorts without refilling the buffer?
- int shortsInBuffer = i + ((this.bufferEnd - this.bufferIndex) / 2);
- if (shortsInBuffer > arraySize)
- shortsInBuffer = arraySize;
- while (i < shortsInBuffer) {
- int val = (this.streamBuffer[this.bufferIndex++] & 0xFF) << 8;
- indexes[i++] = val + (this.streamBuffer[this.bufferIndex++] & 0xFF);
- }
- if (i < arraySize && stream != null)
- readStreamBuffer(stream);
- }
- break;
- default :
- while (i < arraySize) {
- indexes[i++] = readStreamInt(stream);
- }
- break;
- }
- return indexes;
-}
-private int readStreamInt(FileInputStream stream) throws IOException {
- if (this.bufferIndex + 4 >= this.bufferEnd) {
- readStreamBuffer(stream);
- }
- int val = (streamBuffer[this.bufferIndex++] & 0xFF) << 24;
- val += (streamBuffer[this.bufferIndex++] & 0xFF) << 16;
- val += (streamBuffer[this.bufferIndex++] & 0xFF) << 8;
- return val + (streamBuffer[this.bufferIndex++] & 0xFF);
-}
-private void writeAllDocumentNames(String[] sortedDocNames, FileOutputStream stream) throws IOException {
- if (sortedDocNames.length == 0)
- throw new IllegalArgumentException();
-
- // assume the file was just created by initializeFrom()
- this.streamBuffer = new byte[BUFFER_WRITE_SIZE];
- this.bufferIndex = 0;
- this.streamEnd = 0;
-
- // in order, write: SIGNATURE & headerInfoOffset place holder, then each compressed chunk of document names
- writeStreamChars(stream, SIGNATURE_CHARS);
- this.headerInfoOffset = this.streamEnd;
- writeStreamInt(stream, -1); // will overwrite with correct value later
-
- int size = sortedDocNames.length;
- this.numberOfChunks = (size / CHUNK_SIZE) + 1;
- this.sizeOfLastChunk = size % CHUNK_SIZE;
- if (this.sizeOfLastChunk == 0) {
- this.numberOfChunks--;
- this.sizeOfLastChunk = CHUNK_SIZE;
- }
- this.documentReferenceSize = size <= 0x7F ? 1 : (size <= 0x7FFF ? 2 : 4); // number of bytes used to encode a reference
-
- this.chunkOffsets = new int[this.numberOfChunks];
- int lastIndex = this.numberOfChunks - 1;
- for (int i = 0; i < this.numberOfChunks; i++) {
- this.chunkOffsets[i] = this.streamEnd;
-
- int chunkSize = i == lastIndex ? this.sizeOfLastChunk : CHUNK_SIZE;
- int chunkIndex = i * CHUNK_SIZE;
- String current = sortedDocNames[chunkIndex];
- writeStreamChars(stream, current.toCharArray());
- for (int j = 1; j < chunkSize; j++) {
- String next = sortedDocNames[chunkIndex + j];
- int len1 = current.length();
- int len2 = next.length();
- int max = len1 < len2 ? len1 : len2;
- int start = 0; // number of identical characters at the beginning (also the index of first character that is different)
- while (current.charAt(start) == next.charAt(start)) {
- start++;
- if (max == start) break; // current is 'abba', next is 'abbab'
- }
- if (start > 255) start = 255;
-
- int end = 0; // number of identical characters at the end
- while (current.charAt(--len1) == next.charAt(--len2)) {
- end++;
- if (len2 == start) break; // current is 'abbba', next is 'abba'
- if (len1 == 0) break; // current is 'xabc', next is 'xyabc'
- }
- if (end > 255) end = 255;
- if ((this.bufferIndex + 2) >= BUFFER_WRITE_SIZE) {
- stream.write(this.streamBuffer, 0, this.bufferIndex);
- this.bufferIndex = 0;
- }
- this.streamBuffer[this.bufferIndex++] = (byte) start;
- this.streamBuffer[this.bufferIndex++] = (byte) end;
- this.streamEnd += 2;
-
- int last = next.length() - end;
- writeStreamChars(stream, (start < last ? CharOperation.subarray(next.toCharArray(), start, last) : CharOperation.NO_CHAR));
- current = next;
- }
- }
- this.startOfCategoryTables = this.streamEnd + 1;
-}
-private void writeCategories(FileOutputStream stream) throws IOException {
- char[][] categoryNames = this.categoryTables.keyTable;
- Object[] tables = this.categoryTables.valueTable;
- for (int i = 0, l = categoryNames.length; i < l; i++)
- if (categoryNames[i] != null)
- writeCategoryTable(categoryNames[i], (HashtableOfObject) tables[i], stream);
- this.categoryTables = null;
-}
-private void writeCategoryTable(char[] categoryName, HashtableOfObject wordsToDocs, FileOutputStream stream) throws IOException {
- // the format of a category table is as follows:
- // any document number arrays with >= 256 elements are written before the table (the offset to each array is remembered)
- // then the number of word->int[] pairs in the table is written
- // for each word -> int[] pair, the word is written followed by:
- // an int <= 0 if the array size == 1
- // an int > 1 & < 256 for the size of the array if its > 1 & < 256, the document array follows immediately
- // 256 if the array size >= 256 followed by another int which is the offset to the array (written prior to the table)
-
- int largeArraySize = 256;
- Object[] values = wordsToDocs.valueTable;
- for (int i = 0, l = values.length; i < l; i++) {
- Object o = values[i];
- if (o != null) {
- if (o instanceof IntList)
- o = values[i] = ((IntList) values[i]).asArray();
- int[] documentNumbers = (int[]) o;
- if (documentNumbers.length >= largeArraySize) {
- values[i] = new Integer(this.streamEnd);
- writeDocumentNumbers(documentNumbers, stream);
- }
- }
- }
-
- this.categoryOffsets.put(categoryName, this.streamEnd); // remember the offset to the start of the table
- this.categoryTables.put(categoryName, null); // flush cached table
- writeStreamInt(stream, wordsToDocs.elementSize);
- char[][] words = wordsToDocs.keyTable;
- for (int i = 0, l = words.length; i < l; i++) {
- Object o = values[i];
- if (o != null) {
- writeStreamChars(stream, words[i]);
- if (o instanceof int[]) {
- int[] documentNumbers = (int[]) o;
- if (documentNumbers.length == 1)
- writeStreamInt(stream, -documentNumbers[0]); // store an array of 1 element by negating the documentNumber (can be zero)
- else
- writeDocumentNumbers(documentNumbers, stream);
- } else {
- writeStreamInt(stream, largeArraySize); // mark to identify that an offset follows
- writeStreamInt(stream, ((Integer) o).intValue()); // offset in the file of the array of document numbers
- }
- }
- }
-}
-private void writeDocumentNumbers(int[] documentNumbers, FileOutputStream stream) throws IOException {
- // must store length as a positive int to detect in-lined array of 1 element
- int length = documentNumbers.length;
- writeStreamInt(stream, length);
- Util.sort(documentNumbers);
- int start = 0;
- switch (this.documentReferenceSize) {
- case 1 :
- while ((this.bufferIndex + length - start) >= BUFFER_WRITE_SIZE) {
- // when documentNumbers is large, write BUFFER_WRITE_SIZE parts & fall thru to write the last part
- int bytesLeft = BUFFER_WRITE_SIZE - this.bufferIndex;
- for (int i=0; i < bytesLeft; i++) {
- this.streamBuffer[this.bufferIndex++] = (byte) documentNumbers[start++];
- }
- stream.write(this.streamBuffer, 0, this.bufferIndex);
- this.bufferIndex = 0;
- }
- while (start < length) {
- this.streamBuffer[this.bufferIndex++] = (byte) documentNumbers[start++];
- }
- this.streamEnd += length;
- break;
- case 2 :
- while ((this.bufferIndex + ((length - start) * 2)) >= BUFFER_WRITE_SIZE) {
- // when documentNumbers is large, write BUFFER_WRITE_SIZE parts & fall thru to write the last part
- int shortsLeft = (BUFFER_WRITE_SIZE - this.bufferIndex) / 2;
- for (int i=0; i < shortsLeft; i++) {
- this.streamBuffer[this.bufferIndex++] = (byte) (documentNumbers[start] >> 8);
- this.streamBuffer[this.bufferIndex++] = (byte) documentNumbers[start++];
- }
- stream.write(this.streamBuffer, 0, this.bufferIndex);
- this.bufferIndex = 0;
- }
- while (start < length) {
- this.streamBuffer[this.bufferIndex++] = (byte) (documentNumbers[start] >> 8);
- this.streamBuffer[this.bufferIndex++] = (byte) documentNumbers[start++];
- }
- this.streamEnd += length * 2;
- break;
- default :
- while (start < length) {
- writeStreamInt(stream, documentNumbers[start++]);
- }
- break;
- }
-}
-private void writeHeaderInfo(FileOutputStream stream) throws IOException {
- writeStreamInt(stream, this.numberOfChunks);
- if ((this.bufferIndex + 2) >= BUFFER_WRITE_SIZE) {
- stream.write(this.streamBuffer, 0, this.bufferIndex);
- this.bufferIndex = 0;
- }
- this.streamBuffer[this.bufferIndex++] = (byte) this.sizeOfLastChunk;
- this.streamBuffer[this.bufferIndex++] = (byte) this.documentReferenceSize;
- this.streamEnd += 2;
-
- // apend the file with chunk offsets
- for (int i = 0; i < this.numberOfChunks; i++) {
- writeStreamInt(stream, this.chunkOffsets[i]);
- }
-
- writeStreamInt(stream, this.startOfCategoryTables);
-
- // append the file with the category offsets... # of name -> offset pairs, followed by each name & an offset to its word->doc# table
- writeStreamInt(stream, this.categoryOffsets.elementSize);
- char[][] categoryNames = this.categoryOffsets.keyTable;
- int[] offsets = this.categoryOffsets.valueTable;
- for (int i = 0, l = categoryNames.length; i < l; i++) {
- if (categoryNames[i] != null) {
- writeStreamChars(stream, categoryNames[i]);
- writeStreamInt(stream, offsets[i]);
- }
- }
- // ensure buffer is written to the stream
- if (this.bufferIndex > 0) {
- stream.write(this.streamBuffer, 0, this.bufferIndex);
- this.bufferIndex = 0;
- }
-}
-private void writeOffsetToHeader(int offsetToHeader) throws IOException {
- if (offsetToHeader > 0) {
- RandomAccessFile file = new RandomAccessFile(this.indexFile, "rw"); //$NON-NLS-1$
- try {
- file.seek(this.headerInfoOffset); // offset to position in header
- file.writeInt(offsetToHeader);
- this.headerInfoOffset = offsetToHeader; // update to reflect the correct offset
- } finally {
- file.close();
- }
- }
-}
-/**
- * Writes a string to the given output stream using UTF-8
- * encoding in a machine-independent manner.
- * <p>
- * First, two bytes of the array are giving the number of bytes to
- * follow. This value is the number of bytes actually written out,
- * not the length of the string. Following the length, each character
- * of the string is put in the bytes array, in sequence, using the UTF-8
- * encoding for the character.
- * </p>
- * <p>
- * Then the entire byte array is written to the output stream
- * using {@link java.io.OutputStream#write(byte[], int, int)} method.
- * </p>
- *
- * @param array char array to be written.
- * @exception IOException if an I/O error occurs while writting
- * the bytes array to the stream.
- */
-private void writeStreamChars(FileOutputStream stream, char[] array) throws IOException {
- if ((this.bufferIndex + 2) >= BUFFER_WRITE_SIZE) {
- stream.write(this.streamBuffer, 0, this.bufferIndex);
- this.bufferIndex = 0;
- }
- int length = array.length;
- this.streamBuffer[this.bufferIndex++] = (byte) ((length >>> 8) & 0xFF); // store chars array length instead of bytes
- this.streamBuffer[this.bufferIndex++] = (byte) (length & 0xFF); // this will allow to read it faster
- this.streamEnd += 2;
-
- // we're assuming that very few char[] are so large that we need to flush the buffer more than once, if at all
- int totalBytesNeeded = length * 3;
- if (totalBytesNeeded <= BUFFER_WRITE_SIZE) {
- if (this.bufferIndex + totalBytesNeeded > BUFFER_WRITE_SIZE) {
- // flush the buffer now to make sure there is room for the array
- stream.write(this.streamBuffer, 0, this.bufferIndex);
- this.bufferIndex = 0;
- }
- writeStreamChars(stream, array, 0, length);
- } else {
- int charsPerWrite = BUFFER_WRITE_SIZE / 3;
- int start = 0;
- while (start < length) {
- stream.write(this.streamBuffer, 0, this.bufferIndex);
- this.bufferIndex = 0;
- int charsLeftToWrite = length - start;
- int end = start + (charsPerWrite < charsLeftToWrite ? charsPerWrite : charsLeftToWrite);
- writeStreamChars(stream, array, start, end);
- start = end;
- }
- }
-}
-private void writeStreamChars(FileOutputStream stream, char[] array, int start, int end) throws IOException {
- // start can NOT be == end
- // must have checked that there is enough room for end - start * 3 bytes in the buffer
-
- int oldIndex = this.bufferIndex;
- while (start < end) {
- int ch = array[start++];
- if ((ch & 0x007F) == ch) {
- this.streamBuffer[this.bufferIndex++] = (byte) ch;
- } else if ((ch & 0x07FF) == ch) {
- // first two bits are stored in first byte
- byte b = (byte) (ch >> 6);
- b &= 0x1F;
- b |= 0xC0;
- this.streamBuffer[this.bufferIndex++] = b;
- // last six bits are stored in second byte
- b = (byte) (ch & 0x3F);
- b |= 0x80;
- this.streamBuffer[this.bufferIndex++] = b;
- } else {
- // first four bits are stored in first byte
- byte b = (byte) (ch >> 12);
- b &= 0x0F;
- b |= 0xE0;
- this.streamBuffer[this.bufferIndex++] = b;
- // six following bits are stored in second byte
- b = (byte) (ch >> 6);
- b &= 0x3F;
- b |= 0x80;
- this.streamBuffer[this.bufferIndex++] = b;
- // last six bits are stored in third byte
- b = (byte) (ch & 0x3F);
- b |= 0x80;
- this.streamBuffer[this.bufferIndex++] = b;
- }
- }
- this.streamEnd += this.bufferIndex - oldIndex;
-}
-private void writeStreamInt(FileOutputStream stream, int val) throws IOException {
- if ((this.bufferIndex + 4) >= BUFFER_WRITE_SIZE) {
- stream.write(this.streamBuffer, 0, this.bufferIndex);
- this.bufferIndex = 0;
- }
- this.streamBuffer[this.bufferIndex++] = (byte) (val >> 24);
- this.streamBuffer[this.bufferIndex++] = (byte) (val >> 16);
- this.streamBuffer[this.bufferIndex++] = (byte) (val >> 8);
- this.streamBuffer[this.bufferIndex++] = (byte) val;
- this.streamEnd += 4;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/index/EntryResult.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/index/EntryResult.java
deleted file mode 100644
index b46cd6f9..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/index/EntryResult.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.index;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfObject;
-import org.eclipse.wst.jsdt.internal.compiler.util.SimpleSet;
-
-public class EntryResult {
-
-private char[] word;
-private HashtableOfObject[] documentTables;
-private SimpleSet documentNames;
-
-public EntryResult(char[] word, HashtableOfObject table) {
- this.word = word;
- if (table != null)
- this.documentTables = new HashtableOfObject[] {table};
-}
-public void addDocumentName(String documentName) {
- if (this.documentNames == null)
- this.documentNames = new SimpleSet(3);
- this.documentNames.add(documentName);
-}
-public void addDocumentTable(HashtableOfObject table) {
- if (this.documentTables != null) {
- int length = this.documentTables.length;
- System.arraycopy(this.documentTables, 0, this.documentTables = new HashtableOfObject[length + 1], 0, length);
- this.documentTables[length] = table;
- } else {
- this.documentTables = new HashtableOfObject[] {table};
- }
-}
-public char[] getWord() {
- return this.word;
-}
-public String[] getDocumentNames(Index index) throws java.io.IOException {
- if (this.documentTables != null) {
- int length = this.documentTables.length;
- if (length == 1 && this.documentNames == null) { // have a single table
- Object offset = this.documentTables[0].get(word);
- int[] numbers = index.diskIndex.readDocumentNumbers(offset);
- String[] names = new String[numbers.length];
- for (int i = 0, l = numbers.length; i < l; i++)
- names[i] = index.diskIndex.readDocumentName(numbers[i]);
- return names;
- }
-
- for (int i = 0; i < length; i++) {
- Object offset = this.documentTables[i].get(word);
- int[] numbers = index.diskIndex.readDocumentNumbers(offset);
- for (int j = 0, k = numbers.length; j < k; j++)
- addDocumentName(index.diskIndex.readDocumentName(numbers[j]));
- }
- }
-
- if (this.documentNames == null)
- return CharOperation.NO_STRINGS;
-
- String[] names = new String[this.documentNames.elementSize];
- int count = 0;
- Object[] values = this.documentNames.values;
- for (int i = 0, l = values.length; i < l; i++)
- if (values[i] != null)
- names[count++] = (String) values[i];
- return names;
-}
-public boolean isEmpty() {
- return this.documentTables == null && this.documentNames == null;
-}
-}
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
deleted file mode 100644
index 868f4831..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/index/Index.java
+++ /dev/null
@@ -1,213 +0,0 @@
-/*******************************************************************************
- * 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.index;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.regex.Pattern;
-
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfObject;
-import org.eclipse.wst.jsdt.internal.compiler.util.SimpleSet;
-import org.eclipse.wst.jsdt.internal.core.search.indexing.ReadWriteMonitor;
-
-/**
- * An <code>Index</code> maps document names to their referenced words in various categories.
- *
- * Queries can search a single category or several at the same time.
- *
- * Indexes are not synchronized structures and should only be queried/updated one at a time.
- */
-
-public class Index {
-
-public String containerPath;
-public ReadWriteMonitor monitor;
-
-protected DiskIndex diskIndex;
-protected MemoryIndex memoryIndex;
-
-/**
- * Mask used on match rule for indexing.
- */
-static final int MATCH_RULE_INDEX_MASK =
- SearchPattern.R_EXACT_MATCH |
- SearchPattern.R_PREFIX_MATCH |
- SearchPattern.R_PATTERN_MATCH |
- SearchPattern.R_REGEXP_MATCH |
- SearchPattern.R_CASE_SENSITIVE |
- SearchPattern.R_CAMELCASE_MATCH;
-
-public static boolean isMatch(char[] pattern, char[] word, int matchRule) {
- if (pattern == null) return true;
- int patternLength = pattern.length;
- int wordLength = word.length;
- if (patternLength == 0) return matchRule != SearchPattern.R_EXACT_MATCH;
- if (wordLength == 0) return (matchRule & SearchPattern.R_PATTERN_MATCH) != 0 && patternLength == 1 && pattern[0] == '*';
-
- // First test camel case if necessary
- boolean isCamelCase = (matchRule & SearchPattern.R_CAMELCASE_MATCH) != 0;
- if (isCamelCase && pattern[0] == word[0] && CharOperation.camelCaseMatch(pattern, word)) {
- return true;
- }
-
- // need to mask some bits of pattern rule (bug 79790)
- matchRule &= ~SearchPattern.R_CAMELCASE_MATCH;
- switch(matchRule & MATCH_RULE_INDEX_MASK) {
- case SearchPattern.R_EXACT_MATCH :
- if (!isCamelCase) {
- return patternLength == wordLength && CharOperation.equals(pattern, word, false);
- }
- // fall through prefix match if camel case failed
- case SearchPattern.R_PREFIX_MATCH :
- return patternLength <= wordLength && CharOperation.prefixEquals(pattern, word, false);
- case SearchPattern.R_PATTERN_MATCH :
- return CharOperation.match(pattern, word, false);
- case SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE :
- if (!isCamelCase) {
- return pattern[0] == word[0] && patternLength == wordLength && CharOperation.equals(pattern, word);
- }
- // fall through prefix match if camel case failed
- case SearchPattern.R_PREFIX_MATCH | SearchPattern.R_CASE_SENSITIVE :
- return pattern[0] == word[0] && patternLength <= wordLength && CharOperation.prefixEquals(pattern, word);
- case SearchPattern.R_PATTERN_MATCH | SearchPattern.R_CASE_SENSITIVE :
- return CharOperation.match(pattern, word, true);
- case SearchPattern.R_REGEXP_MATCH: {
- return Pattern.compile(new String(pattern), Pattern.CASE_INSENSITIVE).matcher(new String(word)).matches();
- }
- case SearchPattern.R_REGEXP_MATCH | SearchPattern.R_CASE_SENSITIVE: {
- return Pattern.matches(new String(pattern), new String(word));
- }
- }
- return false;
-}
-
-
-public Index(String fileName, String containerPath, boolean reuseExistingFile) throws IOException {
- this.containerPath = containerPath;
- this.monitor = new ReadWriteMonitor();
-
- this.memoryIndex = new MemoryIndex();
- this.diskIndex = new DiskIndex(fileName);
- this.diskIndex.initialize(reuseExistingFile);
-}
-public void addIndexEntry(char[] category, char[] key, String containerRelativePath) {
- this.memoryIndex.addIndexEntry(category, key, containerRelativePath);
-}
-public String containerRelativePath(String documentPath) {
- int index = documentPath.indexOf(IJavaScriptSearchScope.JAR_FILE_ENTRY_SEPARATOR);
- if (index == -1) {
-
- IPath containerPath = new Path(this.containerPath);
- IPath docPath = new Path(documentPath);
-
- if(containerPath.makeAbsolute().equals(docPath.makeAbsolute())) {
- return documentPath;
- }
-
- index = this.containerPath.length();
- if (documentPath.length() < index)
- throw new IllegalArgumentException("Document path " + documentPath + " must be relative to " + this.containerPath); //$NON-NLS-1$ //$NON-NLS-2$
- else if (documentPath.length()==index)
- index--;
- }
- return documentPath.substring(index + 1);
-}
-public File getIndexFile() {
- return this.diskIndex == null ? null : this.diskIndex.indexFile;
-}
-public boolean hasChanged() {
- return this.memoryIndex.hasChanged();
-}
-/**
- * Returns the entries containing the given key in a group of categories, or null if no matches are found.
- * The matchRule dictates whether its an exact, prefix or pattern match, as well as case sensitive or insensitive.
- * If the key is null then all entries in specified categories are returned.
- */
-public EntryResult[] query(char[][] categories, char[] key, int matchRule) throws IOException {
- if (this.memoryIndex.shouldMerge() && monitor.exitReadEnterWrite()) {
- try {
- save();
- } finally {
- monitor.exitWriteEnterRead();
- }
- }
-
- HashtableOfObject results;
- int rule = matchRule & MATCH_RULE_INDEX_MASK;
- if (this.memoryIndex.hasChanged()) {
- results = this.diskIndex.addQueryResults(categories, key, rule, this.memoryIndex);
- results = this.memoryIndex.addQueryResults(categories, key, rule, results);
- } else {
- results = this.diskIndex.addQueryResults(categories, key, rule, null);
- }
- if (results == null) return null;
-
- EntryResult[] entryResults = new EntryResult[results.elementSize];
- int count = 0;
- Object[] values = results.valueTable;
- for (int i = 0, l = values.length; i < l; i++) {
- EntryResult result = (EntryResult) values[i];
- if (result != null)
- entryResults[count++] = result;
- }
- return entryResults;
-}
-/**
- * Returns the document names that contain the given substring, if null then returns all of them.
- */
-public String[] queryDocumentNames(String substring) throws IOException {
- SimpleSet results;
- if (this.memoryIndex.hasChanged()) {
- results = this.diskIndex.addDocumentNames(substring, this.memoryIndex);
- this.memoryIndex.addDocumentNames(substring, results);
- } else {
- results = this.diskIndex.addDocumentNames(substring, null);
- }
- if (results.elementSize == 0) return null;
-
- String[] documentNames = new String[results.elementSize];
- int count = 0;
- Object[] paths = results.values;
- for (int i = 0, l = paths.length; i < l; i++)
- if (paths[i] != null)
- documentNames[count++] = (String) paths[i];
- return documentNames;
-}
-public void remove(String containerRelativePath) {
- this.memoryIndex.remove(containerRelativePath);
-}
-public void save() throws IOException {
- // must own the write lock of the monitor
- if (!hasChanged()) return;
-
- int numberOfChanges = this.memoryIndex.docsToReferences.elementSize;
- this.diskIndex = this.diskIndex.mergeWith(this.memoryIndex);
- this.memoryIndex = new MemoryIndex();
- if (numberOfChanges > 1000)
- System.gc(); // reclaim space if the MemoryIndex was very BIG
-}
-public void startQuery() {
- if (this.diskIndex != null)
- this.diskIndex.startQuery();
-}
-public void stopQuery() {
- if (this.diskIndex != null)
- this.diskIndex.stopQuery();
-}
-public String toString() {
- return "Index for " + this.containerPath; //$NON-NLS-1$
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/index/MemoryIndex.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/index/MemoryIndex.java
deleted file mode 100644
index 1fde9766..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/index/MemoryIndex.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.index;
-
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-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.core.util.SimpleWordSet;
-
-public class MemoryIndex {
-
-public int NUM_CHANGES = 100; // number of separate document changes... used to decide when to merge
-
-SimpleLookupTable docsToReferences; // document paths -> HashtableOfObject(category names -> set of words)
-SimpleWordSet allWords; // save space by locally interning the referenced words, since an indexer can generate numerous duplicates
-String lastDocumentName;
-HashtableOfObject lastReferenceTable;
-
-MemoryIndex() {
- this.docsToReferences = new SimpleLookupTable(7);
- this.allWords = new SimpleWordSet(7);
-}
-void addDocumentNames(String substring, SimpleSet results) {
- // assumed the disk index already skipped over documents which have been added/changed/deleted
- Object[] paths = this.docsToReferences.keyTable;
- Object[] referenceTables = this.docsToReferences.valueTable;
- if (substring == null) { // add all new/changed documents
- for (int i = 0, l = referenceTables.length; i < l; i++)
- if (referenceTables[i] != null)
- results.add(paths[i]);
- } else {
- for (int i = 0, l = referenceTables.length; i < l; i++)
- if (referenceTables[i] != null && ((String) paths[i]).startsWith(substring, 0))
- results.add(paths[i]);
- }
-}
-void addIndexEntry(char[] category, char[] key, String documentName) {
- HashtableOfObject referenceTable;
- if (documentName.equals(this.lastDocumentName))
- referenceTable = this.lastReferenceTable;
- else {
- // assumed a document was removed before its reindexed
- referenceTable = (HashtableOfObject) this.docsToReferences.get(documentName);
- if (referenceTable == null)
- this.docsToReferences.put(documentName, referenceTable = new HashtableOfObject(3));
- this.lastDocumentName = documentName;
- this.lastReferenceTable = referenceTable;
- }
-
- SimpleWordSet existingWords = (SimpleWordSet) referenceTable.get(category);
- if (existingWords == null) {
- existingWords = new SimpleWordSet(1);
- }
- existingWords.add(this.allWords.add(key));
- referenceTable.put(category,existingWords);
-
-
-}
-HashtableOfObject addQueryResults(char[][] categories, char[] key, int matchRule, HashtableOfObject results) {
- // assumed the disk index already skipped over documents which have been added/changed/deleted
- // results maps a word -> EntryResult
- Object[] paths = this.docsToReferences.keyTable;
- Object[] referenceTables = this.docsToReferences.valueTable;
- if (matchRule == (SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE) && key != null) {
- nextPath : for (int i = 0, l = referenceTables.length; i < l; i++) {
- HashtableOfObject categoryToWords = (HashtableOfObject) referenceTables[i];
- if (categoryToWords != null) {
- for (int j = 0, m = categories.length; j < m; j++) {
- SimpleWordSet wordSet = (SimpleWordSet) categoryToWords.get(categories[j]);
- if (wordSet != null && wordSet.includes(key)) {
- if (results == null)
- results = new HashtableOfObject(13);
- EntryResult result = (EntryResult) results.get(key);
- if (result == null)
- results.put(key, result = new EntryResult(key, null));
- result.addDocumentName((String) paths[i]);
- continue nextPath;
- }
- }
- }
- }
- } else {
- for (int i = 0, l = referenceTables.length; i < l; i++) {
- HashtableOfObject categoryToWords = (HashtableOfObject) referenceTables[i];
- if (categoryToWords != null) {
- for (int j = 0, m = categories.length; j < m; j++) {
- SimpleWordSet wordSet = (SimpleWordSet) categoryToWords.get(categories[j]);
- if (wordSet != null) {
- char[][] words = wordSet.words;
- for (int k = 0, n = words.length; k < n; k++) {
- char[] word = words[k];
- if (word != null && Index.isMatch(key, word, matchRule)) {
- if (results == null)
- results = new HashtableOfObject(13);
- EntryResult result = (EntryResult) results.get(word);
- if (result == null)
- results.put(word, result = new EntryResult(word, null));
- result.addDocumentName((String) paths[i]);
- }
- }
- }
- }
- }
- }
- }
- return results;
-}
-boolean hasChanged() {
- return this.docsToReferences.elementSize > 0;
-}
-void remove(String documentName) {
- if (documentName.equals(this.lastDocumentName)) {
- this.lastDocumentName = null;
- this.lastReferenceTable = null;
- }
- this.docsToReferences.put(documentName, null);
-}
-boolean shouldMerge() {
- return this.docsToReferences.elementSize >= NUM_CHANGES;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/BooleanValue.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/BooleanValue.java
deleted file mode 100644
index f7bf80b9..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/BooleanValue.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.interpret;
-
-public class BooleanValue extends Value {
-
- boolean value;
- public BooleanValue(boolean value) {
- super(BOOLEAN);
- this.value=value;
- }
- public boolean booleanValue() {
- return value;
- }
- public int numberValue() {
- return value? 1 : 0;
- }
- public String stringValue() {
- return value?"true":"false"; //$NON-NLS-1$ //$NON-NLS-2$
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/Contants.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/Contants.java
deleted file mode 100644
index 6cdfd9c2..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/Contants.java
+++ /dev/null
@@ -1,17 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.interpret;
-
-public interface Contants {
- final char[] VALUE_ARR=new char[]{'v','a','l','u','e' };
- final char[] PROTOTYPE_ARR=new char[]{'p','r','o','t','o','t','y','p','e' };
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/FunctionValue.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/FunctionValue.java
deleted file mode 100644
index 9d57dc03..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/FunctionValue.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.interpret;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration;
-
-public class FunctionValue extends ObjectValue {
-
- MethodDeclaration method;
- public ObjectValue prototype=new ObjectValue();
-
- protected FunctionValue(MethodDeclaration method) {
- super();
- this.type=Value.FUNCTION;
- this.method=method;
- }
-
-
- public Value getValue(char[] name) {
- if (CharOperation.equals(Contants.PROTOTYPE_ARR, name))
- return prototype;
- return super.getValue(name);
- }
-
-
- public void setValue(char[] name, Value value) {
- if (CharOperation.equals(Contants.PROTOTYPE_ARR, name))
- {
- if (value.type!=OBJECT)
- throw new InterpretException("invalid prototype"); //$NON-NLS-1$
- this.prototype=(ObjectValue)value;
- }
- super.setValue(name, value);
- }
-
-
- public Value execute(InterpreterEngine interpreter,ObjectValue receiver, Value[] arguments)
- {
- MethodDeclaration method=this.method;
- InterpreterContext context = interpreter.context=interpreter.newContext(interpreter.context,receiver, method);
- if (method.arguments!=null)
- for (int i=0;i<method.arguments.length;i++)
- {
- Value value=(i<arguments.length) ? arguments[i]:Value.NullObjectValue;
- if (i<arguments.length)
- context.setValue(method.arguments[i].name, value);
- }
- //TODO: crate "arguments" Array here
- interpreter.execBlock(method.statements);
- Value returnValue=context.returnValue;
- if (returnValue==null)
- returnValue=Value.UndefinedObjectValue;
-
- interpreter.restorePreviousContext();
- return returnValue;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/InterpretException.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/InterpretException.java
deleted file mode 100644
index 6ceeffd3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/InterpretException.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.interpret;
-
-public class InterpretException extends RuntimeException {
-
- /**
- *
- */
- private static final long serialVersionUID = -7863417691192829257L;
-
- public InterpretException() {
- super();
- }
-
- public InterpretException(String arg0) {
- super(arg0);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/InterpretedScript.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/InterpretedScript.java
deleted file mode 100644
index 1f225975..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/InterpretedScript.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.interpret;
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ProgramElement;
-import org.eclipse.wst.jsdt.internal.compiler.util.Util;
-
-public class InterpretedScript {
- public CompilationUnitDeclaration compilationUnit;
- int [] lineEnds;
- int sourceSize;
-
- public InterpretedScript(CompilationUnitDeclaration compilationUnit, int[] lineEnds, int sourceSize) {
- super();
- this.compilationUnit = compilationUnit;
- this.lineEnds = lineEnds;
- this.sourceSize=sourceSize;
- }
-
- public int lineNumber(ProgramElement element)
- {
- return Util.getLineNumber(element.sourceStart, lineEnds, 0, this.sourceSize);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/Interpreter.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/Interpreter.java
deleted file mode 100644
index bb942d2e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/Interpreter.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.interpret;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.Locale;
-import java.util.Map;
-
-import org.eclipse.wst.jsdt.internal.compiler.CompilationResult;
-import org.eclipse.wst.jsdt.internal.compiler.DefaultErrorHandlingPolicies;
-import org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.batch.CompilationUnit;
-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.parser.Parser;
-import org.eclipse.wst.jsdt.internal.compiler.problem.DefaultProblemFactory;
-import org.eclipse.wst.jsdt.internal.compiler.problem.ProblemReporter;
-import org.eclipse.wst.jsdt.internal.compiler.util.Util;
-
-public class Interpreter {
-
-
- public static InterpreterResult interpet(String code, InterpreterContext context)
- {
- InterpretedScript parsedUnit = parseString(code);
-
- InterpreterResult result = interpret(parsedUnit.compilationUnit, context);
-
- parsedUnit.compilationUnit.cleanUp();
-
- return result;
-
- }
-
-
- public static InterpretedScript parseFile(String fileName) {
- File file = new File(fileName);
- InterpretedScript unit=null;
- if (file.exists())
- {
- try {
- byte[] fileByteContent = Util.getFileByteContent(file);
- char[] chars = Util.bytesToChar(fileByteContent, Util.UTF_8);
- unit=parse(chars);
- } catch (IOException e) {
- }
- }
- return unit;
- }
-
- public static InterpretedScript parseString(String code) {
- char[] source = code.toCharArray();
- return parse(source);
- }
-
-
- private static InterpretedScript parse(char[] source) {
- Map options =new CompilerOptions().getMap();
-options.put(CompilerOptions.OPTION_ReportUnusedLocal, CompilerOptions.IGNORE);
- options.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_3);
- options.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
- options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
- CompilerOptions compilerOptions =new CompilerOptions(options);
-Parser parser =
- new Parser(
- new ProblemReporter(
- DefaultErrorHandlingPolicies.exitAfterAllProblems(),
- compilerOptions,
- new DefaultProblemFactory(Locale.getDefault())),
- true);
-
-ICompilationUnit sourceUnit = new CompilationUnit(source, "interpreted", null); //$NON-NLS-1$
-
-CompilationResult compilationUnitResult = new CompilationResult(sourceUnit, 0, 0, compilerOptions.maxProblemsPerUnit);
-CompilationUnitDeclaration parsedUnit = parser.parse(sourceUnit, compilationUnitResult);
-int[] lineEnds = parser.scanner.lineEnds;
-return new InterpretedScript(parsedUnit,lineEnds,parser.scanner.linePtr);
- }
-
- public static InterpreterResult interpret(CompilationUnitDeclaration ast, InterpreterContext context)
- {
-
- InterpreterEngine engine = new InterpreterEngine(context);
-
- return engine.interpret(ast);
-
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/InterpreterContext.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/InterpreterContext.java
deleted file mode 100644
index e0fed445..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/InterpreterContext.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.interpret;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfObject;
-import org.eclipse.wst.jsdt.internal.core.interpret.builtin.BuiltInHelper;
-
-public class InterpreterContext implements ValueReference{
-
- protected HashtableOfObject values=new HashtableOfObject();
- protected InterpreterContext parent;
- InterpreterContext lastReference;
- public Value returnValue;
- ValueReference thisObject;
- public int returnCode;
-
- public InterpreterContext() {
- this(null,null);
- }
-
- public InterpreterContext(InterpreterContext parent,ObjectValue thisObject) {
- this.parent=parent;
- this.thisObject= (thisObject!=null) ? thisObject : (ValueReference)globalContext();
-
- }
-
-
-
- public Value getValue(char [] name) {
-
- InterpreterContext checkContext=this;
- do {
- this.lastReference=checkContext;
- Value value=(Value) checkContext.values.get(name);
- if (value!=null)
- {
- return value;
- }
- checkContext=checkContext.parent;
- } while (checkContext!=null);
- return Value.UndefinedObjectValue;
- }
-
- public void setValue(char [] name, Value value) {
- values.put(name, value);
-
- }
-
- public ValueReference getReference(char [] name) {
- if (parent==null || values.containsKey(name))
- return this;
- return parent.getReference(name);
- }
-
- public void initailizeBuiltins() {
- BuiltInHelper.initializeBuiltinObjects(this);
-
- }
-
- public InterpreterContext globalContext()
- {
- InterpreterContext checkContext=this;
- while (checkContext.parent!=null)
- checkContext=checkContext.parent;
- return checkContext;
-
- }
-
- public List getContextStack()
- {
- ArrayList list=new ArrayList();
- InterpreterContext currentContext=this;
- while (currentContext!=null)
- {
- list.add(0, currentContext);
- currentContext=currentContext.parent;
- }
- return list;
- }
-
- public ValueReference getThisObject() {
- return thisObject;
- }
-
- public InterpreterContext getParent()
- {
- return this.parent;
- }
-}
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
deleted file mode 100644
index b41fe98a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/InterpreterEngine.java
+++ /dev/null
@@ -1,716 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.interpret;
-
-import org.eclipse.wst.jsdt.core.UnimplementedException;
-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.AllocationExpression;
-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.CompilationUnitDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ContinueStatement;
-import org.eclipse.wst.jsdt.internal.compiler.ast.EqualExpression;
-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.FieldReference;
-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.IntLiteral;
-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.NullLiteral;
-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.ReturnStatement;
-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.TrueLiteral;
-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.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ClassScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Scope;
-import org.eclipse.wst.jsdt.internal.core.interpret.builtin.BuiltInString;
-
-public class InterpreterEngine extends ASTVisitor implements Contants{
-
-
- protected InterpreterContext context;
- InterpreterResult result = new InterpreterResult();
-
- static final int STOP_RETURN =1;
- static final int STOP_BREAK =2;
- static final int STOP_CONTINUE =3;
- static final int STOP_THROW =4;
-
-
-
-
-
- class ExprStackItem extends Value{
- ValueReference reference;
- char [] referenceName;
- int value;
- Object objValue;
-
- ExprStackItem()
- {super(0);}
-
- public int numberValue()
- {
- switch (type)
- {
- case Value.BOOLEAN:
- case Value.NUMBER:
- return value;
- case Value.STRING:
- return Integer.valueOf((String)objValue).intValue();
- default:
- throw new UnimplementedException();
- }
- }
- public String stringValue()
- {
- switch (type)
- {
- case Value.BOOLEAN:
- return value!=0 ?"true":"false"; //$NON-NLS-1$ //$NON-NLS-2$
- case Value.NUMBER:
- return String.valueOf(value);
- case Value.STRING:
- return (String)objValue;
- default:
- throw new UnimplementedException();
- }
- }
-
- public boolean booleanValue()
- {
- switch (type)
- {
- case Value.BOOLEAN:
- case Value.NUMBER:
- return value!=0 ;
- case Value.STRING:
- return ((String)objValue).length()!=0;
- default:
- throw new UnimplementedException();
- }
- }
-
- public ObjectValue getObjectValue()
- {
-
-
- switch (type)
- {
- case OBJECT:
- case FUNCTION:
- return (ObjectValue)objValue;
- case UNDEFINED:
- throw new InterpretException("null reference"); //$NON-NLS-1$
- case BOOLEAN:
- {
- ObjectValue obj= new ObjectValue();
- obj.setValue(VALUE_ARR,this);
- return obj;
- }
- case NUMBER:
- {
- ObjectValue obj= new ObjectValue();
- obj.setValue(VALUE_ARR,this);
- return obj;
- }
- case STRING:
- {
- ObjectValue obj= new ObjectValue(BuiltInString.prototype);
- obj.setValue(VALUE_ARR,new StringValue(this.stringValue()));
- return obj;
- }
- }
- throw new UnimplementedException();
-
-
- }
-
- Value getValue()
- {
-
-
- switch (type)
- {
- case NULL:
- case UNDEFINED:
- return (Value)objValue;
- case BOOLEAN:
- return new BooleanValue(value!=0);
- case NUMBER:
- return new NumberValue(value);
- case STRING:
- return new StringValue((String)objValue);
- case OBJECT:
- return (ObjectValue)objValue;
- case FUNCTION:
- return (FunctionValue)objValue;
- }
-
- throw new UnimplementedException();
-
-
- }
-
- public Object valueObject() {
- return objValue;
- }
-
-
- }
-
- ExprStackItem []stack=new ExprStackItem[30];
- int stackPtr=-1;
-
-
- public InterpreterEngine(InterpreterContext context) {
- this.context=context;
-
- for (int i=0;i<stack.length;i++)
- stack[i]=new ExprStackItem();
- }
-
- public InterpreterResult interpret(CompilationUnitDeclaration ast)
- {
- if (ast.ignoreFurtherInvestigation)
- throw new InterpretException("compile errors"); //$NON-NLS-1$
-
- execBlock(ast.statements);
- if (stackPtr>=0)
- result.result=stack[stackPtr--];
- else
- result.result=Value.UndefinedObjectValue;
- return result;
- }
-
-
- public void endVisit(BinaryExpression binaryExpression, BlockScope scope) {
- ExprStackItem value2= stack[stackPtr--];
- ExprStackItem value1= stack[stackPtr--];
- int resultInt=0;
- Object resultObj=null;
- int type=Value.BOOLEAN; // most common
- int operator=(binaryExpression.bits & ASTNode.OperatorMASK) >> ASTNode.OperatorSHIFT;
- switch (operator)
- {
- case OperatorIds.PLUS:
- if (value1.type==Value.STRING || value2.type == Value.STRING)
- {
- resultObj = value1.stringValue()+value2.stringValue();
- type=Value.STRING;
- }
- else
- {
- resultInt = value1.numberValue()+value2.numberValue();
- type=Value.NUMBER;
- }
- break;
- case OperatorIds.MINUS:
- resultInt = value1.numberValue()-value2.numberValue();
- type=Value.NUMBER;
- break;
- case OperatorIds.DIVIDE:
- resultInt = value1.numberValue() / value2.numberValue();
- type=Value.NUMBER;
- break;
- case OperatorIds.MULTIPLY:
- resultInt = value1.numberValue() * value2.numberValue();
- type=Value.NUMBER;
- break;
- case OperatorIds.REMAINDER:
- resultInt = value1.numberValue() % value2.numberValue();
- type=Value.NUMBER;
- break;
- case OperatorIds.GREATER:
- resultInt = (value1.numberValue() > value2.numberValue()) ?1:0;
- break;
- case OperatorIds.GREATER_EQUAL:
- resultInt = (value1.numberValue() >= value2.numberValue())?1:0;
- break;
- case OperatorIds.LESS:
- resultInt = (value1.numberValue() < value2.numberValue())?1:0;
- break;
- case OperatorIds.LESS_EQUAL:
- resultInt = (value1.numberValue() <= value2.numberValue())?1:0;
- break;
- case OperatorIds.AND_AND:
- resultInt = (value1.booleanValue() && value2.booleanValue())?1:0;
- break;
- case OperatorIds.AND:
- resultInt = value1.numberValue() & value2.numberValue();
- break;
- case OperatorIds.OR:
- resultInt = value1.numberValue() | value2.numberValue();
- break;
- case OperatorIds.OR_OR:
- resultInt = (value1.booleanValue() || value2.booleanValue())?1:0;
- break;
- default:
- throw new UnimplementedException(""); //$NON-NLS-1$
-
- }
-
- pushValue(type,resultInt,resultObj);
-
- }
-
- public void endVisit(EqualExpression equalExpression, BlockScope scope) {
- ExprStackItem value2= stack[stackPtr--];
- ExprStackItem value1= stack[stackPtr--];
- int type=Value.BOOLEAN; // most common
- boolean equal=false;
- int operator=(equalExpression.bits & ASTNode.OperatorMASK) >> ASTNode.OperatorSHIFT;
- switch (operator)
- {
- case OperatorIds.EQUAL_EQUAL:
- case OperatorIds.NOT_EQUAL:
-
- switch (value1.type)
- {
- case Value.NUMBER:
- case Value.BOOLEAN:
- equal=value1.numberValue()==value2.numberValue(); break;
- case Value.STRING:
- if (value2.type==Value.NUMBER)
- equal=value1.numberValue()==value2.numberValue();
- else
- equal=value1.stringValue().equals(value2.stringValue());
- break;
- case Value.UNDEFINED:
- case Value.NULL:
- equal=(value2.type==Value.UNDEFINED || value2.type==Value.NULL); break;
- default:
- equal=(value1.objValue==value2.objValue);
-
- }
- if (operator==OperatorIds.NOT_EQUAL)
- equal = !equal;
- break;
- case OperatorIds.EQUAL_EQUAL_EQUAL:
- case OperatorIds.NOT_EQUAL_EQUAL:
- if (value1.type==value2.type)
- {
- switch (value1.type)
- {
- case Value.NUMBER:
- case Value.BOOLEAN:
- equal=value1.value==value2.value; break;
- case Value.STRING:
- equal=value1.stringValue().equals(value2.stringValue());
- break;
- case Value.UNDEFINED:
- case Value.NULL:
- equal=true; break;
- default:
- equal=(value1.objValue==value2.objValue);
- }
- }
- if (operator==OperatorIds.NOT_EQUAL_EQUAL)
- equal = !equal;
- break;
- default:
- throw new UnimplementedException(""); //$NON-NLS-1$
-
- }
-
- pushValue(type,equal? 1:0,null);
-
- }
-
-
- public boolean visit(PostfixExpression postfixExpression, BlockScope scope) {
- ExprStackItem value= execute(postfixExpression.lhs);
- if (value.reference==null)
- throw new InterpretException("invalid assigment left hand side"); //$NON-NLS-1$
-
- int number=value.numberValue();
- int orgNumber=number;
-
- switch (postfixExpression.operator) {
- case OperatorIds.PLUS :
- number++; //$NON-NLS-1$
- break;
- case OperatorIds.MINUS :
- number++; //$NON-NLS-1$
- break;
- }
- Value newValue = new NumberValue(number);
- value.reference.setValue(value.referenceName, newValue);
- pushNumber(orgNumber);
- return false;
- }
-
- public boolean visit(PrefixExpression prefixExpression, BlockScope scope) {
- ExprStackItem value= execute(prefixExpression.lhs);
- if (value.reference==null)
- throw new InterpretException("invalid assigment left hand side"); //$NON-NLS-1$
-
- int number=value.numberValue();
-
- switch (prefixExpression.operator) {
- case OperatorIds.PLUS :
- number++; //$NON-NLS-1$
- break;
- case OperatorIds.MINUS :
- number++; //$NON-NLS-1$
- break;
- }
- Value newValue = new NumberValue(number);
- value.reference.setValue(value.referenceName, newValue);
- pushNumber(number);
- return false;
- }
-
- private void pushValue(int type,int value,Object objValue)
- {
- if (++stackPtr >=stack.length)
- {
- ExprStackItem []newStack=new ExprStackItem[stack.length*2];
- System.arraycopy(stack, 0, newStack, 0, stack.length);
- for (int i=stack.length;i<newStack.length;i++)
- newStack[i]=new ExprStackItem();
- stack=newStack;
-
- }
- stack[stackPtr].type=type;
- stack[stackPtr].value=value;
- stack[stackPtr].objValue=objValue;
- }
-
- private void pushNumber(int number)
- {
- pushValue(Value.NUMBER,number,null);
- }
-
- private void pushString (String string)
- {
- pushValue(Value.STRING,0,string);
- }
-
- private void pushExprStackItem(ExprStackItem item)
- {
- pushValue(item.type,item.value,item.objValue);
- }
- private void pushReference(ValueReference reference,char[] name,Value value)
- {
- pushValue(value,false);
- stack[stackPtr].reference=reference;
- stack[stackPtr].referenceName=name;
- }
-
- private void pushValue(Value value,boolean allowUndefined) {
- int type=0;
- int intValue=0;
- Object objValue=null;
- if (value!=null && (value.type!=Value.UNDEFINED || allowUndefined))
- {
- type=value.type;
- switch (type)
- {
- case Value.BOOLEAN:
- case Value.NUMBER:
- intValue=value.numberValue(); break;
- case Value.STRING:
- objValue=value.stringValue(); break;
-
- default:
- objValue=value;
- }
- }
- pushValue(type,intValue,objValue);
- }
-
-
- public boolean visit(IntLiteral intLiteral, BlockScope scope) {
- int value=(intLiteral.source==null)? intLiteral.value : Integer.valueOf(new String(intLiteral.source)).intValue();
- pushNumber(value);
- return true;
- }
-
- public boolean visit(SingleNameReference singleNameReference, BlockScope scope) {
- char [] name=singleNameReference.token;
- Value value=this.context.getValue(name);
- pushReference(this.context.lastReference, name, value);
- return true;
- }
-
- public boolean visit(SingleNameReference singleNameReference, ClassScope scope) {
- return visit(singleNameReference,(BlockScope) null);
- }
-
- public void endVisit(Assignment assignment, BlockScope scope) {
- ExprStackItem assignValue= stack[stackPtr--];
- ExprStackItem refValue= stack[stackPtr--];
- if (refValue.reference==null)
- throw new InterpretException("invalid assigment left hand side"); //$NON-NLS-1$
- refValue.reference.setValue(refValue.referenceName, assignValue.getValue());
- pushExprStackItem(assignValue);
- }
-
- public void endVisit(ObjectLiteralField field, BlockScope scope) {
- ExprStackItem fieldValue= stack[stackPtr--];
- --stackPtr;//name
- ObjectValue object=(ObjectValue)stack[stackPtr].objValue;
- char [] name=null;
- if (field.fieldName instanceof SingleNameReference)
- name=((SingleNameReference)field.fieldName).token;
- else if (field.fieldName instanceof StringLiteral)
- name=((StringLiteral)field.fieldName).source();
- else
- throw new InterpretException("invalid object literal field"); //$NON-NLS-1$
- object.setValue(name, fieldValue);
- }
-
- public boolean visit(ObjectLiteral literal, BlockScope scope) {
- pushValue(Value.OBJECT, 0, new ObjectValue());
- return true;
- }
-
- protected ExprStackItem execute(Expression expr)
- {
- expr.traverse(this,(BlockScope) null);
- ExprStackItem value= stack[stackPtr--];
- return value;
- }
-
- public boolean visit(FieldReference fieldReference, BlockScope scope) {
- Value receiver=execute(fieldReference.receiver);
- ObjectValue object=receiver.getObjectValue();
- pushReference(object,fieldReference.token,object.getValue(fieldReference.token));
- return false;
- }
- public boolean visit(ThisReference thisReference, BlockScope scope) {
- ObjectValue value=null;
- if (this.context.thisObject instanceof ObjectValue)
- value=(ObjectValue)this.context.thisObject;
- pushValue(value, false);
- return false;
- }
- public boolean visit(MethodDeclaration methodDeclaration, Scope scope) {
- FunctionValue func=new FunctionValue(methodDeclaration);
- this.context.setValue(methodDeclaration.selector, func);
-
- return false;
- }
-
- public boolean visit(FunctionExpression functionExpression, BlockScope scope) {
- FunctionValue func=new FunctionValue(functionExpression.methodDeclaration);
- pushValue(func, false);
- return false;
- }
-
- public boolean visit(MessageSend messageSend, BlockScope scope) {
- FunctionValue function=null;
-
- ValueReference receiverObj=this.context;
- Value receiver=null;
- if (messageSend.receiver!=null)
- {
- receiver=execute(messageSend.receiver);
- if (receiver.type==Value.FUNCTION && messageSend.selector==null)
- function=(FunctionValue) receiver.valueObject();
- else
- receiverObj=receiver.getObjectValue();
-
- }
-
- if (function==null)
- {
- receiver=receiverObj.getValue(messageSend.selector);
- if (receiver.type==Value.FUNCTION)
- function=(FunctionValue)receiver;
- else
- throw new InterpretException("not a function:"+new String((messageSend.selector))); //$NON-NLS-1$
-
- }
-
- int restoreStackPtr=this.stackPtr;
- Value [] arguments;
- if (messageSend.arguments!=null)
- {
- arguments= new Value[messageSend.arguments.length];
- for (int i = 0; i < arguments.length; i++) {
- arguments[i]=execute(messageSend.arguments[i]);
- this.stackPtr++;
- }
- }
- else
- arguments=new Value[0];
- if (!(receiverObj instanceof ObjectValue))
- receiverObj=null;
- Value returnValue=function.execute(this, (ObjectValue)receiverObj, arguments);
- this.stackPtr=restoreStackPtr;
- pushValue(returnValue,true);
- return false;
- }
-
- protected int execBlock(ProgramElement[] statements) {
- this.context.returnCode=0;
- for (int i = 0; i < statements.length && this.context.returnCode==0; i++) {
- statements[i].traverse(this, null);
- }
- return this.context.returnCode;
- }
-
- protected int execStatement(ProgramElement statement) {
- this.context.returnCode=0;
- if (statement==null)
- return 0;
- statement.traverse(this, null);
- return this.context.returnCode;
- }
-
-
-
- public boolean visit(AllocationExpression allocationExpression, BlockScope scope) {
- Value value = execute(allocationExpression.member);
- if (value.type!=Value.FUNCTION)
- throw new InterpretException("not a function:"+allocationExpression.member.toString()); //$NON-NLS-1$
- FunctionValue function= (FunctionValue) value.valueObject();
-
- ObjectValue receiver = new ObjectValue(function.prototype);
-
- int restoreStackPtr=this.stackPtr;
- Value [] arguments;
- if (!allocationExpression.isShort && allocationExpression.arguments!=null)
- {
- arguments= new Value[allocationExpression.arguments.length];
- for (int i = 0; i < arguments.length; i++) {
- arguments[i]=execute(allocationExpression.arguments[i]);
- this.stackPtr++;
- }
- }
- else
- arguments= new Value[0];
-
- function.execute(this, receiver, arguments);
- this.stackPtr=restoreStackPtr;
- pushValue(receiver,false);
-
- return false;
- }
-
- public boolean visit(FalseLiteral falseLiteral, BlockScope scope) {
- pushValue(Value.BOOLEAN, 0, null);
- return false;
- }
-
- public boolean visit(NullLiteral nullLiteral, BlockScope scope) {
- pushValue(Value.NULL, 1, Value.NullObjectValue);
- return false;
- }
-
- public boolean visit(UndefinedLiteral undefined, BlockScope scope) {
- pushValue(Value.UNDEFINED, 1, Value.UndefinedObjectValue);
- return false;
- }
-
-
- public boolean visit(StringLiteral stringLiteral, BlockScope scope) {
- pushString(new String(stringLiteral.source()));
- return false;
- }
-
- public boolean visit(TrueLiteral trueLiteral, BlockScope scope) {
- pushValue(Value.BOOLEAN, 1, null);
- return false;
- }
-
- public boolean visit(ReturnStatement returnStatement, BlockScope scope) {
- Value returnValue=Value.UndefinedObjectValue;
- if (returnStatement.expression!=null)
- returnValue = execute(returnStatement.expression);
- this.context.returnValue=returnValue;
- this.context.returnCode=STOP_RETURN;
- return false;
- }
-
- public boolean visit(LocalDeclaration localDeclaration, BlockScope scope) {
- Value value = Value.UndefinedObjectValue;
- if (localDeclaration.initialization!=null)
- value=execute(localDeclaration.initialization);
- this.context.setValue(localDeclaration.name, value.getValue());
- return false;
- }
-
- public boolean visit(Block block, BlockScope scope) {
- execBlock(block.statements);
- return false;
- }
-
- public boolean visit(IfStatement ifStatement, BlockScope scope) {
- Value condition=execute(ifStatement.condition);
- if (condition.booleanValue())
- execStatement(ifStatement.thenStatement);
- else
- execStatement(ifStatement.elseStatement);
-
- return false;
- }
-
- public boolean visit(WhileStatement whileStatement, BlockScope scope) {
- while (true)
- {
- Value condition=execute(whileStatement.condition);
- if (condition.booleanValue())
- {
- int returnCode=execStatement(whileStatement.action);
- if (returnCode!=0 && returnCode!=STOP_CONTINUE)
- return false;
- }
- else
- return false;
- }
- }
-
- public boolean visit(BreakStatement breakStatement, BlockScope scope) {
- this.context.returnCode=STOP_BREAK;
- return false;
- }
-
- public boolean visit(ContinueStatement continueStatement, BlockScope scope) {
- this.context.returnCode=STOP_CONTINUE;
- return false;
- }
-
-
-
- protected InterpreterContext newContext(InterpreterContext parent,ObjectValue thisObject, ProgramElement method)
- {
- return new InterpreterContext( parent, thisObject);
- }
-
- public void restorePreviousContext() {
- this.context=this.context.parent;
- }
-
-
-
-
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/InterpreterResult.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/InterpreterResult.java
deleted file mode 100644
index 7640dd4c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/InterpreterResult.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.interpret;
-
-public class InterpreterResult {
-
- InterpretException exception;
- Object result;
-
- public boolean hasErrors()
- {
- return exception!=null;
- }
-
- public Object getResult()
- {
- return result;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/NativeFunction.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/NativeFunction.java
deleted file mode 100644
index c0d849d8..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/NativeFunction.java
+++ /dev/null
@@ -1,20 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.interpret;
-
-
-public class NativeFunction extends FunctionValue {
-
- protected NativeFunction() {
- super(null);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/NativeObject.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/NativeObject.java
deleted file mode 100644
index ef2c6438..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/NativeObject.java
+++ /dev/null
@@ -1,15 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.interpret;
-
-public class NativeObject extends ObjectValue {
- Object nativeObject;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/NumberValue.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/NumberValue.java
deleted file mode 100644
index 29ab7b44..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/NumberValue.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.interpret;
-
-public class NumberValue extends Value{
-
- int intValue;
-
- public NumberValue(int value)
- {
- super(NUMBER);
- this.intValue=value;
- }
-
-
- public int numberValue()
- {
- return intValue;
- }
- public String stringValue()
- {
- return String.valueOf(intValue);
- }
-
- public boolean booleanValue() { return (intValue==0) ? false:true;}
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/ObjectValue.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/ObjectValue.java
deleted file mode 100644
index e75fea58..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/ObjectValue.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.interpret;
-
-import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfObject;
-
-public class ObjectValue extends Value implements ValueReference {
-
- public HashtableOfObject properties=new HashtableOfObject();
- public ObjectValue() {
- super(OBJECT);
- }
- public ObjectValue(ObjectValue prototype) {
- super(OBJECT);
- if (prototype!=null)
- try {
- properties=(HashtableOfObject)prototype.properties.clone();
- } catch (CloneNotSupportedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- public Value getValue(char[] name) {
- return (Value)properties.get(name);
- }
- public void setValue(char [] name, Value value) {
- properties.put(name, value);
- }
-
- public String stringValue()
- {
- Value value = (Value)properties.get(VALUE_ARR);
- if (value!=null)
- return value.stringValue();
- return ""; //$NON-NLS-1$
- }
-
- public ObjectValue getObjectValue()
- {
- return this;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/StringValue.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/StringValue.java
deleted file mode 100644
index 955f8ebe..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/StringValue.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.interpret;
-
-public class StringValue extends Value {
-
- String stringValue;
-
- public StringValue(String value) {
- super(Value.STRING);
- this.stringValue=value;
- }
-
-
- public boolean booleanValue() {
- return stringValue.length()!=0;
- }
-
- public int numberValue() {
- return Integer.valueOf(stringValue).intValue();
- }
-
- public String stringValue() {
- return stringValue;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/Value.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/Value.java
deleted file mode 100644
index cd932998..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/Value.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.interpret;
-
-import org.eclipse.wst.jsdt.core.UnimplementedException;
-
-public class Value implements Contants {
- public static final int BOOLEAN =1;
- public static final int NUMBER = 2;
- public static final int STRING = 3;
- public static final int OBJECT = 4;
- public static final int UNDEFINED = 5;
- public static final int NULL = 6;
- public static final int FUNCTION = 7;
-
- int type;
-
- public static Value UndefinedObjectValue=new Value(UNDEFINED);
- public static Value NullObjectValue=new Value(NULL);
-
-
- protected Value(int type)
- {
- this.type=type;
- }
-
- public int numberValue()
- {
- return 0;
- }
-
- public final int getType()
- {return type;}
-
- public String stringValue()
- {
- switch (type)
- {
- case NULL:
- return "null"; //$NON-NLS-1$
- case UNDEFINED:
- return "undefined"; //$NON-NLS-1$
- }
- return ""; //$NON-NLS-1$
- }
- public boolean booleanValue() {return false;}
-
- public ObjectValue getObjectValue()
- {
-
-
- switch (type)
- {
- case NULL:
- case UNDEFINED:
- throw new InterpretException("null reference"); //$NON-NLS-1$
- case BOOLEAN:
- case NUMBER:
- case STRING:
- ObjectValue obj= new ObjectValue();
- obj.setValue(VALUE_ARR,this);
- return obj;
- }
-
- throw new UnimplementedException();
-
-
- }
-
- public Object valueObject() {
- return null;
- }
-
- Value getValue()
- {
- return this;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/ValueReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/ValueReference.java
deleted file mode 100644
index fa1d1352..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/ValueReference.java
+++ /dev/null
@@ -1,18 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.interpret;
-
-public interface ValueReference {
-
- Value getValue(char [] name);
- void setValue(char [] name, Value value);
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/builtin/BuiltInHelper.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/builtin/BuiltInHelper.java
deleted file mode 100644
index 51b415cb..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/builtin/BuiltInHelper.java
+++ /dev/null
@@ -1,22 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.interpret.builtin;
-
-import org.eclipse.wst.jsdt.internal.core.interpret.InterpreterContext;
-
-public class BuiltInHelper {
-
- public static void initializeBuiltinObjects(InterpreterContext context)
- {
- BuiltInObject.initializeContext(context);
- BuiltInString.initializeContext(context);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/builtin/BuiltInObject.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/builtin/BuiltInObject.java
deleted file mode 100644
index b2db2b74..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/builtin/BuiltInObject.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.interpret.builtin;
-
-import org.eclipse.wst.jsdt.internal.core.interpret.BooleanValue;
-import org.eclipse.wst.jsdt.internal.core.interpret.InterpreterContext;
-import org.eclipse.wst.jsdt.internal.core.interpret.InterpreterEngine;
-import org.eclipse.wst.jsdt.internal.core.interpret.NativeFunction;
-import org.eclipse.wst.jsdt.internal.core.interpret.ObjectValue;
-import org.eclipse.wst.jsdt.internal.core.interpret.StringValue;
-import org.eclipse.wst.jsdt.internal.core.interpret.Value;
-
-public class BuiltInObject {
-
- public static ObjectValue prototype;
-
- public static void initializeContext(InterpreterContext context) {
-
- prototype = new ObjectValue();
-
- prototype.setValue("toString".toCharArray(), //$NON-NLS-1$
- new NativeFunction() {
-
- public Value execute(InterpreterEngine interpreter,ObjectValue receiver, Value[] arguments) {
- if (receiver.getType()==Value.STRING)
- return receiver;
- return new StringValue(receiver.stringValue());
- }
-
- });
-
- prototype.setValue("hasProperty".toCharArray(), //$NON-NLS-1$
- new NativeFunction() {
-
- public Value execute(InterpreterEngine interpreter,ObjectValue receiver, Value[] arguments) {
- if (arguments.length>0)
- return new BooleanValue(receiver.properties.containsKey(arguments[0].stringValue().toCharArray()));
- return new BooleanValue(false);
- }
-
- });
-
-
- NativeFunction constructor = new NativeFunction() {
-
- public Value execute(InterpreterEngine interpreter,ObjectValue receiver, Value[] arguments) {
-
- return Value.UndefinedObjectValue;
- }
- };
- constructor.prototype=prototype;
-
- context.setValue(new char[]{'O','b','j','e','c','t'},constructor);
-
-
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/builtin/BuiltInString.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/builtin/BuiltInString.java
deleted file mode 100644
index a7b1194d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/builtin/BuiltInString.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.interpret.builtin;
-
-import org.eclipse.wst.jsdt.internal.core.interpret.InterpreterContext;
-import org.eclipse.wst.jsdt.internal.core.interpret.InterpreterEngine;
-import org.eclipse.wst.jsdt.internal.core.interpret.NativeFunction;
-import org.eclipse.wst.jsdt.internal.core.interpret.NumberValue;
-import org.eclipse.wst.jsdt.internal.core.interpret.ObjectValue;
-import org.eclipse.wst.jsdt.internal.core.interpret.Value;
-
-public class BuiltInString {
-
-
- public static ObjectValue prototype;
-
- public static void initializeContext(InterpreterContext context) {
-
- prototype = new ObjectValue(BuiltInObject.prototype);
-
- prototype.setValue("indexOf".toCharArray(), //$NON-NLS-1$
- new NativeFunction() {
-
- public Value execute(InterpreterEngine interpreter,ObjectValue receiver, Value[] arguments) {
- String str=receiver.stringValue();
- String searchStr="";
- int fromIndex=0;
- if (arguments.length>0)
- searchStr=arguments[0].stringValue();
- if (arguments.length>1)
- fromIndex=arguments[1].numberValue();
- int index = str.indexOf(searchStr, fromIndex);
- return new NumberValue(index);
- }
-
- });
-
-
- NativeFunction constructor = new NativeFunction() {
-
- public Value execute(InterpreterEngine interpreter,ObjectValue receiver, Value[] arguments) {
-
- return Value.UndefinedObjectValue;
- }
- };
- constructor.prototype=prototype;
-
- context.setValue(new char[]{'S','t','r','i','n','g'},constructor);
-
-
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/AbstractSearchScope.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/AbstractSearchScope.java
deleted file mode 100644
index 24c67af2..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/AbstractSearchScope.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * 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.wst.jsdt.core.IJavaScriptElementDelta;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-
-public abstract class AbstractSearchScope implements IJavaScriptSearchScope {
-
-/* (non-Javadoc)
- * Process the given delta and refresh its internal state if needed.
- * Returns whether the internal state was refreshed.
- */
-public abstract void processDelta(IJavaScriptElementDelta delta);
-
-public boolean shouldExclude(String container, String resourceName) {
- 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
deleted file mode 100644
index baa3bc4b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/BasicSearchEngine.java
+++ /dev/null
@@ -1,1640 +0,0 @@
-/*******************************************************************************
- * 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.search;
-
-import java.util.HashMap;
-import java.util.HashSet;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IMember;
-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.WorkingCopyOwner;
-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.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-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.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;
-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.env.AccessRestriction;
-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;
-import org.eclipse.wst.jsdt.internal.compiler.problem.DefaultProblemFactory;
-import org.eclipse.wst.jsdt.internal.compiler.problem.ProblemReporter;
-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.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.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.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.util.Messages;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * Search basic engine. Public search engine (see {@link org.eclipse.wst.jsdt.core.search.SearchEngine}
- * for detailed comment), now uses basic engine functionalities.
- * Note that search basic engine does not implement depreciated functionalities...
- */
-public class BasicSearchEngine {
-
- /*
- * A default parser to parse non-reconciled working copies
- */
- private Parser parser;
- private CompilerOptions compilerOptions;
-
- /*
- * A list of working copies that take precedence over their original
- * compilation units.
- */
- private IJavaScriptUnit[] workingCopies;
-
- /*
- * A working copy owner whose working copies will take precedent over
- * their original compilation units.
- */
- private WorkingCopyOwner workingCopyOwner;
-
- /**
- * For tracing purpose.
- */
- public static boolean VERBOSE = false;
-
- /*
- * Creates a new search basic engine.
- */
- public BasicSearchEngine() {
- // will use working copies of PRIMARY owner
- }
-
- /**
- * @see org.eclipse.wst.jsdt.core.search.SearchEngine#SearchEngine(IJavaScriptUnit[]) for detailed comment.
- */
- public BasicSearchEngine(IJavaScriptUnit[] workingCopies) {
- this.workingCopies = workingCopies;
- }
-
- char convertTypeKind(int typeDeclarationKind) {
- switch(typeDeclarationKind) {
- case TypeDeclaration.CLASS_DECL : return IIndexConstants.CLASS_SUFFIX;
- default : return IIndexConstants.TYPE_SUFFIX;
- }
- }
- /**
- * @see org.eclipse.wst.jsdt.core.search.SearchEngine#SearchEngine(WorkingCopyOwner) for detailed comment.
- */
- public BasicSearchEngine(WorkingCopyOwner workingCopyOwner) {
- this.workingCopyOwner = workingCopyOwner;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.core.search.SearchEngine#createHierarchyScope(IType) for detailed comment.
- */
- public static IJavaScriptSearchScope createHierarchyScope(IType type) throws JavaScriptModelException {
- return createHierarchyScope(type, DefaultWorkingCopyOwner.PRIMARY);
- }
-
- /**
- * @see org.eclipse.wst.jsdt.core.search.SearchEngine#createHierarchyScope(IType,WorkingCopyOwner) for detailed comment.
- */
- public static IJavaScriptSearchScope createHierarchyScope(IType type, WorkingCopyOwner owner) throws JavaScriptModelException {
- return new HierarchyScope(type, owner);
- }
-
- /**
- * @see org.eclipse.wst.jsdt.core.search.SearchEngine#createJavaSearchScope(IJavaScriptElement[]) for detailed comment.
- */
- public static IJavaScriptSearchScope createJavaSearchScope(IJavaScriptElement[] elements) {
- return createJavaSearchScope(elements, true);
- }
-
- /**
- * @see org.eclipse.wst.jsdt.core.search.SearchEngine#createJavaSearchScope(IJavaScriptElement[], boolean) for detailed comment.
- */
- public static IJavaScriptSearchScope createJavaSearchScope(IJavaScriptElement[] elements, boolean includeReferencedProjects) {
- int includeMask = IJavaScriptSearchScope.SOURCES | IJavaScriptSearchScope.APPLICATION_LIBRARIES | IJavaScriptSearchScope.SYSTEM_LIBRARIES;
- if (includeReferencedProjects) {
- includeMask |= IJavaScriptSearchScope.REFERENCED_PROJECTS;
- }
- return createJavaSearchScope(elements, includeMask);
- }
-
- /**
- * @see org.eclipse.wst.jsdt.core.search.SearchEngine#createJavaSearchScope(IJavaScriptElement[], int) for detailed comment.
- */
- public static IJavaScriptSearchScope createJavaSearchScope(IJavaScriptElement[] elements, int includeMask) {
- JavaSearchScope scope = new JavaSearchScope();
- HashSet visitedProjects = new HashSet(2);
- for (int i = 0, length = elements.length; i < length; i++) {
- IJavaScriptElement element = elements[i];
- if (element != null) {
- try {
- if (element instanceof JavaProject) {
- scope.add((JavaProject)element, includeMask, visitedProjects);
- } else {
- scope.add(element);
- }
- } catch (JavaScriptModelException e) {
- // ignore
- }
- }
- }
- return scope;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.core.search.SearchEngine#createTypeNameMatch(IType, int) for detailed comment.
- */
- public static TypeNameMatch createTypeNameMatch(IType type, int modifiers) {
- return new JavaSearchTypeNameMatch(type, modifiers);
- }
-
- /**
- * @see org.eclipse.wst.jsdt.core.search.SearchEngine#createWorkspaceScope() for detailed comment.
- */
- public static IJavaScriptSearchScope createWorkspaceScope() {
- return JavaModelManager.getJavaModelManager().getWorkspaceScope();
- }
-
- /**
- * Searches for matches to a given query. Search queries can be created using helper
- * methods (from a String pattern or a Java element) and encapsulate the description of what is
- * being searched (for example, search method declarations in a case sensitive way).
- *
- * @param scope the search result has to be limited to the given scope
- * @param requestor a callback object to which each match is reported
- */
- void findMatches(SearchPattern pattern, SearchParticipant[] participants, IJavaScriptSearchScope scope, SearchRequestor requestor, IProgressMonitor monitor) throws CoreException {
- if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException();
- try {
- if (VERBOSE) {
- Util.verbose("Searching for pattern: " + pattern.toString()); //$NON-NLS-1$
- Util.verbose(scope.toString());
- }
- if (participants == null) {
- if (VERBOSE) Util.verbose("No participants => do nothing!"); //$NON-NLS-1$
- return;
- }
-
- /* initialize progress monitor */
- int length = participants.length;
- if (monitor != null)
- monitor.beginTask(Messages.engine_searching, 100 * length);
- IndexManager indexManager = JavaModelManager.getJavaModelManager().getIndexManager();
- requestor.beginReporting();
- for (int i = 0; i < length; i++) {
- if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException();
-
- SearchParticipant participant = participants[i];
- try {
- if (monitor != null) monitor.subTask(Messages.bind(Messages.engine_searching_indexing, new String[] {participant.getDescription()}));
- participant.beginSearching();
- requestor.enterParticipant(participant);
- PathCollector pathCollector = new PathCollector();
- indexManager.performConcurrentJob(
- new PatternSearchJob(pattern, participant, scope, pathCollector),
- IJavaScriptSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
- monitor==null ? null : new SubProgressMonitor(monitor, 50));
- if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException();
-
- // locate index matches if any (note that all search matches could have been issued during index querying)
- if (monitor != null) monitor.subTask(Messages.bind(Messages.engine_searching_matching, new String[] {participant.getDescription()}));
- String[] indexMatchPaths = pathCollector.getPaths();
- if (indexMatchPaths != null) {
- pathCollector = null; // release
- int indexMatchLength = indexMatchPaths.length;
- SearchDocument[] indexMatches = new SearchDocument[indexMatchLength];
- for (int j = 0; j < indexMatchLength; j++) {
- indexMatches[j] = participant.getDocument(indexMatchPaths[j]);
- }
- SearchDocument[] matches = MatchLocator.addWorkingCopies(pattern, indexMatches, getWorkingCopies(), participant);
- participant.locateMatches(matches, pattern, scope, requestor, monitor==null ? null : new SubProgressMonitor(monitor, 50));
- }
- } finally {
- requestor.exitParticipant(participant);
- participant.doneSearching();
- }
- }
- } finally {
- requestor.endReporting();
- if (monitor != null)
- monitor.done();
- }
- }
- /**
- * Returns a new default Java search participant.
- *
- * @return a new default Java search participant
- * @since 3.0
- */
- public static SearchParticipant getDefaultSearchParticipant() {
- return new JavaSearchParticipant();
- }
-
-
- /**
- * @param matchRule
- */
- public static String getMatchRuleString(final int matchRule) {
- if (matchRule == 0) {
- return "R_EXACT_MATCH"; //$NON-NLS-1$
- }
- StringBuffer buffer = new StringBuffer();
- for (int i=1; i<=8; i++) {
- int bit = matchRule & (1<<(i-1));
- if (bit != 0 && buffer.length()>0) buffer.append(" | "); //$NON-NLS-1$
- switch (bit) {
- case SearchPattern.R_PREFIX_MATCH:
- buffer.append("R_PREFIX_MATCH"); //$NON-NLS-1$
- break;
- case SearchPattern.R_CASE_SENSITIVE:
- buffer.append("R_CASE_SENSITIVE"); //$NON-NLS-1$
- break;
- case SearchPattern.R_EQUIVALENT_MATCH:
- buffer.append("R_EQUIVALENT_MATCH"); //$NON-NLS-1$
- break;
- case SearchPattern.R_ERASURE_MATCH:
- buffer.append("R_ERASURE_MATCH"); //$NON-NLS-1$
- break;
- case SearchPattern.R_FULL_MATCH:
- buffer.append("R_FULL_MATCH"); //$NON-NLS-1$
- break;
- case SearchPattern.R_PATTERN_MATCH:
- buffer.append("R_PATTERN_MATCH"); //$NON-NLS-1$
- break;
- case SearchPattern.R_REGEXP_MATCH:
- buffer.append("R_REGEXP_MATCH"); //$NON-NLS-1$
- break;
- case SearchPattern.R_CAMELCASE_MATCH:
- buffer.append("R_CAMELCASE_MATCH"); //$NON-NLS-1$
- break;
- }
- }
- return buffer.toString();
- }
-
- /**
- * Return kind of search corresponding to given value.
- *
- * @param searchFor
- */
- public static String getSearchForString(final int searchFor) {
- switch (searchFor) {
- case IJavaScriptSearchConstants.TYPE:
- return ("TYPE"); //$NON-NLS-1$
- case IJavaScriptSearchConstants.METHOD:
- return ("METHOD"); //$NON-NLS-1$
- case IJavaScriptSearchConstants.PACKAGE:
- return ("PACKAGE"); //$NON-NLS-1$
- case IJavaScriptSearchConstants.CONSTRUCTOR:
- return ("CONSTRUCTOR"); //$NON-NLS-1$
- case IJavaScriptSearchConstants.FIELD:
- return ("FIELD"); //$NON-NLS-1$
- case IJavaScriptSearchConstants.CLASS:
- return ("CLASS"); //$NON-NLS-1$
- case IJavaScriptSearchConstants.VAR:
- return ("VAR"); //$NON-NLS-1$
- case IJavaScriptSearchConstants.FUNCTION:
- return ("FUNCTION"); //$NON-NLS-1$
- }
- return "UNKNOWN"; //$NON-NLS-1$
- }
-
- private Parser getParser() {
- if (this.parser == null) {
- this.compilerOptions = new CompilerOptions(JavaScriptCore.getOptions());
- ProblemReporter problemReporter =
- new ProblemReporter(
- DefaultErrorHandlingPolicies.proceedWithAllProblems(),
- this.compilerOptions,
- new DefaultProblemFactory());
- this.parser = new Parser(problemReporter, true);
- }
- return this.parser;
- }
-
- /*
- * Returns the list of working copies used by this search engine.
- * Returns null if none.
- */
- private IJavaScriptUnit[] getWorkingCopies() {
- IJavaScriptUnit[] copies;
- if (this.workingCopies != null) {
- if (this.workingCopyOwner == null) {
- copies = JavaModelManager.getJavaModelManager().getWorkingCopies(DefaultWorkingCopyOwner.PRIMARY, false/*don't add primary WCs a second time*/);
- if (copies == null) {
- copies = this.workingCopies;
- } else {
- HashMap pathToCUs = new HashMap();
- for (int i = 0, length = copies.length; i < length; i++) {
- IJavaScriptUnit unit = copies[i];
- pathToCUs.put(unit.getPath(), unit);
- }
- for (int i = 0, length = this.workingCopies.length; i < length; i++) {
- IJavaScriptUnit unit = this.workingCopies[i];
- pathToCUs.put(unit.getPath(), unit);
- }
- int length = pathToCUs.size();
- copies = new IJavaScriptUnit[length];
- pathToCUs.values().toArray(copies);
- }
- } else {
- copies = this.workingCopies;
- }
- } else if (this.workingCopyOwner != null) {
- copies = JavaModelManager.getJavaModelManager().getWorkingCopies(this.workingCopyOwner, true/*add primary WCs*/);
- } else {
- copies = JavaModelManager.getJavaModelManager().getWorkingCopies(DefaultWorkingCopyOwner.PRIMARY, false/*don't add primary WCs a second time*/);
- }
- if (copies == null) return null;
-
- // filter out primary working copies that are saved
- IJavaScriptUnit[] result = null;
- int length = copies.length;
- int index = 0;
- for (int i = 0; i < length; i++) {
- CompilationUnit copy = (CompilationUnit)copies[i];
- try {
- if (!copy.isPrimary()
- || copy.hasUnsavedChanges()
- || copy.hasResourceChanged()) {
- if (result == null) {
- result = new IJavaScriptUnit[length];
- }
- result[index++] = copy;
- }
- } catch (JavaScriptModelException e) {
- // copy doesn't exist: ignore
- }
- }
- if (index != length && result != null) {
- System.arraycopy(result, 0, result = new IJavaScriptUnit[index], 0, index);
- }
- return result;
- }
-
- /*
- * Returns the list of working copies used to do the search on the given Java element.
- */
- private IJavaScriptUnit[] getWorkingCopies(IJavaScriptElement element) {
- if (element instanceof IMember) {
- IJavaScriptUnit cu = ((IMember)element).getJavaScriptUnit();
- if (cu != null && cu.isWorkingCopy()) {
- IJavaScriptUnit[] copies = getWorkingCopies();
- int length = copies == null ? 0 : copies.length;
- if (length > 0) {
- IJavaScriptUnit[] newWorkingCopies = new IJavaScriptUnit[length+1];
- System.arraycopy(copies, 0, newWorkingCopies, 0, length);
- newWorkingCopies[length] = cu;
- return newWorkingCopies;
- }
- return new IJavaScriptUnit[] {cu};
- }
- }
- return getWorkingCopies();
- }
-
- boolean match(char patternTypeSuffix, int modifiers) {
- switch(patternTypeSuffix) {
- case IIndexConstants.CLASS_SUFFIX :
- return modifiers == 0;
- }
- return true;
- }
-
- boolean match(char patternTypeSuffix, char[] patternPkg, char[] patternTypeName, int matchRule, int typeKind, char[] pkg, char[] typeName) {
- if (typeName==null)
- typeName=CharOperation.NO_CHAR;
- switch(patternTypeSuffix) {
- case IIndexConstants.CLASS_SUFFIX :
- if (typeKind != TypeDeclaration.CLASS_DECL) return false;
- break;
- case IIndexConstants.TYPE_SUFFIX : // nothing
- }
-
- boolean isCaseSensitive = (matchRule & SearchPattern.R_CASE_SENSITIVE) != 0;
- if (patternPkg != null && !CharOperation.equals(patternPkg, pkg, isCaseSensitive))
- return false;
-
- if (patternTypeName != null) {
- boolean isCamelCase = (matchRule & SearchPattern.R_CAMELCASE_MATCH) != 0;
- int matchMode = matchRule & JavaSearchPattern.MATCH_MODE_MASK;
- if (!isCaseSensitive && !isCamelCase) {
- patternTypeName = CharOperation.toLowerCase(patternTypeName);
- }
- boolean matchFirstChar = !isCaseSensitive || patternTypeName[0] == typeName[0];
- if (isCamelCase && matchFirstChar && CharOperation.camelCaseMatch(patternTypeName, typeName)) {
- return true;
- }
- switch(matchMode) {
- case SearchPattern.R_EXACT_MATCH :
- if (!isCamelCase) {
- return matchFirstChar && CharOperation.equals(patternTypeName, typeName, isCaseSensitive);
- }
- // fall through next case to match as prefix if camel case failed
- case SearchPattern.R_PREFIX_MATCH :
- return matchFirstChar && CharOperation.prefixEquals(patternTypeName, typeName, isCaseSensitive);
- case SearchPattern.R_PATTERN_MATCH :
- return CharOperation.match(patternTypeName, typeName, isCaseSensitive);
- case SearchPattern.R_REGEXP_MATCH :
- // TODO (frederic) implement regular expression match
- break;
- }
- }
- return true;
-
- }
-
- /**
- * Searches for matches of a given search pattern. Search patterns can be created using helper
- * methods (from a String pattern or a Java element) and encapsulate the description of what is
- * being searched (for example, search method declarations in a case sensitive way).
- *
- * @see org.eclipse.wst.jsdt.core.search.SearchEngine#search(SearchPattern, SearchParticipant[], IJavaScriptSearchScope, SearchRequestor, IProgressMonitor)
- * for detailed comment
- */
- public void search(SearchPattern pattern, SearchParticipant[] participants, IJavaScriptSearchScope scope, SearchRequestor requestor, IProgressMonitor monitor) throws CoreException {
- if (VERBOSE) {
- Util.verbose("BasicSearchEngine.search(SearchPattern, SearchParticipant[], IJavaScriptSearchScope, SearchRequestor, IProgressMonitor)"); //$NON-NLS-1$
- }
- findMatches(pattern, participants, scope, requestor, monitor);
- }
-
-
- public void searchAllBindingNames(
- final char[] packageName,
- final char[] bindingName,
- final int bindingType,
- final int matchRule,
- IJavaScriptSearchScope scope,
- final IRestrictedAccessBindingRequestor nameRequestor,
- int waitingPolicy,
- boolean doParse,
- IProgressMonitor progressMonitor) throws JavaScriptModelException {
-
- if (VERBOSE) {
- Util.verbose("BasicSearchEngine.searchAllBindingNames(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(" - type name: "+(bindingName==null?"null":new String(bindingName))); //$NON-NLS-1$ //$NON-NLS-2$
- Util.verbose(" - match rule: "+getMatchRuleString(matchRule)); //$NON-NLS-1$
- Util.verbose(" - bindingType for: "+bindingType); //$NON-NLS-1$
- Util.verbose(" - scope: "+scope); //$NON-NLS-1$
- }
-
- IndexManager indexManager = JavaModelManager.getJavaModelManager().getIndexManager();
- SearchPattern searchPattern=null;
- char suffix=0;
- switch(bindingType){
-
- case Binding.TYPE :
- {
-
-
- suffix = IIndexConstants.CLASS_SUFFIX;
- searchPattern = new TypeDeclarationPattern(
- packageName,
- null, // do find member types
- bindingName,
- suffix,
- matchRule);
-
- break;
- }
- case Binding.VARIABLE :
- case Binding.LOCAL :
- case Binding.FIELD :
- {
- searchPattern = new LocalVariablePattern(true, false, false,bindingName, matchRule);
- }
- break;
- case Binding.METHOD:
- {
- searchPattern = new MethodPattern(
- true,false,true,
- bindingName,
- null,null,null,null,
- null,null,null,
- matchRule);
-
- }
- break;
- default: // some combination
- {
- if ((bindingType & Binding.METHOD) >0)
- {
- 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);
- if (searchPattern==null)
- searchPattern=localVariablePattern;
- else
- searchPattern=new OrPattern(searchPattern,localVariablePattern);
- }
- 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;
- else
- searchPattern=new OrPattern(searchPattern,typeDeclarationPattern);
- }
- }
- }
- 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
- IndexQueryRequestor searchRequestor = new IndexQueryRequestor(){
- public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access) {
- // Filter unexpected types
- JavaSearchPattern record = (JavaSearchPattern)indexRecord;
-
- // Accept document path
- AccessRestriction accessRestriction = null;
- int modifiers=ClassFileConstants.AccPublic;
- char[] packageName=null;
- char[] simpleBindingName=null;
- if (record instanceof MethodPattern) {
- MethodPattern methodPattern = (MethodPattern) record;
- simpleBindingName=methodPattern.selector;
- Path path = new Path(documentPath);
- String string = path.lastSegment();
- if (path.hasTrailingSeparator()) // is library
- {
- packageName=string.toCharArray();
- }
- }
- else if (record instanceof LocalVariablePattern)
- {
- LocalVariablePattern localVariablePattern = (LocalVariablePattern) record;
- simpleBindingName=localVariablePattern.name;
- Path path = new Path(documentPath);
- String string = path.lastSegment();
- if (path.hasTrailingSeparator()) // is library
- {
- packageName=string.toCharArray();
- }
-
- }else if (record instanceof TypeDeclarationPattern) {
- TypeDeclarationPattern typeDecPattern = (TypeDeclarationPattern)record;
- simpleBindingName=typeDecPattern.simpleName;
- Path path = new Path(documentPath);
- String string = path.lastSegment();
- if (path.hasTrailingSeparator()) // is library
- {
- packageName=string.toCharArray();
- }
- }
-
- nameRequestor.acceptBinding( bindingType,modifiers, packageName, simpleBindingName, documentPath, accessRestriction);
-
- return true;
- }
- };
-
- try {
- if (progressMonitor != null) {
- progressMonitor.beginTask(Messages.engine_searching, 100);
- }
- // 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 && doParse) {
- for (int i = 0; i < copiesLength; i++) {
- IJavaScriptUnit workingCopy = copies[i];
- if (!scope.encloses(workingCopy)) continue;
- final String path = workingCopy.getPath().toString();
- if (workingCopy.isConsistent()) {
- char[] packageDeclaration = CharOperation.NO_CHAR;
- switch (bindingType)
- {
- case Binding.TYPE:
- {
- 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, bindingName, matchRule, kind, packageDeclaration, simpleName)) {
- nameRequestor.acceptBinding(bindingType,type.getFlags(), packageDeclaration, simpleName, path, null);
- }
- }
- }
- case Binding.METHOD:
- {
- 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);
- }
- }
- }
- break;
- case Binding.VARIABLE :
- case Binding.LOCAL :
- case Binding.FIELD :
- {
- 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);
- }
- }
- }
- break;
- }
- } 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, Scope blockScope) {
-// return false; // no local/anonymous type
-// }
- public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope compilationUnitScope) {
- if (bindingType==Binding.TYPE &&
- match(typeSuffix, packageName, bindingName, matchRule, TypeDeclaration.kind(typeDeclaration.modifiers), packageDeclaration, typeDeclaration.name)) {
- nameRequestor.acceptBinding(bindingType,typeDeclaration.modifiers, packageDeclaration, typeDeclaration.name, path, null);
- }
- return true;
- }
- public boolean visit(LocalDeclaration localDeclaration, BlockScope scope) {
- if ((scope instanceof CompilationUnitScope) && (bindingType==Binding.LOCAL || bindingType==Binding.FIELD || bindingType==Binding.VARIABLE )&&
- match(typeSuffix, packageName, bindingName, matchRule,0, packageDeclaration, localDeclaration.name)) {
- nameRequestor.acceptBinding(bindingType,localDeclaration.modifiers, packageDeclaration, localDeclaration.name, path, null);
- }
- 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);
- }
- 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())) {
- nameRequestor.acceptBinding(bindingType,0, packageDeclaration, inferredType.getName(), path, null);
- }
- return true;
- }
- public boolean visit(InferredAttribute inferredField, BlockScope scope) {
- if ((scope instanceof CompilationUnitScope) && (bindingType==Binding.LOCAL || bindingType==Binding.FIELD || bindingType==Binding.VARIABLE )&&
- match(typeSuffix, packageName, bindingName, matchRule,0, packageDeclaration, inferredField.name)) {
- nameRequestor.acceptBinding(bindingType,inferredField.modifiers, packageDeclaration, inferredField.name, path, null);
- }
- return true;
- }
- public boolean visit(InferredMethod inferredMethod, BlockScope scope) {
- if (bindingType==Binding.METHOD && inferredMethod.name!=null &&
- match(typeSuffix, packageName, bindingName, matchRule,0, packageDeclaration, inferredMethod.name)) {
- nameRequestor.acceptBinding(bindingType,((MethodDeclaration)inferredMethod.getFunctionDeclaration()).modifiers, packageDeclaration, inferredMethod.name, path, null);
- }
- return true;
- }
- }
- parsedUnit.traverse(new AllTypeDeclarationsVisitor(), parsedUnit.scope);
- }
- }
- }
- }
- } finally {
- if (progressMonitor != null) {
- progressMonitor.done();
- }
- }
- }
-
-
-
-
- /**
- * Searches for all secondary types in the given scope.
- * The search can be selecting specific types (given a package or a type name
- * prefix and match modes).
- */
- public void searchAllSecondaryTypeNames(
- IPackageFragmentRoot[] sourceFolders,
- final IRestrictedAccessTypeRequestor nameRequestor,
- boolean waitForIndexes,
- IProgressMonitor progressMonitor) throws JavaScriptModelException {
-
- if (VERBOSE) {
- Util.verbose("BasicSearchEngine.searchAllSecondaryTypeNames(IPackageFragmentRoot[], IRestrictedAccessTypeRequestor, boolean, IProgressMonitor)"); //$NON-NLS-1$
- StringBuffer buffer = new StringBuffer(" - source folders: "); //$NON-NLS-1$
- int length = sourceFolders.length;
- for (int i=0; i<length; i++) {
- if (i==0) {
- buffer.append('[');
- } else {
- buffer.append(',');
- }
- buffer.append(sourceFolders[i].getElementName());
- }
- buffer.append("]\n - waitForIndexes: "); //$NON-NLS-1$
- buffer.append(waitForIndexes);
- Util.verbose(buffer.toString());
- }
-
- 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;
-
- // Index requestor
- 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;
- }
-
- // 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 pos = 0;
- if (pkgLength > 0) {
- System.arraycopy(record.pkg, 0, path, pos, pkgLength-1);
- CharOperation.replace(path, '.', '/');
- path[pkgLength-1] = '/';
- pos += pkgLength;
- }
- if (nameLength > 0) {
- System.arraycopy(record.simpleName, 0, path, pos, nameLength);
- pos += nameLength;
- }
- // Update access restriction if path is not empty
- if (pos > 0) {
- accessRestriction = access.getViolatedRestriction(path);
- }
- }
- nameRequestor.acceptType(record.modifiers, record.pkg, record.simpleName, record.enclosingTypeNames, documentPath, accessRestriction);
- return true;
- }
- };
-
- // add type names from indexes
- try {
- if (progressMonitor != null) {
- progressMonitor.beginTask(Messages.engine_searching, 100);
- }
- indexManager.performConcurrentJob(
- new PatternSearchJob(
- pattern,
- getDefaultSearchParticipant(), // Java search only
- createJavaSearchScope(sourceFolders),
- searchRequestor),
- waitForIndexes
- ? IJavaScriptSearchConstants.WAIT_UNTIL_READY_TO_SEARCH
- : IJavaScriptSearchConstants.FORCE_IMMEDIATE_SEARCH,
- progressMonitor == null ? null : new SubProgressMonitor(progressMonitor, 100));
- } catch (OperationCanceledException oce) {
- // do nothing
- } finally {
- if (progressMonitor != null) {
- progressMonitor.done();
- }
- }
- }
-
- /**
- * 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
- */
- public void searchAllTypeNames(
- final char[] packageName,
- final int packageMatchRule,
- final char[] typeName,
- final int typeMatchRule,
- int searchFor,
- 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: "+(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(" - 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;
- }
- final TypeDeclarationPattern pattern = packageMatchRule == SearchPattern.R_EXACT_MATCH
- ? new TypeDeclarationPattern(
- packageName,
- null,
- typeName,
- typeSuffix,
- typeMatchRule)
- : new QualifiedTypeDeclarationPattern(
- packageName,
- packageMatchRule,
- typeName,
- typeSuffix,
- typeMatchRule);
-
- // 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
- IndexQueryRequestor searchRequestor = new IndexQueryRequestor(){
- public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access) {
- // Filter unexpected types
- 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;
- }
-
- // 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 pos = 0;
- if (pkgLength > 0) {
- System.arraycopy(record.pkg, 0, path, pos, pkgLength-1);
- CharOperation.replace(path, '.', '/');
- path[pkgLength-1] = '/';
- pos += pkgLength;
- }
- if (nameLength > 0) {
- System.arraycopy(record.simpleName, 0, path, pos, nameLength);
- pos += nameLength;
- }
- // Update access restriction if path is not empty
- if (pos > 0) {
- accessRestriction = access.getViolatedRestriction(path);
- }
- }
- if (match(record.typeSuffix, record.modifiers)) {
- nameRequestor.acceptType(record.modifiers, record.pkg, record.simpleName, record.enclosingTypeNames, documentPath, accessRestriction);
- }
- return true;
- }
- };
-
- try {
- if (progressMonitor != null) {
- progressMonitor.beginTask(Messages.engine_searching, 100);
- }
- // 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; i < copiesLength; 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);
- }
- }
- }
- } 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
- }
- 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<l; j++) {
- type = type.getType(new String(enclosingTypeNames[j]));
- }
- ((TypeNameMatchRequestorWrapper)nameRequestor).requestor.acceptTypeNameMatch(new JavaSearchTypeNameMatch(type, 0));
- } else {
- nameRequestor.acceptType(memberTypeDeclaration.modifiers, packageDeclaration, memberTypeDeclaration.name, enclosingTypeNames, path, null);
- }
- }
- return true;
- }
- public boolean visit(InferredType inferredType, BlockScope scope) {
- if (match(typeSuffix, packageName, typeName, typeMatchRule, TypeDeclaration.kind(0), packageDeclaration, inferredType.getName())) {
- if (nameRequestor instanceof TypeNameMatchRequestorWrapper) {
- IType type = workingCopy.getType(new String(typeName));
- ((TypeNameMatchRequestorWrapper)nameRequestor).requestor.acceptTypeNameMatch(new JavaSearchTypeNameMatch(type, 0));
- } else {
- nameRequestor.acceptType(0, packageDeclaration, inferredType.getName(), CharOperation.NO_CHAR_CHAR, path, null);
- }
- }
- return true;
- }
- }
- parsedUnit.traverse(new AllTypeDeclarationsVisitor(), parsedUnit.scope);
- }
- }
- }
- }
- } finally {
- if (progressMonitor != null) {
- progressMonitor.done();
- }
- }
- }
-
- /**
- * Searches for all top-level types and member types in the given scope using a case sensitive exact match
- * with the given qualified names and type names.
- *
- * @see org.eclipse.wst.jsdt.core.search.SearchEngine#searchAllTypeNames(char[][], char[][], IJavaScriptSearchScope, org.eclipse.wst.jsdt.core.search.TypeNameRequestor, int, IProgressMonitor)
- * for detailed comment
- */
- public void searchAllTypeNames(
- final char[][] qualifications,
- final char[][] typeNames,
- final int matchRule,
- int searchFor,
- 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: "+(typeNames==null?"null":new String(CharOperation.concatWith(typeNames, ',')))); //$NON-NLS-1$ //$NON-NLS-2$
- Util.verbose(" - match rule: "+matchRule); //$NON-NLS-1$
- Util.verbose(" - search for: "+searchFor); //$NON-NLS-1$
- Util.verbose(" - scope: "+scope); //$NON-NLS-1$
- }
- IndexManager indexManager = JavaModelManager.getJavaModelManager().getIndexManager();
-
- final char typeSuffix;
- switch(searchFor){
- case IJavaScriptSearchConstants.CLASS :
- typeSuffix = IIndexConstants.CLASS_SUFFIX;
- break;
- default :
- typeSuffix = IIndexConstants.TYPE_SUFFIX;
- break;
- }
- final MultiTypeDeclarationPattern pattern = new MultiTypeDeclarationPattern(qualifications, typeNames, typeSuffix, matchRule);
-
- // 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
- IndexQueryRequestor searchRequestor = new IndexQueryRequestor(){
- public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access) {
- // Filter unexpected types
- QualifiedTypeDeclarationPattern record = (QualifiedTypeDeclarationPattern) 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;
- }
-
- // Accept document path
- AccessRestriction accessRestriction = null;
- if (access != null) {
- // Compute document relative path
- 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 (qualificationLength > 0) {
- System.arraycopy(record.qualification, 0, path, pos, qualificationLength - 1);
- CharOperation.replace(path, '.', '/');
- path[qualificationLength-1] = '/';
- pos += qualificationLength;
- }
- if (nameLength > 0) {
- System.arraycopy(record.simpleName, 0, path, pos, nameLength);
- pos += nameLength;
- }
- // Update access restriction if path is not empty
- if (pos > 0) {
- accessRestriction = access.getViolatedRestriction(path);
- }
- }
- nameRequestor.acceptType(record.modifiers, record.pkg, record.simpleName, record.enclosingTypeNames, documentPath, accessRestriction);
- return true;
- }
- };
-
- try {
- if (progressMonitor != null) {
- progressMonitor.beginTask(Messages.engine_searching, 100);
- }
- // 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;
- }
- if (pattern.matchesDecodedKey(new QualifiedTypeDeclarationPattern(qualification, simpleName, suffix, matchRule))) {
- nameRequestor.acceptType(type.getFlags(), packageDeclaration, simpleName, enclosingTypeNames, path, null);
- }
- }
- } 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
- }
- 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;
- }
- 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;
- }
- }
- 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);
- }
- return true;
- }
- }
- parsedUnit.traverse(new AllTypeDeclarationsVisitor(), parsedUnit.scope);
- }
- }
- }
- }
- } finally {
- if (progressMonitor != null) {
- progressMonitor.done();
- }
- }
- }
-
- public void searchDeclarations(IJavaScriptElement enclosingElement, SearchRequestor requestor, SearchPattern pattern, IProgressMonitor monitor) throws JavaScriptModelException {
- if (VERBOSE) {
- Util.verbose(" - java element: "+enclosingElement); //$NON-NLS-1$
- }
- IJavaScriptSearchScope scope = createJavaSearchScope(new IJavaScriptElement[] {enclosingElement});
- IResource resource = enclosingElement.getResource();
- if (enclosingElement instanceof IMember) {
- IMember member = (IMember) enclosingElement;
- IJavaScriptUnit cu = member.getJavaScriptUnit();
- if (cu != null) {
- resource = cu.getResource();
- } else if (member.isBinary()) {
- // binary member resource cannot be used as this
- // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=148215
- resource = null;
- }
- }
- try {
- if (resource instanceof IFile) {
- try {
- requestor.beginReporting();
- if (VERBOSE) {
- Util.verbose("Searching for " + pattern + " in " + resource.getFullPath()); //$NON-NLS-1$//$NON-NLS-2$
- }
- SearchParticipant participant = getDefaultSearchParticipant();
- SearchDocument[] documents = MatchLocator.addWorkingCopies(
- pattern,
- new SearchDocument[] {new JavaSearchDocument(enclosingElement.getPath().toString(), participant)},
- getWorkingCopies(enclosingElement),
- participant);
- participant.locateMatches(
- documents,
- pattern,
- scope,
- requestor,
- monitor);
- } finally {
- requestor.endReporting();
- }
- } else {
- search(
- pattern,
- new SearchParticipant[] {getDefaultSearchParticipant()},
- scope,
- requestor,
- monitor);
- }
- } catch (CoreException e) {
- if (e instanceof JavaScriptModelException)
- throw (JavaScriptModelException) e;
- throw new JavaScriptModelException(e);
- }
- }
-
- /**
- * Searches for all declarations of the fields accessed in the given element.
- * The element can be a compilation unit, a source type, or a source method.
- * Reports the field declarations using the given requestor.
- *
- * @see org.eclipse.wst.jsdt.core.search.SearchEngine#searchDeclarationsOfAccessedFields(IJavaScriptElement, SearchRequestor, IProgressMonitor)
- * for detailed comment
- */
- public void searchDeclarationsOfAccessedFields(IJavaScriptElement enclosingElement, SearchRequestor requestor, IProgressMonitor monitor) throws JavaScriptModelException {
- if (VERBOSE) {
- Util.verbose("BasicSearchEngine.searchDeclarationsOfAccessedFields(IJavaScriptElement, SearchRequestor, SearchPattern, IProgressMonitor)"); //$NON-NLS-1$
- }
- SearchPattern pattern = new DeclarationOfAccessedFieldsPattern(enclosingElement);
- searchDeclarations(enclosingElement, requestor, pattern, monitor);
- }
-
- /**
- * Searches for all declarations of the types referenced in the given element.
- * The element can be a compilation unit, a source type, or a source method.
- * Reports the type declarations using the given requestor.
- *
- * @see org.eclipse.wst.jsdt.core.search.SearchEngine#searchDeclarationsOfReferencedTypes(IJavaScriptElement, SearchRequestor, IProgressMonitor)
- * for detailed comment
- */
- public void searchDeclarationsOfReferencedTypes(IJavaScriptElement enclosingElement, SearchRequestor requestor, IProgressMonitor monitor) throws JavaScriptModelException {
- if (VERBOSE) {
- Util.verbose("BasicSearchEngine.searchDeclarationsOfReferencedTypes(IJavaScriptElement, SearchRequestor, SearchPattern, IProgressMonitor)"); //$NON-NLS-1$
- }
- SearchPattern pattern = new DeclarationOfReferencedTypesPattern(enclosingElement);
- searchDeclarations(enclosingElement, requestor, pattern, monitor);
- }
-
- /**
- * Searches for all declarations of the methods invoked in the given element.
- * The element can be a compilation unit, a source type, or a source method.
- * Reports the method declarations using the given requestor.
- *
- * @see org.eclipse.wst.jsdt.core.search.SearchEngine#searchDeclarationsOfSentMessages(IJavaScriptElement, SearchRequestor, IProgressMonitor)
- * for detailed comment
- */
- public void searchDeclarationsOfSentMessages(IJavaScriptElement enclosingElement, SearchRequestor requestor, IProgressMonitor monitor) throws JavaScriptModelException {
- if (VERBOSE) {
- Util.verbose("BasicSearchEngine.searchDeclarationsOfSentMessages(IJavaScriptElement, SearchRequestor, SearchPattern, IProgressMonitor)"); //$NON-NLS-1$
- }
- SearchPattern pattern = new DeclarationOfReferencedMethodsPattern(enclosingElement);
- searchDeclarations(enclosingElement, requestor, pattern, monitor);
- }
-
- /**
- * <p>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.</p>
- *
- * @param typeNamePattern type name pattern to search for
- * @param typeMatchRule Search pattern matching rule to use with the given <code>typeNamePattern</code>
- * @param scope scope of the search
- * @param nameRequester requester to report findings to
- * @param waitingPolicy Policy to use when waiting for the index
- * @param progressMonitor monitor to report index search progress to
- *
- * @see SearchPattern#R_CAMELCASE_MATCH
- * @see SearchPattern#R_CASE_SENSITIVE
- * @see SearchPattern#R_EQUIVALENT_MATCH
- * @see SearchPattern#R_EXACT_MATCH
- * @see SearchPattern#R_FULL_MATCH
- * @see SearchPattern#R_PATTERN_MATCH
- * @see SearchPattern#R_PREFIX_MATCH
- * @see SearchPattern#R_REGEXP_MATCH
- *
- * @see IJavaScriptSearchConstants#FORCE_IMMEDIATE_SEARCH
- * @see IJavaScriptSearchConstants#CANCEL_IF_NOT_READY_TO_SEARCH
- * @see IJavaScriptSearchConstants#WAIT_UNTIL_READY_TO_SEARCH
- */
- public void searchAllConstructorDeclarations(
- final char[] typeNamePattern,
- final int typeMatchRule,
- IJavaScriptSearchScope scope,
- final IConstructorRequestor nameRequester,
- 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 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,
- typeMatchRule);
-
- // Index requester
- IndexQueryRequestor searchRequestor = new IndexQueryRequestor(){
- public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access) {
- // Filter unexpected types
- ConstructorDeclarationPattern record = (ConstructorDeclarationPattern)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);
- }
- }
- nameRequester.acceptConstructor(
- record.modifiers,
- record.declaringSimpleName,
- record.parameterCount,
- record.parameterTypes,
- record.parameterNames,
- documentPath,
- accessRestriction);
- return true;
- }
- };
-
- try {
- if (progressMonitor != null) {
- progressMonitor.beginTask(Messages.engine_searching, 1000);
- }
- // Find constructor declarations from index
- indexManager.performConcurrentJob(
- new PatternSearchJob(
- pattern,
- getDefaultSearchParticipant(), // JavaScript search only
- scope,
- searchRequestor),
- waitingPolicy,
- progressMonitor == null ? null : new SubProgressMonitor(progressMonitor, 1000));
- } finally {
- if (progressMonitor != null) {
- progressMonitor.done();
- }
- }
- }
-}
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
deleted file mode 100644
index 3c1e6c00..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/HierarchyScope.java
+++ /dev/null
@@ -1,365 +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;
-
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptElementDelta;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-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.internal.compiler.util.SuffixConstants;
-import org.eclipse.wst.jsdt.internal.core.JavaElement;
-import org.eclipse.wst.jsdt.internal.core.JavaModelManager;
-import org.eclipse.wst.jsdt.internal.core.JavaProject;
-import org.eclipse.wst.jsdt.internal.core.hierarchy.TypeHierarchy;
-
-/**
- * Scope limited to the subtype and supertype hierarchy of a given type.
- */
-public class HierarchyScope extends AbstractSearchScope implements SuffixConstants {
-
- public IType focusType;
- private String focusPath;
- private WorkingCopyOwner owner;
-
- private ITypeHierarchy hierarchy;
- private IType[] types;
- private HashSet resourcePaths;
- private IPath[] enclosingProjectsAndJars;
-
- protected IResource[] elements;
- protected int elementCount;
-
- public boolean needsRefresh;
-
- /* (non-Javadoc)
- * Adds the given resource to this search scope.
- */
- public void add(IResource element) {
- if (this.elementCount == this.elements.length) {
- System.arraycopy(
- this.elements,
- 0,
- this.elements = new IResource[this.elementCount * 2],
- 0,
- this.elementCount);
- }
- elements[elementCount++] = element;
- }
-
- /* (non-Javadoc)
- * Creates a new hiearchy scope for the given type.
- */
- public HierarchyScope(IType type, WorkingCopyOwner owner) throws JavaScriptModelException {
- this.focusType = type;
- this.owner = owner;
-
- this.enclosingProjectsAndJars = this.computeProjectsAndJars(type);
-
- // resource path
- IPackageFragmentRoot root = (IPackageFragmentRoot)type.getPackageFragment().getParent();
-// if (root.isArchive()) {
-// IPath jarPath = root.getPath();
-// Object target = JavaModel.getTarget(ResourcesPlugin.getWorkspace().getRoot(), jarPath, true);
-// String zipFileName;
-// if (target instanceof IFile) {
-// // internal jar
-// zipFileName = jarPath.toString();
-// } else if (target instanceof File) {
-// // external jar
-// zipFileName = ((File)target).getPath();
-// } else {
-// return; // unknown target
-// }
-// this.focusPath =
-// zipFileName
-// + JAR_FILE_ENTRY_SEPARATOR
-// + type.getFullyQualifiedName().replace('.', '/')
-// + SUFFIX_STRING_class;
-// }
-// else
- {
- this.focusPath = type.getPath().toString();
- }
-
- this.needsRefresh = true;
-
- //disabled for now as this could be expensive
- //JavaModelManager.getJavaModelManager().rememberScope(this);
- }
- private void buildResourceVector() {
- HashMap resources = new HashMap();
- HashMap paths = new HashMap();
- this.types = this.hierarchy.getAllClasses();
- IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
- for (int i = 0; i < this.types.length; i++) {
- IType type = this.types[i];
- IResource resource = type.getResource();
- if (resource != null && resources.get(resource) == null) {
- resources.put(resource, resource);
- add(resource);
- }
- IPackageFragmentRoot root =
- (IPackageFragmentRoot) type.getPackageFragment().getParent();
-// if (root instanceof JarPackageFragmentRoot) {
-// // type in a jar
-// JarPackageFragmentRoot jar = (JarPackageFragmentRoot) root;
-// IPath jarPath = jar.getPath();
-// Object target = JavaModel.getTarget(workspaceRoot, jarPath, true);
-// String zipFileName;
-// if (target instanceof IFile) {
-// // internal jar
-// zipFileName = jarPath.toString();
-// } else if (target instanceof File) {
-// // external jar
-// zipFileName = ((File)target).getPath();
-// } else {
-// continue; // unknown target
-// }
-// String resourcePath =
-// zipFileName
-// + JAR_FILE_ENTRY_SEPARATOR
-// + type.getFullyQualifiedName().replace('.', '/')
-// + SUFFIX_STRING_class;
-//
-// this.resourcePaths.add(resourcePath);
-// paths.put(jarPath, type);
-// } else
- {
- // type is a project
- paths.put(type.getJavaScriptProject().getProject().getFullPath(), type);
- }
- }
- this.enclosingProjectsAndJars = new IPath[paths.size()];
- int i = 0;
- for (Iterator iter = paths.keySet().iterator(); iter.hasNext();) {
- this.enclosingProjectsAndJars[i++] = (IPath) iter.next();
- }
- }
- /*
- * Computes the paths of projects and jars that the hierarchy on the given type could contain.
- * This is a super set of the project and jar paths once the hierarchy is computed.
- */
- private IPath[] computeProjectsAndJars(IType type) throws JavaScriptModelException {
- HashSet set = new HashSet();
- IPackageFragmentRoot root = (IPackageFragmentRoot)type.getPackageFragment().getParent();
- if (root.isArchive()) {
- // add the root
- set.add(root.getPath());
- // add all projects that reference this archive and their dependents
- IPath rootPath = root.getPath();
- IJavaScriptModel model = JavaModelManager.getJavaModelManager().getJavaModel();
- IJavaScriptProject[] projects = model.getJavaScriptProjects();
- HashSet visited = new HashSet();
- for (int i = 0; i < projects.length; i++) {
- JavaProject project = (JavaProject) projects[i];
- IIncludePathEntry entry = project.getClasspathEntryFor(rootPath);
- if (entry != null) {
- // add the project and its binary pkg fragment roots
- IPackageFragmentRoot[] roots = project.getAllPackageFragmentRoots();
- set.add(project.getPath());
- for (int k = 0; k < roots.length; k++) {
- IPackageFragmentRoot pkgFragmentRoot = roots[k];
- if (pkgFragmentRoot.getKind() == IPackageFragmentRoot.K_BINARY) {
- set.add(pkgFragmentRoot.getPath());
- }
- }
- // add the dependent projects
- this.computeDependents(project, set, visited);
- }
- }
- } else {
- // add all the project's pkg fragment roots
- IJavaScriptProject project = (IJavaScriptProject)root.getParent();
- IPackageFragmentRoot[] roots = project.getAllPackageFragmentRoots();
- for (int i = 0; i < roots.length; i++) {
- IPackageFragmentRoot pkgFragmentRoot = roots[i];
- if (pkgFragmentRoot.getKind() == IPackageFragmentRoot.K_BINARY) {
- set.add(pkgFragmentRoot.getPath());
- } else {
- set.add(pkgFragmentRoot.getParent().getPath());
- }
- }
- // add the dependent projects
- this.computeDependents(project, set, new HashSet());
- }
- IPath[] result = new IPath[set.size()];
- set.toArray(result);
- return result;
- }
- private void computeDependents(IJavaScriptProject project, HashSet set, HashSet visited) {
- if (visited.contains(project)) return;
- visited.add(project);
- IProject[] dependents = project.getProject().getReferencingProjects();
- for (int i = 0; i < dependents.length; i++) {
- try {
- IJavaScriptProject dependent = JavaScriptCore.create(dependents[i]);
- IPackageFragmentRoot[] roots = dependent.getPackageFragmentRoots();
- set.add(dependent.getPath());
- for (int j = 0; j < roots.length; j++) {
- IPackageFragmentRoot pkgFragmentRoot = roots[j];
- if (pkgFragmentRoot.isArchive()) {
- set.add(pkgFragmentRoot.getPath());
- }
- }
- this.computeDependents(dependent, set, visited);
- } catch (JavaScriptModelException e) {
- // project is not a java project
- }
- }
- }
- /* (non-Javadoc)
- * @see IJavaScriptSearchScope#encloses(String)
- */
- public boolean encloses(String resourcePath) {
- if (this.hierarchy == null) {
- if (resourcePath.equals(this.focusPath)) {
- return true;
- } else {
- if (this.needsRefresh) {
- try {
- this.initialize();
- } catch (JavaScriptModelException e) {
- return false;
- }
- } else {
- // the scope is used only to find enclosing projects and jars
- // clients is responsible for filtering out elements not in the hierarchy (see SearchEngine)
- return true;
- }
- }
- }
- if (this.needsRefresh) {
- try {
- this.refresh();
- } catch(JavaScriptModelException e) {
- return false;
- }
- }
- int separatorIndex = resourcePath.indexOf(JAR_FILE_ENTRY_SEPARATOR);
- if (separatorIndex != -1) {
- return this.resourcePaths.contains(resourcePath);
- } else {
- for (int i = 0; i < this.elementCount; i++) {
- if (resourcePath.startsWith(this.elements[i].getFullPath().toString())) {
- return true;
- }
- }
- }
- return false;
- }
- /* (non-Javadoc)
- * @see IJavaScriptSearchScope#encloses(IJavaScriptElement)
- */
- public boolean encloses(IJavaScriptElement element) {
- if (this.hierarchy == null) {
- if (this.focusType.equals(element.getAncestor(IJavaScriptElement.TYPE))) {
- return true;
- } else {
- if (this.needsRefresh) {
- try {
- this.initialize();
- } catch (JavaScriptModelException e) {
- return false;
- }
- } else {
- // the scope is used only to find enclosing projects and jars
- // clients is responsible for filtering out elements not in the hierarchy (see SearchEngine)
- return true;
- }
- }
- }
- if (this.needsRefresh) {
- try {
- this.refresh();
- } catch(JavaScriptModelException e) {
- return false;
- }
- }
- IType type = null;
- if (element instanceof IType) {
- type = (IType) element;
- } else if (element instanceof IMember) {
- type = ((IMember) element).getDeclaringType();
- }
- if (type != null) {
- if (this.hierarchy.contains(type)) {
- return true;
- } else {
- // be flexible: look at original element (see bug 14106 Declarations in Hierarchy does not find declarations in hierarchy)
- IType original;
- if (!type.isBinary()
- && (original = (IType)type.getPrimaryElement()) != null) {
- return this.hierarchy.contains(original);
- }
- }
- }
- return false;
- }
- /* (non-Javadoc)
- * @see IJavaScriptSearchScope#enclosingProjectsAndJars()
- * @deprecated
- */
- public IPath[] enclosingProjectsAndJars() {
- if (this.needsRefresh) {
- try {
- this.refresh();
- } catch(JavaScriptModelException e) {
- return new IPath[0];
- }
- }
- return this.enclosingProjectsAndJars;
- }
- protected void initialize() throws JavaScriptModelException {
- this.resourcePaths = new HashSet();
- this.elements = new IResource[5];
- this.elementCount = 0;
- this.needsRefresh = false;
- if (this.hierarchy == null) {
- this.hierarchy = this.focusType.newTypeHierarchy(this.owner, null);
- } else {
- this.hierarchy.refresh(null);
- }
- this.buildResourceVector();
- }
- /*
- * @see AbstractSearchScope#processDelta(IJavaScriptElementDelta)
- */
- public void processDelta(IJavaScriptElementDelta delta) {
- if (this.needsRefresh) return;
- this.needsRefresh = this.hierarchy == null ? false : ((TypeHierarchy)this.hierarchy).isAffected(delta);
- }
- protected void refresh() throws JavaScriptModelException {
- if (this.hierarchy != null) {
- this.initialize();
- }
- }
- public String toString() {
- return "HierarchyScope on " + ((JavaElement)this.focusType).toStringWithAncestors(); //$NON-NLS-1$
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IConstructorRequestor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IConstructorRequestor.java
deleted file mode 100644
index e8cccebc..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IConstructorRequestor.java
+++ /dev/null
@@ -1,40 +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;
-
-import org.eclipse.wst.jsdt.internal.compiler.env.AccessRestriction;
-
-/**
- * A <code>IConstructorRequestor</code> collects search results from a <code>searchAllConstructorDeclarations</code>
- * query to a <code>SearchBasicEngine</code> providing restricted access information of declaring type when a constructor is accepted.
- */
-public interface IConstructorRequestor {
-
- /**
- * <p>Accepts a constructor found during an index search.</p>
- *
- * @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 <code>parameterCount</code>
- * @param parameterNames Names of the parameters, should be same length as <code>parameterCount</code>
- * @param path to the document containing the constructor match
- * @param access Accessibility of the constructor
- */
- public void acceptConstructor(
- int modifiers,
- char[] typeName,
- int parameterCount,
- char[][] parameterTypes,
- char[][] parameterNames,
- String path,
- AccessRestriction access);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IRestrictedAccessBindingRequestor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IRestrictedAccessBindingRequestor.java
deleted file mode 100644
index 59dde305..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IRestrictedAccessBindingRequestor.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.search;
-
-import java.util.ArrayList;
-
-import org.eclipse.wst.jsdt.internal.compiler.env.AccessRestriction;
-
-/**
- * A <code>IRestrictedAccessTypeRequestor</code> collects search results from a <code>searchAllTypeNames</code>
- * query to a <code>SearchBasicEngine</code> providing restricted access information when a type is accepted.
- * @see org.eclipse.wst.jsdt.core.search.TypeNameRequestor
- */
-public interface IRestrictedAccessBindingRequestor {
-
- public boolean acceptBinding(int type, int modifiers, char[] packageName, char[] simpleBindingName, String path, AccessRestriction access);
-
- public String getFoundPath();
-
- public void reset();
-
- public void setExcludePath(String excludePath);
-
- public ArrayList getFoundPaths();
-
-}
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
deleted file mode 100644
index d3208dd3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IRestrictedAccessTypeRequestor.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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.internal.compiler.env.AccessRestriction;
-
-/**
- * A <code>IRestrictedAccessTypeRequestor</code> collects search results from a <code>searchAllTypeNames</code>
- * query to a <code>SearchBasicEngine</code> providing restricted access information when a type is accepted.
- * @see org.eclipse.wst.jsdt.core.search.TypeNameRequestor
- */
-public interface IRestrictedAccessTypeRequestor {
-
- public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path, AccessRestriction access);
-
-}
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
deleted file mode 100644
index c09d28db..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IndexQueryRequestor.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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.search.SearchParticipant;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.compiler.env.AccessRuleSet;
-
-/**
- * TODO add spec
- */
-public abstract class IndexQueryRequestor {
-
- // answer false if requesting cancel
- 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
deleted file mode 100644
index d7b673b5..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IndexSelector.java
+++ /dev/null
@@ -1,223 +0,0 @@
-/*******************************************************************************
- * 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.search;
-
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.compiler.util.SimpleSet;
-import org.eclipse.wst.jsdt.internal.core.JavaModelManager;
-import org.eclipse.wst.jsdt.internal.core.JavaProject;
-import org.eclipse.wst.jsdt.internal.core.LibraryFragmentRoot;
-import org.eclipse.wst.jsdt.internal.core.PackageFragmentRoot;
-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.MethodPattern;
-
-/**
- * Selects the indexes that correspond to projects in a given search scope
- * and that are dependent on a given focus element.
- */
-public class IndexSelector {
- IJavaScriptSearchScope searchScope;
- SearchPattern pattern;
- IPath[] indexLocations; // cache of the keys for looking index up
-
-public IndexSelector(
- IJavaScriptSearchScope searchScope,
- SearchPattern pattern) {
-
- this.searchScope = searchScope;
- this.pattern = pattern;
-}
-/**
- * Returns whether elements of the given project or jar can see the given focus (an IJavaScriptProject or
- * a JarPackageFragmentRot) either because the focus is part of the project or the jar, or because it is
- * accessible throught the project's classpath
- */
-public static boolean canSeeFocus(IJavaScriptElement focus, boolean isPolymorphicSearch, IPath projectOrJarPath) {
- try {
- IIncludePathEntry[] focusEntries = null;
- if (isPolymorphicSearch) {
- JavaProject focusProject = (JavaProject) focus;
- focusEntries = focusProject.getExpandedClasspath();
- }
- IJavaScriptModel model = focus.getJavaScriptModel();
- IJavaScriptProject project = getJavaProject(projectOrJarPath, model);
- if (project != null)
- return canSeeFocus(focus, (JavaProject) project, focusEntries);
-
- // projectOrJarPath is a jar
- // it can see the focus only if it is on the classpath of a project that can see the focus
- IJavaScriptProject[] allProjects = model.getJavaScriptProjects();
- for (int i = 0, length = allProjects.length; i < length; i++) {
- JavaProject otherProject = (JavaProject) allProjects[i];
- IIncludePathEntry entry = otherProject.getClasspathEntryFor(projectOrJarPath);
- if (entry != null
- && entry.getEntryKind() == IIncludePathEntry.CPE_LIBRARY
- && canSeeFocus(focus, otherProject, focusEntries))
- return true;
- }
- return false;
- } catch (JavaScriptModelException e) {
- return false;
- }
-}
-public static boolean canSeeFocus(IJavaScriptElement focus, JavaProject javaProject, IIncludePathEntry[] focusEntriesForPolymorphicSearch) {
- try {
- if (focus.equals(javaProject))
- return true;
-
- if (focusEntriesForPolymorphicSearch != null) {
- // look for refering project
- IPath projectPath = javaProject.getProject().getFullPath();
- for (int i = 0, length = focusEntriesForPolymorphicSearch.length; i < length; i++) {
- IIncludePathEntry entry = focusEntriesForPolymorphicSearch[i];
- if (entry.getEntryKind() == IIncludePathEntry.CPE_PROJECT && entry.getPath().equals(projectPath))
- return true;
- }
- }
- if (focus instanceof LibraryFragmentRoot || focus instanceof PackageFragmentRoot) {
- // focus is part of a jar
- IPath focusPath = focus.getPath();
- IIncludePathEntry[] entries = javaProject.getExpandedClasspath();
- for (int i = 0, length = entries.length; i < length; i++) {
- IIncludePathEntry entry = entries[i];
- if ((entry.getEntryKind() == IIncludePathEntry.CPE_LIBRARY || entry.getEntryKind() == IIncludePathEntry.CPE_SOURCE) && entry.getPath().equals(focusPath))
- return true;
- }
- if(focus instanceof LibraryFragmentRoot)
- return false;
- }
- // look for dependent projects
- IPath focusPath = null;
- if(focus instanceof PackageFragmentRoot)
- focusPath = ((JavaProject) focus.getParent()).getProject().getFullPath();
- else
- focusPath = ((JavaProject) focus).getProject().getFullPath();
- IIncludePathEntry[] entries = javaProject.getExpandedClasspath();
- for (int i = 0, length = entries.length; i < length; i++) {
- IIncludePathEntry entry = entries[i];
- if (entry.getEntryKind() == IIncludePathEntry.CPE_PROJECT && entry.getPath().equals(focusPath))
- return true;
- }
- return false;
- } catch (JavaScriptModelException e) {
- return false;
- }
-}
-/*
- * Compute the list of paths which are keying index files.
- */
-private void initializeIndexLocations() {
- IPath[] projectsAndJars = this.searchScope.enclosingProjectsAndJars();
- IndexManager manager = JavaModelManager.getJavaModelManager().getIndexManager();
- SimpleSet locations = new SimpleSet();
- IJavaScriptElement focus = MatchLocator.projectOrJarFocus(this.pattern);
- if (focus == null) {
- for (int i = 0; i < projectsAndJars.length; i++)
- locations.add(manager.computeIndexLocation(projectsAndJars[i]));
- } else {
- try {
- // find the projects from projectsAndJars that see the focus then walk those projects looking for the jars from projectsAndJars
- int length = projectsAndJars.length;
- JavaProject[] projectsCanSeeFocus = new JavaProject[length];
- SimpleSet visitedProjects = new SimpleSet(length);
- int projectIndex = 0;
- SimpleSet jarsToCheck = new SimpleSet(length);
- IIncludePathEntry[] focusEntries = null;
- if (this.pattern instanceof MethodPattern) { // should consider polymorphic search for method patterns
- JavaProject focusProject = focus instanceof LibraryFragmentRoot || focus instanceof PackageFragmentRoot ? (JavaProject) focus.getParent() : (JavaProject) focus;
- focusEntries = focusProject.getExpandedClasspath();
- }
- IJavaScriptModel model = JavaModelManager.getJavaModelManager().getJavaModel();
- for (int i = 0; i < length; i++) {
- IPath path = projectsAndJars[i];
- JavaProject project = (JavaProject) getJavaProject(path, model);
- if (project != null) {
- visitedProjects.add(project);
- if (canSeeFocus(focus, project, focusEntries)) {
- locations.add(manager.computeIndexLocation(path));
- projectsCanSeeFocus[projectIndex++] = project;
- }
- } else {
- jarsToCheck.add(path);
- }
- }
- for (int i = 0; i < projectIndex && jarsToCheck.elementSize > 0; i++) {
- IIncludePathEntry[] entries = projectsCanSeeFocus[i].getResolvedClasspath();
- for (int j = entries.length; --j >= 0;) {
- IIncludePathEntry entry = entries[j];
- if (entry.getEntryKind() == IIncludePathEntry.CPE_LIBRARY) {
- IPath path = entry.getPath();
- if (jarsToCheck.includes(path)) {
- locations.add(manager.computeIndexLocation(entry.getPath()));
- jarsToCheck.remove(path);
- }
- }
- }
- }
- // jar files can be included in the search scope without including one of the projects that references them, so scan all projects that have not been visited
- if (jarsToCheck.elementSize > 0) {
- IJavaScriptProject[] allProjects = model.getJavaScriptProjects();
- for (int i = 0, l = allProjects.length; i < l && jarsToCheck.elementSize > 0; i++) {
- JavaProject project = (JavaProject) allProjects[i];
- if (!visitedProjects.includes(project)) {
- IIncludePathEntry[] entries = project.getResolvedClasspath();
- for (int j = entries.length; --j >= 0;) {
- IIncludePathEntry entry = entries[j];
- if (entry.getEntryKind() == IIncludePathEntry.CPE_LIBRARY) {
- IPath path = entry.getPath();
- if (jarsToCheck.includes(path)) {
- locations.add(manager.computeIndexLocation(entry.getPath()));
- jarsToCheck.remove(path);
- }
- }
- }
- }
- }
- }
- } catch (JavaScriptModelException e) {
- // ignored
- }
- }
-
- this.indexLocations = new IPath[locations.elementSize];
- Object[] values = locations.values;
- int count = 0;
- for (int i = values.length; --i >= 0;)
- if (values[i] != null)
- this.indexLocations[count++] = (IPath) values[i];
-}
-public IPath[] getIndexLocations() {
- if (this.indexLocations == null) {
- this.initializeIndexLocations();
- }
- return this.indexLocations;
-}
-
-/**
- * Returns the java project that corresponds to the given path.
- * Returns null if the path doesn't correspond to a project.
- */
-private static IJavaScriptProject getJavaProject(IPath path, IJavaScriptModel model) {
- IJavaScriptProject project = model.getJavaScriptProject(path.lastSegment());
- if (project.exists()) {
- return project;
- }
- return null;
-}
-}
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
deleted file mode 100644
index 9eae996b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/JavaSearchDocument.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*******************************************************************************
- * 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.resources.IFile;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchDocument;
-import org.eclipse.wst.jsdt.core.search.SearchParticipant;
-import org.eclipse.wst.jsdt.internal.core.search.processing.JobManager;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-public class JavaSearchDocument extends SearchDocument {
-
- private IFile file;
- protected byte[] byteContents;
- protected char[] charContents;
- private String packageName;
-
- public JavaSearchDocument(String documentPath, SearchParticipant participant) {
- super(documentPath, participant);
- }
- 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( IPath filePath, char[] contents, SearchParticipant participant, String packageName) {
- super(filePath.toString(), participant);
- this.charContents = contents;
- this.packageName=packageName;
-
- }
-
- public byte[] getByteContents() {
- if (this.byteContents != null) return this.byteContents;
- try {
- return Util.getResourceContentsAsByteArray(getFile());
- } catch (JavaScriptModelException e) {
- if (BasicSearchEngine.VERBOSE || JobManager.VERBOSE) { // used during search and during indexing
- e.printStackTrace();
- }
- return null;
- }
- }
- public char[] getCharContents() {
- if (this.charContents != null) return this.charContents;
- try {
- return Util.getResourceContentsAsCharArray(getFile());
- } catch (JavaScriptModelException e) {
- if (BasicSearchEngine.VERBOSE || JobManager.VERBOSE) { // used during search and during indexing
- e.printStackTrace();
- }
- return null;
- }
- }
- public String getEncoding() {
- // Return the encoding of the associated file
- IFile resource = getFile();
- if (resource != null) {
- try {
- return resource.getCharset();
- }
- catch(CoreException ce) {
- try {
- return ResourcesPlugin.getWorkspace().getRoot().getDefaultCharset();
- } catch (CoreException e) {
- // use no encoding
- }
- }
- }
- return null;
- }
- private IFile getFile() {
- if (this.file == null)
- this.file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(getPath()));
- return this.file;
- }
- public String toString() {
- return "SearchDocument for " + getPath(); //$NON-NLS-1$
- }
- public String getPackageName() {
- return packageName;
- }
-}
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
deleted file mode 100644
index b3e20a11..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/JavaSearchParticipant.java
+++ /dev/null
@@ -1,120 +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;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-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.core.search.indexing.SourceIndexer;
-import org.eclipse.wst.jsdt.internal.core.search.matching.MatchLocator;
-
-/**
- * A search participant describes a particular extension to a generic search mechanism, allowing thus to
- * perform combined search actions which will involve all required participants
- *
- * A search scope defines which participants are involved.
- *
- * A search participant is responsible for holding index files, and selecting the appropriate ones to feed to
- * index queries. It also can map a document path to an actual document (note that documents could live outside
- * the workspace or no exist yet, and thus aren't just resources).
- */
-public class JavaSearchParticipant extends SearchParticipant {
-
- IndexSelector indexSelector;
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.search.SearchParticipant#beginSearching()
- */
- public void beginSearching() {
- super.beginSearching();
- this.indexSelector = null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.search.SearchParticipant#doneSearching()
- */
- public void doneSearching() {
- this.indexSelector = null;
- super.doneSearching();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.search.SearchParticipant#getName()
- */
- public String getDescription() {
- return "JavaScript"; //$NON-NLS-1$
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.search.SearchParticipant#getDocument(String)
- */
- public SearchDocument getDocument(String documentPath) {
- return new JavaSearchDocument(documentPath, this);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.search.SearchParticipant#indexDocument(SearchDocument)
- */
- public void indexDocument(SearchDocument document, IPath indexPath) {
- // TODO must verify that the document + indexPath match, when this is not called from scheduleDocumentIndexing
- document.removeAllIndexEntries(); // in case the document was already indexed
-
- String documentPath = document.getPath();
- if (org.eclipse.wst.jsdt.internal.core.util.Util.isJavaLikeFileName(documentPath)) {
- new SourceIndexer(document).indexDocument();
- }
- 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();
-// }
- }
-
- /* (non-Javadoc)
- * @see SearchParticipant#locateMatches(SearchDocument[], SearchPattern, IJavaScriptSearchScope, SearchRequestor, IProgressMonitor)
- */
- public void locateMatches(SearchDocument[] indexMatches, SearchPattern pattern,
- IJavaScriptSearchScope scope, SearchRequestor requestor, IProgressMonitor monitor) throws CoreException {
-
- MatchLocator matchLocator =
- new MatchLocator(
- pattern,
- requestor,
- scope,
- monitor
- );
-
- /* eliminating false matches and locating them */
- if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException();
- matchLocator.locateMatches(indexMatches);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.search.SearchParticipant#selectIndexes(org.eclipse.wst.jsdt.core.search.SearchQuery, org.eclipse.wst.jsdt.core.search.SearchContext)
- */
- public IPath[] selectIndexes(
- SearchPattern pattern,
- IJavaScriptSearchScope scope) {
-
- if (this.indexSelector == null) {
- this.indexSelector = new IndexSelector(scope, pattern);
- }
- return this.indexSelector.getIndexLocations();
- }
-
-}
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
deleted file mode 100644
index 9f297e56..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/JavaSearchScope.java
+++ /dev/null
@@ -1,710 +0,0 @@
-/*******************************************************************************
- * 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.search;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Hashtable;
-import java.util.Map;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-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.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptElementDelta;
-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.IMember;
-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.internal.compiler.env.AccessRuleSet;
-import org.eclipse.wst.jsdt.internal.core.ClasspathEntry;
-import org.eclipse.wst.jsdt.internal.core.JavaElement;
-import org.eclipse.wst.jsdt.internal.core.JavaModel;
-import org.eclipse.wst.jsdt.internal.core.JavaModelManager;
-import org.eclipse.wst.jsdt.internal.core.JavaProject;
-import org.eclipse.wst.jsdt.internal.core.PackageFragment;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * A Java-specific scope for searching relative to one or more java elements.
- */
-public class JavaSearchScope extends AbstractSearchScope {
-
- private ArrayList elements;
-
- /* The paths of the resources in this search scope
- (or the classpath entries' paths if the resources are projects)
- */
- private ArrayList projectPaths = new ArrayList(); // container paths projects
- private int[] projectIndexes; // Indexes of projects in list
- private String[] containerPaths; // path to the container (e.g. /P/src, /P/lib.jar, c:\temp\mylib.jar)
- private String[] relativePaths; // path relative to the container (e.g. x/y/Z.class, x/y, (empty))
- private boolean[] isPkgPath; // in the case of packages, matches must be direct children of the folder
- protected AccessRuleSet[] pathRestrictions;
- private int pathsCount;
- private int threshold;
-
- private IPath[] enclosingProjectsAndJars;
- private Hashtable exclusionPathList = new Hashtable();
-
- public final static AccessRuleSet NOT_ENCLOSED = new AccessRuleSet(null, null);
-
-public JavaSearchScope() {
- this(5);
-}
-
-private JavaSearchScope(int size) {
- initialize(size);
-
- //disabled for now as this could be expensive
- //JavaModelManager.getJavaModelManager().rememberScope(this);
-}
-
-private void addEnclosingProjectOrJar(IPath path) {
- int length = this.enclosingProjectsAndJars.length;
- for (int i = 0; i < length; i++) {
- if (this.enclosingProjectsAndJars[i].equals(path)) return;
- }
- System.arraycopy(
- this.enclosingProjectsAndJars,
- 0,
- this.enclosingProjectsAndJars = new IPath[length+1],
- 0,
- length);
- this.enclosingProjectsAndJars[length] = path;
-}
-
-/**
- * Add java project all fragment roots to current java search scope.
- * @see #add(JavaProject, IPath, int, HashSet, IIncludePathEntry)
- */
-public void add(JavaProject project, int includeMask, HashSet visitedProject) throws JavaScriptModelException {
- add(project, null, includeMask, visitedProject, null);
-}
-/**
- * Add a path to current java search scope or all project fragment roots if null.
- * Use project resolved classpath to retrieve and store access restriction on each classpath entry.
- * Recurse if dependent projects are found.
- * @param javaProject Project used to get resolved classpath entries
- * @param pathToAdd Path to add in case of single element or null if user want to add all project package fragment roots
- * @param includeMask Mask to apply on classpath entries
- * @param visitedProjects Set to avoid infinite recursion
- * @param referringEntry Project raw entry in referring project classpath
- * @throws JavaScriptModelException May happen while getting java model info
- */
-void add(JavaProject javaProject, IPath pathToAdd, int includeMask, HashSet visitedProjects, IIncludePathEntry referringEntry) throws JavaScriptModelException {
- IProject project = javaProject.getProject();
- if (!project.isAccessible() || !visitedProjects.add(project)) return;
-
- IPath projectPath = project.getFullPath();
- String projectPathString = projectPath.toString();
- this.addEnclosingProjectOrJar(projectPath);
-
- IIncludePathEntry[] entries = javaProject.getResolvedClasspath();
- IJavaScriptModel model = javaProject.getJavaScriptModel();
- JavaModelManager.PerProjectInfo perProjectInfo = javaProject.getPerProjectInfo();
- for (int i = 0, length = entries.length; i < length; i++) {
- IIncludePathEntry entry = entries[i];
- AccessRuleSet access = null;
- ClasspathEntry cpEntry = (ClasspathEntry) entry;
- if (referringEntry != null) {
- // Add only exported entries.
- // Source folder are implicitly exported.
- if (!entry.isExported() && entry.getEntryKind() != IIncludePathEntry.CPE_SOURCE) continue;
- cpEntry = cpEntry.combineWith((ClasspathEntry)referringEntry);
-// cpEntry = ((ClasspathEntry)referringEntry).combineWith(cpEntry);
- }
- access = cpEntry.getAccessRuleSet();
- switch (entry.getEntryKind()) {
- case IIncludePathEntry.CPE_LIBRARY:
- IIncludePathEntry rawEntry = null;
- Map rootPathToRawEntries = perProjectInfo.rootPathToRawEntries;
- if (rootPathToRawEntries != null) {
- rawEntry = (IIncludePathEntry) rootPathToRawEntries.get(entry.getPath());
- }
- if (rawEntry == null) break;
- switch (rawEntry.getEntryKind()) {
- case IIncludePathEntry.CPE_LIBRARY:
- case IIncludePathEntry.CPE_VARIABLE:
- if ((includeMask & APPLICATION_LIBRARIES) != 0) {
- IPath path = entry.getPath();
- if (pathToAdd == null || pathToAdd.equals(path)) {
- String pathToString = path.getDevice() == null ? path.toString() : path.toOSString();
- add(projectPath.toString(), "", pathToString, false/*not a package*/, access); //$NON-NLS-1$
- addEnclosingProjectOrJar(path);
- }
- }
- break;
- case IIncludePathEntry.CPE_CONTAINER:
- IJsGlobalScopeContainer container = JavaScriptCore.getJsGlobalScopeContainer(rawEntry.getPath(), javaProject);
- if (container == null) break;
- if ((container.getKind() == IJsGlobalScopeContainer.K_APPLICATION && (includeMask & APPLICATION_LIBRARIES) != 0)
- || (includeMask & SYSTEM_LIBRARIES) != 0) {
- IPath path = entry.getPath();
- if (pathToAdd == null || pathToAdd.equals(path)) {
- String pathToString = path.getDevice() == null ? path.toString() : path.toOSString();
- add(projectPath.toString(), "", pathToString, false/*not a package*/, access); //$NON-NLS-1$
- addEnclosingProjectOrJar(path);
- }
- }
- break;
- }
- break;
- case IIncludePathEntry.CPE_PROJECT:
- if ((includeMask & REFERENCED_PROJECTS) != 0) {
- IPath path = entry.getPath();
- if (pathToAdd == null || pathToAdd.equals(path)) {
- add((JavaProject) model.getJavaScriptProject(entry.getPath().lastSegment()), null, includeMask, visitedProjects, cpEntry);
- }
- }
- break;
- case IIncludePathEntry.CPE_SOURCE:
- if ((includeMask & SOURCES) != 0) {
- IPath path = entry.getPath();
- if (pathToAdd == null || pathToAdd.equals(path)) {
- add(projectPath.toString(), Util.relativePath(path,1/*remove project segment*/), projectPathString, false/*not a package*/, access);
- }
- }
- break;
- }
- }
-}
-/**
- * Add an element to the java search scope.
- * @param element The element we want to add to current java search scope
- * @throws JavaScriptModelException May happen if some Java Model info are not available
- */
-public void add(IJavaScriptElement element) throws JavaScriptModelException {
- IPath containerPath = null;
- String containerPathToString = null;
- int includeMask = SOURCES | APPLICATION_LIBRARIES | SYSTEM_LIBRARIES;
- switch (element.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_MODEL:
- // a workspace sope should be used
- break;
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- add((JavaProject)element, null, includeMask, new HashSet(2), null);
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- IPackageFragmentRoot root = (IPackageFragmentRoot)element;
-
-
- IPath rootPath = root.getPath();
-
- IIncludePathEntry entry = root.getResolvedIncludepathEntry();
- if(entry == null)
- break;
- IPath[] exclusionsPaths = entry.getExclusionPatterns();
-
- if(exclusionsPaths!=null && exclusionsPaths.length>0)
- addExclusions(rootPath, exclusionsPaths);
-
-
- containerPath = root.getKind() == IPackageFragmentRoot.K_SOURCE ? root.getParent().getPath() : rootPath;
- containerPathToString = containerPath.getDevice() == null ? containerPath.toString() : containerPath.toOSString();
- IResource rootResource = root.getResource();
- String projectPath = root.getJavaScriptProject().getPath().toString();
- if (rootResource != null && rootResource.isAccessible()) {
- String relativePath = Util.relativePath(rootResource.getFullPath(), containerPath.segmentCount());
- add(projectPath, relativePath, containerPathToString, false/*not a package*/, null);
- } else {
- add(projectPath, "", containerPathToString, false/*not a package*/, null); //$NON-NLS-1$
- }
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- root = (IPackageFragmentRoot)element.getParent();
- projectPath = root.getJavaScriptProject().getPath().toString();
- if (root.isArchive()) {
- 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);
- } else {
- IResource resource = element.getResource();
- if (resource != null) {
- if (resource.isAccessible()) {
- containerPath = root.getKind() == IPackageFragmentRoot.K_SOURCE ? root.getParent().getPath() : root.getPath();
- } else {
- // for working copies, get resource container full path
- containerPath = resource.getParent().getFullPath();
- }
- containerPathToString = containerPath.getDevice() == null ? containerPath.toString() : containerPath.toOSString();
- String relativePath = Util.relativePath(resource.getFullPath(), containerPath.segmentCount());
- add(projectPath, relativePath, containerPathToString, true/*package*/, null);
- }
- }
- break;
- default:
- // remember sub-cu (or sub-class file) java elements
- if (element instanceof IMember) {
- if (this.elements == null) {
- this.elements = new ArrayList();
- }
- this.elements.add(element);
- }
- root = (IPackageFragmentRoot) element.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- projectPath = root.getJavaScriptProject().getPath().toString();
- String relativePath;
- if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
- containerPath = root.getParent().getPath();
- relativePath = Util.relativePath(getPath(element, false/*full path*/), 1/*remove project segmet*/);
- } else {
- containerPath = root.getPath();
- relativePath = getPath(element, true/*relative path*/).toString();
- }
- containerPathToString = containerPath.getDevice() == null ? containerPath.toString() : containerPath.toOSString();
- add(projectPath, relativePath, containerPathToString, false/*not a package*/, null);
- }
-
- if (containerPath != null)
- addEnclosingProjectOrJar(containerPath);
-}
-
-/**
- * @param exclusionsPaths
- */
-private void addExclusions(IPath containerPath, IPath[] exclusionsPaths) {
-
- this.exclusionPathList.put(containerPath.toString(), exclusionsPaths);
-}
-
-public boolean shouldExclude(String container, String resourceName) {
- boolean shouldExclude = false;
-
- if(container==null || resourceName==null || exclusionPathList.size()==0) return false;
-
- IPath[] exclusions = (IPath[])exclusionPathList.get(container);
- if(exclusions==null) return false;
- IPath fullPath = new Path(container + "/" + resourceName); //$NON-NLS-1$
-
- for(int i=0;!shouldExclude && i<exclusions.length;i++) {
- shouldExclude = Util.isExcluded(fullPath, null, new char[][] {exclusions[i].toString().toCharArray()});
- }
-
- return shouldExclude;
-}
-
-/**
- * Adds the given path to this search scope. Remember if subfolders need to be included
- * and associated access restriction as well.
- */
-private void add(String projectPath, String relativePath, String containerPath, boolean isPackage, AccessRuleSet access) {
- // normalize containerPath and relativePath
- containerPath = normalize(containerPath);
- relativePath = normalize(relativePath);
- int length = this.containerPaths.length,
- index = (containerPath.hashCode()& 0x7FFFFFFF) % length;
- String currentRelativePath, currentContainerPath;
- while ((currentRelativePath = this.relativePaths[index]) != null && (currentContainerPath = this.containerPaths[index]) != null) {
- if (currentRelativePath.equals(relativePath) && currentContainerPath.equals(containerPath))
- return;
- if (++index == length) {
- index = 0;
- }
- }
- int idx = this.projectPaths.indexOf(projectPath);
- if (idx == -1) {
- // store project in separated list to minimize memory footprint
- this.projectPaths.add(projectPath);
- idx = this.projectPaths.indexOf(projectPath);
- }
- this.projectIndexes[index] = idx;
- this.relativePaths[index] = relativePath;
- this.containerPaths[index] = containerPath;
- this.isPkgPath[index] = isPackage;
- if (this.pathRestrictions != null)
- this.pathRestrictions[index] = access;
- else if (access != null) {
- this.pathRestrictions = new AccessRuleSet[this.relativePaths.length];
- this.pathRestrictions[index] = access;
- }
-
- // assumes the threshold is never equal to the size of the table
- if (++this.pathsCount > this.threshold)
- rehash();
-}
-
-/*
- * E.g.
- *
- * 1. /P/src/pkg/X.js
- * 2. /P/src/pkg
- * 3. /P/lib.jar|org/eclipse/jdt/core/IJavaScriptElement.class
- * 4. /home/mylib.jar|x/y/z/X.class
- * 5. c:\temp\mylib.jar|x/y/Y.class
- *
- * @see IJavaScriptSearchScope#encloses(String)
- */
-public boolean encloses(String resourcePathString) {
- int separatorIndex = resourcePathString.indexOf(JAR_FILE_ENTRY_SEPARATOR);
- if (separatorIndex != -1) {
- // internal or external jar (case 3, 4, or 5)
- String jarPath = resourcePathString.substring(0, separatorIndex);
- String relativePath = resourcePathString.substring(separatorIndex+1);
- return indexOf(jarPath, relativePath) >= 0;
- }
- // resource in workspace (case 1 or 2)
- return indexOf(resourcePathString) >= 0;
-}
-
-/**
- * <p>Returns paths list index of given path or -1 if not found.
- * If there are multiple paths in the index that enclose the given path,
- * the index for the most specific enclosing path will be given.</p>
- *
- * NOTE: Use indexOf(String, String) for path inside jars
- *
- * @param fullPath the full path of the resource, e.g.
- * 1. /P/src/pkg/X.js
- * 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
- int answer = -1;
- String answerFullPath = null;
- for (int i = 0, length = this.relativePaths.length; i < length; i++) {
- String currentRelativePath = this.relativePaths[i];
- if (currentRelativePath == null) continue;
- String currentContainerPath = this.containerPaths[i];
- String currentFullPath = currentRelativePath.length() == 0 ? currentContainerPath : (currentContainerPath + '/' + currentRelativePath);
- if (encloses(currentFullPath, fullPath, i)) {
- /*
- * BUG330274 : If have not found answer yet or the new answer
- * 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)) {
- answerFullPath = currentFullPath;
- answer = i;
- }
- }
- }
-
- return answer;
-}
-
-/**
- * Returns paths list index of given path or -1 if not found.
- * @param containerPath the path of the container, e.g.
- * 1. /P/src
- * 2. /P
- * 3. /P/lib.jar
- * 4. /home/mylib.jar
- * 5. c:\temp\mylib.jar
- * @param relativePath the forward slash path relatively to the container, e.g.
- * 1. x/y/Z.class
- * 2. x/y
- * 3. X.js
- * 4. (empty)
- */
-private int indexOf(String containerPath, String relativePath) {
- // use the hash to get faster comparison
- int length = this.containerPaths.length,
- index = (containerPath.hashCode()& 0x7FFFFFFF) % length;
- String currentContainerPath;
- while ((currentContainerPath = this.containerPaths[index]) != null) {
- if (currentContainerPath.equals(containerPath)) {
- String currentRelativePath = this.relativePaths[index];
- if (encloses(currentRelativePath, relativePath, index))
- return index;
- }
- if (++index == length) {
- index = 0;
- }
- }
- return -1;
-}
-
-/*
- * 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
- path = normalize(path);
-
- int pathLength = path.length();
- int enclosingLength = enclosingPath.length();
- if (pathLength < enclosingLength) {
- return false;
- }
- if (enclosingLength == 0) {
- return true;
- }
- if (pathLength == enclosingLength) {
- IPath path1 = new Path(path);
- IPath path2 = new Path(enclosingPath);
- return path1.equals(path2);
- }
- if (!this.isPkgPath[index]) {
- return path.startsWith(enclosingPath)
- && path.charAt(enclosingLength) == '/';
- } else {
- // if looking at a package, this scope encloses the given path
- // if the given path is a direct child of the folder
- // or if the given path path is the folder path (see bug 13919 Declaration for package not found if scope is not project)
- if (path.startsWith(enclosingPath)
- && ((enclosingPath.length() == path.lastIndexOf('/'))
- || (enclosingPath.length() == path.length()))) {
- return true;
- }
- }
- return false;
-}
-
-/* (non-Javadoc)
- * @see IJavaScriptSearchScope#encloses(IJavaScriptElement)
- */
-public boolean encloses(IJavaScriptElement element) {
- if (this.elements != null) {
- for (int i = 0, length = this.elements.size(); i < length; i++) {
- IJavaScriptElement scopeElement = (IJavaScriptElement)this.elements.get(i);
- IJavaScriptElement searchedElement = element;
- while (searchedElement != null) {
- if (searchedElement.equals(scopeElement))
- return true;
- searchedElement = searchedElement.getParent();
- }
- }
- return false;
- }
- IPackageFragmentRoot root = (IPackageFragmentRoot) element.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- if (root != null && root.isArchive()) {
- // external or internal jar
- IPath rootPath = root.getPath();
- String rootPathToString = rootPath.getDevice() == null ? rootPath.toString() : rootPath.toOSString();
- IPath relativePath = getPath(element, true/*relative path*/);
- return indexOf(rootPathToString, relativePath.toString()) >= 0;
- }
- // resource in workspace
- String fullResourcePathString = getPath(element, false/*full path*/).toString();
- return indexOf(fullResourcePathString) >= 0;
-}
-
-/* (non-Javadoc)
- * @see IJavaScriptSearchScope#enclosingProjectsAndJars()
- */
-public IPath[] enclosingProjectsAndJars() {
- return this.enclosingProjectsAndJars;
-}
-private IPath getPath(IJavaScriptElement element, boolean relativeToRoot) {
- switch (element.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_MODEL:
- return Path.EMPTY;
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- return element.getPath();
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- if (relativeToRoot)
- return Path.EMPTY;
- return element.getPath();
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- String relativePath = Util.concatWith(((PackageFragment) element).names, '/');
- return getPath(element.getParent(), relativeToRoot).append(new Path(relativePath));
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- case IJavaScriptElement.CLASS_FILE:
- return getPath(element.getParent(), relativeToRoot).append(new Path(element.getElementName()));
- default:
- return getPath(element.getParent(), relativeToRoot);
- }
-}
-
-/**
- * Get access rule set corresponding to a given path.
- * @param relativePath The path user want to have restriction access
- * @return The access rule set for given path or null if none is set for it.
- * Returns specific uninit access rule set when scope does not enclose the given path.
- */
-public AccessRuleSet getAccessRuleSet(String relativePath, String containerPath) {
- int index = indexOf(containerPath, relativePath);
- if (index == -1) {
- // this search scope does not enclose given path
- return NOT_ENCLOSED;
- }
- if (this.pathRestrictions == null)
- return null;
- return this.pathRestrictions[index];
-}
-
-protected void initialize(int size) {
- this.pathsCount = 0;
- this.threshold = size; // size represents the expected number of elements
- int extraRoom = (int) (size * 1.75f);
- if (this.threshold == extraRoom)
- extraRoom++;
- this.relativePaths = new String[extraRoom];
- this.containerPaths = new String[extraRoom];
- this.projectPaths = new ArrayList();
- this.projectIndexes = new int[extraRoom];
- this.isPkgPath = new boolean[extraRoom];
- this.pathRestrictions = null; // null to optimize case where no access rules are used
-
- this.enclosingProjectsAndJars = new IPath[0];
-}
-
-/*
- * Removes trailing slashes from the given path
- */
-private String normalize(String path) {
- int pathLength = path.length();
- int index = pathLength-1;
- while (index >= 0 && path.charAt(index) == '/')
- index--;
- if (index != pathLength-1)
- return path.substring(0, index + 1);
- return path;
-}
-
-/*
- * @see AbstractSearchScope#processDelta(IJavaScriptElementDelta)
- */
-public void processDelta(IJavaScriptElementDelta delta) {
- switch (delta.getKind()) {
- case IJavaScriptElementDelta.CHANGED:
- IJavaScriptElementDelta[] children = delta.getAffectedChildren();
- for (int i = 0, length = children.length; i < length; i++) {
- IJavaScriptElementDelta child = children[i];
- this.processDelta(child);
- }
- break;
- case IJavaScriptElementDelta.REMOVED:
- IJavaScriptElement element = delta.getElement();
- if (this.encloses(element)) {
- if (this.elements != null) {
- this.elements.remove(element);
- }
- IPath path = null;
- switch (element.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- path = ((IJavaScriptProject)element).getProject().getFullPath();
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- 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 !
- toRemove = i;
- break;
- }
- }
- if (toRemove != -1) {
- this.relativePaths[toRemove] = null;
- rehash();
- }
- }
- }
- break;
- }
-}
-
-/**
- * Returns the package fragment root corresponding to a given resource path.
- *
- * @param resourcePathString path of expected package fragment root.
- * @return the {@link IPackageFragmentRoot package fragment root} which path
- * match the given one or <code>null</code> if none was found.
- */
-public IPackageFragmentRoot packageFragmentRoot(String resourcePathString) {
- int index = -1;
- int separatorIndex = resourcePathString.indexOf(JAR_FILE_ENTRY_SEPARATOR);
- boolean isJarFile = separatorIndex != -1;
- if (isJarFile) {
- // internal or external jar (case 3, 4, or 5)
- String jarPath = resourcePathString.substring(0, separatorIndex);
- String relativePath = resourcePathString.substring(separatorIndex+1);
- index = indexOf(jarPath, relativePath);
- } else {
- // resource in workspace (case 1 or 2)
- index = indexOf(resourcePathString);
- }
- if (index >= 0) {
- int idx = projectIndexes[index];
- String projectPath = idx == -1 ? null : (String) this.projectPaths.get(idx);
- if (projectPath != null) {
- IJavaScriptProject project =JavaScriptCore.create(ResourcesPlugin.getWorkspace().getRoot().getProject(projectPath));
- if (isJarFile) {
- return project.getPackageFragmentRoot(this.containerPaths[index]);
- }
- Object target = JavaModel.getTarget(ResourcesPlugin.getWorkspace().getRoot(), new Path(this.containerPaths[index]+'/'+this.relativePaths[index]), false);
- if (target instanceof IProject) {
- return project.getPackageFragmentRoot((IProject) target);
- }
- if (target instanceof IResource) {
- IJavaScriptElement element = JavaScriptCore.create((IResource)target);
- return (IPackageFragmentRoot) element.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- }
- if (target instanceof File)
- {
- return project.getPackageFragmentRoot(this.containerPaths[index]);
- }
- }
- }
- return null;
-}
-
-private void rehash() {
- JavaSearchScope newScope = new JavaSearchScope(this.pathsCount * 2); // double the number of expected elements
- newScope.projectPaths.ensureCapacity(this.projectPaths.size());
- String currentPath;
- for (int i = this.relativePaths.length; --i >= 0;)
- if ((currentPath = this.relativePaths[i]) != null) {
- int idx = this.projectIndexes[i];
- String projectPath = idx == -1 ? null : (String)this.projectPaths.get(idx);
- newScope.add(projectPath, currentPath, this.containerPaths[i], this.isPkgPath[i], this.pathRestrictions == null ? null : this.pathRestrictions[i]);
- }
-
- this.relativePaths = newScope.relativePaths;
- this.containerPaths = newScope.containerPaths;
- this.projectPaths = newScope.projectPaths;
- this.projectIndexes = newScope.projectIndexes;
- this.isPkgPath = newScope.isPkgPath;
- this.pathRestrictions = newScope.pathRestrictions;
- this.threshold = newScope.threshold;
-}
-
-public String toString() {
- StringBuffer result = new StringBuffer("JavaSearchScope on "); //$NON-NLS-1$
- if (this.elements != null) {
- result.append("["); //$NON-NLS-1$
- for (int i = 0, length = this.elements.size(); i < length; i++) {
- JavaElement element = (JavaElement)this.elements.get(i);
- result.append("\n\t"); //$NON-NLS-1$
- result.append(element.toStringWithAncestors());
- }
- result.append("\n]"); //$NON-NLS-1$
- } else {
- if (this.pathsCount == 0) {
- result.append("[empty scope]"); //$NON-NLS-1$
- } else {
- result.append("["); //$NON-NLS-1$
- for (int i = 0; i < this.relativePaths.length; i++) {
- String path = this.relativePaths[i];
- if (path == null) continue;
- result.append("\n\t"); //$NON-NLS-1$
- result.append(this.containerPaths[i]);
- if (path.length() > 0) {
- result.append('/');
- result.append(path);
- }
- }
- result.append("\n]"); //$NON-NLS-1$
- }
- }
- return result.toString();
-}
-}
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
deleted file mode 100644
index a630d454..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/JavaSearchTypeNameMatch.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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.IType;
-import org.eclipse.wst.jsdt.core.search.TypeNameMatch;
-
-/**
- * Java Search concrete class for a type name match.
- *
- * @since 3.3
- */
-public class JavaSearchTypeNameMatch extends TypeNameMatch {
-
-private IType type;
-private int modifiers = -1; // store modifiers to avoid java model population
-
-/**
- * Creates a new Java Search type name match.
- */
-public JavaSearchTypeNameMatch(IType type, int modifiers) {
- this.type = type;
- this.modifiers = modifiers;
-}
-
-/* (non-Javadoc)
- * Returns whether the matched type is equals to the given object or not.
- * @see java.lang.Object#equals(java.lang.Object)
- */
-public boolean equals(Object obj) {
- if (obj == this) return true; // avoid unnecessary calls for identical objects
- if (obj instanceof TypeNameMatch) {
- TypeNameMatch match = (TypeNameMatch) obj;
- if (this.type == null) {
- return match.getType() == null && match.getModifiers() == this.modifiers;
- }
- return this.type.equals(match.getType()) && match.getModifiers() == this.modifiers;
- }
- return false;
-}
-
-/* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.search.TypeNameMatch#getModifiers()
- */
-public int getModifiers() {
- return this.modifiers;
-}
-
-/* (non-Javadoc)
- * Note that returned handle exists as it matches a type accepted
- * from up-to-date index file.
- * @see org.eclipse.wst.jsdt.core.search.TypeNameMatch#getType()
- */
-public IType getType() {
- return this.type;
-}
-
-/* (non-Javadoc)
- * Returns the hash code of the matched type.
- * @see java.lang.Object#hashCode()
- */
-public int hashCode() {
- if (this.type == null) return this.modifiers;
- return this.type.hashCode();
-}
-
-/**
- * Set modifiers of the matched type.
- *
- * @param modifiers the modifiers of the matched type.
- */
-public void setModifiers(int modifiers) {
- this.modifiers = modifiers;
-}
-
-/**
- * Set matched type.
- *
- * @param type the matched type.
- */
-public void setType(IType type) {
- this.type = type;
-}
-
-/* (non-Javadoc)
- * Returns the string of the matched type.
- * @see java.lang.Object#toString()
- */
-public String toString() {
- if (this.type == null) return super.toString();
- return this.type.toString();
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/JavaWorkspaceScope.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/JavaWorkspaceScope.java
deleted file mode 100644
index 99bea2a6..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/JavaWorkspaceScope.java
+++ /dev/null
@@ -1,145 +0,0 @@
-/*******************************************************************************
- * 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 java.util.HashSet;
-
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptElementDelta;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.compiler.env.AccessRuleSet;
-import org.eclipse.wst.jsdt.internal.core.JavaModelManager;
-import org.eclipse.wst.jsdt.internal.core.JavaProject;
-
-/**
- * A Java-specific scope for searching the entire workspace.
- * The scope can be configured to not search binaries. By default, binaries
- * are included.
- */
-public class JavaWorkspaceScope extends JavaSearchScope {
-
-protected boolean needsInitialize;
-
-public boolean encloses(IJavaScriptElement element) {
- /*
- if (this.needsInitialize) {
- this.initialize();
- }
- return super.encloses(element);
- */
- /*A workspace scope encloses all java elements (this assumes that the index selector
- * and thus enclosingProjectAndJars() returns indexes on the classpath only and that these
- * indexes are consistent.)
- * NOTE: Returning true gains 20% of a hierarchy build on Object
- */
- return true;
-}
-public boolean encloses(String resourcePathString) {
- /*
- if (this.needsInitialize) {
- this.initialize();
- }
- return super.encloses(resourcePathString);
- */
- /*A workspace scope encloses all resources (this assumes that the index selector
- * and thus enclosingProjectAndJars() returns indexes on the classpath only and that these
- * indexes are consistent.)
- * NOTE: Returning true gains 20% of a hierarchy build on Object
- */
- return true;
-}
-public IPath[] enclosingProjectsAndJars() {
- if (this.needsInitialize) {
- this.initialize(5);
- }
- return super.enclosingProjectsAndJars();
-}
-public boolean equals(Object o) {
- return o instanceof JavaWorkspaceScope;
-}
-public AccessRuleSet getAccessRuleSet(String relativePath, String containerPath) {
- if (this.pathRestrictions == null)
- return null;
- return super.getAccessRuleSet(relativePath, containerPath);
-}
-public int hashCode() {
- return JavaWorkspaceScope.class.hashCode();
-}
-public void initialize(int size) {
- super.initialize(size);
- try {
- IJavaScriptProject[] projects = JavaModelManager.getJavaModelManager().getJavaModel().getJavaScriptProjects();
- for (int i = 0, length = projects.length; i < length; i++) {
- int includeMask = SOURCES | APPLICATION_LIBRARIES | SYSTEM_LIBRARIES;
- add((JavaProject) projects[i], null, includeMask, new HashSet(length*2, 1), null);
- }
- } catch (JavaScriptModelException ignored) {
- // ignore
- }
- this.needsInitialize = false;
-}
-public void processDelta(IJavaScriptElementDelta delta) {
- if (this.needsInitialize) return;
- IJavaScriptElement element = delta.getElement();
- switch (element.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_MODEL:
- IJavaScriptElementDelta[] children = delta.getAffectedChildren();
- for (int i = 0, length = children.length; i < length; i++) {
- IJavaScriptElementDelta child = children[i];
- this.processDelta(child);
- }
- break;
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- int kind = delta.getKind();
- switch (kind) {
- case IJavaScriptElementDelta.ADDED:
- case IJavaScriptElementDelta.REMOVED:
- this.needsInitialize = true;
- break;
- case IJavaScriptElementDelta.CHANGED:
- int flags = delta.getFlags();
- if ((flags & IJavaScriptElementDelta.F_CLOSED) != 0
- || (flags & IJavaScriptElementDelta.F_OPENED) != 0) {
- this.needsInitialize = true;
- } else {
- children = delta.getAffectedChildren();
- for (int i = 0, length = children.length; i < length; i++) {
- IJavaScriptElementDelta child = children[i];
- this.processDelta(child);
- }
- }
- break;
- }
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- kind = delta.getKind();
- switch (kind) {
- case IJavaScriptElementDelta.ADDED:
- case IJavaScriptElementDelta.REMOVED:
- this.needsInitialize = true;
- break;
- case IJavaScriptElementDelta.CHANGED:
- int flags = delta.getFlags();
- if ((flags & IJavaScriptElementDelta.F_ADDED_TO_CLASSPATH) > 0
- || (flags & IJavaScriptElementDelta.F_REMOVED_FROM_CLASSPATH) > 0) {
- this.needsInitialize = true;
- }
- break;
- }
- break;
- }
-}
-public String toString() {
- return "JavaWorkspaceScope"; //$NON-NLS-1$
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/PathCollector.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/PathCollector.java
deleted file mode 100644
index 989ae0ba..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/PathCollector.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.search;
-
-import java.util.HashSet;
-import java.util.Iterator;
-
-import org.eclipse.wst.jsdt.core.search.SearchParticipant;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.compiler.env.AccessRuleSet;
-
-/**
- * Collects the resource paths reported by a client to this search requestor.
- */
-public class PathCollector extends IndexQueryRequestor {
-
- /* a set of resource paths */
- public HashSet paths = new HashSet(5);
-
- /* (non-Javadoc)
- * @seeIndexQueryRequestor#acceptIndexMatch(IndexRecord, SearchParticipant, SearchPattern)
- */
- public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access) {
- paths.add(documentPath);
- return true;
- }
-
- /**
- * Returns the paths that have been collected.
- */
- public String[] getPaths() {
- String[] result = new String[this.paths.size()];
- int i = 0;
- for (Iterator iter = this.paths.iterator(); iter.hasNext();) {
- result[i++] = (String)iter.next();
- }
- return result;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/PatternSearchJob.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/PatternSearchJob.java
deleted file mode 100644
index e77d34d8..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/PatternSearchJob.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*******************************************************************************
- * 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 java.io.IOException;
-
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchParticipant;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-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.indexing.IndexManager;
-import org.eclipse.wst.jsdt.internal.core.search.indexing.ReadWriteMonitor;
-import org.eclipse.wst.jsdt.internal.core.search.matching.MatchLocator;
-import org.eclipse.wst.jsdt.internal.core.search.processing.IJob;
-import org.eclipse.wst.jsdt.internal.core.search.processing.JobManager;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-public class PatternSearchJob implements IJob {
-
-protected SearchPattern pattern;
-protected IJavaScriptSearchScope scope;
-protected SearchParticipant participant;
-protected IndexQueryRequestor requestor;
-protected boolean areIndexesReady;
-protected long executionTime = 0;
-
-public PatternSearchJob(SearchPattern pattern, SearchParticipant participant, IJavaScriptSearchScope scope, IndexQueryRequestor requestor) {
- this.pattern = pattern;
- this.participant = participant;
- this.scope = scope;
- this.requestor = requestor;
-}
-public boolean belongsTo(String jobFamily) {
- return true;
-}
-public void cancel() {
- // search job is cancelled through progress
-}
-public void ensureReadyToRun() {
- if (!this.areIndexesReady)
- getIndexes(null/*progress*/); // may trigger some index recreation
-}
-public boolean execute(IProgressMonitor progressMonitor) {
- if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException();
-
- boolean isComplete = COMPLETE;
- executionTime = 0;
- Index[] indexes = getIndexes(progressMonitor);
- try {
- int max = indexes.length;
- if (progressMonitor != null)
- progressMonitor.beginTask("", max); //$NON-NLS-1$
- for (int i = 0; i < max; i++) {
- isComplete &= search(indexes[i], progressMonitor);
- if (progressMonitor != null) {
- if (progressMonitor.isCanceled()) throw new OperationCanceledException();
- progressMonitor.worked(1);
- }
- }
- if (JobManager.VERBOSE)
- Util.verbose("-> execution time: " + executionTime + "ms - " + this);//$NON-NLS-1$//$NON-NLS-2$
- return isComplete;
- } finally {
- if (progressMonitor != null)
- progressMonitor.done();
- }
-}
-public Index[] getIndexes(IProgressMonitor progressMonitor) {
- // acquire the in-memory indexes on the fly
- IPath[] indexLocations = this.participant.selectIndexes(this.pattern, this.scope);
- int length = indexLocations.length;
- Index[] indexes = new Index[length];
- int count = 0;
- IndexManager indexManager = JavaModelManager.getJavaModelManager().getIndexManager();
- for (int i = 0; i < length; i++) {
- if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException();
- // may trigger some index recreation work
- IPath indexLocation = indexLocations[i];
- Index index = indexManager.getIndex(indexLocation);
- if (index == null) {
- // only need containerPath if the index must be built
- IPath containerPath = (IPath) indexManager.indexLocations.keyForValue(indexLocation);
- if (containerPath != null) // sanity check
- index = indexManager.getIndex(containerPath, indexLocation, true /*reuse index file*/, false /*do not create if none*/);
- }
- if (index != null)
- indexes[count++] = index; // only consider indexes which are ready
- }
- if (count == length)
- this.areIndexesReady = true;
- else
- System.arraycopy(indexes, 0, indexes=new Index[count], 0, count);
- return indexes;
-}
-public boolean search(Index index, IProgressMonitor progressMonitor) {
- if (index == null) return COMPLETE;
- if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException();
-
- ReadWriteMonitor monitor = index.monitor;
- if (monitor == null) return COMPLETE; // index got deleted since acquired
- try {
- monitor.enterRead(); // ask permission to read
- long start = System.currentTimeMillis();
- MatchLocator.findIndexMatches(this.pattern, index, requestor, this.participant, this.scope, progressMonitor);
- executionTime += System.currentTimeMillis() - start;
- return COMPLETE;
- } catch (IOException e) {
- if (e instanceof java.io.EOFException)
- e.printStackTrace();
- return FAILED;
- } finally {
- monitor.exitRead(); // finished reading
- }
-}
-public String toString() {
- return "searching " + pattern.toString(); //$NON-NLS-1$
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/SubTypeSearchJob.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/SubTypeSearchJob.java
deleted file mode 100644
index 59a94404..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/SubTypeSearchJob.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*******************************************************************************
- * 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.IProgressMonitor;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchParticipant;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.compiler.util.SimpleSet;
-import org.eclipse.wst.jsdt.internal.core.index.Index;
-
-public class SubTypeSearchJob extends PatternSearchJob {
-
-SimpleSet indexes = new SimpleSet(5);
-
-public SubTypeSearchJob(SearchPattern pattern, SearchParticipant participant, IJavaScriptSearchScope scope, IndexQueryRequestor requestor) {
- super(pattern, participant, scope, requestor);
-}
-public void finished() {
- Object[] values = this.indexes.values;
- for (int i = 0, l = values.length; i < l; i++)
- if (values[i] != null)
- ((Index) values[i]).stopQuery();
-}
-public boolean search(Index index, IProgressMonitor progressMonitor) {
- if (index == null) return COMPLETE;
- if (indexes.addIfNotIncluded(index) == index)
- index.startQuery();
- return super.search(index, progressMonitor);
-}
-}
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
deleted file mode 100644
index 04f604a4..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/TypeNameMatchRequestorWrapper.java
+++ /dev/null
@@ -1,221 +0,0 @@
-/*******************************************************************************
- * 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<l; j++) {
- type = type.getType(new String(enclosingTypeNames[j]));
- }
- type = type.getType(new String(simpleTypeName));
- } else {
- type = cu.getType(new String(simpleTypeName));
- }
- break;
- case IJavaScriptElement.CLASS_FILE:
- type = ((IClassFile)openable).getType();
- break;
- }
- } else {
- int separatorIndex= path.indexOf(IJavaScriptSearchScope.JAR_FILE_ENTRY_SEPARATOR);
- type = separatorIndex == -1
- ? createTypeFromPath(path, new String(simpleTypeName), enclosingTypeNames)
- : createTypeFromJar(path, separatorIndex);
- }
- if (type != null) {
- this.requestor.acceptTypeNameMatch(new JavaSearchTypeNameMatch(type, modifiers));
- }
- } catch (JavaScriptModelException e) {
- // skip
- }
-}
-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 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<resourcePath.length()))
- && resourcePath.charAt(rootPathLength) == '/'))) {
- IPackageFragmentRoot root = ((JavaSearchScope)this.scope).packageFragmentRoot(resourcePath);
- if (root == null) return null;
- this.lastPkgFragmentRoot = root;
- this.lastPkgFragmentRootPath = this.lastPkgFragmentRoot.getPath().toString();
- this.packageHandles = new HashtableOfArrayToObject(5);
- }
-
-
- boolean isLibrary = this.lastPkgFragmentRoot instanceof LibraryFragmentRoot && !((LibraryFragmentRoot)this.lastPkgFragmentRoot).isDirectory();
- // create handle
- if(isLibrary) {
- String[] pkgName = new String[] {this.lastPkgFragmentRootPath};
- IPackageFragment pkgFragment= (IPackageFragment) this.packageHandles.get(pkgName);
- if (pkgFragment == null) {
- pkgFragment= ((PackageFragmentRoot) this.lastPkgFragmentRoot).getPackageFragment(pkgName[0]);
- this.packageHandles.put(pkgName, pkgFragment);
- }
- IClassFile classFile= pkgFragment.getClassFile(pkgName[0]);
- return classFile.getType(simpleTypeName);
- }else {
- resourcePath = resourcePath.substring(this.lastPkgFragmentRootPath.length() + 1);
- String[] simpleNames = new Path(resourcePath).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);
- }
- 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<etnLength; i++) {
- type = type.getType(new String(enclosingTypeNames[i]));
- }
- type = type.getType(simpleTypeName);
- }
- return type;
- } else {
- IClassFile classFile= pkgFragment.getClassFile(simpleName);
- return classFile.getType(simpleTypeName);
- }
- }
-
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/TypeNameRequestorWrapper.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/TypeNameRequestorWrapper.java
deleted file mode 100644
index f53c9e4d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/TypeNameRequestorWrapper.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*******************************************************************************
- * 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.wst.jsdt.core.search.TypeNameRequestor;
-import org.eclipse.wst.jsdt.internal.compiler.env.AccessRestriction;
-
-/**
- * Wrapper used to link {@link IRestrictedAccessTypeRequestor} with {@link 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,
- * TypeNameRequestor nameRequestor,
- * int waitingPolicy,
- * org.eclipse.core.runtime.IProgressMonitor monitor) }.
- */
-public class TypeNameRequestorWrapper implements IRestrictedAccessTypeRequestor {
- TypeNameRequestor requestor;
- public TypeNameRequestorWrapper(TypeNameRequestor requestor) {
- this.requestor = requestor;
- }
- public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path, AccessRestriction access) {
- this.requestor.acceptType(modifiers, packageName, simpleTypeName, enclosingTypeNames, path);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/AbstractIndexer.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/AbstractIndexer.java
deleted file mode 100644
index 9330e63b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/AbstractIndexer.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/*******************************************************************************
- * 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.search.indexing;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.search.SearchDocument;
-import org.eclipse.wst.jsdt.internal.core.JavaModelManager;
-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.FieldPattern;
-import org.eclipse.wst.jsdt.internal.core.search.matching.MethodPattern;
-import org.eclipse.wst.jsdt.internal.core.search.matching.SuperTypeReferencePattern;
-import org.eclipse.wst.jsdt.internal.core.search.matching.TypeDeclarationPattern;
-
-public abstract class AbstractIndexer implements IIndexConstants {
-
- SearchDocument document;
-
- public AbstractIndexer(SearchDocument document) {
- this.document = document;
- }
-
- public void addClassDeclaration(
- int modifiers,
- char[] packageName,
- char[] name,
- char[][] enclosingTypeNames,
- char[] superclass,
- boolean secondary) {
- addTypeDeclaration(modifiers, packageName, name, enclosingTypeNames, secondary);
-
- if (superclass != null) {
- addTypeReference(superclass);
- }
- addIndexEntry(
- SUPER_REF,
- SuperTypeReferencePattern.createIndexKey(
- modifiers, packageName, name, enclosingTypeNames, superclass));
- }
- 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));
-
- if (parameterTypes != null) {
- for (int i = 0; i < argCount; i++)
- 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);
- }
- public void addFieldReference(char[] fieldName) {
- addNameReference(fieldName);
- }
- 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));
-
- if (parameterTypes != null) {
- for (int i = 0; i < argCount; 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 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);
- addIndexEntry(TYPE_DECL, indexKey);
- }
- public void addTypeReference(char[] typeName) {
- if (typeName!=null)
- addNameReference(CharOperation.lastSegment(typeName, '.'));
- }
- public abstract void indexDocument();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/AddFolderToIndex.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/AddFolderToIndex.java
deleted file mode 100644
index 71dfdbdd..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/AddFolderToIndex.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*******************************************************************************
- * 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.indexing;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceProxy;
-import org.eclipse.core.resources.IResourceProxyVisitor;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.compiler.SourceElementParser;
-import org.eclipse.wst.jsdt.internal.core.index.Index;
-import org.eclipse.wst.jsdt.internal.core.search.processing.JobManager;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-class AddFolderToIndex extends IndexRequest {
- IPath folderPath;
- IProject project;
- char[][] inclusionPatterns;
- char[][] exclusionPatterns;
-
- public AddFolderToIndex(IPath folderPath, IProject project, char[][] inclusionPatterns, char[][] exclusionPatterns, IndexManager manager) {
- super(project.getFullPath(), manager);
- this.folderPath = folderPath;
- this.project = project;
- this.inclusionPatterns = inclusionPatterns;
- this.exclusionPatterns = exclusionPatterns;
- }
- public boolean execute(IProgressMonitor progressMonitor) {
-
- if (this.isCancelled || progressMonitor != null && progressMonitor.isCanceled()) return true;
- if (!project.isAccessible()) return true; // nothing to do
- IResource folder = this.project.getParent().findMember(this.folderPath);
- if (folder == null || folder.getType() == IResource.FILE) return true; // nothing to do, source folder was removed
-
- /* ensure no concurrent write access to index */
- Index index = this.manager.getIndex(this.containerPath, true, /*reuse index file*/ true /*create if none*/);
- if (index == null) return true;
- ReadWriteMonitor monitor = index.monitor;
- if (monitor == null) return true; // index got deleted since acquired
-
- try {
- monitor.enterRead(); // ask permission to read
-
- final IPath container = this.containerPath;
- final IndexManager indexManager = this.manager;
- final SourceElementParser parser = indexManager.getSourceElementParser(JavaScriptCore.create(this.project), null/*requestor will be set by indexer*/);
- if (this.exclusionPatterns == null && this.inclusionPatterns == null) {
- folder.accept(
- new IResourceProxyVisitor() {
- public boolean visit(IResourceProxy proxy) /* throws CoreException */{
- if (proxy.getType() == IResource.FILE) {
- if (org.eclipse.wst.jsdt.internal.core.util.Util.isJavaLikeFileName(proxy.getName())
- ||org.eclipse.wst.jsdt.internal.core.util.Util.isMetadataFileName(proxy.getName()))
- indexManager.addSource((IFile) proxy.requestResource(), container, parser);
- return false;
- }
- return true;
- }
- },
- IResource.NONE
- );
- } else {
- folder.accept(
- new IResourceProxyVisitor() {
- public boolean visit(IResourceProxy proxy) /* throws CoreException */{
- switch(proxy.getType()) {
- case IResource.FILE :
- if (org.eclipse.wst.jsdt.internal.core.util.Util.isJavaLikeFileName(proxy.getName())) {
- IResource resource = proxy.requestResource();
- if (!Util.isExcluded(resource, inclusionPatterns, exclusionPatterns))
- indexManager.addSource((IFile)resource, container, parser);
- }
- return false;
- case IResource.FOLDER :
- if (exclusionPatterns != null && inclusionPatterns == null) {
- // if there are inclusion patterns then we must walk the children
- if (Util.isExcluded(proxy.requestFullPath(), inclusionPatterns, exclusionPatterns, true))
- return false;
- }
- }
- return true;
- }
- },
- IResource.NONE
- );
- }
- } catch (CoreException e) {
- if (JobManager.VERBOSE) {
- Util.verbose("-> failed to add " + this.folderPath + " to index because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$
- e.printStackTrace();
- }
- return false;
- } finally {
- monitor.exitRead(); // free read lock
- }
- return true;
- }
- public String toString() {
- return "adding " + this.folderPath + " to index " + this.containerPath; //$NON-NLS-1$ //$NON-NLS-2$
- }
-}
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
deleted file mode 100644
index 2b99cfb3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/AddLibraryFileToIndex.java
+++ /dev/null
@@ -1,221 +0,0 @@
-/*******************************************************************************
- * 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.indexing;
-
-import java.io.File;
-import java.io.IOException;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.IPath;
-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.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 AddLibraryFileToIndex extends IndexRequest {
-
- IPath absolutePath;
- 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);
- }
- public boolean equals(Object o) {
- if (o instanceof AddLibraryFileToIndex) {
- if (this.containerPath != null)
- return this.containerPath.equals(((AddLibraryFileToIndex) o).containerPath);
- }
- return false;
- }
- public int 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
- }
- 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 libraryFilePath = null;
-
- monitor.enterWrite(); // ask permission to write
- 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()
- libraryFilePath = (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 " + libraryFilePath.toString() + " has been cancelled"); //$NON-NLS-1$ //$NON-NLS-2$
- return false;
- }
-
- if (JobManager.VERBOSE)
- 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;
-// }
-// }
-// }
-//
- // 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();
- index = manager.recreateIndex(this.containerPath);
- if (index == null) {
- // failed to recreate index, see 73330
- manager.removeIndex(this.containerPath);
- 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;
- File file = new File(filePath.toOSString());
-
- if (file.isFile())
- indexFile(file, participant, index, libraryFilePath);
- else
- {
- indexDirectory(file, participant, index, libraryFilePath);
- }
-
- this.manager.saveIndex(index);
- if (JobManager.VERBOSE)
- org.eclipse.wst.jsdt.internal.core.util.Util.verbose("-> done indexing of " //$NON-NLS-1$
- + libraryFilePath.toString() + " (" //$NON-NLS-1$
- + (System.currentTimeMillis() - initialTime) + "ms)"); //$NON-NLS-1$
- } finally {
- 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();
- }
- manager.removeIndex(this.containerPath);
- return false;
- }
- return true;
- }
- protected Integer updatedIndexState() {
- return IndexManager.REBUILDING_STATE;
- }
- public String toString() {
- return "indexing " + this.containerPath.toString(); //$NON-NLS-1$
- }
-
- private void indexFile(File file,SearchParticipant participant, Index index, IPath libraryFilePath)
- {
- try {
- final char[] classFileChars = org.eclipse.wst.jsdt.internal.compiler.util.Util.getFileCharContent(file,null);
- String packageName="";
- JavaSearchDocument entryDocument = new JavaSearchDocument( new Path(file.getAbsolutePath()), classFileChars, participant,packageName);
- this.manager.indexDocument(entryDocument, participant, index, this.containerPath);
- } catch (Exception ex)
- {}
-
- }
-
- private void indexDirectory(File file,SearchParticipant participant, Index index, IPath libraryFilePath)
- {
- 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);
-
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/AddLibraryFolderToIndex.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/AddLibraryFolderToIndex.java
deleted file mode 100644
index e48da519..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/AddLibraryFolderToIndex.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*******************************************************************************
- * 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.indexing;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceProxy;
-import org.eclipse.core.resources.IResourceProxyVisitor;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.wst.jsdt.internal.core.index.Index;
-import org.eclipse.wst.jsdt.internal.core.search.processing.JobManager;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-class AddLibraryFolderToIndex extends IndexRequest {
- IPath folderPath;
- IProject project;
- char[][] inclusionPatterns;
- char[][] exclusionPatterns;
-
- public AddLibraryFolderToIndex(IPath folderPath, IProject project, char[][] inclusionPatterns, char[][] exclusionPatterns, IndexManager manager) {
- super(project.getFullPath(), manager);
- this.folderPath = folderPath;
- this.project = project;
- this.inclusionPatterns = inclusionPatterns;
- this.exclusionPatterns = exclusionPatterns;
- }
-
- private void indexFile(IFile resource) {
-// AddLibraryFileToIndex request = new AddLibraryFileToIndex(resource,this.manager);
-// if (!this.manager.isJobWaiting(request))
-// this.manager.request(request);
- this.manager.addSource(resource, folderPath, null);
- }
-// private void indexFile(IPath resource) {
-// AddLibraryFileToIndex request = new AddLibraryFileToIndex(resource,this.manager);
-// if (!this.manager.isJobWaiting(request))
-// this.manager.request(request);
-// }
-
- public boolean execute(IProgressMonitor progressMonitor) {
-
- if (this.isCancelled || progressMonitor != null && progressMonitor.isCanceled()) return true;
- if (!project.isAccessible()) return true; // nothing to do
- IResource folder = this.project.getParent().findMember(this.folderPath);
- if (folder == null || folder.getType() == IResource.FILE) return true; // nothing to do, source folder was removed
-
- /* ensure no concurrent write access to index */
- Index index = this.manager.getIndex(this.containerPath, true, /*reuse index file*/ true /*create if none*/);
- if (index == null) return true;
- ReadWriteMonitor monitor = index.monitor;
- if (monitor == null) return true; // index got deleted since acquired
-
- try {
- monitor.enterRead(); // ask permission to read
-
-// final IPath container = this.containerPath;
-// final IndexManager indexManager = this.manager;
-// final SourceElementParser parser = indexManager.getSourceElementParser(JavaScriptCore.create(this.project), null/*requestor will be set by indexer*/);
- if (this.exclusionPatterns == null && this.inclusionPatterns == null) {
- folder.accept(
- new IResourceProxyVisitor() {
- public boolean visit(IResourceProxy proxy) /* throws CoreException */{
- if (proxy.getType() == IResource.FILE) {
- if (org.eclipse.wst.jsdt.internal.core.util.Util.isJavaLikeFileName(proxy.getName())
- ||org.eclipse.wst.jsdt.internal.core.util.Util.isMetadataFileName(proxy.getName()))
- indexFile((IFile) proxy.requestResource());
- //indexManager.addSource((IFile) proxy.requestResource(), container, parser);
- return false;
- }
- return true;
- }
- },
- IResource.NONE
- );
- } else {
- folder.accept(
- new IResourceProxyVisitor() {
- public boolean visit(IResourceProxy proxy) /* throws CoreException */{
- switch(proxy.getType()) {
- case IResource.FILE :
- if (org.eclipse.wst.jsdt.internal.core.util.Util.isJavaLikeFileName(proxy.getName())
- ||org.eclipse.wst.jsdt.internal.core.util.Util.isMetadataFileName(proxy.getName())){
- IResource resource = proxy.requestResource();
- if (!Util.isExcluded(resource, inclusionPatterns, exclusionPatterns))
- indexFile((IFile) proxy.requestResource());
- //indexManager.addSource((IFile)resource, container, parser);
- }
- return false;
- case IResource.FOLDER :
- if (exclusionPatterns != null && inclusionPatterns == null) {
- // if there are inclusion patterns then we must walk the children
- if (Util.isExcluded(proxy.requestFullPath(), inclusionPatterns, exclusionPatterns, true))
- return false;
- }
- }
- return true;
- }
- },
- IResource.NONE
- );
- }
- } catch (CoreException e) {
- if (JobManager.VERBOSE) {
- Util.verbose("-> failed to add " + this.folderPath + " to index because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$
- e.printStackTrace();
- }
- return false;
- } finally {
- monitor.exitRead(); // free read lock
- }
- return true;
- }
- public String toString() {
- return "adding " + this.folderPath + " to index " + this.containerPath; //$NON-NLS-1$ //$NON-NLS-2$
- }
- protected Integer updatedIndexState() {
- return IndexManager.REBUILDING_STATE;
- }
-}
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
deleted file mode 100644
index 5d6366cf..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/IIndexConstants.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*******************************************************************************
- * 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.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=
- 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';
-
- char[] ONE_STAR = new char[] {'*'};
- 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};
-
- 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;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/IndexAllProject.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/IndexAllProject.java
deleted file mode 100644
index 7a284b1d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/IndexAllProject.java
+++ /dev/null
@@ -1,259 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.search.indexing;
-
-import java.io.IOException;
-import java.net.URI;
-import java.util.HashSet;
-
-import org.eclipse.core.filesystem.EFS;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceProxy;
-import org.eclipse.core.resources.IResourceProxyVisitor;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.compiler.SourceElementParser;
-import org.eclipse.wst.jsdt.internal.compiler.util.SimpleLookupTable;
-import org.eclipse.wst.jsdt.internal.core.ClasspathEntry;
-import org.eclipse.wst.jsdt.internal.core.JavaProject;
-import org.eclipse.wst.jsdt.internal.core.index.Index;
-import org.eclipse.wst.jsdt.internal.core.search.processing.JobManager;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-public class IndexAllProject extends IndexRequest {
- IProject project;
-
- public IndexAllProject(IProject project, IndexManager manager) {
- super(project.getFullPath(), manager);
- this.project = project;
- }
- public boolean equals(Object o) {
- if (o instanceof IndexAllProject)
- return this.project.equals(((IndexAllProject) o).project);
- return false;
- }
- /**
- * Ensure consistency of a project index. Need to walk all nested resources,
- * and discover resources which have either been changed, added or deleted
- * since the index was produced.
- */
- public boolean execute(IProgressMonitor progressMonitor) {
-
- if (this.isCancelled || progressMonitor != null && progressMonitor.isCanceled()) return true;
- if (!project.isAccessible()) return true; // nothing to do
-
- ReadWriteMonitor monitor = null;
- try {
- // Get source folder entries. Libraries are done as a separate job
- JavaProject javaProject = (JavaProject)JavaScriptCore.create(this.project);
- // Do not create marker while getting raw classpath (see bug 41859)
- IIncludePathEntry[] entries = javaProject.getRawIncludepath();
- int length = entries.length;
- IIncludePathEntry[] sourceEntries = new IIncludePathEntry[length];
- int sourceEntriesNumber = 0;
-
- // it does not appear necessary to index the entire project
- //IIncludePathEntry projectRoot = JavaScriptCore.newSourceEntry( javaProject.getPath());
-
-
- for (int i = 0; i < length; i++) {
- IIncludePathEntry entry = entries[i];
- if (entry.getEntryKind() == IIncludePathEntry.CPE_SOURCE) //&&
- //(! javaProject.getPath().isPrefixOf(entry.getPath())|| ! JavaProject.hasJavaNature(project) ))
- sourceEntries[sourceEntriesNumber++] = entry;
- }
-
- //if(JavaProject.hasJavaNature(project)) sourceEntries[sourceEntriesNumber++] = projectRoot;
-
- if (sourceEntriesNumber == 0) {
- IPath projectPath = javaProject.getPath();
- for (int i = 0; i < length; i++) {
- IIncludePathEntry entry = entries[i];
- if (entry.getEntryKind() == IIncludePathEntry.CPE_LIBRARY && entry.getPath().equals(projectPath)) {
- // the project is also a library folder (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=89815)
- // ensure a job exists to index it as a binary folder
- this.manager.indexLibrary(entry, this.project);
- return true;
- }
- }
-
- // nothing to index but want to save an empty index file so its not 'rebuilt' when part of a search request
- Index index = this.manager.getIndexForUpdate(this.containerPath, true, /*reuse index file*/ true /*create if none*/);
- if (index != null)
- this.manager.saveIndex(index);
- return true;
- }
- if (sourceEntriesNumber != length)
- System.arraycopy(sourceEntries, 0, sourceEntries = new IIncludePathEntry[sourceEntriesNumber], 0, sourceEntriesNumber);
-
- Index index = this.manager.getIndexForUpdate(this.containerPath, true, /*reuse index file*/ true /*create if none*/);
- if (index == null) return true;
- monitor = index.monitor;
- if (monitor == null) return true; // index got deleted since acquired
-
- monitor.enterRead(); // ask permission to read
-
- String[] paths = index.queryDocumentNames(""); // all file names //$NON-NLS-1$
- int max = paths == null ? 0 : paths.length;
- final SimpleLookupTable indexedFileNames = new SimpleLookupTable(max == 0 ? 33 : max + 11);
- final String OK = "OK"; //$NON-NLS-1$
- final String DELETED = "DELETED"; //$NON-NLS-1$
- if (paths != null) {
- for (int i = 0; i < max; i++)
- indexedFileNames.put(paths[i], DELETED);
- }
- final long indexLastModified = max == 0 ? 0L : index.getIndexFile().lastModified();
-
- IWorkspaceRoot root = this.project.getWorkspace().getRoot();
- for (int i = 0; i < sourceEntriesNumber; i++) {
- if (this.isCancelled) return false;
-
- IIncludePathEntry entry = sourceEntries[i];
- IResource sourceFolder = root.findMember(entry.getPath());
- if (sourceFolder != null) {
-
- // collect output locations if source is project (see http://bugs.eclipse.org/bugs/show_bug.cgi?id=32041)
- final HashSet outputs = new HashSet();
- if (sourceFolder.getType() == IResource.PROJECT) {
- // Do not create marker while getting output location (see bug 41859)
- outputs.add(javaProject.getOutputLocation());
- }
- final boolean hasOutputs = !outputs.isEmpty();
-
- final char[][] inclusionPatterns = ((ClasspathEntry) entry).fullInclusionPatternChars();
- final char[][] exclusionPatterns = ((ClasspathEntry) entry).fullExclusionPatternChars();
- if (max == 0) {
- sourceFolder.accept(
- new IResourceProxyVisitor() {
- public boolean visit(IResourceProxy proxy) {
- if (isCancelled) return false;
- switch(proxy.getType()) {
- case IResource.FILE :
- if (org.eclipse.wst.jsdt.internal.core.util.Util.isJavaLikeFileName(proxy.getName())
- ||org.eclipse.wst.jsdt.internal.core.util.Util.isMetadataFileName(proxy.getName())
- ) {
- IFile file = (IFile) proxy.requestResource();
- if (exclusionPatterns != null || inclusionPatterns != null)
- if (Util.isExcluded(file, inclusionPatterns, exclusionPatterns))
- return false;
- indexedFileNames.put(Util.relativePath(file.getFullPath(), 1/*remove project segment*/), file);
- }
- return false;
- case IResource.FOLDER :
- if (exclusionPatterns != null && inclusionPatterns == null) {
- // if there are inclusion patterns then we must walk the children
- if (Util.isExcluded(proxy.requestFullPath(), inclusionPatterns, exclusionPatterns, true))
- return false;
- }
- if (hasOutputs && outputs.contains(proxy.requestFullPath()))
- return false;
- }
- return true;
- }
- },
- IResource.NONE
- );
- } else {
- sourceFolder.accept(
- new IResourceProxyVisitor() {
- public boolean visit(IResourceProxy proxy) throws CoreException {
- if (isCancelled) return false;
- switch(proxy.getType()) {
- case IResource.FILE :
- if (org.eclipse.wst.jsdt.internal.core.util.Util.isJavaLikeFileName(proxy.getName())
- ||org.eclipse.wst.jsdt.internal.core.util.Util.isMetadataFileName(proxy.getName()))
- {
- IFile file = (IFile) proxy.requestResource();
- URI location = file.getLocationURI();
- if (location == null) return false;
- if (exclusionPatterns != null || inclusionPatterns != null)
- if (Util.isExcluded(file, inclusionPatterns, exclusionPatterns))
- return false;
- String relativePathString = Util.relativePath(file.getFullPath(), 1/*remove project segment*/);
- indexedFileNames.put(relativePathString,
- indexedFileNames.get(relativePathString) == null
- || indexLastModified < EFS.getStore(location).fetchInfo().getLastModified()
- ? (Object) file
- : (Object) OK);
- }
- return false;
- case IResource.FOLDER :
- if (exclusionPatterns != null || inclusionPatterns != null)
- if (Util.isExcluded(proxy.requestResource(), inclusionPatterns, exclusionPatterns))
- return false;
- if (hasOutputs && outputs.contains(proxy.requestFullPath()))
- return false;
- }
- return true;
- }
- },
- IResource.NONE
- );
- }
- }
- }
-
- SourceElementParser parser = this.manager.getSourceElementParser(javaProject, null/*requestor will be set by indexer*/);
- Object[] names = indexedFileNames.keyTable;
- Object[] values = indexedFileNames.valueTable;
- for (int i = 0, namesLength = names.length; i < namesLength; i++) {
- String name = (String) names[i];
- if (name != null) {
- if (this.isCancelled) return false;
-
- Object value = values[i];
- if (value != OK) {
- if (value == DELETED)
- this.manager.remove(name, this.containerPath);
- else
- this.manager.addSource((IFile) value, this.containerPath, parser);
- }
- }
- }
-
- // request to save index when all cus have been indexed... also sets state to SAVED_STATE
- this.manager.request(new SaveIndex(this.containerPath, this.manager));
- } catch (CoreException e) {
- if (JobManager.VERBOSE) {
- Util.verbose("-> failed to index " + this.project + " because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$
- e.printStackTrace();
- }
- this.manager.removeIndex(this.containerPath);
- return false;
- } catch (IOException e) {
- if (JobManager.VERBOSE) {
- Util.verbose("-> failed to index " + this.project + " because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$
- e.printStackTrace();
- }
- this.manager.removeIndex(this.containerPath);
- return false;
- } finally {
- if (monitor != null)
- monitor.exitRead(); // free read lock
- }
- return true;
- }
- public int hashCode() {
- return this.project.hashCode();
- }
- protected Integer updatedIndexState() {
- return IndexManager.REBUILDING_STATE;
- }
- public String toString() {
- return "indexing project " + this.project.getFullPath(); //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/IndexBinaryFolder.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/IndexBinaryFolder.java
deleted file mode 100644
index 245013e3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/IndexBinaryFolder.java
+++ /dev/null
@@ -1,199 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.search.indexing;
-
-import java.io.IOException;
-import java.net.URI;
-
-import org.eclipse.core.filesystem.EFS;
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceProxy;
-import org.eclipse.core.resources.IResourceProxyVisitor;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.compiler.util.SimpleLookupTable;
-import org.eclipse.wst.jsdt.internal.core.ClasspathEntry;
-import org.eclipse.wst.jsdt.internal.core.JavaModel;
-import org.eclipse.wst.jsdt.internal.core.JavaModelManager;
-import org.eclipse.wst.jsdt.internal.core.JavaProject;
-import org.eclipse.wst.jsdt.internal.core.index.Index;
-import org.eclipse.wst.jsdt.internal.core.search.processing.JobManager;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-public class IndexBinaryFolder extends IndexRequest {
- IContainer folder;
- char[][] exclusionPatterns;
-
- public IndexBinaryFolder(IContainer folder, IndexManager manager) {
- super(folder.getFullPath(), manager);
- this.folder = folder;
-
- // need to check for exclusion patterns
- try {
- JavaModel model = JavaModelManager.getJavaModelManager().getJavaModel();
- JavaProject javaProject = (JavaProject) model.getJavaProject(folder.getProject());
- IIncludePathEntry[] newResolvedClasspath = javaProject.getResolvedClasspath();
- IPath folderPath = folder.getFullPath();
- for (int i = 0; i < newResolvedClasspath.length; i++) {
- boolean found = false;
- // Request indexing
- int entryKind = newResolvedClasspath[i].getEntryKind();
- switch (entryKind) {
- case IIncludePathEntry.CPE_LIBRARY:
- IPath newPath = newResolvedClasspath[i].getPath();
- if(newPath.equals(folderPath)) {
- exclusionPatterns = ((ClasspathEntry)newResolvedClasspath[i]).fullExclusionPatternChars();
- found = true;
- }
- break;
- }
- if(found)
- break;
- }
- } catch (JavaScriptModelException e) {
- // project doesn't exist
- return;
- }
- }
-
- public boolean equals(Object o) {
- if (o instanceof IndexBinaryFolder)
- return this.folder.equals(((IndexBinaryFolder) o).folder);
- return false;
- }
- /**
- * Ensure consistency of a folder index. Need to walk all nested resources,
- * and discover resources which have either been changed, added or deleted
- * since the index was produced.
- */
- public boolean execute(IProgressMonitor progressMonitor) {
-
- if (this.isCancelled || progressMonitor != null && progressMonitor.isCanceled()) return true;
- if (!this.folder.isAccessible()) return true; // nothing to do
-
- Index index = this.manager.getIndexForUpdate(this.containerPath, true, /*reuse index file*/ true /*create if none*/);
- if (index == null) return true;
- ReadWriteMonitor monitor = index.monitor;
- if (monitor == null) return true; // index got deleted since acquired
-
- try {
- monitor.enterRead(); // ask permission to read
-
- String[] paths = index.queryDocumentNames(""); // all file names //$NON-NLS-1$
- int max = paths == null ? 0 : paths.length;
- final SimpleLookupTable indexedFileNames = new SimpleLookupTable(max==0 ? 33 : max+11);
- final String OK = "OK"; //$NON-NLS-1$
- final String DELETED = "DELETED"; //$NON-NLS-1$
- if (paths == null) {
- this.folder.accept(new IResourceProxyVisitor() {
- public boolean visit(IResourceProxy proxy) {
- if (isCancelled) return false;
- if (proxy.getType() == IResource.FILE) {
- if (org.eclipse.wst.jsdt.internal.compiler.util.Util.isClassFileName(proxy.getName())) {
- IFile file = (IFile) proxy.requestResource();
- if(exclusionPatterns == null || !Util.isExcluded(file, null, exclusionPatterns)) {
- String containerRelativePath = Util.relativePath(file.getFullPath(), containerPath.segmentCount());
- indexedFileNames.put(containerRelativePath, file);
- }
- }
- return false;
- }
- return true;
- }
- }, IResource.NONE);
- } else {
- for (int i = 0; i < max; i++) {
- indexedFileNames.put(paths[i], DELETED);
- }
- final long indexLastModified = index.getIndexFile().lastModified();
- this.folder.accept(
- new IResourceProxyVisitor() {
- public boolean visit(IResourceProxy proxy) throws CoreException {
- if (isCancelled) return false;
- if (proxy.getType() == IResource.FILE) {
- if (org.eclipse.wst.jsdt.internal.compiler.util.Util.isClassFileName(proxy.getName())) {
- IFile file = (IFile) proxy.requestResource();
- if(exclusionPatterns == null || !Util.isExcluded(file, null, exclusionPatterns)) {
- URI location = file.getLocationURI();
- if (location != null) {
- String containerRelativePath = Util.relativePath(file.getFullPath(), containerPath.segmentCount());
- indexedFileNames.put(containerRelativePath,
- indexedFileNames.get(containerRelativePath) == null
- || indexLastModified <
- EFS.getStore(location).fetchInfo().getLastModified()
- ? (Object) file
- : (Object) OK);
- }
- }
- }
- return false;
- }
- return true;
- }
- },
- IResource.NONE
- );
- }
-
- Object[] names = indexedFileNames.keyTable;
- Object[] values = indexedFileNames.valueTable;
- for (int i = 0, length = names.length; i < length; i++) {
- String name = (String) names[i];
- if (name != null) {
- if (this.isCancelled) return false;
-
- Object value = values[i];
- if (value != OK) {
- if (value == DELETED)
- this.manager.remove(name, this.containerPath);
- else {
- this.manager.addBinary((IFile) value, this.containerPath);
- }
- }
- }
- }
-
- // request to save index when all class files have been indexed... also sets state to SAVED_STATE
- this.manager.request(new SaveIndex(this.containerPath, this.manager));
- } catch (CoreException e) {
- if (JobManager.VERBOSE) {
- Util.verbose("-> failed to index " + this.folder + " because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$
- e.printStackTrace();
- }
- this.manager.removeIndex(this.containerPath);
- return false;
- } catch (IOException e) {
- if (JobManager.VERBOSE) {
- Util.verbose("-> failed to index " + this.folder + " because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$
- e.printStackTrace();
- }
- this.manager.removeIndex(this.containerPath);
- return false;
- } finally {
- monitor.exitRead(); // free read lock
- }
- return true;
- }
- public int hashCode() {
- return this.folder.hashCode();
- }
- protected Integer updatedIndexState() {
- return IndexManager.REBUILDING_STATE;
- }
- public String toString() {
- return "indexing binary folder " + this.folder.getFullPath(); //$NON-NLS-1$
- }
-}
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
deleted file mode 100644
index fc1ad236..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/IndexManager.java
+++ /dev/null
@@ -1,836 +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.indexing;
-
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Locale;
-import java.util.Map;
-import java.util.zip.CRC32;
-
-import org.eclipse.core.filesystem.EFS;
-import org.eclipse.core.filesystem.IFileStore;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.ResourcesPlugin;
-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.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-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.core.search.IJavaScriptSearchScope;
-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.ISourceElementRequestor;
-import org.eclipse.wst.jsdt.internal.compiler.SourceElementParser;
-import org.eclipse.wst.jsdt.internal.compiler.impl.CompilerOptions;
-import org.eclipse.wst.jsdt.internal.compiler.problem.DefaultProblemFactory;
-import org.eclipse.wst.jsdt.internal.compiler.util.SimpleLookupTable;
-import org.eclipse.wst.jsdt.internal.compiler.util.SimpleSet;
-import org.eclipse.wst.jsdt.internal.core.ClasspathEntry;
-import org.eclipse.wst.jsdt.internal.core.JavaModel;
-import org.eclipse.wst.jsdt.internal.core.JavaModelManager;
-import org.eclipse.wst.jsdt.internal.core.JavaProject;
-import org.eclipse.wst.jsdt.internal.core.LibraryFragmentRoot;
-import org.eclipse.wst.jsdt.internal.core.index.DiskIndex;
-import org.eclipse.wst.jsdt.internal.core.index.Index;
-import org.eclipse.wst.jsdt.internal.core.search.BasicSearchEngine;
-import org.eclipse.wst.jsdt.internal.core.search.PatternSearchJob;
-import org.eclipse.wst.jsdt.internal.core.search.processing.IJob;
-import org.eclipse.wst.jsdt.internal.core.search.processing.JobManager;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-public class IndexManager extends JobManager implements IIndexConstants {
-
- // key = containerPath, value = indexLocation path
- // indexLocation path is created by appending an index file name to the getJavaPluginWorkingLocation() path
- public SimpleLookupTable indexLocations = new SimpleLookupTable();
- // key = indexLocation path, value = an index
- private SimpleLookupTable indexes = new SimpleLookupTable();
-
- /* need to save ? */
- private boolean needToSave = false;
- private static final CRC32 checksumCalculator = new CRC32();
- private IPath javaPluginLocation = null;
-
- /* can only replace a current state if its less than the new one */
- // key = indexLocation path, value = index state integer
- private SimpleLookupTable indexStates = null;
- private File savedIndexNamesFile = new File(getSavedIndexesDirectory(), "savedIndexNames.txt"); //$NON-NLS-1$
- public static Integer SAVED_STATE = new Integer(0);
- public static Integer UPDATING_STATE = new Integer(1);
- public static Integer UNKNOWN_STATE = new Integer(2);
- public static Integer REBUILDING_STATE = new Integer(3);
- private static final String INDEX_FILE_SUFFIX = ".index";
-
-
-public synchronized void aboutToUpdateIndex(IPath containerPath, Integer newIndexState) {
- // newIndexState is either UPDATING_STATE or REBUILDING_STATE
- // must tag the index as inconsistent, in case we exit before the update job is started
- IPath indexLocation = computeIndexLocation(containerPath);
- Object state = getIndexStates().get(indexLocation);
- Integer currentIndexState = state == null ? UNKNOWN_STATE : (Integer) state;
- if (currentIndexState.equals(REBUILDING_STATE)) return; // already rebuilding the index
-
- int compare = newIndexState.compareTo(currentIndexState);
- if (compare > 0) {
- // so UPDATING_STATE replaces SAVED_STATE and REBUILDING_STATE replaces everything
- updateIndexState(indexLocation, newIndexState);
- } else if (compare < 0 && this.indexes.get(indexLocation) == null) {
- // if already cached index then there is nothing more to do
- rebuildIndex(indexLocation, containerPath);
- }
-}
-/**
- * Trigger addition of a resource to an index
- * Note: the actual operation is performed in background
- */
-public void addBinary(IFile resource, IPath containerPath) {
- if (JavaScriptCore.getPlugin() == null) return;
- SearchParticipant participant = SearchEngine.getDefaultSearchParticipant();
- SearchDocument document = participant.getDocument(resource.getFullPath().toString());
- IPath indexLocation = computeIndexLocation(containerPath);
- scheduleDocumentIndexing(document, containerPath, indexLocation, participant);
-}
-/**
- * Trigger addition of a resource to an index
- * Note: the actual operation is performed in background
- */
-public void addSource(IFile resource, IPath containerPath, SourceElementParser parser) {
- if (JavaScriptCore.getPlugin() == null) return;
- SearchParticipant participant = SearchEngine.getDefaultSearchParticipant();
- SearchDocument document = participant.getDocument(resource.getFullPath().toString());
- ((InternalSearchDocument) document).parser = parser;
- IPath indexLocation = computeIndexLocation(containerPath);
- scheduleDocumentIndexing(document, containerPath, indexLocation, participant);
-}
-/*
- * Removes unused indexes from disk.
- */
-public void cleanUpIndexes() {
- SimpleSet knownPaths = new SimpleSet();
- IJavaScriptSearchScope scope = BasicSearchEngine.createWorkspaceScope();
- PatternSearchJob job = new PatternSearchJob(null, SearchEngine.getDefaultSearchParticipant(), scope, null);
- Index[] selectedIndexes = job.getIndexes(null);
- for (int i = 0, l = selectedIndexes.length; i < l; i++) {
- String path = selectedIndexes[i].getIndexFile().getAbsolutePath();
- knownPaths.add(path);
- }
-
- if (this.indexStates != null) {
- Object[] keys = this.indexStates.keyTable;
- IPath[] locations = new IPath[this.indexStates.elementSize];
- int count = 0;
- for (int i = 0, l = keys.length; i < l; i++) {
- IPath key = (IPath) keys[i];
- if (key != null && !knownPaths.includes(key.toOSString()))
- locations[count++] = key;
- }
- if (count > 0)
- removeIndexesState(locations);
- }
- deleteIndexFiles(knownPaths);
-}
-public IPath computeIndexLocation(IPath containerPath) {
- IPath indexLocation = (IPath) this.indexLocations.get(containerPath);
- if (indexLocation == null) {
- String pathString = containerPath.toOSString();
- checksumCalculator.reset();
- checksumCalculator.update(pathString.getBytes());
- String fileName = Long.toString(checksumCalculator.getValue()) + ".index"; //$NON-NLS-1$
- if (VERBOSE)
- Util.verbose("-> index name for " + pathString + " is " + fileName); //$NON-NLS-1$ //$NON-NLS-2$
- // to share the indexLocation between the indexLocations and indexStates tables, get the key from the indexStates table
- indexLocation = (IPath) getIndexStates().getKey(getJavaPluginWorkingLocation().append(fileName));
- this.indexLocations.put(containerPath, indexLocation);
- }
- return indexLocation;
-}
-public void deleteIndexFiles() {
- this.savedIndexNamesFile.delete(); // forget saved indexes & delete each index file
- deleteIndexFiles(null);
-}
-private void deleteIndexFiles(SimpleSet pathsToKeep) {
- File[] indexesFiles = getSavedIndexesDirectory().listFiles();
- if (indexesFiles == null) return;
-
- for (int i = 0, l = indexesFiles.length; i < l; i++) {
- String fileName = indexesFiles[i].getAbsolutePath();
- if (pathsToKeep != null && pathsToKeep.includes(fileName)) continue;
- if (fileName.regionMatches(true, fileName.length() - INDEX_FILE_SUFFIX.length(), INDEX_FILE_SUFFIX, 0, INDEX_FILE_SUFFIX.length())) {
- if (VERBOSE)
- Util.verbose("Deleting index file " + indexesFiles[i]); //$NON-NLS-1$
- indexesFiles[i].delete();
- }
- }
-}
-/*
- * Creates an empty index at the given location, for the given container path, if none exist.
- */
-public void ensureIndexExists(IPath indexLocation, IPath containerPath) {
- SimpleLookupTable states = getIndexStates();
- Object state = states.get(indexLocation);
- if (state == null) {
- updateIndexState(indexLocation, REBUILDING_STATE);
- getIndex(containerPath, indexLocation, true, true);
- }
-}
-public SourceElementParser getSourceElementParser(IJavaScriptProject project, ISourceElementRequestor requestor) {
- // disable task tags to speed up parsing
- Map options = project.getOptions(true);
- options.put(JavaScriptCore.COMPILER_TASK_TAGS, ""); //$NON-NLS-1$
-
- SourceElementParser parser = new IndexingParser(
- requestor,
- new DefaultProblemFactory(Locale.getDefault()),
- new CompilerOptions(options),
- true, // index local declarations
- true, // optimize string literals
- false); // do not use source javadoc parser to speed up parsing
- parser.reportOnlyOneSyntaxError = true;
-
- // Always check javadoc while indexing
- parser.javadocParser.checkDocComment = true;
- parser.javadocParser.reportProblems = false;
-
- return parser;
-}
-/**
- * Returns the index for a given project, according to the following algorithm:
- * - if index is already in memory: answers this one back
- * - if (reuseExistingFile) then read it and return this index and record it in memory
- * - if (createIfMissing) then create a new empty index and record it in memory
- *
- * Warning: Does not check whether index is consistent (not being used)
- */
-public synchronized Index getIndex(IPath containerPath, boolean reuseExistingFile, boolean createIfMissing) {
- IPath indexLocation = computeIndexLocation(containerPath);
- return getIndex(containerPath, indexLocation, reuseExistingFile, createIfMissing);
-}
-/**
- * Returns the index for a given project, according to the following algorithm:
- * - if index is already in memory: answers this one back
- * - if (reuseExistingFile) then read it and return this index and record it in memory
- * - if (createIfMissing) then create a new empty index and record it in memory
- *
- * Warning: Does not check whether index is consistent (not being used)
- */
-public synchronized Index getIndex(IPath containerPath, IPath indexLocation, boolean reuseExistingFile, boolean createIfMissing) {
- // Path is already canonical per construction
- Index index = getIndex(indexLocation);
- if (index == null) {
- Object state = getIndexStates().get(indexLocation);
- Integer currentIndexState = state == null ? UNKNOWN_STATE : (Integer) state;
- if (currentIndexState == UNKNOWN_STATE) {
- // should only be reachable for query jobs
- // IF you put an index in the cache, then AddJarFileToIndex fails because it thinks there is nothing to do
- rebuildIndex(indexLocation, containerPath);
- return null;
- }
-
- // index isn't cached, consider reusing an existing index file
- String containerPathString = containerPath.getDevice() == null ? containerPath.toString() : containerPath.toOSString();
- String indexLocationString = indexLocation.toOSString();
- if (reuseExistingFile) {
- File indexFile = new File(indexLocationString);
- if (indexFile.exists()) { // check before creating index so as to avoid creating a new empty index if file is missing
- try {
- index = new Index(indexLocationString, containerPathString, true /*reuse index file*/);
- this.indexes.put(indexLocation, index);
- return index;
- } catch (IOException e) {
- // failed to read the existing file or its no longer compatible
- if (currentIndexState != REBUILDING_STATE) { // rebuild index if existing file is corrupt, unless the index is already being rebuilt
- if (VERBOSE)
- Util.verbose("-> cannot reuse existing index: "+indexLocationString+" path: "+containerPathString); //$NON-NLS-1$ //$NON-NLS-2$
- rebuildIndex(indexLocation, containerPath);
- return null;
- }
- /*index = null;*/ // will fall thru to createIfMissing & create a empty index for the rebuild all job to populate
- }
- }
- if (currentIndexState == SAVED_STATE) { // rebuild index if existing file is missing
- rebuildIndex(indexLocation, containerPath);
- return null;
- }
- }
- // index wasn't found on disk, consider creating an empty new one
- if (createIfMissing) {
- try {
- if (VERBOSE)
- Util.verbose("-> create empty index: "+indexLocationString+" path: "+containerPathString); //$NON-NLS-1$ //$NON-NLS-2$
- index = new Index(indexLocationString, containerPathString, false /*do not reuse index file*/);
- this.indexes.put(indexLocation, index);
- return index;
- } catch (IOException e) {
- if (VERBOSE)
- Util.verbose("-> unable to create empty index: "+indexLocationString+" path: "+containerPathString); //$NON-NLS-1$ //$NON-NLS-2$
- // The file could not be created. Possible reason: the project has been deleted.
- return null;
- }
- }
- }
- //System.out.println(" index name: " + path.toOSString() + " <----> " + index.getIndexFile().getName());
- return index;
-}
-public synchronized Index getIndex(IPath indexLocation) {
- return (Index) this.indexes.get(indexLocation); // is null if unknown, call if the containerPath must be computed
-}
-public synchronized Index getIndexForUpdate(IPath containerPath, boolean reuseExistingFile, boolean createIfMissing) {
- IPath indexLocation = computeIndexLocation(containerPath);
- if (getIndexStates().get(indexLocation) == REBUILDING_STATE)
- return getIndex(containerPath, indexLocation, reuseExistingFile, createIfMissing);
-
- return null; // abort the job since the index has been removed from the REBUILDING_STATE
-}
-private SimpleLookupTable getIndexStates() {
- if (this.indexStates != null) return this.indexStates;
-
- this.indexStates = new SimpleLookupTable();
- IPath indexesDirectoryPath = getJavaPluginWorkingLocation();
- char[][] savedNames = readIndexState(indexesDirectoryPath.toOSString());
- if (savedNames != null) {
- for (int i = 1, l = savedNames.length; i < l; i++) { // first name is saved signature, see readIndexState()
- char[] savedName = savedNames[i];
- if (savedName.length > 0) {
- IPath indexLocation = indexesDirectoryPath.append(new String(savedName)); // shares indexesDirectoryPath's segments
- if (VERBOSE)
- Util.verbose("Reading saved index file " + indexLocation); //$NON-NLS-1$
- this.indexStates.put(indexLocation, SAVED_STATE);
- }
- }
- } else {
- deleteIndexFiles();
- }
- return this.indexStates;
-}
-
- private IPath getJavaPluginWorkingLocation() {
- if (this.javaPluginLocation != null)
- return this.javaPluginLocation;
-
- IPath stateLocation = JavaScriptCore.getPlugin().getStateLocation().addTrailingSeparator().append("indexes"); //$NON-NLS-1$
- try {
- IFileStore store = EFS.getLocalFileSystem().getStore(stateLocation);
- if (!store.fetchInfo().exists()) {
- store.mkdir(EFS.SHALLOW, null);
- }
- }
- catch (CoreException e) {
- e.printStackTrace();
- }
-
- return this.javaPluginLocation = stateLocation;
- }
-
-private File getSavedIndexesDirectory() {
- return new File(getJavaPluginWorkingLocation().toOSString());
-}
-public void indexDocument(SearchDocument searchDocument, SearchParticipant searchParticipant, Index index, IPath indexLocation) {
- try {
- ((InternalSearchDocument) searchDocument).index = index;
- searchParticipant.indexDocument(searchDocument, indexLocation);
- } finally {
- ((InternalSearchDocument) searchDocument).index = null;
- }
-}
-/**
- * Trigger addition of the entire content of a project
- * Note: the actual operation is performed in background
- */
-public void indexAll(IProject project) {
- if (JavaScriptCore.getPlugin() == null) return;
-
- // Also request indexing of binaries on the classpath
- // determine the new children
- try {
- JavaModel model = JavaModelManager.getJavaModelManager().getJavaModel();
- JavaProject javaProject = (JavaProject) model.getJavaProject(project);
- // only consider immediate libraries - each project will do the same
- // NOTE: force to resolve CP variables before calling indexer - 19303, so that initializers
- // will be run in the current thread.
- IIncludePathEntry[] entries = javaProject.getResolvedClasspath();
- for (int i = 0; i < entries.length; i++) {
- IIncludePathEntry entry= entries[i];
- if (entry.getEntryKind() == IIncludePathEntry.CPE_LIBRARY)
- this.indexLibrary(entry, project);
- }
- } catch(JavaScriptModelException e){ // cannot retrieve classpath info
- }
-
- // check if the same request is not already in the queue
- IndexRequest request = new IndexAllProject(project, this);
- if (!isJobWaiting(request))
- this.request(request);
-}
-/**
- * Trigger addition of a library to an index
- * Note: the actual operation is performed in background
- */
-public void indexLibrary(IIncludePathEntry entry, IProject requestingProject) {
- // requestingProject is no longer used to cancel jobs but leave it here just in case
- if (JavaScriptCore.getPlugin() == null) return;
- IndexRequest request = null;
- Object target = JavaModel.getTarget(ResourcesPlugin.getWorkspace().getRoot(), entry.getPath(), true);
- 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);
-
- if (!isJobWaiting(request))
- this.request(request);
-
-
-
-// if (target instanceof IFile) {
-// request = new AddLibraryFileToIndex((IFile) target, this);
-//// request = new AddJarFileToIndex((IFile) target, this);
-// } else if (target instanceof File) {
-// if (((File) target).isFile()) {
-// request = new AddJarFileToIndex(path, this);
-// } else {
-// return;
-// }
-// } else if (target instanceof IContainer) {
-// request = new IndexBinaryFolder((IContainer) target, this);
-// } else {
-// return;
-// }
-//
-// // check if the same request is not already in the queue
-// if (!isJobWaiting(request))
-// this.request(request);
-}
-
- public void indexLibrary(LibraryFragmentRoot entry, IProject requestingProject) {
- try {
- indexLibrary(entry.getRawIncludepathEntry(), requestingProject);
- } catch (JavaScriptModelException ex) {
-
- ex.printStackTrace();
- }
-
- }
-/**
- * Index the content of the given source folder.
- */
-public void indexSourceFolder(JavaProject javaProject, IPath sourceFolder, char[][] inclusionPatterns, char[][] exclusionPatterns) {
- IProject project = javaProject.getProject();
- if (this.jobEnd > this.jobStart) {
- // skip it if a job to index the project is already in the queue
- IndexRequest request = new IndexAllProject(project, this);
- if (isJobWaiting(request)) return;
- }
-
- this.request(new AddFolderToIndex(sourceFolder, project, inclusionPatterns, exclusionPatterns, this));
-}
-public synchronized void jobWasCancelled(IPath containerPath) {
- IPath indexLocation = computeIndexLocation(containerPath);
- Index index = getIndex(indexLocation);
- if (index != null) {
- index.monitor = null;
- this.indexes.removeKey(indexLocation);
- }
- updateIndexState(indexLocation, UNKNOWN_STATE);
-}
-/**
- * Advance to the next available job, once the current one has been completed.
- * Note: clients awaiting until the job count is zero are still waiting at this point.
- */
-protected synchronized void moveToNextJob() {
- // remember that one job was executed, and we will need to save indexes at some point
- needToSave = true;
- super.moveToNextJob();
-}
-/**
- * No more job awaiting.
- */
-protected void notifyIdle(long idlingTime){
- if (idlingTime > 1000 && needToSave) saveIndexes();
-}
-/**
- * Name of the background process
- */
-public String processName(){
- return Messages.process_name;
-}
-private void rebuildIndex(IPath indexLocation, IPath containerPath) {
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- if (workspace == null) return;
- Object target = JavaModel.getTarget(workspace.getRoot(), containerPath, true);
- if (target == null) return;
-
- if (VERBOSE)
- Util.verbose("-> request to rebuild index: "+indexLocation+" path: "+containerPath); //$NON-NLS-1$ //$NON-NLS-2$
-
- updateIndexState(indexLocation, REBUILDING_STATE);
- IndexRequest request = null;
- if (target instanceof IProject) {
- IProject p = (IProject) target;
- if (JavaProject.hasJavaNature(p))
- 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 File) {
- request = new AddLibraryFileToIndex(containerPath, this);
-// request = new AddJarFileToIndex(containerPath, this);
- }
- if (request != null)
- request(request);
-}
-/**
- * Recreates the index for a given path, keeping the same read-write monitor.
- * Returns the new empty index or null if it didn't exist before.
- * Warning: Does not check whether index is consistent (not being used)
- */
-public synchronized Index recreateIndex(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);
- ReadWriteMonitor monitor = index == null ? null : index.monitor;
-
- if (VERBOSE)
- Util.verbose("-> recreating index: "+indexLocation+" for path: "+containerPathString); //$NON-NLS-1$ //$NON-NLS-2$
- index = new Index(indexLocation.toOSString(), containerPathString, false /*reuse index file*/);
- this.indexes.put(indexLocation, index);
- index.monitor = monitor;
- return index;
- } catch (IOException e) {
- // The file could not be created. Possible reason: the project has been deleted.
- if (VERBOSE) {
- Util.verbose("-> failed to recreate index for path: "+containerPathString); //$NON-NLS-1$
- e.printStackTrace();
- }
- return null;
- }
-}
-/**
- * Trigger removal of a resource to an index
- * Note: the actual operation is performed in background
- */
-public void remove(String containerRelativePath, IPath indexedContainer){
- request(new RemoveFromIndex(containerRelativePath, indexedContainer, this));
-}
-/**
- * Removes the index for a given path.
- * This is a no-op if the index did not exist.
- */
-public synchronized void removeIndex(IPath containerPath) {
- if (VERBOSE)
- Util.verbose("removing index " + containerPath); //$NON-NLS-1$
- IPath indexLocation = computeIndexLocation(containerPath);
- Index index = getIndex(indexLocation);
- File indexFile = null;
- if (index != null) {
- index.monitor = null;
- indexFile = index.getIndexFile();
- }
- if (indexFile == null)
- indexFile = new File(indexLocation.toOSString()); // index is not cached yet, but still want to delete the file
- if (indexFile.exists())
- indexFile.delete();
- this.indexes.removeKey(indexLocation);
- updateIndexState(indexLocation, null);
-}
-/**
- * Removes all indexes whose paths start with (or are equal to) the given path.
- */
-public synchronized void removeIndexPath(IPath path) {
- Object[] keyTable = this.indexes.keyTable;
- Object[] valueTable = this.indexes.valueTable;
- IPath[] locations = null;
- int max = this.indexes.elementSize;
- int count = 0;
- for (int i = 0, l = keyTable.length; i < l; i++) {
- IPath indexLocation = (IPath) keyTable[i];
- if (indexLocation == null)
- continue;
- if (path.isPrefixOf(indexLocation)) {
- Index index = (Index) valueTable[i];
- index.monitor = null;
- if (locations == null)
- locations = new IPath[max];
- locations[count++] = indexLocation;
- File indexFile = index.getIndexFile();
- if (indexFile.exists())
- indexFile.delete();
- } else {
- max--;
- }
- }
- if (locations != null) {
- for (int i = 0; i < count; i++)
- this.indexes.removeKey(locations[i]);
- removeIndexesState(locations);
- }
-}
-/**
- * Removes all indexes whose paths start with (or are equal to) the given path.
- */
-public synchronized void removeIndexFamily(IPath path) {
- // only finds cached index files... shutdown removes all non-cached index files
- ArrayList toRemove = null;
- Object[] containerPaths = this.indexLocations.keyTable;
- for (int i = 0, length = containerPaths.length; i < length; i++) {
- IPath containerPath = (IPath) containerPaths[i];
- if (containerPath == null) continue;
- if (path.isPrefixOf(containerPath)) {
- if (toRemove == null)
- toRemove = new ArrayList();
- toRemove.add(containerPath);
- }
- }
- if (toRemove != null)
- for (int i = 0, length = toRemove.size(); i < length; i++)
- this.removeIndex((IPath) toRemove.get(i));
-}
-/**
- * Remove the content of the given source folder from the index.
- */
-public void removeSourceFolderFromIndex(JavaProject javaProject, IPath sourceFolder, char[][] inclusionPatterns, char[][] exclusionPatterns) {
- IProject project = javaProject.getProject();
- if (this.jobEnd > this.jobStart) {
- // skip it if a job to index the project is already in the queue
- IndexRequest request = new IndexAllProject(project, this);
- if (isJobWaiting(request)) return;
- }
-
- this.request(new RemoveFolderFromIndex(sourceFolder, inclusionPatterns, exclusionPatterns, project, this));
-}
-/**
- * Flush current state
- */
-public synchronized void reset() {
- super.reset();
- if (this.indexes != null) {
- this.indexes = new SimpleLookupTable();
- this.indexStates = null;
- }
- this.indexLocations = new SimpleLookupTable();
- this.javaPluginLocation = null;
-}
-public void saveIndex(Index index) throws IOException {
- // must have permission to write from the write monitor
- if (index.hasChanged()) {
- if (VERBOSE)
- Util.verbose("-> saving index " + index.getIndexFile()); //$NON-NLS-1$
- index.save();
- }
- synchronized (this) {
- IPath containerPath = new Path(index.containerPath);
- if (this.jobEnd > this.jobStart) {
- for (int i = this.jobEnd; i > this.jobStart; i--) { // skip the current job
- IJob job = this.awaitingJobs[i];
- if (job instanceof IndexRequest)
- if (((IndexRequest) job).containerPath.equals(containerPath)) return;
- }
- }
- IPath indexLocation = computeIndexLocation(containerPath);
- updateIndexState(indexLocation, SAVED_STATE);
- }
-}
-/**
- * Commit all index memory changes to disk
- */
-public void saveIndexes() {
- // only save cached indexes... the rest were not modified
- ArrayList toSave = new ArrayList();
- synchronized(this) {
- Object[] valueTable = this.indexes.valueTable;
- for (int i = 0, l = valueTable.length; i < l; i++) {
- Index index = (Index) valueTable[i];
- if (index != null)
- toSave.add(index);
- }
- }
-
- boolean allSaved = true;
- for (int i = 0, length = toSave.size(); i < length; i++) {
- Index index = (Index) toSave.get(i);
- ReadWriteMonitor monitor = index.monitor;
- if (monitor == null) continue; // index got deleted since acquired
- try {
- // take read lock before checking if index has changed
- // don't take write lock yet since it can cause a deadlock (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=50571)
- monitor.enterRead();
- if (index.hasChanged()) {
- if (monitor.exitReadEnterWrite()) {
- try {
- saveIndex(index);
- } catch(IOException e) {
- if (VERBOSE) {
- Util.verbose("-> got the following exception while saving:", System.err); //$NON-NLS-1$
- e.printStackTrace();
- }
- allSaved = false;
- } finally {
- monitor.exitWriteEnterRead();
- }
- } else {
- allSaved = false;
- }
- }
- } finally {
- monitor.exitRead();
- }
- }
- this.needToSave = !allSaved;
-}
-public void scheduleDocumentIndexing(final SearchDocument searchDocument, IPath container, final IPath indexLocation, final SearchParticipant searchParticipant) {
- request(new IndexRequest(container, this) {
- public boolean execute(IProgressMonitor progressMonitor) {
- if (this.isCancelled || progressMonitor != null && progressMonitor.isCanceled()) return true;
-
- /* ensure no concurrent write access to index */
- Index index = getIndex(this.containerPath, indexLocation, true, /*reuse index file*/ true /*create if none*/);
- if (index == null) return true;
- ReadWriteMonitor monitor = index.monitor;
- if (monitor == null) return true; // index got deleted since acquired
-
- try {
- monitor.enterWrite(); // ask permission to write
- indexDocument(searchDocument, searchParticipant, index, indexLocation);
- } finally {
- monitor.exitWrite(); // free write lock
- }
- return true;
- }
- public String toString() {
- return "indexing " + searchDocument.getPath(); //$NON-NLS-1$
- }
- });
-}
-
-public String toString() {
- StringBuffer buffer = new StringBuffer(10);
- buffer.append(super.toString());
- buffer.append("In-memory indexes:\n"); //$NON-NLS-1$
- int count = 0;
- Object[] valueTable = this.indexes.valueTable;
- for (int i = 0, l = valueTable.length; i < l; i++) {
- Index index = (Index) valueTable[i];
- if (index != null)
- buffer.append(++count).append(" - ").append(index.toString()).append('\n'); //$NON-NLS-1$
- }
- return buffer.toString();
-}
-
-private char[][] readIndexState(String dirOSString) {
- try {
- char[] savedIndexNames = org.eclipse.wst.jsdt.internal.compiler.util.Util.getFileCharContent(savedIndexNamesFile, null);
- if (savedIndexNames.length > 0) {
- char[][] names = CharOperation.splitOn('\n', savedIndexNames);
- if (names.length > 1) {
- // First line is DiskIndex signature + saved plugin working location (see writeSavedIndexNamesFile())
- String savedSignature = DiskIndex.SIGNATURE + "+" + dirOSString; //$NON-NLS-1$
- if (savedSignature.equals(new String(names[0])))
- return names;
- }
- }
- }
- catch (IOException ignored) {
- if (VERBOSE)
- Util.verbose("Failed to read saved index file names"); //$NON-NLS-1$
- }
- return null;
-}
-private synchronized void removeIndexesState(IPath[] locations) {
- getIndexStates(); // ensure the states are initialized
- int length = locations.length;
- boolean changed = false;
- for (int i=0; i<length; i++) {
- if (locations[i] == null) continue;
- if ((indexStates.removeKey(locations[i]) != null)) {
- changed = true;
- if (VERBOSE) {
- Util.verbose("-> index state updated to: ? for: "+locations[i]); //$NON-NLS-1$
- }
- }
- }
- if (!changed) return;
-
- writeSavedIndexNamesFile();
-}
-private synchronized void updateIndexState(IPath indexLocation, Integer indexState) {
- if (indexLocation.isEmpty())
- throw new IllegalArgumentException();
-
- getIndexStates(); // ensure the states are initialized
- if (indexState != null) {
- if (indexState.equals(indexStates.get(indexLocation))) return; // not changed
- indexStates.put(indexLocation, indexState);
- } else {
- if (!indexStates.containsKey(indexLocation)) return; // did not exist anyway
- indexStates.removeKey(indexLocation);
- }
-
- writeSavedIndexNamesFile();
-
- if (VERBOSE) {
- String state = "?"; //$NON-NLS-1$
- if (indexState == SAVED_STATE) state = "SAVED"; //$NON-NLS-1$
- else if (indexState == UPDATING_STATE) state = "UPDATING"; //$NON-NLS-1$
- else if (indexState == UNKNOWN_STATE) state = "UNKNOWN"; //$NON-NLS-1$
- else if (indexState == REBUILDING_STATE) state = "REBUILDING"; //$NON-NLS-1$
- Util.verbose("-> index state updated to: " + state + " for: "+indexLocation); //$NON-NLS-1$ //$NON-NLS-2$
- }
-}
-private void writeSavedIndexNamesFile() {
- BufferedWriter writer = null;
- try {
- writer = new BufferedWriter(new FileWriter(savedIndexNamesFile));
- writer.write(DiskIndex.SIGNATURE);
- writer.write('+');
- writer.write(getJavaPluginWorkingLocation().toOSString());
- writer.write('\n');
- Object[] keys = indexStates.keyTable;
- Object[] states = indexStates.valueTable;
- for (int i = 0, l = states.length; i < l; i++) {
- IPath key = (IPath) keys[i];
- if (key != null && !key.isEmpty() && states[i] == SAVED_STATE) {
- writer.write(key.lastSegment());
- writer.write('\n');
- }
- }
- } catch (IOException ignored) {
- if (VERBOSE)
- Util.verbose("Failed to write saved index file names", System.err); //$NON-NLS-1$
- } finally {
- if (writer != null) {
- try {
- writer.close();
- } catch (IOException e) {
- // ignore
- }
- }
- }
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/IndexRequest.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/IndexRequest.java
deleted file mode 100644
index a181c671..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/IndexRequest.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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 org.eclipse.core.runtime.IPath;
-import org.eclipse.wst.jsdt.internal.core.search.processing.IJob;
-
-public abstract class IndexRequest implements IJob {
- protected boolean isCancelled = false;
- protected IPath containerPath;
- protected IndexManager manager;
-
- public IndexRequest(IPath containerPath, IndexManager manager) {
- this.containerPath = containerPath;
- this.manager = manager;
- }
- public boolean belongsTo(String projectNameOrJarPath) {
- // used to remove pending jobs because the project was deleted... not to delete index files
- // can be found either by project name or JAR path name
- return projectNameOrJarPath.equals(this.containerPath.segment(0))
- || projectNameOrJarPath.equals(this.containerPath.toString());
- }
- public void cancel() {
- this.manager.jobWasCancelled(this.containerPath);
- this.isCancelled = true;
- }
- public void ensureReadyToRun() {
- // tag the index as inconsistent
- this.manager.aboutToUpdateIndex(this.containerPath, updatedIndexState());
- }
- protected Integer updatedIndexState() {
- return IndexManager.UPDATING_STATE;
- }
-}
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
deleted file mode 100644
index 5d62e484..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/IndexingParser.java
+++ /dev/null
@@ -1,64 +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.indexing;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.IProblemFactory;
-import org.eclipse.wst.jsdt.internal.compiler.ISourceElementRequestor;
-import org.eclipse.wst.jsdt.internal.compiler.SourceElementParser;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ImportReference;
-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.impl.CompilerOptions;
-
-/*
- * A source element parser that avoids creating unnecessary nodes.
- */
-public class IndexingParser extends SourceElementParser {
- SingleNameReference singleNameReference = new SingleNameReference(CharOperation.NO_CHAR, 0);
- QualifiedNameReference qualifiedNameReference = new QualifiedNameReference(CharOperation.NO_CHAR_CHAR, new long[0], 0, 0);
- ImportReference importReference = new ImportReference(CharOperation.NO_CHAR_CHAR, new long[1], false);
-
- public IndexingParser(ISourceElementRequestor requestor, IProblemFactory problemFactory, CompilerOptions options, boolean reportLocalDeclarations, boolean optimizeStringLiterals, boolean useSourceJavadocParser) {
- super(requestor, problemFactory, options, reportLocalDeclarations,
- optimizeStringLiterals, useSourceJavadocParser);
- }
-
-// protected ImportReference newImportReference(char[][] tokens, long[] sourcePositions, boolean onDemand, int mod) {
-// ImportReference ref = this.importReference;
-// ref.tokens = tokens;
-// ref.sourcePositions = sourcePositions;
-// if (onDemand) {
-// ref.bits |= ASTNode.OnDemand;
-// }
-// ref.sourceEnd = (int) (sourcePositions[sourcePositions.length-1] & 0x00000000FFFFFFFF);
-// ref.sourceStart = (int) (sourcePositions[0] >>> 32);
-// ref.modifiers = modifiers;
-// return ref;
-// }
-//
-// protected SingleNameReference newSingleNameReference(char[] source, long positions) {
-// SingleNameReference ref = this.singleNameReference;
-// ref.token = source;
-// ref.sourceStart = (int) (positions >>> 32);
-// ref.sourceEnd = (int) positions;
-// return ref;
-// }
-//
-// protected QualifiedNameReference newQualifiedNameReference(char[][] tokens, long[] positions, int sourceStart, int sourceEnd) {
-// QualifiedNameReference ref = this.qualifiedNameReference;
-// ref.tokens = tokens;
-// ref.sourcePositions = positions;
-// ref.sourceStart = sourceStart;
-// ref.sourceEnd = sourceEnd;
-// return ref;
-// }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/InternalSearchDocument.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/InternalSearchDocument.java
deleted file mode 100644
index f57463fb..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/InternalSearchDocument.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*******************************************************************************
- * 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
- * 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 org.eclipse.wst.jsdt.internal.compiler.SourceElementParser;
-import org.eclipse.wst.jsdt.internal.core.index.Index;
-
-/**
- * Internal search document implementation
- */
-public class InternalSearchDocument {
- Index index;
- private String containerRelativePath;
- SourceElementParser parser;
- /*
- * Hidden by API SearchDocument subclass
- */
- public void addIndexEntry(char[] category, char[] key) {
- if (this.index != null)
- index.addIndexEntry(category, key, getContainerRelativePath());
- }
- private String getContainerRelativePath() {
- if (this.containerRelativePath == null)
- this.containerRelativePath = this.index.containerRelativePath(getPath());
- return this.containerRelativePath;
- }
- /*
- * Hidden by API SearchDocument subclass
- */
- public void removeAllIndexEntries() {
- if (this.index != null)
- index.remove(getContainerRelativePath());
- }
- /*
- * Hidden by API SearchDocument subclass
- */
- public String getPath() {
- return null; // implemented by subclass
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/ReadWriteMonitor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/ReadWriteMonitor.java
deleted file mode 100644
index 053ea8c3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/ReadWriteMonitor.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.search.indexing;
-
-/**
- * Monitor ensuring no more than one writer working concurrently.
- * Multiple readers are allowed to perform simultaneously.
- */
-public class ReadWriteMonitor {
-
-/**
- * <0 : writing (cannot go beyond -1, i.e one concurrent writer)
- * =0 : idle
- * >0 : reading (number of concurrent readers)
- */
-private int status = 0;
-/**
- * Concurrent reading is allowed
- * Blocking only when already writing.
- */
-public synchronized void enterRead() {
- while (status < 0) {
- try {
- wait();
- } catch(InterruptedException e) {
- // ignore
- }
- }
- status++;
-}
-/**
- * Only one writer at a time is allowed to perform
- * Blocking only when already writing or reading.
- */
-public synchronized void enterWrite() {
- while (status != 0) {
- try {
- wait();
- } catch(InterruptedException e) {
- // ignore
- }
- }
- status--;
-}
-/**
- * Only notify waiting writer(s) if last reader
- */
-public synchronized void exitRead() {
-
- if (--status == 0) notifyAll();
-}
-/**
- * When writing is over, all readers and possible
- * writers are granted permission to restart concurrently
- */
-public synchronized void exitWrite() {
-
- if (++status == 0) notifyAll();
-}
-/**
- * Atomic exitRead/enterWrite: Allows to keep monitor in between
- * exit read and next enter write.
- * Use when writing changes is optional, otherwise call the individual methods.
- * Returns false if multiple readers are accessing the index.
- */
-public synchronized boolean exitReadEnterWrite() {
- if (status != 1) return false; // only continue if this is the only reader
-
- status = -1;
- return true;
-}
-/**
- * Atomic exitWrite/enterRead: Allows to keep monitor in between
- * exit write and next enter read.
- * When writing is over, all readers are granted permissing to restart
- * concurrently.
- * This is the same as:
- * <pre>
- * synchronized(monitor) {
- * monitor.exitWrite();
- * monitor.enterRead();
- * }
- * </pre>
- */
-public synchronized void exitWriteEnterRead() {
- this.exitWrite();
- this.enterRead();
-}
-public String toString() {
- StringBuffer buffer = new StringBuffer();
- if (status == 0) {
- buffer.append("Monitor idle "); //$NON-NLS-1$
- } else if (status < 0) {
- buffer.append("Monitor writing "); //$NON-NLS-1$
- } else if (status > 0) {
- buffer.append("Monitor reading "); //$NON-NLS-1$
- }
- buffer.append("(status = "); //$NON-NLS-1$
- buffer.append(this.status);
- buffer.append(")"); //$NON-NLS-1$
- return buffer.toString();
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/RemoveFolderFromIndex.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/RemoveFolderFromIndex.java
deleted file mode 100644
index 97f84afb..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/RemoveFolderFromIndex.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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.IOException;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.wst.jsdt.internal.core.index.Index;
-import org.eclipse.wst.jsdt.internal.core.search.processing.JobManager;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-class RemoveFolderFromIndex extends IndexRequest {
- IPath folderPath;
- char[][] inclusionPatterns;
- char[][] exclusionPatterns;
- IProject project;
-
- public RemoveFolderFromIndex(IPath folderPath, char[][] inclusionPatterns, char[][] exclusionPatterns, IProject project, IndexManager manager) {
- super(project.getFullPath(), manager);
- this.folderPath = folderPath;
- this.inclusionPatterns = inclusionPatterns;
- this.exclusionPatterns = exclusionPatterns;
- this.project = project;
- }
- public boolean execute(IProgressMonitor progressMonitor) {
-
- if (this.isCancelled || progressMonitor != null && progressMonitor.isCanceled()) return true;
-
- /* ensure no concurrent write access to index */
- Index index = this.manager.getIndex(this.containerPath, true, /*reuse index file*/ false /*create if none*/);
- if (index == null) return true;
- ReadWriteMonitor monitor = index.monitor;
- if (monitor == null) return true; // index got deleted since acquired
-
- try {
- monitor.enterRead(); // ask permission to read
- String containerRelativePath = Util.relativePath(this.folderPath, this.containerPath.segmentCount());
- String[] paths = index.queryDocumentNames(containerRelativePath);
- // all file names belonging to the folder or its subfolders and that are not excluded (see http://bugs.eclipse.org/bugs/show_bug.cgi?id=32607)
- if (paths != null) {
- if (this.exclusionPatterns == null && this.inclusionPatterns == null) {
- for (int i = 0, max = paths.length; i < max; i++) {
- manager.remove(paths[i], this.containerPath); // write lock will be acquired by the remove operation
- }
- } else {
- for (int i = 0, max = paths.length; i < max; i++) {
- String documentPath = this.containerPath.toString() + '/' + paths[i];
- if (!Util.isExcluded(new Path(documentPath), this.inclusionPatterns, this.exclusionPatterns, false))
- manager.remove(paths[i], this.containerPath); // write lock will be acquired by the remove operation
- }
- }
- }
- } catch (IOException e) {
- if (JobManager.VERBOSE) {
- Util.verbose("-> failed to remove " + this.folderPath + " from index because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$
- e.printStackTrace();
- }
- return false;
- } finally {
- monitor.exitRead(); // free read lock
- }
- return true;
- }
- public String toString() {
- return "removing " + this.folderPath + " from index " + this.containerPath; //$NON-NLS-1$ //$NON-NLS-2$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/RemoveFromIndex.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/RemoveFromIndex.java
deleted file mode 100644
index 5160af40..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/RemoveFromIndex.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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 org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.wst.jsdt.internal.core.index.Index;
-
-class RemoveFromIndex extends IndexRequest {
- String resourceName;
-
- public RemoveFromIndex(String resourceName, IPath containerPath, IndexManager manager) {
- super(containerPath, manager);
- this.resourceName = resourceName;
- }
- public boolean execute(IProgressMonitor progressMonitor) {
-
- if (this.isCancelled || progressMonitor != null && progressMonitor.isCanceled()) return true;
-
- /* ensure no concurrent write access to index */
- Index index = this.manager.getIndex(this.containerPath, true, /*reuse index file*/ false /*create if none*/);
- if (index == null) return true;
- ReadWriteMonitor monitor = index.monitor;
- if (monitor == null) return true; // index got deleted since acquired
-
- try {
- monitor.enterWrite(); // ask permission to write
- index.remove(resourceName);
- } finally {
- monitor.exitWrite(); // free write lock
- }
- return true;
- }
- public String toString() {
- return "removing " + this.resourceName + " from index " + this.containerPath; //$NON-NLS-1$ //$NON-NLS-2$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/SaveIndex.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/SaveIndex.java
deleted file mode 100644
index f1bea392..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/SaveIndex.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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.IOException;
-
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.wst.jsdt.internal.core.index.Index;
-import org.eclipse.wst.jsdt.internal.core.search.processing.JobManager;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/*
- * Save the index of a project.
- */
-public class SaveIndex extends IndexRequest {
- public SaveIndex(IPath containerPath, IndexManager manager) {
- super(containerPath, manager);
- }
- public boolean execute(IProgressMonitor progressMonitor) {
-
- if (this.isCancelled || progressMonitor != null && progressMonitor.isCanceled()) return true;
-
- /* ensure no concurrent write access to index */
- Index index = this.manager.getIndex(this.containerPath, true /*reuse index file*/, false /*don't create if none*/);
- if (index == null) return true;
- ReadWriteMonitor monitor = index.monitor;
- if (monitor == null) return true; // index got deleted since acquired
-
- try {
- monitor.enterWrite(); // ask permission to write
- this.manager.saveIndex(index);
- } catch (IOException e) {
- if (JobManager.VERBOSE) {
- Util.verbose("-> failed to save index " + this.containerPath + " because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$
- e.printStackTrace();
- }
- return false;
- } finally {
- monitor.exitWrite(); // free write lock
- }
- return true;
- }
- public String toString() {
- return "saving index for " + this.containerPath; //$NON-NLS-1$
- }
-}
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
deleted file mode 100644
index dedc317d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/SourceIndexer.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*******************************************************************************
- * 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
- * bug 242694 - Michael Spector <spektom@gmail.com>
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.search.indexing;
-
-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.internal.compiler.SourceElementParser;
-import org.eclipse.wst.jsdt.internal.compiler.util.SuffixConstants;
-import org.eclipse.wst.jsdt.internal.core.BasicCompilationUnit;
-import org.eclipse.wst.jsdt.internal.core.JavaModelManager;
-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;
-
-/**
- * A SourceIndexer indexes java files using a java parser. The following items are indexed:
- * Declarations of:
- * - Classes<br>
- * - Interfaces; <br>
- * - Methods;<br>
- * - Fields;<br>
- * References to:
- * - Methods (with number of arguments); <br>
- * - Fields;<br>
- * - Types;<br>
- * - Constructors.
- */
-public class SourceIndexer extends AbstractIndexer implements SuffixConstants {
-
- public SourceIndexer(SearchDocument document) {
- super(document);
- }
- public void indexDocument() {
- // Create a new Parser
- SourceIndexerRequestor requestor = new SourceIndexerRequestor(this);
- String documentPath = this.document.getPath();
- SourceElementParser parser = ((InternalSearchDocument) this.document).parser;
- if (parser == null) {
- IPath path = new Path(documentPath);
- IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(path.segment(0));
- parser = JavaModelManager.getJavaModelManager().indexManager.getSourceElementParser(JavaScriptCore.create(project), requestor);
- } else {
- parser.setRequestor(requestor);
- }
-
- // Launch the parser
- char[] source = null;
- char[] name = null;
- try {
- source = document.getCharContents();
- name = documentPath.toCharArray();
- } catch(Exception e){
- // ignore
- }
- if (source == null || name == null) return; // could not retrieve document info (e.g. resource was discarded)
- String pkgName=((JavaSearchDocument)document).getPackageName();
- char [][]packageName=null;
- if (pkgName!=null)
- {
- packageName=new char[1][];
- packageName[0]=pkgName.toCharArray();
- }
- BasicCompilationUnit compilationUnit = new BasicCompilationUnit(source, packageName, new String(name));
- try {
- parser.parseCompilationUnit(compilationUnit, true/*full parse*/);
- } catch (Exception e) {
- if (JobManager.VERBOSE) {
- e.printStackTrace();
- }
- }
- }
- public void indexMetadata() {
- // Create a new Parser
- SourceIndexerRequestor requestor = new SourceIndexerRequestor(this);
- String documentPath = this.document.getPath();
-
-
- // Launch the parser
- char[] source = null;
- char[] name = null;
- try {
- source = document.getCharContents();
- name = documentPath.toCharArray();
- } catch(Exception e){
- // ignore
- }
- if (source == null || name == null) return; // could not retrieve document info (e.g. resource was discarded)
- String pkgName=((JavaSearchDocument)document).getPackageName();
- char [][]packageName=null;
- if (pkgName!=null)
- {
- packageName=new char[1][];
- packageName[0]=pkgName.toCharArray();
- }
-
- LibraryAPIs apis = MetadataReader.readAPIsFromString(new String(source),documentPath);
- new MetadataSourceElementNotifier(apis,requestor).notifyRequestor();
-
- }
-
-}
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
deleted file mode 100644
index 5fadb995..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/SourceIndexerRequestor.java
+++ /dev/null
@@ -1,293 +0,0 @@
-/*******************************************************************************
- * 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.search.indexing;
-
-import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.ISourceElementRequestor;
-import org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration;
-import org.eclipse.wst.jsdt.internal.core.search.processing.JobManager;
-
-/**
- * This class is used by the JavaParserIndexer. When parsing the java file, the requestor
- * recognises the java elements (methods, fields, ...) and add them to an index.
- */
-public class SourceIndexerRequestor implements ISourceElementRequestor, IIndexConstants {
- SourceIndexer indexer;
-
- char[] packageName = CharOperation.NO_CHAR;
- char[][] enclosingTypeNames = new char[5][];
- int depth = 0;
- int methodDepth = 0;
-
-public SourceIndexerRequestor(SourceIndexer indexer) {
- this.indexer = indexer;
-}
-/**
- * @see ISourceElementRequestor#acceptConstructorReference(char[], int, int)
- */
-public void acceptConstructorReference(char[] typeName, int argCount, int sourcePosition) {
- this.indexer.addConstructorReference(typeName, argCount);
- int lastDot = CharOperation.lastIndexOf('.', typeName);
- if (lastDot != -1) {
- char[][] qualification = CharOperation.splitOn('.', CharOperation.subarray(typeName, 0, lastDot));
- for (int i = 0, length = qualification.length; i < length; i++) {
- this.indexer.addNameReference(qualification[i]);
- }
- }
-}
-/**
- * @see ISourceElementRequestor#acceptFieldReference(char[], int)
- */
-public void acceptFieldReference(char[] fieldName, int sourcePosition) {
- this.indexer.addFieldReference(fieldName);
-}
-/**
- * @see ISourceElementRequestor#acceptImport(int, int, char[][], boolean, int)
- */
-public void acceptImport(int declarationStart, int declarationEnd, char[][] tokens, boolean onDemand) {
- // imports have already been reported while creating the ImportRef node (see SourceElementParser#comsume*ImportDeclarationName() methods)
-}
-/**
- * @see ISourceElementRequestor#acceptLineSeparatorPositions(int[])
- */
-public void acceptLineSeparatorPositions(int[] positions) {
- // implements interface method
-}
-/**
- * @see ISourceElementRequestor#acceptMethodReference(char[], int, int)
- */
-public void acceptMethodReference(char[] methodName, int argCount, int sourcePosition) {
- this.indexer.addMethodReference(methodName, argCount);
-}
-/**
- * @see ISourceElementRequestor#acceptPackage(int, int, char[])
- */
-public void acceptPackage(int declarationStart, int declarationEnd, char[] name) {
- this.packageName = name;
-}
-/**
- * @see ISourceElementRequestor#acceptProblem(CategorizedProblem)
- */
-public void acceptProblem(CategorizedProblem problem) {
- // implements interface method
-}
-/**
- * @see ISourceElementRequestor#acceptTypeReference(char[][], int, int)
- */
-public void acceptTypeReference(char[][] typeName, int sourceStart, int sourceEnd) {
- int length = typeName.length;
- for (int i = 0; i < length - 1; i++)
- acceptUnknownReference(typeName[i], 0); // ?
- acceptTypeReference(typeName[length - 1], 0);
-}
-/**
- * @see ISourceElementRequestor#acceptTypeReference(char[], int)
- */
-public void acceptTypeReference(char[] simpleTypeName, int sourcePosition) {
- this.indexer.addTypeReference(simpleTypeName);
-}
-/**
- * @see ISourceElementRequestor#acceptUnknownReference(char[][], int, int)
- */
-public void acceptUnknownReference(char[][] name, int sourceStart, int sourceEnd) {
- for (int i = 0; i < name.length; i++) {
- acceptUnknownReference(name[i], 0);
- }
-}
-/**
- * @see ISourceElementRequestor#acceptUnknownReference(char[], int)
- */
-public void acceptUnknownReference(char[] name, int sourcePosition) {
- this.indexer.addNameReference(name);
-}
-/*
- * Rebuild the proper qualification for the current source type:
- *
- * java.lang.Object ---> null
- * java.util.Hashtable$Entry --> [Hashtable]
- * x.y.A$B$C --> [A, B]
- */
-public char[][] enclosingTypeNames(){
-
- if (depth == 0) return null;
-
- char[][] qualification = new char[this.depth][];
- System.arraycopy(this.enclosingTypeNames, 0, qualification, 0, this.depth);
- return qualification;
-}
-
-private void enterClass(TypeInfo typeInfo) {
- if(typeInfo.anonymousMember) {
- this.pushTypeName(typeInfo.name);
- return;
- }
- // eliminate possible qualifications, given they need to be fully resolved again
- if (typeInfo.superclass != null) {
- //typeInfo.superclass = getSimpleName(typeInfo.superclass);
-
- // add implicit constructor reference to default constructor
- this.indexer.addConstructorReference(typeInfo.superclass, 0);
- }
- char[][] typeNames;
- if (this.methodDepth > 0) {
- // set specific ['0'] value for local and anonymous to be able to filter them
- typeNames = ONE_ZERO_CHAR;
- } else {
- typeNames = this.enclosingTypeNames();
- }
- char [] typeName=typeInfo.name;
- char [] pkgName=this.packageName;
- int index;
- 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.pushTypeName(typeInfo.name);
-}
-/**
- * @see ISourceElementRequestor#enterCompilationUnit()
- */
-public void enterCompilationUnit() {
- // implements interface method
-}
-/**
- * @see ISourceElementRequestor#enterConstructor(MethodInfo)
- */
-public void enterConstructor(MethodInfo methodInfo) {
- this.indexer.addConstructorDeclaration(methodInfo.name, methodInfo.parameterTypes, methodInfo.parameterNames, methodInfo.modifiers);
- this.methodDepth++;
-}
-/**
- * @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);
- }
- this.methodDepth++;
-}
-/**
- * @see ISourceElementRequestor#enterInitializer(int, int)
- */
-public void enterInitializer(int declarationSourceStart, int modifiers) {
- this.methodDepth++;
-}
-/**
- * @see ISourceElementRequestor#enterMethod(MethodInfo)
- */
-public void enterMethod(MethodInfo methodInfo) {
- boolean isFunction=this.depth==0;
- this.indexer.addMethodDeclaration(methodInfo.name, methodInfo.parameterTypes, methodInfo.returnType,isFunction);
- this.methodDepth++;
-}
-/**
- * @see ISourceElementRequestor#enterType(TypeInfo)
- */
-public void enterType(TypeInfo typeInfo) {
- // TODO (jerome) might want to merge the 4 methods
- switch (TypeDeclaration.kind(typeInfo.modifiers)) {
- case TypeDeclaration.CLASS_DECL:
- enterClass(typeInfo);
- break;
- }
-}
-
-/**
- * @see ISourceElementRequestor#exitCompilationUnit(int)
- */
-public void exitCompilationUnit(int declarationEnd) {
- // implements interface method
-}
-/**
- * @see ISourceElementRequestor#exitConstructor(int)
- */
-public void exitConstructor(int declarationEnd) {
- this.methodDepth--;
-}
-/**
- * @see ISourceElementRequestor#exitField(int, int, int)
- */
-public void exitField(int initializationStart, int declarationEnd, int declarationSourceEnd) {
- this.methodDepth--;
-}
-/**
- * @see ISourceElementRequestor#exitInitializer(int)
- */
-public void exitInitializer(int declarationEnd) {
- this.methodDepth--;
-}
-/**
- * @see ISourceElementRequestor#exitMethod(int, int, int)
- */
-public void exitMethod(int declarationEnd, int defaultValueStart, int defaultValueEnd) {
- this.methodDepth--;
-}
-/**
- * @see ISourceElementRequestor#exitType(int)
- */
-public void exitType(int declarationEnd) {
- popTypeName();
-}
-/*
- * Returns the unqualified name without parameters from the given type name.
- */
-private char[] getSimpleName(char[] typeName) {
- int lastDot = -1, lastGenericStart = -1;
- int depthCount = 0;
- int length = typeName.length;
- lastDotLookup: for (int i = length -1; i >= 0; i--) {
- switch (typeName[i]) {
- case '.':
- if (depthCount == 0) {
- lastDot = i;
- break lastDotLookup;
- }
- break;
- case '<':
- depthCount--;
- if (depthCount == 0) lastGenericStart = i;
- break;
- case '>':
- depthCount++;
- break;
- }
- }
- if (lastGenericStart < 0) {
- if (lastDot < 0) {
- return typeName;
- }
- return CharOperation.subarray(typeName, lastDot + 1, length);
- }
- return CharOperation.subarray(typeName, lastDot + 1, lastGenericStart);
-}
-public void popTypeName() {
- if (depth > 0) {
- enclosingTypeNames[--depth] = null;
- } else if (JobManager.VERBOSE) {
- // dump a trace so it can be tracked down
- try {
- enclosingTypeNames[-1] = null;
- } catch (ArrayIndexOutOfBoundsException e) {
- e.printStackTrace();
- }
- }
-}
-public void pushTypeName(char[] typeName) {
- if (depth == enclosingTypeNames.length)
- System.arraycopy(enclosingTypeNames, 0, enclosingTypeNames = new char[depth*2][], 0, depth);
- enclosingTypeNames[depth++] = typeName;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/AndPattern.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/AndPattern.java
deleted file mode 100644
index d81d9ace..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/AndPattern.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*******************************************************************************
- * 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.matching;
-
-import java.io.IOException;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchParticipant;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.compiler.util.SimpleSet;
-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.IndexQueryRequestor;
-
-/**
- * Query the index multiple times and do an 'and' on the results.
- */
-public abstract class AndPattern extends JavaSearchPattern { // TODO should rename IntersectingPattern, and make AndPattern a true subclass
-
-public AndPattern(int patternKind, int matchRule) {
- super(patternKind, matchRule);
-}
-public void findIndexMatches(Index index, IndexQueryRequestor requestor, SearchParticipant participant, IJavaScriptSearchScope scope, IProgressMonitor progressMonitor) throws IOException {
- if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException();
-
- this.resetQuery();
- SimpleSet intersectedNames = null;
- try {
- index.startQuery();
- do {
- SearchPattern pattern = ((InternalSearchPattern) this).currentPattern();
- EntryResult[] entries = ((InternalSearchPattern)pattern).queryIn(index);
- if (entries == null) return;
-
- SearchPattern decodedResult = pattern.getBlankPattern();
- SimpleSet newIntersectedNames = new SimpleSet(3);
- for (int i = 0, l = entries.length; i < l; i++) {
- if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException();
-
- EntryResult entry = entries[i];
- decodedResult.decodeIndexKey(entry.getWord());
- if (pattern.matchesDecodedKey(decodedResult)) {
- String[] names = entry.getDocumentNames(index);
- if (intersectedNames != null) {
- for (int j = 0, n = names.length; j < n; j++)
- if (intersectedNames.includes(names[j]))
- newIntersectedNames.add(names[j]);
- } else {
- for (int j = 0, n = names.length; j < n; j++)
- newIntersectedNames.add(names[j]);
- }
- }
- }
-
- if (newIntersectedNames.elementSize == 0) return;
- intersectedNames = newIntersectedNames;
- } while (this.hasNextQuery());
- } finally {
- index.stopQuery();
- }
-
- String containerPath = index.containerPath;
- Object[] names = intersectedNames.values;
- for (int i = 0, l = names.length; i < l; i++)
- if (names[i] != null)
- ((InternalSearchPattern) this).acceptMatch((String) names[i], containerPath, null/*no pattern*/, requestor, participant, scope); // AndPatterns cannot provide the decoded result
-}
-/**
- * Returns whether another query must be done.
- */
-protected abstract boolean hasNextQuery();
-/**
- * Resets the query and prepares this pattern to be queried.
- */
-protected abstract void resetQuery();
-}
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
deleted file mode 100644
index 66989681..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/ClassFileMatchLocator.java
+++ /dev/null
@@ -1,266 +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.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-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;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BinaryTypeBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.FieldBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding;
-import org.eclipse.wst.jsdt.internal.compiler.problem.AbortCompilation;
-import org.eclipse.wst.jsdt.internal.core.BinaryType;
-import org.eclipse.wst.jsdt.internal.core.ClassFile;
-import org.eclipse.wst.jsdt.internal.core.JavaElement;
-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;
-
-public class ClassFileMatchLocator implements IIndexConstants {
-
-public static char[] convertClassFileFormat(char[] name) {
- return CharOperation.replaceOnCopy(name, '/', '.');
-}
-
-private boolean checkDeclaringType(IBinaryType enclosingBinaryType, char[] simpleName, char[] qualification, boolean isCaseSensitive, boolean isCamelCase) {
- if (simpleName == null && qualification == null) return true;
- if (enclosingBinaryType == null) return true;
-
- char[] declaringTypeName = convertClassFileFormat(enclosingBinaryType.getName());
- return checkTypeName(simpleName, qualification, declaringTypeName, isCaseSensitive, isCamelCase);
-}
-private boolean checkParameters(char[] methodDescriptor, char[][] parameterSimpleNames, char[][] parameterQualifications, boolean isCaseSensitive, boolean isCamelCase) {
- char[][] arguments = Signature.getParameterTypes(methodDescriptor);
- int parameterCount = parameterSimpleNames.length;
- if (parameterCount != arguments.length) return false;
- for (int i = 0; i < parameterCount; i++)
- if (!checkTypeName(parameterSimpleNames[i], parameterQualifications[i], Signature.toCharArray(arguments[i]), isCaseSensitive, isCamelCase))
- return false;
- return true;
-}
-private boolean checkTypeName(char[] simpleName, char[] qualification, char[] fullyQualifiedTypeName, boolean isCaseSensitive, boolean isCamelCase) {
- // NOTE: if case insensitive then simpleName & qualification are assumed to be lowercase
- char[] wildcardPattern = PatternLocator.qualifiedPattern(simpleName, qualification);
- if (wildcardPattern == null) return true;
- return CharOperation.match(wildcardPattern, fullyQualifiedTypeName, isCaseSensitive);
-}
-/**
- * Locate declaration in the current class file. This class file is always in a jar.
- */
-public void locateMatches(MatchLocator locator, ClassFile classFile, IBinaryType info) throws CoreException {
- // check class definition
- SearchPattern pattern = locator.pattern;
- BinaryType binaryType = (BinaryType) classFile.getType();
- if (matchBinary(pattern, info, null)) {
- binaryType = new ResolvedBinaryType((JavaElement) binaryType.getParent(), binaryType.getElementName(), binaryType.getKey());
- locator.reportBinaryMemberDeclaration(null, binaryType, null, info, SearchMatch.A_ACCURATE);
- }
-
- int accuracy = SearchMatch.A_ACCURATE;
- if (((InternalSearchPattern)pattern).mustResolve) {
- try {
- BinaryTypeBinding binding = locator.cacheBinaryType(binaryType, info);
- if (binding != null) {
- // filter out element not in hierarchy scope
- if (!locator.typeInHierarchy(binding)) return;
-
- MethodBinding[] methods = binding.methods();
- for (int i = 0, l = methods.length; i < l; i++) {
- MethodBinding method = methods[i];
- if (locator.patternLocator.resolveLevel(method) == PatternLocator.ACCURATE_MATCH) {
- char[] methodSignature = method.signature();
- IFunction methodHandle = binaryType.getFunction(
- new String(method.isConstructor() ? binding.compoundName[binding.compoundName.length-1] : method.selector),
- CharOperation.toStrings(Signature.getParameterTypes(convertClassFileFormat(methodSignature))));
- locator.reportBinaryMemberDeclaration(null, methodHandle, method, info, SearchMatch.A_ACCURATE);
- }
- }
-
- FieldBinding[] fields = binding.fields();
- for (int i = 0, l = fields.length; i < l; i++) {
- FieldBinding field = fields[i];
- if (locator.patternLocator.resolveLevel(field) == PatternLocator.ACCURATE_MATCH) {
- IField fieldHandle = binaryType.getField(new String(field.name));
- locator.reportBinaryMemberDeclaration(null, fieldHandle, field, info, SearchMatch.A_ACCURATE);
- }
- }
-
- // no need to check binary info since resolve was successful
- return;
- }
- } catch (AbortCompilation e) { // if compilation was aborted it is a problem with the class path
- }
- // report as a potential match if binary info matches the pattern
- accuracy = SearchMatch.A_INACCURATE;
- }
-
- IBinaryMethod[] methods = info.getMethods();
- if (methods != null) {
- for (int i = 0, l = methods.length; i < l; i++) {
- IBinaryMethod method = methods[i];
- if (matchBinary(pattern, method, info)) {
- char[] name;
- if (method.isConstructor()) {
- name = info.getName();
- int lastSlash = CharOperation.lastIndexOf('/', name);
- if (lastSlash != -1) {
- name = CharOperation.subarray(name, lastSlash+1, name.length);
- }
- } else {
- name = method.getSelector();
- }
- String selector = new String(name);
- String[] parameterTypes = CharOperation.toStrings(Signature.getParameterTypes(convertClassFileFormat(method.getMethodDescriptor())));
- IFunction methodHandle = binaryType.getFunction(selector, parameterTypes);
- methodHandle = new ResolvedBinaryMethod(binaryType, selector, parameterTypes, methodHandle.getKey());
- locator.reportBinaryMemberDeclaration(null, methodHandle, null, info, accuracy);
- }
- }
- }
-
- IBinaryField[] fields = info.getFields();
- if (fields != null) {
- for (int i = 0, l = fields.length; i < l; i++) {
- IBinaryField field = fields[i];
- if (matchBinary(pattern, field, info)) {
- String fieldName = new String(field.getName());
- IField fieldHandle = binaryType.getField(fieldName);
- fieldHandle = new ResolvedBinaryField(binaryType, fieldName, fieldHandle.getKey());
- locator.reportBinaryMemberDeclaration(null, fieldHandle, null, info, accuracy);
- }
- }
- }
-}
-/**
- * Finds out whether the given binary info matches the search pattern.
- * Default is to return false.
- */
-boolean matchBinary(SearchPattern pattern, Object binaryInfo, IBinaryType enclosingBinaryType) {
- switch (((InternalSearchPattern)pattern).kind) {
- case CONSTRUCTOR_PATTERN :
- return matchConstructor((ConstructorPattern) pattern, binaryInfo, enclosingBinaryType);
- case FIELD_PATTERN :
- return matchField((FieldPattern) pattern, binaryInfo, enclosingBinaryType);
- case METHOD_PATTERN :
- return matchMethod((MethodPattern) pattern, binaryInfo, enclosingBinaryType);
- case SUPER_REF_PATTERN :
- return matchSuperTypeReference((SuperTypeReferencePattern) pattern, binaryInfo, enclosingBinaryType);
- case TYPE_DECL_PATTERN :
- return matchTypeDeclaration((TypeDeclarationPattern) pattern, binaryInfo, enclosingBinaryType);
- case OR_PATTERN :
- SearchPattern[] patterns = ((OrPattern) pattern).patterns;
- for (int i = 0, length = patterns.length; i < length; i++)
- if (matchBinary(patterns[i], binaryInfo, enclosingBinaryType)) return true;
- }
- return false;
-}
-boolean matchConstructor(ConstructorPattern pattern, Object binaryInfo, IBinaryType enclosingBinaryType) {
- if (!pattern.findDeclarations) return false; // only relevant when finding declarations
- if (!(binaryInfo instanceof IBinaryMethod)) return false;
-
- IBinaryMethod method = (IBinaryMethod) binaryInfo;
- if (!method.isConstructor()) return false;
- if (!checkDeclaringType(enclosingBinaryType, pattern.declaringSimpleName, pattern.declaringQualification, pattern.isCaseSensitive(), pattern.isCamelCase()))
- return false;
- if (pattern.parameterSimpleNames != null) {
- char[] methodDescriptor = convertClassFileFormat(method.getMethodDescriptor());
- if (!checkParameters(methodDescriptor, pattern.parameterSimpleNames, pattern.parameterQualifications, pattern.isCaseSensitive(), pattern.isCamelCase()))
- return false;
- }
- return true;
-}
-boolean matchField(FieldPattern pattern, Object binaryInfo, IBinaryType enclosingBinaryType) {
- if (!pattern.findDeclarations) return false; // only relevant when finding declarations
- if (!(binaryInfo instanceof IBinaryField)) return false;
-
- IBinaryField field = (IBinaryField) binaryInfo;
- if (!pattern.matchesName(pattern.name, field.getName())) return false;
- if (!checkDeclaringType(enclosingBinaryType, pattern.declaringSimpleName, pattern.declaringQualification, pattern.isCaseSensitive(), pattern.isCamelCase()))
- return false;
-
- char[] fieldTypeSignature = Signature.toCharArray(convertClassFileFormat(field.getTypeName()));
- return checkTypeName(pattern.typeSimpleName, pattern.typeQualification, fieldTypeSignature, pattern.isCaseSensitive(), pattern.isCamelCase());
-}
-boolean matchMethod(MethodPattern pattern, Object binaryInfo, IBinaryType enclosingBinaryType) {
- if (!pattern.findDeclarations) return false; // only relevant when finding declarations
- if (!(binaryInfo instanceof IBinaryMethod)) return false;
-
- IBinaryMethod method = (IBinaryMethod) binaryInfo;
- if (!pattern.matchesName(pattern.selector, method.getSelector())) return false;
- if (!checkDeclaringType(enclosingBinaryType, pattern.declaringSimpleName, pattern.declaringQualification, 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 checkParameters = pattern.parameterSimpleNames != null;
- if (checkReturnType || checkParameters) {
- char[] methodDescriptor = convertClassFileFormat(method.getMethodDescriptor());
- if (checkReturnType) {
- char[] returnTypeSignature = Signature.toCharArray(Signature.getReturnType(methodDescriptor));
- if (!checkTypeName(pattern.returnSimpleName, pattern.returnQualification, returnTypeSignature, pattern.isCaseSensitive(), pattern.isCamelCase()))
- return false;
- }
- if (checkParameters && !checkParameters(methodDescriptor, pattern.parameterSimpleNames, pattern.parameterQualifications, pattern.isCaseSensitive(), pattern.isCamelCase()))
- return false;
- }
- return true;
-}
-boolean matchSuperTypeReference(SuperTypeReferencePattern pattern, Object binaryInfo, IBinaryType enclosingBinaryType) {
- if (!(binaryInfo instanceof IBinaryType)) return false;
-
- IBinaryType type = (IBinaryType) binaryInfo;
-
- char[] vmName = type.getSuperclassName();
- if (vmName != null) {
- char[] superclassName = convertClassFileFormat(vmName);
- if (checkTypeName(pattern.superSimpleName, pattern.superQualification, superclassName, pattern.isCaseSensitive(), pattern.isCamelCase()))
- return true;
- }
- return false;
-}
-boolean matchTypeDeclaration(TypeDeclarationPattern pattern, Object binaryInfo, IBinaryType enclosingBinaryType) {
- if (!(binaryInfo instanceof IBinaryType)) return false;
-
- IBinaryType type = (IBinaryType) binaryInfo;
- char[] fullyQualifiedTypeName = convertClassFileFormat(type.getName());
- boolean qualifiedPattern = pattern instanceof QualifiedTypeDeclarationPattern;
- if (pattern.enclosingTypeNames == null || qualifiedPattern) {
- 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;
- if (!checkTypeName(simpleName, pkg, fullyQualifiedTypeName, pattern.isCaseSensitive(), pattern.isCamelCase())) return false;
- } else {
- char[] enclosingTypeName = CharOperation.concatWith(pattern.enclosingTypeNames, '.');
- char[] patternString = pattern.pkg == null
- ? enclosingTypeName
- : CharOperation.concat(pattern.pkg, 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/ClasspathSourceDirectory.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/ClasspathSourceDirectory.java
deleted file mode 100644
index 2df411bd..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/ClasspathSourceDirectory.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.wst.jsdt.internal.compiler.env.NameEnvironmentAnswer;
-import org.eclipse.wst.jsdt.internal.compiler.util.SimpleLookupTable;
-import org.eclipse.wst.jsdt.internal.core.builder.ClasspathLocation;
-import org.eclipse.wst.jsdt.internal.core.util.ResourceCompilationUnit;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-public class ClasspathSourceDirectory extends ClasspathLocation {
-
- IContainer sourceFolder;
- SimpleLookupTable directoryCache;
- SimpleLookupTable missingPackageHolder = new SimpleLookupTable();
- char[][] fullExclusionPatternChars;
- char[][] fulInclusionPatternChars;
-
-ClasspathSourceDirectory(IContainer sourceFolder, char[][] fullExclusionPatternChars, char[][] fulInclusionPatternChars) {
- this.sourceFolder = sourceFolder;
- this.directoryCache = new SimpleLookupTable(5);
- this.fullExclusionPatternChars = fullExclusionPatternChars;
- this.fulInclusionPatternChars = fulInclusionPatternChars;
-}
-
-public void cleanup() {
- this.directoryCache = null;
-}
-
-SimpleLookupTable directoryTable(String qualifiedPackageName) {
- SimpleLookupTable dirTable = (SimpleLookupTable) directoryCache.get(qualifiedPackageName);
- if (dirTable == missingPackageHolder) return null; // package exists in another classpath directory or jar
- if (dirTable != null) return dirTable;
-
- try {
- IResource container = sourceFolder.findMember(qualifiedPackageName); // this is a case-sensitive check
- if (container instanceof IContainer) {
- IResource[] members = ((IContainer) container).members();
- dirTable = new SimpleLookupTable();
- for (int i = 0, l = members.length; i < l; i++) {
- IResource m = members[i];
- String name;
- if (m.getType() == IResource.FILE) {
- int index = Util.indexOfJavaLikeExtension(name = m.getName());
- if (index >= 0) {
- String fullPath = m.getFullPath().toString();
- if (!org.eclipse.wst.jsdt.internal.compiler.util.Util.isExcluded(fullPath.toCharArray(), this.fulInclusionPatternChars, this.fullExclusionPatternChars, false/*not a folder path*/)) {
- dirTable.put(name.substring(0, index), m);
- }
- }
- }
- }
- directoryCache.put(qualifiedPackageName, dirTable);
- return dirTable;
- }
- } catch(CoreException ignored) {
- // treat as if missing
- }
- directoryCache.put(qualifiedPackageName, missingPackageHolder);
- return null;
-}
-
-public boolean equals(Object o) {
- if (this == o) return true;
- if (!(o instanceof ClasspathSourceDirectory)) return false;
-
- return sourceFolder.equals(((ClasspathSourceDirectory) o).sourceFolder);
-}
-
-public NameEnvironmentAnswer findClass(String sourceFileWithoutExtension, String qualifiedPackageName, String qualifiedSourceFileWithoutExtension) {
- SimpleLookupTable dirTable = directoryTable(qualifiedPackageName);
- if (dirTable != null && dirTable.elementSize > 0) {
- IFile file = (IFile) dirTable.get(sourceFileWithoutExtension);
- if (file != null) {
- return new NameEnvironmentAnswer(new ResourceCompilationUnit(file, file.getLocationURI()), null /* no access restriction */);
- }
- }
- return null;
-}
-
-public IPath getProjectRelativePath() {
- return sourceFolder.getProjectRelativePath();
-}
-
-public boolean isPackage(String qualifiedPackageName) {
- return directoryTable(qualifiedPackageName) != null;
-}
-
-public void reset() {
- this.directoryCache = new SimpleLookupTable(5);
-}
-
-public String toString() {
- return "Source classpath directory " + sourceFolder.getFullPath().toString(); //$NON-NLS-1$
-}
-
-public String debugPathString() {
- return this.sourceFolder.getFullPath().toString();
-}
-
-}
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;
-
-/**
- * <p>Pattern used to find and store constructor declarations.</p>
- */
-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);
- }
-
- /**
- * <p>Decodes an index key made with {@link #createDeclarationIndexKey(char[], int, char[][], char[][], int)} into the
- * parameters of this pattern.</p>
- *
- * @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;
- }
- }
-
- /**
- * <p>Creates a constructor index key based on the given information to be placed in the index.</p>
- *
- * @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 <code>parameterCount</code>
- * @param parameterNames Names of the parameters, should be same length as <code>parameterCount</code>
- * @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
deleted file mode 100644
index 1dbbf080..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/ConstructorLocator.java
+++ /dev/null
@@ -1,358 +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.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-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.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.ConstructorDeclaration;
-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.FieldDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.FieldReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocMessageSend;
-import org.eclipse.wst.jsdt.internal.compiler.ast.MessageSend;
-import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedAllocationExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.SingleNameReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Binding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding;
-import org.eclipse.wst.jsdt.internal.compiler.util.Util;
-
-public class ConstructorLocator extends PatternLocator {
-
-protected ConstructorPattern 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;
-
- if (!matchParametersCount(node, ((ExplicitConstructorCall) node).arguments)) 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))
- return IMPOSSIBLE_MATCH;
-
-// if (!matchParametersCount(node, allocation.arguments)) return IMPOSSIBLE_MATCH;
-
- 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;
- 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()))
- return IMPOSSIBLE_MATCH;
- }
-
-// if (!matchParametersCount(field, allocation.arguments)) 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);
- }
- 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;
-
- // 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;
- }
- level = newLevel; // can only be downgraded
- }
- }
- }
- 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;
- }
- 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;
- }
-
- // 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;
- }
-
- 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;
- }
- }
- 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;
- }
-
- // Create search match
- match = locator.newMethodReferenceMatch(element, elementBinding, accuracy, -1, -1, true, reference);
-
- if (this.pattern.hasConstructorArguments()) { // 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();
- 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);
-}
-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);
- }
- }
- 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 (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()))
- 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;
-}
-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
- }
- }
- }
- 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);
- }
- }
- 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
deleted file mode 100644
index 3f458119..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/ConstructorPattern.java
+++ /dev/null
@@ -1,309 +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 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.index.EntryResult;
-import org.eclipse.wst.jsdt.internal.core.index.Index;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-public class ConstructorPattern extends JavaSearchPattern {
-
-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 };
-
-/**
- * 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);
-}
-
-ConstructorPattern(int matchRule) {
- super(CONSTRUCTOR_PATTERN, matchRule);
-}
-public ConstructorPattern(
- boolean findDeclarations,
- boolean findReferences,
- char[] declaringSimpleName,
- char[] declaringQualification,
- char[][] parameterQualifications,
- char[][] parameterSimpleNames,
- int matchRule) {
-
- this(matchRule);
-
- 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]);
- }
- } else {
- this.parameterCount = -1;
- }
- ((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
- }
-
- constructorParameters = true;
-
- // Store type signature and arguments for declaring type
- storeTypeSignaturesAndArguments(method.getDeclaringType());
-
-
- // 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<length; i++) {
- parametersTypeSignatures[i] = Util.splitTypeLevelsSignature(parameterSignatures[i]);
- parametersTypeArguments[i] = Util.getAllTypeArguments(parametersTypeSignatures[i]);
- }
- }
- }
-
- // 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) {
-
- this(findDeclarations,
- findReferences,
- declaringSimpleName,
- declaringQualification,
- parameterQualifications,
- parameterSimpleNames,
- matchRule);
-
- // Store type signature and arguments for declaring type
- if (declaringSignature != null) {
- typeSignatures = Util.splitTypeLevelsSignature(declaringSignature);
- setTypeArguments(Util.getAllTypeArguments(typeSignatures));
- }
-
- // 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<length; i++) {
- parametersTypeSignatures[i] = Util.splitTypeLevelsSignature(parameterSignatures[i]);
- parametersTypeArguments[i] = Util.getAllTypeArguments(parametersTypeSignatures[i]);
- }
- }
- }
-
- // Store type signatures and arguments for method
- constructorArguments = arguments;
- if (arguments == null || arguments.length == 0) {
- if (getTypeArguments() != null && getTypeArguments().length > 0) {
- constructorArguments = getTypeArguments()[0];
- }
- }
- 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;
- }
- if (i == last) {
- this.parameterCount = key[i] - '0';
- } else {
- power *= 10;
- this.parameterCount += power * (key[i] - '0');
- }
- }
-}
-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;
-
- // 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;
- }
- 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;
- }
-
- 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$
- }
- 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]);
- }
- }
- 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
deleted file mode 100644
index 2fe392e0..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/DeclarationOfAccessedFieldsPattern.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*******************************************************************************
- * 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.matching;
-
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.compiler.util.SimpleSet;
-
-public class DeclarationOfAccessedFieldsPattern extends FieldPattern {
-
-protected IJavaScriptElement enclosingElement;
-protected SimpleSet knownFields;
-
-public DeclarationOfAccessedFieldsPattern(IJavaScriptElement enclosingElement) {
- super(false, true, true, false,null, null, null, null, null, R_PATTERN_MATCH,
- (enclosingElement instanceof IField) ?(IField)enclosingElement :null);
-
- this.enclosingElement = enclosingElement;
- this.knownFields = new SimpleSet();
- ((InternalSearchPattern)this).mustResolve = true;
-}
-}
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
deleted file mode 100644
index 6057147f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/DeclarationOfReferencedMethodsPattern.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*******************************************************************************
- * 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.matching;
-
-//import java.util.HashSet;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.compiler.util.SimpleSet;
-
-public class DeclarationOfReferencedMethodsPattern extends MethodPattern {
-
-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);
-
- this.enclosingElement = enclosingElement;
- this.knownMethods = new SimpleSet();
- ((InternalSearchPattern)this).mustResolve = true;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/DeclarationOfReferencedTypesPattern.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/DeclarationOfReferencedTypesPattern.java
deleted file mode 100644
index 2f0ceb67..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/DeclarationOfReferencedTypesPattern.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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.matching;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.compiler.util.SimpleSet;
-
-public class DeclarationOfReferencedTypesPattern extends TypeReferencePattern {
-
-protected SimpleSet knownTypes;
-protected IJavaScriptElement enclosingElement;
-
-public DeclarationOfReferencedTypesPattern(IJavaScriptElement enclosingElement) {
- super(null, null, R_PATTERN_MATCH);
-
- this.enclosingElement = enclosingElement;
- this.knownTypes = new SimpleSet();
- ((InternalSearchPattern)this).mustResolve = true;
-}
-}
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
deleted file mode 100644
index b2b8425f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/FieldLocator.java
+++ /dev/null
@@ -1,459 +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.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.infer.InferredAttribute;
-import org.eclipse.wst.jsdt.core.search.FieldDeclarationMatch;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode;
-import org.eclipse.wst.jsdt.internal.compiler.ast.AbstractVariableDeclaration;
-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.ImportReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.NameReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedNameReference;
-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.TypeDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.env.IBinaryType;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ArrayBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Binding;
-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.LocalVariableBinding;
-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.util.SimpleSet;
-import org.eclipse.wst.jsdt.internal.core.JavaElement;
-
-public class FieldLocator extends VariableLocator {
-
-protected boolean isDeclarationOfAccessedFieldsPattern;
-FieldPattern fieldPattern;
-
-
-public FieldLocator(FieldPattern pattern) {
- super(pattern);
- this.fieldPattern=pattern;
- this.isDeclarationOfAccessedFieldsPattern = this.pattern instanceof DeclarationOfAccessedFieldsPattern;
-}
-public int match(ASTNode node, MatchingNodeSet nodeSet) {
- int declarationsLevel = IMPOSSIBLE_MATCH;
- return nodeSet.addMatch(node, declarationsLevel);
-}
-//public int match(ConstructorDeclaration node, MatchingNodeSet nodeSet) - SKIP IT
-public int match(FieldDeclaration node, MatchingNodeSet nodeSet) {
- int referencesLevel = IMPOSSIBLE_MATCH;
- if (this.pattern.findReferences)
- // must be a write only access with an initializer
- if (this.pattern.writeAccess && !this.pattern.readAccess && node.initialization != null)
- if (matchesName(this.pattern.name, node.name))
- referencesLevel = ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH;
-
- int declarationsLevel = IMPOSSIBLE_MATCH;
- if (this.pattern.findDeclarations) {
- switch (node.getKind()) {
- case AbstractVariableDeclaration.FIELD :
- if (matchesName(this.pattern.name, node.name))
- if (matchesTypeReference(((FieldPattern)this.pattern).typeSimpleName, node.type))
- declarationsLevel = ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH;
- break;
- }
- }
- return nodeSet.addMatch(node, referencesLevel >= declarationsLevel ? referencesLevel : declarationsLevel); // use the stronger match
-}
-
-public int match(LocalDeclaration node, MatchingNodeSet nodeSet) {
- if (!this.fieldPattern.isVar)
- return IMPOSSIBLE_MATCH;
- int referencesLevel = IMPOSSIBLE_MATCH;
- if (this.pattern.findReferences)
- // must be a write only access with an initializer
- if (this.pattern.writeAccess && !this.pattern.readAccess && node.initialization != null)
- if (matchesName(this.pattern.name, node.name))
- referencesLevel = ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH;
-
- int declarationsLevel = IMPOSSIBLE_MATCH;
- if (this.pattern.findDeclarations)
- if (matchesName(this.pattern.name, node.name))
-// if (node.declarationSourceStart == this.pattern.getVariableStart())
- declarationsLevel = ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH;
-
- return nodeSet.addMatch(node, referencesLevel >= declarationsLevel ? referencesLevel : declarationsLevel); // use the stronger match
-}
-
-//public int match(ConstructorDeclaration node, MatchingNodeSet nodeSet) - SKIP IT
-public int match(InferredAttribute node, MatchingNodeSet nodeSet) {
- if (this.fieldPattern.isVar)
- return IMPOSSIBLE_MATCH;
- int referencesLevel = IMPOSSIBLE_MATCH;
- if (this.pattern.findReferences)
- // must be a write only access with an initializer
- if (this.pattern.writeAccess && !this.pattern.readAccess /*&& node.initialization != null*/)
- if (matchesName(this.pattern.name, node.name))
- referencesLevel = ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH;
-
- int declarationsLevel = IMPOSSIBLE_MATCH;
- if (this.pattern.findDeclarations) {
-// switch (node.getKind()) {
-// case AbstractVariableDeclaration.FIELD :
-// case AbstractVariableDeclaration.ENUM_CONSTANT :
- if (matchesName(this.pattern.name, node.name))
-// if (matchesTypeReference(((FieldPattern)this.pattern).typeSimpleName, node.type))
- declarationsLevel = ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH;
-// break;
-// }
- }
- return nodeSet.addMatch(node, referencesLevel >= declarationsLevel ? referencesLevel : declarationsLevel); // use the stronger match
-}
-//public int match(FunctionDeclaration node, MatchingNodeSet nodeSet) - SKIP IT
-//public int match(MessageSend node, MatchingNodeSet nodeSet) - SKIP IT
-//public int match(TypeDeclaration node, MatchingNodeSet nodeSet) - SKIP IT
-//public int match(TypeReference node, MatchingNodeSet nodeSet) - SKIP IT
-
-protected int matchContainer() {
- if (this.pattern.findReferences) {
- // need to look everywhere to find in javadocs and static import
- return ALL_CONTAINER;
- }
- return (this.fieldPattern.isVar)? COMPILATION_UNIT_CONTAINER : CLASS_CONTAINER;
-}
-
-protected int matchField(FieldBinding field, boolean matchName) {
- if (field == null) return INACCURATE_MATCH;
-
- if (matchName && !matchesName(this.pattern.name, field.readableName())) return IMPOSSIBLE_MATCH;
-
- FieldPattern fieldPattern = (FieldPattern)this.pattern;
- ReferenceBinding receiverBinding = field.declaringClass;
- if (receiverBinding == null) {
- if (field == ArrayBinding.ArrayLength)
- // optimized case for length field of an array
- return fieldPattern.declaringQualification == null && fieldPattern.declaringSimpleName == 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);
- if (declaringLevel == IMPOSSIBLE_MATCH) return IMPOSSIBLE_MATCH;
-
- // look at field type only if declaring type is not specified
- if (fieldPattern.declaringSimpleName == null) return declaringLevel;
-
- // get real field binding
- FieldBinding fieldBinding = field;
-
- int typeLevel = resolveLevelForType(fieldBinding.type);
- return declaringLevel > typeLevel ? typeLevel : declaringLevel; // return the weaker match
-}
-
-protected int matchLocalVariable(LocalVariableBinding variable, boolean matchName) {
- if (variable == null) return INACCURATE_MATCH;
-
- if (matchName && !matchesName(this.pattern.name, variable.readableName())) return IMPOSSIBLE_MATCH;
-
- return ACCURATE_MATCH;
-}
-
-/* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.core.search.matching.PatternLocator#matchLevelAndReportImportRef(org.eclipse.wst.jsdt.internal.compiler.ast.ImportReference, org.eclipse.wst.jsdt.internal.compiler.lookup.Binding, org.eclipse.wst.jsdt.internal.core.search.matching.MatchLocator)
- * Accept to report match of static field on static import
- */
-protected void matchLevelAndReportImportRef(ImportReference importRef, Binding binding, MatchLocator locator) throws CoreException {
-}
-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);
- return IMPOSSIBLE_MATCH;
- }
- return super.matchReference(node, nodeSet, writeOnlyAccess);
-}
-protected void matchReportReference(ASTNode reference, IJavaScriptElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException {
- if (this.isDeclarationOfAccessedFieldsPattern) {
- // need exact match to be able to open on type ref
- if (accuracy != SearchMatch.A_ACCURATE) return;
-
- // element that references the field must be included in the enclosing element
- DeclarationOfAccessedFieldsPattern declPattern = (DeclarationOfAccessedFieldsPattern) this.pattern;
- while (element != null && !declPattern.enclosingElement.equals(element))
- element = element.getParent();
- if (element != null) {
- if (reference instanceof FieldReference) {
- reportDeclaration(((FieldReference) reference).binding, locator, declPattern.knownFields);
- } else if (reference instanceof QualifiedNameReference) {
- QualifiedNameReference qNameRef = (QualifiedNameReference) reference;
- Binding nameBinding = qNameRef.binding;
- if (nameBinding instanceof FieldBinding)
- reportDeclaration((FieldBinding)nameBinding, locator, declPattern.knownFields);
- int otherMax = qNameRef.otherBindings == null ? 0 : qNameRef.otherBindings.length;
- for (int i = 0; i < otherMax; i++)
- reportDeclaration(qNameRef.otherBindings[i], locator, declPattern.knownFields);
- } else if (reference instanceof SingleNameReference) {
- reportDeclaration((FieldBinding)((SingleNameReference) reference).binding, locator, declPattern.knownFields);
- }
- }
- } else if (reference instanceof ImportReference) {
- ImportReference importRef = (ImportReference) reference;
- long[] positions = importRef.sourcePositions;
- int lastIndex = importRef.tokens.length - 1;
- int start = (int) ((positions[lastIndex]) >>> 32);
- int end = (int) positions[lastIndex];
- match = locator.newFieldReferenceMatch(element, elementBinding, accuracy, start, end-start+1, importRef);
- locator.report(match);
- } else if (reference instanceof FieldReference) {
- FieldReference fieldReference = (FieldReference) reference;
- long position = fieldReference.nameSourcePosition;
- int start = (int) (position >>> 32);
- int end = (int) position;
- match = locator.newFieldReferenceMatch(element, elementBinding, accuracy, start, end-start+1, fieldReference);
- locator.report(match);
- } else if (reference instanceof SingleNameReference) {
- int offset = reference.sourceStart;
- match = locator.newFieldReferenceMatch(element, elementBinding, accuracy, offset, reference.sourceEnd-offset+1, reference);
- locator.report(match);
- } else if (reference instanceof QualifiedNameReference) {
- QualifiedNameReference qNameRef = (QualifiedNameReference) reference;
- int length = qNameRef.tokens.length;
- SearchMatch[] matches = new SearchMatch[length];
- Binding nameBinding = qNameRef.binding;
- int indexOfFirstFieldBinding = qNameRef.indexOfFirstFieldBinding > 0 ? qNameRef.indexOfFirstFieldBinding-1 : 0;
-
- // first token
- if (matchesName(this.pattern.name, qNameRef.tokens[indexOfFirstFieldBinding]) && !(nameBinding instanceof LocalVariableBinding)) {
- FieldBinding fieldBinding = nameBinding instanceof FieldBinding ? (FieldBinding) nameBinding : null;
- if (fieldBinding == null) {
- matches[indexOfFirstFieldBinding] = locator.newFieldReferenceMatch(element, elementBinding, accuracy, -1, -1, reference);
- } else {
- switch (matchField(fieldBinding, false)) {
- case ACCURATE_MATCH:
- matches[indexOfFirstFieldBinding] = locator.newFieldReferenceMatch(element, elementBinding, SearchMatch.A_ACCURATE, -1, -1, reference);
- break;
- case INACCURATE_MATCH:
- match = locator.newFieldReferenceMatch(element, elementBinding, SearchMatch.A_INACCURATE, -1, -1, reference);
- matches[indexOfFirstFieldBinding] = match;
- break;
- }
- }
- }
-
- // other tokens
- for (int i = indexOfFirstFieldBinding+1; i < length; i++) {
- char[] token = qNameRef.tokens[i];
- if (matchesName(this.pattern.name, token)) {
- FieldBinding otherBinding = qNameRef.otherBindings == null ? null : qNameRef.otherBindings[i-(indexOfFirstFieldBinding+1)];
- if (otherBinding == null) {
- matches[i] = locator.newFieldReferenceMatch(element, elementBinding, accuracy, -1, -1, reference);
- } else {
- switch (matchField(otherBinding, false)) {
- case ACCURATE_MATCH:
- matches[i] = locator.newFieldReferenceMatch(element, elementBinding, SearchMatch.A_ACCURATE, -1, -1, reference);
- break;
- case INACCURATE_MATCH:
- match = locator.newFieldReferenceMatch(element, elementBinding, SearchMatch.A_INACCURATE, -1, -1, reference);
- matches[i] = match;
- break;
- }
- }
- }
- }
- locator.reportAccurateFieldReference(matches, qNameRef);
- }
-}
-/* (non-Javadoc)
- * Overridden to reject unexact matches.
- * @see org.eclipse.wst.jsdt.internal.core.search.matching.PatternLocator#updateMatch(org.eclipse.wst.jsdt.internal.compiler.lookup.ParameterizedTypeBinding, char[][][], org.eclipse.wst.jsdt.internal.core.search.matching.MatchLocator)
- *
- */
-protected void updateMatch(char[][][] patternTypeArguments, MatchLocator locator) {
- // We can only refine if locator has an unit scope.
- if (locator.unitScope == null) return;
- if (!match.isExact()) {
- // cannot accept neither erasure nor compatible match
- match.setRule(0);
- }
-}
-protected void reportDeclaration(FieldBinding fieldBinding, MatchLocator locator, SimpleSet knownFields) throws CoreException {
- // ignore length field
- if (fieldBinding == ArrayBinding.ArrayLength) return;
-
- ReferenceBinding declaringClass = fieldBinding.declaringClass;
- IType type = locator.lookupType(declaringClass);
- if (type == null) return; // case of a secondary type
-
- char[] bindingName = fieldBinding.name;
- IField field = type.getField(new String(bindingName));
- if (knownFields.addIfNotIncluded(field)==null) return;
-
- IResource resource = type.getResource();
- boolean isBinary = type.isBinary();
- IBinaryType info = null;
- if (isBinary) {
- if (resource == null)
- resource = type.getJavaScriptProject().getProject();
- info = locator.getBinaryInfo((org.eclipse.wst.jsdt.internal.core.ClassFile) type.getClassFile(), resource);
- locator.reportBinaryMemberDeclaration(resource, field, fieldBinding, info, SearchMatch.A_ACCURATE);
- } else {
- Scope scp = ((SourceTypeBinding) declaringClass).scope;
- if (scp instanceof ClassScope) {
- ClassScope scope=(ClassScope)scp;
- TypeDeclaration typeDecl = scope.referenceContext;
- if (typeDecl!=null) {
- FieldDeclaration fieldDecl = null;
- FieldDeclaration[] fieldDecls = typeDecl.fields;
- for (int i = 0, length = fieldDecls.length; i < length; i++) {
- if (CharOperation.equals(bindingName, fieldDecls[i].name)) {
- fieldDecl = fieldDecls[i];
- break;
- }
- }
- if (fieldDecl != null) {
- int offset = fieldDecl.sourceStart;
- match = new FieldDeclarationMatch(((JavaElement) field)
- .resolved(fieldBinding), SearchMatch.A_ACCURATE,
- offset, fieldDecl.sourceEnd - offset + 1, locator
- .getParticipant(), resource);
- locator.report(match);
- }
- } else if (scope.inferredType!=null)
- {
- InferredAttribute attribute=null;
- for (int attributeInx=0; attributeInx<scope.inferredType.numberAttributes; attributeInx++) {
- InferredAttribute element = scope.inferredType.attributes[attributeInx];
- if (CharOperation.equals(bindingName, element.name)) {
- attribute =element;
- break;
- }
-
- }
- if (attribute != null) {
- int offset = attribute.sourceStart;
- match = new FieldDeclarationMatch(((JavaElement) field)
- .resolved(fieldBinding), SearchMatch.A_ACCURATE,
- offset, attribute.sourceEnd - offset + 1, locator
- .getParticipant(), resource);
- locator.report(match);
- }
-
- }
-
- }
- else if (scp !=null)
- //TODO: could be compilation unit scope
- throw new org.eclipse.wst.jsdt.core.UnimplementedException();
- }
-}
-protected int referenceType() {
- return IJavaScriptElement.FIELD;
-}
-public int resolveLevel(ASTNode possiblelMatchingNode) {
- if (this.pattern.findReferences) {
- if (possiblelMatchingNode instanceof FieldReference)
- if (!this.fieldPattern.isVar)
- return matchField(((FieldReference) possiblelMatchingNode).binding, true);
- else return IMPOSSIBLE_MATCH;
- else if (possiblelMatchingNode instanceof NameReference)
- return resolveLevel((NameReference) possiblelMatchingNode);
- }
- if (possiblelMatchingNode instanceof FieldDeclaration)
- return matchField(((FieldDeclaration) possiblelMatchingNode).binding, true);
- else if (possiblelMatchingNode instanceof LocalDeclaration)
- return matchLocalVariable(((LocalDeclaration) possiblelMatchingNode).binding, true);
- return IMPOSSIBLE_MATCH;
-}
-public int resolveLevel(Binding binding) {
- if (binding == null) return INACCURATE_MATCH;
- if (fieldPattern.isVar)
- {
- if (!(binding instanceof LocalVariableBinding)) return IMPOSSIBLE_MATCH;
- LocalVariableBinding localVariableBinding=(LocalVariableBinding) binding;
- if (localVariableBinding.declaringScope.kind!=Scope.COMPILATION_UNIT_SCOPE)
- return IMPOSSIBLE_MATCH;
- return matchLocalVariable((LocalVariableBinding) binding, true);
- }
- else
- {
- if (!(binding instanceof FieldBinding)) return IMPOSSIBLE_MATCH;
-
- return matchField((FieldBinding) binding, true);
-
- }
-}
-protected int resolveLevel(NameReference nameRef) {
- if (nameRef instanceof SingleNameReference)
- return resolveLevel(nameRef.binding);
-
- Binding binding = nameRef.binding;
- QualifiedNameReference qNameRef = (QualifiedNameReference) nameRef;
- FieldBinding fieldBinding = null;
- if (binding instanceof FieldBinding) {
- fieldBinding = (FieldBinding) binding;
- char[] bindingName = fieldBinding.name;
- int lastDot = CharOperation.lastIndexOf('.', bindingName);
- if (lastDot > -1)
- bindingName = CharOperation.subarray(bindingName, lastDot+1, bindingName.length);
- if (matchesName(this.pattern.name, bindingName)) {
- int level = matchField(fieldBinding, false);
- if (level != IMPOSSIBLE_MATCH) return level;
- }
- }
- int otherMax = qNameRef.otherBindings == null ? 0 : qNameRef.otherBindings.length;
- for (int i = 0; i < otherMax; i++) {
- char[] token = qNameRef.tokens[i + qNameRef.indexOfFirstFieldBinding];
- if (matchesName(this.pattern.name, token)) {
- FieldBinding otherBinding = qNameRef.otherBindings[i];
- int level = matchField(otherBinding, false);
- if (level != IMPOSSIBLE_MATCH) return level;
- }
- }
- return IMPOSSIBLE_MATCH;
-}
-/* (non-Javadoc)
- * Resolve level for type with a given binding.
- */
-protected int resolveLevelForType(TypeBinding typeBinding) {
- FieldPattern fieldPattern = (FieldPattern) this.pattern;
- TypeBinding fieldTypeBinding = typeBinding;
- return resolveLevelForType(
- fieldPattern.typeSimpleName,
- fieldPattern.typeQualification,
- fieldPattern.getTypeArguments(),
- 0,
- fieldTypeBinding);
-}
-
-public int matchLocalDeclaration(LocalDeclaration node, MatchingNodeSet nodeSet) {
- int referencesLevel = IMPOSSIBLE_MATCH;
- if (this.pattern.findReferences)
- // must be a write only access with an initializer
- if (this.pattern.writeAccess && !this.pattern.readAccess && node.initialization != null)
- if (matchesName(this.pattern.name, node.name))
- referencesLevel = ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH;
-
- int declarationsLevel = IMPOSSIBLE_MATCH;
- if (this.pattern.findDeclarations)
- if (matchesName(this.pattern.name, node.name))
- declarationsLevel = ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH;
-
- return nodeSet.addMatch(node, referencesLevel >= declarationsLevel ? referencesLevel : declarationsLevel); // use the stronger match
-}
-}
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
deleted file mode 100644
index 95fc070c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/FieldPattern.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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.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;
-
-public class FieldPattern extends VariablePattern {
-
-// 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);
-
- // store type signatures and arguments
- if (typeSignature != null) {
- this.typeSignatures = Util.splitTypeLevelsSignature(typeSignature);
- setTypeArguments(Util.getAllTypeArguments(this.typeSignatures));
- }
-}
-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() {
-
- 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;
- }
- else {
- 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;
-}
-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/InternalSearchPattern.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/InternalSearchPattern.java
deleted file mode 100644
index e97402e7..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/InternalSearchPattern.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*******************************************************************************
- * 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.search.matching;
-
-import java.io.IOException;
-
-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.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchParticipant;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.compiler.env.AccessRuleSet;
-import org.eclipse.wst.jsdt.internal.compiler.util.Util;
-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.IndexQueryRequestor;
-import org.eclipse.wst.jsdt.internal.core.search.JavaSearchScope;
-
-/**
- * Internal search pattern implementation
- */
-public abstract class InternalSearchPattern {
-
- /**
- * The focus element (used for reference patterns)
- */
- IJavaScriptElement focus;
-
- int kind;
- boolean mustResolve = true;
-
- void acceptMatch(String relativePath, String containerPath, SearchPattern pattern, IndexQueryRequestor requestor, SearchParticipant participant, IJavaScriptSearchScope scope) {
-
- if (scope instanceof JavaSearchScope) {
- JavaSearchScope javaSearchScope = (JavaSearchScope) scope;
- // Get document path access restriction from java search scope
- // Note that requestor has to verify if needed whether the document violates the access restriction or not
- AccessRuleSet access = javaSearchScope.getAccessRuleSet(relativePath, containerPath);
- if (access != JavaSearchScope.NOT_ENCLOSED) { // scope encloses the document path
- String documentPath = documentPath(containerPath, relativePath);
- if (!requestor.acceptIndexMatch(documentPath, pattern, participant, access))
- throw new OperationCanceledException();
- }
- } else {
- String documentPath = documentPath(containerPath, relativePath);
- if (scope.encloses(documentPath))
- if (!requestor.acceptIndexMatch(documentPath, pattern, participant, null))
- throw new OperationCanceledException();
-
- }
- }
- SearchPattern currentPattern() {
- return (SearchPattern) this;
- }
- String documentPath(String containerPath, String relativePath) {
- /* For some library entries containerPath == relativePath */
-
- if(containerPath!=null && relativePath!=null) {
- IPath container = new Path(containerPath);
- IPath relative = new Path(relativePath);
- if(container.makeAbsolute() . equals(relative.makeAbsolute())) {
- return relativePath;
- }
- }
-
- String separator = Util.isArchiveFileName(containerPath) ? IJavaScriptSearchScope.JAR_FILE_ENTRY_SEPARATOR : "/"; //$NON-NLS-1$
- StringBuffer buffer = new StringBuffer(containerPath.length() + separator.length() + relativePath.length());
- buffer.append(new Path(containerPath).toString());
- buffer.append(separator);
- buffer.append(new Path(relativePath).toString());
- return buffer.toString();
- }
- /**
- * Query a given index for matching entries. Assumes the sender has opened the index and will close when finished.
- */
- public void findIndexMatches(Index index, IndexQueryRequestor requestor, SearchParticipant participant, IJavaScriptSearchScope scope, IProgressMonitor monitor) throws IOException {
- if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException();
- try {
- index.startQuery();
- SearchPattern pattern = currentPattern();
- EntryResult[] entries = ((InternalSearchPattern)pattern).queryIn(index);
- if (entries == null) return;
-
- SearchPattern decodedResult = pattern.getBlankPattern();
- String containerPath = index.containerPath;
- for (int i = 0, l = entries.length; i < l; i++) {
- if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException();
-
- EntryResult entry = entries[i];
- decodedResult.decodeIndexKey(entry.getWord());
- if (pattern.matchesDecodedKey(decodedResult)) {
- // TODO (kent) some clients may not need the document names
- String[] names = entry.getDocumentNames(index);
- for (int j = 0, n = names.length; j < n; j++) {
- if(!scope.shouldExclude(containerPath, names[j]))
- acceptMatch(names[j], containerPath, decodedResult, requestor, participant, scope);
-
- }
- }
- }
- } finally {
- index.stopQuery();
- }
- }
- boolean isPolymorphicSearch() {
- return false;
- }
- EntryResult[] queryIn(Index index) throws IOException {
- SearchPattern pattern = (SearchPattern) this;
- return index.query(pattern.getIndexCategories(), pattern.getIndexKey(), pattern.getMatchRule());
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/JavaSearchNameEnvironment.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/JavaSearchNameEnvironment.java
deleted file mode 100644
index 64b24659..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/JavaSearchNameEnvironment.java
+++ /dev/null
@@ -1,202 +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 java.util.HashMap;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-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.NameEnvironmentAnswer;
-import org.eclipse.wst.jsdt.internal.compiler.impl.ITypeRequestor;
-import org.eclipse.wst.jsdt.internal.compiler.util.SuffixConstants;
-import org.eclipse.wst.jsdt.internal.core.ClasspathEntry;
-import org.eclipse.wst.jsdt.internal.core.JavaModel;
-import org.eclipse.wst.jsdt.internal.core.JavaProject;
-import org.eclipse.wst.jsdt.internal.core.PackageFragmentRoot;
-import org.eclipse.wst.jsdt.internal.core.builder.ClasspathLocation;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/*
- * A name environment based on the classpath of a Java project.
- */
-public class JavaSearchNameEnvironment implements INameEnvironment, SuffixConstants {
-
- ClasspathLocation[] locations;
-
- /*
- * A map from the fully qualified slash-separated name of the main type (String) to the working copy
- */
- HashMap workingCopies;
-
-public JavaSearchNameEnvironment(IJavaScriptProject javaProject, org.eclipse.wst.jsdt.core.IJavaScriptUnit[] copies) {
- computeClasspathLocations(javaProject.getProject().getWorkspace().getRoot(), (JavaProject) javaProject);
-
- int length = copies == null ? 0 : copies.length;
- this.workingCopies = new HashMap(length);
- if (copies != null) {
- for (int i = 0; i < length; i++) {
- org.eclipse.wst.jsdt.core.IJavaScriptUnit workingCopy = copies[i];
- String pkg = ""; //$NON-NLS-1$
- String cuName = workingCopy.getElementName();
- String mainTypeName = Util.getNameWithoutJavaLikeExtension(cuName);
- String qualifiedMainTypeName = pkg.length() == 0 ? mainTypeName : pkg.replace('.', '/') + '/' + mainTypeName;
- this.workingCopies.put(qualifiedMainTypeName, workingCopy);
- }
- }
-}
-
-public void cleanup() {
- for (int i = 0, length = this.locations.length; i < length; i++) {
- this.locations[i].cleanup();
- }
-}
-
-private void computeClasspathLocations(IWorkspaceRoot workspaceRoot, JavaProject javaProject) {
-
- IPackageFragmentRoot[] roots = null;
- try {
- roots = javaProject.getAllPackageFragmentRoots();
- } catch (JavaScriptModelException e) {
- // project doesn't exist
- this.locations = new ClasspathLocation[0];
- return;
- }
- int length = roots.length;
- ClasspathLocation[] cpLocations = new ClasspathLocation[length];
- int index = 0;
- for (int i = 0; i < length; i++) {
- PackageFragmentRoot root = (PackageFragmentRoot) roots[i];
- IPath path = root.getPath();
- try {
- Object target = JavaModel.getTarget(workspaceRoot, path, false);
- if (target == null) {
- // target doesn't exist any longer
- // just resize cpLocations
- System.arraycopy(cpLocations, 0, cpLocations = new ClasspathLocation[cpLocations.length-1], 0, index);
- } else if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
- cpLocations[index++] = new ClasspathSourceDirectory((IContainer)target, root.fullExclusionPatternChars(), root.fullInclusionPatternChars());
- } else if (target instanceof IContainer){
- cpLocations[index++] = ClasspathLocation.forBinaryFolder((IContainer) target, false, ((ClasspathEntry) root.getRawIncludepathEntry()).getAccessRuleSet());
- }
- else
- cpLocations[index++] = ClasspathLocation.forLibrary(path.toOSString(), ((ClasspathEntry) root.getRawIncludepathEntry()).getAccessRuleSet());
-
- } catch (CoreException e1) {
- // problem opening zip file or getting root kind
- // consider root corrupt and ignore
- // just resize cpLocations
- System.arraycopy(cpLocations, 0, cpLocations = new ClasspathLocation[cpLocations.length-1], 0, index);
- }
- }
- this.locations = cpLocations;
-}
-
-private NameEnvironmentAnswer findClass(String qualifiedTypeName, char[] typeName) {
- String
- binaryFileName = null, qBinaryFileName = null,
- sourceFileName = null, qSourceFileName = null,
- qPackageName = null;
- NameEnvironmentAnswer suggestedAnswer = null;
- for (int i = 0, length = this.locations.length; i < length; i++) {
- ClasspathLocation location = this.locations[i];
- NameEnvironmentAnswer answer;
- if (location instanceof ClasspathSourceDirectory) {
- if (sourceFileName == null) {
- qSourceFileName = qualifiedTypeName; // doesn't include the file extension
- sourceFileName = qSourceFileName;
- qPackageName = ""; //$NON-NLS-1$
- if (qualifiedTypeName.length() > typeName.length) {
- int typeNameStart = qSourceFileName.length() - typeName.length;
- qPackageName = qSourceFileName.substring(0, typeNameStart - 1);
- sourceFileName = qSourceFileName.substring(typeNameStart);
- }
- }
- ICompilationUnit workingCopy = (ICompilationUnit) this.workingCopies.get(qualifiedTypeName);
- if (workingCopy != null) {
- answer = new NameEnvironmentAnswer(workingCopy, null /*no access restriction*/);
- } else {
- answer = location.findClass(
- sourceFileName, // doesn't include the file extension
- qPackageName,
- qSourceFileName); // doesn't include the file extension
- }
- } else {
- if (binaryFileName == null) {
- qBinaryFileName = qualifiedTypeName + SUFFIX_STRING_java;
- binaryFileName = qBinaryFileName;
- qPackageName = ""; //$NON-NLS-1$
- if (qualifiedTypeName.length() > typeName.length) {
- int typeNameStart = qBinaryFileName.length() - typeName.length - 6; // size of ".class"
- qPackageName = qBinaryFileName.substring(0, typeNameStart - 1);
- binaryFileName = qBinaryFileName.substring(typeNameStart);
- }
- }
- answer =
- location.findClass(
- binaryFileName,
- qPackageName,
- qBinaryFileName);
- }
- if (answer != null) {
- if (!answer.ignoreIfBetter()) {
- if (answer.isBetter(suggestedAnswer))
- return answer;
- } else if (answer.isBetter(suggestedAnswer))
- // remember suggestion and keep looking
- suggestedAnswer = answer;
- }
- }
- if (suggestedAnswer != null)
- // no better answer was found
- return suggestedAnswer;
- return null;
-}
-public NameEnvironmentAnswer findBinding(char[] typeName, char[][] packageName, int type, ITypeRequestor requestor, boolean returnMultiple, String excludePath) {
- //TODO: implement
- throw new org.eclipse.wst.jsdt.core.UnimplementedException();
-// return findType(typeName,packageName);
-}
-public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName, ITypeRequestor requestor) {
- if (typeName != null)
- return findClass(
- new String(CharOperation.concatWith(packageName, typeName, '/')),
- typeName);
- return null;
-}
-
-public NameEnvironmentAnswer findType(char[][] compoundName, ITypeRequestor requestor) {
- if (compoundName != null)
- return findClass(
- new String(CharOperation.concatWith(compoundName, '/')),
- compoundName[compoundName.length - 1]);
- return null;
-}
-
-public boolean isPackage(char[][] compoundName, char[] packageName) {
- return isPackage(new String(CharOperation.concatWith(compoundName, packageName, '/')));
-}
-
-public boolean isPackage(String qualifiedPackageName) {
- for (int i = 0, length = this.locations.length; i < length; i++)
- if (this.locations[i].isPackage(qualifiedPackageName))
- return true;
- return false;
-}
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/JavaSearchPattern.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/JavaSearchPattern.java
deleted file mode 100644
index 1e286d0c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/JavaSearchPattern.java
+++ /dev/null
@@ -1,245 +0,0 @@
-/*******************************************************************************
- * 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
- * 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.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.core.search.indexing.IIndexConstants;
-
-
-public class JavaSearchPattern extends SearchPattern implements IIndexConstants {
-
- /*
- * Whether this pattern is case sensitive.
- */
- boolean isCaseSensitive;
-
- /*
- * Whether this pattern is camel case.
- */
- boolean isCamelCase;
-
- /**
- * One of following pattern value:
- * <ul>
- * <li>{@link #R_EXACT_MATCH}</li>
- * <li>{@link #R_PREFIX_MATCH}</li>
- * <li>{@link #R_PATTERN_MATCH}</li>
- * <li>{@link #R_REGEXP_MATCH}</li>
- * <li>{@link #R_CAMELCASE_MATCH}</li>
- * </ul>
- */
- int matchMode;
-
- /**
- * One of {@link #R_ERASURE_MATCH}, {@link #R_EQUIVALENT_MATCH}, {@link #R_FULL_MATCH}.
- */
- int matchCompatibility;
-
- /**
- * Mask used on match rule for match mode.
- */
- public static final int MATCH_MODE_MASK = R_EXACT_MATCH | R_PREFIX_MATCH | R_PATTERN_MATCH | R_REGEXP_MATCH;
-
- /**
- * Mask used on match rule for generic relevance.
- */
- public static final int MATCH_COMPATIBILITY_MASK = R_ERASURE_MATCH | R_EQUIVALENT_MATCH | R_FULL_MATCH;
-
- // Signatures and arguments for parameterized types search
- char[][] typeSignatures;
- private char[][][] typeArguments;
- private int flags = 0;
- static final int HAS_TYPE_ARGUMENTS = 1;
-
- protected JavaSearchPattern(int patternKind, int matchRule) {
- super(matchRule);
- ((InternalSearchPattern)this).kind = patternKind;
- // Use getMatchRule() instead of matchRule as super constructor may modify its value
- // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=81377
- int rule = getMatchRule();
- this.isCaseSensitive = (rule & R_CASE_SENSITIVE) != 0;
- this.isCamelCase = (rule & R_CAMELCASE_MATCH) != 0;
- this.matchCompatibility = rule & MATCH_COMPATIBILITY_MASK;
- this.matchMode = rule & MATCH_MODE_MASK;
- }
-
- public SearchPattern getBlankPattern() {
- return null;
- }
-
- int getMatchMode() {
- return this.matchMode;
- }
-
- boolean isCamelCase() {
- return this.isCamelCase;
- }
-
- boolean isCaseSensitive () {
- return this.isCaseSensitive;
- }
-
- boolean isErasureMatch() {
- return (this.matchCompatibility & R_ERASURE_MATCH) != 0;
- }
-
- boolean isEquivalentMatch() {
- return (this.matchCompatibility & R_EQUIVALENT_MATCH) != 0;
- }
-
- /*
- * Extract method arguments using unique key for parameterized methods
- * and type parameters for non-generic ones.
- */
- char[][] extractMethodArguments(IFunction method) {
- return null;
- }
-
- /**
- * @return Returns the typeArguments.
- */
- final char[][][] getTypeArguments() {
- return typeArguments;
- }
-
- /**
- * Returns whether the pattern has signatures or not.
- * If pattern {@link #typeArguments} field, this field shows that it was built
- * on a generic source type.
- * @return true if {@link #typeSignatures} field is not null and has a length greater than 0.
- */
- public final boolean hasSignatures() {
- return this.typeSignatures != null && this.typeSignatures.length > 0;
- }
-
- /**
- * Returns whether the pattern includes type arguments information or not.
- * @return default is false
- */
- public final boolean hasTypeArguments() {
- return (this.flags & HAS_TYPE_ARGUMENTS) != 0;
- }
-
- /**
- * Returns whether the pattern includes type parameters information or not.
- * @return true if {@link #typeArguments} contains type parameters instead
- * type arguments signatures.
- */
- public final boolean hasTypeParameters() {
- return !hasSignatures() && hasTypeArguments();
- }
-
- /**
- * Return whether two suffixes are compatible.
- *
- * Note that obvious compatibility values as equals and {@link IIndexConstants#TYPE_SUFFIX}
- * has to be tested by caller to avoid unnecessary method call...
- *
- * @param typeSuffix
- * @param patternSuffix
- * @return true if suffixes are compatible, false otherwise
- */
- boolean matchDifferentTypeSuffixes(int typeSuffix, int patternSuffix) {
- switch(typeSuffix) {
- case CLASS_SUFFIX :
- return false;
- }
-
- // Default behavior is to match suffixes
- return true;
- }
-
- protected StringBuffer print(StringBuffer output) {
- output.append(", "); //$NON-NLS-1$
- if (hasTypeArguments() && hasSignatures()) {
- output.append("signature:\""); //$NON-NLS-1$
- output.append(this.typeSignatures[0]);
- output.append("\", "); //$NON-NLS-1$
- }
- if (this.isCamelCase) {
- output.append("camel case + "); //$NON-NLS-1$
- }
- switch(getMatchMode()) {
- case R_EXACT_MATCH :
- output.append("exact match,"); //$NON-NLS-1$
- break;
- case R_PREFIX_MATCH :
- output.append("prefix match,"); //$NON-NLS-1$
- break;
- case R_PATTERN_MATCH :
- output.append("pattern match,"); //$NON-NLS-1$
- break;
- case R_REGEXP_MATCH :
- output.append("regexp match, "); //$NON-NLS-1$
- break;
- }
- if (isCaseSensitive())
- output.append(" case sensitive"); //$NON-NLS-1$
- else
- output.append(" case insensitive"); //$NON-NLS-1$
- if ((this.matchCompatibility & R_ERASURE_MATCH) != 0) {
- output.append(", erasure only"); //$NON-NLS-1$
- }
- if ((this.matchCompatibility & R_EQUIVALENT_MATCH) != 0) {
- output.append(", equivalent oronly"); //$NON-NLS-1$
- }
- return output;
- }
- /**
- * @param typeArguments The typeArguments to set.
- */
- final void setTypeArguments(char[][][] typeArguments) {
- this.typeArguments = typeArguments;
- // update flags
- if (this.typeArguments != null) {
- int length = this.typeArguments.length;
- for (int i=0; i<length; i++) {
- if (this.typeArguments[i] != null && this.typeArguments[i].length > 0) {
- this.flags |= HAS_TYPE_ARGUMENTS;
- break;
- }
- }
- }
- }
-
- /*
- * Extract and store type signatures and arguments using unique key for parameterized types
- * and type parameters for non-generic ones
- */
- void storeTypeSignaturesAndArguments(IType type) {
- // Scan hierachy to store type arguments at each level
- char[][][] typeParameters = new char[10][][];
- int ptr = -1;
- boolean hasParameters = false;
- IJavaScriptElement parent = type;
- while (parent != null && parent.getElementType() == IJavaScriptElement.TYPE) {
- if (++ptr > typeParameters.length) {
- System.arraycopy(typeParameters, 0, typeParameters = new char[typeParameters.length+10][][], 0, ptr);
- }
- parent = parent.getParent();
- }
-
- // Store type arguments if any
- if (hasParameters) {
- if (++ptr < typeParameters.length)
- System.arraycopy(typeParameters, 0, typeParameters = new char[ptr][][], 0, ptr);
- setTypeArguments(typeParameters);
- }
-
- }
-
- public final String toString() {
- return print(new StringBuffer(30)).toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/LocalVariableLocator.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/LocalVariableLocator.java
deleted file mode 100644
index f3817d08..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/LocalVariableLocator.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*******************************************************************************
- * 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.matching;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode;
-import org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.NameReference;
-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.lookup.Binding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.LocalVariableBinding;
-import org.eclipse.wst.jsdt.internal.core.LocalVariable;
-
-public class LocalVariableLocator extends VariableLocator {
-
-public LocalVariableLocator(VariablePattern pattern) {
- super(pattern);
-}
-public int match(LocalDeclaration node, MatchingNodeSet nodeSet) {
- int referencesLevel = IMPOSSIBLE_MATCH;
- if (this.pattern.findReferences)
- // must be a write only access with an initializer
- if (this.pattern.writeAccess && !this.pattern.readAccess && node.initialization != null)
- if (matchesName(this.pattern.name, node.name))
- referencesLevel = ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH;
-
- int declarationsLevel = IMPOSSIBLE_MATCH;
- if (this.pattern.findDeclarations)
- if (matchesName(this.pattern.name, node.name))
- if (node.declarationSourceStart == this.pattern.getVariableStart())
- declarationsLevel = ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH;
-
- return nodeSet.addMatch(node, referencesLevel >= declarationsLevel ? referencesLevel : declarationsLevel); // use the stronger match
-}
-
-//private LocalVariable getLocalVariable() {
-// return ((LocalVariablePattern) this.pattern).localVariable;
-//}
-
-
-protected void matchReportReference(ASTNode reference, IJavaScriptElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException {
- int offset = -1;
- int length = -1;
- if (reference instanceof SingleNameReference) {
- offset = reference.sourceStart;
- length = reference.sourceEnd-offset+1;
- } else if (reference instanceof QualifiedNameReference) {
- QualifiedNameReference qNameRef = (QualifiedNameReference) reference;
- long sourcePosition = qNameRef.sourcePositions[0];
- offset = (int) (sourcePosition >>> 32);
- length = ((int) sourcePosition) - offset +1;
- } else if (reference instanceof LocalDeclaration) {
- element = this.pattern.getJavaElement();
- if (element instanceof LocalVariable)
- {
- LocalVariable localVariable = (LocalVariable)element;
- offset = localVariable.nameStart;
- length = localVariable.nameEnd-offset+1;
- }
- else
- {
- offset=this.pattern.getVariableStart();
- length=this.pattern.getVariableLength();
- }
- }
- if (offset >= 0) {
- match = locator.newLocalVariableReferenceMatch(element, accuracy, offset, length, reference);
- locator.report(match);
- }
-}
-protected int matchContainer() {
- return METHOD_CONTAINER;
-}
-protected int matchLocalVariable(LocalVariableBinding variable, boolean matchName) {
- if (variable == null) return INACCURATE_MATCH;
-
- if (matchName && !matchesName(this.pattern.name, variable.readableName())) return IMPOSSIBLE_MATCH;
-
- return variable.declaration.declarationSourceStart ==this.pattern.getVariableStart()
- ? ACCURATE_MATCH
- : IMPOSSIBLE_MATCH;
-}
-protected int referenceType() {
- return IJavaScriptElement.LOCAL_VARIABLE;
-}
-public int resolveLevel(ASTNode possiblelMatchingNode) {
- if (this.pattern.findReferences)
- if (possiblelMatchingNode instanceof NameReference)
- return resolveLevel((NameReference) possiblelMatchingNode);
- if (possiblelMatchingNode instanceof LocalDeclaration)
- return matchLocalVariable(((LocalDeclaration) possiblelMatchingNode).binding, true);
- return IMPOSSIBLE_MATCH;
-}
-public int resolveLevel(Binding binding) {
- if (binding == null) return INACCURATE_MATCH;
- if (!(binding instanceof LocalVariableBinding)) return IMPOSSIBLE_MATCH;
-
- return matchLocalVariable((LocalVariableBinding) binding, true);
-}
-protected int resolveLevel(NameReference nameRef) {
- return resolveLevel(nameRef.binding);
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/LocalVariablePattern.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/LocalVariablePattern.java
deleted file mode 100644
index 65355ae6..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/LocalVariablePattern.java
+++ /dev/null
@@ -1,115 +0,0 @@
-/*******************************************************************************
- * 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.matching;
-
-import java.io.IOException;
-
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchParticipant;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.compiler.env.AccessRuleSet;
-import org.eclipse.wst.jsdt.internal.core.LocalVariable;
-import org.eclipse.wst.jsdt.internal.core.index.Index;
-import org.eclipse.wst.jsdt.internal.core.search.IndexQueryRequestor;
-import org.eclipse.wst.jsdt.internal.core.search.JavaSearchScope;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-public class LocalVariablePattern extends VariablePattern {
-
-LocalVariable localVariable;
-
-
-public LocalVariablePattern(boolean findDeclarations, boolean readAccess, boolean writeAccess, LocalVariable localVariable, int matchRule) {
- super(LOCAL_VAR_PATTERN, findDeclarations, readAccess, writeAccess, localVariable.getElementName().toCharArray(), matchRule,localVariable);
- this.localVariable=localVariable;
-}
-
-
-public LocalVariablePattern(boolean findDeclarations, boolean readAccess, boolean writeAccess,char [] name, int matchRule) {
- super(LOCAL_VAR_PATTERN, findDeclarations, readAccess, writeAccess,name, matchRule,null);
-}
-
-
-public void findIndexMatches(Index index, IndexQueryRequestor requestor, SearchParticipant participant, IJavaScriptSearchScope scope, IProgressMonitor progressMonitor) throws IOException {
- if (this.localVariable!=null)
- {
-
-// IPackageFragmentRoot root = (IPackageFragmentRoot)this.localVariable.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- String documentPath;
- String relativePath;
-// if (root.isArchive()) {
-// IType type = (IType)this.localVariable.getAncestor(IJavaScriptElement.TYPE);
-// relativePath = (type.getFullyQualifiedName('/')).replace('.', '/') + SuffixConstants.SUFFIX_STRING_java;
-// documentPath = root.getPath() + IJavaScriptSearchScope.JAR_FILE_ENTRY_SEPARATOR + relativePath;
-// } else
- {
- IPath path = this.localVariable.getPath();
- documentPath = path.toString();
- relativePath = Util.relativePath(path, 1/*remove project segment*/);
- }
-
- if (scope instanceof JavaSearchScope) {
- JavaSearchScope javaSearchScope = (JavaSearchScope) scope;
- // Get document path access restriction from java search scope
- // Note that requestor has to verify if needed whether the document violates the access restriction or not
- AccessRuleSet access = javaSearchScope.getAccessRuleSet(relativePath, index.containerPath);
- if (access != JavaSearchScope.NOT_ENCLOSED) { // scope encloses the path
- if (!requestor.acceptIndexMatch(documentPath, this, participant, access))
- throw new OperationCanceledException();
- }
- } else if (scope.encloses(documentPath)) {
- if (!requestor.acceptIndexMatch(documentPath, this, participant, null))
- throw new OperationCanceledException();
- }
- }
- else
- {
- super.findIndexMatches( index, requestor, participant, scope, progressMonitor);
- }
-}
-
-
-protected static char[][] REF_CATEGORIES = { REF };
-protected static char[][] REF_AND_DECL_CATEGORIES = { REF, VAR_DECL };
-protected static char[][] DECL_CATEGORIES = { VAR_DECL };
-
-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;
-}
-public char[] getIndexKey() {
- return this.name;
-}
-public SearchPattern getBlankPattern() {
- return new LocalVariablePattern(false, false, false, (char [])null, R_EXACT_MATCH | R_CASE_SENSITIVE);
-}
-public void decodeIndexKey(char[] key) {
- this.name = key;
-}
-protected StringBuffer print(StringBuffer output) {
- if (this.findDeclarations) {
- output.append(this.findReferences
- ? "LocalVarCombinedPattern: " //$NON-NLS-1$
- : "LocalVarDeclarationPattern: "); //$NON-NLS-1$
- } else {
- output.append("LocalVarReferencePattern: "); //$NON-NLS-1$
- }
- output.append(this.localVariable.toStringWithAncestors());
- 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
deleted file mode 100644
index ec374e7b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MatchLocator.java
+++ /dev/null
@@ -1,2594 +0,0 @@
-/*******************************************************************************
- * 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.search.matching;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-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.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-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.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-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.core.search.FieldDeclarationMatch;
-import org.eclipse.wst.jsdt.core.search.FieldReferenceMatch;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.LocalVariableDeclarationMatch;
-import org.eclipse.wst.jsdt.core.search.LocalVariableReferenceMatch;
-import org.eclipse.wst.jsdt.core.search.MethodDeclarationMatch;
-import org.eclipse.wst.jsdt.core.search.MethodReferenceMatch;
-import org.eclipse.wst.jsdt.core.search.PackageReferenceMatch;
-import org.eclipse.wst.jsdt.core.search.SearchDocument;
-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.core.search.TypeDeclarationMatch;
-import org.eclipse.wst.jsdt.core.search.TypeReferenceMatch;
-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.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.ArrayTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Block;
-import org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration;
-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.LocalDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration;
-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.TypeDeclaration;
-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.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;
-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.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.LookupEnvironment;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding;
-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.TagBits;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-import org.eclipse.wst.jsdt.internal.compiler.parser.Parser;
-import org.eclipse.wst.jsdt.internal.compiler.parser.Scanner;
-import org.eclipse.wst.jsdt.internal.compiler.parser.SourceTypeConverter;
-import org.eclipse.wst.jsdt.internal.compiler.parser.TerminalTokens;
-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.DefaultProblemFactory;
-import org.eclipse.wst.jsdt.internal.compiler.problem.ProblemReporter;
-import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfIntValues;
-import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfObject;
-import org.eclipse.wst.jsdt.internal.compiler.util.Messages;
-import org.eclipse.wst.jsdt.internal.compiler.util.SimpleLookupTable;
-import org.eclipse.wst.jsdt.internal.compiler.util.SimpleSet;
-import org.eclipse.wst.jsdt.internal.core.BinaryMember;
-import org.eclipse.wst.jsdt.internal.core.BinaryType;
-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.JavaModelManager;
-import org.eclipse.wst.jsdt.internal.core.JavaProject;
-import org.eclipse.wst.jsdt.internal.core.LibraryFragmentRoot;
-import org.eclipse.wst.jsdt.internal.core.LocalVariable;
-import org.eclipse.wst.jsdt.internal.core.MetadataFile;
-import org.eclipse.wst.jsdt.internal.core.NameLookup;
-import org.eclipse.wst.jsdt.internal.core.Openable;
-import org.eclipse.wst.jsdt.internal.core.PackageFragmentRoot;
-import org.eclipse.wst.jsdt.internal.core.SearchableEnvironment;
-import org.eclipse.wst.jsdt.internal.core.SourceMapper;
-import org.eclipse.wst.jsdt.internal.core.SourceMethod;
-import org.eclipse.wst.jsdt.internal.core.SourceTypeElementInfo;
-import org.eclipse.wst.jsdt.internal.core.hierarchy.HierarchyResolver;
-import org.eclipse.wst.jsdt.internal.core.index.Index;
-import org.eclipse.wst.jsdt.internal.core.search.BasicSearchEngine;
-import org.eclipse.wst.jsdt.internal.core.search.HierarchyScope;
-import org.eclipse.wst.jsdt.internal.core.search.IndexQueryRequestor;
-import org.eclipse.wst.jsdt.internal.core.search.IndexSelector;
-import org.eclipse.wst.jsdt.internal.core.search.JavaSearchDocument;
-import org.eclipse.wst.jsdt.internal.core.util.HandleFactory;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-import org.eclipse.wst.jsdt.internal.oaametadata.LibraryAPIs;
-
-public class MatchLocator implements ITypeRequestor, ITypeRequestor2 {
-
-public static final int MAX_AT_ONCE;
-static {
- long maxMemory = Runtime.getRuntime().maxMemory();
- int ratio = (int) Math.round(((double) maxMemory) / (64 * 0x100000));
- switch (ratio) {
- case 0:
- case 1:
- MAX_AT_ONCE = 100;
- break;
- case 2:
- MAX_AT_ONCE = 200;
- break;
- case 3:
- MAX_AT_ONCE = 300;
- break;
- default:
- MAX_AT_ONCE = 400;
- break;
- }
-}
-
-// permanent state
-public SearchPattern pattern;
-public PatternLocator patternLocator;
-public int matchContainer;
-public SearchRequestor requestor;
-public IJavaScriptSearchScope scope;
-public IProgressMonitor progressMonitor;
-
-public org.eclipse.wst.jsdt.core.IJavaScriptUnit[] workingCopies;
-public HandleFactory handleFactory;
-
-// cache of all super type names if scope is hierarchy scope
-public char[][][] allSuperTypeNames;
-
-// the following is valid for the current project
-public MatchLocatorParser parser;
-private Parser basicParser;
-public INameEnvironment nameEnvironment;
-public NameLookup nameLookup;
-public LookupEnvironment lookupEnvironment;
-public HierarchyResolver hierarchyResolver;
-
-public CompilerOptions options;
-
-// management of PossibleMatch to be processed
-public int numberOfMatches; // (numberOfMatches - 1) is the last unit in matchesToProcess
-public PossibleMatch[] matchesToProcess;
-public PossibleMatch currentPossibleMatch;
-
-/*
- * Time spent in the IJavaScriptSearchResultCollector
- */
-public long resultCollectorTime = 0;
-
-// Progress information
-int progressStep;
-int progressWorked;
-
-// Binding resolution and cache
-CompilationUnitScope unitScope;
-SimpleLookupTable bindings;
-
-// Cache for method handles
-HashSet methodHandles;
-
-private HashtableOfObject parsedUnits;
-
-
-class ReportMatchingVisitor extends ASTVisitor
-{
- MatchingNodeSet nodeSet;
- boolean matchedClassContainer;
- IJavaScriptElement enclosingElement;
- boolean typeInHierarchy;
- CoreException exception;
-
- public ReportMatchingVisitor(MatchingNodeSet nodeSet, boolean matchedClassContainer, IJavaScriptElement enclosingElement, boolean typeInHierarchy) {
- super();
- this.nodeSet = nodeSet;
- this.matchedClassContainer = matchedClassContainer;
- this.enclosingElement = enclosingElement;
- this.typeInHierarchy = typeInHierarchy;
- }
-
- public boolean visit(LocalDeclaration localDeclaration, BlockScope scope) {
- Integer level = (Integer) nodeSet.matchingNodes.removeKey(localDeclaration);
- int accuracy = (level != null && matchedClassContainer) ? level.intValue() : -1;
- try {
- reportMatching(localDeclaration, null, null, enclosingElement, accuracy, typeInHierarchy, nodeSet);
- } catch (CoreException e) {
- exception=e;
- }
-
- return false;
- }
-
- public boolean visit(MethodDeclaration methodDeclaration, Scope parentScope) {
- Integer level = (Integer) nodeSet.matchingNodes.removeKey(methodDeclaration);
- int value = (level != null && matchedClassContainer) ? level.intValue() : -1;
- try {
- reportMatching(null, methodDeclaration, enclosingElement, value, typeInHierarchy, nodeSet);
- } catch (CoreException e) {
- exception=e;
- }
- return false;
- }
-
-}
-
-
-/**
- * An ast visitor that visits local type declarations.
- */
-public class LocalDeclarationVisitor extends ASTVisitor {
- IJavaScriptElement enclosingElement;
- Binding enclosingElementBinding;
- MatchingNodeSet nodeSet;
- HashtableOfIntValues occurrencesCounts = new HashtableOfIntValues(); // key = class name (char[]), value = occurrenceCount (int)
- public LocalDeclarationVisitor(IJavaScriptElement enclosingElement, Binding enclosingElementBinding, MatchingNodeSet nodeSet) {
- this.enclosingElement = enclosingElement;
- this.enclosingElementBinding = enclosingElementBinding;
- this.nodeSet = nodeSet;
- }
- public boolean visit(TypeDeclaration typeDeclaration, BlockScope unused) {
- try {
- char[] simpleName;
- if ((typeDeclaration.bits & ASTNode.IsAnonymousType) != 0) {
- simpleName = CharOperation.NO_CHAR;
- } else {
- simpleName = typeDeclaration.name;
- }
- int occurrenceCount = occurrencesCounts.get(simpleName);
- if (occurrenceCount == HashtableOfIntValues.NO_VALUE) {
- occurrenceCount = 1;
- } else {
- occurrenceCount = occurrenceCount + 1;
- }
- occurrencesCounts.put(simpleName, occurrenceCount);
- if ((typeDeclaration.bits & ASTNode.IsAnonymousType) != 0) {
- reportMatching(typeDeclaration, this.enclosingElement, -1, nodeSet, occurrenceCount);
- } else {
- Integer level = (Integer) nodeSet.matchingNodes.removeKey(typeDeclaration);
- reportMatching(typeDeclaration, this.enclosingElement, level != null ? level.intValue() : -1, nodeSet, occurrenceCount);
- }
- return false; // don't visit members as this was done during reportMatching(...)
- } catch (CoreException e) {
- throw new WrappedCoreException(e);
- }
- }
-}
-
-public static class WorkingCopyDocument extends JavaSearchDocument {
- public org.eclipse.wst.jsdt.core.IJavaScriptUnit workingCopy;
- WorkingCopyDocument(org.eclipse.wst.jsdt.core.IJavaScriptUnit workingCopy, SearchParticipant participant) {
- super(workingCopy.getPath().toString(), participant);
- this.charContents = ((CompilationUnit)workingCopy).getContents();
- this.workingCopy = workingCopy;
- }
- public String toString() {
- return "WorkingCopyDocument for " + getPath(); //$NON-NLS-1$
- }
-}
-
-public static class WrappedCoreException extends RuntimeException {
- private static final long serialVersionUID = 8354329870126121212L; // backward compatible
- public CoreException coreException;
- public WrappedCoreException(CoreException coreException) {
- this.coreException = coreException;
- }
-}
-
-public static SearchDocument[] addWorkingCopies(InternalSearchPattern pattern, SearchDocument[] indexMatches, org.eclipse.wst.jsdt.core.IJavaScriptUnit[] copies, SearchParticipant participant) {
- // working copies take precedence over corresponding compilation units
- HashMap workingCopyDocuments = workingCopiesThatCanSeeFocus(copies, pattern.focus, pattern.isPolymorphicSearch(), participant);
- SearchDocument[] matches = null;
- int length = indexMatches.length;
- for (int i = 0; i < length; i++) {
- SearchDocument searchDocument = indexMatches[i];
- if (searchDocument.getParticipant() == participant) {
- SearchDocument workingCopyDocument = (SearchDocument) workingCopyDocuments.remove(searchDocument.getPath());
- if (workingCopyDocument != null) {
- if (matches == null) {
- System.arraycopy(indexMatches, 0, matches = new SearchDocument[length], 0, length);
- }
- matches[i] = workingCopyDocument;
- }
- }
- }
- if (matches == null) { // no working copy
- matches = indexMatches;
- }
- int remainingWorkingCopiesSize = workingCopyDocuments.size();
- if (remainingWorkingCopiesSize != 0) {
- System.arraycopy(matches, 0, matches = new SearchDocument[length+remainingWorkingCopiesSize], 0, length);
- Iterator iterator = workingCopyDocuments.values().iterator();
- int index = length;
- while (iterator.hasNext()) {
- matches[index++] = (SearchDocument) iterator.next();
- }
- }
- return matches;
-}
-
-public static void setFocus(InternalSearchPattern pattern, IJavaScriptElement focus) {
- pattern.focus = focus;
-}
-
-/*
- * Returns the working copies that can see the given focus.
- */
-private static HashMap workingCopiesThatCanSeeFocus(org.eclipse.wst.jsdt.core.IJavaScriptUnit[] copies, IJavaScriptElement focus, boolean isPolymorphicSearch, SearchParticipant participant) {
- if (copies == null) return new HashMap();
- if (focus != null) {
- while (!(focus instanceof IJavaScriptProject)) {
- focus = focus.getParent();
- }
- }
- HashMap result = new HashMap();
- for (int i=0, length = copies.length; i<length; i++) {
- org.eclipse.wst.jsdt.core.IJavaScriptUnit workingCopy = copies[i];
- IPath projectOrJar = MatchLocator.getProjectOrJar(workingCopy).getPath();
- if (focus == null || IndexSelector.canSeeFocus(focus, isPolymorphicSearch, projectOrJar)) {
- result.put(
- workingCopy.getPath().toString(),
- new WorkingCopyDocument(workingCopy, participant)
- );
- }
- }
- return result;
-}
-
-
-public static SearchPattern createAndPattern(final SearchPattern leftPattern, final SearchPattern rightPattern) {
- return new AndPattern(0/*no kind*/, 0/*no rule*/) {
- SearchPattern current = leftPattern;
- public SearchPattern currentPattern() {
- return this.current;
- }
- protected boolean hasNextQuery() {
- if (this.current == leftPattern) {
- this.current = rightPattern;
- return true;
- }
- return false;
- }
- protected void resetQuery() {
- this.current = leftPattern;
- }
- };
-}
-
-/**
- * Query a given index for matching entries. Assumes the sender has opened the index and will close when finished.
- */
-public static void findIndexMatches(InternalSearchPattern pattern, Index index, IndexQueryRequestor requestor, SearchParticipant participant, IJavaScriptSearchScope scope, IProgressMonitor monitor) throws IOException {
- pattern.findIndexMatches(index, requestor, participant, scope, monitor);
-}
-
-public static IJavaScriptElement getProjectOrJar(IJavaScriptElement element) {
- while (!(element instanceof IJavaScriptProject) &&
- !( element instanceof LibraryFragmentRoot) &&
- !( element instanceof PackageFragmentRoot)) {
- element = element.getParent();
- }
- return element;
-}
-
-public static IJavaScriptElement projectOrJarFocus(InternalSearchPattern pattern) {
- return pattern == null || pattern.focus == null ? null : getProjectOrJar(pattern.focus);
-}
-
-public MatchLocator(
- SearchPattern pattern,
- SearchRequestor requestor,
- IJavaScriptSearchScope scope,
- IProgressMonitor progressMonitor) {
-
- this.pattern = pattern;
- this.patternLocator = PatternLocator.patternLocator(this.pattern);
- this.matchContainer = this.patternLocator.matchContainer();
- this.requestor = requestor;
- this.scope = scope;
- this.progressMonitor = progressMonitor;
-}
-/**
- * Add an additional binary type
- */
-public void accept(IBinaryType binaryType, PackageBinding packageBinding, AccessRestriction accessRestriction) {
- /* commented out below is the original code with a compilation error */
- System.out.println("Bad call to method-- IMPLEMENT MatchLocator. accept(IBinaryType binaryType, PackageBinding packageBinding, AccessRestriction accessRestriction) "); //$NON-NLS-1$
- //this.lookupEnvironment.createBinaryTypeFrom(binaryType., packageBinding, accessRestriction);
-}
-/**
- * Add an additional compilation unit into the loop
- * -> build compilation unit declarations, their bindings and record their results.
- */
-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, 1, 1, this.options.maxProblemsPerUnit);
- try {
- if (parsedUnits == null)
- parsedUnits = new HashtableOfObject();
- CompilationUnitDeclaration parsedUnit = (CompilationUnitDeclaration) parsedUnits.get(sourceUnit.getFileName());
- if(parsedUnit == null) {
- Parser parser = basicParser();
- parsedUnit = parser.dietParse(sourceUnit, unitResult);
- parser.inferTypes(parsedUnit, this.options);
- parsedUnits.put(sourceUnit.getFileName(), parsedUnit);
- }
- this.lookupEnvironment.buildTypeBindings(parsedUnit, typeNames, accessRestriction);
- this.lookupEnvironment.completeTypeBindings(parsedUnit, typeNames, true);
- } 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
- }
- }
- // Display unit error in debug mode
- if (BasicSearchEngine.VERBOSE) {
- if (unitResult.problemCount > 0) {
- System.out.println(unitResult);
- }
- }
-}
-public void accept(ICompilationUnit sourceUnit, AccessRestriction accessRestriction) {
- accept(sourceUnit, new char[0][0], accessRestriction);
-}
-
-
-public void accept(LibraryAPIs libraryMetaData)
-{
- lookupEnvironment.buildTypeBindings(libraryMetaData);
-
-}
-/**
- * Add additional source types
- */
-public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding, AccessRestriction accessRestriction) {
- // case of SearchableEnvironment of an IJavaScriptProject is used
- ISourceType sourceType = sourceTypes[0];
- while (sourceType.getEnclosingType() != null)
- sourceType = sourceType.getEnclosingType();
- if (sourceType instanceof SourceTypeElementInfo) {
- // get source
- SourceTypeElementInfo elementInfo = (SourceTypeElementInfo) sourceType;
- IType type = elementInfo.getHandle();
- ICompilationUnit sourceUnit = (ICompilationUnit) type.getJavaScriptUnit();
- accept(sourceUnit, accessRestriction);
- } else {
- CompilationResult result = new CompilationResult(sourceType.getFileName(), sourceType.getPackageName(), 1, 1, 0);
- CompilationUnitDeclaration unit =
- SourceTypeConverter.buildCompilationUnit(
- sourceTypes,
- SourceTypeConverter.FIELD_AND_METHOD // need field and methods
- | SourceTypeConverter.MEMBER_TYPE, // need member types
- // no need for field initialization
- this.lookupEnvironment.problemReporter,
- result);
- this.lookupEnvironment.buildTypeBindings(unit, accessRestriction);
- this.lookupEnvironment.completeTypeBindings(unit, true);
- }
-}
-protected Parser basicParser() {
- if (this.basicParser == null) {
- ProblemReporter problemReporter =
- new ProblemReporter(
- DefaultErrorHandlingPolicies.proceedWithAllProblems(),
- this.options,
- new DefaultProblemFactory());
- this.basicParser = new Parser(problemReporter, false);
- this.basicParser.reportOnlyOneSyntaxError = true;
- }
- return this.basicParser;
-}
-/*
- * Caches the given binary type in the lookup environment and returns it.
- * Returns the existing one if already cached.
- * Returns null if source type binding was cached.
- */
-protected BinaryTypeBinding cacheBinaryType(IType type, IBinaryType binaryType) throws JavaScriptModelException {
- IType enclosingType = type.getDeclaringType();
- if (enclosingType != null)
- cacheBinaryType(enclosingType, null); // cache enclosing types first, so that binary type can be found in lookup enviroment
- if (binaryType == null) {
- ClassFile classFile = (ClassFile) type.getClassFile();
- try {
- binaryType = getBinaryInfo(classFile, classFile.getResource());
- } catch (CoreException e) {
- if (e instanceof JavaScriptModelException) {
- throw (JavaScriptModelException) e;
- } else {
- throw new JavaScriptModelException(e);
- }
- }
- }
-
- BinaryTypeBinding binding = null; //this.lookupEnvironment.cacheBinaryType(type, (AccessRestriction)null /*no access restriction*/);
- if (binding == null) { // it was already cached as a result of a previous query
- char[][] compoundName = CharOperation.splitOn('.', type.getFullyQualifiedName().toCharArray());
- ReferenceBinding referenceBinding = this.lookupEnvironment.getCachedType(compoundName);
- if (referenceBinding != null && (referenceBinding instanceof BinaryTypeBinding))
- binding = (BinaryTypeBinding) referenceBinding; // if the binding could be found and if it comes from a binary type
- }
- return binding;
-}
-/*
- * Computes the super type names of the focus type if any.
- */
-protected char[][][] computeSuperTypeNames(IType focusType) {
- String fullyQualifiedName = focusType.getFullyQualifiedName();
- int lastDot = fullyQualifiedName.lastIndexOf('.');
- char[] qualification = lastDot == -1 ? CharOperation.NO_CHAR : fullyQualifiedName.substring(0, lastDot).toCharArray();
- char[] simpleName = focusType.getElementName().toCharArray();
-
- SuperTypeNamesCollector superTypeNamesCollector =
- new SuperTypeNamesCollector(
- this.pattern,
- simpleName,
- qualification,
- new MatchLocator(this.pattern, this.requestor, this.scope, this.progressMonitor), // clone MatchLocator so that it has no side effect
- focusType,
- this.progressMonitor);
- try {
- this.allSuperTypeNames = superTypeNamesCollector.collect();
- } catch (JavaScriptModelException e) {
- // problem collecting super type names: leave it null
- }
- return this.allSuperTypeNames;
-}
-/**
- * Creates an IFunction from the given method declaration and type.
- */
-protected IJavaScriptElement createHandle(AbstractMethodDeclaration method, IJavaScriptElement parent) {
- if (!(parent instanceof IType ||
- parent instanceof org.eclipse.wst.jsdt.core.IJavaScriptUnit ||
- parent instanceof org.eclipse.wst.jsdt.core.IClassFile
- )) return parent;
-
-// IType type = (IType) parent;
- Argument[] arguments = method.arguments;
- int argCount = arguments == null ? 0 : arguments.length;
-// if (type.isBinary()) {
-// // don't cache the methods of the binary type
-// // fall thru if its a constructor with a synthetic argument... find it the slower way
-// ClassFileReader reader = classFileReader(type);
-// if (reader != null) {
-// IBinaryMethod[] methods = reader.getMethods();
-// if (methods != null) {
-// // build arguments names
-// boolean firstIsSynthetic = false;
-// if (reader.isMember() && method.isConstructor() && !Flags.isStatic(reader.getModifiers())) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=48261
-// firstIsSynthetic = true;
-// argCount++;
-// }
-// char[][] argumentTypeNames = new char[argCount][];
-// for (int i = 0; i < argCount; i++) {
-// char[] typeName = null;
-// if (i == 0 && firstIsSynthetic) {
-// typeName = type.getDeclaringType().getFullyQualifiedName().toCharArray();
-// } else if (arguments != null) {
-// TypeReference typeRef = arguments[firstIsSynthetic ? i - 1 : i].type;
-// typeName = CharOperation.concatWith(typeRef.getTypeName(), '.');
-// for (int k = 0, dim = typeRef.dimensions(); k < dim; k++)
-// typeName = CharOperation.concat(typeName, new char[] {'[', ']'});
-// }
-// if (typeName == null) {
-// // invalid type name
-// return null;
-// }
-// argumentTypeNames[i] = typeName;
-// }
-//
-// // return binary method
-// return createBinaryMethodHandle(type, method.selector, argumentTypeNames);
-// }
-// }
-// return null;
-// }
-
- String[] parameterTypeSignatures = new String[argCount];
- if (arguments != null) {
- for (int i = 0; i < argCount; i++) {
- TypeReference typeRef = arguments[i].type;
- char[] typeName = typeRef!=null ? CharOperation.concatWith(typeRef.getTypeName(), '.')
- : null;
- parameterTypeSignatures[i] = Signature.createTypeSignature(typeName, false);
- }
- }
-
- char [] methodName=method.isInferred()?method.inferredMethod.name:method.selector;
- if (methodName==null)
- return null;
- return createMethodHandle(parent, new String(methodName), parameterTypeSignatures);
-}
-/*
- * Create method handle.
- * Store occurences for create handle to retrieve possible duplicate ones.
- */
-private IJavaScriptElement createMethodHandle(IJavaScriptElement parent, String methodName, String[] parameterTypeSignatures) {
- IFunction methodHandle = null;
- if (parent instanceof org.eclipse.wst.jsdt.core.IJavaScriptUnit) {
- org.eclipse.wst.jsdt.core.IJavaScriptUnit compUnit = (org.eclipse.wst.jsdt.core.IJavaScriptUnit ) parent;
- methodHandle = compUnit.getFunction(methodName, parameterTypeSignatures);
-
- }
- else if (parent instanceof ICompilationUnit) {
- org.eclipse.wst.jsdt.core.IClassFile classFile = (org.eclipse.wst.jsdt.core.IClassFile ) parent;
- methodHandle = classFile.getFunction(methodName, parameterTypeSignatures);
-
- }
- else if (parent instanceof IType) {
- IType type = (IType) parent;
- methodHandle = type.getFunction(methodName, parameterTypeSignatures);
-
- }
- if (methodHandle instanceof SourceMethod) {
- while (this.methodHandles.contains(methodHandle)) {
- ((SourceMethod) methodHandle).occurrenceCount++;
- }
- }
- this.methodHandles.add(methodHandle);
- return methodHandle;
-}
-protected IJavaScriptElement createHandle(InferredAttribute fieldDeclaration, InferredType typeDeclaration, IJavaScriptElement parent) {
- if (parent instanceof ITypeRoot) {
- ITypeRoot typeRoot = (ITypeRoot) parent;
- parent=typeRoot.getType(new String(typeDeclaration.getName()));
- }
- if (!(parent instanceof IType)) return parent;
-
- return ((IType) parent).getField(new String(fieldDeclaration.name));
-}
-
-
-/**
- * Creates an IField from the given field declaration and type.
- */
-protected IJavaScriptElement createHandle(FieldDeclaration fieldDeclaration, TypeDeclaration typeDeclaration, IJavaScriptElement parent) {
- if (!(parent instanceof IType)) return parent;
- IType type = (IType) parent;
-
- switch (fieldDeclaration.getKind()) {
- case AbstractVariableDeclaration.FIELD :
- return ((IType) parent).getField(new String(fieldDeclaration.name));
- }
- if (type.isBinary()) {
- // do not return initializer for binary types
- // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=98378
- return type;
- }
- // find occurence count of the given initializer in its type declaration
- int occurrenceCount = 0;
- FieldDeclaration[] fields = typeDeclaration.fields;
- for (int i = 0, length = fields.length; i < length; i++) {
- if (fields[i].getKind() == AbstractVariableDeclaration.INITIALIZER) {
- occurrenceCount++;
- if (fields[i].equals(fieldDeclaration)) break;
- }
- }
- return ((IType) parent).getInitializer(occurrenceCount);
-}
-/**
- * Create an handle for a local variable declartion (may be a local variable or type parameter).
- */
-protected IJavaScriptElement createHandle(AbstractVariableDeclaration variableDeclaration, IJavaScriptElement parent) {
- switch (variableDeclaration.getKind()) {
- case AbstractVariableDeclaration.LOCAL_VARIABLE:
- String signature = (variableDeclaration.type!=null) ?
- new String(variableDeclaration.type.resolvedType.signature()): Signature.SIG_ANY;
- return new LocalVariable((JavaElement)parent,
- new String(variableDeclaration.name),
- variableDeclaration.declarationSourceStart,
- variableDeclaration.declarationSourceEnd,
- variableDeclaration.sourceStart,
- variableDeclaration.sourceEnd,
- signature
- );
- case AbstractVariableDeclaration.PARAMETER:
- return new LocalVariable((JavaElement)parent,
- new String(variableDeclaration.name),
- variableDeclaration.declarationSourceStart,
- variableDeclaration.declarationSourceEnd,
- variableDeclaration.sourceStart,
- variableDeclaration.sourceEnd,
- new String(variableDeclaration.type.resolvedType.signature())
- );
- }
- return null;
-}
-/*
- * Creates hierarchy resolver if needed.
- * Returns whether focus is visible.
- */
-protected boolean createHierarchyResolver(IType focusType, PossibleMatch[] possibleMatches) {
- // cache focus type if not a possible match
- char[][] compoundName = CharOperation.splitOn('.', focusType.getFullyQualifiedName().toCharArray());
- boolean isPossibleMatch = false;
- for (int i = 0, length = possibleMatches.length; i < length; i++) {
- if (CharOperation.equals(possibleMatches[i].compoundName, compoundName)) {
- isPossibleMatch = true;
- break;
- }
- }
- if (!isPossibleMatch) {
- if (focusType.isBinary()) {
- try {
- cacheBinaryType(focusType, null);
- } catch (JavaScriptModelException e) {
- return false;
- }
- } else {
- // cache all types in the focus' compilation unit (even secondary types)
- accept((ICompilationUnit) focusType.getJavaScriptUnit(), null /*TODO no access restriction*/);
- }
- }
-
- // resolve focus type
- this.hierarchyResolver = new HierarchyResolver(this.lookupEnvironment, null/*hierarchy is not going to be computed*/);
- ReferenceBinding binding = this.hierarchyResolver.setFocusType(compoundName);
- return binding != null && binding.isValidBinding() && (binding.tagBits & TagBits.HierarchyHasProblems) == 0;
-}
-/**
- * Creates an IImportDeclaration from the given import statement
- */
-protected IJavaScriptElement createImportHandle(ImportReference importRef) {
- char[] importName = CharOperation.concatWith(importRef.getImportName(), '.');
- if ((importRef.bits & ASTNode.OnDemand) != 0)
- importName = CharOperation.concat(importName, ".*" .toCharArray()); //$NON-NLS-1$
- Openable openable = this.currentPossibleMatch.openable;
- if (openable instanceof CompilationUnit)
- return ((CompilationUnit) openable).getImport(new String(importName));
-
- // 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));
-}
-/**
- * Creates an IType from the given simple top level type name.
- */
-protected IType createTypeHandle(String simpleTypeName) {
- Openable openable = this.currentPossibleMatch.openable;
- if (openable instanceof CompilationUnit)
- return ((CompilationUnit) openable).getType(simpleTypeName);
-
- IType binaryType = ((ClassFile) openable).getType(simpleTypeName);
-// String binaryTypeQualifiedName = binaryType.getTypeQualifiedName();
-// if (simpleTypeName.equals(binaryTypeQualifiedName))
- return binaryType; // answer only top-level types, sometimes the classFile is for a member/local type
-
-// // type name may be null for anonymous (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=164791)
-// String classFileName = simpleTypeName.length() == 0 ? binaryTypeQualifiedName : simpleTypeName;
-// IClassFile classFile = binaryType.getPackageFragment().getClassFile(classFileName + SuffixConstants.SUFFIX_STRING_class);
-// return classFile.getType();
-}
-protected boolean encloses(IJavaScriptElement element) {
- return element != null && this.scope.encloses(element);
-}
-/* (non-Javadoc)
- * Return info about last type argument of a parameterized type reference.
- * These info are made of concatenation of 2 int values which are respectively
- * depth and end position of the last type argument.
- * For example, this method will return 0x300000020 for type ref List<List<List<String>>>
- * if end position of type reference "String" equals 32.
- */
-private long findLastTypeArgumentInfo(TypeReference typeRef) {
- // Get last list of type arguments for parameterized qualified type reference
- TypeReference lastTypeArgument = typeRef;
- int depth = 0;
- while (true) {
- TypeReference[] lastTypeArguments = null;
- // Get last type argument for single type reference of last list of argument of parameterized qualified type reference
- TypeReference last = null;
- if (lastTypeArguments != null) {
- for (int i=lastTypeArguments.length-1; i>=0 && last==null; i++) {
- last = lastTypeArguments[i];
- }
- }
- if (last == null) break;
- depth++;
- lastTypeArgument = last;
- }
- // Current type reference is not parameterized. So, it is the last type argument
- return (((long) depth) << 32) + lastTypeArgument.sourceEnd;
-}
-protected IBinaryType getBinaryInfo(ClassFile classFile, IResource resource) throws CoreException {
- BinaryType binaryType = (BinaryType) classFile.getType();
- if (classFile.isOpen())
- return (IBinaryType) binaryType.getElementInfo(); // reuse the info from the java model cache
-
- // create a temporary info
-// IBinaryType info;
-// try {
-// PackageFragment pkg = (PackageFragment) classFile.getParent();
-// PackageFragmentRoot root = (PackageFragmentRoot) pkg.getParent();
-// if (root.isArchive()) {
-// // class file in a jar
-// String classFileName = classFile.getElementName();
-// String classFilePath = Util.concatWith(pkg.names, classFileName, '/');
-// ZipFile zipFile = null;
-// try {
-// zipFile = ((JarPackageFragmentRoot) root).getJar();
-// info = ClassFileReader.read(zipFile, classFilePath);
-// } finally {
-// JavaModelManager.getJavaModelManager().closeZipFile(zipFile);
-// }
-// } else {
-// // class file in a directory
-// info = Util.newClassFileReader(resource);
-// }
-// if (info == null) throw binaryType.newNotPresentException();
-// return info;
-// } catch (ClassFormatException e) {
-// //e.printStackTrace();
-// return null;
-// } catch (java.io.IOException e) {
-// throw new JavaScriptModelException(e, IJavaScriptModelStatusConstants.IO_EXCEPTION);
-// }
- return null;
-}
-protected IType getFocusType() {
- return this.scope instanceof HierarchyScope ? ((HierarchyScope) this.scope).focusType : null;
-}
-protected void getMethodBodies(CompilationUnitDeclaration unit, MatchingNodeSet nodeSet) {
- if (unit.ignoreMethodBodies) {
- unit.ignoreFurtherInvestigation = true;
- return; // if initial diet parse did not work, no need to dig into method bodies.
- }
-
- // save existing values to restore them at the end of the parsing process
- // see bug 47079 for more details
- int[] oldLineEnds = this.parser.scanner.lineEnds;
- int oldLinePtr = this.parser.scanner.linePtr;
-
- try {
- CompilationResult compilationResult = unit.compilationResult;
- this.parser.scanner.setSource(compilationResult);
-
- if (this.parser.javadocParser.checkDocComment) {
- char[] contents = compilationResult.compilationUnit.getContents();
- this.parser.javadocParser.scanner.setSource(contents);
- }
- this.parser.nodeSet = nodeSet;
- this.parser.parseBodies(unit);
- } finally {
- this.parser.nodeSet = null;
- // this is done to prevent any side effects on the compilation unit result
- // line separator positions array.
- this.parser.scanner.lineEnds = oldLineEnds;
- this.parser.scanner.linePtr = oldLinePtr;
- }
-}
-protected TypeBinding getType(Object typeKey, char[] typeName) {
- if (this.unitScope == null || typeName == null || typeName.length == 0) return null;
- // Try to get binding from cache
- Binding binding = (Binding) this.bindings.get(typeKey);
- if (binding != null) {
- if (binding instanceof TypeBinding && binding.isValidBinding())
- return (TypeBinding) binding;
- return null;
- }
- // Get binding from unit scope
- char[][] compoundName = CharOperation.splitOn('.', typeName);
- TypeBinding typeBinding = this.unitScope.getType(compoundName, compoundName.length);
- this.bindings.put(typeKey, typeBinding);
- return typeBinding.isValidBinding() ? typeBinding : null;
-}
-public MethodBinding getMethodBinding(MethodPattern methodPattern) {
- if (this.unitScope == null) return null;
- // Try to get binding from cache
- Binding binding = (Binding) this.bindings.get(methodPattern);
- if (binding != null) {
- if (binding instanceof MethodBinding && binding.isValidBinding())
- return (MethodBinding) binding;
- 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();
- }
- TypeBinding declaringTypeBinding = getType(typeName, typeName);
- if (declaringTypeBinding != null) {
- if (declaringTypeBinding.isArrayType()) {
- declaringTypeBinding = declaringTypeBinding.leafComponentType();
- }
- if (!declaringTypeBinding.isBaseType()) {
- char[][] parameterTypes = methodPattern.parameterSimpleNames;
- if (parameterTypes == null) return null;
- int paramTypeslength = parameterTypes.length;
- ReferenceBinding referenceBinding = (ReferenceBinding) declaringTypeBinding;
- MethodBinding[] methods = referenceBinding.getMethods(methodPattern.selector);
- int methodsLength = methods.length;
- for (int i=0; i<methodsLength; i++) {
- TypeBinding[] methodParameters = methods[i].parameters;
- int paramLength = methodParameters==null ? 0 : methodParameters.length;
- boolean found = false;
- if (methodParameters != null && paramLength == paramTypeslength) {
- for (int p=0; p<paramLength; p++) {
- if (CharOperation.equals(methodParameters[p].sourceName(), parameterTypes[p])) {
- // param erasure match
- found = true;
- } else {
- // type variable
- found = false;
- if (!found) break;
- }
- }
- }
- if (found) {
- this.bindings.put(methodPattern, methods[i]);
- return methods[i];
- }
- }
- }
- }
- this.bindings.put(methodPattern, new ProblemMethodBinding(methodPattern.selector, null, ProblemReasons.NotFound));
- return null;
-}
-protected boolean hasAlreadyDefinedType(CompilationUnitDeclaration parsedUnit) {
- CompilationResult result = parsedUnit.compilationResult;
- if (result == null) return false;
- for (int i = 0; i < result.problemCount; i++)
- if (result.problems[i].getID() == IProblem.DuplicateTypes)
- return true;
- return false;
-}
-/**
- * Create a new parser for the given project, as well as a lookup environment.
- */
-public void initialize(JavaProject project, int possibleMatchSize) throws JavaScriptModelException {
- // clean up name environment only if there are several possible match as it is reused
- // when only one possible match (bug 58581)
- if (this.nameEnvironment != null && possibleMatchSize != 1)
- this.nameEnvironment.cleanup();
-
- SearchableEnvironment searchableEnvironment = project.newSearchableNameEnvironment(this.workingCopies);
-
- // if only one possible match, a file name environment costs too much,
- // so use the existing searchable environment which will populate the java model
- // only for this possible match and its required types.
- this.nameEnvironment = true//possibleMatchSize == 1
- ? (INameEnvironment) searchableEnvironment
- : (INameEnvironment) new JavaSearchNameEnvironment(project, this.workingCopies);
-
- // create lookup environment
- Map map = project.getOptions(true);
- map.put(CompilerOptions.OPTION_TaskTags, ""); //$NON-NLS-1$
- this.options = new CompilerOptions(map);
- ProblemReporter problemReporter =
- new ProblemReporter(
- DefaultErrorHandlingPolicies.proceedWithAllProblems(),
- this.options,
- new DefaultProblemFactory());
- this.lookupEnvironment = new LookupEnvironment(this, this.options, problemReporter, this.nameEnvironment);
-
- this.parser = MatchLocatorParser.createParser(problemReporter, this);
-
- // basic parser needs also to be reset as project options may have changed
- // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=163072
- this.basicParser = null;
-
- // remember project's name lookup
- this.nameLookup = searchableEnvironment.nameLookup;
-
- // initialize queue of units
- this.numberOfMatches = 0;
- this.matchesToProcess = new PossibleMatch[possibleMatchSize];
-}
-protected void locateMatches(JavaProject javaProject, PossibleMatch[] possibleMatches, int start, int length) throws CoreException {
- initialize(javaProject, length);
-
- // create and resolve binding (equivalent to beginCompilation() in Compiler)
- boolean mustResolvePattern = ((InternalSearchPattern)this.pattern).mustResolve;
- boolean mustResolve = mustResolvePattern;
- this.patternLocator.mayBeGeneric = this.options.sourceLevel >= ClassFileConstants.JDK1_5;
- boolean bindingsWereCreated = mustResolve;
- try {
- for (int i = start, maxUnits = start + length; i < maxUnits; i++) {
- PossibleMatch possibleMatch = possibleMatches[i];
- try {
- if (possibleMatch.openable instanceof MetadataFile)
- {
- this.currentPossibleMatch=possibleMatch;
- processMetadata((MetadataFile)possibleMatch.openable);
- }
- else
- {
- if (!parseAndBuildBindings(possibleMatch, mustResolvePattern)) continue;
- // Currently we only need to resolve over pattern flag if there's potential parameterized types
- if (this.patternLocator.mayBeGeneric) {
- // If pattern does not resolve then rely on possible match node set resolution
- // which may have been modified while locator was adding possible matches to it
- if (!mustResolvePattern && !mustResolve) {
- mustResolve = possibleMatch.nodeSet.mustResolve;
- bindingsWereCreated = mustResolve;
- }
- } else {
- // Reset matching node resolution with pattern one if there's no potential parameterized type
- // to minimize side effect on previous search behavior
- possibleMatch.nodeSet.mustResolve = mustResolvePattern;
- }
- // possible match node resolution has been merged with pattern one, so rely on it to know
- // whether we need to process compilation unit now or later
- if (!possibleMatch.nodeSet.mustResolve) {
- if (this.progressMonitor != null) {
- this.progressWorked++;
- if ((this.progressWorked%this.progressStep)==0) this.progressMonitor.worked(this.progressStep);
- }
- process(possibleMatch, bindingsWereCreated);
- if (this.numberOfMatches>0 && this.matchesToProcess[this.numberOfMatches-1] == possibleMatch) {
- // forget last possible match as it was processed
- this.numberOfMatches--;
- }
- }
- }
- } finally {
- if (!possibleMatch.nodeSet.mustResolve)
- possibleMatch.cleanUp();
- }
- }
- if (mustResolve)
- this.lookupEnvironment.completeTypeBindings();
-
- // create hierarchy resolver if needed
- IType focusType = getFocusType();
- if (focusType == null) {
- this.hierarchyResolver = null;
- } else if (!createHierarchyResolver(focusType, possibleMatches)) {
- // focus type is not visible, use the super type names instead of the bindings
- if (computeSuperTypeNames(focusType) == null) return;
- }
- } catch (AbortCompilation e) {
- bindingsWereCreated = false;
- }
-
- if (!mustResolve) {
- return;
- }
-
- // possible match resolution
- for (int i = 0; i < this.numberOfMatches; i++) {
- 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) {
- // problem with class path: it could not find base classes
- // continue and try next matching openable reporting innacurate matches (since bindings will be null)
- bindingsWereCreated = false;
- } catch (JavaScriptModelException e) {
- // problem with class path: it could not find base classes
- // continue and try next matching openable reporting innacurate matches (since bindings will be null)
- bindingsWereCreated = false;
- } finally {
- if (this.progressMonitor != null) {
- this.progressWorked++;
- if ((this.progressWorked%this.progressStep)==0) this.progressMonitor.worked(this.progressStep);
- }
- if (this.options.verbose)
- System.out.println(
- Messages.bind(Messages.compilation_done,
- new String[] {
- String.valueOf(i + 1),
- String.valueOf(this.numberOfMatches),
- new String(possibleMatch.parsedUnit.getFileName())
- }));
- // cleanup compilation unit result
- possibleMatch.cleanUp();
- }
- }
-}
-private void processMetadata(MetadataFile metadataFile) throws CoreException{
-
- IType [] types = metadataFile.getTypes();
- int matchLevel=PatternLocator.IMPOSSIBLE_MATCH;
- for (int typeIndex = 0; typeIndex < types.length; typeIndex++) {
- IType type=types[typeIndex];
- matchLevel=this.patternLocator.matchMetadataElement(type);
- if (matchLevel>=PatternLocator.POSSIBLE_MATCH)
- reportMatching(type, matchLevel, null, 1);
- IFunction[] methods = type.getFunctions();
- for (int methodIndex = 0; methodIndex < methods.length; methodIndex++) {
- IFunction method=methods[methodIndex];
- matchLevel=this.patternLocator.matchMetadataElement(method);
- if (matchLevel>=PatternLocator.POSSIBLE_MATCH)
- reportMatching(method, matchLevel, null, 1);
- }
- IField[] fields = type.getFields();
- for (int fieldIndex = 0; fieldIndex < fields.length; fieldIndex++) {
- IField field=fields[fieldIndex];
- matchLevel=this.patternLocator.matchMetadataElement(field);
- if (matchLevel>=PatternLocator.POSSIBLE_MATCH)
- reportMatching(field, matchLevel, null, 1);
- }
- }
- IFunction[] methods = metadataFile.getFunctions();
- for (int methodIndex = 0; methodIndex < methods.length; methodIndex++) {
- IFunction method=methods[methodIndex];
- matchLevel=this.patternLocator.matchMetadataElement(method);
- if (matchLevel>=PatternLocator.POSSIBLE_MATCH)
- reportMatching(method, matchLevel, null, 1);
- }
- IField[] fields = metadataFile.getFields();
- for (int fieldIndex = 0; fieldIndex < fields.length; fieldIndex++) {
- IField field=fields[fieldIndex];
- matchLevel=this.patternLocator.matchMetadataElement(field);
- if (matchLevel>=PatternLocator.POSSIBLE_MATCH)
- reportMatching(field, matchLevel, null, 1);
- }
-
-}
-
-/**
- * Locate the matches amongst the possible matches.
- */
-protected void locateMatches(JavaProject javaProject, PossibleMatchSet matchSet, int expected) throws CoreException {
- PossibleMatch[] possibleMatches = matchSet.getPossibleMatches(javaProject.getPackageFragmentRoots());
- int length = possibleMatches.length;
- // increase progress from duplicate matches not stored in matchSet while adding...
- if (this.progressMonitor != null && expected>length) {
- this.progressWorked += expected-length;
- this.progressMonitor.worked( expected-length);
- }
- // locate matches (processed matches are limited to avoid problem while using VM default memory heap size)
- for (int index = 0; index < length;) {
- int max = Math.min(MAX_AT_ONCE, length - index);
- locateMatches(javaProject, possibleMatches, index, max);
- index += max;
- }
- this.patternLocator.clear();
-}
-/**
- * Locate the matches in the given files and report them using the search requestor.
- */
-public void locateMatches(SearchDocument[] searchDocuments) throws CoreException {
- int docsLength = searchDocuments.length;
- if (BasicSearchEngine.VERBOSE) {
- System.out.println("Locating matches in documents ["); //$NON-NLS-1$
- for (int i = 0; i < docsLength; i++)
- System.out.println("\t" + searchDocuments[i]); //$NON-NLS-1$
- System.out.println("]"); //$NON-NLS-1$
- }
-
- // init infos for progress increasing
- int n = docsLength<1000 ? Math.min(Math.max(docsLength/200+1, 2),4) : 5 *(docsLength/1000);
- this.progressStep = docsLength < n ? 1 : docsLength / n; // step should not be 0
- this.progressWorked = 0;
-
- // extract working copies
- ArrayList copies = new ArrayList();
- for (int i = 0; i < docsLength; i++) {
- SearchDocument document = searchDocuments[i];
- if (document instanceof WorkingCopyDocument) {
- copies.add(((WorkingCopyDocument)document).workingCopy);
- }
- }
- int copiesLength = copies.size();
- this.workingCopies = new org.eclipse.wst.jsdt.core.IJavaScriptUnit[copiesLength];
- copies.toArray(this.workingCopies);
-
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- this.bindings = new SimpleLookupTable();
- try {
- // optimize access to zip files during search operation
- manager.cacheZipFiles();
-
- // initialize handle factory (used as a cache of handles so as to optimize space)
- if (this.handleFactory == null)
- this.handleFactory = new HandleFactory();
-
- if (this.progressMonitor != null) {
- this.progressMonitor.beginTask("", searchDocuments.length); //$NON-NLS-1$
- }
-
- // initialize pattern for polymorphic search (ie. method reference pattern)
- this.patternLocator.initializePolymorphicSearch(this);
-
- JavaProject previousJavaProject = null;
- PossibleMatchSet matchSet = new PossibleMatchSet();
- Util.sort(searchDocuments, new Util.Comparer() {
- public int compare(Object a, Object b) {
- return ((SearchDocument)a).getPath().compareTo(((SearchDocument)b).getPath());
- }
- });
- int displayed = 0; // progress worked displayed
- String previousPath = null;
- for (int i = 0; i < docsLength; i++) {
- if (this.progressMonitor != null && this.progressMonitor.isCanceled()) {
- throw new OperationCanceledException();
- }
-
- // skip duplicate paths
- SearchDocument searchDocument = searchDocuments[i];
- searchDocuments[i] = null; // free current document
- String pathString = searchDocument.getPath();
- if (i > 0 && pathString.equals(previousPath)) {
- if (this.progressMonitor != null) {
- this.progressWorked++;
- if ((this.progressWorked%this.progressStep)==0) this.progressMonitor.worked(this.progressStep);
- }
- displayed++;
- continue;
- }
- previousPath = pathString;
-
- Openable openable;
- org.eclipse.wst.jsdt.core.IJavaScriptUnit workingCopy = null;
- if (searchDocument instanceof WorkingCopyDocument) {
- workingCopy = ((WorkingCopyDocument)searchDocument).workingCopy;
- openable = (Openable) workingCopy;
- } else if(searchDocument.isVirtual()) {
- openable = (Openable)searchDocument.getJavaElement();
- }else{
- openable = this.handleFactory.createOpenable(pathString, this.scope);
- }
- if (openable == null) {
- if (this.progressMonitor != null) {
- this.progressWorked++;
- if ((this.progressWorked%this.progressStep)==0) this.progressMonitor.worked(this.progressStep);
- }
- displayed++;
- continue; // match is outside classpath
- }
-
- // create new parser and lookup environment if this is a new project
- IResource resource = null;
- JavaProject javaProject = (JavaProject) openable.getJavaScriptProject();
- resource = workingCopy != null ? workingCopy.getResource() : openable.getResource();
- if (resource == null)
- resource = javaProject.getProject(); // case of a file in an external jar
- if (!javaProject.equals(previousJavaProject)) {
- // locate matches in previous project
- if (previousJavaProject != null) {
- try {
- locateMatches(previousJavaProject, matchSet, i-displayed);
- displayed = i;
- } catch (JavaScriptModelException e) {
- // problem with classpath in this project -> skip it
- }
- matchSet.reset();
- }
- previousJavaProject = javaProject;
- }
- matchSet.add(new PossibleMatch(this, resource, openable, searchDocument, ((InternalSearchPattern) this.pattern).mustResolve));
- }
-
- // last project
- if (previousJavaProject != null) {
- try {
- locateMatches(previousJavaProject, matchSet, docsLength-displayed);
- } catch (JavaScriptModelException e) {
- // problem with classpath in last project -> ignore
- }
- }
-
- } finally {
- if (this.progressMonitor != null)
- this.progressMonitor.done();
- if (this.nameEnvironment != null)
- this.nameEnvironment.cleanup();
- if(this.parsedUnits != null) {
- parsedUnits.clear();
- }
- manager.flushZipFiles();
- this.bindings = null;
- }
-}
-//*/
-protected IType lookupType(ReferenceBinding typeBinding) {
- if (typeBinding == null) return null;
-
- char[] packageName = typeBinding.qualifiedPackageName();
- IPackageFragment[] pkgs = this.nameLookup.findPackageFragments(
- (packageName == null || packageName.length == 0)
- ? IPackageFragment.DEFAULT_PACKAGE_NAME
- : new String(packageName),
- false);
-
- // iterate type lookup in each package fragment
- char[] sourceName = typeBinding.qualifiedSourceName();
- String typeName = new String(sourceName);
- int acceptFlag = 0;
- if (typeBinding.isClass()) {
- acceptFlag = NameLookup.ACCEPT_CLASSES;
- }
- if (pkgs != null) {
- for (int i = 0, length = pkgs.length; i < length; i++) {
- IType type = this.nameLookup.findType(typeName, pkgs[i], false, acceptFlag, true/*consider secondary types*/);
- if (type != null) return type;
- }
- }
-
- // search inside enclosing element
- char[][] qualifiedName = CharOperation.splitOn('.', sourceName);
- int length = qualifiedName.length;
- if (length == 0) return null;
-
- IType type = createTypeHandle(new String(qualifiedName[0])); // find the top-level type
- if (type == null) return null;
-
- for (int i = 1; i < length; i++) {
- type = type.getType(new String(qualifiedName[i]));
- if (type == null) return null;
- }
- if (type.exists()) return type;
- return null;
-}
-public SearchMatch newDeclarationMatch(
- IJavaScriptElement element,
- Binding binding,
- int accuracy,
- int offset,
- int length) {
- SearchParticipant participant = getParticipant();
- IResource resource = this.currentPossibleMatch.resource;
- return newDeclarationMatch(element, binding, accuracy, offset, length, participant, resource);
-}
-
-public SearchMatch newDeclarationMatch(
- IJavaScriptElement element,
- Binding binding,
- int accuracy,
- int offset,
- int length,
- SearchParticipant participant,
- IResource resource) {
- switch (element.getElementType()) {
- case IJavaScriptElement.TYPE:
- return new TypeDeclarationMatch(binding == null ? element : ((JavaElement) element).resolved(binding), accuracy, offset, length, participant, resource);
- case IJavaScriptElement.FIELD:
- return new FieldDeclarationMatch(binding == null ? element : ((JavaElement) element).resolved(binding), accuracy, offset, length, participant, resource);
- case IJavaScriptElement.METHOD:
- return new MethodDeclarationMatch(binding == null ? element : ((JavaElement) element).resolved(binding), accuracy, offset, length, participant, resource);
- case IJavaScriptElement.LOCAL_VARIABLE:
- return new LocalVariableDeclarationMatch(element, accuracy, offset, length, participant, resource);
- default:
- return null;
- }
-}
-
-public SearchMatch newFieldReferenceMatch(
- IJavaScriptElement enclosingElement,
- Binding enclosingBinding,
- int accuracy,
- int offset,
- int length,
- ASTNode reference) {
- int bits = reference.bits;
- boolean isCoupoundAssigned = (bits & ASTNode.IsCompoundAssigned) != 0;
- boolean isReadAccess = isCoupoundAssigned || (bits & ASTNode.IsStrictlyAssigned) == 0;
- boolean isWriteAccess = isCoupoundAssigned || (bits & ASTNode.IsStrictlyAssigned) != 0;
- boolean insideDocComment = (bits & ASTNode.InsideJavadoc) != 0;
- SearchParticipant participant = getParticipant();
- IResource resource = this.currentPossibleMatch.resource;
- if (enclosingBinding != null)
- enclosingElement = ((JavaElement) enclosingElement).resolved(enclosingBinding);
- return new FieldReferenceMatch(enclosingElement, accuracy, offset, length, isReadAccess, isWriteAccess, insideDocComment, participant, resource);
-}
-
-public SearchMatch newLocalVariableReferenceMatch(
- IJavaScriptElement enclosingElement,
- int accuracy,
- int offset,
- int length,
- ASTNode reference) {
- int bits = reference.bits;
- boolean isCoupoundAssigned = (bits & ASTNode.IsCompoundAssigned) != 0;
- boolean isReadAccess = isCoupoundAssigned || (bits & ASTNode.IsStrictlyAssigned) == 0;
- boolean isWriteAccess = isCoupoundAssigned || (bits & ASTNode.IsStrictlyAssigned) != 0;
- boolean insideDocComment = (bits & ASTNode.InsideJavadoc) != 0;
- SearchParticipant participant = getParticipant();
- IResource resource = this.currentPossibleMatch.resource;
- return new LocalVariableReferenceMatch(enclosingElement, accuracy, offset, length, isReadAccess, isWriteAccess, insideDocComment, participant, resource);
-}
-
-public SearchMatch newMethodReferenceMatch(
- IJavaScriptElement enclosingElement,
- Binding enclosingBinding,
- int accuracy,
- int offset,
- int length,
- boolean isConstructor,
- ASTNode reference) {
- SearchParticipant participant = getParticipant();
- IResource resource = this.currentPossibleMatch.resource;
- boolean insideDocComment = (reference.bits & ASTNode.InsideJavadoc) != 0;
- if (enclosingBinding != null)
- enclosingElement = ((JavaElement) enclosingElement).resolved(enclosingBinding);
- boolean isOverridden = (accuracy & PatternLocator.SUPER_INVOCATION_FLAVOR) != 0;
- return new MethodReferenceMatch(enclosingElement, accuracy, offset, length, isConstructor, isOverridden, insideDocComment, participant, resource);
-}
-
-public SearchMatch newPackageReferenceMatch(
- IJavaScriptElement enclosingElement,
- int accuracy,
- int offset,
- int length,
- ASTNode reference) {
- SearchParticipant participant = getParticipant();
- IResource resource = this.currentPossibleMatch.resource;
- boolean insideDocComment = (reference.bits & ASTNode.InsideJavadoc) != 0;
- return new PackageReferenceMatch(enclosingElement, accuracy, offset, length, insideDocComment, participant, resource);
-}
-
-public TypeReferenceMatch newTypeReferenceMatch(
- IJavaScriptElement enclosingElement,
- Binding enclosingBinding,
- int accuracy,
- int offset,
- int length,
- ASTNode reference) {
- SearchParticipant participant = getParticipant();
- IResource resource = this.currentPossibleMatch.resource;
- boolean insideDocComment = (reference.bits & ASTNode.InsideJavadoc) != 0;
- if (enclosingBinding != null)
- enclosingElement = ((JavaElement) enclosingElement).resolved(enclosingBinding);
- return new TypeReferenceMatch(enclosingElement, accuracy, offset, length, insideDocComment, participant, resource);
-}
-
-public TypeReferenceMatch newTypeReferenceMatch(
- IJavaScriptElement enclosingElement,
- Binding enclosingBinding,
- int accuracy,
- ASTNode reference) {
- return newTypeReferenceMatch(enclosingElement, enclosingBinding, accuracy, reference.sourceStart, reference.sourceEnd-reference.sourceStart+1, reference);
-}
-
-/**
- * Add the possibleMatch to the loop
- * -> build compilation unit declarations, their bindings and record their results.
- */
-protected boolean parseAndBuildBindings(PossibleMatch possibleMatch, boolean mustResolve) throws CoreException {
- if (this.progressMonitor != null && this.progressMonitor.isCanceled())
- throw new OperationCanceledException();
-
- try {
- if (BasicSearchEngine.VERBOSE)
- System.out.println("Parsing " + possibleMatch.openable.toStringWithAncestors()); //$NON-NLS-1$
-
- this.parser.nodeSet = possibleMatch.nodeSet;
- CompilationResult unitResult = new CompilationResult(possibleMatch, 1, 1, this.options.maxProblemsPerUnit);
- CompilationUnitDeclaration parsedUnit = this.parser.dietParse(possibleMatch, unitResult);
- if (parsedUnit != null) {
- this.parser.inferTypes(parsedUnit,this.options);
- if (!parsedUnit.isEmpty()) {
- if (mustResolve) {
- this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/);
- }
- if (hasAlreadyDefinedType(parsedUnit)) return false; // skip type has it is hidden so not visible
- getMethodBodies(parsedUnit, possibleMatch.nodeSet);
- if (this.patternLocator.mayBeGeneric && !mustResolve && possibleMatch.nodeSet.mustResolve) {
- // special case: possible match node set force resolution although pattern does not
- // => we need to build types for this compilation unit
- this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/);
- }
- }
-
- // add the possibleMatch with its parsedUnit to matchesToProcess
- possibleMatch.parsedUnit = parsedUnit;
- int size = this.matchesToProcess.length;
- if (this.numberOfMatches == size)
- System.arraycopy(this.matchesToProcess, 0, this.matchesToProcess = new PossibleMatch[size == 0 ? 1 : size * 2], 0, this.numberOfMatches);
- this.matchesToProcess[this.numberOfMatches++] = possibleMatch;
- }
- } finally {
- this.parser.nodeSet = null;
- }
- return true;
-}
-/*
- * Process a compilation unit already parsed and build.
- */
-protected void process(PossibleMatch possibleMatch, boolean bindingsWereCreated) throws CoreException {
- this.currentPossibleMatch = possibleMatch;
- CompilationUnitDeclaration unit = possibleMatch.parsedUnit;
- try {
- if (unit.isEmpty()) {
- if (this.currentPossibleMatch.openable instanceof ClassFile) {
- ClassFile classFile = (ClassFile) this.currentPossibleMatch.openable;
- IBinaryType info = getBinaryInfo(classFile, this.currentPossibleMatch.resource);
- if (info != null) {
- boolean mayBeGeneric = this.patternLocator.mayBeGeneric;
- this.patternLocator.mayBeGeneric = false; // there's no longer generics in class files
- try {
- new ClassFileMatchLocator().locateMatches(this, classFile, info);
- }
- finally {
- this.patternLocator.mayBeGeneric = mayBeGeneric;
- }
- }
- }
- return;
- }
- if (hasAlreadyDefinedType(unit)) return; // skip type has it is hidden so not visible
-
- // Move getMethodBodies to #parseAndBuildings(...) method to allow possible match resolution management
- //getMethodBodies(unit);
-
- boolean mustResolve = (((InternalSearchPattern)this.pattern).mustResolve || possibleMatch.nodeSet.mustResolve);
- if (bindingsWereCreated && mustResolve) {
- if (unit.types != null || unit.statements!=null) {
- if (BasicSearchEngine.VERBOSE)
- System.out.println("Resolving " + this.currentPossibleMatch.openable.toStringWithAncestors()); //$NON-NLS-1$
-
- this.lookupEnvironment.unitBeingCompleted = unit;
- reduceParseTree(unit);
-
- if (unit.scope != null) {
- // fault in fields & methods
- unit.scope.faultInTypes();
- }
- unit.resolve();
- } else if (unit.isPackageInfo()) {
- if (BasicSearchEngine.VERBOSE)
- System.out.println("Resolving " + this.currentPossibleMatch.openable.toStringWithAncestors()); //$NON-NLS-1$
- unit.resolve();
- }
- }
- reportMatching(unit, mustResolve);
- } catch (AbortCompilation e) {
- // could not resolve: report inaccurate matches
- reportMatching(unit, false); // do not resolve when cu has errors
- if (!(e instanceof AbortCompilationUnit)) {
- // problem with class path
- throw e;
- }
- } finally {
- this.lookupEnvironment.unitBeingCompleted = null;
- this.currentPossibleMatch = null;
- }
-}
-protected void purgeMethodStatements(TypeDeclaration type, boolean checkEachMethod) {
- checkEachMethod = checkEachMethod
- && this.currentPossibleMatch.nodeSet.hasPossibleNodes(type.declarationSourceStart, type.declarationSourceEnd);
- AbstractMethodDeclaration[] methods = type.methods;
- if (methods != null) {
- if (checkEachMethod) {
- for (int j = 0, length = methods.length; j < length; j++) {
- AbstractMethodDeclaration method = methods[j];
- purgeMethodStatements(method);
- }
- } else {
- for (int j = 0, length = methods.length; j < length; j++) {
- methods[j].statements = null;
- methods[j].javadoc = null;
- }
- }
- }
-
- TypeDeclaration[] memberTypes = type.memberTypes;
- if (memberTypes != null)
- for (int i = 0, l = memberTypes.length; i < l; i++)
- purgeMethodStatements(memberTypes[i], checkEachMethod);
-}
-
-private void purgeMethodStatements(AbstractMethodDeclaration method) {
- if (!this.currentPossibleMatch.nodeSet.hasPossibleNodes(method.declarationSourceStart, method.declarationSourceEnd)) {
- method.statements = null;
- method.javadoc = null;
- }
-}
-
-/**
- * Called prior to the unit being resolved. Reduce the parse tree where possible.
- */
-protected void reduceParseTree(CompilationUnitDeclaration unit) {
- // remove statements from methods that have no possible matching nodes
- if (unit.types!=null)
- {
- TypeDeclaration[] types = unit.types;
- for (int i = 0, l = types.length; i < l; i++)
- purgeMethodStatements(types[i], true);
- }
- if (unit.statements!=null)
- for (int i = 0; i < unit.statements.length; i++) {
- if (unit.statements[i] instanceof AbstractMethodDeclaration)
- purgeMethodStatements((AbstractMethodDeclaration)unit.statements[i]);
- }
-
-}
-public SearchParticipant getParticipant() {
- return this.currentPossibleMatch.document.getParticipant();
-}
-
-protected void report(SearchMatch match) throws CoreException {
- long start = -1;
- if (BasicSearchEngine.VERBOSE) {
- start = System.currentTimeMillis();
- System.out.println("Reporting match"); //$NON-NLS-1$
- System.out.println("\tResource: " + match.getResource());//$NON-NLS-1$
- System.out.println("\tPositions: [offset=" + match.getOffset() + ", length=" + match.getLength() + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- try {
- if (this.parser != null && match.getOffset() > 0 && match.getLength() > 0 && !(match.getElement() instanceof BinaryMember)) {
- String selection = new String(this.parser.scanner.source, match.getOffset(), match.getLength());
- System.out.println("\tSelection: -->" + selection + "<--"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- } catch (Exception e) {
- // it's just for debug purposes... ignore all exceptions in this area
- }
- try {
- JavaElement javaElement = (JavaElement)match.getElement();
- System.out.println("\tJava element: "+ javaElement.toStringWithAncestors()); //$NON-NLS-1$
- if (!javaElement.exists()) {
- System.out.println("\t\tWARNING: this element does NOT exist!"); //$NON-NLS-1$
- }
- } catch (Exception e) {
- // it's just for debug purposes... ignore all exceptions in this area
- }
- if (match instanceof TypeReferenceMatch) {
- try {
- TypeReferenceMatch typeRefMatch = (TypeReferenceMatch) match;
- JavaElement local = (JavaElement) typeRefMatch.getLocalElement();
- if (local != null) {
- System.out.println("\tLocal element: "+ local.toStringWithAncestors()); //$NON-NLS-1$
- }
- IJavaScriptElement[] others = typeRefMatch.getOtherElements();
- if (others != null) {
- int length = others.length;
- if (length > 0) {
- System.out.println("\tOther elements:"); //$NON-NLS-1$
- for (int i=0; i<length; i++) {
- JavaElement other = (JavaElement) others[i];
- System.out.println("\t\t- "+ other.toStringWithAncestors()); //$NON-NLS-1$
- }
- }
- }
- } catch (Exception e) {
- // it's just for debug purposes... ignore all exceptions in this area
- }
- }
- System.out.println(match.getAccuracy() == SearchMatch.A_ACCURATE
- ? "\tAccuracy: EXACT_MATCH" //$NON-NLS-1$
- : "\tAccuracy: POTENTIAL_MATCH"); //$NON-NLS-1$
- System.out.print("\tRule: "); //$NON-NLS-1$
- if (match.isExact()) {
- System.out.print("EXACT"); //$NON-NLS-1$
- } else if (match.isEquivalent()) {
- System.out.print("EQUIVALENT"); //$NON-NLS-1$
- } else if (match.isErasure()) {
- System.out.print("ERASURE"); //$NON-NLS-1$
- } else {
- System.out.print("INVALID RULE"); //$NON-NLS-1$
- }
- if (match instanceof MethodReferenceMatch) {
- MethodReferenceMatch methodReferenceMatch = (MethodReferenceMatch) match;
- if (methodReferenceMatch.isSuperInvocation()) {
- System.out.print("+SUPER INVOCATION"); //$NON-NLS-1$
- }
- if (methodReferenceMatch.isImplicit()) {
- System.out.print("+IMPLICIT"); //$NON-NLS-1$
- }
- }
- System.out.println("\n\tRaw: "+match.isRaw()); //$NON-NLS-1$
- }
- this.requestor.acceptSearchMatch(match);
- if (BasicSearchEngine.VERBOSE)
- this.resultCollectorTime += System.currentTimeMillis()-start;
-}
-/**
- * Finds the accurate positions of the sequence of tokens given by qualifiedName
- * in the source and reports a reference to this this qualified name
- * to the search requestor.
- */
-protected void reportAccurateTypeReference(SearchMatch match, ASTNode typeRef, char[] name) throws CoreException {
- if (match.getRule() == 0) return;
- if (!encloses((IJavaScriptElement)match.getElement())) return;
-
- // Compute source positions of the qualified reference
- int sourceStart = typeRef.sourceStart;
- int sourceEnd = typeRef.sourceEnd;
- Scanner scanner = this.parser.scanner;
- scanner.setSource(this.currentPossibleMatch.getContents());
- scanner.resetTo(sourceStart, sourceEnd);
-
- int token = -1;
- int currentPosition;
- do {
- currentPosition = scanner.currentPosition;
- try {
- token = scanner.getNextToken();
- } catch (InvalidInputException e) {
- // ignore
- }
- if (token == TerminalTokens.TokenNameIdentifier && this.pattern.matchesName(name, scanner.getCurrentTokenSource())) {
- int length = scanner.currentPosition-currentPosition;
- match.setOffset(currentPosition);
- match.setLength(length);
- report(match);
- return;
- }
- } while (token != TerminalTokens.TokenNameEOF);
-
- // Report match
- match.setOffset(sourceStart);
- match.setLength(sourceEnd-sourceStart+1);
- report(match);
-}
-
-/**
- * Finds the accurate positions of the sequence of tokens given by qualifiedName
- * in the source and reports a reference to this parameterized type name
- * to the search requestor.
- * @since 3.1
- */
-protected void reportAccurateParameterizedMethodReference(SearchMatch match, ASTNode statement, TypeReference[] typeArguments) throws CoreException {
- if (match.getRule() == 0) return;
- if (!encloses((IJavaScriptElement)match.getElement())) return;
-
- // If there's type arguments, look for end (ie. char '>') of last one.
- int start = match.getOffset();
- if (typeArguments != null && typeArguments.length > 0) {
- boolean isErasureMatch= (pattern instanceof OrPattern) ? ((OrPattern)pattern).isErasureMatch() : ((JavaSearchPattern)pattern).isErasureMatch();
- if (!isErasureMatch) {
-
- // Initialize scanner
- Scanner scanner = this.parser.scanner;
- char[] source = this.currentPossibleMatch.getContents();
- scanner.setSource(source);
-
- // Search previous opening '<'
- start = typeArguments[0].sourceStart;
- int end = statement.sourceEnd;
- scanner.resetTo(start, end);
- int lineStart = start;
- try {
- linesUp: while (true) {
- while (scanner.source[scanner.currentPosition] != '\n') {
- scanner.currentPosition--;
- if (scanner.currentPosition == 0) break linesUp;
- }
- lineStart = scanner.currentPosition+1;
- scanner.resetTo(lineStart, end);
- while (!scanner.atEnd()) {
- if (scanner.getNextToken() == TerminalTokens.TokenNameLESS) {
- start = scanner.getCurrentTokenStartPosition();
- break linesUp;
- }
- }
- end = lineStart - 2;
- scanner.currentPosition = end;
- }
- }
- catch (InvalidInputException ex) {
- // give up
- }
- }
- }
-
- // Report match
- match.setOffset(start);
- match.setLength(statement.sourceEnd-start+1);
- report(match);
-}
-
-/**
- * Finds the accurate positions of the sequence of tokens given by qualifiedName
- * in the source and reports a reference to this parameterized type name
- * to the search requestor.
- * @since 3.1
- */
-protected void reportAccurateParameterizedTypeReference(SearchMatch match, TypeReference typeRef, int index, TypeReference[] typeArguments) throws CoreException {
- if (match.getRule() == 0) return;
- if (!encloses((IJavaScriptElement)match.getElement())) return;
-
- // If there's type arguments, look for end (ie. char '>') of last one.
- int end = typeRef.sourceEnd;
- if (typeArguments != null) {
- // Initialize scanner
- Scanner scanner = this.parser.scanner;
- char[] source = this.currentPossibleMatch.getContents();
- scanner.setSource(source);
-
- boolean shouldMatchErasure= (pattern instanceof OrPattern) ? ((OrPattern)pattern).isErasureMatch() : ((JavaSearchPattern)pattern).isErasureMatch();
- boolean hasSignatures = (pattern instanceof OrPattern) ? ((OrPattern)pattern).hasSignatures() : ((JavaSearchPattern)pattern).hasSignatures();
- if (shouldMatchErasure || !hasSignatures) {
- // if pattern is erasure only, then select the end of the reference
- if (typeRef instanceof QualifiedTypeReference && index >= 0) {
- long[] positions = ((QualifiedTypeReference) typeRef).sourcePositions;
- end = (int) positions[index];
- } else if (typeRef instanceof ArrayTypeReference) {
- end = ((ArrayTypeReference) typeRef).originalSourceEnd;
- }
- } else {
- // Set scanner position at end of last type argument
- scanner.resetTo(end, source.length-1);
- int depth = 0;
- for (int i=typeArguments.length-1; i>=0; i--) {
- if (typeArguments[i] != null) {
- long lastTypeArgInfo = findLastTypeArgumentInfo(typeArguments[i]);
- depth = (int) (lastTypeArgInfo >>> 32)+1;
- scanner.resetTo(((int)lastTypeArgInfo)+1, scanner.eofPosition-1);
- break;
- }
- }
-
- // Now, scan to search next closing '>'
- while (depth-- > 0) {
- while (!scanner.atEnd()) {
- if (scanner.getNextChar() == '>') {
- end = scanner.currentPosition - 1;
- break;
- }
- }
- }
- }
- }
-
- // Report match
- match.setLength(end-match.getOffset()+1);
- report(match);
-}
-/**
- * Finds the accurate positions of each valid token in the source and
- * reports a reference to this token to the search requestor.
- * A token is valid if it has an accuracy which is not -1.
- */
-protected void reportAccurateEnumConstructorReference(SearchMatch match, FieldDeclaration field, AllocationExpression allocation) throws CoreException {
- report(match);
- return;
-}
-/**
- * Finds the accurate positions of each valid token in the source and
- * reports a reference to this token to the search requestor.
- * A token is valid if it has an accuracy which is not -1.
- */
-protected void reportAccurateFieldReference(SearchMatch[] matches, QualifiedNameReference qNameRef) throws CoreException {
- if (matches == null) return; // there's nothing to accurate in this case
- int matchesLength = matches.length;
-
- int sourceStart = qNameRef.sourceStart;
- int sourceEnd = qNameRef.sourceEnd;
- char[][] tokens = qNameRef.tokens;
-
- // compute source positions of the qualified reference
- Scanner scanner = this.parser.scanner;
- scanner.setSource(this.currentPossibleMatch.getContents());
- scanner.resetTo(sourceStart, sourceEnd);
- int sourceLength = sourceEnd-sourceStart+1;
-
- int refSourceStart = -1, refSourceEnd = -1;
- int length = tokens.length;
- int token = -1;
- int previousValid = -1;
- int i = 0;
- int index = 0;
- do {
- int currentPosition = scanner.currentPosition;
- // read token
- try {
- token = scanner.getNextToken();
- } catch (InvalidInputException e) {
- //ignore
- }
- if (token != TerminalTokens.TokenNameEOF) {
- char[] currentTokenSource = scanner.getCurrentTokenSource();
- boolean equals = false;
- while (i < length && !(equals = this.pattern.matchesName(tokens[i++], currentTokenSource))){/*empty*/}
- if (equals && (previousValid == -1 || previousValid == i - 2)) {
- previousValid = i - 1;
- if (refSourceStart == -1)
- refSourceStart = currentPosition;
- refSourceEnd = scanner.currentPosition - 1;
- } else {
- i = 0;
- refSourceStart = -1;
- previousValid = -1;
- }
- // read '.'
- try {
- token = scanner.getNextToken();
- } catch (InvalidInputException e) {
- // ignore
- }
- }
- SearchMatch match = matches[index];
- if (match != null && match.getRule() != 0) {
- if (!encloses((IJavaScriptElement)match.getElement())) return;
- // accept reference
- if (refSourceStart != -1) {
- match.setOffset(refSourceStart);
- match.setLength(refSourceEnd-refSourceStart+1);
- report(match);
- } else {
- match.setOffset(sourceStart);
- match.setLength(sourceLength);
- report(match);
- }
- i = 0;
- }
- refSourceStart = -1;
- previousValid = -1;
- if (index < matchesLength - 1) {
- index++;
- }
- } while (token != TerminalTokens.TokenNameEOF);
-
-}
-protected void reportBinaryMemberDeclaration(IResource resource, IMember binaryMember, Binding binaryMemberBinding, IBinaryType info, int accuracy) throws CoreException {
- ClassFile classFile = (ClassFile) binaryMember.getClassFile();
- ISourceRange range = classFile.isOpen() ? binaryMember.getNameRange() : SourceMapper.UNKNOWN_RANGE;
- if (range.getOffset() == -1) {
- BinaryType type = (BinaryType) classFile.getType();
- String sourceFileName = type.sourceFileName(info);
- if (sourceFileName != null) {
- SourceMapper mapper = classFile.getSourceMapper();
- if (mapper != null) {
- char[] contents = mapper.findSource(type, sourceFileName);
- if (contents != null)
- range = mapper.mapSource(type, contents, info, binaryMember);
- }
- }
- }
- if (resource == null) resource = this.currentPossibleMatch.resource;
- SearchMatch match = newDeclarationMatch(binaryMember, binaryMemberBinding, accuracy, range.getOffset(), range.getLength(), getParticipant(), resource);
- report(match);
-}
-/**
- * Visit the given method declaration and report the nodes that match exactly the
- * search pattern (ie. the ones in the matching nodes set)
- * Note that the method declaration has already been checked.
- */
-protected void reportMatching(TypeDeclaration type, AbstractMethodDeclaration method, IJavaScriptElement parent, int accuracy, boolean typeInHierarchy, MatchingNodeSet nodeSet) throws CoreException {
- IJavaScriptElement enclosingElement = null;
- if (accuracy > -1) {
- enclosingElement = createHandle(method, parent);
- if (enclosingElement != null) { // skip if unable to find method
- // compute source positions of the selector
- Scanner scanner = parser.scanner;
- int nameSourceStart = method.sourceStart;
- scanner.setSource(this.currentPossibleMatch.getContents());
- scanner.resetTo(nameSourceStart, method.sourceEnd);
- try {
- scanner.getNextToken();
- } catch (InvalidInputException e) {
- // ignore
- }
- if (encloses(enclosingElement)) {
- SearchMatch match = null;
- if (method.isDefaultConstructor()) {
- // Use type for match associated element as default constructor does not exist in source
- int offset = type.sourceStart;
- 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);
- }
- if (match != null) {
- report(match);
- }
- }
- }
- }
-
- // handle nodes for the local type first
- if ((method.bits & ASTNode.HasLocalType) != 0) {
- if (enclosingElement == null)
- enclosingElement = createHandle(method, parent);
- LocalDeclarationVisitor localDeclarationVisitor = new LocalDeclarationVisitor(enclosingElement, method.binding, nodeSet);
- try {
- method.traverse(localDeclarationVisitor, (ClassScope) null);
- } catch (WrappedCoreException e) {
- throw e.coreException;
- }
- }
-
- // references in this method
- if (typeInHierarchy) {
- ASTNode[] nodes = nodeSet.matchingNodes(method.declarationSourceStart, method.declarationSourceEnd);
- if (nodes != null) {
- if ((this.matchContainer & PatternLocator.METHOD_CONTAINER) != 0) {
- if (enclosingElement == null)
- enclosingElement = createHandle(method, parent);
- if (encloses(enclosingElement)) {
- 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);
- }
- return;
- }
- }
- for (int i = 0, l = nodes.length; i < l; i++)
- nodeSet.matchingNodes.removeKey(nodes[i]);
- }
- }
-}
-/**
- * Visit the given resolved parse tree and report the nodes that match the search pattern.
- */
-protected void reportMatching(CompilationUnitDeclaration unit, boolean mustResolve) throws CoreException {
- MatchingNodeSet nodeSet = this.currentPossibleMatch.nodeSet;
- boolean locatorMustResolve = this.patternLocator.mustResolve;
- if (nodeSet.mustResolve) this.patternLocator.mustResolve = true;
- if (BasicSearchEngine.VERBOSE) {
- System.out.println("Report matching: "); //$NON-NLS-1$
- int size = nodeSet.matchingNodes==null ? 0 : nodeSet.matchingNodes.elementSize;
- System.out.print(" - node set: accurate="+ size); //$NON-NLS-1$
- size = nodeSet.possibleMatchingNodesSet==null ? 0 : nodeSet.possibleMatchingNodesSet.elementSize;
- System.out.println(", possible="+size); //$NON-NLS-1$
- System.out.print(" - must resolve: "+mustResolve); //$NON-NLS-1$
- System.out.print(" (locator: "+this.patternLocator.mustResolve); //$NON-NLS-1$
- System.out.println(", nodeSet: "+nodeSet.mustResolve+')'); //$NON-NLS-1$
- }
- if (mustResolve) {
- this.unitScope= unit.scope.compilationUnitScope();
- // move the possible matching nodes that exactly match the search pattern to the matching nodes set
- Object[] nodes = nodeSet.possibleMatchingNodesSet.values;
- for (int i = 0, l = nodes.length; i < l; i++) {
- ASTNode node = (ASTNode) nodes[i];
- if (node == null) continue;
- if (node instanceof ImportReference) {
- // special case for import refs: they don't know their binding
- // import ref cannot be in the hierarchy of a type
- if (this.hierarchyResolver != null) continue;
-
- ImportReference importRef = (ImportReference) node;
- Binding binding = (importRef.bits & ASTNode.OnDemand) != 0
- ? unitScope.getImport(CharOperation.subarray(importRef.tokens, 0, importRef.tokens.length), true)
- : unitScope.getImport(importRef.tokens, false);
- this.patternLocator.matchLevelAndReportImportRef(importRef, binding, this);
- }
- nodeSet.addMatch(node, this.patternLocator.resolveLevel(node));
- }
- nodeSet.possibleMatchingNodesSet = new SimpleSet(3);
- if (BasicSearchEngine.VERBOSE) {
- int size = nodeSet.matchingNodes==null ? 0 : nodeSet.matchingNodes.elementSize;
- System.out.print(" - node set: accurate="+size); //$NON-NLS-1$
- size = nodeSet.possibleMatchingNodesSet==null ? 0 : nodeSet.possibleMatchingNodesSet.elementSize;
- System.out.println(", possible="+size); //$NON-NLS-1$
- }
- } else {
- this.unitScope = null;
- }
-
- if (nodeSet.matchingNodes.elementSize == 0) return; // no matching nodes were found
- this.methodHandles = new HashSet();
-
- boolean matchedUnitContainer = (this.matchContainer & PatternLocator.COMPILATION_UNIT_CONTAINER) != 0;
-
- // report references in javadoc
- if (unit.javadoc != null) {
- ASTNode[] nodes = nodeSet.matchingNodes(unit.javadoc.sourceStart, unit.javadoc.sourceEnd);
- if (nodes != null) {
- if (!matchedUnitContainer) {
- for (int i = 0, l = nodes.length; i < l; i++)
- nodeSet.matchingNodes.removeKey(nodes[i]);
- } else {
- IJavaScriptElement element = null;
- for (int i = 0, l = nodes.length; i < l; i++) {
- ASTNode node = nodes[i];
- Integer level = (Integer) nodeSet.matchingNodes.removeKey(node);
- if (encloses(element))
- this.patternLocator.matchReportReference(node, element, null/*no binding*/, level.intValue(), this);
- }
- }
- }
- }
-
- if (matchedUnitContainer) {
- ImportReference[] imports = unit.imports;
- if (imports != null) {
- for (int i = 0, l = imports.length; i < l; i++) {
- ImportReference importRef = imports[i];
- Integer level = (Integer) nodeSet.matchingNodes.removeKey(importRef);
- if (level != null)
- this.patternLocator.matchReportImportRef(importRef, null/*no binding*/, createImportHandle(importRef), level.intValue(), this);
- }
- }
- }
-
- TypeDeclaration[] types = unit.types;
- if (types != null) {
- for (int i = 0, l = types.length; i < l; i++) {
- if (nodeSet.matchingNodes.elementSize == 0) return; // reported all the matching nodes
- TypeDeclaration type = types[i];
- Integer level = (Integer) nodeSet.matchingNodes.removeKey(type);
- int accuracy = (level != null && matchedUnitContainer) ? level.intValue() : -1;
- reportMatching(type, null, accuracy, nodeSet, 1);
- }
- }
- ProgramElement[] statements = unit.statements;
-
- if (statements!=null)
- {
- IJavaScriptElement enclosingElement = this.currentPossibleMatch.openable;
- if (enclosingElement == null) return;
-
- boolean typeInHierarchy = true;
- boolean matchedClassContainer=true;
- ReportMatchingVisitor reportMatchingVisitor = new ReportMatchingVisitor(nodeSet,matchedClassContainer,enclosingElement,typeInHierarchy);
- unit.traverse(reportMatchingVisitor, unit.scope);
-
- for (int i = 0; i < statements.length; i++) {
- if (nodeSet.matchingNodes.elementSize == 0) return; // reported all the matching nodes
- if (statements[i] instanceof AbstractMethodDeclaration) {//already handled
- } else if (statements[i] instanceof LocalDeclaration) {//already handled
- }
- else
- {
- ASTNode[] nodes = nodeSet.matchingNodes(statements[i].sourceStart, statements[i].sourceEnd);
- if (nodes != null) {
- if ((this.matchContainer & PatternLocator.COMPILATION_UNIT_CONTAINER) != 0) {
- if (encloses(enclosingElement)) {
- for (int j = 0, l = nodes.length; j < l; j++) {
- ASTNode node = nodes[j];
- Integer level = (Integer) nodeSet.matchingNodes.removeKey(node);
- int accuracy = (level != null && matchedClassContainer) ? level.intValue() : -1;
- this.patternLocator.matchReportReference(node, enclosingElement, unit.compilationUnitBinding, unit.scope, accuracy, this);
- }
-// return;
- }
- }
- for (int j = 0, l = nodes.length; j < l; j++)
- nodeSet.matchingNodes.removeKey(nodes[j]);
- }
- }
-
- }
- }
- for (int i=0;i<unit.numberInferredTypes;i++) {
- InferredType inferredType = unit.inferredTypes[i];
- IJavaScriptElement enclosingElement = this.currentPossibleMatch.openable;
- if (enclosingElement == null) return;
- boolean typeInHierarchy = true;
- boolean matchedClassContainer=true;
- enclosingElement=((ITypeRoot)enclosingElement).getType(new String(inferredType.getName()));
-
- Integer level = (Integer) nodeSet.matchingNodes.removeKey(inferredType);
- int accuracy = (level != null && matchedClassContainer) ? level.intValue() : -1;
- reportMatching(inferredType, null, accuracy, nodeSet, 1);
-
- for (int attributeInx=0; attributeInx<inferredType.numberAttributes; attributeInx++) {
- InferredAttribute attribute = inferredType.attributes[attributeInx];
- level = (Integer) nodeSet.matchingNodes.removeKey(attribute);
- accuracy = (level != null && matchedClassContainer) ? level.intValue() : -1;
- reportMatching(attribute, inferredType, enclosingElement, accuracy, typeInHierarchy, nodeSet);
-
- }
- ArrayList methods = inferredType.methods;
- if (methods!=null)
- for (Iterator iterator = methods.iterator(); iterator.hasNext();) {
- InferredMethod method = (InferredMethod) iterator.next();
- level = (Integer) nodeSet.matchingNodes.removeKey(method);
- accuracy = (level != null && matchedClassContainer) ? level.intValue() : -1;
- int value = (level != null && matchedClassContainer) ? level.intValue() : -1;
- reportMatching(null, (AbstractMethodDeclaration) method.getFunctionDeclaration(), enclosingElement, value, typeInHierarchy, nodeSet);
-
- }
- }
-
-
- // Clear handle cache
- this.methodHandles = null;
- this.bindings.removeKey(this.pattern);
- this.patternLocator.mustResolve = locatorMustResolve;
-}
-/**
- * Visit the given field declaration and report the nodes that match exactly the
- * search pattern (ie. the ones in the matching nodes set)
- */
-protected void reportMatching(FieldDeclaration field, FieldDeclaration[] otherFields, TypeDeclaration type, IJavaScriptElement parent, int accuracy, boolean typeInHierarchy, MatchingNodeSet nodeSet) throws CoreException {
- IJavaScriptElement enclosingElement = null;
- if (accuracy > -1) {
- enclosingElement = createHandle(field, type, parent);
- if (encloses(enclosingElement)) {
- int offset = field.sourceStart;
- SearchMatch match = newDeclarationMatch(enclosingElement, field.binding, accuracy, offset, field.sourceEnd-offset+1);
- if (field.initialization instanceof AllocationExpression) {
- reportAccurateEnumConstructorReference(match, field, (AllocationExpression) field.initialization);
- } else {
- report(match);
- }
- }
- }
-
- // handle the nodes for the local type first
- if ((field.bits & ASTNode.HasLocalType) != 0) {
- if (enclosingElement == null)
- enclosingElement = createHandle(field, type, parent);
- LocalDeclarationVisitor localDeclarationVisitor = new LocalDeclarationVisitor(enclosingElement, field.binding, nodeSet);
- try {
- field.traverse(localDeclarationVisitor, null);
- } catch (WrappedCoreException e) {
- throw e.coreException;
- }
- }
-
- if (typeInHierarchy) {
- // Look at field declaration
- if (field.endPart1Position != 0) { // not necessary if field is an initializer
- ASTNode[] nodes = nodeSet.matchingNodes(field.declarationSourceStart, field.endPart1Position);
- 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 (enclosingElement == null)
- enclosingElement = createHandle(field, type, parent);
- if (encloses(enclosingElement)) {
- for (int i = 0, l = nodes.length; i < l; i++) {
- ASTNode node = nodes[i];
- Integer level = (Integer) nodeSet.matchingNodes.removeKey(node);
- IJavaScriptElement[] otherElements = null;
- if (otherFields != null) {
- int length = otherFields.length;
- int size = 0;
- while (size<length && otherFields[size] != null) {
- size++;
- }
- otherElements = new IJavaScriptElement[size];
- for (int j=0; j<size; j++) {
- otherElements[j] = createHandle(otherFields[j], type, parent);
- }
- }
- this.patternLocator.matchReportReference(node, enclosingElement, null, otherElements, field.binding, level.intValue(), this);
- }
- }
- }
- }
- }
-
- // Look in initializer
- int fieldEnd = field.endPart2Position == 0 ? field.declarationSourceEnd : field.endPart2Position;
- ASTNode[] nodes = nodeSet.matchingNodes(field.sourceStart, fieldEnd);
- 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 (enclosingElement == null) {
- enclosingElement = createHandle(field, type, parent);
- }
- if (encloses(enclosingElement)) {
- for (int i = 0, l = nodes.length; i < l; i++) {
- ASTNode node = nodes[i];
- Integer level = (Integer) nodeSet.matchingNodes.removeKey(node);
- // Set block scope for initializer in case there would have other local and other elements to report
- BlockScope blockScope = null;
- if (field.getKind() == AbstractVariableDeclaration.INITIALIZER) {
- Block block = ((Initializer)field).block;
- if (block != null) blockScope = block.scope;
- }
- this.patternLocator.matchReportReference(node, enclosingElement, field.binding, blockScope, level.intValue(), this);
- }
- }
- }
- }
- }
-}
-
-
-protected void reportMatching(InferredAttribute field, InferredType type, IJavaScriptElement parent, int accuracy, boolean typeInHierarchy, MatchingNodeSet nodeSet) throws CoreException {
- IJavaScriptElement enclosingElement = null;
- if (accuracy > -1) {
- enclosingElement = createHandle(field, type, parent);
- if (encloses(enclosingElement)) {
- int offset = field.sourceStart;
- SearchMatch match = newDeclarationMatch(enclosingElement, field.binding, accuracy, offset, field.sourceEnd-offset+1);
- report(match);
- }
- }
-
-
-}
-
-protected void reportMatching(InferredType type, IJavaScriptElement parent, int accuracy, MatchingNodeSet nodeSet, int occurrenceCount) throws CoreException {
- // create type handle
- IJavaScriptElement enclosingElement = parent;
- if (enclosingElement == null) {
- enclosingElement = createTypeHandle(new String(type.getName()));
- } else if (enclosingElement instanceof IType) {
- enclosingElement = ((IType) parent).getType(new String(type.getName()));
- } else if (enclosingElement instanceof IMember) {
- IMember member = (IMember) parent;
- if (member.isBinary()) {
- enclosingElement = ((IClassFile)this.currentPossibleMatch.openable).getType();
- } else {
- enclosingElement = member.getType(new String(type.getName()), occurrenceCount);
- }
- }
- if (enclosingElement == null) return;
- boolean enclosesElement = encloses(enclosingElement);
-
- // report the type declaration
- if (accuracy > -1 && enclosesElement) {
- int offset = type.sourceStart;
- SearchMatch match = this.patternLocator.newDeclarationMatch(type, enclosingElement, type.binding, accuracy, type.sourceEnd-offset+1, this);
- report(match);
- }
-
-// boolean matchedClassContainer = (this.matchContainer & PatternLocator.CLASS_CONTAINER) != 0;
-
-}
-
-
-protected void reportMatching( IJavaScriptElement enclosingElement, int accuracy, MatchingNodeSet nodeSet, int occurrenceCount) throws CoreException {
- // create type handle
- if (enclosingElement == null) return;
- boolean enclosesElement = encloses(enclosingElement);
-
- // report the type declaration
- if (accuracy > -1 && enclosesElement) {
- int offset = 0;//element.g;
- int elementLength=0;
- SearchMatch match = this.patternLocator.newDeclarationMatch(null, enclosingElement, null, accuracy, elementLength, this);
- report(match);
- }
-
-// boolean matchedClassContainer = (this.matchContainer & PatternLocator.CLASS_CONTAINER) != 0;
-
-}
-
-
-protected void reportMatching(LocalDeclaration field, LocalDeclaration[] otherFields, TypeDeclaration type, IJavaScriptElement parent, int accuracy, boolean typeInHierarchy, MatchingNodeSet nodeSet) throws CoreException {
- IJavaScriptElement enclosingElement = null;
- if (accuracy > -1) {
- enclosingElement = createHandle(field, parent);
- if (encloses(enclosingElement)) {
- int offset = field.sourceStart;
- SearchMatch match = newDeclarationMatch(enclosingElement, field.binding, accuracy, offset, field.sourceEnd-offset+1);
- report(match);
- }
- }
-
-
- if (typeInHierarchy) {
- // 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 (enclosingElement == null) {
- enclosingElement = createHandle(field, parent);
- }
- if (encloses(enclosingElement)) {
- for (int i = 0, l = nodes.length; i < l; i++) {
- ASTNode node = nodes[i];
- Integer level = (Integer) nodeSet.matchingNodes.removeKey(node);
- // Set block scope for initializer in case there would have other local and other elements to report
- BlockScope blockScope = null;
- this.patternLocator.matchReportReference(node, enclosingElement, field.binding, blockScope, level.intValue(), this);
- }
- }
- }
- }
- }
-}
-
-
-/**
- * Visit the given type declaration and report the nodes that match exactly the
- * search pattern (ie. the ones in the matching nodes set)
- */
-protected void reportMatching(TypeDeclaration type, IJavaScriptElement parent, int accuracy, MatchingNodeSet nodeSet, int occurrenceCount) throws CoreException {
- // create type handle
- IJavaScriptElement enclosingElement = parent;
- if (enclosingElement == null) {
- enclosingElement = createTypeHandle(new String(type.name));
- } else if (enclosingElement instanceof IType) {
- enclosingElement = ((IType) parent).getType(new String(type.name));
- } else if (enclosingElement instanceof IMember) {
- IMember member = (IMember) parent;
- if (member.isBinary()) {
- enclosingElement = ((IClassFile)this.currentPossibleMatch.openable).getType();
- } else {
- enclosingElement = member.getType(new String(type.name), occurrenceCount);
- }
- }
- if (enclosingElement == null) return;
- boolean enclosesElement = encloses(enclosingElement);
-
- // report the type declaration
- if (accuracy > -1 && enclosesElement) {
- int offset = type.sourceStart;
- SearchMatch match = this.patternLocator.newDeclarationMatch(type, enclosingElement, type.binding, accuracy, type.sourceEnd-offset+1, this);
- report(match);
- }
-
- boolean matchedClassContainer = (this.matchContainer & PatternLocator.CLASS_CONTAINER) != 0;
-
- // report references in javadoc
- if (type.javadoc != null) {
- ASTNode[] nodes = nodeSet.matchingNodes(type.declarationSourceStart, type.sourceStart);
- if (nodes != null) {
- if (!matchedClassContainer) {
- for (int i = 0, l = nodes.length; i < l; i++)
- nodeSet.matchingNodes.removeKey(nodes[i]);
- } else {
- for (int i = 0, l = nodes.length; i < l; i++) {
- ASTNode node = nodes[i];
- Integer level = (Integer) nodeSet.matchingNodes.removeKey(node);
- if (enclosesElement) {
- this.patternLocator.matchReportReference(node, enclosingElement, type.binding, level.intValue(), this);
- }
- }
- }
- }
- }
-
- // super types
- if ((type.bits & ASTNode.IsAnonymousType) != 0) {
- TypeReference superType =type.allocation.type;
- if (superType != null) {
- Integer level = (Integer) nodeSet.matchingNodes.removeKey(superType);
- if (level != null && matchedClassContainer)
- this.patternLocator.matchReportReference(superType, enclosingElement, type.binding, level.intValue(), this);
- }
- } else {
- TypeReference superClass = type.superclass;
- if (superClass != null) {
- reportMatchingSuper(superClass, enclosingElement, type.binding, nodeSet, matchedClassContainer);
- }
- }
-
- // filter out element not in hierarchy scope
- boolean typeInHierarchy = type.binding == null || typeInHierarchy(type.binding);
- matchedClassContainer = matchedClassContainer && typeInHierarchy;
-
- // Visit fields
- FieldDeclaration[] fields = type.fields;
- if (fields != null) {
- if (nodeSet.matchingNodes.elementSize == 0) return; // end as all matching nodes were reported
- FieldDeclaration[] otherFields = null;
- int first = -1;
- int length = fields.length;
- for (int i = 0; i < length; i++) {
- FieldDeclaration field = fields[i];
- boolean last = field.endPart2Position == 0 || field.declarationEnd == field.endPart2Position;
- // Store first index of multiple field declaration
- if (!last) {
- if (first == -1) {
- first = i;
- }
- }
- if (first >= 0) {
- // Store all multiple fields but first one for other elements
- if (i > first) {
- if (otherFields == null) {
- otherFields = new FieldDeclaration[length-i];
- }
- otherFields[i-1-first] = field;
- }
- // On last field, report match with all other elements
- if (last) {
- for (int j=first; j<=i; j++) {
- Integer level = (Integer) nodeSet.matchingNodes.removeKey(fields[j]);
- int value = (level != null && matchedClassContainer) ? level.intValue() : -1;
- reportMatching(fields[j], otherFields, type, enclosingElement, value, typeInHierarchy, nodeSet);
- }
- first = -1;
- otherFields = null;
- }
- } else {
- // Single field, report normally
- Integer level = (Integer) nodeSet.matchingNodes.removeKey(field);
- int value = (level != null && matchedClassContainer) ? level.intValue() : -1;
- reportMatching(field, null, type, enclosingElement, value, typeInHierarchy, nodeSet);
- }
- }
- }
-
- // Visit methods
- AbstractMethodDeclaration[] methods = type.methods;
- if (methods != null) {
- if (nodeSet.matchingNodes.elementSize == 0) return; // end as all matching nodes were reported
- for (int i = 0, l = methods.length; i < l; i++) {
- AbstractMethodDeclaration method = methods[i];
- Integer level = (Integer) nodeSet.matchingNodes.removeKey(method);
- int value = (level != null && matchedClassContainer) ? level.intValue() : -1;
- reportMatching(type, method, enclosingElement, value, typeInHierarchy, nodeSet);
- }
- }
-
- // Visit types
- TypeDeclaration[] memberTypes = type.memberTypes;
- if (memberTypes != null) {
- for (int i = 0, l = memberTypes.length; i < l; i++) {
- if (nodeSet.matchingNodes.elementSize == 0) return; // end as all matching nodes were reported
- TypeDeclaration memberType = memberTypes[i];
- Integer level = (Integer) nodeSet.matchingNodes.removeKey(memberType);
- int value = (level != null && matchedClassContainer) ? level.intValue() : -1;
- reportMatching(memberType, enclosingElement, value, nodeSet, 1);
- }
- }
-}
-protected void reportMatchingSuper(TypeReference superReference, IJavaScriptElement enclosingElement, Binding elementBinding, MatchingNodeSet nodeSet, boolean matchedClassContainer) throws CoreException {
- ASTNode[] nodes = null;
- if (nodes != null) {
- if ((this.matchContainer & PatternLocator.CLASS_CONTAINER) == 0) {
- for (int i = 0, l = nodes.length; i < l; i++)
- nodeSet.matchingNodes.removeKey(nodes[i]);
- } else {
- if (encloses(enclosingElement))
- 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, elementBinding, level.intValue(), this);
- }
- }
- } else {
- Integer level = (Integer) nodeSet.matchingNodes.removeKey(superReference);
- if (level != null && matchedClassContainer)
- this.patternLocator.matchReportReference(superReference, enclosingElement, elementBinding, level.intValue(), this);
- }
-}
-protected boolean typeInHierarchy(ReferenceBinding binding) {
- if (this.hierarchyResolver == null) return true; // not a hierarchy scope
- if (this.hierarchyResolver.subOrSuperOfFocus(binding)) return true;
-
- if (this.allSuperTypeNames != null) {
- char[][] compoundName = binding.compoundName;
- for (int i = 0, length = this.allSuperTypeNames.length; i < length; i++)
- if (CharOperation.equals(compoundName, this.allSuperTypeNames[i]))
- return true;
- }
- return false;
-}
-
-public CompilationUnitDeclaration doParse(ICompilationUnit unit, AccessRestriction accessRestriction) {
- CompilationResult unitResult =
- new CompilationResult(unit, 1, 1, this.options.maxProblemsPerUnit);
- try {
- Parser parser=basicParser();
- CompilationUnitDeclaration parsedUnit = parser.parse(unit, unitResult);
- parser.inferTypes(parsedUnit,this.options);
- 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
-// }
- }
-
-}
-}
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
deleted file mode 100644
index fb9ad9b5..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MatchLocatorParser.java
+++ /dev/null
@@ -1,366 +0,0 @@
-/*******************************************************************************
- * 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.search.matching;
-
-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.ASTVisitor;
-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.CompilationUnitDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ConstructorDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Expression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Initializer;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocAllocationExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocArgumentExpression;
-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.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.NameReference;
-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.TypeDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-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.parser.Parser;
-import org.eclipse.wst.jsdt.internal.compiler.problem.ProblemReporter;
-
-/**
- * A parser that locates ast nodes that match a given search pattern.
- */
-public class MatchLocatorParser extends Parser {
-
-MatchingNodeSet nodeSet;
-PatternLocator patternLocator;
-private ASTVisitor localDeclarationVisitor;
-
-public static MatchLocatorParser createParser(ProblemReporter problemReporter, MatchLocator locator) {
- return new MatchLocatorParser(problemReporter, locator);
-}
-
-/**
- * An ast visitor that visits local type declarations.
- */
-public class NoClassNoMethodDeclarationVisitor extends ASTVisitor {
- public boolean visit(ConstructorDeclaration constructorDeclaration, Scope scope) {
- return (constructorDeclaration.bits & ASTNode.HasLocalType) != 0; // continue only if it has local type
- }
- public boolean visit(FieldDeclaration fieldDeclaration, MethodScope scope) {
- return (fieldDeclaration.bits & ASTNode.HasLocalType) != 0; // continue only if it has local type;
- }
- public boolean visit(Initializer initializer, MethodScope scope) {
- return (initializer.bits & ASTNode.HasLocalType) != 0; // continue only if it has local type
- }
- public boolean visit(MethodDeclaration methodDeclaration, Scope scope) {
- return (methodDeclaration.bits & ASTNode.HasLocalType) != 0; // continue only if it has local type
- }
-}
-public class MethodButNoClassDeclarationVisitor extends NoClassNoMethodDeclarationVisitor {
- public boolean visit(TypeDeclaration localTypeDeclaration, Scope scope) {
- patternLocator.match(localTypeDeclaration, nodeSet);
- return true;
- }
- public boolean visit(InferredType localTypeDeclaration, BlockScope scope) {
- patternLocator.match(localTypeDeclaration, nodeSet);
- return true;
- }
-}
-public class ClassButNoMethodDeclarationVisitor extends ASTVisitor {
- public boolean visit(ConstructorDeclaration constructorDeclaration, Scope scope) {
- patternLocator.match(constructorDeclaration, nodeSet);
- return (constructorDeclaration.bits & ASTNode.HasLocalType) != 0; // continue only if it has local type
- }
- public boolean visit(FieldDeclaration fieldDeclaration, Scope scope) {
- patternLocator.match(fieldDeclaration, nodeSet);
- return (fieldDeclaration.bits & ASTNode.HasLocalType) != 0; // continue only if it has local type;
- }
- public boolean visit(InferredAttribute field, BlockScope scope) {
- patternLocator.match(field, nodeSet);
- return false; // continue only if it has local type;
- }
- public boolean visit(Initializer initializer, MethodScope scope) {
- patternLocator.match(initializer, nodeSet);
- return (initializer.bits & ASTNode.HasLocalType) != 0; // continue only if it has local type
- }
- public boolean visit(TypeDeclaration memberTypeDeclaration, Scope scope) {
- patternLocator.match(memberTypeDeclaration, nodeSet);
- return true;
- }
- public boolean visit(MethodDeclaration methodDeclaration, Scope scope) {
- patternLocator.match(methodDeclaration, nodeSet);
- return (methodDeclaration.bits & ASTNode.HasLocalType) != 0; // continue only if it has local type
- }
- public boolean visit(InferredMethod inferredMethod, BlockScope scope) {
- patternLocator.match(inferredMethod, nodeSet);
- return false;
- }
-}
-public class ClassAndMethodDeclarationVisitor extends ClassButNoMethodDeclarationVisitor {
- public boolean visit(TypeDeclaration localTypeDeclaration, Scope scope) {
- patternLocator.match(localTypeDeclaration, nodeSet);
- return true;
- }
- public boolean visit(InferredType localTypeDeclaration, BlockScope scope) {
- patternLocator.match(localTypeDeclaration, nodeSet);
- return true;
- }
-}
-
-protected MatchLocatorParser(ProblemReporter problemReporter, MatchLocator locator) {
- super(problemReporter, true);
- this.reportOnlyOneSyntaxError = true;
- this.patternLocator = locator.patternLocator;
- if ((locator.matchContainer & PatternLocator.CLASS_CONTAINER) != 0) {
- this.localDeclarationVisitor = (locator.matchContainer & PatternLocator.METHOD_CONTAINER) != 0
- ? new ClassAndMethodDeclarationVisitor()
- : new ClassButNoMethodDeclarationVisitor();
- } else {
- this.localDeclarationVisitor = (locator.matchContainer & PatternLocator.METHOD_CONTAINER) != 0
- ? new MethodButNoClassDeclarationVisitor()
- : new NoClassNoMethodDeclarationVisitor();
- }
-}
-public void checkComment() {
- super.checkComment();
- if (this.javadocParser.checkDocComment && this.javadoc != null) {
-
- // Search for pattern locator matches in javadoc comment parameters @param tags
- JavadocSingleNameReference[] paramReferences = this.javadoc.paramReferences;
- if (paramReferences != null) {
- for (int i=0, length=paramReferences.length; i < length; i++) {
- this.patternLocator.match(paramReferences[i], this.nodeSet);
- }
- }
-
- // Search for pattern locator matches in javadoc comment @throws/@exception tags
- TypeReference[] thrownExceptions = this.javadoc.exceptionReferences;
- if (thrownExceptions != null) {
- for (int i=0, length=thrownExceptions.length; i < length; i++) {
- this.patternLocator.match(thrownExceptions[i], this.nodeSet);
- }
- }
-
- // Search for pattern locator matches in javadoc comment @see tags
- Expression[] references = this.javadoc.seeReferences;
- if (references != null) {
- for (int i=0, length=references.length; i < length; i++) {
- Expression reference = references[i];
- if (reference instanceof TypeReference) {
- TypeReference typeRef = (TypeReference) reference;
- this.patternLocator.match(typeRef, this.nodeSet);
- } else if (reference instanceof JavadocFieldReference) {
- JavadocFieldReference fieldRef = (JavadocFieldReference) reference;
- this.patternLocator.match(fieldRef, this.nodeSet);
- if (fieldRef.receiver instanceof TypeReference && !fieldRef.receiver.isThis()) {
- TypeReference typeRef = (TypeReference) fieldRef.receiver;
- this.patternLocator.match(typeRef, this.nodeSet);
- }
- } else if (reference instanceof JavadocMessageSend) {
- JavadocMessageSend messageSend = (JavadocMessageSend) reference;
- this.patternLocator.match(messageSend, this.nodeSet);
- if (messageSend.receiver instanceof TypeReference && !messageSend.receiver.isThis()) {
- TypeReference typeRef = (TypeReference) messageSend.receiver;
- this.patternLocator.match(typeRef, this.nodeSet);
- }
- if (messageSend.arguments != null) {
- for (int a=0,al=messageSend.arguments.length; a<al; a++) {
- JavadocArgumentExpression argument = (JavadocArgumentExpression) messageSend.arguments[a];
- if (argument.argument != null && argument.argument.type != null) {
- this.patternLocator.match(argument.argument.type, this.nodeSet);
- }
- }
- }
- } else if (reference instanceof JavadocAllocationExpression) {
- JavadocAllocationExpression constructor = (JavadocAllocationExpression) reference;
- this.patternLocator.match(constructor, this.nodeSet);
- if (constructor.type != null && !constructor.type.isThis()) {
- this.patternLocator.match(constructor.type, this.nodeSet);
- }
- if (constructor.arguments != null) {
- for (int a=0,al=constructor.arguments.length; a<al; a++) {
- this.patternLocator.match(constructor.arguments[a], this.nodeSet);
- JavadocArgumentExpression argument = (JavadocArgumentExpression) constructor.arguments[a];
- if (argument.argument != null && argument.argument.type != null) {
- this.patternLocator.match(argument.argument.type, this.nodeSet);
- }
- }
- }
- }
- }
- }
- }
-}
-protected void classInstanceCreation(boolean alwaysQualified, boolean isShort) {
- super.classInstanceCreation(alwaysQualified, isShort);
- this.patternLocator.match(this.expressionStack[this.expressionPtr], this.nodeSet);
-}
-protected void consumeAssignment() {
- super.consumeAssignment();
- this.patternLocator.match(this.expressionStack[this.expressionPtr], this.nodeSet);
-}
-protected void consumeCallExpressionWithSimpleName() {
- super.consumeCallExpressionWithSimpleName();
-
- // this is always a Reference
- this.patternLocator.match((Reference) this.expressionStack[this.expressionPtr], this.nodeSet);
-}
-protected void consumeMemberExpressionWithSimpleName() {
- super.consumeMemberExpressionWithSimpleName();
-
- // this is always a Reference
- this.patternLocator.match((Reference) this.expressionStack[this.expressionPtr], this.nodeSet);
-}
-protected void consumeFormalParameter(boolean isVarArgs) {
- super.consumeFormalParameter(isVarArgs);
-
- // this is always a LocalDeclaration
- this.patternLocator.match((LocalDeclaration) this.astStack[this.astPtr], this.nodeSet);
-}
-protected void consumeLocalVariableDeclaration() {
- super.consumeLocalVariableDeclaration();
-
- // this is always a LocalDeclaration
- this.patternLocator.match((LocalDeclaration) this.astStack[this.astPtr], this.nodeSet);
-}
-protected void consumeCallExpressionWithArguments() {
- super.consumeCallExpressionWithArguments();
-
- // this is always a MessageSend
- this.patternLocator.match((MessageSend) this.expressionStack[this.expressionPtr], this.nodeSet);
-}
-protected void consumePrimaryNoNewArray() {
- // pop parenthesis positions (and don't update expression positions
- // (see http://bugs.eclipse.org/bugs/show_bug.cgi?id=23329)
- intPtr--;
- intPtr--;
-}
-
-protected void consumeUnaryExpression(int op, boolean post) {
- super.consumeUnaryExpression(op, post);
- this.patternLocator.match(this.expressionStack[this.expressionPtr], this.nodeSet);
-}
-protected TypeReference copyDims(TypeReference typeRef, int dim) {
- TypeReference result = super.copyDims(typeRef, dim);
- if (this.nodeSet.removePossibleMatch(typeRef) != null)
- this.nodeSet.addPossibleMatch(result);
- else if (this.nodeSet.removeTrustedMatch(typeRef) != null)
- this.nodeSet.addTrustedMatch(result, true);
- return result;
-}
-protected TypeReference getTypeReference(int dim) {
- TypeReference typeRef = super.getTypeReference(dim);
- this.patternLocator.match(typeRef, this.nodeSet); // NB: Don't check container since type reference can happen anywhere
- return typeRef;
-}
-protected NameReference getUnspecifiedReference() {
- NameReference nameRef = super.getUnspecifiedReference();
- this.patternLocator.match(nameRef, this.nodeSet); // NB: Don't check container since unspecified reference can happen anywhere
- return nameRef;
-}
-protected NameReference getUnspecifiedReferenceOptimized() {
- NameReference nameRef = super.getUnspecifiedReferenceOptimized();
- this.patternLocator.match(nameRef, this.nodeSet); // NB: Don't check container since unspecified reference can happen anywhere
- return nameRef;
-}
-/**
- * Parses the method bodies in the given compilation unit
- * @param unit CompilationUnitDeclaration
- */
-public void parseBodies(CompilationUnitDeclaration unit) {
- TypeDeclaration[] types = unit.types;
- if (types != null)
- for (int i = 0; i < types.length; i++) {
- TypeDeclaration type = types[i];
- this.patternLocator.match(type, this.nodeSet);
- this.parseBodies(type, unit);
- }
-
-
- ProgramElement[] statements = unit.statements;
- if (statements != null)
- for (int i = 0; i < statements.length; i++) {
- if (statements[i] instanceof LocalDeclaration)
- {
- ((LocalDeclaration)statements[i]).traverse(localDeclarationVisitor, null);
- 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);
- methodDeclaration.traverse(localDeclarationVisitor, (Scope) null);
- if (this.patternLocator instanceof MethodLocator)
- ((MethodLocator)this.patternLocator).match((MethodDeclaration)statements[i], this.nodeSet);
-
- }
-
- }
-
- unit.traverseInferredTypes(localDeclarationVisitor, null);
-}
-/**
- * Parses the member bodies in the given type.
- * @param type TypeDeclaration
- * @param unit CompilationUnitDeclaration
- */
-protected void parseBodies(TypeDeclaration type, CompilationUnitDeclaration unit) {
- FieldDeclaration[] fields = type.fields;
- if (fields != null) {
- for (int i = 0; i < fields.length; i++) {
- FieldDeclaration field = fields[i];
- if (field instanceof Initializer)
- this.parse((Initializer) field, type, unit);
- field.traverse(localDeclarationVisitor, null);
- }
- }
-
- AbstractMethodDeclaration[] methods = type.methods;
- if (methods != null) {
- for (int i = 0; i < methods.length; i++) {
- AbstractMethodDeclaration method = methods[i];
- if (method.sourceStart >= type.bodyStart) { // if not synthetic
- if (method instanceof MethodDeclaration) {
- MethodDeclaration methodDeclaration = (MethodDeclaration) method;
- this.parse(methodDeclaration, unit);
- methodDeclaration.traverse(localDeclarationVisitor, (Scope) null);
- } else if (method instanceof ConstructorDeclaration) {
- ConstructorDeclaration constructorDeclaration = (ConstructorDeclaration) method;
- this.parse(constructorDeclaration, unit);
- constructorDeclaration.traverse(localDeclarationVisitor, (Scope) null);
- }
- } else if (method.isDefaultConstructor()) {
- method.parseStatements(this, unit);
- }
- }
- }
-
-// TypeDeclaration[] memberTypes = type.memberTypes;
-// if (memberTypes != null) {
-// for (int i = 0; i < memberTypes.length; i++) {
-// TypeDeclaration memberType = memberTypes[i];
-// this.parseBodies(memberType, unit);
-// memberType.traverse(localDeclarationVisitor, (Scope) 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
deleted file mode 100644
index 05d15637..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MatchingNodeSet.java
+++ /dev/null
@@ -1,211 +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 java.util.ArrayList;
-
-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.util.HashtableOfLong;
-import org.eclipse.wst.jsdt.internal.compiler.util.SimpleLookupTable;
-import org.eclipse.wst.jsdt.internal.compiler.util.SimpleSet;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * A set of matches and possible matches, which need to be resolved.
- */
-public class MatchingNodeSet {
-
-/**
- * Map of matching ast nodes that don't need to be resolved to their accuracy level.
- * Each node is removed as it is reported.
- */
-SimpleLookupTable matchingNodes = new SimpleLookupTable(3); // node -> accuracy
-private HashtableOfLong matchingNodesKeys = new HashtableOfLong(3); // sourceRange -> node
-static Integer EXACT_MATCH = new Integer(SearchMatch.A_ACCURATE);
-static Integer POTENTIAL_MATCH = new Integer(SearchMatch.A_INACCURATE);
-static Integer ERASURE_MATCH = new Integer(SearchPattern.R_ERASURE_MATCH);
-
-/**
- * Tell whether locators need to resolve or not for current matching node set.
- */
-public boolean mustResolve;
-
-/**
- * Set of possible matching ast nodes. They need to be resolved
- * to determine if they really match the search pattern.
- */
-SimpleSet possibleMatchingNodesSet = new SimpleSet(7);
-private HashtableOfLong possibleMatchingNodesKeys = new HashtableOfLong(7);
-
-
-public MatchingNodeSet(boolean mustResolvePattern) {
- super();
- mustResolve = mustResolvePattern;
-}
-
-public int addMatch(ASTNode node, int matchLevel) {
- int maskedLevel = matchLevel & PatternLocator.MATCH_LEVEL_MASK;
- switch (maskedLevel) {
- case PatternLocator.INACCURATE_MATCH:
- if (matchLevel != maskedLevel) {
- addTrustedMatch(node, new Integer(SearchMatch.A_INACCURATE+(matchLevel & PatternLocator.FLAVORS_MASK)));
- } else {
- addTrustedMatch(node, POTENTIAL_MATCH);
- }
- break;
- case PatternLocator.POSSIBLE_MATCH:
- addPossibleMatch(node);
- break;
- case PatternLocator.ERASURE_MATCH:
- if (matchLevel != maskedLevel) {
- addTrustedMatch(node, new Integer(SearchPattern.R_ERASURE_MATCH+(matchLevel & PatternLocator.FLAVORS_MASK)));
- } else {
- addTrustedMatch(node, ERASURE_MATCH);
- }
- break;
- case PatternLocator.ACCURATE_MATCH:
- if (matchLevel != maskedLevel) {
- addTrustedMatch(node, new Integer(SearchMatch.A_ACCURATE+(matchLevel & PatternLocator.FLAVORS_MASK)));
- } else {
- addTrustedMatch(node, EXACT_MATCH);
- }
- break;
- }
- return matchLevel;
-}
-public void addPossibleMatch(ASTNode node) {
- // remove existing node at same position from set
- // (case of recovery that created the same node several time
- // see http://bugs.eclipse.org/bugs/show_bug.cgi?id=29366)
- long key = (((long) node.sourceStart) << 32) + node.sourceEnd;
- ASTNode existing = (ASTNode) this.possibleMatchingNodesKeys.get(key);
- if (existing != null && existing.getClass().equals(node.getClass()))
- this.possibleMatchingNodesSet.remove(existing);
-
- // add node to set
- this.possibleMatchingNodesSet.add(node);
- this.possibleMatchingNodesKeys.put(key, node);
-}
-public void addTrustedMatch(ASTNode node, boolean isExact) {
- addTrustedMatch(node, isExact ? EXACT_MATCH : POTENTIAL_MATCH);
-
-}
-void addTrustedMatch(ASTNode node, Integer level) {
- // remove existing node at same position from set
- // (case of recovery that created the same node several time
- // see http://bugs.eclipse.org/bugs/show_bug.cgi?id=29366)
- long key = (((long) node.sourceStart) << 32) + node.sourceEnd;
- ASTNode existing = (ASTNode) this.matchingNodesKeys.get(key);
- if (existing != null && existing.getClass().equals(node.getClass()))
- this.matchingNodes.removeKey(existing);
-
- // map node to its accuracy level
- this.matchingNodes.put(node, level);
- this.matchingNodesKeys.put(key, node);
-}
-protected boolean hasPossibleNodes(int start, int end) {
- Object[] nodes = this.possibleMatchingNodesSet.values;
- for (int i = 0, l = nodes.length; i < l; i++) {
- ASTNode node = (ASTNode) nodes[i];
- if (node != null && !node.isInferred()&& start <= node.sourceStart && node.sourceEnd <= end)
- return true;
- }
- nodes = this.matchingNodes.keyTable;
- for (int i = 0, l = nodes.length; i < l; i++) {
- ASTNode node = (ASTNode) nodes[i];
- if (node != null && start <= node.sourceStart && node.sourceEnd <= end)
- return true;
- }
- return false;
-}
-/**
- * Returns the matching nodes that are in the given range in the source order.
- */
-protected ASTNode[] matchingNodes(int start, int end) {
- ArrayList nodes = null;
- Object[] keyTable = this.matchingNodes.keyTable;
- for (int i = 0, l = keyTable.length; i < l; i++) {
- ASTNode node = (ASTNode) keyTable[i];
- if (node != null && start <= node.sourceStart && node.sourceEnd <= end) {
- if (!node.isInferred())
- {
- if (nodes == null) nodes = new ArrayList();
- nodes.add(node);
- }
- }
- }
- if (nodes == null) return null;
-
- ASTNode[] result = new ASTNode[nodes.size()];
- nodes.toArray(result);
-
- // sort nodes by source starts
- Util.Comparer comparer = new Util.Comparer() {
- public int compare(Object o1, Object o2) {
- return ((ASTNode) o1).sourceStart - ((ASTNode) o2).sourceStart;
- }
- };
- Util.sort(result, comparer);
- return result;
-}
-public Object removePossibleMatch(ASTNode node) {
- long key = (((long) node.sourceStart) << 32) + node.sourceEnd;
- ASTNode existing = (ASTNode) this.possibleMatchingNodesKeys.get(key);
- if (existing == null) return null;
-
- this.possibleMatchingNodesKeys.put(key, null);
- return this.possibleMatchingNodesSet.remove(node);
-}
-public Object removeTrustedMatch(ASTNode node) {
- long key = (((long) node.sourceStart) << 32) + node.sourceEnd;
- ASTNode existing = (ASTNode) this.matchingNodesKeys.get(key);
- if (existing == null) return null;
-
- this.matchingNodesKeys.put(key, null);
- return this.matchingNodes.removeKey(node);
-}
-public String toString() {
- // TODO (jerome) should show both tables
- StringBuffer result = new StringBuffer();
- result.append("Exact matches:"); //$NON-NLS-1$
- Object[] keyTable = this.matchingNodes.keyTable;
- Object[] valueTable = this.matchingNodes.valueTable;
- for (int i = 0, l = keyTable.length; i < l; i++) {
- ASTNode node = (ASTNode) keyTable[i];
- if (node == null) continue;
- result.append("\n\t"); //$NON-NLS-1$
- switch (((Integer)valueTable[i]).intValue()) {
- case SearchMatch.A_ACCURATE:
- result.append("ACCURATE_MATCH: "); //$NON-NLS-1$
- break;
- case SearchMatch.A_INACCURATE:
- result.append("INACCURATE_MATCH: "); //$NON-NLS-1$
- break;
- case SearchPattern.R_ERASURE_MATCH:
- result.append("ERASURE_MATCH: "); //$NON-NLS-1$
- break;
- }
- node.print(0, result);
- }
-
- result.append("\nPossible matches:"); //$NON-NLS-1$
- Object[] nodes = this.possibleMatchingNodesSet.values;
- for (int i = 0, l = nodes.length; i < l; i++) {
- ASTNode node = (ASTNode) nodes[i];
- if (node == null) continue;
- result.append("\nPOSSIBLE_MATCH: "); //$NON-NLS-1$
- node.print(0, result);
- }
- return result.toString();
-}
-}
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
deleted file mode 100644
index c411a15d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MethodLocator.java
+++ /dev/null
@@ -1,634 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.search.matching;
-
-import java.util.HashMap;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-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.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;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ImportReference;
-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.TypeDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.env.IBinaryType;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Binding;
-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.ReferenceBinding;
-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.util.SimpleSet;
-import org.eclipse.wst.jsdt.internal.core.JavaElement;
-import org.eclipse.wst.jsdt.internal.core.search.BasicSearchEngine;
-
-public class MethodLocator extends PatternLocator {
-
-protected MethodPattern pattern;
-protected boolean isDeclarationOfReferencedMethodsPattern;
-
-//extra reference info
-public char[][][] allSuperDeclaringTypeNames;
-
-//method declarations which parameters verification fail
-private HashMap methodDeclarationsWithInvalidParam = new HashMap();
-
-public MethodLocator(MethodPattern pattern) {
- super(pattern);
-
- this.pattern = pattern;
- this.isDeclarationOfReferencedMethodsPattern = this.pattern instanceof DeclarationOfReferencedMethodsPattern;
-}
-/*
- * Clear caches
- */
-protected void clear() {
- this.methodDeclarationsWithInvalidParam = new HashMap();
-}
-public void initializePolymorphicSearch(MatchLocator locator) {
- long start = 0;
- if (BasicSearchEngine.VERBOSE) {
- start = System.currentTimeMillis();
- }
- try {
- this.allSuperDeclaringTypeNames =
- new SuperTypeNamesCollector(
- this.pattern,
- this.pattern.declaringSimpleName,
- this.pattern.declaringQualification,
- locator,
- this.pattern.declaringType,
- locator.progressMonitor).collect();
- } catch (JavaScriptModelException e) {
- // inaccurate matches will be found
- }
- if (BasicSearchEngine.VERBOSE) {
- System.out.println("Time to initialize polymorphic search: "+(System.currentTimeMillis()-start)); //$NON-NLS-1$
- }
-}
-/*
- * Return whether a type name is in pattern all super declaring types names.
- */
-private boolean isTypeInSuperDeclaringTypeNames(char[][] typeName) {
- if (allSuperDeclaringTypeNames == null) return false;
- int length = allSuperDeclaringTypeNames.length;
- for (int i= 0; i<length; i++) {
- if (CharOperation.equals(allSuperDeclaringTypeNames[i], typeName)) {
- return true;
- }
- }
- return false;
-}
-/**
- * Returns whether the code gen will use an invoke virtual for
- * this message send or not.
- */
-protected boolean isVirtualInvoke(MethodBinding method, MessageSend messageSend) {
- return !method.isStatic() && !method.isPrivate() && !messageSend.isSuperAccess();
-}
-public int match(ASTNode node, MatchingNodeSet nodeSet) {
- int declarationsLevel = IMPOSSIBLE_MATCH;
- return nodeSet.addMatch(node, declarationsLevel);
-}
-//public int match(ConstructorDeclaration node, MatchingNodeSet nodeSet) - SKIP IT
-//public int match(Expression node, MatchingNodeSet nodeSet) - SKIP IT
-//public int match(FieldDeclaration node, MatchingNodeSet nodeSet) - SKIP IT
-public int match(MethodDeclaration node, MatchingNodeSet nodeSet) {
- if (!this.pattern.findDeclarations) return IMPOSSIBLE_MATCH;
-
- // Verify method name
- if (!matchesName(this.pattern.selector, node.getSafeName())) 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 = node.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;
- }
- this.methodDeclarationsWithInvalidParam.put(node, null);
- } else {
- return IMPOSSIBLE_MATCH;
- }
- }
- }
- }
-
- // 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);
-}
-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))) {
- int length = this.pattern.parameterSimpleNames.length;
- ASTNode[] args = node.arguments;
- int argsLength = args == null ? 0 : args.length;
- if (length != argsLength) return IMPOSSIBLE_MATCH;
- }
-
- return nodeSet.addMatch(node, ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH);
-}
-//public int match(TypeDeclaration node, MatchingNodeSet nodeSet) - SKIP IT
-//public int match(TypeReference node, MatchingNodeSet nodeSet) - SKIP IT
-
-protected int matchContainer() {
- if (this.pattern.findReferences) {
- // need to look almost everywhere to find in javadocs and static import
- return ALL_CONTAINER;
- }
- return pattern.isFunction ? COMPILATION_UNIT_CONTAINER : CLASS_CONTAINER;
-}
-/* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.core.search.matching.PatternLocator#matchLevelAndReportImportRef(org.eclipse.wst.jsdt.internal.compiler.ast.ImportReference, org.eclipse.wst.jsdt.internal.compiler.lookup.Binding, org.eclipse.wst.jsdt.internal.core.search.matching.MatchLocator)
- * Accept to report match of static field on static import
- */
-protected void matchLevelAndReportImportRef(ImportReference importRef, Binding binding, MatchLocator locator) throws CoreException {
-}
-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) {
- // 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);
- if (level > newLevel) {
- 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
-// }
-// }
- }
-
- return level;
-}
-private boolean matchOverriddenMethod(ReferenceBinding type, MethodBinding method, MethodBinding matchMethod) {
- if (type == null || this.pattern.selector == null) return false;
-
- // matches superclass
- if (!CharOperation.equals(type.compoundName, TypeConstants.JAVA_LANG_OBJECT)) {
- ReferenceBinding superClass = type.superclass();
- if (matchOverriddenMethod(superClass, method, matchMethod)) {
- return true;
- }
- }
-
- return false;
-}
-/**
- * @see org.eclipse.wst.jsdt.internal.core.search.matching.PatternLocator#matchReportReference(org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode, org.eclipse.wst.jsdt.core.IJavaScriptElement, Binding, int, org.eclipse.wst.jsdt.internal.core.search.matching.MatchLocator)
- */
-protected void matchReportReference(ASTNode reference, IJavaScriptElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException {
- MethodBinding methodBinding = (reference instanceof MessageSend) ? ((MessageSend)reference).binding: ((elementBinding instanceof MethodBinding) ? (MethodBinding) elementBinding : null);
- if (this.isDeclarationOfReferencedMethodsPattern) {
- if (methodBinding == null) return;
- // need exact match to be able to open on type ref
- if (accuracy != SearchMatch.A_ACCURATE) return;
-
- // element that references the method must be included in the enclosing element
- DeclarationOfReferencedMethodsPattern declPattern = (DeclarationOfReferencedMethodsPattern) this.pattern;
- while (element != null && !declPattern.enclosingElement.equals(element))
- element = element.getParent();
- if (element != null) {
- reportDeclaration(methodBinding, locator, declPattern.knownMethods);
- }
- } else {
- match = locator.newMethodReferenceMatch(element, elementBinding, accuracy, -1, -1, false /*not constructor*/, reference);
- if (this.pattern.findReferences && reference instanceof MessageSend) {
- IJavaScriptElement focus = ((InternalSearchPattern) this.pattern).focus;
- // verify closest match if pattern was bound
- // (see bug 70827)
- if (focus != null && focus.getElementType() == IJavaScriptElement.METHOD) {
- if (methodBinding != null) {
- boolean isPrivate = Flags.isPrivate(((IFunction) focus).getFlags());
- if (isPrivate && !CharOperation.equals(methodBinding.declaringClass.sourceName, focus.getParent().getElementName().toCharArray())) {
- return; // finally the match was not possible
- }
- }
- }
- matchReportReference((MessageSend)reference, locator, ((MessageSend)reference).binding);
- } else {
- int offset = reference.sourceStart;
- int length = reference.sourceEnd - offset + 1;
- match.setOffset(offset);
- match.setLength(length);
- locator.report(match);
- }
- }
-}
-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();
- if (!report) return;
-
- // Report match
- int offset = (int) (messageSend.nameSourcePosition >>> 32);
- match.setOffset(offset);
- 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;
- // If method parameters verification was not valid, then try to see if method arguments can match a method in hierarchy
- if (this.methodDeclarationsWithInvalidParam.containsKey(reference)) {
- // First see if this reference has already been resolved => report match if validated
- Boolean report = (Boolean) this.methodDeclarationsWithInvalidParam.get(reference);
- if (report != null) {
- if (report.booleanValue()) {
- return super.newDeclarationMatch(reference, element, elementBinding, accuracy, length, locator);
- }
- return null;
- }
- if (matchOverriddenMethod(methodBinding.declaringClass, methodBinding, null)) {
- this.methodDeclarationsWithInvalidParam.put(reference, Boolean.TRUE);
- return super.newDeclarationMatch(reference, element, elementBinding, accuracy, length, locator);
- }
- if (isTypeInSuperDeclaringTypeNames(methodBinding.declaringClass.compoundName)) {
- MethodBinding patternBinding = locator.getMethodBinding(this.pattern);
- if (patternBinding != null) {
- if (!matchOverriddenMethod(patternBinding.declaringClass, patternBinding, methodBinding)) {
- this.methodDeclarationsWithInvalidParam.put(reference, Boolean.FALSE);
- return null;
- }
- }
- this.methodDeclarationsWithInvalidParam.put(reference, Boolean.TRUE);
- return super.newDeclarationMatch(reference, element, elementBinding, accuracy, length, locator);
- }
- this.methodDeclarationsWithInvalidParam.put(reference, Boolean.FALSE);
- return null;
- }
- }
- return super.newDeclarationMatch(reference, element, elementBinding, accuracy, length, locator);
-}
-protected int referenceType() {
- return IJavaScriptElement.METHOD;
-}
-protected void reportDeclaration(MethodBinding methodBinding, MatchLocator locator, SimpleSet knownMethods) throws CoreException {
- ReferenceBinding declaringClass = methodBinding.declaringClass;
- IType type = locator.lookupType(declaringClass);
- if (type == null) return; // case of a secondary type
-
- char[] bindingSelector = methodBinding.selector;
- boolean isBinary = type.isBinary();
- IFunction method = null;
- TypeBinding[] parameters = methodBinding.original().parameters;
- int parameterLength = parameters.length;
-// if (isBinary) {
-// char[][] parameterTypes = new char[parameterLength][];
-// for (int i = 0; i<parameterLength; i++) {
-// char[] typeName = parameters[i].qualifiedSourceName();
-// for (int j=0, dim=parameters[i].dimensions(); j<dim; j++) {
-// typeName = CharOperation.concat(typeName, new char[] {'[', ']'});
-// }
-// parameterTypes[i] = typeName;
-// }
-// method = locator.createBinaryMethodHandle(type, methodBinding.selector, parameterTypes);
-// } else {
- String[] parameterTypes = new String[parameterLength];
- for (int i = 0; i < parameterLength; i++) {
- char[] typeName = parameters[i].shortReadableName();
- if (parameters[i].isMemberType()) {
- typeName = CharOperation.subarray(typeName, CharOperation.indexOf('.', typeName)+1, typeName.length);
- }
- parameterTypes[i] = Signature.createTypeSignature(typeName, false);
- }
- method = type.getFunction(new String(bindingSelector), parameterTypes);
-// }
- if (method == null || knownMethods.addIfNotIncluded(method) == null) return;
-
- IResource resource = type.getResource();
- IBinaryType info = null;
- if (isBinary) {
- if (resource == null)
- resource = type.getJavaScriptProject().getProject();
- info = locator.getBinaryInfo((org.eclipse.wst.jsdt.internal.core.ClassFile)type.getClassFile(), resource);
- locator.reportBinaryMemberDeclaration(resource, method, methodBinding, info, SearchMatch.A_ACCURATE);
- } else {
- ClassScope scope = (ClassScope)((SourceTypeBinding) declaringClass).scope;
- if (scope != null) {
- TypeDeclaration typeDecl = scope.referenceContext;
- AbstractMethodDeclaration methodDecl = null;
- AbstractMethodDeclaration[] methodDecls = typeDecl.methods;
- for (int i = 0, length = methodDecls.length; i < length; i++) {
- if (CharOperation.equals(bindingSelector, methodDecls[i].selector)) {
- methodDecl = methodDecls[i];
- break;
- }
- }
- if (methodDecl != null) {
- int offset = methodDecl.sourceStart;
- Binding binding = methodDecl.binding;
- if (binding != null)
- method = (IFunction) ((JavaElement) method).resolved(binding);
- match = new MethodDeclarationMatch(method, SearchMatch.A_ACCURATE, offset, methodDecl.sourceEnd-offset+1, locator.getParticipant(), resource);
- locator.report(match);
- }
- }
- }
-}
-public int resolveLevel(ASTNode possibleMatchingNode) {
- if (this.pattern.findReferences) {
- if (possibleMatchingNode instanceof MessageSend) {
- return resolveLevel((MessageSend) possibleMatchingNode);
- }
- }
- if (this.pattern.findDeclarations) {
- if (possibleMatchingNode instanceof MethodDeclaration) {
- return resolveLevel(((MethodDeclaration) possibleMatchingNode).binding);
- }
- else if (possibleMatchingNode instanceof InferredMethod)
- return resolveLevel(((InferredMethod) possibleMatchingNode).methodBinding);
-}
- return IMPOSSIBLE_MATCH;
-}
-public int resolveLevel(Binding binding) {
- if (binding == null) return INACCURATE_MATCH;
- if (!(binding instanceof MethodBinding)) return IMPOSSIBLE_MATCH;
-
- MethodBinding method = (MethodBinding) binding;
- boolean skipVerif = this.pattern.findDeclarations && this.mayBeGeneric;
- int methodLevel = matchMethod(method, skipVerif);
- if (methodLevel == IMPOSSIBLE_MATCH) {
- if (method != method.original()) methodLevel = matchMethod(method.original(), skipVerif);
- if (methodLevel == IMPOSSIBLE_MATCH) {
- return IMPOSSIBLE_MATCH;
- } else {
- method = method.original();
- }
- }
-
- // declaring type
- char[] qualifiedPattern = qualifiedPattern(this.pattern.declaringSimpleName, this.pattern.declaringQualification);
- 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;
- }
- int declaringLevel = subType
- ? resolveLevelAsSubtype(qualifiedPattern, method.declaringClass, null)
- : resolveLevelForType(qualifiedPattern, method.declaringClass);
- return methodLevel > declaringLevel ? declaringLevel : methodLevel; // return the weaker match
-}
-protected int resolveLevel(MessageSend messageSend) {
- MethodBinding method = messageSend.binding;
- if (method == null) {
- return INACCURATE_MATCH;
- }
- if (messageSend.resolvedType == null) {
- // Closest match may have different argument numbers when ProblemReason is NotFound
- // see MessageSend#resolveType(BlockScope)
- // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=97322
- int argLength = messageSend.arguments == null ? 0 : messageSend.arguments.length;
- if (pattern.parameterSimpleNames == null || argLength == pattern.parameterSimpleNames.length) {
- return INACCURATE_MATCH;
- }
- return IMPOSSIBLE_MATCH;
- }
-
- int methodLevel = matchMethod(method, false);
- if (methodLevel == IMPOSSIBLE_MATCH) {
- if (method != method.original()) methodLevel = matchMethod(method.original(), false);
- if (methodLevel == IMPOSSIBLE_MATCH) return IMPOSSIBLE_MATCH;
- method = method.original();
- }
-
- // receiver type
- char[] qualifiedPattern = qualifiedPattern(this.pattern.declaringSimpleName, this.pattern.declaringQualification);
- if (qualifiedPattern == null) return methodLevel; // since any declaring class will do
-
- int declaringLevel;
- if (isVirtualInvoke(method, messageSend) && (messageSend.actualReceiverType instanceof ReferenceBinding)) {
- ReferenceBinding methodReceiverType = (ReferenceBinding) messageSend.actualReceiverType;
- declaringLevel = resolveLevelAsSubtype(qualifiedPattern, methodReceiverType, method.parameters);
- if (declaringLevel == IMPOSSIBLE_MATCH) {
- if (method.declaringClass == null || this.allSuperDeclaringTypeNames == null) {
- declaringLevel = INACCURATE_MATCH;
- } else {
- char[][] compoundName = methodReceiverType.compoundName;
- for (int i = 0, max = this.allSuperDeclaringTypeNames.length; i < max; i++) {
- if (CharOperation.equals(this.allSuperDeclaringTypeNames[i], compoundName)) {
- return methodLevel // since this is an ACCURATE_MATCH so return the possibly weaker match
- | SUPER_INVOCATION_FLAVOR; // this is an overridden method => add flavor to returned level
- }
- }
- /* Do not return interfaces potential matches
- * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=157814#c8"
- if (methodReceiverType.isInterface()) {
- // all methods interface with same name and parameters are potential matches
- // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=156491
- return INACCURATE_MATCH | POLYMORPHIC_FLAVOR;
- }
- */
- }
- }
- if ((declaringLevel & FLAVORS_MASK) != 0) {
- // level got some flavors => return it
- return declaringLevel;
- }
- } else {
- declaringLevel = resolveLevelForType(qualifiedPattern, method.declaringClass);
- }
- return methodLevel > declaringLevel ? declaringLevel : methodLevel; // return the weaker match
-}
-/**
- * Returns whether the given reference type binding matches or is a subtype of a type
- * that matches the given qualified pattern.
- * Returns ACCURATE_MATCH if it does.
- * Returns INACCURATE_MATCH if resolve fails
- * Returns IMPOSSIBLE_MATCH if it doesn't.
- */
-protected int resolveLevelAsSubtype(char[] qualifiedPattern, ReferenceBinding type, TypeBinding[] argumentTypes) {
- if (type == null) return INACCURATE_MATCH;
-
- int level = resolveLevelForType(qualifiedPattern, type);
- if (level != IMPOSSIBLE_MATCH) {
- level |= OVERRIDDEN_METHOD_FLAVOR;
-
- return level;
- }
-
- // matches superclass
- if (!CharOperation.equals(type.compoundName, TypeConstants.JAVA_LANG_OBJECT)) {
- level = resolveLevelAsSubtype(qualifiedPattern, type.superclass(), argumentTypes);
- if (level != IMPOSSIBLE_MATCH) {
- if (argumentTypes != null) {
- // need to verify if method may be overridden
- MethodBinding[] methods = type.getMethods(this.pattern.selector);
- for (int i=0, length=methods.length; i<length; i++) {
- MethodBinding method = methods[i];
- TypeBinding[] parameters = method.parameters;
- if (argumentTypes.length == parameters.length) {
- boolean found = true;
- for (int j=0,l=parameters.length; j<l; j++) {
- if (parameters[j] != argumentTypes[j]) {
- found = false;
- break;
- }
- }
- if (found) { // one method match in hierarchy
- if ((level & OVERRIDDEN_METHOD_FLAVOR) != 0) {
- // this method is already overridden on a super class, current match is impossible
- return IMPOSSIBLE_MATCH;
- }
- if (!method.isAbstract()) {
- // store the fact that the method is overridden
- level |= OVERRIDDEN_METHOD_FLAVOR;
- }
- }
- }
- }
- }
- return level | SUB_INVOCATION_FLAVOR; // add flavor to returned level
- }
- }
-
-
- return INACCURATE_MATCH;
-}
-public String toString() {
- return "Locator for " + this.pattern.toString(); //$NON-NLS-1$
-}
-
-public int match(InferredMethod inferredMethod, MatchingNodeSet nodeSet) {
- if (!this.pattern.findDeclarations) return IMPOSSIBLE_MATCH;
-
- // Verify method name
- if (!matchesName(this.pattern.selector, inferredMethod.name)) 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;
- 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;
- }
- this.methodDeclarationsWithInvalidParam.put((AbstractMethodDeclaration)inferredMethod.getFunctionDeclaration(), null);
- } else {
- return IMPOSSIBLE_MATCH;
- }
- }
- }
- }
-
- // 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
deleted file mode 100644
index 703bb57d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MethodPattern.java
+++ /dev/null
@@ -1,380 +0,0 @@
-/*******************************************************************************
- * 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.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.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 };
-
-/**
- * Method entries are encoded as selector '/' Arity:
- * e.g. 'foo/0'
- */
-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) {
-
- this(findDeclarations,
- findReferences,
- isFunction,
- selector,
- declaringQualification,
- declaringSimpleName,
- returnQualification,
- returnSimpleName,
- parameterQualifications,
- parameterSimpleNames,
- method.getDeclaringType(),
- matchRule);
-
- // Set flags
- try {
- this.varargs = (method.getFlags() & Flags.AccVarargs) != 0;
- } catch (JavaScriptModelException e) {
- // do nothing
- }
-
- methodParameters = true;
-
- if (declaringType!=null) {
- // Store type signature and arguments for declaring type
- storeTypeSignaturesAndArguments(declaringType);
-
- }
- // 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; i<length; i++) {
- parametersTypeSignatures[i] = Util.splitTypeLevelsSignature(parameterSignatures[i]);
- parametersTypeArguments[i] = Util.getAllTypeArguments(parametersTypeSignatures[i]);
- }
- }
- }
-
- // 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(findDeclarations,
- findReferences,
- isFunction,
- selector,
- declaringQualification,
- declaringSimpleName,
- returnQualification,
- returnSimpleName,
- parameterQualifications,
- parameterSimpleNames,
- null,
- matchRule);
-
- // Store type signature and arguments for declaring type
- if (declaringSignature != null) {
- typeSignatures = Util.splitTypeLevelsSignature(declaringSignature);
- setTypeArguments(Util.getAllTypeArguments(typeSignatures));
- }
-
- // 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; i<length; i++) {
- parametersTypeSignatures[i] = Util.splitTypeLevelsSignature(parameterSignatures[i]);
- parametersTypeArguments[i] = Util.getAllTypeArguments(parametersTypeSignatures[i]);
- }
- }
- }
-
- // Store type signatures and arguments for method
- methodArguments = arguments;
- if (hasMethodArguments()) ((InternalSearchPattern)this).mustResolve = true;
-}
-public void decodeIndexKey(char[] key) {
- int last = key.length - 1;
- this.parameterCount = 0;
- this.selector = null;
- int power = 1;
- for (int i=last; i>=0; i--) {
- if (key[i] == SEPARATOR) {
- System.arraycopy(key, 0, this.selector = new char[i], 0, i);
- break;
- }
- if (i == last) {
- this.parameterCount = key[i] - '0';
- } else {
- power *= 10;
- this.parameterCount += power * (key[i] - '0');
- }
- }
-}
-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;
-
- 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;
- }
- 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;
- }
-
- 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$
- }
- 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]);
- }
- }
- 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
deleted file mode 100644
index b40807d5..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MultiTypeDeclarationPattern.java
+++ /dev/null
@@ -1,191 +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 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 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]);
- }
- // null simple names are allowed (should return all names)
- if (simpleNames != null) {
- if ((isCaseSensitive() || isCamelCase()) ) {
- this.simpleNames = simpleNames;
- } else {
- int length = simpleNames.length;
- this.simpleNames = new char[length][];
- for (int i = 0; i < length; i++)
- this.simpleNames[i] = CharOperation.toLowerCase(simpleNames[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;
- }
- }
-
- // check qualified name
- if (this.qualifications != null) {
- int count = 0;
- int max = this.qualifications.length;
- if (max == 0 && pattern.qualification.length > 0) {
- return false;
- }
- 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
- }
-
- 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);
- }
- 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;
- }
- }
-
- 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$
- }
- output.append("> "); //$NON-NLS-1$
- }
- 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$
- }
- 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/OrLocator.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/OrLocator.java
deleted file mode 100644
index 69e65c27..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/OrLocator.java
+++ /dev/null
@@ -1,293 +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.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-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.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.ConstructorDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Expression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration;
-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.Reference;
-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.lookup.Binding;
-
-public class OrLocator extends PatternLocator {
-
-protected PatternLocator[] patternLocators;
-
-public OrLocator(OrPattern pattern) {
- super(pattern);
-
- SearchPattern[] patterns = pattern.patterns;
- int length = patterns.length;
- this.patternLocators = new PatternLocator[length];
- for (int i = 0; i < length; i++)
- this.patternLocators[i] = PatternLocator.patternLocator(patterns[i]);
-}
-public void initializePolymorphicSearch(MatchLocator locator) {
- for (int i = 0, length = this.patternLocators.length; i < length; i++)
- this.patternLocators[i].initializePolymorphicSearch(locator);
-}
-public int match(ASTNode node, MatchingNodeSet nodeSet) {
- int level = IMPOSSIBLE_MATCH;
- for (int i = 0, length = this.patternLocators.length; i < length; i++) {
- int newLevel = this.patternLocators[i].match(node, nodeSet);
- if (newLevel > level) {
- if (newLevel == ACCURATE_MATCH) return ACCURATE_MATCH;
- level = newLevel;
- }
- }
- return level;
-}
-public int match(ConstructorDeclaration node, MatchingNodeSet nodeSet) {
- int level = IMPOSSIBLE_MATCH;
- for (int i = 0, length = this.patternLocators.length; i < length; i++) {
- int newLevel = this.patternLocators[i].match(node, nodeSet);
- if (newLevel > level) {
- if (newLevel == ACCURATE_MATCH) return ACCURATE_MATCH;
- level = newLevel;
- }
- }
- return level;
-}
-public int match(Expression node, MatchingNodeSet nodeSet) {
- int level = IMPOSSIBLE_MATCH;
- for (int i = 0, length = this.patternLocators.length; i < length; i++) {
- int newLevel = this.patternLocators[i].match(node, nodeSet);
- if (newLevel > level) {
- if (newLevel == ACCURATE_MATCH) return ACCURATE_MATCH;
- level = newLevel;
- }
- }
- return level;
-}
-public int match(FieldDeclaration node, MatchingNodeSet nodeSet) {
- int level = IMPOSSIBLE_MATCH;
- for (int i = 0, length = this.patternLocators.length; i < length; i++) {
- int newLevel = this.patternLocators[i].match(node, nodeSet);
- if (newLevel > level) {
- if (newLevel == ACCURATE_MATCH) return ACCURATE_MATCH;
- level = newLevel;
- }
- }
- return level;
-}
-
-public int match(InferredAttribute node, MatchingNodeSet nodeSet) {
- int level = IMPOSSIBLE_MATCH;
- for (int i = 0, length = this.patternLocators.length; i < length; i++) {
- int newLevel = this.patternLocators[i].match(node, nodeSet);
- if (newLevel > level) {
- if (newLevel == ACCURATE_MATCH) return ACCURATE_MATCH;
- level = newLevel;
- }
- }
- return level;
-}
-
-public int match(LocalDeclaration node, MatchingNodeSet nodeSet) {
- int level = IMPOSSIBLE_MATCH;
- for (int i = 0, length = this.patternLocators.length; i < length; i++) {
- int newLevel = this.patternLocators[i].match(node, nodeSet);
- if (newLevel > level) {
- if (newLevel == ACCURATE_MATCH) return ACCURATE_MATCH;
- level = newLevel;
- }
- }
- return level;
-}
-public int match(MethodDeclaration node, MatchingNodeSet nodeSet) {
- int level = IMPOSSIBLE_MATCH;
- for (int i = 0, length = this.patternLocators.length; i < length; i++) {
- int newLevel = this.patternLocators[i].match(node, nodeSet);
- if (newLevel > level) {
- if (newLevel == ACCURATE_MATCH) return ACCURATE_MATCH;
- level = newLevel;
- }
- }
- return level;
-}
-
-public int match(InferredMethod node, MatchingNodeSet nodeSet) {
- int level = IMPOSSIBLE_MATCH;
- for (int i = 0, length = this.patternLocators.length; i < length; i++) {
- int newLevel = this.patternLocators[i].match(node, nodeSet);
- if (newLevel > level) {
- if (newLevel == ACCURATE_MATCH) return ACCURATE_MATCH;
- level = newLevel;
- }
- }
- return level;
-}
-
-public int match(MessageSend node, MatchingNodeSet nodeSet) {
- int level = IMPOSSIBLE_MATCH;
- for (int i = 0, length = this.patternLocators.length; i < length; i++) {
- int newLevel = this.patternLocators[i].match(node, nodeSet);
- if (newLevel > level) {
- if (newLevel == ACCURATE_MATCH) return ACCURATE_MATCH;
- level = newLevel;
- }
- }
- return level;
-}
-public int match(Reference node, MatchingNodeSet nodeSet) {
- int level = IMPOSSIBLE_MATCH;
- for (int i = 0, length = this.patternLocators.length; i < length; i++) {
- int newLevel = this.patternLocators[i].match(node, nodeSet);
- if (newLevel > level) {
- if (newLevel == ACCURATE_MATCH) return ACCURATE_MATCH;
- level = newLevel;
- }
- }
- return level;
-}
-public int match(TypeDeclaration node, MatchingNodeSet nodeSet) {
- int level = IMPOSSIBLE_MATCH;
- for (int i = 0, length = this.patternLocators.length; i < length; i++) {
- int newLevel = this.patternLocators[i].match(node, nodeSet);
- if (newLevel > level) {
- if (newLevel == ACCURATE_MATCH) return ACCURATE_MATCH;
- level = newLevel;
- }
- }
- return level;
-}
-
-public int match(InferredType node, MatchingNodeSet nodeSet) {
- int level = IMPOSSIBLE_MATCH;
- for (int i = 0, length = this.patternLocators.length; i < length; i++) {
- int newLevel = this.patternLocators[i].match(node, nodeSet);
- if (newLevel > level) {
- if (newLevel == ACCURATE_MATCH) return ACCURATE_MATCH;
- level = newLevel;
- }
- }
- return level;
-}
-
-public int match(TypeReference node, MatchingNodeSet nodeSet) {
- int level = IMPOSSIBLE_MATCH;
- for (int i = 0, length = this.patternLocators.length; i < length; i++) {
- int newLevel = this.patternLocators[i].match(node, nodeSet);
- if (newLevel > level) {
- if (newLevel == ACCURATE_MATCH) return ACCURATE_MATCH;
- level = newLevel;
- }
- }
- return level;
-}
-protected int matchContainer() {
- int result = 0;
- for (int i = 0, length = this.patternLocators.length; i < length; i++)
- result |= this.patternLocators[i].matchContainer();
- return result;
-}
-protected void matchLevelAndReportImportRef(ImportReference importRef, Binding binding, MatchLocator locator) throws CoreException {
- Binding refBinding = binding;
-
- // Look for closest pattern
- PatternLocator closestPattern = null;
- int level = IMPOSSIBLE_MATCH;
- for (int i = 0, length = this.patternLocators.length; i < length; i++) {
- PatternLocator patternLocator = this.patternLocators[i];
- int newLevel = patternLocator.referenceType() == 0 ? IMPOSSIBLE_MATCH : patternLocator.resolveLevel(refBinding);
- if (newLevel > level) {
- closestPattern = patternLocator;
- if (newLevel == ACCURATE_MATCH) break;
- level = newLevel;
- }
- }
- if (closestPattern != null) {
- closestPattern.matchLevelAndReportImportRef(importRef, binding, locator);
- }
-}
-protected void matchReportImportRef(ImportReference importRef, Binding binding, IJavaScriptElement element, int accuracy, MatchLocator locator) throws CoreException {
- PatternLocator closestPattern = null;
- int level = IMPOSSIBLE_MATCH;
- for (int i = 0, length = this.patternLocators.length; i < length; i++) {
- int newLevel = this.patternLocators[i].matchLevel(importRef);
- if (newLevel > level) {
- closestPattern = this.patternLocators[i];
- if (newLevel == ACCURATE_MATCH) break;
- level = newLevel;
- }
- }
- if (closestPattern != null)
- closestPattern.matchReportImportRef(importRef, binding, element, accuracy, locator);
-}
-protected void matchReportReference(ASTNode reference, IJavaScriptElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException {
- PatternLocator closestPattern = null;
- int level = IMPOSSIBLE_MATCH;
- for (int i = 0, length = this.patternLocators.length; i < length; i++) {
- PatternLocator patternLocator = this.patternLocators[i];
- int newLevel = patternLocator.referenceType() == 0 ? IMPOSSIBLE_MATCH : patternLocator.resolveLevel(reference);
- if (newLevel > level) {
- closestPattern = patternLocator;
- if (newLevel == ACCURATE_MATCH) break;
- level = newLevel;
- }
- }
- if (closestPattern != null)
- closestPattern.matchReportReference(reference, element, elementBinding, accuracy, locator);
-}
-public SearchMatch newDeclarationMatch(ASTNode reference, IJavaScriptElement element, Binding elementBinding, int accuracy, int length, MatchLocator locator) {
- PatternLocator closestPattern = null;
- int level = IMPOSSIBLE_MATCH;
- for (int i = 0, pl = this.patternLocators.length; i < pl; i++) {
- PatternLocator patternLocator = this.patternLocators[i];
- int newLevel = patternLocator.referenceType() == 0 ? IMPOSSIBLE_MATCH : patternLocator.resolveLevel(reference);
- if (newLevel > level) {
- closestPattern = patternLocator;
- if (newLevel == ACCURATE_MATCH) break;
- level = newLevel;
- }
- }
- if (closestPattern != null) {
- return closestPattern.newDeclarationMatch(reference, element, elementBinding, accuracy, length, locator);
- }
- // super implementation...
- return locator.newDeclarationMatch(element, elementBinding, accuracy, reference.sourceStart, length);
-}
-public int resolveLevel(ASTNode node) {
- int level = IMPOSSIBLE_MATCH;
- for (int i = 0, length = this.patternLocators.length; i < length; i++) {
- int newLevel = this.patternLocators[i].resolveLevel(node);
- if (newLevel > level) {
- if (newLevel == ACCURATE_MATCH) return ACCURATE_MATCH;
- level = newLevel; // want to answer the stronger match
- }
- }
- return level;
-}
-public int resolveLevel(Binding binding) {
- int level = IMPOSSIBLE_MATCH;
- for (int i = 0, length = this.patternLocators.length; i < length; i++) {
- int newLevel = this.patternLocators[i].resolveLevel(binding);
- if (newLevel > level) {
- if (newLevel == ACCURATE_MATCH) return ACCURATE_MATCH;
- level = newLevel; // want to answer the stronger match
- }
- }
- return level;
-}
-}
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
deleted file mode 100644
index 0d4271ce..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/OrPattern.java
+++ /dev/null
@@ -1,109 +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 java.io.IOException;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchParticipant;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.core.index.Index;
-import org.eclipse.wst.jsdt.internal.core.search.IndexQueryRequestor;
-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;
-
- public OrPattern(SearchPattern leftPattern, SearchPattern rightPattern) {
- super(Math.max(leftPattern.getMatchRule(), rightPattern.getMatchRule()));
- ((InternalSearchPattern)this).kind = OR_PATTERN;
- ((InternalSearchPattern)this).mustResolve = ((InternalSearchPattern) leftPattern).mustResolve || ((InternalSearchPattern) rightPattern).mustResolve;
-
- SearchPattern[] leftPatterns = leftPattern instanceof OrPattern ? ((OrPattern) leftPattern).patterns : null;
- SearchPattern[] rightPatterns = rightPattern instanceof OrPattern ? ((OrPattern) rightPattern).patterns : null;
- int leftSize = leftPatterns == null ? 1 : leftPatterns.length;
- int rightSize = rightPatterns == null ? 1 : rightPatterns.length;
- this.patterns = new SearchPattern[leftSize + rightSize];
-
- if (leftPatterns == null)
- this.patterns[0] = leftPattern;
- else
- System.arraycopy(leftPatterns, 0, this.patterns, 0, leftSize);
- if (rightPatterns == null)
- this.patterns[leftSize] = rightPattern;
- else
- System.arraycopy(rightPatterns, 0, this.patterns, leftSize, rightSize);
-
- // Store erasure match
- matchCompatibility = 0;
- for (int i = 0, length = this.patterns.length; i < length; i++) {
- matchCompatibility |= ((JavaSearchPattern) this.patterns[i]).matchCompatibility;
- }
- }
- public void findIndexMatches(Index index, IndexQueryRequestor requestor, SearchParticipant participant, IJavaScriptSearchScope scope, IProgressMonitor progressMonitor) throws IOException {
- // per construction, OR pattern can only be used with a PathCollector (which already gather results using a set)
- try {
- index.startQuery();
- for (int i = 0, length = this.patterns.length; i < length; i++)
- ((InternalSearchPattern)this.patterns[i]).findIndexMatches(index, requestor, participant, scope, progressMonitor);
- } finally {
- index.stopQuery();
- }
- }
-
- public SearchPattern getBlankPattern() {
- return null;
- }
-
- boolean isErasureMatch() {
- return (this.matchCompatibility & R_ERASURE_MATCH) != 0;
- }
-
- boolean isPolymorphicSearch() {
- for (int i = 0, length = this.patterns.length; i < length; i++)
- if (((InternalSearchPattern) this.patterns[i]).isPolymorphicSearch()) return true;
- return false;
- }
-
- /**
- * Returns whether the pattern has signatures or not.
- * @return true if one at least of the stored pattern has signatures.
- */
- public final boolean hasSignatures() {
- boolean isErasureMatch = isErasureMatch();
- for (int i = 0, length = this.patterns.length; i < length && !isErasureMatch; i++) {
- if (((JavaSearchPattern) this.patterns[i]).hasSignatures()) return true;
- }
- return false;
- }
-
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- buffer.append(this.patterns[0].toString());
- for (int i = 1, length = this.patterns.length; i < length; i++) {
- buffer.append("\n| "); //$NON-NLS-1$
- buffer.append(this.patterns[i].toString());
- }
- return buffer.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/PackageDeclarationLocator.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/PackageDeclarationLocator.java
deleted file mode 100644
index ea7db24b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/PackageDeclarationLocator.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.search.matching;
-
-public class PackageDeclarationLocator extends PatternLocator {
-
-protected PackageDeclarationPattern pattern;
-
-public PackageDeclarationLocator(PackageDeclarationPattern pattern) {
- super(pattern);
-
- this.pattern = pattern;
-}
-protected int matchContainer() {
- return 0;
-}
-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/PackageDeclarationPattern.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/PackageDeclarationPattern.java
deleted file mode 100644
index f9fd5d0f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/PackageDeclarationPattern.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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.internal.core.index.EntryResult;
-import org.eclipse.wst.jsdt.internal.core.index.Index;
-
-public class PackageDeclarationPattern extends JavaSearchPattern {
-
-protected char[] pkgName;
-
-public PackageDeclarationPattern(char[] pkgName, int matchRule) {
- super(PKG_DECL_PATTERN, matchRule);
- this.pkgName = pkgName;
-}
-EntryResult[] queryIn(Index index) {
- // package declarations are not indexed
- return null;
-}
-protected StringBuffer print(StringBuffer output) {
- output.append("PackageDeclarationPattern: <"); //$NON-NLS-1$
- if (this.pkgName != null)
- output.append(this.pkgName);
- 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/PackageReferenceLocator.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/PackageReferenceLocator.java
deleted file mode 100644
index d4fe40c9..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/PackageReferenceLocator.java
+++ /dev/null
@@ -1,337 +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.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-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.ast.ASTNode;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ImportReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocQualifiedTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocSingleTypeReference;
-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.TypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ArrayBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Binding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ImportBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding;
-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.ReferenceBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-import org.eclipse.wst.jsdt.internal.compiler.util.Util;
-
-public class PackageReferenceLocator extends PatternLocator {
-
-protected PackageReferencePattern pattern;
-
-// check that referenced type is actually defined in this package fragment
-public static boolean isDeclaringPackageFragment(IPackageFragment packageFragment, ReferenceBinding typeBinding) {
- char[] fileName = typeBinding.getFileName();
- if (fileName != null) {
- // retrieve the actual file name from the full path (sources are generally only containing it already)
- fileName = CharOperation.replaceOnCopy(fileName, '/', '\\'); // ensure to not do any side effect on file name (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=136016)
- fileName = CharOperation.lastSegment(fileName, '\\');
-
- try {
- switch (packageFragment.getKind()) {
- case IPackageFragmentRoot.K_SOURCE :
- if (!org.eclipse.wst.jsdt.internal.core.util.Util.isJavaLikeFileName(fileName) || !packageFragment.getJavaScriptUnit(new String(fileName)).exists()) {
- return false; // unit doesn't live in selected package
- }
- break;
- case IPackageFragmentRoot.K_BINARY :
-// if (Util.isJavaFileName(fileName)) { // binary with attached source
-// int length = fileName.length;
-// System.arraycopy(fileName, 0, fileName = new char[length], 0, length - 4); // copy all but extension
-// System.arraycopy(SuffixConstants.SUFFIX_class, 0, fileName, length - 4, 4);
-// }
- if (!Util.isClassFileName(fileName) || !packageFragment.getClassFile(new String(fileName)).exists()) {
- return false; // classfile doesn't live in selected package
- }
- break;
- }
- } catch(JavaScriptModelException e) {
- // unable to determine kind; tolerate this match
- }
- }
- return true; // by default, do not eliminate
-}
-
-public PackageReferenceLocator(PackageReferencePattern pattern) {
- super(pattern);
-
- this.pattern = pattern;
-}
-public int match(ASTNode node, MatchingNodeSet nodeSet) { // interested in ImportReference
- if (!(node instanceof ImportReference)) return IMPOSSIBLE_MATCH;
-
- return nodeSet.addMatch(node, matchLevel((ImportReference) node));
-}
-//public int match(ConstructorDeclaration node, MatchingNodeSet nodeSet) - SKIP IT
-//public int match(Expression node, MatchingNodeSet nodeSet) - SKIP IT
-//public int match(FieldDeclaration node, MatchingNodeSet nodeSet) - SKIP IT
-//public int match(FunctionDeclaration node, MatchingNodeSet nodeSet) - SKIP IT
-//public int match(MessageSend node, MatchingNodeSet nodeSet) - SKIP IT
-public int match(Reference node, MatchingNodeSet nodeSet) { // interested in QualifiedNameReference
- if (!(node instanceof QualifiedNameReference)) return IMPOSSIBLE_MATCH;
-
- return nodeSet.addMatch(node, matchLevelForTokens(((QualifiedNameReference) node).tokens));
-}
-//public int match(TypeDeclaration node, MatchingNodeSet nodeSet) - SKIP IT
-public int match(TypeReference node, MatchingNodeSet nodeSet) { // interested in QualifiedTypeReference only
- if (node instanceof JavadocSingleTypeReference) {
- char[][] tokens = new char[][] { ((JavadocSingleTypeReference) node).token };
- return nodeSet.addMatch(node, matchLevelForTokens(tokens));
- }
- if (!(node instanceof QualifiedTypeReference)) return IMPOSSIBLE_MATCH;
- return nodeSet.addMatch(node, matchLevelForTokens(((QualifiedTypeReference) node).tokens));
-}
-
-protected int matchLevel(ImportReference importRef) {
- return matchLevelForTokens(importRef.tokens);
-}
-protected int matchLevelForTokens(char[][] tokens) {
- if (this.pattern.pkgName == null) return ACCURATE_MATCH;
-
- char[] packageName = null;
- if (this.isCamelCase) {
- packageName = CharOperation.concatWith(tokens, '.');
- if (CharOperation.camelCaseMatch(this.pattern.pkgName, packageName)) {
- return POSSIBLE_MATCH;
- }
- }
- switch (this.matchMode) {
- case SearchPattern.R_EXACT_MATCH:
- case SearchPattern.R_PREFIX_MATCH:
- if (packageName==null) packageName = CharOperation.concatWith(tokens, '.');
- if (CharOperation.prefixEquals(this.pattern.pkgName, packageName, this.isCaseSensitive)) {
- return POSSIBLE_MATCH;
- }
- break;
- case SearchPattern.R_PATTERN_MATCH:
- char[] patternName = this.pattern.pkgName[this.pattern.pkgName.length - 1] == '*'
- ? this.pattern.pkgName
- : CharOperation.concat(this.pattern.pkgName, ".*".toCharArray()); //$NON-NLS-1$
- if (packageName==null) packageName = CharOperation.concatWith(tokens, '.');
- if (CharOperation.match(patternName, packageName, this.isCaseSensitive)) {
- return POSSIBLE_MATCH;
- }
- break;
- case SearchPattern.R_REGEXP_MATCH :
- // TODO (frederic) implement regular expression match
- break;
- }
- return IMPOSSIBLE_MATCH;
-}
-protected void matchReportImportRef(ImportReference importRef, Binding binding, IJavaScriptElement element, int accuracy, MatchLocator locator) throws CoreException {
- if (binding == null) {
- this.matchReportReference(importRef, element, null/*no binding*/, accuracy, locator);
- } else {
- if (locator.encloses(element)) {
- long[] positions = importRef.sourcePositions;
- int last = positions.length - 1;
- if (binding instanceof ProblemReferenceBinding)
- binding = ((ProblemReferenceBinding) binding).closestMatch();
- if (binding instanceof ReferenceBinding) {
- PackageBinding pkgBinding = ((ReferenceBinding) binding).fPackage;
- if (pkgBinding != null)
- last = pkgBinding.compoundName.length;
- }
- if (binding instanceof PackageBinding)
- last = ((PackageBinding) binding).compoundName.length;
- int start = (int) (positions[0] >>> 32);
- int end = (int) positions[last - 1];
- match = locator.newPackageReferenceMatch(element, accuracy, start, end-start+1, importRef);
- locator.report(match);
- }
- }
-}
-protected void matchReportReference(ASTNode reference, IJavaScriptElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException {
- long[] positions = null;
- int last = -1;
- if (reference instanceof ImportReference) {
- ImportReference importRef = (ImportReference) reference;
- positions = importRef.sourcePositions;
- last = (importRef.bits & ASTNode.OnDemand) != 0 ? positions.length : positions.length - 1;
- } else {
- TypeBinding typeBinding = null;
- if (reference instanceof QualifiedNameReference) {
- QualifiedNameReference qNameRef = (QualifiedNameReference) reference;
- positions = qNameRef.sourcePositions;
- switch (qNameRef.bits & ASTNode.RestrictiveFlagMASK) {
- case Binding.FIELD : // reading a field
- typeBinding = qNameRef.actualReceiverType;
- break;
- case Binding.TYPE : //=============only type ==============
- if (qNameRef.binding instanceof TypeBinding)
- typeBinding = (TypeBinding) qNameRef.binding;
- break;
- case Binding.VARIABLE : //============unbound cases===========
- case Binding.TYPE | Binding.VARIABLE :
- Binding binding = qNameRef.binding;
- if (binding instanceof TypeBinding) {
- typeBinding = (TypeBinding) binding;
- } else if (binding instanceof ProblemFieldBinding) {
- typeBinding = qNameRef.actualReceiverType;
- last = qNameRef.tokens.length - (qNameRef.otherBindings == null ? 2 : qNameRef.otherBindings.length + 2);
- } else if (binding instanceof ProblemBinding) {
- ProblemBinding pbBinding = (ProblemBinding) binding;
- typeBinding = pbBinding.searchType;
- last = CharOperation.occurencesOf('.', pbBinding.name);
- }
- break;
- }
- } else if (reference instanceof QualifiedTypeReference) {
- QualifiedTypeReference qTypeRef = (QualifiedTypeReference) reference;
- positions = qTypeRef.sourcePositions;
- typeBinding = qTypeRef.resolvedType;
- } else if (reference instanceof JavadocSingleTypeReference) {
- JavadocSingleTypeReference jsTypeRef = (JavadocSingleTypeReference) reference;
- positions = new long[1];
- positions[0] = (((long)jsTypeRef.sourceStart) << 32) + jsTypeRef.sourceEnd;
- typeBinding = jsTypeRef.resolvedType;
- }
- if (positions == null) return;
- if (typeBinding instanceof ArrayBinding)
- typeBinding = ((ArrayBinding) typeBinding).leafComponentType;
- if (typeBinding instanceof ProblemReferenceBinding)
- typeBinding = ((ProblemReferenceBinding) typeBinding).closestMatch();
- if (typeBinding instanceof ReferenceBinding) {
- PackageBinding pkgBinding = ((ReferenceBinding) typeBinding).fPackage;
- if (pkgBinding != null)
- last = pkgBinding.compoundName.length;
- }
- // Do not report qualified references which are only enclosing type
- // (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=91078)
- ReferenceBinding enclosingType = typeBinding == null ? null: typeBinding.enclosingType();
- if (enclosingType != null) {
- int length = positions.length;
- while (enclosingType != null && length > 0) {
- length--;
- enclosingType = enclosingType.enclosingType();
- }
- if (length <= 1) return;
- }
- }
- if (last == -1) {
- last = this.pattern.segments.length;
- }
- if (last == 0) return;
- if (last > positions.length) last = positions.length;
- int sourceStart = (int) (positions[0] >>> 32);
- int sourceEnd = ((int) positions[last - 1]);
- match = locator.newPackageReferenceMatch(element, accuracy, sourceStart, sourceEnd-sourceStart+1, reference);
- locator.report(match);
-}
-protected int referenceType() {
- return IJavaScriptElement.PACKAGE_FRAGMENT;
-}
-public int resolveLevel(ASTNode node) {
- if (node instanceof JavadocQualifiedTypeReference) {
- JavadocQualifiedTypeReference qualifRef = (JavadocQualifiedTypeReference) node;
- if (qualifRef.packageBinding != null)
- return resolveLevel(qualifRef.packageBinding);
- return resolveLevel(qualifRef.resolvedType);
- }
- if (node instanceof JavadocSingleTypeReference) {
- JavadocSingleTypeReference singleRef = (JavadocSingleTypeReference) node;
- if (singleRef.packageBinding != null)
- return resolveLevel(singleRef.packageBinding);
- return IMPOSSIBLE_MATCH;
- }
- if (node instanceof QualifiedTypeReference)
- return resolveLevel(((QualifiedTypeReference) node).resolvedType);
- if (node instanceof QualifiedNameReference)
- return this.resolveLevel((QualifiedNameReference) node);
-// if (node instanceof ImportReference) - Not called when resolve is true, see MatchingNodeSet.reportMatching(unit)
- return IMPOSSIBLE_MATCH;
-}
-public int resolveLevel(Binding binding) {
- if (binding == null) return INACCURATE_MATCH;
-
- char[][] compoundName = null;
- if (binding instanceof ImportBinding) {
- compoundName = ((ImportBinding) binding).compoundName;
- } else if (binding instanceof PackageBinding) {
- compoundName = ((PackageBinding) binding).compoundName;
- } else {
- if (binding instanceof ArrayBinding)
- binding = ((ArrayBinding) binding).leafComponentType;
- if (binding instanceof ProblemReferenceBinding)
- binding = ((ProblemReferenceBinding) binding).closestMatch();
- if (binding == null) return INACCURATE_MATCH;
-
- if (binding instanceof ReferenceBinding) {
- PackageBinding pkgBinding = ((ReferenceBinding) binding).fPackage;
- if (pkgBinding == null) return INACCURATE_MATCH;
- compoundName = pkgBinding.compoundName;
- }
- }
- if (compoundName != null && matchesName(this.pattern.pkgName, CharOperation.concatWith(compoundName, '.'))) {
- if (((InternalSearchPattern) this.pattern).focus instanceof IPackageFragment && binding instanceof ReferenceBinding) {
- // check that type is located inside this instance of a package fragment
- if (!isDeclaringPackageFragment((IPackageFragment)((InternalSearchPattern) this.pattern).focus, (ReferenceBinding)binding))
- return IMPOSSIBLE_MATCH;
- }
- return ACCURATE_MATCH;
- } else {
- return IMPOSSIBLE_MATCH;
- }
-}
-protected int resolveLevel(QualifiedNameReference qNameRef) {
- TypeBinding typeBinding = null;
- switch (qNameRef.bits & ASTNode.RestrictiveFlagMASK) {
- case Binding.FIELD : // reading a field
- if (qNameRef.tokens.length < (qNameRef.otherBindings == null ? 3 : qNameRef.otherBindings.length + 3))
- return IMPOSSIBLE_MATCH; // must be at least p1.A.x
- typeBinding = qNameRef.actualReceiverType;
- break;
- case Binding.LOCAL : // reading a local variable
- return IMPOSSIBLE_MATCH; // no package match in it
- case Binding.TYPE : //=============only type ==============
- if (qNameRef.binding instanceof TypeBinding)
- typeBinding = (TypeBinding) qNameRef.binding;
- break;
- /*
- * Handling of unbound qualified name references. The match may reside in the resolved fragment,
- * which is recorded inside the problem binding, along with the portion of the name until it became a problem.
- */
- case Binding.VARIABLE : //============unbound cases===========
- case Binding.TYPE | Binding.VARIABLE :
- Binding binding = qNameRef.binding;
- if (binding instanceof ProblemReferenceBinding) {
- typeBinding = (TypeBinding) binding;
- } else if (binding instanceof ProblemFieldBinding) {
- if (qNameRef.tokens.length < (qNameRef.otherBindings == null ? 3 : qNameRef.otherBindings.length + 3))
- return IMPOSSIBLE_MATCH; // must be at least p1.A.x
- typeBinding = qNameRef.actualReceiverType;
- } else if (binding instanceof ProblemBinding) {
- ProblemBinding pbBinding = (ProblemBinding) binding;
- if (CharOperation.occurencesOf('.', pbBinding.name) <= 0) // index of last bound token is one before the pb token
- return INACCURATE_MATCH;
- typeBinding = pbBinding.searchType;
- }
- break;
- }
- return resolveLevel(typeBinding);
-}
-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/PackageReferencePattern.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/PackageReferencePattern.java
deleted file mode 100644
index 0551a1d9..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/PackageReferencePattern.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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;
-
-public class PackageReferencePattern extends AndPattern {
-
-protected char[] pkgName;
-
-protected char[][] segments;
-protected int currentSegment;
-
-protected static char[][] CATEGORIES = { REF };
-
-public PackageReferencePattern(char[] pkgName, int matchRule) {
- this(matchRule);
-
- if (pkgName == null || pkgName.length == 0) {
- this.pkgName = null;
- this.segments = new char[][] {CharOperation.NO_CHAR};
- ((InternalSearchPattern)this).mustResolve = false;
- } else {
- this.pkgName = (isCaseSensitive() || isCamelCase()) ? pkgName : CharOperation.toLowerCase(pkgName);
- this.segments = CharOperation.splitOn('.', this.pkgName);
- ((InternalSearchPattern)this).mustResolve = true;
- }
-}
-PackageReferencePattern(int matchRule) {
- super(PKG_REF_PATTERN, matchRule);
-}
-public void decodeIndexKey(char[] key) {
- // Package reference keys are encoded as 'name' (where 'name' is the last segment of the package name)
- this.pkgName = key;
-}
-public SearchPattern getBlankPattern() {
- return new PackageReferencePattern(R_EXACT_MATCH | R_CASE_SENSITIVE);
-}
-public char[] getIndexKey() {
- // Package reference keys are encoded as 'name' (where 'name' is the last segment of the package name)
- if (this.currentSegment >= 0)
- return this.segments[this.currentSegment];
- return null;
-}
-public char[][] getIndexCategories() {
- return CATEGORIES;
-}
-protected boolean hasNextQuery() {
- // if package has at least 4 segments, don't look at the first 2 since they are mostly
- // redundant (eg. in 'org.eclipse.wst.jsdt.core.*' 'org.eclipse' is used all the time)
- return --this.currentSegment >= (this.segments.length >= 4 ? 2 : 0);
-}
-public boolean matchesDecodedKey(SearchPattern decodedPattern) {
- return true; // index key is not encoded so query results all match
-}
-protected void resetQuery() {
- /* walk the segments from end to start as it will find less potential references using 'lang' than 'java' */
- this.currentSegment = this.segments.length - 1;
-}
-protected StringBuffer print(StringBuffer output) {
- output.append("PackageReferencePattern: <"); //$NON-NLS-1$
- if (this.pkgName != null)
- output.append(this.pkgName);
- 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/PatternLocator.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/PatternLocator.java
deleted file mode 100644
index fda8902e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/PatternLocator.java
+++ /dev/null
@@ -1,682 +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 java.util.Arrays;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.Signature;
-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.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.ConstructorDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Expression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration;
-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.Reference;
-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.lookup.ArrayBinding;
-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.Scope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-import org.eclipse.wst.jsdt.internal.core.search.indexing.IIndexConstants;
-
-public abstract class PatternLocator implements IIndexConstants {
-
-// store pattern info
-protected int matchMode;
-protected boolean isCaseSensitive;
-protected boolean isCamelCase;
-protected boolean isEquivalentMatch;
-protected boolean isErasureMatch;
-protected boolean mustResolve;
-protected boolean mayBeGeneric;
-
-// match to report
-SearchMatch match = null;
-
-/* match levels */
-public static final int IMPOSSIBLE_MATCH = 0;
-public static final int INACCURATE_MATCH = 1;
-public static final int POSSIBLE_MATCH = 2;
-public static final int ACCURATE_MATCH = 3;
-public static final int ERASURE_MATCH = 4;
-
-// Possible rule match flavors
-// see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=79866
-public static final int EXACT_FLAVOR = 0x0010;
-public static final int PREFIX_FLAVOR = 0x0020;
-public static final int PATTERN_FLAVOR = 0x0040;
-public static final int REGEXP_FLAVOR = 0x0080;
-public static final int CAMELCASE_FLAVOR = 0x0100;
-public static final int SUPER_INVOCATION_FLAVOR = 0x0200;
-public static final int SUB_INVOCATION_FLAVOR = 0x0400;
-public static final int OVERRIDDEN_METHOD_FLAVOR = 0x0800;
-public static final int MATCH_LEVEL_MASK = 0x0F;
-public static final int FLAVORS_MASK = ~MATCH_LEVEL_MASK;
-
-/* match container */
-public static final int COMPILATION_UNIT_CONTAINER = 1;
-public static final int CLASS_CONTAINER = 2;
-public static final int METHOD_CONTAINER = 4;
-public static final int FIELD_CONTAINER = 8;
-public static final int ALL_CONTAINER =
- COMPILATION_UNIT_CONTAINER | CLASS_CONTAINER | METHOD_CONTAINER | FIELD_CONTAINER;
-
-/* match rule */
-public static final int RAW_MASK = SearchPattern.R_EQUIVALENT_MATCH | SearchPattern.R_ERASURE_MATCH;
-public static final int RULE_MASK = RAW_MASK; // no other values for the while...
-
-public static PatternLocator patternLocator(SearchPattern pattern) {
- switch (((InternalSearchPattern)pattern).kind) {
- case IIndexConstants.PKG_REF_PATTERN :
- return new PackageReferenceLocator((PackageReferencePattern) pattern);
- case IIndexConstants.PKG_DECL_PATTERN :
- return new PackageDeclarationLocator((PackageDeclarationPattern) pattern);
- case IIndexConstants.TYPE_REF_PATTERN :
- return new TypeReferenceLocator((TypeReferencePattern) pattern);
- case IIndexConstants.TYPE_DECL_PATTERN :
- return new TypeDeclarationLocator((TypeDeclarationPattern) pattern);
- case IIndexConstants.SUPER_REF_PATTERN :
- return new SuperTypeReferenceLocator((SuperTypeReferencePattern) pattern);
- case IIndexConstants.CONSTRUCTOR_PATTERN :
- return new ConstructorLocator((ConstructorPattern) pattern);
- case IIndexConstants.FIELD_PATTERN :
- IJavaScriptElement element = ((FieldPattern)pattern).getJavaElement();
- if (element instanceof IField) {
- IField field = (IField) element;
- if (field.getDeclaringType()==null)
- return new LocalVariableLocator((VariablePattern)pattern);
- }
- return new FieldLocator((FieldPattern) pattern);
- case IIndexConstants.METHOD_PATTERN :
- return new MethodLocator((MethodPattern) pattern);
- case IIndexConstants.OR_PATTERN :
- return new OrLocator((OrPattern) pattern);
- case IIndexConstants.LOCAL_VAR_PATTERN :
- return new LocalVariableLocator((LocalVariablePattern) pattern);
- }
- return null;
-}
-public static char[] qualifiedPattern(char[] simpleNamePattern, char[] qualificationPattern) {
- // NOTE: if case insensitive search then simpleNamePattern & qualificationPattern are assumed to be lowercase
- if (simpleNamePattern == null) {
- if (qualificationPattern == null) return null;
- return CharOperation.concat(qualificationPattern, ONE_STAR, '.');
- } else {
- return qualificationPattern == null
- ? CharOperation.concat(ONE_STAR, simpleNamePattern)
- : CharOperation.concat(qualificationPattern, simpleNamePattern, '/');
- }
-}
-public static char[] qualifiedSourceName(TypeBinding binding) {
- if (binding instanceof ReferenceBinding) {
- ReferenceBinding type = (ReferenceBinding) binding;
- if (type.isLocalType())
- return type.isMemberType()
- ? CharOperation.concat(qualifiedSourceName(type.enclosingType()), type.sourceName(), '.')
- : CharOperation.concat(qualifiedSourceName(type.enclosingType()), new char[] {'.', '1', '.'}, type.sourceName());
- }
- return binding != null ? binding.qualifiedSourceName() : null;
-}
-
-public PatternLocator(SearchPattern pattern) {
- int matchRule = pattern.getMatchRule();
- this.isCaseSensitive = (matchRule & SearchPattern.R_CASE_SENSITIVE) != 0;
- this.isCamelCase = (matchRule & SearchPattern.R_CAMELCASE_MATCH) != 0;
- this.isErasureMatch = (matchRule & SearchPattern.R_ERASURE_MATCH) != 0;
- this.isEquivalentMatch = (matchRule & SearchPattern.R_EQUIVALENT_MATCH) != 0;
- this.matchMode = matchRule & JavaSearchPattern.MATCH_MODE_MASK;
- this.mustResolve = ((InternalSearchPattern)pattern).mustResolve;
-}
-/*
- * Clear caches
- */
-protected void clear() {
- // nothing to clear by default
-}
-/* (non-Javadoc)
- * Modify PatternLocator.qualifiedPattern behavior:
- * do not add star before simple name pattern when qualification pattern is null.
- * This avoid to match p.X when pattern is only X...
- */
-protected char[] getQualifiedPattern(char[] simpleNamePattern, char[] qualificationPattern) {
- // NOTE: if case insensitive search then simpleNamePattern & qualificationPattern are assumed to be lowercase
- if (simpleNamePattern == null) {
- if (qualificationPattern == null) return null;
- return CharOperation.concat(qualificationPattern, ONE_STAR, '.');
- } else if (qualificationPattern == null) {
- return simpleNamePattern;
- } else {
- return CharOperation.concat(qualificationPattern, simpleNamePattern, '.');
- }
-}
-/* (non-Javadoc)
- * Modify PatternLocator.qualifiedSourceName behavior:
- * also concatene enclosing type name when type is a only a member type.
- */
-protected char[] getQualifiedSourceName(TypeBinding binding) {
- TypeBinding type = binding instanceof ArrayBinding ? ((ArrayBinding)binding).leafComponentType : binding;
- if (type instanceof ReferenceBinding) {
- if (type.isLocalType()) {
- return CharOperation.concat(qualifiedSourceName(type.enclosingType()), new char[] {'.', '1', '.'}, binding.sourceName());
- } else if (type.isMemberType()) {
- return CharOperation.concat(qualifiedSourceName(type.enclosingType()), binding.sourceName(), '.');
- }
- }
- return binding != null ? binding.qualifiedSourceName() : null;
-}
-/*
- * Get binding of type argument from a class unit scope and its index position.
- * Cache is lazy initialized and if no binding is found, then store a problem binding
- * to avoid making research twice...
- */
-protected TypeBinding getTypeNameBinding(int index) {
- return null;
-}
-/**
- * Initializes this search pattern so that polymorphic search can be performed.
- */
-public void initializePolymorphicSearch(MatchLocator locator) {
- // default is to do nothing
-}
-/**
- * Check if the given ast node syntactically matches this pattern.
- * If it does, add it to the match set.
- * Returns the match level.
- */
-public int match(ASTNode node, MatchingNodeSet nodeSet) { // needed for some generic nodes
- // each subtype should override if needed
- return IMPOSSIBLE_MATCH;
-}
-public int match(ConstructorDeclaration node, MatchingNodeSet nodeSet) {
- // each subtype should override if needed
- return IMPOSSIBLE_MATCH;
-}
-public int match(Expression node, MatchingNodeSet nodeSet) {
- // each subtype should override if needed
- return IMPOSSIBLE_MATCH;
-}
-public int match(FieldDeclaration node, MatchingNodeSet nodeSet) {
- // each subtype should override if needed
- return IMPOSSIBLE_MATCH;
-}
-public int match(LocalDeclaration node, MatchingNodeSet nodeSet) {
- // each subtype should override if needed
- return IMPOSSIBLE_MATCH;
-}
-public int match(MethodDeclaration node, MatchingNodeSet nodeSet) {
- // each subtype should override if needed
- return IMPOSSIBLE_MATCH;
-}
-public int match(MessageSend node, MatchingNodeSet nodeSet) {
- // each subtype should override if needed
- return IMPOSSIBLE_MATCH;
-}
-public int match(Reference node, MatchingNodeSet nodeSet) {
- // each subtype should override if needed
- return IMPOSSIBLE_MATCH;
-}
-public int match(TypeDeclaration node, MatchingNodeSet nodeSet) {
- // each subtype should override if needed
- return IMPOSSIBLE_MATCH;
-}
-public int match(TypeReference node, MatchingNodeSet nodeSet) {
- // each subtype should override if needed
- return IMPOSSIBLE_MATCH;
-}
-public int match(InferredType inferredType, MatchingNodeSet nodeSet) {
- // each subtype should override if needed
- return IMPOSSIBLE_MATCH;
-}
-
-public int match(InferredMethod inferredMethod, MatchingNodeSet nodeSet) {
- // each subtype should override if needed
- return IMPOSSIBLE_MATCH;
-}
-
-public int match(InferredAttribute inferredAttribute, MatchingNodeSet nodeSet) {
- // each subtype should override if needed
- return IMPOSSIBLE_MATCH;
-}
-
-/**
- * Returns the type(s) of container for this pattern.
- * It is a bit combination of types, denoting compilation unit, class declarations, field declarations or method declarations.
- */
-protected int matchContainer() {
- // override if the pattern can be more specific
- return ALL_CONTAINER;
-}
-/**
- * Returns whether the given name matches the given pattern.
- */
-protected boolean matchesName(char[] pattern, char[] name) {
- if (pattern == null) return true; // null is as if it was "*"
- if (name == null) return false; // cannot match null name
- return matchNameValue(pattern, name) != IMPOSSIBLE_MATCH;
-}
-/**
- * Return how the given name matches the given pattern.
- * @see "https://bugs.eclipse.org/bugs/show_bug.cgi?id=79866"
- *
- * @param pattern
- * @param name
- * @return Possible values are:
- * <ul>
- * <li> {@link #ACCURATE_MATCH}</li>
- * <li> {@link #IMPOSSIBLE_MATCH}</li>
- * <li> {@link #POSSIBLE_MATCH} which may be flavored with following values:
- * <ul>
- * <li>{@link #EXACT_FLAVOR}: Given name is equals to pattern</li>
- * <li>{@link #PREFIX_FLAVOR}: Given name prefix equals to pattern</li>
- * <li>{@link #CAMELCASE_FLAVOR}: Given name matches pattern as Camel Case</li>
- * <li>{@link #PATTERN_FLAVOR}: Given name matches pattern as Pattern (ie. using '*' and '?' characters)</li>
- * </ul>
- * </li>
- * </ul>
- */
-protected int matchNameValue(char[] pattern, char[] name) {
- if (pattern == null) return ACCURATE_MATCH; // null is as if it was "*"
- if (name == null) return IMPOSSIBLE_MATCH; // cannot match null name
- if (name.length == 0) { // empty name
- if (pattern.length == 0) { // can only matches empty pattern
- return ACCURATE_MATCH;
- }
- return IMPOSSIBLE_MATCH;
- } else if (pattern.length == 0) {
- return IMPOSSIBLE_MATCH; // need to have both name and pattern length==0 to be accurate
- }
- boolean matchFirstChar = !this.isCaseSensitive || pattern[0] == name[0];
- boolean sameLength = pattern.length == name.length;
- boolean canBePrefix = name.length >= pattern.length;
- if (this.isCamelCase && matchFirstChar && CharOperation.camelCaseMatch(pattern, name)) {
- return POSSIBLE_MATCH;
- }
- switch (this.matchMode) {
- case SearchPattern.R_EXACT_MATCH:
- if (!this.isCamelCase) {
- if (sameLength && matchFirstChar && CharOperation.equals(pattern, name, this.isCaseSensitive)) {
- return POSSIBLE_MATCH | EXACT_FLAVOR;
- }
- break;
- }
- // fall through next case to match as prefix if camel case failed
- case SearchPattern.R_PREFIX_MATCH:
- if (canBePrefix && matchFirstChar && CharOperation.prefixEquals(pattern, name, this.isCaseSensitive)) {
- return POSSIBLE_MATCH;
- }
- break;
- case SearchPattern.R_PATTERN_MATCH:
- if (!this.isCaseSensitive) {
- pattern = CharOperation.toLowerCase(pattern);
- }
- if (CharOperation.match(pattern, name, this.isCaseSensitive)) {
- return POSSIBLE_MATCH;
- }
- break;
- case SearchPattern.R_REGEXP_MATCH :
- // TODO (frederic) implement regular expression match
- break;
- }
- return IMPOSSIBLE_MATCH;
-}
-/**
- * Returns whether the given type reference matches the given pattern.
- */
-protected boolean matchesTypeReference(char[] pattern, TypeReference type) {
- if (pattern == null) return true; // null is as if it was "*"
- if (type == null) return true; // treat as an inexact match
-
- char[][] compoundName = type.getTypeName();
- char[] simpleName = compoundName[compoundName.length - 1];
- int dimensions = type.dimensions() * 2;
- if (dimensions > 0) {
- int length = simpleName.length;
- char[] result = new char[length + dimensions];
- System.arraycopy(simpleName, 0, result, 0, length);
- for (int i = length, l = result.length; i < l;) {
- result[i++] = '[';
- result[i++] = ']';
- }
- simpleName = result;
- }
-
- return matchesName(pattern, simpleName);
-}
-/**
- * Returns the match level for the given importRef.
- */
-protected int matchLevel(ImportReference importRef) {
- // override if interested in import references which are caught by the generic version of match(ASTNode, MatchingNodeSet)
- return IMPOSSIBLE_MATCH;
-}
-/**
- * Reports the match of the given import reference if the resolveLevel is high enough.
- */
-protected void matchLevelAndReportImportRef(ImportReference importRef, Binding binding, MatchLocator locator) throws CoreException {
- int level = resolveLevel(binding);
- if (level >= INACCURATE_MATCH) {
- matchReportImportRef(
- importRef,
- binding,
- locator.createImportHandle(importRef),
- level == ACCURATE_MATCH
- ? SearchMatch.A_ACCURATE
- : SearchMatch.A_INACCURATE,
- locator);
- }
-}
-/**
- * Reports the match of the given import reference.
- */
-protected void matchReportImportRef(ImportReference importRef, Binding binding, IJavaScriptElement element, int accuracy, MatchLocator locator) throws CoreException {
- if (locator.encloses(element)) {
- // default is to report a match as a regular ref.
- this.matchReportReference(importRef, element, null/*no binding*/, accuracy, locator);
- }
-}
-/**
- * Reports the match of the given reference.
- */
-protected void matchReportReference(ASTNode reference, IJavaScriptElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException {
- match = null;
- int referenceType = referenceType();
- int offset = reference.sourceStart;
- switch (referenceType) {
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- match = locator.newPackageReferenceMatch(element, accuracy, offset, reference.sourceEnd-offset+1, reference);
- break;
- case IJavaScriptElement.TYPE:
- match = locator.newTypeReferenceMatch(element, elementBinding, accuracy, offset, reference.sourceEnd-offset+1, reference);
- break;
- case IJavaScriptElement.FIELD:
- match = locator.newFieldReferenceMatch(element, elementBinding, accuracy, offset, reference.sourceEnd-offset+1, reference);
- break;
- case IJavaScriptElement.LOCAL_VARIABLE:
- match = locator.newLocalVariableReferenceMatch(element, accuracy, offset, reference.sourceEnd-offset+1, reference);
- break;
- }
- if (match != null) {
- locator.report(match);
- }
-}
-/**
- * Reports the match of the given reference. Also provide a local element to eventually report in match.
- */
-protected void matchReportReference(ASTNode reference, IJavaScriptElement element, IJavaScriptElement localElement, IJavaScriptElement[] otherElements, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException {
- matchReportReference(reference, element, elementBinding, accuracy, locator);
-}
-/**
- * Reports the match of the given reference. Also provide a scope to look for potential other elements.
- */
-protected void matchReportReference(ASTNode reference, IJavaScriptElement element, Binding elementBinding, Scope scope, int accuracy, MatchLocator locator) throws CoreException {
- matchReportReference(reference, element, elementBinding, accuracy, locator);
-}
-public SearchMatch newDeclarationMatch(ASTNode reference, IJavaScriptElement element, Binding elementBinding, int accuracy, int length, MatchLocator locator) {
- int offset=(reference!=null )?reference.sourceStart : 0;
- if (reference instanceof AbstractMethodDeclaration) {
- AbstractMethodDeclaration method = (AbstractMethodDeclaration) reference;
- if (method.selector==null && method.inferredMethod!=null)
- {
- offset=method.inferredMethod.nameStart;
- if (length>=0)
- length=method.inferredMethod.name.length;
- }
- }
-
- return locator.newDeclarationMatch(element, elementBinding, accuracy, offset, length);
-}
-protected int referenceType() {
- return 0; // defaults to unknown (a generic JavaSearchMatch will be created)
-}
-/**
- * Finds out whether the given ast node matches this search pattern.
- * Returns IMPOSSIBLE_MATCH if it doesn't.
- * Returns INACCURATE_MATCH if it potentially matches this search pattern (ie.
- * it has already been resolved but resolving failed.)
- * Returns ACCURATE_MATCH if it matches exactly this search pattern (ie.
- * it doesn't need to be resolved or it has already been resolved.)
- */
-public int resolveLevel(ASTNode possibleMatchingNode) {
- // only called with nodes which were possible matches to the call to matchLevel
- // need to do instance of checks to find out exact type of ASTNode
- return IMPOSSIBLE_MATCH;
-}
-/*
- * Update pattern locator match comparing type arguments with pattern ones.
- * Try to resolve pattern and look for compatibility with type arguments
- * to set match rule.
- */
-protected void updateMatch(TypeBinding[] argumentsBinding, MatchLocator locator, char[][] patternArguments, boolean hasTypeParameters) {
- // Only possible if locator has an unit scope.
- if (locator.unitScope == null) return;
-
- // First compare lengthes
- int patternTypeArgsLength = patternArguments==null ? 0 : patternArguments.length;
- int typeArgumentsLength = argumentsBinding == null ? 0 : argumentsBinding.length;
-
- // Initialize match rule
- int matchRule = match.getRule();
- if (match.isRaw()) {
- if (patternTypeArgsLength != 0) {
- matchRule &= ~SearchPattern.R_FULL_MATCH;
- }
- }
- if (hasTypeParameters) {
- matchRule = SearchPattern.R_ERASURE_MATCH;
- }
-
- // Compare arguments lengthes
- if (patternTypeArgsLength == typeArgumentsLength) {
- if (!match.isRaw() && hasTypeParameters) {
- // generic patterns are always not compatible match
- match.setRule(SearchPattern.R_ERASURE_MATCH);
- return;
- }
- } else {
- if (patternTypeArgsLength==0) {
- if (!match.isRaw() || hasTypeParameters) {
- match.setRule(matchRule & ~SearchPattern.R_FULL_MATCH);
- }
- } else if (typeArgumentsLength==0) {
- // raw binding is always compatible
- match.setRule(matchRule & ~SearchPattern.R_FULL_MATCH);
- } else {
- match.setRule(0); // impossible match
- }
- return;
- }
- if (argumentsBinding == null || patternArguments == null) {
- match.setRule(matchRule);
- return;
- }
-
- // Compare binding for each type argument only if pattern is not erasure only and at first level
- if (!hasTypeParameters && !match.isRaw() && (match.isEquivalent() || match.isExact())) {
- for (int i=0; i<typeArgumentsLength; i++) {
- // Get parameterized type argument binding
- TypeBinding argumentBinding = argumentsBinding[i];
- // Get binding for pattern argument
- char[] patternTypeArgument = patternArguments[i];
- char patternWildcard = patternTypeArgument[0];
- char[] patternTypeName = patternTypeArgument;
-
- patternTypeName = Signature.toCharArray(patternTypeName);
- TypeBinding patternBinding = locator.getType(patternTypeArgument, patternTypeName);
-
- // If have no binding for pattern arg, then we won't be able to refine accuracy
- if (patternBinding == null) {
- continue;
- }
-
- // Verify tha pattern binding is compatible with match type argument binding
- switch (patternWildcard) {
- default:
- if (argumentBinding == patternBinding)
- // valid only when arg is equals to pattern
- continue;
- break;
- }
-
- // Argument does not match => erasure match will be the only possible one
- match.setRule(SearchPattern.R_ERASURE_MATCH);
- return;
- }
- }
-
- // Set match rule
- match.setRule(matchRule);
-}
-/**
- * Finds out whether the given binding matches this search pattern.
- * Returns ACCURATE_MATCH if it does.
- * Returns INACCURATE_MATCH if resolve failed but match is still possible.
- * Returns IMPOSSIBLE_MATCH otherwise.
- * Default is to return INACCURATE_MATCH.
- */
-public int resolveLevel(Binding binding) {
- // override if the pattern can match the binding
- return INACCURATE_MATCH;
-}
-/**
- * Returns whether the given type binding matches the given simple name pattern
- * and qualification pattern.
- * Note that from since 3.1, this method resolve to accurate member or local types
- * even if they are not fully qualified (ie. X.Member instead of p.X.Member).
- * Returns ACCURATE_MATCH if it does.
- * Returns INACCURATE_MATCH if resolve failed.
- * Returns IMPOSSIBLE_MATCH if it doesn't.
- */
-protected int resolveLevelForType(char[] simpleNamePattern, char[] qualificationPattern, TypeBinding binding) {
-// return resolveLevelForType(qualifiedPattern(simpleNamePattern, qualificationPattern), type);
- if (binding==TypeBinding.ANY || binding==TypeBinding.UNKNOWN)
- return ACCURATE_MATCH;
- if (Arrays.equals(Signature.ANY, simpleNamePattern))
- return ACCURATE_MATCH;
- char[] qualifiedPattern = getQualifiedPattern(simpleNamePattern, qualificationPattern);
- int level = resolveLevelForType(qualifiedPattern, binding);
- if (level == ACCURATE_MATCH || binding == null) return level;
- TypeBinding type = binding instanceof ArrayBinding ? ((ArrayBinding)binding).leafComponentType : binding;
- char[] sourceName = null;
- if (type.isMemberType() || type.isLocalType()) {
- if (qualificationPattern != null) {
- sourceName = getQualifiedSourceName(binding);
- } else {
- sourceName = binding.sourceName();
- }
- } else if (qualificationPattern == null) {
- 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);
- return matchPattern ? ACCURATE_MATCH : IMPOSSIBLE_MATCH;
-
-}
-
-/**
- * Returns whether the given type binding matches the given qualified pattern.
- * Returns ACCURATE_MATCH if it does.
- * Returns INACCURATE_MATCH if resolve failed.
- * Returns IMPOSSIBLE_MATCH if it doesn't.
- */
-protected int resolveLevelForType(char[] qualifiedPattern, TypeBinding type) {
- if (qualifiedPattern == null) return ACCURATE_MATCH;
- if (type == null) return INACCURATE_MATCH;
-
- // NOTE: if case insensitive search then qualifiedPattern is assumed to be lowercase
- char [] filePath=new char[]{};
- char [] bindingPath=filePath;
- int index;
- if ( (index=CharOperation.lastIndexOf('/', qualifiedPattern))>-1)
- {
- filePath=CharOperation.subarray(qualifiedPattern, 0, index);
- qualifiedPattern=CharOperation.subarray(qualifiedPattern, index+1, qualifiedPattern.length);
- bindingPath=type.getFileName();
- index=CharOperation.lastIndexOf('/', bindingPath);
- if (index>-1)
- bindingPath=CharOperation.subarray(bindingPath, 0, index);
- }
-
- char[] qualifiedPackageName = type.qualifiedPackageName();
- char[] qualifiedSourceName = qualifiedSourceName(type);
- char[] fullyQualifiedTypeName = qualifiedPackageName.length == 0
- ? qualifiedSourceName
- : CharOperation.concat(qualifiedPackageName, qualifiedSourceName, '.');
- if (CharOperation.match(qualifiedPattern, fullyQualifiedTypeName, this.isCaseSensitive))
- {
- if (filePath.length>0)
- {
- return (CharOperation.endsWith(bindingPath, filePath)) ? ACCURATE_MATCH:IMPOSSIBLE_MATCH;
- }
- return ACCURATE_MATCH;
- }
- return IMPOSSIBLE_MATCH;
-}
-/* (non-Javadoc)
- * Resolve level for type with a given binding with all pattern information.
- */
-protected int resolveLevelForType (char[] simpleNamePattern,
- char[] qualificationPattern,
- char[][][] patternTypeArguments,
- int depth,
- TypeBinding type) {
- // standard search with no generic additional information must succeed
- int level = resolveLevelForType(simpleNamePattern, qualificationPattern, type);
- if (level == IMPOSSIBLE_MATCH) return IMPOSSIBLE_MATCH;
- if (type == null || patternTypeArguments == null || patternTypeArguments.length == 0 || depth >= patternTypeArguments.length) {
- return level;
- }
-
- // Standard types (ie. neither generic nor parameterized nor raw types)
- // cannot match pattern with type parameters or arguments
- return (patternTypeArguments[depth]==null || patternTypeArguments[depth].length==0) ? level : IMPOSSIBLE_MATCH;
-
-}
-public String toString(){
- return "SearchPattern"; //$NON-NLS-1$
-}
-
-public int matchMetadataElement(IJavaScriptElement element)
-{
- return IMPOSSIBLE_MATCH;
-}
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/PossibleMatch.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/PossibleMatch.java
deleted file mode 100644
index 081e2028..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/PossibleMatch.java
+++ /dev/null
@@ -1,160 +0,0 @@
-/*******************************************************************************
- * 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.matching;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.wst.jsdt.core.LibrarySuperType;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.search.SearchDocument;
-import org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit;
-import org.eclipse.wst.jsdt.internal.core.ClassFile;
-import org.eclipse.wst.jsdt.internal.core.CompilationUnit;
-import org.eclipse.wst.jsdt.internal.core.Openable;
-import org.eclipse.wst.jsdt.internal.core.PackageFragment;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-public class PossibleMatch implements ICompilationUnit {
-
-public static final String NO_SOURCE_FILE_NAME = "NO SOURCE FILE NAME"; //$NON-NLS-1$
-
-public IResource resource;
-public Openable openable;
-public MatchingNodeSet nodeSet;
-public char[][] compoundName;
-CompilationUnitDeclaration parsedUnit;
-public SearchDocument document;
-private String sourceFileName;
-private char[] source;
-
-public PossibleMatch(MatchLocator locator, IResource resource, Openable openable, SearchDocument document, boolean mustResolve) {
- this.resource = resource;
- this.openable = openable;
- this.document = document;
- this.nodeSet = new MatchingNodeSet(mustResolve);
- char[] qualifiedName = getQualifiedName();
- if (qualifiedName != null)
- this.compoundName = CharOperation.splitOn('.', qualifiedName);
-}
-public void cleanUp() {
- this.source = null;
- if (this.parsedUnit != null) {
- this.parsedUnit.cleanUp();
- this.parsedUnit = null;
- }
- this.nodeSet = null;
-}
-public boolean equals(Object obj) {
- if (this.compoundName == null) return super.equals(obj);
- if (!(obj instanceof PossibleMatch)) return false;
-
- // By using the compoundName of the source file, multiple .class files (A, A$M...) are considered equal
- // Even .class files for secondary types and their nested types
- return CharOperation.equals(this.compoundName, ((PossibleMatch) obj).compoundName);
-}
-public char[] getContents() {
- if (this.source != null) return this.source;
-
- if (this.openable instanceof ClassFile) {
-// String fileName = getSourceFileName();
-// if (fileName == NO_SOURCE_FILE_NAME) return CharOperation.NO_CHAR;
-//
-// SourceMapper sourceMapper = this.openable.getSourceMapper();
-// IType type = ((ClassFile) this.openable).getType();
-// return this.source = sourceMapper.findSource(type, fileName);
- return this.source = ((ClassFile)this.openable ).getContents();
- }
- return this.source = this.document.getCharContents();
-}
-/**
- * The exact openable file name. In particular, will be the originating .class file for binary openable with attached
- * source.
- * @see org.eclipse.wst.jsdt.internal.compiler.env.IDependent#getFileName()
- * @see PackageReferenceLocator#isDeclaringPackageFragment(org.eclipse.wst.jsdt.core.IPackageFragment, org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding)
- */
-public char[] getFileName() {
- return this.openable.getPath().toString().toCharArray();
-}
-public char[] getMainTypeName() {
- // The file is no longer opened to get its name => remove fix for bug 32182
- return this.compoundName[this.compoundName.length-1];
-}
-public char[][] getPackageName() {
- int length = this.compoundName.length;
- if (length <= 1) return CharOperation.NO_CHAR_CHAR;
- return CharOperation.subarray(this.compoundName, 0, length - 1);
-}
-/*
- * Returns the fully qualified name of the main type of the compilation unit
- * or the main type of the .js file that defined the class file.
- */
-private char[] getQualifiedName() {
- if (this.openable instanceof CompilationUnit) {
- // get file name
- String fileName = this.openable.getElementName(); // working copy on a .class file may not have a resource, so use the element name
- // get main type name
- char[] mainTypeName = Util.getNameWithoutJavaLikeExtension(fileName).toCharArray();
- CompilationUnit cu = (CompilationUnit) this.openable;
- return cu.getType(new String(mainTypeName)).getFullyQualifiedName().toCharArray();
- } else if (this.openable instanceof ClassFile) {
- String fileName = getSourceFileName();
- if (fileName == NO_SOURCE_FILE_NAME)
- return ((ClassFile) this.openable).getType().getFullyQualifiedName('.').toCharArray();
-
- // Class file may have a source file name with ".js" extension (see bug 73784)
- int index = Util.indexOfJavaLikeExtension(fileName);
- String simpleName = index==-1 ? fileName : fileName.substring(0, index);
- PackageFragment pkg = (PackageFragment) this.openable.getParent();
- return Util.concatWith(pkg.names, simpleName, '.').toCharArray();
- }
- return null;
-}
-/*
- * Returns the source file name of the class file.
- * Returns NO_SOURCE_FILE_NAME if not found.
- */
-private String getSourceFileName() {
- if (this.sourceFileName != null) return this.sourceFileName;
-
- this.sourceFileName = NO_SOURCE_FILE_NAME;
-// if (this.openable.getSourceMapper() != null) {
-// BinaryType type = (BinaryType) ((ClassFile) this.openable).getType();
-// ClassFileReader reader = MatchLocator.classFileReader(type);
-// if (reader != null) {
-// String fileName = type.sourceFileName(reader);
-// this.sourceFileName = fileName == null ? NO_SOURCE_FILE_NAME : fileName;
-// }
-// }
- return this.sourceFileName;
-}
-public int hashCode() {
- if (this.compoundName == null) return super.hashCode();
-
- int hashCode = 0;
- for (int i = 0, length = this.compoundName.length; i < length; i++)
- hashCode += CharOperation.hashCode(this.compoundName[i]);
- return hashCode;
-}
-public String toString() {
- return this.openable == null ? "Fake PossibleMatch" : this.openable.toString(); //$NON-NLS-1$
-}
-/* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit#getCommonSuperType()
- */
-public LibrarySuperType getCommonSuperType() {
- return openable.getCommonSuperType();
-}
-public String getInferenceID() {
- return null;
-}
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/PossibleMatchSet.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/PossibleMatchSet.java
deleted file mode 100644
index f9e0c5ac..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/PossibleMatchSet.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.internal.compiler.util.ObjectVector;
-import org.eclipse.wst.jsdt.internal.compiler.util.SimpleLookupTable;
-
-/**
- * A set of PossibleMatches that is sorted by package fragment roots.
- */
-public class PossibleMatchSet {
-
-private SimpleLookupTable rootsToPossibleMatches = new SimpleLookupTable(5);
-private int elementCount = 0;
-private static final IPath VIRTUAL_RESOURCE = new Path("****&&VIRTUALRESOURCE&&*****"); //$NON-NLS-1$
-
-public void add(PossibleMatch possibleMatch) {
- IPath path = null;
- if(possibleMatch.document.isVirtual()) {
- path = VIRTUAL_RESOURCE; // workspace root
- }else {
- path = possibleMatch.openable.getPackageFragmentRoot().getPath();
- }
- ObjectVector possibleMatches = (ObjectVector) this.rootsToPossibleMatches.get(path);
- if (possibleMatches != null) {
- if (possibleMatches.contains(possibleMatch)) return;
- } else {
- this.rootsToPossibleMatches.put(path, possibleMatches = new ObjectVector());
- }
-
- possibleMatches.add(possibleMatch);
- this.elementCount++;
-}
-public PossibleMatch[] getPossibleMatches(IPackageFragmentRoot[] roots) {
- PossibleMatch[] result = new PossibleMatch[this.elementCount];
- int index = 0;
- // Virtual entries
- ObjectVector virtualEntries = (ObjectVector) this.rootsToPossibleMatches.get(VIRTUAL_RESOURCE);
-
- if (virtualEntries != null) {
- virtualEntries.copyInto(result, index);
- index += virtualEntries.size();
- }
-
-
- for (int i = 0, length = roots.length; i < length; i++) {
-
- if(roots[i].getPath()!=null && roots[i].getPath().isEmpty()) continue;
-
- ObjectVector possibleMatches = (ObjectVector) this.rootsToPossibleMatches.get(roots[i].getPath());
- if (possibleMatches != null) {
- possibleMatches.copyInto(result, index);
- index += possibleMatches.size();
- }
- }
- if (index < this.elementCount) {
-
- System.arraycopy(result, 0, result = new PossibleMatch[index], 0, index);
-
- }
- return result;
-}
-public void reset() {
- this.rootsToPossibleMatches = new SimpleLookupTable(5);
- this.elementCount = 0;
-}
-}
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
deleted file mode 100644
index 8330b79d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/SecondaryTypeDeclarationPattern.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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.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;
-
-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);
-}
-
-public SecondaryTypeDeclarationPattern(int matchRule) {
- super(matchRule);
-}
-
-public SearchPattern getBlankPattern() {
- return new SecondaryTypeDeclarationPattern(R_EXACT_MATCH | R_CASE_SENSITIVE);
-}
-protected StringBuffer print(StringBuffer output) {
- output.append("Secondary"); //$NON-NLS-1$
- return super.print(output);
-}
-
-/* (non-Javadoc)
- * @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);
-}
-
-}
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
deleted file mode 100644
index 88a32cbb..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/SuperTypeNamesCollector.java
+++ /dev/null
@@ -1,304 +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.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.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.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.ASTVisitor;
-import org.eclipse.wst.jsdt.internal.compiler.CompilationResult;
-import org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ConstructorDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Initializer;
-import org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.env.AccessRuleSet;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BinaryTypeBinding;
-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.MethodScope;
-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.problem.AbortCompilation;
-import org.eclipse.wst.jsdt.internal.core.JavaModelManager;
-import org.eclipse.wst.jsdt.internal.core.JavaProject;
-import org.eclipse.wst.jsdt.internal.core.Openable;
-import org.eclipse.wst.jsdt.internal.core.SourceType;
-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.PathCollector;
-import org.eclipse.wst.jsdt.internal.core.search.PatternSearchJob;
-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.util.ASTNodeFinder;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * Collects the super type names of a given declaring type.
- * Returns NOT_FOUND_DECLARING_TYPE if the declaring type was not found.
- * Returns null if the declaring type pattern doesn't require an exact match.
- */
-public class SuperTypeNamesCollector {
-
- /**
- * An ast visitor that visits type declarations and member type declarations
- * collecting their super type names.
- */
- public class TypeDeclarationVisitor extends ASTVisitor {
- public boolean visit(TypeDeclaration typeDeclaration, BlockScope scope) {
- ReferenceBinding binding = typeDeclaration.binding;
- if (SuperTypeNamesCollector.this.matches(binding))
- SuperTypeNamesCollector.this.collectSuperTypeNames(binding);
- return true;
- }
- public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) {
- ReferenceBinding binding = typeDeclaration.binding;
- if (SuperTypeNamesCollector.this.matches(binding))
- SuperTypeNamesCollector.this.collectSuperTypeNames(binding);
- return true;
- }
- public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope scope) {
- ReferenceBinding binding = memberTypeDeclaration.binding;
- if (SuperTypeNamesCollector.this.matches(binding))
- SuperTypeNamesCollector.this.collectSuperTypeNames(binding);
- return true;
- }
- public boolean visit(FieldDeclaration fieldDeclaration, MethodScope scope) {
- return false; // don't visit field declarations
- }
- public boolean visit(Initializer initializer, MethodScope scope) {
- return false; // don't visit initializers
- }
- public boolean visit(ConstructorDeclaration constructorDeclaration, ClassScope scope) {
- return false; // don't visit constructor declarations
- }
- public boolean visit(MethodDeclaration methodDeclaration, Scope scope) {
- return false; // don't visit method declarations
- }
- }
-SearchPattern pattern;
-char[] typeSimpleName;
-char[] typeQualification;
-MatchLocator locator;
-IType type;
-IProgressMonitor progressMonitor;
-char[][][] result;
-int resultIndex;
-
-public SuperTypeNamesCollector(
- SearchPattern pattern,
- char[] typeSimpleName,
- char[] typeQualification,
- MatchLocator locator,
- IType type,
- IProgressMonitor progressMonitor) {
-
- this.pattern = pattern;
- this.typeSimpleName = typeSimpleName;
- this.typeQualification = typeQualification;
- this.locator = locator;
- this.type = type;
- this.progressMonitor = progressMonitor;
-}
-
-protected void addToResult(char[][] compoundName) {
- int resultLength = this.result.length;
- for (int i = 0; i < resultLength; i++)
- if (CharOperation.equals(this.result[i], compoundName)) return; // already known
-
- if (resultLength == this.resultIndex)
- System.arraycopy(this.result, 0, this.result = new char[resultLength*2][][], 0, resultLength);
- this.result[this.resultIndex++] = compoundName;
-}
-/*
- * Parse the given compiation unit and build its type bindings.
- */
-protected CompilationUnitDeclaration buildBindings(IJavaScriptUnit compilationUnit, boolean isTopLevelOrMember) throws JavaScriptModelException {
- // source unit
- org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit sourceUnit = (org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit) compilationUnit;
-
- CompilationResult compilationResult = new CompilationResult(sourceUnit, 1, 1, 0);
- CompilationUnitDeclaration unit =
- isTopLevelOrMember ?
- this.locator.basicParser().dietParse(sourceUnit, compilationResult) :
- this.locator.basicParser().parse(sourceUnit, compilationResult);
- if (unit != null) {
- this.locator.lookupEnvironment.buildTypeBindings(unit, null /*no access restriction*/);
- this.locator.lookupEnvironment.completeTypeBindings(unit, !isTopLevelOrMember);
- if (!isTopLevelOrMember) {
- if (unit.scope != null)
- unit.scope.faultInTypes(); // fault in fields & methods
- unit.resolve();
- }
- }
- return unit;
-}
-public char[][][] collect() throws JavaScriptModelException {
- if (this.type != null) {
- // Collect the paths of the cus that are in the hierarchy of the given type
- this.result = new char[1][][];
- this.resultIndex = 0;
- JavaProject javaProject = (JavaProject) this.type.getJavaScriptProject();
- this.locator.initialize(javaProject, 0);
- try {
- if (this.type.isBinary()) {
- BinaryTypeBinding binding = this.locator.cacheBinaryType(this.type, null);
- if (binding != null)
- collectSuperTypeNames(binding);
- } else {
- IJavaScriptUnit unit = this.type.getJavaScriptUnit();
- SourceType sourceType = (SourceType) this.type;
- boolean isTopLevelOrMember = sourceType.getOuterMostLocalContext() == null;
- CompilationUnitDeclaration parsedUnit = buildBindings(unit, isTopLevelOrMember);
- if (parsedUnit != null) {
- ASTNodeFinder nodeFinder = new ASTNodeFinder(parsedUnit);
- InferredType inferredType=nodeFinder.findInferredType(this.type);
- if (inferredType!=null)
- collectSuperTypeNames(inferredType.binding);
- else
- {
- TypeDeclaration typeDecl = nodeFinder.findType(this.type);
- if (typeDecl != null && typeDecl.binding != null)
- collectSuperTypeNames(typeDecl.binding);
- }
- }
- }
- } catch (AbortCompilation e) {
- // problem with classpath: report inacurrate matches
- return null;
- }
- if (this.result.length > this.resultIndex)
- System.arraycopy(this.result, 0, this.result = new char[this.resultIndex][][], 0, this.resultIndex);
- return this.result;
- }
-
- // Collect the paths of the cus that declare a type which matches declaringQualification + declaringSimpleName
- String[] paths = this.getPathsOfDeclaringType();
- if (paths == null) return null;
-
- // Create bindings from source types and binary types and collect super type names of the type declaration
- // that match the given declaring type
- Util.sort(paths); // sort by projects
- JavaProject previousProject = null;
- this.result = new char[1][][];
- this.resultIndex = 0;
- for (int i = 0, length = paths.length; i < length; i++) {
- try {
- Openable openable = this.locator.handleFactory.createOpenable(paths[i], this.locator.scope);
- if (openable == null) continue; // outside classpath
-
- IJavaScriptProject project = openable.getJavaScriptProject();
- if (!project.equals(previousProject)) {
- previousProject = (JavaProject) project;
- this.locator.initialize(previousProject, 0);
- }
- if (openable instanceof IJavaScriptUnit) {
- IJavaScriptUnit unit = (IJavaScriptUnit) openable;
- CompilationUnitDeclaration parsedUnit = buildBindings(unit, true /*only toplevel and member types are visible to the focus type*/);
- if (parsedUnit != null)
- parsedUnit.traverse(new TypeDeclarationVisitor(), parsedUnit.scope);
- } else if (openable instanceof IClassFile) {
- IClassFile classFile = (IClassFile) openable;
- BinaryTypeBinding binding = this.locator.cacheBinaryType(classFile.getType(), null);
- if (matches(binding))
- collectSuperTypeNames(binding);
- }
- } catch (AbortCompilation e) {
- // ignore: continue with next element
- } catch (JavaScriptModelException e) {
- // ignore: continue with next element
- }
- }
- if (this.result.length > this.resultIndex)
- System.arraycopy(this.result, 0, this.result = new char[this.resultIndex][][], 0, this.resultIndex);
- return this.result;
-}
-/**
- * Collects the names of all the supertypes of the given type.
- */
-protected void collectSuperTypeNames(ReferenceBinding binding) {
- ReferenceBinding superclass = binding.superclass();
- if (superclass != null) {
- this.addToResult(superclass.compoundName);
- this.collectSuperTypeNames(superclass);
- }
-}
-protected String[] getPathsOfDeclaringType() {
- if (this.typeQualification == null && this.typeSimpleName == null) return null;
-
- final PathCollector pathCollector = new PathCollector();
- 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.typeSimpleName,
- IIndexConstants.TYPE_SUFFIX,
- this.pattern.getMatchRule());
- IndexQueryRequestor searchRequestor = new IndexQueryRequestor(){
- public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access) {
- TypeDeclarationPattern record = (TypeDeclarationPattern)indexRecord;
- if (record.enclosingTypeNames != IIndexConstants.ONE_ZERO_CHAR) { // filter out local and anonymous classes
- pathCollector.acceptIndexMatch(documentPath, indexRecord, participant, access);
- }
- return true;
- }
- };
-
- indexManager.performConcurrentJob(
- new PatternSearchJob(
- searchPattern,
- new JavaSearchParticipant(),
- scope,
- searchRequestor),
- IJavaScriptSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
- progressMonitor == null ? null : new SubProgressMonitor(progressMonitor, 100));
- return pathCollector.getPaths();
-}
-protected boolean matches(char[][] compoundName) {
- int length = compoundName.length;
- if (length == 0) return false;
- char[] simpleName = compoundName[length-1];
- int last = length - 1;
- if (this.typeSimpleName == null || this.pattern.matchesName(simpleName, this.typeSimpleName)) {
- // most frequent case: simple name equals last segment of compoundName
- char[][] qualification = new char[last][];
- System.arraycopy(compoundName, 0, qualification, 0, last);
- 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);
-}
-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
deleted file mode 100644
index 73e7c9ce..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/SuperTypeReferenceLocator.java
+++ /dev/null
@@ -1,85 +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.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode;
-import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedTypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.SingleTypeReference;
-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;
-
-public class SuperTypeReferenceLocator extends PatternLocator {
-
-protected SuperTypeReferencePattern pattern;
-
-public SuperTypeReferenceLocator(SuperTypeReferencePattern pattern) {
- super(pattern);
-
- this.pattern = pattern;
-}
-//public int match(ASTNode node, MatchingNodeSet nodeSet) - SKIP IT
-//public int match(ConstructorDeclaration node, MatchingNodeSet nodeSet) - SKIP IT
-//public int match(Expression node, MatchingNodeSet nodeSet) - SKIP IT
-//public int match(FieldDeclaration node, MatchingNodeSet nodeSet) - SKIP IT
-//public int match(FunctionDeclaration node, MatchingNodeSet nodeSet) - SKIP IT
-//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) - SKIP IT
-public int match(TypeReference node, MatchingNodeSet nodeSet) {
- if (this.pattern.superSimpleName == null)
- return nodeSet.addMatch(node, ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH);
-
- char[] typeRefSimpleName = null;
- if (node instanceof SingleTypeReference) {
- typeRefSimpleName = ((SingleTypeReference) node).token;
- } else { // QualifiedTypeReference
- char[][] tokens = ((QualifiedTypeReference) node).tokens;
- typeRefSimpleName = tokens[tokens.length-1];
- }
- if (matchesName(this.pattern.superSimpleName, typeRefSimpleName))
- return nodeSet.addMatch(node, ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH);
-
- return IMPOSSIBLE_MATCH;
-}
-
-protected int matchContainer() {
- return CLASS_CONTAINER;
-}
-protected int referenceType() {
- return IJavaScriptElement.TYPE;
-}
-public int resolveLevel(ASTNode node) {
- if (!(node instanceof TypeReference)) return IMPOSSIBLE_MATCH;
-
- TypeReference typeRef = (TypeReference) node;
- TypeBinding binding = typeRef.resolvedType;
- if (binding == null) return INACCURATE_MATCH;
- return resolveLevelForType(this.pattern.superSimpleName, this.pattern.superQualification, binding);
-}
-public int resolveLevel(Binding binding) {
- if (binding == null) return INACCURATE_MATCH;
- if (!(binding instanceof ReferenceBinding)) return IMPOSSIBLE_MATCH;
-
- ReferenceBinding type = (ReferenceBinding) binding;
- int level = IMPOSSIBLE_MATCH;
-
- level = resolveLevelForType(this.pattern.superSimpleName, this.pattern.superQualification, type.superclass());
- if (level == ACCURATE_MATCH) return ACCURATE_MATCH;
-
- return level;
-}
-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/SuperTypeReferencePattern.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/SuperTypeReferencePattern.java
deleted file mode 100644
index 9611618a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/SuperTypeReferencePattern.java
+++ /dev/null
@@ -1,221 +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 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 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] = '.';
- }
- 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;
- }
- result[pos++] = SEPARATOR;
- if (superQLength > 0) {
- System.arraycopy(superQualification, 0, result, pos, superQLength);
- pos += superQLength;
- }
- result[pos++] = SEPARATOR;
- if (simpleLength > 0) {
- System.arraycopy(simpleName, 0, result, pos, simpleLength);
- pos += simpleLength;
- }
- result[pos++] = SEPARATOR;
- if (enclosingLength > 0) {
- System.arraycopy(enclosingTypeName, 0, result, pos, enclosingLength);
- pos += enclosingLength;
- }
- result[pos++] = SEPARATOR;
- if (packageLength > 0) {
- System.arraycopy(packageName, 0, result, pos, packageLength);
- pos += packageLength;
- }
- result[pos++] = SEPARATOR;
- result[pos] = (char) modifiers;
- return result;
-}
-
-public SuperTypeReferencePattern(
- char[] superQualification,
- char[] superSimpleName,
- int matchRule) {
-
- this(matchRule);
-
- 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;
- }
- }
-
- 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;
- }
- }
-
- 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;
-
- 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;
- }
-
- return index.query(getIndexCategories(), key, matchRule); // match rule is irrelevant when the key is null
-}
-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);
-}
-}
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
deleted file mode 100644
index c62b50fc..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/TypeDeclarationLocator.java
+++ /dev/null
@@ -1,141 +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.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.infer.InferredType;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode;
-import org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Binding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ProblemReferenceBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding;
-
-public class TypeDeclarationLocator extends PatternLocator {
-
-protected TypeDeclarationPattern pattern; // can be a QualifiedTypeDeclarationPattern
-
-public TypeDeclarationLocator(TypeDeclarationPattern pattern) {
- super(pattern);
-
- this.pattern = pattern;
-}
-//public int match(ASTNode node, MatchingNodeSet nodeSet) - SKIP IT
-//public int match(ConstructorDeclaration node, MatchingNodeSet nodeSet) - SKIP IT
-//public int match(Expression node, MatchingNodeSet nodeSet) - SKIP IT
-//public int match(FieldDeclaration node, MatchingNodeSet nodeSet) - SKIP IT
-//public int match(FunctionDeclaration node, MatchingNodeSet nodeSet) - SKIP IT
-//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))
- return nodeSet.addMatch(node, ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH);
-
- return IMPOSSIBLE_MATCH;
-}
-//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))
- 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)
- {
- if (pkg.length>0 &&
- matchesName(CharOperation.concat(pkg, this.pattern.simpleName, '.'), typeName))
- return nodeSet.addMatch(node, ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH);
- }
- else // any package
- {
- int index=CharOperation.lastIndexOf('.', typeName);
- if (index>=0 &&
- matchesName(CharOperation.subarray(typeName, index+1,typeName.length),this.pattern.simpleName))
- return nodeSet.addMatch(node, ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH);
-
- }
- return IMPOSSIBLE_MATCH;
-}
-public int resolveLevel(ASTNode node) {
- Binding binding=null;
- if (node instanceof TypeDeclaration)
- binding=((TypeDeclaration) node).binding;
- else if (node instanceof InferredType)
- {
- InferredType type=(InferredType) node;
- if (!type.isDefinition || (type.isAnonymous && !type.isNamed()))
- return IMPOSSIBLE_MATCH;
- binding=type.binding;
- }
- else
- return IMPOSSIBLE_MATCH;
-
- return resolveLevel(binding);
-}
-public int resolveLevel(Binding binding) {
- if (binding == null) return INACCURATE_MATCH;
- if (!(binding instanceof TypeBinding)) return IMPOSSIBLE_MATCH;
-
- 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);
- } else {
- char[] enclosingTypeName = this.pattern.enclosingTypeNames == null ? null : CharOperation.concatWith(this.pattern.enclosingTypeNames, '.');
- return resolveLevelForType(this.pattern.simpleName, this.pattern.pkg, enclosingTypeName, type);
- }
-}
-/**
- * Returns whether the given type binding matches the given simple name pattern
- * qualification pattern and enclosing type name pattern.
- */
-protected int resolveLevelForType(char[] simpleNamePattern, char[] qualificationPattern, char[] enclosingNamePattern, TypeBinding type) {
- if (enclosingNamePattern == null)
- return resolveLevelForType(simpleNamePattern, qualificationPattern, type);
- if (qualificationPattern == null)
- return resolveLevelForType(simpleNamePattern, enclosingNamePattern, type);
-
- // case of an import reference while searching for ALL_OCCURENCES of a type (see bug 37166)
- if (type instanceof ProblemReferenceBinding) return IMPOSSIBLE_MATCH;
-
- // 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, '.')))
- return resolveLevelForType(simpleNamePattern, fullQualificationPattern, type);
- return IMPOSSIBLE_MATCH;
-}
-public String toString() {
- return "Locator for " + this.pattern.toString(); //$NON-NLS-1$
-}
-
-
-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;
- if (this.pattern.simpleName == null || matchesName(this.pattern.simpleName, typeName))
- return ACCURATE_MATCH;
- if (pkg!=null && pkg.length>0 &&
- matchesName(CharOperation.concat(pkg, this.pattern.simpleName, '.'), typeName))
- return ACCURATE_MATCH;
- return IMPOSSIBLE_MATCH;
-}
-
-
-}
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
deleted file mode 100644
index bbb9fe35..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/TypeDeclarationPattern.java
+++ /dev/null
@@ -1,326 +0,0 @@
-/*******************************************************************************
- * 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 <spektom@gmail.com> 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);
-}
-}
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
deleted file mode 100644
index 234c3a8d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/TypeReferenceLocator.java
+++ /dev/null
@@ -1,730 +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.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IType;
-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.core.search.TypeDeclarationMatch;
-import org.eclipse.wst.jsdt.core.search.TypeReferenceMatch;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ArrayTypeReference;
-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.ImportReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.NameReference;
-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.SingleNameReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.SingleTypeReference;
-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.IBinaryType;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ArrayBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BaseTypeBinding;
-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.LocalTypeBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding;
-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.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.util.SimpleSet;
-import org.eclipse.wst.jsdt.internal.core.JavaElement;
-
-public class TypeReferenceLocator extends PatternLocator {
-
-protected TypeReferencePattern pattern;
-protected boolean isDeclarationOfReferencedTypesPattern;
-
-public TypeReferenceLocator(TypeReferencePattern pattern) {
-
- super(pattern);
-
- this.pattern = pattern;
- this.isDeclarationOfReferencedTypesPattern = this.pattern instanceof DeclarationOfReferencedTypesPattern;
-}
-protected IJavaScriptElement findElement(IJavaScriptElement element, int accuracy) {
- // need exact match to be able to open on type ref
- if (accuracy != SearchMatch.A_ACCURATE) return null;
-
- // element that references the type must be included in the enclosing element
- DeclarationOfReferencedTypesPattern declPattern = (DeclarationOfReferencedTypesPattern) this.pattern;
- while (element != null && !declPattern.enclosingElement.equals(element))
- element = element.getParent();
- return element;
-}
-public int match(ASTNode node, MatchingNodeSet nodeSet) { // interested in ImportReference
- if (!(node instanceof ImportReference)) return IMPOSSIBLE_MATCH;
-
- return nodeSet.addMatch(node, matchLevel((ImportReference) node));
-}
-//public int match(ConstructorDeclaration node, MatchingNodeSet nodeSet) - SKIP IT
-//public int match(Expression node, MatchingNodeSet nodeSet) - SKIP IT
-//public int match(FieldDeclaration node, MatchingNodeSet nodeSet) - SKIP IT
-//public int match(FunctionDeclaration node, MatchingNodeSet nodeSet) - SKIP IT
-//public int match(MessageSend node, MatchingNodeSet nodeSet) - SKIP IT
-public int match(Reference node, MatchingNodeSet nodeSet) { // interested in NameReference & its subtypes
- if (!(node instanceof NameReference))
- {
- if (node instanceof FieldReference) {
- FieldReference fieldReference = (FieldReference) node;
- if (!(fieldReference.receiver instanceof SingleNameReference || fieldReference.receiver instanceof FieldReference))
- return IMPOSSIBLE_MATCH;
- if (matchesName(this.pattern.simpleName, fieldReference.token))
- return nodeSet.addMatch(node, POSSIBLE_MATCH); // resolution is needed to find out if it is a type ref
- }
- return IMPOSSIBLE_MATCH;
- }
-
- if (this.pattern.simpleName == null)
- return nodeSet.addMatch(node, ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH);
-
- if (node instanceof SingleNameReference) {
- if (matchesName(this.pattern.simpleName, ((SingleNameReference) node).token))
- return nodeSet.addMatch(node, POSSIBLE_MATCH); // resolution is needed to find out if it is a type ref
- } else {
- char[][] tokens = ((QualifiedNameReference) node).tokens;
- for (int i = 0, max = tokens.length; i < max; i++)
- if (matchesName(this.pattern.simpleName, tokens[i]))
- return nodeSet.addMatch(node, POSSIBLE_MATCH); // resolution is needed to find out if it is a type ref
- }
-
- return IMPOSSIBLE_MATCH;
-}
-//public int match(TypeDeclaration node, MatchingNodeSet nodeSet) - SKIP IT
-public int match(TypeReference node, MatchingNodeSet nodeSet) {
- if (this.pattern.simpleName == null)
- return nodeSet.addMatch(node, ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH);
-
- if (node instanceof SingleTypeReference) {
- if (matchesName(this.pattern.simpleName, ((SingleTypeReference) node).token))
- return nodeSet.addMatch(node, ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH);
- } else {
- char[][] tokens = ((QualifiedTypeReference) node).tokens;
- for (int i = 0, max = tokens.length; i < max; i++)
- if (matchesName(this.pattern.simpleName, tokens[i]))
- return nodeSet.addMatch(node, POSSIBLE_MATCH); // resolution is needed to find out if it is a type ref
- }
-
- return IMPOSSIBLE_MATCH;
-}
-
-protected int matchLevel(ImportReference importRef) {
- if (this.pattern.qualification == null) {
- if (this.pattern.simpleName == null) return ACCURATE_MATCH;
- char[][] tokens = importRef.tokens;
- if (matchesName(this.pattern.simpleName, tokens[tokens.length-1])) return ACCURATE_MATCH;
- } else {
- char[][] tokens = importRef.tokens;
- char[] qualifiedPattern = this.pattern.simpleName == null
- ? this.pattern.qualification
- : CharOperation.concat(this.pattern.qualification, this.pattern.simpleName, '.');
- char[] qualifiedTypeName = CharOperation.concatWith(tokens, '.');
- if (qualifiedPattern == null) return ACCURATE_MATCH; // null is as if it was "*"
- if (qualifiedTypeName == null) return IMPOSSIBLE_MATCH; // cannot match null name
- if (qualifiedTypeName.length == 0) { // empty name
- if (qualifiedPattern.length == 0) { // can only matches empty pattern
- return ACCURATE_MATCH;
- }
- return IMPOSSIBLE_MATCH;
- }
- boolean matchFirstChar = !this.isCaseSensitive || (qualifiedPattern[0] == qualifiedTypeName[0]);
- if (this.isCamelCase && matchFirstChar && CharOperation.camelCaseMatch(qualifiedPattern, qualifiedTypeName)) {
- return POSSIBLE_MATCH;
- }
- switch (this.matchMode) {
- case SearchPattern.R_EXACT_MATCH:
- case SearchPattern.R_PREFIX_MATCH:
- if (CharOperation.prefixEquals(qualifiedPattern, qualifiedTypeName, this.isCaseSensitive)) {
- return POSSIBLE_MATCH;
- }
- break;
-
- case SearchPattern.R_PATTERN_MATCH:
- if (CharOperation.match(qualifiedPattern, qualifiedTypeName, this.isCaseSensitive)) {
- return POSSIBLE_MATCH;
- }
- break;
-
- case SearchPattern.R_REGEXP_MATCH :
- // TODO (frederic) implement regular expression match
- break;
- }
- }
- return IMPOSSIBLE_MATCH;
-}
-
-protected void matchReportImportRef(ImportReference importRef, Binding binding, IJavaScriptElement element, int accuracy, MatchLocator locator) throws CoreException {
- if (this.isDeclarationOfReferencedTypesPattern) {
- if ((element = findElement(element, accuracy)) != null) {
- SimpleSet knownTypes = ((DeclarationOfReferencedTypesPattern) this.pattern).knownTypes;
- while (binding instanceof ReferenceBinding) {
- ReferenceBinding typeBinding = (ReferenceBinding) binding;
- reportDeclaration(typeBinding, 1, locator, knownTypes);
- binding = typeBinding.enclosingType();
- }
- }
- return;
- }
-
- // return if this is not necessary to report
- if (this.pattern.hasTypeArguments() && !this.isEquivalentMatch &&!this.isErasureMatch) {
- return;
- }
-
- // Create search match
- match = locator.newTypeReferenceMatch(element, binding, accuracy, importRef);
-
- // set match raw flag and rule
- match.setRaw(true);
- if (this.pattern.hasTypeArguments()) {
- // binding is raw => only compatible erasure if pattern has type arguments
- match.setRule(match.getRule() & (~SearchPattern.R_FULL_MATCH));
- }
-
- // Try to find best selection for match
- ReferenceBinding typeBinding = null;
- boolean lastButOne = false;
- if (binding instanceof ReferenceBinding) {
- typeBinding = (ReferenceBinding) binding;
- } else if (binding instanceof FieldBinding) { // may happen for static import
- typeBinding = ((FieldBinding)binding).declaringClass;
- } else if (binding instanceof MethodBinding) { // may happen for static import
- typeBinding = ((MethodBinding)binding).declaringClass;
- }
- if (typeBinding != null) {
- int lastIndex = importRef.tokens.length - 1;
- if (lastButOne) {
- // for field or method static import, use last but one token
- lastIndex--;
- }
- if (typeBinding instanceof ProblemReferenceBinding) {
- ProblemReferenceBinding pbBinding = (ProblemReferenceBinding) typeBinding;
- typeBinding = pbBinding.closestMatch();
- lastIndex = pbBinding.compoundName.length - 1;
- }
- // try to match all enclosing types for which the token matches as well.
- while (typeBinding != null && lastIndex >= 0) {
- if (resolveLevelForType(typeBinding) != IMPOSSIBLE_MATCH) {
- if (locator.encloses(element)) {
- long[] positions = importRef.sourcePositions;
- // index now depends on pattern type signature
- int index = lastIndex;
- if (this.pattern.qualification != null) {
- index = lastIndex - this.pattern.segmentsSize;
- }
- if (index < 0) index = 0;
- int start = (int) ((positions[index]) >>> 32);
- int end = (int) positions[lastIndex];
- // report match
- match.setOffset(start);
- match.setLength(end-start+1);
- locator.report(match);
- }
- return;
- }
- lastIndex--;
- typeBinding = typeBinding.enclosingType();
- }
- }
- locator.reportAccurateTypeReference(match, importRef, this.pattern.simpleName);
-}
-protected void matchReportReference(ArrayTypeReference arrayRef, IJavaScriptElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException {
- if (this.pattern.simpleName == null) {
- // TODO (frederic) need to add a test for this case while searching generic types...
- if (locator.encloses(element)) {
- int offset = arrayRef.sourceStart;
- int length = arrayRef.sourceEnd-offset+1;
- if (this.match == null) {
- this.match = locator.newTypeReferenceMatch(element, elementBinding, accuracy, offset, length, arrayRef);
- } else {
- this.match.setOffset(offset);
- this.match.setLength(length);
- }
- locator.report(match);
- return;
- }
- }
- match = locator.newTypeReferenceMatch(element, elementBinding, accuracy, arrayRef);
- if (arrayRef.resolvedType != null) {
- matchReportReference(arrayRef, -1, arrayRef.resolvedType.leafComponentType(), locator);
- return;
- }
- locator.reportAccurateTypeReference(match, arrayRef, this.pattern.simpleName);
-}
-/**
- * Reports the match of the given reference.
- */
-protected void matchReportReference(ASTNode reference, IJavaScriptElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException {
- matchReportReference(reference, element, null, null, elementBinding, accuracy, locator);
-}
-/**
- * Reports the match of the given reference. Also provide a local and other elements to eventually report in match.
- */
-protected void matchReportReference(ASTNode reference, IJavaScriptElement element, IJavaScriptElement localElement, IJavaScriptElement[] otherElements, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException {
- if (this.isDeclarationOfReferencedTypesPattern) {
- if ((element = findElement(element, accuracy)) != null)
- reportDeclaration(reference, element, locator, ((DeclarationOfReferencedTypesPattern) this.pattern).knownTypes);
- return;
- }
-
- // Create search match
- TypeReferenceMatch refMatch = locator.newTypeReferenceMatch(element, elementBinding, accuracy, reference);
- refMatch.setLocalElement(localElement);
- refMatch.setOtherElements(otherElements);
- this.match = refMatch;
-
- // Report match depending on reference type
- if (reference instanceof QualifiedNameReference)
- matchReportReference((QualifiedNameReference) reference, element, elementBinding, accuracy, locator);
- else if (reference instanceof QualifiedTypeReference)
- matchReportReference((QualifiedTypeReference) reference, element, elementBinding, accuracy, locator);
- else if (reference instanceof ArrayTypeReference)
- matchReportReference((ArrayTypeReference) reference, element, elementBinding, accuracy, locator);
- else {
- TypeBinding typeBinding = reference instanceof Expression ? ((Expression)reference).resolvedType : null;
- if (typeBinding != null) {
- matchReportReference((Expression)reference, -1, typeBinding, locator);
- return;
- }
- locator.report(match);
- }
-}
-/**
- * Reports the match of the given reference. Also provide a scope to look for possible local and other elements.
- */
-protected void matchReportReference(ASTNode reference, IJavaScriptElement element, Binding elementBinding, Scope scope, int accuracy, MatchLocator locator) throws CoreException {
- if (scope == null || (scope.kind != Scope.BLOCK_SCOPE && scope.kind != Scope.METHOD_SCOPE)) {
- matchReportReference(reference, element, elementBinding, accuracy, locator);
- return;
- }
-
- // Look if some block scope local variable declarations include reference start position
- BlockScope blockScope = (BlockScope) scope;
- LocalDeclaration[] localDeclarations = blockScope.findLocalVariableDeclarations(reference.sourceStart);
- IJavaScriptElement localElement = null;
- IJavaScriptElement[] otherElements = null;
-
- // Some local variable declaration are matching
- if (localDeclarations != null) {
- int length = localDeclarations.length;
-
- // Set local element to first matching local declaration
- int idx = 0;
- for (; idx<length; idx++) {
- if (localDeclarations[idx] == null) break;
- if (reference.sourceStart == localDeclarations[idx].declarationSourceStart) {
- localElement = locator.createHandle(localDeclarations[idx], element);
- break;
- }
- if (idx>0 && localDeclarations[idx].sourceStart > reference.sourceStart) {
- localElement = locator.createHandle(localDeclarations[idx-1], element);
- break;
- }
- }
- if (localElement == null && idx > 0) {
- if (reference.sourceEnd < localDeclarations[idx-1].declarationEnd) {
- localElement = locator.createHandle(localDeclarations[idx-1], element);
- }
- }
-
- // Store other local variable declarations in other elements
- int size = 0;
- for (int j=1; j<length; j++) {
- if (localDeclarations[j] == null) break;
- if (reference.sourceStart == localDeclarations[j].declarationSourceStart) {
- if (otherElements == null) {
- otherElements = new IJavaScriptElement[length-j];
- }
- otherElements[size++] = locator.createHandle(localDeclarations[j], element);
- }
- }
- if (size > 0 && size != (length-1)) {
- System.arraycopy(otherElements, 0, otherElements = new IJavaScriptElement[size], 0, size);
- }
- }
-
- // Report match with local and other elements if any
- matchReportReference(reference, element, localElement, otherElements, elementBinding, accuracy, locator);
-}
-protected void matchReportReference(QualifiedNameReference qNameRef, IJavaScriptElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException {
- Binding binding = qNameRef.binding;
- TypeBinding typeBinding = null;
- int lastIndex = qNameRef.tokens.length - 1;
- switch (qNameRef.bits & ASTNode.RestrictiveFlagMASK) {
- case Binding.FIELD : // reading a field
- typeBinding = qNameRef.actualReceiverType;
- lastIndex -= qNameRef.otherBindings == null ? 1 : qNameRef.otherBindings.length + 1;
- break;
- case Binding.TYPE : //=============only type ==============
- if (binding instanceof TypeBinding)
- typeBinding = (TypeBinding) binding;
- break;
- case Binding.VARIABLE : //============unbound cases===========
- case Binding.TYPE | Binding.VARIABLE :
- if (binding instanceof ProblemReferenceBinding) {
- typeBinding = (TypeBinding) binding;
- } else if (binding instanceof ProblemFieldBinding) {
- typeBinding = qNameRef.actualReceiverType;
- lastIndex -= qNameRef.otherBindings == null ? 1 : qNameRef.otherBindings.length + 1;
- } else if (binding instanceof ProblemBinding) {
- typeBinding = ((ProblemBinding) binding).searchType;
- }
- break;
- }
- if (typeBinding instanceof ProblemReferenceBinding) {
- ProblemReferenceBinding pbBinding = (ProblemReferenceBinding) typeBinding;
- typeBinding = pbBinding.closestMatch();
- lastIndex = pbBinding.compoundName.length - 1;
- }
-
- // Create search match to report
- if (this.match == null) {
- this.match = locator.newTypeReferenceMatch(element, elementBinding, accuracy, qNameRef);
- }
-
- // try to match all enclosing types for which the token matches as well.
- if (typeBinding instanceof ReferenceBinding) {
- ReferenceBinding refBinding = (ReferenceBinding) typeBinding;
- while (refBinding != null && lastIndex >= 0) {
- if (resolveLevelForType(refBinding) == ACCURATE_MATCH) {
- if (locator.encloses(element)) {
- long[] positions = qNameRef.sourcePositions;
- // index now depends on pattern type signature
- int index = lastIndex;
- if (this.pattern.qualification != null) {
- index = lastIndex - this.pattern.segmentsSize;
- }
- if (index < 0) index = 0;
- int start = (int) ((positions[index]) >>> 32);
- int end = (int) positions[lastIndex];
- match.setOffset(start);
- match.setLength(end-start+1);
-
- // Look if there's a need to special report for parameterized type
- matchReportReference(qNameRef, lastIndex, refBinding, locator);
- }
- return;
- }
- lastIndex--;
- refBinding = refBinding.enclosingType();
- }
- }
- locator.reportAccurateTypeReference(match, qNameRef, this.pattern.simpleName);
-}
-protected void matchReportReference(QualifiedTypeReference qTypeRef, IJavaScriptElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException {
- TypeBinding typeBinding = qTypeRef.resolvedType;
- int lastIndex = qTypeRef.tokens.length - 1;
- if (typeBinding instanceof ArrayBinding)
- typeBinding = ((ArrayBinding) typeBinding).leafComponentType;
- if (typeBinding instanceof ProblemReferenceBinding) {
- ProblemReferenceBinding pbBinding = (ProblemReferenceBinding) typeBinding;
- typeBinding = pbBinding.closestMatch();
- lastIndex = pbBinding.compoundName.length - 1;
- }
-
- // Create search match to report
- if (this.match == null) {
- this.match = locator.newTypeReferenceMatch(element, elementBinding, accuracy, qTypeRef);
- }
-
- // try to match all enclosing types for which the token matches as well
- if (typeBinding instanceof ReferenceBinding) {
- ReferenceBinding refBinding = (ReferenceBinding) typeBinding;
- while (refBinding != null && lastIndex >= 0) {
- if (resolveLevelForType(refBinding) != IMPOSSIBLE_MATCH) {
- if (locator.encloses(element)) {
- long[] positions = qTypeRef.sourcePositions;
- // index now depends on pattern type signature
- int index = lastIndex;
- if (this.pattern.qualification != null) {
- index = lastIndex - this.pattern.segmentsSize;
- }
- if (index < 0) index = 0;
- int start = (int) ((positions[index]) >>> 32);
- int end = (int) positions[lastIndex];
- match.setOffset(start);
- match.setLength(end-start+1);
-
- // Look if there's a need to special report for parameterized type
- matchReportReference(qTypeRef, lastIndex, refBinding, locator);
- }
- return;
- }
- lastIndex--;
- refBinding = refBinding.enclosingType();
- }
- }
- locator.reportAccurateTypeReference(match, qTypeRef, this.pattern.simpleName);
-}
-void matchReportReference(Expression expr, int lastIndex, TypeBinding refBinding, MatchLocator locator) throws CoreException {
-
- if (this.pattern.hasTypeArguments()) { // binding has no type params, compatible erasure if pattern does
- match.setRule(SearchPattern.R_ERASURE_MATCH);
- }
-
- // Report match
- if (expr instanceof ArrayTypeReference) {
- locator.reportAccurateTypeReference(match, expr, this.pattern.simpleName);
- return;
- }
- if (refBinding.isLocalType()) {
- // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=82673
- LocalTypeBinding local = (LocalTypeBinding) refBinding;
- IJavaScriptElement focus = ((InternalSearchPattern)pattern).focus;
- if (focus != null && local.enclosingMethod != null && focus.getParent().getElementType() == IJavaScriptElement.METHOD) {
- IFunction method = (IFunction) focus.getParent();
- if (!CharOperation.equals(local.enclosingMethod.selector, method.getElementName().toCharArray())) {
- return;
- }
- }
- }
- locator.report(match);
-}
-protected int referenceType() {
- return IJavaScriptElement.TYPE;
-}
-protected void reportDeclaration(ASTNode reference, IJavaScriptElement element, MatchLocator locator, SimpleSet knownTypes) throws CoreException {
- int maxType = -1;
- TypeBinding typeBinding = null;
- if (reference instanceof TypeReference) {
- typeBinding = ((TypeReference) reference).resolvedType;
- maxType = Integer.MAX_VALUE;
- } else if (reference instanceof QualifiedNameReference) {
- QualifiedNameReference qNameRef = (QualifiedNameReference) reference;
- Binding binding = qNameRef.binding;
- maxType = qNameRef.tokens.length - 1;
- switch (qNameRef.bits & ASTNode.RestrictiveFlagMASK) {
- case Binding.FIELD : // reading a field
- typeBinding = qNameRef.actualReceiverType;
- maxType -= qNameRef.otherBindings == null ? 1 : qNameRef.otherBindings.length + 1;
- break;
- case Binding.TYPE : //=============only type ==============
- if (binding instanceof TypeBinding)
- typeBinding = (TypeBinding) binding;
- break;
- case Binding.VARIABLE : //============unbound cases===========
- case Binding.TYPE | Binding.VARIABLE :
- if (binding instanceof ProblemFieldBinding) {
- typeBinding = qNameRef.actualReceiverType;
- maxType -= qNameRef.otherBindings == null ? 1 : qNameRef.otherBindings.length + 1;
- } else if (binding instanceof ProblemBinding) {
- ProblemBinding pbBinding = (ProblemBinding) binding;
- typeBinding = pbBinding.searchType; // second chance with recorded type so far
- char[] partialQualifiedName = pbBinding.name;
- maxType = CharOperation.occurencesOf('.', partialQualifiedName) - 1; // index of last bound token is one before the pb token
- if (typeBinding == null || maxType < 0) return;
- }
- break;
- }
- } else if (reference instanceof SingleNameReference) {
- typeBinding = (TypeBinding) ((SingleNameReference) reference).binding;
- maxType = 1;
- }
-
- if (typeBinding instanceof ArrayBinding)
- typeBinding = ((ArrayBinding) typeBinding).leafComponentType;
- if (typeBinding == null || typeBinding instanceof BaseTypeBinding) return;
- if (typeBinding instanceof ProblemReferenceBinding) {
- ReferenceBinding original = ((ProblemReferenceBinding) typeBinding).closestMatch();
- if (original == null) return; // original may not be set (bug 71279)
- typeBinding = original;
- }
- reportDeclaration((ReferenceBinding) typeBinding, maxType, locator, knownTypes);
-}
-protected void reportDeclaration(ReferenceBinding typeBinding, int maxType, MatchLocator locator, SimpleSet knownTypes) throws CoreException {
- IType type = locator.lookupType(typeBinding);
- if (type == null) return; // case of a secondary type
-
- IResource resource = type.getResource();
- boolean isBinary = type.isBinary();
- IBinaryType info = null;
- if (isBinary) {
- if (resource == null)
- resource = type.getJavaScriptProject().getProject();
- info = locator.getBinaryInfo((org.eclipse.wst.jsdt.internal.core.ClassFile) type.getClassFile(), resource);
- }
- while (maxType >= 0 && type != null) {
- if (!knownTypes.includes(type)) {
- if (isBinary) {
- locator.reportBinaryMemberDeclaration(resource, type, typeBinding, info, SearchMatch.A_ACCURATE);
- } else {
- ClassScope scope = (ClassScope)((SourceTypeBinding) typeBinding).scope;
- if (scope != null) {
- TypeDeclaration typeDecl = scope.referenceContext;
- int offset = typeDecl.sourceStart;
- match = new TypeDeclarationMatch(((JavaElement) type).resolved(typeBinding), SearchMatch.A_ACCURATE, offset, typeDecl.sourceEnd-offset+1, locator.getParticipant(), resource);
- locator.report(match);
- }
- }
- knownTypes.add(type);
- }
- typeBinding = typeBinding.enclosingType();
- IJavaScriptElement parent = type.getParent();
- if (parent instanceof IType) {
- type = (IType)parent;
- } else {
- type = null;
- }
- maxType--;
- }
-}
-public int resolveLevel(ASTNode node) {
- if (node instanceof NameReference)
- return resolveLevel((NameReference) node);
- if (node instanceof FieldReference)
- return resolveLevel((FieldReference)node);
- if (node instanceof TypeReference)
- return resolveLevel((TypeReference) node);
-// if (node instanceof ImportReference) - Not called when resolve is true, see MatchingNodeSet.reportMatching(unit)
- return IMPOSSIBLE_MATCH;
-}
-public int resolveLevel(Binding binding) {
- if (binding == null) return INACCURATE_MATCH;
- if (!(binding instanceof TypeBinding)) return IMPOSSIBLE_MATCH;
-
- TypeBinding typeBinding = (TypeBinding) binding;
- if (typeBinding instanceof ArrayBinding)
- typeBinding = ((ArrayBinding) typeBinding).leafComponentType;
- if (typeBinding instanceof ProblemReferenceBinding)
- typeBinding = ((ProblemReferenceBinding) typeBinding).closestMatch();
-
- if (((InternalSearchPattern) this.pattern).focus instanceof IType && typeBinding instanceof ReferenceBinding) {
- IPackageFragment pkg = ((IType) ((InternalSearchPattern) this.pattern).focus).getPackageFragment();
- // check that type is located inside this instance of a package fragment
- if (!PackageReferenceLocator.isDeclaringPackageFragment(pkg, (ReferenceBinding) typeBinding))
- return IMPOSSIBLE_MATCH;
- }
-
- return resolveLevelForTypeOrEnclosingTypes(this.pattern.simpleName, this.pattern.qualification, typeBinding);
-}
-protected int resolveLevel(NameReference nameRef) {
- Binding binding = nameRef.binding;
-
- if (nameRef instanceof SingleNameReference) {
- if (binding instanceof ProblemReferenceBinding)
- binding = ((ProblemReferenceBinding) binding).closestMatch();
- if (binding instanceof ReferenceBinding)
- return resolveLevelForType((ReferenceBinding) binding);
- return binding == null || binding instanceof ProblemBinding ? INACCURATE_MATCH : IMPOSSIBLE_MATCH;
- }
-
- TypeBinding typeBinding = null;
- QualifiedNameReference qNameRef = (QualifiedNameReference) nameRef;
- switch (qNameRef.bits & ASTNode.RestrictiveFlagMASK) {
- case Binding.FIELD : // reading a field
- if (qNameRef.tokens.length < (qNameRef.otherBindings == null ? 2 : qNameRef.otherBindings.length + 2))
- return IMPOSSIBLE_MATCH; // must be at least A.x
- typeBinding = nameRef.actualReceiverType;
- break;
- case Binding.LOCAL : // reading a local variable
- return IMPOSSIBLE_MATCH; // no type match in it
- case Binding.TYPE : //=============only type ==============
- if (binding instanceof TypeBinding)
- typeBinding = (TypeBinding) binding;
- break;
- /*
- * Handling of unbound qualified name references. The match may reside in the resolved fragment,
- * which is recorded inside the problem binding, along with the portion of the name until it became a problem.
- */
- case Binding.VARIABLE : //============unbound cases===========
- case Binding.TYPE | Binding.VARIABLE :
- if (binding instanceof ProblemReferenceBinding) {
- typeBinding = (TypeBinding) binding;
- } else if (binding instanceof ProblemFieldBinding) {
- if (qNameRef.tokens.length < (qNameRef.otherBindings == null ? 2 : qNameRef.otherBindings.length + 2))
- return IMPOSSIBLE_MATCH; // must be at least A.x
- typeBinding = nameRef.actualReceiverType;
- } else if (binding instanceof ProblemBinding) {
- ProblemBinding pbBinding = (ProblemBinding) binding;
- if (CharOperation.occurencesOf('.', pbBinding.name) <= 0) // index of last bound token is one before the pb token
- return INACCURATE_MATCH;
- typeBinding = pbBinding.searchType;
- }
- break;
- }
- return resolveLevel(typeBinding);
-}
-
-protected int resolveLevel(FieldReference fieldReference) {
- Binding binding = fieldReference.typeBinding;
-
- if (binding instanceof ProblemReferenceBinding)
- binding = ((ProblemReferenceBinding) binding).closestMatch();
- if (binding instanceof ReferenceBinding)
- return resolveLevelForType((ReferenceBinding) binding);
- return binding == null || binding instanceof ProblemBinding ? INACCURATE_MATCH : IMPOSSIBLE_MATCH;
-}
-
-protected int resolveLevel(TypeReference typeRef) {
- TypeBinding typeBinding = typeRef.resolvedType;
- if (typeBinding instanceof ArrayBinding)
- typeBinding = ((ArrayBinding) typeBinding).leafComponentType;
- if (typeBinding instanceof ProblemReferenceBinding)
- typeBinding = ((ProblemReferenceBinding) typeBinding).closestMatch();
-
- if (typeRef instanceof SingleTypeReference) {
- return resolveLevelForType(typeBinding);
- } else
- return resolveLevelForTypeOrEnclosingTypes(this.pattern.simpleName, this.pattern.qualification, typeBinding);
-}
-/* (non-Javadoc)
- * Resolve level for type with a given binding.
- * This is just an helper to avoid call of method with all parameters...
- */
-protected int resolveLevelForType(TypeBinding typeBinding) {
- return resolveLevelForType(
- this.pattern.simpleName,
- this.pattern.qualification,
- this.pattern.getTypeArguments(),
- 0,
- typeBinding);
-}
-/**
- * Returns whether the given type binding or one of its enclosing types
- * matches the given simple name pattern and qualification pattern.
- * Returns ACCURATE_MATCH if it does.
- * Returns INACCURATE_MATCH if resolve failed.
- * Returns IMPOSSIBLE_MATCH if it doesn't.
- */
-protected int resolveLevelForTypeOrEnclosingTypes(char[] simpleNamePattern, char[] qualificationPattern, TypeBinding binding) {
- if (binding == null) return INACCURATE_MATCH;
-
- if (binding instanceof ReferenceBinding) {
- ReferenceBinding type = (ReferenceBinding) binding;
- while (type != null) {
- int level = resolveLevelForType(type);
- if (level != IMPOSSIBLE_MATCH) return level;
-
- type = type.enclosingType();
- }
- }
- 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/TypeReferencePattern.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/TypeReferencePattern.java
deleted file mode 100644
index 6c968ddc..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/TypeReferencePattern.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/*******************************************************************************
- * 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.matching;
-
-import org.eclipse.wst.jsdt.core.IType;
-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;
-
- public class TypeReferencePattern extends AndPattern {
-
- protected char[] qualification;
- protected char[] simpleName;
-
- protected char[] currentCategory;
-
- /* Optimization: case where simpleName == null */
- public int segmentsSize;
- protected char[][] segments;
- protected int currentSegment;
-
- protected static char[][] CATEGORIES = { REF };
-
- public TypeReferencePattern(char[] qualification, char[] simpleName, int matchRule) {
- this(matchRule);
-
- int index;
- if (simpleName!=null && (index=CharOperation.lastIndexOf('.',simpleName)) >0)
- {
- qualification=CharOperation.subarray(simpleName, 0, index);
- simpleName=CharOperation.subarray(simpleName, index+1, simpleName.length);
- }
-
- this.qualification = isCaseSensitive() ? qualification : CharOperation.toLowerCase(qualification);
- this.simpleName = (isCaseSensitive() || isCamelCase()) ? simpleName : CharOperation.toLowerCase(simpleName);
-
- if (simpleName == null)
- this.segments = this.qualification == null ? ONE_STAR_CHAR : CharOperation.splitOn('.', this.qualification);
- else
- this.segments = null;
-
- if (this.segments == null)
- if (this.qualification == null)
- this.segmentsSize = 0;
- else
- this.segmentsSize = CharOperation.occurencesOf('.', this.qualification) + 1;
- else
- this.segmentsSize = this.segments.length;
-
- ((InternalSearchPattern)this).mustResolve = true; // always resolve (in case of a simple name reference being a potential match)
- }
- /*
- * Instanciate a type reference pattern with additional information for generics search
- */
- public TypeReferencePattern(char[] qualification, char[] simpleName, String typeSignature, int matchRule) {
- this(qualification, simpleName,matchRule);
- if (typeSignature != null) {
- // store type signatures and arguments
- this.typeSignatures = Util.splitTypeLevelsSignature(typeSignature);
- setTypeArguments(Util.getAllTypeArguments(this.typeSignatures));
- if (hasTypeArguments()) {
- this.segmentsSize = getTypeArguments().length + CharOperation.occurencesOf('/', this.typeSignatures[0]) - 1;
- }
- }
- }
- /*
- * Instanciate a type reference pattern with additional information for generics search
- */
- public TypeReferencePattern(char[] qualification, char[] simpleName, IType type, int matchRule) {
- this(qualification, simpleName,matchRule);
- storeTypeSignaturesAndArguments(type);
- }
- TypeReferencePattern(int matchRule) {
- super(TYPE_REF_PATTERN, matchRule);
- }
- public void decodeIndexKey(char[] key) {
- this.simpleName = key;
- }
- public SearchPattern getBlankPattern() {
- return new TypeReferencePattern(R_EXACT_MATCH | R_CASE_SENSITIVE);
- }
- public char[] getIndexKey() {
- if (this.simpleName != null)
- return this.simpleName;
-
- // Optimization, eg. type reference is 'org.eclipse.wst.jsdt.core.*'
- if (this.currentSegment >= 0)
- return this.segments[this.currentSegment];
- return null;
- }
- public char[][] getIndexCategories() {
- return CATEGORIES;
- }
- protected boolean hasNextQuery() {
- if (this.segments == null) return false;
-
- // Optimization, eg. type reference is 'org.eclipse.wst.jsdt.core.*'
- // if package has at least 4 segments, don't look at the first 2 since they are mostly
- // redundant (eg. in 'org.eclipse.wst.jsdt.core.*' 'org.eclipse' is used all the time)
- return --this.currentSegment >= (this.segments.length >= 4 ? 2 : 0);
- }
-
- public boolean matchesDecodedKey(SearchPattern decodedPattern) {
- return true; // index key is not encoded so query results all match
- }
-
- protected void resetQuery() {
- /* walk the segments from end to start as it will find less potential references using 'lang' than 'java' */
- if (this.segments != null)
- this.currentSegment = this.segments.length - 1;
- }
- protected StringBuffer print(StringBuffer output) {
- output.append("TypeReferencePattern: qualification<"); //$NON-NLS-1$
- if (qualification != null)
- output.append(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/VariableLocator.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/VariableLocator.java
deleted file mode 100644
index 1e43899f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/VariableLocator.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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.internal.compiler.ast.Assignment;
-import org.eclipse.wst.jsdt.internal.compiler.ast.CompoundAssignment;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Expression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.NameReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedNameReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Reference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.SingleNameReference;
-
-public class VariableLocator extends PatternLocator {
-
-protected VariablePattern pattern;
-
-public VariableLocator(VariablePattern pattern) {
- super(pattern);
-
- this.pattern = pattern;
-}
-public int match(Expression node, MatchingNodeSet nodeSet) { // interested in Assignment
- if (this.pattern.writeAccess) {
- if (this.pattern.readAccess) return IMPOSSIBLE_MATCH; // already checked the lhs in match(Reference...) before we reached here
-
- if (node instanceof Assignment) {
- Expression lhs = ((Assignment) node).lhs;
- if (lhs instanceof Reference)
- return matchReference((Reference) lhs, nodeSet, true);
- }
- } else if (this.pattern.readAccess) {
- if (node instanceof Assignment && !(node instanceof CompoundAssignment)) {
- // the lhs of a simple assignment may be added in match(Reference...) before we reach here
- // for example, the fieldRef to 'this.x' in the statement this.x = x; is not considered a readAccess
- Expression lhs = ((Assignment) node).lhs;
- nodeSet.removePossibleMatch(lhs);
- nodeSet.removeTrustedMatch(lhs);
- }
- }
- return IMPOSSIBLE_MATCH;
-}
-public int match(Reference node, MatchingNodeSet nodeSet) { // interested in NameReference & its subtypes
- return this.pattern.readAccess
- ? matchReference(node, nodeSet, false)
- : IMPOSSIBLE_MATCH;
-}
-protected int matchReference(Reference node, MatchingNodeSet nodeSet, boolean writeOnlyAccess) {
- if (node instanceof NameReference) {
- if (this.pattern.name == null) {
- 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);
- } else {
- QualifiedNameReference qNameRef = (QualifiedNameReference) node;
- char[][] tokens = qNameRef.tokens;
- if (writeOnlyAccess) {
- // in the case of the assigment of a qualified name reference, the match must be on the last token
- if (matchesName(this.pattern.name, tokens[tokens.length-1]))
- return nodeSet.addMatch(node, POSSIBLE_MATCH);
- } else {
- for (int i = 0, max = tokens.length; i < max; i++)
- if (matchesName(this.pattern.name, tokens[i]))
- return nodeSet.addMatch(node, POSSIBLE_MATCH);
- }
- }
- }
- 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/VariablePattern.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/VariablePattern.java
deleted file mode 100644
index 3cfab831..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/VariablePattern.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*******************************************************************************
- * 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.matching;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-
-public abstract class VariablePattern extends JavaSearchPattern {
-
-protected boolean findDeclarations;
-protected boolean findReferences;
-protected boolean readAccess;
-protected boolean writeAccess;
-
-public char[] name;
-
-ISourceReference sourceVariable;
-
-public VariablePattern(int patternKind, boolean findDeclarations, boolean readAccess, boolean writeAccess, char[] name, int matchRule,
- ISourceReference sourceRef) {
- super(patternKind, matchRule);
-
- this.findDeclarations = findDeclarations; // set to find declarations & all occurences
- this.readAccess = readAccess; // set to find any reference, read only references & all occurences
- this.writeAccess = writeAccess; // set to find any reference, write only references & all occurences
- this.findReferences = readAccess || writeAccess;
-
- this.name = (isCaseSensitive() || isCamelCase()) ? name : CharOperation.toLowerCase(name);
- this.sourceVariable=sourceRef;
-}
-
-public IJavaScriptElement getJavaElement()
-{
- return (IJavaScriptElement) this.sourceVariable;
-}
-
-protected int getVariableStart()
-{
- try {
- return this.sourceVariable.getSourceRange().getOffset();
- } catch (JavaScriptModelException e) {
- return -1;
- }
-}
-
-protected int getVariableLength()
-{
- try {
- return this.sourceVariable.getSourceRange().getLength();
- } catch (JavaScriptModelException e) {
- return -1;
- }
-}
-
-/*
- * Returns whether a method declaration or message send will need to be resolved to
- * find out if this method pattern matches it.
- */
-protected boolean mustResolve() {
- // would like to change this so that we only do it if generic references are found
- return this.findReferences; // always resolve (in case of a simple name reference being a potential match)
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/processing/IJob.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/processing/IJob.java
deleted file mode 100644
index 4dad751a..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/processing/IJob.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.search.processing;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-
-public interface IJob {
-
- /* Waiting policies */
- int ForceImmediate = 1;
- int CancelIfNotReady = 2;
- int WaitUntilReady = 3;
-
- /* Job's result */
- boolean FAILED = false;
- boolean COMPLETE = true;
-
- /**
- * Answer true if the job belongs to a given family (tag)
- */
- public boolean belongsTo(String jobFamily);
- /**
- * Asks this job to cancel its execution. The cancellation
- * can take an undertermined amount of time.
- */
- public void cancel();
- /**
- * Ensures that this job is ready to run.
- */
- public void ensureReadyToRun();
- /**
- * Execute the current job, answer whether it was successful.
- */
- public boolean execute(IProgressMonitor progress);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/processing/JobManager.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/processing/JobManager.java
deleted file mode 100644
index 2f2c73a8..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/processing/JobManager.java
+++ /dev/null
@@ -1,469 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.search.processing;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-public abstract class JobManager implements Runnable {
-
- /* queue of jobs to execute */
- protected IJob[] awaitingJobs = new IJob[10];
- protected int jobStart = 0;
- protected int jobEnd = -1;
- protected boolean executing = false;
-
- /* background processing */
- protected Thread processingThread;
- protected Job progressJob;
-
- /* counter indicating whether job execution is enabled or not, disabled if <= 0
- it cannot go beyond 1 */
- private int enableCount = 1;
-
- public static boolean VERBOSE = false;
- /* flag indicating that the activation has completed */
- public boolean activated = false;
-
- private int awaitingClients = 0;
-
- /**
- * Invoked exactly once, in background, before starting processing any job
- */
- public void activateProcessing() {
- this.activated = true;
- }
- /**
- * Answer the amount of awaiting jobs.
- */
- public synchronized int awaitingJobsCount() {
- // pretend busy in case concurrent job attempts performing before activated
- return this.activated ? this.jobEnd - this.jobStart + 1 : 1;
- }
- /**
- * Answers the first job in the queue, or null if there is no job available
- * Until the job has completed, the job manager will keep answering the same job.
- */
- public synchronized IJob currentJob() {
- if (this.enableCount > 0 && this.jobStart <= this.jobEnd)
- return this.awaitingJobs[this.jobStart];
- return null;
- }
- public void disable() {
- this.enableCount--;
- if (VERBOSE)
- Util.verbose("DISABLING background indexing"); //$NON-NLS-1$
- }
- /**
- * Remove the index from cache for a given project.
- * Passing null as a job family discards them all.
- */
- public void discardJobs(String jobFamily) {
-
- if (VERBOSE)
- Util.verbose("DISCARD background job family - " + jobFamily); //$NON-NLS-1$
-
- try {
- IJob currentJob;
- // cancel current job if it belongs to the given family
- synchronized(this){
- currentJob = this.currentJob();
- disable();
- }
- if (currentJob != null && (jobFamily == null || currentJob.belongsTo(jobFamily))) {
- currentJob.cancel();
-
- // wait until current active job has finished
- while (this.processingThread != null && this.executing){
- try {
- if (VERBOSE)
- Util.verbose("-> waiting end of current background job - " + currentJob); //$NON-NLS-1$
- Thread.sleep(50);
- } catch(InterruptedException e){
- // ignore
- }
- }
- }
-
- // flush and compact awaiting jobs
- int loc = -1;
- synchronized(this) {
- for (int i = this.jobStart; i <= this.jobEnd; i++) {
- currentJob = this.awaitingJobs[i];
- if (currentJob != null) { // sanity check
- this.awaitingJobs[i] = null;
- if (!(jobFamily == null || currentJob.belongsTo(jobFamily))) { // copy down, compacting
- this.awaitingJobs[++loc] = currentJob;
- } else {
- if (VERBOSE)
- Util.verbose("-> discarding background job - " + currentJob); //$NON-NLS-1$
- currentJob.cancel();
- }
- }
- }
- this.jobStart = 0;
- this.jobEnd = loc;
- }
- } finally {
- enable();
- }
- if (VERBOSE)
- Util.verbose("DISCARD DONE with background job family - " + jobFamily); //$NON-NLS-1$
- }
- public synchronized void enable() {
- this.enableCount++;
- if (VERBOSE)
- Util.verbose("ENABLING background indexing"); //$NON-NLS-1$
- this.notifyAll(); // wake up the background thread if it is waiting (context must be synchronized)
- }
- public synchronized boolean isJobWaiting(IJob request) {
- for (int i = this.jobEnd; i > this.jobStart; i--) // don't check job at jobStart, as it may have already started
- if (request.equals(this.awaitingJobs[i])) return true;
- return false;
- }
- /**
- * Advance to the next available job, once the current one has been completed.
- * Note: clients awaiting until the job count is zero are still waiting at this point.
- */
- protected synchronized void moveToNextJob() {
- //if (!enabled) return;
-
- if (this.jobStart <= this.jobEnd) {
- this.awaitingJobs[this.jobStart++] = null;
- if (this.jobStart > this.jobEnd) {
- this.jobStart = 0;
- this.jobEnd = -1;
- }
- }
- }
- /**
- * When idle, give chance to do something
- */
- protected void notifyIdle(long idlingTime) {
- // do nothing
- }
- /**
- * This API is allowing to run one job in concurrence with background processing.
- * Indeed since other jobs are performed in background, resource sharing might be
- * an issue.Therefore, this functionality allows a given job to be run without
- * colliding with background ones.
- * Note: multiple thread might attempt to perform concurrent jobs at the same time,
- * and should synchronize (it is deliberately left to clients to decide whether
- * concurrent jobs might interfere or not. In general, multiple read jobs are ok).
- *
- * Waiting policy can be:
- * IJobConstants.ForceImmediateSearch
- * IJobConstants.CancelIfNotReadyToSearch
- * IJobConstants.WaitUntilReadyToSearch
- *
- */
- public boolean performConcurrentJob(IJob searchJob, int waitingPolicy, IProgressMonitor progress) {
- if (VERBOSE)
- Util.verbose("STARTING concurrent job - " + searchJob); //$NON-NLS-1$
-
- searchJob.ensureReadyToRun();
-
- boolean status = IJob.FAILED;
- try {
- int concurrentJobWork = 100;
- if (progress != null)
- progress.beginTask("", concurrentJobWork); //$NON-NLS-1$
- if (awaitingJobsCount() > 0) {
- switch (waitingPolicy) {
-
- case IJob.ForceImmediate :
- if (VERBOSE)
- Util.verbose("-> NOT READY - forcing immediate - " + searchJob);//$NON-NLS-1$
- try {
- disable(); // pause indexing
- status = searchJob.execute(progress == null ? null : new SubProgressMonitor(progress, concurrentJobWork));
- } finally {
- enable();
- }
- if (VERBOSE)
- Util.verbose("FINISHED concurrent job - " + searchJob); //$NON-NLS-1$
- return status;
-
- case IJob.CancelIfNotReady :
- if (VERBOSE)
- Util.verbose("-> NOT READY - cancelling - " + searchJob); //$NON-NLS-1$
- if (VERBOSE)
- Util.verbose("CANCELED concurrent job - " + searchJob); //$NON-NLS-1$
- throw new OperationCanceledException();
-
- case IJob.WaitUntilReady :
- IProgressMonitor subProgress = null;
- try {
- int totalWork = 1000;
- if (progress != null) {
- subProgress = new SubProgressMonitor(progress, concurrentJobWork * 8 / 10);
- subProgress.beginTask("", totalWork); //$NON-NLS-1$
- concurrentJobWork = concurrentJobWork * 2 / 10;
- }
- // use local variable to avoid potential NPE (see bug 20435 NPE when searching java method
- // and bug 42760 NullPointerException in JobManager when searching)
- Thread t = this.processingThread;
- int originalPriority = t == null ? -1 : t.getPriority();
- try {
- if (t != null)
- t.setPriority(Thread.currentThread().getPriority());
- synchronized(this) {
- this.awaitingClients++;
- }
- IJob previousJob = null;
- int awaitingJobsCount;
- int lastJobsCount = totalWork;
- float lastWorked = 0;
- float totalWorked = 0;
- while ((awaitingJobsCount = awaitingJobsCount()) > 0) {
- if (subProgress != null && subProgress.isCanceled())
- throw new OperationCanceledException();
- IJob currentJob = currentJob();
- // currentJob can be null when jobs have been added to the queue but job manager is not enabled
- if (currentJob != null && currentJob != previousJob) {
- if (VERBOSE)
- Util.verbose("-> NOT READY - waiting until ready - " + searchJob);//$NON-NLS-1$
- if (subProgress != null) {
- subProgress.subTask(
- Messages.bind(Messages.manager_filesToIndex, Integer.toString(awaitingJobsCount)));
- // ratio of the amount of work relative to the total work
- float ratio = awaitingJobsCount < totalWork ? 1 : ((float) totalWork) / awaitingJobsCount;
- if (lastJobsCount > awaitingJobsCount) {
- totalWorked += (lastJobsCount - awaitingJobsCount) * ratio;
- } else {
- // more jobs were added, just increment by the ratio
- totalWorked += ratio;
- }
- if (totalWorked - lastWorked >= 1) {
- subProgress.worked((int) (totalWorked - lastWorked));
- lastWorked = totalWorked;
- }
- lastJobsCount = awaitingJobsCount;
- }
- previousJob = currentJob;
- }
- try {
- if (VERBOSE)
- Util.verbose("-> GOING TO SLEEP - " + searchJob);//$NON-NLS-1$
- Thread.sleep(50);
- } catch (InterruptedException e) {
- // ignore
- }
- }
- } finally {
- synchronized(this) {
- this.awaitingClients--;
- }
- if (t != null && originalPriority > -1 && t.isAlive())
- t.setPriority(originalPriority);
- }
- } finally {
- if (subProgress != null)
- subProgress.done();
- }
- }
- }
- status = searchJob.execute(progress == null ? null : new SubProgressMonitor(progress, concurrentJobWork));
- } finally {
- if (progress != null)
- progress.done();
- if (VERBOSE)
- Util.verbose("FINISHED concurrent job - " + searchJob); //$NON-NLS-1$
- }
- return status;
- }
- public abstract String processName();
-
- public synchronized void request(IJob job) {
-
- job.ensureReadyToRun();
-
- // append the job to the list of ones to process later on
- int size = this.awaitingJobs.length;
- if (++this.jobEnd == size) { // when growing, relocate jobs starting at position 0
- this.jobEnd -= this.jobStart;
- System.arraycopy(this.awaitingJobs, this.jobStart, this.awaitingJobs = new IJob[size * 2], 0, this.jobEnd);
- this.jobStart = 0;
- }
- this.awaitingJobs[this.jobEnd] = job;
- if (VERBOSE) {
- Util.verbose("REQUEST background job - " + job); //$NON-NLS-1$
- Util.verbose("AWAITING JOBS count: " + awaitingJobsCount()); //$NON-NLS-1$
- }
- notifyAll(); // wake up the background thread if it is waiting
- }
- /**
- * Flush current state
- */
- public synchronized void reset() {
- if (VERBOSE)
- Util.verbose("Reset"); //$NON-NLS-1$
-
- if (this.processingThread != null) {
- discardJobs(null); // discard all jobs
- } else {
- /* initiate background processing */
- this.processingThread = new Thread(this, this.processName());
- this.processingThread.setDaemon(true);
- // less prioritary by default, priority is raised if clients are actively waiting on it
- this.processingThread.setPriority(Thread.NORM_PRIORITY-1);
- this.processingThread.start();
- }
- }
- /**
- * Infinite loop performing resource indexing
- */
- public void run() {
-
- long idlingStart = -1;
- activateProcessing();
- try {
- class ProgressJob extends Job {
- ProgressJob(String name) {
- super(name);
- }
- protected IStatus run(IProgressMonitor monitor) {
- int awaitingJobsCount;
- while (!monitor.isCanceled() && (awaitingJobsCount = awaitingJobsCount()) > 0) {
- monitor.subTask(Messages.bind(Messages.manager_filesToIndex, Integer.toString(awaitingJobsCount)));
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- // ignore
- }
- }
- return Status.OK_STATUS;
- }
- }
- this.progressJob = null;
- while (this.processingThread != null) {
- try {
- IJob job;
- synchronized (this) {
- // handle shutdown case when notifyAll came before the wait but after the while loop was entered
- if (this.processingThread == null) continue;
-
- // must check for new job inside this sync block to avoid timing hole
- if ((job = currentJob()) == null) {
- if (this.progressJob != null) {
- this.progressJob.cancel();
- this.progressJob = null;
- }
- if (idlingStart < 0)
- idlingStart = System.currentTimeMillis();
- else
- notifyIdle(System.currentTimeMillis() - idlingStart);
- this.wait(); // wait until a new job is posted (or reenabled:38901)
- } else {
- idlingStart = -1;
- }
- }
- if (job == null) {
- notifyIdle(System.currentTimeMillis() - idlingStart);
- // just woke up, delay before processing any new jobs, allow some time for the active thread to finish
- Thread.sleep(500);
- continue;
- }
- if (VERBOSE) {
- Util.verbose(awaitingJobsCount() + " awaiting jobs"); //$NON-NLS-1$
- Util.verbose("STARTING background job - " + job); //$NON-NLS-1$
- }
- try {
- this.executing = true;
- if (this.progressJob == null) {
- this.progressJob = new ProgressJob(Messages.manager_indexingInProgress);
- this.progressJob.setPriority(Job.LONG);
- this.progressJob.setSystem(true);
- this.progressJob.schedule();
- }
- /*boolean status = */job.execute(null);
- //if (status == FAILED) request(job);
- } finally {
- this.executing = false;
- if (VERBOSE)
- Util.verbose("FINISHED background job - " + job); //$NON-NLS-1$
- moveToNextJob();
- if (this.awaitingClients == 0)
- Thread.sleep(50);
- }
- } catch (InterruptedException e) { // background indexing was interrupted
- }
- }
- } catch (RuntimeException e) {
- if (this.processingThread != null) { // if not shutting down
- // log exception
- Util.log(e, "Background Indexer Crash Recovery"); //$NON-NLS-1$
-
- // keep job manager alive
- this.discardJobs(null);
- this.processingThread = null;
- this.reset(); // this will fork a new thread with no waiting jobs, some indexes will be inconsistent
- }
- throw e;
- } catch (Error e) {
- if (this.processingThread != null && !(e instanceof ThreadDeath)) {
- // log exception
- Util.log(e, "Background Indexer Crash Recovery"); //$NON-NLS-1$
-
- // keep job manager alive
- this.discardJobs(null);
- this.processingThread = null;
- this.reset(); // this will fork a new thread with no waiting jobs, some indexes will be inconsistent
- }
- throw e;
- }
- }
- /**
- * Stop background processing, and wait until the current job is completed before returning
- */
- public void shutdown() {
-
- if (VERBOSE)
- Util.verbose("Shutdown"); //$NON-NLS-1$
-
- disable();
- discardJobs(null); // will wait until current executing job has completed
- Thread thread = this.processingThread;
- try {
- if (thread != null) { // see http://bugs.eclipse.org/bugs/show_bug.cgi?id=31858
- synchronized (this) {
- this.processingThread = null; // mark the job manager as shutting down so that the thread will stop by itself
- this.notifyAll(); // ensure its awake so it can be shutdown
- }
- // in case processing thread is handling a job
- thread.join();
- }
- Job job = this.progressJob;
- if (job != null) {
- job.cancel();
- job.join();
- }
- } catch (InterruptedException e) {
- // ignore
- }
- }
- public String toString() {
- StringBuffer buffer = new StringBuffer(10);
- buffer.append("Enable count:").append(this.enableCount).append('\n'); //$NON-NLS-1$
- int numJobs = this.jobEnd - this.jobStart + 1;
- buffer.append("Jobs in queue:").append(numJobs).append('\n'); //$NON-NLS-1$
- for (int i = 0; i < numJobs && i < 15; i++) {
- buffer.append(i).append(" - job["+i+"]: ").append(this.awaitingJobs[this.jobStart+i]).append('\n'); //$NON-NLS-1$ //$NON-NLS-2$
- }
- return buffer.toString();
- }
-}
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
deleted file mode 100644
index 8120c9b1..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ASTNodeFinder.java
+++ /dev/null
@@ -1,215 +0,0 @@
-/*******************************************************************************
- * 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.util;
-
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IInitializer;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IType;
-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.ASTVisitor;
-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.CompilationUnitDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Initializer;
-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.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ClassScope;
-import org.eclipse.wst.jsdt.internal.core.SourceRefElement;
-import org.eclipse.wst.jsdt.internal.core.SourceType;
-
-/**
- * Finds an ASTNode given an IJavaScriptElement in a CompilationUnitDeclaration
- */
-public class ASTNodeFinder {
- private CompilationUnitDeclaration unit;
-
- public ASTNodeFinder(CompilationUnitDeclaration unit) {
- this.unit = unit;
- }
-
- /*
- * Finds the FieldDeclaration in the given ast corresponding to the given field handle.
- * Returns null if not found.
- */
- public FieldDeclaration findField(IField fieldHandle) {
- TypeDeclaration typeDecl = findType((IType)fieldHandle.getParent());
- if (typeDecl == null) return null;
- FieldDeclaration[] fields = typeDecl.fields;
- if (fields != null) {
- char[] fieldName = fieldHandle.getElementName().toCharArray();
- for (int i = 0, length = fields.length; i < length; i++) {
- FieldDeclaration field = fields[i];
- if (CharOperation.equals(fieldName, field.name)) {
- return field;
- }
- }
- }
- return null;
- }
-
- /*
- * Finds the Initializer in the given ast corresponding to the given initializer handle.
- * Returns null if not found.
- */
- public Initializer findInitializer(IInitializer initializerHandle) {
- TypeDeclaration typeDecl = findType((IType)initializerHandle.getParent());
- if (typeDecl == null) return null;
- FieldDeclaration[] fields = typeDecl.fields;
- if (fields != null) {
- int occurenceCount = ((SourceRefElement)initializerHandle).occurrenceCount;
- for (int i = 0, length = fields.length; i < length; i++) {
- FieldDeclaration field = fields[i];
- if (field instanceof Initializer && --occurenceCount == 0) {
- return (Initializer)field;
- }
- }
- }
- return null;
- }
-
- /*
- * Finds the AbstractMethodDeclaration in the given ast corresponding to the given method handle.
- * Returns null if not found.
- */
- public AbstractMethodDeclaration findMethod(IFunction methodHandle) {
- TypeDeclaration typeDecl = findType((IType)methodHandle.getParent());
- if (typeDecl == null) return null;
- AbstractMethodDeclaration[] methods = typeDecl.methods;
- if (methods != null) {
- char[] selector = methodHandle.getElementName().toCharArray();
- String[] parameterTypeSignatures = methodHandle.getParameterTypes();
- 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)) {
- Argument[] args = method.arguments;
- int argsLength = args == null ? 0 : args.length;
- if (argsLength == parameterCount) {
- for (int j = 0; j < parameterCount; j++) {
- TypeReference type = args[j].type;
- String signature = Util.typeSignature(type);
- if (!signature.equals(parameterTypeSignatures[j])) {
- continue nextMethod;
- }
- }
- return method;
- }
- }
- }
- }
- return null;
- }
-
- /*
- * Finds the TypeDeclaration in the given ast corresponding to the given type handle.
- * Returns null if not found.
- */
- public TypeDeclaration findType(IType typeHandle) {
- if (!JavaScriptCore.IS_ECMASCRIPT4)
- return null;
- IJavaScriptElement parent = typeHandle.getParent();
- final char[] typeName = typeHandle.getElementName().toCharArray();
- final int occurenceCount = ((SourceType)typeHandle).occurrenceCount;
- final boolean findAnonymous = typeName.length == 0;
- class Visitor extends ASTVisitor {
- TypeDeclaration result;
- int count = 0;
- public boolean visit(TypeDeclaration typeDeclaration, BlockScope scope) {
- if (result != null) return false;
- if ((typeDeclaration.bits & ASTNode.IsAnonymousType) != 0) {
- if (findAnonymous && ++count == occurenceCount) {
- result = typeDeclaration;
- }
- } else {
- if (!findAnonymous && CharOperation.equals(typeName, typeDeclaration.name)) {
- result = typeDeclaration;
- }
- }
- return false; // visit only one level
- }
- }
- switch (parent.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- TypeDeclaration[] types = this.unit.types;
- if (types != null) {
- for (int i = 0, length = types.length; i < length; i++) {
- TypeDeclaration type = types[i];
- if (CharOperation.equals(typeName, type.name)) {
- return type;
- }
- }
- }
- break;
- case IJavaScriptElement.TYPE:
- TypeDeclaration parentDecl = findType((IType)parent);
- if (parentDecl == null) return null;
- types = parentDecl.memberTypes;
- if (types != null) {
- for (int i = 0, length = types.length; i < length; i++) {
- TypeDeclaration type = types[i];
- if (CharOperation.equals(typeName, type.name)) {
- return type;
- }
- }
- }
- break;
- case IJavaScriptElement.FIELD:
- FieldDeclaration fieldDecl = findField((IField)parent);
- if (fieldDecl == null) return null;
- Visitor visitor = new Visitor();
- fieldDecl.traverse(visitor, null);
- return visitor.result;
- case IJavaScriptElement.INITIALIZER:
- Initializer initializer = findInitializer((IInitializer)parent);
- if (initializer == null) return null;
- visitor = new Visitor();
- initializer.traverse(visitor, null);
- return visitor.result;
- case IJavaScriptElement.METHOD:
- AbstractMethodDeclaration methodDecl = findMethod((IFunction)parent);
- if (methodDecl == null) return null;
- visitor = new Visitor();
- methodDecl.traverse(visitor, (ClassScope)null);
- return visitor.result;
- }
- return null;
- }
- public InferredType findInferredType(IType typeHandle)
- {
- final char[] typeName = typeHandle.getElementName().toCharArray();
- final int occurenceCount = ((SourceType)typeHandle).occurrenceCount;
- final boolean findAnonymous = typeName.length == 0;
- int count = 0;
- for (int i = 0; i < this.unit.numberInferredTypes; i++) {
- InferredType inferredType = this.unit.inferredTypes[i];
- if (!inferredType.isDefinition || inferredType.isEmptyGlobal())
- continue;
-
- if (!inferredType.isNamed()) {
- if (findAnonymous && ++count == occurenceCount) {
- return inferredType;
- }
- } else {
- if (!findAnonymous && CharOperation.equals(inferredType.getName(),typeName)) {
- return inferredType;
- }
- }
- }
- return null;
- }
-}
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
deleted file mode 100644
index 3d86d251..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/BindingKeyParser.java
+++ /dev/null
@@ -1,761 +0,0 @@
-/*******************************************************************************
- * 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.internal.core.util;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-
-public class BindingKeyParser {
-
- int keyStart;
-
- static final char C_THROWN = '|';
-
- static class Scanner {
- static final int PACKAGE = 0;
- static final int TYPE = 1;
- static final int FIELD = 2;
- static final int METHOD = 3;
- static final int ARRAY = 4;
- static final int LOCAL_VAR = 5;
- static final int FLAGS = 6;
- static final int BASE_TYPE = 9;
- static final int END = 10;
-
- static final int START = -1;
-
- int index = 0, start;
- char[] source;
- int token = START;
-
- Scanner(char[] source) {
- this.source = source;
- }
-
- char[] getTokenSource() {
- int length = this.index-this.start;
- char[] result = new char[length];
- System.arraycopy(this.source, this.start, result, 0, length);
- return result;
- }
-
- boolean isAtFieldOrMethodStart() {
- return
- this.index < this.source.length
- && this.source[this.index] == '.';
- }
-
- boolean isAtLocalVariableStart() {
- return
- this.index < this.source.length
- && this.source[this.index] == '#';
- }
-
- boolean isAtMemberTypeStart() {
- return
- this.index < this.source.length
- && (this.source[this.index] == '$'
- || (this.source[this.index] == '.' && this.source[this.index-1] == '>'));
- }
-
- boolean isAtParametersEnd() {
- return
- this.index < this.source.length
- && this.source[this.index] == '>';
- }
-
- boolean isAtParametersStart() {
- char currentChar;
- return
- this.index > 0
- && this.index < this.source.length
- && ((currentChar = this.source[this.index]) == '<'
- || currentChar == '%');
- }
-
- boolean isAtRawTypeEnd() {
- return
- this.index > 0
- && this.index < this.source.length
- && this.source[this.index] == '>';
- }
-
- boolean isAtSecondaryTypeStart() {
- return
- this.index < this.source.length
- && this.source[this.index] == '~';
- }
-
- boolean isAtWildcardStart() {
- return
- this.index < this.source.length
- && "*+-".indexOf(this.source[this.index]) != -1; //$NON-NLS-1$
- }
-
- boolean isAtTypeParameterStart() {
- return
- this.index < this.source.length
- && this.source[this.index] == 'T';
- }
-
- boolean isAtTypeArgumentStart() {
- return this.index < this.source.length && "LIZVCDBFJS[!".indexOf(this.source[this.index]) != -1; //$NON-NLS-1$
- }
-
- boolean isAtThrownStart() {
- return
- this.index < this.source.length
- && this.source[this.index] == C_THROWN;
- }
-
- boolean isAtTypeVariableStart() {
- return
- this.index < this.source.length
- && this.source[this.index] == ':';
- }
-
- boolean isAtTypeWithCaptureStart() {
- return
- this.index < this.source.length
- && this.source[this.index] == '&';
- }
-
- int nextToken() {
- int previousTokenEnd = this.index;
- this.start = this.index;
- int length = this.source.length;
- while (this.index <= length) {
- char currentChar = this.index == length ? Character.MIN_VALUE : this.source[this.index];
- switch (currentChar) {
- case 'A':
- case 'B':
- case 'C':
- case 'D':
- case 'F':
- case 'I':
- case 'J':
- case 'N':
- case 'S':
- case 'V':
- case 'Z':
- // base type
- if (this.index == previousTokenEnd
- && (this.index == 0 || this.source[this.index-1] != '.')) { // case of field or method starting with one of the character above
- this.index++;
- this.token = BASE_TYPE;
- return this.token;
- }
- break;
- case 'L':
- case 'T':
- if (this.index == previousTokenEnd) {
- this.start = this.index+1;
- }
- break;
- case ';':
- if (this.index == previousTokenEnd) {
- this.start = this.index+1;
- previousTokenEnd = this.start;
- } else {
- this.token = TYPE;
- return this.token;
- }
- break;
- case '~':
- if (this.index == previousTokenEnd) {
- this.start = this.index+1;
- } else {
- this.token = TYPE;
- return this.token;
- }
- break;
- case '.':
- case '%':
- case ':':
- case '>':
- this.start = this.index+1;
- previousTokenEnd = this.start;
- break;
- case '[':
- while (this.index < length && this.source[this.index] == '[')
- this.index++;
- this.token = ARRAY;
- return this.token;
- case '<':
- if (this.start > 0) {
- switch (this.source[this.start-1]) {
- case '.':
- if (this.source[this.start-2] == '>')
- // case of member type where enclosing type is parameterized
- this.token = TYPE;
- else
- this.token = METHOD;
- return this.token;
- default:
- if (this.index == previousTokenEnd) {
- this.start = this.index+1;
- previousTokenEnd = this.start;
- } else {
- this.token = TYPE;
- return this.token;
- }
- }
- }
- break;
- case '(':
- this.token = METHOD;
- return this.token;
- case ')':
- if (this.token == TYPE) {
- this.token = FIELD;
- return this.token;
- }
- this.start = this.index+1;
- previousTokenEnd = this.start;
- break;
- case '#':
- if (this.index == previousTokenEnd) {
- this.start = this.index+1;
- previousTokenEnd = this.start;
- } else {
- this.token = LOCAL_VAR;
- return this.token;
- }
- break;
- case Character.MIN_VALUE:
- switch (this.token) {
- case START:
- this.token = PACKAGE;
- break;
- case METHOD:
- case LOCAL_VAR:
- this.token = LOCAL_VAR;
- break;
- case TYPE:
- if (this.index > this.start && this.source[this.start-1] == '.')
- this.token = FIELD;
- else
- this.token = END;
- break;
- default:
- this.token = END;
- break;
- }
- return this.token;
- }
- this.index++;
- }
- this.token = END;
- return this.token;
- }
-
- void skipMethodSignature() {
- this.start = this.index;
- int braket = 0;
- while (this.index < this.source.length) {
- switch (this.source[this.index]) {
- case '#':
- case '%':
- case C_THROWN:
- return;
- case ':':
- if (braket == 0)
- return;
- break;
- case '<':
- case '(':
- braket++;
- break;
- case '>':
- case ')':
- braket--;
- break;
- }
- this.index++;
- }
- }
-
- void skipThrownStart() {
- while (this.index < this.source.length && this.source[this.index] == C_THROWN)
- this.index++;
- }
-
- void skipParametersStart() {
- while (this.index < this.source.length && (this.source[this.index] == '<' || this.source[this.index] == '%'))
- this.index++;
- }
-
- void skipParametersEnd() {
- while (this.index < this.source.length && this.source[this.index] != '>')
- this.index++;
- this.index++;
- }
-
- void skipTypeEnd() {
- if (this.index < this.source.length && this.source[this.index] == ';')
- this.index++;
- }
-
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- switch (this.token) {
- case START:
- buffer.append("START: "); //$NON-NLS-1$
- break;
- case PACKAGE:
- buffer.append("PACKAGE: "); //$NON-NLS-1$
- break;
- case TYPE:
- buffer.append("TYPE: "); //$NON-NLS-1$
- break;
- case FIELD:
- buffer.append("FIELD: "); //$NON-NLS-1$
- break;
- case METHOD:
- buffer.append("METHOD: "); //$NON-NLS-1$
- break;
- case ARRAY:
- buffer.append("ARRAY: "); //$NON-NLS-1$
- break;
- case LOCAL_VAR:
- buffer.append("LOCAL VAR: "); //$NON-NLS-1$
- break;
- case FLAGS:
- buffer.append("MODIFIERS: "); //$NON-NLS-1$
- break;
- case BASE_TYPE:
- buffer.append("BASE TYPE: "); //$NON-NLS-1$
- break;
- case END:
- buffer.append("END: "); //$NON-NLS-1$
- break;
- }
- if (this.index < 0) {
- buffer.append("**"); //$NON-NLS-1$
- buffer.append(this.source);
- } else if (this.index <= this.source.length) {
- buffer.append(this.source, 0, this.start);
- buffer.append('*');
- if (this.start <= this.index) {
- buffer.append(this.source, this.start, this.index - this.start);
- buffer.append('*');
- buffer.append(this.source, this.index, this.source.length - this.index);
- } else {
- buffer.append('*');
- buffer.append(this.source, this.start, this.source.length - this.start);
- }
- } else {
- buffer.append(this.source);
- buffer.append("**"); //$NON-NLS-1$
- }
- return buffer.toString();
- }
- }
- private boolean parsingPaused;
-
- private Scanner scanner;
-
- private boolean hasTypeName = true;
-
- public BindingKeyParser(BindingKeyParser parser) {
- this(""); //$NON-NLS-1$
- this.scanner = parser.scanner;
- }
-
- public BindingKeyParser(String key) {
- this.scanner = new Scanner(key.toCharArray());
- }
-
- public void consumeArrayDimension(char[] brakets) {
- // default is to do nothing
- }
-
- public void consumeBaseType(char[] baseTypeSig) {
- // default is to do nothing
- }
-
- public void consumeCapture(int position) {
- // default is to do nothing
- }
-
- public void consumeException() {
- // default is to do nothing
- }
-
- public void consumeField(char[] fieldName) {
- // default is to do nothing
- }
-
- public void consumeParameterizedGenericMethod() {
- // default is to do nothing
- }
-
- public void consumeLocalType(char[] uniqueKey) {
- // default is to do nothing
- }
-
- public void consumeLocalVar(char[] varName) {
- // default is to do nothing
- }
-
- public void consumeMethod(char[] selector, char[] signature) {
- // default is to do nothing
- }
-
- public void consumeModifiers(char[] modifiers) {
- // default is to do nothing
- }
-
- public void consumeNonGenericType() {
- // default is to do nothing
- }
-
- public void consumeMemberType(char[] simpleTypeName) {
- // default is to do nothing
- }
-
- public void consumePackage(char[] pkgName) {
- // default is to do nothing
- }
-
- public void consumeParameterizedType(char[] simpleTypeName, boolean isRaw) {
- // default is to do nothing
- }
-
- public void consumeParser(BindingKeyParser parser) {
- // default is to do nothing
- }
-
- public void consumeRawType() {
- // default is to do nothing
- }
-
- public void consumeScope(int scopeNumber) {
- // default is to do nothing
- }
-
- public void consumeSecondaryType(char[] simpleTypeName) {
- // default is to do nothing
- }
-
- public void consumeFullyQualifiedName(char[] fullyQualifiedName) {
- // default is to do nothing
- }
-
- public void consumeKey() {
- // default is to do nothing
- }
-
- public void consumeTopLevelType() {
- // default is to do nothing
- }
-
- public void consumeType() {
- // default is to do nothing
- }
-
- public void consumeTypeParameter(char[] typeParameterName) {
- // default is to do nothing
- }
-
- public void consumeTypeVariable(char[] position, char[] typeVariableName) {
- // default is to do nothing
- }
-
- public void consumeTypeWithCapture() {
- // default is to do nothing
- }
-
- public void consumeWildCard(int kind) {
- // default is to do nothing
- }
-
- /*
- * Returns the string that this binding key wraps.
- */
- public String getKey() {
- return new String(this.scanner.source);
- }
-
- public boolean hasTypeName() {
- return this.hasTypeName;
- }
-
- public void malformedKey() {
- // default is to do nothing
- }
-
- public BindingKeyParser newParser() {
- return new BindingKeyParser(this);
- }
-
- public void parse() {
- parse(false/*don't pause after fully qualified name*/);
- }
-
- public void parse(boolean pauseAfterFullyQualifiedName) {
- try {
- if (!this.parsingPaused) {
- // fully qualified name
- parseFullyQualifiedName();
- parseSecondaryType();
- if (pauseAfterFullyQualifiedName) {
- this.parsingPaused = true;
- return;
- }
- }
- if (!hasTypeName()) {
- consumeKey();
- return;
- }
- consumeTopLevelType();
- //parseInnerType();
-
- if (this.scanner.isAtParametersStart()) {
- this.scanner.skipParametersStart();
- if (this.scanner.isAtTypeParameterStart()) {
- // generic type
- parseGenericType();
- // skip ";>"
- this.scanner.skipParametersEnd();
- // local type in generic type
- parseInnerType();
- } else if (this.scanner.isAtTypeArgumentStart())
- // parameterized type
- parseParameterizedType(null/*top level type or member type with raw enclosing type*/, false/*no raw*/);
- else if (this.scanner.isAtRawTypeEnd())
- // raw type
- parseRawType();
- } else {
- // non-generic type
- consumeNonGenericType();
- }
-
- consumeType();
- this.scanner.skipTypeEnd();
-
- if (this.scanner.isAtFieldOrMethodStart()) {
- switch (this.scanner.nextToken()) {
- case Scanner.FIELD:
- parseField();
- return;
- case Scanner.METHOD:
- parseMethod();
- if (this.scanner.isAtLocalVariableStart()) {
- parseLocalVariable();
- } else if (this.scanner.isAtTypeVariableStart()) {
- parseTypeVariable();
- }
- break;
- default:
- malformedKey();
- return;
- }
- } else if (this.scanner.isAtTypeVariableStart()) {
- parseTypeVariable();
- }
-
- consumeKey();
- } catch (IllegalArgumentException e) {
- // the given key was illegal
- }
- }
-
- private void parseFullyQualifiedName() {
- switch(this.scanner.nextToken()) {
- case Scanner.PACKAGE:
- this.keyStart = 0;
- consumePackage(this.scanner.getTokenSource());
- this.hasTypeName = false;
- return;
- case Scanner.TYPE:
- this.keyStart = this.scanner.start-1;
- consumeFullyQualifiedName(this.scanner.getTokenSource());
- break;
- case Scanner.BASE_TYPE:
- this.keyStart = this.scanner.start-1;
- consumeBaseType(this.scanner.getTokenSource());
- this.hasTypeName = false;
- break;
- case Scanner.ARRAY:
- this.keyStart = this.scanner.start;
- consumeArrayDimension(this.scanner.getTokenSource());
- switch (this.scanner.nextToken()) {
- case Scanner.TYPE:
- consumeFullyQualifiedName(this.scanner.getTokenSource());
- break;
- case Scanner.BASE_TYPE:
- consumeBaseType(this.scanner.getTokenSource());
- this.hasTypeName = false;
- break;
- default:
- malformedKey();
- return;
- }
- break;
- default:
- malformedKey();
- return;
- }
- }
-
- private void parseParameterizedMethod() {
- this.scanner.skipParametersStart();
- while (!this.scanner.isAtParametersEnd()) {
- parseTypeArgument();
- }
- consumeParameterizedGenericMethod();
- }
-
- private void parseGenericType() {
- while (!this.scanner.isAtParametersEnd()) {
- if (this.scanner.nextToken() != Scanner.TYPE) {
- malformedKey();
- return;
- }
- consumeTypeParameter(this.scanner.getTokenSource());
- this.scanner.skipTypeEnd();
- }
- }
-
- private void parseInnerType() {
- if (!this.scanner.isAtMemberTypeStart() || this.scanner.nextToken() != Scanner.TYPE)
- return;
- char[] typeName = this.scanner.getTokenSource();
- if (Character.isDigit(typeName[0])) {
- // anonymous or local type
- int nextToken = Scanner.TYPE;
- while (this.scanner.isAtMemberTypeStart())
- nextToken = this.scanner.nextToken();
- typeName = nextToken == Scanner.END ? this.scanner.source : CharOperation.subarray(this.scanner.source, this.keyStart, this.scanner.index+1);
- consumeLocalType(typeName);
- } else {
- consumeMemberType(typeName);
- parseInnerType();
- }
- }
-
- private void parseLocalVariable() {
- if (this.scanner.nextToken() != Scanner.LOCAL_VAR) {
- malformedKey();
- return;
- }
- char[] varName = this.scanner.getTokenSource();
- if (Character.isDigit(varName[0])) {
- int index = Integer.parseInt(new String(varName));
- consumeScope(index);
- if (!this.scanner.isAtLocalVariableStart()) {
- malformedKey();
- return;
- }
- parseLocalVariable();
- } else {
- consumeLocalVar(varName);
- }
- }
-
- private void parseMethod() {
- char[] selector = this.scanner.getTokenSource();
- this.scanner.skipMethodSignature();
- char[] signature = this.scanner.getTokenSource();
- consumeMethod(selector, signature);
- if (this.scanner.isAtThrownStart()) {
- parseThrownExceptions();
- }
- if (this.scanner.isAtParametersStart())
- parseParameterizedMethod();
- }
-
- private void parseField() {
- char[] fieldName = this.scanner.getTokenSource();
- parseReturnType();
- consumeField(fieldName);
- }
-
- private void parseThrownExceptions() {
- while (this.scanner.isAtThrownStart()) {
- this.scanner.skipThrownStart();
- BindingKeyParser parser = newParser();
- parser.parse();
- consumeParser(parser);
- consumeException();
- }
- }
-
- private void parseParameterizedType(char[] typeName, boolean isRaw) {
- if (!isRaw) {
- while (!this.scanner.isAtParametersEnd()) {
- parseTypeArgument();
- }
- }
- // skip ";>"
- this.scanner.skipParametersEnd();
- consumeParameterizedType(typeName, isRaw);
- this.scanner.skipTypeEnd();
- if (this.scanner.isAtMemberTypeStart() && this.scanner.nextToken() == Scanner.TYPE) {
- typeName = this.scanner.getTokenSource();
- if (this.scanner.isAtParametersStart()) {
- this.scanner.skipParametersStart();
- parseParameterizedType(typeName, this.scanner.isAtRawTypeEnd());
- } else
- consumeParameterizedType(typeName, true/*raw*/);
- }
- }
-
- private void parseRawType() {
- this.scanner.skipParametersEnd();
- consumeRawType();
- this.scanner.skipTypeEnd();
- if (this.scanner.isAtMemberTypeStart() && this.scanner.nextToken() == Scanner.TYPE) {
- char[] typeName = this.scanner.getTokenSource();
- if (this.scanner.isAtParametersStart()) {
- this.scanner.skipParametersStart();
- parseParameterizedType(typeName, this.scanner.isAtRawTypeEnd());
- } else
- consumeParameterizedType(typeName, true/*raw*/);
- }
- }
-
- private void parseReturnType() {
- BindingKeyParser parser = newParser();
- parser.parse();
- consumeParser(parser);
- }
-
- private void parseSecondaryType() {
- if (!this.scanner.isAtSecondaryTypeStart() || this.scanner.nextToken() != Scanner.TYPE) return;
- consumeSecondaryType(this.scanner.getTokenSource());
- }
-
- private void parseTypeArgument() {
- BindingKeyParser parser = newParser();
- parser.parse();
- consumeParser(parser);
- }
-
- private void parseTypeVariable() {
- if (this.scanner.nextToken() != Scanner.TYPE) {
- malformedKey();
- return;
- }
- char[] typeVariableName = this.scanner.getTokenSource();
- char[] position;
- int length = typeVariableName.length;
- if (length > 0 && Character.isDigit(typeVariableName[0])) {
- int firstT = CharOperation.indexOf('T', typeVariableName);
- position = CharOperation.subarray(typeVariableName, 0, firstT);
- typeVariableName = CharOperation.subarray(typeVariableName, firstT+1, typeVariableName.length);
- } else {
- position = CharOperation.NO_CHAR;
- }
- consumeTypeVariable(position, typeVariableName);
- this.scanner.skipTypeEnd();
- }
-}
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
deleted file mode 100644
index fb2c5694..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/BindingKeyResolver.java
+++ /dev/null
@@ -1,338 +0,0 @@
-/*******************************************************************************
- * 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.internal.core.util;
-
-import java.util.ArrayList;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.Compiler;
-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.lookup.BinaryTypeBinding;
-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.LocalTypeBinding;
-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.MethodBinding;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding;
-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.TypeBinding;
-
-public class BindingKeyResolver extends BindingKeyParser {
- Compiler compiler;
- Binding compilerBinding;
-
- char[][] compoundName;
- int dimension;
- LookupEnvironment environment;
- ReferenceBinding genericType;
- MethodBinding methodBinding;
-
- char[] secondarySimpleName;
- CompilationUnitDeclaration parsedUnit;
- BlockScope scope;
- TypeBinding typeBinding;
- TypeDeclaration typeDeclaration;
- ArrayList types = new ArrayList();
- int rank = 0;
-
- int wildcardRank;
-
- CompilationUnitDeclaration outerMostParsedUnit;
-
- private BindingKeyResolver(BindingKeyParser parser, Compiler compiler, LookupEnvironment environment, int wildcardRank, CompilationUnitDeclaration outerMostParsedUnit) {
- super(parser);
- this.compiler = compiler;
- this.environment = environment;
- this.wildcardRank = wildcardRank;
- this.outerMostParsedUnit = outerMostParsedUnit;
- }
-
- public BindingKeyResolver(String key) {
- this(key, null, null);
- }
-
- public BindingKeyResolver(String key, Compiler compiler, LookupEnvironment environment) {
- super(key);
- this.compiler = compiler;
- this.environment = environment;
- }
-
- /*
- * If not already cached, computes and cache the compound name (pkg name + top level name) of this key.
- * Returns the package name if key is a pkg key.
- * Returns an empty array if malformed.
- * This key's scanner should be positioned on the package or type token.
- */
- public char[][] compoundName() {
- return this.compoundName;
- }
-
- public void consumeArrayDimension(char[] brakets) {
- this.dimension = brakets.length;
- }
-
- public void consumeBaseType(char[] baseTypeSig) {
- this.compoundName = new char[][] {getKey().toCharArray()};
- TypeBinding baseTypeBinding = getBaseTypeBinding(baseTypeSig);
- if (baseTypeBinding != null) {
- this.typeBinding = baseTypeBinding;
- }
- }
-
- public void consumeException() {
- this.types = new ArrayList();
- }
-
- public void consumeField(char[] fieldName) {
- FieldBinding[] fields = ((ReferenceBinding) this.typeBinding).availableFields(); // resilience
- for (int i = 0, length = fields.length; i < length; i++) {
- FieldBinding field = fields[i];
- if (CharOperation.equals(fieldName, field.name)) {
- this.typeBinding = null;
- this.compilerBinding = field;
- return;
- }
- }
- }
-
- public void consumeLocalType(char[] uniqueKey) {
- LocalTypeBinding[] localTypeBindings = this.parsedUnit.localTypes;
- for (int i = 0; i < this.parsedUnit.localTypeCount; i++)
- if (CharOperation.equals(uniqueKey, localTypeBindings[i].computeUniqueKey(false/*not a leaf*/))) {
- this.typeBinding = localTypeBindings[i];
- return;
- }
- }
-
- public void consumeLocalVar(char[] varName) {
- if (this.scope == null) {
- this.scope = this.methodBinding.sourceMethod().scope;
- }
- for (int i = 0; i < this.scope.localIndex; i++) {
- LocalVariableBinding local = this.scope.locals[i];
- if (CharOperation.equals(varName, local.name)) {
- this.methodBinding = null;
- this.compilerBinding = local;
- return;
- }
- }
- }
-
- public void consumeMethod(char[] selector, char[] signature) {
- MethodBinding[] methods = ((ReferenceBinding) this.typeBinding).availableMethods(); // resilience
- for (int i = 0, methodLength = methods.length; i < methodLength; i++) {
- MethodBinding method = methods[i];
- if (CharOperation.equals(selector, method.selector) || (selector.length == 0 && method.isConstructor())) {
- char[] methodSignature = method.signature();
- if (CharOperation.equals(signature, methodSignature)) {
- this.typeBinding = null;
- this.methodBinding = method;
- this.compilerBinding = this.methodBinding;
- return;
- }
- }
- }
- }
-
- public void consumeMemberType(char[] simpleTypeName) {
- this.typeBinding = getTypeBinding(simpleTypeName);
- }
-
- public void consumePackage(char[] pkgName) {
- this.compoundName = CharOperation.splitOn('/', pkgName);
- this.compilerBinding = new PackageBinding(this.compoundName, null, this.environment);
- }
-
- public void consumeParser(BindingKeyParser parser) {
- this.types.add(parser);
- }
-
- public void consumeScope(int scopeNumber) {
- if (this.scope == null) {
- this.scope = this.methodBinding.sourceMethod().scope;
- }
- if (scopeNumber >= this.scope.subscopeCount)
- return; // malformed key
- this.scope = (BlockScope) this.scope.subscopes[scopeNumber];
- }
-
- public void consumeSecondaryType(char[] simpleTypeName) {
- this.secondarySimpleName = simpleTypeName;
- }
-
- public void consumeFullyQualifiedName(char[] fullyQualifiedName) {
- this.compoundName = CharOperation.splitOn('/', fullyQualifiedName);
- }
-
- public void consumeTopLevelType() {
- this.parsedUnit = getCompilationUnitDeclaration();
- if (this.parsedUnit != null && this.compiler != null) {
- this.compiler.process(this.parsedUnit, this.compiler.totalUnits+1); // noop if unit has already been resolved
- }
- if (this.parsedUnit == null) {
- this.typeBinding = getBinaryBinding();
- } else {
- char[] typeName = this.secondarySimpleName == null ? this.compoundName[this.compoundName.length-1] : this.secondarySimpleName;
- this.typeBinding = getTypeBinding(typeName);
- }
- }
-
- public void consumeKey() {
- if (this.typeBinding != null) {
- this.typeBinding = getArrayBinding(this.dimension, this.typeBinding);
- this.compilerBinding = this.typeBinding;
- }
- }
-
- public void consumeTypeWithCapture() {
- BindingKeyResolver resolver = (BindingKeyResolver) this.types.get(0);
- this.typeBinding =(TypeBinding) resolver.compilerBinding;
- }
-
- /*
- * If the given dimension is greater than 0 returns an array binding for the given type binding.
- * Otherwise return the given type binding.
- * Returns null if the given type binding is null.
- */
- private TypeBinding getArrayBinding(int dim, TypeBinding binding) {
- if (binding == null) return null;
- if (dim == 0) return binding;
- return this.environment.createArrayType(binding, dim);
- }
-
- private TypeBinding getBaseTypeBinding(char[] signature) {
- switch (signature[0]) {
- case 'I' :
- return TypeBinding.INT;
- case 'Z' :
- return TypeBinding.BOOLEAN;
- case 'V' :
- return TypeBinding.VOID;
- case 'C' :
- return TypeBinding.CHAR;
- case 'D' :
- return TypeBinding.DOUBLE;
- case 'F' :
- return TypeBinding.FLOAT;
- case 'J' :
- return TypeBinding.LONG;
- case 'S' :
- return TypeBinding.SHORT;
- case 'N':
- return TypeBinding.NULL;
- default :
- return null;
- }
- }
-
- /*
- * Returns a binary binding corresonding to this key's compound name.
- * Returns null if not found.
- */
- private TypeBinding getBinaryBinding() {
- if (this.compoundName.length == 0) return null;
- return this.environment.getType(this.compoundName);
- }
-
- /*
- * Finds the compilation unit declaration corresponding to the key in the given lookup environment.
- * Returns null if no compilation unit declaration could be found.
- * This key's scanner should be positioned on the package token.
- */
- public CompilationUnitDeclaration getCompilationUnitDeclaration() {
- char[][] name = this.compoundName;
- if (name.length == 0) return null;
- if (this.environment == null) return null;
- ReferenceBinding binding = this.environment.getType(name);
- if (!(binding instanceof SourceTypeBinding)) {
- if (this.secondarySimpleName == null)
- return null;
- // case of a secondary type with no primary type (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=177115)
- int length = name.length;
- System.arraycopy(name, 0, name = new char[length][], 0, length-1);
- name[length-1] = this.secondarySimpleName;
- binding = this.environment.getType(name);
- if (!(binding instanceof SourceTypeBinding))
- return null;
- }
- SourceTypeBinding sourceTypeBinding = (SourceTypeBinding) binding;
- if (sourceTypeBinding.scope == null)
- return null;
- return sourceTypeBinding.scope.compilationUnitScope().referenceContext;
- }
-
- /*
- * Returns the compiler binding corresponding to this key.
- * Returns null is malformed.
- * This key's scanner should be positioned on the package token.
- */
- public Binding getCompilerBinding() {
- try {
- parse();
- return this.compilerBinding;
- } catch (RuntimeException e) {
- Util.log(e, "Could not create binding from binding key: " + getKey()); //$NON-NLS-1$
- return null;
- }
- }
-
- private TypeBinding getTypeBinding(char[] simpleTypeName) {
- if (this.typeBinding instanceof BinaryTypeBinding) {
- return ((BinaryTypeBinding) this.typeBinding).getMemberType(simpleTypeName);
- } else {
- TypeDeclaration[] typeDeclarations =
- this.typeDeclaration == null ?
- (this.parsedUnit == null ? null : this.parsedUnit.types) :
- this.typeDeclaration.memberTypes;
- if (typeDeclarations == null) return null;
- for (int i = 0, length = typeDeclarations.length; i < length; i++) {
- TypeDeclaration declaration = typeDeclarations[i];
- if (CharOperation.equals(simpleTypeName, declaration.name)) {
- this.typeDeclaration = declaration;
- return declaration.binding;
- }
- }
- }
- return null;
- }
-
- private TypeBinding[] getTypeBindingArguments() {
- int size = this.types.size();
- TypeBinding[] arguments = new TypeBinding[size];
- for (int i = 0; i < size; i++) {
- BindingKeyResolver resolver = (BindingKeyResolver) this.types.get(i);
- TypeBinding compilerBinding2 = (TypeBinding) resolver.compilerBinding;
- if (compilerBinding2 == null) {
- throw new IllegalArgumentException();
- }
- arguments[i] = compilerBinding2;
- }
- this.types = new ArrayList();
- return arguments;
- }
-
- public void malformedKey() {
- this.compoundName = CharOperation.NO_CHAR_CHAR;
- }
-
- public BindingKeyParser newParser() {
- return new BindingKeyResolver(this, this.compiler, this.environment, this.rank, this.outerMostParsedUnit == null ? this.parsedUnit : this.outerMostParsedUnit);
- }
-
- public String toString() {
- return getKey();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/CharArrayBuffer.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/CharArrayBuffer.java
deleted file mode 100644
index 19945f81..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/CharArrayBuffer.java
+++ /dev/null
@@ -1,193 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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.internal.compiler.util.Util;
-
-/**
- * The <code>CharArrayBuffer</code> is intended as a lightweight partial implementation
- * of the StringBuffer class, but using <code>char[]'s</code> instead of Strings.
- *
- * <p>The <code>CharArrayBuffer</code> maintains a list of <code>char[]'s</code>
- * which don't get appended until the user asks for them. The following
- * code illustrates how to use the class.
- *
- * <code>
- * CharArrayBuffer buffer = new CharArrayBuffer(myCharArray);
- * buffer.append(moreBytes, 0, someLength);
- * myCharArray = buffer.getContents();
- * </code>
- *
- * <p>NOTE: This class is not Thread safe!
- */
-public class CharArrayBuffer {
- /**
- * This is the buffer of char arrays which must be appended together
- * during the getContents method.
- */
- protected char[][] fBuffer;
-
- /**
- * The default buffer size.
- */
- public static final int DEFAULT_BUFFER_SIZE = 10;
-
- /**
- * The end of the buffer
- */
- protected int fEnd;
-
- /**
- * The current size of the buffer.
- */
- protected int fSize;
-
- /**
- * A buffer of ranges which is maintained along with
- * the buffer. Ranges are of the form {start, length}.
- * Enables append(char[] array, int start, int end).
- */
- protected int[][] fRanges;
-/**
- * Creates a <code>CharArrayBuffer</code> with the default buffer size (10).
- */
-public CharArrayBuffer() {
- this(null, DEFAULT_BUFFER_SIZE);
-}
-/**
- * Creates a <code>CharArrayBuffer</code> with the default buffer size,
- * and sets the first element in the buffer to be the given char[].
- *
- * @param first - the first element to be placed in the buffer, ignored if null
- */
-public CharArrayBuffer(char[] first) {
- this(first, DEFAULT_BUFFER_SIZE);
-}
-/**
- * Creates a <code>CharArrayBuffer</code> with the given buffer size,
- * and sets the first element in the buffer to be the given char array.
- *
- * @param first - the first element of the buffer, ignored if null.
- * @param size - the buffer size, if less than 1, set to the DEFAULT_BUFFER_SIZE.
- */
-public CharArrayBuffer(char[] first, int size) {
- fSize = (size > 0) ? size : DEFAULT_BUFFER_SIZE;
- fBuffer = new char[fSize][];
- fRanges = new int[fSize][];
- fEnd = 0;
- if (first != null)
- append(first, 0, first.length);
-}
-/**
- * Creates a <code>CharArrayBuffer</code> with the given buffer size.
- *
- * @param size - the size of the buffer.
- */
-public CharArrayBuffer(int size) {
- this(null, size);
-}
-/**
- * Appends the entire given char array. Given for convenience.
- *
- * @param src - a char array which is appended to the end of the buffer.
- */
-public CharArrayBuffer append(char[] src) {
- if (src != null)
- append(src, 0, src.length);
- return this;
-}
-/**
- * Appends a sub array of the given array to the buffer.
- *
- * @param src - the next array of characters to be appended to the buffer, ignored if null
- * @param start - the start index in the src array.
- * @param length - the number of characters from start to be appended
- *
- * @throws ArrayIndexOutOfBoundsException - if arguments specify an array index out of bounds.
- */
-public CharArrayBuffer append(char[] src, int start, int length) {
- if (start < 0) throw new ArrayIndexOutOfBoundsException();
- if (length < 0) throw new ArrayIndexOutOfBoundsException();
- if (src != null) {
- int srcLength = src.length;
- if (start > srcLength) throw new ArrayIndexOutOfBoundsException();
- if (length + start > srcLength) throw new ArrayIndexOutOfBoundsException();
- /** do length check here to allow exceptions to be thrown */
- if (length > 0) {
- if (fEnd == fSize) {
- int size2 = fSize * 2;
- System.arraycopy(fBuffer, 0, (fBuffer = new char[size2][]), 0, fSize);
- System.arraycopy(fRanges, 0, (fRanges = new int[size2][]), 0, fSize);
- fSize *= 2;
- }
- fBuffer[fEnd] = src;
- fRanges[fEnd] = new int[] {start, length};
- fEnd++;
- }
- }
- return this;
-}
-/**
- * Appends the given char. Given for convenience.
- *
- * @param c - a char which is appended to the end of the buffer.
- */
-public CharArrayBuffer append(char c) {
- append(new char[] {c}, 0, 1);
- return this;
-}
-/**
- * Appends the given String to the buffer. Given for convenience, use
- * #append(char[]) if possible
- *
- * @param src - a char array which is appended to the end of the buffer.
- */
-public CharArrayBuffer append(String src) {
- if (src != null)
- append(src.toCharArray(), 0, src.length());
- return this;
-}
-/**
- * Returns the entire contents of the buffer as one
- * char[] or null if nothing has been put in the buffer.
- */
-public char[] getContents() {
- if (fEnd == 0)
- return null;
-
- // determine the size of the array
- int size = 0;
- for (int i = 0; i < fEnd; i++)
- size += fRanges[i][1];
-
- if (size > 0) {
- char[] result = new char[size];
- int current = 0;
- // copy the results
- for(int i = 0; i < fEnd; i++) {
- int[] range = fRanges[i];
- int length = range[1];
- System.arraycopy(fBuffer[i], range[0], result, current, length);
- current += length;
- }
- return result;
- }
- return null;
-}
-/**
- * Returns the contents of the buffer as a String, or
- * an empty string if the buffer is empty.
- */
-public String toString() {
- char[] contents = getContents();
- return (contents != null) ? new String(contents) : Util.EMPTY_STRING;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/CodeSnippetParsingUtil.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/CodeSnippetParsingUtil.java
deleted file mode 100644
index 4dcd56fc..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/CodeSnippetParsingUtil.java
+++ /dev/null
@@ -1,204 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2002, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.util;
-
-import java.util.Locale;
-import java.util.Map;
-
-import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem;
-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.ConstructorDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Expression;
-import org.eclipse.wst.jsdt.internal.compiler.batch.CompilationUnit;
-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.problem.DefaultProblemFactory;
-import org.eclipse.wst.jsdt.internal.compiler.problem.ProblemReporter;
-
-/**
- * Utility class to parse different code snippets
- */
-public class CodeSnippetParsingUtil {
-
- public RecordedParsingInformation recordedParsingInformation;
-
- private RecordedParsingInformation getRecordedParsingInformation(CompilationResult compilationResult, CommentRecorderParser parser) {
- int problemsCount = compilationResult.problemCount;
- CategorizedProblem[] problems = null;
- if (problemsCount != 0) {
- final CategorizedProblem[] compilationResultProblems = compilationResult.problems;
- if (compilationResultProblems.length == problemsCount) {
- problems = compilationResultProblems;
- } else {
- System.arraycopy(compilationResultProblems, 0, (problems = new CategorizedProblem[problemsCount]), 0, problemsCount);
- }
- }
- return new RecordedParsingInformation(problems, compilationResult.getLineSeparatorPositions(), parser.getCommentsPositions());
- }
-
- public ASTNode[] parseClassBodyDeclarations(char[] source, Map settings, boolean recordParsingInformation) {
- return parseClassBodyDeclarations(source, 0, source.length, settings, recordParsingInformation);
- }
-
- public ASTNode[] parseClassBodyDeclarations(char[] source, int offset, int length, Map settings, boolean recordParsingInformation) {
- if (source == null) {
- throw new IllegalArgumentException();
- }
- CompilerOptions compilerOptions = new CompilerOptions(settings);
- final ProblemReporter problemReporter = new ProblemReporter(
- DefaultErrorHandlingPolicies.proceedWithAllProblems(),
- compilerOptions,
- new DefaultProblemFactory(Locale.getDefault()));
-
- CommentRecorderParser parser = new CommentRecorderParser(problemReporter, false);
- parser.setMethodsFullRecovery(false);
- parser.setStatementsRecovery(false);
-
- ICompilationUnit sourceUnit =
- new CompilationUnit(
- source,
- "", //$NON-NLS-1$
- compilerOptions.defaultEncoding);
-
- CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, compilerOptions.maxProblemsPerUnit);
- final CompilationUnitDeclaration compilationUnitDeclaration = new CompilationUnitDeclaration(problemReporter, compilationResult, source.length);
- ASTNode[] result = parser.parseClassBodyDeclarations(source, offset, length, compilationUnitDeclaration);
-
- if (recordParsingInformation) {
- this.recordedParsingInformation = getRecordedParsingInformation(compilationResult, parser);
- }
- return result;
- }
-
- public CompilationUnitDeclaration parseCompilationUnit(char[] source, Map settings, boolean recordParsingInformation) {
- if (source == null) {
- throw new IllegalArgumentException();
- }
- CompilerOptions compilerOptions = new CompilerOptions(settings);
- CommentRecorderParser parser =
- new CommentRecorderParser(
- new ProblemReporter(
- DefaultErrorHandlingPolicies.proceedWithAllProblems(),
- compilerOptions,
- new DefaultProblemFactory(Locale.getDefault())),
- false);
-
- ICompilationUnit sourceUnit =
- new CompilationUnit(
- source,
- "", //$NON-NLS-1$
- compilerOptions.defaultEncoding);
- final CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, compilerOptions.maxProblemsPerUnit);
- CompilationUnitDeclaration compilationUnitDeclaration = parser.dietParse(sourceUnit, compilationResult);
-
- if (recordParsingInformation) {
- this.recordedParsingInformation = getRecordedParsingInformation(compilationResult, parser);
- }
-
- if (compilationUnitDeclaration.ignoreMethodBodies) {
- compilationUnitDeclaration.ignoreFurtherInvestigation = true;
- // if initial diet parse did not work, no need to dig into method bodies.
- return compilationUnitDeclaration;
- }
-
- //fill the methods bodies in order for the code to be generated
- //real parse of the method....
- parser.scanner.setSource(compilationResult);
- org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration[] types = compilationUnitDeclaration.types;
- if (types != null) {
- for (int i = types.length; --i >= 0;) {
- types[i].parseMethod(parser, compilationUnitDeclaration);
- }
- }
-
- if (recordParsingInformation) {
- this.recordedParsingInformation.updateRecordedParsingInformation(compilationResult);
- }
- return compilationUnitDeclaration;
- }
-
- public Expression parseExpression(char[] source, Map settings, boolean recordParsingInformation) {
- return parseExpression(source, 0, source.length, settings, recordParsingInformation);
- }
-
- public Expression parseExpression(char[] source, int offset, int length, Map settings, boolean recordParsingInformation) {
-
- if (source == null) {
- throw new IllegalArgumentException();
- }
- CompilerOptions compilerOptions = new CompilerOptions(settings);
- final ProblemReporter problemReporter = new ProblemReporter(
- DefaultErrorHandlingPolicies.proceedWithAllProblems(),
- compilerOptions,
- new DefaultProblemFactory(Locale.getDefault()));
-
- CommentRecorderParser parser = new CommentRecorderParser(problemReporter, false);
-
- ICompilationUnit sourceUnit =
- new CompilationUnit(
- source,
- "", //$NON-NLS-1$
- compilerOptions.defaultEncoding);
-
- CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, compilerOptions.maxProblemsPerUnit);
- Expression result = parser.parseExpression(source, offset, length, new CompilationUnitDeclaration(problemReporter, compilationResult, source.length));
-
- if (recordParsingInformation) {
- this.recordedParsingInformation = getRecordedParsingInformation(compilationResult, parser);
- }
- return result;
- }
-
- public ConstructorDeclaration parseStatements(char[] source, Map settings, boolean recordParsingInformation, boolean enabledStatementRecovery) {
- return parseStatements(source, 0, source.length, settings, recordParsingInformation, enabledStatementRecovery);
- }
-
- public ConstructorDeclaration parseStatements(char[] source, int offset, int length, Map settings, boolean recordParsingInformation, boolean enabledStatementRecovery) {
- if (source == null) {
- throw new IllegalArgumentException();
- }
- CompilerOptions compilerOptions = new CompilerOptions(settings);
- final ProblemReporter problemReporter = new ProblemReporter(
- DefaultErrorHandlingPolicies.proceedWithAllProblems(),
- compilerOptions,
- new DefaultProblemFactory(Locale.getDefault()));
- CommentRecorderParser parser = new CommentRecorderParser(problemReporter, false);
- parser.setMethodsFullRecovery(false);
- parser.setStatementsRecovery(enabledStatementRecovery);
-
- ICompilationUnit sourceUnit =
- new CompilationUnit(
- source,
- "", //$NON-NLS-1$
- compilerOptions.defaultEncoding);
-
- final CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, compilerOptions.maxProblemsPerUnit);
- CompilationUnitDeclaration compilationUnitDeclaration = new CompilationUnitDeclaration(problemReporter, compilationResult, length);
-
- ConstructorDeclaration constructorDeclaration = new ConstructorDeclaration(compilationResult);
- constructorDeclaration.sourceEnd = -1;
- constructorDeclaration.declarationSourceEnd = offset + length - 1;
- constructorDeclaration.bodyStart = offset;
- constructorDeclaration.bodyEnd = offset + length - 1;
-
- parser.scanner.setSource(compilationResult);
- parser.scanner.resetTo(offset, offset + length);
- parser.parse(constructorDeclaration, compilationUnitDeclaration, true);
-
- if (recordParsingInformation) {
- this.recordedParsingInformation = getRecordedParsingInformation(compilationResult, parser);
- }
- return constructorDeclaration;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/CommentRecorderParser.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/CommentRecorderParser.java
deleted file mode 100644
index b969ed6c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/CommentRecorderParser.java
+++ /dev/null
@@ -1,260 +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.util;
-
-import org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants;
-import org.eclipse.wst.jsdt.internal.compiler.impl.CompilerOptions;
-import org.eclipse.wst.jsdt.internal.compiler.parser.Parser;
-import org.eclipse.wst.jsdt.internal.compiler.problem.ProblemReporter;
-import org.eclipse.wst.jsdt.internal.compiler.problem.ProblemSeverities;
-
-/**
- * Internal parser used for parsing source to create DOM AST nodes.
- *
- * @since 3.0
- */
-public class CommentRecorderParser extends Parser {
-
- // support for comments
- int[] commentStops = new int[10];
- int[] commentStarts = new int[10];
- int commentPtr = -1; // no comment test with commentPtr value -1
- protected final static int CommentIncrement = 100;
-
- /**
- * @param problemReporter
- * @param optimizeStringLiterals
- */
- public CommentRecorderParser(ProblemReporter problemReporter, boolean optimizeStringLiterals) {
- super(problemReporter, optimizeStringLiterals);
- }
-
- // old javadoc style check which doesn't include all leading comments into declaration
- // for backward compatibility with 2.1 DOM
- public void checkComment() {
-
- // discard obsolete comments while inside methods or fields initializer (see bug 74369)
- if (!(this.diet && this.dietInt==0) && this.scanner.commentPtr >= 0) {
- flushCommentsDefinedPriorTo(this.endStatementPosition);
- }
- boolean deprecated = false;
- boolean checkDeprecated = false;
- int lastCommentIndex = -1;
-
- //since jdk1.2 look only in the last java doc comment...
- nextComment : for (lastCommentIndex = this.scanner.commentPtr; lastCommentIndex >= 0; lastCommentIndex--){
- //look for @deprecated into the first javadoc comment preceeding the declaration
- int commentSourceStart = this.scanner.commentStarts[lastCommentIndex];
- // javadoc only (non javadoc comment have negative end positions.)
- if ((commentSourceStart < 0) ||
- (this.modifiersSourceStart != -1 && this.modifiersSourceStart < commentSourceStart) ||
- (this.scanner.commentStops[lastCommentIndex] < 0))
- {
- continue nextComment;
- }
- checkDeprecated = true;
- int commentSourceEnd = this.scanner.commentStops[lastCommentIndex] - 1; //stop is one over
-
- // do not report problem before last parsed comment while recovering code...
- this.javadocParser.reportProblems = this.currentElement == null || commentSourceEnd > this.lastJavadocEnd;
- deprecated = this.javadocParser.checkDeprecation(lastCommentIndex);
- this.javadoc = this.javadocParser.docComment;
- break nextComment;
- }
- if (deprecated) {
- checkAndSetModifiers(ClassFileConstants.AccDeprecated);
- }
- // modify the modifier source start to point at the first comment
- if (lastCommentIndex >= 0 && checkDeprecated) {
- this.modifiersSourceStart = this.scanner.commentStarts[lastCommentIndex];
- if (this.modifiersSourceStart < 0) {
- this.modifiersSourceStart = -this.modifiersSourceStart;
- }
- }
- }
-
- /**
- * Insure that start position is always positive.
- * @see org.eclipse.wst.jsdt.internal.compiler.parser.Parser#containsComment(int, int)
- */
- public boolean containsComment(int sourceStart, int sourceEnd) {
- int iComment = this.scanner.commentPtr;
- for (; iComment >= 0; iComment--) {
- int commentStart = this.scanner.commentStarts[iComment];
- if (commentStart < 0) {
- commentStart = -commentStart;
- }
- // ignore comments before start
- if (commentStart < sourceStart) continue;
- // ignore comments after end
- if (commentStart > sourceEnd) continue;
- return true;
- }
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.parser.Parser#endParse(int)
- */
- protected CompilationUnitDeclaration endParse(int act) {
- CompilationUnitDeclaration unit = super.endParse(act);
- if (unit.comments == null) {
- pushOnCommentsStack(0, this.scanner.commentPtr);
- unit.comments = getCommentsPositions();
- }
- return unit;
- }
-
- /* (non-Javadoc)
- * Save all source comments currently stored before flushing them.
- * @see org.eclipse.wst.jsdt.internal.compiler.parser.Parser#flushCommentsDefinedPriorTo(int)
- */
- 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 <position> is immediately followed by a line comment, then
- // flush this comment and shift <position> to the comment end.
- if (validCount > 0){
- int immediateCommentEnd = 0;
- while (index<lastCommentIndex && (immediateCommentEnd = -this.scanner.commentStops[index+1]) > 0){ // only tolerating non-javadoc comments (non-javadoc comment end positions are negative)
- // 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 (org.eclipse.wst.jsdt.internal.compiler.util.Util.getLineNumber(position, this.scanner.lineEnds, 0, this.scanner.linePtr)
- != org.eclipse.wst.jsdt.internal.compiler.util.Util.getLineNumber(immediateCommentEnd, this.scanner.lineEnds, 0, this.scanner.linePtr)) break;
- position = immediateCommentEnd;
- validCount--; // flush this comment
- index++;
- }
- }
-
- if (index < 0) return position; // no obsolete comment
- pushOnCommentsStack(0, index); // store comment before flushing them
-
- 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;
- }
-
- /*
- * Build a n*2 matrix of comments positions.
- * For each position, 0 is for start position and 1 for end position of the comment.
- */
- public int[][] getCommentsPositions() {
- int[][] positions = new int[this.commentPtr+1][2];
- for (int i = 0, max = this.commentPtr; i <= max; i++){
- positions[i][0] = this.commentStarts[i];
- positions[i][1] = this.commentStops[i];
- }
- return positions;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.parser.Parser#initialize()
- */
- public void initialize(boolean initializeNLS) {
- super.initialize(initializeNLS);
- this.commentPtr = -1;
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.parser.Parser#initialize()
- */
- public void initialize() {
- super.initialize();
- this.commentPtr = -1;
- }
-
- /* (non-Javadoc)
- * Create and store a specific comment recorder scanner.
- * @see org.eclipse.wst.jsdt.internal.compiler.parser.Parser#initializeScanner()
- */
- public void initializeScanner() {
- this.scanner = new CommentRecorderScanner(
- false /*comment*/,
- false /*whitespace*/,
- this.options.getSeverity(CompilerOptions.NonExternalizedString) != ProblemSeverities.Ignore /*nls*/,
- this.options.sourceLevel /*sourceLevel*/,
- this.options.taskTags/*taskTags*/,
- this.options.taskPriorites/*taskPriorities*/,
- this.options.isTaskCaseSensitive/*taskCaseSensitive*/);
- }
-
- /*
- * Push all stored comments in stack.
- */
- private void pushOnCommentsStack(int start, int end) {
-
- for (int i=start; i<=end; i++) {
- // First see if comment hasn't been already stored
- int scannerStart = this.scanner.commentStarts[i]<0 ? -this.scanner.commentStarts[i] : this.scanner.commentStarts[i];
- int commentStart = this.commentPtr == -1 ? -1 : (this.commentStarts[this.commentPtr]<0 ? -this.commentStarts[this.commentPtr] : this.commentStarts[this.commentPtr]);
- if (commentStart == -1 || scannerStart > commentStart) {
- int stackLength = this.commentStarts.length;
- if (++this.commentPtr >= stackLength) {
- System.arraycopy(
- this.commentStarts, 0,
- this.commentStarts = new int[stackLength + CommentIncrement], 0,
- stackLength);
- System.arraycopy(
- this.commentStops, 0,
- this.commentStops = new int[stackLength + CommentIncrement], 0,
- stackLength);
- }
- this.commentStarts[this.commentPtr] = this.scanner.commentStarts[i];
- this.commentStops[this.commentPtr] = this.scanner.commentStops[i];
- }
- }
- }
- /* (non-Javadoc)
- * Save all source comments currently stored before flushing them.
- * @see org.eclipse.wst.jsdt.internal.compiler.parser.Parser#resetModifiers()
- */
- protected void resetModifiers() {
- pushOnCommentsStack(0, this.scanner.commentPtr);
- super.resetModifiers();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/CommentRecorderScanner.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/CommentRecorderScanner.java
deleted file mode 100644
index 128e08c7..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/CommentRecorderScanner.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*******************************************************************************
- * 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
- * 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.internal.compiler.parser.Scanner;
-
-/**
- * Internal scanner used for DOM AST nodes.
- *
- * @since 3.0
- */
-public class CommentRecorderScanner extends Scanner {
-
- public CommentRecorderScanner(
- boolean tokenizeComments,
- boolean tokenizeWhiteSpace,
- boolean checkNonExternalizedStringLiterals,
- long sourceLevel,
- char[][] taskTags,
- char[][] taskPriorities,
- boolean isTaskCaseSensitive) {
- super(tokenizeComments, tokenizeWhiteSpace, checkNonExternalizedStringLiterals, sourceLevel, taskTags, taskPriorities, isTaskCaseSensitive);
- }
-
- /**
- * Set start position negative for line comments.
- * @see org.eclipse.wst.jsdt.internal.compiler.parser.Scanner#recordComment(int)
- */
- public void recordComment(int token) {
- super.recordComment(token);
- if (token == TokenNameCOMMENT_LINE) {
- // for comment line both positions are negative
- this.commentStarts[this.commentPtr] = -this.commentStarts[this.commentPtr];
- }
- }
-}
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
deleted file mode 100644
index 4fff789d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ConvertUtility.java
+++ /dev/null
@@ -1,333 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.util;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IProjectDescription;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.SubProgressMonitor;
-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.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.LibrarySuperType;
-import org.eclipse.wst.jsdt.internal.core.JavaProject;
-
-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 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$
-
- public static final String VIRTUAL_CONTAINER = "org.eclipse.wst.jsdt.launching.WebProject"; //$NON-NLS-1$
- public static final IIncludePathEntry VIRTUAL_SCOPE_ENTRY = JavaScriptCore.newContainerEntry(new Path(VIRTUAL_CONTAINER), new IAccessRule[0], new IIncludePathAttribute[]{IIncludePathAttribute.HIDE}, false);
-
-
- static void addJsNature(IProject project, IProgressMonitor monitor) throws CoreException {
- if (monitor != null && monitor.isCanceled()) {
- throw new OperationCanceledException();
- }
- if (!hasNature(project)) {
- IProjectDescription description = project.getDescription();
- String[] prevNatures = description.getNatureIds();
- String[] newNatures = new String[prevNatures.length + NATURE_IDS.length];
- System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
- // newNatures[prevNatures.length] = JavaScriptCore.NATURE_ID;
- for (int i = 0; i < NATURE_IDS.length; i++) {
- newNatures[prevNatures.length + i] = NATURE_IDS[i];
- }
- description.setNatureIds(newNatures);
- project.setDescription(description, monitor);
- }
- else {
- if (monitor != null) {
- monitor.worked(1);
- }
- }
- }
-
- public static boolean hasNature(IProject project) {
- try {
- for (int i = 0; i < NATURE_IDS.length; i++) {
- if (!project.hasNature(NATURE_IDS[i])) {
- return false;
- }
- }
- }
- catch (CoreException ex) {
- return false;
- }
- return true;
- }
-
- static void removeJsNature(IProject project, IProgressMonitor monitor) throws CoreException {
- if (monitor != null && monitor.isCanceled()) {
- throw new OperationCanceledException();
- }
- if (hasNature(project)) {
- IProjectDescription description = project.getDescription();
- String[] prevNatures = description.getNatureIds();
- String[] newNatures = new String[prevNatures.length - NATURE_IDS.length];
- int k = 0;
- head : for (int i = 0; i < prevNatures.length; i++) {
- for (int j = 0; j < NATURE_IDS.length; j++) {
- if (prevNatures[i].equals(NATURE_IDS[j])) {
- continue head;
- }
- }
- newNatures[k++] = prevNatures[i];
- }
- description.setNatureIds(newNatures);
- project.setDescription(description, monitor);
- }
- else {
- if (monitor != null) {
- monitor.worked(1);
- }
- }
- }
-
- private boolean DEBUG = false;
- private IProject fCurrProject;
- private JavaProject fJavaProject;
- private IPath fOutputLocation;
-
- public ConvertUtility(IProject project) {
- fCurrProject = project;
- fOutputLocation = fCurrProject.getFullPath();
- }
-
- private IProgressMonitor monitorFor(IProgressMonitor monitor) {
- if (monitor != null)
- return monitor;
- return new NullProgressMonitor();
- }
-
- public void addBrowserSupport(boolean changeSuperType, IProgressMonitor monitor) throws CoreException {
- IProgressMonitor progressMonitor = monitorFor(monitor);
- progressMonitor.beginTask(Messages.converter_ConfiguringForBrowser, 2);
- fJavaProject = (JavaProject) JavaScriptCore.create(fCurrProject);
- if (!fJavaProject.exists())
- configure(new SubProgressMonitor(progressMonitor, 1));
-
- fJavaProject.setProject(fCurrProject);
-
- IIncludePathEntry[] includePath = getRawClassPath();
- includePath = addEntry(includePath, VIRTUAL_SCOPE_ENTRY, false);
- includePath = addEntry(includePath, JavaScriptCore.newContainerEntry(BROWSER_LIBRARY_PATH), false);
-
- try {
- if (!hasProjectClassPathFile()) {
- fJavaProject.setRawIncludepath(includePath, fOutputLocation, new SubProgressMonitor(progressMonitor, 1));
- }
- else {
- fJavaProject.setRawIncludepath(includePath, new SubProgressMonitor(progressMonitor, 1));
- }
- }
- catch (Exception e) {
- System.out.println(e);
- }
-
- if (changeSuperType) {
- LibrarySuperType superType = new LibrarySuperType(BROWSER_LIBRARY_PATH, getJavaScriptProject(), BROWSER_SUPER_TYPE_NAME);
- getJavaScriptProject().setCommonSuperType(superType);
- }
-
- // getJavaProject().addToBuildSpec(BUILDER_ID);
- // fCurrProject.refreshLocal(IResource.DEPTH_INFINITE, monitor);
- progressMonitor.done();
- }
-
- private IIncludePathEntry[] addEntry(IIncludePathEntry[] entries, IIncludePathEntry newEntry, boolean first) {
- for (int i = 0; i < entries.length; i++) {
- // avoid duplicate IIncludePathEntry-s
- if (newEntry.getPath().equals(entries[i].getPath())) {
- return entries;
- }
- }
-
- List entriesList = new ArrayList(Arrays.asList(entries));
- if (first && !entriesList.isEmpty())
- entriesList.add(0, newEntry);
- else
- entriesList.add(newEntry);
- return (IIncludePathEntry[]) entriesList.toArray(new IIncludePathEntry[entriesList.size()]);
- }
-
- // private void createSourceClassPath() {
- // if (hasAValidSourcePath()) {
- // return;
- // }
- // // IPath projectPath = fCurrProject.getFullPath();
- // // classPathEntries.add(JavaScriptCore.newSourceEntry(projectPath));
- // }
-
- // public void deconfigure() throws CoreException {
- // Vector badEntries = new Vector();
- // IIncludePathEntry defaultJRELibrary = createRuntimeEntry();
- // IIncludePathEntry[] localEntries = initLocalClassPath();
- // badEntries.add(defaultJRELibrary);
- // badEntries.addAll(Arrays.asList(localEntries));
- // IIncludePathEntry[] entries = getRawClassPath();
- // List goodEntries = new ArrayList();
- // for (int i = 0; i < entries.length; i++) {
- // if (!badEntries.contains(entries[i])) {
- // goodEntries.add(entries[i]);
- // }
- // }
- // IPath outputLocation = getJavaScriptProject().getOutputLocation();
- // getJavaScriptProject().setRawIncludepath((IIncludePathEntry[])
- // goodEntries.toArray(new IIncludePathEntry[] {}), outputLocation,
- // monitor);
- //
- // // getJavaProject().removeFromBuildSpec(BUILDER_ID);
- // getJavaScriptProject().deconfigure();
- //
- // removeJsNature(fCurrProject, monitor);
- // fCurrProject.refreshLocal(IResource.DEPTH_INFINITE, monitor);
- // }
-
- private IIncludePathEntry[] addSystemEntry(IIncludePathEntry[] entries) {
- IIncludePathEntry defaultJRELibrary = createRuntimeEntry();
- try {
- for (int i = 0; i < entries.length; i++) {
- if (defaultJRELibrary.equals(entries[i])) {
- return entries;
- }
- }
- }
- catch (Exception e) {
- if (DEBUG) {
- System.out.println("Error checking system library in include path:" + e); //$NON-NLS-1$
- }
- }
- return addEntry(entries, defaultJRELibrary, false);
- }
-
- public void configure(IProgressMonitor monitor) throws CoreException {
- IProgressMonitor progressMonitor = monitorFor(monitor);
- progressMonitor.beginTask("", 2);//$NON-NLS-1$
- addJsNature(fCurrProject, new SubProgressMonitor(progressMonitor, 1));
-
- fJavaProject = (JavaProject) JavaScriptCore.create(fCurrProject);
- fJavaProject.setProject(fCurrProject);
-
- IIncludePathEntry[] includePath = getRawClassPath();
- includePath = addSystemEntry(includePath);
-
- try {
- if (!hasProjectClassPathFile()) {
- fJavaProject.setRawIncludepath(includePath, fOutputLocation, new SubProgressMonitor(progressMonitor, 1));
- }
- else {
- fJavaProject.setRawIncludepath(includePath, new SubProgressMonitor(progressMonitor, 1));
- }
- }
- catch (Exception e) {
- System.out.println(e);
- }
-
- LibrarySuperType superType = new LibrarySuperType(new Path(SYSTEM_LIBRARY), getJavaScriptProject(), SYSTEM_SUPER_TYPE_NAME);
- getJavaScriptProject().setCommonSuperType(superType);
- progressMonitor.done();
-
- // getJavaProject().addToBuildSpec(BUILDER_ID);
- // fCurrProject.refreshLocal(IResource.DEPTH_INFINITE, monitor);
- }
-
- private IIncludePathEntry createRuntimeEntry() {
- return JavaScriptCore.newContainerEntry(new Path(SYSTEM_LIBRARY));
- }
-
- private JavaProject getJavaScriptProject() {
- if (fJavaProject == null) {
- fJavaProject = (JavaProject) JavaScriptCore.create(fCurrProject);
- fJavaProject.setProject(fCurrProject);
- }
- return fJavaProject;
- }
-
- public IProject getProject() {
- return this.fCurrProject;
- }
-
- public IIncludePathEntry[] getDefaultSourcePaths(IProject p) {
- IIncludePathEntry[] defaults = new IIncludePathEntry[]{JavaScriptCore.newSourceEntry(p.getFullPath())};
- try {
- IConfigurationElement[] configurationElements = Platform.getExtensionRegistry().getConfigurationElementsFor("org.eclipse.wst.jsdt.core.sourcePathProvider");
- List provided = new ArrayList();
- for (int i = 0; i < configurationElements.length; i++) {
- DefaultSourcePathProvider provider = (DefaultSourcePathProvider) configurationElements[i].createExecutableExtension("class");
- if (provider != null) {
- provided.addAll(Arrays.asList(provider.getDefaultSourcePaths(p)));
- }
- }
- if (!provided.isEmpty()) {
- return (IIncludePathEntry[]) provided.toArray(new IIncludePathEntry[provided.size()]);
- }
- }
- catch (Exception e) {
- if (Platform.inDebugMode()) {
- Platform.getLog(JavaScriptCore.getPlugin().getBundle()).log(new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, "Problem getting source paths", e));
- }
- }
- return defaults;
- }
-
- private IIncludePathEntry[] getRawClassPath() {
- JavaProject proj = new JavaProject();
- proj.setProject(fCurrProject);
- 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 hasProjectClassPathFile() {
- if (fCurrProject == null) {
- return false;
- }
- return fCurrProject.getFolder(JavaProject.DEFAULT_PREFERENCES_DIRNAME).getFile(JavaProject.CLASSPATH_FILENAME).exists();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/DOMFinder.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/DOMFinder.java
deleted file mode 100644
index ab752aac..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/DOMFinder.java
+++ /dev/null
@@ -1,117 +0,0 @@
-/*******************************************************************************
- * 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
- * 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.IInitializer;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.ImportDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Initializer;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.PackageDeclaration;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.internal.core.SourceRefElement;
-
-public class DOMFinder extends ASTVisitor {
-
- public ASTNode foundNode = null;
- public IBinding foundBinding = null;
-
- private JavaScriptUnit ast;
- private SourceRefElement element;
- private boolean resolveBinding;
- private int rangeStart = -1, rangeLength = 0;
-
- public DOMFinder(JavaScriptUnit ast, SourceRefElement element, boolean resolveBinding) {
- this.ast = ast;
- this.element = element;
- this.resolveBinding = resolveBinding;
- }
-
- protected boolean found(ASTNode node, ASTNode name) {
- if (name.getStartPosition() == this.rangeStart && name.getLength() == this.rangeLength) {
- this.foundNode = node;
- return true;
- }
- return false;
- }
-
- public ASTNode search() throws JavaScriptModelException {
- ISourceRange range = null;
- if (this.element instanceof IMember && !(this.element instanceof IInitializer))
- range = ((IMember) this.element).getNameRange();
- else
- range = this.element.getSourceRange();
- this.rangeStart = range.getOffset();
- this.rangeLength = range.getLength();
- this.ast.accept(this);
- return this.foundNode;
- }
-
- public boolean visit(AnonymousClassDeclaration node) {
- ASTNode name;
- ASTNode parent = node.getParent();
- switch (parent.getNodeType()) {
- case ASTNode.CLASS_INSTANCE_CREATION:
- name = ((ClassInstanceCreation) parent).getType();
- break;
- default:
- return true;
- }
- if (found(node, name) && this.resolveBinding)
- this.foundBinding = node.resolveBinding();
- return true;
- }
-
- public boolean visit(ImportDeclaration node) {
- if (found(node, node) && this.resolveBinding)
- this.foundBinding = node.resolveBinding();
- return true;
- }
-
- public boolean visit(Initializer node) {
- // note that no binding exists for an Initializer
- found(node, node);
- return true;
- }
-
- public boolean visit(FunctionDeclaration node) {
- if (found(node, node.getName()) && this.resolveBinding)
- this.foundBinding = node.resolveBinding();
- return true;
- }
-
- public boolean visit(PackageDeclaration node) {
- if (found(node, node) && this.resolveBinding)
- this.foundBinding = node.resolveBinding();
- return true;
- }
-
- public boolean visit(TypeDeclaration node) {
- if (found(node, node.getName()) && this.resolveBinding)
- this.foundBinding = node.resolveBinding();
- return true;
- }
-
- public boolean visit(VariableDeclarationFragment node) {
- if (found(node, node.getName()) && this.resolveBinding)
- this.foundBinding = node.resolveBinding();
- return true;
- }
-}
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
deleted file mode 100644
index a148ea62..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/DefaultSourcePathProvider.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 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.internal.core.util;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-
-public abstract class DefaultSourcePathProvider {
- public DefaultSourcePathProvider() {
- }
-
- public IIncludePathEntry[] getDefaultSourcePaths(IProject p) {
- return new IIncludePathEntry[]{JavaScriptCore.newSourceEntry(p.getFullPath())};
- }
-}
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
deleted file mode 100644
index ebf84356..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/HandleFactory.java
+++ /dev/null
@@ -1,374 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.util;
-
-import java.util.HashMap;
-import java.util.HashSet;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-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.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-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.IPackageFragment;
-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.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-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.FieldDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ClassScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.Scope;
-import org.eclipse.wst.jsdt.internal.core.JavaModel;
-import org.eclipse.wst.jsdt.internal.core.JavaModelManager;
-import org.eclipse.wst.jsdt.internal.core.JavaProject;
-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.SourceRefElement;
-
-/**
- * Creates java element handles.
- */
-public class HandleFactory {
-
- /**
- * Cache package fragment root information to optimize speed performance.
- */
- private String lastPkgFragmentRootPath;
- private PackageFragmentRoot lastPkgFragmentRoot;
- private boolean lastIsFullPath;
-
- /**
- * Cache package handles to optimize memory.
- */
- private HashtableOfArrayToObject packageHandles;
-
- private JavaModel javaModel;
-
- public HandleFactory() {
- this.javaModel = JavaModelManager.getJavaModelManager().getJavaModel();
- }
-
-
- /**
- * Creates an Openable handle from the given resource path.
- * The resource path can be a path to a file in the workbench (eg. /Proj/com/ibm/jdt/core/HandleFactory.js)
- * or a path to a file in a jar file - it then contains the path to the jar file and the path to the file in the jar
- * (eg. c:/jdk1.2.2/jre/lib/rt.jar|java/lang/Object.class or /Proj/rt.jar|java/lang/Object.class)
- * NOTE: This assumes that the resource path is the toString() of an IPath,
- * in other words, it uses the IPath.SEPARATOR for file path
- * and it uses '/' for entries in a zip file.
- * If not null, uses the given scope as a hint for getting Java project handles.
- */
- 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 {
- // path to a file in a directory
- // Optimization: cache package fragment root handle and package handles
- int rootPathLength = -1;
- //FIXME - may want to add some performance checks back here at some point
- // Fix for https://bugs.eclipse.org/bugs/show_bug.cgi?id=317511
-// if (this.lastPkgFragmentRootPath == null
-// || !(resourcePath.startsWith(this.lastPkgFragmentRootPath)
-// && (rootPathLength = this.lastPkgFragmentRootPath.length()) > 0
-// && resourcePath.charAt(rootPathLength) == '/')) {
-
- if (resourcePath.endsWith("/")) //$NON-NLS-1$
- resourcePath=resourcePath.substring(0,resourcePath.length()-1);
- PackageFragmentRoot root= this.getPkgFragmentRoot(resourcePath);
- if (root instanceof LibraryFragmentRoot && !((LibraryFragmentRoot)root).isDirectory())
- {
- return (Openable)((LibraryFragmentRoot)root).getPackageFragment(resourcePath).getClassFile(resourcePath);
- }
- if (root == null)
- return null; // match is outside classpath
- this.lastPkgFragmentRoot = root;
- this.lastPkgFragmentRootPath = this.lastIsFullPath ?
- this.lastPkgFragmentRoot.getLocation().toString() : this.lastPkgFragmentRoot.getPath().toString();
- this.packageHandles = new HashtableOfArrayToObject(5);
- //}
- // create handle
- resourcePath = resourcePath.substring(this.lastPkgFragmentRootPath.length() + 1);
- String[] simpleNames = new Path(resourcePath).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);
- }
- String simpleName= simpleNames[length];
-
- if (pkgFragment.isSource() &&
- !Util.isMetadataFileName(simpleName)) {
- IJavaScriptUnit unit= pkgFragment.getJavaScriptUnit(simpleName);
- return (Openable) unit;
- } else {
- IClassFile classFile= pkgFragment.getClassFile(simpleName);
- return (Openable) classFile;
- }
-// }
- }
-
- /**
- * Returns a handle denoting the class member identified by its scope.
- */
- public IJavaScriptElement createElement(ClassScope scope, IJavaScriptUnit unit, HashSet existingElements, HashMap knownScopes) {
- return createElement(scope, scope.referenceContext.sourceStart, unit, existingElements, knownScopes);
- }
- /**
- * Create handle by adding child to parent obtained by recursing into parent scopes.
- */
- private IJavaScriptElement createElement(Scope scope, int elementPosition, IJavaScriptUnit unit, HashSet existingElements, HashMap knownScopes) {
- IJavaScriptElement newElement = (IJavaScriptElement)knownScopes.get(scope);
- if (newElement != null) return newElement;
-
- switch(scope.kind) {
- case Scope.COMPILATION_UNIT_SCOPE :
- newElement = unit;
- break;
- case Scope.CLASS_SCOPE :
- IJavaScriptElement parentElement = createElement(scope.parent, elementPosition, unit, existingElements, knownScopes);
- switch (parentElement.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_UNIT :
- newElement = ((IJavaScriptUnit)parentElement).getType(new String(scope.enclosingSourceType().sourceName));
- break;
- case IJavaScriptElement.TYPE :
- newElement = ((IType)parentElement).getType(new String(scope.enclosingSourceType().sourceName));
- break;
- case IJavaScriptElement.FIELD :
- case IJavaScriptElement.INITIALIZER :
- case IJavaScriptElement.METHOD :
- IMember member = (IMember)parentElement;
- if (member.isBinary()) {
- return null;
- } else {
- newElement = member.getType(new String(scope.enclosingSourceType().sourceName), 1);
- // increment occurrence count if collision is detected
- if (newElement != null) {
- while (!existingElements.add(newElement)) ((SourceRefElement)newElement).occurrenceCount++;
- }
- }
- break;
- }
- if (newElement != null) {
- knownScopes.put(scope, newElement);
- }
- break;
- case Scope.METHOD_SCOPE :
- IType parentType = (IType) createElement(scope.parent, elementPosition, unit, existingElements, knownScopes);
- MethodScope methodScope = (MethodScope) scope;
- if (methodScope.isInsideInitializer()) {
- // inside field or initializer, must find proper one
- TypeDeclaration type = methodScope.referenceType();
- int occurenceCount = 1;
- for (int i = 0, length = type.fields.length; i < length; i++) {
- FieldDeclaration field = type.fields[i];
- if (field.declarationSourceStart < elementPosition && field.declarationSourceEnd > elementPosition) {
- switch (field.getKind()) {
- case AbstractVariableDeclaration.FIELD :
- newElement = parentType.getField(new String(field.name));
- break;
- case AbstractVariableDeclaration.INITIALIZER :
- newElement = parentType.getInitializer(occurenceCount);
- break;
- }
- break;
- } else if (field.getKind() == AbstractVariableDeclaration.INITIALIZER) {
- occurenceCount++;
- }
- }
- } else {
- // method element
- AbstractMethodDeclaration method = methodScope.referenceMethod();
- newElement = parentType.getFunction(new String(method.getSafeName()), Util.typeParameterSignatures(method));
- if (newElement != null) {
- knownScopes.put(scope, newElement);
- }
- }
- break;
- case Scope.BLOCK_SCOPE :
- // standard block, no element per se
- newElement = createElement(scope.parent, elementPosition, unit, existingElements, knownScopes);
- break;
- }
- return newElement;
- }
- /**
- * Returns the package fragment root that corresponds to the given jar path.
- * See createOpenable(...) for the format of the jar path string.
- * If not null, uses the given scope as a hint for getting Java project handles.
- */
- private IPackageFragmentRoot getJarPkgFragmentRoot(String jarPathString, IJavaScriptSearchScope scope) {
-
- IPath jarPath= new Path(jarPathString);
-
- Object target = JavaModel.getTarget(ResourcesPlugin.getWorkspace().getRoot(), jarPath, false);
- if (target instanceof IFile) {
- // internal jar: is it on the classpath of its project?
- // e.g. org.eclipse.swt.win32/ws/win32/swt.jar
- // is NOT on the classpath of org.eclipse.swt.win32
- IFile jarFile = (IFile)target;
- JavaProject javaProject = (JavaProject) this.javaModel.getJavaProject(jarFile);
- try {
- IIncludePathEntry entry = javaProject.getClasspathEntryFor(jarPath);
- if (entry != null) {
- return javaProject.getPackageFragmentRoot(jarFile);
- }
- } catch (JavaScriptModelException e) {
- // ignore and try to find another project
- }
- }
-
- // walk projects in the scope and find the first one that has the given jar path in its classpath
- IJavaScriptProject[] projects;
- if (scope != null) {
- IPath[] enclosingProjectsAndJars = scope.enclosingProjectsAndJars();
- int length = enclosingProjectsAndJars.length;
- projects = new IJavaScriptProject[length];
- int index = 0;
- for (int i = 0; i < length; i++) {
- IPath path = enclosingProjectsAndJars[i];
- if (!org.eclipse.wst.jsdt.internal.compiler.util.Util.isArchiveFileName(path.lastSegment())) {
- projects[index++] = this.javaModel.getJavaScriptProject(path.segment(0));
- }
- }
- if (index < length) {
- System.arraycopy(projects, 0, projects = new IJavaScriptProject[index], 0, index);
- }
- IPackageFragmentRoot root = getJarPkgFragmentRoot(jarPath, target, projects);
- if (root != null) {
- return root;
- }
- }
-
- // not found in the scope, walk all projects
- try {
- projects = this.javaModel.getJavaScriptProjects();
- } catch (JavaScriptModelException e) {
- // java model is not accessible
- return null;
- }
- return getJarPkgFragmentRoot(jarPath, target, projects);
- }
-
- private IPackageFragmentRoot getJarPkgFragmentRoot(
- IPath jarPath,
- Object target,
- IJavaScriptProject[] projects) {
- for (int i= 0, projectCount= projects.length; i < projectCount; i++) {
- try {
- JavaProject javaProject= (JavaProject)projects[i];
- IIncludePathEntry classpathEnty = javaProject.getClasspathEntryFor(jarPath);
- if (classpathEnty != null) {
- if (target instanceof IFile) {
- // internal jar
- return javaProject.getPackageFragmentRoot((IFile)target);
- } else {
- // external jar
- return javaProject.getPackageFragmentRoot0(jarPath);
- }
- }
- } catch (JavaScriptModelException e) {
- // JavaScriptModelException from getResolvedClasspath - a problem occured while accessing project: nothing we can do, ignore
- }
- }
- return null;
- }
-
- /**
- * Returns the package fragment root that contains the given resource path.
- */
- private PackageFragmentRoot getPkgFragmentRoot(String pathString) {
-
- IPath path= new Path(pathString);
- IProject[] projects= ResourcesPlugin.getWorkspace().getRoot().getProjects();
- this.lastIsFullPath=false;
- for (int i= 0, max= projects.length; i < max; i++) {
- try {
- IProject project = projects[i];
- if (!project.isAccessible()
- || !project.hasNature(JavaScriptCore.NATURE_ID)) continue;
- IJavaScriptProject javaProject= this.javaModel.getJavaProject(project);
- IPackageFragmentRoot[] roots= javaProject.getPackageFragmentRoots();
- for (int j= 0, rootCount= roots.length; j < rootCount; j++) {
- PackageFragmentRoot root= (PackageFragmentRoot)roots[j];
- if ( root.getPath().isPrefixOf(path) && !Util.isExcluded(path, root.fullInclusionPatternChars(), root.fullExclusionPatternChars(), false))
- {
- return root;
- }
- if ( root.getLocation().isPrefixOf(path)
- && !Util.isExcluded(path, root.fullInclusionPatternChars(), root.fullExclusionPatternChars(), false)) {
- this.lastIsFullPath=true;
- return root;
- }
- }
- } catch (CoreException e) {
- // CoreException from hasNature - should not happen since we check that the project is accessible
- // JavaScriptModelException from getPackageFragmentRoots - a problem occured while accessing project: nothing we can do, ignore
- }
- }
- return null;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/HashSetOfArray.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/HashSetOfArray.java
deleted file mode 100644
index c4fae300..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/HashSetOfArray.java
+++ /dev/null
@@ -1,149 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.util;
-
-/**
- * HashSet of Object[]
- */
-public final class HashSetOfArray implements Cloneable {
-
- // to avoid using Enumerations, walk the individual tables skipping nulls
- public Object[][] set;
-
- public int elementSize; // number of elements in the table
- int threshold;
-
- public HashSetOfArray() {
- this(13);
- }
-
- public HashSetOfArray(int size) {
-
- this.elementSize = 0;
- this.threshold = size; // size represents the expected number of elements
- int extraRoom = (int) (size * 1.75f);
- if (this.threshold == extraRoom)
- extraRoom++;
- this.set = new Object[extraRoom][];
- }
-
- public Object clone() throws CloneNotSupportedException {
- HashSetOfArray result = (HashSetOfArray) super.clone();
- result.elementSize = this.elementSize;
- result.threshold = this.threshold;
-
- int length = this.set.length;
- result.set = new Object[length][];
- System.arraycopy(this.set, 0, result.set, 0, length);
-
- return result;
- }
-
- public boolean contains(Object[] array) {
- int length = this.set.length;
- int index = hashCode(array) % length;
- int arrayLength = array.length;
- Object[] currentArray;
- while ((currentArray = this.set[index]) != null) {
- if (currentArray.length == arrayLength && Util.equalArraysOrNull(currentArray, array))
- return true;
- if (++index == length) {
- index = 0;
- }
- }
- return false;
- }
-
- private int hashCode(Object[] element) {
- return hashCode(element, element.length);
- }
-
- private int hashCode(Object[] element, int length) {
- int hash = 0;
- for (int i = length-1; i >= 0; i--)
- hash = Util.combineHashCodes(hash, element[i].hashCode());
- return hash & 0x7FFFFFFF;
- }
-
- public Object add(Object[] array) {
- int length = this.set.length;
- int index = hashCode(array) % length;
- int arrayLength = array.length;
- Object[] currentArray;
- while ((currentArray = this.set[index]) != null) {
- if (currentArray.length == arrayLength && Util.equalArraysOrNull(currentArray, array))
- return this.set[index] = array;
- if (++index == length) {
- index = 0;
- }
- }
- this.set[index] = array;
-
- // assumes the threshold is never equal to the size of the table
- if (++this.elementSize > threshold)
- rehash();
- return array;
- }
-
- public Object remove(Object[] array) {
- int length = this.set.length;
- int index = hashCode(array) % length;
- int arrayLength = array.length;
- Object[] currentArray;
- while ((currentArray = this.set[index]) != null) {
- if (currentArray.length == arrayLength && Util.equalArraysOrNull(currentArray, array)) {
- Object existing = this.set[index];
- this.elementSize--;
- this.set[index] = null;
- rehash();
- return existing;
- }
- if (++index == length) {
- index = 0;
- }
- }
- return null;
- }
-
- private void rehash() {
-
- HashSetOfArray newHashSet = new HashSetOfArray(elementSize * 2); // double the number of expected elements
- Object[] currentArray;
- for (int i = this.set.length; --i >= 0;)
- if ((currentArray = this.set[i]) != null)
- newHashSet.add(currentArray);
-
- this.set = newHashSet.set;
- this.threshold = newHashSet.threshold;
- }
-
- public int size() {
- return elementSize;
- }
-
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- Object[] element;
- for (int i = 0, length = this.set.length; i < length; i++)
- if ((element = this.set[i]) != null) {
- buffer.append('{');
- for (int j = 0, length2 = element.length; j < length2; j++) {
- buffer.append(element[j]);
- if (j != length2-1)
- buffer.append(", "); //$NON-NLS-1$
- }
- buffer.append("}"); //$NON-NLS-1$
- if (i != length-1)
- buffer.append('\n');
- }
- return buffer.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/HashtableOfArrayToObject.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/HashtableOfArrayToObject.java
deleted file mode 100644
index 2285f1d2..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/HashtableOfArrayToObject.java
+++ /dev/null
@@ -1,187 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.util;
-
-/**
- * Hashtable of {Object[] --> Object }
- */
-public final class HashtableOfArrayToObject implements Cloneable {
-
- // to avoid using Enumerations, walk the individual tables skipping nulls
- public Object[][] keyTable;
- public Object[] valueTable;
-
- public int elementSize; // number of elements in the table
- int threshold;
-
- public HashtableOfArrayToObject() {
- this(13);
- }
-
- public HashtableOfArrayToObject(int size) {
-
- this.elementSize = 0;
- this.threshold = size; // size represents the expected number of elements
- int extraRoom = (int) (size * 1.75f);
- if (this.threshold == extraRoom)
- extraRoom++;
- this.keyTable = new Object[extraRoom][];
- this.valueTable = new Object[extraRoom];
- }
-
- public Object clone() throws CloneNotSupportedException {
- HashtableOfArrayToObject result = (HashtableOfArrayToObject) super.clone();
- result.elementSize = this.elementSize;
- result.threshold = this.threshold;
-
- int length = this.keyTable.length;
- result.keyTable = new Object[length][];
- System.arraycopy(this.keyTable, 0, result.keyTable, 0, length);
-
- length = this.valueTable.length;
- result.valueTable = new Object[length];
- System.arraycopy(this.valueTable, 0, result.valueTable, 0, length);
- return result;
- }
-
- public boolean containsKey(Object[] key) {
- int length = this.keyTable.length;
- int index = hashCode(key) % length;
- int keyLength = key.length;
- Object[] currentKey;
- while ((currentKey = this.keyTable[index]) != null) {
- if (currentKey.length == keyLength && Util.equalArraysOrNull(currentKey, key))
- return true;
- if (++index == length) {
- index = 0;
- }
- }
- return false;
- }
-
- public Object get(Object[] key) {
- int length = this.keyTable.length;
- int index = hashCode(key) % length;
- int keyLength = key.length;
- Object[] currentKey;
- while ((currentKey = this.keyTable[index]) != null) {
- if (currentKey.length == keyLength && Util.equalArraysOrNull(currentKey, key))
- return this.valueTable[index];
- if (++index == length) {
- index = 0;
- }
- }
- return null;
- }
-
- public Object[] getKey(Object[] key, int keyLength) {
- int length = this.keyTable.length;
- int index = hashCode(key, keyLength) % length;
- Object[] currentKey;
- while ((currentKey = this.keyTable[index]) != null) {
- if (currentKey.length == keyLength && Util.equalArrays(currentKey, key, keyLength))
- return currentKey;
- if (++index == length) {
- index = 0;
- }
- }
- return null;
- }
-
- private int hashCode(Object[] element) {
- return hashCode(element, element.length);
- }
-
- private int hashCode(Object[] element, int length) {
- int hash = 0;
- for (int i = length-1; i >= 0; i--)
- hash = Util.combineHashCodes(hash, element[i].hashCode());
- return hash & 0x7FFFFFFF;
- }
-
- public Object put(Object[] key, Object value) {
- int length = this.keyTable.length;
- int index = hashCode(key) % length;
- int keyLength = key.length;
- Object[] currentKey;
- while ((currentKey = this.keyTable[index]) != null) {
- if (currentKey.length == keyLength && Util.equalArraysOrNull(currentKey, key))
- return this.valueTable[index] = value;
- if (++index == length) {
- index = 0;
- }
- }
- this.keyTable[index] = key;
- this.valueTable[index] = value;
-
- // assumes the threshold is never equal to the size of the table
- if (++this.elementSize > threshold)
- rehash();
- return value;
- }
-
- public Object removeKey(Object[] key) {
- int length = this.keyTable.length;
- int index = hashCode(key) % length;
- int keyLength = key.length;
- Object[] currentKey;
- while ((currentKey = this.keyTable[index]) != null) {
- if (currentKey.length == keyLength && Util.equalArraysOrNull(currentKey, key)) {
- Object value = this.valueTable[index];
- this.elementSize--;
- this.keyTable[index] = null;
- this.valueTable[index] = null;
- rehash();
- return value;
- }
- if (++index == length) {
- index = 0;
- }
- }
- return null;
- }
-
- private void rehash() {
-
- HashtableOfArrayToObject newHashtable = new HashtableOfArrayToObject(elementSize * 2); // double the number of expected elements
- Object[] currentKey;
- for (int i = this.keyTable.length; --i >= 0;)
- if ((currentKey = this.keyTable[i]) != null)
- newHashtable.put(currentKey, this.valueTable[i]);
-
- this.keyTable = newHashtable.keyTable;
- this.valueTable = newHashtable.valueTable;
- this.threshold = newHashtable.threshold;
- }
-
- public int size() {
- return elementSize;
- }
-
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- Object[] element;
- for (int i = 0, length = this.keyTable.length; i < length; i++)
- if ((element = this.keyTable[i]) != null) {
- buffer.append('{');
- for (int j = 0, length2 = element.length; j < length2; j++) {
- buffer.append(element[j]);
- if (j != length2-1)
- buffer.append(", "); //$NON-NLS-1$
- }
- buffer.append("} -> "); //$NON-NLS-1$
- buffer.append(this.valueTable[i]);
- if (i != length-1)
- buffer.append('\n');
- }
- return buffer.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ICacheEnumeration.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ICacheEnumeration.java
deleted file mode 100644
index 2ac54379..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ICacheEnumeration.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.util;
-
-import java.util.Enumeration;
-
-/**
- * The <code>ICacheEnumeration</code> is used to iterate over both the keys
- * and values in an LRUCache. The <code>getValue()</code> method returns the
- * value of the last key to be retrieved using <code>nextElement()</code>.
- * The <code>nextElement()</code> method must be called before the
- * <code>getValue()</code> method.
- *
- * <p>The iteration can be made efficient by making use of the fact that values in
- * the cache (instances of <code>LRUCacheEntry</code>), know their key. For this reason,
- * Hashtable lookups don't have to be made at each step of the iteration.
- *
- * <p>Modifications to the cache must not be performed while using the
- * enumeration. Doing so will lead to an illegal state.
- *
- * @see LRUCache
- */
-public interface ICacheEnumeration extends Enumeration {
- /**
- * Returns the value of the previously accessed key in the enumeration.
- * Must be called after a call to nextElement().
- *
- * @return Value of current cache entry
- */
- public Object getValue();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ILRUCacheable.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ILRUCacheable.java
deleted file mode 100644
index 48f5e949..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ILRUCacheable.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.util;
-
-/**
- * Types implementing this interface can occupy a variable amount of space
- * in an LRUCache. Cached items that do not implement this interface are
- * considered to occupy one unit of space.
- *
- * @see LRUCache
- */
-public interface ILRUCacheable {
- /**
- * Returns the space the receiver consumes in an LRU Cache. The default space
- * value is 1.
- *
- * @return int Amount of cache space taken by the receiver
- */
- public int getCacheFootprint();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/KeyKind.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/KeyKind.java
deleted file mode 100644
index dc2fe165..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/KeyKind.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.util;
-
-public class KeyKind extends BindingKeyParser {
-
- public static final int F_TYPE = 0x00001;
- public static final int F_METHOD = 0x00010;
- public static final int F_FIELD = 0x00011;
- public static final int F_TYPE_PARAMETER = 0x00100;
- public static final int F_LOCAL_VAR = 0x00101;
- public static final int F_MEMBER = 0x00110;
- public static final int F_LOCAL = 0x00111;
- public static final int F_PARAMETERIZED_TYPE = 0x01000;
- public static final int F_RAW_TYPE = 0x01001;
- public static final int F_WILDCARD_TYPE = 0x01010;
- public static final int F_PARAMETERIZED_METHOD = 0x01011;
- public static final int F_CAPTURE = 0x01111;
- public static final int F_CONSTRUCTOR = 0x10000;
-
- public int flags = 0;
- private KeyKind innerKeyKind;
-
- public KeyKind(BindingKeyParser parser) {
- super(parser);
- }
-
- public KeyKind(String key) {
- super(key);
- }
-
- public void consumeBaseType(char[] baseTypeSig) {
- this.flags |= F_TYPE;
- }
-
- public void consumeCapture(int position) {
- this.flags |= F_CAPTURE;
- }
-
- public void consumeField(char[] fieldName) {
- this.flags |= F_FIELD;
- }
-
- public void consumeLocalType(char[] uniqueKey) {
- this.flags |= F_LOCAL;
- }
-
- public void consumeLocalVar(char[] varName) {
- this.flags |= F_LOCAL_VAR;
- }
-
- public void consumeMemberType(char[] simpleTypeName) {
- this.flags |= F_MEMBER;
- }
-
- public void consumeMethod(char[] selector, char[] signature) {
- this.flags |= F_METHOD;
- if (selector.length == 0)
- this.flags |= F_CONSTRUCTOR;
- }
-
- public void consumeParameterizedGenericMethod() {
- this.flags |= F_PARAMETERIZED_METHOD;
- }
-
- public void consumeParameterizedType(char[] simpleTypeName, boolean isRaw) {
- this.flags |= isRaw ? F_RAW_TYPE : F_PARAMETERIZED_TYPE;
- }
-
- public void consumeParser(BindingKeyParser parser) {
- this.innerKeyKind = (KeyKind) parser;
- }
-
- public void consumeRawType() {
- this.flags |= F_RAW_TYPE;
- }
-
- public void consumeTopLevelType() {
- this.flags |= F_TYPE;
- }
-
- public void consumeTypeParameter(char[] typeParameterName) {
- this.flags |= F_TYPE_PARAMETER;
- }
-
- public void consumeTypeWithCapture() {
- this.flags = this.innerKeyKind.flags;
- }
-
- public void consumeWildCard(int kind) {
- this.flags |= F_WILDCARD_TYPE;
- }
-
- public BindingKeyParser newParser() {
- return new KeyKind(this);
- }
-}
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
deleted file mode 100644
index 488472f7..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/KeyToSignature.java
+++ /dev/null
@@ -1,194 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.util;
-
-import java.util.ArrayList;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-
-/*
- * Converts a binding key into a signature
- */
-public class KeyToSignature extends BindingKeyParser {
-
- public static final int SIGNATURE = 0;
- public static final int TYPE_ARGUMENTS = 1;
- public static final int DECLARING_TYPE = 2;
- public static final int THROWN_EXCEPTIONS = 3;
-
- public StringBuffer signature = new StringBuffer();
- private int kind;
- private ArrayList arguments = new ArrayList();
- private ArrayList thrownExceptions = new ArrayList();
- private int mainTypeStart = -1;
- private int mainTypeEnd;
- private int typeSigStart = -1;
-
- public static final char[] ObjectSignature = "Ljava/lang/Object;".toCharArray(); //$NON-NLS-1$
-
-
- public KeyToSignature(BindingKeyParser parser) {
- super(parser);
- this.kind = ((KeyToSignature) parser).kind;
- }
-
- public KeyToSignature(String key, int kind) {
- super(key);
- this.kind = kind;
- }
-
- public void consumeArrayDimension(char[] brakets) {
- this.signature.append(brakets);
- }
-
- public void consumeBaseType(char[] baseTypeSig) {
- this.typeSigStart = this.signature.length();
- this.signature.append(baseTypeSig);
- }
-
- public void consumeCapture(int position) {
- // behave as if it was a wildcard
- this.signature = ((KeyToSignature) this.arguments.get(0)).signature;
- }
-
- public void consumeLocalType(char[] uniqueKey) {
- this.signature = new StringBuffer();
- // remove trailing semi-colon as it is added later in comsumeType()
- uniqueKey = CharOperation.subarray(uniqueKey, 0, uniqueKey.length-1);
- CharOperation.replace(uniqueKey, '/', '.');
- this.signature.append(uniqueKey);
- }
-
- public void consumeMethod(char[] selector, char[] methodSignature) {
- this.arguments = new ArrayList();
- CharOperation.replace(methodSignature, '/', '.');
- switch(this.kind) {
- case SIGNATURE:
- this.signature = new StringBuffer();
- this.signature.append(methodSignature);
- break;
- }
- }
-
- public void consumeMemberType(char[] simpleTypeName) {
- this.signature.append('$');
- this.signature.append(simpleTypeName);
- }
-
- public void consumePackage(char[] pkgName) {
- this.signature.append(pkgName);
- }
-
- public void consumeParameterizedType(char[] simpleTypeName, boolean isRaw) {
- if (simpleTypeName != null) {
- // member type
- this.signature.append('.');
- this.signature.append(simpleTypeName);
- }
- if (!isRaw) {
- this.signature.append('<');
- int length = this.arguments.size();
- for (int i = 0; i < length; i++) {
- this.signature.append(((KeyToSignature) this.arguments.get(i)).signature);
- }
- this.signature.append('>');
- if (this.kind != TYPE_ARGUMENTS)
- this.arguments = new ArrayList();
- }
- }
-
- public void consumeParser(BindingKeyParser parser) {
- this.arguments.add(parser);
- }
-
- public void consumeField(char[] fieldName) {
- if (this.kind == SIGNATURE) {
- this.signature = ((KeyToSignature) this.arguments.get(0)).signature;
- }
- }
-
- public void consumeException() {
- int size = this.arguments.size();
- if (size > 0) {
- for (int i=0; i<size; i++) {
- this.thrownExceptions.add(((KeyToSignature) this.arguments.get(i)).signature.toString());
- }
- this.arguments = new ArrayList();
- }
- }
-
- public void consumeFullyQualifiedName(char[] fullyQualifiedName) {
- this.typeSigStart = this.signature.length();
- this.signature.append('L');
- this.signature.append(CharOperation.replaceOnCopy(fullyQualifiedName, '/', '.'));
- }
-
- public void consumeSecondaryType(char[] simpleTypeName) {
- this.signature.append('~');
- this.mainTypeStart = this.signature.lastIndexOf(".") + 1; //$NON-NLS-1$
- if (this.mainTypeStart == 0)
- this.mainTypeStart = 1; // default package
- this.mainTypeEnd = this.signature.length();
- this.signature.append(simpleTypeName);
- }
-
- public void consumeType() {
- // remove main type if needed
- if (this.mainTypeStart != -1) {
- this.signature.replace(this.mainTypeStart, this.mainTypeEnd, ""); //$NON-NLS-1$
- }
- this.signature.append(';');
- }
-
- public void consumeTypeVariable(char[] position, char[] typeVariableName) {
- this.signature = new StringBuffer();
- this.signature.append('T');
- this.signature.append(typeVariableName);
- this.signature.append(';');
- }
-
- public void consumeTypeWithCapture() {
- KeyToSignature keyToSignature = (KeyToSignature) this.arguments.get(0);
- this.signature = keyToSignature.signature;
- this.arguments = keyToSignature.arguments;
- this.thrownExceptions = keyToSignature.thrownExceptions;
- }
-
- public String[] getThrownExceptions() {
- int length = this.thrownExceptions.size();
- String[] result = new String[length];
- for (int i = 0; i < length; i++) {
- result[i] = (String) this.thrownExceptions.get(i);
- }
- return result;
- }
-
- public String[] getTypeArguments() {
- int length = this.arguments.size();
- String[] result = new String[length];
- for (int i = 0; i < length; i++) {
- result[i] = ((KeyToSignature) this.arguments.get(i)).signature.toString();
- }
- return result;
- }
-
- public BindingKeyParser newParser() {
- return new KeyToSignature(this);
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return this.signature.toString();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/LRUCache.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/LRUCache.java
deleted file mode 100644
index 73792502..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/LRUCache.java
+++ /dev/null
@@ -1,525 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.util;
-
-import java.text.NumberFormat;
-import java.util.Enumeration;
-import java.util.Hashtable;
-
-/**
- * The <code>LRUCache</code> is a hashtable that stores a finite number of elements.
- * When an attempt is made to add values to a full cache, the least recently used values
- * in the cache are discarded to make room for the new values as necessary.
- *
- * <p>The data structure is based on the LRU virtual memory paging scheme.
- *
- * <p>Objects can take up a variable amount of cache space by implementing
- * the <code>ILRUCacheable</code> interface.
- *
- * <p>This implementation is NOT thread-safe. Synchronization wrappers would
- * have to be added to ensure atomic insertions and deletions from the cache.
- *
- * @see org.eclipse.wst.jsdt.internal.core.util.ILRUCacheable
- */
-public class LRUCache implements Cloneable {
-
- /**
- * This type is used internally by the LRUCache to represent entries
- * stored in the cache.
- * It is static because it does not require a pointer to the cache
- * which contains it.
- *
- * @see LRUCache
- */
- protected static class LRUCacheEntry {
-
- /**
- * Hash table key
- */
- public Object _fKey;
-
- /**
- * Hash table value (an LRUCacheEntry object)
- */
- public Object _fValue;
-
- /**
- * Time value for queue sorting
- */
- public int _fTimestamp;
-
- /**
- * Cache footprint of this entry
- */
- public int _fSpace;
-
- /**
- * Previous entry in queue
- */
- public LRUCacheEntry _fPrevious;
-
- /**
- * Next entry in queue
- */
- public LRUCacheEntry _fNext;
-
- /**
- * Creates a new instance of the receiver with the provided values
- * for key, value, and space.
- */
- public LRUCacheEntry (Object key, Object value, int space) {
- _fKey = key;
- _fValue = value;
- _fSpace = space;
- }
-
- /**
- * Returns a String that represents the value of this object.
- */
- public String toString() {
-
- return "LRUCacheEntry [" + _fKey + "-->" + _fValue + "]"; //$NON-NLS-3$ //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
-
- /**
- * Amount of cache space used so far
- */
- protected int fCurrentSpace;
-
- /**
- * Maximum space allowed in cache
- */
- protected int fSpaceLimit;
-
- /**
- * Counter for handing out sequential timestamps
- */
- protected int fTimestampCounter;
-
- /**
- * Hash table for fast random access to cache entries
- */
- protected Hashtable fEntryTable;
-
- /**
- * Start of queue (most recently used entry)
- */
- protected LRUCacheEntry fEntryQueue;
-
- /**
- * End of queue (least recently used entry)
- */
- protected LRUCacheEntry fEntryQueueTail;
-
- /**
- * Default amount of space in the cache
- */
- protected static final int DEFAULT_SPACELIMIT = 100;
- /**
- * Creates a new cache. Size of cache is defined by
- * <code>DEFAULT_SPACELIMIT</code>.
- */
- public LRUCache() {
-
- this(DEFAULT_SPACELIMIT);
- }
- /**
- * Creates a new cache.
- * @param size Size of Cache
- */
- public LRUCache(int size) {
-
- fTimestampCounter = fCurrentSpace = 0;
- fEntryQueue = fEntryQueueTail = null;
- fEntryTable = new Hashtable(size);
- fSpaceLimit = size;
- }
- /**
- * Returns a new cache containing the same contents.
- *
- * @return New copy of object.
- */
- public Object clone() {
-
- LRUCache newCache = newInstance(fSpaceLimit);
- LRUCacheEntry qEntry;
-
- /* Preserve order of entries by copying from oldest to newest */
- qEntry = this.fEntryQueueTail;
- while (qEntry != null) {
- newCache.privateAdd (qEntry._fKey, qEntry._fValue, qEntry._fSpace);
- qEntry = qEntry._fPrevious;
- }
- return newCache;
- }
- public double fillingRatio() {
- return (fCurrentSpace) * 100.0 / fSpaceLimit;
- }
- /**
- * Flushes all entries from the cache.
- */
- public void flush() {
-
- fCurrentSpace = 0;
- LRUCacheEntry entry = fEntryQueueTail; // Remember last entry
- fEntryTable = new Hashtable(); // Clear it out
- fEntryQueue = fEntryQueueTail = null;
- while (entry != null) { // send deletion notifications in LRU order
- entry = entry._fPrevious;
- }
- }
- /**
- * Flushes the given entry from the cache. Does nothing if entry does not
- * exist in cache.
- *
- * @param key Key of object to flush
- */
- public void flush (Object key) {
-
- LRUCacheEntry entry;
-
- entry = (LRUCacheEntry) fEntryTable.get(key);
-
- /* If entry does not exist, return */
- if (entry == null) return;
-
- this.privateRemoveEntry (entry, false);
- }
- /**
- * Answers the value in the cache at the given key.
- * If the value is not in the cache, returns null
- *
- * @param key Hash table key of object to retrieve
- * @return Retreived object, or null if object does not exist
- */
- public Object get(Object key) {
-
- LRUCacheEntry entry = (LRUCacheEntry) fEntryTable.get(key);
- if (entry == null) {
- return null;
- }
-
- this.updateTimestamp (entry);
- return entry._fValue;
- }
- /**
- * Returns the amount of space that is current used in the cache.
- */
- public int getCurrentSpace() {
- return fCurrentSpace;
- }
- /**
- * Returns the maximum amount of space available in the cache.
- */
- public int getSpaceLimit() {
- return fSpaceLimit;
- }
- /**
- * Returns an Enumeration of the keys currently in the cache.
- */
- public Enumeration keys() {
-
- return fEntryTable.keys();
- }
- /**
- * Returns an enumeration that iterates over all the keys and values
- * currently in the cache.
- */
- public ICacheEnumeration keysAndValues() {
- return new ICacheEnumeration() {
-
- Enumeration fValues = fEntryTable.elements();
- LRUCacheEntry fEntry;
-
- public boolean hasMoreElements() {
- return fValues.hasMoreElements();
- }
-
- public Object nextElement() {
- fEntry = (LRUCacheEntry) fValues.nextElement();
- return fEntry._fKey;
- }
-
- public Object getValue() {
- if (fEntry == null) {
- throw new java.util.NoSuchElementException();
- }
- return fEntry._fValue;
- }
- };
- }
- /**
- * Ensures there is the specified amount of free space in the receiver,
- * by removing old entries if necessary. Returns true if the requested space was
- * made available, false otherwise.
- *
- * @param space Amount of space to free up
- */
- protected boolean makeSpace (int space) {
-
- int limit;
-
- limit = this.getSpaceLimit();
-
- /* if space is already available */
- if (fCurrentSpace + space <= limit) {
- return true;
- }
-
- /* if entry is too big for cache */
- if (space > limit) {
- return false;
- }
-
- /* Free up space by removing oldest entries */
- while (fCurrentSpace + space > limit && fEntryQueueTail != null) {
- this.privateRemoveEntry (fEntryQueueTail, false);
- }
- return true;
- }
- /**
- * Returns a new LRUCache instance
- */
- protected LRUCache newInstance(int size) {
- return new LRUCache(size);
- }
- /**
- * Answers the value in the cache at the given key.
- * If the value is not in the cache, returns null
- *
- * This function does not modify timestamps.
- */
- public Object peek(Object key) {
-
- LRUCacheEntry entry = (LRUCacheEntry) fEntryTable.get(key);
- if (entry == null) {
- return null;
- }
- return entry._fValue;
- }
- /**
- * Adds an entry for the given key/value/space.
- */
- protected void privateAdd (Object key, Object value, int space) {
-
- LRUCacheEntry entry;
-
- entry = new LRUCacheEntry(key, value, space);
- this.privateAddEntry (entry, false);
- }
- /**
- * Adds the given entry from the receiver.
- * @param shuffle Indicates whether we are just shuffling the queue
- * (in which case, the entry table is not modified).
- */
- protected void privateAddEntry (LRUCacheEntry entry, boolean shuffle) {
-
- if (!shuffle) {
- fEntryTable.put (entry._fKey, entry);
- fCurrentSpace += entry._fSpace;
- }
-
- entry._fTimestamp = fTimestampCounter++;
- entry._fNext = this.fEntryQueue;
- entry._fPrevious = null;
-
- if (fEntryQueue == null) {
- /* this is the first and last entry */
- fEntryQueueTail = entry;
- } else {
- fEntryQueue._fPrevious = entry;
- }
-
- fEntryQueue = entry;
- }
- /**
- * fallen off the bottom of the LRU queue.
- * Subclasses could over-ride this to implement a persistent cache below the LRU cache.
- */
- protected void privateNotifyDeletionFromCache(LRUCacheEntry entry) {
- // Default is NOP.
- }
- /**
- * Removes the entry from the entry queue.
- * @param shuffle indicates whether we are just shuffling the queue
- * (in which case, the entry table is not modified).
- */
- protected void privateRemoveEntry (LRUCacheEntry entry, boolean shuffle) {
-
- LRUCacheEntry previous, next;
-
- previous = entry._fPrevious;
- next = entry._fNext;
-
- if (!shuffle) {
- fEntryTable.remove(entry._fKey);
- fCurrentSpace -= entry._fSpace;
- }
-
- /* if this was the first entry */
- if (previous == null) {
- fEntryQueue = next;
- } else {
- previous._fNext = next;
- }
-
- /* if this was the last entry */
- if (next == null) {
- fEntryQueueTail = previous;
- } else {
- next._fPrevious = previous;
- }
- }
- /**
- * Sets the value in the cache at the given key. Returns the value.
- *
- * @param key Key of object to add.
- * @param value Value of object to add.
- * @return added value.
- */
- public Object put(Object key, Object value) {
-
- int newSpace, oldSpace, newTotal;
- LRUCacheEntry entry;
-
- /* Check whether there's an entry in the cache */
- newSpace = spaceFor(value);
- entry = (LRUCacheEntry) fEntryTable.get (key);
-
- if (entry != null) {
-
- /**
- * Replace the entry in the cache if it would not overflow
- * the cache. Otherwise flush the entry and re-add it so as
- * to keep cache within budget
- */
- oldSpace = entry._fSpace;
- newTotal = getCurrentSpace() - oldSpace + newSpace;
- if (newTotal <= getSpaceLimit()) {
- updateTimestamp (entry);
- entry._fValue = value;
- entry._fSpace = newSpace;
- this.fCurrentSpace = newTotal;
- return value;
- } else {
- privateRemoveEntry (entry, false);
- }
- }
- if (makeSpace(newSpace)) {
- privateAdd (key, value, newSpace);
- }
- return value;
- }
- /**
- * Removes and returns the value in the cache for the given key.
- * If the key is not in the cache, returns null.
- *
- * @param key Key of object to remove from cache.
- * @return Value removed from cache.
- */
- public Object removeKey (Object key) {
-
- LRUCacheEntry entry = (LRUCacheEntry) fEntryTable.get(key);
- if (entry == null) {
- return null;
- }
- Object value = entry._fValue;
- this.privateRemoveEntry (entry, false);
- return value;
- }
- /**
- * Sets the maximum amount of space that the cache can store
- *
- * @param limit Number of units of cache space
- */
- public void setSpaceLimit(int limit) {
- if (limit < fSpaceLimit) {
- makeSpace(fSpaceLimit - limit);
- }
- fSpaceLimit = limit;
- }
- /**
- * Returns the space taken by the given value.
- */
- protected int spaceFor (Object value) {
-
- if (value instanceof ILRUCacheable) {
- return ((ILRUCacheable) value).getCacheFootprint();
- } else {
- return 1;
- }
- }
- /**
- * Returns a String that represents the value of this object. This method
- * is for debugging purposes only.
- */
- public String toString() {
- return
- toStringFillingRation("LRUCache") + //$NON-NLS-1$
- toStringContents();
- }
-
- /**
- * Returns a String that represents the contents of this object. This method
- * is for debugging purposes only.
- */
- protected String toStringContents() {
- StringBuffer result = new StringBuffer();
- int length = fEntryTable.size();
- Object[] unsortedKeys = new Object[length];
- String[] unsortedToStrings = new String[length];
- Enumeration e = this.keys();
- for (int i = 0; i < length; i++) {
- Object key = e.nextElement();
- unsortedKeys[i] = key;
- unsortedToStrings[i] =
- (key instanceof org.eclipse.wst.jsdt.internal.core.JavaElement) ?
- ((org.eclipse.wst.jsdt.internal.core.JavaElement)key).getElementName() :
- key.toString();
- }
- ToStringSorter sorter = new ToStringSorter();
- sorter.sort(unsortedKeys, unsortedToStrings);
- for (int i = 0; i < length; i++) {
- String toString = sorter.sortedStrings[i];
- Object value = this.get(sorter.sortedObjects[i]);
- result.append(toString);
- result.append(" -> "); //$NON-NLS-1$
- result.append(value);
- result.append("\n"); //$NON-NLS-1$
- }
- return result.toString();
- }
-
- public String toStringFillingRation(String cacheName) {
- StringBuffer buffer = new StringBuffer(cacheName);
- buffer.append('[');
- buffer.append(getSpaceLimit());
- buffer.append("]: "); //$NON-NLS-1$
- buffer.append(NumberFormat.getInstance().format(fillingRatio()));
- buffer.append("% full"); //$NON-NLS-1$
- return buffer.toString();
- }
-
- /**
- * Updates the timestamp for the given entry, ensuring that the queue is
- * kept in correct order. The entry must exist
- */
- protected void updateTimestamp (LRUCacheEntry entry) {
-
- entry._fTimestamp = fTimestampCounter++;
- if (fEntryQueue != entry) {
- this.privateRemoveEntry (entry, true);
- this.privateAddEntry (entry, true);
- }
- return;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/MementoTokenizer.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/MementoTokenizer.java
deleted file mode 100644
index 2b006fb0..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/MementoTokenizer.java
+++ /dev/null
@@ -1,115 +0,0 @@
-/*******************************************************************************
- * 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
- * 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.internal.core.JavaElement;
-
-public class MementoTokenizer {
- private static final String COUNT = Character.toString(JavaElement.JEM_COUNT);
- private static final String JAVAPROJECT = Character.toString(JavaElement.JEM_JAVAPROJECT);
- private static final String PACKAGEFRAGMENTROOT = Character.toString(JavaElement.JEM_PACKAGEFRAGMENTROOT);
- private static final String PACKAGEFRAGMENT = Character.toString(JavaElement.JEM_PACKAGEFRAGMENT);
- private static final String FIELD = Character.toString(JavaElement.JEM_FIELD);
- private static final String METHOD = Character.toString(JavaElement.JEM_METHOD);
- private static final String INITIALIZER = Character.toString(JavaElement.JEM_INITIALIZER);
- private static final String COMPILATIONUNIT = Character.toString(JavaElement.JEM_COMPILATIONUNIT);
- private static final String CLASSFILE = Character.toString(JavaElement.JEM_CLASSFILE);
- private static final String TYPE = Character.toString(JavaElement.JEM_TYPE);
- private static final String PACKAGEDECLARATION = Character.toString(JavaElement.JEM_PACKAGEDECLARATION);
- private static final String IMPORTDECLARATION = Character.toString(JavaElement.JEM_IMPORTDECLARATION);
- private static final String LOCALVARIABLE = Character.toString(JavaElement.JEM_LOCALVARIABLE);
- private static final String TYPE_PARAMETER = Character.toString(JavaElement.JEM_TYPE_PARAMETER);
-
- private final char[] memento;
- private final int length;
- private int index = 0;
-
- public MementoTokenizer(String memento) {
- this.memento = memento.toCharArray();
- this.length = this.memento.length;
- }
-
- public boolean hasMoreTokens() {
- return this.index < this.length;
- }
-
- public String nextToken() {
- int start = this.index;
- StringBuffer buffer = null;
- switch (this.memento[this.index++]) {
- case JavaElement.JEM_ESCAPE:
- buffer = new StringBuffer();
- buffer.append(this.memento[this.index]);
- start = ++this.index;
- break;
- case JavaElement.JEM_COUNT:
- return COUNT;
- case JavaElement.JEM_JAVAPROJECT:
- return JAVAPROJECT;
- case JavaElement.JEM_PACKAGEFRAGMENTROOT:
- return PACKAGEFRAGMENTROOT;
- case JavaElement.JEM_PACKAGEFRAGMENT:
- return PACKAGEFRAGMENT;
- case JavaElement.JEM_FIELD:
- return FIELD;
- case JavaElement.JEM_METHOD:
- return METHOD;
- case JavaElement.JEM_INITIALIZER:
- return INITIALIZER;
- case JavaElement.JEM_COMPILATIONUNIT:
- return COMPILATIONUNIT;
- case JavaElement.JEM_CLASSFILE:
- return CLASSFILE;
- case JavaElement.JEM_TYPE:
- return TYPE;
- case JavaElement.JEM_PACKAGEDECLARATION:
- return PACKAGEDECLARATION;
- case JavaElement.JEM_IMPORTDECLARATION:
- return IMPORTDECLARATION;
- case JavaElement.JEM_LOCALVARIABLE:
- return LOCALVARIABLE;
- case JavaElement.JEM_TYPE_PARAMETER:
- return TYPE_PARAMETER;
- }
- loop: while (this.index < this.length) {
- switch (this.memento[this.index]) {
- case JavaElement.JEM_ESCAPE:
- if (buffer == null) buffer = new StringBuffer();
- buffer.append(this.memento, start, this.index - start);
- start = ++this.index;
- break;
- case JavaElement.JEM_COUNT:
- case JavaElement.JEM_JAVAPROJECT:
- case JavaElement.JEM_PACKAGEFRAGMENTROOT:
- case JavaElement.JEM_PACKAGEFRAGMENT:
- case JavaElement.JEM_FIELD:
- case JavaElement.JEM_METHOD:
- case JavaElement.JEM_INITIALIZER:
- case JavaElement.JEM_COMPILATIONUNIT:
- case JavaElement.JEM_CLASSFILE:
- case JavaElement.JEM_TYPE:
- case JavaElement.JEM_PACKAGEDECLARATION:
- case JavaElement.JEM_IMPORTDECLARATION:
- case JavaElement.JEM_LOCALVARIABLE:
- case JavaElement.JEM_TYPE_PARAMETER:
- break loop;
- }
- this.index++;
- }
- if (buffer != null) {
- buffer.append(this.memento, start, this.index - start);
- return buffer.toString();
- } else {
- return new String(this.memento, start, this.index - start);
- }
- }
-
-}
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
deleted file mode 100644
index 85f1bcd1..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/Messages.java
+++ /dev/null
@@ -1,268 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.util;
-
-import java.text.MessageFormat;
-
-import org.eclipse.osgi.util.NLS;
-
-public final class Messages extends NLS {
-
- private static final String BUNDLE_NAME = "org.eclipse.wst.jsdt.internal.core.util.messages";//$NON-NLS-1$
-
- private Messages() {
- // Do not instantiate
- }
-
- public static String hierarchy_nullProject;
- public static String hierarchy_nullRegion;
- public static String hierarchy_nullFocusType;
- public static String hierarchy_creating;
- public static String hierarchy_creatingOnType;
- public static String element_doesNotExist;
- public static String element_notOnClasspath;
- public static String element_invalidClassFileName;
- public static String element_reconciling;
- public static String element_attachingSource;
- public static String element_invalidResourceForProject;
- public static String element_nullName;
- public static String element_nullType;
- public static String element_illegalParent;
- public static String javamodel_initialization;
- public static String javamodel_building_after_upgrade;
- public static String javamodel_configuring;
- public static String javamodel_configuring_classpath_containers;
- public static String javamodel_configuring_searchengine;
- public static String javamodel_getting_build_state_number;
- public static String javamodel_refreshing_external_jars;
- public static String operation_needElements;
- public static String operation_needName;
- public static String operation_needPath;
- public static String operation_needAbsolutePath;
- public static String operation_needString;
- public static String operation_notSupported;
- public static String operation_cancelled;
- public static String operation_nullContainer;
- public static String operation_nullName;
- public static String operation_copyElementProgress;
- public static String operation_moveElementProgress;
- public static String operation_renameElementProgress;
- public static String operation_copyResourceProgress;
- public static String operation_moveResourceProgress;
- public static String operation_renameResourceProgress;
- public static String operation_createUnitProgress;
- public static String operation_createFieldProgress;
- public static String operation_createImportsProgress;
- public static String operation_createMethodProgress;
- public static String operation_createPackageProgress;
- public static String operation_createPackageFragmentProgress;
- public static String operation_createTypeProgress;
- public static String operation_deleteElementProgress;
- public static String operation_deleteResourceProgress;
- public static String operation_cannotRenameDefaultPackage;
- public static String operation_pathOutsideProject;
- public static String operation_sortelements;
- public static String workingCopy_commit;
- public static String build_preparingBuild;
- public static String build_readStateProgress;
- public static String build_saveStateProgress;
- public static String build_saveStateComplete;
- public static String build_readingDelta;
- public static String build_analyzingDeltas;
- public static String build_analyzingSources;
- public static String build_compiling;
- public static String build_foundHeader;
- public static String build_fixedHeader;
- public static String build_oneError;
- public static String build_oneWarning;
- public static String build_multipleErrors;
- public static String build_multipleWarnings;
- public static String build_done;
- public static String build_wrongFileFormat;
- public static String build_cannotSaveState;
- public static String build_cannotSaveStates;
- public static String build_initializationError;
- public static String build_serializationError;
-// public static String build_classFileCollision;
-// public static String build_duplicateClassFile;
-// public static String build_duplicateResource;
-// public static String build_inconsistentClassFile;
- public static String build_inconsistentProject;
- public static String build_incompleteClassPath;
- public static String build_missingSourceFile;
- public static String build_prereqProjectHasClasspathProblems;
- public static String build_prereqProjectMustBeRebuilt;
- public static String build_abortDueToClasspathProblems;
- public static String status_cannot_retrieve_attached_javadoc;
- public static String status_cannotUseDeviceOnPath;
- public static String status_coreException;
- public static String status_defaultPackageReadOnly;
- public static String status_evaluationError;
- public static String status_JDOMError;
- public static String status_IOException;
- public static String status_indexOutOfBounds;
- public static String status_invalidContents;
- public static String status_invalidDestination;
- public static String status_invalidName;
- public static String status_invalidPackage;
- public static String status_invalidPath;
- public static String status_invalidProject;
- public static String status_invalidResource;
- public static String status_invalidResourceType;
- public static String status_invalidSibling;
- public static String status_nameCollision;
- public static String status_noLocalContents;
- public static String status_OK;
- public static String status_readOnly;
- public static String status_targetException;
- public static String status_unknown_javadoc_format;
- public static String status_updateConflict;
- public static String classpath_buildPath;
- public static String classpath_cannotNestEntryInEntry;
- public static String classpath_cannotNestEntryInEntryNoExclusion;
- public static String classpath_cannotNestEntryInLibrary;
- public static String classpath_cannotReadClasspathFile;
- public static String classpath_cannotReferToItself;
- public static String classpath_closedProject;
- public static String classpath_cycle;
- public static String classpath_duplicateEntryPath;
- public static String classpath_illegalContainerPath;
- public static String classpath_illegalEntryInClasspathFile;
- public static String classpath_illegalLibraryPath;
- public static String classpath_illegalLibraryArchive;
- public static String classpath_illegalExternalFolder;
- public static String classpath_illegalProjectPath;
- public static String classpath_illegalSourceFolderPath;
- public static String classpath_illegalVariablePath;
- public static String classpath_invalidContainer;
- public static String classpath_mustEndWithSlash;
- public static String classpath_unboundContainerPath;
- public static String classpath_unboundLibrary;
- public static String classpath_unboundProject;
- public static String classpath_unboundSourceAttachment;
- public static String classpath_unboundSourceFolder;
- public static String classpath_unboundVariablePath;
- public static String classpath_unknownKind;
- public static String classpath_xmlFormatError;
- public static String classpath_disabledInclusionExclusionPatterns;
- public static String classpath_duplicateEntryExtraAttribute;
- public static String classpath_deprecated_variable;
- public static String file_notFound;
- public static String file_badFormat;
- public static String path_nullPath;
- public static String path_mustBeAbsolute;
- public static String cache_invalidLoadFactor;
- public static String savedState_jobName;
- public static String restrictedAccess_project;
- public static String restrictedAccess_library;
- public static String restrictedAccess_constructor_project;
- public static String restrictedAccess_constructor_library;
- public static String restrictedAccess_field_project;
- public static String restrictedAccess_field_library;
- public static String restrictedAccess_method_project;
- public static String restrictedAccess_method_library;
- public static String convention_unit_nullName;
- public static String convention_unit_notJavaName;
- public static String convention_classFile_nullName;
- public static String convention_classFile_notClassFileName;
- public static String convention_illegalIdentifier;
- public static String convention_import_nullImport;
- public static String convention_import_unqualifiedImport;
- public static String convention_type_nullName;
- public static String convention_type_nameWithBlanks;
- public static String convention_type_dollarName;
- public static String convention_type_lowercaseName;
- public static String convention_type_invalidName;
- public static String convention_package_nullName;
- public static String convention_package_emptyName;
- public static String convention_package_dotName;
- public static String convention_package_nameWithBlanks;
- public static String convention_package_consecutiveDotsName;
- public static String convention_package_uppercaseName;
- public static String dom_cannotDetail;
- public static String dom_nullTypeParameter;
- public static String dom_nullNameParameter;
- public static String dom_nullReturnType;
- public static String dom_nullExceptionType;
- public static String dom_mismatchArgNamesAndTypes;
- public static String dom_addNullChild;
- public static String dom_addIncompatibleChild;
- public static String dom_addChildWithParent;
- public static String dom_unableAddChild;
- public static String dom_addAncestorAsChild;
- public static String dom_addNullSibling;
- public static String dom_addSiblingBeforeRoot;
- public static String dom_addIncompatibleSibling;
- public static String dom_addSiblingWithParent;
- public static String dom_addAncestorAsSibling;
- public static String dom_addNullInterface;
- public static String dom_nullInterfaces;
- public static String importRewrite_processDescription;
- public static String correction_nullRequestor;
- public static String correction_nullUnit;
- public static String engine_searching;
- public static String engine_searching_indexing;
- public static String engine_searching_matching;
- public static String exception_wrongFormat;
- public static String process_name;
- public static String manager_filesToIndex;
- public static String manager_indexingInProgress;
- public static String converter_ConfiguringForJavaScript;
- public static String converter_ConfiguringForBrowser;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
-
- /**
- * Bind the given message's substitution locations with the given string values.
- *
- * @param message the message to be manipulated
- * @return the manipulated String
- */
- public static String bind(String message) {
- return bind(message, null);
- }
-
- /**
- * Bind the given message's substitution locations with the given string values.
- *
- * @param message the message to be manipulated
- * @param binding the object to be inserted into the message
- * @return the manipulated String
- */
- public static String bind(String message, Object binding) {
- return bind(message, new Object[] {binding});
- }
-
- /**
- * Bind the given message's substitution locations with the given string values.
- *
- * @param message the message to be manipulated
- * @param binding1 An object to be inserted into the message
- * @param binding2 A second object to be inserted into the message
- * @return the manipulated String
- */
- public static String bind(String message, Object binding1, Object binding2) {
- return bind(message, new Object[] {binding1, binding2});
- }
-
- /**
- * Bind the given message's substitution locations with the given string values.
- *
- * @param message the message to be manipulated
- * @param bindings An array of objects to be inserted into the message
- * @return the manipulated String
- */
- public static String bind(String message, Object[] bindings) {
- return MessageFormat.format(message, bindings);
- }
-}
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
deleted file mode 100644
index 66fd6eb0..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/PublicScanner.java
+++ /dev/null
@@ -1,4245 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.util;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.compiler.IScanner;
-import org.eclipse.wst.jsdt.core.compiler.ITerminalSymbols;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.internal.compiler.CompilationResult;
-import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants;
-import org.eclipse.wst.jsdt.internal.compiler.parser.NLSTag;
-import org.eclipse.wst.jsdt.internal.compiler.parser.ScannerHelper;
-import org.eclipse.wst.jsdt.internal.compiler.util.Messages;
-import org.eclipse.wst.jsdt.internal.compiler.util.Util;
-
-public class PublicScanner implements IScanner, ITerminalSymbols {
-
- //public int newIdentCount = 0;
-
- /* APIs ares
- - getNextToken() which return the current type of the token
- (this value is not memorized by the scanner)
- - getCurrentTokenSource() which provides with the token "REAL" source
- (aka all unicode have been transformed into a correct char)
- - sourceStart gives the position into the stream
- - currentPosition-1 gives the sourceEnd position into the stream
- */
- public long sourceLevel;
- public long complianceLevel;
-
- // 1.4 feature
- public boolean useAssertAsAnIndentifier = false;
- //flag indicating if processed source contains occurrences of keyword assert
- public boolean containsAssertKeyword = false;
-
- // 1.5 feature
- public boolean useEnumAsAnIndentifier = false;
-
- public boolean recordLineSeparator = false;
- public char currentCharacter;
- public int startPosition;
- public int currentPosition;
- public int initialPosition, eofPosition;
- // after this position eof are generated instead of real token from the source
-
- public boolean tokenizeComments = false;
- public boolean tokenizeWhiteSpace = false;
-
- //source should be viewed as a window (aka a part)
- //of a entire very large stream
- public char source[];
-
- //unicode support
- public char[] withoutUnicodeBuffer;
- public int withoutUnicodePtr; //when == 0 ==> no unicode in the current token
- public boolean unicodeAsBackSlash = false;
-
- public boolean scanningFloatLiteral = false;
-
- //support for /** comments
- public final static int COMMENT_ARRAYS_SIZE = 30;
- public int[] commentStops = new int[COMMENT_ARRAYS_SIZE];
- public int[] commentStarts = new int[COMMENT_ARRAYS_SIZE];
- public int[] commentTagStarts = new int[COMMENT_ARRAYS_SIZE];
- public int commentPtr = -1; // no comment test with commentPtr value -1
- protected int lastCommentLinePosition = -1;
-
- // task tag support
- public char[][] foundTaskTags = null;
- public char[][] foundTaskMessages;
- public char[][] foundTaskPriorities = null;
- public int[][] foundTaskPositions;
- public int foundTaskCount = 0;
- public char[][] taskTags = null;
- public char[][] taskPriorities = null;
- public boolean isTaskCaseSensitive = true;
-
- //diet parsing support - jump over some method body when requested
- public boolean diet = false;
-
- //support for the poor-line-debuggers ....
- //remember the position of the cr/lf
- public int[] lineEnds = new int[250];
- public int linePtr = -1;
- public boolean wasAcr = false;
-
- public static final String END_OF_SOURCE = "End_Of_Source"; //$NON-NLS-1$
-
- public static final String INVALID_HEXA = "Invalid_Hexa_Literal"; //$NON-NLS-1$
- public static final String INVALID_OCTAL = "Invalid_Octal_Literal"; //$NON-NLS-1$
- public static final String INVALID_CHARACTER_CONSTANT = "Invalid_Character_Constant"; //$NON-NLS-1$
- public static final String INVALID_ESCAPE = "Invalid_Escape"; //$NON-NLS-1$
- public static final String INVALID_INPUT = "Invalid_Input"; //$NON-NLS-1$
- public static final String INVALID_UNICODE_ESCAPE = "Invalid_Unicode_Escape"; //$NON-NLS-1$
- public static final String INVALID_FLOAT = "Invalid_Float_Literal"; //$NON-NLS-1$
- public static final String INVALID_LOW_SURROGATE = "Invalid_Low_Surrogate"; //$NON-NLS-1$
- public static final String INVALID_HIGH_SURROGATE = "Invalid_High_Surrogate"; //$NON-NLS-1$
-
- public static final String NULL_SOURCE_STRING = "Null_Source_String"; //$NON-NLS-1$
- public static final String UNTERMINATED_STRING = "Unterminated_String"; //$NON-NLS-1$
- public static final String UNTERMINATED_COMMENT = "Unterminated_Comment"; //$NON-NLS-1$
- public static final String INVALID_CHAR_IN_STRING = "Invalid_Char_In_String"; //$NON-NLS-1$
- public static final String INVALID_DIGIT = "Invalid_Digit"; //$NON-NLS-1$
- private static final int[] EMPTY_LINE_ENDS = Util.EMPTY_INT_ARRAY;
-
- //----------------optimized identifier managment------------------
- static final char[] charArray_a = new char[] {'a'},
- charArray_b = new char[] {'b'},
- charArray_c = new char[] {'c'},
- charArray_d = new char[] {'d'},
- charArray_e = new char[] {'e'},
- charArray_f = new char[] {'f'},
- charArray_g = new char[] {'g'},
- charArray_h = new char[] {'h'},
- charArray_i = new char[] {'i'},
- charArray_j = new char[] {'j'},
- charArray_k = new char[] {'k'},
- charArray_l = new char[] {'l'},
- charArray_m = new char[] {'m'},
- charArray_n = new char[] {'n'},
- charArray_o = new char[] {'o'},
- charArray_p = new char[] {'p'},
- charArray_q = new char[] {'q'},
- charArray_r = new char[] {'r'},
- charArray_s = new char[] {'s'},
- charArray_t = new char[] {'t'},
- charArray_u = new char[] {'u'},
- charArray_v = new char[] {'v'},
- charArray_w = new char[] {'w'},
- charArray_x = new char[] {'x'},
- charArray_y = new char[] {'y'},
- charArray_z = new char[] {'z'};
-
- static final char[] initCharArray =
- new char[] {'\u0000', '\u0000', '\u0000', '\u0000', '\u0000', '\u0000'};
- static final int TableSize = 30, InternalTableSize = 6; //30*6 =210 entries
-
- public static final int OptimizedLength = 7;
- public /*static*/ final char[][][][] charArray_length =
- new char[OptimizedLength][TableSize][InternalTableSize][];
- // support for detecting non-externalized string literals
- public static final char[] TAG_PREFIX= "//$NON-NLS-".toCharArray(); //$NON-NLS-1$
- public static final int TAG_PREFIX_LENGTH= TAG_PREFIX.length;
- public static final char TAG_POSTFIX= '$';
- public static final int TAG_POSTFIX_LENGTH= 1;
- private NLSTag[] nlsTags = null;
- protected int nlsTagsPtr;
- public boolean checkNonExternalizedStringLiterals;
-
- // generic support
- public boolean returnOnlyGreater = false;
-
- /*static*/ {
- for (int i = 0; i < 6; i++) {
- for (int j = 0; j < TableSize; j++) {
- for (int k = 0; k < InternalTableSize; k++) {
- this.charArray_length[i][j][k] = initCharArray;
- }
- }
- }
- }
- /*static*/ int newEntry2 = 0,
- newEntry3 = 0,
- newEntry4 = 0,
- newEntry5 = 0,
- newEntry6 = 0;
- public boolean insideRecovery = false;
-
- protected int currentToken;
-
- public static final int RoundBracket = 0;
- public static final int SquareBracket = 1;
- public static final int CurlyBracket = 2;
- public static final int BracketKinds = 3;
-
- // extended unicode support
- public static final int LOW_SURROGATE_MIN_VALUE = 0xDC00;
- public static final int HIGH_SURROGATE_MIN_VALUE = 0xD800;
- public static final int HIGH_SURROGATE_MAX_VALUE = 0xDBFF;
- public static final int LOW_SURROGATE_MAX_VALUE = 0xDFFF;
-
-public PublicScanner() {
- this(false /*comment*/, false /*whitespace*/, false /*nls*/, ClassFileConstants.JDK1_3 /*sourceLevel*/, null/*taskTag*/, null/*taskPriorities*/, true /*taskCaseSensitive*/);
-}
-
-public PublicScanner(
- boolean tokenizeComments,
- boolean tokenizeWhiteSpace,
- boolean checkNonExternalizedStringLiterals,
- long sourceLevel,
- long complianceLevel,
- char[][] taskTags,
- char[][] taskPriorities,
- boolean isTaskCaseSensitive) {
-
- this.eofPosition = Integer.MAX_VALUE;
- this.tokenizeComments = tokenizeComments;
- this.tokenizeWhiteSpace = tokenizeWhiteSpace;
- this.sourceLevel = sourceLevel;
- this.complianceLevel = complianceLevel;
- this.checkNonExternalizedStringLiterals = checkNonExternalizedStringLiterals;
- this.taskTags = taskTags;
- this.taskPriorities = taskPriorities;
- this.isTaskCaseSensitive = isTaskCaseSensitive;
-}
-
-public PublicScanner(
- boolean tokenizeComments,
- boolean tokenizeWhiteSpace,
- boolean checkNonExternalizedStringLiterals,
- long sourceLevel,
- char[][] taskTags,
- char[][] taskPriorities,
- boolean isTaskCaseSensitive) {
-
- this(
- tokenizeComments,
- tokenizeWhiteSpace,
- checkNonExternalizedStringLiterals,
- sourceLevel,
- sourceLevel,
- taskTags,
- taskPriorities,
- isTaskCaseSensitive);
-}
-
-public final boolean atEnd() {
- // This code is not relevant if source is
- // Only a part of the real stream input
-
- return this.eofPosition <= this.currentPosition;
-}
-
-// chech presence of task: tags
-// TODO (frederic) see if we need to take unicode characters into account...
-public void checkTaskTag(int commentStart, int commentEnd) throws InvalidInputException {
- char[] src = this.source;
-
- // only look for newer task: tags
- if (this.foundTaskCount > 0
- && this.foundTaskPositions[this.foundTaskCount - 1][0] >= commentStart) {
- return;
- }
- int foundTaskIndex = this.foundTaskCount;
- char previous = src[commentStart+1]; // should be '*' or '/'
- for (
- int i = commentStart + 2; i < commentEnd && i < this.eofPosition; i++) {
- char[] tag = null;
- char[] priority = null;
- // check for tag occurrence only if not ambiguous with javadoc tag
- if (previous != '@') {
- nextTag : for (int itag = 0; itag < this.taskTags.length; itag++) {
- tag = this.taskTags[itag];
- int tagLength = tag.length;
- if (tagLength == 0) continue nextTag;
-
- // ensure tag is not leaded with letter if tag starts with a letter
- if (ScannerHelper.isJavaIdentifierStart(tag[0])) {
- if (ScannerHelper.isJavaIdentifierPart(previous)) {
- continue nextTag;
- }
- }
-
- for (int t = 0; t < tagLength; t++) {
- char sc, tc;
- int x = i+t;
- if (x >= this.eofPosition || x >= commentEnd) continue nextTag;
- if ((sc = src[i + t]) != (tc = tag[t])) { // case sensitive check
- if (this.isTaskCaseSensitive || (ScannerHelper.toLowerCase(sc) != ScannerHelper.toLowerCase(tc))) { // case insensitive check
- continue nextTag;
- }
- }
- }
- // ensure tag is not followed with letter if tag finishes with a letter
- if (i+tagLength < commentEnd && ScannerHelper.isJavaIdentifierPart(src[i+tagLength-1])) {
- if (ScannerHelper.isJavaIdentifierPart(src[i + tagLength]))
- continue nextTag;
- }
- if (this.foundTaskTags == null) {
- this.foundTaskTags = new char[5][];
- this.foundTaskMessages = new char[5][];
- this.foundTaskPriorities = new char[5][];
- this.foundTaskPositions = new int[5][];
- } else if (this.foundTaskCount == this.foundTaskTags.length) {
- System.arraycopy(this.foundTaskTags, 0, this.foundTaskTags = new char[this.foundTaskCount * 2][], 0, this.foundTaskCount);
- System.arraycopy(this.foundTaskMessages, 0, this.foundTaskMessages = new char[this.foundTaskCount * 2][], 0, this.foundTaskCount);
- System.arraycopy(this.foundTaskPriorities, 0, this.foundTaskPriorities = new char[this.foundTaskCount * 2][], 0, this.foundTaskCount);
- System.arraycopy(this.foundTaskPositions, 0, this.foundTaskPositions = new int[this.foundTaskCount * 2][], 0, this.foundTaskCount);
- }
-
- priority = this.taskPriorities != null && itag < this.taskPriorities.length
- ? this.taskPriorities[itag]
- : null;
-
- this.foundTaskTags[this.foundTaskCount] = tag;
- this.foundTaskPriorities[this.foundTaskCount] = priority;
- this.foundTaskPositions[this.foundTaskCount] = new int[] { i, i + tagLength - 1 };
- this.foundTaskMessages[this.foundTaskCount] = CharOperation.NO_CHAR;
- this.foundTaskCount++;
- i += tagLength - 1; // will be incremented when looping
- break nextTag;
- }
- }
- previous = src[i];
- }
- boolean containsEmptyTask = false;
- for (int i = foundTaskIndex; i < this.foundTaskCount; i++) {
- // retrieve message start and end positions
- int msgStart = this.foundTaskPositions[i][0] + this.foundTaskTags[i].length;
- int max_value = i + 1 < this.foundTaskCount
- ? this.foundTaskPositions[i + 1][0] - 1
- : commentEnd - 1;
- // at most beginning of next task
- if (max_value < msgStart) {
- max_value = msgStart; // would only occur if tag is before EOF.
- }
- int end = -1;
- char c;
- for (int j = msgStart; j < max_value; j++) {
- if ((c = src[j]) == '\n' || c == '\r') {
- end = j - 1;
- break;
- }
- }
- if (end == -1) {
- for (int j = max_value; j > msgStart; j--) {
- if ((c = src[j]) == '*') {
- end = j - 1;
- break;
- }
- }
- if (end == -1)
- end = max_value;
- }
- if (msgStart == end) {
- // if the description is empty, we might want to see if two tags are not sharing the same message
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=110797
- containsEmptyTask = true;
- continue;
- }
- // trim the message
- while (CharOperation.isWhitespace(src[end]) && msgStart <= end)
- end--;
- while (CharOperation.isWhitespace(src[msgStart]) && msgStart <= end)
- msgStart++;
- // update the end position of the task
- this.foundTaskPositions[i][1] = end;
- // get the message source
- final int messageLength = end - msgStart + 1;
- char[] message = new char[messageLength];
- System.arraycopy(src, msgStart, message, 0, messageLength);
- this.foundTaskMessages[i] = message;
- }
- if (containsEmptyTask) {
- for (int i = foundTaskIndex, max = this.foundTaskCount; i < max; i++) {
- if (this.foundTaskMessages[i].length == 0) {
- loop: for (int j = i + 1; j < max; j++) {
- if (this.foundTaskMessages[j].length != 0) {
- this.foundTaskMessages[i] = this.foundTaskMessages[j];
- this.foundTaskPositions[i][1] = this.foundTaskPositions[j][1];
- break loop;
- }
- }
- }
- }
- }
-}
-
-public char[] getCurrentIdentifierSource() {
- //return the token REAL source (aka unicodes are precomputed)
-
- char[] result;
- if (this.withoutUnicodePtr != 0) {
- //0 is used as a fast test flag so the real first char is in position 1
- System.arraycopy(
- this.withoutUnicodeBuffer,
- 1,
- result = new char[this.withoutUnicodePtr],
- 0,
- this.withoutUnicodePtr);
- } else {
- int length = this.currentPosition - this.startPosition;
- if (length == this.eofPosition) return this.source;
- switch (length) { // see OptimizedLength
- case 1 :
- return optimizedCurrentTokenSource1();
- case 2 :
- return optimizedCurrentTokenSource2();
- case 3 :
- return optimizedCurrentTokenSource3();
- case 4 :
- return optimizedCurrentTokenSource4();
- case 5 :
- return optimizedCurrentTokenSource5();
- case 6 :
- return optimizedCurrentTokenSource6();
- }
- //no optimization
- System.arraycopy(this.source, this.startPosition, result = new char[length], 0, length);
- }
- //newIdentCount++;
- return result;
-}
-public int getCurrentTokenEndPosition(){
- return this.currentPosition - 1;
-}
-public char[] getCurrentTokenSource() {
- // Return the token REAL source (aka unicodes are precomputed)
-
- char[] result;
- if (this.withoutUnicodePtr != 0)
- // 0 is used as a fast test flag so the real first char is in position 1
- System.arraycopy(
- this.withoutUnicodeBuffer,
- 1,
- result = new char[this.withoutUnicodePtr],
- 0,
- this.withoutUnicodePtr);
- else {
- int length;
- System.arraycopy(
- this.source,
- this.startPosition,
- result = new char[length = this.currentPosition - this.startPosition],
- 0,
- length);
- }
- return result;
-}
-public final String getCurrentTokenString() {
- // Return current token as a string
-
- if (this.withoutUnicodePtr != 0) {
- // 0 is used as a fast test flag so the real first char is in position 1
- return new String(
- this.withoutUnicodeBuffer,
- 1,
- this.withoutUnicodePtr);
- }
- return new String(
- this.source,
- this.startPosition,
- this.currentPosition - this.startPosition);
-}
-public char[] getCurrentTokenSourceString() {
- //return the token REAL source (aka unicodes are precomputed).
- //REMOVE the two " that are at the beginning and the end.
-
- char[] result;
- if (this.withoutUnicodePtr != 0)
- //0 is used as a fast test flag so the real first char is in position 1
- System.arraycopy(this.withoutUnicodeBuffer, 2,
- //2 is 1 (real start) + 1 (to jump over the ")
- result = new char[this.withoutUnicodePtr - 2], 0, this.withoutUnicodePtr - 2);
- else {
- int length;
- System.arraycopy(
- this.source,
- this.startPosition + 1,
- result = new char[length = this.currentPosition - this.startPosition - 2],
- 0,
- length);
- }
- return result;
-}
-public final String getCurrentStringLiteral() {
- //return the token REAL source (aka unicodes are precomputed).
- //REMOVE the two " that are at the beginning and the end.
-
- if (this.withoutUnicodePtr != 0)
- //0 is used as a fast test flag so the real first char is in position 1
- //2 is 1 (real start) + 1 (to jump over the ")
- return new String(this.withoutUnicodeBuffer, 2, this.withoutUnicodePtr - 2);
- else {
- return new String(this.source, this.startPosition + 1, this.currentPosition - this.startPosition - 2);
- }
-}
-public final char[] getRawTokenSource() {
- int length = this.currentPosition - this.startPosition;
- char[] tokenSource = new char[length];
- System.arraycopy(this.source, this.startPosition, tokenSource, 0, length);
- return tokenSource;
-}
-
-public final char[] getRawTokenSourceEnd() {
- int length = this.eofPosition - this.currentPosition - 1;
- char[] sourceEnd = new char[length];
- System.arraycopy(this.source, this.currentPosition, sourceEnd, 0, length);
- return sourceEnd;
-}
-
-public int getCurrentTokenStartPosition(){
- return this.startPosition;
-}
-/*
- * Search the source position corresponding to the end of a given line number
- *
- * Line numbers are 1-based, and relative to the scanner initialPosition.
- * Character positions are 0-based.
- *
- * In case the given line number is inconsistent, answers -1.
- */
-public final int getLineEnd(int lineNumber) {
-
- if (this.lineEnds == null || this.linePtr == -1)
- return -1;
- if (lineNumber > this.lineEnds.length+1)
- return -1;
- if (lineNumber <= 0)
- return -1;
- if (lineNumber == this.lineEnds.length + 1)
- return this.eofPosition;
- return this.lineEnds[lineNumber-1]; // next line start one character behind the lineEnd of the previous line
-}
-
-public final int[] getLineEnds() {
- //return a bounded copy of this.lineEnds
- if (this.linePtr == -1) {
- return EMPTY_LINE_ENDS;
- }
- int[] copy;
- System.arraycopy(this.lineEnds, 0, copy = new int[this.linePtr + 1], 0, this.linePtr + 1);
- return copy;
-}
-
-/**
- * Search the source position corresponding to the beginning of a given line number
- *
- * Line numbers are 1-based, and relative to the scanner initialPosition.
- * Character positions are 0-based.
- *
- * e.g. getLineStart(1) --> 0 indicates that the first line starts at character 0.
- *
- * In case the given line number is inconsistent, answers -1.
- *
- * @param lineNumber int
- * @return int
- */
-public final int getLineStart(int lineNumber) {
-
- if (this.lineEnds == null || this.linePtr == -1)
- return -1;
- if (lineNumber > this.lineEnds.length + 1)
- return -1;
- if (lineNumber <= 0)
- return -1;
-
- if (lineNumber == 1)
- return this.initialPosition;
- return this.lineEnds[lineNumber-2]+1; // next line start one character behind the lineEnd of the previous line
-}
-public final int getNextChar() {
- try {
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- } else {
- this.unicodeAsBackSlash = false;
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
- return this.currentCharacter;
- } catch (IndexOutOfBoundsException e) {
- return -1;
- } catch(InvalidInputException e) {
- return -1;
- }
-}
-public final int getNextCharWithBoundChecks() {
- if (this.currentPosition >= this.eofPosition) {
- return -1;
- }
- this.currentCharacter = this.source[this.currentPosition++];
- if (this.currentPosition >= this.eofPosition) {
- this.unicodeAsBackSlash = false;
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- return this.currentCharacter;
- }
- if (this.currentCharacter == '\\' && this.source[this.currentPosition] == 'u') {
- try {
- getNextUnicodeChar();
- } catch (InvalidInputException e) {
- return -1;
- }
- } else {
- this.unicodeAsBackSlash = false;
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
- return this.currentCharacter;
-}
-public final boolean getNextChar(char testedChar) {
- //BOOLEAN
- //handle the case of unicode.
- //when a unicode appears then we must use a buffer that holds char internal values
- //At the end of this method currentCharacter holds the new visited char
- //and currentPosition points right next after it
- //Both previous lines are true if the currentCharacter is == to the testedChar
- //On false, no side effect has occured.
-
- //ALL getNextChar.... ARE OPTIMIZED COPIES
-
- if (this.currentPosition >= this.eofPosition) { // handle the obvious case upfront
- this.unicodeAsBackSlash = false;
- return false;
- }
-
- int temp = this.currentPosition;
- try {
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- if (this.currentCharacter != testedChar) {
- this.currentPosition = temp;
- this.withoutUnicodePtr--;
- return false;
- }
- return true;
- } //-------------end unicode traitement--------------
- else {
- if (this.currentCharacter != testedChar) {
- this.currentPosition = temp;
- return false;
- }
- this.unicodeAsBackSlash = false;
- if (this.withoutUnicodePtr != 0)
- unicodeStore();
- return true;
- }
- } catch (IndexOutOfBoundsException e) {
- this.unicodeAsBackSlash = false;
- this.currentPosition = temp;
- return false;
- } catch(InvalidInputException e) {
- this.unicodeAsBackSlash = false;
- this.currentPosition = temp;
- return false;
- }
-}
-public final int getNextChar(char testedChar1, char testedChar2) {
- //INT 0 : testChar1 \\\\///\\\\ 1 : testedChar2 \\\\///\\\\ -1 : others
- //test can be done with (x==0) for the first and (x>0) for the second
- //handle the case of unicode.
- //when a unicode appears then we must use a buffer that holds char internal values
- //At the end of this method currentCharacter holds the new visited char
- //and currentPosition points right next after it
- //Both previous lines are true if the currentCharacter is == to the testedChar1/2
- //On false, no side effect has occured.
-
- //ALL getNextChar.... ARE OPTIMIZED COPIES
- if (this.currentPosition >= this.eofPosition) // handle the obvious case upfront
- return -1;
-
- int temp = this.currentPosition;
- try {
- int result;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- if (this.currentCharacter == testedChar1) {
- result = 0;
- } else if (this.currentCharacter == testedChar2) {
- result = 1;
- } else {
- this.currentPosition = temp;
- this.withoutUnicodePtr--;
- result = -1;
- }
- return result;
- } else {
- if (this.currentCharacter == testedChar1) {
- result = 0;
- } else if (this.currentCharacter == testedChar2) {
- result = 1;
- } else {
- this.currentPosition = temp;
- return -1;
- }
-
- if (this.withoutUnicodePtr != 0)
- unicodeStore();
- return result;
- }
- } catch (IndexOutOfBoundsException e) {
- this.currentPosition = temp;
- return -1;
- } catch(InvalidInputException e) {
- this.currentPosition = temp;
- return -1;
- }
-}
-public final boolean getNextCharAsDigit() throws InvalidInputException {
- //BOOLEAN
- //handle the case of unicode.
- //when a unicode appears then we must use a buffer that holds char internal values
- //At the end of this method currentCharacter holds the new visited char
- //and currentPosition points right next after it
- //Both previous lines are true if the currentCharacter is a digit
- //On false, no side effect has occured.
-
- //ALL getNextChar.... ARE OPTIMIZED COPIES
- if (this.currentPosition >= this.eofPosition) // handle the obvious case upfront
- return false;
-
- int temp = this.currentPosition;
- try {
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- if (!ScannerHelper.isDigit(this.currentCharacter)) {
- this.currentPosition = temp;
- this.withoutUnicodePtr--;
- return false;
- }
- return true;
- } else {
- if (!ScannerHelper.isDigit(this.currentCharacter)) {
- this.currentPosition = temp;
- return false;
- }
- if (this.withoutUnicodePtr != 0)
- unicodeStore();
- return true;
- }
- } catch (IndexOutOfBoundsException e) {
- this.currentPosition = temp;
- return false;
- } catch(InvalidInputException e) {
- this.currentPosition = temp;
- return false;
- }
-}
-public final boolean getNextCharAsDigit(int radix) {
- //BOOLEAN
- //handle the case of unicode.
- //when a unicode appears then we must use a buffer that holds char internal values
- //At the end of this method currentCharacter holds the new visited char
- //and currentPosition points right next after it
- //Both previous lines are true if the currentCharacter is a digit base on radix
- //On false, no side effect has occured.
-
- //ALL getNextChar.... ARE OPTIMIZED COPIES
- if (this.currentPosition >= this.eofPosition) // handle the obvious case upfront
- return false;
-
- int temp = this.currentPosition;
- try {
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- if (ScannerHelper.digit(this.currentCharacter, radix) == -1) {
- this.currentPosition = temp;
- this.withoutUnicodePtr--;
- return false;
- }
- return true;
- } else {
- if (ScannerHelper.digit(this.currentCharacter, radix) == -1) {
- this.currentPosition = temp;
- return false;
- }
- if (this.withoutUnicodePtr != 0)
- unicodeStore();
- return true;
- }
- } catch (IndexOutOfBoundsException e) {
- this.currentPosition = temp;
- return false;
- } catch(InvalidInputException e) {
- this.currentPosition = temp;
- return false;
- }
-}
-public boolean getNextCharAsJavaIdentifierPartWithBoundCheck() {
- //BOOLEAN
- //handle the case of unicode.
- //when a unicode appears then we must use a buffer that holds char internal values
- //At the end of this method currentCharacter holds the new visited char
- //and currentPosition points right next after it
- //Both previous lines are true if the currentCharacter is a JavaIdentifierPart
- //On false, no side effect has occured.
-
- //ALL getNextChar.... ARE OPTIMIZED COPIES
- int pos = this.currentPosition;
- if (pos >= this.eofPosition) // handle the obvious case upfront
- return false;
-
- int temp2 = this.withoutUnicodePtr;
- try {
- boolean unicode = false;
- this.currentCharacter = this.source[this.currentPosition++];
- if (this.currentPosition < this.eofPosition) {
- if (this.currentCharacter == '\\' && this.source[this.currentPosition] == 'u') {
- getNextUnicodeChar();
- unicode = true;
- }
- }
- char c = this.currentCharacter;
- boolean isJavaIdentifierPart = false;
- if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) {
- if (this.complianceLevel < ClassFileConstants.JDK1_5) {
- this.currentPosition = pos;
- this.withoutUnicodePtr = temp2;
- return false;
- }
- // Unicode 4 detection
- char low = (char) getNextCharWithBoundChecks();
- if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) {
- // illegal low surrogate
- this.currentPosition = pos;
- this.withoutUnicodePtr = temp2;
- return false;
- }
- isJavaIdentifierPart = ScannerHelper.isJavaIdentifierPart(c, low);
- }
- else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) {
- this.currentPosition = pos;
- this.withoutUnicodePtr = temp2;
- return false;
- } else {
- isJavaIdentifierPart = ScannerHelper.isJavaIdentifierPart(c);
- }
- if (unicode) {
- if (!isJavaIdentifierPart) {
- this.currentPosition = pos;
- this.withoutUnicodePtr = temp2;
- return false;
- }
- return true;
- } else {
- if (!isJavaIdentifierPart) {
- this.currentPosition = pos;
- return false;
- }
-
- if (this.withoutUnicodePtr != 0)
- unicodeStore();
- return true;
- }
- } catch(InvalidInputException e) {
- this.currentPosition = pos;
- this.withoutUnicodePtr = temp2;
- return false;
- }
-}
-public boolean getNextCharAsJavaIdentifierPart() {
- //BOOLEAN
- //handle the case of unicode.
- //when a unicode appears then we must use a buffer that holds char internal values
- //At the end of this method currentCharacter holds the new visited char
- //and currentPosition points right next after it
- //Both previous lines are true if the currentCharacter is a JavaIdentifierPart
- //On false, no side effect has occured.
-
- //ALL getNextChar.... ARE OPTIMIZED COPIES
- int pos;
- if ((pos = this.currentPosition) >= this.eofPosition) // handle the obvious case upfront
- return false;
-
- int temp2 = this.withoutUnicodePtr;
- try {
- boolean unicode = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- unicode = true;
- }
- char c = this.currentCharacter;
- boolean isJavaIdentifierPart = false;
- if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) {
- if (this.complianceLevel < ClassFileConstants.JDK1_5) {
- this.currentPosition = pos;
- this.withoutUnicodePtr = temp2;
- return false;
- }
- // Unicode 4 detection
- char low = (char) getNextChar();
- if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) {
- // illegal low surrogate
- this.currentPosition = pos;
- this.withoutUnicodePtr = temp2;
- return false;
- }
- isJavaIdentifierPart = ScannerHelper.isJavaIdentifierPart(c, low);
- }
- else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) {
- this.currentPosition = pos;
- this.withoutUnicodePtr = temp2;
- return false;
- } else {
- isJavaIdentifierPart = ScannerHelper.isJavaIdentifierPart(c);
- }
- if (unicode) {
- if (!isJavaIdentifierPart) {
- this.currentPosition = pos;
- this.withoutUnicodePtr = temp2;
- return false;
- }
- return true;
- } else {
- if (!isJavaIdentifierPart) {
- this.currentPosition = pos;
- return false;
- }
-
- if (this.withoutUnicodePtr != 0)
- unicodeStore();
- return true;
- }
- } catch (IndexOutOfBoundsException e) {
- this.currentPosition = pos;
- this.withoutUnicodePtr = temp2;
- return false;
- } catch(InvalidInputException e) {
- this.currentPosition = pos;
- this.withoutUnicodePtr = temp2;
- return false;
- }
-}
-/*
- * External API in JavaScriptConventions.
- * This is used to optimize the case where the scanner is used to scan a single identifier.
- * In this case, the AIOOBE is slower to handle than a bound check
- */
-public int scanIdentifier() throws InvalidInputException {
- int whiteStart = 0;
- while (true) { //loop for jumping over comments
- this.withoutUnicodePtr = 0;
- //start with a new token (even comment written with unicode )
- // ---------Consume white space and handles startPosition---------
- whiteStart = this.currentPosition;
- boolean isWhiteSpace, hasWhiteSpaces = false;
- int offset;
- int unicodePtr;
- boolean checkIfUnicode = false;
- do {
- unicodePtr = this.withoutUnicodePtr;
- offset = this.currentPosition;
- this.startPosition = this.currentPosition;
- if (this.currentPosition < this.eofPosition) {
- this.currentCharacter = this.source[this.currentPosition++];
- checkIfUnicode = this.currentPosition < this.eofPosition
- && this.currentCharacter == '\\'
- && this.source[this.currentPosition] == 'u';
- } else if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) {
- // reposition scanner in case we are interested by spaces as tokens
- this.currentPosition--;
- this.startPosition = whiteStart;
- return TokenNameWHITESPACE;
- } else {
- return TokenNameEOF;
- }
- if (checkIfUnicode) {
- isWhiteSpace = jumpOverUnicodeWhiteSpace();
- offset = this.currentPosition - offset;
- } else {
- offset = this.currentPosition - offset;
- // inline version of:
- //isWhiteSpace =
- // (this.currentCharacter == ' ') || ScannerHelper.isWhitespace(this.currentCharacter);
- switch (this.currentCharacter) {
- case 10 : /* \ u000a: LINE FEED */
- case 12 : /* \ u000c: FORM FEED */
- case 13 : /* \ u000d: CARRIAGE RETURN */
- case 32 : /* \ u0020: SPACE */
- case 9 : /* \ u0009: HORIZONTAL TABULATION */
- isWhiteSpace = true;
- break;
- default :
- isWhiteSpace = false;
- }
- }
- if (isWhiteSpace) {
- hasWhiteSpaces = true;
- }
- } while (isWhiteSpace);
- if (hasWhiteSpaces) {
- if (this.tokenizeWhiteSpace) {
- // reposition scanner in case we are interested by spaces as tokens
- this.currentPosition-=offset;
- this.startPosition = whiteStart;
- if (checkIfUnicode) {
- this.withoutUnicodePtr = unicodePtr;
- }
- return TokenNameWHITESPACE;
- } else if (checkIfUnicode) {
- this.withoutUnicodePtr = 0;
- unicodeStore();
- } else {
- this.withoutUnicodePtr = 0;
- }
- }
- char c = this.currentCharacter;
- if (c < ScannerHelper.MAX_OBVIOUS) {
- if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) {
- return scanIdentifierOrKeywordWithBoundCheck();
- }
- return TokenNameERROR;
- }
- boolean isJavaIdStart;
- if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) {
- if (this.complianceLevel < ClassFileConstants.JDK1_5) {
- throw new InvalidInputException(INVALID_UNICODE_ESCAPE);
- }
- // Unicode 4 detection
- char low = (char) getNextCharWithBoundChecks();
- if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) {
- // illegal low surrogate
- throw new InvalidInputException(INVALID_LOW_SURROGATE);
- }
- isJavaIdStart = ScannerHelper.isJavaIdentifierStart(c, low);
- } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) {
- if (this.complianceLevel < ClassFileConstants.JDK1_5) {
- throw new InvalidInputException(INVALID_UNICODE_ESCAPE);
- }
- throw new InvalidInputException(INVALID_HIGH_SURROGATE);
- } else {
- // optimized case already checked
- isJavaIdStart = Character.isJavaIdentifierStart(c);
- }
- if (isJavaIdStart)
- return scanIdentifierOrKeywordWithBoundCheck();
- return TokenNameERROR;
- }
-}
-public int getNextToken() throws InvalidInputException {
- this.wasAcr = false;
- if (this.diet) {
- jumpOverMethodBody();
- this.diet = false;
- return this.currentPosition > this.eofPosition ? TokenNameEOF : TokenNameRBRACE;
- }
- int whiteStart = 0;
- int previousToken = this.currentToken;
- try {
- while (true) { //loop for jumping over comments
- this.withoutUnicodePtr = 0;
- //start with a new token (even comment written with unicode )
-
- // ---------Consume white space and handles startPosition---------
- whiteStart = this.currentPosition;
- boolean isWhiteSpace, hasWhiteSpaces = false;
- int offset;
- int unicodePtr;
- boolean checkIfUnicode = false;
- do {
- unicodePtr = this.withoutUnicodePtr;
- offset = this.currentPosition;
- this.startPosition = this.currentPosition;
- try {
- checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u');
- } catch(IndexOutOfBoundsException e) {
- if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) {
- // reposition scanner in case we are interested by spaces as tokens
- this.currentPosition--;
- this.startPosition = whiteStart;
- return this.currentToken=TokenNameWHITESPACE;
- }
- if (this.currentPosition > this.eofPosition)
- return this.currentToken=TokenNameEOF;
- }
- if (this.currentPosition > this.eofPosition)
- return this.currentToken=TokenNameEOF;
- if (checkIfUnicode) {
- isWhiteSpace = jumpOverUnicodeWhiteSpace();
- offset = this.currentPosition - offset;
- } else {
- offset = this.currentPosition - offset;
- if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) {
- if (this.recordLineSeparator) {
- pushLineSeparator();
- }
- }
- // inline version of:
- //isWhiteSpace =
- // (this.currentCharacter == ' ') || ScannerHelper.isWhitespace(this.currentCharacter);
- switch (this.currentCharacter) {
- case 10 : /* \ u000a: LINE FEED */
- case 12 : /* \ u000c: FORM FEED */
- case 13 : /* \ u000d: CARRIAGE RETURN */
- case 32 : /* \ u0020: SPACE */
- case 9 : /* \ u0009: HORIZONTAL TABULATION */
- isWhiteSpace = true;
- break;
- default :
- isWhiteSpace = false;
- }
- }
- if (isWhiteSpace) {
- hasWhiteSpaces = true;
- }
- } while (isWhiteSpace);
- if (hasWhiteSpaces) {
- if (this.tokenizeWhiteSpace) {
- // reposition scanner in case we are interested by spaces as tokens
- this.currentPosition-=offset;
- this.startPosition = whiteStart;
- if (checkIfUnicode) {
- this.withoutUnicodePtr = unicodePtr;
- }
- return this.currentToken=TokenNameWHITESPACE;
- } else if (checkIfUnicode) {
- this.withoutUnicodePtr = 0;
- unicodeStore();
- } else {
- this.withoutUnicodePtr = 0;
- }
- }
- // ---------Identify the next token-------------
- switch (this.currentCharacter) {
- case '@' :
-/* if (this.sourceLevel >= ClassFileConstants.JDK1_5) {
- return this.currentToken=TokenNameAT;
- } else {
- return this.currentToken=TokenNameERROR;
- }*/
- return this.currentToken=TokenNameAT;
- case '(' :
- return this.currentToken=TokenNameLPAREN;
- case ')' :
- return this.currentToken=TokenNameRPAREN;
- case '{' :
- return this.currentToken=TokenNameLBRACE;
- case '}' :
- return this.currentToken=TokenNameRBRACE;
- case '[' :
- return this.currentToken=TokenNameLBRACKET;
- case ']' :
- return this.currentToken=TokenNameRBRACKET;
- case ';' :
- return this.currentToken=TokenNameSEMICOLON;
- case ',' :
- return this.currentToken=TokenNameCOMMA;
- case '.' :
- if (getNextCharAsDigit()) {
- return scanNumber(true);
- }
- return this.currentToken=TokenNameDOT;
-
- case '+' :
- {
- int test;
- if ((test = getNextChar('+', '=')) == 0)
- return this.currentToken=TokenNamePLUS_PLUS;
- if (test > 0)
- return this.currentToken=TokenNamePLUS_EQUAL;
- return this.currentToken=TokenNamePLUS;
- }
- case '-' :
- {
- int test;
- if ((test = getNextChar('-', '=')) == 0)
- return this.currentToken=TokenNameMINUS_MINUS;
- if (test > 0)
- return this.currentToken=TokenNameMINUS_EQUAL;
- return this.currentToken=TokenNameMINUS;
- }
- case '~' :
- return this.currentToken=TokenNameTWIDDLE;
- case '!' :
- if (getNextChar('='))
- {
- if (getNextChar('='))
- return this.currentToken=TokenNameNOT_EQUAL_EQUAL;
- return this.currentToken=TokenNameNOT_EQUAL;
- }
- return this.currentToken=TokenNameNOT;
- case '*' :
- if (getNextChar('='))
- return this.currentToken=TokenNameMULTIPLY_EQUAL;
- return this.currentToken=TokenNameMULTIPLY;
- case '%' :
- if (getNextChar('='))
- return this.currentToken=TokenNameREMAINDER_EQUAL;
- return this.currentToken=TokenNameREMAINDER;
- case '<' :
- {
- int test;
- if ((test = getNextChar('=', '<')) == 0)
- return this.currentToken=TokenNameLESS_EQUAL;
- if (test > 0) {
- if (getNextChar('='))
- return this.currentToken=TokenNameLEFT_SHIFT_EQUAL;
- return this.currentToken=TokenNameLEFT_SHIFT;
- }
- return this.currentToken=TokenNameLESS;
- }
- case '>' :
- {
- int test;
- if (this.returnOnlyGreater) {
- return this.currentToken=TokenNameGREATER;
- }
- if ((test = getNextChar('=', '>')) == 0)
- return this.currentToken=TokenNameGREATER_EQUAL;
- if (test > 0) {
- if ((test = getNextChar('=', '>')) == 0)
- return this.currentToken=TokenNameRIGHT_SHIFT_EQUAL;
- if (test > 0) {
- if (getNextChar('='))
- return this.currentToken=TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL;
- return this.currentToken=TokenNameUNSIGNED_RIGHT_SHIFT;
- }
- return this.currentToken=TokenNameRIGHT_SHIFT;
- }
- return this.currentToken=TokenNameGREATER;
- }
- case '=' :
- if (getNextChar('='))
- {
- if (getNextChar('='))
- return this.currentToken=TokenNameEQUAL_EQUAL_EQUAL;
- return this.currentToken=TokenNameEQUAL_EQUAL;
- }
- return this.currentToken=TokenNameEQUAL;
- case '&' :
- {
- int test;
- if ((test = getNextChar('&', '=')) == 0)
- return this.currentToken=TokenNameAND_AND;
- if (test > 0)
- return this.currentToken=TokenNameAND_EQUAL;
- return this.currentToken=TokenNameAND;
- }
- case '|' :
- {
- int test;
- if ((test = getNextChar('|', '=')) == 0)
- return this.currentToken=TokenNameOR_OR;
- if (test > 0)
- return this.currentToken=TokenNameOR_EQUAL;
- return this.currentToken=TokenNameOR;
- }
- case '^' :
- if (getNextChar('='))
- return this.currentToken=TokenNameXOR_EQUAL;
- return this.currentToken=TokenNameXOR;
- case '?' :
- return this.currentToken=TokenNameQUESTION;
- case ':' :
- return this.currentToken=TokenNameCOLON;
-/* case '\'' :
- {
- int test;
- if ((test = getNextChar('\n', '\r')) == 0) {
- throw new InvalidInputException(INVALID_CHARACTER_CONSTANT);
- }
- if (test > 0) {
- // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed
- for (int lookAhead = 0; lookAhead < 3; lookAhead++) {
- if (this.currentPosition + lookAhead == this.eofPosition)
- break;
- if (this.source[this.currentPosition + lookAhead] == '\n')
- break;
- if (this.source[this.currentPosition + lookAhead] == '\'') {
- this.currentPosition += lookAhead + 1;
- break;
- }
- }
- throw new InvalidInputException(INVALID_CHARACTER_CONSTANT);
- }
- }
- if (getNextChar('\'')) {
- // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed
- for (int lookAhead = 0; lookAhead < 3; lookAhead++) {
- if (this.currentPosition + lookAhead == this.eofPosition)
- break;
- if (this.source[this.currentPosition + lookAhead] == '\n')
- break;
- if (this.source[this.currentPosition + lookAhead] == '\'') {
- this.currentPosition += lookAhead + 1;
- break;
- }
- }
- throw new InvalidInputException(INVALID_CHARACTER_CONSTANT);
- }
- if (getNextChar('\\')) {
- if (this.unicodeAsBackSlash) {
- // consume next character
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- } else {
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
- } else {
- this.currentCharacter = this.source[this.currentPosition++];
- }
- scanEscapeCharacter();
- } else { // consume next character
- this.unicodeAsBackSlash = false;
- checkIfUnicode = false;
- try {
- checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u');
- } catch(IndexOutOfBoundsException e) {
- this.currentPosition--;
- throw new InvalidInputException(INVALID_CHARACTER_CONSTANT);
- }
- if (checkIfUnicode) {
- getNextUnicodeChar();
- } else {
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
- }
- if (getNextChar('\''))
- return this.currentToken=TokenNameCharacterLiteral;
- // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed
- for (int lookAhead = 0; lookAhead < 20; lookAhead++) {
- if (this.currentPosition + lookAhead == this.eofPosition)
- break;
- if (this.source[this.currentPosition + lookAhead] == '\n')
- break;
- if (this.source[this.currentPosition + lookAhead] == '\'') {
- this.currentPosition += lookAhead + 1;
- break;
- }
- }
- throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); */
- case '\'' :
- case '"' :
- char character = this.currentCharacter;
- try {
- // consume next character
- this.unicodeAsBackSlash = false;
- boolean isUnicode = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- isUnicode = true;
- } else {
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
-
- while ((this.currentCharacter != character) || ((this.currentCharacter == character) && (isUnicode == true))) {
- if ((this.currentCharacter == '\n' && !isUnicode) || (this.currentCharacter == '\r' && !isUnicode)) {
- this.currentPosition--; // set current position on new line character
- throw new InvalidInputException(INVALID_CHAR_IN_STRING);
- }
- if (this.currentCharacter == '\\') {
- if (this.unicodeAsBackSlash) {
- this.withoutUnicodePtr--;
- // consume next character
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- isUnicode = true;
- this.withoutUnicodePtr--;
- } else {
- isUnicode = false;
- }
- } else {
- if (this.withoutUnicodePtr == 0) {
- unicodeInitializeBuffer(this.currentPosition - this.startPosition);
- }
- this.withoutUnicodePtr --;
- this.currentCharacter = this.source[this.currentPosition++];
- }
- // we need to compute the escape character in a separate buffer
- if (scanEscapeCharacter() && this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
- // consume next character
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- isUnicode = true;
- } else {
- isUnicode = false;
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
-
- }
- } catch (IndexOutOfBoundsException e) {
- this.currentPosition--;
- throw new InvalidInputException(UNTERMINATED_STRING);
- } catch (InvalidInputException e) {
- if (e.getMessage().equals(INVALID_ESCAPE)) {
- // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed
- for (int lookAhead = 0; lookAhead < 50; lookAhead++) {
- if (this.currentPosition + lookAhead == this.eofPosition)
- break;
- if (this.source[this.currentPosition + lookAhead] == '\n')
- break;
- if (this.source[this.currentPosition + lookAhead] == character) {
- this.currentPosition += lookAhead + 1;
- break;
- }
- }
-
- }
- throw e; // rethrow
- }
- if (character == '\'') {
- return this.currentToken=TokenNameCharacterLiteral;
- }
- return this.currentToken=TokenNameStringLiteral;
-
- case '/' :
- {
- int test;
- if ((test = getNextChar('/', '*')) == 0) { //line comment
- this.lastCommentLinePosition = this.currentPosition;
- try { //get the next char
- this.currentCharacter = this.source[this.currentPosition++];
-
- boolean isUnicode = false;
- while (this.currentCharacter != '\r' && this.currentCharacter != '\n') {
- this.lastCommentLinePosition = this.currentPosition;
- //get the next char
- this.currentCharacter = this.source[this.currentPosition++];
- }
- /*
- * We need to completely consume the line break
- */
- if (this.currentCharacter == '\r'
- && this.eofPosition > this.currentPosition) {
- if (this.source[this.currentPosition] == '\n') {
- this.currentPosition++;
- this.currentCharacter = '\n';
- } else if ((this.source[this.currentPosition] == '\\')
- && (this.source[this.currentPosition + 1] == 'u')) {
- getNextUnicodeChar();
- isUnicode = true;
- }
- }
- recordComment(TokenNameCOMMENT_LINE);
- if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition);
- if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) {
- if (this.checkNonExternalizedStringLiterals) {
- parseTags();
- }
- if (this.recordLineSeparator) {
- if (isUnicode) {
- pushUnicodeLineSeparator();
- } else {
- pushLineSeparator();
- }
- }
- }
- if (this.tokenizeComments) {
- return this.currentToken=TokenNameCOMMENT_LINE;
- }
- } catch (IndexOutOfBoundsException e) {
- this.currentPosition--;
- recordComment(TokenNameCOMMENT_LINE);
- if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition);
- if (this.checkNonExternalizedStringLiterals) {
- parseTags();
- }
- if (this.tokenizeComments) {
- return this.currentToken=TokenNameCOMMENT_LINE;
- } else {
- this.currentPosition++;
- }
- }
- break;
- }
- if (test > 0) { //traditional and javadoc comment
- try { //get the next char
- boolean isJavadoc = false, star = false;
- boolean isUnicode = false;
- int previous;
- // consume next character
- this.unicodeAsBackSlash = false;
- this.currentCharacter = this.source[this.currentPosition++];
-
- if (this.currentCharacter == '*') {
- isJavadoc = true;
- star = true;
- }
- if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) {
- if (this.recordLineSeparator) {
- if (isUnicode) {
- pushUnicodeLineSeparator();
- } else {
- pushLineSeparator();
- }
- }
- }
- isUnicode = false;
- previous = this.currentPosition;
- this.currentCharacter = this.source[this.currentPosition++];
- // empty comment is not a javadoc /**/
- if (this.currentCharacter == '/') {
- isJavadoc = false;
- }
- //loop until end of comment */
- int firstTag = 0;
- while ((this.currentCharacter != '/') || (!star)) {
- if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) {
- if (this.recordLineSeparator) {
- if (isUnicode) {
- pushUnicodeLineSeparator();
- } else {
- pushLineSeparator();
- }
- }
- }
- switch (this.currentCharacter) {
- case '*':
- star = true;
- break;
- case '@':
- if (firstTag == 0) {
- firstTag = previous;
- }
- // fall through default case to set star to false
- default:
- star = false;
- }
- //get next char
- previous = this.currentPosition;
- this.currentCharacter = this.source[this.currentPosition++];
- }
- int token = isJavadoc ? TokenNameCOMMENT_JAVADOC : TokenNameCOMMENT_BLOCK;
- recordComment(token);
- this.commentTagStarts[this.commentPtr] = firstTag;
- if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition);
- if (this.tokenizeComments) {
- /*
- if (isJavadoc)
- return this.currentToken=TokenNameCOMMENT_JAVADOC;
- return this.currentToken=TokenNameCOMMENT_BLOCK;
- */
- return this.currentToken=token;
- }
- } catch (IndexOutOfBoundsException e) {
- this.currentPosition--;
- throw new InvalidInputException(UNTERMINATED_COMMENT);
- }
- break;
- }
- if (checkIfDivide(previousToken)){
- if (getNextChar('='))
- {
- currentToken=TokenNameDIVIDE_EQUAL;
- return currentToken;
- }
- currentToken=TokenNameDIVIDE;
- return currentToken;
- }
-
- // check if regular expression
- if (checkIfRegExp()) {
- currentToken = TokenNameRegExLiteral;
- return currentToken;
- } else {
- if (getNextChar('='))
- {
- currentToken=TokenNameDIVIDE_EQUAL;
- return currentToken;
- }
- currentToken=TokenNameDIVIDE;
- return currentToken;
- }
- }
- case '\u001a' :
- if (atEnd())
- return this.currentToken=TokenNameEOF;
- //the atEnd may not be <currentPosition == eofPosition> if source is only some part of a real (external) stream
- throw new InvalidInputException("Ctrl-Z"); //$NON-NLS-1$
- default :
- char c = this.currentCharacter;
- if (c < ScannerHelper.MAX_OBVIOUS) {
- if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) {
- return scanIdentifierOrKeyword();
- } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0) {
- return scanNumber(false);
- } else {
- return this.currentToken=TokenNameERROR;
- }
- }
- boolean isJavaIdStart;
- if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) {
- if (this.complianceLevel < ClassFileConstants.JDK1_5) {
- throw new InvalidInputException(INVALID_UNICODE_ESCAPE);
- }
- // Unicode 4 detection
- char low = (char) getNextChar();
- if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) {
- // illegal low surrogate
- throw new InvalidInputException(INVALID_LOW_SURROGATE);
- }
- isJavaIdStart = ScannerHelper.isJavaIdentifierStart(c, low);
- }
- else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) {
- if (this.complianceLevel < ClassFileConstants.JDK1_5) {
- throw new InvalidInputException(INVALID_UNICODE_ESCAPE);
- }
- throw new InvalidInputException(INVALID_HIGH_SURROGATE);
- } else {
- // optimized case already checked
- isJavaIdStart = Character.isJavaIdentifierStart(c);
- }
- if (isJavaIdStart)
- return scanIdentifierOrKeyword();
- if (ScannerHelper.isDigit(this.currentCharacter)) {
- return scanNumber(false);
- }
- return this.currentToken=TokenNameERROR;
- }
- }
- } //-----------------end switch while try--------------------
- catch (IndexOutOfBoundsException e) {
- if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) {
- // reposition scanner in case we are interested by spaces as tokens
- this.currentPosition--;
- this.startPosition = whiteStart;
- return this.currentToken=TokenNameWHITESPACE;
- }
- }
- return this.currentToken=TokenNameEOF;
-}
-
-public void getNextUnicodeChar()
- throws InvalidInputException {
- //VOID
- //handle the case of unicode.
- //when a unicode appears then we must use a buffer that holds char internal values
- //At the end of this method currentCharacter holds the new visited char
- //and currentPosition points right next after it
-
- //ALL getNextChar.... ARE OPTIMIZED COPIES
- int c1 = 0, c2 = 0, c3 = 0, c4 = 0, unicodeSize = 6;
- this.currentPosition++;
- if (this.currentPosition < this.eofPosition) {
- while (this.source[this.currentPosition] == 'u') {
- this.currentPosition++;
- if (this.currentPosition >= this.eofPosition) {
- this.currentPosition--;
- throw new InvalidInputException(INVALID_UNICODE_ESCAPE);
- }
- unicodeSize++;
- }
- } else {
- this.currentPosition--;
- throw new InvalidInputException(INVALID_UNICODE_ESCAPE);
- }
-
- if ((this.currentPosition + 4) > this.eofPosition) {
- this.currentPosition += (this.eofPosition - this.currentPosition);
- throw new InvalidInputException(INVALID_UNICODE_ESCAPE);
- }
- if ((c1 = ScannerHelper.getNumericValue(this.source[this.currentPosition++])) > 15
- || c1 < 0
- || (c2 = ScannerHelper.getNumericValue(this.source[this.currentPosition++])) > 15
- || c2 < 0
- || (c3 = ScannerHelper.getNumericValue(this.source[this.currentPosition++])) > 15
- || c3 < 0
- || (c4 = ScannerHelper.getNumericValue(this.source[this.currentPosition++])) > 15
- || c4 < 0){
- throw new InvalidInputException(INVALID_UNICODE_ESCAPE);
- }
- this.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4);
- //need the unicode buffer
- if (this.withoutUnicodePtr == 0) {
- //buffer all the entries that have been left aside....
- unicodeInitializeBuffer(this.currentPosition - unicodeSize - this.startPosition);
- }
- //fill the buffer with the char
- unicodeStore();
- this.unicodeAsBackSlash = this.currentCharacter == '\\';
-}
-public NLSTag[] getNLSTags() {
- final int length = this.nlsTagsPtr;
- if (length != 0) {
- NLSTag[] result = new NLSTag[length];
- System.arraycopy(this.nlsTags, 0, result, 0, length);
- this.nlsTagsPtr = 0;
- return result;
- }
- return null;
-}
-public char[] getSource(){
- return this.source;
-}
-public final void jumpOverMethodBody() {
-
- this.wasAcr = false;
- int found = 1;
- try {
- while (true) { //loop for jumping over comments
- this.withoutUnicodePtr = 0;
- // ---------Consume white space and handles startPosition---------
- boolean isWhiteSpace;
- do {
- this.startPosition = this.currentPosition;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- isWhiteSpace = jumpOverUnicodeWhiteSpace();
- } else {
- if (this.recordLineSeparator
- && ((this.currentCharacter == '\r') || (this.currentCharacter == '\n'))) {
- pushLineSeparator();
- }
- isWhiteSpace = CharOperation.isWhitespace(this.currentCharacter);
- }
- } while (isWhiteSpace);
-
- // -------consume token until } is found---------
- NextToken: switch (this.currentCharacter) {
- case '{' :
- found++;
- break NextToken;
- case '}' :
- found--;
- if (found == 0)
- return;
- break NextToken;
- case '\'' :
- {
- boolean test;
- test = getNextChar('\\');
- if (test) {
- try {
- if (this.unicodeAsBackSlash) {
- // consume next character
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- } else {
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
- } else {
- this.currentCharacter = this.source[this.currentPosition++];
- }
- scanEscapeCharacter();
- } catch (InvalidInputException ex) {
- // ignore
- }
- } else {
- try { // consume next character
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- } else {
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
- } catch (InvalidInputException ex) {
- // ignore
- }
- }
- getNextChar('\'');
- break NextToken;
- }
- case '"' :
- try {
- try { // consume next character
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- } else {
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
- } catch (InvalidInputException ex) {
- // ignore
- }
- while (this.currentCharacter != '"') {
- if (this.currentCharacter == '\r'){
- if (this.source[this.currentPosition] == '\n') this.currentPosition++;
- break NextToken; // the string cannot go further that the line
- }
- if (this.currentCharacter == '\n'){
- break; // the string cannot go further that the line
- }
- if (this.currentCharacter == '\\') {
- try {
- if (this.unicodeAsBackSlash) {
- // consume next character
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- } else {
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
- } else {
- this.currentCharacter = this.source[this.currentPosition++];
- }
- scanEscapeCharacter();
- } catch (InvalidInputException ex) {
- // ignore
- }
- }
- try { // consume next character
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- } else {
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
- } catch (InvalidInputException ex) {
- // ignore
- }
- }
- } catch (IndexOutOfBoundsException e) {
- return;
- }
- break NextToken;
- case '/' :
- {
- int test;
- if ((test = getNextChar('/', '*')) == 0) { //line comment
- try {
- this.lastCommentLinePosition = this.currentPosition;
- //get the next char
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- }
- //handle the \\u case manually into comment
- if (this.currentCharacter == '\\') {
- if (this.source[this.currentPosition] == '\\')
- this.currentPosition++;
- } //jump over the \\
- boolean isUnicode = false;
- while (this.currentCharacter != '\r' && this.currentCharacter != '\n') {
- this.lastCommentLinePosition = this.currentPosition;
- //get the next char
- isUnicode = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- isUnicode = true;
- getNextUnicodeChar();
- }
- //handle the \\u case manually into comment
- if (this.currentCharacter == '\\') {
- if (this.source[this.currentPosition] == '\\')
- this.currentPosition++;
- } //jump over the \\
- }
- /*
- * We need to completely consume the line break
- */
- if (this.currentCharacter == '\r'
- && this.eofPosition > this.currentPosition) {
- if (this.source[this.currentPosition] == '\n') {
- this.currentPosition++;
- this.currentCharacter = '\n';
- } else if ((this.source[this.currentPosition] == '\\')
- && (this.source[this.currentPosition + 1] == 'u')) {
- isUnicode = true;
- getNextUnicodeChar();
- }
- }
- recordComment(TokenNameCOMMENT_LINE);
- if (this.recordLineSeparator
- && ((this.currentCharacter == '\r') || (this.currentCharacter == '\n'))) {
- if (this.checkNonExternalizedStringLiterals) {
- parseTags();
- }
- if (this.recordLineSeparator) {
- if (isUnicode) {
- pushUnicodeLineSeparator();
- } else {
- pushLineSeparator();
- }
- }
- }
- } catch (IndexOutOfBoundsException e) {
- //an eof will then be generated
- this.currentPosition--;
- recordComment(TokenNameCOMMENT_LINE);
- if (this.checkNonExternalizedStringLiterals) {
- parseTags();
- }
- if (!this.tokenizeComments) {
- this.currentPosition++;
- }
- }
- break NextToken;
- }
- if (test > 0) { //traditional and javadoc comment
- boolean isJavadoc = false;
- try { //get the next char
- boolean star = false;
- int previous;
- boolean isUnicode = false;
- // consume next character
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- isUnicode = true;
- } else {
- isUnicode = false;
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
-
- if (this.currentCharacter == '*') {
- isJavadoc = true;
- star = true;
- }
- if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) {
- if (this.recordLineSeparator) {
- if (isUnicode) {
- pushUnicodeLineSeparator();
- } else {
- pushLineSeparator();
- }
- }
- }
- isUnicode = false;
- previous = this.currentPosition;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- isUnicode = true;
- } else {
- isUnicode = false;
- }
- //handle the \\u case manually into comment
- if (this.currentCharacter == '\\') {
- if (this.source[this.currentPosition] == '\\')
- this.currentPosition++; //jump over the \\
- }
- // empty comment is not a javadoc /**/
- if (this.currentCharacter == '/') {
- isJavadoc = false;
- }
- //loop until end of comment */
- int firstTag = 0;
- while ((this.currentCharacter != '/') || (!star)) {
- if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) {
- if (this.recordLineSeparator) {
- if (isUnicode) {
- pushUnicodeLineSeparator();
- } else {
- pushLineSeparator();
- }
- }
- }
- switch (this.currentCharacter) {
- case '*':
- star = true;
- break;
- case '@':
- if (firstTag == 0) {
- firstTag = previous;
- }
- // fall through default case to set star to false
- default:
- star = false;
- }
- //get next char
- previous = this.currentPosition;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- isUnicode = true;
- } else {
- isUnicode = false;
- }
- //handle the \\u case manually into comment
- if (this.currentCharacter == '\\') {
- if (this.source[this.currentPosition] == '\\')
- this.currentPosition++;
- } //jump over the \\
- }
- recordComment(isJavadoc ? TokenNameCOMMENT_JAVADOC : TokenNameCOMMENT_BLOCK);
- this.commentTagStarts[this.commentPtr] = firstTag;
- } catch (IndexOutOfBoundsException e) {
- return;
- }
- break NextToken;
- }
- break NextToken;
- }
-
- default :
- try {
- char c = this.currentCharacter;
- if (c < ScannerHelper.MAX_OBVIOUS) {
- if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) {
- scanIdentifierOrKeyword();
- break NextToken;
- } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0) {
- scanNumber(false);
- break NextToken;
- } else {
- break NextToken;
- }
- }
- boolean isJavaIdStart;
- if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) {
- if (this.complianceLevel < ClassFileConstants.JDK1_5) {
- throw new InvalidInputException(INVALID_UNICODE_ESCAPE);
- }
- // Unicode 4 detection
- char low = (char) getNextChar();
- if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) {
- // illegal low surrogate
- break NextToken;
- }
- isJavaIdStart = ScannerHelper.isJavaIdentifierStart(c, low);
- } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) {
- break NextToken;
- } else {
- // optimized case already checked
- isJavaIdStart = Character.isJavaIdentifierStart(c);
- }
- if (isJavaIdStart) {
- scanIdentifierOrKeyword();
- break NextToken;
- }
-// if (ScannerHelper.isDigit(this.currentCharacter)) {
-// scanNumber(false);
-// break NextToken;
-// }
- } catch (InvalidInputException ex) {
- // ignore
- }
- }
- }
- //-----------------end switch while try--------------------
- } catch (IndexOutOfBoundsException e) {
- // ignore
- } catch (InvalidInputException e) {
- // ignore
- }
- return;
-}
-public final boolean jumpOverUnicodeWhiteSpace() throws InvalidInputException {
- //BOOLEAN
- //handle the case of unicode. Jump over the next whiteSpace
- //making startPosition pointing on the next available char
- //On false, the currentCharacter is filled up with a potential
- //correct char
-
- this.wasAcr = false;
- getNextUnicodeChar();
- return CharOperation.isWhitespace(this.currentCharacter);
-}
-
-final char[] optimizedCurrentTokenSource1() {
- //return always the same char[] build only once
-
- //optimization at no speed cost of 99.5 % of the singleCharIdentifier
- char charOne = this.source[this.startPosition];
- switch (charOne) {
- case 'a' :
- return charArray_a;
- case 'b' :
- return charArray_b;
- case 'c' :
- return charArray_c;
- case 'd' :
- return charArray_d;
- case 'e' :
- return charArray_e;
- case 'f' :
- return charArray_f;
- case 'g' :
- return charArray_g;
- case 'h' :
- return charArray_h;
- case 'i' :
- return charArray_i;
- case 'j' :
- return charArray_j;
- case 'k' :
- return charArray_k;
- case 'l' :
- return charArray_l;
- case 'm' :
- return charArray_m;
- case 'n' :
- return charArray_n;
- case 'o' :
- return charArray_o;
- case 'p' :
- return charArray_p;
- case 'q' :
- return charArray_q;
- case 'r' :
- return charArray_r;
- case 's' :
- return charArray_s;
- case 't' :
- return charArray_t;
- case 'u' :
- return charArray_u;
- case 'v' :
- return charArray_v;
- case 'w' :
- return charArray_w;
- case 'x' :
- return charArray_x;
- case 'y' :
- return charArray_y;
- case 'z' :
- return charArray_z;
- default :
- return new char[] {charOne};
- }
-}
-final char[] optimizedCurrentTokenSource2() {
- //try to return the same char[] build only once
-
- char[] src = this.source;
- int start = this.startPosition;
- char c0 , c1;
- int hash = (((c0=src[start]) << 6) + (c1=src[start+1])) % TableSize;
- char[][] table = this.charArray_length[0][hash];
- int i = newEntry2;
- while (++i < InternalTableSize) {
- char[] charArray = table[i];
- if ((c0 == charArray[0]) && (c1 == charArray[1]))
- return charArray;
- }
- //---------other side---------
- i = -1;
- int max = newEntry2;
- while (++i <= max) {
- char[] charArray = table[i];
- if ((c0 == charArray[0]) && (c1 == charArray[1]))
- return charArray;
- }
- //--------add the entry-------
- if (++max >= InternalTableSize) max = 0;
- char[] r;
- System.arraycopy(src, start, r= new char[2], 0, 2);
- //newIdentCount++;
- return table[newEntry2 = max] = r; //(r = new char[] {c0, c1});
-}
-final char[] optimizedCurrentTokenSource3() {
- //try to return the same char[] build only once
-
- char[] src = this.source;
- int start = this.startPosition;
- char c0, c1=src[start+1], c2;
- int hash = (((c0=src[start])<< 6) + (c2=src[start+2])) % TableSize;
-// int hash = ((c0 << 12) + (c1<< 6) + c2) % TableSize;
- char[][] table = this.charArray_length[1][hash];
- int i = newEntry3;
- while (++i < InternalTableSize) {
- char[] charArray = table[i];
- if ((c0 == charArray[0]) && (c1 == charArray[1]) && (c2 == charArray[2]))
- return charArray;
- }
- //---------other side---------
- i = -1;
- int max = newEntry3;
- while (++i <= max) {
- char[] charArray = table[i];
- if ((c0 == charArray[0]) && (c1 == charArray[1]) && (c2 == charArray[2]))
- return charArray;
- }
- //--------add the entry-------
- if (++max >= InternalTableSize) max = 0;
- char[] r;
- System.arraycopy(src, start, r= new char[3], 0, 3);
- //newIdentCount++;
- return table[newEntry3 = max] = r; //(r = new char[] {c0, c1, c2});
-}
-final char[] optimizedCurrentTokenSource4() {
- //try to return the same char[] build only once
-
- char[] src = this.source;
- int start = this.startPosition;
- char c0, c1 = src[start+1], c2, c3 = src[start+3];
- int hash = (((c0=src[start]) << 6) + (c2=src[start+2])) % TableSize;
-// int hash = (int) (((((long) c0) << 18) + (c1 << 12) + (c2 << 6) + c3) % TableSize);
- char[][] table = this.charArray_length[2][hash];
- int i = newEntry4;
- while (++i < InternalTableSize) {
- char[] charArray = table[i];
- if ((c0 == charArray[0])
- && (c1 == charArray[1])
- && (c2 == charArray[2])
- && (c3 == charArray[3]))
- return charArray;
- }
- //---------other side---------
- i = -1;
- int max = newEntry4;
- while (++i <= max) {
- char[] charArray = table[i];
- if ((c0 == charArray[0])
- && (c1 == charArray[1])
- && (c2 == charArray[2])
- && (c3 == charArray[3]))
- return charArray;
- }
- //--------add the entry-------
- if (++max >= InternalTableSize) max = 0;
- char[] r;
- System.arraycopy(src, start, r= new char[4], 0, 4);
- //newIdentCount++;
- return table[newEntry4 = max] = r; //(r = new char[] {c0, c1, c2, c3});
-}
-final char[] optimizedCurrentTokenSource5() {
- //try to return the same char[] build only once
-
- char[] src = this.source;
- int start = this.startPosition;
- char c0, c1 = src[start+1], c2, c3 = src[start+3], c4;
- int hash = (((c0=src[start]) << 12) +((c2=src[start+2]) << 6) + (c4=src[start+4])) % TableSize;
-// int hash = (int) (((((long) c0) << 24) + (((long) c1) << 18) + (c2 << 12) + (c3 << 6) + c4) % TableSize);
- char[][] table = this.charArray_length[3][hash];
- int i = newEntry5;
- while (++i < InternalTableSize) {
- char[] charArray = table[i];
- if ((c0 == charArray[0])
- && (c1 == charArray[1])
- && (c2 == charArray[2])
- && (c3 == charArray[3])
- && (c4 == charArray[4]))
- return charArray;
- }
- //---------other side---------
- i = -1;
- int max = newEntry5;
- while (++i <= max) {
- char[] charArray = table[i];
- if ((c0 == charArray[0])
- && (c1 == charArray[1])
- && (c2 == charArray[2])
- && (c3 == charArray[3])
- && (c4 == charArray[4]))
- return charArray;
- }
- //--------add the entry-------
- if (++max >= InternalTableSize) max = 0;
- char[] r;
- System.arraycopy(src, start, r= new char[5], 0, 5);
- //newIdentCount++;
- return table[newEntry5 = max] = r; //(r = new char[] {c0, c1, c2, c3, c4});
-}
-final char[] optimizedCurrentTokenSource6() {
- //try to return the same char[] build only once
-
- char[] src = this.source;
- int start = this.startPosition;
- char c0, c1 = src[start+1], c2, c3 = src[start+3], c4, c5 = src[start+5];
- int hash = (((c0=src[start]) << 12) +((c2=src[start+2]) << 6) + (c4=src[start+4])) % TableSize;
-// int hash = (int)(((((long) c0) << 32) + (((long) c1) << 24) + (((long) c2) << 18) + (c3 << 12) + (c4 << 6) + c5) % TableSize);
- char[][] table = this.charArray_length[4][hash];
- int i = newEntry6;
- while (++i < InternalTableSize) {
- char[] charArray = table[i];
- if ((c0 == charArray[0])
- && (c1 == charArray[1])
- && (c2 == charArray[2])
- && (c3 == charArray[3])
- && (c4 == charArray[4])
- && (c5 == charArray[5]))
- return charArray;
- }
- //---------other side---------
- i = -1;
- int max = newEntry6;
- while (++i <= max) {
- char[] charArray = table[i];
- if ((c0 == charArray[0])
- && (c1 == charArray[1])
- && (c2 == charArray[2])
- && (c3 == charArray[3])
- && (c4 == charArray[4])
- && (c5 == charArray[5]))
- return charArray;
- }
- //--------add the entry-------
- if (++max >= InternalTableSize) max = 0;
- char[] r;
- System.arraycopy(src, start, r= new char[6], 0, 6);
- //newIdentCount++;
- return table[newEntry6 = max] = r; //(r = new char[] {c0, c1, c2, c3, c4, c5});
-}
-
-private void parseTags() {
- int position = 0;
- final int currentStartPosition = this.startPosition;
- final int currentLinePtr = this.linePtr;
- if (currentLinePtr >= 0) {
- position = this.lineEnds[currentLinePtr] + 1;
- }
- while (ScannerHelper.isWhitespace(this.source[position])) {
- position++;
- }
- if (currentStartPosition == position) {
- // the whole line is commented out
- return;
- }
- char[] s = null;
- int sourceEnd = this.currentPosition;
- int sourceStart = currentStartPosition;
- int sourceDelta = 0;
- if (this.withoutUnicodePtr != 0) {
- // 0 is used as a fast test flag so the real first char is in position 1
- System.arraycopy(
- this.withoutUnicodeBuffer,
- 1,
- s = new char[this.withoutUnicodePtr],
- 0,
- this.withoutUnicodePtr);
- sourceEnd = this.withoutUnicodePtr;
- sourceStart = 1;
- sourceDelta = currentStartPosition;
- } else {
- s = this.source;
- }
- int pos = CharOperation.indexOf(TAG_PREFIX, s, true, sourceStart, sourceEnd);
- if (pos != -1) {
- if (this.nlsTags == null) {
- this.nlsTags = new NLSTag[10];
- this.nlsTagsPtr = 0;
- }
- while (pos != -1) {
- int start = pos + TAG_PREFIX_LENGTH;
- int end = CharOperation.indexOf(TAG_POSTFIX, s, start, sourceEnd);
- if (end != -1) {
- NLSTag currentTag = null;
- final int currentLine = currentLinePtr + 1;
- try {
- currentTag = new NLSTag(pos + sourceDelta, end + sourceDelta, currentLine, extractInt(s, start, end));
- } catch (NumberFormatException e) {
- currentTag = new NLSTag(pos + sourceDelta, end + sourceDelta, currentLine, -1);
- }
- if (this.nlsTagsPtr == this.nlsTags.length) {
- // resize
- System.arraycopy(this.nlsTags, 0, (this.nlsTags = new NLSTag[this.nlsTagsPtr + 10]), 0, this.nlsTagsPtr);
- }
- this.nlsTags[this.nlsTagsPtr++] = currentTag;
- } else {
- end = start;
- }
- pos = CharOperation.indexOf(TAG_PREFIX, s, true, end, sourceEnd);
- }
- }
-}
-private int extractInt(char[] array, int start, int end) {
- int value = 0;
- for (int i = start; i < end; i++) {
- final char currentChar = array[i];
- int digit = 0;
- switch(currentChar) {
- case '0' :
- digit = 0;
- break;
- case '1' :
- digit = 1;
- break;
- case '2' :
- digit = 2;
- break;
- case '3' :
- digit = 3;
- break;
- case '4' :
- digit = 4;
- break;
- case '5' :
- digit = 5;
- break;
- case '6' :
- digit = 6;
- break;
- case '7' :
- digit = 7;
- break;
- case '8' :
- digit = 8;
- break;
- case '9' :
- digit = 9;
- break;
- default :
- throw new NumberFormatException();
- }
- value *= 10;
- if (digit < 0) throw new NumberFormatException();
- value += digit;
- }
- return value;
-}
-public final void pushLineSeparator() {
- //see comment on isLineDelimiter(char) for the use of '\n' and '\r'
- final int INCREMENT = 250;
- //currentCharacter is at position currentPosition-1
- // cr 000D
- if (this.currentCharacter == '\r') {
- int separatorPos = this.currentPosition - 1;
- if ((this.linePtr >= 0) && (this.lineEnds[this.linePtr] >= separatorPos)) return;
- int length = this.lineEnds.length;
- if (++this.linePtr >= length)
- System.arraycopy(this.lineEnds, 0, this.lineEnds = new int[length + INCREMENT], 0, length);
- this.lineEnds[this.linePtr] = separatorPos;
- // look-ahead for merged cr+lf
- try {
- if (this.source[this.currentPosition] == '\n') {
- //System.out.println("look-ahead LF-" + this.currentPosition);
- this.lineEnds[this.linePtr] = this.currentPosition;
- this.currentPosition++;
- this.wasAcr = false;
- } else {
- this.wasAcr = true;
- }
- } catch(IndexOutOfBoundsException e) {
- this.wasAcr = true;
- }
- } else {
- // lf 000A
- if (this.currentCharacter == '\n') { //must merge eventual cr followed by lf
- if (this.wasAcr && (this.lineEnds[this.linePtr] == (this.currentPosition - 2))) {
- //System.out.println("merge LF-" + (this.currentPosition - 1));
- this.lineEnds[this.linePtr] = this.currentPosition - 1;
- } else {
- int separatorPos = this.currentPosition - 1;
- if ((this.linePtr >= 0) && (this.lineEnds[this.linePtr] >= separatorPos)) return;
- int length = this.lineEnds.length;
- if (++this.linePtr >= length)
- System.arraycopy(this.lineEnds, 0, this.lineEnds = new int[length + INCREMENT], 0, length);
- this.lineEnds[this.linePtr] = separatorPos;
- }
- this.wasAcr = false;
- }
- }
-}
-public final void pushUnicodeLineSeparator() {
- // cr 000D
- if (this.currentCharacter == '\r') {
- if (this.source[this.currentPosition] == '\n') {
- this.wasAcr = false;
- } else {
- this.wasAcr = true;
- }
- } else {
- // lf 000A
- if (this.currentCharacter == '\n') { //must merge eventual cr followed by lf
- this.wasAcr = false;
- }
- }
-}
-
-public void recordComment(int token) {
- // compute position
- int stopPosition = this.currentPosition;
- switch (token) {
- case TokenNameCOMMENT_LINE:
- stopPosition = -this.lastCommentLinePosition;
- break;
- case TokenNameCOMMENT_BLOCK:
- stopPosition = -this.currentPosition;
- break;
- }
-
- // a new comment is recorded
- int length = this.commentStops.length;
- if (++this.commentPtr >= length) {
- int newLength = length + COMMENT_ARRAYS_SIZE*10;
- System.arraycopy(this.commentStops, 0, this.commentStops = new int[newLength], 0, length);
- System.arraycopy(this.commentStarts, 0, this.commentStarts = new int[newLength], 0, length);
- System.arraycopy(this.commentTagStarts, 0, this.commentTagStarts = new int[newLength], 0, length);
- }
- this.commentStops[this.commentPtr] = stopPosition;
- this.commentStarts[this.commentPtr] = this.startPosition;
-}
-
-/**
- * Reposition the scanner on some portion of the original source. The given endPosition is the last valid position.
- * Beyond this position, the scanner will answer EOF tokens (<code>ITerminalSymbols.TokenNameEOF</code>).
- *
- * @param begin the given start position
- * @param end the given end position
- */
-public void resetTo(int begin, int end) {
- //reset the scanner to a given position where it may rescan again
-
- this.diet = false;
- this.initialPosition = this.startPosition = this.currentPosition = begin;
- if (this.source != null && this.eofPosition < end) {
- this.eofPosition = this.source.length;
- } else {
- this.eofPosition = end < Integer.MAX_VALUE ? end + 1 : end;
- }
- this.commentPtr = -1; // reset comment stack
- this.foundTaskCount = 0;
-}
-
-/**
- * Processes an escaped character sequence on the current source position.
- * @return Whether a character was produced. Thus, false in case of a string line continuation.
- * @throws InvalidInputException
- */
-public final boolean scanEscapeCharacter() throws InvalidInputException {
- // the string with "\\u" is a legal string of two chars \ and u
- //thus we use a direct access to the source (for regular cases).
- switch (this.currentCharacter) {
- case 'b' :
- this.currentCharacter = '\b';
- break;
- case 't' :
- this.currentCharacter = '\t';
- break;
- case 'n' :
- this.currentCharacter = '\n';
- break;
- case 'f' :
- this.currentCharacter = '\f';
- break;
- case 'r' :
- this.currentCharacter = '\r';
- break;
- case '\"' :
- this.currentCharacter = '\"';
- break;
- case '\'' :
- this.currentCharacter = '\'';
- break;
- case '\\' :
- this.currentCharacter = '\\';
- break;
- case '\r':
- if (this.source[this.currentPosition] == '\n')
- this.currentPosition++;
- case '\n':
- case '\u2029':
- case '\u2028':
- return false;
- case 'x' :
- int digit1 = ScannerHelper.digit(this.source[this.currentPosition], 16);
- int digit2 = ScannerHelper.digit(this.source[this.currentPosition + 1], 16);
- if ( digit1 != -1 && digit2 != -1 ) {
-
- int number = (digit1 * 16) + digit2;
- this.currentPosition = this.currentPosition + 2;
- this.currentCharacter = (char)number;
- break;
- }
-
- default :
- // -----------octal escape--------------
- // OctalDigit
- // OctalDigit OctalDigit
- // ZeroToThree OctalDigit OctalDigit
-
- int number = ScannerHelper.getNumericValue(this.currentCharacter);
- if (number >= 0 && number <= 7) {
- boolean zeroToThreeNot = number > 3;
- if (ScannerHelper.isDigit(this.currentCharacter = this.source[this.currentPosition++])) {
- int digit = ScannerHelper.getNumericValue(this.currentCharacter);
- if (digit >= 0 && digit <= 7) {
- number = (number * 8) + digit;
- if (ScannerHelper.isDigit(this.currentCharacter = this.source[this.currentPosition++])) {
- if (zeroToThreeNot) {// has read \NotZeroToThree OctalDigit Digit --> ignore last character
- this.currentPosition--;
- } else {
- digit = ScannerHelper.getNumericValue(this.currentCharacter);
- if (digit >= 0 && digit <= 7){ // has read \ZeroToThree OctalDigit OctalDigit
- number = (number * 8) + digit;
- } else {// has read \ZeroToThree OctalDigit NonOctalDigit --> ignore last character
- this.currentPosition--;
- }
- }
- } else { // has read \OctalDigit NonDigit--> ignore last character
- this.currentPosition--;
- }
- } else { // has read \OctalDigit NonOctalDigit--> ignore last character
- this.currentPosition--;
- }
- } else { // has read \OctalDigit --> ignore last character
- this.currentPosition--;
- }
- if (number > 255)
- throw new InvalidInputException(INVALID_ESCAPE);
- this.currentCharacter = (char) number;
- }
-// in JavaScript when a backslash followed by character, the
-// backslash is ignored.
-// else
-// throw new InvalidInputException(INVALID_ESCAPE);
- }
- return true;
-}
-public int scanIdentifierOrKeywordWithBoundCheck() {
- //test keywords
-
- //first dispatch on the first char.
- //then the length. If there are several
- //keywors with the same length AND the same first char, then do another
- //dispatch on the second char
- this.useAssertAsAnIndentifier = false;
- this.useEnumAsAnIndentifier = false;
-
- char[] src = this.source;
- identLoop: {
- int pos;
- int srcLength = this.eofPosition;
- while (true) {
- if ((pos = this.currentPosition) >= srcLength) // handle the obvious case upfront
- break identLoop;
- char c = src[pos];
- if (c < ScannerHelper.MAX_OBVIOUS) {
- if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] &
- (ScannerHelper.C_UPPER_LETTER | ScannerHelper.C_LOWER_LETTER | ScannerHelper.C_IDENT_PART | ScannerHelper.C_DIGIT)) != 0) {
- if (this.withoutUnicodePtr != 0) {
- this.currentCharacter = c;
- unicodeStore();
- }
- this.currentPosition++;
- } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & (ScannerHelper.C_SEPARATOR | ScannerHelper.C_JLS_SPACE)) != 0) {
- this.currentCharacter = c;
- break identLoop;
- } else {
- //System.out.println("slow<=128: "+ c);
- while (getNextCharAsJavaIdentifierPartWithBoundCheck()){/*empty*/}
- break identLoop;
- }
- } else {
- //System.out.println("slow>>128: "+ c);
- while (getNextCharAsJavaIdentifierPartWithBoundCheck()){/*empty*/}
- break identLoop;
- }
- }
- }
-
- int index, length;
- char[] data;
- if (this.withoutUnicodePtr == 0) {
- //quick test on length == 1 but not on length > 12 while most identifier
- //have a length which is <= 12...but there are lots of identifier with
- //only one char....
- if ((length = this.currentPosition - this.startPosition) == 1) {
- return TokenNameIdentifier;
- }
- data = this.source;
- index = this.startPosition;
- } else {
- if ((length = this.withoutUnicodePtr) == 1)
- return TokenNameIdentifier;
- data = this.withoutUnicodeBuffer;
- index = 1;
- }
-
- return internalScanIdentifierOrKeyword(index, length, data);
-}
-public int scanIdentifierOrKeyword() {
- //test keywords
-
- //first dispatch on the first char.
- //then the length. If there are several
- //keywors with the same length AND the same first char, then do another
- //dispatch on the second char
- this.useAssertAsAnIndentifier = false;
- this.useEnumAsAnIndentifier = false;
-
- char[] src = this.source;
- identLoop: {
- int pos;
- int srcLength = this.eofPosition;
- while (true) {
- if ((pos = this.currentPosition) >= srcLength) // handle the obvious case upfront
- break identLoop;
- char c = src[pos];
- if (c < ScannerHelper.MAX_OBVIOUS) {
- if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] &
- (ScannerHelper.C_UPPER_LETTER | ScannerHelper.C_LOWER_LETTER | ScannerHelper.C_IDENT_PART | ScannerHelper.C_DIGIT)) != 0) {
- if (this.withoutUnicodePtr != 0) {
- this.currentCharacter = c;
- unicodeStore();
- }
- this.currentPosition++;
- } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & (ScannerHelper.C_SEPARATOR | ScannerHelper.C_JLS_SPACE)) != 0) {
- this.currentCharacter = c;
- break identLoop;
- } else {
- //System.out.println("slow<=128: "+ c);
- while (getNextCharAsJavaIdentifierPart()){/*empty*/}
- break identLoop;
- }
- } else {
- //System.out.println("slow>>128: "+ c);
- while (getNextCharAsJavaIdentifierPart()){/*empty*/}
- break identLoop;
- }
- }
- }
-
- int index, length;
- char[] data;
- if (this.withoutUnicodePtr == 0) {
- //quick test on length == 1 but not on length > 12 while most identifier
- //have a length which is <= 12...but there are lots of identifier with
- //only one char....
- if ((length = this.currentPosition - this.startPosition) == 1) {
- return TokenNameIdentifier;
- }
- data = this.source;
- index = this.startPosition;
- } else {
- if ((length = this.withoutUnicodePtr) == 1)
- return TokenNameIdentifier;
- data = this.withoutUnicodeBuffer;
- index = 1;
- }
-
- return internalScanIdentifierOrKeyword(index, length, data);
-}
-
-private int internalScanIdentifierOrKeyword(int index, int length, char[] data) {
-
- switch (data[index]) {
-
- case 'a' :
- if (length==8) {
- //abstract
- if ((data[++index] == 'b')
- && (data[++index] == 's')
- && (data[++index] == 't')
- && (data[++index] == 'r')
- && (data[++index] == 'a')
- && (data[++index] == 'c')
- && (data[++index] == 't')) {
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- this.containsAssertKeyword = true;
- return TokenNameabstract;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- } else {
- return TokenNameIdentifier;
- }
- }
- else
- return TokenNameIdentifier;
- case 'b' : //boolean break byte
- switch (length) {
- case 4 :
- if ((data[++index] == 'y') && (data[++index] == 't') && (data[++index] == 'e'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNamebyte;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- else
- return TokenNameIdentifier;
- case 5 :
- if ((data[++index] == 'r')
- && (data[++index] == 'e')
- && (data[++index] == 'a')
- && (data[++index] == 'k'))
- return TokenNamebreak;
- else
- return TokenNameIdentifier;
- case 7 :
- if ((data[++index] == 'o')
- && (data[++index] == 'o')
- && (data[++index] == 'l')
- && (data[++index] == 'e')
- && (data[++index] == 'a')
- && (data[++index] == 'n'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNameboolean;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
-
- else
- return TokenNameIdentifier;
- default :
- return TokenNameIdentifier;
- }
-
- case 'c' : //case char catch const class continue
- switch (length) {
- case 4 :
- if (data[++index] == 'a')
- if ((data[++index] == 's') && (data[++index] == 'e'))
- return TokenNamecase;
- else
- return TokenNameIdentifier;
- else
- if ((data[index] == 'h') && (data[++index] == 'a') && (data[++index] == 'r'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNamechar;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- else
- return TokenNameIdentifier;
- case 5 :
- if (data[++index] == 'a')
- if ((data[++index] == 't') && (data[++index] == 'c') && (data[++index] == 'h'))
- return TokenNamecatch;
- else
- return TokenNameIdentifier;
- else
- if (data[index] == 'l')
- if ((data[++index] == 'a')
- && (data[++index] == 's')
- && (data[++index] == 's'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNameclass;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- else
- return TokenNameIdentifier;
- else if ((data[index] == 'o')
- && (data[++index] == 'n')
- && (data[++index] == 's')
- && (data[++index] == 't'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNameconst;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- else
- return TokenNameIdentifier;
- case 8 :
- if ((data[++index] == 'o')
- && (data[++index] == 'n')
- && (data[++index] == 't')
- && (data[++index] == 'i')
- && (data[++index] == 'n')
- && (data[++index] == 'u')
- && (data[++index] == 'e'))
- return TokenNamecontinue;
- else
- return TokenNameIdentifier;
- default :
- return TokenNameIdentifier;
- }
-
- case 'd' : //default do double
- switch (length) {
- case 2 :
- if ((data[++index] == 'o'))
- return TokenNamedo;
- else
- return TokenNameIdentifier;
- case 6 :
- if (data[++index] == 'o')
- {
- if ((data[++index] == 'u')
- && (data[++index] == 'b')
- && (data[++index] == 'l')
- && (data[++index] == 'e'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNamedouble;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- else
- return TokenNameIdentifier;
- }
- else if (data[index]=='e')
- {
- if ((data[++index] == 'l')
- && (data[++index] == 'e')
- && (data[++index] == 't')
- && (data[++index] == 'e'))
- return TokenNamedelete;
- else
- return TokenNameIdentifier;
-
- }
- else
- return TokenNameIdentifier;
- case 7 :
- if ((data[++index] == 'e')
- && (data[++index] == 'f')
- && (data[++index] == 'a')
- && (data[++index] == 'u')
- && (data[++index] == 'l')
- && (data[++index] == 't'))
- return TokenNamedefault;
- else
- return TokenNameIdentifier;
- case 8 :
-//@GINO: Bug 197987 (Temp Fix)
-// if ((data[++index] == 'e')
-// && (data[++index] == 'b')
-// && (data[++index] == 'u')
-// && (data[++index] == 'g')
-// && (data[++index] == 'g')
-// && (data[++index] == 'e')
-// && (data[++index] == 'r'))
-// return TokenNamedebugger;
-// else
- return TokenNameIdentifier;
- default :
- return TokenNameIdentifier;
- }
- case 'e' : //else extends
- switch (length) {
- case 4 :
- if ((data[++index] == 'l') && (data[++index] == 's') && (data[++index] == 'e'))
- return TokenNameelse;
- else if ((data[index] == 'n')
- && (data[++index] == 'u')
- && (data[++index] == 'm')) {
- if (this.sourceLevel >= ClassFileConstants.JDK1_5) {
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNameenum;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- } else {
- this.useEnumAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- } else {
- return TokenNameIdentifier;
- }
- case 6 :
- if ((data[++index] == 'x')
- && (data[++index] == 'p')
- && (data[++index] == 'o')
- && (data[++index] == 'r')
- && (data[++index] == 't'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNameexport;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- else
- return TokenNameIdentifier;
- case 7 :
- if ((data[++index] == 'x')
- && (data[++index] == 't')
- && (data[++index] == 'e')
- && (data[++index] == 'n')
- && (data[++index] == 'd')
- && (data[++index] == 's'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNameextends;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- else
- return TokenNameIdentifier;
- default :
- return TokenNameIdentifier;
- }
-
- case 'f' : //final finally float for false
- switch (length) {
- case 3 :
- if ((data[++index] == 'o') && (data[++index] == 'r'))
- return TokenNamefor;
- else
- return TokenNameIdentifier;
- case 5 :
- if (data[++index] == 'i')
- if ((data[++index] == 'n')
- && (data[++index] == 'a')
- && (data[++index] == 'l')) {
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNamefinal;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- } else
- return TokenNameIdentifier;
- else
- if (data[index] == 'l')
- if ((data[++index] == 'o')
- && (data[++index] == 'a')
- && (data[++index] == 't'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNamefloat;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- else
- return TokenNameIdentifier;
- else
- if ((data[index] == 'a')
- && (data[++index] == 'l')
- && (data[++index] == 's')
- && (data[++index] == 'e'))
- return TokenNamefalse;
- else
- return TokenNameIdentifier;
- case 7 :
- if ((data[++index] == 'i')
- && (data[++index] == 'n')
- && (data[++index] == 'a')
- && (data[++index] == 'l')
- && (data[++index] == 'l')
- && (data[++index] == 'y'))
- return TokenNamefinally;
- else
- return TokenNameIdentifier;
-
- case 8 :
- if ((data[++index] == 'u')
- && (data[++index] == 'n')
- && (data[++index] == 'c')
- && (data[++index] == 't')
- && (data[++index] == 'i')
- && (data[++index] == 'o')
- && (data[++index] == 'n'))
- return TokenNamefunction;
- else
- return TokenNameIdentifier;
-
- default :
- return TokenNameIdentifier;
- }
- case 'g' : //goto
- if (length == 4) {
- if ((data[++index] == 'o')
- && (data[++index] == 't')
- && (data[++index] == 'o')) {
- return TokenNamegoto;
- }
- } //no goto in java are allowed, so why java removes this keyword ???
- return TokenNameIdentifier;
-
- case 'i' : //if implements import instanceof int interface
- switch (length) {
- case 2 :
- if (data[++index] == 'f')
- return TokenNameif;
- else if (data[index] == 'n')
- return TokenNamein;
- else
- return TokenNameIdentifier;
- case 3 :
- if ((data[++index] == 'n') && (data[++index] == 't'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNameint;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- else
- return TokenNameIdentifier;
- case 6 :
- if ((data[++index] == 'm')
- && (data[++index] == 'p')
- && (data[++index] == 'o')
- && (data[++index] == 'r')
- && (data[++index] == 't'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNameimport;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- else
- return TokenNameIdentifier;
- case 8 :
- if ((data[++index] == 'n')
- && (data[++index] == 'f')
- && (data[++index] == 'i')
- && (data[++index] == 'n')
- && (data[++index] == 'i')
- && (data[++index] == 't')
- && (data[++index] == 'y'))
- return TokenNameinfinity;
- else
- return TokenNameIdentifier;
- case 9 :
- if ((data[++index] == 'n')
- && (data[++index] == 't')
- && (data[++index] == 'e')
- && (data[++index] == 'r')
- && (data[++index] == 'f')
- && (data[++index] == 'a')
- && (data[++index] == 'c')
- && (data[++index] == 'e'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNameinterface;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- else
- return TokenNameIdentifier;
- case 10 :
- if (data[++index] == 'm')
- if ((data[++index] == 'p')
- && (data[++index] == 'l')
- && (data[++index] == 'e')
- && (data[++index] == 'm')
- && (data[++index] == 'e')
- && (data[++index] == 'n')
- && (data[++index] == 't')
- && (data[++index] == 's'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNameimplements;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- else
- return TokenNameIdentifier;
- else
- if ((data[index] == 'n')
- && (data[++index] == 's')
- && (data[++index] == 't')
- && (data[++index] == 'a')
- && (data[++index] == 'n')
- && (data[++index] == 'c')
- && (data[++index] == 'e')
- && (data[++index] == 'o')
- && (data[++index] == 'f'))
- return TokenNameinstanceof;
- else
- return TokenNameIdentifier;
-
- default :
- return TokenNameIdentifier;
- }
-
- case 'l' : //long
- if (length == 4) {
- if ((data[++index] == 'o')
- && (data[++index] == 'n')
- && (data[++index] == 'g')) {
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNamelong;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- }
- }
- return TokenNameIdentifier;
-
- case 'n' : //native new null
- switch (length) {
- case 3 :
- if ((data[++index] == 'e') && (data[++index] == 'w'))
- return TokenNamenew;
- else
- return TokenNameIdentifier;
- case 4 :
- if ((data[++index] == 'u') && (data[++index] == 'l') && (data[++index] == 'l'))
- return TokenNamenull;
- else
- return TokenNameIdentifier;
- case 6 :
- if ((data[++index] == 'a')
- && (data[++index] == 't')
- && (data[++index] == 'i')
- && (data[++index] == 'v')
- && (data[++index] == 'e')) {
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNamenative;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- } else
- return TokenNameIdentifier;
- default :
- return TokenNameIdentifier;
- }
-
- case 'p' : //package private protected public
- switch (length) {
- case 6 :
- if ((data[++index] == 'u')
- && (data[++index] == 'b')
- && (data[++index] == 'l')
- && (data[++index] == 'i')
- && (data[++index] == 'c')) {
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNamepublic;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- } else
- return TokenNameIdentifier;
- case 7 :
- if (data[++index] == 'a')
- if ((data[++index] == 'c')
- && (data[++index] == 'k')
- && (data[++index] == 'a')
- && (data[++index] == 'g')
- && (data[++index] == 'e'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNamepackage;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- else
- return TokenNameIdentifier;
- else
- if ((data[index] == 'r')
- && (data[++index] == 'i')
- && (data[++index] == 'v')
- && (data[++index] == 'a')
- && (data[++index] == 't')
- && (data[++index] == 'e')) {
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNameprivate;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- } else
- return TokenNameIdentifier;
- case 9 :
- if ((data[++index] == 'r')
- && (data[++index] == 'o')
- && (data[++index] == 't')
- && (data[++index] == 'e')
- && (data[++index] == 'c')
- && (data[++index] == 't')
- && (data[++index] == 'e')
- && (data[++index] == 'd')) {
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNameprotected;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- } else
- return TokenNameIdentifier;
-
- default :
- return TokenNameIdentifier;
- }
-
- case 'r' : //return
- if (length == 6) {
- if ((data[++index] == 'e')
- && (data[++index] == 't')
- && (data[++index] == 'u')
- && (data[++index] == 'r')
- && (data[++index] == 'n')) {
- return TokenNamereturn;
- }
- }
- return TokenNameIdentifier;
-
- case 's' : //short static super switch synchronized strictfp
- switch (length) {
- case 5 :
- if (data[++index] == 'h')
- if ((data[++index] == 'o') && (data[++index] == 'r') && (data[++index] == 't'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNameshort;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- else
- return TokenNameIdentifier;
- else
- if ((data[index] == 'u')
- && (data[++index] == 'p')
- && (data[++index] == 'e')
- && (data[++index] == 'r'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNamesuper;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- else
- return TokenNameIdentifier;
-
- case 6 :
- if (data[++index] == 't')
- if ((data[++index] == 'a')
- && (data[++index] == 't')
- && (data[++index] == 'i')
- && (data[++index] == 'c')) {
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNamestatic;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- } else
- return TokenNameIdentifier;
- else
- if ((data[index] == 'w')
- && (data[++index] == 'i')
- && (data[++index] == 't')
- && (data[++index] == 'c')
- && (data[++index] == 'h'))
- return TokenNameswitch;
- else
- return TokenNameIdentifier;
- case 8 :
- if ((data[++index] == 't')
- && (data[++index] == 'r')
- && (data[++index] == 'i')
- && (data[++index] == 'c')
- && (data[++index] == 't')
- && (data[++index] == 'f')
- && (data[++index] == 'p'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNamestrictfp;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- else
- return TokenNameIdentifier;
- case 12 :
- if ((data[++index] == 'y')
- && (data[++index] == 'n')
- && (data[++index] == 'c')
- && (data[++index] == 'h')
- && (data[++index] == 'r')
- && (data[++index] == 'o')
- && (data[++index] == 'n')
- && (data[++index] == 'i')
- && (data[++index] == 'z')
- && (data[++index] == 'e')
- && (data[++index] == 'd')) {
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNamesynchronized;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- } else
- return TokenNameIdentifier;
- default :
- return TokenNameIdentifier;
- }
-
- case 't' : //try throw throws transient this true
- switch (length) {
- case 3 :
- if ((data[++index] == 'r') && (data[++index] == 'y'))
- return TokenNametry;
- else
- return TokenNameIdentifier;
- case 4 :
- if (data[++index] == 'h')
- if ((data[++index] == 'i') && (data[++index] == 's'))
- return TokenNamethis;
- else
- return TokenNameIdentifier;
- else
- if ((data[index] == 'r') && (data[++index] == 'u') && (data[++index] == 'e'))
- return TokenNametrue;
- else
- return TokenNameIdentifier;
- case 5 :
- if ((data[++index] == 'h')
- && (data[++index] == 'r')
- && (data[++index] == 'o')
- && (data[++index] == 'w'))
- return TokenNamethrow;
- else
- return TokenNameIdentifier;
- case 6 :
- if ((data[++index] == 'h')
- && (data[++index] == 'r')
- && (data[++index] == 'o')
- && (data[++index] == 'w')
- && (data[++index] == 's'))
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNamethrows;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- else
- if ((data[index] == 'y')
- && (data[++index] == 'p')
- && (data[++index] == 'e')
- && (data[++index] == 'o')
- && (data[++index] == 'f'))
- return TokenNametypeof;
- else
- return TokenNameIdentifier;
- case 9 :
- if ((data[++index] == 'r')
- && (data[++index] == 'a')
- && (data[++index] == 'n')
- && (data[++index] == 's')
- && (data[++index] == 'i')
- && (data[++index] == 'e')
- && (data[++index] == 'n')
- && (data[++index] == 't')) {
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNametransient;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- } else
- return TokenNameIdentifier;
-
- default :
- return TokenNameIdentifier;
- }
-
- case 'u' : //goto
- if (length == 9) {
- if ((data[++index] == 'n')
- && (data[++index] == 'd')
- && (data[++index] == 'e')
- && (data[++index] == 'f')
- && (data[++index] == 'i')
- && (data[++index] == 'n')
- && (data[++index] == 'e')
- && (data[++index] == 'd')) {
- return TokenNameundefined;
- }
- } //no goto in java are allowed, so why java removes this keyword ???
- return TokenNameIdentifier;
-
- case 'v' : //void volatile
- switch (length) {
- case 3 :
- if ((data[++index] == 'a') && (data[++index] == 'r'))
- return TokenNamevar;
- else
- return TokenNameIdentifier;
- case 4 :
- if ((data[++index] == 'o') && (data[++index] == 'i') && (data[++index] == 'd'))
- return TokenNamevoid;
- else
- return TokenNameIdentifier;
- case 8 :
- if ((data[++index] == 'o')
- && (data[++index] == 'l')
- && (data[++index] == 'a')
- && (data[++index] == 't')
- && (data[++index] == 'i')
- && (data[++index] == 'l')
- && (data[++index] == 'e')) {
- if (this.sourceLevel >= ClassFileConstants.JDK1_4) {
- return TokenNamevolatile;
- } else {
- this.useAssertAsAnIndentifier = true;
- return TokenNameIdentifier;
- }
- } else
- return TokenNameIdentifier;
-
- default :
- return TokenNameIdentifier;
- }
-
- case 'w' : //while widefp
- switch (length) {
- case 4 :
- if ((data[++index] == 'i')
- && (data[++index] == 't')
- && (data[++index] == 'h'))
- return TokenNamewith;
- else
- return TokenNameIdentifier;
- case 5 :
- if ((data[++index] == 'h')
- && (data[++index] == 'i')
- && (data[++index] == 'l')
- && (data[++index] == 'e'))
- return TokenNamewhile;
- else
- return TokenNameIdentifier;
- //case 6:if ( (data[++index] =='i') && (data[++index]=='d') && (data[++index]=='e') && (data[++index]=='f')&& (data[++index]=='p'))
- //return TokenNamewidefp ;
- //else
- //return TokenNameIdentifier;
- default :
- return TokenNameIdentifier;
- }
-
- default :
- return TokenNameIdentifier;
- }
-}
-
-
-public int scanNumber(boolean dotPrefix) throws InvalidInputException {
-
- //when entering this method the currentCharacter is the first
- //digit of the number. It may be preceeded by a '.' when
- //dotPrefix is true
-
- boolean floating = dotPrefix;
- if ((!dotPrefix) && (this.currentCharacter == '0')) {
- if (getNextChar('x', 'X') >= 0) { //----------hexa-----------------
- int start = this.currentPosition;
- while (getNextCharAsDigit(16)){/*empty*/}
- int end = this.currentPosition;
- if (getNextChar('l', 'L') >= 0) {
- if (end == start) {
- throw new InvalidInputException(INVALID_HEXA);
- }
- return TokenNameLongLiteral;
- } else if (getNextChar('.')) {
- if (this.sourceLevel < ClassFileConstants.JDK1_5) {
- if (end == start) {
- throw new InvalidInputException(INVALID_HEXA);
- }
- this.currentPosition = end;
- return TokenNameIntegerLiteral;
- }
- // hexadecimal floating point literal
- // read decimal part
- boolean hasNoDigitsBeforeDot = end == start;
- start = this.currentPosition;
- while (getNextCharAsDigit(16)){/*empty*/}
- end = this.currentPosition;
- if (hasNoDigitsBeforeDot && end == start) {
- throw new InvalidInputException(INVALID_HEXA);
- }
-
- if (getNextChar('p', 'P') >= 0) { // consume next character
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- } else {
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
-
- if ((this.currentCharacter == '-')
- || (this.currentCharacter == '+')) { // consume next character
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- } else {
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
- }
- if (!ScannerHelper.isDigit(this.currentCharacter)) {
- throw new InvalidInputException(INVALID_HEXA);
- }
- while (getNextCharAsDigit()){/*empty*/}
- if (getNextChar('f', 'F') >= 0) {
- return TokenNameFloatingPointLiteral;
- }
- if (getNextChar('d', 'D') >= 0) {
- return TokenNameDoubleLiteral;
- }
- if (getNextChar('l', 'L') >= 0) {
- throw new InvalidInputException(INVALID_HEXA);
- }
- return TokenNameDoubleLiteral;
- } else {
- throw new InvalidInputException(INVALID_HEXA);
- }
- } else if (getNextChar('p', 'P') >= 0) { // consume next character
- if (this.sourceLevel < ClassFileConstants.JDK1_5) {
- // if we are in source level < 1.5 we report an integer literal
- this.currentPosition = end;
- return TokenNameIntegerLiteral;
- }
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- } else {
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
-
- if ((this.currentCharacter == '-')
- || (this.currentCharacter == '+')) { // consume next character
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- } else {
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
- }
- if (!ScannerHelper.isDigit(this.currentCharacter))
- throw new InvalidInputException(INVALID_FLOAT);
- while (getNextCharAsDigit()){/*empty*/}
- if (getNextChar('f', 'F') >= 0)
- return TokenNameFloatingPointLiteral;
- if (getNextChar('d', 'D') >= 0)
- return TokenNameDoubleLiteral;
- if (getNextChar('l', 'L') >= 0) {
- throw new InvalidInputException(INVALID_HEXA);
- }
- return TokenNameDoubleLiteral;
- } else {
- if (end == start)
- throw new InvalidInputException(INVALID_HEXA);
- return TokenNameIntegerLiteral;
- }
- }
-
- //there is x or X in the number
- //potential octal ! ... some one may write 000099.0 ! thus 00100 < 00078.0 is true !!!!! crazy language
- if (getNextCharAsDigit()) { //-------------potential octal-----------------
- while (getNextCharAsDigit()){/*empty*/}
-
- if (getNextChar('l', 'L') >= 0) {
- return TokenNameLongLiteral;
- }
-
- if (getNextChar('f', 'F') >= 0) {
- return TokenNameFloatingPointLiteral;
- }
-
- if (getNextChar('d', 'D') >= 0) {
- return TokenNameDoubleLiteral;
- } else { //make the distinction between octal and float ....
- boolean isInteger = true;
- if (getNextChar('.')) {
- isInteger = false;
- while (getNextCharAsDigit()){/*empty*/}
- }
- if (getNextChar('e', 'E') >= 0) { // consume next character
- isInteger = false;
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- } else {
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
-
- if ((this.currentCharacter == '-')
- || (this.currentCharacter == '+')) { // consume next character
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- } else {
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
- }
- if (!ScannerHelper.isDigit(this.currentCharacter))
- throw new InvalidInputException(INVALID_FLOAT);
- while (getNextCharAsDigit()){/*empty*/}
- }
- if (getNextChar('f', 'F') >= 0)
- return TokenNameFloatingPointLiteral;
- if (getNextChar('d', 'D') >= 0 || !isInteger)
- return TokenNameDoubleLiteral;
- return TokenNameIntegerLiteral;
- }
- } else {
- /* carry on */
- }
- }
-
- while (getNextCharAsDigit()){/*empty*/}
-
- if ((!dotPrefix) && (getNextChar('l', 'L') >= 0))
- return TokenNameLongLiteral;
-
- if ((!dotPrefix) && (getNextChar('.'))) { //decimal part that can be empty
- while (getNextCharAsDigit()){/*empty*/}
- floating = true;
- }
-
- //if floating is true both exponant and suffix may be optional
-
- if (getNextChar('e', 'E') >= 0) {
- floating = true;
- // consume next character
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- } else {
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
-
- if ((this.currentCharacter == '-')
- || (this.currentCharacter == '+')) { // consume next character
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
- } else {
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
- }
- if (!ScannerHelper.isDigit(this.currentCharacter))
- throw new InvalidInputException(INVALID_FLOAT);
- while (getNextCharAsDigit()){/*empty*/}
- }
-
- if (getNextChar('d', 'D') >= 0)
- return TokenNameDoubleLiteral;
- if (getNextChar('f', 'F') >= 0)
- return TokenNameFloatingPointLiteral;
-
- //the long flag has been tested before
-
- return floating ? TokenNameDoubleLiteral : TokenNameIntegerLiteral;
-}
-/**
- * Search the line number corresponding to a specific position
- * @param position int
- * @return int
- */
-public final int getLineNumber(int position) {
- return Util.getLineNumber(position, this.lineEnds, 0, this.linePtr);
-}
-public final void setSource(char[] sourceString){
- //the source-buffer is set to sourceString
-
- int sourceLength;
- if (sourceString == null) {
- this.source = CharOperation.NO_CHAR;
- sourceLength = 0;
- } else {
- this.source = sourceString;
- sourceLength = sourceString.length;
- }
- this.startPosition = -1;
- this.eofPosition = sourceLength;
- this.initialPosition = this.currentPosition = 0;
- this.containsAssertKeyword = false;
- this.linePtr = -1;
-}
-/*
- * Should be used if a parse (usually a diet parse) has already been performed on the unit,
- * so as to get the already computed line end positions.
- */
-public final void setSource(char[] contents, CompilationResult compilationResult) {
- if (contents == null) {
- char[] cuContents = compilationResult.compilationUnit.getContents();
- setSource(cuContents);
- } else {
- setSource(contents);
- }
- int[] lineSeparatorPositions = compilationResult.lineSeparatorPositions;
- if (lineSeparatorPositions != null) {
- this.lineEnds = lineSeparatorPositions;
- this.linePtr = lineSeparatorPositions.length - 1;
- }
-}
-/*
- * Should be used if a parse (usually a diet parse) has already been performed on the unit,
- * so as to get the already computed line end positions.
- */
-public final void setSource(CompilationResult compilationResult) {
- setSource(null, compilationResult);
-}
-public String toString() {
- if (this.startPosition == this.eofPosition)
- return "EOF\n\n" + new String(this.source); //$NON-NLS-1$
- if (this.currentPosition > this.eofPosition)
- return "behind the EOF\n\n" + new String(this.source); //$NON-NLS-1$
-
- char front[] = new char[this.startPosition];
- System.arraycopy(this.source, 0, front, 0, this.startPosition);
-
- int middleLength = (this.currentPosition - 1) - this.startPosition + 1;
- char middle[];
- if (middleLength > -1) {
- middle = new char[middleLength];
- System.arraycopy(
- this.source,
- this.startPosition,
- middle,
- 0,
- middleLength);
- } else {
- middle = CharOperation.NO_CHAR;
- }
-
- char end[] = new char[this.eofPosition - (this.currentPosition - 1)];
- System.arraycopy(
- this.source,
- (this.currentPosition - 1) + 1,
- end,
- 0,
- this.eofPosition - (this.currentPosition - 1) - 1);
-
- return new String(front)
- + "\n===============================\nStarts here -->" //$NON-NLS-1$
- + new String(middle)
- + "<-- Ends here\n===============================\n" //$NON-NLS-1$
- + new String(end);
-}
-
-public String toStringAction(int act) {
- switch (act) {
- case TokenNameIdentifier :
- return "Identifier(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$
- case TokenNameabstract :
- return "abstract"; //$NON-NLS-1$
- case TokenNameboolean :
- return "boolean"; //$NON-NLS-1$
- case TokenNamebreak :
- return "break"; //$NON-NLS-1$
- case TokenNamebyte :
- return "byte"; //$NON-NLS-1$
- case TokenNamecase :
- return "case"; //$NON-NLS-1$
- case TokenNamecatch :
- return "catch"; //$NON-NLS-1$
- case TokenNamechar :
- return "char"; //$NON-NLS-1$
- case TokenNameclass :
- return "class"; //$NON-NLS-1$
- case TokenNamecontinue :
- return "continue"; //$NON-NLS-1$
- case TokenNamedefault :
- return "default"; //$NON-NLS-1$
- case TokenNamedelete :
- return "delete"; //$NON-NLS-1$
- case TokenNamedebugger :
- return "debugger"; //$NON-NLS-1$
- case TokenNamedo :
- return "do"; //$NON-NLS-1$
- case TokenNamedouble :
- return "double"; //$NON-NLS-1$
- case TokenNameelse :
- return "else"; //$NON-NLS-1$
- case TokenNameextends :
- return "extends"; //$NON-NLS-1$
- case TokenNamefalse :
- return "false"; //$NON-NLS-1$
- case TokenNamefinal :
- return "final"; //$NON-NLS-1$
- case TokenNamefinally :
- return "finally"; //$NON-NLS-1$
- case TokenNamefloat :
- return "float"; //$NON-NLS-1$
- case TokenNamefor :
- return "for"; //$NON-NLS-1$
- case TokenNamefunction :
- return "function"; //$NON-NLS-1$
- case TokenNameif :
- return "if"; //$NON-NLS-1$
- case TokenNameimplements :
- return "implements"; //$NON-NLS-1$
- case TokenNameimport :
- return "import"; //$NON-NLS-1$
- case TokenNamein :
- return "in"; //$NON-NLS-1$
- case TokenNameinfinity :
- return "infinity"; //$NON-NLS-1$
- case TokenNameinstanceof :
- return "instanceof"; //$NON-NLS-1$
- case TokenNameint :
- return "int"; //$NON-NLS-1$
- case TokenNameinterface :
- return "interface"; //$NON-NLS-1$
- case TokenNamelong :
- return "long"; //$NON-NLS-1$
- case TokenNamenative :
- return "native"; //$NON-NLS-1$
- case TokenNamenew :
- return "new"; //$NON-NLS-1$
- case TokenNamenull :
- return "null"; //$NON-NLS-1$
- case TokenNamepackage :
- return "package"; //$NON-NLS-1$
- case TokenNameprivate :
- return "private"; //$NON-NLS-1$
- case TokenNameprotected :
- return "protected"; //$NON-NLS-1$
- case TokenNamepublic :
- return "public"; //$NON-NLS-1$
- case TokenNamereturn :
- return "return"; //$NON-NLS-1$
- case TokenNameshort :
- return "short"; //$NON-NLS-1$
- case TokenNamestatic :
- return "static"; //$NON-NLS-1$
- case TokenNamesuper :
- return "super"; //$NON-NLS-1$
- case TokenNameswitch :
- return "switch"; //$NON-NLS-1$
- case TokenNamesynchronized :
- return "synchronized"; //$NON-NLS-1$
- case TokenNamethis :
- return "this"; //$NON-NLS-1$
- case TokenNamethrow :
- return "throw"; //$NON-NLS-1$
- case TokenNamethrows :
- return "throws"; //$NON-NLS-1$
- case TokenNametransient :
- return "transient"; //$NON-NLS-1$
- case TokenNametrue :
- return "true"; //$NON-NLS-1$
- case TokenNametry :
- return "try"; //$NON-NLS-1$
- case TokenNameundefined :
- return "undefined"; //$NON-NLS-1$
- case TokenNamevar :
- return "var"; //$NON-NLS-1$
- case TokenNamevoid :
- return "void"; //$NON-NLS-1$
- case TokenNamevolatile :
- return "volatile"; //$NON-NLS-1$
- case TokenNamewhile :
- return "while"; //$NON-NLS-1$
- case TokenNamewith :
- return "with"; //$NON-NLS-1$
-
-
- case TokenNameIntegerLiteral :
- return "Integer(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$
- case TokenNameLongLiteral :
- return "Long(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$
- case TokenNameFloatingPointLiteral :
- return "Float(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$
- case TokenNameDoubleLiteral :
- return "Double(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$
- case TokenNameCharacterLiteral :
- return "Char(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$
- case TokenNameStringLiteral :
- return "String(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$
-
- case TokenNamePLUS_PLUS :
- return "++"; //$NON-NLS-1$
- case TokenNameMINUS_MINUS :
- return "--"; //$NON-NLS-1$
- case TokenNameEQUAL_EQUAL :
- return "=="; //$NON-NLS-1$
- case TokenNameEQUAL_EQUAL_EQUAL :
- return "==="; //$NON-NLS-1$
- case TokenNameLESS_EQUAL :
- return "<="; //$NON-NLS-1$
- case TokenNameGREATER_EQUAL :
- return ">="; //$NON-NLS-1$
- case TokenNameNOT_EQUAL :
- return "!="; //$NON-NLS-1$
- case TokenNameNOT_EQUAL_EQUAL :
- return "!=="; //$NON-NLS-1$
- case TokenNameLEFT_SHIFT :
- return "<<"; //$NON-NLS-1$
- case TokenNameRIGHT_SHIFT :
- return ">>"; //$NON-NLS-1$
- case TokenNameUNSIGNED_RIGHT_SHIFT :
- return ">>>"; //$NON-NLS-1$
- case TokenNamePLUS_EQUAL :
- return "+="; //$NON-NLS-1$
- case TokenNameMINUS_EQUAL :
- return "-="; //$NON-NLS-1$
- case TokenNameMULTIPLY_EQUAL :
- return "*="; //$NON-NLS-1$
- case TokenNameDIVIDE_EQUAL :
- return "/="; //$NON-NLS-1$
- case TokenNameAND_EQUAL :
- return "&="; //$NON-NLS-1$
- case TokenNameOR_EQUAL :
- return "|="; //$NON-NLS-1$
- case TokenNameXOR_EQUAL :
- return "^="; //$NON-NLS-1$
- case TokenNameREMAINDER_EQUAL :
- return "%="; //$NON-NLS-1$
- case TokenNameLEFT_SHIFT_EQUAL :
- return "<<="; //$NON-NLS-1$
- case TokenNameRIGHT_SHIFT_EQUAL :
- return ">>="; //$NON-NLS-1$
- case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL :
- return ">>>="; //$NON-NLS-1$
- case TokenNameOR_OR :
- return "||"; //$NON-NLS-1$
- case TokenNameAND_AND :
- return "&&"; //$NON-NLS-1$
- case TokenNamePLUS :
- return "+"; //$NON-NLS-1$
- case TokenNameMINUS :
- return "-"; //$NON-NLS-1$
- case TokenNameNOT :
- return "!"; //$NON-NLS-1$
- case TokenNameREMAINDER :
- return "%"; //$NON-NLS-1$
- case TokenNameXOR :
- return "^"; //$NON-NLS-1$
- case TokenNameAND :
- return "&"; //$NON-NLS-1$
- case TokenNameMULTIPLY :
- return "*"; //$NON-NLS-1$
- case TokenNameOR :
- return "|"; //$NON-NLS-1$
- case TokenNameTWIDDLE :
- return "~"; //$NON-NLS-1$
- case TokenNameDIVIDE :
- return "/"; //$NON-NLS-1$
- case TokenNameGREATER :
- return ">"; //$NON-NLS-1$
- case TokenNameLESS :
- return "<"; //$NON-NLS-1$
- case TokenNameLPAREN :
- return "("; //$NON-NLS-1$
- case TokenNameRPAREN :
- return ")"; //$NON-NLS-1$
- case TokenNameLBRACE :
- return "{"; //$NON-NLS-1$
- case TokenNameRBRACE :
- return "}"; //$NON-NLS-1$
- case TokenNameLBRACKET :
- return "["; //$NON-NLS-1$
- case TokenNameRBRACKET :
- return "]"; //$NON-NLS-1$
- case TokenNameSEMICOLON :
- return ";"; //$NON-NLS-1$
- case TokenNameQUESTION :
- return "?"; //$NON-NLS-1$
- case TokenNameCOLON :
- return ":"; //$NON-NLS-1$
- case TokenNameCOMMA :
- return ","; //$NON-NLS-1$
- case TokenNameDOT :
- return "."; //$NON-NLS-1$
- case TokenNameEQUAL :
- return "="; //$NON-NLS-1$
- case TokenNameEOF :
- return "EOF"; //$NON-NLS-1$
- case TokenNameWHITESPACE :
- return "white_space(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$
- default :
- return "not-a-token"; //$NON-NLS-1$
- }
-}
-
-public void unicodeInitializeBuffer(int length) {
- this.withoutUnicodePtr = length;
- if (this.withoutUnicodeBuffer == null) this.withoutUnicodeBuffer = new char[length+(1+10)];
- int bLength = this.withoutUnicodeBuffer.length;
- if (1+length >= bLength) {
- System.arraycopy(this.withoutUnicodeBuffer, 0, this.withoutUnicodeBuffer = new char[length + (1+10)], 0, bLength);
- }
- System.arraycopy(this.source, this.startPosition, this.withoutUnicodeBuffer, 1, length);
-}
-public void unicodeStore() {
- int pos = ++this.withoutUnicodePtr;
- if (this.withoutUnicodeBuffer == null) this.withoutUnicodeBuffer = new char[10];
- int length = this.withoutUnicodeBuffer.length;
- if (pos == length) {
- System.arraycopy(this.withoutUnicodeBuffer, 0, this.withoutUnicodeBuffer = new char[length * 2], 0, length);
- }
- this.withoutUnicodeBuffer[pos] = this.currentCharacter;
-}
-protected boolean checkIfDivide(int previousToken){
-
- if (previousToken == TokenNameIdentifier || previousToken == TokenNameStringLiteral ||
- previousToken == TokenNameCharacterLiteral ||
- previousToken == TokenNameIntegerLiteral ||
- previousToken == TokenNameRPAREN ||
- previousToken == TokenNameRBRACKET) {
-
- return true;
- }
-
- return false;
-}
-/*
- * This code is duplicated in PublicScanner.java
- */
-
-public static final String NON_TERM_REGEXP = Messages.Scanner_NON_TERM_REGEXP;
-public static final String INVALID_REGEXP_OPT = Messages.Scanner_INVALID_REGEXP_OPT;
-public static final String UNEXP_REGEXP = Messages.Scanner_UNEXP_REGEXP;
-
-
-protected boolean checkIfRegExp() throws IndexOutOfBoundsException, InvalidInputException {
- // Try to process as regular expression
-
- int regExpPosition = this.currentPosition;
-// char regexpCharacter = this.currentCharacter;
- char orginalCharacter = this.currentCharacter;
- char previousCharacter = this.currentCharacter;
- int previousPosition = this.currentPosition;
- int previousUnicodePtr = this.withoutUnicodePtr;
- boolean regExp = false;
-
- // consume next character
- this.unicodeAsBackSlash = false;
-// boolean isUnicode = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
-// isUnicode = true;
- } else {
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
-
- try {
- while (this.currentCharacter != '/' &&
- this.currentCharacter != '\r' && this.currentCharacter != '\n') {
-
- if (this.currentCharacter == '\\') {
- if (this.unicodeAsBackSlash) {
- this.withoutUnicodePtr--;
- // consume next character
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
-// isUnicode = true;
- this.withoutUnicodePtr--;
- } else {
-// isUnicode = false;
- }
- } else {
- if (this.withoutUnicodePtr == 0) {
- unicodeInitializeBuffer(this.currentPosition - this.startPosition);
- }
- this.withoutUnicodePtr --;
- this.currentCharacter = this.source[this.currentPosition++];
- }
- // we need to compute the escape character in a separate buffer
- if (scanEscapeCharacter() && this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
-
- // consume next character
- previousCharacter=this.currentCharacter;
- previousPosition=this.currentPosition;
- previousUnicodePtr=this.withoutUnicodePtr;
- this.unicodeAsBackSlash = false;
- if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\')
- && (this.source[this.currentPosition] == 'u')) {
- getNextUnicodeChar();
-// isUnicode = true;
- } else {
-// isUnicode = false;
- if (this.withoutUnicodePtr != 0) {
- unicodeStore();
- }
- }
-
- if (this.currentCharacter == '/') {
- regExp = true;
- }
-
- }
-
- // Check for valid RegExp options
- if (regExp == true) {
- boolean haverexExpCharI = false;
- boolean haverexExpCharG = false;
- boolean haverexExpCharM = false;
- for (int count =0; count<=3; count++) {
- previousCharacter=this.currentCharacter;
- previousPosition=this.currentPosition;
- previousUnicodePtr=this.withoutUnicodePtr;
- if (getNextChar() != -1) {
- if (Character.isLetterOrDigit(this.currentCharacter)){
- if (this.currentCharacter == 'i' && haverexExpCharI == false) {
- haverexExpCharI = true;
- } else if (this.currentCharacter == 'g' && haverexExpCharG == false) {
- haverexExpCharG = true;
- } else if (this.currentCharacter == 'm' && haverexExpCharM == false) {
- haverexExpCharM = true;
- } else {
- if (count != 3)
- throw new InvalidInputException(INVALID_REGEXP_OPT);
- }
- } else {
- break;
- }
- } else {
- // Just fall through, may be end of file.
- }
- }
- }
- } catch (IndexOutOfBoundsException e) {
- throw new InvalidInputException(NON_TERM_REGEXP);
- }
-
- if (regExp == false){
- this.currentCharacter=orginalCharacter;
- this.currentPosition=regExpPosition;
- return false;
- }
- // Back up one character
- this.currentCharacter = previousCharacter;
- this.currentPosition = previousPosition;
- this.withoutUnicodePtr = previousUnicodePtr;
- return true;
-
-
-/* this.currentPosition = regExpPosition;
- this.currentCharacter = regexpCharacter;
- this.currentCharacter = orginalCharaceter;
- this.withoutUnicodePtr = 0; */
-
-}
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/RecordedParsingInformation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/RecordedParsingInformation.java
deleted file mode 100644
index 135ff3ab..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/RecordedParsingInformation.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2002, 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
- * 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.compiler.CategorizedProblem;
-import org.eclipse.wst.jsdt.internal.compiler.CompilationResult;
-
-/**
- * Use to keep track of recorded information during the parsing like comment positions,
- * line ends or problems.
- */
-public class RecordedParsingInformation {
- public CategorizedProblem[] problems;
- public int problemsCount;
- public int[] lineEnds;
- public int[][] commentPositions;
-
- public RecordedParsingInformation(CategorizedProblem[] problems, int[] lineEnds, int[][] commentPositions) {
- this.problems = problems;
- this.lineEnds = lineEnds;
- this.commentPositions = commentPositions;
- this.problemsCount = problems != null ? problems.length : 0;
- }
-
- void updateRecordedParsingInformation(CompilationResult compilationResult) {
- if (compilationResult.problems != null) {
- this.problems = compilationResult.problems;
- this.problemsCount = this.problems.length;
- }
- }
-}
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
deleted file mode 100644
index e30e2c26..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ReferenceInfoAdapter.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.util;
-
-/**
- * An adapter which implements the methods for handling
- * reference information from the parser.
- */
-public abstract class ReferenceInfoAdapter {
-/**
- * Does nothing.
- */
-public void acceptConstructorReference(char[] typeName, int argCount, int sourcePosition) {
- // Does nothing
-}
-/**
- * Does nothing.
- */
-public void acceptFieldReference(char[] fieldName, int sourcePosition) {
- // Does nothing
-}
-/**
- * Does nothing.
- */
-public void acceptMethodReference(char[] methodName, int argCount, int sourcePosition) {
- // Does nothing
-}
-/**
- * Does nothing.
- */
-public void acceptTypeReference(char[][] typeName, int sourceStart, int sourceEnd) {
- // Does nothing
-}
-/**
- * Does nothing.
- */
-public void acceptTypeReference(char[] typeName, int sourcePosition) {
- // Does nothing
-}
-/**
- * Does nothing.
- */
-public void acceptUnknownReference(char[][] name, int sourceStart, int sourceEnd) {
- // Does nothing
-}
-/**
- * Does nothing.
- */
-public void acceptUnknownReference(char[] name, 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
deleted file mode 100644
index e5e7db1f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ResourceCompilationUnit.java
+++ /dev/null
@@ -1,43 +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.util;
-
-import java.net.URI;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.compiler.batch.CompilationUnit;
-
-/**
- * An IJavaScriptUnit that retrieves its contents using an IFile
- */
-public class ResourceCompilationUnit extends CompilationUnit {
-
- protected IFile file;
-
- public ResourceCompilationUnit(IFile file, URI location) {
- super(null/*no contents*/, location == null ? file.getFullPath().toString() : location.getPath(), null/*encoding is used only when retrieving the contents*/);
- this.file = file;
- }
-
- public char[] getContents() {
- if (this.contents != null)
- return this.contents; // answer the cached source
-
- // otherwise retrieve it
- try {
- return Util.getResourceContentsAsCharArray(this.file);
- } catch (CoreException e) {
- return CharOperation.NO_CHAR;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/SimpleDocument.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/SimpleDocument.java
deleted file mode 100644
index 1ebb3fc1..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/SimpleDocument.java
+++ /dev/null
@@ -1,371 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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.jface.text.IDocument;
-import org.eclipse.jface.text.IDocumentListener;
-import org.eclipse.jface.text.IDocumentPartitioner;
-import org.eclipse.jface.text.IDocumentPartitioningListener;
-import org.eclipse.jface.text.IPositionUpdater;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITypedRegion;
-import org.eclipse.jface.text.Position;
-
-/**
- * Minimal implementation of IDocument to apply text edit onto a string.
- */
-public class SimpleDocument implements IDocument {
-
- private StringBuffer buffer;
-
-
- public SimpleDocument(String source) {
- this.buffer = new StringBuffer(source);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#getChar(int)
- */
- public char getChar(int offset) {
- return 0;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#getLength()
- */
- public int getLength() {
- return this.buffer.length();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#get()
- */
- public String get() {
- return this.buffer.toString();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#get(int, int)
- */
- public String get(int offset, int length) {
- return this.buffer.substring(offset, offset + length);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#set(java.lang.String)
- */
- public void set(String text) {
- // defining interface method
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#replace(int, int, java.lang.String)
- */
- public void replace(int offset, int length, String text) {
-
- this.buffer.replace(offset, offset + length, text);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#addDocumentListener(org.eclipse.jface.text.IDocumentListener)
- */
- public void addDocumentListener(IDocumentListener listener) {
- // defining interface method
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#removeDocumentListener(org.eclipse.jface.text.IDocumentListener)
- */
- public void removeDocumentListener(IDocumentListener listener) {
- // defining interface method
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#addPrenotifiedDocumentListener(org.eclipse.jface.text.IDocumentListener)
- */
- public void addPrenotifiedDocumentListener(IDocumentListener documentAdapter) {
- // defining interface method
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#removePrenotifiedDocumentListener(org.eclipse.jface.text.IDocumentListener)
- */
- public void removePrenotifiedDocumentListener(IDocumentListener documentAdapter) {
- // defining interface method
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#addPositionCategory(java.lang.String)
- */
- public void addPositionCategory(String category) {
- // defining interface method
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#removePositionCategory(java.lang.String)
- */
- public void removePositionCategory(String category) {
- // defining interface method
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#getPositionCategories()
- */
- public String[] getPositionCategories() {
- // defining interface method
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#containsPositionCategory(java.lang.String)
- */
- public boolean containsPositionCategory(String category) {
- // defining interface method
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#addPosition(org.eclipse.jface.text.Position)
- */
- public void addPosition(Position position) {
- // defining interface method
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#removePosition(org.eclipse.jface.text.Position)
- */
- public void removePosition(Position position) {
- // defining interface method
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#addPosition(java.lang.String, org.eclipse.jface.text.Position)
- */
- public void addPosition(String category, Position position) {
- // defining interface method
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#removePosition(java.lang.String, org.eclipse.jface.text.Position)
- */
- public void removePosition(String category, Position position) {
- // defining interface method
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#getPositions(java.lang.String)
- */
- public Position[] getPositions(String category) {
- // defining interface method
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#containsPosition(java.lang.String, int, int)
- */
- public boolean containsPosition(String category, int offset, int length) {
- // defining interface method
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#computeIndexInCategory(java.lang.String, int)
- */
- public int computeIndexInCategory(String category, int offset) {
- // defining interface method
- return 0;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#addPositionUpdater(org.eclipse.jface.text.IPositionUpdater)
- */
- public void addPositionUpdater(IPositionUpdater updater) {
- // defining interface method
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#removePositionUpdater(org.eclipse.jface.text.IPositionUpdater)
- */
- public void removePositionUpdater(IPositionUpdater updater) {
- // defining interface method
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#insertPositionUpdater(org.eclipse.jface.text.IPositionUpdater, int)
- */
- public void insertPositionUpdater(IPositionUpdater updater, int index) {
- // defining interface method
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#getPositionUpdaters()
- */
- public IPositionUpdater[] getPositionUpdaters() {
- // defining interface method
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#getLegalContentTypes()
- */
- public String[] getLegalContentTypes() {
- // defining interface method
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#getContentType(int)
- */
- public String getContentType(int offset) {
- // defining interface method
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#getPartition(int)
- */
- public ITypedRegion getPartition(int offset) {
- // defining interface method
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#computePartitioning(int, int)
- */
- public ITypedRegion[] computePartitioning(int offset, int length) {
- // defining interface method
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#addDocumentPartitioningListener(org.eclipse.jface.text.IDocumentPartitioningListener)
- */
- public void addDocumentPartitioningListener(IDocumentPartitioningListener listener) {
- // defining interface method
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#removeDocumentPartitioningListener(org.eclipse.jface.text.IDocumentPartitioningListener)
- */
- public void removeDocumentPartitioningListener(IDocumentPartitioningListener listener) {
- // defining interface method
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#setDocumentPartitioner(org.eclipse.jface.text.IDocumentPartitioner)
- */
- public void setDocumentPartitioner(IDocumentPartitioner partitioner) {
- // defining interface method
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#getDocumentPartitioner()
- */
- public IDocumentPartitioner getDocumentPartitioner() {
- // defining interface method
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#getLineLength(int)
- */
- public int getLineLength(int line) {
- // defining interface method
- return 0;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#getLineOfOffset(int)
- */
- public int getLineOfOffset(int offset) {
- // defining interface method
- return 0;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#getLineOffset(int)
- */
- public int getLineOffset(int line) {
- // defining interface method
- return 0;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#getLineInformation(int)
- */
- public IRegion getLineInformation(int line) {
- // defining interface method
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#getLineInformationOfOffset(int)
- */
- public IRegion getLineInformationOfOffset(int offset) {
- // defining interface method
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#getNumberOfLines()
- */
- public int getNumberOfLines() {
- // defining interface method
- return 0;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#getNumberOfLines(int, int)
- */
- public int getNumberOfLines(int offset, int length) {
- // defining interface method
- return 0;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#computeNumberOfLines(java.lang.String)
- */
- public int computeNumberOfLines(String text) {
- // defining interface method
- return 0;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#getLegalLineDelimiters()
- */
- public String[] getLegalLineDelimiters() {
- // defining interface method
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.IDocument#getLineDelimiter(int)
- */
- public String getLineDelimiter(int line) {
- // defining interface method
- return null;
- }
-
- /**
- * @see org.eclipse.jface.text.IDocument#search(int, java.lang.String, boolean, boolean, boolean)
- * @deprecated
- */
- public int search(
- int startOffset,
- String findString,
- boolean forwardSearch,
- boolean caseSensitive,
- boolean wholeWord) {
- // defining interface method
- return 0;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/SimpleWordSet.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/SimpleWordSet.java
deleted file mode 100644
index cfd1c97e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/SimpleWordSet.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * 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.compiler.CharOperation;
-
-public final class SimpleWordSet {
-
-// to avoid using Enumerations, walk the individual values skipping nulls
-public char[][] words;
-public int elementSize; // number of elements in the table
-public int threshold;
-
-public SimpleWordSet(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.words = new char[extraRoom][];
-}
-
-public char[] add(char[] word) {
- int length = this.words.length;
- int index = CharOperation.hashCode(word) % length;
- char[] current;
- while ((current = words[index]) != null) {
- if (CharOperation.equals(current, word)) return current;
- if (++index == length) index = 0;
- }
- words[index] = word;
-
- // assumes the threshold is never equal to the size of the table
- if (++elementSize > threshold) rehash();
- return word;
-}
-
-public boolean includes(char[] word) {
- int length = this.words.length;
- int index = CharOperation.hashCode(word) % length;
- char[] current;
- while ((current = words[index]) != null) {
- if (CharOperation.equals(current, word)) return true;
- if (++index == length) index = 0;
- }
- return false;
-}
-
-private void rehash() {
- SimpleWordSet newSet = new SimpleWordSet(elementSize * 2); // double the number of expected elements
- char[] current;
- for (int i = words.length; --i >= 0;)
- if ((current = words[i]) != null)
- newSet.add(current);
-
- this.words = newSet.words;
- this.elementSize = newSet.elementSize;
- this.threshold = newSet.threshold;
-}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ToStringSorter.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ToStringSorter.java
deleted file mode 100644
index 13461ef1..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ToStringSorter.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.util;
-
-/**
- * The SortOperation takes a collection of objects and returns
- * a sorted collection of these objects. The sorting of these
- * objects is based on their toString(). They are sorted in
- * alphabetical order.
- */
-public class ToStringSorter {
- Object[] sortedObjects;
- String[] sortedStrings;
-/**
- * Returns true if stringTwo is 'greater than' stringOne
- * This is the 'ordering' method of the sort operation.
- */
-public boolean compare(String stringOne, String stringTwo) {
- return stringOne.compareTo(stringTwo) < 0;
-}
-/**
- * Sort the objects in sorted collection and return that collection.
- */
-private void quickSort(int left, int right) {
- int originalLeft = left;
- int originalRight = right;
- int midIndex = left + (right - left) / 2;
- String midToString = this.sortedStrings[midIndex];
-
- do {
- while (compare(this.sortedStrings[left], midToString))
- left++;
- while (compare(midToString, this.sortedStrings[right]))
- right--;
- if (left <= right) {
- Object tmp = this.sortedObjects[left];
- this.sortedObjects[left] = this.sortedObjects[right];
- this.sortedObjects[right] = tmp;
- String tmpToString = this.sortedStrings[left];
- this.sortedStrings[left] = this.sortedStrings[right];
- this.sortedStrings[right] = tmpToString;
- left++;
- right--;
- }
- } while (left <= right);
-
- if (originalLeft < right)
- quickSort(originalLeft, right);
- if (left < originalRight)
- quickSort(left, originalRight);
-}
-/**
- * Return a new sorted collection from this unsorted collection.
- * Sort using quick sort.
- */
-public void sort(Object[] unSortedObjects, String[] unsortedStrings) {
- int size = unSortedObjects.length;
- this.sortedObjects = new Object[size];
- this.sortedStrings = new String[size];
-
- //copy the array so can return a new sorted collection
- System.arraycopy(unSortedObjects, 0, this.sortedObjects, 0, size);
- System.arraycopy(unsortedStrings, 0, this.sortedStrings, 0, size);
- if (size > 1)
- quickSort(0, size - 1);
-}
-}
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
deleted file mode 100644
index 4def4c9f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/Util.java
+++ /dev/null
@@ -1,2697 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.util;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.PrintStream;
-import java.net.URI;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.StringTokenizer;
-
-import org.eclipse.core.filesystem.EFS;
-import org.eclipse.core.filesystem.IFileStore;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ProjectScope;
-import org.eclipse.core.resources.ResourceAttributes;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.QualifiedName;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.content.IContentType;
-import org.eclipse.core.runtime.preferences.IScopeContext;
-import org.eclipse.core.runtime.preferences.InstanceScope;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.text.edits.MalformedTreeException;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatusConstants;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-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.Signature;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ArrayType;
-import org.eclipse.wst.jsdt.core.dom.InferredType;
-import org.eclipse.wst.jsdt.core.dom.PrimitiveType;
-import org.eclipse.wst.jsdt.core.dom.QualifiedType;
-import org.eclipse.wst.jsdt.core.dom.SimpleType;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.infer.IInferEngine;
-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.TypeReference;
-import org.eclipse.wst.jsdt.internal.compiler.parser.ScannerHelper;
-import org.eclipse.wst.jsdt.internal.compiler.util.SuffixConstants;
-import org.eclipse.wst.jsdt.internal.core.JavaElement;
-import org.eclipse.wst.jsdt.internal.core.JavaModelManager;
-import org.eclipse.wst.jsdt.internal.core.PackageFragmentRoot;
-import org.eclipse.wst.jsdt.internal.oaametadata.IOAAMetaDataConstants;
-
-/**
- * Provides convenient utility methods to other types in this package.
- */
-public class Util {
-
- public interface Comparable {
- /**
- * Returns 0 if this and c are equal, >0 if this is greater than c,
- * or <0 if this is less than c.
- */
- int compareTo(Comparable c);
- }
-
- public interface Comparer {
- /**
- * Returns 0 if a and b are equal, >0 if a is greater than b,
- * or <0 if a is less than b.
- */
- int compare(Object a, Object b);
- }
- private static final String ARGUMENTS_DELIMITER = "#"; //$NON-NLS-1$
-
- private static final String EMPTY_ARGUMENT = " "; //$NON-NLS-1$
-
- private static char[][] JAVA_LIKE_EXTENSIONS;
- public static boolean ENABLE_JAVA_LIKE_EXTENSIONS = true;
-
- private static final char[] VOID = "void".toCharArray(); //$NON-NLS-1$
- private static final char[] INIT = "<init>".toCharArray(); //$NON-NLS-1$
-
- private Util() {
- // cannot be instantiated
- }
- public static boolean isSameResourceString(String path1, String tail) {
- if(path1==null || tail==null) return false;
- int index = path1.toLowerCase().indexOf(tail.toLowerCase());
- return (index >-1 && (index + tail.length() == path1.length()));
-
- }
-
- public static boolean isSameResourceString(IPath path1, IPath tail) {
- return isSameResourceString(path1.toString(), tail.toString());
- }
-
- /**
- * Returns a new array adding the second array at the end of first array.
- * It answers null if the first and second are null.
- * If the first array is null or if it is empty, then a new array is created with second.
- * If the second array is null, then the first array is returned.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * first = null
- * second = "a"
- * => result = {"a"}
- * </pre>
- * <li><pre>
- * first = {"a"}
- * second = null
- * => result = {"a"}
- * </pre>
- * </li>
- * <li><pre>
- * first = {"a"}
- * second = {"b"}
- * => result = {"a", "b"}
- * </pre>
- * </li>
- * </ol>
- *
- * @param first the first array to concatenate
- * @param second the array to add at the end of the first array
- * @return a new array adding the second array at the end of first array, or null if the two arrays are null.
- */
- public static final String[] arrayConcat(String[] first, String second) {
- if (second == null)
- return first;
- if (first == null)
- return new String[] {second};
-
- int length = first.length;
- if (first.length == 0) {
- return new String[] {second};
- }
-
- String[] result = new String[length + 1];
- System.arraycopy(first, 0, result, 0, length);
- result[length] = second;
- return result;
- }
-
- /**
- * Checks the type signature in String sig,
- * starting at start and ending before end (end is not included).
- * Returns the index of the character immediately after the signature if valid,
- * or -1 if not valid.
- */
- private static int checkTypeSignature(String sig, int start, int end, boolean allowVoid) {
- if (start >= end) return -1;
- int i = start;
- char c = sig.charAt(i++);
- int nestingDepth = 0;
- while (c == '[') {
- ++nestingDepth;
- if (i >= end) return -1;
- c = sig.charAt(i++);
- }
- switch (c) {
- case 'B':
- case 'C':
- case 'D':
- case 'F':
- case 'I':
- case 'J':
- case 'S':
- case 'Z':
- break;
- case 'V':
- if (!allowVoid) return -1;
- // array of void is not allowed
- if (nestingDepth != 0) return -1;
- break;
- case 'L':
- int semicolon = sig.indexOf(';', i);
- // Must have at least one character between L and ;
- if (semicolon <= i || semicolon >= end) return -1;
- i = semicolon + 1;
- break;
- default:
- return -1;
- }
- return i;
- }
-
- /**
- * Combines two hash codes to make a new one.
- */
- public static int combineHashCodes(int hashCode1, int hashCode2) {
- return hashCode1 * 17 + hashCode2;
- }
-
- /**
- * Compares two byte arrays.
- * Returns <0 if a byte in a is less than the corresponding byte in b, or if a is shorter, or if a is null.
- * Returns >0 if a byte in a is greater than the corresponding byte in b, or if a is longer, or if b is null.
- * Returns 0 if they are equal or both null.
- */
- public static int compare(byte[] a, byte[] b) {
- if (a == b)
- return 0;
- if (a == null)
- return -1;
- if (b == null)
- return 1;
- int len = Math.min(a.length, b.length);
- for (int i = 0; i < len; ++i) {
- int diff = a[i] - b[i];
- if (diff != 0)
- return diff;
- }
- if (a.length > len)
- return 1;
- if (b.length > len)
- return -1;
- return 0;
- }
- /**
- * Compares two strings lexicographically.
- * The comparison is based on the Unicode value of each character in
- * the strings.
- *
- * @return the value <code>0</code> if the str1 is equal to str2;
- * a value less than <code>0</code> if str1
- * is lexicographically less than str2;
- * and a value greater than <code>0</code> if str1 is
- * lexicographically greater than str2.
- */
- public static int compare(char[] str1, char[] str2) {
- int len1= str1.length;
- int len2= str2.length;
- int n= Math.min(len1, len2);
- int i= 0;
- while (n-- != 0) {
- char c1= str1[i];
- char c2= str2[i++];
- if (c1 != c2) {
- return c1 - c2;
- }
- }
- return len1 - len2;
- }
-
- /**
- * Concatenate two strings with a char in between.
- * @see #concat(String, String)
- */
- public static String concat(String s1, char c, String s2) {
- if (s1 == null) s1 = "null"; //$NON-NLS-1$
- if (s2 == null) s2 = "null"; //$NON-NLS-1$
- int l1 = s1.length();
- int l2 = s2.length();
- char[] buf = new char[l1 + 1 + l2];
- s1.getChars(0, l1, buf, 0);
- buf[l1] = c;
- s2.getChars(0, l2, buf, l1 + 1);
- return new String(buf);
- }
-
- /**
- * Concatenate two strings.
- * Much faster than using +, which:
- * - creates a StringBuffer,
- * - which is synchronized,
- * - of default size, so the resulting char array is
- * often larger than needed.
- * This implementation creates an extra char array, since the
- * String constructor copies its argument, but there's no way around this.
- */
- public static String concat(String s1, String s2) {
- if (s1 == null) s1 = "null"; //$NON-NLS-1$
- if (s2 == null) s2 = "null"; //$NON-NLS-1$
- int l1 = s1.length();
- int l2 = s2.length();
- char[] buf = new char[l1 + l2];
- s1.getChars(0, l1, buf, 0);
- s2.getChars(0, l2, buf, l1);
- return new String(buf);
- }
-
- /**
- * Returns the concatenation of the given array parts using the given separator between each part.
- * <br>
- * <br>
- * For example:<br>
- * <ol>
- * <li><pre>
- * array = {"a", "b"}
- * separator = '.'
- * => result = "a.b"
- * </pre>
- * </li>
- * <li><pre>
- * array = {}
- * separator = '.'
- * => result = ""
- * </pre></li>
- * </ol>
- *
- * @param array the given array
- * @param separator the given separator
- * @return the concatenation of the given array parts using the given separator between each part
- */
- public static final String concatWith(String[] array, char separator) {
- StringBuffer buffer = new StringBuffer();
- for (int i = 0, length = array.length; i < length; i++) {
- buffer.append(array[i]);
- if (i < length - 1)
- buffer.append(separator);
- }
- return buffer.toString();
- }
-
- /**
- * Returns the concatenation of the given array parts using the given separator between each
- * part and appending the given name at the end.
- * <br>
- * <br>
- * For example:<br>
- * <ol>
- * <li><pre>
- * name = "c"
- * array = { "a", "b" }
- * separator = '.'
- * => result = "a.b.c"
- * </pre>
- * </li>
- * <li><pre>
- * name = null
- * array = { "a", "b" }
- * separator = '.'
- * => result = "a.b"
- * </pre></li>
- * <li><pre>
- * name = " c"
- * array = null
- * separator = '.'
- * => result = "c"
- * </pre></li>
- * </ol>
- *
- * @param array the given array
- * @param name the given name
- * @param separator the given separator
- * @return the concatenation of the given array parts using the given separator between each
- * part and appending the given name at the end
- */
- public static final String concatWith(
- String[] array,
- String name,
- char separator) {
-
- if (array == null || array.length == 0) return name;
- if (name == null || name.length() == 0) return concatWith(array, separator);
- StringBuffer buffer = new StringBuffer();
- for (int i = 0, length = array.length; i < length; i++) {
- buffer.append(array[i]);
- buffer.append(separator);
- }
- buffer.append(name);
- return buffer.toString();
-
- }
-
- /**
- * Concatenate three strings.
- * @see #concat(String, String)
- */
- public static String concat(String s1, String s2, String s3) {
- if (s1 == null) s1 = "null"; //$NON-NLS-1$
- if (s2 == null) s2 = "null"; //$NON-NLS-1$
- if (s3 == null) s3 = "null"; //$NON-NLS-1$
- int l1 = s1.length();
- int l2 = s2.length();
- int l3 = s3.length();
- char[] buf = new char[l1 + l2 + l3];
- s1.getChars(0, l1, buf, 0);
- s2.getChars(0, l2, buf, l1);
- s3.getChars(0, l3, buf, l1 + l2);
- return new String(buf);
- }
-
- /**
- * Converts a type signature from the IBinaryType representation to the DC representation.
- */
- public static String convertTypeSignature(char[] sig, int start, int length) {
- return new String(sig, start, length).replace('/', '.');
- }
-
- /*
- * Returns the default java extension (".js").
- * To be used when the extension is not known.
- */
- public static String defaultJavaExtension() {
- return SuffixConstants.SUFFIX_STRING_java;
- }
-
- /**
- * Apply the given edit on the given string and return the updated string.
- * Return the given string if anything wrong happen while applying the edit.
- *
- * @param original the given string
- * @param edit the given edit
- *
- * @return the updated string
- */
- public final static String editedString(String original, TextEdit edit) {
- if (edit == null) {
- return original;
- }
- SimpleDocument document = new SimpleDocument(original);
- try {
- edit.apply(document, TextEdit.NONE);
- return document.get();
- } catch (MalformedTreeException e) {
- e.printStackTrace();
- } catch (BadLocationException e) {
- e.printStackTrace();
- }
- return original;
- }
-
- /**
- * Returns true iff str.toLowerCase().endsWith(end.toLowerCase())
- * implementation is not creating extra strings.
- */
- public final static boolean endsWithIgnoreCase(String str, String end) {
-
- int strLength = str == null ? 0 : str.length();
- int endLength = end == null ? 0 : end.length();
-
- // return false if the string is smaller than the end.
- if(endLength > strLength)
- return false;
-
- // return false if any character of the end are
- // not the same in lower case.
- for(int i = 1 ; i <= endLength; i++){
- if(ScannerHelper.toLowerCase(end.charAt(endLength - i)) != ScannerHelper.toLowerCase(str.charAt(strLength - i)))
- return false;
- }
-
- return true;
- }
-
- /**
- * Compares two arrays using equals() on the elements.
- * Neither can be null. Only the first len elements are compared.
- * Return false if either array is shorter than len.
- */
- public static boolean equalArrays(Object[] a, Object[] b, int len) {
- if (a == b) return true;
- if (a.length < len || b.length < len) return false;
- for (int i = 0; i < len; ++i) {
- if (a[i] == null) {
- if (b[i] != null) return false;
- } else {
- if (!a[i].equals(b[i])) return false;
- }
- }
- return true;
- }
-
- /**
- * Compares two arrays using equals() on the elements.
- * Either or both arrays may be null.
- * Returns true if both are null.
- * Returns false if only one is null.
- * If both are arrays, returns true iff they have the same length and
- * all elements are equal.
- */
- public static boolean equalArraysOrNull(int[] a, int[] b) {
- if (a == b)
- return true;
- if (a == null || b == null)
- return false;
- int len = a.length;
- if (len != b.length)
- return false;
- for (int i = 0; i < len; ++i) {
- if (a[i] != b[i])
- return false;
- }
- return true;
- }
-
- /**
- * Compares two arrays using equals() on the elements.
- * Either or both arrays may be null.
- * Returns true if both are null.
- * Returns false if only one is null.
- * If both are arrays, returns true iff they have the same length and
- * all elements compare true with equals.
- */
- public static boolean equalArraysOrNull(Object[] a, Object[] b) {
- if (a == b) return true;
- if (a == null || b == null) return false;
-
- int len = a.length;
- if (len != b.length) return false;
- // walk array from end to beginning as this optimizes package name cases
- // where the first part is always the same (e.g. org.eclipse.wst.jsdt)
- for (int i = len-1; i >= 0; i--) {
- if (a[i] == null) {
- if (b[i] != null) return false;
- } else {
- if (!a[i].equals(b[i])) return false;
- }
- }
- return true;
- }
-
- /**
- * Compares two arrays using equals() on the elements.
- * The arrays are first sorted.
- * Either or both arrays may be null.
- * Returns true if both are null.
- * Returns false if only one is null.
- * If both are arrays, returns true iff they have the same length and
- * iff, after sorting both arrays, all elements compare true with equals.
- * The original arrays are left untouched.
- */
- public static boolean equalArraysOrNullSortFirst(Comparable[] a, Comparable[] b) {
- if (a == b) return true;
- if (a == null || b == null) return false;
- int len = a.length;
- if (len != b.length) return false;
- if (len >= 2) { // only need to sort if more than two items
- a = sortCopy(a);
- b = sortCopy(b);
- }
- for (int i = 0; i < len; ++i) {
- if (!a[i].equals(b[i])) return false;
- }
- return true;
- }
-
- /**
- * Compares two String arrays using equals() on the elements.
- * The arrays are first sorted.
- * Either or both arrays may be null.
- * Returns true if both are null.
- * Returns false if only one is null.
- * If both are arrays, returns true iff they have the same length and
- * iff, after sorting both arrays, all elements compare true with equals.
- * The original arrays are left untouched.
- */
- public static boolean equalArraysOrNullSortFirst(String[] a, String[] b) {
- if (a == b) return true;
- if (a == null || b == null) return false;
- int len = a.length;
- if (len != b.length) return false;
- if (len >= 2) { // only need to sort if more than two items
- a = sortCopy(a);
- b = sortCopy(b);
- }
- for (int i = 0; i < len; ++i) {
- if (!a[i].equals(b[i])) return false;
- }
- return true;
- }
-
- /**
- * Compares two objects using equals().
- * Either or both array may be null.
- * Returns true if both are null.
- * Returns false if only one is null.
- * Otherwise, return the result of comparing with equals().
- */
- public static boolean equalOrNull(Object a, Object b) {
- if (a == b) {
- return true;
- }
- if (a == null || b == null) {
- return false;
- }
- return a.equals(b);
- }
-
- /*
- * Returns whether the given file name equals to the given string ignoring the java like extension
- * of the file name.
- * Returns false if it is not a java like file name.
- */
- public static boolean equalsIgnoreJavaLikeExtension(String fileName, String string) {
- int fileNameLength = fileName.length();
- int stringLength = string.length();
- if (fileNameLength < stringLength) return false;
- for (int i = 0; i < stringLength; i ++) {
- if (fileName.charAt(i) != string.charAt(i)) {
- return false;
- }
- }
- char[][] javaLikeExtensions = getJavaLikeExtensions();
- suffixes: for (int i = 0, length = javaLikeExtensions.length; i < length; i++) {
- char[] suffix = javaLikeExtensions[i];
- int extensionStart = stringLength+1;
- if (extensionStart + suffix.length != fileNameLength) continue;
- if (fileName.charAt(stringLength) != '.') continue;
- for (int j = extensionStart; j < fileNameLength; j++) {
- char ch = fileName.charAt(j);
- if (ch != suffix[j-extensionStart] && Character.toLowerCase(ch) != suffix[j-extensionStart])
- continue suffixes;
- }
- return true;
- }
- return false;
- }
-
- /**
- * Given a qualified name, extract the last component.
- * If the input is not qualified, the same string is answered.
- */
- public static String extractLastName(String qualifiedName) {
- int i = qualifiedName.lastIndexOf('.');
- if (i == -1) return qualifiedName;
- return qualifiedName.substring(i+1);
- }
-
- /**
- * Extracts the parameter types from a method signature.
- */
- public static String[] extractParameterTypes(char[] sig) {
- int count = getParameterCount(sig);
- String[] result = new String[count];
- if (count == 0)
- return result;
- int i = CharOperation.indexOf('(', sig) + 1;
- count = 0;
- int len = sig.length;
- int start = i;
- for (;;) {
- if (i == len)
- break;
- char c = sig[i];
- if (c == ')')
- break;
- if (c == '[') {
- ++i;
- } else
- if (c == 'L') {
- i = CharOperation.indexOf(';', sig, i + 1) + 1;
- Assert.isTrue(i != 0);
- result[count++] = convertTypeSignature(sig, start, i - start);
- start = i;
- } else {
- ++i;
- result[count++] = convertTypeSignature(sig, start, i - start);
- start = i;
- }
- }
- return result;
- }
-
- /**
- * Extracts the return type from a method signature.
- */
- public static String extractReturnType(String sig) {
- int i = sig.lastIndexOf(')');
- Assert.isTrue(i != -1);
- return sig.substring(i+1);
- }
-
-
- /**
- * Finds the first line separator used by the given text.
- *
- * @return </code>"\n"</code> or </code>"\r"</code> or </code>"\r\n"</code>,
- * or <code>null</code> if none found
- */
- public static String findLineSeparator(char[] text) {
- // find the first line separator
- int length = text.length;
- if (length > 0) {
- char nextChar = text[0];
- for (int i = 0; i < length; i++) {
- char currentChar = nextChar;
- nextChar = i < length-1 ? text[i+1] : ' ';
- switch (currentChar) {
- case '\n': return "\n"; //$NON-NLS-1$
- case '\r': return nextChar == '\n' ? "\r\n" : "\r"; //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
- }
- // not found
- return null;
- }
-
-// public static IClassFileAttribute getAttribute(IClassFileReader classFileReader, char[] attributeName) {
-// IClassFileAttribute[] attributes = classFileReader.getAttributes();
-// for (int i = 0, max = attributes.length; i < max; i++) {
-// if (CharOperation.equals(attributes[i].getAttributeName(), attributeName)) {
-// return attributes[i];
-// }
-// }
-// return null;
-// }
-
-// public static IClassFileAttribute getAttribute(ICodeAttribute codeAttribute, char[] attributeName) {
-// IClassFileAttribute[] attributes = codeAttribute.getAttributes();
-// for (int i = 0, max = attributes.length; i < max; i++) {
-// if (CharOperation.equals(attributes[i].getAttributeName(), attributeName)) {
-// return attributes[i];
-// }
-// }
-// return null;
-// }
-
-// public static IClassFileAttribute getAttribute(IFieldInfo fieldInfo, char[] attributeName) {
-// IClassFileAttribute[] attributes = fieldInfo.getAttributes();
-// for (int i = 0, max = attributes.length; i < max; i++) {
-// if (CharOperation.equals(attributes[i].getAttributeName(), attributeName)) {
-// return attributes[i];
-// }
-// }
-// return null;
-// }
-//
-// public static IClassFileAttribute getAttribute(IMethodInfo methodInfo, char[] attributeName) {
-// IClassFileAttribute[] attributes = methodInfo.getAttributes();
-// for (int i = 0, max = attributes.length; i < max; i++) {
-// if (CharOperation.equals(attributes[i].getAttributeName(), attributeName)) {
-// return attributes[i];
-// }
-// }
-// return null;
-// }
-
- /**
- * Returns the registered Java like extensions.
- */
- public static char[][] getJavaLikeExtensions() {
- if (JAVA_LIKE_EXTENSIONS == null) {
- // TODO (jerome) reenable once JDT UI supports other file extensions (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=71460)
- if (!ENABLE_JAVA_LIKE_EXTENSIONS)
- JAVA_LIKE_EXTENSIONS = new char[][] {SuffixConstants.EXTENSION_java.toCharArray()};
- else {
- IContentType javaContentType = Platform.getContentTypeManager().getContentType(JavaScriptCore.JAVA_SOURCE_CONTENT_TYPE);
- HashSet fileExtensions = new HashSet();
- // content types derived from java content type should be included (https://bugs.eclipse.org/bugs/show_bug.cgi?id=121715)
- IContentType[] contentTypes = Platform.getContentTypeManager().getAllContentTypes();
- for (int i = 0, length = contentTypes.length; i < length; i++) {
- if (contentTypes[i].isKindOf(javaContentType)) { // note that javaContentType.isKindOf(javaContentType) == true
- String[] fileExtension = contentTypes[i].getFileSpecs(IContentType.FILE_EXTENSION_SPEC);
- for (int j = 0, length2 = fileExtension.length; j < length2; j++) {
- fileExtensions.add(fileExtension[j]);
- }
- }
- }
- int length = fileExtensions.size();
- // note that file extensions contains "js" as it is defined in JSDT Core's plugin.xml
- char[][] extensions = new char[length][];
- extensions[0] = SuffixConstants.EXTENSION_java.toCharArray(); // ensure that "js" is first
- int index = 1;
- Iterator iterator = fileExtensions.iterator();
- while (iterator.hasNext()) {
- String fileExtension = (String) iterator.next();
- if (SuffixConstants.EXTENSION_java.equals(fileExtension))
- continue;
- extensions[index++] = fileExtension.toCharArray();
- }
- JAVA_LIKE_EXTENSIONS = extensions;
- }
- }
- return JAVA_LIKE_EXTENSIONS;
- }
- /**
- * Returns the substring of the given file name, ending at the start of a
- * Java like extension. The entire file name is returned if it doesn't end
- * with a Java like extension.
- */
- public static String getNameWithoutJavaLikeExtension(String fileName) {
- int index = indexOfJavaLikeExtension(fileName);
- if (index == -1)
- return fileName;
- return fileName.substring(0, index);
- }
-
- /**
- * Returns the line separator found in the given text.
- * If it is null, or not found return the line delimitor for the given project.
- * If the project is null, returns the line separator for the workspace.
- * If still null, return the system line separator.
- */
- public static String getLineSeparator(String text, IJavaScriptProject project) {
- String lineSeparator = null;
-
- // line delimiter in given text
- if (text != null && text.length() != 0) {
- lineSeparator = findLineSeparator(text.toCharArray());
- if (lineSeparator != null)
- return lineSeparator;
- }
-
- // line delimiter in project preference
- IScopeContext[] scopeContext;
- if (project != null) {
- scopeContext= new IScopeContext[] { new ProjectScope(project.getProject()) };
- lineSeparator= Platform.getPreferencesService().getString(Platform.PI_RUNTIME, Platform.PREF_LINE_SEPARATOR, null, scopeContext);
- if (lineSeparator != null)
- return lineSeparator;
- }
-
- // line delimiter in workspace preference
- scopeContext= new IScopeContext[] { new InstanceScope() };
- lineSeparator = Platform.getPreferencesService().getString(Platform.PI_RUNTIME, Platform.PREF_LINE_SEPARATOR, null, scopeContext);
- if (lineSeparator != null)
- return lineSeparator;
-
- // system line delimiter
- return org.eclipse.wst.jsdt.internal.compiler.util.Util.LINE_SEPARATOR;
- }
-
- /**
- * Returns the line separator used by the given buffer.
- * Uses the given text if none found.
- *
- * @return </code>"\n"</code> or </code>"\r"</code> or </code>"\r\n"</code>
- */
- private static String getLineSeparator(char[] text, char[] buffer) {
- // search in this buffer's contents first
- String lineSeparator = findLineSeparator(buffer);
- if (lineSeparator == null) {
- // search in the given text
- lineSeparator = findLineSeparator(text);
- if (lineSeparator == null) {
- // default to system line separator
- return getLineSeparator((String) null, (IJavaScriptProject) null);
- }
- }
- return lineSeparator;
- }
-
- /**
- * Returns the number of parameter types in a method signature.
- */
- public static int getParameterCount(char[] sig) {
- int i = CharOperation.indexOf('(', sig) + 1;
- Assert.isTrue(i != 0);
- int count = 0;
- int len = sig.length;
- for (;;) {
- if (i == len)
- break;
- char c = sig[i];
- if (c == ')')
- break;
- if (c == '[') {
- ++i;
- } else
- if (c == 'L') {
- ++count;
- i = CharOperation.indexOf(';', sig, i + 1) + 1;
- Assert.isTrue(i != 0);
- } else {
- ++count;
- ++i;
- }
- }
- return count;
- }
-
- /**
- * Put all the arguments in one String.
- */
- public static String getProblemArgumentsForMarker(String[] arguments){
- StringBuffer args = new StringBuffer(10);
-
- args.append(arguments.length);
- args.append(':');
-
-
- for (int j = 0; j < arguments.length; j++) {
- if(j != 0)
- args.append(ARGUMENTS_DELIMITER);
-
- if(arguments[j].length() == 0) {
- args.append(EMPTY_ARGUMENT);
- } else {
- args.append(arguments[j]);
- }
- }
-
- return args.toString();
- }
-
- /**
- * Separate all the arguments of a String made by getProblemArgumentsForMarker
- */
- public static String[] getProblemArgumentsFromMarker(String argumentsString){
- if (argumentsString == null) return null;
- int index = argumentsString.indexOf(':');
- if(index == -1)
- return null;
-
- int length = argumentsString.length();
- int numberOfArg;
- try{
- numberOfArg = Integer.parseInt(argumentsString.substring(0 , index));
- } catch (NumberFormatException e) {
- return null;
- }
- argumentsString = argumentsString.substring(index + 1, length);
-
- String[] args = new String[length];
- int count = 0;
-
- StringTokenizer tokenizer = new StringTokenizer(argumentsString, ARGUMENTS_DELIMITER);
- while(tokenizer.hasMoreTokens()) {
- String argument = tokenizer.nextToken();
- if(argument.equals(EMPTY_ARGUMENT))
- argument = ""; //$NON-NLS-1$
- args[count++] = argument;
- }
-
- if(count != numberOfArg)
- return null;
-
- System.arraycopy(args, 0, args = new String[count], 0, count);
- return args;
- }
-
- /**
- * Returns the given file's contents as a byte array.
- */
- public static byte[] getResourceContentsAsByteArray(IFile file) throws JavaScriptModelException {
- InputStream stream= null;
- try {
- stream = file.getContents(true);
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- }
- try {
- return org.eclipse.wst.jsdt.internal.compiler.util.Util.getInputStreamAsByteArray(stream, -1);
- } catch (IOException e) {
- throw new JavaScriptModelException(e, IJavaScriptModelStatusConstants.IO_EXCEPTION);
- } finally {
- try {
- stream.close();
- } catch (IOException e) {
- // ignore
- }
- }
- }
-
- /**
- * Returns the given file's contents as a character array.
- */
- public static char[] getResourceContentsAsCharArray(IFile file) throws JavaScriptModelException {
- // Get encoding from file
- String encoding;
- try {
- encoding = file.getCharset();
- } catch(CoreException ce) {
- // do not use any encoding
- encoding = null;
- }
- return getResourceContentsAsCharArray(file, encoding);
- }
-
- public static char[] getResourceContentsAsCharArray(IFile file, String encoding) throws JavaScriptModelException {
- // Get file length
- // workaround https://bugs.eclipse.org/bugs/show_bug.cgi?id=130736 by using java.io.File if possible
- IPath location = file.getLocation();
- long length;
- if (location == null) {
- // non local file
- try {
- length = EFS.getStore(file.getLocationURI()).fetchInfo().getLength();
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- }
- } else {
- // local file
- length = location.toFile().length();
- }
-
- // Get resource contents
- InputStream stream= null;
- try {
- stream = file.getContents(true);
- } catch (CoreException e) {
- throw new JavaScriptModelException(e, IJavaScriptModelStatusConstants.ELEMENT_DOES_NOT_EXIST);
- }
- try {
- return org.eclipse.wst.jsdt.internal.compiler.util.Util.getInputStreamAsCharArray(stream, (int) length, encoding);
- } catch (IOException e) {
- throw new JavaScriptModelException(e, IJavaScriptModelStatusConstants.IO_EXCEPTION);
- } finally {
- try {
- stream.close();
- } catch (IOException e) {
- // ignore
- }
- }
- }
-
- /*
- * Returns the signature of the given type.
- */
- public static String getSignature(Type type) {
- StringBuffer buffer = new StringBuffer();
- getFullyQualifiedName(type, buffer);
- return Signature.createTypeSignature(buffer.toString(), false/*not resolved in source*/);
- }
-
- /*
- * Returns the source attachment property for this package fragment root's path
- */
- public static String getSourceAttachmentProperty(IPath path) throws JavaScriptModelException {
- Map rootPathToAttachments = JavaModelManager.getJavaModelManager().rootPathToAttachments;
- String property = (String) rootPathToAttachments.get(path);
- if (property == null) {
- try {
- property = ResourcesPlugin.getWorkspace().getRoot().getPersistentProperty(getSourceAttachmentPropertyName(path));
- if (property == null) {
- rootPathToAttachments.put(path, PackageFragmentRoot.NO_SOURCE_ATTACHMENT);
- return null;
- }
- rootPathToAttachments.put(path, property);
- return property;
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- }
- } else if (property.equals(PackageFragmentRoot.NO_SOURCE_ATTACHMENT)) {
- return null;
- } else
- return property;
- }
-
- private static QualifiedName getSourceAttachmentPropertyName(IPath path) {
- return new QualifiedName(JavaScriptCore.PLUGIN_ID, "sourceattachment: " + path.toOSString()); //$NON-NLS-1$
- }
-
- public static void setSourceAttachmentProperty(IPath path, String property) {
- JavaModelManager.getJavaModelManager().rootPathToAttachments.put(path, property);
- try {
- ResourcesPlugin.getWorkspace().getRoot().setPersistentProperty(getSourceAttachmentPropertyName(path), property);
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
-
- /*
- * Returns the declaring type signature of the element represented by the given binding key.
- * Returns the signature of the element if it is a type.
- *
- * @return the declaring type signature
- */
- public static String getDeclaringTypeSignature(String key) {
- KeyToSignature keyToSignature = new KeyToSignature(key, KeyToSignature.DECLARING_TYPE);
- keyToSignature.parse();
- return keyToSignature.signature.toString();
- }
-
- /*
- * Appends to the given buffer the fully qualified name (as it appears in the source) of the given type
- */
- private static void getFullyQualifiedName(Type type, StringBuffer buffer) {
- switch (type.getNodeType()) {
- case ASTNode.ARRAY_TYPE:
- ArrayType arrayType = (ArrayType) type;
- getFullyQualifiedName(arrayType.getElementType(), buffer);
- for (int i = 0, length = arrayType.getDimensions(); i < length; i++) {
- buffer.append('[');
- buffer.append(']');
- }
- break;
- case ASTNode.PRIMITIVE_TYPE:
- buffer.append(((PrimitiveType) type).getPrimitiveTypeCode().toString());
- break;
- case ASTNode.QUALIFIED_TYPE:
- buffer.append(((QualifiedType) type).getName().getFullyQualifiedName());
- break;
- case ASTNode.SIMPLE_TYPE:
- buffer.append(((SimpleType) type).getName().getFullyQualifiedName());
- break;
- case ASTNode.INFERRED_TYPE:
- buffer.append(((InferredType) type).getType());
- break;
- }
- }
-
- /**
- * Returns a trimmed version the simples names returned by Signature.
- */
- public static String[] getTrimmedSimpleNames(String name) {
- String[] result = Signature.getSimpleNames(name);
- for (int i = 0, length = result.length; i < length; i++) {
- result[i] = result[i].trim();
- }
- return result;
- }
-
- /*
- * Returns the index of the most specific argument paths which is strictly enclosing the path to check
- */
- public static int indexOfEnclosingPath(IPath checkedPath, IPath[] paths, int pathCount) {
-
- int bestMatch = -1, bestLength = -1;
- for (int i = 0; i < pathCount; i++){
- if (paths[i].equals(checkedPath)) continue;
- if (paths[i].isPrefixOf(checkedPath)) {
- int currentLength = paths[i].segmentCount();
- if (currentLength > bestLength) {
- bestLength = currentLength;
- bestMatch = i;
- }
- }
- }
- return bestMatch;
- }
-
- /*
- * Returns the index of the Java like extension of the given file name
- * or -1 if it doesn't end with a known Java like extension.
- * Note this is the index of the '.' even if it is not considered part of the extension.
- */
- public static int indexOfJavaLikeExtension(String fileName) {
-
-
- int fileNameLength = fileName.length();
- char[][] javaLikeExtensions = getJavaLikeExtensions();
- extensions: for (int i = 0, length = javaLikeExtensions.length; i < length; i++) {
- char[] extension = javaLikeExtensions[i];
- int extensionLength = extension.length;
- int extensionStart = fileNameLength - extensionLength;
- int dotIndex = extensionStart - 1;
- if (dotIndex < 0) continue;
- if (fileName.charAt(dotIndex) != '.') continue;
- for (int j = 0; j < extensionLength; j++) {
- char ch = fileName.charAt(extensionStart + j);
- if (ch != extension[j] && Character.toLowerCase(ch)!=extension[j] )
- continue extensions;
- }
- return dotIndex;
- }
- return -1;
- }
-
- /*
- * Returns the index of the first argument paths which is equal to the path to check
- */
- public static int indexOfMatchingPath(IPath checkedPath, IPath[] paths, int pathCount) {
-
- for (int i = 0; i < pathCount; i++){
- if (paths[i]!=null && paths[i].equals(checkedPath)) return i;
- }
- return -1;
- }
-
- /*
- * Returns the index of the first argument paths which is strictly nested inside the path to check
- */
- public static int indexOfNestedPath(IPath checkedPath, IPath[] paths, int pathCount) {
-
- for (int i = 0; i < pathCount; i++){
- if (checkedPath.equals(paths[i])) continue;
- if (checkedPath.isPrefixOf(paths[i])) return i;
- }
- return -1;
- }
- /**
- * Returns whether the local file system supports accessing and modifying
- * the given attribute.
- */
- protected static boolean isAttributeSupported(int attribute) {
- return (EFS.getLocalFileSystem().attributes() & attribute) != 0;
- }
-
- /**
- * Returns whether the given resource is read-only or not.
- * @param resource
- * @return <code>true</code> if the resource is read-only, <code>false</code> if it is not or
- * if the file system does not support the read-only attribute.
- */
- public static boolean isReadOnly(IResource resource) {
- if (isReadOnlySupported()) {
- ResourceAttributes resourceAttributes = resource.getResourceAttributes();
- if (resourceAttributes == null) return false; // not supported on this platform for this resource
- return resourceAttributes.isReadOnly();
- }
- return false;
- }
-
- /**
- * Returns whether the local file system supports accessing and modifying
- * the read only flag.
- */
- public static boolean isReadOnlySupported() {
- return isAttributeSupported(EFS.ATTRIBUTE_READ_ONLY);
- }
-
- /*
- * Returns whether the given java element is exluded from its root's classpath.
- * It doesn't check whether the root itself is on the classpath or not
- */
- public static final boolean isExcluded(IJavaScriptElement element) {
- int elementType = element.getElementType();
- switch (elementType) {
- case IJavaScriptElement.JAVASCRIPT_MODEL:
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- return false;
-
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- PackageFragmentRoot root = (PackageFragmentRoot)element.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- IResource resource = element.getResource();
- return resource != null && isExcluded(resource, root.fullInclusionPatternChars(), root.fullExclusionPatternChars());
-
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- root = (PackageFragmentRoot)element.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- resource = element.getResource();
- if (resource == null)
- return false;
- if (isExcluded(resource, root.fullInclusionPatternChars(), root.fullExclusionPatternChars()))
- return true;
- return isExcluded(element.getParent());
-
- default:
- IJavaScriptElement cu = element.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- return cu != null && isExcluded(cu);
- }
- }
- /*
- * Returns whether the given resource path matches one of the inclusion/exclusion
- * patterns.
- * NOTE: should not be asked directly using pkg root pathes
- * @see IIncludePathEntry#getInclusionPatterns
- * @see IIncludePathEntry#getExclusionPatterns
- */
- public final static boolean isExcluded(IPath resourcePath, char[][] inclusionPatterns, char[][] exclusionPatterns, boolean isFolderPath) {
- if (inclusionPatterns == null && exclusionPatterns == null) return false;
- return org.eclipse.wst.jsdt.internal.compiler.util.Util.isExcluded(resourcePath.toString().toCharArray(), inclusionPatterns, exclusionPatterns, isFolderPath);
- }
-
- /*
- * Returns whether the given resource matches one of the exclusion patterns.
- * NOTE: should not be asked directly using pkg root pathes
- * @see IIncludePathEntry#getExclusionPatterns
- */
- public final static boolean isExcluded(IResource resource, char[][] inclusionPatterns, char[][] exclusionPatterns) {
- IPath path = resource.getFullPath();
- // ensure that folders are only excluded if all of their children are excluded
- int resourceType = resource.getType();
- return isExcluded(path, inclusionPatterns, exclusionPatterns, resourceType == IResource.FOLDER || resourceType == IResource.PROJECT);
- }
-
- public final static boolean isExcluded(IPath path, char[][] inclusionPatterns, char[][] exclusionPatterns) {
-
- return isExcluded(path, inclusionPatterns, exclusionPatterns, path.toFile().isDirectory());
- }
-
- /**
- * Validate the given .class file name.
- * A .class file name must obey the following rules:
- * <ul>
- * <li> it must not be null
- * <li> it must include the <code>".class"</code> suffix
- * <li> its prefix must be a valid identifier
- * </ul>
- * </p>
- * @param name the name of a .class file
- * @param sourceLevel the source level
- * @param complianceLevel the compliance level
- * @return a status object with code <code>IStatus.OK</code> if
- * the given name is valid as a .class file name, otherwise a status
- * object indicating what is wrong with the name
- */
- public static boolean isValidClassFileName(String name, String sourceLevel, String complianceLevel) {
- return JavaScriptConventions.validateClassFileName(name, sourceLevel, complianceLevel).getSeverity() != IStatus.ERROR;
- }
-
-
- /**
- * Validate the given compilation unit name.
- * A compilation unit name must obey the following rules:
- * <ul>
- * <li> it must not be null
- * <li> it must include the <code>".js"</code> suffix
- * <li> its prefix must be a valid identifier
- * </ul>
- * </p>
- * @param name the name of a compilation unit
- * @param sourceLevel the source level
- * @param complianceLevel the compliance level
- * @return a status object with code <code>IStatus.OK</code> if
- * the given name is valid as a compilation unit name, otherwise a status
- * object indicating what is wrong with the name
- */
- public static boolean isValidCompilationUnitName(String name, String sourceLevel, String complianceLevel) {
- return JavaScriptConventions.validateCompilationUnitName(name, sourceLevel, complianceLevel).getSeverity() != IStatus.ERROR;
- }
-
- /**
- * Returns true if the given folder name is valid for a package,
- * false if it is not.
- * @param folderName the name of the folder
- * @param sourceLevel the source level
- * @param complianceLevel the compliance level
- */
- public static boolean isValidFolderNameForPackage(String folderName, String sourceLevel, String complianceLevel) {
- return JavaScriptConventions.validatePackageName(folderName, sourceLevel, complianceLevel).getSeverity() != IStatus.ERROR;
- }
-
- /**
- * Returns true if the given method signature is valid,
- * false if it is not.
- */
- public static boolean isValidMethodSignature(String sig) {
- int len = sig.length();
- if (len == 0) return false;
- int i = 0;
- char c = sig.charAt(i++);
- if (c != '(') return false;
- if (i >= len) return false;
- while (sig.charAt(i) != ')') {
- // Void is not allowed as a parameter type.
- i = checkTypeSignature(sig, i, len, false);
- if (i == -1) return false;
- if (i >= len) return false;
- }
- ++i;
- i = checkTypeSignature(sig, i, len, true);
- return i == len;
- }
-
- /**
- * Returns true if the given type signature is valid,
- * false if it is not.
- */
- public static boolean isValidTypeSignature(String sig, boolean allowVoid) {
- int len = sig.length();
- return checkTypeSignature(sig, 0, len, allowVoid) == len;
- }
-
- /*
- * Returns the simple name of a local type from the given binary type name.
- * The last '$' is at lastDollar. The last character of the type name is at end-1.
- */
- public static String localTypeName(String binaryTypeName, int lastDollar, int end) {
- if (lastDollar > 0 && binaryTypeName.charAt(lastDollar-1) == '$')
- // local name starts with a dollar sign
- // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=103466)
- return binaryTypeName;
- int nameStart = lastDollar+1;
- while (nameStart < end && Character.isDigit(binaryTypeName.charAt(nameStart)))
- nameStart++;
- return binaryTypeName.substring(nameStart, end);
- }
-
- /*
- * Add a log entry
- */
- public static void log(Throwable e, String message) {
- Throwable nestedException;
- if (e instanceof JavaScriptModelException
- && (nestedException = ((JavaScriptModelException)e).getException()) != null) {
- e = nestedException;
- }
- IStatus status= new Status(
- IStatus.ERROR,
- JavaScriptCore.PLUGIN_ID,
- IStatus.ERROR,
- message,
- e);
- JavaScriptCore.getPlugin().getLog().log(status);
- }
-
- /**
- * Normalizes the cariage returns in the given text.
- * They are all changed to use the given buffer's line separator.
- */
- public static char[] normalizeCRs(char[] text, char[] buffer) {
- CharArrayBuffer result = new CharArrayBuffer();
- int lineStart = 0;
- int length = text.length;
- if (length == 0) return text;
- String lineSeparator = getLineSeparator(text, buffer);
- char nextChar = text[0];
- for (int i = 0; i < length; i++) {
- char currentChar = nextChar;
- nextChar = i < length-1 ? text[i+1] : ' ';
- switch (currentChar) {
- case '\n':
- int lineLength = i-lineStart;
- char[] line = new char[lineLength];
- System.arraycopy(text, lineStart, line, 0, lineLength);
- result.append(line);
- result.append(lineSeparator);
- lineStart = i+1;
- break;
- case '\r':
- lineLength = i-lineStart;
- if (lineLength >= 0) {
- line = new char[lineLength];
- System.arraycopy(text, lineStart, line, 0, lineLength);
- result.append(line);
- result.append(lineSeparator);
- if (nextChar == '\n') {
- nextChar = ' ';
- lineStart = i+2;
- } else {
- // when line separator are mixed in the same file
- // \r might not be followed by a \n. If not, we should increment
- // lineStart by one and not by two.
- lineStart = i+1;
- }
- } else {
- // when line separator are mixed in the same file
- // we need to prevent NegativeArraySizeException
- lineStart = i+1;
- }
- break;
- }
- }
- char[] lastLine;
- if (lineStart > 0) {
- int lastLineLength = length-lineStart;
- if (lastLineLength > 0) {
- lastLine = new char[lastLineLength];
- System.arraycopy(text, lineStart, lastLine, 0, lastLineLength);
- result.append(lastLine);
- }
- return result.getContents();
- }
- return text;
- }
-
- /**
- * Normalizes the cariage returns in the given text.
- * They are all changed to use given buffer's line sepatator.
- */
- public static String normalizeCRs(String text, String buffer) {
- return new String(normalizeCRs(text.toCharArray(), buffer.toCharArray()));
- }
-
- /**
- * Converts the given relative path into a package name.
- * Returns null if the path is not a valid package name.
- * @param pkgPath the package path
- * @param sourceLevel the source level
- * @param complianceLevel the compliance level
- */
- public static String packageName(IPath pkgPath, String sourceLevel, String complianceLevel) {
- StringBuffer pkgName = new StringBuffer(IPackageFragment.DEFAULT_PACKAGE_NAME);
- for (int j = 0, max = pkgPath.segmentCount(); j < max; j++) {
- String segment = pkgPath.segment(j);
- if (!isValidFolderNameForPackage(segment, sourceLevel, complianceLevel)) {
- return null;
- }
- pkgName.append(segment);
- if (j < pkgPath.segmentCount() - 1) {
- pkgName.append("." ); //$NON-NLS-1$
- }
- }
- return pkgName.toString();
- }
-
- /**
- * Returns the length of the common prefix between s1 and s2.
- */
- public static int prefixLength(char[] s1, char[] s2) {
- int len= 0;
- int max= Math.min(s1.length, s2.length);
- for (int i= 0; i < max && s1[i] == s2[i]; ++i)
- ++len;
- return len;
- }
- /**
- * Returns the length of the common prefix between s1 and s2.
- */
- public static int prefixLength(String s1, String s2) {
- int len= 0;
- int max= Math.min(s1.length(), s2.length());
- for (int i= 0; i < max && s1.charAt(i) == s2.charAt(i); ++i)
- ++len;
- return len;
- }
- private static void quickSort(char[][] list, int left, int right) {
- int original_left= left;
- int original_right= right;
- char[] mid= list[left + (right - left) / 2];
- do {
- while (compare(list[left], mid) < 0) {
- left++;
- }
- while (compare(mid, list[right]) < 0) {
- right--;
- }
- if (left <= right) {
- char[] tmp= list[left];
- list[left]= list[right];
- list[right]= tmp;
- left++;
- right--;
- }
- } while (left <= right);
- if (original_left < right) {
- quickSort(list, original_left, right);
- }
- if (left < original_right) {
- quickSort(list, left, original_right);
- }
- }
-
- /**
- * Sort the comparable objects in the given collection.
- */
- private static void quickSort(Comparable[] sortedCollection, int left, int right) {
- int original_left = left;
- int original_right = right;
- Comparable mid = sortedCollection[ left + (right - left) / 2];
- do {
- while (sortedCollection[left].compareTo(mid) < 0) {
- left++;
- }
- while (mid.compareTo(sortedCollection[right]) < 0) {
- right--;
- }
- if (left <= right) {
- Comparable tmp = sortedCollection[left];
- sortedCollection[left] = sortedCollection[right];
- sortedCollection[right] = tmp;
- left++;
- right--;
- }
- } while (left <= right);
- if (original_left < right) {
- quickSort(sortedCollection, original_left, right);
- }
- if (left < original_right) {
- quickSort(sortedCollection, left, original_right);
- }
- }
- private static void quickSort(int[] list, int left, int right) {
- int original_left= left;
- int original_right= right;
- int mid= list[left + (right - left) / 2];
- do {
- while (list[left] < mid) {
- left++;
- }
- while (mid < list[right]) {
- right--;
- }
- if (left <= right) {
- int tmp= list[left];
- list[left]= list[right];
- list[right]= tmp;
- left++;
- right--;
- }
- } while (left <= right);
- if (original_left < right) {
- quickSort(list, original_left, right);
- }
- if (left < original_right) {
- quickSort(list, left, original_right);
- }
- }
-
- /**
- * Sort the objects in the given collection using the given comparer.
- */
- private static void quickSort(Object[] sortedCollection, int left, int right, Comparer comparer) {
- int original_left = left;
- int original_right = right;
- Object mid = sortedCollection[ left + (right - left) / 2];
- do {
- while (comparer.compare(sortedCollection[left], mid) < 0) {
- left++;
- }
- while (comparer.compare(mid, sortedCollection[right]) < 0) {
- right--;
- }
- if (left <= right) {
- Object tmp = sortedCollection[left];
- sortedCollection[left] = sortedCollection[right];
- sortedCollection[right] = tmp;
- left++;
- right--;
- }
- } while (left <= right);
- if (original_left < right) {
- quickSort(sortedCollection, original_left, right, comparer);
- }
- if (left < original_right) {
- quickSort(sortedCollection, left, original_right, comparer);
- }
- }
-
- /**
- * Sort the strings in the given collection.
- */
- private static void quickSort(String[] sortedCollection, int left, int right) {
- int original_left = left;
- int original_right = right;
- String mid = sortedCollection[ left + (right - left) / 2];
- do {
- while (sortedCollection[left].compareTo(mid) < 0) {
- left++;
- }
- while (mid.compareTo(sortedCollection[right]) < 0) {
- right--;
- }
- if (left <= right) {
- String tmp = sortedCollection[left];
- sortedCollection[left] = sortedCollection[right];
- sortedCollection[right] = tmp;
- left++;
- right--;
- }
- } while (left <= right);
- if (original_left < right) {
- quickSort(sortedCollection, original_left, right);
- }
- if (left < original_right) {
- quickSort(sortedCollection, left, original_right);
- }
- }
-
- /**
- * Returns the toString() of the given full path minus the first given number of segments.
- * The returned string is always a relative path (it has no leading slash)
- */
- public static String relativePath(IPath fullPath, int skipSegmentCount) {
- boolean hasTrailingSeparator = fullPath.hasTrailingSeparator();
- String[] segments = fullPath.segments();
-
- // compute length
- int length = 0;
- int max = segments.length;
- if (max > skipSegmentCount) {
- for (int i1 = skipSegmentCount; i1 < max; i1++) {
- length += segments[i1].length();
- }
- //add the separator lengths
- length += max - skipSegmentCount - 1;
- }
- if (hasTrailingSeparator)
- length++;
-
- char[] result = new char[length];
- int offset = 0;
- int len = segments.length - 1;
- if (len >= skipSegmentCount) {
- //append all but the last segment, with separators
- for (int i = skipSegmentCount; i < len; i++) {
- int size = segments[i].length();
- segments[i].getChars(0, size, result, offset);
- offset += size;
- result[offset++] = '/';
- }
- //append the last segment
- int size = segments[len].length();
- segments[len].getChars(0, size, result, offset);
- offset += size;
- }
- if (hasTrailingSeparator)
- result[offset++] = '/';
- return new String(result);
- }
-
- /*
- * Resets the list of Java-like extensions after a change in content-type.
- */
- public static void resetJavaLikeExtensions() {
- JAVA_LIKE_EXTENSIONS = null;
- }
-
- /**
- * Return a new array which is the split of the given string using the given divider. The given end
- * is exclusive and the given start is inclusive.
- * <br>
- * <br>
- * For example:
- * <ol>
- * <li><pre>
- * divider = 'b'
- * string = "abbaba"
- * start = 2
- * end = 5
- * result => { "", "a", "" }
- * </pre>
- * </li>
- * </ol>
- *
- * @param divider the given divider
- * @param string the given string
- * @param start the given starting index
- * @param end the given ending index
- * @return a new array which is the split of the given string using the given divider
- * @throws ArrayIndexOutOfBoundsException if start is lower than 0 or end is greater than the array length
- */
- public static final String[] splitOn(
- char divider,
- String string,
- int start,
- int end) {
- int length = string == null ? 0 : string.length();
- if (length == 0 || start > end)
- return CharOperation.NO_STRINGS;
-
- int wordCount = 1;
- for (int i = start; i < end; i++)
- if (string.charAt(i) == divider)
- wordCount++;
- String[] split = new String[wordCount];
- int last = start, currentWord = 0;
- for (int i = start; i < end; i++) {
- if (string.charAt(i) == divider) {
- split[currentWord++] = string.substring(last, i);
- last = i + 1;
- }
- }
- split[currentWord] = string.substring(last, end);
- return split;
- }
- /**
- * Sets or unsets the given resource as read-only in the file system.
- * It's a no-op if the file system does not support the read-only attribute.
- *
- * @param resource The resource to set as read-only
- * @param readOnly <code>true</code> to set it to read-only,
- * <code>false</code> to unset
- */
- public static void setReadOnly(IResource resource, boolean readOnly) {
- if (isReadOnlySupported()) {
- ResourceAttributes resourceAttributes = resource.getResourceAttributes();
- if (resourceAttributes == null) return; // not supported on this platform for this resource
- resourceAttributes.setReadOnly(readOnly);
- try {
- resource.setResourceAttributes(resourceAttributes);
- } catch (CoreException e) {
- // ignore
- }
- }
- }
- public static void sort(char[][] list) {
- if (list.length > 1)
- quickSort(list, 0, list.length - 1);
- }
-
- /**
- * Sorts an array of Comparable objects in place.
- */
- public static void sort(Comparable[] objects) {
- if (objects.length > 1)
- quickSort(objects, 0, objects.length - 1);
- }
- public static void sort(int[] list) {
- if (list.length > 1)
- quickSort(list, 0, list.length - 1);
- }
-
- /**
- * Sorts an array of objects in place.
- * The given comparer compares pairs of items.
- */
- public static void sort(Object[] objects, Comparer comparer) {
- if (objects.length > 1)
- quickSort(objects, 0, objects.length - 1, comparer);
- }
-
- /**
- * Sorts an array of strings in place using quicksort.
- */
- public static void sort(String[] strings) {
- if (strings.length > 1)
- quickSort(strings, 0, strings.length - 1);
- }
-
- /**
- * Sorts an array of Comparable objects, returning a new array
- * with the sorted items. The original array is left untouched.
- */
- public static Comparable[] sortCopy(Comparable[] objects) {
- int len = objects.length;
- Comparable[] copy = new Comparable[len];
- System.arraycopy(objects, 0, copy, 0, len);
- sort(copy);
- return copy;
- }
-
- /**
- * Sorts an array of Java elements based on their toStringWithAncestors(),
- * returning a new array with the sorted items.
- * The original array is left untouched.
- */
- public static IJavaScriptElement[] sortCopy(IJavaScriptElement[] elements) {
- int len = elements.length;
- IJavaScriptElement[] copy = new IJavaScriptElement[len];
- System.arraycopy(elements, 0, copy, 0, len);
- sort(copy, new Comparer() {
- public int compare(Object a, Object b) {
- return ((JavaElement) a).toStringWithAncestors().compareTo(((JavaElement) b).toStringWithAncestors());
- }
- });
- return copy;
- }
-
- /**
- * Sorts an array of Strings, returning a new array
- * with the sorted items. The original array is left untouched.
- */
- public static Object[] sortCopy(Object[] objects, Comparer comparer) {
- int len = objects.length;
- Object[] copy = new Object[len];
- System.arraycopy(objects, 0, copy, 0, len);
- sort(copy, comparer);
- return copy;
- }
-
- /**
- * Sorts an array of Strings, returning a new array
- * with the sorted items. The original array is left untouched.
- */
- public static String[] sortCopy(String[] objects) {
- int len = objects.length;
- String[] copy = new String[len];
- System.arraycopy(objects, 0, copy, 0, len);
- sort(copy);
- return copy;
- }
-
- /*
- * Returns whether the given compound name starts with the given prefix.
- * Returns true if the n first elements of the prefix are equals and the last element of the
- * prefix is a prefix of the corresponding element in the compound name.
- */
- public static boolean startsWithIgnoreCase(String[] compoundName, String[] prefix) {
- int prefixLength = prefix.length;
- int nameLength = compoundName.length;
- if (prefixLength > nameLength) return false;
- for (int i = 0; i < prefixLength - 1; i++) {
- if (!compoundName[i].equalsIgnoreCase(prefix[i]))
- return false;
- }
- return compoundName[prefixLength-1].toLowerCase().startsWith(prefix[prefixLength-1].toLowerCase());
- }
-
- /*
- * Returns whether the given compound name matches the given pattern.
- */
- public static boolean matchesWithIgnoreCase(String[] compoundName, String pattern) {
- if (pattern.equals("*")) return true; //$NON-NLS-1$
- int nameLength = compoundName.length;
- if (pattern.length() == 0) return nameLength == 0;
- if (nameLength == 0) return false;
- int length = nameLength-1;
- for (int i=0; i<nameLength; i++) {
- length += compoundName[i].length();
- }
- char[] compoundChars = new char[length];
- int pos = 0;
- for (int i=0; i<nameLength; i++) {
- if (pos > 0) compoundChars[pos++] = '.';
- char[] array = compoundName[i].toCharArray();
- int size = array.length;
- System.arraycopy(array, 0, compoundChars, pos, size);
- pos += size;
- }
- return CharOperation.match(pattern.toCharArray(), compoundChars, false);
- }
-
- /**
- * Converts a String[] to char[][].
- */
- public static char[][] toCharArrays(String[] a) {
- int len = a.length;
- if (len == 0) return CharOperation.NO_CHAR_CHAR;
- char[][] result = new char[len][];
- for (int i = 0; i < len; ++i) {
- result[i] = a[i].toCharArray();
- }
- return result;
- }
-
- /**
- * Converts a String to char[][], where segments are separate by '.'.
- */
- public static char[][] toCompoundChars(String s) {
- int len = s.length();
- if (len == 0) {
- return CharOperation.NO_CHAR_CHAR;
- }
- int segCount = 1;
- for (int off = s.indexOf('.'); off != -1; off = s.indexOf('.', off + 1)) {
- ++segCount;
- }
- char[][] segs = new char[segCount][];
- int start = 0;
- for (int i = 0; i < segCount; ++i) {
- int dot = s.indexOf('.', start);
- int end = (dot == -1 ? s.length() : dot);
- segs[i] = new char[end - start];
- s.getChars(start, end, segs[i], 0);
- start = end + 1;
- }
- return segs;
- }
- /*
- * Converts the given URI to a local file. Use the existing file if the uri is on the local file system.
- * Otherwise fetch it.
- * Returns null if unable to fetch it.
- */
- public static File toLocalFile(URI uri, IProgressMonitor monitor) throws CoreException {
- IFileStore fileStore = EFS.getStore(uri);
- File localFile = fileStore.toLocalFile(EFS.NONE, monitor);
- if (localFile ==null)
- // non local file system
- localFile= fileStore.toLocalFile(EFS.CACHE, monitor);
- return localFile;
- }
- /**
- * Converts a char[][] to String, where segments are separated by '.'.
- */
- public static String toString(char[][] c) {
- StringBuffer sb = new StringBuffer();
- for (int i = 0, max = c.length; i < max; ++i) {
- if (i != 0) sb.append('.');
- sb.append(c[i]);
- }
- return sb.toString();
- }
-
- /**
- * Converts a char[][] and a char[] to String, where segments are separated by '.'.
- */
- public static String toString(char[][] c, char[] d) {
- if (c == null) return new String(d);
- StringBuffer sb = new StringBuffer();
- for (int i = 0, max = c.length; i < max; ++i) {
- sb.append(c[i]);
- sb.append('.');
- }
- sb.append(d);
- return sb.toString();
- }
-
- /*
- * Converts a char[][] to String[].
- */
- public static String[] toStrings(char[][] a) {
- int len = a.length;
- String[] result = new String[len];
- for (int i = 0; i < len; ++i) {
- result[i] = new String(a[i]);
- }
- return result;
- }
- private static void appendArrayTypeSignature(char[] string, int start, StringBuffer buffer, boolean compact) {
- int length = string.length;
- // need a minimum 2 char
- if (start >= length - 1) {
- throw new IllegalArgumentException();
- }
- char c = string[start];
- if (c != Signature.C_ARRAY) {
- throw new IllegalArgumentException();
- }
-
- int index = start;
- c = string[++index];
- while(c == Signature.C_ARRAY) {
- // need a minimum 2 char
- if (index >= length - 1) {
- throw new IllegalArgumentException();
- }
- c = string[++index];
- }
-
- appendTypeSignature(string, index, buffer, compact);
-
- for(int i = 0, dims = index - start; i < dims; i++) {
- buffer.append('[').append(']');
- }
- }
- private static void appendClassTypeSignature(char[] string, int start, StringBuffer buffer, boolean compact) {
- char c = string[start];
- if (c != Signature.C_RESOLVED) {
- return;
- }
- int p = start + 1;
- int checkpoint = buffer.length();
- while (true) {
- c = string[p];
- switch(c) {
- case Signature.C_SEMICOLON :
- // all done
- return;
- case Signature.C_DOT :
- case '/' :
- // erase package prefix
- if (compact) {
- buffer.setLength(checkpoint);
- } else {
- buffer.append('.');
- }
- break;
- case Signature.C_DOLLAR :
- /**
- * 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);
- }
- p++;
- }
- }
- static void appendTypeSignature(char[] string, int start, StringBuffer buffer, boolean compact) {
- char c = string[start];
- switch (c) {
- case Signature.C_ARRAY :
- appendArrayTypeSignature(string, start, buffer, compact);
- break;
- case Signature.C_RESOLVED :
- appendClassTypeSignature(string, start, buffer, compact);
- break;
- case Signature.C_VOID :
- buffer.append(VOID);
- break;
- }
- }
- public static String toString(char[] declaringClass, char[] methodName, char[] methodSignature, boolean includeReturnType, boolean compact) {
- final boolean isConstructor = CharOperation.equals(methodName, INIT);
- int firstParen = CharOperation.indexOf(Signature.C_PARAM_START, methodSignature);
- if (firstParen == -1) {
- return ""; //$NON-NLS-1$
- }
-
- StringBuffer buffer = new StringBuffer(methodSignature.length + 10);
-
- // decode declaring class name
- // it can be either an array signature or a type signature
- if (declaringClass.length > 0) {
- char[] declaringClassSignature = null;
- if (declaringClass[0] == Signature.C_ARRAY) {
- CharOperation.replace(declaringClass, '/', '.');
- declaringClassSignature = Signature.toCharArray(declaringClass);
- } else {
- CharOperation.replace(declaringClass, '/', '.');
- declaringClassSignature = declaringClass;
- }
- int lastIndexOfSlash = CharOperation.lastIndexOf('.', declaringClassSignature);
- if (compact && lastIndexOfSlash != -1) {
- buffer.append(declaringClassSignature, lastIndexOfSlash + 1, declaringClassSignature.length - lastIndexOfSlash - 1);
- } else {
- buffer.append(declaringClassSignature);
- }
- }
-
- // selector
- if (!isConstructor) {
- buffer.append('.');
- if (methodName != null) {
- buffer.append(methodName);
- }
- }
-
- // parameters
- buffer.append('(');
- char[][] pts = Signature.getParameterTypes(methodSignature);
- for (int i = 0, max = pts.length; i < max; i++) {
- appendTypeSignature(pts[i], 0 , buffer, compact);
- if (i != pts.length - 1) {
- buffer.append(',');
- buffer.append(' ');
- }
- }
- buffer.append(')');
-
- if (!isConstructor) {
- buffer.append(" : "); //$NON-NLS-1$
- // return type
- if (includeReturnType) {
- char[] rts = Signature.getReturnType(methodSignature);
- appendTypeSignature(rts, 0 , buffer, compact);
- }
- }
- return String.valueOf(buffer);
- }
- /*
- * Returns the unresolved type parameter signatures of the given method
- * e.g. {"QString;", "[int", "[[Qjava.util.Vector;"}
- */
- public static String[] typeParameterSignatures(AbstractMethodDeclaration method) {
- Argument[] args = method.arguments;
- if (args != null) {
- int length = args.length;
- String[] signatures = new String[length];
- for (int i = 0; i < args.length; i++) {
- Argument arg = args[i];
- signatures[i] = typeSignature(arg.type);
- }
- return signatures;
- }
- return CharOperation.NO_STRINGS;
- }
-
- /*
- * Returns the unresolved type signature of the given type reference,
- * e.g. "QString;", "[int", "[[Qjava.util.Vector;"
- */
- public static String typeSignature(TypeReference type) {
- if (type==null)
- return Signature.SIG_ANY;
- char[][] compoundName = type.getTypeName();
- char[] typeName =CharOperation.concatWith(compoundName, '.');
- String signature = Signature.createTypeSignature(typeName, false/*don't resolve*/);
- return signature;
- }
-
- /**
- * Asserts that the given method signature is valid.
- */
- public static void validateMethodSignature(String sig) {
- Assert.isTrue(isValidMethodSignature(sig));
- }
-
- /**
- * Asserts that the given type signature is valid.
- */
- public static void validateTypeSignature(String sig, boolean allowVoid) {
- Assert.isTrue(isValidTypeSignature(sig, allowVoid));
- }
- public static void verbose(String log) {
- verbose(log, System.out);
- }
- public static synchronized void verbose(String log, PrintStream printStream) {
- int start = 0;
- do {
- int end = log.indexOf('\n', start);
- printStream.print(Thread.currentThread());
- printStream.print(" "); //$NON-NLS-1$
- printStream.print(log.substring(start, end == -1 ? log.length() : end+1));
- start = end+1;
- } while (start != 0);
- printStream.println();
- }
-
- /**
- * Returns true if the given name ends with one of the known java like extension.
- * (implementation is not creating extra strings)
- */
- public final static boolean isJavaLikeFileName(String name) {
- if (name == null) return false;
- return indexOfJavaLikeExtension(name) != -1;
- }
-
-
- public final static boolean isMetadataFileName(String name) {
- if (name == null) return false;
- return name.endsWith(IOAAMetaDataConstants.METADATA_FILE);
- }
-
- /**
- * Returns true if the given name ends with one of the known java like extension.
- * (implementation is not creating extra strings)
- */
- public final static boolean isJavaLikeFileName(char[] fileName) {
- if (fileName == null) return false;
- int fileNameLength = fileName.length;
- char[][] javaLikeExtensions = getJavaLikeExtensions();
- extensions: for (int i = 0, length = javaLikeExtensions.length; i < length; i++) {
- char[] extension = javaLikeExtensions[i];
- int extensionLength = extension.length;
- int extensionStart = fileNameLength - extensionLength;
- if (extensionStart-1 < 0) continue;
- if (fileName[extensionStart-1] != '.') continue;
- for (int j = 0; j < extensionLength; j++) {
- char ch = fileName[extensionStart + j];
- if (ch != extension[j] && Character.toLowerCase(ch)!= extension[j])
- continue extensions;
- }
- return true;
- }
- return false;
- }
-
- /**
- * Scans the given string for a type signature starting at the given index
- * and returns the index of the last character.
- * <pre>
- * TypeSignature:
- * | BaseTypeSignature
- * | ArrayTypeSignature
- * | ClassTypeSignature
- * | TypeVariableSignature
- * </pre>
- *
- * @param string the signature string
- * @param start the 0-based character index of the first character
- * @return the 0-based character index of the last character
- * @exception IllegalArgumentException if this is not a type signature
- */
- public static int scanTypeSignature(char[] string, int start) {
- // need a minimum 1 char
- if (start >= string.length) {
- throw new IllegalArgumentException();
- }
- char c = string[start];
- switch (c) {
- case Signature.C_ARRAY :
- return scanArrayTypeSignature(string, start);
- case Signature.C_RESOLVED :
- case Signature.C_UNRESOLVED :
- return scanClassTypeSignature(string, start);
- case Signature.C_VOID :
- case Signature.C_ANY :
- return scanBaseTypeSignature(string, start);
- default :
- throw new IllegalArgumentException();
- }
- }
-
- /**
- * Scans the given string for a base type signature starting at the given index
- * and returns the index of the last character.
- * <pre>
- * BaseTypeSignature:
- * <b>B</b> | <b>C</b> | <b>D</b> | <b>F</b> | <b>I</b>
- * | <b>J</b> | <b>S</b> | <b>V</b> | <b>Z</b>
- * </pre>
- * Note that although the base type "V" is only allowed in method return types,
- * there is no syntactic ambiguity. This method will accept them anywhere
- * without complaint.
- *
- * @param string the signature string
- * @param start the 0-based character index of the first character
- * @return the 0-based character index of the last character
- * @exception IllegalArgumentException if this is not a base type signature
- */
- public static int scanBaseTypeSignature(char[] string, int start) {
- // need a minimum 1 char
- if (start >= string.length) {
- throw new IllegalArgumentException();
- }
- char c = string[start];
- if ("BCDFIJSVZA".indexOf(c) >= 0) { //$NON-NLS-1$
- return start;
- } else {
- throw new IllegalArgumentException();
- }
- }
-
- /**
- * Scans the given string for an array type signature starting at the given
- * index and returns the index of the last character.
- * <pre>
- * ArrayTypeSignature:
- * <b>[</b> TypeSignature
- * </pre>
- *
- * @param string the signature string
- * @param start the 0-based character index of the first character
- * @return the 0-based character index of the last character
- * @exception IllegalArgumentException if this is not an array type signature
- */
- public static int scanArrayTypeSignature(char[] string, int start) {
- int length = string.length;
- // need a minimum 2 char
- if (start >= length - 1) {
- throw new IllegalArgumentException();
- }
- char c = string[start];
- if (c != Signature.C_ARRAY) {
- throw new IllegalArgumentException();
- }
-
- c = string[++start];
- while(c == Signature.C_ARRAY) {
- // need a minimum 2 char
- if (start >= length - 1) {
- throw new IllegalArgumentException();
- }
- c = string[++start];
- }
- return scanTypeSignature(string, start);
- }
-
- /**
- * Scans the given string for an identifier starting at the given
- * index and returns the index of the last character.
- * Stop characters are: ";", ":", "&lt;", "&gt;", "/", ".".
- *
- * @param string the signature string
- * @param start the 0-based character index of the first character
- * @return the 0-based character index of the last character
- * @exception IllegalArgumentException if this is not an identifier
- */
- public static int scanIdentifier(char[] string, int start) {
- // need a minimum 1 char
- if (start >= string.length) {
- throw new IllegalArgumentException();
- }
- int p = start;
- while (true) {
- char c = string[p];
- if (c == '<' || c == '>' || c == ':' || c == ';' || c == '.' || c == '/') {
- return p - 1;
- }
- p++;
- if (p == string.length) {
- return p - 1;
- }
- }
- }
-
- /**
- * Scans the given string for a class type signature starting at the given
- * index and returns the index of the last character.
- * <pre>
- * ClassTypeSignature:
- * { <b>L</b> | <b>Q</b> } Identifier
- * { { <b>/</b> | <b>.</b> Identifier [ <b>&lt;</b> TypeArgumentSignature* <b>&gt;</b> ] }
- * <b>;</b>
- * </pre>
- * Note that although all "/"-identifiers most come before "."-identifiers,
- * there is no syntactic ambiguity. This method will accept them without
- * complaint.
- *
- * @param string the signature string
- * @param start the 0-based character index of the first character
- * @return the 0-based character index of the last character
- * @exception IllegalArgumentException if this is not a class type signature
- */
- public static int scanClassTypeSignature(char[] string, int start) {
- // need a minimum 3 chars "Lx;"
- if (start >= string.length - 2) {
- throw new IllegalArgumentException();
- }
- // must start in "L" or "Q"
- char c = string[start];
- if (c != Signature.C_RESOLVED && c != Signature.C_UNRESOLVED) {
- return -1;
- }
- int p = start + 1;
- while (true) {
- if (p >= string.length) {
- throw new IllegalArgumentException();
- }
- c = string[p];
- if (c == Signature.C_SEMICOLON) {
- // all done
- return p;
- } else if (c == Signature.C_DOT || c == '/') {
- int id = scanIdentifier(string, p + 1);
- p = id;
- }
- p++;
- }
- }
-
- /**
- * Scans the given string for a type argument signature starting at the given
- * index and returns the index of the last character.
- * <pre>
- * TypeArgumentSignature:
- * <b>&#42;</b>
- * | <b>+</b> TypeSignature
- * | <b>-</b> TypeSignature
- * | TypeSignature
- * </pre>
- * Note that although base types are not allowed in type arguments, there is
- * no syntactic ambiguity. This method will accept them without complaint.
- *
- * @param string the signature string
- * @param start the 0-based character index of the first character
- * @return the 0-based character index of the last character
- * @exception IllegalArgumentException if this is not a type argument signature
- */
- public static int scanTypeArgumentSignature(char[] string, int start) {
- // need a minimum 1 char
- if (start >= string.length) {
- throw new IllegalArgumentException();
- }
-
- return scanTypeSignature(string, start);
-
- }
-
- /**
- * Get all type arguments from an array of signatures.
- *
- * Example:
- * For following type X<Y<Z>,V<W>,U>.A<B> signatures is:
- * [
- * ['L','X','<','L','Y','<','L','Z',';'>',';','L','V','<','L','W',';'>',';','L','U',';',>',';'],
- * ['L','A','<','L','B',';','>',';']
- * ]
- * @see #splitTypeLevelsSignature(String)
- * Then, this method returns:
- * [
- * [
- * ['L','Y','<','L','Z',';'>',';'],
- * ['L','V','<','L','W',';'>',';'],
- * ['L','U',';']
- * ],
- * [
- * ['L','B',';']
- * ]
- * ]
- *
- * @param typeSignatures Array of signatures (one per each type levels)
- * @throws IllegalArgumentException If one of provided signature is malformed
- * @return char[][][] Array of type arguments for each signature
- */
- public final static char[][][] getAllTypeArguments(char[][] typeSignatures) {
- if (typeSignatures == null) return null;
- int length = typeSignatures.length;
- char[][][] typeArguments = new char[length][][];
- return typeArguments;
- }
- /**
- * Split signatures of all levels from a type unique key.
- *
- * Example:
- * For following type X<Y<Z>,V<W>,U>.A<B>, unique key is:
- * "LX<LY<LZ;>;LV<LW;>;LU;>.LA<LB;>;"
- *
- * The return splitted signatures array is:
- * [
- * ['L','X','<','L','Y','<','L','Z',';'>',';','L','V','<','L','W',';'>',';','L','U','>',';'],
- * ['L','A','<','L','B',';','>',';']
- *
- * @param typeSignature ParameterizedSourceType type signature
- * @return char[][] Array of signatures for each level of given unique key
- */
- public final static char[][] splitTypeLevelsSignature(String typeSignature) {
- // In case of IJavaScriptElement signature, replace '$' by '.'
- char[] source = typeSignature.toCharArray();
- CharOperation.replace(source, '$', '.');
-
- // Init counters and arrays
- char[][] signatures = new char[10][];
- int signaturesCount = 0;
-// int[] lengthes = new int [10];
- int typeArgsCount = 0;
- int paramOpening = 0;
-
- // Scan each signature character
- for (int idx=0, ln = source.length; idx < ln; idx++) {
- switch (source[idx]) {
- case '>':
- paramOpening--;
- if (paramOpening == 0) {
- if (signaturesCount == signatures.length) {
- System.arraycopy(signatures, 0, signatures = new char[signaturesCount+10][], 0, signaturesCount);
- }
- typeArgsCount = 0;
- }
- break;
- case '<':
- paramOpening++;
- if (paramOpening == 1) {
- typeArgsCount = 1;
- }
- break;
- case '*':
- case ';':
- if (paramOpening == 1) typeArgsCount++;
- break;
- case '.':
- if (paramOpening == 0) {
- if (signaturesCount == signatures.length) {
- System.arraycopy(signatures, 0, signatures = new char[signaturesCount+10][], 0, signaturesCount);
- }
- signatures[signaturesCount] = new char[idx+1];
- System.arraycopy(source, 0, signatures[signaturesCount], 0, idx);
- signatures[signaturesCount][idx] = Signature.C_SEMICOLON;
- signaturesCount++;
- }
- break;
- case '/':
- source[idx] = '.';
- break;
- }
- }
-
- // Resize signatures array
- char[][] typeSignatures = new char[signaturesCount+1][];
- typeSignatures[0] = source;
- for (int i=1, j=signaturesCount-1; i<=signaturesCount; i++, j--){
- typeSignatures[i] = signatures[j];
- }
- return typeSignatures;
- }
-
- /*
- * Can throw IllegalArgumentException or ArrayIndexOutOfBoundsException
- */
- public static String toAnchor(char[] methodSignature, String methodName, boolean isVarArgs) {
- try {
- return new String(toAnchor(methodSignature, methodName.toCharArray(), isVarArgs));
- } catch(IllegalArgumentException e) {
- return null;
- }
- }
- private static char[] toAnchor(char[] methodSignature, char[] methodName, boolean isVargArgs) {
- int firstParen = CharOperation.indexOf(Signature.C_PARAM_START, methodSignature);
- if (firstParen == -1) {
- throw new IllegalArgumentException();
- }
-
- StringBuffer buffer = new StringBuffer(methodSignature.length + 10);
-
- // selector
- if (methodName != null) {
- buffer.append(methodName);
- }
-
- // parameters
- buffer.append('(');
- char[][] pts = Signature.getParameterTypes(methodSignature);
- for (int i = 0, max = pts.length; i < max; i++) {
- if (i == max - 1) {
- appendTypeSignatureForAnchor(pts[i], 0 , buffer, isVargArgs);
- } else {
- appendTypeSignatureForAnchor(pts[i], 0 , buffer, false);
- }
- if (i != pts.length - 1) {
- buffer.append(',');
- buffer.append(' ');
- }
- }
- buffer.append(')');
- char[] result = new char[buffer.length()];
- buffer.getChars(0, buffer.length(), result, 0);
- return result;
- }
-
- private static int appendTypeSignatureForAnchor(char[] string, int start, StringBuffer buffer, boolean isVarArgs) {
- // need a minimum 1 char
- if (start >= string.length) {
- throw new IllegalArgumentException();
- }
- char c = string[start];
- if (isVarArgs) {
- switch (c) {
- case Signature.C_ARRAY :
- return appendArrayTypeSignatureForAnchor(string, start, buffer, true);
- case Signature.C_RESOLVED :
- case Signature.C_VOID :
- default:
- throw new IllegalArgumentException(); // a var args is an array type
- }
- } else {
- switch (c) {
- case Signature.C_ARRAY :
- return appendArrayTypeSignatureForAnchor(string, start, buffer, false);
- case Signature.C_RESOLVED :
- return appendClassTypeSignatureForAnchor(string, start, buffer);
- case Signature.C_VOID :
- buffer.append(VOID);
- return start;
- default :
- throw new IllegalArgumentException();
- }
- }
- }
-
- private static int appendArrayTypeSignatureForAnchor(char[] string, int start, StringBuffer buffer, boolean isVarArgs) {
- int length = string.length;
- // need a minimum 2 char
- if (start >= length - 1) {
- throw new IllegalArgumentException();
- }
- char c = string[start];
- if (c != Signature.C_ARRAY) {
- throw new IllegalArgumentException();
- }
-
- int index = start;
- c = string[++index];
- while(c == Signature.C_ARRAY) {
- // need a minimum 2 char
- if (index >= length - 1) {
- throw new IllegalArgumentException();
- }
- c = string[++index];
- }
-
- int e = appendTypeSignatureForAnchor(string, index, buffer, false);
-
- for(int i = 1, dims = index - start; i < dims; i++) {
- buffer.append('[').append(']');
- }
-
- if (isVarArgs) {
- buffer.append('.').append('.').append('.');
- } else {
- buffer.append('[').append(']');
- }
- return e;
- }
- private static int appendClassTypeSignatureForAnchor(char[] string, int start, StringBuffer buffer) {
- // need a minimum 3 chars "Lx;"
- if (start >= string.length - 2) {
- throw new IllegalArgumentException();
- }
- // must start in "L" or "Q"
- char c = string[start];
- if (c != Signature.C_RESOLVED && c != Signature.C_UNRESOLVED) {
- throw new IllegalArgumentException();
- }
- int p = start + 1;
- while (true) {
- if (p >= string.length) {
- throw new IllegalArgumentException();
- }
- c = string[p];
- switch(c) {
- case Signature.C_SEMICOLON :
- // all done
- return p;
- case Signature.C_DOT :
- 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);
- }
- p++;
- }
- }
-
- /*
- * @GINO: Anonymous UI Label
- *
- * 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_LABEL = "{}"; //$NON-NLS-1$
-
- /*
- * @GINO: Anonymous UI Label
- *
- * This method is used to hide the internal name used for anonymous types
- */
- public static void insertTypeLabel(char[] typeName, StringBuffer buf) {
- insertTypeLabel( new String(typeName), buf );
- }
-
- /*
- * @GINO: Anonymous UI Label
- *
- * This method is used to hide the internal name used for anonymous types
- */
- public static void insertTypeLabel(String typeName, StringBuffer buf) {
- if( typeName.startsWith(ANONYMOUS_MARKER) ){
- buf.append( ANONYMOUS_LABEL );
- }
- else{
- buf.append(typeName);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/WeakHashSet.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/WeakHashSet.java
deleted file mode 100644
index a22e0409..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/WeakHashSet.java
+++ /dev/null
@@ -1,217 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.util;
-import java.lang.ref.ReferenceQueue;
-import java.lang.ref.WeakReference;
-
-/**
- * A hashset whose values can be garbage collected.
- */
-public class WeakHashSet {
-
- public static class HashableWeakReference extends WeakReference {
- public int hashCode;
- public HashableWeakReference(Object referent, ReferenceQueue queue) {
- super(referent, queue);
- this.hashCode = referent.hashCode();
- }
- public boolean equals(Object obj) {
- if (!(obj instanceof HashableWeakReference)) return false;
- Object referent = get();
- Object other = ((HashableWeakReference) obj).get();
- if (referent == null) return other == null;
- return referent.equals(other);
- }
- public int hashCode() {
- return this.hashCode;
- }
- public String toString() {
- Object referent = get();
- if (referent == null) return "[hashCode=" + this.hashCode + "] <referent was garbage collected>"; //$NON-NLS-1$ //$NON-NLS-2$
- return "[hashCode=" + this.hashCode + "] " + referent.toString(); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
-
- HashableWeakReference[] values;
- public int elementSize; // number of elements in the table
- int threshold;
- ReferenceQueue referenceQueue = new ReferenceQueue();
-
- public WeakHashSet() {
- this(5);
- }
-
- public WeakHashSet(int size) {
- this.elementSize = 0;
- this.threshold = size; // size represents the expected number of elements
- int extraRoom = (int) (size * 1.75f);
- if (this.threshold == extraRoom)
- extraRoom++;
- this.values = new HashableWeakReference[extraRoom];
- }
-
- /*
- * Adds the given object to this set.
- * If an object that is equals to the given object already exists, do nothing.
- * Returns the existing object or the new object if not found.
- */
- public Object add(Object obj) {
- cleanupGarbageCollectedValues();
- int valuesLength = this.values.length,
- index = (obj.hashCode() & 0x7FFFFFFF) % valuesLength;
- HashableWeakReference currentValue;
- while ((currentValue = this.values[index]) != null) {
- Object referent;
- if (obj.equals(referent = currentValue.get())) {
- return referent;
- }
- if (++index == valuesLength) {
- index = 0;
- }
- }
- this.values[index] = new HashableWeakReference(obj, this.referenceQueue);
-
- // assumes the threshold is never equal to the size of the table
- if (++this.elementSize > this.threshold)
- rehash();
-
- return obj;
- }
-
- private void addValue(HashableWeakReference value) {
- Object obj = value.get();
- if (obj == null) return;
- int valuesLength = this.values.length;
- int index = (value.hashCode & 0x7FFFFFFF) % valuesLength;
- HashableWeakReference currentValue;
- while ((currentValue = this.values[index]) != null) {
- if (obj.equals(currentValue.get())) {
- return;
- }
- if (++index == valuesLength) {
- index = 0;
- }
- }
- this.values[index] = value;
-
- // assumes the threshold is never equal to the size of the table
- if (++this.elementSize > this.threshold)
- rehash();
- }
-
- private void cleanupGarbageCollectedValues() {
- HashableWeakReference toBeRemoved;
- while ((toBeRemoved = (HashableWeakReference) this.referenceQueue.poll()) != null) {
- int hashCode = toBeRemoved.hashCode;
- int valuesLength = this.values.length;
- int index = (hashCode & 0x7FFFFFFF) % valuesLength;
- HashableWeakReference currentValue;
- while ((currentValue = this.values[index]) != null) {
- if (currentValue == toBeRemoved) {
- // replace the value at index with the last value with the same hash
- int sameHash = index;
- int current;
- while ((currentValue = this.values[current = (sameHash + 1) % valuesLength]) != null && currentValue.hashCode == hashCode)
- sameHash = current;
- this.values[index] = this.values[sameHash];
- this.values[sameHash] = null;
- this.elementSize--;
- break;
- }
- if (++index == valuesLength) {
- index = 0;
- }
- }
- }
- }
-
- public boolean contains(Object obj) {
- return get(obj) != null;
- }
-
- /*
- * Return the object that is in this set and that is equals to the given object.
- * Return null if not found.
- */
- public Object get(Object obj) {
- cleanupGarbageCollectedValues();
- int valuesLength = this.values.length;
- int index = (obj.hashCode() & 0x7FFFFFFF) % valuesLength;
- HashableWeakReference currentValue;
- while ((currentValue = this.values[index]) != null) {
- Object referent;
- if (obj.equals(referent = currentValue.get())) {
- return referent;
- }
- if (++index == valuesLength) {
- index = 0;
- }
- }
- return null;
- }
-
- private void rehash() {
- WeakHashSet newHashSet = new WeakHashSet(this.elementSize * 2); // double the number of expected elements
- newHashSet.referenceQueue = this.referenceQueue;
- HashableWeakReference currentValue;
- for (int i = 0, length = this.values.length; i < length; i++)
- if ((currentValue = this.values[i]) != null)
- newHashSet.addValue(currentValue);
-
- this.values = newHashSet.values;
- this.threshold = newHashSet.threshold;
- this.elementSize = newHashSet.elementSize;
- }
-
- /*
- * Removes the object that is in this set and that is equals to the given object.
- * Return the object that was in the set, or null if not found.
- */
- public Object remove(Object obj) {
- cleanupGarbageCollectedValues();
- int valuesLength = this.values.length;
- int index = (obj.hashCode() & 0x7FFFFFFF) % valuesLength;
- HashableWeakReference currentValue;
- while ((currentValue = this.values[index]) != null) {
- Object referent;
- if (obj.equals(referent = currentValue.get())) {
- this.elementSize--;
- this.values[index] = null;
- rehash();
- return referent;
- }
- if (++index == valuesLength) {
- index = 0;
- }
- }
- return null;
- }
-
- public int size() {
- return this.elementSize;
- }
-
- public String toString() {
- StringBuffer buffer = new StringBuffer("{"); //$NON-NLS-1$
- for (int i = 0, length = this.values.length; i < length; i++) {
- HashableWeakReference value = this.values[i];
- if (value != null) {
- Object ref = value.get();
- if (ref != null) {
- buffer.append(ref.toString());
- buffer.append(", "); //$NON-NLS-1$
- }
- }
- }
- buffer.append("}"); //$NON-NLS-1$
- return buffer.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/WeakHashSetOfCharArray.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/WeakHashSetOfCharArray.java
deleted file mode 100644
index 49717924..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/WeakHashSetOfCharArray.java
+++ /dev/null
@@ -1,220 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.core.util;
-import java.lang.ref.ReferenceQueue;
-import java.lang.ref.WeakReference;
-
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-
-/**
- * A hashset of char[] whose values can be garbage collected.
- */
-public class WeakHashSetOfCharArray {
-
- public static class HashableWeakReference extends WeakReference {
- public int hashCode;
- public HashableWeakReference(char[] referent, ReferenceQueue queue) {
- super(referent, queue);
- this.hashCode = CharOperation.hashCode(referent);
- }
- public boolean equals(Object obj) {
- if (!(obj instanceof HashableWeakReference)) return false;
- char[] referent = (char[]) get();
- char[] other = (char[]) ((HashableWeakReference) obj).get();
- if (referent == null) return other == null;
- return CharOperation.equals(referent, other);
- }
- public int hashCode() {
- return this.hashCode;
- }
- public String toString() {
- char[] referent = (char[]) get();
- if (referent == null) return "[hashCode=" + this.hashCode + "] <referent was garbage collected>"; //$NON-NLS-1$ //$NON-NLS-2$
- return "[hashCode=" + this.hashCode + "] \"" + new String(referent) + '\"'; //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
-
- HashableWeakReference[] values;
- public int elementSize; // number of elements in the table
- int threshold;
- ReferenceQueue referenceQueue = new ReferenceQueue();
-
- public WeakHashSetOfCharArray() {
- this(5);
- }
-
- public WeakHashSetOfCharArray(int size) {
- this.elementSize = 0;
- this.threshold = size; // size represents the expected number of elements
- int extraRoom = (int) (size * 1.75f);
- if (this.threshold == extraRoom)
- extraRoom++;
- this.values = new HashableWeakReference[extraRoom];
- }
-
- /*
- * Adds the given char array to this set.
- * If a char array that is equals to the given char array already exists, do nothing.
- * Returns the existing char array or the new char array if not found.
- */
- public char[] add(char[] array) {
- cleanupGarbageCollectedValues();
- int valuesLength = this.values.length,
- index = (CharOperation.hashCode(array) & 0x7FFFFFFF) % valuesLength;
- HashableWeakReference currentValue;
- while ((currentValue = this.values[index]) != null) {
- char[] referent;
- if (CharOperation.equals(array, referent = (char[]) currentValue.get())) {
- return referent;
- }
- if (++index == valuesLength) {
- index = 0;
- }
- }
- this.values[index] = new HashableWeakReference(array, this.referenceQueue);
-
- // assumes the threshold is never equal to the size of the table
- if (++this.elementSize > this.threshold)
- rehash();
-
- return array;
- }
-
- private void addValue(HashableWeakReference value) {
- char[] array = (char[]) value.get();
- if (array == null) return;
- int valuesLength = this.values.length;
- int index = (value.hashCode & 0x7FFFFFFF) % valuesLength;
- HashableWeakReference currentValue;
- while ((currentValue = this.values[index]) != null) {
- if (CharOperation.equals(array, (char[]) currentValue.get())) {
- return;
- }
- if (++index == valuesLength) {
- index = 0;
- }
- }
- this.values[index] = value;
-
- // assumes the threshold is never equal to the size of the table
- if (++this.elementSize > this.threshold)
- rehash();
- }
-
- private void cleanupGarbageCollectedValues() {
- HashableWeakReference toBeRemoved;
- while ((toBeRemoved = (HashableWeakReference) this.referenceQueue.poll()) != null) {
- int hashCode = toBeRemoved.hashCode;
- int valuesLength = this.values.length;
- int index = (hashCode & 0x7FFFFFFF) % valuesLength;
- HashableWeakReference currentValue;
- while ((currentValue = this.values[index]) != null) {
- if (currentValue == toBeRemoved) {
- // replace the value at index with the last value with the same hash
- int sameHash = index;
- int current;
- while ((currentValue = this.values[current = (sameHash + 1) % valuesLength]) != null && currentValue.hashCode == hashCode)
- sameHash = current;
- this.values[index] = this.values[sameHash];
- this.values[sameHash] = null;
- this.elementSize--;
- break;
- }
- if (++index == valuesLength) {
- index = 0;
- }
- }
- }
- }
-
- public boolean contains(char[] array) {
- return get(array) != null;
- }
-
- /*
- * Return the char array that is in this set and that is equals to the given char array.
- * Return null if not found.
- */
- public char[] get(char[] array) {
- cleanupGarbageCollectedValues();
- int valuesLength = this.values.length;
- int index = (CharOperation.hashCode(array) & 0x7FFFFFFF) % valuesLength;
- HashableWeakReference currentValue;
- while ((currentValue = this.values[index]) != null) {
- char[] referent;
- if (CharOperation.equals(array, referent = (char[]) currentValue.get())) {
- return referent;
- }
- if (++index == valuesLength) {
- index = 0;
- }
- }
- return null;
- }
-
- private void rehash() {
- WeakHashSetOfCharArray newHashSet = new WeakHashSetOfCharArray(this.elementSize * 2); // double the number of expected elements
- newHashSet.referenceQueue = this.referenceQueue;
- HashableWeakReference currentValue;
- for (int i = 0, length = this.values.length; i < length; i++)
- if ((currentValue = this.values[i]) != null)
- newHashSet.addValue(currentValue);
-
- this.values = newHashSet.values;
- this.threshold = newHashSet.threshold;
- this.elementSize = newHashSet.elementSize;
- }
-
- /*
- * Removes the char array that is in this set and that is equals to the given char array.
- * Return the char array that was in the set, or null if not found.
- */
- public char[] remove(char[] array) {
- cleanupGarbageCollectedValues();
- int valuesLength = this.values.length;
- int index = (CharOperation.hashCode(array) & 0x7FFFFFFF) % valuesLength;
- HashableWeakReference currentValue;
- while ((currentValue = this.values[index]) != null) {
- char[] referent;
- if (CharOperation.equals(array, referent = (char[]) currentValue.get())) {
- this.elementSize--;
- this.values[index] = null;
- rehash();
- return referent;
- }
- if (++index == valuesLength) {
- index = 0;
- }
- }
- return null;
- }
-
- public int size() {
- return this.elementSize;
- }
-
- public String toString() {
- StringBuffer buffer = new StringBuffer("{"); //$NON-NLS-1$
- for (int i = 0, length = this.values.length; i < length; i++) {
- HashableWeakReference value = this.values[i];
- if (value != null) {
- char[] ref = (char[]) value.get();
- if (ref != null) {
- buffer.append('\"');
- buffer.append(ref);
- buffer.append("\", "); //$NON-NLS-1$
- }
- }
- }
- buffer.append("}"); //$NON-NLS-1$
- return buffer.toString();
- }
-}
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
deleted file mode 100644
index 586b39ef..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/messages.properties
+++ /dev/null
@@ -1,247 +0,0 @@
-###############################################################################
-# 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
-###############################################################################
-
-### JavaModel messages.
-
-### hierarchy
-hierarchy_nullProject = Project argument cannot be null
-hierarchy_nullRegion = Region cannot be null
-hierarchy_nullFocusType = Type focus cannot be null
-hierarchy_creating = Creating type hierarchy...
-hierarchy_creatingOnType = Creating type hierarchy on {0}...
-
-### java element
-element_doesNotExist = {0} does not exist
-element_notOnClasspath = {0} is not on its project''s include path
-element_invalidClassFileName = JavaScript file name must end with .js
-element_reconciling = Reconciling...
-element_attachingSource = Attaching source...
-element_invalidResourceForProject = Illegal argument - must be one of IProject, IFolder, or IFile
-element_nullName = Name cannot be null
-element_nullType = Type cannot be null
-element_illegalParent = Illegal parent argument
-
-### java model operations
-operation_needElements = Operation requires one or more elements
-operation_needName = Operation requires a name
-operation_needPath = Operation requires a path
-operation_needAbsolutePath = Operation requires an absolute path. Relative path specified was: ''{0}''
-operation_needString = Operation requires a String.
-operation_notSupported = Operation not supported for specified element type(s):
-operation_cancelled = Operation cancelled
-operation_nullContainer = Container cannot be null
-operation_nullName = Name cannot be null
-operation_copyElementProgress = Copying elements...
-operation_moveElementProgress = Moving elements...
-operation_renameElementProgress = Renaming elements...
-operation_copyResourceProgress = Copying resources...
-operation_moveResourceProgress = Moving resources...
-operation_renameResourceProgress = Renaming resources...
-operation_createUnitProgress = Creating a JavaScript file...
-operation_createFieldProgress = Creating a field...
-operation_createImportsProgress = Creating imports...
-operation_createMethodProgress = Creating a function...
-operation_createPackageProgress = Creating a package declaration...
-operation_createPackageFragmentProgress = Creating package fragment(s)...
-operation_createTypeProgress = Creating a type...
-operation_deleteElementProgress = Deleting elements...
-operation_deleteResourceProgress = Deleting resources...
-operation_cannotRenameDefaultPackage = Default package cannot be renamed
-operation_pathOutsideProject = Path ''{0}'' must denote location inside project ''{1}''
-operation_sortelements = Sorting elements...
-
-### working copy
-workingCopy_commit = Committing working copy...
-
-### build status messages
-build_preparingBuild = Preparing to validate {0}
-build_readStateProgress = Reading saved validation state for project {0}
-build_saveStateProgress = Saving validation state for project {0}
-build_saveStateComplete = Saved in {0} ms
-build_readingDelta = Reading resource change information for {0}
-build_analyzingDeltas = Analyzing deltas
-build_analyzingSources = Analyzing sources
-build_compiling = Validating {0}
-build_foundHeader = Found
-build_fixedHeader = Fixed
-build_oneError = 1 error
-build_oneWarning = 1 warning
-build_multipleErrors = {0} errors
-build_multipleWarnings = {0} warnings
-build_done = Validation done
-
-### build errors
-build_wrongFileFormat = Wrong file format
-build_cannotSaveState = Error saving last validation state for project {0}
-build_cannotSaveStates = Error saving validation states
-build_initializationError = Validator initialization error
-build_serializationError = Validator serialization error
-
-### build inconsistencies
-#build_classFileCollision = Class file collision: {0}
-#build_duplicateClassFile = The type {0} is already defined
-#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_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_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
-
-### status
-status_cannotUseDeviceOnPath = Operation requires a path with no device. Path specified was: {0}
-status_coreException = Core exception
-status_defaultPackageReadOnly = Default folder is read-only
-status_evaluationError = Evaluation error: {0}
-status_JDOMError = JDOM error
-status_IOException = I/O exception
-status_indexOutOfBounds = Index out of bounds
-status_invalidContents = Invalid contents specified
-status_invalidDestination = Invalid destination: ''{0}''
-status_invalidName = Invalid name specified: {0}
-status_invalidPackage = Invalid folder: {0}
-status_invalidPath = Invalid path: ''{0}''
-status_invalidProject = Invalid project: {0}
-status_invalidResource = Invalid resource: {0}
-status_invalidResourceType = Invalid resource type for {0}
-status_invalidSibling = Invalid sibling: {0}
-status_nameCollision = {0} already exists in target
-status_noLocalContents = Cannot find local contents for resource: {0}
-status_OK = OK
-status_readOnly = {0} is read-only
-status_targetException = Target exception
-status_updateConflict = Update conflict
-status_cannot_retrieve_attached_javadoc = Cannot retrieve the attached JSDoc for {0}{1}
-status_unknown_javadoc_format = Unknown JSDoc format for {0}
-
-### classpath
-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_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 classpath 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_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}
-classpath_illegalProjectPath = Illegal path for required project: ''{0}'' in project {1}
-classpath_illegalSourceFolderPath = Illegal path for required source folder: ''{0}'' in project {1}
-classpath_illegalVariablePath = Illegal classpath variable path: ''{0}'' in project {1}, must have at least one segment
-classpath_invalidContainer = Invalid classpath container: ''{0}'' in project {1}
-classpath_mustEndWithSlash = End exclusion filter ''{0}'' with / to fully exclude ''{1}''
-classpath_unboundContainerPath = Unbound classpath container: ''{0}'' in project ''{1}''
-classpath_unboundLibrary = Project ''{1}'' is missing required library: ''{0}''
-classpath_unboundProject = Project ''{1}'' is missing required Java project: ''{0}''
-classpath_unboundSourceAttachment = Invalid source attachment: ''{0}'' for required library ''{1}'' in project ''{1}''
-classpath_unboundSourceFolder = Project ''{1}'' is missing required source folder: ''{0}''
-classpath_unboundVariablePath = Unbound classpath variable: ''{0}'' in project ''{1}''
-classpath_unknownKind = Unknown kind: ''{0}''
-classpath_xmlFormatError = XML format error in ''.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 classpath entry ''{1}'' for project ''{2}''
-classpath_deprecated_variable = Include path variable ''{0}'' in project ''{1}'' is deprecated: {2}
-
-### miscellaneous
-file_notFound = File not found: ''{0}''
-file_badFormat = Bad format
-path_nullPath = Path cannot be null
-path_mustBeAbsolute = Path must be absolute
-cache_invalidLoadFactor = Incorrect load factor
-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_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
-
-### access restrictions
-restrictedAccess_project = The type {0} is not accessible due to restriction on required project {1}
-restrictedAccess_library = The type {0} is not accessible due to restriction on required library {1}
-restrictedAccess_constructor_project = The constructor {0} is not accessible due to restriction on required project {1}
-restrictedAccess_constructor_library = The constructor {0} is not accessible due to restriction on required library {1}
-restrictedAccess_field_project = The field {0} from the type {1} is not accessible due to restriction on required project {2}
-restrictedAccess_field_library = The field {0} from the type {1} is not accessible due to restriction on required library {2}
-restrictedAccess_method_project = The function {0} from the type {1} is not accessible due to restriction on required project {2}
-restrictedAccess_method_library = The function {0} from the type {1} is not accessible due to restriction on required library {2}
-
-### java conventions
-convention_unit_nullName = JavaScript file name must not be null
-convention_unit_notJavaName = JavaScript file name must end with .js, or one of the registered JavaScript-like extensions
-convention_classFile_nullName = .class file name must not be null
-convention_classFile_notClassFileName = .class file name must end with .class
-convention_illegalIdentifier = ''{0}'' is not a valid JavaScript identifier
-convention_import_nullImport = An import declaration must not be null
-convention_import_unqualifiedImport = An import declaration must not end with an unqualified *
-convention_type_nullName = A JavaScript type name must not be null
-convention_type_nameWithBlanks = A JavaScript type name must not start or end with a blank
-convention_type_dollarName = By convention, JavaScript type names usually don't contain the $ character
-convention_type_lowercaseName = By convention, JavaScript type names usually start with an uppercase letter
-convention_type_invalidName = The type name ''{0}'' is not a valid identifier
-convention_package_nullName = A folder name must not be null
-convention_package_emptyName = A folder name must not be empty
-convention_package_dotName = A folder name cannot start or end with a dot
-convention_package_nameWithBlanks = A folder name must not start or end with a blank
-convention_package_consecutiveDotsName = A folder name must not contain two consecutive dots
-convention_package_uppercaseName = By convention, folder names usually start with a lowercase letter
-
-### DOM
-dom_cannotDetail = Unable to generate detailed source indexes
-dom_nullTypeParameter = Cannot add parameter with null type
-dom_nullNameParameter = Cannot add parameter with null name
-dom_nullReturnType = Return type cannot be null
-dom_nullExceptionType = Cannot add null exception
-dom_mismatchArgNamesAndTypes = Types and names must have identical length
-dom_addNullChild = Attempt to add null child
-dom_addIncompatibleChild = Attempt to add child of incompatible type
-dom_addChildWithParent = Attempt to add child that is already parented
-dom_unableAddChild = Attempt to add child to node that cannot have children
-dom_addAncestorAsChild = Attempt to add ancestor as child
-dom_addNullSibling = Attempt to insert null sibling
-dom_addSiblingBeforeRoot = Attempt to insert sibling before root node
-dom_addIncompatibleSibling = Attempt to insert sibling of incompatible type
-dom_addSiblingWithParent = Attempt to insert sibling that is already parented
-dom_addAncestorAsSibling = Attempt to insert ancestor as sibling
-dom_addNullInterface = Cannot add null interface
-dom_nullInterfaces = Illegal to set super interfaces to null
-
-### import rewrite
-importRewrite_processDescription = Updating imports
-
-### correction
-correction_nullRequestor = Requestor cannot be null
-correction_nullUnit = JavaScript file cannot be null
-
-### Eclipse JavaScript Core Search messages.
-
-engine_searching = Searching...
-engine_searching_indexing = Looking through {0} indexes...
-engine_searching_matching = Locating {0} matches...
-exception_wrongFormat = Wrong format
-process_name = JavaScript indexing
-manager_filesToIndex = {0} files to index
-manager_indexingInProgress = JavaScript indexing in progress
-
-### Disassembler messages
-
-
-### Project conversion
-converter_ConfiguringForJavaScript=Configuring for JavaScript
-converter_ConfiguringForBrowser=Configuring for Browser \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/AbortFormatting.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/AbortFormatting.java
deleted file mode 100644
index c3915b59..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/AbortFormatting.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.formatter;
-
-/**
- * Unchecked exception wrapping invalid input checked exception which may occur
- * when scanning original formatted source.
- *
- * @since 2.1
- */
-public class AbortFormatting extends RuntimeException {
-
- Throwable nestedException;
- private static final long serialVersionUID = -5796507276311428526L; // backward compatible
-
- public AbortFormatting(String message) {
- super(message);
- }
- public AbortFormatting(Throwable nestedException) {
- super(nestedException.getMessage());
- this.nestedException = nestedException;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/BinaryExpressionFragmentBuilder.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/BinaryExpressionFragmentBuilder.java
deleted file mode 100644
index 691b69c1..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/BinaryExpressionFragmentBuilder.java
+++ /dev/null
@@ -1,480 +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.formatter;
-
-import java.util.ArrayList;
-
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-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.AllocationExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ArrayAllocationExpression;
-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.ClassLiteralAccess;
-import org.eclipse.wst.jsdt.internal.compiler.ast.CombinedBinaryExpression;
-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.DoubleLiteral;
-import org.eclipse.wst.jsdt.internal.compiler.ast.EqualExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Expression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ExtendedStringLiteral;
-import org.eclipse.wst.jsdt.internal.compiler.ast.FalseLiteral;
-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.InstanceOfExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.IntLiteral;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ListExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.MessageSend;
-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.ObjectLiteral;
-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.QualifiedAllocationExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedNameReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedThisReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.RegExLiteral;
-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.StringLiteralConcatenation;
-import org.eclipse.wst.jsdt.internal.compiler.ast.SuperReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.ThisReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.TrueLiteral;
-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.lookup.BlockScope;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.ClassScope;
-import org.eclipse.wst.jsdt.internal.compiler.parser.TerminalTokens;
-
-class BinaryExpressionFragmentBuilder
- extends ASTVisitor {
-
- ArrayList fragmentsList;
- ArrayList operatorsList;
- private int realFragmentsSize;
-
- BinaryExpressionFragmentBuilder() {
- this.fragmentsList = new ArrayList();
- this.operatorsList = new ArrayList();
- this.realFragmentsSize = 0;
- }
-
- private final void addRealFragment(ASTNode node) {
- this.fragmentsList.add(node);
- this.realFragmentsSize++;
- }
-
- private final void addSmallFragment(ASTNode node) {
- this.fragmentsList.add(node);
- }
-
- private boolean buildFragments(Expression expression) {
- if (((expression.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT) != 0) {
- addRealFragment(expression);
- return false;
- } else {
- return true;
- }
- }
-
- public ASTNode[] fragments() {
- ASTNode[] fragments = new ASTNode[this.fragmentsList.size()];
- this.fragmentsList.toArray(fragments);
- return fragments;
- }
-
- public int[] operators() {
- int length = operatorsList.size();
- int[] tab = new int[length];
- for (int i = 0; i < length; i++) {
- tab[i] = ((Integer)operatorsList.get(i)).intValue();
- }
- return tab;
- }
-
- public int realFragmentsSize() {
- return this.realFragmentsSize;
- }
-
- public boolean visit(
- AllocationExpression allocationExpression,
- BlockScope scope) {
- this.addRealFragment(allocationExpression);
- return false;
- }
-
- public boolean visit(
- AND_AND_Expression and_and_Expression,
- BlockScope scope) {
-
- if (((and_and_Expression.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT) != 0) {
- addRealFragment(and_and_Expression);
- } else {
- and_and_Expression.left.traverse(this, scope);
- this.operatorsList.add(new Integer(TerminalTokens.TokenNameAND_AND));
- and_and_Expression.right.traverse(this, scope);
- }
- return false;
- }
-
- public boolean visit(
- ArrayAllocationExpression arrayAllocationExpression,
- BlockScope scope) {
- this.addRealFragment(arrayAllocationExpression);
- return false;
- }
-
- public boolean visit(ArrayInitializer arrayInitializer, BlockScope scope) {
- this.addRealFragment(arrayInitializer);
- return false;
- }
-
- public boolean visit(
- ArrayQualifiedTypeReference arrayQualifiedTypeReference,
- BlockScope scope) {
- this.addRealFragment(arrayQualifiedTypeReference);
- return false;
- }
-
- public boolean visit(
- ArrayQualifiedTypeReference arrayQualifiedTypeReference,
- ClassScope scope) {
- this.addRealFragment(arrayQualifiedTypeReference);
- return false;
- }
-
- public boolean visit(ArrayReference arrayReference, BlockScope scope) {
- this.addRealFragment(arrayReference);
- return false;
- }
-
- public boolean visit(
- ArrayTypeReference arrayTypeReference,
- BlockScope scope) {
- this.addRealFragment(arrayTypeReference);
- return false;
- }
-
- public boolean visit(
- ArrayTypeReference arrayTypeReference,
- ClassScope scope) {
- this.addRealFragment(arrayTypeReference);
- return false;
- }
-
- public boolean visit(Assignment assignment, BlockScope scope) {
- this.addRealFragment(assignment);
- return false;
- }
-
- public boolean visit(BinaryExpression binaryExpression, BlockScope scope) {
- if (binaryExpression instanceof CombinedBinaryExpression) {
- CombinedBinaryExpression expression = (CombinedBinaryExpression) binaryExpression;
- if (expression.referencesTable != null) {
- return this.visit(expression, scope);
- }
- }
- final int numberOfParens = (binaryExpression.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- this.addRealFragment(binaryExpression);
- } else {
- switch((binaryExpression.bits & ASTNode.OperatorMASK) >> ASTNode.OperatorSHIFT) {
- case OperatorIds.PLUS :
- if (buildFragments(binaryExpression)) {
- binaryExpression.left.traverse(this, scope);
- this.operatorsList.add(new Integer(TerminalTokens.TokenNamePLUS));
- binaryExpression.right.traverse(this, scope);
- }
- return false;
- case OperatorIds.MINUS :
- if (buildFragments(binaryExpression)) {
- binaryExpression.left.traverse(this, scope);
- this.operatorsList.add(new Integer(TerminalTokens.TokenNameMINUS));
- binaryExpression.right.traverse(this, scope);
- }
- return false;
- case OperatorIds.MULTIPLY :
- if (buildFragments(binaryExpression)) {
- binaryExpression.left.traverse(this, scope);
- this.operatorsList.add(new Integer(TerminalTokens.TokenNameMULTIPLY));
- binaryExpression.right.traverse(this, scope);
- }
- return false;
- case OperatorIds.REMAINDER :
- if (buildFragments(binaryExpression)) {
- binaryExpression.left.traverse(this, scope);
- this.operatorsList.add(new Integer(TerminalTokens.TokenNameREMAINDER));
- binaryExpression.right.traverse(this, scope);
- }
- return false;
- case OperatorIds.XOR :
- if (buildFragments(binaryExpression)) {
- binaryExpression.left.traverse(this, scope);
- this.operatorsList.add(new Integer(TerminalTokens.TokenNameXOR));
- binaryExpression.right.traverse(this, scope);
- }
- return false;
- case OperatorIds.DIVIDE :
- if (buildFragments(binaryExpression)) {
- binaryExpression.left.traverse(this, scope);
- this.operatorsList.add(new Integer(TerminalTokens.TokenNameDIVIDE));
- binaryExpression.right.traverse(this, scope);
- }
- return false;
- case OperatorIds.OR :
- if (buildFragments(binaryExpression)) {
- binaryExpression.left.traverse(this, scope);
- this.operatorsList.add(new Integer(TerminalTokens.TokenNameOR));
- binaryExpression.right.traverse(this, scope);
- }
- return false;
- case OperatorIds.AND :
- if (buildFragments(binaryExpression)) {
- binaryExpression.left.traverse(this, scope);
- this.operatorsList.add(new Integer(TerminalTokens.TokenNameAND));
- binaryExpression.right.traverse(this, scope);
- }
- return false;
- default:
- this.addRealFragment(binaryExpression);
- }
- }
- return false;
- }
-
- public boolean visit(CombinedBinaryExpression combinedBinaryExpression, BlockScope scope) {
- // keep implementation in sync with BinaryExpression#resolveType
- if (combinedBinaryExpression.referencesTable == null) {
- this.addRealFragment(combinedBinaryExpression.left);
- this.operatorsList.add(new Integer(TerminalTokens.TokenNamePLUS));
- this.addRealFragment(combinedBinaryExpression.right);
- return false;
- }
- BinaryExpression cursor = combinedBinaryExpression.referencesTable[0];
- if (cursor.left instanceof CombinedBinaryExpression) {
- this.visit((CombinedBinaryExpression) cursor.left, scope);
- } else {
- this.addRealFragment(cursor.left);
- }
- for (int i = 0, end = combinedBinaryExpression.arity; i < end; i ++) {
- this.operatorsList.add(new Integer(TerminalTokens.TokenNamePLUS));
- this.addRealFragment(combinedBinaryExpression.referencesTable[i].right);
- }
- this.operatorsList.add(new Integer(TerminalTokens.TokenNamePLUS));
- this.addRealFragment(combinedBinaryExpression.right);
- return false;
- }
-
- public boolean visit(
- ClassLiteralAccess classLiteralAccess,
- BlockScope scope) {
- this.addRealFragment(classLiteralAccess);
- return false;
- }
-
- public boolean visit(
- CompoundAssignment compoundAssignment,
- BlockScope scope) {
- this.addRealFragment(compoundAssignment);
- return false;
- }
-
- public boolean visit(
- ConditionalExpression conditionalExpression,
- BlockScope scope) {
- this.addRealFragment(conditionalExpression);
- return false;
- }
-
- public boolean visit(DoubleLiteral doubleLiteral, BlockScope scope) {
- this.addSmallFragment(doubleLiteral);
- return false;
- }
-
- public boolean visit(EqualExpression equalExpression, BlockScope scope) {
- this.addRealFragment(equalExpression);
- return false;
- }
-
- public boolean visit(
- ExtendedStringLiteral extendedStringLiteral,
- BlockScope scope) {
- this.addRealFragment(extendedStringLiteral);
- return false;
- }
-
- public boolean visit(FalseLiteral falseLiteral, BlockScope scope) {
- this.addSmallFragment(falseLiteral);
- return false;
- }
-
- public boolean visit(FieldReference fieldReference, BlockScope scope) {
- this.addRealFragment(fieldReference);
- return false;
- }
-
-
- public boolean visit(ObjectLiteral literal, BlockScope scope) {
- this.addRealFragment(literal);
- return false;
- }
-
- public boolean visit(UndefinedLiteral undefined, BlockScope scope) {
- this.addSmallFragment(undefined);
- return false;
- }
-
- public boolean visit(FunctionExpression functionExpression, BlockScope scope) {
- this.addRealFragment(functionExpression);
- return false;
- }
-
- public boolean visit(
- InstanceOfExpression instanceOfExpression,
- BlockScope scope) {
- this.addRealFragment(instanceOfExpression);
- return false;
- }
-
- public boolean visit(IntLiteral intLiteral, BlockScope scope) {
- this.addSmallFragment(intLiteral);
- return false;
- }
-
- public boolean visit(
- ListExpression listExpression,
- BlockScope scope) {
- this.addRealFragment(listExpression);
- return false;
- }
-
- public boolean visit(MessageSend messageSend, BlockScope scope) {
- this.addRealFragment(messageSend);
- return false;
- }
-
- public boolean visit(StringLiteralConcatenation stringLiteral, BlockScope scope) {
- if (((stringLiteral.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT) != 0) {
- addRealFragment(stringLiteral);
- return false;
- } else {
- for (int i = 0, max = stringLiteral.counter; i < max; i++) {
- this.addRealFragment(stringLiteral.literals[i]);
- if (i < max - 1) {
- this.operatorsList.add(new Integer(TerminalTokens.TokenNamePLUS));
- }
- }
- return false;
- }
- }
-
- public boolean visit(NullLiteral nullLiteral, BlockScope scope) {
- this.addRealFragment(nullLiteral);
- return false;
- }
-
- public boolean visit(OR_OR_Expression or_or_Expression, BlockScope scope) {
- if (((or_or_Expression.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT) != 0) {
- addRealFragment(or_or_Expression);
- } else {
- or_or_Expression.left.traverse(this, scope);
- this.operatorsList.add(new Integer(TerminalTokens.TokenNameOR_OR));
- or_or_Expression.right.traverse(this, scope);
- }
- return false;
- }
-
- public boolean visit(
- PostfixExpression postfixExpression,
- BlockScope scope) {
- this.addRealFragment(postfixExpression);
- return false;
- }
-
- public boolean visit(PrefixExpression prefixExpression, BlockScope scope) {
- this.addRealFragment(prefixExpression);
- return false;
- }
-
- public boolean visit(RegExLiteral regexLiteral, BlockScope scope) {
- this.addSmallFragment(regexLiteral);
- return false;
- }
-
-
- public boolean visit(
- QualifiedAllocationExpression qualifiedAllocationExpression,
- BlockScope scope) {
- this.addRealFragment(qualifiedAllocationExpression);
- return false;
- }
- public boolean visit(
- QualifiedNameReference qualifiedNameReference,
- BlockScope scope) {
- this.addRealFragment(qualifiedNameReference);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedThisReference, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(
- QualifiedThisReference qualifiedThisReference,
- BlockScope scope) {
- this.addRealFragment(qualifiedThisReference);
- return false;
- }
-
- public boolean visit(
- SingleNameReference singleNameReference,
- BlockScope scope) {
- this.addRealFragment(singleNameReference);
- return false;
- }
-
- public boolean visit(StringLiteral stringLiteral, BlockScope scope) {
- this.addRealFragment(stringLiteral);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.SuperReference, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(SuperReference superReference, BlockScope scope) {
- this.addRealFragment(superReference);
- return false;
- }
-
- public boolean visit(ThisReference thisReference, BlockScope scope) {
- this.addRealFragment(thisReference);
- return false;
- }
-
- public boolean visit(TrueLiteral trueLiteral, BlockScope scope) {
- this.addSmallFragment(trueLiteral);
- return false;
- }
-
- public boolean visit(UnaryExpression unaryExpression, BlockScope scope) {
- this.addRealFragment(unaryExpression);
- return false;
- }
-
- public int size() {
- return this.fragmentsList.size();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/CascadingMethodInvocationFragmentBuilder.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/CascadingMethodInvocationFragmentBuilder.java
deleted file mode 100644
index 3e9383b4..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/CascadingMethodInvocationFragmentBuilder.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.formatter;
-
-import java.util.ArrayList;
-
-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.MessageSend;
-import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope;
-
-class CascadingMethodInvocationFragmentBuilder
- extends ASTVisitor {
-
- ArrayList fragmentsList;
-
- CascadingMethodInvocationFragmentBuilder() {
- this.fragmentsList = new ArrayList();
- }
-
- public MessageSend[] fragments() {
- MessageSend[] fragments = new MessageSend[this.fragmentsList.size()];
- this.fragmentsList.toArray(fragments);
- return fragments;
- }
-
- public int size() {
- return this.fragmentsList.size();
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.MessageSend, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(MessageSend messageSend, BlockScope scope) {
- if ( messageSend.receiver==null || (messageSend.receiver.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT == 0) {
-
- if (messageSend.receiver!=null &&messageSend.receiver instanceof MessageSend) {
- this.fragmentsList.add(0, messageSend);
- messageSend.receiver.traverse(this, scope);
- return false;
- }
- this.fragmentsList.add(0, messageSend);
- this.fragmentsList.add(1, messageSend);
- } else {
- this.fragmentsList.add(0, messageSend);
- this.fragmentsList.add(1, messageSend);
- }
- return false;
- }
-}
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
deleted file mode 100644
index 0c431e20..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/CodeFormatterVisitor.java
+++ /dev/null
@@ -1,4783 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2002, 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.formatter;
-
-import java.util.ArrayList;
-import java.util.Map;
-
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-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.ArrayAllocationExpression;
-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.ClassLiteralAccess;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Clinit;
-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.DoStatement;
-import org.eclipse.wst.jsdt.internal.compiler.ast.DoubleLiteral;
-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.ForeachStatement;
-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.InstanceOfExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.IntLiteral;
-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.NullLiteral;
-import org.eclipse.wst.jsdt.internal.compiler.ast.OR_OR_Expression;
-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.QualifiedAllocationExpression;
-import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedNameReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedThisReference;
-import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedTypeReference;
-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.StringLiteralConcatenation;
-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.impl.CompilerOptions;
-import org.eclipse.wst.jsdt.internal.compiler.impl.Constant;
-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.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.parser.Scanner;
-import org.eclipse.wst.jsdt.internal.compiler.parser.TerminalTokens;
-import org.eclipse.wst.jsdt.internal.core.util.CodeSnippetParsingUtil;
-import org.eclipse.wst.jsdt.internal.formatter.align.Alignment;
-import org.eclipse.wst.jsdt.internal.formatter.align.AlignmentException;
-import org.eclipse.wst.jsdt.internal.formatter.comment.CommentRegion;
-
-/**
- * This class is responsible for formatting a valid java source code.
- * @since 2.1
- */
-/*
- <extension
- id="org.eclipse.wst.jsdt.core.newformatter.codeformatter"
- name="org.eclipse.wst.jsdt.core.newformatter.codeformatter"
- point="org.eclipse.wst.jsdt.core.codeFormatter">
- <codeFormatter
- class="org.eclipse.wst.jsdt.internal.formatter.CodeFormatterVisitor">
- </codeFormatter>
- </extension>
-*/
-public class CodeFormatterVisitor extends ASTVisitor {
-
- public static class MultiFieldDeclaration extends FieldDeclaration {
-
- FieldDeclaration[] declarations;
-
- MultiFieldDeclaration(FieldDeclaration[] declarations){
- this.declarations = declarations;
- this.modifiers = declarations[0].modifiers;
- }
- }
-
- public final static boolean DEBUG = false;
- private static final int NO_MODIFIERS = 0;
- /*
- * Set of expected tokens type for a single type reference.
- * This array needs to be SORTED.
- */
- private static final int[] SINGLETYPEREFERENCE_EXPECTEDTOKENS = new int[] {
- TerminalTokens.TokenNameIdentifier,
- TerminalTokens.TokenNameboolean,
- TerminalTokens.TokenNamebyte,
- TerminalTokens.TokenNamechar,
- TerminalTokens.TokenNamedouble,
- TerminalTokens.TokenNamefloat,
- TerminalTokens.TokenNameint,
- TerminalTokens.TokenNamelong,
- TerminalTokens.TokenNameshort,
- TerminalTokens.TokenNamevoid
- };
- private static final int[] CLOSING_GENERICS_EXPECTEDTOKENS = new int[] {
- TerminalTokens.TokenNameRIGHT_SHIFT,
- TerminalTokens.TokenNameUNSIGNED_RIGHT_SHIFT,
- TerminalTokens.TokenNameGREATER
- };
- private int chunkKind;
- public int lastLocalDeclarationSourceStart;
- private Scanner localScanner;
- public DefaultCodeFormatterOptions preferences;
- public Scribe scribe;
-
- public CodeFormatterVisitor(DefaultCodeFormatterOptions preferences, Map settings, int offset, int length, CodeSnippetParsingUtil codeSnippetParsingUtil) {
- long sourceLevel = settings == null
- ? ClassFileConstants.JDK1_3
- : CompilerOptions.versionToJdkLevel(settings.get(JavaScriptCore.COMPILER_SOURCE));
- this.localScanner = new Scanner(true, false, false/*nls*/, sourceLevel/*sourceLevel*/, null/*taskTags*/, null/*taskPriorities*/, true/*taskCaseSensitive*/);
-
- this.preferences = preferences;
- this.scribe = new Scribe(this, sourceLevel, offset, length, codeSnippetParsingUtil);
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#acceptProblem(org.eclipse.wst.jsdt.core.compiler.IProblem)
- */
- public void acceptProblem(IProblem problem) {
- super.acceptProblem(problem);
- }
-
- private BinaryExpressionFragmentBuilder buildFragments(BinaryExpression binaryExpression, BlockScope scope) {
- BinaryExpressionFragmentBuilder builder = new BinaryExpressionFragmentBuilder();
-
- if (binaryExpression instanceof CombinedBinaryExpression) {
- binaryExpression.traverse(builder, scope);
- return builder;
- }
- switch((binaryExpression.bits & ASTNode.OperatorMASK) >> ASTNode.OperatorSHIFT) {
- case OperatorIds.MULTIPLY :
- binaryExpression.left.traverse(builder, scope);
- builder.operatorsList.add(new Integer(TerminalTokens.TokenNameMULTIPLY));
- binaryExpression.right.traverse(builder, scope);
- break;
- case OperatorIds.PLUS :
- binaryExpression.left.traverse(builder, scope);
- builder.operatorsList.add(new Integer(TerminalTokens.TokenNamePLUS));
- binaryExpression.right.traverse(builder, scope);
- break;
- case OperatorIds.DIVIDE :
- binaryExpression.left.traverse(builder, scope);
- builder.operatorsList.add(new Integer(TerminalTokens.TokenNameDIVIDE));
- binaryExpression.right.traverse(builder, scope);
- break;
- case OperatorIds.REMAINDER :
- binaryExpression.left.traverse(builder, scope);
- builder.operatorsList.add(new Integer(TerminalTokens.TokenNameREMAINDER));
- binaryExpression.right.traverse(builder, scope);
- break;
- case OperatorIds.XOR :
- binaryExpression.left.traverse(builder, scope);
- builder.operatorsList.add(new Integer(TerminalTokens.TokenNameXOR));
- binaryExpression.right.traverse(builder, scope);
- break;
- case OperatorIds.MINUS :
- binaryExpression.left.traverse(builder, scope);
- builder.operatorsList.add(new Integer(TerminalTokens.TokenNameMINUS));
- binaryExpression.right.traverse(builder, scope);
- break;
- case OperatorIds.OR :
- binaryExpression.left.traverse(builder, scope);
- builder.operatorsList.add(new Integer(TerminalTokens.TokenNameOR));
- binaryExpression.right.traverse(builder, scope);
- break;
- case OperatorIds.AND :
- binaryExpression.left.traverse(builder, scope);
- builder.operatorsList.add(new Integer(TerminalTokens.TokenNameAND));
- binaryExpression.right.traverse(builder, scope);
- break;
- case OperatorIds.AND_AND :
- binaryExpression.left.traverse(builder, scope);
- builder.operatorsList.add(new Integer(TerminalTokens.TokenNameAND_AND));
- binaryExpression.right.traverse(builder, scope);
- break;
- case OperatorIds.OR_OR :
- binaryExpression.left.traverse(builder, scope);
- builder.operatorsList.add(new Integer(TerminalTokens.TokenNameOR_OR));
- binaryExpression.right.traverse(builder, scope);
- break;
- }
-
- return builder;
- }
-
- private CascadingMethodInvocationFragmentBuilder buildFragments(MessageSend messageSend, BlockScope scope) {
- CascadingMethodInvocationFragmentBuilder builder = new CascadingMethodInvocationFragmentBuilder();
-
- messageSend.traverse(builder, scope);
- return builder;
- }
- public boolean checkChunkStart(int kind) {
- if (this.chunkKind != kind) {
- this.chunkKind = kind;
- return true;
- }
- return false;
- }
-
- private boolean commentStartsBlock(int start, int end) {
- this.localScanner.resetTo(start, end);
- try {
- if (this.localScanner.getNextToken() == TerminalTokens.TokenNameLBRACE) {
- switch(this.localScanner.getNextToken()) {
- case TerminalTokens.TokenNameCOMMENT_BLOCK :
- case TerminalTokens.TokenNameCOMMENT_JAVADOC :
- case TerminalTokens.TokenNameCOMMENT_LINE :
- return true;
- }
- }
- } catch(InvalidInputException e) {
- // ignore
- }
- return false;
- }
-
- private ASTNode[] computeMergedMemberDeclarations(ASTNode[] nodes){
- ArrayList mergedNodes = new ArrayList();
- for (int i = 0, max = nodes.length; i < max; i++) {
- ASTNode currentNode = nodes[i];
- if (currentNode instanceof FieldDeclaration) {
- FieldDeclaration currentField = (FieldDeclaration) currentNode;
- if (mergedNodes.size() == 0) {
- // first node
- mergedNodes.add(currentNode);
- } else {
- // we need to check if the previous merged node is a field declaration
- ASTNode previousMergedNode = (ASTNode) mergedNodes.get(mergedNodes.size() - 1);
- if (previousMergedNode instanceof MultiFieldDeclaration) {
- // we merge the current node
- MultiFieldDeclaration multiFieldDeclaration = (MultiFieldDeclaration) previousMergedNode;
- int length = multiFieldDeclaration.declarations.length;
- System.arraycopy(multiFieldDeclaration.declarations, 0, multiFieldDeclaration.declarations= new FieldDeclaration[length+1], 0, length);
- multiFieldDeclaration.declarations[length] = currentField;
- } else if (previousMergedNode instanceof FieldDeclaration) {
- // need to check we need to create a multiple field declaration
- if (currentField.declarationSourceStart == ((FieldDeclaration) previousMergedNode).declarationSourceStart) {
- // we create a multi field declaration
- mergedNodes.set(mergedNodes.size() - 1, new MultiFieldDeclaration(new FieldDeclaration[]{ (FieldDeclaration)previousMergedNode, currentField}));
- } else {
- mergedNodes.add(currentNode);
- }
- } else {
- mergedNodes.add(currentNode);
- }
- }
- } else {
- mergedNodes.add(currentNode);
- }
- }
- if (mergedNodes.size() != nodes.length) {
- ASTNode[] result = new ASTNode[mergedNodes.size()];
- mergedNodes.toArray(result);
- return result;
- } else {
- return nodes;
- }
- }
-
- private ASTNode[] computeMergedMemberDeclarations(TypeDeclaration typeDeclaration){
-
- int fieldIndex = 0, fieldCount = (typeDeclaration.fields == null) ? 0 : typeDeclaration.fields.length;
- FieldDeclaration field = fieldCount == 0 ? null : typeDeclaration.fields[fieldIndex];
- int fieldStart = field == null ? Integer.MAX_VALUE : field.declarationSourceStart;
-
- int methodIndex = 0, methodCount = (typeDeclaration.methods == null) ? 0 : typeDeclaration.methods.length;
- AbstractMethodDeclaration method = methodCount == 0 ? null : typeDeclaration.methods[methodIndex];
- int methodStart = method == null ? Integer.MAX_VALUE : method.declarationSourceStart;
-
- int typeIndex = 0, typeCount = (typeDeclaration.memberTypes == null) ? 0 : typeDeclaration.memberTypes.length;
- TypeDeclaration type = typeCount == 0 ? null : typeDeclaration.memberTypes[typeIndex];
- int typeStart = type == null ? Integer.MAX_VALUE : type.declarationSourceStart;
-
- final int memberLength = fieldCount+methodCount+typeCount;
- ASTNode[] members = new ASTNode[memberLength];
- if (memberLength != 0) {
- int index = 0;
- int previousFieldStart = -1;
- do {
- if (fieldStart < methodStart && fieldStart < typeStart) {
- // next member is a field
- if (fieldStart == previousFieldStart){
- ASTNode previousMember = members[index - 1];
- if (previousMember instanceof MultiFieldDeclaration) {
- MultiFieldDeclaration multiField = (MultiFieldDeclaration) previousMember;
- int length = multiField.declarations.length;
- System.arraycopy(multiField.declarations, 0, multiField.declarations=new FieldDeclaration[length+1], 0, length);
- multiField.declarations[length] = field;
- } else {
- members[index - 1] = new MultiFieldDeclaration(new FieldDeclaration[]{ (FieldDeclaration)previousMember, field});
- }
- } else {
- members[index++] = field;
- }
- previousFieldStart = fieldStart;
- if (++fieldIndex < fieldCount) { // find next field if any
- fieldStart = (field = typeDeclaration.fields[fieldIndex]).declarationSourceStart;
- } else {
- fieldStart = Integer.MAX_VALUE;
- }
- } else if (methodStart < fieldStart && methodStart < typeStart) {
- // next member is a method
- if (!method.isDefaultConstructor() && !method.isClinit()) {
- members[index++] = method;
- }
- if (++methodIndex < methodCount) { // find next method if any
- methodStart = (method = typeDeclaration.methods[methodIndex]).declarationSourceStart;
- } else {
- methodStart = Integer.MAX_VALUE;
- }
- } else {
- // next member is a type
- members[index++] = type;
- if (++typeIndex < typeCount) { // find next type if any
- typeStart = (type = typeDeclaration.memberTypes[typeIndex]).declarationSourceStart;
- } else {
- typeStart = Integer.MAX_VALUE;
- }
- }
- } while ((fieldIndex < fieldCount) || (typeIndex < typeCount) || (methodIndex < methodCount));
-
- if (members.length != index) {
- System.arraycopy(members, 0, members=new ASTNode[index], 0, index);
- }
- }
- return members;
- }
-
- private boolean dumpBinaryExpression(
- BinaryExpression binaryExpression,
- int operator,
- BlockScope scope) {
-
-// boolean addSpace= operator==TerminalTokens.TokenNamein || operator==TerminalTokens.TokenNameinstanceof;
- final int numberOfParens = (binaryExpression.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
-
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(binaryExpression, numberOfParens);
- }
- BinaryExpressionFragmentBuilder builder = buildFragments(binaryExpression, scope);
- final int fragmentsSize = builder.size();
-
- if ((builder.realFragmentsSize() > 1 || builder.size() > 4) && numberOfParens == 0) {
- this.scribe.printComment();
- Alignment binaryExpressionAlignment = this.scribe.createAlignment("binaryExpressionAlignment", this.preferences.alignment_for_binary_expression, Alignment.R_OUTERMOST, fragmentsSize, this.scribe.scanner.currentPosition); //$NON-NLS-1$
- this.scribe.enterAlignment(binaryExpressionAlignment);
- boolean ok = false;
- ASTNode[] fragments = builder.fragments();
- int[] operators = builder.operators();
- do {
- try {
- for (int i = 0; i < fragmentsSize - 1; i++) {
- ASTNode fragment = fragments[i];
- fragment.traverse(this, scope);
- this.scribe.printTrailingComment();
- if (this.scribe.lastNumberOfNewLines == 1) {
- // a new line has been inserted by printTrailingComment()
- this.scribe.indentationLevel = binaryExpressionAlignment.breakIndentationLevel;
- }
- if (this.preferences.wrap_before_binary_operator) {
- this.scribe.alignFragment(binaryExpressionAlignment, i);
- this.scribe.printNextToken(operators[i], this.preferences.insert_space_before_binary_operator);
- } else {
- this.scribe.printNextToken(operators[i], this.preferences.insert_space_before_binary_operator);
- this.scribe.alignFragment(binaryExpressionAlignment, i);
- }
- if (operators[i] == TerminalTokens.TokenNameMINUS && isNextToken(TerminalTokens.TokenNameMINUS)) {
- // the next character is a minus (unary operator)
- this.scribe.space();
- }
- if (this.preferences.insert_space_after_binary_operator) {
- this.scribe.space();
- }
- }
- fragments[fragmentsSize - 1].traverse(this, scope);
- this.scribe.printTrailingComment();
- ok = true;
- } catch(AlignmentException e){
- this.scribe.redoAlignment(e);
- }
- } while (!ok);
- this.scribe.exitAlignment(binaryExpressionAlignment, true);
- } else {
- binaryExpression.left.traverse(this, scope);
- this.scribe.printNextToken(operator, this.preferences.insert_space_before_binary_operator);
- if (operator == TerminalTokens.TokenNameMINUS && isNextToken(TerminalTokens.TokenNameMINUS)) {
- // the next character is a minus (unary operator)
- this.scribe.space();
- }
- if (this.preferences.insert_space_after_binary_operator) {
- this.scribe.space();
- }
- binaryExpression.right.traverse(this, scope);
- }
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(binaryExpression, numberOfParens);
- }
- return false;
- }
-
- private boolean dumpEqualityExpression(
- BinaryExpression binaryExpression,
- int operator,
- BlockScope scope) {
-
- final int numberOfParens = (binaryExpression.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
-
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(binaryExpression, numberOfParens);
- }
- binaryExpression.left.traverse(this, scope);
- this.scribe.printNextToken(operator, this.preferences.insert_space_before_binary_operator);
- if (this.preferences.insert_space_after_binary_operator) {
- this.scribe.space();
- }
- binaryExpression.right.traverse(this, scope);
-
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(binaryExpression, numberOfParens);
- }
- return false;
- }
-
- private final TextEdit failedToFormat() {
- if (DEBUG) {
- System.out.println("COULD NOT FORMAT \n" + this.scribe.scanner); //$NON-NLS-1$
- System.out.println(this.scribe);
- }
- return null;
- }
-
- private void format(
- AbstractMethodDeclaration methodDeclaration,
- ClassScope scope,
- boolean isChunkStart,
- boolean isFirstClassBodyDeclaration) {
-
- if (isFirstClassBodyDeclaration) {
- int newLinesBeforeFirstClassBodyDeclaration = this.preferences.blank_lines_before_first_class_body_declaration;
- if (newLinesBeforeFirstClassBodyDeclaration > 0) {
- this.scribe.printEmptyLines(newLinesBeforeFirstClassBodyDeclaration);
- }
- } else {
- final int newLineBeforeChunk = isChunkStart ? this.preferences.blank_lines_before_new_chunk : 0;
- if (newLineBeforeChunk > 0) {
- this.scribe.printEmptyLines(newLineBeforeChunk);
- }
- }
- final int newLinesBeforeMethod = this.preferences.blank_lines_before_method;
- if (newLinesBeforeMethod > 0 && !isFirstClassBodyDeclaration) {
- this.scribe.printEmptyLines(newLinesBeforeMethod);
- } else if (this.scribe.line != 0 || this.scribe.column != 1) {
- this.scribe.printNewLine();
- }
- methodDeclaration.traverse(this, scope);
- }
-
- private void format(AbstractVariableDeclaration fieldDeclaration, ASTVisitor visitor, MethodScope scope, boolean isChunkStart, boolean isFirstClassBodyDeclaration) {
-
- if (isFirstClassBodyDeclaration) {
- int newLinesBeforeFirstClassBodyDeclaration = this.preferences.blank_lines_before_first_class_body_declaration;
- if (newLinesBeforeFirstClassBodyDeclaration > 0) {
- this.scribe.printEmptyLines(newLinesBeforeFirstClassBodyDeclaration);
- }
- } else {
- int newLineBeforeChunk = isChunkStart ? this.preferences.blank_lines_before_new_chunk : 0;
- if (newLineBeforeChunk > 0) {
- this.scribe.printEmptyLines(newLineBeforeChunk);
- }
- final int newLinesBeforeField = this.preferences.blank_lines_before_field;
- if (newLinesBeforeField > 0) {
- this.scribe.printEmptyLines(newLinesBeforeField);
- }
- }
- Alignment memberAlignment = this.scribe.getMemberAlignment();
-
- this.scribe.printComment();
- this.scribe.printModifiers(this);
- this.scribe.space();
-
- this.scribe.printNextToken(TerminalTokens.TokenNamevar, true);
-
-
- /*
- * Field type
- */
-// fieldDeclaration.type.traverse(this, scope);
-
- /*
- * Field name
- */
- this.scribe.alignFragment(memberAlignment, 0);
-
- this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier, true);
-
- /*
- * Check for extra dimensions
- */
- int extraDimensions = getDimensions();
- if (extraDimensions != 0) {
- for (int i = 0; i < extraDimensions; i++) {
- this.scribe.printNextToken(TerminalTokens.TokenNameLBRACKET);
- this.scribe.printNextToken(TerminalTokens.TokenNameRBRACKET);
- }
- }
-
- /*
- * Field initialization
- */
- final Expression initialization = fieldDeclaration.initialization;
- if (initialization != null) {
- this.scribe.alignFragment(memberAlignment, 1);
- this.scribe.printNextToken(TerminalTokens.TokenNameEQUAL, this.preferences.insert_space_before_assignment_operator);
- if (this.preferences.insert_space_after_assignment_operator) {
- this.scribe.space();
- }
- Alignment assignmentAlignment = this.scribe.createAlignment("fieldDeclarationAssignmentAlignment", this.preferences.alignment_for_assignment, Alignment.R_OUTERMOST, 1, this.scribe.scanner.currentPosition); //$NON-NLS-1$
- this.scribe.enterAlignment(assignmentAlignment);
- boolean ok = false;
- do {
- try {
- this.scribe.alignFragment(assignmentAlignment, 0);
- initialization.traverse(this, scope);
- ok = true;
- } catch(AlignmentException e){
- this.scribe.redoAlignment(e);
- }
- } while (!ok);
- this.scribe.exitAlignment(assignmentAlignment, true);
- }
-
- this.scribe.printOptionalNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
-
- if (memberAlignment != null) {
- this.scribe.alignFragment(memberAlignment, 2);
- this.scribe.printTrailingComment();
- } else {
- this.scribe.space();
- this.scribe.printTrailingComment();
- }
- }
-
- private void format(ImportReference importRef, boolean isLast) {
- if (importRef.isInternal())
- return;
- this.scribe.printNextToken(TerminalTokens.TokenNameimport);
- this.preferences.number_of_empty_lines_to_preserve = this.preferences.blank_lines_between_import_groups;
- this.scribe.space();
- if ((importRef.bits & ASTNode.OnDemand) != 0) {
- this.scribe.printQualifiedReference(importRef.sourceEnd);
- this.scribe.printNextToken(TerminalTokens.TokenNameDOT);
- this.scribe.printNextToken(TerminalTokens.TokenNameMULTIPLY);
- this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- } else {
- this.scribe.printQualifiedReference(importRef.sourceEnd);
- this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- }
- if (isLast) {
- this.scribe.printTrailingComment();
- } else {
- this.scribe.printTrailingComment(this.preferences.blank_lines_between_import_groups);
- }
- this.scribe.printNewLine();
- }
-
-
- private void format(MultiFieldDeclaration multiFieldDeclaration, ASTVisitor visitor, MethodScope scope, boolean isChunkStart, boolean isFirstClassBodyDeclaration) {
-
- if (isFirstClassBodyDeclaration) {
- int newLinesBeforeFirstClassBodyDeclaration = this.preferences.blank_lines_before_first_class_body_declaration;
- if (newLinesBeforeFirstClassBodyDeclaration > 0) {
- this.scribe.printEmptyLines(newLinesBeforeFirstClassBodyDeclaration);
- }
- } else {
- int newLineBeforeChunk = isChunkStart ? this.preferences.blank_lines_before_new_chunk : 0;
- if (newLineBeforeChunk > 0) {
- this.scribe.printEmptyLines(newLineBeforeChunk);
- }
- final int newLinesBeforeField = this.preferences.blank_lines_before_field;
- if (newLinesBeforeField > 0) {
- this.scribe.printEmptyLines(newLinesBeforeField);
- }
- }
- Alignment fieldAlignment = this.scribe.getMemberAlignment();
-
- this.scribe.printComment();
- this.scribe.printModifiers(this);
- this.scribe.space();
-
- multiFieldDeclaration.declarations[0].type.traverse(this, scope);
-
- final int multipleFieldDeclarationsLength = multiFieldDeclaration.declarations.length;
-
- Alignment multiFieldDeclarationsAlignment =this.scribe.createAlignment(
- "multiple_field",//$NON-NLS-1$
- this.preferences.alignment_for_multiple_fields,
- multipleFieldDeclarationsLength - 1,
- this.scribe.scanner.currentPosition);
- this.scribe.enterAlignment(multiFieldDeclarationsAlignment);
-
- boolean ok = false;
- do {
- try {
- for (int i = 0, length = multipleFieldDeclarationsLength; i < length; i++) {
- FieldDeclaration fieldDeclaration = multiFieldDeclaration.declarations[i];
- /*
- * Field name
- */
- if (i == 0) {
- this.scribe.alignFragment(fieldAlignment, 0);
- this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier, true);
- } else {
- this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier, false);
- }
-
- /*
- * Check for extra dimensions
- */
- int extraDimensions = getDimensions();
- if (extraDimensions != 0) {
- for (int index = 0; index < extraDimensions; index++) {
- this.scribe.printNextToken(TerminalTokens.TokenNameLBRACKET);
- this.scribe.printNextToken(TerminalTokens.TokenNameRBRACKET);
- }
- }
-
- /*
- * Field initialization
- */
- final Expression initialization = fieldDeclaration.initialization;
- if (initialization != null) {
- if (i == 0) {
- this.scribe.alignFragment(fieldAlignment, 1);
- }
- this.scribe.printNextToken(TerminalTokens.TokenNameEQUAL, this.preferences.insert_space_before_assignment_operator);
- if (this.preferences.insert_space_after_assignment_operator) {
- this.scribe.space();
- }
- initialization.traverse(this, scope);
- }
-
- if (i != length - 1) {
- this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_multiple_field_declarations);
- this.scribe.printTrailingComment();
- this.scribe.alignFragment(multiFieldDeclarationsAlignment, i);
-
- if (this.preferences.insert_space_after_comma_in_multiple_field_declarations) {
- this.scribe.space();
- }
- } else {
- this.scribe.printOptionalNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.alignFragment(fieldAlignment, 2);
- this.scribe.printTrailingComment();
- }
- }
- ok = true;
- } catch (AlignmentException e) {
- this.scribe.redoAlignment(e);
- }
- } while (!ok);
- this.scribe.exitAlignment(multiFieldDeclarationsAlignment, true);
- }
-
- /**
- * @see org.eclipse.wst.jsdt.core.formatter.CodeFormatter#format(int, String, int, int, int, String)
- */
- public TextEdit format(String string, ASTNode[] nodes) {
- // reset the scribe
- this.scribe.reset();
-
- long startTime = System.currentTimeMillis();
-
- final char[] compilationUnitSource = string.toCharArray();
-
- this.localScanner.setSource(compilationUnitSource);
- this.scribe.initializeScanner(compilationUnitSource);
-
- if (nodes == null) {
- return null;
- }
-
- this.lastLocalDeclarationSourceStart = -1;
- try {
- formatClassBodyDeclarations(nodes);
- } catch(AbortFormatting e){
- return failedToFormat();
- }
- if (DEBUG){
- System.out.println("Formatting time: " + (System.currentTimeMillis() - startTime)); //$NON-NLS-1$
- }
- return this.scribe.getRootEdit();
- }
-
- /**
- * @see org.eclipse.wst.jsdt.core.formatter.CodeFormatter#format(int, String, int, int, int, String)
- */
- public TextEdit format(String string, CompilationUnitDeclaration compilationUnitDeclaration) {
- // reset the scribe
- this.scribe.reset();
-
- if (compilationUnitDeclaration == null || compilationUnitDeclaration.ignoreFurtherInvestigation) {
- return failedToFormat();
- }
-
- long startTime = System.currentTimeMillis();
-
- final char[] compilationUnitSource = string.toCharArray();
-
- this.localScanner.setSource(compilationUnitSource);
- this.scribe.initializeScanner(compilationUnitSource);
-
- this.lastLocalDeclarationSourceStart = -1;
- try {
- compilationUnitDeclaration.traverse(this, compilationUnitDeclaration.scope);
- } catch(AbortFormatting e){
- return failedToFormat();
- }
- if (DEBUG){
- System.out.println("Formatting time: " + (System.currentTimeMillis() - startTime)); //$NON-NLS-1$
- }
- return this.scribe.getRootEdit();
- }
-
- /**
- * @see org.eclipse.wst.jsdt.core.formatter.CodeFormatter#format(int, String, int, int, int, String)
- */
- public TextEdit format(String string, ConstructorDeclaration constructorDeclaration) {
- // reset the scribe
- this.scribe.reset();
-
- long startTime = System.currentTimeMillis();
-
- final char[] compilationUnitSource = string.toCharArray();
-
- this.localScanner.setSource(compilationUnitSource);
- this.scribe.initializeScanner(compilationUnitSource);
-
- if (constructorDeclaration == null) {
- return null;
- }
-
- this.lastLocalDeclarationSourceStart = -1;
- try {
- ExplicitConstructorCall explicitConstructorCall = constructorDeclaration.constructorCall;
- if (explicitConstructorCall != null && !explicitConstructorCall.isImplicitSuper()) {
- explicitConstructorCall.traverse(this, null);
- }
- Statement[] statements = constructorDeclaration.statements;
- if (statements != null) {
- formatStatements(null, statements, false);
- }
- if (hasComments()) {
- this.scribe.printNewLine();
- }
- this.scribe.printComment();
- } catch(AbortFormatting e){
- return failedToFormat();
- }
- if (DEBUG){
- System.out.println("Formatting time: " + (System.currentTimeMillis() - startTime)); //$NON-NLS-1$
- }
- return this.scribe.getRootEdit();
- }
-
- /**
- * @see org.eclipse.wst.jsdt.core.formatter.CodeFormatter#format(int, String, int, int, int, String)
- */
- public TextEdit format(String string, Expression expression) {
- // reset the scribe
- this.scribe.reset();
-
- long startTime = System.currentTimeMillis();
-
- final char[] compilationUnitSource = string.toCharArray();
-
- this.localScanner.setSource(compilationUnitSource);
- this.scribe.initializeScanner(compilationUnitSource);
-
- if (expression == null) {
- return null;
- }
-
- this.lastLocalDeclarationSourceStart = -1;
- try {
- expression.traverse(this, (BlockScope) null);
- this.scribe.printComment();
- } catch(AbortFormatting e){
- return failedToFormat();
- }
- if (DEBUG){
- System.out.println("Formatting time: " + (System.currentTimeMillis() - startTime)); //$NON-NLS-1$
- }
- return this.scribe.getRootEdit();
- }
-
- /**
- * @see org.eclipse.wst.jsdt.core.formatter.CodeFormatter#format(int, String, int, int, int, String)
- */
- public TextEdit format(String string, CommentRegion region) {
- // reset the scribe
- this.scribe.reset();
-
- if (region == null) {
- return failedToFormat();
- }
-
- long startTime = 0;
- if (DEBUG){
- startTime = System.currentTimeMillis();
- }
-
- final char[] compilationUnitSource = string.toCharArray();
-
- this.scribe.initializeScanner(compilationUnitSource);
-
- TextEdit result = null;
- try {
- result = region.format(this.preferences.initial_indentation_level, true);
- } catch(AbortFormatting e){
- return failedToFormat();
- }
- if (DEBUG){
- System.out.println("Formatting time: " + (System.currentTimeMillis() - startTime)); //$NON-NLS-1$
- }
- return result;
- }
-
- private void format(TypeDeclaration typeDeclaration){
- /*
- * Print comments to get proper line number
- */
- this.scribe.printComment();
- int line = this.scribe.line;
-
- this.scribe.printModifiers(this);
-
- if (this.scribe.line > line) {
- // annotations introduced new line, but this is not a line wrapping
- // see 158267
- line = this.scribe.line;
- }
-
- /*
- * Type name
- */
- switch(TypeDeclaration.kind(typeDeclaration.modifiers)) {
- case TypeDeclaration.CLASS_DECL :
- this.scribe.printNextToken(TerminalTokens.TokenNameclass, true);
- break;
- }
- this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier, true);
-
- /*
- * Superclass
- */
- final TypeReference superclass = typeDeclaration.superclass;
- if (superclass != null) {
- Alignment superclassAlignment =this.scribe.createAlignment(
- "superclass", //$NON-NLS-1$
- this.preferences.alignment_for_superclass_in_type_declaration,
- 2,
- this.scribe.scanner.currentPosition);
- this.scribe.enterAlignment(superclassAlignment);
- boolean ok = false;
- do {
- try {
- this.scribe.alignFragment(superclassAlignment, 0);
- this.scribe.printNextToken(TerminalTokens.TokenNameextends, true);
- this.scribe.alignFragment(superclassAlignment, 1);
- this.scribe.space();
- superclass.traverse(this, typeDeclaration.scope);
- ok = true;
- } catch (AlignmentException e) {
- this.scribe.redoAlignment(e);
- }
- } while (!ok);
- this.scribe.exitAlignment(superclassAlignment, true);
- }
-
- /*
- * Type body
- */
- String class_declaration_brace;
- boolean space_before_opening_brace;
- int kind = TypeDeclaration.kind(typeDeclaration.modifiers);
-
- class_declaration_brace = this.preferences.brace_position_for_type_declaration;
- space_before_opening_brace = this.preferences.insert_space_before_opening_brace_in_type_declaration;
-
- formatLeftCurlyBrace(line, class_declaration_brace);
- formatTypeOpeningBrace(class_declaration_brace, space_before_opening_brace, typeDeclaration);
-
- boolean indent_body_declarations_compare_to_header;
-
- indent_body_declarations_compare_to_header = this.preferences.indent_body_declarations_compare_to_type_header;
-
- if (indent_body_declarations_compare_to_header) {
- this.scribe.indent();
- }
-
- formatTypeMembers(typeDeclaration);
-
- if (indent_body_declarations_compare_to_header) {
- this.scribe.unIndent();
- }
-
- if (this.preferences.insert_new_line_in_empty_type_declaration) {
- this.scribe.printNewLine();
- }
-
- this.scribe.printNextToken(TerminalTokens.TokenNameRBRACE);
- this.scribe.printTrailingComment();
- if (class_declaration_brace.equals(DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED)) {
- this.scribe.unIndent();
- }
- if (hasComments()) {
- this.scribe.printNewLine();
- }
- }
-
- private void format(
- TypeDeclaration memberTypeDeclaration,
- ClassScope scope,
- boolean isChunkStart,
- boolean isFirstClassBodyDeclaration) {
-
- if (isFirstClassBodyDeclaration) {
- int newLinesBeforeFirstClassBodyDeclaration = this.preferences.blank_lines_before_first_class_body_declaration;
- if (newLinesBeforeFirstClassBodyDeclaration > 0) {
- this.scribe.printEmptyLines(newLinesBeforeFirstClassBodyDeclaration);
- }
- } else {
- int newLineBeforeChunk = isChunkStart ? this.preferences.blank_lines_before_new_chunk : 0;
- if (newLineBeforeChunk > 0) {
- this.scribe.printEmptyLines(newLineBeforeChunk);
- }
- final int newLinesBeforeMember = this.preferences.blank_lines_before_member_type;
- if (newLinesBeforeMember > 0) {
- this.scribe.printEmptyLines(newLinesBeforeMember);
- }
- }
- memberTypeDeclaration.traverse(this, scope);
- }
-
- private void formatAnonymousTypeDeclaration(TypeDeclaration typeDeclaration) {
- /*
- * Type body
- */
- String anonymous_type_declaration_brace_position = this.preferences.brace_position_for_anonymous_type_declaration;
-
- formatTypeOpeningBrace(anonymous_type_declaration_brace_position, this.preferences.insert_space_before_opening_brace_in_anonymous_type_declaration, typeDeclaration);
-
- this.scribe.indent();
-
- formatTypeMembers(typeDeclaration);
-
- this.scribe.unIndent();
- if (this.preferences.insert_new_line_in_empty_anonymous_type_declaration) {
- this.scribe.printNewLine();
- }
- this.scribe.printNextToken(TerminalTokens.TokenNameRBRACE);
- if (anonymous_type_declaration_brace_position.equals(DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED)) {
- this.scribe.unIndent();
- }
- }
-
- /**
- * @param block
- * @param scope
- * @param block_brace_position
- */
- private void formatBlock(Block block, BlockScope scope, String block_brace_position, boolean insertSpaceBeforeOpeningBrace) {
- formatOpeningBrace(block_brace_position, insertSpaceBeforeOpeningBrace);
- final Statement[] statements = block.statements;
- if (statements != null) {
- this.scribe.printNewLine();
- if (this.preferences.indent_statements_compare_to_block) {
- this.scribe.indent();
- }
- formatStatements(scope, statements, true);
- this.scribe.printComment();
-
- if (this.preferences.indent_statements_compare_to_block) {
- this.scribe.unIndent();
- }
- } else if (this.preferences.insert_new_line_in_empty_block) {
- this.scribe.printNewLine();
- if (this.preferences.indent_statements_compare_to_block) {
- this.scribe.indent();
- }
- this.scribe.printComment();
-
- if (this.preferences.indent_statements_compare_to_block) {
- this.scribe.unIndent();
- }
- } else {
- if (this.preferences.indent_statements_compare_to_block) {
- this.scribe.indent();
- }
- this.scribe.printComment();
-
- if (this.preferences.indent_statements_compare_to_block) {
- this.scribe.unIndent();
- }
- }
- this.scribe.printNextToken(TerminalTokens.TokenNameRBRACE);
- this.scribe.printTrailingComment();
- if (DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED.equals(block_brace_position)) {
- this.scribe.unIndent();
- }
- }
-
- private void formatCascadingMessageSends(CascadingMethodInvocationFragmentBuilder builder, BlockScope scope) {
- int size = builder.size();
- MessageSend[] fragments = builder.fragments();
- Expression fragment = fragments[0].receiver;
- int startingPositionInCascade = 1;
- if (fragment!=null &&!fragment.isImplicitThis()) {
- fragment.traverse(this, scope);
- } else {
- MessageSend currentMessageSend = fragments[1];
- final int numberOfParens = (currentMessageSend.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(currentMessageSend, numberOfParens);
- }
- ASTNode[] arguments = currentMessageSend.arguments;
- this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier); // selector
- this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, this.preferences.insert_space_before_opening_paren_in_method_invocation);
- if (arguments != null) {
- if (this.preferences.insert_space_after_opening_paren_in_method_invocation) {
- this.scribe.space();
- }
- int argumentLength = arguments.length;
- Alignment argumentsAlignment = this.scribe.createAlignment(
- "messageArguments", //$NON-NLS-1$
- this.preferences.alignment_for_arguments_in_method_invocation,
- Alignment.R_OUTERMOST,
- argumentLength,
- this.scribe.scanner.currentPosition);
- this.scribe.enterAlignment(argumentsAlignment);
- boolean okForArguments = false;
- do {
- try {
- for (int j = 0; j < argumentLength; j++) {
- if (j > 0) {
- this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_method_invocation_arguments);
- this.scribe.printTrailingComment();
- }
- this.scribe.alignFragment(argumentsAlignment, j);
- if (j > 0 && this.preferences.insert_space_after_comma_in_method_invocation_arguments) {
- this.scribe.space();
- }
- arguments[j].traverse(this, scope);
- }
- okForArguments = true;
- } catch (AlignmentException e) {
- this.scribe.redoAlignment(e);
- }
- } while (!okForArguments);
- this.scribe.exitAlignment(argumentsAlignment, true);
- this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_before_closing_paren_in_method_invocation);
- } else {
- this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_between_empty_parens_in_method_invocation);
- }
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(currentMessageSend, numberOfParens);
- }
- startingPositionInCascade = 2;
- }
- Alignment cascadingMessageSendAlignment =
- this.scribe.createAlignment(
- "cascadingMessageSendAlignment", //$NON-NLS-1$
- this.preferences.alignment_for_selector_in_method_invocation,
- Alignment.R_INNERMOST,
- size,
- this.scribe.scanner.currentPosition);
- this.scribe.enterAlignment(cascadingMessageSendAlignment);
- boolean ok = false;
- do {
- try {
- this.scribe.alignFragment(cascadingMessageSendAlignment, 0);
- //this.scribe.printNextToken(TerminalTokens.TokenNameDOT);
- // Fix for https://bugs.eclipse.org/bugs/show_bug.cgi?id=221018
- // functions can return functions in javascript so there won't always be a dot
- this.scribe.printOptionalNextToken(TerminalTokens.TokenNameDOT, false);
- for (int i = startingPositionInCascade; i < size; i++) {
- MessageSend currentMessageSend = fragments[i];
- final int numberOfParens = (currentMessageSend.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(currentMessageSend, numberOfParens);
- }
- ASTNode[] arguments = currentMessageSend.arguments;
- // Fix for https://bugs.eclipse.org/bugs/show_bug.cgi?id=221018
- // functions can return functions in javascript so there won't always be another identifier name
- this.scribe.printOptionalNextToken(TerminalTokens.TokenNameIdentifier, false); // selector
- this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, this.preferences.insert_space_before_opening_paren_in_method_invocation);
- if (arguments != null) {
- if (this.preferences.insert_space_after_opening_paren_in_method_invocation) {
- this.scribe.space();
- }
- int argumentLength = arguments.length;
- Alignment argumentsAlignment = this.scribe.createAlignment(
- "messageArguments", //$NON-NLS-1$
- this.preferences.alignment_for_arguments_in_method_invocation,
- Alignment.R_OUTERMOST,
- argumentLength,
- this.scribe.scanner.currentPosition);
- this.scribe.enterAlignment(argumentsAlignment);
- boolean okForArguments = false;
- do {
- try {
- for (int j = 0; j < argumentLength; j++) {
- if (j > 0) {
- this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_method_invocation_arguments);
- this.scribe.printTrailingComment();
- }
- this.scribe.alignFragment(argumentsAlignment, j);
- if (j > 0 && this.preferences.insert_space_after_comma_in_method_invocation_arguments) {
- this.scribe.space();
- }
- arguments[j].traverse(this, scope);
- }
- okForArguments = true;
- } catch (AlignmentException e) {
- this.scribe.redoAlignment(e);
- }
- } while (!okForArguments);
- this.scribe.exitAlignment(argumentsAlignment, true);
- this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_before_closing_paren_in_method_invocation);
- } else {
- this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_between_empty_parens_in_method_invocation);
- }
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(currentMessageSend, numberOfParens);
- }
- if (i < size - 1) {
- this.scribe.alignFragment(cascadingMessageSendAlignment, i);
- this.scribe.printOptionalNextToken(TerminalTokens.TokenNameDOT, false);
- }
- }
- ok = true;
- } catch(AlignmentException e){
- this.scribe.redoAlignment(e);
- }
- } while (!ok);
- this.scribe.exitAlignment(cascadingMessageSendAlignment, true);
- }
-
- /*
- * Merged traversal of member (types, fields, methods)
- */
- private void formatClassBodyDeclarations(ASTNode[] nodes) {
- final int FIELD = 1, METHOD = 2;//, TYPE = 3;
- this.scribe.lastNumberOfNewLines = 1;
- ASTNode[] mergedNodes = computeMergedMemberDeclarations(nodes);
- Alignment memberAlignment = this.scribe.createMemberAlignment("typeMembers", this.preferences.align_type_members_on_columns ? Alignment.M_MULTICOLUMN : Alignment.M_NO_ALIGNMENT, 4, this.scribe.scanner.currentPosition); //$NON-NLS-1$
- this.scribe.enterMemberAlignment(memberAlignment);
- boolean isChunkStart = false;
- boolean ok = false;
- int startIndex = 0;
- do {
- try {
- for (int i = startIndex, max = mergedNodes.length; i < max; i++) {
- ASTNode member = mergedNodes[i];
- if (member instanceof FieldDeclaration) {
- isChunkStart = memberAlignment.checkChunkStart(FIELD, i, this.scribe.scanner.currentPosition);
- if (member instanceof MultiFieldDeclaration){
- MultiFieldDeclaration multiField = (MultiFieldDeclaration) member;
- format(multiField, this, null, isChunkStart, i == 0);
- } else if (member instanceof Initializer) {
- int newLineBeforeChunk = isChunkStart ? this.preferences.blank_lines_before_new_chunk : 0;
- if (newLineBeforeChunk > 0 && i != 0) {
- this.scribe.printEmptyLines(newLineBeforeChunk);
- } else if (i == 0) {
- int newLinesBeforeFirstClassBodyDeclaration = this.preferences.blank_lines_before_first_class_body_declaration;
- if (newLinesBeforeFirstClassBodyDeclaration > 0) {
- this.scribe.printEmptyLines(newLinesBeforeFirstClassBodyDeclaration);
- }
- }
- Initializer initializer = (Initializer) member;
- initializer.traverse(this, null);
- } else {
- FieldDeclaration field = (FieldDeclaration) member;
- format(field, this, null, isChunkStart, i == 0);
- }
- } else if (member instanceof LocalDeclaration) {
- LocalDeclaration field = (LocalDeclaration) member;
- format(field, this, null, isChunkStart, i == 0);
- } else if (member instanceof AbstractMethodDeclaration) {
- isChunkStart = memberAlignment.checkChunkStart(METHOD, i, this.scribe.scanner.currentPosition);
- format((AbstractMethodDeclaration) member, null, isChunkStart, i == 0);
- } else {
-// isChunkStart = memberAlignment.checkChunkStart(TYPE, i, this.scribe.scanner.currentPosition);
-// format((TypeDeclaration)member, null, isChunkStart, i == 0);
- member.traverse(this, null);
- }
- if (isNextToken(TerminalTokens.TokenNameSEMICOLON)) {
- this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- }
- if (i != max - 1) {
- this.scribe.printNewLine();
- }
- }
- ok = true;
- } catch(AlignmentException e){
- startIndex = memberAlignment.chunkStartIndex;
- this.scribe.redoMemberAlignment(e);
- }
- } while (!ok);
- this.scribe.exitMemberAlignment(memberAlignment);
- if (hasComments()) {
- this.scribe.printNewLine();
- }
- this.scribe.printComment();
- }
-
- private void formatEmptyTypeDeclaration(boolean isFirst) {
- boolean hasSemiColon = isNextToken(TerminalTokens.TokenNameSEMICOLON);
- while(isNextToken(TerminalTokens.TokenNameSEMICOLON)) {
- this.scribe.printComment();
- this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- }
- if (hasSemiColon && isFirst) {
- this.scribe.printNewLine();
- }
- }
-
- private void formatGuardClauseBlock(Block block, BlockScope scope) {
-
- this.scribe.printNextToken(TerminalTokens.TokenNameLBRACE, this.preferences.insert_space_before_opening_brace_in_block);
- this.scribe.space();
-
- final Statement[] statements = block.statements;
- statements[0].traverse(this, scope);
- this.scribe.printNextToken(TerminalTokens.TokenNameRBRACE, true);
- this.scribe.printTrailingComment();
- }
-
- private void formatLeftCurlyBrace(final int line, final String bracePosition) {
- /*
- * deal with (quite unexpected) comments right before lcurly
- */
- this.scribe.printComment();
- if (DefaultCodeFormatterConstants.NEXT_LINE_ON_WRAP.equals(bracePosition)
- && (this.scribe.line > line || this.scribe.column >= this.preferences.page_width))
- {
- this.scribe.printNewLine();
- }
- }
-
- private void formatLocalDeclaration(LocalDeclaration localDeclaration, BlockScope scope, boolean insertSpaceBeforeComma, boolean insertSpaceAfterComma) {
-
- if (!isMultipleLocalDeclaration(localDeclaration)) {
- if (localDeclaration.modifiers != NO_MODIFIERS) {
- this.scribe.printComment();
- this.scribe.printModifiers(this);
- this.scribe.space();
- }
-
- this.scribe.printNextToken(TerminalTokens.TokenNamevar, true);
-
- /*
- * Argument type
- */
- if (localDeclaration.type != null) {
- localDeclaration.type.traverse(this, scope);
- }
- /*
- * Print the argument name
- */
- this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier, true);
- } else {
- /*
- * Print the argument name
- */
- this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier, false);
- }
- /*
- * Check for extra dimensions
- */
- int extraDimensions = getDimensions();
- if (extraDimensions != 0) {
- for (int index = 0; index < extraDimensions; index++) {
- this.scribe.printNextToken(TerminalTokens.TokenNameLBRACKET);
- this.scribe.printNextToken(TerminalTokens.TokenNameRBRACKET);
- }
- }
-
- final Expression initialization = localDeclaration.initialization;
- if (initialization != null) {
- /*
- * Print the method name
- */
- this.scribe.printNextToken(TerminalTokens.TokenNameEQUAL, this.preferences.insert_space_before_assignment_operator);
- if (this.preferences.insert_space_after_assignment_operator) {
- this.scribe.space();
- }
- Alignment assignmentAlignment = this.scribe.createAlignment("localDeclarationAssignmentAlignment", this.preferences.alignment_for_assignment, Alignment.R_OUTERMOST, 1, this.scribe.scanner.currentPosition); //$NON-NLS-1$
- this.scribe.enterAlignment(assignmentAlignment);
- boolean ok = false;
- do {
- try {
- this.scribe.alignFragment(assignmentAlignment, 0);
- initialization.traverse(this, scope);
- ok = true;
- } catch(AlignmentException e){
- this.scribe.redoAlignment(e);
- }
- } while (!ok);
- this.scribe.exitAlignment(assignmentAlignment, true);
- }
-
- if (isPartOfMultipleLocalDeclaration()) {
- this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, insertSpaceBeforeComma);
- if (insertSpaceAfterComma) {
- this.scribe.space();
- }
- this.scribe.printTrailingComment();
- }
- }
-
- private void formatMessageSend(
- MessageSend messageSend,
- BlockScope scope,
- Alignment messageAlignment) {
-
- if (messageAlignment != null) {
- this.scribe.alignFragment(messageAlignment, 0);
- if (messageSend.selector!=null)
- this.scribe.printNextToken(TerminalTokens.TokenNameDOT);
- }
- if (messageSend.selector!=null)
- this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier); // selector
- this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, this.preferences.insert_space_before_opening_paren_in_method_invocation);
-
- final Expression[] arguments = messageSend.arguments;
- if (arguments != null) {
- if (this.preferences.insert_space_after_opening_paren_in_method_invocation) {
- this.scribe.space();
- }
- int argumentsLength = arguments.length;
- if (argumentsLength > 1) {
- Alignment argumentsAlignment = this.scribe.createAlignment(
- "messageArguments", //$NON-NLS-1$
- this.preferences.alignment_for_arguments_in_method_invocation,
- argumentsLength,
- this.scribe.scanner.currentPosition);
- this.scribe.enterAlignment(argumentsAlignment);
- boolean ok = false;
- do {
- try {
- for (int i = 0; i < argumentsLength; i++) {
- if (i > 0) {
- this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_method_invocation_arguments);
- this.scribe.printTrailingComment();
- }
- this.scribe.alignFragment(argumentsAlignment, i);
- if (i > 0 && this.preferences.insert_space_after_comma_in_method_invocation_arguments) {
- this.scribe.space();
- }
- arguments[i].traverse(this, scope);
- }
- ok = true;
- } catch (AlignmentException e) {
- this.scribe.redoAlignment(e);
- }
- } while (!ok);
- this.scribe.exitAlignment(argumentsAlignment, true);
- } else {
- for (int i = 0; i < argumentsLength; i++) {
- if (i > 0) {
- this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_method_invocation_arguments);
- this.scribe.printTrailingComment();
- }
- if (i > 0 && this.preferences.insert_space_after_comma_in_method_invocation_arguments) {
- this.scribe.space();
- }
- arguments[i].traverse(this, scope);
- }
- }
- this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_before_closing_paren_in_method_invocation);
- } else {
- this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_between_empty_parens_in_method_invocation);
- }
- }
-
- private void formatMethodArguments(
- AbstractMethodDeclaration methodDeclaration,
- boolean spaceBeforeOpenParen,
- boolean spaceBetweenEmptyParameters,
- boolean spaceBeforeClosingParen,
- boolean spaceBeforeFirstParameter,
- boolean spaceBeforeComma,
- boolean spaceAfterComma,
- int methodDeclarationParametersAlignment) {
-
- this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, spaceBeforeOpenParen);
-
- final Argument[] arguments = methodDeclaration.arguments;
- if (arguments != null) {
- if (spaceBeforeFirstParameter) {
- this.scribe.space();
- }
- int argumentLength = arguments.length;
- Alignment argumentsAlignment = this.scribe.createAlignment(
- "methodArguments",//$NON-NLS-1$
- methodDeclarationParametersAlignment,
- argumentLength,
- this.scribe.scanner.currentPosition);
- this.scribe.enterAlignment(argumentsAlignment);
- boolean ok = false;
- do {
- try {
- for (int i = 0; i < argumentLength; i++) {
- if (i > 0) {
- this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, spaceBeforeComma);
- this.scribe.printTrailingComment();
- }
- this.scribe.alignFragment(argumentsAlignment, i);
- if (i > 0 && spaceAfterComma) {
- this.scribe.space();
- }
- arguments[i].traverse(this, methodDeclaration.scope);
- }
- ok = true;
- } catch (AlignmentException e) {
- this.scribe.redoAlignment(e);
- }
- } while (!ok);
- this.scribe.exitAlignment(argumentsAlignment, true);
-
- this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, spaceBeforeClosingParen);
- } else {
- this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, spaceBetweenEmptyParameters);
- }
- }
-
- private void formatEnumConstantArguments(
- FieldDeclaration enumConstant,
- boolean spaceBeforeOpenParen,
- boolean spaceBetweenEmptyParameters,
- boolean spaceBeforeClosingParen,
- boolean spaceBeforeFirstParameter,
- boolean spaceBeforeComma,
- boolean spaceAfterComma,
- int methodDeclarationParametersAlignment) {
-
- if (!isNextToken(TerminalTokens.TokenNameLPAREN)) {
- return;
- }
-
- this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, spaceBeforeOpenParen);
- final Expression[] arguments = ((AllocationExpression) enumConstant.initialization).arguments;
- if (arguments != null) {
- int argumentLength = arguments.length;
- Alignment argumentsAlignment = this.scribe.createAlignment(
- "enumConstantArguments",//$NON-NLS-1$
- methodDeclarationParametersAlignment,
- argumentLength,
- this.scribe.scanner.currentPosition);
- this.scribe.enterAlignment(argumentsAlignment);
- boolean ok = false;
- do {
- try {
- if (spaceBeforeFirstParameter) {
- this.scribe.space();
- }
- for (int i = 0; i < argumentLength; i++) {
- if (i > 0) {
- this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, spaceBeforeComma);
- this.scribe.printTrailingComment();
- }
- this.scribe.alignFragment(argumentsAlignment, i);
- if (i > 0 && spaceAfterComma) {
- this.scribe.space();
- }
- arguments[i].traverse(this, (BlockScope) null);
- }
- ok = true;
- } catch (AlignmentException e) {
- this.scribe.redoAlignment(e);
- }
- } while (!ok);
- this.scribe.exitAlignment(argumentsAlignment, true);
-
- this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, spaceBeforeClosingParen);
- } else {
- this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, spaceBetweenEmptyParameters);
- }
- }
-
- private void formatNecessaryEmptyStatement() {
- if (this.preferences.put_empty_statement_on_new_line) {
- this.scribe.printNewLine();
- this.scribe.indent();
- this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- this.scribe.unIndent();
- } else {
- this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- }
- }
-
- private void formatOpeningBrace(String bracePosition, boolean insertSpaceBeforeBrace) {
-
- if (DefaultCodeFormatterConstants.NEXT_LINE.equals(bracePosition)) {
- this.scribe.printNewLine();
- } else if (DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED.equals(bracePosition)) {
- this.scribe.printNewLine();
- this.scribe.indent();
- }
- this.scribe.printNextToken(TerminalTokens.TokenNameLBRACE, insertSpaceBeforeBrace);
-
- this.scribe.printTrailingComment();
- }
-
-
- private void formatOpeningBracket(String bracePosition, boolean insertSpaceBeforeBrace) {
-
- if (DefaultCodeFormatterConstants.NEXT_LINE.equals(bracePosition)) {
- this.scribe.printNewLine();
- } else if (DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED.equals(bracePosition)) {
- this.scribe.printNewLine();
- this.scribe.indent();
- }
- this.scribe.printNextToken(TerminalTokens.TokenNameLBRACKET, insertSpaceBeforeBrace);
-
- this.scribe.printTrailingComment();
- }
- private void formatStatements(BlockScope scope, final Statement[] statements, boolean insertNewLineAfterLastStatement) {
- int statementsLength = statements.length;
- for (int i = 0; i < statementsLength; i++) {
- final Statement statement = statements[i];
- if (i > 0 && (statements[i - 1] instanceof EmptyStatement) && !(statement instanceof EmptyStatement)) {
- this.scribe.printNewLine();
- }
- statement.traverse(this, scope);
- if (statement instanceof Expression) {
- this.scribe.printOptionalNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- if (i != statementsLength - 1) {
- if (!(statement instanceof EmptyStatement) && !(statements[i + 1] instanceof EmptyStatement)) {
- this.scribe.printNewLine();
- }
- } else if (i == statementsLength - 1 && insertNewLineAfterLastStatement) {
- this.scribe.printNewLine();
- }
- } else if (statement instanceof LocalDeclaration) {
- LocalDeclaration currentLocal = (LocalDeclaration) statement;
- if (i < (statementsLength - 1)) {
- /*
- * We need to check that the next statement is a local declaration
- */
- if (statements[i + 1] instanceof LocalDeclaration) {
- LocalDeclaration nextLocal = (LocalDeclaration) statements[i + 1];
- if (currentLocal.declarationSourceStart != nextLocal.declarationSourceStart) {
- this.scribe.printOptionalNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- if (i != statementsLength - 1) {
- if (!(statement instanceof EmptyStatement) && !(statements[i + 1] instanceof EmptyStatement)) {
- this.scribe.printNewLine();
- }
- } else if (i == statementsLength - 1 && insertNewLineAfterLastStatement) {
- this.scribe.printNewLine();
- }
- }
- } else {
- this.scribe.printOptionalNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- if (i != statementsLength - 1) {
- if (!(statement instanceof EmptyStatement) && !(statements[i + 1] instanceof EmptyStatement)) {
- this.scribe.printNewLine();
- }
- } else if (i == statementsLength - 1 && insertNewLineAfterLastStatement) {
- this.scribe.printNewLine();
- }
- }
- } else {
- this.scribe.printOptionalNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- if (i != statementsLength - 1) {
- if (!(statement instanceof EmptyStatement) && !(statements[i + 1] instanceof EmptyStatement)) {
- this.scribe.printNewLine();
- }
- } else if (i == statementsLength - 1 && insertNewLineAfterLastStatement) {
- this.scribe.printNewLine();
- }
- }
- } else if (i != statementsLength - 1) {
- if (!(statement instanceof EmptyStatement) && !(statements[i + 1] instanceof EmptyStatement)) {
- this.scribe.printNewLine();
- }
- } else if (i == statementsLength - 1 && insertNewLineAfterLastStatement) {
- this.scribe.printNewLine();
- }
- }
- }
-
- /*
- * Merged traversal of member (types, fields, methods)
- */
- private void formatTypeMembers(TypeDeclaration typeDeclaration) {
- Alignment memberAlignment = this.scribe.createMemberAlignment("typeMembers", this.preferences.align_type_members_on_columns ? Alignment.M_MULTICOLUMN : Alignment.M_NO_ALIGNMENT, 3, this.scribe.scanner.currentPosition); //$NON-NLS-1$
- this.scribe.enterMemberAlignment(memberAlignment);
- ASTNode[] members = computeMergedMemberDeclarations(typeDeclaration);
- boolean isChunkStart = false;
- boolean ok = false;
- int startIndex = 0;
- do {
- try {
- for (int i = startIndex, max = members.length; i < max; i++) {
- ASTNode member = members[i];
- if (member instanceof FieldDeclaration) {
- isChunkStart = memberAlignment.checkChunkStart(Alignment.CHUNK_FIELD, i, this.scribe.scanner.currentPosition);
- if (member instanceof MultiFieldDeclaration) {
- MultiFieldDeclaration multiField = (MultiFieldDeclaration) member;
-
- if (multiField.isStatic()) {
- format(multiField, this, typeDeclaration.staticInitializerScope, isChunkStart, i == 0);
- } else {
- format(multiField, this, typeDeclaration.initializerScope, isChunkStart, i == 0);
- }
- } else if (member instanceof Initializer) {
- int newLineBeforeChunk = isChunkStart ? this.preferences.blank_lines_before_new_chunk : 0;
- if (newLineBeforeChunk > 0 && i != 0) {
- this.scribe.printEmptyLines(newLineBeforeChunk);
- } else if (i == 0) {
- int newLinesBeforeFirstClassBodyDeclaration = this.preferences.blank_lines_before_first_class_body_declaration;
- if (newLinesBeforeFirstClassBodyDeclaration > 0) {
- this.scribe.printEmptyLines(newLinesBeforeFirstClassBodyDeclaration);
- }
- }
- Initializer initializer = (Initializer) member;
- if (initializer.isStatic()) {
- initializer.traverse(this, typeDeclaration.staticInitializerScope);
- } else {
- initializer.traverse(this, typeDeclaration.initializerScope);
- }
- } else {
- FieldDeclaration field = (FieldDeclaration) member;
- if (field.isStatic()) {
- format(field, this, typeDeclaration.staticInitializerScope, isChunkStart, i == 0);
- } else {
- format(field, this, typeDeclaration.initializerScope, isChunkStart, i == 0);
- }
- }
- } else if (member instanceof AbstractMethodDeclaration) {
- isChunkStart = memberAlignment.checkChunkStart(Alignment.CHUNK_METHOD, i, this.scribe.scanner.currentPosition);
- format((AbstractMethodDeclaration) member, typeDeclaration.scope, isChunkStart, i == 0);
- } else if (member instanceof TypeDeclaration) {
- isChunkStart = memberAlignment.checkChunkStart(Alignment.CHUNK_TYPE, i, this.scribe.scanner.currentPosition);
- format((TypeDeclaration)member, typeDeclaration.scope, isChunkStart, i == 0);
- }
- if (isNextToken(TerminalTokens.TokenNameSEMICOLON)) {
- this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- }
- this.scribe.printNewLine();
- // realign to the proper value
- if (this.scribe.memberAlignment != null) {
- // select the last alignment
- this.scribe.indentationLevel = this.scribe.memberAlignment.originalIndentationLevel;
- }
- }
- ok = true;
- } catch(AlignmentException e){
- startIndex = memberAlignment.chunkStartIndex;
- this.scribe.redoMemberAlignment(e);
- }
- } while (!ok);
- this.scribe.printComment();
- this.scribe.exitMemberAlignment(memberAlignment);
- }
-
- private void formatTypeOpeningBraceForEnumConstant(String bracePosition, boolean insertSpaceBeforeBrace, TypeDeclaration typeDeclaration) {
- int fieldCount = (typeDeclaration.fields == null) ? 0 : typeDeclaration.fields.length;
- int methodCount = (typeDeclaration.methods == null) ? 0 : typeDeclaration.methods.length;
- int typeCount = (typeDeclaration.memberTypes == null) ? 0 : typeDeclaration.memberTypes.length;
-
- if (methodCount <= 2) {
- for (int i = 0, max = methodCount; i < max; i++) {
- final AbstractMethodDeclaration abstractMethodDeclaration = typeDeclaration.methods[i];
- if (abstractMethodDeclaration.isDefaultConstructor()) {
- methodCount--;
- } else if (abstractMethodDeclaration.isClinit()) {
- methodCount--;
- }
- }
- }
- final int memberLength = fieldCount + methodCount+typeCount;
-
- boolean insertNewLine = memberLength > 0;
-
- if (!insertNewLine) {
- if ((typeDeclaration.bits & ASTNode.IsAnonymousType) != 0) {
- insertNewLine = this.preferences.insert_new_line_in_empty_enum_constant;
- }
- }
-
- formatOpeningBrace(bracePosition, insertSpaceBeforeBrace);
-
- if (insertNewLine) {
- this.scribe.printNewLine();
- }
- }
- private void formatTypeOpeningBrace(String bracePosition, boolean insertSpaceBeforeBrace, TypeDeclaration typeDeclaration) {
- int fieldCount = (typeDeclaration.fields == null) ? 0 : typeDeclaration.fields.length;
- int methodCount = (typeDeclaration.methods == null) ? 0 : typeDeclaration.methods.length;
- int typeCount = (typeDeclaration.memberTypes == null) ? 0 : typeDeclaration.memberTypes.length;
-
- if (methodCount <= 2) {
- for (int i = 0, max = methodCount; i < max; i++) {
- final AbstractMethodDeclaration abstractMethodDeclaration = typeDeclaration.methods[i];
- if (abstractMethodDeclaration.isDefaultConstructor()) {
- methodCount--;
- } else if (abstractMethodDeclaration.isClinit()) {
- methodCount--;
- }
- }
- }
- final int memberLength = fieldCount + methodCount + typeCount;
-
- boolean insertNewLine = memberLength > 0;
-
- if (!insertNewLine) {
- if ((typeDeclaration.bits & ASTNode.IsAnonymousType) != 0) {
- insertNewLine = this.preferences.insert_new_line_in_empty_anonymous_type_declaration;
- } else {
- insertNewLine = this.preferences.insert_new_line_in_empty_type_declaration;
- }
- }
-
- formatOpeningBrace(bracePosition, insertSpaceBeforeBrace);
-
- if (insertNewLine) {
- this.scribe.printNewLine();
- }
- }
- private int getDimensions() {
-
- this.localScanner.resetTo(this.scribe.scanner.currentPosition, this.scribe.scannerEndPosition - 1);
- int dimensions = 0;
- int balance = 0;
- try {
- int token;
- loop: while ((token = this.localScanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
- switch(token) {
- case TerminalTokens.TokenNameRBRACKET:
- dimensions++;
- balance--;
- break;
- case TerminalTokens.TokenNameCOMMENT_BLOCK :
- case TerminalTokens.TokenNameCOMMENT_JAVADOC :
- case TerminalTokens.TokenNameCOMMENT_LINE :
- break;
- case TerminalTokens.TokenNameLBRACKET :
- balance++;
- break;
- default:
- break loop;
- }
- }
- } catch(InvalidInputException e) {
- // ignore
- }
- if (balance == 0) {
- return dimensions;
- }
- return 0;
- }
-
- private boolean hasComments() {
-
- this.localScanner.resetTo(this.scribe.scanner.startPosition, this.scribe.scannerEndPosition - 1);
- try {
- switch(this.localScanner.getNextToken()) {
- case TerminalTokens.TokenNameCOMMENT_BLOCK :
- case TerminalTokens.TokenNameCOMMENT_JAVADOC :
- case TerminalTokens.TokenNameCOMMENT_LINE :
- return true;
- }
- } catch(InvalidInputException e) {
- // ignore
- }
- return false;
- }
-
- private boolean isNextToken(int tokenName) {
- this.localScanner.resetTo(this.scribe.scanner.currentPosition, this.scribe.scannerEndPosition - 1);
- try {
- int token = this.localScanner.getNextToken();
- loop: while(true) {
- switch(token) {
- case TerminalTokens.TokenNameCOMMENT_BLOCK :
- case TerminalTokens.TokenNameCOMMENT_JAVADOC :
- case TerminalTokens.TokenNameCOMMENT_LINE :
- token = this.localScanner.getNextToken();
- continue loop;
- default:
- break loop;
- }
- }
- return token == tokenName;
- } catch(InvalidInputException e) {
- // ignore
- }
- return false;
- }
-
- private boolean isClosingGenericToken() {
- this.localScanner.resetTo(this.scribe.scanner.currentPosition, this.scribe.scannerEndPosition - 1);
- try {
- int token = this.localScanner.getNextToken();
- loop: while(true) {
- switch(token) {
- case TerminalTokens.TokenNameCOMMENT_BLOCK :
- case TerminalTokens.TokenNameCOMMENT_JAVADOC :
- case TerminalTokens.TokenNameCOMMENT_LINE :
- token = this.localScanner.getNextToken();
- continue loop;
- default:
- break loop;
- }
- }
- switch(token) {
- case TerminalTokens.TokenNameGREATER :
- case TerminalTokens.TokenNameRIGHT_SHIFT :
- case TerminalTokens.TokenNameUNSIGNED_RIGHT_SHIFT :
- return true;
- }
- } catch(InvalidInputException e) {
- // ignore
- }
- return false;
- }
-
- private boolean isGuardClause(Block block) {
- return !commentStartsBlock(block.sourceStart, block.sourceEnd)
- && block.statements != null
- && block.statements.length == 1
- && (block.statements[0] instanceof ReturnStatement || block.statements[0] instanceof ThrowStatement);
- }
-
- private boolean isMultipleLocalDeclaration(LocalDeclaration localDeclaration) {
-
- if (localDeclaration.declarationSourceStart == this.lastLocalDeclarationSourceStart) return true;
- this.lastLocalDeclarationSourceStart = localDeclaration.declarationSourceStart;
- return false;
- }
-
- private boolean isPartOfMultipleLocalDeclaration() {
- this.localScanner.resetTo(this.scribe.scanner.currentPosition, this.scribe.scannerEndPosition - 1);
- try {
- int token;
- while ((token = this.localScanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
- switch(token) {
- case TerminalTokens.TokenNameCOMMA ://90
- return true;
- case TerminalTokens.TokenNameCOMMENT_BLOCK :
- case TerminalTokens.TokenNameCOMMENT_JAVADOC :
- case TerminalTokens.TokenNameCOMMENT_LINE :
- break;
- default:
- return false;
- }
- }
- } catch(InvalidInputException e) {
- // ignore
- }
- return false;
- }
-
- private void manageClosingParenthesizedExpression(Expression expression, int numberOfParens) {
- for (int i = 0; i < numberOfParens; i++) {
- this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_before_closing_paren_in_parenthesized_expression);
- }
- }
-
- private void manageOpeningParenthesizedExpression(Expression expression, int numberOfParens) {
- for (int i = 0; i < numberOfParens; i++) {
- this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, this.preferences.insert_space_before_opening_paren_in_parenthesized_expression);
- if (this.preferences.insert_space_after_opening_paren_in_parenthesized_expression) {
- this.scribe.space();
- }
- }
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.AllocationExpression, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(
- AllocationExpression allocationExpression,
- BlockScope scope) {
- // 'new' ClassType '(' ArgumentListopt ')' ClassBodyopt
-
- final int numberOfParens = (allocationExpression.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(allocationExpression, numberOfParens);
- }
- this.scribe.printNextToken(TerminalTokens.TokenNamenew);
- this.scribe.space();
-
- if (allocationExpression.type!=null)
- allocationExpression.type.traverse(this, scope);
- else
- allocationExpression.member.traverse(this, scope);
-
- if (!allocationExpression.isShort) {
- this.scribe
- .printNextToken(
- TerminalTokens.TokenNameLPAREN,
- this.preferences.insert_space_before_opening_paren_in_method_invocation);
- final Expression[] arguments = allocationExpression.arguments;
- if (arguments != null) {
- if (this.preferences.insert_space_after_opening_paren_in_method_invocation) {
- this.scribe.space();
- }
- int argumentLength = arguments.length;
- Alignment argumentsAlignment = this.scribe
- .createAlignment(
- "allocation",//$NON-NLS-1$
- this.preferences.alignment_for_arguments_in_allocation_expression,
- argumentLength,
- this.scribe.scanner.currentPosition);
- this.scribe.enterAlignment(argumentsAlignment);
- boolean ok = false;
- do {
- try {
- for (int i = 0; i < argumentLength; i++) {
- if (i > 0) {
- this.scribe
- .printNextToken(
- TerminalTokens.TokenNameCOMMA,
- this.preferences.insert_space_before_comma_in_allocation_expression);
- this.scribe.printTrailingComment();
- }
- this.scribe.alignFragment(argumentsAlignment, i);
- if (i > 0
- && this.preferences.insert_space_after_comma_in_allocation_expression) {
- this.scribe.space();
- }
- arguments[i].traverse(this, scope);
- }
- ok = true;
- } catch (AlignmentException e) {
- this.scribe.redoAlignment(e);
- }
- } while (!ok);
- this.scribe.exitAlignment(argumentsAlignment, true);
- this.scribe
- .printNextToken(
- TerminalTokens.TokenNameRPAREN,
- this.preferences.insert_space_before_closing_paren_in_method_invocation);
- } else {
- this.scribe
- .printNextToken(
- TerminalTokens.TokenNameRPAREN,
- this.preferences.insert_space_between_empty_parens_in_method_invocation);
- }
- }
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(allocationExpression, numberOfParens);
- }
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.AND_AND_Expression, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(
- AND_AND_Expression and_and_Expression,
- BlockScope scope) {
-
- return dumpBinaryExpression(and_and_Expression, TerminalTokens.TokenNameAND_AND, scope);
- }
-
- /**
- * @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 (argument.modifiers != NO_MODIFIERS) {
- this.scribe.printComment();
- this.scribe.printModifiers(this);
- this.scribe.space();
- }
-
- /*
- * Argument type
- */
- if (argument.type != null) {
- argument.type.traverse(this, scope);
- }
-
-// if (argument.isVarArgs()) {
-// this.scribe.printNextToken(TerminalTokens.TokenNameELLIPSIS, this.preferences.insert_space_before_ellipsis);
-// if (this.preferences.insert_space_after_ellipsis) {
-// this.scribe.space();
-// }
-// this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier, false);
-// } else {
- /*
- * Print the argument name
- */
- this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier, false);
-// }
-
-
- /*
- * Check for extra dimensions
- */
- int extraDimensions = getDimensions();
- if (extraDimensions != 0) {
- for (int i = 0; i < extraDimensions; i++) {
- this.scribe.printNextToken(TerminalTokens.TokenNameLBRACKET);
- this.scribe.printNextToken(TerminalTokens.TokenNameRBRACKET);
- }
- }
-
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.ArrayAllocationExpression, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(
- ArrayAllocationExpression arrayAllocationExpression,
- BlockScope scope) {
-
- final int numberOfParens = (arrayAllocationExpression.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(arrayAllocationExpression, numberOfParens);
- }
- this.scribe.printNextToken(TerminalTokens.TokenNamenew);
- this.scribe.space();
- arrayAllocationExpression.type.traverse(this, scope);
-
- final Expression[] dimensions = arrayAllocationExpression.dimensions;
- int dimensionsLength = dimensions.length;
- for (int i = 0; i < dimensionsLength; i++) {
- if (this.preferences.insert_space_before_opening_bracket_in_array_allocation_expression) {
- this.scribe.space();
- }
- this.scribe.printNextToken(TerminalTokens.TokenNameLBRACKET, false);
- if (dimensions[i] != null) {
- if (this.preferences.insert_space_after_opening_bracket_in_array_allocation_expression) {
- this.scribe.space();
- }
- dimensions[i].traverse(this, scope);
- this.scribe.printNextToken(TerminalTokens.TokenNameRBRACKET, this.preferences.insert_space_before_closing_bracket_in_array_allocation_expression);
- } else {
- this.scribe.printNextToken(TerminalTokens.TokenNameRBRACKET, this.preferences.insert_space_between_empty_brackets_in_array_allocation_expression);
- }
- }
- final ArrayInitializer initializer = arrayAllocationExpression.initializer;
- if (initializer != null) {
- initializer.traverse(this, scope);
- }
-
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(arrayAllocationExpression, numberOfParens);
- }
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.ArrayInitializer, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(ArrayInitializer arrayInitializer, BlockScope scope) { final int numberOfParens = (arrayInitializer.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(arrayInitializer, numberOfParens);
- }
-
- final Expression[] expressions = arrayInitializer.expressions;
- if (expressions != null) {
- String array_initializer_brace_position = this.preferences.brace_position_for_array_initializer;
- formatOpeningBracket(array_initializer_brace_position, false);
-
- int expressionsLength = expressions.length;
- final boolean insert_new_line_after_opening_brace = this.preferences.insert_new_line_after_opening_brace_in_array_initializer;
- if (expressionsLength > 1) {
- if (insert_new_line_after_opening_brace) {
- this.scribe.printNewLine();
- }
- Alignment arrayInitializerAlignment =this.scribe.createAlignment(
- "array_initializer",//$NON-NLS-1$
- this.preferences.alignment_for_expressions_in_array_initializer,
- Alignment.R_OUTERMOST,
- expressionsLength,
- this.scribe.scanner.currentPosition,
- this.preferences.continuation_indentation_for_array_initializer,
- true);
-
- if (insert_new_line_after_opening_brace) {
- arrayInitializerAlignment.fragmentIndentations[0] = arrayInitializerAlignment.breakIndentationLevel;
- }
-
- this.scribe.enterAlignment(arrayInitializerAlignment);
- boolean ok = false;
- do {
- try {
- this.scribe.alignFragment(arrayInitializerAlignment, 0);
- if (this.preferences.insert_space_after_opening_brace_in_array_initializer) {
- this.scribe.space();
- }
- expressions[0].traverse(this, scope);
- for (int i = 1; i < expressionsLength; i++) {
- this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_array_initializer);
- this.scribe.printTrailingComment();
- this.scribe.alignFragment(arrayInitializerAlignment, i);
- if (this.preferences.insert_space_after_comma_in_array_initializer) {
- this.scribe.space();
- }
- expressions[i].traverse(this, scope);
- if (i == expressionsLength - 1) {
- if (isNextToken(TerminalTokens.TokenNameCOMMA)) {
- this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_array_initializer);
- this.scribe.printTrailingComment();
- }
- }
- }
- ok = true;
- } catch (AlignmentException e) {
- this.scribe.redoAlignment(e);
- }
- } while (!ok);
- this.scribe.exitAlignment(arrayInitializerAlignment, true);
- } else {
- if (insert_new_line_after_opening_brace) {
- this.scribe.printNewLine();
- this.scribe.indent();
- }
- // we don't need to use an alignment
- if (this.preferences.insert_space_after_opening_brace_in_array_initializer) {
- this.scribe.space();
- } else {
- this.scribe.needSpace = false;
- }
- expressions[0].traverse(this, scope);
- if (isNextToken(TerminalTokens.TokenNameCOMMA)) {
- this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_array_initializer);
- this.scribe.printTrailingComment();
- }
- if (insert_new_line_after_opening_brace) {
- this.scribe.unIndent();
- }
- }
- if (this.preferences.insert_new_line_before_closing_brace_in_array_initializer) {
- this.scribe.printNewLine();
- } else if (this.preferences.insert_space_before_closing_brace_in_array_initializer) {
- this.scribe.space();
- }
- this.scribe.printNextToken(TerminalTokens.TokenNameRBRACKET, false);
- if (array_initializer_brace_position.equals(DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED)) {
- this.scribe.unIndent();
- }
- } else {
- boolean keepEmptyArrayInitializerOnTheSameLine = this.preferences.keep_empty_array_initializer_on_one_line;
-
- if (keepEmptyArrayInitializerOnTheSameLine) {
- this.scribe.printNextToken(TerminalTokens.TokenNameLBRACKET, false);
- this.scribe.printNextToken(TerminalTokens.TokenNameRBRACKET, this.preferences.insert_space_between_empty_braces_in_array_initializer);
- } else {
- String array_initializer_brace_position = this.preferences.brace_position_for_array_initializer;
- formatOpeningBracket(array_initializer_brace_position, false);
- this.scribe.printNextToken(TerminalTokens.TokenNameRBRACKET, this.preferences.insert_space_between_empty_braces_in_array_initializer);
- if (array_initializer_brace_position.equals(DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED)) {
- this.scribe.unIndent();
- }
- }
- }
-
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(arrayInitializer, numberOfParens);
- }
- return false;
- }
-
- public boolean visit(ObjectLiteral objectLiteral, BlockScope scope) {
- final int numberOfParens = (objectLiteral.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(objectLiteral, numberOfParens);
- }
-
- final ObjectLiteralField[] expressions = objectLiteral.fields;
- if (expressions != null) {
- String objlit_initializer_brace_position = this.preferences.brace_position_for_objlit_initializer;
- formatOpeningBrace(objlit_initializer_brace_position, false);
-
- int expressionsLength = expressions.length;
- final boolean insert_new_line_after_opening_brace = this.preferences.insert_new_line_after_opening_brace_in_objlit_initializer;
- if (expressionsLength > 1) {
- if (insert_new_line_after_opening_brace) {
- this.scribe.printNewLine();
- }
- Alignment objlitInitializerAlignment =this.scribe.createAlignment(
- "objlit_initializer",//$NON-NLS-1$
- this.preferences.alignment_for_expressions_in_array_initializer,
- Alignment.R_OUTERMOST,
- expressionsLength,
- this.scribe.scanner.currentPosition,
- this.preferences.continuation_indentation_for_objlit_initializer,
- true);
-
- if (insert_new_line_after_opening_brace) {
- objlitInitializerAlignment.fragmentIndentations[0] = objlitInitializerAlignment.breakIndentationLevel;
- }
-
- this.scribe.enterAlignment(objlitInitializerAlignment);
- boolean ok = false;
- do {
- try {
- this.scribe.alignFragment(objlitInitializerAlignment, 0);
- if (this.preferences.insert_space_after_opening_brace_in_array_initializer) {
- this.scribe.space();
- }
- expressions[0].traverse(this, scope);
- for (int i = 1; i < expressionsLength; i++) {
- this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_array_initializer);
- this.scribe.printTrailingComment();
- this.scribe.alignFragment(objlitInitializerAlignment, i);
- if (this.preferences.insert_space_after_comma_in_array_initializer) {
- this.scribe.space();
- }
-
- if (this.preferences.insert_new_line_after_comma_in_objlit_initializer) {
- this.scribe.printNewLine();
- }
-
-
- expressions[i].traverse(this, scope);
-
- if (i == expressionsLength - 1) {
- if (isNextToken(TerminalTokens.TokenNameCOMMA)) {
- this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_array_initializer);
- this.scribe.printTrailingComment();
- }
- }
- }
- ok = true;
- } catch (AlignmentException e) {
- this.scribe.redoAlignment(e);
- }
- } while (!ok);
- this.scribe.exitAlignment(objlitInitializerAlignment, true);
- } else {
- if (insert_new_line_after_opening_brace) {
- this.scribe.printNewLine();
- this.scribe.indent();
- }
- // we don't need to use an alignment
- if (this.preferences.insert_space_after_opening_brace_in_array_initializer) {
- this.scribe.space();
- } else {
- this.scribe.needSpace = false;
- }
- expressions[0].traverse(this, scope);
- if (isNextToken(TerminalTokens.TokenNameCOMMA)) {
- this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_array_initializer);
- this.scribe.printTrailingComment();
- }
- if (insert_new_line_after_opening_brace) {
- this.scribe.unIndent();
- }
- }
- if (this.preferences.insert_new_line_before_closing_brace_in_objlit_initializer) {
- this.scribe.printNewLine();
- } else if (this.preferences.insert_space_before_closing_brace_in_array_initializer) {
- this.scribe.space();
- }
- this.scribe.printNextToken(TerminalTokens.TokenNameRBRACE, false);
- if (objlit_initializer_brace_position.equals(DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED)) {
- this.scribe.unIndent();
- }
- } else {
- boolean keepEmptyObjLitInitializerOnTheSameLine = this.preferences.keep_empty_objlit_initializer_on_one_line;
- String objlit_initializer_brace_position = this.preferences.brace_position_for_objlit_initializer;
- if (keepEmptyObjLitInitializerOnTheSameLine) {
- this.scribe.printNextToken(TerminalTokens.TokenNameLBRACE, false);
- this.scribe.printNextToken(TerminalTokens.TokenNameRBRACE, this.preferences.insert_space_between_empty_braces_in_array_initializer);
- } else {
- formatOpeningBrace(objlit_initializer_brace_position, false);
- this.scribe.printNextToken(TerminalTokens.TokenNameRBRACE, false);
- if (objlit_initializer_brace_position.equals(DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED)) {
- this.scribe.unIndent();
- }
- }
- }
-
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(objectLiteral, numberOfParens);
- }
- return false;
-}
-
- public boolean visit(ObjectLiteralField literalField,BlockScope scope)
- {
- literalField.fieldName.traverse(this, scope);
- this.scribe.printNextToken(TerminalTokens.TokenNameCOLON, this.preferences.insert_space_before_colon_in_object_initializer);
- if(this.preferences.insert_space_after_colon_in_object_initializer) {
- this.scribe.space();
- }
- literalField.initializer.traverse(this, scope);
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.ArrayQualifiedTypeReference, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(
- ArrayQualifiedTypeReference arrayQualifiedTypeReference,
- BlockScope scope) {
-
- final int numberOfParens = (arrayQualifiedTypeReference.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(arrayQualifiedTypeReference, numberOfParens);
- }
- this.scribe.printArrayQualifiedReference(arrayQualifiedTypeReference.tokens.length, arrayQualifiedTypeReference.sourceEnd);
- int dimensions = getDimensions();
- if (dimensions != 0) {
- for (int i = 0; i < dimensions; i++) {
- this.scribe.printNextToken(TerminalTokens.TokenNameLBRACKET);
- this.scribe.printNextToken(TerminalTokens.TokenNameRBRACKET);
- }
- }
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(arrayQualifiedTypeReference, numberOfParens);
- }
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.ArrayQualifiedTypeReference, org.eclipse.wst.jsdt.internal.compiler.lookup.ClassScope)
- */
- public boolean visit(
- ArrayQualifiedTypeReference arrayQualifiedTypeReference,
- ClassScope scope) {
-
- final int numberOfParens = (arrayQualifiedTypeReference.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(arrayQualifiedTypeReference, numberOfParens);
- }
- this.scribe.printArrayQualifiedReference(arrayQualifiedTypeReference.tokens.length, arrayQualifiedTypeReference.sourceEnd);
- int dimensions = getDimensions();
- if (dimensions != 0) {
- for (int i = 0; i < dimensions; i++) {
- this.scribe.printNextToken(TerminalTokens.TokenNameLBRACKET);
- this.scribe.printNextToken(TerminalTokens.TokenNameRBRACKET);
- }
- }
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(arrayQualifiedTypeReference, numberOfParens);
- }
- return false;
- }
-
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.ArrayReference, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(ArrayReference arrayReference, BlockScope scope) {
-
- final int numberOfParens = (arrayReference.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(arrayReference, numberOfParens);
- }
- arrayReference.receiver.traverse(this, scope);
- this.scribe.printNextToken(TerminalTokens.TokenNameLBRACKET, this.preferences.insert_space_before_opening_bracket_in_array_reference);
- if (this.preferences.insert_space_after_opening_bracket_in_array_reference) {
- this.scribe.space();
- }
- arrayReference.position.traverse(this, scope);
- this.scribe.printNextToken(TerminalTokens.TokenNameRBRACKET, this.preferences.insert_space_before_closing_bracket_in_array_reference);
-
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(arrayReference, numberOfParens);
- }
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.ArrayTypeReference, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(
- ArrayTypeReference arrayTypeReference,
- BlockScope scope) {
-
- final int numberOfParens = (arrayTypeReference.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(arrayTypeReference, numberOfParens);
- }
- this.scribe.printNextToken(SINGLETYPEREFERENCE_EXPECTEDTOKENS);
-
- int dimensions = getDimensions();
- if (dimensions != 0) {
- if (this.preferences.insert_space_before_opening_bracket_in_array_type_reference) {
- this.scribe.space();
- }
- for (int i = 0; i < dimensions; i++) {
- this.scribe.printNextToken(TerminalTokens.TokenNameLBRACKET);
- if (this.preferences.insert_space_between_brackets_in_array_type_reference) {
- this.scribe.space();
- }
- this.scribe.printNextToken(TerminalTokens.TokenNameRBRACKET);
- }
- }
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(arrayTypeReference, numberOfParens);
- }
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.ArrayTypeReference, org.eclipse.wst.jsdt.internal.compiler.lookup.ClassScope)
- */
- public boolean visit(
- ArrayTypeReference arrayTypeReference,
- ClassScope scope) {
-
- final int numberOfParens = (arrayTypeReference.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(arrayTypeReference, numberOfParens);
- }
- this.scribe.printNextToken(SINGLETYPEREFERENCE_EXPECTEDTOKENS);
- int dimensions = getDimensions();
- if (dimensions != 0) {
- if (this.preferences.insert_space_before_opening_bracket_in_array_type_reference) {
- this.scribe.space();
- }
- for (int i = 0; i < dimensions; i++) {
- this.scribe.printNextToken(TerminalTokens.TokenNameLBRACKET);
- if (this.preferences.insert_space_between_brackets_in_array_type_reference) {
- this.scribe.space();
- }
- this.scribe.printNextToken(TerminalTokens.TokenNameRBRACKET);
- }
- }
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(arrayTypeReference, numberOfParens);
- }
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.AssertStatement, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
-// public boolean visit(AssertStatement assertStatement, BlockScope scope) {
-//
-// this.scribe.printNextToken(TerminalTokens.TokenNameassert);
-// this.scribe.space();
-// assertStatement.assertExpression.traverse(this, scope);
-//
-// if (assertStatement.exceptionArgument != null) {
-// this.scribe.printNextToken(TerminalTokens.TokenNameCOLON, this.preferences.insert_space_before_colon_in_assert);
-// if (this.preferences.insert_space_after_colon_in_assert) {
-// this.scribe.space();
-// }
-// assertStatement.exceptionArgument.traverse(this, scope);
-// }
-// this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
-// this.scribe.printTrailingComment();
-// return false;
-// }
-
- /**
- * @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) {
-
- final int numberOfParens = (assignment.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(assignment, numberOfParens);
- }
- assignment.lhs.traverse(this, scope);
- this.scribe.printNextToken(TerminalTokens.TokenNameEQUAL, this.preferences.insert_space_before_assignment_operator);
- if (this.preferences.insert_space_after_assignment_operator) {
- this.scribe.space();
- }
-
- Alignment assignmentAlignment = this.scribe.createAlignment("assignmentAlignment", this.preferences.alignment_for_assignment, Alignment.R_OUTERMOST, 1, this.scribe.scanner.currentPosition); //$NON-NLS-1$
- this.scribe.enterAlignment(assignmentAlignment);
- boolean ok = false;
- do {
- try {
- this.scribe.alignFragment(assignmentAlignment, 0);
- assignment.expression.traverse(this, scope);
- ok = true;
- } catch(AlignmentException e){
- this.scribe.redoAlignment(e);
- }
- } while (!ok);
- this.scribe.exitAlignment(assignmentAlignment, true);
-
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(assignment, numberOfParens);
- }
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.BinaryExpression, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(BinaryExpression binaryExpression, BlockScope scope) {
-
- switch((binaryExpression.bits & ASTNode.OperatorMASK) >> ASTNode.OperatorSHIFT) {
- case OperatorIds.AND :
- return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameAND, scope);
- case OperatorIds.DIVIDE :
- return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameDIVIDE, scope);
- case OperatorIds.GREATER :
- return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameGREATER, scope);
- case OperatorIds.GREATER_EQUAL :
- return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameGREATER_EQUAL, scope);
- case OperatorIds.LEFT_SHIFT :
- return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameLEFT_SHIFT, scope);
- case OperatorIds.LESS :
- return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameLESS, scope);
- case OperatorIds.LESS_EQUAL :
- return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameLESS_EQUAL, scope);
- case OperatorIds.MINUS :
- return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameMINUS, scope);
- case OperatorIds.MULTIPLY :
- return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameMULTIPLY, scope);
- case OperatorIds.OR :
- return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameOR, scope);
- case OperatorIds.PLUS :
- return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNamePLUS, scope);
- case OperatorIds.REMAINDER :
- return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameREMAINDER, scope);
- case OperatorIds.RIGHT_SHIFT :
- return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameRIGHT_SHIFT, scope);
- case OperatorIds.UNSIGNED_RIGHT_SHIFT :
- return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameUNSIGNED_RIGHT_SHIFT, scope);
- case OperatorIds.XOR :
- return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameXOR, scope);
- case OperatorIds.INSTANCEOF :
- return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameinstanceof, scope);
- case OperatorIds.IN :
- return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNamein, scope);
- default:
- throw new IllegalStateException();
- }
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.Block, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(Block block, BlockScope scope) {
- formatBlock(block, scope, this.preferences.brace_position_for_block, this.preferences.insert_space_before_opening_brace_in_block);
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.BreakStatement, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(BreakStatement breakStatement, BlockScope scope) {
-
- this.scribe.printNextToken(TerminalTokens.TokenNamebreak);
- if (breakStatement.label != null) {
- this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier, true);
- }
- this.scribe.printOptionalNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.CaseStatement, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(CaseStatement caseStatement, BlockScope scope) {
- if (caseStatement.constantExpression == null) {
- this.scribe.printNextToken(TerminalTokens.TokenNamedefault);
- this.scribe.printNextToken(TerminalTokens.TokenNameCOLON, this.preferences.insert_space_before_colon_in_default);
- } else {
- this.scribe.printNextToken(TerminalTokens.TokenNamecase);
- this.scribe.space();
- caseStatement.constantExpression.traverse(this, scope);
- this.scribe.printNextToken(TerminalTokens.TokenNameCOLON, this.preferences.insert_space_before_colon_in_case);
- }
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.ClassLiteralAccess, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(ClassLiteralAccess classLiteral, BlockScope scope) {
-
- final int numberOfParens = (classLiteral.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(classLiteral, numberOfParens);
- }
- classLiteral.type.traverse(this, scope);
- this.scribe.printNextToken(TerminalTokens.TokenNameDOT);
- this.scribe.printNextToken(TerminalTokens.TokenNameclass);
-
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(classLiteral, numberOfParens);
- }
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.Clinit, org.eclipse.wst.jsdt.internal.compiler.lookup.ClassScope)
- */
- public boolean visit(Clinit clinit, ClassScope scope) {
-
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration, org.eclipse.wst.jsdt.internal.compiler.lookup.CompilationUnitScope)
- */
- public boolean visit(
- CompilationUnitDeclaration compilationUnitDeclaration,
- CompilationUnitScope scope) {
-
- // fake new line to handle empty lines before package declaration or import declarations
- this.scribe.lastNumberOfNewLines = 1;
- /*
- * Package declaration
- */
- final boolean hasPackage = compilationUnitDeclaration.currentPackage != null;
- if (hasPackage) {
- if (hasComments()) {
- this.scribe.printComment();
- }
- int blankLinesBeforePackage = this.preferences.blank_lines_before_package;
- if (blankLinesBeforePackage > 0) {
- this.scribe.printEmptyLines(blankLinesBeforePackage);
- }
-
- this.scribe.space();
- // dump the package keyword
- this.scribe.printNextToken(TerminalTokens.TokenNamepackage);
- this.scribe.space();
- this.scribe.printQualifiedReference(compilationUnitDeclaration.currentPackage.sourceEnd);
- this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- int blankLinesAfterPackage = this.preferences.blank_lines_after_package;
- if (blankLinesAfterPackage > 0) {
- this.scribe.printEmptyLines(blankLinesAfterPackage);
- } else {
- this.scribe.printNewLine();
- }
- } else {
- this.scribe.printComment();
- }
-
- /*
- * Import statements
- */
- final ImportReference[] imports = compilationUnitDeclaration.imports;
- if (imports != null) {
- if (hasPackage) {
- int blankLinesBeforeImports = this.preferences.blank_lines_before_imports;
- if (blankLinesBeforeImports > 0) {
- this.scribe.printEmptyLines(blankLinesBeforeImports);
- }
- }
- int importLength = imports.length;
- int savedNumberOfLineToPreserve = this.preferences.number_of_empty_lines_to_preserve;
- if (importLength != 1) {
- format(imports[0], false);
- for (int i = 1; i < importLength - 1; i++) {
- format(imports[i], false);
- }
- format(imports[importLength - 1], true);
- this.preferences.number_of_empty_lines_to_preserve = savedNumberOfLineToPreserve;
- } else {
- format(imports[0], true);
- }
- this.preferences.number_of_empty_lines_to_preserve = savedNumberOfLineToPreserve;
-
- int blankLinesAfterImports = this.preferences.blank_lines_after_imports;
- if (blankLinesAfterImports > 0) {
- this.scribe.printEmptyLines(blankLinesAfterImports);
- }
- }
-
- formatEmptyTypeDeclaration(true);
-
- int blankLineBetweenTypeDeclarations = this.preferences.blank_lines_between_type_declarations;
-// /*
-// * Type declarations
-// */
-// final TypeDeclaration[] types = compilationUnitDeclaration.types;
-// if (types != null) {
-// int typesLength = types.length;
-// for (int i = 0; i < typesLength - 1; i++) {
-// types[i].traverse(this, scope);
-// formatEmptyTypeDeclaration(false);
-// if (blankLineBetweenTypeDeclarations != 0) {
-// this.scribe.printEmptyLines(blankLineBetweenTypeDeclarations);
-// } else {
-// this.scribe.printNewLine();
-// }
-// }
-// types[typesLength - 1].traverse(this, scope);
-// }
-//
- final ProgramElement[] statements = compilationUnitDeclaration.statements;
- if (statements != null && statements.length>0) {
- int statementsLength = statements.length;
- for (int i = 0; i < statementsLength - 1; i++) {
- statements[i].traverse(this, scope);
- this.scribe.printOptionalNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- if (blankLineBetweenTypeDeclarations != 0) {
- this.scribe.printEmptyLines(blankLineBetweenTypeDeclarations);
- } else {
- this.scribe.printNewLine();
- }
- }
- statements[statementsLength - 1].traverse(this, scope);
- }
-
-
- this.scribe.printEndOfCompilationUnit();
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.CompoundAssignment, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(
- CompoundAssignment compoundAssignment,
- BlockScope scope) {
-
- final int numberOfParens = (compoundAssignment.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(compoundAssignment, numberOfParens);
- }
- compoundAssignment.lhs.traverse(this, scope);
-
- /*
- * Print the operator
- */
- int operator;
- switch(compoundAssignment.operator) {
- case OperatorIds.PLUS :
- operator = TerminalTokens.TokenNamePLUS_EQUAL;
- break;
- case OperatorIds.MINUS :
- operator = TerminalTokens.TokenNameMINUS_EQUAL;
- break;
- case OperatorIds.MULTIPLY :
- operator = TerminalTokens.TokenNameMULTIPLY_EQUAL;
- break;
- case OperatorIds.DIVIDE :
- operator = TerminalTokens.TokenNameDIVIDE_EQUAL;
- break;
- case OperatorIds.AND :
- operator = TerminalTokens.TokenNameAND_EQUAL;
- break;
- case OperatorIds.OR :
- operator = TerminalTokens.TokenNameOR_EQUAL;
- break;
- case OperatorIds.XOR :
- operator = TerminalTokens.TokenNameXOR_EQUAL;
- break;
- case OperatorIds.REMAINDER :
- operator = TerminalTokens.TokenNameREMAINDER_EQUAL;
- break;
- case OperatorIds.LEFT_SHIFT :
- operator = TerminalTokens.TokenNameLEFT_SHIFT_EQUAL;
- break;
- case OperatorIds.RIGHT_SHIFT :
- operator = TerminalTokens.TokenNameRIGHT_SHIFT_EQUAL;
- break;
- default: // OperatorIds.UNSIGNED_RIGHT_SHIFT :
- operator = TerminalTokens.TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL;
- }
-
- this.scribe.printNextToken(operator, this.preferences.insert_space_before_assignment_operator);
- if (this.preferences.insert_space_after_assignment_operator) {
- this.scribe.space();
- }
- Alignment assignmentAlignment = this.scribe.createAlignment("compoundAssignmentAlignment", this.preferences.alignment_for_assignment, Alignment.R_OUTERMOST, 1, this.scribe.scanner.currentPosition); //$NON-NLS-1$
- this.scribe.enterAlignment(assignmentAlignment);
- boolean ok = false;
- do {
- try {
- this.scribe.alignFragment(assignmentAlignment, 0);
- compoundAssignment.expression.traverse(this, scope);
- ok = true;
- } catch(AlignmentException e){
- this.scribe.redoAlignment(e);
- }
- } while (!ok);
- this.scribe.exitAlignment(assignmentAlignment, true);
-
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(compoundAssignment, numberOfParens);
- }
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.ConditionalExpression, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(
- ConditionalExpression conditionalExpression,
- BlockScope scope) {
-
- final int numberOfParens = (conditionalExpression.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(conditionalExpression, numberOfParens);
- }
- conditionalExpression.condition.traverse(this, scope);
-
- Alignment conditionalExpressionAlignment =this.scribe.createAlignment(
- "conditionalExpression", //$NON-NLS-1$
- this.preferences.alignment_for_conditional_expression,
- 2,
- this.scribe.scanner.currentPosition);
-
- this.scribe.enterAlignment(conditionalExpressionAlignment);
- boolean ok = false;
- do {
- try {
- this.scribe.alignFragment(conditionalExpressionAlignment, 0);
- this.scribe.printNextToken(TerminalTokens.TokenNameQUESTION, this.preferences.insert_space_before_question_in_conditional);
-
- if (this.preferences.insert_space_after_question_in_conditional) {
- this.scribe.space();
- }
- conditionalExpression.valueIfTrue.traverse(this, scope);
- this.scribe.printTrailingComment();
- this.scribe.alignFragment(conditionalExpressionAlignment, 1);
- this.scribe.printNextToken(TerminalTokens.TokenNameCOLON, this.preferences.insert_space_before_colon_in_conditional);
-
- if (this.preferences.insert_space_after_colon_in_conditional) {
- this.scribe.space();
- }
- conditionalExpression.valueIfFalse.traverse(this, scope);
-
- ok = true;
- } catch (AlignmentException e) {
- this.scribe.redoAlignment(e);
- }
- } while (!ok);
- this.scribe.exitAlignment(conditionalExpressionAlignment, true);
-
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(conditionalExpression, numberOfParens);
- }
- return false;
- }
-
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.ConstructorDeclaration, org.eclipse.wst.jsdt.internal.compiler.lookup.ClassScope)
- */
- public boolean visit(
- ConstructorDeclaration constructorDeclaration,
- ClassScope scope) {
-
- if (constructorDeclaration.ignoreFurtherInvestigation) {
- this.scribe.printComment();
- if (this.scribe.indentationLevel != 0) {
- this.scribe.printIndentationIfNecessary();
- }
- this.scribe.scanner.resetTo(constructorDeclaration.declarationSourceEnd + 1, this.scribe.scannerEndPosition - 1);
- this.scribe.printTrailingComment();
- switch(this.scribe.scanner.source[this.scribe.scanner.currentPosition]) {
- case '\n' :
- this.scribe.scanner.currentPosition++;
- this.scribe.lastNumberOfNewLines = 1;
- break;
- case '\r' :
- this.scribe.scanner.currentPosition++;
- if (this.scribe.scanner.source[this.scribe.scanner.currentPosition] == '\n') {
- this.scribe.scanner.currentPosition++;
- }
- this.scribe.lastNumberOfNewLines = 1;
- }
- return false;
- }
- /*
- * Print comments to get proper line number
- */
- this.scribe.printComment();
- int line = this.scribe.line;
- this.scribe.printModifiers(this);
- if (this.scribe.line > line) {
- // annotations introduced new line, but this is not a line wrapping
- // see 158267
- line = this.scribe.line;
- }
- this.scribe.space();
-
- /*
- * Print the method name
- */
- this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier, true);
-
- formatMethodArguments(
- constructorDeclaration,
- this.preferences.insert_space_before_opening_paren_in_constructor_declaration,
- this.preferences.insert_space_between_empty_parens_in_constructor_declaration,
- this.preferences.insert_space_before_closing_paren_in_constructor_declaration,
- this.preferences.insert_space_after_opening_paren_in_constructor_declaration,
- this.preferences.insert_space_before_comma_in_constructor_declaration_parameters,
- this.preferences.insert_space_after_comma_in_constructor_declaration_parameters,
- this.preferences.alignment_for_parameters_in_constructor_declaration);
-
- if (!constructorDeclaration.isAbstract()) {
- /*
- * Method body
- */
- String constructor_declaration_brace = this.preferences.brace_position_for_constructor_declaration;
- formatLeftCurlyBrace(line, constructor_declaration_brace);
- formatOpeningBrace(constructor_declaration_brace, this.preferences.insert_space_before_opening_brace_in_constructor_declaration);
- final int numberOfBlankLinesAtBeginningOfMethodBody = this.preferences.blank_lines_at_beginning_of_method_body;
- if (numberOfBlankLinesAtBeginningOfMethodBody > 0) {
- this.scribe.printEmptyLines(numberOfBlankLinesAtBeginningOfMethodBody);
- }
- if (constructorDeclaration.constructorCall != null && !constructorDeclaration.constructorCall.isImplicitSuper()) {
- this.scribe.printNewLine();
- if (this.preferences.indent_statements_compare_to_body) {
- this.scribe.indent();
- }
- constructorDeclaration.constructorCall.traverse(this, constructorDeclaration.scope);
- if (this.preferences.indent_statements_compare_to_body) {
- this.scribe.unIndent();
- }
- }
- final Statement[] statements = constructorDeclaration.statements;
- if (statements != null) {
- this.scribe.printNewLine();
- if (this.preferences.indent_statements_compare_to_body) {
- this.scribe.indent();
- }
- formatStatements(constructorDeclaration.scope, statements, true);
- this.scribe.printComment();
- if (this.preferences.indent_statements_compare_to_body) {
- this.scribe.unIndent();
- }
- } else if (this.preferences.insert_new_line_in_empty_method_body) {
- this.scribe.printNewLine();
- if (this.preferences.indent_statements_compare_to_body) {
- this.scribe.indent();
- }
- this.scribe.printComment();
- if (this.preferences.indent_statements_compare_to_body) {
- this.scribe.unIndent();
- }
- }
- this.scribe.printNextToken(TerminalTokens.TokenNameRBRACE);
- this.scribe.printTrailingComment();
- if (constructor_declaration_brace.equals(DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED)) {
- this.scribe.unIndent();
- }
- } else {
- // no method body
- this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- }
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.ContinueStatement, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(ContinueStatement continueStatement, BlockScope scope) {
-
- this.scribe.printNextToken(TerminalTokens.TokenNamecontinue);
- if (continueStatement.label != null) {
- this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier, true);
- }
- this.scribe.printOptionalNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- return false;
- }
-
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.DoStatement, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(DoStatement doStatement, BlockScope scope) {
-
- this.scribe.printNextToken(TerminalTokens.TokenNamedo);
- final int line = this.scribe.line;
-
- final Statement action = doStatement.action;
- if (action != null) {
- if (action instanceof Block) {
- formatLeftCurlyBrace(line, this.preferences.brace_position_for_block);
- action.traverse(this, scope);
- } else if (action instanceof EmptyStatement) {
- /*
- * This is an empty statement
- */
- formatNecessaryEmptyStatement();
- } else {
- this.scribe.printNewLine();
- this.scribe.indent();
- action.traverse(this, scope);
- if (action instanceof Expression || action instanceof LocalDeclaration) {
- this.scribe.printOptionalNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- }
- this.scribe.printNewLine();
- this.scribe.unIndent();
- }
- } else {
- /*
- * This is an empty statement
- */
- formatNecessaryEmptyStatement();
- }
-
- if (this.preferences.insert_new_line_before_while_in_do_statement) {
- this.scribe.printNewLine();
- }
- this.scribe.printNextToken(TerminalTokens.TokenNamewhile, this.preferences.insert_space_after_closing_brace_in_block);
- this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, this.preferences.insert_space_before_opening_paren_in_while);
-
- if (this.preferences.insert_space_after_opening_paren_in_while) {
- this.scribe.space();
- }
-
- doStatement.condition.traverse(this, scope);
-
- this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_before_closing_paren_in_while);
- this.scribe.printOptionalNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.DoubleLiteral, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(DoubleLiteral doubleLiteral, BlockScope scope) {
-
- final int numberOfParens = (doubleLiteral.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(doubleLiteral, numberOfParens);
- }
- Constant constant = doubleLiteral.constant;
- if (constant != null && constant.doubleValue() < 0) {
- this.scribe.printNextToken(TerminalTokens.TokenNameMINUS);
- }
- this.scribe.printNextToken(TerminalTokens.TokenNameDoubleLiteral);
-
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(doubleLiteral, numberOfParens);
- }
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.EmptyStatement, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(EmptyStatement statement, BlockScope scope) {
- if (this.preferences.put_empty_statement_on_new_line) {
- this.scribe.printNewLine();
- }
- this.scribe.printOptionalNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- return false;
- }
- // field is an enum constant
- public boolean visit(FieldDeclaration enumConstant, MethodScope scope) {
- /*
- * Print comments to get proper line number
- */
- this.scribe.printComment();
- final int line = this.scribe.line;
-
- this.scribe.printModifiers(this);
- this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier, false);
- formatEnumConstantArguments(
- enumConstant,
- this.preferences.insert_space_before_opening_paren_in_enum_constant,
- this.preferences.insert_space_between_empty_parens_in_enum_constant,
- this.preferences.insert_space_before_closing_paren_in_enum_constant,
- this.preferences.insert_space_after_opening_paren_in_enum_constant,
- this.preferences.insert_space_before_comma_in_enum_constant_arguments,
- this.preferences.insert_space_after_comma_in_enum_constant_arguments,
- this.preferences.alignment_for_arguments_in_enum_constant);
-
- Expression initialization = enumConstant.initialization;
- if (initialization instanceof QualifiedAllocationExpression) {
- TypeDeclaration typeDeclaration = ((QualifiedAllocationExpression) initialization).anonymousType;
- int fieldsCount = typeDeclaration.fields == null ? 0 : typeDeclaration.fields.length;
- int methodsCount = typeDeclaration.methods == null ? 0 : typeDeclaration.methods.length;
- int membersCount = typeDeclaration.memberTypes == null ? 0 : typeDeclaration.memberTypes.length;
-
- /*
- * Type body
- */
- String enum_constant_brace = this.preferences.brace_position_for_enum_constant;
-
- formatLeftCurlyBrace(line, enum_constant_brace);
- formatTypeOpeningBraceForEnumConstant(enum_constant_brace, this.preferences.insert_space_before_opening_brace_in_enum_constant, typeDeclaration);
-
- if (this.preferences.indent_body_declarations_compare_to_enum_constant_header) {
- this.scribe.indent();
- }
-
- if (fieldsCount != 0 || methodsCount != 0 || membersCount != 0) {
- formatTypeMembers(typeDeclaration);
- }
-
- if (this.preferences.indent_body_declarations_compare_to_enum_constant_header) {
- this.scribe.unIndent();
- }
-
- if (this.preferences.insert_new_line_in_empty_enum_constant) {
- this.scribe.printNewLine();
- }
- this.scribe.printNextToken(TerminalTokens.TokenNameRBRACE);
- this.scribe.printTrailingComment();
- if (enum_constant_brace.equals(DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED)) {
- this.scribe.unIndent();
- }
- if (hasComments()) {
- this.scribe.printNewLine();
- }
- }
- return false;
- }
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.EqualExpression, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(EqualExpression equalExpression, BlockScope scope) {
-
- int operator = (equalExpression.bits & ASTNode.OperatorMASK) >> ASTNode.OperatorSHIFT;
- if (operator == OperatorIds.EQUAL_EQUAL) {
- return dumpEqualityExpression(equalExpression, TerminalTokens.TokenNameEQUAL_EQUAL, scope);
- } if (operator == OperatorIds.NOT_EQUAL) {
- return dumpEqualityExpression(equalExpression, TerminalTokens.TokenNameNOT_EQUAL, scope);
- } if (operator == OperatorIds.EQUAL_EQUAL_EQUAL) {
- return dumpEqualityExpression(equalExpression, TerminalTokens.TokenNameEQUAL_EQUAL_EQUAL, scope);
-
- }else {
- return dumpEqualityExpression(equalExpression, TerminalTokens.TokenNameNOT_EQUAL_EQUAL, scope);
- }
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.ExplicitConstructorCall, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(
- ExplicitConstructorCall explicitConstructor,
- BlockScope scope) {
-
- if (explicitConstructor.isImplicitSuper()) {
- return false;
- }
- final Expression qualification = explicitConstructor.qualification;
- if (qualification != null) {
- qualification.traverse(this, scope);
- this.scribe.printNextToken(TerminalTokens.TokenNameDOT);
- }
-
- TypeReference[] typeArguments = explicitConstructor.typeArguments;
- if (typeArguments != null) {
- this.scribe.printNextToken(TerminalTokens.TokenNameLESS, this.preferences.insert_space_before_opening_angle_bracket_in_type_arguments);
- if (this.preferences.insert_space_after_opening_angle_bracket_in_type_arguments) {
- this.scribe.space();
- }
- int length = typeArguments.length;
- for (int i = 0; i < length - 1; i++) {
- typeArguments[i].traverse(this, scope);
- this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_type_arguments);
- if (this.preferences.insert_space_after_comma_in_type_arguments) {
- this.scribe.space();
- }
- }
- typeArguments[length - 1].traverse(this, scope);
- if (isClosingGenericToken()) {
- this.scribe.printNextToken(CLOSING_GENERICS_EXPECTEDTOKENS, this.preferences.insert_space_before_closing_angle_bracket_in_type_arguments);
- }
- if (this.preferences.insert_space_after_closing_angle_bracket_in_type_arguments) {
- this.scribe.space();
- }
- }
-
- if (explicitConstructor.isSuperAccess()) {
- this.scribe.printNextToken(TerminalTokens.TokenNamesuper);
- } else {
- this.scribe.printNextToken(TerminalTokens.TokenNamethis);
- }
- this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, this.preferences.insert_space_before_opening_paren_in_method_invocation);
-
- final Expression[] arguments = explicitConstructor.arguments;
- if (arguments != null) {
- if (this.preferences.insert_space_after_opening_paren_in_method_invocation) {
- this.scribe.space();
- }
- int argumentLength = arguments.length;
- Alignment argumentsAlignment =this.scribe.createAlignment(
- "explicit_constructor_call",//$NON-NLS-1$
- this.preferences.alignment_for_arguments_in_explicit_constructor_call,
- argumentLength,
- this.scribe.scanner.currentPosition);
- this.scribe.enterAlignment(argumentsAlignment);
- boolean ok = false;
- do {
- try {
- for (int i = 0; i < argumentLength; i++) {
- if (i > 0) {
- this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_explicit_constructor_call_arguments);
- this.scribe.printTrailingComment();
- }
- this.scribe.alignFragment(argumentsAlignment, i);
- if (i > 0 && this.preferences.insert_space_after_comma_in_explicit_constructor_call_arguments) {
- this.scribe.space();
- }
- arguments[i].traverse(this, scope);
- }
- ok = true;
- } catch (AlignmentException e) {
- this.scribe.redoAlignment(e);
- }
- } while (!ok);
- this.scribe.exitAlignment(argumentsAlignment, true);
- this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_before_closing_paren_in_method_invocation);
- } else {
- this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_between_empty_parens_in_method_invocation);
- }
- this.scribe.printOptionalNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- return false;
- }
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.FalseLiteral, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(FalseLiteral falseLiteral, BlockScope scope) {
-
- final int numberOfParens = (falseLiteral.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(falseLiteral, numberOfParens);
- }
- this.scribe.printNextToken(TerminalTokens.TokenNamefalse);
-
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(falseLiteral, numberOfParens);
- }
- return false;
- }
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.FieldReference, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(FieldReference fieldReference, BlockScope scope) {
-
- final int numberOfParens = (fieldReference.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(fieldReference, numberOfParens);
- }
- fieldReference.receiver.traverse(this, scope);
- this.scribe.printNextToken(TerminalTokens.TokenNameDOT);
- this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier);
-
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(fieldReference, numberOfParens);
- }
- return false;
- }
-
- public boolean visit(ForeachStatement forStatement, BlockScope scope) {
- this.scribe.printNextToken(TerminalTokens.TokenNamefor);
- final int line = this.scribe.line;
- this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, this.preferences.insert_space_before_opening_paren_in_for);
-
- if (this.preferences.insert_space_after_opening_paren_in_for) {
- this.scribe.space();
- }
- formatLocalDeclaration(forStatement.elementVariable, scope, false, false);
-
- this.scribe.printNextToken(TerminalTokens.TokenNameCOLON, this.preferences.insert_space_before_colon_in_for);
- if (this.preferences.insert_space_after_colon_in_for) {
- this.scribe.space();
- }
- forStatement.collection.traverse(this, scope);
-
- this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_before_closing_paren_in_for);
-
- final Statement action = forStatement.action;
- if (action != null) {
- if (action instanceof Block) {
- formatLeftCurlyBrace(line, this.preferences.brace_position_for_block);
- action.traverse(this, scope);
- } else if (action instanceof EmptyStatement) {
- /*
- * This is an empty statement
- */
- formatNecessaryEmptyStatement();
- } else {
- this.scribe.indent();
- this.scribe.printNewLine();
- action.traverse(this, scope);
- this.scribe.unIndent();
- }
- if (action instanceof Expression || action instanceof LocalDeclaration) {
- this.scribe.printOptionalNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- }
- } else {
- /*
- * This is an empty statement
- */
- formatNecessaryEmptyStatement();
- }
- return false;
- }
-
- public boolean visit(ForInStatement forStatement, BlockScope scope) {
- this.scribe.printNextToken(TerminalTokens.TokenNamefor);
- final int line = this.scribe.line;
- this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, this.preferences.insert_space_before_opening_paren_in_for);
-
- if (this.preferences.insert_space_after_opening_paren_in_for) {
- this.scribe.space();
- }
- forStatement.iterationVariable.traverse(this, scope);
-
- this.scribe.printNextToken(TerminalTokens.TokenNamein, this.preferences.insert_space_before_colon_in_for);
- if (this.preferences.insert_space_after_colon_in_for) {
- this.scribe.space();
- }
- forStatement.collection.traverse(this, scope);
-
- this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_before_closing_paren_in_for);
-
- final Statement action = forStatement.action;
- if (action != null) {
- if (action instanceof Block) {
- formatLeftCurlyBrace(line, this.preferences.brace_position_for_block);
- action.traverse(this, scope);
- } else if (action instanceof EmptyStatement) {
- /*
- * This is an empty statement
- */
- formatNecessaryEmptyStatement();
- } else {
- this.scribe.indent();
- this.scribe.printNewLine();
- action.traverse(this, scope);
- this.scribe.unIndent();
- }
- if (action instanceof Expression || action instanceof LocalDeclaration) {
- this.scribe.printOptionalNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- }
- } else {
- /*
- * This is an empty statement
- */
- formatNecessaryEmptyStatement();
- }
- return false;
- }
-
-
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.ForStatement, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(ForStatement forStatement, BlockScope scope) {
-
- this.scribe.printNextToken(TerminalTokens.TokenNamefor);
- final int line = this.scribe.line;
- this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, this.preferences.insert_space_before_opening_paren_in_for);
-
- if (this.preferences.insert_space_after_opening_paren_in_for) {
- this.scribe.space();
- }
- final Statement[] initializations = forStatement.initializations;
- if (initializations != null) {
- int length = initializations.length;
- for (int i = 0; i < length; i++) {
- if (initializations[i] instanceof LocalDeclaration) {
- formatLocalDeclaration((LocalDeclaration) initializations[i], scope, this.preferences.insert_space_before_comma_in_for_inits, this.preferences.insert_space_after_comma_in_for_inits);
- } else {
- initializations[i].traverse(this, scope);
- if (i >= 0 && (i < length - 1)) {
- this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_for_inits);
- if (this.preferences.insert_space_after_comma_in_for_inits) {
- this.scribe.space();
- }
- this.scribe.printTrailingComment();
- }
- }
- }
- }
- this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon_in_for);
- final Expression condition = forStatement.condition;
- if (condition != null) {
- if (this.preferences.insert_space_after_semicolon_in_for) {
- this.scribe.space();
- }
- condition.traverse(this, scope);
- }
- this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon_in_for);
- final Statement[] increments = forStatement.increments;
- if (increments != null) {
- if (this.preferences.insert_space_after_semicolon_in_for) {
- this.scribe.space();
- }
- for (int i = 0, length = increments.length; i < length; i++) {
- increments[i].traverse(this, scope);
- if (i != length - 1) {
- this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_for_increments);
- if (this.preferences.insert_space_after_comma_in_for_increments) {
- this.scribe.space();
- }
- this.scribe.printTrailingComment();
- }
- }
- }
- this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_before_closing_paren_in_for);
-
- final Statement action = forStatement.action;
- if (action != null) {
- if (action instanceof Block) {
- formatLeftCurlyBrace(line, this.preferences.brace_position_for_block);
- action.traverse(this, scope);
- } else if (action instanceof EmptyStatement) {
- /*
- * This is an empty statement
- */
- formatNecessaryEmptyStatement();
- } else {
- this.scribe.indent();
- this.scribe.printNewLine();
- action.traverse(this, scope);
- this.scribe.unIndent();
- }
- if (action instanceof Expression || action instanceof LocalDeclaration) {
- this.scribe.printOptionalNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- }
- } else {
- /*
- * This is an empty statement
- */
- formatNecessaryEmptyStatement();
- }
- return false;
- }
-
- public boolean visit(FunctionExpression functionExpression, BlockScope scope) {
-
- final int numberOfParens = (functionExpression.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(functionExpression, numberOfParens);
- }
- visit(functionExpression.methodDeclaration,scope);
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(functionExpression, numberOfParens);
- }
- return false;
- }
-
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.IfStatement, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(IfStatement ifStatement, BlockScope scope) {
-
- this.scribe.printNextToken(TerminalTokens.TokenNameif);
- final int line = this.scribe.line;
- this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, this.preferences.insert_space_before_opening_paren_in_if);
- if (this.preferences.insert_space_after_opening_paren_in_if) {
- this.scribe.space();
- }
- ifStatement.condition.traverse(this, scope);
- this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_before_closing_paren_in_if);
-
- final Statement thenStatement = ifStatement.thenStatement;
- final Statement elseStatement = ifStatement.elseStatement;
-
- boolean thenStatementIsBlock = false;
- if (thenStatement != null) {
- if (thenStatement instanceof Block) {
- thenStatementIsBlock = true;
- if (isGuardClause((Block)thenStatement) && elseStatement == null && this.preferences.keep_guardian_clause_on_one_line) {
- /*
- * Need a specific formatting for guard clauses
- * guard clauses are block with a single return or throw
- * statement
- */
- formatGuardClauseBlock((Block) thenStatement, scope);
- } else {
- formatLeftCurlyBrace(line, this.preferences.brace_position_for_block);
- thenStatement.traverse(this, scope);
- if (elseStatement != null && (this.preferences.insert_new_line_before_else_in_if_statement)) {
- this.scribe.printNewLine();
- }
- }
- } else if (elseStatement == null && this.preferences.keep_simple_if_on_one_line) {
- Alignment compactIfAlignment = this.scribe.createAlignment(
- "compactIf", //$NON-NLS-1$
- this.preferences.alignment_for_compact_if,
- Alignment.R_OUTERMOST,
- 1,
- this.scribe.scanner.currentPosition,
- 1,
- false);
- this.scribe.enterAlignment(compactIfAlignment);
- boolean ok = false;
- do {
- try {
- this.scribe.alignFragment(compactIfAlignment, 0);
- this.scribe.space();
- thenStatement.traverse(this, scope);
- if (thenStatement instanceof Expression || thenStatement instanceof LocalDeclaration) {
- this.scribe.printOptionalNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- }
- ok = true;
- } catch (AlignmentException e) {
- this.scribe.redoAlignment(e);
- }
- } while (!ok);
- this.scribe.exitAlignment(compactIfAlignment, true);
- } else if (this.preferences.keep_then_statement_on_same_line) {
- this.scribe.space();
- thenStatement.traverse(this, scope);
- if (thenStatement instanceof Expression || thenStatement instanceof LocalDeclaration) {
- this.scribe.printOptionalNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- }
- if (elseStatement != null) {
- this.scribe.printNewLine();
- }
- } else {
- this.scribe.printTrailingComment();
- this.scribe.printNewLine();
- this.scribe.indent();
- thenStatement.traverse(this, scope);
- if (thenStatement instanceof Expression || thenStatement instanceof LocalDeclaration) {
- this.scribe.printOptionalNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- }
- if (elseStatement != null) {
- this.scribe.printNewLine();
- }
- this.scribe.unIndent();
- }
- }
-
- if (elseStatement != null) {
- if (thenStatementIsBlock) {
- this.scribe.printNextToken(TerminalTokens.TokenNameelse, this.preferences.insert_space_after_closing_brace_in_block);
- } else {
- this.scribe.printNextToken(TerminalTokens.TokenNameelse, true);
- }
- if (elseStatement instanceof Block) {
- elseStatement.traverse(this, scope);
- } else if (elseStatement instanceof IfStatement) {
- if (!this.preferences.compact_else_if) {
- this.scribe.printNewLine();
- this.scribe.indent();
- }
- this.scribe.space();
- elseStatement.traverse(this, scope);
- if (!this.preferences.compact_else_if) {
- this.scribe.unIndent();
- }
- } else if (this.preferences.keep_else_statement_on_same_line) {
- this.scribe.space();
- elseStatement.traverse(this, scope);
- if (elseStatement instanceof Expression || elseStatement instanceof LocalDeclaration) {
- this.scribe.printOptionalNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- }
- } else {
- this.scribe.printNewLine();
- this.scribe.indent();
- elseStatement.traverse(this, scope);
- if (elseStatement instanceof Expression || elseStatement instanceof LocalDeclaration) {
- this.scribe.printOptionalNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- }
- this.scribe.unIndent();
- }
- }
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.Initializer, org.eclipse.wst.jsdt.internal.compiler.lookup.MethodScope)
- */
- public boolean visit(Initializer initializer, MethodScope scope) {
-
- if (initializer.isStatic()) {
- this.scribe.printNextToken(TerminalTokens.TokenNamestatic);
- }
- initializer.block.traverse(this, scope);
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.InstanceOfExpression, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(
- InstanceOfExpression instanceOfExpression,
- BlockScope scope) {
-
- final int numberOfParens = (instanceOfExpression.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(instanceOfExpression, numberOfParens);
- }
- instanceOfExpression.expression.traverse(this, scope);
- this.scribe.printNextToken(TerminalTokens.TokenNameinstanceof, true);
- this.scribe.space();
- instanceOfExpression.type.traverse(this, scope);
-
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(instanceOfExpression, numberOfParens);
- }
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.IntLiteral, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(IntLiteral intLiteral, BlockScope scope) {
-
- final int numberOfParens = (intLiteral.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(intLiteral, numberOfParens);
- }
- Constant constant = intLiteral.constant;
- if (constant != null && constant.intValue() < 0) {
- this.scribe.printNextToken(TerminalTokens.TokenNameMINUS);
- }
- this.scribe.printNextToken(TerminalTokens.TokenNameIntegerLiteral);
-
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(intLiteral, numberOfParens);
- }
- return false;
- }
-
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.LabeledStatement, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(LabeledStatement labeledStatement, BlockScope scope) {
-
- this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier);
- this.scribe.printNextToken(TerminalTokens.TokenNameCOLON, this.preferences.insert_space_before_colon_in_labeled_statement);
- if (this.preferences.insert_space_after_colon_in_labeled_statement) {
- this.scribe.space();
- }
- final Statement statement = labeledStatement.statement;
- statement.traverse(this, scope);
- if (statement instanceof Expression || statement instanceof LocalDeclaration) {
- this.scribe.printOptionalNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- }
- return false;
- }
-
- /**
- * @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) {
- formatLocalDeclaration(localDeclaration, scope, this.preferences.insert_space_before_comma_in_multiple_local_declarations, this.preferences.insert_space_after_comma_in_multiple_local_declarations);
- return false;
- }
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.MessageSend, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(MessageSend messageSend, BlockScope scope) {
-
- final int numberOfParens = (messageSend.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(messageSend, numberOfParens);
- }
- CascadingMethodInvocationFragmentBuilder builder = buildFragments(messageSend, scope);
-
- if (builder.size() >= 3 && numberOfParens == 0) {
- formatCascadingMessageSends(builder, scope);
- } else {
- Alignment messageAlignment = null;
- if (messageSend.receiver!=null && !messageSend.receiver.isImplicitThis()) {
- messageSend.receiver.traverse(this, scope);
- messageAlignment = this.scribe.createAlignment(
- "messageAlignment", //$NON-NLS-1$
- this.preferences.alignment_for_selector_in_method_invocation,
- 1,
- this.scribe.scanner.currentPosition);
- this.scribe.enterAlignment(messageAlignment);
- boolean ok = false;
- do {
- try {
- formatMessageSend(messageSend, scope, messageAlignment);
- ok = true;
- } catch (AlignmentException e) {
- this.scribe.redoAlignment(e);
- }
- } while (!ok);
- this.scribe.exitAlignment(messageAlignment, true);
- } else {
- formatMessageSend(messageSend, scope, null);
- }
- }
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(messageSend, numberOfParens);
- }
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration, org.eclipse.wst.jsdt.internal.compiler.lookup.ClassScope)
- */
- public boolean visit(
- MethodDeclaration methodDeclaration,
- Scope scope) {
-
- if (methodDeclaration.ignoreFurtherInvestigation) {
- this.scribe.printComment();
- if (this.scribe.indentationLevel != 0) {
- this.scribe.printIndentationIfNecessary();
- }
- this.scribe.scanner.resetTo(methodDeclaration.declarationSourceEnd + 1, this.scribe.scannerEndPosition - 1);
- this.scribe.printTrailingComment();
- switch(this.scribe.scanner.source[this.scribe.scanner.currentPosition]) {
- case '\n' :
- this.scribe.scanner.currentPosition++;
- this.scribe.lastNumberOfNewLines = 1;
- break;
- case '\r' :
- this.scribe.scanner.currentPosition++;
- if (this.scribe.scanner.source[this.scribe.scanner.currentPosition] == '\n') {
- this.scribe.scanner.currentPosition++;
- }
- this.scribe.lastNumberOfNewLines = 1;
- }
- return false;
- }
-
- /*
- * Print comments to get proper line number
- */
- this.scribe.printComment();
- int line = this.scribe.line;
-
- this.scribe.printModifiers(this);
-
- if (this.scribe.line > line) {
- // annotations introduced new line, but this is not a line wrapping
- // see 158267
- line = this.scribe.line;
- }
- // fix for 258956
- //this.scribe.space();
-
- /*
- * Print the method name
- */
- this.scribe.printNextToken(TerminalTokens.TokenNamefunction);
-
- if (methodDeclaration.selector!=null)
- this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier, true);
-
- formatMethodArguments(
- methodDeclaration,
- this.preferences.insert_space_before_opening_paren_in_method_declaration,
- this.preferences.insert_space_between_empty_parens_in_method_declaration,
- this.preferences.insert_space_before_closing_paren_in_method_declaration,
- this.preferences.insert_space_after_opening_paren_in_method_declaration,
- this.preferences.insert_space_before_comma_in_method_declaration_parameters,
- this.preferences.insert_space_after_comma_in_method_declaration_parameters,
- this.preferences.alignment_for_parameters_in_method_declaration);
-
- /*
- * Check for extra dimensions
- */
- int extraDimensions = getDimensions();
- if (extraDimensions != 0) {
- for (int i = 0; i < extraDimensions; i++) {
- this.scribe.printNextToken(TerminalTokens.TokenNameLBRACKET);
- this.scribe.printNextToken(TerminalTokens.TokenNameRBRACKET);
- }
- }
-
- final MethodScope methodDeclarationScope = methodDeclaration.scope;
-
- if (!methodDeclaration.isAbstract() && ((methodDeclaration.modifiers & ExtraCompilerModifiers.AccSemicolonBody) == 0)) {
- /*
- * Method body
- */
- String method_declaration_brace = this.preferences.brace_position_for_method_declaration;
- formatLeftCurlyBrace(line, method_declaration_brace);
- formatOpeningBrace(method_declaration_brace, this.preferences.insert_space_before_opening_brace_in_method_declaration);
- final int numberOfBlankLinesAtBeginningOfMethodBody = this.preferences.blank_lines_at_beginning_of_method_body;
- if (numberOfBlankLinesAtBeginningOfMethodBody > 0) {
- this.scribe.printEmptyLines(numberOfBlankLinesAtBeginningOfMethodBody);
- }
- final Statement[] statements = methodDeclaration.statements;
- if (statements != null) {
- this.scribe.printNewLine();
- if (this.preferences.indent_statements_compare_to_body) {
- this.scribe.indent();
- }
- formatStatements(methodDeclarationScope, statements, true);
- this.scribe.printComment();
- if (this.preferences.indent_statements_compare_to_body) {
- this.scribe.unIndent();
- }
- } else if (this.preferences.insert_new_line_in_empty_method_body) {
- this.scribe.printNewLine();
- if (this.preferences.indent_statements_compare_to_body) {
- this.scribe.indent();
- }
- this.scribe.printComment();
- if (this.preferences.indent_statements_compare_to_body) {
- this.scribe.unIndent();
- }
- }
- this.scribe.printNextToken(TerminalTokens.TokenNameRBRACE);
- this.scribe.printTrailingComment();
- if (method_declaration_brace.equals(DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED)) {
- this.scribe.unIndent();
- }
- } else {
- // no method body
- this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- }
- return false;
- }
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.NullLiteral, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(NullLiteral nullLiteral, BlockScope scope) {
-
- final int numberOfParens = (nullLiteral.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(nullLiteral, numberOfParens);
- }
- this.scribe.printNextToken(TerminalTokens.TokenNamenull);
-
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(nullLiteral, numberOfParens);
- }
- return false;
- }
-
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.OR_OR_Expression, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(OR_OR_Expression or_or_Expression, BlockScope scope) {
- return dumpBinaryExpression(or_or_Expression, TerminalTokens.TokenNameOR_OR, scope);
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.PostfixExpression, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(
- PostfixExpression postfixExpression,
- BlockScope scope) {
-
- final int numberOfParens = (postfixExpression.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(postfixExpression, numberOfParens);
- }
- postfixExpression.lhs.traverse(this, scope);
- int operator = postfixExpression.operator == OperatorIds.PLUS
- ? TerminalTokens.TokenNamePLUS_PLUS : TerminalTokens.TokenNameMINUS_MINUS;
- this.scribe.printNextToken(operator, this.preferences.insert_space_before_postfix_operator);
- if (this.preferences.insert_space_after_postfix_operator) {
- this.scribe.space();
- }
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(postfixExpression, numberOfParens);
- }
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.PrefixExpression, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(PrefixExpression prefixExpression, BlockScope scope) {
-
- final int numberOfParens = (prefixExpression.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(prefixExpression, numberOfParens);
- }
- int operator = prefixExpression.operator == OperatorIds.PLUS
- ? TerminalTokens.TokenNamePLUS_PLUS : TerminalTokens.TokenNameMINUS_MINUS;
- this.scribe.printNextToken(operator, this.preferences.insert_space_before_prefix_operator);
- if (this.preferences.insert_space_after_prefix_operator) {
- this.scribe.space();
- }
- prefixExpression.lhs.traverse(this, scope);
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(prefixExpression, numberOfParens);
- }
- return false;
- }
-
- public boolean visit(RegExLiteral regexLiteral, BlockScope scope) {
-
- final int numberOfParens = (regexLiteral.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(regexLiteral, numberOfParens);
- }
- this.scribe.printNextToken(TerminalTokens.TokenNameRegExLiteral);
-
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(regexLiteral, numberOfParens);
- }
- return false;
- }
-
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedAllocationExpression, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(
- QualifiedAllocationExpression qualifiedAllocationExpression,
- BlockScope scope) {
-
- final int numberOfParens = (qualifiedAllocationExpression.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(qualifiedAllocationExpression, numberOfParens);
- }
- final Expression enclosingInstance = qualifiedAllocationExpression.enclosingInstance;
- if (enclosingInstance != null) {
- enclosingInstance.traverse(this, scope);
- this.scribe.printNextToken(TerminalTokens.TokenNameDOT);
- }
-
- this.scribe.printNextToken(TerminalTokens.TokenNamenew);
- this.scribe.space();
-
- final int line = this.scribe.line;
- qualifiedAllocationExpression.type.traverse(this, scope);
-
- this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, this.preferences.insert_space_before_opening_paren_in_method_invocation);
-
- final Expression[] arguments = qualifiedAllocationExpression.arguments;
- if (arguments != null) {
- if (this.preferences.insert_space_after_opening_paren_in_method_invocation) {
- this.scribe.space();
- }
- int argumentLength = arguments.length;
- Alignment argumentsAlignment =this.scribe.createAlignment(
- "allocation",//$NON-NLS-1$
- this.preferences.alignment_for_arguments_in_qualified_allocation_expression,
- argumentLength,
- this.scribe.scanner.currentPosition);
- this.scribe.enterAlignment(argumentsAlignment);
- boolean ok = false;
- do {
- try {
- for (int i = 0; i < argumentLength; i++) {
- if (i > 0) {
- this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_allocation_expression);
- this.scribe.printTrailingComment();
- }
- this.scribe.alignFragment(argumentsAlignment, i);
- if (i > 0 && this.preferences.insert_space_after_comma_in_allocation_expression) {
- this.scribe.space();
- }
- arguments[i].traverse(this, scope);
- }
- ok = true;
- } catch (AlignmentException e) {
- this.scribe.redoAlignment(e);
- }
- } while (!ok);
- this.scribe.exitAlignment(argumentsAlignment, true);
- this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_before_closing_paren_in_method_invocation);
- } else {
- this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_between_empty_parens_in_method_invocation);
- }
- final TypeDeclaration anonymousType = qualifiedAllocationExpression.anonymousType;
- if (anonymousType != null) {
- formatLeftCurlyBrace(line, this.preferences.brace_position_for_anonymous_type_declaration);
- formatAnonymousTypeDeclaration(anonymousType);
- }
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(qualifiedAllocationExpression, numberOfParens);
- }
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedNameReference, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(
- QualifiedNameReference qualifiedNameReference,
- BlockScope scope) {
-
- final int numberOfParens = (qualifiedNameReference.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(qualifiedNameReference, numberOfParens);
- }
- this.scribe.printQualifiedReference(qualifiedNameReference.sourceEnd);
-
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(qualifiedNameReference, numberOfParens);
- }
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedThisReference, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(
- QualifiedThisReference qualifiedThisReference,
- BlockScope scope) {
-
- final int numberOfParens = (qualifiedThisReference.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(qualifiedThisReference, numberOfParens);
- }
- qualifiedThisReference.qualification.traverse(this, scope);
- this.scribe.printNextToken(TerminalTokens.TokenNameDOT);
- this.scribe.printNextToken(TerminalTokens.TokenNamethis);
-
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(qualifiedThisReference, numberOfParens);
- }
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedTypeReference, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(
- QualifiedTypeReference qualifiedTypeReference,
- BlockScope scope) {
-
- final int numberOfParens = (qualifiedTypeReference.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(qualifiedTypeReference, numberOfParens);
- }
- this.scribe.printQualifiedReference(qualifiedTypeReference.sourceEnd);
-
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(qualifiedTypeReference, numberOfParens);
- }
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedTypeReference, org.eclipse.wst.jsdt.internal.compiler.lookup.ClassScope)
- */
- public boolean visit(
- QualifiedTypeReference qualifiedTypeReference,
- ClassScope scope) {
-
- final int numberOfParens = (qualifiedTypeReference.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(qualifiedTypeReference, numberOfParens);
- }
- this.scribe.printQualifiedReference(qualifiedTypeReference.sourceEnd);
-
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(qualifiedTypeReference, numberOfParens);
- }
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.ReturnStatement, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(ReturnStatement returnStatement, BlockScope scope) {
-
- this.scribe.printNextToken(TerminalTokens.TokenNamereturn);
- final Expression expression = returnStatement.expression;
- if (expression != null) {
- final int numberOfParens = (expression.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if ((numberOfParens != 0 && this.preferences.insert_space_before_parenthesized_expression_in_return)
- || numberOfParens == 0) {
- this.scribe.space();
- }
- expression.traverse(this, scope);
- }
- /*
- * Print the semi-colon
- */
- this.scribe.printOptionalNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- return false;
- }
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.SingleNameReference, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(SingleNameReference singleNameReference, BlockScope scope) {
-
- final int numberOfParens = (singleNameReference.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(singleNameReference, numberOfParens);
- }
- this.scribe.printNextToken(SINGLETYPEREFERENCE_EXPECTEDTOKENS);
-
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(singleNameReference, numberOfParens);
- }
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.SingleTypeReference, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(
- SingleTypeReference singleTypeReference,
- BlockScope scope) {
-
- final int numberOfParens = (singleTypeReference.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(singleTypeReference, numberOfParens);
- }
- this.scribe.printNextToken(SINGLETYPEREFERENCE_EXPECTEDTOKENS);
-
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(singleTypeReference, numberOfParens);
- }
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.SingleTypeReference, org.eclipse.wst.jsdt.internal.compiler.lookup.ClassScope)
- */
- public boolean visit(
- SingleTypeReference singleTypeReference,
- ClassScope scope) {
-
- final int numberOfParens = (singleTypeReference.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(singleTypeReference, numberOfParens);
- }
- this.scribe.printNextToken(SINGLETYPEREFERENCE_EXPECTEDTOKENS);
-
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(singleTypeReference, numberOfParens);
- }
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.StringLiteral, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(StringLiteral stringLiteral, BlockScope scope) {
- final int numberOfParens = (stringLiteral.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(stringLiteral, numberOfParens);
- }
- this.scribe.checkNLSTag(stringLiteral.sourceStart);
- this.scribe.printNextToken(new int[]{TerminalTokens.TokenNameCharacterLiteral, TerminalTokens.TokenNameStringLiteral});
- this.scribe.printTrailingComment();
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(stringLiteral, numberOfParens);
- }
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.NullLiteral, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(StringLiteralConcatenation stringLiteral, BlockScope scope) {
- final int numberOfParens = (stringLiteral.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(stringLiteral, numberOfParens);
- }
-
- this.scribe.printComment();
- ASTNode[] fragments = stringLiteral.literals;
- int fragmentsSize = stringLiteral.counter;
- Alignment binaryExpressionAlignment = this.scribe.createAlignment("binaryExpressionAlignment", this.preferences.alignment_for_binary_expression, Alignment.R_OUTERMOST, fragmentsSize, this.scribe.scanner.currentPosition); //$NON-NLS-1$
- this.scribe.enterAlignment(binaryExpressionAlignment);
- boolean ok = false;
- do {
- try {
- for (int i = 0; i < fragmentsSize - 1; i++) {
- ASTNode fragment = fragments[i];
- fragment.traverse(this, scope);
- this.scribe.printTrailingComment();
- if (this.scribe.lastNumberOfNewLines == 1) {
- // a new line has been inserted by printTrailingComment()
- this.scribe.indentationLevel = binaryExpressionAlignment.breakIndentationLevel;
- }
- this.scribe.alignFragment(binaryExpressionAlignment, i);
- this.scribe.printNextToken(TerminalTokens.TokenNamePLUS, this.preferences.insert_space_before_binary_operator);
- if (this.preferences.insert_space_after_binary_operator) {
- this.scribe.space();
- }
- }
- fragments[fragmentsSize - 1].traverse(this, scope);
- this.scribe.printTrailingComment();
- ok = true;
- } catch(AlignmentException e){
- this.scribe.redoAlignment(e);
- }
- } while (!ok);
- this.scribe.exitAlignment(binaryExpressionAlignment, true);
-
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(stringLiteral, numberOfParens);
- }
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.SuperReference, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(SuperReference superReference, BlockScope scope) {
-
- final int numberOfParens = (superReference.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(superReference, numberOfParens);
- }
- this.scribe.printNextToken(TerminalTokens.TokenNamesuper);
-
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(superReference, numberOfParens);
- }
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.SwitchStatement, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(SwitchStatement switchStatement, BlockScope scope) {
- this.scribe.printNextToken(TerminalTokens.TokenNameswitch);
- this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, this.preferences.insert_space_before_opening_paren_in_switch);
-
- if (this.preferences.insert_space_after_opening_paren_in_switch) {
- this.scribe.space();
- }
-
- switchStatement.expression.traverse(this, scope);
- this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_before_closing_paren_in_switch);
- /*
- * Type body
- */
- String switch_brace = this.preferences.brace_position_for_switch;
- formatOpeningBrace(switch_brace, this.preferences.insert_space_before_opening_brace_in_switch);
- this.scribe.printNewLine();
-
- if (this.preferences.indent_switchstatements_compare_to_switch) {
- this.scribe.indent();
- }
- final Statement[] statements = switchStatement.statements;
- boolean wasACase = false;
- boolean wasAStatement = false;
- if (statements != null) {
- int statementsLength = statements.length;
- for (int i = 0; i < statementsLength; i++) {
- final Statement statement = statements[i];
- if (statement instanceof CaseStatement) {
- if (wasACase) {
- this.scribe.printNewLine();
- }
- if ((wasACase && this.preferences.indent_switchstatements_compare_to_cases)
- || (wasAStatement && this.preferences.indent_switchstatements_compare_to_cases)) {
- this.scribe.unIndent();
- }
- statement.traverse(this, scope);
- this.scribe.printTrailingComment();
- wasACase = true;
- wasAStatement = false;
- if (this.preferences.indent_switchstatements_compare_to_cases) {
- this.scribe.indent();
- }
- } else if (statement instanceof BreakStatement) {
- if (this.preferences.indent_breaks_compare_to_cases) {
- if (wasAStatement && !this.preferences.indent_switchstatements_compare_to_cases) {
- this.scribe.indent();
- }
- } else {
- if (wasAStatement) {
- if (this.preferences.indent_switchstatements_compare_to_cases) {
- this.scribe.unIndent();
- }
- }
- if (wasACase && this.preferences.indent_switchstatements_compare_to_cases) {
- this.scribe.unIndent();
- }
- }
- if (wasACase) {
- this.scribe.printNewLine();
- }
- statement.traverse(this, scope);
- if (this.preferences.indent_breaks_compare_to_cases) {
- this.scribe.unIndent();
- }
- wasACase = false;
- wasAStatement = false;
- } else if (statement instanceof Block) {
- String bracePosition;
- if (wasACase) {
- if (this.preferences.indent_switchstatements_compare_to_cases) {
- this.scribe.unIndent();
- }
- bracePosition = this.preferences.brace_position_for_block_in_case;
- formatBlock((Block) statement, scope, bracePosition, this.preferences.insert_space_after_colon_in_case);
- if (this.preferences.indent_switchstatements_compare_to_cases) {
- this.scribe.indent();
- }
- } else {
- bracePosition = this.preferences.brace_position_for_block;
- formatBlock((Block) statement, scope, bracePosition, this.preferences.insert_space_before_opening_brace_in_block);
- }
- wasAStatement = true;
- wasACase = false;
- } else {
- this.scribe.printNewLine();
- statement.traverse(this, scope);
- wasAStatement = true;
- wasACase = false;
- }
- if (statement instanceof Expression || statement instanceof LocalDeclaration) {
- /*
- * Print the semi-colon
- */
- this.scribe.printOptionalNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- this.scribe.printNewLine();
- } else if (statement instanceof LocalDeclaration) {
- LocalDeclaration currentLocal = (LocalDeclaration) statement;
- if (i < (statementsLength - 1)) {
- /*
- * We need to check that the next statement is a local declaration
- */
- if (statements[i + 1] instanceof LocalDeclaration) {
- LocalDeclaration nextLocal = (LocalDeclaration) statements[i + 1];
- if (currentLocal.declarationSourceStart != nextLocal.declarationSourceStart) {
- /*
- * Print the semi-colon
- */
- this.scribe.printOptionalNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- this.scribe.printNewLine();
- }
- } else {
- /*
- * Print the semi-colon
- */
- this.scribe.printOptionalNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- this.scribe.printNewLine();
- }
- } else {
- /*
- * Print the semi-colon
- */
- this.scribe.printOptionalNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- this.scribe.printNewLine();
- }
- } else if (!wasACase) {
- this.scribe.printNewLine();
- }
- this.scribe.printComment();
- }
- }
-
- if ((wasACase || wasAStatement) && this.preferences.indent_switchstatements_compare_to_cases) {
- this.scribe.unIndent();
- }
- if (this.preferences.indent_switchstatements_compare_to_switch) {
- this.scribe.unIndent();
- }
- this.scribe.printNewLine();
- this.scribe.printNextToken(TerminalTokens.TokenNameRBRACE);
- this.scribe.printTrailingComment();
- if (switch_brace.equals(DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED)) {
- this.scribe.unIndent();
- }
- return false;
- }
-
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.ThisReference, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(ThisReference thisReference, BlockScope scope) {
-
- if (!thisReference.isImplicitThis()) {
- final int numberOfParens = (thisReference.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(thisReference, numberOfParens);
- }
- this.scribe.printNextToken(TerminalTokens.TokenNamethis);
-
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(thisReference, numberOfParens);
- }
- }
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.ThrowStatement, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(ThrowStatement throwStatement, BlockScope scope) {
-
- this.scribe.printNextToken(TerminalTokens.TokenNamethrow);
- Expression expression = throwStatement.exception;
- final int numberOfParens = (expression.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if ((numberOfParens > 0 && this.preferences.insert_space_before_parenthesized_expression_in_throw)
- || numberOfParens == 0) {
- this.scribe.space();
- }
- expression.traverse(this, scope);
- /*
- * Print the semi-colon
- */
- this.scribe.printOptionalNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.TrueLiteral, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(TrueLiteral trueLiteral, BlockScope scope) {
-
- final int numberOfParens = (trueLiteral.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(trueLiteral, numberOfParens);
- }
- this.scribe.printNextToken(TerminalTokens.TokenNametrue);
-
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(trueLiteral, numberOfParens);
- }
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.TryStatement, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(TryStatement tryStatement, BlockScope scope) {
-
- this.scribe.printNextToken(TerminalTokens.TokenNametry);
- tryStatement.tryBlock.traverse(this, scope);
- if (tryStatement.catchArguments != null) {
- for (int i = 0, max = tryStatement.catchBlocks.length; i < max; i++) {
- if (this.preferences.insert_new_line_before_catch_in_try_statement) {
- this.scribe.printNewLine();
- }
- this.scribe.printNextToken(TerminalTokens.TokenNamecatch, this.preferences.insert_space_after_closing_brace_in_block);
- final int line = this.scribe.line;
- this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, this.preferences.insert_space_before_opening_paren_in_catch);
-
- if (this.preferences.insert_space_after_opening_paren_in_catch) {
- this.scribe.space();
- }
-
- tryStatement.catchArguments[i].traverse(this, scope);
-
- this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_before_closing_paren_in_catch);
-
- formatLeftCurlyBrace(line, this.preferences.brace_position_for_block);
- tryStatement.catchBlocks[i].traverse(this, scope);
- }
- }
- if (tryStatement.finallyBlock != null) {
- if (this.preferences.insert_new_line_before_finally_in_try_statement) {
- this.scribe.printNewLine();
- }
- this.scribe.printNextToken(TerminalTokens.TokenNamefinally, this.preferences.insert_space_after_closing_brace_in_block);
- tryStatement.finallyBlock.traverse(this, scope);
- }
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(
- TypeDeclaration localTypeDeclaration,
- BlockScope scope) {
-
- format(localTypeDeclaration);
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration, org.eclipse.wst.jsdt.internal.compiler.lookup.ClassScope)
- */
- public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope scope) {
- format(memberTypeDeclaration);
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration, org.eclipse.wst.jsdt.internal.compiler.lookup.CompilationUnitScope)
- */
- public boolean visit(
- TypeDeclaration typeDeclaration,
- CompilationUnitScope scope) {
-
- format(typeDeclaration);
- return false;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.UnaryExpression, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(UnaryExpression unaryExpression, BlockScope scope) {
-
- final int numberOfParens = (unaryExpression.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(unaryExpression, numberOfParens);
- }
-
- /*
- * Print the operator
- */
- int operator;
- boolean addSpace=false;
- int operatorValue = (unaryExpression.bits & ASTNode.OperatorMASK) >> ASTNode.OperatorSHIFT;
- switch(operatorValue) {
- case OperatorIds.PLUS:
- operator = TerminalTokens.TokenNamePLUS;
- break;
- case OperatorIds.MINUS:
- operator = TerminalTokens.TokenNameMINUS;
- break;
- case OperatorIds.TWIDDLE:
- operator = TerminalTokens.TokenNameTWIDDLE;
- break;
- case OperatorIds.DELETE:
- operator = TerminalTokens.TokenNamedelete;
- addSpace=true;
- break;
- case OperatorIds.VOID:
- operator = TerminalTokens.TokenNamevoid;
- addSpace=true;
- break;
- case OperatorIds.TYPEOF:
- operator = TerminalTokens.TokenNametypeof;
- addSpace=true;
- break;
- default:
- operator = TerminalTokens.TokenNameNOT;
- }
-
- this.scribe.printNextToken(operator, this.preferences.insert_space_before_unary_operator);
- if (this.preferences.insert_space_after_unary_operator || addSpace) {
- this.scribe.space();
- }
- Expression expression = unaryExpression.expression;
-
- if (expression instanceof PrefixExpression) {
- PrefixExpression prefixExpression = (PrefixExpression) expression;
- final int numberOfParensForExpression = (prefixExpression.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParensForExpression == 0) {
- switch(operatorValue) {
- case OperatorIds.PLUS:
- if (prefixExpression.operator == OperatorIds.PLUS) {
- this.scribe.space();
- }
- break;
- case OperatorIds.MINUS:
- if (prefixExpression.operator == OperatorIds.MINUS) {
- this.scribe.space();
- }
- break;
- }
- }
- expression.traverse(this, scope);
- } else {
- expression.traverse(this, scope);
- }
-
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(unaryExpression, numberOfParens);
- }
- return false;
- }
-
- public boolean visit(UndefinedLiteral undefinedLiteral, BlockScope scope) {
-
- final int numberOfParens = (undefinedLiteral.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT;
- if (numberOfParens > 0) {
- manageOpeningParenthesizedExpression(undefinedLiteral, numberOfParens);
- }
- this.scribe.printNextToken(TerminalTokens.TokenNameundefined);
-
- if (numberOfParens > 0) {
- manageClosingParenthesizedExpression(undefinedLiteral, numberOfParens);
- }
- return false;
- }
-
-
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.WhileStatement, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(WhileStatement whileStatement, BlockScope scope) {
-
- this.scribe.printNextToken(TerminalTokens.TokenNamewhile);
- final int line = this.scribe.line;
- this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, this.preferences.insert_space_before_opening_paren_in_while);
-
- if (this.preferences.insert_space_after_opening_paren_in_while) {
- this.scribe.space();
- }
- whileStatement.condition.traverse(this, scope);
-
- this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_before_closing_paren_in_while);
-
- final Statement action = whileStatement.action;
- if (action != null) {
- if (action instanceof Block) {
- formatLeftCurlyBrace(line, this.preferences.brace_position_for_block);
- action.traverse(this, scope);
- } else if (action instanceof EmptyStatement) {
- /*
- * This is an empty statement
- */
- formatNecessaryEmptyStatement();
- } else {
- this.scribe.printNewLine();
- this.scribe.indent();
- action.traverse(this, scope);
- if (action instanceof Expression || action instanceof LocalDeclaration) {
- this.scribe.printOptionalNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- }
- this.scribe.unIndent();
- }
- } else {
- /*
- * This is an empty statement
- */
- formatNecessaryEmptyStatement();
- }
- return false;
- }
-
-
- /**
- * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.WhileStatement, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope)
- */
- public boolean visit(WithStatement withStatement, BlockScope scope) {
-
- this.scribe.printNextToken(TerminalTokens.TokenNamewith);
- final int line = this.scribe.line;
- this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, this.preferences.insert_space_before_opening_paren_in_while);
-
- if (this.preferences.insert_space_after_opening_paren_in_while) {
- this.scribe.space();
- }
- withStatement.condition.traverse(this, scope);
-
- this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_before_closing_paren_in_while);
-
- final Statement action = withStatement.action;
- if (action != null) {
- if (action instanceof Block) {
- formatLeftCurlyBrace(line, this.preferences.brace_position_for_block);
- action.traverse(this, scope);
- } else if (action instanceof EmptyStatement) {
- /*
- * This is an empty statement
- */
- formatNecessaryEmptyStatement();
- } else {
- this.scribe.printNewLine();
- this.scribe.indent();
- action.traverse(this, scope);
- if (action instanceof Expression|| action instanceof LocalDeclaration) {
- this.scribe.printOptionalNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon);
- this.scribe.printTrailingComment();
- }
- this.scribe.unIndent();
- }
- } else {
- /*
- * This is an empty statement
- */
- formatNecessaryEmptyStatement();
- }
- return false;
- }
-
- public boolean visit(ListExpression listExpression, BlockScope scope) {
- int expressionsLength=listExpression.expressions.length;
- Alignment argumentsAlignment = this.scribe.createAlignment(
- "messageArguments", //$NON-NLS-1$
- this.preferences.alignment_for_arguments_in_method_invocation,
- expressionsLength,
- this.scribe.scanner.currentPosition);
- this.scribe.enterAlignment(argumentsAlignment);
- boolean ok = false;
- do {
- try {
- for (int i = 0; i < expressionsLength; i++) {
- if (i > 0) {
- this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_method_invocation_arguments);
- this.scribe.printTrailingComment();
- }
- this.scribe.alignFragment(argumentsAlignment, i);
- if (i > 0 && this.preferences.insert_space_after_comma_in_method_invocation_arguments) {
- this.scribe.space();
- }
- listExpression.expressions[i].traverse(this, scope);
- }
- ok = true;
- } catch (AlignmentException e) {
- this.scribe.redoAlignment(e);
- }
- } while (!ok);
- this.scribe.exitAlignment(argumentsAlignment, true);
- return false;
- }
-}
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
deleted file mode 100644
index 1c386d68..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/DefaultCodeFormatter.java
+++ /dev/null
@@ -1,420 +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.formatter;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.Position;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.compiler.ITerminalSymbols;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.core.formatter.CodeFormatter;
-import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants;
-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.ConstructorDeclaration;
-import org.eclipse.wst.jsdt.internal.compiler.ast.Expression;
-import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants;
-import org.eclipse.wst.jsdt.internal.compiler.impl.CompilerOptions;
-import org.eclipse.wst.jsdt.internal.compiler.parser.Scanner;
-import org.eclipse.wst.jsdt.internal.compiler.util.Util;
-import org.eclipse.wst.jsdt.internal.core.util.CodeSnippetParsingUtil;
-import org.eclipse.wst.jsdt.internal.formatter.comment.CommentRegion;
-import org.eclipse.wst.jsdt.internal.formatter.comment.JavaDocRegion;
-import org.eclipse.wst.jsdt.internal.formatter.comment.MultiCommentRegion;
-
-public class DefaultCodeFormatter extends CodeFormatter {
-
- public static final boolean DEBUG = false;
- private static Scanner ProbingScanner;
-
- /**
- * Creates a comment region for a specific document partition type.
- *
- * @param kind the comment snippet kind
- * @param document the document which contains the comment region
- * @param range range of the comment region in the document
- * @return a new comment region for the comment region range in the
- * document
- * @since 3.1
- */
- public static CommentRegion createRegion(int kind, IDocument document, Position range, CodeFormatterVisitor formatter) {
- switch (kind) {
- case CodeFormatter.K_SINGLE_LINE_COMMENT:
- return new CommentRegion(document, range, formatter);
- case CodeFormatter.K_MULTI_LINE_COMMENT:
- return new MultiCommentRegion(document, range, formatter);
- case CodeFormatter.K_JAVA_DOC:
- return new JavaDocRegion(document, range, formatter);
- }
- return null;
- }
-
- private CodeSnippetParsingUtil codeSnippetParsingUtil;
- private Map defaultCompilerOptions;
-
- private CodeFormatterVisitor newCodeFormatter;
- private Map options;
-
- private DefaultCodeFormatterOptions preferences;
-
- public DefaultCodeFormatter() {
- this(new DefaultCodeFormatterOptions(DefaultCodeFormatterConstants.getJavaConventionsSettings()), null);
- }
-
- public DefaultCodeFormatter(DefaultCodeFormatterOptions preferences) {
- this(preferences, null);
- }
-
- public DefaultCodeFormatter(DefaultCodeFormatterOptions defaultCodeFormatterOptions, Map options) {
- if (options != null) {
- this.options = options;
- this.preferences = new DefaultCodeFormatterOptions(options);
- } else {
- this.options = JavaScriptCore.getOptions();
- this.preferences = new DefaultCodeFormatterOptions(DefaultCodeFormatterConstants.getJavaConventionsSettings());
- }
- this.defaultCompilerOptions = getDefaultCompilerOptions();
- if (defaultCodeFormatterOptions != null) {
- this.preferences.set(defaultCodeFormatterOptions.getMap());
- }
- }
-
- public DefaultCodeFormatter(Map options) {
- this(null, options);
- }
-
- public String createIndentationString(final int indentationLevel) {
- if (indentationLevel < 0) {
- throw new IllegalArgumentException();
- }
-
- int tabs = 0;
- int spaces = 0;
- switch(this.preferences.tab_char) {
- case DefaultCodeFormatterOptions.SPACE :
- spaces = indentationLevel * this.preferences.tab_size;
- break;
- case DefaultCodeFormatterOptions.TAB :
- tabs = indentationLevel;
- break;
- case DefaultCodeFormatterOptions.MIXED :
- int tabSize = this.preferences.tab_size;
- int spaceEquivalents = indentationLevel * this.preferences.indentation_size;
- tabs = spaceEquivalents / tabSize;
- spaces = spaceEquivalents % tabSize;
- break;
- default:
- return Util.EMPTY_STRING;
- }
- if (tabs == 0 && spaces == 0) {
- return Util.EMPTY_STRING;
- }
- StringBuffer buffer = new StringBuffer(tabs + spaces);
- for(int i = 0; i < tabs; i++) {
- buffer.append('\t');
- }
- for(int i = 0; i < spaces; i++) {
- buffer.append(' ');
- }
- return buffer.toString();
- }
-
- /**
- * @see org.eclipse.wst.jsdt.core.formatter.CodeFormatter#format(int, java.lang.String, int, int, int, java.lang.String)
- */
- public TextEdit format(
- int kind,
- String source,
- int offset,
- int length,
- int indentationLevel,
- String lineSeparator) {
-
- if (offset < 0 || length < 0 || length > source.length()) {
- throw new IllegalArgumentException();
- }
- this.codeSnippetParsingUtil = new CodeSnippetParsingUtil();
- switch(kind) {
- case K_CLASS_BODY_DECLARATIONS :
- return formatClassBodyDeclarations(source, indentationLevel, lineSeparator, offset, length);
- case K_JAVASCRIPT_UNIT :
- return formatCompilationUnit(source, indentationLevel, lineSeparator, offset, length);
- case K_EXPRESSION :
- return formatExpression(source, indentationLevel, lineSeparator, offset, length);
- case K_STATEMENTS :
- return formatStatements(source, indentationLevel, lineSeparator, offset, length);
- case K_UNKNOWN :
- return probeFormatting(source, indentationLevel, lineSeparator, offset, length);
- case K_JAVA_DOC :
- case K_MULTI_LINE_COMMENT :
- case K_SINGLE_LINE_COMMENT :
- return formatComment(kind, source, indentationLevel, lineSeparator, offset, length);
- }
- return null;
- }
-
- private TextEdit formatClassBodyDeclarations(String source, int indentationLevel, String lineSeparator, int offset, int length) {
- ASTNode[] bodyDeclarations = this.codeSnippetParsingUtil.parseClassBodyDeclarations(source.toCharArray(), getDefaultCompilerOptions(), true);
-
- if (bodyDeclarations == null) {
- // a problem occured while parsing the source
- return null;
- }
- return internalFormatClassBodyDeclarations(source, indentationLevel, lineSeparator, bodyDeclarations, offset, length);
- }
-
- /**
- * Returns the resulting text edit after formatting the given comment.
- *
- * @param kind the given kind
- * @param source the given source
- * @param indentationLevel the given indentation level
- * @param lineSeparator the given line separator
- * @param offset the given offset
- * @param length the given length
- * @return the resulting text edit
- * @deprecated
- */
- private TextEdit formatComment(int kind, String source, int indentationLevel, String lineSeparator, int offset, int length) {
- Object oldOption = this.options.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT);
- boolean isFormattingComments = false;
- if (oldOption == null) {
- switch (kind) {
- case CodeFormatter.K_SINGLE_LINE_COMMENT:
- isFormattingComments = DefaultCodeFormatterConstants.TRUE.equals(this.options.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_LINE_COMMENT));
- break;
- case CodeFormatter.K_MULTI_LINE_COMMENT:
- isFormattingComments = DefaultCodeFormatterConstants.TRUE.equals(this.options.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_BLOCK_COMMENT));
- break;
- case CodeFormatter.K_JAVA_DOC:
- isFormattingComments = DefaultCodeFormatterConstants.TRUE.equals(this.options.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_JAVADOC_COMMENT));
- }
- } else {
- isFormattingComments = DefaultCodeFormatterConstants.TRUE.equals(oldOption);
- }
- if (isFormattingComments) {
- if (lineSeparator != null) {
- this.preferences.line_separator = lineSeparator;
- } else {
- this.preferences.line_separator = Util.LINE_SEPARATOR;
- }
- this.preferences.initial_indentation_level = indentationLevel;
- this.newCodeFormatter = new CodeFormatterVisitor(this.preferences, this.options, offset, length, null);
- final CommentRegion region = createRegion(kind, new Document(source), new Position(offset, length), this.newCodeFormatter);
- if (region != null) {
- return this.newCodeFormatter.format(source, region);
- }
- }
- return new MultiTextEdit();
- }
-
- private TextEdit formatCompilationUnit(String source, int indentationLevel, String lineSeparator, int offset, int length) {
- CompilationUnitDeclaration compilationUnitDeclaration = this.codeSnippetParsingUtil.parseCompilationUnit(source.toCharArray(), getDefaultCompilerOptions(), true);
-
- if (lineSeparator != null) {
- this.preferences.line_separator = lineSeparator;
- } else {
- this.preferences.line_separator = Util.LINE_SEPARATOR;
- }
- this.preferences.initial_indentation_level = indentationLevel;
-
- this.newCodeFormatter = new CodeFormatterVisitor(this.preferences, this.options, offset, length, this.codeSnippetParsingUtil);
-
- return this.newCodeFormatter.format(source, compilationUnitDeclaration);
- }
-
- private TextEdit formatExpression(String source, int indentationLevel, String lineSeparator, int offset, int length) {
- Expression expression = this.codeSnippetParsingUtil.parseExpression(source.toCharArray(), getDefaultCompilerOptions(), true);
-
- if (expression == null) {
- // a problem occured while parsing the source
- return null;
- }
- return internalFormatExpression(source, indentationLevel, lineSeparator, expression, offset, length);
- }
-
- private TextEdit formatStatements(String source, int indentationLevel, String lineSeparator, int offset, int length) {
- ConstructorDeclaration constructorDeclaration = this.codeSnippetParsingUtil.parseStatements(source.toCharArray(), getDefaultCompilerOptions(), true, false);
-
- if (constructorDeclaration.statements == null) {
- // a problem occured while parsing the source
- return null;
- }
- return internalFormatStatements(source, indentationLevel, lineSeparator, constructorDeclaration, offset, length);
- }
-
- public String getDebugOutput() {
- return this.newCodeFormatter.scribe.toString();
- }
-
- private Map getDefaultCompilerOptions() {
- if (this.defaultCompilerOptions == null) {
- Map optionsMap = new HashMap(30);
- optionsMap.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.DO_NOT_GENERATE);
- optionsMap.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.DO_NOT_GENERATE);
- optionsMap.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.DO_NOT_GENERATE);
- optionsMap.put(CompilerOptions.OPTION_PreserveUnusedLocal, CompilerOptions.PRESERVE);
- optionsMap.put(CompilerOptions.OPTION_DocCommentSupport, CompilerOptions.DISABLED);
- optionsMap.put(CompilerOptions.OPTION_ReportMethodWithConstructorName, CompilerOptions.IGNORE);
- optionsMap.put(CompilerOptions.OPTION_ReportUndefinedField, CompilerOptions.IGNORE);
- optionsMap.put(CompilerOptions.OPTION_ReportOverridingMethodWithoutSuperInvocation, CompilerOptions.IGNORE);
- optionsMap.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.IGNORE);
- optionsMap.put(CompilerOptions.OPTION_ReportDeprecationInDeprecatedCode, CompilerOptions.DISABLED);
- optionsMap.put(CompilerOptions.OPTION_ReportDeprecationWhenOverridingDeprecatedMethod, CompilerOptions.DISABLED);
- optionsMap.put(CompilerOptions.OPTION_ReportHiddenCatchBlock, CompilerOptions.IGNORE);
- optionsMap.put(CompilerOptions.OPTION_ReportUnusedLocal, CompilerOptions.IGNORE);
- optionsMap.put(CompilerOptions.OPTION_ReportUnusedParameter, CompilerOptions.IGNORE);
- optionsMap.put(CompilerOptions.OPTION_ReportWrongNumberOfArguments, CompilerOptions.IGNORE);
- optionsMap.put(CompilerOptions.OPTION_ReportNoEffectAssignment, CompilerOptions.IGNORE);
- optionsMap.put(CompilerOptions.OPTION_ReportNonExternalizedStringLiteral, CompilerOptions.IGNORE);
- optionsMap.put(CompilerOptions.OPTION_ReportNonStaticAccessToStatic, CompilerOptions.IGNORE);
- optionsMap.put(CompilerOptions.OPTION_ReportIndirectStaticAccess, CompilerOptions.IGNORE);
- optionsMap.put(CompilerOptions.OPTION_ReportUnusedPrivateMember, CompilerOptions.IGNORE);
- optionsMap.put(CompilerOptions.OPTION_ReportLocalVariableHiding, CompilerOptions.IGNORE);
- optionsMap.put(CompilerOptions.OPTION_ReportFieldHiding, CompilerOptions.IGNORE);
- optionsMap.put(CompilerOptions.OPTION_ReportPossibleAccidentalBooleanAssignment, CompilerOptions.IGNORE);
- optionsMap.put(CompilerOptions.OPTION_ReportEmptyStatement, CompilerOptions.IGNORE);
- optionsMap.put(CompilerOptions.OPTION_ReportAssertIdentifier, CompilerOptions.IGNORE);
- optionsMap.put(CompilerOptions.OPTION_ReportEnumIdentifier, CompilerOptions.IGNORE);
- optionsMap.put(CompilerOptions.OPTION_ReportUndocumentedEmptyBlock, CompilerOptions.IGNORE);
- optionsMap.put(CompilerOptions.OPTION_ReportUnnecessaryTypeCheck, CompilerOptions.IGNORE);
- optionsMap.put(CompilerOptions.OPTION_ReportInvalidJavadoc, CompilerOptions.IGNORE);
- optionsMap.put(CompilerOptions.OPTION_ReportInvalidJavadocTagsVisibility, CompilerOptions.PUBLIC);
- optionsMap.put(CompilerOptions.OPTION_ReportInvalidJavadocTags, CompilerOptions.DISABLED);
- optionsMap.put(CompilerOptions.OPTION_ReportInvalidJavadocTagsDeprecatedRef, CompilerOptions.DISABLED);
- optionsMap.put(CompilerOptions.OPTION_ReportInvalidJavadocTagsNotVisibleRef, CompilerOptions.DISABLED);
- optionsMap.put(CompilerOptions.OPTION_ReportMissingJavadocTags, CompilerOptions.IGNORE);
- optionsMap.put(CompilerOptions.OPTION_ReportMissingJavadocTagsVisibility, CompilerOptions.PUBLIC);
- optionsMap.put(CompilerOptions.OPTION_ReportMissingJavadocTagsOverriding, CompilerOptions.DISABLED);
- optionsMap.put(CompilerOptions.OPTION_ReportMissingJavadocComments, CompilerOptions.IGNORE);
- optionsMap.put(CompilerOptions.OPTION_ReportMissingJavadocCommentsVisibility, CompilerOptions.IGNORE);
- optionsMap.put(CompilerOptions.OPTION_ReportMissingJavadocCommentsOverriding, CompilerOptions.DISABLED);
- optionsMap.put(CompilerOptions.OPTION_ReportFinallyBlockNotCompletingNormally, CompilerOptions.IGNORE);
- optionsMap.put(CompilerOptions.OPTION_ReportUnusedDeclaredThrownException, CompilerOptions.IGNORE);
- optionsMap.put(CompilerOptions.OPTION_ReportUnusedDeclaredThrownExceptionWhenOverriding, CompilerOptions.DISABLED);
- optionsMap.put(CompilerOptions.OPTION_ReportUnqualifiedFieldAccess, CompilerOptions.IGNORE);
- optionsMap.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_4);
- optionsMap.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_2);
- optionsMap.put(CompilerOptions.OPTION_TaskTags, ""); //$NON-NLS-1$
- optionsMap.put(CompilerOptions.OPTION_TaskPriorities, ""); //$NON-NLS-1$
- optionsMap.put(CompilerOptions.OPTION_TaskCaseSensitive, CompilerOptions.DISABLED);
- optionsMap.put(CompilerOptions.OPTION_ReportUnusedParameterWhenImplementingAbstract, CompilerOptions.DISABLED);
- optionsMap.put(CompilerOptions.OPTION_ReportUnusedParameterWhenOverridingConcrete, CompilerOptions.DISABLED);
- optionsMap.put(CompilerOptions.OPTION_ReportSpecialParameterHidingField, CompilerOptions.DISABLED);
- optionsMap.put(CompilerOptions.OPTION_MaxProblemPerUnit, String.valueOf(100));
- optionsMap.put(CompilerOptions.OPTION_InlineJsr, CompilerOptions.DISABLED);
- this.defaultCompilerOptions = optionsMap;
- }
- Object sourceOption = this.options.get(CompilerOptions.OPTION_Source);
- if (sourceOption != null) {
- this.defaultCompilerOptions.put(CompilerOptions.OPTION_Source, sourceOption);
- } else {
- this.defaultCompilerOptions.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
- }
- return this.defaultCompilerOptions;
- }
-
- private TextEdit internalFormatClassBodyDeclarations(String source, int indentationLevel, String lineSeparator, ASTNode[] bodyDeclarations, int offset, int length) {
- if (lineSeparator != null) {
- this.preferences.line_separator = lineSeparator;
- } else {
- this.preferences.line_separator = Util.LINE_SEPARATOR;
- }
- this.preferences.initial_indentation_level = indentationLevel;
-
- this.newCodeFormatter = new CodeFormatterVisitor(this.preferences, this.options, offset, length, this.codeSnippetParsingUtil);
- return this.newCodeFormatter.format(source, bodyDeclarations);
- }
-
- private TextEdit internalFormatExpression(String source, int indentationLevel, String lineSeparator, Expression expression, int offset, int length) {
- if (lineSeparator != null) {
- this.preferences.line_separator = lineSeparator;
- } else {
- this.preferences.line_separator = Util.LINE_SEPARATOR;
- }
- this.preferences.initial_indentation_level = indentationLevel;
-
- this.newCodeFormatter = new CodeFormatterVisitor(this.preferences, this.options, offset, length, this.codeSnippetParsingUtil);
-
- TextEdit textEdit = this.newCodeFormatter.format(source, expression);
- return textEdit;
- }
-
- private TextEdit internalFormatStatements(String source, int indentationLevel, String lineSeparator, ConstructorDeclaration constructorDeclaration, int offset, int length) {
- if (lineSeparator != null) {
- this.preferences.line_separator = lineSeparator;
- } else {
- this.preferences.line_separator = Util.LINE_SEPARATOR;
- }
- this.preferences.initial_indentation_level = indentationLevel;
-
- this.newCodeFormatter = new CodeFormatterVisitor(this.preferences, this.options, offset, length, this.codeSnippetParsingUtil);
-
- return this.newCodeFormatter.format(source, constructorDeclaration);
- }
-
- private TextEdit probeFormatting(String source, int indentationLevel, String lineSeparator, int offset, int length) {
- if (ProbingScanner == null) {
- // scanner use to check if the kind could be K_JAVA_DOC, K_MULTI_LINE_COMMENT or K_SINGLE_LINE_COMMENT
- ProbingScanner = new Scanner(true, true, false/*nls*/, ClassFileConstants.JDK1_3, ClassFileConstants.JDK1_3, null/*taskTags*/, null/*taskPriorities*/, true/*taskCaseSensitive*/);
- }
- ProbingScanner.setSource(source.toCharArray());
- ProbingScanner.resetTo(offset, offset + length);
- try {
- switch(ProbingScanner.getNextToken()) {
- case ITerminalSymbols.TokenNameCOMMENT_BLOCK :
- if (ProbingScanner.getCurrentTokenEndPosition() == offset + length - 1) {
- return formatComment(K_MULTI_LINE_COMMENT, source, indentationLevel, lineSeparator, offset, length);
- }
- break;
- case ITerminalSymbols.TokenNameCOMMENT_LINE :
- if (ProbingScanner.getCurrentTokenEndPosition() == offset + length - 1) {
- return formatComment(K_SINGLE_LINE_COMMENT, source, indentationLevel, lineSeparator, offset, length);
- }
- break;
- case ITerminalSymbols.TokenNameCOMMENT_JAVADOC :
- if (ProbingScanner.getCurrentTokenEndPosition() == offset + length - 1) {
- return formatComment(K_JAVA_DOC, source, indentationLevel, lineSeparator, offset, length);
- }
- }
- } catch (InvalidInputException e) {
- // ignore
- }
- ProbingScanner.setSource((char[]) null);
-
- // probe for expression
- Expression expression = this.codeSnippetParsingUtil.parseExpression(source.toCharArray(), getDefaultCompilerOptions(), true);
- if (expression != null) {
- return internalFormatExpression(source, indentationLevel, lineSeparator, expression, offset, length);
- }
-
- // probe for body declarations (fields, methods, constructors)
- ASTNode[] bodyDeclarations = this.codeSnippetParsingUtil.parseClassBodyDeclarations(source.toCharArray(), getDefaultCompilerOptions(), true);
- if (bodyDeclarations != null) {
- return internalFormatClassBodyDeclarations(source, indentationLevel, lineSeparator, bodyDeclarations, offset, length);
- }
-
- // probe for statements
- ConstructorDeclaration constructorDeclaration = this.codeSnippetParsingUtil.parseStatements(source.toCharArray(), getDefaultCompilerOptions(), true, false);
- if (constructorDeclaration.statements != null) {
- return internalFormatStatements(source, indentationLevel, lineSeparator, constructorDeclaration, offset, length);
- }
-
- // this has to be a compilation unit
- return formatCompilationUnit(source, indentationLevel, lineSeparator, offset, length);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/DefaultCodeFormatterOptions.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/DefaultCodeFormatterOptions.java
deleted file mode 100644
index d43ca6ea..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/DefaultCodeFormatterOptions.java
+++ /dev/null
@@ -1,2475 +0,0 @@
-/*******************************************************************************
- * 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
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.formatter;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants;
-import org.eclipse.wst.jsdt.internal.formatter.align.Alignment;
-
-/**
- * This is still subject to changes before 3.0.
- * @since 3.0
- */
-
-public class DefaultCodeFormatterOptions {
- public static final int TAB = 1;
- public static final int SPACE = 2;
- public static final int MIXED = 4;
-
- public static DefaultCodeFormatterOptions getDefaultSettings() {
- DefaultCodeFormatterOptions options = new DefaultCodeFormatterOptions();
- options.setDefaultSettings();
- return options;
- }
-
- public static DefaultCodeFormatterOptions getEclipseDefaultSettings() {
- DefaultCodeFormatterOptions options = new DefaultCodeFormatterOptions();
- options.setEclipseDefaultSettings();
- return options;
- }
-
- public static DefaultCodeFormatterOptions getJavaConventionsSettings() {
- DefaultCodeFormatterOptions options = new DefaultCodeFormatterOptions();
- options.setJavaConventionsSettings();
- return options;
- }
-
- public int alignment_for_arguments_in_allocation_expression;
- public int alignment_for_arguments_in_enum_constant;
- public int alignment_for_arguments_in_explicit_constructor_call;
- public int alignment_for_arguments_in_method_invocation;
- public int alignment_for_arguments_in_qualified_allocation_expression;
- public int alignment_for_assignment;
- public int alignment_for_binary_expression;
- public int alignment_for_compact_if;
- public int alignment_for_conditional_expression;
- public int alignment_for_enum_constants;
- public int alignment_for_expressions_in_array_initializer;
- public int alignment_for_multiple_fields;
- public int alignment_for_parameters_in_constructor_declaration;
- public int alignment_for_parameters_in_method_declaration;
- public int alignment_for_selector_in_method_invocation;
- public int alignment_for_superclass_in_type_declaration;
- public int alignment_for_superinterfaces_in_enum_declaration;
- public int alignment_for_superinterfaces_in_type_declaration;
- public int alignment_for_throws_clause_in_constructor_declaration;
- public int alignment_for_throws_clause_in_method_declaration;
- public int alignment_for_fields_in_object_literal;
-
- public boolean align_type_members_on_columns;
-
- public String brace_position_for_annotation_type_declaration;
- public String brace_position_for_anonymous_type_declaration;
- public String brace_position_for_array_initializer;
- public String brace_position_for_objlit_initializer;
- public String brace_position_for_block;
- public String brace_position_for_block_in_case;
- public String brace_position_for_constructor_declaration;
- public String brace_position_for_enum_constant;
- public String brace_position_for_enum_declaration;
- public String brace_position_for_method_declaration;
- public String brace_position_for_type_declaration;
- public String brace_position_for_switch;
-
- public int continuation_indentation;
- public int continuation_indentation_for_array_initializer;
- public int continuation_indentation_for_objlit_initializer;
-
- public int blank_lines_after_imports;
- public int blank_lines_after_package;
- public int blank_lines_before_field;
- public int blank_lines_before_first_class_body_declaration;
- public int blank_lines_before_imports;
- public int blank_lines_before_member_type;
- public int blank_lines_before_method;
- public int blank_lines_before_new_chunk;
- public int blank_lines_before_package;
- public int blank_lines_between_import_groups;
- public int blank_lines_between_type_declarations;
- public int blank_lines_at_beginning_of_method_body;
-
- public boolean comment_clear_blank_lines_in_javadoc_comment;
- public boolean comment_clear_blank_lines_in_block_comment;
- public boolean comment_format_javadoc_comment;
- public boolean comment_format_line_comment;
- public boolean comment_format_block_comment;
- public boolean comment_format_header;
- public boolean comment_format_html;
- public boolean comment_format_source;
- public boolean comment_indent_parameter_description;
- public boolean comment_indent_root_tags;
- public boolean comment_insert_empty_line_before_root_tags;
- public boolean comment_insert_new_line_for_parameter;
- public int comment_line_length;
-
- public boolean indent_statements_compare_to_block;
- public boolean indent_statements_compare_to_body;
- public boolean indent_body_declarations_compare_to_annotation_declaration_header;
- public boolean indent_body_declarations_compare_to_enum_constant_header;
- public boolean indent_body_declarations_compare_to_enum_declaration_header;
- public boolean indent_body_declarations_compare_to_type_header;
- public boolean indent_breaks_compare_to_cases;
- public boolean indent_empty_lines;
- public boolean indent_switchstatements_compare_to_cases;
- public boolean indent_switchstatements_compare_to_switch;
- public int indentation_size;
-
- public boolean insert_new_line_after_annotation;
- public boolean insert_new_line_after_opening_brace_in_array_initializer;
- public boolean insert_new_line_after_opening_brace_in_objlit_initializer;
- public boolean insert_new_line_after_comma_in_objlit_initializer;
- public boolean insert_new_line_at_end_of_file_if_missing;
- public boolean insert_new_line_before_catch_in_try_statement;
- public boolean insert_new_line_before_closing_brace_in_array_initializer;
- public boolean insert_new_line_before_closing_brace_in_objlit_initializer;
- public boolean insert_new_line_before_else_in_if_statement;
- public boolean insert_new_line_before_finally_in_try_statement;
- public boolean insert_new_line_before_while_in_do_statement;
- public boolean insert_new_line_in_empty_anonymous_type_declaration;
- public boolean insert_new_line_in_empty_block;
- public boolean insert_new_line_in_empty_annotation_declaration;
- public boolean insert_new_line_in_empty_enum_constant;
- public boolean insert_new_line_in_empty_enum_declaration;
- public boolean insert_new_line_in_empty_method_body;
- public boolean insert_new_line_in_empty_type_declaration;
- public boolean insert_space_after_and_in_type_parameter;
- public boolean insert_space_after_assignment_operator;
- public boolean insert_space_after_at_in_annotation;
- public boolean insert_space_after_at_in_annotation_type_declaration;
- public boolean insert_space_after_binary_operator;
- public boolean insert_space_after_closing_angle_bracket_in_type_arguments;
- public boolean insert_space_after_closing_angle_bracket_in_type_parameters;
- public boolean insert_space_after_closing_paren_in_cast;
- public boolean insert_space_after_closing_brace_in_block;
- public boolean insert_space_after_colon_in_assert;
- public boolean insert_space_after_colon_in_case;
- public boolean insert_space_after_colon_in_conditional;
- public boolean insert_space_after_colon_in_object_initializer;
- public boolean insert_space_after_colon_in_for;
- public boolean insert_space_after_colon_in_labeled_statement;
- public boolean insert_space_after_comma_in_allocation_expression;
- public boolean insert_space_after_comma_in_annotation;
- public boolean insert_space_after_comma_in_array_initializer;
- public boolean insert_space_after_comma_in_constructor_declaration_parameters;
- public boolean insert_space_after_comma_in_constructor_declaration_throws;
- public boolean insert_space_after_comma_in_enum_constant_arguments;
- public boolean insert_space_after_comma_in_enum_declarations;
- public boolean insert_space_after_comma_in_explicit_constructor_call_arguments;
- public boolean insert_space_after_comma_in_for_increments;
- public boolean insert_space_after_comma_in_for_inits;
- public boolean insert_space_after_comma_in_method_invocation_arguments;
- public boolean insert_space_after_comma_in_method_declaration_parameters;
- public boolean insert_space_after_comma_in_method_declaration_throws;
- public boolean insert_space_after_comma_in_multiple_field_declarations;
- public boolean insert_space_after_comma_in_multiple_local_declarations;
- public boolean insert_space_after_comma_in_parameterized_type_reference;
- public boolean insert_space_after_comma_in_superinterfaces;
- public boolean insert_space_after_comma_in_type_arguments;
- public boolean insert_space_after_comma_in_type_parameters;
- public boolean insert_space_after_ellipsis;
- public boolean insert_space_after_opening_angle_bracket_in_parameterized_type_reference;
- public boolean insert_space_after_opening_angle_bracket_in_type_arguments;
- public boolean insert_space_after_opening_angle_bracket_in_type_parameters;
- public boolean insert_space_after_opening_bracket_in_array_allocation_expression;
- public boolean insert_space_after_opening_bracket_in_array_reference;
- public boolean insert_space_after_opening_brace_in_array_initializer;
- public boolean insert_space_after_opening_paren_in_annotation;
- public boolean insert_space_after_opening_paren_in_cast;
- public boolean insert_space_after_opening_paren_in_catch;
- public boolean insert_space_after_opening_paren_in_constructor_declaration;
- public boolean insert_space_after_opening_paren_in_enum_constant;
- public boolean insert_space_after_opening_paren_in_for;
- public boolean insert_space_after_opening_paren_in_if;
- public boolean insert_space_after_opening_paren_in_method_declaration;
- public boolean insert_space_after_opening_paren_in_method_invocation;
- public boolean insert_space_after_opening_paren_in_parenthesized_expression;
- public boolean insert_space_after_opening_paren_in_switch;
- public boolean insert_space_after_opening_paren_in_synchronized;
- public boolean insert_space_after_opening_paren_in_while;
- public boolean insert_space_after_postfix_operator;
- public boolean insert_space_after_prefix_operator;
- public boolean insert_space_after_question_in_conditional;
- public boolean insert_space_after_semicolon_in_for;
- public boolean insert_space_after_unary_operator;
- public boolean insert_space_before_at_in_annotation_type_declaration;
- public boolean insert_space_before_assignment_operator;
- public boolean insert_space_before_binary_operator;
- public boolean insert_space_before_closing_angle_bracket_in_parameterized_type_reference;
- public boolean insert_space_before_closing_angle_bracket_in_type_arguments;
- public boolean insert_space_before_closing_angle_bracket_in_type_parameters;
- public boolean insert_space_before_closing_brace_in_array_initializer;
- public boolean insert_space_before_closing_bracket_in_array_allocation_expression;
- public boolean insert_space_before_closing_bracket_in_array_reference;
- public boolean insert_space_before_closing_paren_in_annotation;
- public boolean insert_space_before_closing_paren_in_cast;
- public boolean insert_space_before_closing_paren_in_catch;
- public boolean insert_space_before_closing_paren_in_constructor_declaration;
- public boolean insert_space_before_closing_paren_in_enum_constant;
- public boolean insert_space_before_closing_paren_in_for;
- public boolean insert_space_before_closing_paren_in_if;
- public boolean insert_space_before_closing_paren_in_method_declaration;
- public boolean insert_space_before_closing_paren_in_method_invocation;
- public boolean insert_space_before_closing_paren_in_parenthesized_expression;
- public boolean insert_space_before_closing_paren_in_switch;
- public boolean insert_space_before_closing_paren_in_synchronized;
- public boolean insert_space_before_closing_paren_in_while;
- public boolean insert_space_before_colon_in_assert;
- public boolean insert_space_before_colon_in_case;
- public boolean insert_space_before_colon_in_conditional;
- public boolean insert_space_before_colon_in_object_initializer;
- public boolean insert_space_before_colon_in_default;
- public boolean insert_space_before_colon_in_for;
- public boolean insert_space_before_colon_in_labeled_statement;
- public boolean insert_space_before_comma_in_allocation_expression;
- public boolean insert_space_before_comma_in_annotation;
- public boolean insert_space_before_comma_in_array_initializer;
- public boolean insert_space_before_comma_in_constructor_declaration_parameters;
- public boolean insert_space_before_comma_in_constructor_declaration_throws;
- public boolean insert_space_before_comma_in_enum_constant_arguments;
- public boolean insert_space_before_comma_in_enum_declarations;
- public boolean insert_space_before_comma_in_explicit_constructor_call_arguments;
- public boolean insert_space_before_comma_in_for_increments;
- public boolean insert_space_before_comma_in_for_inits;
- public boolean insert_space_before_comma_in_method_invocation_arguments;
- public boolean insert_space_before_comma_in_method_declaration_parameters;
- public boolean insert_space_before_comma_in_method_declaration_throws;
- public boolean insert_space_before_comma_in_multiple_field_declarations;
- public boolean insert_space_before_comma_in_multiple_local_declarations;
- public boolean insert_space_before_comma_in_parameterized_type_reference;
- public boolean insert_space_before_comma_in_superinterfaces;
- public boolean insert_space_before_comma_in_type_arguments;
- public boolean insert_space_before_comma_in_type_parameters;
- public boolean insert_space_before_ellipsis;
- public boolean insert_space_before_parenthesized_expression_in_return;
- public boolean insert_space_before_parenthesized_expression_in_throw;
- public boolean insert_space_before_opening_angle_bracket_in_parameterized_type_reference;
- public boolean insert_space_before_opening_angle_bracket_in_type_arguments;
- public boolean insert_space_before_opening_angle_bracket_in_type_parameters;
- public boolean insert_space_before_opening_brace_in_annotation_type_declaration;
- public boolean insert_space_before_opening_brace_in_anonymous_type_declaration;
- public boolean insert_space_before_opening_brace_in_block;
- public boolean insert_space_before_opening_brace_in_constructor_declaration;
- public boolean insert_space_before_opening_brace_in_enum_constant;
- public boolean insert_space_before_opening_brace_in_enum_declaration;
- public boolean insert_space_before_opening_brace_in_method_declaration;
- public boolean insert_space_before_opening_brace_in_type_declaration;
- public boolean insert_space_before_opening_bracket_in_array_allocation_expression;
- public boolean insert_space_before_opening_bracket_in_array_reference;
- public boolean insert_space_before_opening_bracket_in_array_type_reference;
- public boolean insert_space_before_opening_paren_in_annotation;
- public boolean insert_space_before_opening_paren_in_annotation_type_member_declaration;
- public boolean insert_space_before_opening_paren_in_catch;
- public boolean insert_space_before_opening_paren_in_constructor_declaration;
- public boolean insert_space_before_opening_paren_in_enum_constant;
- public boolean insert_space_before_opening_paren_in_for;
- public boolean insert_space_before_opening_paren_in_if;
- public boolean insert_space_before_opening_paren_in_method_invocation;
- public boolean insert_space_before_opening_paren_in_method_declaration;
- public boolean insert_space_before_opening_paren_in_switch;
- public boolean insert_space_before_opening_brace_in_switch;
- public boolean insert_space_before_opening_paren_in_synchronized;
- public boolean insert_space_before_opening_paren_in_parenthesized_expression;
- public boolean insert_space_before_opening_paren_in_while;
- public boolean insert_space_before_postfix_operator;
- public boolean insert_space_before_prefix_operator;
- public boolean insert_space_before_question_in_conditional;
- public boolean insert_space_before_semicolon;
- public boolean insert_space_before_semicolon_in_for;
- public boolean insert_space_before_unary_operator;
- public boolean insert_space_between_brackets_in_array_type_reference;
- public boolean insert_space_between_empty_braces_in_array_initializer;
- public boolean insert_space_between_empty_brackets_in_array_allocation_expression;
- public boolean insert_space_between_empty_parens_in_annotation_type_member_declaration;
- public boolean insert_space_between_empty_parens_in_constructor_declaration;
- public boolean insert_space_between_empty_parens_in_enum_constant;
- public boolean insert_space_between_empty_parens_in_method_declaration;
- public boolean insert_space_between_empty_parens_in_method_invocation;
- public boolean compact_else_if;
- public boolean keep_guardian_clause_on_one_line;
- public boolean keep_else_statement_on_same_line;
- public boolean keep_empty_array_initializer_on_one_line;
- public boolean keep_empty_objlit_initializer_on_one_line;
- public boolean keep_simple_if_on_one_line;
- public boolean keep_then_statement_on_same_line;
- public boolean never_indent_block_comments_on_first_column;
- public boolean never_indent_line_comments_on_first_column;
- public int number_of_empty_lines_to_preserve;
- public boolean put_empty_statement_on_new_line;
- public int tab_size;
- public final char filling_space = ' ';
- public int page_width;
- public int tab_char;
- public boolean use_tabs_only_for_leading_indentations;
- public boolean wrap_before_binary_operator;
-
- public int initial_indentation_level;
- public String line_separator;
-
- private DefaultCodeFormatterOptions() {
- // cannot be instantiated
- }
-
- public DefaultCodeFormatterOptions(Map settings) {
- setDefaultSettings();
- if (settings == null) return;
- set(settings);
- }
-
- private String getAlignment(int alignment) {
- return Integer.toString(alignment);
- }
-
- public Map getMap() {
- Map options = new HashMap();
- options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_ALLOCATION_EXPRESSION, getAlignment(this.alignment_for_arguments_in_allocation_expression));
- options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_ENUM_CONSTANT, getAlignment(this.alignment_for_arguments_in_enum_constant));
- options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_EXPLICIT_CONSTRUCTOR_CALL, getAlignment(this.alignment_for_arguments_in_explicit_constructor_call));
- options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION, getAlignment(this.alignment_for_arguments_in_method_invocation));
- options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_QUALIFIED_ALLOCATION_EXPRESSION, getAlignment(this.alignment_for_arguments_in_qualified_allocation_expression));
- options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ASSIGNMENT, getAlignment(this.alignment_for_assignment));
- options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_BINARY_EXPRESSION, getAlignment(this.alignment_for_binary_expression));
- options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_COMPACT_IF, getAlignment(this.alignment_for_compact_if));
- options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_CONDITIONAL_EXPRESSION, getAlignment(this.alignment_for_conditional_expression));
- options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ENUM_CONSTANTS, getAlignment(this.alignment_for_enum_constants));
- options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_ARRAY_INITIALIZER, getAlignment(this.alignment_for_expressions_in_array_initializer));
- options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_MULTIPLE_FIELDS, getAlignment(this.alignment_for_multiple_fields));
- options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_CONSTRUCTOR_DECLARATION, getAlignment(this.alignment_for_parameters_in_constructor_declaration));
- options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION, getAlignment(this.alignment_for_parameters_in_method_declaration));
- options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SELECTOR_IN_METHOD_INVOCATION, getAlignment(this.alignment_for_selector_in_method_invocation));
- options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SUPERCLASS_IN_TYPE_DECLARATION, getAlignment(this.alignment_for_superclass_in_type_declaration));
- options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SUPERINTERFACES_IN_ENUM_DECLARATION, getAlignment(this.alignment_for_superinterfaces_in_enum_declaration));
- options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SUPERINTERFACES_IN_TYPE_DECLARATION, getAlignment(this.alignment_for_superinterfaces_in_type_declaration));
- options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_THROWS_CLAUSE_IN_CONSTRUCTOR_DECLARATION, getAlignment(this.alignment_for_throws_clause_in_constructor_declaration));
- options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_THROWS_CLAUSE_IN_METHOD_DECLARATION, getAlignment(this.alignment_for_throws_clause_in_method_declaration));
- options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGN_TYPE_MEMBERS_ON_COLUMNS, this.align_type_members_on_columns ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
- options.put(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ANNOTATION_TYPE_DECLARATION, this.brace_position_for_annotation_type_declaration);
- options.put(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ANONYMOUS_TYPE_DECLARATION, this.brace_position_for_anonymous_type_declaration);
- options.put(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ARRAY_INITIALIZER, this.brace_position_for_array_initializer);
- options.put(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_OBJLIT_INITIALIZER, this.brace_position_for_objlit_initializer);
- options.put(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_BLOCK, this.brace_position_for_block);
- options.put(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_BLOCK_IN_CASE, this.brace_position_for_block_in_case);
- options.put(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_CONSTRUCTOR_DECLARATION, this.brace_position_for_constructor_declaration);
- options.put(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ENUM_CONSTANT, this.brace_position_for_enum_constant);
- options.put(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ENUM_DECLARATION, this.brace_position_for_enum_declaration);
- options.put(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION, this.brace_position_for_method_declaration);
- options.put(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_TYPE_DECLARATION, this.brace_position_for_type_declaration);
- options.put(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_SWITCH, this.brace_position_for_switch);
- options.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_CLEAR_BLANK_LINES_IN_BLOCK_COMMENT, this.comment_clear_blank_lines_in_javadoc_comment ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
- options.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_CLEAR_BLANK_LINES_IN_JAVADOC_COMMENT, this.comment_clear_blank_lines_in_block_comment ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
- options.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_JAVADOC_COMMENT, this.comment_format_javadoc_comment ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
- options.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_LINE_COMMENT, this.comment_format_line_comment ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
- options.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_BLOCK_COMMENT, this.comment_format_block_comment ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
- options.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_HEADER, this.comment_format_header ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
- options.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_HTML, this.comment_format_html ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
- options.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_SOURCE, this.comment_format_source ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
- options.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_INDENT_PARAMETER_DESCRIPTION, this.comment_indent_parameter_description ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
- options.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_INDENT_ROOT_TAGS, this.comment_indent_root_tags ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
- options.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_INSERT_EMPTY_LINE_BEFORE_ROOT_TAGS, this.comment_insert_empty_line_before_root_tags ? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_INSERT_NEW_LINE_FOR_PARAMETER, this.comment_insert_new_line_for_parameter ? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_LINE_LENGTH, Integer.toString(this.comment_line_length));
- options.put(DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION, Integer.toString(this.continuation_indentation));
- options.put(DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION_FOR_ARRAY_INITIALIZER, Integer.toString(this.continuation_indentation_for_array_initializer));
- options.put(DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION_FOR_OBJLIT_INITIALIZER, Integer.toString(this.continuation_indentation_for_objlit_initializer));
- options.put(DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_AFTER_IMPORTS, Integer.toString(this.blank_lines_after_imports));
- options.put(DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_AFTER_PACKAGE, Integer.toString(this.blank_lines_after_package));
- options.put(DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_BEFORE_FIELD, Integer.toString(this.blank_lines_before_field));
- options.put(DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_BEFORE_FIRST_CLASS_BODY_DECLARATION, Integer.toString(this.blank_lines_before_first_class_body_declaration));
- options.put(DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_BEFORE_IMPORTS, Integer.toString(this.blank_lines_before_imports));
- options.put(DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_BEFORE_MEMBER_TYPE, Integer.toString(this.blank_lines_before_member_type));
- options.put(DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_BEFORE_METHOD, Integer.toString(this.blank_lines_before_method));
- options.put(DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_BEFORE_NEW_CHUNK, Integer.toString(this.blank_lines_before_new_chunk));
- options.put(DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_BEFORE_PACKAGE, Integer.toString(this.blank_lines_before_package));
- options.put(DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_BETWEEN_IMPORT_GROUPS, Integer.toString(this.blank_lines_between_import_groups));
- options.put(DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_BETWEEN_TYPE_DECLARATIONS, Integer.toString(this.blank_lines_between_type_declarations));
- options.put(DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_AT_BEGINNING_OF_METHOD_BODY, Integer.toString(this.blank_lines_at_beginning_of_method_body));
- options.put(DefaultCodeFormatterConstants.FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BLOCK, this.indent_statements_compare_to_block ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BODY, this.indent_statements_compare_to_body ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ANNOTATION_DECLARATION_HEADER, this.indent_body_declarations_compare_to_annotation_declaration_header ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ENUM_CONSTANT_HEADER, this.indent_body_declarations_compare_to_enum_constant_header ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ENUM_DECLARATION_HEADER, this.indent_body_declarations_compare_to_enum_declaration_header ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_TYPE_HEADER, this.indent_body_declarations_compare_to_type_header ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INDENT_BREAKS_COMPARE_TO_CASES, this.indent_breaks_compare_to_cases ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INDENT_EMPTY_LINES, this.indent_empty_lines ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_CASES, this.indent_switchstatements_compare_to_cases ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_SWITCH, this.indent_switchstatements_compare_to_switch ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INDENTATION_SIZE, Integer.toString(this.indentation_size));
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_AFTER_ANNOTATION, this.insert_new_line_after_annotation ? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_AFTER_OPENING_BRACE_IN_ARRAY_INITIALIZER, this.insert_new_line_after_opening_brace_in_array_initializer? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_AFTER_OPENING_BRACE_IN_OBJLIT_INITIALIZER, this.insert_new_line_after_opening_brace_in_objlit_initializer? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_AFTER_COMMA_IN_OBJLIT_INITIALIZER, this.insert_new_line_after_comma_in_objlit_initializer? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_AT_END_OF_FILE_IF_MISSING, this.insert_new_line_at_end_of_file_if_missing ? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_BEFORE_CATCH_IN_TRY_STATEMENT, this.insert_new_line_before_catch_in_try_statement? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_BEFORE_CLOSING_BRACE_IN_ARRAY_INITIALIZER, this.insert_new_line_before_closing_brace_in_array_initializer? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_BEFORE_CLOSING_BRACE_IN_OBJLIT_INITIALIZER, this.insert_new_line_before_closing_brace_in_objlit_initializer? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_BEFORE_ELSE_IN_IF_STATEMENT, this.insert_new_line_before_else_in_if_statement? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_BEFORE_FINALLY_IN_TRY_STATEMENT, this.insert_new_line_before_finally_in_try_statement? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_BEFORE_WHILE_IN_DO_STATEMENT, this.insert_new_line_before_while_in_do_statement? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_IN_EMPTY_ANONYMOUS_TYPE_DECLARATION, this.insert_new_line_in_empty_anonymous_type_declaration? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_IN_EMPTY_BLOCK, this.insert_new_line_in_empty_block? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_IN_EMPTY_ANNOTATION_DECLARATION, this.insert_new_line_in_empty_annotation_declaration ? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_IN_EMPTY_ENUM_CONSTANT, this.insert_new_line_in_empty_enum_constant? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_IN_EMPTY_ENUM_DECLARATION, this.insert_new_line_in_empty_enum_declaration? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_IN_EMPTY_METHOD_BODY, this.insert_new_line_in_empty_method_body? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_IN_EMPTY_TYPE_DECLARATION, this.insert_new_line_in_empty_type_declaration? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_AND_IN_TYPE_PARAMETER, this.insert_space_after_and_in_type_parameter? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_ASSIGNMENT_OPERATOR, this.insert_space_after_assignment_operator? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_AT_IN_ANNOTATION, this.insert_space_after_at_in_annotation? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_AT_IN_ANNOTATION_TYPE_DECLARATION, this.insert_space_after_at_in_annotation_type_declaration ? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_BINARY_OPERATOR, this.insert_space_after_binary_operator? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_CLOSING_ANGLE_BRACKET_IN_TYPE_ARGUMENTS, this.insert_space_after_closing_angle_bracket_in_type_arguments ? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_CLOSING_ANGLE_BRACKET_IN_TYPE_PARAMETERS, this.insert_space_after_closing_angle_bracket_in_type_parameters ? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_CLOSING_PAREN_IN_CAST, this.insert_space_after_closing_paren_in_cast? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_CLOSING_BRACE_IN_BLOCK, this.insert_space_after_closing_brace_in_block? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COLON_IN_ASSERT, this.insert_space_after_colon_in_assert ? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COLON_IN_CASE, this.insert_space_after_colon_in_case ? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COLON_IN_CONDITIONAL, this.insert_space_after_colon_in_conditional ? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COLON_IN_OBJECT_INITIALIZER, this.insert_space_after_colon_in_object_initializer ? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COLON_IN_FOR, this.insert_space_after_colon_in_for ? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COLON_IN_LABELED_STATEMENT, this.insert_space_after_colon_in_labeled_statement? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_ALLOCATION_EXPRESSION, this.insert_space_after_comma_in_allocation_expression? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_ANNOTATION, this.insert_space_after_comma_in_annotation? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_ARRAY_INITIALIZER, this.insert_space_after_comma_in_array_initializer? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_CONSTRUCTOR_DECLARATION_PARAMETERS, this.insert_space_after_comma_in_constructor_declaration_parameters? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_CONSTRUCTOR_DECLARATION_THROWS, this.insert_space_after_comma_in_constructor_declaration_throws? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_ENUM_CONSTANT_ARGUMENTS, this.insert_space_after_comma_in_enum_constant_arguments ? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_ENUM_DECLARATIONS, this.insert_space_after_comma_in_enum_declarations ? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_EXPLICIT_CONSTRUCTOR_CALL_ARGUMENTS, this.insert_space_after_comma_in_explicit_constructor_call_arguments? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_FOR_INCREMENTS, this.insert_space_after_comma_in_for_increments? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_FOR_INITS, this.insert_space_after_comma_in_for_inits? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_METHOD_INVOCATION_ARGUMENTS, this.insert_space_after_comma_in_method_invocation_arguments? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_METHOD_DECLARATION_PARAMETERS, this.insert_space_after_comma_in_method_declaration_parameters? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_METHOD_DECLARATION_THROWS, this.insert_space_after_comma_in_method_declaration_throws? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_MULTIPLE_FIELD_DECLARATIONS, this.insert_space_after_comma_in_multiple_field_declarations? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_MULTIPLE_LOCAL_DECLARATIONS, this.insert_space_after_comma_in_multiple_local_declarations? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_PARAMETERIZED_TYPE_REFERENCE, this.insert_space_after_comma_in_parameterized_type_reference? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_SUPERINTERFACES, this.insert_space_after_comma_in_superinterfaces? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_TYPE_ARGUMENTS, this.insert_space_after_comma_in_type_arguments ? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_TYPE_PARAMETERS, this.insert_space_after_comma_in_type_parameters ? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_BRACKET_IN_ARRAY_ALLOCATION_EXPRESSION, this.insert_space_after_opening_bracket_in_array_allocation_expression? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_ELLIPSIS, this.insert_space_after_ellipsis ? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_ANGLE_BRACKET_IN_PARAMETERIZED_TYPE_REFERENCE, this.insert_space_after_opening_angle_bracket_in_parameterized_type_reference? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_ANGLE_BRACKET_IN_TYPE_ARGUMENTS, this.insert_space_after_opening_angle_bracket_in_type_arguments? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_ANGLE_BRACKET_IN_TYPE_PARAMETERS, this.insert_space_after_opening_angle_bracket_in_type_parameters? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_BRACKET_IN_ARRAY_REFERENCE, this.insert_space_after_opening_bracket_in_array_reference? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_BRACE_IN_ARRAY_INITIALIZER, this.insert_space_after_opening_brace_in_array_initializer? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_ANNOTATION, this.insert_space_after_opening_paren_in_annotation? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_CAST, this.insert_space_after_opening_paren_in_cast? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_CATCH, this.insert_space_after_opening_paren_in_catch? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_CONSTRUCTOR_DECLARATION, this.insert_space_after_opening_paren_in_constructor_declaration? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_ENUM_CONSTANT, this.insert_space_after_opening_paren_in_enum_constant? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_FOR, this.insert_space_after_opening_paren_in_for? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_IF, this.insert_space_after_opening_paren_in_if? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_METHOD_DECLARATION, this.insert_space_after_opening_paren_in_method_declaration? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_METHOD_INVOCATION, this.insert_space_after_opening_paren_in_method_invocation? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_PARENTHESIZED_EXPRESSION, this.insert_space_after_opening_paren_in_parenthesized_expression? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_SWITCH, this.insert_space_after_opening_paren_in_switch? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_SYNCHRONIZED, this.insert_space_after_opening_paren_in_synchronized? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_WHILE, this.insert_space_after_opening_paren_in_while? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_POSTFIX_OPERATOR, this.insert_space_after_postfix_operator? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_PREFIX_OPERATOR, this.insert_space_after_prefix_operator? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_QUESTION_IN_CONDITIONAL, this.insert_space_after_question_in_conditional? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_SEMICOLON_IN_FOR, this.insert_space_after_semicolon_in_for? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_UNARY_OPERATOR, this.insert_space_after_unary_operator? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_AT_IN_ANNOTATION_TYPE_DECLARATION, this.insert_space_before_at_in_annotation_type_declaration ? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_ASSIGNMENT_OPERATOR, this.insert_space_before_assignment_operator? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_BINARY_OPERATOR, this.insert_space_before_binary_operator? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_ANGLE_BRACKET_IN_PARAMETERIZED_TYPE_REFERENCE, this.insert_space_before_closing_angle_bracket_in_parameterized_type_reference? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_ANGLE_BRACKET_IN_TYPE_ARGUMENTS, this.insert_space_before_closing_angle_bracket_in_type_arguments? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_ANGLE_BRACKET_IN_TYPE_PARAMETERS, this.insert_space_before_closing_angle_bracket_in_type_parameters? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_BRACE_IN_ARRAY_INITIALIZER, this.insert_space_before_closing_brace_in_array_initializer? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_BRACKET_IN_ARRAY_ALLOCATION_EXPRESSION, this.insert_space_before_closing_bracket_in_array_allocation_expression? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_BRACKET_IN_ARRAY_REFERENCE, this.insert_space_before_closing_bracket_in_array_reference? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_ANNOTATION, this.insert_space_before_closing_paren_in_annotation? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_CAST, this.insert_space_before_closing_paren_in_cast? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_CATCH, this.insert_space_before_closing_paren_in_catch? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_CONSTRUCTOR_DECLARATION, this.insert_space_before_closing_paren_in_constructor_declaration? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_ENUM_CONSTANT, this.insert_space_before_closing_paren_in_enum_constant? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_FOR, this.insert_space_before_closing_paren_in_for? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_IF, this.insert_space_before_closing_paren_in_if? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_METHOD_DECLARATION, this.insert_space_before_closing_paren_in_method_declaration? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_METHOD_INVOCATION, this.insert_space_before_closing_paren_in_method_invocation? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_PARENTHESIZED_EXPRESSION, this.insert_space_before_closing_paren_in_parenthesized_expression? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_SWITCH, this.insert_space_before_closing_paren_in_switch? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_SYNCHRONIZED, this.insert_space_before_closing_paren_in_synchronized? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_WHILE, this.insert_space_before_closing_paren_in_while? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_ASSERT, this.insert_space_before_colon_in_assert? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_CASE, this.insert_space_before_colon_in_case? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_CONDITIONAL, this.insert_space_before_colon_in_conditional? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_OBJECT_INITIALIZER, this.insert_space_before_colon_in_object_initializer? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_DEFAULT, this.insert_space_before_colon_in_default? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_FOR, this.insert_space_before_colon_in_for ? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_LABELED_STATEMENT, this.insert_space_before_colon_in_labeled_statement? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_ALLOCATION_EXPRESSION, this.insert_space_before_comma_in_allocation_expression? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_ANNOTATION, this.insert_space_before_comma_in_annotation? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_ARRAY_INITIALIZER, this.insert_space_before_comma_in_array_initializer? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_CONSTRUCTOR_DECLARATION_PARAMETERS, this.insert_space_before_comma_in_constructor_declaration_parameters? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_CONSTRUCTOR_DECLARATION_THROWS, this.insert_space_before_comma_in_constructor_declaration_throws? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_ENUM_CONSTANT_ARGUMENTS, this.insert_space_before_comma_in_enum_constant_arguments? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_ENUM_DECLARATIONS, this.insert_space_before_comma_in_enum_declarations? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_EXPLICIT_CONSTRUCTOR_CALL_ARGUMENTS, this.insert_space_before_comma_in_explicit_constructor_call_arguments? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_FOR_INCREMENTS, this.insert_space_before_comma_in_for_increments? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_FOR_INITS, this.insert_space_before_comma_in_for_inits? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_METHOD_INVOCATION_ARGUMENTS, this.insert_space_before_comma_in_method_invocation_arguments? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_METHOD_DECLARATION_PARAMETERS, this.insert_space_before_comma_in_method_declaration_parameters? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_METHOD_DECLARATION_THROWS, this.insert_space_before_comma_in_method_declaration_throws? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_MULTIPLE_FIELD_DECLARATIONS, this.insert_space_before_comma_in_multiple_field_declarations? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_MULTIPLE_LOCAL_DECLARATIONS, this.insert_space_before_comma_in_multiple_local_declarations? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_SUPERINTERFACES, this.insert_space_before_comma_in_superinterfaces? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_TYPE_ARGUMENTS, this.insert_space_before_comma_in_type_arguments ? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_TYPE_PARAMETERS, this.insert_space_before_comma_in_type_parameters? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_PARAMETERIZED_TYPE_REFERENCE, this.insert_space_before_comma_in_parameterized_type_reference? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_ELLIPSIS, this.insert_space_before_ellipsis ? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_ANGLE_BRACKET_IN_PARAMETERIZED_TYPE_REFERENCE, this.insert_space_before_opening_angle_bracket_in_parameterized_type_reference? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_ANGLE_BRACKET_IN_TYPE_ARGUMENTS, this.insert_space_before_opening_angle_bracket_in_type_arguments? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_ANGLE_BRACKET_IN_TYPE_PARAMETERS, this.insert_space_before_opening_angle_bracket_in_type_parameters? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_ANNOTATION_TYPE_DECLARATION, this.insert_space_before_opening_brace_in_annotation_type_declaration ? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_ANONYMOUS_TYPE_DECLARATION, this.insert_space_before_opening_brace_in_anonymous_type_declaration? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_BLOCK, this.insert_space_before_opening_brace_in_block? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_CONSTRUCTOR_DECLARATION, this.insert_space_before_opening_brace_in_constructor_declaration? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_ENUM_CONSTANT, this.insert_space_before_opening_brace_in_enum_constant? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_ENUM_DECLARATION, this.insert_space_before_opening_brace_in_enum_declaration? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_METHOD_DECLARATION, this.insert_space_before_opening_brace_in_method_declaration? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_TYPE_DECLARATION, this.insert_space_before_opening_brace_in_type_declaration? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACKET_IN_ARRAY_ALLOCATION_EXPRESSION, this.insert_space_before_opening_bracket_in_array_allocation_expression ? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACKET_IN_ARRAY_REFERENCE, this.insert_space_before_opening_bracket_in_array_reference? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACKET_IN_ARRAY_TYPE_REFERENCE, this.insert_space_before_opening_bracket_in_array_type_reference? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_ANNOTATION, this.insert_space_before_opening_paren_in_annotation? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_ANNOTATION_TYPE_MEMBER_DECLARATION, this.insert_space_before_opening_paren_in_annotation_type_member_declaration ? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_CATCH, this.insert_space_before_opening_paren_in_catch? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_CONSTRUCTOR_DECLARATION, this.insert_space_before_opening_paren_in_constructor_declaration? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_ENUM_CONSTANT, this.insert_space_before_opening_paren_in_enum_constant? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_FOR, this.insert_space_before_opening_paren_in_for? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_IF, this.insert_space_before_opening_paren_in_if? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_METHOD_INVOCATION, this.insert_space_before_opening_paren_in_method_invocation? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_METHOD_DECLARATION, this.insert_space_before_opening_paren_in_method_declaration? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_SWITCH, this.insert_space_before_opening_paren_in_switch? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_SWITCH, this.insert_space_before_opening_brace_in_switch? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_SYNCHRONIZED, this.insert_space_before_opening_paren_in_synchronized? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_PARENTHESIZED_EXPRESSION, this.insert_space_before_opening_paren_in_parenthesized_expression? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_WHILE, this.insert_space_before_opening_paren_in_while? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_PARENTHESIZED_EXPRESSION_IN_RETURN, this.insert_space_before_parenthesized_expression_in_return ? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_PARENTHESIZED_EXPRESSION_IN_THROW, this.insert_space_before_parenthesized_expression_in_throw ? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_POSTFIX_OPERATOR, this.insert_space_before_postfix_operator? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_PREFIX_OPERATOR, this.insert_space_before_prefix_operator? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_QUESTION_IN_CONDITIONAL, this.insert_space_before_question_in_conditional? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_SEMICOLON, this.insert_space_before_semicolon? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_SEMICOLON_IN_FOR, this.insert_space_before_semicolon_in_for? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_UNARY_OPERATOR, this.insert_space_before_unary_operator? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_BRACKETS_IN_ARRAY_TYPE_REFERENCE, this.insert_space_between_brackets_in_array_type_reference? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_BRACES_IN_ARRAY_INITIALIZER, this.insert_space_between_empty_braces_in_array_initializer? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_BRACKETS_IN_ARRAY_ALLOCATION_EXPRESSION, this.insert_space_between_empty_brackets_in_array_allocation_expression? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_ANNOTATION_TYPE_MEMBER_DECLARATION, this.insert_space_between_empty_parens_in_annotation_type_member_declaration? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_CONSTRUCTOR_DECLARATION, this.insert_space_between_empty_parens_in_constructor_declaration? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_ENUM_CONSTANT, this.insert_space_between_empty_parens_in_enum_constant? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_METHOD_DECLARATION, this.insert_space_between_empty_parens_in_method_declaration? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_METHOD_INVOCATION, this.insert_space_between_empty_parens_in_method_invocation? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- options.put(DefaultCodeFormatterConstants.FORMATTER_COMPACT_ELSE_IF, this.compact_else_if ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
- options.put(DefaultCodeFormatterConstants.FORMATTER_KEEP_GUARDIAN_CLAUSE_ON_ONE_LINE, this.keep_guardian_clause_on_one_line ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
- options.put(DefaultCodeFormatterConstants.FORMATTER_KEEP_ELSE_STATEMENT_ON_SAME_LINE, this.keep_else_statement_on_same_line ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
- options.put(DefaultCodeFormatterConstants.FORMATTER_KEEP_EMPTY_ARRAY_INITIALIZER_ON_ONE_LINE, this.keep_empty_array_initializer_on_one_line ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
- options.put(DefaultCodeFormatterConstants.FORMATTER_KEEP_EMPTY_OBJLIT_INITIALIZER_ON_ONE_LINE, this.keep_empty_objlit_initializer_on_one_line ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
- options.put(DefaultCodeFormatterConstants.FORMATTER_KEEP_SIMPLE_IF_ON_ONE_LINE, this.keep_simple_if_on_one_line ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
- options.put(DefaultCodeFormatterConstants.FORMATTER_KEEP_THEN_STATEMENT_ON_SAME_LINE, this.keep_then_statement_on_same_line ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
- options.put(DefaultCodeFormatterConstants.FORMATTER_NEVER_INDENT_BLOCK_COMMENTS_ON_FIRST_COLUMN, this.never_indent_block_comments_on_first_column ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
- options.put(DefaultCodeFormatterConstants.FORMATTER_NEVER_INDENT_LINE_COMMENTS_ON_FIRST_COLUMN, this.never_indent_line_comments_on_first_column ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
- options.put(DefaultCodeFormatterConstants.FORMATTER_NUMBER_OF_EMPTY_LINES_TO_PRESERVE, Integer.toString(this.number_of_empty_lines_to_preserve));
- options.put(DefaultCodeFormatterConstants.FORMATTER_PUT_EMPTY_STATEMENT_ON_NEW_LINE, this.put_empty_statement_on_new_line ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
- options.put(DefaultCodeFormatterConstants.FORMATTER_LINE_SPLIT, Integer.toString(this.page_width));
- switch(this.tab_char) {
- case SPACE :
- options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaScriptCore.SPACE);
- break;
- case TAB :
- options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaScriptCore.TAB);
- break;
- case MIXED :
- options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, DefaultCodeFormatterConstants.MIXED);
- break;
- }
- options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, Integer.toString(this.tab_size));
- options.put(DefaultCodeFormatterConstants.FORMATTER_USE_TABS_ONLY_FOR_LEADING_INDENTATIONS, this.use_tabs_only_for_leading_indentations ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
- options.put(DefaultCodeFormatterConstants.FORMATTER_WRAP_BEFORE_BINARY_OPERATOR, this.wrap_before_binary_operator ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE);
- return options;
- }
-
- public void set(Map settings) {
- final Object alignmentForArgumentsInAllocationExpressionOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_ALLOCATION_EXPRESSION);
- if (alignmentForArgumentsInAllocationExpressionOption != null) {
- try {
- this.alignment_for_arguments_in_allocation_expression = Integer.parseInt((String) alignmentForArgumentsInAllocationExpressionOption);
- } catch (NumberFormatException e) {
- this.alignment_for_arguments_in_allocation_expression = Alignment.M_COMPACT_SPLIT;
- } catch (ClassCastException e) {
- this.alignment_for_arguments_in_allocation_expression = Alignment.M_COMPACT_SPLIT;
- }
- }
- final Object alignmentForArgumentsInEnumConstantOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_ENUM_CONSTANT);
- if (alignmentForArgumentsInEnumConstantOption != null) {
- try {
- this.alignment_for_arguments_in_enum_constant = Integer.parseInt((String) alignmentForArgumentsInEnumConstantOption);
- } catch (NumberFormatException e) {
- this.alignment_for_arguments_in_enum_constant = Alignment.M_COMPACT_SPLIT;
- } catch (ClassCastException e) {
- this.alignment_for_arguments_in_enum_constant = Alignment.M_COMPACT_SPLIT;
- }
- }
- final Object alignmentForArgumentsInExplicitConstructorCallOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_EXPLICIT_CONSTRUCTOR_CALL);
- if (alignmentForArgumentsInExplicitConstructorCallOption != null) {
- try {
- this.alignment_for_arguments_in_explicit_constructor_call = Integer.parseInt((String) alignmentForArgumentsInExplicitConstructorCallOption);
- } catch (NumberFormatException e) {
- this.alignment_for_arguments_in_explicit_constructor_call = Alignment.M_COMPACT_SPLIT;
- } catch (ClassCastException e) {
- this.alignment_for_arguments_in_explicit_constructor_call = Alignment.M_COMPACT_SPLIT;
- }
- }
- final Object alignmentForArgumentsInMethodInvocationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION);
- if (alignmentForArgumentsInMethodInvocationOption != null) {
- try {
- this.alignment_for_arguments_in_method_invocation = Integer.parseInt((String) alignmentForArgumentsInMethodInvocationOption);
- } catch (NumberFormatException e) {
- this.alignment_for_arguments_in_method_invocation = Alignment.M_COMPACT_SPLIT;
- } catch (ClassCastException e) {
- this.alignment_for_arguments_in_method_invocation = Alignment.M_COMPACT_SPLIT;
- }
- }
- final Object alignmentForArgumentsInQualifiedAllocationExpressionOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_QUALIFIED_ALLOCATION_EXPRESSION);
- if (alignmentForArgumentsInQualifiedAllocationExpressionOption != null) {
- try {
- this.alignment_for_arguments_in_qualified_allocation_expression = Integer.parseInt((String) alignmentForArgumentsInQualifiedAllocationExpressionOption);
- } catch (NumberFormatException e) {
- this.alignment_for_arguments_in_qualified_allocation_expression = Alignment.M_COMPACT_SPLIT;
- } catch (ClassCastException e) {
- this.alignment_for_arguments_in_qualified_allocation_expression = Alignment.M_COMPACT_SPLIT;
- }
- }
- final Object alignmentForAssignmentOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ASSIGNMENT);
- if (alignmentForAssignmentOption != null) {
- try {
- this.alignment_for_assignment = Integer.parseInt((String) alignmentForAssignmentOption);
- } catch (NumberFormatException e) {
- this.alignment_for_assignment = Alignment.M_ONE_PER_LINE_SPLIT;
- } catch (ClassCastException e) {
- this.alignment_for_assignment = Alignment.M_ONE_PER_LINE_SPLIT;
- }
- }
- final Object alignmentForBinaryExpressionOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_BINARY_EXPRESSION);
- if (alignmentForBinaryExpressionOption != null) {
- try {
- this.alignment_for_binary_expression = Integer.parseInt((String) alignmentForBinaryExpressionOption);
- } catch (NumberFormatException e) {
- this.alignment_for_binary_expression = Alignment.M_COMPACT_SPLIT;
- } catch (ClassCastException e) {
- this.alignment_for_binary_expression = Alignment.M_COMPACT_SPLIT;
- }
- }
- final Object alignmentForCompactIfOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_COMPACT_IF);
- if (alignmentForCompactIfOption != null) {
- try {
- this.alignment_for_compact_if = Integer.parseInt((String) alignmentForCompactIfOption);
- } catch (NumberFormatException e) {
- this.alignment_for_compact_if = Alignment.M_ONE_PER_LINE_SPLIT | Alignment.M_INDENT_BY_ONE;
- } catch (ClassCastException e) {
- this.alignment_for_compact_if = Alignment.M_ONE_PER_LINE_SPLIT | Alignment.M_INDENT_BY_ONE;
- }
- }
- final Object alignmentForConditionalExpressionOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_CONDITIONAL_EXPRESSION);
- if (alignmentForConditionalExpressionOption != null) {
- try {
- this.alignment_for_conditional_expression = Integer.parseInt((String) alignmentForConditionalExpressionOption);
- } catch (NumberFormatException e) {
- this.alignment_for_conditional_expression = Alignment.M_ONE_PER_LINE_SPLIT;
- } catch (ClassCastException e) {
- this.alignment_for_conditional_expression = Alignment.M_ONE_PER_LINE_SPLIT;
- }
- }
- final Object alignmentForEnumConstantsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ENUM_CONSTANTS);
- if (alignmentForEnumConstantsOption != null) {
- try {
- this.alignment_for_enum_constants = Integer.parseInt((String) alignmentForEnumConstantsOption);
- } catch (NumberFormatException e) {
- this.alignment_for_enum_constants = Alignment.NONE;
- } catch (ClassCastException e) {
- this.alignment_for_enum_constants = Alignment.NONE;
- }
- }
- final Object alignmentForExpressionsInArrayInitializerOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_ARRAY_INITIALIZER);
- if (alignmentForExpressionsInArrayInitializerOption != null) {
- try {
- this.alignment_for_expressions_in_array_initializer = Integer.parseInt((String) alignmentForExpressionsInArrayInitializerOption);
- } catch (NumberFormatException e) {
- this.alignment_for_expressions_in_array_initializer = Alignment.M_COMPACT_SPLIT;
- } catch (ClassCastException e) {
- this.alignment_for_expressions_in_array_initializer = Alignment.M_COMPACT_SPLIT;
- }
- }
- final Object alignmentForMultipleFieldsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_MULTIPLE_FIELDS);
- if (alignmentForMultipleFieldsOption != null) {
- try {
- this.alignment_for_multiple_fields = Integer.parseInt((String) alignmentForMultipleFieldsOption);
- } catch (NumberFormatException e) {
- this.alignment_for_multiple_fields = Alignment.M_COMPACT_SPLIT;
- } catch (ClassCastException e) {
- this.alignment_for_multiple_fields = Alignment.M_COMPACT_SPLIT;
- }
- }
- final Object alignmentForParametersInConstructorDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_CONSTRUCTOR_DECLARATION);
- if (alignmentForParametersInConstructorDeclarationOption != null) {
- try {
- this.alignment_for_parameters_in_constructor_declaration = Integer.parseInt((String) alignmentForParametersInConstructorDeclarationOption);
- } catch (NumberFormatException e) {
- this.alignment_for_parameters_in_constructor_declaration = Alignment.M_COMPACT_SPLIT;
- } catch (ClassCastException e) {
- this.alignment_for_parameters_in_constructor_declaration = Alignment.M_COMPACT_SPLIT;
- }
- }
- final Object alignmentForParametersInMethodDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION);
- if (alignmentForParametersInMethodDeclarationOption != null) {
- try {
- this.alignment_for_parameters_in_method_declaration = Integer.parseInt((String) alignmentForParametersInMethodDeclarationOption);
- } catch (NumberFormatException e) {
- this.alignment_for_parameters_in_method_declaration = Alignment.M_COMPACT_SPLIT;
- } catch(ClassCastException e) {
- this.alignment_for_parameters_in_method_declaration = Alignment.M_COMPACT_SPLIT;
- }
- }
- final Object alignmentForSelectorInMethodInvocationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SELECTOR_IN_METHOD_INVOCATION);
- if (alignmentForSelectorInMethodInvocationOption != null) {
- try {
- this.alignment_for_selector_in_method_invocation = Integer.parseInt((String) alignmentForSelectorInMethodInvocationOption);
- } catch (NumberFormatException e) {
- this.alignment_for_selector_in_method_invocation = Alignment.M_COMPACT_SPLIT;
- } catch(ClassCastException e) {
- this.alignment_for_selector_in_method_invocation = Alignment.M_COMPACT_SPLIT;
- }
- }
- final Object alignmentForSuperclassInTypeDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SUPERCLASS_IN_TYPE_DECLARATION);
- if (alignmentForSuperclassInTypeDeclarationOption != null) {
- try {
- this.alignment_for_superclass_in_type_declaration = Integer.parseInt((String) alignmentForSuperclassInTypeDeclarationOption);
- } catch (NumberFormatException e) {
- this.alignment_for_superclass_in_type_declaration = Alignment.M_NEXT_SHIFTED_SPLIT;
- } catch(ClassCastException e) {
- this.alignment_for_superclass_in_type_declaration = Alignment.M_NEXT_SHIFTED_SPLIT;
- }
- }
- final Object alignmentForSuperinterfacesInEnumDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SUPERINTERFACES_IN_ENUM_DECLARATION);
- if (alignmentForSuperinterfacesInEnumDeclarationOption != null) {
- try {
- this.alignment_for_superinterfaces_in_enum_declaration = Integer.parseInt((String) alignmentForSuperinterfacesInEnumDeclarationOption);
- } catch (NumberFormatException e) {
- this.alignment_for_superinterfaces_in_enum_declaration = Alignment.M_NEXT_SHIFTED_SPLIT;
- } catch(ClassCastException e) {
- this.alignment_for_superinterfaces_in_enum_declaration = Alignment.M_NEXT_SHIFTED_SPLIT;
- }
- }
- final Object alignmentForSuperinterfacesInTypeDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SUPERINTERFACES_IN_TYPE_DECLARATION);
- if (alignmentForSuperinterfacesInTypeDeclarationOption != null) {
- try {
- this.alignment_for_superinterfaces_in_type_declaration = Integer.parseInt((String) alignmentForSuperinterfacesInTypeDeclarationOption);
- } catch (NumberFormatException e) {
- this.alignment_for_superinterfaces_in_type_declaration = Alignment.M_NEXT_SHIFTED_SPLIT;
- } catch(ClassCastException e) {
- this.alignment_for_superinterfaces_in_type_declaration = Alignment.M_NEXT_SHIFTED_SPLIT;
- }
- }
- final Object alignmentForThrowsClauseInConstructorDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_THROWS_CLAUSE_IN_CONSTRUCTOR_DECLARATION);
- if (alignmentForThrowsClauseInConstructorDeclarationOption != null) {
- try {
- this.alignment_for_throws_clause_in_constructor_declaration = Integer.parseInt((String) alignmentForThrowsClauseInConstructorDeclarationOption);
- } catch (NumberFormatException e) {
- this.alignment_for_throws_clause_in_constructor_declaration = Alignment.M_COMPACT_SPLIT;
- } catch(ClassCastException e) {
- this.alignment_for_throws_clause_in_constructor_declaration = Alignment.M_COMPACT_SPLIT;
- }
- }
- final Object alignmentForThrowsClauseInMethodDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_THROWS_CLAUSE_IN_METHOD_DECLARATION);
- if (alignmentForThrowsClauseInMethodDeclarationOption != null) {
- try {
- this.alignment_for_throws_clause_in_method_declaration = Integer.parseInt((String) alignmentForThrowsClauseInMethodDeclarationOption);
- } catch (NumberFormatException e) {
- this.alignment_for_throws_clause_in_method_declaration = Alignment.M_COMPACT_SPLIT;
- } catch(ClassCastException e) {
- this.alignment_for_throws_clause_in_method_declaration = Alignment.M_COMPACT_SPLIT;
- }
- }
- final Object alignTypeMembersOnColumnsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_ALIGN_TYPE_MEMBERS_ON_COLUMNS);
- if (alignTypeMembersOnColumnsOption != null) {
- this.align_type_members_on_columns = DefaultCodeFormatterConstants.TRUE.equals(alignTypeMembersOnColumnsOption);
- }
- final Object bracePositionForAnnotationTypeDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ANNOTATION_TYPE_DECLARATION);
- if (bracePositionForAnnotationTypeDeclarationOption != null) {
- try {
- this.brace_position_for_annotation_type_declaration = (String) bracePositionForAnnotationTypeDeclarationOption;
- } catch(ClassCastException e) {
- this.brace_position_for_annotation_type_declaration = DefaultCodeFormatterConstants.END_OF_LINE;
- }
- }
- final Object bracePositionForAnonymousTypeDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ANONYMOUS_TYPE_DECLARATION);
- if (bracePositionForAnonymousTypeDeclarationOption != null) {
- try {
- this.brace_position_for_anonymous_type_declaration = (String) bracePositionForAnonymousTypeDeclarationOption;
- } catch(ClassCastException e) {
- this.brace_position_for_anonymous_type_declaration = DefaultCodeFormatterConstants.END_OF_LINE;
- }
- }
- final Object bracePositionForArrayInitializerOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ARRAY_INITIALIZER);
- if (bracePositionForArrayInitializerOption != null) {
- try {
- this.brace_position_for_array_initializer = (String) bracePositionForArrayInitializerOption;
- } catch(ClassCastException e) {
- this.brace_position_for_array_initializer = DefaultCodeFormatterConstants.END_OF_LINE;
- }
- }
- final Object bracePositionForObjLitInitializerOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_OBJLIT_INITIALIZER);
- if (bracePositionForObjLitInitializerOption != null) {
- try {
- this.brace_position_for_objlit_initializer = (String) bracePositionForObjLitInitializerOption;
- } catch(ClassCastException e) {
- this.brace_position_for_objlit_initializer = DefaultCodeFormatterConstants.END_OF_LINE;
- }
- }
- final Object bracePositionForBlockOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_BLOCK);
- if (bracePositionForBlockOption != null) {
- try {
- this.brace_position_for_block = (String) bracePositionForBlockOption;
- } catch(ClassCastException e) {
- this.brace_position_for_block = DefaultCodeFormatterConstants.END_OF_LINE;
- }
- }
- final Object bracePositionForBlockInCaseOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_BLOCK_IN_CASE);
- if (bracePositionForBlockInCaseOption != null) {
- try {
- this.brace_position_for_block_in_case = (String) bracePositionForBlockInCaseOption;
- } catch(ClassCastException e) {
- this.brace_position_for_block_in_case = DefaultCodeFormatterConstants.END_OF_LINE;
- }
- }
- final Object bracePositionForConstructorDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_CONSTRUCTOR_DECLARATION);
- if (bracePositionForConstructorDeclarationOption != null) {
- try {
- this.brace_position_for_constructor_declaration = (String) bracePositionForConstructorDeclarationOption;
- } catch(ClassCastException e) {
- this.brace_position_for_constructor_declaration = DefaultCodeFormatterConstants.END_OF_LINE;
- }
- }
- final Object bracePositionForEnumConstantOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ENUM_CONSTANT);
- if (bracePositionForEnumConstantOption != null) {
- try {
- this.brace_position_for_enum_constant = (String) bracePositionForEnumConstantOption;
- } catch(ClassCastException e) {
- this.brace_position_for_enum_constant = DefaultCodeFormatterConstants.END_OF_LINE;
- }
- }
- final Object bracePositionForEnumDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ENUM_DECLARATION);
- if (bracePositionForEnumDeclarationOption != null) {
- try {
- this.brace_position_for_enum_declaration = (String) bracePositionForEnumDeclarationOption;
- } catch(ClassCastException e) {
- this.brace_position_for_enum_declaration = DefaultCodeFormatterConstants.END_OF_LINE;
- }
- }
- final Object bracePositionForMethodDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION);
- if (bracePositionForMethodDeclarationOption != null) {
- try {
- this.brace_position_for_method_declaration = (String) bracePositionForMethodDeclarationOption;
- } catch(ClassCastException e) {
- this.brace_position_for_method_declaration = DefaultCodeFormatterConstants.END_OF_LINE;
- }
- }
- final Object bracePositionForSwitchOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_SWITCH);
- if (bracePositionForSwitchOption != null) {
- try {
- this.brace_position_for_switch = (String) bracePositionForSwitchOption;
- } catch(ClassCastException e) {
- this.brace_position_for_switch = DefaultCodeFormatterConstants.END_OF_LINE;
- }
- }
- final Object bracePositionForTypeDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_TYPE_DECLARATION);
- if (bracePositionForTypeDeclarationOption != null) {
- try {
- this.brace_position_for_type_declaration = (String) bracePositionForTypeDeclarationOption;
- } catch(ClassCastException e) {
- this.brace_position_for_type_declaration = DefaultCodeFormatterConstants.END_OF_LINE;
- }
- }
- final Object continuationIndentationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION);
- if (continuationIndentationOption != null) {
- try {
- this.continuation_indentation = Integer.parseInt((String) continuationIndentationOption);
- } catch (NumberFormatException e) {
- this.continuation_indentation = 2;
- } catch(ClassCastException e) {
- this.continuation_indentation = 2;
- }
- }
- final Object continuationIndentationForArrayInitializerOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION_FOR_ARRAY_INITIALIZER);
- if (continuationIndentationForArrayInitializerOption != null) {
- try {
- this.continuation_indentation_for_array_initializer = Integer.parseInt((String) continuationIndentationForArrayInitializerOption);
- } catch (NumberFormatException e) {
- this.continuation_indentation_for_array_initializer = 2;
- } catch(ClassCastException e) {
- this.continuation_indentation_for_array_initializer = 2;
- }
- }
- final Object continuationIndentationForObjLitInitializerOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION_FOR_OBJLIT_INITIALIZER);
- if (continuationIndentationForObjLitInitializerOption != null) {
- try {
- this.continuation_indentation_for_objlit_initializer = Integer.parseInt((String) continuationIndentationForObjLitInitializerOption);
- } catch (NumberFormatException e) {
- this.continuation_indentation_for_objlit_initializer = 1;
- } catch(ClassCastException e) {
- this.continuation_indentation_for_objlit_initializer = 1;
- }
- }
- final Object blankLinesAfterImportsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_AFTER_IMPORTS);
- if (blankLinesAfterImportsOption != null) {
- try {
- this.blank_lines_after_imports = Integer.parseInt((String) blankLinesAfterImportsOption);
- } catch (NumberFormatException e) {
- this.blank_lines_after_imports = 0;
- } catch(ClassCastException e) {
- this.blank_lines_after_imports = 0;
- }
- }
- final Object blankLinesAfterPackageOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_AFTER_PACKAGE);
- if (blankLinesAfterPackageOption != null) {
- try {
- this.blank_lines_after_package = Integer.parseInt((String) blankLinesAfterPackageOption);
- } catch (NumberFormatException e) {
- this.blank_lines_after_package = 0;
- } catch(ClassCastException e) {
- this.blank_lines_after_package = 0;
- }
- }
- final Object blankLinesBeforeFieldOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_BEFORE_FIELD);
- if (blankLinesBeforeFieldOption != null) {
- try {
- this.blank_lines_before_field = Integer.parseInt((String) blankLinesBeforeFieldOption);
- } catch (NumberFormatException e) {
- this.blank_lines_before_field = 0;
- } catch(ClassCastException e) {
- this.blank_lines_before_field = 0;
- }
- }
- final Object blankLinesBeforeFirstClassBodyDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_BEFORE_FIRST_CLASS_BODY_DECLARATION);
- if (blankLinesBeforeFirstClassBodyDeclarationOption != null) {
- try {
- this.blank_lines_before_first_class_body_declaration = Integer.parseInt((String) blankLinesBeforeFirstClassBodyDeclarationOption);
- } catch (NumberFormatException e) {
- this.blank_lines_before_first_class_body_declaration = 0;
- } catch(ClassCastException e) {
- this.blank_lines_before_first_class_body_declaration = 0;
- }
- }
- final Object blankLinesBeforeImportsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_BEFORE_IMPORTS);
- if (blankLinesBeforeImportsOption != null) {
- try {
- this.blank_lines_before_imports = Integer.parseInt((String) blankLinesBeforeImportsOption);
- } catch (NumberFormatException e) {
- this.blank_lines_before_imports = 0;
- } catch(ClassCastException e) {
- this.blank_lines_before_imports = 0;
- }
- }
- final Object blankLinesBeforeMemberTypeOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_BEFORE_MEMBER_TYPE);
- if (blankLinesBeforeMemberTypeOption != null) {
- try {
- this.blank_lines_before_member_type = Integer.parseInt((String) blankLinesBeforeMemberTypeOption);
- } catch (NumberFormatException e) {
- this.blank_lines_before_member_type = 0;
- } catch(ClassCastException e) {
- this.blank_lines_before_member_type = 0;
- }
- }
- final Object blankLinesBeforeMethodOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_BEFORE_METHOD);
- if (blankLinesBeforeMethodOption != null) {
- try {
- this.blank_lines_before_method = Integer.parseInt((String) blankLinesBeforeMethodOption);
- } catch (NumberFormatException e) {
- this.blank_lines_before_method = 0;
- } catch(ClassCastException e) {
- this.blank_lines_before_method = 0;
- }
- }
- final Object blankLinesBeforeNewChunkOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_BEFORE_NEW_CHUNK);
- if (blankLinesBeforeNewChunkOption != null) {
- try {
- this.blank_lines_before_new_chunk = Integer.parseInt((String) blankLinesBeforeNewChunkOption);
- } catch (NumberFormatException e) {
- this.blank_lines_before_new_chunk = 0;
- } catch(ClassCastException e) {
- this.blank_lines_before_new_chunk = 0;
- }
- }
- final Object blankLinesBeforePackageOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_BEFORE_PACKAGE);
- if (blankLinesBeforePackageOption != null) {
- try {
- this.blank_lines_before_package = Integer.parseInt((String) blankLinesBeforePackageOption);
- } catch (NumberFormatException e) {
- this.blank_lines_before_package = 0;
- } catch(ClassCastException e) {
- this.blank_lines_before_package = 0;
- }
- }
- final Object blankLinesBetweenImportGroupsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_BETWEEN_IMPORT_GROUPS);
- if (blankLinesBetweenImportGroupsOption != null) {
- try {
- this.blank_lines_between_import_groups = Integer.parseInt((String) blankLinesBetweenImportGroupsOption);
- } catch (NumberFormatException e) {
- this.blank_lines_between_import_groups = 1;
- } catch(ClassCastException e) {
- this.blank_lines_between_import_groups = 1;
- }
- }
- final Object blankLinesBetweenTypeDeclarationsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_BETWEEN_TYPE_DECLARATIONS);
- if (blankLinesBetweenTypeDeclarationsOption != null) {
- try {
- this.blank_lines_between_type_declarations = Integer.parseInt((String) blankLinesBetweenTypeDeclarationsOption);
- } catch (NumberFormatException e) {
- this.blank_lines_between_type_declarations = 0;
- } catch(ClassCastException e) {
- this.blank_lines_between_type_declarations = 0;
- }
- }
- final Object blankLinesAtBeginningOfMethodBodyOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_AT_BEGINNING_OF_METHOD_BODY);
- if (blankLinesAtBeginningOfMethodBodyOption != null) {
- try {
- this.blank_lines_at_beginning_of_method_body = Integer.parseInt((String) blankLinesAtBeginningOfMethodBodyOption);
- } catch (NumberFormatException e) {
- this.blank_lines_at_beginning_of_method_body = 0;
- } catch(ClassCastException e) {
- this.blank_lines_at_beginning_of_method_body = 0;
- }
- }
- setDeprecatedOptions(settings);
- final Object commentFormatJavadocCommentOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_JAVADOC_COMMENT);
- if (commentFormatJavadocCommentOption != null) {
- this.comment_format_javadoc_comment = DefaultCodeFormatterConstants.TRUE.equals(commentFormatJavadocCommentOption);
- }
- final Object commentFormatBlockCommentOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_BLOCK_COMMENT);
- if (commentFormatBlockCommentOption != null) {
- this.comment_format_block_comment = DefaultCodeFormatterConstants.TRUE.equals(commentFormatBlockCommentOption);
- }
- final Object commentFormatLineCommentOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_LINE_COMMENT);
- if (commentFormatLineCommentOption != null) {
- this.comment_format_line_comment = DefaultCodeFormatterConstants.TRUE.equals(commentFormatLineCommentOption);
- }
- final Object commentFormatHeaderOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_HEADER);
- if (commentFormatHeaderOption != null) {
- this.comment_format_header = DefaultCodeFormatterConstants.TRUE.equals(commentFormatHeaderOption);
- }
- final Object commentFormatHtmlOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_HTML);
- if (commentFormatHtmlOption != null) {
- this.comment_format_html = DefaultCodeFormatterConstants.TRUE.equals(commentFormatHtmlOption);
- }
- final Object commentFormatSourceOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_SOURCE);
- if (commentFormatSourceOption != null) {
- this.comment_format_source = DefaultCodeFormatterConstants.TRUE.equals(commentFormatSourceOption);
- }
- final Object commentIndentParameterDescriptionOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_INDENT_PARAMETER_DESCRIPTION);
- if (commentIndentParameterDescriptionOption != null) {
- this.comment_indent_parameter_description = DefaultCodeFormatterConstants.TRUE.equals(commentIndentParameterDescriptionOption);
- }
- final Object commentIndentRootTagsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_INDENT_ROOT_TAGS);
- if (commentIndentRootTagsOption != null) {
- this.comment_indent_root_tags = DefaultCodeFormatterConstants.TRUE.equals(commentIndentRootTagsOption);
- }
- final Object commentInsertEmptyLineBeforeRootTagsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_INSERT_EMPTY_LINE_BEFORE_ROOT_TAGS);
- if (commentInsertEmptyLineBeforeRootTagsOption != null) {
- this.comment_insert_empty_line_before_root_tags = JavaScriptCore.INSERT.equals(commentInsertEmptyLineBeforeRootTagsOption);
- }
- final Object commentInsertNewLineForParameterOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_INSERT_NEW_LINE_FOR_PARAMETER);
- if (commentInsertNewLineForParameterOption != null) {
- this.comment_insert_new_line_for_parameter = JavaScriptCore.INSERT.equals(commentInsertNewLineForParameterOption);
- }
- final Object commentLineLengthOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_LINE_LENGTH);
- if (commentLineLengthOption != null) {
- try {
- this.comment_line_length = Integer.parseInt((String) commentLineLengthOption);
- } catch (NumberFormatException e) {
- this.comment_line_length = 80;
- } catch(ClassCastException e) {
- this.comment_line_length = 80;
- }
- }
- final Object indentStatementsCompareToBlockOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BLOCK);
- if (indentStatementsCompareToBlockOption != null) {
- this.indent_statements_compare_to_block = DefaultCodeFormatterConstants.TRUE.equals(indentStatementsCompareToBlockOption);
- }
- final Object indentStatementsCompareToBodyOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BODY);
- if (indentStatementsCompareToBodyOption != null) {
- this.indent_statements_compare_to_body = DefaultCodeFormatterConstants.TRUE.equals(indentStatementsCompareToBodyOption);
- }
- final Object indentBodyDeclarationsCompareToAnnotationDeclarationHeaderOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ANNOTATION_DECLARATION_HEADER);
- if (indentBodyDeclarationsCompareToAnnotationDeclarationHeaderOption != null) {
- this.indent_body_declarations_compare_to_annotation_declaration_header = DefaultCodeFormatterConstants.TRUE.equals(indentBodyDeclarationsCompareToAnnotationDeclarationHeaderOption);
- }
- final Object indentBodyDeclarationsCompareToEnumConstantHeaderOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ENUM_CONSTANT_HEADER);
- if (indentBodyDeclarationsCompareToEnumConstantHeaderOption != null) {
- this.indent_body_declarations_compare_to_enum_constant_header = DefaultCodeFormatterConstants.TRUE.equals(indentBodyDeclarationsCompareToEnumConstantHeaderOption);
- }
- final Object indentBodyDeclarationsCompareToEnumDeclarationHeaderOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ENUM_DECLARATION_HEADER);
- if (indentBodyDeclarationsCompareToEnumDeclarationHeaderOption != null) {
- this.indent_body_declarations_compare_to_enum_declaration_header = DefaultCodeFormatterConstants.TRUE.equals(indentBodyDeclarationsCompareToEnumDeclarationHeaderOption);
- }
- final Object indentBodyDeclarationsCompareToTypeHeaderOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_TYPE_HEADER);
- if (indentBodyDeclarationsCompareToTypeHeaderOption != null) {
- this.indent_body_declarations_compare_to_type_header = DefaultCodeFormatterConstants.TRUE.equals(indentBodyDeclarationsCompareToTypeHeaderOption);
- }
- final Object indentBreaksCompareToCasesOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INDENT_BREAKS_COMPARE_TO_CASES);
- if (indentBreaksCompareToCasesOption != null) {
- this.indent_breaks_compare_to_cases = DefaultCodeFormatterConstants.TRUE.equals(indentBreaksCompareToCasesOption);
- }
- final Object indentEmptyLinesOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INDENT_EMPTY_LINES);
- if (indentEmptyLinesOption != null) {
- this.indent_empty_lines = DefaultCodeFormatterConstants.TRUE.equals(indentEmptyLinesOption);
- }
- final Object indentSwitchstatementsCompareToCasesOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_CASES);
- if (indentSwitchstatementsCompareToCasesOption != null) {
- this.indent_switchstatements_compare_to_cases = DefaultCodeFormatterConstants.TRUE.equals(indentSwitchstatementsCompareToCasesOption);
- }
- final Object indentSwitchstatementsCompareToSwitchOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_SWITCH);
- if (indentSwitchstatementsCompareToSwitchOption != null) {
- this.indent_switchstatements_compare_to_switch = DefaultCodeFormatterConstants.TRUE.equals(indentSwitchstatementsCompareToSwitchOption);
- }
- final Object indentationSizeOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INDENTATION_SIZE);
- if (indentationSizeOption != null) {
- try {
- this.indentation_size = Integer.parseInt((String) indentationSizeOption);
- } catch (NumberFormatException e) {
- this.indentation_size = 4;
- } catch(ClassCastException e) {
- this.indentation_size = 4;
- }
- }
- final Object insertNewLineAfterAnnotationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_AFTER_ANNOTATION);
- if (insertNewLineAfterAnnotationOption != null) {
- this.insert_new_line_after_annotation = JavaScriptCore.INSERT.equals(insertNewLineAfterAnnotationOption);
- }
- final Object insertNewLineAfterOpeningBraceInArrayInitializerOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_AFTER_OPENING_BRACE_IN_ARRAY_INITIALIZER);
- if (insertNewLineAfterOpeningBraceInArrayInitializerOption != null) {
- this.insert_new_line_after_opening_brace_in_array_initializer = JavaScriptCore.INSERT.equals(insertNewLineAfterOpeningBraceInArrayInitializerOption);
- }
- final Object insertNewLineAfterOpeningBraceInObjLitInitializerOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_AFTER_OPENING_BRACE_IN_OBJLIT_INITIALIZER);
- if (insertNewLineAfterOpeningBraceInObjLitInitializerOption != null) {
- this.insert_new_line_after_opening_brace_in_objlit_initializer = JavaScriptCore.INSERT.equals(insertNewLineAfterOpeningBraceInObjLitInitializerOption);
- }
- final Object insertNewLineAfterCommaInObjLitInitializerOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_AFTER_COMMA_IN_OBJLIT_INITIALIZER);
- if (insertNewLineAfterCommaInObjLitInitializerOption != null) {
- this.insert_new_line_after_comma_in_objlit_initializer = JavaScriptCore.INSERT.equals(insertNewLineAfterCommaInObjLitInitializerOption);
- }
- final Object insertNewLineAtEndOfFileIfMissingOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_AT_END_OF_FILE_IF_MISSING);
- if (insertNewLineAtEndOfFileIfMissingOption != null) {
- this.insert_new_line_at_end_of_file_if_missing = JavaScriptCore.INSERT.equals(insertNewLineAtEndOfFileIfMissingOption);
- }
- final Object insertNewLineBeforeCatchInTryStatementOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_BEFORE_CATCH_IN_TRY_STATEMENT);
- if (insertNewLineBeforeCatchInTryStatementOption != null) {
- this.insert_new_line_before_catch_in_try_statement = JavaScriptCore.INSERT.equals(insertNewLineBeforeCatchInTryStatementOption);
- }
- final Object insertNewLineBeforeClosingBraceInArrayInitializerOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_BEFORE_CLOSING_BRACE_IN_ARRAY_INITIALIZER);
- if (insertNewLineBeforeClosingBraceInArrayInitializerOption != null) {
- this.insert_new_line_before_closing_brace_in_array_initializer = JavaScriptCore.INSERT.equals(insertNewLineBeforeClosingBraceInArrayInitializerOption);
- }
- final Object insertNewLineBeforeClosingBraceInObjLitInitializerOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_BEFORE_CLOSING_BRACE_IN_OBJLIT_INITIALIZER);
- if (insertNewLineBeforeClosingBraceInObjLitInitializerOption != null) {
- this.insert_new_line_before_closing_brace_in_objlit_initializer = JavaScriptCore.INSERT.equals(insertNewLineBeforeClosingBraceInObjLitInitializerOption);
- }
- final Object insertNewLineBeforeElseInIfStatementOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_BEFORE_ELSE_IN_IF_STATEMENT);
- if (insertNewLineBeforeElseInIfStatementOption != null) {
- this.insert_new_line_before_else_in_if_statement = JavaScriptCore.INSERT.equals(insertNewLineBeforeElseInIfStatementOption);
- }
- final Object insertNewLineBeforeFinallyInTryStatementOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_BEFORE_FINALLY_IN_TRY_STATEMENT);
- if (insertNewLineBeforeFinallyInTryStatementOption != null) {
- this.insert_new_line_before_finally_in_try_statement = JavaScriptCore.INSERT.equals(insertNewLineBeforeFinallyInTryStatementOption);
- }
- final Object insertNewLineBeforeWhileInDoStatementOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_BEFORE_WHILE_IN_DO_STATEMENT);
- if (insertNewLineBeforeWhileInDoStatementOption != null) {
- this.insert_new_line_before_while_in_do_statement = JavaScriptCore.INSERT.equals(insertNewLineBeforeWhileInDoStatementOption);
- }
- final Object insertNewLineInEmptyAnonymousTypeDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_IN_EMPTY_ANONYMOUS_TYPE_DECLARATION);
- if (insertNewLineInEmptyAnonymousTypeDeclarationOption != null) {
- this.insert_new_line_in_empty_anonymous_type_declaration = JavaScriptCore.INSERT.equals(insertNewLineInEmptyAnonymousTypeDeclarationOption);
- }
- final Object insertNewLineInEmptyBlockOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_IN_EMPTY_BLOCK);
- if (insertNewLineInEmptyBlockOption != null) {
- this.insert_new_line_in_empty_block = JavaScriptCore.INSERT.equals(insertNewLineInEmptyBlockOption);
- }
- final Object insertNewLineInEmptyAnnotationDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_IN_EMPTY_ANNOTATION_DECLARATION);
- if (insertNewLineInEmptyAnnotationDeclarationOption != null) {
- this.insert_new_line_in_empty_annotation_declaration = JavaScriptCore.INSERT.equals(insertNewLineInEmptyAnnotationDeclarationOption);
- }
- final Object insertNewLineInEmptyEnumConstantOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_IN_EMPTY_ENUM_CONSTANT);
- if (insertNewLineInEmptyEnumConstantOption != null) {
- this.insert_new_line_in_empty_enum_constant = JavaScriptCore.INSERT.equals(insertNewLineInEmptyEnumConstantOption);
- }
- final Object insertNewLineInEmptyEnumDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_IN_EMPTY_ENUM_DECLARATION);
- if (insertNewLineInEmptyEnumDeclarationOption != null) {
- this.insert_new_line_in_empty_enum_declaration = JavaScriptCore.INSERT.equals(insertNewLineInEmptyEnumDeclarationOption);
- }
- final Object insertNewLineInEmptyMethodBodyOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_IN_EMPTY_METHOD_BODY);
- if (insertNewLineInEmptyMethodBodyOption != null) {
- this.insert_new_line_in_empty_method_body = JavaScriptCore.INSERT.equals(insertNewLineInEmptyMethodBodyOption);
- }
- final Object insertNewLineInEmptyTypeDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_IN_EMPTY_TYPE_DECLARATION);
- if (insertNewLineInEmptyTypeDeclarationOption != null) {
- this.insert_new_line_in_empty_type_declaration = JavaScriptCore.INSERT.equals(insertNewLineInEmptyTypeDeclarationOption);
- }
- final Object insertSpaceAfterAndInWildcardOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_AND_IN_TYPE_PARAMETER);
- if (insertSpaceAfterAndInWildcardOption != null) {
- this.insert_space_after_and_in_type_parameter = JavaScriptCore.INSERT.equals(insertSpaceAfterAndInWildcardOption);
- }
- final Object insertSpaceAfterAssignmentOperatorOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_ASSIGNMENT_OPERATOR);
- if (insertSpaceAfterAssignmentOperatorOption != null) {
- this.insert_space_after_assignment_operator = JavaScriptCore.INSERT.equals(insertSpaceAfterAssignmentOperatorOption);
- }
- final Object insertSpaceAfterAtInAnnotationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_AT_IN_ANNOTATION);
- if (insertSpaceAfterAtInAnnotationOption != null) {
- this.insert_space_after_at_in_annotation = JavaScriptCore.INSERT.equals(insertSpaceAfterAtInAnnotationOption);
- }
- final Object insertSpaceAfterAtInAnnotationTypeDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_AT_IN_ANNOTATION_TYPE_DECLARATION);
- if (insertSpaceAfterAtInAnnotationTypeDeclarationOption != null) {
- this.insert_space_after_at_in_annotation_type_declaration = JavaScriptCore.INSERT.equals(insertSpaceAfterAtInAnnotationTypeDeclarationOption);
- }
- final Object insertSpaceAfterBinaryOperatorOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_BINARY_OPERATOR);
- if (insertSpaceAfterBinaryOperatorOption != null) {
- this.insert_space_after_binary_operator = JavaScriptCore.INSERT.equals(insertSpaceAfterBinaryOperatorOption);
- }
- final Object insertSpaceAfterClosingAngleBracketInTypeArgumentsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_CLOSING_ANGLE_BRACKET_IN_TYPE_ARGUMENTS);
- if (insertSpaceAfterClosingAngleBracketInTypeArgumentsOption != null) {
- this.insert_space_after_closing_angle_bracket_in_type_arguments = JavaScriptCore.INSERT.equals(insertSpaceAfterClosingAngleBracketInTypeArgumentsOption);
- }
- final Object insertSpaceAfterClosingAngleBracketInTypeParametersOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_CLOSING_ANGLE_BRACKET_IN_TYPE_PARAMETERS);
- if (insertSpaceAfterClosingAngleBracketInTypeParametersOption != null) {
- this.insert_space_after_closing_angle_bracket_in_type_parameters = JavaScriptCore.INSERT.equals(insertSpaceAfterClosingAngleBracketInTypeParametersOption);
- }
- final Object insertSpaceAfterClosingParenInCastOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_CLOSING_PAREN_IN_CAST);
- if (insertSpaceAfterClosingParenInCastOption != null) {
- this.insert_space_after_closing_paren_in_cast = JavaScriptCore.INSERT.equals(insertSpaceAfterClosingParenInCastOption);
- }
- final Object insertSpaceAfterClosingBraceInBlockOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_CLOSING_BRACE_IN_BLOCK);
- if (insertSpaceAfterClosingBraceInBlockOption != null) {
- this.insert_space_after_closing_brace_in_block = JavaScriptCore.INSERT.equals(insertSpaceAfterClosingBraceInBlockOption);
- }
- final Object insertSpaceAfterColonInAssertOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COLON_IN_ASSERT);
- if (insertSpaceAfterColonInAssertOption != null) {
- this.insert_space_after_colon_in_assert = JavaScriptCore.INSERT.equals(insertSpaceAfterColonInAssertOption);
- }
- final Object insertSpaceAfterColonInCaseOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COLON_IN_CASE);
- if (insertSpaceAfterColonInCaseOption != null) {
- this.insert_space_after_colon_in_case = JavaScriptCore.INSERT.equals(insertSpaceAfterColonInCaseOption);
- }
- final Object insertSpaceAfterColonInConditionalOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COLON_IN_CONDITIONAL);
- if (insertSpaceAfterColonInConditionalOption != null) {
- this.insert_space_after_colon_in_conditional = JavaScriptCore.INSERT.equals(insertSpaceAfterColonInConditionalOption);
- }
- final Object insertSpaceAfterColonInObjectInitializerOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COLON_IN_OBJECT_INITIALIZER);
- if (insertSpaceAfterColonInObjectInitializerOption != null) {
- this.insert_space_after_colon_in_object_initializer = JavaScriptCore.INSERT.equals(insertSpaceAfterColonInObjectInitializerOption);
- }
- final Object insertSpaceAfterColonInForOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COLON_IN_FOR);
- if (insertSpaceAfterColonInForOption != null) {
- this.insert_space_after_colon_in_for = JavaScriptCore.INSERT.equals(insertSpaceAfterColonInForOption);
- }
- final Object insertSpaceAfterColonInLabeledStatementOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COLON_IN_LABELED_STATEMENT);
- if (insertSpaceAfterColonInLabeledStatementOption != null) {
- this.insert_space_after_colon_in_labeled_statement = JavaScriptCore.INSERT.equals(insertSpaceAfterColonInLabeledStatementOption);
- }
- final Object insertSpaceAfterCommaInAllocationExpressionOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_ALLOCATION_EXPRESSION);
- if (insertSpaceAfterCommaInAllocationExpressionOption != null) {
- this.insert_space_after_comma_in_allocation_expression = JavaScriptCore.INSERT.equals(insertSpaceAfterCommaInAllocationExpressionOption);
- }
- final Object insertSpaceAfterCommaInAnnotationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_ANNOTATION);
- if (insertSpaceAfterCommaInAnnotationOption != null) {
- this.insert_space_after_comma_in_annotation = JavaScriptCore.INSERT.equals(insertSpaceAfterCommaInAnnotationOption);
- }
- final Object insertSpaceAfterCommaInArrayInitializerOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_ARRAY_INITIALIZER);
- if (insertSpaceAfterCommaInArrayInitializerOption != null) {
- this.insert_space_after_comma_in_array_initializer = JavaScriptCore.INSERT.equals(insertSpaceAfterCommaInArrayInitializerOption);
- }
- final Object insertSpaceAfterCommaInConstructorDeclarationParametersOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_CONSTRUCTOR_DECLARATION_PARAMETERS);
- if (insertSpaceAfterCommaInConstructorDeclarationParametersOption != null) {
- this.insert_space_after_comma_in_constructor_declaration_parameters = JavaScriptCore.INSERT.equals(insertSpaceAfterCommaInConstructorDeclarationParametersOption);
- }
- final Object insertSpaceAfterCommaInConstructorDeclarationThrowsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_CONSTRUCTOR_DECLARATION_THROWS);
- if (insertSpaceAfterCommaInConstructorDeclarationThrowsOption != null) {
- this.insert_space_after_comma_in_constructor_declaration_throws = JavaScriptCore.INSERT.equals(insertSpaceAfterCommaInConstructorDeclarationThrowsOption);
- }
- final Object insertSpaceAfterCommaInEnumConstantArgumentsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_ENUM_CONSTANT_ARGUMENTS);
- if (insertSpaceAfterCommaInEnumConstantArgumentsOption != null) {
- this.insert_space_after_comma_in_enum_constant_arguments = JavaScriptCore.INSERT.equals(insertSpaceAfterCommaInEnumConstantArgumentsOption);
- }
- final Object insertSpaceAfterCommaInEnumDeclarationsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_ENUM_DECLARATIONS);
- if (insertSpaceAfterCommaInEnumDeclarationsOption != null) {
- this.insert_space_after_comma_in_enum_declarations = JavaScriptCore.INSERT.equals(insertSpaceAfterCommaInEnumDeclarationsOption);
- }
- final Object insertSpaceAfterCommaInExplicitConstructorCallArgumentsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_EXPLICIT_CONSTRUCTOR_CALL_ARGUMENTS);
- if (insertSpaceAfterCommaInExplicitConstructorCallArgumentsOption != null) {
- this.insert_space_after_comma_in_explicit_constructor_call_arguments = JavaScriptCore.INSERT.equals(insertSpaceAfterCommaInExplicitConstructorCallArgumentsOption);
- }
- final Object insertSpaceAfterCommaInForIncrementsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_FOR_INCREMENTS);
- if (insertSpaceAfterCommaInForIncrementsOption != null) {
- this.insert_space_after_comma_in_for_increments = JavaScriptCore.INSERT.equals(insertSpaceAfterCommaInForIncrementsOption);
- }
- final Object insertSpaceAfterCommaInForInitsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_FOR_INITS);
- if (insertSpaceAfterCommaInForInitsOption != null) {
- this.insert_space_after_comma_in_for_inits = JavaScriptCore.INSERT.equals(insertSpaceAfterCommaInForInitsOption);
- }
- final Object insertSpaceAfterCommaInMethodInvocationArgumentsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_METHOD_INVOCATION_ARGUMENTS);
- if (insertSpaceAfterCommaInMethodInvocationArgumentsOption != null) {
- this.insert_space_after_comma_in_method_invocation_arguments = JavaScriptCore.INSERT.equals(insertSpaceAfterCommaInMethodInvocationArgumentsOption);
- }
- final Object insertSpaceAfterCommaInMethodDeclarationParametersOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_METHOD_DECLARATION_PARAMETERS);
- if (insertSpaceAfterCommaInMethodDeclarationParametersOption != null) {
- this.insert_space_after_comma_in_method_declaration_parameters = JavaScriptCore.INSERT.equals(insertSpaceAfterCommaInMethodDeclarationParametersOption);
- }
- final Object insertSpaceAfterCommaInMethodDeclarationThrowsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_METHOD_DECLARATION_THROWS);
- if (insertSpaceAfterCommaInMethodDeclarationThrowsOption != null) {
- this.insert_space_after_comma_in_method_declaration_throws = JavaScriptCore.INSERT.equals(insertSpaceAfterCommaInMethodDeclarationThrowsOption);
- }
- final Object insertSpaceAfterCommaInMultipleFieldDeclarationsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_MULTIPLE_FIELD_DECLARATIONS);
- if (insertSpaceAfterCommaInMultipleFieldDeclarationsOption != null) {
- this.insert_space_after_comma_in_multiple_field_declarations = JavaScriptCore.INSERT.equals(insertSpaceAfterCommaInMultipleFieldDeclarationsOption);
- }
- final Object insertSpaceAfterCommaInMultipleLocalDeclarationsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_MULTIPLE_LOCAL_DECLARATIONS);
- if (insertSpaceAfterCommaInMultipleLocalDeclarationsOption != null) {
- this.insert_space_after_comma_in_multiple_local_declarations = JavaScriptCore.INSERT.equals(insertSpaceAfterCommaInMultipleLocalDeclarationsOption);
- }
- final Object insertSpaceAfterCommaInParameterizedTypeReferenceOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_PARAMETERIZED_TYPE_REFERENCE);
- if (insertSpaceAfterCommaInParameterizedTypeReferenceOption != null) {
- this.insert_space_after_comma_in_parameterized_type_reference = JavaScriptCore.INSERT.equals(insertSpaceAfterCommaInParameterizedTypeReferenceOption);
- }
- final Object insertSpaceAfterCommaInSuperinterfacesOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_SUPERINTERFACES);
- if (insertSpaceAfterCommaInSuperinterfacesOption != null) {
- this.insert_space_after_comma_in_superinterfaces = JavaScriptCore.INSERT.equals(insertSpaceAfterCommaInSuperinterfacesOption);
- }
- final Object insertSpaceAfterCommaInTypeArgumentsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_TYPE_ARGUMENTS);
- if (insertSpaceAfterCommaInTypeArgumentsOption != null) {
- this.insert_space_after_comma_in_type_arguments = JavaScriptCore.INSERT.equals(insertSpaceAfterCommaInTypeArgumentsOption);
- }
- final Object insertSpaceAfterCommaInTypeParametersOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_TYPE_PARAMETERS);
- if (insertSpaceAfterCommaInTypeParametersOption != null) {
- this.insert_space_after_comma_in_type_parameters = JavaScriptCore.INSERT.equals(insertSpaceAfterCommaInTypeParametersOption);
- }
- final Object insertSpaceAfterEllipsisOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_ELLIPSIS);
- if (insertSpaceAfterEllipsisOption != null) {
- this.insert_space_after_ellipsis = JavaScriptCore.INSERT.equals(insertSpaceAfterEllipsisOption);
- }
- final Object insertSpaceAfterOpeningAngleBracketInParameterizedTypeReferenceOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_ANGLE_BRACKET_IN_PARAMETERIZED_TYPE_REFERENCE);
- if (insertSpaceAfterOpeningAngleBracketInParameterizedTypeReferenceOption != null) {
- this.insert_space_after_opening_angle_bracket_in_parameterized_type_reference = JavaScriptCore.INSERT.equals(insertSpaceAfterOpeningAngleBracketInParameterizedTypeReferenceOption);
- }
- final Object insertSpaceAfterOpeningAngleBracketInTypeArgumentsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_ANGLE_BRACKET_IN_TYPE_ARGUMENTS);
- if (insertSpaceAfterOpeningAngleBracketInTypeArgumentsOption != null) {
- this.insert_space_after_opening_angle_bracket_in_type_arguments = JavaScriptCore.INSERT.equals(insertSpaceAfterOpeningAngleBracketInTypeArgumentsOption);
- }
- final Object insertSpaceAfterOpeningAngleBracketInTypeParametersOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_ANGLE_BRACKET_IN_TYPE_PARAMETERS);
- if (insertSpaceAfterOpeningAngleBracketInTypeParametersOption != null) {
- this.insert_space_after_opening_angle_bracket_in_type_parameters = JavaScriptCore.INSERT.equals(insertSpaceAfterOpeningAngleBracketInTypeParametersOption);
- }
- final Object insertSpaceAfterOpeningBracketInArrayAllocationExpressionOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_BRACKET_IN_ARRAY_ALLOCATION_EXPRESSION);
- if (insertSpaceAfterOpeningBracketInArrayAllocationExpressionOption != null) {
- this.insert_space_after_opening_bracket_in_array_allocation_expression = JavaScriptCore.INSERT.equals(insertSpaceAfterOpeningBracketInArrayAllocationExpressionOption);
- }
- final Object insertSpaceAfterOpeningBracketInArrayReferenceOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_BRACKET_IN_ARRAY_REFERENCE);
- if (insertSpaceAfterOpeningBracketInArrayReferenceOption != null) {
- this.insert_space_after_opening_bracket_in_array_reference = JavaScriptCore.INSERT.equals(insertSpaceAfterOpeningBracketInArrayReferenceOption);
- }
- final Object insertSpaceAfterOpeningBraceInArrayInitializerOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_BRACE_IN_ARRAY_INITIALIZER);
- if (insertSpaceAfterOpeningBraceInArrayInitializerOption != null) {
- this.insert_space_after_opening_brace_in_array_initializer = JavaScriptCore.INSERT.equals(insertSpaceAfterOpeningBraceInArrayInitializerOption);
- }
- final Object insertSpaceAfterOpeningParenInAnnotationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_ANNOTATION);
- if (insertSpaceAfterOpeningParenInAnnotationOption != null) {
- this.insert_space_after_opening_paren_in_annotation = JavaScriptCore.INSERT.equals(insertSpaceAfterOpeningParenInAnnotationOption);
- }
- final Object insertSpaceAfterOpeningParenInCastOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_CAST);
- if (insertSpaceAfterOpeningParenInCastOption != null) {
- this.insert_space_after_opening_paren_in_cast = JavaScriptCore.INSERT.equals(insertSpaceAfterOpeningParenInCastOption);
- }
- final Object insertSpaceAfterOpeningParenInCatchOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_CATCH);
- if (insertSpaceAfterOpeningParenInCatchOption != null) {
- this.insert_space_after_opening_paren_in_catch = JavaScriptCore.INSERT.equals(insertSpaceAfterOpeningParenInCatchOption);
- }
- final Object insertSpaceAfterOpeningParenInConstructorDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_CONSTRUCTOR_DECLARATION);
- if (insertSpaceAfterOpeningParenInConstructorDeclarationOption != null) {
- this.insert_space_after_opening_paren_in_constructor_declaration = JavaScriptCore.INSERT.equals(insertSpaceAfterOpeningParenInConstructorDeclarationOption);
- }
- final Object insertSpaceAfterOpeningParenInEnumConstantOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_ENUM_CONSTANT);
- if (insertSpaceAfterOpeningParenInEnumConstantOption != null) {
- this.insert_space_after_opening_paren_in_enum_constant = JavaScriptCore.INSERT.equals(insertSpaceAfterOpeningParenInEnumConstantOption);
- }
- final Object insertSpaceAfterOpeningParenInForOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_FOR);
- if (insertSpaceAfterOpeningParenInForOption != null) {
- this.insert_space_after_opening_paren_in_for = JavaScriptCore.INSERT.equals(insertSpaceAfterOpeningParenInForOption);
- }
- final Object insertSpaceAfterOpeningParenInIfOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_IF);
- if (insertSpaceAfterOpeningParenInIfOption != null) {
- this.insert_space_after_opening_paren_in_if = JavaScriptCore.INSERT.equals(insertSpaceAfterOpeningParenInIfOption);
- }
- final Object insertSpaceAfterOpeningParenInMethodDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_METHOD_DECLARATION);
- if (insertSpaceAfterOpeningParenInMethodDeclarationOption != null) {
- this.insert_space_after_opening_paren_in_method_declaration = JavaScriptCore.INSERT.equals(insertSpaceAfterOpeningParenInMethodDeclarationOption);
- }
- final Object insertSpaceAfterOpeningParenInMethodInvocationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_METHOD_INVOCATION);
- if (insertSpaceAfterOpeningParenInMethodInvocationOption != null) {
- this.insert_space_after_opening_paren_in_method_invocation = JavaScriptCore.INSERT.equals(insertSpaceAfterOpeningParenInMethodInvocationOption);
- }
- final Object insertSpaceAfterOpeningParenInParenthesizedExpressionOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_PARENTHESIZED_EXPRESSION);
- if (insertSpaceAfterOpeningParenInParenthesizedExpressionOption != null) {
- this.insert_space_after_opening_paren_in_parenthesized_expression = JavaScriptCore.INSERT.equals(insertSpaceAfterOpeningParenInParenthesizedExpressionOption);
- }
- final Object insertSpaceAfterOpeningParenInSwitchOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_SWITCH);
- if (insertSpaceAfterOpeningParenInSwitchOption != null) {
- this.insert_space_after_opening_paren_in_switch = JavaScriptCore.INSERT.equals(insertSpaceAfterOpeningParenInSwitchOption);
- }
- final Object insertSpaceAfterOpeningParenInSynchronizedOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_SYNCHRONIZED);
- if (insertSpaceAfterOpeningParenInSynchronizedOption != null) {
- this.insert_space_after_opening_paren_in_synchronized = JavaScriptCore.INSERT.equals(insertSpaceAfterOpeningParenInSynchronizedOption);
- }
- final Object insertSpaceAfterOpeningParenInWhileOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_WHILE);
- if (insertSpaceAfterOpeningParenInWhileOption != null) {
- this.insert_space_after_opening_paren_in_while = JavaScriptCore.INSERT.equals(insertSpaceAfterOpeningParenInWhileOption);
- }
- final Object insertSpaceAfterPostfixOperatorOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_POSTFIX_OPERATOR);
- if (insertSpaceAfterPostfixOperatorOption != null) {
- this.insert_space_after_postfix_operator = JavaScriptCore.INSERT.equals(insertSpaceAfterPostfixOperatorOption);
- }
- final Object insertSpaceAfterPrefixOperatorOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_PREFIX_OPERATOR);
- if (insertSpaceAfterPrefixOperatorOption != null) {
- this.insert_space_after_prefix_operator = JavaScriptCore.INSERT.equals(insertSpaceAfterPrefixOperatorOption);
- }
- final Object insertSpaceAfterQuestionInConditionalOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_QUESTION_IN_CONDITIONAL);
- if (insertSpaceAfterQuestionInConditionalOption != null) {
- this.insert_space_after_question_in_conditional = JavaScriptCore.INSERT.equals(insertSpaceAfterQuestionInConditionalOption);
- }
- final Object insertSpaceAfterSemicolonInForOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_SEMICOLON_IN_FOR);
- if (insertSpaceAfterSemicolonInForOption != null) {
- this.insert_space_after_semicolon_in_for = JavaScriptCore.INSERT.equals(insertSpaceAfterSemicolonInForOption);
- }
- final Object insertSpaceAfterUnaryOperatorOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_UNARY_OPERATOR);
- if (insertSpaceAfterUnaryOperatorOption != null) {
- this.insert_space_after_unary_operator = JavaScriptCore.INSERT.equals(insertSpaceAfterUnaryOperatorOption);
- }
- final Object insertSpaceBeforeAtInAnnotationTypeDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_AT_IN_ANNOTATION_TYPE_DECLARATION);
- if (insertSpaceBeforeAtInAnnotationTypeDeclarationOption != null) {
- this.insert_space_before_at_in_annotation_type_declaration = JavaScriptCore.INSERT.equals(insertSpaceBeforeAtInAnnotationTypeDeclarationOption);
- }
- final Object insertSpaceBeforeAssignmentOperatorOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_ASSIGNMENT_OPERATOR);
- if (insertSpaceBeforeAssignmentOperatorOption != null) {
- this.insert_space_before_assignment_operator = JavaScriptCore.INSERT.equals(insertSpaceBeforeAssignmentOperatorOption);
- }
- final Object insertSpaceBeforeBinaryOperatorOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_BINARY_OPERATOR);
- if (insertSpaceBeforeBinaryOperatorOption != null) {
- this.insert_space_before_binary_operator = JavaScriptCore.INSERT.equals(insertSpaceBeforeBinaryOperatorOption);
- }
- final Object insertSpaceBeforeClosingAngleBracketInParameterizedTypeReferenceOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_ANGLE_BRACKET_IN_PARAMETERIZED_TYPE_REFERENCE);
- if (insertSpaceBeforeClosingAngleBracketInParameterizedTypeReferenceOption != null) {
- this.insert_space_before_closing_angle_bracket_in_parameterized_type_reference = JavaScriptCore.INSERT.equals(insertSpaceBeforeClosingAngleBracketInParameterizedTypeReferenceOption);
- }
- final Object insertSpaceBeforeClosingAngleBracketInTypeArgumentsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_ANGLE_BRACKET_IN_TYPE_ARGUMENTS);
- if (insertSpaceBeforeClosingAngleBracketInTypeArgumentsOption != null) {
- this.insert_space_before_closing_angle_bracket_in_type_arguments = JavaScriptCore.INSERT.equals(insertSpaceBeforeClosingAngleBracketInTypeArgumentsOption);
- }
- final Object insertSpaceBeforeClosingAngleBracketInTypeParametersOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_ANGLE_BRACKET_IN_TYPE_PARAMETERS);
- if (insertSpaceBeforeClosingAngleBracketInTypeParametersOption != null) {
- this.insert_space_before_closing_angle_bracket_in_type_parameters = JavaScriptCore.INSERT.equals(insertSpaceBeforeClosingAngleBracketInTypeParametersOption);
- }
- final Object insertSpaceBeforeClosingBraceInArrayInitializerOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_BRACE_IN_ARRAY_INITIALIZER);
- if (insertSpaceBeforeClosingBraceInArrayInitializerOption != null) {
- this.insert_space_before_closing_brace_in_array_initializer = JavaScriptCore.INSERT.equals(insertSpaceBeforeClosingBraceInArrayInitializerOption);
- }
- final Object insertSpaceBeforeClosingBracketInArrayAllocationExpressionOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_BRACKET_IN_ARRAY_ALLOCATION_EXPRESSION);
- if (insertSpaceBeforeClosingBracketInArrayAllocationExpressionOption != null) {
- this.insert_space_before_closing_bracket_in_array_allocation_expression = JavaScriptCore.INSERT.equals(insertSpaceBeforeClosingBracketInArrayAllocationExpressionOption);
- }
- final Object insertSpaceBeforeClosingBracketInArrayReferenceOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_BRACKET_IN_ARRAY_REFERENCE);
- if (insertSpaceBeforeClosingBracketInArrayReferenceOption != null) {
- this.insert_space_before_closing_bracket_in_array_reference = JavaScriptCore.INSERT.equals(insertSpaceBeforeClosingBracketInArrayReferenceOption);
- }
- final Object insertSpaceBeforeClosingParenInAnnotationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_ANNOTATION);
- if (insertSpaceBeforeClosingParenInAnnotationOption != null) {
- this.insert_space_before_closing_paren_in_annotation = JavaScriptCore.INSERT.equals(insertSpaceBeforeClosingParenInAnnotationOption);
- }
- final Object insertSpaceBeforeClosingParenInCastOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_CAST);
- if (insertSpaceBeforeClosingParenInCastOption != null) {
- this.insert_space_before_closing_paren_in_cast = JavaScriptCore.INSERT.equals(insertSpaceBeforeClosingParenInCastOption);
- }
- final Object insertSpaceBeforeClosingParenInCatchOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_CATCH);
- if (insertSpaceBeforeClosingParenInCatchOption != null) {
- this.insert_space_before_closing_paren_in_catch = JavaScriptCore.INSERT.equals(insertSpaceBeforeClosingParenInCatchOption);
- }
- final Object insertSpaceBeforeClosingParenInConstructorDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_CONSTRUCTOR_DECLARATION);
- if (insertSpaceBeforeClosingParenInConstructorDeclarationOption != null) {
- this.insert_space_before_closing_paren_in_constructor_declaration = JavaScriptCore.INSERT.equals(insertSpaceBeforeClosingParenInConstructorDeclarationOption);
- }
- final Object insertSpaceBeforeClosingParenInEnumConstantOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_ENUM_CONSTANT);
- if (insertSpaceBeforeClosingParenInEnumConstantOption != null) {
- this.insert_space_before_closing_paren_in_enum_constant = JavaScriptCore.INSERT.equals(insertSpaceBeforeClosingParenInEnumConstantOption);
- }
- final Object insertSpaceBeforeClosingParenInForOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_FOR);
- if (insertSpaceBeforeClosingParenInForOption != null) {
- this.insert_space_before_closing_paren_in_for = JavaScriptCore.INSERT.equals(insertSpaceBeforeClosingParenInForOption);
- }
- final Object insertSpaceBeforeClosingParenInIfOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_IF);
- if (insertSpaceBeforeClosingParenInIfOption != null) {
- this.insert_space_before_closing_paren_in_if = JavaScriptCore.INSERT.equals(insertSpaceBeforeClosingParenInIfOption);
- }
- final Object insertSpaceBeforeClosingParenInMethodDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_METHOD_DECLARATION);
- if (insertSpaceBeforeClosingParenInMethodDeclarationOption != null) {
- this.insert_space_before_closing_paren_in_method_declaration = JavaScriptCore.INSERT.equals(insertSpaceBeforeClosingParenInMethodDeclarationOption);
- }
- final Object insertSpaceBeforeClosingParenInMethodInvocationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_METHOD_INVOCATION);
- if (insertSpaceBeforeClosingParenInMethodInvocationOption != null) {
- this.insert_space_before_closing_paren_in_method_invocation = JavaScriptCore.INSERT.equals(insertSpaceBeforeClosingParenInMethodInvocationOption);
- }
- final Object insertSpaceBeforeClosingParenInParenthesizedExpressionOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_PARENTHESIZED_EXPRESSION);
- if (insertSpaceBeforeClosingParenInParenthesizedExpressionOption != null) {
- this.insert_space_before_closing_paren_in_parenthesized_expression = JavaScriptCore.INSERT.equals(insertSpaceBeforeClosingParenInParenthesizedExpressionOption);
- }
- final Object insertSpaceBeforeClosingParenInSwitchOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_SWITCH);
- if (insertSpaceBeforeClosingParenInSwitchOption != null) {
- this.insert_space_before_closing_paren_in_switch = JavaScriptCore.INSERT.equals(insertSpaceBeforeClosingParenInSwitchOption);
- }
- final Object insertSpaceBeforeClosingParenInSynchronizedOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_SYNCHRONIZED);
- if (insertSpaceBeforeClosingParenInSynchronizedOption != null) {
- this.insert_space_before_closing_paren_in_synchronized = JavaScriptCore.INSERT.equals(insertSpaceBeforeClosingParenInSynchronizedOption);
- }
- final Object insertSpaceBeforeClosingParenInWhileOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_WHILE);
- if (insertSpaceBeforeClosingParenInWhileOption != null) {
- this.insert_space_before_closing_paren_in_while = JavaScriptCore.INSERT.equals(insertSpaceBeforeClosingParenInWhileOption);
- }
- final Object insertSpaceBeforeColonInAssertOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_ASSERT);
- if (insertSpaceBeforeColonInAssertOption != null) {
- this.insert_space_before_colon_in_assert = JavaScriptCore.INSERT.equals(insertSpaceBeforeColonInAssertOption);
- }
- final Object insertSpaceBeforeColonInCaseOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_CASE);
- if (insertSpaceBeforeColonInCaseOption != null) {
- this.insert_space_before_colon_in_case = JavaScriptCore.INSERT.equals(insertSpaceBeforeColonInCaseOption);
- }
- final Object insertSpaceBeforeColonInConditionalOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_CONDITIONAL);
- if (insertSpaceBeforeColonInConditionalOption != null) {
- this.insert_space_before_colon_in_conditional = JavaScriptCore.INSERT.equals(insertSpaceBeforeColonInConditionalOption);
- }
- final Object insertSpaceBeforeColonInObjectInitializerOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_OBJECT_INITIALIZER);
- if (insertSpaceBeforeColonInObjectInitializerOption != null) {
- this.insert_space_before_colon_in_object_initializer = JavaScriptCore.INSERT.equals(insertSpaceBeforeColonInObjectInitializerOption);
- }
- final Object insertSpaceBeforeColonInDefaultOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_DEFAULT);
- if (insertSpaceBeforeColonInDefaultOption != null) {
- this.insert_space_before_colon_in_default = JavaScriptCore.INSERT.equals(insertSpaceBeforeColonInDefaultOption);
- }
- final Object insertSpaceBeforeColonInForOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_FOR);
- if (insertSpaceBeforeColonInForOption != null) {
- this.insert_space_before_colon_in_for = JavaScriptCore.INSERT.equals(insertSpaceBeforeColonInForOption);
- }
- final Object insertSpaceBeforeColonInLabeledStatementOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_LABELED_STATEMENT);
- if (insertSpaceBeforeColonInLabeledStatementOption != null) {
- this.insert_space_before_colon_in_labeled_statement = JavaScriptCore.INSERT.equals(insertSpaceBeforeColonInLabeledStatementOption);
- }
- final Object insertSpaceBeforeCommaInAllocationExpressionOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_ALLOCATION_EXPRESSION);
- if (insertSpaceBeforeCommaInAllocationExpressionOption != null) {
- this.insert_space_before_comma_in_allocation_expression = JavaScriptCore.INSERT.equals(insertSpaceBeforeCommaInAllocationExpressionOption);
- }
- final Object insertSpaceBeforeCommaInAnnotationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_ANNOTATION);
- if (insertSpaceBeforeCommaInAnnotationOption != null) {
- this.insert_space_before_comma_in_annotation = JavaScriptCore.INSERT.equals(insertSpaceBeforeCommaInAnnotationOption);
- }
- final Object insertSpaceBeforeCommaInArrayInitializerOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_ARRAY_INITIALIZER);
- if (insertSpaceBeforeCommaInArrayInitializerOption != null) {
- this.insert_space_before_comma_in_array_initializer = JavaScriptCore.INSERT.equals(insertSpaceBeforeCommaInArrayInitializerOption);
- }
- final Object insertSpaceBeforeCommaInConstructorDeclarationParametersOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_CONSTRUCTOR_DECLARATION_PARAMETERS);
- if (insertSpaceBeforeCommaInConstructorDeclarationParametersOption != null) {
- this.insert_space_before_comma_in_constructor_declaration_parameters = JavaScriptCore.INSERT.equals(insertSpaceBeforeCommaInConstructorDeclarationParametersOption);
- }
- final Object insertSpaceBeforeCommaInConstructorDeclarationThrowsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_CONSTRUCTOR_DECLARATION_THROWS);
- if (insertSpaceBeforeCommaInConstructorDeclarationThrowsOption != null) {
- this.insert_space_before_comma_in_constructor_declaration_throws = JavaScriptCore.INSERT.equals(insertSpaceBeforeCommaInConstructorDeclarationThrowsOption);
- }
- final Object insertSpaceBeforeCommaInEnumConstantArgumentsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_ENUM_CONSTANT_ARGUMENTS);
- if (insertSpaceBeforeCommaInEnumConstantArgumentsOption != null) {
- this.insert_space_before_comma_in_enum_constant_arguments = JavaScriptCore.INSERT.equals(insertSpaceBeforeCommaInEnumConstantArgumentsOption);
- }
- final Object insertSpaceBeforeCommaInEnumDeclarationsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_ENUM_DECLARATIONS);
- if (insertSpaceBeforeCommaInEnumDeclarationsOption != null) {
- this.insert_space_before_comma_in_enum_declarations = JavaScriptCore.INSERT.equals(insertSpaceBeforeCommaInEnumDeclarationsOption);
- }
- final Object insertSpaceBeforeCommaInExplicitConstructorCallArgumentsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_EXPLICIT_CONSTRUCTOR_CALL_ARGUMENTS);
- if (insertSpaceBeforeCommaInExplicitConstructorCallArgumentsOption != null) {
- this.insert_space_before_comma_in_explicit_constructor_call_arguments = JavaScriptCore.INSERT.equals(insertSpaceBeforeCommaInExplicitConstructorCallArgumentsOption);
- }
- final Object insertSpaceBeforeCommaInForIncrementsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_FOR_INCREMENTS);
- if (insertSpaceBeforeCommaInForIncrementsOption != null) {
- this.insert_space_before_comma_in_for_increments = JavaScriptCore.INSERT.equals(insertSpaceBeforeCommaInForIncrementsOption);
- }
- final Object insertSpaceBeforeCommaInForInitsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_FOR_INITS);
- if (insertSpaceBeforeCommaInForInitsOption != null) {
- this.insert_space_before_comma_in_for_inits = JavaScriptCore.INSERT.equals(insertSpaceBeforeCommaInForInitsOption);
- }
- final Object insertSpaceBeforeCommaInMethodInvocationArgumentsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_METHOD_INVOCATION_ARGUMENTS);
- if (insertSpaceBeforeCommaInMethodInvocationArgumentsOption != null) {
- this.insert_space_before_comma_in_method_invocation_arguments = JavaScriptCore.INSERT.equals(insertSpaceBeforeCommaInMethodInvocationArgumentsOption);
- }
- final Object insertSpaceBeforeCommaInMethodDeclarationParametersOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_METHOD_DECLARATION_PARAMETERS);
- if (insertSpaceBeforeCommaInMethodDeclarationParametersOption != null) {
- this.insert_space_before_comma_in_method_declaration_parameters = JavaScriptCore.INSERT.equals(insertSpaceBeforeCommaInMethodDeclarationParametersOption);
- }
- final Object insertSpaceBeforeCommaInMethodDeclarationThrowsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_METHOD_DECLARATION_THROWS);
- if (insertSpaceBeforeCommaInMethodDeclarationThrowsOption != null) {
- this.insert_space_before_comma_in_method_declaration_throws = JavaScriptCore.INSERT.equals(insertSpaceBeforeCommaInMethodDeclarationThrowsOption);
- }
- final Object insertSpaceBeforeCommaInMultipleFieldDeclarationsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_MULTIPLE_FIELD_DECLARATIONS);
- if (insertSpaceBeforeCommaInMultipleFieldDeclarationsOption != null) {
- this.insert_space_before_comma_in_multiple_field_declarations = JavaScriptCore.INSERT.equals(insertSpaceBeforeCommaInMultipleFieldDeclarationsOption);
- }
- final Object insertSpaceBeforeCommaInMultipleLocalDeclarationsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_MULTIPLE_LOCAL_DECLARATIONS);
- if (insertSpaceBeforeCommaInMultipleLocalDeclarationsOption != null) {
- this.insert_space_before_comma_in_multiple_local_declarations = JavaScriptCore.INSERT.equals(insertSpaceBeforeCommaInMultipleLocalDeclarationsOption);
- }
- final Object insertSpaceBeforeCommaInParameterizedTypeReferenceOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_PARAMETERIZED_TYPE_REFERENCE);
- if (insertSpaceBeforeCommaInParameterizedTypeReferenceOption != null) {
- this.insert_space_before_comma_in_parameterized_type_reference = JavaScriptCore.INSERT.equals(insertSpaceBeforeCommaInParameterizedTypeReferenceOption);
- }
- final Object insertSpaceBeforeCommaInSuperinterfacesOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_SUPERINTERFACES);
- if (insertSpaceBeforeCommaInSuperinterfacesOption != null) {
- this.insert_space_before_comma_in_superinterfaces = JavaScriptCore.INSERT.equals(insertSpaceBeforeCommaInSuperinterfacesOption);
- }
- final Object insertSpaceBeforeCommaInTypeArgumentsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_TYPE_ARGUMENTS);
- if (insertSpaceBeforeCommaInTypeArgumentsOption != null) {
- this.insert_space_before_comma_in_type_arguments = JavaScriptCore.INSERT.equals(insertSpaceBeforeCommaInTypeArgumentsOption);
- }
- final Object insertSpaceBeforeCommaInTypeParametersOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_TYPE_PARAMETERS);
- if (insertSpaceBeforeCommaInTypeParametersOption != null) {
- this.insert_space_before_comma_in_type_parameters = JavaScriptCore.INSERT.equals(insertSpaceBeforeCommaInTypeParametersOption);
- }
- final Object insertSpaceBeforeEllipsisOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_ELLIPSIS);
- if (insertSpaceBeforeEllipsisOption != null) {
- this.insert_space_before_ellipsis = JavaScriptCore.INSERT.equals(insertSpaceBeforeEllipsisOption);
- }
- final Object insertSpaceBeforeOpeningAngleBrackerInParameterizedTypeReferenceOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_ANGLE_BRACKET_IN_PARAMETERIZED_TYPE_REFERENCE);
- if (insertSpaceBeforeOpeningAngleBrackerInParameterizedTypeReferenceOption != null) {
- this.insert_space_before_opening_angle_bracket_in_parameterized_type_reference = JavaScriptCore.INSERT.equals(insertSpaceBeforeOpeningAngleBrackerInParameterizedTypeReferenceOption);
- }
- final Object insertSpaceBeforeOpeningAngleBrackerInTypeArgumentsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_ANGLE_BRACKET_IN_TYPE_ARGUMENTS);
- if (insertSpaceBeforeOpeningAngleBrackerInTypeArgumentsOption != null) {
- this.insert_space_before_opening_angle_bracket_in_type_arguments = JavaScriptCore.INSERT.equals(insertSpaceBeforeOpeningAngleBrackerInTypeArgumentsOption);
- }
- final Object insertSpaceBeforeOpeningAngleBrackerInTypeParametersOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_ANGLE_BRACKET_IN_TYPE_PARAMETERS);
- if (insertSpaceBeforeOpeningAngleBrackerInTypeParametersOption != null) {
- this.insert_space_before_opening_angle_bracket_in_type_parameters = JavaScriptCore.INSERT.equals(insertSpaceBeforeOpeningAngleBrackerInTypeParametersOption);
- }
- final Object insertSpaceBeforeOpeningBraceInAnnotationTypeDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_ANNOTATION_TYPE_DECLARATION);
- if (insertSpaceBeforeOpeningBraceInAnnotationTypeDeclarationOption != null) {
- this.insert_space_before_opening_brace_in_annotation_type_declaration = JavaScriptCore.INSERT.equals(insertSpaceBeforeOpeningBraceInAnnotationTypeDeclarationOption);
- }
- final Object insertSpaceBeforeOpeningBraceInAnonymousTypeDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_ANONYMOUS_TYPE_DECLARATION);
- if (insertSpaceBeforeOpeningBraceInAnonymousTypeDeclarationOption != null) {
- this.insert_space_before_opening_brace_in_anonymous_type_declaration = JavaScriptCore.INSERT.equals(insertSpaceBeforeOpeningBraceInAnonymousTypeDeclarationOption);
- }
- final Object insertSpaceBeforeOpeningBraceInBlockOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_BLOCK);
- if (insertSpaceBeforeOpeningBraceInBlockOption != null) {
- this.insert_space_before_opening_brace_in_block = JavaScriptCore.INSERT.equals(insertSpaceBeforeOpeningBraceInBlockOption);
- }
- final Object insertSpaceBeforeOpeningBraceInConstructorDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_CONSTRUCTOR_DECLARATION);
- if (insertSpaceBeforeOpeningBraceInConstructorDeclarationOption != null) {
- this.insert_space_before_opening_brace_in_constructor_declaration = JavaScriptCore.INSERT.equals(insertSpaceBeforeOpeningBraceInConstructorDeclarationOption);
- }
- final Object insertSpaceBeforeOpeningBraceInEnumDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_ENUM_DECLARATION);
- if (insertSpaceBeforeOpeningBraceInEnumDeclarationOption != null) {
- this.insert_space_before_opening_brace_in_enum_declaration = JavaScriptCore.INSERT.equals(insertSpaceBeforeOpeningBraceInEnumDeclarationOption);
- }
- final Object insertSpaceBeforeOpeningBraceInEnumConstantOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_ENUM_CONSTANT);
- if (insertSpaceBeforeOpeningBraceInEnumConstantOption != null) {
- this.insert_space_before_opening_brace_in_enum_constant = JavaScriptCore.INSERT.equals(insertSpaceBeforeOpeningBraceInEnumConstantOption);
- }
- final Object insertSpaceBeforeOpeningBraceInMethodDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_METHOD_DECLARATION);
- if (insertSpaceBeforeOpeningBraceInMethodDeclarationOption != null) {
- this.insert_space_before_opening_brace_in_method_declaration = JavaScriptCore.INSERT.equals(insertSpaceBeforeOpeningBraceInMethodDeclarationOption);
- }
- final Object insertSpaceBeforeOpeningBraceInTypeDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_TYPE_DECLARATION);
- if (insertSpaceBeforeOpeningBraceInTypeDeclarationOption != null) {
- this.insert_space_before_opening_brace_in_type_declaration = JavaScriptCore.INSERT.equals(insertSpaceBeforeOpeningBraceInTypeDeclarationOption);
- }
- final Object insertSpaceBeforeOpeningBracketInArrayAllocationExpressionOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACKET_IN_ARRAY_ALLOCATION_EXPRESSION);
- if (insertSpaceBeforeOpeningBracketInArrayAllocationExpressionOption != null) {
- this.insert_space_before_opening_bracket_in_array_allocation_expression = JavaScriptCore.INSERT.equals(insertSpaceBeforeOpeningBracketInArrayAllocationExpressionOption);
- }
- final Object insertSpaceBeforeOpeningBracketInArrayReferenceOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACKET_IN_ARRAY_REFERENCE);
- if (insertSpaceBeforeOpeningBracketInArrayReferenceOption != null) {
- this.insert_space_before_opening_bracket_in_array_reference = JavaScriptCore.INSERT.equals(insertSpaceBeforeOpeningBracketInArrayReferenceOption);
- }
- final Object insertSpaceBeforeOpeningBracketInArrayTypeReferenceOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACKET_IN_ARRAY_TYPE_REFERENCE);
- if (insertSpaceBeforeOpeningBracketInArrayTypeReferenceOption != null) {
- this.insert_space_before_opening_bracket_in_array_type_reference = JavaScriptCore.INSERT.equals(insertSpaceBeforeOpeningBracketInArrayTypeReferenceOption);
- }
- final Object insertSpaceBeforeOpeningParenInAnnotationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_ANNOTATION);
- if (insertSpaceBeforeOpeningParenInAnnotationOption != null) {
- this.insert_space_before_opening_paren_in_annotation = JavaScriptCore.INSERT.equals(insertSpaceBeforeOpeningParenInAnnotationOption);
- }
- final Object insertSpaceBeforeOpeningParenInAnnotationTypeMemberDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_ANNOTATION_TYPE_MEMBER_DECLARATION);
- if (insertSpaceBeforeOpeningParenInAnnotationTypeMemberDeclarationOption != null) {
- this.insert_space_before_opening_paren_in_annotation_type_member_declaration = JavaScriptCore.INSERT.equals(insertSpaceBeforeOpeningParenInAnnotationTypeMemberDeclarationOption);
- }
- final Object insertSpaceBeforeOpeningParenInCatchOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_CATCH);
- if (insertSpaceBeforeOpeningParenInCatchOption != null) {
- this.insert_space_before_opening_paren_in_catch = JavaScriptCore.INSERT.equals(insertSpaceBeforeOpeningParenInCatchOption);
- }
- final Object insertSpaceBeforeOpeningParenInConstructorDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_CONSTRUCTOR_DECLARATION);
- if (insertSpaceBeforeOpeningParenInConstructorDeclarationOption != null) {
- this.insert_space_before_opening_paren_in_constructor_declaration = JavaScriptCore.INSERT.equals(insertSpaceBeforeOpeningParenInConstructorDeclarationOption);
- }
- final Object insertSpaceBeforeOpeningParenInEnumConstantOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_ENUM_CONSTANT);
- if (insertSpaceBeforeOpeningParenInEnumConstantOption != null) {
- this.insert_space_before_opening_paren_in_enum_constant = JavaScriptCore.INSERT.equals(insertSpaceBeforeOpeningParenInEnumConstantOption);
- }
- final Object insertSpaceBeforeOpeningParenInForOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_FOR);
- if (insertSpaceBeforeOpeningParenInForOption != null) {
- this.insert_space_before_opening_paren_in_for = JavaScriptCore.INSERT.equals(insertSpaceBeforeOpeningParenInForOption);
- }
- final Object insertSpaceBeforeOpeningParenInIfOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_IF);
- if (insertSpaceBeforeOpeningParenInIfOption != null) {
- this.insert_space_before_opening_paren_in_if = JavaScriptCore.INSERT.equals(insertSpaceBeforeOpeningParenInIfOption);
- }
- final Object insertSpaceBeforeOpeningParenInMethodInvocationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_METHOD_INVOCATION);
- if (insertSpaceBeforeOpeningParenInMethodInvocationOption != null) {
- this.insert_space_before_opening_paren_in_method_invocation = JavaScriptCore.INSERT.equals(insertSpaceBeforeOpeningParenInMethodInvocationOption);
- }
- final Object insertSpaceBeforeOpeningParenInMethodDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_METHOD_DECLARATION);
- if (insertSpaceBeforeOpeningParenInMethodDeclarationOption != null) {
- this.insert_space_before_opening_paren_in_method_declaration = JavaScriptCore.INSERT.equals(insertSpaceBeforeOpeningParenInMethodDeclarationOption);
- }
- final Object insertSpaceBeforeOpeningParenInSwitchOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_SWITCH);
- if (insertSpaceBeforeOpeningParenInSwitchOption != null) {
- this.insert_space_before_opening_paren_in_switch = JavaScriptCore.INSERT.equals(insertSpaceBeforeOpeningParenInSwitchOption);
- }
- final Object insertSpaceBeforeOpeningBraceInSwitchOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_SWITCH);
- if (insertSpaceBeforeOpeningBraceInSwitchOption != null) {
- this.insert_space_before_opening_brace_in_switch = JavaScriptCore.INSERT.equals(insertSpaceBeforeOpeningBraceInSwitchOption);
- }
- final Object insertSpaceBeforeOpeningParenInSynchronizedOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_SYNCHRONIZED);
- if (insertSpaceBeforeOpeningParenInSynchronizedOption != null) {
- this.insert_space_before_opening_paren_in_synchronized = JavaScriptCore.INSERT.equals(insertSpaceBeforeOpeningParenInSynchronizedOption);
- }
- final Object insertSpaceBeforeOpeningParenInParenthesizedExpressionOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_PARENTHESIZED_EXPRESSION);
- if (insertSpaceBeforeOpeningParenInParenthesizedExpressionOption != null) {
- this.insert_space_before_opening_paren_in_parenthesized_expression = JavaScriptCore.INSERT.equals(insertSpaceBeforeOpeningParenInParenthesizedExpressionOption);
- }
- final Object insertSpaceBeforeOpeningParenInWhileOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_WHILE);
- if (insertSpaceBeforeOpeningParenInWhileOption != null) {
- this.insert_space_before_opening_paren_in_while = JavaScriptCore.INSERT.equals(insertSpaceBeforeOpeningParenInWhileOption);
- }
- final Object insertSpaceBeforeParenthesizedExpressionInReturnOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_PARENTHESIZED_EXPRESSION_IN_RETURN);
- if (insertSpaceBeforeParenthesizedExpressionInReturnOption != null) {
- this.insert_space_before_parenthesized_expression_in_return = JavaScriptCore.INSERT.equals(insertSpaceBeforeParenthesizedExpressionInReturnOption);
- }
- final Object insertSpaceBeforeParenthesizedExpressionInThrowOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_PARENTHESIZED_EXPRESSION_IN_THROW);
- if (insertSpaceBeforeParenthesizedExpressionInThrowOption != null) {
- this.insert_space_before_parenthesized_expression_in_throw = JavaScriptCore.INSERT.equals(insertSpaceBeforeParenthesizedExpressionInThrowOption);
- }
- final Object insertSpaceBeforePostfixOperatorOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_POSTFIX_OPERATOR);
- if (insertSpaceBeforePostfixOperatorOption != null) {
- this.insert_space_before_postfix_operator = JavaScriptCore.INSERT.equals(insertSpaceBeforePostfixOperatorOption);
- }
- final Object insertSpaceBeforePrefixOperatorOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_PREFIX_OPERATOR);
- if (insertSpaceBeforePrefixOperatorOption != null) {
- this.insert_space_before_prefix_operator = JavaScriptCore.INSERT.equals(insertSpaceBeforePrefixOperatorOption);
- }
- final Object insertSpaceBeforeQuestionInConditionalOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_QUESTION_IN_CONDITIONAL);
- if (insertSpaceBeforeQuestionInConditionalOption != null) {
- this.insert_space_before_question_in_conditional = JavaScriptCore.INSERT.equals(insertSpaceBeforeQuestionInConditionalOption);
- }
- final Object insertSpaceBeforeSemicolonOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_SEMICOLON);
- if (insertSpaceBeforeSemicolonOption != null) {
- this.insert_space_before_semicolon = JavaScriptCore.INSERT.equals(insertSpaceBeforeSemicolonOption);
- }
- final Object insertSpaceBeforeSemicolonInForOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_SEMICOLON_IN_FOR);
- if (insertSpaceBeforeSemicolonInForOption != null) {
- this.insert_space_before_semicolon_in_for = JavaScriptCore.INSERT.equals(insertSpaceBeforeSemicolonInForOption);
- }
- final Object insertSpaceBeforeUnaryOperatorOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_UNARY_OPERATOR);
- if (insertSpaceBeforeUnaryOperatorOption != null) {
- this.insert_space_before_unary_operator = JavaScriptCore.INSERT.equals(insertSpaceBeforeUnaryOperatorOption);
- }
- final Object insertSpaceBetweenBracketsInArrayTypeReferenceOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_BRACKETS_IN_ARRAY_TYPE_REFERENCE);
- if (insertSpaceBetweenBracketsInArrayTypeReferenceOption != null) {
- this.insert_space_between_brackets_in_array_type_reference = JavaScriptCore.INSERT.equals(insertSpaceBetweenBracketsInArrayTypeReferenceOption);
- }
- final Object insertSpaceBetweenEmptyBracesInArrayInitializerOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_BRACES_IN_ARRAY_INITIALIZER);
- if (insertSpaceBetweenEmptyBracesInArrayInitializerOption != null) {
- this.insert_space_between_empty_braces_in_array_initializer = JavaScriptCore.INSERT.equals(insertSpaceBetweenEmptyBracesInArrayInitializerOption);
- }
- final Object insertSpaceBetweenEmptyBracketsInArrayAllocationExpressionOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_BRACKETS_IN_ARRAY_ALLOCATION_EXPRESSION);
- if (insertSpaceBetweenEmptyBracketsInArrayAllocationExpressionOption != null) {
- this.insert_space_between_empty_brackets_in_array_allocation_expression = JavaScriptCore.INSERT.equals(insertSpaceBetweenEmptyBracketsInArrayAllocationExpressionOption);
- }
- final Object insertSpaceBetweenEmptyParensInConstructorDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_CONSTRUCTOR_DECLARATION);
- if (insertSpaceBetweenEmptyParensInConstructorDeclarationOption != null) {
- this.insert_space_between_empty_parens_in_constructor_declaration = JavaScriptCore.INSERT.equals(insertSpaceBetweenEmptyParensInConstructorDeclarationOption);
- }
- final Object insertSpaceBetweenEmptyParensInAnnotationTypeMemberDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_ANNOTATION_TYPE_MEMBER_DECLARATION);
- if (insertSpaceBetweenEmptyParensInAnnotationTypeMemberDeclarationOption != null) {
- this.insert_space_between_empty_parens_in_annotation_type_member_declaration = JavaScriptCore.INSERT.equals(insertSpaceBetweenEmptyParensInAnnotationTypeMemberDeclarationOption);
- }
- final Object insertSpaceBetweenEmptyParensInEnumConstantOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_ENUM_CONSTANT);
- if (insertSpaceBetweenEmptyParensInEnumConstantOption != null) {
- this.insert_space_between_empty_parens_in_enum_constant = JavaScriptCore.INSERT.equals(insertSpaceBetweenEmptyParensInEnumConstantOption);
- }
- final Object insertSpaceBetweenEmptyParensInMethodDeclarationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_METHOD_DECLARATION);
- if (insertSpaceBetweenEmptyParensInMethodDeclarationOption != null) {
- this.insert_space_between_empty_parens_in_method_declaration = JavaScriptCore.INSERT.equals(insertSpaceBetweenEmptyParensInMethodDeclarationOption);
- }
- final Object insertSpaceBetweenEmptyParensInMethodInvocationOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_METHOD_INVOCATION);
- if (insertSpaceBetweenEmptyParensInMethodInvocationOption != null) {
- this.insert_space_between_empty_parens_in_method_invocation = JavaScriptCore.INSERT.equals(insertSpaceBetweenEmptyParensInMethodInvocationOption);
- }
- final Object compactElseIfOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_COMPACT_ELSE_IF);
- if (compactElseIfOption != null) {
- this.compact_else_if = DefaultCodeFormatterConstants.TRUE.equals(compactElseIfOption);
- }
- final Object keepGuardianClauseOnOneLineOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_KEEP_GUARDIAN_CLAUSE_ON_ONE_LINE);
- if (keepGuardianClauseOnOneLineOption != null) {
- this.keep_guardian_clause_on_one_line = DefaultCodeFormatterConstants.TRUE.equals(keepGuardianClauseOnOneLineOption);
- }
- final Object keepElseStatementOnSameLineOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_KEEP_ELSE_STATEMENT_ON_SAME_LINE);
- if (keepElseStatementOnSameLineOption != null) {
- this.keep_else_statement_on_same_line = DefaultCodeFormatterConstants.TRUE.equals(keepElseStatementOnSameLineOption);
- }
- final Object keepEmptyArrayInitializerOnOneLineOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_KEEP_EMPTY_ARRAY_INITIALIZER_ON_ONE_LINE);
- if (keepEmptyArrayInitializerOnOneLineOption != null) {
- this.keep_empty_array_initializer_on_one_line = DefaultCodeFormatterConstants.TRUE.equals(keepEmptyArrayInitializerOnOneLineOption);
- }
- final Object keepEmptyObjLitInitializerOnOneLineOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_KEEP_EMPTY_OBJLIT_INITIALIZER_ON_ONE_LINE);
- if (keepEmptyObjLitInitializerOnOneLineOption != null) {
- this.keep_empty_objlit_initializer_on_one_line = DefaultCodeFormatterConstants.TRUE.equals(keepEmptyObjLitInitializerOnOneLineOption);
- }
- final Object keepSimpleIfOnOneLineOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_KEEP_SIMPLE_IF_ON_ONE_LINE);
- if (keepSimpleIfOnOneLineOption != null) {
- this.keep_simple_if_on_one_line = DefaultCodeFormatterConstants.TRUE.equals(keepSimpleIfOnOneLineOption);
- }
- final Object keepThenStatementOnSameLineOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_KEEP_THEN_STATEMENT_ON_SAME_LINE);
- if (keepThenStatementOnSameLineOption != null) {
- this.keep_then_statement_on_same_line = DefaultCodeFormatterConstants.TRUE.equals(keepThenStatementOnSameLineOption);
- }
- final Object neverIndentBlockCommentOnFirstColumnOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_NEVER_INDENT_BLOCK_COMMENTS_ON_FIRST_COLUMN);
- if (neverIndentBlockCommentOnFirstColumnOption != null) {
- this.never_indent_block_comments_on_first_column = DefaultCodeFormatterConstants.TRUE.equals(neverIndentBlockCommentOnFirstColumnOption);
- }
- final Object neverIndentLineCommentOnFirstColumnOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_NEVER_INDENT_LINE_COMMENTS_ON_FIRST_COLUMN);
- if (neverIndentLineCommentOnFirstColumnOption != null) {
- this.never_indent_line_comments_on_first_column = DefaultCodeFormatterConstants.TRUE.equals(neverIndentLineCommentOnFirstColumnOption);
- }
- final Object numberOfEmptyLinesToPreserveOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_NUMBER_OF_EMPTY_LINES_TO_PRESERVE);
- if (numberOfEmptyLinesToPreserveOption != null) {
- try {
- this.number_of_empty_lines_to_preserve = Integer.parseInt((String) numberOfEmptyLinesToPreserveOption);
- } catch (NumberFormatException e) {
- this.number_of_empty_lines_to_preserve = 0;
- } catch(ClassCastException e) {
- this.number_of_empty_lines_to_preserve = 0;
- }
- }
- final Object putEmptyStatementOnNewLineOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_PUT_EMPTY_STATEMENT_ON_NEW_LINE);
- if (putEmptyStatementOnNewLineOption != null) {
- this.put_empty_statement_on_new_line = DefaultCodeFormatterConstants.TRUE.equals(putEmptyStatementOnNewLineOption);
- }
- final Object tabSizeOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE);
- if (tabSizeOption != null) {
- try {
- this.tab_size = Integer.parseInt((String) tabSizeOption);
- } catch (NumberFormatException e) {
- this.tab_size = 4;
- } catch(ClassCastException e) {
- this.tab_size = 4;
- }
- }
- final Object useTabsOnlyForLeadingIndentationsOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_USE_TABS_ONLY_FOR_LEADING_INDENTATIONS);
- if (useTabsOnlyForLeadingIndentationsOption != null) {
- this.use_tabs_only_for_leading_indentations = DefaultCodeFormatterConstants.TRUE.equals(useTabsOnlyForLeadingIndentationsOption);
- }
- final Object pageWidthOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_LINE_SPLIT);
- if (pageWidthOption != null) {
- try {
- this.page_width = Integer.parseInt((String) pageWidthOption);
- } catch (NumberFormatException e) {
- this.page_width = 80;
- } catch(ClassCastException e) {
- this.page_width = 80;
- }
- }
- final Object useTabOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR);
- if (useTabOption != null) {
- if (JavaScriptCore.TAB.equals(useTabOption)) {
- this.tab_char = TAB;
- } else if (JavaScriptCore.SPACE.equals(useTabOption)) {
- this.tab_char = SPACE;
- } else {
- this.tab_char = MIXED;
- }
- }
- final Object wrapBeforeBinaryOperatorOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_WRAP_BEFORE_BINARY_OPERATOR);
- if (wrapBeforeBinaryOperatorOption != null) {
- this.wrap_before_binary_operator = DefaultCodeFormatterConstants.TRUE.equals(wrapBeforeBinaryOperatorOption);
- }
- }
-
- /**
- * @param settings the given map
- * @deprecated
- */
- private void setDeprecatedOptions(Map settings) {
- // backward compatibility code
- final Object commentClearBlankLinesOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_CLEAR_BLANK_LINES);
- if (commentClearBlankLinesOption != null) {
- this.comment_clear_blank_lines_in_javadoc_comment = DefaultCodeFormatterConstants.TRUE.equals(commentClearBlankLinesOption);
- this.comment_clear_blank_lines_in_block_comment = DefaultCodeFormatterConstants.TRUE.equals(commentClearBlankLinesOption);
- } else {
- final Object commentClearBlankLinesInJavadocCommentOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_CLEAR_BLANK_LINES_IN_JAVADOC_COMMENT);
- if (commentClearBlankLinesInJavadocCommentOption != null) {
- this.comment_clear_blank_lines_in_javadoc_comment = DefaultCodeFormatterConstants.TRUE.equals(commentClearBlankLinesInJavadocCommentOption);
- }
- final Object commentClearBlankLinesInBlockCommentOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_CLEAR_BLANK_LINES_IN_BLOCK_COMMENT);
- if (commentClearBlankLinesInBlockCommentOption != null) {
- this.comment_clear_blank_lines_in_block_comment = DefaultCodeFormatterConstants.TRUE.equals(commentClearBlankLinesInBlockCommentOption);
- }
- }
- }
-
- public void setDefaultSettings() {
- this.alignment_for_arguments_in_allocation_expression = Alignment.M_COMPACT_SPLIT;
- this.alignment_for_arguments_in_enum_constant = Alignment.M_COMPACT_SPLIT;
- this.alignment_for_arguments_in_explicit_constructor_call = Alignment.M_COMPACT_SPLIT;
- this.alignment_for_arguments_in_method_invocation = Alignment.M_COMPACT_SPLIT;
- this.alignment_for_arguments_in_qualified_allocation_expression = Alignment.M_COMPACT_SPLIT;
- this.alignment_for_assignment = Alignment.M_NO_ALIGNMENT;
- this.alignment_for_binary_expression = Alignment.M_COMPACT_SPLIT;
- this.alignment_for_compact_if = Alignment.M_ONE_PER_LINE_SPLIT | Alignment.M_INDENT_BY_ONE;
- this.alignment_for_conditional_expression = Alignment.M_ONE_PER_LINE_SPLIT;
- this.alignment_for_enum_constants = Alignment.NONE;
- this.alignment_for_expressions_in_array_initializer = Alignment.M_COMPACT_SPLIT;
- this.alignment_for_multiple_fields = Alignment.M_COMPACT_SPLIT;
- this.alignment_for_parameters_in_constructor_declaration = Alignment.M_COMPACT_SPLIT;
- this.alignment_for_parameters_in_method_declaration = Alignment.M_COMPACT_SPLIT;
- this.alignment_for_selector_in_method_invocation = Alignment.M_COMPACT_SPLIT;
- this.alignment_for_superclass_in_type_declaration = Alignment.M_NEXT_SHIFTED_SPLIT;
- this.alignment_for_superinterfaces_in_enum_declaration = Alignment.M_NEXT_SHIFTED_SPLIT;
- this.alignment_for_superinterfaces_in_type_declaration = Alignment.M_NEXT_SHIFTED_SPLIT;
- this.alignment_for_throws_clause_in_constructor_declaration = Alignment.M_COMPACT_SPLIT;
- this.alignment_for_throws_clause_in_method_declaration = Alignment.M_COMPACT_SPLIT;
- this.align_type_members_on_columns = false;
- this.brace_position_for_annotation_type_declaration = DefaultCodeFormatterConstants.END_OF_LINE;
- this.brace_position_for_anonymous_type_declaration = DefaultCodeFormatterConstants.END_OF_LINE;
- this.brace_position_for_array_initializer = DefaultCodeFormatterConstants.END_OF_LINE;
- this.brace_position_for_objlit_initializer = DefaultCodeFormatterConstants.END_OF_LINE;
- this.brace_position_for_block = DefaultCodeFormatterConstants.END_OF_LINE;
- this.brace_position_for_block_in_case = DefaultCodeFormatterConstants.END_OF_LINE;
- this.brace_position_for_constructor_declaration = DefaultCodeFormatterConstants.END_OF_LINE;
- this.brace_position_for_enum_constant = DefaultCodeFormatterConstants.END_OF_LINE;
- this.brace_position_for_enum_declaration = DefaultCodeFormatterConstants.END_OF_LINE;
- this.brace_position_for_method_declaration = DefaultCodeFormatterConstants.END_OF_LINE;
- this.brace_position_for_type_declaration = DefaultCodeFormatterConstants.END_OF_LINE;
- this.brace_position_for_switch = DefaultCodeFormatterConstants.END_OF_LINE;
- this.comment_clear_blank_lines_in_block_comment = false;
- this.comment_clear_blank_lines_in_javadoc_comment = false;
- this.comment_format_block_comment = true;
- this.comment_format_javadoc_comment = true;
- this.comment_format_line_comment = true;
- this.comment_format_header = false;
- this.comment_format_html = true;
- this.comment_format_source = true;
- this.comment_indent_parameter_description = true;
- this.comment_indent_root_tags = true;
- this.comment_insert_empty_line_before_root_tags = true;
- this.comment_insert_new_line_for_parameter = true;
- this.comment_line_length = 80;
- this.continuation_indentation = 2;
- this.continuation_indentation_for_array_initializer = 2;
- this.continuation_indentation_for_objlit_initializer = 1;
- this.blank_lines_after_imports = 0;
- this.blank_lines_after_package = 0;
- this.blank_lines_before_field = 0;
- this.blank_lines_before_first_class_body_declaration = 0;
- this.blank_lines_before_imports = 0;
- this.blank_lines_before_member_type = 0;
- this.blank_lines_before_method = 0;
- this.blank_lines_before_new_chunk = 0;
- this.blank_lines_before_package = 0;
- this.blank_lines_between_import_groups = 1;
- this.blank_lines_between_type_declarations = 0;
- this.blank_lines_at_beginning_of_method_body = 0;
- this.indent_statements_compare_to_block = true;
- this.indent_statements_compare_to_body = true;
- this.indent_body_declarations_compare_to_annotation_declaration_header = true;
- this.indent_body_declarations_compare_to_enum_constant_header = true;
- this.indent_body_declarations_compare_to_enum_declaration_header = true;
- this.indent_body_declarations_compare_to_type_header = true;
- this.indent_breaks_compare_to_cases = true;
- this.indent_empty_lines = false;
- this.indent_switchstatements_compare_to_cases = true;
- this.indent_switchstatements_compare_to_switch = true;
- this.indentation_size = 4;
- this.insert_new_line_after_annotation = true;
- this.insert_new_line_after_opening_brace_in_array_initializer = false;
- this.insert_new_line_after_opening_brace_in_objlit_initializer = true;
- this.insert_new_line_after_comma_in_objlit_initializer = true;
- this.insert_new_line_at_end_of_file_if_missing = false;
- this.insert_new_line_before_catch_in_try_statement = false;
- this.insert_new_line_before_closing_brace_in_array_initializer = false;
- this.insert_new_line_before_closing_brace_in_objlit_initializer = true;
- this.insert_new_line_before_else_in_if_statement = false;
- this.insert_new_line_before_finally_in_try_statement = false;
- this.insert_new_line_before_while_in_do_statement = false;
- this.insert_new_line_in_empty_anonymous_type_declaration = true;
- this.insert_new_line_in_empty_block = true;
- this.insert_new_line_in_empty_annotation_declaration = true;
- this.insert_new_line_in_empty_enum_constant = true;
- this.insert_new_line_in_empty_enum_declaration = true;
- this.insert_new_line_in_empty_method_body = true;
- this.insert_new_line_in_empty_type_declaration = true;
- this.insert_space_after_and_in_type_parameter = true;
- this.insert_space_after_assignment_operator = true;
- this.insert_space_after_at_in_annotation = false;
- this.insert_space_after_at_in_annotation_type_declaration = false;
- this.insert_space_after_binary_operator = true;
- this.insert_space_after_closing_angle_bracket_in_type_arguments = true;
- this.insert_space_after_closing_angle_bracket_in_type_parameters = true;
- this.insert_space_after_closing_paren_in_cast = true;
- this.insert_space_after_closing_brace_in_block = true;
- this.insert_space_after_colon_in_assert = true;
- this.insert_space_after_colon_in_case = true;
- this.insert_space_after_colon_in_conditional = true;
- this.insert_space_after_colon_in_object_initializer = true;
- this.insert_space_after_colon_in_for = true;
- this.insert_space_after_colon_in_labeled_statement = true;
- this.insert_space_after_comma_in_allocation_expression = true;
- this.insert_space_after_comma_in_annotation = true;
- this.insert_space_after_comma_in_array_initializer = true;
- this.insert_space_after_comma_in_constructor_declaration_parameters = true;
- this.insert_space_after_comma_in_constructor_declaration_throws = true;
- this.insert_space_after_comma_in_enum_constant_arguments = true;
- this.insert_space_after_comma_in_enum_declarations = true;
- this.insert_space_after_comma_in_explicit_constructor_call_arguments = true;
- this.insert_space_after_comma_in_for_increments = true;
- this.insert_space_after_comma_in_for_inits = true;
- this.insert_space_after_comma_in_method_invocation_arguments = true;
- this.insert_space_after_comma_in_method_declaration_parameters = true;
- this.insert_space_after_comma_in_method_declaration_throws = true;
- this.insert_space_after_comma_in_multiple_field_declarations = true;
- this.insert_space_after_comma_in_multiple_local_declarations = true;
- this.insert_space_after_comma_in_parameterized_type_reference = true;
- this.insert_space_after_comma_in_superinterfaces = true;
- this.insert_space_after_comma_in_type_arguments = true;
- this.insert_space_after_comma_in_type_parameters = true;
- this.insert_space_after_ellipsis = true;
- this.insert_space_after_opening_angle_bracket_in_parameterized_type_reference = false;
- this.insert_space_after_opening_angle_bracket_in_type_arguments = false;
- this.insert_space_after_opening_angle_bracket_in_type_parameters = false;
- this.insert_space_after_opening_bracket_in_array_allocation_expression = false;
- this.insert_space_after_opening_bracket_in_array_reference = false;
- this.insert_space_after_opening_brace_in_array_initializer = false;
- this.insert_space_after_opening_paren_in_annotation = false;
- this.insert_space_after_opening_paren_in_cast = false;
- this.insert_space_after_opening_paren_in_catch = false;
- this.insert_space_after_opening_paren_in_constructor_declaration = false;
- this.insert_space_after_opening_paren_in_enum_constant = false;
- this.insert_space_after_opening_paren_in_for = false;
- this.insert_space_after_opening_paren_in_if = false;
- this.insert_space_after_opening_paren_in_method_declaration = false;
- this.insert_space_after_opening_paren_in_method_invocation = false;
- this.insert_space_after_opening_paren_in_parenthesized_expression = false;
- this.insert_space_after_opening_paren_in_switch = false;
- this.insert_space_after_opening_paren_in_synchronized = false;
- this.insert_space_after_opening_paren_in_while = false;
- this.insert_space_after_postfix_operator = false;
- this.insert_space_after_prefix_operator = false;
- this.insert_space_after_question_in_conditional = true;
- this.insert_space_after_semicolon_in_for = true;
- this.insert_space_after_unary_operator = false;
- this.insert_space_before_at_in_annotation_type_declaration = true;
- this.insert_space_before_assignment_operator = true;
- this.insert_space_before_binary_operator = true;
- this.insert_space_before_closing_angle_bracket_in_parameterized_type_reference = false;
- this.insert_space_before_closing_angle_bracket_in_type_arguments = false;
- this.insert_space_before_closing_angle_bracket_in_type_parameters = false;
- this.insert_space_before_closing_brace_in_array_initializer = false;
- this.insert_space_before_closing_bracket_in_array_allocation_expression = false;
- this.insert_space_before_closing_bracket_in_array_reference = false;
- this.insert_space_before_closing_paren_in_annotation = false;
- this.insert_space_before_closing_paren_in_cast = false;
- this.insert_space_before_closing_paren_in_catch = false;
- this.insert_space_before_closing_paren_in_constructor_declaration = false;
- this.insert_space_before_closing_paren_in_enum_constant = false;
- this.insert_space_before_closing_paren_in_for = false;
- this.insert_space_before_closing_paren_in_if = false;
- this.insert_space_before_closing_paren_in_method_declaration = false;
- this.insert_space_before_closing_paren_in_method_invocation = false;
- this.insert_space_before_closing_paren_in_parenthesized_expression = false;
- this.insert_space_before_closing_paren_in_switch = false;
- this.insert_space_before_closing_paren_in_synchronized = false;
- this.insert_space_before_closing_paren_in_while = false;
- this.insert_space_before_colon_in_assert = true;
- this.insert_space_before_colon_in_case = true;
- this.insert_space_before_colon_in_conditional = true;
- this.insert_space_before_colon_in_object_initializer = true;
- this.insert_space_before_colon_in_default = true;
- this.insert_space_before_colon_in_for = true;
- this.insert_space_before_colon_in_labeled_statement = true;
- this.insert_space_before_comma_in_allocation_expression = false;
- this.insert_space_before_comma_in_array_initializer = false;
- this.insert_space_before_comma_in_constructor_declaration_parameters = false;
- this.insert_space_before_comma_in_constructor_declaration_throws = false;
- this.insert_space_before_comma_in_enum_constant_arguments = false;
- this.insert_space_before_comma_in_enum_declarations = false;
- this.insert_space_before_comma_in_explicit_constructor_call_arguments = false;
- this.insert_space_before_comma_in_for_increments = false;
- this.insert_space_before_comma_in_for_inits = false;
- this.insert_space_before_comma_in_method_invocation_arguments = false;
- this.insert_space_before_comma_in_method_declaration_parameters = false;
- this.insert_space_before_comma_in_method_declaration_throws = false;
- this.insert_space_before_comma_in_multiple_field_declarations = false;
- this.insert_space_before_comma_in_multiple_local_declarations = false;
- this.insert_space_before_comma_in_parameterized_type_reference = false;
- this.insert_space_before_comma_in_superinterfaces = false;
- this.insert_space_before_comma_in_type_arguments = false;
- this.insert_space_before_comma_in_type_parameters = false;
- this.insert_space_before_ellipsis = false;
- this.insert_space_before_parenthesized_expression_in_return = true;
- this.insert_space_before_parenthesized_expression_in_throw = true;
- this.insert_space_before_opening_angle_bracket_in_parameterized_type_reference = false;
- this.insert_space_before_opening_angle_bracket_in_type_arguments = false;
- this.insert_space_before_opening_angle_bracket_in_type_parameters = false;
- this.insert_space_before_opening_brace_in_annotation_type_declaration = true;
- this.insert_space_before_opening_brace_in_anonymous_type_declaration = true;
- this.insert_space_before_opening_brace_in_block = true;
- this.insert_space_before_opening_brace_in_constructor_declaration = true;
- this.insert_space_before_opening_brace_in_enum_constant = true;
- this.insert_space_before_opening_brace_in_enum_declaration = true;
- this.insert_space_before_opening_brace_in_method_declaration = true;
- this.insert_space_before_opening_brace_in_switch = true;
- this.insert_space_before_opening_brace_in_type_declaration = true;
- this.insert_space_before_opening_bracket_in_array_allocation_expression = false;
- this.insert_space_before_opening_bracket_in_array_reference = false;
- this.insert_space_before_opening_bracket_in_array_type_reference = false;
- this.insert_space_before_opening_paren_in_annotation = false;
- this.insert_space_before_opening_paren_in_annotation_type_member_declaration = false;
- this.insert_space_before_opening_paren_in_catch = true;
- this.insert_space_before_opening_paren_in_constructor_declaration = false;
- this.insert_space_before_opening_paren_in_enum_constant = false;
- this.insert_space_before_opening_paren_in_for = true;
- this.insert_space_before_opening_paren_in_if = true;
- this.insert_space_before_opening_paren_in_method_invocation = false;
- this.insert_space_before_opening_paren_in_method_declaration = false;
- this.insert_space_before_opening_paren_in_switch = true;
- this.insert_space_before_opening_paren_in_synchronized = true;
- this.insert_space_before_opening_paren_in_parenthesized_expression = false;
- this.insert_space_before_opening_paren_in_while = true;
- this.insert_space_before_postfix_operator = false;
- this.insert_space_before_prefix_operator = false;
- this.insert_space_before_question_in_conditional = true;
- this.insert_space_before_semicolon = false;
- this.insert_space_before_semicolon_in_for = false;
- this.insert_space_before_unary_operator = false;
- this.insert_space_between_brackets_in_array_type_reference = false;
- this.insert_space_between_empty_braces_in_array_initializer = false;
- this.insert_space_between_empty_brackets_in_array_allocation_expression = false;
- this.insert_space_between_empty_parens_in_annotation_type_member_declaration = false;
- this.insert_space_between_empty_parens_in_constructor_declaration = false;
- this.insert_space_between_empty_parens_in_enum_constant = false;
- this.insert_space_between_empty_parens_in_method_declaration = false;
- this.insert_space_between_empty_parens_in_method_invocation = false;
- this.compact_else_if = true;
- this.keep_guardian_clause_on_one_line = false;
- this.keep_else_statement_on_same_line = false;
- this.keep_empty_array_initializer_on_one_line = false;
- this.keep_empty_objlit_initializer_on_one_line = false;
- this.keep_simple_if_on_one_line = false;
- this.keep_then_statement_on_same_line = false;
- this.never_indent_block_comments_on_first_column = false;
- this.never_indent_line_comments_on_first_column = false;
- this.number_of_empty_lines_to_preserve = 1;
- this.put_empty_statement_on_new_line = false;
- this.tab_size = 4;
- this.page_width = 80;
- this.tab_char = TAB; // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=49081
- this.use_tabs_only_for_leading_indentations = false;
- this.wrap_before_binary_operator = true;
- }
-
- public void setEclipseDefaultSettings() {
- setJavaConventionsSettings();
- this.tab_char = TAB;
- this.tab_size = 4;
- }
-
- public void setJavaConventionsSettings() {
- this.alignment_for_arguments_in_allocation_expression = Alignment.M_COMPACT_SPLIT;
- this.alignment_for_arguments_in_enum_constant = Alignment.M_COMPACT_SPLIT;
- this.alignment_for_arguments_in_explicit_constructor_call = Alignment.M_COMPACT_SPLIT;
- this.alignment_for_arguments_in_method_invocation = Alignment.M_COMPACT_SPLIT;
- this.alignment_for_arguments_in_qualified_allocation_expression = Alignment.M_COMPACT_SPLIT;
- this.alignment_for_assignment = Alignment.M_NO_ALIGNMENT;
- this.alignment_for_binary_expression = Alignment.M_COMPACT_SPLIT;
- this.alignment_for_compact_if = Alignment.M_COMPACT_SPLIT;
- this.alignment_for_conditional_expression = Alignment.M_NEXT_PER_LINE_SPLIT;
- this.alignment_for_enum_constants = Alignment.NONE;
- this.alignment_for_expressions_in_array_initializer = Alignment.M_COMPACT_SPLIT;
- this.alignment_for_multiple_fields = Alignment.M_COMPACT_SPLIT;
- this.alignment_for_parameters_in_constructor_declaration = Alignment.M_COMPACT_SPLIT;
- this.alignment_for_parameters_in_method_declaration = Alignment.M_COMPACT_SPLIT;
- this.alignment_for_selector_in_method_invocation = Alignment.M_COMPACT_SPLIT;
- this.alignment_for_superclass_in_type_declaration = Alignment.M_COMPACT_SPLIT;
- this.alignment_for_superinterfaces_in_enum_declaration = Alignment.M_COMPACT_SPLIT;
- this.alignment_for_superinterfaces_in_type_declaration = Alignment.M_COMPACT_SPLIT;
- this.alignment_for_throws_clause_in_constructor_declaration = Alignment.M_COMPACT_SPLIT;
- this.alignment_for_throws_clause_in_method_declaration = Alignment.M_COMPACT_SPLIT;
- this.align_type_members_on_columns = false;
- this.brace_position_for_annotation_type_declaration = DefaultCodeFormatterConstants.END_OF_LINE;
- this.brace_position_for_anonymous_type_declaration = DefaultCodeFormatterConstants.END_OF_LINE;
- this.brace_position_for_array_initializer = DefaultCodeFormatterConstants.END_OF_LINE;
- this.brace_position_for_objlit_initializer = DefaultCodeFormatterConstants.END_OF_LINE;
- this.brace_position_for_block = DefaultCodeFormatterConstants.END_OF_LINE;
- this.brace_position_for_block_in_case = DefaultCodeFormatterConstants.END_OF_LINE;
- this.brace_position_for_constructor_declaration = DefaultCodeFormatterConstants.END_OF_LINE;
- this.brace_position_for_enum_constant = DefaultCodeFormatterConstants.END_OF_LINE;
- this.brace_position_for_enum_declaration = DefaultCodeFormatterConstants.END_OF_LINE;
- this.brace_position_for_method_declaration = DefaultCodeFormatterConstants.END_OF_LINE;
- this.brace_position_for_type_declaration = DefaultCodeFormatterConstants.END_OF_LINE;
- this.brace_position_for_switch = DefaultCodeFormatterConstants.END_OF_LINE;
- this.comment_clear_blank_lines_in_block_comment = false;
- this.comment_clear_blank_lines_in_javadoc_comment = false;
- this.comment_format_block_comment = true;
- this.comment_format_javadoc_comment = true;
- this.comment_format_line_comment = true;
- this.comment_format_header = false;
- this.comment_format_html = true;
- this.comment_format_source = true;
- this.comment_indent_parameter_description = true;
- this.comment_indent_root_tags = true;
- this.comment_insert_empty_line_before_root_tags = true;
- this.comment_insert_new_line_for_parameter = true;
- this.comment_line_length = 80;
- this.continuation_indentation = 2;
- this.continuation_indentation_for_array_initializer = 2;
- this.continuation_indentation_for_objlit_initializer = 1;
- this.blank_lines_after_imports = 1;
- this.blank_lines_after_package = 1;
- this.blank_lines_before_field = 0;
- this.blank_lines_before_first_class_body_declaration = 0;
- this.blank_lines_before_imports = 1;
- this.blank_lines_before_member_type = 1;
- this.blank_lines_before_method = 1;
- this.blank_lines_before_new_chunk = 1;
- this.blank_lines_before_package = 0;
- this.blank_lines_between_import_groups = 1;
- this.blank_lines_between_type_declarations = 0;
- this.blank_lines_at_beginning_of_method_body = 0;
- this.indent_statements_compare_to_block = true;
- this.indent_statements_compare_to_body = true;
- this.indent_body_declarations_compare_to_annotation_declaration_header = true;
- this.indent_body_declarations_compare_to_enum_constant_header = true;
- this.indent_body_declarations_compare_to_enum_declaration_header = true;
- this.indent_body_declarations_compare_to_type_header = true;
- this.indent_breaks_compare_to_cases = true;
- this.indent_empty_lines = false;
- this.indent_switchstatements_compare_to_cases = true;
- this.indent_switchstatements_compare_to_switch = false;
- this.indentation_size = 4;
- this.insert_new_line_after_annotation = true;
- this.insert_new_line_after_opening_brace_in_array_initializer = false;
- this.insert_new_line_after_opening_brace_in_objlit_initializer = true;
- this.insert_new_line_after_comma_in_objlit_initializer = true;
- this.insert_new_line_at_end_of_file_if_missing = false;
- this.insert_new_line_before_catch_in_try_statement = false;
- this.insert_new_line_before_closing_brace_in_array_initializer = false;
- this.insert_new_line_before_closing_brace_in_objlit_initializer = true;
- this.insert_new_line_before_else_in_if_statement = false;
- this.insert_new_line_before_finally_in_try_statement = false;
- this.insert_new_line_before_while_in_do_statement = false;
- this.insert_new_line_in_empty_anonymous_type_declaration = true;
- this.insert_new_line_in_empty_block = true;
- this.insert_new_line_in_empty_annotation_declaration = true;
- this.insert_new_line_in_empty_enum_constant = true;
- this.insert_new_line_in_empty_enum_declaration = true;
- this.insert_new_line_in_empty_method_body = true;
- this.insert_new_line_in_empty_type_declaration = true;
- this.insert_space_after_and_in_type_parameter = true;
- this.insert_space_after_assignment_operator = true;
- this.insert_space_after_at_in_annotation = false;
- this.insert_space_after_at_in_annotation_type_declaration = false;
- this.insert_space_after_binary_operator = true;
- this.insert_space_after_closing_angle_bracket_in_type_arguments = true;
- this.insert_space_after_closing_angle_bracket_in_type_parameters = true;
- this.insert_space_after_closing_paren_in_cast = true;
- this.insert_space_after_closing_brace_in_block = true;
- this.insert_space_after_colon_in_assert = true;
- this.insert_space_after_colon_in_case = true;
- this.insert_space_after_colon_in_conditional = true;
- this.insert_space_after_colon_in_object_initializer = true;
- this.insert_space_after_colon_in_for = true;
- this.insert_space_after_colon_in_labeled_statement = true;
- this.insert_space_after_comma_in_allocation_expression = true;
- this.insert_space_after_comma_in_annotation = true;
- this.insert_space_after_comma_in_array_initializer = true;
- this.insert_space_after_comma_in_constructor_declaration_parameters = true;
- this.insert_space_after_comma_in_constructor_declaration_throws = true;
- this.insert_space_after_comma_in_enum_constant_arguments = true;
- this.insert_space_after_comma_in_enum_declarations = true;
- this.insert_space_after_comma_in_explicit_constructor_call_arguments = true;
- this.insert_space_after_comma_in_for_increments = true;
- this.insert_space_after_comma_in_for_inits = true;
- this.insert_space_after_comma_in_method_invocation_arguments = true;
- this.insert_space_after_comma_in_method_declaration_parameters = true;
- this.insert_space_after_comma_in_method_declaration_throws = true;
- this.insert_space_after_comma_in_multiple_field_declarations = true;
- this.insert_space_after_comma_in_multiple_local_declarations = true;
- this.insert_space_after_comma_in_parameterized_type_reference = true;
- this.insert_space_after_comma_in_superinterfaces = true;
- this.insert_space_after_comma_in_type_arguments = true;
- this.insert_space_after_comma_in_type_parameters = true;
- this.insert_space_after_ellipsis = true;
- this.insert_space_after_opening_angle_bracket_in_parameterized_type_reference = false;
- this.insert_space_after_opening_angle_bracket_in_type_arguments = false;
- this.insert_space_after_opening_angle_bracket_in_type_parameters = false;
- this.insert_space_after_opening_bracket_in_array_allocation_expression = false;
- this.insert_space_after_opening_bracket_in_array_reference = false;
- this.insert_space_after_opening_brace_in_array_initializer = true;
- this.insert_space_after_opening_paren_in_annotation = false;
- this.insert_space_after_opening_paren_in_cast = false;
- this.insert_space_after_opening_paren_in_catch = false;
- this.insert_space_after_opening_paren_in_constructor_declaration = false;
- this.insert_space_after_opening_paren_in_enum_constant = false;
- this.insert_space_after_opening_paren_in_for = false;
- this.insert_space_after_opening_paren_in_if = false;
- this.insert_space_after_opening_paren_in_method_declaration = false;
- this.insert_space_after_opening_paren_in_method_invocation = false;
- this.insert_space_after_opening_paren_in_parenthesized_expression = false;
- this.insert_space_after_opening_paren_in_switch = false;
- this.insert_space_after_opening_paren_in_synchronized = false;
- this.insert_space_after_opening_paren_in_while = false;
- this.insert_space_after_postfix_operator = false;
- this.insert_space_after_prefix_operator = false;
- this.insert_space_after_question_in_conditional = true;
- this.insert_space_after_semicolon_in_for = true;
- this.insert_space_after_unary_operator = false;
- this.insert_space_before_at_in_annotation_type_declaration = true;
- this.insert_space_before_assignment_operator = true;
- this.insert_space_before_binary_operator = true;
- this.insert_space_before_closing_angle_bracket_in_parameterized_type_reference = false;
- this.insert_space_before_closing_angle_bracket_in_type_arguments = false;
- this.insert_space_before_closing_angle_bracket_in_type_parameters = false;
- this.insert_space_before_closing_brace_in_array_initializer = true;
- this.insert_space_before_closing_bracket_in_array_allocation_expression = false;
- this.insert_space_before_closing_bracket_in_array_reference = false;
- this.insert_space_before_closing_paren_in_annotation = false;
- this.insert_space_before_closing_paren_in_cast = false;
- this.insert_space_before_closing_paren_in_catch = false;
- this.insert_space_before_closing_paren_in_constructor_declaration = false;
- this.insert_space_before_closing_paren_in_enum_constant = false;
- this.insert_space_before_closing_paren_in_for = false;
- this.insert_space_before_closing_paren_in_if = false;
- this.insert_space_before_closing_paren_in_method_declaration = false;
- this.insert_space_before_closing_paren_in_method_invocation = false;
- this.insert_space_before_closing_paren_in_parenthesized_expression = false;
- this.insert_space_before_closing_paren_in_switch = false;
- this.insert_space_before_closing_paren_in_synchronized = false;
- this.insert_space_before_closing_paren_in_while = false;
- this.insert_space_before_colon_in_assert = true;
- this.insert_space_before_colon_in_case = false;
- this.insert_space_before_colon_in_conditional = true;
- this.insert_space_before_colon_in_object_initializer = true;
- this.insert_space_before_colon_in_default = false;
- this.insert_space_before_colon_in_for = true;
- this.insert_space_before_colon_in_labeled_statement = false;
- this.insert_space_before_comma_in_allocation_expression = false;
- this.insert_space_before_comma_in_array_initializer = false;
- this.insert_space_before_comma_in_constructor_declaration_parameters = false;
- this.insert_space_before_comma_in_constructor_declaration_throws = false;
- this.insert_space_before_comma_in_enum_constant_arguments = false;
- this.insert_space_before_comma_in_enum_declarations = false;
- this.insert_space_before_comma_in_explicit_constructor_call_arguments = false;
- this.insert_space_before_comma_in_for_increments = false;
- this.insert_space_before_comma_in_for_inits = false;
- this.insert_space_before_comma_in_method_invocation_arguments = false;
- this.insert_space_before_comma_in_method_declaration_parameters = false;
- this.insert_space_before_comma_in_method_declaration_throws = false;
- this.insert_space_before_comma_in_multiple_field_declarations = false;
- this.insert_space_before_comma_in_multiple_local_declarations = false;
- this.insert_space_before_comma_in_parameterized_type_reference = false;
- this.insert_space_before_comma_in_superinterfaces = false;
- this.insert_space_before_comma_in_type_arguments = false;
- this.insert_space_before_comma_in_type_parameters = false;
- this.insert_space_before_ellipsis = false;
- this.insert_space_before_parenthesized_expression_in_return = true;
- this.insert_space_before_parenthesized_expression_in_throw = true;
- this.insert_space_before_opening_angle_bracket_in_parameterized_type_reference = false;
- this.insert_space_before_opening_angle_bracket_in_type_arguments = false;
- this.insert_space_before_opening_angle_bracket_in_type_parameters = false;
- this.insert_space_before_opening_brace_in_annotation_type_declaration = true;
- this.insert_space_before_opening_brace_in_anonymous_type_declaration = true;
- this.insert_space_before_opening_brace_in_block = true;
- this.insert_space_before_opening_brace_in_constructor_declaration = true;
- this.insert_space_before_opening_brace_in_enum_constant = true;
- this.insert_space_before_opening_brace_in_enum_declaration = true;
- this.insert_space_before_opening_brace_in_method_declaration = true;
- this.insert_space_before_opening_brace_in_switch = true;
- this.insert_space_before_opening_brace_in_type_declaration = true;
- this.insert_space_before_opening_bracket_in_array_allocation_expression = false;
- this.insert_space_before_opening_bracket_in_array_reference = false;
- this.insert_space_before_opening_bracket_in_array_type_reference = false;
- this.insert_space_before_opening_paren_in_annotation = false;
- this.insert_space_before_opening_paren_in_annotation_type_member_declaration = false;
- this.insert_space_before_opening_paren_in_catch = true;
- this.insert_space_before_opening_paren_in_constructor_declaration = false;
- this.insert_space_before_opening_paren_in_enum_constant = false;
- this.insert_space_before_opening_paren_in_for = true;
- this.insert_space_before_opening_paren_in_if = true;
- this.insert_space_before_opening_paren_in_method_invocation = false;
- this.insert_space_before_opening_paren_in_method_declaration = false;
- this.insert_space_before_opening_paren_in_switch = true;
- this.insert_space_before_opening_paren_in_synchronized = true;
- this.insert_space_before_opening_paren_in_parenthesized_expression = false;
- this.insert_space_before_opening_paren_in_while = true;
- this.insert_space_before_postfix_operator = false;
- this.insert_space_before_prefix_operator = false;
- this.insert_space_before_question_in_conditional = true;
- this.insert_space_before_semicolon = false;
- this.insert_space_before_semicolon_in_for = false;
- this.insert_space_before_unary_operator = false;
- this.insert_space_between_brackets_in_array_type_reference = false;
- this.insert_space_between_empty_braces_in_array_initializer = false;
- this.insert_space_between_empty_brackets_in_array_allocation_expression = false;
- this.insert_space_between_empty_parens_in_annotation_type_member_declaration = false;
- this.insert_space_between_empty_parens_in_constructor_declaration = false;
- this.insert_space_between_empty_parens_in_enum_constant = false;
- this.insert_space_between_empty_parens_in_method_declaration = false;
- this.insert_space_between_empty_parens_in_method_invocation = false;
- this.compact_else_if = true;
- this.keep_guardian_clause_on_one_line = false;
- this.keep_else_statement_on_same_line = false;
- this.keep_empty_array_initializer_on_one_line = false;
- this.keep_empty_objlit_initializer_on_one_line = false;
- this.keep_simple_if_on_one_line = false;
- this.keep_then_statement_on_same_line = false;
- this.never_indent_block_comments_on_first_column = false;
- this.never_indent_line_comments_on_first_column = false;
- this.number_of_empty_lines_to_preserve = 1;
- this.put_empty_statement_on_new_line = true;
- this.tab_size = 8;
- this.page_width = 80;
- this.tab_char = MIXED;
- this.use_tabs_only_for_leading_indentations = false;
- this.wrap_before_binary_operator = true;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/Location.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/Location.java
deleted file mode 100644
index ee5c4f60..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/Location.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.formatter;
-
-/**
- * A location maintains positional information both in original source and in the output source.
- * It remembers source offsets, line/column and indentation level.
- * @since 2.1
- */
-public class Location {
-
- public int inputOffset;
- public int outputLine;
- public int outputColumn;
- public int outputIndentationLevel;
- public boolean needSpace;
- public boolean pendingSpace;
- public int nlsTagCounter;
- public int lastLocalDeclarationSourceStart;
- public int numberOfIndentations;
- public int inputToken;
- public int inputTokenNonWS;
-
- // chunk management
- public int lastNumberOfNewLines;
-
- // edits management
- int editsIndex;
- OptimizedReplaceEdit textEdit;
-
- public Location(Scribe scribe, int sourceRestart){
- update(scribe, sourceRestart);
- }
-
- public void update(Scribe scribe, int sourceRestart){
- this.outputColumn = scribe.column;
- this.outputLine = scribe.line;
- this.inputOffset = sourceRestart;
- this.inputToken=scribe.scanner.currentToken;
- this.inputTokenNonWS=scribe.scanner.currentNonWhitespaceToken;
- this.outputIndentationLevel = scribe.indentationLevel;
- this.lastNumberOfNewLines = scribe.lastNumberOfNewLines;
- this.needSpace = scribe.needSpace;
- this.pendingSpace = scribe.pendingSpace;
- this.editsIndex = scribe.editsIndex;
- this.nlsTagCounter = scribe.nlsTagCounter;
- this.numberOfIndentations = scribe.numberOfIndentations;
- textEdit = scribe.getLastEdit();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/OptimizedReplaceEdit.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/OptimizedReplaceEdit.java
deleted file mode 100644
index 60acf44f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/OptimizedReplaceEdit.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.formatter;
-
-public class OptimizedReplaceEdit {
-
- int offset;
- int length;
- String replacement;
-
- public OptimizedReplaceEdit(int offset, int length, String replacement) {
- this.offset = offset;
- this.length = length;
- this.replacement = replacement;
- }
-
- public String toString() {
- return "(" + this.offset + ", length " + this.length + " :>" + this.replacement + "<"; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/Scribe.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/Scribe.java
deleted file mode 100644
index 6d0671d8..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/Scribe.java
+++ /dev/null
@@ -1,1800 +0,0 @@
-/*******************************************************************************
- * 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.formatter;
-
-import java.util.Arrays;
-
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor;
-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.compiler.util.Util;
-import org.eclipse.wst.jsdt.internal.core.util.CodeSnippetParsingUtil;
-import org.eclipse.wst.jsdt.internal.core.util.RecordedParsingInformation;
-import org.eclipse.wst.jsdt.internal.formatter.align.Alignment;
-import org.eclipse.wst.jsdt.internal.formatter.align.AlignmentException;
-
-/**
- * This class is responsible for dumping formatted source
- * @since 2.1
- */
-public class Scribe {
- private static final int INITIAL_SIZE = 100;
-
- private boolean checkLineWrapping;
- /** one-based column */
- public int column;
- private int[][] commentPositions;
-
- // Most specific alignment.
- public Alignment currentAlignment;
- public int currentToken;
-
- // edits management
- private OptimizedReplaceEdit[] edits;
- public int editsIndex;
-
- public CodeFormatterVisitor formatter;
- public int indentationLevel;
- public int lastNumberOfNewLines;
- public int line;
-
- private int[] lineEnds;
- private String lineSeparator;
- public Alignment memberAlignment;
- public boolean needSpace = false;
-
- public int nlsTagCounter;
- public int pageWidth;
- public boolean pendingSpace = false;
-
- public Scanner scanner;
- public int scannerEndPosition;
- public int tabLength;
- public int indentationSize;
- private int textRegionEnd;
- private int textRegionStart;
- public int tabChar;
- public int numberOfIndentations;
- private boolean useTabsOnlyForLeadingIndents;
-
- /** indent empty lines*/
- private final boolean indentEmptyLines;
-
- private final boolean formatJavadocComment;
- private final boolean formatBlockComment;
-
- Scribe(CodeFormatterVisitor formatter, long sourceLevel, int offset, int length, CodeSnippetParsingUtil codeSnippetParsingUtil) {
- this.scanner = new Scanner(true, true, false/*nls*/, sourceLevel/*sourceLevel*/, null/*taskTags*/, null/*taskPriorities*/, true/*taskCaseSensitive*/);
- this.formatter = formatter;
- this.pageWidth = formatter.preferences.page_width;
- this.tabLength = formatter.preferences.tab_size;
- this.indentationLevel= 0; // initialize properly
- this.numberOfIndentations = 0;
- this.useTabsOnlyForLeadingIndents = formatter.preferences.use_tabs_only_for_leading_indentations;
- this.indentEmptyLines = formatter.preferences.indent_empty_lines;
- this.tabChar = formatter.preferences.tab_char;
- if (this.tabChar == DefaultCodeFormatterOptions.MIXED) {
- this.indentationSize = formatter.preferences.indentation_size;
- } else {
- this.indentationSize = this.tabLength;
- }
- this.lineSeparator = formatter.preferences.line_separator;
- this.indentationLevel = formatter.preferences.initial_indentation_level * this.indentationSize;
- this.textRegionStart = offset;
- this.textRegionEnd = offset + length - 1;
- if (codeSnippetParsingUtil != null) {
- final RecordedParsingInformation information = codeSnippetParsingUtil.recordedParsingInformation;
- if (information != null) {
- this.lineEnds = information.lineEnds;
- this.commentPositions = information.commentPositions;
- }
- }
- this.formatBlockComment = formatter.preferences.comment_format_block_comment;
- this.formatJavadocComment = formatter.preferences.comment_format_javadoc_comment;
- reset();
- }
-
- private final void addDeleteEdit(int start, int end) {
- if (this.edits.length == this.editsIndex) {
- // resize
- resize();
- }
- addOptimizedReplaceEdit(start, end - start + 1, Util.EMPTY_STRING);
- }
-
- public final void addInsertEdit(int insertPosition, String insertedString) {
- if (this.edits.length == this.editsIndex) {
- // resize
- resize();
- }
- addOptimizedReplaceEdit(insertPosition, 0, insertedString);
- }
-
- private final void addOptimizedReplaceEdit(int offset, int length, String replacement) {
- if (this.editsIndex > 0) {
- // try to merge last two edits
- final OptimizedReplaceEdit previous = this.edits[this.editsIndex-1];
- final int previousOffset = previous.offset;
- final int previousLength = previous.length;
- final int endOffsetOfPreviousEdit = previousOffset + previousLength;
- final int replacementLength = replacement.length();
- final String previousReplacement = previous.replacement;
- final int previousReplacementLength = previousReplacement.length();
- if (previousOffset == offset && previousLength == length && (replacementLength == 0 || previousReplacementLength == 0)) {
- if (this.currentAlignment != null) {
- final Location location = this.currentAlignment.location;
- if (location.editsIndex == this.editsIndex) {
- location.editsIndex--;
- location.textEdit = previous;
- }
- }
- this.editsIndex--;
- return;
- }
- if (endOffsetOfPreviousEdit == offset) {
- if (length != 0) {
- if (replacementLength != 0) {
- this.edits[this.editsIndex - 1] = new OptimizedReplaceEdit(previousOffset, previousLength + length, previousReplacement + replacement);
- } else if (previousLength + length == previousReplacementLength) {
- // check the characters. If they are identical, we can get rid of the previous edit
- boolean canBeRemoved = true;
- loop: for (int i = previousOffset; i < previousOffset + previousReplacementLength; i++) {
- if (scanner.source[i] != previousReplacement.charAt(i - previousOffset)) {
- this.edits[this.editsIndex - 1] = new OptimizedReplaceEdit(previousOffset, previousReplacementLength, previousReplacement);
- canBeRemoved = false;
- break loop;
- }
- }
- if (canBeRemoved) {
- if (this.currentAlignment != null) {
- final Location location = this.currentAlignment.location;
- if (location.editsIndex == this.editsIndex) {
- location.editsIndex--;
- location.textEdit = previous;
- }
- }
- this.editsIndex--;
- }
- } else {
- this.edits[this.editsIndex - 1] = new OptimizedReplaceEdit(previousOffset, previousLength + length, previousReplacement);
- }
- } else {
- if (replacementLength != 0) {
- this.edits[this.editsIndex - 1] = new OptimizedReplaceEdit(previousOffset, previousLength, previousReplacement + replacement);
- }
- }
- } else if ((offset + length == previousOffset) && (previousLength + length == replacementLength + previousReplacementLength)) {
- // check if both edits corresponds to the orignal source code
- boolean canBeRemoved = true;
- String totalReplacement = replacement + previousReplacement;
- loop: for (int i = 0; i < previousLength + length; i++) {
- if (scanner.source[i + offset] != totalReplacement.charAt(i)) {
- this.edits[this.editsIndex - 1] = new OptimizedReplaceEdit(offset, previousLength + length, totalReplacement);
- canBeRemoved = false;
- break loop;
- }
- }
- if (canBeRemoved) {
- if (this.currentAlignment != null) {
- final Location location = this.currentAlignment.location;
- if (location.editsIndex == this.editsIndex) {
- location.editsIndex--;
- location.textEdit = previous;
- }
- }
- this.editsIndex--;
- }
- } else {
- this.edits[this.editsIndex++] = new OptimizedReplaceEdit(offset, length, replacement);
- }
- } else {
- this.edits[this.editsIndex++] = new OptimizedReplaceEdit(offset, length, replacement);
- }
- }
-
- public final void addReplaceEdit(int start, int end, String replacement) {
- if (this.edits.length == this.editsIndex) {
- // resize
- resize();
- }
- addOptimizedReplaceEdit(start, end - start + 1, replacement);
- }
-
- public void alignFragment(Alignment alignment, int fragmentIndex){
- alignment.fragmentIndex = fragmentIndex;
- alignment.checkColumn();
- alignment.performFragmentEffect();
- }
-
- public void checkNLSTag(int sourceStart) {
- if (hasNLSTag(sourceStart)) {
- this.nlsTagCounter++;
- }
- }
- public void consumeNextToken() {
- printComment();
- try {
- this.currentToken = this.scanner.getNextToken();
- addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition());
- } catch (InvalidInputException e) {
- throw new AbortFormatting(e);
- }
- }
- public Alignment createAlignment(String name, int mode, int count, int sourceRestart){
- return createAlignment(name, mode, Alignment.R_INNERMOST, count, sourceRestart);
- }
-
- public Alignment createAlignment(String name, int mode, int count, int sourceRestart, boolean adjust){
- return createAlignment(name, mode, Alignment.R_INNERMOST, count, sourceRestart, adjust);
- }
-
- public Alignment createAlignment(String name, int mode, int tieBreakRule, int count, int sourceRestart){
- return createAlignment(name, mode, tieBreakRule, count, sourceRestart, this.formatter.preferences.continuation_indentation, false);
- }
-
- public Alignment createAlignment(String name, int mode, int count, int sourceRestart, int continuationIndent, boolean adjust){
- return createAlignment(name, mode, Alignment.R_INNERMOST, count, sourceRestart, continuationIndent, adjust);
- }
-
- public Alignment createAlignment(String name, int mode, int tieBreakRule, int count, int sourceRestart, int continuationIndent, boolean adjust){
- Alignment alignment = new Alignment(name, mode, tieBreakRule, this, count, sourceRestart, continuationIndent);
- // adjust break indentation
- if (adjust && this.memberAlignment != null) {
- Alignment current = this.memberAlignment;
- while (current.enclosing != null) {
- current = current.enclosing;
- }
- if ((current.mode & Alignment.M_MULTICOLUMN) != 0) {
- final int indentSize = this.indentationSize;
- switch(current.chunkKind) {
- case Alignment.CHUNK_METHOD :
- case Alignment.CHUNK_TYPE :
- if ((mode & Alignment.M_INDENT_BY_ONE) != 0) {
- alignment.breakIndentationLevel = this.indentationLevel + indentSize;
- } else {
- alignment.breakIndentationLevel = this.indentationLevel + continuationIndent * indentSize;
- }
- alignment.update();
- break;
- case Alignment.CHUNK_FIELD :
- if ((mode & Alignment.M_INDENT_BY_ONE) != 0) {
- alignment.breakIndentationLevel = current.originalIndentationLevel + indentSize;
- } else {
- alignment.breakIndentationLevel = current.originalIndentationLevel + continuationIndent * indentSize;
- }
- alignment.update();
- break;
- }
- } else {
- switch(current.mode & Alignment.SPLIT_MASK) {
- case Alignment.M_COMPACT_SPLIT :
- case Alignment.M_COMPACT_FIRST_BREAK_SPLIT :
- case Alignment.M_NEXT_PER_LINE_SPLIT :
- case Alignment.M_NEXT_SHIFTED_SPLIT :
- case Alignment.M_ONE_PER_LINE_SPLIT :
- final int indentSize = this.indentationSize;
- switch(current.chunkKind) {
- case Alignment.CHUNK_METHOD :
- case Alignment.CHUNK_TYPE :
- if ((mode & Alignment.M_INDENT_BY_ONE) != 0) {
- alignment.breakIndentationLevel = this.indentationLevel + indentSize;
- } else {
- alignment.breakIndentationLevel = this.indentationLevel + continuationIndent * indentSize;
- }
- alignment.update();
- break;
- case Alignment.CHUNK_FIELD :
- if ((mode & Alignment.M_INDENT_BY_ONE) != 0) {
- alignment.breakIndentationLevel = current.originalIndentationLevel + indentSize;
- } else {
- alignment.breakIndentationLevel = current.originalIndentationLevel + continuationIndent * indentSize;
- }
- alignment.update();
- break;
- }
- break;
- }
- }
- }
- return alignment;
- }
-
- public Alignment createMemberAlignment(String name, int mode, int count, int sourceRestart) {
- Alignment mAlignment = createAlignment(name, mode, Alignment.R_INNERMOST, count, sourceRestart);
- mAlignment.breakIndentationLevel = this.indentationLevel;
- return mAlignment;
- }
-
- public void enterAlignment(Alignment alignment){
- alignment.enclosing = this.currentAlignment;
- alignment.location.lastLocalDeclarationSourceStart = this.formatter.lastLocalDeclarationSourceStart;
- this.currentAlignment = alignment;
- }
-
- public void enterMemberAlignment(Alignment alignment) {
- alignment.enclosing = this.memberAlignment;
- alignment.location.lastLocalDeclarationSourceStart = this.formatter.lastLocalDeclarationSourceStart;
- this.memberAlignment = alignment;
- }
-
- public void exitAlignment(Alignment alignment, boolean discardAlignment){
- Alignment current = this.currentAlignment;
- while (current != null){
- if (current == alignment) break;
- current = current.enclosing;
- }
- if (current == null) {
- throw new AbortFormatting("could not find matching alignment: "+alignment); //$NON-NLS-1$
- }
- this.indentationLevel = alignment.location.outputIndentationLevel;
- this.numberOfIndentations = alignment.location.numberOfIndentations;
- this.formatter.lastLocalDeclarationSourceStart = alignment.location.lastLocalDeclarationSourceStart;
- if (discardAlignment){
- this.currentAlignment = alignment.enclosing;
- }
- }
-
- public void exitMemberAlignment(Alignment alignment){
- Alignment current = this.memberAlignment;
- while (current != null){
- if (current == alignment) break;
- current = current.enclosing;
- }
- if (current == null) {
- throw new AbortFormatting("could not find matching alignment: "+alignment); //$NON-NLS-1$
- }
- this.indentationLevel = current.location.outputIndentationLevel;
- this.numberOfIndentations = current.location.numberOfIndentations;
- this.formatter.lastLocalDeclarationSourceStart = alignment.location.lastLocalDeclarationSourceStart;
- this.memberAlignment = current.enclosing;
- }
-
- public Alignment getAlignment(String name){
- if (this.currentAlignment != null) {
- return this.currentAlignment.getAlignment(name);
- }
- return null;
- }
-
- /**
- * Answer actual indentation level based on true column position
- * @return int
- */
- public int getColumnIndentationLevel() {
- return this.column - 1;
- }
-
- public final int getCommentIndex(int position) {
- if (this.commentPositions == null)
- return -1;
- int length = this.commentPositions.length;
- if (length == 0) {
- return -1;
- }
- int g = 0, d = length - 1;
- int m = 0;
- while (g <= d) {
- m = g + (d - g) / 2;
- int bound = this.commentPositions[m][1];
- if (bound < 0) {
- bound = -bound;
- }
- if (bound < position) {
- g = m + 1;
- } else if (bound > position) {
- d = m - 1;
- } else {
- return m;
- }
- }
- return -(g + 1);
- }
-
- private int getCurrentCommentOffset(int start) {
- int linePtr = -Arrays.binarySearch(this.lineEnds, start);
- int offset = 0;
- int beginningOfLine = this.getLineEnd(linePtr - 1);
- if (beginningOfLine == -1) {
- beginningOfLine = 0;
- }
- int currentStartPosition = start;
- char[] source = scanner.source;
-
- // find the position of the beginning of the line containing the comment
- while (beginningOfLine > currentStartPosition) {
- if (linePtr > 0) {
- beginningOfLine = this.getLineEnd(--linePtr);
- } else {
- beginningOfLine = 0;
- break;
- }
- }
- for (int i = currentStartPosition - 1; i >= beginningOfLine ; i--) {
- char currentCharacter = source[i];
- switch (currentCharacter) {
- case '\t' :
- offset += this.tabLength;
- break;
- case ' ' :
- offset++;
- break;
- case '\r' :
- case '\n' :
- break;
- default:
- return offset;
- }
- }
- return offset;
- }
-
- public String getEmptyLines(int linesNumber) {
- if (this.nlsTagCounter > 0) {
- return Util.EMPTY_STRING;
- }
- StringBuffer buffer = new StringBuffer();
- if (lastNumberOfNewLines == 0) {
- linesNumber++; // add an extra line breaks
- for (int i = 0; i < linesNumber; i++) {
- if (indentEmptyLines) printIndentationIfNecessary(buffer);
- buffer.append(this.lineSeparator);
- }
- lastNumberOfNewLines += linesNumber;
- line += linesNumber;
- column = 1;
- needSpace = false;
- this.pendingSpace = false;
- } else if (lastNumberOfNewLines == 1) {
- for (int i = 0; i < linesNumber; i++) {
- if (indentEmptyLines) printIndentationIfNecessary(buffer);
- buffer.append(this.lineSeparator);
- }
- lastNumberOfNewLines += linesNumber;
- line += linesNumber;
- column = 1;
- needSpace = false;
- this.pendingSpace = false;
- } else {
- if ((lastNumberOfNewLines - 1) >= linesNumber) {
- // there is no need to add new lines
- return Util.EMPTY_STRING;
- }
- final int realNewLineNumber = linesNumber - lastNumberOfNewLines + 1;
- for (int i = 0; i < realNewLineNumber; i++) {
- if (indentEmptyLines) printIndentationIfNecessary(buffer);
- buffer.append(this.lineSeparator);
- }
- lastNumberOfNewLines += realNewLineNumber;
- line += realNewLineNumber;
- column = 1;
- needSpace = false;
- this.pendingSpace = false;
- }
- return String.valueOf(buffer);
- }
-
- public OptimizedReplaceEdit getLastEdit() {
- if (this.editsIndex > 0) {
- return this.edits[this.editsIndex - 1];
- }
- return null;
- }
-
- public final int getLineEnd(int lineNumber) {
- if (this.lineEnds == null)
- return -1;
- if (lineNumber >= this.lineEnds.length + 1)
- return this.scannerEndPosition;
- if (lineNumber <= 0)
- return -1;
- return this.lineEnds[lineNumber-1]; // next line start one character behind the lineEnd of the previous line
- }
-
- Alignment getMemberAlignment() {
- return this.memberAlignment;
- }
-
- public String getNewLine() {
- if (this.nlsTagCounter > 0) {
- return Util.EMPTY_STRING;
- }
- if (lastNumberOfNewLines >= 1) {
- column = 1; // ensure that the scribe is at the beginning of a new line
- return Util.EMPTY_STRING;
- }
- line++;
- lastNumberOfNewLines = 1;
- column = 1;
- needSpace = false;
- this.pendingSpace = false;
- return this.lineSeparator;
- }
-
- /**
- * Answer next indentation level based on column estimated position
- * (if column is not indented, then use indentationLevel)
- */
- public int getNextIndentationLevel(int someColumn) {
- int indent = someColumn - 1;
- if (indent == 0)
- return this.indentationLevel;
- if (this.tabChar == DefaultCodeFormatterOptions.TAB) {
- if (this.useTabsOnlyForLeadingIndents) {
- return indent;
- }
- int rem = indent % this.indentationSize;
- int addition = rem == 0 ? 0 : this.indentationSize - rem; // round to superior
- return indent + addition;
- } else {
- return indent;
- }
- }
-
- private String getPreserveEmptyLines(int count) {
- if (count > 0) {
- if (this.formatter.preferences.number_of_empty_lines_to_preserve != 0) {
- int linesToPreserve = Math.min(count, this.formatter.preferences.number_of_empty_lines_to_preserve);
- return this.getEmptyLines(linesToPreserve);
- } else {
- return getNewLine();
- }
- }
- return Util.EMPTY_STRING;
- }
-
- public TextEdit getRootEdit() {
- MultiTextEdit edit = null;
- int length = this.textRegionEnd - this.textRegionStart + 1;
- if (this.textRegionStart <= 0) {
- if (length <= 0) {
- edit = new MultiTextEdit(0, 0);
- } else {
- edit = new MultiTextEdit(0, this.textRegionEnd + 1);
- }
- } else {
- edit = new MultiTextEdit(this.textRegionStart, this.textRegionEnd - this.textRegionStart + 1);
- }
- for (int i= 0, max = this.editsIndex; i < max; i++) {
- OptimizedReplaceEdit currentEdit = edits[i];
- if (isValidEdit(currentEdit)) {
- edit.addChild(new ReplaceEdit(currentEdit.offset, currentEdit.length, currentEdit.replacement));
- }
- }
- this.edits = null;
- return edit;
- }
-
- public void handleLineTooLong() {
- // search for closest breakable alignment, using tiebreak rules
- // look for outermost breakable one
- int relativeDepth = 0, outerMostDepth = -1;
- Alignment targetAlignment = this.currentAlignment;
- while (targetAlignment != null){
- if (targetAlignment.tieBreakRule == Alignment.R_OUTERMOST && targetAlignment.couldBreak()){
- outerMostDepth = relativeDepth;
- }
- targetAlignment = targetAlignment.enclosing;
- relativeDepth++;
- }
- if (outerMostDepth >= 0) {
- throw new AlignmentException(AlignmentException.LINE_TOO_LONG, outerMostDepth);
- }
- // look for innermost breakable one
- relativeDepth = 0;
- targetAlignment = this.currentAlignment;
- while (targetAlignment != null){
- if (targetAlignment.couldBreak()){
- throw new AlignmentException(AlignmentException.LINE_TOO_LONG, relativeDepth);
- }
- targetAlignment = targetAlignment.enclosing;
- relativeDepth++;
- }
- // did not find any breakable location - proceed
- }
-
- /*
- * Check if there is a NLS tag on this line. If yes, return true, returns false otherwise.
- */
- private boolean hasNLSTag(int sourceStart) {
- // search the last comment where commentEnd < current lineEnd
- if (this.lineEnds == null) return false;
- int index = Arrays.binarySearch(this.lineEnds, sourceStart);
- int currentLineEnd = this.getLineEnd(-index);
- if (currentLineEnd != -1) {
- int commentIndex = getCommentIndex(currentLineEnd);
- if (commentIndex < 0) {
- commentIndex = -commentIndex - 2;
- }
- if (commentIndex >= 0 && commentIndex < this.commentPositions.length) {
- int start = this.commentPositions[commentIndex][0];
- if (start < 0) {
- start = -start;
- // check that we are on the same line
- int lineIndexForComment = Arrays.binarySearch(this.lineEnds, start);
- if (lineIndexForComment == index) {
- return CharOperation.indexOf(Scanner.TAG_PREFIX, this.scanner.source, true, start, currentLineEnd) != -1;
- }
- }
- }
- }
- return false;
- }
-
- public void indent() {
- this.indentationLevel += this.indentationSize;
- this.numberOfIndentations++;
- }
-
- /**
- * @param compilationUnitSource
- */
- public void initializeScanner(char[] compilationUnitSource) {
- this.scanner.setSource(compilationUnitSource);
- this.scannerEndPosition = compilationUnitSource.length;
- this.scanner.resetTo(0, this.scannerEndPosition - 1);
- this.edits = new OptimizedReplaceEdit[INITIAL_SIZE];
- }
-
- private boolean isOnFirstColumn(int start) {
- if (this.lineEnds == null) return start == 0;
- int index = Arrays.binarySearch(this.lineEnds, start);
- // we want the line end of the previous line
- int previousLineEnd = this.getLineEnd(-index - 1);
- return previousLineEnd != -1 && previousLineEnd == start - 1;
- }
-
- private boolean isValidEdit(OptimizedReplaceEdit edit) {
- final int editLength= edit.length;
- final int editReplacementLength= edit.replacement.length();
- final int editOffset= edit.offset;
- if (editLength != 0) {
- /* if edit is completely inside selected range
- * else if edit is spanning the beginning of the selected range
- */
- if (this.textRegionStart <= editOffset && (editOffset + editLength - 1) <= this.textRegionEnd) {
- if (editReplacementLength != 0 && editLength == editReplacementLength) {
- for (int i = editOffset, max = editOffset + editLength; i < max; i++) {
- if (scanner.source[i] != edit.replacement.charAt(i - editOffset)) {
- return true;
- }
- }
- return false;
- } else {
- return true;
- }
- } else if (editOffset <= this.textRegionStart && editOffset + editLength >= this.textRegionStart) {
- int i = editOffset;
- for (int max = editOffset + editLength; i < max; i++) {
- int replacementStringIndex = i - editOffset;
- if (replacementStringIndex >= editReplacementLength || scanner.source[i] != edit.replacement.charAt(replacementStringIndex)) {
- break;
- }
- }
- if (i - editOffset != editReplacementLength && i != editOffset + editLength - 1) {
- edit.offset = textRegionStart;
- edit.length = 0;
- edit.replacement = edit.replacement.substring(i - editOffset);
- return true;
- }
- }
- } else if (this.textRegionStart <= editOffset && editOffset <= this.textRegionEnd) {
- return true;
- } else if (editOffset == this.scannerEndPosition && editOffset == this.textRegionEnd + 1) {
- return true;
- }
- return false;
- }
-
- private void preserveEmptyLines(int count, int insertPosition) {
- if (count > 0) {
- if (this.formatter.preferences.number_of_empty_lines_to_preserve != 0) {
- int linesToPreserve = Math.min(count, this.formatter.preferences.number_of_empty_lines_to_preserve);
- this.printEmptyLines(linesToPreserve, insertPosition);
- } else {
- printNewLine(insertPosition);
- }
- }
- }
-
- private void print(char[] s, boolean considerSpaceIfAny) {
- if (checkLineWrapping && s.length + column > this.pageWidth) {
- handleLineTooLong();
- }
- this.lastNumberOfNewLines = 0;
- if (this.indentationLevel != 0) {
- printIndentationIfNecessary();
- }
- if (considerSpaceIfAny) {
- this.space();
- }
- if (this.pendingSpace) {
- this.addInsertEdit(this.scanner.getCurrentTokenStartPosition(), " "); //$NON-NLS-1$
- }
- this.pendingSpace = false;
- this.needSpace = false;
- column += s.length;
- needSpace = true;
- }
-
- private void printBlockComment(char[] s, boolean isJavadoc) {
- int currentTokenStartPosition = this.scanner.getCurrentTokenStartPosition();
- int currentTokenEndPosition = this.scanner.getCurrentTokenEndPosition() + 1;
-
- this.scanner.resetTo(currentTokenStartPosition, currentTokenEndPosition - 1);
- int currentCharacter;
- boolean isNewLine = false;
- int start = currentTokenStartPosition;
- int nextCharacterStart = currentTokenStartPosition;
- int previousStart = currentTokenStartPosition;
- boolean onFirstColumn = isOnFirstColumn(start);
-
- boolean indentComment = false;
- if (this.indentationLevel != 0) {
- if (isJavadoc
- || !this.formatter.preferences.never_indent_block_comments_on_first_column
- || !onFirstColumn) {
- indentComment = true;
- printIndentationIfNecessary();
- }
- }
- if (this.pendingSpace) {
- this.addInsertEdit(currentTokenStartPosition, " "); //$NON-NLS-1$
- }
- this.needSpace = false;
- this.pendingSpace = false;
-
- int currentCommentOffset = onFirstColumn ? 0 : getCurrentCommentOffset(start);
- boolean formatComment = (isJavadoc && formatJavadocComment) || (!isJavadoc && formatBlockComment);
-
- while (nextCharacterStart <= currentTokenEndPosition && (currentCharacter = this.scanner.getNextChar()) != -1) {
- nextCharacterStart = this.scanner.currentPosition;
-
- switch(currentCharacter) {
- case '\r' :
- start = previousStart;
- isNewLine = true;
- if (this.scanner.getNextChar('\n')) {
- currentCharacter = '\n';
- nextCharacterStart = this.scanner.currentPosition;
- }
- break;
- case '\n' :
- start = previousStart;
- isNewLine = true;
- nextCharacterStart = this.scanner.currentPosition;
- break;
- default:
- if (isNewLine) {
- this.column = 1;
- this.line++;
- isNewLine = false;
-
- StringBuffer buffer = new StringBuffer();
- if (onFirstColumn) {
- // simply insert indentation if necessary
- buffer.append(this.lineSeparator);
- if (indentComment) {
- printIndentationIfNecessary(buffer);
- }
- if (formatComment) {
- if (ScannerHelper.isWhitespace((char) currentCharacter)) {
- int previousStartPosition = this.scanner.currentPosition;
- while(currentCharacter != -1 && currentCharacter != '\r' && currentCharacter != '\n' && ScannerHelper.isWhitespace((char) currentCharacter)) {
- previousStart = nextCharacterStart;
- previousStartPosition = this.scanner.currentPosition;
- currentCharacter = this.scanner.getNextChar();
- nextCharacterStart = this.scanner.currentPosition;
- }
- if (currentCharacter == '\r' || currentCharacter == '\n') {
- nextCharacterStart = previousStartPosition;
- }
- }
- if (currentCharacter != '\r' && currentCharacter != '\n') {
- buffer.append(' ');
- }
- }
- } else {
- if (ScannerHelper.isWhitespace((char) currentCharacter)) {
- int previousStartPosition = this.scanner.currentPosition;
- int count = 0;
- loop: while(currentCharacter != -1 && currentCharacter != '\r' && currentCharacter != '\n' && ScannerHelper.isWhitespace((char) currentCharacter)) {
- if (count >= currentCommentOffset) {
- break loop;
- }
- previousStart = nextCharacterStart;
- previousStartPosition = this.scanner.currentPosition;
- switch(currentCharacter) {
- case '\t' :
- count += this.tabLength;
- break;
- default :
- count ++;
- }
- currentCharacter = this.scanner.getNextChar();
- nextCharacterStart = this.scanner.currentPosition;
- }
- if (currentCharacter == '\r' || currentCharacter == '\n') {
- nextCharacterStart = previousStartPosition;
- }
- }
- buffer.append(this.lineSeparator);
- if (indentComment) {
- printIndentationIfNecessary(buffer);
- }
- if (formatComment) {
- int previousStartTemp = previousStart;
- int nextCharacterStartTemp = nextCharacterStart;
- while(currentCharacter != -1 && currentCharacter != '\r' && currentCharacter != '\n' && ScannerHelper.isWhitespace((char) currentCharacter)) {
- previousStart = nextCharacterStart;
- currentCharacter = this.scanner.getNextChar();
- nextCharacterStart = this.scanner.currentPosition;
- }
- if (currentCharacter == '*') {
- buffer.append(' ');
- } else {
- previousStart = previousStartTemp;
- nextCharacterStart = nextCharacterStartTemp;
- }
- this.scanner.currentPosition = nextCharacterStart;
- }
- }
- addReplaceEdit(start, previousStart - 1, String.valueOf(buffer));
- } else {
- this.column += (nextCharacterStart - previousStart);
- }
- }
- previousStart = nextCharacterStart;
- this.scanner.currentPosition = nextCharacterStart;
- }
- this.lastNumberOfNewLines = 0;
- needSpace = false;
- this.scanner.resetTo(currentTokenEndPosition, this.scannerEndPosition - 1);
- if (isJavadoc) {
- printNewLine();
- }
- }
-
- public void printEndOfCompilationUnit() {
- try {
- // if we have a space between two tokens we ensure it will be dumped in the formatted string
- int currentTokenStartPosition = this.scanner.currentPosition;
- boolean hasComment = false;
- boolean hasLineComment = false;
- boolean hasWhitespace = false;
- int count = 0;
- while (true) {
- this.currentToken = this.scanner.getNextToken();
- switch(this.currentToken) {
- case TerminalTokens.TokenNameWHITESPACE :
- char[] whiteSpaces = this.scanner.getCurrentTokenSource();
- count = 0;
- for (int i = 0, max = whiteSpaces.length; i < max; i++) {
- switch(whiteSpaces[i]) {
- case '\r' :
- if ((i + 1) < max) {
- if (whiteSpaces[i + 1] == '\n') {
- i++;
- }
- }
- count++;
- break;
- case '\n' :
- count++;
- }
- }
- if (count == 0) {
- hasWhitespace = true;
- addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition());
- } else if (hasComment) {
- if (count == 1) {
- this.printNewLine(this.scanner.getCurrentTokenStartPosition());
- } else {
- preserveEmptyLines(count - 1, this.scanner.getCurrentTokenStartPosition());
- }
- addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition());
- } else if (hasLineComment) {
- this.preserveEmptyLines(count, this.scanner.getCurrentTokenStartPosition());
- addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition());
- } else {
- addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition());
- }
- currentTokenStartPosition = this.scanner.currentPosition;
- break;
- case TerminalTokens.TokenNameCOMMENT_LINE :
- if (count >= 1) {
- if (count > 1) {
- preserveEmptyLines(count - 1, this.scanner.getCurrentTokenStartPosition());
- } else if (count == 1) {
- printNewLine(this.scanner.getCurrentTokenStartPosition());
- }
- } else if (hasWhitespace) {
- space();
- }
- hasWhitespace = false;
- this.printLineComment(this.scanner.getRawTokenSource());
- currentTokenStartPosition = this.scanner.currentPosition;
- hasLineComment = true;
- count = 0;
- break;
- case TerminalTokens.TokenNameCOMMENT_BLOCK :
- if (count >= 1) {
- if (count > 1) {
- preserveEmptyLines(count - 1, this.scanner.getCurrentTokenStartPosition());
- } else if (count == 1) {
- printNewLine(this.scanner.getCurrentTokenStartPosition());
- }
- } else if (hasWhitespace) {
- space();
- }
- hasWhitespace = false;
- this.printBlockComment(this.scanner.getRawTokenSource(), false);
- currentTokenStartPosition = this.scanner.currentPosition;
- hasLineComment = false;
- hasComment = true;
- count = 0;
- break;
- case TerminalTokens.TokenNameCOMMENT_JAVADOC :
- if (count >= 1) {
- if (count > 1) {
- preserveEmptyLines(count - 1, this.scanner.getCurrentTokenStartPosition());
- } else if (count == 1) {
- printNewLine(this.scanner.getCurrentTokenStartPosition());
- }
- } else if (hasWhitespace) {
- space();
- }
- hasWhitespace = false;
- this.printBlockComment(this.scanner.getRawTokenSource(), true);
- currentTokenStartPosition = this.scanner.currentPosition;
- hasLineComment = false;
- hasComment = true;
- count = 0;
- break;
- case TerminalTokens.TokenNameSEMICOLON :
- char[] currentTokenSource = this.scanner.getRawTokenSource();
- this.print(currentTokenSource, this.formatter.preferences.insert_space_before_semicolon);
- break;
- case TerminalTokens.TokenNameEOF :
- if (count >= 1 || this.formatter.preferences.insert_new_line_at_end_of_file_if_missing) {
- this.printNewLine(this.scannerEndPosition);
- }
- return;
- default :
- // step back one token
- this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1);
- return;
- }
- }
- } catch (InvalidInputException e) {
- throw new AbortFormatting(e);
- }
- }
-
- public void printComment() {
- try {
- // if we have a space between two tokens we ensure it will be dumped in the formatted string
- int currentTokenStartPosition = this.scanner.currentPosition;
- int previousToken=this.scanner.currentToken;
- int previousNonWSToken=this.scanner.currentNonWhitespaceToken;
- boolean hasComment = false;
- boolean hasLineComment = false;
- boolean hasWhitespace = false;
- int count = 0;
- while ((this.currentToken = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
- switch(this.currentToken) {
- case TerminalTokens.TokenNameWHITESPACE :
- char[] whiteSpaces = this.scanner.getCurrentTokenSource();
- count = 0;
- for (int i = 0, max = whiteSpaces.length; i < max; i++) {
- switch(whiteSpaces[i]) {
- case '\r' :
- if ((i + 1) < max) {
- if (whiteSpaces[i + 1] == '\n') {
- i++;
- }
- }
- count++;
- break;
- case '\n' :
- count++;
- }
- }
- if (count == 0) {
- hasWhitespace = true;
- addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition());
- } else if (hasComment) {
- if (count == 1) {
- this.printNewLine(this.scanner.getCurrentTokenStartPosition());
- } else {
- preserveEmptyLines(count - 1, this.scanner.getCurrentTokenStartPosition());
- }
- addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition());
- } else if (hasLineComment) {
- this.preserveEmptyLines(count, this.scanner.getCurrentTokenStartPosition());
- addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition());
- } else if (count != 0 && this.formatter.preferences.number_of_empty_lines_to_preserve != 0) {
- addReplaceEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition(), this.getPreserveEmptyLines(count - 1));
- } else {
- addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition());
- }
- currentTokenStartPosition = this.scanner.currentPosition;
- previousToken=this.scanner.currentToken;
- break;
- case TerminalTokens.TokenNameCOMMENT_LINE :
- if (count >= 1) {
- if (count > 1) {
- preserveEmptyLines(count - 1, this.scanner.getCurrentTokenStartPosition());
- } else if (count == 1) {
- printNewLine(this.scanner.getCurrentTokenStartPosition());
- }
- } else if (hasWhitespace) {
- space();
- }
- hasWhitespace = false;
- this.printLineComment(this.scanner.getRawTokenSource());
- currentTokenStartPosition = this.scanner.currentPosition;
- previousToken=this.scanner.currentToken;
- hasLineComment = true;
- count = 0;
- break;
- case TerminalTokens.TokenNameCOMMENT_BLOCK :
- if (count >= 1) {
- if (count > 1) {
- preserveEmptyLines(count - 1, this.scanner.getCurrentTokenStartPosition());
- } else if (count == 1) {
- printNewLine(this.scanner.getCurrentTokenStartPosition());
- }
- } else if (hasWhitespace) {
- space();
- }
- hasWhitespace = false;
- this.printBlockComment(this.scanner.getRawTokenSource(), false);
- currentTokenStartPosition = this.scanner.currentPosition;
- previousToken=this.scanner.currentToken;
- hasLineComment = false;
- hasComment = true;
- count = 0;
- break;
- case TerminalTokens.TokenNameCOMMENT_JAVADOC :
- if (count >= 1) {
- if (count > 1) {
- preserveEmptyLines(count - 1, this.scanner.getCurrentTokenStartPosition());
- } else if (count == 1) {
- printNewLine(this.scanner.getCurrentTokenStartPosition());
- }
- } else if (hasWhitespace) {
- space();
- }
- hasWhitespace = false;
- this.printBlockComment(this.scanner.getRawTokenSource(), true);
- previousToken=this.scanner.currentToken;
- currentTokenStartPosition = this.scanner.currentPosition;
- hasLineComment = false;
- hasComment = true;
- count = 0;
- break;
- default :
- // step back one token
- this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1,previousToken,previousNonWSToken);
- return;
- }
- }
- } catch (InvalidInputException e) {
- throw new AbortFormatting(e);
- }
- }
-
- private void printLineComment(char[] s) {
- int currentTokenStartPosition = this.scanner.getCurrentTokenStartPosition();
- int currentTokenEndPosition = this.scanner.getCurrentTokenEndPosition() + 1;
- if (CharOperation.indexOf(Scanner.TAG_PREFIX, this.scanner.source, true, currentTokenStartPosition, currentTokenEndPosition) != -1) {
- this.nlsTagCounter = 0;
- }
- this.scanner.resetTo(currentTokenStartPosition, currentTokenEndPosition - 1);
- int currentCharacter;
- int start = currentTokenStartPosition;
- int nextCharacterStart = currentTokenStartPosition;
-
- if (this.indentationLevel != 0) {
- if (!this.formatter.preferences.never_indent_line_comments_on_first_column
- || !isOnFirstColumn(start)) {
- printIndentationIfNecessary();
- }
- }
- if (this.pendingSpace) {
- this.addInsertEdit(currentTokenStartPosition, " "); //$NON-NLS-1$
- }
- this.needSpace = false;
- this.pendingSpace = false;
- int previousStart = currentTokenStartPosition;
-
- loop: while (nextCharacterStart <= currentTokenEndPosition && (currentCharacter = this.scanner.getNextChar()) != -1) {
- nextCharacterStart = this.scanner.currentPosition;
-
- switch(currentCharacter) {
- case '\r' :
- start = previousStart;
- break loop;
- case '\n' :
- start = previousStart;
- break loop;
- }
- previousStart = nextCharacterStart;
- }
- if (start != currentTokenStartPosition) {
- // this means that the line comment doesn't end the file
- addReplaceEdit(start, currentTokenEndPosition - 1, lineSeparator);
- this.line++;
- this.column = 1;
- this.lastNumberOfNewLines = 1;
- }
- this.needSpace = false;
- this.pendingSpace = false;
- // realign to the proper value
- if (this.currentAlignment != null) {
- if (this.memberAlignment != null) {
- // select the last alignment
- if (this.currentAlignment.location.inputOffset > this.memberAlignment.location.inputOffset) {
- if (this.currentAlignment.couldBreak() && this.currentAlignment.wasSplit) {
- this.currentAlignment.performFragmentEffect();
- }
- } else {
- this.indentationLevel = Math.max(this.indentationLevel, this.memberAlignment.breakIndentationLevel);
- }
- }
- }
- this.scanner.resetTo(currentTokenEndPosition, this.scannerEndPosition - 1);
- }
- public void printEmptyLines(int linesNumber) {
- this.printEmptyLines(linesNumber, this.scanner.getCurrentTokenEndPosition() + 1);
- }
-
- private void printEmptyLines(int linesNumber, int insertPosition) {
- final String buffer = getEmptyLines(linesNumber);
- if (Util.EMPTY_STRING == buffer) return;
-
- addInsertEdit(insertPosition, buffer);
- }
-
- void printIndentationIfNecessary() {
- StringBuffer buffer = new StringBuffer();
- printIndentationIfNecessary(buffer);
- if (buffer.length() > 0) {
- addInsertEdit(this.scanner.getCurrentTokenStartPosition(), buffer.toString());
- this.pendingSpace = false;
- }
- }
-
- private void printIndentationIfNecessary(StringBuffer buffer) {
- switch(this.tabChar) {
- case DefaultCodeFormatterOptions.TAB :
- boolean useTabsForLeadingIndents = this.useTabsOnlyForLeadingIndents;
- int numberOfLeadingIndents = this.numberOfIndentations;
- int indentationsAsTab = 0;
- if (useTabsForLeadingIndents) {
- while (this.column <= this.indentationLevel) {
- if (indentationsAsTab < numberOfLeadingIndents) {
- buffer.append('\t');
- indentationsAsTab++;
- int complement = this.tabLength - ((this.column - 1) % this.tabLength); // amount of space
- this.column += complement;
- this.needSpace = false;
- } else {
- buffer.append(' ');
- this.column++;
- this.needSpace = false;
- }
- }
- } else {
- while (this.column <= this.indentationLevel) {
- buffer.append('\t');
- int complement = this.tabLength - ((this.column - 1) % this.tabLength); // amount of space
- this.column += complement;
- this.needSpace = false;
- }
- }
- break;
- case DefaultCodeFormatterOptions.SPACE :
- while (this.column <= this.indentationLevel) {
- buffer.append(' ');
- this.column++;
- this.needSpace = false;
- }
- break;
- case DefaultCodeFormatterOptions.MIXED :
- useTabsForLeadingIndents = this.useTabsOnlyForLeadingIndents;
- numberOfLeadingIndents = this.numberOfIndentations;
- indentationsAsTab = 0;
- if (useTabsForLeadingIndents) {
- final int columnForLeadingIndents = numberOfLeadingIndents * this.indentationSize;
- while (this.column <= this.indentationLevel) {
- if (this.column <= columnForLeadingIndents) {
- if ((this.column - 1 + this.tabLength) <= this.indentationLevel) {
- buffer.append('\t');
- this.column += this.tabLength;
- } else if ((this.column - 1 + this.indentationSize) <= this.indentationLevel) {
- // print one indentation
- for (int i = 0, max = this.indentationSize; i < max; i++) {
- buffer.append(' ');
- this.column++;
- }
- } else {
- buffer.append(' ');
- this.column++;
- }
- } else {
- for (int i = this.column, max = this.indentationLevel; i <= max; i++) {
- buffer.append(' ');
- this.column++;
- }
- }
- this.needSpace = false;
- }
- } else {
- while (this.column <= this.indentationLevel) {
- if ((this.column - 1 + this.tabLength) <= this.indentationLevel) {
- buffer.append('\t');
- this.column += this.tabLength;
- } else if ((this.column - 1 + this.indentationSize) <= this.indentationLevel) {
- // print one indentation
- for (int i = 0, max = this.indentationSize; i < max; i++) {
- buffer.append(' ');
- this.column++;
- }
- } else {
- buffer.append(' ');
- this.column++;
- }
- this.needSpace = false;
- }
- }
- break;
- }
- }
-
- public void printModifiers(ASTVisitor visitor) {
- try {
- boolean isFirstModifier = true;
- int currentTokenStartPosition = this.scanner.currentPosition;
- int previousToken=this.scanner.currentToken;
- int previousNonWSToken=this.scanner.currentNonWhitespaceToken;
- boolean hasComment = false;
- boolean hasModifiers = false;
- while ((this.currentToken = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
- switch(this.currentToken) {
- case TerminalTokens.TokenNamepublic :
- case TerminalTokens.TokenNameprotected :
- case TerminalTokens.TokenNameprivate :
- case TerminalTokens.TokenNamestatic :
- case TerminalTokens.TokenNameabstract :
- case TerminalTokens.TokenNamefinal :
- case TerminalTokens.TokenNamenative :
- case TerminalTokens.TokenNamesynchronized :
- case TerminalTokens.TokenNametransient :
- case TerminalTokens.TokenNamevolatile :
- hasModifiers = true;
- this.print(this.scanner.getRawTokenSource(), !isFirstModifier);
- isFirstModifier = false;
- currentTokenStartPosition = this.scanner.currentPosition;
- previousToken=previousNonWSToken=this.scanner.currentToken;
- break;
- case TerminalTokens.TokenNameCOMMENT_BLOCK :
- this.printBlockComment(this.scanner.getRawTokenSource(), false);
- currentTokenStartPosition = this.scanner.currentPosition;
- previousToken=this.scanner.currentToken;
- hasComment = true;
- break;
- case TerminalTokens.TokenNameCOMMENT_JAVADOC :
- this.printBlockComment(this.scanner.getRawTokenSource(), true);
- currentTokenStartPosition = this.scanner.currentPosition;
- previousToken=this.scanner.currentToken;
- hasComment = true;
- break;
- case TerminalTokens.TokenNameCOMMENT_LINE :
- this.printLineComment(this.scanner.getRawTokenSource());
- currentTokenStartPosition = this.scanner.currentPosition;
- previousToken=this.scanner.currentToken;
- break;
- case TerminalTokens.TokenNameWHITESPACE :
- addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition());
- int count = 0;
- char[] whiteSpaces = this.scanner.getCurrentTokenSource();
- for (int i = 0, max = whiteSpaces.length; i < max; i++) {
- switch(whiteSpaces[i]) {
- case '\r' :
- if ((i + 1) < max) {
- if (whiteSpaces[i + 1] == '\n') {
- i++;
- }
- }
- count++;
- break;
- case '\n' :
- count++;
- }
- }
- if (count >= 1 && hasComment) {
- printNewLine();
- }
- currentTokenStartPosition = this.scanner.currentPosition;
- previousToken=this.scanner.currentToken;
- hasComment = false;
- break;
- default:
- if (hasModifiers) {
- this.space();
- }
- // step back one token
- this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1,previousToken,previousNonWSToken);
- return;
- }
- }
- } catch (InvalidInputException e) {
- throw new AbortFormatting(e);
- }
- }
-
- public void printNewLine() {
- if (this.nlsTagCounter > 0) {
- return;
- }
- if (lastNumberOfNewLines >= 1) {
- column = 1; // ensure that the scribe is at the beginning of a new line
- return;
- }
- addInsertEdit(this.scanner.getCurrentTokenEndPosition() + 1, this.lineSeparator);
- line++;
- lastNumberOfNewLines = 1;
- column = 1;
- needSpace = false;
- this.pendingSpace = false;
- }
-
- public void printNewLine(int insertPosition) {
- if (this.nlsTagCounter > 0) {
- return;
- }
- if (lastNumberOfNewLines >= 1) {
- column = 1; // ensure that the scribe is at the beginning of a new line
- return;
- }
- addInsertEdit(insertPosition, this.lineSeparator);
- line++;
- lastNumberOfNewLines = 1;
- column = 1;
- needSpace = false;
- this.pendingSpace = false;
- }
-
- public void printNextToken(int expectedTokenType){
- printNextToken(expectedTokenType, false);
- }
-
- public void printNextToken(int expectedTokenType, boolean considerSpaceIfAny){
- printComment();
- try {
- this.currentToken = this.scanner.getNextToken();
- if (expectedTokenType != this.currentToken) {
- throw new AbortFormatting("unexpected token type, expecting:"+expectedTokenType+", actual:"+this.currentToken);//$NON-NLS-1$//$NON-NLS-2$
- }
- char[] currentTokenSource = this.scanner.getRawTokenSource();
- this.print(currentTokenSource, considerSpaceIfAny);
- } catch (InvalidInputException e) {
- throw new AbortFormatting(e);
- }
- }
-
- public void printNextToken(int[] expectedTokenTypes) {
- printNextToken(expectedTokenTypes, false);
- }
-
- public void printNextToken(int[] expectedTokenTypes, boolean considerSpaceIfAny){
- printComment();
- try {
- this.currentToken = this.scanner.getNextToken();
- char[] currentTokenSource = this.scanner.getRawTokenSource();
- if (Arrays.binarySearch(expectedTokenTypes, this.currentToken) < 0) {
- StringBuffer expectations = new StringBuffer(5);
- for (int i = 0; i < expectedTokenTypes.length; i++){
- if (i > 0) {
- expectations.append(',');
- }
- expectations.append(expectedTokenTypes[i]);
- }
- throw new AbortFormatting("unexpected token type, expecting:["+expectations.toString()+"], actual:"+this.currentToken);//$NON-NLS-1$//$NON-NLS-2$
- }
- this.print(currentTokenSource, considerSpaceIfAny);
- } catch (InvalidInputException e) {
- throw new AbortFormatting(e);
- }
- }
-
-
- public void printOptionalNextToken(int expectedTokenType, boolean considerSpaceIfAny){
- printComment();
- try {
- int tokenStart=this.scanner.currentPosition;
- if (this.scanner.atEnd())
- return;
- this.currentToken = this.scanner.getNextToken();
- char[] currentTokenSource = this.scanner.getRawTokenSource();
- if (expectedTokenType != this.currentToken) {
- this.scanner.resetTo(tokenStart, this.scannerEndPosition - 1);
- }
- else
- this.print(currentTokenSource, considerSpaceIfAny);
- } catch (InvalidInputException e) {
- throw new AbortFormatting(e);
- }
- }
-
- public void printArrayQualifiedReference(int numberOfTokens, int sourceEnd) {
- int currentTokenStartPosition = this.scanner.currentPosition;
- int previousToken=this.scanner.currentToken;
- int previousNonWSToken=this.scanner.currentNonWhitespaceToken;
- int numberOfIdentifiers = 0;
- try {
- do {
- this.printComment();
- switch(this.currentToken = this.scanner.getNextToken()) {
- case TerminalTokens.TokenNameEOF :
- return;
- case TerminalTokens.TokenNameWHITESPACE :
- addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition());
- currentTokenStartPosition = this.scanner.currentPosition;
- previousToken=this.scanner.currentToken;
- break;
- case TerminalTokens.TokenNameCOMMENT_BLOCK :
- case TerminalTokens.TokenNameCOMMENT_JAVADOC :
- this.printBlockComment(this.scanner.getRawTokenSource(), false);
- currentTokenStartPosition = this.scanner.currentPosition;
- previousToken=this.scanner.currentToken;
- break;
- case TerminalTokens.TokenNameCOMMENT_LINE :
- this.printLineComment(this.scanner.getRawTokenSource());
- currentTokenStartPosition = this.scanner.currentPosition;
- previousToken=this.scanner.currentToken;
- break;
- case TerminalTokens.TokenNameIdentifier :
- this.print(this.scanner.getRawTokenSource(), false);
- currentTokenStartPosition = this.scanner.currentPosition;
- previousToken=previousNonWSToken=this.scanner.currentToken;
- if (++ numberOfIdentifiers == numberOfTokens) {
- this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1);
- return;
- }
- break;
- case TerminalTokens.TokenNameDOT :
- this.print(this.scanner.getRawTokenSource(), false);
- currentTokenStartPosition = this.scanner.currentPosition;
- previousToken=previousNonWSToken=this.scanner.currentToken;
- break;
- default:
- this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1,previousToken,previousNonWSToken);
- return;
- }
- } while (this.scanner.currentPosition <= sourceEnd);
- } catch(InvalidInputException e) {
- throw new AbortFormatting(e);
- }
- }
-
- public void printQualifiedReference(int sourceEnd) {
- int currentTokenStartPosition = this.scanner.currentPosition;
- int previousToken=this.scanner.currentToken;
- int previousNonWSToken=this.scanner.currentNonWhitespaceToken;
- try {
- do {
- this.printComment();
- switch(this.currentToken = this.scanner.getNextToken()) {
- case TerminalTokens.TokenNameEOF :
- return;
- case TerminalTokens.TokenNameWHITESPACE :
- addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition());
- currentTokenStartPosition = this.scanner.currentPosition;
- previousToken=this.scanner.currentToken;
- break;
- case TerminalTokens.TokenNameCOMMENT_BLOCK :
- case TerminalTokens.TokenNameCOMMENT_JAVADOC :
- this.printBlockComment(this.scanner.getRawTokenSource(), false);
- currentTokenStartPosition = this.scanner.currentPosition;
- previousToken=this.scanner.currentToken;
- break;
- case TerminalTokens.TokenNameCOMMENT_LINE :
- this.printLineComment(this.scanner.getRawTokenSource());
- currentTokenStartPosition = this.scanner.currentPosition;
- previousToken=this.scanner.currentToken;
- break;
- case TerminalTokens.TokenNameIdentifier :
- case TerminalTokens.TokenNameDOT :
- this.print(this.scanner.getRawTokenSource(), false);
- currentTokenStartPosition = this.scanner.currentPosition;
- previousToken=previousNonWSToken=this.scanner.currentToken;
- break;
- default:
- this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1,previousToken,previousNonWSToken);
- return;
- }
- } while (this.scanner.currentPosition <= sourceEnd);
- } catch(InvalidInputException e) {
- throw new AbortFormatting(e);
- }
- }
-
- private void printRule(StringBuffer stringBuffer) {
- for (int i = 0; i < this.pageWidth; i++){
- if ((i % this.tabLength) == 0) {
- stringBuffer.append('+');
- } else {
- stringBuffer.append('-');
- }
- }
- stringBuffer.append(this.lineSeparator);
-
- for (int i = 0; i < (pageWidth / tabLength); i++) {
- stringBuffer.append(i);
- stringBuffer.append('\t');
- }
- }
-
- public void printTrailingComment(int numberOfNewLinesToInsert) {
- try {
- // if we have a space between two tokens we ensure it will be dumped in the formatted string
- int currentTokenStartPosition = this.scanner.currentPosition;
- int previousToken=this.scanner.currentToken;
- int previousNonWSToken=this.scanner.currentNonWhitespaceToken;
- boolean hasWhitespaces = false;
- boolean hasLineComment = false;
- while ((this.currentToken = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
- switch(this.currentToken) {
- case TerminalTokens.TokenNameWHITESPACE :
- int count = 0;
- char[] whiteSpaces = this.scanner.getCurrentTokenSource();
- for (int i = 0, max = whiteSpaces.length; i < max; i++) {
- switch(whiteSpaces[i]) {
- case '\r' :
- if ((i + 1) < max) {
- if (whiteSpaces[i + 1] == '\n') {
- i++;
- }
- }
- count++;
- break;
- case '\n' :
- count++;
- }
- }
- if (hasLineComment) {
- if (count >= 1) {
- currentTokenStartPosition = this.scanner.getCurrentTokenStartPosition();
- this.preserveEmptyLines(numberOfNewLinesToInsert, currentTokenStartPosition);
- addDeleteEdit(currentTokenStartPosition, this.scanner.getCurrentTokenEndPosition());
- this.scanner.resetTo(this.scanner.currentPosition, this.scannerEndPosition - 1);
- return;
- } else {
- this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1,previousToken,previousNonWSToken);
- return;
- }
- } else if (count > 1) {
- this.printEmptyLines(numberOfNewLinesToInsert, this.scanner.getCurrentTokenStartPosition());
- this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1,previousToken,previousNonWSToken);
- return;
- } else {
- hasWhitespaces = true;
- currentTokenStartPosition = this.scanner.currentPosition;
- previousToken=this.scanner.currentToken;
- addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition());
- }
- break;
- case TerminalTokens.TokenNameCOMMENT_LINE :
- if (hasWhitespaces) {
- space();
- }
- this.printLineComment(this.scanner.getRawTokenSource());
- currentTokenStartPosition = this.scanner.currentPosition;
- previousToken=this.scanner.currentToken;
- hasLineComment = true;
- break;
- case TerminalTokens.TokenNameCOMMENT_BLOCK :
- if (hasWhitespaces) {
- space();
- }
- this.printBlockComment(this.scanner.getRawTokenSource(), false);
- currentTokenStartPosition = this.scanner.currentPosition;
- previousToken=this.scanner.currentToken;
- break;
- default :
- // step back one token
- this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1,previousToken,previousNonWSToken);
- return;
- }
- }
- } catch (InvalidInputException e) {
- throw new AbortFormatting(e);
- }
- }
- public void printTrailingComment() {
- try {
- // if we have a space between two tokens we ensure it will be dumped in the formatted string
- int currentTokenStartPosition = this.scanner.currentPosition;
- int previousToken=this.scanner.currentToken;
- int previousNonWSToken=this.scanner.currentNonWhitespaceToken;
-
- boolean hasWhitespaces = false;
- boolean hasComment = false;
- boolean hasLineComment = false;
- while ((this.currentToken = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) {
- switch(this.currentToken) {
- case TerminalTokens.TokenNameWHITESPACE :
- int count = 0;
- char[] whiteSpaces = this.scanner.getCurrentTokenSource();
- for (int i = 0, max = whiteSpaces.length; i < max; i++) {
- switch(whiteSpaces[i]) {
- case '\r' :
- if ((i + 1) < max) {
- if (whiteSpaces[i + 1] == '\n') {
- i++;
- }
- }
- count++;
- break;
- case '\n' :
- count++;
- }
- }
- if (hasLineComment) {
- if (count >= 1) {
- currentTokenStartPosition = this.scanner.getCurrentTokenStartPosition();
- this.preserveEmptyLines(count, currentTokenStartPosition);
- addDeleteEdit(currentTokenStartPosition, this.scanner.getCurrentTokenEndPosition());
- this.scanner.resetTo(this.scanner.currentPosition, this.scannerEndPosition - 1);
- return;
- } else {
- this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1,previousToken,previousNonWSToken);
- return;
- }
- } else if (count >= 1) {
- if (hasComment) {
- this.printNewLine(this.scanner.getCurrentTokenStartPosition());
- }
- this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1,previousToken,previousNonWSToken);
- return;
- } else {
- hasWhitespaces = true;
- currentTokenStartPosition = this.scanner.currentPosition;
- previousToken=this.scanner.currentToken;
- addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition());
- }
- break;
- case TerminalTokens.TokenNameCOMMENT_LINE :
- if (hasWhitespaces) {
- space();
- }
- this.printLineComment(this.scanner.getRawTokenSource());
- currentTokenStartPosition = this.scanner.currentPosition;
- previousToken=this.scanner.currentToken;
- hasLineComment = true;
- break;
- case TerminalTokens.TokenNameCOMMENT_BLOCK :
- if (hasWhitespaces) {
- space();
- }
- this.printBlockComment(this.scanner.getRawTokenSource(), false);
- currentTokenStartPosition = this.scanner.currentPosition;
- previousToken=this.scanner.currentToken;
- hasComment = true;
- break;
- default :
- // step back one token
- this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1,previousToken,previousNonWSToken);
- return;
- }
- }
- } catch (InvalidInputException e) {
- throw new AbortFormatting(e);
- }
- }
-
- void redoAlignment(AlignmentException e){
- if (e.relativeDepth > 0) { // if exception targets a distinct context
- e.relativeDepth--; // record fact that current context got traversed
- this.currentAlignment = this.currentAlignment.enclosing; // pop currentLocation
- throw e; // rethrow
- }
- // reset scribe/scanner to restart at this given location
- this.resetAt(this.currentAlignment.location);
- this.scanner.resetTo(this.currentAlignment.location.inputOffset, this.scanner.eofPosition,this.currentAlignment.location.inputToken,this.currentAlignment.location.inputTokenNonWS);
- // clean alignment chunkKind so it will think it is a new chunk again
- this.currentAlignment.chunkKind = 0;
- }
-
- void redoMemberAlignment(AlignmentException e){
- // reset scribe/scanner to restart at this given location
- this.resetAt(this.memberAlignment.location);
- this.scanner.resetTo(this.memberAlignment.location.inputOffset, this.scanner.eofPosition,this.memberAlignment.location.inputToken,this.currentAlignment.location.inputTokenNonWS);
- // clean alignment chunkKind so it will think it is a new chunk again
- this.memberAlignment.chunkKind = 0;
- }
-
- public void reset() {
- this.checkLineWrapping = true;
- this.line = 0;
- this.column = 1;
- this.editsIndex = 0;
- this.nlsTagCounter = 0;
- }
-
- private void resetAt(Location location) {
- this.line = location.outputLine;
- this.column = location.outputColumn;
- this.indentationLevel = location.outputIndentationLevel;
- this.numberOfIndentations = location.numberOfIndentations;
- this.lastNumberOfNewLines = location.lastNumberOfNewLines;
- this.needSpace = location.needSpace;
- this.pendingSpace = location.pendingSpace;
- this.editsIndex = location.editsIndex;
- this.nlsTagCounter = location.nlsTagCounter;
- if (this.editsIndex > 0) {
- this.edits[this.editsIndex - 1] = location.textEdit;
- }
- this.formatter.lastLocalDeclarationSourceStart = location.lastLocalDeclarationSourceStart;
- }
-
- private void resize() {
- System.arraycopy(this.edits, 0, (this.edits = new OptimizedReplaceEdit[this.editsIndex * 2]), 0, this.editsIndex);
- }
-
- public void space() {
- if (!this.needSpace) return;
- this.lastNumberOfNewLines = 0;
- this.pendingSpace = true;
- this.column++;
- this.needSpace = false;
- }
-
- public String toString() {
- StringBuffer stringBuffer = new StringBuffer();
- stringBuffer
- .append("(page width = " + this.pageWidth + ") - (tabChar = ");//$NON-NLS-1$//$NON-NLS-2$
- switch(this.tabChar) {
- case DefaultCodeFormatterOptions.TAB :
- stringBuffer.append("TAB");//$NON-NLS-1$
- break;
- case DefaultCodeFormatterOptions.SPACE :
- stringBuffer.append("SPACE");//$NON-NLS-1$
- break;
- default :
- stringBuffer.append("MIXED");//$NON-NLS-1$
- }
- stringBuffer
- .append(") - (tabSize = " + this.tabLength + ")")//$NON-NLS-1$//$NON-NLS-2$
- .append(this.lineSeparator)
- .append("(line = " + this.line + ") - (column = " + this.column + ") - (identationLevel = " + this.indentationLevel + ")") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- .append(this.lineSeparator)
- .append("(needSpace = " + this.needSpace + ") - (lastNumberOfNewLines = " + this.lastNumberOfNewLines + ") - (checkLineWrapping = " + this.checkLineWrapping + ")") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- .append(this.lineSeparator)
- .append("==================================================================================") //$NON-NLS-1$
- .append(this.lineSeparator);
- printRule(stringBuffer);
- return stringBuffer.toString();
- }
-
- public void unIndent() {
- this.indentationLevel -= this.indentationSize;
- this.numberOfIndentations--;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/align/Alignment.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/align/Alignment.java
deleted file mode 100644
index 1aff487e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/align/Alignment.java
+++ /dev/null
@@ -1,417 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.formatter.align;
-
-import org.eclipse.wst.jsdt.internal.formatter.Location;
-import org.eclipse.wst.jsdt.internal.formatter.Scribe;
-
-/**
- * Alignment management
- *
- * @since 2.1
- */
-public class Alignment {
-
- // name of alignment
- public String name;
-
- // link to enclosing alignment
- public Alignment enclosing;
-
- // start location of this alignment
- public Location location;
-
- // indentation management
- public int fragmentIndex;
- public int fragmentCount;
- public int[] fragmentIndentations;
- public boolean needRedoColumnAlignment;
-
- // chunk management
- public int chunkStartIndex;
- public int chunkKind;
-
- // break management
- public int originalIndentationLevel;
- public int breakIndentationLevel;
- public int shiftBreakIndentationLevel;
- public int[] fragmentBreaks;
- public boolean wasSplit;
-
- public Scribe scribe;
-
- /*
- * Alignment modes
- */
- public static final int M_FORCE = 1; // if bit set, then alignment will be non-optional (default is optional)
- public static final int M_INDENT_ON_COLUMN = 2; // if bit set, broken fragments will be aligned on current location column (default is to break at current indentation level)
- public static final int M_INDENT_BY_ONE = 4; // if bit set, broken fragments will be indented one level below current (not using continuation indentation)
-
- // split modes can be combined either with M_FORCE or M_INDENT_ON_COLUMN
-
- /** foobar(#fragment1, #fragment2, <ul>
- * <li> #fragment3, #fragment4 </li>
- * </ul>
- */
- public static final int M_COMPACT_SPLIT = 16; // fill each line with all possible fragments
-
- /** foobar(<ul>
- * <li> #fragment1, #fragment2, </li>
- * <li> #fragment5, #fragment4, </li>
- * </ul>
- */
- public static final int M_COMPACT_FIRST_BREAK_SPLIT = 32; // compact mode, but will first try to break before first fragment
-
- /** foobar(<ul>
- * <li> #fragment1, </li>
- * <li> #fragment2, </li>
- * <li> #fragment3 </li>
- * <li> #fragment4, </li>
- * </ul>
- */
- public static final int M_ONE_PER_LINE_SPLIT = 32+16; // one fragment per line
-
- /**
- * foobar(<ul>
- * <li> #fragment1, </li>
- * <li> #fragment2, </li>
- * <li> #fragment3 </li>
- * <li> #fragment4, </li>
- * </ul>
- */
- public static final int M_NEXT_SHIFTED_SPLIT = 64; // one fragment per line, subsequent are indented further
-
- /** foobar(#fragment1, <ul>
- * <li> #fragment2, </li>
- * <li> #fragment3 </li>
- * <li> #fragment4, </li>
- * </ul>
- */
- public static final int M_NEXT_PER_LINE_SPLIT = 64+16; // one per line, except first fragment (if possible)
-
- //64+32
- //64+32+16
-
- // mode controlling column alignments
- /**
- * <table BORDER COLS=4 WIDTH="100%" >
- * <tr><td>#fragment1A</td> <td>#fragment2A</td> <td>#fragment3A</td> <td>#very-long-fragment4A</td></tr>
- * <tr><td>#fragment1B</td> <td>#long-fragment2B</td> <td>#fragment3B</td> <td>#fragment4B</td></tr>
- * <tr><td>#very-long-fragment1C</td> <td>#fragment2C</td> <td>#fragment3C</td> <td>#fragment4C</td></tr>
- * </table>
- */
- public static final int M_MULTICOLUMN = 256; // fragments are on same line, but multiple line of fragments will be aligned vertically
-
- public static final int M_NO_ALIGNMENT = 0;
-
- public int mode;
-
- public static final int SPLIT_MASK = M_ONE_PER_LINE_SPLIT | M_NEXT_SHIFTED_SPLIT | M_COMPACT_SPLIT | M_COMPACT_FIRST_BREAK_SPLIT | M_NEXT_PER_LINE_SPLIT;
-
- // alignment tie-break rules - when split is needed, will decide whether innermost/outermost alignment is to be chosen
- public static final int R_OUTERMOST = 1;
- public static final int R_INNERMOST = 2;
- public int tieBreakRule;
-
- // alignment effects on a per fragment basis
- public static final int NONE = 0;
- public static final int BREAK = 1;
-
- // chunk kind
- public static final int CHUNK_FIELD = 1;
- public static final int CHUNK_METHOD = 2;
- public static final int CHUNK_TYPE = 3;
- public static final int CHUNK_ENUM = 4;
-
- // location to align and break on.
- public Alignment(String name, int mode, int tieBreakRule, Scribe scribe, int fragmentCount, int sourceRestart, int continuationIndent){
-
- this.name = name;
- this.location = new Location(scribe, sourceRestart);
- this.mode = mode;
- this.tieBreakRule = tieBreakRule;
- this.fragmentCount = fragmentCount;
- this.scribe = scribe;
- this.originalIndentationLevel = this.scribe.indentationLevel;
- this.wasSplit = false;
-
- // initialize the break indentation level, using modes and continuationIndentationLevel preference
- final int indentSize = this.scribe.indentationSize;
- int currentColumn = this.location.outputColumn;
- if (currentColumn == 1) {
- currentColumn = this.location.outputIndentationLevel + 1;
- }
-
- if ((mode & M_INDENT_ON_COLUMN) != 0) {
- // indent broken fragments at next indentation level, based on current column
- this.breakIndentationLevel = this.scribe.getNextIndentationLevel(currentColumn);
- if (this.breakIndentationLevel == this.location.outputIndentationLevel) {
- this.breakIndentationLevel += (continuationIndent * indentSize);
- }
- } else if ((mode & M_INDENT_BY_ONE) != 0) {
- // indent broken fragments exactly one level deeper than current indentation
- this.breakIndentationLevel = this.location.outputIndentationLevel + indentSize;
- } else {
- this.breakIndentationLevel = this.location.outputIndentationLevel + continuationIndent * indentSize;
- }
- this.shiftBreakIndentationLevel = this.breakIndentationLevel + indentSize;
-
- this.fragmentIndentations = new int[this.fragmentCount];
- this.fragmentBreaks = new int[this.fragmentCount];
-
- // check for forced alignments
- if ((this.mode & M_FORCE) != 0) {
- couldBreak();
- }
- }
-
- public boolean checkChunkStart(int kind, int startIndex, int sourceRestart) {
- if (this.chunkKind != kind) {
- this.chunkKind = kind;
-
- // when redoing same chunk alignment, must not reset
- if (startIndex != this.chunkStartIndex) {
- this.chunkStartIndex = startIndex;
- this.location.update(this.scribe, sourceRestart);
- reset();
- }
- return true;
- }
- return false;
- }
-
- public void checkColumn() {
- if ((this.mode & M_MULTICOLUMN) != 0) {
- int currentIndentation = this.scribe.getNextIndentationLevel(this.scribe.column+(this.scribe.needSpace ? 1 : 0));
- int fragmentIndentation = this.fragmentIndentations[this.fragmentIndex];
- if (currentIndentation > fragmentIndentation) {
- this.fragmentIndentations[this.fragmentIndex] = currentIndentation;
- if (fragmentIndentation != 0) {
- for (int i = this.fragmentIndex+1; i < this.fragmentCount; i++) {
- this.fragmentIndentations[i] = 0;
- }
- this.needRedoColumnAlignment = true;
- }
- }
- // backtrack only once all fragments got checked
- if (this.needRedoColumnAlignment && this.fragmentIndex == this.fragmentCount-1) { // alignment too small
-
-// if (CodeFormatterVisitor.DEBUG){
-// System.out.println("ALIGNMENT TOO SMALL");
-// System.out.println(this);
-// }
- this.needRedoColumnAlignment = false;
- int relativeDepth = 0;
- Alignment targetAlignment = this.scribe.memberAlignment;
- while (targetAlignment != null){
- if (targetAlignment == this){
- throw new AlignmentException(AlignmentException.ALIGN_TOO_SMALL, relativeDepth);
- }
- targetAlignment = targetAlignment.enclosing;
- relativeDepth++;
- }
- }
- }
- }
-
- public boolean couldBreak(){
- int i;
- switch(mode & SPLIT_MASK){
-
- /* # aligned fragment
- * foo(
- * #AAAAA, #BBBBB,
- * #CCCC);
- */
- case M_COMPACT_FIRST_BREAK_SPLIT :
- if (this.fragmentBreaks[0] == NONE) {
- this.fragmentBreaks[0] = BREAK;
- this.fragmentIndentations[0] = this.breakIndentationLevel;
- return wasSplit = true;
- }
- i = this.fragmentIndex;
- do {
- if (this.fragmentBreaks[i] == NONE) {
- this.fragmentBreaks[i] = BREAK;
- this.fragmentIndentations[i] = this.breakIndentationLevel;
- return wasSplit = true;
- }
- } while (--i >= 0);
- break;
- /* # aligned fragment
- * foo(#AAAAA, #BBBBB,
- * #CCCC);
- */
- case M_COMPACT_SPLIT :
- i = this.fragmentIndex;
- do {
- if (this.fragmentBreaks[i] == NONE) {
- this.fragmentBreaks[i] = BREAK;
- this.fragmentIndentations[i] = this.breakIndentationLevel;
- return wasSplit = true;
- }
- } while (--i >= 0);
- break;
-
- /* # aligned fragment
- * foo(
- * #AAAAA,
- * #BBBBB,
- * #CCCC);
- */
- case M_NEXT_SHIFTED_SPLIT :
- if (this.fragmentBreaks[0] == NONE) {
- this.fragmentBreaks[0] = BREAK;
- this.fragmentIndentations[0] = this.breakIndentationLevel;
- for (i = 1; i < this.fragmentCount; i++){
- this.fragmentBreaks[i] = BREAK;
- this.fragmentIndentations[i] = this.shiftBreakIndentationLevel;
- }
- return wasSplit = true;
- }
- break;
-
- /* # aligned fragment
- * foo(
- * #AAAAA,
- * #BBBBB,
- * #CCCC);
- */
- case M_ONE_PER_LINE_SPLIT :
- if (this.fragmentBreaks[0] == NONE) {
- for (i = 0; i < this.fragmentCount; i++){
- this.fragmentBreaks[i] = BREAK;
- this.fragmentIndentations[i] = this.breakIndentationLevel;
- }
- return wasSplit = true;
- }
- /* # aligned fragment
- * foo(#AAAAA,
- * #BBBBB,
- * #CCCC);
- */
- case M_NEXT_PER_LINE_SPLIT :
- if (this.fragmentBreaks[0] == NONE) {
- if (this.fragmentCount > 1
- && this.fragmentBreaks[1] == NONE) {
- if ((this.mode & M_INDENT_ON_COLUMN) != 0) {
- this.fragmentIndentations[0] = this.breakIndentationLevel;
- }
- for (i = 1; i < this.fragmentCount; i++) {
- this.fragmentBreaks[i] = BREAK;
- this.fragmentIndentations[i] = this.breakIndentationLevel;
- }
- return wasSplit = true;
- }
- }
- break;
- }
- return false; // cannot split better
- }
-
- public Alignment getAlignment(String targetName) {
-
- if (targetName.equals(this.name)) return this;
- if (this.enclosing == null) return null;
-
- return this.enclosing.getAlignment(targetName);
- }
-
- // perform alignment effect for current fragment
- public void performFragmentEffect(){
- if ((this.mode & M_MULTICOLUMN) == 0) {
- switch(this.mode & SPLIT_MASK) {
- case Alignment.M_COMPACT_SPLIT :
- case Alignment.M_COMPACT_FIRST_BREAK_SPLIT :
- case Alignment.M_NEXT_PER_LINE_SPLIT :
- case Alignment.M_NEXT_SHIFTED_SPLIT :
- case Alignment.M_ONE_PER_LINE_SPLIT :
- break;
- default:
- return;
- }
- }
-
- if (this.fragmentBreaks[this.fragmentIndex] == BREAK) {
- this.scribe.printNewLine();
- }
- if (this.fragmentIndentations[this.fragmentIndex] > 0) {
- this.scribe.indentationLevel = this.fragmentIndentations[this.fragmentIndex];
- }
- }
-
- // reset fragment indentation/break status
- public void reset() {
-
- if (fragmentCount > 0){
- this.fragmentIndentations = new int[this.fragmentCount];
- this.fragmentBreaks = new int[this.fragmentCount];
- }
-
- // check for forced alignments
- if ((mode & M_FORCE) != 0) {
- couldBreak();
- }
- }
-
- public void toFragmentsString(StringBuffer buffer){
- // default implementation
- }
-
- public String toString() {
- StringBuffer buffer = new StringBuffer(10);
- buffer
- .append(getClass().getName())
- .append(':')
- .append("<name: ") //$NON-NLS-1$
- .append(this.name)
- .append(">"); //$NON-NLS-1$
- if (this.enclosing != null) {
- buffer
- .append("<enclosingName: ") //$NON-NLS-1$
- .append(this.enclosing.name)
- .append('>');
- }
- buffer.append('\n');
-
- for (int i = 0; i < this.fragmentCount; i++){
- buffer
- .append(" - fragment ") //$NON-NLS-1$
- .append(i)
- .append(": ") //$NON-NLS-1$
- .append("<break: ") //$NON-NLS-1$
- .append(this.fragmentBreaks[i] > 0 ? "YES" : "NO") //$NON-NLS-1$ //$NON-NLS-2$
- .append(">") //$NON-NLS-1$
- .append("<indent: ") //$NON-NLS-1$
- .append(this.fragmentIndentations[i])
- .append(">\n"); //$NON-NLS-1$
- }
- buffer.append('\n');
- return buffer.toString();
- }
-
- public void update() {
- for (int i = 1; i < this.fragmentCount; i++){
- if (this.fragmentBreaks[i] == BREAK) {
- this.fragmentIndentations[i] = this.breakIndentationLevel;
- }
- }
- }
-
- public boolean isWrapped() {
- for (int i = 0, max = this.fragmentCount; i < max; i++) {
- if (this.fragmentBreaks[i] == BREAK) {
- return true;
- }
- }
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/align/AlignmentException.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/align/AlignmentException.java
deleted file mode 100644
index ba1b5585..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/align/AlignmentException.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.formatter.align;
-
-/**
- * Exception used to backtrack and break available alignments
- * When the exception is thrown, it is assumed that some alignment will be changed.
- *
- * @since 2.1
- */
-public class AlignmentException extends RuntimeException {
-
- public static final int LINE_TOO_LONG = 1;
- public static final int ALIGN_TOO_SMALL = 2;
- private static final long serialVersionUID = -3324134986466253314L; // backward compatible
-
- int reason;
- int value;
- public int relativeDepth;
-
- public AlignmentException(int reason, int relativeDepth) {
- this(reason, 0, relativeDepth);
- }
-
- public AlignmentException(int reason, int value, int relativeDepth) {
- this.reason = reason;
- this.value = value;
- this.relativeDepth = relativeDepth;
- }
-
- public String toString(){
- StringBuffer buffer = new StringBuffer(10);
- switch(this.reason){
- case LINE_TOO_LONG :
- buffer.append("LINE_TOO_LONG"); //$NON-NLS-1$
- break;
- case ALIGN_TOO_SMALL :
- buffer.append("ALIGN_TOO_SMALL"); //$NON-NLS-1$
- break;
- }
- buffer
- .append("<relativeDepth: ") //$NON-NLS-1$
- .append(this.relativeDepth)
- .append(">\n"); //$NON-NLS-1$
- return buffer.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/CommentFormatterUtil.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/CommentFormatterUtil.java
deleted file mode 100644
index ebdb1e0b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/CommentFormatterUtil.java
+++ /dev/null
@@ -1,119 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.formatter.comment;
-
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.BadPositionCategoryException;
-import org.eclipse.jface.text.DefaultPositionUpdater;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.Position;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.ToolFactory;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * Comment formatting utils.
- *
- * @since 3.1
- */
-public class CommentFormatterUtil {
-
- /**
- * Evaluates the edit on the given string.
- *
- * @throws IllegalArgumentException if the positions are not inside the
- * string
- */
- public static String evaluateFormatterEdit(String string, TextEdit edit, Position[] positions) {
- try {
- Document doc= createDocument(string, positions);
- edit.apply(doc, 0);
- if (positions != null) {
- for (int i= 0; i < positions.length; i++) {
- Assert.isTrue(!positions[i].isDeleted, "Position got deleted"); //$NON-NLS-1$
- }
- }
- return doc.get();
- } catch (BadLocationException e) {
- log(e); // bug in the formatter
- Assert.isTrue(false, "Formatter created edits with wrong positions: " + e.getMessage()); //$NON-NLS-1$
- }
- return null;
- }
-
- /**
- * Creates edits that describe how to format the given string. Returns
- * <code>null</code> if the code could not be formatted for the given
- * kind.
- *
- * @throws IllegalArgumentException if the offset and length are not
- * inside the string
- */
- public static TextEdit format2(int kind, String string, int indentationLevel, String lineSeparator, Map options) {
- int length= string.length();
- if (0 < 0 || length < 0 || 0 + length > string.length()) {
- throw new IllegalArgumentException("offset or length outside of string. offset: " + 0 + ", length: " + length + ", string size: " + string.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
- }
- return ToolFactory.createCodeFormatter(options).format(kind, string, 0, length, indentationLevel, lineSeparator);
- }
-
- /**
- * Returns a document with the given content and the given positions
- * registered with the {@link DefaultPositionUpdater}.
- *
- * @param content the content
- * @param positions the positions
- * @return the document
- * @throws IllegalArgumentException
- */
- private static Document createDocument(String content, Position[] positions) throws IllegalArgumentException {
- Document doc= new Document(content);
- try {
- if (positions != null) {
- final String POS_CATEGORY= "myCategory"; //$NON-NLS-1$
-
- doc.addPositionCategory(POS_CATEGORY);
- doc.addPositionUpdater(new DefaultPositionUpdater(POS_CATEGORY) {
- protected boolean notDeleted() {
- if (fOffset < fPosition.offset && (fPosition.offset + fPosition.length < fOffset + fLength)) {
- fPosition.offset= fOffset + fLength; // deleted positions: set to end of remove
- return false;
- }
- return true;
- }
- });
- for (int i= 0; i < positions.length; i++) {
- try {
- doc.addPosition(POS_CATEGORY, positions[i]);
- } catch (BadLocationException e) {
- throw new IllegalArgumentException("Position outside of string. offset: " + positions[i].offset + ", length: " + positions[i].length + ", string size: " + content.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
- }
- }
- }
- } catch (BadPositionCategoryException cannotHappen) {
- // can not happen: category is correctly set up
- }
- return doc;
- }
-
- /**
- * Logs the given throwable.
- *
- * @param t the throwable
- * @since 3.1
- */
- public static void log(Throwable t) {
- Util.log(t, "Exception occured while formatting comments"); //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/CommentLine.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/CommentLine.java
deleted file mode 100644
index 88b77195..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/CommentLine.java
+++ /dev/null
@@ -1,315 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.formatter.comment;
-
-import java.util.LinkedList;
-
-import org.eclipse.wst.jsdt.internal.compiler.parser.ScannerHelper;
-
-/**
- * General comment line in a comment region.
- *
- * @since 3.0
- */
-public abstract class CommentLine implements IBorderAttributes {
-
- /** Prefix of non-formattable comment lines */
- protected static final String NON_FORMAT_START_PREFIX= "/*-"; //$NON-NLS-1$
-
- /** The attributes of this line */
- private int fAttributes= 0;
-
- /** The parent region of this line */
- private final CommentRegion fParent;
-
- /** The comment ranges in this line */
- private final LinkedList fRanges= new LinkedList();
-
- /**
- * Creates a new comment line.
- *
- * @param parent comment region to create the comment line for
- */
- protected CommentLine(final CommentRegion parent) {
- fParent= parent;
- }
-
- /**
- * Adapts the line attributes from the previous line in the comment
- * region.
- *
- * @param previous the previous comment line in the comment region
- */
- protected abstract void adapt(final CommentLine previous);
-
- /**
- * Appends the specified comment range to this comment line.
- *
- * @param range comment range to append to this line
- */
- protected void append(final CommentRange range) {
- fRanges.add(range);
- }
-
- /**
- * Formats this comment line as content line.
- *
- * @param predecessor the predecessor comment line in the comment region
- * @param last the most recently processed comment range
- * @param indentation the indentation of the comment region
- * @param line the index of this comment line in the comment region
- * @return the first comment range in this comment line
- */
- protected CommentRange formatLine(final CommentLine predecessor, final CommentRange last, final String indentation, final int line) {
-
- int offset= 0;
- int length= 0;
-
- CommentRange next= last;
- CommentRange previous= null;
-
- final int stop= fRanges.size() - 1;
- final int end= fParent.getSize() - 1;
-
- for (int index= stop; index >= 0; index--) {
-
- previous= next;
- next= (CommentRange)fRanges.get(index);
-
- if (fParent.canFormat(previous, next)) {
-
- offset= next.getOffset() + next.getLength();
- length= previous.getOffset() - offset;
-
- if (index == stop && line != end)
- fParent.logEdit(fParent.getDelimiter(predecessor, this, previous, next, indentation), offset, length);
- else
- fParent.logEdit(fParent.getDelimiter(previous, next), offset, length);
- }
- }
- return next;
- }
-
- /**
- * Formats this comment line as end line having a lower border
- * consisting of content line prefixes.
- *
- * @param range last comment range of the last comment line in the
- * comment region
- * @param indentation the indentation of the comment region
- * @param length the maximal length of text in this comment region
- * measured in average character widths
- */
- protected void formatLowerBorder(final CommentRange range, final String indentation, final int length) {
-
- final int offset= range.getOffset() + range.getLength();
-
- final StringBuffer buffer= new StringBuffer(length);
- final String end= getEndingPrefix();
- final String delimiter= fParent.getDelimiter();
-
- if (fParent.isSingleLine() && fParent.getSize() == 1)
- buffer.append(end);
- else {
-
- final String filler= getContentPrefix().trim();
-
- buffer.append(delimiter);
- buffer.append(indentation);
-
- if (fParent.hasBorder(BORDER_LOWER)) {
-
- buffer.append(' ');
- for (int character= 0; character < length; character++)
- buffer.append(filler);
-
- buffer.append(end.trim());
-
- } else
- buffer.append(end);
- }
- fParent.logEdit(buffer.toString(), offset, fParent.getLength() - offset);
- }
-
- /**
- * Formats this comment line as start line having an upper border
- * consisting of content line prefixes.
- *
- * @param range the first comment range in the comment region
- * @param indentation the indentation of the comment region
- * @param length the maximal length of text in this comment region
- * measured in average character widths
- */
- protected void formatUpperBorder(final CommentRange range, final String indentation, final int length) {
-
- final StringBuffer buffer= new StringBuffer(length);
- final String start= getStartingPrefix();
- final String content= getContentPrefix();
-
- if (fParent.isSingleLine() && fParent.getSize() == 1)
- buffer.append(start);
- else {
-
- final String trimmed= start.trim();
- final String filler= content.trim();
-
- buffer.append(trimmed);
-
- if (fParent.hasBorder(BORDER_UPPER)) {
-
- for (int character= 0; character < length - trimmed.length() + start.length(); character++)
- buffer.append(filler);
- }
-
- buffer.append(fParent.getDelimiter());
- buffer.append(indentation);
- buffer.append(content);
- }
- fParent.logEdit(buffer.toString(), 0, range.getOffset());
- }
-
- /**
- * Returns the line prefix of content lines.
- *
- * @return line prefix of content lines
- */
- protected abstract String getContentPrefix();
-
- /**
- * Returns the line prefix of end lines.
- *
- * @return line prefix of end lines
- */
- protected abstract String getEndingPrefix();
-
- /**
- * Returns the first comment range in this comment line.
- *
- * @return the first comment range
- */
- protected final CommentRange getFirst() {
- return (CommentRange)fRanges.getFirst();
- }
-
- /**
- * Returns the indentation reference string for this line.
- *
- * @return the indentation reference string for this line
- */
- protected String getIndentationReference() {
- return ""; //$NON-NLS-1$
- }
-
- /**
- * Returns the last comment range in this comment line.
- *
- * @return the last comment range
- */
- protected final CommentRange getLast() {
- return (CommentRange)fRanges.getLast();
- }
-
- /**
- * Returns the parent comment region of this comment line.
- *
- * @return the parent comment region
- */
- protected final CommentRegion getParent() {
- return fParent;
- }
-
- /**
- * Returns the number of comment ranges in this comment line.
- *
- * @return the number of ranges in this line
- */
- protected final int getSize() {
- return fRanges.size();
- }
-
- /**
- * Returns the line prefix of start lines.
- *
- * @return line prefix of start lines
- */
- protected abstract String getStartingPrefix();
-
- /**
- * Is the attribute <code>attribute</code> true?
- *
- * @param attribute the attribute to get.
- * @return <code>true</code> iff this attribute is <code>true</code>,
- * <code>false</code> otherwise.
- */
- protected final boolean hasAttribute(final int attribute) {
- return (fAttributes & attribute) == attribute;
- }
-
- /**
- * Scans this comment line for comment range boundaries.
- *
- * @param line the index of this line in the comment region
- */
- protected abstract void scanLine(final int line);
-
- /**
- * Set the attribute <code>attribute</code> to true.
- *
- * @param attribute the attribute to set.
- */
- protected final void setAttribute(final int attribute) {
- fAttributes |= attribute;
- }
-
- /**
- * Tokenizes this comment line into comment ranges
- *
- * @param line the index of this line in the comment region
- */
- protected void tokenizeLine(final int line) {
-
- int offset= 0;
- int index= offset;
-
- final CommentRange range= (CommentRange)fRanges.get(0);
- final int begin= range.getOffset();
-
- final String content= fParent.getText(begin, range.getLength());
- final int length= content.length();
-
- while (offset < length) {
-
- while (offset < length && ScannerHelper.isWhitespace(content.charAt(offset)))
- offset++;
-
- index= offset;
-
- while (index < length && !ScannerHelper.isWhitespace(content.charAt(index)))
- index++;
-
- if (index - offset > 0) {
- fParent.append(new CommentRange(begin + offset, index - offset));
-
- offset= index;
- }
- }
- }
-
- public String toString() {
- final StringBuffer buffer = new StringBuffer();
- final int size = this.fRanges.size();
- for (int i = 0; i < size; i++) {
- buffer.append(this.fRanges.get(i)).append("\n"); //$NON-NLS-1$
- }
- return String.valueOf(buffer);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/CommentRange.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/CommentRange.java
deleted file mode 100644
index 6ae66667..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/CommentRange.java
+++ /dev/null
@@ -1,262 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.formatter.comment;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.jface.text.Position;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-
-/**
- * Range in a comment region in comment region coordinates.
- *
- * @since 3.0
- */
-public class CommentRange extends Position implements ICommentAttributes, IHtmlTagDelimiters {
-
- /** The attributes of this range */
- private int fAttributes= 0;
-
- /**
- * Creates a new comment range.
- *
- * @param position offset of the range
- * @param count length of the range
- */
- public CommentRange(final int position, final int count) {
- super(position, count);
- }
-
- /**
- * Is the attribute <code>attribute</code> true?
- *
- * @param attribute the attribute to get
- * @return <code>true</code> iff this attribute is <code>true</code>,
- * <code>false</code> otherwise
- */
- protected final boolean hasAttribute(final int attribute) {
- return (fAttributes & attribute) == attribute;
- }
-
- /**
- * Does this comment range contain a closing HTML tag?
- *
- * @param token token belonging to the comment range
- * @param tag the HTML tag to check
- * @return <code>true</code> iff this comment range contains a closing
- * html tag, <code>false</code> otherwise
- */
- protected final boolean isClosingTag(final char[] token, final char[] tag) {
-
- boolean result= (CharOperation.indexOf(HTML_CLOSE_PREFIX, token, false) == 0)
- && token[token.length - 1] == HTML_TAG_POSTFIX;
- if (result) {
-
- setAttribute(COMMENT_CLOSE);
- result= CharOperation.equals(tag, token, HTML_CLOSE_PREFIX.length, token.length - 1, false);
- }
- return result;
- }
-
- /**
- * Does this comment range contain an opening HTML tag?
- *
- * @param token token belonging to the comment range
- * @param tag the HTML tag to check
- * @return <code>true</code> iff this comment range contains an
- * opening html tag, <code>false</code> otherwise
- */
- protected final boolean isOpeningTag(final char[] token, final char[] tag) {
-
- boolean result= token.length > 0
- && token[0] == HTML_TAG_PREFIX
- && (CharOperation.indexOf(HTML_CLOSE_PREFIX, token, false) != 0)
- && token[token.length - 1] == HTML_TAG_POSTFIX;
- if (result) {
-
- setAttribute(COMMENT_OPEN);
- result= CharOperation.indexOf(tag, token, false) == 1;
- }
- return result;
- }
-
- /**
- * Mark the comment range with the occurred HTML tags.
- *
- * @param tags the HTML tags to test for their occurrence
- * @param token token belonging to the comment range
- * @param attribute attribute to set if a HTML tag is present
- * @param open <code>true</code> iff opening tags should be marked,
- * <code>false</code> otherwise
- * @param close <code>true</code> iff closing tags should be marked,
- * <code>false</code> otherwise
- */
- protected final void markHtmlTag(final char[][] tags, final char[] token, final int attribute, final boolean open, final boolean close) {
- if (token[0] == HTML_TAG_PREFIX && token[token.length - 1] == HTML_TAG_POSTFIX) {
-
- char[] tag= null;
- boolean isOpen= false;
- boolean isClose= false;
-
- for (int index= 0; index < tags.length; index++) {
-
- tag= tags[index];
-
- isOpen= isOpeningTag(token, tag);
- isClose= isClosingTag(token, tag);
-
- if ((open && isOpen) || (close && isClose)) {
-
- setAttribute(attribute);
- break;
- }
- }
- }
- }
-
- /**
- * Mark the comment range with the occurred tags.
- *
- * @param tags the tags to test for their occurrence
- * @param prefix the prefix which is common to all the tags to test
- * @param token the token belonging to the comment range
- * @param attribute attribute to set if a tag is present
- */
- protected final void markPrefixTag(final char[][] tags, final char prefix, final char[] token, final int attribute) {
-
- if (token[0] == prefix) {
-
- char[] tag= null;
- for (int index= 0; index < tags.length; index++) {
-
- tag= tags[index];
- if (CharOperation.equals(token, tag)) {
-
- setAttribute(attribute);
- break;
- }
- }
- }
- }
-
- /**
- * Marks the comment range with the HTML range tag.
- *
- * @param token the token belonging to the comment range
- * @param tag the HTML tag which confines the HTML range
- * @param level the nesting level of the current HTML range
- * @param key the key of the attribute to set if the comment range is in
- * the HTML range
- * @param html <code>true</code> iff the HTML tags in this HTML range
- * should be marked too, <code>false</code> otherwise
- * @return the new nesting level of the HTML range
- */
- protected final int markTagRange(final char[] token, final char[] tag, int level, final int key, final boolean html) {
-
- if (isOpeningTag(token, tag)) {
- if (level++ > 0)
- setAttribute(key);
- } else if (isClosingTag(token, tag)) {
- if (--level > 0)
- setAttribute(key);
- } else if (level > 0) {
- if (html || !hasAttribute(COMMENT_HTML))
- setAttribute(key);
- }
- return level;
- }
-
- /**
- * Moves this comment range.
- *
- * @param delta the delta to move the range
- */
- public final void move(final int delta) {
- offset += delta;
- }
-
- /**
- * Set the attribute <code>attribute</code> to true.
- *
- * @param attribute the attribute to set.
- */
- protected final void setAttribute(final int attribute) {
- fAttributes |= attribute;
- }
-
- /**
- * Trims this comment range at the beginning.
- *
- * @param delta amount to trim the range
- */
- public final void trimBegin(final int delta) {
- offset += delta;
- length -= delta;
- }
-
- /**
- * Trims this comment range at the end.
- *
- * @param delta amount to trim the range
- */
- public final void trimEnd(final int delta) {
- length += delta;
- }
-
- /*
- * @see java.lang.Object#toString()
- * @since 3.1
- */
- public String toString() {
- List attributes= new ArrayList();
- if (hasAttribute(COMMENT_BLANKLINE))
- attributes.add("COMMENT_BLANKLINE"); //$NON-NLS-1$
- if (hasAttribute(COMMENT_BREAK))
- attributes.add("COMMENT_BREAK"); //$NON-NLS-1$
- if (hasAttribute(COMMENT_CLOSE))
- attributes.add("COMMENT_CLOSE"); //$NON-NLS-1$
- if (hasAttribute(COMMENT_CODE))
- attributes.add("COMMENT_CODE"); //$NON-NLS-1$
- if (hasAttribute(COMMENT_HTML))
- attributes.add("COMMENT_HTML"); //$NON-NLS-1$
- if (hasAttribute(COMMENT_IMMUTABLE))
- attributes.add("COMMENT_IMMUTABLE"); //$NON-NLS-1$
- if (hasAttribute(COMMENT_NEWLINE))
- attributes.add("COMMENT_NEWLINE"); //$NON-NLS-1$
- if (hasAttribute(COMMENT_OPEN))
- attributes.add("COMMENT_OPEN"); //$NON-NLS-1$
- if (hasAttribute(COMMENT_PARAGRAPH))
- attributes.add("COMMENT_PARAGRAPH"); //$NON-NLS-1$
- if (hasAttribute(COMMENT_PARAMETER))
- attributes.add("COMMENT_PARAMETER"); //$NON-NLS-1$
- if (hasAttribute(COMMENT_ROOT))
- attributes.add("COMMENT_ROOT"); //$NON-NLS-1$
- if (hasAttribute(COMMENT_SEPARATOR))
- attributes.add("COMMENT_SEPARATOR"); //$NON-NLS-1$
- if (hasAttribute(COMMENT_FIRST_TOKEN))
- attributes.add("COMMENT_FIRST_TOKEN"); //$NON-NLS-1$
- if (hasAttribute(COMMENT_STARTS_WITH_RANGE_DELIMITER))
- attributes.add("COMMENT_STARTS_WITH_RANGE_DELIMITER"); //$NON-NLS-1$
-
- StringBuffer buf= new StringBuffer("CommentRange [" + offset + "+" + length + "] {"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- for (Iterator it= attributes.iterator(); it.hasNext();) {
- String string= (String) it.next();
- buf.append(string);
- if (it.hasNext())
- buf.append(", "); //$NON-NLS-1$
- }
-
- return buf.toString() + "}"; //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/CommentRegion.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/CommentRegion.java
deleted file mode 100644
index 005b4840..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/CommentRegion.java
+++ /dev/null
@@ -1,573 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.formatter.comment;
-
-import java.util.Iterator;
-import java.util.LinkedList;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.DefaultLineTracker;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.ILineTracker;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Position;
-import org.eclipse.text.edits.MalformedTreeException;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.internal.compiler.parser.ScannerHelper;
-import org.eclipse.wst.jsdt.internal.formatter.CodeFormatterVisitor;
-import org.eclipse.wst.jsdt.internal.formatter.DefaultCodeFormatterOptions;
-import org.eclipse.wst.jsdt.internal.formatter.Scribe;
-
-/**
- * Comment region in a source code document.
- *
- * @since 3.0
- */
-public class CommentRegion extends Position implements IHtmlTagDelimiters, IBorderAttributes, ICommentAttributes {
-
- /** Default comment range delimiter */
- protected static final String COMMENT_RANGE_DELIMITER= " "; //$NON-NLS-1$
-
- /** Default line prefix length */
- private static final int COMMENT_PREFIX_LENGTH= 3;
-
- /** The borders of this region */
- private int fBorders= 0;
-
- /** Should all blank lines be cleared during formatting? */
- protected boolean fClear;
-
- /** The line delimiter used in this comment region */
- private final String fDelimiter;
-
- /** The document to format */
- private final IDocument fDocument;
-
- /** The lines in this comment region */
- private final LinkedList fLines= new LinkedList();
-
- /** The formatting preferences */
- protected final DefaultCodeFormatterOptions preferences;
-
- /** The comment ranges in this comment region */
- private final LinkedList fRanges= new LinkedList();
-
- /** Is this comment region a single line region? */
- private final boolean fSingleLine;
-
- /** Number of spaces representing tabulator */
- private int fTabSize;
-
- /** the scribe used to create edits */
- protected Scribe scribe;
-
- /**
- * Creates a new comment region.
- *
- * @param document the document which contains the comment region
- * @param position the position of this comment region in the document
- * @param formatter the given code formatter
- */
- public CommentRegion(final IDocument document, final Position position, final CodeFormatterVisitor formatter) {
- super(position.getOffset(), position.getLength());
-
- this.preferences = formatter.preferences;
- fDelimiter = this.preferences.line_separator;
- fDocument= document;
-
- fTabSize= DefaultCodeFormatterOptions.SPACE == this.preferences.tab_char ? this.preferences.indentation_size : this.preferences.tab_size;
-
- this.scribe = formatter.scribe;
-
- final ILineTracker tracker= new DefaultLineTracker();
-
- IRegion range= null;
- CommentLine line= null;
-
- tracker.set(getText(0, getLength()));
- final int lines= tracker.getNumberOfLines();
-
- fSingleLine= lines == 1;
-
- try {
-
- for (int index= 0; index < lines; index++) {
-
- range= tracker.getLineInformation(index);
- line= createLine();
- line.append(new CommentRange(range.getOffset(), range.getLength()));
-
- fLines.add(line);
- }
-
- } catch (BadLocationException exception) {
- // Should not happen
- }
- }
-
- /**
- * Appends the comment range to this comment region.
- *
- * @param range comment range to append to this comment region
- */
- protected final void append(final CommentRange range) {
- fRanges.addLast(range);
- }
-
- /**
- * Can the comment range be appended to the comment line?
- *
- * @param line comment line where to append the comment range
- * @param previous comment range which is the predecessor of the current
- * comment range
- * @param next comment range to test whether it can be appended to the
- * comment line
- * @param index amount of space in the comment line used by already
- * inserted comment ranges
- * @param width the maximal width of text in this comment region
- * measured in average character widths
- * @return <code>true</code> iff the comment range can be added to the
- * line, <code>false</code> otherwise
- */
- protected boolean canAppend(final CommentLine line, final CommentRange previous, final CommentRange next, final int index, final int width) {
- return index == 0 || index + next.getLength() <= width;
- }
-
- /**
- * Can the whitespace between the two comment ranges be formatted?
- *
- * @param previous previous comment range which was already formatted,
- * can be <code>null</code>
- * @param next next comment range to be formatted
- * @return <code>true</code> iff the next comment range can be
- * formatted, <code>false</code> otherwise.
- */
- protected boolean canFormat(final CommentRange previous, final CommentRange next) {
- return previous != null;
- }
-
- /**
- * Formats the comment region with the given indentation level.
- *
- * @param indentationLevel the indentation level
- * @return the resulting text edit of the formatting process
- * @since 3.1
- */
- public final TextEdit format(int indentationLevel, boolean returnEdit) {
- final String probe= getText(0, CommentLine.NON_FORMAT_START_PREFIX.length());
- if (!probe.startsWith(CommentLine.NON_FORMAT_START_PREFIX)) {
-
- int margin= this.preferences.comment_line_length;
- String indentation= computeIndentation(indentationLevel);
- margin= Math.max(COMMENT_PREFIX_LENGTH + 1, margin - stringToLength(indentation) - COMMENT_PREFIX_LENGTH);
-
- tokenizeRegion();
- markRegion();
- wrapRegion(margin);
- formatRegion(indentation, margin);
-
- }
- if (returnEdit) {
- return this.scribe.getRootEdit();
- }
- return null;
- }
-
- /**
- * Formats this comment region.
- *
- * @param indentation the indentation of this comment region
- * @param width the maximal width of text in this comment region
- * measured in average character widths
- */
- protected void formatRegion(final String indentation, final int width) {
-
- final int last= fLines.size() - 1;
- if (last >= 0) {
-
- CommentLine lastLine= (CommentLine)fLines.get(last);
- CommentRange lastRange= lastLine.getLast();
- lastLine.formatLowerBorder(lastRange, indentation, width);
-
- CommentLine previous;
- CommentLine next= null;
- CommentRange range= null;
- for (int line= last; line >= 0; line--) {
-
- previous= next;
- next= (CommentLine)fLines.get(line);
-
- range= next.formatLine(previous, range, indentation, line);
- }
- next.formatUpperBorder(range, indentation, width);
- }
- }
-
- /**
- * Returns the line delimiter used in this comment region.
- *
- * @return the line delimiter for this comment region
- */
- protected final String getDelimiter() {
- return fDelimiter;
- }
-
- /**
- * Returns the line delimiter used in this comment line break.
- *
- * @param predecessor the predecessor comment line after the line break
- * @param successor the successor comment line before the line break
- * @param previous the comment range after the line break
- * @param next the comment range before the line break
- * @param indentation indentation of the formatted line break
- * @return the line delimiter for this comment line break
- */
- protected String getDelimiter(final CommentLine predecessor, final CommentLine successor, final CommentRange previous, final CommentRange next, final String indentation) {
- return fDelimiter + indentation + successor.getContentPrefix();
- }
-
- /**
- * Returns the range delimiter for this comment range break.
- *
- * @param previous the previous comment range to the right of the range
- * delimiter
- * @param next the next comment range to the left of the range delimiter
- * @return the delimiter for this comment range break
- */
- protected String getDelimiter(final CommentRange previous, final CommentRange next) {
- return COMMENT_RANGE_DELIMITER;
- }
-
- /**
- * Returns the document of this comment region.
- *
- * @return the document of this region
- */
- protected final IDocument getDocument() {
- return fDocument;
- }
-
- /**
- * Returns the comment ranges in this comment region
- *
- * @return the comment ranges in this region
- */
- protected final LinkedList getRanges() {
- return fRanges;
- }
-
- /**
- * Returns the number of comment lines in this comment region.
- *
- * @return the number of lines in this comment region
- */
- protected final int getSize() {
- return fLines.size();
- }
-
- /**
- * Returns the text of this comment region in the indicated range.
- *
- * @param position the offset of the comment range to retrieve in
- * comment region coordinates
- * @param count the length of the comment range to retrieve
- * @return the content of this comment region in the indicated range
- */
- protected final String getText(final int position, final int count) {
-
- String content= ""; //$NON-NLS-1$
- try {
- content= fDocument.get(getOffset() + position, count);
- } catch (BadLocationException exception) {
- // Should not happen
- }
- return content;
- }
-
- /**
- * Does the border <code>border</code> exist?
- *
- * @param border the type of the border, must be a border attribute of
- * <code>CommentRegion</code>
- * @return <code>true</code> iff this border exists,
- * <code>false</code> otherwise
- */
- protected final boolean hasBorder(final int border) {
- return (fBorders & border) == border;
- }
-
- /**
- * Does the comment range consist of letters and digits only?
- *
- * @param range the comment range to text
- * @return <code>true</code> iff the comment range consists of letters
- * and digits only, <code>false</code> otherwise
- */
- protected final boolean isAlphaNumeric(final CommentRange range) {
-
- final String token= getText(range.getOffset(), range.getLength());
-
- for (int index= 0; index < token.length(); index++) {
- if (!ScannerHelper.isLetterOrDigit(token.charAt(index)))
- return false;
- }
- return true;
- }
-
- /**
- * Does the comment range contain no letters and digits?
- *
- * @param range the comment range to text
- * @return <code>true</code> iff the comment range contains no letters
- * and digits, <code>false</code> otherwise
- */
- protected final boolean isNonAlphaNumeric(final CommentRange range) {
-
- final String token= getText(range.getOffset(), range.getLength());
-
- for (int index= 0; index < token.length(); index++) {
- if (ScannerHelper.isLetterOrDigit(token.charAt(index)))
- return false;
- }
- return true;
- }
-
- /**
- * Should blank lines be cleared during formatting?
- *
- * @return <code>true</code> iff blank lines should be cleared,
- * <code>false</code> otherwise
- */
- protected final boolean isClearLines() {
- return fClear;
- }
-
- /**
- * Is this comment region a single line region?
- *
- * @return <code>true</code> iff this region is single line,
- * <code>false</code> otherwise
- */
- protected final boolean isSingleLine() {
- return fSingleLine;
- }
-
- /**
- * Logs a text edit operation occurred during the formatting process
- *
- * @param change the changed text
- * @param position offset measured in comment region coordinates where
- * to apply the changed text
- * @param count length of the range where to apply the changed text
- */
- protected final void logEdit(final String change, final int position, final int count) {
- try {
- final int base= getOffset() + position;
- final String content= fDocument.get(base, count);
-
- if (!change.equals(content)) {
- if (count > 0) {
- this.scribe.addReplaceEdit(base, base + count - 1, change);
- } else {
- this.scribe.addInsertEdit(base, change);
- }
- }
- } catch (BadLocationException exception) {
- // Should not happen
- CommentFormatterUtil.log(exception);
- } catch (MalformedTreeException exception) {
- // Do nothing
- CommentFormatterUtil.log(exception);
- }
- }
-
- /**
- * Marks the comment ranges in this comment region.
- */
- protected void markRegion() {
- // Do nothing
- }
-
- /**
- * Set the border type <code>border</code> to true.
- *
- * @param border the type of the border. Must be a border attribute of
- * <code>CommentRegion</code>
- */
- protected final void setBorder(final int border) {
- fBorders |= border;
- }
-
- /**
- * Returns the indentation of the given indentation level.
- *
- * @param indentationLevel the indentation level
- * @return the indentation of the given indentation level
- * @since 3.1
- */
- private String computeIndentation(int indentationLevel) {
- if (DefaultCodeFormatterOptions.TAB == this.preferences.tab_char)
- return replicate("\t", indentationLevel); //$NON-NLS-1$
-
- if (DefaultCodeFormatterOptions.SPACE == this.preferences.tab_char)
- return replicate(" ", indentationLevel * this.preferences.tab_size); //$NON-NLS-1$
-
- if (DefaultCodeFormatterOptions.MIXED == this.preferences.tab_char) {
- int tabSize= this.preferences.tab_size;
- int indentSize= this.preferences.indentation_size;
- int spaceEquivalents= indentationLevel * indentSize;
- return replicate("\t", spaceEquivalents / tabSize) + replicate(" ", spaceEquivalents % tabSize); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- Assert.isTrue(false);
- return null;
- }
-
- /**
- * Returns the given string n-times replicated.
- *
- * @param string the string
- * @param n n
- * @return the given string n-times replicated
- * @since 3.1
- */
- private String replicate(String string, int n) {
- StringBuffer buffer= new StringBuffer(n*string.length());
- for (int i= 0; i < n; i++)
- buffer.append(string);
- return buffer.toString();
- }
-
- /**
- * Computes the equivalent indentation for a string
- *
- * @param reference the string to compute the indentation for
- * @return the indentation string
- */
- protected final String stringToIndent(final String reference) {
- return replicate(" ", stringToLength(reference)); //$NON-NLS-1$
- }
-
- /**
- * Returns the length of the string in expanded characters.
- *
- * @param reference the string to get the length for
- * @return the length of the string in expanded characters
- */
- protected final int stringToLength(final String reference) {
- return expandTabs(reference).length();
- }
-
- /**
- * Expands the given string's tabs according to the given tab size.
- *
- * @param string the string
- * @return the expanded string
- * @since 3.1
- */
- private String expandTabs(String string) {
- StringBuffer expanded= new StringBuffer();
- for (int i= 0, n= string.length(), chars= 0; i < n; i++) {
- char ch= string.charAt(i);
- if (ch == '\t') {
- for (; chars < fTabSize; chars++)
- expanded.append(' ');
- chars= 0;
- } else {
- expanded.append(ch);
- chars++;
- if (chars >= fTabSize)
- chars= 0;
- }
-
- }
- return expanded.toString();
- }
-
- /**
- * Tokenizes the comment region.
- */
- protected void tokenizeRegion() {
-
- int index= 0;
- CommentLine line= null;
-
- for (final Iterator iterator= fLines.iterator(); iterator.hasNext(); index++) {
-
- line= (CommentLine)iterator.next();
-
- line.scanLine(index);
- line.tokenizeLine(index);
- }
- }
-
- /**
- * Wraps the comment ranges in this comment region into comment lines.
- *
- * @param width the maximal width of text in this comment region
- * measured in average character widths
- */
- protected void wrapRegion(final int width) {
-
- fLines.clear();
-
- int index= 0;
- boolean adapted= false;
-
- CommentLine successor= null;
- CommentLine predecessor= null;
-
- CommentRange previous= null;
- CommentRange next= null;
-
- while (!fRanges.isEmpty()) {
-
- index= 0;
- adapted= false;
-
- predecessor= successor;
- successor= createLine();
- fLines.add(successor);
-
- while (!fRanges.isEmpty()) {
- next= (CommentRange)fRanges.getFirst();
-
- if (canAppend(successor, previous, next, index, width)) {
-
- if (!adapted && predecessor != null) {
-
- successor.adapt(predecessor);
- adapted= true;
- }
-
- fRanges.removeFirst();
- successor.append(next);
-
- index += (next.getLength() + 1);
- previous= next;
- } else
- break;
- }
- }
- }
-
- /**
- * Creates a new line for this region.
- *
- * @return a new line for this region
- * @since 3.1
- */
- protected CommentLine createLine() {
- return new SingleCommentLine(this);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/HTMLEntity2JavaReader.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/HTMLEntity2JavaReader.java
deleted file mode 100644
index f1b38840..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/HTMLEntity2JavaReader.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.formatter.comment;
-
-import java.io.IOException;
-import java.io.Reader;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.wst.jsdt.internal.compiler.parser.ScannerHelper;
-
-/**
- * <code>SubstitutionTextReader</code> that will substitute plain text values
- * for html entities encountered in the original text. Line breaks and
- * whitespace are preserved.
- *
- * @since 3.0
- */
-public class HTMLEntity2JavaReader extends SubstitutionTextReader {
-
- /** The hard-coded entity map. */
- private static final Map fgEntityLookup;
-
- static {
- fgEntityLookup= new HashMap(7);
- fgEntityLookup.put("lt", "<"); //$NON-NLS-1$ //$NON-NLS-2$
- fgEntityLookup.put("gt", ">"); //$NON-NLS-1$ //$NON-NLS-2$
- fgEntityLookup.put("nbsp", " "); //$NON-NLS-1$ //$NON-NLS-2$
- fgEntityLookup.put("amp", "&"); //$NON-NLS-1$ //$NON-NLS-2$
- fgEntityLookup.put("circ", "^"); //$NON-NLS-1$ //$NON-NLS-2$
- fgEntityLookup.put("tilde", "~"); //$NON-NLS-2$ //$NON-NLS-1$
- fgEntityLookup.put("quot", "\""); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /**
- * Creates a new instance that will read from <code>reader</code>
- *
- * @param reader the source reader
- */
- public HTMLEntity2JavaReader(Reader reader) {
- super(reader);
- setSkipWhitespace(false);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.SubstitutionTextReader#computeSubstitution(int)
- */
- protected String computeSubstitution(int c) throws IOException {
- if (c == '&')
- return processEntity();
- return null;
- }
-
- /**
- * Replaces an HTML entity body (without &amp; and ;) with its
- * plain/text (or plain/java) counterpart.
- *
- * @param symbol the entity body to resolve
- * @return the plain/text counterpart of <code>symbol</code>
- */
- protected String entity2Text(String symbol) {
- if (symbol.length() > 1 && symbol.charAt(0) == '#') {
- int ch;
- try {
- if (symbol.charAt(1) == 'x') {
- ch= Integer.parseInt(symbol.substring(2), 16);
- } else {
- ch= Integer.parseInt(symbol.substring(1), 10);
- }
- return " " + (char) ch; //$NON-NLS-1$
- } catch (NumberFormatException e) {
- // ignore
- }
- } else {
- String str= (String) fgEntityLookup.get(symbol);
- if (str != null) {
- return str;
- }
- }
- return "&" + symbol; // not found //$NON-NLS-1$
- }
-
- /**
- * Reads an HTML entity from the stream and returns its plain/text
- * counterpart.
- *
- * @return an entity read from the stream, or the stream content.
- * @throws IOException if the underlying reader throws one
- */
- private String processEntity() throws IOException {
- StringBuffer buf= new StringBuffer();
- int ch= nextChar();
- while (ScannerHelper.isLetterOrDigit((char) ch) || ch == '#') {
- buf.append((char) ch);
- ch= nextChar();
- }
- if (ch == ';')
- return entity2Text(buf.toString());
- buf.insert(0, '&');
- if (ch != -1)
- buf.append((char) ch);
- return buf.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/IBorderAttributes.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/IBorderAttributes.java
deleted file mode 100644
index 9ff5c2ac..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/IBorderAttributes.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.formatter.comment;
-
-/**
- * Comment region border attributes.
- *
- * @since 3.0
- */
-public interface IBorderAttributes {
-
- /** Region has lower border attribute */
- public static final int BORDER_LOWER= 1 << 0;
-
- /** Region has upper border attribute */
- public static final int BORDER_UPPER= 1 << 1;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/ICommentAttributes.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/ICommentAttributes.java
deleted file mode 100644
index 9b0913b8..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/ICommentAttributes.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.formatter.comment;
-
-/**
- * General comment range attributes.
- *
- * @since 3.0
- */
-public interface ICommentAttributes {
-
- /** Range has blank line attribute */
- public static final int COMMENT_BLANKLINE= 1 << 1;
-
- /** Range has line break attribute */
- public static final int COMMENT_BREAK= 1 << 2;
-
- /** Range has close tag attribute */
- public static final int COMMENT_CLOSE= 1 << 3;
-
- /** Range has source code attribute */
- public static final int COMMENT_CODE= 1 << 4;
-
- /** Range has html tag attribute */
- public static final int COMMENT_HTML= 1 << 5;
-
- /** Range has the immutable region attribute */
- public static final int COMMENT_IMMUTABLE= 1 << 6;
-
- /** Range has new line attribute */
- public static final int COMMENT_NEWLINE= 1 << 7;
-
- /** Range has open tag attribute */
- public static final int COMMENT_OPEN= 1 << 8;
-
- /** Range has paragraph attribute */
- public static final int COMMENT_PARAGRAPH= 1 << 9;
-
- /** Range has parameter tag attribute */
- public static final int COMMENT_PARAMETER= 1 << 10;
-
- /** Range has root tag attribute */
- public static final int COMMENT_ROOT= 1 << 11;
-
- /** Range has paragraph separator attribute */
- public static final int COMMENT_SEPARATOR= 1 << 12;
-
- /** Range is the first token on the line in the original source */
- public static final int COMMENT_FIRST_TOKEN= 1 << 13;
-
- /**
- * Range was preceded by whitespace / line delimiters
- * @since 3.1
- */
- public static final int COMMENT_STARTS_WITH_RANGE_DELIMITER= 1 << 14;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/IHtmlTagDelimiters.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/IHtmlTagDelimiters.java
deleted file mode 100644
index e81f5b52..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/IHtmlTagDelimiters.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.formatter.comment;
-
-/**
- * Html tag constants.
- *
- * @since 3.0
- */
-public interface IHtmlTagDelimiters {
-
- /** Html tag close prefix */
- public static final char[] HTML_CLOSE_PREFIX= "</".toCharArray(); //$NON-NLS-1$
-
- /** Html tag postfix */
- public static final char HTML_TAG_POSTFIX= '>';
-
- /** Html tag prefix */
- public static final char HTML_TAG_PREFIX= '<';
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/IJavaDocTagConstants.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/IJavaDocTagConstants.java
deleted file mode 100644
index b2c829c0..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/IJavaDocTagConstants.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.formatter.comment;
-
-/**
- * Javadoc tag constants.
- *
- * @since 3.0
- */
-public interface IJavaDocTagConstants {
-
- /** Javadoc break tags */
- public static final char[][] JAVADOC_BREAK_TAGS = new char[][] {
- "dd".toCharArray(), //$NON-NLS-1$
- "dt".toCharArray(), //$NON-NLS-1$
- "li".toCharArray(), //$NON-NLS-1$
- "td".toCharArray(), //$NON-NLS-1$
- "th".toCharArray(), //$NON-NLS-1$
- "tr".toCharArray(), //$NON-NLS-1$
- "h1".toCharArray(), //$NON-NLS-1$
- "h2".toCharArray(), //$NON-NLS-1$
- "h3".toCharArray(), //$NON-NLS-1$
- "h4".toCharArray(), //$NON-NLS-1$
- "h5".toCharArray(), //$NON-NLS-1$
- "h6".toCharArray(), //$NON-NLS-1$
- "q".toCharArray() //$NON-NLS-1$
- };
-
- /** Javadoc single break tag */
- public static final char[][] JAVADOC_SINGLE_BREAK_TAG= new char[][] { "br".toCharArray() }; //$NON-NLS-1$
-
- /** Javadoc code tags */
- public static final char[][] JAVADOC_CODE_TAGS= new char[][] { "pre".toCharArray() }; //$NON-NLS-1$
-
- /** Javadoc immutable tags */
- public static final char[][] JAVADOC_IMMUTABLE_TAGS= new char[][] {
- "code".toCharArray(), //$NON-NLS-1$
- "em".toCharArray(), //$NON-NLS-1$
- "pre".toCharArray(), //$NON-NLS-1$
- "q".toCharArray(), //$NON-NLS-1$
- "tt".toCharArray() //$NON-NLS-1$
- };
-
- /** Javadoc new line tags */
- public static final char[][] JAVADOC_NEWLINE_TAGS= new char[][] {
- "dd".toCharArray(), //$NON-NLS-1$
- "dt".toCharArray(), //$NON-NLS-1$
- "li".toCharArray(), //$NON-NLS-1$
- "td".toCharArray(), //$NON-NLS-1$
- "th".toCharArray(), //$NON-NLS-1$
- "tr".toCharArray(), //$NON-NLS-1$
- "h1".toCharArray(), //$NON-NLS-1$
- "h2".toCharArray(), //$NON-NLS-1$
- "h3".toCharArray(), //$NON-NLS-1$
- "h4".toCharArray(), //$NON-NLS-1$
- "h5".toCharArray(), //$NON-NLS-1$
- "h6".toCharArray(), //$NON-NLS-1$
- "q".toCharArray() //$NON-NLS-1$
- };
-
- /** Javadoc parameter tags */
- public static final char[][] JAVADOC_PARAM_TAGS= new char[][] {
- "@exception".toCharArray(), //$NON-NLS-1$
- "@param".toCharArray(), //$NON-NLS-1$
- "@serialField".toCharArray(), //$NON-NLS-1$
- "@throws".toCharArray() //$NON-NLS-1$
- };
-
- /** Javadoc separator tags */
- public static final char[][] JAVADOC_SEPARATOR_TAGS= new char[][] {
- "dl".toCharArray(), //$NON-NLS-1$
- "hr".toCharArray(), //$NON-NLS-1$
- "nl".toCharArray(), //$NON-NLS-1$
- "p".toCharArray(), //$NON-NLS-1$
- "pre".toCharArray(), //$NON-NLS-1$
- "ul".toCharArray(), //$NON-NLS-1$
- "ol".toCharArray() //$NON-NLS-1$
- };
-
- /** Javadoc tag prefix */
- public static final char JAVADOC_TAG_PREFIX= '@';
-
- /** Link tag postfix */
- public static final char LINK_TAG_POSTFIX= '}';
-
- /** Link tag prefix */
- public static final String LINK_TAG_PREFIX_STRING = "{@"; //$NON-NLS-1$
-
- public static final char[] LINK_TAG_PREFIX= LINK_TAG_PREFIX_STRING.toCharArray();
-
-
- /** Comment root tags */
- public static final char[][] COMMENT_ROOT_TAGS= new char[][] {
- "@deprecated".toCharArray(), //$NON-NLS-1$
- "@see".toCharArray(), //$NON-NLS-1$
- "@since".toCharArray(), //$NON-NLS-1$
- "@version".toCharArray() //$NON-NLS-1$
- };
-
- /** Tag prefix of comment tags */
- public static final char COMMENT_TAG_PREFIX= '@';
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/Java2HTMLEntityReader.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/Java2HTMLEntityReader.java
deleted file mode 100644
index def29409..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/Java2HTMLEntityReader.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.formatter.comment;
-
-import java.io.Reader;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * <code>SubstitutionTextReader</code> that will substitute html entities for
- * html symbols encountered in the original text. Line breaks and whitespaces
- * are preserved.
- *
- * @since 3.0
- */
-public class Java2HTMLEntityReader extends SubstitutionTextReader {
-
- /** The hardcoded entity map. */
- private static final Map fgEntityLookup;
-
- static {
- fgEntityLookup= new HashMap(7);
- fgEntityLookup.put("<", "&lt;"); //$NON-NLS-1$ //$NON-NLS-2$
- fgEntityLookup.put(">", "&gt;"); //$NON-NLS-1$ //$NON-NLS-2$
- fgEntityLookup.put("&", "&amp;"); //$NON-NLS-1$ //$NON-NLS-2$
- fgEntityLookup.put("^", "&circ;"); //$NON-NLS-1$ //$NON-NLS-2$
- fgEntityLookup.put("~", "&tilde;"); //$NON-NLS-2$ //$NON-NLS-1$
- fgEntityLookup.put("\"", "&quot;"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /**
- * Creates a new instance that will read from <code>reader</code>
- *
- * @param reader the source reader
- */
- public Java2HTMLEntityReader(Reader reader) {
- super(reader);
- setSkipWhitespace(false);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.SubstitutionTextReader#computeSubstitution(int)
- */
- protected String computeSubstitution(int c) {
- String lookup= (String) fgEntityLookup.get(String.valueOf((char) c));
- return lookup;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/JavaDocLine.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/JavaDocLine.java
deleted file mode 100644
index 4eb1490d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/JavaDocLine.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.formatter.comment;
-
-/**
- * Javadoc comment line in a comment region.
- *
- * @since 3.0
- */
-public class JavaDocLine extends MultiCommentLine {
-
- /** Line prefix of javadoc start lines */
- public static final String JAVADOC_START_PREFIX= "/**"; //$NON-NLS-1$
-
- /**
- * Creates a new javadoc line.
- *
- * @param region comment region to create the line for
- */
- protected JavaDocLine(final CommentRegion region) {
- super(region);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.text.comment.CommentLine#formatUpperBorder(org.eclipse.wst.jsdt.internal.corext.text.comment.CommentRange, java.lang.String, int)
- */
- protected void formatUpperBorder(final CommentRange range, final String indentation, final int length) {
-
- final CommentRegion parent= getParent();
-
- if (parent.isSingleLine() && parent.getSize() == 1) {
- parent.logEdit(getStartingPrefix() + CommentRegion.COMMENT_RANGE_DELIMITER, 0, range.getOffset());
- } else
- super.formatUpperBorder(range, indentation, length);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.text.comment.CommentLine#getStartingPrefix()
- */
- protected String getStartingPrefix() {
- return JAVADOC_START_PREFIX;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/JavaDocRegion.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/JavaDocRegion.java
deleted file mode 100644
index aef5ebc6..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/JavaDocRegion.java
+++ /dev/null
@@ -1,363 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.formatter.comment;
-
-import java.io.IOException;
-import java.io.StringReader;
-import java.util.ArrayList;
-import java.util.Iterator;
-
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.DefaultLineTracker;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.ILineTracker;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.formatter.CodeFormatter;
-import org.eclipse.wst.jsdt.internal.compiler.parser.ScannerHelper;
-import org.eclipse.wst.jsdt.internal.formatter.CodeFormatterVisitor;
-
-
-/**
- * Javadoc region in a source code document.
- *
- * @since 3.0
- */
-public class JavaDocRegion extends MultiCommentRegion implements IJavaDocTagConstants {
-
- /** The positions of code ranges */
- private final ArrayList fCodePositions= new ArrayList();
-
- /** Should HTML tags be formatted? */
- private final boolean fFormatHtml;
-
- /** Should source code regions be formatted? */
- private final boolean fFormatSource;
-
- /**
- * Creates a new Javadoc region.
- *
- * @param document the document which contains the comment region
- * @param position the position of this comment region in the document
- * @param formatter the given formatter
- */
- public JavaDocRegion(final IDocument document, final Position position, final CodeFormatterVisitor formatter) {
- super(document, position, formatter);
-
- fFormatSource = this.preferences.comment_format_source;
- fFormatHtml = this.preferences.comment_format_html;
- fClear = this.preferences.comment_clear_blank_lines_in_javadoc_comment;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.text.comment.CommentRegion#canFormat(org.eclipse.wst.jsdt.internal.corext.text.comment.CommentRange, org.eclipse.wst.jsdt.internal.corext.text.comment.CommentRange)
- */
- protected boolean canFormat(final CommentRange previous, final CommentRange next) {
-
- if (previous != null) {
-
- final boolean isCurrentCode= next.hasAttribute(COMMENT_CODE);
- final boolean isLastCode= previous.hasAttribute(COMMENT_CODE);
-
- final int base= getOffset();
-
- if (!isLastCode && isCurrentCode)
- fCodePositions.add(new Position(base + previous.getOffset()));
- else if (isLastCode && !isCurrentCode)
- fCodePositions.add(new Position(base + next.getOffset() + next.getLength()));
-
- if (previous.hasAttribute(COMMENT_IMMUTABLE) && next.hasAttribute(COMMENT_IMMUTABLE))
- return false;
-
- return true;
- }
- return false;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.text.comment.CommentRegion#formatRegion(java.lang.String, int)
- */
- protected final void formatRegion(final String indentation, final int width) {
-
- super.formatRegion(indentation, width);
-
- if (fFormatSource) {
-
- try {
-
- if (fCodePositions.size() > 0) {
-
- int begin= 0;
- int end= 0;
-
- Position position= null;
-
- final IDocument document= getDocument();
-
- for (int index= fCodePositions.size() - 1; index >= 0;) {
-
- position= (Position)fCodePositions.get(index--);
- begin= position.getOffset();
-
- if (index >= 0) {
- position= (Position)fCodePositions.get(index--);
- end= position.getOffset();
- } else {
- /*
- * Handle missing closing tag
- * see: https://bugs.eclipse.org/bugs/show_bug.cgi?id=57011
- */
- position= null;
- end= getOffset() + getLength() - MultiCommentLine.MULTI_COMMENT_END_PREFIX.trim().length();
- while (end > begin && ScannerHelper.isWhitespace(document.getChar(end - 1)))
- end--;
- }
-
- String snippet= document.get(begin, end - begin);
- snippet= preprocessCodeSnippet(snippet);
- snippet= formatCodeSnippet(snippet);
- snippet= postprocessCodeSnippet(snippet, indentation);
-
- logEdit(snippet, begin - getOffset(), end - begin);
- }
- }
- } catch (BadLocationException e) {
- // Can not happen
- CommentFormatterUtil.log(e);
- }
- }
- }
-
- /**
- * Preprocess a given code snippet.
- *
- * @param snippet the code snippet
- * @return the preprocessed code snippet
- */
- private String preprocessCodeSnippet(String snippet) {
- // strip content prefix
- StringBuffer buffer= new StringBuffer();
- ILineTracker tracker= new DefaultLineTracker();
- String contentPrefix= MultiCommentLine.MULTI_COMMENT_CONTENT_PREFIX.trim();
-
- buffer.setLength(0);
- buffer.append(snippet);
- tracker.set(snippet);
- for (int line= tracker.getNumberOfLines() - 1; line > 0; line--) {
- int lineOffset;
- try {
- lineOffset= tracker.getLineOffset(line);
- } catch (BadLocationException e) {
- // Can not happen
- CommentFormatterUtil.log(e);
- return snippet;
- }
- int prefixOffset= buffer.indexOf(contentPrefix, lineOffset);
- if (prefixOffset >= 0 && buffer.substring(lineOffset, prefixOffset).trim().length() == 0)
- buffer.delete(lineOffset, prefixOffset + contentPrefix.length() + 1);
- }
-
- return convertHtml2Java(buffer.toString());
- }
-
- /**
- * Format the given code snippet
- *
- * @param snippet the code snippet
- * @return the formatted code snippet
- */
- private String formatCodeSnippet(String snippet) {
- String lineDelimiter= TextUtilities.getDefaultLineDelimiter(getDocument());
- TextEdit edit= CommentFormatterUtil.format2(CodeFormatter.K_UNKNOWN, snippet, 0, lineDelimiter, this.preferences.getMap());
- if (edit != null)
- snippet= CommentFormatterUtil.evaluateFormatterEdit(snippet, edit, null);
- return snippet;
- }
-
- /**
- * Postprocesses the given code snippet with the given indentation.
- *
- * @param snippet the code snippet
- * @param indentation the indentation
- * @return the postprocessed code snippet
- */
- private String postprocessCodeSnippet(String snippet, String indentation) {
- // patch content prefix
- StringBuffer buffer= new StringBuffer();
- ILineTracker tracker= new DefaultLineTracker();
- String patch= indentation + MultiCommentLine.MULTI_COMMENT_CONTENT_PREFIX;
-
- // remove trailing spaces
- int i= snippet.length();
- while (i > 0 && ' ' == snippet.charAt(i-1))
- i--;
- snippet= snippet.substring(0, i);
-
- buffer.setLength(0);
- String lineDelimiter= getDelimiter();
- if (lineDelimiter != null && snippet.indexOf(lineDelimiter) != 0)
- buffer.append(lineDelimiter);
- buffer.append(convertJava2Html(snippet));
- if (lineDelimiter != null && snippet.lastIndexOf(lineDelimiter) != snippet.length() - lineDelimiter.length())
- buffer.append(lineDelimiter);
- tracker.set(buffer.toString());
-
- for (int line= tracker.getNumberOfLines() - 1; line > 0; line--)
- try {
- buffer.insert(tracker.getLineOffset(line), patch);
- } catch (BadLocationException e) {
- // Can not happen
- CommentFormatterUtil.log(e);
- return snippet;
- }
-
- return buffer.toString();
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.text.comment.MultiCommentRegion#markHtmlRanges()
- */
- protected final void markHtmlRanges() {
-
- markTagRanges(JAVADOC_IMMUTABLE_TAGS, COMMENT_IMMUTABLE, true);
-
- if (fFormatSource)
- markTagRanges(JAVADOC_CODE_TAGS, COMMENT_CODE, false);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.text.comment.MultiCommentRegion#markHtmlTag(org.eclipse.wst.jsdt.internal.corext.text.comment.CommentRange, java.lang.String)
- */
- protected final void markHtmlTag(final CommentRange range, final char[] token) {
-
- if (range.hasAttribute(COMMENT_HTML)) {
-
- range.markHtmlTag(JAVADOC_IMMUTABLE_TAGS, token, COMMENT_IMMUTABLE, true, true);
- if (fFormatHtml) {
-
- range.markHtmlTag(JAVADOC_SEPARATOR_TAGS, token, COMMENT_SEPARATOR, true, true);
- range.markHtmlTag(JAVADOC_BREAK_TAGS, token, COMMENT_BREAK, false, true);
- range.markHtmlTag(JAVADOC_SINGLE_BREAK_TAG, token, COMMENT_BREAK, true, false);
- range.markHtmlTag(JAVADOC_NEWLINE_TAGS, token, COMMENT_NEWLINE, true, false);
-
- } else
- range.markHtmlTag(JAVADOC_CODE_TAGS, token, COMMENT_SEPARATOR, true, true);
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.text.comment.MultiCommentRegion#markJavadocTag(org.eclipse.wst.jsdt.internal.corext.text.comment.CommentRange, java.lang.String)
- */
- protected final void markJavadocTag(final CommentRange range, final char[] token) {
-
- range.markPrefixTag(JAVADOC_PARAM_TAGS, COMMENT_TAG_PREFIX, token, COMMENT_PARAMETER);
-
- if (token[0] == JAVADOC_TAG_PREFIX && !range.hasAttribute(COMMENT_PARAMETER))
- range.setAttribute(COMMENT_ROOT);
- }
-
- /**
- * Marks the comment region with the HTML range tag.
- *
- * @param tags the HTML tag which confines the HTML range
- * @param attribute the attribute to set if the comment range is in the
- * HTML range
- * @param html <code>true</code> iff the HTML tags in this HTML range
- * should be marked too, <code>false</code> otherwise
- */
- protected final void markTagRanges(final char[][] tags, final int attribute, final boolean html) {
-
- int level= 0;
- int count= 0;
- char[] token= null;
- CommentRange current= null;
-
- for (int index= 0; index < tags.length; index++) {
-
- level= 0;
- for (final Iterator iterator= getRanges().iterator(); iterator.hasNext();) {
-
- current= (CommentRange)iterator.next();
- count= current.getLength();
-
- if (count > 0 || level > 0) { // PR44035: when inside a tag, mark blank lines as well to get proper snippet formatting
-
- token= getText(current.getOffset(), current.getLength()).toCharArray();
- level= current.markTagRange(token, tags[index], level, attribute, html);
- }
- }
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.text.comment.CommentRegion#canAppend(org.eclipse.wst.jsdt.internal.corext.text.comment.CommentLine, org.eclipse.wst.jsdt.internal.corext.text.comment.CommentRange, org.eclipse.wst.jsdt.internal.corext.text.comment.CommentRange, int, int)
- */
- protected boolean canAppend(CommentLine line, CommentRange previous, CommentRange next, int index, int count) {
- // don't append code sections
- if (next.hasAttribute(COMMENT_CODE | COMMENT_FIRST_TOKEN) && line.getSize() != 0)
- return false;
- return super.canAppend(line, previous, next, index, count);
- }
-
- /**
- * Converts <code>formatted</code> into valid html code suitable to be
- * put inside &lt;pre&gt;&lt;/pre&gt; tags by replacing any html symbols
- * by the relevant entities.
- *
- * @param formatted the formatted java code
- * @return html version of the formatted code
- */
- private String convertJava2Html(String formatted) {
- Java2HTMLEntityReader reader= new Java2HTMLEntityReader(new StringReader(formatted));
- char[] buf= new char[256];
- StringBuffer buffer= new StringBuffer();
- int l;
- try {
- do {
- l= reader.read(buf);
- if (l != -1)
- buffer.append(buf, 0, l);
- } while (l > 0);
- return buffer.toString();
- } catch (IOException e) {
- return formatted;
- }
- }
-
- /**
- * Converts <code>html</code> into java code suitable for formatting
- * by replacing any html entities by their plain text representation.
- *
- * @param html html code, may contain html entities
- * @return plain textified version of <code>html</code>
- */
- private String convertHtml2Java(String html) {
- HTMLEntity2JavaReader reader= new HTMLEntity2JavaReader(new StringReader(html));
- char[] buf= new char[html.length()]; // html2text never gets longer, only shorter!
-
- try {
- int read= reader.read(buf);
- return new String(buf, 0, read);
- } catch (IOException e) {
- return html;
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.text.comment.CommentRegion#createLine()
- * @since 3.1
- */
- protected CommentLine createLine() {
- return new JavaDocLine(this);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/MultiCommentLine.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/MultiCommentLine.java
deleted file mode 100644
index 876e4781..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/MultiCommentLine.java
+++ /dev/null
@@ -1,409 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.formatter.comment;
-
-import java.util.HashSet;
-import java.util.Set;
-
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.wst.jsdt.internal.compiler.parser.ScannerHelper;
-
-/**
- * Multi-line comment line in a comment region.
- *
- * @since 3.0
- */
-public class MultiCommentLine extends CommentLine implements ICommentAttributes, IHtmlTagDelimiters, IJavaDocTagConstants {
-
- /** Line prefix of multi-line comment content lines */
- public static final String MULTI_COMMENT_CONTENT_PREFIX= " * "; //$NON-NLS-1$
-
- /** Line prefix of multi-line comment end lines */
- public static final String MULTI_COMMENT_END_PREFIX= " */"; //$NON-NLS-1$
-
- /** Line prefix of multi-line comment content lines */
- public static final String MULTI_COMMENT_START_PREFIX= "/* "; //$NON-NLS-1$
-
- /** The indentation reference of this line */
- private String fReferenceIndentation= ""; //$NON-NLS-1$
-
- /** The javadoc tag lookup. */
- private static final Set fgTagLookup;
-
- static {
- fgTagLookup= new HashSet();
- for (int i= 0; i < JAVADOC_BREAK_TAGS.length; i++) {
- fgTagLookup.add(new String(JAVADOC_BREAK_TAGS[i]));
- }
- for (int i= 0; i < JAVADOC_SINGLE_BREAK_TAG.length; i++) {
- fgTagLookup.add(new String(JAVADOC_SINGLE_BREAK_TAG[i]));
- }
- for (int i= 0; i < JAVADOC_CODE_TAGS.length; i++) {
- fgTagLookup.add(new String(JAVADOC_CODE_TAGS[i]));
- }
- for (int i= 0; i < JAVADOC_IMMUTABLE_TAGS.length; i++) {
- fgTagLookup.add(new String(JAVADOC_IMMUTABLE_TAGS[i]));
- }
- for (int i= 0; i < JAVADOC_NEWLINE_TAGS.length; i++) {
- fgTagLookup.add(new String(JAVADOC_NEWLINE_TAGS[i]));
- }
- for (int i= 0; i < JAVADOC_SEPARATOR_TAGS.length; i++) {
- fgTagLookup.add(new String(JAVADOC_SEPARATOR_TAGS[i]));
- }
- }
-
- /**
- * Creates a new multi-line comment line.
- *
- * @param region comment region to create the line for
- */
- protected MultiCommentLine(final CommentRegion region) {
- super(region);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.text.comment.CommentLine#adapt(org.eclipse.wst.jsdt.internal.corext.text.comment.CommentLine)
- */
- protected void adapt(final CommentLine previous) {
-
- if (!hasAttribute(COMMENT_ROOT) && !hasAttribute(COMMENT_PARAMETER) && !previous.hasAttribute(COMMENT_BLANKLINE))
- fReferenceIndentation= previous.getIndentationReference();
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.text.comment.CommentLine#append(org.eclipse.wst.jsdt.internal.corext.text.comment.CommentRange)
- */
- protected void append(final CommentRange range) {
-
- final MultiCommentRegion parent= (MultiCommentRegion)getParent();
-
- if (range.hasAttribute(COMMENT_PARAMETER))
- setAttribute(COMMENT_PARAMETER);
- else if (range.hasAttribute(COMMENT_ROOT))
- setAttribute(COMMENT_ROOT);
- else if (range.hasAttribute(COMMENT_BLANKLINE))
- setAttribute(COMMENT_BLANKLINE);
-
- final int ranges= getSize();
- if (ranges == 1) {
-
- if (parent.isIndentRoots()) {
-
- final CommentRange first= getFirst();
- final String common= parent.getText(first.getOffset(), first.getLength()) + CommentRegion.COMMENT_RANGE_DELIMITER;
-
- if (hasAttribute(COMMENT_ROOT))
- fReferenceIndentation= common;
- else if (hasAttribute(COMMENT_PARAMETER)) {
- if (parent.isIndentDescriptions())
- fReferenceIndentation= "\t" + common; //$NON-NLS-1$
- else
- fReferenceIndentation= common;
- }
- }
- }
- super.append(range);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.text.comment.CommentLine#getContentLinePrefix()
- */
- protected String getContentPrefix() {
- return MULTI_COMMENT_CONTENT_PREFIX;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.text.comment.CommentLine#getEndLinePrefix()
- */
- protected String getEndingPrefix() {
- return MULTI_COMMENT_END_PREFIX;
- }
-
- /**
- * Returns the reference indentation to use for this line.
- *
- * @return the reference indentation for this line
- */
- protected final String getIndentationReference() {
- return fReferenceIndentation;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.text.comment.CommentLine#getStartLinePrefix()
- */
- protected String getStartingPrefix() {
- return MULTI_COMMENT_START_PREFIX;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.text.comment.CommentLine#scanLine(int)
- */
- protected void scanLine(final int line) {
-
- final CommentRegion parent= getParent();
- final String start= getStartingPrefix().trim();
- final String end= getEndingPrefix().trim();
- final String content= getContentPrefix().trim();
-
- final int lines= parent.getSize();
- final CommentRange range= getFirst();
-
- int offset= 0;
- int postfix= 0;
-
- String text= parent.getText(range.getOffset(), range.getLength());
- if (line == 0) {
-
- offset= text.indexOf(start);
- if (offset >= 0 && text.substring(0, offset).trim().length() != 0)
- offset= -1;
-
- if (offset >= 0) {
-
- offset += start.length();
- range.trimBegin(offset);
-
- postfix= text.lastIndexOf(end);
- if (postfix >= 0 && text.substring(postfix + end.length()).trim().length() != 0)
- postfix= -1;
-
- if (postfix >= offset)
- // comment ends on same line
- range.setLength(postfix - offset);
- else {
- postfix= text.lastIndexOf(content);
- if (postfix >= 0 && text.substring(postfix + content.length()).trim().length() != 0)
- postfix= -1;
-
- if (postfix >= offset) {
-
- range.setLength(postfix - offset);
- parent.setBorder(BORDER_UPPER);
-
- if (postfix > offset) {
-
- text= parent.getText(range.getOffset(), range.getLength());
- final IRegion region= trimLine(text, content);
-
- range.move(region.getOffset());
- range.setLength(region.getLength());
- }
- }
- }
- }
- } else if (line == lines - 1) {
-
- offset= text.indexOf(content);
- if (offset >= 0 && text.substring(0, offset).trim().length() != 0)
- offset= -1;
- postfix= text.lastIndexOf(end);
- if (postfix >= 0 && text.substring(postfix + end.length()).trim().length() != 0)
- postfix= -1;
-
- if (offset >= 0 && offset == postfix)
- // no content on line, only the comment postfix
- range.setLength(0);
- else {
- if (offset >= 0)
- // omit the content prefix
- range.trimBegin(offset + content.length());
-
- if (postfix >= 0)
- // omit the comment postfix
- range.trimEnd(-end.length());
-
- text= parent.getText(range.getOffset(), range.getLength());
- final IRegion region= trimLine(text, content);
- if (region.getOffset() != 0 || region.getLength() != text.length()) {
-
- range.move(region.getOffset());
- range.setLength(region.getLength());
-
- parent.setBorder(BORDER_UPPER);
- parent.setBorder(BORDER_LOWER);
- }
- }
- } else {
-
- offset= text.indexOf(content);
- if (offset >= 0 && text.substring(0, offset).trim().length() != 0)
- offset= -1;
-
- if (offset >= 0) {
-
- offset += content.length();
- range.trimBegin(offset);
- }
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.text.comment.CommentLine#tokenizeLine(int)
- */
- protected void tokenizeLine(int line) {
-
- int offset= 0;
- int index= offset;
-
- final CommentRegion parent= getParent();
- final CommentRange range= getFirst();
- final int begin= range.getOffset();
-
- final String content= parent.getText(begin, range.getLength());
- final int length= content.length();
-
- while (offset < length && ScannerHelper.isWhitespace(content.charAt(offset)))
- offset++;
-
- CommentRange result= null;
- if (offset >= length && !parent.isClearLines() && (line > 0 && line < parent.getSize() - 1)) {
-
- result= new CommentRange(begin, 0);
- result.setAttribute(COMMENT_BLANKLINE);
- result.setAttribute(COMMENT_FIRST_TOKEN);
-
- parent.append(result);
- }
-
- int attribute= COMMENT_FIRST_TOKEN | COMMENT_STARTS_WITH_RANGE_DELIMITER;
- while (offset < length) {
-
- while (offset < length && ScannerHelper.isWhitespace(content.charAt(offset))) {
- offset++;
- attribute |= COMMENT_STARTS_WITH_RANGE_DELIMITER;
- }
-
- index= offset;
-
- if (index < length) {
-
- if (content.charAt(index) == HTML_TAG_PREFIX) {
-
- // in order to avoid recognizing any < in a comment, even those which are part of e.g.
- // java source code, we validate the tag content to be one of the recognized
- // tags (structural, breaks, pre, code).
- int tag= ++index;
- while (index < length && content.charAt(index) != HTML_TAG_POSTFIX && content.charAt(index) != HTML_TAG_PREFIX)
- index++;
-
- if (index < length && content.charAt(index) == HTML_TAG_POSTFIX && isValidTag(content.substring(tag, index))) {
- index++;
- attribute |= COMMENT_HTML; // only set html attribute if postfix found
- } else {
- // no tag - do the usual thing from the original offset
- index= tag;
- while (index < length
- && !ScannerHelper.isWhitespace(content.charAt(index))
- && content.charAt(index) != HTML_TAG_PREFIX
- && !content.startsWith(LINK_TAG_PREFIX_STRING, index))
- index++;
- }
-
-
- } else if (content.startsWith(LINK_TAG_PREFIX_STRING, index)) {
-
- while (index < length && content.charAt(index) != LINK_TAG_POSTFIX)
- index++;
-
- if (index < length && content.charAt(index) == LINK_TAG_POSTFIX)
- index++;
-
- attribute |= COMMENT_OPEN | COMMENT_CLOSE;
-
- } else {
-
- while (index < length
- && !ScannerHelper.isWhitespace(content.charAt(index))
- && content.charAt(index) != HTML_TAG_PREFIX
- && !content.startsWith(LINK_TAG_PREFIX_STRING, index))
- index++;
- }
- }
-
- if (index - offset > 0) {
-
- result= new CommentRange(begin + offset, index - offset);
- result.setAttribute(attribute);
-
- parent.append(result);
- offset= index;
- }
-
- attribute= 0;
- }
- }
-
- /**
- * Checks whether <code>tag</code> is a valid tag content (text inside
- * the angular brackets &lt;, &gt;).
- * <p>
- * The algorithm is to see if the tag trimmed of whitespace and an
- * optional slash starts with one of our recognized tags.
- *
- * @param tag the tag to check
- * @return <code>true</code> if <code>tag</code> is a valid tag
- * content
- */
- private boolean isValidTag(String tag) {
- // strip the slash
- if (tag.startsWith("/")) //$NON-NLS-1$
- tag= tag.substring(1, tag.length());
-
- // strip ws
- tag= tag.trim();
-
- // extract first token
- int i= 0;
- while (i < tag.length() && !ScannerHelper.isWhitespace(tag.charAt(i)))
- i++;
- tag= tag.substring(0, i);
-
- // see if it's a tag
- return isTagName(tag.toLowerCase());
- }
-
- /**
- * Checks whether <code>tag</code> is one of the configured tags.
- *
- * @param tag the tag to check
- * @return <code>true</code> if <code>tag</code> is a configured tag
- * name
- */
- private boolean isTagName(String tag) {
- return fgTagLookup.contains(tag);
- }
-
- /**
- * Removes all leading and trailing occurrences from <code>line</code>.
- *
- * @param line the string to remove the occurrences of
- * <code>trimmable</code>
- * @param trimmable the string to remove from <code>line</code>
- * @return the region of the trimmed substring within <code>line</code>
- */
- protected final IRegion trimLine(final String line, final String trimmable) {
-
- final int trim= trimmable.length();
-
- int offset= 0;
- int length= line.length() - trim;
-
- while (line.startsWith(trimmable, offset))
- offset += trim;
-
- while (line.startsWith(trimmable, length))
- length -= trim;
-
- return new Region(offset, length + trim);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/MultiCommentRegion.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/MultiCommentRegion.java
deleted file mode 100644
index eaa7d276..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/MultiCommentRegion.java
+++ /dev/null
@@ -1,245 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.formatter.comment;
-
-import java.util.Iterator;
-import java.util.ListIterator;
-
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.Position;
-import org.eclipse.wst.jsdt.internal.formatter.CodeFormatterVisitor;
-
-/**
- * Multi-comment region in a source code document.
- *
- * @since 3.0
- */
-public class MultiCommentRegion extends CommentRegion implements IJavaDocTagConstants {
-
- /** Should root tag parameter descriptions be indented after the tag? */
- private final boolean fIndentDescriptions;
-
- /** Should root tag parameter descriptions be indented? */
- private final boolean fIndentRoots;
-
- /** Should description of parameters go to the next line? */
- private final boolean fParameterNewLine;
-
- /** Should root tags be separated from description? */
- private boolean fSeparateRoots;
-
- /**
- * Creates a new multi-comment region.
- *
- * @param document the document which contains the comment region
- * @param position the position of this comment region in the document
- * @param formatter the given formatter
- */
- public MultiCommentRegion(final IDocument document, final Position position, final CodeFormatterVisitor formatter) {
- super(document, position, formatter);
-
- fIndentRoots= this.preferences.comment_indent_root_tags;
- fIndentDescriptions= this.preferences.comment_indent_parameter_description;
- fSeparateRoots= this.preferences.comment_insert_empty_line_before_root_tags;
- fParameterNewLine= this.preferences.comment_insert_new_line_for_parameter;
- fClear = this.preferences.comment_clear_blank_lines_in_block_comment;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.text.comment.CommentRegion#canAppend(org.eclipse.wst.jsdt.internal.corext.text.comment.CommentLine, org.eclipse.wst.jsdt.internal.corext.text.comment.CommentRange, org.eclipse.wst.jsdt.internal.corext.text.comment.CommentRange, int, int)
- */
- protected boolean canAppend(final CommentLine line, final CommentRange previous, final CommentRange next, final int index, int count) {
-
- final boolean blank= next.hasAttribute(COMMENT_BLANKLINE);
-
- // Avoid wrapping punctuation
- if (next.getLength() <= 2 && !blank && isNonAlphaNumeric(next))
- return true;
-
- if (fParameterNewLine && line.hasAttribute(COMMENT_PARAMETER) && line.getSize() > 1)
- return false;
-
- if (previous != null) {
-
- if (index != 0 && (blank || previous.hasAttribute(COMMENT_BLANKLINE) || next.hasAttribute(COMMENT_PARAMETER) || next.hasAttribute(COMMENT_ROOT) || next.hasAttribute(COMMENT_SEPARATOR) || next.hasAttribute(COMMENT_NEWLINE) || previous.hasAttribute(COMMENT_BREAK) || previous.hasAttribute(COMMENT_SEPARATOR)))
- return false;
-
- if (previous.hasAttribute(COMMENT_ROOT))
- return true;
-
- if (next.hasAttribute(COMMENT_IMMUTABLE) && previous.hasAttribute(COMMENT_IMMUTABLE))
- return true;
- }
-
- // always append elements that did not have any range separators
- if (!next.hasAttribute(COMMENT_STARTS_WITH_RANGE_DELIMITER)) {
- return true;
- }
-
- if (fIndentRoots && !line.hasAttribute(COMMENT_ROOT) && !line.hasAttribute(COMMENT_PARAMETER))
- count -= stringToLength(line.getIndentationReference());
-
- // Avoid appending consecutive immutable ranges, which together exceed the line width
- if (next.hasAttribute(COMMENT_IMMUTABLE) && (previous == null || !previous.hasAttribute(COMMENT_IMMUTABLE))) {
- // Breaking the abstraction by directly accessing the list of ranges for looking ahead
- Iterator iter= getRanges().iterator();
- CommentRange current= null;
- while (iter.hasNext() && current != next)
- current= (CommentRange) iter.next();
-
- if (current != null && iter.hasNext()) {
- try {
- int lineNumber= getDocument().getLineOfOffset(getOffset() + current.getOffset());
- CommentRange last= current;
- while (iter.hasNext()) {
- current= (CommentRange) iter.next();
- if (current.hasAttribute(COMMENT_IMMUTABLE) && getDocument().getLineOfOffset(getOffset() + current.getOffset()) == lineNumber)
- last= current;
- else
- break;
- }
- count -= last.getOffset() + last.getLength() - (next.getOffset() + next.getLength());
- } catch (BadLocationException e) {
- // Should not happen
- }
- }
- }
-
- return super.canAppend(line, previous, next, index, count);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.text.comment.CommentRegion#getDelimiter(org.eclipse.wst.jsdt.internal.corext.text.comment.CommentLine, org.eclipse.wst.jsdt.internal.corext.text.comment.CommentLine, org.eclipse.wst.jsdt.internal.corext.text.comment.CommentRange, org.eclipse.wst.jsdt.internal.corext.text.comment.CommentRange, java.lang.String)
- */
- protected String getDelimiter(CommentLine predecessor, CommentLine successor, CommentRange previous, CommentRange next, String indentation) {
-
- final String delimiter= super.getDelimiter(predecessor, successor, previous, next, indentation);
-
- if (previous != null) {
-
- // Blank line before <pre> tag
- if (previous.hasAttribute(COMMENT_IMMUTABLE | COMMENT_SEPARATOR) && !next.hasAttribute(COMMENT_CODE) && !successor.hasAttribute(COMMENT_BLANKLINE))
- return delimiter + delimiter;
-
- // Blank line after </pre> tag
- else if (next.hasAttribute(COMMENT_IMMUTABLE | COMMENT_SEPARATOR) && !successor.hasAttribute(COMMENT_BLANKLINE) && !predecessor.hasAttribute(COMMENT_BLANKLINE))
- return delimiter + delimiter;
-
- // Add blank line before first root/parameter tag, if "Blank line before Javadoc tags"
- else if (fSeparateRoots && previous.hasAttribute(COMMENT_PARAGRAPH) && !successor.hasAttribute(COMMENT_BLANKLINE) && !predecessor.hasAttribute(COMMENT_BLANKLINE))
- return delimiter + delimiter;
-
- else if (fIndentRoots && !predecessor.hasAttribute(COMMENT_ROOT) && !predecessor.hasAttribute(COMMENT_PARAMETER) && !predecessor.hasAttribute(COMMENT_BLANKLINE))
- return delimiter + stringToIndent(predecessor.getIndentationReference());
- }
- return delimiter;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.text.comment.CommentRegion#getDelimiter(org.eclipse.wst.jsdt.internal.corext.text.comment.CommentRange, org.eclipse.wst.jsdt.internal.corext.text.comment.CommentRange)
- */
- protected String getDelimiter(final CommentRange previous, final CommentRange next) {
- // simply preserve range (~ word) breaks
- if (previous != null && !previous.hasAttribute(COMMENT_STARTS_WITH_RANGE_DELIMITER)) {
- return ""; //$NON-NLS-1$
- } else {
- return super.getDelimiter(previous, next);
- }
- }
-
- /**
- * Should root tag parameter descriptions be indented after the tag?
- *
- * @return <code>true</code> iff the descriptions should be indented
- * after, <code>false</code> otherwise.
- */
- protected final boolean isIndentDescriptions() {
- return fIndentDescriptions;
- }
-
- /**
- * Should root tag parameter descriptions be indented?
- *
- * @return <code>true</code> iff the root tags should be indented,
- * <code>false</code> otherwise.
- */
- protected final boolean isIndentRoots() {
- return fIndentRoots;
- }
-
- /**
- * Marks the comment ranges confined by HTML ranges.
- */
- protected void markHtmlRanges() {
- // Do nothing
- }
-
- /**
- * Marks the comment range with its HTML tag attributes.
- *
- * @param range the comment range to mark
- * @param token token associated with the comment range
- */
- protected void markHtmlTag(final CommentRange range, final char[] token) {
- // Do nothing
- }
-
- /**
- * Marks the comment range with its javadoc tag attributes.
- *
- * @param range the comment range to mark
- * @param token token associated with the comment range
- */
- protected void markJavadocTag(final CommentRange range, final char[] token) {
- range.markPrefixTag(COMMENT_ROOT_TAGS, COMMENT_TAG_PREFIX, token, COMMENT_ROOT);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.text.comment.CommentRegion#markRegion()
- */
- protected void markRegion() {
-
- int count= 0;
- boolean paragraph= false;
-
- char[] token= null;
- CommentRange range= null;
-
- for (final ListIterator iterator= getRanges().listIterator(); iterator.hasNext();) {
-
- range= (CommentRange)iterator.next();
- count= range.getLength();
-
- if (count > 0) {
-
- token= getText(range.getOffset(), count).toLowerCase().toCharArray();
-
- markJavadocTag(range, token);
- if (!paragraph && (range.hasAttribute(COMMENT_ROOT) || range.hasAttribute(COMMENT_PARAMETER))) {
- range.setAttribute(COMMENT_PARAGRAPH);
- paragraph= true;
- }
- markHtmlTag(range, token);
- }
- }
- markHtmlRanges();
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.text.comment.CommentRegion#createLine()
- * @since 3.1
- */
- protected CommentLine createLine() {
- return new MultiCommentLine(this);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/SingleCommentLine.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/SingleCommentLine.java
deleted file mode 100644
index 4f376db3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/SingleCommentLine.java
+++ /dev/null
@@ -1,115 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.formatter.comment;
-
-/**
- * Single-line comment line in a comment region.
- *
- * @since 3.0
- */
-public class SingleCommentLine extends CommentLine {
-
- /** Line prefix for single line comments */
- public static final String SINGLE_COMMENT_PREFIX= "// "; //$NON-NLS-1$
-
- /** NLS tag prefix */
- private static final String NLS_TAG_PREFIX= "//$NON-NLS-"; //$NON-NLS-1$
-
- /** Is the comment a NLS locale tag sequence? */
- private boolean fLocaleSequence= false;
-
- /**
- * Creates a new single-line comment line.
- *
- * @param region comment region to create the line for
- */
- protected SingleCommentLine(final CommentRegion region) {
- super(region);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.text.comment.CommentLine#adapt(org.eclipse.wst.jsdt.internal.corext.text.comment.CommentLine)
- */
- protected void adapt(final CommentLine previous) {
- // Do nothing
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.text.comment.CommentLine#formatLowerBorder(org.eclipse.wst.jsdt.internal.corext.text.comment.CommentRange, java.lang.String, int)
- */
- protected void formatLowerBorder(final CommentRange range, final String indentation, final int length) {
-
- final int offset= range.getOffset() + range.getLength();
- final CommentRegion parent= getParent();
-
- parent.logEdit(parent.getDelimiter(), offset, parent.getLength() - offset);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.text.comment.CommentLine#formatUpperBorder(org.eclipse.wst.jsdt.internal.corext.text.comment.CommentRange, java.lang.String, int)
- */
- protected void formatUpperBorder(final CommentRange range, final String indentation, final int length) {
-
- final CommentRegion parent= getParent();
-
- parent.logEdit(getContentPrefix(), 0, range.getOffset());
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.text.comment.CommentLine#getContentPrefix()
- */
- protected String getContentPrefix() {
- return SINGLE_COMMENT_PREFIX;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.text.comment.CommentLine#getEndingPrefix()
- */
- protected String getEndingPrefix() {
- return SINGLE_COMMENT_PREFIX;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.text.comment.CommentLine#getStartingPrefix()
- */
- protected String getStartingPrefix() {
- return SINGLE_COMMENT_PREFIX;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.text.comment.CommentLine#scanLine(int)
- */
- protected void scanLine(final int line) {
-
- final CommentRange range= getFirst();
- final String content= getParent().getText(range.getOffset(), range.getLength());
- final String prefix= getContentPrefix().trim();
-
- final int offset= content.indexOf(prefix);
- if (offset >= 0) {
-
- if (content.startsWith(NLS_TAG_PREFIX))
- fLocaleSequence= true;
-
- range.trimBegin(offset + prefix.length());
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.text.comment.CommentLine#tokenizeLine(int)
- */
- protected void tokenizeLine(final int line) {
-
- if (!fLocaleSequence)
- super.tokenizeLine(line);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/SubstitutionTextReader.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/SubstitutionTextReader.java
deleted file mode 100644
index d0a1395d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/comment/SubstitutionTextReader.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.formatter.comment;
-
-
-import java.io.IOException;
-import java.io.Reader;
-
-import org.eclipse.wst.jsdt.internal.compiler.parser.ScannerHelper;
-
-/**
- * Reads the text contents from a reader and computes for each character
- * a potential substitution. The substitution may eat more characters than
- * only the one passed into the computation routine.
- */
-public abstract class SubstitutionTextReader extends Reader {
-
- private Reader fReader;
- private boolean fWasWhiteSpace;
- private int fCharAfterWhiteSpace;
-
- /**
- * Tells whether white space characters are skipped.
- */
- private boolean fSkipWhiteSpace= true;
-
- private boolean fReadFromBuffer;
- private StringBuffer fBuffer;
- private int fIndex;
-
-
- protected SubstitutionTextReader(Reader reader) {
- fReader= reader;
- fBuffer= new StringBuffer();
- fIndex= 0;
- fReadFromBuffer= false;
- fCharAfterWhiteSpace= -1;
- fWasWhiteSpace= true;
- }
-
- /**
- * Gets the content as a String
- */
- public String getString() throws IOException {
- StringBuffer buf= new StringBuffer();
- int ch;
- while ((ch= read()) != -1) {
- buf.append((char)ch);
- }
- return buf.toString();
- }
-
- /**
- * Implement to compute the substitution for the given character and
- * if necessary subsequent characters. Use <code>nextChar</code>
- * to read subsequent characters.
- */
- protected abstract String computeSubstitution(int c) throws IOException;
-
- /**
- * Returns the internal reader.
- */
- protected Reader getReader() {
- return fReader;
- }
-
- /**
- * Returns the next character.
- */
- protected int nextChar() throws IOException {
- fReadFromBuffer= (fBuffer.length() > 0);
- if (fReadFromBuffer) {
- char ch= fBuffer.charAt(fIndex++);
- if (fIndex >= fBuffer.length()) {
- fBuffer.setLength(0);
- fIndex= 0;
- }
- return ch;
- } else {
- int ch= fCharAfterWhiteSpace;
- if (ch == -1) {
- ch= fReader.read();
- }
- if (fSkipWhiteSpace && ScannerHelper.isWhitespace((char)ch)) {
- do {
- ch= fReader.read();
- } while (ScannerHelper.isWhitespace((char)ch));
- if (ch != -1) {
- fCharAfterWhiteSpace= ch;
- return ' ';
- }
- } else {
- fCharAfterWhiteSpace= -1;
- }
- return ch;
- }
- }
-
- /*
- * @see Reader#read()
- */
- public int read() throws IOException {
- int c;
- do {
-
- c= nextChar();
- while (!fReadFromBuffer) {
- String s= computeSubstitution(c);
- if (s == null)
- break;
- if (s.length() > 0)
- fBuffer.insert(0, s);
- c= nextChar();
- }
-
- } while (fSkipWhiteSpace && fWasWhiteSpace && (c == ' '));
- fWasWhiteSpace= (c == ' ' || c == '\r' || c == '\n');
- return c;
- }
-
- /*
- * @see Reader#read(char[],int,int)
- */
- public int read(char cbuf[], int off, int len) throws IOException {
- int end= off + len;
- for (int i= off; i < end; i++) {
- int ch= read();
- if (ch == -1) {
- if (i == off) {
- return -1;
- } else {
- return i - off;
- }
- }
- cbuf[i]= (char)ch;
- }
- return len;
- }
-
- /*
- * @see java.io.Reader#ready()
- */
- public boolean ready() throws IOException {
- return fReader.ready();
- }
-
- /*
- * @see Reader#close()
- */
- public void close() throws IOException {
- fReader.close();
- }
-
- /*
- * @see Reader#reset()
- */
- public void reset() throws IOException {
- fReader.reset();
- fWasWhiteSpace= true;
- fCharAfterWhiteSpace= -1;
- fBuffer.setLength(0);
- fIndex= 0;
- }
-
- protected final void setSkipWhitespace(boolean state) {
- fSkipWhiteSpace= state;
- }
-
- protected final boolean isSkippingWhitespace() {
- return fSkipWhiteSpace;
- }
-}
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
deleted file mode 100644
index 476842b1..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/options.properties
+++ /dev/null
@@ -1,75 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 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
-# http://www.eclipse.org/legal/epl-v10.html
-#
-# Contributors:
-# IBM Corporation - initial API and implementation
-###############################################################################
-newline.openingBrace.number=1
-newline.openingBrace.category=Newline
-newline.openingBrace.name=I&nsert new line before opening brace
-newline.openingBrace.possibleValues=2|Insert|Do not insert
-newline.openingBrace.description=When Insert, a new line is inserted before an opening brace, otherwise nothing is inserted
-
-newline.controlStatement.number=2
-newline.controlStatement.category=Newline
-newline.controlStatement.name=Insert new &line in control statement
-newline.controlStatement.possibleValues=2|Insert|Do not insert
-newline.controlStatement.description=When Insert, a new line is inserted between } and else, catch, finally
-
-newline.clearAll.number=3
-newline.clearAll.category=Newline
-newline.clearAll.name=Clear all &blank lines
-newline.clearAll.possibleValues=2|Clear|Preserve one
-newline.clearAll.description=When Clear, all blank lines are removed. When Preserve one, only one is kept and all others removed.
-
-newline.elseIf.number=4
-newline.elseIf.category=Newline
-newline.elseIf.name=&Keep else if on the same line
-newline.elseIf.possibleValues=2|Yes|No
-newline.elseIf.description=When Yes, a blank line is inserted between a else and a if when they are contiguous
-
-newline.emptyBlock.number=5
-newline.emptyBlock.category=Newline
-newline.emptyBlock.name=In&sert a new line inside an empty block
-newline.emptyBlock.possibleValues=2|Insert|Do not insert
-newline.emptyBlock.description=When insert, a line break is inserted between contiguous { and }, if } is not followed by a keyword.
-
-line.split.number=6
-line.split.category=Line splitting
-line.split.name=Ma&ximum line length
-line.split.possibleValues=-1
-line.split.description=Enable splitting of long lines (exceeding the configurable length). Length of 0 will disable line splitting
-
-style.compactAssignment.number=7
-style.compactAssignment.category=Style
-style.compactAssignment.name=&Compact assignment
-style.compactAssignment.possibleValues=2|Compact|Normal
-style.compactAssignment.description=Assignments can be formatted asymmetrically, e.g. 'int x= 2;', when Normal, a space is inserted before the assignment operator
-
-style.reuseExistingLayout.number=8
-style.reuseExistingLayout.category=Style
-style.reuseExistingLayout.name=&Reuse existing layout
-style.reuseExistingLayout.possibleValues=2|Reuse|Do not reuse
-style.reuseExistingLayout.description=If the user has formatted his code a certain way, the formatter does not try to reformat it
-
-tabulation.char.number=9
-tabulation.char.category=Style
-tabulation.char.name=Indentation is represented by &tab
-tabulation.char.possibleValues=2|Tab|Spaces
-tabulation.char.description=Either choose to indent with tab characters or spaces
-
-tabulation.size.number=10
-tabulation.size.category=Style
-tabulation.size.name=&Amount of spaces representing a tab
-tabulation.size.possibleValues=-1
-tabulation.size.description=Tabulation size in term of space characters
-
-space.castexpression.number=11
-space.castexpression.category=Style
-space.castexpression.name=&Insert a space in cast expression
-space.castexpression.size.possibleValues=2|Insert|Do not insert
-space.castexpression.description=When insert, a space is added between the closing parenthesis and the expression of the cast expression
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
deleted file mode 100644
index cb790da9..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Alias.java
+++ /dev/null
@@ -1,28 +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.oaametadata;
-
-public class Alias {
-/* alias_element = element alias {
- alias_content & alias_attributes & foreign_attributes
- }
- alias_content = (
- empty
- )
- alias_attributes = (
- name & datatype
- )
-*/
- public String name;
- public String datatype;
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Ancestor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Ancestor.java
deleted file mode 100644
index 65b10662..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Ancestor.java
+++ /dev/null
@@ -1,15 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.oaametadata;
-
-public class Ancestor {
- String dataType;
-}
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
deleted file mode 100644
index a0f006e6..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Author.java
+++ /dev/null
@@ -1,35 +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.oaametadata;
-
-public class Author {
-// author_element = element author {
-// author_content & author_attributes & foreign_attributes
-// }
-// author_content = (
-// aboutMe_element? & quote_element?
-// )
-// author_attributes = (
-// email? & location? & name? & organization? &
-// photo? & type? & website?
-// )
-
- public String email;
- public String location;
- public String name;
- public String organization;
- public String photo;
- public String type;
- public String website;
-
- public String aboutMe;
- public String quote;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/ClassData.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/ClassData.java
deleted file mode 100644
index 2504e265..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/ClassData.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.oaametadata;
-
-import java.util.ArrayList;
-
-public class ClassData extends VersionableElement{
-
-
-/* class_element = element class {
- class_content & class_attributes & foreign_nodes
- }
- class_content = (
- aliases_element? & ancestors_element? & constructors_element? &
- mixes_element? & methods_element? & properties_element? &
- descriptive_elements & compatibility_elements
- )
- class_attributes = (
- name & superclass? & visibility? &
- getterPattern? & setterPattern?
- )
-
-
- interface_element = element interface {
- interface_content & interface_attributes & foreign_nodes
- }
- interface_content = (
- constructors_element? & exceptions_element? & mixes_element? &
- methods_element? & properties_element? &
- descriptive_elements & compatibility_elements
- # Research the above, make consistent with the spec
- # FIXME: aliases? ancestors?
- )
- interface_attributes = (
- name? & superclass? & visibility? &
- getterPattern? & setterPattern?
- )
-
-
-*/
-
- public Ancestor [] ancestors;
- public Alias [] aliases;
- public Method [] constructors;
- public Event [] events;
- public Method [] methods;
- public Property [] fields;
- public Property [] properties;
- public Mix [] mixins;
-
- public String name;
- public String superclass;
- public String visibility;
- public String getterPattern;
- public String setterPattern;
- public boolean isInterface;
-
- public Property [] getFields()
- {
- ArrayList list = new ArrayList();
- if (this.fields!=null)
- for (int i = 0; i < this.fields.length; i++) {
- if (this.fields[i].isField)
- list.add(this.fields[i]);
- }
- return (Property [] )list.toArray(new Property[list.size()]);
- }
-
- public Property [] getProperties()
- {
- ArrayList list = new ArrayList();
- if (this.fields!=null)
- for (int i = 0; i < this.fields.length; i++) {
- if (!this.fields[i].isField)
- list.add(this.fields[i]);
- }
- return (Property [] )list.toArray(new Property[list.size()]);
- }
-
-
- public Method getMethod(String name)
- {
- if (this.methods!=null)
- for (int i = 0; i < this.methods.length; i++) {
- if (this.methods[i].name.equals(name))
- return this.methods[i];
-
- }
- return null;
- }
-
- public Property getField(String elementName) {
- if (this.fields!=null)
- for (int i = 0; i < this.fields.length; i++) {
- if (elementName.equals( this.fields[i].name))
- return this.fields[i];
- }
- if (this.properties!=null)
- for (int i = 0; i < this.properties.length; i++) {
- if (elementName.equals( this.properties[i].name))
- return this.properties[i];
- }
- return null;
-
- }
-
- public String getSuperClass()
- {
- if (superclass!=null && superclass.length()>0)
- return superclass;
- if (this.ancestors!=null )
- for (int i = 0; i < this.ancestors.length; i++) {
-//TODO: should be other attributes on ancestor to check, not yet in spec
- String dataType = this.ancestors[i].dataType;
- if (dataType!=null&& dataType.length()>0)
- return dataType;
- }
- return null;
- }
-}
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
deleted file mode 100644
index 9bc1cc37..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/DepreciatedOrAvailable.java
+++ /dev/null
@@ -1,19 +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.oaametadata;
-
-public class DepreciatedOrAvailable {
-
- public boolean isDepreciated;
- public String text;
- public String version;
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/DocumentedElement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/DocumentedElement.java
deleted file mode 100644
index 4fbe38aa..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/DocumentedElement.java
+++ /dev/null
@@ -1,19 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.oaametadata;
-
-public class DocumentedElement {
- public String description;
- public String remarks;
- public String examples;
-
- public boolean isHTMLDescription;
-}
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
deleted file mode 100644
index f3098bb1..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Enum.java
+++ /dev/null
@@ -1,18 +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.oaametadata;
-
-public class Enum {
-
- public String name;
- public String datatype;
- public Option[]options;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Event.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Event.java
deleted file mode 100644
index d2ddd9b3..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Event.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.oaametadata;
-
-public class Event extends VersionableElement {
-
- public Parameter [] parameters;
- public ReturnsData returns;
- /*
- event_element = element event {
- event_content & event_attributes & foreign_nodes
- }
- event_content = (
- parameters_element? & returns_element? &
- descriptive_elements & compatibility_elements
- # Research the above, make consistent with the spec
- # <parameters>? <returns>?
- )
- event_attributes = (
- empty
- )
- */
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Exception.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Exception.java
deleted file mode 100644
index 704267ca..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Exception.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.oaametadata;
-
-public class Exception extends VersionableElement{
-
-
-// exception_element = element exception {
-// exception_content & exception_attributes & foreign_nodes
-// }
-// exception_content = (
-// parameters_element? & returns_element? &
-// descriptive_elements & compatibility_elements
-// # Research the above, make consistent with the spec
-// # <parameters>? <returns>?
-// )
-// exception_attributes = (
-// empty
-// )
-
- public Parameter[] parameters;
- public ReturnsData returns;
- public String type;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/IOAAMetaDataConstants.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/IOAAMetaDataConstants.java
deleted file mode 100644
index 38a2266e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/IOAAMetaDataConstants.java
+++ /dev/null
@@ -1,154 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.oaametadata;
-
-public interface IOAAMetaDataConstants {
-
- public final static String METADATA_FILE="oam.xml";
-
- public final static String NAMESPACE_API="http://openajax.org/metadata";
-
- public final static String TAG_ABOUTME="aboutMe";
- public final static String TAG_ALIAS="alias";
- public final static String ATTRIBUTE_ALAIS_NAME="name";
- public final static String ATTRIBUTE_ALAIS_TYPE="datatype";
- public final static String TAG_ALIASES ="aliases";
- public final static String TAG_ANCESTORS = "ancestors";
- public final static String TAG_ANCESTOR = "ancestor";
- public final static String ATTRIBUTE_ANCESTOR_DATATYPE = "datatype";
-
- public final static String TAG_API="api";
- public final static String ATTRIBUTE_API_VERSION ="version";
- public final static String ATTRIBUTE_API_LANGUAGE ="language";
- public final static String ATTRIBUTE_API_GETTERPATTERN="getterPattern";
- public final static String ATTRIBUTE_API_SETTERPATTERN="setterPattern";
- public final static String ATTRIBUTE_API_SPEC="spec";
-
- public final static String TAG_AUTHOR="author";
- public final static String ATTRIBUTE_AUTHOR_EMAIL ="email";
- public final static String ATTRIBUTE_AUTHOR_LOCATION ="location";
- public final static String ATTRIBUTE_AUTHOR_NAME ="name";
- public final static String ATTRIBUTE_AUTHOR_ORGANIZATION ="organization";
- public final static String ATTRIBUTE_AUTHOR_PHOTO ="photo";
- public final static String ATTRIBUTE_AUTHOR_TYPE ="type";
- public final static String ATTRIBUTE_AUTHOR_WEBSITE ="website";
- public final static String TAG_AUTHORS ="authors";
- public final static String TAG_AVAILABLE ="available";
- public final static String ATTRIBUTE_AVAILABLE_VERSION ="version";
- public final static String TAG_CLASS ="class";
- public final static String ATTRIBUTE_CLASS_NAME ="name";
- public final static String ATTRIBUTE_CLASS_SUPERCLASS ="superclass";
- public final static String ATTRIBUTE_CLASS_VISIBILITY ="visibility";
- public final static String ATTRIBUTE_CLASS_GETTERPATTERN="getterPattern";
- public final static String ATTRIBUTE_CLASS_SETTERPATTERN="setterPattern";
- public final static String TAG_CLASSES ="classes";
- public final static String TAG_CONSTRUCTOR ="constructor";
- public final static String ATTRIBUTE_CONSTRUCTOR_SCOPE ="scope";
- public final static String ATTRIBUTE_CONSTRUCTOR_VISIBILITY ="visibility";
- public final static String TAG_CONSTRUCTORS ="constructors";
- public final static String TAG_DEPRECIATED ="deprecated";
- public final static String ATTRIBUTE_DEPRECIATED_VERSION = "version";
- public final static String TAG_DESCRIPTION ="description";
- public final static String ATTRIBUTE_DESCRIPTION_TYPE ="type";
- public final static String TAG_ENUM ="enum";
- public final static String ATTRIBUTE_ENUM_NAME ="name";
- public final static String ATTRIBUTE_ENUM_DATATYPE ="datatype";
- public final static String TAG_ENUMS ="enums";
- public final static String TAG_EVENT ="event";
- public final static String TAG_EVENTS ="events";
- public final static String TAG_EXAMPLE ="example";
- public final static String TAG_EXAMPLES ="examples";
- public final static String TAG_EXCEPTION ="exception";
- public final static String ATTRIBUTE_EXCEPTION_TYPE ="type";
- public final static String TAG_EXCEPTIONS ="exceptions";
- public final static String TAG_FIELD ="field";
- public final static String ATTRIBUTE_FIELD_NAME = "name";
- public final static String ATTRIBUTE_FIELD_DATATYPE = "datatype";
- public final static String ATTRIBUTE_FIELD_VISIBILITY = "visibility";
- public final static String ATTRIBUTE_FIELD_SCOPE = "scope";
- public final static String TAG_FIELDS ="fields";
- public final static String TAG_FRAGMENT ="fragment";
- public final static String TAG_GLOBALS ="globals";
- public final static String TAG_INCLUDE ="include";
- public final static String ATTRIBUTE_INCLUDE_SRC ="src";
- public final static String TAG_INTERFACE ="interface";
- public final static String ATTRIBUTE_INTERFACE_NAME ="name";
- public final static String ATTRIBUTE_INTERFACE_TYPE ="type";
- public final static String ATTRIBUTE_INTERFACE_SUPERCLASS ="superclass";
- public final static String ATTRIBUTE_INTERFACE_VISIBILITY ="visibility";
- public final static String TAG_INTERFACES ="interfaces";
- public final static String TAG_LICENSE ="license";
- public final static String TAG_METHOD ="method";
- public final static String ATTRIBUTE_METHOD_NAME ="name";
- public final static String ATTRIBUTE_METHOD_SCOPE ="scope";
- public final static String TAG_METHODS ="methods";
- public final static String TAG_MIX ="mix";
- public final static String ATTRIBUTE_MIX_DATATYPE ="datatype";
- public final static String ATTRIBUTE_MIX_FROMSCOPE ="fromScope";
- public final static String ATTRIBUTE_MIX_TOSCOPE ="toScope";
- public final static String TAG_MIXES ="mixes";
- public final static String TAG_MIXIN ="mixin";
- public final static String ATTRIBUTE_MIXIN_NAME ="name";
- public final static String ATTRIBUTE_MIXIN_SCOPE ="scope";
- public final static String ATTRIBUTE_MIXIN_VISIBILITY ="visibility";
- public final static String TAG_MIXINS ="mixins";
- public final static String TAG_NAMESPACE ="namespace";
- public final static String ATTRIBUTE_NAMESPACE_NAME ="name";
- public final static String ATTRIBUTE_NAMESPACE_VISIBILITY ="visibility";
- public final static String TAG_NAMESPACES ="namespaces";
- public final static String TAG_OPTION ="option";
- public final static String ATTRIBUTE_OPTION_LABEL ="label";
- public final static String ATTRIBUTE_OPTION_VALUE ="value";
- public final static String TAG_OPTIONS ="options";
- public final static String TAG_PARAMETER ="parameter";
- public final static String ATTRIBUTE_PARAMETER_NAME ="name";
- public final static String ATTRIBUTE_PARAMETER_DATATYPE ="datatype";
- public final static String ATTRIBUTE_PARAMETER_USAGE ="usage";
- public final static String TAG_PARAMETERS ="parameters";
- public final static String TAG_PROPERTIES ="properties";
- public final static String TAG_PROPERTY ="property";
- public final static String TAG_QOUTE="quote";
- public final static String TAG_REMARKS ="remarks";
- public final static String TAG_RETURNS ="returns";
- public final static String ATTRIBUTE_RETURNS_DATATYPE ="datatype";
- public final static String TAG_SEEALSO ="seealso";
- public final static String TAG_TITLE ="title";
- public final static String TAG_TOPIC ="topic";
- public final static String TAG_TOPICS ="topics";
- public final static String TAG_USERAGENT ="useragent";
- public final static String TAG_USERAGENTS ="useragents";
-
-
- public final static String USAGE_STATIC ="static";
- public final static String USAGE_INSTANCE ="instance";
-
- public final static String VISIBILITY_PUBLIC ="public";
- public final static String VISIBILITY_PRIVATE ="private";
- public final static String VISIBILITY_PROTECTED ="protected";
- public final static String VISIBILITY_INTERNAL ="internal";
- public final static String VISIBILITY_PROTECTED_INTERNAL ="protected-internal";
-
-
- public final static String MIME_TYPE_TEXT="text/plain";
- public final static String MIME_TYPE_HTML="text/html";
-
-//
-// LOCALIZATION
-//
- public final static String TAG_MESSAGEBUNDLE ="messagebundle";
- public final static String TAG_MSG ="msg";
- public final static String ATTRIBUTE_MSG_NAME ="name";
-
- public final static String VARIABLE_SUBSTITUTION_STRING ="%%";
-
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/LibraryAPIs.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/LibraryAPIs.java
deleted file mode 100644
index 06b2f5df..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/LibraryAPIs.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*******************************************************************************
- * 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.internal.oaametadata;
-
-public class LibraryAPIs {
- public ClassData[] classes;
-
- public Method [] globalMethods;
- public Property[] globalVars;
-
-// interface
-// license
-
-
- public String description;
- public Author[] authors;
- public char[] fileName;
- public Enum[] enums;
- public Mixin [] mixins;
- public Namespace [] namespaces;
-
- // Attributes
- public String libraryVersion;
- public String language;
- public String getterPattern;
- public String setterPattern;
- public String spec;
-
-// alias_element* & aliases_element? & class_element* & classes_element? &
-// globals_element? & interface_element* & interfaces_element? & license_element? &
-// mixin_element* & mixins_element? & namespace_element* & namespaces_element? &
-// descriptive_elements
- Alias [] aliases;
-
-
- public Property getGlobalVar(String name) {
- if (this.globalVars!=null)
- for (int i = 0; i < this.globalVars.length; i++) {
- if (name.equals(this.globalVars[i].name))
- return this.globalVars[i];
- }
- return null;
- }
- public ClassData getClass(String name) {
- if (this.classes!=null)
- for (int i = 0; i < this.classes.length; i++) {
- if (name.equals(this.classes[i].name))
- return this.classes[i];
- }
- return null;
- }
- public Method getGlobalMethod(String name) {
- if (this.globalMethods!=null)
- for (int i = 0; i < this.globalMethods.length; i++) {
- if (name.equals(this.globalMethods[i].name))
- return this.globalMethods[i];
- }
- return null;
- }
- public Enum getEnum(String name) {
- if (this.enums!=null)
- for (int i = 0; i < this.enums.length; i++) {
- if (name.equals(this.enums[i].name))
- return this.enums[i];
- }
- return null;
- }
-
-
-}
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
deleted file mode 100644
index 861188b0..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/MetadataReader.java
+++ /dev/null
@@ -1,880 +0,0 @@
-/*******************************************************************************
- * 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.internal.oaametadata;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.StringReader;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Locale;
-import java.util.Stack;
-
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.parsers.SAXParser;
-import javax.xml.parsers.SAXParserFactory;
-
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-import org.xml.sax.Attributes;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-import org.xml.sax.XMLReader;
-import org.xml.sax.helpers.DefaultHandler;
-
-public class MetadataReader extends DefaultHandler implements IOAAMetaDataConstants
-{
-
- LibraryAPIs apis=new LibraryAPIs();
-
- Stack stack=new Stack();
-
- HashMap states=new HashMap();
-
- boolean collectText=false;
- boolean collectHTML=false;
- boolean pendingEndElement=false;
-
- boolean doTranslation=true;
-
- String collectTextElement;
-
- int currentState=STATE_API;
- Object currentObject;
-
- StringBuffer text=new StringBuffer();
- HashMap collections;
-
- String filePath;
-
- HashMap messages=new HashMap();
-
-
- static class StackElement {
- HashMap collections;
- Object currentObject;
- int state;
-
- StackElement(int st, Object obj, HashMap map)
- {
- this.collections=map;
- this.currentObject=obj;
- this.state=st;
- }
- }
-
- static final int STATE_ABOUTME=1;
- static final int STATE_ALIAS=2;
- static final int STATE_ALAISES=3;
- static final int STATE_ANCESTOR=4;
- static final int STATE_ANCESTORS=5;
- static final int STATE_API=6;
- static final int STATE_AUTHOR=7;
- static final int STATE_AUTHORS=8;
- static final int STATE_AVAILABLE= 9;
- static final int STATE_CONSTRUCTOR=10;
- static final int STATE_CONSTRUCTORS=11;
- static final int STATE_CLASS=12;
- static final int STATE_CLASSES=13;
-
- static final int STATE_DEPRECIATED = 14;
- static final int STATE_DESCRIPTION =15;
- static final int STATE_ENUM =16;
- static final int STATE_ENUMS =17;
- static final int STATE_EVENT =18;
- static final int STATE_EVENTS =19;
- static final int STATE_EXAMPLE =20;
- static final int STATE_EXAMPLES =21;
- static final int STATE_EXCEPTION =22;
- static final int STATE_EXCEPTIONS =23;
- static final int STATE_FIELD =24;
- static final int STATE_FIELDS =25;
- static final int STATE_GLOBALS=26;
- static final int STATE_INTERFACE =27;
- static final int STATE_INTERFACES =28;
- static final int STATE_LICENSE =29;
- static final int STATE_METHOD=30;
- static final int STATE_METHODS =31;
- static final int STATE_MIX =32;
- static final int STATE_MIXES =33;
- static final int STATE_MIXIN =34;
- static final int STATE_MIXINS =35;
- static final int STATE_NAMESPACE =36;
- static final int STATE_NAMESPACES =37;
- static final int STATE_OPTION =38;
- static final int STATE_OPTIONS =39;
- static final int STATE_PARAMETER =40;
- static final int STATE_PARAMETERS =41;
- static final int STATE_PROPERTY=42;
- static final int STATE_PROPERTIES=43;
- static final int STATE_QOUTE =44;
- static final int STATE_REMARKS =45;
- static final int STATE_RETURNS =46;
- static final int STATE_SEEALSO =47;
- static final int STATE_TITLE=48;
- static final int STATE_TOPIC =49;
- static final int STATE_TOPICS =50;
- static final int STATE_USERAGENT =51;
- static final int STATE_USERAGENTS =52;
-
- static final int STATE_INCLUDE =53;
-
- static final ArrayList EMPTY_LIST=new ArrayList();
-
- {
- states.put(TAG_ABOUTME, new Integer(STATE_ABOUTME));
- states.put(TAG_API, new Integer(STATE_API));
- states.put(TAG_AUTHOR, new Integer(STATE_AUTHOR));
- states.put(TAG_AVAILABLE, new Integer(STATE_AVAILABLE));
- states.put(TAG_CLASS, new Integer(STATE_CLASS));
- states.put(TAG_CLASSES, new Integer(STATE_CLASSES));
- states.put(TAG_ENUM, new Integer(STATE_ENUM));
- states.put(TAG_ENUMS, new Integer(STATE_ENUMS));
- states.put(TAG_EXAMPLE, new Integer(STATE_EXAMPLE));
- states.put(TAG_EXAMPLES, new Integer(STATE_EXAMPLES));
- states.put(TAG_GLOBALS, new Integer(STATE_GLOBALS));
- states.put(TAG_METHOD, new Integer(STATE_METHOD));
- states.put(TAG_PROPERTY, new Integer(STATE_PROPERTY));
- states.put(TAG_PROPERTIES, new Integer(STATE_PROPERTIES));
- states.put(TAG_ALIAS, new Integer(STATE_ALIAS));
- states.put(TAG_ALIASES, new Integer(STATE_ALAISES));
- states.put(TAG_ANCESTORS, new Integer(STATE_ANCESTORS));
- states.put(TAG_ANCESTOR, new Integer(STATE_ANCESTOR));
- states.put(TAG_AUTHORS, new Integer(STATE_AUTHORS));
- states.put(TAG_AUTHOR, new Integer(STATE_AUTHOR));
- states.put(TAG_CONSTRUCTORS, new Integer(STATE_CONSTRUCTORS));
- states.put(TAG_CONSTRUCTOR, new Integer(STATE_CONSTRUCTOR));
-
-
- states.put(TAG_DEPRECIATED, new Integer(STATE_DEPRECIATED));
- states.put(TAG_DESCRIPTION, new Integer(STATE_DESCRIPTION ));
- states.put(TAG_ENUM, new Integer(STATE_ENUM ));
- states.put(TAG_EVENT, new Integer(STATE_EVENT ));
- states.put(TAG_EVENTS, new Integer(STATE_EVENTS));
- states.put(TAG_EXAMPLE, new Integer(STATE_EXAMPLE ));
- states.put(TAG_EXAMPLES, new Integer(STATE_EXAMPLES ));
- states.put(TAG_EXCEPTION, new Integer(STATE_EXCEPTION ));
- states.put(TAG_EXCEPTIONS, new Integer(STATE_EXCEPTIONS));
- states.put(TAG_FIELD, new Integer(STATE_FIELD ));
- states.put(TAG_FIELDS, new Integer(STATE_FIELDS ));
- states.put(TAG_INTERFACE, new Integer(STATE_INTERFACE ));
- states.put(TAG_INTERFACES, new Integer(STATE_INTERFACES ));
- states.put(TAG_LICENSE, new Integer(STATE_LICENSE));
- states.put(TAG_METHODS, new Integer(STATE_METHODS ));
- states.put(TAG_MIX, new Integer(STATE_MIX ));
- states.put(TAG_MIXES, new Integer(STATE_MIXES ));
- states.put(TAG_MIXIN, new Integer(STATE_MIXIN));
- states.put(TAG_MIXINS, new Integer(STATE_MIXINS ));
- states.put(TAG_NAMESPACE, new Integer(STATE_NAMESPACE ));
- states.put(TAG_NAMESPACES, new Integer(STATE_NAMESPACES ));
- states.put(TAG_OPTION, new Integer(STATE_OPTION ));
- states.put(TAG_OPTIONS, new Integer(STATE_OPTIONS ));
- states.put(TAG_PARAMETER, new Integer(STATE_PARAMETER ));
- states.put(TAG_PARAMETERS, new Integer(STATE_PARAMETERS ));
- states.put(TAG_QOUTE, new Integer(STATE_QOUTE ));
- states.put(TAG_REMARKS, new Integer(STATE_REMARKS ));
- states.put(TAG_RETURNS, new Integer(STATE_RETURNS ));
- states.put(TAG_SEEALSO, new Integer(STATE_SEEALSO ));
- states.put(TAG_TITLE, new Integer(STATE_TITLE));
- states.put(TAG_TOPIC, new Integer(STATE_TOPIC));
- states.put(TAG_TOPICS, new Integer(STATE_TOPICS ));
- states.put(TAG_USERAGENT, new Integer(STATE_USERAGENT ));
- states.put(TAG_USERAGENTS, new Integer(STATE_USERAGENTS ));
-
- states.put(TAG_INCLUDE, new Integer(STATE_INCLUDE ));
-
- }
-
-
- public static LibraryAPIs readAPIsFromStream(InputSource inputSource, String path) {
-
- MetadataReader handler= new MetadataReader();
- handler.filePath=path;
- handler.loadMessageBundle();
- parseMetadata(inputSource, handler);
- return handler.apis;
- }
-
- private static void parseMetadata(InputSource inputSource,
- MetadataReader handler) {
- try {
- final SAXParserFactory factory= SAXParserFactory.newInstance();
- final SAXParser parser= factory.newSAXParser();
-// parser.setProperty("http://xml.org/sax/features/namespaces", new Boolean(true));
- XMLReader reader=parser.getXMLReader();
- reader.setFeature("http://xml.org/sax/features/namespaces", true);
- parser.parse(inputSource, handler);
- } catch (SAXException e) {
- Util.log(e, "error reading oaametadata");
- } catch (IOException e) {
- Util.log(e, "error reading oaametadata");
- } catch (ParserConfigurationException e) {
- Util.log(e, "error reading oaametadata");
- }
- }
-
- public static LibraryAPIs readAPIsFromString(String metadata, String path) {
- return readAPIsFromStream(new InputSource(new StringReader(metadata)),path);
- }
-
- public static LibraryAPIs readAPIsFromFile(String fileName) {
- try {
- FileInputStream file = new FileInputStream(fileName);
- LibraryAPIs apis= readAPIsFromStream(new InputSource(file),fileName);
- apis.fileName=fileName.toCharArray();
- return apis;
- } catch (FileNotFoundException e) {
- Util.log(e, "error reading oaametadata");
- }
- return null;
- }
-
-
- public void characters(char[] ch, int start, int length)
- throws SAXException {
- if (collectText)
- {
- if (collectHTML && pendingEndElement)
- {
- text.append("/>");
- pendingEndElement=false;
- }
- text.append(ch,start,length);
- }
- }
-
- public void endElement(String uri, String localName, String name)
- throws SAXException {
-
- if (collectText)
- {
- if (NAMESPACE_API.equals(uri)&& localName.equals(collectTextElement))
- {
- switch (this.currentState)
- {
- case STATE_DESCRIPTION:
- {
- if (this.currentObject instanceof DocumentedElement)
- {
- DocumentedElement documentedElement=((DocumentedElement)this.currentObject);
- documentedElement.description=localizedString(this.text.toString());
- documentedElement.isHTMLDescription=this.collectHTML;
- }
- break;
- }
- case STATE_DEPRECIATED:
- case STATE_AVAILABLE:
- {
- if (this.currentObject instanceof DepreciatedOrAvailable)
- {
- ((DepreciatedOrAvailable)this.currentObject).text=localizedString(this.text.toString());
- }
- break;
- }
-
- case STATE_ABOUTME:
- case STATE_QOUTE:
- {
- if (this.currentObject instanceof Author)
- {
- String text=localizedString(this.text.toString());
- Author author=(Author)this.currentObject;
- if (this.currentState==STATE_ABOUTME)
- author.aboutMe=text;
- else
- author.quote=text;
- }
- break;
- }
- }
- popState();
- this.collectText=false;
- this.collectHTML=false;
- this.collectTextElement=null;
- this.text=new StringBuffer();
- }
- else
- {
- if (pendingEndElement)
- text.append("/>");
- else
- text.append("</").append(localName).append(">");
- }
- pendingEndElement=false;
- }
- else
- {
-
- switch (this.currentState)
- {
- case STATE_API:
- {
- ArrayList collection = getCollection(TAG_CLASS);
- this.apis.classes= (ClassData[])collection.toArray(new ClassData[collection.size()]);
- collection = getCollection(TAG_METHOD);
- this.apis.globalMethods= (Method[])collection.toArray(new Method[collection.size()]);
- collection = getCollection(TAG_PROPERTY);
- this.apis.globalVars= (Property[])collection.toArray(new Property[collection.size()]);
- collection = getCollection(TAG_AUTHOR);
- this.apis.authors= (Author[])collection.toArray(new Author[collection.size()]);
- collection = getCollection(TAG_ENUM);
- this.apis.enums= (Enum[])collection.toArray(new Enum[collection.size()]);
- collection = getCollection(TAG_ALIAS);
- this.apis.aliases= (Alias[])collection.toArray(new Alias[collection.size()]);
- collection = getCollection(TAG_MIXIN);
- this.apis.mixins= (Mixin[])collection.toArray(new Mixin[collection.size()]);
- collection = getCollection(TAG_NAMESPACE);
- this.apis.namespaces= (Namespace[])collection.toArray(new Namespace[collection.size()]);
- break;
- }
- case STATE_CLASS:
- case STATE_INTERFACE:
- {
- ClassData clazz=(ClassData)this.currentObject;
- ArrayList collection = getCollection(TAG_ANCESTOR);
- clazz.ancestors= (Ancestor[])collection.toArray(new Ancestor[collection.size()]);
- collection = getCollection(TAG_CONSTRUCTOR);
- clazz.constructors= (Method[])collection.toArray(new Method[collection.size()]);
- collection = getCollection(TAG_EVENT);
- clazz.events= (Event[])collection.toArray(new Event[collection.size()]);
- collection = getCollection(TAG_PROPERTY);
- clazz.properties= (Property[])collection.toArray(new Property[collection.size()]);
- collection = getCollection(TAG_FIELD);
- clazz.fields= (Property[])collection.toArray(new Property[collection.size()]);
- collection = getCollection(TAG_METHOD);
- clazz.methods= (Method[])collection.toArray(new Method[collection.size()]);
- collection = getCollection(TAG_AUTHOR);
- clazz.mixins= (Mix[])collection.toArray(new Mix[collection.size()]);
- collection = getCollection(TAG_ALIAS);
- clazz.aliases= (Alias[])collection.toArray(new Alias[collection.size()]);
- break;
- }
-
- case STATE_CONSTRUCTOR:
- case STATE_METHOD:
- {
- Method method=(Method)this.currentObject;
- ArrayList collection = getCollection(TAG_EXCEPTION);
- method.exceptions= (Exception[])collection.toArray(new Exception[collection.size()]);
- collection = getCollection(TAG_PARAMETER);
- method.parameters= (Parameter[])collection.toArray(new Parameter[collection.size()]);
-
- break;
- }
-
- case STATE_ENUM:
- {
- Enum enumData=(Enum)this.currentObject;
- ArrayList collection = getCollection(TAG_OPTION);
- enumData.options= (Option[])collection.toArray(new Option[collection.size()]);
- break;
- }
-
- case STATE_EVENT:
- {
- Event event=(Event)this.currentObject;
- ArrayList collection = getCollection(TAG_PARAMETER);
- event.parameters= (Parameter[])collection.toArray(new Parameter[collection.size()]);
- break;
- }
-
- case STATE_EXCEPTION:
- {
- Exception exception=(Exception)this.currentObject;
- ArrayList collection = getCollection(TAG_PARAMETER);
- exception.parameters= (Parameter[])collection.toArray(new Parameter[collection.size()]);
- break;
- }
-
- }
- popState();
- }
- }
-
- public void startElement(String uri, String localName, String name,
- Attributes attributes) throws SAXException {
- if (collectText)
- {
- if (collectHTML) {
- text.append("<").append(localName);
- int nAttributes = attributes.getLength();
- for (int i = 0; i < nAttributes; i++) {
- String qname = attributes.getQName(i);
- String value = attributes.getValue(i);
- text.append(" ").append(qname).append("=\"").append(value)
- .append("\"");
- }
- }
- pendingEndElement=true;
- }
- else
- {
- Integer stateObj=null;
- pushState();
- if (NAMESPACE_API.equals(uri))
- {
- stateObj=(Integer)states.get(localName);
- if (stateObj!=null)
- {
- int state=stateObj.intValue();
- switch (state)
- {
-
- case STATE_ABOUTME:
- {
- startCollectingText(localName,attributes);
- break;
- }
-
- case STATE_ALIAS:
- {
- Alias alias=new Alias();
- this.currentObject=alias;
- addCollectionElement(TAG_ALIAS, alias);
- alias.name = attributes.getValue(ATTRIBUTE_ALAIS_NAME);
- alias.datatype = attributes.getValue(ATTRIBUTE_ALAIS_TYPE);
-
- break;
- }
-
- case STATE_ANCESTOR:
- {
- Ancestor ancestor=new Ancestor();
- this.currentObject=ancestor;
- addCollectionElement(TAG_ANCESTOR, ancestor);
- ancestor.dataType = attributes.getValue(ATTRIBUTE_ANCESTOR_DATATYPE);
-
- break;
- }
-
- case STATE_API:
- {
- this.apis.libraryVersion = attributes.getValue(ATTRIBUTE_API_VERSION);
- this.apis.language = attributes.getValue(ATTRIBUTE_API_LANGUAGE);
- this.apis.getterPattern = attributes.getValue(ATTRIBUTE_API_GETTERPATTERN);
- this.apis.setterPattern = attributes.getValue(ATTRIBUTE_API_SETTERPATTERN);
- this.apis.setterPattern = attributes.getValue(ATTRIBUTE_API_SETTERPATTERN);
- this.apis.spec = attributes.getValue(ATTRIBUTE_API_SPEC);
- this.collections=new HashMap();
- break;
- }
-
- case STATE_AUTHOR:
- {
- Author author=new Author();
- this.currentObject=author;
-
- author.email = attributes.getValue(ATTRIBUTE_AUTHOR_EMAIL);
- author.location = attributes.getValue(ATTRIBUTE_AUTHOR_LOCATION);
- author.name = attributes.getValue(ATTRIBUTE_AUTHOR_NAME);
- author.organization = attributes.getValue(ATTRIBUTE_AUTHOR_ORGANIZATION);
- author.photo = attributes.getValue(ATTRIBUTE_AUTHOR_PHOTO);
- author.type = attributes.getValue(ATTRIBUTE_AUTHOR_TYPE);
- author.website = attributes.getValue(ATTRIBUTE_AUTHOR_WEBSITE);
-
- addCollectionElement(TAG_AUTHOR, author);
- break;
- }
-
- case STATE_AVAILABLE:
- {
- DepreciatedOrAvailable available=new DepreciatedOrAvailable();
- if (this.currentObject instanceof VersionableElement)
- ((VersionableElement)this.currentObject).available=available;
- available.version = attributes.getValue(ATTRIBUTE_AVAILABLE_VERSION);
- startCollectingText(localName,attributes);
- break;
- }
-
-
-
- case STATE_CLASS:
- case STATE_INTERFACE:
- {
- ClassData clazz=new ClassData();
- this.currentObject=clazz;
- if (STATE_INTERFACE==state)
- {
- clazz.isInterface=true;
- addCollectionElement(TAG_INTERFACE, clazz);
- }
- else
- addCollectionElement(TAG_CLASS, clazz);
- clazz.name = attributes.getValue(ATTRIBUTE_CLASS_NAME);
- clazz.superclass = attributes.getValue(ATTRIBUTE_CLASS_SUPERCLASS);
- clazz.visibility = attributes.getValue(ATTRIBUTE_CLASS_VISIBILITY);
- clazz.getterPattern = attributes.getValue(ATTRIBUTE_CLASS_GETTERPATTERN);
- clazz.setterPattern = attributes.getValue(ATTRIBUTE_CLASS_SETTERPATTERN);
-
- this.collections=new HashMap();
- break;
- }
-
- case STATE_CONSTRUCTOR:
- case STATE_METHOD:
- {
- Method method=new Method();
- if (STATE_CONSTRUCTOR==state)
- {
- method.isContructor=true;
- addCollectionElement(TAG_CONSTRUCTOR, method);
- }
- else
- addCollectionElement(TAG_METHOD, method);
- this.currentObject=method;
- method.scope = attributes.getValue(ATTRIBUTE_CONSTRUCTOR_SCOPE);
- method.visibility = attributes.getValue(ATTRIBUTE_CONSTRUCTOR_VISIBILITY);
- method.name = attributes.getValue(ATTRIBUTE_METHOD_NAME);
-
- this.collections=new HashMap();
- break;
- }
-
-
- case STATE_DEPRECIATED:
- {
- DepreciatedOrAvailable depreciated=new DepreciatedOrAvailable();
- if (this.currentObject instanceof VersionableElement)
- ((VersionableElement)this.currentObject).depreciated=depreciated;
- depreciated.isDepreciated=true;
- depreciated.version = attributes.getValue(ATTRIBUTE_DEPRECIATED_VERSION);
- startCollectingText(localName,attributes);
- break;
- }
-
- case STATE_DESCRIPTION:
- {
- startCollectingText(localName,attributes);
- break;
- }
-
- case STATE_ENUM:
- {
- Enum enumData =new Enum();
- this.currentObject=enumData;
- addCollectionElement(TAG_ENUM, enumData);
- enumData.name = attributes.getValue(ATTRIBUTE_ENUM_NAME);
- enumData.datatype = attributes.getValue(ATTRIBUTE_ENUM_DATATYPE);
-
- break;
- }
-
- case STATE_EVENT:
- {
- Event event=new Event();
- this.currentObject=event;
- addCollectionElement(TAG_EVENT, event);
-
- this.collections=new HashMap();
- break;
- }
-
- case STATE_EXCEPTION:
- {
- Exception exception=new Exception();
- this.currentObject=exception;
- addCollectionElement(TAG_EXCEPTION, exception);
-
- this.collections=new HashMap();
- break;
- }
-
-
- case STATE_FIELD:
- case STATE_PROPERTY:
- {
- Property property=new Property();
- this.currentObject=property;
- if (STATE_FIELD==state)
- {
- property.isField=true;
- addCollectionElement(TAG_FIELD, property);
- }
- else
- addCollectionElement(TAG_PROPERTY, property);
- property.name = attributes.getValue(ATTRIBUTE_FIELD_NAME);
- property.dataType = attributes.getValue(ATTRIBUTE_FIELD_DATATYPE);
- property.scope = attributes.getValue(ATTRIBUTE_FIELD_SCOPE);
- property.visibility = attributes.getValue(ATTRIBUTE_FIELD_VISIBILITY);
-
- this.collections=new HashMap();
- break;
- }
-
-
- case STATE_INCLUDE:
- {
- String src= attributes.getValue(ATTRIBUTE_INCLUDE_SRC);
- handleInclude(src);
- break;
- }
-
-
- case STATE_MIX:
- {
- Mix mix=new Mix();
- addCollectionElement(TAG_MIX, mix);
- this.currentObject=mix;
- mix.datatype = attributes.getValue(ATTRIBUTE_MIX_DATATYPE);
- mix.fromScope = attributes.getValue(ATTRIBUTE_MIX_FROMSCOPE);
- mix.toScope = attributes.getValue(ATTRIBUTE_MIX_TOSCOPE);
-
- break;
-
- }
-
- case STATE_MIXIN:
- {
- Mixin mixin=new Mixin();
- addCollectionElement(TAG_MIXIN, mixin);
- this.currentObject=mixin;
- mixin.name = attributes.getValue(ATTRIBUTE_MIXIN_NAME);
- mixin.scope = attributes.getValue(ATTRIBUTE_MIXIN_SCOPE);
- mixin.visibility = attributes.getValue(ATTRIBUTE_MIXIN_VISIBILITY);
-
- break;
-
- }
-
- case STATE_NAMESPACE:
- {
- Namespace namespace=new Namespace();
- addCollectionElement(TAG_NAMESPACE, namespace);
- this.currentObject=namespace;
- namespace.name = attributes.getValue(ATTRIBUTE_NAMESPACE_NAME);
- namespace.visibility = attributes.getValue(ATTRIBUTE_NAMESPACE_VISIBILITY);
-
- break;
-
- }
-
- case STATE_PARAMETER:
- {
- Parameter parameter=new Parameter();
- this.currentObject=parameter;
- addCollectionElement(TAG_PARAMETER, parameter);
- parameter.name = attributes.getValue(ATTRIBUTE_PARAMETER_NAME);
- parameter.dataType = attributes.getValue(ATTRIBUTE_PARAMETER_DATATYPE);
- parameter.usage = attributes.getValue(ATTRIBUTE_PARAMETER_USAGE);
-
- this.collections=new HashMap();
- break;
- }
-
- case STATE_QOUTE:
- {
- startCollectingText(localName,attributes);
- break;
- }
-
-
- case STATE_RETURNS:
- {
- ReturnsData returnData =new ReturnsData();
- if (this.currentObject instanceof Method)
- ((Method)this.currentObject).returns=returnData;
- else if (this.currentObject instanceof Event)
- ((Event)this.currentObject).returns=returnData;
- else if (this.currentObject instanceof Exception)
- ((Exception)this.currentObject).returns=returnData;
- this.currentObject=returnData;
- returnData.dataType = attributes.getValue(ATTRIBUTE_RETURNS_DATATYPE);
- break;
- }
-
-
- }
- this.currentState=state;
- }
- }
- }
- }
-
- private void startCollectingText(String localName,Attributes attributes) {
- this.collectText=true;
- this.collectTextElement=localName;
- this.collectHTML=MIME_TYPE_HTML.equals(attributes.getValue(ATTRIBUTE_DESCRIPTION_TYPE));
- this.text=new StringBuffer();
- }
-
- private void addCollectionElement(String tagClass,Object element) {
- if (this.collections==null)
- this.collections=new HashMap();
- ArrayList list = (ArrayList)this.collections.get(tagClass);
- if (list==null)
- {
- this.collections.put(tagClass, list=new ArrayList());
- }
- list.add(element);
- }
-
-
- private ArrayList getCollection(String tagClass) {
- ArrayList list = (ArrayList)this.collections.get(tagClass);
- if (list==null)
- list=EMPTY_LIST;
- return list;
- }
-
- private void popState() {
- StackElement stackElement=(StackElement)stack.pop();
- this.currentState=stackElement.state;
- this.collections=stackElement.collections;
- this.currentObject=stackElement.currentObject;
- }
-
-
- private void pushState() {
- StackElement newElement=new StackElement(this.currentState,this.currentObject, this.collections);
- stack.push(newElement);
- }
-
-
- private String localizedString(String string)
- {
- if (!this.doTranslation)
- return string;
- int subLength=VARIABLE_SUBSTITUTION_STRING.length();
- int index=string.indexOf(VARIABLE_SUBSTITUTION_STRING);
- if (index<0)
- return string;
- StringBuffer text=new StringBuffer();
- int start=0;
- while (index>=0)
- {
- text.append(string.substring(start, index));
- start=index+subLength;
- index=string.indexOf(VARIABLE_SUBSTITUTION_STRING,start);
- if (index<0)
- {
- text.append(string.substring(start-subLength));
- break;
- }
- String key=string.substring(start,index);
- String value=(String)this.messages.get(key);
- String replace=(value!=null)?
- value :
- VARIABLE_SUBSTITUTION_STRING+key+VARIABLE_SUBSTITUTION_STRING;
- text.append(replace);
- start=index+subLength;
- index=string.indexOf(VARIABLE_SUBSTITUTION_STRING,start);
- }
- return text.toString();
-
- }
-
- private void handleInclude(String src)
- {
- IPath basePath = new Path(this.filePath);
- Path srcPath= new Path (src);
- basePath=basePath.removeLastSegments(1);
- basePath=basePath.append(srcPath);
-
- String fileName = basePath.toOSString();
- String savePath=this.filePath;
- try {
- FileInputStream file = new FileInputStream(fileName);
- this.filePath=fileName;
- parseMetadata( new InputSource(file),this);
- } catch (FileNotFoundException e) {
- Util.log(e, "error reading oaametadata");
- }
- this.filePath=savePath;
-
- }
-
- private void loadMessageBundle()
- {
-
- class MessageBundleHandler extends DefaultHandler
- {
- String currentID;
- StringBuffer text;
- public void startElement(String uri, String localName, String name,
- Attributes attributes) throws SAXException {
- if (TAG_MSG.equals(localName))
- {
- currentID = attributes.getValue(ATTRIBUTE_MSG_NAME);
- if (currentID!=null && currentID.length()>0)
- text=new StringBuffer();
- else
- currentID=null;
- }
- }
- public void endElement(String uri, String localName, String name)
- throws SAXException {
- if (currentID!=null)
- {
- messages.put(currentID, text.toString());
- }
- currentID=null;
- text=null;
- }
- public void characters(char[] ch, int start, int length)
- throws SAXException {
- if (currentID!=null && text!=null)
- {
- text.append(ch,start,length);
- }
- }
- }
-
-
- final String[] variants = buildVariants();
- for (int i = 0; i < variants.length; i++) {
- // loader==null if we're launched off the Java boot classpath
- File file = new File(variants[i]);
- if (!file.exists())
- continue;
-
- try {
- InputSource inputSource = new InputSource(new FileReader(file));
- } catch (FileNotFoundException e) {
- Util.log(e, "error reading oaametadata");
- }
- }
-
-
- }
-
- private static final String EXTENSION = ".xml"; //$NON-NLS-1$
- private static final String ALL = "ALL"; //$NON-NLS-1$
- private static String[] nlSuffixes;
-
- private static String[] buildVariants() {
- if (nlSuffixes == null) {
- //build list of suffixes for loading resource bundles
- String nl = Locale.getDefault().toString();
- ArrayList result = new ArrayList(4);
- int lastSeparator;
- String defaultStr="";
- while (true) {
- result.add( nl +defaultStr+ EXTENSION);
- lastSeparator = nl.lastIndexOf('_');
- if (lastSeparator == -1)
- break;
- defaultStr="_"+ALL;
- nl = nl.substring(0, lastSeparator);
- }
- //add the empty suffix last (most general)
- result.add(ALL+"_"+ALL+EXTENSION);
- nlSuffixes = (String[]) result.toArray(new String[result.size()]);
- }
- String[] variants = new String[nlSuffixes.length];
- for (int i = 0; i < variants.length; i++)
- variants[i] = nlSuffixes[i];
- return variants;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/MetadataSourceElementNotifier.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/MetadataSourceElementNotifier.java
deleted file mode 100644
index d05f80d5..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/MetadataSourceElementNotifier.java
+++ /dev/null
@@ -1,154 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.oaametadata;
-
-import org.eclipse.wst.jsdt.internal.compiler.ISourceElementRequestor;
-import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants;
-import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfObject;
-
-public class MetadataSourceElementNotifier {
-
- LibraryAPIs apis;
- ISourceElementRequestor requestor;
- HashtableOfObject notifiedTypes=new HashtableOfObject();
-
- public MetadataSourceElementNotifier(LibraryAPIs apis, ISourceElementRequestor requestor)
- {
- this.requestor=requestor;
- this.apis=apis;
- }
-
- public void notifyRequestor()
- {
- this.requestor.enterCompilationUnit();
- if (this.apis.classes!=null)
- for (int i = 0; i < apis.classes.length; i++) {
- notifySourceElementRequestor(this.apis.classes[i]);
- }
- this.requestor.exitCompilationUnit(0);
- }
-
- public void notifySourceElementRequestor( ClassData clazz ) {
-
- char [] typeName=clazz.name.toCharArray();
- // prevent possible recurrsion
- if (notifiedTypes.containsKey(typeName))
- return;
- notifiedTypes.put(typeName, null);
-
-
- ISourceElementRequestor.TypeInfo typeInfo = new ISourceElementRequestor.TypeInfo();
- typeInfo.declarationStart = 0;
- typeInfo.modifiers = 0;
-
- typeInfo.name = typeName;
-
- typeInfo.nameSourceStart = 0;//type.getNameStart();
- typeInfo.nameSourceEnd = 0;//typeInfo.nameSourceStart+typeInfo.name.length-1;
-
- String superClass=clazz.getSuperClass();
- if (superClass!=null)
- typeInfo.superclass =superClass.toCharArray();
- typeInfo.secondary = false;
-
- typeInfo.anonymousMember = false;
-
- requestor.enterType(typeInfo);
-
- Property[] fields = clazz.getFields();
- for (int attributeInx=0; attributeInx<fields.length; attributeInx++) {
- Property field = fields[attributeInx];
- ISourceElementRequestor.FieldInfo fieldInfo = new ISourceElementRequestor.FieldInfo();
- fieldInfo.declarationStart = 0;//field.sourceStart();
- fieldInfo.name = field.name.toCharArray();
- fieldInfo.modifiers = 0;
-
- if (field.isStatic())
- fieldInfo.modifiers |= ClassFileConstants.AccStatic;
- fieldInfo.nameSourceStart = 0;//field.nameStart;
- fieldInfo.nameSourceEnd = 0;//field.nameStart+field.name.length-1;
-
- fieldInfo.type = field.dataType!=null ? field.dataType.toCharArray():null;
-
-// fieldInfo.annotationPositions = collectAnnotationPositions(fieldDeclaration.annotations);
-// fieldInfo.categories = (char[][]) this.nodesToCategories.get(fieldDeclaration);
- requestor.enterField(fieldInfo);
-
-// //If this field is of an anonymous type, need to notify so that it shows as a child
-// if( field.type != null && field.type.isAnonymous && !field.type.isNamed() ){
-// notifySourceElementRequestor( field.type );
-// }
-
- int initializationStart=0;//field.initializationStart;
- requestor.exitField(initializationStart,0,0/*field.sourceEnd(),field.sourceEnd()*/);
- }
-
- if (clazz.constructors!=null)
- for (int methodInx=0;methodInx<clazz.constructors.length;methodInx++) {
- Method method=clazz.constructors[methodInx];
-
- boolean isConstructor=true;
-
- notifyMethod(method, isConstructor);
-
- }
-
-
- if (clazz.methods!=null)
- for (int methodInx=0;methodInx<clazz.methods.length;methodInx++) {
- Method method=clazz.methods[methodInx];
-
- boolean isConstructor=false;
-
- notifyMethod(method, isConstructor);
-
- }
-
- requestor.exitType(0/*clazz.sourceEnd*/);
-
- }
-
- private void notifyMethod(Method method, boolean isConstructor) {
- ISourceElementRequestor.MethodInfo methodInfo = new ISourceElementRequestor.MethodInfo();
- methodInfo.isConstructor = isConstructor;
- char[][] argumentTypes = null;
- char[][] argumentNames = null;
- Parameter [] arguments = method.parameters;
- if (arguments != null) {
- int argumentLength = arguments.length;
- argumentTypes = new char[argumentLength][];
- argumentNames = new char[argumentLength][];
- for (int i = 0; i < argumentLength; i++) {
- if (arguments[i].dataType!=null)
- argumentTypes[i] = arguments[i].dataType.toCharArray();
- argumentNames[i] = arguments[i].name.toCharArray();
- }
- }
-// int selectorSourceEnd = this.sourceEnds.get(methodDeclaration);
-
- methodInfo.declarationStart = 0;//methodDeclaration.declarationSourceStart;
- methodInfo.modifiers = 0;
- if (method.isStatic())
- methodInfo.modifiers |= ClassFileConstants.AccStatic;
- methodInfo.name =(isConstructor)? new char[0] : method.name.toCharArray();
- methodInfo.nameSourceStart = 0;//method.nameStart;
- methodInfo.nameSourceEnd = 0;//method.nameStart+method.name.length-1;
- methodInfo.parameterTypes = argumentTypes;
- methodInfo.parameterNames = argumentNames;
- methodInfo.categories =null;// (char[][]) this.nodesToCategories.get(methodDeclaration);
- requestor.enterMethod(methodInfo);
-
-
- requestor.exitMethod(0/*methodDeclaration.declarationSourceEnd*/, -1, -1);
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Method.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Method.java
deleted file mode 100644
index 0f0bd721..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Method.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.oaametadata;
-
-public class Method extends VersionableElement {
-
-// method_element = element method {
-// method_content & method_attributes & foreign_nodes
-// }
-// method_content = (
-// exceptions_element? & parameters_element? & returns_element? &
-// descriptive_elements & compatibility_elements
-// # Research the above, make consistent with the spec
-// )
-// method_attributes = (
-// name? & scope? & visibility?
-// )
-
-
- public String scope;
- public String visibility;
- public String name;
-
- public boolean isContructor;
-
- public Exception [] exceptions;
- public Parameter [] parameters;
- public ReturnsData returns;
- public boolean isStatic() {
- return IOAAMetaDataConstants.USAGE_STATIC.equals(scope);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Mix.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Mix.java
deleted file mode 100644
index cb5985e0..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Mix.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.oaametadata;
-
-public class Mix extends DocumentedElement{
-// mix_element = element mix {
-// mix_content & mix_attributes & foreign_nodes
-// }
-// mix_content = (
-// descriptive_elements
-// # Research the above, make consistent with the spec
-// # FIXME: aliases? ancestors?
-// )
-// mix_attributes = (
-// datatype? & fromScope? & toScope?
-// )
-
- String datatype;
- String fromScope;
- String toScope;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Mixin.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Mixin.java
deleted file mode 100644
index 260f351c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Mixin.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.oaametadata;
-
-public class Mixin extends DocumentedElement {
-// mixin_element = element mixin {
-// mixin_content & mixin_attributes & foreign_nodes
-// }
-// mixin_content = (
-// descriptive_elements
-// # Research the above, make consistent with the spec
-// # FIXME: aliases? ancestors?
-// )
-// mixin_attributes = (
-// name? & scope? & visibility?
-// )
-
- public String name;
- public String scope;
- public String visibility;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Namespace.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Namespace.java
deleted file mode 100644
index dfaf575c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Namespace.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.oaametadata;
-
-public class Namespace extends DocumentedElement{
-// namespace_element = element namespace {
-// namespace_content & namespace_attributes & foreign_nodes
-// }
-// namespace_content = (
-// descriptive_elements
-// # Research the above, make consistent with the spec
-// # FIXME: aliases? ancestors?
-// )
-// namespace_attributes = (
-// name & visibility?
-// )
-// )
-
- String name;
- String visibility;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Option.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Option.java
deleted file mode 100644
index 72072423..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Option.java
+++ /dev/null
@@ -1,17 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.oaametadata;
-
-public class Option extends DocumentedElement {
-
- String label;
- String value;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Parameter.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Parameter.java
deleted file mode 100644
index 03a34c75..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Parameter.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.oaametadata;
-
-public class Parameter extends VersionableElement {
-// parameter_element = element parameter {
-// parameter_content & parameter_attributes & foreign_nodes
-// }
-// parameter_content = (
-// options_element? &
-// descriptive_elements & compatibility_elements
-// # Research the above, make consistent with the spec
-// )
-// parameter_attributes = (
-// datatype? & name? & usage? &
-// datatype_supplemental_attributes # FIXME: Is this correct?
-// )
-
-
- public String name;
- public String dataType;
- public String usage;
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Property.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Property.java
deleted file mode 100644
index 89373194..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Property.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.oaametadata;
-
-public class Property extends VersionableElement{
-
-
-// field_element = element field {
-// field_content & field_attributes & foreign_nodes
-// }
-// field_content = (
-// descriptive_elements & compatibility_elements
-// # Research the above, make consistent with the spec
-// )
-// field_attributes = (
-// name? & datatype? & visibility? & scope? &
-// datatype_supplemental_attributes # FIXME: Is this correct?
-// # <scope>?
-// )
-
-// property_element = element property {
-// property_content & property_attributes & foreign_nodes
-// }
-// property_content = (
-// options_element? &
-// descriptive_elements & compatibility_elements
-// )
-// property_attributes = (
-// datatype? & default_attribute? & hidden? & name? & readonly? &
-// required? & scope? & transient? & urlparam & visibility &
-// datatype_supplemental_attributes & pattern_attributes & pubsub_attributes
-// )
-
-
- public String name;
- public String dataType;
- public String visibility;
- public String scope;
- public boolean isField;
-
- public boolean isStatic()
- {
- return IOAAMetaDataConstants.USAGE_STATIC.equals(scope);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/ReturnsData.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/ReturnsData.java
deleted file mode 100644
index 02f5b94b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/ReturnsData.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.oaametadata;
-
-public class ReturnsData extends DocumentedElement {
-// returns_element = element returns {
-// returns_content & returns_attributes & foreign_nodes
-// }
-// returns_content = (
-// descriptive_elements
-// # Research the above, make consistent with the spec
-// )
-// returns_attributes = (
-// datatype? &
-// datatype_supplemental_attributes # FIXME: Is this correct?
-// )
-
-
- public String dataType;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/VersionableElement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/VersionableElement.java
deleted file mode 100644
index ccc6b2df..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/VersionableElement.java
+++ /dev/null
@@ -1,18 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.oaametadata;
-
-public class VersionableElement extends DocumentedElement{
-
- public DepreciatedOrAvailable depreciated;
- public DepreciatedOrAvailable available;
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/AbstractVMInstall.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/AbstractVMInstall.java
deleted file mode 100644
index 0a4b7b94..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/AbstractVMInstall.java
+++ /dev/null
@@ -1,472 +0,0 @@
-/*******************************************************************************
- * 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.launching;
-
-
-import java.io.File;
-import java.net.URL;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-/**
- * Abstract implementation of a VM install.
- * <p>
- * Clients implementing VM installs must subclass this class.
- * </p>
- *
- * 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 AbstractVMInstall implements IVMInstall, IVMInstall2, IVMInstall3 {
-
- private IVMInstallType fType;
- private String fId;
- private String fName;
- private File fInstallLocation;
- private LibraryLocation[] fSystemLibraryDescriptions;
- private URL fJavadocLocation;
- private String fVMArgs;
- // system properties are cached in user preferences prefixed with this key, followed
- // by vm type, vm id, and system property name
-// private static final String PREF_VM_INSTALL_SYSTEM_PROPERTY = "PREF_VM_INSTALL_SYSTEM_PROPERTY"; //$NON-NLS-1$
- // whether change events should be fired
- private boolean fNotify = true;
-
- /**
- * Constructs a new VM install.
- *
- * @param type The type of this VM install.
- * Must not be <code>null</code>
- * @param id The unique identifier of this VM instance
- * Must not be <code>null</code>.
- * @throws IllegalArgumentException if any of the required
- * parameters are <code>null</code>.
- */
- public AbstractVMInstall(IVMInstallType type, String id) {
- if (type == null)
- throw new IllegalArgumentException(LaunchingMessages.vmInstall_assert_typeNotNull);
- if (id == null)
- throw new IllegalArgumentException(LaunchingMessages.vmInstall_assert_idNotNull);
- fType= type;
- fId= id;
- }
-
- /* (non-Javadoc)
- * Subclasses should not override this method.
- * @see IVMInstall#getId()
- */
- public String getId() {
- return fId;
- }
-
- /* (non-Javadoc)
- * Subclasses should not override this method.
- * @see IVMInstall#getName()
- */
- public String getName() {
- return fName;
- }
-
- /* (non-Javadoc)
- * Subclasses should not override this method.
- * @see IVMInstall#setName(String)
- */
- public void setName(String name) {
- if (!name.equals(fName)) {
- PropertyChangeEvent event = new PropertyChangeEvent(this, IVMInstallChangedListener.PROPERTY_NAME, fName, name);
- fName= name;
- if (fNotify) {
- JavaRuntime.fireVMChanged(event);
- }
- }
- }
-
- /* (non-Javadoc)
- * Subclasses should not override this method.
- * @see IVMInstall#getInstallLocation()
- */
- public File getInstallLocation() {
- return fInstallLocation;
- }
-
- /* (non-Javadoc)
- * Subclasses should not override this method.
- * @see IVMInstall#setInstallLocation(File)
- */
- public void setInstallLocation(File installLocation) {
- if (!installLocation.equals(fInstallLocation)) {
- PropertyChangeEvent event = new PropertyChangeEvent(this, IVMInstallChangedListener.PROPERTY_INSTALL_LOCATION, fInstallLocation, installLocation);
- fInstallLocation= installLocation;
- if (fNotify) {
- JavaRuntime.fireVMChanged(event);
- }
- }
- }
-
- /* (non-Javadoc)
- * Subclasses should not override this method.
- * @see IVMInstall#getVMInstallType()
- */
- public IVMInstallType getVMInstallType() {
- return fType;
- }
-
- /* (non-Javadoc)
- * @see IVMInstall#getVMRunner(String)
- */
- public IVMRunner getVMRunner(String mode) {
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.launching.IVMInstall#getLibraryLocations()
- */
- public LibraryLocation[] getLibraryLocations() {
- return fSystemLibraryDescriptions;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.launching.IVMInstall#setLibraryLocations(org.eclipse.wst.jsdt.launching.LibraryLocation[])
- */
- public void setLibraryLocations(LibraryLocation[] locations) {
- if (locations == fSystemLibraryDescriptions) {
- return;
- }
- LibraryLocation[] newLocations = locations;
- if (newLocations == null) {
- newLocations = getVMInstallType().getDefaultLibraryLocations(getInstallLocation());
- }
- LibraryLocation[] prevLocations = fSystemLibraryDescriptions;
- if (prevLocations == null) {
- prevLocations = getVMInstallType().getDefaultLibraryLocations(getInstallLocation());
- }
-
- if (newLocations.length == prevLocations.length) {
- int i = 0;
- boolean equal = true;
- while (i < newLocations.length && equal) {
- equal = newLocations[i].equals(prevLocations[i]);
- i++;
- }
- if (equal) {
- // no change
- return;
- }
- }
-
- PropertyChangeEvent event = new PropertyChangeEvent(this, IVMInstallChangedListener.PROPERTY_LIBRARY_LOCATIONS, prevLocations, newLocations);
- fSystemLibraryDescriptions = locations;
- if (fNotify) {
- JavaRuntime.fireVMChanged(event);
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.launching.IVMInstall#getJavadocLocation()
- */
- public URL getJavadocLocation() {
- return fJavadocLocation;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.launching.IVMInstall#setJavadocLocation(java.net.URL)
- */
- public void setJavadocLocation(URL url) {
- if (url == fJavadocLocation) {
- return;
- }
- if (url != null && fJavadocLocation != null) {
- if (url.equals(fJavadocLocation)) {
- // no change
- return;
- }
- }
-
- PropertyChangeEvent event = new PropertyChangeEvent(this, IVMInstallChangedListener.PROPERTY_JAVADOC_LOCATION, fJavadocLocation, url);
- fJavadocLocation = url;
- if (fNotify) {
- JavaRuntime.fireVMChanged(event);
- }
- }
-
- /**
- * Whether this VM should fire property change notifications.
- *
- * @param notify
- *
- */
- protected void setNotify(boolean notify) {
- fNotify = notify;
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#equals(java.lang.Object)
- *
- */
- public boolean equals(Object object) {
- if (object instanceof IVMInstall) {
- IVMInstall vm = (IVMInstall)object;
- return getVMInstallType().equals(vm.getVMInstallType()) &&
- getId().equals(vm.getId());
- }
- return false;
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#hashCode()
- *
- */
- public int hashCode() {
- return getVMInstallType().hashCode() + getId().hashCode();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.launching.IVMInstall#getDefaultVMArguments()
- *
- */
- public String[] getVMArguments() {
- String args = getVMArgs();
- if (args == null) {
- return null;
- }
- ExecutionArguments ex = new ExecutionArguments(args, ""); //$NON-NLS-1$
- return ex.getVMArgumentsArray();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.launching.IVMInstall#setDefaultVMArguments(java.lang.String[])
- *
- */
- public void setVMArguments(String[] vmArgs) {
- if (vmArgs == null) {
- setVMArgs(null);
- } else {
- StringBuffer buf = new StringBuffer();
- for (int i = 0; i < vmArgs.length; i++) {
- String string = vmArgs[i];
- buf.append(string);
- buf.append(" "); //$NON-NLS-1$
- }
- setVMArgs(buf.toString().trim());
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.launching.IVMInstall2#getVMArgs()
- */
- public String getVMArgs() {
- return fVMArgs;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.launching.IVMInstall2#setVMArgs(java.lang.String)
- */
- public void setVMArgs(String vmArgs) {
- if (fVMArgs == null) {
- if (vmArgs == null) {
- // No change
- return;
- }
- } else if (fVMArgs.equals(vmArgs)) {
- // No change
- return;
- }
- PropertyChangeEvent event = new PropertyChangeEvent(this, IVMInstallChangedListener.PROPERTY_VM_ARGUMENTS, fVMArgs, vmArgs);
- fVMArgs = vmArgs;
- if (fNotify) {
- JavaRuntime.fireVMChanged(event);
- }
- }
-
- /* (non-Javadoc)
- * Subclasses should override.
- * @see org.eclipse.wst.jsdt.launching.IVMInstall2#getJavaVersion()
- */
- public String getJavaVersion() {
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.launching.IVMInstall3#evaluateSystemProperties(java.lang.String[], org.eclipse.core.runtime.IProgressMonitor)
- */
-
-// JSDT never called
-// public Map evaluateSystemProperties(String[] properties, IProgressMonitor monitor) throws CoreException {
-// //locate the launching support jar - it contains the main program to run
-// if (monitor == null) {
-// monitor = new NullProgressMonitor();
-// }
-// Map map = new HashMap();
-//
-// // first check cache (preference store) to avoid launching VM
-// Preferences preferences = JavaRuntime.getPreferences();
-// boolean cached = true;
-// for (int i = 0; i < properties.length; i++) {
-// String property = properties[i];
-// String key = getSystemPropertyKey(property);
-// if (preferences.contains(key)) {
-// String value = preferences.getString(key);
-// map.put(property, value);
-// } else {
-// map.clear();
-// cached = false;
-// break;
-// }
-// }
-// if (!cached) {
-// // launch VM to evaluate properties
-// File file = LaunchingPlugin.getFileInPlugin(new Path("lib/launchingsupport.jar")); //$NON-NLS-1$
-// if (file.exists()) {
-// String javaVersion = getJavaVersion();
-// boolean hasXMLSupport = false;
-// if (javaVersion != null) {
-// hasXMLSupport = true;
-// if (javaVersion.startsWith(JavaScriptCore.VERSION_1_1) ||
-// javaVersion.startsWith(JavaScriptCore.VERSION_1_2) ||
-// javaVersion.startsWith(JavaScriptCore.VERSION_1_3)) {
-// hasXMLSupport = false;
-// }
-// }
-// String mainType = null;
-// if (hasXMLSupport) {
-// mainType = "org.eclipse.wst.jsdt.internal.launching.support.SystemProperties"; //$NON-NLS-1$
-// } else {
-// mainType = "org.eclipse.wst.jsdt.internal.launching.support.LegacySystemProperties"; //$NON-NLS-1$
-// }
-// VMRunnerConfiguration config = new VMRunnerConfiguration(mainType, new String[]{file.getAbsolutePath()});
-// IVMRunner runner = getVMRunner(ILaunchManager.RUN_MODE);
-// if (runner == null) {
-// abort(LaunchingMessages.AbstractVMInstall_0, null, IJavaLaunchConfigurationConstants.ERR_INTERNAL_ERROR);
-// }
-// config.setProgramArguments(properties);
-// Launch launch = new Launch(null, ILaunchManager.RUN_MODE, null);
-// if (monitor.isCanceled()) {
-// return map;
-// }
-// monitor.beginTask(LaunchingMessages.AbstractVMInstall_1, 2);
-// runner.run(config, launch, monitor);
-// IProcess[] processes = launch.getProcesses();
-// if (processes.length != 1) {
-// abort(LaunchingMessages.AbstractVMInstall_0, null, IJavaLaunchConfigurationConstants.ERR_INTERNAL_ERROR);
-// }
-// IProcess process = processes[0];
-// try {
-// int total = 0;
-// int max = JavaRuntime.getPreferences().getInt(JavaRuntime.PREF_CONNECT_TIMEOUT);
-// while (!process.isTerminated()) {
-// try {
-// if (total > max) {
-// break;
-// }
-// Thread.sleep(50);
-// total+=50;
-// } catch (InterruptedException e) {
-// }
-// }
-// } finally {
-// if (!launch.isTerminated()) {
-// launch.terminate();
-// }
-// }
-// monitor.worked(1);
-// if (monitor.isCanceled()) {
-// return map;
-// }
-//
-// monitor.subTask(LaunchingMessages.AbstractVMInstall_3);
-// IStreamsProxy streamsProxy = process.getStreamsProxy();
-// String text = null;
-// if (streamsProxy != null) {
-// text = streamsProxy.getOutputStreamMonitor().getContents();
-// }
-// if (text != null && text.length() > 0) {
-// try {
-// DocumentBuilder parser = LaunchingPlugin.getParser();
-// Document document = parser.parse(new ByteArrayInputStream(text.getBytes()));
-// Element envs = document.getDocumentElement();
-// NodeList list = envs.getChildNodes();
-// int length = list.getLength();
-// for (int i = 0; i < length; ++i) {
-// Node node = list.item(i);
-// short type = node.getNodeType();
-// if (type == Node.ELEMENT_NODE) {
-// Element element = (Element) node;
-// if (element.getNodeName().equals("property")) { //$NON-NLS-1$
-// String name = element.getAttribute("name"); //$NON-NLS-1$
-// String value = element.getAttribute("value"); //$NON-NLS-1$
-// map.put(name, value);
-// }
-// }
-// }
-// } catch (SAXException e) {
-// abort(LaunchingMessages.AbstractVMInstall_4, e, IJavaLaunchConfigurationConstants.ERR_INTERNAL_ERROR);
-// } catch (IOException e) {
-// abort(LaunchingMessages.AbstractVMInstall_4, e, IJavaLaunchConfigurationConstants.ERR_INTERNAL_ERROR);
-// }
-// } else {
-// abort(LaunchingMessages.AbstractVMInstall_0, null, IJavaLaunchConfigurationConstants.ERR_INTERNAL_ERROR);
-// }
-// monitor.worked(1);
-// } else {
-// abort(LaunchingMessages.AbstractVMInstall_0, null, IJavaLaunchConfigurationConstants.ERR_INTERNAL_ERROR);
-// }
-// // cache for future reference
-// Iterator keys = map.keySet().iterator();
-// while (keys.hasNext()) {
-// String property = (String)keys.next();
-// String value = (String) map.get(property);
-// String key = getSystemPropertyKey(property);
-// preferences.setValue(key, value);
-// }
-// }
-// monitor.done();
-// return map;
-// }
-
- /**
- * Generates a key used to cache system property for this VM in this plug-ins
- * preference store.
- *
- * @param property system property name
- * @return preference store key
- */
-// private String getSystemPropertyKey(String property) {
-// StringBuffer buffer = new StringBuffer();
-// buffer.append(PREF_VM_INSTALL_SYSTEM_PROPERTY);
-// buffer.append("."); //$NON-NLS-1$
-// buffer.append(getVMInstallType().getId());
-// buffer.append("."); //$NON-NLS-1$
-// buffer.append(getId());
-// buffer.append("."); //$NON-NLS-1$
-// buffer.append(property);
-// return buffer.toString();
-// }
-
- /**
- * Throws a core exception with an error status object built from the given
- * message, lower level exception, and error code.
- *
- * @param message the status message
- * @param exception lower level exception associated with the error, or
- * <code>null</code> if none
- * @param code error code
- * @throws CoreException the "abort" core exception
- *
- */
- protected void abort(String message, Throwable exception, int code) throws CoreException {
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, code, message, exception));
- }
-
-}
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
deleted file mode 100644
index 23e3344b..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/AbstractVMInstallType.java
+++ /dev/null
@@ -1,177 +0,0 @@
-/*******************************************************************************
- * 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.launching;
-
-
-import java.io.File;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IExecutableExtension;
-
-import com.ibm.icu.text.MessageFormat;
-
-/**
- * Abstract implementation of a VM install type.
- * Subclasses should implement
- * <ul>
- * <li><code>IVMInstall doCreateVMInstall(String id)</code></li>
- * <li><code>String getName()</code></li>
- * <li><code>IStatus validateInstallLocation(File installLocation)</code></li>
- * </ul>
- * <p>
- * Clients implementing VM install types should subclass this class.
- * </p>
- *
- * 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 AbstractVMInstallType implements IVMInstallType, IExecutableExtension {
- private List fVMs;
- private String fId;
-
- /**
- * Constructs a new VM install type.
- */
- protected AbstractVMInstallType() {
- fVMs= new ArrayList(10);
- }
-
- /* (non-Javadoc)
- * Subclasses should not override this method.
- * @see IVMType#getVMs()
- */
- public IVMInstall[] getVMInstalls() {
- IVMInstall[] vms= new IVMInstall[fVMs.size()];
- return (IVMInstall[])fVMs.toArray(vms);
- }
-
- /* (non-Javadoc)
- * Subclasses should not override this method.
- * @see IVMType#disposeVM(String)
- */
- public void disposeVMInstall(String id) {
- for (int i= 0; i < fVMs.size(); i++) {
- IVMInstall vm= (IVMInstall)fVMs.get(i);
- if (vm.getId().equals(id)) {
- fVMs.remove(i);
- JavaRuntime.fireVMRemoved(vm);
- return;
- }
- }
- }
-
- /* (non-Javadoc)
- * Subclasses should not override this method.
- * @see IVMType#getVM(String)
- */
- public IVMInstall findVMInstall(String id) {
- for (int i= 0; i < fVMs.size(); i++) {
- IVMInstall vm= (IVMInstall)fVMs.get(i);
- if (vm.getId().equals(id)) {
- return vm;
- }
- }
- return null;
- }
-
- /* (non-Javadoc)
- * Subclasses should not override this method.
- * @see IVMType#createVM(String)
- */
- public IVMInstall createVMInstall(String id) throws IllegalArgumentException {
- if (findVMInstall(id) != null) {
- String format= LaunchingMessages.vmInstallType_duplicateVM;
- throw new IllegalArgumentException(MessageFormat.format(format, new String[] { id }));
- }
- IVMInstall vm= doCreateVMInstall(id);
- fVMs.add(vm);
- return vm;
- }
-
- /**
- * Subclasses should return a new instance of the appropriate
- * <code>IVMInstall</code> subclass from this method.
- * @param id The vm's id. The <code>IVMInstall</code> instance that is created must
- * return <code>id</code> from its <code>getId()</code> method.
- * Must not be <code>null</code>.
- * @return the newly created IVMInstall instance. Must not return <code>null</code>.
- */
- protected abstract IVMInstall doCreateVMInstall(String id);
-
- /* (non-Javadoc)
- * @see org.eclipse.core.runtime.IExecutableExtension#setInitializationData(org.eclipse.core.runtime.IConfigurationElement, java.lang.String, java.lang.Object)
- */
- /**
- * Initializes the id parameter from the "id" attribute
- * in the configuration markup.
- * Subclasses should not override this method.
- * @param config the configuration element used to trigger this execution.
- * It can be queried by the executable extension for specific
- * configuration properties
- * @param propertyName the name of an attribute of the configuration element
- * used on the <code>createExecutableExtension(String)</code> call. This
- * argument can be used in the cases where a single configuration element
- * is used to define multiple executable extensions.
- * @param data adapter data in the form of a <code>String</code>,
- * a <code>Hashtable</code>, or <code>null</code>.
- * @see org.eclipse.core.runtime.IExecutableExtension#setInitializationData(org.eclipse.core.runtime.IConfigurationElement, java.lang.String, java.lang.Object)
- */
- public void setInitializationData(IConfigurationElement config, String propertyName, Object data) {
- fId= config.getAttribute("id"); //$NON-NLS-1$
- }
-
- /* (non-Javadoc)
- * Subclasses should not override this method.
- * @see IVMType#getId()
- */
- public String getId() {
- return fId;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jdt.launching.IVMInstallType#findVMInstallByName(java.lang.String)
- */
- public IVMInstall findVMInstallByName(String name) {
- for (int i= 0; i < fVMs.size(); i++) {
- IVMInstall vm= (IVMInstall)fVMs.get(i);
- if (vm.getName().equals(name)) {
- return vm;
- }
- }
- return null;
- }
-
- /**
- * Returns a URL for the default jsdoc location of a VM installed at the
- * given home location, or <code>null</code> if none. The default
- * implementation returns <code>null</code>, subclasses must override as
- * appropriate.
- * <p>
- * Note, this method would ideally be added to <code>IVMInstallType</code>,
- * but it would have been a breaking API change between 2.0 and 2.1. Thus,
- * it has been added to the abstract base class that VM install types should
- * subclass.
- * </p>
- *
- * @param installLocation home location
- * @return default jsdoc location or <code>null</code>
- *
- */
- public URL getDefaultJavadocLocation(File installLocation) {
- return null;
- }
-}
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
deleted file mode 100644
index d839bc59..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/ExecutionArguments.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*******************************************************************************
- * 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.launching;
-
-
-import org.eclipse.debug.core.DebugPlugin;
-
-/**
- * The execution arguments for running a JavaScript VM. The execution arguments are
- * separated into two parts: arguments to the VM itself, and arguments to the JavaScript
- * main program. This class provides convenience methods for parsing a string
- * of arguments into separate components.
- * <p>
- * Clients may instantiate this class; it is not intended to be subclassed.
- * </p>
- *
- * 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 ExecutionArguments {
- private String fVMArgs;
- private String fProgramArgs;
-
- /**
- * Creates a new execution arguments object.
- *
- * @param vmArgs command line argument string passed to the VM
- * @param programArgs command line argument string passed to the program
- */
- public ExecutionArguments(String vmArgs, String programArgs) {
- if (vmArgs == null || programArgs == null)
- throw new IllegalArgumentException();
- fVMArgs= vmArgs;
- fProgramArgs= programArgs;
- }
-
- /**
- * Returns the VM arguments as one string.
- *
- * @return the VM arguments as one string
- */
- public String getVMArguments() {
- return fVMArgs;
- }
-
- /**
- * Returns the program arguments as one string.
- *
- * @return the program arguments as one string
- */
- public String getProgramArguments() {
- return fProgramArgs;
- }
-
- /**
- * Returns the VM arguments as an array of individual arguments.
- *
- * @return the VM arguments as an array of individual arguments
- */
- public String[] getVMArgumentsArray() {
- return DebugPlugin.parseArguments(fVMArgs);
- }
-
- /**
- * Returns the program arguments as an array of individual arguments.
- *
- * @return the program arguments as an array of individual arguments
- */
- public String[] getProgramArgumentsArray() {
- return DebugPlugin.parseArguments(fProgramArgs);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IJavaLaunchConfigurationConstants.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IJavaLaunchConfigurationConstants.java
deleted file mode 100644
index 81964729..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IJavaLaunchConfigurationConstants.java
+++ /dev/null
@@ -1,495 +0,0 @@
-/*******************************************************************************
- * 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.launching;
-
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-
-
-/**
- * Constant definitions for JavaScript launch configurations.
- * <p>
- * Constant definitions only; not to be implemented.
- * </p>
- *
- * 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 IJavaLaunchConfigurationConstants {
-
- /**
- * Identifier for the Local JavaScript Application launch configuration type
- * (value <code>"org.eclipse.wst.jsdt.launching.localJavaApplication"</code>).
- */
- public static final String ID_JAVA_APPLICATION = JavaScriptCore.PLUGIN_ID + ".localJavaApplication"; //$NON-NLS-1$
-
- /**
- * Identifier for the Remote JavaScript Application launch configuration type
- * (value <code>"org.eclipse.wst.jsdt.launching.remoteJavaApplication"</code>).
- */
- public static final String ID_REMOTE_JAVA_APPLICATION = JavaScriptCore.PLUGIN_ID + ".remoteJavaApplication"; //$NON-NLS-1$
-
- /**
- * Identifier for the JavaScript Applet launch configuration type
- * (value <code>"org.eclipse.wst.jsdt.launching.javaApplet"</code>).
- */
- public static final String ID_JAVA_APPLET = JavaScriptCore.PLUGIN_ID + ".javaApplet"; //$NON-NLS-1$
-
- /**
- * Identifier for the standard Socket Attaching VM connector
- * (value <code>"org.eclipse.wst.jsdt.launching.socketAttachConnector"</code>).
- */
- public static final String ID_SOCKET_ATTACH_VM_CONNECTOR = JavaScriptCore.PLUGIN_ID + ".socketAttachConnector"; //$NON-NLS-1$
-
- /**
- * Identifier for the javascript process type, which is annotated on processes created
- * by the local javascript application launch delegate.
- *
- * (value <code>"java"</code>).
- */
- public static final String ID_JAVA_PROCESS_TYPE = "java"; //$NON-NLS-1$
-
- /**
- * Launch configuration attribute key. The value is a name of
- * a JavaScript project associated with a JavaScript launch configuration.
- */
- public static final String ATTR_PROJECT_NAME = JavaScriptCore.PLUGIN_ID + ".PROJECT_ATTR"; //$NON-NLS-1$
-
- /**
- * Launch configuration attribute key. The value is a fully qualified name
- * of a main type to launch.
- */
- public static final String ATTR_MAIN_TYPE_NAME = JavaScriptCore.PLUGIN_ID + ".MAIN_TYPE"; //$NON-NLS-1$
-
- /**
- * Launch configuration attribute key. The value is a boolean specifying
- * whether execution should stop when main is entered. The default value
- * is <code>false</code>.
- *
- *
- */
- public static final String ATTR_STOP_IN_MAIN = JavaScriptCore.PLUGIN_ID + ".STOP_IN_MAIN"; //$NON-NLS-1$
-
- /**
- * Launch configuration attribute key. The value is a string specifying
- * program arguments for a JavaScript launch configuration, as they should appear
- * on the command line.
- */
- public static final String ATTR_PROGRAM_ARGUMENTS = JavaScriptCore.PLUGIN_ID + ".PROGRAM_ARGUMENTS"; //$NON-NLS-1$
-
- /**
- * Launch configuration attribute key. The value is a string specifying
- * VM arguments for a JavaScript launch configuration, as they should appear
- * on the command line.
- */
- public static final String ATTR_VM_ARGUMENTS = JavaScriptCore.PLUGIN_ID + ".VM_ARGUMENTS"; //$NON-NLS-1$
-
- /**
- * Launch configuration attribute key. The value is a string specifying a
- * path to the working directory to use when launching a local VM.
- * When specified as an absolute path, the path represents a path in the local
- * file system. When specified as a full path, the path represents a workspace
- * relative path. When unspecified, the working directory defaults to the project
- * associated with a launch configuration. When no project is associated with a
- * launch configuration, the working directory is inherited from the current
- * process.
- */
- public static final String ATTR_WORKING_DIRECTORY = JavaScriptCore.PLUGIN_ID + ".WORKING_DIRECTORY"; //$NON-NLS-1$
-
- /**
- * Launch configuration attribute key. The value is a path identifying the JRE used
- * when launching a local VM. The path is a includepath container corresponding
- * to the <code>JavaRuntime.JRE_CONTAINER</code> includepath container.
- * <p>
- * When unspecified the default JRE for a launch configuration is used (which is the
- * JRE associated with the project being launched, or the workspace default JRE when
- * no project is associated with a configuration). The default JRE includepath container
- * refers explicitly to the workspace default JRE.
- * </p>
- *
- */
- public static final String ATTR_JRE_CONTAINER_PATH = JavaRuntime.JRE_CONTAINER;
-
- /**
- * Launch configuration attribute key. The value is a name of a VM install
- * to use when launching a local VM. This attribute must be qualified
- * by a VM install type, via the <code>ATTR_VM_INSTALL_TYPE</code>
- * attribute. When unspecified, the default VM is used.
- *
- * @deprecated use <code>ATTR_JRE_CONTAINER_PATH</code>
- */
- public static final String ATTR_VM_INSTALL_NAME = JavaScriptCore.PLUGIN_ID + ".VM_INSTALL_NAME"; //$NON-NLS-1$
-
- /**
- * Launch configuration attribute key. The value is an identifier of
- * a VM install type. Used in conjunction with a VM install name, to
- * specify the VM to use when launching a local JavaScript application.
- * The associated VM install name is specified via the attribute
- * <code>ATTR_VM_INSTALL_NAME</code>.
- *
- * @deprecated use <code>ATTR_JRE_CONTAINER_PATH</code>
- */
- public static final String ATTR_VM_INSTALL_TYPE = JavaScriptCore.PLUGIN_ID + ".VM_INSTALL_TYPE_ID"; //$NON-NLS-1$
-
- /**
- * Launch configuration attribute key. The value is a Map of attributes specific
- * to a particular VM install type, used when launching a local Java
- * application. The map is passed to a <code>VMRunner</code> via a <code>VMRunnerConfiguration</code>
- * when launching a VM. The attributes in the map are implementation dependent
- * and are limited to String keys and values.
- */
- public static final String ATTR_VM_INSTALL_TYPE_SPECIFIC_ATTRS_MAP = JavaScriptCore.PLUGIN_ID + "VM_INSTALL_TYPE_SPECIFIC_ATTRS_MAP"; //$NON-NLS-1$
-
- /**
- * Launch configuration attribute key. The value is an identifier of
- * a VM connector, specifying a connector to use when attaching to
- * a remote VM.
- */
- public static final String ATTR_VM_CONNECTOR= JavaScriptCore.PLUGIN_ID + ".VM_CONNECTOR_ID"; //$NON-NLS-1$
-
- /**
- * Launch configuration attribute key. The attribute value is an ordered list of strings
- * which are mementos for runtime class path entries. When unspecified, a default
- * includepath is generated by the includepath provider associated with a launch
- * configuration (via the <code>ATTR_CLASSPATH_PROVIDER</code> attribute).
- */
- public static final String ATTR_CLASSPATH = JavaScriptCore.PLUGIN_ID + ".CLASSPATH"; //$NON-NLS-1$
-
- /**
- * Launch configuration attribute key. The value is a boolean specifying
- * whether a default includepath should be used when launching a local
- * JavaScript application. When <code>false</code>, a includepath must be specified
- * via the <code>ATTR_CLASSPATH</code> attribute. When <code>true</code> or
- * unspecified, a includepath is computed by the includepath provider associated
- * with a launch configuration.
- */
- public static final String ATTR_DEFAULT_CLASSPATH = JavaScriptCore.PLUGIN_ID + ".DEFAULT_CLASSPATH"; //$NON-NLS-1$
-
- /**
- * Launch configuration attribute key. The value is an identifier of a
- * includepath provider extension used to compute the includepath
- * for a launch configuration. When unspecified, the default includepath
- * provider is used - <code>StandardClasspathProvider</code>.
- */
- public static final String ATTR_CLASSPATH_PROVIDER = JavaScriptCore.PLUGIN_ID + ".CLASSPATH_PROVIDER"; //$NON-NLS-1$
-
- /**
- * Launch configuration attribute key. The value is an ordered list of
- * strings which are mementos for associated runtime includepath entries
- * interpreted as locations in which to look for source code. When unspecified,
- * a default source lookup path is generated by the source path provider
- * associated with a launch configurations (via the
- * <code>ATTR_SOURCE_PATH_PROVIDER</code> attribute).
- */
- public static final String ATTR_SOURCE_PATH = JavaScriptCore.PLUGIN_ID + ".SOURCE_PATH"; //$NON-NLS-1$
-
- /**
- * Launch configuration attribute key. The value is a boolean specifying
- * whether a default source lookup path should be used. When
- * <code>false</code> a source path must be specified via the
- * <code>ATTR_SOURCE_PATH</code> attribute. When <code>true</code> or
- * unspecified, a source lookup path is computed by the source path
- * provider associated with a launch configuration.
- */
- public static final String ATTR_DEFAULT_SOURCE_PATH = JavaScriptCore.PLUGIN_ID + ".DEFAULT_SOURCE_PATH"; //$NON-NLS-1$
-
- /**
- * Launch configuration attribute key. The value is an identifier of a
- * source path provider extension used to compute the source lookup path
- * for a launch configuration. When unspecified, the default source lookup
- * path provider is used - <code>StandardSourcePathProvider</code>.
- */
- public static final String ATTR_SOURCE_PATH_PROVIDER = JavaScriptCore.PLUGIN_ID + ".SOURCE_PATH_PROVIDER"; //$NON-NLS-1$
-
- /**
- * Launch configuration attribute key. The value is a boolean, indicating
- * whether a VM will support/allow the terminate action.
- * This attribute is used for remote debugging.
- */
- public static final String ATTR_ALLOW_TERMINATE = JavaScriptCore.PLUGIN_ID + ".ALLOW_TERMINATE"; //$NON-NLS-1$
-
- /**
- * Attribute key for VM specific attributes found in the
- * <code>ATTR_VM_INSTALL_TYPE_SPECIFIC_ATTRS_MAP</code>. The value is a String,
- * indicating the String to use to invoke the JRE.
- */
- public static final String ATTR_JAVA_COMMAND = JavaScriptCore.PLUGIN_ID + ".JAVA_COMMAND"; //$NON-NLS-1$
-
- /**
- * Launch configuration attribute key. The value is
- * a map. Keys in the map correspond to arguments names
- * returned by <code>IVMConnector#getDefaultArguments()</code>.
- * Values are strings corresponding to the values to use when
- * establishing a connection to a remote VM.
- */
- public static final String ATTR_CONNECT_MAP = JavaScriptCore.PLUGIN_ID + ".CONNECT_MAP"; //$NON-NLS-1$
-
- /**
- * Launch configuration attribute key. The value is an integer
- * indicating the width of the applet viewing area.
- *
- *
- */
- public static final String ATTR_APPLET_WIDTH = JavaScriptCore.PLUGIN_ID + ".APPLET_WIDTH"; //$NON-NLS-1$
-
- /**
- * Launch configuration attribute key. The value is an integer
- * indicating the height of the applet viewing area.
- *
- *
- */
- public static final String ATTR_APPLET_HEIGHT = JavaScriptCore.PLUGIN_ID + ".APPLET_HEIGHT"; //$NON-NLS-1$
-
- /**
- * Launch configuration attribute key. The value is a String indicating the
- * HTML name of the applet.
- *
- *
- */
- public static final String ATTR_APPLET_NAME = JavaScriptCore.PLUGIN_ID + ".APPLET_NAME"; //$NON-NLS-1$
-
- /**
- * Launch configuration attribute key. The value is a Map. Keys in the map
- * represent applet parameter names and the values in the map are the
- * corresponding parameter values
- *
- *
- */
- public static final String ATTR_APPLET_PARAMETERS = JavaScriptCore.PLUGIN_ID + ".APPLET_PARAMETERS"; //$NON-NLS-1$
-
- /**
- * Launch configuration attribute key. The value is a String indicating the
- * fully qualified name of the applet viewer utility class to use.
- *
- *
- */
- public static final String ATTR_APPLET_APPLETVIEWER_CLASS = JavaScriptCore.PLUGIN_ID + ".APPLET_APPLETVIEWER_CLASS"; //$NON-NLS-1$
-
- /**
- * Attribute key for a VM specific argument. Value is an array
- * of strings describing paths in the local file system that
- * should be prepended to the bootpath, or <code>null</code>
- * if none. The value is computed dynamically at launch time
- * and placed in the VM specific arguments map by the JavaScript
- * application launch delegate.
- *
- *
- */
- public static final String ATTR_BOOTPATH_PREPEND = JavaScriptCore.PLUGIN_ID + ".-Xbootincludepath/p:"; //$NON-NLS-1$
-
- /**
- * Attribute key for a VM specific argument. Value is an array
- * of strings describing paths in the local file system that
- * should be placed on the bootpath explicitly, or <code>null</code>
- * if none. The value is computed dynamically at launch time
- * and placed in the VM specific arguments map by the JavaScript
- * application launch delegate.
- *
- *
- */
- public static final String ATTR_BOOTPATH = JavaScriptCore.PLUGIN_ID + ".-Xbootincludepath:"; //$NON-NLS-1$
-
- /**
- * Attribute key for a VM specific argument. Value is an array
- * of strings describing paths in the local file system that
- * should be appended to the bootpath, or <code>null</code>
- * if none. The value is computed dynamically at launch time
- * and placed in the VM specific arguments map by the JavaScript
- * application launch delegate.
- *
- *
- */
- public static final String ATTR_BOOTPATH_APPEND = JavaScriptCore.PLUGIN_ID + ".-Xbootincludepath/a:"; //$NON-NLS-1$
-
- /**
- * Status code indicating a launch configuration does not
- * specify a project when a project is required.
- */
- public static final int ERR_UNSPECIFIED_PROJECT = 100;
-
- /**
- * Status code indicating a launch configuration does not
- * specify a main type to launch.
- */
- public static final int ERR_UNSPECIFIED_MAIN_TYPE = 101;
-
- /**
- * Status code indicating a launch configuration does not
- * specify a VM Install Type.
- */
- public static final int ERR_UNSPECIFIED_VM_INSTALL_TYPE = 102;
-
- /**
- * Status code indicating a launch configuration does not
- * specify a VM Install
- */
- public static final int ERR_UNSPECIFIED_VM_INSTALL = 103;
-
- /**
- * Status code indicating a launch configuration's VM install
- * type could not be found.
- */
- public static final int ERR_VM_INSTALL_TYPE_DOES_NOT_EXIST = 104;
-
- /**
- * Status code indicating a launch configuration's VM install
- * could not be found.
- */
- public static final int ERR_VM_INSTALL_DOES_NOT_EXIST = 105;
-
- /**
- * Status code indicating a VM runner could not be located
- * for the VM install specified by a launch configuration.
- */
- public static final int ERR_VM_RUNNER_DOES_NOT_EXIST = 106;
-
- /**
- * Status code indicating the project associated with
- * a launch configuration is not a JavaScript project.
- */
- public static final int ERR_NOT_A_JAVA_PROJECT = 107;
-
- /**
- * Status code indicating the specified working directory
- * does not exist.
- */
- public static final int ERR_WORKING_DIRECTORY_DOES_NOT_EXIST = 108;
-
- /**
- * Status code indicating a launch configuration does not
- * specify a host name value
- */
- public static final int ERR_UNSPECIFIED_HOSTNAME = 109;
-
- /**
- * Status code indicating a launch configuration has
- * specified an invalid host name attribute
- */
- public static final int ERR_INVALID_HOSTNAME = 110;
-
- /**
- * Status code indicating a launch configuration does not
- * specify a port number value
- */
- public static final int ERR_UNSPECIFIED_PORT = 111;
-
- /**
- * Status code indicating a launch configuration has
- * specified an invalid port number attribute
- */
- public static final int ERR_INVALID_PORT = 112;
-
- /**
- * Status code indicating an attempt to connect to a remote VM
- * has failed.
- */
- public static final int ERR_REMOTE_VM_CONNECTION_FAILED = 113;
-
- /**
- * Status code indicating that the shared memory attach connector
- * could not be found.
- */
- public static final int ERR_SHARED_MEMORY_CONNECTOR_UNAVAILABLE = 114;
-
- /**
- * Status code indicating that the Eclipse runtime does not support
- * launching a program with a working directory. This feature is only
- * available if Eclipse is run on a 1.3 runtime or higher.
- * <p>
- * A status handler may be registered for this error condition,
- * and should return a Boolean indicating whether the program
- * should be relaunched with the default working directory.
- * </p>
- */
- public static final int ERR_WORKING_DIRECTORY_NOT_SUPPORTED = 115;
-
- /**
- * Status code indicating that an error occurred launching a VM.
- * The status error message is the text that
- * the VM wrote to standard error before exiting.
- */
- public static final int ERR_VM_LAUNCH_ERROR = 116;
-
- /**
- * Status code indicating that a timeout has occurred waiting for
- * the VM to connect with the debugger.
- * <p>
- * A status handler may be registered for this error condition,
- * and should return a Boolean indicating whether the program
- * should continue waiting for a connection for the associated
- * timeout period.
- * </p>
- */
- public static final int ERR_VM_CONNECT_TIMEOUT = 117;
-
- /**
- * Status code indicating that a free socket was not available to
- * communicate with the VM.
- */
- public static final int ERR_NO_SOCKET_AVAILABLE = 118;
-
- /**
- * Status code indicating that the JDI connector required for a
- * debug launch was not available.
- */
- public static final int ERR_CONNECTOR_NOT_AVAILABLE = 119;
-
- /**
- * Status code indicating that the debugger failed to connect
- * to the VM.
- */
- public static final int ERR_CONNECTION_FAILED = 120;
-
- /**
- * Status code indicating that the applet launcher was asked to
- * launch a resource that did not extend <code>java.applet.Applet</code>.
- *
- *
- */
- public static final int ERR_NOT_AN_APPLET = 121;
-
- /**
- * Status code indicating that no launch configuration was specified.
- *
- *
- */
- public static final int ERR_UNSPECIFIED_LAUNCH_CONFIG = 122;
-
- /**
- * Status code indicating that the .html file used to initiate an applet
- * launch could not be built.
- *
- *
- */
- public static final int ERR_COULD_NOT_BUILD_HTML = 123;
-
- /**
- * Status code indicating that the project referenced by a launch configuration
- * is closed.
- *
- *
- */
- public static final int ERR_PROJECT_CLOSED = 124;
-
- /**
- * Status code indicating an unexpected internal error.
- */
- public static final int ERR_INTERNAL_ERROR = 150;
-
- /**
- * Default value for the 'ATTR_APPLET_APPLETVIEWER' attribute.
- *
- *
- */
- public static final String DEFAULT_APPLETVIEWER_CLASS = "sun.applet.AppletViewer"; //$NON-NLS-1$
- public static final String MAIN_ENTRY_METHOD_NAME="$$main$$";
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IRuntimeClasspathEntry.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IRuntimeClasspathEntry.java
deleted file mode 100644
index 7ff78cbf..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IRuntimeClasspathEntry.java
+++ /dev/null
@@ -1,332 +0,0 @@
-/*******************************************************************************
- * 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.launching;
-
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-
-/**
- * Represents an entry on a runtime includepath. A runtime includepath entry
- * may refer to one of the following:
- * <ul>
- * <li>A JavaScript project (type <code>PROJECT</code>) - a project entry refers
- * to all of the built classes in a project, and resolves to the output
- * location(s) of the associated JavaScript project.</li>
- * <li>An archive (type <code>ARCHIVE</code>) - an archive refers to a jar, zip, or
- * folder in the workspace or in the local file system containing class
- * files. An archive may have attached source.</li>
- * <li>A variable (type <code>VARIABLE</code>) - a variable refers to a
- * includepath variable, which may refer to a jar.</li>
- * <li>A library (type <code>CONTAINER</code>) - a container refers to includepath
- * container variable which refers to a collection of archives derived
- * dynamically, on a per project basis.</li>
- * <li>A contributed includepath entry (type <code>OTHER</code>) - a contributed
- * includepath entry is an extension contributed by a plug-in. The resolution
- * of a contributed includepath entry is client defined. See
- * <code>IRuntimeClasspathEntry2</code>.
- * </ul>
- * <p>
- * Clients may implement this interface for contributed a includepath entry
- * types (i.e. type <code>OTHER</code>). Note, contributed includepath entries
- * are new in 3.0, and are only intended to be contributed by the JavaScript debugger.
- * </p>
- *
- * @see org.eclipse.jdt.launching.IRuntimeClasspathEntry2
- *
- * 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 IRuntimeClasspathEntry {
-
- /**
- * Type identifier for project entries.
- */
- public static final int PROJECT = 1;
-
- /**
- * Type identifier for archive entries.
- */
- public static final int ARCHIVE = 2;
-
- /**
- * Type identifier for variable entries.
- */
- public static final int VARIABLE = 3;
-
- /**
- * Type identifier for container entries.
- */
- public static final int CONTAINER = 4;
-
- /**
- * Type identifier for contributed entries.
- *
- */
- public static final int OTHER = 5;
-
- /**
- * Classpath property identifier for entries that appear on the
- * bootstrap path by default.
- */
- public static final int STANDARD_CLASSES = 1;
-
- /**
- * Classpath property identifier for entries that should appear on the
- * bootstrap path explicitly.
- */
- public static final int BOOTSTRAP_CLASSES = 2;
-
- /**
- * Classpath property identifier for entries that should appear on the
- * user includepath.
- */
- public static final int USER_CLASSES = 3;
-
- /**
- * Returns this includepath entry's type. The type of a runtime includepath entry is
- * identified by one of the following constants:
- * <ul>
- * <li><code>PROJECT</code></li>
- * <li><code>ARCHIVE</code></li>
- * <li><code>VARIABLE</code></li>
- * <li><code>CONTAINER</code></li>
- * <li><code>OTHER</code></li>
- * </ul>
- * <p>
- * Since 3.0, a type of <code>OTHER</code> may be returned.
- * </p>
- * @return this includepath entry's type
- */
- public int getType();
-
- /**
- * Returns a memento for this includepath entry.
- * <p>
- * Since 3.0, the memento for a contributed includepath entry (i.e. of
- * type <code>OTHER</code>), must be in the form of an XML document,
- * with the following element structure:
- * <pre>
- * <runtimeClasspathEntry id="exampleId">
- * <memento
- * key1="value1"
- * ...>
- * </memento>
- * </runtimeClasspathEntry>
- * </pre>
- * The <code>id</code> attribute is the unique identifier of the extension
- * that contributed this runtime includepath entry type, via the extension
- * point <code>org.eclipse.jdt.launching.runtimeClasspathEntries</code>.
- * The <code>memento</code> element will be used to initialize a
- * restored runtime includepath entry, via the method
- * <code>IRuntimeClasspathEntry2.initializeFrom(Element memento)</code>. The
- * attributes of the <code>memento</code> element are client defined.
- * </p>
- *
- * @return a memento for this includepath entry
- * @exception CoreException if an exception occurs generating a memento
- */
- public String getMemento() throws CoreException;
-
- /**
- * Returns the path associated with this entry, or <code>null</code>
- * if none. The format of the
- * path returned depends on this entry's type:
- * <ul>
- * <li><code>PROJECT</code> - a workspace relative path to the associated
- * project.</li>
- * <li><code>ARCHIVE</code> - the absolute path of the associated archive,
- * which may or may not be in the workspace.</li>
- * <li><code>VARIABLE</code> - the path corresponding to the associated
- * includepath variable entry.</li>
- * <li><code>CONTAINER</code> - the path corresponding to the associated
- * includepath container variable entry.</li>
- * <li><code>OTHER</code> - the path returned is client defined.</li>
- * </ul>
- * <p>
- * Since 3.0, this method may return <code>null</code>.
- * </p>
- * @return the path associated with this entry, or <code>null</code>
- * @see org.eclipse.IIncludePathEntry.core.IClasspathEntry#getPath()
- */
- public IPath getPath();
-
- /**
- * Returns the resource associated with this entry, or <code>null</code>
- * if none. A project, archive, or folder entry may be associated
- * with a resource.
- *
- * @return the resource associated with this entry, or <code>null</code>
- */
- public IResource getResource();
-
- /**
- * Returns the path to the source archive associated with this
- * entry, or <code>null</code> if this includepath entry has no
- * source attachment.
- * <p>
- * Only archive and variable entries may have source attachments.
- * For archive entries, the path (if present) locates a source
- * archive. For variable entries, the path (if present) has
- * an analogous form and meaning as the variable path, namely the first segment
- * is the name of a includepath variable.
- * </p>
- *
- * @return the path to the source archive, or <code>null</code> if none
- */
- public IPath getSourceAttachmentPath();
-
- /**
- * Sets the path to the source archive associated with this
- * entry, or <code>null</code> if this includepath entry has no
- * source attachment.
- * <p>
- * Only archive and variable entries may have source attachments.
- * For archive entries, the path refers to a source
- * archive. For variable entries, the path has
- * an analogous form and meaning as the variable path, namely the
- * first segment is the name of a includepath variable.
- * </p>
- * <p>
- * Note that an empty path (<code>Path.EMPTY</code>) is considered
- * <code>null</code>.
- * </p>
- *
- * @param path the path to the source archive, or <code>null</code> if none
- */
- public void setSourceAttachmentPath(IPath path);
-
- /**
- * Returns the path within the source archive where package fragments
- * are located. An empty path indicates that packages are located at
- * the root of the source archive. Returns a non-<code>null</code> value
- * if and only if <code>getSourceAttachmentPath</code> returns
- * a non-<code>null</code> value.
- *
- * @return root path within the source archive, or <code>null</code> if
- * not applicable
- */
- public IPath getSourceAttachmentRootPath();
-
- /**
- * Sets the path within the source archive where package fragments
- * are located. A root path indicates that packages are located at
- * the root of the source archive. Only valid if a source attachment
- * path is also specified.
- * <p>
- * Note that an empty path (<code>Path.EMPTY</code>) is considered
- * <code>null</code>.
- * </p>
- *
- * @param path root path within the source archive, or <code>null</code>
- */
- public void setSourceAttachmentRootPath(IPath path);
-
- /**
- * Returns a constant indicating where this entry should appear on the
- * runtime includepath by default.
- * The value returned is one of the following:
- * <ul>
- * <li><code>STANDARD_CLASSES</code> - a standard entry does not need to appear
- * on the runtime includepath</li>
- * <li><code>BOOTSTRAP_CLASSES</code> - a bootstrap entry should appear on the
- * boot path</li>
- * <li><code>USER_CLASSES</code> - a user entry should appear on the path
- * containing user or application classes</li>
- * </ul>
- *
- * @return where this entry should appear on the runtime includepath
- */
- public int getClasspathProperty();
-
- /**
- * Sets whether this entry should appear on the bootstrap includepath,
- * the user includepath, or whether this entry is a standard bootstrap entry
- * that does not need to appear on the includepath.
- * The location is one of:
- * <ul>
- * <li><code>STANDARD_CLASSES</code> - a standard entry does not need to appear
- * on the runtime includepath</li>
- * <li><code>BOOTSTRAP_CLASSES</code> - a bootstrap entry should appear on the
- * boot path</li>
- * <li><code>USER_CLASSES</code> - a user entry should appear on the path
- * conatining user or application classes</li>
- * </ul>
- *
- * @param location a classpat property constant
- */
- public void setClasspathProperty(int location);
-
- /**
- * Returns an absolute path in the local file system for this entry,
- * or <code>null</code> if none, or if this entry is of type <code>CONTAINER</code>.
- *
- * @return an absolute path in the local file system for this entry,
- * or <code>null</code> if none
- */
- public String getLocation();
-
- /**
- * Returns an absolute path in the local file system for the source
- * attachment associated with this entry entry, or <code>null</code> if none.
- *
- * @return an absolute path in the local file system for the source
- * attachment associated with this entry entry, or <code>null</code> if none
- */
- public String getSourceAttachmentLocation();
-
- /**
- * Returns a path relative to this entry's source attachment path for the
- * root location containing source, or <code>null</code> if none.
- *
- * @return a path relative to this entry's source attachment path for the
- * root location containing source, or <code>null</code> if none
- */
- public String getSourceAttachmentRootLocation();
-
- /**
- * Returns the first segment of the path associated with this entry, or <code>null</code>
- * if this entry is not of type <code>VARIABLE</code> or <code>CONTAINER</code>.
- *
- * @return the first segment of the path associated with this entry, or <code>null</code>
- * if this entry is not of type <code>VARIABLE</code> or <code>CONTAINER</code>
- */
- public String getVariableName();
-
- /**
- * Returns a includepath entry equivalent to this runtime includepath entry,
- * or <code>null</code> if none.
- * <p>
- * Since 3.0, this method may return <code>null</code>.
- * </p>
- * @return a includepath entry equivalent to this runtime includepath entry,
- * or <code>null</code>
- *
- */
- public IIncludePathEntry getClasspathEntry();
-
- /**
- * Returns the JavaScript project associated with this runtime includepath entry
- * or <code>null</code> if none. Runtime includepath entries of type
- * <code>CONTAINER</code> may be associated with a project for the
- * purposes of resolving the entries in a container.
- *
- * @return the JavaScript project associated with this runtime includepath entry
- * or <code>null</code> if none
- *
- */
- public IJavaScriptProject getJavaProject();
-}
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
deleted file mode 100644
index 9d6e6943..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IRuntimeClasspathEntry2.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*******************************************************************************
- * 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.launching;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.debug.core.ILaunchConfiguration;
-import org.w3c.dom.Element;
-
-/**
- * Enhancements to <code>IRuntimeClasspathEntry</code> to support
- * extensible runtime includepath entries. Contributed runtime includepath
- * entries have a type of <code>OTHER</code>, and are contributed to
- * the <code>runtimeClasspathEntries</code> extension point.
- * <p>
- * Clients are not intended to implement this interface, as new types
- * of runtime includepath entries are only intended to be contributed
- * by the JavaScript debugger.
- * </p>
- *
- * @see org.eclipse.wst.jsdt.launching.IRuntimeClasspathEntry
- *
- * 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 IRuntimeClasspathEntry2 extends IRuntimeClasspathEntry {
-
- /**
- * Initializes this runtime includepath entry from the given memento.
- *
- * @param memento memento created by a includepath entry of the same type
- * @throws CoreException if unable to initialize from the given memento
- */
- public void initializeFrom(Element memento) throws CoreException;
-
- /**
- * Returns the unique identifier of the extension that contributed
- * this includepath entry type, or <code>null</code> if this includepath
- * entry type was not contributed.
- *
- * @return the unique identifier of the extension that contributed
- * this includepath entry type, or <code>null</code> if this includepath
- * entry type was not contributed
- */
- public String getTypeId();
-
- /**
- * Returns whether this includepath entry is composed of other entries.
- *
- * @return whether this includepath entry is composed of other entries
- */
- public boolean isComposite();
-
- /**
- * Returns the includepath entries this entry is composed of, or an
- * empty collection if this entry is not a composite entry.
- *
- * @param configuration the context (launch configuration) in which
- * this runtime includepath entry is being queried for contained
- * entries, possibly <code>null</code>
- * @return the includepath entries this entry is composed of, or an
- * empty collection if this entry is not a composite entry
- * @throws CoreException if unable to retrieve contained entries
- */
- public IRuntimeClasspathEntry[] getRuntimeClasspathEntries(ILaunchConfiguration configuration) throws CoreException;
-
- /**
- * Returns a human readable name for this includepath entry.
- *
- * @return a human readable name for this includepath entry
- */
- public String getName();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IRuntimeClasspathEntryResolver.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IRuntimeClasspathEntryResolver.java
deleted file mode 100644
index ad84e6bc..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IRuntimeClasspathEntryResolver.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*******************************************************************************
- * 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.launching;
-
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.debug.core.ILaunchConfiguration;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-
-/**
- * Resolves variable and/or container runtime includepath entries in
- * the context of a launch configuration or JavaScript project. A resolver can be declared
- * as an extension (<code>org.eclipse.wst.jsdt.launching.runtimeClasspathEntryResolver</code>),
- * or be registered with the <code>JavaRuntime</code> programmatically.
- * <p>
- * A resolver is registered for a specific includepath
- * <code>VARIABLE</code> and/or <code>CONTAINER</code>. A resolver is
- * consulted when a runtime includepath entry is needs to be resolved.
- * </p>
- * A resolver extension is defined in <code>plugin.xml</code>.
- * Following is an example definition of a runtime includepath entry
- * resolver extension.
- * <pre>
- * &lt;extension point="org.eclipse.wst.jsdt.launching.runtimeClasspathEntryResolvers"&gt;
- * &lt;runtimeClasspathEntryResolver
- * id="com.example.ExampleResolver"
- * class="com.example.ExampleResolverImpl"
- * variable="VAR_NAME"
- * container="CONTAINER_ID"
- * &lt;/runtimeClasspathEntryResolver&gt;
- * &lt;/extension&gt;
- * </pre>
- * The attributes are specified as follows:
- * <ul>
- * <li><code>id</code> specifies a unique identifier for this extension.</li>
- * <li><code>class</code> specifies the fully qualified name of the JavaScript class
- * that implements <code>IRuntimeClasspathEntryResolver</code>.</li>
- * <li><code>variable</code> name of the includepath variable this resolver
- * is registered for.</li>
- * <li><code>container</code> identifier of the includepath container this
- * resolver is registered for.</li>
- * </ul>
- * At least one of <code>variable</code> or <code>container</code> must be
- * specified.
- * </p>
- * <p>
- * Clients may implement this interface.
- * </p>
- *
- * 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 IRuntimeClasspathEntryResolver {
-
- /**
- * Returns resolved runtime includepath entries for the given runtime includepath entry,
- * in the context of the given launch configuration.
- *
- * @param entry runtime includepath entry to resolve, of type
- * <code>VARIABLE</code> or <code>CONTAINTER</code>
- * @param configuration the context in which the runtime includepath entry
- * needs to be resolved
- * @return resolved entries (zero or more)
- * @exception CoreException if unable to resolve the entry
- */
- public IRuntimeClasspathEntry[] resolveRuntimeClasspathEntry(IRuntimeClasspathEntry entry, ILaunchConfiguration configuration) throws CoreException;
-
- /**
- * Returns resolved runtime includepath entries for the given runtime includepath entry,
- * in the context of the given JavaScript project.
- *
- * @param entry runtime includepath entry to resolve, of type
- * <code>VARIABLE</code> or <code>CONTAINTER</code>
- * @param project context in which the runtime includepath entry
- * needs to be resolved
- * @return resolved entries (zero or more)
- * @exception CoreException if unable to resolve the entry
- */
- public IRuntimeClasspathEntry[] resolveRuntimeClasspathEntry(IRuntimeClasspathEntry entry, IJavaScriptProject project) throws CoreException;
-
- /**
- * Returns a VM install associated with the given includepath entry,
- * or <code>null</code> if none.
- *
- * @param entry includepath entry
- * @return vm install associated with entry or <code>null</code> if none
- * @exception CoreException if unable to resolve a VM
- */
- public IVMInstall resolveVMInstall(IIncludePathEntry entry) throws CoreException;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IRuntimeClasspathEntryResolver2.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IRuntimeClasspathEntryResolver2.java
deleted file mode 100644
index 71491c19..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IRuntimeClasspathEntryResolver2.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*******************************************************************************
- * 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.launching;
-
-
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-
-/**
- * Optional enhancements to {@link IRuntimeClasspathEntryResolver}.
- * <p>
- * Clients may implement this interface.
- * </p>
- *
- * 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 IRuntimeClasspathEntryResolver2 extends IRuntimeClasspathEntryResolver {
-
- /**
- * Returns whether the given includepath entry references a VM install.
- *
- * @param entry includepath entry
- * @return whether the given includepath entry references a VM install
- */
- public boolean isVMInstallReference(IIncludePathEntry entry);
-}
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
deleted file mode 100644
index c47938ce..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IRuntimeClasspathProvider.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*******************************************************************************
- * 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.launching;
-
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.debug.core.ILaunchConfiguration;
-
-/**
- * A includepath provider computes an unresolved includepath for a launch
- * configuration, and resolves includepath entries for a launch configuration.
- * A includepath provider is defined as an extension of type
- * <code>org.eclipse.wst.jsdt.launching.includepathProvider</code>.
- * <p>
- * A provider is registered with an identifier that can be
- * referenced by a launch configuration. A includepath provider is consulted
- * to compute a includepath or source lookup path when a launch configuration
- * references a provider in one or both of the following attributes:
- * <ul>
- * <li><code>ATTR_CLASSPATH_PROVIDER</code></li>
- * <li><code>ATTR_SOURCE_PATH_PROVIDER</code></li>
- * </ul>
- * </p>
- * A provider extension is defined in <code>plugin.xml</code>.
- * Following is an example definition of a runtime includepath provider
- * extension.
- * <pre>
- * &lt;extension point="org.eclipse.wst.jsdt.launching.includepathProviders"&gt;
- * &lt;includepathProvider
- * id="com.example.ExampleClasspathProvider"
- * class="com.example.ExampleClasspathProviderImpl"
- * &lt;/includepathProvider&gt;
- * &lt;/extension&gt;
- * </pre>
- * The attributes are specified as follows:
- * <ul>
- * <li><code>id</code> specifies a unique identifier for this extension. This
- * identifier may be used to reference a provider on one of the launch
- * configuration attributes mentioned above.</li>
- * <li><code>class</code> specifies the fully qualified name of the JavaScript class
- * that implements <code>IRuntimeClasspathProvider</code>.</li>
- * </ul>
- * </p>
- * <p>
- * Clients may implement this interface.
- * </p>
- *
- *
- * 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 IRuntimeClasspathProvider {
-
- /**
- * Computes and returns an unresolved includepath for the given launch configuration.
- * Variable and container entries are not resolved.
- *
- * @param configuration launch configuration
- * @return unresolved path
- * @exception CoreException if unable to compute a path
- */
- public IRuntimeClasspathEntry[] computeUnresolvedClasspath(ILaunchConfiguration configuration) throws CoreException;
-
- /**
- * Returns the resolved path corresponding to the given path, in the context of the
- * given launch configuration. Variable and container entries are resolved. The returned
- * (resolved) path need not have the same number of entries as the given (unresolved)
- * path.
- *
- * @param entries entries to resolve
- * @param configuration launch configuration context to resolve in
- * @return resolved path
- * @exception CoreException if unable to resolve a path
- */
- public IRuntimeClasspathEntry[] resolveClasspath(IRuntimeClasspathEntry[] entries, ILaunchConfiguration configuration) throws CoreException;
-
-}
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
deleted file mode 100644
index 360fdd44..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IVMInstall.java
+++ /dev/null
@@ -1,162 +0,0 @@
-/*******************************************************************************
- * 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.launching;
-
-import java.io.File;
-import java.net.URL;
-
-/**
- * Represents a particular installation of a VM. A VM instance holds all parameters
- * specific to a VM installation. Unlike VM types, VM instances can be created and
- * configured dynamically at run-time. This is typically done by the user
- * interactively in the UI.
- * <p>
- * A VM install is responsible for creating VM runners to launch a JavaScript program
- * in a specific mode.
- * </p>
- * <p>
- * This interface is intended to be implemented by clients that contribute
- * to the <code>"org.eclipse.wst.jsdt.launching.vmInstallTypes"</code> extension point.
- * Rather than implementing this interface directly, it is strongly recommended that
- * clients subclass {@link org.eclipse.wst.jsdt.launching.AbstractVMInstall} to be insulated
- * from potential API additions. In 3.1, a new optional interface has been added for
- * implementors of this interface - {@link org.eclipse.wst.jsdt.launching.IVMInstall2}.
- * The new interface is implemented by {@link org.eclipse.wst.jsdt.launching.AbstractVMInstall}.
- * </p>
- * @see org.eclipse.wst.jsdt.launching.IVMInstall2
- *
- * 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 IVMInstall {
- /**
- * Returns a VM runner that runs this installed VM in the given mode.
- *
- * @param mode the mode the VM should be launched in; one of the constants
- * declared in <code>org.eclipse.debug.core.ILaunchManager</code>
- * @return a VMRunner for a given mode May return <code>null</code> if the given mode
- * is not supported by this VM.
- * @see org.eclipse.debug.core.ILaunchManager
- */
- IVMRunner getVMRunner(String mode);
- /**
- * Returns the id for this VM. VM IDs are unique within the VMs
- * of a given VM type. The VM id is not intended to be presented to users.
- *
- * @return the VM identifier. Must not return <code>null</code>.
- */
- String getId();
- /**
- * Returns the display name of this VM.
- * The VM name is intended to be presented to users.
- *
- * @return the display name of this VM. May return <code>null</code>.
- */
- String getName();
- /**
- * Sets the display name of this VM.
- * The VM name is intended to be presented to users.
- *
- * @param name the display name of this VM
- */
- void setName(String name);
- /**
- * Returns the root directory of the install location of this VM.
- *
- * @return the root directory of this VM installation. May
- * return <code>null</code>.
- */
- File getInstallLocation();
- /**
- * Sets the root directory of the install location of this VM.
- *
- * @param installLocation the root directory of this VM installation
- */
- void setInstallLocation(File installLocation);
-
- /**
- * Returns the VM type of this VM.
- *
- * @return the VM type that created this IVMInstall instance
- */
- IVMInstallType getVMInstallType();
-
- /**
- * Returns the library locations of this IVMInstall. Generally,
- * clients should use <code>JavaRuntime.getLibraryLocations(IVMInstall)</code>
- * to determine the libraries associated with this VM install.
- *
- * @see IVMInstall#setLibraryLocations(LibraryLocation[])
- * @return The library locations of this IVMInstall.
- * Returns <code>null</code> to indicate that this VM install uses
- * the default library locations associated with this VM's install type.
- *
- */
- LibraryLocation[] getLibraryLocations();
-
- /**
- * Sets the library locations of this IVMInstall.
- * @param locations The <code>LibraryLocation</code>s to associate
- * with this IVMInstall.
- * May be <code>null</code> to indicate that this VM install uses
- * the default library locations associated with this VM's install type.
- *
- */
- void setLibraryLocations(LibraryLocation[] locations);
-
- /**
- * Sets the jsdoc location associated with this VM install.
- *
- * @param url a url pointing to the jsdoc location associated with
- * this VM install
- *
- */
- public void setJavadocLocation(URL url);
-
- /**
- * Returns the jsdoc location associated with this VM install.
- *
- * @return a url pointing to the jsdoc location associated with
- * this VM install, or <code>null</code> if none
- *
- */
- public URL getJavadocLocation();
-
- /**
- * Returns VM arguments to be used with this vm install whenever this
- * VM is launched as they should be passed to the command line, or
- * <code>null</code> if none.
- *
- * @return VM arguments to be used with this vm install whenever this
- * VM is launched as they should be passed to the command line, or
- * <code>null</code> if none
- *
- */
- public String[] getVMArguments();
-
- /**
- * Sets VM arguments to be used with this vm install whenever this
- * VM is launched, possibly <code>null</code>. This is equivalent
- * to <code>setVMArgs(String)</code> with whitespace character delimited
- * arguments.
- *
- * @param vmArgs VM arguments to be used with this vm install whenever this
- * VM is launched, possibly <code>null</code>
- *
- * @deprecated if possible, clients should use setVMArgs(String) on
- * {@link IVMInstall2} when possible
- */
- public void setVMArguments(String[] vmArgs);
-
-}
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
deleted file mode 100644
index 144787ae..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IVMInstall2.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.launching;
-
-
-/**
- * Optional extensions that may be implemented by an
- * {@link org.eclipse.wst.jsdt.launching.IVMInstall}.
- * <p>
- * When an <code>IVMInstall</code> implements this interface,
- * clients must call <code>getVMArgs()</code> in place of
- * <code>getVMArguments()</code> and <code>setVMArgs(String)</code> in place of
- * <code>setVMArguments(String[])</code>. This avoids the problem noted
- * in bug 73493.
- * </p>
- * <p>
- * Additionally, this interface optionally provides the JavaScript version
- * associated with a VM install.
- * </p>
- * <p>
- * Clients that implement {@link org.eclipse.wst.jsdt.launching.IVMInstall} may additionally
- * implement this interface. However, it is strongly recommended that clients subclass
- * {@link org.eclipse.wst.jsdt.launching.AbstractVMInstall} instead, which already implements
- * this interface, and will insulate clients from additional API additions in the future.
- * </p>
- *
- * 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 IVMInstall2 {
-
- /**
- * Returns VM arguments to be used with this vm install whenever this
- * VM is launched as a raw string, or <code>null</code> if none.
- *
- * @return VM arguments to be used with this vm install whenever this
- * VM is launched as a raw string, or <code>null</code> if none
- */
- public String getVMArgs();
-
- /**
- * Sets VM arguments to be used with this vm install whenever this
- * VM is launched as a raw string, possibly <code>null</code>.
- *
- * @param vmArgs VM arguments to be used with this vm install whenever this
- * VM is launched as a raw string, possibly <code>null</code>
- */
- public void setVMArgs(String vmArgs);
-
- /**
- * Returns a string representing the <code>java.version</code> system property
- * of this VM install, or <code>null</code> if unknown.
- *
- * @return a string representing the <code>java.version</code> system property
- * of this VM install, or <code>null</code> if unknown.
- */
- public String getJavaVersion();
-}
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
deleted file mode 100644
index 66328a0d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IVMInstall3.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*******************************************************************************
- * 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.launching;
-
-
-/**
- * Optional extensions that may be implemented by an
- * {@link org.eclipse.wst.jsdt.launching.IVMInstall}, providing access to
- * a JRE's system properties.
- * <p>
- * Clients that implement {@link org.eclipse.wst.jsdt.launching.IVMInstall} may additionally
- * implement this interface. However, it is strongly recommended that clients subclass
- * {@link org.eclipse.wst.jsdt.launching.AbstractVMInstall} instead, which already implements
- * this interface, and will insulate clients from additional API additions in the future.
- * </p>
- *
- * 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 IVMInstall3 {
-
- /**
- * Evaluates the specified system properties in this VM, returning the result
- * as a map of property names to property values.
- *
- * @param properties the property names to evaluate, for example <code>{"user.home"}</code>
- * @param monitor progress monitor or <code>null</code>
- * @return map of system property names to associated property values
- * @throws CoreException if an exception occurs evaluating the properties
- *
- */
-// ASDT never called
- // public Map evaluateSystemProperties(String[] properties, IProgressMonitor monitor) throws CoreException;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IVMInstallChangedListener.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IVMInstallChangedListener.java
deleted file mode 100644
index 72cd7ee7..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IVMInstallChangedListener.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*******************************************************************************
- * 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.launching;
-
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-
-
-
-/**
- * A VM install changed listener is notified when
- * the workspace default VM install changes, or when an attribute of
- * a specific VM install changes.
- * Listeners register with <code>JavaRuntime</code>.
- * <p>
- * Clients may implement this interface.
- * </p>
- *
- * 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 IVMInstallChangedListener {
-
- /**
- * Property constant indicating the library locations associated
- * with a VM install have changed.
- */
- public static final String PROPERTY_LIBRARY_LOCATIONS = JavaScriptCore.PLUGIN_ID + ".PROPERTY_LIBRARY_LOCATIONS"; //$NON-NLS-1$
-
- /**
- * Property constant indicating the name associated
- * with a VM install has changed.
- */
- public static final String PROPERTY_NAME = JavaScriptCore.PLUGIN_ID + ".PROPERTY_NAME"; //$NON-NLS-1$
-
- /**
- * Property constant indicating the install location of
- * a VM install has changed.
- */
- public static final String PROPERTY_INSTALL_LOCATION =JavaScriptCore.PLUGIN_ID + ".PROPERTY_INSTALL_LOCATION"; //$NON-NLS-1$
-
- /**
- * Property constant indicating the jsdoc location associated
- * with a VM install has changed.
- */
- public static final String PROPERTY_JAVADOC_LOCATION = JavaScriptCore.PLUGIN_ID+ ".PROPERTY_JAVADOC_LOCATION"; //$NON-NLS-1$
-
- /**
- * Property constant indicating the VM arguments associated
- * with a VM install has changed.
- *
- *
- */
- public static final String PROPERTY_VM_ARGUMENTS = JavaScriptCore.PLUGIN_ID + ".PROPERTY_VM_ARGUMENTS"; //$NON-NLS-1$
-
- /**
- * Notification that the workspace default VM install
- * has changed.
- *
- * @param previous the VM install that was previously assigned
- * to the workspace, possibly <code>null</code>
- * @param current the VM install that is currently assigned to the
- * workspace, possibly <code>null</code>
- */
- public void defaultVMInstallChanged(IVMInstall previous, IVMInstall current);
-
- /**
- * Notification that a property of a VM install has changed.
- *
- * @param event event describing the change. The VM that has changed
- * is the source object associated with the event.
- */
- public void vmChanged(PropertyChangeEvent event);
-
- /**
- * Notification that a VM has been created.
- *
- * @param vm the vm that has been created
- */
- public void vmAdded(IVMInstall vm);
-
- /**
- * Notification that a VM has been disposed.
- *
- * @param vm the vm that has been disposed
- */
- public void vmRemoved(IVMInstall vm);
-
-}
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
deleted file mode 100644
index e6345dd9..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IVMInstallType.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/*******************************************************************************
- * 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.launching;
-
-import java.io.File;
-
-import org.eclipse.core.runtime.IStatus;
-
-/**
- * Represents a particular type of VM for which there may be
- * any number of VM installations. An example of a VM type
- * is the standard JRE which might have instances corresponding
- * to different installed versions such as JRE 1.2.2 and
- * JRE 1.3.
- * <p>
- * This interface is intended to be implemented by clients that contribute
- * to the <code>"org.eclipse.wst.jsdt.launching.vmType"</code> extension point.
- * </p>
- *
- *
- * 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 IVMInstallType {
- /**
- * Creates a new instance of this VM Install type.
- * The newly created IVMInstall is managed by this IVMInstallType.
- *
- * @param id An id String that must be unique within this IVMInstallType.
- *
- * @return the newly created VM instance
- *
- * @throws IllegalArgumentException If the id exists already.
- */
- IVMInstall createVMInstall(String id);
- /**
- * Finds the VM with the given id.
- *
- * @param id the VM id
- * @return a VM instance, or <code>null</code> if not found
- */
- IVMInstall findVMInstall(String id);
- /**
- * Finds the VM with the given name.
- *
- * @param name the VM name
- * @return a VM instance, or <code>null</code> if not found
- *
- */
- IVMInstall findVMInstallByName(String name);
-
- /**
- * Remove the VM associated with the given id from the set of VMs managed by
- * this VM type. Has no effect if a VM with the given id is not currently managed
- * by this type.
- * A VM install that is disposed may not be used anymore.
- *
- * @param id the id of the VM to be disposed.
- */
- void disposeVMInstall(String id);
- /**
- * Returns all VM instances managed by this VM type.
- *
- * @return the list of VM instances managed by this VM type
- */
- IVMInstall[] getVMInstalls();
- /**
- * Returns the display name of this VM type.
- *
- * @return the name of this IVMInstallType
- */
- String getName();
-
- /**
- * Returns the globally unique id of this VM type.
- * Clients are responsible for providing a unique id.
- *
- * @return the id of this IVMInstallType
- */
- String getId();
- /**
- * Validates the given location of a VM installation.
- * <p>
- * For example, an implementation might check whether the VM executable
- * is present.
- * </p>
- *
- * @param installLocation the root directory of a potential installation for
- * this type of VM
- * @return a status object describing whether the install location is valid
- */
- IStatus validateInstallLocation(File installLocation);
-
- /**
- * Tries to detect an installed VM that matches this VM install type.
- * Typically, this method will detect the VM installation the
- * Eclipse platform runs on. Implementers should return <code>null</code> if they
- * can't assure that a given vm install matches this IVMInstallType.
- * @return The location of an VM installation that can be used
- * with this VM install type, or <code>null</code> if unable
- * to locate an installed VM.
- */
- File detectInstallLocation();
-
- /**
- * Returns a collection of <code>LibraryLocation</code>s that represent the
- * default system libraries of this VM install type, if a VM was installed
- * at the given <code>installLocation</code>.
- * The returned <code>LibraryLocation</code>s may not exist if the
- * <code>installLocation</code> is not a valid install location.
- *
- * @param installLocation home location
- * @see LibraryLocation
- * @see IVMInstallType#validateInstallLocation(File)
- *
- * @return default library locations based on the given <code>installLocation</code>.
- *
- */
- LibraryLocation[] getDefaultLibraryLocations(File installLocation);
-}
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
deleted file mode 100644
index e1911d18..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IVMRunner.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*******************************************************************************
- * 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.launching;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.debug.core.ILaunch;
-
-
-
-/**
- * A VM runner starts a JavaScript VM running a JavaScript program.
- * <p>
- * Clients may implement this interface to launch a new kind of VM.
- * </p>
- *
- * 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 IVMRunner {
-
- /**
- * Launches a JavaScript VM as specified in the given configuration,
- * contributing results (debug targets and processes), to the
- * given launch.
- *
- * @param configuration the configuration settings for this run
- * @param launch the launch to contribute to
- * @param monitor progress monitor or <code>null</code>
- * @exception CoreException if an exception occurs while launching
- */
- public void run(VMRunnerConfiguration configuration, ILaunch launch, IProgressMonitor monitor) throws CoreException;
-
-}
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
deleted file mode 100644
index db5682ff..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/JREContainer.java
+++ /dev/null
@@ -1,195 +0,0 @@
-/*******************************************************************************
- * 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.launching;
-
-
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.wst.jsdt.core.IAccessRule;
-import org.eclipse.wst.jsdt.core.IIncludePathAttribute;
-import org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-
-import com.ibm.icu.text.MessageFormat;
-
-/**
- * JRE Container - resolves a includepath container variable to a JRE
- *
- * 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 JREContainer implements IJsGlobalScopeContainer {
-
- /**
- * Corresponding JRE
- */
- private IVMInstall fVMInstall = null;
-
- /**
- * Container path used to resolve to this JRE
- */
- private IPath fPath = null;
-
- /**
- * Cache of includepath entries per VM install. Cleared when a VM changes.
- */
- private static Map fgClasspathEntries = null;
-
- private static IAccessRule[] EMPTY_RULES = new IAccessRule[0];
-
- /**
- * Returns the includepath entries associated with the given VM.
- *
- * @param vm
- * @return includepath entries
- */
- private static IIncludePathEntry[] getClasspathEntries(IVMInstall vm) {
- if (fgClasspathEntries == null) {
- fgClasspathEntries = new HashMap(10);
- // add a listener to clear cached value when a VM changes or is removed
-// IVMInstallChangedListener listener = new IVMInstallChangedListener() {
-// public void defaultVMInstallChanged(IVMInstall previous, IVMInstall current) {
-// }
-//
-// public void vmChanged(PropertyChangeEvent event) {
-// if (event.getSource() != null) {
-// fgClasspathEntries.remove(event.getSource());
-// }
-// }
-//
-// public void vmAdded(IVMInstall newVm) {
-// }
-//
-// public void vmRemoved(IVMInstall removedVm) {
-// fgClasspathEntries.remove(removedVm);
-// }
-// };
-// JavaRuntime.addVMInstallChangedListener(listener);
- }
- IIncludePathEntry[] entries = (IIncludePathEntry[])fgClasspathEntries.get(vm);
- if (entries == null) {
- entries = computeClasspathEntries(vm);
- fgClasspathEntries.put(vm, entries);
- }
- return entries;
- }
-
- /**
- * Computes the includepath entries associated with a VM - one entry per library.
- *
- * @param vm
- * @return includepath entries
- */
- private static IIncludePathEntry[] computeClasspathEntries(IVMInstall vm) {
- LibraryLocation[] libs = vm.getLibraryLocations();
- boolean overridejsdoc = false;
- if (libs == null) {
- libs = JavaRuntime.getLibraryLocations(vm);
- overridejsdoc = true;
- }
- List entries = new ArrayList(libs.length);
- for (int i = 0; i < libs.length; i++) {
- if (!libs[i].getSystemLibraryPath().isEmpty()) {
- IPath sourcePath = libs[i].getSystemLibrarySourcePath();
- if (sourcePath.isEmpty()) {
- sourcePath = null;
- }
- IPath rootPath = libs[i].getPackageRootPath();
- if (rootPath.isEmpty()) {
- rootPath = null;
- }
- URL javadocLocation = libs[i].getJavadocLocation();
- if (overridejsdoc && javadocLocation == null) {
- javadocLocation = vm.getJavadocLocation();
- }
- IIncludePathAttribute[] attributes = null;
- if (javadocLocation == null) {
- attributes = new IIncludePathAttribute[0];
- } else {
- attributes = new IIncludePathAttribute[]{JavaScriptCore.newIncludepathAttribute(IIncludePathAttribute.JSDOC_LOCATION_ATTRIBUTE_NAME, javadocLocation.toExternalForm())};
- }
- entries.add(JavaScriptCore.newLibraryEntry(libs[i].getSystemLibraryPath(), sourcePath, rootPath, EMPTY_RULES, attributes, false));
- }
- }
- return (IIncludePathEntry[])entries.toArray(new IIncludePathEntry[entries.size()]);
- }
-
- /**
- * Constructs a JRE includepath conatiner on the given VM install
- *
- * @param vm vm install - cannot be <code>null</code>
- * @param path container path used to resolve this JRE
- */
- public JREContainer(IVMInstall vm, IPath path) {
- fVMInstall = vm;
- fPath = path;
- }
-
- /**
- * @see IJsGlobalScopeContainer#getClasspathEntries()
- * @deprecated Use {@link #getIncludepathEntries()} instead
- */
- public IIncludePathEntry[] getClasspathEntries() {
- return getIncludepathEntries();
- }
-
- /**
- * @see IJsGlobalScopeContainer#getIncludepathEntries()
- */
- public IIncludePathEntry[] getIncludepathEntries() {
- return getClasspathEntries(fVMInstall);
- }
-
- /**
- * @see IJsGlobalScopeContainer#getDescription()
- */
- public String getDescription() {
-// String environmentId = JavaRuntime.getExecutionEnvironmentId(getPath());
-// String tag = null;
-// if (environmentId == null) {
-// tag = fVMInstall.getName();
-// } else {
-// tag = environmentId;
-// }
- return MessageFormat.format(LaunchingMessages.JREContainer_JRE_System_Library_1, new String[]{});
- }
-
- /**
- * @see IJsGlobalScopeContainer#getKind()
- */
- public int getKind() {
- return IJsGlobalScopeContainer.K_DEFAULT_SYSTEM;
- }
-
- /**
- * @see IJsGlobalScopeContainer#getPath()
- */
- public IPath getPath() {
- return fPath;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer#resolvedLibraryImport(java.lang.String)
- */
- public String[] resolvedLibraryImport(String a) {
-
- return null;
- }
-
-}
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
deleted file mode 100644
index 2b5c7045..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/JREContainerInitializer.java
+++ /dev/null
@@ -1,301 +0,0 @@
-/*******************************************************************************
- * 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.launching;
-
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-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.JsGlobalScopeContainerInitializer;
-import org.eclipse.wst.jsdt.core.compiler.libraries.LibraryLocation;
-import org.eclipse.wst.jsdt.core.compiler.libraries.SystemLibraryLocation;
-import org.eclipse.wst.jsdt.core.infer.DefaultInferrenceProvider;
-
-/**
- * Resolves a container for a JRE includepath container entry.
- *
- * 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 JREContainerInitializer extends JsGlobalScopeContainerInitializer {
-
- public static final String JsECMA_NAME = LaunchingMessages.JREContainerInitializer_JsECMA_NAME;
-
- /**
- * @see JsGlobalScopeContainerInitializer#initialize(IPath, IJavaScriptProject)
- */
- public void initialize(IPath containerPath, IJavaScriptProject project) throws CoreException {
- int size = containerPath.segmentCount();
- if (size > 0) {
- if (containerPath.segment(0).equals(JavaRuntime.JRE_CONTAINER)) {
- IVMInstall vm = resolveVM(containerPath);
- JREContainer container = null;
- if (vm != null) {
- container = new JREContainer(vm, containerPath);
- }
- JavaScriptCore.setJsGlobalScopeContainer(containerPath, new IJavaScriptProject[] {project}, new IJsGlobalScopeContainer[] {container}, null);
- }
- }
- }
-
-
-
- public int getKind() {
- return K_DEFAULT_SYSTEM;
- }
-
-
-
- /**
- * Returns the VM install associated with the container path, or <code>null</code>
- * if it does not exist.
- */
- public static IVMInstall resolveVM(IPath containerPath) {
- IVMInstall vm = null;
- if (containerPath.segmentCount() > 1) {
- // specific JRE
- String id = getExecutionEnvironmentId(containerPath);
- if (id != null) {
- //TODO: implement
- throw new org.eclipse.wst.jsdt.core.UnimplementedException();
-// IExecutionEnvironmentsManager manager = JavaRuntime.getExecutionEnvironmentsManager();
-// IExecutionEnvironment environment = manager.getEnvironment(id);
-// if (environment != null) {
-// vm = resolveVM(environment);
-// }
- } else {
- String vmTypeId = getVMTypeId(containerPath);
- String vmName = getVMName(containerPath);
- IVMInstallType vmType = JavaRuntime.getVMInstallType(vmTypeId);
- if (vmType != null) {
- vm = vmType.findVMInstallByName(vmName);
- }
- }
- } else {
- // workspace default JRE
- vm = JavaRuntime.getDefaultVMInstall();
- }
- return vm;
- }
-
-// /**
-// * Returns the VM install bound to the given execution environment
-// * or <code>null</code>.
-// *
-// * @param environment
-// * @return vm install or <code>null</code>
-// *
-// */
-// public static IVMInstall resolveVM(IExecutionEnvironment environment) {
-// IVMInstall vm = environment.getDefaultVM();
-// if (vm == null) {
-// IVMInstall[] installs = environment.getCompatibleVMs();
-// // take the first strictly compatible vm if there is no default
-// for (int i = 0; i < installs.length; i++) {
-// IVMInstall install = installs[i];
-// if (environment.isStrictlyCompatible(install)) {
-// vm = install;
-// break;
-// }
-// }
-// // use the first vm failing that
-// if (vm == null && installs.length > 0) {
-// vm = installs[0];
-// }
-// }
-// return vm;
-// }
-
- /**
- * Returns the segment from the path containing the execution environment id
- * or <code>null</code>
- *
- * @param path container path
- * @return ee id
- */
- public static String getExecutionEnvironmentId(IPath path) {
- return null;
-// String name = getVMName(path);
-// if (name != null) {
-//// name = decodeEnvironmentId(name);
-//// IExecutionEnvironmentsManager manager = JavaRuntime.getExecutionEnvironmentsManager();
-//// IExecutionEnvironment environment = manager.getEnvironment(name);
-//// if (environment != null) {
-//// return environment.getId();
-//// }
-// }
-// return null;
- }
-
- /**
- * Returns whether the given path identifies a vm by exeuction environment.
- *
- * @param path
- * @return whether the given path identifies a vm by exeuction environment
- */
- public static boolean isExecutionEnvironment(IPath path) {
- return getExecutionEnvironmentId(path) != null;
- }
-
- /**
- * Escapes foward slashes in environment id.
- *
- * @param id
- * @return esaped name
- */
- public static String encodeEnvironmentId(String id) {
- return id.replace('/', '%');
- }
-
- public static String decodeEnvironmentId(String id) {
- return id.replace('%', '/');
- }
-
- /**
- * Returns the VM type identifier from the given container ID path.
- *
- * @return the VM type identifier from the given container ID path
- */
- public static String getVMTypeId(IPath path) {
- return path.segment(1);
- }
-
- /**
- * Returns the VM name from the given container ID path.
- *
- * @return the VM name from the given container ID path
- */
- public static String getVMName(IPath path) {
- return path.segment(2);
- }
-
- /**
- * The container can be updated if it refers to an existing VM.
- *
- * @see org.eclipse.jdt.core.JsGlobalScopeContainerInitializer#canUpdateJsGlobalScopeContainer(org.eclipse.core.runtime.IPath, org.eclipse.IJavaScriptProject.core.IJavaProject)
- */
- public boolean canUpdateJsGlobalScopeContainer(IPath containerPath, IJavaScriptProject project) {
-// if (containerPath != null && containerPath.segmentCount() > 0) {
-// if (JavaRuntime.JRE_CONTAINER.equals(containerPath.segment(0))) {
-// return resolveVM(containerPath) != null;
-// }
-// }
- return false;
- }
-
- /**
- * @see org.eclipse.jdt.core.JsGlobalScopeContainerInitializer#requestJsGlobalScopeContainerUpdate(org.eclipse.core.runtime.IPath, org.eclipse.IJavaScriptProject.core.IJavaProject, org.eclipse.jdt.core.IJsGlobalScopeContainer)
- */
- public void requestJsGlobalScopeContainerUpdate(IPath containerPath, IJavaScriptProject project, IJsGlobalScopeContainer containerSuggestion) throws CoreException {
-// IVMInstall vm = resolveVM(containerPath);
-// if (vm == null) {
-// IStatus status = new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IJavaLaunchConfigurationConstants.ERR_VM_INSTALL_DOES_NOT_EXIST, MessageFormat.format(LaunchingMessages.JREContainerInitializer_JRE_referenced_by_includepath_container__0__does_not_exist__1, new String[]{containerPath.toString()}), null);
-// throw new CoreException(status);
-// }
-// // update of the vm with new library locations
-//
-// IIncludePathEntry[] entries = containerSuggestion.getClasspathEntries();
-// LibraryLocation[] libs = new LibraryLocation[entries.length];
-// for (int i = 0; i < entries.length; i++) {
-// IIncludePathEntry entry = entries[i];
-// if (entry.getEntryKind() == IIncludePathEntry.CPE_LIBRARY) {
-// IPath path = entry.getPath();
-// File lib = path.toFile();
-// if (lib.exists() && lib.isFile()) {
-// IPath srcPath = entry.getSourceAttachmentPath();
-// if (srcPath == null) {
-// srcPath = Path.EMPTY;
-// }
-// IPath rootPath = entry.getSourceAttachmentRootPath();
-// if (rootPath == null) {
-// rootPath = Path.EMPTY;
-// }
-// URL javadocLocation = null;
-// IIncludePathAttribute[] extraAttributes = entry.getExtraAttributes();
-// for (int j = 0; j < extraAttributes.length; j++) {
-// IIncludePathAttribute attribute = extraAttributes[j];
-// if (attribute.getName().equals(IIncludePathAttribute.JSDOC_LOCATION_ATTRIBUTE_NAME)) {
-// String url = attribute.getValue();
-// if (url != null && url.trim().length() > 0) {
-// try {
-// javadocLocation = new URL(url);
-// } catch (MalformedURLException e) {
-// JavaPlugin.log(e);
-// }
-// }
-// }
-// }
-// libs[i] = new LibraryLocation(path, srcPath, rootPath, javadocLocation);
-// } else {
-// IStatus status = new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IJavaLaunchConfigurationConstants.ERR_INTERNAL_ERROR, MessageFormat.format(LaunchingMessages.JREContainerInitializer_Classpath_entry__0__does_not_refer_to_an_existing_library__2, new String[]{entry.getPath().toString()}), null);
-// throw new CoreException(status);
-// }
-// } else {
-// IStatus status = new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IJavaLaunchConfigurationConstants.ERR_INTERNAL_ERROR, MessageFormat.format(LaunchingMessages.JREContainerInitializer_Classpath_entry__0__does_not_refer_to_a_library__3, new String[]{entry.getPath().toString()}), null);
-// throw new CoreException(status);
-// }
-// }
-// VMStandin standin = new VMStandin(vm);
-// standin.setLibraryLocations(libs);
-// standin.convertToRealVM();
-// JavaRuntime.saveVMConfiguration();
- }
-
- /**
- * @see org.eclipse.jdt.core.JsGlobalScopeContainerInitializer#getDescription(org.eclipse.core.runtime.IPath, org.eclipse.IJavaScriptProject.core.IJavaProject)
- */
- public String getDescription(IPath containerPath, IJavaScriptProject project) {
- if (containerPath != null && containerPath.segment(0).equals(JavaRuntime.JRE_CONTAINER))
- return LaunchingMessages.JREContainerInitializer_JsECMA_NAME;
-
-// String tag = getExecutionEnvironmentId(containerPath);
-// if (tag == null && containerPath.segmentCount() > 2) {
-// tag = getVMName(containerPath);
-// }
-// if (tag != null) {
-// return MessageFormat.format(LaunchingMessages.JREContainer_JRE_System_Library_1, new String[]{tag});
-// }
-
-// return LaunchingMessages.JREContainerInitializer_Default_System_Library_1;
- return containerPath.lastSegment();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.IJsGlobalScopeContainerInitialzer#getLibraryLocation()
- */
- public LibraryLocation getLibraryLocation() {
- return new SystemLibraryLocation();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer#allowAttachJsDoc()
- */
- public boolean allowAttachJsDoc() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer#containerSuperTypes()
- */
- public String[] containerSuperTypes() {
- return new String[] {LaunchingMessages.JREContainerInitializer_Global,LaunchingMessages.JREContainerInitializer_Object,LaunchingMessages.JREContainerInitializer_Array};
- }
-
- public String getInferenceID() {
- return DefaultInferrenceProvider.ID;
- }
-
-
-}
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
deleted file mode 100644
index 1ccab7b9..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/JavaRuntime.java
+++ /dev/null
@@ -1,2595 +0,0 @@
-/*******************************************************************************
- * 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.launching;
-
-import java.io.File;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-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.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.compiler.libraries.SystemLibraryLocation;
-
-import com.ibm.icu.text.MessageFormat;
-
-/**
- * The central access point for launching support. This class manages
- * the registered VM types contributed through the
- * <code>"org.eclipse.wst.jsdt.launching.vmType"</code> extension point.
- * As well, this class provides VM install change notification,
- * and computes includepaths and source lookup paths for launch
- * configurations.
- * <p>
- * This class provides static methods only; it is not intended to be
- * instantiated or subclassed by clients.
- * </p>
- *
- * 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 final class JavaRuntime {
-
- /**
- * Classpath variable name used for the default JRE's library
- * (value <code>"JRE_LIB"</code>).
- */
- public static final String JRELIB_VARIABLE= "JRE_LIB"; //$NON-NLS-1$
-
- /**
- * Classpath variable name used for the default JRE's library source
- * (value <code>"JRE_SRC"</code>).
- */
- public static final String JRESRC_VARIABLE= "JRE_SRC"; //$NON-NLS-1$
-
- /**
- * Classpath variable name used for the default JRE's library source root
- * (value <code>"JRE_SRCROOT"</code>).
- */
- public static final String JRESRCROOT_VARIABLE= "JRE_SRCROOT"; //$NON-NLS-1$
-
- /**
- * Simple identifier constant (value <code>"runtimeClasspathEntryResolvers"</code>) for the
- * runtime includepath entry resolvers extension point.
- *
- *
- */
- public static final String EXTENSION_POINT_RUNTIME_CLASSPATH_ENTRY_RESOLVERS= "runtimeClasspathEntryResolvers"; //$NON-NLS-1$
-
- /**
- * Simple identifier constant (value <code>"classpathProviders"</code>) for the
- * runtime includepath providers extension point.
- *
- *
- */
- public static final String EXTENSION_POINT_RUNTIME_CLASSPATH_PROVIDERS= "classpathProviders"; //$NON-NLS-1$
-
- /**
- * Simple identifier constant (value <code>"executionEnvironments"</code>) for the
- * execution environments extension point.
- *
- *
- */
- public static final String EXTENSION_POINT_EXECUTION_ENVIRONMENTS= "executionEnvironments"; //$NON-NLS-1$
-
- /**
- * Simple identifier constant (value <code>"vmInstalls"</code>) for the
- * VM installs extension point.
- *
- *
- */
- public static final String EXTENSION_POINT_VM_INSTALLS = "vmInstalls"; //$NON-NLS-1$
-
- /**
- * Classpath container used for a project's JRE
- * (value <code>"org.eclipse.wst.jsdt.launching.JRE_CONTAINER"</code>). A
- * container is resolved in the context of a specific JavaScript project, to one
- * or more system libraries contained in a JRE. The container can have zero
- * or two path segments following the container name. When no segments
- * follow the container name, the workspace default JRE is used to build a
- * project. Otherwise the segments identify a specific JRE used to build a
- * project:
- * <ol>
- * <li>VM Install Type Identifier - identifies the type of JRE used to build the
- * project. For example, the standard VM.</li>
- * <li>VM Install Name - a user defined name that identifies that a specific VM
- * of the above kind. For example, <code>IBM 1.3.1</code>. This information is
- * shared in a projects includepath file, so teams must agree on JRE naming
- * conventions.</li>
- * </ol>
- * <p>
- * Since 3.2, the path may also identify an execution environment as follows:
- * <ol>
- * <li>Execution environment extension point name
- * (value <code>executionEnvironments</code>)</li>
- * <li>Identifier of a contributed execution environment</li>
- * </ol>
- * </p>
- *
- */
- public static final String JRE_CONTAINER ="org.eclipse.wst.jsdt.launching.JRE_CONTAINER"; //$NON-NLS-1$
- public static final String BASE_BROWSER_LIB="org.eclipse.wst.jsdt.launching.baseBrowserLibrary";
-
- /*
- * Default supertype for javascript unit s
- */
- public static final String DEFAULT_SUPER_TYPE ="Global"; //$NON-NLS-1$
-
- public static final String DEFAULT_SUPER_TYPE_LIBRARY = JRE_CONTAINER; //$NON-NLS-1$
- /**
- * A status code indicating that a JRE could not be resolved for a project.
- * When a JRE cannot be resolved for a project by this plug-in's container
- * initializer, an exception is thrown with this status code. A status handler
- * may be registered for this status code. The <code>source</code> object provided
- * to the status handler is the JavaScript project for which the path could not be
- * resolved. The status handler must return an <code>IVMInstall</code> or <code>null</code>.
- * The container resolver will re-set the project's includepath if required.
- *
- *
- */
- public static final int ERR_UNABLE_TO_RESOLVE_JRE = 160;
-
- /**
- * Preference key for launch/connect timeout. VM Runners should honor this timeout
- * value when attempting to launch and connect to a debuggable VM. The value is
- * an int, indicating a number of milliseconds.
- *
- *
- */
- public static final String PREF_CONNECT_TIMEOUT = JavaScriptCore.PLUGIN_ID + ".PREF_CONNECT_TIMEOUT"; //$NON-NLS-1$
-
- /**
- * Preference key for the String of XML that defines all installed VMs.
- *
- *
- */
- public static final String PREF_VM_XML = JavaScriptCore.PLUGIN_ID + ".PREF_VM_XML"; //$NON-NLS-1$
-
- /**
- * Default launch/connect timeout (ms).
- *
- *
- */
- public static final int DEF_CONNECT_TIMEOUT = 20000;
-
- /**
- * Attribute key for a process property. The class
- * <code>org.eclipse.debug.core.model.IProcess</code> allows attaching
- * String properties to processes.
- * The value of this attribute is the command line a process
- * was launched with. Implementers of <code>IVMRunner</code> should use
- * this attribute key to attach the command lines to the processes they create.
- *
- * @deprecated - use <code>IProcess.ATTR_CMDLINE</code>
- */
- public final static String ATTR_CMDLINE= JavaScriptCore.PLUGIN_ID + ".launcher.cmdLine"; //$NON-NLS-1$
-
- /**
- * Attribute key for a includepath attribute referencing a
- * list of shared libraries that should appear on the
- * <code>-Djava.library.path</code> system property.
- * <p>
- * The factory methods <code>newLibraryPathsAttribute(String[])</code>
- * and <code>getLibraryPaths(IIncludePathAttribute)</code> should be used to
- * encode and decode the attribute value.
- * </p>
- * <p>
- * Each string is used to create an <code>IPath</code> using the constructor
- * <code>Path(String)</code>, and may contain <code>IStringVariable</code>'s.
- * Variable substitution is performed on the string prior to constructing
- * a path from the string.
- * If the resulting <code>IPath</code> is a relative path, it is interpreted
- * as relative to the workspace location. If the path is absolute, it is
- * interpreted as an absolute path in the local file system.
- * </p>
- *
- * @see org.eclipse.wst.jsdt.core.IIncludePathAttribute
- */
- public static final String CLASSPATH_ATTR_LIBRARY_PATH_ENTRY = JavaScriptCore.PLUGIN_ID + ".CLASSPATH_ATTR_LIBRARY_PATH_ENTRY"; //$NON-NLS-1$
-
- // lock for vm initialization
- private static Object fgVMLock = new Object();
- private static boolean fgInitializingVMs = false;
-
- private static IVMInstallType[] fgVMTypes= null;
- private static String fgDefaultVMId= null;
-// private static String fgDefaultVMConnectorId = null;
-
- /**
- * Resolvers keyed by variable name, container id,
- * and runtime includepath entry id.
- */
- private static Map fgVariableResolvers = null;
- private static Map fgContainerResolvers = null;
-// private static Map fgRuntimeClasspathEntryResolvers = null;
-
- /**
- * Path providers keyed by id
- */
-// private static Map fgPathProviders = null;
-
- /**
- * Default includepath and source path providers.
- */
-// private static IRuntimeClasspathProvider fgDefaultClasspathProvider = new StandardClasspathProvider();
-// private static IRuntimeClasspathProvider fgDefaultSourcePathProvider = new StandardSourcePathProvider();
-
- /**
- * VM change listeners
- */
- private static ListenerList fgVMListeners = new ListenerList(5);
-
- /**
- * Cache of already resolved projects in container entries. Used to avoid
- * cycles in project dependencies when resolving includepath container entries.
- * Counters used to know when entering/exiting to clear cache
- */
-// private static ThreadLocal fgProjects = new ThreadLocal(); // Lists
-// private static ThreadLocal fgEntryCount = new ThreadLocal(); // Integers
-
- /**
- * Set of IDs of VMs contributed via vmInstalls extension point.
- */
-// private static Set fgContributedVMs = new HashSet();
-
- private static IVMInstall defaultVM;
-
- /**
- * This class contains only static methods, and is not intended
- * to be instantiated.
- */
- private JavaRuntime() {
- }
-
-// /**
-// * Initializes vm type extensions.
-// */
-// private static void initializeVMTypeExtensions() {
-// IExtensionPoint extensionPoint= Platform.getExtensionRegistry().getExtensionPoint(JavaPlugin.getPluginId(), "vmInstallTypes"); //$NON-NLS-1$
-// IConfigurationElement[] configs= extensionPoint.getConfigurationElements();
-// MultiStatus status= new MultiStatus(JavaScriptCore.PLUGIN_ID, IStatus.OK, LaunchingMessages.JavaRuntime_exceptionOccurred, null);
-// fgVMTypes= new IVMInstallType[configs.length];
-//
-// for (int i= 0; i < configs.length; i++) {
-// try {
-// IVMInstallType vmType= (IVMInstallType)configs[i].createExecutableExtension("class"); //$NON-NLS-1$
-// fgVMTypes[i]= vmType;
-// } catch (CoreException e) {
-// status.add(e.getStatus());
-// }
-// }
-// if (!status.isOK()) {
-// //only happens on a CoreException
-// JavaPlugin.log(status);
-// //cleanup null entries in fgVMTypes
-// List temp= new ArrayList(fgVMTypes.length);
-// for (int i = 0; i < fgVMTypes.length; i++) {
-// if(fgVMTypes[i] != null) {
-// temp.add(fgVMTypes[i]);
-// }
-// fgVMTypes= new IVMInstallType[temp.size()];
-// fgVMTypes= (IVMInstallType[])temp.toArray(fgVMTypes);
-// }
-// }
-// }
-
- /**
- * Returns the VM assigned to build the given JavaScript project.
- * The project must exist. The VM assigned to a project is
- * determined from its build path.
- *
- * @param project the project to retrieve the VM from
- * @return the VM instance that is assigned to build the given JavaScript project
- * Returns <code>null</code> if no VM is referenced on the project's build path.
- * @throws CoreException if unable to determine the project's VM install
- */
- public static IVMInstall getVMInstall(IJavaScriptProject project) throws CoreException {
- // check the includepath
- IVMInstall vm = null;
- IIncludePathEntry[] classpath = project.getRawIncludepath();
- IRuntimeClasspathEntryResolver resolver = null;
- for (int i = 0; i < classpath.length; i++) {
- IIncludePathEntry entry = classpath[i];
- switch (entry.getEntryKind()) {
- case IIncludePathEntry.CPE_VARIABLE:
- resolver = getVariableResolver(entry.getPath().segment(0));
- if (resolver != null) {
- vm = resolver.resolveVMInstall(entry);
- }
- break;
- case IIncludePathEntry.CPE_CONTAINER:
- resolver = getContainerResolver(entry.getPath().segment(0));
- if (resolver != null) {
- vm = resolver.resolveVMInstall(entry);
- }
- break;
- }
- if (vm != null) {
- return vm;
- }
- }
- return null;
- }
-
- /**
- * Returns the VM install type with the given unique id.
- * @param id the VM install type unique id
- * @return The VM install type for the given id, or <code>null</code> if no
- * VM install type with the given id is registered.
- */
- public static IVMInstallType getVMInstallType(String id) {
- IVMInstallType[] vmTypes= getVMInstallTypes();
- for (int i= 0; i < vmTypes.length; i++) {
- if (vmTypes[i].getId().equals(id)) {
- return vmTypes[i];
- }
- }
- return null;
- }
-
- /**
- * Sets a VM as the system-wide default VM, and notifies registered VM install
- * change listeners of the change.
- *
- * @param vm The vm to make the default. May be <code>null</code> to clear
- * the default.
- * @param monitor progress monitor or <code>null</code>
- */
- public static void setDefaultVMInstall(IVMInstall vm, IProgressMonitor monitor) throws CoreException {
- setDefaultVMInstall(vm, monitor, true);
- }
-
- /**
- * Sets a VM as the system-wide default VM, and notifies registered VM install
- * change listeners of the change.
- *
- * @param vm The vm to make the default. May be <code>null</code> to clear
- * the default.
- * @param monitor progress monitor or <code>null</code>
- * @param savePreference If <code>true</code>, update workbench preferences to reflect
- * the new default VM.
- *
- */
- public static void setDefaultVMInstall(IVMInstall vm, IProgressMonitor monitor, boolean savePreference) throws CoreException {
- IVMInstall previous = null;
- if (fgDefaultVMId != null) {
- previous = getVMFromCompositeId(fgDefaultVMId);
- }
- fgDefaultVMId= getCompositeIdFromVM(vm);
- if (savePreference) {
- saveVMConfiguration();
- }
- IVMInstall current = null;
- if (fgDefaultVMId != null) {
- current = getVMFromCompositeId(fgDefaultVMId);
- }
- if (previous != current) {
- notifyDefaultVMChanged(previous, current);
- }
- }
-
-// /**
-// * Sets a VM connector as the system-wide default VM. This setting is persisted when
-// * saveVMConfiguration is called.
-// * @param connector The connector to make the default. May be <code>null</code> to clear
-// * the default.
-// * @param monitor The progress monitor to use
-// *
-// * @throws CoreException Thrown if saving the new default setting fails
-// */
-// public static void setDefaultVMConnector(IVMConnector connector, IProgressMonitor monitor) throws CoreException {
-// fgDefaultVMConnectorId= connector.getIdentifier();
-// saveVMConfiguration();
-// }
-
- /**
- * Return the default VM set with <code>setDefaultVM()</code>.
- * @return Returns the default VM. May return <code>null</code> when no default
- * VM was set or when the default VM has been disposed.
- */
- public static IVMInstall getDefaultVMInstall() {
- IVMInstall install= getVMFromCompositeId(getDefaultVMId());
-//TODO: uncommment getInstallLocation()
- if (install != null /* && install.getInstallLocation().exists()*/) {
- return install;
- }
- // if the default JRE goes missing, re-detect
- if (install != null) {
- install.getVMInstallType().disposeVMInstall(install.getId());
- }
- synchronized (fgVMLock) {
- fgDefaultVMId = null;
- fgVMTypes = null;
- initializeVMs();
- }
- return getVMFromCompositeId(getDefaultVMId());
- }
-
-// /**
-// * Return the default VM connector.
-// * @return Returns the default VM connector.
-// *
-// */
-// public static IVMConnector getDefaultVMConnector() {
-// String id = getDefaultVMConnectorId();
-// IVMConnector connector = null;
-// if (id != null) {
-// connector = getVMConnector(id);
-// }
-// if (connector == null) {
-// connector = new SocketAttachConnector();
-// }
-// return connector;
-// }
-
- /**
- * Returns the list of registered VM types. VM types are registered via
- * <code>"org.eclipse.wst.jsdt.launching.vmTypes"</code> extension point.
- * Returns an empty list if there are no registered VM types.
- *
- * @return the list of registered VM types
- */
- public static IVMInstallType[] getVMInstallTypes() {
- initializeVMs();
- return fgVMTypes;
- }
-
- private static String getDefaultVMId() {
- initializeVMs();
- return fgDefaultVMId;
- }
-
-// private static String getDefaultVMConnectorId() {
-// initializeVMs();
-// return fgDefaultVMConnectorId;
-// }
-//
- /**
- * Returns a String that uniquely identifies the specified VM across all VM types.
- *
- * @param vm the instance of IVMInstallType to be identified
- *
- *
- */
- public static String getCompositeIdFromVM(IVMInstall vm) {
- if (vm == null) {
- return null;
- }
- //TODO: implement
- throw new org.eclipse.wst.jsdt.core.UnimplementedException();
-// IVMInstallType vmType= vm.getVMInstallType();
-// String typeID= vmType.getId();
-// CompositeId id= new CompositeId(new String[] { typeID, vm.getId() });
-// return id.toString();
- }
-
- /**
- * Return the VM corresponding to the specified composite Id. The id uniquely
- * identifies a VM across all vm types.
- *
- * @param idString the composite id that specifies an instance of IVMInstall
- *
- *
- */
- public static IVMInstall getVMFromCompositeId(String idString) {
- if (idString == null || idString.length() == 0) {
- return null;
- }
- return defaultVM;
-// CompositeId id= CompositeId.fromString(idString);
-// if (id.getPartCount() == 2) {
-// IVMInstallType vmType= getVMInstallType(id.get(0));
-// if (vmType != null) {
-// return vmType.findVMInstall(id.get(1));
-// }
-// }
-// return null;
- }
-
-// /**
-// * Returns a new runtime includepath entry for the given expression that
-// * may contain string substitution variable references. The resulting expression
-// * refers to an archive (jar or directory) containing class files.
-// *
-// * @param expression an expression that resolves to the location of an archive
-// * @return runtime includepath entry
-// *
-// */
-// public static IRuntimeClasspathEntry newStringVariableClasspathEntry(String expression) {
-// return new VariableClasspathEntry(expression);
-// }
-//
-// /**
-// * Returns a new runtime includepath entry containing the default includepath
-// * for the specified JavaScript project.
-// *
-// * @param project JavaScript project
-// * @return runtime includepath entry
-// *
-// */
-// public static IRuntimeClasspathEntry newDefaultProjectClasspathEntry(IJavaScriptProject project) {
-// return new DefaultProjectClasspathEntry(project);
-// }
-
- /**
- * Returns a new runtime includepath entry for the given project.
- *
- * @param project JavaScript project
- * @return runtime includepath entry
- *
- */
- public static IRuntimeClasspathEntry newProjectRuntimeClasspathEntry(IJavaScriptProject project) {
- IIncludePathEntry cpe = JavaScriptCore.newProjectEntry(project.getProject().getFullPath());
- return newRuntimeClasspathEntry(cpe);
- }
-
-
- /**
- * Returns a new runtime includepath entry for the given archive.
- *
- * @param resource archive resource
- * @return runtime includepath entry
- *
- */
- public static IRuntimeClasspathEntry newArchiveRuntimeClasspathEntry(IResource resource) {
- IIncludePathEntry cpe = JavaScriptCore.newLibraryEntry(resource.getFullPath(), null, null);
- return newRuntimeClasspathEntry(cpe);
- }
-
- /**
- * Returns a new runtime includepath entry for the given archive (possibly
- * external).
- *
- * @param path absolute path to an archive
- * @return runtime includepath entry
- *
- */
- public static IRuntimeClasspathEntry newArchiveRuntimeClasspathEntry(IPath path) {
- IIncludePathEntry cpe = JavaScriptCore.newLibraryEntry(path, null, null);
- return newRuntimeClasspathEntry(cpe);
- }
-
- /**
- * Returns a new runtime includepath entry for the includepath
- * variable with the given path.
- *
- * @param path variable path; first segment is the name of the variable;
- * trailing segments are appended to the resolved variable value
- * @return runtime includepath entry
- *
- */
- public static IRuntimeClasspathEntry newVariableRuntimeClasspathEntry(IPath path) {
- IIncludePathEntry cpe = JavaScriptCore.newVariableEntry(path, null, null);
- return newRuntimeClasspathEntry(cpe);
- }
-
- /**
- * Returns a runtime includepath entry for the given container path with the given
- * includepath property.
- *
- * @param path container path
- * @param includepathProperty the type of entry - one of <code>USER_CLASSES</code>,
- * <code>BOOTSTRAP_CLASSES</code>, or <code>STANDARD_CLASSES</code>
- * @return runtime includepath entry
- * @exception CoreException if unable to construct a runtime includepath entry
- *
- */
- public static IRuntimeClasspathEntry newRuntimeContainerClasspathEntry(IPath path, int classpathProperty) throws CoreException {
- return newRuntimeContainerClasspathEntry(path, classpathProperty, null);
- }
-
- /**
- * Returns a runtime includepath entry for the given container path with the given
- * includepath property to be resolved in the context of the given JavaScript project.
- *
- * @param path container path
- * @param includepathProperty the type of entry - one of <code>USER_CLASSES</code>,
- * <code>BOOTSTRAP_CLASSES</code>, or <code>STANDARD_CLASSES</code>
- * @param project JavaScript project context used for resolution, or <code>null</code>
- * if to be resolved in the context of the launch configuration this entry
- * is referenced in
- * @return runtime includepath entry
- * @exception CoreException if unable to construct a runtime includepath entry
- *
- */
- public static IRuntimeClasspathEntry newRuntimeContainerClasspathEntry(IPath path, int classpathProperty, IJavaScriptProject project) throws CoreException {
-// IIncludePathEntry cpe = JavaScriptCore.newContainerEntry(path);
-// RuntimeClasspathEntry entry = new RuntimeClasspathEntry(cpe, classpathProperty);
-// entry.setJavaProject(project);
-// return entry;
- //TODO: implement
- throw new org.eclipse.wst.jsdt.core.UnimplementedException();
- }
-
- /**
- * Returns a runtime includepath entry constructed from the given memento.
- *
- * @param memento a memento for a runtime includepath entry
- * @return runtime includepath entry
- * @exception CoreException if unable to construct a runtime includepath entry
- *
- */
- public static IRuntimeClasspathEntry newRuntimeClasspathEntry(String memento) throws CoreException {
-// try {
-// Element root = null;
-// DocumentBuilder parser = LaunchingPlugin.getParser();
-// StringReader reader = new StringReader(memento);
-// InputSource source = new InputSource(reader);
-// root = parser.parse(source).getDocumentElement();
-//
-// String id = root.getAttribute("id"); //$NON-NLS-1$
-// if (id == null || id.length() == 0) {
-// // assume an old format
-// return new RuntimeClasspathEntry(root);
-// }
-// // get the extension & create a new one
-// IRuntimeClasspathEntry2 entry = LaunchingPlugin.getDefault().newRuntimeClasspathEntry(id);
-// NodeList list = root.getChildNodes();
-// for (int i = 0; i < list.getLength(); i++) {
-// Node node = list.item(i);
-// if (node.getNodeType() == Node.ELEMENT_NODE) {
-// Element element = (Element)node;
-// if ("memento".equals(element.getNodeName())) { //$NON-NLS-1$
-// entry.initializeFrom(element);
-// }
-// }
-// }
-// return entry;
-// } catch (SAXException e) {
-// abort(LaunchingMessages.JavaRuntime_31, e);
-// } catch (IOException e) {
-// abort(LaunchingMessages.JavaRuntime_32, e);
-// }
-// return null;
- //TODO: implement
- throw new org.eclipse.wst.jsdt.core.UnimplementedException();
- }
-
- /**
- * Returns a runtime includepath entry that corresponds to the given
- * includepath entry. The includepath entry may not be of type <code>CPE_SOURCE</code>
- * or <code>CPE_CONTAINER</code>.
- *
- * @param entry a includepath entry
- * @return runtime includepath entry
- *
- */
- private static IRuntimeClasspathEntry newRuntimeClasspathEntry(IIncludePathEntry entry) {
-// return new RuntimeClasspathEntry(entry);
- //TODO: implement
- throw new org.eclipse.wst.jsdt.core.UnimplementedException();
- }
-
- /**
- * Computes and returns the default unresolved runtime includepath for the
- * given project.
- *
- * @return runtime includepath entries
- * @exception CoreException if unable to compute the runtime includepath
- * @see IRuntimeClasspathEntry
- *
- */
- public static IRuntimeClasspathEntry[] computeUnresolvedRuntimeClasspath(IJavaScriptProject project) throws CoreException {
-// IIncludePathEntry[] entries = project.getRawClasspath();
-// List includepathEntries = new ArrayList(3);
-// for (int i = 0; i < entries.length; i++) {
-// IIncludePathEntry entry = entries[i];
-// switch (entry.getEntryKind()) {
-// case IIncludePathEntry.CPE_CONTAINER:
-// IJsGlobalScopeContainer container = JavaScriptCore.getJsGlobalScopeContainer(entry.getPath(), project);
-// if (container != null) {
-// switch (container.getKind()) {
-// case IJsGlobalScopeContainer.K_APPLICATION:
-// // don't look at application entries
-// break;
-// case IJsGlobalScopeContainer.K_DEFAULT_SYSTEM:
-// includepathEntries.add(newRuntimeContainerClasspathEntry(container.getPath(), IRuntimeClasspathEntry.STANDARD_CLASSES, project));
-// break;
-// case IJsGlobalScopeContainer.K_SYSTEM:
-// includepathEntries.add(newRuntimeContainerClasspathEntry(container.getPath(), IRuntimeClasspathEntry.BOOTSTRAP_CLASSES, project));
-// break;
-// }
-// }
-// break;
-// case IIncludePathEntry.CPE_VARIABLE:
-// if (JRELIB_VARIABLE.equals(entry.getPath().segment(0))) {
-// IRuntimeClasspathEntry jre = newVariableRuntimeClasspathEntry(entry.getPath());
-// jre.setClasspathProperty(IRuntimeClasspathEntry.STANDARD_CLASSES);
-// includepathEntries.add(jre);
-// }
-// break;
-// default:
-// break;
-// }
-// }
-// includepathEntries.add(newDefaultProjectClasspathEntry(project));
-// return (IRuntimeClasspathEntry[]) includepathEntries.toArray(new IRuntimeClasspathEntry[includepathEntries.size()]);
-//
-//TODO: implement
-throw new org.eclipse.wst.jsdt.core.UnimplementedException();
- }
-
-// /**
-// * Computes and returns the unresolved source lookup path for the given launch
-// * configuration.
-// *
-// * @param configuration launch configuration
-// * @return runtime includepath entries
-// * @exception CoreException if unable to compute the source lookup path
-// *
-// */
-// public static IRuntimeClasspathEntry[] computeUnresolvedSourceLookupPath(ILaunchConfiguration configuration) throws CoreException {
-// return getSourceLookupPathProvider(configuration).computeUnresolvedClasspath(configuration);
-// }
-//
-// /**
-// * Resolves the given source lookup path, returning the resolved source lookup path
-// * in the context of the given launch configuration.
-// *
-// * @param entries unresolved entries
-// * @param configuration launch configuration
-// * @return resolved entries
-// * @exception CoreException if unable to resolve the source lookup path
-// *
-// */
-// public static IRuntimeClasspathEntry[] resolveSourceLookupPath(IRuntimeClasspathEntry[] entries, ILaunchConfiguration configuration) throws CoreException {
-// return getSourceLookupPathProvider(configuration).resolveClasspath(entries, configuration);
-// }
-//
-// /**
-// * Returns the includepath provider for the given launch configuration.
-// *
-// * @param configuration launch configuration
-// * @return includepath provider
-// * @exception CoreException if unable to resolve the path provider
-// *
-// */
-// public static IRuntimeClasspathProvider getClasspathProvider(ILaunchConfiguration configuration) throws CoreException {
-// String providerId = configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_CLASSPATH_PROVIDER, (String)null);
-// IRuntimeClasspathProvider provider = null;
-// if (providerId == null) {
-// provider = fgDefaultClasspathProvider;
-// } else {
-// provider = (IRuntimeClasspathProvider)getClasspathProviders().get(providerId);
-// if (provider == null) {
-// abort(MessageFormat.format(LaunchingMessages.JavaRuntime_26, new String[]{providerId}), null);
-// }
-// }
-// return provider;
-// }
-//
-// /**
-// * Returns the source lookup path provider for the given launch configuration.
-// *
-// * @param configuration launch configuration
-// * @return source lookup path provider
-// * @exception CoreException if unable to resolve the path provider
-// *
-// */
-// public static IRuntimeClasspathProvider getSourceLookupPathProvider(ILaunchConfiguration configuration) throws CoreException {
-// String providerId = configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_SOURCE_PATH_PROVIDER, (String)null);
-// IRuntimeClasspathProvider provider = null;
-// if (providerId == null) {
-// provider = fgDefaultSourcePathProvider;
-// } else {
-// provider = (IRuntimeClasspathProvider)getClasspathProviders().get(providerId);
-// if (provider == null) {
-// abort(MessageFormat.format(LaunchingMessages.JavaRuntime_27, new String[]{providerId}), null);
-// }
-// }
-// return provider;
-// }
-
- /**
- * Returns resolved entries for the given entry in the context of the given
- * launch configuration. If the entry is of kind
- * <code>VARIABLE</code> or <code>CONTAINER</code>, variable and container
- * resolvers are consulted. If the entry is of kind <code>PROJECT</code>,
- * and the associated JavaScript project specifies non-default output locations,
- * the corresponding output locations are returned. Otherwise, the given
- * entry is returned.
- * <p>
- * If the given entry is a variable entry, and a resolver is not registered,
- * the entry itself is returned. If the given entry is a container, and a
- * resolver is not registered, resolved runtime includepath entries are calculated
- * from the associated container includepath entries, in the context of the project
- * associated with the given launch configuration.
- * </p>
- * @param entry runtime includepath entry
- * @param configuration launch configuration
- * @return resolved runtime includepath entry
- * @exception CoreException if unable to resolve
- * @see IRuntimeClasspathEntryResolver
- *
- */
- public static IRuntimeClasspathEntry[] resolveRuntimeClasspathEntry(IRuntimeClasspathEntry entry, ILaunchConfiguration configuration) throws CoreException {
- //TODO: implement
- throw new org.eclipse.wst.jsdt.core.UnimplementedException();
-// switch (entry.getType()) {
-// case IRuntimeClasspathEntry.PROJECT:
-// // if the project has multiple output locations, they must be returned
-// IResource resource = entry.getResource();
-// if (resource instanceof IProject) {
-// IProject p = (IProject)resource;
-// IJavaScriptProject project = JavaScriptCore.create(p);
-// if (project == null || !p.isOpen() || !project.exists()) {
-// return new IRuntimeClasspathEntry[0];
-// }
-// IRuntimeClasspathEntry[] entries = resolveOutputLocations(project, entry.getClasspathProperty());
-// if (entries != null) {
-// return entries;
-// }
-// } else {
-// // could not resolve project
-// abort(MessageFormat.format(LaunchingMessages.JavaRuntime_Classpath_references_non_existant_project___0__3, new String[]{entry.getPath().lastSegment()}), null);
-// }
-// break;
-// case IRuntimeClasspathEntry.VARIABLE:
-// IRuntimeClasspathEntryResolver resolver = getVariableResolver(entry.getVariableName());
-// if (resolver == null) {
-// IRuntimeClasspathEntry[] resolved = resolveVariableEntry(entry, null, configuration);
-// if (resolved != null) {
-// return resolved;
-// }
-// break;
-// }
-// return resolver.resolveRuntimeClasspathEntry(entry, configuration);
-// case IRuntimeClasspathEntry.CONTAINER:
-// resolver = getContainerResolver(entry.getVariableName());
-// if (resolver == null) {
-// return computeDefaultContainerEntries(entry, configuration);
-// }
-// return resolver.resolveRuntimeClasspathEntry(entry, configuration);
-// case IRuntimeClasspathEntry.ARCHIVE:
-// // verify the archive exists
-// String location = entry.getLocation();
-// if (location == null) {
-// abort(MessageFormat.format(LaunchingMessages.JavaRuntime_Classpath_references_non_existant_archive___0__4, new String[]{entry.getPath().toString()}), null);
-// }
-// File file = new File(location);
-// if (!file.exists()) {
-// abort(MessageFormat.format(LaunchingMessages.JavaRuntime_Classpath_references_non_existant_archive___0__4, new String[]{entry.getPath().toString()}), null);
-// }
-// break;
-// case IRuntimeClasspathEntry.OTHER:
-// resolver = getContributedResolver(((IRuntimeClasspathEntry2)entry).getTypeId());
-// return resolver.resolveRuntimeClasspathEntry(entry, configuration);
-// default:
-// break;
-// }
-// return new IRuntimeClasspathEntry[] {entry};
- }
-
-// /**
-// * Default resolution for a includepath variable - resolve to an archive. Only
-// * one of project/configuration can be non-null.
-// *
-// * @param entry
-// * @param project the project context or <code>null</code>
-// * @param configuration configuration context or <code>null</code>
-// * @return IRuntimeClasspathEntry[]
-// * @throws CoreException
-// */
-// private static IRuntimeClasspathEntry[] resolveVariableEntry(IRuntimeClasspathEntry entry, IJavaScriptProject project, ILaunchConfiguration configuration) throws CoreException {
-// // default resolution - an archive
-// IPath archPath = JavaScriptCore.getClasspathVariable(entry.getVariableName());
-// if (archPath != null) {
-// if (entry.getPath().segmentCount() > 1) {
-// archPath = archPath.append(entry.getPath().removeFirstSegments(1));
-// }
-// IPath srcPath = null;
-// IPath srcVar = entry.getSourceAttachmentPath();
-// IPath srcRootPath = null;
-// IPath srcRootVar = entry.getSourceAttachmentRootPath();
-// if (archPath != null && !archPath.isEmpty()) {
-// if (srcVar != null && !srcVar.isEmpty()) {
-// srcPath = JavaScriptCore.getClasspathVariable(srcVar.segment(0));
-// if (srcPath != null) {
-// if (srcVar.segmentCount() > 1) {
-// srcPath = srcPath.append(srcVar.removeFirstSegments(1));
-// }
-// if (srcRootVar != null && !srcRootVar.isEmpty()) {
-// srcRootPath = JavaScriptCore.getClasspathVariable(srcRootVar.segment(0));
-// if (srcRootPath != null) {
-// if (srcRootVar.segmentCount() > 1) {
-// srcRootPath = srcRootPath.append(srcRootVar.removeFirstSegments(1));
-// }
-// }
-// }
-// }
-// }
-// // now resolve the archive (recursively)
-// IIncludePathEntry archEntry = JavaScriptCore.newLibraryEntry(archPath, srcPath, srcRootPath, entry.getClasspathEntry().isExported());
-// IRuntimeClasspathEntry runtimeArchEntry = newRuntimeClasspathEntry(archEntry);
-// runtimeArchEntry.setClasspathProperty(entry.getClasspathProperty());
-// if (configuration == null) {
-// return resolveRuntimeClasspathEntry(runtimeArchEntry, project);
-// }
-// return resolveRuntimeClasspathEntry(runtimeArchEntry, configuration);
-// }
-// }
-// return null;
-// }
-//
-// /**
-// * Returns runtime includepath entries corresponding to the output locations
-// * of the given project, or null if the project only uses the default
-// * output location.
-// *
-// * @param project
-// * @param includepathProperty the type of includepath entries to create
-// * @return IRuntimeClasspathEntry[] or <code>null</code>
-// * @throws CoreException
-// */
-// private static IRuntimeClasspathEntry[] resolveOutputLocations(IJavaScriptProject project, int includepathProperty) throws CoreException {
-// List nonDefault = new ArrayList();
-// if (project.exists() && project.getProject().isOpen()) {
-// IIncludePathEntry entries[] = project.getRawClasspath();
-// for (int i = 0; i < entries.length; i++) {
-// IIncludePathEntry includepathEntry = entries[i];
-// if (includepathEntry.getEntryKind() == IIncludePathEntry.CPE_SOURCE) {
-// IPath path = includepathEntry.getOutputLocation();
-// if (path != null) {
-// nonDefault.add(path);
-// }
-// }
-// }
-// }
-// if (nonDefault.isEmpty()) {
-// return null;
-// }
-// // add the default location if not already included
-// IPath def = project.getOutputLocation();
-// if (!nonDefault.contains(def)) {
-// nonDefault.add(def);
-// }
-// IRuntimeClasspathEntry[] locations = new IRuntimeClasspathEntry[nonDefault.size()];
-// for (int i = 0; i < locations.length; i++) {
-// IIncludePathEntry newEntry = JavaScriptCore.newLibraryEntry((IPath)nonDefault.get(i), null, null);
-// locations[i] = new RuntimeClasspathEntry(newEntry);
-// locations[i].setClasspathProperty(includepathProperty);
-// }
-// return locations;
-// }
-
- /**
- * Returns resolved entries for the given entry in the context of the given
- * JavaScript project. If the entry is of kind
- * <code>VARIABLE</code> or <code>CONTAINER</code>, variable and container
- * resolvers are consulted. If the entry is of kind <code>PROJECT</code>,
- * and the associated JavaScript project specifies non-default output locations,
- * the corresponding output locations are returned. Otherwise, the given
- * entry is returned.
- * <p>
- * If the given entry is a variable entry, and a resolver is not registered,
- * the entry itself is returned. If the given entry is a container, and a
- * resolver is not registered, resolved runtime includepath entries are calculated
- * from the associated container includepath entries, in the context of the
- * given project.
- * </p>
- * @param entry runtime includepath entry
- * @param project JavaScript project context
- * @return resolved runtime includepath entry
- * @exception CoreException if unable to resolve
- * @see IRuntimeClasspathEntryResolver
- *
- */
- public static IRuntimeClasspathEntry[] resolveRuntimeClasspathEntry(IRuntimeClasspathEntry entry, IJavaScriptProject project) throws CoreException {
-// switch (entry.getType()) {
-// case IRuntimeClasspathEntry.PROJECT:
-// // if the project has multiple output locations, they must be returned
-// IResource resource = entry.getResource();
-// if (resource instanceof IProject) {
-// IProject p = (IProject)resource;
-// IJavaScriptProject jp = JavaScriptCore.create(p);
-// if (jp != null && p.isOpen() && jp.exists()) {
-// IRuntimeClasspathEntry[] entries = resolveOutputLocations(jp, entry.getClasspathProperty());
-// if (entries != null) {
-// return entries;
-// }
-// } else {
-// return new IRuntimeClasspathEntry[0];
-// }
-// }
-// break;
-// case IRuntimeClasspathEntry.VARIABLE:
-// IRuntimeClasspathEntryResolver resolver = getVariableResolver(entry.getVariableName());
-// if (resolver == null) {
-// IRuntimeClasspathEntry[] resolved = resolveVariableEntry(entry, project, null);
-// if (resolved != null) {
-// return resolved;
-// }
-// break;
-// }
-// return resolver.resolveRuntimeClasspathEntry(entry, project);
-// case IRuntimeClasspathEntry.CONTAINER:
-// resolver = getContainerResolver(entry.getVariableName());
-// if (resolver == null) {
-// return computeDefaultContainerEntries(entry, project);
-// }
-// return resolver.resolveRuntimeClasspathEntry(entry, project);
-// case IRuntimeClasspathEntry.OTHER:
-// resolver = getContributedResolver(((IRuntimeClasspathEntry2)entry).getTypeId());
-// return resolver.resolveRuntimeClasspathEntry(entry, project);
-// default:
-// break;
-// }
-// return new IRuntimeClasspathEntry[] {entry};
- //TODO: implement
- throw new org.eclipse.wst.jsdt.core.UnimplementedException();
- }
-
- /**
- * Performs default resolution for a container entry.
- * Delegates to the JavaScript model.
- */
-// private static IRuntimeClasspathEntry[] computeDefaultContainerEntries(IRuntimeClasspathEntry entry, ILaunchConfiguration config) throws CoreException {
-// IJavaScriptProject project = entry.getJavaProject();
-// if (project == null) {
-// project = getJavaProject(config);
-// }
-// return computeDefaultContainerEntries(entry, project);
-// }
-
- /**
- * Performs default resolution for a container entry.
- * Delegates to the JavaScript model.
- */
-// private static IRuntimeClasspathEntry[] computeDefaultContainerEntries(IRuntimeClasspathEntry entry, IJavaScriptProject project) throws CoreException {
-// //TODO: implement
-// throw new org.eclipse.wst.jsdt.core.UnimplementedException();
-//// if (project == null || entry == null) {
-//// // cannot resolve without entry or project context
-//// return new IRuntimeClasspathEntry[0];
-//// }
-//// IJsGlobalScopeContainer container = JavaScriptCore.getJsGlobalScopeContainer(entry.getPath(), project);
-//// if (container == null) {
-//// abort(MessageFormat.format(LaunchingMessages.JavaRuntime_Could_not_resolve_includepath_container___0__1, new String[]{entry.getPath().toString()}), null);
-//// // execution will not reach here - exception will be thrown
-//// return null;
-//// }
-//// IIncludePathEntry[] cpes = container.getClasspathEntries();
-//// int property = -1;
-//// switch (container.getKind()) {
-//// case IJsGlobalScopeContainer.K_APPLICATION:
-//// property = IRuntimeClasspathEntry.USER_CLASSES;
-//// break;
-//// case IJsGlobalScopeContainer.K_DEFAULT_SYSTEM:
-//// property = IRuntimeClasspathEntry.STANDARD_CLASSES;
-//// break;
-//// case IJsGlobalScopeContainer.K_SYSTEM:
-//// property = IRuntimeClasspathEntry.BOOTSTRAP_CLASSES;
-//// break;
-//// }
-//// List resolved = new ArrayList(cpes.length);
-//// List projects = (List) fgProjects.get();
-//// Integer count = (Integer) fgEntryCount.get();
-//// if (projects == null) {
-//// projects = new ArrayList();
-//// fgProjects.set(projects);
-//// count = new Integer(0);
-//// }
-//// int intCount = count.intValue();
-//// intCount++;
-//// fgEntryCount.set(new Integer(intCount));
-//// try {
-//// for (int i = 0; i < cpes.length; i++) {
-//// IIncludePathEntry cpe = cpes[i];
-//// if (cpe.getEntryKind() == IIncludePathEntry.CPE_PROJECT) {
-//// IProject p = ResourcesPlugin.getWorkspace().getRoot().getProject(cpe.getPath().segment(0));
-//// IJavaScriptProject jp = JavaScriptCore.create(p);
-//// if (!projects.contains(jp)) {
-//// projects.add(jp);
-//// IRuntimeClasspathEntry includepath = newDefaultProjectClasspathEntry(jp);
-//// IRuntimeClasspathEntry[] entries = resolveRuntimeClasspathEntry(includepath, jp);
-//// for (int j = 0; j < entries.length; j++) {
-//// IRuntimeClasspathEntry e = entries[j];
-//// if (!resolved.contains(e)) {
-//// resolved.add(entries[j]);
-//// }
-//// }
-//// }
-//// } else {
-//// IRuntimeClasspathEntry e = newRuntimeClasspathEntry(cpe);
-//// if (!resolved.contains(e)) {
-//// resolved.add(e);
-//// }
-//// }
-//// }
-//// } finally {
-//// intCount--;
-//// if (intCount == 0) {
-//// fgProjects.set(null);
-//// fgEntryCount.set(null);
-//// } else {
-//// fgEntryCount.set(new Integer(intCount));
-//// }
-//// }
-//// // set includepath property
-//// IRuntimeClasspathEntry[] result = new IRuntimeClasspathEntry[resolved.size()];
-//// for (int i = 0; i < result.length; i++) {
-//// result[i] = (IRuntimeClasspathEntry) resolved.get(i);
-//// result[i].setClasspathProperty(property);
-//// }
-//// return result;
-// }
-
- /**
- * Computes and returns the unresolved class path for the given launch configuration.
- * Variable and container entries are unresolved.
- *
- * @param configuration launch configuration
- * @return unresolved runtime includepath entries
- * @exception CoreException if unable to compute the includepath
- *
- */
- public static IRuntimeClasspathEntry[] computeUnresolvedRuntimeClasspath(ILaunchConfiguration configuration) throws CoreException {
-// return getClasspathProvider(configuration).computeUnresolvedClasspath(configuration);
- //TODO: implement
- throw new org.eclipse.wst.jsdt.core.UnimplementedException();
-
- }
-
- /**
- * Resolves the given includepath, returning the resolved includepath
- * in the context of the given launch configuration.
- *
- * @param entries unresolved includepath
- * @param configuration launch configuration
- * @return resolved runtime includepath entries
- * @exception CoreException if unable to compute the includepath
- *
- */
- public static IRuntimeClasspathEntry[] resolveRuntimeClasspath(IRuntimeClasspathEntry[] entries, ILaunchConfiguration configuration) throws CoreException {
-// TODO: implement
- throw new org.eclipse.wst.jsdt.core.UnimplementedException();
-// return getClasspathProvider(configuration).resolveClasspath(entries, configuration);
- }
-
- /**
- * Return the <code>IJavaScriptProject</code> referenced in the specified configuration or
- * <code>null</code> if none.
- *
- * @exception CoreException if the referenced JavaScript project does not exist
- *
- */
- public static IJavaScriptProject getJavaProject(ILaunchConfiguration configuration) throws CoreException {
-////TODO: implement
-//throw new org.eclipse.wst.jsdt.core.UnimplementedException();
- String projectName = configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, (String)null);
- if ((projectName == null) || (projectName.trim().length() < 1)) {
- return null;
- }
- IJavaScriptProject javaProject = getJavaModel().getJavaScriptProject(projectName);
- if (javaProject != null && javaProject.getProject().exists() && !javaProject.getProject().isOpen()) {
- abort(MessageFormat.format(LaunchingMessages.JavaRuntime_28, new String[] {configuration.getName(), projectName}), IJavaLaunchConfigurationConstants.ERR_PROJECT_CLOSED, null);
- }
- if ((javaProject == null) || !javaProject.exists()) {
- abort(MessageFormat.format(LaunchingMessages.JavaRuntime_Launch_configuration__0__references_non_existing_project__1___1, new String[] {configuration.getName(), projectName}), IJavaLaunchConfigurationConstants.ERR_NOT_A_JAVA_PROJECT, null);
- }
- return javaProject;
- }
-
- /**
- * Convenience method to get the javascript model.
- */
- private static IJavaScriptModel getJavaModel() {
- return JavaScriptCore.create(ResourcesPlugin.getWorkspace().getRoot());
- }
-
- /**
- * Returns the VM install for the given launch configuration.
- * The VM install is determined in the following prioritized way:
- * <ol>
- * <li>The VM install is explicitly specified on the launch configuration
- * via the <code>ATTR_JRE_CONTAINER_PATH</code> attribute (since 3.2).</li>
- * <li>The VM install is explicitly specified on the launch configuration
- * via the <code>ATTR_VM_INSTALL_TYPE</code> and <code>ATTR_VM_INSTALL_ID</code>
- * attributes.</li>
- * <li>If no explicit VM install is specified, the VM install associated with
- * the launch configuration's project is returned.</li>
- * <li>If no project is specified, or the project does not specify a custom
- * VM install, the workspace default VM install is returned.</li>
- * </ol>
- *
- * @param configuration launch configuration
- * @return vm install
- * @exception CoreException if unable to compute a vm install
- *
- */
- public static IVMInstall computeVMInstall(ILaunchConfiguration configuration) throws CoreException {
- String jreAttr = configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_JRE_CONTAINER_PATH, (String)null);
- if (jreAttr == null) {
- String type = configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_INSTALL_TYPE, (String)null);
- if (type == null) {
- IJavaScriptProject proj = getJavaProject(configuration);
- if (proj != null) {
- IVMInstall vm = getVMInstall(proj);
- if (vm != null) {
- return vm;
- }
- }
- } else {
- String name = configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_INSTALL_NAME, (String)null);
- return resolveVM(type, name, configuration);
- }
- } else {
- IPath jrePath = Path.fromPortableString(jreAttr);
- IIncludePathEntry entry = JavaScriptCore.newContainerEntry(jrePath);
- IRuntimeClasspathEntryResolver2 resolver = getVariableResolver(jrePath.segment(0));
- if (resolver != null) {
- return resolver.resolveVMInstall(entry);
- } else {
- resolver = getContainerResolver(jrePath.segment(0));
- if (resolver != null) {
- return resolver.resolveVMInstall(entry);
- }
- }
- }
-
- return getDefaultVMInstall();
- }
- /**
- * Returns the VM of the given type with the specified name.
- *
- * @param type vm type identifier
- * @param name vm name
- * @return vm install
- * @exception CoreException if unable to resolve
- *
- */
- private static IVMInstall resolveVM(String type, String name, ILaunchConfiguration configuration) throws CoreException {
- IVMInstallType vt = getVMInstallType(type);
- if (vt == null) {
- // error type does not exist
- abort(MessageFormat.format(LaunchingMessages.JavaRuntime_Specified_VM_install_type_does_not_exist___0__2, new String[] {type}), null);
- }
- IVMInstall vm = null;
- // look for a name
- if (name == null) {
- // error - type specified without a specific install (could be an old config that specified a VM ID)
- // log the error, but choose the default VM.
- IStatus status = new Status(IStatus.WARNING, JavaScriptCore.PLUGIN_ID, IJavaLaunchConfigurationConstants.ERR_UNSPECIFIED_VM_INSTALL, MessageFormat.format(LaunchingMessages.JavaRuntime_VM_not_fully_specified_in_launch_configuration__0____missing_VM_name__Reverting_to_default_VM__1, new String[] {configuration.getName()}), null);
- JavaScriptCore.getPlugin().getLog().log(status);
- return getDefaultVMInstall();
- }
- vm = vt.findVMInstallByName(name);
- if (vm == null) {
- // error - install not found
- abort(MessageFormat.format(LaunchingMessages.JavaRuntime_Specified_VM_install_not_found__type__0___name__1__2, new String[] {vt.getName(), name}), null);
- } else {
- return vm;
- }
- // won't reach here
- return null;
- }
-
- /**
- * Throws a core exception with an internal error status.
- *
- * @param message the status message
- * @param exception lower level exception associated with the
- * error, or <code>null</code> if none
- */
- private static void abort(String message, Throwable exception) throws CoreException {
- abort(message, IJavaLaunchConfigurationConstants.ERR_INTERNAL_ERROR, exception);
- }
-
-
- /**
- * Throws a core exception with an internal error status.
- *
- * @param message the status message
- * @param code status code
- * @param exception lower level exception associated with the
- *
- * error, or <code>null</code> if none
- */
- private static void abort(String message, int code, Throwable exception) throws CoreException {
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, code, message, exception));
- }
-
- /**
- * Computes the default application includepath entries for the given
- * project.
- *
- * @param jproject The project to compute the includepath for
- * @return The computed includepath. May be empty, but not null.
- * @throws CoreException if unable to compute the default includepath
- */
- public static String[] computeDefaultRuntimeClassPath(IJavaScriptProject jproject) throws CoreException {
- IRuntimeClasspathEntry[] unresolved = computeUnresolvedRuntimeClasspath(jproject);
- // 1. remove bootpath entries
- // 2. resolve & translate to local file system paths
- List resolved = new ArrayList(unresolved.length);
- for (int i = 0; i < unresolved.length; i++) {
- IRuntimeClasspathEntry entry = unresolved[i];
- if (entry.getClasspathProperty() == IRuntimeClasspathEntry.USER_CLASSES) {
- IRuntimeClasspathEntry[] entries = resolveRuntimeClasspathEntry(entry, jproject);
- for (int j = 0; j < entries.length; j++) {
- String location = entries[j].getLocation();
- if (location != null) {
- resolved.add(location);
- }
- }
- }
- }
- return (String[])resolved.toArray(new String[resolved.size()]);
- }
-
- /**
- * Saves the VM configuration information to the preferences. This includes
- * the following information:
- * <ul>
- * <li>The list of all defined IVMInstall instances.</li>
- * <li>The default VM</li>
- * <ul>
- * This state will be read again upon first access to VM
- * configuration information.
- */
- public static void saveVMConfiguration() throws CoreException {
- if (fgVMTypes == null) {
- // if the VM types have not been instantiated, there can be no changes.
- return;
- }
- //TODO: implement
- throw new org.eclipse.wst.jsdt.core.UnimplementedException();
-// try {
-// String xml = getVMsAsXML();
-// getPreferences().setValue(PREF_VM_XML, xml);
-// savePreferences();
-// } catch (IOException e) {
-// throw new CoreException(new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, IStatus.ERROR, LaunchingMessages.JavaRuntime_exceptionsOccurred, e));
-// } catch (ParserConfigurationException e) {
-// throw new CoreException(new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, IStatus.ERROR, LaunchingMessages.JavaRuntime_exceptionsOccurred, e));
-// } catch (TransformerException e) {
-// throw new CoreException(new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, IStatus.ERROR, LaunchingMessages.JavaRuntime_exceptionsOccurred, e));
-// }
- }
-
-// private static String getVMsAsXML() throws IOException, ParserConfigurationException, TransformerException {
-// VMDefinitionsContainer container = new VMDefinitionsContainer();
-// container.setDefaultVMInstallCompositeID(getDefaultVMId());
-// container.setDefaultVMInstallConnectorTypeID(getDefaultVMConnectorId());
-// IVMInstallType[] vmTypes= getVMInstallTypes();
-// for (int i = 0; i < vmTypes.length; ++i) {
-// IVMInstall[] vms = vmTypes[i].getVMInstalls();
-// for (int j = 0; j < vms.length; j++) {
-// IVMInstall install = vms[j];
-// container.addVM(install);
-// }
-// }
-// return container.getAsXML();
-// }
-//
-// /**
-// * This method loads installed JREs based an existing user preference
-// * or old vm configurations file. The VMs found in the preference
-// * or vm configurations file are added to the given VM definitions container.
-// *
-// * Returns whether the user preferences should be set - i.e. if it was
-// * not already set when initialized.
-// */
-// private static boolean addPersistedVMs(VMDefinitionsContainer vmDefs) throws IOException {
-// // Try retrieving the VM preferences from the preference store
-// String vmXMLString = getPreferences().getString(PREF_VM_XML);
-//
-// // If the preference was found, load VMs from it into memory
-// if (vmXMLString.length() > 0) {
-// try {
-// ByteArrayInputStream inputStream = new ByteArrayInputStream(vmXMLString.getBytes());
-// VMDefinitionsContainer.parseXMLIntoContainer(inputStream, vmDefs);
-// return false;
-// } catch (IOException ioe) {
-// LaunchingPlugin.log(ioe);
-// }
-// } else {
-// // Otherwise, look for the old file that previously held the VM definitions
-// IPath stateLocation= LaunchingPlugin.getDefault().getStateLocation();
-// IPath stateFile= stateLocation.append("vmConfiguration.xml"); //$NON-NLS-1$
-// File file = new File(stateFile.toOSString());
-//
-// if (file.exists()) {
-// // If file exists, load VM definitions from it into memory and write the definitions to
-// // the preference store WITHOUT triggering any processing of the new value
-// FileInputStream fileInputStream = new FileInputStream(file);
-// VMDefinitionsContainer.parseXMLIntoContainer(fileInputStream, vmDefs);
-// }
-// }
-// return true;
-// }
-//
-// /**
-// * Loads contributed VM installs
-// *
-// */
-// private static void addVMExtensions(VMDefinitionsContainer vmDefs) {
-// IExtensionPoint extensionPoint = Platform.getExtensionRegistry().getExtensionPoint(LaunchingPlugin.ID_PLUGIN, JavaRuntime.EXTENSION_POINT_VM_INSTALLS);
-// IConfigurationElement[] configs= extensionPoint.getConfigurationElements();
-// for (int i = 0; i < configs.length; i++) {
-// IConfigurationElement element = configs[i];
-// try {
-// if ("vmInstall".equals(element.getName())) { //$NON-NLS-1$
-// String vmType = element.getAttribute("vmInstallType"); //$NON-NLS-1$
-// if (vmType == null) {
-// abort(MessageFormat.format("Missing required vmInstallType attribute for vmInstall contributed by {0}", //$NON-NLS-1$
-// new String[]{element.getContributor().getName()}), null);
-// }
-// String id = element.getAttribute("id"); //$NON-NLS-1$
-// if (id == null) {
-// abort(MessageFormat.format("Missing required id attribute for vmInstall contributed by {0}", //$NON-NLS-1$
-// new String[]{element.getContributor().getName()}), null);
-// }
-// IVMInstallType installType = getVMInstallType(vmType);
-// if (installType == null) {
-// abort(MessageFormat.format("vmInstall {0} contributed by {1} references undefined VM install type {2}", //$NON-NLS-1$
-// new String[]{id, element.getContributor().getName(), vmType}), null);
-// }
-// IVMInstall install = installType.findVMInstall(id);
-// if (install == null) {
-// // only load/create if first time we've seen this VM install
-// String name = element.getAttribute("name"); //$NON-NLS-1$
-// if (name == null) {
-// abort(MessageFormat.format("vmInstall {0} contributed by {1} missing required attribute name", //$NON-NLS-1$
-// new String[]{id, element.getContributor().getName()}), null);
-// }
-// String home = element.getAttribute("home"); //$NON-NLS-1$
-// if (home == null) {
-// abort(MessageFormat.format("vmInstall {0} contributed by {1} missing required attribute home", //$NON-NLS-1$
-// new String[]{id, element.getContributor().getName()}), null);
-// }
-// String jsdoc = element.getAttribute("javadocURL"); //$NON-NLS-1$
-// String vmArgs = element.getAttribute("vmArgs"); //$NON-NLS-1$
-// VMStandin standin = new VMStandin(installType, id);
-// standin.setName(name);
-// home = substitute(home);
-// File homeDir = new File(home);
-// if (homeDir.exists()) {
-// try {
-// // adjust for relative path names
-// home = homeDir.getCanonicalPath();
-// homeDir = new File(home);
-// } catch (IOException e) {
-// }
-// }
-// IStatus status = installType.validateInstallLocation(homeDir);
-// if (!status.isOK()) {
-// abort(MessageFormat.format("Illegal install location {0} for vmInstall {1} contributed by {2}: {3}", //$NON-NLS-1$
-// new String[]{home, id, element.getContributor().getName(), status.getMessage()}), null);
-// }
-// standin.setInstallLocation(homeDir);
-// if (jsdoc != null) {
-// try {
-// standin.setJavadocLocation(new URL(javadoc));
-// } catch (MalformedURLException e) {
-// abort(MessageFormat.format("Illegal javadocURL attribute for vmInstall {0} contributed by {1}", //$NON-NLS-1$
-// new String[]{id, element.getContributor().getName()}), e);
-// }
-// }
-// if (vmArgs != null) {
-// standin.setVMArgs(vmArgs);
-// }
-// IConfigurationElement[] libraries = element.getChildren("library"); //$NON-NLS-1$
-// LibraryLocation[] locations = null;
-// if (libraries.length > 0) {
-// locations = new LibraryLocation[libraries.length];
-// for (int j = 0; j < libraries.length; j++) {
-// IConfigurationElement library = libraries[j];
-// String libPathStr = library.getAttribute("path"); //$NON-NLS-1$
-// if (libPathStr == null) {
-// abort(MessageFormat.format("library for vmInstall {0} contributed by {1} missing required attribute libPath", //$NON-NLS-1$
-// new String[]{id, element.getContributor().getName()}), null);
-// }
-// String sourcePathStr = library.getAttribute("sourcePath"); //$NON-NLS-1$
-// String packageRootStr = library.getAttribute("packageRootPath"); //$NON-NLS-1$
-// String javadocOverride = library.getAttribute("javadocURL"); //$NON-NLS-1$
-// URL url = null;
-// if (javadocOverride != null) {
-// try {
-// url = new URL(javadocOverride);
-// } catch (MalformedURLException e) {
-// abort(MessageFormat.format("Illegal javadocURL attribute specified for library {0} for vmInstall {1} contributed by {2}" //$NON-NLS-1$
-// ,new String[]{libPathStr, id, element.getContributor().getName()}), e);
-// }
-// }
-// IPath homePath = new Path(home);
-// IPath libPath = homePath.append(substitute(libPathStr));
-// IPath sourcePath = Path.EMPTY;
-// if (sourcePathStr != null) {
-// sourcePath = homePath.append(substitute(sourcePathStr));
-// }
-// IPath packageRootPath = Path.EMPTY;
-// if (packageRootStr != null) {
-// packageRootPath = new Path(substitute(packageRootStr));
-// }
-// locations[j] = new LibraryLocation(libPath, sourcePath, packageRootPath, url);
-// }
-// }
-// standin.setLibraryLocations(locations);
-// vmDefs.addVM(standin);
-// }
-// fgContributedVMs.add(id);
-// } else {
-// abort(MessageFormat.format("Illegal element {0} in vmInstalls extension contributed by {1}", //$NON-NLS-1$
-// new String[]{element.getName(), element.getContributor().getName()}), null);
-// }
-// } catch (CoreException e) {
-// LaunchingPlugin.log(e);
-// }
-// }
-// }
-//
-// /**
-// * Performs string substitution on the given expression.
-// *
-// * @param expression
-// * @return expression after string substitution
-// * @throws CoreException
-// *
-// */
-// private static String substitute(String expression) throws CoreException {
-// return VariablesPlugin.getDefault().getStringVariableManager().performStringSubstitution(expression);
-// }
-//
-// /**
-// * Returns whether the VM install with the specified id was contributed via
-// * the vmInstalls extension point.
-// *
-// * @param id vm id
-// * @return whether the vm install was contributed via extension point
-// *
-// */
-// public static boolean isContributedVMInstall(String id) {
-// getVMInstallTypes(); // ensure VMs are initialized
-// return fgContributedVMs.contains(id);
-// }
-
- /**
- * Evaluates library locations for a IVMInstall. If no library locations are set on the install, a default
- * location is evaluated and checked if it exists.
- * @return library locations with paths that exist or are empty
- *
- */
- public static LibraryLocation[] getLibraryLocations(IVMInstall vm) {
- IPath[] libraryPaths;
- IPath[] sourcePaths;
- IPath[] sourceRootPaths;
- URL[] javadocLocations;
- LibraryLocation[] locations= vm.getLibraryLocations();
- if (locations == null) {
- URL defJavaDocLocation = vm.getJavadocLocation();
- LibraryLocation[] dflts= vm.getVMInstallType().getDefaultLibraryLocations(vm.getInstallLocation());
- libraryPaths = new IPath[dflts.length];
- sourcePaths = new IPath[dflts.length];
- sourceRootPaths = new IPath[dflts.length];
- javadocLocations= new URL[dflts.length];
- for (int i = 0; i < dflts.length; i++) {
- libraryPaths[i]= dflts[i].getSystemLibraryPath();
- if (defJavaDocLocation == null) {
- javadocLocations[i]= dflts[i].getJavadocLocation();
- } else {
- javadocLocations[i]= defJavaDocLocation;
- }
- if (!libraryPaths[i].toFile().isFile()) {
- libraryPaths[i]= Path.EMPTY;
- }
-
- sourcePaths[i]= dflts[i].getSystemLibrarySourcePath();
- if (sourcePaths[i]!=null && sourcePaths[i].toFile().isFile()) {
- sourceRootPaths[i]= dflts[i].getPackageRootPath();
- } else {
- sourcePaths[i]= Path.EMPTY;
- sourceRootPaths[i]= Path.EMPTY;
- }
- }
- } else {
- libraryPaths = new IPath[locations.length];
- sourcePaths = new IPath[locations.length];
- sourceRootPaths = new IPath[locations.length];
- javadocLocations= new URL[locations.length];
- for (int i = 0; i < locations.length; i++) {
- libraryPaths[i]= locations[i].getSystemLibraryPath();
- sourcePaths[i]= locations[i].getSystemLibrarySourcePath();
- sourceRootPaths[i]= locations[i].getPackageRootPath();
- javadocLocations[i]= locations[i].getJavadocLocation();
- }
- }
- locations = new LibraryLocation[sourcePaths.length];
- for (int i = 0; i < sourcePaths.length; i++) {
- locations[i] = new LibraryLocation(libraryPaths[i], sourcePaths[i], sourceRootPaths[i], javadocLocations[i]);
- }
- return locations;
- }
-
-// /**
-// * Detect the VM that Eclipse is running on.
-// *
-// * @return a VM standin representing the VM that Eclipse is running on, or
-// * <code>null</code> if unable to detect the runtime VM
-// */
-// private static VMStandin detectEclipseRuntime() {
-// VMStandin detectedVMStandin = null;
-// // Try to detect a VM for each declared VM type
-// IVMInstallType[] vmTypes= getVMInstallTypes();
-// for (int i = 0; i < vmTypes.length; i++) {
-//
-// File detectedLocation= vmTypes[i].detectInstallLocation();
-// if (detectedLocation != null && detectedVMStandin == null) {
-//
-// // Make sure the VM id is unique
-// long unique = System.currentTimeMillis();
-// IVMInstallType vmType = vmTypes[i];
-// while (vmType.findVMInstall(String.valueOf(unique)) != null) {
-// unique++;
-// }
-//
-// // Create a standin for the detected VM and add it to the result collector
-// String vmID = String.valueOf(unique);
-// detectedVMStandin = new VMStandin(vmType, vmID);
-// detectedVMStandin.setInstallLocation(detectedLocation);
-// detectedVMStandin.setName(generateDetectedVMName(detectedVMStandin));
-// if (vmType instanceof AbstractVMInstallType) {
-// AbstractVMInstallType abs = (AbstractVMInstallType)vmType;
-// URL url = abs.getDefaultJavadocLocation(detectedLocation);
-// detectedVMStandin.setJavadocLocation(url);
-// }
-// }
-// }
-// return detectedVMStandin;
-// }
-//
-// private static boolean equals(String optionName, Map defaultOptions, Map options) {
-// return defaultOptions.get(optionName).equals(options.get(optionName));
-// }
-//
-// /**
-// * Make the name of a detected VM stand out.
-// */
-// private static String generateDetectedVMName(IVMInstall vm) {
-// return vm.getInstallLocation().getName();
-// }
-//
-// /**
-// * Creates and returns a includepath entry describing
-// * the JRE_LIB includepath variable.
-// *
-// * @return a new IIncludePathEntry that describes the JRE_LIB includepath variable
-// */
-// public static IIncludePathEntry getJREVariableEntry() {
-// return JavaScriptCore.newVariableEntry(
-// new Path(JRELIB_VARIABLE),
-// new Path(JRESRC_VARIABLE),
-// new Path(JRESRCROOT_VARIABLE)
-// );
-// }
-//
- /**
- * Creates and returns a includepath entry describing
- * the default JRE container entry.
- *
- * @return a new IIncludePathEntry that describes the default JRE container entry
- *
- */
- public static IIncludePathEntry getDefaultJREContainerEntry() {
- return JavaScriptCore.newContainerEntry(newDefaultJREContainerPath());
- }
-
- /**
- * Returns a path for the JRE includepath container identifying the
- * default VM install.
- *
- * @return includepath container path
- *
- */
- public static IPath newDefaultJREContainerPath() {
- return new Path(JRE_CONTAINER);
- }
-
- /**
- * Returns a path for the JRE includepath container identifying the
- * specified VM install by type and name.
- *
- * @param vm vm install
- * @return includepath container path
- *
- */
- public static IPath newJREContainerPath(IVMInstall vm) {
- return newJREContainerPath(vm.getVMInstallType().getId(), vm.getName());
- }
-
- /**
- * Returns a path for the JRE includepath container identifying the
- * specified VM install by type and name.
- *
- * @param typeId vm install type identifier
- * @param name vm install name
- * @return includepath container path
- *
- */
- public static IPath newJREContainerPath(String typeId, String name) {
- IPath path = newDefaultJREContainerPath();
- path = path.append(typeId);
- path = path.append(name);
- return path;
- }
-
-// /**
-// * Returns a path for the JRE includepath container identifying the
-// * specified execution environment.
-// *
-// * @param environment execution environment
-// * @return includepath container path
-// *
-// */
-// public static IPath newJREContainerPath(IExecutionEnvironment environment) {
-// IPath path = newDefaultJREContainerPath();
-// path = path.append(StandardVMType.ID_STANDARD_VM_TYPE);
-// path = path.append(JREContainerInitializer.encodeEnvironmentId(environment.getId()));
-// return path;
-// }
-
- /**
- * Returns the JRE referenced by the specified JRE includepath container
- * path or <code>null</code> if none.
- *
- * @param jreContainerPath
- * @return JRE referenced by the specified JRE includepath container
- * path or <code>null</code>
- *
- */
- public static IVMInstall getVMInstall(IPath jreContainerPath) {
- return JREContainerInitializer.resolveVM(jreContainerPath);
- }
-//
-// /**
-// * Returns the identifier of the VM install type referenced by the
-// * given JRE includepath container path, or <code>null</code> if none.
-// *
-// * @param jreContainerPath
-// * @return vm install type identifier or <code>null</code>
-// *
-// */
-// public static String getVMInstallTypeId(IPath jreContainerPath) {
-// if (JREContainerInitializer.isExecutionEnvironment(jreContainerPath)) {
-// return null;
-// }
-// return JREContainerInitializer.getVMTypeId(jreContainerPath);
-// }
-//
-// /**
-// * Returns the name of the VM install referenced by the
-// * given JRE includepath container path, or <code>null</code> if none.
-// *
-// * @param jreContainerPath
-// * @return vm name or <code>null</code>
-// *
-// */
-// public static String getVMInstallName(IPath jreContainerPath) {
-// if (JREContainerInitializer.isExecutionEnvironment(jreContainerPath)) {
-// return null;
-// }
-// return JREContainerInitializer.getVMName(jreContainerPath);
-// }
-
- /**
- * Returns the execution environment identifier in the following JRE
- * includepath container path, or <code>null</code> if none.
- *
- * @param jreContainerPath includepath container path
- * @return execution environment identifier or <code>null</code>
- *
- */
- public static String getExecutionEnvironmentId(IPath jreContainerPath) {
- return JREContainerInitializer.getExecutionEnvironmentId(jreContainerPath);
- }
-
- /**
- * Returns a runtime includepath entry identifying the JRE to use when launching the specified
- * configuration or <code>null</code> if none is specified. The entry returned represents a
- * either a includepath variable or includepath container that resolves to a JRE.
- * <p>
- * The entry is resolved as follows:
- * <ol>
- * <li>If the <code>ATTR_JRE_CONTAINER_PATH</code> is present, it is used to create
- * a includepath container referring to a JRE.</li>
- * <li>Next, if the <code>ATTR_VM_INSTALL_TYPE</code> and <code>ATTR_VM_INSTALL_NAME</code>
- * attributes are present, they are used to create a includepath container.</li>
- * <li>When none of the above attributes are specified, a default entry is
- * created which refers to the JRE referenced by the build path of the configuration's
- * associated JavaScript project. This could be a includepath variable or includepath container.</li>
- * <li>When there is no JavaScript project associated with a configuration, the workspace
- * default JRE is used to create a container path.</li>
- * </ol>
- * </p>
- * @param configuration
- * @return includepath container path identifying a JRE or <code>null</code>
- * @exception org.eclipse.core.runtime.CoreException if an exception occurs retrieving
- * attributes from the specified launch configuration
- *
- */
- public static IRuntimeClasspathEntry computeJREEntry(ILaunchConfiguration configuration) throws CoreException {
- String jreAttr = configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_JRE_CONTAINER_PATH, (String)null);
- IPath containerPath = null;
- if (jreAttr == null) {
- String type = configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_INSTALL_TYPE, (String)null);
- if (type == null) {
- // default JRE for the launch configuration
- IJavaScriptProject proj = getJavaProject(configuration);
- if (proj == null) {
- containerPath = newDefaultJREContainerPath();
- } else {
- return computeJREEntry(proj);
- }
- } else {
- String name = configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_INSTALL_NAME, (String)null);
- if (name != null) {
- containerPath = newDefaultJREContainerPath().append(type).append(name);
- }
- }
- } else {
- containerPath = Path.fromPortableString(jreAttr);
- }
- if (containerPath != null) {
- return newRuntimeContainerClasspathEntry(containerPath, IRuntimeClasspathEntry.STANDARD_CLASSES);
- }
- return null;
- }
-
- /**
- * Returns a runtime includepath entry identifying the JRE referenced by the specified
- * project, or <code>null</code> if none. The entry returned represents a either a
- * includepath variable or includepath container that resolves to a JRE.
- *
- * @param project JavaScript project
- * @return JRE runtime includepath entry or <code>null</code>
- * @exception org.eclipse.core.runtime.CoreException if an exception occurs
- * accessing the project's includepath
- *
- */
- public static IRuntimeClasspathEntry computeJREEntry(IJavaScriptProject project) throws CoreException {
- IIncludePathEntry[] rawClasspath = project.getRawIncludepath();
- IRuntimeClasspathEntryResolver2 resolver = null;
- for (int i = 0; i < rawClasspath.length; i++) {
- IIncludePathEntry entry = rawClasspath[i];
- switch (entry.getEntryKind()) {
- case IIncludePathEntry.CPE_VARIABLE:
- resolver = getVariableResolver(entry.getPath().segment(0));
- if (resolver != null) {
- if (resolver.isVMInstallReference(entry)) {
- return newRuntimeClasspathEntry(entry);
- }
- }
- break;
- case IIncludePathEntry.CPE_CONTAINER:
- resolver = getContainerResolver(entry.getPath().segment(0));
- if (resolver != null) {
- if (resolver.isVMInstallReference(entry)) {
- IJsGlobalScopeContainer container = JavaScriptCore.getJsGlobalScopeContainer(entry.getPath(), project);
- if (container != null) {
- switch (container.getKind()) {
- case IJsGlobalScopeContainer.K_APPLICATION:
- break;
- case IJsGlobalScopeContainer.K_DEFAULT_SYSTEM:
- return newRuntimeContainerClasspathEntry(entry.getPath(), IRuntimeClasspathEntry.STANDARD_CLASSES);
- case IJsGlobalScopeContainer.K_SYSTEM:
- return newRuntimeContainerClasspathEntry(entry.getPath(), IRuntimeClasspathEntry.BOOTSTRAP_CLASSES);
- }
- }
- }
- }
- break;
- }
-
- }
- return null;
- }
-
-// /**
-// * Returns whether the given runtime includepath entry refers to a vm install.
-// *
-// * @param entry
-// * @return whether the given runtime includepath entry refers to a vm install
-// *
-// */
-// public static boolean isVMInstallReference(IRuntimeClasspathEntry entry) {
-// IIncludePathEntry includepathEntry = entry.getClasspathEntry();
-// if (includepathEntry != null) {
-// switch (includepathEntry.getEntryKind()) {
-// case IIncludePathEntry.CPE_VARIABLE:
-// IRuntimeClasspathEntryResolver2 resolver = getVariableResolver(includepathEntry.getPath().segment(0));
-// if (resolver != null) {
-// return resolver.isVMInstallReference(includepathEntry);
-// }
-// break;
-// case IIncludePathEntry.CPE_CONTAINER:
-// resolver = getContainerResolver(includepathEntry.getPath().segment(0));
-// if (resolver != null) {
-// return resolver.isVMInstallReference(includepathEntry);
-// }
-// break;
-// }
-// }
-// return false;
-// }
-//
-// /**
-// * Returns the VM connector defined with the specified identifier,
-// * or <code>null</code> if none.
-// *
-// * @param id VM connector identifier
-// * @return VM connector or <code>null</code> if none
-// *
-// */
-// public static IVMConnector getVMConnector(String id) {
-// return LaunchingPlugin.getDefault().getVMConnector(id);
-// }
-//
-// /**
-// * Returns all VM connector extensions.
-// *
-// * @return VM connectors
-// *
-// */
-// public static IVMConnector[] getVMConnectors() {
-// return LaunchingPlugin.getDefault().getVMConnectors();
-// }
-
- /**
- * Returns the preference store for the launching plug-in.
- *
- * @return the preference store for the launching plug-in
- *
- */
- public static Preferences getPreferences() {
- return JavaScriptCore.getPlugin().getPluginPreferences();
- }
-
- /**
- * Saves the preferences for the launching plug-in.
- *
- *
- */
- public static void savePreferences() {
- JavaScriptCore.getPlugin().savePluginPreferences();
- }
-
-// /**
-// * Registers the given resolver for the specified variable.
-// *
-// * @param resolver runtime includepath entry resolver
-// * @param variableName variable name to register for
-// *
-// */
-// public static void addVariableResolver(IRuntimeClasspathEntryResolver resolver, String variableName) {
-// Map map = getVariableResolvers();
-// map.put(variableName, resolver);
-// }
-
- /**
- * Registers the given resolver for the specified container.
- *
- * @param resolver runtime includepath entry resolver
- * @param containerIdentifier identifier of the includepath container to register for
- *
- */
- public static void addContainerResolver(IRuntimeClasspathEntryResolver resolver, String containerIdentifier) {
- Map map = getContainerResolvers();
- map.put(containerIdentifier, resolver);
- }
-
- /**
- * Returns all registered variable resolvers.
- */
- private static Map getVariableResolvers() {
- if (fgVariableResolvers == null) {
- initializeResolvers();
- }
- return fgVariableResolvers;
- }
-
- /**
- * Returns all registered container resolvers.
- */
- private static Map getContainerResolvers() {
- if (fgContainerResolvers == null) {
- initializeResolvers();
- }
- return fgContainerResolvers;
- }
-
-// /**
-// * Returns all registered runtime includepath entry resolvers.
-// */
-// private static Map getEntryResolvers() {
-// if (fgRuntimeClasspathEntryResolvers == null) {
-// initializeResolvers();
-// }
-// return fgRuntimeClasspathEntryResolvers;
-// }
-//
- private static void initializeResolvers() {
- fgContainerResolvers=new HashMap();
-//TODO: implement
-//throw new org.eclipse.wst.jsdt.core.UnimplementedException();
- // IExtensionPoint point = Platform.getExtensionRegistry().getExtensionPoint(LaunchingPlugin.ID_PLUGIN, EXTENSION_POINT_RUNTIME_CLASSPATH_ENTRY_RESOLVERS);
-// IConfigurationElement[] extensions = point.getConfigurationElements();
-// fgVariableResolvers = new HashMap(extensions.length);
-// fgContainerResolvers = new HashMap(extensions.length);
-// fgRuntimeClasspathEntryResolvers = new HashMap(extensions.length);
-// for (int i = 0; i < extensions.length; i++) {
-// RuntimeClasspathEntryResolver res = new RuntimeClasspathEntryResolver(extensions[i]);
-// String variable = res.getVariableName();
-// String container = res.getContainerId();
-// String entryId = res.getRuntimeClasspathEntryId();
-// if (variable != null) {
-// fgVariableResolvers.put(variable, res);
-// }
-// if (container != null) {
-// fgContainerResolvers.put(container, res);
-// }
-// if (entryId != null) {
-// fgRuntimeClasspathEntryResolvers.put(entryId, res);
-// }
-// }
- }
-
-// /**
-// * Returns all registered includepath providers.
-// */
-// private static Map getClasspathProviders() {
-// if (fgPathProviders == null) {
-// initializeProviders();
-// }
-// return fgPathProviders;
-// }
-//
-// private static void initializeProviders() {
-// IExtensionPoint point = Platform.getExtensionRegistry().getExtensionPoint(LaunchingPlugin.ID_PLUGIN, EXTENSION_POINT_RUNTIME_CLASSPATH_PROVIDERS);
-// IConfigurationElement[] extensions = point.getConfigurationElements();
-// fgPathProviders = new HashMap(extensions.length);
-// for (int i = 0; i < extensions.length; i++) {
-// RuntimeClasspathProvider res = new RuntimeClasspathProvider(extensions[i]);
-// fgPathProviders.put(res.getIdentifier(), res);
-// }
-// }
-
- /**
- * Returns the resolver registered for the given variable, or
- * <code>null</code> if none.
- *
- * @param variableName the variable to determine the resolver for
- * @return the resolver registered for the given variable, or
- * <code>null</code> if none
- */
- private static IRuntimeClasspathEntryResolver2 getVariableResolver(String variableName) {
- return (IRuntimeClasspathEntryResolver2)getVariableResolvers().get(variableName);
- }
-
- /**
- * Returns the resolver registered for the given container id, or
- * <code>null</code> if none.
- *
- * @param containerId the container to determine the resolver for
- * @return the resolver registered for the given container id, or
- * <code>null</code> if none
- */
- private static IRuntimeClasspathEntryResolver2 getContainerResolver(String containerId) {
- return (IRuntimeClasspathEntryResolver2)getContainerResolvers().get(containerId);
- }
-
-// /**
-// * Returns the resolver registered for the given contributed includepath
-// * entry type.
-// *
-// * @param typeId the id of the contributed includepath entry
-// * @return the resolver registered for the given includepath entry
-// */
-// private static IRuntimeClasspathEntryResolver getContributedResolver(String typeId) {
-// IRuntimeClasspathEntryResolver resolver = (IRuntimeClasspathEntryResolver)getEntryResolvers().get(typeId);
-// if (resolver == null) {
-// return new DefaultEntryResolver();
-// }
-// return resolver;
-// }
-//
-// /**
-// * Adds the given listener to the list of registered VM install changed
-// * listeners. Has no effect if an identical listener is already registered.
-// *
-// * @param listener the listener to add
-// *
-// */
-// public static void addVMInstallChangedListener(IVMInstallChangedListener listener) {
-// fgVMListeners.add(listener);
-// }
-//
-// /**
-// * Removes the given listener from the list of registered VM install changed
-// * listeners. Has no effect if an identical listener is not already registered.
-// *
-// * @param listener the listener to remove
-// *
-// */
-// public static void removeVMInstallChangedListener(IVMInstallChangedListener listener) {
-// fgVMListeners.remove(listener);
-// }
-
- private static void notifyDefaultVMChanged(IVMInstall previous, IVMInstall current) {
- Object[] listeners = fgVMListeners.getListeners();
- for (int i = 0; i < listeners.length; i++) {
- IVMInstallChangedListener listener = (IVMInstallChangedListener)listeners[i];
- listener.defaultVMInstallChanged(previous, current);
- }
- }
-
- /**
- * Notifies all VM install changed listeners of the given property change.
- *
- * @param event event describing the change.
- *
- */
- public static void fireVMChanged(PropertyChangeEvent event) {
- Object[] listeners = fgVMListeners.getListeners();
- for (int i = 0; i < listeners.length; i++) {
- IVMInstallChangedListener listener = (IVMInstallChangedListener)listeners[i];
- listener.vmChanged(event);
- }
- }
-
- /**
- * Notifies all VM install changed listeners of the VM addition
- *
- * @param vm the VM that has been added
- *
- */
- public static void fireVMAdded(IVMInstall vm) {
- if (!fgInitializingVMs) {
- Object[] listeners = fgVMListeners.getListeners();
- for (int i = 0; i < listeners.length; i++) {
- IVMInstallChangedListener listener = (IVMInstallChangedListener)listeners[i];
- listener.vmAdded(vm);
- }
- }
- }
-
- /**
- * Notifies all VM install changed listeners of the VM removal
- *
- * @param vm the VM that has been removed
- *
- */
- public static void fireVMRemoved(IVMInstall vm) {
- Object[] listeners = fgVMListeners.getListeners();
- for (int i = 0; i < listeners.length; i++) {
- IVMInstallChangedListener listener = (IVMInstallChangedListener)listeners[i];
- listener.vmRemoved(vm);
- }
- }
-
-// /**
-// * Return the String representation of the default output directory of the
-// * launch config's project or <code>null</code> if there is no config, no
-// * project or some sort of problem.
-// *
-// * @return the default output directory for the specified launch
-// * configuration's project
-// *
-// */
-// public static String getProjectOutputDirectory(ILaunchConfiguration config) {
-// try {
-// if (config != null) {
-// IJavaScriptProject javaProject = JavaRuntime.getJavaProject(config);
-// if (javaProject != null) {
-// IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
-// IPath outputLocation = javaProject.getOutputLocation();
-// IResource resource = root.findMember(outputLocation);
-// if (resource != null) {
-// IPath path = resource.getFullPath();
-// if (path != null) {
-// return path.makeRelative().toString();
-// }
-// }
-// }
-// }
-// } catch (CoreException ce) {
-// }
-// return null;
-// }
-//
-// /**
-// * Returns a collection of source containers corresponding to the given
-// * resolved runtime includepath entries.
-// * <p>
-// * Note that the entries must be resolved to ARCHIVE and PROJECT entries,
-// * as source containers cannot be determined for unresolved entries.
-// * </p>
-// * @param entries entries to translate
-// * @return source containers corresponding to the given runtime includepath entries
-// *
-// */
-// public static ISourceContainer[] getSourceContainers(IRuntimeClasspathEntry[] entries) {
-// return JavaSourceLookupUtil.translate(entries);
-// }
-//
-// /**
-// * Returns a collection of paths that should be appended to the given project's
-// * <code>java.library.path</code> system property when launched. Entries are
-// * searched for on the project's build path as extra includepath attributes.
-// * Each entry represents an absolute path in the local file system.
-// *
-// * @param project the project to compute the <code>java.library.path</code> for
-// * @param requiredProjects whether to consider entries in required projects
-// * @return a collection of paths representing entries that should be appended
-// * to the given project's <code>java.library.path</code>
-// * @throws CoreException if unable to compute the JavaScript library path
-// *
-// * @see org.eclipse.wst.jsdt.core.IIncludePathAttribute
-// * @see JavaRuntime#CLASSPATH_ATTR_LIBRARY_PATH_ENTRY
-// */
-// public static String[] computeJavaLibraryPath(IJavaScriptProject project, boolean requiredProjects) throws CoreException {
-// Set visited = new HashSet();
-// List entries = new ArrayList();
-// gatherJavaLibraryPathEntries(project, requiredProjects, visited, entries);
-// List resolved = new ArrayList(entries.size());
-// Iterator iterator = entries.iterator();
-// IStringVariableManager manager = VariablesPlugin.getDefault().getStringVariableManager();
-// IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
-// while (iterator.hasNext()) {
-// String entry = (String) iterator.next();
-// String resolvedEntry = manager.performStringSubstitution(entry);
-// IPath path = new Path(resolvedEntry);
-// if (path.isAbsolute()) {
-// File file = path.toFile();
-// resolved.add(file.getAbsolutePath());
-// } else {
-// IResource resource = root.findMember(path);
-// if (resource != null) {
-// IPath location = resource.getLocation();
-// if (location != null) {
-// resolved.add(location.toFile().getAbsolutePath());
-// }
-// }
-// }
-// }
-// return (String[])resolved.toArray(new String[resolved.size()]);
-// }
-//
-// /**
-// * Gathers all JavaScript library entries for the given project and optionally its required
-// * projects.
-// *
-// * @param project project to gather entries for
-// * @param requiredProjects whether to consider required projects
-// * @param visited projects already considered
-// * @param entries collection to add library entries to
-// * @throws CoreException if unable to gather includepath entries
-// *
-// */
-// private static void gatherJavaLibraryPathEntries(IJavaScriptProject project, boolean requiredProjects, Set visited, List entries) throws CoreException {
-// if (visited.contains(project)) {
-// return;
-// }
-// visited.add(project);
-// IIncludePathEntry[] rawClasspath = project.getRawClasspath();
-// IIncludePathEntry[] required = processJavaLibraryPathEntries(project, requiredProjects, rawClasspath, entries);
-// if (required != null) {
-// IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
-// for (int i = 0; i < required.length; i++) {
-// IIncludePathEntry entry = required[i];
-// String projectName = entry.getPath().segment(0);
-// IProject p = root.getProject(projectName);
-// if (p.exists()) {
-// IJavaScriptProject requiredProject = JavaScriptCore.create(p);
-// if (requiredProject != null) {
-// gatherJavaLibraryPathEntries(requiredProject, requiredProjects, visited, entries);
-// }
-// }
-// }
-// }
-// }
-//
-// /**
-// * Adds all javascript library path extra includepath entry values to the given entries collection
-// * specified on the given project's includepath, and returns a collection of required
-// * projects, or <code>null</code>.
-// *
-// * @param project project being processed
-// * @param collectRequired whether to collect required projects
-// * @param includepathEntries the project's raw includepath
-// * @param entries collection to add javascript library path entries to
-// * @return required project includepath entries or <code>null</code>
-// * @throws CoreException
-// *
-// */
-// private static IIncludePathEntry[] processJavaLibraryPathEntries(IJavaScriptProject project, boolean collectRequired, IIncludePathEntry[] includepathEntries, List entries) throws CoreException {
-// List req = null;
-// for (int i = 0; i < includepathEntries.length; i++) {
-// IIncludePathEntry entry = includepathEntries[i];
-// IIncludePathAttribute[] extraAttributes = entry.getExtraAttributes();
-// for (int j = 0; j < extraAttributes.length; j++) {
-// String[] paths = getLibraryPaths(extraAttributes[j]);
-// if (paths != null) {
-// for (int k = 0; k < paths.length; k++) {
-// entries.add(paths[k]);
-// }
-// }
-// }
-// if (entry.getEntryKind() == IIncludePathEntry.CPE_CONTAINER) {
-// IJsGlobalScopeContainer container = JavaScriptCore.getJsGlobalScopeContainer(entry.getPath(), project);
-// if (container != null) {
-// IIncludePathEntry[] requiredProjects = processJavaLibraryPathEntries(project, collectRequired, container.getClasspathEntries(), entries);
-// if (requiredProjects != null) {
-// if (req == null) {
-// req = new ArrayList();
-// }
-// for (int j = 0; j < requiredProjects.length; j++) {
-// req.add(requiredProjects[j]);
-// }
-// }
-// }
-// } else if (collectRequired && entry.getEntryKind() == IIncludePathEntry.CPE_PROJECT) {
-// if (req == null) {
-// req = new ArrayList();
-// }
-// req.add(entry);
-// }
-// }
-// if (req != null) {
-// return (IIncludePathEntry[]) req.toArray(new IIncludePathEntry[req.size()]);
-// }
-// return null;
-// }
-//
-// /**
-// * Creates a new includepath attribute referencing a list of shared libraries that should
-// * appear on the <code>-Djava.library.path</code> system property at runtime
-// * for an associated {@link IIncludePathEntry}.
-// * <p>
-// * The factory methods <code>newLibraryPathsAttribute(String[])</code>
-// * and <code>getLibraryPaths(IIncludePathAttribute)</code> should be used to
-// * encode and decode the attribute value.
-// * </p>
-// * @param paths an array of strings representing paths of shared libraries.
-// * Each string is used to create an <code>IPath</code> using the constructor
-// * <code>Path(String)</code>, and may contain <code>IStringVariable</code>'s.
-// * Variable substitution is performed on each string before a path is constructed
-// * from a string.
-// * @return a includepath attribute with the name <code>CLASSPATH_ATTR_LIBRARY_PATH_ENTRY</code>
-// * and an value encoded to the specified paths.
-// *
-// */
-// public static IIncludePathAttribute newLibraryPathsAttribute(String[] paths) {
-// StringBuffer value = new StringBuffer();
-// for (int i = 0; i < paths.length; i++) {
-// value.append(paths[i]);
-// if (i < (paths.length - 1)) {
-// value.append("|"); //$NON-NLS-1$
-// }
-// }
-// return JavaScriptCore.newClasspathAttribute(CLASSPATH_ATTR_LIBRARY_PATH_ENTRY, value.toString());
-// }
-//
-// /**
-// * Returns an array of strings referencing shared libraries that should
-// * appear on the <code>-Djava.library.path</code> system property at runtime
-// * for an associated {@link IIncludePathEntry}, or <code>null</code> if the
-// * given attribute is not a <code>CLASSPATH_ATTR_LIBRARY_PATH_ENTRY</code>.
-// * Each string is used to create an <code>IPath</code> using the constructor
-// * <code>Path(String)</code>, and may contain <code>IStringVariable</code>'s.
-// * <p>
-// * The factory methods <code>newLibraryPathsAttribute(String[])</code>
-// * and <code>getLibraryPaths(IIncludePathAttribute)</code> should be used to
-// * encode and decode the attribute value.
-// * </p>
-// * @param attribute a <code>CLASSPATH_ATTR_LIBRARY_PATH_ENTRY</code> includepath attribute
-// * @return an array of strings referencing shared libraries that should
-// * appear on the <code>-Djava.library.path</code> system property at runtime
-// * for an associated {@link IIncludePathEntry}, or <code>null</code> if the
-// * given attribute is not a <code>CLASSPATH_ATTR_LIBRARY_PATH_ENTRY</code>.
-// * Each string is used to create an <code>IPath</code> using the constructor
-// * <code>Path(String)</code>, and may contain <code>IStringVariable</code>'s.
-// *
-// */
-// public static String[] getLibraryPaths(IIncludePathAttribute attribute) {
-// if (CLASSPATH_ATTR_LIBRARY_PATH_ENTRY.equals(attribute.getName())) {
-// String value = attribute.getValue();
-// return value.split("\\|"); //$NON-NLS-1$
-// }
-// return null;
-// }
-//
-// /**
-// * Returns the execution environments manager.
-// *
-// * @return execution environments manager
-// *
-// */
-// public static IExecutionEnvironmentsManager getExecutionEnvironmentsManager() {
-// return EnvironmentsManager.getDefault();
-// }
-
- /**
- * Perform VM type and VM install initialization. Does not hold locks
- * while performing change notification.
- *
- *
- */
- private static void initializeVMs() {
-
-
-// VMDefinitionsContainer vmDefs = null;
-// boolean setPref = false;
-// boolean updateCompliance = false;
- synchronized (fgVMLock) {
- if (fgVMTypes == null) {
- try {
- fgInitializingVMs = true;
- fgVMTypes=new IVMInstallType[]{new StandardVMType()};
- defaultVM = new StandardVM(fgVMTypes[0],"defaultVM"); //$NON-NLS-1$
- fgDefaultVMId=defaultVM.getId();
- File location = SystemLibraryLocation.getInstance().getWorkingLibPath().toFile();
- defaultVM.setInstallLocation(location);
-
-// // 1. load VM type extensions
-// initializeVMTypeExtensions();
-// try {
-// vmDefs = new VMDefinitionsContainer();
-// // 2. add persisted VMs
-// setPref = addPersistedVMs(vmDefs);
-//
-// // 3. if there are none, detect the eclipse runtime
-// if (vmDefs.getValidVMList().isEmpty()) {
-// // calling out to detectEclipseRuntime() could allow clients to change
-// // VM settings (i.e. call back into change VM settings).
-// VMListener listener = new VMListener();
-// addVMInstallChangedListener(listener);
-// setPref = true;
-// VMStandin runtime = detectEclipseRuntime();
-// removeVMInstallChangedListener(listener);
-// if (!listener.isChanged()) {
-// if (runtime != null) {
-// updateCompliance = true;
-// vmDefs.addVM(runtime);
-// vmDefs.setDefaultVMInstallCompositeID(getCompositeIdFromVM(runtime));
-// }
-// } else {
-// // VMs were changed - reflect current settings
-// addPersistedVMs(vmDefs);
-// vmDefs.setDefaultVMInstallCompositeID(fgDefaultVMId);
-// updateCompliance = fgDefaultVMId != null;
-// }
-// }
-// // 4. load contributed VM installs
-// addVMExtensions(vmDefs);
-// // 5. verify default VM is valid
-// String defId = vmDefs.getDefaultVMInstallCompositeID();
-// boolean validDef = false;
-// if (defId != null) {
-// Iterator iterator = vmDefs.getValidVMList().iterator();
-// while (iterator.hasNext()) {
-// IVMInstall vm = (IVMInstall) iterator.next();
-// if (getCompositeIdFromVM(vm).equals(defId)) {
-// validDef = true;
-// break;
-// }
-// }
-// }
-// if (!validDef) {
-// // use the first as the default
-// setPref = true;
-// List list = vmDefs.getValidVMList();
-// if (!list.isEmpty()) {
-// IVMInstall vm = (IVMInstall) list.get(0);
-// vmDefs.setDefaultVMInstallCompositeID(getCompositeIdFromVM(vm));
-// }
-// }
-// fgDefaultVMId = vmDefs.getDefaultVMInstallCompositeID();
-// fgDefaultVMConnectorId = vmDefs.getDefaultVMInstallConnectorTypeID();
-//
-// // Create the underlying VMs for each valid VM
-// List vmList = vmDefs.getValidVMList();
-// Iterator vmListIterator = vmList.iterator();
-// while (vmListIterator.hasNext()) {
-// VMStandin vmStandin = (VMStandin) vmListIterator.next();
-// vmStandin.convertToRealVM();
-// }
-//
-//
-// } catch (IOException e) {
-// JavaPlugin.log(e);
-// }
- } finally {
- fgInitializingVMs = false;
- }
- }
- }
-// if (vmDefs != null) {
-// // notify of initial VMs for backwards compatibility
-// IVMInstallType[] installTypes = getVMInstallTypes();
-// for (int i = 0; i < installTypes.length; i++) {
-// IVMInstallType type = installTypes[i];
-// IVMInstall[] installs = type.getVMInstalls();
-// for (int j = 0; j < installs.length; j++) {
-// fireVMAdded(installs[j]);
-// }
-// }
-//
-// // save settings if required
-// if (setPref) {
-// try {
-// String xml = vmDefs.getAsXML();
-// LaunchingPlugin.getDefault().getPluginPreferences().setValue(PREF_VM_XML, xml);
-// } catch (ParserConfigurationException e) {
-// LaunchingPlugin.log(e);
-// } catch (IOException e) {
-// LaunchingPlugin.log(e);
-// } catch (TransformerException e) {
-// LaunchingPlugin.log(e);
-// }
-//
-// }
-//
-// // update compliance if required
-// if (updateCompliance) {
-// updateCompliance(getDefaultVMInstall());
-// }
-// }
- }
-
-// /**
-// * Update compiler compliance settings based on the given vm.
-// *
-// * @param vm
-// */
-// private static void updateCompliance(IVMInstall vm) {
-// if (vm instanceof IVMInstall2) {
-// String javaVersion = ((IVMInstall2)vm).getJavaVersion();
-// if (javaVersion != null && javaVersion.startsWith(JavaScriptCore.VERSION_1_5)) {
-// Hashtable defaultOptions = JavaScriptCore.getDefaultOptions();
-// Hashtable options = JavaScriptCore.getOptions();
-// boolean isDefault =
-// equals(JavaScriptCore.COMPILER_COMPLIANCE, defaultOptions, options) &&
-// equals(JavaScriptCore.COMPILER_SOURCE, defaultOptions, options) &&
-// equals(JavaScriptCore.COMPILER_CODEGEN_TARGET_PLATFORM, defaultOptions, options) &&
-// equals(JavaScriptCore.COMPILER_PB_ASSERT_IDENTIFIER, defaultOptions, options) &&
-// equals(JavaScriptCore.COMPILER_PB_ENUM_IDENTIFIER, defaultOptions, options);
-// // only update the compliance settings if they are default settings, otherwise the
-// // settings have already been modified by a tool or user
-// if (isDefault) {
-// options.put(JavaScriptCore.COMPILER_COMPLIANCE, JavaScriptCore.VERSION_1_5);
-// options.put(JavaScriptCore.COMPILER_SOURCE, JavaScriptCore.VERSION_1_5);
-// options.put(JavaScriptCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaScriptCore.VERSION_1_5);
-// options.put(JavaScriptCore.COMPILER_PB_ASSERT_IDENTIFIER, JavaScriptCore.ERROR);
-// options.put(JavaScriptCore.COMPILER_PB_ENUM_IDENTIFIER, JavaScriptCore.ERROR);
-// JavaScriptCore.setOptions(options);
-// }
-// }
-// }
-// }
-//
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/LaunchingMessages.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/LaunchingMessages.java
deleted file mode 100644
index 95cc3904..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/LaunchingMessages.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM - Initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.launching;
-
-import org.eclipse.osgi.util.NLS;
-
-public class LaunchingMessages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.wst.jsdt.launching.LaunchingMessages";//$NON-NLS-1$
-
- public static String JavaRuntime_Specified_VM_install_type_does_not_exist___0__2;
- public static String JavaRuntime_VM_not_fully_specified_in_launch_configuration__0____missing_VM_name__Reverting_to_default_VM__1;
- public static String JavaRuntime_Specified_VM_install_not_found__type__0___name__1__2;
-
- public static String JREContainerInitializer_Array;
-
- public static String JREContainerInitializer_Global;
-
- public static String JREContainerInitializer_JsECMA_NAME;
-
- public static String JREContainerInitializer_Object;
-
-
- public static String libraryLocation_assert_libraryNotNull;
-
-
- public static String StandardVMType_Standard_VM_3;
-
- public static String vmInstall_assert_idNotNull;
- public static String vmInstall_assert_typeNotNull;
-
- public static String vmInstallType_duplicateVM;
-
- public static String vmRunnerConfig_assert_classNotNull;
- public static String vmRunnerConfig_assert_classPathNotNull;
- public static String vmRunnerConfig_assert_programArgsNotNull;
- public static String vmRunnerConfig_assert_vmArgsNotNull;
-
-
- public static String JREContainer_JRE_System_Library_1;
-
- public static String JREContainerInitializer_Default_System_Library_1;
-
- public static String JavaRuntime_28;
- public static String JavaRuntime_Launch_configuration__0__references_non_existing_project__1___1;
-
-
- static {
- // load message values from bundle file
- NLS.initializeMessages(BUNDLE_NAME, LaunchingMessages.class);
- }
-
-
-}
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
deleted file mode 100644
index 58f3186f..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/LaunchingMessages.properties
+++ /dev/null
@@ -1,42 +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
-###############################################################################
-
-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.
-JavaRuntime_Specified_VM_install_not_found__type__0___name__1__2=Specified VM install not found: type {0}, name {1}
-
-
-libraryLocation_assert_libraryNotNull=library cannot be null
-
-StandardVMType_Standard_VM_3=Standard VM
-
-vmInstall_assert_idNotNull=id cannot be null
-vmInstall_assert_typeNotNull=VM type cannot be null
-
-vmInstallType_duplicateVM=Duplicate VM: {0}
-
-vmRunnerConfig_assert_classNotNull=classToLaunch cannot be null
-vmRunnerConfig_assert_classPathNotNull=classPath cannot be null
-vmRunnerConfig_assert_programArgsNotNull=args cannot be null
-vmRunnerConfig_assert_vmArgsNotNull=args cannot be null
-
-# "ECMAScript defines a collection of built-in objects that round out the
-# definition of ECMAScript entities. - Ecma262r3, sec. 4.2"
-JREContainer_JRE_System_Library_1=ECMAScript Built-In Library
-JREContainerInitializer_Global=Global
-JREContainerInitializer_Object=Object
-JREContainerInitializer_Array=Array
-
-JREContainerInitializer_Default_System_Library_1=ECMAScript System Libraries
-JREContainerInitializer_JsECMA_NAME=JavaScript Language (ECMA-262)
-
-JavaRuntime_28=Launch configuration {0} references closed project {1}
-JavaRuntime_Launch_configuration__0__references_non_existing_project__1___1=Launch configuration {0} references non-existing project {1}.
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
deleted file mode 100644
index 7da6bc6d..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/LibraryLocation.java
+++ /dev/null
@@ -1,164 +0,0 @@
-/*******************************************************************************
- * 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.launching;
-
-import java.net.URL;
-
-import org.eclipse.core.runtime.IPath;
-
-
-/**
- * The location of a library (for example rt.jar).
- * <p>
- * Clients may instantiate this class; it is not intended to be subclassed.
- * </p>
- *
- * 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 final class LibraryLocation {
- private IPath fSystemLibrary;
- private IPath fSystemLibrarySource;
- private IPath fPackageRootPath;
- private URL fJavadocLocation;
-
- /**
- * Creates a new library location.
- *
- * @param libraryPath The location of the JAR containing java.lang.Object
- * Must not be <code>null</code>.
- * @param sourcePath The location of the zip file containing the sources for <code>library</code>
- * Must not be <code>null</code> (Use Path.EMPTY instead)
- * @param packageRoot The path inside the <code>source</code> zip file where packages names
- * begin. If the source for java.lang.Object source is found at
- * "src/java/lang/Object.java" in the zip file, the
- * packageRoot should be "src"
- * Must not be <code>null</code>. (Use Path.EMPTY or IPath.ROOT)
- * @throws IllegalArgumentException If the library path is <code>null</code>.
- */
- public LibraryLocation(IPath libraryPath, IPath sourcePath, IPath packageRoot) {
- this(libraryPath, sourcePath, packageRoot, null);
- }
-
- /**
- * Creates a new library location.
- *
- * @param libraryPath The location of the JAR containing java.lang.Object
- * Must not be <code>null</code>.
- * @param sourcePath The location of the zip file containing the sources for <code>library</code>
- * Must not be <code>null</code> (Use Path.EMPTY instead)
- * @param packageRoot The path inside the <code>source</code> zip file where packages names
- * begin. If the source for java.lang.Object source is found at
- * "src/java/lang/Object.java" in the zip file, the
- * packageRoot should be "src"
- * Must not be <code>null</code>. (Use Path.EMPTY or IPath.ROOT)
- * @param javadocLocation The location of the jsdoc for <code>library</code>
- * @throws IllegalArgumentException If the library path is <code>null</code>.
- *
- */
- public LibraryLocation(IPath libraryPath, IPath sourcePath, IPath packageRoot, URL javadocLocation) {
- if (libraryPath == null)
- throw new IllegalArgumentException(LaunchingMessages.libraryLocation_assert_libraryNotNull);
-
- fSystemLibrary= libraryPath;
- fSystemLibrarySource= sourcePath;
- fPackageRootPath= packageRoot;
- fJavadocLocation= javadocLocation;
- }
-
- /**
- * Returns the JRE library jar location.
- *
- * @return The JRE library jar location.
- */
- public IPath getSystemLibraryPath() {
- return fSystemLibrary;
- }
-
- /**
- * Returns the JRE library source zip location.
- *
- * @return The JRE library source zip location.
- */
- public IPath getSystemLibrarySourcePath() {
- return fSystemLibrarySource;
- }
-
- /**
- * Returns the path to the default package in the sources zip file
- *
- * @return The path to the default package in the sources zip file.
- */
- public IPath getPackageRootPath() {
- return fPackageRootPath;
- }
- /* (non-Javadoc)
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public boolean equals(Object obj) {
- if (obj instanceof LibraryLocation) {
- LibraryLocation lib = (LibraryLocation)obj;
- return getSystemLibraryPath().equals(lib.getSystemLibraryPath())
- && equals(getSystemLibrarySourcePath(), lib.getSystemLibrarySourcePath())
- && equals(getPackageRootPath(), lib.getPackageRootPath())
- && equalsOrNull(getJavadocLocation(), lib.getJavadocLocation());
- }
- return false;
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#hashCode()
- */
- public int hashCode() {
- return getSystemLibraryPath().hashCode();
- }
-
- /**
- * Returns whether the given paths are equal - either may be <code>null</code>.
- * @param path1 path to be compared
- * @param path2 path to be compared
- * @return whether the given paths are equal
- */
- protected boolean equals(IPath path1, IPath path2) {
- return equalsOrNull(path1, path2);
- }
-
- /**
- * Returns whether the given objects are equal - either may be <code>null</code>.
- * @param o1 object to be compared
- * @param o2 object to be compared
- * @return whether the given objects are equal or both null
- *
- */
- private boolean equalsOrNull(Object o1, Object o2) {
- if (o1 == null) {
- return o2 == null;
- }
- if (o2 == null) {
- return false;
- }
- return o1.equals(o2);
- }
-
- /**
- * Returns the jsdoc location associated with this Library location.
- *
- * @return a url pointing to the jsdoc location associated with
- * this Library location, or <code>null</code> if none
- *
- */
- public URL getJavadocLocation() {
- return fJavadocLocation;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/ListenerList.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/ListenerList.java
deleted file mode 100644
index b18e8b33..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/ListenerList.java
+++ /dev/null
@@ -1,142 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.launching;
-
-
-/**
- * Local version of org.eclipse.jface.util.ListenerList (modified)s
- *
- * 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 ListenerList {
- /**
- * The current number of listeners.
- * Maintains invariant: 0 <= fSize <= listeners.length.
- */
- private int fSize;
-
- /**
- * The list of listeners. Initially <code>null</code> but initialized
- * to an array of size capacity the first time a listener is added.
- * Maintains invariant: listeners != null if and only if fSize != 0
- */
- private Object[] fListeners= null;
-
- /**
- * The empty array singleton instance, returned by getListeners()
- * when size == 0.
- */
- private static final Object[] EmptyArray= new Object[0];
-
- /**
- * Creates a listener list with the given initial capacity.
- *
- * @param capacity the number of listeners which this list can initially accept
- * without growing its internal representation; must be at least 1
- */
- public ListenerList(int capacity) {
- if (capacity < 1) {
- throw new IllegalArgumentException();
- }
- fListeners= new Object[capacity];
- fSize= 0;
- }
-
- /**
- * Adds a listener to the list.
- * Has no effect if an identical listener is already registered.
- *
- * @param listener a listener
- */
- public synchronized void add(Object listener) {
- if (listener == null) {
- throw new IllegalArgumentException();
- }
- // check for duplicates using identity
- for (int i= 0; i < fSize; ++i) {
- if (fListeners[i] == listener) {
- return;
- }
- }
- // grow array if necessary
- if (fSize == fListeners.length) {
- Object[] temp= new Object[(fSize * 2) + 1];
- System.arraycopy(fListeners, 0, temp, 0, fSize);
- fListeners= temp;
- }
- fListeners[fSize++]= listener;
- }
-
- /**
- * Returns an array containing all the registered listeners.
- * The resulting array is unaffected by subsequent adds or removes.
- * If there are no listeners registered, the result is an empty array
- * singleton instance (no garbage is created).
- * Use this method when notifying listeners, so that any modifications
- * to the listener list during the notification will have no effect on the
- * notification itself.
- */
- public synchronized Object[] getListeners() {
- if (fSize == 0) {
- return EmptyArray;
- }
- Object[] result= new Object[fSize];
- System.arraycopy(fListeners, 0, result, 0, fSize);
- return result;
- }
-
- /**
- * Removes a listener from the list.
- * Has no effect if an identical listener was not already registered.
- *
- * @param listener a listener
- */
- public synchronized void remove(Object listener) {
- if (listener == null) {
- throw new IllegalArgumentException();
- }
-
- for (int i= 0; i < fSize; ++i) {
- if (fListeners[i] == listener) {
- if (--fSize == 0) {
- fListeners= new Object[1];
- } else {
- if (i < fSize) {
- fListeners[i]= fListeners[fSize];
- }
- fListeners[fSize]= null;
- }
- return;
- }
- }
- }
-
- /**
- * Removes all the listeners from the list.
- */
- public void removeAll() {
- fListeners= new Object[0];
- fSize= 0;
- }
-
- /**
- * Returns the number of registered listeners
- *
- * @return the number of registered listeners
- */
- public int size() {
- return fSize;
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/PropertyChangeEvent.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/PropertyChangeEvent.java
deleted file mode 100644
index cecd39d6..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/PropertyChangeEvent.java
+++ /dev/null
@@ -1,107 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.launching;
-
-
-import java.util.EventObject;
-/**
- * An event object describing a change to a named property.
- * <p>
- * JavaRuntime provides change notification for properties of VM installs
- * </p>
- * <p>
- * Clients may instantiate this class; not intended to be subclassed.
- * </p>
- *
- * 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 PropertyChangeEvent extends EventObject {
-
- /**
- * All serializable objects should have a stable serialVersionUID
- */
- private static final long serialVersionUID = 1L;
-
- /**
- * The name of the changed property.
- */
- private String propertyName;
-
- /**
- * The old value of the changed property, or <code>null</code> if
- * not known or not relevant.
- */
- private Object oldValue;
-
- /**
- * The new value of the changed property, or <code>null</code> if
- * not known or not relevant.
- */
- private Object newValue;
-
- /**
- * Creates a new property change event.
- *
- * @param source the object whose property has changed
- * @param property the property that has changed (must not be
- * <code>null</code>)
- * @param oldValue the old value of the property, or
- * <code>null</code> if none
- * @param newValue the new value of the property, or
- * <code>null</code> if none
- */
- public PropertyChangeEvent(
- Object source,
- String property,
- Object oldValue,
- Object newValue) {
-
- super(source);
- if (property == null) {
- throw new IllegalArgumentException();
- }
- this.propertyName = property;
- this.oldValue = oldValue;
- this.newValue = newValue;
- }
-
- /**
- * Returns the name of the property that changed.
- *
- * @return the name of the property that changed
- */
- public String getProperty() {
- return propertyName;
- }
-
- /**
- * Returns the new value of the property.
- *
- * @return the new value, or <code>null</code> if not known
- * or not relevant
- */
- public Object getNewValue() {
- return newValue;
- }
-
- /**
- * Returns the old value of the property.
- *
- * @return the old value, or <code>null</code> if not known
- * or not relevant
- */
- public Object getOldValue() {
- return oldValue;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/StandardVM.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/StandardVM.java
deleted file mode 100644
index b0254a36..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/StandardVM.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 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
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.launching;
-
-
-import java.io.File;
-
-/**
- *
- * 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 StandardVM extends AbstractVMInstall {
- StandardVM(IVMInstallType type, String id) {
- super(type, id);
- }
- /* (non-Javadoc)
- * @see org.eclipse.jdt.launching.IVMInstall#getVMRunner(java.lang.String)
- */
- public IVMRunner getVMRunner(String mode) {
-// if (ILaunchManager.RUN_MODE.equals(mode)) {
-// return new StandardVMRunner(this);
-// } else if (ILaunchManager.DEBUG_MODE.equals(mode)) {
-// return new StandardVMDebugger(this);
-// }
-// return null;
- //TODO: implement
- throw new org.eclipse.wst.jsdt.core.UnimplementedException();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jdt.launching.IVMInstall#getJavaVersion()
- */
- public String getJavaVersion() {
- StandardVMType installType = (StandardVMType) getVMInstallType();
- File installLocation = getInstallLocation();
- if (installLocation != null) {
- File executable = StandardVMType.findJavaExecutable(installLocation);
- if (executable != null) {
- String vmVersion = installType.getVMVersion(installLocation, executable);
- // strip off extra info
- StringBuffer version = new StringBuffer();
- for (int i = 0; i < vmVersion.length(); i++) {
- char ch = vmVersion.charAt(i);
- if (Character.isDigit(ch) || ch == '.') {
- version.append(ch);
- } else {
- break;
- }
- }
- if (version.length() > 0) {
- return version.toString();
- }
- }
- }
- return null;
- }
-}
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
deleted file mode 100644
index 4eb12f6c..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/StandardVMType.java
+++ /dev/null
@@ -1,633 +0,0 @@
-/*******************************************************************************
- * 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.launching;
-
-
-import java.io.File;
-import java.io.IOException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * A VM install type for VMs the conform to the standard
- * JDK installion layout.
- *
- * 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 StandardVMType extends AbstractVMInstallType {
-
- public static final String ID_STANDARD_VM_TYPE = "org.eclipse.wst.jsdt.internal.debug.ui.launcher.StandardVMType"; //$NON-NLS-1$
- /**
- * The root path for the attached src
- */
- private String fDefaultRootPath;
-
- /**
- * Map of the install path for which we were unable to generate
- * the library info during this session.
- */
-// private static Map fgFailedInstallPath= new HashMap();
-
- /**
- * Convenience handle to the system-specific file separator character
- */
- private static final char fgSeparator = File.separatorChar;
-
- /**
- * The list of locations in which to look for the javascript executable in candidate
- * VM install locations, relative to the VM install location.
- */
- private static final String[] fgCandidateJavaFiles = {"javaw", "javaw.exe", "java", "java.exe", "j9w", "j9w.exe", "j9", "j9.exe"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
- private static final String[] fgCandidateJavaLocations = {"bin" + fgSeparator, "jre" + fgSeparator + "bin" + fgSeparator}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
- /**
- * Starting in the specified VM install location, attempt to find the 'java' executable
- * file. If found, return the corresponding <code>File</code> object, otherwise return
- * <code>null</code>.
- */
- public static File findJavaExecutable(File vmInstallLocation) {
- // Try each candidate in order. The first one found wins. Thus, the order
- // of fgCandidateJavaLocations and fgCandidateJavaFiles is significant.
- for (int i = 0; i < fgCandidateJavaFiles.length; i++) {
- for (int j = 0; j < fgCandidateJavaLocations.length; j++) {
- File javaFile = new File(vmInstallLocation, fgCandidateJavaLocations[j] + fgCandidateJavaFiles[i]);
- if (javaFile.isFile()) {
- return javaFile;
- }
- }
- }
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jdt.launching.IVMInstallType#getName()
- */
- public String getName() {
- return LaunchingMessages.StandardVMType_Standard_VM_3;
- }
-
-
- protected IVMInstall doCreateVMInstall(String id) {
- return new StandardVM(this, id);
- }
-
-// /**
-// * Return library information corresponding to the specified install
-// * location. If the info does not exist, create it using the given Java
-// * executable.
-// */
-// protected synchronized LibraryInfo getLibraryInfo(File javaHome, File javaExecutable) {
-//
-// // See if we already know the info for the requested VM. If not, generate it.
-// String installPath = javaHome.getAbsolutePath();
-// LibraryInfo info = LaunchingPlugin.getLibraryInfo(installPath);
-// if (info == null) {
-// info= (LibraryInfo)fgFailedInstallPath.get(installPath);
-// if (info == null) {
-// info = generateLibraryInfo(javaHome, javaExecutable);
-// if (info == null) {
-// info = getDefaultLibraryInfo(javaHome);
-// fgFailedInstallPath.put(installPath, info);
-// } else {
-// // only persist if we were able to generate info - see bug 70011
-// LaunchingPlugin.setLibraryInfo(installPath, info);
-// }
-// }
-// }
-// return info;
-// }
-//
-// /**
-// * Return <code>true</code> if the appropriate system libraries can be found for the
-// * specified javascript executable, <code>false</code> otherwise.
-// */
-// protected boolean canDetectDefaultSystemLibraries(File javaHome, File javaExecutable) {
-// LibraryLocation[] locations = getDefaultLibraryLocations(javaHome);
-// String version = getVMVersion(javaHome, javaExecutable);
-// return locations.length > 0 && !version.startsWith("1.1"); //$NON-NLS-1$
-// }
-
- /**
- * Returns the version of the VM at the given location, with the given
- * executable.
- *
- * @param javaHome
- * @param javaExecutable
- * @return String
- */
- protected String getVMVersion(File javaHome, File javaExecutable) {
-// LibraryInfo info = getLibraryInfo(javaHome, javaExecutable);
-// return info.getVersion();
- //TODO: implement
- throw new org.eclipse.wst.jsdt.core.UnimplementedException();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jdt.launching.IVMInstallType#detectInstallLocation()
- */
- public File detectInstallLocation() {
-// // do not detect on the Mac OS
-// if (Platform.getOS().equals(Constants.OS_MACOSX)) {
-// return null;
-// }
-//
-// // Retrieve the 'java.home' system property. If that directory doesn't exist,
-// // return null.
-// File javaHome;
-// try {
-// javaHome= new File (System.getProperty("java.home")).getCanonicalFile(); //$NON-NLS-1$
-// } catch (IOException e) {
-// LaunchingPlugin.log(e);
-// return null;
-// }
-// if (!javaHome.exists()) {
-// return null;
-// }
-//
-// // Find the 'java' executable file under the javascript home directory. If it can't be
-// // found, return null.
-// File javaExecutable = findJavaExecutable(javaHome);
-// if (javaExecutable == null) {
-// return null;
-// }
-//
-// // If the reported javascript home directory terminates with 'jre', first see if
-// // the parent directory contains the required libraries
-// boolean foundLibraries = false;
-// if (javaHome.getName().equalsIgnoreCase("jre")) { //$NON-NLS-1$
-// File parent= new File(javaHome.getParent());
-// if (canDetectDefaultSystemLibraries(parent, javaExecutable)) {
-// javaHome = parent;
-// foundLibraries = true;
-// }
-// }
-//
-// // If we haven't already found the libraries, look in the reported javascript home dir
-// if (!foundLibraries) {
-// if (!canDetectDefaultSystemLibraries(javaHome, javaExecutable)) {
-// return null;
-// }
-// }
-//
-// return javaHome;
- //TODO: implement
- throw new org.eclipse.wst.jsdt.core.UnimplementedException();
- }
-
- /**
- * Return an <code>IPath</code> corresponding to the single library file containing the
- * standard JavaScript classes for most VMs version 1.2 and above.
- */
- protected IPath getDefaultSystemLibrary(File javaHome) {
- IPath jreLibPath= new Path(javaHome.getPath()).append("lib").append("rt.jar"); //$NON-NLS-2$ //$NON-NLS-1$
- if (jreLibPath.toFile().isFile()) {
- return jreLibPath;
- }
- return new Path(javaHome.getPath()).append("jre").append("lib").append("rt.jar"); //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$
- }
-
- /**
- * Returns a path to the source attachment for the given libaray, or
- * an empty path if none.
- *
- * @param libLocation
- * @return a path to the source attachment for the given library, or
- * an empty path if none
- */
- protected IPath getDefaultSystemLibrarySource(File libLocation) {
- File parent= libLocation.getParentFile();
- while (parent != null) {
- File parentsrc= new File(parent, "src.jar"); //$NON-NLS-1$
- if (parentsrc.isFile()) {
- setDefaultRootPath("src");//$NON-NLS-1$
- return new Path(parentsrc.getPath());
- }
- parentsrc= new File(parent, "src.zip"); //$NON-NLS-1$
- if (parentsrc.isFile()) {
- setDefaultRootPath(""); //$NON-NLS-1$
- return new Path(parentsrc.getPath());
- }
- parent = parent.getParentFile();
- }
- // if we didn't find any of the normal source files, look for J9 source
- IPath result = checkForJ9LibrarySource(libLocation);
- if (result != null)
- return result;
- setDefaultRootPath(""); //$NON-NLS-1$
- return Path.EMPTY;
- }
-
- // J9 has a known/fixed structure for its libs and source locations. Here just
- // look for the source associated with each lib.
- private IPath checkForJ9LibrarySource(File libLocation) {
- File parent= libLocation.getParentFile();
- String name = libLocation.getName();
- if (name.equalsIgnoreCase("classes.zip")) { //$NON-NLS-1$
- File source = new File(parent, "source/source.zip"); //$NON-NLS-1$
- return source.isFile() ? new Path(source.getPath()) : Path.EMPTY;
- }
- if (name.equalsIgnoreCase("locale.zip")) { //$NON-NLS-1$
- File source = new File(parent, "source/locale-src.zip"); //$NON-NLS-1$
- return source.isFile() ? new Path(source.getPath()) : Path.EMPTY;
- }
- if (name.equalsIgnoreCase("charconv.zip")) { //$NON-NLS-1$
- File source = new File(parent, "charconv-src.zip"); //$NON-NLS-1$
- return source.isFile() ? new Path(source.getPath()) : Path.EMPTY;
- }
- return null;
- }
-
- protected IPath getDefaultPackageRootPath() {
- return new Path(getDefaultRootPath());
- }
-
- /**
- * NOTE: We do not add libraries from the "endorsed" directory explicitly, as
- * the bootpath contains these entries already (if they exist).
- *
- * @see org.eclipse.jdt.launching.IVMInstallType#getDefaultLibraryLocations(File)
- */
- public LibraryLocation[] getDefaultLibraryLocations(File installLocation) {
-
-
- File libFile = new File(installLocation,"system.js"); //$NON-NLS-1$
- Path libPath = new Path(libFile.getAbsolutePath());
- LibraryLocation location = new LibraryLocation(libPath,null,null);
- return new LibraryLocation[]{location};
-
-
-// // Determine the javascript executable that corresponds to the specified install location
-// // and use this to generate library info. If no javascript executable was found,
-// // the 'standard' libraries will be returned.
-// File javaExecutable = findJavaExecutable(installLocation);
-// LibraryInfo libInfo;
-// if (javaExecutable == null) {
-// libInfo = getDefaultLibraryInfo(installLocation);
-// } else {
-// libInfo = getLibraryInfo(installLocation, javaExecutable);
-// }
-//
-// String[] bootpath = libInfo.getBootpath();
-//
-// List endorsed = gatherAllLibraries(libInfo.getEndorsedDirs());
-// List extensions = gatherAllLibraries(libInfo.getExtensionDirs());
-// List allLibs = new ArrayList(endorsed.size() + bootpath.length + extensions.size());
-//
-// // Add all endorsed libraries - they are first, as they replace
-// // classes in the standard libraries/bootpath
-// appendLibraries(endorsed, allLibs);
-//
-// // next is the bootpath libraries
-// List boot = new ArrayList(bootpath.length);
-// URL url = getDefaultJavadocLocation(installLocation);
-// for (int i = 0; i < bootpath.length; i++) {
-// IPath path = new Path(bootpath[i]);
-// File lib = path.toFile();
-// if (lib.exists() && lib.isFile()) {
-// LibraryLocation libraryLocation = new LibraryLocation(path,
-// getDefaultSystemLibrarySource(lib),
-// getDefaultPackageRootPath(),
-// url);
-// boot.add(libraryLocation);
-// }
-// }
-// appendLibraries(boot, allLibs);
-//
-// // Add all extension libraries
-// appendLibraries(extensions, allLibs);
-//
-// return (LibraryLocation[])allLibs.toArray(new LibraryLocation[allLibs.size()]);
- }
-
- /**
- * Appends the non-duplicate libraries in libraryLocations to the list
- * of allLibs.
- *
- * @param libraryLocations libraries to append
- * @param allLibs list to append to, omitting duplicates
- */
-// private void appendLibraries(List libraryLocations, List allLibs) {
-// Iterator iter = libraryLocations.iterator();
-// while (iter.hasNext()) {
-// LibraryLocation lib = (LibraryLocation)iter.next();
-// // check for dups, in case bootpath contains an ext dir entry (see bug 50201)
-// if (!isDuplicateLibrary(allLibs, lib)) {
-// allLibs.add(lib);
-// }
-// }
-// }
-
- /**
- * Returns whether the given library is already contained in the given list.
- * Rather than checking the library for equality (which considers source attachments),
- * we check the actual OS path to the library for equality.
- *
- * @param libs list of library locations
- * @param dup possible dup
- * @return whether dup is contained in list of libraries
- */
-// private boolean isDuplicateLibrary(List libs, LibraryLocation dup) {
-// String osPath = dup.getSystemLibraryPath().toOSString();
-// for (int i = 0; i < libs.size(); i++) {
-// LibraryLocation location = (LibraryLocation) libs.get(i);
-// if (location.getSystemLibraryPath().toOSString().equalsIgnoreCase(osPath)) {
-// return true;
-// }
-// }
-// return false;
-// }
-
-// /**
-// * Returns default library info for the given install location.
-// *
-// * @param installLocation
-// * @return LibraryInfo
-// */
-// protected LibraryInfo getDefaultLibraryInfo(File installLocation) {
-// IPath rtjar = getDefaultSystemLibrary(installLocation);
-// File extDir = getDefaultExtensionDirectory(installLocation);
-// File endDir = getDefaultEndorsedDirectory(installLocation);
-// String[] dirs = null;
-// if (extDir == null) {
-// dirs = new String[0];
-// } else {
-// dirs = new String[] {extDir.getAbsolutePath()};
-// }
-// String[] endDirs = null;
-// if (endDir == null) {
-// endDirs = new String[0];
-// } else {
-// endDirs = new String[] {endDir.getAbsolutePath()};
-// }
-// return new LibraryInfo("???", new String[] {rtjar.toOSString()}, dirs, endDirs); //$NON-NLS-1$
-// }
-
- /**
- * Returns a list of all zips and jars contained in the given directories.
- *
- * @param dirPaths a list of absolute paths of directories to search
- * @return List of all zips and jars
- */
- protected List gatherAllLibraries(String[] dirPaths) {
- List libraries = new ArrayList();
- for (int i = 0; i < dirPaths.length; i++) {
- File extDir = new File(dirPaths[i]);
- if (extDir.exists() && extDir.isDirectory()) {
- String[] names = extDir.list();
- for (int j = 0; j < names.length; j++) {
- String name = names[j];
- File jar = new File(extDir, name);
- if (jar.isFile()) {
- int length = name.length();
- if (length > 4) {
- String suffix = name.substring(length - 4);
- if (suffix.equalsIgnoreCase(".zip") || suffix.equalsIgnoreCase(".jar")) { //$NON-NLS-1$ //$NON-NLS-2$
- try {
- IPath libPath = new Path(jar.getCanonicalPath());
- LibraryLocation library = new LibraryLocation(libPath, Path.EMPTY, Path.EMPTY, null);
- libraries.add(library);
- } catch (IOException e) {
- Util.log(e, ""); //$NON-NLS-1$
- }
- }
- }
- }
- }
- }
- }
- return libraries;
- }
-
- /**
- * Returns the default location of the extension directory, based on the given
- * install location. The resulting file may not exist, or be <code>null</code>
- * if an extension directory is not supported.
- *
- * @param installLocation
- * @return default extension directory or <code>null</code>
- */
- protected File getDefaultExtensionDirectory(File installLocation) {
- File jre = null;
- if (installLocation.getName().equalsIgnoreCase("jre")) { //$NON-NLS-1$
- jre = installLocation;
- } else {
- jre = new File(installLocation, "jre"); //$NON-NLS-1$
- }
- File lib = new File(jre, "lib"); //$NON-NLS-1$
- File ext = new File(lib, "ext"); //$NON-NLS-1$
- return ext;
- }
-
- /**
- * Returns the default location of the endorsed directory, based on the
- * given install location. The resulting file may not exist, or be
- * <code>null</code> if an endorsed directory is not supported.
- *
- * @param installLocation
- * @return default endorsed directory or <code>null</code>
- */
- protected File getDefaultEndorsedDirectory(File installLocation) {
- File lib = new File(installLocation, "lib"); //$NON-NLS-1$
- File ext = new File(lib, "endorsed"); //$NON-NLS-1$
- return ext;
- }
-
- protected String getDefaultRootPath() {
- return fDefaultRootPath;
- }
-
- protected void setDefaultRootPath(String defaultRootPath) {
- fDefaultRootPath = defaultRootPath;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jdt.launching.IVMInstallType#validateInstallLocation(java.io.File)
- */
- public IStatus validateInstallLocation(File javaHome) {
-// IStatus status = null;
-// if (Platform.getOS().equals(Constants.OS_MACOSX)) {
-// status = new Status(IStatus.ERROR, LaunchingPlugin.getUniqueIdentifier(), 0, LaunchingMessages.StandardVMType_Standard_VM_not_supported_on_MacOS__1, null);
-// } else {
-// File javaExecutable = findJavaExecutable(javaHome);
-// if (javaExecutable == null) {
-// status = new Status(IStatus.ERROR, LaunchingPlugin.getUniqueIdentifier(), 0, LaunchingMessages.StandardVMType_Not_a_JDK_Root__Java_executable_was_not_found_1, null); //
-// } else {
-// if (canDetectDefaultSystemLibraries(javaHome, javaExecutable)) {
-// status = new Status(IStatus.OK, LaunchingPlugin.getUniqueIdentifier(), 0, LaunchingMessages.StandardVMType_ok_2, null);
-// } else {
-// status = new Status(IStatus.ERROR, LaunchingPlugin.getUniqueIdentifier(), 0, LaunchingMessages.StandardVMType_Not_a_JDK_root__System_library_was_not_found__1, null);
-// }
-// }
-// }
-// return status;
- //TODO: implement
- throw new org.eclipse.wst.jsdt.core.UnimplementedException();
- }
-
-// /**
-// * Generates library information for the given javascript executable. A main
-// * program is run (<code>org.eclipse.jdt.internal.launching.support.
-// * LibraryDetector</code>), that dumps the system properties for bootpath
-// * and extension directories. This output is then parsed and cached for
-// * future reference.
-// *
-// * @return library info or <code>null</code> if none
-// */
-// protected LibraryInfo generateLibraryInfo(File javaHome, File javaExecutable) {
-// LibraryInfo info = null;
-//
-// // if this is 1.1.X, the properties will not exist
-// IPath classesZip = new Path(javaHome.getAbsolutePath()).append("lib").append("classes.zip"); //$NON-NLS-1$ //$NON-NLS-2$
-// if (classesZip.toFile().exists()) {
-// return new LibraryInfo("1.1.x", new String[] {classesZip.toOSString()}, new String[0], new String[0]); //$NON-NLS-1$
-// }
-// //locate the launching support jar - it contains the main program to run
-// File file = LaunchingPlugin.getFileInPlugin(new Path("lib/launchingsupport.jar")); //$NON-NLS-1$
-// if (file.exists()) {
-// String javaExecutablePath = javaExecutable.getAbsolutePath();
-// String[] cmdLine = new String[] {javaExecutablePath, "-includepath", file.getAbsolutePath(), "org.eclipse.jdt.internal.launching.support.LibraryDetector"}; //$NON-NLS-1$ //$NON-NLS-2$
-// Process p = null;
-// try {
-// p = Runtime.getRuntime().exec(cmdLine);
-// IProcess process = DebugPlugin.newProcess(new Launch(null, ILaunchManager.RUN_MODE, null), p, "Library Detection"); //$NON-NLS-1$
-// for (int i= 0; i < 200; i++) {
-// // Wait no more than 10 seconds (200 * 50 mils)
-// if (process.isTerminated()) {
-// break;
-// }
-// try {
-// Thread.sleep(50);
-// } catch (InterruptedException e) {
-// }
-// }
-// info = parseLibraryInfo(process);
-// } catch (IOException ioe) {
-// LaunchingPlugin.log(ioe);
-// } finally {
-// if (p != null) {
-// p.destroy();
-// }
-// }
-// }
-// if (info == null) {
-// // log error that we were unable to generate library info - see bug 70011
-// LaunchingPlugin.log(MessageFormat.format("Failed to retrieve default libraries for {0}", new String[]{javaHome.getAbsolutePath()})); //$NON-NLS-1$
-// }
-// return info;
-// }
-//
-// /**
-// * Parses the output from 'LibraryDetector'.
-// */
-// protected LibraryInfo parseLibraryInfo(IProcess process) {
-// IStreamsProxy streamsProxy = process.getStreamsProxy();
-// String text = null;
-// if (streamsProxy != null) {
-// text = streamsProxy.getOutputStreamMonitor().getContents();
-// }
-// if (text != null && text.length() > 0) {
-// int index = text.indexOf("|"); //$NON-NLS-1$
-// if (index > 0) {
-// String version = text.substring(0, index);
-// text = text.substring(index + 1);
-// index = text.indexOf("|"); //$NON-NLS-1$
-// if (index > 0) {
-// String bootPaths = text.substring(0, index);
-// String[] bootPath = parsePaths(bootPaths);
-//
-// text = text.substring(index + 1);
-// index = text.indexOf("|"); //$NON-NLS-1$
-//
-// if (index > 0) {
-// String extDirPaths = text.substring(0, index);
-// String endorsedDirsPath = text.substring(index + 1);
-// String[] extDirs = parsePaths(extDirPaths);
-// String[] endDirs = parsePaths(endorsedDirsPath);
-// return new LibraryInfo(version, bootPath, extDirs, endDirs);
-// }
-// }
-// }
-// }
-// return null;
-// }
-
- protected String[] parsePaths(String paths) {
- List list = new ArrayList();
- int pos = 0;
- int index = paths.indexOf(File.pathSeparatorChar, pos);
- while (index > 0) {
- String path = paths.substring(pos, index);
- list.add(path);
- pos = index + 1;
- index = paths.indexOf(File.pathSeparatorChar, pos);
- }
- String path = paths.substring(pos);
- if (!path.equals("null")) { //$NON-NLS-1$
- list.add(path);
- }
- return (String[])list.toArray(new String[list.size()]);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jdt.launching.IVMInstallType#disposeVMInstall(java.lang.String)
- */
- public void disposeVMInstall(String id) {
- IVMInstall vm = findVMInstall(id);
- if (vm != null) {
-// String path = vm.getInstallLocation().getAbsolutePath();
-// LaunchingPlugin.setLibraryInfo(path, null);
-// fgFailedInstallPath.remove(path);
- //TODO: implement
- throw new org.eclipse.wst.jsdt.core.UnimplementedException();
- }
- super.disposeVMInstall(id);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jdt.launching.AbstractVMInstallType#getDefaultJavadocLocation(java.io.File)
- */
- public URL getDefaultJavadocLocation(File installLocation) {
-// File javaExecutable = findJavaExecutable(installLocation);
-// if (javaExecutable != null) {
-// LibraryInfo libInfo = getLibraryInfo(installLocation, javaExecutable);
-// if (libInfo != null) {
-// String version = libInfo.getVersion();
-// if (version != null) {
-// try {
-// if (version.startsWith("1.5")) { //$NON-NLS-1$
-// return new URL("http://java.sun.com/j2se/1.5.0/docs/api/"); //$NON-NLS-1$
-// } else if (version.startsWith("1.4")) { //$NON-NLS-1$
-// return new URL("http://java.sun.com/j2se/1.4.2/docs/api/"); //$NON-NLS-1$
-// } else if (version.startsWith("1.3")) { //$NON-NLS-1$
-// return new URL("http://java.sun.com/j2se/1.3/docs/api/"); //$NON-NLS-1$
-// } else if (version.startsWith("1.2")) { //$NON-NLS-1$
-// return new URL("http://java.sun.com/products/jdk/1.2/docs/api"); //$NON-NLS-1$
-// }
-// } catch (MalformedURLException e) {
-// }
-// }
-// }
-// }
-// return null;
- //TODO: implement
- throw new org.eclipse.wst.jsdt.core.UnimplementedException();
- }
-
-}
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
deleted file mode 100644
index 413d5c76..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/VMRunnerConfiguration.java
+++ /dev/null
@@ -1,269 +0,0 @@
-/*******************************************************************************
- * 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.launching;
-
-
-import java.util.Map;
-
-/**
- * Holder for various arguments passed to a VM runner.
- * Mandatory parameters are passed in the constructor; optional arguments, via setters.
- * <p>
- * Clients may instantiate this class; it is not intended to be subclassed.
- * </p>
- *
- * 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 VMRunnerConfiguration {
- private String fClassToLaunch;
- private String[] fVMArgs;
- private String[] fProgramArgs;
- private String[] fEnvironment;
- private String[] fClassPath;
- private String[] fBootClassPath;
- private String fWorkingDirectory;
- private Map fVMSpecificAttributesMap;
- private boolean fResume = true;
-
- private static final String[] fgEmpty= new String[0];
-
- /**
- * Creates a new configuration for launching a VM to run the given main class
- * using the given class path.
- *
- * @param classToLaunch The fully qualified name of the class to launch. May not be null.
- * @param classPath The includepath. May not be null.
- */
- public VMRunnerConfiguration(String classToLaunch, String[] classPath) {
- if (classToLaunch == null) {
- throw new IllegalArgumentException(LaunchingMessages.vmRunnerConfig_assert_classNotNull);
- }
- if (classPath == null) {
- throw new IllegalArgumentException(LaunchingMessages.vmRunnerConfig_assert_classPathNotNull);
- }
- fClassToLaunch= classToLaunch;
- fClassPath= classPath;
- }
-
- /**
- * Sets the <code>Map</code> that contains String name/value pairs that represent
- * VM-specific attributes.
- *
- * @param map the <code>Map</code> of VM-specific attributes.
- *
- */
- public void setVMSpecificAttributesMap(Map map) {
- fVMSpecificAttributesMap = map;
- }
-
- /**
- * Sets the custom VM arguments. These arguments will be appended to the list of
- * VM arguments that a VM runner uses when launching a VM. Typically, these VM arguments
- * are set by the user.
- * These arguments will not be interpreted by a VM runner, the client is responsible for
- * passing arguments compatible with a particular VM runner.
- *
- * @param args the list of VM arguments
- */
- public void setVMArguments(String[] args) {
- if (args == null) {
- throw new IllegalArgumentException(LaunchingMessages.vmRunnerConfig_assert_vmArgsNotNull);
- }
- fVMArgs= args;
- }
-
- /**
- * Sets the custom program arguments. These arguments will be appended to the list of
- * program arguments that a VM runner uses when launching a VM (in general: none).
- * Typically, these VM arguments are set by the user.
- * These arguments will not be interpreted by a VM runner, the client is responsible for
- * passing arguments compatible with a particular VM runner.
- *
- * @param args the list of arguments
- */
- public void setProgramArguments(String[] args) {
- if (args == null) {
- throw new IllegalArgumentException(LaunchingMessages.vmRunnerConfig_assert_programArgsNotNull);
- }
- fProgramArgs= args;
- }
-
- /**
- * Sets the environment for the JavaScript program. The JavaScript VM will be
- * launched in the given environment.
- *
- * @param environment the environment for the JavaScript program specified as an array
- * of strings, each element specifying an environment variable setting in the
- * format <i>name</i>=<i>value</i>
- *
- */
- public void setEnvironment(String[] environment) {
- fEnvironment= environment;
- }
-
- /**
- * Sets the boot includepath. Note that the boot includepath will be passed to the
- * VM "as is". This means it has to be complete. Interpretation of the boot class path
- * is up to the VM runner this object is passed to.
- * <p>
- * In release 3.0, support has been added for appending and prepending the
- * boot includepath. Generally an <code>IVMRunner</code> should use the prepend,
- * main, and append boot includepaths provided. However, in the case that an
- * <code>IVMRunner</code> does not support these options, a complete bootpath
- * should also be specified.
- * </p>
- * @param bootClassPath The boot includepath. An empty array indicates an empty
- * bootpath and <code>null</code> indicates a default bootpath.
- */
- public void setBootClassPath(String[] bootClassPath) {
- fBootClassPath= bootClassPath;
- }
-
- /**
- * Returns the <code>Map</code> that contains String name/value pairs that represent
- * VM-specific attributes.
- *
- * @return The <code>Map</code> of VM-specific attributes or <code>null</code>.
- *
- */
- public Map getVMSpecificAttributesMap() {
- return fVMSpecificAttributesMap;
- }
-
- /**
- * Returns the name of the class to launch.
- *
- * @return The fully qualified name of the class to launch. Will not be <code>null</code>.
- */
- public String getClassToLaunch() {
- return fClassToLaunch;
- }
-
- /**
- * Returns the includepath.
- *
- * @return the includepath
- */
- public String[] getClassPath() {
- return fClassPath;
- }
-
- /**
- * Returns the boot includepath. An empty array indicates an empty
- * bootpath and <code>null</code> indicates a default bootpath.
- * <p>
- * In 3.0, support has been added for prepending and appending to the
- * boot includepath. The new attributes are stored in the VM specific
- * attributes map using the following keys defined in
- * <code>IJavaLaunchConfigurationConstants</code>:
- * <ul>
- * <li>ATTR_BOOTPATH_PREPEND</li>
- * <li>ATTR_BOOTPATH_APPEND</li>
- * <li>ATTR_BOOTPATH</li>
- * </ul>
- * </p>
- * @return The boot includepath. An empty array indicates an empty
- * bootpath and <code>null</code> indicates a default bootpath.
- * @see #setBootClassPath(String[])
- * @see IJavaLaunchConfigurationConstants
- */
- public String[] getBootClassPath() {
- return fBootClassPath;
- }
-
- /**
- * Returns the arguments to the VM itself.
- *
- * @return The VM arguments. Default is an empty array. Will not be <code>null</code>.
- * @see #setVMArguments(String[])
- */
- public String[] getVMArguments() {
- if (fVMArgs == null) {
- return fgEmpty;
- }
- return fVMArgs;
- }
-
- /**
- * Returns the arguments to the JavaScript program.
- *
- * @return The JavaScript program arguments. Default is an empty array. Will not be <code>null</code>.
- * @see #setProgramArguments(String[])
- */
- public String[] getProgramArguments() {
- if (fProgramArgs == null) {
- return fgEmpty;
- }
- return fProgramArgs;
- }
-
- /**
- * Returns the environment for the JavaScript program or <code>null</code>
- *
- * @return The JavaScript program environment. Default is <code>null</code>
- *
- */
- public String[] getEnvironment() {
- return fEnvironment;
- }
-
- /**
- * Sets the working directory for a launched VM.
- *
- * @param path the absolute path to the working directory
- * to be used by a launched VM, or <code>null</code> if
- * the default working directory is to be inherited from the
- * current process
- *
- */
- public void setWorkingDirectory(String path) {
- fWorkingDirectory = path;
- }
-
- /**
- * Returns the working directory of a launched VM.
- *
- * @return the absolute path to the working directory
- * of a launched VM, or <code>null</code> if the working
- * directory is inherited from the current process
- *
- */
- public String getWorkingDirectory() {
- return fWorkingDirectory;
- }
-
- /**
- * Sets whether the VM is resumed on startup when launched in
- * debug mode. Has no effect when not in debug mode.
- *
- * @param resume whether to resume the VM on startup
- *
- */
- public void setResumeOnStartup(boolean resume) {
- fResume = resume;
- }
-
- /**
- * Returns whether the VM is resumed on startup when launched
- * in debug mode. Has no effect when no in debug mode. Default
- * value is <code>true</code> for backwards compatibility.
- *
- * @return whether to resume the VM on startup
- *
- */
- public boolean isResumeOnStartup() {
- return fResume;
- }
-}
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
deleted file mode 100644
index efacf839..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/VMStandin.java
+++ /dev/null
@@ -1,146 +0,0 @@
-/*******************************************************************************
- * 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.launching;
-
-
-
-/**
- * An implementation of IVMInstall that is used for manipulating VMs without necessarily
- * committing changes.
- * <p>
- * Instances of this class act like wrappers. All other instances of IVMInstall represent
- * 'real live' VMs that may be used for building or launching. Instances of this class
- * behave like 'temporary' VMs that are not visible and not available for building or launching.
- * </p>
- * <p>
- * Instances of this class may be constructed as a preliminary step to creating a 'live' VM
- * or as a preliminary step to making changes to a 'real' VM.
- * </p>
- * When <code>convertToRealVM</code> is called, a corresponding 'real' VM is created
- * if one did not previously exist, or the corresponding 'real' VM is updated.
- * </p>
- * <p>
- * Clients may instantiate this class; it is not intended to be subclassed.
- * </p>
- *
- * 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 VMStandin extends AbstractVMInstall {
-
- /**
- * <code>java.version</code> system property, or <code>null</code>
- *
- */
- private String fJavaVersion = null;
-
- /*
- * @see org.eclipse.wst.jsdt.launching.AbstractVMInstall#AbstractVMInstall(org.eclipse.wst.jsdt.launching.IVMInstallType, java.lang.String)
- */
- public VMStandin(IVMInstallType type, String id) {
- super(type, id);
- setNotify(false);
- }
-
- /**
- * Constructs a copy of the specified VM with the given identifier.
- *
- * @param sourceVM
- * @param id
- *
- */
- public VMStandin(IVMInstall sourceVM, String id) {
- super(sourceVM.getVMInstallType(), id);
- setNotify(false);
- init(sourceVM);
- }
-
- /**
- * Construct a <code>VMStandin</code> instance based on the specified <code>IVMInstall</code>.
- * Changes to this standin will not be reflected in the 'real' VM until <code>convertToRealVM</code>
- * is called.
- *
- * @param realVM the 'real' VM from which to construct this standin VM
- */
- public VMStandin(IVMInstall realVM) {
- this (realVM.getVMInstallType(), realVM.getId());
- init(realVM);
- }
-
- /**
- * Initializes the settings of this standin based on the settings in the given
- * VM install.
- *
- * @param realVM VM to copy settings from
- */
- private void init(IVMInstall realVM) {
- setName(realVM.getName());
- setInstallLocation(realVM.getInstallLocation());
- setLibraryLocations(realVM.getLibraryLocations());
- setJavadocLocation(realVM.getJavadocLocation());
- if (realVM instanceof IVMInstall2) {
- IVMInstall2 vm2 = (IVMInstall2) realVM;
- setVMArgs(vm2.getVMArgs());
- fJavaVersion = vm2.getJavaVersion();
- } else {
- setVMArguments(realVM.getVMArguments());
- fJavaVersion = null;
- }
- }
-
- /**
- * If no corresponding 'real' VM exists, create one and populate it from this standin instance.
- * If a corresponding VM exists, update its attributes from this standin instance.
- *
- * @return IVMInstall the 'real' corresponding to this standin VM
- */
- public IVMInstall convertToRealVM() {
- IVMInstallType vmType= getVMInstallType();
- IVMInstall realVM= vmType.findVMInstall(getId());
- boolean notify = true;
-
- if (realVM == null) {
- realVM= vmType.createVMInstall(getId());
- notify = false;
- }
- // do not notify of property changes on new VMs
- if (realVM instanceof AbstractVMInstall) {
- ((AbstractVMInstall)realVM).setNotify(notify);
- }
- realVM.setName(getName());
- realVM.setInstallLocation(getInstallLocation());
- realVM.setLibraryLocations(getLibraryLocations());
- realVM.setJavadocLocation(getJavadocLocation());
- if (realVM instanceof IVMInstall2) {
- IVMInstall2 vm2 = (IVMInstall2) realVM;
- vm2.setVMArgs(getVMArgs());
- } else {
- realVM.setVMArguments(getVMArguments());
- }
-
- if (realVM instanceof AbstractVMInstall) {
- ((AbstractVMInstall)realVM).setNotify(true);
- }
- if (!notify) {
- JavaRuntime.fireVMAdded(realVM);
- }
- return realVM;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.launching.IVMInstall#getJavaVersion()
- */
- public String getJavaVersion() {
- return fJavaVersion;
- }
-}
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
deleted file mode 100644
index 378c1e76..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/libraries/BasicBrowserLibraryJsGlobalScopeContainerInitializer.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/*******************************************************************************
- * 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.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;
-import org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer;
-import org.eclipse.wst.jsdt.core.compiler.libraries.LibraryLocation;
-import org.eclipse.wst.jsdt.core.compiler.libraries.SystemLibraryLocation;
-import org.eclipse.wst.jsdt.core.infer.DefaultInferrenceProvider;
-
-/**
- *
- * 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 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$
-
- 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'}
- };
-
- static class BasicLibLocation extends SystemLibraryLocation {
- BasicLibLocation() {
- super();
- }
-
- public char[][] getLibraryFileNames() {
- return BasicBrowserLibraryJsGlobalScopeContainerInitializer.LIBRARY_FILE_NAME ;
- }
-
- static LibraryLocation fInstance;
-
- public static LibraryLocation getInstance(){
- if(fInstance== null){
- fInstance = new BasicLibLocation();
- }
- return fInstance;
- }
- }
-
- public LibraryLocation getLibraryLocation() {
- return BasicLibLocation.getInstance();
- }
-
- /**
- * @deprecated Use {@link #getIncludepathEntries()} instead
- */
- public IIncludePathEntry[] getClasspathEntries() {
- return getIncludepathEntries();
- }
-
- 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)
- */
- public boolean canUpdateJsGlobalScopeContainer(IPath containerPath, IJavaScriptProject project) {
- return true;
- }
-
- protected IJsGlobalScopeContainer getContainer(IPath containerPath, IJavaScriptProject project) {
- return this;
- }
-
- public String getDescription() {
- return BasicBrowserLibraryJsGlobalScopeContainerInitializer.LibraryDescription;
- }
-
- public String getDescription(IPath containerPath, IJavaScriptProject project) {
- if (containerPath == null || containerPath.isEmpty())
- return null;
-
- 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);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer#containerSuperTypes()
- */
- public String[] containerSuperTypes() {
- return new String[] {BROWSER_SUPER_TYPE_NAME};
- }
-
- public String getInferenceID() {
- return DefaultInferrenceProvider.ID;
- }
-}
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
deleted file mode 100644
index f3120fcf..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/libraries/BasicLibraryContainer.java
+++ /dev/null
@@ -1,22 +0,0 @@
-/*******************************************************************************
- * 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
deleted file mode 100644
index 05f5c09e..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/libraries/Messages.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*******************************************************************************
- * 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;
-
-import org.eclipse.osgi.util.NLS;
-
-public class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.wst.jsdt.libraries.messages"; //$NON-NLS-1$
-
- public static String BasicBrowserLibraryJsGlobalScopeContainerInitializer_CommonWebBrowser;
-
- public static String BasicBrowserLibraryJsGlobalScopeContainerInitializer_ECMA3Browser;
-
- public static String BasicBrowserLibraryJsGlobalScopeContainerInitializer_ECMA3BrowserLibrary;
-
- public static String BasicBrowserLibraryJsGlobalScopeContainerInitializer_ECMA3DOM;
-
- /**
- * @deprecated
- */
- public static String BasicBrowserLibraryJsGlobalScopeContainerInitializer_Window;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
-
- private Messages() {
- }
-}
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
deleted file mode 100644
index 764c3bad..00000000
--- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/libraries/messages.properties
+++ /dev/null
@@ -1,15 +0,0 @@
-###############################################################################
-# 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
-###############################################################################
-BasicBrowserLibraryJsGlobalScopeContainerInitializer_ECMA3Browser=ECMA 3 Browser Support
-BasicBrowserLibraryJsGlobalScopeContainerInitializer_ECMA3DOM=ECMA 3 DOM
-BasicBrowserLibraryJsGlobalScopeContainerInitializer_CommonWebBrowser=Common Web Browser
-BasicBrowserLibraryJsGlobalScopeContainerInitializer_ECMA3BrowserLibrary=ECMA 3 Browser Support Library
-BasicBrowserLibraryJsGlobalScopeContainerInitializer_Window=Window

Back to the top